diff --git a/.gitattributes b/.gitattributes index b30c558773cf51e9d3c152714fc944f089bab0ba..f3fa2bd01d02e51f1390daea371f28652855b3c1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -545,3 +545,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/post_grad.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/split_cat.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/triton.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_heuristics.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_impls.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm100.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_benchmark_request.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_benchmark_request.py new file mode 100644 index 0000000000000000000000000000000000000000..a113493a8259e0016a02dddf15d509de1a117ab1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_benchmark_request.py @@ -0,0 +1,143 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import functools +import logging +from ctypes import byref, c_int, c_size_t, c_void_p +from typing import Any, TYPE_CHECKING + +import torch +from torch._inductor import config +from torch._inductor.autotune_process import ( + BenchmarkRequest, + GPUDeviceBenchmarkMixin, + TensorMeta, +) +from torch._inductor.codecache import DLLWrapper, ROCmCodeCache + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + + +log = logging.getLogger(__name__) + + +class ROCmBenchmarkRequest(GPUDeviceBenchmarkMixin, BenchmarkRequest): + # Important: Instances of this class have to be serializable + # across process boundaries. Do not put CUDA Tensors in here! + + def __init__( + self, + kernel_name: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + extra_args: Iterable[Any], + source_code: str, + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args) + self.source_code = source_code + self.workspace_size: int = 0 + self.workspace: torch.Tensor | None = None + self.DLL: DLLWrapper | None = None + self._workspace_size_updated = False + self.hash_key: str = "" + self.source_file: str = "" + self.hash_key, self.source_file = ROCmCodeCache.write(self.source_code, "so") + + def precompile(self): + # Prepopulate code cache + # may happen in separate Threadpool + log.debug("Precompiling %s", self) + ROCmCodeCache.compile(self.source_code, "so") + if config.rocm.generate_test_runner: + ROCmCodeCache.compile(self.source_code, "exe") + log.debug("Done precompiling %s", self) + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + self.ensure_dll_loaded() + self.update_workspace_size() + args = [c_void_p(tensor.data_ptr()) for tensor in list(input_tensors) + [out]] + size_args = [c_int(arg) for arg in self.extra_args] + log.debug( + "make_run_fn: self.kernel_name=%s, self.source_file=%s, self.hash_key=%s, self.DLL=%s, args=%s, self.extra_args=%s", + self.kernel_name, + self.source_file, + self.hash_key, + self.DLL, + args, + self.extra_args, + ) + stream_ptr = c_void_p(torch.cuda.current_stream().cuda_stream) + run_method = getattr(self.DLL, self.kernel_name) + workspace_ptr = c_void_p(0) + if self.workspace_size > 0: + self.workspace = torch.zeros( + (self.workspace_size + 7) // 8, + dtype=torch.float64, + device=out.device, + ) + workspace_ptr = c_void_p(self.workspace.data_ptr()) + + # Generate partial function. + return functools.partial( + run_method, + *args, + *size_args, + None, # null workspace size ptr + workspace_ptr, # set workspace ptr, + stream_ptr, + ) + + def update_workspace_size(self) -> None: + if self._workspace_size_updated: + return + self.ensure_dll_loaded() + unique_input_count = len( + dict.fromkeys(meta.name for meta in self.input_tensor_meta) + ) + args = [c_void_p(None) for _ in range(unique_input_count + 1)] + stream_ptr = c_void_p(torch.cuda.current_stream().cuda_stream) + + run_method = getattr(self.DLL, self.kernel_name) + # Retrieve workspace_size and initialize workspace. + c_workspace_size = c_size_t() + size_args = [c_int(arg) for arg in self.extra_args] + run_method( + *args, # input ptrs and output ptrs + *size_args, + byref( + c_workspace_size + ), # set workspace size ptr to retrieve workspace size + None, # null workspace ptr + stream_ptr, + ) + torch.cuda.synchronize() # shake out any CUDA errors + self.workspace_size = c_workspace_size.value + log.debug( + "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", + self.workspace_size, + self.kernel_name, + self.source_file, + self.hash_key, + self.DLL, + args, + self.extra_args, + ) + self._workspace_size_updated = True + + def ensure_dll_loaded(self): + if self.DLL is None: + self.DLL, self.hash_key, self.source_file = ROCmCodeCache.load( + self.source_code, "so" + ) + + def cleanup_run_fn(self) -> None: + if self.DLL is not None: + self.DLL.close() + self.workspace = None + + def __str__(self) -> str: + return f"{self.kernel_name=}, {self.source_file=}, {self.hash_key=}" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_cpp_scheduling.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_cpp_scheduling.py new file mode 100644 index 0000000000000000000000000000000000000000..3698dc67be774a63412de4c017bb928780178087 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_cpp_scheduling.py @@ -0,0 +1,114 @@ +# mypy: allow-untyped-defs +import logging +from collections.abc import Sequence +from typing import cast, TypeGuard + +from ... import config +from ...codecache import code_hash, get_path +from ...scheduler import BaseSchedulerNode, BaseScheduling, SchedulerNode +from ...utils import get_fused_kernel_name, get_kernel_metadata, sympy_product +from ...virtualized import V +from ..common import IndentedBuffer +from .rocm_template_buffer import ROCmTemplateBuffer + + +log = logging.getLogger(__name__) + + +class ROCmCPPScheduling(BaseScheduling): + """ + Partial Scheduling implementation for ROCm C++ Kernels. + This class is intended to be used in combination with TritonScheduling, + and delegated to by CUDACombinedScheduling. + + It handles fusion decisions and ROCm C++ specific template code generation. + """ + + def group_fn(self, sizes): + return tuple(V.graph.sizevars.simplify(sympy_product(s)) for s in sizes) + + @staticmethod + def is_rocm_cpp_template(node: BaseSchedulerNode) -> TypeGuard[SchedulerNode]: + return isinstance(node, SchedulerNode) and isinstance( + node.node, ROCmTemplateBuffer + ) + + def can_fuse_vertical( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + return False + + def define_kernel(self, src_code: str, node_schedule) -> str: + wrapper = V.graph.wrapper_code + if src_code in wrapper.src_to_kernel: + kernel_name = wrapper.src_to_kernel[src_code] + else: + fused_name = ( + get_fused_kernel_name(node_schedule, config.triton.descriptive_names) + if config.triton.descriptive_names + else "" + ) + kernel_name = "_".join(["rocm", fused_name, wrapper.next_kernel_suffix()]) + # use the original src_code as the key + wrapper.src_to_kernel[src_code] = kernel_name + src_code = src_code.replace("KERNEL_NAME", kernel_name) + + _, _, kernel_path = get_path(code_hash(src_code), "py") + + compile_wrapper = IndentedBuffer() + compile_wrapper.writeline("async_compile.rocm(r'''") + compile_wrapper.splice(src_code, strip=True) + compile_wrapper.writeline( + f"''', 'so', aot_compile={str(V.graph.aot_mode)})" + ) + + metadata_comment = f"# kernel path: {kernel_path}" + origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper) + metadata_comment += "\n" + origins + "\n" + detailed_origins + wrapper.define_kernel( + kernel_name, compile_wrapper.getvalue(), metadata_comment + ) + + # For JIT cpp_wrapper, the kernel call site emits a bare + # `extern "C"` symbol reference; compile the .so now so the + # wrapper compile can link against it via extra_flags. + # Autotune compiled a .so for the unfused kernel name + # (e.g. rocm_), but at codegen time the kernel name + # gains a descriptive prefix (rocm_fused_mm_), so the + # exported symbol differs and we need a fresh compile. + if V.graph.cpp_wrapper and not V.graph.aot_mode: + from ...codecache import ROCmCodeCache + + so_path, _, _ = ROCmCodeCache.compile(src_code, "so") + wrapper.external_kernel_libs.add(so_path) + return kernel_name + + def codegen_template( + self, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + prologue_nodes: Sequence[BaseSchedulerNode], + ): + """ + Codegen a ROCm template, possibly with fused epilogues + """ + if not self.is_rocm_cpp_template(template_node): + raise AssertionError( + "Template node passed to ROCmScheduler.codegen_template must be a SchedulerNode that wraps a ROCmTemplateBuffer" + ) + _, (_numel, rnumel) = template_node.group + if rnumel != 1: + raise AssertionError(f"expected rnumel == 1, got {rnumel}") + ctb: ROCmTemplateBuffer = cast(ROCmTemplateBuffer, template_node.node) + kernel, render = ctb.make_kernel_render(ctb) # type: ignore[misc] + with kernel: + template_node.mark_run() + src_code = render() + + with V.set_kernel_handler(kernel): + node_schedule = [template_node] + kernel_name = self.define_kernel(src_code, node_schedule) + self.codegen_comment(node_schedule, kernel_name) + kernel.call_kernel(kernel_name, ctb) + V.graph.removed_buffers |= kernel.removed_buffers + self.free_buffers_in_scheduler() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..41fb5cdf0526db05e6d7fedbb6932fbc854a2031 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_kernel.py @@ -0,0 +1,298 @@ +# mypy: allow-untyped-defs +import logging +from collections.abc import Callable, Sequence +from typing import Any, TYPE_CHECKING + +import torch._inductor.config as config +from torch._inductor.codegen.cpp_wrapper_cpu import CppWrapperCpu +from torch._inductor.utils import do_bench_using_profiling + +from ...ir import Buffer, ChoiceCaller, IRNode, Layout, PrimitiveInfoType, TensorBox +from ...virtualized import V +from ..common import Kernel, OpOverrides, WorkspaceArg, WorkspaceZeroMode +from ..cpp_utils import CppPrinter +from .rocm_benchmark_request import ROCmBenchmarkRequest +from .rocm_template_buffer import ROCmTemplateBuffer +from .rocm_utils import DTYPE_TO_ROCM_TYPE + + +if TYPE_CHECKING: + from torch._inductor.codegen.rocm.rocm_template import ArgInfo, ROCmTemplate + +log = logging.getLogger(__name__) + +cexpr = CppPrinter().doprint + + +def _normalize_idx(index: int, total_length: int) -> int: + return index if index >= 0 else index + total_length + + +class ROCmKernel(Kernel): + """ + Baseclass for ROCm based Kernels + """ + + overrides = OpOverrides # type: ignore[assignment] + + +class ROCmTemplateKernel(ROCmKernel): + """ + Template kernels defined by ROCm in C++. + """ + + _EXTRA_CPP_ARGS = "size_t* workspace_size, uint8_t* workspace, hipStream_t stream" + + def __init__( + self, + kernel_name: str, + runtime_arg_info: list["ArgInfo"], + runtime_arg_values: list[Any], + ) -> None: + """ + Initializes a new instance of the ROCmTemplateKernel class. + + Args: + kernel_name (str): The name of the kernel. + """ + super().__init__() + self.kernel_name = kernel_name + # Mapping from arg name to IRNode. + self.named_nodes: dict[str, IRNode] = {} + self.runtime_arg_info = runtime_arg_info + self.runtime_arg_values = runtime_arg_values + + def get_signature(self): + return self.signature + + def def_kernel( + self, + inputs: list[IRNode], + outputs: list[IRNode], + size_args: list[str], + names_str: str = "", + input_reorder: list[int] | None = None, + ) -> str: + """ + Hook called from template code to generate function definition and + needed args. + + Args: + inputs: List of input IRNodes + outputs: List of output IRNodes + names_str: Comma separated list of input + output argument names. + input_reorder: The actual order of input nodes. + e.g. The template might have input argument defined as [X, W, Bias], + and the actual input passed into this template could be [Bias, X, W]. + In this case, the `input_reorder` would be [2, 0, 1]. + """ + names = [x.strip() for x in names_str.strip().split(",")] + if len(inputs) + len(outputs) != len(names): + raise RuntimeError( + f"{len(inputs) + len(outputs)=} != {len(names)=}, {inputs=}, {outputs=}, {names=}" + ) + + if input_reorder == [2, 0, 1]: + input_reorder = [4, 0, 1, 2, 3] + + if input_reorder is not None: + if len(inputs) != len(input_reorder): + raise AssertionError( + f"expected len(inputs) == len(input_reorder), " + f"got {len(inputs)} and {len(input_reorder)}" + ) + else: + input_reorder = list(range(len(inputs))) + + for idx in input_reorder: + name = names[idx] + node = inputs[idx] + if node is not None: + self.named_nodes[name] = node + self.args.input_buffers[node.get_name()] = name + + for name, node in zip(names[len(inputs) : len(inputs) + len(outputs)], outputs): + if node is not None: + self.named_nodes[name] = node + self.args.output_buffers[node.get_name()] = name + + arg_defs, *_ = self.args.cpp_argdefs(DTYPE_TO_ROCM_TYPE) + + runtime_arg_defs = [f"{arg.ty} {arg.name}" for arg in self.runtime_arg_info] + + signature = f"int {self.kernel_name}({', '.join(arg_defs + size_args + runtime_arg_defs)},{self._EXTRA_CPP_ARGS})" + self.signature = signature + return signature + + def call_kernel( + self, + name: str, + node: "ROCmTemplateBuffer", # type: ignore[name-defined] + ) -> None: + """ + Generates code to call the kernel through V.graph.wrapper_code. + used from within torch._inductor.wrapper.PythonWrapperCodegen + + name: Name of kernel function. + node: The ROCmTemplateBuffer node which contains information about the kernel, it's fused epilogue nodes + as well as all required inputs and outputs. + """ + wrapper = V.graph.wrapper_code + + arg_types: list[Any] + if V.graph.cpp_wrapper: + # Make sure we initialize these kernels since they're exported as + # C-style symbol names. + if not isinstance(wrapper, CppWrapperCpu): + raise AssertionError( + f"expected wrapper to be CppWrapperCpu, got {type(wrapper)}" + ) + wrapper.initialized_kernels[name] = self + # Kinda hacky because we always originally initialize name with "KERNEL_NAME" + # So, we replace with the real kernel name passed as an arg to this function. + self.signature = self.signature.replace("KERNEL_NAME", name) + _, call_args, arg_types = self.args.cpp_argdefs(DTYPE_TO_ROCM_TYPE) + else: + _, call_args, _, arg_types = self.args.python_argdefs() + + kernel_args = [] + for arg in call_args: + # dynamo wraps unspec variable as 0d CPU tensor, need convert to scalar + if V.graph.is_unspec_arg(arg): + arg = arg + ".item()" + else: + if not V.graph.cpp_wrapper: + arg = f"c_void_p({arg}.data_ptr())" + kernel_args.append(arg) + + # add size args + size_args = [ + f"{V.graph.sizevars.simplify(sarg)}" for sarg in node.template.size_args() + ] + + if V.graph.cpp_wrapper: + kernel_args.extend(size_args) + else: + kernel_args.extend(f"c_int({sarg})" for sarg in size_args) + + if V.graph.cpp_wrapper: + arg_types.extend(["int"] * len(node.template.size_args())) + + # the runtime args come right after the size args + kernel_args.extend(self.runtime_arg_values) + for arg in self.runtime_arg_info: + arg_types.append(arg.ty) + + # workspace_size ptr is NULL to mark this call is not intended for retrieving workspace_size. + # workspace_size should have already been retrieved prior to this call. + kernel_args.append("nullptr" if V.graph.cpp_wrapper else "None") + if V.graph.cpp_wrapper: + arg_types.append("size_t*") + + if node.get_workspace_size() > 0: + ws = WorkspaceArg( + count=node.get_workspace_size(), + device=V.graph.get_current_device_or_throw(), + zero_mode=WorkspaceZeroMode.UNINITIALIZED, + outer_name=WorkspaceArg.unique_name(), + ) + wrapper.generate_workspace_allocation(ws) + data_ptr = f"{ws.outer_name}.data_ptr()" + kernel_args.append( + data_ptr if V.graph.cpp_wrapper else f"c_void_p({data_ptr})" + ) + else: + ws = None + kernel_args.append("nullptr" if V.graph.cpp_wrapper else "None") + if V.graph.cpp_wrapper: + arg_types.append("uint8_t*") + wrapper.generate_kernel_call( + name, + kernel_args, + triton=False, + arg_types=arg_types, + ) + if ws: + wrapper.generate_workspace_deallocation(ws) + + +class ROCmTemplateCaller(ChoiceCaller): + """ + ROCmTemplateCaller + + This class represents a caller for ROCm template kernels. It is a subclass of ChoiceCaller. + Attributes: + name (str): The name of the caller. + category (str): The category of the caller. + bmreq (ROCmBenchmarkRequest): The benchmark request for the caller. + template_buffer (ROCmTemplateBuffer): The template buffer for the caller. + """ + + def __init__( + self, + name: str, + category: str, + input_nodes: list[Buffer], + layout: Layout, + make_kernel_render: Callable[ + [ROCmTemplateBuffer, Sequence[IRNode] | None], str + ], + bmreq: ROCmBenchmarkRequest, + template: "ROCmTemplate", # type: ignore[name-defined] + info_kwargs: dict[str, PrimitiveInfoType | list[PrimitiveInfoType]] | None, # type: ignore[type-arg] + ) -> None: + super().__init__(name, input_nodes, layout, description="") + self.category = category + self.make_kernel_render = make_kernel_render + self.bmreq = bmreq + self.template = template + self.info_kwargs = info_kwargs + + def precompile(self) -> None: + if self.bmreq is None: + raise AssertionError("expected self.bmreq to be set") + self.bmreq.precompile() + + def benchmark(self, *args, out) -> float: + if self.bmreq is None: + raise AssertionError("expected self.bmreq to be set") + if config.profile_bandwidth_with_do_bench_using_profiling: + algo = self.bmreq.make_run_fn(*args, out=out) + return do_bench_using_profiling(algo) + return self.bmreq.benchmark(*args, out=out) + + def __str__(self) -> str: + return f"ROCmTemplateCaller(source_file={self.bmreq.source_file}, {self.info_dict()})" + + def call_name(self) -> str: + return f"rocm_template_kernels.{self.name}" + + def hash_key(self) -> str: + return "-".join( + [ + self.category, + self.bmreq.hash_key, + ] + ) + + def info_dict(self) -> dict[str, PrimitiveInfoType | list[PrimitiveInfoType]]: + """Information returned here is logged to the autotune log file when that is enabled.""" + return { + "backend": "ROCm", + "name": self.name, + **dict(self.info_kwargs["op"].dict_items()), # type: ignore[union-attr, index] + } + + def output_node(self) -> TensorBox: + self.bmreq.update_workspace_size() + buffer = ROCmTemplateBuffer( + layout=self.layout, + inputs=self.input_nodes, + make_kernel_render=self.make_kernel_render, + workspace_size=self.bmreq.workspace_size, + template=self.template, + ) + # Pass KTC annotation to the buffer for encoding + if "ktc" in self.annotations: + buffer.annotations["ktc"] = self.annotations["ktc"] + return TensorBox.create(buffer) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..d0fb4c568b037811006ca031d29ec4923c6caa77 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_template.py @@ -0,0 +1,194 @@ +# mypy: allow-untyped-defs +import functools +import itertools +import logging +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any +from unittest.mock import patch + +from ...autotune_process import TensorMeta +from ...ir import Buffer, IRNode, Layout +from ...utils import IndentedBuffer, unique +from ...virtualized import V +from ..common import KernelTemplate +from .rocm_benchmark_request import ROCmBenchmarkRequest +from .rocm_kernel import ROCmTemplateCaller, ROCmTemplateKernel +from .rocm_template_buffer import ROCmTemplateBuffer +from .rocm_utils import DTYPE_TO_ROCM_TYPE + + +log = logging.getLogger(__name__) + + +# FIXME: unify with the CUDA version +@dataclass(frozen=True) +class ArgInfo: + name: str + ty: str + + +class ROCmTemplate(KernelTemplate): + index_counter = itertools.count() + gfx9_threads_per_warp = 64 + + def __init__( + self, + name: str, + input_nodes: list[Buffer], + layout: Layout, + input_reorder: list[int] | None = None, + ) -> None: + """ + + Baseclass for ROCm C++ Templates, derived from KernelTemplate. Not to be instantiated directly. + + Args: + name (str): The name of the ROCmTemplate object. + input_nodes (List[IRNode]): A list of input IRNodes. + layout (Layout): The layout of the output buffer / tensor. + input_reorder (Optional[List[int]]): An optional list that specifies the order of the input nodes. + + """ + super().__init__(name) + self.input_nodes = input_nodes + self.output_node: Buffer = Buffer(name="buf_out", layout=layout) + self.input_reorder = input_reorder + self.layout = layout + + def generate( # type: ignore[override] + self, + **kwargs, + ) -> ROCmTemplateCaller: + """ + Generates the ROCm template caller object for the given GEMM template and operation. This ROCmTemplateCaller + may be used to call and benchmark the generated ROCm kernel in a standalone manner to enable Autotuning. + + Args: + kwargs: Additional keyword arguments. + + Returns: + A ROCmTemplateCaller object representing the generated ROCm template caller. + """ + kernel_name = f"rocm_{self.name}" + kernel_hash_name = f"rocm_{self.name}_{next(self.index_counter)}" + with ( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)), + ROCmTemplateKernel( + kernel_name=kernel_name, + runtime_arg_info=self.get_runtime_arg_info(), + runtime_arg_values=self.get_runtime_arg_values(**kwargs), + ) as kernel, + ): + code = self.render(kernel=kernel, **kwargs) + _, call_args, _, _ = kernel.args.python_argdefs() + log.debug("Autotune key: %s, Generated Code:\n%s", kernel_hash_name, code) + log.debug( + "Args: cpp_argdefs: %s, python_argdefs: %s", + kernel.args.cpp_argdefs(DTYPE_TO_ROCM_TYPE), + kernel.args.python_argdefs(), + ) + + input_reorder = ( + self.input_reorder + if self.input_reorder is not None + else list(range(len(self.input_nodes))) + ) + expected_args = list( + unique(self.input_nodes[idx].get_name() for idx in input_reorder) + ) + expected_args.extend([self.output_node.get_name()]) + if list(call_args)[: len(expected_args)] != expected_args: + raise AssertionError( + ( + call_args, + expected_args, + ) + ) + + size_args = ( + self.size_args() if hasattr(self, "size_args") else () + ) # subclass should define def size_args() + # Resolve symbolic sizes to concrete ints for benchmarking only. + size_args_ints = list(V.graph.sizevars.optimization_hints(size_args)) + # The runtime args come right after the size args + runtime_args = self.get_runtime_arg_values(**kwargs) + extra_args = size_args_ints + runtime_args + bmreq = ROCmBenchmarkRequest( + kernel_name=kernel_name, + input_tensor_meta=TensorMeta.from_irnodes(self.input_nodes), + output_tensor_meta=TensorMeta.from_irnodes(self.output_node), + extra_args=extra_args, + source_code=code, + ) + + def make_kernel_render( + template_node: ROCmTemplateBuffer, + epilogue_nodes: Sequence[IRNode] | None = None, + ): + kernel = ROCmTemplateKernel( + kernel_name="KERNEL_NAME", + runtime_arg_info=self.get_runtime_arg_info(), + runtime_arg_values=self.get_runtime_arg_values(**kwargs), + ) + render = functools.partial( + self.render, + kernel=kernel, + template_buffer_node=template_node, + epilogue_nodes=epilogue_nodes, + **kwargs, # includes "op" argument in case of CUTLASSGemmTemplate + ) + return kernel, render + + return ROCmTemplateCaller( + kernel_hash_name, + self.name, + self.input_nodes, + self.output_node.get_layout(), + make_kernel_render, + bmreq, + self, + kwargs, + ) + + def header(self) -> IndentedBuffer: + res = IndentedBuffer() + res.splice( + """ + #include + #include + #include + #include + #include + """ + ) + return res + + def globals(self) -> IndentedBuffer: + res = IndentedBuffer() + res.splice( + """ + // We compile all models with -fvisibility=hidden. Any symbols that need to be + // exposed in the final shared library must be declared with PT_EXPORT to make + // them visible. + #ifdef __GNUC__ // Applies to any compiler with GNU extensions (clang and g++) + #define PT_EXPORT __attribute__((__visibility__("default"))) + #else + #ifdef _WIN32 + #define PT_EXPORT __declspec(dllexport) + #else + #define PT_EXPORT + #endif + #endif + """ + ) + return res + + def render(self, **kwargs) -> str: + raise NotImplementedError + + def get_runtime_arg_info(self) -> list[ArgInfo]: + return [] + + def get_runtime_arg_values(self, **kwargs) -> list[Any]: + return [] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_template_buffer.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_template_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..9c90d71c19980279f13cad86d7385825ba7212c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_template_buffer.py @@ -0,0 +1,27 @@ +from collections.abc import Callable, Sequence +from typing import TypeVar +from typing_extensions import ParamSpec + +from ...ir import Buffer, Layout, TemplateBuffer + + +_P = ParamSpec("_P") +_T = TypeVar("_T") + + +class ROCmTemplateBuffer(TemplateBuffer): + def __init__( + self, + layout: Layout, + inputs: Sequence[Buffer], + make_kernel_render: Callable[_P, _T], + workspace_size: int, + template: "ROCmTemplate", # type: ignore[name-defined] # noqa: F821 + ) -> None: + super().__init__(layout, inputs, make_kernel_render) + # Global memory (in bytes) needed for this template. + self.workspace_size = workspace_size + self.template = template + + def get_workspace_size(self) -> int: + return self.workspace_size if self.workspace_size is not None else 0 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..36871ac5c7f8fcf0a8b91a143168ab1b90530b0b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_utils.py @@ -0,0 +1,17 @@ +# mypy: allow-untyped-defs + + +import torch + +from ..cpp_utils import DTYPE_TO_CPP + + +DTYPE_TO_ROCM_TYPE = { + **DTYPE_TO_CPP, + torch.float16: "uint16_t", + torch.float8_e4m3fnuz: "uint8_t", + torch.float8_e5m2fnuz: "uint8_t", + torch.float8_e4m3fn: "uint8_t", + torch.float8_e5m2: "uint8_t", + torch.bfloat16: "uint16_t", +} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/segmented_tree.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/segmented_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..40d132d66ea236526c8ba89c9a263e6786ae6b78 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/segmented_tree.py @@ -0,0 +1,242 @@ +from collections.abc import Callable +from typing import Generic, TypeVar + + +T = TypeVar("T") + + +def _value_or(opt: T | None, default: T) -> T: + return opt if opt is not None else default + + +class SegmentedTree(Generic[T]): + def __init__( + self, + values: list[T], + update_op: Callable[[T, T], T], + summary_op: Callable[[T, T], T], + identity_element: T, + ): + """ + Initialize a segment tree with the given values and operations. + + Args: + values: list of initial values + update_op: Function to apply when updating a value (e.g., addition) + summary_op: Function to summarize two values (e.g., min, max, sum) + identity_element: Identity element for the summary_op (e.g., 0 for sum, float('inf') for min) + + Raises: + ValueError: If the input values list is empty + """ + if not values: + raise ValueError("Cannot create a segment tree with empty values list") + + self.n = len(values) + self.update_op = update_op + self.summary_op = summary_op + self.identity = identity_element + + # Size of segment tree array (next power of 2 * 2) + # The tree follows a standard heap layout where + # node `n`'s children are at `2*n` and `2*n+1`. + # Index 0 is unused. + self.size = 1 + while self.size < self.n: + self.size *= 2 + self.size *= 2 + + # Initialize tree and lazy arrays + self.tree = [identity_element] * self.size + # The lazy array contains updates to the given node + # Upon update, we only push updates to the top-most + # nodes that fully receive the update. We then + # propagate the update down as required (i.e., when + # we receive an interval query that neither fully + # contains the node nor fully doesn't contain the + # node + self.lazy: list[T | None] = [None] * self.size + + # Build the tree + self._build(values, 1, 0, self.n - 1) + + def _build(self, values: list[T], node: int, start: int, end: int) -> None: + """ + Build the segment tree recursively. + + Args: + values: Original array of values + node: Current node index in the segment tree + start: Start index of the segment + end: End index of the segment + """ + if start == end: + # Leaf node + if start < len(values): + self.tree[node] = values[start] + return + + mid = (start + end) // 2 + left_child = 2 * node + right_child = 2 * node + 1 + + # Recursively build left and right subtrees + self._build(values, left_child, start, mid) + self._build(values, right_child, mid + 1, end) + + # Update current node with summary of children + self.tree[node] = self.summary_op(self.tree[left_child], self.tree[right_child]) + + def _children(self, node: int) -> list[int]: + return [2 * node, 2 * node + 1] + + def _push_lazy(self, node: int, start: int, end: int) -> None: + """ + Push lazy updates down to children. + + Args: + node: Current node index + start: Start index of the segment + end: End index of the segment + """ + lazy_node = self.lazy[node] + if lazy_node is None: + return + + # Apply lazy update to current node + self.tree[node] = self.update_op(self.tree[node], lazy_node) + + if start != end: # Not a leaf node + # Propagate to children + for child in self._children(node): + self.lazy[child] = self.update_op( + _value_or(self.lazy[child], self.identity), lazy_node + ) + + # Clear the lazy value + self.lazy[node] = None + + def _update_range_helper( + self, node: int, start: int, end: int, left: int, right: int, value: T + ) -> None: + """ + Helper method to update a range of values in the segment tree. + + Args: + node: Current node index + start: Start index of the current segment + end: End index of the current segment + left: Start index of the range to update + right: End index of the range to update + value: Value to apply to the range + """ + # Push lazy updates before processing this node + self._push_lazy(node, start, end) + + # No overlap + if start > right or end < left: + return + + # Complete overlap + if start >= left and end <= right: + # Apply update to current node + self.lazy[node] = value + self._push_lazy(node, start, end) + return + + # Partial overlap, recurse to children + mid = (start + end) // 2 + left_child = 2 * node + right_child = 2 * node + 1 + + self._update_range_helper(left_child, start, mid, left, right, value) + self._update_range_helper(right_child, mid + 1, end, left, right, value) + + # Update current node based on children + self.tree[node] = self.summary_op(self.tree[left_child], self.tree[right_child]) + + def _query_range_helper( + self, node: int, start: int, end: int, left: int, right: int + ) -> T: + """ + Helper method to query a range of values in the segment tree. + + Args: + node: Current node index + start: Start index of the current segment + end: End index of the current segment + left: Start index of the range to query + right: End index of the range to query + + Returns: + Summary value for the range + """ + # No overlap + if start > right or end < left: + return self.identity + + # Push lazy updates before processing this node + self._push_lazy(node, start, end) + + # Complete overlap + if start >= left and end <= right: + return self.tree[node] + + # Partial overlap, recurse to children + mid = (start + end) // 2 + left_child = 2 * node + right_child = 2 * node + 1 + + left_result = self._query_range_helper(left_child, start, mid, left, right) + right_result = self._query_range_helper(right_child, mid + 1, end, left, right) + + # Combine results from children + return self.summary_op(left_result, right_result) + + def update_range(self, start: int, end: int, value: T) -> None: + """ + Update a range of values in the segment tree. + + Args: + start: Start index of the range to update (inclusive) + end: End index of the range to update (inclusive) + value: Value to apply to the range + + Raises: + ValueError: If start > end or indices are out of bounds + """ + if start > end: + raise ValueError("Start index must be less than or equal to end index") + + if start < 0 or start >= self.n: + raise ValueError(f"Start index {start} out of bounds [0, {self.n - 1}]") + + if end < 0 or end >= self.n: + raise ValueError(f"End index {end} out of bounds [0, {self.n - 1}]") + + self._update_range_helper(1, 0, self.n - 1, start, end, value) + + def summarize_range(self, start: int, end: int) -> T: + """ + Query a range of values in the segment tree. + + Args: + start: Start index of the range to query (inclusive) + end: End index of the range to query (inclusive) + + Returns: + Summary value for the range according to the summary operation + + Raises: + ValueError: If start > end or indices are out of bounds + """ + if start > end: + raise ValueError("Start index must be less than or equal to end index") + + if start < 0 or start >= self.n: + raise ValueError(f"Start index {start} out of bounds [0, {self.n - 1}]") + + if end < 0 or end >= self.n: + raise ValueError(f"End index {end} out of bounds [0, {self.n - 1}]") + + return self._query_range_helper(1, 0, self.n - 1, start, end) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/simd.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/simd.py new file mode 100644 index 0000000000000000000000000000000000000000..cf82938d7611e5c21e00e0270ae21fc10b5682b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/simd.py @@ -0,0 +1,5058 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import collections +import contextlib +import dataclasses +import functools +import itertools +import logging +import math +import operator +import textwrap +from collections import Counter +from typing import Any, cast, Generic, NamedTuple, TYPE_CHECKING +from typing_extensions import TypeVar + +import sympy + +import torch +import torch._logging +from torch._inductor import metrics +from torch._inductor.ir import MultiTemplateBuffer +from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols +from torch.fx.immutable_collections import immutable_dict +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import FloorDiv, Identity, ModularIndexing +from torch.utils._sympy.symbol import ( + free_symbol_is_type, + prefix_str, + symbol_is_type, + SymT, +) + +from ..._dynamo.utils import counters +from .. import config, ir, scheduler +from ..analyze_preserves_zero_mask import prologue_preserves_zero_mask +from ..codecache import code_hash, PyCodeCache +from ..dependencies import MemoryDep, StarDep, WeakDep + + +if TYPE_CHECKING: + from collections.abc import Callable + + from ..ir import IRNode + +from ..ops_handler import WrapperHandler +from ..optimize_indexing import ( + convert_index_expr_to_value_expr, + indexing_dtype_strength_reduction, +) +from ..runtime.coordinate_descent_tuner import CoordescTuner +from ..runtime.hints import DeviceProperties, InductorMeta +from ..runtime.runtime_utils import ( + green_text, + last_power_of_2, + next_power_of_2, + yellow_text, +) +from ..scheduler import BaseSchedulerNode, BaseScheduling, WhyNoFuse +from ..utils import ( + cache_property_on_self, + decompose_index, + expr_fits_within_32bit, + get_dtype_size, + IndentedBuffer, + Placeholder, + prefix_is_reduction, + sympy_index_symbol, + sympy_product, + sympy_subs, + unique, +) +from ..virtualized import ops, OpsWrapper, V +from .block_analysis import BlockPatternMatcher +from .common import CSEVariable, index_prevent_reordering, Kernel, PythonPrinter +from .multi_kernel import MultiKernel, SizeHintMultiKernel +from .simd_kernel_features import ( + DisableReduction, + EnableReduction, + NodeScheduleEntry, + NodeScheduleMarker, + SIMDKernelFeatures, +) + + +_MAX_INLINE_PRECOMPUTABLE_SIZE_EXPR_OPS = 64 + + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Sequence + + from torch._inductor.codegen.triton import TritonKernel + from torch._inductor.tiling_utils import CoalesceVarAnalysis + + +log = logging.getLogger(__name__) +perf_hint_log = torch._logging.getArtifactLogger(__name__, "perf_hints") +schedule_log = torch._logging.getArtifactLogger(__name__, "schedule") +fusion_log = torch._logging.getArtifactLogger(__name__, "fusion") + + +pexpr = PythonPrinter().doprint + +all_prefixes = OrderedSet(["z", "y", "x", "r0_", "r1_"]) + + +def get_max_tiles(default: int = 2) -> int: + max_tiles = torch._inductor.config.triton.max_tiles + return max_tiles if max_tiles is not None else default + + +@dataclasses.dataclass +class IterationRanges: + """ + Each range tree represents multiple sets of iteration indexing + in a single tiled dimension in the output kernel. + + If you have two loops ranges one (4, 3, 2) and another (4, 6), + then the range tree will be: + 4 (i0) + 3 (i1) 6 (i3) + 2 (i2) + Where i0 is shared between both loops, but then the split into + different indexing vars. All loop ranges must iterate over + the same number of elements. + """ + + def __init__( + self, + name: str, + var_list: list[sympy.Symbol], + var_ranges: dict[sympy.Symbol, sympy.Expr], + numel: sympy.Expr, + prefix: str, + *, + kernel: SIMDKernel, + divisor=sympy.S.One, + length=sympy.S.One, + root: IterationRangesRoot, + ) -> None: + super().__init__() + self.name = name + self.var_list = var_list + self.var_ranges = var_ranges + self.numel = numel + self.prefix = prefix + self.divisor = divisor + self.length = length + self.kernel = kernel + self.root = root + + @property + @cache_property_on_self + def is_reduction(self) -> bool: + return prefix_is_reduction(self.prefix) + + def symbol(self) -> sympy.Symbol: + return sympy_index_symbol(self.name) + + @property + @cache_property_on_self + def symt(self) -> SymT: + prefix_to_symt = {prefix: symt for symt, prefix in prefix_str.items()} + return prefix_to_symt[self.prefix] + + +class IterationRangesRoot(IterationRanges): + """ + Root of a iteration range tree that represents a single + tiled dimension in the output kernel. It contains multiple + sets of iteration represented with IterationRangesEntry. + """ + + def __init__( + self, + name: str, + numel: sympy.Expr, + prefix: str, + index: int, + kernel: SIMDKernel, + pid_cache: dict[str, str] | None = None, + *, + is_loop: bool, + tensor_dim: int | None, + grid_dim: int | None, + has_zdim: bool, + ) -> None: + if pid_cache is None: + pid_cache = {} + super().__init__( + name=name, + var_list=[], + var_ranges={}, + numel=numel, + prefix=prefix, + kernel=kernel, + root=self, + ) + self.index = index + # Store all the nodes in one flat list + self.nodes: dict[sympy.Expr, IterationRangesEntry] = {} + # This is for re-ordering program ID in triton mm template + # pid_cache["tl.program_id(0)"] = pid_m + self.pid_cache: dict[str, str] = pid_cache + + # True if the dimension is implemented as a single program looping over + # the full dimension (currently only used for non-persistent reduction) + + if is_loop and not (self.is_reduction and grid_dim is None): + raise AssertionError("loop ranges must be reduction with no grid_dim") + self.is_loop = is_loop + # Index of corresponding dimension on triton tensors + self.tensor_dim = tensor_dim + # Index of corresponding dimension in the triton grid + self.grid_dim = grid_dim + self.has_zdim = has_zdim + + def __repr__(self) -> str: + return f"IterationRangesRoot({self.name!r}, {self.numel}, ...)" + + def block_size(self) -> sympy.Expr: + return sympy.Symbol(f"{self.prefix.upper()}BLOCK", integer=True, positive=True) + + def block_size_str(self) -> str: + return str(self.block_size()) + + def block_offset(self) -> sympy.Expr: + # iteration_ranges_codegen_header uses this to derive the tile-local + # base index for the tree. + return sympy.Symbol(f"{self.prefix}offset", integer=True, nonnegative=True) + + def mask_name(self) -> str: + return f"{self.prefix}mask" + + def owns_mask(self, mask_var: str) -> bool: + return mask_var == self.mask_name() + + def mask_shape(self, tensor_ndim: int) -> tuple[str, ...]: + if self.tensor_dim is None: + return () + + shape = ["1"] * tensor_ndim + shape[self.tensor_dim] = self.block_size_str() + return tuple(shape) + + def supports_constant_mask(self) -> bool: + return True + + def has_custom_codegen_header(self) -> bool: + return False + + def named_constants(self) -> tuple[tuple[sympy.Symbol, sympy.Expr, bool], ...]: + return () + + def cache_clear(self) -> None: + for node in self.nodes.values(): + node.cache_clear() + + def index_sym(self) -> sympy.Symbol: + return sympy_index_symbol(f"{self.prefix}index") + + def lookup(self, divisor: sympy.Expr, length: sympy.Expr) -> IterationRangesEntry: + """ + Lookup a given RangeTreeEntry, creating it if needed + """ + if V.graph.sizevars.statically_known_equals(divisor * length, self.numel): + expr = FloorDiv(self.index_sym(), divisor) + else: + expr = ModularIndexing(self.index_sym(), divisor, length) + + if expr not in self.nodes: + node = IterationRangesEntry( + f"{self.prefix}{next(V.kernel.iter_vars_count)}", + divisor, + length, + expr, + self, + ) + V.kernel.range_tree_nodes[node.symbol()] = node + self.var_list.append(node.symbol()) + self.var_ranges[node.symbol()] = length + self.nodes[expr] = node + return self.nodes[expr] + + def full_range(self) -> IterationRangesEntry: + """Return the canonical entry for this root's unsplit logical index. + + This is ``lookup(1, numel)``, so the entry is interned in + ``range_tree_nodes`` just like split entries. + """ + return self.lookup(sympy.S.One, self.numel) + + def construct_entries( + self, lengths: list[sympy.Expr] + ) -> list[IterationRangesEntry]: + divisor = sympy.S.One + itervars = [] + for length in reversed(lengths): + itervars.append(self.lookup(divisor, length)) + divisor = divisor * length + return [*reversed(itervars)] + + def construct(self, lengths: list[sympy.Expr]) -> list[sympy.Symbol]: + return [e.symbol() for e in self.construct_entries(lengths)] + + def vars_and_sizes( + self, index: sympy.Expr + ) -> tuple[list[sympy.Symbol], list[sympy.Expr]]: + """Figure out vars from this tree used in index""" + + def get_sort_key(x: IterationRangesEntry) -> tuple[int, bool]: + """ + Gets the key for sorting nodes. When two nodes have the + same divisor, the node with length as 1 should be handled + first so the current divisor is not changed after multiplied + node.length. Returns `not length_is_one_hint` for ascending + sort. + """ + divisor_hint = V.graph.sizevars.optimization_hint(x.divisor) + length_is_one_hint = V.graph.sizevars.optimization_hint(x.length) == 1 + return (divisor_hint, not length_is_one_hint) + + nodes = [V.kernel.range_tree_nodes.get(s) for s in index.free_symbols] + nodes = [n for n in nodes if n and n.root is self] + nodes.sort(key=lambda x: get_sort_key(x)) + divisor = sympy.S.One + index_vars = [] + sizes = [] + + def add(node): + nonlocal divisor + index_vars.append(node.symbol()) + sizes.append(node.length) + divisor = divisor * node.length + + for node in nodes: + if not V.graph.sizevars.statically_known_equals(node.divisor, divisor): + # fill in unused index var + add(self.lookup(divisor, FloorDiv(node.divisor, divisor))) + divisor = node.divisor + add(node) + if not V.graph.sizevars.statically_known_equals(self.numel, divisor): + # fill in unused index var + add(self.lookup(divisor, FloorDiv(self.numel, divisor))) + + return [*reversed(index_vars)], [*reversed(sizes)] + + +class IterationRangesEntry(IterationRanges): + def __init__( + self, + name: str, + divisor: sympy.Expr, + length: sympy.Expr, + expr: sympy.Expr, + parent: IterationRanges, + ) -> None: + super().__init__( + name=name, + numel=parent.numel / length, + var_list=parent.var_list, + var_ranges=parent.var_ranges, + prefix=parent.prefix, + divisor=divisor, + length=length, + kernel=parent.kernel, + root=parent.root, + ) + self.parent = parent + self.codegen = functools.lru_cache(None)(self._codegen) + self.expr = expr + + def __repr__(self) -> str: + return f"IterationRangesEntry({self.name}, {self.divisor}, {self.length}, {self.expr}, {self.var_ranges})" + + def set_name(self, name: str) -> None: + self.codegen = lambda: name # type: ignore[assignment] + self.codegen.cache_clear = lambda: None # type: ignore[method-assign] + self.name = name + + def cache_clear(self) -> None: + self.codegen.cache_clear() + + def _codegen(self) -> str: + V.kernel.codegen_iteration_ranges_entry(self) + return self.name + + def precomputed_args(self) -> list[sympy.Expr]: + # for dynamic shapes, find parts of indexing expressions that have to be precomputed + precomputed_args: list[sympy.Expr] = [] + if isinstance(self.expr, sympy.Symbol): + return precomputed_args + if not isinstance(self.expr, (FloorDiv, ModularIndexing)): + raise AssertionError(type(self.expr)) + for arg in self.expr.args[1:]: + if not isinstance(arg, (sympy.Integer, sympy.Symbol)): + symbols = arg.free_symbols + if len(symbols) > 0 and all( + symbol_is_type(s, SymT.SIZE) for s in symbols + ): + precomputed_args.append(arg) + return precomputed_args + + def __hash__(self) -> int: + return hash(self.name) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, IterationRangesEntry): + raise AssertionError(f"expected IterationRangesEntry, got {type(other)}") + return self.name == other.name + + +class DerivedIterationRangesRoot(IterationRangesRoot): + """A root with reduced numel/block_size derived from a parent tree. + + Used for the grouped reduction output: if the parent R tree covers 1024 + columns with local_reduction_size=128, the derived root covers 8 groups. It shares + the parent's loop structure (same is_loop, prefix, loop variable) but + has its own block geometry: + + parent R: numel=1024, block_size=RBLOCK, offset=roffset + derived R: numel=8, block_size=RBLOCK//128, offset=roffset//128 + + This lets the grouped reduction store at reduced-resolution offsets + while still running inside the parent's reduction loop. + """ + + def __init__( + self, + parent: IterationRangesRoot, + *, + numel: sympy.Expr, + block_size: sympy.Expr, + block_offset: sympy.Expr, + name_suffix: str = "reduced", + named_constants: tuple[tuple[sympy.Symbol, sympy.Expr, bool], ...] = (), + ) -> None: + super().__init__( + name=f"{name_suffix}_{parent.name}", + numel=numel, + prefix=parent.prefix, + index=parent.index, + kernel=parent.kernel, + pid_cache=parent.pid_cache, + # Outer reductions are not always persistent. When the parent + # reduction tree is looped, any derived view of it must also stay + # loop-local; otherwise its block offset is emitted once in the + # kernel prologue and closes over a stale reduction offset from a + # previous loop iteration. + is_loop=parent.is_loop, + tensor_dim=parent.tensor_dim, + grid_dim=parent.grid_dim, + has_zdim=parent.has_zdim, + ) + self._block_size = block_size + self._block_offset = block_offset + self._named_constants = named_constants + + def block_size(self) -> sympy.Expr: + return self._block_size + + def block_offset(self) -> sympy.Expr: + return self._block_offset + + def index_sym(self) -> sympy.Symbol: + return sympy_index_symbol(self.name) + + def mask_name(self) -> str: + return f"{self.name}_mask" + + def supports_constant_mask(self) -> bool: + # Derived roots use expressions like R0_BLOCK // G rather than + # fixed-config block keys, so keep their masks explicit. + return False + + def named_constants(self) -> tuple[tuple[sympy.Symbol, sympy.Expr, bool], ...]: + return self._named_constants + + def has_custom_codegen_header(self) -> bool: + return True + + +def constant_repr(value: int | float) -> str: + if value == float("inf"): + return 'float("inf")' + elif value == float("-inf"): + return 'float("-inf")' + elif math.isnan(value): + return 'float("nan")' + return repr(value) + + +CSEVariableType = TypeVar("CSEVariableType", bound=CSEVariable, default=CSEVariable) + + +@dataclasses.dataclass +class PartialAccumulate: + buffer_name: str + reduction_type: str + value: Any + + +class NodeInfo(NamedTuple): + """ + Pre-computed node information for combo kernel partitioning. + """ + + node_schedule: list + tiling: dict + tiling_scores: dict | None + numel: Any + rnumel: Any + features: SIMDKernelFeatures + is_persistent_reduction: bool + + +class SIMDKernel(Kernel[CSEVariableType], Generic[CSEVariableType]): + """ + Common base class for Triton/Halide codegen which both use flattened indexing rather than loop nests. + """ + + sexpr: Callable[[sympy.Expr], str] = pexpr + kexpr: Callable[[sympy.Expr], str] + allow_block_ptr: bool = False + # pyrefly: ignore [bad-override] + kernel_name: str + + def __init__( + self, + tiling: dict[str, sympy.Expr], + features: SIMDKernelFeatures, + pid_cache: dict[str, str] | None = None, + override_persistent_reduction: bool | None = None, + override_cooperative_reduction: bool | None = None, + tiling_scores: dict[str, sympy.Expr] | None = None, + mix_order_reduction: bool = False, + ) -> None: + if pid_cache is None: + pid_cache = {} + super().__init__() + self.features = features + self.mutations = features.get_mutations() + self.body = IndentedBuffer() + self.indexing_code = IndentedBuffer() + self.numels = { + prefix: V.graph.sizevars.simplify(val) for prefix, val in tiling.items() + } + self.range_trees: list[IterationRangesRoot] = [] + self.range_tree_nodes: dict[sympy.Symbol, IterationRangesEntry] = {} + self.iter_vars_count = itertools.count() + self.inside_reduction = features.is_reduction() + self.cooperative_reduction: bool = ( + override_cooperative_reduction + if override_cooperative_reduction is not None + else self.should_use_cooperative_reduction() + ) + self.tiling_scores: dict[str, sympy.Expr] | None = tiling_scores + self.tiling: dict[str, sympy.Expr] = tiling + self.persistent_reduction: bool = ( + override_persistent_reduction + if override_persistent_reduction is not None + else self.should_use_persistent_reduction() + ) + self.mix_order_reduction: bool = mix_order_reduction + self.no_x_dim = self.want_no_x_dim() + self.code_hash: str | None = None + # Info to enable multiple store_output calls for epilogue subtiling + self.store_output_ctr = itertools.count() + self.is_native_matmul = False + if config.triton.native_matmul: + for node in self.features.node_schedule: + if ( + isinstance(node, scheduler.SchedulerNode) + and isinstance(node.node, ir.ComputedBuffer) + and node.node.get_reduction_type() == "dot" + ): + self.is_native_matmul = True + break + + # define this in a closure to make cache local to object + @functools.cache + def simplify_indexing(index: sympy.Expr): + index = V.graph.sizevars.simplify_with_ranges(index, self.var_ranges()) + for tree in self.range_trees: + index = self.combine_contiguous_dims(index, tree) + + return self.combine_modular_indexing_pairs(index) + + self.simplify_indexing = simplify_indexing + self.initialize_range_tree(pid_cache) + + self.rsplit_size = 0 + self.min_xblock: int | None = None + self.min_rblock: int | None = None + self.saved_partial_accumulate: list[PartialAccumulate] = [] + self._index_dtype = self.features.select_index_dtype() + + def codegen_template_body( + self, + scheduling, + template_node, + epilogue_nodes, + prologue_nodes, + buf_name_to_prologue_group, + prologue_preserves_zero_mask_fn, + render, + ) -> str: + """Generate template source code with fused prologues and epilogues. + + Subclasses override this to implement custom code generation. + The default implementation raises NotImplementedError — the actual + standard path lives in ``TritonTemplateKernel.codegen_template_body``. + """ + raise NotImplementedError + + def get_unfused_epilogues(self) -> list[Any]: + """Return epilogue nodes that were not fused into the kernel. + + These nodes need separate codegen (via ``call_kernel``) and must + be excluded from ``mark_run`` in ``_codegen_single_template``. + + The standard path fuses all epilogues, so this returns ``[]``. + ``ExternalTritonTemplateKernel`` overrides this for epilogues that + don't read exactly one template output and cannot be fused. + """ + return [] + + def _get_store_output_subgraph_name(self, i: int) -> str: + return f"" + + def get_store_output_count(self): + total = next(self.store_output_ctr) + self.store_output_ctr = itertools.count(start=total - 1, step=1) + return total + + @property + @cache_property_on_self + def num_reduction_dims(self) -> int: + return sum(prefix_is_reduction(prefix) for prefix in self.numels) + + def dtype_to_str(self, dtype: torch.dtype) -> str: + raise NotImplementedError + + def get_index_dtype_as_torch_dtype(self) -> torch.dtype: + return self._index_dtype + + @property + def index_dtype(self) -> str: + return self.dtype_to_str(self.get_index_dtype_as_torch_dtype()) + + def want_no_x_dim(self) -> bool: + return False + + def construct_range_trees( + self, + pid_cache: dict[str, str] | None, + inside_reduction: bool, + is_reduction: bool, + numels: dict[str, sympy.Expr], + no_x_dim: bool, + ) -> list[IterationRangesRoot]: + active_prefixes = OrderedSet( + prefix for prefix in all_prefixes if prefix in numels + ) + no_r_dim = not inside_reduction or not is_reduction + + def filtered_index_map(seq, mask) -> dict[Any, int]: + return { + val: idx for idx, val in enumerate(val for val in seq if val in mask) + } + + grid_dims = ["x", "y", "z"] + pointwise_tensor_dims = list(reversed(grid_dims)) + reduction_dims = ["r0_", "r1_"] + if no_x_dim: + tensor_dims = reduction_dims + elif no_r_dim: + tensor_dims = pointwise_tensor_dims + else: + tensor_dims = pointwise_tensor_dims + reduction_dims + + # Filter out unused tensor dims. + # Convert to dicts for O(1) index lookup. + tensor_dim_map = filtered_index_map(tensor_dims, active_prefixes) + grid_dim_map = filtered_index_map(grid_dims, all_prefixes) + + range_trees = [] + for i, prefix in enumerate(active_prefixes): + is_reduction = prefix_is_reduction(prefix) + tensor_dim = tensor_dim_map.get(prefix) + grid_dim = grid_dim_map.get(prefix) + index = i if grid_dim is None else grid_dim + range_trees.append( + IterationRangesRoot( + f"{prefix}index", + numels[prefix], + prefix, + index, + self, # type: ignore[arg-type] + pid_cache=pid_cache, + is_loop=is_reduction and not self.persistent_reduction, + tensor_dim=tensor_dim, + grid_dim=grid_dim, + has_zdim="z" in numels, + ) + ) + return range_trees + + def initialize_range_tree(self, pid_cache: dict[str, str]) -> None: + range_trees = self.construct_range_trees( + pid_cache, + self.inside_reduction, + self.features.is_reduction(), + self.numels, + self.no_x_dim, + ) + self.range_trees.extend(range_trees) + + def finalize_indexing(self, indices: Sequence[sympy.Expr]) -> None: + """ + Hook called right before codegen with every index that will be + used in the fused kernel. + """ + + def store_reduction(self, name: str, index: sympy.Expr, value: CSEVariable) -> None: + prior = self.inside_reduction + self.inside_reduction = False + try: + return self.store(name, index, value) + finally: + self.inside_reduction = prior + + def should_use_cooperative_reduction(self) -> bool: + return False # defined in subclass + + def should_use_persistent_reduction(self) -> bool: + return False # defined in subclass + + def var_ranges(self) -> dict[sympy.Symbol, sympy.Expr]: + return dict( + itertools.chain.from_iterable( + tree.var_ranges.items() for tree in self.range_trees + ) + ) + + def combine_modular_indexing_pairs(self, index: sympy.Expr) -> sympy.Expr: + if not isinstance(index, ModularIndexing): + return index + x = index.args[0] + if (tree_node := self.range_tree_nodes.get(x)) is None: + return index + new_index = sympy_subs(index, {x: tree_node.expr}) + new_index = V.graph.sizevars.combine_modular_indexing_pairs(new_index) + # the index now contains xindex/etc, which is nonstandard, fix it up + return sympy_subs( + new_index, + {tree_node.root.index_sym(): tree_node.root.full_range().symbol()}, + ) + + def combine_contiguous_dims( + self, index: sympy.Expr, tree: IterationRangesRoot + ) -> sympy.Expr: + if isinstance(index, sympy.Add) and index.has(FloorDiv): + candidate_vars, _ = tree.vars_and_sizes(index) + else: + candidate_vars = None + if expand_res := V.graph.sizevars.expand_floor_div(index, candidate_vars): + new_index, denominator = expand_res # type: ignore[misc] + return FloorDiv(self._combine_contiguous_dims(new_index, tree), denominator) + else: + return self._combine_contiguous_dims(index, tree) + + def _combine_contiguous_dims( + self, index: sympy.Expr, tree: IterationRangesRoot + ) -> sympy.Expr: + """ + More aggressive simplification to merge contiguous dims + """ + if isinstance(index, (sympy.Integer, sympy.Symbol)): + return index + index_vars, sizes = tree.vars_and_sizes(index) + if len(sizes) <= 1: + return index + new_sizes, reindex, _prune = V.graph.sizevars._simplify_loops( + index_vars, sizes, index_prevent_reordering([index], index_vars, sizes) + ) + if new_sizes == sizes: + return index + new_index_vars = tree.construct(new_sizes) + new_index = sympy_subs(index, dict(zip(index_vars, reindex(new_index_vars)))) + return new_index + + def disable_reduction(self) -> contextlib.AbstractContextManager[None]: + should_flush = self.range_trees[-1].is_loop or self.cooperative_reduction + + @contextlib.contextmanager + def ctx(): + if not self.features.is_reduction(): + if self.inside_reduction: + raise AssertionError("expected not self.inside_reduction") + yield + return + if should_flush: + # calling codegen_body() will flush all the pending buffers + # and write out a reduction loop + self.codegen_body() + self.inside_reduction = False + try: + yield + if should_flush: + # flush out any code before opening the next loop + self.codegen_body() + finally: + self.inside_reduction = True + + return ctx() + + def set_ranges(self, *lengths: sympy.Expr) -> list[sympy.Symbol]: + if len(lengths) != len(self.range_trees): + raise AssertionError( + f"expected len(lengths) == len(self.range_trees), " + f"got {len(lengths)} and {len(self.range_trees)}" + ) + return [ + ranges.construct(length) + for length, ranges in zip(lengths, self.range_trees) + ] + + @staticmethod + def _split_iteration_ranges( + groups: Iterable[sympy.Expr], lengths: Sequence[Sequence[sympy.Expr]] + ) -> tuple[ + list[list[sympy.Expr]], list[list[Callable[[list[sympy.Expr]], sympy.Expr]]] + ]: + # Special case: if a node's sizes are ([], []), there's nothing to split. + if all(len(length) == 0 for length in lengths): + return [[] for group in groups], [] + + sv = V.graph.sizevars + new_ranges: list[list[sympy.Expr]] = [[] for _ in groups] + remaining = [sv.simplify(g) for g in groups] + var_count = itertools.count() + + def add_range(i: int, expr: sympy.Expr) -> int: + expr = sv.simplify(expr) + if not sv.statically_known_multiple_of(remaining[i], expr): + raise CantSplit(remaining[i], expr) + # guard on the last item out + remaining[i] = FloorDiv(remaining[i], expr) + new_ranges[i].append(expr) + return next(var_count) + + def make_combined( + sizes: list[sympy.Expr], idxs: list[int] + ) -> Callable[[list[sympy.Expr]], sympy.Expr]: + """ + Builds the nested expression: + ((...((s1*v[i1] + v[i2]) * s2 + v[i3]) ... ) * sk + v[i(k+1)]) + """ + if len(idxs) != len(sizes) + 1: + raise AssertionError( + f"expected len(idxs) == len(sizes) + 1, " + f"got {len(idxs)} and {len(sizes) + 1}" + ) + + def getter(flat_vars: list[sympy.Expr]) -> sympy.Expr: + expr = flat_vars[idxs[0]] + for s, idx in zip(sizes, idxs[1:]): + expr = s * expr + flat_vars[idx] + return expr + + return getter + + return_getters_groups = [] + current_group = 0 + for length_group in lengths: + return_getters = [] + for size in length_group: + if sv.statically_known_equals(size, 1): # type: ignore[arg-type] + return_getters.append(lambda _: sympy.S.Zero) + continue + + while current_group < len(remaining) and sv.statically_known_equals( + remaining[current_group], + 1, # type: ignore[arg-type] + ): + # scroll to next group with remaining elements + current_group += 1 + + # When fusing a node whose flat iteration size spans three + # consecutive kernel groups, decompose it across those groups. + # This covers both bmm-style [z, y, x, 1] groups and nested + # reduction [outer, groups, local] groups. + if current_group + 2 < len(remaining) and sv.statically_known_gt( + size, remaining[current_group] * remaining[current_group + 1] + ): + # need to break size in three + if not sv.statically_known_multiple_of( + size, remaining[current_group] * remaining[current_group + 1] + ): + raise CantSplit( + size, + remaining[current_group] * remaining[current_group + 1], + ) + + size1 = remaining[current_group] + size2 = remaining[current_group + 1] + size3 = FloorDiv(size, size1 * size2) + return_getters.append( + # pyrefly: ignore [bad-argument-type] + make_combined( + [size2, size3], + [ + add_range(current_group, size1), + add_range(current_group + 1, size2), + add_range(current_group + 2, size3), + ], + ) + ) + + # Two-dimensional tiling: split size across current_group and next group. + elif current_group + 1 < len(remaining) and ( + sv.statically_known_gt(size, remaining[current_group]) + or + # statically_known_gt(size, remaining) may return False for symbolic + # expressions like 64*u0 vs u0, because both could be 0. Similarly for + # backed expressions like s25*(((s70 - 5)//4)) - s25 and + # (s25*(((s70 - 5)//4)) - s25)*64. + # We want to assume tensor sizes are not 0 and pass the gt + # using the following logic. + # + # if A//B = C and C >= 1 + # then A = B * C + R + # and assuming A!=0 + # A must be > B . + # + sv.statically_known_gt(FloorDiv(size, remaining[current_group]), 1) + ): + # need to break size in two + if not sv.statically_known_multiple_of( + size, remaining[current_group] + ): + raise CantSplit(size, remaining[current_group]) + + size1 = remaining[current_group] + size2 = FloorDiv(size, remaining[current_group]) + return_getters.append( + # pyrefly: ignore [bad-argument-type] + make_combined( + [size2], + [ + add_range(current_group, size1), + add_range(current_group + 1, size2), + ], + ) + ) + else: + if current_group >= len(remaining): + raise CantSplit(size, 0) + return_getters.append( + # pyrefly: ignore [bad-argument-type] + operator.itemgetter(add_range(current_group, size)) + ) + return_getters_groups.append(return_getters) + + if not all(V.graph.sizevars.guarding_hint_or_throw(s) == 1 for s in remaining): + # Non-unit leftover extents mean the node's iteration space does not + # tile onto the kernel groups -- e.g. fusing an epilogue whose row + # count is a strict sub-multiple of a template's tiling ([s, N] into + # [K*s, N]). Raise CantSplit (consistent with the divisibility exits + # in add_range above) so callers like is_compatible and + # Scheduler.speedup_by_fusion skip this fusion and fall back to + # unfused codegen instead of hard-failing the whole compile. + raise CantSplit(remaining, lengths) + # pyrefly: ignore [bad-return] + return new_ranges, return_getters_groups + + @classmethod + def prepare_split_iteration_lengths( + cls, + groups: Iterable[sympy.Expr], + lengths: Sequence[Sequence[sympy.Expr]], + reduction_numel: sympy.Expr = sympy.S.One, + ) -> Sequence[Sequence[sympy.Expr]]: + "Fill in the reduction numel of lengths if missing" + sizevars = V.graph.sizevars + if len(lengths[1]) == 0 and ( + not sizevars.statically_known_equals(reduction_numel, sympy.S.One) + and sizevars.statically_known_equals( + sympy_product(groups), + sympy_product(lengths[0]) * reduction_numel, + ) + ): + return (lengths[0], [reduction_numel]) + + return lengths + + @classmethod + def is_compatible( + cls, + groups: Iterable[sympy.Expr], + lengths: Sequence[Sequence[sympy.Expr]], + reduction_numel: sympy.Expr = sympy.S.One, + ) -> bool: + lengths = cls.prepare_split_iteration_lengths(groups, lengths, reduction_numel) + + try: + cls._split_iteration_ranges(groups, lengths) + return True + except CantSplit: + return False + + def split_and_set_ranges( + self, lengths: Sequence[Sequence[sympy.Expr]] + ) -> list[list[sympy.Expr]]: + """ + Split and set iteration ranges for the kernel based on the provided lengths. + + This method maps the kernel's tiling structure to the node's iteration space, + handling both pointwise and reduction dimensions appropriately. + + Args: + lengths: A sequence of sequences of symbolic expressions representing + the sizes of different dimensions for each node. + + Returns: + A list of lists of symbolic expressions representing the mapped + iteration variables for each dimension. + """ + # Create a dictionary mapping each range tree prefix to its total number of elements + tiling = {rt.prefix: rt.numel for rt in self.range_trees} + + # If we're not inside a reduction loop, set all reduction dimensions to 1 + # This effectively disables reduction dimensions when not needed + if not self.inside_reduction: + for prefix in tiling: + if prefix_is_reduction(prefix): + tiling[prefix] = sympy.S.One + + # Extract the values from the tiling dictionary to create groups + groups = [*tiling.values()] + + # Map the kernel's group structure to the node's sizes and set the ranges + # using the set_ranges method, returning the resulting iteration variables + return self.map_kernel_groups_to_node_sizes(groups, lengths, self.set_ranges) + + @classmethod + def map_kernel_groups_to_node_sizes( + cls, + groups: Sequence[sympy.Expr], + lengths: Sequence[Sequence[sympy.Expr]], + set_ranges, + ) -> list[list[sympy.Expr]]: + """ + We may want to fuse `for i0 in s0*s1` into a tiled kernel with groups (s0, s1). + + To do this we need to split up the iteration space of i0 into something like: + for i1 in s0: + for i2 in s1: + i0 = i1*s1 + i2 + .... + + This function matches and resplits lengths to the groups of + this kernel to enable tiled + non-tiled fusions. + """ + if len(lengths) == len(groups) and all( + V.graph.sizevars.simplify(sympy_product(x) - g) == 0 + for x, g in zip(lengths, groups) + ): + return set_ranges(*lengths) + + new_ranges, return_getters_groups = cls._split_iteration_ranges(groups, lengths) + itervars = [*itertools.chain.from_iterable(set_ranges(*new_ranges))] + return [[fn(itervars) for fn in fns] for fns in return_getters_groups] + + def is_indirect_indexing(self, index: sympy.Expr) -> bool: + # tmpX means indirect indexing + return free_symbol_is_type(index, SymT.TMP) + + def is_broadcasted(self, index: sympy.Expr) -> bool: + # Note. This may not be correct when there is indirect indexing + if self.is_indirect_indexing(index): + return False + + active_trees = self.active_range_trees() + index_numels = [1] * len(active_trees) + for symbol in index.free_symbols: + entry = self.range_tree_nodes.get(symbol) + if entry is None: + # Non-iterated variables, e.g. strides + continue + if not isinstance(entry.parent, IterationRangesRoot): + raise AssertionError( + f"expected entry.parent to be IterationRangesRoot, " + f"got {type(entry.parent)}" + ) + # Find which active tree this entry belongs to (identity check + # because derived trees may shadow the same prefix). + tree_pos = next( + (i for i, tree in enumerate(active_trees) if tree is entry.parent), + None, + ) + if tree_pos is None: + # The symbol belongs to an inactive tree family, e.g. a + # reduction symbol outside the reduction or a temporarily + # swapped-out derived tree. + continue + index_numels[tree_pos] *= entry.length + + # If the index variables only iterate over a subset of the kernel + # numels, then it must be broadcasted. + simplify = V.graph.sizevars.simplify + return any( + simplify(idx_range) != simplify(iter_range) # type: ignore[arg-type] + for idx_range, iter_range in zip( + index_numels, (tree.numel for tree in active_trees) + ) + ) + + def index_to_str(self, index: sympy.Expr) -> str: + """ + Convert an index expr to a string that can be used in output code. + e.g. a sympy expression "s2" may actually appear as "ks1" in the generated kernel. + + Index expressions often need to be passed in as arguments to the triton kernel. + Rename_indexing and codegen_indexing keep track of the needed indices and add + new parameters to the function signature. + """ + if isinstance(index, list): + return f"[{', '.join(map(self.index_to_str, index))}]" + return self.kexpr(self.rename_indexing(index)) # type: ignore[call-arg] + + @staticmethod + def _should_precompute_size_expr(index: sympy.Expr) -> bool: + if ( + isinstance(index, (int, sympy.Symbol, sympy.Number)) + or index.is_number + or index.is_symbol + or index.is_integer is not True + ): + return False + + symbols = index.free_symbols + return ( + bool(symbols) + and all( + symbol_is_type( + s, + ( + SymT.SIZE, + SymT.UNBACKED_INT, + SymT.PRECOMPUTED_SIZE, + ), + ) + for s in symbols + ) + and sympy.count_ops(index) > _MAX_INLINE_PRECOMPUTABLE_SIZE_EXPR_OPS + ) + + def prepare_indexing( + self, + index: sympy.Expr, + ) -> sympy.Expr: + index = self.simplify_indexing(index) + index = sympy_subs(index, V.graph.sizevars.precomputed_replacements) + # if simple replacements didn't get rid of floor/ceil, try full subs + if len(index.atoms(sympy.floor)) or len(index.atoms(sympy.ceiling)): + index = index.subs(V.graph.sizevars.precomputed_replacements) + # last resort, if no range vars are in the expr, hoist it + # TODO instead of trying to blindly find complicated exprs, we should hoist the + # inputs/outputs sizes and strides, but at the time indexing is generated + # kernel inputs and outputs are not set yet, we'd need a deeper refactor + # to do it this way + + if len(index.atoms(sympy.ceiling)): + for a in index.atoms(sympy.ceiling): + # for nested exprs, atoms yields top level first (?) + # so if everything goes fine, lower level replacements will come up empty + symbols = a.free_symbols + if len(symbols) > 0 and all( + symbol_is_type(s, (SymT.SIZE, SymT.PRECOMPUTED_SIZE)) + for s in symbols + ): + replacements = {a: V.graph.sizevars.lookup_precomputed_size(a)} + index = sympy_subs(index, replacements) + + simp_index = self.simplify_indexing(index) + + singleton_replacements = {} + for tree in self.active_range_trees(): + if not V.graph.sizevars.statically_known_equals(tree.numel, 1): + continue + # Any active loop var ranging over a singleton extent is + # semantically equal to zero. Canonicalizing those symbols here is + # globally safe and lets degenerate tiles CSE identical loads/stores. + for symbol in tree.var_list: + singleton_replacements[symbol] = sympy.S.Zero + if singleton_replacements: + simp_index = sympy_subs(simp_index, singleton_replacements) + + # Now that we are done simplifying we can unwrap Identity so downstream + # handling for its contained expression will work. In particular, + # backend index/mask analysis needs to recognize wrapped constants. + simp_index = ( + simp_index if not isinstance(simp_index, Identity) else simp_index.args[0] + ) + + if self._should_precompute_size_expr(simp_index): + simp_index = V.graph.sizevars.lookup_precomputed_size(simp_index) + + return self.codegen_indexing(simp_index) + + def active_range_trees(self) -> list[IterationRangesRoot]: + # Hide reduction trees outside reduction loops so indexing and mask + # generation only see axes active in the current stage. + return [ + t for t in self.range_trees if not t.is_reduction or self.inside_reduction + ] + + @contextlib.contextmanager + def use_range_trees( + self, range_trees: Sequence[IterationRangesRoot] + ) -> Iterator[None]: + """Temporarily codegen against an alternate range-tree family.""" + saved = self.range_trees + self.range_trees = list(range_trees) + # simplify_indexing depends on the active range trees, so swapping the + # tree family must invalidate any cached simplifications. + self.simplify_indexing.cache_clear() + try: + yield + finally: + self.range_trees = saved + self.simplify_indexing.cache_clear() + + def codegen_indexing(self, expr: sympy.Expr) -> sympy.Expr: + expr = V.graph.sizevars.simplify_with_ranges(expr, self.var_ranges()) + for sym in sorted(expr.free_symbols, key=str): + if sym in self.range_tree_nodes: + # if indexing expression is complicated, we precompute it on the host side + # and send the result as a kernel argument + replacements = {} + for ps in self.range_tree_nodes[sym].precomputed_args(): # type: ignore[index] + replacements[ps] = V.graph.sizevars.lookup_precomputed_size(ps) + if len(replacements) > 0: + self.range_tree_nodes[sym].expr = sympy_subs( # type: ignore[index] + self.range_tree_nodes[sym].expr, + replacements, # type: ignore[index] + ) + self.range_tree_nodes[sym].codegen() # type: ignore[index] + return expr + + def codegen_nan_check(self) -> None: + raise NotImplementedError("NYI: codegen_nan_check") + + def iteration_ranges_codegen_header( + self, + entry: IterationRangesRoot, + code: IndentedBuffer, + ) -> None: + raise NotImplementedError("NYI: iteration_ranges_codegen_header") + + def deallocate_workspaces(self): + wrapper = V.graph.wrapper_code + for ws in reversed(self.args.workspace_args): + wrapper.generate_workspace_deallocation(ws) + + def call_kernel( + self, name: str, node: IRNode | None = None, deallocate_ws: bool = True + ) -> None: + raise NotImplementedError("NYI: call_kernel") + + @contextlib.contextmanager + def mask_loads(self, mask: str | OpsWrapper, value: int | float) -> Iterator[str]: + """Context manager to add an additional mask to tl.load/store""" + prior = self._load_mask + prior_val = self._load_other + if prior: + mask = ops.logical_and(mask, prior) + + mask = OpsWrapper._unwrap(mask) + self._load_mask = mask + self._load_other = value + try: + # TODO(jansel): do we need a reshape here? + yield mask + finally: + self._load_mask = prior + self._load_other = prior_val + + def get_strides_of_load(self, index: sympy.Expr) -> dict[sympy.Symbol, sympy.Expr]: + """ + This gets the stride of the index for each of the tiling variables + (technically, it does it at index 0) + + For example, if + xindex = x0 + 512*x1 + 1024*r0 + x0 = (xindex//512) + x1 = (xindex % 512) + r0 = rindex // 1024 + + this function would return + {xindex: 512, rindex: 1024} + """ + index_to_tile_indexes = {k: v.expr for k, v in self.range_tree_nodes.items()} + index_in_tile_vars = sympy_subs(index, index_to_tile_indexes) # type: ignore[arg-type] + strides = {} + for range_tree in self.range_trees: + s = sympy_index_symbol(range_tree.name) + strides[s] = sympy_subs(index_in_tile_vars, {s: 1}) - sympy_subs( + index_in_tile_vars, {s: 0} + ) + return strides + + @staticmethod + def _map_tuple_or_scalar(fn, value): + if isinstance(value, tuple): + return tuple(map(fn, value)) + return fn(value) + + def estimate_flops(self) -> int | None: + flops = [ + node.estimate_flops() + for node in NodeScheduleMarker.only_nodes(self.features.node_schedule) + ] + return sum(filter(None, flops)) + + def estimate_kernel_num_bytes(self): + """ + Try the best to estimate the total size (in bytes) of the + kernel's inputs and outputs, which is used for estimating the memory + throughput of this kernel. This information is used for checking how + far we are from the peak memory bandwidth. It's important that + we want to avoid overestimating the sizes of the inputs and outputs, + because it can wrongfully give us a very large memory traffic value, + which may be even larger than the theoretical bandwidth and thus + become very misleading. This is particularly problematic for cases + where we slice some inputs. In those cases, we should only count + the size of the "slices" instead of the original inputs, because + only the slices contribute to the real memory traffic. + """ + nbytes = [] + ninplace_args = len(unique(self.args.inplace_buffers.values())) + _, call_args, _, _ = self.args.python_argdefs() + buf_accesses = self.features.buf_accesses() + + # For pointwise and reduction kernels, this is the upper-bound numels + # for the output buffer. + # FIXME: This is not exactly right for cases like below: + # def foo(tensor0, tensor1): + # x0 = narrow(tensor0) + # return cat(x0, tensor1) + # For this example, we will end up overestimate the size for the + # slice s0. Potentially, we could have precise inputs information + # if we maintained the original inputs of the Pointwise kernel created + # for the "cat". However, I think it might be a bit overwhelming that + # we add such complexity only for handling some particular cases for + # benchmarking. + out_numel = V.graph.sizevars.optimization_hint( + sympy_product(self.numels.values()) + ) + for i, arg in enumerate(call_args): + # "buf" may be narrowed. In this case, the number of memory accesses + # should be estimated based on the reinterpreted layout. + # On the other hand, buf may be broadcasted. In this case, + # counting the size of the underline storage would give us + # a better estimation in terms of memory accesses. + if arg not in buf_accesses: + nbytes.append(0) + continue + arg_numel = V.graph.get_numel(arg) + buf_size = V.graph.sizevars.optimization_hint(arg_numel) + if buf_size > out_numel: + # This arg points to a buf that has been sliced. + # We need to count each individual slice to have + # a better estimation. + indices = OrderedSet[Any]() + no_index_dep_count = 0 + for dep in buf_accesses[arg]: + if isinstance(dep, (StarDep, WeakDep)): + indices.add(f"no_index_dep_{no_index_dep_count}") + no_index_dep_count += 1 + else: + indices.add(dep.index) + numel = len(indices) * out_numel + else: + numel = buf_size + dtype = V.graph.get_dtype(arg) + dtype_size = get_dtype_size(dtype) + # pyrefly: ignore [bad-argument-type] + nbytes.append(numel * dtype_size * (1 + int(i < ninplace_args))) + return sum(nbytes) + + def warn_mix_layout(self, kernel_name): + """ + Print message if the kernel have mixed layout inputs. + Only care about 4D tensor for now. + """ + if ( + len(self.args.input_buffers) == 1 + and len(self.args.output_buffers) == 1 + and len(self.args.inplace_buffers) == 0 + ): + # even if input buffer and output buffer have different layout, + # this can be a layout conversion kernel. No need to warn for + # the mix layouts. + return + + argdefs, call_args, _signature, _ = self.args.python_argdefs() + uniform_stride_order = None + # pyrefly: ignore [bad-assignment] + for arg_name in call_args: + buf = V.graph.try_get_buffer(arg_name) + if not buf: + continue + layout = buf.get_layout() + if len(layout.size) == 4: + # ignore the tensor if only 1 dimension is non-zero + if len([x for x in layout.size if x == 1]) == 3: + continue + stride_order = ir.get_stride_order(layout.stride) + if uniform_stride_order is None: + uniform_stride_order = stride_order + elif uniform_stride_order != stride_order: + msg = yellow_text( + f"Expected stride order {uniform_stride_order}, but found stride order" + + f" {stride_order} for kernel {kernel_name}" + ) + log.warning(msg) + + stride_order_list = [ + ir.get_stride_order( + V.graph.get_buffer(name).get_layout().stride + ) + if V.graph.try_get_buffer(name) + else None + for name in call_args + ] + size_list = [ + V.graph.get_buffer(name).get_layout().size + if V.graph.try_get_buffer(name) + else None + for name in call_args + ] + source_list = [ + "GraphInput" + if name in V.graph.graph_inputs + else "IntermediateBuffer" + if name in V.graph.name_to_buffer + else None + for name in call_args + ] + + argdef_names = [x.name for x in argdefs] + msg = yellow_text( + f" param names {argdef_names}\n buf names {call_args}\n strides {stride_order_list}" + + f"\n sizes {size_list}\n sources {source_list}\n" + ) + log.warning(msg) + return + msg = green_text( + f"All the inputs for the triton kernel {kernel_name} have uniform layout" + ) + log.warning(msg) + + def welford_reduce_fallback(self, dtype, value): + sum_ = ops.reduction(dtype, dtype, "sum", value) + self.inside_reduction = False + rnumel = ops.index_expr(self.features.reduction_numel, dtype) + mean = ops.truediv(sum_, rnumel) + + self.inside_reduction = True + dx = ops.sub(value, mean) + dx2 = ops.mul(dx, dx) + m2 = ops.reduction(dtype, dtype, "sum", dx2) + return OpsWrapper._unwrap((mean, m2, rnumel)) + + def prepare_softmax_twopass_fallback(self, dtype, value): + vmax = ops.reduction(dtype, dtype, "fmax", value) + sub = ops.sub(value, vmax) + exp = ops.exp(sub) + vsum = ops.reduction(dtype, dtype, "sum", exp) + return OpsWrapper._unwrap((vmax, vsum)) + + def codegen_kernel(self): + raise NotImplementedError + + def codegen_body(self): + pass + + def codegen_iteration_ranges_entry(self, entry: IterationRangesEntry): + pass + + +@dataclasses.dataclass(frozen=True) +class _IterationSpace: + """Source domain used to remap a pointwise body. + + ``groups`` are source-domain extents. ``values`` are the matching + codegen-side symbolic index expressions in the outer kernel. + + For a grouped reduction body with logical ranges [B, D // G, G], + ``groups`` may be [B, D // G, G] while ``values`` are the concrete + symbols the parent kernel is using for those coordinates. + """ + + groups: Sequence[sympy.Expr] + values: Sequence[sympy.Expr] + + +@dataclasses.dataclass +class _DerivedIterationFamily: + """Iteration family for a nested-reduction consumer stage. + + Two configurations: + - reduced-output: swaps in a derived grouped-axis tree; ``index_subs`` + rewrites body vars to the active tree symbols + - parent-full: reuses outer trees; store_cache values are broadcast-lifted + lazily through CSE when needed + """ + + # Trees to swap onto the kernel while this stage runs + range_trees: tuple[IterationRangesRoot, ...] + # Rewrite body iter-var symbols to derived tree symbols (reduced-output) + index_subs: dict[sympy.Symbol, sympy.Expr] = dataclasses.field(default_factory=dict) + _headers_emitted: bool = False + + def remap_index(self, index: sympy.Expr) -> sympy.Expr: + return index.subs(self.index_subs) + + def is_active_on(self, kernel: SIMDKernel[Any]) -> bool: + if len(kernel.range_trees) != len(self.range_trees): + return False + return all( + active is expected + for active, expected in zip(kernel.range_trees, self.range_trees) + ) + + @contextlib.contextmanager + def ensure_active(self, kernel: SIMDKernel[Any]): + """Activate this family if it isn't already active on ``kernel``.""" + if self.is_active_on(kernel): + yield + else: + with self.activate(kernel): + yield + + def ensure_headers(self, kernel: SIMDKernel[Any]) -> None: + # Called lazily from activate(). Reduced-output families may activate + # more than once (the grouped reduction stores through the family, then + # reduced-output epilogues run inside it), so emit derived headers once. + # Parent-full families reuse the outer trees, so this stays a no-op. + if self._headers_emitted: + return + for tree in self.range_trees: + if isinstance(tree, DerivedIterationRangesRoot): + # Looped derived trees depend on the current reduction-loop + # offset, so emit them in the loop-local indexing buffer. + # Non-looped trees can be emitted once in the kernel prologue. + emit_in_loop_body = tree.is_loop and kernel.inside_reduction + target = kernel.indexing_code if emit_in_loop_body else kernel.body + kernel.iteration_ranges_codegen_header(tree, target) + self._headers_emitted = True + + @contextlib.contextmanager + def activate(self, kernel: SIMDKernel[Any]) -> Iterator[None]: + # Temporarily switch the kernel's active iteration family so normal + # load/store/indexing code interprets indices in this family's space. + self.ensure_headers(kernel) + with kernel.use_range_trees(self.range_trees): + yield + + +@dataclasses.dataclass(frozen=True) +class _GroupedReductionVars: + """Variables used to call the grouped-reduction body. + + ``iter_remapped`` and ``reduce_remapped`` are the iteration/reduction + arguments passed to the grouped reduction's loop body. ``passthrough`` is + the non-grouped axis, while ``group_index`` and ``local_reduction`` are + the two pieces of the grouped parent axis after it is split into + [num_groups, local_reduction_size]. ``group_index_var`` is None only for + the single-group case, where the group index is the constant 0. + """ + + iter_remapped: list[sympy.Expr] + reduce_remapped: list[sympy.Expr] + passthrough_iter_var: sympy.Symbol + group_index_var: sympy.Symbol | None + group_index_expr: sympy.Expr + local_reduction_var: sympy.Expr + + +@dataclasses.dataclass(frozen=True) +class _GroupedReductionLayout: + """Geometry of the grouped reduction (the consumer reduction in a + nested-reduction pair). Describes how the outer kernel's tile is + reshaped into [num_groups, local_reduction_size], which axis is reduced, + and how reduced values are lifted back for epilogues. + """ + + x_tree: IterationRangesRoot + r_tree: IterationRangesRoot + local_reduction_size: sympy.Integer + local_reduction_in_r: bool + + @classmethod + def from_kernel( + cls, + kernel: SIMDKernel[Any], + local_reduction_size: sympy.Integer, + local_reduction_in_r: bool, + ) -> _GroupedReductionLayout: + if len(kernel.range_trees) != 2: + raise AssertionError( + f"expected exactly 2 range trees, got {len(kernel.range_trees)}" + ) + x_tree, r_tree = kernel.range_trees + if x_tree.prefix != "x": + raise AssertionError(f"expected x range tree, got {x_tree.prefix!r}") + return cls( + x_tree=x_tree, + r_tree=r_tree, + local_reduction_size=local_reduction_size, + local_reduction_in_r=local_reduction_in_r, + ) + + @property + def group_tree(self) -> IterationRangesRoot: + """The tree decomposed into [num_groups, local_reduction_size].""" + return self.r_tree if self.local_reduction_in_r else self.x_tree + + @property + def passthrough_tree(self) -> IterationRangesRoot: + """The tree that passes through unchanged (not grouped).""" + return self.x_tree if self.local_reduction_in_r else self.r_tree + + @property + def parent_axis(self) -> int: + # Axis of the grouped parent dimension within the 2D [x, r] tile. + return 1 if self.local_reduction_in_r else 0 + + @property + def group_prefix(self) -> str: + return "nested_" + self.group_tree.prefix.upper().removesuffix("_") + + @property + def local_reduction_size_sym(self) -> sympy.Symbol: + return sympy.Symbol( + f"{self.group_prefix}_LOCAL_REDUCTION_SIZE", + integer=True, + positive=True, + ) + + @property + def reduced_block_sym(self) -> sympy.Symbol: + return sympy.Symbol( + f"{self.group_prefix}_REDUCED_BLOCK", + integer=True, + positive=True, + ) + + @property + def parent_block(self) -> str: + return self.group_tree.block_size_str() + + @property + def passthrough_block(self) -> str: + return self.passthrough_tree.block_size_str() + + @property + def num_groups(self) -> sympy.Expr: + return FloorDiv(self.group_tree.numel, self.local_reduction_size) + + @property + def num_groups_str(self) -> str: + return str(self.reduced_block_sym) + + @property + def local_reduction_size_dim(self) -> str: + return str(self.local_reduction_size_sym) + + @property + def reshape_shape(self) -> tuple[str, str, str]: + """Shape used before the local group reduction.""" + if self.local_reduction_in_r: + return ( + self.passthrough_block, + self.num_groups_str, + self.local_reduction_size_dim, + ) + return ( + self.num_groups_str, + self.local_reduction_size_dim, + self.passthrough_block, + ) + + @property + def reduce_axis(self) -> int: + """Axis reduced in [passthrough, num_groups, local_reduction_size].""" + return 2 if self.local_reduction_in_r else 1 + + @property + def output_shape(self) -> tuple[str, str]: + if self.local_reduction_in_r: + return (self.passthrough_block, self.num_groups_str) + return (self.num_groups_str, self.passthrough_block) + + def construct_group_reduction_vars( + self, + body: Any, + ) -> _GroupedReductionVars: + if V.graph.sizevars.statically_known_equals(self.num_groups, 1): + # Degenerate grouped axis: the parent dimension is exactly one + # group. Reuse the parent full-range symbol for the group lane so + # remapped shared-input loads CSE with the outer-reduction load. + group_index_expr = sympy.S.Zero + group_index_var = None + local_reduction_var = self.group_tree.full_range().symbol() + else: + group_index_var, local_reduction_var = self.group_tree.construct( + [self.num_groups, self.local_reduction_size] + ) + group_index_expr = group_index_var + # The passthrough axis is not split; it is reconstructed as a single + # loop variable so the grouped body can still address the unchanged + # parent-tile dimension. + passthrough_var = self.passthrough_tree.construct( + [self.passthrough_tree.numel] + )[0] + + reduce_remapped = [local_reduction_var] + if len(body.iter_vars) == 2: + iter_remapped = ( + [passthrough_var, group_index_expr] + if self.local_reduction_in_r + else [group_index_expr, passthrough_var] + ) + elif len(body.iter_vars) == 1: + # 1 iter var: flatten passthrough_tree and group index into one index. + iter_remapped = [ + passthrough_var * self.num_groups + group_index_expr + if self.local_reduction_in_r + else group_index_expr * self.passthrough_tree.numel + passthrough_var + ] + else: + raise AssertionError("nested grouped reduction expects 1 or 2 iter vars") + + return _GroupedReductionVars( + iter_remapped, + reduce_remapped, + passthrough_var, + group_index_var, + group_index_expr, + local_reduction_var, + ) + + def make_reduced_output_family( + self, + group_reduction_vars: _GroupedReductionVars, + ) -> _DerivedIterationFamily: + def build(tree: IterationRangesRoot) -> IterationRangesRoot: + if tree is not self.group_tree: + # Only the grouped axis changes shape in the reduced-output + # family. Reuse the passthrough tree directly so we do not emit + # duplicate index/mask headers like reduced_xindex = xindex. + return tree + local_reduction_size_const = ( + self.local_reduction_size_sym, + self.local_reduction_size, + True, + ) + reduced_block_const = ( + self.reduced_block_sym, + FloorDiv(tree.block_size(), self.local_reduction_size_sym), + True, + ) + return DerivedIterationRangesRoot( + tree, + numel=FloorDiv(tree.numel, self.local_reduction_size), + block_size=self.reduced_block_sym, + block_offset=FloorDiv( + tree.block_offset(), self.local_reduction_size_sym + ), + named_constants=(local_reduction_size_const, reduced_block_const), + ) + + reduced_x_tree = build(self.x_tree) + reduced_r_tree = build(self.r_tree) + index_subs: dict[sympy.Symbol, sympy.Expr] = {} + reduced_passthrough_tree = ( + reduced_x_tree if self.local_reduction_in_r else reduced_r_tree + ) + reduced_group_tree = ( + reduced_r_tree if self.local_reduction_in_r else reduced_x_tree + ) + index_subs[group_reduction_vars.passthrough_iter_var] = ( + reduced_passthrough_tree.full_range().symbol() + ) + if group_reduction_vars.group_index_var is not None: + # The single-group case uses constant 0 for the group lane, so + # there is no constructed group-index symbol to rewrite. + index_subs[group_reduction_vars.group_index_var] = ( + reduced_group_tree.full_range().symbol() + ) + return _DerivedIterationFamily( + index_subs=index_subs, + range_trees=(reduced_x_tree, reduced_r_tree), + ) + + def make_parent_full_family( + self, + ) -> _DerivedIterationFamily: + return _DerivedIterationFamily( + range_trees=(self.x_tree, self.r_tree), + ) + + def parent_full_iteration_values( + self, group_reduction_vars: _GroupedReductionVars + ) -> _IterationSpace: + if not self.local_reduction_in_r: + source_groups = [ + self.num_groups, + self.local_reduction_size, + self.passthrough_tree.numel, + ] + source_values = [ + group_reduction_vars.group_index_expr, + group_reduction_vars.local_reduction_var, + group_reduction_vars.passthrough_iter_var, + ] + return _IterationSpace( + source_groups, + source_values, + ) + return _IterationSpace( + [self.x_tree.numel, self.r_tree.numel], + [self.x_tree.full_range().symbol(), self.r_tree.full_range().symbol()], + ) + + def maybe_broadcast_value_to_parent_resolution( + self, + kernel: TritonKernel, + value: CSEVariable, + ) -> CSEVariable: + if value.dtype is None: + raise AssertionError("value must have a known dtype") + if value.shape is None or len(value.shape) < 2: + # Some scalar or opaque CSE values do not carry block-shape + # metadata. Pointwise consumers can still rely on Triton + # broadcasting, unlike grouped-reduction reshape inputs. + return value + + return self._broadcast_value_to_parent_resolution( + kernel, + value, + materialize_singleton=False, + ) + + def ensure_parent_tile_resolution( + self, + kernel: TritonKernel, + value: CSEVariable, + ) -> CSEVariable: + if value.dtype is None: + raise AssertionError("value must have a known dtype") + if not (value.shape is not None and len(value.shape) >= 2): + raise AssertionError( + "grouped reduction input must have a known parent-tile shape" + ) + + return self._broadcast_value_to_parent_resolution( + kernel, + value, + materialize_singleton=True, + ) + + def _broadcast_value_to_parent_resolution( + self, + kernel: TritonKernel, + value: CSEVariable, + *, + materialize_singleton: bool, + ) -> CSEVariable: + if value.dtype is None: + raise AssertionError("value must have a known dtype") + if not (value.shape is not None and len(value.shape) >= 2): + raise AssertionError("value must have a known parent-tile shape") + parent_dim = str(value.shape[self.parent_axis]) + if parent_dim == self.parent_block or ( + parent_dim == "1" and not materialize_singleton + ): + return value + + passthrough_extent = self.passthrough_block + parent_extent = self.parent_block + if parent_dim == "1": + # A parent-axis singleton already broadcasts semantically, but the + # grouped reduction still needs a full parent tile before reshape. + if self.local_reduction_in_r: + pre_broadcast_shape = (passthrough_extent, 1) + broadcast_shape = (passthrough_extent, parent_extent) + final_shape = (passthrough_extent, parent_extent) + else: + pre_broadcast_shape = (1, passthrough_extent) + broadcast_shape = (parent_extent, passthrough_extent) + final_shape = (parent_extent, passthrough_extent) + elif self.local_reduction_in_r: + num_groups = self.num_groups_str + local_reduction_size = self.local_reduction_size_dim + # [X, groups] -> [X, groups, 1] -> [X, groups, G] -> [X, R] + pre_broadcast_shape = (passthrough_extent, num_groups, 1) + broadcast_shape = (passthrough_extent, num_groups, local_reduction_size) + final_shape = (passthrough_extent, parent_extent) + else: + num_groups = self.num_groups_str + local_reduction_size = self.local_reduction_size_dim + # [groups, R] -> [groups, 1, R] -> [groups, G, R] -> [X, R] + pre_broadcast_shape = (num_groups, 1, passthrough_extent) + broadcast_shape = (num_groups, local_reduction_size, passthrough_extent) + final_shape = (parent_extent, passthrough_extent) + value = kernel.emit_broadcast_via_reshape( + value=value, + pre_broadcast_shape=pre_broadcast_shape, + broadcast_shape=broadcast_shape, + final_shape=final_shape, + dtype=value.dtype, + out_shape=final_shape, + ) + return value + + +@dataclasses.dataclass(frozen=True) +class _ParentFullLoadTransform: + """Lift loaded values to parent-full resolution when needed.""" + + kernel: TritonKernel + layout: _GroupedReductionLayout + + def apply(self, value: CSEVariable) -> CSEVariable: + return self.layout.maybe_broadcast_value_to_parent_resolution( + self.kernel, + value, + ) + + +class _GroupedReductionOpsHandler(WrapperHandler): # type: ignore[type-arg] + """Group-reduction stage handler: reshape parent-full tile into + [num_groups, local_reduction_size], reduce over the local axis, and store + the result. + Loads go through the normal CSE path, then may be lifted to parent + resolution before the reshape. + """ + + def __init__( + self, + inner, + kernel: TritonKernel, + *, + layout: _GroupedReductionLayout, + family: _DerivedIterationFamily, + load_transform: _ParentFullLoadTransform | None = None, + ): + super().__init__(inner) + self._kernel = kernel + self._layout = layout + self._family = family + self._load_transform = load_transform + + def load(self, name: str, index: sympy.Expr) -> CSEVariable: + value = self._inner.load(name, index) + if self._load_transform is not None: + # Used when a nested stage reads reduced values that must be lifted + # back to parent-tile resolution before this body consumes them. + value = self._load_transform.apply(value) + return value + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: str, + value: CSEVariable, + ) -> CSEVariable: + """Reshape the parent-full tile and reduce over the local reduction.""" + k = self._kernel + value = self._layout.ensure_parent_tile_resolution(k, value) + # The grouped-reduction reshape uses the grouped-axis named constants + # from the reduced-output family, so emit the derived headers before + # we materialize the reshape line. + self._family.ensure_headers(k) + reshaped = k.emit_reshape(value, self._layout.reshape_shape, src_dtype) + k.num_reduction += 1 + return k.emit_reduce( + reshaped, + reduction_type, + self._layout.reduce_axis, + dtype, + self._layout.output_shape, + ) + + def store_reduction(self, name: str, index: sympy.Expr, value: CSEVariable) -> None: + remapped_index = self._family.remap_index(index) + with self._family.ensure_active(self._kernel): + self._inner.store(name, remapped_index, value) + + +class _PointwiseRemapHandler(WrapperHandler): # type: ignore[type-arg] + """Pointwise bodies at a remapped iteration range. + + Unlike _GroupedReductionOpsHandler (which performs reshape+reduce), this + handler runs pure pointwise bodies for reduced/parent-full prologues + and epilogues. Loads use the normal CSE path after index remapping, then + may be lifted to parent resolution. + """ + + def __init__( + self, + inner, + kernel: SIMDKernel, + *, + family: _DerivedIterationFamily, + load_transform: _ParentFullLoadTransform | None = None, + ): + super().__init__(inner) + self._kernel = kernel + self._family = family + self._load_transform = load_transform + + def load(self, name: str, index: sympy.Expr) -> CSEVariable: + remapped_index = self._family.remap_index(index) + with self._family.ensure_active(self._kernel): + value = self._inner.load(name, remapped_index) + if self._load_transform is not None: + value = self._load_transform.apply(value) + return value + + def store( + self, + name: str, + index: sympy.Expr, + value: CSEVariable, + mode: Any = None, + ) -> None: + k = self._kernel + remapped_index = self._family.remap_index(index) + with self._family.ensure_active(k): + self._inner.store(name, remapped_index, value, mode=mode) + + +class SIMDScheduling(BaseScheduling): + """ + Single Instruction Multiple Data parent class used for fusion across + multiple different backends. + """ + + kernel_type: type[Any] = SIMDKernel # override in subclass + + def group_fn(self, sizes): + return tuple(V.graph.sizevars.simplify(sympy_product(s)) for s in sizes) + + def can_fuse(self, node1, node2): + """ + Hook called by Scheduler to determine if the Triton backend + can fuse node1 and node2. These nodes might already be + FusedSchedulerNodes. + """ + if isinstance(node1, scheduler.ForeachKernelSchedulerNode) or isinstance( + node2, scheduler.ForeachKernelSchedulerNode + ): + return scheduler.ForeachKernelSchedulerNode.can_fuse(node1, node2) + + _, (numel1, rnumel1) = node1.group + _, (numel2, rnumel2) = node2.group + why = WhyNoFuse(node1, node2) + + if node1.is_split_scan() and not node2.is_split_scan(): + if node2.is_reduction(): + why("Split scan cannot fuse with reductions") + return False + elif node2.is_split_scan() and not node1.is_split_scan(): + if node1.is_reduction(): + why("Split scan cannot fuse with reductions") + return False + + if node1.is_reduction() and node2.is_reduction(): + reduction_can_fuse = numel1 == numel2 and rnumel1 == rnumel2 + if not reduction_can_fuse: + from torch._inductor.scheduler import MixOrderReduction + + reduction_can_fuse = MixOrderReduction.can_fuse(node1, node2) + + if not reduction_can_fuse: + # Scheduler legality creates the fused nested node, but SIMD + # still runs this backend fusion gate. The regular + # numel/rnumel checks reject nested reductions because the two + # reductions intentionally use different iteration spaces. + from torch._inductor.scheduler import NestedReduction + + reduction_can_fuse = NestedReduction._is_dependent_reduction_pair( + node1, node2 + ) and NestedReduction.can_fuse(node1, node2) + + if not reduction_can_fuse: + why( + "numel/rnumel mismatch (reduce) (%s, %s), (%s, %s)", + numel1, + numel2, + rnumel1, + rnumel2, + ) + + if reduction_can_fuse and ( + node1.is_native_matmul() or node2.is_native_matmul() + ): + # Ensure node1 is always the native matmul side + if not node1.is_native_matmul(): + node1, node2 = node2, node1 + + # 1. A native matmul node keeps its original loop order. + # For example: C[z,y,x] = torch.bmm(A[z,y,r], B[z,r,x]) keeps (z,y,x) order. + # (see simplify_and_reorder in ir.py) + # + # 2. Triton kernels with native matmul always tile loops as (z,y,x) + # (see get_tiling_and_scores in this file) + # + # 3. If a candidate node (node2) uses a different loop order (e.g., (z,x,y,r)), + # its tiling is incompatible with native matmul tiling (z,y,x,r). + # This means _split_iteration_ranges will fail, so these nodes should not be fused. + tiling = node1.get_tiling(numel1, rnumel1) + if not all( + SIMDKernel.is_compatible( + tiling.values(), n2.get_ranges(), reduction_numel=rnumel1 + ) + for n2 in node2.get_nodes() + ): + why("invalid loop order and tiling for native matmul") + return False + + return reduction_can_fuse + + if not node1.is_reduction() and not node2.is_reduction(): + if not (numel1 == numel2 and rnumel1 == rnumel2): + if not node2.is_template(): + why( + "numel/rnumel mismatch (non-reduce) (%s, %s), (%s, %s)", + numel1, + numel2, + rnumel1, + rnumel2, + ) + return False + else: + # prologue fusion input sizes differ from output group + # fuse so long as this node matches the group of existing prologue nodes + for node in node2.get_nodes(): + # don't need to check epilogue nodes for prologue fusion, break after template + if node.is_template(): + break + # we would have already restricted prologue from fusing if it had multiple + # uses, so it must be fusing into this node + if not node.used_buffer_names() & node1.get_buffer_names(): + continue + _, (pro_numel, pro_rnumel) = node.group + if not (numel1 == pro_numel and rnumel1 == pro_rnumel): + why( + "numel/rnumel mismatch prologue mismatch (%s, %s), (%s, %s)", + numel1, + pro_numel, + rnumel1, + pro_rnumel, + ) + return False + + for n in (node1, node2): + if n.is_template(): + return True + + # check for a bad combined tiling + tiling1 = node1.get_tiling(numel1, rnumel1) + tiling2 = node2.get_tiling(numel1, rnumel1) + tiling3 = self.select_tiling( + node1.get_nodes() + node2.get_nodes(), numel1, rnumel1 + ) + if config.triton.tiling_prevents_pointwise_fusion: + cond = True + if len(tiling1) > 2: + if len(tiling2) > 2: + cond = tiling1 == tiling2 == tiling3 + else: + cond = tiling1 == tiling3 + elif len(tiling2) > 2: + cond = tiling2 == tiling3 + if not cond: + why( + "tiling mismatch (%s, %s, %s)", + tiling1, + tiling2, + tiling3, + ) + return False + + return True + + if not node1.is_reduction() and node2.is_reduction(): + if not (rnumel1 == 1 and rnumel2 != 1): + raise AssertionError( + f"expected rnumel1 == 1 and rnumel2 != 1, " + f"got {rnumel1} and {rnumel2}" + ) + if numel1 == numel2 * rnumel2: + if not all( + SIMDKernel.is_compatible((numel2, rnumel2), n.get_ranges()) + for n in node1.get_nodes() + ): + why("nodes numel/rnumel incompatibility") + return False + if ( + config.triton.tiling_prevents_reduction_fusion + and not node1.is_template() + ): + is_reduction_tiling_valid = tuple( + node1.get_tiling(numel1, sympy.S.One).values() + ) in ( + (numel1, 1), + (numel2, rnumel2, 1), + ) + if not is_reduction_tiling_valid: + why("invalid tiling for reduction") + return is_reduction_tiling_valid + return True + + if numel1 != numel2: + why("nodes numel incompatibility") + return numel1 == numel2 + + if not node1.is_reduction() or node2.is_reduction(): + raise AssertionError( + "expected node1 to be a reduction and node2 not a reduction" + ) + # swap args to hit the case above + return self.can_fuse_horizontal(node2, node1) + + can_fuse_vertical = can_fuse + can_fuse_horizontal = can_fuse + + def generate_node_schedule(self, nodes, numel, rnumel): + node_schedule: list[Any] = [] + done = OrderedSet[scheduler.BaseSchedulerNode]() + # Writes with a reduced shape, meaning they are only present once the + # reduction loop has ended + not_ready_yet_nodes: OrderedSet[str] = OrderedSet() + current_loop_buffer_usage: OrderedSet[str] = OrderedSet() + maybe_split_index: int | None = None + + def fits_in_main_body(n): + _, (node_numel, node_rnumel) = n.group + return (node_numel == numel and node_rnumel == rnumel) or ( + node_numel == numel * rnumel and node_rnumel == 1 + ) + + def fits_outside_reduction(n): + _, (node_numel, node_rnumel) = n.group + return node_numel == numel and node_rnumel == 1 and rnumel != 1 + + def expect_improved_memory_usage(n): + for read in n.read_writes.reads: + if read.name in current_loop_buffer_usage: + return True + return False + + def schedule_node_in_loop(n): + done.add(n) + node_schedule.append(n) + current_loop_buffer_usage.update([x.name for x in n.read_writes.reads]) + + # A scan is modelled as a reduction in the scheduler but has a + # full sized output that can be used inside the loop body + if ( + n.is_reduction() + and isinstance(n, scheduler.SchedulerNode) + and isinstance(n.node, ir.ComputedBuffer) + and not isinstance(n.node.data, ir.Scan) + ): + not_ready_yet_nodes.add(n.get_name()) + else: # this node is available within the loop + current_loop_buffer_usage.update([x.name for x in n.read_writes.writes]) + + @contextlib.contextmanager + def end_current_reduction_loop(): + nonlocal maybe_split_index + if node_schedule and node_schedule[-1] is EnableReduction: + node_schedule.pop() + else: + node_schedule.append(DisableReduction) + if maybe_split_index: + node_schedule.insert(maybe_split_index, DisableReduction) + node_schedule.insert(maybe_split_index + 1, EnableReduction) + maybe_split_index = None + yield + node_schedule.append(EnableReduction) + not_ready_yet_nodes.clear() + current_loop_buffer_usage.clear() + + def requires_closing_previous_reduction(node, node_schedule): + if rnumel == 1: + return False + if not not_ready_yet_nodes & node.ancestors: + return False + if not ( + node_schedule + and not isinstance( + node_schedule[-1], (EnableReduction, DisableReduction) + ) + ): + raise AssertionError( + "expected non-empty node_schedule not ending in a reduction toggle" + ) + return bool(not_ready_yet_nodes) + + for node in nodes: + if node in done: + continue + done.add(node) + + if fits_in_main_body(node): + if requires_closing_previous_reduction(node, node_schedule): + with end_current_reduction_loop(): + pass # need to start a new reduction loop + + if current_loop_buffer_usage and not expect_improved_memory_usage(node): + # If we don't improve memory usage, then it is better to split into two loops + maybe_split_index = maybe_split_index or len(node_schedule) + else: + # Memory usage got improved, cancel the loop split + maybe_split_index = None + + schedule_node_in_loop(node) + elif fits_outside_reduction(node): + with end_current_reduction_loop(): + node_schedule.append(node) + else: + raise NotImplementedError( + f"unexpected group: ({numel}, {rnumel}) != {node.group[1]}" + ) + + return node_schedule + + def codegen_mix_order_reduction(self, node): + node1, node2 = node.node1, node.node2 + + # Make sure there are no producer/consumer relationship + if not ( + not (node1.ancestors & node2.get_operation_names()) + and not (node2.ancestors & node1.get_operation_names()) + ): + raise AssertionError("node1 and node2 must not be ancestors of each other") + + self._codegen_mix_order_reduction(node1, node2) + + def _split_mix_order_reduction_epilogue(self, node): + # TODO: do more validation here + nodes = node.get_nodes() + reductions = [] + epilogues = [] + for node in nodes: + if node.is_reduction(): + reductions.append(node) + else: + epilogues.append(node) + return reductions, epilogues + + def _generate_kernel_code_for_mix_order_reduction( + self, kernel_features, split_size, for_benchmark + ): + """ + for_benchmark: + True if the generated code is for benchmarking. We need make + sure benchmark harness code is generated. + """ + numel, rnumel = kernel_features.numel, kernel_features.reduction_numel + node_schedule = kernel_features.node_schedule + + kernel = self.create_kernel_choices( + kernel_features, + [{"x": numel, "r0_": rnumel}], + { + "features": kernel_features, + "tiling_scores": None, + "mix_order_reduction": True, + "override_persistent_reduction": True, + }, + )[0] + if not kernel.persistent_reduction: + raise AssertionError("expected kernel.persistent_reduction") + if not kernel.mix_order_reduction: + raise AssertionError("expected kernel.mix_order_reduction") + kernel.rsplit_size = split_size + self.codegen_node_schedule_with_kernel(node_schedule, kernel) + + # allocate workspace for this kernel + _, ws_name, ws_off = kernel.args.workspace( + len(kernel.saved_partial_accumulate) + * kernel.numels["r0_"] + * ((kernel.numels["x"] + kernel.rsplit_size - 1) // kernel.rsplit_size), + False, + dtype=torch.float, + ) + if ws_off != 0: + raise AssertionError(f"{ws_off=}") + with kernel: + kernel.codegen_body() + + stack = contextlib.ExitStack() + with V.set_kernel_handler(kernel), stack: + if for_benchmark: + stack.enter_context(config.patch(benchmark_kernel=True)) + src_code = kernel.codegen_kernel() + + if for_benchmark: + # only do this if we are doing benchmarking. + # When we are generating final code, the kernel name + # should be decided differently with node type, fx node name + # etc. + src_code = src_code.replace(str(Placeholder.KERNEL_NAME), "triton_") + return kernel, ws_name, src_code + + # pyrefly: ignore [bad-override] + def benchmark_codegened_module( + self, + mod, + n_spills_threshold=8, + node_names: OrderedSet[str] | None = None, + skip_perf_cache: bool = False, + ) -> tuple[float, str]: + raise NotImplementedError + + def _codegen_mix_order_reduction(self, node1, node2): + numel, rnumel = scheduler.MixOrderReduction.get_numel_rnumel(node1) + + def _pick_split_size(): + # the overridden has highest priority + if config.triton.mix_order_reduction_split_size is not None: + return config.triton.mix_order_reduction_split_size + + # heuristics based on number of SMs + device_prop = DeviceProperties.create(node1.get_device()) + num_sm = device_prop.multi_processor_count + estimated_num_splits = num_sm * 8 + + # split_size is decided based on hint. + # optimization_hint is fine here: the result is clamped to [16, 128], + # so any fallback value still produces a valid split size. + numel_hint = V.graph.sizevars.optimization_hint(numel) + split_size = max(last_power_of_2(numel_hint // estimated_num_splits), 16) + split_size = min(split_size, 128) + return split_size + + split_size = _pick_split_size() + + # pyrefly: ignore [bad-assignment] + metrics.codegen_mix_order_reduction += 1 + + # split epilogue out of node2 + node2_reductions, node2_epilogue = self._split_mix_order_reduction_epilogue( + node2 + ) + + converted_nodes = [] + for subnode in node2_reductions: + subnode.cancel_reduction_split() + converted = subnode.extract_pw_from_reduction() + converted.swap_pw_red_dimension() + converted_nodes.append(converted) + node_schedule = self.generate_node_schedule( + node1.get_nodes() + converted_nodes, numel, rnumel + ) + kernel_features = SIMDKernelFeatures(node_schedule, numel, rnumel) + + # The autotuning is skipped in deterministic mode + if ( + not torch._inductor.config.deterministic + and config.triton.mix_order_reduction_split_size is None + and ( + config.triton.mix_order_reduction_autotune_split_size + or config.max_autotune + or config.coordinate_descent_tuning + ) + ): + + def _bench(candidate_split_size): + _, _, src_code = self._generate_kernel_code_for_mix_order_reduction( + kernel_features, + split_size=candidate_split_size, + for_benchmark=True, + ) + mod = PyCodeCache.load(src_code) + ms, _ = self.benchmark_codegened_module(mod) + return ms + + split_size = CoordescTuner.autotune_single_field( + _bench, + split_size, + 8, + ) + + kernel, ws_name, src_code = self._generate_kernel_code_for_mix_order_reduction( + kernel_features, + split_size=split_size, + for_benchmark=False, + ) + + # rename intermediate reduction output to final reduction + # output + is_split_reduction = bool(node2_reductions[0].node._split_size) + rename = {} + if is_split_reduction: + for subnode in node2_reductions: + bufname = subnode.get_outputs()[0].node.get_name() + username = ( + subnode.get_outputs()[0] + .users[0] + .node.get_outputs()[0] + .node.get_name() + ) + rename[bufname] = username + if not self.scheduler: + raise AssertionError("expected self.scheduler to be set") + self.scheduler.removed_ops.add( + subnode.get_outputs()[0].users[0].node.get_name() + ) + V.graph.removed_buffers.add(bufname) + + for partial_accum in kernel.saved_partial_accumulate: + partial_accum.buffer_name = rename.get( + partial_accum.buffer_name, partial_accum.buffer_name + ) + + kernel_name = self.define_kernel(src_code, node_schedule, kernel) + kernel.kernel_name = kernel_name + kernel.code_hash = code_hash(src_code) + + with V.set_kernel_handler(kernel): + for node in kernel_features.scheduler_nodes(): + # No need to allocate buffer for split reduction + # since we are gonna to allocate workspace to store the + # intermediate reduction reduction + if node.get_outputs()[0].node.get_name() not in rename: + node.mark_run() + + V.graph.wrapper_code.make_comment("# Call mix order reduction kernel") + self.codegen_comment(node_schedule, None) + # workspace args is still needed after the call + kernel.call_kernel(kernel.kernel_name, deallocate_ws=False) + V.graph.removed_buffers |= kernel.removed_buffers + V.graph.inplaced_to_remove |= kernel.inplaced_to_remove + + # an extra round of reduction + if len(converted_nodes) != len(kernel.saved_partial_accumulate): + raise AssertionError( + f"expected len(converted_nodes) == " + f"len(kernel.saved_partial_accumulate), got " + f"{len(converted_nodes)} and {len(kernel.saved_partial_accumulate)}" + ) + nsplit = V.graph.wrapper_code.codegen_python_sizevar( + (numel + split_size - 1) // split_size + ) + for idx, partial_accum in enumerate(kernel.saved_partial_accumulate): + buffer_name = partial_accum.buffer_name + + stride_str = f"({nsplit}) * ({rnumel})" + start = f"{idx} * {stride_str}" + end = f"({idx} + 1) * {stride_str}" + reduction_type2op = { + "min": "amin", + "max": "amax", + } + opname = reduction_type2op.get( + partial_accum.reduction_type, partial_accum.reduction_type + ) + final_reduce = f"{buffer_name} = {ws_name}[{start} : {end}].view({nsplit}, {rnumel}).{opname}(dim=0)" + + # Restore the exact original shape via .view() to handle keepdim + # and multi-dimensional reductions correctly. + buffer = V.graph.get_buffer(buffer_name) + if buffer is not None: + final_shape = [ + V.graph.wrapper_code.codegen_python_sizevar(s) + for s in buffer.get_layout().size + ] + final_shape_str = f"[{', '.join(final_shape)}]" + final_reduce += f".view({final_shape_str})" + + # The workspace tensor is in torch.float, need a cast if the buffer is + # not. + if (buffer_dtype := V.graph.get_dtype(buffer_name)) != torch.float: + final_reduce += f".to({buffer_dtype})" + V.graph.wrapper_code.writeline(final_reduce) + # mark the buffer as allocated, so we don't try to allocate + # it again when it's later used + V.graph.wrapper_code.allocated.add(buffer_name) + + kernel.deallocate_workspaces() + + if node2_epilogue: + self._codegen_nodes(node2_epilogue) + + self.free_buffers_in_scheduler() + + def codegen_nested_reduction(self, node): + """ + Generate a single kernel with an outer reduction, a group + reduction, and optional reduced/parent-full epilogues for + dependent cross-axis reductions that share a large input. + + The local group may split either parent tree. For example, + group-in-R reshapes [XBLOCK, RBLOCK] into [XBLOCK, RBLOCK/G, G], + while group-in-X reshapes it into [XBLOCK/G, G, RBLOCK]. + """ + outer_node, grouped_node = node.node1, node.node2 + _, (outer_numel, outer_rnumel) = outer_node.group + _, (grouped_numel, grouped_rnumel) = grouped_node.group + local_reduction_size = node.group_size + local_reduction_in_r = ( + node.grouped_axis is scheduler.NestedReduction.GroupedAxis.R + ) + local_reduction_size_hint = int(local_reduction_size) + nested_pointwise_domains = ( + scheduler.NestedReduction._classify_nested_pointwise_nodes( + outer_node, + grouped_node, + node.domain_context, + ) + ) + if nested_pointwise_domains is None: + raise AssertionError("expected nested pointwise domains to be classified") + pointwise_domain_by_node: dict[ + BaseSchedulerNode, scheduler.NestedReduction.PointwiseDomain + ] = dict(nested_pointwise_domains) + local_reduction_domain = ( + scheduler.NestedReduction.PointwiseDomain.LOCAL_REDUCTION_INPUT + ) + outer_local_reduction_pointwise = [ + sn + for sn, domain in nested_pointwise_domains + if sn in outer_node.get_nodes() and domain is local_reduction_domain + ] + outer_local_reduction_pointwise_set = OrderedSet( + outer_local_reduction_pointwise + ) + outer_codegen_nodes = [ + sn + for sn in outer_node.get_nodes() + if sn not in outer_local_reduction_pointwise_set + ] + grouped_reduction: scheduler.SchedulerNode = node.grouped_reduction + grouped_schedule: list[NodeScheduleEntry] = self.generate_node_schedule( + grouped_node.get_nodes(), + grouped_numel, + grouped_rnumel, + ) + if not any(sn is grouped_reduction for sn in grouped_schedule): + raise AssertionError("grouped reduction must appear in grouped schedule") + grouped_reduction_body = grouped_reduction._body + + combined_schedule = self.generate_node_schedule( + outer_codegen_nodes, + outer_numel, + outer_rnumel, + ) + coalesce_analysis = ( + outer_node.get_coalesce_analysis() + if torch._inductor.config.triton.coalesce_tiling_analysis + else None + ) + kernel_features = SIMDKernelFeatures( + combined_schedule, + outer_numel, + outer_rnumel, + coalesce_analysis, + ) + # The outer reduction owns the grid and persistent/tiling choice. The + # grouped reduction is emitted inside that tile, so its accesses do not + # feed these heuristics yet. + tiling, tiling_score = self.get_tiling_and_scores( + combined_schedule, + outer_numel, + outer_rnumel, + coalesce_analysis, + ) + if "y" in tiling or "z" in tiling: + raise AssertionError("nested reduction does not support tiled reductions") + + metrics.codegen_nested_reduction += 1 + kernel_kwargs: dict[str, Any] = { + "features": kernel_features, + "override_cooperative_reduction": False, + "tiling_scores": tiling_score, + } + kernel = cast( + "TritonKernel", + self.create_kernel_choices( + kernel_features, + [tiling], + kernel_kwargs, + )[0], + ) + + if local_reduction_in_r: + kernel.min_rblock = local_reduction_size_hint + else: + kernel.min_xblock = local_reduction_size_hint + + # Emit the first stage through the normal scheduler path so its loads, + # stores, CSE state, masks, and reduction setup are identical to an + # ordinary SIMD reduction kernel. Nested handlers append later stages. + self.codegen_node_schedule_with_kernel(combined_schedule, kernel) + + with kernel: + # Flush the outer reduction code: + # - Persistent: one pass, no loops + # - Looped: disable_reduction already flushed loop 1 + # and post-loop code, but pending buffers may still have the next + # pass. Flush it now so later nested stages can consume it. + kernel.codegen_body() + + layout: _GroupedReductionLayout = _GroupedReductionLayout.from_kernel( + kernel, + local_reduction_size, + local_reduction_in_r, + ) + group_reduction_vars: _GroupedReductionVars = ( + layout.construct_group_reduction_vars(grouped_reduction_body) + ) + reduced_output_family: _DerivedIterationFamily = ( + layout.make_reduced_output_family(group_reduction_vars) + ) + parent_full_family: _DerivedIterationFamily = ( + layout.make_parent_full_family() + ) + local_reduction_source: _IterationSpace = ( + self._local_reduction_iteration_values( + grouped_reduction_body, + group_reduction_vars.iter_remapped, + group_reduction_vars.reduce_remapped, + ) + ) + parent_full_source: _IterationSpace = layout.parent_full_iteration_values( + group_reduction_vars + ) + self._codegen_remapped_pointwise( + kernel, + outer_local_reduction_pointwise, + parent_full_family, + local_reduction_source, + load_transform=_ParentFullLoadTransform(kernel, layout), + ) + self._codegen_nested_grouped_schedule( + kernel, + grouped_schedule, + grouped_reduction, + layout, + group_reduction_vars.iter_remapped, + group_reduction_vars.reduce_remapped, + local_reduction_source, + parent_full_source, + pointwise_domain_by_node, + reduced_output_family, + parent_full_family, + ) + + kernel.codegen_body() + + self._finalize_nested_reduction_kernel( + kernel, + combined_schedule, + node, + [ + *combined_schedule, + *outer_local_reduction_pointwise, + *grouped_schedule, + ], + ) + + def _finalize_nested_reduction_kernel( + self, + kernel, + combined_schedule, + node, + config_patch_schedule=None, + ) -> None: + config_patches = self._collect_config_patches( + config_patch_schedule or combined_schedule + ) + with V.set_kernel_handler(kernel), config.patch(**config_patches): + src_code = kernel.codegen_kernel() + kernel.kernel_name = self.define_kernel( + src_code, + combined_schedule, + kernel, + ) + kernel.code_hash = code_hash(src_code) + + with V.set_kernel_handler(kernel): + for sn in node.get_nodes(): + sn.mark_run() + + base_scheduler_nodes = [ + node for node in combined_schedule if isinstance(node, BaseSchedulerNode) + ] + self._launch_kernel_and_cleanup(kernel, base_scheduler_nodes) + + def _codegen_nested_grouped_schedule( + self, + kernel, + grouped_schedule, + grouped_reduction: scheduler.SchedulerNode, + layout: _GroupedReductionLayout, + iter_remapped, + reduce_remapped, + local_reduction_source: _IterationSpace, + parent_full_source: _IterationSpace, + pointwise_domain_by_node: dict[ + BaseSchedulerNode, scheduler.NestedReduction.PointwiseDomain + ], + reduced_output_family, + parent_full_family, + ) -> None: + """Interpret the local reduction schedule with nested emitters. + + ``local_reduction_source`` is the pre-reduction domain, including the + local reduction lane. ``parent_full_source`` is the outer tile domain + used by pointwise consumers after reduced values are broadcast back. + """ + grouped_reduction_body = grouped_reduction._body + reduced_source = _IterationSpace( + [ + grouped_reduction_body.var_ranges[v] + for v in grouped_reduction_body.iter_vars + ], + iter_remapped, + ) + parent_full_load_transform = _ParentFullLoadTransform(kernel, layout) + for sn in grouped_schedule: + if sn in (DisableReduction, EnableReduction): + # These markers only control standalone reduction-loop + # emission. Nested codegen lowers the grouped reduction as a + # local reshape+reduce inside the outer kernel, so there is no + # grouped loop to close or reopen here. + continue + if not isinstance(sn, scheduler.SchedulerNode): + raise AssertionError(f"expected SchedulerNode, got {type(sn)}") + if sn is grouped_reduction: + self._codegen_grouped_reduction( + kernel, + sn, + layout, + iter_remapped, + reduce_remapped, + reduced_output_family, + ) + continue + domain = pointwise_domain_by_node.get(sn) + if domain is None: + raise AssertionError(f"no pointwise domain classified for {sn}") + if domain is scheduler.NestedReduction.PointwiseDomain.REDUCED: + self._codegen_remapped_pointwise( + kernel, + [sn], + reduced_output_family, + reduced_source, + ) + continue + elif ( + domain + is scheduler.NestedReduction.PointwiseDomain.LOCAL_REDUCTION_INPUT + ): + source = local_reduction_source + elif domain is scheduler.NestedReduction.PointwiseDomain.PARENT_FULL: + source = self._select_full_resolution_pointwise_source( + sn, + parent_full_source, + local_reduction_source, + ) + else: + raise AssertionError(f"unexpected nested pointwise domain: {domain}") + self._codegen_remapped_pointwise( + kernel, + [sn], + parent_full_family, + source, + load_transform=parent_full_load_transform, + ) + + def _select_full_resolution_pointwise_source( + self, + sn: scheduler.SchedulerNode, + parent_full_source: _IterationSpace, + local_reduction_source: _IterationSpace, + ) -> _IterationSpace: + sn_ranges = sn.get_ranges() + if self._ranges_exactly_match_groups(parent_full_source.groups, sn_ranges): + return parent_full_source + if self._ranges_exactly_match_groups(local_reduction_source.groups, sn_ranges): + return local_reduction_source + if SIMDKernel.is_compatible(parent_full_source.groups, sn_ranges): + return parent_full_source + if SIMDKernel.is_compatible(local_reduction_source.groups, sn_ranges): + return local_reduction_source + raise AssertionError( + f"unsupported full-resolution nested pointwise ranges: {sn_ranges}" + ) + + @staticmethod + def _ranges_exactly_match_groups( + groups: Sequence[sympy.Expr], + ranges: Sequence[Sequence[sympy.Expr]], + ) -> bool: + iter_ranges, reduction_ranges = ranges + return ( + not reduction_ranges + and len(iter_ranges) == len(groups) + and all( + V.graph.sizevars.statically_known_equals(iter_range, group) + for iter_range, group in zip(iter_ranges, groups) + ) + ) + + def _codegen_grouped_reduction( + self, + kernel, + grouped_reduction: scheduler.SchedulerNode, + layout: _GroupedReductionLayout, + iter_remapped, + reduce_remapped, + reduced_output_family, + ) -> None: + grouped_reduction_body = grouped_reduction._body + load_transform = _ParentFullLoadTransform(kernel, layout) + handler = _GroupedReductionOpsHandler( + V.get_ops_handler(), + kernel=kernel, + layout=layout, + family=reduced_output_family, + load_transform=load_transform, + ) + with V.set_ops_handler(handler), kernel.set_current_node(grouped_reduction): + grouped_reduction_body( + iter_remapped, + reduce_remapped, + allow_same_symbol_in_index=True, + ) + + @classmethod + def _map_iteration_values_to_node_sizes( + cls, + source: _IterationSpace, + lengths: Sequence[Sequence[sympy.Expr]], + ) -> list[list[sympy.Expr]]: + groups = source.groups + values = source.values + if len(groups) != len(values): + raise AssertionError( + f"groups/values length mismatch: {len(groups)} != {len(values)}" + ) + + def split_values_by_ranges( + *new_ranges: Sequence[sympy.Expr], + ) -> list[list[sympy.Expr]]: + return [ + decompose_index(value, ranges) + for value, ranges in zip(values, new_ranges) + ] + + return SIMDKernel.map_kernel_groups_to_node_sizes( + groups, + lengths, + split_values_by_ranges, + ) + + def _local_reduction_iteration_values( + self, + body, + iter_remapped, + reduce_remapped, + ) -> _IterationSpace: + body_vars = [*body.iter_vars, *body.reduce_vars] + groups = [body.var_ranges[v] for v in body_vars] + return _IterationSpace(groups, [*iter_remapped, *reduce_remapped]) + + def _codegen_remapped_pointwise( + self, + kernel, + pointwise_nodes, + family: _DerivedIterationFamily, + source: _IterationSpace, + *, + load_transform: _ParentFullLoadTransform | None = None, + ) -> None: + """Emit pointwise nodes under an explicit nested iteration family. + + `source` describes the coordinate space whose values are remapped into + each pointwise node's own loop ranges. + """ + with family.activate(kernel): + for sn in pointwise_nodes: + iter_vars, reduction_vars = self._map_iteration_values_to_node_sizes( + source, + sn.get_ranges(), + ) + if reduction_vars: + raise AssertionError( + f"pointwise node must have no reduction vars, got {reduction_vars}" + ) + handler = _PointwiseRemapHandler( + V.get_ops_handler(), + kernel=kernel, + family=family, + load_transform=load_transform, + ) + with V.set_ops_handler(handler), kernel.set_current_node(sn): + sn._body(iter_vars) + + def _codegen_nodes( + self, + nodes: Sequence[scheduler.SchedulerNode], + coalesce_analysis: CoalesceVarAnalysis | None = None, + ): + if not self.scheduler: + raise AssertionError("expected self.scheduler to be set") + nodes = [ + node for node in nodes if node.get_name() not in self.scheduler.removed_ops + ] + if not nodes: + return + _, (numel, rnumel) = max(nodes, key=lambda x: int(x.is_reduction())).group + + node_schedule = self.generate_node_schedule(nodes, numel, rnumel) + schedule_log.debug("Schedule:\n %s", node_schedule) + + return self.codegen_node_schedule( + SIMDKernelFeatures(node_schedule, numel, rnumel, coalesce_analysis) + ) + + def codegen_node( + self, node: scheduler.FusedSchedulerNode | scheduler.SchedulerNode + ): + """ + Given a set of pre-fused nodes, generate a SIMD kernel. + """ + if not self.scheduler: + raise AssertionError("expected self.scheduler to be set") + nodes = [ + node + for node in node.get_nodes() + if node.get_name() not in self.scheduler.removed_ops + ] + if len(nodes) == 0: + return + + if torch._inductor.config.triton.coalesce_tiling_analysis: + if len(nodes) != len(node.get_nodes()): + if not self.scheduler: + raise AssertionError("expected self.scheduler to be set") + node = scheduler.FusedSchedulerNode(self.scheduler, nodes) + coalesce_analysis = node.get_coalesce_analysis() + else: + coalesce_analysis = None + + return self._codegen_nodes(nodes, coalesce_analysis) # type: ignore[arg-type] + + @staticmethod + def can_use_32bit_indexing( + numel: sympy.Expr, + buffers: Iterable[ir.Buffer | ir.TensorBox | ir.TorchBindObject | ir.IRNode], + ) -> bool: + int_max = torch.iinfo(torch.int32).max + + if not expr_fits_within_32bit(numel): + return False + + # Any use of a MultiOutputLayout will create a buffer with a + # Layout whose sizes are accounted for + buf_sizes = [ + buf.get_layout().storage_size() + for buf in buffers + if buf.has_tensor_output() + ] + + for buf in buffers: + if not buf.has_tensor_output() and isinstance(buf, ir.MutationOutput): + mutated_bufs = buf.get_mutation_buffers() + buf_sizes += [ + buf.get_layout().storage_size() + for buf in mutated_bufs + if buf.has_tensor_output() + ] + + if not all(expr_fits_within_32bit(size) for size in buf_sizes): + return False + + # Only install guards for 32-bit indexing as there is no correctness + # issue with using 64-bit for everything + V.graph.sizevars.check_leq(numel, int_max) # type: ignore[arg-type] + for size in buf_sizes: + V.graph.sizevars.check_leq(size, int_max) # type: ignore[arg-type] + return True + + def process_kernel( + self, + kernel: Any, + node_schedule: list[NodeScheduleEntry], + only_gen_src_code: bool = False, + ) -> None: + """ + Process a kernel by generating code for its node schedule and updating graph state. + """ + self.codegen_node_schedule_with_kernel(node_schedule, kernel) + if not only_gen_src_code: + with V.set_kernel_handler(kernel): + for node in NodeScheduleMarker.only_nodes(node_schedule): + node.mark_run() + V.graph.removed_buffers |= kernel.removed_buffers + V.graph.inplaced_to_remove |= kernel.inplaced_to_remove + + def _collect_config_patches(self, node_schedule: list[Any]) -> dict[str, Any]: + """Collect and merge config_patches from all operations in the node schedule. + + This enables scoped config (e.g., coordinate_descent_tuning) for kernels + that contain decomposition operations. + """ + merged_patches: dict[str, Any] = {} + for node in node_schedule: + if isinstance(node, BaseSchedulerNode) and node.node is not None: + patches = node.node.get_config_patches() + if patches: + merged_patches.update(patches) + return merged_patches + + def codegen_node_schedule(self, kernel_features: SIMDKernelFeatures): + """ + Generate code for nodes in kernel_features + """ + node_schedule = kernel_features.node_schedule + + tiling, tiling_score = self.get_tiling_and_scores( + node_schedule, + kernel_features.numel, + kernel_features.reduction_numel, + kernel_features.coalesce_analysis, + ) + kernels = self.create_kernel_choices( + kernel_features, + [tiling], + {"features": kernel_features, "tiling_scores": tiling_score}, + ) + for kernel in kernels: + self.codegen_node_schedule_with_kernel(node_schedule, kernel) + MultiKernel.merge_workspaces_inplace(kernels) + + # Collect config_patches from operations (e.g., decomposition ops with + # coordinate_descent_tuning) and apply during kernel codegen + config_patches = self._collect_config_patches(node_schedule) + + for kernel in kernels: + with V.set_kernel_handler(kernel), config.patch(**config_patches): + src_code = kernel.codegen_kernel() + kernel_name = self.define_kernel(src_code, node_schedule, kernel) + log.debug("Generating kernel code with kernel_name: %s", kernel_name) + kernel.kernel_name = kernel_name + kernel.code_hash = code_hash(src_code) + del kernel + + final_kernel: SIMDKernel | MultiKernel + if len(kernels) > 1: + final_kernel = MultiKernel(kernels) + else: + (final_kernel,) = kernels + + with V.set_kernel_handler(final_kernel): + for node in kernel_features.scheduler_nodes(): + node.mark_run() + + # filter out NodeScheduleMarker + base_scheduler_nodes: list[BaseSchedulerNode] = [ + node for node in node_schedule if isinstance(node, BaseSchedulerNode) + ] + self._launch_kernel_and_cleanup( + final_kernel, + base_scheduler_nodes, + free_buffers=False, + ) + + if ( + V.graph.wrapper_code.supports_intermediate_hooks # type: ignore[has-type] + and config.generate_intermediate_hooks + ): + # Not every node in the schedule will actually be live on output; + # we can't check dead buffers. + live_outs = kernels[0].args.live_output_buffers() + for node in kernel_features.scheduler_nodes(): + name = node.get_name() + if name not in live_outs: + continue + if node.node is None: + raise AssertionError("expected node.node to not be None") + origin_node = node.node.get_origin_node() + if origin_node is not None: + counters["inductor"]["intermediate_hooks"] += 1 + V.graph.wrapper_code.writeline( + f"run_intermediate_hooks({origin_node.name!r}, {name})" + ) + + self.free_buffers_in_scheduler() + + def _launch_kernel_and_cleanup( + self, + kernel, + base_scheduler_nodes: list[BaseSchedulerNode], + *, + free_buffers: bool = True, + ) -> None: + self.codegen_comment(base_scheduler_nodes, kernel.kernel_name) + if config.cpp.enable_kernel_profile: + V.graph.wrapper_code.write_kernel_context_guard_begin() + if config.cpp.enable_kernel_profile and config.cpp.enable_kernel_context_guard: + V.graph.wrapper_code.write_kernel_context_guard( + kernel.kernel_name, + base_scheduler_nodes, + ) + kernel.call_kernel(kernel.kernel_name) + if config.cpp.enable_kernel_profile: + V.graph.wrapper_code.write_kernel_context_guard_end() + + if config.nan_asserts: + kernel.codegen_nan_check() + if config.warn_mix_layout: + kernel.warn_mix_layout(kernel.kernel_name) + + V.graph.removed_buffers |= kernel.removed_buffers + V.graph.inplaced_to_remove |= kernel.inplaced_to_remove + + if free_buffers: + self.free_buffers_in_scheduler() + + def create_kernel_choices( + self, kernel_features: SIMDKernelFeatures, kernel_args, kernel_kwargs + ) -> list[SIMDKernel]: + return [ + self.kernel_type( + *kernel_args, + **kernel_kwargs, + ) + ] + + def codegen_node_schedule_with_kernel(self, node_schedule, kernel): + with kernel: + stack = contextlib.ExitStack() + all_indexing = {} + + # First pass to collect indexing and decide inplace updates + for node in node_schedule: + if node is DisableReduction: + stack.enter_context(kernel.disable_reduction()) + elif node is EnableReduction: + stack.close() + else: + node.decide_inplace_update() + index_vars = kernel.split_and_set_ranges(node.get_ranges()) + all_indexing.update( + dict.fromkeys( + node._body.indexing_from_args(index_vars).values() + ) + ) + + kernel.finalize_indexing(all_indexing.keys()) + + # Second pass to do codegen + for node in node_schedule: + if node is DisableReduction: + stack.enter_context(kernel.disable_reduction()) + elif node is EnableReduction: + stack.close() + else: + # TODO - use split ranges ? + indexing_dtype_strength_reduction(node._body) + convert_index_expr_to_value_expr(node._body) + index_vars = kernel.split_and_set_ranges(node.get_ranges()) + node.codegen(index_vars) + + def _codegen_single_template( + self, + kernel, + render, + template_node, + epilogue_nodes, + prologue_nodes, + *, + only_gen_src_code=False, + ): + """ + Helper method to codegen a single template kernel variant + """ + buf_name_to_prologue_group = {} + template_reads = template_node.used_buffer_names() + prologue_group = [] + for prologue in prologue_nodes: + names = prologue.get_buffer_names() + prologue_group.append(prologue) + # this must be the end of a prologue group + if names & template_reads: + if len(names) != 1: + raise AssertionError(f"expected len(names) == 1, got {len(names)}") + buf_name_to_prologue_group[next(iter(names))] = prologue_group + kernel.prologue_fused_inputs.add(next(iter(names))) + prologue_group = [] + + # all prologue groups should have finalized with use in template + if len(prologue_group) != 0: + raise AssertionError( + f"expected empty prologue_group, got {len(prologue_group)}" + ) + + # Remove prologue-fused inputs from input_buffers so that + # remove_kernel_local_buffers can remove them. + for buf_name in kernel.prologue_fused_inputs: + kernel.args.input_buffers.pop(buf_name, None) + + # Dispatch to the kernel for source generation. TritonTemplateKernel + # handles the standard Triton path; ExternalTritonTemplateKernel + # handles external backends (e.g. Helion). + src_code = kernel.codegen_template_body( + self, + template_node, + epilogue_nodes, + prologue_nodes, + buf_name_to_prologue_group, + prologue_preserves_zero_mask, + render, + ) + + if config.benchmark_kernel: + num_gb = kernel.estimate_kernel_num_bytes() / 1e9 + src_code = ( + f"{kernel.imports_for_benchmark_kernel()}\n" + f"{src_code}\n" + f"{kernel.codegen_kernel_benchmark(num_gb).getvalue()}" + ) + + node_schedule = [*prologue_nodes, template_node, *epilogue_nodes] + + if only_gen_src_code: + return src_code + + # Unfused epilogues are codegen'd separately in call_kernel; + # exclude them from mark_run. + unfused_set = OrderedSet([id(n) for n in kernel.get_unfused_epilogues()]) + with V.set_kernel_handler(kernel): + template_node.mark_run() + for node in epilogue_nodes: + if id(node) not in unfused_set: + node.mark_run() + for node in prologue_nodes: + node.mark_run() + + kernel.kernel_name = self.define_kernel(src_code, node_schedule, kernel) + + return kernel + + def _get_multikernel_shapes( + self, node: MultiTemplateBuffer + ) -> tuple[tuple[int, ...], ...]: + from ..ir import IRNode + + def get_size(arg): + if not isinstance(arg, IRNode): + return None + if isinstance(arg, ir.BaseView): # triton templates want the base tensor. + arg = arg.unwrap_view() + if (size := arg.maybe_get_size()) is None: + return None + return tuple(s for s in size) + + out = [] + for arg in list(node.inputs) + [node]: + if isinstance(arg, (list, tuple)): + out.append(tuple(get_size(_arg) for _arg in arg)) + else: + out.append(get_size(arg)) + return tuple(out) + + def _kernel_has_dynamic_shapes(self, node: MultiTemplateBuffer) -> bool: + shapes = self._get_multikernel_shapes(node) + return any( + any( + isinstance(s, sympy.Expr) and not isinstance(s, sympy.Integer) + for s in shape + ) + for shape in shapes + ) + + def _make_shape_cache_key( + self, node: MultiTemplateBuffer, hint: int + ) -> tuple[tuple[int, ...], ...]: + """ + Returns cache key for hint-based multi-graph; key is tuple of shapes with hint filled in. + """ + shapes = self._get_multikernel_shapes(node) + return tuple( + tuple( + hint + if isinstance(s, sympy.Expr) and not isinstance(s, sympy.Integer) + else s + for s in shape + ) + for shape in shapes + ) + + def codegen_template( + self, + template_node, + epilogue_nodes, + prologue_nodes, + *, + only_gen_src_code=False, + hint_override: int | None = None, + ) -> str | None: + """ + Codegen a triton template with multi-kernel dispatch support + + If `only_gen_src_code=True` the src code will be returned instead of being + codegenned into the wrapper + """ + + _, (_numel, rnumel) = template_node.group + if rnumel != 1: + raise AssertionError(f"expected rnumel == 1, got {rnumel}") + + if ( + isinstance(template_node.node, MultiTemplateBuffer) + and template_node.node._make_kernel_renders + and len(template_node.node._make_kernel_renders) > 1 + and self._kernel_has_dynamic_shapes(template_node.node) + ): + kernels = {} + src_codes = [] + + for ( + size_hint, + make_kernel_render, + ) in template_node.node._make_kernel_renders.items(): + kernel, render = make_kernel_render( + template_node.node, hint_override=hint_override + ) + + if only_gen_src_code: + src_code = self._codegen_single_template( + kernel, + render, + template_node, + epilogue_nodes, + prologue_nodes, + only_gen_src_code=True, + ) + if not isinstance(src_code, str): + raise AssertionError( + f"expected src_code to be a str, got {type(src_code)}" + ) + # pyrefly: ignore [bad-argument-type] + src_codes.append(src_code) + else: + if size_hint is None: + continue # skip kernel generation based on real runtime value; only use hints + kernel = self._codegen_single_template( + kernel, + render, + template_node, + epilogue_nodes, + prologue_nodes, + only_gen_src_code=False, + ) + shape_cache_key = ( + None + if size_hint is None + else self._make_shape_cache_key(template_node.node, size_hint) + ) + # pyrefly: ignore [unsupported-operation] + kernels[shape_cache_key] = kernel + + if only_gen_src_code: + return "\n\n".join(src_codes) + + MultiKernel.merge_workspaces_inplace(list(kernels.values())) + multi_kernel = SizeHintMultiKernel(kernels) + node_schedule = [*prologue_nodes, template_node, *epilogue_nodes] + self.codegen_comment(node_schedule, multi_kernel.kernel_name) + multi_kernel.call_kernel(multi_kernel.kernel_name) + V.graph.removed_buffers |= multi_kernel.removed_buffers + V.graph.inplaced_to_remove |= multi_kernel.inplaced_to_remove + self.free_buffers_in_scheduler() + return None + else: + kernel, render = template_node.node.make_kernel_render( + template_node.node, hint_override=hint_override + ) + + if only_gen_src_code: + return self._codegen_single_template( + kernel, + render, + template_node, + epilogue_nodes, + prologue_nodes, + only_gen_src_code=True, + ) + else: + kernel = self._codegen_single_template( + kernel, + render, + template_node, + epilogue_nodes, + prologue_nodes, + only_gen_src_code=False, + ) + + node_schedule = [*prologue_nodes, template_node, *epilogue_nodes] + self.codegen_comment(node_schedule, kernel.kernel_name) + kernel.call_kernel(kernel.kernel_name, template_node.node) + + V.graph.removed_buffers |= kernel.removed_buffers + V.graph.inplaced_to_remove |= kernel.inplaced_to_remove + self.free_buffers_in_scheduler() + return None + + def codegen_sync(self): + V.graph.wrapper_code.generate_debug_sync(V.graph.wrapper_code) + + def _codegen_standalone_kernel( + self, + node_info: NodeInfo, + only_gen_src_code: bool, + ) -> tuple[str, TritonKernel]: + kernel_kwargs: dict[str, Any] = {} + self.kernel_type.apply_feature_required_overrides( + node_info.features, kernel_kwargs + ) + kernel = self.kernel_type( + node_info.tiling, + features=node_info.features, + tiling_scores=node_info.tiling_scores, + **kernel_kwargs, + ) + self.process_kernel(kernel, node_info.node_schedule, only_gen_src_code) + with V.set_kernel_handler(kernel): + src_code = kernel.codegen_kernel() + return src_code, kernel + + def _probe_subkernel_heuristic(self, node_info: NodeInfo) -> tuple[list[Any], Any]: + from ..runtime.triton_heuristics import ( + persistent_reduction, + pointwise, + reduction, + ) + from .triton_utils import select_tile_hint + + kernel_kwargs: dict[str, Any] = dict( + is_combo_kernel=True, + override_cooperative_reduction=False, + ) + self.kernel_type.apply_feature_required_overrides( + node_info.features, kernel_kwargs + ) + kernel = self.kernel_type( + node_info.tiling, + features=node_info.features, + tiling_scores=node_info.tiling_scores, + **kernel_kwargs, + ) + with config.patch(benchmark_kernel=False), V.set_kernel_handler(kernel): + self.codegen_node_schedule_with_kernel(node_info.node_schedule, kernel) + _ = kernel.codegen_kernel() + + size_hints = { + prefix: next_power_of_2(int(V.graph.sizevars.optimization_hint(numel))) + for prefix, numel in kernel.numels.items() + if not prefix_is_reduction(prefix) or kernel.inside_reduction + } + inductor_meta = cast( + "InductorMeta", + { + **kernel.inductor_meta_common(), + **kernel.inductor_meta_per_kernel(), + }, + ) + if kernel.persistent_reduction: + configs = persistent_reduction( + size_hints, + reduction_hint=kernel.features.get_reduction_hint(kernel.tiling_scores), + triton_meta=kernel.triton_meta, + inductor_meta=inductor_meta, + return_configs=True, + ) + elif kernel.inside_reduction: + configs = reduction( + size_hints, + reduction_hint=kernel.features.get_reduction_hint(kernel.tiling_scores), + triton_meta=kernel.triton_meta, + inductor_meta=inductor_meta, + return_configs=True, + ) + else: + _, _, signature, _ = kernel.args.python_argdefs() + configs = pointwise( + size_hints, + triton_meta=kernel.triton_meta, + tile_hint=select_tile_hint(size_hints, signature), + inductor_meta=inductor_meta, + return_configs=True, + ) + return configs, kernel + + @staticmethod + def _stitch_combo_block_config(chosen_configs: list[Any]) -> dict[str, int]: + """Suffix each subkernel's BLOCK kwargs into one combo config dict + (XBLOCK -> XBLOCK_0, XBLOCK_1, ...; R0_BLOCK -> R0_BLOCK_0, ...).""" + return { + f"{key}_{i}": int(cfg.kwargs[key]) + for i, cfg in enumerate(chosen_configs) + for key in cfg.kwargs + if key.endswith("BLOCK") + } + + @staticmethod + def _stitch_no_bench_combo_config( + chosen_configs: list[Any], chosen_nodes: list[Any] + ) -> Any: + import triton + + def node_total_bytes(snode: Any) -> int: + return sum( + V.graph.get_dep_size_hint(d, count_bytes=True) + for d in itertools.chain( + snode.read_writes.reads, snode.read_writes.writes + ) + ) + + # Heaviest subkernel by total memory traffic dominates runtime; its + # config is authoritative for the combo. Its num_warps, num_stages, + # and non-BLOCK kwargs (HIP backend options like waves_per_eu) apply + # combo-wide. Per-subkernel BLOCK kwargs are suffixed (XBLOCK_0, ...). + winner_idx = max( + range(len(chosen_configs)), + key=lambda i: node_total_bytes(chosen_nodes[i]), + ) + winner_cfg = chosen_configs[winner_idx] + + stitched_kwargs: dict[str, Any] = SIMDScheduling._stitch_combo_block_config( + chosen_configs + ) + stitched_kwargs.update( + { + key: value + for key, value in winner_cfg.kwargs.items() + if not key.endswith("BLOCK") + } + ) + + return triton.Config( + stitched_kwargs, + num_warps=int(winner_cfg.num_warps), + num_stages=int(winner_cfg.num_stages), + ) + + def _autotune_subkernels_compile_time( + self, group: list[Any], node_schedule_map: dict[Any, NodeInfo] + ) -> list[Any | None]: + """Autotune each combo subkernel standalone at compile time and read back its winning + config (None for a subkernel whose compile or benchmark failed, which the caller + carves out to run standalone instead of failing the compile). + + Triton precompiles are submitted to the async compile pool as each subkernel is codegened. + The subkernels are then benchmarked in compile-completion order through the standard + benchmark_codegened_module path, so device benchmarking overlaps the remaining precompiles + while retaining preserve_rng_state, argument cloning and the n_spills guard. Subkernels + with a single candidate config (unless coordinate descent tuning is on) or an autotune + cache hit are taken directly with no benchmark. + """ + from concurrent.futures import as_completed + + from ..async_compile import AsyncCompile + from ..codecache import CodeCacheFuture + + async_compile = AsyncCompile() + use_process_pool = async_compile.use_process_pool() + work: list[tuple[Any, Any, bool, bool, Any]] = [] + futures_by_autotuner: dict[int, Any] = {} + seen_autotuners: OrderedSet[int] = OrderedSet() + + # Benchmark codegen must not count toward generated_kernel_count: these kernels + # are never emitted into the wrapper. + old_kernel_count = metrics.generated_kernel_count + for pn in group: + node_info = node_schedule_map[pn] + # Cooperative reductions are disabled to match how the combo emits its + # subkernels; force_cooperative_reductions must be patched too since it + # short-circuits should_use_cooperative_reduction before the first flag. + with config.patch( + { + "triton.cooperative_reductions": False, + "triton.force_cooperative_reductions": False, + } + ): + src_code = self.generate_kernel_code_from_nodes( + pn.get_nodes(), + benchmark_kernel=True, + coalesce_analysis=node_info.features.coalesce_analysis, + ) + mod = PyCodeCache.load(src_code) + autotuner = mod.triton_ + configs = autotuner.configs + already_tuned = bool(autotuner.launchers) # from a prior compile this run + # One candidate config -> nothing to autotune among configs, so take it directly. + # Skip only when CDT is off: with CDT on, coordinate descent can still improve a + # single config by searching its neighbors. + single = ( + not config.coordinate_descent_tuning + and configs is not None + and len(configs) == 1 + ) + autotuner_id = id(autotuner) + duplicate = autotuner_id in seen_autotuners + seen_autotuners.add(autotuner_id) + future = futures_by_autotuner.get(autotuner_id) + if not already_tuned and not duplicate and not single and use_process_pool: + # triton() may compile synchronously and return a raw autotuner + # (e.g. TRITON_INTERPRET=1) despite use_process_pool being True. + maybe_future = async_compile.triton("triton_", src_code) + future = ( + maybe_future if isinstance(maybe_future, CodeCacheFuture) else None + ) + futures_by_autotuner[autotuner_id] = future + work.append((pn, mod, already_tuned or duplicate, single, future)) + metrics.generated_kernel_count = old_kernel_count + + winners: list[Any | None] = [None] * len(work) + failed: OrderedSet[int] = OrderedSet() + + def fallback(index: int, pn: Any) -> None: + counters["inductor"]["combo_subkernel_autotune_fallback"] += 1 + log.warning("combo compile-time autotune failed for %s; carving out", pn) + failed.add(index) + + def benchmark(index: int) -> None: + pn, mod, already_tuned, single, _ = work[index] + autotuner = mod.triton_ + configs = autotuner.configs + benchmark_failed = False + if not already_tuned and not single: + # skip_perf_cache: the winner is needed in launchers, not just the timing. + try: + ms, _mod_path = self.benchmark_codegened_module( + mod, skip_perf_cache=True + ) + except Exception: + log.debug("combo subkernel benchmark raised", exc_info=True) + ms = float("inf") + # inf means the benchmark failed or spilled; launchers != 1 means the + # autotune race never pruned to a winner. + benchmark_failed = ( + math.isinf(ms) and len(autotuner.launchers) != 1 + ) or len(autotuner.launchers) > 1 + if benchmark_failed: + fallback(index, pn) + return + launchers = autotuner.launchers + info = autotuner.autotune_cache_info or {} + # cached == no fresh benchmark ran: in-process reuse (launchers already set), + # the benchmark was skipped (no launchers), or a .best_config hit. + cached = ( + already_tuned + or not launchers + or info.get("autotune_cache_state") == "hit" + ) + counters["inductor"][ + "combo_subkernel_autotune_cached" + if cached + else "combo_subkernel_autotune" + ] += 1 + if launchers: + winners[index] = launchers[0].config + elif configs: + winners[index] = configs[0] + else: + # configs is None after a precompile that failed to produce launchers. + fallback(index, pn) + + pending: dict[Any, list[int]] = {} + ready: list[int] = [] + for index, (*_, future) in enumerate(work): + raw_future = getattr(future, "future", None) + if raw_future is None: + ready.append(index) + else: + pending.setdefault(raw_future, []).append(index) + + def resolve_and_benchmark(future: Any, indices: list[int]) -> None: + if future is not None: + try: + # Waiting on the raw pool future (not the LambdaFuture wrapper) + # surfaces worker exceptions without repeating the wrapper's + # parent-side precompile of a kernel we discard: benchmark() uses + # mod.triton_, whose own precompile hits the now-warm disk cache. + future.result() + except Exception: + for index in indices: + fallback(index, work[index][0]) + return + for index in indices: + benchmark(index) + + resolved_futures: OrderedSet[int] = OrderedSet() + for index in ready: + future = work[index][-1] + if future is not None and id(future) in resolved_futures: + future = None + elif future is not None: + resolved_futures.add(id(future)) + resolve_and_benchmark(future, [index]) + + for raw_future in as_completed(pending): + resolve_and_benchmark(raw_future, pending[raw_future]) + + if any(w is None for i, w in enumerate(winners) if i not in failed): + raise AssertionError("expected all combo subkernels to be autotuned") + return winners + + def _build_combo_kernel( + self, + fusion_pns: list[Any], + node_schedule_map: dict[Any, NodeInfo], + enable_autotune: bool, + mixed_sizes: bool, + per_subkernel_blocks: bool, + only_gen_src_code: bool, + ) -> Any: + """Build a ComboKernel and its sub-kernels from a list of partition nodes.""" + from .triton_combo_kernel import ComboKernel + + kernel = ComboKernel( + triton_kernel_cls=self.kernel_type, + enable_autotune=enable_autotune, + mixed_sizes=mixed_sizes, + per_subkernel_blocks=per_subkernel_blocks, + ) + for pn in fusion_pns: + node_info = node_schedule_map[pn] + subkernel = ComboKernel.create_triton_kernel( + node_info.tiling, + features=node_info.features, + optimize_mask=not mixed_sizes, + triton_kernel_cls=self.kernel_type, + tiling_scores=node_info.tiling_scores, + per_subkernel_blocks=per_subkernel_blocks, + ) + self.process_kernel( + kernel.create_sub_kernel(subkernel), + node_info.node_schedule, + only_gen_src_code, + ) + return kernel + + @staticmethod + def _combo_launch_candidates(winners: list[Any]) -> list[Any]: + """Deduplicate the subkernels' winner launch configs (non-block kwargs + num_warps + + num_stages) into the candidate set for the combo's kernel-level autotune.""" + from .triton_combo_kernel import ComboLaunchConfig + + seen: dict[Any, Any] = {} + for w in winners: + nb = {k: int(v) for k, v in w.kwargs.items() if not k.endswith("BLOCK")} + key = (tuple(sorted(nb.items())), int(w.num_warps), int(w.num_stages)) + seen[key] = ComboLaunchConfig(nb, int(w.num_warps), int(w.num_stages)) + return [seen[k] for k in sorted(seen)] + + def generate_combo_kernel_code( + self, + subkernel_nodes: list[BaseSchedulerNode], + custom_part_algorithm: bool, + enable_autotune: bool, + mixed_sizes: bool, + only_gen_src_code: bool = False, + per_subkernel_blocks: bool = False, + ) -> list[tuple[str | None, Any, Any]]: + """ + Generate kernel code for combo kernel partitions. + + Partitions subkernel_nodes using horizontal_partition(), then generates + kernel code for each partition. Single-node partitions are generated as + regular kernels, while multi-node partitions use ComboKernel. + + Returns a list of (src_code, kernel, node_group) tuples. + """ + from .triton import TritonKernel + from .triton_combo_kernel import ComboKernel + + # This is currently the only type supported by this method + if not issubclass(self.kernel_type, TritonKernel): + raise AssertionError( + f"expected self.kernel_type to subclass TritonKernel, " + f"got {self.kernel_type}" + ) + + fused_node_lists = [node.get_nodes() for node in subkernel_nodes] + node_schedule_map: dict[Any, NodeInfo] = {} + for pn, nodes in zip(subkernel_nodes, fused_node_lists): + _, (numel, rnumel) = max(nodes, key=lambda x: int(x.is_reduction())).group + node_schedule = self.generate_node_schedule(nodes, numel, rnumel) + tiling_scores = None + if per_subkernel_blocks: + if torch._inductor.config.triton.coalesce_tiling_analysis: + if not isinstance( + pn, (scheduler.FusedSchedulerNode, scheduler.SchedulerNode) + ): + raise AssertionError( + f"expected pn to be FusedSchedulerNode or " + f"SchedulerNode, got {type(pn)}" + ) + coalesce_analysis = pn.get_coalesce_analysis() + else: + coalesce_analysis = None + features = SIMDKernelFeatures( + node_schedule, numel, rnumel, coalesce_analysis=coalesce_analysis + ) + tiling, tiling_scores = self.get_tiling_and_scores( + node_schedule, + numel, + rnumel, + features.coalesce_analysis, + ) + else: + features = SIMDKernelFeatures(node_schedule, numel, rnumel) + tiling = self.select_tiling(node_schedule, numel, rnumel) + is_persistent_reduction = ( + features.is_reduction() + and V.choices.should_use_persistent_reduction( + features.with_tiling_scores(tiling_scores), + cooperative_reduction=False, + ) + ) + node_schedule_map[pn] = NodeInfo( + node_schedule=node_schedule, + tiling=tiling, + tiling_scores=tiling_scores, + numel=numel, + rnumel=rnumel, + features=features, + is_persistent_reduction=is_persistent_reduction, + ) + + partitions = ComboKernel.horizontal_partition( + nodes=subkernel_nodes, + triton_scheduling=self, + custom_algorithm=custom_part_algorithm, + node_info_map=node_schedule_map, + ) + log.debug( + "ComboKernels: %d nodes partitioned into %s groups", + len(subkernel_nodes), + [len(p) for p in partitions], + ) + kernel_code_list = [] + for node_group in partitions: + if len(node_group) == 0: + continue + + if len(node_group) == 1: + # Single-node partition + node_info = node_schedule_map[node_group[0]] + if only_gen_src_code: + # Skip code generation - caller has cached benchmark results + kernel_code_list.append((None, None, node_group)) + else: + src_code, kernel = self._codegen_standalone_kernel( + node_info, only_gen_src_code + ) + # pyrefly: ignore [bad-argument-type] + kernel_code_list.append((src_code, kernel, node_group)) + else: + if ( + enable_autotune + and per_subkernel_blocks + and config.combo_kernel_compile_time_autotune + and not only_gen_src_code + ): + group = list(node_group) + tuned = self._autotune_subkernels_compile_time( + group, node_schedule_map + ) + # A None winner means its compile/benchmark failed; carve it out to + # run standalone rather than stitch a bogus config or fail compile. + fusable = [(pn, w) for pn, w in zip(group, tuned) if w is not None] + carve_out = [pn for pn, w in zip(group, tuned) if w is None] + if len(fusable) >= 2: + fusable_pns = [pn for pn, _ in fusable] + winners = [w for _, w in fusable] + kernel = self._build_combo_kernel( + fusable_pns, + node_schedule_map, + enable_autotune=True, + mixed_sizes=mixed_sizes, + per_subkernel_blocks=True, + only_gen_src_code=only_gen_src_code, + ) + kernel.combo_compile_time_autotune = True + kernel.combo_launch_candidates = self._combo_launch_candidates( + winners + ) + # Compile-time autotune needs only the per-subkernel block sizes; + # warps / num_stages / backend kwargs are autotuned over + # combo_launch_candidates. + kernel.stitched_block_config = self._stitch_combo_block_config( + winners + ) + src_code = kernel.codegen_kernel() + # pyrefly: ignore [bad-argument-type] + kernel_code_list.append((src_code, kernel, fusable_pns)) + else: + # Fewer than two tunable sub-kernels: emit them all standalone. + carve_out = list(group) + for pn in carve_out: + co_src, co_kernel = self._codegen_standalone_kernel( + node_schedule_map[pn], only_gen_src_code + ) + # pyrefly: ignore [bad-argument-type] + kernel_code_list.append((co_src, co_kernel, [pn])) + continue + no_bench_mode = per_subkernel_blocks and not enable_autotune + fusion_pns: list[Any] = [] + fusion_configs: list[Any] = [] + carve_out_pns: list[Any] = [] + if no_bench_mode: + old_kernel_count = metrics.generated_kernel_count + try: + for pn in node_group: + configs, probe_kernel = self._probe_subkernel_heuristic( + node_schedule_map[pn] + ) + if torch.version.hip or torch.xpu.is_available(): + fuse_ok = configs and not probe_kernel.autotune_hints + else: + fuse_ok = configs and len(configs) <= 2 + if fuse_ok: + fusion_pns.append(pn) + fusion_configs.append(configs[0]) + else: + carve_out_pns.append(pn) + finally: + if only_gen_src_code: + metrics.generated_kernel_count = old_kernel_count + if len(fusion_pns) < 2: + fusion_pns = [] + fusion_configs = [] + carve_out_pns = list(node_group) + else: + fusion_pns = list(node_group) + + if len(fusion_pns) >= 2: + kernel = self._build_combo_kernel( + fusion_pns, + node_schedule_map, + enable_autotune=enable_autotune, + mixed_sizes=mixed_sizes, + per_subkernel_blocks=per_subkernel_blocks, + only_gen_src_code=only_gen_src_code, + ) + + if no_bench_mode and fusion_configs: + kernel.no_bench_stitched_config = ( + self._stitch_no_bench_combo_config( + fusion_configs, fusion_pns + ) + ) + + src_code = kernel.codegen_kernel() + # pyrefly: ignore [bad-argument-type] + kernel_code_list.append((src_code, kernel, fusion_pns)) + + for pn in carve_out_pns: + co_src_code, co_kernel = self._codegen_standalone_kernel( + node_schedule_map[pn], only_gen_src_code + ) + # pyrefly: ignore [bad-argument-type] + kernel_code_list.append((co_src_code, co_kernel, [pn])) + # pyrefly: ignore [bad-return] + return kernel_code_list + + def codegen_combo_kernel(self, combo_kernel_node): + subkernel_nodes = combo_kernel_node.get_subkernel_nodes() + custom_part_algorithm = combo_kernel_node.use_custom_partition_algo + enable_autotune = combo_kernel_node.enable_autotune + mixed_sizes = config.combo_kernel_allow_mixed_sizes > 1 or ( + config.combo_kernel_allow_mixed_sizes == 1 and custom_part_algorithm + ) + + per_subkernel_blocks = combo_kernel_node.per_subkernel_blocks + + kernel_code_list = self.generate_combo_kernel_code( + subkernel_nodes, + custom_part_algorithm, + enable_autotune, + mixed_sizes, + per_subkernel_blocks=per_subkernel_blocks, + ) + + for src_code, kernel, _ in kernel_code_list: + kernel_name = self.define_kernel(src_code, [combo_kernel_node], kernel) + self.codegen_comment(combo_kernel_node.snodes, kernel_name) + log.debug("ComboKernels: generated kernel %s.", kernel_name) + kernel.call_kernel(kernel_name) + + self.free_buffers_in_scheduler() + + @classmethod + @functools.lru_cache(32) + def candidate_tilings(cls, node, numel, reduction_numel) -> list[CandidateTiling]: + is_pointwise = reduction_numel == 1 + + def tile_ranges(is_pointwise: bool, ranges, rw) -> list[CandidateTiling]: + """ + Compute tiling candidates by dividing up the iteration ranges. + """ + if len(rw.range_vars) != len(ranges): + raise AssertionError(f"{rw.range_vars=} {ranges=}") + + # isinstance(dep, MemoryDep): this filters out StarDeps. StarDeps refer to reads + # that need to access the entire tensor; they don't contribute read indexing + # information (and practically, they don't have dep.index so they can't be used + # for stride_hints below + dep_sources = [rw.reads, rw.writes] + if not all( + isinstance(dep, (MemoryDep, StarDep)) + for dep in itertools.chain.from_iterable(dep_sources) + ): + raise AssertionError("expected all deps to be MemoryDep or StarDep") + deps = [ + dep + for dep in itertools.chain.from_iterable(dep_sources) + if dep.name not in V.graph.removed_buffers + and isinstance(dep, MemoryDep) + ] + write_names = OrderedSet([dep.name for dep in rw.writes]) + + def collapse_ranges(ranges: Sequence[sympy.Expr]) -> sympy.Expr: + return V.graph.sizevars.simplify(sympy_product(ranges)) + + # Default to no tiling. + tilings = [ + CandidateTiling( + tiling=cls.create_partial_tiling( + [collapse_ranges(ranges)], is_pointwise + ), + name="none", + score=0, + ) + ] + + # Find non-trivial tiling candidates. + for dep in deps: + strides = V.graph.sizevars.stride_hints(dep.index, rw.range_vars) + if len(strides) != len(ranges): + raise AssertionError( + f"expected len(strides) == len(ranges), " + f"got {len(strides)} and {len(ranges)}" + ) + try: + split = strides.index(1) + 1 + if split == len(ranges): + continue + if all(s == 0 for s in strides[split:]): + # if this is a broadcasted tensor and all dimensions after split are broadcast, + # this is not a real split + continue + + except ValueError: + continue + + tiled_groups = ( + collapse_ranges(ranges[:split]), + collapse_ranges(ranges[split:]), + ) + + # score by number of elements + score = V.graph.sizevars.optimization_hint( + sympy_product( + size for size, stride in zip(ranges, strides) if stride != 0 + ) + ) + if dep.name in write_names: + # ngimel said contiguous writes is more important than reads + score *= 2 + if CandidateTiling.is_good_size(tiled_groups[0]): + score *= 2 + if CandidateTiling.is_good_size(tiled_groups[1]): + score *= 2 + + if ( + V.graph.sizevars.optimization_hint( + score - sympy_product(itertools.chain(ranges, reduction_ranges)) + ) + >= 0 + ): + tilings.append( + CandidateTiling( + tiling=cls.create_partial_tiling( + [ + collapse_ranges(ranges[:split]), + collapse_ranges(ranges[split:]), + ], + reduction_numel, + ), + score=score, + name=dep.name, + ) + ) + + return tilings + + pointwise_ranges, reduction_ranges = node.get_ranges() + if ( + len(pointwise_ranges) <= 1 + and len(reduction_ranges) <= 1 + or free_unbacked_symbols(pointwise_ranges + reduction_ranges) + ): + return [] + + # Tile either pointwise or reduction dims. + pointwise_ranges, reduction_ranges = node.get_ranges() + partial_tilings = tile_ranges( + is_pointwise, + pointwise_ranges if is_pointwise else reduction_ranges, + node.pointwise_or_reduction_read_writes(is_pointwise), + ) + + # Fill in the missing ranges. + full_tilings = [ + CandidateTiling( + tiling=cls.complete_partial_tiling( + tiling.tiling, numel, reduction_numel + ), + score=tiling.score, + name=tiling.name, + ) + for tiling in partial_tilings + ] + + return full_tilings + + @classmethod + def create_tiling( + cls, pw_tiling: Sequence[sympy.Expr], reduction_tiling: Sequence[sympy.Expr] + ) -> immutable_dict[str, sympy.Expr]: + """ + Create a tiling dict from pointwise and reduction splits. + """ + pw_prefixes = ("z", "y", "x") + reduction_prefixes = ("r0_", "r1_") + if len(pw_tiling) > len(pw_prefixes): + raise AssertionError( + f"expected len(pw_tiling) <= len(pw_prefixes), " + f"got {len(pw_tiling)} and {len(pw_prefixes)}" + ) + if len(reduction_tiling) > len(reduction_prefixes): + raise AssertionError( + f"expected len(reduction_tiling) <= len(reduction_prefixes), " + f"got {len(reduction_tiling)} and {len(reduction_prefixes)}" + ) + + return immutable_dict( + [ + *zip(pw_prefixes[-len(pw_tiling) :], pw_tiling, strict=False), + *zip(reduction_prefixes, reduction_tiling, strict=False), + ] + ) + + @classmethod + def create_partial_tiling( + cls, + tiling: Sequence[sympy.Expr], + is_pointwise: bool, + ) -> immutable_dict[str, sympy.Expr]: + return cls.create_tiling( + tiling if is_pointwise else [], + tiling if not is_pointwise else [], + ) + + @classmethod + def complete_partial_tiling( + cls, + tiling: dict[str, sympy.Expr], + numel: sympy.Expr, + reduction_numel: sympy.Expr, + ) -> immutable_dict[str, sympy.Expr]: + """ + Given a tiling for only pointwise or reduction dimensions, adds the missing one. + """ + splits = list(tiling.values()) + is_pointwise = "x" in tiling + + total_numel = numel * reduction_numel + missing_tiling = [total_numel / sympy_product(splits)] + + tiling_args = ( + (splits, missing_tiling) if is_pointwise else (missing_tiling, splits) + ) + return cls.create_tiling(*tiling_args) + + @classmethod + def get_nd_tilings( + cls, + node_schedule, + pointwise_numel, + reduction_numel, + ) -> list[immutable_dict[str, sympy.Expr]]: + """ + Creates N-dimensional tiling candidates, attempting to simplify loads/stores + by tiling the kernel into higher dimensions. + + Returns a list of tilings ranked by dimensionality. + """ + + def collapse_dims( + dims: Sequence[sympy.Expr], fallback_numel: sympy.Expr + ) -> tuple[sympy.Expr, ...]: + """ + Collapse dimensions to the maximum allowed number of tiles. + """ + if not dims: + return (fallback_numel,) + max_tiles = get_max_tiles(2) + if V.graph.sizevars.statically_known_equals( + pointwise_numel, 1 + ) and V.graph.sizevars.statically_known_gt(reduction_numel, 1): + # We only have at most two dimensions to tile over when emitting a + # reduction-only kernel. + max_tiles = min(max_tiles, 2) + num_leading_dims = max(0, len(dims) - max_tiles) + first_trailing_dim = num_leading_dims + 1 + collapsed_leading_dim = sympy_product(dims[:first_trailing_dim]) + return (collapsed_leading_dim,) + tuple(dims[first_trailing_dim:]) + + def tile_var_ranges( + var_ranges, ranges_to_tile, total_numel + ) -> tuple[sympy.Expr, ...]: + # Pattern match the subexpression pertaining to each index variable. + tiling = [] + for var, numel in var_ranges: + index = BlockPatternMatcher.get_subexpr_involving_symbol(dep.index, var) + + # Heuristic to bound the maximum dimensionality of the block. + num_dims = max( + 2, + index.count(FloorDiv) + index.count(ModularIndexing), + len(ranges_to_tile), + ) + + # Attempt to pattern match the index expr. + # Failed matches default to the full range. + match_result = BlockPatternMatcher.match_mod_div_block_expr( + index, var, numel, num_dims + ) + dims = match_result[0] if match_result is not None else [numel] + tiling.extend(dims) + + # Prune dimensions of size 1. + tiling = [ + dim + for dim in tiling + if not V.graph.sizevars.statically_known_equals(dim, sympy.S.One) + ] + + return collapse_dims(tiling, total_numel) + + is_pointwise = reduction_numel == 1 + tilings = OrderedSet[immutable_dict[str, sympy.Expr]]() + for node in EnableReduction.filter(node_schedule): + if not isinstance(node, scheduler.SchedulerNode): + continue + + # If this is a reduction schedule, skip nodes which are missing their + # reduction ranges. + node_ranges = node.get_ranges() + if not is_pointwise and len(node_ranges[1]) == 0: + continue + + # Use the node ranges as the default tiling candidate. + default_pointwise_tiling = collapse_dims(node_ranges[0], pointwise_numel) + default_reduction_tiling = collapse_dims(node_ranges[1], reduction_numel) + node_tilings = [(default_pointwise_tiling, default_reduction_tiling)] + + # Search the indexing expressions for more candidates. + # If we see modular indexing, try to subdivide ranges into their implied + # block shape. + memory_deps = [ + dep + for dep in node.read_writes.reads_and_writes() + if isinstance(dep, MemoryDep) and len(dep.ranges) > 0 + ] + for dep in memory_deps: + # Attempt to partition variable ranges into pointwise and reduction groups. + # To achieve this, merge the leading ranges until we reach the pointwise numel. + all_var_ranges = [*dep.ranges.items()] + pointwise_vars_numel = sympy.S.One + sizevars = V.graph.sizevars + pointwise_end_idx = 0 + for idx, (_var, numel) in enumerate(all_var_ranges): + pointwise_vars_numel *= numel + pointwise_end_idx = idx + if sizevars.statically_known_geq( + pointwise_vars_numel, pointwise_numel + ): + break + + # Reject the split if it does not match the total pointwise numel. + if not sizevars.statically_known_equals( + pointwise_vars_numel, pointwise_numel + ): + continue + + # Partition var ranges into pointwise and reduction splits, tiling them + # separately. + reduction_start_idx = pointwise_end_idx + 1 + pointwise_var_ranges = all_var_ranges[:reduction_start_idx] + reduction_var_ranges = ( + None if is_pointwise else all_var_ranges[reduction_start_idx:] + ) + pointwise_tiling = tile_var_ranges( + pointwise_var_ranges, node_ranges[0], pointwise_numel + ) + reduction_tiling = ( + (sympy.S.One,) + if is_pointwise + else tile_var_ranges( + reduction_var_ranges, node_ranges[1], reduction_numel + ) + ) + + if len(pointwise_tiling) and len(reduction_tiling) > 0: + node_tilings.append((pointwise_tiling, reduction_tiling)) + + # Each memory dependency contributes one pointwise and reduction tiling. We + # take the Cartesian product of these, yielding all possible joint tilings. + for pointwise_tiling, reduction_tiling in itertools.product( + *zip(*node_tilings) + ): + tilings.add(cls.create_tiling(pointwise_tiling, reduction_tiling)) + + # Rank tilings by the number of dimensions. E.g., prefer 2D to 1D. + # Since this is a stable sort, ties are broken by schedule order. + ranked_tilings = sorted( + tilings, + key=len, + reverse=True, + ) + + return ranked_tilings + + @classmethod + def compute_tiling_strategy( + cls, + node_schedule: list[NodeScheduleEntry], + pointwise_numel: sympy.Expr, + reduction_numel: sympy.Expr, + coalesce_analysis: CoalesceVarAnalysis, + ) -> _TilingSelection: + """ + Generates a tiling, and a score of each tile according to each tile's coalesced memory accesses. + """ + tiling_var: sympy.Expr | None = ( + None + if not coalesce_analysis.suggested_split + else coalesce_analysis.suggested_split.var + ) + + all_iter_vars = coalesce_analysis.norm_read_writes.index_vars + all_red_vars = coalesce_analysis.norm_read_writes.reduce_vars + ranges = coalesce_analysis.norm_read_writes.var_ranges + + pw_ranges = [ranges[v] for v in all_iter_vars] + red_ranges = [ranges[v] for v in all_red_vars] + + # Sometimes dynamic shapes is unable to prove equality without hint + get_hint = V.graph.sizevars.optimization_hint + torch._check( + get_hint(sympy_product(pw_ranges)) == get_hint(pointwise_numel), + lambda: f"{pw_ranges}, {pointwise_numel}, {node_schedule}", + ) + + torch._check( + get_hint(sympy_product(red_ranges)) == get_hint(reduction_numel), + lambda: f"{red_ranges}, {reduction_numel}, {node_schedule}", + ) + + # score of a pointwise or reduction split + scored_sub_split: dict[Any, _SubSplit] = {} + + score_split: list[tuple[_SubSplit, _SubSplit]] = [] + + def process_node_vars( + vars_to_use: tuple[sympy.Expr, ...] = (), + use_split_var: bool = False, + is_pointwise: bool = False, + ) -> _SubSplit: + """ + Generate a tiling, and a tiling score, given vars to use as splits. + """ + + ranges = pw_ranges if is_pointwise else red_ranges + target_numel = pointwise_numel if is_pointwise else reduction_numel + # Some kernels have no reduction ranges, and a reduction numel of 1 + if not ranges: + if target_numel: + return _SubSplit([target_numel], [], 0) + else: + return _SubSplit([], [], 0) + + key = (repr(vars_to_use), use_split_var, is_pointwise) + if out := scored_sub_split.get(key): + return out + + splitting_vars = all_iter_vars if is_pointwise else all_red_vars + + splits = [] + split_scores = [] + prod = 1 + prev_var_coalesced_score = 0 + + # iterate from non-dense to dense + for v, v_range in zip(splitting_vars, ranges): + if v not in vars_to_use: + prod *= v_range + prev_var_coalesced_score = coalesce_analysis.coalesced_by_var.get( + v, 0 + ) + continue + + if use_split_var and v == tiling_var: + var_tiling = coalesce_analysis.suggested_split + if var_tiling is None: + raise AssertionError("expected var_tiling to not be None") + + tile = var_tiling.tiling_factor + remainder = FloorDiv(v_range, var_tiling.tiling_factor) + + splits.append(prod * remainder) + split_scores.append(var_tiling.score) + + splits.append(tile) + split_scores.append(coalesce_analysis.coalesced_by_var.get(v, 0)) + + prod = 1 + prev_var_coalesced_score = 0 + + continue + + prod *= v_range + splits.append(prod) + split_scores.append(coalesce_analysis.coalesced_by_var.get(v, 0)) + prod = 1 + + if prod != 1 or (is_pointwise and len(splits) == 0): + splits.append(prod) + split_scores.append(prev_var_coalesced_score) + + coalesced_memory = sum(split_scores) + + # penalize splits that leave small blocks + # where we can't fully utilize full memory transaction + # TODO: incorporate exact bitwidth, and read/write + # coalesced write is 2x more important + for i in range(len(splits)): + s = V.graph.sizevars.optimization_hint(splits[i], fallback=32) + s = min(s, 8) + split_scores[i] = int(split_scores[i] * s / 8) + + sub_split = _SubSplit(splits, split_scores, coalesced_memory) + scored_sub_split[key] = sub_split + return sub_split + + # add the default tiling + score_split.append( + ( + process_node_vars(is_pointwise=True), + process_node_vars(is_pointwise=False), + ) + ) + + if tiling_var: + score_split.append( + ( + process_node_vars( + (tiling_var,), use_split_var=True, is_pointwise=True + ), + process_node_vars(is_pointwise=False), + ) + ) + + # TODO, add tests, reduction splits if config.triton.tile_reductions + # TODO: we should ignore tiny increases in score for extra splits + overlapping_iter_vars = ( + all_iter_vars & coalesce_analysis.coalesced_by_var.keys() + ) + for v in overlapping_iter_vars: + score_split.append( + ( + process_node_vars((v,), is_pointwise=True), + process_node_vars(is_pointwise=False), + ) + ) + + if get_max_tiles(default=3) == 3 and reduction_numel == 1: + for vars_to_use in itertools.combinations(overlapping_iter_vars, 2): + score_split.append( + ( + process_node_vars(vars_to_use, is_pointwise=True), + process_node_vars(is_pointwise=False), + ) + ) + + tilings: list[tuple[CandidateTiling, immutable_dict[str, sympy.Expr], int]] = [] + for pw, red in score_split: + candidate = CandidateTiling( + cls.create_tiling(pw.splits, red.splits), + score=sum(pw.split_scores) + sum(red.split_scores), + ) + tiling_score = cls.create_tiling(pw.split_scores, red.split_scores) + tilings.append( + (candidate, tiling_score, pw.coalesced_memory + red.coalesced_memory) + ) + + default_tiling = cls.create_tiling([pointwise_numel], [reduction_numel]) + + # add a slight penalty for longer tilings that don't increase score much, + # and are poor sizes + bad_size_additional_tiling_penalty = 1.025 + good_size_tiling_penalty = 1.005 + + total_uncoalesced = sum(coalesce_analysis.uncoalesced_addrs.values()) + # Every access is either coalesced or not under a given tiling, and the + # total is tiling-independent, so the uncoalesced remainder is exact. + total_memory = ( + sum(coalesce_analysis.coalesced_by_var.values()) + total_uncoalesced + ) + + def score_mod(t): + score_factor = 1.0 + for tile_size in t[0].tiling.values(): + if not CandidateTiling.is_good_size(tile_size): + score_factor = score_factor / bad_size_additional_tiling_penalty + else: + score_factor = score_factor / good_size_tiling_penalty + + # Add uncoalesced memory score to prevent small coalesced benefits + # from dominating large amounts of uncoalesced memory + uncoalesced_penalty = total_uncoalesced * 0.05 + + return -(t[0].score + uncoalesced_penalty) * score_factor + + def make_selection( + tiling: dict[str, sympy.Expr], + tiling_score: immutable_dict[str, sympy.Expr], + coalesced_memory: int, + ) -> _TilingSelection: + return _TilingSelection( + tiling, + tiling_score, + MemoryCoalescing( + coalesced=coalesced_memory, + uncoalesced=max(total_memory - coalesced_memory, 0), + ), + ) + + # apply penalty for longer tilings that don't increase score much + for cand, tiling_score, coalesced_memory in sorted(tilings, key=score_mod): + if ( + cls.tiling_is_compatible( + node_schedule, pointwise_numel, reduction_numel, cand.tiling + ) + or cand.tiling == default_tiling + ): + # we always include default reduction numel == 1, don't include + tiling_len = len(cand.tiling) - (1 if reduction_numel == 1 else 0) + if tiling_len > get_max_tiles(default=3): + perf_hint_log.info( + "Found optimal tiling with %s tiles but torch._inductor.config.triton.max_tiles " + "set to %s. Consider increasing", + tiling_len, + torch._inductor.config.triton.max_tiles, + ) + continue + + return make_selection(cand.tiling, tiling_score, coalesced_memory) + + # surprisingly, the default tiling is not always read as compatible by `tiling_is_compatible` + # TODO - look into, occurs with dynamic shapes often + if cand.tiling == default_tiling: + return make_selection(cand.tiling, tiling_score, coalesced_memory) + + return _TilingSelection(default_tiling, None, None) + + @classmethod + def tiling_is_compatible( + cls, + node_schedule: list[NodeScheduleEntry], + numel: sympy.Expr, + reduction_numel: sympy.Expr, + tiling: dict[str, sympy.Expr], + ): + if not isinstance(tiling, dict): + raise AssertionError(f"expected tiling to be a dict, got {type(tiling)}") + return all( + SIMDKernel.is_compatible( + tiling.values(), node.get_ranges(), reduction_numel=reduction_numel + ) + for node in node_schedule + if isinstance(node, scheduler.SchedulerNode) + ) + + @classmethod + def get_first_compatible_tiling( + cls, + node_schedule: list[NodeScheduleEntry], + numel: sympy.Expr, + reduction_numel: sympy.Expr, + ranked_tilings: list[dict[str, sympy.Expr]], + ): + for tiling in ranked_tilings: + if cls.tiling_is_compatible(node_schedule, numel, reduction_numel, tiling): + return tiling + + return None + + @classmethod + def select_tiling( + cls, + node_schedule, + numel, + reduction_numel=sympy.S.One, + coalesce_analysis: CoalesceVarAnalysis | None = None, + ) -> dict[str, sympy.Expr]: + return cls.get_tiling_and_scores( + node_schedule, numel, reduction_numel, coalesce_analysis + )[0] + + @classmethod + def get_tiling_and_scores( + cls, + node_schedule, + numel, + reduction_numel=sympy.S.One, + coalesce_analysis: CoalesceVarAnalysis | None = None, + ) -> tuple[dict[str, sympy.Expr], dict[str, sympy.Expr] | None]: + """ + Heuristics to decide how to tile kernels. + Currently, we tile based on stride-1 dimensions. + + Returns: + `(tile1, tile2, reduction_numel)` s.t. `tile1 * tile2 == numel` + """ + selection = cls.select_tiling_with_memory( + node_schedule, numel, reduction_numel, coalesce_analysis + ) + return selection.tiling, selection.tiling_scores + + @classmethod + def select_tiling_with_memory( + cls, + node_schedule, + numel, + reduction_numel=sympy.S.One, + coalesce_analysis: CoalesceVarAnalysis | None = None, + ) -> _TilingSelection: + """ + Heuristics to decide how to tile kernels. + Currently, we tile based on stride-1 dimensions. + + Same selection as get_tiling_and_scores(), additionally reporting the + coalesced/uncoalesced memory under the selected tiling when known. + """ + # If this is a reduction, only tile reduction dims. + is_pointwise = reduction_numel == 1 + + # Tiled reductions are gated by a config flag. + default_tiling = cls.create_tiling([numel], [reduction_numel]) + + # Force tiling compatible with matmul dimensions + # when natively generating matmul without template calls. + for node in EnableReduction.filter(node_schedule): + if isinstance(node.node, ir.ComputedBuffer): + if ( + node.node.get_reduction_type() == "dot" + and config.triton.native_matmul + ): + # A[M,K] @ B[K,N] + # force tiling to be {'y':M, 'x':N, 'r0_':K} + node_ranges = node.get_ranges() + range_y_x = node_ranges[0] # (M,N) + range_r = node_ranges[1] # (K) + tiling = cls.create_tiling(range_y_x, range_r) + return _TilingSelection(tiling, None, None) + + # # TODO: enable by default + if ( + torch._inductor.config.triton.coalesce_tiling_analysis + and coalesce_analysis + and not config.triton.prefer_nd_tiling + ): + return cls.compute_tiling_strategy( + node_schedule, numel, reduction_numel, coalesce_analysis + ) + + if (not is_pointwise and not config.triton.tile_reductions) or get_max_tiles( + default=2 + ) <= 1: + # Emit a perf hint in case we miss an opportunity to tile a reduction. + if perf_hint_log.level <= logging.WARNING: + for node in EnableReduction.filter(node_schedule): + if ( + not config.triton.tile_reductions + and len(cls.candidate_tilings(node, numel, reduction_numel)) > 0 + ): + perf_hint_log.info( + textwrap.dedent( + """ + Reduction over non-contiguous dims. + Consider setting config.triton.tile_reductions to True. + """ + ) + ) + break + + return _TilingSelection(default_tiling, None, None) + + seen_names: OrderedSet[str] = OrderedSet() + candidate_tiles: Counter[CandidateTiling] = collections.Counter() + for node in EnableReduction.filter(node_schedule): + for candidate_tiling in cls.candidate_tilings(node, numel, reduction_numel): + if candidate_tiling.name in seen_names: + continue + elif candidate_tiling.name is not None: + seen_names.add(candidate_tiling.name) + candidate_tiles[candidate_tiling] += candidate_tiling.score + + ranked_tilings: list[dict[str, sympy.Expr]] = [ + candidate_tiling.tiling + for candidate_tiling, score in candidate_tiles.most_common() + ] + + if get_max_tiles(default=2) >= 3 and is_pointwise: + # Consider adding a third dimension of tiling, but only + # when a1 is a multiple of b1; otherwise, you have a lot + # of stragglers which is annoying to generate code for. + # + # NB: More than three max tiles is not enabled by default. + + def convert_tiling_to_3d( + tiling0: dict[str, sympy.Expr], tiling1: dict[str, sympy.Expr] + ) -> dict[str, sympy.Expr] | None: + a0, a1 = tiling0["x"], tiling0.get("y", 1) + b0, b1 = tiling1["x"], tiling1.get("y", 1) + + # TODO: These tiling decisions (equality, ordering, divisibility) + # are structural — they determine the kernel's iteration space + # decomposition — but are NOT guarded here. If the relationship + # between a1 and b1 changes across dynamic shape inputs, the + # compiled kernel could be wrong. Seems scary, unless there is a reason + # this is safe in that case probably we need better comment here ! + hint = V.graph.sizevars.guarding_hint_or_throw + if hint(a1 - b1) == 0: + return None + if hint(a1 - b1) < 0: + # swap so a0 is bigger + (a0, a1), (b0, b1) = (b0, b1), (a0, a1) + + if not (hint(a1 - b1) > 0): + raise AssertionError( + f"expected hint(a1 - b1) > 0, got {hint(a1 - b1)}" + ) + if not V.graph.sizevars.statically_known_multiple_of(a1, b1): + return None + + new_tiling = { + "z": a0, + "y": FloorDiv(a1, b1), + "x": b1, + "r0_": tiling0["r0_"], + } + + return new_tiling + + for i in range(1, len(ranked_tilings)): + new_3d_tiling = convert_tiling_to_3d( + ranked_tilings[0], ranked_tilings[i] + ) + if new_3d_tiling is not None: + ranked_tilings = [new_3d_tiling] + ranked_tilings + break # only 1 choice for now + + if len(ranked_tilings) > 1: + perf_hint_log.info("possibly bad tiling: %s", ranked_tilings) + + # Optionally, prefer tiling into as many dimensions as possible. + # pyrefly: ignore [unbound-name] + if config.triton.prefer_nd_tiling: + ranked_tilings = ( + cls.get_nd_tilings(node_schedule, numel, reduction_numel) + + ranked_tilings + ) + + if tiling := cls.get_first_compatible_tiling( + node_schedule, numel, reduction_numel, ranked_tilings + ): + return _TilingSelection(tiling, None, None) + + return _TilingSelection(default_tiling, None, None) + + def flush(self): + pass + + def ready_to_flush(self) -> bool: + return False + + def generate_kernel_code_from_nodes( + self, + nodes, + benchmark_kernel=False, + hint_override: int | None = None, + coalesce_analysis: CoalesceVarAnalysis | None = None, + ): + if not any(n.is_template() for n in nodes): + _, (numel, rnumel) = max(nodes, key=lambda x: int(x.is_reduction())).group + node_schedule = self.generate_node_schedule(nodes, numel, rnumel) + if ( + coalesce_analysis is None + and torch._inductor.config.triton.coalesce_tiling_analysis + ): + from torch._inductor.tiling_utils import ( + analyze_memory_coalescing_for_nodes, + ) + + coalesce_analysis = analyze_memory_coalescing_for_nodes(nodes) + features = SIMDKernelFeatures( + node_schedule, numel, rnumel, coalesce_analysis=coalesce_analysis + ) + tiling, tiling_scores = self.get_tiling_and_scores( + node_schedule, + numel, + rnumel, + features.coalesce_analysis, + ) + kernel_kwargs: dict[str, Any] = {} + self.kernel_type.apply_feature_required_overrides(features, kernel_kwargs) + kernel = self.kernel_type( + tiling, + features=features, + tiling_scores=tiling_scores, + **kernel_kwargs, + ) + self.codegen_node_schedule_with_kernel(node_schedule, kernel) + # Collect config_patches from operations + config_patches = self._collect_config_patches(node_schedule) + config_patches["benchmark_kernel"] = benchmark_kernel + with ( + config.patch(**config_patches), + V.set_kernel_handler(kernel), + ): + src_code = kernel.codegen_kernel() + else: + prologue, template, epilogue = nodes[0].get_prologue_template_epilogue( + nodes + ) + with config.patch("benchmark_kernel", benchmark_kernel): + src_code = self.codegen_template( + template, + epilogue, + prologue, + only_gen_src_code=True, + hint_override=hint_override, + ) + + # pyrefly: ignore [missing-attribute] + src_code = src_code.replace(str(Placeholder.KERNEL_NAME), "triton_") + return src_code + + def define_kernel(self, src_code, node_schedule, kernel): + raise NotImplementedError + + +@dataclasses.dataclass(frozen=True) +class _SubSplit: + """A candidate pointwise or reduction split, and what it coalesces.""" + + splits: list[sympy.Expr] + # Intra-kernel ranking scores, penalized for small blocks. + split_scores: list[int] + # Absolute coalesced memory, comparable across kernels. + coalesced_memory: int + + +# Use a fixed 16x heuristic for uncoalesced memory traffic. +_UNCOALESCED_MEMORY_COST_WEIGHT = 16 + + +@dataclasses.dataclass(frozen=True) +class MemoryCoalescing: + """Memory accessed under a tiling, split by whether it coalesces. + + These are absolute memory scores (writes weighted x2, as in + CoalesceVarAnalysis), so unlike tiling scores they are comparable across + different kernels - e.g. one fused kernel against two separate ones. + """ + + coalesced: int + uncoalesced: int + + def weighted_cost(self) -> int: + """Total cost, weighting uncoalesced traffic as more expensive.""" + return self.coalesced + _UNCOALESCED_MEMORY_COST_WEIGHT * self.uncoalesced + + +@dataclasses.dataclass(frozen=True) +class _TilingSelection: + tiling: dict[str, sympy.Expr] + tiling_scores: dict[str, sympy.Expr] | None + # None when the tiling was forced or fell back, so memory was never scored. + memory: MemoryCoalescing | None + + +@dataclasses.dataclass(frozen=True) +class CandidateTiling: + tiling: dict[str, sympy.Expr] + score: int # higher is better + name: str | None = None + + @staticmethod + def is_good_size(s): + """Somewhat arbitrary heuristic used to boost scores for some sizes""" + s = V.graph.sizevars.optimization_hint(s, fallback=8192) + return s >= 32 and (s % 32 == 0) + + +class CantSplit(Exception): + def __init__(self, expr, remaining): + super().__init__() + self.expr = expr + self.remaining = remaining + + def __str__(self): + return f"{self.expr} not divisible by {self.remaining}" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/simd_kernel_features.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/simd_kernel_features.py new file mode 100644 index 0000000000000000000000000000000000000000..10c408c17b8d32a5fdf074316794602c87a4db3d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/simd_kernel_features.py @@ -0,0 +1,790 @@ +from __future__ import annotations + +import collections +import dataclasses +import functools +import itertools +import typing +from typing import Any + +import sympy + +import torch + +from ...utils._ordered_set import OrderedSet +from ...utils._sympy.functions import FloorDiv, Min, ModularIndexing +from ...utils._sympy.symbol import make_symbol, SymT +from .. import ir +from ..dependencies import Dep, extract_loop_body_with_args, MemoryDep +from ..runtime.hints import ReductionHint +from ..runtime.runtime_utils import next_power_of_2 +from ..scheduler import SchedulerNode +from ..utils import cache_on_self +from ..virtualized import V + + +if typing.TYPE_CHECKING: + from collections.abc import Iterable, Sequence + + from torch._inductor.tiling_utils import CoalesceVarAnalysis + + +_INNER_REDUCTION_RATIO = 32 +_SMALL_INNER_REDUCTION_RATIO = 16 +_SMALL_INNER_REDUCTION_MAX_RBLOCK = 512 + + +def tiling_scores_suggest_inner_reduction( + tiling_scores: dict[str, sympy.Expr], reduction_numel: sympy.Expr +) -> bool: + """Return whether tiling scores justify treating a reduction as inner.""" + sizevars = V.graph.sizevars + non_reduction_score = sum( + sizevars.optimization_hint(tiling_scores.get(dim, 0), fallback=0) + for dim in ("x", "y", "z") + ) + non_reduction_score = max(non_reduction_score, 1) + r_score = sizevars.optimization_hint(tiling_scores["r0_"], fallback=0) + if r_score >= _INNER_REDUCTION_RATIO * non_reduction_score: + return True + if r_score < _SMALL_INNER_REDUCTION_RATIO * non_reduction_score: + return False + + # Moderate score ratios are useful while persistent configs can keep XBLOCK=8. + rblock_hint = next_power_of_2( + max(sizevars.optimization_hint(reduction_numel, fallback=1), 1) + ) + return rblock_hint <= _SMALL_INNER_REDUCTION_MAX_RBLOCK + + +class NodeScheduleMarker: + @staticmethod + def only_nodes(it: Iterable[NodeScheduleEntry]) -> Iterable[SchedulerNode]: + for item in it: + if not (item is DisableReduction or item is EnableReduction): + yield item # type: ignore[misc] + + @staticmethod + def is_reduction() -> bool: + return False + + +NodeScheduleEntry = SchedulerNode | type[NodeScheduleMarker] + + +class DisableReduction(NodeScheduleMarker): + """ + Marker to invoke `kernel.disable_reduction()`. This closes a + reduction loop and allows for pointwise ops to occur on the output + of a reduction. + """ + + +class EnableReduction(NodeScheduleMarker): + """ + Marker to end a DisableReduction block. + """ + + @staticmethod + def filter(node_schedule: list[NodeScheduleEntry]) -> Iterable[SchedulerNode]: + """ + Get the nodes from node_schedule skipping those in a + DisableReduction block. + """ + disabled = False + for node in node_schedule: + if node in (EnableReduction, DisableReduction): + # Don't tile stuff outside the main reduction loop + disabled = node is DisableReduction + elif disabled: + pass + else: + yield node # type: ignore[misc] + + +class SIMDKernelFeatures: + """ + An ordered schedule of nodes that will become a single kernel. + """ + + def __init__( + self, + node_schedule: list[NodeScheduleEntry], + numel: sympy.Expr, + reduction_numel: sympy.Expr = sympy.S.One, + coalesce_analysis: CoalesceVarAnalysis | None = None, + tiling_scores: dict[str, sympy.Expr] | None = None, + ): + self.node_schedule = node_schedule + # numel excludes reduction_numel + self.numel: sympy.Expr = V.graph.sizevars.simplify(numel) + self.reduction_numel: sympy.Expr = V.graph.sizevars.simplify(reduction_numel) + self._stats_cache: dict[tuple[sympy.Expr, ...], MemoryStats] = {} + self.coalesce_analysis = coalesce_analysis + self.tiling_scores = tiling_scores + + def with_tiling_scores( + self, tiling_scores: dict[str, sympy.Expr] | None + ) -> SIMDKernelFeatures: + return SIMDKernelFeatures( + self.node_schedule, + self.numel, + self.reduction_numel, + self.coalesce_analysis, + tiling_scores, + ) + + @cache_on_self + def is_reduction(self) -> bool: + return self.reduction_numel != 1 + + @cache_on_self + def scheduler_nodes(self) -> Iterable[SchedulerNode]: + return tuple(NodeScheduleMarker.only_nodes(self.node_schedule)) + + def reduction_nodes(self) -> list[SchedulerNode]: + return [n for n in self.scheduler_nodes() if n.is_reduction()] + + @cache_on_self + def strict_sum_reductions(self) -> tuple[ir.Reduction, ...]: + return tuple( + node.node.data + for node in self.reduction_nodes() + if isinstance(node.node, ir.ComputedBuffer) + and isinstance(node.node.data, ir.Reduction) + and node.node.data.strict_sum_rblock is not None + ) + + def has_strict_sum_multirow_reduction(self) -> bool: + return any(r.strict_sum_multirow for r in self.strict_sum_reductions()) + + @cache_on_self + def strict_sum_rblock(self) -> int | None: + rblocks = OrderedSet( + reduction.strict_sum_rblock for reduction in self.strict_sum_reductions() + ) + if not rblocks: + return None + if len(rblocks) != 1: + raise AssertionError( + f"strict sums require one reduction block size, got {rblocks}" + ) + return next(iter(rblocks)) + + @cache_on_self + def buf_accesses(self) -> dict[str, list[Dep]]: + """only needed for config.benchmark_kernel""" + buf_accesses = collections.defaultdict(list) + for node in self.scheduler_nodes(): + for access in node.read_writes.reads | node.read_writes.writes: + buf_accesses[access.name].append(access) + return buf_accesses + + @cache_on_self + def op_counts(self) -> collections.Counter[str]: + counts: collections.Counter[str] = collections.Counter() + for node in self.scheduler_nodes(): + counts.update(node._body.op_counts) + return counts + + def contains_op(self, op_name: str) -> bool: + """True if V.ops.{op_name} is used in node_schedule""" + return bool(self.op_counts().get(op_name)) + + def get_mutations(self) -> OrderedSet[str]: + mutations: OrderedSet[str] = OrderedSet() + for node in self.scheduler_nodes(): + for buf in node.get_outputs(): + mutations.update(buf.get_mutations()) + return mutations + + @cache_on_self + def select_index_dtype(self) -> torch.dtype: + # Gather all used buffer names + buffer_names: OrderedSet[str] = OrderedSet() + for node in self.scheduler_nodes(): + buffer_names.update(node.get_buffer_names()) + buffer_names.update(node.used_buffer_names()) + buffers = [V.graph.get_buffer(name) for name in buffer_names] + + # In theory we can separately check xnumel and rnumel are <= int_max + # but some indexers do use the full linear index so we need to be + # conservative here. + total_numel = self.numel * self.reduction_numel + + from .simd import SIMDScheduling + + if SIMDScheduling.can_use_32bit_indexing(total_numel, buffers): + # Fused address expressions can overflow int32 even when + # numel/storage_size are within range, so check them directly. + if self.any_index_expr_overflows_int32(): + return torch.int64 + return torch.int32 + return torch.int64 + + @cache_on_self + def any_index_expr_overflows_int32(self) -> bool: + """Return True if any MemoryDep addressing expression can overflow int32. + + Two complementary checks are applied to each index: + + - Constant offset: the index evaluated at the origin (every loop + variable set to 0) must lie within [-2**31, 2**31 - 1]. This is cheap + and independent of loop-var ranges, so it also covers deps whose sizes + are symbolic. + - Variable-scaled bound: the index bounded over the actual iteration + range of every loop variable must not exceed 2**31 - 1. This catches + overflow such as the `V * x0` synthesized when unrolled chunked-loop + slices are stitched into one pointwise kernel (`V` a per-chunk stride, + `x0` spanning the fused numel); unlike a `numel * max_stride` proxy it + is exact, since a stride on a size-1 dim multiplies an empty range and + drops out. Deps with a symbolic loop-var size, or whose bound is + unknown/indirect (infinite), are skipped here and left to the + constant-offset and per-buffer storage-size checks. + """ + from torch.utils._sympy.numbers import int_oo + from torch.utils._sympy.value_ranges import bound_sympy, ValueRanges + + int32_max = sympy.Integer(2**31 - 1) + int32_min = sympy.Integer(-(2**31)) + for node in self.scheduler_nodes(): + for dep in itertools.chain(node.read_writes.reads, node.read_writes.writes): + if not isinstance(dep, MemoryDep): + continue + index = dep.index + if not isinstance(index, sympy.Expr): + continue + + # Constant offset (index at the origin). + try: + const_part = index.subs( + {s: sympy.Integer(0) for s in index.free_symbols} + ) + if isinstance(const_part, sympy.Expr) and ( + const_part > int32_max or const_part < int32_min + ): + return True + except (ZeroDivisionError, TypeError, ValueError): + pass + + # Variable-scaled bound over concrete loop-var ranges. A + # ValueRanges bound must be concrete, so skip a dep with any + # symbolic loop-var size. + sizes = dep.size + if any(getattr(s, "free_symbols", None) for s in sizes): + continue + try: + var_ranges = { + var: ValueRanges(0, max(int(size) - 1, 0)) + for var, size in zip(dep.var_names, sizes) + } + upper = bound_sympy(index, var_ranges).upper + if ( + isinstance(upper, sympy.Expr) + and not upper.has(int_oo, sympy.oo) + and upper > int32_max + ): + return True + except (ZeroDivisionError, TypeError, ValueError): + continue + return False + + def get_reduction_hint( + self, tiling_scores: dict[str, sympy.Expr] | None = None + ) -> ReductionHint: + if tiling_scores is None: + tiling_scores = self.tiling_scores + reductions = self.reduction_nodes() + if len(reductions) > 0: + hints = [self.reduction_hint(n) for n in reductions] + if hints.count(hints[0]) == len(hints): + reduction_hint_val = hints[0] + else: + reduction_hint_val = ReductionHint.DEFAULT + + if ( + reduction_hint_val == ReductionHint.INNER + and self.has_non_contiguous_pw_in_reduction_kernel() + ): + reduction_hint_val = ReductionHint.DEFAULT + + # Upgrade DEFAULT to INNER for inner reductions based on tiling scores + if ( + reduction_hint_val == ReductionHint.DEFAULT + and tiling_scores is not None + and "x" in tiling_scores + and "r0_" in tiling_scores + ): + if tiling_scores_suggest_inner_reduction( + tiling_scores, self.reduction_numel + ): + reduction_hint_val = ReductionHint.INNER + else: + reduction_hint_val = ReductionHint.DEFAULT + return reduction_hint_val + + @cache_on_self + def buffer_read_counts(self) -> dict[str, int]: + """Counts how many times each buffer is read within the kernel""" + read_counts: dict[str, int] = collections.defaultdict(int) + + for node in self.scheduler_nodes(): + # node.read_writes.reads contains MemoryDep objects for each read + for read_dep in node.read_writes.reads: + read_counts[read_dep.name] += 1 + + return dict(read_counts) # Convert defaultdict to regular dict + + def has_non_contiguous_pw_in_reduction_kernel(self) -> bool: + pointwise_nodes = [ + n + for n in self.scheduler_nodes() + if not n.is_reduction() + and n.group[1][0] == self.numel * self.reduction_numel + ] + for node in pointwise_nodes: + # An index can be an integer when loading a random seed. + if not all( + not isinstance(dep, MemoryDep) + or dep.is_contiguous() + or isinstance(dep.index, (sympy.Integer, int)) + or dep.stride1_for_last_dim() + for dep in itertools.chain( + node.read_writes.reads, node.read_writes.writes + ) + ): + return True + return False + + @staticmethod + def reduction_hint(node: Any) -> ReductionHint: + if not node.is_reduction(): + raise AssertionError("expected node to be a reduction") + if node.node.data.reduction_hint != ReductionHint.INNER and all( + dep.is_contiguous() + for dep in itertools.chain(node.read_writes.reads, node.read_writes.writes) + ): + return ReductionHint.INNER + else: + return node.node.data.reduction_hint + + def memory_stats( + self, groups_dict: dict[str, sympy.Expr] | None = None + ) -> MemoryStats: + """Analysis to generate features that can be used in heuristics""" + if groups_dict is None: + groups = (self.numel, self.reduction_numel) + elif groups_dict.keys() == OrderedSet(["x", "r0_"]): + groups = (groups_dict["x"], groups_dict["r0_"]) + else: + raise NotImplementedError(f"groups_dict={groups_dict!r}") + result = self._stats_cache.get(groups) + if result is None: + self._stats_cache[groups] = result = MemoryStats.compute( + MemoryEstimator(self, groups) + ) + return result + + +class MemoryEstimator: + """ + Estimate various properties of the kernel for use in heuristics. + We simulate the memory effects of CSE/buffer elimination in codegen. + """ + + kernel_sizes: tuple[sympy.Expr, ...] + outside_loop: MemoryEstimate + loops: list[MemoryEstimate] + persistent: MemoryEstimate + symbols: list[sympy.Symbol] + + def __init__(self, features: SIMDKernelFeatures, groups: Sequence[sympy.Expr]): + self.features = features + self.inside_reduction = features.is_reduction() + self.store_buffer_names: OrderedSet[str] = OrderedSet() + self.must_keep_buffers: OrderedSet[str] = OrderedSet() + self.num_reductions_dims = 1 + self.groups = groups + self.symbols = [make_symbol(SymT.INDEX, i) for i in range(len(groups))] + # We are doing two estimates simultaneously: + # 1) the first is a for a non-persistent (aka looped) reduction, using self.outside_loop/self.loops + # we add an item to loops each corresponding to each reduction loop in the kernel + # outside_loop is only used for broadcasting or point-wise ops that don't use the reduction dimension + # 2) the second is for a persistent kernel, using self.persistent + # persistent kernels don't have loops, so we only have one MemoryEstimate() + # for point-wise ops the two estimates will be the same, they matter for reductions only + self.outside_loop = MemoryEstimate() + self.loops = [MemoryEstimate()] + self.persistent = MemoryEstimate() + self.simulate_codegen() + self.remove_kernel_local() + + def simulate_codegen(self) -> None: + from .simd import SIMDKernel + + kernel_size_outside_loop = (*self.groups[:-1], sympy.S.One) + kernel_size_inside_loop = tuple(self.groups) + self.kernel_sizes = kernel_size_inside_loop + + for node in self.features.node_schedule: + if node is DisableReduction: + self.inside_reduction = False + self.kernel_sizes = kernel_size_outside_loop + continue + elif node is EnableReduction: + self.inside_reduction = True + self.kernel_sizes = kernel_size_inside_loop + self.loops.append(MemoryEstimate()) + continue + if not isinstance(node, SchedulerNode): + raise AssertionError(f"expected SchedulerNode, got {type(node)}") + rw = extract_loop_body_with_args( + node._body, + SIMDKernel.map_kernel_groups_to_node_sizes( + self.kernel_sizes, node.get_ranges(), self.set_ranges + ), + dict(zip(self.symbols, self.kernel_sizes)), + ) + + for dep in rw._reads: + if not isinstance(dep, MemoryDep): + continue + dep = dep.simplify_with_ranges() + if not self.persistent.writes.get(dep.name): # cache miss? + self.persistent.reads[dep.name].add(dep) + # the cache behavior of looped kernels is more complex than the persistent case above + # some operations are lifted outside the loop (if they don't use the reduction dimension) + # other operations are inside the loop, and can only be reused within the same loop + if not ( + self.outside_loop.writes.get(dep.name) + or self.loops[-1].writes.get(dep.name) + ): + self.scope(dep).reads[dep.name].add(dep) + if dep.name in self.store_buffer_names and self.loops[-1].reads.get( + dep.name + ): + self.must_keep_buffers.add(dep.name) + + for dep in rw._writes: + if not isinstance(dep, MemoryDep): + continue + dep = dep.simplify_with_ranges() + self.store_buffer_names.add(dep.name) + self.persistent.writes[dep.name].add(dep) + self.scope(dep).writes[dep.name].add(dep) + + def remove_kernel_local(self) -> None: + # Remove any kernel-local buffers + fused_node_names = OrderedSet( + [n.get_name() for n in self.features.scheduler_nodes()] + ) + for name in self.store_buffer_names: + if not self.persistent.reads.get( + name + ) and V.graph.scheduler.can_buffer_be_removed_through_fusion( + name, fused_node_names + ): + self.persistent.remove(name) + if name not in self.must_keep_buffers: + # we can also remove this from the looped kernel + self.outside_loop.remove(name) + for loop in self.loops: + loop.remove(name) + + if not self.loops[-1]: + self.loops.pop() # for pointwise ops + + def scope(self, dep: MemoryDep) -> MemoryEstimate: + """Determine how a read/write should be categorized""" + if self.inside_reduction and ( + self.has_reduction_var(dep.index) or dep.is_indirect() + ): + return self.loops[-1] + return self.outside_loop + + def has_reduction_var(self, index: sympy.Expr) -> bool: + for sym in self.symbols[-self.num_reductions_dims :]: + if isinstance(sym, sympy.Symbol) and sym in index.free_symbols: + return True + return False + + def set_ranges(self, *lengths: list[list[sympy.Expr]]) -> list[list[sympy.Expr]]: + if len(self.kernel_sizes) != len(lengths): + raise AssertionError( + f"expected len(kernel_sizes) == len(lengths), got " + f"{len(self.kernel_sizes)} != {len(lengths)}" + ) + return [ + self.make_flat_range(sym, numel, length) + for sym, numel, length in zip(self.symbols, self.kernel_sizes, lengths) + ] + + @staticmethod + def make_flat_range( + sym: sympy.Symbol, numel: sympy.Expr, lengths: list[sympy.Expr] + ) -> list[sympy.Expr]: + if len(lengths) == 1 and numel == lengths[0]: + return [sym] + divisor = sympy.S.One + itervars = [] + for length in reversed(lengths): + if V.graph.sizevars.statically_known_equals(divisor * length, numel): + expr = FloorDiv(sym, divisor) + else: + expr = ModularIndexing(sym, divisor, length) + itervars.append(expr) + divisor = divisor * length + return [*reversed(itervars)] + + +@dataclasses.dataclass +class MemoryEstimate: + """Tracks the memory usage of a single loop in the generated kernel""" + + reads: dict[str, OrderedSet[MemoryDep]] = dataclasses.field( + default_factory=functools.partial(collections.defaultdict, OrderedSet) + ) + writes: dict[str, OrderedSet[MemoryDep]] = dataclasses.field( + default_factory=functools.partial(collections.defaultdict, OrderedSet) + ) + + def remove(self, name: str) -> None: + self.reads.pop(name, None) + self.writes.pop(name, None) + + def __bool__(self) -> bool: + return bool(self.reads or self.writes) + + def __repr__(self) -> str: + return f"""MemoryEstimate( + reads={[*itertools.chain.from_iterable(self.reads.values())]!r}, + writes={[*itertools.chain.from_iterable(self.writes.values())]!r} + )""" + + +@dataclasses.dataclass +class StatsForDim: + """Memory usage stats for a block dimension in the generated kernel (different from user dimensions)""" + + # the number of load/store ops + count_per_thread_contiguous: int = 0 + count_per_thread_broadcast: int = 0 + count_per_thread_non_contiguous: int = 0 # excludes broadcast + + # total bytes in each load/store op for a single element + bytes_per_thread_contiguous: int = 0 + bytes_per_thread_broadcast: int = 0 + bytes_per_thread_non_contiguous: int = 0 # excludes broadcast + + # total bytes read by entire kernel + bytes_contiguous_or_broadcast: sympy.Expr = sympy.S.Zero + bytes_non_contiguous: sympy.Expr = sympy.S.Zero + + def __add__(self, other: typing.Self) -> StatsForDim: + return StatsForDim( + count_per_thread_contiguous=self.count_per_thread_contiguous + + other.count_per_thread_contiguous, + count_per_thread_broadcast=self.count_per_thread_broadcast + + other.count_per_thread_broadcast, + count_per_thread_non_contiguous=self.count_per_thread_non_contiguous + + other.count_per_thread_non_contiguous, + bytes_per_thread_contiguous=self.bytes_per_thread_contiguous + + other.bytes_per_thread_contiguous, + bytes_per_thread_broadcast=self.bytes_per_thread_broadcast + + other.bytes_per_thread_broadcast, + bytes_per_thread_non_contiguous=self.bytes_per_thread_non_contiguous + + other.bytes_per_thread_non_contiguous, + bytes_contiguous_or_broadcast=self.bytes_contiguous_or_broadcast + + other.bytes_contiguous_or_broadcast, + bytes_non_contiguous=self.bytes_non_contiguous + other.bytes_non_contiguous, + ) + + @property + def count_per_thread(self) -> int: + return ( + self.count_per_thread_contiguous + + self.count_per_thread_broadcast + + self.count_per_thread_non_contiguous + ) + + @property + def bytes_per_thread(self) -> int: + return ( + self.bytes_per_thread_contiguous + + self.bytes_per_thread_broadcast + + self.bytes_per_thread_non_contiguous + ) + + @property + def bytes(self) -> sympy.Expr: + return self.bytes_contiguous_or_broadcast + self.bytes_non_contiguous + + @property + def contiguous_score(self) -> float: + return 1.0 - self.count_per_thread_non_contiguous / max( + self.count_per_thread, 1 + ) + + +@dataclasses.dataclass +class StatsForLoop: + """Memory usage stats for single loop in the generated kernel""" + + # load/store ops + count_per_thread: int = 0 + bytes_per_thread: int = 0 + + def __add__(self, other: typing.Self) -> StatsForLoop: + return StatsForLoop( + count_per_thread=self.count_per_thread + other.count_per_thread, + bytes_per_thread=self.bytes_per_thread + other.bytes_per_thread, + ) + + +@dataclasses.dataclass +class StatsForReadsOrWrites: + """Memory usage stats that are collected for reads/writes/both""" + + dim: list[StatsForDim] + loop: list[StatsForLoop] + # total bytes contiguous in any dimension + bytes_contiguous_or_broadcast: sympy.Expr = sympy.S.Zero + bytes_non_contiguous: sympy.Expr = sympy.S.Zero + + def __add__(self, other: typing.Self) -> StatsForReadsOrWrites: + if len(self.dim) != len(other.dim): + raise AssertionError( + f"expected len(self.dim) == len(other.dim), got " + f"{len(self.dim)} != {len(other.dim)}" + ) + if len(self.loop) != len(other.loop): + raise AssertionError( + f"expected len(self.loop) == len(other.loop), got " + f"{len(self.loop)} != {len(other.loop)}" + ) + return StatsForReadsOrWrites( + dim=[a + b for a, b in zip(self.dim, other.dim)], + loop=[a + b for a, b in zip(self.loop, other.loop)], + bytes_contiguous_or_broadcast=self.bytes_contiguous_or_broadcast + + self.bytes_contiguous_or_broadcast, + bytes_non_contiguous=self.bytes_non_contiguous + other.bytes_non_contiguous, + ) + + @property + def count_per_thread(self) -> int: + return self.dim[0].count_per_thread + + @property + def bytes_per_thread(self) -> int: + return self.dim[0].bytes_per_thread + + @property + def bytes(self) -> sympy.Expr: + return self.bytes_contiguous_or_broadcast + self.bytes_non_contiguous + + @classmethod + def compute( + cls, + loop_deps: list[dict[str, OrderedSet[MemoryDep]]], + index_symbols: list[sympy.Symbol], + ) -> typing.Self: + ndim = len(index_symbols) + result = cls(dim := [StatsForDim() for _ in range(ndim)], []) + for dep_group in loop_deps: + result.loop.append(loop_stats := StatsForLoop()) + for name, deps in dep_group.items(): + if not deps: + raise AssertionError(f"expected non-empty deps for {name}") + contiguous_or_broadcast = [True] * ndim + numel = sympy.S.Zero + itemsize = V.graph.get_dtype(name).itemsize + loop_stats.count_per_thread += len(deps) + loop_stats.bytes_per_thread += itemsize * len(deps) + for dep in deps: + strides: list[sympy.Expr] = V.graph.sizevars.stride_vars( + dep.index, index_symbols + ) + for i in range(ndim): + if V.graph.sizevars.statically_known_equals(strides[i], 1): + dim[i].count_per_thread_contiguous += 1 + dim[i].bytes_per_thread_contiguous += itemsize + elif ( + V.graph.sizevars.statically_known_equals(strides[i], 0) + and not dep.is_indirect() + ): + dim[i].count_per_thread_broadcast += 1 + dim[i].bytes_per_thread_broadcast += itemsize + else: + dim[i].count_per_thread_non_contiguous += 1 + dim[i].bytes_per_thread_non_contiguous += itemsize + contiguous_or_broadcast[i] = False + numel += dep.get_numel() + if len(deps) > 1: + # can't read more elements than exist in the buffer + numel = Min(numel, V.graph.get_numel(name)) + nbytes = numel * itemsize + for i in range(ndim): + if contiguous_or_broadcast[i]: + dim[i].bytes_contiguous_or_broadcast += nbytes + else: + dim[i].bytes_non_contiguous += nbytes + if any(contiguous_or_broadcast): + result.bytes_contiguous_or_broadcast += nbytes + else: + result.bytes_non_contiguous += nbytes + if len(result.loop) > 1: + # the first loop represent the "outside of the loop" compute which could be long lived + result.loop = [result.loop[0] + x for x in result.loop[1:]] + return result + + +@dataclasses.dataclass +class StatsForKernelType: + """Memory usage stats that are collected for both persistent and looped kernels""" + + reads: StatsForReadsOrWrites + writes: StatsForReadsOrWrites + memory: StatsForReadsOrWrites + + @classmethod + def compute( + cls, loops: list[MemoryEstimate], estimator: MemoryEstimator + ) -> typing.Self: + reads = StatsForReadsOrWrites.compute( + [loop.reads for loop in loops], estimator.symbols + ) + writes = StatsForReadsOrWrites.compute( + [loop.writes for loop in loops], estimator.symbols + ) + return cls( + reads=reads, + writes=writes, + memory=reads + writes, + ) + + +@dataclasses.dataclass +class MemoryStats: + """Memory usage stats collected for each generated kernel""" + + persistent: StatsForKernelType + looped: StatsForKernelType + + def get(self, persistent: bool) -> StatsForKernelType: + return self.persistent if persistent else self.looped + + @classmethod + def compute(cls, estimator: MemoryEstimator) -> typing.Self: + persistent = StatsForKernelType.compute([estimator.persistent], estimator) + if len(estimator.loops) == 1 and not ( + estimator.outside_loop and estimator.loops[0] + ): + looped = persistent # loops/persistent is the same in this common case + else: + looped = StatsForKernelType.compute( + [estimator.outside_loop, *estimator.loops], estimator + ) + return cls( + persistent=persistent, + looped=looped, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/subgraph.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/subgraph.py new file mode 100644 index 0000000000000000000000000000000000000000..5e130f4dcbb6b63d00ac85323fa1f85fc35862d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/subgraph.py @@ -0,0 +1,615 @@ +import contextlib +import functools +import itertools +import logging +from collections.abc import Callable +from typing import Any + +import sympy + +import torch +import torch._inductor.config as config +from torch._dynamo.utils import counters +from torch._inductor import ir +from torch._inductor.autotune_process import ( + SubgraphCPUBenchmarkRequest, + SubgraphGPUBenchmarkRequest, + TensorMeta, +) +from torch._inductor.codegen.common import KernelTemplate +from torch._inductor.ir import ( + Buffer, + FixedLayout, + get_free_symbols, + get_symbolic_inputs, + gm_original_output_strides, + ir_node_to_tensor, + Layout, +) +from torch._inductor.runtime.benchmarking import benchmarker +from torch._inductor.utils import do_bench_using_profiling +from torch._inductor.virtualized import V +from torch.utils._ordered_set import OrderedSet + + +log = logging.getLogger(__name__) + + +def inline_subgraph_to_ir_nodes( + gm: torch.fx.GraphModule, inputs: list[Any], name: str +) -> Any: + """Inline a subgraph by converting its FX operations to individual IR nodes. + + This converts a subgraph to multiple ComputedBuffer nodes (fusable), + enabling epilogue fusion with subsequent operations. + + Returns: + TensorBox containing the final operation result as individual IR nodes + """ + from torch._inductor.lowering import process_subgraph_nodes + + # Temporarily switch V.graph.module to subgraph during processing; restore to prevent IR nodes added to wrong graph + original_module = V.graph.module + try: + V.graph.module = gm + return process_subgraph_nodes(gm, inputs) + finally: + V.graph.module = original_module + + +class SubgraphChoiceCaller(ir.ChoiceCaller): + """ + Represents a Subgraph Autotuning choice, and the subgraph can be any arbitrary + GraphModule. Compiles the Subgraph down to a module for benchmarking. + """ + + def __init__( + self, + name: str, + input_nodes: list[Buffer], + layout: Layout, + description: str, + make_fx_graph: Callable[..., Any], + input_gen_fns: dict[int, Callable[[Any], torch.Tensor]] | None = None, + ) -> None: + super().__init__(name, input_nodes, layout, description) + + # Create inputs for tracing and benchmarking: + # - trace_inputs: Always use symbolic inputs for tracing so the graph works + # for any size at runtime. This correctly captures shape-dependent operations + # like x * x.shape[0]. + # - benchmark_inputs: Use input_gen_fns if provided (for range-specific benchmarks) + # or concrete inputs from ir_node_to_tensor with guard_shape=False. + trace_inputs = [] + self.benchmark_inputs = [] + with V.fake_mode: + for i, inp in enumerate(self.input_nodes): + # Here there will be no unbacked symbols, as SubgraphBuffer does not support them + if len(get_free_symbols(inp.get_size(), unbacked_only=True)) != 0: + raise AssertionError("expected no unbacked symbols in input size") + if len(get_free_symbols(inp.get_stride(), unbacked_only=True)) != 0: + raise AssertionError("expected no unbacked symbols in input stride") + + inp.data.freeze_layout() # type: ignore[attr-defined] + + # Always use symbolic inputs for tracing + trace_inputs.append(ir_node_to_tensor(inp)) + + # Use input_gen_fn for benchmarking if provided, otherwise concrete sizes + if input_gen_fns is not None and i in input_gen_fns: + self.benchmark_inputs.append(input_gen_fns[i](inp)) + else: + self.benchmark_inputs.append( + ir_node_to_tensor(inp, replace_symbols_with_hints=True) + ) + + # Trace with symbolic inputs for guard detection + self.gm = make_fx_graph(*trace_inputs) + gm_original_output_strides(self.gm) + # Store symbolic inputs for sym_input computation + self.example_inputs = trace_inputs + + self.sym_inputs = get_symbolic_inputs(self.input_nodes) + self.sym_input_values = self._compute_sym_input_values() + + # Cached decomposition info for range-based dispatch (set via cache_decomposition) + self.decomposition: Callable[..., Any] | None = None + self.decomposition_kwargs: dict[str, Any] = {} + # Config patches to apply during kernel codegen (e.g., coordinate_descent_tuning) + self.config_patches: dict[str, Any] = {} + # Cache compiled module to avoid recompiling on every benchmark call + self._compiled_module: Any = None + # Cache benchmark request for async autotuning + self._bmreq: ( + SubgraphGPUBenchmarkRequest | SubgraphCPUBenchmarkRequest | None + ) = None + + # Pre-compile only if using async pipelined autotuning + # Must happen in __init__ because compilation requires virtualized context (V.graph, V.debug) + if config.pipeline_max_autotune_gemm: + with V.fake_mode: + self._compiled_module = self._compile_for_benchmarking() + self._bmreq = self._create_benchmark_request() + + def _compute_sym_input_values(self) -> list[int]: + """Extract concrete dimension values for sym_inputs from benchmark_inputs. + + The compiled module expects symbolic dimension values as runtime arguments. + This maps each symbolic variable to its concrete value from the benchmark tensors. + Used for range based autotuning. + """ + sym_input_names = OrderedSet( + [s.name for s in self.sym_inputs if hasattr(s, "name")] + ) + + # Build mapping: symbolic dimension name -> concrete value + sym_name_to_value: dict[str, int] = {} + for inp_node, benchmark_inp in zip(self.input_nodes, self.benchmark_inputs): + if isinstance(benchmark_inp, torch.Tensor): + for sym_dim, actual_dim in zip( + inp_node.get_size(), benchmark_inp.shape + ): + if isinstance(sym_dim, sympy.Symbol): + sym_name_to_value[sym_dim.name] = int(actual_dim) + elif str(sym_dim) in sym_input_names: + sym_name_to_value[str(sym_dim)] = int(actual_dim) + + result = [] + for sym_var in self.sym_inputs: + if isinstance(sym_var, sympy.Symbol) and sym_var.name in sym_name_to_value: + result.append(sym_name_to_value[sym_var.name]) + else: + hint = V.graph.sizevars.shape_env.optimization_hint(sym_var, fallback=1) + result.append(int(hint)) + return result + + def cache_decomposition( + self, decomposition: Callable[..., Any], kwargs: dict[str, Any] + ) -> None: + """Cache decomposition function and kwargs for range-based dispatch lookup.""" + self.decomposition = decomposition + self.decomposition_kwargs = kwargs + + def __str__(self) -> str: + return f"SubgraphCaller({self.name})" + + def _compile_for_benchmarking(self) -> Any: + """Compile the subgraph for benchmarking, returns the compiled module.""" + from torch._inductor.graph import GraphLowering + + safe_name = self.name.replace("::", "_").replace(".", "_") + + # Symbolic inputs produce code with symbolic sizes resolved at runtime + # via sym_input_values. Without symbols (static shapes), compile with + # benchmark_inputs whose sizes match the actual benchmark tensors. + compile_inputs = ( + self.example_inputs if self.sym_inputs else self.benchmark_inputs + ) + log.debug("Benchmark compile %s: sym_inputs=%s", self.name, self.sym_inputs) + + if self.gm is None: + raise AssertionError("expected self.gm to be set") + bm_graph_lowering = GraphLowering( + gm=self.gm, + example_inputs=compile_inputs, + shape_env=V.graph._shape_env, + cpp_wrapper=V.graph.cpp_wrapper, + aot_mode=V.graph.aot_mode, + extern_node_serializer=V.graph.extern_node_serializer, + is_inference=V.graph.is_inference, + is_backward=V.graph.is_backward, + name=f"benchmark_{safe_name}", + ) + + for sym_inp in self.sym_inputs: + bm_graph_lowering.graph_inputs[sym_inp.name] = sym_inp + bm_graph_lowering.graph_input_names.append(sym_inp.name) + + with V.set_graph_handler(bm_graph_lowering): + # Apply config_patches during benchmarking (e.g., coordinate_descent_tuning) + # Also disable max_autotune to avoid nested autotuning + benchmark_config: dict[str, Any] = { + "max_autotune": False, + "max_autotune_gemm": False, + "max_autotune_gemm_backends": "ATEN", + "benchmark_fusion": False, + "pipeline_max_autotune_gemm": False, + **self.config_patches, + } + with config.patch(benchmark_config): + bm_graph_lowering.run(*compile_inputs) + return bm_graph_lowering.compile_to_module() + + def _create_benchmark_request( + self, + ) -> SubgraphGPUBenchmarkRequest | SubgraphCPUBenchmarkRequest: + """Create a benchmark request for async autotuning.""" + if self._compiled_module is None: + raise AssertionError( + "Module must be compiled before creating benchmark request" + ) + input_tensor_meta = TensorMeta.from_irnodes(self.input_nodes) + output_tensor_meta = TensorMeta.from_irnodes(self.layout) + + if self.layout.device.type == "cpu": + bmreq_cls = SubgraphCPUBenchmarkRequest + else: + bmreq_cls = SubgraphGPUBenchmarkRequest + + return bmreq_cls( + kernel_name=self.name, + input_tensor_meta=input_tensor_meta, + output_tensor_meta=output_tensor_meta, + extra_args=tuple(), + module_path=self._compiled_module.__file__, + module_cache_key=self._compiled_module.key, + sym_input_values=self.sym_input_values, + ) + + @property + def bmreq( + self, + ) -> SubgraphGPUBenchmarkRequest | SubgraphCPUBenchmarkRequest: + """Benchmark request for async autotuning. Pre-compiled when pipeline_max_autotune_gemm is enabled.""" + if self._bmreq is None: + raise AssertionError( + "bmreq accessed but pipeline_max_autotune_gemm was not enabled during __init__" + ) + return self._bmreq + + def _ensure_compiled(self) -> None: + """Ensure the module is compiled. Used for lazy compilation in non-async path.""" + if self._compiled_module is None: + self._compiled_module = self._compile_for_benchmarking() + + def benchmark(self, *args: list[Any], out: torch.Tensor) -> float: + """Regular benchmarking: compile if needed, then use benchmarker.""" + self._ensure_compiled() + bm_func = self._compiled_module.call + sym_inputs = self.sym_input_values + + def fn() -> Any: + return bm_func([*sym_inputs, *args]) + + if self._benchmark_with_cudagraphs: + return benchmarker.benchmark_gpu_with_cuda_graph(fn) + + if config.profile_bandwidth_with_do_bench_using_profiling: + return do_bench_using_profiling(fn) + return benchmarker.benchmark( + fn, + device=benchmarker.infer_device(*sym_inputs, *args), + ) + + def benchmark_collective(self, *args: list[Any], out: torch.Tensor) -> None: + """Run once for collective benchmarking (barrier sync handled by caller).""" + self._ensure_compiled() + self._compiled_module.call([*self.sym_input_values, *args]) + + def hash_key(self) -> str: + if self.gm is None: + raise AssertionError("expected self.gm to be set") + return "-".join( + [ + self.name.rsplit("_", 1)[0], + *[str(inp.get_size()) for inp in self.input_nodes], + *[str(inp.get_stride()) for inp in self.input_nodes], + str(self.gm.graph), + ] + ) + + def output_node(self) -> ir.TensorBox: + if self.gm is None: + raise AssertionError("expected self.gm to be set") + return ir.TensorBox.create( + ir.SubgraphBuffer( + layout=self.layout, + input_nodes=self.input_nodes, + gm=self.gm, + example_inputs=self.example_inputs, + subgraph_name=self.name, + config_patches=self.config_patches if self.config_patches else None, + ) + ) + + def info_dict(self) -> dict[str, Any]: + """Information returned here is logged to the autotune log file when that is enabled.""" + return { + "backend": "subgraph", + "kernel_name": self.name, + } + + def autoheuristic_id(self) -> str: + return f"subgraph_{self.name}" + + +class SubgraphTemplate(KernelTemplate): + """ + A template for subgraph evaluation to be used in autotuning. + + This class allows creating customized subgraphs that can be appended + as choices during the autotuning process, enabling the selection of + optimal implementations for complex operations. + """ + + index_counter = itertools.count() + + def __init__( + self, + name: str, + ): + """ + Initialize a subgraph template. + + Args: + name: The name of this template + graph: The FX graph + """ + super().__init__(name=name) + + def generate( # type: ignore[override] + self, + name: str, + input_nodes: list[Buffer], + layout: Layout, + make_fx_graph: Callable[..., Any], + description: str = "", + input_gen_fns: dict[int, Callable[[Any], torch.Tensor]] | None = None, + **kwargs: Any, + ) -> SubgraphChoiceCaller: + """ + Generate a SubgraphChoiceCaller instance for autotuning. + + Args: + name: The name for this subgraph choice + input_nodes: List of input nodes to the subgraph + layout: Memory layout information for the output + make_fx_graph: Callable that creates the FX graph for this subgraph + description: Optional description of this choice + input_gen_fns: Optional dict mapping input indices to tensor generators + **kwargs: Additional keyword arguments + + Returns: + SubgraphChoiceCaller: A callable object that can be used for autotuning + """ + + return SubgraphChoiceCaller( + name=f"{name}_{next(SubgraphTemplate.index_counter)}", + input_nodes=input_nodes, + layout=layout, + description=description, + make_fx_graph=make_fx_graph, + input_gen_fns=input_gen_fns, + ) + + def generate_custom_op_choices( + self, + name: str, + decompositions: list[Callable[..., Any]], + input_nodes: list[Buffer], + non_tensor_args: list[dict[str, Any]], + default_impl: Callable[..., Any] | None = None, + input_gen_fns: dict[int, Callable[[Any], torch.Tensor]] | None = None, + config_patches_list: list[dict[str, Any]] | None = None, + ) -> list[SubgraphChoiceCaller]: + """ + Generate multiple SubgraphChoiceCaller instances for custom op autotuning. + + This method extends SubgraphTemplate to support custom op decompositions, + allowing multiple implementations to compete in autotuning. + + Args: + name: Base name for the choices + decompositions: List of decomposition functions to compete in autotuning + input_nodes: List of tensor inputs. All tensor arguments must be passed here. + non_tensor_args: List of non-tensor kwargs only, one dict per corresponding decomposition. + default_impl: Default implementation for layout inference + input_gen_fns: Optional dict mapping input indices to tensor generators + config_patches_list: Optional list of config patches per decomposition + + Returns: + List of SubgraphChoiceCaller instances for autotuning + """ + if not decompositions: + return [] + + if len(decompositions) != len(non_tensor_args): + raise AssertionError( + f"decompositions and non_tensor_args must have same length, " + f"got {len(decompositions)} decompositions and {len(non_tensor_args)} kwargs" + ) + + # Default to empty config_patches if not provided + if config_patches_list is None: + config_patches_list = [{} for _ in decompositions] + + # Infer layouts and ensure layout consistency for fair autotuning comparison + layouts = [ + self._infer_custom_op_layout( + input_nodes, decomp, kwargs, default_impl, input_gen_fns + ) + for decomp, kwargs in zip(decompositions, non_tensor_args) + ] + + # Validate all decompositions produce equivalent layouts for fair comparison + self._validate_layout_equivalence(name, decompositions, layouts) + layout = layouts[0] # All layouts are now validated to be equivalent + + choices: list[SubgraphChoiceCaller] = [] + for decomp, decomp_kwargs, config_patches in zip( + decompositions, non_tensor_args, config_patches_list + ): + # Create make_fx_graph function for this decomposition + # Uses error_on_new_guards to detect impls that add guards + from torch.fx.experimental.symbolic_shapes import _ShapeEnvGuardError + + def make_fx_graph( + *args: Any, + decomp: Callable[..., Any] = decomp, + decomp_kwargs: dict[str, Any] = decomp_kwargs, + ) -> Any: + # decomp_kwargs contains all merged parameters: CustomOpConfig params + runtime kwargs + + from torch.fx.experimental.proxy_tensor import make_fx + + from ..decomposition import select_decomp_table + + decomposition_table = select_decomp_table() + shape_env = V.fake_mode.shape_env + + # Use error_on_new_guards to detect impls that add guards during tracing + guard_ctx = ( + shape_env.error_on_new_guards() + if shape_env is not None + else contextlib.nullcontext() + ) + with guard_ctx: + return make_fx( + functools.partial(decomp, **decomp_kwargs), + decomposition_table=decomposition_table, + tracing_mode="symbolic", + )(*args) + + # Generate descriptive name for this variant + variant_name = self._generate_variant_name(decomp, decomp_kwargs) + + # Try to create choice; skip if it adds guards + try: + choice = self.generate( + name=f"{name}_{variant_name}", + input_nodes=input_nodes, + layout=layout, + make_fx_graph=make_fx_graph, + description=f"CustomOp {decomp.__name__}", + input_gen_fns=input_gen_fns, + ) + except _ShapeEnvGuardError: + log.info( + "Skipping decomposition %s: adds guards during tracing", + decomp.__name__, + ) + counters["inductor"]["custom_op_decomp_guard_skips"] += 1 + continue + + # Cache decomposition info for range-based dispatch + choice.cache_decomposition(decomp, decomp_kwargs) + # Store config_patches for this choice + choice.config_patches = config_patches + choices.append(choice) + + return choices + + def _generate_variant_name( + self, decomp: Callable[..., Any], kwargs: dict[str, Any] + ) -> str: + """Generate a descriptive name for a decomposition variant with its parameters.""" + import re + + base_name = decomp.__name__ + if not kwargs: + return base_name + + def sanitize_value(v: Any) -> str: + """Convert a value to a valid Python identifier component.""" + s = str(v) + # Replace invalid characters with underscores + s = re.sub(r"[^a-zA-Z0-9_]", "_", s) + # Ensure it doesn't start with a digit + if s and s[0].isdigit(): + s = "_" + s + return s + + param_suffix = "_".join( + f"{k}_{sanitize_value(v)}" for k, v in sorted(kwargs.items()) + ) + return f"{base_name}_{param_suffix}" + + def _validate_non_tensor_kwargs(self, kwargs: dict[str, Any]) -> None: + """Validate that kwargs contains only non-tensor arguments.""" + for key, value in kwargs.items(): + if isinstance(value, (torch.Tensor, Buffer)): + raise AssertionError( + f"kwargs['{key}'] contains tensor {type(value)}. " + f"Tensor arguments should be in input_nodes, not kwargs. " + f"Only scalar/non-tensor parameters should be in kwargs." + ) + + def _validate_layout_equivalence( + self, + op_name: str, + decompositions: list[Callable[..., Any]], + layouts: list[Layout], + ) -> None: + """Ensure all layouts have consistent stride, device, dtype, and sizes for fair autotuning.""" + if not layouts: + return + + reference = layouts[0] + for i, layout in enumerate(layouts[1:], start=1): + if (layout.device, layout.dtype, layout.size, layout.stride) != ( + reference.device, + reference.dtype, + reference.size, + reference.stride, + ): + raise AssertionError( + f"Layout mismatch in custom op '{op_name}': " + f"decomposition '{decompositions[i].__name__}' produces " + f"({layout.device}, {layout.dtype}, {layout.size}, {layout.stride}) " + f"but '{decompositions[0].__name__}' produces " + f"({reference.device}, {reference.dtype}, {reference.size}, {reference.stride})" + ) + + def _infer_custom_op_layout( + self, + input_nodes: list[Buffer], + function_decomposition: Callable[..., Any], + kwargs: dict[str, Any], + default_impl: Callable[..., Any] | None = None, + input_gen_fns: dict[int, Callable[[Any], torch.Tensor]] | None = None, + ) -> Layout: + """Infer output layout for custom ops using the default implementation when available. + Note that the Subgraph assumes custom ops return exactly one tensor output. + TODO: Add support for multiple output custom ops. + """ + import functools + + from torch._inductor.virtualized import V + + # Assert kwargs contain only non-tensor arguments + self._validate_non_tensor_kwargs(kwargs) + + with V.fake_mode: + example_inputs = [] + for i, inp in enumerate(input_nodes): + if input_gen_fns and i in input_gen_fns: + fake_tensor = input_gen_fns[i](inp) + else: + raw_shape = inp.get_size() + concrete_shape = V.graph.sizevars.optimization_hints(raw_shape) + raw_stride = inp.get_stride() + concrete_stride = V.graph.sizevars.optimization_hints(raw_stride) + fake_tensor = torch.empty_strided( + concrete_shape, + concrete_stride, + dtype=inp.get_dtype(), + device=inp.get_device(), + ) + example_inputs.append(fake_tensor) + + fn = functools.partial(function_decomposition, **kwargs) + output = fn(*example_inputs) + + # Assert single output + if not isinstance(output, torch.Tensor): + raise AssertionError( + f"Expected single tensor output, got {type(output)}. " + f"Multi-output custom ops not yet supported in autotuning." + ) + + return FixedLayout( + device=output.device, + dtype=output.dtype, + size=output.shape, + stride=output.stride(), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton.py new file mode 100644 index 0000000000000000000000000000000000000000..83242f9290966fe6555eaa595bbfcb1893f41877 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton.py @@ -0,0 +1,8609 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import ast +import collections +import contextlib +import copy +import dataclasses +import functools +import itertools +import logging +import math +import operator +import os +import textwrap +from abc import abstractmethod +from collections.abc import Callable, Iterable, Sequence +from functools import lru_cache +from typing import Any, cast, TYPE_CHECKING, TypeVar + +import sympy +from sympy.printing.precedence import PRECEDENCE + +import torch +import torch._logging +import torch.utils._pytree as pytree +from torch._dynamo.device_interface import get_interface_for_device +from torch._dynamo.utils import identity, preserve_rng_state +from torch._prims_common import is_integer_dtype, type_to_dtype +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import ( + CeilDiv, + FloorDiv, + Min, + ModularIndexing, + TruncToFloat, + TruncToInt, +) +from torch.utils._triton import ( + get_triton_version, + has_triton_cpu_backend, + has_triton_package, + has_triton_stable_tma_api, +) + +from ...utils._sympy.symbol import free_symbol_is_type, prefix_str, symbol_is_type, SymT +from ...utils._sympy.value_ranges import ValueRanges +from .. import config, ir, metrics, utils +from ..async_compile import AsyncCompile +from ..codecache import code_hash, get_path, PyCodeCache, write_atomic +from ..debug import set_kernel_post_grad_provenance_tracing +from ..ops_handler import DefaultHandler +from ..runtime import triton_heuristics +from ..runtime.benchmarking import benchmarker +from ..runtime.hints import ( + AutotuneHint, + DeviceProperties, + get_warp_size, + native_matmul_persistent_rblock, + ReductionHint, + TRITON_MAX_BLOCK, + TRITON_MAX_RSPLIT, + TritonMeta, +) +from ..runtime.runtime_utils import get_max_y_grid, next_power_of_2 +from ..scheduler import ( + BaseSchedulerNode, + FusedExternTritonKernelSchedulerNode, + FusedSchedulerNode, + Scheduler, + SchedulerNode, +) +from ..shape_propagation import get_broadcasted_shape +from ..stream_utils import ( + coor_benchmark_device_idx, + coor_device_str, + get_raw_stream_name, +) +from ..utils import ( + _TMA_SUPPORTED_DTYPES, + cache_on_self, + DelayReplaceLine, + device_supports_fp64, + get_bounds_index_expr, + get_fused_kernel_name, + get_kernel_metadata, + is_welford_reduction, + Placeholder, + prefix_is_pointwise, + prefix_is_reduction, + sympy_dot, + sympy_product, + sympy_subs, + TMA_ALIGNMENT, + triton_type, + triton_version_uses_attrs_dict, + upcast_compute_type, +) +from ..virtualized import _ops as ops, ReductionType, StoreMode, V +from ..wrapper_benchmark import get_kernel_category_by_source_code +from .block_analysis import BlockPatternMatcher +from .common import ( + ArgName, + BackendFeature, + ConstexprArg, + CSE, + CSEVariable, + DeferredLine, + IndentedBuffer, + InplacedBuffer, + is_buffer_removed, + OpOverrides, + PythonPrinter, + RemovedArg, + SizeArg, + TensorArg, + WorkspaceArg, + WorkspaceZeroMode, +) +from .simd import ( + constant_repr, + DerivedIterationRangesRoot, + IterationRanges, + IterationRangesEntry, + IterationRangesRoot, + PartialAccumulate, + SIMDKernel, + SIMDScheduling, +) +from .simd_kernel_features import tiling_scores_suggest_inner_reduction +from .triton_utils import ( + config_of, + equal_1_arg_indices, + is_unaligned_buffer_name, + select_tile_hint, + should_unwrap_unspec_arg, + signature_to_meta, + use_uint8_triton_storage_for_cuda_float8_e4m3fn, +) +from .wrapper import SymbolicCallArg + + +if TYPE_CHECKING: + from types import ModuleType + + from torch._inductor.dtype_propagation import DtypePropagationOpsHandler + from torch.fx.experimental.symbolic_shapes import ShapeEnv + + from ..ir import IRNode + from .common import BlockShapeType + from .simd_kernel_features import SIMDKernelFeatures + + _T = TypeVar("_T") + +log = logging.getLogger(__name__) +perf_hint_log = torch._logging.getArtifactLogger(__name__, "perf_hints") +schedule_log = torch._logging.getArtifactLogger(__name__, "schedule") +fusion_log = torch._logging.getArtifactLogger(__name__, "fusion") +async_compile = AsyncCompile() + + +def get_triton_reduction_function(reduction_type): + use_helper = reduction_type in ("any", "max", "min", "prod", "fmax") + module = "triton_helpers" if use_helper else "tl" + if reduction_type in ("max", "min", "fmax"): + strict = ( + "_strict" + if config.strict_signed_zero and reduction_type in ("max", "min") + else "" + ) + return f"{module}.{reduction_type}2{strict}" + else: + return f"{module}.{reduction_type}" + + +def is_sympy_integer_like(expr: object): + """ + Is this expression a Sympy Integer or is it an integer sympy Expr + containing no free symbols. The latter case can happen with Identity expr. + """ + if not isinstance(expr, sympy.Expr): + return False + return isinstance(expr, sympy.Integer) or ( + expr.is_integer and len(expr.free_symbols) == 0 + ) + + +def _materialize_trunc_to_float_expr( + expr: sympy.Expr, dtype: torch.dtype +) -> sympy.Expr: + if not dtype.is_floating_point or not expr.has(TruncToInt): + return expr + + # Preserve float truncation semantics when materializing symbolic scalars + # into floating tensors. Casting to the kernel index dtype first can + # overflow before the requested floating-point conversion happens. Only + # rewrite truncations that are already participating in floating-point + # computation; integer subexpressions and predicates must keep exact + # integer semantics until the final materialization cast. + if expr.func is TruncToInt: + return TruncToFloat(*expr.args) + + def is_predicate_expr(node: sympy.Basic) -> bool: + return bool( + getattr(node, "is_Boolean", False) or getattr(node, "is_Relational", False) + ) + + def rewrite_float_subexpr(node: sympy.Expr) -> sympy.Expr: + if not node.has(TruncToInt): + return node + if node.func is TruncToInt: + return TruncToFloat(*node.args) + if is_predicate_expr(node) or node.is_integer: + return node + + new_args = tuple( + rewrite_float_subexpr(arg) + if isinstance(arg, sympy.Expr) and not is_predicate_expr(arg) + else arg + for arg in node.args + ) + if new_args == node.args: + return node + return node.func(*new_args) + + return rewrite_float_subexpr(expr) + + +class OpDtypeSupport: + """ + Some Triton ops such as libdevice and tl.math only support float32 and float64. + This class records which dtypes are supported by specific IR ops. + """ + + supported_dtypes: dict[str, OrderedSet[torch.dtype]] = {} + convert_outputs: dict[str, bool] = {} + + @classmethod + def register_upcast(cls, func: Callable[..., str], convert_output: bool) -> None: + op_name = func.__name__ + cls.supported_dtypes[op_name] = OrderedSet([torch.float32, torch.float64]) + cls.convert_outputs[op_name] = convert_output + + +@lru_cache(None) +def gen_attr_descriptor_import() -> str: + """ + import AttrsDescriptor if the triton version is new enough to have this + class defined. + """ + if not has_triton_package(): + return "" + + import triton.compiler.compiler + + # Note: this works because triton.compiler.compiler imports AttrsDescriptor from triton.backends.compiler + # When support for the legacy AttrsDescriptor is removed then this import path should be changed. + if hasattr(triton.compiler.compiler, "AttrsDescriptor"): + return "from triton.compiler.compiler import AttrsDescriptor" + else: + return "" + + +class TritonSymbols: + """ + Stores sympy.Symbol instances and constants associated with triton codegen. + """ + + reduction_types = OrderedSet([SymT.R0_INDEX, SymT.R1_INDEX]) + block_types = OrderedSet([SymT.XBLOCK, SymT.YBLOCK, SymT.ZBLOCK, *reduction_types]) + + block_offsets = { + symt: sympy.Symbol(f"{prefix_str[symt]}offset", integer=True, nonnegative=True) + for symt in block_types + } + + block_sizes = { + symt: sympy.Symbol( + f"{prefix_str[symt].upper()}BLOCK", integer=True, positive=True + ) + for symt in block_types + } + + @classmethod + def get_block_shape(cls, expr: sympy.Expr) -> BlockShapeType: + # return block shape of sympy Expression + # e.g., + # tmp13 = y1 + # tmp14 = x0 - tmp13 + # + # get_block_shape(y1) = (YBLOCK,1,1) + # get_block_shape(x0-tmp13) = (YBLOCK,XBLOCK,1) + + expr_shape: BlockShapeType = () + expr_vars = expr.free_symbols + for var in expr_vars: + if symbol_is_type(var, SymT.TMP): + cse_var = V.kernel.cse.varname_map[var.name] + var_shape = tuple(cse_var.shape) + elif symbol_is_type( + var, + ( + SymT.UNBACKED_INT, + SymT.SIZE, + SymT.PRECOMPUTED_SIZE, + SymT.INDEX, + SymT.FLOAT, + SymT.UNBACKED_FLOAT, + ), + ): + var_shape = () + else: + node = V.kernel.range_tree_nodes.get(var) + if node is None: + raise AssertionError(f"Unregistered range symbol: {var.name}") + tree = node.root + ndim = V.kernel.triton_tensor_ndim() + shape = ["1"] * ndim + if tree.tensor_dim is None: + # tree has no tensor dimension (e.g. no_x_dim mode), + # treat as scalar + var_shape = () + else: + shape[tree.tensor_dim] = str(cls.get_block_size(tree)) + var_shape = tuple(shape) + + # Union current variable shape + expr_shape = get_broadcasted_shape(expr_shape, var_shape) + + if expr_shape is None: + raise AssertionError("expr_shape must not be None") + + return expr_shape + + @classmethod + def get_block_size(cls, tree: IterationRanges) -> sympy.Expr: + return tree.root.block_size() + + @classmethod + def get_block_offset(cls, tree: IterationRanges) -> sympy.Expr: + return tree.root.block_offset() + + @classmethod + def mask_name_for_symbol( + cls, kernel: TritonKernel, symbol: sympy.Symbol + ) -> str | None: + # Prefer the owning range-tree entry when one exists instead of + # reconstructing xmask/rmask from the symbol prefix. + if (node := kernel.range_tree_nodes.get(symbol)) is not None: + return node.root.mask_name() + for symt in cls.block_types: + if symbol_is_type(symbol, symt): + return f"{prefix_str[symt]}mask" + return None + + @classmethod + def is_reduction_index_symbol( + cls, kernel: TritonKernel, symbol: sympy.Symbol + ) -> bool: + if (node := kernel.range_tree_nodes.get(symbol)) is not None: + return node.root.is_reduction + return symbol_is_type(symbol, cls.reduction_types) + + @classmethod + def has_reduction_index_symbol(cls, kernel: TritonKernel, expr: sympy.Expr) -> bool: + """Return whether any symbol in a composite block shape is reduction-owned.""" + return any( + cls.is_reduction_index_symbol(kernel, symbol) + for symbol in expr.free_symbols + ) + + +@dataclasses.dataclass +class IndexingOptions: + index_str: str + mask_vars: OrderedSet[str] + expand_str: str | None + _has_rindex: bool + index: sympy.Expr + expand_shape: Sequence[int | str] | None + + def has_mask(self) -> bool: + return bool(self.mask_vars) + + def has_indirect(self) -> bool: + return free_symbol_is_type(self.index, SymT.TMP) + + def has_rindex(self) -> bool: + return self._has_rindex + + def has_tmpmask(self) -> bool: + return any(str(mask).startswith("tmp") for mask in self.mask_vars) + + def has_rmask(self) -> bool: + # Outside the reduction loop we ignore reduction-tree masks, matching + # the set of axes that indexing generation treats as active. + return any( + isinstance(mask, str) and tree.is_reduction and tree.owns_mask(mask) + for tree in V.kernel.active_range_trees() + for mask in self.mask_vars + ) + + @property + def mask_str(self) -> str: + # The sorted call is added to make sure the order is still + # deterministic if self.mask_vars contains mix of string + # and TritonCSEVariable + return ( + " & ".join(sorted(map(str, self.mask_vars))) if self.mask_vars else "None" + ) + + +@dataclasses.dataclass +class BlockDescriptorOptions: + """ + This is a base class that describes a block descriptor used in Triton kernels. + It can be used to create either a tensor descriptor (with TensorDescriptorOptions) + or a block pointer (with BlockPtrOptions). + """ + + params: BlockParameters + constant_offset: sympy.Expr + order: list[int] + mask_vars: OrderedSet[str] + broadcast_shape: Sequence[sympy.Expr] + broadcasting_dims: list[bool] + final_shape: Sequence[sympy.Expr] + # If the BlockParameters have been sorted using a particular stride order + # transpose load / store blocks at runtime using the information in + # stride_sorter. + stride_sorter: BlockParameters.StrideSorter + _boundary_check: list[int] | None = None + # Can we safely lift the constructor + # to the top of the kernel? + can_lift: bool = False + + @property + def shape(self) -> list[sympy.Expr]: + return self.params.shape + + @property + def block_shape(self) -> list[sympy.Expr]: + return self.params.block_shape + + @property + def strides(self) -> list[sympy.Expr]: + return self.params.strides + + @property + def offsets(self) -> list[sympy.Expr]: + return self.params.offsets + + @classmethod + def create( + cls, + *, + params: BlockParameters, + constant_offset: sympy.Expr, + range_trees: list[IterationRangesRoot], + mask_vars: OrderedSet[str], + get_max_block: Callable[[str], int], + stride_sorter_cls: type[BlockParameters.StrideSorter], + can_lift: bool = False, + ) -> BlockDescriptorOptions: + """Helper to create a BlockDescriptorOptions instance""" + + sizevars = V.graph.sizevars + + def lookup_size(exprs: Iterable[sympy.Expr]) -> list[sympy.Expr]: + return [sizevars.lookup_precomputed_size(expr) for expr in exprs] + + # Look up precomputed sizes + params.shape = lookup_size(params.shape) + params.strides = lookup_size(params.strides) + + # Strip out dimensions of size 1. + # Size 1 dimensions are redundant since the triton kernel shape + # will be e.g. [YBLOCK, XBLOCK], so tl.reshape would just remove these + # dimensions anyway + singleton_dims = [ + sizevars.statically_known_equals(dim, 1) for dim in params.block_shape + ] + if all(singleton_dims): + # Handle a pure singletons, e.g. [1, 1] + singleton_dims[-1] = False + + # Drop singleton dimensions from the block descriptor. + params = params.remove_dims(singleton_dims) + + # Compute the final shape, adjusting for special kernel types. + final_shape = [TritonSymbols.get_block_size(tree) for tree in range_trees] + if V.kernel.no_x_dim: + if range_trees[0].prefix != "x": + raise AssertionError( + f"expected first range tree prefix to be 'x', got " + f"{range_trees[0].prefix!r}" + ) + final_shape.pop(0) + + # Check to see which of the final shape dimensions are included in this parameter + # e.g. if block shape is [XBLOCK // 2, XBLOCK % 2], but the kernel shape + # is [XBLOCK, R0_BLOCK], we need to expand the final shape to add reduction dims. + # We do this before broadcasting dimensions are removed so that the check + # below that compares the number of included dimensions to the kernel numels + # is correct + included_final_shape_dims = OrderedSet() + for expr in params.block_shape: + if isinstance(expr, sympy.Expr): + for sym in expr.free_symbols: + sym_str = str(sym).lower() + if prefix_is_reduction(sym_str) or prefix_is_pointwise(sym_str): + included_final_shape_dims.add(sym) + + reduction_ndim = V.kernel.num_reduction_dims + if ( + not V.kernel.inside_reduction + and len(included_final_shape_dims) == len(V.kernel.numels) - reduction_ndim + and V.kernel.features.is_reduction() + ): + # Need to expand rank to match the rank used inside the reduction loop + final_shape += [sympy.S.One] * reduction_ndim + + # Maybe reorder dimensions based on strides + # with tl.trans applied at load / store time + params, stride_sorter = params.maybe_sort_with_stride_order( + stride_sorter_cls=stride_sorter_cls, shape_env=V.graph._shape_env + ) + + # Strip out dimensions of stride 0. + # These will be restored with tl.broadcast_to. + broadcasting_dims = [ + sizevars.statically_known_equals(stride, 0) for stride in params.strides + ] + + # Record the post-broadcast shape before broadcasting dims are removed. + # The pre-broadcast shape is identical to this, except broadcasting dims are + # replaced with 1. + broadcast_shape = params.block_shape + + # Drop broadcasting dims from the block descriptor. + params = params.remove_dims(broadcasting_dims) + + try: + # Get permutation to sort strides in ascending order. + # This is used as the order argument in tl.make_block_ptr + order = utils.argsort_sym(V.graph._shape_env, params.strides) + except AssertionError: + # Symbolic shapes, failed to evaluate comparison expression + order = list(reversed(range(len(params.strides)))) + + result = cls( + params=params, + constant_offset=V.graph.sizevars.lookup_precomputed_size(constant_offset), + order=order, + mask_vars=mask_vars, + final_shape=final_shape, + broadcast_shape=broadcast_shape, + broadcasting_dims=broadcasting_dims, + stride_sorter=stride_sorter, + can_lift=can_lift, + ) + result.compute_boundary_check(get_max_block, range_trees) + return result + + def replace_offset( + self, expr: sympy.Expr, replacement: sympy.Expr, symt: SymT + ) -> sympy.Expr: + """ + Replaces instances of {symt}_offset with the new expression. + """ + roffset = TritonSymbols.block_offsets[symt] + return sympy_subs(expr, {roffset: replacement}) + + def remove_roffsets(self, expr: sympy.Expr) -> sympy.Expr: + for symt in TritonSymbols.reduction_types: + expr = self.replace_offset(expr, sympy.Integer(0), symt) + return expr + + def compute_boundary_check( + self, + get_max_block: Callable[[str], int], + range_trees: list[IterationRangesRoot], + ) -> None: + """List of indices to pass to tl.load(boundary_check=...)""" + sizevars = V.graph.sizevars + + # Substitute maximum block sizes in shape expressions. + # This works in multiple_of checks because block sizes are powers of 2. + block_to_max: dict[sympy.Expr, Any] = { + TritonSymbols.block_sizes[t.symt]: get_max_block(prefix_str[t.symt]) + for t in range_trees + } + + # Also see Note: Constant mask optimisation + # if ynumel / YBLOCK > max_ygrid, then the z dimension is used to handle + # the remaining programs that cannot fit into the y dimension. This means + # it's possible that more than the required number of programs are launched, + # possibly leading to out-of-bounds accesses. So even if ynumel divides YBLOCK, + # boundary checking is required in the dimensions that are based on YBLOCK + # e.g. for [YBLOCK // 16, YBLOCK, XBLOCK] dimensions 0 and 1 need boundary + # checks when max_ygrid is exceeded. + needs_overflow_grid = any(map(V.kernel.needs_yz_grid_overflow, range_trees)) + self._boundary_check = [ + idx + for idx in range(len(self.shape)) + if ( + not sizevars.statically_known_equals(self.strides[idx], sympy.S.Zero) + and ( + ( + needs_overflow_grid + and TritonSymbols.block_sizes[SymT.YBLOCK] + in self.block_shape[idx].free_symbols + ) + or ( + not sizevars.statically_known_multiple_of( + self.shape[idx], self.block_shape[idx] + ) + and not sizevars.statically_known_multiple_of( + self.shape[idx], + sympy_subs(self.block_shape[idx], block_to_max), + ) + ) + ) + and not ( + V.kernel.no_x_dim + and self.block_shape[idx] == TritonSymbols.block_sizes[SymT.XBLOCK] + ) + ) + ] + + def boundary_check(self) -> list[int]: + if self._boundary_check is None: + raise AssertionError("_boundary_check must be set") + return self._boundary_check + + def has_indirect(self) -> bool: + return False # block_ptr can't do indirect indexing + + def has_rindex(self) -> bool: + return any( + TritonSymbols.has_reduction_index_symbol( + cast("TritonKernel", V.kernel), expr + ) + for expr in self.block_shape + ) + + def has_rmask(self) -> bool: + return self.has_rindex() + + def has_tmpmask(self) -> bool: + return False # block_ptr can't do indirect indexing + + def has_mask(self) -> bool: + return bool(self.boundary_check()) + + def codegen_broadcast_and_reshape( + self, + value: str, + initial_shape: Sequence[sympy.Expr], + final_shape: Sequence[sympy.Expr], + allow_implicit: bool, + for_store: bool, + ) -> tuple[str, Sequence[sympy.Expr | int | str]]: + """ + Generate a broadcast and a reshape for the block descriptor. + This restores stride-0 dimensions which were removed from the block descriptor. + + Transposes are also applied to the input using self.stride_sorter: + if for_store is True: + - First Broadcast the value. Since self.broadcast_shape is stored in + descending stride order, it must be reverted to the original order + since the input value does not have dims with descending strides + - After, transpose the broadcasted value so that dimensions are in + descending stride order + - Finally reshape to the block shape + else (for load): + - First broadcast the value to self.broadcast_shape (strides are descending) + - Then transpose the value so that dimensions no longer have descending strides + - Finally reshape the block to the final kernel tile shape + """ + current_shape: Sequence[sympy.Expr | int | str] = initial_shape + + def apply_reshape( + value: str, + old_shape: Sequence[sympy.Expr | int | str], + new_shape: Sequence[sympy.Expr | int | str], + ) -> str: + nonlocal current_shape + result = triton_reshape(value, old_shape, new_shape) + if triton_shape_dims(old_shape) != triton_shape_dims(new_shape): + current_shape = new_shape + return result + + broadcast_shape = self.broadcast_shape + broadcasting_dims = self.broadcasting_dims + + # If the block parameters have been sorted by descending strides, + # permute the broadcasting parameters so that they are compatible + # with the value being stored. This is because the dimensions + # of the value being stored are not sorted in descending stride order, + # but the broadcasting parameters are based on the dims in sorted order + if for_store: + broadcast_shape = self.stride_sorter.revert(self.broadcast_shape) + broadcasting_dims = self.stride_sorter.revert(self.broadcasting_dims) + + # Reshape to add singletons. + pre_broadcast_shape = [ + sympy.S.One if is_broadcasting else dim + for dim, is_broadcasting in zip(broadcast_shape, broadcasting_dims) + ] + value = apply_reshape(value, initial_shape, pre_broadcast_shape) + + implicit_broadcast_shape = pre_broadcast_shape + if ( + not self.stride_sorter.is_identity + and not for_store + and len(pre_broadcast_shape) == len(final_shape) + ): + # If all we need to do is transpose to match the final shape + # with implicit broadcasting then we don't need an explicit broadcast + # unless the caller requests it. So just test implicit broadcast support + # with the transposed pre broadcast shape + implicit_broadcast_shape = self.stride_sorter.revert(pre_broadcast_shape) + + # Broadcast singletons. + # For loads, we can often implicitly broadcast singleton dimensions. + # We need an explicit broadcast for stores, or if the final reshape does more + # than add singletons. + sizevars = V.graph.sizevars + supports_implicit_broadcast = allow_implicit and ( + len(implicit_broadcast_shape) == len(final_shape) + and all( + sizevars.statically_known_equals(pre_dim, 1) + or sizevars.statically_known_equals(pre_dim, post_dim) + for pre_dim, post_dim in zip(implicit_broadcast_shape, final_shape) + ) + ) + + if any(self.broadcasting_dims) and not supports_implicit_broadcast: + value = ( + f"tl.broadcast_to({value}, {V.kernel.index_to_str(broadcast_shape)})" + ) + current_shape = broadcast_shape + + old_shape = self.broadcast_shape + if not self.stride_sorter.is_identity: + # if for_store the transform is + # (non-descending strides) broadcasted kernel tile shape + # -> (descending strides) block descriptor shape + # o/w if loading the transform is + # (descending strides) ((maybe implicitly) broadcasted block shape + # -> (non-descending) (maybe implicitly) broadcasted kernel tile shape + permute_dims = ( + self.stride_sorter.sort_idx + if for_store + else self.stride_sorter.revert_sort_idx + ) + value = f"tl.trans({value}, {permute_dims})" + current_shape = [current_shape[i] for i in permute_dims] + old_shape = ( + self.broadcast_shape + if for_store + else self.stride_sorter.revert(self.broadcast_shape) + ) + + # Reshape to the final shape. + value = apply_reshape(value, old_shape, final_shape) + return value, current_shape + + +@dataclasses.dataclass +class TensorDescriptorOptions(BlockDescriptorOptions): + def format(self, name: str, roffset=True) -> str: + """ + Codegen a call to tl.make_tensor_descriptor() + + Args: + name: variable name for pointer + roffset: unused, but kept for compatibility with BlockPtrOptions.format() + + Returns: + "tl.make_tensor_descriptor(...)" + """ + + f = V.kernel.index_to_str + args = [ + ( + f"{name} + ({f(self.constant_offset)})" + if self.constant_offset != 0 + else name + ), + f"shape={f(self.shape)}", + f"strides={f(self.strides)}", + f"block_shape={f(self.block_shape)}", + ] + + return f"tl.make_tensor_descriptor({', '.join(args)})" + + +@dataclasses.dataclass +class BlockPtrOptions(BlockDescriptorOptions): + def replace_offset( + self, expr: sympy.Expr, replacement: sympy.Expr, symt: SymT + ) -> sympy.Expr: + """ + Replaces instances of {symt}_offset with the new expression. + """ + roffset = TritonSymbols.block_offsets[symt] + return sympy_subs(expr, {roffset: replacement}) + + def remove_roffsets(self, expr: sympy.Expr) -> sympy.Expr: + for symt in TritonSymbols.reduction_types: + expr = self.replace_offset(expr, sympy.Integer(0), symt) + return expr + + def format(self, name: str, roffset=True) -> str: + """ + Codegen a call to tl.make_block_ptr() + + Args: + name: variable name for pointer + roffset: should rn_offset be included in offsets=..., for use with tl.advance() + + Returns: + "tl.make_block_ptr(...)" + """ + f = V.kernel.index_to_str + offsets = [*self.offsets] + if not roffset: + offsets = [self.remove_roffsets(offset) for offset in offsets] + args = [ + ( + f"{name} + ({f(self.constant_offset)})" + if self.constant_offset != 0 + else name + ), + f"shape={f(self.shape)}", + f"strides={f(self.strides)}", + f"block_shape={f(self.block_shape)}", + f"order={f(self.order)}", + f"offsets={f(offsets)}", + ] + return f"tl.make_block_ptr({', '.join(args)})" + + def advance_roffset(self, symt: SymT) -> sympy.Expr: + """ + Codegen string to pass to tl.advance(name, ...). + + Advance is the difference between offsets in each loop iteration. + To compute it, we replace rN_offset with multiples of RN_BLOCK. + Since we expect rN_offset to vary in range(0, rN_numel, RN_BLOCK), the first + iteration has rN_offset=0, while the second has rN_offset=RN_BLOCK. + """ + rblock = TritonSymbols.block_sizes[symt] + advance = [ + ( + self.replace_offset(offset, rblock, symt) + - self.replace_offset(offset, sympy.S.Zero, symt) + ) + for offset in self.offsets + ] + return advance + + +def triton_shape_dims(shape: Sequence[sympy.Expr | int | str]) -> list[str]: + """Format mixed symbolic and pre-rendered Triton shape dimensions. + + Nested-reduction codegen builds reshape/broadcast shapes from both sympy + expressions and already-rendered block-size strings. + """ + return [ + dim if isinstance(dim, str) else V.kernel.index_to_str(dim) for dim in shape + ] + + +def triton_shape_str(shape: Sequence[sympy.Expr | int | str]) -> str: + return f"[{', '.join(triton_shape_dims(shape))}]" + + +def triton_reshape( + value: str, + old_shape: Sequence[sympy.Expr | int | str], + new_shape: Sequence[sympy.Expr | int | str], +) -> str: + """Workaround https://github.com/triton-lang/triton/issues/2836""" + if not (isinstance(old_shape, list) and isinstance(new_shape, list)): + raise AssertionError("old_shape and new_shape must both be lists") + + old_shape_str = triton_shape_dims(old_shape) + new_shape_str = triton_shape_dims(new_shape) + + if old_shape_str == new_shape_str: + return value + if [s for s in new_shape_str if s != "1"] != old_shape_str: + return f"tl.reshape({value}, [{', '.join(new_shape_str)}])" + # rewrite to [:, None] syntax, which is less buggy + idx = 0 + expand = [] + for size in new_shape_str: + if idx < len(old_shape_str) and size == old_shape_str[idx]: + expand.append(":") + idx += 1 + else: + if size != "1": + raise AssertionError(f"expected size '1', got {size!r}") + expand.append("None") + if idx != len(old_shape_str): + raise AssertionError( + f"expected idx == len(old_shape_str), got {idx} != {len(old_shape_str)}" + ) + return f"{value}[{', '.join(expand)}]" + + +# NB: Inheriting from PythonPrinter is somewhat dangerous, because there are a +# number of operators which Triton "implements", but in a way that is +# inconsistent with Python semantics (and consistent with C semantics). We +# must override all of these, or it is potential silent correctness problem +class TritonPrinter(PythonPrinter): # noqa: docstring_linter + def _print_TruncToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + return ( + # pyrefly: ignore [missing-attribute] + f"libdevice.trunc({self._print(expr.args[0])}).to({V.kernel.index_dtype})" + ) + + def _print_TruncToFloat(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + value = self._print(expr.args[0]) + # Adding +0.0 preserves large floating results while canonicalizing + # libdevice.trunc(-0.0) back to Python's +0.0 materialization behavior. + # pyrefly: ignore [missing-attribute] + return f"(libdevice.trunc({value}) + tl.zeros_like({value}))" + + @staticmethod + def _get_scalar_float_type() -> str: + """Return the Triton float type for scalar shape math. + + Uses tl.float64 by default but falls back to tl.float32 on devices + that lack fp64 support (e.g. Intel Arc consumer GPUs). + """ + if not device_supports_fp64(V.graph.current_device): + return "tl.float32" + return "tl.float64" + + def _print_Float(self, expr: sympy.Expr) -> str: + if expr.is_integer: + # sympy considers 0.0 to be integer, but triton doesn't. + # this workaround prints the float as an integer + # xref: https://github.com/sympy/sympy/issues/26620 + ret = str(int(expr)) + elif config.is_fbcode() and torch.version.hip: + ret = f"{expr}" + else: + float_type = self._get_scalar_float_type() + ret = f"tl.full([], {expr}, {float_type})" + return ret + + def _print_ToFloat(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [bad-argument-type] + s = self.parenthesize(expr.args[0], PRECEDENCE["Atom"] - 0.5) + float_type = self._get_scalar_float_type() + return f"{s}.to({float_type})" + + def _print_PythonMod(self, expr: sympy.Expr) -> str: + quot, div = expr.args + if quot.is_nonnegative and div.is_nonnegative: + return self.stringify(expr.args, " % ", PRECEDENCE["Atom"] - 0.5) + # pyrefly: ignore [missing-attribute] + quot_s = self._print(quot) + # pyrefly: ignore [missing-attribute] + div_s = self._print(div) + return f"triton_helpers.remainder_integer({quot_s}, {div_s})" + + def _print_FloorDiv(self, expr: sympy.Expr) -> str: + if not expr.is_integer: + raise AssertionError("expr must be integer") + quot, div = expr.args + if quot.is_nonnegative and div.is_nonnegative: + return self.stringify(expr.args, " // ", PRECEDENCE["Atom"] - 0.5) + # pyrefly: ignore [missing-attribute] + quot_s = self._print(quot) + # pyrefly: ignore [missing-attribute] + div_s = self._print(div) + return f"triton_helpers.div_floor_integer({quot_s}, {div_s})" + + # TODO: This is wrong, when lhs, rhs > 2**53, Python does a higher + # precision algorithm, which we would need to replicate here + def _print_IntTrueDiv(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " / ", PRECEDENCE["Atom"] - 0.5) + + # NB: sympy.floor/ceiling produce integers, so we have to do the + # conversion to index dtype + def _print_floor(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + return ( + # pyrefly: ignore [missing-attribute] + f"libdevice.floor({self._print(expr.args[0])}).to({V.kernel.index_dtype})" + ) + + def _print_FloorToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + return ( + # pyrefly: ignore [missing-attribute] + f"libdevice.floor({self._print(expr.args[0])}).to({V.kernel.index_dtype})" + ) + + def _print_ceiling(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"libdevice.ceil({self._print(expr.args[0])}).to({V.kernel.index_dtype})" + + def _print_CeilToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"libdevice.ceil({self._print(expr.args[0])}).to({V.kernel.index_dtype})" + + def _helper_sqrt(self, expr: sympy.Expr) -> str: + # pyrefly: ignore [missing-attribute] + return f"tl.sqrt_rn(({self._print(expr)}).to(tl.float32))" + + def _print_FloatPow(self, expr: sympy.Expr) -> str: + # pyrefly: ignore [missing-attribute] + base = self._print(expr.args[0]) + # pyrefly: ignore [missing-attribute] + exp = self._print(expr.args[1]) + # libdevice.pow requires both arguments to have the same type. + # Cast to float64 for precision. Falls back to float32 on devices + # without fp64 support. This is scalar shape math, not tensor ops. + float_type = self._get_scalar_float_type() + return f"libdevice.pow(({base}).to({float_type}), ({exp}).to({float_type}))" + + def _print_PowByNatural(self, expr: sympy.Expr) -> str: + float_type = self._get_scalar_float_type() + if expr.args[0].is_Integer: + base = f"tl.full([], {float(expr.args[0])}, {float_type})" + else: + # pyrefly: ignore [missing-attribute] + base = f"({self._print(expr.args[0])}).to({float_type})" + exp_val = expr.args[1] + if exp_val.is_Integer: + exp = f"tl.full([], {float(exp_val)}, {float_type})" + else: + # pyrefly: ignore [missing-attribute] + exp = f"({self._print(exp_val)}).to({float_type})" + # libdevice.pow requires both arguments to have the same type. + # Cast to float64 for precision. Falls back to float32 on devices + # without fp64 support. This is scalar shape math, not tensor ops. + return f"libdevice.pow({base}, {exp})" + + def _print_Where(self, expr: sympy.Expr) -> str: + c = self.doprint(expr.args[0]) + p = self.doprint(expr.args[1]) + q = self.doprint(expr.args[2]) + return f"tl.where({c}, {p}, {q})" + + def _print_min_max_helper(self, expr: sympy.Expr, cmp: str) -> str: + """ + Helper for max/min code generation. + cmp: > or < + """ + if len(expr.args) == 1: + # pyrefly: ignore [missing-attribute] + return self._print(expr.args[0]) + + mid = len(expr.args) // 2 + cls = type(expr) + # pyrefly: ignore [missing-attribute] + a = self._print(cls(*expr.args[:mid])) + # pyrefly: ignore [missing-attribute] + b = self._print(cls(*expr.args[mid:])) + + # Use a macro so we can propagate constexprs. + # https://github.com/triton-lang/triton/issues/3815 + a, b = tuple(f"({x})" for x in (a, b)) + if cmp not in (">", "<"): + raise AssertionError(f"Unexpected comparator: '{cmp}'") + return f"({a} * ({a} {cmp}= {b}) + {b} * ({b} {cmp} {a}))" + + def _print_Min(self, expr: sympy.Expr) -> str: + return self._print_min_max_helper(expr, "<") + + def _print_Max(self, expr: sympy.Expr) -> str: + return self._print_min_max_helper(expr, ">") + + def _print_Abs(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"tl_math.abs({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_cos(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"libdevice.cos(({self._print(expr.args[0])}).to(tl.float32))" + + def _print_OpaqueUnaryFn_cosh(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"libdevice.cosh(({self._print(expr.args[0])}).to(tl.float32))" + + def _print_OpaqueUnaryFn_acos(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"libdevice.acos(({self._print(expr.args[0])}).to(tl.float32))" + + def _print_OpaqueUnaryFn_sin(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"libdevice.sin(({self._print(expr.args[0])}).to(tl.float32))" + + def _print_OpaqueUnaryFn_sinh(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"libdevice.sinh(({self._print(expr.args[0])}).to(tl.float32))" + + def _print_OpaqueUnaryFn_asin(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"libdevice.asin(({self._print(expr.args[0])}).to(tl.float32))" + + def _print_OpaqueUnaryFn_tan(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"libdevice.tan(({self._print(expr.args[0])}).to(tl.float32))" + + def _print_OpaqueUnaryFn_tanh(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"libdevice.tanh(({self._print(expr.args[0])}).to(tl.float32))" + + def _print_OpaqueUnaryFn_atan(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"libdevice.atan(({self._print(expr.args[0])}).to(tl.float32))" + + def _print_OpaqueUnaryFn_log2(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"libdevice.log2(({self._print(expr.args[0])}).to(tl.float32))" + + def _print_RoundToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + return ( + # pyrefly: ignore [missing-attribute] + f"libdevice.llrint({self._print(expr.args[0])}).to({V.kernel.index_dtype})" + ) + + def _print_RoundDecimal(self, expr: sympy.Expr) -> str: + if len(expr.args) != 2: + raise AssertionError(f"expected 2 args, got {len(expr.args)}") + number, ndigits = expr.args + if number.is_integer: + # ndigits < 0 should have been filtered by the sympy function + if ndigits >= 0: + raise AssertionError(f"expected ndigits < 0, got {ndigits}") + raise ValueError( + f"For integer inputs, only non-negative ndigits are currently supported, but got {ndigits}." + ) + + number_str = self.parenthesize(number, PRECEDENCE["Mul"]) + return f"libdevice.nearbyint(1e{ndigits} * {number_str}) * 1e{-ndigits}" + + +texpr = TritonPrinter().doprint + + +def triton_compute_type(dtype: torch.dtype) -> str: + """Convert torch.dtype to triton type and upcast [b]float16 to float32""" + return triton_type(upcast_compute_type(dtype)) + + +def triton_store_type(dtype: torch.dtype) -> str: + """Convert torch.dtype to triton type, with fix for storing tl.bool""" + if dtype == torch.bool: + dtype = torch.int8 + return triton_type(dtype) + + +def upcast_acc_dtype(dtype: torch.dtype) -> torch.dtype: + """Implicit upcasts used for Triton reduction types""" + if is_integer_dtype(dtype) and dtype.is_signed and dtype.itemsize <= 4: + return torch.int32 + return upcast_compute_type(dtype) + + +def triton_acc_type(dtype: torch.dtype) -> str: + """Convert torch.dtype to triton type, with reduction upcasts""" + return triton_compute_type(upcast_acc_dtype(dtype)) + + +def low_precision_fp(dtype: torch.dtype) -> bool: + return dtype.itemsize <= 2 and dtype.is_floating_point + + +def low_precision_fp_var(var: CSEVariable | Any) -> bool: + if not isinstance(var, CSEVariable): + return False + + dtype = var.dtype + return low_precision_fp(dtype) if isinstance(dtype, torch.dtype) else False + + +def triton_arg_dtype(arg: Any) -> torch.dtype | None: + if isinstance(arg, CSEVariable): + return arg.dtype + if isinstance(arg, torch._prims_common.Number): + return type_to_dtype(type(arg)) + return None + + +def needs_upcast_to_float32(arg: Any) -> bool: + return ( + not config.triton.codegen_upcast_to_fp32 + and isinstance(arg, CSEVariable) + and arg.dtype in (torch.float16, torch.bfloat16) + ) + + +class TritonCSEVariable(CSEVariable): + def __init__( + self, + name: str, + bounds: ValueRanges[Any], + dtype: torch.dtype, + shape: BlockShapeType = None, + ) -> None: + super().__init__(name, bounds, dtype, shape=shape) + # We'll use this to track which masks the variable needs when used for indirect indexing + self.mask_vars: OrderedSet[str] = OrderedSet() + if dtype is None: + raise AssertionError("TritonCSEVariable must have dtype") + if shape is None: + raise AssertionError("TritonCSEVariable must have shape") + + def update_on_args(self, name, args, kwargs): + for arg in args: + if isinstance(arg, TritonCSEVariable): + self.mask_vars.update(arg.mask_vars) + elif isinstance(arg, sympy.Symbol): + # most of the time index vars don't need masks associated with them + # however, when index vars are used to compute indices for indirect reads + # those reads should subsequently be masked, + if ( + mask_name := TritonSymbols.mask_name_for_symbol( + cast("TritonKernel", V.kernel), arg + ) + ) is not None: + self.mask_vars.add(mask_name) + + +@dataclasses.dataclass(frozen=True) +class TritonOpTraceEntry: + name: str + args: tuple[Any, ...] + kwargs: tuple[tuple[str, Any], ...] + result: Any + + +def get_dtype_handler() -> DtypePropagationOpsHandler: + from torch._inductor.dtype_propagation import DtypePropagationOpsHandler + + return DtypePropagationOpsHandler() + + +def maybe_upcast_float32(convert_output: bool = True) -> Callable[[_T], _T]: + """ + Codegen helper to upcast arguments to float32, depending on the config and dtype. + This decorates tl.math/libdevice codegen functions. + """ + + def maybe_upcast_arg(var) -> str: + upcast_string = ".to(tl.float32)" if needs_upcast_to_float32(var) else "" + return f"{var}{upcast_string}" + + def decorator(func: Callable[..., Any]) -> Callable[..., Any]: + # Record that this function only supports float32 and float64. + OpDtypeSupport.register_upcast(func, convert_output) + + def wrapped(*args, **kwargs) -> str: + # Optionally upcast args to float32. + upcast_args = [maybe_upcast_arg(arg) for arg in args] + upcast_kwargs = {key: maybe_upcast_arg(val) for key, val in kwargs.items()} + + # Call the decorated function, optionally downcasting the result. + result = func(*upcast_args, **upcast_kwargs) + any_needs_upcast = convert_output and any( + needs_upcast_to_float32(var) + for var in itertools.chain(args, kwargs.values()) + ) + result_dtype = ( + None + if not any_needs_upcast + else getattr(get_dtype_handler(), func.__name__)(*args, **kwargs) + ) + needs_downcast = result_dtype not in (torch.float32, None) + downcast_string = ( + f".to({triton_type(result_dtype)})" + if needs_downcast and result_dtype is not None + else "" + ) + return f"{result}{downcast_string}" + + return wrapped + + return decorator # type: ignore[return-value] + + +class TritonOverrides(OpOverrides): + """Map element-wise ops to Triton e.g., ops.to_dtype(x,...) -> x.to(...)""" + + _LOG_2_E = math.log2(math.e) + + @staticmethod + def to_dtype( + x, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types=True, + ): + fp8_dtypes = ( + torch.float8_e4m3fn, + torch.float8_e5m2, + ) + + def _get_min_elements_per_thread( + src_dtype: torch.dtype, dst_dtype: torch.dtype + ) -> int: + if src_dtype == dst_dtype: + # No data type conversion is needed. No requirements on min_elem_per_thread. + return 0 + + # fp8 data type conversions has min_elem_per_thread requirements. + # Refer to Triton implementations here: + # https://github.com/triton-lang/triton/blob/10f59d8ce04052521c1bc0cb3a3f8b98918fc7e3/lib/Conversion/TritonGPUToLLVM/ElementwiseOpToLLVM.cpp#L10. + # Triton doesn't support type conversions between fp8_e4m3 and fp8_e5m2. + if ( + src_dtype in fp8_dtypes + and dst_dtype in fp8_dtypes + and src_dtype != dst_dtype + ): + raise AssertionError( + "Conversions between float8_e5m2 and float8_e4m3fn is not supported!" + ) + if src_dtype == torch.float8_e5m2 or dst_dtype == torch.float8_e5m2: + return 4 + if src_dtype == torch.float8_e4m3fn or dst_dtype == torch.float8_e4m3fn: + return 2 + # No requirements on min_elem_per_thread. + return 0 + + if src_dtype is not None: + # Both dtype and src_dtype are set. This is used by torch to(dtype=dtype). + # It takes the maximum min_elem_per_thread if there are multiple fp8 conversions + # in the same kernel. + V.kernel.min_elem_per_thread = max( + _get_min_elements_per_thread(src_dtype, dtype), + V.kernel.min_elem_per_thread, + ) + + if src_dtype is not None and use_uint8_triton_storage_for_cuda_float8_e4m3fn( + src_dtype + ): + x = f"triton_helpers.fp8e4m3fn_to_float32({x})" + src_dtype = torch.float32 + + if dtype == torch.bool: + return f"({x} != 0)" + elif dtype == torch.uint8 and ( + src_dtype is not None and src_dtype.is_floating_point or src_dtype is None + ): + # to work around llvm uint conversion semantics that produces 0's for negative + # values when converting from floating types. + # optimization - if source type is known and it's not a floating type, then + # do not apply conversion to the intermediate type. + return f"{x}.to(tl.int16).to(tl.uint8)" + + if use_compute_types: + out_dtype = triton_compute_type(dtype) + else: + out_dtype = triton_store_type(dtype) + + if ( + src_dtype is not None + and dtype in fp8_dtypes + and (src_dtype == torch.bool or is_integer_dtype(src_dtype)) + ): + return f"{x}.to(tl.float32).to({out_dtype})" + + return f"{x}.to({out_dtype})" + + @staticmethod + def to_dtype_bitcast(x, dtype: torch.dtype, src_dtype: torch.dtype): + if src_dtype.itemsize != dtype.itemsize: + raise AssertionError( + f"itemsize mismatch: {src_dtype.itemsize} != {dtype.itemsize}" + ) + # We may promote float16 or bfloat16 to float32 and cause the + # bitwidth of dtype to be different from the input tensor (i.e. float32). + # In such as case, we will have to convert the input tensor to + # its src_type, perform bitcast, and then convert the bit-casted + # tensor back to float to ensure we use values with the right precision. + if x.dtype != src_dtype: + x = f"{x}.to({triton_type(src_dtype)})" + + out = f"{x}.to({triton_type(dtype)}, bitcast=True)" + if upcast_compute_type(dtype) != dtype: + out = f"{out}.to({triton_type(upcast_compute_type(dtype))})" + + return out + + @staticmethod + def _shaped_constant(value, dtype, shape): + type_ = torch._prims_common.dtype_to_type(dtype) + triton_val = constant_repr(type_(value)) + triton_type = triton_compute_type(dtype) + + # Triton's scalar_constant() treats -0.0 as 0 (since -0.0 == 0 in Python), + # Work around by encoding -0.0 as its IEEE 754 hex in uint and bitcasting. + if value == 0 and math.copysign(1.0, value) < 0: + if triton_type == "tl.float32": + return f"tl.full({shape}, 0x80000000, tl.uint32).to({triton_type}, bitcast=True)" + elif triton_type == "tl.float64": + return f"tl.full({shape}, 0x8000000000000000, tl.uint64).to({triton_type}, bitcast=True)" + + # NOTE: We use tl.full here to get the expected type. + # Otherwise, subnormal float32 values are treated as fp64 + # causing fp32 * fp64 promotion and different numerical results. + if value < 0 and not dtype.is_signed: + triton_signed_type = f"tl.{triton_type[4:]}" + return f"tl.full({shape}, {triton_val}, {triton_signed_type}).to({triton_type})" + else: + return f"tl.full({shape}, {triton_val}, {triton_type})" + + @classmethod + def constant(cls, value, dtype): + return cls._shaped_constant(value, dtype, shape=[]) + + @staticmethod + def sub(x, y): + if ( + isinstance(x, CSEVariable) + and x == y + and x.dtype is not None + and x.dtype.is_floating_point + ): + # Avoid giving LLVM a tmp - tmp pattern that it can reassociate + # through tmp's producer. A plain 0.0 is only valid for finite + # inputs; nan/inf inputs should still produce nan like x - x. + non_finite = f"({TritonOverrides.isnan(x)} | {TritonOverrides.isinf(x)})" + return f"tl.where({non_finite}, {x} * 0.0, 0.0)" + return f"{x} - {y}" + + @classmethod + def _cast_libdevice_arg(cls, arg, dtype: torch.dtype) -> str: + if isinstance(arg, torch._prims_common.Number): + return cls.constant(arg, dtype) + if triton_arg_dtype(arg) == dtype: + return f"{arg}" + return f"({arg}).to({triton_type(dtype)})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def abs(x): + return f"tl_math.abs({x})" + + # TODO - register these ops as having divergent dtype + # output if doing graph pass to remove consecutive casts + + @staticmethod + def truediv(x, y): + x_dtype = getattr(x, "dtype", None) + y_dtype = getattr(y, "dtype", None) + + if ( + x_dtype == torch.float32 + and y_dtype == torch.float32 + and config.eager_numerics.division_rounding + ): + # x / y in Triton is lowered to div.full which is approx + # we want div_rn to adhere with eager + out = f"triton.language.div_rn({x}, {y})" + else: + out = f"({x} / {y})" + + if low_precision_fp_var(x) or low_precision_fp_var(y): + out_dtype = get_dtype_handler().truediv(x, y) + if out_dtype in (torch.float16, torch.float32): + out = f"{out}.to({triton_type(out_dtype)})" + + return out + + @staticmethod + def div_rn(x, y): + """ + Division with round-to-nearest rounding mode. + Always uses triton.language.div_rn for float32 inputs to match eager CUDA behavior. + """ + x_dtype = getattr(x, "dtype", None) + y_dtype = getattr(y, "dtype", None) + + if x_dtype == torch.float32 and y_dtype == torch.float32: + out = f"triton.language.div_rn({x}, {y})" + else: + # Fall back to regular division for non-float32 types + out = f"({x} / {y})" + + if low_precision_fp_var(x) or low_precision_fp_var(y): + out_dtype = get_dtype_handler().truediv(x, y) + if out_dtype in (torch.float16, torch.float32): + out = f"{out}.to({triton_type(out_dtype)})" + + return out + + @staticmethod + def mod(x, y): + out = f"({x} % {y})" + if low_precision_fp_var(x) or low_precision_fp_var(y): + out_dtype = get_dtype_handler().mod(x, y) + if out_dtype in (torch.float16, torch.float32): + out = f"{out}.to({triton_type(out_dtype)})" + return out + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def exp(x): + """ + When use_fast_math, use the ftz (flushing to zero) variant + of exponent computation. + + Check https://github.com/triton-lang/triton/issues/5735 for + more details. + """ + if config.use_fast_math: + return f"tl_math.exp({x})" + else: + return f"libdevice.exp({x})" + + @staticmethod + @maybe_upcast_float32() + def exp2(x): + return f"libdevice.exp2({x})" + + @staticmethod + @maybe_upcast_float32() + def expm1(x): + return f"libdevice.expm1({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def sqrt(x): + return f"tl.sqrt_rn({x})" + + @staticmethod + def relu(x): + bug = config.triton.inject_relu_bug_TESTING_ONLY + if bug == "compile_error": + return "compile error!" + elif bug == "runtime_error": + # NB: this only triggers runtime error as long as input + # is not all zero + return f'triton_helpers.device_assert_then({x} == 0, "injected assert fail", {x})' + elif bug == "accuracy": + return f"{x} + 1" + elif bug is None: + return ops.maximum(ops.constant(0, torch.int32), x) + else: + raise AssertionError( + f"unrecognized config triton.inject_relu_bug_TESTING_ONLY = {bug!r}" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def minimum(a, b): + return f"tl.minimum({a}, {b}, tl.PropagateNan.ALL)" + + @staticmethod + # pyrefly: ignore [bad-override] + def maximum(a, b): + return f"tl.maximum({a}, {b}, tl.PropagateNan.ALL)" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmaximum(a, b): + return f"tl.maximum({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def where(a, b, c): + return f"tl.where({a}, {b}, {c})" + + @staticmethod + # pyrefly: ignore [bad-override] + def dot(a, b): + """ + Triton code generation for lowering ops.dot to tl.dot. + + The logic is as follows: + + 1. Downcasting for performance + If the data was previously upcasted to fp32, we downcast back to the + original dtype (e.g., fp16 or bf16) for better performance. While + surrounding operations may run in fp32, matmul itself is executed at the + original precision to optimize throughput. + + 2. Handling non-constant reduction masks + If the reduction mask is not constant and there was any operation between + tl.load and tl.dot, we zero out regions outside the mask using + tl.where(r0_mask, val, 0). + This ensures that values outside the mask do not contribute to the dot + product, preventing incorrect results. + + 3. Shape alignment for tl.dot + We massage shapes to match the tl.dot requirement of (Y, R) x (R, X). + Current codegen eagerly broadcasts tl.arange to create unique axes. We + reshape, transpose, or broadcast to align with the (Y, R) x (R, X) shape. + We avoid using 3D dot ((Z, Y, R) x (Z, R, X)) because 3D tl.dot has + poor performance. During batched matmul (bmm), we keep ZBLOCK=1 and call + the 2D dot kernel instead. + """ + if not V.kernel.is_native_matmul: + raise AssertionError("expected native matmul kernel") + orig_a, orig_b = a, b + + def is_where_needed(var): + # Skip if the variable doesn't have a reduction mask + if not any(map(prefix_is_reduction, var.mask_vars)): + return False + + reduction_range = V.kernel.range_trees[-1] + if not reduction_range.is_reduction: + raise AssertionError("reduction_range must be a reduction") + + # Skip if reduction mask was already constant + if V.kernel._has_constant_mask(reduction_range): + return False + + # Skip if the variable is already zeroed outside the mask + # (e.g., from tl.load(..., other=0.0)) + # TODO : track the value of outside of mask region with cse + for k, v in V.kernel.cse._cache.items(): + if v == var and "tl.load" in k and "other=0.0" in k: + return False + + return True + + def where_cond(var): + default = ir.Reduction.default_value("dot", var.dtype) + reduction_mask = [ + tree.mask_name() for tree in V.kernel.range_trees if tree.is_reduction + ] + + if len(reduction_mask) != 1: + raise AssertionError("don't tile reduction when native matmul") + + where_var = TritonKernelOverrides.where(reduction_mask[0], var, default) + return V.kernel.cse.generate( + V.kernel.compute, where_var, dtype=var.dtype, shape=var.shape + ) + + # When computing expressions like ((A+1) @ (B+2)), + # native codegen will do + # + # a = tl.load(..., r0_mask, other=0.0) + # b = tl.load(..., r0_mask, other=0.0) + # tmp0 = a+1 + # tmp1 = b+2 + # tmp2 = tl.dot(tmp0, tmp1) + # + # This produces incorrect results because outside of r0_mask is not zero. + # So before calling tl.dot, apply tl.where to zero out values properly. + # TODO: Optimize - We don't need both operands to be zeroed except NaN * 0 + if is_where_needed(orig_a): + a = where_cond(a) + if is_where_needed(orig_b): + b = where_cond(b) + + def reshape_transpose_broadcast_for_dot( + value, + initial_shape: Sequence[sympy.Expr], + final_shape: Sequence[sympy.Expr], + ) -> str: + """ + Generate a reshape, transpose, and broadcast for the tl.dot. + tl.dot requires specific shape requirement : (Y,R) x (R,X) + but the current triton codegen eagerly broadcast the tl.arange so + it needs to be reshaped to meet the requirement. + + This is done by three steps. + 1. remove the empty dimension (dim with size 1) and make it 2d with tl.reshape + 2. permute the dimension if needed (e.g., (X,R) -> (R,X)) with tl.trans + 3. broadcast if needed with broadcast_to. + - This shows up when matmul operand is broadcasted with torch.expand/repeat. + - e.g., torch.rand((16,)).expand(16,16) @ B + + e.g., (Y,1,R), (Y,R) -> tl.reshape(var, (Y,R)) + e.g., (1,X,R), (R,X) -> tl.trans(tl.reshape(var, (X,R))) + e.g., (1,X,1), (R,X) -> tl.broadcast_to(tl.trans(tl.reshape(var, (X,1))), (R,X)) + + TODO : eventually we want to remove this function when lazy broadcasting arrives + """ + + # Triton 3d dot is slower than 2d dot, so we want to keep block shape in 2d + # by fixing ZBLOCK=1 in the autotune config + if ZBLOCK in initial_shape: + initial_shape = ["1" if dim == ZBLOCK else dim for dim in initial_shape] + + if final_shape == [YBLOCK, RBLOCK]: + if XBLOCK in initial_shape: + raise AssertionError("left tl.dot operand cannot depend on x") + + shape_2d = ["1", "1"] + if YBLOCK in initial_shape: + shape_2d[0] = YBLOCK + if RBLOCK in initial_shape: + shape_2d[1] = RBLOCK + + # reshape it into 2d + value = triton_reshape(value, initial_shape, shape_2d) + + # broadcast if needed + broadcast_needed = shape_2d != [YBLOCK, RBLOCK] + if broadcast_needed: + value = f"tl.broadcast_to({value}, ({YBLOCK}, {RBLOCK}))" + + elif final_shape == [RBLOCK, XBLOCK]: + if YBLOCK in initial_shape: + raise AssertionError("right tl.dot operand cannot depend on y") + + shape_2d = ["1", "1"] + if XBLOCK in initial_shape: + shape_2d[0] = XBLOCK + if RBLOCK in initial_shape: + shape_2d[1] = RBLOCK + + # reshape it into 2d (X,R) + value = triton_reshape(value, initial_shape, shape_2d) + + # transpose to (R,X) + value = f"tl.trans({value})" + + # broadcast if needed + broadcast_needed = shape_2d != [XBLOCK, RBLOCK] + if broadcast_needed: + value = f"tl.broadcast_to({value}, ({RBLOCK}, {XBLOCK}))" + else: + raise NotImplementedError + + return value + + if len(V.kernel.dense_size_list()) < 3: + raise AssertionError("tl.dot can only do mm and bmm") + + XBLOCK = str(TritonSymbols.block_sizes[SymT.XBLOCK]) + YBLOCK = str(TritonSymbols.block_sizes[SymT.YBLOCK]) + ZBLOCK = str(TritonSymbols.block_sizes[SymT.ZBLOCK]) + RBLOCK = str(TritonSymbols.block_sizes[SymT.R0_INDEX]) + + a = V.kernel.cse.generate( + V.kernel.compute, + reshape_transpose_broadcast_for_dot(a, list(a.shape), [YBLOCK, RBLOCK]), + dtype=a.dtype, + shape=(YBLOCK, RBLOCK), + ) + + b = V.kernel.cse.generate( + V.kernel.compute, + reshape_transpose_broadcast_for_dot(b, list(b.shape), [RBLOCK, XBLOCK]), + dtype=b.dtype, + shape=(RBLOCK, XBLOCK), + ) + + if torch.backends.cuda.matmul.fp32_precision == "tf32": + input_precision = "tf32" + else: + input_precision = "ieee" + + return f'tl.dot({a}, {b}, input_precision="{input_precision}")' + + @staticmethod + def inline_asm_elementwise( + *inputs, + asm, + constraints=None, + dtype=torch.float32, + is_pure=True, + pack=1, + input_dtypes=None, + ): + # Use the actual dtype, not the compute type — the asm operates on + # specific register types and Triton needs to know the real output type. + asm_triton_type = triton_type(dtype) + if constraints is None: + constraints = ", ".join(["=r"] + ["r" for _ in inputs]) + + # Inductor computes bf16/fp16 in fp32. For "h" (16-bit register) + # constraints, cast back to the original dtype so the asm sees the + # right register type. + constraint_parts = [p.strip() for p in constraints.split(",")] + input_constraints = [p for p in constraint_parts if not p.startswith("=")] + cast_inputs = [] + for i, (inp, c) in enumerate(zip(inputs, input_constraints[: len(inputs)])): + if ( + c == "h" + and input_dtypes is not None + and isinstance(inp, CSEVariable) + and inp.dtype != input_dtypes[i] + ): + cast_inputs.append(f"{inp}.to({triton_type(input_dtypes[i])})") + else: + cast_inputs.append(str(inp)) + + if torch.version.hip: + # AMDGCN asm strings may contain real newlines (instructions are + # newline-separated, unlike PTX which uses semicolons). The + # generated code is nested inside two Python string layers: + # Layer 1 : the cached wrapper .py file + # Layer 2 : the Triton kernel source (a triple-quoted string + # inside that wrapper, exec'd / JIT-compiled) + # repr() escapes \n -> \\n, then we double the backslashes so + # they survive both layers: \\\\n -> (L1 parse) \\n -> (L2 parse) \n. + asm_literal = repr(asm).replace("\\", "\\\\") + constraints_literal = repr(constraints).replace("\\", "\\\\") + else: + asm_literal = f"'{asm}'" + constraints_literal = f"'{constraints}'" + + def asm_call(args): + return ( + f"tl.inline_asm_elementwise({asm_literal}, {constraints_literal}, " + f"[{args}], dtype={asm_triton_type}, is_pure={is_pure}, pack={pack})" + ) + + if pack <= 1: + return asm_call(", ".join(cast_inputs)) + + first_input = inputs[0] + compute = V.kernel.compute + cse = V.kernel.cse + result = cse.newvar(dtype=dtype, shape=first_input.shape) + packed_args = ", ".join( + f"triton_helpers.inline_asm_pack({inp}, {pack})" for inp in cast_inputs + ) + compute.writeline(f"{result} = {asm_call(packed_args)}") + compute.writeline( + f"{result} = triton_helpers.inline_asm_unpack({result}, {first_input}, {pack})" + ) + return result + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def cos(x): + return f"tl_math.cos({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def sin(x): + return f"tl_math.sin({x})" + + @classmethod + def index_expr(cls, expr, dtype): + raise NotImplementedError("ops.index_expr not implemented outside a kernel") + + @classmethod + def value_expr(cls, expr, dtype): + raise NotImplementedError("ops.value_expr not implemented outside a kernel") + + @staticmethod + def masked(mask, body, other): + raise NotImplementedError("ops.masked not implemented outside a kernel") + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def lgamma(x): + return f"libdevice.lgamma({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def erf(x): + return f"libdevice.erf({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def cosh(x): + return f"libdevice.cosh({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def sinh(x): + return f"libdevice.sinh({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def acos(x): + return f"libdevice.acos({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def acosh(x): + return f"libdevice.acosh({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def asin(x): + return f"libdevice.asin({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def asinh(x): + return f"libdevice.asinh({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def atan2(x, y): + return f"libdevice.atan2({x}, {y})" + + @staticmethod + def _f32_const_from_bits(bits: int) -> str: + return f"tl.full([], 0x{bits:08X}, tl.uint32).to(tl.float32, bitcast=True)" + + @staticmethod + def _inline_asm_f32(asm: str, args: Sequence[Any], shape: BlockShapeType) -> Any: + constraints = ", ".join(["=f"] + ["f"] * len(args)) + args_str = ", ".join(map(str, args)) + return V.kernel.cse.generate( + V.kernel.compute, + f"tl.inline_asm_elementwise('{asm}', '{constraints}', " + f"[{args_str}], dtype=tl.float32, is_pure=True, pack=1)", + dtype=torch.float32, + shape=shape, + ) + + @staticmethod + def _cuda_atanf(x: CSEVariable) -> CSEVariable: + # Match CUDA's device atanf implementation. This sequence mirrors + # nvcc-generated PTX for `atan(float)`: abs/reciprocal range reduction, + # a Horner polynomial in exact f32 hex constants using fma.rn, pi/2 + # reconstruction for |x| > 1, sign-bit restoration, and NaN handling. + # Triton's bundled libdevice uses a different approximation, and a + # 1 ULP atan difference can be amplified by steep consumers such as + # digamma near zero. + shape = x.shape + + def gen(expr: str, dtype: torch.dtype = torch.float32) -> TritonCSEVariable: + return V.kernel.cse.generate( + V.kernel.compute, expr, dtype=dtype, shape=shape + ) + + def fma(a: Any, b: Any, c: Any) -> Any: + return TritonOverrides._inline_asm_f32( + "fma.rn.f32 $0, $1, $2, $3;", [a, b, c], shape + ) + + c = TritonOverrides._f32_const_from_bits + one = c(0x3F800000) + inf = c(0x7F800000) + + abs_x = gen(f"tl_math.abs({x})") + large = gen(f"{abs_x} > {one}", torch.bool) + rcp = TritonOverrides._inline_asm_f32( + "rcp.approx.ftz.f32 $0, $1;", [abs_x], shape + ) + z = gen(f"tl.where({large}, {rcp}, {abs_x})") + z2 = gen(f"{z} * {z}") + + poly = fma(c(0x3B2090AA), z2, c(0xBC6BE14F)) + poly = fma(poly, z2, c(0x3D23397E)) + poly = fma(poly, z2, c(0xBD948A7A)) + poly = fma(poly, z2, c(0x3DD76B21)) + poly = fma(poly, z2, c(0xBE111E88)) + poly = fma(poly, z2, c(0x3E4CAF60)) + poly = fma(poly, z2, c(0xBEAAAA27)) + + correction = gen(f"{z2} * {poly}") + result = fma(correction, z, z) + neg_result = gen(f"-{result}") + pi_over_two_minus_result = fma(c(0x3F6EE581), c(0x3FD774EB), neg_result) + result = gen(f"tl.where({large}, {pi_over_two_minus_result}, {result})") + + sign_mask = "tl.full([], 0x80000000, tl.uint32)" + sign = gen(f"{x}.to(tl.uint32, bitcast=True) & {sign_mask}", torch.uint32) + result_bits = gen(f"{result}.to(tl.uint32, bitcast=True)", torch.uint32) + signed_bits = gen(f"{sign} | {result_bits}", torch.uint32) + signed_result = gen(f"{signed_bits}.to(tl.float32, bitcast=True)") + not_nan = gen(f"{abs_x} <= {inf}", torch.bool) + return gen(f"tl.where({not_nan}, {signed_result}, {result})") + + @staticmethod + # pyrefly: ignore [bad-override] + def atan(x): + dtype = triton_arg_dtype(x) + needs_upcast = needs_upcast_to_float32(x) + if ( + not torch.version.hip + and V.graph.get_current_device_or_throw().type == "cuda" + and isinstance(x, CSEVariable) + and (dtype == torch.float32 or needs_upcast) + ): + result_dtype = None + if needs_upcast: + result_dtype = dtype + x = V.kernel.cse.generate( + V.kernel.compute, + f"{x}.to(tl.float32)", + dtype=torch.float32, + shape=x.shape, + ) + result = TritonOverrides._cuda_atanf(x) + if result_dtype is not None and result_dtype != torch.float32: + return f"{result}.to({triton_type(result_dtype)})" + return result + + upcast = ".to(tl.float32)" if needs_upcast else "" + result = f"libdevice.atan({x}{upcast})" + if needs_upcast and dtype is not None and dtype != torch.float32: + return f"{result}.to({triton_type(dtype)})" + return result + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def atanh(x): + return f"libdevice.atanh({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def copysign(x, y): + return f"libdevice.copysign({x}, {y})" + + @staticmethod + @maybe_upcast_float32() + def erfc(x): + return f"libdevice.erfc({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def erfinv(x): + return f"libdevice.erfinv({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def hypot(x, y): + return f"libdevice.hypot({x}, {y})" + + @staticmethod + @maybe_upcast_float32() + def log10(x): + return f"libdevice.log10({x})" + + @staticmethod + @maybe_upcast_float32() + def log2(x): + return f"libdevice.log2({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def ldexp(x, n): + return f"libdevice.ldexp({x}, {n}.to(tl.int32))" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def nextafter(x, y): + return f"libdevice.nextafter({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_and(a, b): + return f"{a} & {b}" + + @staticmethod + def logical_not(a): + return f"{a} == 0" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_or(a, b): + return f"{a} | {b}" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_xor(a, b): + return f"({a} ^ {b})" + + @staticmethod + def bitwise_and(a, b): + return f"{a} & {b}" + + @staticmethod + def bitwise_not(a): + return f"~{a}" + + @staticmethod + def bitwise_or(a, b): + return f"{a} | {b}" + + @staticmethod + def bitwise_xor(a, b): + return f"{a} ^ {b}" + + @staticmethod + def bitwise_left_shift(a, b): + return f"{a} << {b}" + + @staticmethod + def bitwise_right_shift(a, b): + return f"{a} >> {b}" + + @staticmethod + def rand(seed, offset): + offset = f"({offset}).to(tl.uint32)" + if TritonOverrides._can_use_4x_random(): + (block,) = V.kernel.dense_size_list() + return f"triton_helpers.rand4x({seed}, {offset}, {block})" + return f"tl.rand({seed}, {offset})" + + @staticmethod + def _can_use_4x_random(): + return ( + isinstance(V.kernel, TritonKernel) + and not isinstance( + V.kernel, torch._inductor.select_algorithm.TritonTemplateKernel + ) + and V.graph.get_current_device_or_throw().type == "cuda" + and V.kernel.triton_tensor_ndim() == 1 + and not config.align_random_eager + ) + + @staticmethod + def rand_eager(seed, base_offset, threads_per_round, tid, vec): + # vec: 4 for fp32, 8 for fp16/bf16 + tid_u32 = f"({tid}).to(tl.uint32)" + denom = f"(({vec})*({threads_per_round}))" + r = f"(({tid_u32})//({denom})*({vec}//4))" + tid_trunc = f"(({tid_u32})%({denom}))" + + return f"triton_helpers.rand_eager_kernel({seed}, {base_offset}+{r}, {tid_trunc}, VEC={vec})" + + @staticmethod + def randn(seed, offset): + offset = f"({offset}).to(tl.uint32)" + if TritonOverrides._can_use_4x_random(): + (block,) = V.kernel.dense_size_list() + return f"triton_helpers.randn4x({seed}, {offset}, {block})" + return f"tl.randn({seed}, {offset})" + + @staticmethod + def randint64(seed, offset, low, high): + offset = f"({offset}).to(tl.uint32)" + return f"triton_helpers.randint64({seed}, {offset}, {low}, {high})" + + @staticmethod + def load_seed(name, offset): + raise NotImplementedError("ops.load_seed not implemented outside a kernel") + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def rsqrt(x): + if torch.version.hip: + return f"tl.rsqrt({x})" + else: + return f"libdevice.rsqrt({x})" + + @staticmethod + @maybe_upcast_float32() + def log1p(x): + return f"libdevice.log1p({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def tan(x): + return f"libdevice.tan({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def tanh(x): + cse_var = V.kernel.cse.varname_map.get(x) + if cse_var and hasattr(cse_var, "dtype"): + dtype = cse_var.dtype + else: + dtype = None + if ( + config.use_fast_math + and torch.version.hip + and get_triton_version() > (3, 5) + and dtype != torch.float64 + and dtype is not None + ): + # Requires upstream Triton 3.6+ for latest fast_tanhf support + # https://github.com/triton-lang/triton/pull/8551 + return f"libdevice.fast_tanhf({x})" + else: + return f"libdevice.tanh({x})" + + @staticmethod + @maybe_upcast_float32() + def sigmoid(x): + return f"tl.sigmoid({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def signbit(x): + # x < 0 is wrong for -0.0 in floating point, so use libdevice for supported floating + # dtypes on CUDA. On XPU, libdevice.signbit has a wrong float64 signature + # (https://github.com/intel/intel-xpu-backend-for-triton/issues/7345); use a bitcast-based + # sign-bit extraction as a workaround until the triton updates. + if V.graph.get_current_device_or_throw().type == "xpu": + return ( + f"({x}).to(tl.int64, bitcast=True) < 0 " + f"if ({x}).dtype is tl.float64 " + f"else (libdevice.signbit({x}) != 0) " + f"if ({x}).dtype is tl.float32 " + f"else {x} < 0" + ) + return ( + f"(libdevice.signbit({x}) != 0) " + f"if ({x}).dtype is tl.float32 or ({x}).dtype is tl.float64 " + f"else {x} < 0" + ) + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def fmod(a, b): + return f"libdevice.fmod({a}, {b})" + + @classmethod + def pow(cls, a, b): + result_dtype = get_dtype_handler().pow(a, b) + if result_dtype is not None and is_integer_dtype(result_dtype): + base = cls._cast_libdevice_arg(a, result_dtype) + exponent = ( + cls.constant(b, torch.int64) + if isinstance(b, torch._prims_common.Number) + else f"{b}" + ) + return f"triton_helpers.pow_integer({base}, {exponent})" + + any_needs_upcast = needs_upcast_to_float32(a) or needs_upcast_to_float32(b) + pow_dtype = result_dtype + if pow_dtype not in (torch.float32, torch.float64): + # libdevice.pow only accepts fp32/fp64. Keep low-precision floating + # cases on the existing fp32 path, and otherwise fall back to fp64 + # for symbolic integer scalar pow expressions like 2 ** ks0. + pow_dtype = ( + torch.float32 + if low_precision_fp(result_dtype) or any_needs_upcast + else torch.float64 + ) + if pow_dtype == torch.float64 and not device_supports_fp64( + V.graph.current_device + ): + pow_dtype = torch.float32 + if result_dtype == torch.float64: + result_dtype = torch.float32 + + cast_a = cls._cast_libdevice_arg(a, pow_dtype) + cast_b = cls._cast_libdevice_arg(b, pow_dtype) + result = f"libdevice.pow({cast_a}, {cast_b})" + if result_dtype is not None and result_dtype != pow_dtype: + if low_precision_fp(result_dtype): + if any_needs_upcast: + result = f"{result}.to({triton_type(result_dtype)})" + else: + result = f"{result}.to({triton_type(result_dtype)})" + return result + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def log(x): + if config.eager_numerics.use_pytorch_libdevice: + # Strict numerics should use the backend math library entry point. + # On ROCm this maps to OCML and avoids Triton's generic log lowering. + return f"libdevice.log({x})" + return f"tl_math.log({x})" + + @staticmethod + @maybe_upcast_float32(convert_output=False) + # pyrefly: ignore [bad-override] + def isinf(x): + return f"libdevice.isinf({x}).to(tl.int1)" + + @staticmethod + @maybe_upcast_float32(convert_output=False) + # pyrefly: ignore [bad-override] + def isnan(x): + return f"libdevice.isnan({x}).to(tl.int1)" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def round(x): + return f"libdevice.nearbyint({x})" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def floor(x): + return f"libdevice.floor({x})" + + @staticmethod + def floordiv(a, b): + # See the comment in lowering.div_mode. a and b are integer type. + # Notice that // in triton behaves as truncdiv instead of floordiv. + # + # We avoid feeding negative values into Triton's // operator because + # Triton's AxisInfo analysis incorrectly deduplicates signed division + # results for contiguous inputs (triton-lang/triton#XXXX). Instead we + # use bitwise complement (~) to make the dividend non-negative: + # floor_div(a, b) = ~(~a // b) when a < 0, a // b when a >= 0 + # For negative b we negate both operands first. + zero = ops.constant(0, torch.int32) + one = ops.constant(1, torch.int32) + # Guard against integer division by zero before the division to + # avoid undefined behavior (LLVM may optimize away a post-division + # check assuming UB doesn't happen). Replace b with 1 when b is 0 + # so the division is safe, then select 0 as the final result. + b_zero = ops.eq(b, zero) + b = ops.where(b_zero, one, b) + b_neg = ops.lt(b, zero) + a = ops.where(b_neg, ops.sub(zero, a), a) + b = ops.where(b_neg, ops.sub(zero, b), b) + a_neg = ops.lt(a, zero) + a = ops.where(a_neg, ops.bitwise_not(a), a) + quot = ops.truncdiv(a, b) + quot = ops.where(a_neg, ops.bitwise_not(quot), quot) + return ops.where(b_zero, zero, quot) + + @staticmethod + # pyrefly: ignore [bad-override] + def sign(x): + z = ops.constant(0, torch.int32) + left = ops.to_dtype((ops.lt(z, x)), torch.int8) + right = ops.to_dtype((ops.lt(x, z)), torch.int8) + sub = ops.sub(left, right) + return f"{sub}.to({x}.dtype)" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def trunc(x): + return f"libdevice.trunc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def truncdiv(a, b): + # See the comment in lowering.div_mode. a and b are integer type. + # Notice that // in triton behaves as truncdiv instead of floordiv + return f"{a} // {b}" + + @staticmethod + @maybe_upcast_float32() + # pyrefly: ignore [bad-override] + def ceil(x): + return f"libdevice.ceil({x})" + + +# Register the custom pow override after class creation so type checkers see +# a plain callable instead of the class-body staticmethod descriptor. +OpDtypeSupport.register_upcast(TritonOverrides.atan, True) +OpDtypeSupport.register_upcast(TritonOverrides.pow, True) +TritonOverrides._initialize_pointwise_overrides("triton") + + +class TritonKernelOverrides(TritonOverrides): + """Map element-wise ops to Triton within a TritonKernel + + Unlike TritonOverrides, these assume the code is going to be inserted into + the body of the main triton kernel and so it may use indexing and mask + variables which are assumed to already be defined in the current scope. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + # happens in __init__ unlike _initialize_pointwise_overrides + # because the libdevice registrations are populated during lowerings + self._setup_libdevice_routing() + + @classmethod + @functools.cache + def _setup_libdevice_routing(cls): + """Set up routing to libdevice implementations for fp64 inputs.""" + + from torch._inductor.codegen.common import OpDecompositions + + for fn_name in torch._inductor.utils.op_requires_libdevice_fp64: + if not hasattr(cls, fn_name): + raise AssertionError(f"missing method {fn_name} on {cls}") + original_impl = getattr(cls, fn_name) + + def decomposition_router(x, _original_impl, _fn_name): + if x.dtype != torch.float64: + return _original_impl(x) + else: + return getattr(OpDecompositions, _fn_name)(x).value + + if fn_name == "sigmoid": + if not hasattr(OpDecompositions, "sigmoid"): + raise AssertionError("OpDecompositions must define sigmoid") + fn = functools.partial( + decomposition_router, _original_impl=original_impl, _fn_name=fn_name + ) + fn.__name__ = fn_name # type: ignore[attr-defined] + setattr(cls, fn_name, staticmethod(fn)) + continue + + def dtype_router(x, _original_impl, _fn_name): + if x.dtype == torch.float64: + return f"libdevice.{_fn_name}({x})" + else: + return _original_impl(x) + + fn = functools.partial( + dtype_router, _original_impl=original_impl, _fn_name=fn_name + ) + fn.__name__ = fn_name # type: ignore[attr-defined] + setattr(cls, fn_name, staticmethod(fn)) + + @classmethod + def constant(cls, value, dtype): + # NOTE: Cannot use shape=[] as it's not supported by triton-rocm + # We could use shape=[1] instead but starting with the correct + # ndim avoids extra `tt.expand_dim` ops appearing in the triton IR. + ndim = V.kernel.triton_tensor_ndim() + shape = [1] * ndim + return cls._shaped_constant(value, dtype, shape=shape) + + @classmethod + def index_expr(cls, expr, dtype): + expr = _materialize_trunc_to_float_expr(expr, dtype) + indexing = V.kernel.indexing( + expr, block_ptr=False, tma_compatibility_checker=None + ) + if not isinstance(indexing, IndexingOptions): + raise AssertionError(f"expected IndexingOptions, got {type(indexing)}") + + shape: BlockShapeType + if indexing.expand_shape: + shape = indexing.expand_shape + else: + shape = TritonSymbols.get_block_shape(indexing.index) + + # Our sympy expr printing casts to the current kernel index dtype. + # We only respect non-int32/int64 dtypes and otherwise use the current + # kernel indexing dtype. Value-producing uses that need to preserve an + # explicit int dtype are rewritten to value_expr. + index_dtype = V.kernel.get_index_dtype_as_torch_dtype() + if dtype in (torch.int32, torch.int64): + cast_dtype = index_dtype + else: + cast_dtype = dtype + # to_dtype(..., use_compute_types=True) emits the Triton compute type + # for cast_dtype, so the CSE metadata must be derived from that same + # dtype. For example, float16 requests emit tl.float32 when compute + # upcasting is enabled, and should be recorded as torch.float32. + output_dtype = upcast_compute_type(cast_dtype) + var = V.kernel.cse.generate( + V.kernel.compute, + cls.to_dtype(f"({indexing.index_str})", cast_dtype), + dtype=output_dtype, + bounds=get_bounds_index_expr(expr), + shape=shape, + ) + + var.mask_vars = indexing.mask_vars + return var + + @classmethod + def value_expr(cls, expr, dtype): + """ + Like :meth:`index_expr`, but honors ``dtype`` by setting the kernel + index dtype before emitting, and casting the result if needed. + """ + real_index_dtype = V.kernel._index_dtype + V.kernel._index_dtype = ( + dtype if dtype in (torch.int32, torch.int64) else torch.int64 + ) + try: + var = cls.index_expr(expr, dtype) + finally: + V.kernel._index_dtype = real_index_dtype + if real_index_dtype != dtype or var.dtype != dtype: + var = V.kernel.cse.generate( + V.kernel.compute, + f"({var}).to({triton_type(dtype)})", + dtype=dtype, + shape=var.shape, + ) + return var + + @staticmethod + def masked(mask, body, other): + if mask is not None and torch.version.hip is not None: + mask = V.kernel.cse.generate( + V.kernel.compute, + f"{mask}.to(tl.int1)", + dtype=torch.bool, + shape=mask.shape, + ) + + nodes = body.graph.find_nodes(op="output") + if not nodes: + raise AssertionError("graph for body does not contain an output") + + need_where = False + # If we have a tl.load with a masking operator and no other value + # we can add the mask here and the other value to the tl.load + # operator to save the branching cost. + for node in nodes: + for arg in node.args: + if ( + arg.target != "load" + or should_unwrap_unspec_arg(arg.args[1]) + # A load whose producer is fused into this kernel is + # served from the CSE store cache and emits no tl.load, + # so the masked-load `other` would be silently dropped; + # fall back to an explicit tl.where. + or arg.args[1] in V.kernel.cse.store_cache + ): + need_where = True + break + + value = None if need_where else other + + with V.kernel.mask_loads(mask, value=value) as new_mask: + result = body() + + if need_where: + # Remove once CSEVariables track the dtype + if result.bounds.is_bool: + other = bool(other) + # Take dtype from result to prevent accidental promotion + other = V.kernel.cse.generate( + V.kernel.compute, + f"tl.full({result}.shape, {constant_repr(other)}, {result}.dtype)", + bounds=ValueRanges.wrap(other), + dtype=result.dtype, + shape=result.shape, + ) + ret = ops.where(new_mask, result, other) + else: + ret = result + + ret.mask_vars.discard(new_mask) + return ret + + @staticmethod + def load_seed(name, offset): + var = V.kernel.args.input(name) + return ( + f"tl.load({var} + {V.kernel.args.seed_offset('load_seed_offset', offset)})" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def frexp(x): + cache_key = f"frexp({x})" + if cse_val := V.kernel.cse.try_get(cache_key): + return cse_val + + mantissa = V.kernel.cse.newvar(dtype=x.dtype, shape=x.shape) + exponent = V.kernel.cse.newvar(dtype=torch.int32, shape=x.shape) + V.kernel.compute.writeline( + f"{mantissa}, {exponent} = triton_helpers.frexp({x})" + ) + V.kernel.cse.put(cache_key, (mantissa, exponent)) + return (mantissa, exponent) + + @staticmethod + # pyrefly: ignore [bad-override] + def partial_accumulate( + name: str, + reduction_type: str, + value: CSEVariable, + extra_meta: dict[str, Any], + ) -> None: + raise NotImplementedError + + +class HelperFunctions: + """An ordered set of helper functions.""" + + _templates_seen: dict[str, str] # Template code to function name + finalized_helpers: list[str] + + def __init__(self) -> None: + self._templates_seen = {} + self.finalized_helpers = [] + + def add(self, template_code: str, *, base_name="_triton_helper_fn") -> str: + """This accepts a function definition with the function name + left as a format specifier e.g. + + @triton.jit + def {name}(arg0, arg1): + return arg0 + arg1 + + We add the templated code to the function set and return the name + assigned to that function. + + """ + existing_name = self._templates_seen.get(template_code) + if existing_name is not None: + # Don't duplicate existing helpers + return existing_name + + name = f"{base_name}{len(self.finalized_helpers)}" + self._templates_seen[template_code] = name + self.finalized_helpers.append(template_code.format(name=name)) + return name + + def __iter__(self): + return iter(self.finalized_helpers) + + def __getitem__(self, idx): + return self.finalized_helpers[idx] + + +@dataclasses.dataclass +class BlockParameters: + """ + Class representing ND block dimensions, for block pointer analysis. + """ + + shape: list[sympy.Expr] = dataclasses.field(default_factory=list) + block_shape: list[sympy.Expr] = dataclasses.field(default_factory=list) + strides: list[sympy.Expr] = dataclasses.field(default_factory=list) + offsets: list[sympy.Expr] = dataclasses.field(default_factory=list) + + @dataclasses.dataclass + class StrideSorter: + original_strides: list[int] + sort_idx: list[int] + revert_sort_idx: list[int] = dataclasses.field(init=False) + + def __post_init__(self): + if len(self.original_strides) <= 0: + raise AssertionError("original_strides must be non-empty") + if len(self.sort_idx) != len(self.original_strides): + raise AssertionError( + f"expected len(sort_idx) == len(original_strides), got {len(self.sort_idx)} != {len(self.original_strides)}" + ) + + identity_sort_idx = list(range(len(self.original_strides))) + self._is_identity = self.sort_idx == identity_sort_idx + + # Set revert_sort_idx + sorted_dims_by_strides_map = {k: i for i, k in enumerate(self.sort_idx)} + self.revert_sort_idx = [ + sorted_dims_by_strides_map[i] + for i in range(len(sorted_dims_by_strides_map)) + ] + + @property + def is_identity(self): + return self._is_identity + + @classmethod + @abstractmethod + def create( + cls, original_strides: list[int | sympy.Expr], shape_env: ShapeEnv + ) -> BlockParameters.StrideSorter: + """Create a `StrideSorter` that can be used to sort block parameters.""" + + def sort(self, attr): + if not self.is_identity: + return [attr[i] for i in self.sort_idx] + return attr + + def revert(self, attr): + if not self.is_identity: + return [attr[i] for i in self.revert_sort_idx] + return attr + + @dataclasses.dataclass + class IdentityStrideSorter(StrideSorter): + def __post_init__(self): + super().__post_init__() + + @classmethod + def create( + cls, original_strides: list[int | sympy.Expr], shape_env: ShapeEnv + ) -> BlockParameters.StrideSorter: + return cls( + original_strides=original_strides, + sort_idx=list(range(len(original_strides))), + ) + + @dataclasses.dataclass + class TensorDecriptorStrideSorter(StrideSorter): + """ + Sorts BlockParameters dimensions with strides in descending order. + """ + + def __post_init__(self): + super().__post_init__() + + @classmethod + def create( + cls, original_strides: list[int | sympy.Expr], shape_env: ShapeEnv + ) -> BlockParameters.StrideSorter: + """ + If the strides are not all known constants or if the strides are already + sorted in descending order, return identity sort. + + For example if block_shape @ strides is [ZBLOCK, XBLOCK, YBLOCK] @ [8, 1, 16] + The indices to sort the strides in descending order will be [2, 0, 1]. + The indices to revert back to the original order will be [1, 2, 0]. + """ + identity_sort = list(range(len(original_strides))) + try: + # TODO: even if the strides are not in descending order the strides + # may be tensor descriptor compliant + # i.e. innermost stride == 1 and outer strides 16 byte aligned + # We should benchmark the effect of applying a transpose to these + # cases vs leaving them unsorted. + sort_idx = utils.argsort_sym(shape_env, original_strides, reverse=True) + except AssertionError: + # Symbolic shapes, failed to evaluate comparison expression + sort_idx = identity_sort + + return cls( + original_strides=original_strides, + sort_idx=sort_idx, + ) + + def __add__(self, other: BlockParameters) -> BlockParameters: + """ + Concatenates block parameters. + """ + cls = type(self) + a, b = tuple(dataclasses.asdict(x) for x in (self, other)) + return cls(**{key: a[key] + b[key] for key in a}) + + def maybe_sort_with_stride_order( + self, stride_sorter_cls: type[StrideSorter], shape_env: ShapeEnv + ) -> tuple[BlockParameters, BlockParameters.StrideSorter]: + """ + Sort `BlockParameter` with stride_sorter_cls. Returns block parameters + as well as a `StrideSorter` which contains information on how the sort + can be reverted. + """ + stride_sorter = stride_sorter_cls.create(self.strides, shape_env=shape_env) + params = BlockParameters( + **{ + key: stride_sorter.sort(val) + for key, val in dataclasses.asdict(self).items() + } + ) + return params, stride_sorter + + def remove_dims(self, removable_dims: list[bool]) -> BlockParameters: + """ + Remove dimensions where removable_dims is True. + """ + + def filter_dims(it): + return [ + item + for item, is_removable in zip(it, removable_dims) + if not is_removable + ] + + return BlockParameters( + **{key: filter_dims(val) for key, val in dataclasses.asdict(self).items()}, + ) + + +class CooperativeReductionWorkspaceCache: + """ + The scratch space used for cooperative reductions can be reused + after two reduction loops. This keeps track of what can be reused. + """ + + def __init__(self, args): + self.args = args + self.current_loop = [] + self.prior_loop = [] + self.ready_for_reuse = collections.defaultdict(collections.deque) + self.loop_count = 0 + self.store_count = 0 + + def allocate(self, nbytes: sympy.Expr): + cached = self.ready_for_reuse.get(nbytes) + if cached: + return cached.popleft() + ws_name, _, ws_offset = self.args.workspace(nbytes, False) + self.current_loop.append((nbytes, ws_name, ws_offset)) + return (ws_name, ws_offset) + + def on_loop_end(self): + # Buffers can be reused after 2 loop ends + for nbytes, ws_name, ws_offset in self.prior_loop: + self.ready_for_reuse[nbytes].append((ws_name, ws_offset)) + self.prior_loop = self.current_loop + self.current_loop = [] + self.loop_count += 1 + + def increment_store_count(self): + prior = self.store_count + self.store_count += 1 + return prior + + +@dataclasses.dataclass +class FixedTritonConfig: + config: dict[str, int] + + def __getitem__(self, item): + return self.config[item] + + def __contains__(self, item): + return item in self.config + + +TritonCSEKey = str | tuple[str, str] +LoadIndexBasis = tuple[IterationRangesEntry, ...] +LoadIndexBases = tuple[LoadIndexBasis | None, ...] + + +@dataclasses.dataclass(frozen=True) +class _UnresolvedLoadIndexState: + """First live load, recorded without performing range analysis.""" + + index: sympy.Expr + result: sympy.Expr + + +@dataclasses.dataclass(frozen=True) +class _ResolvedLoadIndexState: + """Last load result plus split bases resolved from an earlier live load.""" + + index: sympy.Expr + result: sympy.Expr + bases: LoadIndexBases + + +LoadIndexState = _UnresolvedLoadIndexState | _ResolvedLoadIndexState + + +class TritonCSE(CSE[TritonCSEVariable, TritonCSEKey]): + """ + Subclasses CSE to apply the current load mask to the cache key to avoid CSEing + variables across separate masked blocks. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._load_index_states: dict[TritonCSEKey, LoadIndexState] = {} + + def invalidate(self, keep_vars: OrderedSet[CSEVariable]) -> None: + super().invalidate(keep_vars) + self._load_index_states.clear() + + def augment_key(self, cache_key: str) -> TritonCSEKey: + if mask := V.kernel._load_mask: + return (cache_key, mask.name) + else: + return cache_key + + +@dataclasses.dataclass +class TMACompatibilityChecker: + """ + Checks if the TMA API can be used for load / store triton operations. + """ + + kernel: TritonKernel + dtype: torch.dtype + for_store: bool + force: bool + # Inductor buffer name being loaded from / stored to. + buffer_name: str | None = None + + def __post_init__(self): + self.failed_debug_prefix = "Cannot use TMA descriptor for load / store since: " + + # Also see Note: TMA API Restrictions for the below + def can_use_tma( + self, + ) -> bool: + if self.force: + return True + + device_type = V.graph.get_current_device_or_throw().type + if device_type == "cpu": + if not ( + config.triton.use_tensor_descriptor + and has_triton_cpu_backend() + and has_triton_stable_tma_api() + ): + log.debug( + "%s Requires Triton CPU backend and `use_tensor_descriptor` option enabled", + self.failed_debug_prefix, + ) + return False + # CPU tensor descriptors are lowered by the CPU backend instead of + # CUDA TMA hardware, so the CUDA dtype map and 16-byte store + # constraints below do not apply. + return True + + if not ( + ( + ( + device_type == "cuda" + and torch.cuda.get_device_capability()[0] >= 9 + and config.assume_aligned_inputs + ) + or device_type == "xpu" + ) + and config.triton.use_tensor_descriptor + and has_triton_stable_tma_api() + ): + log.debug( + "%s Requires triton>=3.4.0, a CUDA device with cc>=9.0," + " use_tensor_descriptor=True, and assume_aligned_inputs=True", + self.failed_debug_prefix, + ) + return False + + # Strict multirow reductions are forced persistent and can settle on + # XBLOCK=1 after the initial TMA probe. Their output store must therefore + # use the scalar fallback rather than a 16-byte tensor descriptor. + if self.for_store and ( + self.kernel.no_x_dim + or self.kernel.features.has_strict_sum_multirow_reduction() + ): + log.debug( + "%s stores with XBLOCK=1 cannot transfer 16 bytes.", + self.failed_debug_prefix, + ) + return False + + if self.dtype not in _TMA_SUPPORTED_DTYPES: + log.debug( + "%s dtype %s has no CUtensorMapDataType mapping.", + self.failed_debug_prefix, + self.dtype, + ) + return False + + return True + + def are_block_parameters_compatible( + self, + block_params: BlockParameters, + constant_offset: sympy.Expr | int = 0, + ) -> bool: + """ + Check if the block parameters are valid for TMA. + If force, we allow relying on symbolic hints equivalent + to what we check for Triton templates. + """ + device_type = V.graph.get_current_device_or_throw().type + if self.force: + strides = [ + V.graph.sizevars.replace_backed_symbols_with_hints(st) + for st in block_params.strides + ] + constant_offset_expr = V.graph.sizevars.replace_backed_symbols_with_hints( + sympy.sympify(constant_offset) + ) + else: + strides = block_params.strides + constant_offset_expr = sympy.sympify(constant_offset) + + # The TMA API requires that the innermost stride is 1 + # and that the outer strides are 16 byte aligned + if not V.graph.sizevars.statically_known_equals(strides[-1], sympy.Integer(1)): + log.debug( + "%s tensor descriptors require innermost stride to be 1. Strides are: %s", + self.failed_debug_prefix, + strides, + ) + return False + + # Early return for Triton CPU + if device_type == "cpu": + return True + + element_size = self.dtype.itemsize + for stride in strides[:-1]: + if not V.graph.sizevars.statically_known_equals( + ModularIndexing(stride * element_size, 1, sympy.Integer(16)), + sympy.Integer(0), + ): + log.debug( + "%s TMA API requires outer strides to be 16 byte aligned. Dtype bytes: %d, strides: %s", + self.failed_debug_prefix, + element_size, + strides, + ) + return False + + # Ensure the TMA descriptor base pointer maintains 16-byte alignment. + # The actual kernel-side base pointer is computed as `in_ptr + constant_offset`. + # While `in_ptr` is handled to be 16-byte aligned (see assume_aligned_inputs and copy_if_misaligned), + # adding a constant element offset may break that alignment requirement. + # We must verify that the resulting address remains 16-byte aligned after applying constant_offset. + if not V.graph.sizevars.statically_known_equals( + ModularIndexing(constant_offset_expr * element_size, 1, sympy.Integer(16)), + sympy.Integer(0), + ): + log.debug( + "%s TMA descriptor base must be 16 byte aligned but constant_offset=%s " + "with %d-byte dtype yields a non-16-byte aligned base.", + self.failed_debug_prefix, + constant_offset_expr, + element_size, + ) + return False + + # When operations like slicing, as_strided, or view(dtype=...) are folded into + # the kernel argument (for example, via reinterpret_tensor with a non-aligned + # storage_offset), the resulting buffer's data_ptr may not be 16-byte aligned. + if self.buffer_name is not None and is_unaligned_buffer_name(self.buffer_name): + log.debug( + "%s TMA descriptor base must be 16 byte aligned but buffer %s " + "is recorded as unaligned (e.g. produced by a sub-pointer " + "view / reinterpret_tensor).", + self.failed_debug_prefix, + self.buffer_name, + ) + return False + + # Now compute the minimum value of the block type that is used + # in the innermost block size that can guarantee that 16 bytes of data + # can be loaded / stored. + # Start with finding the innermost block type + innermost_block_shape = block_params.block_shape[-1] + + # Pure singleton case + if V.graph.sizevars.statically_known_equals( + innermost_block_shape, sympy.Integer(1) + ): + log.debug( + "%s innermost block shape cannot load 16 bytes. Block shape: %s", + self.failed_debug_prefix, + block_params.block_shape, + ) + return False + + innermost_block_type = None + innermost_block_symt = None + for block_type_str in innermost_block_shape.free_symbols: + for block_symt in TritonSymbols.block_types: + if symbol_is_type(block_type_str, block_symt): + innermost_block_type = block_type_str + innermost_block_symt = block_symt + break + + if not (innermost_block_type and innermost_block_symt): + raise AssertionError( + f"{innermost_block_shape} expr must contain a single block type from {TritonSymbols.block_types}" + ) + + if ( + self.kernel.features.strict_sum_rblock() == 1 + and innermost_block_symt in TritonSymbols.reduction_types + ): + log.debug( + "%s strict sum linear accumulation requires a reduction block size of 1", + self.failed_debug_prefix, + ) + return False + + # For persistent reductions, the reduction block sizes are fixed at compile time. + # Only apply this logic when the innermost block is a reduction block; + # persistent reductions can still have pointwise-style loads where the innermost block is X/Y/Z, + # and in that case we should fall back to the generic analysis below. + if ( + self.kernel.persistent_reduction + and innermost_block_symt in TritonSymbols.reduction_types + ): + # For a discontiguous tensor, a 1D block will be split across several + # dimensions, e.g. R0_BLOCK: + # block_shape=[XBLOCK, ((R0_BLOCK + 31)//32), Min(1, ((R0_BLOCK + 31)//32)), Min(32, R0_BLOCK)] + # The persistent R0_BLOCK will be a power of 2 that is at least r0_numel So it + # should be guaranteed that Min(32, R0_BLOCK) * element_size >= 16 + innermost_tree_prefix = prefix_str[innermost_block_symt] + tree_numel = None + for t in self.kernel.range_trees: + if t.is_reduction and t.prefix == innermost_tree_prefix: + tree_numel = t.numel + break + if tree_numel is None: + # If we can't map the innermost reduction block type to a reduction range tree, + # we cannot determine the persistent RBLOCK value, + # so we cannot validate the 16-byte innermost-dimension requirement for TMA. + # Treat this as incompatible rather than asserting during compilation, fallback to non-TMA loads. + log.debug( + "%s could not find reduction range tree for innermost prefix %s Block shape: %s", + self.failed_debug_prefix, + innermost_tree_prefix, + block_params.block_shape, + ) + return False + persistent_rblock = self.kernel._get_persistent_reduction_block(tree_numel) + innermost_block_bytes = ( + innermost_block_shape.subs({innermost_block_type: persistent_rblock}) + * element_size + ) + if not V.graph.sizevars.statically_known_geq( + innermost_block_bytes, sympy.Integer(16) + ): + log.debug( + "%s persistent reduction innermost block shape cannot transfer 16 bytes. Block shape: %s, persistent RBLOCK: %d", + self.failed_debug_prefix, + block_params.block_shape, + persistent_rblock, + ) + return False + + else: + # E.g. if the innermost block shape is Min(2, XBLOCK) + # then the TMA API can only be used if the dtype has an 8 byte element + # size so that 16 bytes of data can be loaded in the innermost dimension + try: + + def indexing_div_rep( + x: sympy.Expr, + y: sympy.Expr, + z: sympy.Expr | None = None, + ) -> sympy.Expr: + div = x / y + if z: + div = div % z + return div + + solve_expr = innermost_block_shape * element_size - 16 + # Sympy cannot handle FloorDiv and ModularIndexing well, so simplify + solve_expr_simplified = solve_expr.replace( + FloorDiv, indexing_div_rep + ).replace(ModularIndexing, indexing_div_rep) + min_block_size = next_power_of_2( + int( + sympy.nsolve( + solve_expr_simplified, + innermost_block_type, + 1, + ) + ) + ) + + # TODO: min block size may be too large / introduce redundancy + if min_block_size > self.kernel.max_block( + prefix_str[innermost_block_symt] + ): + log.debug( + "%s the minimum block size to satisfy expression %s is too large: %d", + self.failed_debug_prefix, + solve_expr_simplified, + min_block_size, + ) + return False + + # When no_x_dim is True, XBLOCK is fixed at 1. TMA cannot + # be used if the innermost block is XBLOCK and the minimum + # required size exceeds 1. + if ( + self.kernel.no_x_dim + and innermost_block_symt == SymT.XBLOCK + and min_block_size > 1 + ): + log.debug( + "%s no_x_dim kernel has XBLOCK fixed at 1 but TMA requires min block size %d", + self.failed_debug_prefix, + min_block_size, + ) + return False + + # In combo kernels without per-subkernel blocks, XBLOCK is + # shared and may be forced to 1 by a sibling sub-kernel. + # Reject TMA when the innermost block is XBLOCK since we + # cannot guarantee it will meet the 16-byte minimum. + if ( + self.kernel.is_combo_kernel + and not self.kernel.per_subkernel_blocks + and innermost_block_symt == SymT.XBLOCK + and min_block_size > 1 + ): + log.debug( + "%s combo kernel with shared XBLOCK cannot guarantee TMA min block size %d", + self.failed_debug_prefix, + min_block_size, + ) + return False + + block_type_str = self.kernel.index_to_str(innermost_block_type) + # Check block sizes if the user has provided a fixed triton config + if self.kernel.fixed_config: + if min_block_size > self.kernel.fixed_config[block_type_str]: + log.debug( + "%s For block %s, fixed config block size %d is smaller " + "than the minimum required: %d", + self.failed_debug_prefix, + block_type_str, + self.kernel.fixed_config[block_type_str], + min_block_size, + ) + return False + else: + # Update the minimum block sizes that are passed to triton + # heuristics + self.kernel.tma_min_block_sizes[block_type_str] = max( + min_block_size, + self.kernel.tma_min_block_sizes.get(block_type_str, 1), + ) + + except ValueError: + log.debug( + "%s innermost block shape cannot load 16 bytes. Block params: %s", + self.failed_debug_prefix, + block_params.block_shape, + ) + return False + + return True + + def can_lift(self) -> bool: + """ + Can you lift the make_tensor_descriptor + call to the top of the kernel? This requires + being certain that all of the shape, stride, + and block_shape information is handled in arguments + or top level definitions. + + Right now we assume this is always possible if you force TMA. + """ + return self.force + + +class TritonKernel(SIMDKernel[TritonCSEVariable]): + """A class to represent a triton kernel and helpers to generate + triton kernel programmatically + """ + + overrides = TritonKernelOverrides # type: ignore[assignment] + helper_functions: HelperFunctions + kexpr: Callable[[sympy.Expr], str] = texpr + allow_block_ptr = True + tma_compatibility_checker_cls = TMACompatibilityChecker + block_ptr_options_cls: type[BlockPtrOptions] = BlockPtrOptions + tensor_descriptor_options_cls: type[TensorDescriptorOptions] = ( + TensorDescriptorOptions + ) + transpose_discontiguous_tensor_descriptors_override: bool | None = None + + def __init__( + self, + tiling: dict[str, sympy.Expr], + min_elem_per_thread=0, + optimize_mask=True, + fixed_config: FixedTritonConfig | None = None, + hint_override: int | None = None, + is_combo_kernel: bool = False, + per_subkernel_blocks: bool = False, + **kwargs, + ) -> None: + self.optimize_mask: bool = optimize_mask + self.fixed_config = fixed_config + self.is_combo_kernel: bool = is_combo_kernel + self.per_subkernel_blocks: bool = per_subkernel_blocks + super().__init__(tiling, **kwargs) + self.cse = TritonCSE(self.newvar_prefix, self.suffix) + # Cache of values that can be reused for the prologue. + self.prologue_cache: dict[str, str] = {} + self.prologue: IndentedBuffer = IndentedBuffer() + self.post_loop_combine: IndentedBuffer = IndentedBuffer() + self.post_loop_store: IndentedBuffer = IndentedBuffer() + self.outside_loop_vars = OrderedSet[Any]() + self.min_elem_per_thread = min_elem_per_thread + self.block_ptr_id = itertools.count() + self.block_ptr_to_buffer = dict[str, str]() + self.helper_functions = HelperFunctions() + self.pointer_advancements: dict[SymT, dict[str, list[sympy.Expr]]] = ( + collections.defaultdict(dict) + ) + self.tma_min_block_sizes = dict[str, int]() + self.host_tma_descriptor_args: dict[str, TensorDescriptorOptions] = {} + self._host_tma_non_materializable: OrderedSet[str] = OrderedSet() + self._host_tma_non_materializable_buffers: OrderedSet[str] | None = None + self._emitted_device_tma = False + self.hint_override = hint_override + self._load_counts: collections.Counter[str] = collections.Counter() + self._pdl_load_index = 0 + self._pdl_has_wait = False + self.op_trace: list[TritonOpTraceEntry] = [] + self.op_trace_buffer_arg_names: list[str] = [] + self._op_trace_buffer_names: dict[str, str] = {} + self._op_trace_cse_names: dict[str, str] = {} + self._op_trace_symbol_names: dict[sympy.Symbol, sympy.Symbol] = {} + self._op_trace_symbol_counts: collections.Counter[str] = collections.Counter() + + # A set of autotuning hints to pass as part of triton_meta + self.autotune_hints = OrderedSet[AutotuneHint]() + self.triton_meta: TritonMeta | None = None + + if self.inside_reduction: + self.codegen_reduction_numels(self.body) + + if self.cooperative_reduction: + self.init_cooperative_reduction() + + self.codegen_range_tree() + + if self.cooperative_reduction: + self.init_cooperative_reduction_mask() + + self.has_load_with_contiguous_rdim = False + # We track the store name since a store can be canceled later + self.stores_with_contiguous_rdim: list[str] = [] + + @property + def uses_tma(self) -> bool: + return bool(self.host_tma_descriptor_args or self._emitted_device_tma) + + @property + def uses_device_tma(self) -> bool: + return self._emitted_device_tma + + def triton_tensor_ndim(self) -> int: + return sum(int(tree.tensor_dim is not None) for tree in self.range_trees) + + def indexing_size_str(self, i: int) -> str: + sizes = ["None"] * self.triton_tensor_ndim() + sizes[i] = ":" + return f"[{', '.join(sizes)}]" + + def dense_size_list(self) -> list[str]: + sizes = ["1"] * self.triton_tensor_ndim() + for tree in self.active_range_trees(): + if tree.tensor_dim is not None: + sizes[tree.tensor_dim] = tree.block_size_str() + return sizes + + def dense_size_str(self) -> str: + return f"[{', '.join(self.dense_size_list())}]" + + def create_constant_mask(self, entry: IterationRangesRoot) -> str: + if entry.tensor_dim is None: + return ( + f"{entry.mask_name()} = tl.full({self.dense_size_str()}, True, tl.int1)" + ) + sizes = ["None"] * self.triton_tensor_ndim() + sizes[entry.tensor_dim] = ":" + suffix = ", ".join(sizes) + return ( + f"{entry.mask_name()} = " + f"tl.full([{entry.block_size_str()}], True, tl.int1)[{suffix}]" + ) + + def _trace_kernel_arg(self, name: str, *, store: bool) -> str: + if name in V.graph.removed_buffers: + return name + if store: + return self.args.output(name) + return self.args.input(name) + + def _trace_buffer(self, name: str, *, store: bool) -> str: + if name not in self._op_trace_buffer_names: + self._op_trace_buffer_names[name] = ( + f"buffer{len(self._op_trace_buffer_names)}" + ) + self.op_trace_buffer_arg_names.append( + self._trace_kernel_arg(name, store=store) + ) + return self._op_trace_buffer_names[name] + + def _trace_cse_var(self, var: CSEVariable) -> tuple[str, str, str, Any]: + if var.name not in self._op_trace_cse_names: + self._op_trace_cse_names[var.name] = f"tmp{len(self._op_trace_cse_names)}" + return ( + "cse", + self._op_trace_cse_names[var.name], + str(var.dtype), + self._normalize_trace_value(var.shape), + ) + + @staticmethod + def _trace_symbol_prefix(symbol: sympy.Symbol) -> str | None: + for symt in ( + SymT.XBLOCK, + SymT.YBLOCK, + SymT.ZBLOCK, + SymT.R0_INDEX, + SymT.R1_INDEX, + ): + if symbol_is_type(symbol, symt): + return prefix_str[symt] + return None + + def _trace_symbol(self, symbol: sympy.Symbol) -> sympy.Symbol: + if symbol in self._op_trace_symbol_names: + return self._op_trace_symbol_names[symbol] + + if symbol_is_type(symbol, SymT.TMP): + name = self._op_trace_cse_names.get(symbol.name) + if name is not None: + normalized = sympy.Symbol(name) + self._op_trace_symbol_names[symbol] = normalized + return normalized + + prefix = self._trace_symbol_prefix(symbol) + if prefix is None: + return symbol + + count = self._op_trace_symbol_counts[prefix] + self._op_trace_symbol_counts[prefix] += 1 + normalized = sympy.Symbol(f"{prefix}{count}", **symbol.assumptions0) + self._op_trace_symbol_names[symbol] = normalized + return normalized + + def _normalize_trace_expr(self, expr: sympy.Expr) -> str: + replacements = { + symbol: self._trace_symbol(symbol) + for symbol in sorted(expr.free_symbols, key=operator.attrgetter("name")) + } + if replacements: + expr = sympy_subs(expr, replacements) + return texpr(expr) + + def _normalize_trace_value(self, value: Any) -> Any: + if isinstance(value, CSEVariable): + return self._trace_cse_var(value) + if isinstance(value, sympy.Expr): + return ("sympy", self._normalize_trace_expr(value)) + if isinstance(value, torch.dtype): + return ("dtype", str(value)) + if isinstance(value, (list, tuple)): + return tuple(self._normalize_trace_value(x) for x in value) + if isinstance(value, dict): + return tuple( + (key, self._normalize_trace_value(val)) + for key, val in sorted(value.items()) + ) + return value + + def record_op_trace( + self, + name: str, + args: tuple[Any, ...], + kwargs: dict[str, Any], + result: Any = None, + ) -> None: + if not self.is_combo_kernel: + return + + if name == "load": + buffer_name, index = args + normalized_args = ( + self._trace_buffer(buffer_name, store=False), + self._normalize_trace_value(index), + ) + elif name == "store": + buffer_name, index, value, mode = args + normalized_args = ( + self._trace_buffer(buffer_name, store=True), + self._normalize_trace_value(index), + self._normalize_trace_value(value), + self._normalize_trace_value(mode), + ) + else: + normalized_args = tuple(self._normalize_trace_value(arg) for arg in args) + + self.op_trace.append( + TritonOpTraceEntry( + name=name, + args=normalized_args, + kwargs=tuple( + (key, self._normalize_trace_value(value)) + for key, value in sorted(kwargs.items()) + ), + result=self._normalize_trace_value(result), + ) + ) + + @staticmethod + def _has_stride1_on_rdim(index) -> bool: + # These analysis is only needed in deterministic mode so far + # to filter triton configs. Return false immediately to avoid + # increasing compilation time when the mode is off. + if not ( + config.deterministic or config.test_configs.force_filter_reduction_configs + ): + return False + support_vars = index.free_symbols + reduce_vars = [ + var + for var in support_vars + if symbol_is_type(var, TritonSymbols.reduction_types) + ] + + if len(reduce_vars) == 0: + return False + + # for expression "x0 + 150528*((x1//(s27*s38))) + 3*(ModularIndexing(x1, 1, s38)) + 672*(ModularIndexing(x1, s38, s27))" + # stride_vars will results in DivisionByZero error + try: + stride_vars = V.graph.sizevars.stride_vars(index, reduce_vars, support_vars) + except ZeroDivisionError: + return False + + return any(stride == 1 for stride in stride_vars) + + @staticmethod + def _is_host_tma_materializable( + indexing: TensorDescriptorOptions, + dtype: torch.dtype | None = None, + ) -> bool: + """Whether the host launcher can build a TensorDescriptor for this + access (not a TMA eligibility check -- that's TMACompatibilityChecker). + """ + if dtype is not None and dtype == torch.bool: + return False + for dim in indexing.block_shape: + if isinstance(dim, (int, sympy.Integer)): + continue + if isinstance(dim, sympy.Symbol): + continue + return False + return True + + def _prescan_host_tma_materializability(self) -> None: + """Populate _host_tma_non_materializable_buffers with buffers that + can't be expressed as a single host-side TMA descriptor.""" + if not config.triton.use_tensor_descriptor: + # Host TMA is off; mark as scanned (no bad buffers, won't change). + self._host_tma_non_materializable_buffers = OrderedSet() + return + self._host_tma_non_materializable_buffers = OrderedSet() + + from .simd_kernel_features import NodeScheduleMarker + + range_tree_symbols = OrderedSet(tree.symbol() for tree in self.range_trees) + if not range_tree_symbols: + return + + from torch.utils._sympy.functions import FloorDiv, ModularIndexing + + buffer_read_indices: dict[ + str, list[tuple[sympy.Expr, tuple[sympy.Symbol, ...]]] + ] = collections.defaultdict(list) + for node in NodeScheduleMarker.only_nodes(self.features.node_schedule): + for dep in node.read_writes.reads: + if not hasattr(dep, "var_names"): + if hasattr(dep, "name"): + self._host_tma_non_materializable_buffers.add(dep.name) + continue + buffer_read_indices[dep.name].append((dep.index, dep.var_names)) + + for buf_name, reads in buffer_read_indices.items(): + if buf_name in self._host_tma_non_materializable_buffers: + continue + + for index, var_names in reads: + dep_vars = OrderedSet(var_names) + + if any(symbol_is_type(s, SymT.TMP) for s in index.free_symbols): + self._host_tma_non_materializable_buffers.add(buf_name) + break + + for expr_node in sympy.preorder_traversal(index): + if isinstance(expr_node, (FloorDiv, ModularIndexing)): + if expr_node.free_symbols & dep_vars: + self._host_tma_non_materializable_buffers.add(buf_name) + break + else: + continue + break + + if buf_name in self._host_tma_non_materializable_buffers: + continue + + if len(reads) > 1: + self._host_tma_non_materializable_buffers.add(buf_name) + + def _check_buffer_alignment(self, name: str, var: str, dtype: torch.dtype) -> bool: + """Whether a buffer's layout offset can't be proven TMA-aligned, so + host-side TMA must be skipped. The CUtensorMap alignment requirement is + CUDA-specific, so this only applies on CUDA; an offset that is not + statically known to be a multiple of TMA_ALIGNMENT is treated as + misaligned (conservative). + """ + if not config.triton.use_tensor_descriptor: + return False + if V.graph.get_current_device_or_throw().type != "cuda": + return False + buf = V.graph.try_get_buffer(name) + if buf is None and hasattr(V.graph, "scheduler") and V.graph.scheduler: + real_name = V.graph.scheduler.mutation_real_name.get(name, name) + if real_name != name: + buf = V.graph.try_get_buffer(real_name) + if buf is None: + return False + layout_offset = getattr(buf.get_layout(), "offset", 0) + if layout_offset == 0: + return False + offset_bytes = layout_offset * dtype.itemsize + if V.graph.sizevars.statically_known_multiple_of(offset_bytes, TMA_ALIGNMENT): + return False + self._host_tma_non_materializable.add(var) + self.host_tma_descriptor_args.pop(var, None) + return True + + @property + def has_store_with_contiguous_rdim(self) -> bool: + return not all( + is_buffer_removed(name) for name in self.stores_with_contiguous_rdim + ) + + def dtype_to_str(self, dtype: torch.dtype) -> str: + return triton_type(dtype) + + def should_use_cooperative_reduction(self) -> bool: + if self._strict_sum_rblock() is not None: + return False + return self.inside_reduction and V.choices.should_use_cooperative_reduction( + V.graph.get_current_device_or_throw(), + self.features.numel, + self.features.reduction_numel, + ) + + def init_cooperative_reduction(self): + """One time setup code for cooperative reductions.""" + if not self.cooperative_reduction: + raise AssertionError("expected cooperative_reduction") + + # shift all the grids over since tl.program_id(0) is for rsplit + for tree in self.range_trees: + if tree.grid_dim is not None: + tree.grid_dim += 1 + + sem_count = self.numels["x"] + if self.fixed_config: + sem_count = CeilDiv(sem_count, self.fixed_config["XBLOCK"]) + self.semaphores_name = self.args.semaphores(sem_count) + self.cooperative_reduction_workspace_cache = CooperativeReductionWorkspaceCache( + self.args + ) + self.body.splice( + """\ + RSPLIT_NEXT_POWER_OF_2: tl.constexpr = triton_helpers.constexpr_next_power_of_2(RSPLIT) + RSPLIT_IS_POWER_OF_2: tl.constexpr = RSPLIT == RSPLIT_NEXT_POWER_OF_2 + HAS_RSPLIT: tl.constexpr = RSPLIT > 1 + rsplit_id = tl.program_id(0) + num_rblocks = (rnumel + RBLOCK - 1) // RBLOCK + rsplit_chunk = (num_rblocks + RSPLIT - 1) // RSPLIT * RBLOCK + rsplit_start = rsplit_chunk * rsplit_id + rsplit_end = rsplit_chunk * (rsplit_id + 1) + """, + ) + if any( + not self._has_constant_mask(tree) + for tree in self.range_trees + if tree.is_reduction + ): + self.body.writeline( + "rsplit_end = tl.where(rsplit_end < rnumel, rsplit_end, rnumel)" + ) + + def init_cooperative_reduction_mask(self): + rsplit_arange = "tl.arange(0, RSPLIT_NEXT_POWER_OF_2)" + if not self.no_x_dim: + rsplit_arange = f"{rsplit_arange}[None, :]" + self.body.writeline(f"rsplit_arange = {rsplit_arange}") + + if self._has_constant_xmask(): + self.body.splice( + """\ + if RSPLIT_IS_POWER_OF_2: + rsplit_mask: tl.constexpr = None + else: + rsplit_mask = rsplit_arange < RSPLIT + """ + ) + else: + if self.no_x_dim: + raise AssertionError("expected no_x_dim to be False") + self.body.writeline( + "rsplit_mask = xmask if RSPLIT_IS_POWER_OF_2 else ((rsplit_arange < RSPLIT) & xmask)" + ) + + def codegen_range_tree(self): + for tree in self.range_trees: + # reduction indexing goes inside a loop + if not tree.is_loop: + self.iteration_ranges_codegen_header(tree, self.body) + elif self.inside_reduction: + # workaround for this issue: + # https://gist.github.com/jansel/6527126f781559095c5531f98a4235a7 + self.body.writeline( + f"{tree.prefix}base = {self.iteration_ranges_ranges_code(tree)}" + ) + + if self.inside_reduction: + if any(tree.is_loop for tree in self.range_trees): + # If the kernel contains loops, compute rbase. + rn_bases = self._get_reduction_symbols( + "base", integer=True, nonnegative=True + ) + rbase = self._flatten_reduction_indices(rn_bases) + self.body.splice(f"rbase = {self.index_to_str(rbase)}") + else: + # For looped reductions, indexing is deferred to the innermost loop. + self.codegen_reduction_indices(self.body) + + def need_numel_args(self): + """ + Indicate whether we need provide numel as arguments for the generated + kernel calls in the benchmark. + + Should be true for pointwise/reduction kernels but false for triton + matmul kernels. + """ + return True + + def should_use_persistent_reduction(self) -> bool: + if not self.inside_reduction: + return False + # ops.sort requires persistent reduction (TritonKernel.sort asserts it), so the + # heuristic must never say otherwise. Enforcing it here covers every construction + # path, including ones that don't apply apply_feature_required_overrides. + if self.features.contains_op("sort") and self.has_persistent_RBLOCK( + self.features.reduction_numel + ): + return True + features = self.features.with_tiling_scores(self.tiling_scores) + return V.choices.should_use_persistent_reduction( + features, self.cooperative_reduction + ) + + @cache_on_self + def _strict_sum_rblock(self) -> int | None: + if self.num_reduction_dims != 1: + return None + return self.features.strict_sum_rblock() + + def want_no_x_dim(self): + return ( + self.persistent_reduction + and len(self.numels) == self.num_reduction_dims + 1 + and self.fixed_config + and self.fixed_config["XBLOCK"] == 1 + ) + + @property + def assert_function(self) -> str: + return "tl.device_assert" + + def indexing( + self, + index: sympy.Expr, + *, + copy_shape: str | tuple[str] | None = None, + dense_indexing=False, + override_mask=None, + block_ptr=False, + tma_compatibility_checker: TMACompatibilityChecker | None = None, + mask_constant_index=False, + ): + """ + Compute the index and mask to pass to tl.load() or tl.store() + """ + index = self.prepare_indexing(index) + index_vars = index.free_symbols + has_rindex = False + + mask_vars: OrderedSet[str] = OrderedSet() + for var in sorted(index_vars, key=operator.attrgetter("name")): + if not isinstance(var, sympy.Symbol): + raise AssertionError(f"expected sympy.Symbol, got {type(var)}") + has_rindex = has_rindex or TritonSymbols.is_reduction_index_symbol( + self, var + ) + if override_mask: + pass + elif symbol_is_type(var, SymT.TMP): + # indirect indexing + cse_var = self.cse.varname_map[var.name] + mask_vars.update(cse_var.mask_vars) + elif symbol_is_type( + var, + ( + SymT.UNBACKED_INT, + SymT.SIZE, + SymT.PRECOMPUTED_SIZE, + SymT.INDEX, + SymT.FLOAT, + SymT.UNBACKED_FLOAT, + ), + ): + pass + else: + if ( + mask_name := TritonSymbols.mask_name_for_symbol(self, var) + ) is not None: + mask_vars.add(mask_name) + + need_dense = ( + config.triton.dense_indexing + or dense_indexing + or self._load_mask is not None + ) and index != 0 + + have_dense = True + have_loop_vars = False + dense_mask_vars: OrderedSet[str] = OrderedSet() + + for tree in self.active_range_trees(): + if index_vars.intersection(tree.var_list): + have_loop_vars = True + else: + have_dense = False + dense_mask_vars.add(tree.mask_name()) + + if ( + ( + (block_ptr and self.allow_block_ptr and config.triton.use_block_ptr) + or ( + tma_compatibility_checker + and tma_compatibility_checker.can_use_tma() + ) + ) + and not override_mask + and not self._load_mask + and len(mask_vars - dense_mask_vars) == 0 + and not self.is_indirect_indexing(index) + and have_loop_vars + # workaround https://github.com/triton-lang/triton/issues/2821 + and self.index_dtype == "tl.int32" + ): + + def match_affine_block( + index: sympy.Expr, range_tree: IterationRangesRoot + ) -> BlockParameters | None: + """ + Matches expressions of the form: + idx = s * xindex + + This implies stride (s,), and shape (XBLOCK,). + """ + stride = BlockPatternMatcher.match_affine_block_expr( + index, range_tree.symbol() + ) + if stride is None: + return None + + return BlockParameters( + shape=[range_tree.numel], + block_shape=[TritonSymbols.get_block_size(range_tree)], + strides=[stride], + offsets=[TritonSymbols.get_block_offset(range_tree)], + ) + + def match_mod_div_block( + index: sympy.Expr, range_tree: IterationRangesRoot + ) -> BlockParameters | None: + """ + Matches higher-dimensional blocks coming from FloorDiv and ModularIndexing. + + Example expression to match: + sN * ((rindex//(d1 * ... * d(N-1)))) + + s1 * ModularIndexing(rindex, 1, d1) + + ... + + s(N-1) * ModularIndexing(rindex, d1 * ... * d(N-2), d(N-1)) + + This iterates over a block of shape (dN, ..., d1) and stride + (sN, ..., s1). (d1,...,d(N-1)) and (s1,...,sN) are + wildcards that we match. + + Note that dN does not appear in the expression, but we solve for it + using range tree numels and the other dims. + """ + index_var = range_tree.symbol() + + # Bound the possible number of dims. We use the following heuristics: + # - At least one dim for each range tree node. + # - At least one dim for every FloorDiv or ModularIndexing op. + # - At least 2 dims to pattern match. + denom, modulo = sympy.symbols( + "denom modulo", + cls=functools.partial(sympy.Wild, exclude=[index_var]), + ) + + num_dims = max( + 2, + # range_tree.nodes only includes the entries for the range tree + # len(range_tree.nodes) <= self.range_tree_nodes + len(range_tree.nodes), + ( + index.count(FloorDiv(index_var, denom)) + + index.count(ModularIndexing(index_var, denom, modulo)) + ), + ) + + # [Note: Precomputed replacements with BlockPatternMatch] + # If there are precomputed replacements in an expression e.g. + # ModularIndexing(d0 * d1, d0, d1), replaced with + # ModularIndexing(p0, d0, d1), it is not possible to match p0 + # with d0 * d1 since sympy is unaware of this fact. Precomputed + # replacements are therefore removed prior to matching a + # BlockPattern, and are reintroduced after any analysis that + # works best on an expression with precomputed replacements removed + sizevars = V.graph.sizevars + index = sizevars.remove_precomputed_replacements(index) + numel = sizevars.remove_precomputed_replacements(range_tree.numel) + + match_result = BlockPatternMatcher.match_mod_div_block_expr( + index, index_var, numel, num_dims + ) + if match_result is None: + return None + + ( + dims, + strides, + block_index_exprs, + ) = match_result + slice_numels = BlockPatternMatcher.get_slice_numels(dims) + + # Check for applicable iteration range sizes. + # When mapping a 1D block into an ND one, we need to know that + # the number of elements is not changed. This means the slice numels of + # the ND iteration range must evenly divide the length of the 1D block. + # There are two cases where we can guarantee this: + # 1. Numels are powers of 2. If numel == 2 ** n, and we know XBLOCK == 2 ** m, + # with n and m integers, then either numel is a multiple of XBLOCK, or numel + # is less than XBLOCK. (If numel is less than XBLOCK, we round up to 1 below.) + # 2. Numels are multiples of the maximum possible block size. + sizevars = V.graph.sizevars + max_block = self.max_block(range_tree.prefix) + if any( + not sizevars.statically_known_multiple_of(numel, max_block) + and not sizevars.statically_known_power_of_2(numel) + for numel in slice_numels + ): + return None + + # Compute the ND block shape from the linear block size. + # Use CielDiv to round leading dimensions up to 1. + # Non-leading dimensions are clamped to the size of the iteration range, + # while the leading dimension can exceed this to accommodate a larger + # block size. + # See [Note: Precomputed replacements with BlockPatternMatch] for + # the call to lookup_precomputed_size + linear_block_size = TritonSymbols.get_block_size(range_tree) + block_shape: list[sympy.Expr] = [ + CeilDiv( + linear_block_size, + sizevars.lookup_precomputed_size(slice_numels[0]), + ) + ] + [ + Min( + CeilDiv( + linear_block_size, sizevars.lookup_precomputed_size(numel) + ), + sizevars.lookup_precomputed_size(dim), + ) + for numel, dim in zip(slice_numels[1:], dims[1:]) + ] + + # Compute block offsets from {xyzr}offset and the matched expressions. + block_offsets: list[sympy.Expr] = [ + sympy_subs( + expr, {index_var: TritonSymbols.get_block_offset(range_tree)} + ) + for expr in block_index_exprs + ] + + return BlockParameters( + shape=[sizevars.lookup_precomputed_size(d) for d in dims], + block_shape=block_shape, + strides=strides, + offsets=block_offsets, + ) + + def match_block_subexpr( + expr: sympy.Expr, + range_tree: IterationRangesRoot, + ) -> BlockParameters | None: + """ + Match a block indexing subexpression involving a single range tree. + """ + for match_func in ( + match_affine_block, + match_mod_div_block, + ): + factored_index_expr = BlockPatternMatcher.factor_index_expr( + expr, range_tree.symbol() + ) + match = match_func(factored_index_expr, range_tree) + if match is not None: + return match + + return None + + def match_block_expr() -> BlockDescriptorOptions | None: + index_relative_to_xyr_index = sympy_subs( + index, {v: t.expr for v, t in self.range_tree_nodes.items()} + ) + range_trees = self.active_range_trees() + + # Partition the index into subexpressions pertaining to each range tree. + # For example xindex * 5 + r0_index * 3 is partitioned to + # (xindex * 5, r0_index * 3). + index_subexprs = [ + BlockPatternMatcher.get_subexpr_involving_symbol( + index_relative_to_xyr_index, tree.symbol() + ) + for tree in range_trees + ] + + # Match each range tree's subexpression separately. + range_symbols = OrderedSet(tree.symbol() for tree in range_trees) + block_params = BlockParameters() + for tree, subexpr in zip(range_trees, index_subexprs): + # Reject mixed terms, e.g. xindex * r0_index. + # NB: the zero expression is allowed, for broadcasting. + if len(range_symbols.intersection(subexpr.free_symbols)) > 1: + return None + + # Match the subexpression for this range tree. + params = match_block_subexpr(subexpr, tree) + if params is None: + return None + block_params += params + + # Collect leftover terms as a constant offset. + offset = index_relative_to_xyr_index - sum(index_subexprs) + + # Form the block pointer or TMA descriptor. + self.filter_masks(mask_vars) + + options_class = ( + self.block_ptr_options_cls + if config.triton.use_block_ptr + else self.tensor_descriptor_options_cls + ) + nonlocal tma_compatibility_checker + stride_sorter_cls: type[BlockParameters.StrideSorter] + if config.triton.use_block_ptr: + can_lift = False + stride_sorter_cls = BlockParameters.IdentityStrideSorter + else: + tma_compatibility_checker = cast( + TMACompatibilityChecker, tma_compatibility_checker + ) + can_lift = tma_compatibility_checker.can_lift() + + if ( + self.transpose_discontiguous_tensor_descriptors_override + is not None + ): + transpose_contiguous = ( + self.transpose_discontiguous_tensor_descriptors_override + ) + else: + transpose_contiguous = ( + config.triton.transpose_discontiguous_tensor_descriptor + ) + + # For templates: + # Only try transpose if we know the output shape + # in case we need to transpose the data. + if hasattr(self, "template_out_shape"): + transpose_contiguous &= copy_shape is not None + + stride_sorter_cls = ( + BlockParameters.TensorDecriptorStrideSorter + if transpose_contiguous + else BlockParameters.IdentityStrideSorter + ) + + options = options_class.create( + params=block_params, + constant_offset=offset, + range_trees=range_trees, + mask_vars=mask_vars, + get_max_block=self.max_block, + can_lift=can_lift, + stride_sorter_cls=stride_sorter_cls, + ) + if isinstance(options, TensorDescriptorOptions): + tma_compatibility_checker = cast( + TMACompatibilityChecker, tma_compatibility_checker + ) + if not tma_compatibility_checker.are_block_parameters_compatible( + options.params, + constant_offset=options.constant_offset, + ): + return None + + return options + + # Return a block pointer, if indexing matches the pattern. + options = match_block_expr() + if options is not None: + return options + expand_str = None + expand_shape: BlockShapeType = None + index_str = self.index_to_str(index) + + def _get_expand_str(): + if copy_shape: + if isinstance(copy_shape, str): + return f"{copy_shape}.shape", None + else: + return "[" + ", ".join(str(c) for c in copy_shape) + "]", copy_shape + else: + return self.dense_size_str(), tuple(self.dense_size_list()) + + if is_sympy_integer_like(index): + # Integer indexing produces a size-1 scalar tensor with the same shape + # as the dense dimension. E.g, if dense_size = [YBLOCK, XBLOCK, R0_BLOCK], + # then we create tl.full([1, 1, 1], int). + # + # Exceptions: + # 1. If copy_shape is explicitly provided, use copy_shape expansion instead. + # 2. If the dense tensor has only one dimension (e.g., [XBLOCK]), + # broadcasting does not apply. For example: + # tl.arange(0, XBLOCK) + tl.full([1], int) # -> broadcasting error + # In this case, we fall back to dense indexing: + # tl.full([XBLOCK], int) + if copy_shape or len(self.dense_size_list()) == 1: + expand_str, expand_shape = _get_expand_str() + else: + expand_str = str([1] * len(self.dense_size_list())) + expand_shape = tuple([1] * len(self.dense_size_list())) + + index_str = f"tl.full({expand_str}, {index_str}, tl.int32)" + if self.fixed_config or self.is_combo_kernel or mask_constant_index: + mask_vars = OrderedSet( + tree.mask_name() + for tree in self.range_trees + if not tree.is_reduction and not self._has_constant_mask(tree) + ) + else: + mask_vars = OrderedSet() + if self._load_mask: + mask_vars.add(self._load_mask) + return IndexingOptions( + index_str, + mask_vars, + expand_str, + has_rindex, + index, + expand_shape=expand_shape, + ) + + if need_dense and not have_dense: + if self.inside_reduction and self.is_native_matmul: + # This avoids full broadcasting (need_dense) when performing native matmul. + # For example, self._load_mask previously required tl.broadcast_to() in index_str. + # Due to the restrictions of tl.dot semantics, we only want to expand the block + # shape for the necessary axes. + # + # Previously: + # tmp1 = tl.load(ptr + tl.broadcast_to(r0, [YBLOCK, XBLOCK, R0_BLOCK]), + # r0_mask & tmp0 & xmask) + # + # Now: + # tmp1 = tl.load(ptr + tl.broadcast_to(r0, [1, 1, R0_BLOCK]), + # r0_mask & tmp0 & xmask) + # + # We achieve this by determining the required block shape through mask inspection. + # When a temporary variable appears in the mask (e.g., self._load_mask), we retrieve + # its true shape by inspecting tmp.mask_vars tracked by TritonCSEVariable. + # + # Caution: it may miss the correct block shape if the specific mask was constant + # and thus not tracked in TritonCSEVariable.mask_vars. + # + # TODO: Once the shape propagation PR lands, reimplement this logic: + # https://github.com/pytorch/pytorch/pull/152198 + mask_shape = mask_vars.copy() + if self._load_mask: + mask_shape.add(self._load_mask) + + axis_masks = OrderedSet( + tree.mask_name() for tree in self.active_range_trees() + ) + while not mask_shape.issubset(axis_masks): + tmp_masks = mask_shape.difference(axis_masks) + tmp = tmp_masks.pop() + if not isinstance(tmp, TritonCSEVariable): + raise AssertionError( + f"expected TritonCSEVariable, got {type(tmp)}" + ) + mask_shape.discard(tmp) + mask_shape.update(tmp.mask_vars) + + # e.g., expand_list becomes ['ZBLOCK', 1, 1, 'R0_BLOCK'] + expand_list = ["1"] * len(self.dense_size_list()) + for mask in mask_shape: + if not isinstance(mask, str): + raise AssertionError(f"expected str mask, got {type(mask)}") + for tree in self.active_range_trees(): + if tree.owns_mask(mask): + dim = tree.tensor_dim + if not isinstance(dim, int): + raise AssertionError( + f"expected int dim, got {type(dim)}" + ) + expand_list[dim] = self.dense_size_list()[dim] + + expand_str = "[" + ",".join(map(str, expand_list)) + "]" + expand_shape = tuple(expand_list) + index_str = f"tl.broadcast_to({index_str}, {expand_str})" + else: + expand_str, expand_shape = _get_expand_str() + index_str = f"tl.broadcast_to({index_str}, {expand_str})" + mask_vars = dense_mask_vars + elif not have_loop_vars and copy_shape: + expand_shape_str, expand_shape = _get_expand_str() + index_str = f"tl.broadcast_to({index_str}, {expand_shape_str})" + mask_vars = dense_mask_vars + + if expand_shape is None: + if need_dense or have_dense: + _, expand_shape = _get_expand_str() + else: + expand_shape = () + + if override_mask: + mask_vars = OrderedSet([override_mask]) + + if self._load_mask: + mask_vars.add(self._load_mask) + + self.filter_masks(mask_vars) + + return IndexingOptions( + index_str, + mask_vars, + expand_str, + has_rindex, + index, + expand_shape=expand_shape, + ) + + def codegen_block_ptr( + self, + name: str, + var: str, + indexing: BlockPtrOptions | TensorDescriptorOptions, + other="", + ) -> tuple[str, str]: + """Generate a block pointer or tensor descriptor for Triton kernel operations. + + This method creates either a block pointer (for regular Triton operations) or + a tensor descriptor (for TMA operations) based on the indexing type. It handles + caching and reuse of descriptors for performance optimization. + + Args: + name: The name of the buffer/tensor being accessed + var: The variable name for the pointer + indexing: Block pointer options or tensor descriptor options containing + indexing information and boundary check settings + other: Additional parameters string (e.g., padding options) + + Returns: + A tuple containing: + - block_descriptor: The generated block pointer or tensor descriptor variable name + - other: Modified additional parameters string with boundary check options + """ + check = indexing.boundary_check() + if isinstance(indexing, TensorDescriptorOptions): + if check and other: + # The TMA API currently does not support padding values + # but the default is zero + if other != ", other=0.0": + raise AssertionError(f"expected ', other=0.0', got {other!r}") + other = "" + + # Host-side TMA: an aligned, zero-offset, materializable buffer whose + # descriptor can be built on the host. Register it and return early -- + # no in-kernel tl.make_tensor_descriptor is emitted for it. + if ( + has_triton_stable_tma_api() + and config.triton.enable_host_side_tma + and not indexing.can_lift + and indexing.constant_offset == 0 + and var not in self._host_tma_non_materializable + and self._is_host_tma_materializable(indexing, V.graph.get_dtype(name)) + ): + if var not in self.host_tma_descriptor_args: + self.host_tma_descriptor_args[var] = indexing + return var, other + # A non-zero constant offset can't be host-TMA'd: mark it + # non-materializable and fall through to device-side TMA below. + elif ( + has_triton_stable_tma_api() + and config.triton.enable_host_side_tma + and not indexing.can_lift + and indexing.constant_offset != 0 + ): + self._host_tma_non_materializable.add(var) + if var in self.host_tma_descriptor_args: + del self.host_tma_descriptor_args[var] + + # Device-side TMA: reached for every case except the host-TMA branch + # above (which returned) -- emit an in-kernel tl.make_tensor_descriptor. + self._emitted_device_tma = True + + else: + if not check: + # workaround https://github.com/triton-lang/triton/issues/2813 + other = "" + elif other: + if other != ", other=0.0": + raise AssertionError(f"expected ', other=0.0', got {other!r}") + other = f", boundary_check={check!r}, padding_option='zero'" + else: + other = f", boundary_check={check!r}" + + if ( + self.inside_reduction + and self.range_trees[-1].is_loop + and indexing.has_rindex() + ) or indexing.can_lift: + if indexing.can_lift and var in self.prologue_cache: + # Check for epilogue subtiling to reuse the same + # tensor descriptor. + block_descriptor = self.prologue_cache[var] + else: + block_ptr_line = indexing.format(var, roffset=False) + block_var = self.cse.try_get(block_ptr_line) + + # Early return if block descriptor already exists + if block_var: + return str(block_var), other + + block_descriptor_id = next(self.block_ptr_id) + if isinstance(indexing, BlockPtrOptions): + block_descriptor = f"block_ptr{block_descriptor_id}" + else: + block_descriptor = f"tma_descriptor{block_descriptor_id}" + named_var = self.cse.namedvar( + block_descriptor, dtype=torch.uint64, shape=[] + ) + self.cse.put(block_ptr_line, named_var) + + line_body = DeferredLine(name, f"{block_descriptor} = {block_ptr_line}") + if indexing.can_lift: + self.prologue.writeline(line_body) + # Cache the descriptor for epilogue subtiling + self.prologue_cache[var] = block_descriptor + else: + self.body.writeline(line_body) + + if isinstance(indexing, BlockPtrOptions): + # Store for later use. If the buffer is removed the below advancements + # are no longer necessary + self.block_ptr_to_buffer[block_descriptor] = name + + # Generate block pointer advancements, for later use. + # We record the entry for every level, even when the + # per-level offset is zero. The outer-loop suffix computes + # a rewind as `outer_step - inner_step * inner_num_iter`; + # if a pointer's outer entry is absent, no rewind is + # emitted and its SSA value (in scf.for-based backends + # such as Triton-MTIA) retains the accumulated inner + # advances across outer iterations, silently loading + # out-of-bounds. The emit site below drops pure no-op + # advances so this does not add codegen noise for + # pointers that are truly constant across all levels. + for symt in TritonSymbols.reduction_types: + advance_offsets = indexing.advance_roffset(symt) + + advancements = self.pointer_advancements[symt] + if block_descriptor in advancements: + raise AssertionError( + f"duplicate advancement for pointer '{block_descriptor}' at type '{symt}'" + ) + advancements[block_descriptor] = advance_offsets + else: + block_descriptor = indexing.format(var) + return block_descriptor, other + + def codegen_block_ptr_store_line(self, name, indexing, block_ptr, value, other=""): + # Stores require an explicit broadcast. We do this in two phases: + # 1. Broadcast the operand to the final shape of the range trees, e.g. [ZBLOCK, + # YBLOCK, XBLOCK]. This protects against implicit broadcasting from loads. + # 2. In case the block pointer / tma descriptor has different dimensionality, broadcast/reshape the + # result to the shape of the pointer. + value = f"tl.broadcast_to({value}, {indexing.final_shape})" + + # If the strides have a non-trivial sort, then the broadcasting dims + # need to be reverted for the store + # Also see indexing.codegen_broadcast_and_reshape + broadcast_shape = indexing.broadcast_shape + broadcasting_dims = indexing.broadcasting_dims + if not indexing.stride_sorter.is_identity: + broadcast_shape = indexing.stride_sorter.revert(broadcast_shape) + broadcasting_dims = indexing.stride_sorter.revert(broadcasting_dims) + + # These dims no longer need broadcasting. + for idx, (dim, broadcast_dim) in enumerate( + zip(indexing.final_shape, broadcast_shape) + ): + if V.graph.sizevars.statically_known_equals(dim, broadcast_dim): + broadcasting_dims[idx] = False + + if not indexing.stride_sorter.is_identity: + indexing.broadcasting_dims = indexing.stride_sorter.sort(broadcasting_dims) + else: + indexing.broadcasting_dims = broadcasting_dims + + value, _ = indexing.codegen_broadcast_and_reshape( + value, + indexing.final_shape, + indexing.block_shape, + allow_implicit=False, + for_store=True, + ) + + # workaround https://github.com/triton-lang/triton/issues/2814 + # For inplace-mutated buffers, the block pointer element type comes from + # the actual tensor (input buffer), which may differ from the graph dtype + # (e.g., _to_copy produces fp32 values stored into a bf16 gradient buffer). + store_dtype = V.graph.get_dtype(name) + if name in self.args.inplace_buffers: + buf = self.args.inplace_buffers[name] + if not isinstance(buf, RemovedArg): + store_dtype = V.graph.get_dtype(buf.other_names[0]) + value = f"{value}.to({triton_store_type(store_dtype)})" + if isinstance(indexing, BlockPtrOptions): + return f"tl.store({block_ptr}, {value}{other})" + return self.codegen_descriptor_store_line(block_ptr, indexing, value) + + def codegen_descriptor_load_line(self, block_descriptor, indexing): + """Generate the descriptor load line. Override for backend customization.""" + return f"{block_descriptor}.load({V.kernel.index_to_str(indexing.offsets)})" + + def codegen_descriptor_store_line(self, block_ptr, indexing, value): + """Generate the descriptor store line. Override for backend customization.""" + return f"{block_ptr}.store({V.kernel.index_to_str(indexing.offsets)}, {value})" + + def check_bounds( + self, + expr: sympy.Expr, + size: sympy.Expr, + lower: bool, + upper: bool, + ): + if not (lower or upper): + return + + if not isinstance(expr, sympy.Expr): + raise AssertionError(f"expected sympy.Expr, got {type(expr)}") + indexing = self.indexing(expr, block_ptr=False, tma_compatibility_checker=None) + if not isinstance(indexing, IndexingOptions): + raise AssertionError(f"expected IndexingOptions, got {type(indexing)}") + + index_str = indexing.index_str + mask_str = indexing.mask_str if indexing.has_mask() else None + size_str = texpr(self.rename_indexing(size)) if upper else None + + # expr is already wrapped + line = self.indirect_assert( + index_str, "0" if lower else None, size_str, mask_str + ) + + buffer = self.get_load_buffer(indexing) + self.cse.generate(buffer, line, assignment=False, dtype=torch.int32) + + def get_load_buffer(self, indexing): + if indexing.has_indirect() or indexing.has_tmpmask(): + # Masked loads must come after the mask is computed + return self.compute + elif ( + self.inside_reduction + and self.range_trees[-1].is_loop + and not indexing.has_rindex() + and not indexing.has_rmask() + ): + # Lift loads whose address and mask are available outside the loop. + return self.body + else: + return self.loads + + def _range_tree_mask_shape(self, mask: str) -> BlockShapeType: + for tree in self.active_range_trees(): + if tree.owns_mask(mask): + return tree.mask_shape(self.triton_tensor_ndim()) + return None + + def _mask_shape(self, mask: str | TritonCSEVariable) -> BlockShapeType: + if isinstance(mask, TritonCSEVariable): + return mask.shape + return self._range_tree_mask_shape(mask) + + def _broadcast_shape_with_masks( + self, + shape: BlockShapeType, + mask_vars: OrderedSet[str | TritonCSEVariable], + ) -> BlockShapeType: + if shape is None: + return None + + result_shape = tuple(shape) + for mask in mask_vars: + mask_shape = self._mask_shape(mask) + if mask_shape is None: + return None + result_shape = get_broadcasted_shape(result_shape, tuple(mask_shape)) + + return result_shape + + GDC_WAIT = "tl.extra.cuda.gdc_wait()" + GDC_LAUNCH = "tl.extra.cuda.gdc_launch_dependents()" + + @staticmethod + def _enable_pdl_codegen(): + if not torch._inductor.config.triton.enable_pdl: + return False + if isinstance(V.kernel, torch._inductor.select_algorithm.TritonTemplateKernel): + return False + # PDL uses CUDA-specific intrinsics (gdc_wait/gdc_launch), not available on ROCm + if torch.version.hip: + return False + return ( + V.graph.get_current_device_or_throw().type == "cuda" + and torch.cuda.get_device_capability()[0] >= 9 + ) + + def _handle_pdl_before_access( + self, wait_buffer, *dependencies, consider_reads=False + ): + if not self._enable_pdl_codegen(): + return + current_node = V.kernel.current_node + prev_node = ( + V.graph.scheduler.previous_node if V.graph.scheduler is not None else None + ) + + def matching_dep(dep): + if prev_node is None: + raise AssertionError("prev_node must not be None") + if current_node is None: + raise AssertionError("current_node must not be None") + prev_deps = prev_node.read_writes.writes + if consider_reads: + prev_deps = itertools.chain(prev_deps, prev_node.read_writes.reads) + return any( + dep == current_node.mutation_renames.get(w.name, w.name) + for w in prev_deps + ) + + if not dependencies: + raise AssertionError("dependencies must not be empty") + need_wait = prev_node is None or any(matching_dep(d) for d in dependencies) + if not need_wait: + return + # hoist before the loop + if self.inside_reduction and self.range_trees[-1].is_loop: + wait_buffer = self.body + + wait_buffer.writeline(self.GDC_WAIT) + + def _handle_pdl_after_load(self, launch_buffer, result_var): + if not self._enable_pdl_codegen(): + return + if result_var.use_count > 1: # we already went through this + return + # hoist after the loop + if self.inside_reduction and self.range_trees[-1].is_loop: + launch_buffer = self.post_loop_combine + + # the issue is that we need to (a) make sure this happens + # but (b) do not know if this is last yet + # so we need to remember this (has_wait), which tells use + # whether we would have needed it, and check if we are last + launch_buffer.writeline(self.GDC_WAIT) + launch_buffer.writeline(self.GDC_LAUNCH) + + def _filter_pdl(self, code: IndentedBuffer): + new_lines = [] + has_wait = False + previous_launch = None + for l in code._lines: + if type(l) is str and self.GDC_WAIT in l: + if has_wait: + continue + else: + has_wait = True + if type(l) is str and self.GDC_LAUNCH in l: + if previous_launch is not None: + new_lines.pop(previous_launch) + previous_launch = len(new_lines) + new_lines.append(l) + code._lines = new_lines + + def _load_index_split_basis( + self, index: sympy.Expr, tree: IterationRangesRoot + ) -> LoadIndexBasis | None: + """Find split digits that reconstruct a range tree's flat index. + + Each entry is one digit in a mixed-radix index. A complete basis has at + least two non-unit digits, starts at divisor 1, and forms a contiguous + divisor chain whose total extent equals the root's numel. + + Symbolic lengths are supported when size analysis can prove those + identities without guards; otherwise this conservatively returns None. + """ + sizevars = V.graph.sizevars + remaining: list[IterationRangesEntry] = [] + for symbol in index.free_symbols: + entry = self.range_tree_nodes.get(symbol) + if ( + entry is not None + and entry.root is tree + and not sizevars.statically_known_equals(entry.length, sympy.S.One) + ): + remaining.append(entry) + if len(remaining) <= 1: + return None + + basis: list[IterationRangesEntry] = [] + divisor = sympy.S.One + # Divisors may be symbolic, so follow the mixed-radix chain with + # guarded equality instead of sorting them. + while remaining: + for i, entry in enumerate(remaining): + if sizevars.statically_known_equals(entry.divisor, divisor): + basis.append(entry) + divisor *= entry.length + remaining.pop(i) + break + else: + return None + if not sizevars.statically_known_equals(divisor, tree.numel): + return None + return tuple(basis) + + def _supports_load_index_basis_reuse(self) -> bool: + """Whether this kernel uses a supported shared coordinate scope.""" + return ( + self.__class__ is TritonKernel + and self.features.is_reduction() + and not self.cooperative_reduction + and not any( + isinstance(tree, DerivedIterationRangesRoot) + for tree in self.range_trees + ) + ) + + def _resolve_load_index_bases(self, state: LoadIndexState) -> LoadIndexBases: + """Return cached bases or derive them from the prior live load.""" + if isinstance(state, _ResolvedLoadIndexState): + return state.bases + # A distinct prior load is still in the CSE scope. Discover which + # range trees it addressed with complete split coordinates. + return tuple( + self._load_index_split_basis(state.index, tree) for tree in self.range_trees + ) + + def _rewrite_full_range_with_basis( + self, + index: sympy.Expr, + tree: IterationRangesRoot, + basis: LoadIndexBasis, + ) -> sympy.Expr: + """Replace a tree's flat symbol with its exact split-coordinate sum.""" + split_index = sum( + (entry.symbol() * entry.divisor for entry in basis), sympy.S.Zero + ) + basis_symbols = OrderedSet([entry.symbol() for entry in basis]) + replacements: dict[sympy.Symbol, sympy.Expr] = {} + sizevars = V.graph.sizevars + for symbol in index.free_symbols - basis_symbols: + entry = self.range_tree_nodes.get(symbol) + # Leave alternate splits alone; only the unsplit full range has + # the direct coordinate identity represented by split_index. + if entry is None or entry.root is not tree: + continue + is_full_range = sizevars.statically_known_equals( + entry.divisor, sympy.S.One + ) and sizevars.statically_known_equals(entry.length, tree.numel) + if is_full_range: + replacements[symbol] = split_index + return sympy_subs(index, replacements) if replacements else index + + def _reuse_load_index_basis(self, name: str, index: sympy.Expr) -> sympy.Expr: + """Rewrite a full-range load coordinate to an observed split basis. + + Reduction bodies can use split coordinates while later pointwise work + uses one flattened coordinate for the same range root. Looped reductions + may reuse a basis within their body; closing the loop invalidates CSE and + clears the basis before codegen enters a different scope. + + TritonKernel subclasses and derived iteration families may use separate + codegen scopes. Cooperative reductions also use an untested partitioned + execution model. Only the base, non-cooperative kernel with base range + trees is accepted here. + """ + if not self._supports_load_index_basis_reuse(): + return index + + cse = cast(TritonCSE, self.cse) + # Use the exact buffer/mask scope already defined by TritonCSE. + cache_key = cse.augment_key(name) + state = cse._load_index_states.get(cache_key) + if state is None: + # Defer range-tree analysis until another live load from this CSE + # scope uses the same buffer with a different index. + cse._load_index_states[cache_key] = _UnresolvedLoadIndexState(index, index) + return index + if state.index == index: + return state.result + + bases = self._resolve_load_index_bases(state) + result = index + for tree, basis in zip(self.range_trees, bases, strict=True): + if basis is not None: + result = self._rewrite_full_range_with_basis(result, tree, basis) + if result != index: + result = V.graph.sizevars.simplify_with_ranges(result, self.var_ranges()) + cse._load_index_states[cache_key] = _ResolvedLoadIndexState( + index, result, bases + ) + return result + + def partial_accumulate( + self, name: str, reduction_type, val, extra_meta: dict[str, Any] + ): + self.saved_partial_accumulate.append( + PartialAccumulate(name, reduction_type, val) + ) + + def load(self, name: str, index: sympy.Expr): + """ + Load from the memory location 'name', offset by some indexing expression 'index'. + """ + var = self.args.input(name) + load_counts = self._load_counts + load_counts[name] += 1 + make_line: Callable[[str], str | DelayReplaceLine] = identity + # Align a flat epilogue load with split coordinates already used in the body. + index = self._reuse_load_index_basis(name, index) + indirect_indexing = self.is_indirect_indexing(index) + original_index = index + dtype = V.graph.get_dtype(name) + uses_uint8_storage = use_uint8_triton_storage_for_cuda_float8_e4m3fn(dtype, var) + + if config.triton.enable_host_side_tma: + if self._host_tma_non_materializable_buffers is None: + self._prescan_host_tma_materializability() + if name in (self._host_tma_non_materializable_buffers or ()): + self._host_tma_non_materializable.add(var) + + skip_tma = config.triton.enable_host_side_tma and self._check_buffer_alignment( + name, var, dtype + ) + tma_checker = ( + None + if skip_tma + else self.tma_compatibility_checker_cls( + self, + dtype, + for_store=False, + force=getattr(self, "tma_load_for_template_epilogue", False), + buffer_name=name, + ) + ) + indexing = self.indexing( + index, + block_ptr=True, + tma_compatibility_checker=tma_checker, + ) + + if isinstance(indexing, IndexingOptions) and self._has_stride1_on_rdim( + indexing.index + ): + self.has_load_with_contiguous_rdim = True + + has_rindex = indexing.has_rindex() + has_tmpmask = indexing.has_tmpmask() + + # Keep the variable in cache if were going to reuse it. Equiv., if any of the following hold + # 1) We are doing broadcasting + # 2) It is a non-coalesced load. The intuition is that if it's + # non-coalesced, we will likely load each element multiple times in + # practice. + # 3) The buffer will be loaded later and it won't be CSE'd. Equiv., + # if all the following hold + # 3.1) We are in a looped or persistent reduction + # 3.2) Its not its last load + # 3.3) This load will not be lifted to the body + # + is_coalesced = any( + i == 1 for i in self.get_strides_of_load(original_index).values() + ) + if self.is_broadcasted(original_index): + ep = ", eviction_policy='evict_last'" + elif not is_coalesced: + ep = ", eviction_policy='evict_last'" + elif self.inside_reduction and ( + self.persistent_reduction or self.range_trees[-1].is_loop + ): + + def decide_later(): + if load_counts[name] > expected_count and ( + has_rindex or indirect_indexing + ): + return "evict_last" + return "evict_first" + + expected_count = load_counts[name] + ep = ", eviction_policy=''" + make_line = functools.partial(DelayReplaceLine, "", decide_later) + else: + ep = "" + + if (has_tmpmask or has_rindex) and indexing.has_mask(): + if self._load_other: + other = f", other={constant_repr(self._load_other)}" + elif uses_uint8_storage: + other = ", other=0" + else: + other = ", other=0.0" + else: + other = "" + + """Check if the buffer we're about to load, has + more than one read dependency + NOTE: enabled with env variable TORCHINDUCTOR_SKIP_L1 + """ + has_read_deps = True + if config.triton.skip_l1_cache: + buffer_read_counts = self.features.buffer_read_counts() + # Graph inputs, primals_*, arg*_* would not be tracked by `buffer_read_counts` + # and it'd be fair to expect them to be reused. + if name in buffer_read_counts: + has_read_deps = buffer_read_counts[name] > 1 + """Skip L1 cache if we're (pretty?) sure the data is used only once + """ + skip_l1_cache = ( + not self.is_broadcasted(original_index) + and not self.inside_reduction + and not has_read_deps + and is_coalesced # for indirect loads is_coalesced is False? + ) + cachemod = "" + if skip_l1_cache: + cachemod = ", cache_modifier='.cg'" + + append_broadcast = None + shape: BlockShapeType = None + + if should_unwrap_unspec_arg(name): + line = var + # unwrapped bf16/fp16 0d tensors are passed in as float32 scalars + # see triton_utils.py:signature_of + if dtype in (torch.float16, torch.bfloat16): + if config.triton.codegen_upcast_to_fp32: + dtype = torch.float32 + else: + line += f".to({triton_type(dtype)})" + shape = () + + else: + if isinstance(indexing, (BlockPtrOptions, TensorDescriptorOptions)): + block_descriptor, other = self.codegen_block_ptr( + name, var, indexing, other + ) + if isinstance(indexing, BlockPtrOptions): + line = f"tl.load({block_descriptor}{other}{ep}{cachemod})" + else: + line = self.codegen_descriptor_load_line(block_descriptor, indexing) + line, shape = indexing.codegen_broadcast_and_reshape( + line, + indexing.block_shape, + indexing.final_shape, + allow_implicit=True, + for_store=False, + ) + elif is_sympy_integer_like(original_index): + self._host_tma_non_materializable.add(var) + self.host_tma_descriptor_args.pop(var, None) + line = f"tl.load({var} + ({original_index}))" + append_broadcast = indexing.expand_str + shape = () + else: + self._host_tma_non_materializable.add(var) + self.host_tma_descriptor_args.pop(var, None) + line = f"tl.load({var} + ({indexing.index_str}), {indexing.mask_str}{ep}{other}{cachemod})" + + # The block shape of tl.load depends on the indexing expression. + # Inferring shape solely from the mask may miss cases where the mask is constant. + # Inferring from indexing.expand_shape alone may also fail when dense indexing is absent. + # so, iterate over variables in the indexexpr to accurately infer the block shape. + if indexing.expand_shape: + shape = indexing.expand_shape + else: + shape = TritonSymbols.get_block_shape(indexing.index) + + if ( + dtype in (torch.float16, torch.bfloat16) + and config.triton.codegen_upcast_to_fp32 + ): + line += ".to(tl.float32)" + dtype = torch.float32 + if dtype == torch.bool and torch.version.hip is None: + # Workaround for https://github.com/triton-lang/triton/issues/2151 + # tl.load returns int8 when loading from pointer to int1 + # NOTE: Currently causes hangs on bool UTs for ROCm + line += ".to(tl.int1)" + dtype = torch.bool + + load_buffer = self.get_load_buffer(indexing) + # Read-after-write companion to the #1615 guard in store(). If we read + # back a buffer we stored in a reduction loop, coalescing can put the + # store and load on different warps, so a warp may read before another + # warp's write is visible. Barrier first to make the writes visible. + if ( + name in self.cse.invalidated_stores + and V.graph.get_current_device_or_throw().type != "cpu" + ): + load_buffer.writeline(DeferredLine(name, "tl.debug_barrier()")) + self._handle_pdl_before_access(load_buffer, name) + result_var = self.cse.generate( + load_buffer, make_line(line), dtype=dtype, shape=shape + ) + self._handle_pdl_after_load(load_buffer, result_var) + if result_var.use_count > 1: + load_counts[name] -= 1 # don't double count cache hit + if not isinstance(result_var, TritonCSEVariable): + raise AssertionError(f"expected TritonCSEVariable, got {type(result_var)}") + result_var.mask_vars = indexing.mask_vars # type: ignore[assignment] + + if append_broadcast: + bcast_operand = result_var + if dtype == torch.bool and str(result_var) in ("True", "False"): + bcast_operand = ( + f"tl.full([1], {1 if str(result_var) == 'True' else 0}, tl.int1)" + ) + line = f"tl.broadcast_to({bcast_operand}, {append_broadcast})" + result_var = self.cse.generate( + load_buffer, line, dtype=dtype, shape=indexing.expand_shape + ) + if indexing.mask_vars: + if dtype.is_floating_point: + zero = "0.0" + elif dtype == torch.bool: + zero = "True" + else: + zero = "0" + other_val = ( + constant_repr(self._load_other) if self._load_other else zero + ) + line = f"tl.where({indexing.mask_str}, {result_var}, {other_val})" + result_var = self.cse.generate( + load_buffer, + line, + dtype=dtype, + shape=self._broadcast_shape_with_masks( + result_var.shape, indexing.mask_vars + ), + ) + + # Only CSE values emitted outside the loop remain valid after it closes. + if not self.inside_reduction or load_buffer is self.body: + self.outside_loop_vars.add(result_var) + + return result_var + + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> None: + """ + store the 'value' to the memory location 'name', offset by some indexing expression 'index'. + """ + + var = self.args.output(name) + original_index = index + dtype = V.graph.get_dtype(name) + + buffer_misaligned = self._check_buffer_alignment(name, var, dtype) + + tma_compatibility_checker = None + if not buffer_misaligned and (mode is None or mode == "tma"): + force = mode == "tma" or getattr(self, "tma_store", False) + tma_compatibility_checker = self.tma_compatibility_checker_cls( + self, + dtype, + for_store=True, + force=force, + buffer_name=name, + ) + indexing = self.indexing( + index, + dense_indexing=True, + block_ptr=mode is None, + tma_compatibility_checker=tma_compatibility_checker, + mask_constant_index=mode == "atomic_add", + ) + + if isinstance(indexing, IndexingOptions) and self._has_stride1_on_rdim( + indexing.index + ): + self.stores_with_contiguous_rdim.append(name) + + # Guard against write-after-read corruption in triton. + # See # https://github.com/triton-lang/triton/issues/1615 + # This triton bug means that a load which is broadcasted over multiple + # warps may see the result of a store that happens later in the triton + # program. The workaround is to add a barrier before storing, which + # enforces that all warps have already read the data. + is_inplace = name in self.args.inplace_buffers + is_broadcasted = self.is_broadcasted(original_index) + if is_inplace and is_broadcasted: + self.stores.writeline(DeferredLine(name, "tl.debug_barrier()")) + + if isinstance(indexing, (BlockPtrOptions, TensorDescriptorOptions)): + block_descriptor, other = self.codegen_block_ptr(name, var, indexing) + # block_ptr / tma descriptor stores don't do implicit casting + line = self.codegen_block_ptr_store_line( + name, indexing, block_descriptor, value, other + ) + elif mode is None: + # If indexing is an integer and value has block shape larger than one, + # broadcasting fails. So, we manually broadcast indexing to the value shape. + # Without broadcast : + # tl.store(out_ptr0 + (tl.full([1, 1], 0, tl.int32)), tmp4, xmask) # Fail + # + # With broadcast: + # tl.store(out_ptr0 + (tl.full([1, 1], 0, tl.int32).broadcast_to((XBLOCK,1)), tmp4, xmask) + indexing_str = indexing.index_str + if is_sympy_integer_like(index): + if self.is_combo_kernel: + # In combo kernels, broadcast pointer to match mask shape + indexing_str += f".broadcast_to({self.dense_size_str()})" + elif value.shape is not None and not all( + str(x) == "1" for x in value.shape + ): + value_shape = ", ".join(map(str, value.shape)) + indexing_str += f".broadcast_to({value_shape})" + self._host_tma_non_materializable.add(var) + self.host_tma_descriptor_args.pop(var, None) + line = f"tl.store({var} + ({indexing_str}), {value}, {indexing.mask_str})" + elif mode == "atomic_add": + self.atomic_add_found = True + indexing_str = indexing.index_str + if ( + is_sympy_integer_like(index) + and value.shape is not None + and not all(str(x) == "1" for x in value.shape) + ): + value_shape = ", ".join(map(str, value.shape)) + indexing_str += f".broadcast_to({value_shape})" + line = f"tl.atomic_add({var} + ({indexing_str}), {value}, {indexing.mask_str}, sem='relaxed')" + else: + raise NotImplementedError(f"store mode={mode}") + + exit_stack = contextlib.ExitStack() + if not self.inside_reduction and self.cooperative_reduction: + exit_stack.enter_context(self.guard_cooperative_store(name, self.stores)) + + self._handle_pdl_before_access(self.stores, name, consider_reads=True) + self.stores.writeline(DeferredLine(name, line)) + + if not self.inside_reduction: + self.outside_loop_vars.add(value) + + exit_stack.close() + + def device_assert_async(self, cond, msg) -> None: + self.compute.writeline(f"tl.device_assert({cond}, {repr(msg)})") + + def guard_cooperative_store(self, name, buffer): + """ + For cooperative reductions only one thread block should write out the result. + We rotate which thread block does each write for better parallelism + """ + idx = self.cooperative_reduction_workspace_cache.increment_store_count() + buffer.writeline(DeferredLine(name, f"if rsplit_id == ({idx} % RSPLIT):")) + return buffer.indent() + + def _combine_masks(self, *variables: CSEVariable | None): + masks = None + for elem in variables: + if elem is None: + continue + if hasattr(elem, "mask_vars"): + if masks is None: + masks = elem.mask_vars + else: + masks = masks | elem.mask_vars + return masks + + def bucketize( + self, + values: CSEVariable, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: CSEVariable, + indexing_dtype: torch.dtype, + right: bool, + sorter: tuple[str, sympy.Expr] | None = None, + sorter_indices: CSEVariable | None = None, + ) -> CSEVariable: + """ + See [Note: Inductor bucketize op] + """ + + # Triton performance for bucketize_binary_search is much better when the number + # of threads equals the number of elements. + # If we're trying to use a bucketize kernel, we should make sure that an + # autotuning config with num_elements_per_warp=(warp_size) exists. + self.autotune_hints.add(AutotuneHint.ONE_ELEMENT_PER_THREAD) + + boundaries_ptr = self.args.input(boundaries[0]) + boundary_size = self.index_to_str(boundaries[1]) + boundaries_underlying_numel = self.index_to_str(boundaries[2]) + boundary_stride = self.index_to_str(boundaries[3]) + sorter_ptr = self.args.input(sorter[0]) if sorter else "None" + sorter_stride = self.index_to_str(sorter[1]) if sorter else "None" + + if indexing_dtype == torch.int32: + triton_dtype = "tl.int32" + elif indexing_dtype == torch.int64: + triton_dtype = "tl.int64" + else: + raise NotImplementedError( + "Bucketize only supports indexing with int32 and int64" + ) + + self._handle_pdl_before_access( + self.compute, boundaries[0], *([sorter[0]] if sorter else []) + ) + result = self.cse.generate( + self.compute, + f"triton_helpers.bucketize_binary_search({values}, " + f"{boundaries_ptr}, {boundary_size}, {boundaries_underlying_numel}, {boundary_stride}, " + f"{boundary_indices}, " + f"{triton_dtype}, " + f"{right}, " + f"{sorter_ptr}, {sorter_stride}, " + f"{sorter_indices}, " + ")", + dtype=indexing_dtype, # type: ignore[attr-defined] + shape=values.shape, + ) + self._handle_pdl_after_load(self.compute, result) + + masks = self._combine_masks(values, boundary_indices, sorter_indices) + result.mask_vars = masks # type: ignore[attr-defined] + + return result + + def reduction_resize(self, value) -> str: + ndims = self.triton_tensor_ndim() + if ndims == 1: + return f"triton_helpers.promote_to_tensor({value})" + + nreduce = self.num_reduction_dims + sizes = [":"] * (ndims - nreduce) + ["None"] * nreduce + return f"{value}[{', '.join(sizes)}]" + + def reduction_resize_and_shape(self, value, shape) -> tuple[str, BlockShapeType]: + ndims = self.triton_tensor_ndim() + if ndims == 1: + return f"triton_helpers.promote_to_tensor({value})", shape + + nreduce = self.num_reduction_dims + sizes = [":"] * (ndims - nreduce) + ["None"] * nreduce + new_shape = ( + (*shape[: (ndims - nreduce)], *[1] * nreduce) if shape is not None else None + ) + return f"{value}[{', '.join(sizes)}]", new_shape + + def reduction_collapse_dims( + self, buffer, value: CSEVariable, dtype: torch.dtype + ) -> CSEVariable: + """ + Reshape to RBLOCK, collapsing all reduction dims. + """ + # This is not needed for 1D reductions. + if self.num_reduction_dims == 1: + return value + + target_ndim = self.triton_tensor_ndim() - self.num_reduction_dims + initial_shape = self.dense_size_list() + target_shape = initial_shape[:target_ndim] + ["RBLOCK"] + return self.cse.generate( + buffer, + triton_reshape(str(value), initial_shape, target_shape), + dtype=dtype, + shape=tuple(target_shape), + ) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: + """ + codegen reduction of value to Triton according the reduction_type + """ + + def should_upcast(d: torch.dtype | None) -> bool: + return d is not None and d.is_floating_point and d.itemsize < 4 + + def maybe_upcast(value: CSEVariable) -> CSEVariable: + # Math reductions in small floats are less accurate because the Triton + # compiler does not automatically promote to FP32 for accumulation. + # Additionally, max/min reductions do not support FP16/BF16. Manually + # promote to FP32 here. + return ( + ops.to_dtype(value, torch.float32) + if should_upcast(value.dtype) + else value + ) + + do_upcast = pytree.tree_any(lambda v: should_upcast(v.dtype), value) + original_dtype = dtype + original_src_dtype = src_dtype + if do_upcast: + # Only promote FB16/BF16; do not promote other integer/boolean dtypes + value = pytree.tree_map(maybe_upcast, value) + src_dtype = torch.float32 if should_upcast(src_dtype) else src_dtype + dtype = torch.float32 if should_upcast(dtype) else dtype + + if not self.inside_reduction: + raise AssertionError("expected inside_reduction") + masks = OrderedSet(tree.mask_name() for tree in self.range_trees) + self.filter_masks(masks) + masks = sorted(masks) + if self._load_mask: + masks.append(self._load_mask) + reduction_range_prefix = self.range_trees[-1].prefix[0] + + # Eager tree-reduces each tile before accumulating tiles linearly. + strict_sum = self._strict_sum_rblock() is not None and reduction_type == "sum" + strict_sum_loop = strict_sum and not self.persistent_reduction + + # When we do native matmtul codegen, + # we don't want to keep the R0_BLOCK/R1_BLOCK in the accumulator. + # so instead of naively calling dense_size_str(), we filter out + # reduction block from accumulator and only keep (Y,X). + # In bmm (Z,Y,R)x(Z,R,X) case, we also remove z dimension from accumulator + # because 3d (Z,Y,X) tl.dot is somehow slower than 2d tl.dot. + # Instead, we force ZBLOCK to be always 1 during autotune. + dense_size_str: str + if self.is_native_matmul: + dense_sizes = self.dense_size_list() + if len(dense_sizes) < 3: + raise AssertionError( + f"expected at least 3 dense sizes, got {len(dense_sizes)}" + ) + xy_sizes_only = [size for size in dense_sizes if "X" in size or "Y" in size] + dense_size_str = f"[{', '.join(xy_sizes_only)}]" + value_shape = tuple(xy_sizes_only) + else: + dense_size_str = self.dense_size_str() + value_shape = tuple(self.dense_size_list()) + + # Say we have + # tmp0 = ops.constant(1, torch.int64) + # tmp1 = ops.reduction(torch.int64, torch.int64, "sum", tmp0) + # tmp0 in the triton code is either a scalar, or single-element tensor + # so if we emit tl.sum directly, it will only give 1 instead of RBLOCK * 1 + # To avoid this, we broadcast to the expected shape first. + value = self._map_tuple_or_scalar( + lambda v: self.cse.generate( + self.compute, + f"tl.broadcast_to({v}, {dense_size_str})", + dtype=v.dtype, + shape=value_shape, + ), + value, + ) + + arg_index_reduction_types = ("argmax", "argmin") + arg_value_reduction_types = ("argmax_value", "argmin_value") + arg_with_value_reduction_types = ("argmax_with_value", "argmin_with_value") + arg_reduction_types = ( + arg_index_reduction_types + + arg_value_reduction_types + + arg_with_value_reduction_types + ) + arg_root_ops = { + "argmax": "max", + "argmin": "min", + "argmax_value": "max", + "argmin_value": "min", + "argmax_with_value": "max", + "argmin_with_value": "min", + } + + logical_index = None + if reduction_type in arg_reduction_types: + if isinstance(value, tuple): + value, logical_index = value + + dim = self.triton_tensor_ndim() - self.num_reduction_dims + root_op: str + + def final_reduction( + buffer, + value: CSEVariable, + result_type: torch.dtype | None, + ) -> tuple[str, torch.dtype | None, BlockShapeType]: + """ + Helper to generate a reduction call, e.g. tl.sum. + """ + triton_reduction_fn = get_triton_reduction_function(reduction_type) + + value = self.reduction_collapse_dims(buffer, value, dtype) + if reduction_type == "dot": + # Native matmul is a special case because accumulator shape is fixed to (Y,X) + is_bmm = len(self.dense_size_list()) == 4 + if value.shape is None: + raise AssertionError("value.shape must not be None") + if is_bmm: + result = f"{value}[None,:,:,None]" # (Y,X) to (Z=1,Y,X,R=1) + shape = [1, *value.shape, 1] + else: + result = f"{value}[:,:,None]" # (Y,X) to (Y,X,R=1) + shape = [*value.shape, 1] + else: + reduction_ordering = ( + ", reduction_ordering=tl.constexpr(tl.ReductionOrdering.INNER_TREE)" + if strict_sum + else "" + ) + result, shape = self.reduction_resize_and_shape( # type: ignore[assignment] + f"{triton_reduction_fn}({value}, {dim}{reduction_ordering})", + value.shape, + ) + + if result_type is not None: + result = f"{result}.to({self.dtype_to_str(result_type)})" + else: + result_type = value.dtype + + return result, result_type, shape + + def final_reduction_define( + buffer, + result_var: CSEVariable, + value: CSEVariable, + result_type: torch.dtype | None, + ) -> None: + """ + Generate a reduction and assign it to an existing variable. + """ + # pyrefly: ignore [bad-assignment] + value, _, _ = final_reduction(buffer, value, result_type) + buffer.splice(f"{result_var} = {value}") + + def final_argreduce(buffer, result_var, value, index, result_kind="index"): + value = self.reduction_collapse_dims(buffer, value, value.dtype) + index = self.reduction_collapse_dims( + buffer, + index, + cast(torch.dtype, index.dtype) + if isinstance(index, CSEVariable) + else V.kernel.get_index_dtype_as_torch_dtype(), + ) + if result_kind == "value_and_index": + result_value, result_index = result_var + buffer.splice( + f"""\ + {result_value}, {result_index} = triton_helpers.{root_op}_with_index({value}, {index}, {dim}) + {result_value} = {self.reduction_resize(f"{result_value}")} + {result_index} = {self.reduction_resize(f"{result_index}")} + """ + ) + elif result_kind == "value": + buffer.splice( + f"""\ + {result_var}_val, {result_var}_idx = triton_helpers.{root_op}_with_index({value}, {index}, {dim}) + {result_var} = {self.reduction_resize(f"{result_var}_val")} + """ + ) + else: + buffer.splice( + f"""\ + {result_var}_val, {result_var}_idx = triton_helpers.{root_op}_with_index({value}, {index}, {dim}) + {result_var} = {self.reduction_resize(f"{result_var}_idx")} + """ + ) + + def argreduce_result_kind(): + if reduction_type in arg_with_value_reduction_types: + return "value_and_index" + if reduction_type in arg_value_reduction_types: + return "value" + return "index" + + cache_key = (src_dtype, reduction_type, value) + if cache_key in self.cse.reduction_cache: + return self.cse.reduction_cache[cache_key] + + acc_type = triton_acc_type(src_dtype) + torch_acc_type = upcast_acc_dtype(src_dtype) + index_dtype = ( + self.features.select_index_dtype() + if reduction_type in arg_reduction_types + else None + ) + result_shape = list(self.dense_size_list()) + for i in range(dim, dim + self.num_reduction_dims): + result_shape[i] = "1" + result_mask_vars = OrderedSet( + var for var in masks if not prefix_is_reduction(var[0]) + ) + result_var: Any + if reduction_type in arg_with_value_reduction_types: + if index_dtype is None: + raise AssertionError("index_dtype must be set for arg reductions") + result_var = ( + self.cse.newvar(dtype=torch_acc_type, shape=tuple(result_shape)), + self.cse.newvar(dtype=index_dtype, shape=tuple(result_shape)), + ) + for var in result_var: + var.mask_vars = result_mask_vars + elif reduction_type in arg_index_reduction_types: + if index_dtype is None: + raise AssertionError("index_dtype must be set for arg reductions") + result_var = self.cse.newvar(dtype=index_dtype, shape=tuple(result_shape)) + result_var.mask_vars = result_mask_vars + else: + result_var = self.cse.newvar( + dtype=torch_acc_type, shape=tuple(result_shape) + ) + result_var.mask_vars = result_mask_vars + cond = " & ".join(masks) + + def where_cond(tval, fval): + if not cond: + return tval + return TritonKernelOverrides.where(cond, tval, fval) + + if self.persistent_reduction: + default = ir.Reduction.default_value(reduction_type, src_dtype) + + def update_constant_dtype(constant, src_dtype, dst_dtype): + "update reduction constant mask value to match dst_dtype" + + # int is the only mask which may not fit within lower bitwidth, + # because float uses inf/-inf + if src_dtype.is_floating_point or src_dtype == torch.bool: + return constant + + if src_dtype == dst_dtype or constant == 0: + return constant + + if constant == torch.iinfo(src_dtype).max: + return torch.iinfo(dst_dtype).max + elif constant == torch.iinfo(src_dtype).min: + return torch.iinfo(dst_dtype).min + else: + return constant + + def _mask_value(value, default) -> CSEVariable: + default = update_constant_dtype(default, src_dtype, value.dtype) + default_str = self._map_tuple_or_scalar(constant_repr, default) + + return self.cse.generate( + self.compute, + where_cond(value, default_str), + dtype=value.dtype, + shape=value.shape, + ) + + masked_value: CSEVariable | Sequence[CSEVariable] | None + if reduction_type == "online_softmax_reduce" and not isinstance( + value, tuple + ): + # Don't generate mask value for online_softmax since we + # will fallback below + masked_value = None + elif isinstance(value, tuple): + masked_value = [_mask_value(v, d) for v, d in zip(value, default)] # type: ignore[arg-type] + elif reduction_type == "dot": + # Here, we don't perform the masking. + # Masking w/ where condition in native matmul is handled in ops.dot codegen. + # Since tl.dot performs reduction within the triton block, + # masking should happen before the tl.dot is called. + masked_value = self.cse.generate(self.compute, value, dtype=value.dtype) + else: + masked_value = _mask_value(value, default) + + if reduction_type in arg_reduction_types: + if not isinstance(masked_value, CSEVariable): + raise AssertionError( + f"expected CSEVariable, got {type(masked_value)}" + ) + if index_dtype is None: + raise AssertionError("expected index_dtype to be set") + if logical_index: + accumulator_index = ( + f"({str(logical_index)}).to({self.dtype_to_str(index_dtype)})" + ) + else: + accumulator_index = str( + self.cse.generate( + self.compute, + f"tl.broadcast_to({reduction_range_prefix}index, {masked_value}.shape)", + dtype=index_dtype, + shape=masked_value.shape, + ) + ) + root_op = arg_root_ops[reduction_type] + final_argreduce( + self.compute, + result_var, + masked_value, + accumulator_index, + argreduce_result_kind(), + ) + elif reduction_type == "welford_reduce": + if self.cooperative_reduction: + # cooperative reductions require full welford for correctness + result_var = self.welford_reduce( + result_var, reduction_type, value, where_cond, acc_type, dtype + ) + else: + # For persistent reductions, don't bother with + # welford's algorithm since it uses more registers, and + # taking two reductions doesn't increase memory usage. + result_var = self.welford_reduce_fallback(dtype, value) + elif reduction_type == "welford_combine": + if not isinstance(masked_value, Sequence): + raise AssertionError(f"expected Sequence, got {type(masked_value)}") + (mean, m2, weight) = masked_value + result_var = tuple( + self.cse.generate(self.compute, value, dtype=dtype, shape=shape) + for value, shape in self._welford( + self.compute, mean, m2, weight, dim, dtype + ) + ) + elif reduction_type == "online_softmax_reduce": + if isinstance(value, tuple): + if not isinstance(masked_value, Sequence): + raise AssertionError( + f"expected masked_value to be a Sequence, got " + f"{type(masked_value)}" + ) + result_sum = self.cse.newvar( + dtype=dtype, shape=cast(CSEVariable, result_var).shape + ) + result_var = self.online_softmax_reduce_final_reduction( + self.compute, + result_var, + result_sum, + masked_value[0], + masked_value[1], + dim, + dtype, + ) + else: + # All data is loaded to register anyway, no need to do + # online softmax + result_var = self.prepare_softmax_twopass_fallback(dtype, value) + else: + if not isinstance(masked_value, CSEVariable): + raise AssertionError( + f"expected CSEVariable, got {type(masked_value)}" + ) + _result, _dtype, _shape = final_reduction( + self.compute, masked_value, masked_value.dtype + ) + if strict_sum and not self.features.has_strict_sum_multirow_reduction(): + zero = constant_repr(cast(Any, default)) + _result = f"{zero} + ({_result})" + result_var = self.cse.generate( + self.compute, _result, dtype=_dtype, shape=_shape + ) + else: + result_prefix = ( + cast(Any, result_var)[0] + if reduction_type in arg_with_value_reduction_types + else result_var + ) + accumulator = self.cse.namedvar( + f"_{result_prefix}", + dtype=torch_acc_type, + shape=tuple(self.dense_size_list()), + ) + default = ir.Reduction.default_accumulator(reduction_type, src_dtype) + default = self._map_tuple_or_scalar(constant_repr, default) + if not isinstance(default, tuple): + if reduction_type == "dot": + dense_sizes = self.dense_size_list() + if len(dense_sizes) < 3: + raise AssertionError( + f"expected at least 3 dense sizes, got {len(dense_sizes)}" + ) + xy_sizes_only = [ + size for size in dense_sizes if "X" in size or "Y" in size + ] + accumulator.shape = tuple(xy_sizes_only) + dense_size_str = f"[{', '.join(xy_sizes_only)}]" + self.body.writeline( + f"{accumulator} = tl.full({dense_size_str}, {default}, {acc_type})" + ) + elif strict_sum_loop: + accumulator.shape = tuple(result_shape) + result_size_str = f"[{', '.join(result_shape)}]" + self.body.writeline( + f"{accumulator} = tl.full({result_size_str}, {default}, {acc_type})" + ) + else: + self.body.writeline( + f"{accumulator} = tl.full({self.dense_size_str()}, {default}, {acc_type})" + ) + + if reduction_type in arg_reduction_types: + accumulator_index = f"_{result_prefix}_index" + if index_dtype is None: + raise AssertionError("index_dtype must be set for arg reductions") + self.body.writeline( + f"{accumulator_index} = tl.full({self.dense_size_str()}, " + f"{torch.iinfo(index_dtype).max}, {self.dtype_to_str(index_dtype)})" + ) + root_op = arg_root_ops[reduction_type] + # Use logical_index if it was unpacked, otherwise fall back to physical index + index_var = ( + f"({str(logical_index)}).to({self.dtype_to_str(index_dtype)})" + if logical_index is not None + else f"{reduction_range_prefix}index" + ) + self.compute.splice( + f"""\ + {accumulator}_next, {accumulator_index}_next = triton_helpers.{root_op}imum_with_index( + {accumulator}, {accumulator_index}, {value}, {index_var} + ) + {accumulator} = {where_cond(f"{accumulator}_next", accumulator)} + {accumulator_index} = {where_cond(f"{accumulator_index}_next", accumulator_index)} + """ + ) + final_argreduce( + self.post_loop_combine, + result_var, + accumulator, + accumulator_index, + argreduce_result_kind(), + ) + elif is_welford_reduction(reduction_type): + result_var = self.welford_reduce( + result_var, reduction_type, value, where_cond, acc_type, dtype + ) + elif reduction_type == "online_softmax_reduce": + accumulator_max = f"_{result_var}_max" + accumulator_sum = f"_{result_var}_sum" + + # setup accumulator + self.body.writeline( + f"{accumulator_max} = tl.full({self.dense_size_str()}, float('-inf'), {acc_type})" + ) + self.body.writeline( + f"{accumulator_sum} = tl.zeros({self.dense_size_str()}, {acc_type})" + ) + + # combine + # Note, we pass config.use_fast_math to the JITFunction + # since a triton kernel can not access a config. + if isinstance(value, tuple): + value_max, value_sum = value + self.compute.splice( + f""" + {accumulator_max}_next, {accumulator_sum}_next = triton_helpers.online_softmax_combine_with_sum( + {accumulator_max}, {accumulator_sum}, {value_max}, {value_sum}, + {config.use_fast_math}, {config.strict_signed_zero} + ) + """ + ) + else: + self.compute.splice( + f""" + {accumulator_max}_next, {accumulator_sum}_next = triton_helpers.online_softmax_combine( + {accumulator_max}, {accumulator_sum}, {value}, + {config.use_fast_math}, {config.strict_signed_zero} + ) + """ + ) + + # mask + self.compute.splice( + f""" + {accumulator_max} = {where_cond(f"{accumulator_max}_next", accumulator_max)} + {accumulator_sum} = {where_cond(f"{accumulator_sum}_next", accumulator_sum)} + """ + ) + + # reduce. Similar to the final reduction for coopereative + # reduction + result_max = result_var + result_sum = self.cse.newvar( + dtype=dtype, shape=cast(Any, result_max).shape + ) + + result_var = self.online_softmax_reduce_final_reduction( + self.post_loop_combine, + result_max, + result_sum, + accumulator_max, + accumulator_sum, + dim, + dtype, + ) + elif strict_sum_loop: + zero = cast(str, default) + masked = self.cse.generate( + self.compute, + where_cond(value, zero), + dtype=value.dtype, + shape=value.shape, + ) + chunk_expr, chunk_dtype, chunk_shape = final_reduction( + self.compute, masked, None + ) + chunk = self.cse.generate( + self.compute, + chunk_expr, + dtype=chunk_dtype, + shape=chunk_shape, + ) + self.compute.writeline(f"{accumulator} = {accumulator} + {chunk}") + self.post_loop_combine.writeline(f"{result_var} = {accumulator}") + else: + combine_fn = ir.get_reduction_combine_fn(reduction_type, src_dtype) + updated = combine_fn(accumulator, value) + if reduction_type == "dot": + self.compute.writeline(f"{accumulator} = {updated}") + else: + self.compute.writeline( + f"{accumulator} = {where_cond(updated, accumulator)}" + ) + + if src_dtype == torch.bool: + # This is only really used for aten.any. It changes the + # final reduction of a non-persistent reduction from + # tmp5 = triton_helpers.max(_tmp5, 1)[:, None] + # to + # tmp5 = triton_helpers.max(_tmp5.to(tl.int8), 1)[:, None].to(tl.int1) + # which is needed because tl.reduce doesn't support tl.int1 + accumulator = self.cse.generate( + self.post_loop_combine, + f"{accumulator}.to(tl.int8)", + dtype=torch.int8, + shape=accumulator.shape, + ) + + final_reduction_define( + self.post_loop_combine, + cast(CSEVariable, result_var), + accumulator, + None, + ) + + if self.cooperative_reduction: + default = ir.Reduction.default_accumulator(reduction_type, src_dtype) + exit_stack = contextlib.ExitStack() + for buf in (self.post_loop_combine, self.post_loop_store): + # only do cooperative reduction combines if we have more than one thread block + buf.writeline("if HAS_RSPLIT:") + exit_stack.enter_context(buf.indent()) + + if reduction_type in arg_reduction_types: + if reduction_type in arg_with_value_reduction_types: + result_value, result_index = cast( + tuple[CSEVariable, CSEVariable], result_var + ) + result_prefix = result_value + block_value = str(result_value) + block_index = str(result_index) + elif reduction_type in arg_value_reduction_types: + result_prefix = cast(CSEVariable, result_var) + block_value = str(result_var) + block_index = self.reduction_resize(f"{result_var}_idx") + else: + result_prefix = cast(CSEVariable, result_var) + block_value = self.reduction_resize(f"{result_var}_val") + block_index = self.reduction_resize(f"{result_var}_idx") + block_value_name = f"{result_prefix}_bval" + self.post_loop_combine.writeline(f"{block_value_name} = {block_value}") + peer_val = self.codegen_cooperative_reduction_peer_combine( + block_value_name, src_dtype, default + ) + index_dtype = self.features.select_index_dtype() + peer_idx_input = f"{result_prefix}_bidx" + self.post_loop_combine.writeline(f"{peer_idx_input} = {block_index}") + peer_idx = self.codegen_cooperative_reduction_peer_combine( + peer_idx_input, index_dtype, torch.iinfo(index_dtype).max + ) + final_argreduce( + self.post_loop_store, + result_var, + peer_val, + peer_idx, + argreduce_result_kind(), + ) + elif is_welford_reduction(reduction_type): + if reduction_type != "welford_reduce": + raise AssertionError( + f"expected reduction_type 'welford_reduce', got {reduction_type!r}" + ) + result_mean, result_m2, result_weight = cast( + tuple[CSEVariable, CSEVariable, CSEVariable], result_var + ) + peer_mean = self.codegen_cooperative_reduction_peer_combine( + result_mean, + upcast_acc_dtype(src_dtype), + default[0], # type: ignore[index] + ) + peer_m2 = self.codegen_cooperative_reduction_peer_combine( + result_m2, + upcast_acc_dtype(src_dtype), + default[1], # type: ignore[index] + ) + peer_weight = self.codegen_cooperative_reduction_peer_combine( + result_weight, + upcast_acc_dtype(src_dtype), + default[2], # type: ignore[index] + ) + self.welford_reduce_final_reduction( + self.post_loop_store, + result_mean, + result_m2, + result_weight, + peer_mean, + peer_m2, + peer_weight, + dim, + dtype, + ) + elif reduction_type == "online_softmax_reduce": + result_max, result_sum = cast( + tuple[CSEVariable, CSEVariable], result_var + ) + if not isinstance(default, Sequence): + raise AssertionError( + f"expected Sequence default, got {type(default)}" + ) + peer_max = self.codegen_cooperative_reduction_peer_combine( + result_max, upcast_acc_dtype(src_dtype), default[0] + ) + peer_sum = self.codegen_cooperative_reduction_peer_combine( + result_sum, upcast_acc_dtype(src_dtype), default[1] + ) + self.online_softmax_reduce_final_reduction( + self.post_loop_store, + result_max, + result_sum, + peer_max, + peer_sum, + dim, + dtype, + ) + else: + peers = self.codegen_cooperative_reduction_peer_combine( + cast(CSEVariable, result_var), upcast_acc_dtype(src_dtype), default + ) + final_reduction_define( + self.post_loop_store, cast(CSEVariable, result_var), peers, None + ) + exit_stack.close() + + self.cse.reduction_cache[cache_key] = cast(Any, result_var) + + result_tuple = result_var if isinstance(result_var, tuple) else (result_var,) + self.outside_loop_vars.update(result_tuple) + if not all(isinstance(x, TritonCSEVariable) for x in result_tuple): + raise AssertionError("all result_tuple entries must be TritonCSEVariable") + + # If BF16/F16 upcasting was done, ensure the output is downcast to the + # expected dtype. + if do_upcast: + for i, result in enumerate(result_tuple): + if reduction_type in arg_with_value_reduction_types and i > 0: + continue + target_dtype = ( + original_src_dtype + if reduction_type + in (arg_value_reduction_types + arg_with_value_reduction_types) + else original_dtype + ) + if result.dtype != target_dtype: + self.post_loop_combine.writeline( + f"{result} = {result}.to({triton_compute_type(target_dtype)})" + ) + + return result_var + + def _online_softmax_reduce( + self, buffer, accumulator_max, accumulator_sum, dim, dtype: torch.dtype + ): + accumulator_max = self.reduction_collapse_dims(buffer, accumulator_max, dtype) + accumulator_sum = self.reduction_collapse_dims(buffer, accumulator_sum, dtype) + result_max, result_sum = [str(self.cse.newvar(dtype=dtype)) for _ in range(2)] + buffer.splice( + f""" + {result_max}, {result_sum} = triton_helpers.online_softmax_reduce( + {accumulator_max}, {accumulator_sum}, {dim}, + {config.use_fast_math}, {config.strict_signed_zero}) + {result_max} = {self.reduction_resize(f"{result_max}")} + {result_sum} = {self.reduction_resize(f"{result_sum}")} + """ + ) + + return result_max, result_sum + + def _welford(self, buffer, mean, m2, weight, dim, dtype: torch.dtype): + """ + Helper to codegen triton_helpers.welford. + """ + mean, m2, weight = ( + self.reduction_collapse_dims(buffer, value, dtype) + for value in (mean, m2, weight) + ) + welford = f"triton_helpers.welford({mean}, {m2}, {weight}, {dim})" + + def reduced_shape(shape): + return tuple(shape[0:dim] + shape[dim + 1 :]) + + welford_results = [ + self.cse.newvar(dtype=dtype, shape=reduced_shape(value.shape)) + for value in (mean, m2, weight) + ] + buffer.writeline(f"{', '.join([str(r) for r in welford_results])} = {welford}") + + return tuple( + self.reduction_resize_and_shape(value, value.shape) + for value in welford_results + ) + + def welford_reduce( + self, result_var, reduction_type, value, where_cond, acc_type, dtype + ): + """Helper to codegen a welford reduction""" + dim = self.triton_tensor_ndim() - self.num_reduction_dims + + accumulator = TritonCSEVariable( + f"{result_var}_mean", + shape=tuple(self.dense_size_list()), + dtype=acc_type, + bounds=ValueRanges.unknown(), + ) + accumulator_m2 = TritonCSEVariable( + f"{result_var}_m2", + shape=tuple(self.dense_size_list()), + dtype=acc_type, + bounds=ValueRanges.unknown(), + ) + accumulator_weight = TritonCSEVariable( + f"{result_var}_weight", + shape=tuple(self.dense_size_list()), + dtype=acc_type, + bounds=ValueRanges.unknown(), + ) + self.body.writeline( + f"{accumulator} = tl.zeros({self.dense_size_str()}, {acc_type})" + ) + self.body.writeline( + f"{accumulator_m2} = tl.zeros({self.dense_size_str()}, {acc_type})" + ) + self.body.writeline( + f"{accumulator_weight} = tl.zeros({self.dense_size_str()}, {acc_type})" + ) + if reduction_type == "welford_combine": + mean, m2, weight = value + self.compute.splice( + f"""\ + {accumulator}_next, {accumulator_m2}_next, {accumulator_weight}_next = triton_helpers.welford_combine( + {accumulator}, {accumulator_m2}, {accumulator_weight}, + {mean}, {m2}, {weight} + ) + """ + ) + else: + if reduction_type != "welford_reduce": + raise AssertionError( + f"expected reduction_type 'welford_reduce', got {reduction_type!r}" + ) + self.compute.splice( + f"""\ + {accumulator}_next, {accumulator_m2}_next, {accumulator_weight}_next = triton_helpers.welford_reduce( + {value}, {accumulator}, {accumulator_m2}, {accumulator_weight}, roffset == 0 + ) + """ + ) + self.compute.splice( + f"""\ + {accumulator} = {where_cond(f"{accumulator}_next", accumulator)} + {accumulator_m2} = {where_cond(f"{accumulator_m2}_next", accumulator_m2)} + {accumulator_weight} = {where_cond(f"{accumulator_weight}_next", accumulator_weight)} + """ + ) + result_mean = result_var + return self.welford_reduce_final_reduction( + self.post_loop_combine, + result_mean, + None, + None, + accumulator, + accumulator_m2, + accumulator_weight, + dim, + dtype, + ) + + def welford_reduce_final_reduction( + self, + buffer, + result_mean, + result_m2, + result_weight, + mean, + m2, + weight, + dim, + dtype, + ): + """Helper to codegen call to triton_helpers.welford""" + values = list(self._welford(buffer, mean, m2, weight, dim, dtype)) + + result_exprs = [result_mean, result_m2, result_weight] + for i, (result_expr, (value, shape)) in enumerate(zip(result_exprs, values)): + if result_expr is None: + result_expr = self.cse.newvar(dtype=dtype, shape=shape) + result_exprs[i] = result_expr + buffer.splice(f"{result_expr} = {value}") + + return tuple(result_exprs) + + def online_softmax_reduce_final_reduction( + self, buffer, result_max, result_sum, peer_max, peer_sum, dim, dtype + ): + accumulator_max = self.reduction_collapse_dims(buffer, peer_max, dtype) + accumulator_sum = self.reduction_collapse_dims(buffer, peer_sum, dtype) + buffer.splice( + f""" + {result_max}, {result_sum} = triton_helpers.online_softmax_reduce( + {accumulator_max}, {accumulator_sum}, {dim}, + {config.use_fast_math}, {config.strict_signed_zero}) + {result_max} = {self.reduction_resize(f"{result_max}")} + {result_sum} = {self.reduction_resize(f"{result_sum}")} + """ + ) + return result_max, result_sum + + def max_rsplit(self): + if self.fixed_config: + return self.fixed_config["RSPLIT"] + return TRITON_MAX_RSPLIT + + def codegen_cooperative_reduction_peer_combine( + self, result_var, dtype, default_val + ) -> CSEVariable: + """ + Generate code to save a [XBLOCK, RSPLIT] temporary workspace, where each thread block writes a different + column. After the barrier, every thread block loads the completed value so that it can compute the final + value independently. + """ + xnumel = self.numels["x"] + mask = "xindex < xnumel" if not self._has_constant_xmask() else None + + nbytes = xnumel * dtype.itemsize * self.max_rsplit() + ws_name, ws_offset = self.cooperative_reduction_workspace_cache.allocate(nbytes) + + self.post_loop_combine.splice( + f""" + {result_var}_ws = ({ws_name} + {self.index_to_str(ws_offset)}).to(tl.pointer_type({triton_type(dtype)})) + tl.store({result_var}_ws + (xindex * RSPLIT + rsplit_id), {result_var}, {mask}) + """, + strip=True, + ) + peers = self.create_cse_var( + f"{result_var}_peers", + shape=["XBLOCK", "RSPLIT"], + dtype=dtype, + bounds=ValueRanges.unknown(), + ) + self.post_loop_store.writeline( + f"{peers} = tl.load({result_var}_ws + (xindex * RSPLIT + rsplit_arange), " + f"rsplit_mask, eviction_policy='evict_first', other=triton_helpers.if_mask(rsplit_mask, {constant_repr(default_val)}))" + ) + return peers + + def store_reduction( + self, + name: str, + index: sympy.Expr, + value: CSEVariable, + ): + if not self.inside_reduction: + raise AssertionError("expected inside_reduction") + self.inside_reduction = False + dtype = V.graph.get_dtype(name) + indexing = self.indexing( + index, + block_ptr=True, + tma_compatibility_checker=self.tma_compatibility_checker_cls( + kernel=self, + dtype=dtype, + for_store=True, + force=False, + ), + ) + self.inside_reduction = True + var = self.args.output(name) + + exit_stack = contextlib.ExitStack() + if self.cooperative_reduction: + exit_stack.enter_context( + self.guard_cooperative_store(name, self.post_loop_store) + ) + + self._handle_pdl_before_access(self.post_loop_store, var) + + if isinstance(indexing, (BlockPtrOptions, TensorDescriptorOptions)): + self.post_loop_store.writeline( + DeferredLine( + name, + self.codegen_block_ptr_store_line( + name, + indexing, + indexing.format(var), + value, + f", boundary_check={indexing.boundary_check()!r}", + ), + ) + ) + else: + if not isinstance(indexing, IndexingOptions): + raise AssertionError(f"expected IndexingOptions, got {type(indexing)}") + + indexing_str = indexing.index_str + if ( + is_sympy_integer_like(index) + and value.shape is not None + and not all(str(x) == "1" for x in value.shape) + ): + value_shape = ", ".join(map(str, value.shape)) + indexing_str += f".broadcast_to({value_shape})" + + self.post_loop_store.writeline( + DeferredLine( + name, + f"tl.store({var} + ({indexing_str}), {value}, {indexing.mask_str})", + ) + ) + + exit_stack.close() + + def emit_reshape( + self, + value: CSEVariable, + shape: Sequence[sympy.Expr | int | str], + dtype: torch.dtype, + ) -> CSEVariable: + """Emit a tl.reshape into a new tile shape, returning a CSE var.""" + return self.cse.generate( + self.compute, + self._reshape_expr(value, shape), + dtype=dtype, + shape=shape, + ) + + def emit_reduce( + self, + value: CSEVariable, + reduction_type: str, + axis: int, + dtype: torch.dtype, + shape: Sequence[Any], + ) -> CSEVariable: + """Emit a Triton reduction primitive along `axis`, returning a CSE var.""" + reduce_fn = get_triton_reduction_function(reduction_type) + return self.cse.generate( + self.compute, + f"{reduce_fn}({value}, {axis})", + dtype=dtype, + shape=shape, + ) + + def emit_broadcast_via_reshape( + self, + value: CSEVariable, + pre_broadcast_shape: Sequence[sympy.Expr | int | str], + broadcast_shape: Sequence[sympy.Expr | int | str], + final_shape: Sequence[sympy.Expr | int | str], + dtype: torch.dtype, + out_shape: Sequence[Any], + ) -> CSEVariable: + """reshape(broadcast_to(reshape(value, pre_broadcast), broadcast), final). + + Used for nested-reduction broadcasts that lift a reduced-resolution + value (one element per group) to full or half resolution. + """ + reshaped = self._reshape_expr(value, pre_broadcast_shape) + broadcasted = ( + f"tl.broadcast_to({reshaped}, {triton_shape_str(broadcast_shape)})" + ) + line = triton_reshape(broadcasted, list(broadcast_shape), list(final_shape)) + return self.cse.generate( + self.compute, + line, + dtype=dtype, + shape=out_shape, + ) + + @staticmethod + def _reshape_expr( + value: CSEVariable, + shape: Sequence[sympy.Expr | int | str], + ) -> str: + old_shape = getattr(value, "shape", None) + if old_shape is None: + return f"tl.reshape({value}, {triton_shape_str(shape)})" + return triton_reshape(str(value), list(old_shape), list(shape)) + + def _lift_helper( + self, fn, values: tuple[CSEVariable, ...], dtypes: tuple[torch.dtype, ...] + ) -> str: + # Lift IR function for scan operations into a triton function + # in the global namespace + helper = IndentedBuffer() + helper.writeline("@triton.jit") + cse = CSE() + + args = [ + tuple( + cse.namedvar(f"arg{i}_{n}", dtype=dtype, shape=value.shape) + for n, (value, dtype) in enumerate(zip(values, dtypes)) + ) + for i in range(2) + ] + signature = ", ".join(str(x) for x in itertools.chain.from_iterable(args)) + helper.writeline(f"def {{name}}({signature}):") + + overrides = TritonOverrides() + + # Build a name that changes depending on fn to workaround a triton bug + # where the combine_fn to reduce and scan is not hashed, and so different + # scan ops may collide in the triton cache. + # This is fixed with the latest triton pin, but not the triton-rocm pin. + helper_name = "_triton_helper_fn" + + from torch._inductor.dtype_propagation import DtypePropagationOpsHandler + from torch._inductor.shape_propagation import ShapePropagationOpsHandler + + shape_handler = ShapePropagationOpsHandler() + dtype_handler = DtypePropagationOpsHandler() + + class CSEProxy(DefaultHandler): + def _default( + self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> Any: + nonlocal helper_name + helper_name += f"_{name}" + + output_dtype = getattr( + dtype_handler, + name, + )(*args, **kwargs) + + output_shape = getattr( + shape_handler, + name, + )(*args, **kwargs) + + return cse.generate( + helper, + getattr(overrides, name)(*args, **kwargs), + dtype=output_dtype, + shape=output_shape, + ) + + with helper.indent(), V.set_ops_handler(CSEProxy()): + outputs = fn(*args) + outputs = ", ".join(str(output) for output in outputs) + helper.writeline(f"return {outputs}") + + return self.helper_functions.add(helper.getvalue(), base_name=helper_name) + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[ + [tuple[CSEVariable, ...], tuple[CSEVariable, ...]], tuple[CSEVariable, ...] + ], + values: tuple[CSEVariable, ...], + ) -> tuple[CSEVariable, ...]: + """ + Perform an associative scan on 'values'. + """ + if not self.inside_reduction: + raise AssertionError("expected inside_reduction") + if self.cooperative_reduction: + raise AssertionError("TODO") + masks = OrderedSet(tree.mask_name() for tree in self.range_trees) + self.filter_masks(masks) + masks = sorted(masks) + if self._load_mask: + raise AssertionError("ops.scan not supported inside ops.masked") + + broadcasted_values = [] + accumulators = [] + + dtypes = tuple(upcast_compute_type(dtype) for dtype in dtypes) + cse_compute = functools.partial(self.cse.generate, self.compute) + combine_helper_fn = self._lift_helper(combine_fn, values, dtypes) + dim = self.triton_tensor_ndim() - self.num_reduction_dims + + for value, dtype in zip(values, dtypes): + value_dtype = self.cse.generate( + self.compute, + f"{value}.to({triton_compute_type(dtype)})", + dtype=dtype, + shape=value.shape, + ) + value = self.cse.generate( + self.compute, + f"tl.broadcast_to({value_dtype}, {self.dense_size_str()})", + dtype=dtype, + shape=tuple(self.dense_size_list()), + ) + broadcasted_values.append(value) + + acc_type = triton_acc_type(dtype) + + if not self.persistent_reduction: + reduced_size = self.dense_size_list() + reduced_size[-1] = "1" + accumulator = self.cse.newvar(dtype=dtype, shape=reduced_size) + reduced_size_str = f"[{', '.join(reduced_size)}]" + + default = "float('nan')" if dtype.is_floating_point else "0" + self.body.writeline( + f"{accumulator} = tl.full({reduced_size_str}, {default}, {acc_type})" + ) + + accumulators.append(accumulator) + + def csv(values): + return " ".join(f"{value}," for value in values) + + def cse_multiple(line, values, masks, dtypes): + n = len(values) + cache_keys = [f"{line}, {i}, {masks}" for i in range(n)] + if all(self.cse.contains(cache_key) for cache_key in cache_keys): + return [self.cse.get(cache_key) for cache_key in cache_keys] + result_vars = [ + self.cse.newvar(dtype=dtype, shape=value.shape) + for (dtype, value) in zip(dtypes, values) + ] + self.compute.writeline( + f"{csv(result_vars)} = {line}", + ) + for result_var, cache_key in zip(result_vars, cache_keys): + if masks: + result_var.mask_vars = masks # type: ignore[attr-defined] + self.cse.put(cache_key, result_var) + return tuple(result_vars) + + partial_scan_vars = cse_multiple( + f"tl.associative_scan(({csv(broadcasted_values)}), {dim}, {combine_helper_fn})", + broadcasted_values, + masks, + dtypes, + ) + + if not self.persistent_reduction: + # tl.reduce doesn't work for non-commutative operators, so instead + # of repeating the scan op as a reduction, we use sum to select the + # last scan value + def _partial_scan_shape(var): + if var.shape is None: + return None + else: + shape = list(var.shape) + shape[-1] = "1" + return shape + + partial_reduce_vars = [ + cse_compute( + f"triton_helpers.select_one(({partial_scan_var}), rbase == (RBLOCK - 1), dim=-1, keep_dims=True)", + dtype=upcast_compute_type(partial_scan_var.dtype), + shape=_partial_scan_shape(partial_scan_var), + ) + for partial_scan_var in partial_scan_vars + ] + accs_next = combine_fn(tuple(accumulators), tuple(partial_reduce_vars)) + full_scan_vars = combine_fn(tuple(accumulators), partial_scan_vars) + result_vars = [ + cse_compute( + f"tl.where(roffset > 0, {full_scan}, {partial_scan})", + dtype=partial_scan.dtype, + shape=partial_scan.shape, + ) + for full_scan, partial_scan in zip(full_scan_vars, partial_scan_vars) + ] + for acc_next, accumulator, partial_reduce in zip( + accs_next, accumulators, partial_reduce_vars + ): + self.compute.writeline( + f"{accumulator} = tl.where(roffset > 0, {acc_next}, {partial_reduce})" + ) + else: + result_vars = partial_scan_vars + + for result_var in result_vars: + if not isinstance(result_var, TritonCSEVariable): + raise AssertionError( + f"expected TritonCSEVariable, got {type(result_var)}" + ) + result_var.mask_vars = OrderedSet(masks) + + return tuple(result_vars) + + def sort( + self, + dtypes: tuple[torch.dtype, ...], + values: tuple[CSEVariable, ...], + stable: bool, + descending: bool, + ) -> tuple[CSEVariable, ...]: + if not self.inside_reduction: + raise AssertionError("expected inside_reduction") + if self.cooperative_reduction: + raise AssertionError("TODO") + masks = OrderedSet(tree.mask_name() for tree in self.range_trees) + self.filter_masks(masks) + masks = sorted(masks) + if self._load_mask: + raise AssertionError("ops.sort not supported inside ops.masked") + if not self.persistent_reduction: + raise AssertionError("ops.sort is only supported in persistent reductions") + + cse_compute = functools.partial(self.cse.generate, self.compute) + dim = self.triton_tensor_ndim() - self.num_reduction_dims + + dtypes = tuple(upcast_compute_type(dtype) for dtype in dtypes) + if len(dtypes) != len(values): + raise AssertionError( + f"expected len(dtypes) == len(values), got {len(dtypes)} != {len(values)}" + ) + broadcasted_values = [ + cse_compute( + f"tl.broadcast_to({value}, {self.dense_size_str()})", + dtype=dtypes[i], + shape=tuple(self.dense_size_list()), + ) + for i, value in enumerate(values) + ] + + def csv(values): + return " ".join(f"{value}," for value in values) + + def cse_multiple(line, broadcasted_values, masks, dtypes): + n = len(broadcasted_values) + cache_keys = [f"{line}, {i}, {masks}" for i in range(n)] + if all(self.cse.contains(cache_key) for cache_key in cache_keys): + return [self.cse.get(cache_key) for cache_key in cache_keys] + result_vars = [ + self.cse.newvar(dtype=dtype, shape=value.shape) + for dtype, value in zip(dtypes, broadcasted_values) + ] # type: ignore[attr-defined] + self.compute.writeline( + f"{csv(result_vars)} = {line}", + ) + for result_var, cache_key in zip(result_vars, cache_keys): + if masks: + result_var.mask_vars = masks # type: ignore[attr-defined] + self.cse.put(cache_key, result_var) + return tuple(result_vars) + + if not self.range_trees[-1].is_reduction: + raise AssertionError("last range tree must be a reduction") + rnumel = "None" if self._has_constant_mask(self.range_trees[-1]) else "rnumel" + + if len(values) == 2: + line = ( + f"triton_helpers.sort_with_index({broadcasted_values[0]}, {broadcasted_values[1]}," + f" {rnumel}, {dim}, stable={stable}, descending={descending})" + ) + result_vars = cse_multiple(line, broadcasted_values, masks, dtypes) + else: + raise AssertionError("Unhandled sort") + + for result_var, input_var in zip(result_vars, values): + result_var.mask_vars = masks # type: ignore[attr-defined] + result_var.bounds = input_var.bounds + + return tuple(result_vars) + + def codegen_prologue(self, code: IndentedBuffer): + """ + Generate the output from prologue. This should be + extracted from the subgraph, which is why this is + partitioned from codegen_body. + """ + if not self.prologue: + return + + code.splice(self.prologue) + self.prologue.clear() + self.prologue_cache.clear() + + def codegen_body(self): + """ + Concat output code from index_code, loads, compute, stores, + suffix into self.body. + + For pointwise kernels, this is called just once at the end. + + For reduction kernels, this generates a loop over the reduction + axis. + """ + if not ( + self.indexing_code + or self.loads + or self.stores + or self.compute + or self.post_loop_combine + or self.post_loop_store + ): + return + + loop_trees = [tree for tree in self.range_trees if tree.is_loop] + if self.mix_order_reduction: + if not self.persistent_reduction: + raise AssertionError( + "Mix order reduction requires persistent reduction" + ) + accumname2var = {} + for idx, partial_accum in enumerate(self.saved_partial_accumulate): + reduction_type = partial_accum.reduction_type + default = ir.Reduction.default_accumulator(reduction_type, torch.float) + default = self._map_tuple_or_scalar(constant_repr, default) + name = f"accum{idx}" + self.body.writeline( + f"{name} = tl.full([R0_BLOCK], {default}, tl.float32)[None, :]" + ) + accumname2var[name] = self.cse.namedvar( + name, dtype=torch.float, shape=("1", "R0_BLOCK") + ) + self.body.writeline("split_size = min(RSPLIT_SIZE, xnumel - xoffset)") + self.body.writeline( + "for _ in tl.range(0, split_size, XBLOCK, num_stages=NUM_STAGES):" + ) + with self.body.indent(offset=1): + # generate xmask if it's not constant + if not self._has_constant_xmask(): + entry = self.range_trees[0] + if entry.prefix != "x": + raise AssertionError( + f"expected entry prefix 'x', got {entry.prefix!r}" + ) + x = entry.prefix + self.body.writeline(f"{x}mask = {entry.name} < {x}numel") + self.body.splice(self.indexing_code) + self.body.writelines( + [ + "xindex += XBLOCK", + ] + ) + self.body.splice(self.loads) + self.body.splice(self.compute) + self.body.splice(self.stores) + self.body.splice(self.post_loop_store) + + if self.uses_tma: + self.body.writeline("xoffset += XBLOCK") + + # no need to sum if XBLOCK == 1, or does that matter? + for idx, partial_accum in enumerate(self.saved_partial_accumulate): + var = partial_accum.value + name = f"accum{idx}" + combine_fn = ir.get_reduction_combine_fn( + partial_accum.reduction_type, torch.float + ) + triton_reduction_function = get_triton_reduction_function( + partial_accum.reduction_type, + ) + newval = self.cse.generate( + self.body, + f"{triton_reduction_function}({var}, 0)", + dtype=var.dtype, + shape=("R0_BLOCK",), + ) + import unittest + + with unittest.mock.patch.object(self, "compute", self.body): + updated = combine_fn( + accumname2var[name], + newval, + ) + self.body.writeline(f"{name} = {updated}") + + for idx in range(len(self.saved_partial_accumulate)): + self.body.writeline( + f"tl.store(ws_ptr + (tl.program_id(0) + {idx} * tl.num_programs(0)) * r0_numel + r0_index, accum{idx}, r0_mask)" + ) + + elif self.inside_reduction and len(loop_trees) > 0: + # Write the loop headers. + for level, tree in enumerate(loop_trees): + with self.body.indent(offset=level): + prefix = tree.prefix + loop_start = "rsplit_start" if self.cooperative_reduction else "0" + loop_end = ( + "rsplit_end" if self.cooperative_reduction else f"{prefix}numel" + ) + # Conditionalize pipelining on HIP for Triton due to + # reports of numerical inaccuracies on older Triton + if torch.version.hip and get_triton_version() > (3, 2): + num_stages = ", num_stages = 2" + else: + num_stages = "" + self.body.writeline( + f"for {prefix}offset in tl.range({loop_start}, {loop_end}, {prefix.upper()}BLOCK{num_stages}):" + ) + with self.body.indent(offset=level + 1): + self.iteration_ranges_codegen_header(tree, self.body) + + # The innermost loop performs the reduction. + with self.body.indent(offset=len(loop_trees)): + self.codegen_reduction_indices(self.body) + self.body.splice(self.indexing_code) + self.body.splice(self.loads) + self.body.splice(self.compute) + self.body.splice(self.stores) + + # Write loop suffixes. + for level, tree in reversed([*enumerate(loop_trees)]): + with self.body.indent(offset=level + 1): + # Advance pointers at the end of each loop. + for block_ptr, advancement in self.pointer_advancements[ + tree.symt + ].items(): + # Subtract any advancements made in the previous loop level. + if level < len(loop_trees) - 1: + prev_tree = loop_trees[level + 1] + prev_advancements = self.pointer_advancements[ + prev_tree.symt + ] + if block_ptr in prev_advancements: + prev_advancement = prev_advancements[block_ptr] + prev_block = TritonSymbols.get_block_size(prev_tree) + prev_num_iter = CeilDiv(prev_tree.numel, prev_block) + advancement = [ + cur - prev * prev_num_iter + for cur, prev in zip(advancement, prev_advancement) + ] + + # Drop pure no-op advances to avoid emitting + # `tl.advance(ptr, [0, 0, ...])` for pointers that + # are constant across every level. + if all( + V.graph.sizevars.statically_known_equals( + offset, sympy.Integer(0) + ) + for offset in advancement + ): + continue + + self.body.writeline( + DeferredLine( + self.block_ptr_to_buffer[block_ptr], + f"{block_ptr} = tl.advance({block_ptr}, {V.kernel.index_to_str(advancement)})", + ) + ) + + # Invalidate any cache entries that came from inside the loop. + self.cse.invalidate(self.outside_loop_vars) + tree.cache_clear() + else: + self.body.splice(self.indexing_code) + self.body.splice(self.loads) + self.body.splice(self.compute) + self.body.splice(self.stores) + self.body.splice(self.post_loop_combine) + if self.cooperative_reduction and ( + self.post_loop_combine or self.post_loop_store + ): + sem_ptr = f"{self.semaphores_name} + tl.program_id(1)" + self.body.splice( + f""" + if HAS_RSPLIT: + triton_helpers.x_grid_barrier({sem_ptr}) + """, + strip=True, + ) + self.cooperative_reduction_workspace_cache.on_loop_end() + if not self.mix_order_reduction: + self.body.splice(self.post_loop_store) + self.indexing_code.clear() + self.loads.clear() + self.compute.clear() + self.stores.clear() + self.post_loop_combine.clear() + self.post_loop_store.clear() + + def kernel_benchmark_extra_args(self) -> list[str]: + args = [] + if self.need_numel_args(): + numel_args: list[sympy.Expr] = [] + self.add_numel_to_call_args("", numel_args, []) + for arg in numel_args: + if isinstance(arg, int): + args.append(str(arg)) + elif isinstance(arg, SymbolicCallArg): + hint = V.graph.sizevars.optimization_hint_with_override( + arg.inner_expr, + hint_override=self.hint_override, + ) + args.append(str(hint)) + elif isinstance(arg, sympy.Expr): + hint = V.graph.sizevars.optimization_hint_with_override( + arg, + hint_override=self.hint_override, + ) + args.append(str(hint)) + else: + raise ValueError(f"Unsupported numel argument type: {type(arg)}") + return args + + def codegen_kernel_benchmark(self, num_gb: float | None) -> IndentedBuffer: + """ + Generates Python code for benchmarking this Triton kernel. + - Creates example inputs (random tensors, constants, sizes). + - Runs the kernel on the current GPU/stream. + - Prints runtime (ms) and throughput (GB/s) using `num_gb`. + Args: + num_gb (float): The number of gigabytes to use for throughput calculation. + Returns: + IndentedBuffer: A buffer containing the generated Python benchmark code. + """ + result = IndentedBuffer() + _argdefs, call_args, signature, _ = self.args.python_argdefs() + + result.writelines(["", "", "def get_args():"]) + with result.indent(): + name_cnt = itertools.count() + var_names = [] + for arg_name, arg_sig in zip(call_args, signature): + var_name = f"arg_{next(name_cnt)}" + buf = V.graph.try_get_buffer(arg_name) + if buf: + size = V.graph.sizevars.optimization_hints_with_override( + buf.get_size(), + hint_override=self.hint_override, + ) + stride = V.graph.sizevars.optimization_hints_with_override( + buf.get_stride(), + hint_override=self.hint_override, + ) + result.writeline( + f"{var_name} = rand_strided({size}, {stride}, device='{coor_device_str(buf.get_device())}', dtype={buf.get_dtype()})" + ) + elif arg_name in V.graph.constants: + # note that random seed is put in V.graph.constants + const_tensor = V.graph.constants[arg_name] + size = V.graph.sizevars.optimization_hints_with_override( + const_tensor.size(), + hint_override=self.hint_override, + ) + stride = V.graph.sizevars.optimization_hints_with_override( + const_tensor.stride(), + hint_override=self.hint_override, + ) + result.writeline( + f"{var_name} = rand_strided({size}, {stride}, device='{coor_device_str(const_tensor.device)}', dtype={const_tensor.dtype})" # type: ignore[arg-type] + ) + elif isinstance(arg_sig, SizeArg): + symval_hint = V.graph.sizevars.optimization_hint_with_override( + arg_sig.expr, + hint_override=self.hint_override, + ) + + # Force the seed_offset to be 0 so calls to the same kernel + # using different seed offset will have the same benchmark harness. + # We can dedup kernel definitions in this case. + if "seed_offset" in arg_sig.name: + symval_hint = 0 + result.writeline(f"{var_name} = {symval_hint}") + elif isinstance(arg_sig, WorkspaceArg): + device = V.graph.get_current_device_or_throw() + count = V.graph.sizevars.optimization_hint_with_override( + arg_sig.count, hint_override=self.hint_override + ) + result.writeline( + f"{var_name} = torch.zeros({count}, device='{coor_device_str(device)}', dtype={arg_sig.dtype})" + ) + else: + raise KeyError( + f"Don't find the buffer or const tensor for {arg_name}" + ) + var_names.append(var_name) + var_names.extend(self.kernel_benchmark_extra_args()) + result.writeline(f"return {', '.join(var_names)},") + + result.writelines(["\n", "\n", "def call(args):"]) + current_device = V.graph.get_current_device_or_throw() + coor_preamble, index = coor_benchmark_device_idx(current_device.index) + with result.indent(): + if coor_preamble: + result.writeline(coor_preamble) + result.writeline(f"with {V.graph.device_ops.device_guard(index)}:") + with result.indent(): + result.writeline( + V.graph.device_ops.set_device(index) + ) # no-op to ensure context + stream_name = get_raw_stream_name(current_device.index) + result.writeline(f"{stream_name} = get_raw_stream({index})") + result.writeline( + f"{str(Placeholder.KERNEL_NAME)}.run(*args, stream={stream_name})" + ) + + # benchmark all configs + result.writelines(["\n", "\n", "def benchmark_all_configs(args):"]) + with result.indent(): + if coor_preamble: + result.writeline(coor_preamble) + result.writeline(f"with {V.graph.device_ops.device_guard(index)}:") + with result.indent(): + result.writeline( + V.graph.device_ops.set_device(index) + ) # no-op to ensure context + result.writeline( + f"return {str(Placeholder.KERNEL_NAME)}.benchmark_all_configs(*args)" + ) + + result.writelines(["\n", "\n", "if __name__ == '__main__':"]) + with result.indent(): + result.writeline( + "from torch._inductor.runtime.benchmarking import benchmarker" + ) + result.writeline("") + + result.writeline("args = get_args()") + result.writeline( + f"ms = benchmarker.benchmark(lambda: call(args), device='{V.graph.get_current_device_or_throw().type}', rep=40)" + ) + result.writeline(f"num_gb = {num_gb}") + result.writeline("gb_per_s = num_gb / (ms / 1e3)") + result.writeline( + 'print(f"{ms:.3f}ms {num_gb:.3f}GB {gb_per_s:.2f}GB/s")' + ) + + return result + + def imports_for_benchmark_kernel(self): + # Dedent BEFORE substituting get_raw_stream: a multi-line override would + # otherwise collapse dedent's common prefix and misindent the imports. + return textwrap.dedent( + """ + from torch._dynamo.testing import rand_strided + {} + import torch + """ + ).format(V.graph.device_ops.import_get_raw_stream_as("get_raw_stream")) + + def _get_heuristic(self): + if self.fixed_config: + return "fixed_config" + elif self.cooperative_reduction: + return "cooperative_reduction" + elif self.persistent_reduction: + if not self.inside_reduction: + raise AssertionError("expected inside_reduction") + return "persistent_reduction" + elif self.inside_reduction: + return "reduction" + return "pointwise" + + @classmethod + @lru_cache(None) + def gen_common_triton_imports(cls) -> str: + imports = IndentedBuffer() + imports.splice( + """ + import triton + import triton.language as tl + """ + ) + try: + import triton.language.extra.tlx # noqa: F401 + + imports.splice( + """ + import triton.language.extra.tlx as tlx # noqa: F401 + """ + ) + except ImportError: + pass + if attr_desc := gen_attr_descriptor_import(): + imports.writeline(attr_desc) + + imports.splice( + """ + from torch._inductor.runtime import triton_helpers, triton_heuristics + from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math + from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, DeviceProperties + """ + ) + if config.triton.proton_profiling: + imports.splice( + """ + import triton.profiler as proton + import triton.profiler.language as pl + pl.enable_semantic('triton') + """ + ) + + return imports.getvalue() + + @classmethod + def triton_meta_common(cls) -> TritonMeta: + return { + "enable_fp_fusion": not config.emulate_precision_casts, + "launch_pdl": cls._enable_pdl_codegen(), + "disable_ftz": config.eager_numerics.disable_ftz, + } + + @classmethod + def inductor_meta_common(cls): + inductor_meta = { + "backend_hash": torch.utils._triton.triton_hash_with_backend(), + "assert_indirect_indexing": config.assert_indirect_indexing, + "autotune_local_cache": config.autotune_local_cache, + "autotune_pointwise": config.triton.autotune_pointwise, + "autotune_remote_cache": config.autotune_remote_cache, + "force_disable_caches": config.force_disable_caches, + "dynamic_scale_rblock": config.dynamic_scale_rblock, + "incremental_autotune": config.incremental_autotune, + "max_autotune": config.max_autotune, + "max_autotune_pointwise": config.max_autotune_pointwise, + "min_split_scan_rblock": config.triton.min_split_scan_rblock, + "spill_threshold": config.triton.spill_threshold, + "store_cubin": config.triton.store_cubin, + "deterministic": config.deterministic or config.batch_invariant, + "batch_invariant": config.batch_invariant, + "force_filter_reduction_configs": config.test_configs.force_filter_reduction_configs, + "mix_order_reduction_allow_multi_stages": config.triton.mix_order_reduction_allow_multi_stages, + "dynamic_disable_pipelining": config.triton.dynamic_disable_pipelining, + } + + if config.write_are_deterministic_algorithms_enabled: + inductor_meta["are_deterministic_algorithms_enabled"] = ( + torch.are_deterministic_algorithms_enabled() + ) + + if torch.version.hip is not None: + inductor_meta["is_hip"] = True + if config.is_fbcode(): + inductor_meta["is_fbcode"] = True + if config.profile_bandwidth: + inductor_meta["profile_bandwidth"] = config.profile_bandwidth + inductor_meta["profile_bandwidth_regex"] = config.profile_bandwidth_regex + inductor_meta["profile_bandwidth_output"] = config.profile_bandwidth_output + inductor_meta["profile_bandwidth_with_do_bench_using_profiling"] = ( + config.profile_bandwidth_with_do_bench_using_profiling + ) + if config.coordinate_descent_tuning: + inductor_meta["coordinate_descent_tuning"] = ( + config.coordinate_descent_tuning + ) + inductor_meta["coordinate_descent_search_radius"] = ( + config.coordinate_descent_search_radius + ) + inductor_meta["coordinate_descent_check_all_directions"] = ( + config.coordinate_descent_check_all_directions + ) + return inductor_meta + + def inductor_meta_per_kernel(self) -> dict[str, Any]: + """ + Used by both standalone codegen_kernel() and ComboKernel.combo_grid_meta() + (which calls this on each sub_kernel). + """ + out: dict[str, Any] = { + "no_x_dim": self.no_x_dim, + "atomic_add_found": self.atomic_add_found, + "num_load": self.num_load, + "num_store": self.num_store, + "num_reduction": self.num_reduction, + # Triton will not accept an OrderedSet for autotune_hints + "autotune_hints": set(self.autotune_hints), # noqa: set_linter + } + if self.mix_order_reduction: + out["RSPLIT_SIZE"] = self.rsplit_size + if config.deterministic or config.test_configs.force_filter_reduction_configs: + out["has_loadstore_with_contiguous_rdim"] = ( + self.has_load_with_contiguous_rdim + or self.has_store_with_contiguous_rdim + ) + if self.tma_min_block_sizes: + out["tma_min_block_sizes"] = self.tma_min_block_sizes + if self.uses_tma: + out["uses_tma"] = True + if self.uses_device_tma: + out["uses_device_tma"] = True + if self.tiling_scores: + out["tiling_scores"] = self.tiling_scores + if self.min_xblock is not None: + out["min_xblock"] = self.min_xblock + if self.min_rblock is not None: + out["min_rblock"] = self.min_rblock + if self.cooperative_reduction: + out["persistent_reduction"] = self.persistent_reduction + if (rblock := self._get_native_matmul_persistent_rblock()) is not None: + out["native_matmul_persistent_rblock"] = rblock + if self.add_persistent_rblock: + out["add_persistent_rblock"] = True + if (rblock := self._strict_sum_rblock()) is not None: + out["strict_sum_rblock"] = rblock + if ( + config.benchmark_kernel + or config.profile_bandwidth + or config.benchmark_combo_kernel + ): + num_gb = self.estimate_kernel_num_bytes() / 1e9 + if num_gb is not None: + out["kernel_num_gb"] = num_gb + if config.benchmark_kernel or config.benchmark_combo_kernel: + flops = self.estimate_flops() + if flops is not None: + out["kernel_flop"] = flops + if self.host_tma_descriptor_args: + _, _, signature, _ = self.args.python_argdefs() + sig_arg_names = OrderedSet( + arg.name for arg in signature if hasattr(arg, "name") + ) + fixed_blocks: dict[str, int] = {} + if self.persistent_reduction: + for rt in self.range_trees: + if rt.is_reduction: + block_name = f"{rt.prefix.upper()}BLOCK" + if block_name not in sig_arg_names: + try: + val = self._get_persistent_reduction_block(rt.numel) + if self.is_native_matmul: + val = max(val, 16) + fixed_blocks[block_name] = val + except (TypeError, ValueError): + pass + + def _resolve_block_dim(s): + s_str = str(s) + if s_str in sig_arg_names: + return s_str + if s_str in fixed_blocks: + return fixed_blocks[s_str] + try: + return int(s) + except (TypeError, ValueError): + return s_str + + def _resolve_tensor_dim(s): + try: + return int(s) + except (TypeError, ValueError): + return str(s) + + resolved = {} + for inner, opts in self.host_tma_descriptor_args.items(): + dims = [_resolve_block_dim(s) for s in opts.block_shape] + resolved[inner] = { + "block_shape": dims, + "shape": [_resolve_tensor_dim(s) for s in opts.shape], + "strides": [_resolve_tensor_dim(s) for s in opts.strides], + } + out["host_tma_descriptor_args"] = resolved + return out + + @functools.cached_property + def add_persistent_rblock(self) -> bool: + # Bail on 3d tiling, which has more complicated coalesce patterns + looped_red = self.features.is_reduction() and not self.persistent_reduction + tiling_scores = self.tiling_scores + two_d_red = len(self.tiling) == 2 + if looped_red and two_d_red: + memory_stats = self.features.memory_stats(self.tiling) + dim_stats = memory_stats.persistent.memory.dim[0] + mem_ops_per_thread = dim_stats.count_per_thread + + if ( + tiling_scores is not None + and "x" in tiling_scores + and "r0_" in tiling_scores + ): + contiguous_red = tiling_scores_suggest_inner_reduction( + tiling_scores, self.features.reduction_numel + ) + else: + contiguous_red = ( + self.features.get_reduction_hint(tiling_scores) + == ReductionHint.INNER + ) + + looped_mem = memory_stats.looped.memory.bytes + persistent_mem = memory_stats.persistent.memory.bytes + # check that we save significant memory by doing persistent + saved_bytes_ratio = V.graph.sizevars.optimization_hint(looped_mem) / max( + V.graph.sizevars.optimization_hint(persistent_mem), + 1, + ) + + # TODO - rnumel should be reasonably close to power of 2 + if ( + # significant memory bandwidth savings + saved_bytes_ratio >= 1.3 + and contiguous_red + # TODO - need more detailed register analysis + and V.graph.sizevars.statically_known_leq( + self.features.reduction_numel, 32768 + ) + # We will already generate a persistent config in this case + and V.graph.sizevars.statically_known_gt( + self.features.reduction_numel, 2048 + ) + and mem_ops_per_thread <= 10 + ): + return True + return False + + def codegen_kernel(self, name=None) -> str: + """ + Convert the TritonKernel from Inductor SIMD IR to triton code, including inductor triton heuristics, imports, + metadata, and benchmarking infra. + """ + + code = IndentedBuffer() + + size_hints = {} + for prefix, numel in self.numels.items(): + if prefix_is_reduction(prefix) and not self.inside_reduction: + continue + + numel_hint = V.graph.sizevars.optimization_hint(numel) + size_hint = next_power_of_2(int(numel_hint)) + size_hints[prefix] = size_hint + + if name is None: + code.splice(self.gen_common_triton_imports()) + device_type = V.graph.get_current_device_or_throw().type + if device_type == "cpu": + code.splice("triton_helpers.set_driver_to_cpu()") + else: + code.splice("triton_helpers.set_driver_to_gpu()") + + if config.benchmark_kernel: + code.splice(self.imports_for_benchmark_kernel()) + + argdefs, _, signature, _ = self.args.python_argdefs() + # maps actual expression to SizeArg if it is in sizevars replacements + for i, arg in enumerate(signature): + if isinstance(arg, SizeArg): + # mypy is unhappy about the sympy.Expr + # type for the key of the dict below + symbol = cast(sympy.Symbol, arg.expr) + if symbol in V.graph.sizevars.inv_precomputed_replacements: + signature[i] = SizeArg( + arg.name, V.graph.sizevars.inv_precomputed_replacements[symbol] + ) + + mutated_args: OrderedSet[str] = OrderedSet() + for mutation in self.mutations: + if mutation in self.args.input_buffers: + mutated_args.add(self.args.input_buffers[mutation]) + if ( + mutation in self.args.inplace_buffers + and mutation not in V.graph.removed_buffers + and mutation not in self.removed_buffers + ): + mutated_args.add( + cast(InplacedBuffer, self.args.inplace_buffers[mutation]).inner_name + ) + if mutation in self.args.output_buffers: + mutation_arg = self.args.output_buffers[mutation] + if isinstance(mutation_arg, RemovedArg): + raise AssertionError("mutation_arg must not be a RemovedArg") + mutated_args.add(mutation_arg) + + # Note: [Workspace Mutation] + # workspace arguments are mutated, but are not marked as mutations in self.mutations + # because their buffers are added during codegen, and aren't tracked during + # lowering/scheduling. So we add them as mutated_args explicitly below. + # + # In the logic below, we only mark the workspaces a mutated if they are marked with + # zero_fill: that's because, if we don't expect the buffer to be pre-filled with + # zeros, then, although we still mutate the data, we don't care about those + # mutations because we don't make any assumptions about the contents of the + # workspace buffer. Similarly, ZERO_PER_GRAPH requires the kernel to return + # the buffer back to its original state. + for argname, arg in zip(argdefs, signature): + if ( + isinstance(arg, WorkspaceArg) + and arg.zero_mode == WorkspaceZeroMode.ZERO_ON_CALL + ): + mutated_args.add(argname.name) + + # pyrefly: ignore [bad-assignment] + mutated_args = sorted(mutated_args) + + for tree in self.active_range_trees(): + sizearg = SizeArg(f"{tree.prefix}numel", tree.numel) + signature.append(sizearg) + argdefs.append(ArgName(sizearg.name)) + # constexpr version causes issues, see + # https://github.com/pytorch/torchdynamo/pull/1362 + # triton_meta["constants"][len(argdefs)] = V.graph.sizevars.size_hint( + # tree.numel + # ) + # argdefs.append(f"{tree.prefix}numel: tl.constexpr") + + def add_constexpr_arg(arg_name): + # new versions (but not old versions) of Triton need constexprs included in the signature + if triton_version_uses_attrs_dict(): + signature.append(ConstexprArg(arg_name)) + argdefs.append(ArgName(arg_name, is_constexpr=True)) + + for tree in self.range_trees: + if tree.is_reduction and self.persistent_reduction: + # Rn_BLOCK for persistent_reduction is defined in codegen_static_numels + continue + if tree.tensor_dim is None: + continue + + add_constexpr_arg(f"{tree.prefix.upper()}BLOCK") + + if self.cooperative_reduction: + add_constexpr_arg("RSPLIT") + + if self.mix_order_reduction: + add_constexpr_arg("RSPLIT_SIZE") + add_constexpr_arg("NUM_STAGES") + + triton_meta_signature = signature_to_meta( + signature, size_dtype=self.index_dtype, argdefs=argdefs + ) + from torch.fx.experimental.proxy_tensor import _coor_enabled + + props_device = V.graph.get_current_device_or_throw() + if _coor_enabled(): + # compile-on-one-rank: drop the rank-specific index so this kernel's triton_meta + # (hence its cache key and the generated code) is byte-identical across ranks; + # the launcher resolves the real device at load time. + # NB: torch.device("cuda").index is None, not 0 -- that None is what reaches + # DeviceProperties.create below. It is not merely cosmetic for the cache key: + # index=None is the sentinel _resolve_load_device and make_launcher + # (triton_heuristics.py) use to set kernel.device_agnostic, which enables the + # per-device module/function handles. Keeping the index here would still give + # byte-identical source on every rank while silently disabling those handles -- + # a wrong-device bug that a byte-identity check would not catch. + props_device = torch.device(props_device.type) + triton_meta: TritonMeta = cast( + TritonMeta, + { + "signature": triton_meta_signature, + "device": DeviceProperties.create(props_device), + "constants": {}, + "native_matmul": ( + torch._inductor.config.triton.native_matmul + and ("tl.dot" in str(self.body) or "tl.dot" in str(self.compute)) + ), + **self.triton_meta_common(), + }, + ) + + if self.cooperative_reduction: + # Cooperative reductions rely on multi-block synchronization that + # requires cooperative-grid launches to avoid hanging. + triton_meta["launch_cooperative_grid"] = True + + # Skip memory optimization for forward of the training loop where we expect + # every new node will increase the peak memory and our greedy approach would + # introduce a lot of unnecessary cpu copies. + optimize_mem = V.graph.is_inference or V.graph.is_backward + + inductor_meta = { + "grid_type": self._get_grid_type().__name__, + "kernel_name": str(Placeholder.DESCRIPTIVE_NAME), + "mutated_arg_names": mutated_args, + "optimize_mem": optimize_mem, + **self.inductor_meta_per_kernel(), + **self.inductor_meta_common(), + } + + # Triton compiler includes equal_to_1 args into constants even + # when they are not constexpr. otherwise there may be a segfault + # during launching the Inductor-compiled Triton kernel. + # https://github.com/pytorch/pytorch/issues/120478#issuecomment-1962822307 + # https://github.com/triton-lang/triton/blob/231efe9ed2d200be0f69a07c298e4342b08efe3d/python/triton/runtime/jit.py#L384 + for arg_num in equal_1_arg_indices(signature): # type: ignore[index] + triton_meta["constants"][signature[arg_num].name] = 1 # type: ignore[index,union-attr] + + self.triton_meta = triton_meta + self.inductor_meta = inductor_meta + + self.codegen_prologue(self.body) + self._prescan_host_tma_materializability() + self.codegen_body() + + tma_fields = ( + "tma_min_block_sizes", + "uses_tma", + "uses_device_tma", + "host_tma_descriptor_args", + ) + final_kernel_meta = self.inductor_meta_per_kernel() + for field in tma_fields: + self.inductor_meta.pop(field, None) + if field in final_kernel_meta: + self.inductor_meta[field] = final_kernel_meta[field] + + if not self.uses_tma: + # TMA probing sets tma_min_block_sizes even when the access falls + # back to tl.load; a stale constraint regresses non-TMA kernels. + self.inductor_meta.pop("tma_min_block_sizes", None) + + self._filter_pdl(self.body) + + # Compute configs after codegen_body() so we know if the kernel + # uses atomic ops. On HIP, buffer ops don't support atomics, so + # we must not tag any args with pointer_range_32 in that case. + # Also disable pointer_range_32 when the config flag is off. + if torch.version.hip is not None and ( + self.atomic_add_found or not config.triton.emit_pointer_range_32 + ): + triton_meta["configs"] = [ + config_of( + signature, + pointer_range_override=(), + skip_cpp_wrapper_input_tensor_alignment=True, + ) + ] + else: + triton_meta["configs"] = [ + config_of(signature, skip_cpp_wrapper_input_tensor_alignment=True) + ] + + for helper in self.helper_functions: + code.writeline("") + code.splice(helper) + + if self.fixed_config: + heuristics_line = f""" + @triton_heuristics.{self._get_heuristic()}( + config={self.fixed_config.config!r}, + filename=__file__, + triton_meta={triton_meta!r}, + inductor_meta={inductor_meta!r} + ) + @triton.jit + """ + elif self.inside_reduction: + reduction_hint = self.features.get_reduction_hint(self.tiling_scores) + heuristics_line = f""" + @triton_heuristics.{self._get_heuristic()}( + size_hints={size_hints!r}, + reduction_hint={reduction_hint}, + filename=__file__, + triton_meta={triton_meta!r}, + inductor_meta={inductor_meta!r} + ) + @triton.jit + """ + else: + hint = select_tile_hint(size_hints, signature) + tile_hint = f"tile_hint=TileHint.{hint.name}," if hint is not None else "" + heuristics_line = f""" + @triton_heuristics.{self._get_heuristic()}( + size_hints={size_hints!r}, {tile_hint} + filename=__file__, + triton_meta={triton_meta!r}, + inductor_meta={inductor_meta!r}, + min_elem_per_thread={self.min_elem_per_thread} + ) + @triton.jit + """ + code.splice(heuristics_line) + kernel_name = name or str(Placeholder.KERNEL_NAME) + code.writeline( + f"def {kernel_name}({', '.join(x.full_name() for x in argdefs)}):" + ) + with code.indent(): + if config.triton.proton_profiling: + code.writeline(f'pl.enter_scope("{kernel_name}")') + self.codegen_static_numels(code) + for old, new in self.args.aliases(): + code.writeline(f"{old} = {new}") + code.splice(self.body) + if config.triton.proton_profiling: + code.writeline(f'pl.exit_scope("{kernel_name}")') + + if config.benchmark_kernel: + code.splice( + self.codegen_kernel_benchmark( + inductor_meta.get("kernel_num_gb") # type: ignore[arg-type] + ) + ) + + return code.getvalue() + + @staticmethod + def _get_persistent_RBLOCK(rnumel): + rnumel = V.graph.sizevars.simplify(rnumel) + if isinstance(rnumel, (sympy.Integer, int)): + val = int(rnumel) + val = next_power_of_2(val) + else: + val = 1 + while not V.graph.sizevars.statically_known_leq(rnumel, val): + if val > 16 * 1024: + raise ValueError(f"Failed to find static RBLOCK for {rnumel}") + val *= 2 + + return val + + return val + + def _get_native_matmul_persistent_rblock(self) -> int | None: + if ( + not self.is_native_matmul + or not self.persistent_reduction + or self.cooperative_reduction + ): + return None + + rblocks = [ + native_matmul_persistent_rblock(self._get_persistent_RBLOCK(tree.numel)) + for tree in self.range_trees + if tree.is_reduction + ] + return math.prod(rblocks) if rblocks else None + + def _get_persistent_reduction_block(self, rnumel) -> int: + if (rblock := self._strict_sum_rblock()) is not None: + if V.graph.sizevars.statically_known_geq(rblock, rnumel): + return rblock + raise AssertionError( + "persistent strict sum requires its planned reduction block " + "to cover the reduction" + ) + return self._get_persistent_RBLOCK(rnumel) + + @staticmethod + def has_persistent_RBLOCK(rnumel): + try: + TritonKernel._get_persistent_RBLOCK(rnumel) + return True + except ValueError: + return False + + @staticmethod + def apply_feature_required_overrides( + kernel_features: SIMDKernelFeatures, kernel_kwargs: dict[str, Any] + ) -> None: + # ops.sort only works with persistent reduction, and is not bandwidth + # bound anyway so taking the hit of non-coalesced loads is okay. + if ( + kernel_features.contains_op("sort") + or kernel_features.has_strict_sum_multirow_reduction() + ): + kernel_kwargs["override_persistent_reduction"] = True + kernel_kwargs["override_cooperative_reduction"] = False + # Cannot use persistent reduction with unknown dynamic rnumel. + if not TritonKernel.has_persistent_RBLOCK(kernel_features.reduction_numel): + if kernel_kwargs.get("override_persistent_reduction"): + raise AssertionError( + "cannot override persistent reduction with unknown dynamic rnumel" + ) + kernel_kwargs["override_persistent_reduction"] = False + + def codegen_static_numels(self, code): + """ + We get a small speedup from hard coding numels if they are static. + + This code stomps on the passed-in values by writing an constant to the top of the kernel. + + In a kernel like: + def KERNEL_NAME(in_ptr0, in_ptr1, out_ptr2, xnumel, r0_numel, XBLOCK : tl.constexpr, R0_BLOCK : tl.constexpr): + + We would add + xnumel = 4096 + r0_numel = 768 + + After the signature, before the kernel code, if we decided to make these static. As its hardcoded, it becomes + a better signal to triton on how to unroll and do some static indexing. So, it's not so much that downstream + knows that its a static numel, as that you just plop a constant into the kernel. + """ + + def is_static_integer(expr: sympy.Expr) -> bool: + return isinstance(expr, (sympy.Integer, int)) + + for tree in self.range_trees: + if not tree.is_reduction or self.inside_reduction: + simplified_tree_numel = V.graph.sizevars.simplify(tree.numel) + if is_static_integer(simplified_tree_numel): + code.writeline(f"{tree.prefix}numel = {int(simplified_tree_numel)}") + + if tree.is_reduction and self.persistent_reduction: + if self.cooperative_reduction: + numel = self.kexpr(self.rename_indexing(tree.numel)) + val = f"triton_helpers.constexpr_next_power_of_2(({numel} + RSPLIT - 1) // RSPLIT)" + else: + val = self._get_persistent_reduction_block(tree.numel) + if self.is_native_matmul: + # tl.dot only supports shapes >= 16 + val = max(val, 16) + + code.writeline(f"{tree.prefix.upper()}BLOCK: tl.constexpr = {val}") + + if tree.prefix == "x" and self.no_x_dim: + code.writeline("XBLOCK: tl.constexpr = 1") + + def _get_grid_type(self) -> type[triton_heuristics.GridExpr]: + n = sum([int(not tree.is_reduction) for tree in self.range_trees]) + if self.mix_order_reduction: + if n != 1: + raise AssertionError(f"expected n == 1, got {n}") + return triton_heuristics.MixOrderReductionGrid + elif self.cooperative_reduction: + if n != 1: + raise AssertionError(f"expected n == 1, got {n}") + return triton_heuristics.CooperativeReductionGrid + elif n == 1: + return triton_heuristics.Grid1D + elif n == 2: + if any(map(self.needs_yz_grid_overflow, self.range_trees)): + return triton_heuristics.Grid2DWithYZOverflow + return triton_heuristics.Grid2D + elif n == 3: + if self.is_native_matmul: + return triton_heuristics.BatchMatmulGrid3D + return triton_heuristics.Grid3D + raise ValueError(f"Unsupported number of dimensions: {n}") + + def add_numel_to_call_args(self, name, call_args, arg_types): + # TODO(jansel): if there are constants, we shouldn't bother passing them as args + for tree in self.range_trees: + if isinstance(tree.numel, (sympy.Integer, sympy.Symbol)): + expr = tree.numel + else: + expr = V.graph.wrapper_code.generate_numel_expr(name, tree) + + if not tree.is_reduction or self.inside_reduction: + call_args.append(expr) + arg_types.append(type(expr)) + + def call_kernel( + self, name: str, node: IRNode | None = None, deallocate_ws: bool = True + ): + wrapper = V.graph.wrapper_code + wrapper.write_triton_header_once() + _, call_args, _, arg_types = self.args.python_argdefs() + self.add_numel_to_call_args(name, call_args, arg_types) + + for ws in self.args.workspace_args: + wrapper.generate_workspace_allocation(ws) + + wrapper.generate_kernel_call( + name, + call_args, + triton=True, + arg_types=arg_types, + triton_meta=self.triton_meta, + inductor_meta=self.inductor_meta, + ) + + if deallocate_ws: + self.deallocate_workspaces() + + def codegen_nan_check(self) -> None: + wrapper = V.graph.wrapper_code + _, call_args, arg_signatures, _ = self.args.python_argdefs() + for arg, arg_signature in zip(call_args, arg_signatures): + if isinstance(arg_signature, TensorArg): + if V.graph.cpp_wrapper: + wrapper.writeline( + f'AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_check_inf_and_nan("{arg}", {arg}));' + ) + else: + line = f"assert not {arg}.isnan().any().item()" + wrapper.writeline(line) + line = f"assert not {arg}.isinf().any().item()" + wrapper.writeline(line) + + def create_cse_var(self, *args, **kwargs) -> TritonCSEVariable: + return TritonCSEVariable(*args, **kwargs) + + def codegen_iteration_ranges_entry(self, entry: IterationRangesEntry): + line = f"{entry.name} = {self.kexpr(self.rename_indexing(entry.expr))}" + + # mix order reduction introduces an extra loop across the x + # dimension + if entry.root.is_loop or (self.mix_order_reduction and entry.prefix == "x"): + self.indexing_code.writeline(line) + else: + # lift non-reduction stores outside loop + self.body.writeline(line) + + def iteration_ranges_ranges_code(self, entry: IterationRangesRoot) -> str: + if entry.tensor_dim is None: + raise AssertionError("entry.tensor_dim must not be None") + size = self.indexing_size_str(entry.tensor_dim) + # For batch matmul, we always set the ZBLOCK=1. + # In this case, we found not broadcasting tl.arange(0, ZBLOCK) is faster. + if ( + self.is_native_matmul + and entry.tensor_dim == 0 + and self.triton_tensor_ndim() == 4 + ): + size = "" + index_dtype = self.index_dtype + suffix = f".to({index_dtype})" if index_dtype != "tl.int32" else "" + if ( + self.cooperative_reduction + and self.persistent_reduction + and entry.is_reduction + ): + suffix = f"{suffix} + rsplit_start" + return f"tl.arange(0, {self.kexpr(entry.block_size())}){size}{suffix}" + + def iteration_ranges_scalar_code( + self, entry: IterationRangesRoot, value: Any + ) -> str: + index_dtype = self.index_dtype + ndim = self.triton_tensor_ndim() + size = [1] * ndim + return f"tl.full({size}, {value}, {index_dtype})" + + def iteration_ranges_get_pid(self, entry: IterationRangesRoot) -> str: + if entry.grid_dim is None: + raise AssertionError("entry.grid_dim must not be None") + key = f"tl.program_id({entry.grid_dim})" + # y_grid has a limit, so express it in terms of y and z in case of overflow. + # z grid is only exercised when max_tiles == 3 (off by default). + if self.needs_yz_grid_overflow(entry): + # For ynumel larger than max_ygrid, we need to use zdim. + # For each z dimension, there are tl.num_programs(1) yblocks which is passed by grad(x,y,z). + # So, we need to add tl.program_id(z) * tl.num_programs(y) *YBLOCK to get the correct yoffset. + key = f"({key} + tl.program_id({entry.grid_dim + 1}) * tl.num_programs({entry.grid_dim}))" + + # For batched matmul, we intentionally remap program_id axes so that the + # batch dimension is placed on CUDA gridDim.x (the fastest-varying launch axis). + # - gridDim.x scales to much larger sizes than gridDim.z (limited to 65536 in CUDA) + if self.is_native_matmul and self.triton_tensor_ndim() == 4: + reversed_pid_map = {0: 2, 1: 1, 2: 0} + key = f"tl.program_id({reversed_pid_map[entry.grid_dim]})" + + pid = entry.pid_cache.get(key, key) + if self.index_dtype != "tl.int32": + return f"{pid}.to({self.index_dtype})" + return pid + + def needs_yz_grid_overflow(self, entry: IterationRangesRoot) -> bool: + # Combo kernels use flattened dispatch where y_pid_offset is computed + # from the flattened pid, so YZ overflow is not needed + if self.is_combo_kernel and self.per_subkernel_blocks: + return False + return ( + entry.grid_dim == 1 + and not entry.has_zdim + and not self.cooperative_reduction + and not V.graph.sizevars.statically_known_leq(entry.numel, get_max_y_grid()) + ) + + def max_block(self, prefix: str) -> int: + if self.fixed_config: + return self.fixed_config[f"{prefix.upper()}BLOCK"] + return TRITON_MAX_BLOCK[prefix.upper()] + + def _has_constant_mask(self, tree: IterationRangesRoot) -> bool: + if not tree.supports_constant_mask(): + return False + + if self.is_native_matmul: + # tl.dot requires the shape to be >= 16, + # so when matmul shape is smaller than 16, we always keep the mask. + if V.graph.sizevars.statically_known_lt(tree.numel, 16): + return False + + if not self.optimize_mask: + return False + + if self.fixed_config and f"{tree.prefix.upper()}BLOCK" in self.fixed_config: + if self.fixed_config[f"{tree.prefix.upper()}BLOCK"] == 1: + return True + elif not self.is_combo_kernel: + if V.graph.sizevars.statically_known_equals(tree.numel, 1): + if not (tree.is_reduction and self.persistent_reduction): + return True + + # Masks are superfluous if numel is a multiple of BLOCK + # (We use the fact that BLOCK is required by triton to be a power of 2) + if tree.is_reduction and self.persistent_reduction: + max_block = self._get_persistent_reduction_block(tree.numel) + # Triton's auto-tuner can map a full hardware warp along the + # reduction axis. When RBLOCK < warp_size the excess lanes + # would execute out-of-bounds global loads. This results in + # faults on AMD hardware. Keep the dynamic mask so that all + # hardware stays correct. + device = V.graph.get_current_device_or_throw() + warp_size = get_warp_size(device) + if isinstance(max_block, int) and max_block < warp_size: + return False + elif tree.prefix == "x" and self.no_x_dim: + max_block = 1 + else: + max_block = self.max_block(tree.prefix) + + if tree.is_reduction and self.cooperative_reduction: + max_block = max_block * self.max_rsplit() + + # [Note: Constant mask optimisation] + # Optional optimization: if block divides numel exactly, we will + # never need to do a masked load to handle stragglers at the end. + # If this tree is for the y dimension, we should only use a constant + # mask if it can be guaranteed that: + # 1. (ynumel / YBLOCK) < max_ygrid or + # 2. (ynumel / YBLOCK) % max_ygrid == 0 + # Because YBLOCK is not constant, use a conservative heuristic: + # only use a constant mask if ynumel < max_ygrid. + # It's faster to avoid masking at all. But it is sound to always + # mask. + if V.graph.sizevars.statically_known_multiple_of(tree.numel, max_block): + return ( + tree.grid_dim != 1 + or tree.has_zdim + or V.graph.sizevars.statically_known_leq(tree.numel, get_max_y_grid()) + ) + + return False + + def _has_constant_xmask(self) -> bool: + xtree = self.range_trees[0] + if xtree.prefix != "x": + raise AssertionError(f"expected xtree prefix 'x', got {xtree.prefix!r}") + return self._has_constant_mask(xtree) + + def filter_masks(self, mask_vars: OrderedSet[str]) -> None: + for tree in self.range_trees: + if self._has_constant_mask(tree): + mask_vars.discard(tree.mask_name()) + + mask_vars.discard("None") + + @cache_on_self + def get_reduction_prefixes(self) -> list[str]: + return [ + prefix_str[symt] + for symt in list(TritonSymbols.reduction_types)[: self.num_reduction_dims] + ] + + def codegen_reduction_numels(self, buffer: IndentedBuffer) -> None: + """ + Generates code that flattens ND reduction numels, block sizes, etc. into 1D. + """ + # rnumel = r0_numel * ... * r(n-1)_numel + reduction_trees = [tree for tree in self.range_trees if tree.is_reduction] + rnumel = " * ".join(sorted(f"{tree.prefix}numel" for tree in reduction_trees)) + buffer.splice(f"rnumel = {self.kexpr(rnumel)}") + + # RBLOCK = R0_BLOCK * ... * R(N-1)_BLOCK + rn_blocks = [ + TritonSymbols.get_block_size(tree) + for tree in self.range_trees + if tree.is_reduction + ] + rblock = sympy_product(rn_blocks) + buffer.splice(f"RBLOCK: tl.constexpr = {self.kexpr(rblock)}") + + def _get_reduction_symbols(self, suffix: str, **kwargs) -> list[sympy.Symbol]: + """ + Helper to initialize symbols like rn_numel, rn_base, etc. + """ + rn_prefixes = self.get_reduction_prefixes() + return [sympy.Symbol(f"{prefix}{suffix}", **kwargs) for prefix in rn_prefixes] + + @cache_on_self + def _get_reduction_index_coeffs(self) -> list[sympy.Expr]: + """ + Compute coefficients to convert ND reduction indices to linear indices. + For example: + rindex = r0_index * r1_numel * ... * rn_numel + ... + rn_index. + """ + rn_prefixes = self.get_reduction_prefixes() + rn_numels = self._get_reduction_symbols("numel", integer=True, positive=True) + return [ + sympy_product(rn_numels[idx + 1 :]) for idx in range(len(rn_prefixes) - 1) + ] + [sympy.Integer(1)] + + def _flatten_reduction_indices(self, multi_inds: list[sympy.Expr]) -> sympy.Expr: + """ + Compute linear reduction indices from N dimensional ones. + """ + coeffs = self._get_reduction_index_coeffs() + return sympy_dot(coeffs, multi_inds) + + def codegen_reduction_indices(self, buffer: IndentedBuffer) -> None: + """ + Generates code that converts ND reduction indices into linear indices. + """ + # Gather relevant numels, indices, etc. + rn_offsets = self._get_reduction_symbols( + "offset", integer=True, nonnegative=True + ) + rn_inds = self._get_reduction_symbols("index", integer=True, nonnegative=True) + + # Compute roffset and rindex. + roffset = self._flatten_reduction_indices(rn_offsets) + buffer.splice(f"roffset = {self.index_to_str(roffset)}") + rindex = self._flatten_reduction_indices(rn_inds) + buffer.splice(f"rindex = {self.index_to_str(rindex)}") + + def iteration_ranges_codegen_header( + self, + entry: IterationRangesRoot, + code: IndentedBuffer, + ) -> None: + if entry.has_custom_codegen_header(): + if ( + self.cooperative_reduction + and self.persistent_reduction + and entry.is_reduction + ): + raise AssertionError( + "derived reduction roots do not support cooperative reductions" + ) + for sym, expr, constexpr in entry.named_constants(): + annotation = ": tl.constexpr" if constexpr else "" + code.writeline(f"{sym}{annotation} = {self.index_to_str(expr)}") + code.writeline( + f"{entry.name} = {self.index_to_str(entry.block_offset())} + " + f"{self.iteration_ranges_ranges_code(entry)}" + ) + code.writeline( + f"{entry.mask_name()} = {entry.name} < {self.index_to_str(entry.numel)}" + ) + return + + x = entry.prefix + if entry.is_loop: + code.writeline(f"{entry.name} = {x}offset + {x}base") + elif entry.grid_dim is None: + # no need to "{x}offset = " + code.writeline(f"{entry.name} = {self.iteration_ranges_ranges_code(entry)}") + code.writeline(f"{x}offset = 0") + else: + if entry.tensor_dim is not None: + line = f"{x}offset + {self.iteration_ranges_ranges_code(entry)}" + else: + line = self.iteration_ranges_scalar_code(entry, f"{x}offset") + + block_size = ( + f"{x.upper()}BLOCK" if not self.mix_order_reduction else "RSPLIT_SIZE" + ) + code.writelines( + [ + f"{x}offset = {self.iteration_ranges_get_pid(entry)} * {block_size}", + f"{entry.name} = {line}", + ] + ) + if self._has_constant_mask(entry): + code.writeline(self.create_constant_mask(entry)) + elif not (x == "x" and self.mix_order_reduction): + # mix order reduction should generate xmask inside the loop + code.writeline(f"{entry.mask_name()} = {entry.name} < {x}numel") + + +class FusedUserDefinedTritonKernel(TritonKernel): + """ + When fusing a user-defined triton kernel with epilogues, we use this class to generate the modified triton kernel source + """ + + def __init__( + self, + tiling: dict[str, sympy.Expr], + features: SIMDKernelFeatures, + scheduler_node: FusedExternTritonKernelSchedulerNode, + ) -> None: + super().__init__( + tiling, + features=features, + min_elem_per_thread=0, + optimize_mask=True, + fixed_config=None, + hint_override=None, + is_combo_kernel=False, + ) + self.scheduler_node = scheduler_node + if not isinstance( + self.scheduler_node.kernel_node.node, ir.UserDefinedTritonKernel + ): + raise AssertionError( + f"expected UserDefinedTritonKernel, got {type(self.scheduler_node.kernel_node.node)}" + ) + self.ir_node: ir.UserDefinedTritonKernel = self.scheduler_node.kernel_node.node + if not self.ir_node.can_fuse_epilogue(): + raise AssertionError("ir_node epilogue must be fusable") + + # must be true because `self.ir_node.can_fuse_epilogue()` + if len(self.ir_node.kernel_stores.stores) != 1: + raise AssertionError( + f"expected 1 store, got {len(self.ir_node.kernel_stores.stores)}" + ) + self.original_stored_expr = ast.unparse( + self.ir_node.kernel_stores.stores[0].store_value_node + ) + self.original_stored_expr = self.original_stored_expr.replace("\n", "") + + def load(self, name: str, index: sympy.Expr) -> TritonCSEVariable: + # must be true because `self.ir_node.can_fuse_epilogue()` + if len(self.ir_node.mutable_args) != 1: + raise AssertionError( + f"expected 1 mutable arg, got {len(self.ir_node.mutable_args)}" + ) + if name == self.ir_node.mutable_args[0].get_name(): + # when the fused epilogue nodes tries to load the mutated buffer + # we replace the load with the expression stored by the user kernel + loaded_expr = self.original_stored_expr + indexing = self.indexing(index) + dtype = V.graph.get_dtype(name) + if indexing.expand_shape: + shape = indexing.expand_shape + else: + shape = TritonSymbols.get_block_shape(indexing.index) + result_var = self.cse.generate( + self.loads, loaded_expr, dtype=dtype, shape=shape + ) + return result_var + else: + # The scheduler should prevent this. + raise AssertionError( + f"Epilogue attempted to load from '{name}'. " + "Inductor indexing variables are not defined in user kernel scope. " + ) + + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> None: + if not isinstance(self.scheduler_node.fused_epilogue.node, ir.ComputedBuffer): + raise AssertionError( + f"expected ComputedBuffer, got {type(self.scheduler_node.fused_epilogue.node)}" + ) + if name == self.scheduler_node.fused_epilogue.node.get_name(): + # when the fused epilogue nodes tries to store to its destination buffer + # we remember this expr and then later replace it into the `tl.store` call of the original kernel + layout = self.scheduler_node.fused_epilogue.node.layout + if not isinstance(layout, ir.Layout): + raise AssertionError(f"expected ir.Layout, got {type(layout)}") + store_dtype = layout.dtype + self.new_store_cse_var = self.cse.generate( + self.compute, + f"{value}.to({triton_store_type(store_dtype)})", + dtype=store_dtype, + shape=value.shape, + ) + else: + raise AssertionError( + f"Epilogue attempted to store to '{name}'. " + "Inductor indexing variables are not defined in user kernel scope. " + ) + + # returns a str which is the src code of a modified version of the user kernel that includes the epilogues + def codegen(self) -> str: + with self: + index_vars = self.split_and_set_ranges( + self.scheduler_node.fused_epilogue.get_ranges() + ) + self.scheduler_node.fused_epilogue.codegen(index_vars) + + # Generate a new AST where the store value expr is replaced with the new value + new_ast = copy.deepcopy(self.ir_node.kernel_ast) + from torch._higher_order_ops.triton_kernel_wrap import ( + identify_triton_stores, + identify_triton_stores_from_ast, + ) + + # avoid redundant cache entry of new_ast + kernel_stores = identify_triton_stores_from_ast(new_ast) + if len(kernel_stores.stores) != 1: + raise AssertionError(f"expected 1 store, got {len(kernel_stores.stores)}") + + new_store_value_node = ast.Name(self.new_store_cse_var.name) + + def _replace_arg( + call_node: ast.Call, + arg_name: str, + positional_index: int, + new_arg, + ): + if len(call_node.args) > positional_index: + call_node.args[positional_index] = new_arg + + # Check keyword args + for keyword in call_node.keywords: + if keyword.arg == arg_name: + keyword.value = new_arg + + _replace_arg( + kernel_stores.stores[0].store_node, "value", 1, new_store_value_node + ) + + src_with_store_replaced = ast.unparse(new_ast) + + # then, we need to inject the additional `load` and `compute` lines generated when we `codegen` the epilogue nodes + + src_lines = src_with_store_replaced.splitlines() + + # identify the store again, because the previous parse-modify-unparse could've change its location + kernel_stores = identify_triton_stores(src_with_store_replaced) + # python ast lineno is 1-indexed + store_line_index = kernel_stores.stores[0].store_node.lineno - 1 + + indentations = " " * kernel_stores.stores[0].store_node.col_offset + + load_lines = [indentations + l for l in self.loads.get_lines_ref()] + compute_lines = [indentations + l for l in self.compute.get_lines_ref()] + + new_src_lines = ( + src_lines[:store_line_index] + + load_lines + + compute_lines + + src_lines[store_line_index:] + ) + return "\n".join(new_src_lines) + + +class TritonScheduling(SIMDScheduling): + """Scheduling backend for Triton kernel code generation.""" + + kernel_type: type[Any] = TritonKernel + backend_features = OrderedSet( + [ + BackendFeature.FOREACH, + BackendFeature.BUCKETIZE, + BackendFeature.INPLACE_BUFFERS, + BackendFeature.MASKED_SCATTER_WITH_INDEX, + BackendFeature.SCAN, + BackendFeature.SORT, + BackendFeature.TRITON_TEMPLATES, + BackendFeature.TUPLE_REDUCTION, + ] + ) + + def __init__(self, scheduler: Scheduler | None) -> None: + super().__init__(scheduler) + if scheduler is None or not hasattr(scheduler, "nodes"): + return + for node in scheduler.nodes: + if isinstance(node, (SchedulerNode, FusedSchedulerNode)): + node.debug_device_str = debug_triton_code + + @classmethod + def get_backend_features(cls, device: torch.device): + if ( + config.triton.cooperative_reductions + or config.triton.force_cooperative_reductions + ): + return OrderedSet( + [*cls.backend_features, BackendFeature.REDUCE_TO_SINGLE_ELEMENT] + ) + return cls.backend_features + + def codegen_comment(self, node_schedule, kernel_name=None): + wrapper = V.graph.wrapper_code + origins, _detailed_origins = get_kernel_metadata(node_schedule, wrapper) + if origins: + wrapper.make_comment(origins) + + if config.debug_fusion: + from torch._inductor.scheduler import ( + BaseSchedulerNode, + ForeachKernelSchedulerNode, + ) + + if not any( + isinstance(n, ForeachKernelSchedulerNode) for n in node_schedule + ): + # We probably should look what are the nodes inside a foreach + # schedule node + node_names = [ + n.get_name() + for n in node_schedule + if isinstance(n, BaseSchedulerNode) + ] + wrapper.make_comment( + f"{wrapper.comment} Fused node name list: {', '.join(node_names)}" + ) + + if kernel_name: + debug_handle = set_kernel_post_grad_provenance_tracing( + node_schedule, # type: ignore[arg-type] + kernel_name, + ) + wrapper.write_provenance_debug_handle(kernel_name, debug_handle) + + def _emit_kernel_to_wrapper( + self, + wrapper, + kernel, + src_code, + kernel_name, + subs_name, + node_schedule, + kernel_path, + get_kernel_metadata, + ): + """Emit kernel to wrapper, with support for external template handlers.""" + # External template handlers (e.g. Helion) can override kernel emission + if kernel.emit_kernel_override( + wrapper, + src_code, + kernel_name, + node_schedule, + kernel_path, + get_kernel_metadata, + ): + return # External handler handled it + + compile_wrapper = IndentedBuffer() + + if async_compile.use_process_pool(): + # The process pool is warm, we can shell out to workers right away. This + # allows us to save the result in async_compile.CompiledTritonKernels, + # so that the second time we call async_compile.triton, we do no work. + async_compile.triton(subs_name, src_code) + + compile_wrapper.writeline(f"async_compile.triton({subs_name!r}, '''") + + compile_wrapper.splice(src_code, strip=True) + current_device = V.graph.get_current_device_or_throw() + compile_wrapper.writeline(f"''', device_str='{current_device.type}')") + + # compile-on-one-rank: the artifact may be built on one machine and run on + # another, so the wrapper must not embed an absolute cache path (it carries the + # building user's name). Relative to the cache root it still locates the file. + from torch.fx.experimental.proxy_tensor import _coor_enabled + + if _coor_enabled() and kernel_path: + from torch._inductor.runtime.cache_dir_utils import cache_dir + + kernel_path = os.path.relpath(kernel_path, cache_dir()) + metadata_comment = f"# kernel path: {kernel_path}" + origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper) + metadata_comment += "\n" + origins + "\n" + detailed_origins + wrapper.define_kernel(kernel_name, compile_wrapper.getvalue(), metadata_comment) + + def define_kernel(self, src_code, node_schedule, kernel): + wrapper = V.graph.wrapper_code + if src_code in wrapper.src_to_kernel: + kernel_name = wrapper.src_to_kernel[src_code] + else: + fused_name = ( + get_fused_kernel_name(node_schedule, config.triton.descriptive_names) + if config.triton.descriptive_names + else "" + ) + if fused_name: + fused_name = V.choices.customize_fused_kernel_name(fused_name, src_code) + kernel_category = get_kernel_category_by_source_code(src_code)[:3] + kernel_name = "_".join( + ["triton", kernel_category, fused_name, wrapper.next_kernel_suffix()] + ) + if config.aot_inductor.model_name_for_generated_files: + # When AOTI compiles multiple submodules, we need to use the model name to + # distinguish kernel related symbols. + kernel_name = f"{config.aot_inductor.model_name_for_generated_files}_{kernel_name}" + + # use the original src_code as the key + wrapper.src_to_kernel[src_code] = kernel_name + subs_name = kernel_name if config.triton.unique_kernel_names else "triton_" + + # DESCRIPTIVE_NAME is used for profiling purposes; it shows the full kernel name + # even when unique_kernel_names is turned off. Meanwhile, KERNEL_NAME is sometimes set + # to "triton_" to maximize caching opportunities (when unique_kernel_names = False). + src_code = src_code.replace(str(Placeholder.DESCRIPTIVE_NAME), kernel_name) + src_code = src_code.replace(str(Placeholder.KERNEL_NAME), subs_name) + + # TODO(voz): Ostensibly, we should not need this. But there are cases where C++ codegen does + # not use BracesBuffer, so we have no good indicator of a C++ buffer atm. + src_code = src_code.replace("#pragma CMT", "#") + + _basename, _, kernel_path = get_path(code_hash(src_code.strip()), "py") + + self._emit_kernel_to_wrapper( + wrapper, + kernel, + src_code, + kernel_name, + subs_name, + node_schedule, + kernel_path, + get_kernel_metadata, + ) + + # log kernel metadata for offline analysis. + # E.g. one can find all unaligned inner reduction and check if + # padding helps with the perf kernel by kernel. + if metrics.is_metric_table_enabled("kernel_metadata"): + metrics.log_kernel_metadata(kernel_name, kernel_path, src_code) + + return kernel_name + + def benchmark_fused_nodes(self, nodes, n_spills_threshold=8) -> tuple[float, str]: + """ + Benchmark fused list of nodes and return the execution time + in milliseconds on randomly generated inputs. + """ + src_code = self.generate_kernel_code_from_nodes(nodes, benchmark_kernel=True) + mod = PyCodeCache.load(src_code) + return self.benchmark_codegened_module( + mod, n_spills_threshold, node_names=OrderedSet(n.get_name() for n in nodes) + ) + + def benchmark_codegened_module( + self, + mod, + n_spills_threshold=8, + node_names: OrderedSet[str] | None = None, + skip_perf_cache: bool = False, + ) -> tuple[float, str]: + """Benchmark an already compiled module. + + skip_perf_cache: don't serve the result from the .kernel_perf memo. Callers that + need the autotuned winner in mod.triton_.launchers (not just the timing) must set + this, since a perf-cache hit returns before the autotuner ever runs. + """ + device_interface = get_interface_for_device(V.graph.device_type) + with ( + preserve_rng_state(), + device_interface.device(V.graph.get_current_device_or_throw()), # type: ignore[attr-defined] + ): + ms = None + + def cache_file_path(): + if mod.__file__ is None: + raise AssertionError("mod.__file__ must not be None") + return os.path.splitext(mod.__file__)[0] + ".kernel_perf" + + def store_cache(): + path = cache_file_path() + write_atomic(path, str(ms)) + + def load_cache(): + path = cache_file_path() + if os.path.exists(path): + with open(path) as fd: + return float(fd.read()) + return None + + node_names = ( + node_names if node_names is not None else OrderedSet(["unknown"]) + ) + log.debug( + "kernel src code for %s written to: %s", + node_names, + mod.__file__, + ) + if not skip_perf_cache: + ms = load_cache() + if ms is not None: + return ms, mod.__file__ + + args = mod.get_args() + call = mod.call + wrapped_jit_function = mod.triton_ + # call once to trigger the compilation + try: + call(wrapped_jit_function.clone_args(*args)[0]) + except Exception as e: + if config.triton.disallow_failing_autotune_kernels_TESTING_ONLY: + raise + log.debug( + "Exception (%s) in compiling fused nodes %s", + e, + node_names, + ) + ms = float("inf") + store_cache() + return ms, mod.__file__ + + launchers = wrapped_jit_function.launchers + if len(launchers) != 1: + raise AssertionError(f"expected 1 launcher, got {len(launchers)}") + # n_spills does not necessarily mean it's not profitable to fuse, + # and sometimes it can be inaccurate + if launchers[0].n_spills > n_spills_threshold: + # skip benchmarking the kernel if there are register spills + ms = float("inf") + else: + device = V.graph.get_current_device_or_throw() + # We have to clone the inplace updated arguments to avoid earlier calls + # generating out of range indices for later calls. + ms = benchmarker.benchmark( + lambda: call(wrapped_jit_function.clone_args(*args)[0]), + device=device, + ) + # overhead of cloning args gives bias for fusing the kernel + # in the case of mutating/in-placeable second fusion + # TODO - would be better as a hook in triton do_bench that reset + # the input values between benchmarking + if len(wrapped_jit_function.mutated_arg_names) > 0: + ms = ms - benchmarker.benchmark( + lambda: wrapped_jit_function.clone_args(*args), + device=str(device), + ) + + log.debug( + "The fused kernel for %s took %.3f ms to run", + node_names, + ms, + ) + store_cache() + return ms, mod.__file__ + + def create_kernel_choices( # type: ignore[override] + self, + kernel_features: SIMDKernelFeatures, + kernel_args: list[Any], + kernel_kwargs: dict[str, Any], + ) -> list[TritonKernel]: + is_scan = kernel_features.contains_op("scan") + is_split_scan = is_scan and any( + node.is_split_scan() for node in kernel_features.scheduler_nodes() + ) + kernel_type: type[TritonKernel] = self.kernel_type + if is_split_scan: + from .triton_split_scan import TritonSplitScanKernel + + kernel_type = TritonSplitScanKernel + + if is_scan: + # TODO(jansel): scan does not yet work with cooperative reductions + kernel_kwargs["override_cooperative_reduction"] = False + + kernel_type.apply_feature_required_overrides(kernel_features, kernel_kwargs) + + kernel_kwargs = V.choices.triton_kernel_kwargs( + kernel_type, kernel_features, kernel_args, kernel_kwargs + ) + kernel = kernel_type(*kernel_args, **kernel_kwargs) + return self.add_multi_kernel_choices(kernel, kernel_args, kernel_kwargs) + + def add_multi_kernel_choices( + self, + kernel: TritonKernel, + kernel_args: list[Any], + kernel_kwargs: dict[str, Any], + ) -> list[TritonKernel]: + kernels: list[TritonKernel] = [kernel] + if not config.triton.multi_kernel: + return kernels + + optional_persistent = kernel.persistent_reduction and not kernel_kwargs.get( + "override_persistent_reduction" + ) + optional_cooperative = kernel.cooperative_reduction and not kernel_kwargs.get( + "override_cooperative_reduction" + ) + if optional_persistent: + kernels.append( + self.kernel_type( + *kernel_args, + **kernel_kwargs, + override_persistent_reduction=False, + ) + ) + if optional_cooperative: + rnumel = kernel.features.reduction_numel + # for larger sizes non-cooperative gets very slow + if V.graph.sizevars.statically_known_leq(rnumel, 65536): + kernels.append( + other := self.kernel_type( + *kernel_args, + **kernel_kwargs, + override_cooperative_reduction=False, + ) + ) + if optional_persistent and other.persistent_reduction: + kernels.append( + self.kernel_type( + *kernel_args, + **kernel_kwargs, + override_cooperative_reduction=False, + override_persistent_reduction=False, + ) + ) + + if len(kernels) > 1: + for kernel2 in kernels[1:]: + # Keep buffers needed by the non-persistent reduction so both kernels have the same arguments + kernel2.must_keep_buffers = kernel.must_keep_buffers + # persistent kernels must be generated last so must_keep_buffers works right + kernels.sort(key=lambda k: k.persistent_reduction) + return kernels + + def benchmark_combo_kernel(self, node_list, node_benchmark_results): + """ + Benchmark combo kernel partitions and return total execution time. + + Generates kernel code for each partition and benchmarks them. + Single-node partitions use benchmark_fused_nodes(), while multi-node + partitions use the combo kernel benchmarking path. + + Returns (total_ms, total_clone_ms, file_list). + """ + mod: ModuleType + ms: float + ms_clone: float + + def cache_file_path(): + if mod.__file__ is None: + raise AssertionError("mod.__file__ must not be None") + return os.path.splitext(mod.__file__)[0] + ".kernel_perf" + + def load_cache(): + path = cache_file_path() + if os.path.exists(path): + with open(path) as fd: + return tuple(float(e) for e in fd.read().split()) + return (None, None) + + def store_cache(): + path = cache_file_path() + write_atomic(path, str(ms) + " " + str(ms_clone)) + + total_ms, file_list = 0, [] + total_clone_ms: float = 0.0 + # Throwaway codegen below mutates these sets; swap in copies and restore + # in the finally: speedup_by_combo_kernel swallows some benchmark + # exceptions (Loop-carried-variable CompilationError) and continues + # compiling with V.graph, so a plain restore-on-return leaks the copies. + removed_buffers_orig = V.graph.removed_buffers + inplaced_to_remove_orig = V.graph.inplaced_to_remove + V.graph.removed_buffers = OrderedSet(removed_buffers_orig) + V.graph.inplaced_to_remove = OrderedSet(inplaced_to_remove_orig) + enable_autotune = config.combo_kernels_autotune > 0 + mixed_sizes = config.combo_kernel_allow_mixed_sizes > 0 + per_subkernel_blocks = config.combo_kernel_per_subkernel_blocks + try: + kernel_code_list = self.generate_combo_kernel_code( + subkernel_nodes=node_list, + custom_part_algorithm=True, + enable_autotune=enable_autotune, + mixed_sizes=mixed_sizes, + only_gen_src_code=True, + per_subkernel_blocks=per_subkernel_blocks, + ) + + # pyrefly: ignore [bad-assignment] + for src_code, kernel, node_group in kernel_code_list: + fused_node_lists = [node.get_nodes() for node in node_group] + names = [n.get_name() for nodes in fused_node_lists for n in nodes] + + if len(node_group) == 1: + # Single-node partition: use cached benchmark results from speedup_by_combo_kernel + node_ms, path = node_benchmark_results[node_group[0]] + # Regular kernels have negligible clone overhead + total_ms += node_ms + total_clone_ms += 0 + file_list.append(path) + continue + + if src_code is None: + raise AssertionError("src_code must not be None") + src_code = src_code.replace(str(Placeholder.KERNEL_NAME), "triton_") + mod = PyCodeCache.load(src_code) + + log.debug( + "kernel src code for %s written to: %s", + names, + mod.__file__, + ) + ms, ms_clone = load_cache() + if ms is not None: + total_ms += ms # type: ignore[assignment] + total_clone_ms += ms_clone + file_list.append(mod.__file__) + continue + + args = mod.get_args() + call = mod.call + wrapped_jit_function = mod.triton_ + + # call once to trigger the compilation + call(wrapped_jit_function.clone_args(*args)[0]) + + launchers = wrapped_jit_function.launchers + if len(launchers) != 1: + raise AssertionError(f"expected 1 launcher, got {len(launchers)}") + if launchers[0].n_spills > 0: + # skip benchmarking the kernel if there are register spills + ms = ms_clone = float("inf") + else: + device = V.graph.get_current_device_or_throw() + # We have to clone the inplace updated arguments to avoid earlier calls + # generating out of range indices for later calls. + ms = benchmarker.benchmark( + lambda: call(wrapped_jit_function.clone_args(*args)[0]), + device=device, + ) + ms_clone = benchmarker.benchmark( + lambda: wrapped_jit_function.clone_args(*args)[0], + device=device, + ) + + log.debug( + "The fused kernel for %s took %.3f ms to run, %.3f ms to clone inputs", + OrderedSet(n.get_name() for n in node_group), + ms, + ms_clone, + ) + store_cache() + total_ms += ms + total_clone_ms += ms_clone + file_list.append(mod.__file__) + args = call = wrapped_jit_function = None + torch.accelerator.empty_cache() + finally: + V.graph.removed_buffers = removed_buffers_orig + V.graph.inplaced_to_remove = inplaced_to_remove_orig + return total_ms, total_clone_ms, file_list + + +def debug_triton_code(node: BaseSchedulerNode) -> list[str]: + lines = [] + multi_template = node.get_template_node() + if not ( + multi_template is None or isinstance(multi_template, ir.MultiTemplateBuffer) + ): + raise AssertionError("multi_template must be None or a MultiTemplateBuffer") + if multi_template and multi_template.make_kernel_render is None: + lines.append(f"{node.get_name()} Unfinalized multi template buffer") + else: + from torch._inductor.codegen.cuda_combined_scheduling import ( + CUDACombinedScheduling, + ) + from torch._inductor.codegen.xpu.xpu_combined_scheduling import ( + XPUCombinedScheduling, + ) + + device = node.get_device() + if device is None: + raise AssertionError("device must not be None") + backend = node.scheduler.get_backend(device) + if not isinstance( + backend, (SIMDScheduling, CUDACombinedScheduling, XPUCombinedScheduling) + ): + raise AssertionError( + f"Scheduling backend should be SIMD or CUDACombined when generating debug Triton strings, got: {type(backend)}" + ) + + with V.graph.set_current_device(device): + # Don't increment kernel count when generating debug string. + # This will confuse some unit tests that check the number of + # generated kernels. + old_generated_kernel_count = metrics.generated_kernel_count + triton_code = backend.generate_kernel_code_from_nodes( + node.get_nodes() + ).strip() + metrics.generated_kernel_count = old_generated_kernel_count + + lines.append(f"{node.get_name()} Triton code:") + lines.append(textwrap.indent(triton_code, " ")) + return lines diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_combo_kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_combo_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..87a21e8456e7cf339aaaeea73525ba5aa756b083 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_combo_kernel.py @@ -0,0 +1,2036 @@ +import io +import itertools +import logging +import textwrap +import tokenize +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from functools import cache +from typing import Any, cast, TYPE_CHECKING + +import sympy +from sympy import Integer, Symbol + +import torch +from torch.utils._ordered_set import OrderedSet + + +if TYPE_CHECKING: + import triton + +from .. import config, metrics +from ..runtime.hints import DeviceProperties, TritonMeta +from ..runtime.runtime_utils import next_power_of_2 +from ..runtime.triton_heuristics import ( + RoundRobinComboKernelGrid, + SequentialComboKernelGrid, + SequentialFlattenComboKernelGrid, +) +from ..scheduler import BaseSchedulerNode +from ..stream_utils import ( + coor_benchmark_device_idx, + coor_device_str, + get_raw_stream_name, +) +from ..utils import ( + clear_on_fresh_cache, + DeferredLineBase, + Placeholder, + triton_version_uses_attrs_dict, +) +from ..virtualized import V +from .common import ( + ArgName, + ConstexprArg, + IndentedBuffer, + InplacedBuffer, + Kernel, + PythonPrinter, + RemovedArg, + SizeArg, + TensorArg, + WorkspaceArg, +) +from .simd import NodeInfo, prefix_is_reduction, SIMDScheduling +from .simd_kernel_features import SIMDKernelFeatures +from .triton import TritonKernel +from .triton_utils import ( + config_of, + equal_1_arg_indices, + is_unaligned_buffer, + signature_to_meta, +) + + +# Default block sizes used when combo kernel autotuning is disabled. +DEFAULT_COMBO_BLOCK_SIZE_1D = 1024 +DEFAULT_COMBO_BLOCK_SIZE_2D = 32 + + +log = logging.getLogger(__name__) +pexpr = PythonPrinter().doprint +LARGE_NUMELS = 51_200_000 +BLOCK_UTILIZATION = 0.8 + + +def _size_hint(expr: Any) -> int: + return V.graph.sizevars.optimization_hint(expr, fallback=1) + + +def _node_partition_log_context( + node: BaseSchedulerNode, node_info_map: dict[BaseSchedulerNode, NodeInfo] +) -> tuple[Any, ...]: + node_info = node_info_map[node] + tiling_hints = tuple( + (str(dim), _size_hint(numel)) + for dim, numel in sorted( + node_info.tiling.items(), key=lambda item: str(item[0]) + ) + ) + return ( + bool(node_info.features.is_reduction()), + node_info.is_persistent_reduction, + tiling_hints, + _size_hint(node_info.numel), + _size_hint(node_info.rnumel), + ) + + +def _partition_separation_log_context( + separated_nodes: list[BaseSchedulerNode], + companion_nodes: list[BaseSchedulerNode], + node_info_map: dict[BaseSchedulerNode, NodeInfo], +) -> tuple[tuple[Any, ...], tuple[Any, ...]]: + return ( + tuple(_node_partition_log_context(n, node_info_map) for n in separated_nodes), + tuple(_node_partition_log_context(n, node_info_map) for n in companion_nodes), + ) + + +def _log_partition_separation( + log_message: str, + separated_nodes: list[BaseSchedulerNode], + companion_nodes: list[BaseSchedulerNode], + node_info_map: dict[BaseSchedulerNode, NodeInfo], +) -> None: + if log.isEnabledFor(logging.DEBUG): + _log_partition_separation_once( + log_message, + len(separated_nodes), + _partition_separation_log_context( + separated_nodes, companion_nodes, node_info_map + ), + ) + + +# This diagnostic is otherwise repeated once per equivalent recompile. +@clear_on_fresh_cache +@cache +def _log_partition_separation_once( + log_message: str, + num_nodes: int, + partition_context: tuple[tuple[Any, ...], tuple[Any, ...]], +) -> None: + log.debug( + log_message, + num_nodes, + ) + + +def _default_custom_combo_kernel_horizontal_partition( + nodes: list[BaseSchedulerNode], + triton_scheduling: SIMDScheduling, + node_info_map: dict[BaseSchedulerNode, NodeInfo], +) -> list[list[BaseSchedulerNode]]: + """Horizontally partition the given list of nodes into a list of list of nodes where each sublist + represents a partition. Nodes in different partitions are implemented in different combo kernels. + Nodes in the same partition are likely to be implemented + in the same combo kernel, but subject to subsequent restrictions like CUDA limits for number of args. + + Input arguments: + nodes: a list of fused scheduler nodes to partition. + triton_scheduling: TritonScheduling instance. + node_info_map: a map from node to NodeInfo NamedTuple + Output: + a list of list of nodes with each sublist representing a partition. + + The default algorithm is to partition nodes based on the following rules: + 1) nodes with the same number of block dimensions are grouped together. + 2) large pointwise nodes (numels greater than LARGE_NUMELS) are separated from other nodes. + 3) large reduce nodes are separated from other nodes. + """ + + if len(nodes) < 1: + raise AssertionError(f"expected at least 1 node, got {len(nodes)}") + + # first partition nodes based on number of block dimensions + tilings = [node_info_map[n].tiling for n in nodes] + + max_dims = max(len(t) for t in tilings) + nodes_per_ndim: list[list[BaseSchedulerNode]] = [] + for i in range(2, max_dims + 1): + group_per_dim = [n for n, t in zip(nodes, tilings) if len(t) == i] + reduction = [ + n for n in group_per_dim if node_info_map[n].features.is_reduction() + ] + not_reduction = [n for n in group_per_dim if n not in reduction] + # rnumel > 2048 usually has long execution time + # BaseSchedulerNode.group[-1][-1] is rnumel for reduction nodes + # Scheduling heuristic: separate long reductions (rnumel > 2048). + # Uses optimization_hint with fallback=1 so unbacked defaults to short reduction. + long_reduction = [ + n + for n in reduction + if V.graph.sizevars.optimization_hint(n.group[-1][-1], fallback=1) > 2048 # type: ignore[arg-type] + ] + short_reduction = [n for n in reduction if n not in long_reduction] + very_large_reduction = [ + n + for n in long_reduction + if ( + V.graph.sizevars.optimization_hint(node_info_map[n].numel, fallback=1) + * V.graph.sizevars.optimization_hint( + node_info_map[n].rnumel, fallback=1 + ) + ) + > LARGE_NUMELS + ] + long_reduction = [n for n in long_reduction if n not in very_large_reduction] + if long_reduction: + _log_partition_separation( + "ComboKernels: %d long reduction nodes are separated", + long_reduction, + not_reduction + short_reduction, + node_info_map, + ) + if very_large_reduction: + log.debug( + "ComboKernels: %d very large reduction nodes are separated", + len(very_large_reduction), + ) + nodes_per_ndim.extend([node] for node in very_large_reduction) + large_pointwise = [ + n + for n in not_reduction + if not node_info_map[n].features.is_reduction() + and len(node_info_map[n].tiling) == 2 + and V.graph.sizevars.optimization_hint( + node_info_map[n].tiling["x"], fallback=1 + ) + > LARGE_NUMELS + ] + if large_pointwise: + companion_nodes = [n for n in not_reduction if n not in large_pointwise] + # TODO benchmark the performance when large pointwise nodes combining with others + # Include the non-large pointwise companions because the diagnostic + # describes a partition decision for the current candidate group. + _log_partition_separation( + "ComboKernels: %d large pointwise nodes are separated", + large_pointwise, + companion_nodes, + node_info_map, + ) + not_reduction = companion_nodes + nodes_per_ndim.extend([node] for node in large_pointwise) + + nodes_per_ndim.extend( + g for g in (not_reduction, short_reduction, long_reduction) if g + ) + + if sum(len(p) for p in nodes_per_ndim) != len(nodes): + raise AssertionError("partitioned node count must equal input node count") + return nodes_per_ndim + + +_custom_combo_kernel_horizontal_partition_algorithm: Callable[ + [ + list[BaseSchedulerNode], + SIMDScheduling, + dict[BaseSchedulerNode, NodeInfo], + ], + list[list[BaseSchedulerNode]], +] = _default_custom_combo_kernel_horizontal_partition + + +def set_custom_combo_kernel_horizontal_partition( + algorithm: Callable[ + [ + list[BaseSchedulerNode], + SIMDScheduling, + dict[BaseSchedulerNode, NodeInfo], + ], + list[list[BaseSchedulerNode]], + ], +) -> None: + """Sets the algorithm used to partition nodes into horizontal partitions. Nodes in different partitions + are implemented in different combo kernels. Nodes in the same partition are likely to be implemented + in the same combo kernel, but subject to subsequent restrictions like CUDA limits for number of args. + + The algorithm should take a list of nodes and return a list of list of nodes. + + The default algorithm is to partition nodes based on number of block dimensions. + """ + global _custom_combo_kernel_horizontal_partition_algorithm + _custom_combo_kernel_horizontal_partition_algorithm = algorithm + + +@dataclass +class PartitionState: + partitions: list[list[BaseSchedulerNode]] + cur_partition: list[BaseSchedulerNode] + cur_count: int + + def finalize(self) -> None: + if self.cur_partition: + self.partitions.append(self.cur_partition) + + +@dataclass +class SubKernelSetup: + uniquify_block_sizes: list[str] + lhs_names: list[str] + + +@dataclass +class SubKernelCode: + setup: IndentedBuffer + body: IndentedBuffer + setup_lhs_names: list[str] + + +@dataclass +class NoinlineSubKernelCall: + params: list[ArgName] + call_args: list[str] + signature_key: tuple[Any, ...] + + +@dataclass +class SharedBody: + body: IndentedBuffer + placeholder_names: list[str] + args_by_subkernel: list[list[str]] + setup_lhs_names: list[str] + + +@dataclass +class ComboLaunchConfig: + kwargs: dict[str, int] + num_warps: int + num_stages: int + + +class ComboKernel(Kernel): + """ + A kernel that combines multiple sub-kernels into a single fused kernel. + """ + + @staticmethod + def _update_partition( + partition_state: PartitionState, + node_rw_count: int, + node_info: BaseSchedulerNode, + ) -> None: + if partition_state.cur_count + node_rw_count > config.combo_kernel_max_num_args: + partition_state.partitions.append(partition_state.cur_partition) + partition_state.cur_partition = [node_info] + partition_state.cur_count = node_rw_count + else: + partition_state.cur_count += node_rw_count + partition_state.cur_partition.append(node_info) + + @staticmethod + def _base_horizontal_partition( + subkernel_nodes: list[BaseSchedulerNode], + triton_scheduling: SIMDScheduling, + node_info_map: dict[BaseSchedulerNode, NodeInfo], + custom_algorithm: bool, + ) -> list[list[BaseSchedulerNode]]: + """Generates a list of lists of node info tuples which consist of (fused_nodes, tiling, numel, rnumel) + for each subkernel node where each sublist is guaranteed to not exceed CUDA limits for number of args + (read/writes) and to have the same 2D or 1D blocking strategy.""" + # TODO support combination of kernels with different block dimensions + if len(subkernel_nodes) < 1: + raise AssertionError( + f"expected at least 1 subkernel node, got {len(subkernel_nodes)}" + ) + mixed_sizes = config.combo_kernel_allow_mixed_sizes > 1 or ( + config.combo_kernel_allow_mixed_sizes == 1 and custom_algorithm + ) + + ndim_to_partition_state: dict[int, PartitionState] = defaultdict( + lambda: PartitionState([], [], 0) + ) + yelem_to_partition_state: dict[int, PartitionState] = defaultdict( + lambda: PartitionState([], [], 0) + ) + all_partitions = [] + + for node in subkernel_nodes: + tiled_groups = node_info_map[node].tiling + node_info = node + + read_writes = node.read_writes + read_write_count = len(read_writes.reads) + len(read_writes.writes) + + ndim = len(tiled_groups) + if ndim < 2: + raise AssertionError(f"Combokernel not support tile {tiled_groups}") + + # Skip 2d reductions (r0_,r1_) and 3D pointwise (x,y,z) from combo + keys = tiled_groups.keys() + if ("r0_" in keys and "r1_" in keys) or "z" in keys: + all_partitions.append([node_info]) + continue + + if not mixed_sizes and ndim == 3: + y_elem = tiled_groups["y"] + partition_state = yelem_to_partition_state[y_elem] + ComboKernel._update_partition( + partition_state, read_write_count, node_info + ) + else: + if not (mixed_sizes or ndim <= 3): + raise AssertionError(f"No mixed sizes: tile {tiled_groups}") + partition_state = ndim_to_partition_state[ndim] + ComboKernel._update_partition( + partition_state, read_write_count, node_info + ) + + for partition_state in ndim_to_partition_state.values(): + partition_state.finalize() + all_partitions.extend(partition_state.partitions) + for partition_state in yelem_to_partition_state.values(): + partition_state.finalize() + all_partitions.extend(partition_state.partitions) + return all_partitions + + @staticmethod + def horizontal_partition( + nodes: list[BaseSchedulerNode], + triton_scheduling: SIMDScheduling, + node_info_map: dict[BaseSchedulerNode, NodeInfo], + custom_algorithm: bool = False, + ) -> list[list[BaseSchedulerNode]]: + """Generates a list of lists of node info tuples which consist of (fused_nodes, tiling, numel, rnum) + for each subkernel node where each sublist forms a ComboKernel. It horizontally partitions nodes into + sublists in the following way: + 1) call _custom_combo_kernel_horizontal_partition_algorithm() if custom_algorithm is True + 2) then, call _base_horizontal_partition() to partition nodes into sublists, each sublist is + guaranteed to not exceed CUDA limits for number of args (read/writes) and to have the same + 2D or 1D blocking strategy. + """ + if custom_algorithm: + raw_partitions = _custom_combo_kernel_horizontal_partition_algorithm( + nodes, triton_scheduling, node_info_map + ) + else: + raw_partitions = [nodes] + + """Generates a list of lists of node info tuples which consist of (fused_nodes, tiling, numel, rnumel) + for each subkernel node where each sublist is guaranteed to not exceed CUDA limits for number of args + (read/writes) and to have the same 2D or 1D blocking strategy.""" + all_partitions = [] + for raw_partition in raw_partitions: + all_partitions.extend( + ComboKernel._base_horizontal_partition( + raw_partition, triton_scheduling, node_info_map, custom_algorithm + ) + ) + return all_partitions + + class SequentialDispatch: + """ + The dispatcher which dispatches the subkernels in a sequential manner: + the blocks are first dispatched to the 1st subkernel (until it is filled), + then to the 2nd subkernel, and so on. + The class defines the methods specific to the dispatch algorithm. + Methods: + codegen_pid_range(...): codegen the pid range for each subkernel. + grid(...): codegen the grid size for launching the combo kernel. + """ + + grid_expr = SequentialComboKernelGrid + + @classmethod + def codegen_pid_range( + cls, kernel: "ComboKernel", num: int, code: IndentedBuffer + ) -> None: + if num == 0: + cls._calculate_xblocks(kernel, code) + code.splice(f"if pid < num_xblocks_{num}:") + with code.indent(): + code.splice("pid_offset = pid") + else: + code.splice(f"elif pid < num_xblocks_{num}:") + with code.indent(): + code.splice(f"pid_offset = pid - num_xblocks_{num - 1}") + + @classmethod + def _calculate_xblocks( + cls, kernel: "ComboKernel", code: IndentedBuffer + ) -> None: + x_numels_list = kernel.x_numels_list + for i in range(len(x_numels_list)): + xnumels, no_x_dim = ( + (x_numels_list[i], False) + if isinstance(x_numels_list[i], str) + and cast(str, x_numels_list[i])[0] != "-" + or ( + isinstance(x_numels_list[i], int) + and cast(int, x_numels_list[i]) > 0 + ) + else (kernel.min_x_blocks_list[i], True) + ) + xblock_str = ( + f"tl.cdiv({xnumels}, XBLOCK)" if not no_x_dim else f"{xnumels}" + ) + if i == 0: + code.splice(f"num_xblocks_{i} = {xblock_str}") + else: + code.splice(f"num_xblocks_{i} = num_xblocks_{i - 1} + {xblock_str}") + + class SequentialFlattenGridDispatch: + """ + Flattened grid dispatch for per-subkernel blocks. + Uses flattened grid (sum of x*y blocks, 1, 1) and computes + x_pid_offset, y_pid_offset from the flattened pid. + """ + + grid_expr = SequentialFlattenComboKernelGrid + + @classmethod + def codegen_pid_range( + cls, kernel: "ComboKernel", num: int, code: IndentedBuffer + ) -> None: + if num == 0: + cls._calculate_total_blocks(kernel, code) + code.splice(f"if pid < num_blocks_{num}:") + else: + code.splice(f"elif pid < num_blocks_{num}:") + + with code.indent(): + # Compute local pid within this subkernel's block range + if num == 0: + code.splice("local_pid = pid") + else: + code.splice(f"local_pid = pid - num_blocks_{num - 1}") + + # Compute x/y indices from flattened local_pid + if kernel.y_tree_list[num]: + code.splice(f"x_pid_offset = local_pid % x_blocks_{num}") + code.splice(f"y_pid_offset = local_pid // x_blocks_{num}") + else: + code.splice("x_pid_offset = local_pid") + + @classmethod + def _calculate_total_blocks( + cls, kernel: "ComboKernel", code: IndentedBuffer + ) -> None: + """ + Calculate total blocks for each subkernel (x_blocks * y_blocks) + and cumulative block counts for dispatch boundaries. + """ + for i, sub_kernel in enumerate(kernel.sub_kernels): + no_x_dim = sub_kernel.no_x_dim + xnumel = ( + kernel.min_x_blocks_list[i] if no_x_dim else kernel.x_numels_list[i] + ) + x_blocks_str = ( + f"tl.cdiv({xnumel}, XBLOCK_{i})" if not no_x_dim else f"{xnumel}" + ) + code.splice(f"x_blocks_{i} = {x_blocks_str}") + + if kernel.y_tree_list[i]: + numel = V.graph.sizevars.simplify(kernel.y_tree_list[i].numel) + ynumel = ( + int(numel) + if isinstance(numel, (Integer, int)) + else f"ynumel_{i}" + ) + code.splice(f"y_blocks_{i} = tl.cdiv({ynumel}, YBLOCK_{i})") + + blocks_expr = ( + f"x_blocks_{i} * y_blocks_{i}" + if kernel.y_tree_list[i] + else f"x_blocks_{i}" + ) + code.splice( + f"num_blocks_{i} = {blocks_expr}" + if i == 0 + else f"num_blocks_{i} = num_blocks_{i - 1} + {blocks_expr}" + ) + + class RoundRobinDispatch: + """ + The dispatcher which dispatches the subkernels in a round robin manner: + the blocks are interleavedly dispatched to each subkernel to execute them + in parallel. + The class defines the methods specific to the dispatch algorithm. + Methods: + codegen_pid_range(...): codegen the pid range for each subkernel. + grid(...): codegen the grid size for launching the combo kernel. + """ + + grid_expr = RoundRobinComboKernelGrid + + @classmethod + def codegen_pid_range( + cls, kernel: "ComboKernel", num: int, code: IndentedBuffer + ) -> None: + num_kernels = len(kernel.sub_kernels) + if num == 0: + cond = "if" + else: + cond = "elif" + code.splice(f"{cond} pid % {num_kernels} == {num}:") + with code.indent(): + code.splice(f"pid_offset = pid // {num_kernels}") + + def __init__( + self, + triton_kernel_cls: type[TritonKernel], + enable_autotune: bool = False, + mixed_sizes: bool = False, + per_subkernel_blocks: bool = False, + ) -> None: + super().__init__() + self.triton_kernel_cls = triton_kernel_cls + self.sub_kernels: list[TritonKernel] = [] + self.iter_vars_count = itertools.count() + self.grids: list[list[int]] = [] + self.min_x_blocks_list: list[int | str] = [] + self.x_numels_list: list[int | str] = [] + self.y_tree_list: list = [] + self.enable_autotune = enable_autotune + self.mixed_sizes = mixed_sizes + self.per_subkernel_blocks = per_subkernel_blocks + self.dispatch_class: ( + type[ + ComboKernel.SequentialDispatch + | ComboKernel.SequentialFlattenGridDispatch + | ComboKernel.RoundRobinDispatch + ] + | None + ) = None + self.block_args: list[str] = [] + # the following are used when autotuning is disabled + self.block_size_1d = DEFAULT_COMBO_BLOCK_SIZE_1D + self.block_size_2d = DEFAULT_COMBO_BLOCK_SIZE_2D + self.num_warps = 8 + self.block_size_reduce = 256 + self.dynamic_shape_args: list[str] = [] + self.no_bench_stitched_config: triton.Config | None = None + self.combo_compile_time_autotune = False + # Compile-time autotune: per-subkernel winning block sizes (XBLOCK_0, ...), passed as args. + self.stitched_block_config: dict[str, int] | None = None + # Distinct winner launch configs across the subkernels; seeds the combo's kernel-level autotune. + self.combo_launch_candidates: list[ComboLaunchConfig] = [] + self.noinline_sub_kernel_calls: list[NoinlineSubKernelCall] = [] + self.noinline_arg_name_maps: list[dict[str, str]] = [] + + @property + def bake_blocks(self) -> bool: + """Whether autotuning is disabled and default block values are required. + + Legacy combo kernels bake these values into the kernel body. Per-subkernel + block combos pass them as constexpr arguments through default_config. + """ + return not self.enable_autotune + + def create_sub_kernel(self, triton_kernel: TritonKernel) -> TritonKernel: + sub_kernel = triton_kernel + # pyrefly: ignore [bad-assignment] + metrics.generated_kernel_count -= 1 + if not self.per_subkernel_blocks: + sub_kernel.args = self.args + sub_kernel.iter_vars_count = self.iter_vars_count + sub_kernel.cse.iter_buffer_ids = self.cse.iter_buffer_ids + self.sub_kernels.append(sub_kernel) + return sub_kernel + + @staticmethod + def create_triton_kernel( + tiling: dict[str, sympy.Expr], + features: SIMDKernelFeatures, + optimize_mask: bool, + triton_kernel_cls: type[TritonKernel], + tiling_scores: dict[str, sympy.Expr] | None = None, + per_subkernel_blocks: bool = False, + ) -> TritonKernel: + """ + Only allow optimize_mask=True when 1) sequential dispatch is used, + 2) numels except x dimension are the same for each sub kernel. + """ + # Flattened dispatch: all dimensions derived from single pid + if per_subkernel_blocks: + pid_cache = { + "tl.program_id(0)": "x_pid_offset", + "tl.program_id(1)": "y_pid_offset", + } + else: + pid_cache = {"tl.program_id(0)": "pid_offset"} + + kwargs: dict[str, Any] = dict( + pid_cache=pid_cache, + optimize_mask=optimize_mask, + is_combo_kernel=True, + per_subkernel_blocks=per_subkernel_blocks, + # foreach kernels don't work with cooperative reductions + override_cooperative_reduction=False, + tiling_scores=tiling_scores, + ) + triton_kernel_cls.apply_feature_required_overrides(features, kwargs) + + return triton_kernel_cls(tiling, features=features, **kwargs) + + def codegen_static_numels_sub_kernel( + self, code: IndentedBuffer, sub_kernel: TritonKernel, num: int + ) -> SubKernelSetup: + """ + We get a small speedup from hard coding numels if they are static. + + This code stomps on the passed-in values by writing an constant to the top of the kernel. + + In a kernel like: + def KERNEL_NAME(in_ptr0, in_ptr1, out_ptr2, xnumel, rnumel, XBLOCK : tl.constexpr, R0_BLOCK : tl.constexpr): + + We would add + xnumel = 4096 + rnumel = 768 + + After the signature, before the kernel code, if we decided to make these static. As its hardcoded, it becomes + a better signal to triton on how to unroll and do some static indexing. So, it's not so much that downstream + knows that its a static numel, as that you just plop a constant into the kernel. + """ + grid = [] + lhs_names: list[str] = [] + uniquify_block_sizes = [] + for tree in sub_kernel.range_trees: + simplified_tree_numel = V.graph.sizevars.simplify(tree.numel) + if isinstance(simplified_tree_numel, (Integer, int)): + lhs_name = f"{tree.prefix}numel" + code.writeline(f"{lhs_name} = {int(simplified_tree_numel)}") + lhs_names.append(lhs_name) + else: + if f"{tree.prefix}numel_{num}" not in self.dynamic_shape_args: + raise AssertionError( + f"{tree.prefix}numel_{num} not in dynamic_shape_args" + ) + uniquify_block_sizes.append(f"{tree.prefix}numel") + + if not tree.is_reduction: + if isinstance(simplified_tree_numel, (Integer, int)): + grid.append(int(simplified_tree_numel)) + else: + # pyrefly: ignore [bad-argument-type] + grid.append(f"{tree.prefix}numel_{num}") + + if tree.is_reduction and sub_kernel.persistent_reduction: + val = TritonKernel._get_persistent_RBLOCK(tree.numel) + suffix = "" if self.per_subkernel_blocks else f"_{num}" + lhs_names.append(f"{tree.prefix.upper()}BLOCK{suffix}") + code.writeline( + f"{tree.prefix.upper()}BLOCK{suffix}: tl.constexpr = {val}" + ) + + if tree.prefix == "x" and sub_kernel.no_x_dim: + suffix = "" if self.per_subkernel_blocks else f"_{num}" + lhs_names.append(f"XBLOCK{suffix}") + code.writeline(f"XBLOCK{suffix}: tl.constexpr = 1") + uniquify_block_sizes.append("XBLOCK") + elif tree.prefix in ("x", "y") and self.per_subkernel_blocks: + uniquify_block_sizes.append(f"{tree.prefix.upper()}BLOCK") + elif tree.is_reduction: + if self.per_subkernel_blocks or sub_kernel.persistent_reduction: + uniquify_block_sizes.append(f"{tree.prefix.upper()}BLOCK") + self.grids.append(grid) + return SubKernelSetup( + uniquify_block_sizes=uniquify_block_sizes, + lhs_names=lhs_names, + ) + + def min_x_blocks_sub_kernel(self, sub_kernel: TritonKernel, num: int) -> None: + """ + Kernels with no_x_dim being true has no tunable XBLOCK. They have a fixed number of X blocks. + Grid calculation needs to make sure that they are assigned with enough number of blocks. + """ + min_x_blocks: int | str = 0 + x_numels: int | str = 0 + for tree in sub_kernel.range_trees: + simplified_tree_numel = V.graph.sizevars.simplify(tree.numel) + if tree.prefix == "x": + if isinstance(simplified_tree_numel, (Integer, int)): + x_numels = int(simplified_tree_numel) + else: + x_numels = f"{tree.prefix}numel_{num}" + if sub_kernel.no_x_dim: + min_x_blocks = x_numels + x_numels = ( + # pyrefly: ignore [unsupported-operation] + -min_x_blocks + if isinstance(x_numels, int) + # pyrefly: ignore [redundant-cast] + else "-" + cast(str, x_numels) + ) + else: + if isinstance(simplified_tree_numel, (Integer, int)): + x_numels = int(simplified_tree_numel) + else: + x_numels = f"{tree.prefix}numel_{num}" + self.min_x_blocks_list.append(min_x_blocks) + self.x_numels_list.append(x_numels) + + def select_heuristics(self, sub_kernel: TritonKernel) -> tuple[str, dict[str, int]]: + size_hints = { + prefix: next_power_of_2(V.graph.sizevars.optimization_hint(numel)) + for prefix, numel in sub_kernel.numels.items() + if not prefix_is_reduction(prefix) or sub_kernel.inside_reduction + } + if sub_kernel.persistent_reduction: + if not sub_kernel.inside_reduction: + raise AssertionError( + "persistent_reduction sub_kernel must be inside_reduction" + ) + heuristics = "persistent_reduction" + elif sub_kernel.inside_reduction: + heuristics = "reduction" + else: + heuristics = "pointwise" + return heuristics, size_hints + + def select_combo_heuristics( + self, heuristics_list: list[str], size_hints_list: list[dict[str, int]] + ) -> tuple[str, dict[str, int], TritonKernel]: + if not self.enable_autotune and self.no_bench_stitched_config is None: + return "foreach", size_hints_list[0], self.sub_kernels[0] + if "reduction" in heuristics_list: + i, _ = max( + enumerate(size_hints_list), + key=lambda x: x[1]["x"] if heuristics_list[x[0]] == "reduction" else 0, + ) + return heuristics_list[i], size_hints_list[i], self.sub_kernels[i] + elif "pointwise" in heuristics_list: + i, _ = max( + enumerate(size_hints_list), + key=lambda x: x[1]["x"] if heuristics_list[x[0]] == "pointwise" else 0, + ) + # modify size_hint to avoid oom check fail (may be a false alarm) + num_pointwise = len([e for e in heuristics_list if e == "pointwise"]) + num_reduction = len([e for e in heuristics_list if e == "reduction"]) + num_persistent_reduction = len( + [e for e in heuristics_list if e == "persistent_reduction"] + ) + if num_reduction != 0: + raise AssertionError( + "combining pointwise and reduction are not supported yet." + ) + heuristics = ( + "pointwise_with_reduction" + if num_persistent_reduction > 0 + else "pointwise" + ) + if len(heuristics_list) - num_pointwise >= 4: + size_hints = size_hints_list[i] + size_hints["x"] = min(128, size_hints["x"]) + return heuristics, size_hints_list[i], self.sub_kernels[i] + else: + # find persistent_reduction with maximum rnumel + i, _ = max( + enumerate(size_hints_list), + key=lambda x: max( + (v for k, v in x[1].items() if prefix_is_reduction(k)) + ), + ) + return heuristics_list[i], size_hints_list[i], self.sub_kernels[i] + + def get_mutated_args_sub_kernels(self) -> list[str]: + mutated_args: OrderedSet[str] = OrderedSet() + for num, sub_kernel in enumerate(self.sub_kernels): + arg_name_map = ( + self.noinline_arg_name_maps[num] if self.per_subkernel_blocks else {} + ) + for mutation in sub_kernel.mutations: + if mutation in sub_kernel.args.input_buffers: + name = sub_kernel.args.input_buffers[mutation] + mutated_args.add(arg_name_map.get(name, name)) + if ( + mutation in sub_kernel.args.inplace_buffers + and mutation not in V.graph.removed_buffers + and mutation not in sub_kernel.removed_buffers + ): + name = cast( + InplacedBuffer, sub_kernel.args.inplace_buffers[mutation] + ).inner_name + mutated_args.add(arg_name_map.get(name, name)) + if mutation in sub_kernel.args.output_buffers: + arg = sub_kernel.args.output_buffers[mutation] + if isinstance(arg, RemovedArg): + raise AssertionError("mutated output buffer arg was removed") + mutated_args.add(arg_name_map.get(arg, arg)) + return sorted(mutated_args) + + def select_dispatch_strategy(self) -> None: + if self.dispatch_class is not None: + return + if self.per_subkernel_blocks: + self.dispatch_class = ComboKernel.SequentialFlattenGridDispatch + return + # mixed_sizes is used for optimize_mask, so it only allows sequential dispatch + # Not mixed sizes on y dim technically is ok to use round robin as wells. + if not self.mixed_sizes or any(isinstance(e, str) for e in self.x_numels_list): + # str in x_numels_list means a dynamic shape + self.dispatch_class = ComboKernel.SequentialDispatch + return + # A negative x_blocks_list element means the kernel is not tunable, + # i.e., no_x_dim = True + x_numels_list = [abs(cast(int, e)) for e in self.x_numels_list] + total = max(x_numels_list) * len(x_numels_list) + needed = sum(x_numels_list) + if needed / total > BLOCK_UTILIZATION: + # Introduced overhead (masked blocks) is less than 20% + self.dispatch_class = ComboKernel.RoundRobinDispatch + else: + self.dispatch_class = ComboKernel.SequentialDispatch + + def jit_line( + self, + heuristics: str, + size_hints: dict[str, int], + selected_kernel: TritonKernel, + signature: list[Any], + argdefs: list[ArgName], + size_hints_list: list[dict[str, int]], + pointwise_with_reduce: bool = False, + ) -> str: + """Write the @triton_heuristics. decorator line for the combo kernel.""" + + can_use_32bit = all(k.index_dtype == "tl.int32" for k in self.sub_kernels) + size_dtype = "tl.int32" if can_use_32bit else "tl.int64" + for i, sub in enumerate(self.sub_kernels): + self.min_x_blocks_sub_kernel(sub, i) + self.select_dispatch_strategy() + triton_meta: TritonMeta = cast( + TritonMeta, + { + "signature": signature_to_meta( + signature, size_dtype=size_dtype, argdefs=argdefs + ), + "device": DeviceProperties.create( + V.graph.get_current_device_or_throw() + ), + "constants": {}, + # Inherit enable_fp_fusion, launch_pdl, disable_ftz so combo kernels + # compile with the same Triton options as standalone kernels. + **TritonKernel.triton_meta_common(), + }, + ) + + for arg_num in equal_1_arg_indices(signature): + triton_meta["constants"][signature[arg_num].name] = 1 # type: ignore[index,union-attr] + + triton_meta["configs"] = [ + config_of(signature, skip_cpp_wrapper_input_tensor_alignment=True) + ] + + mutated_args = self.get_mutated_args_sub_kernels() + dispatch = self.dispatch_class + if dispatch is None: + raise AssertionError("dispatch_class must not be None") + + # Compute the max persistent R0_BLOCK across sub-kernels. + # This is used by _reduction_configs() to avoid generating configs + # where XBLOCK * max_persistent_rblock creates pathologically large + # tiles that cause extreme ROCm compilation times. + # The max_persistent_rblock mirrors how R0_BLOCK is computed in + # codegen_static_numels_sub_kernel() for persistent reductions. + max_persistent_rblock = 0 + if not self.per_subkernel_blocks: + max_persistent_rblock = max( + ( + TritonKernel._get_persistent_RBLOCK(tree.numel) + for sub in self.sub_kernels + if sub.persistent_reduction + for tree in sub.range_trees + if tree.is_reduction + ), + default=0, + ) + + inductor_meta = { + "grid_type": dispatch.grid_expr.__name__, + "combo_grid_meta": self.combo_grid_meta(size_hints_list), + "kernel_name": str(Placeholder.DESCRIPTIVE_NAME), + "mutated_arg_names": mutated_args, + # Matches triton.py:codegen_kernel(): inference/backward graphs skip + # CPU-copy of mutated args during autotune retries; training-forward + # graphs must keep it to preserve benchmark inputs across retries. + "optimize_mem": V.graph.is_inference or V.graph.is_backward, + **self.triton_kernel_cls.inductor_meta_common(), + } + if max_persistent_rblock > 0: + inductor_meta["max_persistent_rblock"] = max_persistent_rblock + + # Sum per-sub-kernel bandwidth / FLOP estimates for the combo launch. + sub_metas = [sub.inductor_meta_per_kernel() for sub in self.sub_kernels] + self._kernel_num_gb = sum(m.get("kernel_num_gb") or 0 for m in sub_metas) + if config.benchmark_kernel or config.profile_bandwidth: + inductor_meta["kernel_num_gb"] = self._kernel_num_gb + if config.benchmark_kernel: + inductor_meta["kernel_flop"] = sum( + m.get("kernel_flop") or 0 for m in sub_metas + ) + + sub_kernel = selected_kernel + if heuristics == "foreach": + heuristics_line = f""" + @triton_heuristics.foreach( + filename=__file__, + triton_meta={triton_meta!r}, + inductor_meta={inductor_meta!r}, + ) + @triton.jit + """ + elif sub_kernel.inside_reduction: + reduction_hint = sub_kernel.features.get_reduction_hint( + sub_kernel.tiling_scores + ) + heuristics_line = f""" + @triton_heuristics.{heuristics}( + size_hints={size_hints!r}, + reduction_hint={reduction_hint}, + filename=__file__, + triton_meta={triton_meta!r}, + inductor_meta={inductor_meta!r} + ) + @triton.jit + """ + else: + tile_hint = "" + if len(size_hints) == 2: + tile_hint = "tile_hint=TileHint.SQUARE," + else: + tile_hint = "tile_hint=TileHint.DEFAULT," + heuristics_line = f""" + @triton_heuristics.{heuristics}( + size_hints={size_hints!r}, {tile_hint} + filename=__file__, + triton_meta={triton_meta!r}, + inductor_meta={inductor_meta!r} + ) + @triton.jit + """ + + self.triton_meta = triton_meta + self.inductor_meta = inductor_meta + + return heuristics_line + + def codegen_blocks(self, code: IndentedBuffer) -> None: + has_yblock = any(self.y_tree_list) + stitched_kwargs = ( + self.no_bench_stitched_config.kwargs + if self.no_bench_stitched_config is not None + else None + ) + + for block in self.block_args: + if stitched_kwargs is not None and block in stitched_kwargs: + size = stitched_kwargs[block] + elif "YBLOCK" in block: + size = self.block_size_2d + elif "XBLOCK" in block: + size = self.block_size_2d if has_yblock else self.block_size_1d + elif "R0_BLOCK" in block: + size = self.block_size_reduce + else: + raise AssertionError(f"{block} is not supported without autotuning") + code.splice(f"{block}: tl.constexpr = {size}") + + def get_block_args(self) -> list[ConstexprArg]: + """ + Calculate blocks from sub_kernels and range_trees. + Update self.block_args, self.y_tree_list + Return the block args + """ + block_names = {} + for i, sub_kernel in enumerate(self.sub_kernels): + y_tree = None + for tree in sub_kernel.range_trees: + if tree.is_reduction and ( + not sub_kernel.inside_reduction or sub_kernel.persistent_reduction + ): + continue + if tree.prefix == "x" and sub_kernel.no_x_dim: + continue + if tree.prefix == "y": + y_tree = tree + if self.per_subkernel_blocks: + block_names[f"{tree.prefix.upper()}BLOCK_{i}"] = tree.prefix + else: + block_names[f"{tree.prefix.upper()}BLOCK"] = tree.prefix + self.y_tree_list.append(y_tree) + self.block_args = list(block_names.keys()) + + return [ConstexprArg(x) for x in block_names] + + def add_numel_to_args( + self, argdefs: list[ArgName], signature: list[Any] + ) -> list[ArgName]: + for num, sub_kernel in enumerate(self.sub_kernels): + for tree in sub_kernel.active_range_trees(): + if not isinstance(tree.numel, (Integer, int)): + # only if it is a dynamic shape + sizearg = SizeArg(f"{tree.prefix}numel_{num}", tree.numel) + signature.append(sizearg) + argdefs.append(ArgName(f"{tree.prefix}numel_{num}")) + self.dynamic_shape_args.append(f"{tree.prefix}numel_{num}") + return argdefs + + def add_numel_to_call_args( + self, name: str, call_args: list[Any], arg_types: list[Any] + ) -> None: + for num, sub_kernel in enumerate(self.sub_kernels): + for tree in sub_kernel.range_trees: + numel_name = f"{tree.prefix}numel_{num}" + if numel_name not in self.dynamic_shape_args: + continue + if isinstance(tree.numel, (Integer, Symbol)): + expr = tree.numel + else: + expr = V.graph.wrapper_code.generate_numel_expr( + name, tree, suffix=str(num) + ) + + if not tree.is_reduction or sub_kernel.inside_reduction: + call_args.append(expr) + arg_types.append(type(expr)) + + def kernel_benchmark_extra_args(self) -> list[str]: + extra_args = [] + for num, sub_kernel in enumerate(self.sub_kernels): + for tree in sub_kernel.range_trees: + numel_name = f"{tree.prefix}numel_{num}" + if numel_name not in self.dynamic_shape_args: + continue + + if not tree.is_reduction or sub_kernel.inside_reduction: + extra_args.append( + str(V.graph.sizevars.optimization_hint(tree.numel)) + ) + return extra_args + + def _merge_noinline_kernel_args(self) -> None: + for sub_kernel in self.sub_kernels: + self._merge_noinline_kernel_arg(sub_kernel) + + self.noinline_arg_name_maps = [ + self._resolve_noinline_kernel_arg_names(sub_kernel) + for sub_kernel in self.sub_kernels + ] + + def _merge_noinline_kernel_arg(self, sub_kernel: TritonKernel) -> None: + # Each noinline body codegens in a local namespace, so different members + # can all have local names like in_ptr0/out_ptr0. First replay every + # local arg into the combo-main namespace; names are resolved only after + # all members have registered their in-place relationships. + local_args = sub_kernel.args + local_argdefs, _, local_signature, _ = local_args.python_argdefs() + + for argdef, signature in zip(local_argdefs, local_signature, strict=True): + if isinstance(signature, TensorArg): + buffer = signature.buffer + inplaced = local_args.inplace_buffers.get(buffer) + if ( + inplaced is not None + and not isinstance(inplaced, RemovedArg) + and inplaced.inner_name == argdef.name + ): + input_name, *output_names = inplaced.other_names + for output_name in output_names: + if output_name not in self.args.inplace_buffers: + self.args.make_inplace(input_name, output_name) + elif local_args.output_buffers.get(buffer) == argdef.name: + self.args.output(buffer) + else: + self.args.input(buffer) + elif isinstance(signature, SizeArg): + expr = signature.expr + if isinstance(expr, Symbol): + self.args.size(expr) + else: + self.args.seed_offset(argdef.name, int(expr)) + + def _resolve_noinline_kernel_arg_names( + self, sub_kernel: TritonKernel + ) -> dict[str, str]: + local_args = sub_kernel.args + local_to_main: dict[str, str] = {} + local_argdefs, _, local_signature, _ = local_args.python_argdefs() + + for argdef, signature in zip(local_argdefs, local_signature, strict=True): + if isinstance(signature, TensorArg): + buffer = signature.buffer + if ( + buffer in local_args.inplace_buffers + or local_args.output_buffers.get(buffer) == argdef.name + ): + main_name = self.args.output(buffer) + else: + main_name = self.args.input(buffer) + elif isinstance(signature, SizeArg): + main_name = self.args.sizevars[signature.expr] + else: + raise AssertionError( + f"unsupported combo noinline argument " + f"{argdef.name}: {type(signature).__name__}" + ) + + local_to_main[argdef.name] = main_name + + return local_to_main + + def _noinline_block_args_for_sub_kernel( + self, sub_kernel: TritonKernel, num: int + ) -> list[tuple[ArgName, str]]: + block_args: list[tuple[ArgName, str]] = [] + for tree in sub_kernel.range_trees: + if tree.prefix == "x" and sub_kernel.no_x_dim: + continue + if tree.prefix in ("x", "y") or ( + tree.is_reduction + and sub_kernel.inside_reduction + and not sub_kernel.persistent_reduction + ): + name = f"{tree.prefix.upper()}BLOCK" + block_args.append((ArgName(name, is_constexpr=True), f"{name}_{num}")) + return block_args + + def _signature_key_part(self, arg: Any) -> tuple[Any, ...]: + if isinstance(arg, TensorArg): + return ("tensor", arg.dtype, is_unaligned_buffer(arg)) + if isinstance(arg, SizeArg): + return ("size", type(arg.expr).__name__) + if isinstance(arg, ConstexprArg): + return ("constexpr", arg.name) + return (type(arg).__name__, getattr(arg, "name", None)) + + def _prepare_noinline_sub_kernel_calls(self) -> None: + calls: list[NoinlineSubKernelCall] = [] + for num, sub_kernel in enumerate(self.sub_kernels): + local_to_main = self.noinline_arg_name_maps[num] + local_argdefs, _, local_signature, _ = sub_kernel.args.python_argdefs() + params = list(local_argdefs) + call_args = [local_to_main[arg.name] for arg in local_argdefs] + signature_key: list[Any] = [ + self._signature_key_part(arg) for arg in local_signature + ] + + for tree in sub_kernel.active_range_trees(): + if isinstance(tree.numel, (Integer, int)): + continue + if tree.is_reduction and not sub_kernel.inside_reduction: + continue + params.append(ArgName(f"{tree.prefix}numel")) + call_args.append(f"{tree.prefix}numel_{num}") + signature_key.append(("range_numel", tree.prefix)) + + params.append(ArgName("x_pid_offset")) + call_args.append("x_pid_offset") + signature_key.append(("dispatch", "x_pid_offset")) + if any(tree.prefix == "y" for tree in sub_kernel.range_trees): + params.append(ArgName("y_pid_offset")) + call_args.append("y_pid_offset") + signature_key.append(("dispatch", "y_pid_offset")) + + for param, call_arg in self._noinline_block_args_for_sub_kernel( + sub_kernel, num + ): + params.append(param) + call_args.append(call_arg) + signature_key.append(("block", param.full_name())) + + calls.append( + NoinlineSubKernelCall( + params=params, + call_args=call_args, + signature_key=tuple(signature_key), + ) + ) + + self.noinline_sub_kernel_calls = calls + + def _can_share_body( + self, + heuristics_list: list[str], + ) -> bool: + if len(self.sub_kernels) < 2: + return False + if self.enable_autotune or self.per_subkernel_blocks: + return False + if torch.version.hip is not None: + # The shared-body form joins live pointer placeholders after a + # many-way dispatch branch. HIP/Triton currently has pathological + # compile times for that IR shape on large foreach lists, so keep + # ROCm on the existing per-branch body emission path. + return False + if self.dispatch_class not in ( + ComboKernel.SequentialDispatch, + ComboKernel.RoundRobinDispatch, + ): + return False + if self.dynamic_shape_args or any(self.y_tree_list): + return False + if any( + sub_kernel.no_x_dim + or sub_kernel.inside_reduction + or sub_kernel.persistent_reduction + for sub_kernel in self.sub_kernels + ): + return False + return all(heuristic == "pointwise" for heuristic in heuristics_list) + + @staticmethod + def _plain_lines(code: IndentedBuffer) -> list[str] | None: + lines: list[str] = [] + for line in code._lines: + if isinstance(line, str): + lines.append(line) + elif isinstance(line, DeferredLineBase): + evaluated = line() + if evaluated is not None: + lines.append(evaluated) + else: + return None + return lines + + @staticmethod + def _replace_names_in_line(line: str, replacements: dict[str, str]) -> str | None: + if not replacements: + return line + try: + pieces: list[str] = [] + cursor = 0 + for token in tokenize.generate_tokens(io.StringIO(line).readline): + if token.type == tokenize.NAME and token.string in replacements: + start, end = token.start[1], token.end[1] + pieces.append(line[cursor:start]) + pieces.append(replacements[token.string]) + cursor = end + pieces.append(line[cursor:]) + return "".join(pieces) + except tokenize.TokenError: + return None + + @classmethod + def _replace_names( + cls, lines: list[str], replacements: dict[str, str] + ) -> list[str] | None: + replaced: list[str] = [] + for line in lines: + new_line = cls._replace_names_in_line(line, replacements) + if new_line is None: + return None + replaced.append(new_line) + return replaced + + @staticmethod + def _names_in_lines(lines: list[str]) -> OrderedSet[str] | None: + names: OrderedSet[str] = OrderedSet() + try: + for line in lines: + for token in tokenize.generate_tokens(io.StringIO(line).readline): + if token.type == tokenize.NAME: + names.add(token.string) + except tokenize.TokenError: + return None + return names + + @staticmethod + def _range_tree_names(sub_kernel: TritonKernel) -> list[str]: + names: list[str] = [] + for tree in sub_kernel.range_trees: + names.append(tree.name) + names.extend(entry.name for entry in tree.nodes.values()) + return names + + @classmethod + def _range_tree_name_replacements( + cls, first: TritonKernel, sub_kernel: TritonKernel + ) -> dict[str, str] | None: + if len(first.range_trees) != len(sub_kernel.range_trees): + return None + + for first_tree, tree in zip( + first.range_trees, sub_kernel.range_trees, strict=True + ): + if ( + first_tree.prefix != tree.prefix + or first_tree.tensor_dim != tree.tensor_dim + or first_tree.is_reduction != tree.is_reduction + ): + return None + + first_names = cls._range_tree_names(first) + names = cls._range_tree_names(sub_kernel) + if len(first_names) != len(names): + return None + return { + name: first_name + for first_name, name in zip(first_names, names, strict=True) + if name != first_name + } + + @classmethod + def _body_name_replacements( + cls, + first: TritonKernel, + sub_kernel: TritonKernel, + args: list[str], + ) -> dict[str, str] | None: + first_cse_names = { + canonical: name for name, canonical in first._op_trace_cse_names.items() + } + replacements: dict[str, str] = {} + for name, canonical in sub_kernel._op_trace_cse_names.items(): + first_name = first_cse_names.get(canonical) + if first_name is None: + return None + if name != first_name: + replacements[name] = first_name + + range_replacements = cls._range_tree_name_replacements(first, sub_kernel) + if range_replacements is None: + return None + replacements.update(range_replacements) + + for i, arg in enumerate(args): + replacements[arg] = f"foreach_arg{i}" + return replacements + + @staticmethod + def _compatible_shared_arg_properties( + args_by_subkernel: list[list[str]], + tensor_args: dict[str, TensorArg], + ) -> bool: + if not args_by_subkernel: + return False + num_args = len(args_by_subkernel[0]) + if num_args == 0: + return False + if any(len(args) != num_args for args in args_by_subkernel): + return False + if any(arg not in tensor_args for args in args_by_subkernel for arg in args): + return False + + for arg_index in range(num_args): + properties = OrderedSet( + [ + ( + tensor_args[args[arg_index]].dtype, + is_unaligned_buffer(tensor_args[args[arg_index]]), + ) + for args in args_by_subkernel + ] + ) + if len(properties) != 1: + return False + + return True + + @classmethod + def _setup_lhs_names(cls, sub_kernel_codes: list[SubKernelCode]) -> list[str]: + names: list[str] = [] + seen: OrderedSet[str] = OrderedSet() + for sub_kernel_code in sub_kernel_codes: + for name in sub_kernel_code.setup_lhs_names: + if name not in seen: + seen.add(name) + names.append(name) + return names + + def _try_get_shared_body( + self, + sub_kernel_codes: list[SubKernelCode], + signature: list[Any], + heuristics_list: list[str], + ) -> SharedBody | None: + if not self._can_share_body(heuristics_list): + return None + + tensor_args = {arg.name: arg for arg in signature if isinstance(arg, TensorArg)} + if not tensor_args: + return None + first_sub_kernel = self.sub_kernels[0] + first_trace = first_sub_kernel.op_trace + if not first_trace: + return None + if any( + sub_kernel.op_trace != first_trace for sub_kernel in self.sub_kernels[1:] + ): + return None + + transformed_bodies: list[list[str]] = [] + args_by_subkernel: list[list[str]] = [] + + for sub_kernel, sub_kernel_code in zip( + self.sub_kernels, sub_kernel_codes, strict=True + ): + lines = self._plain_lines(sub_kernel_code.body) + if lines is None: + return None + body_names = self._names_in_lines(lines) + if body_names is None: + return None + if any( + arg in body_names and arg not in tensor_args + for arg in sub_kernel.op_trace_buffer_arg_names + ): + return None + args = [ + arg + for arg in sub_kernel.op_trace_buffer_arg_names + if arg in tensor_args and arg in body_names + ] + # Every live tensor pointer in the emitted body must come from the + # structured trace so placeholder substitution cannot miss it. + if any(arg in body_names and arg not in args for arg in tensor_args): + return None + args_by_subkernel.append(args) + + replacements = self._body_name_replacements( + first_sub_kernel, sub_kernel, args + ) + if replacements is None: + return None + transformed = self._replace_names(lines, replacements) + if transformed is None: + return None + + transformed_bodies.append(transformed) + + if any(body != transformed_bodies[0] for body in transformed_bodies[1:]): + return None + if not self._compatible_shared_arg_properties(args_by_subkernel, tensor_args): + return None + + setup_lhs_names = self._setup_lhs_names(sub_kernel_codes) + + body = IndentedBuffer() + body.writelines(transformed_bodies[0]) + return SharedBody( + body=body, + placeholder_names=[ + f"foreach_arg{i}" for i in range(len(args_by_subkernel[0])) + ], + args_by_subkernel=args_by_subkernel, + setup_lhs_names=setup_lhs_names, + ) + + def _codegen_sub_kernel_bodies( + self, + ) -> list[SubKernelCode]: + sub_kernel_codes: list[SubKernelCode] = [] + for num, sub_kernel in enumerate(self.sub_kernels): + setup = IndentedBuffer() + sub_kernel_setup = self.codegen_static_numels_sub_kernel( + setup, sub_kernel, num + ) + sub_kernel.codegen_prologue(sub_kernel.body) + sub_kernel.codegen_body() + sub_kernel._filter_pdl(sub_kernel.body) + uniquify = ( + [] + if self.per_subkernel_blocks + else sub_kernel_setup.uniquify_block_sizes + ) + body = self.uniquify_block_sizes(sub_kernel.body, num, uniquify) + sub_kernel_codes.append( + SubKernelCode( + setup=setup, + body=body, + setup_lhs_names=sub_kernel_setup.lhs_names, + ) + ) + return sub_kernel_codes + + def _codegen_branch( + self, + code: IndentedBuffer, + num: int, + sub_kernel_code: SubKernelCode, + ) -> None: + if self.dispatch_class is None: + raise AssertionError("dispatch_class must not be None") + self.dispatch_class.codegen_pid_range(self, num, code) + with code.indent(): + code.splice(sub_kernel_code.setup) + code.splice(sub_kernel_code.body) + + def _codegen_noinline_sub_kernels( + self, + code: IndentedBuffer, + kernel_name: str, + sub_kernel_codes: list[SubKernelCode], + ) -> list[str]: + """Emit each sub-kernel body as a @triton.jit(noinline=True) device + function and return the per-branch call lines.""" + call_lines: list[str] = [] + defs = IndentedBuffer() + emitted: dict[tuple[Any, ...], str] = {} + for num, sub_kernel_code in enumerate(sub_kernel_codes): + noinline_call = self.noinline_sub_kernel_calls[num] + params = noinline_call.params + call_args = noinline_call.call_args + key = ( + sub_kernel_code.setup.getvalue(), + sub_kernel_code.body.getvalue(), + noinline_call.signature_key, + ) + + sub_name = emitted.get(key) + if sub_name is None: + sub_name = f"{kernel_name}_body_{len(emitted)}" + emitted[key] = sub_name + defs.writeline("") + defs.writeline("@triton.jit(noinline=True)") + defs.writeline( + f"def {sub_name}({', '.join(p.full_name() for p in params)}):" + ) + with defs.indent(): + defs.splice(sub_kernel_code.setup) + defs.splice(sub_kernel_code.body) + call_lines.append(f"{sub_name}({', '.join(call_args)})") + defs.writeline("") + code.splice(defs) + return call_lines + + def _codegen_shared_branches( + self, + code: IndentedBuffer, + sub_kernel_codes: list[SubKernelCode], + shared_body: SharedBody, + ) -> None: + if self.dispatch_class is None: + raise AssertionError("dispatch_class must not be None") + for num, sub_kernel_code in enumerate(sub_kernel_codes): + self.dispatch_class.codegen_pid_range(self, num, code) + with code.indent(): + code.splice(sub_kernel_code.setup) + for placeholder, arg in zip( + shared_body.placeholder_names, + shared_body.args_by_subkernel[num], + strict=True, + ): + code.writeline(f"{placeholder} = {arg}") + + code.splice("else:") + with code.indent(): + code.splice("pid_offset = 0") + for name in shared_body.setup_lhs_names: + code.writeline(f"{name} = 0") + for placeholder, arg in zip( + shared_body.placeholder_names, + shared_body.args_by_subkernel[0], + strict=True, + ): + code.writeline(f"{placeholder} = {arg}") + + code.splice(shared_body.body) + + def codegen_kernel(self, name: str | None = None) -> str: + """Generate the triton code for a combo kernel that fuses multiple sub-kernels.""" + # TODO: is it correct to use the first sub kernel's heuristics? + heuristics_list, size_hints_list = [], [] + for subkernel in self.sub_kernels: + h, s = self.select_heuristics(subkernel) + heuristics_list.append(h) + size_hints_list.append(s) + heuristics, size_hints, selected_kernel = self.select_combo_heuristics( + heuristics_list, size_hints_list + ) + pointwise_with_reduction, heuristics = ( + (True, "pointwise") + if heuristics == "pointwise_with_reduction" + else (False, heuristics) + ) + code = IndentedBuffer() + + code.splice(self.triton_kernel_cls.gen_common_triton_imports()) + if config.benchmark_combo_kernel: + code.splice(self.imports_for_benchmark_kernel()) + + seen_helpers: OrderedSet[str] = OrderedSet() + for sub_kernel in self.sub_kernels: + for helper in sub_kernel.helper_functions: + if helper not in seen_helpers: + code.writeline("") + code.splice(helper) + seen_helpers.add(helper) + + if self.per_subkernel_blocks: + self._merge_noinline_kernel_args() + + argdefs, _, signature, _ = self.args.python_argdefs() + argdefs = self.add_numel_to_args(argdefs, signature) + if self.per_subkernel_blocks: + main_arg_names = OrderedSet(arg.name for arg in argdefs) + mapped_arg_names = OrderedSet( + name + for name_map in self.noinline_arg_name_maps + for name in name_map.values() + ) + missing_arg_names = mapped_arg_names - main_arg_names + if missing_arg_names: + raise AssertionError( + "combo noinline call arguments missing from main signature: " + f"{sorted(missing_arg_names)}" + ) + block_args = self.get_block_args() + if not self.bake_blocks or self.per_subkernel_blocks: + argdefs.extend([ArgName(x.name, is_constexpr=True) for x in block_args]) + if triton_version_uses_attrs_dict(): + signature.extend(block_args) + if self.per_subkernel_blocks: + self._prepare_noinline_sub_kernel_calls() + + kernel_name = name or str(Placeholder.KERNEL_NAME) + + sub_kernel_codes = self._codegen_sub_kernel_bodies() + # Sub-functions must be emitted before the main kernel's heuristics + # decorator line (triton reads the decorated function's source by + # inspection). PDL intrinsics move with each body and proton scopes + # wrap the main kernel around the calls, so neither needs the inline + # form. + noinline_calls: list[str] | None = None + if self.per_subkernel_blocks: + noinline_calls = self._codegen_noinline_sub_kernels( + code, kernel_name, sub_kernel_codes + ) + + code.splice( + self.jit_line( + heuristics, + size_hints, + selected_kernel, + pointwise_with_reduce=pointwise_with_reduction, + signature=signature, + argdefs=argdefs, + size_hints_list=size_hints_list, + ) + ) + code.writeline( + f"def {kernel_name}({', '.join(x.full_name() for x in argdefs)}):" + ) + + with code.indent(): + if config.triton.proton_profiling: + code.writeline(f'pl.enter_scope("{kernel_name}")') + code.splice("pid = tl.program_id(0)") + if self.bake_blocks and not self.per_subkernel_blocks: + self.codegen_blocks(code) + + shared_body = self._try_get_shared_body( + sub_kernel_codes, signature, heuristics_list + ) + if shared_body is not None: + self._codegen_shared_branches(code, sub_kernel_codes, shared_body) + elif noinline_calls is not None: + if self.dispatch_class is None: + raise AssertionError("dispatch_class must not be None") + for num, call_line in enumerate(noinline_calls): + self.dispatch_class.codegen_pid_range(self, num, code) + with code.indent(): + code.writeline(call_line) + code.splice("else:") + with code.indent(): + code.splice("pass") + else: + for num, sub_kernel_code in enumerate(sub_kernel_codes): + self._codegen_branch(code, num, sub_kernel_code) + + code.splice("else:") + with code.indent(): + code.splice("pass") + if config.triton.proton_profiling: + code.writeline(f'pl.exit_scope("{kernel_name}")') + + if config.benchmark_combo_kernel: + code.splice(self.codegen_kernel_benchmark(num_gb=self._kernel_num_gb)) + + return code.getvalue() + + def codegen_kernel_benchmark(self, num_gb: float) -> IndentedBuffer: + """ + Generates Python code for benchmarking this combo kernel. + - Creates example inputs (random tensors, constants, sizes). + - Runs the kernel on the current GPU/stream. + - Prints runtime (ms) and throughput (GB/s) using `num_gb`. + Args: + num_gb (float): The number of gigabytes to use for throughput calculation. + Returns: + IndentedBuffer: A buffer containing the generated Python benchmark code. + """ + result = IndentedBuffer() + _argdefs, call_args, signature, _ = self.args.python_argdefs() + result.writelines(["", "", "def get_args():"]) + with result.indent(): + name_cnt = itertools.count() + var_names = [] + for arg_name, arg_sig in zip(call_args, signature): + var_name = f"arg_{next(name_cnt)}" + buf = V.graph.try_get_buffer(arg_name) + if buf: + size = V.graph.sizevars.optimization_hints(buf.get_size()) + stride = V.graph.sizevars.optimization_hints(buf.get_stride()) + result.writeline( + f"{var_name} = rand_strided({size}, {stride}, device='{coor_device_str(buf.get_device())}', dtype={buf.get_dtype()})" + ) + elif arg_name in V.graph.constants: + # note that random seed is put in V.graph.constants + const_tensor = V.graph.constants[arg_name] + size = V.graph.sizevars.optimization_hints(const_tensor.size()) + stride = V.graph.sizevars.optimization_hints(const_tensor.stride()) + result.writeline( + f"{var_name} = rand_strided({size}, {stride}, device='{coor_device_str(const_tensor.device)}', dtype={const_tensor.dtype})" # type: ignore[arg-type] + ) + elif isinstance(arg_sig, SizeArg): + symval_hint = V.graph.sizevars.optimization_hint(arg_sig.expr) + + # Force the seed_offset to be 0 so calls to the same kernel + # using different seed offset will have the same benchmark harness. + # We can dedup kernel definitions in this case. + if "seed_offset" in arg_sig.name: + symval_hint = 0 + result.writeline(f"{var_name} = {symval_hint}") + elif isinstance(arg_sig, WorkspaceArg): + device = V.graph.get_current_device_or_throw() + count = V.graph.sizevars.optimization_hint(arg_sig.count) + # for benchmark harness, we ignore arg_sig.zero_mode and always zero it + result.writeline( + f"{var_name} = torch.zeros({count}, device='{coor_device_str(device)}', dtype={arg_sig.dtype})" + ) + else: + raise KeyError( + f"Don't find the buffer or const tensor for {arg_name}" + ) + var_names.append(var_name) + if self.dynamic_shape_args: + var_names.extend(self.kernel_benchmark_extra_args()) + result.writeline(f"return {', '.join(var_names)},") + + result.writelines(["\n", "\n", "def call(args):"]) + device = V.graph.get_current_device_or_throw() + coor_preamble, index = coor_benchmark_device_idx(device.index) + with result.indent(): + if coor_preamble: + result.writeline(coor_preamble) + result.writeline(f"with {V.graph.device_ops.device_guard(index)}:") + with result.indent(): + result.writeline( + V.graph.device_ops.set_device(index) + ) # no-op to ensure context + stream_name = get_raw_stream_name(device.index) + result.writeline(f"{stream_name} = get_raw_stream({index})") + result.writeline( + f"{str(Placeholder.KERNEL_NAME)}.run(*args, stream={stream_name})" + ) + + # benchmark all configs + result.writelines(["\n", "\n", "def benchmark_all_configs(args):"]) + with result.indent(): + if coor_preamble: + result.writeline(coor_preamble) + result.writeline(f"with {V.graph.device_ops.device_guard(index)}:") + with result.indent(): + result.writeline( + V.graph.device_ops.set_device(index) + ) # no-op to ensure context + result.writeline( + f"return {str(Placeholder.KERNEL_NAME)}.benchmark_all_configs(*args)" + ) + + result.writelines(["\n", "\n", "if __name__ == '__main__':"]) + with result.indent(): + result.writeline( + "from torch._inductor.runtime.benchmarking import benchmarker" + ) + result.writeline("") + + result.writeline("args = get_args()") + result.writeline( + f"ms = benchmarker.benchmark(call, fn_args=(args,), device='{device.type}',rep=40)" + ) + result.writeline(f"num_gb = {num_gb}") + result.writeline("gb_per_s = num_gb / (ms / 1e3)") + result.writeline( + 'print(f"{ms:.3f}ms {num_gb:.3f}GB {gb_per_s:.2f}GB/s")' + ) + + return result + + def imports_for_benchmark_kernel(self) -> str: + # Dedent BEFORE substituting get_raw_stream: a multi-line override would + # otherwise collapse dedent's common prefix and misindent the imports. + return textwrap.dedent( + """ + from torch._dynamo.testing import rand_strided + {} + import torch + """ + ).format(V.graph.device_ops.import_get_raw_stream_as("get_raw_stream")) + + def uniquify_block_sizes( + self, code: IndentedBuffer, num_kernel: int, uniquify: list[str] + ) -> IndentedBuffer: + if not uniquify: + return code + modified = IndentedBuffer(initial_indent=code._indent) + for line in code._lines: + if isinstance(line, str) and (blocks := [e for e in uniquify if e in line]): + modified_line = line + for block in blocks: + modified_line = modified_line.replace( + block, f"{block}_{num_kernel}" + ) + modified.writeline(modified_line) + elif isinstance(line, DeferredLineBase) and ( + blocks := [e for e in uniquify if e in line.line] + ): + modified_line = line.line + for block in blocks: + modified_line = modified_line.replace( + block, f"{block}_{num_kernel}" + ) + new_line = line._new_line(modified_line) + modified.writeline(new_line) + else: + modified.writeline(line) + return modified + + def call_kernel(self, name: str) -> None: + _, call_args, _, arg_types = self.args.python_argdefs() + + wrapper = V.graph.wrapper_code + if self.dispatch_class is None: + raise AssertionError("dispatch_class must not be None") + if self.dynamic_shape_args: + self.add_numel_to_call_args(name, call_args, arg_types) + + wrapper.generate_kernel_call( + name, + call_args, + triton=True, + arg_types=arg_types, + triton_meta=self.triton_meta, + inductor_meta=self.inductor_meta, + ) + + def combo_grid_meta(self, size_hints_list: list[dict[str, int]]) -> dict[str, Any]: + """ + Build metadata used by combo-kernel grid/dispatch/autotune helpers. + """ + dynamic_shape = bool(self.dynamic_shape_args) + num_kernels = len(self.sub_kernels) + min_blocks = ( + max(self.min_x_blocks_list) * num_kernels if not dynamic_shape else None + ) + + meta: dict[str, Any] = { + "num_kernels": num_kernels, + "min_blocks": min_blocks, + # Captured at codegen time so runtime sees the same value the + # source was generated with, regardless of later config changes. + "autotune_grouping": config.combo_kernel_autotune_grouping, + "block_arg_names": tuple(self.block_args), + } + + if self.bake_blocks or self.combo_compile_time_autotune: + default_config: dict[str, int] = {} + if self.combo_compile_time_autotune: + # Compile-time autotune: per-subkernel winning block sizes are passed as args; + # num_warps / num_stages / backend kwargs are autotuned over the distinct winner + # launch candidates (flattened to tuples so the meta stays repr-serializable). + if not self.combo_launch_candidates: + raise AssertionError( + "compile-time autotune requires at least one launch candidate" + ) + if self.stitched_block_config is not None: + default_config = dict(self.stitched_block_config) + meta["stitched_launch_candidates"] = [ + (c.kwargs, c.num_warps, c.num_stages) + for c in self.combo_launch_candidates + ] + elif self.no_bench_stitched_config is not None: + stitched = self.no_bench_stitched_config + default_config = { + k: int(v) for k, v in stitched.kwargs.items() if "BLOCK" in k + } + meta["stitched_backend_kwargs"] = { + k: v for k, v in stitched.kwargs.items() if "BLOCK" not in k + } + meta["stitched_num_warps"] = stitched.num_warps + meta["stitched_num_stages"] = stitched.num_stages + elif self.per_subkernel_blocks: + # Per-subkernel block sizes: XBLOCK_0, XBLOCK_1, etc. + for num, sub_kernel in enumerate(self.sub_kernels): + if sub_kernel.no_x_dim: + default_config[f"XBLOCK_{num}"] = 1 + else: + block_size = ( + self.block_size_2d + if any(self.y_tree_list) + else self.block_size_1d + ) + default_config[f"XBLOCK_{num}"] = block_size + + if self.y_tree_list[num]: + default_config[f"YBLOCK_{num}"] = self.block_size_2d + else: + if "YBLOCK" in self.block_args: + default_config = { + "XBLOCK": self.block_size_2d, + "YBLOCK": self.block_size_2d, + } + else: + default_config = {"XBLOCK": self.block_size_1d} + meta["default_config"] = default_config + else: + meta["default_config"] = None + + for num, sub_kernel in enumerate(self.sub_kernels): + meta[f"no_x_dim_{num}"] = sub_kernel.no_x_dim + + if self.per_subkernel_blocks: + meta[f"heuristic_{num}"] = ( + "persistent_reduction" + if sub_kernel.persistent_reduction + else "reduction" + if sub_kernel.inside_reduction + else "pointwise" + ) + + meta[f"size_hints_{num}"] = size_hints_list[num] + meta[f"inductor_meta_{num}"] = sub_kernel.inductor_meta_per_kernel() + if meta[f"heuristic_{num}"] == "pointwise": + if len(size_hints_list[num]) == 2: + meta[f"tile_hint_{num}"] = "TileHint.SQUARE" + else: + meta[f"tile_hint_{num}"] = "TileHint.DEFAULT" + else: + meta[f"reduction_hint_{num}"] = ( + sub_kernel.features.get_reduction_hint( + sub_kernel.tiling_scores + ).name + ) + + for tree in sub_kernel.range_trees: + if not tree.is_reduction: + numel_name = f"{tree.prefix}numel_{num}" + if numel_name in self.dynamic_shape_args: + meta[numel_name] = None + else: + meta[numel_name] = int(V.graph.sizevars.simplify(tree.numel)) + + return meta diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_split_scan.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_split_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..87f0c5e01e849ed0896f6f6e01dc243e2a93af82 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_split_scan.py @@ -0,0 +1,228 @@ +# mypy: allow-untyped-defs +import functools + +import sympy + +from torch._inductor import config +from torch._inductor.codegen.simd import IterationRangesRoot, prefix_is_reduction +from torch._inductor.codegen.triton import ( + triton_compute_type, + TritonCSEVariable, + TritonKernel, +) +from torch._inductor.runtime.triton_heuristics import SplitScanGrid +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import CeilDiv + +from ..utils import sympy_product, upcast_compute_type + + +class TritonSplitScanKernel(TritonKernel): + """Generates a triton kernel that supports ops.scan calls while also splitting + the reduction dimension over multiple triton programs. + + For this kernel, loop numels will always take the form ``(xdim, rdim)`` + and the grid has the shape ``(CeilDiv(rdim, RBLOCK), xdim)``. Communication + between blocks occurs within a global memory workspace buffer, which + must be zero-filled before launching the kernel. + + Note that generation for ``ops.reduction`` is not supported. + + For details of the communication strategy, see + https://research.nvidia.com/publication/2016-03_single-pass-parallel-prefix-scan-decoupled-look-back + + """ + + def __init__( + self, + tiling: dict[str, sympy.Expr], + pid_cache=None, + fixed_config=None, + **kwargs, + ) -> None: + if pid_cache is not None: + raise AssertionError("not supported") + if fixed_config is not None: + raise AssertionError("not supported") + super().__init__( + tiling, + **kwargs, + ) + self.no_x_dim = True + + def should_use_persistent_reduction(self) -> bool: + return False + + def should_use_cooperative_reduction(self) -> bool: + return False + + def initialize_range_tree(self, pid_cache): + prefixes = ["y", "x", "r0_"] + if len(self.numels) > len(prefixes): + raise AssertionError("z dimension not supported for split scan") + active_prefixes = prefixes[len(prefixes) - len(self.numels) :] + + grid_dims = {"r0_": 0, "x": 1, "y": 2} + for prefix in active_prefixes: + numel = self.numels[prefix] + tensor_dim = 0 if prefix_is_reduction(prefix) else None + grid_dim = grid_dims[prefix] + self.range_trees.append( + IterationRangesRoot( + f"{prefix}index", + numel, + prefix, + grid_dim, + self, # type: ignore[arg-type] + pid_cache=pid_cache, + is_loop=False, + tensor_dim=tensor_dim, + grid_dim=grid_dim, + has_zdim=False, + ) + ) + + def reduction(self, dtype, src_dtype, reduction_type, value): + raise NotImplementedError("NYI TritonSplitDimKernel reductions") + + def scan(self, dtypes, combine_fn, values): + """ + Perform an associative scan on 'values'. + """ + import triton.language as tl + + (dtype,) = dtypes + (value,) = values + + dtype = upcast_compute_type(dtype) + compute_type = triton_compute_type(dtype) + compute_type_triton = getattr(tl, compute_type[3:]) + + element_nbits = compute_type_triton.primitive_bitwidth + + scratch_type = "tl.uint32" if element_nbits <= 16 else "tl.uint64" + scratch_type_triton = getattr(tl, scratch_type[3:]) + scratch_elems_per_block = 3 if element_nbits == 64 else 1 + scratch_nbytes_per_block = scratch_elems_per_block * ( + scratch_type_triton.primitive_bitwidth // 8 + ) + + cse_compute = functools.partial(self.cse.generate, self.compute) + + if len(self.numels) != 2: + raise AssertionError("Unexpected tiling") + min_rblock = config.triton.min_split_scan_rblock + reduction_numel = sympy_product( + numel + for prefix, numel in self.numels.items() + if prefix_is_reduction(prefix) + ) + pointwise_numel = sympy_product( + numel + for prefix, numel in self.numels.items() + if not prefix_is_reduction(prefix) + ) + max_blocks = pointwise_numel * CeilDiv(reduction_numel, min_rblock) + nbytes = scratch_nbytes_per_block * max_blocks + scratch_base: str | TritonCSEVariable + scratch_base, _, offset = self.args.workspace(nelem=nbytes, zero_fill=True) + if offset != 0: + scratch_base = f"({scratch_base} + {self.index_to_str(offset)})" + runtime_rblocks = f"tl.num_programs({self.range_trees[-1].index})" + scratch_base = ( + f"{scratch_base}.to(tl.pointer_type({scratch_type})) + xoffset * " + f"{scratch_elems_per_block} * {runtime_rblocks}" + ) + + masks = OrderedSet(f"{tree.prefix}mask" for tree in self.range_trees) + self.filter_masks(masks) + if self._load_mask: + raise AssertionError("ops.scan not supported inside ops.masked") + + value = cse_compute( + f"{value}.to({compute_type})", + dtype=dtype, + shape=value.shape, + ) + value = cse_compute( + f"tl.broadcast_to({value}, {self.dense_size_str()})", + dtype=dtype, + shape=self.dense_size_list(), + ) + + combine_helper_fn = self._lift_helper(combine_fn, (value,), (dtype,)) + dim = self.triton_tensor_ndim() - 1 + if dim != 0: + raise AssertionError(f"expected scan dim == 0, got {dim}") + scan_shape = value.shape + if scan_shape is None: + raise AssertionError("expected value.shape to be set") + reduced_shape = list(scan_shape) + del reduced_shape[dim] + + block_sum = cse_compute( + f"tl.reduce({value}, {dim}, {combine_helper_fn})", + dtype=dtype, + shape=reduced_shape, + ) + exclusive_prefix = self.cse.newvar( + dtype=dtype, + shape=reduced_shape, + ) + if element_nbits == 64: + self.compute.splice( + f""" + {exclusive_prefix} = triton_helpers.exclusive_scan_decoupled_lookback_64( + {scratch_base}, + {block_sum}, + {self.iteration_ranges_get_pid(self.range_trees[-1])}, + {combine_helper_fn}, + ) + """, + strip=True, + ) + + else: + if element_nbits > 32: + raise AssertionError( + f"expected element_nbits <= 32, got {element_nbits}" + ) + value_as_uint_dtype = f"tl.uint{element_nbits}" + + self.compute.splice( + f""" + {exclusive_prefix} = triton_helpers.exclusive_scan_decoupled_lookback( + {scratch_base}, + {block_sum}, + {self.iteration_ranges_get_pid(self.range_trees[-1])}, + {combine_helper_fn}, + DTYPE_VALUE_AS_UINT={value_as_uint_dtype}, + DTYPE_PACK={scratch_type}, + ) + """, + strip=True, + ) + # Compute final cumsum + block_scan = cse_compute( + f"tl.associative_scan({value}, {dim}, {combine_helper_fn})", + dtype=dtype, + shape=scan_shape, + ) + combined_result = cse_compute( + f"{combine_helper_fn}({exclusive_prefix}, {block_scan})", + dtype=dtype, + shape=scan_shape, + ) + return ( + cse_compute( + f"tl.where(roffset == 0, {block_scan}, {combined_result})", + dtype=dtype, + shape=scan_shape, + ), + ) + + def _get_heuristic(self): + return "split_scan" + + def _get_grid_type(self) -> type[SplitScanGrid]: + return SplitScanGrid diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..05854448207c9889389c1f82939f8922f940ba1c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_utils.py @@ -0,0 +1,387 @@ +# mypy: allow-untyped-defs +from typing import Any + +import sympy + +import torch +from torch.utils._sympy.symbol import symbol_is_type, SymT + +from .. import config +from ..runtime.hints import AttrsDescriptorWrapper, DeviceProperties +from ..utils import ( + _type_of, + device_supports_fp64, + expr_fits_within_32bit, + triton_version_uses_attrs_dict, +) +from ..virtualized import V +from .common import ( + ArgName, + ConstexprArg, + KernelArgType, + SizeArg, + TensorArg, + TMADescriptorArg, + WorkspaceArg, +) + + +def should_unwrap_unspec_arg(name: str): + if V.graph.is_unspec_arg(name): + # Unwrap on all devices except CPU + if V.graph.get_current_device_or_throw().type != "cpu": + return True + # Only unwrap on CPU if the input is not used as an output + if name not in V.graph.mutated_buffers: + return True + return False + + +def use_uint8_triton_storage_for_cuda_float8_e4m3fn( + dtype: torch.dtype, + arg_name: str | None = None, + *, + device: torch.device | None = None, +) -> bool: + # Triton rejects fp8e4nv pointer types before sm89, but eager CUDA can + # still dequantize float8_e4m3fn values by treating storage as raw bytes. + if dtype != torch.float8_e4m3fn or torch.version.hip is not None: + return False + if arg_name is not None and not arg_name.startswith("in_ptr"): + return False + + if device is None: + try: + device = V.graph.get_current_device_or_throw() + except AttributeError: + return False + + if device.type != "cuda": + return False + + return DeviceProperties.create(device).cc < 89 + + +def signature_of(arg: KernelArgType, *, size_dtype: str | None) -> str: + if isinstance(arg, TensorArg): + typ = _type_of(arg.dtype) + if should_unwrap_unspec_arg(arg.buffer): + # had unwrapped 0d tensor as scalar + new_typ = typ.lstrip("*") + if new_typ in ["fp16", "bf16"]: + return "fp32" + else: + return new_typ + elif use_uint8_triton_storage_for_cuda_float8_e4m3fn(arg.dtype, arg.name): + return "*u8" + else: + return typ + if isinstance(arg, SizeArg): + if arg.expr is None: + if triton_version_uses_attrs_dict(): + # In newer versions of Triton, the signature includes "None" args + # and their type is marked as "constexpr" + return "constexpr" + else: + # In older versions of Triton... + # From triton/runtime/jit.py + # `None` is nullptr. Implicitly convert to *i8. + return "*i8" + elif _arg_equals_1(arg) and triton_version_uses_attrs_dict(): + # In new versions of Triton, if we have an equal-to-1 arg that's marked as a constant, + # it should be marked as "constexpr" in the signature. + return "constexpr" + elif isinstance(arg.expr, (float, sympy.Float)): + # Python floats are natively fp64, so use fp64 to preserve precision + if config._use_fp64_for_unbacked_floats and device_supports_fp64( + V.graph.current_device + ): + return "fp64" + return "fp32" + elif isinstance(arg.expr, sympy.Symbol) and symbol_is_type( + arg.expr, (SymT.UNBACKED_FLOAT) + ): + # Unbacked floats from .item() should preserve fp64 precision + if config._use_fp64_for_unbacked_floats and device_supports_fp64( + V.graph.current_device + ): + return "fp64" + return "fp32" + elif isinstance(arg.expr, bool): + return "i1" + + # if this is an integer + if size_dtype == "tl.int32": + return "i32" + elif size_dtype == "tl.int64": + return "i64" + elif size_dtype is None: + # no hint: we'll see if we know that this is a 32-bit int, and guard if possible. + int_max = torch.iinfo(torch.int32).max + if expr_fits_within_32bit(arg.expr): + V.graph.sizevars.check_leq(arg.expr, int_max) + return "i32" + else: + return "i64" + else: + raise NotImplementedError(f"unhandled size_dtype {size_dtype}") + if isinstance(arg, WorkspaceArg): + return _type_of(arg.dtype) + if isinstance(arg, TMADescriptorArg): + if arg.api_type == "experimental": + return "nvTmaDesc" + else: + # https://github.com/triton-lang/triton/blob/9695baed9b46cf957e08b157bb4133f4a4b331c5/python/triton/runtime/jit.py#L360-L363 + if arg.api_type != "stable": + raise AssertionError( + f"expected api_type == 'stable', got {arg.api_type}" + ) + if arg.block_shape is None: + raise AssertionError("expected block_shape to not be None") + if arg.dtype is None: + raise AssertionError("expected dtype to not be None") + inner = _type_of(arg.dtype)[1:] # strip the `*`: *fp32 -> fp32 + return f"tensordesc<{inner}{list(arg.block_shape)}>" + if isinstance(arg, ConstexprArg): + return "constexpr" + raise NotImplementedError(f"unhandled {type(arg)}: {arg}") + + +def non_constexpr_signature(signature): + new_signature = [] + for arg in signature: + if not isinstance(arg, ConstexprArg): + new_signature.append(arg) + + return new_signature + + +def select_tile_hint(size_hints, signature): + """Pick TileHint.SQUARE vs TileHint.DEFAULT for 2D pointwise; None for 1D. + + SQUARE applies when the kernel has exactly 2 size hints and 4 non-constexpr + signature args (input, output, and 2 numel args -> a square 2D tile). + """ + from torch._inductor.runtime.hints import TileHint + + if len(size_hints) != 2: + return None + if len(non_constexpr_signature(signature)) == 4: + return TileHint.SQUARE + return TileHint.DEFAULT + + +def signature_to_meta( + signature: list[KernelArgType], + *, + size_dtype: str | None, + argdefs: list[ArgName], + indices: list[int] | None = None, + is_template: bool = False, +) -> dict[str, str]: + if indices is None: + indices = list(range(len(signature))) + + def _decide_tl_dtype(arg): + # Even if the ks0 symbol itself is within tl.int32 range, it's + # risky to use tl.int32 dtype since we may have ks0*ks1 later + # for kernels like torch.mean when dynamic shape is enabled. + # + # Check config.triton.use_block_ptr, since Triton block pointer + # does not support 64bit indexing: + # https://gist.github.com/shunting314/6a41c776171720ce4561f202dcde0ad6 + # + # If the triton metadata is for a template, don't use tl.int64 index. + # Templates like flex attention/decoding uses block pointers which + # does not support 64 bit indexing. + if ( + not config.triton.use_block_ptr + and not is_template + and isinstance(arg, SizeArg) + and arg.name.startswith("ks") + ): + return "tl.int64" + return size_dtype + + return { + argdefs[i].name: signature_of(arg, size_dtype=_decide_tl_dtype(arg)) + for i, arg in zip(indices, signature) + } + + +def _get_buffer_layout(buf_name: str) -> "torch._inductor.ir.Layout": + """Get the layout for a buffer, handling both scheduler buffers and graph inputs.""" + if V.graph.scheduler: + layout = V.graph.scheduler.get_buffer_layout(buf_name) + else: + buffer = V.graph.try_get_buffer(buf_name) + # output arg + if not buffer: + if buf_name != V.kernel.output_node.name: + raise AssertionError( + f"expected buf_name == output_node.name, got {buf_name}" + ) + layout = V.kernel.output_node.layout + else: + layout = buffer.get_layout() + return layout + + +def is_unaligned_buffer_name(buf_name: str) -> bool: + if buf_name in V.graph.unaligned_buffers: + return True + + if buf_name in V.graph.graph_inputs: + # See Note: [Input Alignment handling in Inductor] + # For graph inputs that is not recorded in V.graph.unaligned_buffers, + # we know for sure the tensor is aligned. + return False + + if buf_name in V.graph.constants: + # all constants are assumed to be aligned + return False + + layout = _get_buffer_layout(buf_name) + if isinstance(layout, torch._inductor.ir.NonOwningLayout): + return not layout.maybe_guard_aligned() + else: + return False + + +def is_unaligned_buffer(arg: TensorArg): + return is_unaligned_buffer_name(arg.buffer) + + +def _arg_equals_1(arg: KernelArgType) -> bool: + return ( + isinstance(arg, SizeArg) + and isinstance(arg.expr, (int, sympy.Integer)) + and V.graph.sizevars.statically_known_equals(arg.expr, 1) # type: ignore[arg-type] + ) + + +def equal_1_arg_indices( + args: list[KernelArgType], + *, + indices: list[int] | None = None, +) -> tuple[int, ...]: + if indices is None: + indices = list(range(len(args))) + + equal_to_1 = tuple(i for i, arg in zip(indices, args) if _arg_equals_1(arg)) + + return equal_to_1 + + +def _is_tensor_within_2gb(arg: TensorArg) -> bool: + """Check if a tensor argument's storage is provably within 2GB. + + Mirrors HIPBackend.is_within_2gb() but uses compile-time symbolic analysis + instead of runtime tensor inspection. This enables canonicalize_pointers to + decompose pointer arithmetic into (splat(base), offset) form for buffer ops. + """ + MAX_BYTES = 2**31 - 1 + try: + # Graph inputs aren't tracked by the scheduler; get their layout + # from the graph_inputs dict to avoid KeyError in get_buffer_layout. + if arg.buffer in V.graph.graph_inputs: + inp = V.graph.graph_inputs[arg.buffer] + if hasattr(inp, "get_layout"): + layout = inp.get_layout() + else: + return False + else: + layout = _get_buffer_layout(arg.buffer) + storage_bytes = layout.storage_size() * arg.dtype.itemsize + return V.graph.sizevars.statically_known_true(storage_bytes <= MAX_BYTES) + except Exception: + return False + + +def config_of( + args: list[KernelArgType], + *, + indices: list[int] | None = None, + pointer_range_override: tuple[int, ...] | None = None, + skip_cpp_wrapper_input_tensor_alignment: bool = False, +) -> Any: + if indices is None: + indices = list(range(len(args))) + + def is_aligned(x: KernelArgType, alignment: int, include_tensor: bool) -> bool: + """ + Roughly follow triton code here: + https://github.com/triton-lang/triton/blob/5282ed890d453e10b9ee30076ef89115dd197761/python/triton/runtime/jit.py#L208-L222 + """ + if isinstance(x, TensorArg): + if include_tensor: + offset_aligned = V.graph.sizevars.statically_known_multiple_of( + x.offset * x.dtype.itemsize, + alignment, # type: ignore[arg-type] + ) + return offset_aligned and not is_unaligned_buffer(x) + else: + return False + if isinstance(x, SizeArg): + # TODO(voz): These are kinda redundant, if we can solve out statically_known_multiple_of with + # _maybe_evaluate_static... + if x.name.startswith("load_seed_offset"): + return False + if x.expr is None: + return False + if isinstance(x.expr, (float, bool)): + return False + return V.graph.sizevars.statically_known_multiple_of(x.expr, alignment) # type: ignore[arg-type] + if isinstance(x, WorkspaceArg): + # We allocate the workspace ourselves, so it is always aligned + return True + if isinstance(x, (TMADescriptorArg, ConstexprArg)): + return False + raise NotImplementedError(f"unhandled {type(x)}: {x}") + + def include_tensor_alignment(arg: KernelArgType) -> bool: + if ( + not skip_cpp_wrapper_input_tensor_alignment + or not V.graph.cpp_wrapper + or V.graph.aot_mode + or not isinstance(arg, TensorArg) + or arg.buffer not in V.graph.graph_inputs + ): + return True + + try: + input_idx = V.graph.graph_input_names.index(arg.buffer) + except ValueError: + return True + return input_idx not in (V.graph.inputs_to_check or ()) + + if config.triton.divisible_by_16: + divisible_by_16 = tuple( + i + for i, arg in zip(indices, args) + if is_aligned( + arg, + alignment=16, + include_tensor=include_tensor_alignment(arg), + ) + ) + else: + divisible_by_16 = () + + equal_to_1 = equal_1_arg_indices(args, indices=indices) + + # On AMD/HIP, tag tensor args whose storage fits in 2GB so Triton + # can use 32-bit pointer offsets and emit buffer load/store ops. + if pointer_range_override is not None: + pointer_range_32 = pointer_range_override + elif torch.version.hip is not None: + pointer_range_32 = tuple( + i + for i, arg in zip(indices, args) + if isinstance(arg, TensorArg) and _is_tensor_within_2gb(arg) + ) + else: + pointer_range_32 = () + + # pyrefly: ignore [bad-argument-count, bad-argument-type] + return AttrsDescriptorWrapper(divisible_by_16, equal_to_1, pointer_range_32) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/wrapper.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..19767a1478d695f72e25bbe04ce5473705ea028f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/wrapper.py @@ -0,0 +1,5267 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import collections +import contextlib +import dataclasses +import dis +import functools +import inspect +import logging +import operator +import os +import random +import re +import tempfile +from collections.abc import Callable +from enum import Enum +from itertools import chain, count +from typing import Any, Literal, Protocol, TYPE_CHECKING + +import sympy +from sympy import Expr + +import torch +import torch._ops +import torch.utils._pytree as pytree +from torch import dtype as torch_dtype +from torch._dynamo.utils import counters, dynamo_timed, get_debug_dir +from torch._inductor.codegen.debug_utils import DebugPrinterManager +from torch._inductor.codegen.multi_kernel import MultiKernelState +from torch._inductor.runtime.runtime_utils import cache_dir +from torch._library.opaque_object import get_opaque_obj_repr, is_opaque_constant_type +from torch._logging import trace_structured +from torch.fx.experimental.proxy_tensor import ( + _coor_check_current_accelerator, + _coor_current_accelerator, + _coor_enabled, +) +from torch.fx.experimental.symbolic_shapes import ( + CallMethodKey, + ConvertIntKey, + DivideByKey, + resolve_unbacked_bindings, + SymTypes, +) +from torch.fx.node import _get_qualified_name +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import CleanDiv, Max, Min +from torch.utils._sympy.singleton_int import SingletonInt +from torch.utils._sympy.symbol import symbol_is_type, SymT + +from .. import async_compile, config, debug as inductor_debug, ir +from ..codecache import output_code_log +from ..ir import IRNode, ReinterpretView +from ..runtime import triton_heuristics +from ..runtime.hints import DeviceProperties, TritonMeta +from ..stream_constants import DEFAULT_STREAM, DEFAULT_STREAM_IDX, STREAM_NAME_TEMPLATE +from ..stream_utils import ( + COOR_DEVICE_IDX_VAR, + coor_device_str, + get_raw_stream_name, + get_stream_name, +) +from ..utils import ( + cache_on_self, + DeferredLineBase, + DelayReplaceLine, + get_benchmark_name, + get_dtype_size, + IndentedBuffer, + is_codegen_graph_partition_subgraph, + is_using_cudagraph_partition, + LineContext, + make_codegen_buffer, + sympy_product, + sympy_str, + sympy_subs, + triton_version_uses_attrs_dict, +) +from ..virtualized import V +from .common import ( + ArgName, + CodeGen, + DeferredLine, + PythonPrinter, + WorkspaceArg, + WorkspaceZeroMode, +) +from .cpp_utils import cexpr +from .custom_extern_kernel_codegen import CUSTOM_EXTERN_KERNEL_CODEGEN +from .triton_utils import config_of, should_unwrap_unspec_arg, signature_to_meta + + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Sequence + + import triton + + from ..graph import GraphLowering + from ..ir import ExternKernel + from ..scheduler import BaseSchedulerNode + from .wrapper_fxir import FxConverter + + +log = logging.getLogger(__name__) + +pexpr = PythonPrinter().doprint + + +def _rewrite_symbol_solution_for_int_codegen(expr: sympy.Expr) -> sympy.Expr: + expr = sympy.together(sympy.sympify(expr)) + numerator, denominator = sympy.fraction(expr) + if denominator == 1: + return numerator + return CleanDiv(numerator, denominator) + + +def _sanitize_for_repr(obj: Any) -> Any: + """Convert Enum values to their underlying value for valid Python repr in code generation.""" + if isinstance(obj, dict): + return {_sanitize_for_repr(k): _sanitize_for_repr(v) for k, v in obj.items()} + if isinstance(obj, list): + return [_sanitize_for_repr(v) for v in obj] + # For namedtuples (have _fields), reconstruct to preserve the type + if isinstance(obj, tuple) and hasattr(obj, "_fields"): + return getattr(type(obj), "_make")( # noqa: B009 + _sanitize_for_repr(getattr(obj, field)) for field in obj._fields + ) + if isinstance(obj, tuple): + return tuple(_sanitize_for_repr(v) for v in obj) + if isinstance(obj, Enum): + return _sanitize_for_repr(obj.value) + return obj + + +ReuseKey = tuple[torch.device, torch.dtype, str, bool, int, tuple[int, int] | None] +CommBufferReuseKey = tuple[torch.device, torch.dtype, str, "ir.CommBufferType", str] +BufferLike = ir.Buffer | WorkspaceArg +FxConversionFunc = Callable[["WrapperLine"], None] + + +@dataclasses.dataclass +class BenchmarkStorageGroup: + buffer_name: str + nbytes: int + device: Any + dtype: Any + inputs: dict[str, tuple[list[int], list[int]]] + + +def buffer_reuse_key(node: BufferLike) -> ReuseKey: + storage_size = V.graph.get_allocation_storage_size(node) + alignment = node.get_name() not in V.graph.unaligned_buffers + stream = V.graph.scheduler.get_buf_stream(node.get_name()) + mempool = V.graph.scheduler.get_buf_mempool(node.get_name()) + return ( + node.get_device_or_error(), + node.get_dtype(), + # NB: this is symbolic so that we don't try to reuse a buffer + # for s0 for s1, just because they happen to share the same + # size hint + sympy_str(V.graph.sizevars.simplify(storage_size)), + alignment, + stream, + mempool, + ) + + +def comm_buffer_reuse_key(node: BufferLike) -> CommBufferReuseKey: + # Comm buffers can only be reused by other comm buffers with the same (device, dtype, size, comm_buffer_type, group_name). + storage_size = V.graph.get_allocation_storage_size(node) + layout = node.get_output_spec() + if not isinstance(layout, ir.CommBufferLayout): + raise AssertionError(f"expected CommBufferLayout, got {type(layout)}") + return ( + node.get_device_or_error(), + node.get_dtype(), + sympy_str(V.graph.sizevars.simplify(storage_size)), + layout.comm_buffer_type, + layout.group_name, + ) + + +def can_match_buffer_size(input_buf: BufferLike, output_buf: BufferLike): + # Return True if input_buf can be re-inplaced for output_buf. + # This differs from `buffer_reuse_key` for general buffer reuse. + if input_buf.get_device_or_error() != output_buf.get_device_or_error(): + return False + + if input_buf.get_dtype() != output_buf.get_dtype(): + return False + + input_size = V.graph.sizevars.simplify( + V.graph.get_allocation_storage_size(input_buf) + ) + output_size = V.graph.sizevars.simplify( + V.graph.get_allocation_storage_size(output_buf) + ) + + if ( + # NB: this is symbolic so that we don't try to reuse a buffer + # for s0 for s1, just because they happen to share the same + # size hint + sympy_str(input_size) == sympy_str(output_size) + ) or ( + # statically known that 0.95 * input_size <= output_size <= input_size + V.graph.sizevars.statically_known_geq(output_size, 0.95 * input_size) + and V.graph.sizevars.statically_known_leq(output_size, input_size) + ): + return True + + return False + + +def codegen_reinterpret_view_helper(data): + """ + Collapse a chain of ReinterpretView <- StorageBox + <- ReinterpretView <- StorageBox.... <- buffer wrappers if every layer + has the same offset as the innermost (base) buffer. + + Returns: + (size, stride, offset, dtype, collapsible: bool) + """ + if isinstance(data, ir.Buffer): + lay = data.get_layout() + return lay.size, lay.stride, lay.offset, lay.dtype, True + + layouts: list[Any] = [] + cur = data + while isinstance(cur, (ir.TensorBox, ir.StorageBox, ir.ReinterpretView)): + lay = cur.get_layout() + if lay is None: + return None, None, None, None, False + layouts.append(lay) + cur = cur.data # unwrap + + if not isinstance(cur, ir.Buffer): + return None, None, None, None, False + + # All wrapper offsets must match base offset to be collapsible + for lay in layouts: + if lay.offset != cur.get_layout().offset: + return None, None, None, None, False + + base_lay = cur.get_layout() + return base_lay.size, base_lay.stride, base_lay.offset, base_lay.dtype, True + + +# TODO: Move to a well known place +TritonMetaParams = dict[str, int] +TritonGrid = ( + tuple[int | sympy.Expr, ...] | Callable[[TritonMetaParams], tuple[int, ...]] +) + + +def user_defined_kernel_grid_fn_code( + name: str, + configs: list[triton.Config], # type: ignore[name-defined] + grids: list[TritonGrid], + wrapper: PythonWrapperCodegen | None = None, + original_fxnode_name: str | None = None, +) -> tuple[str, str]: + output = IndentedBuffer() + + def _convert_to_sympy_expr(item: int | sympy.Expr) -> sympy.Expr: + return item if isinstance(item, sympy.Expr) else sympy.Integer(item) + + def determine_grid( + grid: TritonGrid, + example_grid: TritonGrid | None = None, + ): + """ + This function returns a tuple of two values: the first one is for the real grid + which is used in the generated code; the second one is an example grid with + concrete values which is used in the autotune block to run the generated + kernels at compile time. + """ + if wrapper is None or callable(grid): + # return as-is when used in eager mode or when grid is callable + return grid, grid + # Grid contains ints/Expr, so utilize wrapper's expr printer for codegen + sympy_grid = tuple(_convert_to_sympy_expr(g) for g in grid) + if not example_grid: + example_grid = sympy_grid + return ( + wrapper.codegen_python_shape_tuple(sympy_grid), + ( + wrapper.codegen_python_shape_tuple( + tuple( + wrapper.generate_example_arg_value(g, type(g)) + for g in example_grid # type: ignore[union-attr] + ) + ) + if config.triton.autotune_at_compile_time + else None + ), + ) + + def writeline(line: str, example_grid: str | None = None): + output.writeline(line) + if ( + wrapper + and config.triton.autotune_at_compile_time + and name not in wrapper.kernel_autotune_names + ): + wrapper.kernel_autotune_calls.writeline(example_grid or line) + + fn_name = f"grid_wrapper_for_{name}" + writeline(f"def {fn_name}(meta):") + kernel_autotune_calls_indent = ( + wrapper.kernel_autotune_calls.indent() + if wrapper and config.triton.autotune_at_compile_time + else contextlib.nullcontext() + ) + with output.indent(), kernel_autotune_calls_indent: + if ( + config.triton.autotune_at_compile_time + and original_fxnode_name + and V.graph.autotuning_grids + and original_fxnode_name in V.graph.autotuning_grids + ): + example_grids = V.graph.autotuning_grids[original_fxnode_name] + else: + example_grids = [None] * len(grids) + if len(grids) == 1: + grid, example_grid = determine_grid(grids[0], example_grids[0]) + writeline(f"return {grid}", f"return {example_grid}") + else: + if len(grids) <= 1: + raise AssertionError(f"expected more than 1 grid, got {len(grids)}") + if len(grids) != len(configs): + raise AssertionError( + f"expected len(grids) == len(configs), got {len(grids)} != {len(configs)}" + ) + seen: OrderedSet[str] = OrderedSet() + # sort the configs from the largest # of kwargs to the smallest to + # emit the grids in the order of (approximately) decreasing specificity + # TODO(aakhundov): the sorting below is generally not sufficient, so + # maybe we'll need to restrict the supported cases to identical kwarg + # names in all autotuning configs. + for grid, c, example_grid in sorted( + zip(grids, configs, example_grids), + key=lambda x: len(x[1].kwargs), + reverse=True, + ): + guardslist = [] + if c.kwargs: + # Remove AMD specific kwargs. + for kwarg in c.kwargs: + if kwarg not in [ + "matrix_instr_nonkdim", + "waves_per_eu", + "kpack", + ]: + guardslist.append(f"meta['{kwarg}'] == {c.kwargs[kwarg]}") + if guardslist: + guards = " and ".join(guardslist) + else: + guards = "True" # for configs with empty kwargs + grid, example_grid = determine_grid(grid, example_grid) + statement = f"if {guards}: return {grid}" + if statement in seen: + continue + seen.add(statement) + writeline(statement, f"if {guards}: return {example_grid}") + + return fn_name, output.getvalue() + + +def user_defined_triton_kernel_transitive_closure_source_code( + kernel, epilogue_fusion: tuple[ir.ComputedBuffer, str] | None = None +) -> str: + """ + Given a triton kernel function pointer collect the transitive closure of + its dependencies + + epilogue_fusion: Optional[(fused epilogue node, modified kerel src code)] + """ + compile_wrapper = IndentedBuffer() + kernel_src = kernel.src + if epilogue_fusion: + kernel_src = epilogue_fusion[1] + compile_wrapper.splice(kernel_src, strip=True) + + # Also include any possible kernel being called indirectly + import triton + from triton import JITFunction # type: ignore[name-defined, attr-defined] + from triton.language import constexpr # type: ignore[name-defined] + from triton.language.core import dtype as triton_dtype + + # global constexpr vars handled above + symbols_included = OrderedSet([kernel.__name__]) + + def traverse(cur_kernel): + # here we extract the unqualified names (i.e., not attributes and + # without prepended module name) loaded in the kernel code, which + # are matched with the co_names and __globals__ below to codegen + # the respective imports necessary for the kernel compilation + unqualified_loads = OrderedSet( + inst.argval + for inst in dis.Bytecode(cur_kernel.fn) + if inst.opname == "LOAD_GLOBAL" + ) + global_annotations = cur_kernel.fn.__globals__.get("__annotations__", {}) + for symbol_name in cur_kernel.fn.__code__.co_names: + if symbol_name in symbols_included: + continue + if symbol_name in cur_kernel.fn.__globals__: + symbol = cur_kernel.fn.__globals__[symbol_name] + if isinstance(symbol, JITFunction): + compile_wrapper.newline() + compile_wrapper.writeline("@triton.jit") + compile_wrapper.splice(symbol.src, strip=True) + symbols_included.add(symbol_name) + traverse(symbol) + elif hasattr(triton, "constexpr_function") and isinstance( + symbol, + triton.runtime.jit.ConstexprFunction, + ): + # Import dtype class if used in type annotations + if "dtype" in symbol.src and "dtype" not in symbols_included: + dtype_symbol = symbol.fn.__globals__.get("dtype") + if ( + dtype_symbol + and hasattr(dtype_symbol, "__module__") + and dtype_symbol.__module__.startswith("triton") + ): + compile_wrapper.writeline( + f"from {dtype_symbol.__module__} import dtype as dtype" + ) + symbols_included.add("dtype") + compile_wrapper.newline() + compile_wrapper.writeline("@triton.constexpr_function") + compile_wrapper.splice(symbol.src, strip=True) + if symbol_name != symbol.fn.__name__: + compile_wrapper.writeline( + f"{symbol_name} = {symbol.fn.__name__}" + ) + symbols_included.add(symbol_name) + traverse(symbol) + elif isinstance(symbol, (int, str, bool, constexpr)): + compile_wrapper.newline() + if isinstance(symbol, constexpr): + symbol_str = f"tl.constexpr({symbol.value!r})" + else: + symbol_str = f"{symbol!r}" + if annotation := global_annotations.get(symbol_name): + if isinstance(annotation, type): + annotation_code = ( + f": {annotation.__module__}.{annotation.__name__}" + ) + else: + annotation_code = f": {annotation!r}" + compile_wrapper.writeline( + f"{symbol_name}{annotation_code} = {symbol_str}" + ) + else: + compile_wrapper.writeline(f"{symbol_name} = {symbol_str}") + symbols_included.add(symbol_name) + elif ( + symbol_name in unqualified_loads + and symbol_name != "tl" # already imported + and hasattr(symbol, "__module__") + # only codegen imports from triton; JITFunctions + # imported from other modules will be codegened + # in the separate branch above + and symbol.__module__.startswith("triton") + ): + # a global symbol imported from triton is referenced + # without module qualification (i.e., `store` instead + # of `tl.store`): need to codegen an import + + # Triton dtype instances have .name instead of .__name__ + if isinstance(symbol, triton_dtype): + compile_wrapper.writeline(f"{symbol_name} = tl.{symbol.name}") + elif hasattr(symbol, "__name__"): + compile_wrapper.writeline( + f"from {symbol.__module__} import {symbol.__name__} as {symbol_name}" + ) + symbols_included.add(symbol_name) + + traverse(kernel) + return compile_wrapper.getvalue() + + +def _escape_triton_kernel_source_for_wrapper(src: str) -> str: + """Escape src for a '''...''' literal, optionally nested in an r\"\"\"...\"\"\" block.""" + src = src.replace("\\", "\\\\") + if config.cpp_wrapper: + # With cpp_wrapper + autotune_at_compile_time=False, the source is + # further embedded in a C++ raw string inside a Python r"""...""" wrapper. + # So we need to add backslash here. + src = src.replace('"""', '\\"\\"\\"') + return src.replace("'''", "\\'\\'\\'") + + +@dataclasses.dataclass +class SymbolicCallArg: + inner: sympy.Symbol + # the original symbolic expression represented by inner + inner_expr: sympy.Expr + + def __str__(self): + return str(self.inner) + + +class MemoryPlanningState: + def __init__(self): + super().__init__() + # Regular buffer reuse pool + self.reuse_pool: dict[ReuseKey, list[FreeIfNotReusedLine]] = ( + collections.defaultdict(list) + ) + # Separate pool for comm buffers (comm-comm reuse only) + self.comm_buffer_reuse_pool: dict[ + CommBufferReuseKey, list[FreeIfNotReusedLine] + ] = collections.defaultdict(list) + self.total_allocated_buffer_size: int = 0 + + def __contains__(self, key: ReuseKey) -> bool: + return bool(self.reuse_pool.get(key, None)) + + def pop(self, key: ReuseKey) -> FreeIfNotReusedLine: + item = self.reuse_pool[key].pop() + if item.is_reused: + raise AssertionError("expected popped reuse pool item to not be reused") + return item + + def push(self, key: ReuseKey, item: FreeIfNotReusedLine) -> None: + if item.is_reused: + raise AssertionError("expected pushed reuse pool item to not be reused") + self.reuse_pool[key].append(item) + + def comm_buffer_contains(self, key: CommBufferReuseKey) -> bool: + return bool(self.comm_buffer_reuse_pool.get(key, None)) + + def comm_buffer_pop(self, key: CommBufferReuseKey) -> FreeIfNotReusedLine: + item = self.comm_buffer_reuse_pool[key].pop() + if item.is_reused: + raise AssertionError( + "expected popped comm buffer reuse pool item to not be reused" + ) + return item + + def comm_buffer_push( + self, key: CommBufferReuseKey, item: FreeIfNotReusedLine + ) -> None: + if item.is_reused: + raise AssertionError( + "expected pushed comm buffer reuse pool item to not be reused" + ) + self.comm_buffer_reuse_pool[key].append(item) + + +class HasWriteLine(Protocol): + def writeline(self, line: LineContext | DeferredLineBase | str) -> None: ... + + +class WrapperLine: + def codegen(self, code: Any) -> None: + raise NotImplementedError(f"Codegen not yet supported for type {type(self)}") + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + raise NotImplementedError(f"FX codegen not yet supported for type {type(self)}") + + +@dataclasses.dataclass +class EnterSubgraphLine(WrapperLine): + wrapper: PythonWrapperCodegen + graph: GraphLowering + + def __post_init__(self) -> None: + self.wrapper.push_computed_sizes(self.wrapper.computed_sizes) + + def codegen(self, code: IndentedBuffer) -> None: + self.wrapper.push_codegened_graph(self.graph) + code.do_indent() + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_enter_subgraph + + +@dataclasses.dataclass +class SwitchLine(WrapperLine): + wrapper: PythonWrapperCodegen + node: ir.Switch + + def codegen(self, code: IndentedBuffer) -> None: + raise NotImplementedError("Only supports FX codegen") + + @staticmethod + def codegen_fx(converter: FxConverter) -> FxConversionFunc: + return converter._generate_switch + + +@dataclasses.dataclass +class CommentLine(WrapperLine): + line: LineContext + + def codegen(self, code: IndentedBuffer) -> None: + code.writeline(self.line) + + @staticmethod + def codegen_fx(converter: FxConverter) -> FxConversionFunc: + return converter._generate_comment + + +@dataclasses.dataclass +class DynamicScalarLine(WrapperLine): + wrapper: PythonWrapperCodegen + node: ir.DynamicScalar + + def codegen(self, code: IndentedBuffer) -> None: + self.wrapper._codegen_dynamic_scalar(self.node) + + @staticmethod + def codegen_fx(converter: FxConverter) -> FxConversionFunc: + return converter._generate_dynamic_scalar + + +@dataclasses.dataclass +class ExitSubgraphLine(WrapperLine): + wrapper: PythonWrapperCodegen + + def __post_init__(self) -> None: + self.wrapper.computed_sizes = self.wrapper.pop_computed_sizes() + + def codegen(self, code: IndentedBuffer) -> None: + self.wrapper.pop_codegened_graph() + code.do_unindent() + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_exit_subgraph + + +# [device-as-parameter] Name of the call()-local variable holding the runtime current +# device index under compile-on-one-rank, so the wrapper is byte-identical across ranks. +_COOR_DEVICE_IDX_VAR = COOR_DEVICE_IDX_VAR + + +def _coor_device_idx_ref(device_idx: int) -> int | str: + """Device index to emit in the wrapper. Under compile-on-one-rank, the call()-local + runtime current-device variable (so the wrapper is byte-identical across ranks); + otherwise the literal compile-time index. + + Safe to ignore ``device_idx`` under CooR: make_fx rejects any operand that is not the + current accelerator (_coor_check_current_accelerator), so every ``device_idx`` reaching + codegen is already the current device's index; redirecting it to the runtime variable + just follows each rank's own device. + """ + return _COOR_DEVICE_IDX_VAR if _coor_enabled() else device_idx + + +@dataclasses.dataclass +class EnterDeviceContextManagerLine(WrapperLine): + device_idx: int + last_seen_device_guard_index: int | None + + def codegen(self, code: IndentedBuffer) -> None: + if V.graph.cpp_wrapper: + code.writeline("\n") + # AOTI stream is bound to a device, so CUDAStreamGuard sets both + # stream and device, and the device cannot change later. + if self.last_seen_device_guard_index is None: + code.writeline_aot( + f"{V.graph.device_ops.cpp_aoti_stream_guard()} stream_guard(stream, this->device_idx_);" + ) + code.writeline_jit( + f"{V.graph.device_ops.cpp_aoti_device_guard()} device_guard({self.device_idx});" + ) + else: + if V.graph.aot_mode: + # AOTI emits a single stream_guard on first use; later + # contexts can only re-enter the same device. In dual-wrapper + # mode the JIT side still needs device_guard updates. + if self.last_seen_device_guard_index != self.device_idx: + raise AssertionError( + "AOTInductor only supports running on one CUDA device" + ) + if not V.graph.aot_mode or V.graph.is_dual_wrapper_mode: + code.writeline_jit(f"device_guard.set_index({self.device_idx});") + else: + # Note _DeviceGuard has less overhead than device, but only accepts + # integers + if _coor_enabled(): + # compile-on-one-rank: resolve the device at runtime so the wrapper is + # byte-identical across ranks -- a shared artifact follows each rank's + # current device instead of the compile-time index. + idx = _COOR_DEVICE_IDX_VAR + code.writeline( + f"{idx} = {V.graph.device_ops.current_device_idx_expr()}" + ) + else: + idx = self.device_idx + code.writeline(f"with {V.graph.device_ops.device_guard(idx)}:") + code.do_indent() + code.writeline(V.graph.device_ops.set_device(idx)) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_enter_device_context_manager + + +class ExitDeviceContextManagerLine(WrapperLine): + def codegen(self, code: IndentedBuffer) -> None: + if not V.graph.cpp_wrapper: + code.do_unindent() + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_exit_device_context_manager + + +@dataclasses.dataclass +class ExternKernelAllocLine(WrapperLine): + wrapper: PythonWrapperCodegen + node: ir.ExternKernelAlloc + + def codegen(self, code: IndentedBuffer) -> None: + node = self.node + args = [*node.codegen_args(), *node.codegen_kwargs()] + self.wrapper._generate_extern_kernel_alloc_helper(self.node, args) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_extern_kernel_alloc + + +@dataclasses.dataclass +class ExternKernelOutLine(WrapperLine): + wrapper: PythonWrapperCodegen + node: ir.ExternKernelOut + + def codegen(self, code: IndentedBuffer) -> None: + node = self.node + args = [*node.codegen_args(), *node.codegen_kwargs(skip_out=True)] + kernel_name = node.get_kernel_name() + if ( + V.graph.cpp_wrapper + and node.cpp_kernel_name == "torch::inductor::_mm_plus_mm" + ): + # For https://github.com/pytorch/pytorch/issues/128474 + kernel_name = "aoti_torch__mm_plus_mm_out" + else: + kernel_name = node.get_kernel_name() + device = d.type if (d := node.get_device()) else V.graph.device_type + self.wrapper._generate_extern_kernel_out_helper( + kernel_name, + node.codegen_reference(), + node.output_view.codegen_reference() if node.output_view else None, + args, + device, + self.node.get_stack_traces(), + ) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_extern_kernel_out + + +@dataclasses.dataclass +class ExternKernelMultiOutLine(WrapperLine): + """Codegen line for multi-output .out() variant calls. + + Generates a kernel call with pre-allocated output buffers passed as + keyword arguments. E.g. kernel(x, out0=buf0, out1=buf1). + """ + + wrapper: PythonWrapperCodegen + node: ir.ExternKernelMultiOut + + def codegen(self, code: IndentedBuffer) -> None: + node = self.node + kernel_name = node.get_kernel_name() + + args = [*node.codegen_args(), *node.codegen_kwargs()] + for out_name, out_node in zip( + node.out_arg_names, node.out_variant_output_nodes + ): + args.append(f"{out_name}={out_node.get_name()}") + + code.writeline(f"{node.get_name()} = {kernel_name}({', '.join(args)})") + + +@dataclasses.dataclass +class FreeLine(WrapperLine): + wrapper: PythonWrapperCodegen + node: BufferLike | ir.TorchBindObject + + def codegen(self, code: IndentedBuffer) -> None: + if self.node.get_name() in V.graph.removed_buffers: + raise AssertionError( + f"buffer {self.node.get_name()} was removed but is being freed" + ) + code.writeline(self.wrapper.make_buffer_free(self.node)) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_free + + +@dataclasses.dataclass +class KernelCallLine(WrapperLine): + wrapper: PythonWrapperCodegen + kernel_name: str + call_args: tuple[Any, ...] + raw_keys: tuple[Any, ...] + raw_args: tuple[Any, ...] + arg_types: list[str] + triton: bool + triton_meta: TritonMeta + inductor_meta: dict[str, Any] | None + device: torch.device + graph_name: str + original_fxnode_name: str + current_stream_idx: int | None = None + + def codegen(self, code: IndentedBuffer) -> None: + self.wrapper._generate_kernel_call_helper( + self.kernel_name, + self.call_args, + triton=self.triton, + arg_types=self.arg_types, + raw_keys=self.raw_keys, + raw_args=self.raw_args, + triton_meta=self.triton_meta, + inductor_meta=self.inductor_meta, + device=self.device, + graph_name=self.graph_name, + original_fxnode_name=self.original_fxnode_name, + current_stream_idx=self.current_stream_idx, + ) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_kernel_call + + +@dataclasses.dataclass +class KernelDefinitionLine(WrapperLine): + wrapper: PythonWrapperCodegen + kernel_name: str + kernel_body: str + metadata: str | None = None + gpu: bool = True + cpp_definition: str | None = None + + def codegen(self, code: IndentedBuffer) -> None: + self.wrapper._define_kernel_helper( + self.kernel_name, + self.kernel_body, + metadata=self.metadata, + gpu=self.gpu, + cpp_definition=self.cpp_definition, + ) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_kernel_definition + + +@dataclasses.dataclass +class MemoryPlanningLine(WrapperLine): + wrapper: PythonWrapperCodegen + + def plan(self, state: MemoryPlanningState) -> MemoryPlanningLine: + """First pass to find reuse""" + return self + + def codegen(self, code: IndentedBuffer) -> None: + """Second pass to output code""" + + def __str__(self) -> str: + """ + Emits a string representation that fits on one line. + """ + args: list[str] = [] + for field in dataclasses.fields(self): + if field.name == "wrapper": + continue + val = getattr(self, field.name) + args.append( + f"{field.name}={val.get_name() if field.type is ir.Buffer else val}" + ) + return f"{type(self).__name__}({', '.join(args)})" + + +@dataclasses.dataclass +class EnterDeviceContextManagerWithStreamInfoLine(EnterDeviceContextManagerLine): + """Enter a device context and retrieve user stream objects. + + Attributes: + num_streams: Number of streams (determined by user annotations on nodes). + stream_idx_to_user_obj_idx: Maps stream_idx → user_object_index for + retrieving user stream objects via _get_stream_by_index. + """ + + num_streams: int = 1 + stream_idx_to_user_obj_idx: dict[int, int] = dataclasses.field(default_factory=dict) + setup_stream_cache: bool = True + + def codegen(self, code: IndentedBuffer) -> None: + """Generate context switching and stream retrieval code.""" + if V.graph.cpp_wrapper: + super().codegen(code) + V.graph.wrapper_code.codegen_stream_info_prologue( + code, self.num_streams, self.stream_idx_to_user_obj_idx + ) + else: + super().codegen(code) + + if self.setup_stream_cache: + code.writeline( + f"{DEFAULT_STREAM} = {V.graph.device_ops.current_stream()}" + ) + + if self.num_streams > 1: + for i in range(1, self.num_streams): + user_obj_idx = self.stream_idx_to_user_obj_idx[i] + code.writeline( + f"{STREAM_NAME_TEMPLATE.format(stream_idx=i)} " + f"= _get_stream_by_index({user_obj_idx})", + ) + + +@dataclasses.dataclass +class ExitDeviceContextManagerWithStreamInfoLine(ExitDeviceContextManagerLine): + """Exit a device context. + + Attributes: + num_streams: Number of streams that were allocated (must match Enter). + """ + + num_streams: int = 1 + + def codegen(self, code: IndentedBuffer) -> None: + """Generate context exit code.""" + if not V.graph.cpp_wrapper: + code.do_unindent() + + +@dataclasses.dataclass +class EnterCudaStreamContextLine(WrapperLine): + """Enter a context executed by the respective device stream. + + Attributes: + stream_idx: The index number for the entering device stream context. + """ + + stream_idx: int + + def codegen(self, code: IndentedBuffer) -> None: + wrapper_code = getattr(V.graph, "wrapper_code", None) + if wrapper_code is None: + code.writeline(f"with {get_stream_name(self.stream_idx)}:") + code.do_indent() + else: + wrapper_code.codegen_enter_cuda_stream_context(code, self.stream_idx) + + +@dataclasses.dataclass +class ExitCudaStreamContextLine(WrapperLine): + """Generate code to exit the current stream context.""" + + def codegen(self, code: IndentedBuffer) -> None: + wrapper_code = getattr(V.graph, "wrapper_code", None) + if wrapper_code is None: + code.do_unindent() + else: + wrapper_code.codegen_exit_cuda_stream_context(code) + + +@dataclasses.dataclass +class EnterCudaMemPoolContextLine(WrapperLine): + """Enter a torch.cuda.use_mem_pool context for scheduler node codegen.""" + + mempool_index: int + device_index: int + + def codegen(self, code: IndentedBuffer) -> None: + code.writeline( + "with torch.cuda.use_mem_pool(" + f"get_external_object_by_index({self.mempool_index}), " + f"device={self.device_index}):" + ) + code.do_indent() + + +class ExitCudaMemPoolContextLine(WrapperLine): + """Exit the active torch.cuda.use_mem_pool context.""" + + def codegen(self, code: IndentedBuffer) -> None: + code.do_unindent() + + +class EfficientPeakEstimate: + def __init__(self): + from ..memory import estimate_peak_memory, get_freeable_input_buf + + scheduler_nodes = V.graph.scheduler.nodes + graph_inputs = OrderedSet(V.graph.graph_inputs.keys()) + graph_outputs = OrderedSet(V.graph.get_output_names()) + names_to_freeable_bufs = get_freeable_input_buf(scheduler_nodes, graph_inputs) + self.overall_peak_memory, peak_by_scheduler_node = estimate_peak_memory( + scheduler_nodes, + names_to_freeable_bufs, + graph_outputs, + ) + + from .segmented_tree import SegmentedTree + + self.segmented_tree = SegmentedTree( + peak_by_scheduler_node, operator.add, max, 0 + ) + + def _get_size(self, node: BufferLike) -> int: + return V.graph.sizevars.optimization_hint( + V.graph.get_allocation_storage_size(node), fallback=0 + ) * get_dtype_size(node.get_dtype()) + + def peak_between(self, line_a: FreeIfNotReusedLine, line_b: AllocateLine): + return self.segmented_tree.summarize_range( + line_a.scheduler_node_index + 1, line_b.scheduler_node_index - 1 + ) + + def update_peak_between(self, line_a: FreeIfNotReusedLine, line_b: AllocateLine): + if line_a.scheduler_node_index + 1 == line_b.scheduler_node_index: + return + self.segmented_tree.update_range( + line_a.scheduler_node_index + 1, + line_b.scheduler_node_index - 1, + self._get_size(line_b.node), + ) + + +@dataclasses.dataclass +class AllocateLine(MemoryPlanningLine): + """Represents a buffer allocation during memory planning.""" + + node: BufferLike + comm_buffer: bool = False + + def __post_init__(self): + if V.graph.scheduler.current_node is None: + raise AssertionError("expected scheduler.current_node to be set") + self.scheduler_node_index = V.graph.scheduler.nodes.index( + V.graph.scheduler.current_node + ) + + def should_reuse_buffer(self, free_line: FreeIfNotReusedLine, size: int) -> bool: + if self.comm_buffer: + return True + if free_line.scheduler_node_index + 1 == self.scheduler_node_index: + return True + overall_peak_memory = self.wrapper.estimate_peak.overall_peak_memory + peak_memory_in_range = self.wrapper.estimate_peak.peak_between(free_line, self) + new_peak_memory = size + peak_memory_in_range + return new_peak_memory <= overall_peak_memory + + def plan(self, state: MemoryPlanningState) -> MemoryPlanningLine: + if self.node.get_name() in V.graph.removed_buffers: + return NullLine(self.wrapper) + + if self.comm_buffer: + # Comm buffers use separate pool (comm-comm reuse only) + key = comm_buffer_reuse_key(self.node) + if config.allow_buffer_reuse and state.comm_buffer_contains(key): + free_line = state.comm_buffer_pop(key) + free_line.is_reused = True + return ReuseLine( + self.wrapper, free_line.node, self.node, comm_buffer=True + ) + return self + + # Regular buffer reuse + # Stream is part of the key, so cross-stream reuse is naturally prevented. + key = buffer_reuse_key(self.node) + if config.allow_buffer_reuse and key in state: + free_line = state.pop(key) + size = V.graph.sizevars.optimization_hint( + V.graph.get_allocation_storage_size(self.node), fallback=0 + ) * get_dtype_size(self.node.get_dtype()) + if self.should_reuse_buffer(free_line, size): + free_line.is_reused = True + self.wrapper.estimate_peak.update_peak_between(free_line, self) + return ReuseLine(self.wrapper, free_line.node, self.node) + else: + state.push(key, free_line) + return self + + if self.node.get_device_or_error().type == "cpu": + static_shape = self.wrapper.static_shape_for_buffer_or_none(self.node) + if static_shape is not None: + state.total_allocated_buffer_size += int( + functools.reduce(operator.mul, static_shape, 1) + ) + + return self + + def codegen(self, code: IndentedBuffer) -> None: + if self.node.get_name() in V.graph.removed_buffers: + raise AssertionError( + f"buffer {self.node.get_name()} was removed but is being freed" + ) + if self.comm_buffer: + self._codegen_comm_buffer(code) + else: + code.writeline(self.wrapper.make_buffer_allocation(self.node)) + + def _codegen_comm_buffer(self, code: IndentedBuffer) -> None: + """Generate allocation code for comm buffers.""" + name = self.node.get_name() + device = self.node.get_device() + if not (device is not None and device.index is not None): + raise AssertionError( + f"Comm buffer requires a valid CUDA device with index, got {device}" + ) + dtype = self.node.get_dtype() + shape = tuple(self.node.get_size()) + stride = tuple(self.node.get_stride()) + layout = self.node.get_output_spec() + if not isinstance(layout, ir.CommBufferLayout): + raise AssertionError(f"expected CommBufferLayout, got {type(layout)}") + comm_buffer_type = layout.comm_buffer_type + group_name = layout.group_name + + if comm_buffer_type == ir.CommBufferType.SYMM_MEM: + # [device-as-parameter] under compile-on-one-rank the comm buffer must follow + # the running rank's device, not the compile-time index. + if _coor_enabled(): + device_arg = f'torch.device("cuda", {V.graph.device_ops.current_device_idx_expr()})' + else: + device_arg = f'torch.device("cuda:{device.index}")' + line = ( + f"{name} = empty_strided_p2p(" + f"{self.wrapper.codegen_shape_tuple(shape)}, " + f"{self.wrapper.codegen_shape_tuple(stride)}, " + f"{dtype}, " + f"{device_arg}, " + f'group_name="{group_name}", ' + f"alloc_id={random.randint(0, 2**64 - 1)})" + ) + else: + raise NotImplementedError( + f"Unsupported comm buffer type: {comm_buffer_type}" + ) + code.writeline(line) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + if self.comm_buffer: + return converter._generate_comm_buffer_allocate + return converter._generate_allocate + + +@dataclasses.dataclass +class FreeIfNotReusedLine(MemoryPlanningLine): + node: BufferLike + is_reused: bool = False + comm_buffer: bool = False + + def __post_init__(self): + if V.graph.scheduler.current_node is None: + raise AssertionError("expected scheduler.current_node to be set") + self.scheduler_node_index = V.graph.scheduler.nodes.index( + V.graph.scheduler.current_node + ) + + def plan(self, state: MemoryPlanningState) -> MemoryPlanningLine: + if len(self.node.get_inputs_that_alias_output()) > 0: + return self + if isinstance(self.node.layout, ir.MultiOutputLayout): + return self + if self.is_reused: + raise AssertionError("expected line to not be reused") + if self.node.get_name() in V.graph.removed_buffers: + return NullLine(self.wrapper) + if config.allow_buffer_reuse: + if self.comm_buffer: + # Comm buffers use separate pool (comm-comm reuse only) + key = comm_buffer_reuse_key(self.node) + state.comm_buffer_push(key, self) + else: + key = buffer_reuse_key(self.node) + state.push(key, self) + return self + + def codegen(self, code: IndentedBuffer) -> None: + if self.node.get_name() in V.graph.removed_buffers: + raise AssertionError( + f"buffer {self.node.get_name()} was removed but is being freed" + ) + if not self.is_reused: + line = self.wrapper.make_buffer_free(self.node) + if self.comm_buffer: + layout = self.node.get_output_spec() + if not isinstance(layout, ir.CommBufferLayout): + raise AssertionError( + f"expected CommBufferLayout, got {type(layout)}" + ) + code.writeline(f"{line} # {layout.comm_buffer_type.value} buffer free") + else: + code.writeline(line) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + if self.comm_buffer: + return converter._generate_comm_buffer_free + return converter._generate_free_if_not_reused + + +@dataclasses.dataclass +class ReinterpretLine(MemoryPlanningLine): + node: BufferLike + reused_as: BufferLike + layout: ir.Layout + + def plan(self, state: MemoryPlanningState) -> MemoryPlanningLine: + return self + + def codegen(self, code: IndentedBuffer) -> None: + if not isinstance(self.layout, ir.NonOwningLayout): + raise AssertionError(f"expected NonOwningLayout, got {type(self.layout)}") + if not isinstance(self.layout.view, ir.ReinterpretView): + raise AssertionError( + f"expected ReinterpretView, got {type(self.layout.view)}" + ) + self.wrapper.codegen_deferred_allocation( + self.reused_as.get_name(), self.layout.view + ) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_reinterpret + + +@dataclasses.dataclass +class ReuseLine(MemoryPlanningLine): + node: BufferLike + reused_as: BufferLike + delete_old: bool = True + comm_buffer: bool = False + + def plan(self, state: MemoryPlanningState) -> MemoryPlanningLine: + if self.node.get_name() in V.graph.removed_buffers: + if self.reused_as.get_name() not in V.graph.removed_buffers: + raise AssertionError( + f"reuse target {self.reused_as.get_name()} expected to be removed" + ) + return NullLine(self.wrapper) + if self.reused_as.get_name() in V.graph.removed_buffers: + raise AssertionError( + f"reuse target {self.reused_as.get_name()} was removed unexpectedly" + ) + return self + + def codegen(self, code: IndentedBuffer) -> None: + if self.node.get_name() in V.graph.removed_buffers: + raise AssertionError( + f"buffer {self.node.get_name()} was removed but is being freed" + ) + if self.reused_as.get_name() in V.graph.removed_buffers: + raise AssertionError( + f"reuse target {self.reused_as.get_name()} was removed unexpectedly" + ) + code.writeline( + self.wrapper.make_buffer_reuse(self.node, self.reused_as, self.delete_old) + ) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_reuse + + +class NullLine(MemoryPlanningLine): + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_null + + +@dataclasses.dataclass +class MultiOutputLine(WrapperLine): + """ + Given a MultiOutputLayout buffer, indexes actual buffer(s) from the result. + """ + + wrapper: PythonWrapperCodegen + result_name: str + arg_name: str + indices: Sequence[Any] + + def codegen(self, code: IndentedBuffer) -> None: + def codegen_list_tuple_access(basename, indices): # type: ignore[no-untyped-def] + if len(indices) > 0: + itype, i = indices[0] + if issubclass(itype, list): + return codegen_list_tuple_access(f"{basename}[{i}]", indices[1:]) + elif issubclass(itype, tuple): + # cpp wrapper code needs to use std::get<> to access a tuple + tuple_access = self.wrapper.codegen_tuple_access( + basename, self.result_name, str(i) + ) + return codegen_list_tuple_access(tuple_access, indices[1:]) + elif issubclass(itype, dict): + return codegen_list_tuple_access(f"{basename}['{i}']", indices[1:]) + else: + raise AssertionError("non supported index type: ", itype) + else: + return basename + + value = codegen_list_tuple_access(self.arg_name, self.indices) + code.writeline( + f"{self.wrapper.declare}{self.result_name} = {value}{self.wrapper.ending}" + ) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_multi_output + + +@dataclasses.dataclass +class IndexPutFallbackLine(WrapperLine): + wrapper: PythonWrapperCodegen + node: ir.IndexPutFallback + indices: list[ir.IRNode | None] + + def codegen(self, code: IndentedBuffer) -> None: + node = self.node + if not ir.is_node_sequence(node.inputs): + raise AssertionError("expected node.inputs to be a node sequence") + (x, values) = (t.codegen_reference() for t in node.inputs[:2]) + indices = [ + idx.codegen_reference() if idx else self.wrapper.none_str + for idx in self.indices + ] + + self.wrapper._generate_index_put_fallback( + node.get_kernel_name(), x, indices, values, *node.codegen_const_args() + ) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_index_put_fallback + + +@dataclasses.dataclass +class ScatterFallbackLine(WrapperLine): + wrapper: PythonWrapperCodegen + node: ir.ScatterFallback + + def codegen(self, code: IndentedBuffer) -> None: + node = self.node + if not ir.is_node_sequence(node.inputs): + raise AssertionError("expected node.inputs to be a node sequence") + if node.src_is_tensor: + (x, index, src) = (t.codegen_reference() for t in node.inputs) + else: + (x, index) = (t.codegen_reference() for t in node.inputs) + src = node.constant_args[1] + device = d.type if (d := node.get_device()) else V.graph.device_type + self.wrapper._generate_scatter_fallback( + x, + [x, node.constant_args[0], index, src], + node.cpp_kernel_name, + node.python_kernel_name, + node.src_is_tensor, + node.kwargs["reduce"], + node.codegen_kwargs(), + device, + ) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_scatter_fallback + + +@dataclasses.dataclass +class SymbolicCallArgLine(WrapperLine): + wrapper: PythonWrapperCodegen + arg: SymbolicCallArg + graph: GraphLowering + + def codegen(self, code: IndentedBuffer) -> None: + self.wrapper._generate_symbolic_call_arg_helper(self.arg, self.graph) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_symbolic_call_arg + + +@dataclasses.dataclass +class UnbackedSymbolDefsLine(WrapperLine): + wrapper: PythonWrapperCodegen + output_name: str + outputs: Any + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None + + def codegen(self, code: IndentedBuffer) -> None: + self.wrapper._codegen_unbacked_symbol_defs_for_outputs( + self.output_name, self.outputs, self.unbacked_bindings + ) + + def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: + return converter._generate_unbacked_symbol_defs + + +@dataclasses.dataclass +class AssertSizeStrideLine(WrapperLine): + wrapper: PythonWrapperCodegen + name: str + size: str + stride: str + op_name: str = "input" + dtype: torch.dtype | None = None + + def codegen(self, code: IndentedBuffer) -> None: + self.wrapper._codegen_assert_size_stride( + code, self.name, self.size, self.stride, self.op_name, self.dtype + ) + + @staticmethod + def codegen_fx(converter: FxConverter) -> FxConversionFunc: + return converter._generate_assert_size_stride + + +@dataclasses.dataclass +class GroupedAssertSizeStrideLine(WrapperLine): + wrapper: PythonWrapperCodegen + asserts: list[tuple[str, str, str]] + op_name: str = "input" + + def codegen(self, code: IndentedBuffer) -> None: + self.wrapper._codegen_assert_size_stride_grouped( + code, self.asserts, self.op_name + ) + + @staticmethod + def codegen_fx(converter: FxConverter) -> FxConversionFunc: + return converter._generate_assert_size_stride + + +@dataclasses.dataclass +class AssertDivByZeroLine(WrapperLine): + """Deferred AOTI runtime check that a sizevar divisor is non-zero. + + Queued from CppWrapperCpu.codegen_cpp_sizevar during the build phase + and replayed at the position of use so the check lands after the + declarations of any unbacked symbols it references. + """ + + wrapper: PythonWrapperCodegen + divisor: str + op_name: str + + def codegen(self, code: IndentedBuffer) -> None: + self.wrapper._codegen_assert_div_by_zero(code, self.divisor, self.op_name) + + +BufferName = str +Line = MemoryPlanningLine | LineContext + + +class PythonWrapperCodegen(CodeGen): + """ + Generate outer wrapper in Python that calls the kernels. + """ + + supports_caching: bool = True # Whether the output code is cacheable. + + def __init__(self): + super().__init__() + self._last_default_stream_device: int | None = None + self._pending_input_asserts: dict[str, tuple[str, str]] = {} + self._pending_alignment_copies: OrderedSet[str] = OrderedSet() + # Inputs read on more than one stream get a copy_if_misaligned per + # consuming stream (each cloning a preserved copy of the original), so + # every stream is ordered after its own aligned clone. A single shared + # copy would leave other streams reading a clone made on -- and ordered + # only after -- the first reader's stream, a cross-stream race. These + # track the reclassified inputs, the saved originals, and the stream + # each working name is currently aligned for. + self._multistream_alignment_copies: OrderedSet[str] = OrderedSet() + self._alignment_orig_saved: OrderedSet[str] = OrderedSet() + self._alignment_aligned_stream: dict[str, int] = {} + self._names_iter: Iterator[int] = count() + self.args_to_buffers: dict[ + str, None | ir.TensorBox | ir.Buffer | ir.TorchBindObject + ] = {} + self.imports = IndentedBuffer() + self.header = make_codegen_buffer() + self.prefix = make_codegen_buffer() + self.suffix = IndentedBuffer() + self.kernel_declarations = IndentedBuffer() + self.wrapper_call = make_codegen_buffer() + self.kernel_autotune_defs = IndentedBuffer() + self.kernel_autotune_calls = IndentedBuffer() + self.subgraph_definitions = IndentedBuffer() + self.kernel_autotune_names: OrderedSet[str] = OrderedSet() + # Map key is the kernel argument name; value is a tuple of the resulting example + # tensor name with the kernel where that tensor was most recently used. + self.kernel_autotune_example_args: dict[str, tuple[str, str]] = {} + self.kernel_autotune_tmp_arg_idx: int = 0 + # If the generated source code is exactly the same, reuse the + # pre-existing kernel for it + self.src_to_kernel: dict[str, str] = {} + self.kernel_numel_expr: OrderedSet[tuple[str, GraphLowering]] = OrderedSet() + self.lines: list[Line] = [] + self.declare = "" + self.declare_maybe_reference = "" + self.ending = "" + self.comment = "#" + self.none_str = "None" + self.move_begin = "std::move(" if V.graph.cpp_wrapper else "" + self.move_end = ")" if V.graph.cpp_wrapper else "" + self.last_seen_device_guard_index: int | None = None + # [device-as-parameter] CooR harness render mode, resolved once and cached: + # None = unresolved, False = compile-on-one-rank off, else the current accelerator. + self._coor_current_accelerator: torch.device | Literal[False] | None = None + self.supports_intermediate_hooks = True + self.user_defined_kernel_cache: dict[ + tuple[Any, ...], tuple[str, Any, dict[str, Any]] + ] = {} + self.unbacked_symbol_decls: OrderedSet[str] = ( + OrderedSet() + ) # str of sympy.Symbol + self.computed_sizes: OrderedSet[sympy.Symbol] = OrderedSet() + self.launcher_fn_name = None + # This function can be overridden to change the launcher name + self.set_launcher_fn_name() + + # this is used for tracking which GraphLowering instance---parent graph + # or (nested) subgraph---is currently codegened; the primary use case is + # including the graph instance into a cache key to avoid cross-graph + # caching during lowering of nested subgraphs + self.codegened_graph_stack = [] + self.computed_sizes_stack = [] + + self.write_header() + + if not is_codegen_graph_partition_subgraph(self): + # See [Note: Removed Graph Partition Arguments] + self.write_prefix() + + self.write_kernel_autotune_defs_header() + + if not V.graph.aot_mode: + for name, hashed in V.graph.constant_reprs.items(): + # include a hash so our code cache puts different constants into different files + self.write_constant(name, hashed) + + self.allocated = OrderedSet[BufferName]() + self.freed = OrderedSet[BufferName]() + + # maps from reusing buffer to reused buffer + self.reuses: dict[BufferName, BufferName] = {} + + self.write_get_raw_stream = functools.lru_cache(None)( # type: ignore[assignment] + self.write_get_raw_stream + ) + + @functools.cache + def add_import_once(line: str) -> None: + self.imports.writeline(line) + if config.triton.autotune_at_compile_time: + self.kernel_autotune_calls.writeline(line) + + self.add_import_once = add_import_once + self._metas: dict[str, str] = {} + self._meta_vars: OrderedSet[str] = OrderedSet() + self.multi_kernel_state = MultiKernelState() + self.already_codegened_subgraphs: OrderedSet[str] = OrderedSet() + self.allocated_workspaces: dict[str, Any] = {} + + # intermediate tensor value printing utility + self.debug_printer = DebugPrinterManager( + debug_printer_level=config.aot_inductor.debug_intermediate_value_printer, + use_array_ref=config.aot_inductor.allow_stack_allocation, + ) + + # Additional files that are dependent to the wrapper (ex. cubin files) + self.additional_files = [] + + # Precompiled kernel .so paths to link into the JIT cpp_wrapper + # (e.g. CUTLASS, ROCm CK). Populated by the scheduling layer when + # cpp_wrapper is set and not aot_mode. + self.external_kernel_libs: OrderedSet[str] = OrderedSet() + + @staticmethod + def create( + is_subgraph: bool, + subgraph_name: str | None, + parent_wrapper: PythonWrapperCodegen | None, + partition_signatures: ir.GraphPartitionSignature | None = None, + ): + if is_subgraph: + if subgraph_name is None: + raise AssertionError("expected subgraph_name to be set") + if parent_wrapper is None: + raise AssertionError("expected parent_wrapper to be set") + return SubgraphPythonWrapperCodegen( + subgraph_name, parent_wrapper, partition_signatures + ) + return PythonWrapperCodegen() + + def set_launcher_fn_name(self) -> None: + # pyrefly: ignore [bad-assignment] + self.launcher_fn_name = "call" + + def write_constant(self, name: str, hashed: str) -> None: + self.header.writeline(f"{name} = None # {hashed}") + + def write_header(self) -> None: + """Write the header section of the generated Python wrapper code.""" + context = torch._guards.TracingContext.try_get() + aot_config_comment = "" + if context is not None and context.aot_graph_name is not None: + aot_config_comment = f"# AOT ID: {context.aot_graph_name}" + inductor_debug_utils = "" + if int(config.aot_inductor.debug_intermediate_value_printer) > 0: + inductor_debug_utils = "from torch._inductor.codegen.debug_utils import _print_debugging_tensor_value_info" + elif torch._inductor.config.test_configs.track_memory_lifecycle: + inductor_debug_utils = "from torch._inductor.runtime.debug_utils import tracked_empty_strided\n" + + self.imports.splice( + f""" + {aot_config_comment} + from ctypes import c_void_p, c_long, c_int + import torch + import math + import random + import os + import tempfile + from math import inf, nan + from cmath import nanj + from torch._inductor.hooks import run_intermediate_hooks + from torch._inductor.utils import maybe_profile + from torch._inductor.codegen.memory_planning import _align as align + from torch import device, empty_strided + from {async_compile.__name__} import AsyncCompile + from torch._inductor.select_algorithm import extern_kernels + {inductor_debug_utils} + """, + strip=True, + ) + self.header.splice( + """ + aten = torch.ops.aten + inductor_ops = torch.ops.inductor + _quantized = torch.ops._quantized + assert_size_stride = torch._C._dynamo.guards.assert_size_stride + assert_size_stride_grouped = torch._C._dynamo.guards.assert_size_stride_grouped + assert_alignment = torch._C._dynamo.guards.assert_alignment + empty_strided_cpu = torch._C._dynamo.guards._empty_strided_cpu + empty_strided_cpu_pinned = torch._C._dynamo.guards._empty_strided_cpu_pinned + empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda + empty_strided_xpu = torch._C._dynamo.guards._empty_strided_xpu + empty_strided_mtia = torch._C._dynamo.guards._empty_strided_mtia + reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor + alloc_from_pool = torch.ops.inductor._alloc_from_pool + async_compile = AsyncCompile() + """, + strip=True, + ) + try: + # Only add empty_strided_p2p() if distributed and SymmetricMemory + # is available + from torch._C._distributed_c10d import _SymmetricMemory # noqa: F401 + + self.header.splice( + """ + empty_strided_p2p = torch._C._distributed_c10d._SymmetricMemory.empty_strided_p2p + """, + strip=True, + ) + except (AttributeError, ImportError): + pass + if config.annotate_training: + self.header.writeline("from torch.cuda import nvtx") + if config.triton.proton_profiling: + self.header.writeline("import triton.profiler as proton") + self.header.writeline("import triton.profiler.language as pl") + self.header.writeline( + "from triton.profiler.hooks import HookManager as _ProtonHookManager" + ) + self.header.writeline("import triton") + self.header.writeline("import atexit") + self.header.writeline("import os") + self.header.writeline( + "triton.set_allocator(lambda size, align, stream: " + "torch.empty(size, dtype=torch.uint8, device='cuda'))" + ) + output_dir = config.triton.proton_output_dir or os.path.join( + get_debug_dir(), "proton" + ) + self.header.writeline(f'os.makedirs("{output_dir}", exist_ok=True)') + proton_name = f'os.path.join("{output_dir}", "inductor")' + trace_path = f'os.path.join("{output_dir}", "inductor.chrome_trace")' + group_by_sm = config.triton.proton_group_by_sm + split_invocations = config.triton.proton_split_invocations + per_cta_occupancy = config.triton.proton_per_cta_occupancy + self.header.writeline( + "from torch._inductor.runtime.proton_utils import process_proton_trace as _proton_process_trace" + ) + self.header.splice( + f""" + def _proton_finalize_and_postprocess(): + proton.finalize() + _trace_path = {trace_path} + if os.path.exists(_trace_path): + _proton_process_trace( + _trace_path, + group_by_sm={group_by_sm}, + split_invocations={split_invocations}, + per_cta_occupancy={per_cta_occupancy}, + ) + """ + ) + # Start proton before kernel compilation (instrumentation backend needs to hook JIT) + self.header.writeline( + "if not _ProtonHookManager.active_hooks: " + f'proton.start({proton_name}, backend="instrumentation", data="trace"); ' + "atexit.register(_proton_finalize_and_postprocess)" + ) + self.header.writeline('pl.enable_semantic("triton")') + + def include_extra_header(self, header: str): + pass + + def write_kernel_autotune_defs_header(self) -> None: + self.kernel_autotune_defs.splice( + f""" + import torch + from math import inf, nan + from torch._dynamo.testing import rand_strided + from torch._dynamo.utils import preserve_rng_state + from torch._inductor.select_algorithm import AlgorithmSelectorCache + from {async_compile.__name__} import AsyncCompile + + async_compile = AsyncCompile() + generate_example_value = AlgorithmSelectorCache.generate_example_value + empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda + empty_strided_xpu = torch._C._dynamo.guards._empty_strided_xpu + """ + ) + + try: + from torch._C import _cuda_getCurrentRawStream # noqa: F401 + + self.kernel_autotune_defs.splice( + """ + get_raw_stream = torch._C._cuda_getCurrentRawStream + """, + strip=True, + ) + except (ImportError, AttributeError): + pass + + @cache_on_self + def write_triton_header_once(self) -> None: + import_str = f""" + import triton + import triton.language as tl + from {triton_heuristics.__name__} import start_graph, end_graph + """ + if config.triton.autotune_at_compile_time: + self.kernel_autotune_calls.splice(import_str) + self.kernel_autotune_calls.writeline( + V.graph.device_ops.import_get_raw_stream_as("get_raw_stream") + ) + if not V.graph.cpp_wrapper: + self.imports.splice(import_str, strip=True) + self.imports.writeline( + V.graph.device_ops.import_get_raw_stream_as("get_raw_stream") + ) + + def write_get_raw_stream_header(self) -> None: + import_get_raw_stream_str = V.graph.device_ops.import_get_raw_stream_as( + "get_raw_stream" + ) + if config.triton.autotune_at_compile_time: + if not self.kernel_autotune_calls.contains(import_get_raw_stream_str): + self.kernel_autotune_calls.writeline(import_get_raw_stream_str) + if not V.graph.cpp_wrapper: + if not self.imports.contains(import_get_raw_stream_str): + self.imports.writeline(import_get_raw_stream_str) + + @cache_on_self + def write_get_raw_stream_header_once(self) -> None: + self.write_get_raw_stream_header() + + def add_meta_once(self, meta: TritonMetaParams) -> str: + # pyrefly: ignore [bad-assignment] + meta = repr(meta) + if meta not in self._metas: + var = f"meta{len(self._metas)}" + # pyrefly: ignore [unsupported-operation] + self._metas[meta] = var + self.header.writeline(f"{var} = {meta}") + if config.triton.autotune_at_compile_time: + self.kernel_autotune_calls.writeline(f"{var} = {meta}") + self._meta_vars.add(var) + # pyrefly: ignore [bad-index, index-error] + return self._metas[meta] + + @cache_on_self + def get_output_refs(self) -> list[str]: + return [ + x.codegen_reference(self.wrapper_call) for x in self.get_graph_outputs() + ] + + def mark_output_type(self) -> None: + return + + def get_graph_inputs( + self, + ) -> dict[str, ir.TensorBox | ir.TorchBindObject | sympy.Expr]: + return V.graph.graph_inputs + + def get_graph_outputs(self) -> list[IRNode]: + return V.graph.graph_outputs + + def codegen_input_size_asserts(self) -> None: + for name, buf in self.get_graph_inputs().items(): + if isinstance( + buf, + ( + sympy.Basic, + ir.TorchBindObject, + ir.GeneratorState, + ir.OpaqueObjectState, + ), + ): + continue + + # a graph partition may take an IRNode output from a previous partition + if name not in V.graph.graph_input_names: + continue + + # comparing strides for 0 size tensor is tricky. Ignore them for now. + if sympy_product(buf.get_size()) == 0: + continue + size = self.codegen_shape_tuple(buf.get_size()) + stride = self.codegen_shape_tuple(buf.get_stride()) + self._pending_input_asserts[name] = (size, stride) + + def codegen_input_nan_asserts(self) -> None: + self.prefix.writeline("# make sure graph inputs are not nan/inf") + for name, buf in self.get_graph_inputs().items(): + if isinstance(buf, (sympy.Basic, ir.TorchBindObject)): + continue + line = f"assert not {name}.isnan().any().item()" + self.prefix.writeline(line) + line = f"assert not {name}.isinf().any().item()" + self.prefix.writeline(line) + + def write_async_compile_wait(self) -> None: + self.prefix.splice( + """ + + async_compile.wait(globals()) + del async_compile + """ + ) + + def write_args(self, input_names: list[str]): + lhs = ", ".join(input_names) + if len(input_names) == 1: + lhs += "," + self.prefix.writeline(f"{lhs} = args") + self.prefix.writeline("args.clear()") + + def write_launcher_fn_call_get_indent(self) -> int: + if config.graph_partition: + self.prefix.splice( + """ + class Runner: + def __init__(self, partitions): + self.partitions = partitions + + def recursively_apply_fns(self, fns): + new_callables = [] + for fn, c in zip(fns, self.partitions): + new_callables.append(fn(c)) + self.partitions = new_callables + + def call(self, args): + """ + ) + prefix_indent = 2 + else: + self.prefix.splice( + f""" + def {self.launcher_fn_name}(args): + """ + ) + prefix_indent = 1 + + return prefix_indent + + def get_graph_input_names(self) -> list[str]: + return V.graph.graph_input_names + + def write_prefix(self) -> None: + if self.launcher_fn_name is None: + raise AssertionError("expected launcher_fn_name to be set") + self.write_async_compile_wait() + prefix_indent = self.write_launcher_fn_call_get_indent() + + with self.prefix.indent(prefix_indent): + if config.triton.debug_sync_graph: + self.generate_debug_sync(self.prefix) + phase = V.graph.get_training_phase() + if config.annotate_training: + self.prefix.writeline( + f"training_annotation = nvtx._device_range_start('{phase}')" + ) + + if graph_input_names := self.get_graph_input_names(): + self.write_args(graph_input_names) + + self.codegen_inputs() + + # avoid duplicating asserts for both partition functions and + # the call function when using cudagraph partition + if not ( + is_using_cudagraph_partition() + and (not is_codegen_graph_partition_subgraph(self)) + ): + self.codegen_input_size_and_nan_asserts() + + def codegen_input_size_and_nan_asserts(self) -> None: + if config.size_asserts: + self.codegen_input_size_asserts() + if config.nan_asserts: + self.codegen_input_nan_asserts() + + # Input size/stride assertions are deferred from the top of call() to just + # before the first kernel that uses each input. This avoids a block of N + # sequential assert calls (~1 us each) on the critical path before the first + # GPU kernel launch. Called from the scheduler codegen loop. + def codegen_deferred_input_asserts(self, input_names: Iterable[str]) -> None: + grouped_asserts: list[tuple[str, str, str]] = [] + for name in input_names: + if name in self._pending_input_asserts: + size, stride = self._pending_input_asserts.pop(name) + grouped_asserts.append((name, size, stride)) + if len(grouped_asserts) == 1: + name, size, stride = grouped_asserts[0] + self.write_assert_size_stride(name, size, stride, "input") + elif len(grouped_asserts) > 1: + self.write_assert_size_stride_grouped(grouped_asserts, "input") + + def write_assert_size_stride( + self, + name: str, + size: str, + stride: str, + op_name: str, + dtype: torch.dtype | None = None, + ) -> None: + """Queue an assert_size_stride for emission during replay.""" + self.writeline(AssertSizeStrideLine(self, name, size, stride, op_name, dtype)) + + def _codegen_assert_size_stride( + self, + code: IndentedBuffer, + name: str, + size: str, + stride: str, + op_name: str, + dtype: torch.dtype | None = None, + ) -> None: + """Emit one assert_size_stride line to `code` (replay-phase target). + + Subclasses override to change the emitted form (e.g., C++ assert with + an AOTI runtime env guard). + """ + if dtype is None: + code.writeline(f"assert_size_stride({name}, {size}, {stride}, {op_name!r})") + else: + self.add_import_once( + "from torch._inductor.runtime.runtime_utils import assert_tensor_metadata" + ) + code.writeline( + f"assert_tensor_metadata({name}, {size}, {stride}, {dtype}, {op_name!r})" + ) + + def write_assert_div_by_zero(self, divisor_str: str, op_name: str) -> None: + """Queue a div-by-zero AOTI check for emission during replay. + + codegen_cpp_sizevar is called in both build and replay phases; + set_writeline routes the WrapperLine appropriately in either case. + """ + self.writeline(AssertDivByZeroLine(self, divisor_str, op_name)) + + def _codegen_assert_div_by_zero( + self, code: IndentedBuffer, divisor_str: str, op_name: str + ) -> None: + """Emit one div-by-zero AOTI check to `code` (replay-phase target). + + Only emitted by C++ wrappers; the Python wrapper relies on Python's + native ZeroDivisionError instead of pre-checking divisors. + """ + raise NotImplementedError( + "AOTI div-by-zero check is only emitted by C++ wrappers" + ) + + def write_assert_size_stride_grouped( + self, asserts: list[tuple[str, str, str]], op_name: str + ) -> None: + """Queue a grouped assert_size_stride for emission during replay.""" + self.writeline(GroupedAssertSizeStrideLine(self, asserts, op_name)) + + def _codegen_assert_size_stride_grouped( + self, code: IndentedBuffer, asserts: list[tuple[str, str, str]], op_name: str + ) -> None: + names = ", ".join(name for name, _, _ in asserts) + sizes = ", ".join(size for _, size, _ in asserts) + strides = ", ".join(stride for _, _, stride in asserts) + code.writeline( + f"assert_size_stride_grouped(({names}), ({sizes}), ({strides}), {op_name!r})" + ) + + def register_alignment_check_inputs(self) -> None: + """Populate pending alignment copies for non-mutated inputs. + Called from the scheduler after mutated_input_idxs is computed.""" + if V.graph.cpp_wrapper: + return + inputs_to_check = V.graph.inputs_to_check + if not inputs_to_check: + return + # Mutated inputs are handled separately by the runtime wrapper, + # which needs to copy back the mutation after the call. + mutated_idxs = OrderedSet(V.graph.mutated_input_idxs) + for idx in inputs_to_check: + if idx not in mutated_idxs: + name = V.graph.graph_input_names[idx] + self._pending_alignment_copies.add(name) + if self._pending_alignment_copies: + V.graph._defers_input_alignment = True + self.imports.writeline( + "from torch._C._dynamo.guards import copy_if_misaligned" + ) + + def codegen_deferred_alignment_copies( + self, input_names: Iterable[str], stream: int = 0 + ) -> None: + """Emit alignment checks/clones for the given stream. + + An input with an alignment constraint needs that input to be + potentially reallocated. This emits the proper copy_if_misaligned calls + to perform that realignment. + + For inputs read on a simple stream this is trivial: we emit immediately + before the first reader. Inputs read on multiple streams get 1 copy per + stream, each reading from a preserved version of the original input. + This ensures we do not need to worry about ordering between multiple + streams. + """ + if V.graph.cpp_wrapper: + return + for name in input_names: + if name in self._pending_alignment_copies: + self._pending_alignment_copies.discard(name) + self.writeline(f"{name} = copy_if_misaligned({name})") + elif name in self._multistream_alignment_copies: + # TODO: if the same input is read again on a stream after an + # intervening different stream (e.g. s1, s2, s1) this re-clones + # on the second s1 use -- correct, but an extra copy. Tracking + # stream joins / per-(name, stream) clone names would let the + # later same-stream use reuse the earlier clone. + if self._alignment_aligned_stream.get(name) == stream: + continue + if name not in self._alignment_orig_saved: + # Preserve the original (still un-rewritten here) so every + # stream clones from it, not from another stream's clone. + self._alignment_orig_saved.add(name) + self.writeline(f"{name}_orig = {name}") + self.writeline(f"{name} = copy_if_misaligned({name}_orig)") + self._alignment_aligned_stream[name] = stream + + def mark_multistream_alignment(self, names: Iterable[str]) -> None: + """Reclassify inputs read on more than one stream so their alignment + copy is emitted per consuming stream (see codegen_deferred_alignment_copies) + rather than once at the first reader by line order -- which would place + the only copy inside one branch's stream and race the other branches.""" + for name in names: + if name in self._pending_alignment_copies: + self._pending_alignment_copies.discard(name) + self._multistream_alignment_copies.add(name) + + # this function (and below) takes the graph name as input so + # that stream caching happens per graph instance. this + # is important for nested subgraph codegening. + def write_get_raw_stream(self, device_idx: int, graph_name: str) -> str: + self.write_get_raw_stream_header() + name = get_raw_stream_name(device_idx) + if config.triton.autotune_at_compile_time: + # compile-on-one-rank: resolve at runtime so the autotune block matches the + # rank-agnostic call() body (see codegen_device_guard_enter). + autotune_idx = ( + V.graph.device_ops.current_device_idx_expr() + if _coor_enabled() + else device_idx + ) + self.kernel_autotune_calls.writeline( + f"{name} = get_raw_stream({autotune_idx})" + ) + if V.graph.cpp_wrapper: + # For cpp wrapper, no need to continue codegen for the main body + return name + self.writeline(f"{name} = get_raw_stream({_coor_device_idx_ref(device_idx)})") + return name + + def get_codegened_graph(self): + return self.codegened_graph_stack[-1] + + def push_codegened_graph(self, graph): + self.codegened_graph_stack.append(graph) + + def pop_codegened_graph(self): + return self.codegened_graph_stack.pop() + + def push_computed_sizes(self, computed_sizes): + from copy import deepcopy + + return self.computed_sizes_stack.append(deepcopy(computed_sizes)) + + def pop_computed_sizes(self): + return self.computed_sizes_stack.pop() + + def next_kernel_suffix(self) -> str: + return f"{next(self._names_iter)}" + + def codegen_device_guard_enter( + self, + device_idx: int, + num_streams: int = 1, + stream_idx_to_user_obj_idx: dict[int, int] | None = None, + ) -> None: + if num_streams > 1: + if stream_idx_to_user_obj_idx is None: + raise AssertionError("expected stream_idx_to_user_obj_idx to be set") + if not V.graph.cpp_wrapper: + import_line = ( + "from torch._dynamo.variables.streams import _get_stream_by_index" + ) + if not self.imports.contains(import_line): + self.imports.writeline(import_line) + setup_stream_cache = self._last_default_stream_device != device_idx + self._last_default_stream_device = device_idx + self.writeline( + EnterDeviceContextManagerWithStreamInfoLine( + device_idx, + self.last_seen_device_guard_index, + num_streams, + stream_idx_to_user_obj_idx, + setup_stream_cache=setup_stream_cache, + ), + ) + else: + self.writeline( + EnterDeviceContextManagerLine( + device_idx, self.last_seen_device_guard_index + ) + ) + if config.triton.autotune_at_compile_time: + # mimic logic of EnterDeviceContextManagerLine.codegen for the autotune code block + self.write_triton_header_once() + # compile-on-one-rank: resolve the device at runtime (like the call() body) so + # the autotune block is byte-identical across ranks, not baked to this rank's idx. + autotune_idx = ( + V.graph.device_ops.current_device_idx_expr() + if _coor_enabled() + else device_idx + ) + self.kernel_autotune_calls.writeline( + f"with {V.graph.device_ops.device_guard(autotune_idx)}:" + ) + self.kernel_autotune_calls.do_indent() + if is_codegen_graph_partition_subgraph(self): + # Need get_raw_stream for subgraph + self.write_get_raw_stream_header() + self.kernel_autotune_calls.writeline( + f"{get_raw_stream_name(device_idx)} = get_raw_stream({autotune_idx})" + ) + self.last_seen_device_guard_index = device_idx + self._num_streams: int = num_streams + + def codegen_device_guard_exit(self) -> None: + if hasattr(self, "_num_streams") and self._num_streams > 1: + self.writeline( + ExitDeviceContextManagerWithStreamInfoLine(self._num_streams) + ) + else: + self.writeline(ExitDeviceContextManagerLine()) + if config.triton.autotune_at_compile_time: + self.kernel_autotune_calls.do_unindent() + + def codegen_cuda_stream_enter( + self, + stream_idx: int, + ) -> EnterCudaStreamContextLine: + """Generate data structure for entering a CUDA Stream context. + + Args: + stream_idx: The index number of the entering CUDA Stream context. + + Raises: + ValueError: If this function is called while the previous stream context isn't exited. + """ + # pyre-fixme[16]: scheduler.current_stream_name added in scheduler commit + if (current_stream_name := V.graph.scheduler.current_stream_name) is not None: + raise ValueError( + f"Nested stream context switching: {current_stream_name} -> " + f"{get_stream_name(stream_idx)}", + ) + ctx_entrance = EnterCudaStreamContextLine(stream_idx=stream_idx) + self.writeline(ctx_entrance) + return ctx_entrance + + def codegen_cuda_stream_exit(self) -> None: + """Generate data structure for exiting a CUDA Stream context.""" + self.writeline(ExitCudaStreamContextLine()) + + def codegen_enter_cuda_stream_context( + self, code: IndentedBuffer, stream_idx: int + ) -> None: + code.writeline(f"with {get_stream_name(stream_idx)}:") + code.do_indent() + + def codegen_exit_cuda_stream_context(self, code: IndentedBuffer) -> None: + code.do_unindent() + + def codegen_stream_info_prologue( + self, + code: IndentedBuffer, + num_streams: int, + stream_idx_to_user_obj_idx: dict[int, int], + ) -> None: + raise NotImplementedError + + def codegen_cuda_mempool_enter(self, mempool: tuple[int, int]) -> None: + """Generate a CUDA MemPool context around code that may allocate.""" + if V.graph.cpp_wrapper: + raise AssertionError("CUDA MemPool contexts require Python wrapper") + import_line = ( + "from torch._dynamo.graph_bytecode_inputs import " + "get_external_object_by_index" + ) + if not self.imports.contains(import_line): + self.imports.writeline(import_line) + mempool_index, device_index = mempool + self.writeline(EnterCudaMemPoolContextLine(mempool_index, device_index)) + + def codegen_cuda_mempool_exit(self) -> None: + """Generate data structure for exiting the current CUDA MemPool context.""" + if V.graph.cpp_wrapper: + raise AssertionError("CUDA MemPool contexts require Python wrapper") + self.writeline(ExitCudaMemPoolContextLine()) + + def generate_return(self, output_refs: list[str]) -> None: + if output_refs: + if config.nan_asserts: + self.wrapper_call.writeline( + "return_vars = (" + ", ".join(output_refs) + ", )" + ) + self.wrapper_call.writeline("for var in return_vars:") + self.wrapper_call.do_indent() + self.wrapper_call.writeline("if isinstance(var, torch.Tensor):") + self.wrapper_call.do_indent() + self.wrapper_call.writeline("assert not var.isnan().any().item()") + self.wrapper_call.writeline("assert not var.isinf().any().item()") + self.wrapper_call.do_unindent(2) + + self.wrapper_call.writeline("return (" + ", ".join(output_refs) + ", )") + else: + self.wrapper_call.writeline("return ()") + + def generate_before_suffix(self, result: IndentedBuffer) -> None: + return + + def generate_after_suffix(self, result: IndentedBuffer) -> None: + if config.graph_partition: + all_partition_name_list = ", ".join(self.all_partition_names) + ( + "," if len(self.all_partition_names) == 1 else "" + ) + + result.splice( + f""" + runner = Runner(partitions=[{all_partition_name_list}]) + call = runner.call + recursively_apply_fns = runner.recursively_apply_fns + """ + ) + + def generate_end(self, result: IndentedBuffer) -> None: + return + + def generate_fallback_kernel(self, node: ir.FallbackKernel) -> None: + # Check if this op has a custom codegen implementation + op_name = node.python_kernel_name + if op_name is not None and op_name in CUSTOM_EXTERN_KERNEL_CODEGEN: + custom_codegen = CUSTOM_EXTERN_KERNEL_CODEGEN[op_name].python + if custom_codegen is not None: + custom_codegen(node, self.writeline) + return + self.writeline(ExternKernelAllocLine(self, node)) + + def generate_extern_kernel_multi_out(self, node: ir.ExternKernelMultiOut) -> None: + """Generate .out() call with pre-allocated output buffers.""" + for out_node in node.out_variant_output_nodes: + self.codegen_allocation(out_node) + self.writeline(ExternKernelMultiOutLine(self, node)) + for out_node in node.out_variant_output_nodes: + if isinstance(out_node.layout, ir.Layout): + out_node.codegen_size_asserts(self) + + def generate_extern_kernel_alloc(self, node: ir.ExternKernelAlloc): + node.codegen_comment(self) + self.writeline(ExternKernelAllocLine(self, node)) + if isinstance(node.layout, ir.Layout): + node.codegen_size_asserts(self) + + def _generate_extern_kernel_alloc_helper(self, extern_kernel, args): + # If it's a NoneLayout then the extern_kernel should essentially be + # treated as if it doesn't return anything + no_return = isinstance(extern_kernel.layout, ir.NoneLayout) + output_name = extern_kernel.get_name() + origin_node = extern_kernel.get_origin_node() + kernel_name = extern_kernel.get_kernel_name() + ending = self.ending + if config.memory_planning and "view_as_complex" in kernel_name: + # view operation fallbacks cause issues since inductor + # doesn't know the memory is still needed and might reuse it. + ending = f".clone(){ending}" + + if config.trace.provenance_tracking_to_timeline: + wrapper_name = self.define_extern_kernel_profile_wrapper( + kernel_name, self.next_kernel_suffix() + ) + else: + wrapper_name = kernel_name + + if no_return: + self.writeline(f"{self.declare}{wrapper_name}({', '.join(args)}){ending}") + else: + self.writeline( + f"{self.declare}{output_name} = {wrapper_name}({', '.join(args)}){ending}" + ) + if ( + self.supports_intermediate_hooks + and config.generate_intermediate_hooks + and origin_node is not None + ): + counters["inductor"]["intermediate_hooks"] += 1 + self.writeline( + f"run_intermediate_hooks({origin_node.name!r}, {output_name})" + ) + + def generate_extern_kernel_out( + self, + node: ir.ExternKernelOut, + ) -> None: + node.codegen_comment(self) + self.writeline(ExternKernelOutLine(self, node)) + + def _generate_extern_kernel_out_helper( + self, + kernel: str, + out: str, + out_view: str | None, + args: list[str], + device: str, + stack_traces: OrderedSet[str] | None = None, + ) -> None: + # add debug printer code for triton kernel calls at (jit) inductor level + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args(args, kernel, None, None, "extern") + args.append(f"out={out_view or out}") + with debug_printer_manager: + if config.trace.provenance_tracking_to_timeline: + wrapper_name = self.define_extern_kernel_profile_wrapper( + kernel, self.next_kernel_suffix() + ) + else: + wrapper_name = kernel + self.writeline(f"{wrapper_name}({', '.join(args)})") + + def _generate_tma_descriptor_call_experimental(self, desc, apply_size_hints=False): + dims = desc.dims + block_dims = desc.block_dims + if apply_size_hints: + dims = V.graph.sizevars.optimization_hint(dims) + block_dims = V.graph.sizevars.optimization_hints(block_dims) + + ptr = f"{desc.tensor.codegen_reference()}.data_ptr()" + # Explicitly call the Python version of val_to_arg_str + dims = ", ".join(PythonWrapperCodegen.val_to_arg_str(self, dim) for dim in dims) + block_dims = ", ".join( + PythonWrapperCodegen.val_to_arg_str(self, dim) for dim in block_dims + ) + element_size = PythonWrapperCodegen.val_to_arg_str(self, desc.element_size) + prefix = "triton.tools.experimental_descriptor" + fn = f"{prefix}.create_{desc.rank}d_tma_descriptor" + args = f"{ptr}, {dims}, {block_dims}, {element_size}" + call = f"{fn}({args})" + return call + + def _generate_tma_descriptor_call_stable(self, desc, apply_size_hints=False): + block_shape = desc.block_shape + if apply_size_hints: + block_shape = V.graph.sizevars.optimization_hints(block_shape) + + prefix = "triton.tools.tensor_descriptor.TensorDescriptor" + fn = f"{prefix}.from_tensor" + args = f"{desc.tensor.codegen_reference()}, {block_shape}" + call = f"{fn}({args})" + return call + + def _generate_tma_descriptor_call(self, desc, apply_size_hints=False): + if isinstance(desc, ir.TMADescriptorExperimental): + return self._generate_tma_descriptor_call_experimental( + desc, apply_size_hints + ) + else: + if not isinstance(desc, ir.TMADescriptorStable): + raise AssertionError(f"expected TMADescriptorStable, got {type(desc)}") + return self._generate_tma_descriptor_call_stable(desc, apply_size_hints) + + def generate_tma_descriptor(self, desc): + call = self._generate_tma_descriptor_call(desc) + line = f"{desc.name} = {call}{self.ending}" + self.writeline(line) + + def generate_scatter_fallback(self, node: ir.ScatterFallback): + self.writeline(ScatterFallbackLine(self, node)) + + def _generate_scatter_fallback( + self, + output, + inputs, + cpp_kernel_name, + python_kernel_name, + src_is_tensor, + reduce, + kwargs, + device, + ): + orig_python_kernel_name = python_kernel_name + if config.trace.provenance_tracking_to_timeline: + python_kernel_name = self.define_extern_kernel_profile_wrapper( + python_kernel_name, self.next_kernel_suffix() + ) + line = f"{python_kernel_name}({','.join(map(str, inputs))}" + if orig_python_kernel_name.startswith("aten.scatter_reduce"): + line += ", ".join([""] + kwargs) + elif reduce: + line += f", reduce={repr(reduce)}" + line += ")" + self.writeline(line) + + def define_extern_kernel_profile_wrapper(self, kernel_name: str, suffix: str): + """Wrap extern calls so profiler events use names with provenance metadata.""" + wrapper_kernel_name = re.sub( + r"\W", + "_", + f"extern_kernels_{kernel_name}_{suffix}", + ) + inductor_debug.alias_kernel_provenance(kernel_name, wrapper_kernel_name) + self.header.splice(f"def {wrapper_kernel_name}(*args, **kwargs):") + with self.header.indent(): + self.header.splice( + "# Extra indirection is only enabled for profiler timeline provenance." + ) + self.header.splice(f"return {kernel_name}(*args, **kwargs)") + return wrapper_kernel_name + + def generate_index_put_fallback(self, node: ir.IndexPutFallback) -> None: + # Collect index tensors into a list. + indices: list[ir.IRNode | None] = [] + valid_indices = node.inputs[2:] + iter_valid_indices = iter(valid_indices) + for i, _ in enumerate(node.indices): + if node.indices[i] is not None: + index = next(iter_valid_indices) + if not isinstance(index, ir.IRNode): + raise AssertionError(f"expected IRNode, got {type(index)}") + indices.append(index) + else: + indices.append(None) + + self.writeline(IndexPutFallbackLine(self, node, indices)) + + def _generate_index_put_fallback(self, kernel, x, indices, values, accumulate): + indices_str = f"[{', '.join(indices)}]" + args = [x, indices_str, values, accumulate] + self.writeline(self.wrap_kernel_call(kernel, args)) + + def generate_fallback_kernel_with_runtime_lookup( + self, + buf_name: str, + python_kernel_name: str, + get_args: Callable[[], Sequence[str]], + op_overload: torch._ops.OpOverload | torch._ops.HigherOrderOperator, + raw_args: Sequence[Any], + outputs: Sequence[ir.Buffer], + ) -> None: + self.writeline(f"{buf_name} = {python_kernel_name}({', '.join(get_args())})") + + def generate(self, is_inference): + with dynamo_timed("PythonWrapperCodegen.generate"): + return self._generate(is_inference) + + def get_wrapper_call_indent(self) -> int: + if config.graph_partition: + return 2 + else: + return 1 + + @contextlib.contextmanager + def set_writeline( + self, + target: IndentedBuffer, + writeline: Callable[..., None], + ) -> Iterator[Callable[..., None]]: + """Temporarily redirect self.writeline to write into `target`. + + Plain strings go through `writeline`. + WrapperLines are codegen'd into `target` directly. + """ + old = self.writeline + + def dispatch(line: LineContext | DeferredLineBase | WrapperLine | str) -> None: + if isinstance(line, WrapperLine): + # pyrefly: ignore [missing-attribute] + line.codegen(target) + else: + writeline(line) + + try: + self.writeline = dispatch # type: ignore[method-assign] + yield dispatch + finally: + self.writeline = old # type: ignore[method-assign] + + def _write_multi_kernel_defs(self) -> None: + kernel_defs = self.multi_kernel_state.kernel_defs + if config.triton.autotune_at_compile_time: + self.kernel_autotune_defs.splice(kernel_defs) + else: + self.header.splice(kernel_defs) + + def _generate(self, is_inference): + if config.profile_bandwidth: + self.write_triton_header_once() + + with contextlib.ExitStack() as stack: + stack.enter_context(self.wrapper_call.indent()) + if config.profiler_mark_wrapper_call: + self.generate_profiler_mark_wrapper_call(stack) + if config.profile_bandwidth: + self.generate_start_graph() + + self.run_wrapper_ir_passes(is_inference) + + if config.triton.store_cubin and not config.triton.autotune_at_compile_time: + self.generate_reset_kernel_saved_flags() + + # At this point, we shouldn't generate any new memory planning lines. + # Override writeline to point at the wrapper call, in case it gets called. + with self.set_writeline(self.wrapper_call, self.wrapper_call.writeline): + for line in self.lines: + if isinstance(line, WrapperLine): + # pyrefly: ignore [missing-attribute] + line.codegen(self.wrapper_call) + else: + self.wrapper_call.writeline(line) + + self._write_multi_kernel_defs() + + output_refs = self.get_output_refs() + self.mark_output_type() + if config.triton.debug_sync_graph: + self.generate_debug_sync(self.wrapper_call) + + if config.profile_bandwidth: + self.generate_end_graph() + + if config.triton.proton_profiling: + self.generate_proton_finalize() + + if config.triton.store_cubin and not config.triton.autotune_at_compile_time: + self.generate_save_uncompiled_kernels() + + if config.triton.autotune_at_compile_time: + self.generate_and_run_autotune_block() + + # cpp_wrapper currently doesn't support nvtx + if config.annotate_training and not config.cpp_wrapper: + self.wrapper_call.writeline( + "nvtx._device_range_end(training_annotation)" + ) + self.generate_return(output_refs) + + # Assemble the final code from sections. + result = IndentedBuffer() + result.splice(self.imports) + result.writeline("") + result.splice(self.header) + # Intermediate const graphs normally use headers rendered by the main + # module. In dual-wrapper-mode, the const graph's JIT wrapper is emitted as + # standalone C++ and needs its own header. + if ( + V.graph.aot_mode + and V.graph.cpp_wrapper + and V.graph.is_const_graph + and not V.graph.is_dual_wrapper_mode + ): + result = IndentedBuffer() + + # Add subgraph definitions to the result + result.splice(self.subgraph_definitions) + self.finalize_prefix() + result.splice(self.prefix) + + wrapper_call_indent = self.get_wrapper_call_indent() + + with result.indent(wrapper_call_indent): + result.splice(self.wrapper_call) + + self.generate_before_suffix(result) + result.splice(self.suffix) + self.generate_after_suffix(result) + + self.generate_end(result) + + self.add_benchmark_harness(result) + + return ( + result.getvaluewithlinemap(), + self.kernel_declarations.getvaluewithlinemap(), + ) + + def generate_and_run_autotune_block(self): + """ + Compose self.kernel_autotune_defs and self.kernel_autotune_calls into a single block of + code and execute it to trigger Triton kernel compilation and auto-tuning + """ + self.kernel_autotune_defs.splice( + """ + async_compile.wait(globals()) + del async_compile + """ + ) + scope = {} # type: ignore[var-annotated] + if config.triton.autotune_at_compile_time and V.graph.autotuning_inputs: + scope = { + self.get_autotuning_input_name(idx): v # type: ignore[attr-defined] + for idx, v in enumerate(V.graph.autotuning_inputs) + } + tuning_code = ( + self.kernel_autotune_defs.getvalue() + + "\n" + + self.kernel_autotune_calls.getvalue() + ) + if output_code_log.level == logging.DEBUG: + # Save the autotuning code block into a file + # Create a temporary file + with tempfile.NamedTemporaryFile( + dir=cache_dir(), suffix=".py", delete=False + ) as f: + f.write(tuning_code.encode("utf-8")) + file_path = f.name + output_code_log.debug( + "Auto-tuning code written to %s", + file_path, + ) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_autotune_at_compile_time_code", + "encoding": "string", + }, + payload_fn=lambda: tuning_code, + ) + # Execute the code to autotune kernels + try: + exec(tuning_code, scope) + except Exception as e: + raise RuntimeError(f"Failed to run autotuning code block: {e}") from e + + def memory_plan(self): + from .memory_planning import MemoryPlanner + + self.lines = MemoryPlanner(self).plan(self.lines) + + def memory_plan_reuse(self): + outputs = self.get_graph_outputs() + out_names = V.graph._get_output_names(outputs) + + while ( + self.lines + and isinstance(self.lines[-1], MemoryPlanningLine) + # TODO: this seems legit, NullLine has no node + and self.lines[-1].node.name not in out_names # type: ignore[attr-defined] + ): + # these lines will be pointless + self.lines.pop() + + # codegen allocations in two passes + planning_states = [MemoryPlanningState()] + past_planning_states = [] + peak_estimate_stack: list[EfficientPeakEstimate] = [] + for i in range(len(self.lines)): + line = self.lines[i] + if isinstance(line, MemoryPlanningLine): + self.lines[i] = line.plan(planning_states[-1]) + elif isinstance(line, EnterSubgraphLine): + planning_states.append(MemoryPlanningState()) + if config.allow_buffer_reuse: + peak_estimate_stack.append(self.estimate_peak) + with V.set_graph_handler(line.graph): + self.estimate_peak = EfficientPeakEstimate() + elif isinstance(line, ExitSubgraphLine): + past_planning_states.append(planning_states.pop()) + if config.allow_buffer_reuse: + self.estimate_peak = peak_estimate_stack.pop() + past_planning_states.append(planning_states.pop()) + if len(planning_states) != 0: + raise AssertionError( + f"expected no remaining planning states, got {len(planning_states)}" + ) + + # conservatively use the sum of all allocated buffer sizes + # in potentially nested scopes as the total allocated size + # FIXME(rec): not used + _total_allocated_buffer_size = sum( + s.total_allocated_buffer_size for s in past_planning_states + ) + + def run_wrapper_ir_passes(self, is_inference: bool): + # We disable planning during training because it presently increases peak memory consumption. + if is_inference and config.memory_planning: + self.memory_plan() + else: + if config.allow_buffer_reuse: + self.estimate_peak = EfficientPeakEstimate() + self.memory_plan_reuse() + + def maybe_emit_replacement_aliases( + self, + sym: sympy.Symbol, + bound_vars: OrderedSet[sympy.Symbol], + ) -> None: + # Deferred runtime asserts and graph input metadata can reference + # either side of a backed-symbol replacement. Emit aliases so both + # the pre-replacement and canonical names are defined. Skip unbacked + # symbols - they are defined separately by the unbacked symbol + # codegen path. + sizevars = getattr(V.graph, "sizevars", None) + shape_env = getattr(sizevars, "shape_env", None) + if shape_env is None: + return + + def is_backed_symbol(s: sympy.Symbol) -> bool: + return not symbol_is_type(s, (SymT.UNBACKED_INT, SymT.UNBACKED_FLOAT)) + + for src, tgt in shape_env.replacements.items(): + if ( + tgt == sym + and isinstance(src, sympy.Symbol) + and src not in bound_vars + and is_backed_symbol(src) + and is_backed_symbol(sym) + ): + self.prefix.writeline(f"{src} = {sym}") + bound_vars.add(src) + elif ( + src == sym + and isinstance(tgt, sympy.Symbol) + and tgt not in bound_vars + and is_backed_symbol(sym) + and is_backed_symbol(tgt) + ): + self.prefix.writeline(f"{tgt} = {sym}") + bound_vars.add(tgt) + + def codegen_input_symbol_assignment( + self, + name: str, + value: ir.TensorBox | sympy.Expr, + bound_vars: OrderedSet[sympy.Symbol], + deferred_symbol_assignments=None, + ): + if isinstance(value, sympy.Expr): + raw_value = value + value = V.graph.sizevars.simplify(raw_value) + if isinstance(value, sympy.Symbol) and value not in bound_vars: + self.prefix.writeline(f"{value} = {name}") + bound_vars.add(value) + self.maybe_emit_replacement_aliases(value, bound_vars) + if isinstance(raw_value, sympy.Symbol): + if raw_value not in bound_vars: + self.prefix.writeline(f"{raw_value} = {name}") + bound_vars.add(raw_value) + return + if not isinstance(value, sympy.Symbol): + return + elif isinstance( + value, + ( + ir.TensorBox, + ir.TorchBindObject, + ir.GeneratorState, + ir.OpaqueObjectState, + ), + ): + return + else: + if torch._inductor.config.graph_partition: + pass + else: + raise AssertionError(f"Unknown value type: {type(value)}") + + def _retry_deferred_symbol_assignments(self, deferred_symbol_assignments) -> None: + while deferred_symbol_assignments: + next_deferred_symbol_assignments = [] + progress = False + for assignment in deferred_symbol_assignments: + progress = assignment(next_deferred_symbol_assignments) or progress + if not progress: + break + deferred_symbol_assignments = next_deferred_symbol_assignments + + def bind_input_symbol( + self, + sym: sympy.Symbol, + input_name: str, + kind: Literal["size", "stride"], + dim: int, + bound_vars: OrderedSet[sympy.Symbol], + ) -> None: + if sym in bound_vars: + return + if kind == "size": + self.prefix.writeline(f"{sym} = {input_name}.size()[{dim}]") + else: + self.prefix.writeline(f"{sym} = {input_name}.stride()[{dim}]") + bound_vars.add(sym) + self.maybe_emit_replacement_aliases(sym, bound_vars) + + def codegen_inputs(self): + """Assign input symbolic shapes to wrapper-local variables.""" + bound_vars = OrderedSet[sympy.Symbol]() + # There is a subtle case in the cpp wrapper codegen which requires generating + # symbol inputs first followed by non-symbol ones. + # + # When a dynamic size constraint specified at the Export time is an expression, + # we need to solve that expression to proper define a symbol in cpp. Thus we + # are enforcing this iterating order here to make sure all plain size symbols + # are defined first. + graph_inputs = self.get_graph_inputs() + inputs = [ + (k, v) for k, v in graph_inputs.items() if isinstance(v, sympy.Symbol) + ] + [(k, v) for k, v in graph_inputs.items() if not isinstance(v, sympy.Symbol)] + deferred_symbol_assignments = [] + for name, value in inputs: + self.codegen_input_symbol_assignment( + name, value, bound_vars, deferred_symbol_assignments + ) + self._retry_deferred_symbol_assignments(deferred_symbol_assignments) + + @functools.cache + def sizeof(name): + self.prefix.writeline(f"{name}_size = {name}.size()") + return f"{name}_size" + + @functools.cache + def strideof(name): + self.prefix.writeline(f"{name}_stride = {name}.stride()") + return f"{name}_stride" + + def bind_input_expr_symbols( + expr: sympy.Symbol | sympy.Expr, + input_name: str, + kind: Literal["size", "stride"], + dim: int, + deferred_symbol_assignments=None, + ) -> bool: + name_fn = sizeof if kind == "size" else strideof + if isinstance(expr, sympy.Symbol): + if expr in bound_vars: + return False + self.prefix.writeline(f"{expr} = {name_fn(input_name)}[{dim}]") + bound_vars.add(expr) + self.maybe_emit_replacement_aliases(expr, bound_vars) + return True + + if not isinstance(expr, sympy.Expr): + return False + + undefined_symbols = [ + sym for sym in expr.free_symbols if sym not in bound_vars + ] + if len(undefined_symbols) != 1: + if ( + len(undefined_symbols) > 1 + and deferred_symbol_assignments is not None + ): + + def retry(deferred_symbol_assignments): + return bind_input_expr_symbols( + expr, + input_name, + kind, + dim, + deferred_symbol_assignments, + ) + + deferred_symbol_assignments.append(retry) + return False + + from torch.utils._sympy.solve import try_solve + + free_symbol = undefined_symbols.pop() + base_name = name_fn(input_name) + dim_symbol = sympy.Symbol(f"{base_name}_{dim}", integer=True) + solution = try_solve(sympy.Eq(expr, dim_symbol), free_symbol) + if solution is None: + return False + + self.prefix.writeline(f"{dim_symbol} = {base_name}[{dim}]") + solution_expr = _rewrite_symbol_solution_for_int_codegen(solution[1]) + self.prefix.writeline(f"{free_symbol} = {pexpr(solution_expr)}") + bound_vars.add(free_symbol) + self.maybe_emit_replacement_aliases(free_symbol, bound_vars) + return True + + for sym, (input_name, kind, dim) in V.graph.symbolic_input_sources.items(): + sym = V.graph.sizevars.simplify(sym) + if not isinstance(sym, sympy.Symbol): + continue + if sym in bound_vars: + continue + if input_name not in graph_inputs: + continue + self.bind_input_symbol(sym, input_name, kind, dim, bound_vars) + + for input_name, value in inputs: + if not isinstance(value, ir.TensorBox): + continue + is_named_graph_input = input_name in V.graph.graph_input_names + bind_assert_symbols = config.size_asserts and ( + is_named_graph_input and sympy_product(value.get_size()) != 0 + ) + for dim, raw_size in enumerate(value.get_size()): + if bind_assert_symbols: + bind_input_expr_symbols( + raw_size, + input_name, + "size", + dim, + deferred_symbol_assignments, + ) + size = V.graph.sizevars.simplify(raw_size) + if bind_assert_symbols and size != raw_size: + bind_input_expr_symbols( + size, + input_name, + "size", + dim, + deferred_symbol_assignments, + ) + for dim, raw_stride in enumerate(value.get_stride()): + if bind_assert_symbols: + bind_input_expr_symbols( + raw_stride, + input_name, + "stride", + dim, + deferred_symbol_assignments, + ) + stride = V.graph.sizevars.simplify(raw_stride) + if bind_assert_symbols and stride != raw_stride: + bind_input_expr_symbols( + stride, + input_name, + "stride", + dim, + deferred_symbol_assignments, + ) + self._retry_deferred_symbol_assignments(deferred_symbol_assignments) + + def _verify_input_symbol_assignment( + input_name: str, + value: ir.TensorBox, + bound_vars: OrderedSet[sympy.Symbol], + ): + is_named_graph_input = input_name in V.graph.graph_input_names + verify_assert_symbols = config.size_asserts and ( + is_named_graph_input and sympy_product(value.get_size()) != 0 + ) + for expr in chain.from_iterable([value.get_size(), value.get_stride()]): + if not isinstance(expr, Expr) or isinstance(expr, sympy.Symbol): + continue + expr = V.graph.sizevars.simplify(expr) + if not isinstance(expr, Expr): + continue + + undefined_symbols = [ + sym + for sym in expr.free_symbols + if sym not in bound_vars and verify_assert_symbols + ] + if len(undefined_symbols) > 0: + raise AssertionError( + f"For {expr}, expected {undefined_symbols} to have been codegen-ed." + ) + + # For inputs with size/strides which contain sympy expressions, we can + # encounter symbols that weren't defined yet. Now, let's check each + # symbol is defined. + for input_name, value in inputs: + if not isinstance(value, ir.TensorBox): + continue + _verify_input_symbol_assignment(input_name, value, bound_vars) + + def ensure_size_computed(self, sym: sympy.Symbol): + if isinstance(sym, sympy.Symbol) and symbol_is_type(sym, SymT.PRECOMPUTED_SIZE): + if sym in self.computed_sizes: + return + self.computed_sizes.add(sym) + expr = V.graph.sizevars.inv_precomputed_replacements[sym] + arg = SymbolicCallArg(sym, expr) + self.writeline(SymbolicCallArgLine(self, arg, V.graph)) + + def finalize_prefix(self): + pass + + def codegen_cpp_sizevar(self, x: Expr, *, simplify: bool = True) -> str: + raise RuntimeError("codegen_cpp_sizevar is only implemented for cpp_wrapper!") + + def codegen_python_sizevar(self, x: Expr, *, simplify: bool = True) -> str: + return pexpr(x, simplify=simplify) + + def codegen_sizevar(self, x: Expr) -> str: + return self.codegen_python_sizevar(x) + + def codegen_tuple_access(self, basename: str, name: str, index: str) -> str: + return f"{basename}[{index}]" + + def codegen_python_shape_tuple(self, shape: Sequence[Expr]) -> str: + parts = [*map(self.codegen_python_sizevar, shape)] + if len(parts) == 0: + return "()" + if len(parts) == 1: + return f"({parts[0]}, )" + return f"({', '.join(parts)})" + + def codegen_shape_tuple(self, shape: Sequence[Expr]) -> str: + return self.codegen_python_shape_tuple(shape) + + def codegen_alloc_from_pool( + self, name, offset, dtype, shape, stride + ) -> tuple[str, list[str]]: + return "alloc_from_pool({})".format( + ", ".join( + [ + name, + pexpr(offset), # bytes not numel + str(dtype), + self.codegen_python_shape_tuple(shape), + self.codegen_python_shape_tuple(stride), + ] + ) + ), [] + + def codegen_reinterpret_view( + self, + data, + size, + stride, + offset, + writeline: Callable[..., None], + dtype=None, + ) -> str: + # Get the innermost buffer's layout info to help reinterpret view. + # Consider a chain of (ReinterpretView <- TensorBox| StorageBox)... <- buffer + # If we only use x.data to determine the reinterpret, we may get wrong layout. + # For example: + # x = ReinterpretView( + # Storage( + # ReinterpretView( + # storage( + # Buffer(name='buf0', layout=(size=(2, 5, 10), ...) + # ), + # layout=(10, 10), + # ), + # ), + # layout=(10, 10), + # ) + # In this case, x.data.layout == x.layout is (10, 10), the reinterpret view will return buf0, + # but buf0 need to be viewed from (2, 5, 10) to (10, 10). + # So we need to dig into the chain to find the innermost buffer's layout. + d_size, d_stride, d_offset, d_dtype, collapsible = ( + codegen_reinterpret_view_helper(data) + ) + + def apply_reinterpret( + name, tgt_size, tgt_stride, tgt_offset, cast_dtype, base_dtype + ): + s = self.codegen_python_shape_tuple(tgt_size) + st = self.codegen_python_shape_tuple(tgt_stride) + off = self.codegen_sizevar(tgt_offset) + expr = f"reinterpret_tensor({name}, {s}, {st}, {off})" + if cast_dtype is not None and cast_dtype != base_dtype: + return f"aten.view.dtype({expr}, {cast_dtype})" + return expr + + name = data.get_name() + collapsed = collapsible and offset == d_offset + if collapsed: + same_layout = size == d_size and stride == d_stride + base_dtype = d_dtype + else: + same_layout = ( + size == data.layout.size + and stride == data.layout.stride + and offset == data.layout.offset + ) + base_dtype = data.dtype + + if same_layout: + if dtype is not None and dtype != base_dtype: + return f"aten.view.dtype({name}, {dtype})" + return f"{name}" + + return apply_reinterpret(name, size, stride, offset, dtype, base_dtype) + + def codegen_device_copy(self, src, dst, non_blocking: bool | str): + self.writeline(f"{dst}.copy_({src}, {non_blocking})") + + def sync_d2h_copy(self, buffer_name: str) -> None: + event_var = f"_d2h_event_{buffer_name}" + self.writeline(f"{event_var} = torch.Event()") + self.writeline(f"{event_var}.record()") + self.writeline(f"{event_var}.synchronize()") + + def codegen_multi_output(self, node: ir.MultiOutput): + result_name = node.get_name() + arg_name = node.input_name(0) + self.writeline(MultiOutputLine(self, result_name, arg_name, node.indices)) + + def codegen_dynamic_select_index(self, node, clamp): + index_str = f"{node.index} + {node.size} if {node.index} < 0 else {node.index}" + if clamp: + index_str = f"max(0, min({node.size}, {index_str}))" + self.writeline( + f"{node.unbacked_offset_symbol} = {node.base_offset} + {node.base_dim_stride} * ({index_str})" + ) + # record in unbacked_symbol_decls so we won't generate a declaration of the symbol again + self.unbacked_symbol_decls.add(str(node.unbacked_offset_symbol)) + + def codegen_dynamic_slice_size(self, node): + def clamp_index(x): + pos = self.codegen_sizevar(Max(0, Min(x, node.size))) + neg = self.codegen_sizevar(Max(0, Min(x + node.size, node.size))) + x_cond = self.codegen_sizevar(x) + return f"{pos} if {x_cond} >= 0 else {neg}" + + def codegen_with_step(start_var, end_var, step): + if step == 1: + return f"{end_var} - {start_var}" + step_ = self.codegen_sizevar(step) + return f"({end_var} - {start_var} + {step_} - 1) // {step_}" + + # codegen start, end + sym = node.unbacked_size_symbol + start = clamp_index(node.start) + end = clamp_index(node.end) + self.writeline(f"{sym}_start = {start}") + self.writeline(f"{sym}_end = {end}") + with_step = codegen_with_step(f"{sym}_start", f"{sym}_end", node.step) + self.writeline(f"{sym} = max(0, {with_step})") + self.unbacked_symbol_decls.add(str(node.unbacked_size_symbol)) + + def codegen_dynamic_scalar(self, node): + self.writeline(DynamicScalarLine(self, node)) + + def _codegen_dynamic_scalar(self, node): + (data,) = (t.codegen_reference() for t in node.inputs) + if len(node.keypath) == 0: + self.writeline(f"{node.sym} = {data}.item()") + elif len(node.keypath) == 1 and isinstance(node.keypath[0], ConvertIntKey): + self.writeline(f"{node.sym} = 1 if {data}.item() else 0") + elif len(node.keypath) == 1 and isinstance(node.keypath[0], DivideByKey): + self.writeline(f"{node.sym}_undivided = {data}.item()") + self.writeline( + f"assert {node.sym}_undivided % {node.keypath[0].divisor} == 0, " + f"f'{{{node.sym}_undivided}} not divisible by {node.keypath[0].divisor}'" + ) + self.writeline( + f"{node.sym} = {node.sym}_undivided // {node.keypath[0].divisor}" + ) + else: + raise AssertionError(f"unrecognized keypath {node.keypath}") + # No one should ever use this buffer, but for uniformity + # define the variable and assign it None + self.writeline(f"{node.get_name()} = None") + + def _coor_device_type_str(self, device: torch.device) -> str: + """Render a device for the benchmark harness rank-agnostically: the bare device type + (no rank-specific index), so it is byte-identical across ranks. cpu/meta have no index + and pass through unchanged; a non-current accelerator violates the single-device + invariant and is refused. Under compile-on-one-rank the current accelerator is read + once per compilation and cached on the wrapper; once cached, the per-input/buffer + harness loops repeat neither the enabled check nor the cudaGetDevice. + """ + cur = self._coor_current_accelerator + if cur is None: + cur = _coor_current_accelerator() if _coor_enabled() else False + self._coor_current_accelerator = cur + if cur is False: + return str(device) + _coor_check_current_accelerator(device, cur) + return device.type + + def benchmark_compiled_module(self, output): + """Write out codegen for benchmarking the output code""" + + def add_fake_input(name, shape, stride, device, dtype): + output.writeline( + f"{name} = rand_strided(" + f"{self.codegen_python_shape_tuple(shape)}, " + f"{self.codegen_python_shape_tuple(stride)}, " + f"device='{self._coor_device_type_str(device)}', dtype={dtype})" + ) + + def add_expr_input(name, val): + output.writeline(f"{name} = {val}") + + def add_torchbind_input(name, value): + if value is None: + output.writeline(f"{name} = None") + return + + import pickle + + try: + output.writeline(f"{name} = pickle.loads({pickle.dumps(value)!r})") + except (TypeError, AttributeError, pickle.PicklingError) as e: + output.writeline( + f'raise TypeError("Failed to pickle opaque type {type(value)} for variable {name}: {str(e)}")' + ) + + # Preserve shared non-empty input storages so benchmark code does not + # explode large aliased views into separate allocations. + storage_groups: dict[StorageWeakRef, BenchmarkStorageGroup] = {} + aliased_input_specs: dict[str, tuple[str, Any, Any]] = {} + example_inputs = V.graph.example_inputs + + if example_inputs is not None: + for name, ex in zip(V.graph.graph_inputs.keys(), example_inputs): + if not isinstance(ex, torch.Tensor): + continue + storage = ex.untyped_storage() + nbytes = storage.nbytes() + storage_key = StorageWeakRef(storage) + group = storage_groups.get(storage_key) + if group is None: + group = BenchmarkStorageGroup( + buffer_name=f"_shared_storage_{len(storage_groups)}", + nbytes=nbytes, + device=ex.device, + dtype=ex.dtype, + inputs={}, + ) + storage_groups[storage_key] = group + + group.inputs[name] = (list(ex.shape), list(ex.stride())) + + # Generate get_args() to create input tensors separately from benchmarking + output.writelines(["", "", "def get_args():"]) + with output.indent(): + output.splice( + """ + from torch._dynamo.testing import rand_strided + """, + strip=True, + ) + + for name, value in V.graph.constants.items(): + # all the constants are global variables, that's why we need + # these 'global var_name' lines + output.writeline(f"global {name}") + add_fake_input( + name, value.size(), value.stride(), value.device, value.dtype + ) + + if len(V.graph.torchbind_constants) > 0: + output.writeline("import pickle") + for name, torchbind_obj in V.graph.torchbind_constants.items(): + # all the constants are global variables, that's why we need + # these 'global var_name' lines + output.writeline(f"global {name}") + add_torchbind_input(name, torchbind_obj) + + # Generate shared storage buffers for aliased inputs + for group in storage_groups.values(): + if len(group.inputs) < 2: + continue + numel = group.nbytes // torch._utils._element_size(group.dtype) + output.writeline( + f"{group.buffer_name} = rand_strided(({numel},), (1,), device='{self._coor_device_type_str(group.device)}', dtype={group.dtype})" + ) + for name, (shape, stride) in group.inputs.items(): + aliased_input_specs[name] = (group.buffer_name, shape, stride) + + for name, value in V.graph.graph_inputs.items(): + if isinstance(value, sympy.Symbol) and isinstance( + V.graph.sizevars.backed_var_to_val.get(value, None), SingletonInt + ): + # Inductor should only work with dense -> dense graph, and + # SingletonInts belong to metadata that should only live on + # the subclass. + continue + if isinstance(value, ir.TorchBindObject): + output.writeline(f"{name} = None") + elif isinstance(value, sympy.Expr): # Don't need to add symbolic + # TODO: this fallback and those below actually will generate possibly + # invalid benchmark code, because it's not guaranteed 42 + # is actually a valid value for the kernel in question. + # See https://github.com/pytorch/pytorch/issues/124686 + add_expr_input( + name, V.graph.sizevars.optimization_hint(value, fallback=42) + ) + elif isinstance(value, sympy.Basic): + # sympy.Boolean (e.g. StrictLessThan from torch.cond predicates) + # is not a sympy.Expr so optimization_hint cannot handle it. + # Use False as a fallback for benchmark harness purposes. + add_expr_input(name, False) + elif isinstance(value, ir.GeneratorState): + # Harness runs outside the runtime device guard, so resolve the index + # with current_device() (the _coor_device_idx var is not in scope here). + gen_idx = ( + V.graph.device_ops.current_device_idx_expr() + if _coor_enabled() + else value.device.index + ) + add_expr_input( + name, + f"torch.cuda.default_generators[{gen_idx}].graphsafe_get_state()", + ) + elif isinstance(value, ir.OpaqueObjectState): + output.writeline(f"{name} = None") + elif name in aliased_input_specs: + buf_name, shape, stride = aliased_input_specs[name] + output.writeline( + f"{name} = torch.as_strided({buf_name}, " + f"{self.codegen_python_shape_tuple(shape)}, " + f"{self.codegen_python_shape_tuple(stride)})" + ) + else: + shape = V.graph.sizevars.optimization_hints( + value.get_size(), fallback=42 + ) + stride = V.graph.sizevars.optimization_hints( + value.get_stride(), fallback=42 + ) + + add_fake_input( + name, + shape, + stride, + value.get_device(), + value.get_dtype(), + ) + + output.writeline(f"return [{', '.join(V.graph.graph_inputs.keys())}]") + + # Generate benchmark_compiled_module() that takes args as parameter + output.writelines( + ["", "", "def benchmark_compiled_module(args, times=10, repeat=10):"] + ) + with output.indent(): + output.splice( + f""" + from torch._inductor.utils import print_performance + fn = lambda: call(list(args)) + return print_performance(fn, times=times, repeat=repeat, device='{V.graph.device_type}') + """, + strip=True, + ) + + def add_benchmark_harness(self, output): + """ + Append a benchmark harness to generated code for debugging + """ + if not config.benchmark_harness: + return + + self.benchmark_compiled_module(output) + + output.writelines(["", "", 'if __name__ == "__main__":']) + with output.indent(): + output.writelines( + [ + "from torch._inductor.wrapper_benchmark import compiled_module_main", + "args = get_args()", + ( + f"compiled_module_main('{get_benchmark_name()}', " + "lambda times, repeat: benchmark_compiled_module(args, times=times, repeat=repeat))" + ), + ] + ) + + def define_kernel( + self, + kernel_name: str, + kernel_body: str, + metadata: str | None = None, + gpu: bool = True, + cpp_definition: str | None = None, + ): + self.writeline( + KernelDefinitionLine( + self, + kernel_name, + kernel_body, + metadata=metadata, + gpu=gpu, + cpp_definition=cpp_definition, + ) + ) + + @staticmethod + def _format_kernel_definition( + kernel_name: str, kernel_body: str, metadata: str | None = None + ): + if config.triton.autotune_at_compile_time and metadata: + # Generating autotune block + # Need to replace C++ comment starter with Python comment starter + metadata = re.sub(r"^// ", "# ", metadata, flags=re.MULTILINE) + metadata_comment = f"{metadata}\n" if metadata else "" + body = f"\n\n{metadata_comment}{kernel_name} = {kernel_body}" + return body + + def _define_kernel_helper( + self, + kernel_name: str, + kernel_body: str, + metadata: str | None = None, + gpu: bool = True, + cpp_definition: str | None = None, + ): + if config.triton.autotune_at_compile_time and gpu: + body = self._format_kernel_definition( + kernel_name, kernel_body, metadata=metadata + ) + self.kernel_autotune_defs.splice(body) + if V.graph.cpp_wrapper: + # For cpp wrapper, no need to continue codegen for the main body + return + + body = self._format_kernel_definition( + kernel_name, kernel_body, metadata=metadata + ) + self.header.splice(body) + + def define_subgraph_launcher_fn(self, name: str, subgraph_code): + self.subgraph_definitions.splice(subgraph_code.value) + + @classmethod + def _get_triton_info_kernel_cls(cls): + # Other inductor triton backends may subclass from + # the `TritonKernel` class. An override of this method + # allows them to set which subclass to use to get information + # such as common triton imports or inductor metadata + from .triton import TritonKernel + + return TritonKernel + + def define_user_defined_triton_kernel( + self, + kernel, + configs, + kwargs, + restore_value_args, + reset_to_zero_args, + grids: list[list[int | sympy.Expr]], + epilogue_fusion: tuple[ir.ComputedBuffer, str] | None, + launch_kwargs: tuple[str, ...], + ): + """Codegen a user-defined Triton kernel and return its cache entry. + + Emits the ``async_compile.triton(...)`` wrapper, assigns a graph-unique + name (with a leading dunder stripped to avoid Python class-based name + mangling at the call site), and records the kernel in + ``user_defined_kernel_cache``. Returns ``(name, triton_meta, + inductor_meta, extra_launcher_call_args)``; subsequent calls with the + same ``cache_key`` reuse the previously assigned name. + """ + from torch._dynamo.device_interface import get_interface_for_device + + from ..runtime.triton_compat import GPUTarget + from ..runtime.triton_helpers import try_filter_backend_options_for_target + from ..runtime.triton_heuristics import ( + config_to_dict, + FixedGrid, + PrecomputedGrid, + ) + from .common import ( + ConstexprArg, + KernelArgType, + SizeArg, + TensorArg, + TMADescriptorArg, + ) + + original_name = kernel.__name__ + signature: list[KernelArgType] = [] + constants: dict[str, Any] = {} + arg_indices: list[int] = [] + equal_to_1_args: list[str] = [] + + def add_to_signature(idx, arg): + signature.append(arg) + arg_indices.append(idx) + + def add_arg(idx, arg, is_constexpr=False, equals_1=False, equals_none=False): + if is_constexpr: + if triton_version_uses_attrs_dict(): + # tl.constexpr args appear in the signature in new versions of triton, + # but not in old versions of triton. + add_to_signature(idx, arg) + + if arg.name in kwargs: + # the arg may not appear in kwargs if it is an autotuned arg. + # in this case, it will be added in triton_heuristics after autotuning. + constants[arg.name] = kwargs[arg.name] + + else: + # the only case where arg name isn't in kwargs, should be + # when the arg is a constexpr. + if arg.name not in kwargs: + raise AssertionError(f"expected {arg.name} in kwargs") + + if equals_1: + if triton_version_uses_attrs_dict(): + # new versions of triton: add the equal-to-1 arg in the signature (labeled as "constexpr"), + # and add the arg as a constant. + # new versions of triton: add the equal-to-1 arg in the signature (labeled as, e.g., "i32"), + # and add the arg as a constant. + add_to_signature(idx, ConstexprArg(name=arg.name)) + else: + add_to_signature(idx, arg) + constants[arg.name] = 1 + elif equals_none: + if triton_version_uses_attrs_dict(): + # new versions of triton: add the none arg in the signature (as a constexpr arg) and as a constant + # old versions of triton: include the none arg as a constant (but not in the signature) + add_to_signature(idx, ConstexprArg(name=arg.name)) + constants[arg.name] = None + else: + add_to_signature(idx, arg) + + arg_names = [p.name for p in kernel.params] + constexprs = [p.num for p in kernel.params if p.is_constexpr] + for idx, key in enumerate(arg_names): + if idx in constexprs: + add_arg(idx, ConstexprArg(name=key), is_constexpr=True) + continue + + if key not in kwargs: + continue + + arg = kwargs[key] + + if kwargs[key] is None: + add_arg(idx, ConstexprArg(name=key), equals_none=True) + else: + if isinstance(arg, ir.TMADescriptor): + api_type, block_shape, dtype = ( + ("stable", arg.block_shape, arg.tensor.get_dtype()) + if isinstance(arg, ir.TMADescriptorStable) + else ("experimental", None, None) + ) + add_arg( + idx, + TMADescriptorArg( + name=key, + api_type=api_type, + block_shape=block_shape, + dtype=dtype, + ), + ) + elif isinstance(arg, ir.Buffer): + add_arg( + idx, + TensorArg( + name=key, + buffer=arg.get_name(), + dtype=arg.get_dtype(), + ), + ) + elif isinstance(arg, ir.ReinterpretView): + # for ReinterpretView we use the underlying + # buffer name and note the (possibly non-zero) + # offset relative to the underlying buffer + add_arg( + idx, + TensorArg( + name=key, + buffer=arg.data.get_name(), + dtype=arg.get_dtype(), + offset=arg.layout.offset, + ), + ) + else: + equals_1 = isinstance( + arg, (int, sympy.Integer) + ) and V.graph.sizevars.statically_known_equals( + arg, + 1, # type: ignore[arg-type] + ) + add_arg(idx, SizeArg(key, arg), equals_1=equals_1) + + triton_signature = signature_to_meta( + signature, + size_dtype=None, # try to infer based on symints + indices=arg_indices, + argdefs=[ArgName(x) for x in kernel.arg_names], + ) + device = V.graph.get_current_device_or_throw() + device_props = DeviceProperties.create(device) + triton_meta: TritonMeta = { + "signature": triton_signature, + "device": device_props, + # Triton compiler includes equal_to_1 args into constants even + # when they are not constexpr. otherwise there may be a segfault + # during launching the Inductor-compiled Triton kernel. + # TODO(aakhundov): add None args to constants, too. currently, this + # causes CUDA errors in test_aot_inductor.test_triton_kernel_with_none_input. + # https://github.com/pytorch/pytorch/issues/120478#issuecomment-1962822307 + # https://github.com/triton-lang/triton/blob/231efe9ed2d200be0f69a07c298e4342b08efe3d/python/triton/runtime/jit.py#L384 + "constants": { + **constants, + **dict.fromkeys(equal_to_1_args, 1), + }, + "configs": [ + config_of( + signature, + indices=arg_indices, + pointer_range_override=(), + ) + ], + } + + if restore_value_args: + triton_meta["restore_value"] = tuple(restore_value_args) + + if reset_to_zero_args: + triton_meta["reset_to_zero"] = tuple(reset_to_zero_args) + + backend_option_candidates = { + name: kwargs[name] for name in launch_kwargs if name in kwargs + } + if backend_option_candidates: + get_interface_for_device(device).raise_if_triton_unavailable(device) + if GPUTarget is None: + raise AssertionError("expected GPUTarget to be not None") + target = GPUTarget( + device_props.type, + device_props.cc, + device_props.warp_size_or_default, + ) + # HOP capture deliberately keeps an over-approximation of launch kwargs so + # a concrete kwarg can still have Triton's direct-call dual meaning: + # kernel parameter plus backend option. Once the target backend is known, + # only names accepted by parse_options() should be serialized into + # triton_meta["backend_options"]. Names that are neither kernel parameters + # nor backend options are invalid launch kwargs, matching eager Triton. + filtered_backend_options = try_filter_backend_options_for_target( + target, backend_option_candidates, kernel.arg_names + ) + if filtered_backend_options: + triton_meta["backend_options"] = filtered_backend_options + + if len(grids) == 1: + # compute the grid in the wrapper and pass it in as an arg + inductor_meta: dict[str, Any] = FixedGrid.setup_grid_as_args() + extra_launcher_call_args = [*map(sympy.sympify, grids[0])] + else: + + def rename_sizes_for_launcher(expr: int | sympy.Expr) -> sympy.Expr: + if isinstance(expr, sympy.Expr): + symbols = [*expr.free_symbols] + if not symbols: + return expr + symbols.sort(key=str) + for sym in symbols: + if sym in extra_launcher_args: + continue + extra_launcher_args[sym] = sympy.Symbol( + f"_launcher_s{len(extra_launcher_args)}" + ) + return sympy_subs(expr, extra_launcher_args) + if not isinstance(expr, int): + raise AssertionError(f"expected int, got {type(expr)}") + return sympy.Integer(expr) + + extra_launcher_args: dict[sympy.Symbol, sympy.Symbol] = {} + grids = [[*map(rename_sizes_for_launcher, grid)] for grid in grids] + + if not (grids and len(grids) == len(configs)): + raise AssertionError( + f"expected non-empty grids matching configs, got {len(grids)} grids and {len(configs)} configs" + ) + precomputed_grids = [] + for grid, cfg in sorted( + zip(grids, configs), key=lambda x: len(x[1].kwargs), reverse=True + ): + precomputed_grids.append( + { + "config": config_to_dict(cfg), + "python": [*map(pexpr, grid)], + "cpp": [*map(cexpr, grid)], + "python_slow": [*map(pexpr, grid)], + } + ) + inductor_meta = { + "grid_type": PrecomputedGrid.__name__, + "precomputed_grids": precomputed_grids, + "extra_launcher_args": [*map(str, extra_launcher_args.values())], + } + extra_launcher_call_args = [*extra_launcher_args.keys()] + + if constexprs: + inductor_meta["declared_constexpr_names"] = [ + arg_names[i] for i in constexprs + ] + + # Distinguish between different functions using function id + cache_key: Any = [id(kernel.fn)] + if len(configs) > 0: + for arg in kwargs.values(): + # We need to key on non tensor arg only in autotune mode + if not isinstance(arg, (ir.Buffer, ir.ReinterpretView)): + cache_key.append(arg) + cache_key.append(str(triton_meta)) + cache_key.extend(str(inductor_meta)) + + if epilogue_fusion is not None: + cache_key.append((epilogue_fusion[0].get_name(), epilogue_fusion[1])) + + cache_key = tuple(cache_key) + if cache_key in self.user_defined_kernel_cache: + name, triton_meta, cached_inductor_meta = self.user_defined_kernel_cache[ + cache_key + ] + return ( + name, + triton_meta, + cached_inductor_meta, + extra_launcher_call_args, + ) + + name = f"{original_name}_{len(self.user_defined_kernel_cache)}" + # Prevent Python class-based name mangling (``__x`` -> ``_Class__x``) + # when the generated call site is inside a class body. + # See https://github.com/pytorch/pytorch/issues/170398 + if name.startswith("__") and not name.endswith("__"): + name = name[1:] + + compile_wrapper = IndentedBuffer() + if config.triton.unique_user_kernel_names: + compile_wrapper.writeline(f"async_compile.triton({name!r}, '''") + else: + compile_wrapper.writeline(f"async_compile.triton({original_name!r}, '''") + + inductor_meta["kernel_name"] = name + triton_info_kernel_cls = self._get_triton_info_kernel_cls() + inductor_meta.update(triton_info_kernel_cls.inductor_meta_common()) + + compile_wrapper.splice(triton_info_kernel_cls.gen_common_triton_imports()) + if config.triton.proton_profiling: + compile_wrapper.writeline('pl.enable_semantic("triton")') + + # Sanitize triton_meta to convert Enum values for valid Python repr + sanitized_triton_meta = _sanitize_for_repr(triton_meta) + compile_wrapper.splice( + f""" + @triton_heuristics.user_autotune( + configs={[*map(config_to_dict, configs)]!r}, + inductor_meta={inductor_meta!r}, + triton_meta={sanitized_triton_meta!r}, + filename=__file__, + custom_kernel=True, + ) + @triton.jit + """ + ) + kernel_src = user_defined_triton_kernel_transitive_closure_source_code( + kernel, epilogue_fusion + ) + if config.triton.unique_user_kernel_names: + # We replace the original_name with the unique name. + kernel_src = kernel_src.replace(f"def {original_name}(", f"def {name}(") + kernel_src = _escape_triton_kernel_source_for_wrapper(kernel_src) + compile_wrapper.splice(kernel_src) + + current_device = V.graph.get_current_device_or_throw() + compile_wrapper.writeline(f"''', device_str='{current_device.type}')") + _, lineno = inspect.getsourcelines(kernel.fn) + srcfile = inspect.getsourcefile(kernel.fn) + metadata = f"# Original path: {srcfile}:{lineno}" + self.define_kernel( + name, + compile_wrapper.getvalue(), + metadata, + ) + # Add to the cache for the next use + self.user_defined_kernel_cache[cache_key] = (name, triton_meta, inductor_meta) + return name, triton_meta, inductor_meta, extra_launcher_call_args + + def generate_numel_expr(self, kernel_name: str, tree, suffix: str | None = None): + sym_name = f"{kernel_name}_{tree.prefix}numel" + if suffix is not None: + sym_name += f"_{suffix}" + sym = sympy.Symbol(sym_name, is_integer=True, is_positive=True) + + # We can get symbolic expressions here, like s0*64 + # It is fine to have them here, but we need to handle them correctly as their own type + # This is tricky to do, so we wrap in a custom type, distinct from scalars, but also from sympy* + # scalars as well. + # This is handled in `generate_args_decl` which has a correct comment of: TODO: only works for + # constant now, need type info. I agree, this needs type info, and while this is not true type info + # it suffices as a type hint for the purposes of producing the correct code for this type. + arg = SymbolicCallArg(sym, tree.numel) + + is_benchmark_kernel = kernel_name == "" + if not is_benchmark_kernel: + self.writeline(SymbolicCallArgLine(self, arg, V.graph)) + + return arg + + def _generate_symbolic_call_arg_helper( + self, arg: SymbolicCallArg, graph: GraphLowering + ) -> None: + self.writeline(f"{arg.inner} = {pexpr(arg.inner_expr)}") + + def generate_workspace_allocation(self, ws: WorkspaceArg): + name = ws.get_name() + line = AllocateLine(self, ws) + if ws.zero_mode == WorkspaceZeroMode.UNINITIALIZED: + self.writeline(line) + elif ws.zero_mode == WorkspaceZeroMode.ZERO_ON_CALL: + self.writeline(line) + self.writeline(self.make_zero_buffer(name)) + elif ws.zero_mode == WorkspaceZeroMode.ZERO_PER_GRAPH: + prior = self.allocated_workspaces.get(name) + if prior: + if not ( + isinstance(prior, AllocateLine) + and isinstance(prior.node, WorkspaceArg) + ): + raise AssertionError( + "expected prior to be an AllocateLine with a WorkspaceArg node" + ) + # expand existing allocation + prior.node = WorkspaceArg.maximum(prior.node, ws) + else: + self.writeline(line) + self.writeline(self.make_zero_buffer(name)) + self.allocated_workspaces[name] = line + else: + raise AssertionError(ws.zero_mode) + + if config.triton.autotune_at_compile_time: + self.kernel_autotune_calls.writeline( + PythonWrapperCodegen.make_allocation( + self, + name, + ws.device, + ws.dtype, + shape=(V.graph.sizevars.optimization_hint(ws.count),), + stride=(1,), + ) + ) + if ws.zero_mode != WorkspaceZeroMode.UNINITIALIZED: + self.kernel_autotune_calls.writeline( + PythonWrapperCodegen.make_zero_buffer(self, name) + ) + + def generate_workspace_deallocation(self, ws: WorkspaceArg): + if ws.zero_mode != WorkspaceZeroMode.ZERO_PER_GRAPH: + self.writeline(FreeIfNotReusedLine(self, ws)) + + def make_zero_buffer(self, name): + return f"{name}.zero_(){self.ending}" + + def wrap_kernel_call(self, name, call_args): + return f"{name}({', '.join(call_args)}){self.ending}" + + def generate_debug_sync(self, buffer): + buffer.writeline(V.graph.device_ops.synchronize()) + + def generate_profiler_mark_wrapper_call(self, stack): + self.wrapper_call.writeline("from torch.profiler import record_function") + self.wrapper_call.writeline( + f"with record_function('graph_{V.graph.graph_id}_inductor_wrapper_call'):" + ) + stack.enter_context(self.wrapper_call.indent()) + + def generate_start_graph(self): + self.wrapper_call.writeline("start_graph()") + + def generate_end_graph(self): + self.wrapper_call.writeline(f"end_graph({config.profile_bandwidth_output!r})") + + def generate_proton_finalize(self): + """Synchronize GPU to ensure proton captures all kernel events.""" + self.wrapper_call.writeline(V.graph.device_ops.synchronize()) + + def generate_reset_kernel_saved_flags(self): + self.wrapper_call.splice( + f""" + for kernel in globals().values(): + if isinstance(kernel, {triton_heuristics.__name__}.CachingAutotuner): + kernel.cuda_kernel_saved = False + kernel.cpu_kernel_saved = False + """ + ) + + def generate_save_uncompiled_kernels(self): + """ + Precompile and save the per-config kernel artifacts (CUBINs on GPU, + ``.so`` + launcher ``.so`` on CPU) for Triton kernels that haven't + been precompiled and saved as a side effect of running the generated + JIT model (Python wrapper). This can happen when the model contains + control flow: only one pass through the control flow operators covers + the kernels that are saved, the remaining kernels are not launched, + hence not saved. The main purpose of this codegen is to compile and + save the Triton kernels outside the active control flow path for + subsequent AOTInductor code generation and compilation. + """ + self.wrapper_call.splice( + f""" + for kernel in globals().values(): + if isinstance(kernel, {triton_heuristics.__name__}.CachingAutotuner): + if kernel.device_props.type == "cpu": + if not kernel.cpu_kernel_saved: + if len(kernel.launchers) == 0: + kernel.precompile() + kernel.save_cpu_kernel(launcher=kernel.launchers[0]) + else: + if not kernel.cuda_kernel_saved: + if len(kernel.launchers) == 0: + kernel.precompile() + kernel.save_gpu_kernel( + stream="stream", # use dummy stream + launcher=kernel.launchers[0], + ) + """ + ) + + def prepare_triton_kernel_call(self, call_args): + def wrap_arg(arg): + if isinstance(arg, str): + # dynamo wraps unspec variable as 0d CPU tensor, need convert to scalar + return arg + ".item()" if should_unwrap_unspec_arg(arg) else arg + elif isinstance(arg, (int, float, bool, SymbolicCallArg)): + return str(arg) + else: + return pexpr(V.graph.sizevars.simplify(arg)) + + return [wrap_arg(arg) for arg in call_args] + + def generate_example_arg_value(self, arg, arg_type, raw_arg=None): + if isinstance(arg_type, torch_dtype): + if isinstance(raw_arg, ir.TMADescriptor): + # first we generate the underlying buffer + buf_name = raw_arg.get_tensor().get_name() + buf = self.args_to_buffers[arg] + elif self.args_to_buffers.get(arg): + buf_name = arg + buf = self.args_to_buffers[arg] + else: + if raw_arg is None: + raise AssertionError( + "V.graph.get_buffer(arg) and raw_arg can't be None at the same time" + ) + buf_name = f"tmp_arg_{self.kernel_autotune_tmp_arg_idx}" + buf = raw_arg + self.kernel_autotune_tmp_arg_idx += 1 + + if buf is None: + raise AssertionError(f"Failed to find a buffer for arg {arg}") + size = V.graph.sizevars.optimization_hints(buf.get_size()) + allocation_size = V.graph.sizevars.optimization_hints( + V.graph.get_allocation_size(buf) + ) + stride = V.graph.sizevars.optimization_hints(buf.get_stride()) + + device = buf.get_device() + dtype = buf.get_dtype() + offset = V.graph.sizevars.optimization_hint(buf.get_layout().offset) + value = f"generate_example_value({size}, {stride}, '{coor_device_str(device)}', {dtype}, {offset}, {allocation_size})" + self.kernel_autotune_calls.writeline(f"{buf_name} = {value}") + + if isinstance(raw_arg, ir.TMADescriptor): + # generate another line initializing a host-side TMA + # descriptor from the underlying buffer created above + value = self._generate_tma_descriptor_call( + desc=raw_arg, + apply_size_hints=True, + ) + buf_name = arg + self.kernel_autotune_calls.writeline(f"{buf_name} = {value}") + + return buf_name + elif issubclass(arg_type, sympy.Basic) or isinstance(arg, SymbolicCallArg): + # arg is a symbol or symbolic expression + if isinstance(arg, str): + if arg in self._meta_vars: + return arg + if raw_arg is None: + return "None" + arg = raw_arg + if isinstance(arg, SymbolicCallArg): + arg = arg.inner_expr + if arg in V.graph.sizevars.inv_precomputed_replacements: + arg = V.graph.sizevars.inv_precomputed_replacements[arg] + + return str(V.graph.sizevars.optimization_hint(arg)) + + elif isinstance(arg, (str, int, float, bool)): + return str(arg) + elif isinstance(arg, list): + return f"[{', '.join(self.generate_example_arg_value(a, type(a)) for a in arg)}]" + else: + raise NotImplementedError(f"Unsupported type {type(arg)}") + + def _grid_dim_str(self, grid_per_dim): + if isinstance(grid_per_dim, list): + return ( + "[" + ", ".join(self._grid_dim_str(item) for item in grid_per_dim) + "]" + ) + else: + return pexpr(grid_per_dim) + + def generate_kernel_call( + self, + kernel_name: str, + call_args, + *, + device=None, + triton=True, + arg_types=None, + raw_keys=None, + raw_args=None, + triton_meta: TritonMeta | None = None, + inductor_meta=None, + original_fxnode_name=None, + ): + """ + Generates kernel call code. + + triton: Defines whether the backend uses Triton for codegen. Otherwise it uses the CUDA language when gpu=True, + and C++ when gpu=False. + """ + + # Store buffers corresponding to each call arg. + # This is used to generate example args for autotuning later on. + self.args_to_buffers.update( + { + arg: V.graph.try_get_buffer(arg) + for arg in call_args + if isinstance(arg, str) + } + ) + + device = device or V.graph.get_current_device_or_throw() + current_stream_idx = V.graph.scheduler.current_stream_idx + self.writeline( + KernelCallLine( + self, + kernel_name=kernel_name, + call_args=call_args, + # pyrefly: ignore [bad-argument-type] + raw_keys=raw_keys, + # pyrefly: ignore [bad-argument-type] + raw_args=raw_args, + # pyrefly: ignore [bad-argument-type] + arg_types=arg_types, + triton=triton, + # pyrefly: ignore [bad-argument-type] + triton_meta=triton_meta, + inductor_meta=inductor_meta, + device=device, + graph_name=V.graph.name, + # pyrefly: ignore [bad-argument-type] + original_fxnode_name=original_fxnode_name, + current_stream_idx=current_stream_idx, + ) + ) + + def _generate_kernel_call_helper( + self, + kernel_name: str, + call_args, + *, + device=None, + triton=True, + arg_types=None, + raw_keys=None, + raw_args=None, + triton_meta: TritonMeta | None = None, + inductor_meta=None, + graph_name="", + original_fxnode_name=None, + current_stream_idx=None, + ): + device = device or V.graph.get_current_device_or_throw() + if not triton and device.type not in ("cuda", "xpu"): + if device.type == "cpu": + self.writeline(self.wrap_kernel_call(kernel_name, call_args)) + elif device.type == "mps": + # TODO: Fix me, MPS does not expose streams now + self.writeline(self.wrap_kernel_call(kernel_name, call_args)) + else: + raise RuntimeError(f"device {device.type} nyi") + return + + call_args_str = self.prepare_triton_kernel_call(call_args) + call_args_str = ", ".join(call_args_str) + if current_stream_idx is not None and current_stream_idx != DEFAULT_STREAM_IDX: + # Inside a user stream context: emit a fresh get_raw_stream call so + # it picks up the active stream at runtime, rather than reusing the + # LRU-cached stream0 variable which captured the default stream. + self.write_get_raw_stream_header() + stream_name = "raw_stream" + self.writeline( + f"{stream_name} = get_raw_stream({_coor_device_idx_ref(device.index)})" + ) + else: + stream_name = PythonWrapperCodegen.write_get_raw_stream( + self, device.index, graph_name + ) + if not triton: + stream_ptr = f"c_void_p({stream_name})" + self.writeline( + f"{kernel_name}.{kernel_name}({call_args_str}, {stream_ptr})" + ) + return + + self.write_triton_header_once() + + if ( + config.triton.autotune_at_compile_time + and kernel_name not in self.kernel_autotune_names + ): + # Create example args for autotune in a separate epilogue + if not (arg_types is not None and len(call_args) == len(arg_types)): + raise AssertionError("call_args and arg_types do not match") + + autotune_args = None + if original_fxnode_name and V.graph.autotuning_mapping: + autotune_args = V.graph.autotuning_mapping.get( + original_fxnode_name, None + ) + + _per_kernel = config.aot_inductor.autotune_per_kernel_alloc + + def get_autotune_deletion_call() -> str: + """Returns del for tensors whose last consumer is this kernel.""" + tensors_to_delete = [ + tensor + for tensor, kn in self.kernel_autotune_example_args.values() + if kn == kernel_name + ] + if tensors_to_delete: + return f"del {', '.join(tensors_to_delete)}\n" + return "" + + def infer_arg_by_inputs(raw_keys, raw_args, idx, reused_args): + """We try to infer raw_arg (i.e. raw_args[idx]) from remaining raw_args. + This is particularly useful for jagged cases, where the dimension is often + being passed in as an input.""" + + target_arg = raw_args[idx] + if target_arg in reused_args: + return True + + for i, (raw_key, raw_arg) in enumerate(zip(raw_keys, raw_args)): + if i == idx or not isinstance(raw_arg, IRNode): + continue + + triton_input = "" + if autotune_args and raw_key in autotune_args: + triton_input = self.get_autotuning_input_name( # type: ignore[attr-defined] + autotune_args[raw_key] + ) + if triton_input == "": + continue + + try: + layout = raw_arg.get_layout() + for dim, s in enumerate(layout.size): + if s == target_arg: + reused_args[target_arg] = f"{triton_input}.shape[{dim}]" + return True + except NotImplementedError: + # If layout for this IRNode is not implemented, we could just skip. + # Only raise for other Error cases. + continue + return False + + all_args = [] + tensor_arg_strs = [] # used only when _per_kernel is True + if raw_args is None: + # create a dummy raw_args for uniform behavior in the following loop + if raw_keys is not None: + raise AssertionError("keys are not None but args are") + raw_keys = [None] * len(call_args) + raw_args = [None] * len(call_args) + else: + if len(raw_args) != len(call_args): + raise AssertionError("call_args and raw_args do not match") + + reused_args = {} + for i, (arg, arg_type, raw_key, raw_arg) in enumerate( + # pyrefly: ignore [bad-argument-type, no-matching-overload] + zip(call_args, arg_types, raw_keys, raw_args) + ): + key = None + if isinstance(arg, str) and "=" in str(arg): + # arg may be passed in a kwarg style, and then we need to extract its value + key, arg = arg.split("=") + + triton_input: str | None = None + if autotune_args and raw_key in autotune_args: + triton_input = self.get_autotuning_input_name( # type: ignore[attr-defined] + autotune_args[raw_key] + ) + + if triton_input: + arg_str = triton_input + if not isinstance(arg_type, torch_dtype) and ( + issubclass(arg_type, sympy.Basic) + or isinstance(arg, SymbolicCallArg) + ): + reused_args[raw_arg] = arg_str + elif raw_key == "" and infer_arg_by_inputs( + raw_keys, raw_args, i, reused_args + ): + # Empty raw_key means this is an arg that's not native to the triton kernel, + # and is being added by inductor. + arg_str = reused_args[raw_arg] + elif isinstance(arg_type, torch_dtype): + # workspace allocation is already generated by `generate_workspace_allocation()` + # in `TritonKernel.call_kernel()`. + if re.match(r"^(workspace|semaphore)", arg): + arg_str = arg + elif _per_kernel: + arg_str = self.generate_example_arg_value( + arg, arg_type, raw_arg + ) + tensor_arg_strs.append(arg_str) + elif arg not in self.kernel_autotune_example_args: + arg_str = self.generate_example_arg_value( + arg, arg_type, raw_arg + ) + else: + arg_str = self.kernel_autotune_example_args[arg][0] + if not _per_kernel: + self.kernel_autotune_example_args[arg] = (arg_str, kernel_name) + else: + arg_str = self.generate_example_arg_value(arg, arg_type, raw_arg) + + if isinstance(arg, str) and should_unwrap_unspec_arg(arg): + arg_str += ".item()" + all_args.append(arg_str if key is None else f"{key}={arg_str}") + + # Make sure kernel launch under a device guard because models don't always run on device 0 + # The autotune block inlines the current-device expression rather than using the + # call()-local _coor_device_idx variable, which is not in scope here. + guard_idx = ( + V.graph.device_ops.current_device_idx_expr() + if _coor_enabled() + else device.index + ) + self.kernel_autotune_calls.writeline( + f"with {V.graph.device_ops.device_guard(guard_idx)}:" + ) + self.kernel_autotune_calls.do_indent() + self.kernel_autotune_calls.writeline( + f"{kernel_name}.run({', '.join(all_args)}, stream={stream_name})" + ) + self.kernel_autotune_calls.do_unindent() + + if _per_kernel and tensor_arg_strs: + self.kernel_autotune_calls.writeline( + f"del {', '.join(tensor_arg_strs)}" + ) + elif not _per_kernel: + self.kernel_autotune_calls.writeline( + DelayReplaceLine( + "", + get_autotune_deletion_call, + "", + ) + ) + self.kernel_autotune_names.add(kernel_name) + if V.graph.cpp_wrapper: + # For cpp wrapper, no need to continue codegen for the main body + return + + # add debug printer code for triton kernel calls at (jit) inductor level + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args(call_args, kernel_name, arg_types, None) + with debug_printer_manager: + self.writeline(f"{kernel_name}.run({call_args_str}, stream={stream_name})") + self.write_triton_header_once() + + def writeline(self, line): + self.lines.append(line) + + def writelines(self, lines): + for line in lines: + self.writeline(line) + + def enter_context(self, ctx): + self.lines.append(LineContext(ctx)) + + def val_to_arg_str(self, s, type_=None): + from torch.utils._triton import has_triton_package + + if has_triton_package(): + import triton + + if isinstance(s, SymTypes): + return pexpr(s.node.expr) + elif isinstance(s, sympy.Expr): + return pexpr(s) + elif isinstance(s, (tuple, list)): + + @dataclasses.dataclass + class Shim: + ref: Any + + def __repr__(self): + return self.ref + + # Explicitly call the Python version of val_to_arg_str + return repr( + type(s)(Shim(PythonWrapperCodegen.val_to_arg_str(self, a)) for a in s) + ) + elif isinstance(s, torch._ops.OpOverload): + return _get_qualified_name(s) + elif isinstance(s, (ir.Buffer, ir.MutableBox, ReinterpretView)): + return s.codegen_reference() + elif has_triton_package() and isinstance(s, triton.language.dtype): # type: ignore[possibly-undefined] + return repr(s) + elif isinstance(s, (ir.GeneratorState, ir.OpaqueObjectState)): + return s.codegen_reference() + elif is_opaque_constant_type(type(s)): + obj_repr, opaque_types = get_opaque_obj_repr(s) + for n, t in opaque_types.items(): + V.graph.opaque_value_type_classes[n] = t + return obj_repr + elif isinstance(s, torch.device) and _coor_enabled() and s.index is not None: + # compile-on-one-rank: repr() of an indexed device would bake this rank's + # index into the wrapper (e.g. an aten fallback's device= arg renders as + # device(type='cuda', index=0)), which the "cuda:N" checks do not catch. + # Emit the bare type so the value follows the enclosing runtime device guard. + return repr(torch.device(s.type)) + else: + return repr(s) + + # The following methods are for memory management + def make_buffer_allocation(self, buffer: BufferLike): + device = buffer.get_device() + dtype = buffer.get_dtype() + shape = tuple(buffer.get_size()) + allocation_shape = tuple(V.graph.get_allocation_size(buffer)) + stride = tuple(buffer.get_stride()) + is_pinned = buffer.get_is_pinned() + return self.make_allocation( + buffer.get_name(), device, dtype, shape, stride, allocation_shape, is_pinned + ) + + @cache_on_self + def write_memory_track_allocation_once(self): + import_str = """ + from torch._inductor.runtime.debug_utils import check_memory_step, track_tensor + """ + if not V.graph.cpp_wrapper: + self.imports.splice(import_str, strip=True) + + def make_allocation( + self, name, device, dtype, shape, stride, allocation_shape=None, is_pinned=False + ): + if allocation_shape is None: + allocation_shape = shape + + codegen_shape_tuple = self.codegen_python_shape_tuple(shape) + codegen_allocation_shape_tuple = self.codegen_python_shape_tuple( + allocation_shape + ) + codegen_stride_tuple = self.codegen_python_shape_tuple(stride) + if torch._inductor.config.test_configs.track_memory_lifecycle: + out = ( + f"{name} = tracked_empty_strided(" + f"{codegen_allocation_shape_tuple}, " + f"{codegen_stride_tuple}, " + f"dtype={dtype}, " + f"device='{device.type}', " + f"name='{name}')" + ) + elif device.type == "cpu" and is_pinned: + out = ( + f"{name} = empty_strided_cpu_pinned(" + f"{codegen_allocation_shape_tuple}, " + f"{codegen_stride_tuple}, " + f"{dtype})" + ) + elif device.type in ("cpu", "cuda", "xpu", "mtia"): + # optimized path for faster allocations, saving ~2us versus the stuff below + out = ( + f"{name} = empty_strided_{device.type}(" + f"{codegen_allocation_shape_tuple}, " + f"{codegen_stride_tuple}, " + f"{dtype})" + ) + # all other devices: + else: + out = ( + f"{name} = empty_strided(" + f"{codegen_allocation_shape_tuple}, " + f"{codegen_stride_tuple}, " + f"device='{device.type}', dtype={dtype})" + ) + if codegen_shape_tuple != codegen_allocation_shape_tuple: + # need an extra as_strided call + out = out + f".as_strided({codegen_shape_tuple}, {codegen_stride_tuple})" + return out + + def make_comment(self, line): + self.writeline(CommentLine(line)) + + def make_tensor_alias(self, new_name, old_name, comment=""): + return f"{self.declare}{new_name} = {old_name}{self.ending} {self.comment} {comment}" + + def make_buffer_free(self, buffer: BufferLike | ir.TorchBindObject): + return f"del {buffer.get_name()}" + + def make_free_by_names(self, names_to_del: list[str]): + return f"del {', '.join(name for name in names_to_del)}" + + def codegen_exact_buffer_reuse(self, old_name: str, new_name: str, del_line: str): + return f"{self.declare_maybe_reference}{new_name} = {old_name}{del_line}{self.ending} {self.comment} reuse" + + def write_provenance_debug_handle( + self, + kernel_name, + debug_handle: int | None = None, + ): + if debug_handle is not None: + self.writeline( + f"{self.comment} [Provenance debug handles] {kernel_name}:{debug_handle}" + ) + + def make_buffer_reuse(self, old: BufferLike, new: BufferLike, delete_old: bool): + if old.get_dtype() != new.get_dtype(): + raise AssertionError( + f"expected matching dtypes, got {old.get_dtype()} and {new.get_dtype()}" + ) + old_name = old.get_name() + new_name = new.get_name() + del_line = ";" + if old_name not in V.graph.get_output_names() and delete_old: + del_line = f"; {self.make_buffer_free(old)}" + + if old.get_size() == new.get_size() and old.get_stride() == new.get_stride(): + return self.codegen_exact_buffer_reuse(old_name, new_name, del_line) + + reinterpret_view = self.codegen_reinterpret_view( + old, new.get_size(), new.get_stride(), 0, self.wrapper_call.writeline + ) + return f"{self.declare}{new_name} = {reinterpret_view}{del_line} {self.comment} reuse" + + def codegen_deferred_allocation(self, name: str, view: ir.ReinterpretView) -> None: + self.writeline( + DeferredLine( + name, + f"{self.declare}{name} = {view.codegen_reference()}{self.ending} {self.comment} alias", + ) + ) + + def codegen_allocation(self, buffer: ir.Buffer): + name = buffer.get_name() + + if ( + name in V.graph.removed_buffers + or name in self.allocated + or isinstance(buffer, (ir.DonatedBuffer, ir.SubgraphBuffer, ir.InputBuffer)) + ): + return + self.allocated.add(name) + if ( + isinstance( + buffer.get_defining_op(), + (ir.ExternKernelAlloc, ir.MultiOutput), + ) + and not buffer.should_allocate() + ): + return + + layout = buffer.get_output_spec() + if isinstance(layout, ir.MutationLayoutSHOULDREMOVE): + return + if isinstance(layout, ir.NoneLayout): + return + if isinstance(layout, ir.NonOwningLayout): + if not isinstance(layout.view, ir.ReinterpretView): + raise AssertionError(f"unexpected {type(layout.view)}: {layout.view}") + box = layout.view.data + if not isinstance(box, ir.StorageBox): + raise AssertionError(type(box)) + input_buffer = box.data + if not isinstance(input_buffer, (ir.Buffer, ir.ReinterpretView)): + raise AssertionError(type(input_buffer)) + if isinstance(input_buffer, ir.ReinterpretView): + + def unwrap_views(target) -> ir.Buffer: + if isinstance(target, ir.BaseView): + return unwrap_views(target.unwrap_view()) + if isinstance(target, ir.MutableBox): + return unwrap_views(target.data) + if not isinstance(target, ir.Buffer): + raise AssertionError(type(target)) + return target + + input_buffer = unwrap_views(input_buffer) + self.codegen_allocation(input_buffer) + self.writeline(ReinterpretLine(self, input_buffer, buffer, layout)) + return + + if isinstance(layout, ir.CommBufferLayout): + self.writeline(AllocateLine(self, buffer, comm_buffer=True)) + return + + self.writeline(AllocateLine(self, buffer)) + + def codegen_free(self, buffer): + name = buffer.get_name() + + # can be freed but not reused + if isinstance(buffer, (ir.InputBuffer, ir.TorchBindObject)): + self.writeline(FreeLine(self, buffer)) + # A multistream input keeps a preserved copy of its original + # ({name}_orig, see codegen_deferred_alignment_copies) that each + # per-stream clone reads from; its lifetime matches the input's, so + # free it here on the normal last_usage -> codegen_free path. + if name in self._alignment_orig_saved: + self._alignment_orig_saved.discard(name) + self.writeline(self.make_free_by_names([f"{name}_orig"])) + return + + if isinstance(buffer.get_output_spec(), ir.CommBufferLayout): + # Comm buffers are not eligible for in-place reuse. Their reuse is + # achieved exclusively via buffer planning. + self.writeline(FreeIfNotReusedLine(self, buffer, comm_buffer=True)) + return + + if not self.can_reuse(buffer): + return + self.freed.add(name) + + self.writeline(FreeIfNotReusedLine(self, buffer)) + + def can_reuse(self, input_buffer, output_buffer=None): + name = input_buffer.get_name() + return not ( + name in V.graph.removed_buffers + or ( + name in V.graph.graph_inputs + and not isinstance( + V.graph.graph_inputs_original[name], ir.DonatedBuffer + ) + ) + or name in V.graph.constants + or name in V.graph.torchbind_constants + or name in V.graph.never_reuse_buffers + or name in self.freed + ) + + def did_reuse(self, buffer, reused_buffer): + # Check whether a given buffer was reused by a possible reuser in the wrapper codegen + # Can be consulted from inside ir codegen, e.g. to determine whether a copy is needed + return ( + buffer.get_name() in self.reuses + and self.reuses[buffer.get_name()] == reused_buffer.get_name() + ) + + def codegen_inplace_reuse(self, input_buffer: ir.Buffer, output_buffer: ir.Buffer): + if not can_match_buffer_size(input_buffer, output_buffer): + raise AssertionError( + "expected input_buffer and output_buffer sizes to match" + ) + self.codegen_allocation(input_buffer) + self.freed.add(input_buffer.get_name()) + self.allocated.add(output_buffer.get_name()) + self.reuses[output_buffer.get_name()] = input_buffer.get_name() + self.writeline(ReuseLine(self, input_buffer, output_buffer)) + + def codegen_unbacked_symbol_decl(self, symbol): + name = str(symbol) + if name in self.unbacked_symbol_decls: + return name + else: + # When in CppWrapperCpu, we should only generate the declaration once + self.unbacked_symbol_decls.add(name) + return self.declare + name + + def codegen_unbacked_symbol_defs_for_outputs( + self, + output_name: str, + outputs: Any, + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None, + ) -> None: + unbacked_bindings = resolve_unbacked_bindings( + V.graph.sizevars.shape_env, unbacked_bindings + ) + self.writeline( + UnbackedSymbolDefsLine(self, output_name, outputs, unbacked_bindings) + ) + + def _codegen_unbacked_symbol_defs_for_outputs( + self, + output_name: str, + outputs: Any, + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None, + ) -> None: + if not unbacked_bindings: + return + + # This code is designed to generate code expressions from symbolic paths (keypaths) + # associated with certain symbols (unbacked bindings). These keypaths describe how + # to access the unbacked symbol in a structured way. + # For example, we might want to generate "u0 = outs[0].stride(1)"", where s = u0, and the keypath + # describes the structure of "outs[0].stride(1)", like [SequenceKey(0), CallMethodKey("stride"), SequenceKey[1]]. + for s, keypath in unbacked_bindings.items(): + # `go` recursively constructs a code expression by processing each element of + # the keypath and construct the expression incrementally. + # For example, given output name outs and keypath [SequenceKey(0), CallMethodKey("stride", 1)], + # it generates "outs[0]" based on SequenceKey(0), then recursively go("outs[0]", [CallMethodKey("stride"), ...]) + def go(expr: str, keypath: pytree.KeyPath): + if keypath == (): + return expr + + if ( + len(keypath) >= 2 + and isinstance(keypath[0], CallMethodKey) + and isinstance(keypath[1], pytree.SequenceKey) + ): + return go( + f"{expr}.{keypath[0].name}({keypath[1].idx})", keypath[2:] + ) + elif isinstance(keypath[0], CallMethodKey): + return go(f"{expr}.{keypath[0].name}()", keypath[1:]) + elif isinstance(keypath[0], pytree.SequenceKey): + return ( + go(f"std::get<{keypath[0].idx}>({expr})", keypath[1:]) + if V.graph.cpp_wrapper + else go(f"{expr}[{keypath[0].idx}]", keypath[1:]) + ) + elif isinstance(keypath[0], DivideByKey): + # TODO: need to assert divisibility + if V.graph.cpp_wrapper: + return go(f"({expr} / {keypath[0].divisor})", keypath[1:]) + return go(f"{expr}.__floordiv__({keypath[0].divisor})", keypath[1:]) + else: + raise AssertionError(f"unrecognized keypath {keypath}") + + # `go_outer` manages the top-level logic for generating the final expression. + # It handles special cases for C++ code generation and adjusts + # the keypath based on the context (e.g., single vs. multiple outputs). + def go_outer(): # type: ignore[no-untyped-def] + if V.graph.cpp_wrapper: + # Special handling for the top level buffer access, + # because self.get_name() is actually never bound; the + # individual output arguments are bound by + # generate_c_shim_fallback_kernel + if len(outputs) == 1: + out = outputs[0] + # When fallback kernel returns a list consisting of a single tensor, + # the output is represented as a MultiOutput with non empty indices. + # In this case, we strip the first key path away. + return go( + outputs[0].get_name(), + keypath[1:] + if isinstance(out, ir.MultiOutput) and len(out.indices) != 0 + else keypath, + ) + else: + if not isinstance(keypath[0], pytree.SequenceKey): + raise AssertionError( + f"expected SequenceKey, got {type(keypath[0])}" + ) + return go(outputs[keypath[0].idx].get_name(), keypath[1:]) + else: + return go(output_name, keypath) + + self.writeline( + f"{self.codegen_unbacked_symbol_decl(s)} = {go_outer()}{self.ending}" + ) + + def codegen_subgraph_by_inlining(self, subgraph, outer_inputs, outer_outputs): + # TODO (desertfire) - This function is the old way of supporting + # subgraph codegen by inlining subgraphs in the output code. For python + # wrapper, we have moved to lifting subgraphs as functions, supported by + # `codegen_subgraph` function. + # + # However this does not work with cpp wrapper. With cpp wrapper, we make + # two passes and the kernels are shared from the first pass to the next. + # Therefore, both the Python and CppWrapper need to share the some + # codegen infra. For now, CppWrapperCpu has not been updated to lift the + # subgraph as functions. Therefore for cpp_wrapper first pass with + # PythonWrapper, we still fallback to the old way of inlining subgraphs + # in the output code. Once we update CppWrapperCpu, we can remove this + # function. + def _codegen_subgraph_prefix(): + if len(subgraph.graph.graph_inputs) != len(outer_inputs): + raise AssertionError( + f"expected matching input counts, got {len(subgraph.graph.graph_inputs)} != {len(outer_inputs)}" + ) + for inner_input, outer_input in zip( + subgraph.graph.graph_inputs, outer_inputs + ): + self.writeline( + f"{self.declare}{inner_input} = {outer_input}{self.ending}" + ) + + def _codegen_subgraph_suffix(): + if len(subgraph.graph.graph_outputs) != len(outer_outputs): + raise AssertionError( + f"expected matching output counts, got {len(subgraph.graph.graph_outputs)} != {len(outer_outputs)}" + ) + for inner_output, outer_output in zip( + subgraph.graph.graph_outputs, outer_outputs + ): + self.writeline( + f"{outer_output} = {inner_output.codegen_reference()}{self.ending}" + ) + + try: + self.push_codegened_graph(subgraph.graph) + # Only ir.Subgraph (invoke_subgraph regions) carries nested config + # patches; other subgraph adapters (e.g. the CodegenGraph used for + # decompose_k) have none. + inductor_config_patches = getattr(subgraph, "inductor_config_patches", None) + ctx = ( + config.patch(inductor_config_patches) + if inductor_config_patches + else contextlib.nullcontext() + ) + with ctx: + self.writeline(f"{self.comment} subgraph: {subgraph.name}") + _codegen_subgraph_prefix() + parent_graph = V.graph + with V.set_graph_handler(subgraph.graph): + subgraph.graph.codegen_subgraph( + parent_graph=parent_graph, + ) + _codegen_subgraph_suffix() + finally: + self.pop_codegened_graph() + + def codegen_partition_call( + self, + partition_id: int, + partition_signatures: ir.GraphPartitionSignature, + ): + """Generate code to call a graph partition""" + input_deallocation = partition_signatures.input_deallocation + output_nodes = partition_signatures.output_nodes + + input_names = list(input_deallocation.keys()) + [ + symbol_input.name for symbol_input in partition_signatures.symbol_inputs + ] + + inputs = ", ".join(input_names) + ("," if len(input_names) == 1 else "") + + output_names = [node.get_name() for node in output_nodes] + outputs = ", ".join(output_names) + ("," if len(output_nodes) == 1 else "") + + # Create a list of inputs for the subgraph call + self.writeline(f"partition{partition_id}_args = [{inputs}]") + + names_to_del = [ + name for name, deallocate in input_deallocation.items() if deallocate + ] + if names_to_del: + self.writeline(f"del {', '.join(names_to_del)}") + + # Call the subgraph launcher function + self.writeline( + f"({outputs}) = self.partitions[{partition_id}](partition{partition_id}_args)" + ) + self.writeline(f"del partition{partition_id}_args") + + def get_partition_name(self, partition_id: int) -> str: + return f"partition_{partition_id}" + + def set_all_partition_names(self, num_partitions: int): + self.all_partition_names = list( + map(self.get_partition_name, range(num_partitions)) + ) + + def codegen_subgraph_call_with_flattened_outputs( + self, subgraph, outer_inputs, outer_flattened_outputs + ): + # Get the input and output names of the subgraph + outer_output_names = ", ".join(outer_flattened_outputs) + ( + "," if len(outer_flattened_outputs) == 1 else "" + ) + outer_input_names = ", ".join(outer_inputs) + ( + "," if len(outer_inputs) == 1 else "" + ) + + self.writeline(f"{subgraph.graph.name}_args = [{outer_input_names}]") + + # Call the subgraph launcher function + self.writeline( + f"({outer_output_names}) = {subgraph.graph.name}({subgraph.graph.name}_args)" + ) + + def codegen_subgraph_call(self, subgraph, outer_inputs, outer_buffer_name): + # Get the input and output names of the subgraph + outer_input_names = ", ".join(outer_inputs) + ( + "," if len(outer_inputs) == 1 else "" + ) + + self.writeline(f"{subgraph.graph.name}_args = [{outer_input_names}]") + + # Since the buffers are already put into the args list, we can free the + # buffers here. + V.graph.scheduler.free_buffers() + + # Call the subgraph launcher function + self.writeline( + f"{outer_buffer_name} = {subgraph.graph.name}({subgraph.graph.name}_args)" + ) + + def codegen_subgraph_common(self, subgraph): + self.push_codegened_graph(subgraph.graph) + self.make_comment("") + self.make_comment(f"{self.comment} subgraph: {subgraph.name}") + + parent_graph = V.graph + subgraph.graph.cpp_wrapper = parent_graph.cpp_wrapper + subgraph.graph.fx_wrapper = parent_graph.fx_wrapper + + if subgraph.graph.name not in self.already_codegened_subgraphs: + # If it is already codegened, the parent wrapper already has + # subgraph fn by name subgraph.graph.name + # Only ir.Subgraph (invoke_subgraph regions) carries nested config + # patches; other subgraph adapters (e.g. the CodegenGraph used for + # decompose_k) have none. + inductor_config_patches = getattr(subgraph, "inductor_config_patches", None) + ctx = ( + config.patch(inductor_config_patches) + if inductor_config_patches + else contextlib.nullcontext() + ) + # do not graph partition inside subgraph bodies + with ( + ctx, + config.patch("graph_partition", False), + V.set_graph_handler(subgraph.graph), + ): + # Call the codegen of subgraph recursively + subgraph_code, _ = subgraph.graph.codegen() + subgraph_name = subgraph.graph.name + self.already_codegened_subgraphs.add(subgraph_name) + self.define_subgraph_launcher_fn(subgraph_name, subgraph_code) + + def codegen_subgraph_with_flattened_outputs( + self, subgraph, outer_inputs, outer_flattened_outputs + ): + self.codegen_subgraph_common(subgraph) + self.codegen_subgraph_call_with_flattened_outputs( + subgraph, outer_inputs, outer_flattened_outputs + ) + + def codegen_subgraph(self, subgraph, outer_inputs, outer_buffer_name): + # Codegen subgraph by recursively calling the codegen for the subgraph. + # This lifts the subgraph as a function in the output code. + self.codegen_subgraph_common(subgraph) + self.codegen_subgraph_call(subgraph, outer_inputs, outer_buffer_name) + + def codegen_invoke_subgraph(self, invoke_subgraph): + name = invoke_subgraph.get_name() + + self.writeline(f"{name} = [None] * {len(invoke_subgraph.outputs)}") + outer_inputs = [buf.codegen_reference() for buf in invoke_subgraph.inputs] + + if V.graph.aot_mode: + outer_outputs = [ + f"{name}[{i}]" for i in range(len(invoke_subgraph.outputs)) + ] + self.codegen_subgraph_by_inlining( + invoke_subgraph.subgraph, outer_inputs, outer_outputs + ) + else: + self.codegen_subgraph(invoke_subgraph.subgraph, outer_inputs, name) + + def codegen_switch(self, node) -> None: + name = node.get_name() + + outer_inputs = [buf.codegen_reference() for buf in node.operands] + + selector_ref = node.selector.codegen_reference() + # Evaluate the selector once into a named local. + selector_var = f"{name}_selector" + if not isinstance(node.selector, ir.ShapeAsConstantBuffer): + # move the Tensor selector to host; always as int so the branch loop + # can use uniform index comparisons (cond: True==1, False==0) + self.writeline(f"{selector_var} = int({selector_ref}.item())") + else: + # ShapeAsConstantBuffer yields a Python bool/int expression; wrap in + # int() so "== " comparisons don't form a Python chained comparison. + self.writeline(f"{selector_var} = int({selector_ref})") + + self.writeline(f"{name} = [None] * {len(node.outputs)}") + + def _emit_branch(keyword: str, condition: str, branch) -> None: + self.writeline(f"{keyword}{condition}:") + self.writeline(EnterSubgraphLine(self, branch.graph)) + if V.graph.aot_mode: + outer_outputs = [f"{name}[{i}]" for i in range(len(node.outputs))] + self.codegen_subgraph_by_inlining(branch, outer_inputs, outer_outputs) + else: + self.codegen_subgraph(branch, outer_inputs, name) + self.writeline(ExitSubgraphLine(self)) + + num_branches = len(node.branches) + for b_idx, branch in enumerate(node.branches): + if b_idx == 0: + keyword, condition = "if", f" {selector_var} == 0" + elif b_idx < num_branches - 1: + keyword, condition = "elif", f" {selector_var} == {b_idx}" + else: + keyword, condition = "else", "" + _emit_branch(keyword, condition, branch) + + def codegen_while_loop(self, while_loop, stack_output): + """while_loop is codegened as a host side while_loop""" + + def codegen_subgraph(subgraph, outer_inputs, outer_outputs): + """Helper method to deduplicate subgraph codegen logic""" + if V.graph.aot_mode: + self.codegen_subgraph_by_inlining(subgraph, outer_inputs, outer_outputs) + else: + self.codegen_subgraph_with_flattened_outputs( + subgraph, outer_inputs, outer_outputs + ) + + name = while_loop.get_name() + outer_carried_inputs = [ + buf.codegen_reference() for buf in while_loop.carried_inputs + ] + outer_additional_inputs = [ + buf.codegen_reference() for buf in while_loop.additional_inputs + ] + + ckp_offset = len(outer_carried_inputs) + self.writeline(f"{name} = [None] * {len(outer_carried_inputs)}") + if stack_output: + self.writeline( + f"{name}.extend([[] for _ in range({len(outer_carried_inputs)})])" + ) + + for i, inp in enumerate(outer_carried_inputs): + # set the initial state before the loop + self.writeline(f"{name}[{i}] = {inp}") + + cond_outer_inputs = [ + *[f"{name}[{i}]" for i in range(len(outer_carried_inputs))], + *outer_additional_inputs, + ] + cond_outer_outputs = [f"{name}_cond_result"] + body_outer_inputs = list( + cond_outer_inputs + ) # same inputs for cond_fn and body_fn + # Carry over the state from body_fn. Note: We only carry over + # the carried_inputs part of the inputs, the additional ones + # are passed in as they're before. + body_outer_outputs = body_outer_inputs[: len(outer_carried_inputs)] + # Check condition at the beginning and set up flag + codegen_subgraph( + while_loop.cond_subgraph, cond_outer_inputs, cond_outer_outputs + ) + self.writeline(f"should_loop = {cond_outer_outputs[0]}") + self.writeline("if not should_loop:") + if stack_output: + # Handle the case when loop never executes + for i, carried_input in enumerate(outer_carried_inputs): + self.writeline(EnterSubgraphLine(self, while_loop.body_subgraph.graph)) + self.writeline(f"{name}[{i}] = {carried_input}.unsqueeze(0).clone()") + self.writeline(ExitSubgraphLine(self)) + else: + for i, carried_input in enumerate(outer_carried_inputs): + self.writeline(EnterSubgraphLine(self, while_loop.body_subgraph.graph)) + self.writeline(f"{name}[{i}] = {carried_input}.clone()") + self.writeline(ExitSubgraphLine(self)) + + self.writeline("while should_loop:") + # Body execution + self.writeline(EnterSubgraphLine(self, while_loop.body_subgraph.graph)) + codegen_subgraph( + while_loop.body_subgraph, body_outer_inputs, body_outer_outputs + ) + self.writeline(ExitSubgraphLine(self)) + + # Collect outputs if enabled + if stack_output: + self.writeline(EnterSubgraphLine(self, while_loop.body_subgraph.graph)) + for i in range(len(outer_carried_inputs)): + self.writeline(f"{name}[{i + ckp_offset}].append({name}[{i}])") + self.writeline(ExitSubgraphLine(self)) + + # Condition check at end of loop + self.writeline(EnterSubgraphLine(self, while_loop.cond_subgraph.graph)) + codegen_subgraph( + while_loop.cond_subgraph, cond_outer_inputs, cond_outer_outputs + ) + self.writeline(ExitSubgraphLine(self)) + self.writeline(f" should_loop = {cond_outer_outputs[0]}") + + # Stack outputs after loop completion + if stack_output: + self.writeline("# Stack outputs after loop completion") + for i in range(len(outer_carried_inputs)): + self.writeline(f"if len({name}[{i + ckp_offset}]) > 0:") + self.writeline(EnterSubgraphLine(self, while_loop.body_subgraph.graph)) + self.writeline( + f"{name}[{i}] = torch.stack({name}[{i + ckp_offset}], dim=0)" + ) + self.writeline(ExitSubgraphLine(self)) + + @staticmethod + def statically_known_int_or_none(x): + try: + if getattr(x, "free_symbols", None): + # _maybe_evaluate_static will return (s0 // (2 // s0)) as 2, but + # the actual codegen will still generate the full expression here. + return None + if isinstance(x, int): + return x + val = V.graph._shape_env._maybe_evaluate_static(x) + if val is None: + return val + return int(val) # type: ignore[call-overload] + except Exception: + return None + + @staticmethod + def statically_known_list_of_ints_or_none(lst): + result = [] + for x in lst: + num = PythonWrapperCodegen.statically_known_int_or_none(x) + if num is None: + return None + result.append(num) + return result + + @staticmethod + def is_statically_known_list_of_ints(lst): + return ( + PythonWrapperCodegen.statically_known_list_of_ints_or_none(lst) is not None + ) + + @staticmethod + def static_shape_for_buffer_or_none(buffer): + return PythonWrapperCodegen.statically_known_list_of_ints_or_none( + buffer.get_size() + ) + + @staticmethod + def can_prove_buffer_has_static_shape(buffer): + return PythonWrapperCodegen.static_shape_for_buffer_or_none(buffer) is not None + + def write_kernel_context_guard( + self, + kernel_name: str, + node_schedule: Sequence[BaseSchedulerNode] | ExternKernel, + ): + return + + def write_kernel_context_guard_begin( + self, + ): + """ + Mark the beginning of kernel context guard + """ + return + + def write_kernel_context_guard_end( + self, + ): + """ + Mark the end of kernel context guard + """ + return + + +class SubgraphPythonWrapperCodegen(PythonWrapperCodegen): + """ + A wrapper codegen that generates code for a subgraph. For most of the + methods, we rely on the implementation in the PythonWrapperCodegen. But we + override a few functions to produce cleaner code (like avoiding writing + imports twice in the output code) + """ + + def __init__( + self, + subgraph_name: str, + parent_wrapper: PythonWrapperCodegen, + partition_signatures: ir.GraphPartitionSignature | None = None, + ): + # It is necessary to set the subgraph_name before calling super __init__ + # because __init__ calls set_launcher_fn_name + self.subgraph_name = subgraph_name + self.parent_wrapper = parent_wrapper + self.partition_signatures = partition_signatures + + super().__init__() + + root = self.get_root_graph() + # Only generate auto-tuning block in the main graph + self.kernel_autotune_defs = root.kernel_autotune_defs + self.kernel_autotune_calls = root.kernel_autotune_calls + # Only store kernel src to name mapping in the main graph + self.src_to_kernel = root.src_to_kernel + # Same here, only define user-defined Triton kernels in the main graph + self.user_defined_kernel_cache = root.user_defined_kernel_cache + + def set_launcher_fn_name(self) -> None: + # This sets up the name of the function containing the launcher code of + # the subgraph. + # pyrefly: ignore [bad-assignment] + self.launcher_fn_name = self.subgraph_name + + def write_header(self) -> None: + pass + + def add_benchmark_harness(self, output): + pass + + def benchmark_compiled_module(self, output): + pass + + def write_async_compile_wait(self): + pass + + def next_kernel_suffix(self) -> str: + # Ensures that subgraphs kernels do not clash with each other + return self.parent_wrapper.next_kernel_suffix() + + def generate_after_suffix(self, result: IndentedBuffer) -> None: + return + + def write_launcher_fn_call_get_indent(self) -> int: + self.prefix.splice( + f""" + def {self.launcher_fn_name}(args): + """ + ) + prefix_indent = 1 + return prefix_indent + + def get_wrapper_call_indent(self) -> int: + return 1 + + def get_graph_inputs( + self, + ) -> dict[str, ir.TensorBox | ir.TorchBindObject | sympy.Expr | None]: + if signature := self.partition_signatures: + inputs = signature.input_nodes | { + str(s): s for s in signature.symbol_inputs + } + else: + inputs = V.graph.graph_inputs + return inputs + + def get_graph_input_names(self) -> list[str]: + if signature := self.partition_signatures: + names = list(signature.input_nodes.keys()) + [ + symbol_input.name for symbol_input in signature.symbol_inputs + ] + else: + names = V.graph.graph_input_names + return names + + def get_graph_outputs(self) -> list[IRNode]: + if signature := self.partition_signatures: + outputs = signature.output_nodes + else: + outputs = V.graph.graph_outputs + return outputs + + def codegen_allocation(self, buffer: ir.Buffer): + name = buffer.get_name() + if (signature := self.partition_signatures) and name in signature.input_nodes: + # skip allocation if buffer is a subgraph input. + # This allows reusing an input buffer in graph partition, + # although this is not allowed in general. + return + + super().codegen_allocation(buffer) + + def _write_get_raw_stream( + self, device_idx: int, graph: GraphLowering | None = None + ) -> str: + self.write_triton_header_once() + # pyre-fixme[16]: scheduler.current_stream_name added in scheduler commit + if (current_stream_name := V.graph.scheduler.current_stream_name) is not None: + name = f"{current_stream_name}_raw" + self.writeline( + f"{name} = {V.graph.device_ops.stream_handle(current_stream_name)}" + ) + else: + name = get_raw_stream_name(device_idx) + self.writeline( + f"{name} = get_raw_stream({_coor_device_idx_ref(device_idx)})" + ) + return name + + def codegen_graph_nvtx_range_push(self, post_grad_graph_id: int) -> None: + """Generate NVTX range push for graph.""" + self.writeline(f"torch.cuda.nvtx.range_push('graph {post_grad_graph_id}')") + + def codegen_graph_nvtx_range_pop(self) -> None: + """Generate NVTX range pop for graph.""" + self.writeline("torch.cuda.nvtx.range_pop()") + + @cache_on_self + def write_triton_header_once(self) -> None: + # TODO: Uncomment in future. This will be needed to support subgraph + # codegen for cpp wrapper. + # if config.triton.autotune_at_compile_time: + # import_str = self.triton_header_str() + # self.kernel_autotune_calls.splice(import_str) + self.parent_wrapper.write_triton_header_once() + + @cache_on_self + def write_get_raw_stream_header_once(self) -> None: + # TODO: Uncomment in future. This will be needed to support subgraph + # codegen for cpp wrapper. + # if config.triton.autotune_at_compile_time: + # self.kernel_autotune_calls.writeline( + # V.graph.device_ops.import_get_raw_stream_as("get_raw_stream") + # ) + self.parent_wrapper.write_get_raw_stream_header_once() + + @cache_on_self + def get_root_graph(self) -> PythonWrapperCodegen: + root: PythonWrapperCodegen | SubgraphPythonWrapperCodegen = self + while isinstance(root, SubgraphPythonWrapperCodegen): + root = root.parent_wrapper + + if not isinstance(root, PythonWrapperCodegen): + raise AssertionError(f"expected PythonWrapperCodegen, got {type(root)}") + return root + + def generate_and_run_autotune_block(self): + # Only execute auto-tuning block in the main graph + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/wrapper_fxir.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/wrapper_fxir.py new file mode 100644 index 0000000000000000000000000000000000000000..1a24302d53a5fa036fbbe45ea3c9d90188efc673 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/wrapper_fxir.py @@ -0,0 +1,1412 @@ +import dataclasses +import functools +import logging +import operator +import textwrap +from collections import Counter +from collections.abc import Callable, Iterable, Sequence +from typing import Any + +import sympy + +import torch +from torch._export.passes._node_metadata_hook import ( + _node_metadata_hook, + _set_node_metadata_hook, +) +from torch._higher_order_ops.triton_kernel_wrap import ( + TraceableTritonKernelWrapper, + tracing_triton_hopifier_singleton, + triton_kernel_wrapper_mutation, +) +from torch._inductor.codecache import LambdaFuture, PyCodeCache +from torch._inductor.runtime.triton_heuristics import CachingAutotuner +from torch._inductor.select_algorithm import extern_kernels # noqa: F401 +from torch._inductor.utils import convert_to_symint +from torch._inductor.virtualized import V +from torch._library.triton import wrap_triton +from torch.fx import GraphModule +from torch.fx.experimental.symbolic_shapes import ( + CallMethodKey, + ConvertIntKey, + DivideByKey, +) +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import FloorDiv +from torch.utils._sympy.interp import _run_sympy_handler, sympy_interp +from torch.utils._sympy.reference import OptimizedPythonReferenceAnalysis +from torch.utils._sympy.solve import try_solve + +from .. import config, ir +from ..runtime.triton_compat import Config +from ..utils import cache_property_on_self, LineContext, ValueWithLineMap +from .common import ( + CodegenSymbol, + FileBackedGraphModule, + WorkspaceArg, + WorkspaceZeroMode, +) +from .wrapper import ( + AllocateLine, + BufferLike, + CommentLine, + DynamicScalarLine, + EnterDeviceContextManagerLine, + EnterSubgraphLine, + ExitDeviceContextManagerLine, + ExitSubgraphLine, + ExternKernelAllocLine, + ExternKernelOutLine, + FreeIfNotReusedLine, + FreeLine, + IndexPutFallbackLine, + KernelCallLine, + KernelDefinitionLine, + Line, + MultiOutputLine, + NullLine, + PythonWrapperCodegen, + ReinterpretLine, + ReuseLine, + ScatterFallbackLine, + SubgraphPythonWrapperCodegen, + SwitchLine, + SymbolicCallArg, + SymbolicCallArgLine, + UnbackedSymbolDefsLine, + WrapperLine, +) + + +aten = torch.ops.aten +log = logging.getLogger(__name__) + + +@dataclasses.dataclass +class SymbolBuffer(CodegenSymbol): + """ + Represents a symbolic graph input. Expressions more complex than a single + sympy.Symbol require a name. + """ + + expr: sympy.Expr + name: str | None = None + + def get_name(self) -> str: + if self.name is not None: + return self.name + if not isinstance(self.expr, sympy.Symbol): + raise AssertionError(f"expression requires a name: {self.expr}") + return str(self.expr) + + def get_example(self) -> torch.Tensor | torch.SymInt: + sym_int = convert_to_symint(self.expr) + if not isinstance(sym_int, torch.SymInt): + raise AssertionError(f"expected torch.SymInt, got {type(sym_int)}") + return sym_int + + +CodegenBuffer = BufferLike | SymbolBuffer + + +@dataclasses.dataclass +class TritonKernel: + """ + Stores metadata about Triton kernels for use in FX. + """ + + tuner: CachingAutotuner + wrapped: TraceableTritonKernelWrapper + + +def replace_floor_div(expr: sympy.Expr) -> sympy.Expr: + """ + Replace sympy.floor with FloorDiv. + """ + + def replace(expr: sympy.Expr) -> sympy.Expr: + expr = sympy.together(expr) + + # Division is represented as a Mul with a Rational factor or a Pow with negative + # exponent. We convert floor(Mul(...)) to FloorDiv(numerator, denominator) by + # partitioning factors into the numerator and denominator. + (numerator, denominator) = (sympy.S.One,) * 2 + for arg in sympy.Mul.make_args(expr): + if isinstance(arg, sympy.Rational): + numerator *= arg.numerator + denominator *= arg.denominator + elif isinstance(arg, sympy.Pow) and arg.exp.is_negative: + denominator *= arg.base**-arg.exp + else: + numerator *= arg + + return FloorDiv(numerator, denominator) + + return expr.replace(sympy.floor, replace) + + +class WrapperFxCodegen(PythonWrapperCodegen): + """ + Backend to generate wrapper code as an FX IR graph. + """ + + supports_caching = False + + def __init__(self, *args: Any, **kwargs: Any): + super().__init__(*args, **kwargs) + self.subgms: dict[str, torch.fx.GraphModule] = {} + + def codegen_inputs(self) -> None: + """ + This would generate code for symbolic input shapes, strides, etc. + Since the FX converter handles this, do nothing here. + """ + + def codegen_switch(self, node: ir.Switch) -> None: + """ + Switch/cond codegen normally emits a number of different wrapper lines. + Instead, FX conversion uses a dedicated line for the whole node. + """ + self.writeline(SwitchLine(self, node)) + for subgraph in node.branches: # pyrefly: ignore [not-iterable] + self.codegen_subgraph_common(subgraph) + + def define_subgraph_launcher_fn( + self, name: str, subgraph_code: ValueWithLineMap | FileBackedGraphModule + ) -> None: + """ + Record subgms as they're generated. + """ + if not isinstance(subgraph_code, FileBackedGraphModule): + raise AssertionError( + f"expected FileBackedGraphModule, got {type(subgraph_code)}" + ) + self.subgms[name] = subgraph_code.gm + + @property + @cache_property_on_self + def is_subgraph(self) -> bool: + return isinstance(self, SubgraphPythonWrapperCodegen) + + def get_fx_graph_inputs( + self, + ) -> dict[str, ir.TensorBox | ir.TorchBindObject | sympy.Expr | None]: + """ + Get the input nodes corresponding to FX graph placeholders. + """ + + if V.aot_compilation and not self.is_subgraph: + # AOT graphs must match the signature of the input module. + return { + node.name: V.graph.graph_inputs.get(node.name) + for node in V.graph.module.graph.find_nodes(op="placeholder") # type: ignore[operator, union-attr] + } + + return self.get_graph_inputs() + + def _generate(self, is_inference: bool) -> tuple[FileBackedGraphModule, None]: + self.run_wrapper_ir_passes(is_inference) + + prologue = "\n".join( + [ + self.imports.getvalue(), + self.header.getvalue(), + ] + ) + gm = FxConverter( + lines=self.lines, + prologue=prologue, + graph_inputs=self.get_fx_graph_inputs(), + graph_outputs=self.get_graph_outputs(), + subgms=self.subgms, + is_subgraph=self.is_subgraph, + ).generate() + + compiled_fn = self.compile_graph(gm) + + return FileBackedGraphModule(gm, compiled_fn), None + + def compile_graph(self, gm: GraphModule) -> Callable[..., Any]: + """ + Converts the graph module into a runnable function. The default implementation + is simply an interpreter calling kernels in eager mode. Derived backends can + override this to do further compilation. + """ + return gm.forward + + def write_header(self) -> None: + """ + Python subgraphs normally lack headers. + Override this behavior to generate prologues for FX subgraphs. + """ + PythonWrapperCodegen.write_header(self) + + def register_alignment_check_inputs(self) -> None: + """FXIR does not emit deferred alignment copies. + Alignment is handled by the runtime wrapper.""" + + def codegen_deferred_alignment_copies( + self, input_names: Iterable[str], stream: int = 0 + ) -> None: + """FXIR does not emit deferred alignment copies.""" + + @classmethod + def create( + cls: type["WrapperFxCodegen"], + is_subgraph: bool, + subgraph_name: str | None, + parent_wrapper: PythonWrapperCodegen | None, + partition_signatures: ir.GraphPartitionSignature | None = None, + ) -> "WrapperFxCodegen": + if is_subgraph: + if subgraph_name is None: + raise AssertionError("subgraph_name must not be None for subgraphs") + if parent_wrapper is None: + raise AssertionError("parent_wrapper must not be None for subgraphs") + + # Subgraphs override some methods of PythonWrapperCodegen. + # Apply these overrides to the user-provided class, with priority given to + # user-provided methods. + class SubgraphFxWrapperCodegen(cls, SubgraphPythonWrapperCodegen): # type: ignore[misc,valid-type] + def compile_graph(self, gm: GraphModule) -> Callable[..., Any]: + """ + Skip graph compilation for subgraphs. + """ + + def crash_if_run(*args: Any) -> None: + raise NotImplementedError("Cannot run a subgraph in isolation!") + + return crash_if_run + + return SubgraphFxWrapperCodegen( + subgraph_name, parent_wrapper, partition_signatures + ) + + return cls() + + +@dataclasses.dataclass +class FxConverter: + """ + Generates FX IR from Wrapper IR. As each instance is only meant to be used once, the + input and output code are stored as attributes. + """ + + lines: list[Line] + prologue: str + graph_inputs: dict[str, ir.TensorBox | ir.TorchBindObject | sympy.Expr | None] + graph_outputs: list[ir.IRNode] + subgms: dict[str, torch.fx.GraphModule] + is_subgraph: bool + + def __post_init__(self) -> None: + graph = torch.fx.Graph() + self.gm = GraphModule({}, graph) # Wrapper FX IR. + self.buffer_to_node: dict[ + str | None, torch.fx.Node + ] = {} # Symbol table for codegen. + self.kernels: dict[str, TritonKernel] = {} # Table to store Triton kernels. + self._unique_symbol_ids: Counter[str] = Counter() + self.tracer = torch.fx.proxy.GraphAppendingTracer(graph) + self.expr_to_proxy: dict[sympy.Expr, torch.fx.Proxy] = {} + + def _import_kernel(self, code: str, kernel_name: str) -> CachingAutotuner: + """ + Imports a kernel from source, possibly autotuning block parameters. + """ + module_code = "\n".join([self.prologue, code]) + mod = PyCodeCache.load(module_code) + kernel = getattr(mod, kernel_name) + + if isinstance(kernel, LambdaFuture): + kernel = kernel.result() + + if not isinstance(kernel, CachingAutotuner): + raise NotImplementedError( + textwrap.dedent(f""" + Unsupported type for kernel {kernel_name}: {type(kernel)}. + FX conversion only supports Triton kernels. + """) + ) + + # Parallel compile workers strip the Python function from the pickled + # JITFunction. FXIR stores the JITFunction in the Triton HOP side table, + # so reload it in the parent before runtime execution can need it. + kernel._ensure_kernel_loaded() + + return kernel + + def _create_as_strided( + self, + input_node: torch.fx.Node, + size: tuple[Any, ...], + stride: tuple[Any, ...], + offset: int | sympy.Expr, + ) -> torch.fx.Node: + if isinstance(offset, sympy.Expr): + offset = replace_floor_div(offset) + return self.gm.graph.call_function( + torch.as_strided, + args=( + input_node, + self._generate_sym_nodes(size), + self._generate_sym_nodes(stride), + self._generate_sym_node(offset), + ), + ) + + def _record_allocation(self, buffer: CodegenBuffer, node: torch.fx.Node) -> None: + """ + Updates the symbol table to record that an Inductor buffer maps to the result of + an FX node. + """ + if node in self.buffer_to_node: + raise AssertionError(f"node already recorded in buffer_to_node: {node}") + self.buffer_to_node[buffer.get_name()] = node + + def _free(self, buffer: CodegenBuffer | ir.TorchBindObject) -> None: + """ + Removes the buffer from the symbol table. + """ + name = buffer.get_name() + del self.buffer_to_node[name] + + def _lookup_args(self, args: tuple[Any, ...]) -> tuple[Any, ...]: + """ + Maps call args back to FX nodes. + """ + return tuple( + self.buffer_to_node[arg] + if isinstance(arg, str) + else arg.inner_expr + if isinstance(arg, SymbolicCallArg) + else arg + for arg in args + ) + + def _get_buffer(self, node: ir.IRNode) -> CodegenBuffer: + """ + Extract buffer data from an IR node. + """ + if isinstance(node, (ir.Buffer, WorkspaceArg)): + return node + elif isinstance(node, (ir.BaseView, ir.MutableBox)): + return self._get_buffer(node.data) + elif isinstance(node, sympy.Symbol): + return SymbolBuffer(node) + else: + raise NotImplementedError(f"Unable to extract buffer from node: {node}") + + def _generate_size_proxy( + self, node: torch.fx.Node, expr: sympy.Expr + ) -> torch.fx.Proxy: + proxy = torch.fx.Proxy(node, tracer=self.tracer) + self.expr_to_proxy[expr] = proxy + return proxy + + def _generate_graph_inputs(self) -> None: + """ + Converts graph inputs to FX placeholders. + """ + + for name, ir_node in self.graph_inputs.items(): + if ir_node is None: + # Create dummy input nodes to match the input signature + self.gm.graph.placeholder(name) + continue + + # Introduce a new symbol for constant inputs. + is_constant = isinstance(ir_node, (int, float, sympy.Integer, sympy.Float)) + + # Special handling for dynamic shapes which are not simple symbols. + is_expr = isinstance(ir_node, sympy.Expr) and not isinstance( + ir_node, (sympy.Symbol, sympy.Integer, sympy.Float) + ) + if is_expr and ir_node.is_integer is not True: + raise NotImplementedError( + f"Unsupported non-integer symbolic graph input: {ir_node}" + ) + + if is_constant: + buffer = SymbolBuffer(sympy.Symbol(name, is_integer=True)) + elif is_expr: + buffer = SymbolBuffer(ir_node, name=name) + else: + buffer = self._get_buffer(ir_node) + placeholder_node = self.gm.graph.placeholder(buffer.get_name()) + placeholder_node.meta["val"] = ( + ir_node if is_constant else buffer.get_example() + ) + self._record_allocation(buffer, placeholder_node) + + # Record symbol definitions for dynamic shapes. + if isinstance(ir_node, sympy.Expr) and not is_constant: + self._generate_size_proxy(placeholder_node, ir_node) + + def _generate_graph_input_shapes(self) -> None: + """ + Generate nodes creating symints that are part of graph input + shape/strides. + """ + + def _codegen_symbol( + sym_or_exp: sympy.Symbol | sympy.Expr, + base_node: torch.fx.Node, + target: torch._ops.OpOverload, + dim: int, + ) -> None: + def codegen_proxy() -> torch.fx.Proxy: + size_node = self.gm.graph.call_function(target, (base_node, dim)) + size_proxy = self._generate_size_proxy(size_node, sym_or_exp) + return size_proxy + + if isinstance(sym_or_exp, sympy.Symbol): + if sym_or_exp in self.expr_to_proxy: + return + codegen_proxy() + + elif isinstance(sym_or_exp, sympy.Integer): + return + + elif isinstance(sym_or_exp, sympy.Expr): + # Check if we need to solve for an undefined symbol. + undefined_symbols = [ + sym + for sym in sym_or_exp.free_symbols + if sym not in self.expr_to_proxy + ] + if len(undefined_symbols) == 0: + self._sympy_interp(sym_or_exp) + return + elif len(undefined_symbols) > 1: + raise NotImplementedError( + f"Underdetermined input expression: {sym_or_exp}" + ) + + # Define a new symbol for the input size. + size_proxy = codegen_proxy() + size_symbol = sympy.Symbol( + size_proxy.node.name, integer=True, nonnegative=True + ) + self.expr_to_proxy[size_symbol] = size_proxy + + self._define_symbol_by_solving( + sym_or_exp, size_symbol, undefined_symbols[0] + ) + + for ir_node in self.graph_inputs.values(): + if isinstance(ir_node, ir.TensorBox): + buffer = self._get_buffer(ir_node) + placeholder_node = self.buffer_to_node[buffer.get_name()] + + for dim, size in enumerate(ir_node.get_size()): + _codegen_symbol( + size, placeholder_node, torch.ops.aten.sym_size.int, dim + ) + for dim, stride in enumerate(ir_node.get_stride()): + _codegen_symbol( + stride, placeholder_node, torch.ops.aten.sym_stride.int, dim + ) + + # A compound input binds its whole expression to one placeholder, so a + # symbol appearing only inside it has no node of its own. Recover it + # from that placeholder, after the loop above has defined every symbol + # the tensor shapes determine. + for ir_node in self.graph_inputs.values(): + if not isinstance(ir_node, sympy.Expr) or isinstance(ir_node, sympy.Symbol): + continue + proxy = self.expr_to_proxy.get(ir_node) + if proxy is None: + continue + undefined = [ + sym for sym in ir_node.free_symbols if sym not in self.expr_to_proxy + ] + if len(undefined) == 0: + continue + elif len(undefined) > 1: + # One bound value cannot determine several symbols. This is a + # branch closing over an expression whose symbols come from + # tensors it does not take, such as y.shape[0] + z.shape[0]. + raise NotImplementedError( + f"Compound input {ir_node} leaves these symbols undefined: " + f"{sorted(undefined, key=str)}" + ) + + # A tensor-derived FX node does not reserve its symbol's name, so a + # Dummy is what keeps the anchor from colliding with one. + anchor = sympy.Dummy(proxy.node.name, integer=True) + self.expr_to_proxy[anchor] = proxy + self._define_symbol_by_solving(ir_node, anchor, undefined[0]) + + def _generate_graph_constants(self) -> None: + for name, value in V.graph.constants.items(): + node = self.gm.graph.get_attr(name) + node.meta["val"] = value + setattr(self.gm, name, value) + self.buffer_to_node[name] = node + + def _generate_buffer(self, node: ir.IRNode) -> torch.fx.Node | None: + """ + Generates FX IR for transformations on a buffer, such as ReinterpretView. + Does nothing if no such transformations are present. + """ + + if isinstance(node, ir.ShapeAsConstantBuffer): + # Generate FX nodes to compute the shape expression. + return self._sympy_interp(node.expr).node + + def generate_to_buffer(node: ir.IRNode) -> BufferLike | None: + if isinstance(node, (ir.Buffer, WorkspaceArg)): + return node + elif isinstance(node, ir.NoneAsConstantBuffer): + return None + elif isinstance(node, ir.MutableBox): + return generate_to_buffer(node.data) + elif isinstance(node, ir.ReinterpretView): + # We need to introduce a new symbol if the output is a ReinterpretView. + # Use a WorkspaceArg for this. + buffer = self._get_buffer(node.data) + if not isinstance(buffer, (ir.Buffer, WorkspaceArg)): + raise AssertionError( + f"expected ir.Buffer or WorkspaceArg, got {type(buffer)}" + ) + unique_name = self.gm.graph._graph_namespace.create_name( + f"{buffer.get_name()}_view", None + ) + device = buffer.get_device() + if not device: + raise AssertionError(f"buffer has no device: {buffer}") + reused_as = WorkspaceArg( + count=buffer.get_size(), + zero_mode=WorkspaceZeroMode.UNINITIALIZED, + device=device, + outer_name=unique_name, + dtype=buffer.get_dtype(), + ) + + # Generate FX IR for the view. + self._generate_reinterpret_helper(buffer, reused_as, node.layout) + + return reused_as + else: + raise NotImplementedError(f"Unrecognized buffer/view node: {node}") + + buffer = generate_to_buffer(node) + return self.buffer_to_node[buffer.get_name()] if buffer is not None else None + + def _generate_outputs( + self, + ) -> torch.fx.Node | None | list[torch.fx.Node | None]: + """ + Generate FX IR for graph outputs. + """ + output_nodes = [ + self._generate_buffer(node) for idx, node in enumerate(self.graph_outputs) + ] + + # Parent graphs with single return elements don't use a tuple. + output_value = ( + output_nodes[0] + if len(output_nodes) == 1 and not self.is_subgraph + else output_nodes + ) + + return output_value + + def _generate_subgm_getattrs(self) -> None: + """ + Generate getattr nodes for subgms. + """ + + def generate_getattr(name: str, subgm: torch.fx.GraphModule) -> torch.fx.Node: + self.gm.add_submodule(name, subgm) + node = self.gm.graph.get_attr(name) + node.meta["val"] = subgm + return node + + self.subgm_getattrs = { + name: generate_getattr(name, subgm) for name, subgm in self.subgms.items() + } + + def _get_subgm_attr(self, subgraph: ir.Subgraph) -> torch.fx.Node: + """ + Look up the getattr node for a subgraph. + """ + graph = subgraph.graph + if graph is None: + raise AssertionError("subgraph.graph must not be None") + return self.subgm_getattrs[graph.name] + + def generate(self) -> torch.fx.GraphModule: + """ + Main entrypoint for FX codegen. + """ + self._generate_graph_inputs() + self._generate_graph_constants() + self._generate_subgm_getattrs() + + with _set_node_metadata_hook( + self.gm, + functools.partial(_node_metadata_hook, fake_mode=V.fake_mode), + ): + self._generate_graph_input_shapes() + + # Generate FX IR from Wrapper IR lines. + for line in self.lines: + if isinstance(line, WrapperLine): + line.codegen_fx(self)(line) + elif isinstance(line, LineContext): + # Ignore line context in FX IR. + pass + else: + raise NotImplementedError( + textwrap.dedent( + f""" + Found line of unrecognized type '{type(line)}': + '{line}' + + FX conversion only supports Wrapper IR lines. + """ + ) + ) + + output = self._generate_outputs() + + self.gm.graph.output(output) + self.gm.recompile() + return self.gm + + def _sympy_interp(self, expr: sympy.Expr) -> torch.fx.Proxy: + # hash cons + if expr in self.expr_to_proxy: + return self.expr_to_proxy[expr] + # base cases, don't cache + if isinstance( + expr, + ( + sympy.Integer, + sympy.Number, + sympy.Symbol, + sympy.logic.boolalg.BooleanAtom, + ), + ): + return sympy_interp( + OptimizedPythonReferenceAnalysis, self.expr_to_proxy, expr + ) + + # hash cons on arguments, run expr handler + self.expr_to_proxy[expr] = _run_sympy_handler( + OptimizedPythonReferenceAnalysis, + [self._sympy_interp(arg) for arg in expr.args], + expr, + ) + return self.expr_to_proxy[expr] + + def _define_symbol_by_solving( + self, expr: sympy.Expr, anchor: sympy.Symbol, symbol: sympy.Symbol + ) -> None: + """ + Define symbol by solving expr == anchor, which already maps to a proxy. + """ + # A returned solution directly defines the symbol in terms of the anchor. + solution = try_solve(sympy.Eq(expr, anchor), symbol) + if solution is None: + raise NotImplementedError( + f"Cannot solve input expression {expr} for {symbol}" + ) + + symbol_expr = solution[1] + # If the symbol is an integer, division becomes FloorDiv. + if symbol.is_integer: + symbol_expr = replace_floor_div(sympy.floor(symbol_expr)) + + # Generate FX for the symbol. + self._sympy_interp(symbol_expr) + self.expr_to_proxy[symbol] = self.expr_to_proxy[symbol_expr] + + def _generate_sym_node(self, s: int | sympy.Expr) -> int | torch.fx.Node: + if isinstance(s, (int, sympy.Integer)): + return int(s) + elif isinstance(s, sympy.Symbol): + if s not in self.expr_to_proxy: + raise AssertionError( + f"Could not find a node corresponding to the symbol {s}" + ) + return self.expr_to_proxy[s].node + elif isinstance(s, sympy.Expr): + return self._sympy_interp(s).node + + elif isinstance(s, torch.fx.Node): + return s + + else: + raise ValueError(f"{s} of type {type(s)} is not a valid input") + + def _generate_sym_nodes( + self, shape: Sequence[sympy.Expr] + ) -> list[int | torch.fx.Node]: + return [self._generate_sym_node(s) for s in shape] + + def _generate_allocate(self, line: WrapperLine) -> None: + if not isinstance(line, AllocateLine): + raise AssertionError(f"expected AllocateLine, got {type(line)}") + buffer = line.node + name = buffer.get_name() + if name in V.graph.removed_buffers: + raise AssertionError(f"buffer {name} is in removed_buffers") + + device = buffer.get_device() + if not device: + raise AssertionError(f"buffer has no device: {buffer}") + dtype = buffer.get_dtype() + shape = self._generate_sym_nodes(buffer.get_size()) + stride = self._generate_sym_nodes(buffer.get_stride()) + + node = self.gm.graph.call_function( + torch.empty_strided, + args=(shape, stride), + kwargs={"dtype": dtype, "device": device.type}, + ) + if not name: + raise AssertionError(f"buffer has an empty name: {buffer}") + node.name = name + self._record_allocation(buffer, node) + + def _generate_switch(self, line: WrapperLine) -> None: + if not isinstance(line, SwitchLine): + raise AssertionError(f"expected SwitchLine, got {type(line)}") + + ir_node = line.node + if ir_node.branches is None: + raise AssertionError("ir_node.branches must not be None") + if ir_node.operands is None: + raise AssertionError("ir_node.operands must not be None") + + def generate_buffer(node: ir.IRNode | None) -> torch.fx.Node | None: + if node is None: + raise AssertionError("node must not be None") + return self._generate_buffer(node) + + selector = generate_buffer(ir_node.selector) + operands = tuple(generate_buffer(arg) for arg in ir_node.operands) + branch_subgms = [self._get_subgm_attr(branch) for branch in ir_node.branches] + + if ir_node.is_cond: + # cond expects (selector, true_fn, false_fn, operands) -- branches unpacked positionally. + if len(branch_subgms) != 2: + raise AssertionError( + f"cond requires exactly 2 branches, got {len(branch_subgms)}" + ) + # branches are stored as [false_fn, true_fn] in ir.Switch + false_subgm, true_subgm = branch_subgms + fx_node = self.gm.graph.call_function( + torch.ops.higher_order.cond, + args=(selector, true_subgm, false_subgm, operands), + ) + else: + # switch expects (selector, [branch_fn, ...], operands) -- branches passed as a list. + fx_node = self.gm.graph.call_function( + torch.ops.higher_order.switch, + args=(selector, branch_subgms, operands), + ) + self._record_allocation(ir_node, fx_node) + + def _generate_assert_size_stride(self, line: WrapperLine) -> None: + pass + + def _generate_comment(self, line: WrapperLine) -> None: + if not isinstance(line, CommentLine): + raise AssertionError(f"expected CommentLine, got {type(line)}") + # We ignore comments in FX IR. + + def _generate_dynamic_scalar(self, line: WrapperLine) -> None: + if not isinstance(line, DynamicScalarLine): + raise AssertionError(f"expected DynamicScalarLine, got {type(line)}") + + ir_node = line.node + (input_ir_node,) = ir_node.inputs + if not isinstance(input_ir_node, ir.IRNode): + raise AssertionError(f"expected ir.IRNode, got {type(input_ir_node)}") + input_fx_node = self._generate_buffer(input_ir_node) + keypath = ir_node.keypath + graph = self.gm.graph + + def generate_item(x: torch.fx.Node | None) -> torch.fx.Node: + if x is None: + raise AssertionError("x must not be None") + return graph.call_function( + aten.item.default, + args=(x,), + ) + + if len(keypath) == 0: + result_fx_node = generate_item(input_fx_node) + elif len(keypath) == 1 and isinstance(keypath[0], ConvertIntKey): + where_fx_node = graph.call_function( + aten.where.Scalar, + args=(input_fx_node, 1, 0), + ) + result_fx_node = generate_item(where_fx_node) + else: + raise NotImplementedError(f"Unsupported keypath: {keypath}") + + result_symbol = ir_node.sym + result_buffer = SymbolBuffer(result_symbol) + self._record_allocation(result_buffer, result_fx_node) + self._generate_size_proxy(result_fx_node, result_symbol) + + def _generate_enter_device_context_manager(self, line: WrapperLine) -> None: + if not isinstance(line, EnterDeviceContextManagerLine): + raise AssertionError( + f"expected EnterDeviceContextManagerLine, got {type(line)}" + ) + # We ignore the device context in FX IR. + + def _generate_exit_device_context_manager(self, line: WrapperLine) -> None: + if not isinstance(line, ExitDeviceContextManagerLine): + raise AssertionError( + f"expected ExitDeviceContextManagerLine, got {type(line)}" + ) + # We ignore the device context in FX IR. + + def _generate_enter_subgraph(self, line: WrapperLine) -> None: + if not isinstance(line, EnterSubgraphLine): + raise AssertionError(f"expected EnterSubgraphLine, got {type(line)}") + # We ignore memory planning lines in FX IR. + + def _generate_exit_subgraph(self, line: WrapperLine) -> None: + if not isinstance(line, ExitSubgraphLine): + raise AssertionError(f"expected ExitSubgraphLine, got {type(line)}") + # We ignore memory planning lines in FX IR. + + def _generate_free(self, line: WrapperLine) -> None: + if not isinstance(line, FreeLine): + raise AssertionError(f"expected FreeLine, got {type(line)}") + + buf = line.node + + # No need to free placeholders. + if self.buffer_to_node[buf.get_name()].op == "placeholder": + return + + self._free(buf) + + def _generate_free_if_not_reused(self, line: WrapperLine) -> None: + if not isinstance(line, FreeIfNotReusedLine): + raise AssertionError(f"expected FreeIfNotReusedLine, got {type(line)}") + buf = line.node + if buf.get_name() in V.graph.removed_buffers: + raise AssertionError(f"buffer {buf.get_name()} is in removed_buffers") + if not line.is_reused: + self._free(buf) + + def _generate_line_context(self, line: WrapperLine) -> None: + if not isinstance(line, LineContext): + raise AssertionError(f"expected LineContext, got {type(line)}") + # We ignore line context in FX IR. + + def _generate_reinterpret(self, line: WrapperLine) -> None: + if not isinstance(line, ReinterpretLine): + raise AssertionError(f"expected ReinterpretLine, got {type(line)}") + self._generate_reinterpret_helper(line.node, line.reused_as, line.layout) + + def _generate_reinterpret_helper( + self, input_buffer: BufferLike, result_buffer: BufferLike, layout: ir.Layout + ) -> None: + input_node = self.buffer_to_node[input_buffer.get_name()] + + # Look up output metadata. + name = result_buffer.get_name() + if not name: + raise AssertionError(f"result_buffer has an empty name: {result_buffer}") + size = tuple(layout.size) + stride = tuple(layout.stride) + if isinstance(layout, ir.NonOwningLayout): + # Look up the view's layout. + view = layout.view + if not isinstance(view, ir.ReinterpretView): + raise AssertionError(f"unexpected type: {type(view)}") + layout = view.layout + offset = input_buffer.get_offset() + layout.offset + + # Map ReinterpretView to as_strided. + result_node = self._create_as_strided(input_node, size, stride, offset) + result_node.name = name + self._record_allocation(result_buffer, result_node) + + def _generate_reuse(self, line: WrapperLine) -> None: + if not isinstance(line, ReuseLine): + raise AssertionError(f"expected ReuseLine, got {type(line)}") + old = line.node + new = line.reused_as + if any(buf.get_name() in V.graph.removed_buffers for buf in (old, new)): + raise AssertionError("old or new buffer is in removed_buffers") + if old.get_dtype() != new.get_dtype(): + raise AssertionError( + f"dtype mismatch: {old.get_dtype()} != {new.get_dtype()}" + ) + + old_node = self.buffer_to_node[old.get_name()] + result_node = old_node + + # Change shape and stride. + size = tuple(new.get_size()) + stride = tuple(new.get_stride()) + offset = new.get_offset() + if ( + tuple(old.get_size()) != size + or tuple(old.get_stride()) != stride + or old.get_offset() != offset + ): + result_node = self._create_as_strided(old_node, size, stride, offset) + + self._record_allocation(new, result_node) + + # Free the old buffer, if we allocated a new tensor. + if ( + old.get_name() not in V.graph.get_output_names() + and line.delete_old + and result_node is not old_node + ): + self._free(old) + + def _generate_multi_output(self, line: WrapperLine) -> None: + if not isinstance(line, MultiOutputLine): + raise AssertionError(f"expected MultiOutputLine, got {type(line)}") + + arg_node = self.buffer_to_node[line.arg_name] + + # For non-tuple / non-list outputs, map the + # output to the same node as the input. + if len(line.indices) == 0: + self.buffer_to_node[line.result_name] = arg_node + return + + # Extract the index for tuple access. + inds = line.indices[0][1:] + if len(inds) != 1: + raise AssertionError(f"Cannot convert {inds} to an index.") + idx = inds[0] + + node = self.gm.graph.call_function(operator.getitem, args=(arg_node, idx)) + node.name = line.result_name + self.buffer_to_node[line.result_name] = node + + def _generate_fallback_call( + self, + ir_node: ir.ExternKernel, + args: tuple[Any, ...] | None = None, + kwargs: dict[str, Any] | None = None, + ) -> None: + fx_node = self.gm.graph.call_function( + ir_node.op_overload, # type: ignore[arg-type] + args=args, + kwargs=kwargs, + ) + result_buffer = ir_node.codegen_reference() + self.buffer_to_node[result_buffer] = fx_node + # For in-place mutation ops (e.g., scatter_reduce_, index_put_), + # update the buffer mapping for mutated inputs so downstream + # references to the mutated buffer see the post-mutation node. + for mutated_name in ir_node.get_mutation_names(): + self.buffer_to_node[mutated_name] = fx_node + + def _generate_index_put_fallback(self, line: WrapperLine) -> None: + if not isinstance(line, IndexPutFallbackLine): + raise AssertionError(f"expected IndexPutFallbackLine, got {type(line)}") + ir_node = line.node + + def generate_buffer_or_none( + x: ir.IRNode | Sequence[ir.IRNode] | None, + ) -> torch.fx.Node | None: + """ + Handles None before calling _generate_buffer. + """ + if x is None: + return None + + if not isinstance(x, ir.IRNode): + raise AssertionError(f"expected ir.IRNode, got {type(x)}") + return self._generate_buffer(x) + + (x, values) = [generate_buffer_or_none(t) for t in ir_node.inputs[:2]] + indices = tuple(generate_buffer_or_none(t) for t in line.indices) + accumulate = ir_node.constant_args[0] + args = (x, indices, values, accumulate) + self._generate_fallback_call(ir_node, args) + + def _generate_scatter_fallback(self, line: WrapperLine) -> None: + if not isinstance(line, ScatterFallbackLine): + raise AssertionError(f"expected ScatterFallbackLine, got {type(line)}") + ir_node = line.node + if not ir.is_node_sequence(ir_node.inputs): + raise AssertionError("ir_node.inputs is not a node sequence") + (x, index, src) = [self._generate_buffer(t) for t in ir_node.inputs] + ( + [] if ir_node.src_is_tensor else [ir_node.constant_args[1]] + ) + args = (x, ir_node.constant_args[0], index, src) + kwargs = {} + if reduce := ir_node.kwargs.get("reduce"): + kwargs["reduce"] = reduce + # Only pass kwargs that the op's schema actually accepts, since + # ScatterFallback stores both reduce and include_self for all + # scatter variants, but not all ops support them (e.g., + # scatter_.value has no kwargs, scatter_reduce_.two has both). + if not isinstance(ir_node.op_overload, torch._ops.OpOverload): + raise AssertionError( + f"expected torch._ops.OpOverload, got {type(ir_node.op_overload)}" + ) + schema_arg_names = OrderedSet( + [a.name for a in ir_node.op_overload._schema.arguments] + ) + kwargs = {k: v for k, v in ir_node.kwargs.items() if k in schema_arg_names} + + self._generate_fallback_call(ir_node, args, kwargs) + + def _generate_null(self, line: WrapperLine) -> None: + if not isinstance(line, NullLine): + raise AssertionError(f"expected NullLine, got {type(line)}") + # Does nothing. + + def _generate_comm_buffer_allocate(self, line: WrapperLine) -> None: + if not (isinstance(line, AllocateLine) and line.comm_buffer): + raise AssertionError("expected AllocateLine with comm_buffer set") + raise NotImplementedError("Comm buffer allocation is not yet supported") + + def _generate_comm_buffer_free(self, line: WrapperLine) -> None: + if not (isinstance(line, FreeIfNotReusedLine) and line.comm_buffer): + raise AssertionError("expected FreeIfNotReusedLine with comm_buffer set") + self._free(line.node) + + def _generate_triton_call(self, line: WrapperLine) -> None: + if not isinstance(line, KernelCallLine): + raise AssertionError(f"expected KernelCallLine, got {type(line)}") + + # Collect all kwargs, including autotuned block sizes. + call_args = self._lookup_args(line.call_args) + kernel = self.kernels[line.kernel_name] + tuner = kernel.tuner + + def tune_kernel(tuner: CachingAutotuner, call_args: Sequence[Any]) -> None: + from triton.runtime import driver + + log.info("Autotuning Triton kernel %s at compile time.", kernel_name) + + device = driver.active.get_current_device() + + stream = driver.active.get_current_stream(device) + + def node_to_tuning_arg(arg: Any) -> Any: + """ + Create real tensors for autotuning arguments, substituting size hints + for dynamic shapes. + """ + + def to_size_hint_sympy_int(arg: sympy.Expr | int) -> int: + return V.graph.sizevars.optimization_hint(arg) + + def to_size_hint_list(arg: list[torch.SymInt | int]) -> list[int]: + args_sympy = [ + x.node.expr if isinstance(x, torch.SymInt) else x for x in arg + ] + return pytree.tree_map(to_size_hint_sympy_int, args_sympy) + + if not isinstance(arg, torch.fx.Node): + return to_size_hint_sympy_int(arg) + + fake = arg.meta["val"] + return torch.empty_strided( + to_size_hint_list(fake.shape), + to_size_hint_list(fake.stride()), + dtype=fake.dtype, + device=device, + ).zero_() + + # call args can be fx nodes or sympy expressions or integers! + arg_values = [node_to_tuning_arg(arg) for arg in call_args] + tuner.run(*arg_values, stream=stream) + + # Optionally autotune the kernels. + # The FX backend currently only supports compile-time tuning. + kernel_name = tuner.fn.__name__ + if config.triton.autotune_at_compile_time: + # Skip compile-time autotuning if any unbacked symbol lacks a user-provided + # optimization hint — autotuning with the generic fallback would + # produce meaningless results. + hinted = V.graph.sizevars.all_unbacked_explicitly_hinted + can_tune = True + for arg in call_args: + if isinstance(arg, torch.fx.Node): + fake = arg.meta["val"] + if not hinted(list(fake.shape) + list(fake.stride())): + can_tune = False + break + elif not hinted(arg): + can_tune = False + break + if can_tune: + tune_kernel(tuner, call_args) + else: + log.info( + "Detected unhinted unbacked symints. Skipping compile-time autotuning for kernel %s.", + kernel_name, + ) + else: + log.info( + "Skipping autotuning for kernel %s. Set config.triton.autotune_at_compile_time = True to enable.", + kernel_name, + ) + + triton_meta = tuner.triton_meta + signature = triton_meta["signature"] + + def add_constants_to_call_args( + call_args: Sequence[Any], cfg: Config + ) -> tuple[Any, ...]: + """ + Add constant kwargs to the arg list. + """ + # Add args from the proper Triton signature. + # Exclude constants and config kwargs, as those are tracked separately. + new_call_args = [] + constants = triton_meta["constants"] + call_kwargs = { + key: val + for key, val in zip(signature, call_args) + # pyrefly: ignore [missing-attribute] + if key not in constants and key not in cfg.kwargs + } + + # Add constants stored as Triton metadata, in signature order. + call_kwargs |= constants + new_call_args = [ + call_kwargs[key] + for key in signature + # pyrefly: ignore [missing-attribute] + if key not in cfg.kwargs + ] + + # Add Inductor's extra launcher args to the end. + if extra_launcher_args := tuner.inductor_meta.get("extra_launcher_args"): + new_call_args.extend( + call_args[len(call_args) - len(extra_launcher_args) :] + ) + + return tuple(new_call_args) + + kernel_config = tuner.compile_results[0].config + extra_options = getattr(kernel_config, "extra_options", None) + call_args = add_constants_to_call_args(call_args, kernel_config) + call_args, grid = tuner._interpret_args_grid(call_args, kernel_config) + call_kwargs = dict(zip(signature, call_args)) + # pyrefly: ignore [missing-attribute] + if any(kwarg in kernel_config.kwargs for kwarg in call_kwargs): + raise AssertionError(f"kwargs overlap config: {call_kwargs}") + # pyrefly: ignore [missing-attribute] + call_kwargs.update(kernel_config.kwargs) + + # Replace sympy.floor with FloorDiv, to make the expression traceable. + grid = [replace_floor_div(x) if isinstance(x, sympy.Expr) else x for x in grid] + wrapper_grid = [tuple(self._generate_sym_nodes(grid))] + call_kwargs = { + name: self._generate_sym_node(val) for name, val in call_kwargs.items() + } + backend_options = triton_meta.get("backend_options", {}) + if backend_options: + # FXIR executes Triton kernels through the HOP, not the already + # materialized CachingAutotuner launcher. Preserve backend option + # values in the HOP payload so a direct FXIR run or later Inductor + # re-lowering re-enters Triton JIT with the same compiler options + # that were used during FXIR precompile/autotune. + for name, value in backend_options.items(): + # If the backend option is also a kernel parameter, call_kwargs + # already contains the launch value reconstructed from the Triton + # signature/config. Keep that value and only add backend options + # that are not otherwise represented in the HOP payload. + call_kwargs.setdefault(name, value) + + # Store non-graphable kwargs in the side table. + ( + call_kwargs, + constant_args_idx, + ) = tracing_triton_hopifier_singleton.store_non_graphable_args(call_kwargs) + + hop_kwargs: dict[str, Any] = { + "kernel_idx": kernel.wrapped.kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": wrapper_grid, + "tma_descriptor_metadata": {}, + "kwargs": call_kwargs, + } + if backend_options: + # Keep the FXIR HOP call shape unchanged for normal Inductor + # kernels. Some downstream HOP py_impls have fixed keyword-only + # signatures and only need launch_kwargs when there are real + # Triton backend options to preserve. + hop_kwargs["launch_kwargs"] = tuple(backend_options) + + triton_node = self.gm.graph.call_function( + triton_kernel_wrapper_mutation, + kwargs=hop_kwargs, + ) + if extra_options: + triton_node.meta["extra_options"] = extra_options + + def _generate_extern_kernel_alloc(self, line: WrapperLine) -> None: + if not isinstance(line, ExternKernelAllocLine): + raise AssertionError(f"expected ExternKernelAllocLine, got {type(line)}") + node = line.node + self._generate_extern_kernel_common(node, node) + + def _generate_extern_kernel_out( + self, + line: WrapperLine, + ) -> None: + if not isinstance(line, ExternKernelOutLine): + raise AssertionError(f"expected ExternKernelOutLine, got {type(line)}") + node = line.node + out_node = node.output_view if node.output_view else node + self._generate_extern_kernel_common(node, out_node) + + def _generate_extern_kernel_common( + self, kernel: ir.ExternKernel, out_ir_node: ir.IRNode + ) -> None: + """ + Generates FX IR from either ExternKernelAlloc or ExternKernelOut. + """ + + # Get FX nodes corresponding to the call args. + if not ir.is_node_sequence(kernel.inputs): + raise AssertionError("kernel.inputs is not a node sequence") + tensor_nodes = tuple(self._generate_buffer(arg) for arg in kernel.inputs) + if hasattr(kernel, "unflatten_args"): + args, _ = kernel.unflatten_args(tensor_nodes, kernel.constant_args) + else: + args = tensor_nodes + tuple(kernel.constant_args) + + # Get the result buffer. + # Some kernels write to a pre-existing output tensor via the "out" kwarg. + # Materialize any IR nodes in kwargs to FX nodes (e.g., TensorBox -> Tensor). + kwargs = { + k: self._generate_buffer(v) if isinstance(v, ir.IRNode) else v + for k, v in kernel.kwargs.items() + } + + result_buffer: str | None = None + if isinstance(kernel, ir.ExternKernelOut): + kwargs["out"] = self.buffer_to_node[out_ir_node.codegen_reference()] + elif isinstance(kernel.layout, (ir.Layout, ir.MultiOutputLayout)): + result_buffer = kernel.get_name() + elif isinstance(kernel.layout, ir.NoneLayout): + pass + else: + raise NotImplementedError(f"Unrecognized output layout: {kernel.layout}") + + fx_node = self.gm.graph.call_function( + kernel.op_overload, # type: ignore[arg-type] + args=args, + kwargs=kwargs, + ) + + # Assign the result to the given name. + if result_buffer: + if "out" in kwargs: + raise AssertionError( + f"Extern kernel '{kernel}' has both result and out kwarg. Expected only one." + ) + fx_node.name = result_buffer + self.buffer_to_node[result_buffer] = fx_node + + def _generate_kernel_call(self, line: WrapperLine) -> None: + if not isinstance(line, KernelCallLine): + raise AssertionError(f"expected KernelCallLine, got {type(line)}") + if not line.triton: + raise NotImplementedError("FX conversion only supports Triton kernels.") + + self._generate_triton_call(line) + + def _generate_kernel_definition(self, line: WrapperLine) -> None: + if not isinstance(line, KernelDefinitionLine): + raise AssertionError(f"expected KernelDefinitionLine, got {type(line)}") + + # Generate code for the kernel. + kernel_code = PythonWrapperCodegen._format_kernel_definition( + line.kernel_name, line.kernel_body, metadata=line.metadata + ) + + # Import the module and store the JIT kernel. + tuner = self._import_kernel(kernel_code, line.kernel_name) + wrapped = wrap_triton(tuner.fn) + self.kernels[line.kernel_name] = TritonKernel(tuner, wrapped) + + def _generate_symbolic_call_arg(self, line: WrapperLine) -> None: + if not isinstance(line, SymbolicCallArgLine): + raise AssertionError(f"expected SymbolicCallArgLine, got {type(line)}") + # Store the arg: expr mapping for later use. + arg = line.arg + + inner_expr_proxy = self._sympy_interp(arg.inner_expr) + self.expr_to_proxy[arg.inner] = inner_expr_proxy + + def _generate_unbacked_symbol_defs(self, line: WrapperLine) -> None: + if not isinstance(line, UnbackedSymbolDefsLine): + raise AssertionError(f"expected UnbackedSymbolDefsLine, got {type(line)}") + graph = self.gm.graph + + def convert_key(node: torch.fx.Node, path: pytree.KeyPath) -> torch.fx.Node: + """ + Generate FX IR for each key entry. + """ + # Base case. + if len(path) == 0: + return node + + # Process the first entry and recurse. + entry = path[0] + if isinstance(entry, CallMethodKey): + target = { + "size": aten.sym_size.int, + "stride": aten.sym_stride.int, + "storage_offset": aten.sym_storage_offset, + }[entry.name] + if not callable(target): + raise AssertionError(f"target is not callable: {target}") + node = graph.call_function( + target, + args=( + (node, path[1].idx) + if len(path) > 1 and isinstance(path[1], pytree.SequenceKey) + else (node,) + ), + ) + return convert_key(node, path[1 + len(node.args) :]) + elif isinstance(entry, pytree.SequenceKey): + node = graph.call_function(operator.getitem, args=(node, entry.idx)) + return convert_key(node, path[1:]) + elif isinstance(entry, DivideByKey): + node = graph.call_function( + operator.floordiv, args=(node, entry.divisor) + ) + return convert_key(node, path[1:]) + else: + raise NotImplementedError(f"Unrecognized entry type: {type(entry)}") + + unbacked_bindings = line.unbacked_bindings + if unbacked_bindings is None: + raise AssertionError("line.unbacked_bindings must not be None") + # Kernels with no unbacked symbols aren't recorded in buffer_to_node, so + # return before the output-buffer lookup to avoid a KeyError. Mirrors + # the non-FX wrapper's early return. + if not unbacked_bindings: + return + root_node = self.buffer_to_node[line.output_name] + for s, keypath in unbacked_bindings.items(): + # Check if we already generated this symbol. + if s.name in self.buffer_to_node: + continue + + node = convert_key(root_node, keypath) + out_buffer = SymbolBuffer(s) + self._record_allocation(out_buffer, node) + self._generate_size_proxy(node, s) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41df01f564f7504b57f12f190435f7dbecbd1873 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/compile_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/compile_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1d71485469c7b0bf6544ae50dc46337c1ebc31c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/compile_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/device_op_overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/device_op_overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89f9c0e0f0ee583a33d8ddad0a46e712bb9db017 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/device_op_overrides.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/xpu_combined_scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/xpu_combined_scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50bf0892f8c233de667f1ffe4700669d9dc9e583 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/xpu_combined_scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/xpu_env.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/xpu_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..466c8a3a1f4bfbb6f3f848808b7784bef72c8714 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/xpu_env.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/compile_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/compile_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7e1a80626d943120a7523417b57c710e22fa12b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/compile_utils.py @@ -0,0 +1,145 @@ +# mypy: allow-untyped-defs +import functools +import logging +import os +import shutil +import subprocess + +from torch._inductor import config +from torch._inductor.codegen.xpu.xpu_env import get_xpu_arch +from torch._inductor.utils import is_linux + +from ..cuda.compile_utils import _cutlass_include_paths + + +log = logging.getLogger(__name__) + + +@functools.cache +def icpx_exist(icpx_path: str | None = "icpx") -> bool: + return icpx_path is not None and shutil.which(icpx_path) is not None + + +def _sycl_compiler() -> str: + # Search order: + # 0) which icpx + # 1) config.xpu.oneapi_root + # 2) ONEAPI_ROOT environment variable + # 3) default system search PATH. + if icpx_exist("icpx"): + return "icpx" + + if os.path.exists(config.xpu.oneapi_root or ""): + oneapi_root = config.xpu.oneapi_root + elif os.path.exists(os.getenv("ONEAPI_ROOT") or ""): + oneapi_root = os.getenv("ONEAPI_ROOT") + else: + oneapi_root = None + + if oneapi_root: + oneapi_inclue = os.path.join(oneapi_root, "include") + if "CPLUS_INCLUDE_PATH" in os.environ: + os.environ["CPLUS_INCLUDE_PATH"] += ":" + oneapi_inclue + else: + os.environ["CPLUS_INCLUDE_PATH"] = oneapi_inclue + return os.path.realpath(os.path.join(oneapi_root, "bin/icpx")) + + # Mirrors _cuda_compiler(): return the bare name and let the compile + # subprocess produce the error, so callers can probe with icpx_exist(). + return "icpx" + + +def _sycl_lib_options() -> list[str]: + """ + Util function for CUTLASS backend to find the correct XPU libraries. + """ + # _set_gpu_runtime_env() # cpp_extension consults the env + from torch.utils import cpp_extension + + lpaths = cpp_extension.library_paths(device_type="xpu") + extra_ldflags: list[str] = [] + if is_linux(): + for path in lpaths: + if "torch/lib" in path: + # don't want to depend on pytorch + continue + # -rpath ensures the DLL can find its dependencies when loaded, even + # if the library path is non-standard. + extra_ldflags.extend([f"-L{path}", "-Xlinker", f"-rpath={path}"]) + + extra_ldflags.append("-lsycl") + else: + raise NotImplementedError( + "Unsupported env, failed to find xpu libs! Currently only Linux is supported." + ) + return extra_ldflags + + +def _sycl_arch_as_compile_option() -> str: + arc_option_map = {"Xe12": "pvc", "Xe20": "bmg-g21,bmg-g31"} + arch = get_xpu_arch() + return arc_option_map.get(arch, "pvc") + + +def _sycl_compiler_options() -> list[str]: + options = [ + "-DCUTLASS_ENABLE_SYCL", + "-DSYCL_INTEL_TARGET", + "-DCUTLASS_VERSIONS_GENERATED", + "-O3", + "-DNDEBUG", + "-std=c++20", + "-fPIC", + "-fsycl", + "-fsycl-targets=spir64_gen", + "-Xspirv-translator", + "-spirv-ext=+SPV_INTEL_split_barrier,+SPV_INTEL_2d_block_io,+SPV_INTEL_subgroup_matrix_multiply_accumulate", + "-fno-sycl-instrument-device-code", + "-DMKL_ILP64", + "-MD", + "-Xs", + ( + f"-device {_sycl_arch_as_compile_option()} " + "-options \"-igc_opts 'VISAOptions=-perfmodel,VectorAliasBBThreshold=100000000000," + "ExtraOCLOptions=-cl-intel-256-GRF-per-thread'\" " + "-options -ze-opt-large-register-file" + ), + ] + if config.cutlass.enable_debug_info: + options.extend(["-lineinfo", "-g", "-DCUTLASS_DEBUG_TRACE_LEVEL=1"]) + return options + + +def xpu_compile_command( + src_files: list[str], + dst_file: str, + dst_file_ext: str, + extra_args: list[str] | None = None, +) -> str: + if extra_args is None: + extra_args = [] + include_paths = _cutlass_include_paths() + sycl_lib_options = _sycl_lib_options() + sycl_compiler_options = _sycl_compiler_options() + + # Build command as a list to preserve arguments with spaces + cmd_parts = ( + [_sycl_compiler()] + + extra_args + + ["-I" + path for path in include_paths] + + ["-isystem", "/include"] + + sycl_compiler_options + + sycl_lib_options + ) + if dst_file_ext == "o": + cmd_parts.extend(["-c", "-o", dst_file] + src_files) + elif dst_file_ext == "so": + cmd_parts.extend(["-shared", "-o", dst_file] + src_files) + elif dst_file_ext == "exe": + cmd_parts.extend(["-o", dst_file] + src_files) + else: + raise NotImplementedError(f"Unsupported output file suffix {dst_file_ext}!") + + res = subprocess.list2cmdline(cmd_parts) + log.debug("XPU command: %s", res) + return res diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/device_op_overrides.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/device_op_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..73bc083f3cd7b632350c84208713dd660c9aa4a3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/device_op_overrides.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +from ..common import ( + DeviceIdx, + DeviceOpOverrides, + register_device_op_overrides, + TritonScratchWorkspace, +) + + +class XPUDeviceOpOverrides(DeviceOpOverrides): + def import_get_raw_stream_as(self, name: str) -> str: + return f"from torch._C import _xpu_getCurrentRawStream as {name}" + + def set_device(self, device_idx: DeviceIdx) -> str: + return f"torch.xpu.set_device({device_idx})" + + def synchronize(self) -> str: + return "torch.xpu.synchronize()" + + def device_guard(self, device_idx: DeviceIdx) -> str: + return f"torch.xpu._DeviceGuard({device_idx})" + + def current_device_idx_expr(self) -> str: + return "torch.xpu.current_device()" + + def current_stream(self) -> str: + return "torch.xpu.current_stream()" + + def cpp_device_guard(self) -> str: + return "at::DeviceGuard" + + def cpp_aoti_device_guard(self) -> str: + return "AOTIXpuGuard" + + def cpp_stream_guard(self) -> str: + return "at::xpu::XPUStreamGuard" + + def cpp_aoti_stream_guard(self) -> str: + return "AOTIXpuStreamGuard" + + def cpp_getStreamFromExternal(self) -> str: + return "at::xpu::getStreamFromExternal" + + def kernel_header(self) -> str: + source_codes = """ + #include + """ + return source_codes + + def kernel_driver(self) -> str: + return "" + + def cpp_stream_type(self) -> str: + return "sycl::queue*" + + def aoti_get_stream(self) -> str: + return "aoti_torch_get_current_xpu_stream" + + def cpp_kernel_type(self) -> str: + return "std::unique_ptr" + + def cpp_device_ptr(self) -> str: + return "void *" + + def cpp_scratch( + self, idx: int, workspace: TritonScratchWorkspace, prefix: str | None = None + ) -> tuple[list[str], str] | None: + return [f"void *global_scratch_{idx} = 0;"], f"global_scratch_{idx}" + + +register_device_op_overrides("xpu", XPUDeviceOpOverrides()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/xpu_combined_scheduling.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/xpu_combined_scheduling.py new file mode 100644 index 0000000000000000000000000000000000000000..cdde64c4eb7d0495e77ee40be25450fd1588c598 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/xpu_combined_scheduling.py @@ -0,0 +1,139 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +from typing import Any, TYPE_CHECKING + +from torch._inductor.scheduler import ( + BaseSchedulerNode, + BaseScheduling, + FusedSchedulerNode, + Scheduler, + SchedulerNode, +) + +from ..cutlass.scheduling import CUTLASSScheduling +from ..triton import TritonScheduling + + +if TYPE_CHECKING: + from collections.abc import Sequence + from typing import TypeAlias + + from sympy import Expr + + import torch + from torch.utils._ordered_set import OrderedSet + + from ..common import BackendFeature + + _IntLike: TypeAlias = int | Expr + + +class XPUCombinedScheduling(BaseScheduling): + """ + Scheduler for XPU Kernels, which delegates calls as appropriate + to the SYCL-C++ and Triton Schedulers, which both work for XPU devices + and use a unified-wrapper for codegen. + + If Scheduling code needs to be specialized for the case of mixed Triton / SYCL C++ code, + this would also be the place to do it. + """ + + def __init__(self, scheduler: Scheduler | None) -> None: + super().__init__(scheduler) + self._triton_scheduling = TritonScheduling(scheduler) + self._cutlass_scheduling = CUTLASSScheduling(scheduler) + + def get_backend_features(self, device: torch.device) -> OrderedSet[BackendFeature]: + return self._triton_scheduling.get_backend_features(device) + + def choose_node_backend(self, node: BaseSchedulerNode) -> BaseScheduling: + if self._cutlass_scheduling.is_cutlass_template(node): + return self._cutlass_scheduling + return self._triton_scheduling + + def can_fuse_vertical( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + if self._cutlass_scheduling.can_fuse_vertical(node1, node2): + return True + elif self._cutlass_scheduling.is_cutlass_template( + node1 + ) or self._cutlass_scheduling.is_cutlass_template(node2): + return False + return self._triton_scheduling.can_fuse_vertical(node1, node2) + + def can_fuse_horizontal( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + for node in (node1, node2): + if self._cutlass_scheduling.is_cutlass_template(node): + return self._cutlass_scheduling.can_fuse_horizontal( + node1, node2 + ) # always False at the moment + return self._triton_scheduling.can_fuse_horizontal(node1, node2) + + def group_fn( + self, sizes: Sequence[Sequence[_IntLike]] + ) -> tuple[tuple[_IntLike, ...], ...]: + return self._triton_scheduling.group_fn(sizes) + + def codegen_template( + self, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + prologue_nodes: Sequence[BaseSchedulerNode], + ) -> str | None: + if self._cutlass_scheduling.is_cutlass_template(template_node): + if prologue_nodes: + raise AssertionError("cutlass template does not support prologue_nodes") + return self._cutlass_scheduling.codegen_template( + template_node, epilogue_nodes, prologue_nodes + ) + else: + return self._triton_scheduling.codegen_template( + template_node, epilogue_nodes, prologue_nodes + ) + + def codegen_mix_order_reduction(self, node): + return self._triton_scheduling.codegen_mix_order_reduction(node) + + def codegen_nested_reduction(self, node): + return self._triton_scheduling.codegen_nested_reduction(node) + + def codegen_node(self, node: FusedSchedulerNode | SchedulerNode) -> None: + return self._triton_scheduling.codegen_node(node) + + def codegen_sync(self) -> None: + return self._triton_scheduling.codegen_sync() + + def flush(self) -> None: + return self._triton_scheduling.flush() + + def codegen_combo_kernel(self, *args: Any, **kwargs: Any) -> None: + return self._triton_scheduling.codegen_combo_kernel(*args, **kwargs) + + def benchmark_fused_nodes( + self, nodes: Sequence[BaseSchedulerNode] + ) -> tuple[float, str]: + return self._triton_scheduling.benchmark_fused_nodes(nodes) + + def benchmark_codegened_module(self, module): + return self._triton_scheduling.benchmark_codegened_module(module) + + def generate_kernel_code_from_nodes( + self, + nodes: Sequence[Any], + benchmark_kernel: bool = False, + hint_override: int | None = None, + ) -> str: + return self._triton_scheduling.generate_kernel_code_from_nodes( + nodes, benchmark_kernel, hint_override=hint_override + ) + + def benchmark_combo_kernel( + self, node_list: Sequence[BaseSchedulerNode], node_benchmark_results + ) -> tuple[float, float, list[str | None]]: + return self._triton_scheduling.benchmark_combo_kernel( + node_list, node_benchmark_results + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/xpu_env.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/xpu_env.py new file mode 100644 index 0000000000000000000000000000000000000000..a74b4cf2a24c7d079b68d46216c24cb2e484717c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/xpu_env.py @@ -0,0 +1,38 @@ +import functools +import logging + +import torch +from torch._inductor.utils import clear_on_fresh_cache + + +log = logging.getLogger(__name__) + + +@clear_on_fresh_cache +@functools.lru_cache(1) +def get_xpu_arch() -> str | None: + from torch.testing._internal.common_xpu import get_xpu_codename, XPUCodename + + name2arch = { + XPUCodename.PVC: "Xe12", + XPUCodename.BMG: "Xe20", + } + + codename = get_xpu_codename() + if not codename or codename not in name2arch: + log.warning("Unknown XPU codename, cannot determine architecture") + return None + + return name2arch[codename] + + +@clear_on_fresh_cache +@functools.lru_cache(1) +def get_xpu_version() -> str | None: + # string of version, like 20250101 + try: + xpu_version = torch.version.xpu or "" + return xpu_version + except Exception: + log.exception("Error getting xpu version") + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/comm_analysis.py b/.venv/lib/python3.12/site-packages/torch/_inductor/comm_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..18b8ae5290a7b34bedaef6308c8aa2e68b169e6d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/comm_analysis.py @@ -0,0 +1,922 @@ +import functools +import logging +import math +import operator +from dataclasses import dataclass +from enum import IntEnum +from typing import Any + +import sympy + +import torch +import torch.utils._pytree as pytree +from torch.fx.experimental.symbolic_shapes import optimization_hint +from torch.fx.operator_schemas import normalize_function + +from . import ir +from .utils import get_dtype_size, snode_args_kwargs, sympy_product +from .virtualized import V + + +log = logging.getLogger(__name__) + + +class NCCL_COLL(IntEnum): + ALL_REDUCE = 0 + ALL_GATHER = 1 + REDUCE_SCATTER = 2 + ALL_TO_ALL = 3 + UNSUPPORTED = 4 + P2P = 5 + + +class NVIDIA_GPU_TYPE(IntEnum): + VOLTA = 0 + AMPERE = 1 + HOPPER = 2 + BLACKWELL = 3 + + +class InterconnectType(IntEnum): + NVLINK_V100 = 0 + NVLINK_A100 = 1 + NVLINK_H100 = 2 + NVLINK_B200 = 3 + IB_HDR = 4 # 200 Gbps InfiniBand + IB_NDR = 5 # 400 Gbps InfiniBand / RoCE + PCIE = 6 # PCIe (no NVLink) + + +@dataclass(frozen=True) +class InterconnectProfile: + """Empirically calibrated interconnect parameters for saturation estimation.""" + + bus_bw_GBps: float # effective bus bandwidth at large messages (GB/s) + latency_per_hop_us: float # per-ring-step latency (us) + base_latency_us: float # fixed startup latency (us) + min_saturation_bytes: int = 0 # floor for small group sizes + + +_MB = 1024 * 1024 + +# Empirically calibrated per-interconnect profiles for saturation estimation. +# NVLink bus_bw from https://github.com/NVIDIA/nccl/blob/master/src/graph/topo.h +# IB hop_lat/base_lat from MAST sweep profiles on H100 GrandTeton RoCE +# (see agent_space/nccl_model_validation.md for calibration data). +# IB min_saturation_bytes floors the estimate for small group sizes where the +# ring-step formula underestimates. +INTERCONNECT_PROFILES: dict[InterconnectType, InterconnectProfile] = { + InterconnectType.NVLINK_H100: InterconnectProfile(36.0, 40.0, 10.0), + InterconnectType.NVLINK_A100: InterconnectProfile(22.0, 45.0, 10.0), + InterconnectType.NVLINK_B200: InterconnectProfile(60.0, 30.0, 10.0), + InterconnectType.NVLINK_V100: InterconnectProfile(14.0, 50.0, 10.0), + InterconnectType.IB_NDR: InterconnectProfile( + 22.0, 12.0, 30.0, min_saturation_bytes=100 * _MB + ), + InterconnectType.IB_HDR: InterconnectProfile( + 11.0, 14.0, 30.0, min_saturation_bytes=75 * _MB + ), + # PCIe: ~10 GB/s effective NCCL bus BW (GPU->CPU->GPU ring steps) + InterconnectType.PCIE: InterconnectProfile(10.0, 60.0, 15.0), +} + +_GPU_TO_INTRA: dict[NVIDIA_GPU_TYPE, InterconnectType] = { + NVIDIA_GPU_TYPE.VOLTA: InterconnectType.NVLINK_V100, + NVIDIA_GPU_TYPE.AMPERE: InterconnectType.NVLINK_A100, + NVIDIA_GPU_TYPE.HOPPER: InterconnectType.NVLINK_H100, + NVIDIA_GPU_TYPE.BLACKWELL: InterconnectType.NVLINK_B200, +} +_GPU_TO_INTER: dict[NVIDIA_GPU_TYPE, InterconnectType] = { + NVIDIA_GPU_TYPE.VOLTA: InterconnectType.IB_HDR, + NVIDIA_GPU_TYPE.AMPERE: InterconnectType.IB_HDR, + NVIDIA_GPU_TYPE.HOPPER: InterconnectType.IB_NDR, + NVIDIA_GPU_TYPE.BLACKWELL: InterconnectType.IB_NDR, +} + + +@functools.lru_cache +def _has_nvlink() -> bool: + """Detect NVLink via nvidia-smi topology, falling back to peer access check.""" + import subprocess + + if not torch.cuda.is_available() or torch.cuda.device_count() < 2: + return True # Single GPU: interconnect irrelevant + try: + result = subprocess.run( + ["nvidia-smi", "topo", "-m"], + capture_output=True, + text=True, + timeout=5, + ) + if result.returncode == 0: + # Check GPU-GPU section (before Legend) for "NV" links + topo = result.stdout.split("Legend")[0] + return "NV" in topo + except (subprocess.TimeoutExpired, OSError): + pass + # Fallback: peer access generally implies NVLink on datacenter GPUs + try: + return torch.cuda.can_device_access_peer(0, 1) + except (AssertionError, RuntimeError): + return True + + +@functools.lru_cache +def get_gpu_type() -> NVIDIA_GPU_TYPE: + # Prefer compute capability (works for all NVIDIA GPUs, including H200, L40, etc.) + if torch.cuda.is_available() and torch.cuda.device_count() > 0: + major = torch.cuda.get_device_properties(0).major + if major >= 10: + return NVIDIA_GPU_TYPE.BLACKWELL + if major >= 9: + return NVIDIA_GPU_TYPE.HOPPER + if major >= 8: + return NVIDIA_GPU_TYPE.AMPERE + if major >= 7: + return NVIDIA_GPU_TYPE.VOLTA + # Fallback: nvidia-smi string matching + gpu_info = torch.utils.collect_env.get_gpu_info(torch.utils.collect_env.run) or "" + if "V100" in gpu_info: + return NVIDIA_GPU_TYPE.VOLTA + elif "A100" in gpu_info: + return NVIDIA_GPU_TYPE.AMPERE + elif "H100" in gpu_info: + return NVIDIA_GPU_TYPE.HOPPER + elif any(gpu in gpu_info for gpu in ("B100", "B200", "B300")): + return NVIDIA_GPU_TYPE.BLACKWELL + else: + return NVIDIA_GPU_TYPE.AMPERE + + +def detect_interconnect(group_size: int) -> InterconnectType: + """Auto-detect interconnect type from GPU generation and group topology.""" + gpus_per_node = torch.cuda.device_count() if torch.cuda.is_available() else 8 + gpu_gen = get_gpu_type() + if math.ceil(group_size / gpus_per_node) == 1: + if not _has_nvlink(): + return InterconnectType.PCIE + return _GPU_TO_INTRA.get(gpu_gen, InterconnectType.NVLINK_A100) + return _GPU_TO_INTER.get(gpu_gen, InterconnectType.IB_HDR) + + +def get_collective_type_from_kernel_name(kernel_name: str) -> NCCL_COLL: + if kernel_name is None: + raise AssertionError("kernel_name must not be None") + if "all_reduce" in kernel_name: + return NCCL_COLL.ALL_REDUCE + elif "all_gather" in kernel_name: + return NCCL_COLL.ALL_GATHER + elif "reduce_scatter" in kernel_name: + return NCCL_COLL.REDUCE_SCATTER + elif any(comm in kernel_name for comm in ("all_to_all", "alltoall")): + return NCCL_COLL.ALL_TO_ALL + elif any(comm in kernel_name for comm in ("isend", "irecv", "batch_p2p")): + return NCCL_COLL.P2P + else: + return NCCL_COLL.UNSUPPORTED + + +def get_collective_type(node: ir.IRNode) -> NCCL_COLL: + if not isinstance(node, ir._CollectiveKernel): + raise ValueError(f"node is not a collective kernel: {node}") + + name = node.python_kernel_name + if name is None: + raise AssertionError("node.python_kernel_name must not be None") + return get_collective_type_from_kernel_name(name) + + +def get_ir_node_size_numel(size: torch.Size, fallback: int = 4096 * 4096) -> int: + numel = sympy_product(size) + if isinstance(numel, sympy.Integer): + return int(numel) + return V.graph.sizevars.optimization_hint(numel, fallback=fallback) + + +def get_fx_node_size_numel(size: torch.Size, fallback: int = 4096 * 4096) -> int: + numel = functools.reduce(operator.mul, size, 1) + result = optimization_hint(numel, fallback=fallback) + return result + + +def get_collective_input_size_bytes(node: ir.IRNode) -> int: + sz_bytes = 0 + for inp in node.inputs: # type: ignore[attr-defined] + numel = get_ir_node_size_numel(inp.layout.size) + sz_bytes += numel * get_dtype_size(inp.layout.dtype) + return sz_bytes + + +def get_collective_group_size(node: ir.IRNode) -> int: + if isinstance(node, ir._CollectiveKernel) and not isinstance(node, ir._WaitKernel): + from torch.distributed.distributed_c10d import _get_group_size_by_name + + return _get_group_size_by_name(node.constant_args[-1]) + else: + raise TypeError(f"Unsupported collective type: {node}") + + +#################################################################################################################### +# The following code and constants are adapted from https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc # +#################################################################################################################### + + +class NCCL_HW(IntEnum): + NVLINK = 0 + PCI = 1 + NET = 2 + + +class NCCL_ALGO(IntEnum): + TREE = 0 + RING = 1 + + +class NCCL_PROTO(IntEnum): + # Matches NCCL devcomm.h protocol enum + LL = 0 # Low-latency + LL128 = 1 # Low-latency 128-byte + SIMPLE = 2 + + +_NUM_ALGOS = 2 # TREE, RING +_NUM_PROTOS = 3 # LL, LL128, SIMPLE + +# Base latencies in us — [algo][proto] +# https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults) +baseLat = [ + # Tree + [6.8, 14.0, 8.4], + # Ring + [6.6, 14.0, 8.4], +] + +# Hardware latencies in us — [hw][algo][proto] +# https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults) +hwLat = [ + # NVLINK + [ + [0.6, 1.25, 4.0], # Tree + [0.6, 1.9, 3.4], # Ring + ], + # PCI + [ + [1.0, 1.9, 4.0], # Tree + [1.0, 2.5, 5.7], # Ring + ], + # NET + [ + [5.0, 8.5, 14.0], # Tree + [2.7, 4.0, 14.0], # Ring + ], +] + + +# LL max bus BW — [compCapIndex][scaleIndex(N1/N2/N4+)] +# https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults) +llMaxBws = [ + [39.0, 39.0, 20.4], # Volta + [87.7, 22.5, 19.0], # Ampere + [141.0, 45.0, 35.0], # Hopper + [282.0, 90.0, 70.0], # Blackwell +] + +# Per-channel max BW caps — [compCapIndex][scaleIndex] +# https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults) +perChMaxRingLL128Bws = [ + [20.0, 20.0, 20.0], # Volta + [20.0, 20.0, 20.0], # Ampere + [36.7, 36.7, 36.7], # Hopper + [40.0, 40.0, 40.0], # Blackwell +] + +# https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults) +perChMaxTreeLL128Bws = [ + [20.0, 20.0, 20.0], # Volta + [20.0, 20.0, 20.0], # Ampere + [36.7, 36.7, 29.0], # Hopper + [55.6, 31.67, 20.0], # Blackwell +] + +# https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults) +perChMaxTreeBws = [ + [26.5, 18.5, 10.0], # Volta + [24.0, 23.6, 17.8], # Ampere + [38.7, 41.4, 36.0], # Hopper + [70.0, 42.8, 24.0], # Blackwell +] + +# Tree correction factor for medium message sizes — [proto][logSize] +# logSize = log2(nBytes >> 6), indices 0..23 map to 64B..256MB +# https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults) +treeCorrectionFactor = [ + # LL + [ + 1.0, + 1.0, + 1.0, + 1.0, + 0.9, + 0.8, + 0.7, + 0.7, + 0.7, + 0.7, + 0.6, + 0.5, + 0.4, + 0.4, + 0.5, + 0.6, + 0.7, + 0.8, + 0.9, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + ], + # LL128 + [ + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 0.9, + 0.8, + 0.8, + 0.8, + 0.7, + 0.6, + 0.6, + 0.6, + 0.6, + 0.6, + 0.6, + 0.8, + 0.9, + 0.9, + 0.9, + 0.9, + 1.0, + 1.0, + 1.0, + ], + # SIMPLE + [ + 0.9, + 0.9, + 0.9, + 0.9, + 0.9, + 0.9, + 0.9, + 0.8, + 0.7, + 0.6, + 0.6, + 0.5, + 0.5, + 0.5, + 0.5, + 0.6, + 0.7, + 0.8, + 0.7, + 0.7, + 0.8, + 0.9, + 0.9, + 0.9, + ], +] + +# Heuristic nChannels per GPU generation. +# NCCL selects dynamically via topology search (up to MAXCHANNELS/2=32 for ring). +# These approximate standard DGX/HGX topologies; see nccl/src/graph/search.cc. +_GPU_NCHANNELS = { + NVIDIA_GPU_TYPE.VOLTA: 2, + NVIDIA_GPU_TYPE.AMPERE: 8, + NVIDIA_GPU_TYPE.HOPPER: 16, + NVIDIA_GPU_TYPE.BLACKWELL: 32, +} + +# NVLink bus bandwidth per GPU (GB/s). +# https://github.com/NVIDIA/nccl/blob/master/src/graph/topo.h (link speed constants) +_GPU_NVLINK_BW: dict[NVIDIA_GPU_TYPE, float] = { + NVIDIA_GPU_TYPE.VOLTA: 120.0, + NVIDIA_GPU_TYPE.AMPERE: 240.0, + NVIDIA_GPU_TYPE.HOPPER: 370.0, + NVIDIA_GPU_TYPE.BLACKWELL: 720.0, +} + +# PCIe effective intra-node bandwidth (GB/s) for NCCL ring. +# Conservative: GPU->CPU->GPU ring steps limit effective BW well below link rate. +_PCIE_INTRA_NODE_BW = 24.0 + +# Per-GPU inter-node bandwidth (GB/s), assuming 1:1 GPU:NIC ratio. +# HDR: 200Gbps=25GB/s, NDR: 400Gbps=50GB/s per NIC. +_GPU_INTER_NODE_BW: dict[NVIDIA_GPU_TYPE, float] = { + NVIDIA_GPU_TYPE.VOLTA: 12.0, + NVIDIA_GPU_TYPE.AMPERE: 25.0, + NVIDIA_GPU_TYPE.HOPPER: 50.0, + NVIDIA_GPU_TYPE.BLACKWELL: 50.0, +} + + +def get_intra_node_bw() -> float: + """Return intra-node bandwidth in GB/s. Config overrides auto-detection.""" + override = torch._inductor.config.intra_node_bw + if override is not None: + return float(override) + if not _has_nvlink(): + return _PCIE_INTRA_NODE_BW + return _GPU_NVLINK_BW.get(get_gpu_type(), 240.0) + + +def get_inter_node_bw() -> float: + """Return inter-node (IB/RoCE) bandwidth in GB/s. Config overrides auto-detection.""" + override = torch._inductor.config.inter_node_bw + if override is not None: + return float(override) + return _GPU_INTER_NODE_BW.get(get_gpu_type(), 25.0) + + +def _log2i(n: int) -> int: + """Integer log2, matching NCCL's log2i (floor of log2).""" + if n <= 0: + return 0 + r = 0 + while n > 1: + n >>= 1 + r += 1 + return r + + +def estimate_nccl_collective_runtime_nccl_estimator(snode) -> float | None: # type: ignore[no-untyped-def] + kernel = snode.node + if kernel is None: + raise AssertionError("snode.node must not be None") + py_kernel_name = getattr(kernel, "python_kernel_name", "") + pg_name = kernel.constant_args[-1] # type: ignore[attr-defined] + from torch.distributed.distributed_c10d import _resolve_process_group + + pg = _resolve_process_group(pg_name) + rank: int = torch.distributed.get_rank(pg) + # TODO(ivankobzarev): Figure out how we can use time estimations, + # without cuda allocations. + device = torch.device(f"cuda:{rank}") + + fn = eval(py_kernel_name) + args, kwargs = snode_args_kwargs(snode) + + # TODO(ivankobzarev): fix out variants snode_args_kwargs + if "all_gather_into_tensor_out" in py_kernel_name: + args = args[1:] + args[0] + + with torch.distributed._time_estimator(group=pg, device=device) as time_estimator: + w = fn(*args, **kwargs) + torch.ops._c10d_functional.wait_tensor.default(w) + + est_time_us = time_estimator.estimated_time + if est_time_us is None: + raise AssertionError("NCCL time estimator did not produce a result") + # -1000 constant is NCCL return in case of error during estimations. + # Observed it for all_to_all estimations. + if est_time_us < 0: + return None + est_time_ms = est_time_us / 1e3 + return est_time_ms + + +def _nccl_algo_time( + nBytes: int, + group_size: int, + coll: NCCL_COLL, + algo: int, + proto: int, +) -> float: + """Compute NCCL estimated time in us for a given (algo, proto) pair. + + Mirrors ncclTopoTuneModel bandwidth/latency computation and + ncclTopoGetAlgoTime from NCCL tuning.cc. Returns -1 if the + (algo, proto) combination is disabled for this configuration. + """ + gpus_per_node = torch.cuda.device_count() if torch.cuda.is_available() else 8 + nNodes = math.ceil(group_size / gpus_per_node) + nRanks = group_size + compCapIndex = get_gpu_type() + index2 = nNodes - 1 if nNodes <= 2 else 2 + + # Total bus bandwidth (not per-channel). Auto-detected from GPU + # generation, or overridden by config. nChannels is only used for + # per-channel BW cap table lookups. + bwIntra = get_intra_node_bw() + bwInter = get_inter_node_bw() + nChannels = _GPU_NCHANNELS.get(compCapIndex, 8) + + # Detect interconnect for IB-specific corrections + interconnect = detect_interconnect(group_size) + is_ib = interconnect in (InterconnectType.IB_NDR, InterconnectType.IB_HDR) + + # LL128: disable for inter-node IB (BW tables calibrated for NVLink only) + # and for large-scale multi-node (>2 nodes) + if proto == NCCL_PROTO.LL128: + if nNodes > 2: + return -1.0 + if nNodes > 1 and is_ib: + return -1.0 + + # --- Bandwidth computation (mirrors ncclTopoTuneModel) --- + # For IB interconnect, always use inter-node BW (bwIntra only for NVLink). + # Original NCCL tuning.cc uses bwIntra for nNodes<=2, designed for NVSwitch; + # doesn't apply to IB. + if nNodes == 1: + bw = bwIntra + elif is_ib: + bw = bwInter + else: + bw = bwIntra if nNodes <= 2 else bwInter + + # IB corrections calibrated against H100 GrandTeton RoCE profiles + # (see agent_space/nccl_model_validation.md for calibration data): + if is_ib and nNodes > 1: + # NIC efficiency: fewer nodes → fewer NICs utilized → lower effective BW. + # 2-node (single inter-hop): ~0.80×; 8+ nodes: ~1.0× + nic_efficiency = 0.77 + 0.23 * min(1.0, (nNodes - 1) / 7) + bw *= nic_efficiency + # Multi-rail: larger messages utilize more NICs (8 NICs per H100 node). + # Power-law fit (exponent 0.17) to non-coalesced profile BW vs size. + if nNodes > 2: + multi_rail = (max(nBytes, 50_000_000) / 50_000_000) ** 0.17 + bw *= multi_rail + + busBw = bw + + index1 = compCapIndex if nNodes == 1 else 0 + llMaxBw = llMaxBws[index1][index2] + + if algo == NCCL_ALGO.RING and proto == NCCL_PROTO.LL: + busBw = min(llMaxBw, busBw * 0.5) + elif algo == NCCL_ALGO.RING and proto == NCCL_PROTO.LL128: + busBw = min( + busBw * (120.0 / 128.0), + nChannels * perChMaxRingLL128Bws[compCapIndex][index2], + ) + elif algo == NCCL_ALGO.TREE and proto == NCCL_PROTO.LL: + busBw = min(busBw * (1.0 / 3.8), llMaxBw) + elif algo == NCCL_ALGO.TREE and proto == NCCL_PROTO.LL128: + factor = 7.0 / 9.0 if nNodes == 1 else 120.0 / 128.0 + busBw = min( + busBw * factor, + nChannels * perChMaxTreeLL128Bws[compCapIndex][index2], + ) + elif algo == NCCL_ALGO.TREE and proto == NCCL_PROTO.SIMPLE: + if coll == NCCL_COLL.ALL_REDUCE: + busBw = min(busBw * 0.92, nChannels * perChMaxTreeBws[compCapIndex][index2]) + # Ring+SIMPLE: no extra cap beyond busBw + + if busBw <= 0: + return -1.0 + + # nsteps for the collective + if coll == NCCL_COLL.ALL_REDUCE: + nsteps = 2 * (nRanks - 1) + elif coll in (NCCL_COLL.REDUCE_SCATTER, NCCL_COLL.ALL_GATHER): + nsteps = nRanks - 1 + elif coll == NCCL_COLL.ALL_TO_ALL: + nsteps = 2 * (nRanks - 1) + elif coll == NCCL_COLL.P2P: + nsteps = 1 + else: + return -1.0 + + # Bus BW to algorithm BW conversion + # Tree allreduce uses 0.5 ratio; Ring uses nRanks/nsteps + if algo == NCCL_ALGO.TREE and coll == NCCL_COLL.ALL_REDUCE: + bandwidth = busBw * 0.5 + elif algo == NCCL_ALGO.RING: + bandwidth = busBw * (1.0 * nRanks / nsteps) + else: + bandwidth = busBw * 0.5 + + if bandwidth <= 0: + return -1.0 + + # --- Latency computation (mirrors ncclTopoTuneModel) --- + intraHw = NCCL_HW.PCI if interconnect == InterconnectType.PCIE else NCCL_HW.NVLINK + lat = baseLat[algo][proto] + intraLat = hwLat[intraHw][algo][proto] + interLat = hwLat[NCCL_HW.NET][algo][proto] + + netOverhead = 1.0 if nNodes > 1 else 0.0 + if proto == NCCL_PROTO.SIMPLE and nNodes > 1: + netOverhead *= 3.0 + intraLat = max(intraLat, netOverhead) + + if algo == NCCL_ALGO.RING: + nInterSteps = ( + 0 + if nNodes == 1 + else (2 * (nNodes - 1) if coll == NCCL_COLL.ALL_REDUCE else nNodes - 1) + ) + lat += (nsteps - nInterSteps) * intraLat + nInterSteps * interLat + elif algo == NCCL_ALGO.TREE: + if coll == NCCL_COLL.ALL_REDUCE: + lat += 2 * ( + (nRanks // max(nNodes, 1) - 1) * intraLat + _log2i(nNodes) * interLat + ) + + # --- ncclTopoGetAlgoTime: time = lat + nBytes / (1000 * bandwidth) --- + # Tree correction factor for medium messages + if algo == NCCL_ALGO.TREE and coll == NCCL_COLL.ALL_REDUCE: + logSize = _log2i(nBytes >> 6) if nBytes >= 64 else 0 + if 0 <= logSize < 24: + bandwidth *= treeCorrectionFactor[proto][logSize] + + time_us = lat + nBytes / (1000.0 * bandwidth) + return time_us + + +def _nccl_best_algo_time( + nBytes: int, + group_size: int, + coll: NCCL_COLL, +) -> tuple[float, int, int]: + """Find the best (algo, proto) for a given collective and return (time_us, algo, proto). + + Iterates all supported (algo, proto) combinations and picks the one with + minimum estimated time, mirroring NCCL's algorithm selection. + """ + best_time = float("inf") + best_algo = NCCL_ALGO.RING + best_proto = NCCL_PROTO.LL + + for algo in (NCCL_ALGO.TREE, NCCL_ALGO.RING): + # Tree only supports allreduce in our model + if algo == NCCL_ALGO.TREE and coll != NCCL_COLL.ALL_REDUCE: + continue + for proto in (NCCL_PROTO.LL, NCCL_PROTO.LL128, NCCL_PROTO.SIMPLE): + t = _nccl_algo_time(nBytes, group_size, coll, algo, proto) + if 0 <= t < best_time: + best_time = t + best_algo = algo + best_proto = proto + + return best_time, best_algo, best_proto + + +def estimate_nccl_collective_runtime_impl( + tensor_storage_size_bytes: int, group_size: int, coll: NCCL_COLL +) -> float: + """Returns estimated NCCL collective runtime in milliseconds (ms). + + Uses a multi-algorithm, multi-protocol model aligned with NCCL's + ncclTopoTuneModel and ncclTopoGetAlgoTime (tuning.cc). Evaluates + Ring and Tree algorithms across LL, LL128, and SIMPLE protocols, + selecting the (algo, proto) pair that minimizes estimated time. + """ + if group_size <= 1: + return 0 + + if coll == NCCL_COLL.UNSUPPORTED: + return 0 + + time_us, _, _ = _nccl_best_algo_time(tensor_storage_size_bytes, group_size, coll) + if time_us < 0 or time_us == float("inf"): + return 0 + return time_us / 1000.0 + + +def compute_min_saturation_bytes( + group_size: int, + coll: NCCL_COLL, + target_efficiency: float = 0.9, +) -> int: + """Compute min message size for target BW efficiency using empirical profiles. + + Uses per-interconnect profiles calibrated to real NCCL behavior (algorithm, + protocol, channel selection) rather than the analytical model. + """ + _SUPPORTED = (NCCL_COLL.ALL_GATHER, NCCL_COLL.REDUCE_SCATTER, NCCL_COLL.ALL_REDUCE) + if coll not in _SUPPORTED: + raise AssertionError( + f"Unsupported collective {coll}, expected one of {_SUPPORTED}" + ) + + if group_size <= 1: + return 0 + + profile = INTERCONNECT_PROFILES[detect_interconnect(group_size)] + + if coll in (NCCL_COLL.ALL_GATHER, NCCL_COLL.REDUCE_SCATTER): + nsteps = group_size - 1 + elif coll == NCCL_COLL.ALL_REDUCE: + nsteps = 2 * (group_size - 1) + else: + return 0 + + total_latency_us = profile.base_latency_us + nsteps * profile.latency_per_hop_us + latency_s = total_latency_us * 1e-6 + bw_bytes_per_s = profile.bus_bw_GBps * 1e9 + eff_ratio = target_efficiency / (1.0 - target_efficiency) + min_bytes = int(eff_ratio * latency_s * bw_bytes_per_s) + return max(min_bytes, profile.min_saturation_bytes) + + +################################################################################################################ +# The above code and constants are adapted from https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc # +################################################################################################################ + + +def estimate_nccl_collective_runtime(node: ir.IRNode) -> float: + """Returns estimated NCCL collective runtime in milliseconds (ms). + + Uses the multi-algorithm, multi-protocol analytical model aligned with + NCCL's tuning.cc to select the best (algo, proto) pair for the given + collective size and topology. + """ + tensor_storage_size_bytes = get_collective_input_size_bytes(node) + group_size = get_collective_group_size(node) + coll = get_collective_type(node) + return estimate_nccl_collective_runtime_impl( + tensor_storage_size_bytes, group_size, coll + ) + + +def estimate_fx_collective_size(fx_node: torch.fx.Node) -> int: + """Estimate the size of a collective operation in bytes, including inputs and outputs.""" + input_bytes = None + + args, kwargs = fx_node.args, fx_node.kwargs + kwargs = dict(kwargs) + + # don't double count pre-allocated buffer passed in + kwargs.pop("out", None) + + def tensor_bytes(t: torch.Tensor) -> int: + return get_fx_node_size_numel(t.size()) * get_dtype_size(t.dtype) + + def add_inp_bytes(inp: torch.fx.Node): + inp_val = inp.meta.get("val", None) + if not isinstance(inp_val, torch.Tensor): + return + + nonlocal input_bytes + if input_bytes is None: + input_bytes = 0 + input_bytes += tensor_bytes(inp_val) + + pytree.tree_map_only( + torch.fx.Node, + add_inp_bytes, + (args, kwargs), + ) + + output_val = fx_node.meta.get("val", None) + + if input_bytes is None or output_val is None: + return 0 + + # Coalesced collectives return a list of tensors + if isinstance(output_val, (list, tuple)): + output_bytes = sum( + tensor_bytes(t) for t in output_val if isinstance(t, torch.Tensor) + ) + elif isinstance(output_val, torch.Tensor): + output_bytes = tensor_bytes(output_val) + else: + return 0 + + return input_bytes + output_bytes + + +def estimate_fx_collective_memory_footprint(fx_node: torch.fx.Node) -> int: + """Estimate the memory footprint of a collective operation in bytes. + + This returns the total bytes that need to be live concurrently in memory. + For all_reduce, we divide by 2 since it can be done in-place. + """ + from torch._inductor.fx_passes.bucketing import ( + is_all_reduce_tensor as is_all_reduce, + ) + + size = estimate_fx_collective_size(fx_node) + return size if not is_all_reduce(fx_node) else size // 2 + + +def estimate_nccl_collective_runtime_from_fx_node( + fx_node: torch.fx.Node, + override_size: int | None = None, + use_nccl_estimator: bool = True, +) -> float: + """Returns estimated NCCL collective runtime in milliseconds (ms). + + Tries the NCCL simulator first (if available and enabled), falls back + to the multi-algo/proto analytical model from tuning.cc. + """ + from torch.distributed.distributed_c10d import _get_group_size_by_name + + if fx_node.target is torch.ops._c10d_functional.all_to_all_single.default: + # TODO(ivankobzarev): Temporarily disabled - NCCL estimator returns internal error. + # for all_to_all during inductor compilation. Falls back to heuristic estimation. + use_nccl_estimator = False + + if override_size is None: + tensor_storage_size_bytes = estimate_fx_collective_size(fx_node) + else: + tensor_storage_size_bytes = override_size + + if isinstance(fx_node.target, str): + raise AssertionError(f"fx_node.target must not be a str, got {fx_node.target}") + opt_args_kwargs = normalize_function( + fx_node.target, + args=fx_node.args, + kwargs=fx_node.kwargs, + normalize_to_only_use_kwargs=True, + ) + if opt_args_kwargs is None: + raise AssertionError("normalize_function returned None") + args, kwargs = opt_args_kwargs + + from torch._inductor.fx_passes.bucketing import _resolve_group_name + + group_name = _resolve_group_name(kwargs["group_name"]) + group_size = _get_group_size_by_name(group_name) + if not isinstance(fx_node.target, torch._ops.OpOverload): + raise AssertionError( + f"expected fx_node.target to be an OpOverload, got {type(fx_node.target)}" + ) + coll = get_collective_type_from_kernel_name(fx_node.target.name()) + + def _nccl_estimate() -> float | None: + # TODO: Refactor with estimate_nccl_collective_runtime_nccl_estimator + from torch.distributed.distributed_c10d import _resolve_process_group, Backend + + pg = _resolve_process_group(group_name) + if torch.distributed.distributed_c10d.get_backend(pg) == Backend.FAKE: + # nccl estimator requires real process group + return None + + device = torch.device("cuda") + try: + backend = pg._get_backend(device) + except RuntimeError: + return None + if not backend.supports_time_estimate: + return None + + flat_args, flat_args_pytree_spec = pytree.tree_flatten((args, kwargs)) + + def _tensor(size, dtype, device) -> torch.Tensor: # type: ignore[no-untyped-def] + return torch.empty( + size if override_size is None else [override_size], + dtype=dtype, + device=device, + ) + + def to_real_tensor(e: Any) -> Any: + if isinstance(e, torch.fx.Node): + return to_real_tensor(e.meta["val"]) + if isinstance(e, torch.Tensor): + return _tensor([get_fx_node_size_numel(e.size())], e.dtype, e.device) + return e + + flat_args = [to_real_tensor(a) for a in flat_args] + real_args, real_kwargs = pytree.tree_unflatten(flat_args, flat_args_pytree_spec) + + fn = fx_node.target + if not isinstance(fn, torch._ops.OpOverload): + raise AssertionError( + f"expected fx_node.target to be an OpOverload, got {type(fn)}" + ) + with torch.distributed._time_estimator( + group=pg, device=device + ) as time_estimator: + w = fn(*real_args, **real_kwargs) + # Coalesced collectives return a list of tensors + if isinstance(w, (list, tuple)): + for t in w: + torch.ops._c10d_functional.wait_tensor.default(t) + else: + torch.ops._c10d_functional.wait_tensor.default(w) + est_time_us = time_estimator.estimated_time + if est_time_us is None: + raise AssertionError("NCCL time estimator did not produce a result") + # -1000 constant is NCCL return in case of error during estimations. + # Observed it for all_to_all estimations. + if est_time_us < 0: + return None + est_time_ms = est_time_us / 1e3 + return est_time_ms + + if use_nccl_estimator: + est_time_ms = _nccl_estimate() + if est_time_ms is not None: + return est_time_ms + + return estimate_nccl_collective_runtime_impl( + tensor_storage_size_bytes, group_size, coll + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/comm_lowering.py b/.venv/lib/python3.12/site-packages/torch/_inductor/comm_lowering.py new file mode 100644 index 0000000000000000000000000000000000000000..c6e5f09843faa38665460babdaa3fbc281c76147 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/comm_lowering.py @@ -0,0 +1,967 @@ +# mypy: allow-untyped-defs +import logging + +import torch +import torch.utils._pytree as pytree +from torch._inductor.utils import is_symbolic +from torch.utils._ordered_set import OrderedSet + +from . import config, ir +from .virtualized import V + + +log = logging.getLogger(__name__) + + +# NOTE [lowering-time collective optimization] +# +# In collective communication libraries such as NCCL, every rank maintains +# communication buffers that are remotely accessible by some peers. Depending +# on the underlying transport, remote accessibility may be established via +# mechanisms such as ib_reg_mr, CUDA P2P, or CUDA multicast. Typically, these +# buffers are private to the communication library by default, and +# communication ops copy user data in and out of these buffers. +# +# To prevent these copies, an optimization commonly known as "user buffer +# registration" can be employed. This allows direct establishment of remote +# accessibility on user buffers, eliminating the need for copying. However, +# this optimization introduces stringent usage requirements, which are +# typically hard to satisfy without being intrusive to the user code: +# +# - Establishing remote accessibility is expensive and often done ahead of +# time. In such implementations, all ranks must agree on the set of allocations +# used for every collective op. Failing to meet this requirement can +# lead to runtime errors or even silent correctness issues. +# - Even if the collective communication library supports gracefully falling +# back to "unregistered" implementations, the fallback mechanism would nullify +# the optimization. +# - Some communication mechanisms impose stricter requirements than others. For +# example, CUDA's multicast + multi-mem instructions require all ranks to agree +# not only on the allocations used for every collective but also on the offsets +# within these allocations. +# +# To support all different mechanisms with optimal results, we aim to satisfy +# the strictest requirement for this family of optimizations - we ensure that +# every collective op invocation is guaranteed to operate on the same +# allocation, at the same offset, in every iteration. +# +# For eligible collective ops, we identify communication buffers at lowering +# time and optionally choose to lower the op to a different kernel +# (communication libraries like NCCL handle both registered and non-registered +# buffers transparently within the same op, though some may require different +# ops for different cases). Later, the codegen will perform "persistent +# allocation" to satisfy the aforementioned constraints, and optionally, +# perform buffer planning to optimize overall memory usage. +def can_realize_as_comm_buffer( + x: ir.TensorBox, comm_buffer_type: ir.CommBufferType +) -> bool: + """ + Check if an input can be realized as a comm buffer of the specified + `comm_buffer_type`. + """ + data = _get_data(x) + + if isinstance(data, ir.Loops): + return True + + # We cannot realize buffers as comm buffers if we don't control their + # allocation. + if isinstance(data, ir.Buffer) and not data.should_allocate(): + return False + + layout = data.get_output_spec() + if isinstance(layout, ir.CommBufferLayout): + return True + + if isinstance(layout, ir.FixedLayout): + return True + + if isinstance(layout, ir.FlexibleLayout) and not is_symbolic(data.get_numel()): + return True + + return False + + +def realize_as_comm_buffer( + x: ir.TensorBox, + comm_buffer_type: ir.CommBufferType, + group_name: "torch.distributed.distributed_c10d.GroupName", +) -> None: + """ + Realize an input as a comm buffer of the specified `comm_buffer_type`. + + Specifically, this realizes the underlying buffer if it's still unrealized + and changes the layout of the buffer to `ir.CommBufferLayout`. + """ + x.realize() + buffer = _get_data(x) + if not isinstance(buffer, ir.Buffer): + raise AssertionError(f"expected an `ir.Buffer`, got {type(buffer)}") + + layout = buffer.get_output_spec() + if isinstance(layout, ir.CommBufferLayout): + return + + # The buffer may have already been frozen to FixedLayout if it was used + # by another operation before the comm operation. + if not isinstance(layout, (ir.FlexibleLayout, ir.FixedLayout)): + raise AssertionError( + "A buffer can only be realized as a comm buffer if it " + f"has `FlexibleLayout` or `FixedLayout` (got {layout})." + ) + + if is_symbolic(buffer.get_numel()): + raise AssertionError( + "A buffer with symbolic shape cannot be converted to " + f"a comm buffer (got {layout})." + ) + + buffer.layout = ir.CommBufferLayout( + layout=layout, + comm_buffer_type=comm_buffer_type, + group_name=group_name, + ) + + +def _get_data(x: ir.TensorBox) -> ir.IRNode: + if isinstance(x.data, ir.BaseView): + # TensorBox -> *View -> StorageBox -> IRNode + node = x.data.unwrap_view() + if not isinstance(node, (ir.BaseView, ir.MutableBox)): + raise AssertionError( + f"expected an `ir.BaseView` or `ir.MutableBox`, got {type(node)}" + ) + return node.data + elif isinstance(x.data, ir.StorageBox): + # TensorBox -> StorageBox -> IRNode + return x.data.data + else: + raise AssertionError( + "Expect the data attr of a `TensorBox` to be either " + f"an `ir.BaseView` or `ir.StorageBox` (got {x.data})." + ) + + +_bufs_to_skip_wait = OrderedSet[tuple[int, str]]() + + +def mark_as_skip_wait(x: ir.IRNode) -> None: + """ + If a non-blocking collective is lowered as a blocking collective, the wait + node in the original graph becomes useless and we can skip the lowering it. + """ + _bufs_to_skip_wait.add((id(V.graph), x.get_name())) + + +def should_skip_wait(x: ir.IRNode) -> bool: + return (id(V.graph), x.get_name()) in _bufs_to_skip_wait + + +def _should_lower_as_one_shot_all_reduce( + inp: ir.TensorBox, + reduce_op: str, + group_name: "torch.distributed.distributed_c10d.GroupName", +): + from torch.distributed._symmetric_memory import is_symm_mem_enabled_for_group + + inp_size = inp.get_numel() * inp.get_dtype().itemsize + return ( + config._collective.auto_select + and is_symm_mem_enabled_for_group(group_name) + and can_realize_as_comm_buffer(inp, ir.CommBufferType.SYMM_MEM) + and reduce_op == "sum" + and inp_size <= config._collective.one_shot_all_reduce_threshold_bytes + ) + + +def _one_shot_all_reduce(inp: ir.TensorBox, reduce_op, group_name): + realize_as_comm_buffer(inp, ir.CommBufferType.SYMM_MEM, group_name) + return pytree.tree_map( + ir.TensorBox.create, + ir.FallbackKernel.create( + torch.ops.symm_mem.one_shot_all_reduce.default, + inp, + reduce_op, + group_name, + ), + ) + + +def _create_out_of_place(kernel, inputs, *args) -> ir.IRNode: + node = ir._CollectiveKernel.create_out_of_place(kernel, inputs, *args) + if not isinstance(node, ir.IRNode): + raise AssertionError(f"expected an `ir.IRNode`, got {type(node)}") + return ir.TensorBox.create(node) + + +def register_comm_lowerings(): + """ + Register lowerings for the comm subsystem. + """ + try: + _ = torch.ops._c10d_functional.all_reduce + except AttributeError: + log.info( + "Inductor support for distributed collectives depends on building " + "torch.distributed" + ) + return + + from .lowering import ( + add_layout_constraint, + clone, + constrain_to_fx_strides, + copy_, + register_lowering, + ) + + def register_comm_lowering(fn): + add_layout_constraint(fn, constrain_to_fx_strides) + return register_lowering(fn) + + c10d = torch.ops._c10d_functional + + @register_comm_lowering(c10d.all_reduce) # type: ignore[misc] + def _all_reduce( + inp: ir.TensorBox, + reduce_op: str, + group_name: "torch.distributed.distributed_c10d.GroupName", + ) -> ir.TensorBox: + if _should_lower_as_one_shot_all_reduce(inp, reduce_op, group_name): + return _one_shot_all_reduce(inp, reduce_op, group_name) + + # Lower as c10d.all_reduce_ + inp = clone(inp) + if config.reorder_for_compute_comm_overlap: + # The horizontal fusion of this clone often severely delays the + # scheduling of the all_reduce_ node. Horizontally fusing this + # clone can almost never out-perform scheduling the all_reduce_ + # earlier. Also in most cases, this clone is eliminated via + # in-place reuse. Therefore, we tell the scheduler to not fuse it. + inp.realize() + V.graph.no_fuse_buffer_names.add(inp.get_name()) + # pyrefly: ignore [bad-assignment] + inp = ir.ExternKernel.require_contiguous(inp) + # Because we are lowering as inplace c10d.all_reduce_, we should generate + # _AllReduce_Kernel instead of _AllReduceKernel. + ir._AllReduce_Kernel.create_inplace( + c10d.all_reduce_.default, + inp, # type: ignore[arg-type] + reduce_op, + group_name, # type: ignore[arg-type] + ) + return inp # type: ignore[return-value] + + @register_comm_lowering(c10d.all_reduce_) # type: ignore[misc] + def _all_reduce_( + inp: ir.TensorBox, + reduce_op: str, + group_name: "torch.distributed.distributed_c10d.GroupName", + ) -> ir.TensorBox: + if _should_lower_as_one_shot_all_reduce(inp, reduce_op, group_name): + ret = copy_( + inp, + _one_shot_all_reduce(inp, reduce_op, group_name), + ) + mark_as_skip_wait(ret) + return inp + + # Lower as c10d.all_reduce_ + # pyrefly: ignore [bad-assignment] + inp = ir.ExternKernel.require_contiguous(inp) + ir._AllReduce_Kernel.create_inplace( + c10d.all_reduce_.default, + inp, # type: ignore[arg-type] + reduce_op, + group_name, # type: ignore[arg-type] + ) + return inp # type: ignore[return-value] + + @register_comm_lowering(c10d.all_reduce_coalesced) + def _all_reduce_coalesced(inputs, reduce_op, group_name): + inputs = [clone(inp) for inp in inputs] + ir._CollectiveKernel.create_inplace( + c10d.all_reduce_coalesced_.default, + inputs, + reduce_op, + group_name, + ) + return inputs + + @register_comm_lowering(c10d.all_reduce_coalesced_) + def _all_reduce_coalesced_(inputs, reduce_op, group_name): + ir._CollectiveKernel.create_inplace( + c10d.all_reduce_coalesced_.default, + inputs, + reduce_op, + group_name, + ) + return inputs + + @register_comm_lowering(c10d.all_gather_into_tensor) + def _all_gather_into_tensor(inp, group_size, group_name): + return _create_out_of_place( + c10d.all_gather_into_tensor.default, + inp, + group_size, + group_name, + ) + + @register_comm_lowering(c10d.all_gather_into_tensor_coalesced) + def _all_gather_into_tensor_coalesced(inputs, group_size, group_name): + return pytree.tree_map( + ir.TensorBox.create, + ir._CollectiveKernel.create_out_of_place( + c10d.all_gather_into_tensor_coalesced.default, + inputs, + group_size, + group_name, + ), + ) + + @register_comm_lowering(c10d.all_gather_into_tensor_out) + def _all_gather_into_tensor_out(inp, group_size, group_name, *, out): + ir._CollectiveKernel.create_inplace( + c10d.all_gather_into_tensor_out.default, + inp, + group_size, + group_name, + out=out, + ) + return out + + @register_comm_lowering(c10d.reduce_scatter_tensor) + def _reduce_scatter_tensor(inp, reduce_op, group_size, group_name): + return _create_out_of_place( + c10d.reduce_scatter_tensor.default, + inp, + reduce_op, + group_size, + group_name, + ) + + @register_comm_lowering(c10d.reduce_scatter_tensor_out) + def _reduce_scatter_tensor_out(inp, reduce_op, group_size, group_name, *, out): + ir._CollectiveKernel.create_inplace( + c10d.reduce_scatter_tensor_out.default, + inp, + reduce_op, + group_size, + group_name, + out=out, + ) + return out + + @register_comm_lowering(c10d.reduce_scatter_tensor_coalesced) + def _reduce_scatter_tensor_coalesced(inputs, reduce_op, group_size, group_name): + return pytree.tree_map( + ir.TensorBox.create, + ir._CollectiveKernel.create_out_of_place( + c10d.reduce_scatter_tensor_coalesced.default, + inputs, + reduce_op, + group_size, + group_name, + ), + ) + + @register_comm_lowering(c10d.all_to_all_single) + def _all_to_all_single(inp, output_split_sizes, input_split_sizes, group_name): + return _create_out_of_place( + c10d.all_to_all_single.default, + inp, + output_split_sizes, + input_split_sizes, + group_name, + ) + + @register_comm_lowering(c10d.broadcast) + def _broadcast(inp, src, group_name): + inp = clone(inp) + ir._CollectiveKernel.create_inplace( + c10d.broadcast_.default, inp, src, group_name + ) + return inp + + @register_comm_lowering(c10d.broadcast_) + def _broadcast_(inp, src, group_name): + ir._CollectiveKernel.create_inplace( + c10d.broadcast_.default, inp, src, group_name + ) + return inp + + @register_comm_lowering(torch.ops._dtensor.shard_dim_alltoall) + def _shard_dim_alltoall(inp, gather_dim, shard_dim, group_name): + return _create_out_of_place( + torch.ops._dtensor.shard_dim_alltoall.default, + inp, + gather_dim, + shard_dim, + group_name, + ) + + @register_comm_lowering(c10d.wait_tensor) + def _wait_tensor(inp): + if should_skip_wait(inp): + return inp + + ir._WaitKernel.create_wait(c10d.wait_tensor.default, inp) + return inp + + @register_comm_lowering(c10d.isend) # type: ignore[misc] + def _isend(inp, dst, tag, group_name): + inp = ir.ExternKernel.require_contiguous(inp) + return _create_out_of_place(c10d.isend.default, inp, dst, tag, group_name) + + @register_comm_lowering(c10d.irecv) # type: ignore[misc] + def _irecv(inp, src, tag, group_name): + inp = ir.ExternKernel.require_contiguous(inp) + ir._CollectiveKernel.create_inplace( + c10d.irecv.default, inp, src, tag, group_name + ) + return inp + + @register_comm_lowering(c10d.batch_p2p_ops) # type: ignore[misc] + def _batch_p2p_ops(op_list, peer_list, tag_list, tensors, group_name): + tensors = [ir.ExternKernel.require_contiguous(t) for t in tensors] + kernel = c10d.batch_p2p_ops.default + with V.graph.fake_mode: + result = ir._CollectiveKernel.process_kernel( + kernel, + op_list, + peer_list, + tag_list, + tensors, + group_name, + ) + example_output = result.example_output + tensor_args = result.tensor_args + non_tensor_args = result.non_tensor_args + unflatten_args = result.unflatten_args + if result.unbacked_bindings: + raise AssertionError(f"{kernel} {result.unbacked_bindings}") + for op, tensor_arg in zip(op_list, tensor_args): + tensor_arg.realize() + if op == "irecv": + V.graph.mark_buffer_mutated(tensor_arg.get_name()) + + device = tensor_args[0].get_device_or_error() + packed = ir._CollectiveKernel( + ir.MultiOutputLayout(device=device), + kernel, + tensor_args, + non_tensor_args, + unflatten_args, + ) + + results = [] + for i, (op, t, ex_out) in enumerate(zip(op_list, tensors, example_output)): + if op == "irecv": + packed.mutation_outputs.append( + ir.MutationOutput(ir.NoneLayout(device=device), t, packed) + ) + packed.alias_names.append(t.get_name()) + results.append(t) + else: + # isend: 0-element placeholder output connected to the collective + placeholder = ir.MultiOutput( + ir._CollectiveKernel.tensor_to_layout(ex_out), + packed, + [(list, i)], + ) + results.append(ir.TensorBox.create(placeholder)) + return results + + +def register_symm_mem_lowerings(): + """ + Register lowerings for symmetric memory (symm_mem) operations. + """ + try: + symm_mem = torch.ops.symm_mem + # Check for an actual operation, not just the namespace. + # torch.ops.symm_mem is a lazy namespace that always exists, + # but the operations may not exist on non-CUDA platforms or + # when USE_DISTRIBUTED is disabled. + _ = symm_mem.one_shot_all_reduce + except AttributeError: + log.info("symm_mem ops not available, skipping symm_mem lowerings") + return + + from torch._library._out_variant import register_out_variant + + # Register manual out variant mappings for symm_mem ops. + register_out_variant( + symm_mem.one_shot_all_reduce.default, + symm_mem.one_shot_all_reduce_out.default, + ) + register_out_variant( + symm_mem.one_shot_all_reduce_copy.default, + symm_mem.one_shot_all_reduce_copy_out.default, + ) + + from .lowering import register_lowering + + def _copy_input_to_comm_buffer( + inp: ir.TensorBox, + comm_buffer_type: ir.CommBufferType, + group_name: "torch.distributed.distributed_c10d.GroupName", + ) -> ir.TensorBox: + """ + Fallback: insert a Pointwise identity copy allocated in P2P via + CommBufferLayout. Used when we don't control the input's allocation. + """ + inp.realize() + copy = ir.Pointwise.create( + device=inp.get_device(), + dtype=inp.get_dtype(), + inner_fn=inp.make_loader(), + ranges=inp.get_size(), + ) + realize_as_comm_buffer(copy, comm_buffer_type, group_name) + return copy + + def _maybe_realize_symm_mem( + inp: ir.TensorBox, + group_name: str, # type: ignore[arg-type] + ) -> ir.TensorBox: + """ + Ensure inp is in P2P memory for a symm_mem collective. + + If inductor controls the buffer's allocation (ComputedBuffer, + or any buffer with FlexibleLayout/FixedLayout), switch its + layout to CommBufferLayout in-place, zero-copy. + + If inductor does not control allocation (e.g. InputBuffer), + insert a Pointwise identity copy into a new CommBufferLayout buffer. + This adds an extra Triton kernel. Returns the possibly new TensorBox. + + TODO(tianrengao): eliminate the extra kernel for static-shape + InputBuffers by pre-allocating P2P memory in the wrapper and DMA .copy_() + """ + if can_realize_as_comm_buffer(inp, ir.CommBufferType.SYMM_MEM): + realize_as_comm_buffer(inp, ir.CommBufferType.SYMM_MEM, group_name) # type: ignore[arg-type] + return inp + else: + return _copy_input_to_comm_buffer( + inp, + ir.CommBufferType.SYMM_MEM, + group_name, # type: ignore[arg-type] + ) + + def _create_low_contention_ag_out( + kernel: torch._ops.OpOverload, + inp: ir.TensorBox, + group_name: "torch.distributed.distributed_c10d.GroupName", + ) -> ir.TensorBox: + from torch.distributed import distributed_c10d as c10d + + inp.realize() + group_size = c10d._get_group_size_by_name(group_name) + out_size = [inp.get_size()[0] * group_size, *inp.get_size()[1:]] + layout = ir.CommBufferLayout( + ir.FixedLayout( + device=inp.get_device_or_error(), + dtype=inp.get_dtype(), + size=out_size, + ), + ir.CommBufferType.SYMM_MEM, + group_name, + ) + return ir.TensorBox.create( + ir.ExternKernelOut( + layout=layout, + inputs=[inp], + constant_args=(group_name,), + op_overload=kernel, + ) + ) + + @register_lowering(symm_mem.one_shot_all_reduce) + def _symm_mem_one_shot_all_reduce( + inp: ir.TensorBox, + reduce_op: str, + group_name: str, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + return pytree.tree_map( + ir.TensorBox.create, + ir.FallbackKernel.create( + symm_mem.one_shot_all_reduce.default, + inp, + reduce_op, + group_name, + ), + ) + + @register_lowering(symm_mem.one_shot_all_reduce_out) + def _symm_mem_one_shot_all_reduce_out( + inp: ir.TensorBox, + reduce_op: str, + group_name: str, + out: ir.TensorBox, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + return pytree.tree_map( + ir.TensorBox.create, + ir.FallbackKernel.create( + symm_mem.one_shot_all_reduce_out.default, + inp, + reduce_op, + group_name, + out, + ), + ) + + @register_lowering(symm_mem.one_shot_all_reduce_copy) + def _symm_mem_one_shot_all_reduce_copy( + symm_buffer: ir.TensorBox, + local_input: ir.TensorBox, + reduce_op: str, + group_name: str, + ): + symm_buffer = _maybe_realize_symm_mem(symm_buffer, group_name) + return pytree.tree_map( + ir.TensorBox.create, + ir.FallbackKernel.create( + symm_mem.one_shot_all_reduce_copy.default, + symm_buffer, + local_input, + reduce_op, + group_name, + ), + ) + + @register_lowering(symm_mem.one_shot_all_reduce_copy_out) + def _symm_mem_one_shot_all_reduce_copy_out( + symm_buffer: ir.TensorBox, + local_input: ir.TensorBox, + reduce_op: str, + group_name: str, + out: ir.TensorBox, + ): + symm_buffer = _maybe_realize_symm_mem(symm_buffer, group_name) + return pytree.tree_map( + ir.TensorBox.create, + ir.FallbackKernel.create( + symm_mem.one_shot_all_reduce_copy_out.default, + symm_buffer, + local_input, + reduce_op, + group_name, + out, + ), + ) + + @register_lowering(symm_mem.two_shot_all_reduce_) + def _symm_mem_two_shot_all_reduce_( + inp: ir.TensorBox, + reduce_op: str, + group_name: str, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + ir.FallbackKernel.create( + symm_mem.two_shot_all_reduce_.default, + inp, + reduce_op, + group_name, + ) + return inp + + @register_lowering(symm_mem.two_shot_all_reduce_out) + def _symm_mem_two_shot_all_reduce_out( + inp: ir.TensorBox, + reduce_op: str, + group_name: str, + output: ir.TensorBox, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + return pytree.tree_map( + ir.TensorBox.create, + ir.FallbackKernel.create( + symm_mem.two_shot_all_reduce_out.default, + inp, + reduce_op, + group_name, + output, + ), + ) + + @register_lowering(symm_mem.multimem_all_reduce_) + def _symm_mem_multimem_all_reduce_( + inp: ir.TensorBox, + reduce_op: str, + group_name: str, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + ir.FallbackKernel.create( + symm_mem.multimem_all_reduce_.default, + inp, + reduce_op, + group_name, + ) + return inp + + @register_lowering(symm_mem.multimem_one_shot_all_reduce) + def _symm_mem_multimem_one_shot_all_reduce( + inp: ir.TensorBox, + reduce_op: str, + group_name: str, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + return pytree.tree_map( + ir.TensorBox.create, + ir.FallbackKernel.create( + symm_mem.multimem_one_shot_all_reduce.default, + inp, + reduce_op, + group_name, + ), + ) + + @register_lowering(symm_mem.multimem_one_shot_all_reduce_out) + def _symm_mem_multimem_one_shot_all_reduce_out( + inp: ir.TensorBox, + reduce_op: str, + group_name: str, + out: ir.TensorBox, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + return pytree.tree_map( + ir.TensorBox.create, + ir.FallbackKernel.create( + symm_mem.multimem_one_shot_all_reduce_out.default, + inp, + reduce_op, + group_name, + out, + ), + ) + + @register_lowering(symm_mem.multimem_one_shot_reduce_out) + def _symm_mem_multimem_one_shot_reduce_out( + inp: ir.TensorBox, + reduce_op: str, + root: int, + group_name: str, + out: ir.TensorBox, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + return pytree.tree_map( + ir.TensorBox.create, + ir.FallbackKernel.create( + symm_mem.multimem_one_shot_reduce_out.default, + inp, + reduce_op, + root, + group_name, + out, + ), + ) + + @register_lowering(symm_mem.multimem_all_gather_out) + def _symm_mem_multimem_all_gather_out( + inp: ir.TensorBox, + group_name: str, + out: ir.TensorBox, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + return pytree.tree_map( + ir.TensorBox.create, + ir.FallbackKernel.create( + symm_mem.multimem_all_gather_out.default, + inp, + group_name, + out, + ), + ) + + @register_lowering(symm_mem.reduce_scatter_out) + def _symm_mem_reduce_scatter_out( + inp: ir.TensorBox, + group_name: str, + split_last_dim: bool, + output: ir.TensorBox, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + return pytree.tree_map( + ir.TensorBox.create, + ir.FallbackKernel.create( + symm_mem.reduce_scatter_out.default, + inp, + group_name, + split_last_dim, + output, + ), + ) + + @register_lowering(symm_mem.all_to_all_vdev) + def _symm_mem_all_to_all_vdev( + inp: ir.TensorBox, + out: ir.TensorBox, + in_splits: ir.TensorBox, + out_splits_offsets: ir.TensorBox, + group_name: str, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + out = _maybe_realize_symm_mem(out, group_name) + ir.FallbackKernel.create( + symm_mem.all_to_all_vdev.default, + inp, + out, + in_splits, + out_splits_offsets, + group_name, + ) + return None + + @register_lowering(symm_mem.all_to_all_vdev_2d) + def _symm_mem_all_to_all_vdev_2d( + inp: ir.TensorBox, + out: ir.TensorBox, + in_splits: ir.TensorBox, + out_splits_offsets: ir.TensorBox, + group_name: str, + major_align=None, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + out = _maybe_realize_symm_mem(out, group_name) + ir.FallbackKernel.create( + symm_mem.all_to_all_vdev_2d.default, + inp, + out, + in_splits, + out_splits_offsets, + group_name, + major_align, + ) + return None + + @register_lowering(symm_mem.all_to_all_vdev_2d_offset) + def _symm_mem_all_to_all_vdev_2d_offset( + inp: ir.TensorBox, + out: ir.TensorBox, + in_splits_offsets: ir.TensorBox, + out_splits_offsets: ir.TensorBox, + group_name: str, + ): + inp = _maybe_realize_symm_mem(inp, group_name) + out = _maybe_realize_symm_mem(out, group_name) + ir.FallbackKernel.create( + symm_mem.all_to_all_vdev_2d_offset.default, + inp, + out, + in_splits_offsets, + out_splits_offsets, + group_name, + ) + return None + + @register_lowering(symm_mem.tile_reduce) + def _symm_mem_tile_reduce( + in_tile: ir.TensorBox, + out_tile: ir.TensorBox, + root: int, + group_name: str, + reduce_op: str = "sum", + ): + in_tile = _maybe_realize_symm_mem(in_tile, group_name) + out_tile = _maybe_realize_symm_mem(out_tile, group_name) + ir.FallbackKernel.create( + symm_mem.tile_reduce.default, + in_tile, + out_tile, + root, + group_name, + reduce_op, + ) + return None + + @register_lowering(symm_mem.multi_root_tile_reduce) + def _symm_mem_multi_root_tile_reduce( + in_tiles, # list of TensorBox + out_tile: ir.TensorBox, + roots, # list of int + group_name: str, + reduce_op: str = "sum", + ): + for i, in_tile in enumerate(in_tiles): + in_tiles[i] = _maybe_realize_symm_mem(in_tile, group_name) + out_tile = _maybe_realize_symm_mem(out_tile, group_name) + ir.FallbackKernel.create( + symm_mem.multi_root_tile_reduce.default, + in_tiles, + out_tile, + roots, + group_name, + reduce_op, + ) + return None + + @register_lowering(symm_mem._low_contention_all_gather) + def _symm_mem_low_contention_all_gather( + inp: ir.TensorBox, + group_name: str, + ): + # Use _CollectiveKernel so that _WaitKernel.get_volatile_reads() + # can track the input's lifetime through wait_tensor, preventing + # the memory planner from reusing the input buffer while the + # backend stream is still reading it. + return _create_out_of_place( + symm_mem._low_contention_all_gather.default, + inp, + group_name, + ) + + @register_lowering(symm_mem._low_contention_all_gather_ce_multicast) + def _symm_mem_low_contention_all_gather_ce_multicast( + inp: ir.TensorBox, + group_name: "torch.distributed.distributed_c10d.GroupName", + ): + return _create_low_contention_ag_out( + symm_mem._low_contention_all_gather_ce_multicast_out.default, + inp, + group_name, + ) + + @register_lowering(symm_mem._low_contention_all_gather_ce_multicast_out) + def _symm_mem_low_contention_all_gather_ce_multicast_out( + inp: ir.TensorBox, + group_name: "torch.distributed.distributed_c10d.GroupName", + out: ir.TensorBox, + ): + inp.realize() + if can_realize_as_comm_buffer(out, ir.CommBufferType.SYMM_MEM): + realize_as_comm_buffer(out, ir.CommBufferType.SYMM_MEM, group_name) + else: + raise RuntimeError( + "_low_contention_all_gather_ce_multicast_out requires an " + "Inductor-owned output buffer that can be realized as symmetric " + "memory; this indicates an invalid lowering." + ) + return pytree.tree_map( + ir.TensorBox.create, + ir.FallbackKernel.create( + symm_mem._low_contention_all_gather_ce_multicast_out.default, + inp, + group_name, + out, + ), + ) + + @register_lowering(symm_mem._low_contention_reduce_scatter) + def _symm_mem_low_contention_reduce_scatter( + inp: ir.TensorBox, + reduce_op: str, + group_name: str, + ): + # Use _CollectiveKernel so that _WaitKernel.get_volatile_reads() + # can track the input's lifetime through wait_tensor, preventing + # the memory planner from reusing the input buffer while the + # backend stream is still reading it. + return _create_out_of_place( + symm_mem._low_contention_reduce_scatter.default, + inp, + reduce_op, + group_name, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/comms.py b/.venv/lib/python3.12/site-packages/torch/_inductor/comms.py new file mode 100644 index 0000000000000000000000000000000000000000..29de4a76c54ea141ab59a1599b0da6fbf0711212 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/comms.py @@ -0,0 +1,2402 @@ +# mypy: allow-untyped-defs +# pyre-strict +from __future__ import annotations + +import heapq +import importlib +import itertools +import logging +import sys +from collections import defaultdict +from dataclasses import dataclass +from typing import Any, TYPE_CHECKING + +import torch +from torch._logging import trace_structured +from torch.utils._ordered_set import OrderedSet + +from . import config, config_comms, ir +from .dependencies import WeakDep + + +if TYPE_CHECKING: + from .ir import IRNode, Operation + +from .memory import ( + estimate_peak_memory_allocfree, + FreeableInputBuffer, + get_freeable_input_buf, + SNodeMemory, +) +from .utils import contains_collective, contains_wait, is_fallback_op, is_wait +from .virtualized import V + + +log = logging.getLogger(__name__) +overlap_log = torch._logging.getArtifactLogger(__name__, "overlap") + +if TYPE_CHECKING: + from torch._inductor.scheduler import BaseSchedulerNode + + +def align_runtime_estimations_across_all_distributed_ranks( + snodes: list[BaseSchedulerNode], +): + runtime_estimations = [snode.get_estimated_runtime() for snode in snodes] + + import torch.distributed as dist + from torch.distributed.distributed_c10d import _get_default_group + + world_size = dist.get_world_size() + pg = _get_default_group() + gathered_runtime_estimations: list[list[float]] = [[] for _ in range(world_size)] + dist.all_gather_object( + gathered_runtime_estimations, + runtime_estimations, + pg, + ) + + lengths = OrderedSet([len(e) for e in gathered_runtime_estimations]) + if len(lengths) != 1: + log.warning( + "Different ranks have different numbers of scheduler nodes (%s), " + "skipping runtime estimation alignment", + [len(e) for e in gathered_runtime_estimations], + ) + for idx, snode in enumerate(snodes): + snode.override_estimated_runtime = runtime_estimations[idx] + return + + median_runtime_estimations = torch.median( + torch.tensor(gathered_runtime_estimations), dim=0 + ).values.tolist() + + for idx, snode in enumerate(snodes): + snode.override_estimated_runtime = median_runtime_estimations[idx] + + +def sink_waits(snodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]: + """ + Greedily schedules waits as late as possible. + """ + return _schedule_for_comm( + snodes, raise_comms=False, sink_waits=True, reorder_for_overlap=False + ) + + +def raise_comms(snodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]: + """ + Greedily schedules comms as early as possible. + """ + return _schedule_for_comm( + snodes, raise_comms=True, sink_waits=False, reorder_for_overlap=False + ) + + +def reorder_compute_for_overlap( + snodes: list[BaseSchedulerNode], +) -> list[BaseSchedulerNode]: + """ + This achieves the following overall scheduling procedure: + Step 1: Given that we've currently scheduled comm N, we now schedule all compute nodes + that are required for comm N + 1 but do not depend on comm N, to run at the same time with comm N. + Step 2: If all those compute nodes are sufficient to overlap comm N, we're done. + Otherwise, we now need to look elsewhere to find compute that overlaps with comm N. + We prioritize compute nodes that are needed sooner. + Step 3: We schedule the compute nodes dependent on comm N and required for comm N + 1. + Step 4: We schedule comm N + 1. + Repeat this for subsequent comm nodes. + """ + return _schedule_for_comm( + snodes, raise_comms=True, sink_waits=True, reorder_for_overlap=True + ) + + +def reorder_communication_preserving_peak_memory( + snodes: list[BaseSchedulerNode], +) -> list[BaseSchedulerNode]: + """ + Reorders communication ops relative to computation ops to improve communication-compute overlapping and hide comm + latency. Stops moving a particular op if it reaches a point that would have increased the peak memory footprint. + + Currently, follows these heuristics (subject to change or tune): + - never reorders collectives relative to one another, for SPMD safety + - has an option for per-collective prefetch limit, but does not enable it by default + - limits the total number of reorder steps to some factor of the graph size to prevent worst-case quadratic + performance + + Prerequisite: sink_comms_and_waits - ensure comm and wait nodes are scheduled as late as possible, respecting data + dependencies. That allows reorder_communication_preserving_peak_memory to take a best case peak-memory snapshot, + and then monotonically improve latency by moving collectives backward in time. + + Peak memory impact is computed in an iterative fashion. First, memory use at each timestep is computed, and global + peak memory is computed as a max over timesteps. Then, when swapping any two adjacent nodes, only the curr-memory + for the earlier of the nodes after the swap is affected. This enables checking step by step whether a swap is + peak-memory-safe, and bailing out if not. Example: + + 0 n0 C0 + 1 n1 C0 + Allocs(n1) - Frees(n1) + 2 n2 C0 + Allocs(n1) - Frees(n1) + Allocs(n2) - Frees(n2) + + 0 n0 C0 + 1 n2 C0 + Allocs(n2) - Frees(n2) <-- After moving n2 to Time 1, only time1 memory changes + 2 n1 C0 + Allocs(n2) - Frees(n2) + Allocs(n1) - Frees(n1) + + """ + reordered_snodes, node_stats = ( + _reorder_communication_preserving_peak_memory_internal(snodes) + ) + + return reordered_snodes + + +@dataclass +class ReorderInfo: + """ + Debug info describing how an individual snode was reordered + """ + + limiting_factor: str = "None" + moves: int = 0 + grouped: int = 0 + grouped_info: str = "" + comm_time: float = -1.0 + comp_time: float = -1.0 + initial_exposed: float = -1.0 + final_exposed: float = -1.0 + overlap_info: str = "None" + + @property + def improvement(self): + return self.initial_exposed - self.final_exposed + + +def is_gemm_like(node: IRNode | Operation | None) -> bool: + if node is None: + return False + + if is_fallback_op( + node, # type: ignore[arg-type] + torch.ops.aten._scaled_dot_product_flash_attention.default, + ): + return True + + if ( + python_kernel_name := getattr(node, "python_kernel_name", None) + ) and "extern_kernels" in python_kernel_name: + return True + return False + + +def contains_gemm_like(snode: BaseSchedulerNode) -> bool: + from torch._inductor.scheduler import GroupedSchedulerNode + + if isinstance(snode, GroupedSchedulerNode): + return any(contains_gemm_like(x) for x in snode.snodes) + else: + return is_gemm_like(snode.node) + + +def _temp_group_visit_leaves(snode: BaseSchedulerNode, fn): + from torch._inductor.scheduler import GroupedSchedulerNode + + if isinstance(snode, GroupedSchedulerNode) and snode.temp_grouping: + for _snode in snode.snodes: + fn(_snode) + else: + fn(snode) + + +def _group_name(snode, with_bufs=False) -> str: + ret = "" + for n in snode.snodes: + if ret: + ret += "_" + ret += n.get_name() + if with_bufs: + ret += f"{list(snode.get_buffer_names())}" + return ret + + +def _is_fake_dep(d): + return isinstance(d, WeakDep) and d.is_fake + + +def _group_names(gns: list[BaseSchedulerNode]) -> str: + return "~".join([gn.get_name() for gn in gns]) + + +def _initialize_memory_tracking(snodes, graph_inputs=None, graph_outputs=None): + """Initialize memory tracking data structures""" + if graph_inputs is None: + graph_inputs = OrderedSet(V.graph.graph_inputs.keys()) + if graph_outputs is None: + graph_outputs = OrderedSet(V.graph.get_output_names()) + + name_to_freeable_input_buf = get_freeable_input_buf(snodes, graph_inputs) + peak_memory, snodes_curr_memory, snodes_allocfree, buf_to_snode_last_use = ( + estimate_peak_memory_allocfree( + snodes, name_to_freeable_input_buf, graph_outputs + ) + ) + _curr_memory = dict(zip(snodes, snodes_curr_memory)) + # pyrefly: ignore [unsupported-operation] + _curr_memory[None] = (0, 0) + + # Build candidate buffer map for optimization + candidate_buffer_map = _build_candidate_buffer_map(buf_to_snode_last_use) + + return ( + peak_memory, + _curr_memory, + snodes_allocfree, + buf_to_snode_last_use, + name_to_freeable_input_buf, + candidate_buffer_map, + ) + + +def _initialize_double_linked_list( + snodes: list[BaseSchedulerNode], +) -> tuple[ + dict[BaseSchedulerNode, BaseSchedulerNode | None], + dict[BaseSchedulerNode, BaseSchedulerNode | None], + BaseSchedulerNode, +]: + """Create double-linked list structure from snodes""" + _prev = {} + _next = {} + for i, snode in enumerate(snodes): + _prev[snode] = snodes[i - 1] if i > 0 else None + _next[snode] = snodes[i + 1] if i < len(snodes) - 1 else None + _head = snodes[0] + return _prev, _next, _head + + +def _build_candidate_buffer_map( + buf_to_snode_last_use: dict, +) -> dict[BaseSchedulerNode, OrderedSet]: + """ + Build inverted index: node -> set of buffers where node appears in successors. + + This optimization reduces buffer iteration from O(total_buffers) to O(buffers_per_node). + Since buffer successors are immutable during reordering, this map doesn't need updates. + + Returns: + dict mapping each node to the set of buffers that have this node in their successors + """ + node_to_candidate_bufs: dict[BaseSchedulerNode, OrderedSet] = defaultdict( + OrderedSet + ) + + for buf in buf_to_snode_last_use: + # Add to every successor node's buffer set + for succ_node in buf.mpi_buffer.succ_nodes: + node_to_candidate_bufs[succ_node].add(buf) + + return dict(node_to_candidate_bufs) + + +def _precompute_node_output_sets( + snodes: list[BaseSchedulerNode], +) -> dict[BaseSchedulerNode, OrderedSet[str]]: + """ + Pre-compute output name sets for all nodes. + + This optimization avoids creating OrderedSet objects repeatedly during + exposed time calculations. + + Returns: + dict mapping each node to a set of its output names + """ + return { + snode: OrderedSet(o.get_name() for o in snode.get_outputs()) for snode in snodes + } + + +def _op_runtime_estimate_mult(snode): + # Apply multipliers for faster experimentation. + # TODO(ivankobzarev): Remove after confirmation that runtime estimations are correct. + if contains_collective(snode): + return config_comms.reorder_sink_runtime_estimations_comm_mult + + return config_comms.reorder_sink_runtime_estimations_non_comm_mult + + +def is_async_collective(snode): + """ + Filtering out ops that contain Collective and Wait inside and considered as Collectives. + See contains_collective function. + If the op contains Wait inside - consider as Synchronous compute. + """ + if python_kernel_name := getattr(snode.node, "python_kernel_name", None): + if "torch.ops._dtensor.shard_dim_alltoall.default" in python_kernel_name: + return False + + return True + + +def contains_async_collective(snode): + return contains_collective(snode, is_async_collective) + + +def _group_nodes_from_linked_list( + head: BaseSchedulerNode | None, + tail: BaseSchedulerNode | None, + next_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None], +) -> list[BaseSchedulerNode]: + """ + Traverse doubly-linked list from head to tail and return nodes as a list. + + Args: + head: Starting node of the segment + tail: Ending node of the segment (inclusive) + next_dict: Dictionary mapping each node to its next node + + Returns: + List of nodes from head to tail (inclusive) + """ + ret = [] + n = head + while True: + if n is not None: + ret.append(n) + if n == tail: + break + n = next_dict[n] # type: ignore[index] + return ret + + +def _is_corresponding_collective_wait( + collective_snode: BaseSchedulerNode, + wait_snode: BaseSchedulerNode, + node_output_sets: dict[BaseSchedulerNode, frozenset[str]], + node_dep_sets: dict[BaseSchedulerNode, frozenset[str]], +) -> bool: + """ + Check if a wait node corresponds to a given collective node. + Uses pre-computed sets for O(1) lookup. + """ + collective_outs = node_output_sets[collective_snode] + unmet_deps = node_dep_sets[wait_snode] + return bool(unmet_deps & collective_outs) + + +def _coll_exposed_communication_time( + collective_snode: BaseSchedulerNode, + next_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None], + runtimes: dict[BaseSchedulerNode, float], + node_output_sets: dict[BaseSchedulerNode, frozenset[str]], + node_dep_sets: dict[BaseSchedulerNode, frozenset[str]], +) -> tuple[float, float, str]: + """ + Calculate exposed communication time by iterating directly over linked list. + Avoids O(N) list construction for each call. + + The collective_snode is the starting point, iteration continues via next_dict. + """ + comm_time = runtimes[collective_snode] + comp_time = 0.0 + collective_outs = node_output_sets[collective_snode] + overlap_info = "" + collectives_found: list[BaseSchedulerNode] = [] + + snode = next_dict[collective_snode] + while snode is not None: + unmet_deps = node_dep_sets[snode] + + if unmet_deps & collective_outs: + overlap_info += f"->W[{snode.get_name()}]" + break + + if contains_collective(snode): + if not contains_async_collective(snode): + break + else: + collectives_found.append(snode) + snode = next_dict[snode] + continue + if contains_wait(snode): + has_wait_for_collectives_found = False + for _coll in collectives_found: + if _is_corresponding_collective_wait( + collective_snode, snode, node_output_sets, node_dep_sets + ): + has_wait_for_collectives_found = True + break + if has_wait_for_collectives_found: + break + + comp_time_before = comp_time + + def accumulate_time(_snode: BaseSchedulerNode) -> None: + nonlocal comp_time + comp_time += runtimes[_snode] + + _temp_group_visit_leaves(snode, accumulate_time) + comp_time_after = comp_time + overlap_info += f"+{snode.get_name()}[{comp_time_after - comp_time_before}]" + + snode = next_dict[snode] + + return comm_time, comp_time, overlap_info + + +def _wait_exposed_communication_time( + wait_snode: BaseSchedulerNode, + head: BaseSchedulerNode, + prev_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None], + runtimes: dict[BaseSchedulerNode, float], + node_output_sets: dict[BaseSchedulerNode, frozenset[str]], + node_dep_sets: dict[BaseSchedulerNode, frozenset[str]], +) -> tuple[float, float, str]: + """ + Calculate exposed communication time for a wait operation by iterating + directly over linked list backwards. Avoids O(N) list construction. + + Iterates from wait_snode backwards using prev_dict to find corresponding collective. + """ + comm_time = 0.0 + comp_time = 0.0 + overlap_info = "" + waits_found: list[BaseSchedulerNode] = [] + + snode = prev_dict[wait_snode] + while snode is not None: + if contains_wait(snode): + waits_found.append(snode) + if contains_collective(snode): + if _is_corresponding_collective_wait( + snode, wait_snode, node_output_sets, node_dep_sets + ): + comm_time = runtimes[snode] + overlap_info += f"->C[{snode.get_name()}]" + break + + if not contains_async_collective(snode): + comp_time = 0.0 + snode = prev_dict[snode] + continue + else: + for w in waits_found: + if _is_corresponding_collective_wait( + snode, w, node_output_sets, node_dep_sets + ): + comp_time = 0.0 + break # inner loop break + snode = prev_dict[snode] + continue + + comp_time_before = comp_time + + def accumulate_time(_snode: BaseSchedulerNode) -> None: + nonlocal comp_time + comp_time += runtimes[_snode] + + _temp_group_visit_leaves(snode, accumulate_time) + comp_time_after = comp_time + overlap_info += f"+{snode.get_name()}[{comp_time_after - comp_time_before}]" + + snode = prev_dict[snode] + + return comm_time, comp_time, overlap_info + + +def _perform_double_linked_list_swap( + candidate: BaseSchedulerNode, + group_head: BaseSchedulerNode, + group_tail: BaseSchedulerNode, + prev_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None], + next_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None], + head: BaseSchedulerNode, +) -> BaseSchedulerNode: + """ + Swap positions of candidate and group in doubly-linked list. + + Transforms: + candidate_prev -> candidate -> group_head...group_tail -> group_tail_next + Into: + candidate_prev -> group_head...group_tail -> candidate -> group_tail_next + + Args: + candidate: Node to swap with group + group_head: First node of group + group_tail: Last node of group + prev_dict: Dictionary mapping nodes to their previous nodes + next_dict: Dictionary mapping nodes to their next nodes + head: Current head of the linked list + + Returns: + New head of the linked list (may change if candidate was the head) + """ + # 0: Update candidate's previous node + candidate_prev = prev_dict[candidate] + if candidate_prev: + next_dict[candidate_prev] = group_head + prev_dict[group_head] = candidate_prev + + # 2: Update group_tail's next node + group_tail_next = next_dict[group_tail] + if group_tail_next: + prev_dict[group_tail_next] = candidate + next_dict[candidate] = group_tail_next + + # 1: Link group_tail to candidate + prev_dict[candidate] = group_tail + next_dict[group_tail] = candidate + + # Update head if candidate was the head + if head == candidate: + return group_head + return head + + +def _calculate_potential_peak_memory_reorder( + candidate: BaseSchedulerNode, + gns: list[BaseSchedulerNode], + group_tail: BaseSchedulerNode, + group_peak_memory: int, + candidate_delta_mem: int, + candidate_allocfree: SNodeMemory, + group_n_to_bufs_after_swap_dealloc_by_candidate: dict, + curr_memory: dict, +) -> tuple[int, dict[BaseSchedulerNode, int]]: + """ + Calculate potential peak memory after swapping candidate with group (reorder version). + + Computes new memory levels for all affected nodes and returns the potential + peak memory along with cached post-allocation memory values for each node. + + Args: + candidate: Node being moved + gns: Group nodes + group_tail: Last node of group + group_peak_memory: Current peak memory within the group + candidate_delta_mem: Net memory change from candidate (alloc - free) + candidate_allocfree: Candidate's allocation/free info + group_n_to_bufs_after_swap_dealloc_by_candidate: Buffers whose deallocation moves to candidate + curr_memory: Current memory state dict + + Returns: + Tuple of (potential_peak_memory, post_alloc_update_dict) + """ + # Caching calculations of memory for group nodes and candidate, + # to apply without recalculation after swap. + _post_alloc_update: dict[BaseSchedulerNode, int] = {} + potential_peak: int = 0 + if not group_n_to_bufs_after_swap_dealloc_by_candidate: + # Not accounting for buffers last use change + potential_peak = max( + group_peak_memory - candidate_delta_mem, + curr_memory[group_tail][1] + - candidate_delta_mem + + candidate_allocfree.size_alloc, + ) + return potential_peak, _post_alloc_update + + # If candidate will be after group, the starting memory level of group nodes + # changes to the -(candidate.size_alloc - candidate.size_free) + mem_after_reorder_delta: int = -candidate_delta_mem + for gn in gns: + gn_post_alloc_mem = curr_memory[gn][0] + mem_after_reorder_delta + _post_alloc_update[gn] = gn_post_alloc_mem + potential_peak = max(potential_peak, gn_post_alloc_mem) + + bufs = group_n_to_bufs_after_swap_dealloc_by_candidate.get(gn) + if bufs is not None: + for buf in bufs: + # Candidate will deallocate those buffers + mem_after_reorder_delta += buf.mpi_buffer.size_free + + candidate_mem_post_alloc = ( + curr_memory[group_tail][1] + + mem_after_reorder_delta + + candidate_allocfree.size_alloc + ) + _post_alloc_update[candidate] = candidate_mem_post_alloc + potential_peak = max(potential_peak, candidate_mem_post_alloc) + return potential_peak, _post_alloc_update + + +def _update_memory_tracking_after_swap_reorder( + candidate: BaseSchedulerNode, + gns: list[BaseSchedulerNode], + group_tail: BaseSchedulerNode, + candidate_delta_mem: int, + candidate_allocfree: SNodeMemory, + group_n_to_bufs_after_swap_dealloc_by_candidate: dict, + post_alloc_update: dict[BaseSchedulerNode, int], + curr_memory: dict, + buf_to_snode_last_use: dict, + snodes_allocfree: dict, +) -> None: + """ + Update memory tracking structures after swap (reorder version). + + Updates curr_memory, buf_to_snode_last_use, and snodes_allocfree dictionaries + to reflect the new memory state after swapping candidate with group. + + Args: + candidate: Node that was moved + gns: Group nodes + group_tail: Last node of group + candidate_delta_mem: Net memory change from candidate (alloc - free) + candidate_allocfree: Candidate's allocation/free info + group_n_to_bufs_after_swap_dealloc_by_candidate: Buffers whose deallocation moves to candidate + post_alloc_update: Cached post-allocation memory values + curr_memory: Current memory state dict (mutated) + buf_to_snode_last_use: Buffer to last-use node mapping (mutated) + snodes_allocfree: Node allocation/free info dict (mutated) + """ + if not group_n_to_bufs_after_swap_dealloc_by_candidate: + for gn in gns: + cm = curr_memory[gn] + curr_memory[gn] = ( + cm[0] - candidate_delta_mem, + cm[1] - candidate_delta_mem, + ) + _candidate_post_alloc_mem = ( + curr_memory[group_tail][1] + candidate_allocfree.size_alloc + ) + _candidate_post_free_mem = ( + _candidate_post_alloc_mem - candidate_allocfree.size_free + ) + curr_memory[candidate] = ( + _candidate_post_alloc_mem, + _candidate_post_free_mem, + ) + return + + # Candidate becomes last use of some bufs + for bufs in group_n_to_bufs_after_swap_dealloc_by_candidate.values(): + for buf in bufs: + buf_to_snode_last_use[buf] = candidate + + size_free_to_move_to_candidate_sum: int = 0 + for n in gns: + _gn_post_alloc_mem: int = post_alloc_update[n] + size_free_to_move_to_candidate: int = sum( + buf.mpi_buffer.size_free + for buf in group_n_to_bufs_after_swap_dealloc_by_candidate[n] + ) + size_free_to_move_to_candidate_sum += size_free_to_move_to_candidate + # group node does not deallocate this after swap + snodes_allocfree[n].size_free -= size_free_to_move_to_candidate + gn_post_free_mem: int = _gn_post_alloc_mem - snodes_allocfree[n].size_free + curr_memory[n] = (_gn_post_alloc_mem, gn_post_free_mem) + _candidate_post_alloc_mem = post_alloc_update[candidate] + snodes_allocfree[candidate].size_free += size_free_to_move_to_candidate_sum + candidate_post_free_mem = ( + _candidate_post_alloc_mem - snodes_allocfree[candidate].size_free + ) + curr_memory[candidate] = ( + _candidate_post_alloc_mem, + candidate_post_free_mem, + ) + + +def _find_buffers_with_changed_last_use( + candidate: BaseSchedulerNode, + gns: list[BaseSchedulerNode], + buf_to_snode_last_use: dict, + candidate_buffer_map: dict[BaseSchedulerNode, OrderedSet], +) -> dict[BaseSchedulerNode, list[FreeableInputBuffer | Any]]: + """ + Find buffers whose last use will change after swapping candidate with group. + + When we swap [candidate [group]] to [[group] candidate], some buffers that + were last used by a group node will now be last used by candidate instead. + This affects memory deallocation timing. + + Args: + candidate: The node being moved + gns: Group nodes being swapped with candidate + buf_to_snode_last_use: Mapping of buffers to their current last-use nodes + candidate_buffer_map: Pre-computed map of node -> buffers using that node + + Returns: + Dict mapping group nodes to buffers that will change their last-use node + """ + group_n_to_bufs_after_swap_dealloc_by_candidate: dict[ + BaseSchedulerNode, list[FreeableInputBuffer | Any] + ] = defaultdict(list) + + # Optimization: only check buffers where candidate is a successor + # Reduces from O(all_buffers) to O(buffers_per_candidate) + candidate_bufs = candidate_buffer_map.get(candidate, OrderedSet()) + gns_set = OrderedSet(gns) # O(1) membership testing + + for buf in candidate_bufs: + snode_last_use = buf_to_snode_last_use[buf] + if snode_last_use in gns_set: + group_n_to_bufs_after_swap_dealloc_by_candidate[snode_last_use].append(buf) + + return group_n_to_bufs_after_swap_dealloc_by_candidate + + +def _is_node_groupable_for_reorder( + candidate: BaseSchedulerNode, +) -> tuple[bool, str | None]: + """ + Check if a candidate node can be grouped with collective during reordering. + + This pass processes collectives left to right, so we avoid grouping with + already-processed collectives based on configuration. + + Args: + candidate: Node to check for groupability + + Returns: + Tuple of (is_groupable, reason_if_not_groupable) + """ + # This pass processes collectives left to right, + # Do not group with processed collectives. + # Leaving config for experimentation in 2D + if not config_comms.reorder_iterative_group_with_collectives: + if contains_async_collective(candidate): + return ( + False, + f"candidate contains_collective {candidate.get_name()}", + ) + if not config_comms.reorder_iterative_use_runtime_estimations: + if contains_gemm_like(candidate): + return False, "contains_gemm_like" + return True, None + + +def _format_and_log_reordering_stats( + stats: dict[BaseSchedulerNode, ReorderInfo], + head: BaseSchedulerNode, + next_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None], + original_snodes_num: int, + peak_memory: int, + name_to_freeable_input_buf: dict, + graph_outputs: OrderedSet[str], +) -> list[BaseSchedulerNode]: + """ + Format reordering statistics, log them, and return final node list. + + Computes improvement metrics, creates a formatted table (using tabulate if + available), validates the reordered node count, recalculates peak memory, + and logs all information. + + Args: + stats: Per-node reordering statistics + head: Head of the reordered linked list + next_dict: Linked list next pointers + original_snodes_num: Original number of nodes (for validation) + peak_memory: Initial peak memory before reordering + name_to_freeable_input_buf: Buffer memory tracking info + graph_outputs: Graph output names + + Returns: + Final reordered list of scheduler nodes + """ + node_stats = stats + improvement = {snode: node_stats[snode].improvement for snode in node_stats} + total_improvement = sum([improvement[snode] for snode in improvement]) + total_moves = sum([node_stats[snode].moves for snode in node_stats]) + + reorder_log_str = ( + f"reorder_communication_preserving_peak_memory improved overlap by {total_improvement} ns" + f" after {total_moves} reorders.\n" + ) + headers = [ + "Collective node", + "comm_time(us)", + "comp_time(us)", + "initial exposed(us)", + "final exposed(us)", + "improvement(us)", + "limiting factor", + "moves", + "grouped", + "grouped_info", + "overlap_info", + ] + rows = [ + [ + node_summary(snode), + node_info.comm_time / 1e3, + node_info.comp_time / 1e3, + node_info.initial_exposed / 1e3, + node_info.final_exposed / 1e3, + node_info.improvement / 1e3, + node_info.limiting_factor, + node_info.moves, + node_info.grouped, + node_info.grouped_info, + node_info.overlap_info, + ] + for snode, node_info in node_stats.items() + ] + if importlib.util.find_spec("tabulate"): + from tabulate import tabulate + + reorder_log_str += tabulate( + rows, + headers=headers, + ) + else: + reorder_log_str += ( + "Please `pip install tabulate` to nicely render overlap stats.\n" + ) + reorder_log_str += str(headers) + "\n" + reorder_log_str += "\n".join(map(str, rows)) + + new_snodes = _group_nodes_from_linked_list(head, None, next_dict) + if len(new_snodes) != original_snodes_num: + raise AssertionError( + f"expected {original_snodes_num} nodes, got {len(new_snodes)}" + ) + new_peak_memory, _, _, _ = estimate_peak_memory_allocfree( + new_snodes, name_to_freeable_input_buf, graph_outputs + ) + reorder_log_str += f"\n peak_memory_before:{peak_memory}" + reorder_log_str += f"\n peak_memory_after:{new_peak_memory}" + + overlap_log.info(reorder_log_str) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "reorder_communication_preserving_peak_memory", + "encoding": "string", + }, + payload_fn=lambda: reorder_log_str, + ) + + return new_snodes + + +def _reorder_communication_preserving_peak_memory_internal( + snodes: list[BaseSchedulerNode], +) -> tuple[list[BaseSchedulerNode], dict[BaseSchedulerNode, ReorderInfo]]: + """ + Internal testing helper that also returns debug info. + Returns: + - reordered snodes list + - dict {snode: ReorderInfo} + """ + has_collectives = False + for snode in snodes: + if contains_collective(snode): + has_collectives = True + break + if not has_collectives: + return snodes, {} + + original_snodes_num = len(snodes) + # heuristic to avoid degenerating to quadratic time + graph_inputs: OrderedSet[str] = OrderedSet(V.graph.graph_inputs.keys()) + graph_outputs: OrderedSet[str] = OrderedSet(V.graph.get_output_names()) + ( + peak_memory, + _curr_memory, + snodes_allocfree, + buf_to_snode_last_use, + name_to_freeable_input_buf, + candidate_buffer_map, + ) = _initialize_memory_tracking(snodes, graph_inputs, graph_outputs) + + runtimes: dict[BaseSchedulerNode, float] = { + snode: estimate_op_runtime(snode) * _op_runtime_estimate_mult(snode) + for snode in snodes + } + + # Pre-compute output and dependency sets for O(1) lookup instead of O(N) creation per iteration + node_output_sets: dict[BaseSchedulerNode, frozenset[str]] = { + snode: frozenset(o.get_name() for o in snode.get_outputs()) for snode in snodes + } + node_dep_sets: dict[BaseSchedulerNode, frozenset[str]] = { + snode: frozenset( + d.name for d in snode.unmet_dependencies if not _is_fake_dep(d) + ) + for snode in snodes + } + + # debug stats + stats: dict[BaseSchedulerNode, ReorderInfo] = {} + + total_moves = 0 + + _prev, _next, _head = _initialize_double_linked_list(snodes) + + debug_num_collectives_to_reorder: int | None = ( + config_comms.reorder_iterative_debug_limit_to_reorder + ) + + num_processed_collectives: int = 0 + curr: BaseSchedulerNode | None = _head + debug_iterative_memory_recompute = ( + config_comms.reorder_iterative_debug_memory_recompute + ) + iterative_recompute_error = False + + while curr is not None and _next[curr] is not None: + _next_curr = _next[curr] + if iterative_recompute_error: + break + + if not contains_async_collective(curr): + curr = _next_curr + continue + + if debug_num_collectives_to_reorder is not None and ( + num_processed_collectives >= debug_num_collectives_to_reorder + ): + break + num_processed_collectives += 1 + + info = stats[curr] = ReorderInfo() + comm_time, comp_time, overlap_info = _coll_exposed_communication_time( + curr, _next, runtimes, node_output_sets, node_dep_sets + ) + info.comm_time = comm_time + info.comp_time = comp_time + info.initial_exposed = info.final_exposed = comm_time - comp_time + info.overlap_info = overlap_info + + candidate = _prev[curr] + group_head = curr + group_tail = curr + group_waits = {} + group_runtime = 0.0 + group_peak_memory = _curr_memory[curr][0] # post_alloc memory + + # Track group dependencies incrementally - initialize from pre-computed sets + group_unmet_deps_names = OrderedSet(node_dep_sets[curr]) + group_output_names = OrderedSet(node_output_sets[curr]) + + while candidate is not None: + if config_comms.reorder_iterative_use_runtime_estimations and ( + info.final_exposed + < -config_comms.reorder_iterative_extra_comm_comp_overlap + * info.comm_time + ): + info.limiting_factor = "unexposed by runtime estimations" + break + + if ( + not config_comms.reorder_iterative_unsafe_collectives_reorder + and contains_collective(candidate) + ): + info.limiting_factor = "collective ordering" + break + + # Early exit: if group has no unmet dependencies, candidate can't have data dependency + data_deps_names = group_unmet_deps_names - group_output_names + if not data_deps_names: + data_dep = False + else: + # Calculate effective dependencies (not satisfied within group) + # Use pre-computed set for O(1) lookup + candidate_out_names = node_output_sets[candidate] + data_dep = bool(candidate_out_names & data_deps_names) + + if data_dep: + is_groupable_result, grouping_reason = _is_node_groupable_for_reorder( + candidate + ) + if is_groupable_result: + group_head = candidate + + # Update incremental dependency tracking using pre-computed sets + group_unmet_deps_names.update(node_dep_sets[candidate]) + group_output_names.update(node_output_sets[candidate]) + + if config_comms.reorder_iterative_use_runtime_estimations: + if contains_wait(candidate): + comm_time, comp_time, _ = _wait_exposed_communication_time( + candidate, + _head, + _prev, + runtimes, + node_output_sets, + node_dep_sets, + ) + group_waits[candidate] = comm_time, comp_time + if not contains_async_collective(candidate): + group_runtime += runtimes[candidate] + + group_peak_memory = max( + group_peak_memory, _curr_memory[candidate][0] + ) + info.grouped += 1 + candidate = _prev[candidate] + continue + else: + msg = ( + f"data dependency detected" + f"\n candidate:{candidate.get_name()}(outs:{[o.get_name() for o in candidate.get_outputs()]})" + f"\n non_group_reason:{grouping_reason}" + ) + info.limiting_factor = msg + break + + if config_comms.reorder_iterative_use_runtime_estimations: + # Check if candidate has sync runtime + if not contains_async_collective(candidate): + c_runtime = runtimes[candidate] + + if c_runtime > 0 and len(group_waits) > 0: + # pyrefly: ignore[no-matching-overload] + exposed_before = max(0, info.comm_time - info.comp_time) + # pyrefly: ignore[no-matching-overload] + exposed_after = max( + 0, info.comm_time - info.comp_time - c_runtime + ) + exposed_delta = exposed_after - exposed_before + for gw_comm_time, gw_comp_time in group_waits.values(): + # pyrefly: ignore [no-matching-overload] + gw_exposed_before = max(0, gw_comm_time - gw_comp_time) + # pyrefly: ignore [no-matching-overload] + gw_exposed_after = max( + 0, gw_comm_time - gw_comp_time + c_runtime + ) + + exposed_delta += gw_exposed_after - gw_exposed_before + + if exposed_delta > 0: + info.limiting_factor = ( + f"candidate has compute {c_runtime}," + f" group contains waits, total_exposed_delta {exposed_delta}" + ) + break + else: + # Update all group_colls comm_time, comp_time + for gw, ( + gw_comm_time, + gw_comp_time, + ) in group_waits.items(): + group_waits[gw] = ( + gw_comm_time, + gw_comp_time - c_runtime, + ) + else: + # Candidate is async_collective + + # Unsafe collectives reordering + # Cj -> [...group_runtime..., Ci] -> Wj + # Checking that we are not increasing exposed time of Cj + if group_runtime > 0: + comm_time, comp_time, _ = _coll_exposed_communication_time( + candidate, _next, runtimes, node_output_sets, node_dep_sets + ) + # pyrefly: ignore[no-matching-overload] + exposed_before = max(0, comm_time - comp_time) + # pyrefly: ignore[no-matching-overload] + exposed_after = max(0, comm_time - comp_time + group_runtime) + exposed_delta = exposed_after - exposed_before + if exposed_delta > 0: + info.limiting_factor = ( + f"candidate {candidate.get_name()} is collective," + f" group_runtime:{group_runtime}," + f" exposed_delta:{exposed_delta} c_comm_time:{comm_time} c_comp_time:{comp_time}" + ) + break + + # Create group nodes list once for swap operations + gns: list[BaseSchedulerNode] = _group_nodes_from_linked_list( + group_head, group_tail, _next + ) + + candidate_allocfree: SNodeMemory = snodes_allocfree[candidate] + candidate_delta_mem: int = ( + candidate_allocfree.size_alloc - candidate_allocfree.size_free + ) + # candidate and one of group nodes are successors of the same buffer + # and last use of the buffer happen in group nodes. + # This last use deallocates it. + # If we swap [candidate [group]] to [[group] candidate], + # candidate becomes the last use + # and deallocated this buffer instead of group node. + # we need to update size_free accordingly to group_node and candidate, + # and recalculate post_alloc, post_free for them. + # + # Buf that changes its last use snode, + # after swap will be deallocated only by candidate, + # while before it was deallocated by group node. + group_n_to_bufs_after_swap_dealloc_by_candidate = ( + _find_buffers_with_changed_last_use( + candidate, gns, buf_to_snode_last_use, candidate_buffer_map + ) + ) + + potential_peak, _post_alloc_update = ( + _calculate_potential_peak_memory_reorder( + candidate, + gns, + group_tail, + group_peak_memory, + candidate_delta_mem, + candidate_allocfree, + group_n_to_bufs_after_swap_dealloc_by_candidate, + _curr_memory, + ) + ) + + if ( + potential_peak - peak_memory + > peak_memory * config_comms.reorder_iterative_peak_memory_budget + ): + info.limiting_factor = ( + f"peak memory new:{potential_peak} vs base:{peak_memory}" + ) + break + info.moves += 1 + total_moves += 1 + + _head = _perform_double_linked_list_swap( + candidate, group_head, group_tail, _prev, _next, _head + ) + + comm_time, comp_time, overlap_info = _coll_exposed_communication_time( + curr, _next, runtimes, node_output_sets, node_dep_sets + ) + info.comm_time = comm_time + info.comp_time = comp_time + info.overlap_info = overlap_info + info.final_exposed = comm_time - comp_time + + _update_memory_tracking_after_swap_reorder( + candidate, + gns, + group_tail, + candidate_delta_mem, + candidate_allocfree, + group_n_to_bufs_after_swap_dealloc_by_candidate, + _post_alloc_update, + _curr_memory, + buf_to_snode_last_use, + snodes_allocfree, + ) + + if debug_iterative_memory_recompute: + # Compare iteratively recomputed memory data + # with full run of estimate_peak_memory + + from .comms_debug import _debug_iterative_memory_recompute + + iterative_recompute_error = _debug_iterative_memory_recompute( + candidate, + gns, + _group_names(gns), + _group_nodes_from_linked_list(_head, None, _next), + name_to_freeable_input_buf, + graph_outputs, + peak_memory, + _curr_memory, + snodes_allocfree, + "reorder_communication_preserving_peak_memory", + group_n_to_bufs_after_swap_dealloc_by_candidate, + ) + if iterative_recompute_error: + break + candidate = _prev[group_head] + curr = _next_curr + + if not config_comms.reorder_sink_verbose_logging: + new_snodes = _group_nodes_from_linked_list(_head, None, _next) + return new_snodes, stats + + new_snodes = _format_and_log_reordering_stats( + stats, + _head, + _next, + original_snodes_num, + peak_memory, + name_to_freeable_input_buf, + graph_outputs, + ) + + return new_snodes, stats + + +def _schedule_for_comm( + snodes: list[BaseSchedulerNode], + raise_comms: bool, + sink_waits: bool, + reorder_for_overlap: bool, +) -> list[BaseSchedulerNode]: + """ + Schedule `snodes` for various comm optimization objectives. + + Args: + snodes: the nodes to be scheduled. + raise_comms: whether to greedily schedule collectives as early as possible + sink_wait: whether to greedily schedule waits as late as possible + reorder_compute_for_overlap: whether to reorder compute nodes to + optimize for compute/communication overlapping. + + Returns: + The new schedule order. + + Some notes on the synergy between different options: + - `raise_comms` provides more overlapping opportunities for `reorder_compute_for_overlap`. + - When both `raise_comms` and `sink_waits` is `True`, `raise_comms` is prioritized. + """ + # We assign each node a tuple of scores (score_0, score_1, score_2), + # decreasing in importance, with a lower value indicating a higher ranking: + # + # - score_0: the lowest comm_idx among the comm nodes that the node blocks. + # If a node doesn't block any comm nodes, its score_0 is set to + # sys.maxsize. This score ensures that comm nodes get scheduled as early as + # possible. + # - score_1: 1 if the node is a wait node, 0 otherwise. This score ensures + # that wait nodes are deferred as late as possible. + # - score_2: the index of the node in the original topological order. This + # score provides stability in case of ties. + # + # When only raise_comms is True, only score_0 and score_2 are considered. + # When only sink_waits is True, only score_1 and score_2 are considered. + # When neither is True, the original order is yielded. + buf_name_to_snode = {} + name_to_fused_node = {} + scores_0, scores_1, scores_2 = {}, {}, {} + for idx, snode in enumerate(snodes): + for buf_name in snode.get_buffer_names(): + buf_name_to_snode[buf_name] = snode + + for op_name in snode.get_operation_names(): + name_to_fused_node[op_name] = snode + name_to_fused_node[snode.get_name()] = snode + + node_name = snode.get_name() + scores_0[node_name] = sys.maxsize + scores_1[node_name] = 0 + scores_2[node_name] = idx + + comm_idx = 0 + for snode in snodes: + if raise_comms and contains_collective(snode): + scores_0[snode.get_name()] = comm_idx + for ancestor in snode.ancestors: + anc_fused_name = name_to_fused_node[ancestor].get_name() + scores_0[anc_fused_name] = min(scores_0[anc_fused_name], comm_idx) + comm_idx += 1 + elif sink_waits and contains_wait(snode): + scores_1[snode.get_name()] = 1 + + class Runnable: + def __init__(self, snode) -> None: + self.snode = snode + name = next(iter(snode.get_operation_names())) + fused_name = name_to_fused_node[name].get_name() + self.score = ( + scores_0[fused_name], + scores_1[fused_name], + scores_2[fused_name], + ) + + def __lt__(self, other): + return self.score < other.score + + unmet_deps: dict[BaseSchedulerNode, OrderedSet[str]] = { + snode: OrderedSet(dep.name for dep in snode.unmet_dependencies) + for snode in snodes + } + + ready: list[Runnable] = [] + buffer_users: dict[str, OrderedSet[BaseSchedulerNode]] = defaultdict(OrderedSet) + snode_to_cost = {snode: estimate_op_runtime(snode) for snode in snodes} + + for snode, deps in unmet_deps.items(): + if len(deps) == 0: + heapq.heappush(ready, Runnable(snode)) + for dep in deps: + buffer_users[dep].add(snode) + + scheduled = [] + + def schedule(snode): + """ + Schedules `snode` and put all unblocked nodes onto the ready queue. + """ + scheduled.append(snode) + for buf_name in snode.get_buffer_names(): + for snode in buffer_users[buf_name]: + unmet_deps[snode].remove(buf_name) + if len(unmet_deps[snode]) == 0: + heapq.heappush(ready, Runnable(snode)) + + def get_overlapping_candidate(): + """ + Return the next node in the ready queue that's neither a collective or + a wait. + """ + candidates = [ + x + for x in ready + if not contains_collective(x.snode) and not contains_wait(x.snode) + ] + if len(candidates) == 0: + return None + return min(candidates, key=lambda x: x.score) + + def schedule_collective_for_overlap(snode): + """ + Schedules collective node `snode`, along with one or more compute nodes + to overlap with it. The strategy is described in the comment of + `reorder_compute_for_overlap`. + """ + if not contains_collective(snode): + raise AssertionError("expected snode to contain a collective") + schedule(snode) + + collective_cost = snode_to_cost[snode] + while ( + collective_cost > 0 + and (candidate := get_overlapping_candidate()) is not None + ): + ready.remove(candidate) + + schedule(candidate.snode) + + collective_cost -= snode_to_cost[candidate.snode] + heapq.heapify(ready) + + while ready: + snode = heapq.heappop(ready).snode + if reorder_for_overlap and contains_collective(snode): + schedule_collective_for_overlap(snode) + else: + schedule(snode) + + for deps in unmet_deps.values(): + if len(deps) != 0: + raise AssertionError( + f"Detected unscheduled nodes. Nodes with unmet dependencies: {unmet_deps}" + ) + return scheduled + + +def decide_global_ordering_of_comms( + nodes: list[BaseSchedulerNode], name_to_buf, name_to_fused_node +) -> list[BaseSchedulerNode]: + """ + Decide global ordering of comms, by just enforcing the ordering that's in the input graph + (might not be the same ordering as the eager mode program). + TODO: Come up with a better approach + """ + if not torch.distributed.is_available(): + return nodes + + comm_nodes = [n for n in nodes if contains_collective(n)] + + for i in range(1, len(comm_nodes)): + # Enforce ordering by making previous comm a `WeakDep` dependency of the next comm + mutating_buf = next(iter(comm_nodes[i].get_buffer_names())) + for buf in comm_nodes[i - 1].get_buffer_names(): + comm_nodes[i].add_fake_dep( + WeakDep(buf, mutating_buf=mutating_buf, is_fake=True) + ) + + return nodes + + +@dataclass +class SinkWaitInfo: + grouped: int = 0 + grouped_info: str = "" + moves: int = 0 + moves_info: str = "" + limiting_factor: str = "None" + comm_time: float = -1.0 + comp_time: float = -1.0 + initial_exposed: float = -1.0 + final_exposed: float = -1.0 + overlap_info: str = "None" + + @property + def improvement(self): + return self.initial_exposed - self.final_exposed + + +def _is_node_groupable_for_sink_waits( + candidate: BaseSchedulerNode, +) -> tuple[bool, str | None]: + """ + Check if a candidate node can be grouped during sink_waits pass. + + Sink Waits traverses waits right to left, so we don't group with + processed waits on the right or with async collectives. + + Args: + candidate: Node to check for groupability + + Returns: + Tuple of (is_groupable, reason_if_not_groupable) + """ + # Sink Waits traverse Waits right to left, + # => we do not group with processed Waits on the right. + if contains_wait(candidate): + return False, f"candidate contains wait {candidate.get_name()}" + if contains_async_collective(candidate): + return ( + False, + f"candidate contains_async_collective {candidate.get_name()}", + ) + + if not config_comms.sink_iterative_use_runtime_estimations: + # Heuristics pre-use_runtime_estimations: + # TODO(ivankobzarev): Remove them after confirming, + # that using runtime estimations always give better results. + # We do not want to group with collectives to not reorder them forward. + if contains_collective(candidate): + return ( + False, + f"candidate contains collective {candidate.get_name()}", + ) + if contains_gemm_like(candidate): + return ( + False, + f"candidate contains gemm_like {candidate.get_name()}", + ) + return True, None + + +def _update_memory_tracking_after_swap_sink_waits( + candidate: BaseSchedulerNode, + gns: list[BaseSchedulerNode], + candidate_delta_mem: int, + candidate_allocfree: SNodeMemory, + group_n_to_bufs_after_swap_dealloc_instead_of_candidate: dict, + post_alloc_update: dict[BaseSchedulerNode, int], + size_free_delta_update: dict[BaseSchedulerNode, int], + curr_memory: dict, + snodes_allocfree: dict, +) -> None: + """ + Update memory tracking structures after swap (sink_waits version). + + Updates curr_memory and snodes_allocfree dictionaries to reflect the new + memory state after swapping candidate with group. + + Args: + candidate: Node that was moved + gns: Group nodes + candidate_delta_mem: Net memory change from candidate (alloc - free) + candidate_allocfree: Candidate's allocation/free info + group_n_to_bufs_after_swap_dealloc_instead_of_candidate: Buffers whose deallocation moves from candidate to group + post_alloc_update: Cached post-allocation memory values + size_free_delta_update: Cached size-free delta values + curr_memory: Current memory state dict (mutated) + snodes_allocfree: Node allocation/free info dict (mutated) + """ + group_head = gns[0] + pre_group_mem = curr_memory[group_head][0] - snodes_allocfree[group_head].size_alloc + if not group_n_to_bufs_after_swap_dealloc_instead_of_candidate: + candidate_post_alloc = pre_group_mem + candidate_allocfree.size_alloc + curr_memory[candidate] = ( + candidate_post_alloc, + candidate_post_alloc - candidate_allocfree.size_free, + ) + for gn in gns: + cm = curr_memory[gn] + curr_memory[gn] = ( + cm[0] + candidate_delta_mem, + cm[1] + candidate_delta_mem, + ) + return + + for n in [candidate, *gns]: + post_alloc = post_alloc_update[n] + snodes_allocfree[n].size_free += size_free_delta_update.get(n, 0) + curr_memory[n] = ( + post_alloc, + post_alloc - snodes_allocfree[n].size_free, + ) + + +def _calculate_potential_peak_memory_sink_waits( + candidate: BaseSchedulerNode, + gns: list[BaseSchedulerNode], + group_head: BaseSchedulerNode, + group_peak_memory: int, + candidate_delta_mem: int, + candidate_allocfree: SNodeMemory, + group_n_to_bufs_after_swap_dealloc_instead_of_candidate: dict, + curr_memory: dict, + snodes_allocfree: dict, +) -> tuple[int, dict[BaseSchedulerNode, int], dict[BaseSchedulerNode, int]]: + """ + Calculate potential peak memory after swapping candidate with group (sink_waits version). + + Computes new memory levels for all affected nodes and returns the potential + peak memory along with cached post-allocation and size-free delta values. + + Args: + candidate: Node being moved + gns: Group nodes + group_head: First node of group + group_peak_memory: Current peak memory within the group + candidate_delta_mem: Net memory change from candidate (alloc - free) + candidate_allocfree: Candidate's allocation/free info + group_n_to_bufs_after_swap_dealloc_instead_of_candidate: Buffers whose deallocation moves from candidate to group + curr_memory: Current memory state dict + snodes_allocfree: Allocation/free info for all nodes + + Returns: + Tuple of (potential_peak_memory, post_alloc_update_dict, size_free_delta_update_dict) + """ + pre_group_mem = curr_memory[group_head][0] - snodes_allocfree[group_head].size_alloc + # Stash memory tracing updates to not recompute them after swap + _post_alloc_update: dict[BaseSchedulerNode, int] = {} + _size_free_delta_update: dict[BaseSchedulerNode, int] = {} + + potential_peak = 0 + if not group_n_to_bufs_after_swap_dealloc_instead_of_candidate: + # Not accounting for buffers liveliness change + potential_peak = max( + group_peak_memory + candidate_delta_mem, + pre_group_mem + candidate_allocfree.size_alloc, + ) + return potential_peak, _post_alloc_update, _size_free_delta_update + + candidate_post_alloc = pre_group_mem + candidate_allocfree.size_alloc + _post_alloc_update[candidate] = candidate_post_alloc + potential_peak = candidate_post_alloc + candidate_size_free_to_move = sum( + buf.mpi_buffer.size_free # type: ignore[attr-defined] + for buf in itertools.chain.from_iterable( + group_n_to_bufs_after_swap_dealloc_instead_of_candidate.values() + ) + ) + _size_free_delta_update[candidate] = -candidate_size_free_to_move + delta_mem = candidate_delta_mem + candidate_size_free_to_move + for gn in gns: + gn_post_alloc = curr_memory[gn][0] + delta_mem + _post_alloc_update[gn] = gn_post_alloc + potential_peak = max(potential_peak, gn_post_alloc) + gn_size_free_to_add = 0 + if gn in group_n_to_bufs_after_swap_dealloc_instead_of_candidate: + bufs = group_n_to_bufs_after_swap_dealloc_instead_of_candidate[gn] + for buf in bufs: + gn_size_free_to_add += buf.mpi_buffer.size_free + _size_free_delta_update[gn] = gn_size_free_to_add + delta_mem -= gn_size_free_to_add + return potential_peak, _post_alloc_update, _size_free_delta_update + + +def _perform_double_linked_list_swap_sink_waits( + candidate: BaseSchedulerNode, + group_head: BaseSchedulerNode, + group_tail: BaseSchedulerNode, + prev_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None], + next_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None], + head: BaseSchedulerNode, +) -> BaseSchedulerNode: + """ + Swap positions of candidate and group in doubly-linked list (sink_waits version). + + Transforms (moves candidate to the left): + group_head_prev -> group_head...group_tail -> candidate -> candidate_next + Into: + group_head_prev -> candidate -> group_head...group_tail -> candidate_next + + Args: + candidate: Node to swap with group + group_head: First node of group + group_tail: Last node of group + prev_dict: Dictionary mapping nodes to their previous nodes + next_dict: Dictionary mapping nodes to their next nodes + head: Current head of the linked list + + Returns: + New head of the linked list (may change if group_head was the head) + """ + # 0: Update group_head's previous node + group_head_prev = prev_dict[group_head] + if group_head_prev: + next_dict[group_head_prev] = candidate + prev_dict[candidate] = group_head_prev + + # 2: Update candidate's next node + candidate_next = next_dict[candidate] + if candidate_next: + prev_dict[candidate_next] = group_tail + next_dict[group_tail] = candidate_next + + # 1: Link candidate to group_head + prev_dict[group_head] = candidate + next_dict[candidate] = group_head + + # Update head if group_head was the head + if group_head == head: + return candidate + return head + + +def _format_and_log_sink_waits_stats( + stats: dict[BaseSchedulerNode, SinkWaitInfo], + head: BaseSchedulerNode, + next_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None], + original_snodes_num: int, + peak_memory: int, + name_to_freeable_input_buf: dict, + graph_outputs: OrderedSet[str], +) -> list[BaseSchedulerNode]: + """ + Format sink_waits statistics, log them, and return final node list. + + Computes improvement metrics, creates a formatted table (using tabulate if + available), validates the reordered node count, recalculates peak memory, + and logs all information. + + Args: + stats: Per-node sink_waits statistics + head: Head of the reordered linked list + next_dict: Linked list next pointers + original_snodes_num: Original number of nodes (for validation) + peak_memory: Initial peak memory before reordering + name_to_freeable_input_buf: Buffer memory tracking info + graph_outputs: Graph output names + + Returns: + Final reordered list of scheduler nodes + """ + headers = [ + "Wait node", + "comm_time(us)", + "comp_time(us)", + "initial exposed(us)", + "final exposed(us)", + "improvement(us)", + "limiting factor", + "grouped", + "grouped_info", + "moves", + "moves_info", + "overlap_info", + ] + rows = [ + [ + node_summary(snode), + info.comm_time / 1e3, + info.comp_time / 1e3, + info.initial_exposed / 1e3, + info.final_exposed / 1e3, + info.improvement / 1e3, + info.limiting_factor, + info.grouped, + info.grouped_info, + info.moves, + info.moves_info, + info.overlap_info, + ] + for snode, info in stats.items() + ] + log_str = "" + if importlib.util.find_spec("tabulate"): + from tabulate import tabulate + + log_str += tabulate( + rows, + headers=headers, + ) + else: + log_str += "Please `pip install tabulate` to nicely render overlap stats.\n" + log_str += str(headers) + "\n" + log_str += "\n".join(map(str, rows)) + overlap_log.info(log_str) + new_snodes = _group_nodes_from_linked_list(head, None, next_dict) + if len(new_snodes) != original_snodes_num: + raise AssertionError( + f"expected {original_snodes_num} nodes, got {len(new_snodes)}" + ) + new_peak_memory, _, _, _ = estimate_peak_memory_allocfree( + new_snodes, name_to_freeable_input_buf, graph_outputs + ) + log_str += f"\n sink_waits_iterative peak_memory_before:{peak_memory}" + log_str += f"\n sink_waits_iterative peak_memory_after:{new_peak_memory}" + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "sink_waits_iterative_info", + "encoding": "string", + }, + payload_fn=lambda: log_str, + ) + return new_snodes + + +def _find_buffers_with_changed_last_use_sink_waits( + candidate: BaseSchedulerNode, + gns: list[BaseSchedulerNode], + buf_to_snode_last_use: dict, + candidate_buffer_map: dict[BaseSchedulerNode, OrderedSet], +) -> dict[BaseSchedulerNode, list[FreeableInputBuffer | Any]]: + """ + Find buffers whose last use will change after swapping in sink_waits pass. + + When we swap [group] candidate to candidate [group], some buffers that + were last used by candidate will now be last used by a group node instead. + This is the opposite direction from the reorder version. + + Args: + candidate: The node being moved (currently last use) + gns: Group nodes being swapped with candidate + buf_to_snode_last_use: Mapping of buffers to their current last-use nodes + candidate_buffer_map: Pre-computed map of node -> buffers using that node + + Returns: + Dict mapping group nodes to buffers that will change their last-use node + """ + group_n_to_bufs_after_swap_dealloc_instead_of_candidate: dict[ + BaseSchedulerNode, list[FreeableInputBuffer | Any] + ] = defaultdict(list) + + # Optimization: only check buffers where candidate is a successor + # Reduces from O(all_buffers) to O(buffers_per_candidate) + candidate_bufs = candidate_buffer_map.get(candidate, OrderedSet()) + + for buf in candidate_bufs: + snode_last_use = buf_to_snode_last_use[buf] + if snode_last_use != candidate: + continue + + # candidate is last use of buf + # Find last group node in successors (maintains order) + succ_nodes = buf.mpi_buffer.succ_nodes + last_succ_gn = None + for gn in gns: + if gn in succ_nodes: + last_succ_gn = gn + + if last_succ_gn is None: + continue + + # gn has successors of buf that after potential swap will become + # last use of buf and start deallocating buf instead of candidate + group_n_to_bufs_after_swap_dealloc_instead_of_candidate[last_succ_gn].append( + buf + ) + + return group_n_to_bufs_after_swap_dealloc_instead_of_candidate + + +def _sink_waits_iterative_internal( + snodes: list[BaseSchedulerNode], +) -> tuple[list[BaseSchedulerNode], dict[BaseSchedulerNode, SinkWaitInfo]]: + original_snodes_num = len(snodes) + if original_snodes_num == 0: + return snodes, {} + graph_inputs: OrderedSet[str] = OrderedSet(V.graph.graph_inputs.keys()) + graph_outputs: OrderedSet[str] = OrderedSet(V.graph.get_output_names()) + ( + peak_memory, + _curr_memory, + snodes_allocfree, + buf_to_snode_last_use, + name_to_freeable_input_buf, + candidate_buffer_map, + ) = _initialize_memory_tracking(snodes, graph_inputs, graph_outputs) + + _prev, _next, _head = _initialize_double_linked_list(snodes) + + stats: dict[BaseSchedulerNode, SinkWaitInfo] = {} + + runtimes: dict[BaseSchedulerNode, float] = { + snode: estimate_op_runtime(snode) * _op_runtime_estimate_mult(snode) + for snode in snodes + } + + # Pre-compute output and dependency sets for O(1) lookup instead of O(N) creation per iteration + node_output_sets: dict[BaseSchedulerNode, frozenset[str]] = { + snode: frozenset(o.get_name() for o in snode.get_outputs()) for snode in snodes + } + node_dep_sets: dict[BaseSchedulerNode, frozenset[str]] = { + snode: frozenset( + d.name for d in snode.unmet_dependencies if not _is_fake_dep(d) + ) + for snode in snodes + } + + curr: BaseSchedulerNode | None = snodes[-1] + + processed_waits = OrderedSet() # type: ignore[var-annotated] + debug_iterative_memory_recompute = ( + config_comms.reorder_iterative_debug_memory_recompute + ) + debug_num_sink_waits_to_reorder: int | None = ( + config_comms.sink_waits_iterative_debug_limit_to_sink + ) + + iterative_recompute_error = False + while curr is not None and _prev[curr] is not None: + _prev_curr = _prev[curr] + if iterative_recompute_error: + break + if ( + debug_num_sink_waits_to_reorder is not None + and len(processed_waits) >= debug_num_sink_waits_to_reorder + ): + break + + if not (contains_wait(curr) and curr not in processed_waits): + curr = _prev_curr + continue + + processed_waits.add(curr) + info = stats[curr] = SinkWaitInfo() + comm_time, comp_time, overlap_info = _wait_exposed_communication_time( + curr, _head, _prev, runtimes, node_output_sets, node_dep_sets + ) + info.initial_exposed = info.final_exposed = comm_time - comp_time + info.comm_time = comm_time + info.comp_time = comp_time + info.overlap_info = overlap_info + + candidate = _next[curr] + group_head = curr + group_tail = curr + group_colls = {} + group_runtime = 0.0 + group_peak_memory = _curr_memory[curr][0] + + # Track group outputs and check collective status incrementally - initialize from pre-computed set + group_output_names = OrderedSet(node_output_sets[curr]) + group_contains_collective = contains_collective(curr) + + while candidate is not None: + if config_comms.sink_iterative_use_runtime_estimations and ( + info.final_exposed + < -config_comms.sink_iterative_extra_comm_comp_overlap * info.comm_time + ): + info.limiting_factor = "unexposed by runtime estimations" + break + + # Early exit: if group has no outputs, candidate can't depend on it + if not group_output_names: + data_dep = False + else: + # Calculate candidate dependencies using pre-computed set + candidate_dep_names = node_dep_sets[candidate] + data_dep = bool(candidate_dep_names & group_output_names) + + # Conservative sink wait, limiting by space before next collective. + # The global strategy is that bucketing should create space. + # For 2D we can experiment with allowing to sink Wait beyond non current group collective. + + if not config_comms.sink_waits_iterative_swap_with_collectives: + if contains_async_collective(candidate): + info.limiting_factor = ( + f"candidate contains_async_collective {candidate.get_name()}" + ) + break + + # 1. If we have data_dep - we can not swap => trying to group + # 2. If swap candidate and current node both contain collectives => trying to group + both_contain_comms = group_contains_collective and contains_collective( + candidate + ) + if data_dep or both_contain_comms: + _is_groupable, groupable_reason = _is_node_groupable_for_sink_waits( + candidate + ) + if _is_groupable: + group_tail = candidate + + # Update incremental tracking using pre-computed set + group_output_names.update(node_output_sets[candidate]) + group_contains_collective = ( + group_contains_collective or contains_collective(candidate) + ) + + if ( + config_comms.sink_iterative_use_runtime_estimations + and contains_collective(candidate) + ): + comm_time, comp_time, _ = _coll_exposed_communication_time( + candidate, _next, runtimes, node_output_sets, node_dep_sets + ) + group_colls[candidate] = (comm_time, comp_time) + if not contains_async_collective(candidate): + group_runtime += runtimes[candidate] + + group_peak_memory = max( + group_peak_memory, _curr_memory[candidate][0] + ) + info.grouped += 1 + candidate = _next[candidate] + continue + elif not data_dep: + if ( + not config_comms.sink_waits_iterative_unsafe_collectives_reorder + and both_contain_comms + ): + info.limiting_factor = ( + f"collective ordering" + f"\n with candidate:{candidate.get_name()}" + ) + break + else: + info.limiting_factor = ( + f"data dependency detected" + f"\n candidate:{candidate.get_name()}" + f"\n non_group_reason:{groupable_reason}" + ) + break + + if config_comms.sink_iterative_use_runtime_estimations: + if is_wait(candidate.node): + # Corresponding collective is before the group, + # Swap can increase exposed time of corresponding collective + comm_time, comp_time, _ = _wait_exposed_communication_time( + candidate, + _head, + _prev, + runtimes, + node_output_sets, + node_dep_sets, + ) + # pyrefly: ignore[no-matching-overload] + exposed_before = max(0, comm_time - comp_time) + # pyrefly: ignore[no-matching-overload] + exposed_after = max(0, comm_time - comp_time + group_runtime) + # We do not know how much we can sink more after this swap, + # Just comparing advantage at the moment for now. + if exposed_after > exposed_before: + info.limiting_factor = ( + "candidate is wait," + f" exposed_before:{exposed_before} vs exposed_after:{exposed_after}" + ) + break + + # Check if candidate has sync runtime + if not contains_async_collective(candidate): + # If candidate has sync runtime, + # Waits of gorup_colls are on the right from group. + # Swap can increase their exposed time. + c_runtime = runtimes[candidate] + + if c_runtime > 0 and len(group_colls) > 0: + # pyrefly: ignore[no-matching-overload] + exposed_before = max(0, info.comm_time - info.comp_time) + # pyrefly: ignore[no-matching-overload] + exposed_after = max( + 0, info.comm_time - info.comp_time - c_runtime + ) + exposed_delta = exposed_after - exposed_before + for gc_comm_time, gc_comp_time in group_colls.values(): + # pyrefly: ignore [no-matching-overload] + gc_exposed_before = max(0, gc_comm_time - gc_comp_time) + # pyrefly: ignore [no-matching-overload] + gc_exposed_after = max( + 0, gc_comm_time - gc_comp_time + c_runtime + ) + exposed_delta += gc_exposed_after - gc_exposed_before + if exposed_delta > 0: + info.limiting_factor = ( + f"candidate has compute {c_runtime}, group contains collectives," + f" total_exposed_delta {exposed_delta}" + ) + break + else: + # Update all group_colls comm_time, comp_time + for gc, ( + gc_comm_time, + gc_comp_time, + ) in group_colls.items(): + group_colls[gc] = ( + gc_comm_time, + gc_comp_time - c_runtime, + ) + + # Create group nodes list once for swap operations + gns: list[BaseSchedulerNode] = _group_nodes_from_linked_list( + group_head, group_tail, _next + ) + + candidate_allocfree: SNodeMemory = snodes_allocfree[candidate] + candidate_delta_mem = ( + candidate_allocfree.size_alloc - candidate_allocfree.size_free + ) + # [group] candidate -> candidate [group] + # Check for buffers with successors in group and candidate last successor + # + # Buf that changes its last use snode, + # It was deallocated by candidate, + # but after swap it will be deallocated by group node. + group_n_to_bufs_after_swap_dealloc_instead_of_candidate = ( + _find_buffers_with_changed_last_use_sink_waits( + candidate, gns, buf_to_snode_last_use, candidate_buffer_map + ) + ) + + potential_peak, _post_alloc_update, _size_free_delta_update = ( + _calculate_potential_peak_memory_sink_waits( + candidate, + gns, + group_head, + group_peak_memory, + candidate_delta_mem, + candidate_allocfree, + group_n_to_bufs_after_swap_dealloc_instead_of_candidate, + _curr_memory, + snodes_allocfree, + ) + ) + if ( + potential_peak - peak_memory + > peak_memory * config_comms.sink_iterative_peak_memory_budget + ): + info.limiting_factor = ( + f"peak memory new:{potential_peak} vs base:{peak_memory}" + ) + break + + info.moves += 1 + info.moves_info += f"+{candidate.get_name()}" + + _head = _perform_double_linked_list_swap_sink_waits( + candidate, group_head, group_tail, _prev, _next, _head + ) + + comm_time, comp_time, overlap_info = _wait_exposed_communication_time( + curr, _head, _prev, runtimes, node_output_sets, node_dep_sets + ) + info.comm_time = comm_time + info.comp_time = comp_time + info.final_exposed = comm_time - comp_time + info.overlap_info = overlap_info + + _update_memory_tracking_after_swap_sink_waits( + candidate, + gns, + candidate_delta_mem, + candidate_allocfree, + group_n_to_bufs_after_swap_dealloc_instead_of_candidate, + _post_alloc_update, + _size_free_delta_update, + _curr_memory, + snodes_allocfree, + ) + + if debug_iterative_memory_recompute: + from .comms_debug import _debug_iterative_memory_recompute + + iterative_recompute_error = _debug_iterative_memory_recompute( + candidate, + gns, + _group_names(gns), + _group_nodes_from_linked_list(_head, None, _next), + name_to_freeable_input_buf, + graph_outputs, + peak_memory, + _curr_memory, + snodes_allocfree, + "sink_waits_iterative", + group_n_to_bufs_after_swap_dealloc_instead_of_candidate, + ) + if iterative_recompute_error: + break + + candidate = _next[group_tail] + curr = _prev_curr + + if not config_comms.reorder_sink_verbose_logging: + new_snodes = _group_nodes_from_linked_list(_head, None, _next) + return new_snodes, stats + + new_snodes = _format_and_log_sink_waits_stats( + stats, + _head, + _next, + original_snodes_num, + peak_memory, + name_to_freeable_input_buf, + graph_outputs, + ) + + return new_snodes, stats + + +def sink_waits_iterative(snodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]: + """ + Similarly to reorder_communication_preserving_peak_memory this pass will try to iteratively + push Wait nodes later, recomputing estimated peak memory before each swap, + and preventing peak memory regressions. + + Pass will be applied to every Wait node. If there are immediate dependencies with next node, + pass will try to group them together and on the next step to swap the group with next candidate. + + If _inductor.config_comms.sink_iterative_use_runtime_estimations is set True, + pass will stop reordering of Wait once corresponding Collective is unexposed, + based on runtime estimations. + + inductor.config_comms.sink_iterative_peak_memory_budget allows to tune how much pass + can regress initial peak memory. + E.g.: + sink_iterative_peak_memory_budget == 0.0 - No regression of initial peak memory is allowed + sink_iterative_peak_memory_budget == 0.2 - Pass can improve comm-compute overlap, sacrificing + 20% of initial peak memory value. + + inductor.config_comms.sink_iterative_extra_comm_comp_overlap config allows to more aggressively + sink waits, stopping only when overlap_compute >= (1 + extra_comm_comp_overlap) * comm_time + """ + return _sink_waits_iterative_internal(snodes)[0] + + +def estimate_op_runtime(snode: BaseSchedulerNode) -> float: + """ + Returns estimated op runtime in milliseconds (ms) + """ + if config.estimate_op_runtime == "default": + runtime = snode.get_estimated_runtime() + else: + if not callable(config.estimate_op_runtime): + raise AssertionError("expected config.estimate_op_runtime to be callable") + runtime = config.estimate_op_runtime(snode) + return runtime + + +def node_summary(snode): + snodes = snode.get_nodes() + if len(snodes) == 1: + detail = "" + if isinstance(snode.node, (ir.ExternKernelOut, ir._CollectiveKernel)): + outs_str = f"outs:{[o.get_name() for o in snode.get_outputs()]}" + ins_str = f"ins:{[d.name for d in snode.unmet_dependencies]}" + detail = f" {snode.get_name()} ({snode.node.python_kernel_name})\n {outs_str}({ins_str})" + layouts = [child.node.get_output_spec() for child in snode.get_nodes()] + out_tensor_info = ",".join( + [ + f" (size={layout.size}, stride={layout.stride})" + if isinstance(layout, ir.Layout) + else "" + for layout in layouts + ] + ) + try: + node_name = snode.node.maybe_get_name() + except AttributeError: + # TODO: node_summary was written without FusedSchedulerNode in mind, generally needs to be hardened + node_name = "" + return f"{snode.node.__class__.__name__}{detail}{out_tensor_info} ({node_name} ({snode.get_estimated_runtime():.0f} ns)" + + # Flatten the summaries for Fused/Foreach/Grouped nodes + summaries = [] + for child_snode in snodes: + summaries.append(node_summary(child_snode)) + return f"{snode.__class__.__name__}: {', '.join(summaries)}" + + +def visualize_overlap(order): + # TODO - this function probably doesn't do a very good job estimating the runtime because it doesn't carefully model + # streams and overlap. For now its mostly useful as a debug visualization. + + total_est_runtime: float = 0.0 + cur_comm_node = None + + def step_log(step, msg): + overlap_log.debug(f"{step:>6}: {msg}") + + for step, snode in enumerate(order): + if cur_comm_node is None: + if contains_collective(snode): + total_est_runtime += estimate_op_runtime(snode) + cur_comm_node = snode.node + elif is_wait(snode.node): + # raise AssertionError( + # "Wait is not expected when there is no collective running" + # ) + pass + else: # exposed compute op + total_est_runtime += estimate_op_runtime(snode) + step_log(step, f"{node_summary(snode)}") + else: # cur_comm_node is not None + if contains_collective(snode): + total_est_runtime += estimate_op_runtime(snode) + cur_comm_node = snode.node + step_log(step, f"{node_summary(snode)}") + elif is_wait(snode.node): # end of this comm op + step_log(step, f"{node_summary(snode)}") + cur_comm_node = None + else: # overlapped compute op + step_log(step, f"| {node_summary(snode)}") + overlap_log.debug(f"Est. runtime (ms): {total_est_runtime / 1000 / 1000}") + + +def simple_overlap(snodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]: + """Move collectives earlier and waits later via adjacent swaps. + Each swap is safe: no collective reordering, no memory regression.""" + if len(snodes) < 2: + return snodes + + collectives = [s for s in snodes if contains_async_collective(s)] + waits = [s for s in snodes if contains_wait(s)] + if not collectives and not waits: + return snodes + + outputs_of: dict[BaseSchedulerNode, frozenset[str]] = { + s: frozenset(o.get_name() for o in s.get_outputs()) for s in snodes + } + # Fake WeakDeps encode ordering-only constraints, such as collective order. + deps_of: dict[BaseSchedulerNode, frozenset[str]] = { + s: frozenset(d.name for d in s.unmet_dependencies) for s in snodes + } + + _prev, _next, _head = _initialize_double_linked_list(snodes) + ( + peak_memory, + _curr_memory, + snodes_allocfree, + _buf_last_use, + _freeable, + _cand_buf_map, + ) = _initialize_memory_tracking(snodes) + + n_moved_colls = 0 + n_moved_waits = 0 + + def peak_memory_safe_swap( + candidate: BaseSchedulerNode, + group_node: BaseSchedulerNode, + *, + sink_wait: bool, + ) -> bool: + nonlocal _head + + group_nodes = [group_node] + candidate_af = snodes_allocfree[candidate] + candidate_delta = candidate_af.size_alloc - candidate_af.size_free + size_free_cache: dict[BaseSchedulerNode, int] = {} + + if sink_wait: + changed_bufs = _find_buffers_with_changed_last_use_sink_waits( + candidate, group_nodes, _buf_last_use, _cand_buf_map + ) + potential_peak, post_alloc_cache, size_free_cache = ( + _calculate_potential_peak_memory_sink_waits( + candidate, + group_nodes, + group_node, + _curr_memory[group_node][0], + candidate_delta, + candidate_af, + changed_bufs, + _curr_memory, + snodes_allocfree, + ) + ) + else: + changed_bufs = _find_buffers_with_changed_last_use( + candidate, group_nodes, _buf_last_use, _cand_buf_map + ) + potential_peak, post_alloc_cache = _calculate_potential_peak_memory_reorder( + candidate, + group_nodes, + group_node, + _curr_memory[group_node][0], + candidate_delta, + candidate_af, + changed_bufs, + _curr_memory, + ) + + if potential_peak > peak_memory: + return False + + if sink_wait: + _head = _perform_double_linked_list_swap_sink_waits( + candidate, group_node, group_node, _prev, _next, _head + ) + _update_memory_tracking_after_swap_sink_waits( + candidate, + group_nodes, + candidate_delta, + candidate_af, + changed_bufs, + post_alloc_cache, + size_free_cache, + _curr_memory, + snodes_allocfree, + ) + else: + _head = _perform_double_linked_list_swap( + candidate, group_node, group_node, _prev, _next, _head + ) + _update_memory_tracking_after_swap_reorder( + candidate, + group_nodes, + group_node, + candidate_delta, + candidate_af, + changed_bufs, + post_alloc_cache, + _curr_memory, + _buf_last_use, + snodes_allocfree, + ) + + return True + + # Phase 1: move each collective earlier via adjacent swaps + # Swap [pred, coll] -> [coll, pred]: pred is the "candidate" (moves later) + for coll in collectives: + coll_deps = deps_of[coll] + moved = False + + pred = _prev[coll] + while pred is not None: + if outputs_of[pred] & coll_deps: + break + if contains_async_collective(pred): + break + if not peak_memory_safe_swap(pred, coll, sink_wait=False): + break + + moved = True + pred = _prev[coll] + + if moved: + n_moved_colls += 1 + + # Phase 2: move each wait later via adjacent swaps + # Swap [wait, succ] -> [succ, wait]: succ is the "candidate" (moves earlier) + for wait in reversed(waits): + wait_outs = outputs_of[wait] + moved = False + + succ = _next[wait] + while succ is not None: + if deps_of[succ] & wait_outs: + break + if contains_wait(succ): + break + if not peak_memory_safe_swap(succ, wait, sink_wait=True): + break + + moved = True + succ = _next[wait] + + if moved: + n_moved_waits += 1 + + if n_moved_colls or n_moved_waits: + log.info( + "simple_overlap: moved %d collectives, %d waits (peak %d MB)", + n_moved_colls, + n_moved_waits, + peak_memory // (1024 * 1024), + ) + + return _group_nodes_from_linked_list(_head, None, _next) + + +def reorder_compute_and_comm_for_overlap( + snodes: list[BaseSchedulerNode], +) -> list[BaseSchedulerNode]: + order = snodes + # pyrefly: ignore [bad-assignment] + for p in config.reorder_for_compute_comm_overlap_passes: + if isinstance(p, str) and p in globals(): + p = globals()[p] # it is a builtin pass + if not callable(p): + raise AssertionError( + f"Invalid reorder_compute_and_comm_for_overlap pass: {p} is not callable" + ) + order = p(order) # type: ignore[operator] + # pyrefly: ignore [bad-return] + return order diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/comms_debug.py b/.venv/lib/python3.12/site-packages/torch/_inductor/comms_debug.py new file mode 100644 index 0000000000000000000000000000000000000000..f40df1a2436fd68d70727180c00526f0a26c42b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/comms_debug.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from torch._logging import trace_structured + +from .memory import estimate_peak_memory_allocfree + + +if TYPE_CHECKING: + from torch.utils._ordered_set import OrderedSet + + from .memory import FreeableInputBuffer, SNodeMemory + from .scheduler import BaseSchedulerNode, SchedulerBuffer + + +def _debug_iterative_memory_recompute( + candidate: BaseSchedulerNode, + gns: list[BaseSchedulerNode], + group_names: str, + snodes: list[BaseSchedulerNode], + name_to_freeable_input_buf: dict[str, FreeableInputBuffer], + graph_outputs: OrderedSet[str], + peak_memory: int, + iter_curr_memory: dict[BaseSchedulerNode, tuple[int, int]], + snodes_allocfree: dict[BaseSchedulerNode, SNodeMemory], + tlparse_name: str, + gn_to_bufs_last_use: dict[ + BaseSchedulerNode, list[FreeableInputBuffer | SchedulerBuffer] + ], +) -> bool: + iterative_recompute_error = False + candidate_allocfree = snodes_allocfree[candidate] + est_peak_memory, snodes_curr_memory, snodes_allocfree, _ = ( + estimate_peak_memory_allocfree( + snodes, name_to_freeable_input_buf, graph_outputs + ) + ) + est_curr_memory = dict(zip(snodes, snodes_curr_memory)) + iter_cm = iter_curr_memory[candidate] + new_cm = est_curr_memory[candidate] + log = "" + if est_peak_memory > peak_memory: + log = "ITERATIVE PEAK DOES NOT MATCH" + iterative_recompute_error = True + if iter_cm != new_cm: + log = "ITERATIVE CURR MEMORY CANDIDATE DOES NOT MATCH" + iterative_recompute_error = True + for gn in gns: + iter_gnm = iter_curr_memory[gn] + new_gnm = est_curr_memory[gn] + if iter_gnm != new_gnm: + log = f"ITERATIVE GN CURR MEMORY DOES NOT MATCH:{gn.get_name()}" + iterative_recompute_error = True + if iterative_recompute_error: + log += ( + f"\nCANDIDATE:{candidate.get_name()}" + f"\nGROUP:{group_names}" + f"\nPEAK_MEMORY_BEFORE:{peak_memory}" + f"\nPEAK_MEMORY_AFTER_SWAP:{est_peak_memory}" + f"\nCANDIDATE:{candidate.debug_str()}" + f"\nCANDIDATE_ITER_CURR_MEMORY:{iter_cm}" + f"\nCANDIDATE_NEW__CURR_MEMORY:{new_cm}" + f"\nCANDIDATE_ITER_ALLOCFREE:{candidate_allocfree}" + f"\nCANDIDATE_NEW_ALLOCFREE:{snodes_allocfree[candidate]}" + ) + peak_log = "" + for i, (pre, _post) in enumerate(snodes_curr_memory): + if est_peak_memory == pre: + n = snodes[i] + peak_log = ( + f"\nNEW_PEAK:{est_peak_memory}(BASE:{peak_memory})" + f" @ SNODE[{i}/{len(snodes)}]:{n.get_name()} {n.debug_str()}" + ) + break + group_log = "" + for i, gn in enumerate(gns): + iter_gnm = iter_curr_memory[gn] + new_gnm = est_curr_memory[gn] + group_log += ( + f"\nGROUP_NODE[{i}]:{gn.debug_str()}" + f"\nGROUP_NODE[{i}] ITER_GNM[{gn.get_name()}]:{iter_gnm}" + f"\nGROUP_NODE[{i}] ESTM_GNM[{gn.get_name()}]:{new_gnm}" + f"\nGROUP_NODE[{i}] ITER_allocfree:{snodes_allocfree[gn]}" + f"\nGROUP_NODE[{i}] ESTM_allocfree:{snodes_allocfree[gn]}" + ) + log += peak_log + log += group_log + log += f"\nGN_TO_BUFS_LAST_USE:{gn_to_bufs_last_use}" + log += "\n\n".join( + [ + ( + f"\nSNODE[{i}]\n{n.debug_str()}" + f"\nITER_cur_mem:{iter_curr_memory[n]}" + f"\nESTM_cur_mem:{est_curr_memory[n]}" + f"\nITER_allocfree:{snodes_allocfree[n]}" + f"\nESTM_allocfree:{snodes_allocfree[n]}" + ) + for i, n in enumerate(snodes) + ] + ) + tname = f"{tlparse_name}_ITERATIVE_RECOMPUTE_ERROR" + print(f"{tname}:\n{log}") + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": tname, + "encoding": "string", + }, + payload_fn=lambda: log, + ) + return iterative_recompute_error diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx.py b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx.py new file mode 100644 index 0000000000000000000000000000000000000000..e098e7e05f594e78a02f5cca43a9500bad8674a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx.py @@ -0,0 +1,3578 @@ +from __future__ import annotations + +import contextlib +import copy +import enum +import functools +import io +import itertools +import json +import logging +import os +import sys +import threading +import time +import warnings +from abc import ABC, abstractmethod +from collections import defaultdict +from contextlib import AbstractContextManager +from dataclasses import dataclass +from inspect import currentframe +from itertools import count +from operator import attrgetter +from typing import Any, Generic, TYPE_CHECKING, TypeVar +from typing_extensions import Never, override, ParamSpec, Protocol, TypedDict, Unpack +from unittest import mock + +import torch._inductor.async_compile +import torch.fx +import torch.utils._pytree as pytree +from functorch.compile import min_cut_rematerialization_partition +from torch import fx +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo import ( + compiled_autograd, + config as dynamo_config, + logging as dynamo_logging, + utils as dynamo_utils, +) +from torch._dynamo.backends import common as dynamo_common +from torch._dynamo.device_interface import get_interface_for_device +from torch._dynamo.repro.after_aot import wrap_compiler_debug +from torch._dynamo.utils import ( + chromium_event_timed, + CompileEventLogger, + counters, + detect_fake_mode, + dynamo_timed, + flatten_graph_inputs, + get_inputs_devices, + get_metrics_context, + GmWrapper, + lazy_format_graph_code, + set_feature_use, +) +from torch._functorch import aot_autograd, config as functorch_config +from torch._functorch._aot_autograd.subclass_parametrization import ( + unwrap_tensor_subclass_parameters, +) +from torch._functorch.aot_autograd import ( + aot_export_module, + GraphOutputName, + make_boxed_func, + SerializableAOTDispatchCompiler, +) +from torch._inductor.codecache import code_hash, FxGraphCache, output_code_log +from torch._inductor.cudagraph_utils import ( + BoxedDeviceIndex, + cudagraph_trees_clone_live_user_visible_outputs, + cudagraphs_log, + format_default_skip_message, + log_cudagraph_skip_and_bump_counter, + PlaceholderInfo, +) +from torch._inductor.custom_graph_pass import CustomPartitionerFn +from torch._inductor.debug import ( + create_kernel_information_json, + create_mapping_pre_post_grad_nodes, + get_kernel_information_jsons, + save_args_for_compile_fx_inner, +) +from torch._inductor.output_code import ( + CompiledAOTI, + CompiledFxGraph, + CompiledFxGraphConstantsWithGm, + copy_strided_storage_, + get_expanded_dims, + index_expanded_dims, + OutputCode, +) +from torch._inductor.runtime.cache_dir_utils import cache_dir +from torch._inductor.utils import ( + BoxedBool, + count_tangents, + fresh_cache, + get_all_devices, + get_static_bw_input_idxs, + InputType, + is_gpu, + should_assume_input_aligned, + should_use_remote_fx_graph_cache, + tensor_is_aligned, +) +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class +from torch._logging import trace_structured +from torch._utils_internal import compile_time_strobelight_meta +from torch.fx import GraphModule +from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols, SymExprPrinter +from torch.fx.passes.fake_tensor_prop import FakeTensorProp +from torch.monitor import _WaitCounter +from torch.utils._ordered_set import OrderedSet + +from .._dynamo.exc import ShortenTraceback, SkipFrame +from ..fx._lazy_graph_module import _use_lazy_graph_module +from ..fx.graph import _PyTreeCodeGen +from ..utils._triton import has_triton +from . import config, distributed_autotune, metrics +from .codegen.common import get_wrapper_codegen_for_device, init_backend_registration +from .debug import DebugContext +from .decomposition import select_decomp_table +from .exc import InductorError +from .fx_passes.joint_graph import joint_graph_passes +from .fx_passes.post_grad import post_grad_passes, view_to_reshape +from .fx_passes.pre_grad import pre_grad_passes +from .graph import GraphLowering +from .ir import get_device_type, IRNode +from .triton_bundler import TritonBundler +from .utils import ( + align_inputs_from_check_idxs, + clone_preserve_strides, + copy_misaligned_inputs, + get_cloned_parameter_buffer_name, + get_first_incompatible_cudagraph_node, + maybe_get_suppress_shape_guards_ctx, + output_node, + remove_unaligned_input_idxs, + shape_env_from_inputs, +) +from .virtualized import V + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, Sequence + + from torch._inductor.output_code import _StrideExprStr, CompiledFnRunner + from torch._ops import OpOverload + from torch.export.pt2_archive._package_weights import Weights + + from .codecache import CacheInfo + from .ir import ExternKernelNode + + +_P = ParamSpec("_P") +_T = TypeVar("_T") + +if TYPE_CHECKING or not config.is_fbcode(): + # no-op decorator + def time_and_log(attr: str) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + return dynamo_utils.identity + + def log_optimus_to_scuba(*args: object, **kwargs: object) -> None: + pass + +else: + from torch._inductor.fb.utils import log_optimus_to_scuba, time_and_log + +if TYPE_CHECKING: + from torch._functorch._aot_autograd.schemas import ( + FQN, + GraphInputName, + GraphSignature, + ) + + CompileFxOutput = ( + Callable[[list[object]], Sequence[torch.Tensor]] | str | list[str] | Weights + ) + + +class FxCompileMode(enum.Enum): + NORMAL = 0 + # For testing - use the serde FxCompile scheme to debug serialization and + # deserialization of GraphModule and CompiledFxGraph. + SERIALIZE = 1 + # Compile using a subprocess instead of in-process. + SUBPROCESS = 2 + + +@dataclass +class FxCompileConfig: + mode: FxCompileMode + use_async: bool + use_progressive: bool + + +def _fx_compile_mode_default() -> FxCompileConfig: + name = "TORCHINDUCTOR_FX_COMPILE_MODE" + value = os.environ.get(name) + if value is None: + return FxCompileConfig(FxCompileMode.NORMAL, False, False) + + use_async = False + use_progressive = False + + if value.lower().startswith("progressive+"): + use_progressive = True + value = value[12:] + if value.lower().startswith("async+"): + use_async = True + value = value[6:] + + try: + value = value.upper() + return FxCompileConfig(FxCompileMode[value], use_async, use_progressive) + except KeyError: + import logging + + log = logging.getLogger(__name__) + log.error( + "Invalid value of %s for %s. Expected one of %s. Using default.", + value, + name, + ", ".join(sorted(repr(x) for x in FxCompileMode.__members__)), + ) + # Remove from the environment so subprocesses don't ALSO complain. + os.environ.pop(name) + return FxCompileConfig(FxCompileMode.NORMAL, False, False) + + +def _get_progression_configs() -> list[dict[str, Any]]: + # TODO make this configurable + return [ + {"max_autotune": True}, + ] + + +_fx_compile_config = _fx_compile_mode_default() +fx_compile_mode = _fx_compile_config.mode +fx_compile_async = _fx_compile_config.use_async +fx_compile_progressive = _fx_compile_config.use_progressive + +log = logging.getLogger(__name__) +perf_hint_log = torch._logging.getArtifactLogger(__name__, "perf_hints") +pre_grad_graphs_log = torch._logging.getArtifactLogger(__name__, "pre_grad_graphs") +post_grad_graphs_log = torch._logging.getArtifactLogger(__name__, "post_grad_graphs") +static_inputs_log = torch._logging.getArtifactLogger( + __name__, "cudagraph_static_inputs" +) +inductor_metrics_log = torch._logging.getArtifactLogger(__name__, "inductor_metrics") + + +def get_static_input_idxs(num_fixed: int) -> list[int]: + # If we are inlining NNModules, we treat all torch.nn.Parameters as static for the purposes + # of cudagraphs. Rather than copying these into cudagraph-owned memory + # like we do for normal inputs on each run, we will re-record a cudagraph if these + # parameter locations change. + context = torch._guards.TracingContext.try_get() + fixed = list(range(num_fixed)) + if not context or not context.fw_metadata: + return fixed + + return context.fw_metadata.static_input_indices + + +def record_original_output_strides(gm: GraphModule) -> None: + output_node = gm.graph.find_nodes(op="output")[0] + + # Don't overwrite strides that were already recorded (e.g., before + # joint_graph_passes which can introduce padded strides via pad_mm). + if "original_output_strides" in output_node.meta: + return + + output_strides = [] + + if not isinstance(output_node.args[0], torch.fx.Node): + output_node_args = output_node.args[0] + else: + output_node_args = output_node.args + + for output in output_node_args: + if ( + isinstance(output, torch.fx.Node) + and (val := output.meta.get("val")) is not None + and isinstance(val, torch.Tensor) + ): + output_strides.append(val.stride()) + else: + # pyrefly: ignore [bad-argument-type] + output_strides.append(None) + output_node.meta["original_output_strides"] = output_strides + + +def _recursive_record_original_output_strides(gm: GraphModule) -> None: + # invoke_subgraph HOP requires output strides to be respected + for node in gm.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ): + subgraph = getattr(gm, node.args[0].target) + _recursive_record_original_output_strides(subgraph) + + record_original_output_strides(gm) + + +def _recursive_record_user_visible_output_idxs(gm: GraphModule) -> None: + # invoke_subgraph HOP requires output strides to be respected + for node in gm.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ): + subgraph = getattr(gm, node.args[0].target) + + for node in subgraph.graph.find_nodes(op="output"): + node.meta["user_visible_output_idxs"] = [ + idx + for idx in range(len(node.args[0])) + if isinstance(node.args[0][idx], torch.fx.Node) + ] + _recursive_record_user_visible_output_idxs(subgraph) + + +def _cudagraph_trees_clone_live_user_outputs() -> bool: + return cudagraph_trees_clone_live_user_visible_outputs() + + +@functools.lru_cache(None) +def _step_logger() -> Callable[..., None]: + return dynamo_logging.get_step_logger(log) + + +@functools.cache +def _warn_tf32_disabled() -> None: + if ( + torch.cuda.is_available() + and torch.backends.cuda.matmul.fp32_precision != "tf32" + and torch.cuda.get_device_capability() >= (8, 0) + ): + perf_hint_log.info( + "TensorFloat32 tensor cores for float32 matrix multiplication available but not enabled. " + "Consider setting `torch.set_float32_matmul_precision('high')` for better performance." + ) + + +def _resolve_name_collision(mod: GraphModule, gm: GraphModule) -> None: + """ + In aot_export_module (make_fx), we create get_attr nodes with name prefix + "_tensor_constant" and "_torchbind_obj". See Tracer.create_arg() in + torch/fx/_symbolic_trace.py + + However, this might result in name collision if the original mod already + has a different buffer with the same name. + + We resolve this potential name collision here by changing the target name + with a new number post fix. + """ + + existing_keys = OrderedSet( + [name for name, val in mod.named_parameters(remove_duplicate=False)] + ) + existing_keys.update( + OrderedSet([name for name, val in mod.named_buffers(remove_duplicate=False)]) + ) + + def find_smallest_i(graph: fx.Graph, prefix: str) -> int: + i = 0 + for node in graph.nodes: + if node.op == "get_attr" and node.target.startswith(prefix): + if len(node.target) > len(prefix): + post_fix = node.target.split(prefix)[-1] + if post_fix.isdigit(): + i = max(i, int(post_fix)) + for key in existing_keys: + if key.startswith(prefix): + if len(key) > len(prefix): + post_fix = key.split(prefix)[-1] + if post_fix.isdigit(): + i = max(i, int(post_fix)) + return i + 1 + + for node in gm.graph.nodes: + if node.op == "get_attr": + target_name = node.target + if not target_name.startswith( + "_tensor_constant" + ) and not target_name.startswith("_torchbind_obj"): + continue + + if not hasattr(mod, target_name): + continue + gm_target = attrgetter(target_name)(gm) + model_target = attrgetter(target_name)(mod) + if isinstance(gm_target, FakeScriptObject): + if ( + isinstance(model_target, FakeScriptObject) + and gm_target.real_obj is model_target.real_obj + ): + continue + elif ( + gm_target.device == model_target.device + and gm_target.dtype == model_target.dtype + and torch.equal(gm_target, model_target) + ): + # If tensors with same name from gm and model are indeed the same, we don't need to rename + # Check device first, to avoid torch.equal(wrapper_CUDA__equal) raise when different device + continue + + prefix = ( + "_tensor_constant" + if target_name.startswith("_tensor_constant") + else "_torchbind_obj" + ) + new_id = find_smallest_i(gm.graph, prefix) + new_target_name = f"{prefix}{new_id}" + node.target = new_target_name + setattr(gm, new_target_name, gm_target) + existing_keys.add(new_target_name) + + +def _unlift_graph( + mod: GraphModule, gm: GraphModule, graph_signature: GraphSignature +) -> GraphModule: + from torch.export.unflatten import _assign_attr, _AttrKind + + _resolve_name_collision(mod, gm) + + state_dict: dict[str, torch.nn.parameter.Parameter | torch.Tensor] = {} + for name, param in mod.named_parameters(remove_duplicate=False): + state_dict[name] = param + _assign_attr( + param, + gm, + name, + attr_kind=_AttrKind.PARAMETER, + ) + for name, buffer in mod.named_buffers(remove_duplicate=False): + state_dict[name] = buffer + _assign_attr( + buffer, + gm, + name, + attr_kind=_AttrKind.BUFFER, + ) + + placeholder_nodes = gm.graph.find_nodes(op="placeholder") + lifted_inputs: list[FQN | None] = [] + + # In AOTI, module parameters and buffers are not lifted as graph inputs. + # As a result, mutation to buffers has side effect which makes their initial + # values different from Eager. So we clone them here as a copy. + # We are not cloning for parameters, although it will be needed if we want to + # support training. + for node in placeholder_nodes: + node_name = node.name + if node_name in graph_signature.inputs_to_parameters: + parameter_name = graph_signature.inputs_to_parameters[node_name] + lifted_inputs.append(parameter_name) + elif node_name in graph_signature.inputs_to_buffers: + buffer_name = graph_signature.inputs_to_buffers[node_name] + lifted_inputs.append(buffer_name) + gm.meta[get_cloned_parameter_buffer_name(buffer_name)] = ( + clone_preserve_strides(state_dict[buffer_name]) + ) + else: + if node_name not in graph_signature.user_inputs: + raise AssertionError( + f"Expected {node_name} to be in graph_signature.user_inputs" + ) + lifted_inputs.append(None) + + from torch.export._unlift import _unlift + + outputs: tuple[torch.fx.Node, ...] = tuple(gm.graph.output_node().args[0]) # type: ignore[arg-type] + mutated_outputs = [] + buffer_mutations = graph_signature.buffers_to_mutate + user_input_mutations = graph_signature.user_inputs_to_mutate + output_tokens = graph_signature.output_tokens + for idx, out in enumerate(outputs): + value: FQN | GraphInputName | None = None + + if idx < len(buffer_mutations) + len(user_input_mutations) + len(output_tokens): + name = GraphOutputName(out.name) + if name in buffer_mutations: + value = buffer_mutations[name] + elif name in user_input_mutations: + value = user_input_mutations[name] + + mutated_outputs.append(value) + + unlifted_gm = _unlift( + gm, + lifted_inputs, + mutated_outputs, + pytree.treespec_leaf(), + None, + ) + # After unlifting, the buffer mutation information is lost. Pass the information + # so that Inductor can do optimizations correctly. + unlifted_gm.meta["mutated_named_buffers"] = OrderedSet(buffer_mutations.values()) + return unlifted_gm + + +def _get_subgraph_names( + gm: GraphModule, skip_invoke_subgraph: bool = False +) -> Generator[str, None, None]: + all_subgraph_names: OrderedSet[str] = OrderedSet( + x.target for x in gm.graph.find_nodes(op="get_attr") + ) + fx_subgraph_names: OrderedSet[str] = OrderedSet() + for child_name, child_module in gm.named_children(): + # Sometimes an owning_module can have unused children. Skip them + # by checking them from get_attr node targets. + if child_name in all_subgraph_names and isinstance( + child_module, torch.fx.GraphModule + ): + fx_subgraph_names.add(child_name) + + if skip_invoke_subgraph: + for node in gm.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ): + fx_subgraph_names.discard(node.args[0].target) + + yield from fx_subgraph_names + + +def _get_nested_region_inductor_config_patches( + gm: GraphModule, +) -> dict[str, Any] | None: + nested_config = getattr(gm, "meta", {}).get("nested_region_config") + patches = getattr(nested_config, "inductor_config_patches", None) + return patches or None + + +def _patch_nested_region_inductor_config( + gm: GraphModule, +) -> AbstractContextManager[None]: + patches = _get_nested_region_inductor_config_patches(gm) + if patches is None: + return contextlib.nullcontext() + return config.patch(patches) + + +def _propagate_invoke_subgraph_nested_region_config(gm: GraphModule) -> None: + # Seed each invoke_subgraph subgraph module's meta from the node meta, which + # (unlike a GraphModule's meta) survives FX transforms. Re-run at the start of + # every pass phase because each is an independent entry point that may see a + # freshly-created module (e.g. the partitioned backward graph); setdefault + # makes re-entry on an already-seeded module a no-op. + for node in gm.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ): + nested_config = node.meta.get("custom", {}).get("nested_region_config") + if nested_config is None: + continue + subgraph_node = node.args[0] + if ( + not isinstance(subgraph_node, torch.fx.Node) + or subgraph_node.op != "get_attr" + or not isinstance(subgraph_node.target, str) + ): + continue + subgraph = getattr(gm, subgraph_node.target, None) + if isinstance(subgraph, GraphModule): + subgraph.meta.setdefault("nested_region_config", nested_config) + + +def _recursive_pre_grad_passes( + gm: GraphModule, + example_inputs: Sequence[InputType], +) -> GraphModule: + with dynamo_timed( + "_recursive_pre_grad_passes", + log_pt2_compile_event=True, + dynamo_compile_column_us="pre_grad_pass_time_us", + ): + _propagate_invoke_subgraph_nested_region_config(gm) + with _patch_nested_region_inductor_config(gm): + if not config.use_pre_grad_passes: + return gm + + add_passes = config.add_pre_grad_passes + remove_passes = config.remove_pre_grad_passes + for subgraph_name in _get_subgraph_names(gm): + subgraph = getattr(gm, subgraph_name) + # as we don't have recursive example inputs, passing empty set here + new_subgraph = _recursive_pre_grad_passes(subgraph, ()) + setattr(gm, subgraph_name, new_subgraph) + return pre_grad_passes(gm, example_inputs, add_passes, remove_passes) + + +def _recursive_joint_graph_passes( + gm: GraphModule, + skip_invoke_subgraph: bool = False, + input_device: torch.device | None = None, +) -> GraphModule: + def _run_on_sub_graph_module(subgraph_name: str) -> None: + subgraph = getattr(gm, subgraph_name) + new_subgraph = _recursive_joint_graph_passes( + subgraph, skip_invoke_subgraph, input_device + ) + setattr(gm, subgraph_name, new_subgraph) + + with dynamo_timed( + "_recursive_joint_graph_passes", + log_pt2_compile_event=True, + dynamo_compile_column_us="joint_graph_pass_time_us", + ): + _propagate_invoke_subgraph_nested_region_config(gm) + with _patch_nested_region_inductor_config(gm): + if not config.use_joint_graph_passes: + return gm + + # invoke_subgraph already runs the _recursive_joint_graph_passes. In + # AOTAutograd, `run_joint_graph_passes_on_hops` partitions the + # invoke_subgraph HOP before calling the partitioner on the outer graph. + # AOTAutograd has access to partition_fn, which internally calls the + # `_recursive_joint_graph_passes` for the subgraph. So, skip recursing + # skip_invoke_subgraph. + old_subgraph_names = OrderedSet( + _get_subgraph_names(gm, skip_invoke_subgraph) + ) + for subgraph_name in old_subgraph_names: + _run_on_sub_graph_module(subgraph_name) + + out_gm = joint_graph_passes(gm, input_device) + + # Some joint graph passes may create new sub graph module. Run one round + # for the newly created graph modules. + # We should not skip graphs for invoke_subgraph HOPs for newly + # generated subgraphs. + for subgraph_name in _get_subgraph_names( + out_gm, skip_invoke_subgraph=False + ): + if subgraph_name not in old_subgraph_names: + _run_on_sub_graph_module(subgraph_name) + return out_gm + + +def _recursive_post_grad_passes(gm: GraphModule, is_inference: bool = False) -> None: + with dynamo_timed( + "_recursive_post_grad_passes", + log_pt2_compile_event=True, + dynamo_compile_column_us="post_grad_pass_time_us", + ): + _propagate_invoke_subgraph_nested_region_config(gm) + with _patch_nested_region_inductor_config(gm): + if not config.use_post_grad_passes: + return + + for subgraph_name in _get_subgraph_names(gm): + subgraph = getattr(gm, subgraph_name) + _recursive_post_grad_passes(subgraph, is_inference) + post_grad_passes(gm, is_inference) + + +def split_const_gm( + gm: GraphModule, + skip_constructor: bool = True, + lifted_constant_names: list[str] | None = None, + skip_folding_node_fn: Callable[[torch.fx.Node], bool] | None = None, +) -> tuple[GraphModule, dict[str, int]]: + """ + This function takes an GraphModule input "gm". + The gm will be split into 2 components, + 1) const_gm, which consists the subgraph of gm that can be constant folded. + 2) gm (being inplace modified,) which returns the graph after constant folding. + + If an additional "lifted_constants" argument is passed in, we will assume the gm has + been lifted and run the transformation accordingly. + + When a "skip_folding_node_fn" callback is passed, we will skip constant folding on + the nodes for which the callback returns True. + + const_output_index is a mapping of corresponding node name from gm to the + output index of const_gm. + Returns (const_gm, const_output_index) + """ + from torch._inductor.constant_folding import ( + CONST_MODULE_TAG, + META_TAG, + MODULE_TAG, + replace_node_with_constant, + run_and_get_constant_graph, + ) + + const_gm = run_and_get_constant_graph( + gm, skip_constructor, lifted_constant_names, skip_folding_node_fn + ) + const_result = const_gm() if lifted_constant_names is None else None + + const_outputs = { + x.name: idx for idx, x in enumerate(tuple(const_gm.graph.nodes)[-1].args[0]) + } + + to_erase_node = [] + to_replace_node = [] + const_output_index = {} + for node in gm.graph.nodes: + if node.name in const_outputs: + to_replace_node.append(node) + elif node.meta[META_TAG] == CONST_MODULE_TAG and node.op != "placeholder": + to_erase_node.append(node) + + for node in to_replace_node: + new_const_name = "_FOLDED_CONST_" + node.name + replace_node_with_constant( + gm, + node, + ( + const_result[const_outputs[node.name]] # type:ignore[index] + if lifted_constant_names is None + else None + ), + new_const_name, + ) + const_output_index[new_const_name] = const_outputs[node.name] + for node in to_erase_node[::-1]: + if node.users: + for n in node.users: + if n.meta[META_TAG] != MODULE_TAG: + raise AssertionError(f"node: {node} user not empty.") + else: + gm.graph.erase_node(node) + gm.recompile() + + return const_gm, const_output_index + + +def is_tf32_warning_applicable(gm: GraphModule) -> bool: + aten = torch.ops.aten + tf32_ops = OrderedSet( + [ + aten.mm.default, + aten.addmm.default, + aten.bmm.default, + aten.baddbmm.default, + ] + ) + for target in tf32_ops: + for node in gm.graph.find_nodes(op="call_function", target=target): + if ( + isinstance(node.meta.get("val", None), torch.Tensor) + and node.meta["val"].dtype == torch.float32 + and node.meta["val"].device.type == "cuda" + ): + return True + return False + + +def maybe_disable_comprehensive_padding( + example_inputs: Sequence[InputType], +) -> AbstractContextManager[None, None]: + """ + For CPU backend, enable comprehensive padding causes some unit tests + fail due to changing number of generated kernels. Skip for now. + """ + has_gpu = any( + is_gpu(t.device.type) for t in example_inputs if isinstance(t, torch.Tensor) + ) + + if config.disable_padding_cpu and config.comprehensive_padding and not has_gpu: + perf_hint_log.info("Skip comprehensive padding on CPU") + return config.patch(comprehensive_padding=False) + elif config.aot_inductor.use_runtime_constant_folding: + perf_hint_log.info( + "Skip comprehensive padding for use_runtime_constant_folding" + ) + return config.patch(comprehensive_padding=False) + else: + return contextlib.nullcontext() + + +def maybe_disable_graph_partition( + cpp_wrapper: bool, aot_mode: bool +) -> AbstractContextManager[None, None]: + """ + graph partition does not support cpp_wrapper and aot_mode yet. + """ + if cpp_wrapper or aot_mode: + return config.patch(graph_partition=False) + else: + return contextlib.nullcontext() + + +def fake_tensor_prop( + gm: GraphModule, + example_inputs: Sequence[InputType], + force_allow_non_fake_inputs: bool = False, +) -> torch._subclasses.FakeTensorMode: + """ + If we can not detect fake mode from the context of inputs, create one. + + The created fake mode will be returned. + """ + # Ensure that decomps that support symbolic shapes are used + with enable_python_dispatcher(): + fake_mode = detect_fake_mode(example_inputs) + if not fake_mode: + fake_mode = torch._subclasses.FakeTensorMode(allow_non_fake_inputs=True) + FakeTensorProp(gm, mode=fake_mode).propagate(*example_inputs) + else: + ctx = ( + contextlib.nullcontext() + if not force_allow_non_fake_inputs + else mock.patch.object(fake_mode, "allow_non_fake_inputs", True) + ) + with ctx: # type: ignore[attr-defined] + FakeTensorProp(gm, mode=fake_mode).propagate_dont_convert_inputs( + *example_inputs + ) + + return fake_mode + + +# pass config dict back to user +def get_patched_config_dict( + config_patches: str | dict[str, Any] | None = None, +) -> dict[str, Any]: + with config.patch(config_patches): + return config.get_config_copy() + + +@contextlib.contextmanager +def with_fresh_cache_if_config() -> Generator[None, None, None]: + if config.force_disable_caches: + # Don't delete the cache dir because it has to survive beyond the + # compile_fx call. Let's put the temp dirs under the default cache + # dir so they're easier to locate. + with fresh_cache(dir=cache_dir(), delete=False): + yield + else: + yield + + +class _CompileFxKwargs(TypedDict, total=False): + cudagraphs: BoxedBool | None + static_input_idxs: Sequence[int] + is_backward: bool + graph_id: int | None + cpp_wrapper: bool + aot_mode: bool + is_inference: bool + layout_opt: bool | None + extern_node_serializer: Callable[[list[ExternKernelNode]], Any] | None + boxed_forward_device_index: BoxedDeviceIndex | None + fx_wrapper: bool + get_decomp_fn: Callable[..., dict[Any, Callable[..., Any]]] + + +class _CompileFxCallable(Protocol): + def __call__( + self, + gm: GraphModule, + example_inputs: Sequence[InputType], + compile_region_name: str | None = None, + **kwargs: Unpack[_CompileFxKwargs], + ) -> OutputCode: ... + + +def compile_fx_inner( + gm: GraphModule, + example_inputs: Sequence[InputType], + compile_region_name: str | None = None, + **kwargs: Unpack[_CompileFxKwargs], +) -> OutputCode: + kwargs.setdefault("cudagraphs", None) + kwargs.setdefault("static_input_idxs", ()) + kwargs.setdefault("is_backward", False) + kwargs.setdefault("graph_id", None) + kwargs.setdefault("cpp_wrapper", False) + kwargs.setdefault("fx_wrapper", False) + kwargs.setdefault("is_inference", False) + kwargs.setdefault("boxed_forward_device_index", None) + kwargs.setdefault("layout_opt", None) + kwargs.setdefault("extern_node_serializer", None) + + # Need with_fresh_cache_if_config for compile_fx_inner even if we already have one for + # compile_fx. The reason is the compilation for backward graph may happen after + # compile_fx return and we may want to use the _LazyGraphModule for compiling + # the backward graph as well. + with contextlib.ExitStack() as stack: + # When cpp_wrapper is enabled, ensure the required triton config + # (store_cubin, autotune_at_compile_time, etc.) is applied. This is + # needed because lazy backward compilation may run after the + # config.patch context from compile_fx has already exited. + # Suppress cudagraph skip logging here; compile_fx already logged it. + if kwargs["cpp_wrapper"]: + stack.enter_context( + config.patch(get_cpp_wrapper_config(log_cudagraph_skip=False)) + ) + # Host-side TMA only selects the descriptor flavor; it needs the TMA path + # itself enabled. Warn (don't silently no-op) if it's set without its + # prerequisites. + if config.triton.enable_host_side_tma and not ( + config.triton.use_tensor_descriptor and config.assume_aligned_inputs + ): + warnings.warn( + "config.triton.enable_host_side_tma has no effect unless both " + "config.triton.use_tensor_descriptor and " + "config.assume_aligned_inputs are also enabled; host-side TMA " + "will be skipped.", + stacklevel=2, + ) + stack.enter_context(torch.utils._python_dispatch._disable_current_modes()) + stack.enter_context(_use_lazy_graph_module(dynamo_config.use_lazy_graph_module)) + stack.enter_context( + dynamo_utils.dynamo_timed( + "compile_fx_inner", + phase_name="inductor_compile", + log_pt2_compile_event=True, + log_waitcounter=True, + waitcounter_name_override="compile_inductor", + dynamo_compile_column_us="inductor_cumulative_compile_time_us", + ) + ) + stack.enter_context(with_fresh_cache_if_config()) + stack.enter_context(DebugContext()) + CompileEventLogger.pt2_compile( + "inductor_compile", + is_backward=kwargs["is_backward"], + ) + compiled_graph = wrap_compiler_debug( + _compile_fx_inner, compiler_name="inductor" + )( + gm, + example_inputs, + compile_region_name=compile_region_name, + **kwargs, + ) + if config.trace.provenance_tracking_to_timeline: + compile_id = torch._guards.CompileContext.current_compile_id() + kernel_information_jsons = get_kernel_information_jsons() + key = str((f"Torch-Compiled Region: {compile_id}", kwargs["is_backward"])) + if key not in kernel_information_jsons: + kernel_information_jsons[key] = create_kernel_information_json() + return compiled_graph + + +@time_and_log(attr="compilation time (in seconds)") +def _compile_fx_inner( + gm: GraphModule, + example_inputs: Sequence[InputType], + compile_region_name: str | None = None, + **graph_kwargs: Unpack[_CompileFxKwargs], +) -> OutputCode: + """ + Inductor API that compiles a single graph. + + If you change the argument list for this function, make sure you + also update the call to save_args_for_compile_fx_inner below accordingly. + """ + aot_mode: bool = V.aot_compilation + + from torch._inductor.autotune_process import use_pipelined_autotuning + + if use_pipelined_autotuning(): + # Warm up max-autotune process pool asap + from torch._inductor.autotune_process import AutotuneProcessPool + + pool_instance = AutotuneProcessPool.get_instance() + pool_instance.warm_up() + + # Clean up Compiled Triton Kernels per inductor compile, as the future objects + # may not be valid for use after they are run/autotuned + torch._inductor.async_compile.CompiledTritonKernels.cache_clear() + + if ( + dynamo_utils.count_calls(gm.graph) == 0 + and not aot_mode + and not torch._functorch.config.bundled_autograd_cache + ): + # trigger the real recompilation for _LazyGraphModule before returning + # the forward method. + from torch._dynamo.utils import CompileEventLogLevel + from torch.fx._lazy_graph_module import _LazyGraphModule + + _LazyGraphModule.force_recompile(gm) + compile_id = torch._guards.CompileContext.current_compile_id() + CompileEventLogger.log_instant_event( + "backward no-op", + metadata={"compile_id": compile_id}, + log_level=CompileEventLogLevel.PT2_COMPILE, + ) + + # pyrefly: ignore[bad-return] + return make_boxed_func(gm.forward) + + static_input_idxs: Sequence[int] = graph_kwargs.setdefault("static_input_idxs", ()) + static_inputs_log.debug("static input idxs compile_fx_inner: %s", static_input_idxs) + inputs_to_check = get_input_idxs_to_check(example_inputs, static_input_idxs) + + if not isinstance(next(iter(reversed(gm.graph.nodes))).args[0], (tuple, list)): + raise AssertionError( + f"inductor can only compile FX graphs which return a tuple/list, but got {gm.graph}" + ) + + _propagate_invoke_subgraph_nested_region_config(gm) + + if graph_kwargs.get("cudagraphs") is None: + graph_kwargs["cudagraphs"] = BoxedBool(config.triton.cudagraphs) + if config.save_args: + save_args_for_compile_fx_inner( + gm, + example_inputs, + compile_region_name=compile_region_name, + **graph_kwargs, + ) + + start = time.time() + + fx_graph_remote_cache = should_use_remote_fx_graph_cache() + + # Check if the registered backend(s) support caching. + init_backend_registration() + backends_support_caching = all( + backend.supports_caching + for backend in ( + get_wrapper_codegen_for_device( + device.type, config.cpp_wrapper, config.fx_wrapper + ) + for device in get_all_devices(gm) + ) + if backend is not None + ) + + with dynamo_timed( + "fx_codegen_and_compile", log_pt2_compile_event=True, log_waitcounter=True + ): + use_cache = ( + not config.force_disable_caches + and (config.fx_graph_cache or fx_graph_remote_cache) + and not aot_mode + and backends_support_caching + and not torch._functorch.config.bundled_autograd_cache + ) + local = config.fx_graph_cache + remote = fx_graph_remote_cache + set_feature_use("fx_cache", use_cache) + + log.debug( + "FX cache status: use_cache=%s, local=%s, remote=%s, aot_mode=%s, force_disable_caches=%s", + use_cache, + local, + remote, + aot_mode, + config.force_disable_caches, + ) + + # TODO: This is a hack purely to get some info to extract_tensor_metadata_for_cache_key, + # figure out how to not have to modify example inputs + for i, input in enumerate(example_inputs): + if ( + isinstance(input, torch.Tensor) + and is_gpu(input.device.type) + and i in static_input_idxs + ): + input._is_inductor_static = True # type: ignore[attr-defined] + + mb_compiled_graph: OutputCode | None = None + key_info = None + cache_info: CacheInfo | None = None + remote_cache = None + constants = CompiledFxGraphConstantsWithGm(gm) + # TODO: this time will be slightly inconsistent with the one computed + # in prepare_key/load_with_key, dump those settings of "cache_event_time" + start_time = time.time_ns() + + if use_cache: + (key_info, cache_info) = FxGraphCache.prepare_key( + gm, example_inputs, graph_kwargs, inputs_to_check, remote + ) + + # Attempt a cache lookup + if key_info is not None: + key, debug_lines = key_info + log.debug("FX cache key generated: %s", key) + if remote: + remote_cache = FxGraphCache.get_remote_cache() + log.debug("Using remote FX cache") + mb_compiled_graph, cache_info = FxGraphCache.load_with_key( + key, + debug_lines, + example_inputs, + local, + remote_cache, + is_backward=graph_kwargs.get("is_backward", False), + constants=constants, + ) + else: + log.debug("Failed to generate FX cache key") + + if torch._functorch.config.bundled_autograd_cache: + if mb_compiled_graph is not None: + raise AssertionError( + "Expected mb_compiled_graph to be None for bundled_autograd_cache path" + ) + if cache_info is not None: + raise AssertionError( + "Expected cache_info to be None for bundled_autograd_cache path" + ) + # When using bundled autograd cache, we still want + # to use the TritonBundler, but we don't want to save + # the results here. The results will get saved directly + # to AOTAutogradCache. + TritonBundler.begin_compile() + try: + mb_compiled_graph = fx_codegen_and_compile( + gm, + example_inputs, + inputs_to_check, + compile_region_name=compile_region_name, + **graph_kwargs, + ) + if mb_compiled_graph is None: + raise AssertionError( + "fx_codegen_and_compile returned None in bundled_autograd_cache path" + ) + ( + triton_bundle, + triton_bundler_meta, + ) = TritonBundler.collect() + mb_compiled_graph.set_triton_bundle(triton_bundle) + except (ShortenTraceback, SkipFrame): + raise + except Exception as e: + raise InductorError(e, currentframe()).with_traceback( + e.__traceback__ + ) from None + finally: + TritonBundler.end_compile() + + # CACHE BYPASS: Compile the graph, don't save it to the cache + # (this can happen either because cache was disabled, or we + # determined the input is uncacheable) + elif cache_info is None or cache_info["cache_state"] == "bypass": + if mb_compiled_graph is not None: + raise AssertionError( + "Expected mb_compiled_graph to be None in cache bypass path" + ) + log.debug( + "FX cache bypass reason: %s", + ( + cache_info.get("cache_bypass_reason", "unknown") + if cache_info is not None + else "FX cache disabled or key generation failed" + ), + ) + try: + mb_compiled_graph = fx_codegen_and_compile( + gm, + example_inputs, + inputs_to_check, + compile_region_name=compile_region_name, + **graph_kwargs, + ) + except Exception as e: + raise InductorError(e, currentframe()).with_traceback( + e.__traceback__ + ) from None + + # CACHE MISS: Compile the graph and save to cache + elif cache_info["cache_state"] == "miss": + if mb_compiled_graph is not None: + raise AssertionError( + "Expected mb_compiled_graph to be None in cache miss path" + ) + if key_info is None: + raise AssertionError("Expected key_info to be set in cache miss path") + log.debug("FX cache miss, compiling and saving to cache") + TritonBundler.begin_compile() + try: + mb_compiled_graph = fx_codegen_and_compile( + gm, + example_inputs, + inputs_to_check, + compile_region_name=compile_region_name, + **graph_kwargs, + ) + if mb_compiled_graph is None: + raise AssertionError( + "fx_codegen_and_compile returned None in cache miss path" + ) + mb_compiled_graph._time_taken_ns = time.time_ns() - start_time + cache_key, debug_lines = key_info + mb_compiled_graph._fx_graph_cache_key = cache_key + mb_compiled_graph._fx_graph_cache_debug_lines = debug_lines + ( + triton_bundle, + triton_bundler_meta, + ) = TritonBundler.collect() + mb_compiled_graph.set_triton_bundle(triton_bundle) + except (ShortenTraceback, SkipFrame): + raise + except Exception as e: + raise InductorError(e, currentframe()).with_traceback( + e.__traceback__ + ) from None + finally: + TritonBundler.end_compile() + if triton_bundler_meta is not None: + cache_info["triton_bundler_meta"] = str(triton_bundler_meta) + cache_info["time_taken_ns"] = mb_compiled_graph._time_taken_ns + log.debug("Saving compiled graph to FX cache with key: %s", cache_key) + FxGraphCache._save_graph( + cache_key, + mb_compiled_graph, + example_inputs, + local, + remote_cache, + ) + + # CACHE HIT: not much to really do, just make sure the cache key + # is recorded on the graph + else: + if cache_info["cache_state"] != "hit": + raise AssertionError( + f"Expected cache_state to be 'hit', got {cache_info['cache_state']!r}" + ) + if mb_compiled_graph is None: + raise AssertionError( + "Expected mb_compiled_graph to be set in cache hit path" + ) + if key_info is None: + raise AssertionError("Expected key_info to be set in cache hit path") + (cache_key, debug_lines) = key_info + log.debug("FX cache hit with key: %s", cache_key) + mb_compiled_graph._fx_graph_cache_key = cache_key + mb_compiled_graph._fx_graph_cache_debug_lines = debug_lines + + if mb_compiled_graph is None: + raise AssertionError( + "Expected mb_compiled_graph to be set after cache handling" + ) + compiled_graph = mb_compiled_graph + if isinstance(compiled_graph, CompiledFxGraph): + compiled_graph.compile_region_name = compile_region_name + + # Logging and observability: we log a single chromium event + # and a tlparse log for every cache action. + # In the event of a bypass, we also logged to the remote table earlier + # with log_cache_bypass. + cache_state = ( + cache_info["cache_state"] if cache_info is not None else "disabled" + ) + # Here for grepping: + # fx_graph_cache_hit + # fx_graph_cache_miss + # fx_graph_cache_bypass + # fx_graph_cache_disabled + cache_event_metadata = dict(cache_info) if cache_info else {} + CompileEventLogger.instant( + f"fx_graph_cache_{cache_state}", + metadata=cache_event_metadata, + time_ns=start_time, + ) + # Add event data about cache hits/miss + # TODO: add remote cache get/put timings here too + CompileEventLogger.try_add_pt2_compile( + "inductor_compile", + cache_state=cache_state, + cache_event_time=start_time, + key=cache_info.get("key") if cache_info else None, + components=cache_info.get("components") if cache_info else None, + cache_bypass_reason=( + cache_info.get("cache_bypass_reason") + if cache_info + else "cache not enabled" + ), + remote_cache_enabled=remote, + local_cache_enabled=local, + ) + + # Don't clog up the main tlparse output with disabled cache + if cache_info is not None: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": f"fx_graph_cache_{cache_state}", + "encoding": "json", + }, + payload_fn=lambda: json.dumps(cache_info), + ) + compiled_graph.post_compile(example_inputs, constants, graph_kwargs) + + policy = config.cudagraph_policy + if policy is not None: + compiled_graph = policy.wrap_output(compiled_graph) + + log.debug("FX codegen and compilation took %.3fs", time.time() - start) + + # This message is for printing overview information of inductor mm counts, shapes,etc after lowering + if log.isEnabledFor(logging.INFO): + mm_table_data = [] + for key, value in counters["aten_mm_info"].items(): + parts = key.split("_") + if len(parts) < 3: + # Unexpected format, show as-is + mm_table_data.append([key, "-", "?", "?", "?", value]) + continue + + # Determine if this is a batched operation by checking the operation name + name = "_".join(parts[:-4]) if len(parts) >= 4 else "_".join(parts[:-3]) + is_batched = name.endswith(("bmm", "baddbmm")) + + if is_batched and len(parts) >= 4: + # Batched operation: last 4 parts are batch, m, n, k + batch, m, n, k = parts[-4:] + name = "_".join(parts[:-4]) + mm_table_data.append([name, batch, m, n, k, value]) + else: + # Non-batched operation: last 3 parts are m, n, k + m, n, k = parts[-3:] + name = "_".join(parts[:-3]) + mm_table_data.append([name, "-", m, n, k, value]) + + log.info("Overview info of inductor aten mms: ") + log.info( + "{:<30} | {:<20} | {:<20} | {:<20} | {:<20} | {:<20}".format( # noqa: G001 + "Name", "B", "M", "N", "K", "Count" + ) + ) + log.info("-" * 130) + for row in mm_table_data: + log.info("{:<30} | {:<20} | {:<20} | {:<20} | {:<20} | {:<20}".format(*row)) # noqa: G001 + log.info("-" * 130) + + # Not strictly necessary, but good to clean up straggling futures + # that are unused to reclaim memory. + torch._inductor.async_compile.CompiledTritonKernels.cache_clear() + + _step_logger()( + logging.INFO, + "torchinductor done compiling " + f"{'BACKWARDS' if graph_kwargs['is_backward'] else 'FORWARDS'} " + f"graph {graph_kwargs['graph_id']}", + ) + return compiled_graph + + +class _FxCompileStat: + # Count of successful compiles of this type + codegen_and_compile: int = 0 + + def __repr__(self) -> str: + return f"codegen_and_compile: {self.codegen_and_compile}" + + +class FxCompile(ABC): + """ + An FxCompile represents a mechanism that can turn a GraphModule into an + OutputCode. + """ + + # Some stats for logging/debugging + _compile_stats: dict[type[FxCompile], _FxCompileStat] = defaultdict(_FxCompileStat) + compile_region_name: str | None = None + + # TODO: We should probably eventually add some kind of async version of this + # so we can kick off a compile and then go do other things - but we'll need + # to know what kind of API we want for that first. + @abstractmethod + def codegen_and_compile( + self, + gm: GraphModule, + example_inputs: Sequence[InputType], + inputs_to_check: Sequence[int], + graph_kwargs: _CompileFxKwargs, + ) -> OutputCode: ... + + @classmethod + def _reset_stats(cls) -> None: + cls._compile_stats.clear() + + +class _InProcessFxCompile(FxCompile): + @override + def codegen_and_compile( + self, + gm: GraphModule, + example_inputs: Sequence[InputType], + inputs_to_check: Sequence[int], + graph_kwargs: _CompileFxKwargs, + ) -> OutputCode: + """ + Generates the OutputCode from the GraphModule and example_inputs. + """ + # Sorry about the mess, we need graph_kwargs to continue to be able + # to propagate it further on + # TODO: _CompileFxKwargs actually has stronger types than in the + # signature, need to tighten it up + + if "cudagraphs" not in graph_kwargs or graph_kwargs["cudagraphs"] is None: + raise AssertionError("Expected 'cudagraphs' to be set in graph_kwargs") + cudagraphs: BoxedBool = graph_kwargs["cudagraphs"] + static_input_idxs: Sequence[int] = graph_kwargs.get("static_input_idxs", ()) + is_backward: bool = graph_kwargs.get("is_backward", False) + graph_id: int | None = graph_kwargs.get("graph_id", None) + cpp_wrapper: bool = graph_kwargs.get("cpp_wrapper", False) + fx_wrapper: bool = graph_kwargs.get("fx_wrapper", False) + aot_mode: bool = V.aot_compilation + is_inference: bool = graph_kwargs.get("is_inference", False) + extern_node_serializer: Callable[[list[ExternKernelNode]], Any] | None = ( + graph_kwargs.get("extern_node_serializer", None) + ) + get_decomp_fn: Callable[..., dict[Any, Callable[..., Any]]] = graph_kwargs.get( + "get_decomp_fn", select_decomp_table + ) + with ( + _WaitCounter("pytorch.wait_counter.actual_codegen_and_compile").guard(), + dynamo_utils.preserve_rng_state(), + ): + if (sleep_sec := config.sleep_sec_TESTING_ONLY) is not None: + import time + + log.warning( + "Sleeping for %s since sleep_sec_TESTING_ONLY is set", sleep_sec + ) + time.sleep(sleep_sec) + + if is_tf32_warning_applicable(gm): + _warn_tf32_disabled() + + inductor_counters = counters["inductor"].copy() + + # lift the maximum depth of the Python interpreter stack + # to adapt large/deep models + sys.setrecursionlimit(max(sys.getrecursionlimit(), 2000)) + + _step_logger()( + logging.INFO, + "torchinductor compiling " + f"{'BACKWARDS' if is_backward else 'FORWARDS'} " + f"graph {graph_id}", + ) + + # Building this parses the source of every Triton kernel in the + # graph, and it is only ever used as a structured-trace artifact: + # logged here, and logged again by the FX graph cache when this + # graph is loaded from it. Produce it from payload_fn so that + # trace_structured's own "is anyone listening" check decides + # whether the work happens at all, and keep what it produced for + # the cache to replay. + produced: list[str] = [] + + def _fx_graph_runnable_payload() -> str: + fd = io.StringIO() + torch._dynamo.repro.after_aot.save_graph_repro( + fd, gm, example_inputs, "inductor", save_dir=None + ) + produced.append(fd.getvalue()) + return produced[0] + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "fx_graph_runnable", + "encoding": "string", + }, + payload_fn=_fx_graph_runnable_payload, + ) + runnable_graph_str = produced[0] if produced else "" + + V.debug.fx_graph(gm, example_inputs) + # TODO: Should we actually dump this? It should be redundant with the aot + # structured logs... + # trace_structured("inductor_input_graph", payload_fn=lambda: gm.print_readable(print_output=False)) + + shape_env = gm.shape_env + if shape_env is None: + shape_env = shape_env_from_inputs(example_inputs) + + # Convert view to reshape in the graph. This is necessary primarily for + # layout optimization. Do it unconditionally for uniformity. + # + # It's needed because when we do layout optimization, a contiguous tensor + # in eager mode may becomes a channels last tensor. A view op previously + # can be applied to the contiguous tensor may not be able to be applied + # on the channels tensor any more. An error like + # RuntimeError: view size is not compatible with input tensor's size and stride + # (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead. + # will be printed. + # + # Replace view op to reshape op in this case. + # As an example, timm_resnest/botnet26t_256/convnext_base etc. will fail if we don't do this. + # + # Also this has to be done before FakeTensorProp below to avoid the failed + # .view() call. + view_to_reshape(gm) + + with dynamo_timed( + "additional_fake_tensor_prop", log_pt2_compile_event=True + ): + # It is safe to run FakeTensorProp under no_grad because by the time + # we're in inductor, we assume that AOTAutograd has already "taken care" + # of autograd, so there should be no more autograd-related API's in the + # graph. + with torch.no_grad(): + fake_mode = fake_tensor_prop(gm, example_inputs) + + _recursive_record_original_output_strides(gm) + + # pattern matcher passes might not preserve striding information + # on node.meta["val"]. if in the future we rely on these being + # correct we will need to fix. + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "before_post_grad_graph", + "encoding": "string", + }, + payload_fn=lambda: gm.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + with V.set_fake_mode(fake_mode): + # has some issues with memory in training + cuda_context = get_cuda_device_context(gm) + with cuda_context: + _recursive_post_grad_passes(gm, is_inference=is_inference) + V.debug.fx_graph_transformed(gm, example_inputs) + post_grad_graphs_log.debug( + "%s", + lazy_format_graph_code( + "AFTER POST GRAD", + gm, + include_stride=True, + include_device=True, + colored=True, + ), + ) + + # We're printing the graph to be used as a cache key - so a + # printer which is a little less readable but faster is + # appropriate. + inductor_post_grad_graph_str = gm.print_readable( + print_output=False, + include_stride=True, + include_device=True, + fast_sympy_print=True, + ) + # "inductor_post_grad_graph" is used in inductor provenance + # tracking highlighter front-end. + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_post_grad_graph", + "encoding": "string", + }, + payload_fn=lambda: inductor_post_grad_graph_str, + ) + if config.effective_provenance_tracking_level() != 0: + provenance_tracking_json = ( + torch.fx.traceback.get_graph_provenance_json(gm.graph) + ) + torch._inductor.debug._inductor_post_to_pre_grad_nodes = ( + create_mapping_pre_post_grad_nodes( + torch._inductor.debug._pre_grad_graph_id, + provenance_tracking_json, + ) + ) + + metrics_context = get_metrics_context() + if metrics_context.in_progress(): + num_graph_breaks = counters["graph_break"].total() + CompileEventLogger.compilation_metric( + overwrite=True, num_graph_breaks=num_graph_breaks + ) + if config.is_fbcode(): + try: + log_optimus_to_scuba( + extra_logging={ + "pt2_configs": str(get_patched_config_dict()) + } + ) + except Exception: + # TODO(T216453900): need to work around for now to support vllm + # See details in vllm/compilation/pass_manager.py. + log.warning("failed to log pt2_configs") + + with ( + V.set_fake_mode(fake_mode), + maybe_disable_comprehensive_padding(example_inputs), + maybe_disable_graph_partition(cpp_wrapper, aot_mode), + ): + const_output_index = None + const_graph = None + const_wrapper_code = None + const_kernel_code = None + + if aot_mode and config.aot_inductor.use_runtime_constant_folding: + # torchbind objects have name that starts with _torchbind_obj + # See caffe2/torch/fx/_symbolic_trace.py?lines=406 + const_gm, const_output_index = split_const_gm( + gm, + skip_folding_node_fn=lambda node: node.op == "get_attr" + and isinstance(node.target, str) + and ( + node.target.startswith("_torchbind_obj") + or isinstance(node.meta.get("val", None), FakeScriptObject) + ), + ) + + const_graph = GraphLowering( + const_gm, + example_inputs=[], + shape_env=shape_env, + graph_id=graph_id, + cpp_wrapper=cpp_wrapper, + aot_mode=aot_mode, + extern_node_serializer=extern_node_serializer, + is_inference=is_inference, + is_backward=is_backward, + is_const_graph=True, + fx_wrapper=fx_wrapper, + get_decomp_fn=get_decomp_fn, + ) + with ( + V.set_graph_handler(const_graph), + V.set_extern_kernel_nodes([]), + ): + if not cpp_wrapper: + raise AssertionError("AOT mode only supports C++ wrapper") + const_graph.run() + const_wrapper_code, const_kernel_code = ( + const_graph.codegen_with_cpp_wrapper() + ) + + graph = GraphLowering( + gm, + # example_inputs will be used by AOTInductor to dry-run the generated code for Triton kernel tuning. + # For the forward pass, we have the real inputs to be used as example_inputs. For the backward pass, + # we currently use fake tensors and defake them later. + example_inputs=example_inputs, + shape_env=shape_env, + graph_id=graph_id, + cpp_wrapper=cpp_wrapper, + aot_mode=aot_mode, + extern_node_serializer=extern_node_serializer, + is_inference=is_inference, + is_backward=is_backward, + const_output_index=const_output_index, + const_wrapper_code=( + const_wrapper_code.value if const_wrapper_code else None + ), + const_kernel_code=( + const_kernel_code.value if const_kernel_code else None + ), + const_module=const_graph, + inputs_to_check=inputs_to_check, + fx_wrapper=fx_wrapper, + get_decomp_fn=get_decomp_fn, + ) + metrics_helper = metrics.CachedMetricsHelper() + + # We are going to start code generating runtime asserts, so make sure + # you don't start adding new ones in the lowering process + graph.freeze_runtime_asserts() + with ( + V.set_graph_handler(graph), + V.set_extern_kernel_nodes([]), + distributed_autotune.graph_context(), + ): + graph.run(*example_inputs) + output_strides: list[tuple[_StrideExprStr, ...] | None] = [] + if graph.graph_outputs is not None: + # We'll put the output strides in the compiled graph so we + # can later return them to the caller via TracingContext + p = SymExprPrinter() + for out in graph.graph_outputs: + if ( + isinstance(out, IRNode) + and out.has_tensor_output() + and len(free_unbacked_symbols(out.get_stride())) == 0 + ): + # Convert to string for eval on the load path + output_strides.append( + tuple(p.doprint(s) for s in out.get_layout().stride) + ) + else: + output_strides.append(None) + + _check_triton_bf16_support(graph) + + # TODO: The switching between AOT mode and not here is a bit + # messy, but it's localized to the block of code below so I'm + # not going to touch it for now + + compiled_fn: Any + compiled_fn_runner: CompiledFnRunner | None = None + with dynamo_timed( + "GraphLowering.compile_to_fn", log_pt2_compile_event=True + ): + if graph.aot_mode and graph.fx_wrapper: + if graph.cpp_wrapper: + raise AssertionError( + "Expected cpp_wrapper to be False for fx_wrapper AOT mode" + ) + compiled_fn = graph.codegen()[0].gm # type: ignore[attr-defined] + output_code_log.debug( + "Output graph module: \n%s", + compiled_fn.print_readable(print_output=False), + ) + + elif graph.aot_mode: + from .codecache import AotCodeCompiler + + if not graph.cpp_wrapper: + raise AssertionError( + "AOT mode only supports C++ wrapper" + ) + wrapper_code, kernel_code = graph.codegen_with_cpp_wrapper() + output_code_log.debug( + "AOT wrapper code: \n%s", wrapper_code.value + ) + if kernel_code.value: + output_code_log.debug( + "AOT kernel code:\n%s", kernel_code.value + ) + + serialized_extern_kernel_nodes = None + if V.extern_kernel_nodes: + serialized_extern_kernel_nodes = ( + graph.extern_node_serializer(V.extern_kernel_nodes) + ) + output_code_log.debug( + "Serialized Extern Kernel Nodes: \n%s", + serialized_extern_kernel_nodes, + ) + + with dynamo_timed( + "AotCodeCompiler.compile", log_pt2_compile_event=True + ): + # Directly return the file path with the compiled code + compiled_fn = AotCodeCompiler.compile( + graph, + wrapper_code.value, + kernel_code.value, + serialized_extern_kernel_nodes, + device_type=graph.device_type, + additional_files=[ + *dict.fromkeys( + graph.wrapper_code.additional_files + + ( + const_graph.wrapper_code.additional_files + if const_graph + else [] + ) + ) + ], + ) + else: + compiled_module = graph.compile_to_module() + compiled_fn = compiled_module.call + compiled_fn_runner = getattr( + compiled_module, "runner", None + ) + + # Dump provenance artifacts for debugging trace + inductor_provenance_tracking_node_mappings = None + inductor_kernel_stack_trace_str = None + if config.effective_provenance_tracking_level() != 0: + inductor_provenance_tracking_node_mappings = json.dumps( + torch._inductor.debug.dump_inductor_provenance_info() + ) + inductor_kernel_stack_trace_str = json.dumps( + torch._inductor.debug._inductor_kernel_stack_trace + ) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_provenance_tracking_node_mappings", + "encoding": "json", + }, + payload_fn=lambda: inductor_provenance_tracking_node_mappings, + ) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_provenance_tracking_kernel_stack_traces", + "encoding": "json", + }, + payload_fn=lambda: inductor_kernel_stack_trace_str, + ) + if inductor_kernel_stack_trace_str: + metrics_context = get_metrics_context() + if metrics_context.in_progress(): + metrics_context.add_to_set( + "inductor_provenance", + inductor_kernel_stack_trace_str, + ) + + node_runtimes = None + if inductor_metrics_log.isEnabledFor(logging.INFO): + num_bytes, nodes_num_elem, node_runtimes = graph.count_bytes() + # pyrefly: ignore [bad-assignment] + metrics.num_bytes_accessed += num_bytes + metrics.node_runtimes += node_runtimes + metrics.nodes_num_elem += nodes_num_elem + inductor_metrics_log.info( + "Graph Metrics:\n%s", + { + "num_bytes_accessed": num_bytes, + "nodes_num_elem": nodes_num_elem, + "node_runtimes": node_runtimes, + }, + ) + + # Collect and dump op runtimes and tensor metadata for TLParse + if config.log_tlparse: + _, _, node_runtimes = graph.count_bytes() + torch._inductor.debug.log_runtime_and_tensor_meta(node_runtimes) + + # Collect and dump collective-op schedule for external diagnostics + torch._inductor.debug.log_collective_schedule(graph.scheduler.nodes) + + # When graph_partition is enabled, skip this check - partitioning handles dynamic shapes + if ( + cudagraphs + and config.triton.cudagraph_skip_dynamic_graphs + and not config.graph_partition + and not V.graph.disable_cudagraphs_reason + and torch._inductor.utils.any_is_symbolic(*example_inputs) + ): + stack_trace = None + for node in gm.graph.nodes: + meta_val = node.meta.get("val", None) + if ( + node.op == "placeholder" + or not isinstance(meta_val, torch.Tensor) + or not torch._inductor.utils.any_is_symbolic(meta_val) + ): + continue + + if stack_trace := node.meta.get("stack_trace", None): + break + disable = "graph with symbolic shapes inputs and config.triton.cudagraph_skip_dynamic_graphs=True." + if stack_trace: + disable = f"{disable} Found from {stack_trace}\n" + else: + disable = f"{disable}\n" + # pyrefly: ignore [unbound-name] + V.graph.disable_cudagraphs_reason = disable + + # pyrefly: ignore [unbound-name] + # When graph_partition is enabled, skip this check - partitioning handles incompatible ops + if ( + cudagraphs + # pyrefly: ignore [unbound-name] + and not config.graph_partition + # pyrefly: ignore [unbound-name] + and not V.graph.disable_cudagraphs_reason + ): + maybe_incompat_node = get_first_incompatible_cudagraph_node(gm) + if maybe_incompat_node: + disable = f"disabling cudagraphs due to incompatible op {maybe_incompat_node.target}" + if stack_trace := maybe_incompat_node.meta.get( + "stack_trace", None + ): + disable = f"{disable} Found from {stack_trace}\n" + # pyrefly: ignore [unbound-name] + V.graph.disable_cudagraphs_reason = disable + + # pyrefly: ignore [unbound-name] + if V.aot_compilation: + if not isinstance( + compiled_fn, + # pyrefly: ignore [unbound-name] + (str, list, torch.fx.GraphModule), + ): + raise AssertionError( + f"Expected compiled_fn to be str, list, or GraphModule, got {type(compiled_fn)}" + ) + return CompiledAOTI( + filename=compiled_fn, device_type=graph.device_type + ) + + # TODO: Hoist this above V.aot_compilation + # pyrefly: ignore [unbound-name] + if cudagraphs and not V.graph.disable_cudagraphs_reason: + from torch._inductor.cudagraph_utils import ( + check_lowering_disable_cudagraph, + ) + + # pyrefly: ignore [unbound-name] + V.graph.disable_cudagraphs_reason = ( + check_lowering_disable_cudagraph( + # pyrefly: ignore [unbound-name] + V.graph.device_node_mapping + ) + ) + + if ( + cudagraphs + and not V.graph.disable_cudagraphs_reason + and graph.scheduler.count_kernel_nodes(graph.scheduler.nodes) + == 0 + ): + V.graph.kernel_free_cudagraph = True + + self._compile_stats[type(self)].codegen_and_compile += 1 + + if ( + # pyrefly: ignore [unbound-name] + torch._inductor.debug.RECORD_GRAPH_EXECUTION + # pyrefly: ignore [unbound-name] + and torch._inductor.debug.GRAPH_COMPILE_IDS is not None + ): + compile_id = str( + # pyrefly: ignore [unbound-name] + torch._guards.CompileContext.current_compile_id() + ) + graph_id = graph_kwargs.get("graph_id") + if graph_id is not None: + # pyrefly: ignore [unbound-name] + torch._inductor.debug.GRAPH_COMPILE_IDS[graph_id] = ( + compile_id + ) + + return CompiledFxGraph( + compiled_fn, + graph, + gm, + output_strides, + # pyrefly: ignore [unbound-name] + V.graph.disable_cudagraphs_reason, + metrics_helper.get_deltas(), + counters["inductor"] - inductor_counters, + cudagraphs, + example_inputs, + static_input_idxs, + self.compile_region_name, + graph_kwargs, + inputs_to_check, + runnable_graph_str, + inductor_post_grad_graph_str, + compiled_fn_runner, + inductor_provenance_tracking_node_mappings, + inductor_kernel_stack_trace_str, + ) + + +def fx_codegen_and_compile( + gm: GraphModule, + example_inputs: Sequence[InputType], + # This is derivable from the other inputs to this function, but we pass it + # in explicitly because it's nontrivial to compute + inputs_to_check: Sequence[int], + compile_region_name: str | None = None, + **graph_kwargs: Unpack[_CompileFxKwargs], +) -> OutputCode: + scheme: FxCompile + + if fx_compile_mode == FxCompileMode.NORMAL: + scheme = _InProcessFxCompile() + elif fx_compile_mode == FxCompileMode.SERIALIZE: + from .compile_fx_ext import _DebugSerdeFxCompile + + scheme = _DebugSerdeFxCompile() + elif fx_compile_mode == FxCompileMode.SUBPROCESS: + from .compile_fx_subproc import _SubprocessFxCompile + + scheme = _SubprocessFxCompile() + + if fx_compile_async: + from .compile_fx_async import _AsyncFxCompile + from .compile_fx_ext import _OutOfProcessFxCompile + + # pyrefly: ignore [unbound-name] + if not isinstance(scheme, _OutOfProcessFxCompile): + raise AssertionError( + "async is only valid with an out-of-process compile mode" + ) + # pyrefly: ignore [unbound-name] + scheme = _AsyncFxCompile(scheme) + scheme._compile.compile_region_name = ( + compile_region_name # pyrefly: ignore[attr-defined] + ) + + if fx_compile_progressive: + from .compile_fx_async import _ProgressiveFxCompile + from .compile_fx_ext import _OutOfProcessFxCompile + + # pyrefly: ignore [unbound-name] + if not isinstance(scheme, _OutOfProcessFxCompile): + raise AssertionError( + "progressive is only valid with an out-of-process compile mode" + ) + + progression_configs = _get_progression_configs() + + # Use in-process compile for the fast version + fast_scheme = _InProcessFxCompile() + fast_scheme.compile_region_name = compile_region_name + + # pyrefly: ignore [unbound-name] + scheme = _ProgressiveFxCompile(fast_scheme, scheme, progression_configs) + scheme._optimized_compile.compile_region_name = ( + compile_region_name # pyrefly: ignore[attr-defined] + ) + + scheme.compile_region_name = compile_region_name # pyrefly: ignore[unbound-name] + + # pyrefly: ignore [unbound-name] + return scheme.codegen_and_compile(gm, example_inputs, inputs_to_check, graph_kwargs) + + +def get_input_idxs_to_check( + inputs: Sequence[InputType], + static_input_idxs: Sequence[int], +) -> Sequence[int]: + """ + This function runs at compile time, and generates a list of indices for which we + might need to do a copy to preserve alignment requirements. + """ + ids_to_check = [] + + for i, input in enumerate(inputs): + if not isinstance(input, torch.Tensor): + # non-tensors don't need alignment + continue + if not is_gpu(input.device.type): + # right now we only care for gpu tensors + continue + with maybe_get_suppress_shape_guards_ctx(): + # suppress guards so that tensor_is_aligned and should_assume_input_aligned + # do not add guards on input's storage offset + if i in static_input_idxs and tensor_is_aligned(input): + continue + if not should_assume_input_aligned(input): + continue + + # if we get here, then + # (a) our triton code assumes that the input is aligned + # (b) we can't be sure ahead of time that the input will actually be aligned. + # therefore, at runtime, we'll need to check that the input is aligned + # (and if not, clone it to make it aligned.) + ids_to_check.append(i) + + return ids_to_check + + +def cudagraphify( + model: Callable[..., Any], + static_input_idxs: Sequence[int] = (), + *, + device_index: int, + stack_traces: list[str | None], + is_backward: bool, + is_inference: bool, + constants: tuple[torch.Tensor, ...] = (), + placeholders: Sequence[PlaceholderInfo] = (), + mutated_input_idxs: tuple[int, ...] = (), + kernel_free_cudagraph: bool = False, + user_visible_output_idxs: tuple[int, ...] = (), +) -> Callable[..., Any]: + from torch._inductor.cudagraph_trees import ( + cudagraphify_impl as new_cudagraphify_impl, + ) + + cudagraphify_fn: Callable[..., Any] + if config.triton.cudagraph_trees: + cudagraphify_fn = functools.partial( + new_cudagraphify_impl, + device_index=device_index, + stack_traces=stack_traces, + is_backward=is_backward, + is_inference=is_inference, + constants=constants, + placeholders=placeholders, + mutated_input_idxs=mutated_input_idxs, + kernel_free_cudagraph=kernel_free_cudagraph, + user_visible_output_idxs=user_visible_output_idxs, + compile_id=torch._guards.CompileContext.current_compile_id(), + ) + else: + cudagraphify_fn = functools.partial( + cudagraphify_impl, + kernel_free_cudagraph=kernel_free_cudagraph, + ) + + thread_local = threading.local() + + def run(new_inputs: Sequence[InputType]) -> Any: + compiled_fn = getattr(thread_local, "compiled_fn", None) + if compiled_fn is None: + with dynamo_utils.preserve_rng_state(): + compiled_fn = cudagraphify_fn(model, new_inputs, static_input_idxs) # type: ignore[arg-type] + thread_local.compiled_fn = compiled_fn + return compiled_fn(new_inputs) # type: ignore[arg-type] + + return run + + +def static_input(x: torch.Tensor) -> torch.Tensor: + """ + Copy and input while preserving strides + """ + return torch.empty_strided(x.size(), x.stride(), dtype=x.dtype, device=x.device) + + +def index_expanded_dims_and_copy_( + dst: torch.Tensor, + src: torch.Tensor, + expanded_dims: list[int], +) -> None: + "Index into expanded dimensions of both dst and src then copy_" + indexed_dst = index_expanded_dims(dst, expanded_dims) + if torch._debug_has_internal_overlap(indexed_dst) != 0: + # dst still self-overlaps after dropping expanded dims (rare). A regular + # copy_ would have ambiguous semantics; bytewise-copy the strided extent + # instead so dst's overlap pattern is reproduced verbatim. + copy_strided_storage_(dst, src) + return + indexed_src = index_expanded_dims(src, expanded_dims) + indexed_dst.copy_(indexed_src) + + +def cudagraphify_impl( + model: Callable[..., Any], + inputs: list[torch.Tensor], + static_input_idxs: Sequence[int] = (), + *, + kernel_free_cudagraph: bool = False, +) -> Callable[[list[InputType]], Any]: + """ + Assumes inputs[static_input_idxs[i]] are always the same memory address + """ + if kernel_free_cudagraph: + return model + + check_input_idxs = get_input_idxs_to_check(inputs, static_input_idxs) # type: ignore[arg-type] + # pyrefly: ignore [annotation-mismatch, redefinition] + static_input_idxs: OrderedSet[int] = OrderedSet( + remove_unaligned_input_idxs(inputs, static_input_idxs) # type: ignore[arg-type] + ) + copy_misaligned_inputs(inputs, check_input_idxs) # type: ignore[arg-type] + + if not isinstance(inputs, list): + raise AssertionError(f"Expected inputs to be a list, got {type(inputs)}") + + inps_expanded_dims = [ + get_expanded_dims(x) if idx not in static_input_idxs else [] + for idx, x in enumerate(inputs) + ] + + # allocate static tensor inputs + static_inputs = [ + ( + x + if not isinstance(x, torch.Tensor) + else static_input(x) + if idx not in static_input_idxs + else x.detach() + ) + for idx, x in enumerate(inputs) + ] + + # copy over input values for fresh allocations + for idx, (x, expanded_dims) in enumerate(zip(inputs, inps_expanded_dims)): + if isinstance(x, torch.Tensor) and idx not in static_input_idxs: + index_expanded_dims_and_copy_(static_inputs[idx], x, expanded_dims) + + # warmup + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + # copy static_inputs because it will be cleared in model + with torch.cuda.stream(stream): + model(list(static_inputs)) + stream.synchronize() + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + + # record + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream, capture_error_mode="thread_local"): + static_outputs = model(list(static_inputs)) + if not isinstance(static_outputs, (list, tuple)): + static_outputs = (static_outputs,) + + if config.size_asserts: + + def run(new_inputs: list[InputType]) -> Callable[[list[InputType]], Any]: + if len(static_inputs) != len(new_inputs): + raise AssertionError( + f"Expected static_inputs and new_inputs to have same length, " + f"got {len(static_inputs)} vs {len(new_inputs)}" + ) + for idx, (dst, src, expanded_dims) in enumerate( + zip(static_inputs, new_inputs, inps_expanded_dims) + ): + if not isinstance(dst, torch.Tensor): + continue + if not isinstance(src, torch.Tensor): + raise AssertionError( + f"Expected src at index {idx} to be a Tensor, got {type(src)}" + ) + if idx in static_input_idxs: + if dst.data_ptr() != src.data_ptr(): + raise AssertionError( + f"Expected static input at index {idx} to have same data_ptr, " + f"got {dst.data_ptr()} vs {src.data_ptr()}" + ) + else: + # TODO - could make one single op of multiple slices + # and avoid dispatch. + # Could also pre-index the `dst` tensors + index_expanded_dims_and_copy_(dst, src, expanded_dims) + new_inputs.clear() + graph.replay() + # pyrefly: ignore [bad-return] + return static_outputs + + else: + copy_indices = [ + idx for idx in range(len(static_inputs)) if idx not in static_input_idxs + ] + + def run(new_inputs: list[InputType]) -> Callable[[list[InputType]], Any]: + for idx in copy_indices: + expanded_dims = inps_expanded_dims[idx] + src = new_inputs[idx] + if not isinstance(src, torch.Tensor): + raise AssertionError( + f"Expected src at index {idx} to be a Tensor, got {type(src)}" + ) + index_expanded_dims_and_copy_(static_inputs[idx], src, expanded_dims) + new_inputs.clear() + graph.replay() + # pyrefly: ignore [bad-return] + return static_outputs + + return align_inputs_from_check_idxs(run, check_input_idxs, OrderedSet()) + + +def compile_fx_aot( + model_: GraphModule, + example_inputs_: list[InputType], + inner_compile: _CompileFxCallable = compile_fx_inner, + config_patches: dict[str, Any] | None = None, +) -> list[str | Weights] | str | GraphModule: + if not isinstance(model_, GraphModule): + raise AssertionError(f"Expected GraphModule, got {type(model_)}: {model_}") + + # [See NOTE] Unwrapping subclasses AOT + unwrap_tensor_subclass_parameters(model_) + + # pyrefly: ignore [annotation-mismatch, redefinition] + config_patches: dict[str, Any] = copy.deepcopy(config_patches or {}) + + if not (config_patches.get("fx_wrapper", False) or config.fx_wrapper): + # If fx_wrapper is not set, then set cpp_wrapper + config_patches["cpp_wrapper"] = True + + output_path = config_patches.get( + "aot_inductor.output_path", config.aot_inductor.output_path + ) + + if output_path: + if output_path.endswith(".pt2"): + raise AssertionError( + "The output path for aot_compile should not have an extension with .pt2 " + "this is for specifying the output path for the .so in AOTInductor. " + "If you would like to package the AOTInductor generated files " + "into a pt2, please call `torch._inductor.aoti_compile_and_package`." + ) + else: + config_patches = { + **config_patches, + "aot_inductor.output_path": code_hash(model_.code), + } + + from .utils import maybe_aoti_standalone_config + + config_patches = maybe_aoti_standalone_config(config_patches) + + extern_node_serializer = config_patches.pop("extern_node_serializer", None) + saved_compile_id = model_.meta.get("dynamo_compile_id", None) + saved_compile_context = torch._guards.CompileContext(saved_compile_id) + with ( + V.set_aot_compilation(True), + torch._guards.compile_context(saved_compile_context), + chromium_event_timed( + "compile_fx_aot", + log_pt2_compile_event=True, + reset_event_log_on_exit=True, + ), + get_metrics_context(), + ): + compiled_artifacts = compile_fx( + model_, + example_inputs_, + inner_compile=functools.partial( + inner_compile, + extern_node_serializer=extern_node_serializer, + ), + config_patches=config_patches, + ) + + if not isinstance(compiled_artifacts, CompiledAOTI): + raise AssertionError( + f"Expected CompiledAOTI, got {type(compiled_artifacts)}" + ) + + return compiled_artifacts.filename + + +_graph_counter = count(0) + + +def fw_compiler_freezing( + aot_autograd_model: GraphModule, + aot_example_inputs: Sequence[InputType], + dynamo_model: GraphModule, + num_example_inputs: int, + inner_compile: Callable[..., Any], + # TODO: Take compiler_config_extra instead + cudagraphs: BoxedBool, + graph_id: int, + forward_device: BoxedDeviceIndex, +) -> Callable[[list[object]], Sequence[torch.Tensor]]: + from torch._inductor.freezing import convert_conv_weights_to_channels_last, freeze + + # partition_fn won't be called + inputs_devices = get_inputs_devices(aot_example_inputs, aot_autograd_model) + aot_autograd_model = _recursive_joint_graph_passes( + aot_autograd_model, + input_device=next(iter(inputs_devices)), + ) + + layout_opt = GraphLowering.decide_layout_opt(aot_autograd_model, is_inference=True) + if layout_opt: + # make sure meta['val'] is properly setup + fake_tensor_prop(aot_autograd_model, aot_example_inputs, True) + convert_conv_weights_to_channels_last(aot_autograd_model) + + opt_model, preserved_arg_indices = freeze( + dynamo_model, + aot_autograd_model, + aot_example_inputs, # type: ignore[arg-type] + ) + + aot_example_inputs = [aot_example_inputs[ind] for ind in preserved_arg_indices] + + fake_mode = detect_fake_mode(aot_example_inputs) + + # for freezing, all graph outputs should be user visible + *_, model_outputs_node = opt_model.graph.nodes + model_outputs = model_outputs_node.args[0] + model_outputs_node.meta["user_visible_output_idxs"] = [ + idx for idx, n in enumerate(model_outputs) if isinstance(n, torch.fx.Node) + ] + + static_input_idxs: list[Any] = [] + # constant params will be real tensors, not fake + tracing_context = torch._guards.TracingContext.try_get() + unwrapped_args_offsets = [0] + max_offset_idx = 0 + if tracing_context is not None: + if tracing_context.params_flat_unwrap_subclasses is None: + raise AssertionError( + "Expected tracing_context.params_flat_unwrap_subclasses to be set" + ) + params_flat_unwrap = tracing_context.params_flat_unwrap_subclasses + max_offset_idx = max(0, len(params_flat_unwrap) - 1) + preserved_indices_params_flat = OrderedSet[int]() + unwrapped_idxs = tracing_context.params_unwrapped_to_flat_index + if unwrapped_idxs is None: + raise AssertionError( + "Expected tracing_context.params_unwrapped_to_flat_index to be set" + ) + current_offset = 0 + if len(params_flat_unwrap) > 0: + unwrapped_args_offsets = [] + + for i in range(len(params_flat_unwrap)): + if i not in preserved_arg_indices: + params_flat_unwrap[i] = None + if i > 0 and unwrapped_idxs[i] == unwrapped_idxs[i - 1]: + current_offset += 1 + else: + preserved_indices_params_flat.add(unwrapped_idxs[i]) + unwrapped_args_offsets.append(current_offset) + + # Deallocate wrapped params, if all subelements were deallocated + if tracing_context.params_flat is None: + raise AssertionError("Expected tracing_context.params_flat to be set") + for i in range(len(tracing_context.params_flat)): + if i not in preserved_indices_params_flat: + tracing_context.params_flat[i] = None + + if tracing_context.fw_metadata: + static_input_idxs = tracing_context.fw_metadata.static_input_indices + + with mock.patch.object(fake_mode, "allow_non_fake_inputs", True): + optimized_function = inner_compile( + opt_model, + aot_example_inputs, + static_input_idxs=static_input_idxs, + cudagraphs=cudagraphs, + graph_id=graph_id, + is_inference=True, + boxed_forward_device_index=forward_device, + layout_opt=layout_opt, + ) + + # aot_inductor codegens a call that takes in just the inputs, so we don't return a wrapper + # that drops constant-ified params + if V.aot_compilation: + return optimized_function + + def wrapper(args: list[object]) -> Sequence[torch.Tensor]: + args_new = [ + args[i - unwrapped_args_offsets[min(i, max_offset_idx)]] + for i in preserved_arg_indices + ] + args.clear() + return optimized_function(args_new) + + wrapper._boxed_call = True # type: ignore[attr-defined] + + return wrapper + + +def get_cpp_wrapper_config(log_cudagraph_skip: bool = True) -> dict[str, object]: + if log_cudagraph_skip and config.triton.cudagraphs and config.graph_partition: + log_cudagraph_skip_and_bump_counter( + format_default_skip_message( + "cpp-wrapper does not support graph partition yet" + ) + ) + + autotune_at_compile_time = ( + config.triton.autotune_at_compile_time + if config.triton.autotune_at_compile_time is not None + # Default to True for AOTI. Subject to change in future. + else has_triton() and V.aot_compilation + ) + return { + "triton.autotune_at_compile_time": autotune_at_compile_time, + "triton.autotune_cublasLt": not autotune_at_compile_time, + "triton.cudagraphs": ( + config.triton.cudagraphs + and not V.aot_compilation + and not config.graph_partition + ), + "triton.store_cubin": True, + } + + +def get_cuda_device_context(gm: torch.fx.GraphModule) -> AbstractContextManager[None]: + """ + Returns a cuda device context manager if there is a single device in the graph + """ + if not torch.cuda.is_available(): + return contextlib.nullcontext() + + cuda_devices: OrderedSet[torch.device] = OrderedSet( + device for device in get_all_devices(gm) if device.type == "cuda" + ) + + return ( + torch.cuda.device(next(iter(cuda_devices))) # type: ignore[return-value] + if len(cuda_devices) == 1 + else contextlib.nullcontext() + ) + + +def partition_fn( + gm: GraphModule, + joint_inputs: Sequence[object], + *, + # When set, replaces the default partitioner (`config.custom_partitioner_fn` + # or `min_cut_rematerialization_partition`) while still running Inductor's + # joint-graph passes first. Used by `_get_partition_fn` so HOP subgraphs + # go through the same joint-pass + raw-partitioner pipeline as the outer + # Inductor compile. + partitioner_fn_override: Callable[..., Any] | None = None, + **kwargs: object, +) -> tuple[GraphModule, GraphModule]: + cuda_context = get_cuda_device_context(gm) + with cuda_context: + # We can skip the invoke_subgraph because the + # entire_partition_fn is called recursively for invoke_subgraph + # in partitioning. + inputs_devices = get_inputs_devices(joint_inputs, gm) + gm = _recursive_joint_graph_passes( + gm, + skip_invoke_subgraph=True, + input_device=next(iter(inputs_devices)), + ) + + static_lifetime_input_indices: list[int] | None = kwargs.pop( # type: ignore[assignment] + "static_lifetime_input_indices", None + ) + + if partitioner_fn_override is not None: + return partitioner_fn_override( + gm, + joint_inputs, + static_lifetime_input_indices=static_lifetime_input_indices, + **kwargs, + ) + + if config.custom_partitioner_fn is None: + with dynamo_utils.dynamo_timed( + "min_cut_rematerialization_partition", log_pt2_compile_event=True + ): + return min_cut_rematerialization_partition( + gm, + joint_inputs, + compiler="inductor", + static_lifetime_input_indices=static_lifetime_input_indices, + # pyrefly: ignore[bad-argument-type] + **kwargs, + ) + else: + if not isinstance(config.custom_partitioner_fn, CustomPartitionerFn): + raise AssertionError( + f"Expected custom_partitioner_fn to be CustomPartitionerFn, " + f"got {type(config.custom_partitioner_fn)}" + ) + with dynamo_utils.dynamo_timed( + config.custom_partitioner_fn.__class__.__name__, + log_pt2_compile_event=True, + ): + return config.custom_partitioner_fn( + gm, + joint_inputs, + compiler="inductor", + static_lifetime_input_indices=static_lifetime_input_indices, + **kwargs, + ) + + +def get_num_model_outputs(model: GraphModule) -> int: + model_outputs_node = output_node(model) + model_outputs = pytree.arg_tree_leaves(*model_outputs_node.args) + return len(model_outputs) + + +def cudagraph_annotation_context( + cudagraphs: BoxedBool, +) -> contextlib.AbstractContextManager[None]: + # When an annotation force-enables cudagraphs but the global config has them + # off, patch config.triton.cudagraphs for the duration of compilation, + # so existing codepaths that access config.triton.cudagraphs work + if cudagraphs.value and not config.triton.cudagraphs: + return config.patch({"triton.cudagraphs": True}) + return contextlib.nullcontext() + + +@dataclass(frozen=True) +class CompilerConfigExtra: + cudagraphs: BoxedBool + graph_id: int + forward_device: BoxedDeviceIndex + forward_is_partitioned: BoxedBool + cudagraphs_bwd_override: bool | None = None + + +def create_compiler_config_extra( + gm: GraphModule | GmWrapper, +) -> CompilerConfigExtra: + gm_meta = gm.meta if isinstance(gm, GraphModule) else None + + # Although cudagraphs may have been enabled via config, various + # conditions (which are tested within the bowels of Inductor) may + # force cudagraphs to be disabled. This mutable box lets us retrieve + # the final determination if cudagraphs actually can be used or not. + cudagraphs = BoxedBool(config.triton.cudagraphs) + + cudagraphs_bwd_override: bool | None = None + + # Override cudagraphs BoxedBool based on override_cudagraphs annotation. + # Disabling fwd disables bwd (copying activations isn't profitable), + # so cudagraphs_bwd_override is only needed for fwd=True / bwd=False. + if ( + gm_meta is not None + and (annotation := gm_meta.get("cudagraph_annotation")) is not None + ): + if annotation.fwd is not None and annotation.fwd != config.triton.cudagraphs: + cudagraphs = BoxedBool(annotation.fwd) + if annotation.fwd: + cudagraphs_log.info( + "enabling cudagraphs due to override_cudagraphs annotation" + ) + else: + log_cudagraph_skip_and_bump_counter( + "disabling cudagraphs due to override_cudagraphs annotation" + ) + + # bwd override only matters when fwd enables cudagraphs but bwd + # explicitly disables them. + if cudagraphs.value and annotation.bwd is not None and not annotation.bwd: + cudagraphs_bwd_override = annotation.bwd + log_cudagraph_skip_and_bump_counter( + "disabling cudagraphs for backward due to override_cudagraphs annotation" + ) + + # TODO: The modern style is to use CompileId from TracingContext to + # identify Inductor compilation. However, this CompileId cannot + # uniquely identify multiple Inductor compilations that arise from + # DDPOptimizer + graph_id = next(_graph_counter) + + # See [Backward Generation Handling] + forward_device = BoxedDeviceIndex(None) + + # Set by the forward compilation when it is partitioned for CUDA graphs. + # The backward reads this to decide whether saved tensors can be assumed + # to have fixed addresses. + forward_is_partitioned = BoxedBool(False) + + return CompilerConfigExtra( + cudagraphs=cudagraphs, + graph_id=graph_id, + forward_device=forward_device, + cudagraphs_bwd_override=cudagraphs_bwd_override, + forward_is_partitioned=forward_is_partitioned, + ) + + +def compile_fx_forward( + gm: GraphModule, + example_inputs: Sequence[InputType], + num_orig_model_outputs: int, + num_example_inputs: int, + compiler_config_extra: CompilerConfigExtra, + inner_compile: Callable[..., OutputCode] = compile_fx_inner, + is_inference: bool = False, +) -> OutputCode: + """ + Compile the forward graph of the given graph module. + + Args: + gm: The graph module to compile. + example_inputs: The example inputs to use for compilation. + num_orig_model_outputs: The number of model outputs from the original dynamo graph. + num_example_inputs: The number of example inputs from the original dynamo graph. + compiler_config_extra: Extra configuration for the compiler. + inner_compile: The inner compile function to use. + is_inference: Whether this is an inference graph. + """ + + if is_inference: + # partition_fn won't be called + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "before_joint_graph", + "encoding": "string", + }, + payload_fn=lambda: gm.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + # Snapshot stack traces on the output node before passes run, + # as later passes may strip stack_trace from individual nodes. + output = output_node(gm) + output.meta["output_stack_traces"] = [ + ( + arg.meta.get("stack_trace") + if isinstance(arg, torch.fx.node.Node) + else None + ) + for arg in output.args[0] # type: ignore[union-attr] + ] + + # Record original output strides BEFORE joint_graph_passes, because + # pad_mm (run as part of joint_graph_passes) can introduce views with + # padded strides that would be incorrectly captured as "original". + _recursive_record_original_output_strides(gm) + + inputs_devices = get_inputs_devices(example_inputs, gm) + gm = _recursive_joint_graph_passes(gm, input_device=next(iter(inputs_devices))) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "after_joint_graph", + "encoding": "string", + }, + payload_fn=lambda: gm.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + fixed = torch._inductor.utils.num_fw_fixed_arguments( + num_example_inputs, len(example_inputs) + ) + + model_outputs_node = output_node(gm) + clone_live_user_outputs = _cudagraph_trees_clone_live_user_outputs() + model_outputs = None + user_visible_output_idxs: list[int] = [] + if config.keep_output_stride or clone_live_user_outputs: + model_outputs = pytree.arg_tree_leaves(*model_outputs_node.args) + num_model_outputs = len(model_outputs) + + context = torch._guards.TracingContext.try_get() + # See Note [User Outputs in the inductor graph] + if context is not None and context.fw_metadata and not is_inference: + original_output_start_index = ( + context.fw_metadata.num_mutated_inp_runtime_indices + ) + else: + original_output_start_index = 0 + + if num_orig_model_outputs > num_model_outputs: + raise AssertionError( + f"Expected num_orig_model_outputs ({num_orig_model_outputs}) " + f"<= num_model_outputs ({num_model_outputs})" + ) + + # Note [User Outputs in the inductor graph] + # We makes the following assumption + # For inference + # len(orig_model_outputs) == len(model_outputs) + # For training + # len(orig_model_outputs) <= len(model_outputs) + # During training, most of the time the model_outputs starts with + # original module's outputs followed by saved activations. + # But this can be not true if the model have inplace updated tensors. + # AOTAutograd will make those tensors being returned before the original + # module's output. + # To make things safe, we'll use original_output_start_index field + # set by AOTAutograd to decide where the original module outputs start. + orig_output_end_idx = original_output_start_index + num_orig_model_outputs + # Sanity check: we are about to splice out the "user" outputs from the full set + # of "graph" outputs. Make sure we're within bounds. + if orig_output_end_idx > num_model_outputs: + raise AssertionError( + f"Expected orig_output_end_idx ({orig_output_end_idx}) " + f"<= num_model_outputs ({num_model_outputs})" + ) + + user_visible_output_idxs = [ + idx + for idx in range(original_output_start_index, orig_output_end_idx) + if isinstance(model_outputs[idx], torch.fx.Node) + ] + + if config.keep_output_stride or clone_live_user_outputs: + model_outputs_node.meta["user_visible_output_idxs"] = user_visible_output_idxs + else: + model_outputs_node.meta["user_visible_output_idxs"] = [] + + # We also mark the invoke_subgraph outputs as user_visible to + # force the outputs of invoke_subgraph subgraph to follow the + # original strides + _recursive_record_user_visible_output_idxs(gm) + + with cudagraph_annotation_context(compiler_config_extra.cudagraphs): + result = inner_compile( + gm, + example_inputs, + static_input_idxs=get_static_input_idxs(fixed), + cudagraphs=compiler_config_extra.cudagraphs, + graph_id=compiler_config_extra.graph_id, + is_inference=is_inference, + boxed_forward_device_index=compiler_config_extra.forward_device, + ) + + if ( + not is_inference + and isinstance(result, CompiledFxGraph) + and result.partition_maps + and len(result.partition_maps) > 1 + ): + compiler_config_extra.forward_is_partitioned.value = True + + return result + + +def compile_fx_backward( + gm: GraphModule, + example_inputs: Sequence[InputType], + compiler_config_extra: CompilerConfigExtra, + inner_compile: Callable[..., OutputCode] = compile_fx_inner, +) -> OutputCode: + """ + Compile the backward graph of the given graph module. + + Args: + gm: The graph module to compile. + example_inputs: The example inputs to use for compilation. + compiler_config_extra: Extra configuration for the compiler. + inner_compile: The inner compile function to use. + """ + from torch._dynamo.convert_frame import compile_lock + + with compile_lock: + model_outputs_node = output_node(gm) + if config.bw_outputs_user_visible: + model_outputs = pytree.arg_tree_leaves(*model_outputs_node.args) + model_outputs_node.meta["user_visible_output_idxs"] = [ + idx + for idx, n in enumerate(model_outputs) + if isinstance(n, torch.fx.Node) + ] + else: + model_outputs_node.meta["user_visible_output_idxs"] = [] + + fixed = count_tangents(gm) + + # Check if cudagraphs should be overridden for backward via annotation + cudagraphs = compiler_config_extra.cudagraphs + if compiler_config_extra.cudagraphs_bwd_override is not None: + cudagraphs = BoxedBool(compiler_config_extra.cudagraphs_bwd_override) + + # When the forward was partitioned, saved activations from inline + # code between partitions are NOT at fixed addresses. Only mark + # primals (params/buffers) as static. + if compiler_config_extra.forward_is_partitioned.value: + static_input_idxs: Sequence[int] = get_static_bw_input_idxs(gm) + else: + static_input_idxs = list(range(fixed)) + with ( + ( + config.patch(get_cpp_wrapper_config()) + if config.cpp_wrapper + else contextlib.nullcontext() + ), + cudagraph_annotation_context(cudagraphs), + ): + return inner_compile( + gm, + example_inputs, + static_input_idxs=static_input_idxs, + cudagraphs=cudagraphs, + is_backward=True, + graph_id=compiler_config_extra.graph_id, + boxed_forward_device_index=compiler_config_extra.forward_device, + ) + + +def run_pre_grad_passes( + model_: GraphModule, example_inputs_: Sequence[InputType] +) -> GraphModule: + # "before_pre_grad_graph" is used in inductor provenance + # tracking highlighter front-end. + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "before_pre_grad_graph", + "encoding": "string", + }, + payload_fn=lambda: model_.print_readable( + print_output=False, include_stride=True, include_device=True + ) + + f"\n\n # graph id: {id(model_.graph)}", + ) + pre_grad_graphs_log.debug( + "%s", + lazy_format_graph_code( + "BEFORE PRE GRAD", + model_, + include_stride=True, + include_device=True, + colored=True, + ), + ) + torch._inductor.debug._pre_grad_graph_id = id(model_.graph) + + if config.effective_provenance_tracking_level() == 1: + for node in model_.graph.nodes: + if node.stack_trace: + torch._inductor.debug._inductor_pre_grad_node_stack_trace[node.name] = ( + node.stack_trace + ) + + model_ = _recursive_pre_grad_passes(model_, example_inputs_) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "after_pre_grad_graph", + "encoding": "string", + }, + payload_fn=lambda: model_.print_readable( + print_output=False, include_stride=True, include_device=True + ) + + f"\n\n # graph id: {id(model_.graph)}", + ) + return model_ + + +@dataclass(frozen=True) +class _ConstantDecompTable(Generic[_P, _T]): + """ + Picklable wrapper around a user-supplied decomposition dict. + + This module-level class is addressable as (module, qualname), so pickle can + serialize an instance by reducing its single field. + """ + + table: dict[OpOverload, Callable[_P, _T]] + + def __call__(self) -> dict[OpOverload, Callable[_P, _T]]: + return self.table + + +def compile_fx( + model_: GraphModule, + example_inputs_: Sequence[InputType], + inner_compile: Callable[..., OutputCode] = compile_fx_inner, + config_patches: dict[str, Any] | None = None, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, + ignore_shape_env: bool = False, + compile_region_name: str | None = None, +) -> CompileFxOutput: + """ + Main entry point for compiling given FX graph. Despite the fact that this + lives in :mod:`torch._inductor`, this function is responsible for calling + into AOT Autograd (and we will eventually get a callback to + ``inner_compile`` to perform actual compilation. In other words, this + function orchestrates end-to-end compilation for the inductor backend when + you use :func:`torch.compile`. + + NB: This function TAKES OWNERSHIP of the input ``model_`` and can potentially + mutate it! Make a copy if you need to preserve the original GraphModule. + """ + if decompositions is not None: + get_decomp_fn: Callable[..., dict[Any, Callable[..., Any]]] = ( + _ConstantDecompTable(decompositions) + ) + else: + get_decomp_fn = select_decomp_table + + # Some arguments trigger a recursive call to compile_fx. Handle these + # short circuits first, before anything else + + from torch._inductor.compiler_bisector import CompilerBisector + + if CompilerBisector.disable_subsystem("inductor", "pre_grad_graph"): + # pyrefly: ignore [bad-return] + return model_ + + if config_patches: + with config.patch(config_patches): + return compile_fx( + model_, + example_inputs_, + # need extra layer of patching as backwards is compiled out of scope + inner_compile=config.patch(config_patches)(inner_compile), + decompositions=decompositions, + ignore_shape_env=ignore_shape_env, + compile_region_name=compile_region_name, + ) + + # Keep region names out of graph_kwargs so they don't perturb FX cache keys. + inner_compile = functools.partial( + inner_compile, + compile_region_name=compile_region_name, + ) + + # Wake up the AsyncCompile subproc pool as early as possible (if there's cuda). + if any( + isinstance(e, torch.Tensor) and e.device.type in ("cuda", "xpu") + for e in example_inputs_ + ): + torch._inductor.async_compile.AsyncCompile.wakeup() + + if config.cpp_wrapper or config.fx_wrapper: + from torch.fx.experimental.proxy_tensor import _coor_enabled + + if _coor_enabled(): + # cpp_wrapper/AOTInductor bakes the compile-time device index into the C++ + # device guard, and fx_wrapper's device-context codegen is a no-op (see + # wrapper_fxir.py); neither is rank-portable, so refuse rather than silently + # emit a non-portable artifact. + # + # NB cudagraphs is deliberately NOT refused here. Its device dependence + # (CompiledFxGraph.device_idxs, which cudagraph_post_compile passes to + # cudagraphify as device_index) lives in the wrapper-level artifact, and that + # artifact is not shared across ranks today: the FX graph cache key embeds the + # device, so each rank builds its own. Only the kernel/cubin layer is shared, + # and that is what the device-agnostic launcher handles. Whoever makes the FX + # graph cache key device-agnostic must revisit device_idxs (and re-check that + # graph-partition functions still define _coor_device_idx in their own scope) + # before cudagraphs can ride on a shared artifact. + raise RuntimeError( + "compile-on-one-rank (device-as-parameter) is not supported with " + "cpp_wrapper/AOTInductor or fx_wrapper: the device guard bakes the " + "compile-time device index, which is not rank-portable." + ) + from torch._export.non_strict_utils import _fakify_script_objects + + cpp_wrapper_config = config.cpp_wrapper + fx_wrapper_config = config.fx_wrapper + + with ( + config.patch(get_cpp_wrapper_config()), + V.set_real_inputs(example_inputs_), + ): + inputs_: Sequence[InputType] = ( + _extract_inputs_from_exported_gm(model_, example_inputs_) + if isinstance(model_, GraphModule) + else example_inputs_ + ) + fake_mode = detect_fake_mode(inputs_) + with _fakify_script_objects(model_, inputs_, {}, fake_mode) as ( + patched_mod, + fake_args, + _, + _, + _, + ): + return _maybe_wrap_and_compile_fx_main( + patched_mod, + fake_args, + inner_compile=functools.partial( + inner_compile, + cpp_wrapper=cpp_wrapper_config, + fx_wrapper=fx_wrapper_config, + ), + ignore_shape_env=ignore_shape_env, + get_decomp_fn=get_decomp_fn, + compile_region_name=compile_region_name, + ) + + return _maybe_wrap_and_compile_fx_main( + model_, + example_inputs_, + inner_compile, + ignore_shape_env, + get_decomp_fn=get_decomp_fn, + compile_region_name=compile_region_name, + ) + + +def _extract_inputs_from_exported_gm( + gm: GraphModule, example_inputs_: Sequence[InputType] +) -> Sequence[InputType]: + fake_inputs = [ + node.meta.get("val") for node in gm.graph.nodes if node.op == "placeholder" + ] + + if not config.fx_wrapper: + # Replace non-tensor inputs with Nones + # constant scalars embedded in the graph + # symbolic scalars (symint) are not supported in non-fx_wrapper mode + fake_inputs = [ + inp if isinstance(inp, torch.Tensor) else None for inp in fake_inputs + ] + + if any(v is not None for v in fake_inputs): + # Validate devices before switching to fake tensors. + for idx, fi, i in zip(count(), fake_inputs, example_inputs_): + if fi is not None and isinstance(fi, torch.Tensor): + if not isinstance(i, torch.Tensor): + raise AssertionError( + f"Expected example input at position #{idx} to be a Tensor, got {type(i)}" + ) + if fi.device != i.device: + raise ValueError( + f"Device mismatch between fake input and example input at position #{idx}: " + f"{fi.device} vs {i.device}. If the model was exported via torch.export(), " + "make sure torch.export() and torch.aot_compile() run on the same device." + ) + return fake_inputs + + return example_inputs_ + + +def _maybe_wrap_and_compile_fx_main( + model_: GraphModule, + example_inputs_: Sequence[InputType], + inner_compile: Callable[..., OutputCode], + ignore_shape_env: bool, + *, + get_decomp_fn: Callable[..., dict[Any, Callable[..., Any]]] = select_decomp_table, + compile_region_name: str | None = None, +) -> CompileFxOutput: + """ + Part of compile_fx, called after patching configs. + + Ultimately we want to call _compile_fx_main, where the actual work happens. + But under various conditions, various forms of wrapping might be needed + around _compile_fx_main. + """ + # Each wrapper below takes a self-contained compile_gm function which is + # called inside the wrapper. This just recursively calls this function. + compile_gm = functools.partial( + _maybe_wrap_and_compile_fx_main, + inner_compile=inner_compile, + ignore_shape_env=ignore_shape_env, + get_decomp_fn=get_decomp_fn, + compile_region_name=compile_region_name, + ) + if not graph_returns_tuple(model_): + return make_graph_return_tuple(model_, example_inputs_, compile_gm) + + if isinstance(model_, GraphModule) and isinstance( + model_.graph._codegen, _PyTreeCodeGen + ): + # this graph is the result of dynamo.export() + return handle_dynamo_export_graph(model_, example_inputs_, compile_gm) + + if any(isinstance(x, (list, tuple, dict)) for x in example_inputs_): + # NB: this short circuit never occurs for Dynamo produced graphs + # (which are pre-flattened) + return flatten_graph_inputs(model_, example_inputs_, compile_gm) + + # Finally do the actual work! + return _compile_fx_main( + model_, + example_inputs_, + inner_compile, + ignore_shape_env, + get_decomp_fn=get_decomp_fn, + compile_region_name=compile_region_name, + ) + + +def _compile_fx_main( + model_: GraphModule, + example_inputs_: Sequence[InputType], + inner_compile: Callable[..., OutputCode], + ignore_shape_env: bool, + *, + get_decomp_fn: Callable[..., dict[Any, Callable[..., Any]]] = select_decomp_table, + compile_region_name: str | None = None, +) -> CompileFxOutput: + """ + Main part of compile_fx, called after wrapping is done. + + Roughly speaking, here the steps will be: + (1) apply pre-grad passes + (2) create `fw_compiler` and `bw_compiler` functions out of `inner_compile` + (3) call aot_autograd, which: + - (3a) creates a joint graph with `decompositions`, + - (3b) partitions it with `partition_fn` into fw and bw graphs (applying joint-graph passes), + - (3c) calls `fw_compiler` and `bw_compiler` on those graphs (applying post-grad passes) + - (3d) finally, assembles the fw and bw compiled functions back together and returns. + """ + with ( + _use_lazy_graph_module(dynamo_config.use_lazy_graph_module), + enable_python_dispatcher(), + torch.fx.traceback.preserve_node_meta( + config.effective_provenance_tracking_level() == 1 + ), + torch._inductor.debug.reset_provenance_globals(), + ): + # Note: Pre-grad passes are now run inside aot_module_simplified (via the + # pre_grad_passes callback) after the cache lookup. + + if config._raise_error_for_testing: + raise AssertionError("config._raise_error_for_testing is set") + + num_example_inputs = len(example_inputs_) + + compiler_config_extra = create_compiler_config_extra(model_) + + decompositions = get_decomp_fn() + inner_compile = functools.partial(inner_compile, get_decomp_fn=get_decomp_fn) + + def fw_compiler_base( + gm: GraphModule, + example_inputs: Sequence[InputType], + is_inference: bool, + ) -> OutputCode: + with dynamo_utils.dynamo_timed("compile_fx..fw_compiler_base"): + if isinstance(model_, GraphModule): + num_orig_model_outputs = get_num_model_outputs(model_) + else: + num_orig_model_outputs = get_num_model_outputs(gm) + return compile_fx_forward( + gm, + example_inputs, + num_orig_model_outputs=num_orig_model_outputs, + num_example_inputs=num_example_inputs, + compiler_config_extra=compiler_config_extra, + inner_compile=inner_compile, + is_inference=is_inference, + ) + + fw_compiler: Callable[[GraphModule, Sequence[InputType]], OutputCode] = ( + functools.partial(fw_compiler_base, is_inference=False) + ) + fw_compiler = SerializableAOTDispatchCompiler(OutputCode, fw_compiler) + + if config.freezing and not torch.is_grad_enabled(): + inference_compiler: Callable[..., Any] = functools.partial( + fw_compiler_freezing, + dynamo_model=model_, + num_example_inputs=num_example_inputs, + inner_compile=inner_compile, + cudagraphs=compiler_config_extra.cudagraphs, + graph_id=compiler_config_extra.graph_id, + forward_device=compiler_config_extra.forward_device, + ) + else: + inference_compiler = functools.partial(fw_compiler_base, is_inference=True) + inference_compiler = SerializableAOTDispatchCompiler( + OutputCode, inference_compiler + ) + + @compile_time_strobelight_meta(phase_name="backward") + def bw_compiler( + gm: GraphModule, example_inputs: Sequence[InputType] + ) -> OutputCode: + with ( + dynamo_utils.dynamo_timed("compile_fx..bw_compiler"), + ): + return compile_fx_backward( + gm, + example_inputs, + compiler_config_extra=compiler_config_extra, + inner_compile=inner_compile, + ) + + bw_compiler = SerializableAOTDispatchCompiler(OutputCode, bw_compiler) + + fake_mode = detect_fake_mode( + example_inputs_ + ) or torch._subclasses.FakeTensorMode(allow_non_fake_inputs=True) + tracing_context = ( + torch._guards.TracingContext.try_get() + or torch._guards.TracingContext(fake_mode) + ) + + if V.aot_compilation and not config.enable_autograd_for_aot: + from .utils import is_valid_aoti_model_name + + is_valid_aoti_model_name() + + # Pre-grad passes for the aot_autograd path are run inside + # aot_module_simplified after the cache lookup. The + # aot_export_module path doesn't use that cache so run them here. + if isinstance(model_, GraphModule): + model_ = run_pre_grad_passes(model_, example_inputs_) + + with functorch_config.patch( + unlift_effect_tokens=True, + selective_decompose=config.selective_decompose, + ): + gm, graph_signature = aot_export_module( + model_, + example_inputs_, + trace_joint=False, + decompositions=decompositions, + ) + if not isinstance(gm, GraphModule): + raise AssertionError( + f"Expected GraphModule from aot_export_module, got {type(gm)}" + ) + from torch._export.utils import _detect_fake_mode_from_gm + + fake_mode = _detect_fake_mode_from_gm(gm) # type: ignore[assignment] + # aot_export_module doesn't account for constant tensor attributes + # so we end up having tensors that don't have fake vals attached. + # This can happen when upstream export is non-strict where we + # preserve the original module params/buffers. Once AOTI switches + # to ep.run_decompositions() flow to lower to post-autograd opset + # this will go away. + for node in gm.graph.nodes: + if node.op == "get_attr" and "val" not in node.meta: + target = attrgetter(node.target)(gm) + if isinstance(target, torch.Tensor): + if fake_mode is None: + raise AssertionError( + "Expected fake_mode to be set for get_attr tensor node" + ) + node.meta["val"] = fake_mode.from_tensor( + target, static_shapes=True + ) + elif isinstance(target, torch.ScriptObject) or is_custom_class( + type(target) + ): + node.meta["val"] = ( + torch._library.fake_class_registry.maybe_to_fake_obj( + fake_mode, target + ) + ) + elif isinstance(target, FakeScriptObject): + node.meta["val"] = target + + unlifted_gm = _unlift_graph(model_, gm, graph_signature) + if "dynamo_flat_name_to_original_fqn" in model_.meta: + unlifted_gm.meta["dynamo_flat_name_to_original_fqn"] = model_.meta[ + "dynamo_flat_name_to_original_fqn" + ] + + if "dynamo_compile_id" in model_.meta: + unlifted_gm.meta["dynamo_compile_id"] = model_.meta["dynamo_compile_id"] + + # Disable amp as in aot_dispatch_autograd (https://github.com/pytorch/pytorch/pull/86515) + # In inference_compiler (fw_compiler_base), _recursive_joint_graph_passes will call into + # _sfdp_init() to register patterns. + # When fallback_random is set to True, the sdpa patterns will be traced during runtime. + # If amp is turned on, the traced FP32 patterns will have prims.convert_element_type which + # will be the same as the generated FP16 patterns. + disable_amp = torch._C._is_any_autocast_enabled() + context = ( + torch._C._DisableAutocast if disable_amp else contextlib.nullcontext + ) + with V.set_fake_mode(fake_mode), compiled_autograd._disable(), context(): + return inference_compiler(unlifted_gm, example_inputs_) + + with ( + V.set_fake_mode(fake_mode), + torch._guards.tracing(tracing_context), + compiled_autograd._disable(), + functorch_config.patch( + unlift_effect_tokens=True, + selective_decompose=config.selective_decompose, + ), + ): + try: + return dynamo_common.aot_autograd( + fw_compiler=fw_compiler, + bw_compiler=bw_compiler, + inference_compiler=inference_compiler, + decompositions=decompositions, + partition_fn=partition_fn, + keep_inference_input_mutations=True, + compiler_config_extra=compiler_config_extra, + ignore_shape_env=ignore_shape_env, + pre_grad_passes=run_pre_grad_passes, + compile_region_name=compile_region_name, + )(model_, example_inputs_) + except ShortenTraceback as e: + # We will also shorten the traceback inside dynamo. + # This is only useful if inductor is called directly with an FX graph. + raise e.remove_dynamo_frames() from None # see TORCHDYNAMO_VERBOSE=1 + + +def graph_returns_tuple(gm: GraphModule) -> bool: + """True if a FX graph returns a tuple""" + if not isinstance(gm, GraphModule): + return True # can't check this, assume true + (rv,) = output_node(gm).args + if isinstance(rv, (list, tuple)): + return True + if ( + isinstance(rv, torch.fx.node.Node) + and hasattr(rv.target, "_schema") + and len(rv.target._schema.returns) > 1 + and all(str(ret.type) == "Tensor" for ret in rv.target._schema.returns) + ): + # for graphs whose result is one node with multiple outputs + return True + return False + + +def make_graph_return_tuple( + gm: GraphModule, + inputs: Sequence[InputType], + compile_gm: Callable[..., Any], +) -> Callable[..., Any]: + """ + Mutate gm so it returns a tuple. This is only needed for graphs + not created by torchdynamo that return non-tuples. + """ + node = output_node(gm) + (rv,) = node.args + rv, spec = pytree.tree_flatten(rv) + with gm.graph.inserting_before(node): + gm.graph.output(rv) + gm.graph.erase_node(node) + gm.recompile() + if not graph_returns_tuple(gm): + raise AssertionError("Expected graph to return a tuple") + + compiled_fn = compile_gm(gm, inputs) + + @functools.wraps(compiled_fn) + def wrapper(*args: Any, **kwargs: Any) -> Any: + return pytree.tree_unflatten(compiled_fn(*args, **kwargs), spec) + + return wrapper + + +def handle_dynamo_export_graph( + gm: GraphModule, + inputs: Sequence[InputType], + compile_gm: Callable[..., Any], +) -> Callable[..., Any]: + """ + `torch._dynamo.export` embeds pytrees in the FX graph codegen object, + convert that to a normal FX graph so inductor can compile it. + """ + codegen = gm.graph._codegen + gm.graph._codegen = torch.fx.graph.CodeGen() + gm.recompile() + + compiled_fn = compile_gm(gm, codegen.process_inputs(*inputs)) + + @functools.wraps(compiled_fn) # type: ignore[misc] + def wrapper(*args: Any) -> Any: + return codegen.process_outputs(compiled_fn(*codegen.process_inputs(*args))) + + return wrapper + + +def _check_triton_bf16_support(graph: GraphLowering) -> None: + def warn_and_skip(device: torch.device | None) -> Never: + from torch._dynamo.exc import SkipFrame + + if device is None: + raise AssertionError("Expected device to be set for bf16 support check") + device_interface = get_interface_for_device(device.type) + device_props = device_interface.get_device_properties(device) + warnings.warn( + f"{device_props.name} does not support bfloat16 compilation natively, skipping" + ) + raise SkipFrame("BF16 is not supported") + + for node in itertools.chain(graph.graph_inputs.values(), graph.graph_outputs): + if not isinstance(node, IRNode): + continue + device_type = get_device_type(node) + if ( + not device_type + or not is_gpu(device_type) + or node.get_dtype() != torch.bfloat16 + ): + continue + device_interface = get_interface_for_device(device_type) + if device_interface.is_bf16_supported(including_emulation=False): + return + warn_and_skip(node.get_device()) + + +def _aoti_flatten_inputs( + gm: torch.fx.GraphModule, + args: list[Any] | tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + *, + options: dict[str, Any] | None = None, +) -> tuple[list[Any], dict[str, Any]]: + """ + Flatten the inputs to the graph module and return the flat inputs and options. + Add "aot_inductor.serialized_in_spec" and "aot_inductor.serialized_out_spec" to the options. + """ + # pyrefly: ignore [missing-module-attribute] + from .compile_fx import graph_returns_tuple + + if not graph_returns_tuple(gm): + raise AssertionError( + "Graph output must be a tuple(). This is so that we can avoid " + "pytree processing of the outputs. Please change the module to " + "have tuple outputs." + ) + + # We will serialize the pytree info into the .so as constant strings + in_spec = None + out_spec = None + if isinstance(gm.graph._codegen, torch.fx.graph._PyTreeCodeGen): + codegen = gm.graph._codegen + gm.graph._codegen = torch.fx.graph.CodeGen() + gm.recompile() + + if codegen.pytree_info.in_spec is not None: + in_spec = codegen.pytree_info.in_spec + if codegen.pytree_info.out_spec is not None: + out_spec = codegen.pytree_info.out_spec + + else: + if hasattr(gm, "_in_spec"): + in_spec = gm._in_spec + if hasattr(gm, "_out_spec"): + out_spec = gm._out_spec + + serialized_in_spec = pytree.treespec_dumps(in_spec) if in_spec is not None else "" + serialized_out_spec = ( + pytree.treespec_dumps(out_spec) if out_spec is not None else "" + ) + + flat_args_with_path, received_spec = pytree.tree_flatten_with_path( + (args, kwargs or {}) + ) + + if any(isinstance(x[1], torch.ScriptObject) for x in flat_args_with_path): + from torch._dynamo.exc import UserError, UserErrorType + + raise UserError( + UserErrorType.INVALID_INPUT, + "TorchBind objects found in inputs. TorchBind object inputs are not supported in AOTInductor. " + "TorchBind objects can only be attributes.", + ) + + # Replace non-tensor (constant) inputs with Nones, since these are not being + # used anyways by the graph + flat_example_inputs = [ + x[1] if isinstance(x[1], torch.Tensor) else None for x in flat_args_with_path + ] + + if in_spec is not None and received_spec != in_spec: + raise ValueError( + "Trying to flatten user inputs with exported input tree spec: \n" + f"{in_spec}\n" + "but actually got inputs with tree spec of: \n" + f"{received_spec}" + ) + + options = ( + { + "aot_inductor.serialized_in_spec": serialized_in_spec, + "aot_inductor.serialized_out_spec": serialized_out_spec, + } + if options is None + else { + **options, + "aot_inductor.serialized_in_spec": serialized_in_spec, + "aot_inductor.serialized_out_spec": serialized_out_spec, + } + ) + return flat_example_inputs, options + + +def autograd_cache_key( + graph, + example_inputs, + ignore_shape_env: bool, + decompositions=None, +): + if config.cpp_wrapper or config.fx_wrapper: + raise RuntimeError( + "autograd_cache_key is not supported with cpp_wrapper or fx_wrapper" + ) + + decompositions = ( + decompositions if decompositions is not None else select_decomp_table() + ) + # compile_fx applies these graph transforms before reaching _compile_fx_main. + # Neither occurs on the torch.compile/Dynamo path (which always produces + # tuple-returning, pre-flattened graphs). Not supported by this API. + if isinstance(graph, GraphModule) and not graph_returns_tuple(graph): + raise NotImplementedError( + "autograd_cache_key does not support graphs that don't return a tuple" + ) + if any(isinstance(x, (list, tuple, dict)) for x in example_inputs): + raise NotImplementedError( + "autograd_cache_key does not support nested container inputs" + ) + + compiler_config_extra = create_compiler_config_extra(graph) + + # These context managers replicate the ones that _compile_fx_main sets up + # before calling aot_autograd, so that the config snapshot captured by + # autograd_cache_key is identical to a real compile_fx run: + # _compile_fx_main outer with-block: _use_lazy_graph_module, + # enable_python_dispatcher, preserve_node_meta, + # reset_provenance_globals + # _compile_fx_main aot_autograd with-block: V.set_fake_mode, + # torch._guards.tracing, compiled_autograd._disable, + # functorch_config.patch + + fake_mode = detect_fake_mode(example_inputs) or torch._subclasses.FakeTensorMode( + allow_non_fake_inputs=True + ) + tracing_context = ( + torch._guards.TracingContext.try_get() + or torch._guards.TracingContext(fake_mode) + ) + + with ( + functorch_config.patch( + unlift_effect_tokens=True, selective_decompose=config.selective_decompose + ), + _use_lazy_graph_module(dynamo_config.use_lazy_graph_module), + enable_python_dispatcher(), + torch.fx.traceback.preserve_node_meta( + config.effective_provenance_tracking_level() == 1 + ), + torch._inductor.debug.reset_provenance_globals(), + V.set_fake_mode(fake_mode), + torch._guards.tracing(tracing_context), + compiled_autograd._disable(), + ): + return aot_autograd.autograd_cache_key( + graph, + example_inputs, + ignore_shape_env=ignore_shape_env, + decompositions=decompositions, + compiler_config_extra=compiler_config_extra, + keep_inference_input_mutations=True, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_async.py b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_async.py new file mode 100644 index 0000000000000000000000000000000000000000..130de46dbf7a9f36239a177b666808458ed86a2b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_async.py @@ -0,0 +1,415 @@ +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass +from typing import Any, TYPE_CHECKING +from typing_extensions import final, override + +import torch._inductor.async_compile # noqa: F401 required to warm up AsyncCompile pools +from torch._inductor.output_code import ( + CompiledFxGraph, + CompiledFxGraphConstants, + OutputCode, +) + +from .compile_fx import _CompileFxKwargs, _InProcessFxCompile, FxCompile + + +# When async compile works with cache, remove the disabling below +BUG_CACHES_DONT_WORK_WITH_ASYNC = True + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + from concurrent.futures import Future + + from torch._inductor.utils import InputType + from torch.fx import GraphModule + + from .compile_fx_ext import _OutOfProcessFxCompile, _WireProtocolPickledOutput + + +@dataclass +class _PostCompileData: + example_inputs: Sequence[InputType] + constants: CompiledFxGraphConstants + graph_kwargs: _CompileFxKwargs + + +@dataclass +class ProgressiveCompilationState: + progression_futures: deque[Future[_WireProtocolPickledOutput]] + callback: Callable[[_WireProtocolPickledOutput], OutputCode] + post_compile_data: _PostCompileData | None + + def check_and_get_ready_stage(self) -> int: + """Check if any progression stage is ready and return its index, or -1 if none are ready.""" + if not self.progression_futures: + return -1 + + stage_index = -1 + if self.post_compile_data: + for i, future in enumerate(self.progression_futures): + if future.done(): + stage_index = i + + return stage_index + + def switch_to_progression_stage(self, stage_index: int) -> tuple[OutputCode, bool]: + """ + Switch to the specified progression stage and return the optimized output code. + Returns a tuple of (optimized_output_code, should_clear_compilation_state). + """ + future = self.progression_futures[stage_index] + if future is None: + raise AssertionError("expected future to be not None") + optimized_output_code = self.callback(future.result()) + + if pcd := self.post_compile_data: + optimized_output_code.post_compile( + pcd.example_inputs, pcd.constants, pcd.graph_kwargs + ) + + # Clear earlier progression futures to free memory + for _ in range(stage_index + 1): + self.progression_futures.popleft() + + # Return whether all compilation state should be cleared + should_clear_state = not self.progression_futures + return optimized_output_code, should_clear_state + + +# _AsyncOutputCode handles the actual management of waiting for an +# out-of-process compile to finish and then switching over to it. +@final +class _AsyncOutputCode(OutputCode): + _eager_fn: Callable[..., Any] | None + _output_code: OutputCode | None + _future: Future[_WireProtocolPickledOutput] | None + _callback: Callable[[_WireProtocolPickledOutput], OutputCode] + _post_compile_data: _PostCompileData | None = None + _boxed_call: bool # Copied from the forward/output_code + + def __init__( + self, + # eager_fn is run until the future is finished. + eager_fn: Callable[..., Any], + # this responds with the result of the out-of-process compile when it's + # ready. + future: Future[_WireProtocolPickledOutput], + # this callback gets called to turn the _WireProtocolPickledOutput into an OutputCode + callback: Callable[[_WireProtocolPickledOutput], OutputCode], + ) -> None: + self._eager_fn = eager_fn + self._boxed_call = getattr(eager_fn, "_boxed_call", False) + self._output_code = None + + self._future = future + self._callback = callback + + @override + def __call__(self, *args: Any) -> Any: + if self._future is not None and self._future.done(): + args = self._switch_to_compiled_fn(args) + + if eager_fn := self._eager_fn: + _AsyncFxCompile._stat_eager_runs += 1 + return eager_fn(*args) + + else: + _AsyncFxCompile._stat_compiled_runs += 1 + if self._output_code is None: + raise AssertionError("expected self._output_code to be not None") + return self._output_code.__call__(*args) + + # Takes and returns the args (converted to the "right" boxed mode) + def _switch_to_compiled_fn(self, args: tuple[Any, ...]) -> tuple[Any, ...]: + if self._future is None: + raise AssertionError("expected self._future to be not None") + + # TODO: If the future ended in an exception do we want to continue + # running eager or hit the exception now? + f, self._future = self._future, None + output_code = self._callback(f.result()) + + if pcd := self._post_compile_data: + self._post_compile_data = None + + output_code.post_compile( + pcd.example_inputs, pcd.constants, pcd.graph_kwargs + ) + + self._output_code = output_code + self._eager_fn = None + boxed_call = getattr(output_code, "_boxed_call", False) + + if self._boxed_call != boxed_call: + if self._boxed_call: + # Was boxed, now unboxed + args = args[0] if len(args) > 0 else () + else: + # Was unboxed, now boxed + args = (args,) + + self._boxed_call = boxed_call + return args + + @override + def post_compile( + self, + example_inputs: Sequence[InputType], + constants: CompiledFxGraphConstants, + graph_kwargs: _CompileFxKwargs, + ) -> None: + if self._eager_fn is not None: + self._post_compile_data = _PostCompileData( + example_inputs, constants, graph_kwargs + ) + else: + if self._output_code is None: + raise AssertionError("expected self._output_code to be not None") + self._output_code.post_compile(example_inputs, constants, graph_kwargs) + + +# Given an FxCompile for an out-of-process compile _AsyncFxCompile will run +# eager until the compiled artifact is ready then it will automatically switch +# over to using the compiled version. +@final +class _AsyncFxCompile(FxCompile): + _compile: _OutOfProcessFxCompile + + # Some debugging stats: + # Number of times we started a background compile. + _stat_bg_started: int = 0 + # Number of times we finished a background compile. + _stat_bg_finished: int = 0 + # Number of times we ran "eager" + _stat_eager_runs: int = 0 + # Number of times we ran our compiled (out-of-process) artifact + _stat_compiled_runs: int = 0 + + def __init__(self, compile: _OutOfProcessFxCompile) -> None: + self._compile = compile + + @classmethod + def _reset_stats(cls) -> None: + cls._stat_bg_started = 0 + cls._stat_bg_finished = 0 + cls._stat_eager_runs = 0 + cls._stat_compiled_runs = 0 + + @override + def codegen_and_compile( + self, + gm: GraphModule, + example_inputs: Sequence[InputType], + inputs_to_check: Sequence[int], + graph_kwargs: _CompileFxKwargs, + ) -> OutputCode: + eager_compile = _InProcessFxCompile() + eager_compile.compile_region_name = self.compile_region_name + eager_output_code = eager_compile.codegen_and_compile( + gm, example_inputs, inputs_to_check, graph_kwargs + ) + + # This is similar to _SerializedFxCompile.codegen_and_compile() but + # handles the async routing. + + serialized = self._compile.serialize_compile( + gm, example_inputs, inputs_to_check, graph_kwargs + ) + if not serialized: + # We can't serialize - just return the eager OutputCode + return eager_output_code + + inputs, constants = serialized + + _AsyncFxCompile._stat_bg_started += 1 + f = self._compile._send_to_child_async(inputs) + + # This is called by _switch_to_compiled_fn() when f has a result... + def callback(pickled_output: _WireProtocolPickledOutput) -> OutputCode: + _AsyncFxCompile._stat_bg_finished += 1 + output = pickled_output.deserialize(constants) + if isinstance(output.graph, CompiledFxGraph): + output.graph.compile_region_name = self.compile_region_name + self._compile._postprocess(output) + return output.graph + + return _AsyncOutputCode(eager_output_code, f, callback) + + +# _ProgressiveOutputCode handles running a fast compile first, then hot-swapping +# to a more optimized version when the expensive compile finishes. +@final +class _ProgressiveOutputCode(OutputCode): + _fast_output_code: OutputCode | None + _optimized_output_code: OutputCode | None + _compilation_state: ProgressiveCompilationState | None + # _boxed_call state is effectively cached (we sometimes wrap unboxed w/ + # lambdas to box them) so we can't change it mid-way. Since _boxed_call=True + # is more common let's default to that and we'll convert if necessary. + _boxed_call: bool = True + + def __init__( + self, + # Fast compile that runs faster than the progressive compiles + fast_output_code: OutputCode, + # Futures for the progressive optimized compiles + progression_futures: Sequence[Future[_WireProtocolPickledOutput]], + # Callback to convert the optimized result to OutputCode + callback: Callable[[_WireProtocolPickledOutput], OutputCode], + ) -> None: + self._fast_output_code = fast_output_code + self._optimized_output_code = None + self._compilation_state = ProgressiveCompilationState( + progression_futures=deque(progression_futures), + callback=callback, + post_compile_data=None, + ) + + @override + def __call__(self, args: Sequence[Any]) -> Any: + # Check if any newer progression stage is ready and switch to it + self._check_and_switch_progression() + + if self._optimized_output_code is not None: + _ProgressiveFxCompile._stat_optimized_runs += 1 + output_code = self._optimized_output_code + else: + _ProgressiveFxCompile._stat_fast_runs += 1 + if self._fast_output_code is None: + raise AssertionError("expected self._fast_output_code to be not None") + output_code = self._fast_output_code + + boxed_call = getattr(output_code, "_boxed_call", False) + if boxed_call: + res = output_code.__call__(args) + else: + res = output_code.__call__(*args) + return res + + def _check_and_switch_progression(self) -> None: + if not self._compilation_state: + return + + stage_index = self._compilation_state.check_and_get_ready_stage() + if stage_index == -1: + # no futures are ready + return + + self._switch_to_progression_stage(stage_index) + + def _switch_to_progression_stage(self, stage_index: int) -> None: + if self._compilation_state is None: + raise AssertionError("expected self._compilation_state to be not None") + optimized_output_code, should_clear_state = ( + self._compilation_state.switch_to_progression_stage(stage_index) + ) + + self._optimized_output_code = optimized_output_code + self._fast_output_code = None + + # Clear all compilation state if no more progression futures are left + if should_clear_state: + self._compilation_state = None + + @override + def post_compile( + self, + example_inputs: Sequence[InputType], + constants: CompiledFxGraphConstants, + graph_kwargs: _CompileFxKwargs, + ) -> None: + if self._fast_output_code is None: + raise AssertionError("expected self._fast_output_code to be not None") + self._fast_output_code.post_compile(example_inputs, constants, graph_kwargs) + + if self._compilation_state is None: + raise AssertionError("expected self._compilation_state to be not None") + # Store for later when optimized version is ready + self._compilation_state.post_compile_data = _PostCompileData( + example_inputs, constants, graph_kwargs + ) + + +# _ProgressiveFxCompile runs a fast compile immediately, then kicks off +# progressive compiles in the background and hot-swaps when they're ready. +@final +class _ProgressiveFxCompile(FxCompile): + _fast_compile: FxCompile + _optimized_compile: _OutOfProcessFxCompile + _progression_configs: list[dict[str, Any]] + + # Debugging stats + _stat_bg_started: int = 0 + _stat_bg_finished: int = 0 + _stat_fast_runs: int = 0 + _stat_optimized_runs: int = 0 + + def __init__( + self, + fast_compile: FxCompile, + optimized_compile: _OutOfProcessFxCompile, + progression_configs: list[dict[str, Any]], + ) -> None: + self._fast_compile = fast_compile + self._optimized_compile = optimized_compile + self._progression_configs = progression_configs + + @classmethod + def _reset_stats(cls) -> None: + cls._stat_bg_started = 0 + cls._stat_bg_finished = 0 + cls._stat_fast_runs = 0 + cls._stat_optimized_runs = 0 + + @override + def codegen_and_compile( + self, + gm: GraphModule, + example_inputs: Sequence[InputType], + inputs_to_check: Sequence[int], + graph_kwargs: _CompileFxKwargs, + ) -> OutputCode: + import torch._inductor.config as inductor_config + + progression_futures: list[Future[_WireProtocolPickledOutput]] = [] + + for config in self._progression_configs: + with inductor_config.patch(config): + _ProgressiveFxCompile._stat_bg_started += 1 + + # Start the progressive compiles in the background + serialized = self._optimized_compile.serialize_compile( + gm, example_inputs, inputs_to_check, graph_kwargs + ) + + if not serialized: + continue + + inputs, constants = serialized + future = self._optimized_compile._send_to_child_async(inputs) + progression_futures.append(future) + + fast_output_code = self._fast_compile.codegen_and_compile( + gm, example_inputs, inputs_to_check, graph_kwargs + ) + + if not progression_futures: + # All async compile attempts failed - just return the fast version + return fast_output_code + + # Callback to handle the optimized result. + # This callback may be called multiple times, once for each progressive level completed, + # but may be skipped if a level either never completes or if a more optimal level + # completes before a less optimal one is switched to. + def callback(pickled_output: _WireProtocolPickledOutput) -> OutputCode: + _ProgressiveFxCompile._stat_bg_finished += 1 + output = pickled_output.deserialize(constants) + if isinstance(output.graph, CompiledFxGraph): + output.graph.compile_region_name = self.compile_region_name + self._optimized_compile._postprocess(output) + return output.graph + + return _ProgressiveOutputCode(fast_output_code, progression_futures, callback) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_ext.py b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..c6e3bf8f779a370a1af446cb80012b48751cffac --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_ext.py @@ -0,0 +1,729 @@ +from __future__ import annotations + +import contextlib +import dataclasses +import functools +import logging +import os +import queue +import sys +import tempfile +import warnings +from abc import abstractmethod +from dataclasses import dataclass +from typing import Any, TYPE_CHECKING, TypeGuard +from typing_extensions import final, override, Self + +import torch._inductor.async_compile +import torch.fx +from torch._inductor.codecache import BypassFxGraphCache, FxGraphCache +from torch._inductor.metrics import CachedMetricsDeltas, CachedMetricsHelper +from torch._inductor.output_code import ( + CompiledFxGraph, + CompiledFxGraphConstants, + CompiledFxGraphConstantsWithGm, + OutputCode, +) +from torch._inductor.utils import patch_subprocess_env +from torch._subclasses import FakeTensorMode +from torch.utils._ordered_set import OrderedSet + +from . import config +from .compile_fx import _CompileFxKwargs, _InProcessFxCompile, FxCompile, log +from .debug import DebugContext +from .graph import GraphLowering +from .virtualized import V + + +if TYPE_CHECKING: + import types + from collections.abc import Generator, Mapping, Sequence + from concurrent.futures import Future + + from torch._inductor.utils import InputType + from torch.fx import GraphModule + + +def _graph_contains_triton_kernel_wrappers(gm: GraphModule) -> bool: + """ + Check if the graph contains triton kernel wrapper nodes. These nodes contain + references to the kernel_side_table which is process-local and can't be + serialized across processes. + """ + from torch._higher_order_ops.triton_kernel_wrap import ( + triton_kernel_wrapper_functional, + triton_kernel_wrapper_mutation, + ) + + for module in gm.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in module.graph.nodes: + if node.target in ( + triton_kernel_wrapper_functional, + triton_kernel_wrapper_mutation, + ): + return True + return False + + +@dataclass +class _VirtualizedSerializer: + """ + This handles the data for serializing Virtualized. + """ + + # The values here get serialized. We don't grab everything because some of + # the fields can't be serialized. + aot_compilation: Any = None + choices: Any = None + local_buffer_context: Any = None + ops: Any = None + kernel: Any = None + current_node: Any = None + + @classmethod + def serialize(cls) -> _VirtualizedSerializer: + """ + Turn the current state of torch._inductor.virtualized.V into a + serializable structure. + """ + kwargs = {} + for f in dataclasses.fields(cls): + kwargs[f.name] = getattr(V, f.name) + return _VirtualizedSerializer(**kwargs) + + def patch(self) -> _VirtualizedSerializerContextManager: + """ + Returns a context manager which patches the saved values into the + current environment. While patched, any value not listed above will be + poisoned so that reads will raise an error. + """ + return _VirtualizedSerializerContextManager(self) + + +class _VirtualizedSerializerContextManager(contextlib.ExitStack): + """ + Helper for _VirtualizedSerializer.patch() + """ + + def __init__(self, virtualized: _VirtualizedSerializer) -> None: + super().__init__() + self.virtualized = virtualized + + @override + def __enter__(self) -> Self: + super().__enter__() + + for set_name in dir(V): + if not set_name.startswith("set_"): + continue + name = set_name[4:] + name = name.removesuffix("_handler") + set_handler = getattr(V, set_name) + if hasattr(self.virtualized, name): + value = getattr(self.virtualized, name) + else: + # poison any values that we don't serialize so that any + # unset accesses are caught. + value = torch._inductor.virtualized._PoisonedVirtual + self.enter_context(set_handler(value)) + + return self + + +def _is_fallback_handler(op: object) -> bool: + try: + return op._is_fallback_handler # type: ignore[attr-defined] + except AttributeError: + return False + + +class _LoweringSerializer: + """ + This handles the data for serializing lowering.lowering + """ + + # A full implementation would make sure that all lowerings are copied over + # (or at least detected and raise a bypass when a non-standard lowering is + # used). For now we just handle tests by looking for lowerings that were + # overridden with a forced fallback. + fallbacks: OrderedSet[str] + + def __init__(self) -> None: + from . import lowering + + self.fallbacks = OrderedSet( + str(k) for k, v in lowering.lowerings.items() if _is_fallback_handler(v) + ) + + def patch(self) -> _LoweringSerializerContextManager: + return _LoweringSerializerContextManager(self) + + +class _LoweringSerializerContextManager(contextlib.ExitStack): + """ + Helper for _LoweringSerializer.patch() + """ + + def __init__(self, lowering: _LoweringSerializer) -> None: + super().__init__() + self.lowering = lowering + + @override + def __enter__(self) -> Self: + super().__enter__() + + from . import lowering + + for k, v in lowering.lowerings.items(): + name = str(k) + if name in self.lowering.fallbacks: + if not _is_fallback_handler(v): + self.enter_context(lowering.force_fallback(k)) # type: ignore[arg-type] + + return self + + +@dataclass +class _FakeTensorModeSerializer: + allow_non_fake_inputs: bool + + def __init__(self, fake_mode: FakeTensorMode) -> None: + self.allow_non_fake_inputs = fake_mode.allow_non_fake_inputs + self.shape_env = fake_mode.shape_env + + @contextlib.contextmanager + def patch(self, fake_mode: FakeTensorMode) -> Generator[None, None, None]: + saved_allow_non_fake_inputs = fake_mode.allow_non_fake_inputs + fake_mode.allow_non_fake_inputs = self.allow_non_fake_inputs + + yield + + fake_mode.allow_non_fake_inputs = saved_allow_non_fake_inputs + + +@dataclass +class _WireProtocolInput: + """ + For _SerializedFxCompile - encapsulates all the data being transferred + (sent) from the parent to the child. + """ + + gm: torch.fx.GraphModule + example_inputs: Sequence[InputType] + inputs_to_check: Sequence[int] + graph_kwargs: _CompileFxKwargs + tracing_context: torch._guards.TracingContext | None + config: dict[str, object] + virtualized: _VirtualizedSerializer + deterministic_guard_for_testing: ( # type: ignore[name-defined] # mypy bug + torch.testing._internal.common_utils.DeterministicGuard | None + ) + logger_state: _LoggerState + lowering: _LoweringSerializer + fake_tensor_mode: _FakeTensorModeSerializer + + def serialize(self) -> _WireProtocolPickledInput: + """ + Turns this object into a _WireProtocolPickledInput which can be + directly transferred across a stream. + """ + from torch.fx._graph_pickler import GraphPickler + + return _WireProtocolPickledInput(GraphPickler.dumps(self)) + + +def _current_fake_mode() -> FakeTensorMode: + fake_mode = None + if context := torch._guards.TracingContext.try_get(): + fake_mode = context.fake_mode + if fake_mode is not None: + return fake_mode + + shape_env = torch.fx.experimental.symbolic_shapes.ShapeEnv() + return FakeTensorMode(shape_env=shape_env) + + +@dataclass +class _WireProtocolPickledInput: + value: bytes + + def deserialize(self) -> _WireProtocolInput: + """ + Turn this streamable object back into a _WireProtocolInput. + """ + from torch.fx._graph_pickler import GraphPickler + + fake_mode = _current_fake_mode() + result = GraphPickler.loads(self.value, fake_mode) + if not isinstance(result, _WireProtocolInput): + raise AssertionError(f"expected _WireProtocolInput, got {type(result)}") + return result + + +@dataclass +class _WireProtocolOutput: + """ + For _SerializedFxCompile - encapsulates all the data being transferred + (returned) back from the child to the parent. + """ + + graph: OutputCode + metrics: CachedMetricsDeltas + logs: list[logging.LogRecord] + warning_replay: list[warnings.WarningMessage] | None + shape_env: torch.fx.experimental.symbolic_shapes.ShapeEnv | None + + def serialize(self) -> _WireProtocolPickledOutput: + """ + Turns this object into a _WireProtocolPickledOutput which can be + directly transferred across a stream. + """ + from torch.fx._graph_pickler import GraphPickler + + if isinstance(self.graph, CompiledFxGraph): + self.graph.prepare_for_serialization() + return _WireProtocolPickledOutput(GraphPickler.dumps(self)) + + +@dataclass +class _WireProtocolPickledOutput: + value: bytes + + def deserialize(self, constants: CompiledFxGraphConstants) -> _WireProtocolOutput: + """ + Turn this streamable object back into a _WireProtocolOutput. + """ + from torch.fx._graph_pickler import GraphPickler + + fake_mode = _current_fake_mode() + result = GraphPickler.loads(self.value, fake_mode) + if not isinstance(result, _WireProtocolOutput): + raise AssertionError(f"expected _WireProtocolOutput, got {type(result)}") + if isinstance(result.graph, CompiledFxGraph): + result.graph.after_deserialization(constants) + return result + + +class _LoggerState: + """ + This class is for tracking logging that happens during an out-of-process + compile so we can "replay" those messages when the compile is done. Used as + a context manager which returns the captured logs (object). + """ + + loggers: dict[str, int] + # The actual log capturing mechanism - this should be None when we're not + # actively capturing logs. + captured_logs: _CapturedLogs | None = None + + def __init__(self) -> None: + # Mapping from logger name to level. + self.loggers = {} + + def filter( + logger: logging.Logger | logging.PlaceHolder, + ) -> TypeGuard[logging.Logger]: + if not isinstance(logger, logging.Logger): + # Assume that Placeholders propagate + return False + # We only want to track torch._inductor logging + if not logger.name.startswith("torch._inductor"): + return False + # If this logger propagates then assume we'll track its parent + if logger.propagate: + return False + return True + + root = logging.getLogger("torch._inductor") + if sys.version_info < (3, 12): + # logging.getChildren() doesn't exist until 3.12 + logging._acquireLock() # type: ignore[attr-defined] + try: + for logger in root.manager.loggerDict.values(): + if filter(logger): + self.loggers[logger.name] = logger.level + finally: + logging._releaseLock() # type: ignore[attr-defined] + else: + q = [root] + while q: + logger = q.pop() + if filter(logger): + self.loggers[logger.name] = logger.level + q.extend(logger.getChildren()) + + def __enter__(self) -> _CapturedLogs: + if self.captured_logs is not None: + raise AssertionError("captured_logs already set on __enter__") + self.captured_logs = _CapturedLogs(self) + self.captured_logs.apply() + return self.captured_logs + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: types.TracebackType | None, + ) -> None: + if self.captured_logs is None: + raise AssertionError("captured_logs not set on __exit__") + self.captured_logs.remove() + + +class _CapturedLogs: + """ + Helper for _LoggerState - this class actually attaches to the logger in + the child process and grabs the log messages themselves. + """ + + state: _LoggerState + queue: queue.Queue[logging.LogRecord] + handlers: dict[str, logging.Handler] | None + + def __init__(self, state: _LoggerState) -> None: + self.state = state + # A queue of the log entries + # TODO: For memory purposes should we log to a file and then respond with that? + self.queue = queue.Queue(-1) + # Mapping from name to handler (only valid when applied) + self.handlers = None + + def finish(self) -> list[logging.LogRecord]: + if self.handlers is not None: + raise AssertionError("expected handlers to be None in finish") + logs = [] + try: + while True: + logs.append(self.queue.get_nowait()) + except queue.Empty: + pass + return logs + + def remove(self) -> None: + if self.handlers is None: + raise AssertionError("expected handlers to be set in remove") + handlers, self.handlers = self.handlers, None + for name, handler in handlers.items(): + logger = logging.getLogger(name) + logger.removeHandler(handler) + + def apply(self) -> None: + from logging.handlers import QueueHandler + + if self.handlers is not None: + raise AssertionError("expected handlers to be None in apply") + self.handlers = {} + for name, level in self.state.loggers.items(): + logger = logging.getLogger(name) + handler = QueueHandler(self.queue) + self.handlers[name] = handler + logger.addHandler(handler) + if level != logging.NOTSET: + logger.setLevel(level) + + +class _SerializedFxCompile(FxCompile): + """ + This is used to represent an FxCompile which occurs across a serialized + boundary. + """ + + @override + def codegen_and_compile( + self, + gm: GraphModule, + example_inputs: Sequence[InputType], + inputs_to_check: Sequence[int], + graph_kwargs: _CompileFxKwargs, + ) -> OutputCode: + # If this code changes it's likely _AsyncFxCompile.codegen_and_compile() + # will also need to match. + + serialized = self.serialize_compile( + gm, example_inputs, inputs_to_check, graph_kwargs + ) + if not serialized: + eager_compile = _InProcessFxCompile() + eager_compile.compile_region_name = self.compile_region_name + return eager_compile.codegen_and_compile( + gm, example_inputs, inputs_to_check, graph_kwargs + ) + + inputs, constants = serialized + output = self._send_to_child(inputs).deserialize(constants) + if isinstance(output.graph, CompiledFxGraph): + output.graph.compile_region_name = self.compile_region_name + + self._postprocess(output) + self._compile_stats[type(self)].codegen_and_compile += 1 + + # TODO: Do we need to figure out what changed in TracingContext in the + # child and plumb that back up to the parent? + + return output.graph + + def serialize_compile( + self, + gm: GraphModule, + example_inputs: Sequence[InputType], + inputs_to_check: Sequence[int], + graph_kwargs: _CompileFxKwargs, + ) -> tuple[_WireProtocolPickledInput, CompiledFxGraphConstantsWithGm] | None: + """ + Prepare a _WireProtocolInput to compile. If None is returned then it + wasn't possible to serialize and we should fallback to in-process. + """ + try: + # _check_for_hop raises BypassFxGraphCache when it detects something + # we can't cache (or serialize) + FxGraphCache._check_for_hop(gm) + except BypassFxGraphCache as e: + log.debug("Skipping %s compile: %s", type(self), e) + return None + + # Triton kernel wrapper nodes contain references to the kernel_side_table + # which is process-local and can't be serialized across processes. + if _graph_contains_triton_kernel_wrappers(gm): + log.debug( + "Skipping %s compile: graph contains triton kernel wrappers", type(self) + ) + return None + + context = torch._guards.TracingContext.try_get() + constants = CompiledFxGraphConstantsWithGm(gm) + logger_state = _LoggerState() + lowering = _LoweringSerializer() + + # If we're running tests then grab the DeterministicGuard (don't want to + # import this if it isn't already imported because it has side-effects) + deterministic_guard_for_testing: ( # type: ignore[name-defined] # mypy bug + torch.testing._internal.common_utils.DeterministicGuard | None + ) = None + try: + deterministic_guard_for_testing = ( + torch.testing._internal.common_utils.DeterministicGuard._current_state() # type: ignore[attr-defined] # mypy bug + ) + except AttributeError: + pass + + fake_mode = _current_fake_mode() + fake_tensor_mode = _FakeTensorModeSerializer(fake_mode) + + from pickle import PicklingError + + try: + input = _WireProtocolInput( + gm, + example_inputs, + inputs_to_check, + graph_kwargs, + context, + config.save_config_portable(), + _VirtualizedSerializer.serialize(), + deterministic_guard_for_testing, + logger_state, + lowering, + fake_tensor_mode, + ).serialize() + return (input, constants) + except (AttributeError, BypassFxGraphCache, PicklingError): + # For example: AttributeError: Can't pickle local object + # 'make_opaque_unary_fn..OpaqueUnaryFn' + + # TODO: scuba record about not being able to do this? + log.warning("Unable to pickle input graph or example inputs", exc_info=True) + + return None + + @abstractmethod + def _send_to_child( + self, pickled_input: _WireProtocolPickledInput + ) -> _WireProtocolPickledOutput: + # The implementation of this should transfer `input` to the child, call + # `_run_in_child(input)` and transfer the result back. + ... + + def _postprocess(self, output: _WireProtocolOutput) -> None: + pass + + @classmethod + def _run_in_child( + cls, + pickled_input: _WireProtocolPickledInput, + extra_env: Mapping[str, str | None] | None = None, + ) -> _WireProtocolPickledOutput: + metrics = CachedMetricsHelper() + + with contextlib.ExitStack() as stack: + stack.enter_context(patch_subprocess_env(extra_env)) + + # Save warnings to "replay" in the parent + warning_replay = stack.enter_context(warnings.catch_warnings(record=True)) + + # TODO: Should we split the input into multiple sections where each + # section sets up state for the previous section? (i.e. a Config section + # which we decode and apply, followed by a FakeTensorMode section which + # we decode and apply, etc) + input = pickled_input.deserialize() + + stack.enter_context(input.virtualized.patch()) + stack.enter_context(input.lowering.patch()) + stack.enter_context(config.patch(input.config)) + captured_logs = stack.enter_context(input.logger_state) + if input.deterministic_guard_for_testing: + stack.enter_context(input.deterministic_guard_for_testing) + stack.enter_context(torch._guards.tracing(input.tracing_context)) + stack.enter_context(DebugContext()) + + fake_mode = _current_fake_mode() + stack.enter_context(input.fake_tensor_mode.patch(fake_mode)) + + output_graph = _InProcessFxCompile().codegen_and_compile( + input.gm, + input.example_inputs, + input.inputs_to_check, + input.graph_kwargs, + ) + + logs = captured_logs.finish() + + return _WireProtocolOutput( + output_graph, + metrics.get_deltas(), + logs, + warning_replay, + fake_mode.shape_env, + ).serialize() + + +# This is a debugging/testing implementation of FxCompile which serializes the +# input and output but still runs the FxCompile in-process. +@final +class _DebugSerdeFxCompile(_SerializedFxCompile): + @override + def _send_to_child( + self, pickled_input: _WireProtocolPickledInput + ) -> _WireProtocolPickledOutput: + # For debugging just serde the input and output but don't run in a + # subprocess. + return self._run_in_child(pickled_input) + + +class _OutOfProcessFxCompile(_SerializedFxCompile): + """ + Represents an FxCompile which is run outside the current process (in + either a subprocess or possibly even a separate machine). + """ + + @override + @final + def _send_to_child( + self, pickled_input: _WireProtocolPickledInput + ) -> _WireProtocolPickledOutput: + f = self._send_to_child_async(pickled_input) + + # For debugging: If we want to print status updates... + # last = time.time() + # while not f.done(): + # print("tick...") + # time.sleep(0.125) + # now = time.time() + # if now - last > 1: + # last = now + + return f.result() + + @abstractmethod + def _send_to_child_async( + self, pickled_input: _WireProtocolPickledInput + ) -> Future[_WireProtocolPickledOutput]: ... + + def _postprocess(self, output: _WireProtocolOutput) -> None: + # Since our metrics were gathered in a subprocess make sure to add them + # here. + CachedMetricsHelper.apply_deltas(output.metrics) + + # This is used by tests to check the output for specific details. For + # remote things (subproc and RE) we need to do the `save_output_code` + # here since it didn't happen earlier in-process. In the future if this + # doesn't have "source_code" (it's a CompiledAOTI, for example) and we + # need it we'll have to grab it and serialize it separately from the + # child. + if GraphLowering.save_output_code is not None: + GraphLowering.save_output_code(output.graph.source_code) # type: ignore[attr-defined] + + # And forward our collected logs. The cache is cleared when the outer + # function exits. + @functools.cache + def getLogger(name: str) -> logging.Logger: + return logging.getLogger(name) + + if output.warning_replay: + for w in output.warning_replay: + warnings.warn_explicit( + message=w.message, + category=w.category, + filename=w.filename, + lineno=w.lineno, + source=w.source, + ) + + for record in output.logs: + logger = getLogger(record.name) + logger.handle(record) + + +# For debugging - create a _FxCompile which writes the serialized data to a file +# and then exits. +# +# TODO: make this a FxCompileMode value? +# +# The "child runner" should look something like this: +# +# import torch +# from torch._inductor import compile_fx +# idx = 0 +# with open(f"/tmp/pytorch_compile_fx_tmp_input_{idx}.bin", "rb") as f: +# input = compile_fx._WireProtocolPickledInput(f.read()) +# result = compile_fx._SubprocessFxCompile._run_in_child(input) +# with open(f"/tmp/pytorch_compile_fx_tmp_output_{idx}.bin", "wb") as f: +# f.write(result.value) +# +@final +class _DebugFileFxCompile(_SerializedFxCompile): + file_index = 0 + + @override + def _send_to_child( + self, pickled_input: _WireProtocolPickledInput + ) -> _WireProtocolPickledOutput: + idx = _DebugFileFxCompile.file_index + _DebugFileFxCompile.file_index += 1 + + name = os.path.join( + tempfile.gettempdir(), f"pytorch_compile_fx_tmp_input_{idx}.bin" + ) + with open(name, "wb") as f: + f.write(pickled_input.value) + print(f"Wrote to {name}") + + if False: + name = os.path.join( + tempfile.gettempdir(), f"pytorch_compile_fx_tmp_actual_{idx}.bin" + ) + actual = self._run_in_child(pickled_input) + with open(name, "wb") as f: + f.write(actual.value) + return actual + elif False: + name = os.path.join( + tempfile.gettempdir(), f"pytorch_compile_fx_tmp_output_{idx}.bin" + ) + with open(name, "rb") as f: + result = _WireProtocolPickledOutput(f.read()) + print(f"Read from {name}") + return result + else: + os._exit(-1) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_subproc.py b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_subproc.py new file mode 100644 index 0000000000000000000000000000000000000000..be18a6a130924460f1cda645b17230ce7f525ab2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_subproc.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import atexit +import functools +import os +from typing import TYPE_CHECKING +from typing_extensions import final, override + +import torch._inductor.async_compile +import torch.fx +from torch._inductor.compile_worker.subproc_pool import ( + AnyPool, + SubprocKind, + SubprocPool, +) +from torch._inductor.utils import clear_caches + +from .compile_fx_ext import ( + _OutOfProcessFxCompile, + _WireProtocolPickledInput, + _WireProtocolPickledOutput, +) + + +if TYPE_CHECKING: + from collections.abc import Mapping + from concurrent.futures import Future + + +@final +class _SubprocessFxCompile(_OutOfProcessFxCompile): + @override + def _send_to_child_async( + self, input: _WireProtocolPickledInput + ) -> Future[_WireProtocolPickledOutput]: + # TODO: Do we need to copy across some kind of logging IDs? (ChromiumEventLogger) + + pool = self.process_pool() + + # TODO: This is probably the wrong thing to do long-term - but for now + # let's share the cache so we can identify tests broken by this later. + env_vars = ["TORCHINDUCTOR_CACHE_DIR", "TRITON_CACHE_DIR"] + extra_env = {v: os.environ.get(v) for v in env_vars} + + return pool.submit( + _SubprocessFxCompile._run_in_child_subprocess, input, extra_env + ) + + @staticmethod + @functools.cache + def process_pool() -> AnyPool: + pool = SubprocPool( + # TODO: Consider raising this limit if we start using async w/ + # subprocess and want to compile multiple graphs in parallel. + 1, + kind=SubprocKind.SPAWN, + ) + + atexit.register(pool.shutdown) + + return pool + + @classmethod + def _run_in_child_subprocess( + cls, + pickled_input: _WireProtocolPickledInput, + extra_env: Mapping[str, str | None] | None, + ) -> _WireProtocolPickledOutput: + # TODO: In subprocess mode we need to clear the inductor caches. + # The problem: + # 1. We compile in worker A which fills stuff in tmpdir + # 2. parent clears inductor caches which deletes tmpdirs and tells + # cpp_prefix_path() to clear its LRU cache + # 3. We compile a second time in subproc A - but since we never told + # cpp_prefix_path() in worker A to clear its LRU it thinks the + # tmpdir still exists and fails to compile. + # + # TODO: We probably should be using a separate tmpdir in the worker + # anyway... but we should probably still respect clear_caches() + # in the parent... maybe? + # + # TODO: We could be less aggressive by keeping a clock which gets + # incremented when we clear the cache, send the clock to the worker and + # only clear caches if the clock changed since last time. + # + clear_caches() + torch._inductor.metrics.reset() + + # TODO: turn off config.fx_graph_async_compile + + result = cls._run_in_child(pickled_input, extra_env) + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__main__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..8e215bdeb684ec59c439fcf087fc042887e2adc6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__main__.py @@ -0,0 +1,81 @@ +# mypy: allow-untyped-defs +import argparse +import base64 +import functools +import importlib +import logging +import os +import sys +from typing import TypeVar + +from torch._inductor.async_compile import pre_fork_setup +from torch._inductor.codecache import torch_key +from torch._inductor.compile_worker.subproc_pool import ( + SubprocKind, + SubprocMain, + SubprocPickler, +) +from torch._inductor.compile_worker.utils import _async_compile_initializer +from torch._inductor.runtime.compile_tasks import _set_triton_ptxas_path + + +_T = TypeVar("_T") + + +log = logging.getLogger(__name__) + +_set_triton_ptxas_path() + +try: + import triton + + if triton is None: + raise AssertionError("triton failed to preload in parent") +except ImportError: + pass + + +def _lookup_and_create_type(base: type[_T], qname: str) -> _T: + """ + Given a base type and qualified name: import & lookup that name, check + that it's of the given type and then instantiate it. + """ + pkg, name = qname.rsplit(".", 1) + mod = importlib.import_module(pkg) + ty = getattr(mod, name) + if not issubclass(ty, base): + raise TypeError(f"Type {ty} is not a subtype of {base}") + return ty() + + +def main(): + try: + parser = argparse.ArgumentParser() + parser.add_argument( + "--pickler", type=functools.partial(_lookup_and_create_type, SubprocPickler) + ) + parser.add_argument("--kind", type=SubprocKind) + parser.add_argument("--workers", type=int) + parser.add_argument("--parent", type=int) + parser.add_argument("--read-fd", type=int) + parser.add_argument("--write-fd", type=int) + parser.add_argument("--torch-key", type=str) + args = parser.parse_args() + if os.getppid() != args.parent: + sys.exit(0) + read_fd = os.fdopen(args.read_fd, "rb") + write_fd = os.fdopen(args.write_fd, "wb") + + pre_fork_setup() + + torch_key.set(base64.b64decode(args.torch_key.encode("utf-8"))) # type: ignore[attr-defined] + + _async_compile_initializer(args.parent) + + SubprocMain(args.pickler, args.kind, args.workers, read_fd, write_fd).main() + except Exception: + log.exception("Uncaught exception in compile_worker subprocess") + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..199aac12dd52621ae457c8ae8984297158087b13 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7b8466bd15d36f1e8314fb60a6c68a5d2f82e4c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/__main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/subproc_pool.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/subproc_pool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9da58e27596c4b520a4432abd8fe5ead6ca5b929 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/subproc_pool.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/timer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/timer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce6c66fa6629139b8d87319a7b3817a8f7b86066 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/timer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/tracked_process_pool.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/tracked_process_pool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee312df5e316537d9d6b71343fa17c626730802a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/tracked_process_pool.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f38cb74f7a1c7c53cb501cc7d2ae05a977a96ac Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/watchdog.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/watchdog.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c63ce1ed6030291c45085b6e8e2fcc8dbd388eb1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/watchdog.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/subproc_pool.py b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/subproc_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..759e5614d22a19d88fc0cf003e8e7118fdd6a20b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/subproc_pool.py @@ -0,0 +1,867 @@ +import base64 +import functools +import itertools +import json +import logging +import multiprocessing +import os +import pickle +import struct +import subprocess +import sys +import threading +import time +import traceback +import typing +from collections.abc import Callable +from concurrent.futures import Future, ProcessPoolExecutor +from concurrent.futures.process import BrokenProcessPool +from enum import Enum, IntEnum +from pathlib import Path +from typing import Any, IO, TypeVar +from typing_extensions import Never, ParamSpec + +# _thread_safe_fork is needed because the subprocesses in the pool can read +# justknobs, e.g., in the Triton compiler. For internal, the import installs +# functionality to destroy singletons before forking and re-enable them after. +import torch._thread_safe_fork # noqa: F401 +from torch._inductor import config +from torch._inductor.codecache import torch_key +from torch._inductor.compile_worker import watchdog +from torch._inductor.compile_worker.timer import Timer +from torch._inductor.compile_worker.tracked_process_pool import ( + TrackedProcessPoolExecutor, +) +from torch._inductor.compile_worker.utils import _async_compile_initializer +from torch._inductor.utils import get_ld_library_path, python_subprocess_env +from torch._logging import trace_structured +from torch._utils_internal import find_compile_subproc_binary +from torch.monitor import _WaitCounter, _WaitCounterTracker + + +log = logging.getLogger(__name__) + +_P = ParamSpec("_P") +_T = TypeVar("_T") + + +class MsgHeader(IntEnum): + ERROR = 0 + SHUTDOWN = 1 + QUIESCE = 2 + WAKEUP = 3 + JOB = 4 + # Sidecar -> parent watchdog report about a still-running job (out-of-band, + # low volume). Payload is a pickled status dict; does not affect the future. + STATUS = 5 + + +def _current_compile_id() -> Any: + # Snapshotted at submit so a later watchdog STATUS report (handled on the + # read thread, which has no ambient compile context) can be attributed to the + # right compile in tlparse. + try: + from torch._guards import CompileContext + + return CompileContext.current_compile_id() + except Exception: + return None + + +def _pack_msg(msg_header: MsgHeader, job_id: int, length: int) -> bytes: + return struct.pack("nnn", int(msg_header), job_id, length) + + +def _unpack_msg(data: bytes) -> tuple[MsgHeader, int, int]: + if not data: + return MsgHeader.ERROR, -1, -1 + msg_header, job_id, length = struct.unpack("nnn", data) + return MsgHeader(msg_header), job_id, length + + +msg_bytes = len(_pack_msg(MsgHeader.JOB, 0, 0)) + +# How often the parent polls the sidecar process for liveness. The sidecar +# dying is the only signal this catches, so a coarse interval is fine. +_SIDECAR_HEALTH_POLL_SECONDS = 2.0 + +# How long, in total, to let compile workers exit on SIGTERM during pool +# teardown before escalating to SIGKILL. A worker wedged holding a lock or in a +# C/GIL section won't honor SIGTERM, and an unbounded wait for it would stall the +# whole shutdown. +_WORKER_TERMINATE_GRACE_SECONDS = 10.0 + + +def _send_msg( + write_pipe: IO[bytes], msg_header: MsgHeader, job_id: int = -1, data: bytes = b"" +) -> None: + length = len(data) + write_pipe.write(_pack_msg(msg_header, job_id, length)) + if length > 0: + write_pipe.write(data) + write_pipe.flush() + + +def _recv_msg(read_pipe: IO[bytes]) -> tuple[MsgHeader, int, bytes]: + msg_header, job_id, length = _unpack_msg(read_pipe.read(msg_bytes)) + data = read_pipe.read(length) if length > 0 else b"" + return msg_header, job_id, data + + +class _SubprocExceptionInfo: + """ + Carries exception info from subprocesses across the wire. traceback + objects are not pickleable, so we store the trace as a string and + use it for the message in the exception thrown in the main process. + """ + + def __init__(self, details: str) -> None: + self.details = details + + +class SubprocException(Exception): + """ + Thrown when a job in a subprocess raises an Exception. + """ + + def __init__(self, details: str, name: str = "") -> None: + self.details = details + super().__init__( + f"An exception occurred in a subprocess:\n\nName={name}\n{details}" + ) + + def with_name(self, name: str) -> "SubprocException": + return SubprocException(self.details, name) + + +class SubprocPickler: + """ + Allows a caller to provide a custom pickler for passing data with the + subprocess. + """ + + def dumps(self, obj: object) -> bytes: + return pickle.dumps(obj, pickle.HIGHEST_PROTOCOL) + + def loads(self, data: bytes) -> object: + return pickle.loads(data) + + +class SubprocKind(Enum): + FORK = "fork" + SPAWN = "spawn" + + +class SubprocPool: + """ + Mimic a concurrent.futures.ProcessPoolExecutor, but wrap it in + a subprocess.Popen() to try to avoid issues with forking/spawning + """ + + def __init__( + self, + nprocs: int, + pickler: SubprocPickler | None = None, + kind: SubprocKind = SubprocKind.FORK, + quiesce: bool = False, + ) -> None: + entry = os.path.join(os.path.dirname(__file__), "__main__.py") + self.pickler = pickler or SubprocPickler() + self.kind = kind + + subproc_read_fd, write_fd = os.pipe() + read_fd, subproc_write_fd = os.pipe() + self.write_pipe = os.fdopen(write_fd, "wb") + self.read_pipe = os.fdopen(read_fd, "rb") + torch_key_str = base64.b64encode(torch_key()).decode("utf-8") + + cmd = [ + sys.executable, + entry, + ] + if (binary := find_compile_subproc_binary()) is not None: + cmd = [binary] + + args = [ + f"--pickler={self.pickler.__class__.__module__}.{self.pickler.__class__.__name__}", + f"--kind={self.kind.value}", + f"--workers={nprocs}", + f"--parent={os.getpid()}", + f"--read-fd={str(subproc_read_fd)}", + f"--write-fd={str(subproc_write_fd)}", + f"--torch-key={torch_key_str}", + ] + cmd.extend(args) + log_path = None + self.log_file = None + + if config.worker_suppress_logging: + log_path = os.devnull + log.info("Suppressing compile worker output due to config") + else: + log_path = config.torchinductor_worker_logpath + if not log_path: + log_path = config.get_worker_log_path() + + if log_path: + # pyrefly: ignore [bad-assignment] + self.log_file = open(log_path, "w") # noqa:SIM115 + # Kept so the liveness watchdog can tail worker output if the sidecar dies. + self.log_path = log_path + + self.process = subprocess.Popen( + cmd, + env={ + **python_subprocess_env(), + # Safeguard against creating a SubprocPool in the subprocess. + "TORCH_WARM_POOL": "0", + # Some internal usages need a modified LD_LIBRARY_PATH. + "LD_LIBRARY_PATH": get_ld_library_path(), + }, + pass_fds=(subproc_read_fd, subproc_write_fd), + stdout=self.log_file, + stderr=self.log_file, + ) + # The sidecar inherited these via pass_fds; the parent uses its own ends + # (write_pipe/read_pipe) and must drop its copies. Otherwise the parent + # itself keeps the result pipe's write end open, so read_pipe would never + # EOF even after the sidecar and all workers are gone. + os.close(subproc_read_fd) + os.close(subproc_write_fd) + + self.write_lock = threading.Lock() + self.read_thread = threading.Thread( + target=self._read_thread, name="InductorSubproc", daemon=True + ) + # Backstop for the sidecar dying. Closing the inherited pipe fds (in the + # parent above and in each worker's initializer) means a dead sidecar + # normally yields a clean EOF that _read_thread handles. This watchdog + # covers the cases where EOF does not arrive -- e.g. a stray fd copy still + # holding the write end open -- by detecting the dead process directly. + self.health_thread = threading.Thread( + target=self._health_monitor, name="InductorSubprocHealth", daemon=True + ) + + self.futures_lock = threading.Lock() + self.pending_futures: dict[int, Future[Any]] = {} + # Compile id captured at submit so watchdog STATUS reports (handled on the + # read thread) attribute to the right compile in tlparse. Keyed by job_id. + self._job_compile_id: dict[int, Any] = {} + # The pending waitcounter, is used to indicate the time when we have any specific job running. + self.pending_waitcounters: dict[int, Any] = {} + self.job_id_count = itertools.count() + + # The running waitcounter indicates the time when the SubProcPool object exists. + self.running = True + self.running_waitcounter = _WaitCounter( + "pytorch.wait_counter.subproc_pool.running" + ).guard() + self.running_waitcounter.__enter__() + + # The quiesce waitcounter indicates when the job is in a quiesced state. + self.quiesce_waitcounter: _WaitCounterTracker | None = None + + # Firstjob is used to capture the time from when the firstjob is queued, to when the first job is done. + self.firstjob = True + self.firstjob_id: int | None = None + self.firstjob_waitcounter = _WaitCounter( + "pytorch.wait_counter.subproc_pool.first_job" + ).guard() + + if quiesce: + self.timer: Timer | None = Timer( + config.quiesce_async_compile_time, self.quiesce + ) + else: + self.timer = None + + # Start threads last to ensure all member variables are initialized + # before any access. + self.read_thread.start() + self.health_thread.start() + + def submit( + self, job_fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs + ) -> Future[_T]: + if args or kwargs: + # pyrefly: ignore [bad-assignment] + job_fn = functools.partial(job_fn, *args, **kwargs) + job_data = self.pickler.dumps(job_fn) + future: Future[_T] + with self.futures_lock: + job_id = next(self.job_id_count) + self.pending_futures[job_id] = future = Future() + self._job_compile_id[job_id] = _current_compile_id() + self.pending_waitcounters[job_id] = _WaitCounter( + "pytorch.wait_counter.subproc_pool.job" + ).guard() + self.pending_waitcounters[job_id].__enter__() + if self.quiesce_waitcounter: + self.firstjob = True + self.quiesce_waitcounter.__exit__() + self.quiesce_waitcounter = None + # This can be entered from either quiesce wakeup, or from startup. + if self.firstjob: + self.firstjob_id = job_id + self.firstjob_waitcounter.__enter__() + self.firstjob = False + future.set_running_or_notify_cancel() + self._send(MsgHeader.JOB, job_id, job_data) + return future + + def _send(self, msg_header: MsgHeader, job_id: int = -1, data: bytes = b"") -> None: + with self.write_lock: + if not self.running: + raise RuntimeError("Attempting to use a closed pool") + _send_msg(self.write_pipe, msg_header, job_id, data) + + def _read_thread(self) -> None: + while True: + data = b"" + job_id = -1 + try: + msg_header, job_id, data = _recv_msg(self.read_pipe) + except Exception: + # Something went wrong during the read. There's no way we have a + # valid msg. + log.exception("failure in subproc_pool._recv_msg") + msg_header = MsgHeader.ERROR + + if msg_header == MsgHeader.STATUS: + # Out-of-band watchdog report; does not touch futures. + self._handle_worker_status(job_id, data) + continue + + if msg_header != MsgHeader.JOB: + # read_pipe returned None or got exception + if self.running: + log.warning("SubprocPool unclean exit") + self.running = False + self.running_waitcounter.__exit__() + self.read_pipe.close() + # Cancel all the pending futures. + self.shutdown() + return + + try: + result = self.pickler.loads(data) + except Exception as e: + # Something went wrong unpickling. We have a job_id so just + # notify that particular future and continue on. + log.exception("unpickle failure in SubprocPool._read_thread") + result = e + + with self.futures_lock: + if not self.running: + return + if self.timer: + self.timer.record_call() + if isinstance(result, _SubprocExceptionInfo): + # An exception occurred in the submitted job + self.pending_futures[job_id].set_exception( + SubprocException(result.details) + ) + elif isinstance(result, Exception): + # An exception occurred in some of our subprocess machinery. + self.pending_futures[job_id].set_exception(result) + else: + self.pending_futures[job_id].set_result(result) + + self.pending_waitcounters[job_id].__exit__() + del self.pending_waitcounters[job_id] + if self.firstjob_id == job_id: + self.firstjob_waitcounter.__exit__() + + del self.pending_futures[job_id] + self._job_compile_id.pop(job_id, None) + + def _health_monitor(self) -> None: + # Poll the sidecar for liveness. If it dies while we still think we are + # running, fail the pending compiles rather than let waiters block + # forever (see health_thread comment in __init__). + while self.running: + returncode = self.process.poll() + if returncode is not None: + self._on_sidecar_death(returncode) + return + time.sleep(_SIDECAR_HEALTH_POLL_SECONDS) + + def _on_sidecar_death(self, returncode: int) -> None: + with self.futures_lock: + if not self.running: + # Expected exit (shutdown) or already handled. + return + self.running = False + # `running` is set under different locks across shutdown()/_read_thread/ + # here, so this exit can race another for the same transition. That's + # safe: _WaitCounterTracker.__exit__ is idempotent (optional::reset()). + self.running_waitcounter.__exit__() + + pid = self.process.pid + log.error( + "Inductor compile worker sidecar (pid %s) exited unexpectedly with " + "code %s during compilation; failing pending compile jobs. Re-run " + "with TORCHINDUCTOR_COMPILE_THREADS=1 to compile in the main process.", + pid, + returncode, + ) + self._log_sidecar_death_diagnostics(returncode) + + exc = RuntimeError( + f"Inductor compile worker sidecar (pid {pid}) exited unexpectedly " + f"with code {returncode} during compilation. Re-run with " + "TORCHINDUCTOR_COMPILE_THREADS=1 to compile in the main process." + ) + with self.futures_lock: + for job_id, future in self.pending_futures.items(): + if not future.cancel(): + future.set_exception(exc) + waitcounter = self.pending_waitcounters.pop(job_id, None) + if waitcounter is not None: + waitcounter.__exit__() + self.pending_futures.clear() + self._job_compile_id.clear() + # We intentionally do not close read_pipe here. _read_thread owns it and + # may be mid-read; closing a buffered pipe out from under a concurrent + # read can deadlock on the buffer lock. It is a daemon thread, so leaving + # it is harmless now that the futures are resolved -- and if the sidecar's + # death already produced an EOF, _read_thread will close the pipe itself. + + def _log_sidecar_death_diagnostics(self, returncode: int) -> None: + tail = "" + if self.log_path and self.log_path != os.devnull: + try: + with open(self.log_path, errors="replace") as f: + tail = "".join(f.readlines()[-50:]) + except OSError: + pass + if tail: + log.error( + "Last output from compile worker sidecar (pid %s):\n%s", + self.process.pid, + tail, + ) + # Surface the same info to structured tracing so production jobs (which + # only have tlparse access) can diagnose the crash. + try: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "compile_worker_sidecar_death", + "encoding": "string", + }, + payload_fn=lambda: ( + f"sidecar pid={self.process.pid} returncode={returncode}\n\n{tail}" + ), + ) + except Exception: + log.warning("Failed to emit sidecar-death trace artifact", exc_info=True) + + def _handle_worker_status(self, job_id: int, data: bytes) -> None: + # Best-effort, and runs on the read thread: a bad status report (corrupt + # payload or a logging failure) must not escape and kill result + # processing, so guard the whole thing. + try: + status = self.pickler.loads(data) + if not isinstance(status, dict): + return + compile_id = self._job_compile_id.get(job_id) + record = {**status, "compile_id": str(compile_id) if compile_id else None} + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "compile_worker_status", + "encoding": "json", + }, + payload_fn=lambda: json.dumps(record), + compile_id=compile_id, + expect_trace_id=False, + suppress_context=True, + record_logging_overhead=False, + ) + except Exception: + log.warning("failed to report compile worker status", exc_info=True) + + def quiesce(self) -> None: + self._send(MsgHeader.QUIESCE) + if self.quiesce_waitcounter is None: + self.quiesce_waitcounter = _WaitCounter( + "pytorch.wait_counter.subproc_pool.quiesced" + ).guard() + self.quiesce_waitcounter.__enter__() + + def wakeup(self) -> None: + self._send(MsgHeader.WAKEUP) + + def shutdown(self) -> None: + try: + with self.write_lock: + if not self.running: + return + if self.timer: + self.timer.quit() + self.running = False + self.running_waitcounter.__exit__() + _send_msg(self.write_pipe, MsgHeader.SHUTDOWN) + self.write_pipe.close() + try: + self.process.wait(300) + except subprocess.TimeoutExpired: + # The sidecar did not exit in time (e.g. wedged tearing down its + # own worker pool). Don't stall the whole process; kill it and + # move on. TimeoutExpired is not an OSError, so it would + # otherwise propagate uncaught out of shutdown(). + log.warning( + "Compile worker sidecar (pid %s) did not exit within 300s; " + "killing it.", + self.process.pid, + ) + self.process.kill() + self.process.wait() + if self.log_file: + self.log_file.close() + except OSError: + log.warning("Ignored OSError in pool shutdown", exc_info=True) + finally: + with self.futures_lock: + for future in self.pending_futures.values(): + if not future.cancel(): + future.set_exception(RuntimeError("SubprocPool closed")) + self.pending_futures.clear() + self._job_compile_id.clear() + + +class SubprocMain: + """Communicates with a SubprocPool in the parent process, called by __main__.py""" + + def __init__( + self, + pickler: SubprocPickler, + kind: SubprocKind, + nprocs: int, + read_pipe: IO[bytes], + write_pipe: IO[bytes], + ) -> None: + self.pickler = pickler + self.kind = kind + self.read_pipe = read_pipe + self.write_pipe = write_pipe + self.write_lock = threading.Lock() + self.nprocs = nprocs + self.pool: ProcessPoolExecutor | None = None + self.pool_finalizer: Any | None = None + self.running = True + # job_id -> monotonic submit time; scanned by the watchdog thread. + self._inflight: dict[int, float] = {} + self._inflight_lock = threading.Lock() + self._watchdog_stop = threading.Event() + + def main(self) -> None: + # Phase heartbeats rely on fork inheritance of the shared buffer; spawn + # workers get no buffer and degrade to duration-only reporting. + if self.kind == SubprocKind.FORK: + watchdog.create(self.nprocs) + self._start_watchdog() + while True: + msg_header, job_id, data = _recv_msg(self.read_pipe) + if msg_header == MsgHeader.JOB: + self.submit(job_id, data) + elif msg_header == MsgHeader.WAKEUP: + self._start_pool() + elif msg_header == MsgHeader.QUIESCE: + self._quiesce() + else: + return self._shutdown() + + def _quiesce(self) -> None: + self._shutdown_pool(terminate_workers=False) + + def _shutdown(self) -> None: + self._watchdog_stop.set() + with self.write_lock: + self.running = False + try: + _send_msg(self.write_pipe, MsgHeader.SHUTDOWN) + self.write_pipe.close() + except BrokenPipeError: + pass # parent process already shutdown + self.read_pipe.close() + self._shutdown_pool(terminate_workers=True) + + def _shutdown_pool(self, *, terminate_workers: bool) -> None: + if self.pool is None: + return + + pool = self.pool + self.pool = None + + if self.pool_finalizer is not None: + if terminate_workers: + self.pool_finalizer.cancel() + self.pool_finalizer = None + + if terminate_workers: + # The sidecar is exiting, so do not let ProcessPoolExecutor's + # interpreter finalization wait for running compiler workers. + _terminate_process_pool(pool) + else: + pool.shutdown(wait=False) + + def submit(self, job_id: int, data: bytes) -> None: + # Clock starts before _start_pool/_warm_process_pool, so the first job's + # reported elapsed intentionally includes cold pool creation and the fork + # of the workers -- that wait is real and worth surfacing. + with self._inflight_lock: + self._inflight[job_id] = time.monotonic() + while self.running: + try: + self._submit_inner(job_id, data) + return + except BrokenProcessPool: + # If any subprocess in the pool crashes, we get a BrokenProcessPool + # exception and the whole pool becomes unusable. Handle crashes by + # recreating the pool and resubmitting. Log it -- this was + # previously silent, hiding repeated worker crashes that can stall + # a job in this retry loop. + log.warning( + "Compile worker pool broke while submitting job %s; " + "recreating the pool and retrying.", + job_id, + exc_info=True, + ) + self.pool = None + + def _submit_inner(self, job_id: int, data: bytes) -> None: + def callback(fut: Future[Any]) -> None: + with self._inflight_lock: + self._inflight.pop(job_id, None) + if not self.running: + return + try: + result = fut.result() + except Exception as e: + log.exception("Error in subprocess") + result = self.pickler.dumps(e) + if not isinstance(result, bytes): + raise AssertionError(f"Expected bytes result, got {type(result)}") + with self.write_lock: + if self.running: + _send_msg(self.write_pipe, MsgHeader.JOB, job_id, result) + return + + self._start_pool() + if self.pool is None: + raise AssertionError("pool must be initialized before submitting jobs") + + future = self.pool.submit( + functools.partial(SubprocMain.do_job, self.pickler, job_id, data) + ) + future.add_done_callback(callback) + + def _start_pool(self) -> None: + if self.pool is not None: + return + + # Recycle heartbeat slots before the new worker generation forks. + watchdog.reset() + + # Only fork workers inherit the sidecar<->parent pipe fds and must close + # them (see _async_compile_initializer). Under spawn the workers do not + # inherit them (close_fds=True + O_CLOEXEC), and these integers would + # refer to unrelated fds the fresh interpreter reused -- closing them + # would be silent corruption, not a no-op. + close_fds = ( + (self.read_pipe.fileno(), self.write_pipe.fileno()) + if self.kind == SubprocKind.FORK + else () + ) + self.pool = TrackedProcessPoolExecutor( + self.nprocs, + mp_context=multiprocessing.get_context(self.kind.value), + initializer=functools.partial( + _async_compile_initializer, os.getpid(), close_fds + ), + ) + self.pool_finalizer = multiprocessing.util.Finalize( + None, self.pool.shutdown, exitpriority=sys.maxsize + ) + _warm_process_pool(self.pool, self.nprocs) + + def _start_watchdog(self) -> None: + interval = config.compile_worker_watchdog_interval_seconds + if interval <= 0: + return + threading.Thread( + target=self._watchdog_loop, + args=(interval,), + name="InductorSubprocWatchdog", + daemon=True, + ).start() + + def _watchdog_loop(self, interval: float) -> None: + # Every `interval` seconds, report any job still running past `interval` + # so a stuck/slow worker leaves a breadcrumb (the parent turns these into + # tlparse artifacts). Re-reports each tick with a growing elapsed time. + while not self._watchdog_stop.wait(interval): + now = time.monotonic() + now_ns = time.monotonic_ns() + heartbeats = watchdog.read_heartbeats() + with self._inflight_lock: + slow = [ + (job_id, elapsed) + for job_id, start in self._inflight.items() + if (elapsed := now - start) >= interval + ] + for job_id, elapsed in slow: + self._report_status(job_id, elapsed, heartbeats.get(job_id), now_ns) + + def _report_status( + self, + job_id: int, + elapsed: float, + heartbeat: tuple[int, int, int] | None, + now_ns: int, + ) -> None: + status: dict[str, Any] = {"job_id": job_id, "elapsed_s": round(elapsed, 1)} + if heartbeat is not None: + phase, phase_start_ns, worker_pid = heartbeat + status["phase"] = watchdog.Phase(phase).name.lower() + status["phase_elapsed_s"] = round((now_ns - phase_start_ns) / 1e9, 1) + status["worker_pid"] = worker_pid + elif watchdog.enabled(): + # Heartbeats are active but this job isn't in any worker's slot. Almost + # always that means it's still queued in the pool -- a running (fork) + # worker stamps its slot before doing anything. It can also briefly + # mean the opposite: a job that just finished (clear_current_job ran in + # do_job's finally) but hasn't yet been popped from _inflight by the + # sidecar callback. That window is negligibly short, so we don't + # distinguish it. + status["phase"] = "queued" + # Otherwise phase tracking is unavailable (e.g. a spawn pool) and the + # report carries duration only -- we can't tell queued from running. + payload = self.pickler.dumps(status) + try: + with self.write_lock: + if self.running: + _send_msg(self.write_pipe, MsgHeader.STATUS, job_id, payload) + except (OSError, ValueError): + # Parent gone / pipe closed; the watchdog is best-effort. + pass + + @staticmethod + def do_job(pickler: SubprocPickler, job_id: int, data: bytes) -> bytes: + # do the pickle/unpickle in the sub-subproc + watchdog.set_current_job(job_id) + try: + job = typing.cast(Callable[[], object], pickler.loads(data)) + try: + result = job() + except Exception: + result = _SubprocExceptionInfo(traceback.format_exc()) + return pickler.dumps(result) + finally: + watchdog.clear_current_job() + + +AnyPool = ProcessPoolExecutor | SubprocPool + + +def _get_process_pool_processes(pool: ProcessPoolExecutor) -> list[Any]: + processes = getattr(pool, "_processes", None) + if processes is not None: + return list(processes.values()) + + manager_thread = getattr(pool, "_executor_manager_thread", None) + manager_processes = getattr(manager_thread, "processes", None) + if manager_processes is not None: + return list(manager_processes.values()) + + return [] + + +def _terminate_process_pool(pool: ProcessPoolExecutor) -> None: + processes = _get_process_pool_processes(pool) + for process in processes: + try: + if process.is_alive(): + process.terminate() + except (OSError, ValueError): + log.warning("Ignored error terminating compile worker", exc_info=True) + + # Give workers a bounded, shared grace period to exit on the SIGTERM above, + # then SIGKILL any that are wedged. Without this the pool.shutdown(wait=True) + # below can block on an unreaped worker until the parent's shutdown wait + # gives up (a ~300s stall). + deadline = time.time() + _WORKER_TERMINATE_GRACE_SECONDS + for process in processes: + try: + remaining = deadline - time.time() + if remaining > 0: + process.join(remaining) + if process.is_alive(): + process.kill() + except (OSError, ValueError, AssertionError): + log.warning("Ignored error killing compile worker", exc_info=True) + + try: + pool.shutdown(wait=True, cancel_futures=True) + except Exception: + log.warning("Ignored error shutting down compile worker pool", exc_info=True) + + +def _warm_process_pool(pool: ProcessPoolExecutor, n: int) -> None: + # We have to fork processes for compiler workers, but the more memory and other resources that are loaded, the + # slower the os.fork time is, quite drastically. It also holds the GIL so we can't put it on another thread. + + # Examples: + # A simple x + x + x script: 10ms seconds in the middle of the program, 2ms at startup + # tf_efficientnet_b0 benchmark: 50ms! in the middle of the program , 3ms at startup + + # So we want to start the workers early when it is still cheap, and also to allow the workers to get + # ready before we have work for them. + + # ProcessPoolExecutor also does not launch the workers until it finds a point when all the workers are idle. + # But if we waited until then fork time will be long and we will be waiting for the processes to initialize. + + # We force them to start here with some YOLOing of the internal methods. + + if hasattr(pool, "_start_queue_management_thread"): + pool._start_queue_management_thread() + else: + for _ in range(n): + pool._adjust_process_count() + if hasattr(pool, "_start_executor_manager_thread"): + pool._start_executor_manager_thread() + + +class TestException(RuntimeError): + pass + + +def raise_testexc() -> Never: + raise TestException + + +def _test_signal_then_sleep(signal_path: str, seconds: float) -> None: + # Test helper: announce that this worker has begun executing by creating + # signal_path, then block. Lets a test wait until a job is actually running + # in a worker before acting on the pool (e.g. shutting it down). + Path(signal_path).touch() + time.sleep(seconds) + + +def _ignore_sigterm_and_sleep_for_test() -> None: + # Test helper: a compile worker that ignores SIGTERM and blocks, forcing pool + # teardown to escalate to SIGKILL instead of stalling on a graceful shutdown. + import signal + + signal.signal(signal.SIGTERM, signal.SIG_IGN) + while True: + time.sleep(3600) + + +def _report_phase_and_sleep_for_test(phase: int, seconds: float) -> None: + # Test helper: report a heartbeat phase from a worker, then block, so the + # sidecar watchdog observes and reports that phase. + watchdog.report_phase(watchdog.Phase(phase)) + time.sleep(seconds) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/timer.py b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/timer.py new file mode 100644 index 0000000000000000000000000000000000000000..03930e0161cb281e3aa5b15931481905fc5dbcf2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/timer.py @@ -0,0 +1,55 @@ +from collections.abc import Callable +from threading import Lock, Thread +from time import monotonic, sleep + + +class Timer: + """ + This measures how long we have gone since last receiving an event and if it is greater than a set interval, calls a function. + """ + + def __init__( + self, + duration: int | float, # Duration in seconds + call: Callable[[], None], # Function to call when we expire + ) -> None: + # We don't start the background thread until we actually get an event. + self.background_thread: Thread | None = None + self.last_called: float | None = None + self.duration = duration + self.sleep_time = duration / 2 + self.call = call + self.exit = False + + self.lock = Lock() + + def record_call(self) -> None: + with self.lock: + if self.background_thread is None: + self.background_thread = Thread( + target=self.check, daemon=True, name="subproc_worker_timer" + ) + self.background_thread.start() + self.last_called = monotonic() + + def quit(self) -> None: + with self.lock: + self.exit = True + + def check(self) -> None: + while True: + # We have to be sensitive on checking here, to avoid too much impact on cpu + sleep(self.sleep_time) + with self.lock: + if self.exit: + return + if self.last_called is None: + raise AssertionError("last_called must be set before timer check") + if self.last_called + self.duration >= monotonic(): + continue + self.last_called = None + self.background_thread = None + + # Releasing lock in case self.call() takes a very long time or is reentrant + self.call() + return diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/tracked_process_pool.py b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/tracked_process_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..44f2457cd5d82a9005b17bf17188e42aa4fd0e08 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/tracked_process_pool.py @@ -0,0 +1,113 @@ +import atexit +import concurrent +import dataclasses +import logging +import threading +from collections.abc import Callable +from concurrent.futures import Future, ProcessPoolExecutor +from dataclasses import dataclass +from multiprocessing.context import BaseContext +from time import time +from typing import Any, TypeVar +from typing_extensions import ParamSpec + +# _thread_safe_fork is needed because the subprocesses in the pool can read +# justknobs, e.g., in the Triton compiler. For internal, the import installs +# functionality to destroy singletons before forking and re-enable them after. +import torch._thread_safe_fork # noqa: F401 + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +log = logging.getLogger(__name__) + + +@dataclass +class _QueueStats: + # Mapping from id(future) -> start time + pending: dict[int, float] = dataclasses.field(default_factory=dict) + timing: list[float] = dataclasses.field(default_factory=list) + enqueue_count: int = 0 + dequeue_count: int = 0 + max_queue_depth: int = 0 + pool_count: int = 0 + + +# The queue statistics tracked by TrackedProcessPoolExecutor. Always grab +# _queue_stats_lock before touching. +_queue_stats = _QueueStats() +_queue_stats_lock = threading.Lock() + + +class TrackedProcessPoolExecutor(ProcessPoolExecutor): + def __init__( + self, + max_workers: int | None = None, + mp_context: BaseContext | None = None, + initializer: Callable[[], object] | None = None, + ) -> None: + with _queue_stats_lock: + _queue_stats.pool_count += 1 + super().__init__(max_workers, mp_context, initializer) + + def _record_dequeue(self, f: Future[Any]) -> None: + now = time() + with _queue_stats_lock: + stats = _queue_stats + if (start_time := stats.pending.pop(id(f), None)) is None: + return + stats.dequeue_count += 1 + duration = now - start_time + stats.timing.append(duration) + + def _record_enqueue(self, f: Future[Any]) -> None: + # Monkeypatch the set_running_or_notify_cancel so we can track when the Future moves out of PENDING. + saved_running_or_notify_cancel = f.set_running_or_notify_cancel + + def set_running_or_notify_cancel() -> Any: + self._record_dequeue(f) + return saved_running_or_notify_cancel() + + now = time() + with _queue_stats_lock: + stats = _queue_stats + stats.pending[id(f)] = now + stats.enqueue_count += 1 + stats.max_queue_depth = max(stats.max_queue_depth, len(stats.pending)) + f.set_running_or_notify_cancel = set_running_or_notify_cancel # type: ignore[method-assign] + + if f._state != concurrent.futures._base.PENDING: + self._record_dequeue(f) + + def submit( + self, fn: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs + ) -> Future[_R]: + # pyrefly: ignore [bad-argument-type] + f = super().submit(fn, *args, **kwargs) + self._record_enqueue(f) + return f + + +@atexit.register +def _queue_stats_report() -> None: + stats = _queue_stats + if stats.pool_count == 0: + return + + timing = stats.timing + timing.sort() + + log.info("AsyncCompile Metrics:") + log.info(" Pools %s", stats.pool_count) + log.info( + " Items %d enqueued / %d dequeued", stats.enqueue_count, stats.dequeue_count + ) + log.info(" Max Queue Depth: %d", stats.max_queue_depth) + n = len(timing) + if n > 0: + log.info(" Longest queue time: %0.2fs", timing[-1]) + log.info(" P50: %0.2fs", timing[n // 2]) + if n >= 20: + log.info(" P95: %0.2fs", timing[n * 95 // 100]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e5919b3f06ee4ce09eaf66ebe75379e9f4bfa4b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/utils.py @@ -0,0 +1,72 @@ +import os +import signal +from threading import Thread +from time import sleep + +from torch._inductor.compile_worker import watchdog + + +_IN_TOPLEVEL_PROCESS = True + + +def in_toplevel_process() -> bool: + global _IN_TOPLEVEL_PROCESS + return _IN_TOPLEVEL_PROCESS + + +# If this process dies abnormally (e.g. segfault) +# it will not shut down the workers. Instead, +# the workers will have their parent reassigned to the +# init process. This launches a separate thread to +# watch for the worker getting reassigned, +# and cleans it up in this case. +# +# This function cannot be an inner function since otherwise mp_context="spawn" would +# not work for ProcessPoolExecutor since inner functions cannot be pickled. +def _async_compile_initializer(orig_ppid: int, close_fds: tuple[int, ...] = ()) -> None: + # In fork mode a worker inherits the sidecar's entire fd table, including the + # sidecar<->parent pipes. The worker must not keep those open: holding the + # result pipe's write end would stop the parent from ever seeing EOF when the + # sidecar dies. The caller only passes these fds under fork; under spawn the + # worker doesn't inherit them and the same integers would name unrelated fds + # the fresh interpreter reused, so closing them there would be silent + # corruption (the OSError guard wouldn't catch it) rather than a no-op. + for fd in close_fds: + try: + os.close(fd) + except OSError: + pass + + import torch._C + + def run() -> None: + while True: + sleep(60) + if orig_ppid != os.getppid(): + os.kill(os.getpid(), signal.SIGKILL) + + global _watchdog_thread, _original_parent + _original_parent = orig_ppid + _watchdog_thread = Thread(target=run, daemon=True) + _watchdog_thread.start() + # Ignore Ctrl-C (i.e. SIGINT) sent to pool workers to avoid meaningless log spam. + signal.signal(signal.SIGINT, signal.SIG_IGN) + + # Install a crash handler to print out the stacktrace for SEGV + torch._C._initCrashHandler() + + # Set a bit to distinguish async_compile subprocesses from the toplevel process. + global _IN_TOPLEVEL_PROCESS + _IN_TOPLEVEL_PROCESS = False + + # Claim a heartbeat slot so the sidecar watchdog can report this worker's + # compile phase (no-op unless the sidecar allocated the shared buffer). + watchdog.init_worker_slot() + + +_watchdog_thread: Thread | None = None +_original_parent: int | None = None + + +def has_parent_changed() -> bool: + return _original_parent != os.getppid() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/watchdog.py b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/watchdog.py new file mode 100644 index 0000000000000000000000000000000000000000..96e408fe3532986dab15a1241f2ab890d58385dc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/watchdog.py @@ -0,0 +1,149 @@ +"""Shared-memory heartbeat so the compile-worker sidecar's watchdog can report +which phase a slow/stuck worker is in (see SubprocMain._watchdog_loop). + +A single multiprocessing.Array is allocated in the sidecar (create()) before it +forks its worker pool; every forked worker inherits the same buffer and writes +only its own slot -- single writer per slot, so no lock is needed there and a +rare torn read is harmless for a coarse once-a-minute diagnostic. The sidecar's +watchdog thread reads all slots. + +Slots are recycled off the pool's lifecycle rather than by polling worker +liveness: the sidecar calls reset() every time it (re)builds the worker pool, +and workers then claim slots 0..nprocs-1 with a per-generation counter. A worker +death tears down and rebuilds the whole pool (ProcessPoolExecutor's behavior), so +reset() runs before the replacement generation forks and there is never more than +one live worker per slot. (If the pool were ever configured to replace workers +individually -- e.g. max_tasks_per_child -- a replacement would simply run out of +counter and report nothing, rather than collide with a live worker's slot.) + +Everything is a no-op unless the sidecar allocated the buffer and the worker +claimed a slot, so the report_phase() calls sprinkled through the compile path +are free in the main process and in non-forking pools (spawn workers do not +inherit the buffer and simply degrade to duration-only reporting). +""" + +from __future__ import annotations + +import multiprocessing +import os +import time +from enum import IntEnum +from typing import Any + + +class Phase(IntEnum): + # Persisted as ints in the shared buffer; append new phases, don't renumber. + RUNNING = 0 + QUERYING_CACHE = 1 + COMPILING = 2 + + +# Per-slot layout: _FIELDS longs. +_FIELDS = 4 +_F_JOB_ID = 0 +_F_PHASE = 1 +_F_PHASE_START_NS = 2 +_F_PID = 3 +_EMPTY = -1 # job_id sentinel for an idle slot + +# Allocated in the sidecar (create) before forking; inherited by fork workers. +# _counter's lock also serializes slot claims and reset(). +_heartbeat: Any | None = None +_counter: Any | None = None +_nprocs: int = 0 +# Claimed post-fork by each worker (init_worker_slot). +_slot: int | None = None + + +def create(nprocs: int) -> None: + """Sidecar: allocate the shared buffer before forking the worker pool.""" + global _heartbeat, _counter, _nprocs + ctx = multiprocessing.get_context("fork") + _nprocs = nprocs + _counter = ctx.Value("i", 0) + buf = ctx.Array("q", nprocs * _FIELDS, lock=False) + for s in range(nprocs): + buf[s * _FIELDS + _F_JOB_ID] = _EMPTY + _heartbeat = buf + + +def reset() -> None: + """Sidecar: recycle all slots for a fresh worker generation. Call before + (re)building the worker pool so the new workers claim clean slots 0..n-1.""" + if _heartbeat is None or _counter is None: + return + with _counter.get_lock(): + _counter.value = 0 + for s in range(_nprocs): + base = s * _FIELDS + _heartbeat[base + _F_JOB_ID] = _EMPTY + _heartbeat[base + _F_PID] = 0 + + +def init_worker_slot() -> None: + """Worker: claim this generation's next slot. No-op if the sidecar didn't + allocate a buffer (main process / spawn pools).""" + global _slot + if _heartbeat is None or _counter is None or _nprocs <= 0: + return + with _counter.get_lock(): + slot = _counter.value + _counter.value = slot + 1 + # Only the first nprocs workers of a generation get a slot; any beyond that + # (which shouldn't happen without per-worker replacement) report nothing. + if slot < _nprocs: + _slot = slot + _heartbeat[slot * _FIELDS + _F_PID] = os.getpid() + + +def set_current_job(job_id: int) -> None: + """Worker: mark the start of a job in this worker's slot.""" + if _heartbeat is None or _slot is None: + return + base = _slot * _FIELDS + _heartbeat[base + _F_PHASE] = int(Phase.RUNNING) + _heartbeat[base + _F_PHASE_START_NS] = time.monotonic_ns() + # Written last so a concurrent reader sees a fully-populated slot or none. + _heartbeat[base + _F_JOB_ID] = job_id + + +def report_phase(phase: Phase) -> None: + """Worker: record the phase this worker just entered.""" + if _heartbeat is None or _slot is None: + return + base = _slot * _FIELDS + _heartbeat[base + _F_PHASE_START_NS] = time.monotonic_ns() + _heartbeat[base + _F_PHASE] = int(phase) + + +def clear_current_job() -> None: + """Worker: mark this slot idle when its job finishes.""" + if _heartbeat is None or _slot is None: + return + _heartbeat[_slot * _FIELDS + _F_JOB_ID] = _EMPTY + + +def enabled() -> bool: + """Sidecar: whether phase heartbeats are active (fork pools only).""" + return _heartbeat is not None + + +def read_heartbeats() -> dict[int, tuple[int, int, int]]: + """Sidecar: job_id -> (phase, phase_start_ns, pid) for currently-busy slots. + + phase_start_ns is worker monotonic_ns; on Linux CLOCK_MONOTONIC is + system-wide so the sidecar can diff it against its own monotonic_ns. + """ + if _heartbeat is None: + return {} + out: dict[int, tuple[int, int, int]] = {} + for s in range(_nprocs): + base = s * _FIELDS + job_id = _heartbeat[base + _F_JOB_ID] + if job_id != _EMPTY: + out[job_id] = ( + _heartbeat[base + _F_PHASE], + _heartbeat[base + _F_PHASE_START_NS], + _heartbeat[base + _F_PID], + ) + return out diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/compiler_bisector.py b/.venv/lib/python3.12/site-packages/torch/_inductor/compiler_bisector.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad2b5e625b8ac43892b83ee400555d81509ce8e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/compiler_bisector.py @@ -0,0 +1,833 @@ +import atexit +import collections +import dataclasses +import functools +import os +import shutil +import sys +import tempfile +from collections.abc import Callable +from dataclasses import dataclass, field + +from torch._inductor.runtime.cache_dir_utils import cache_dir + + +# Set the subdirectory name +SUBDIR_NAME = "bisect" + + +@dataclass +class Subsystem: + name: str + + +@dataclass +class BisectSubsystem(Subsystem): + pass + + +@dataclass +class BinarySubsystem(Subsystem): + pass + + +@dataclass +class ConfigChange(BinarySubsystem): + name: str = field(init=False) + config_name: str + config_field: str + config_value: object + + def __post_init__(self) -> None: + self.name = f"{self.config_name}_{self.config_field}" + + +# Dictionary of backend -> subsystems +BACKENDS: dict[str, list[Subsystem]] = { + # run dynamo without aot_autograd + "eager": [], + # run dynamo with aot_autograd, but no partitioner or decomps + "aot_eager": [], + # run dynamo with aot autograd, decompositions and partitioner + "aot_eager_decomp_partition": [ + ConfigChange("aot_eager_decomp_partition", "cse", False), + BisectSubsystem( + "decomposition" + ), # number of decompositions we apply in tracing + ], # TODO - add cse ? + # applies CrossRefFakeMode on invocation + "aot_eager_decomp_partition_crossref": [], + "inductor": [ + BisectSubsystem("pre_grad_passes"), # passes applied on pre-grad IR + BisectSubsystem("joint_graph_passes"), # passes applied on joint graph + BisectSubsystem( + "post_grad_passes" + ), # passes applied individually on forward, and backward in inductor + ConfigChange("inductor", "fallback_random", True), + ConfigChange("inductor", "emulate_precision_casts", True), + ConfigChange("inductor", "layout_optimization", False), + ConfigChange("inductor", "comprehensive_padding", False), + BisectSubsystem("cudagraphs"), # cudagraph wrapping of compiled graphs + BisectSubsystem("lowerings"), # lowering aten operators to inductor + ], # TODO - add more - fusions ? +} + +subsystem_call_counter: dict[str, int] = collections.Counter() + + +@functools.cache +def get_env_val(env_str: str) -> str | None: + return os.environ.get(env_str, None) + + +@dataclasses.dataclass +class BisectionResult: + """ + backend: torch.compile backend responsible for failure + subsystem: optional, registered component identified for failure + bisect_number: optional, number of times the subsystem needed to be applied to trigger failure + debug_info: associated info of the triggering bisect application of subsystem + """ + + backend: str + subsystem: str | None = None + bisect_number: int | None = None + debug_info: str | None = None + + +class CompilerBisector: + """ + This class iteratively runs torch.compile backends (eager, aot_eager, inductor) to find the + first backend that can repro an issue. + + Once it discovers the offending backend it will iteratively disable subsystems within the backend. + For subsystems which are applied repeatedly, such as the number of post grad passes or number + of lowering of nodes to inductor ir, it will bisect to find the offending application. + + The idiomatic way to run it is with `do_bisect`. You can also use it by setting the env flags + `TORCH_BISECT_BACKEND`, `TORCH_BISECT_SUBSYSTEM` and `TORCH_BISECT_MAX`. + + It also supports a CLI interface: + + python -m torch._inductor.compiler_bisector start + python -m torch._inductor.compiler_bisector good + python -m torch._inductor.compiler_bisector bad + python -m torch._inductor.compiler_bisector end + + Or use `run` to automatically bisect by running a command repeatedly: + + python -m torch._inductor.compiler_bisector run + + The command's exit code determines the result: 0 = good, non-zero = bad. + The TORCH_COMPILE_BACKEND env var is set to the backend being tested. + """ + + bisection_enabled: bool = False + + in_process_cache: str | None = None + + @classmethod + def clear_call_counter_debug_info( + cls, backend_name: str, subsystem_name: str + ) -> None: + file_path = os.path.join( + cls.get_dir(), + backend_name, + f"{subsystem_name}_call_counter_debug_info.txt", + ) + cls.write_lines_to_file(file_path, []) + + @classmethod + def reset_counters(cls) -> None: + subsystem_call_counter.clear() + for backend, subsystem_list in BACKENDS.items(): + for subsystem in subsystem_list: + if isinstance(subsystem, BisectSubsystem): + cls.clear_call_counter_debug_info(backend, subsystem.name) + + @classmethod + def get_dir(cls) -> str: + return f"{cache_dir() if not cls.in_process_cache else cls.in_process_cache}/{SUBDIR_NAME}" + + @classmethod + def write_lines_to_file( + cls, file_path: str, lines: list[str], *, append: bool = False + ) -> None: + os.makedirs(os.path.dirname(file_path), exist_ok=True) + with open(file_path, "a" if append else "w") as file: + file.writelines(lines) + + @classmethod + def read_lines_from_file(cls, file_path: str) -> list[str]: + if os.path.exists(file_path): + with open(file_path) as file: + return file.readlines() + return [] + + @classmethod + def update_run_state( + cls, backend_name: str, subsystem: Subsystem, run_state: str + ) -> None: + file_path = os.path.join( + cls.get_dir(), backend_name, f"{subsystem.name}_run_state.txt" + ) + if isinstance(subsystem, ConfigChange): + if run_state != "test_disable": + raise AssertionError( + f"expected run_state == 'test_disable', got {run_state}" + ) + cls.set_config_values( + backend_name, + subsystem.name, + {subsystem.config_field: subsystem.config_value}, + ) + + cls.write_lines_to_file(file_path, [run_state]) + + @classmethod + def set_config_values( + cls, backend: str, subsystem: str, config_data: dict[str, object] + ) -> None: + file_path = os.path.join(cls.get_dir(), backend, f"{subsystem}_config.txt") + lines = [f"{k}={v}\n" for k, v in config_data.items()] + cls.write_lines_to_file(file_path, lines) + + @classmethod + def update_bisect_status(cls, backend_name: str, subsystem_name: str) -> None: + if not isinstance(subsystem_name, str): + raise AssertionError( + f"expected subsystem_name to be str, got {type(subsystem_name)}" + ) + file_path = os.path.join(cls.get_dir(), "bisect_status.txt") + lines = [f"backend={backend_name}\n", f"subsystem={subsystem_name}\n"] + cls.write_lines_to_file(file_path, lines) + + @classmethod + def update_bisect_range( + cls, backend_name: str, subsystem_name: str, low: int, high: int + ) -> None: + if not isinstance(subsystem_name, str): + raise AssertionError( + f"expected subsystem_name to be str, got {type(subsystem_name)}" + ) + file_path = os.path.join( + cls.get_dir(), backend_name, f"{subsystem_name}_bisect_range.txt" + ) + lines = [f"low={low}\n", f"high={high}\n"] + cls.write_lines_to_file(file_path, lines) + + @classmethod + def add_call_counter_debug_info( + cls, backend_name: str, subsystem_name: str, call_counter: int, debug_info: str + ) -> None: + file_path = os.path.join( + cls.get_dir(), backend_name, f"{subsystem_name}_call_counter_debug_info.txt" + ) + # This is only called for the last ~2 items in a bisect, so writing duplicate + # lines does not have performance implications later. + lines = [f"{call_counter}={debug_info}\n"] + cls.write_lines_to_file(file_path, lines, append=True) + + @classmethod + def get_call_counter_debug_info( + cls, backend_name: str, subsystem_name: str, call_counter: int + ) -> str | None: + file_path = os.path.join( + cls.get_dir(), backend_name, f"{subsystem_name}_call_counter_debug_info.txt" + ) + call_counter_str = str(call_counter) + for line in reversed(cls.read_lines_from_file(file_path)): + counter, _, debug_info = line.strip().partition("=") + if counter == call_counter_str: + return debug_info + return None + + @classmethod + def get_backend(cls) -> str | None: + """ + Returns the active backend, if any + """ + if val := get_env_val("TORCH_BISECT_BACKEND"): + return val + + file_path = os.path.join(cls.get_dir(), "bisect_status.txt") + lines = cls.read_lines_from_file(file_path) + for line in lines: + if line.startswith("backend="): + return line.strip().split("=")[1] + return None + + @classmethod + def get_subsystem(cls) -> str | None: + """ + Returns the active subsystem, if any + """ + + if val := get_env_val("TORCH_BISECT_SUBSYSTEM"): + return val + + file_path = os.path.join(cls.get_dir(), "bisect_status.txt") + lines = cls.read_lines_from_file(file_path) + for line in lines: + if line.startswith("subsystem="): + out = line.strip().split("=")[1] + return out or None + return None + + @classmethod + def get_subsystem_object(cls, backend_name: str, subsystem_name: str) -> Subsystem: + return next(obj for obj in BACKENDS[backend_name] if obj.name == subsystem_name) + + @classmethod + def get_run_state(cls, backend_name: str, subsystem_name: str) -> str | None: + """ + Returns the current stage of bisecting, if Any + """ + + file_path = os.path.join( + cls.get_dir(), backend_name, f"{subsystem_name}_run_state.txt" + ) + lines = cls.read_lines_from_file(file_path) + if lines: + out = lines[0].strip() + if out not in ("test_disable", "find_max_bounds", "bisect"): + raise AssertionError( + f"unexpected run_state {out!r}, expected one of " + "'test_disable', 'find_max_bounds', 'bisect'" + ) + return out + return None + + @classmethod + def get_bisect_range( + cls, backend_name: str, subsystem_name: str + ) -> tuple[int, int]: + file_path = os.path.join( + cls.get_dir(), backend_name, f"{subsystem_name}_bisect_range.txt" + ) + lines = cls.read_lines_from_file(file_path) + low = None + high = None + # pyrefly: ignore [bad-assignment] + for line in reversed(lines): + if line.startswith("low="): + low = int(line.strip().split("=")[1]) + elif line.startswith("high="): + high = int(line.strip().split("=")[1]) + + if low is not None and high is not None: + break + + if low is None or high is None: + raise RuntimeError( + f"Trying to get bisect range when it is not set: subsystem {subsystem_name}" + ) + + return low, high + + @classmethod + def update_config_change(cls, backend: str, subsystem: ConfigChange) -> None: + file_path = os.path.join(cls.get_dir(), backend, f"{subsystem.name}_config.txt") + lines = [ + f"config_name={subsystem.config_name}\n", + f"config_field={subsystem.config_field}\n", + f"config_value={subsystem.config_value}\n", + ] + cls.write_lines_to_file(file_path, lines) + + @classmethod + def get_config_change(cls, config_name: str) -> dict[str, object] | None: + backend = cls.get_backend() + subsystem = cls.get_subsystem() + + if not backend or not subsystem: + return None + + file_path = os.path.join(cls.get_dir(), backend, f"{subsystem}_config.txt") + + if not os.path.exists(file_path): + return None + + lines = cls.read_lines_from_file(file_path) + config_data = {} + for line in lines: + key, value = line.strip().split("=", 1) + config_data[key] = eval(value) + + return config_data + + @classmethod + def delete_bisect_status(cls) -> None: + # in process_cache we have created if it exists, just the subdirectory of non created dir + dir_name = cls.in_process_cache or cls.get_dir() + if os.path.exists(dir_name): + shutil.rmtree(dir_name) + print("Bisection status deleted.") + else: + print("No bisection status found.") + + @classmethod + def get_system_counter(cls, name: str, increment: bool = True) -> int: + global subsystem_call_counter + curr = subsystem_call_counter[name] + if increment: + subsystem_call_counter[name] += 1 + return curr + + @classmethod + def disable_subsystem( + cls, + backend: str, + subsystem: str, + debug_info: Callable[[], str] | None = None, + ) -> bool: + if not cls.bisection_enabled: + return False + + if cls.get_backend() != backend: + return False + + if cls.get_subsystem() != subsystem: + return False + + if val := get_env_val("TORCH_BISECT_MAX"): + counter = cls.get_system_counter(subsystem, increment=True) + return counter > int(val) + + run_state = cls.get_run_state(backend, subsystem) + if run_state == "test_disable": + # First run, disable completely + return True + elif run_state == "find_max_bounds": + # Second run, update bisection range and return True to enable the subsystem + cls.update_bisect_range( + backend, + subsystem, + 0, + cls.get_system_counter(subsystem, increment=True), + ) + return False + else: + if run_state != "bisect": + raise AssertionError(f"expected run_state == 'bisect', got {run_state}") + # If the environment variable is not set, use the bisection range midpoint + low, high = cls.get_bisect_range(backend, subsystem) + # if high - low <= 2: + midpoint = (low + high) // 2 + call_counter = cls.get_system_counter(subsystem) + + if ( + call_counter >= low + and call_counter <= high + and (high - low) <= 2 + and debug_info is not None + ): + cls.add_call_counter_debug_info( + backend, subsystem, call_counter, debug_info() + ) + + return call_counter > midpoint + + @classmethod + def advance_subsystem( + cls, curr_backend: str, curr_subsystem: Subsystem + ) -> Subsystem | None: + """ + Tries to move to the next subsystem within the current system. + """ + print(f"Disabling {curr_subsystem.name} did not fix the issue.") + + current_subsystems = BACKENDS[curr_backend] + current_subsystem_index = next( + i + for i, subsystem in enumerate(current_subsystems) + if subsystem.name == curr_subsystem.name + ) + + if current_subsystem_index < len(current_subsystems) - 1: + next_subsystem = current_subsystems[current_subsystem_index + 1] + cls.update_bisect_status(curr_backend, next_subsystem.name) + cls.update_run_state(curr_backend, next_subsystem, "test_disable") + print( + f"Moving to the next subsystem: {curr_backend} - {next_subsystem.name}" + ) + return next_subsystem + else: + print( + f"All subsystems in {curr_backend} have been checked. The issue is not in this system." + ) + return None + + @classmethod + def advance_backend(cls, curr_backend: str) -> str | None: + """ + Tries Move to the next backend. + """ + current_system_index = list(BACKENDS.keys()).index(curr_backend) + + if current_system_index < len(BACKENDS) - 1: + curr_backend = list(BACKENDS.keys())[current_system_index + 1] + cls.update_bisect_status(curr_backend, "") + print(f"Moving to the next system: {curr_backend}") + return curr_backend + else: + return None + + @classmethod + def process_subsystem( + cls, + curr_backend: str, + curr_subsystem: Subsystem, + fn: Callable[[], bool], + cli_interface: bool = True, + ) -> bool: + """ + Process the current subsystem. Returns True if the issue is found, False otherwise. + """ + if not isinstance(curr_subsystem, Subsystem): + raise AssertionError( + f"expected curr_subsystem to be Subsystem, got {type(curr_subsystem)}" + ) + while True: + run_state = cls.get_run_state(curr_backend, curr_subsystem.name) + cls.reset_counters() + if run_state == "test_disable": + if not fn(): + next_subsystem = cls.advance_subsystem(curr_backend, curr_subsystem) + if not next_subsystem: + return False + curr_subsystem = next_subsystem + else: + if isinstance(curr_subsystem, ConfigChange): + print( + f"Setting config {curr_subsystem.config_name} field {curr_subsystem.config_field} " + f"to {curr_subsystem.config_value} fixed the issue" + ) + else: + print(f"Disabling {curr_subsystem.name} fixed the issue.") + if isinstance(curr_subsystem, BinarySubsystem): + return True + print("Starting bisect by getting upper bound.") + cls.update_run_state( + curr_backend, curr_subsystem, "find_max_bounds" + ) + elif run_state == "find_max_bounds": + if fn(): + raise RuntimeError( + f"Function succeeded with 'find_max_bounds' status for {curr_backend} - {curr_subsystem.name}." + ) + else: + _, high = cls.get_bisect_range(curr_backend, curr_subsystem.name) + print(f"Upper bound of {high} found for {curr_backend}.") + cls.update_run_state(curr_backend, curr_subsystem, "bisect") + elif run_state == "bisect": + low, high = cls.get_bisect_range(curr_backend, curr_subsystem.name) + midpoint = (low + high) // 2 + print( + f"Bisecting {curr_backend} - {curr_subsystem.name} (Range: [{low}, {high}], Midpoint: {midpoint})" + ) + if fn(): + cls.update_bisect_range( + curr_backend, curr_subsystem.name, midpoint + 1, high + ) + else: + cls.update_bisect_range( + curr_backend, curr_subsystem.name, low, midpoint + ) + low, high = cls.get_bisect_range(curr_backend, curr_subsystem.name) + if low == high: + print( + f"Binary search completed for {curr_backend} - {curr_subsystem.name}. The bisect number is {low}. " + f"Debug info: {cls.get_call_counter_debug_info(curr_backend, curr_subsystem.name, low) or 'not found'}" + ) + return True + else: + raise RuntimeError(f"Unexpected run_state {run_state}") + + if cli_interface: + sys.exit(0) + + @classmethod + def initialize_system(cls) -> None: + curr_backend = next(iter(BACKENDS.keys())) + curr_subsystem = "" + cls.update_bisect_status(curr_backend, curr_subsystem) + print(f"Starting bisection process with system: {curr_backend}") + + @classmethod + def do_bisect( + cls, fn: Callable[[], bool], cli_interface: bool = False + ) -> BisectionResult | None: + """ + Run fn repeatedly attempting to bisect torch.compile. fn should return True on success and False on failure. + """ + + # TODO graph bisecting is not well composed with lowering + # bisector so far. Use a config to opt-in + import torch._inductor.config as inductor_config + + if inductor_config.test_configs.bisect_pre_grad_graph: + BACKENDS["inductor"].insert(0, BisectSubsystem("pre_grad_graph")) + + if not cli_interface: + bisection_enabled_orig = cls.bisection_enabled + cls.delete_bisect_status() + cls.bisection_enabled = True + # Only create temp dir if not already set (CLI run mode pre-sets it) + if not cls.in_process_cache: + cls.in_process_cache = tempfile.mkdtemp() + + def cleanup() -> None: + cls.bisection_enabled = bisection_enabled_orig + cls.delete_bisect_status() + cls.in_process_cache = None + + if BACKENDS["inductor"][0].name == "pre_grad_graph": + del BACKENDS["inductor"][0] + + cleanup_handler = atexit.register(cleanup) + + class DisableBisect: + def __del__(self) -> None: + cleanup() + atexit.unregister(cleanup_handler) + + _cleanup = DisableBisect() + + curr_backend = cls.get_backend() + curr_subsystem_name = cls.get_subsystem() + + if not curr_backend: + cls.initialize_system() + curr_backend = cls.get_backend() + if curr_backend is None: + raise AssertionError( + "expected curr_backend to be set after initialize_system" + ) + curr_subsystem_name = cls.get_subsystem() + + curr_subsystem = ( + cls.get_subsystem_object(curr_backend, curr_subsystem_name) + if curr_subsystem_name is not None + else None + ) + while True: + if curr_backend is None: + raise AssertionError("expected curr_backend to be set") + cls.reset_counters() + if curr_subsystem: + result = cls.process_subsystem( + curr_backend, curr_subsystem, fn, cli_interface=cli_interface + ) + if result: + curr_subsystem = cls.get_subsystem_object( + curr_backend, + cls.get_subsystem(), # type: ignore[arg-type] + ) + + if isinstance(curr_subsystem, BinarySubsystem): + return BisectionResult( + curr_backend, + curr_subsystem.name, + 0, + curr_subsystem.name, + ) + + low, _ = cls.get_bisect_range(curr_backend, curr_subsystem.name) + return BisectionResult( + curr_backend, + curr_subsystem.name, + low, + cls.get_call_counter_debug_info( + curr_backend, curr_subsystem.name, low + ), + ) + + next_subsystem = cls.advance_subsystem(curr_backend, curr_subsystem) + if not next_subsystem: + print( + f"The issue is in the {curr_backend} system, but could not identify subsystem." + ) + if curr_backend is None: + raise AssertionError("expected curr_backend to be set") + return BisectionResult(curr_backend) + + curr_subsystem = next_subsystem + else: + if fn(): + next_backend = cls.advance_backend(curr_backend) + if not next_backend: + print("All systems have been checked.") + return None + + curr_backend = next_backend + else: + current_subsystems = BACKENDS[curr_backend] + if current_subsystems: + curr_subsystem = current_subsystems[0] + cls.update_bisect_status(curr_backend, curr_subsystem.name) + cls.update_run_state( + curr_backend, curr_subsystem, "test_disable" + ) + print( + f"The issue is in the {curr_backend} system. Moving to the first subsystem: {curr_subsystem}" + ) + else: + print(f"The issue is in the {curr_backend} system.") + return BisectionResult(curr_backend) + + if cli_interface: + sys.exit(0) + + +HELP_TEXT = """\ +Usage: python -m torch._inductor.compiler_bisector + +Commands: + start Start a new bisection session (manual mode) + good Mark the current state as good (no issue) + bad Mark the current state as bad (issue present) + end End the bisection session and clean up + run Automatically bisect by running a command repeatedly + Exit code 0 = good, non-zero = bad + +Example - using 'run' for automatic bisection: + + 1. Create a test script (e.g., test_bug.py): + + import os, sys, torch + + def main(): + torch._dynamo.reset() + # Use the backend the bisector is testing + backend = os.environ.get("TORCH_COMPILE_BACKEND", "inductor") + + @torch.compile(backend=backend) + def fn(x): + return x.sin() # or your failing operation + + x = torch.randn(10) + compiled = fn(x) + expected = x.sin() # eager reference + + if torch.allclose(compiled, expected, rtol=1e-4, atol=1e-4): + return 0 # PASS + else: + print(f"FAIL: got {compiled}, expected {expected}") + return 1 # FAIL + + if __name__ == "__main__": + sys.exit(main()) + + 2. Run the bisector: + + python -m torch._inductor.compiler_bisector run python test_bug.py + + 3. The bisector will: + - Test backends (eager, aot_eager, inductor) to find which fails + - Test subsystems within that backend (passes, lowerings, etc.) + - Binary search to find the exact operation causing the issue + + Output: + Disabling lowerings fixed the issue. + Binary search completed for inductor - lowerings. The bisect number is 42. + Bisection complete: BisectionResult(backend='inductor', subsystem='lowerings', ...) + +Environment variables set for your test script: + TORCH_COMPILE_BACKEND - The backend being tested (use this in torch.compile) +""" + + +def command_line_usage() -> None: + """Entry point for the compiler bisector command-line interface.""" + if len(sys.argv) < 2: + print(HELP_TEXT) + sys.exit(1) + + bisection_manager = CompilerBisector() + command = sys.argv[1] + + if command == "end": + bisection_manager.delete_bisect_status() + sys.exit(0) + + if command == "start": + bisection_manager.delete_bisect_status() + bisection_manager.initialize_system() + sys.exit(0) + + if command == "run": + if len(sys.argv) < 3: + print( + "Usage: python -m torch._inductor.compiler_bisector run [args...]" + ) + sys.exit(1) + + import subprocess + + run_cmd = sys.argv[2:] + + def test_function() -> bool: + # Pass bisection state to subprocess via environment variables + env = os.environ.copy() + backend = bisection_manager.get_backend() + subsystem = bisection_manager.get_subsystem() + + if backend: + # For test script to select the right backend + env["TORCH_COMPILE_BACKEND"] = backend + # For bisector in subprocess to know which backend we're testing + env["TORCH_BISECT_BACKEND"] = backend + + if subsystem: + if backend is None: # subsystem requires a backend + raise AssertionError("subsystem requires a backend") + env["TORCH_BISECT_SUBSYSTEM"] = subsystem + # Get run_state to determine TORCH_BISECT_MAX + run_state = bisection_manager.get_run_state(backend, subsystem) + if run_state == "test_disable": + # -1 means always disable (counter > -1 is always True) + env["TORCH_BISECT_MAX"] = "-1" + # For find_max_bounds and bisect, let the subprocess use file-based + # mechanisms. The subprocess reads run_state and bisect_range from + # files, and writes the actual count during find_max_bounds. + + result = subprocess.run(run_cmd, env=env) + return result.returncode == 0 + + bisection_manager.delete_bisect_status() + bisection_manager.bisection_enabled = True + # Use shared cache_dir instead of temp dir so subprocesses can access files + CompilerBisector.in_process_cache = cache_dir() + result = bisection_manager.do_bisect(test_function, cli_interface=False) + if result: + print(f"\nBisection complete: {result}") + else: + print("\nBisection complete: no issue found") + sys.exit(0) + + if command not in ["good", "bad"]: + print(f"Invalid command: {command}") + print("Must be 'good', 'bad', 'start', 'end', or 'run'.") + sys.exit(1) + + def test_function() -> bool: + return command == "good" + + if not bisection_manager.get_backend(): + raise ValueError("Must call start prior to good or bad") + + bisection_manager.do_bisect(test_function, cli_interface=True) + + +def get_is_bisection_enabled() -> bool: + return ( + CompilerBisector.get_subsystem() is not None + or CompilerBisector.get_backend() is not None + ) + + +CompilerBisector.bisection_enabled = get_is_bisection_enabled() + +if __name__ == "__main__": + command_line_usage() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/config.py b/.venv/lib/python3.12/site-packages/torch/_inductor/config.py new file mode 100644 index 0000000000000000000000000000000000000000..9f3498f53ddc69c7ff0e204f1b754cd366fcbcfa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/config.py @@ -0,0 +1,3178 @@ +import os +import sys +from collections.abc import Callable +from typing import Any, cast, Literal, TYPE_CHECKING + +import torch +import torch._inductor.custom_graph_pass +from torch._environment import is_fbcode +from torch.utils._config_module import ( + Config, + get_tristate_env, + inherit_fields_from, + install_config_module, +) + + +if TYPE_CHECKING: + from torch._inductor.choices import InductorChoices + from torch._inductor.cudagraph_utils import CUDAGraphPolicy + +inplace_padding = os.environ.get("TORCHINDUCTOR_INPLACE_PADDING", "1") == "1" +can_inplace_pad_graph_input = False # ease testing + + +def fx_graph_remote_cache_default() -> bool | None: + return get_tristate_env("TORCHINDUCTOR_FX_GRAPH_REMOTE_CACHE") + + +def vec_isa_ok_default() -> bool | None: + if os.environ.get("TORCHINDUCTOR_VEC_ISA_OK") == "1": + return True + if os.environ.get("TORCHINDUCTOR_VEC_ISA_OK") == "0": + return False + return None + + +def autotune_remote_cache_default() -> bool | None: + return get_tristate_env("TORCHINDUCTOR_AUTOTUNE_REMOTE_CACHE") + + +def bundled_autotune_remote_cache_default() -> bool | None: + return get_tristate_env("TORCHINDUCTOR_BUNDLED_AUTOTUNE_REMOTE_CACHE") + + +def bundle_triton_into_fx_graph_cache_default() -> bool | None: + return get_tristate_env( + "TORCHINDUCTOR_BUNDLE_TRITON_INTO_FX_GRAPH_CACHE", + True if not is_fbcode() else None, + ) + + +def autotune_at_compile_time_default() -> bool | None: + return get_tristate_env("TORCHINDUCTOR_AUTOTUNE_AT_COMPILE_TIME") + + +def static_cuda_launcher_default() -> bool: + STATIC_CUDA_LAUNCHER_VERSION = 2 + + if "TORCHINDUCTOR_USE_STATIC_CUDA_LAUNCHER" in os.environ: + return os.environ.get("TORCHINDUCTOR_USE_STATIC_CUDA_LAUNCHER") == "1" + elif is_fbcode(): + version = torch._utils_internal.justknobs_getval_int( + "pytorch/inductor:static_cuda_launcher_version" + ) + return version <= STATIC_CUDA_LAUNCHER_VERSION + else: + # Default true in OSS + return True + + +def prologue_fusion_enabled() -> bool: + ENABLE_PROLOGUE_FUSION_VERSION = 0 + + if "TORCHINDUCTOR_PROLOGUE_FUSION" in os.environ: + return os.environ.get("TORCHINDUCTOR_PROLOGUE_FUSION") == "1" + elif is_fbcode(): + jk_name = "pytorch/inductor:prologue_fusion_version" + version = torch._utils_internal.justknobs_getval_int(jk_name) + return version <= ENABLE_PROLOGUE_FUSION_VERSION + else: + return True + + +# Enable auto_functionalized_v2 (enabled by default) +enable_auto_functionalized_v2 = ( + os.environ.get("TORCHDYNAMO_AUTO_FUNCTIONALIZED_V2", "1") == "1" +) + +# add some debug printouts +debug = False + +# Whether to disable a progress bar for autotuning +disable_progress = True + +# Whether to enable printing the source code for each future +verbose_progress = False + +# Configurable compile worker logging path for subproc_pool +worker_log_path = ( + "/logs/dedicated_log_torch_compile_worker_rank" if is_fbcode() else None +) + +# precompilation timeout +precompilation_timeout_seconds: int = int( + os.environ.get("TORCHINDUCTOR_PRECOMPILATION_TIMEOUT_SECONDS", 60 * 5) +) + +# use fx aot graph codegen cache +fx_graph_cache: bool = Config( + justknob="pytorch/remote_cache:enable_local_fx_graph_cache", + env_name_default="TORCHINDUCTOR_FX_GRAPH_CACHE_DEFAULT", + env_name_force="TORCHINDUCTOR_FX_GRAPH_CACHE", + default=True, +) + +remote_gemm_autotune_cache: bool = False + +# use remote fx aot graph codegen cache +# False: Disables the cache +# True: Enables the cache +# None: Not set -- Off for OSS, JustKnobs based for internal +fx_graph_remote_cache: bool | None = fx_graph_remote_cache_default() + +# should we bundle triton caching into fx graph cache +bundle_triton_into_fx_graph_cache: bool | None = ( + bundle_triton_into_fx_graph_cache_default() +) + +non_blocking_remote_cache_write: bool = Config( + justknob="pytorch/remote_cache:enable_non_blocking_remote_cache_write_v2", + env_name_force="TORCHINDUCTOR_NON_BLOCKING_REMOTE_CACHE_WRITE", + default=True, +) + +# Enable autotune local cache. +# +# See bundled_autotune_remote_cache for the effect this flag has on the bundled +# remote cache. +autotune_local_cache: bool = True + +# Enable autotune remote cache. +# +# Enables/disables the autotune remote cache regardless of the state of +# autotune_local_cache. If both local and remote are enabled then on write both +# are written and on read local is checked first and only on a cache miss is +# remote read. +# +# False: Disables the cache +# True: Enables the cache +# None: Not set -- Off for OSS, JustKnobs based for internal +autotune_remote_cache: bool | None = autotune_remote_cache_default() + +# Enable bundled autotune cache. +# +# Enables/disables the bundled autotune cache regardless of the state of +# autotune_remote_cache. However it does depend on the local cache for local +# state management - as a result if the local cache is disabled this will also +# disable the bundled autotune cache. +# +# False: Disables the cache +# True: Enables the cache (requires autotune_local_cache) +# None: Not set -- Off for OSS, JustKnobs based for internal +bundled_autotune_remote_cache: bool | None = bundled_autotune_remote_cache_default() + +# See torch.compiler.config.force_disable_caches +force_disable_caches: bool = Config(alias="torch.compiler.config.force_disable_caches") + +# Unsafe way to skip dynamic shape guards to get faster cache load +unsafe_skip_cache_dynamic_shape_guards: bool = False + +# Unsafe way to mark non torch functions as safe to cache +# dictionary is from function name -> cache key +# Any function name in the dictionary will be allowed to be cacheable +# by AOTAutogradCache and FxGraphCache. +# changing the cache key value will change the resulting +# FXGraphCache key. +# Example usage: +# torch._inductor.config.unsafe_marked_cacheable_functions = { +# 'torch.ops.my_function' : torch.__version__ +# } +# The above example causes the custom op torch.ops.my_function to be cacheable, +# and for cache keys to be keyed by the current torch version +unsafe_marked_cacheable_functions: dict[str, str] = {} + +# sleep in inductor for testing +sleep_sec_TESTING_ONLY: int | None = None + +# The default layout constraint for user-defined triton kernels. +# See "The default layout constraint for custom operators" for options. +triton_kernel_default_layout_constraint: Literal[ + "needs_fixed_stride_order", "flexible_layout" +] = "needs_fixed_stride_order" + +# use cpp wrapper instead of python wrapper +# incompatible with disable_cpp_codegen +cpp_wrapper: bool = os.environ.get("TORCHINDUCTOR_CPP_WRAPPER", "0") == "1" + +# controls whether to compile entry and kernel separately for cpp_wrapper mode. +# turn on this option to compile entry and kernel separately and minimize compile time of the entry part. +# see https://github.com/pytorch/pytorch/pull/148773 +# Note: compiling entry and kernel separately may have a non-negligible impact on the performance. +# see https://github.com/pytorch/pytorch/issues/156037 +cpp_wrapper_build_separate: bool = ( + os.environ.get("TORCHINDUCTOR_CPP_WRAPPER_BUILD_SEPARATE", "0") == "1" +) + +fx_wrapper: bool = os.environ.get("TORCHINDUCTOR_FX_WRAPPER", "0") == "1" + +# Controls automatic precompiling of common include files for codecache.CppCodeCache +# (i.e. for cpp_wrapper mode and for cpp kernels on CPU). AOTI header precompiling is +# controlled by a separate flag. +cpp_cache_precompile_headers: bool = ( + os.environ.get( + "TORCHINDUCTOR_CPP_CACHE_PRECOMPILE_HEADERS", "0" if is_fbcode() else "1" + ) + == "1" +) + +online_softmax = os.environ.get("TORCHINDUCTOR_ONLINE_SOFTMAX", "1") == "1" + +apply_gumbel_max_trick = ( + os.environ.get("TORCHINDUCTOR_APPLY_GUMBEL_MAX_TRICK", "1") == "1" +) + +# dead code elimination +dce = False + +# assume weight tensors are fixed size +static_weight_shapes = True + +# put correctness assertions in generated code +size_asserts = os.environ.get("TORCHINDUCTOR_SIZE_ASSERTS", "1") == "1" +nan_asserts = os.environ.get("TORCHINDUCTOR_NAN_ASSERTS") == "1" +runtime_triton_nan_asserts = ( + os.environ.get("TORCHINDUCTOR_RUNTIME_TRITON_NAN_ASSERTS") == "1" +) +scalar_asserts = os.environ.get("TORCHINDUCTOR_SCALAR_ASSERTS", "1") == "1" + +# Disable by default in fbcode +alignment_asserts = ( + os.environ.get("TORCHINDUCTOR_ALIGNMENT_ASSERTS", "0" if is_fbcode() else "1") + == "1" +) + +# enable loop reordering based on input orders +pick_loop_orders = True + +# reuse a kernel input as the output +inplace_buffers = True + +# reuse a buffer for an unrelated purpose +allow_buffer_reuse = True + +# Enable pooled allocations for non-output tensors +memory_planning = os.environ.get("TORCHINDUCTOR_MEMORY_PLANNING", "0") == "1" + +# Enable to allow using ftz variant of exponenet instruction in triton codegen. +use_fast_math = os.environ.get("TORCHINDUCTOR_USE_FAST_MATH") == "1" + +# Use slower compare/select reductions for their ordered signed-zero tie behavior. +# NaNs are propagated regardless of this setting. +strict_signed_zero = False + +# How to organize memory under memory_planning=True: +# - "none": do not try to pool storage, just reuse +# - "intermediates": all non-outputs share storage, outputs each get unique storage +# - "outputs": two pools, one for intermediates (freed on return) and one for outputs +# - "combined": a single pool for both intermediates and outputs +# pyrefly: ignore [bad-assignment] +memory_pool: Literal["none", "intermediates", "outputs", "combined"] = os.environ.get( + "TORCHINDUCTOR_MEMORY_POOL", "intermediates" +) # type: ignore[assignment] + +# codegen benchmark harness +benchmark_harness = True + +# fuse pointwise into templates epilogues +epilogue_fusion = True + +# fuse atomic-add scatter mutations into Triton template epilogues +# Disabled by default because performance depends on index contention. +epilogue_fusion_with_atomic_add = False + +# fuse pointwise into template prologues +prologue_fusion = prologue_fusion_enabled() + +# do epilogue fusions before other fusions +epilogue_fusion_first = False + +# do epilogue fusions for user defined triton kernels +epilogue_fusion_user_defined_triton_kernel = False + +# enable pattern match+replace optimizations +pattern_matcher = True + +# set to True to enable the back-to-back GEMM pass +b2b_gemm_pass = False + +# register custom graph optimization pass hook. so far, pre/post passes are +# only applied before/after pattern_matcher in post_grad_passes. +# +# Implement CustomGraphPass to allow Inductor to graph compiled artifacts +# to which your custom passes have been applied: +post_grad_custom_pre_pass: torch._inductor.custom_graph_pass.CustomGraphPassType = None +post_grad_custom_post_pass: torch._inductor.custom_graph_pass.CustomGraphPassType = None + +# Allow users to pass in custom partition function +custom_partitioner_fn: torch._inductor.custom_graph_pass.CustomPartitionerFnType = None + +# Registers a custom joint graph pass. +joint_custom_pre_pass: torch._inductor.custom_graph_pass.CustomGraphPassType = None +joint_custom_post_pass: torch._inductor.custom_graph_pass.CustomGraphPassType = None + +# Registers a custom pregrad pass. Note that the pre-grad IR is 1. +# non-functional, 2. non-normalized, and 3. prone to change. Ideally we should +# use post-grad passes. +pre_grad_custom_pass: torch._inductor.custom_graph_pass.CustomGraphPassType = None + +# Registers a custom pass to be run right before fusion in Inductor scheduler. +# WARNING: Inductor scheduler IR is at prototype stage and subject to change, +# hence custom IR passes built on top of it might break in the future. +_pre_fusion_custom_pass: ( + torch._inductor.custom_graph_pass.CustomSchedulerPassCallable | None +) = None + +# Registers a custom pass to be run right after fusion in Inductor scheduler. +# WARNING: Inductor scheduler IR is at prototype stage and subject to change, +# hence custom IR passes built on top of it might break in the future. +_post_fusion_custom_pass: ( + torch._inductor.custom_graph_pass.CustomSchedulerPassCallable | None +) = None + +# Deprecated +split_cat_fx_passes = True + +# Optimize conv-batchnorm if batchnorm is in eval mode. Slightly reduces numerical stability. +efficient_conv_bn_eval_fx_passes = False + +# Enable predispatch aten IR for export +is_predispatch = False + +# Deprecated +group_fusion = False + +# Deprecated +batch_fusion = True + +# Pre grad fusion and options in order, set to empty dict to disable fusion. +# Call `torch._inductor.fx_passes.group_batch_fusion.list_group_batch_fusions()` to see available fusions. +# batch fusion options: +# batch_linear +# batch_linear_lhs +# cat_linear +# batch_layernorm +# batch_tanh +# batch_relu +# batch_sigmoid + +# split cat fusion options: +# normalization_pass +# remove_split_with_size_one_pass +# merge_getitem_cat_pass +# merge_stack_tahn_unbind +# merge_splits_pass +# mutate_cat_pass +# split_cat_pass +pre_grad_fusion_options: dict[str, dict[str, Any]] = {} + +# Post grad fusion and options, set to empty dict to disable fusion. +# Call `torch._inductor.fx_passes.group_batch_fusion.list_group_batch_fusions(False)` to see available fusions. +post_grad_fusion_options: dict[str, dict[str, Any]] = {} + +# enable reordering pass for improving memory locality +reorder_for_locality = True + +# Also run reorder_for_locality (a semantics-preserving pass; see +# reorder_for_locality in fx_passes/post_grad.py for the cases it guards) on +# training graphs, not just inference. Default off. Gated by reorder_for_locality +# above: enabling this while that is False does nothing. +reorder_for_locality_in_training = ( + os.environ.get("TORCHINDUCTOR_REORDER_LOCALITY_TRAINING", "0") == "1" +) + +# Scale down Rn_BLOCK for better occupancy +dynamic_scale_rblock = os.environ.get("TORCHINDUCTOR_DYNAMIC_SCALE_RBLOCK", "1") == "1" + +# this forces fusion for int_mm with mul. Needed when you want to avoid realizing the int32 +# but the mul gets fused with other pointwise ops instead. +force_fuse_int_mm_with_mul = False + +# Prevent unfusing addmm into mm+add for bf16/fp16 to avoid precision loss +# from extra truncation at the mm output. Set to False to allow unfusing +# (may improve perf at the cost of accuracy for some models). +keep_addmm_fused_for_half_dtypes = True + +# DEPRECATED. This setting is ignored. +use_mixed_mm = True + +# enable runtime numeric check for pre/post grad fx passes +# floating point provides limited accuracy (about 7 decimal digits for single precision +# floating point numbers,about 16 decimal digits for double precision floating point numbers) +# according to PyTorch documentation. +# https://pytorch.org/docs/stable/notes/numerical_accuracy.html#batched-computations-or-slice-computations +fx_passes_numeric_check: dict[str, Any] = { + "pre_grad": False, + "precision": 1e-4, + "num_iterations": 1, + "requires_optimizer": True, +} + +# DEPRECATED. This setting is ignored. +mixed_mm_choice: Literal["default", "triton", "aten", "heuristic"] = "heuristic" + +# enable reordering pass for increasing overlap between compute and communication +reorder_for_compute_comm_overlap = False + +# Decompose DTensor Shard(dim) -> Shard(other_dim) all-to-all into explicit +# layout ops plus _c10d_functional.all_to_all_single/wait_tensor. This is +# experimental and intentionally opt-in. +decompose_shard_dim_alltoall = ( + os.environ.get("TORCHINDUCTOR_DECOMPOSE_SHARD_DIM_ALLTOALL", "0") == "1" +) + +# passes (in execution order) for increasing overlap between compute and communication +# for built-in passes, use string name; for user-defined passes, pass in the function handle +# WARNING: Inductor scheduler IR is at prototype stage and subject to change, +# hence custom IR passes built on top of it might break in the future. +# +# See aten_distributed_optimizations, it is recommended way for distributed optimizations. +# +# Recommended configuration for reorder_for_compute_comm_overlap_passes: +# [ +# "reorder_communication_preserving_peak_memory", +# "sink_waits_iterative", +# "reorder_communication_preserving_peak_memory", +# ] +reorder_for_compute_comm_overlap_passes: list[ + str + | Callable[ + [list["torch._inductor.scheduler.BaseSchedulerNode"]], + list["torch._inductor.scheduler.BaseSchedulerNode"], + ] +] = [] + +# Maximum number of positions to advance a given collective, unlimited by default +reorder_prefetch_limit: int | None = None + +# enable operator reordering for peak memory optimization +reorder_for_peak_memory = True +reorder_for_peak_memory_debug = False + +# In some cases, when all the nodes that can be scheduled are quite large, +# it is beneficial to switch the scheduling strategy. So instead of using +# size as the criterion, we choose a node that can unlock more nodes to +# become schedulable by analyzing their successor nodes. The default value +# is zero, which turns off this optimization. +size_threshold_for_succ_based_strategy: int = 0 + + +bucket_all_gathers_fx: Literal["none", "all", "only_fsdp"] = "none" +# By default torch._inductor.fx_passes.bucketing.bucket_size_determinator is used +bucket_all_gathers_fx_bucket_size_determinator: Callable[[int], int] | None = None + +bucket_all_gathers_bucket_mode: Literal[ + "default", "custom_ops", "custom_ops_multidtype" +] = "default" + +# Fuse duplicate reduce_scatter ops whose waited results are summed via add. +dedup_reduce_scatters: bool = False + +bucket_reduce_scatters_fx: Literal["none", "all"] = "none" +# By default torch._inductor.fx_passes.bucketing.bucket_size_determinator is used +bucket_reduce_scatters_fx_bucket_size_determinator: Callable[[int], int] | None = None + +bucket_reduce_scatters_bucket_mode: Literal[ + "default", "custom_ops", "custom_ops_multidtype" +] = "default" + + +bucket_all_reduces_fx: Literal["none", "all"] = "none" +# By default torch._inductor.fx_passes.bucketing.bucket_size_determinator is used +bucket_all_reduces_fx_bucket_size_determinator: Callable[[int], int] | None = None + +# runtime estimation function for ops +# for built-in estimation function, pass in "default"; for user-defined estimation function, pass in the function handle +estimate_op_runtime = "default" + +runtime_estimations_mms_benchmark: bool = False + +# unit: GB/s, uni-directional P2P bandwidth per card (NVLink). +# None = auto-detect from GPU generation; set to override. +intra_node_bw: int | None = None + +# unit: GB/s, uni-directional P2P bandwidth per node (IB/RoCE). +# None = auto-detect from GPU generation; set to override. +inter_node_bw: int | None = None + +# unit: GB/s, uni-directional CPU<>GPU bandwidth +# default value is PCIe; modify for your hardware or measured bandwidth +cpu_gpu_bw = 50.0 + +# use Inductor's experimental benchmarker (runtime/benchmarking.py) +# to benchmark kernels during autotuning, otherwise fall back to +# Triton's `do_bench`. the experimental benchmarker may produce +# results that are not consistent with `do_bench`'s results +use_experimental_benchmarker: bool = Config( + default=True, + env_name_force="TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER", + justknob="pytorch/inductor:use_experimental_benchmarker", +) + +# Enable distributed autotuning. When this is enabled we will distribute the +# autotuning across distributed ranks in the same program group - so instead of +# each rank autotuning every kernel they only autotune 1/world size kernels and +# then share the results. +distributed_max_autotune_gemm = ( + os.environ.get("TORCHINDUCTOR_DISTRIBUTED_MAX_AUTOTUNE_GEMM") == "1" +) + +# Pipeline autotuning for max-autotune-gemm. Overlap lowering and benchmarking on GPU +pipeline_max_autotune_gemm = ( + os.environ.get("TORCHINDUCTOR_PIPELINE_GEMM_AUTOTUNING") == "1" +) + +# use torch profiler to benchmark kernels during autotuning +# when enabled, this takes precedence over use_experimental_benchmarker +use_torch_profiler_benchmarker: bool = Config( + default=False, + env_name_force="TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER", + justknob="pytorch/inductor:use_torch_profiler_benchmarker", +) + +# enable slow autotuning passes to select algorithms +max_autotune = os.environ.get("TORCHINDUCTOR_MAX_AUTOTUNE") == "1" + +# enable slow autotuning passes to select pointwise/reductions algorithms +max_autotune_pointwise = os.environ.get("TORCHINDUCTOR_MAX_AUTOTUNE_POINTWISE") == "1" + +# enable slow autotuning passes to select gemm algorithms +max_autotune_gemm = os.environ.get("TORCHINDUCTOR_MAX_AUTOTUNE_GEMM") == "1" + +# When True, autotuning is spread across real kernel invocations instead of +# blocking on the first call. Each run() call executes one config and records +# timing via CUDA events, progressively eliminating underperforming configs. +# An additional JK gate inside the plugin can still block the feature on True. +incremental_autotune: bool | None = get_tristate_env( + "TORCHINDUCTOR_INCREMENTAL_AUTOTUNE", default=False +) + +inductor_default_autotune_warmup = int( + os.getenv("TORCHINDUCTOR_DEFAULT_AUTOTUNE_WARMUP", 25) +) +inductor_default_autotune_rep = int( + os.getenv("TORCHINDUCTOR_DEFAULT_AUTOTUNE_REP", 100) +) + +# When enabled, the autotuner captures each candidate kernel in a CUDA graph +# and benchmarks graph replay instead of eager kernel launches. This eliminates +# host-side dispatch overhead from timing measurements, giving results that are +# representative of CUDA graph replay execution. Useful when the compiled output +# will run under external CUDA graph capture. Only applies with max_autotune. +autotune_cudagraph_benchmarking: bool = ( + os.environ.get("TORCHINDUCTOR_AUTOTUNE_CUDAGRAPH_BENCHMARKING") == "1" +) + + +# Modifies the number of autotuning choices displayed, set to None for all +def _autotune_num_choices_displayed_default() -> int | None: + env_val = os.environ.get("TORCHINDUCTOR_AUTOTUNE_NUM_CHOICES_DISPLAYED") + if env_val is None: + return 10 + if env_val.lower() in ("none", "all"): + return None + return int(env_val) + + +autotune_num_choices_displayed: int | None = _autotune_num_choices_displayed_default() + +# Report the autotune choices and their benchmark results. Default is True. +max_autotune_report_choices_stats = ( + os.environ.get("TORCHINDUCTOR_MAX_AUTOTUNE_REPORT_CHOICES_STATS", "1") == "1" +) + +# Prune configs that have a theoretical maximum shared memory usage than the hardware limit +# Will over-prune - pruning some valid configs with theoretical shared memory usage higher +# than real shared memory usage, ensuring that invalid configs are not possibly autotuned +max_autotune_prune_choices_based_on_shared_mem = ( + os.environ.get("TORCHINDUCTOR_MAX_AUTOTUNE_PRUNE_CHOICES_BASED_ON_SHARED_MEM", "0") + == "1" +) + +# Disable triton from trying to initialize and detect devices on the host +triton_disable_device_detection = ( + os.environ.get("TORCHINDUCTOR_TRITON_DISABLE_DEVICE_DETECTION", "0") == "1" +) + +# enable inductor graph partition to allow multiple inductor graphs for the same dynamo graph +graph_partition: bool = ( + os.environ.get("TORCHINDUCTOR_GRAPH_PARTITION", "1" if not is_fbcode() else "0") + == "1" +) + +# Pluggable CUDAGraph wrapping policy. When set to a ``CUDAGraphPolicy`` +# instance, ``post_compile`` delegates cudagraph wrapping to the policy +# instead of the built-in ``cudagraphify`` pipeline. This allows custom +# cudagraph implementations, selective inner-vs-outer wrapping for +# regional compilation, and shared memory pool management. +# +# See ``torch._inductor.cudagraph_utils.CUDAGraphPolicy`` for the base class. +cudagraph_policy: "CUDAGraphPolicy | None" = None + +# register ops upon which inductor should partition the graph. name format should be +# "namespace::kernel_name" (e.g., aten::mm) for op overload packet, or +# "namespace::kernel_name.overload" (e.g., aten::mm.default). +custom_should_partition_ops: list[str] = [] + +# register ops whose OUTPUT unbacked symints should cause partition. Any tensors or ops +# that use these output unbacked symints (e.g. in their shapes, strides, or offsets) +# will be excluded from cudagraph partitions. This is useful for operators that produce +# data-dependent unbacked symints (e.g., from a custom op that returns a SymInt). +# Note: Input symints to these ops remain cudagraph-safe; only the output symints are +# marked as cudagraph-unsafe. Name format should be "namespace::kernel_name" +# (e.g., mylib::get_split_point) for op overload packet, or +# "namespace::kernel_name.overload" for specific overloads. +cudagraph_unsafe_unbacked_ops: list[str] = [] + +# whether template autotuning should allow flexible layouts if possible (e.g. only extern choices) +max_autotune_allow_flexible_layouts: bool = False + +# Size hints for multi-kernel dispatch. +# A reasonable default value of this config would be [64, 256, 4096] +# TODO: @bobrenjc93 to roll this out to a few internal models to ensure this works +# as expected before turning it on for everyone. +multi_kernel_hints: list[int] = [] + + +# Specify candidate backends for gemm autotune. +# Possible choices are combinations of: ATen, Triton, CUTLASS, CUTEDSL, NVGEMM, CK, CKTILE, CPP. +# ATen: default Pytorch ATen kernels. +# Triton: Triton templates defined in torch inductor (AMD and NVidia GPUs). +# CUTLASS: Cutlass templates and kernels (NVidia GPUs only). +# CUTEDSL: CuteDSL templates for Blackwell GPUs (NVidia SM100-SM109 only). +# NVGEMM: NVIDIA Universal GEMM via cutlass.operators (NVidia GPUs only). +# CK: Composable Kernel templates and kernels (AMD Instinct GPUs only). +# CKTILE: Composable Kernel templates and kernels, new API (AMD Instinct GPUs only). +# CPP: CPP templates and kernels for CPU. +max_autotune_gemm_backends = os.environ.get( + "TORCHINDUCTOR_MAX_AUTOTUNE_GEMM_BACKENDS", "ATEN,TRITON,CPP" +).upper() + + +# Configures the maximum number of NVIDIA Universal GEMM (NVGEMM) configs to profile +# in max_autotune. Default 10: a sweep over GDN2/attn/MoE + FLUX shapes (bf16 and +# nvfp4, M=1..4096) showed the heuristic's ranked winner sits in the top ~5 for +# small/large M and for all nvfp4, but for mid-M (~512) bf16 the best config can +# rank much deeper -- capping at 5 there lost up to ~11%, while cap 10 recovered +# nearly all of it (diminishing returns beyond 10). Set to 0, None, or env var +# "none"/"all" to tune all configs. +def _nvgemm_max_profiling_configs_default() -> int | None: + env_val = os.environ.get("TORCHINDUCTOR_NVGEMM_MAX_PROFILING_CONFIGS", "10") + if env_val.lower() in ("none", "all"): + return None + return int(env_val) + + +nvgemm_max_profiling_configs: int | None = _nvgemm_max_profiling_configs_default() + +# When enabled, adds supplement kernel configs that nvMatmulHeuristics +# doesn't explore (certain tile/cluster combos that empirically beat +# cuBLAS on decode shapes). These are added on top of the heuristic +# picks, increasing the total number of configs benchmarked. +nvgemm_supplement_configs: bool = ( + os.environ.get("TORCHINDUCTOR_NVGEMM_SUPPLEMENT_CONFIGS", "0") == "1" +) + +# When enabled, adds swap_ab NVGEMM choices that swap A/B operands so the +# large N dimension goes on the M-axis. Improves tile utilization for +# small-M decode shapes typical in LLM inference (M << N). +nvgemm_swap_ab: bool = os.environ.get("TORCHINDUCTOR_NVGEMM_SWAP_AB", "0") == "1" + + +# Triton conv templates show wins on ROCm; on CUDA, profiling shows no gains on H100. +_conv_default_backends = "ATEN,TRITON" if torch.version.hip else "ATEN" + +# As above, specify candidate backends for conv autotune. +# NB: in some cases for 1x1 convs we emit as matmul, +# which will use the backends of `max_autotune_gemm_backends` +max_autotune_conv_backends = os.environ.get( + "TORCHINDUCTOR_MAX_AUTOTUNE_CONV_BACKENDS", "ATEN,TRITON" +).upper() + +# As above, specify candidate backends for conv backward weight autotune. +max_autotune_conv_bwd_weight_backends = os.environ.get( + "TORCHINDUCTOR_MAX_AUTOTUNE_BWD_WEIGHT_CONV_BACKENDS", _conv_default_backends +).upper() + +# As above, specify candidate backends for conv backward input autotune. +max_autotune_conv_bwd_input_backends = os.environ.get( + "TORCHINDUCTOR_MAX_AUTOTUNE_BWD_INPUT_CONV_BACKENDS", _conv_default_backends +).upper() + +# Specify the size of the search space for GEMM autotuning. +# DEFAULT - balance between compile time overhead and performance +# EXHAUSTIVE - maximize performance +# pyrefly: ignore [bad-assignment] +max_autotune_gemm_search_space: Literal["DEFAULT", "EXHAUSTIVE"] = os.environ.get( + "TORCHINDUCTOR_MAX_AUTOTUNE_GEMM_SEARCH_SPACE", "DEFAULT" +).upper() # type: ignore[assignment] + +# Specify the size of the search space for flex attention autotuning. +# DEFAULT - balance between compile time overhead and performance +# EXHAUSTIVE - maximize performance +# pyrefly: ignore [bad-assignment] +max_autotune_flex_search_space: Literal["DEFAULT", "EXHAUSTIVE"] = os.environ.get( + "TORCHINDUCTOR_MAX_AUTOTUNE_FLEX_SEARCH_SPACE", "DEFAULT" +).upper() # type: ignore[assignment] + + +# Fall back to ATen for all ops by default, except those nodes that users explicitly +# annotated with regional inductor compile. Please read torch.fx.passes.regional_inductor +# on to explicitly annotate. This is currently only used by inductor lite mode. +# Different from default inductor mode that fuses all nodes, this config enables an +# opt-in mode that only fuse for user-specified nodes. The motivation is to provide +# guaranteed numeric correctness and give full control to users. +fallback_by_default: bool = False + + +# This config allows selective decomposition of certain operators in the graph. +# Currently the only use case is to patch the same-name config in functorch, for +# inductor lite mode. See more details in [Note: Selective Decomposition] +selective_decompose: bool = False + + +# Use dead code elimination +use_dce: bool = True + + +# Use fx graph passes +use_pre_grad_passes: bool = True + +# "early": pre-grad passes run before cache lookup (every compile). +# "late": pre-grad passes run after cache lookup (only on cache miss); +# requires custom passes to implement uuid() for the cache key. +# "default": resolves to "late" when possible (no custom pass, or custom pass +# with uuid), falls back to "early" otherwise. +pre_grad_pass_timing: Literal["early", "late", "default"] = "default" + + +use_joint_graph_passes: bool = True +use_post_grad_passes: bool = True + + +cutedsl_enable_autotuning: bool = ( + os.environ.get("CUTEDSL_ENABLE_AUTOTUNING", "0") == "1" +) + +# DEPRECATED. This setting is ignored. +autotune_fallback_to_aten = False + +# the value used as a fallback for the unbacked SymInts +# that can appear in the input shapes (e.g., in autotuning) +unbacked_symint_fallback = 8192 + +# DEPRECATED. This setting is ignored. +search_autotune_cache = False + +save_args = os.environ.get("TORCHINDUCTOR_SAVE_ARGS") == "1" + +# We will disable creating subprocess for autotuning if this is False +autotune_in_subproc = os.environ.get("TORCHINDUCTOR_AUTOTUNE_IN_SUBPROC") == "1" + +# The following three timeouts are applicable if autotune_in_subproc is True: + +# Max time that a valid benchmark result may take during autotuning +max_autotune_subproc_result_timeout_seconds = 60.0 +# DEPRECATED. This setting is ignored. +max_autotune_subproc_graceful_timeout_seconds = 0.0 +# DEPRECATED. This setting is ignored. +max_autotune_subproc_terminate_timeout_seconds = 0.0 + +# If autotuning in subprocess, whether to use multiple devices +autotune_multi_device = os.environ.get("TORCHINDUCTOR_AUTOTUNE_MULTI_DEVICE") == "1" + +# Number of benchmark runs for collective operations +collective_benchmark_nruns = int( + os.environ.get("TORCHINDUCTOR_COLLECTIVE_BENCHMARK_NRUNS", "50") +) + +# Timeout in seconds for collective benchmarking +collective_benchmark_timeout = float( + os.environ.get("TORCHINDUCTOR_COLLECTIVE_BENCHMARK_TIMEOUT", "30") +) + +coordinate_descent_tuning = ( + os.environ.get("TORCHINDUCTOR_COORDINATE_DESCENT_TUNING") == "1" +) +coordinate_descent_check_all_directions = ( + os.environ.get("TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS") == "1" +) +coordinate_descent_search_radius = int( + os.environ.get("TORCHINDUCTOR_COORDINATE_DESCENT_RADIUS", "1") +) + +# AutoHeuristic is a framework that allows one to collect data from autotuning, use the data to learn a heuristic, and +# generate the learned heuristic to code which is shipped with the compiler + + +def _parse_autoheuristic_collect_env(): + collect_env = os.environ.get("TORCHINDUCTOR_AUTOHEURISTIC_COLLECT", "").split(",") + return collect_env + + +def _parse_autoheuristic_use_env(): + use_env = os.environ.get("TORCHINDUCTOR_AUTOHEURISTIC_USE", "mixed_mm").split(",") + return use_env + + +class autoheuristic_collect: + """ + Config for which autoheuristic optimizations should collect training data. + """ + + pad_mm = "pad_mm" in _parse_autoheuristic_collect_env() + mixed_mm = "mixed_mm" in _parse_autoheuristic_collect_env() + + +class autoheuristic_use: + """ + Config for which autoheuristic optimizations should use learned heuristics. + """ + + pad_mm = True if "pad_mm" in _parse_autoheuristic_use_env() else None + mixed_mm = True if "mixed_mm" in _parse_autoheuristic_use_env() else None + + +# If set to 1, will run a JIT post compile hook if one is set. +run_jit_post_compile_hook = ( + os.environ.get("TORCHINDUCTOR_RUN_JIT_POST_COMPILE_HOOK", "0") == "1" +) + + +def run_autoheuristic(name: str) -> bool: + return collect_autoheuristic(name) or use_autoheuristic(name) + + +def collect_autoheuristic(name: str) -> bool: + if hasattr(autoheuristic_collect, name): + return getattr(autoheuristic_collect, name) + else: + # For test compatibility with non-standard ops (e.g. "test", "foo" used in tests) + return name in _parse_autoheuristic_collect_env() + + +def use_autoheuristic(name: str) -> bool: + if hasattr(autoheuristic_use, name): + attr = getattr(autoheuristic_use, name) + if attr is None: + return torch._inductor.config.deterministic + return attr + else: + # For test compatibility with non-standard ops (e.g. "test", "foo" used in tests) + return name in _parse_autoheuristic_use_env() + + +# If set to "DEFAULT", this will use the default log path specified in autoheuristic.py. +# If set to another path, autoheuristic will instead log results to the given path. +autoheuristic_log_path = os.environ.get( + "TORCHINDUCTOR_AUTOHEURISTIC_LOG_PATH", "DEFAULT" +) + +# Disabled by default on ROCm, opt-in if model utilises NHWC convolutions +layout_opt_default = "1" if not torch.version.hip else "0" +layout_optimization = ( + os.environ.get("TORCHINDUCTOR_LAYOUT_OPTIMIZATION", layout_opt_default) == "1" +) + +force_layout_optimization = os.environ.get("TORCHINDUCTOR_FORCE_LAYOUT_OPT", "0") == "1" + +# Cache SDPA constraint results keyed by (tensor identity, stride_order) to avoid +# creating duplicate buffers when the same tensor feeds multiple SDPA positions +# (e.g., key=value in simplified PMA attention). +cache_sdpa_constraint = ( + os.environ.get("TORCHINDUCTOR_CACHE_SDPA_CONSTRAINT", "0") == "1" +) + + +# Whether to keep the output strides the same as eager after layout optimization. +keep_output_stride = os.environ.get("TORCHINDUCTOR_KEEP_OUTPUT_STRIDE", "1") == "1" + +# Whether view outputs must match eager strides exactly instead of only matching +# their stride order. Exact matching can introduce additional copy kernels. +strict_output_strides = False + +# Enabling this will let compiler print warning messages if a generated triton +# kernel has inputs with mixed layouts. This is helpful for perf debugging +# since kernel with mixed layout inputs may run much slower then one whose inputs +# have uniform layouts. +warn_mix_layout = os.environ.get("TORCHINDUCTOR_WARN_MIX_LAYOUT") == "1" + +# control store vs recompute heuristic +# For fanouts, rematerialization can lead to exponential blowup. So, have +# smaller threshold +realize_reads_threshold = 4 +_realize_opcount_threshold_default = 30 +realize_opcount_threshold: int | None = None +realize_opusers_threshold = 5 +# CPU kernels tolerate larger fused pointwise bodies than GPU kernels, and +# materializing moderate CPU expressions can add expensive full-buffer traffic. +realize_cpu_opcount_threshold = 50 + +# Threshold to prevent excessive accumulation of ops in one buffer during lowering +_realize_acc_reads_threshold_default = 8 +realize_acc_reads_threshold: int | None = None +realize_cpu_acc_reads_threshold = 12 +realize_acc_reads_size_threshold: int | None = ( + None # TODO(xuanzh): harden this to make it non optional +) + + +# Defer early realization of cheap output nodes (0 buffer reads, small opcount) +# to prevent cascade materialization in fullgraph compilation. +# Shared constants/indices saved for backward get eagerly materialized because +# they are graph outputs with multiple users, which inflates downstream read +# counts and can trigger suboptimal Triton block size heuristics. +delay_realize_cheap_outputs: bool = Config( + env_name_force="TORCHINDUCTOR_DELAY_REALIZE_CHEAP_OUTPUTS", + default=True, +) + +# fallback to eager for random/dropout, this is slow but useful for debugging +fallback_random = False + +# align random/dropout as eager mode(aten) behavior, maintaining fused possibility and faster gpu kernel +align_random_eager = False + +# fallback embedding_bag_byte_unpack to eager +fallback_embedding_bag_byte_unpack = False + +# automatically create fallbacks when encountering an unhandled op +implicit_fallbacks = True +assume_unaligned_fallback_output = ( + os.environ.get("TORCHINDUCTOR_ASSUME_UNALIGNED_FALLBACK_OUTPUT") == "1" +) + +# Factory callable that returns a custom InductorChoices instance. +# A callable (rather than a class) is used to defer imports and avoid circular +# dependencies between config and the choices module. Example: +# +# def _custom_choices_factory(): +# from my_package.choices import MyInductorChoices +# return MyInductorChoices() +# +# config.inductor_choices_class = _custom_choices_factory +# +# The returned instance must implement uuid() for cache key serialization. +inductor_choices_class: Callable[[], "InductorChoices"] | None = None + +# fuse even in cases without common reads +aggressive_fusion = False + +# For each fused kernel in the wrapper, comment with the nodes that get fused. +# Useful for debugging fusion. +debug_fusion: bool = os.environ.get("TORCHINDUCTOR_DEBUG_FUSION") == "1" +benchmark_fusion: bool = os.environ.get("TORCHINDUCTOR_BENCHMARK_FUSION") == "1" +enabled_metric_tables = os.environ.get("TORCHINDUCTOR_ENABLED_METRIC_TABLES", "") +loop_ordering_after_fusion: bool = ( + os.environ.get( + "TORCHINDUCTOR_LOOP_ORDERING_AFTER_FUSION", "0" if is_fbcode() else "1" + ) + == "1" +) +loop_reindexing_after_fusion: bool = ( + os.environ.get("TORCHINDUCTOR_LOOP_REINDEXING_AFTER_FUSION", "1") == "1" +) + + +# When trying to fuse two nodes, one with: +# a[contiguous_writes] = fn(...) +# and another node: +# b[contiguous_writes] = a[discontiguous_reads] +# If b is unary, and we can figure out an inverse formula for +# discontiguous writes, invert b as : +# b[inverse(discontiguous_writes)] = a[contiguous_reads] +# so that the nodes can fuse. for more details: https://gist.github.com/eellison/6f9f4a7ec10a860150b15b719f9285a9 +loop_index_inversion_in_fusion: bool = True + +# If fusing two nodes only save less than score_fusion_memory_threshold memory, +# we should not bother fusing the nodes. +# +# This is especially helpful to resolve https://github.com/pytorch/pytorch/issues/133242 +# Previously we fuse two nodes because of common read of a scalar tensor. +# If we skip it, the loop ordering after fusion mechanism kicks in and can +# brings more savings. +# +# For the cases loop ordering after fusion does not help, we don't lose much. +score_fusion_memory_threshold = 10 + +# For Triton Templates, select fastest of best template + epilogue vs best template + separate epilogue kernel +benchmark_epilogue_fusion = ( + os.environ.get("TORCHINDUCTOR_BENCHMARK_EPILOGUE_FUSION", "1") == "1" +) + +# Take how many of the top triton kernels to benchmark epilogue +max_epilogue_benchmarked_choices = 1 + +# how many nodes to allow into a single fusion +max_fusion_size = 64 + +# Minimum overlap ratio to consider fusion beneficial when inputs are shared by no indices overlapped. +# Valid range: [0, 1]. Default to not fusion. +min_overlap_ratio = 1.1 + +# how many nodes to attempt pairwise fusion with in a buffer group +max_fusion_buffer_group_pairwise_attempts = 64 + +# maximum number of unique input/output buffers allowed in fused kernels. +# The check is disabled if set to None. +max_fusion_unique_io_buffers: int | None = None + +# max number of inputs to always fuse cat as a pointwise op regardless of +# per-input op complexity. Beyond this limit (up to max_pointwise_cat_inputs), +# fusion is only applied when every input has a low op count. +max_complex_pointwise_cat_inputs = 8 + +# max number of inputs to generate cat as a pointwise op with masked loads. +# Inputs beyond max_complex_pointwise_cat_inputs but within this limit are +# only fused when every input has a simple computation (op count <= 2). +max_pointwise_cat_inputs = 8 + +# force concat to be generated as a pointwise op with masked loads +force_pointwise_cat = False + +# replace small reductions with pointwise, disable with `= 1` +unroll_reductions_threshold = 8 + +# Add extra comments to output code (causes compile cache misses) +comment_origin = False + +# Convert 1x1 convs into matmuls +conv_1x1_as_mm = False + +# For reductions with a small output size (usually 1, e.g. x.sum()) there is not enough +# parallelism to saturate the GPU. We have two ways of handling this, either `split_reductions` +# or `triton.cooperative_reductions` which are mutually exclusive. +# split_reductions: uses multiple kernels to gain more parallelism +# triton.cooperative_reductions: uses cross thread-block synchronization to gain more parallelism +# enabling both of these will implicitly disable split_reductions +split_reductions = os.getenv("TORCHINDUCTOR_SPLIT_REDUCTIONS", "1") == "1" + +# A deterministic mode that skips any on device benchmarking in Inductor +# if we know they affect numerics. WARNING: Expect perf hit in this mode. +deterministic = os.getenv("TORCHINDUCTOR_DETERMINISTIC") == "1" + +# Batch-invariant mode: stable per-sample compiled kernel across batch sizes. Implies deterministic. +batch_invariant = os.getenv("TORCHINDUCTOR_BATCH_INVARIANT") == "1" + +# Use eager's opt-in INNER_TREE order for eligible NVIDIA CUDA sums. +# pyrefly: ignore [bad-assignment] +numerics: Literal["default", "strict"] = os.environ.get( + "TORCHINDUCTOR_NUMERICS", "default" +) # type: ignore[assignment] + +# When we do split reduction, this number control the minimum value for +# num_split. Too small num_split make the split reduction less efficient. +# It's a much bigger problem when we compile a dynamic shape kernel with +# non-representative inputs. +min_num_split = int(os.environ.get("TORCHINDUCTOR_MIN_NUM_SPLIT", 0)) + +benchmark_kernel = os.environ.get("TORCHINDUCTOR_BENCHMARK_KERNEL", "0") == "1" + +# Enable constant and index_expr folding +constant_and_index_propagation = True + +# we always add constants into graph.constants without +# performing any constant-inlining optimization +always_keep_tensor_constants = False + +# assert that indirect indexing does not read / write out of bounds +assert_indirect_indexing = True + +# skip emitting runtime assertions for unbacked symbols in generated code +do_not_emit_runtime_assertions = False + +# compute CSE bounds on variables that do not appear in the FX graph +compute_all_bounds = False + +# enable the combo kernel that combines data-independent kernels (additional +# to foreach kernels) into a single one (Experimental) +combo_kernels = False +# benchmark combo kernels and only allow ones with perf gains +benchmark_combo_kernel = False +# combo_kernel autotuning options: 0 - disable, 1 - enable except for foreach, +# 2 - enable for all +combo_kernels_autotune = 1 +# Enable masking for combining kernels of mixed sizes: 0 - disable, 1 - enable +# for all except for foreach, 2 - enable for all +combo_kernel_allow_mixed_sizes = 1 +# Enable dynamic shapes for foreach kernels +combo_kernel_foreach_dynamic_shapes = True +# Maximum number of arguments (read/write buffers) allowed in a combo kernel +combo_kernel_max_num_args = 250 +# Maximum number of sub-kernels allowed in a single combo kernel +combo_kernel_max_num_nodes = 8 +# When True, each combo sub-kernel gets its own block sizes (XBLOCK_0, YBLOCK_0, etc.) +# allowing different sub-kernels to use different tile sizes based on their heuristics. +# When False, all sub-kernels share block sizes (XBLOCK, YBLOCK, etc.) +combo_kernel_per_subkernel_blocks = False +# When True, each combo sub-kernel autotunes its block sizes standalone at compile time; the +# winning per-subkernel blocks are stitched into the combo kernel and passed as args (the combo +# then autotunes num_warps/num_stages over the winners). Requires +# combo_kernel_per_subkernel_blocks. +combo_kernel_compile_time_autotune: bool = Config( + justknob="pytorch/inductor:combo_kernel_compile_time_autotune", + env_name_force="TORCHINDUCTOR_COMBO_KERNEL_COMPILE_TIME_AUTOTUNE", + default=False, +) +# When True, combo-kernel autotuning groups sub-kernels that share the same +# candidate config set and kernel-analysis signature. Disabled by default. +combo_kernel_autotune_grouping = True +# When True, only pointwise kernels are eligible for combo kernel fusion. +combo_kernels_pointwise_only = False +# Memory-aware combo kernel gating. +# None: disable that threshold dimension +# 0: allow no graph-peak increase +# value: allow total graph-peak delta up to that limit +# The accepted delta is measured against the original graph peak before combo +# kernels. When both thresholds are set, the tighter limit wins. +combo_kernel_peak_memory_increase_gb: float | None = None # Absolute cap in GB +combo_kernel_peak_memory_pct_threshold: float | None = 0.05 +# Maximum baseline-index span of a single combo candidate. Groups whose +# first-to-last baseline-index distance exceeds this are split into +# sub-windows. Set to -1 (or any negative value) to disable splitting +# and treat each parallel group as one window. +combo_kernel_max_distance: int = -1 + +# constant folding on the joint graph +joint_graph_constant_folding = True + +# Enable indirect_indexing asserts for decompositions and lowerings +debug_index_asserts = False + +# warnings intended for PyTorch developers, disable for point releases +is_nightly_or_source = "dev" in torch.__version__ or "git" in torch.__version__ +developer_warnings = is_fbcode() or is_nightly_or_source + +# This pattern matches a special usage of scatter +# 1. It's applied to a constant tensor +# 2. The index tensor has size 1 in the scatter dimension +# Such pattern generates a sparse matrix when the const tensor is all-zero. +# We can lower this pattern to a pointwise kernel for more fusion opportunities +# and saving memory footprint. +optimize_scatter_upon_const_tensor = ( + os.environ.get("TORCHINDUCTOR_OPTIMIZE_SCATTER_UPON_CONST_TENSOR", "1") == "1" +) + +# options in caffe2/torch/_inductor/fx_passes/pre_grad.py +add_pre_grad_passes: str | None = None +remove_pre_grad_passes: str | None = None + +# Comma-separated list of pass names to disable. Passes disabled via this config +# will be skipped when they go through GraphTransformObserver. +# Can be set via TORCHINDUCTOR_DISABLED_PASSES env var. +# Use uppercase pass names (e.g., "PASS1,PASS2"). +disabled_passes: str = Config( + env_name_force="TORCHINDUCTOR_DISABLED_PASSES", + default="", +) + + +# The multiprocessing start method to use for inductor workers in the codecache. +def decide_worker_start_method() -> str: + if "TORCHINDUCTOR_WORKER_START" in os.environ: + start_method = os.environ["TORCHINDUCTOR_WORKER_START"] + else: + start_method = "subprocess" + if start_method not in ( + "subprocess", + "fork", + "spawn", + ): + raise AssertionError(f"Invalid start method: {start_method}") + return start_method + + +worker_start_method: str = decide_worker_start_method() + +# Threshold to decide if a kernel has small memory access in bytes +# Default value is 16 MB which is arbitrarily selected. +small_memory_access_threshold: int = 16777216 + +# Whether to log from subprocess workers that are launched. +worker_suppress_logging: bool = Config( + justknob="pytorch/compiler:worker_suppress_logging", + env_name_force="TORCHINDUCTOR_WORKER_SUPPRESS_LOGGING", + default=True, +) + +# The compile-worker sidecar runs a watchdog that, every N seconds, reports any +# compile job still running after N seconds back to the parent, which emits it as +# a structured-trace artifact (viewable in tlparse). This leaves a breadcrumb for +# a stuck/slow worker that would otherwise wedge silently (the parent just blocks +# reading the result pipe). Read in the sidecar. 0 disables the watchdog. +compile_worker_watchdog_interval_seconds: int = int( + os.environ.get("TORCHINDUCTOR_COMPILE_WORKER_WATCHDOG_INTERVAL", 60) +) + +# Log per-operation runtime estimates for TLParse analysis. +log_tlparse: bool = Config( + env_name_force="LOG_TLPARSE", + default=False, +) + +# Flags to turn on all_reduce fusion. These 2 flags should be automatically turned +# on by DDP and should not be set by the users. +_fuse_ddp_communication = False +_fuse_ddp_bucket_size = 25 + +# Flag to control which fusion passes to apply. Functions in the list will +# be applied in order. There are two different fusion passes +# --"fuse_ddp_with_concat_op" and "fuse_ddp_with_coalesced_op". The default +# one is "fuse_ddp_with_concat_op". Users can also change this to a customized +# fusion function. +# +# The fusion currently does not support multiple DDP with different PG or +# data type. This feature will be added in the future PRs. +# +# "schedule_comm_wait" is used to delay the wait ops to maximize comm/comp +# overlapping. At this moment, this pass performs better than +# reorder_for_compute_comm_overlap_passes but we will add the logic of +# "schedule_comm_wait" in the future and remove the one here. +_fuse_ddp_communication_passes: list[Callable[..., None] | str] = [ + "fuse_ddp_with_concat_op", + "schedule_comm_wait", +] + +_micro_pipeline_tp: bool = False + + +# Enable/disable partitioned scatter optimization for atomic add kernels. +# Improves kernel performance for high-contention index_put(accumulate=True) +# at the cost of temporary memory for expanded partition buffers. +_partitioned_scatter_default = "1" if torch.version.hip else "0" +partitioned_scatter_enabled = ( + os.environ.get( + "TORCHINDUCTOR_PARTITIONED_SCATTER_ENABLED", _partitioned_scatter_default + ) + == "1" +) + +# Power-of-2 bounds for num_partitions (bitwise AND partition assignment requires pow2). +# Capped at 64: contention relief saturates before that while the expanded buffer keeps +# growing, and P=128 measured slower than P=64 at every contention level on MI308X. +partitioned_scatter_min_partitions: int = 2 +partitioned_scatter_max_partitions: int = 64 + +# Skip ops with fewer writes than this — small scatters don't generate meaningful contention. +partitioned_scatter_min_index_size: int = 4096 + +# Skip ops where index_numel / scatter_dim_size is below this ratio. +# Contention is measured per scatter-dim slot; low density means most slots get ≤1 write. +# The partitioned form pays a zero-fill and reduce over the expanded buffer plus a +# slower scatter kernel (atomics over P copies lose cache residency), whether or not +# contention was actually relieved. Assumes indices spread uniformly over all slots; +# the real distribution is a runtime property, so concentrated indices are +# under-estimated here. +partitioned_scatter_min_contention_ratio: float = 4.0 + +# GPU memory reserved for state invisible to the FX profile: CUDA driver context, +# PyTorch caching allocator pool, and kernel scratch (cuBLAS/Triton). Subtracted from +# total GPU memory to compute available headroom for expanded partition buffers. +# 1.5 GB is conservative for MI300 (206 GB total); tune down to allow more partitions. +partitioned_scatter_non_model_floor_bytes: int = 1_500_000_000 + +# Bypass the heuristic skip gates (min_index_size, min_contention_ratio, and the +# diminishing-returns cap on num_partitions). Correctness gates and the hard memory +# budget are still enforced. Useful for benchmarking or skewed-index workloads where +# static estimates undercount real contention. +# Enable via: TORCHINDUCTOR_PARTITIONED_SCATTER_FORCE=1 +partitioned_scatter_force: bool = ( + os.environ.get("TORCHINDUCTOR_PARTITIONED_SCATTER_FORCE", "0") == "1" +) + + +class _collective: + auto_select: bool = False + one_shot_all_reduce_threshold_bytes: int = 128 * 1024 + + +class aten_distributed_optimizations: + """Configuration for distributed optimization passes on ATen FX graphs.""" + + # Move collectives earlier and waits later in the inductor schedule + # to overlap communication with compute. + # + # Guarantees: + # - No collective reordering (preserves NCCL stream ordering) + # - No memory regression (each move verified individually) + # - Predictable (no runtime estimation, no heuristics) + enable_simple_overlap: bool = True + + # Enable overlap scheduling pass + enable_overlap_scheduling: bool = False + + # Enable overlap-preserving collective bucketing + collective_bucketing: bool | None = None + + # Insert ordering dependencies to preserve overlap relationships. This should only be used if + # compiling with inductor, or for subsequent passes before removing the ops prior to execution + insert_overlap_deps: bool | None = None + + # Maximum compute node prefetch distance for overlap scheduling + max_compute_pre_fetch: int | None = None + + compute_overlap_multipler: float | None = None + + # Custom runtime estimation function for ops + # For user-defined estimation function, pass in the function handle + # None means use default estimations + # TODO - need estimated and profile based version + custom_runtime_estimation: Callable[[torch.fx.Node], float | None] | None = None + + # Method for estimating collective runtime + # "analytical": Use bandwidth formulas (default) + # "benchmark": Use CUDA events with power-of-2 rounding and interpolation + # In deterministic mode, this setting is ignored and "analytical" is used. + collective_estimator: Literal["analytical", "benchmark"] = "analytical" + + # Method for estimating compute (ATen op) runtime + # "analytical": Use roofline model estimates (deterministic, no GPU sync) + # "benchmark": Use GPU benchmarking (more accurate, requires GPU sync) + # In deterministic mode, this setting is ignored and "analytical" is used. + compute_estimator: Literal["analytical", "benchmark"] = "benchmark" + + # Chrome Trace JSON path for profile-guided runtime estimation. + profile_guided_estimations_profile_path: str | None = None + + # Maximum memory increase above baseline for prefetch operations + # Uses minimum of absolute cap and ratio of baseline + max_memory_increase_gb: float | None = None # Absolute cap in GB + max_memory_increase_ratio: float | None = None # Ratio of baseline peak memory + + # Maximum GB of concurrent collective data in flight. Too much in flight memory + # can cause memory fragmentation within the CUDA Caching Allocator. + max_in_flight_gb: float | None = None + + # Maximum prefetch or bucketing candidates. Mainly intended for compile time. + max_coll_distance: int | None = None + log_final_collectives_estimations: bool = False + + # Bucket exposed collectives first (None means auto) + bucket_exposed_first: bool | None = None + + # Experimental setting to bucket only internode communications + bucket_only_internode_comms: bool = False + + # Enable fusion region detection for overlap scheduling cost estimation. + # When enabled, groups of fusible ops (pointwise, reduction, etc.) have their + # I/O costs corrected to exclude intermediates that inductor will not materialize. + enable_fusion_regions: bool = True + + # Default bucketing mode for auto and manual overlap scheduling + # "default": traced bucketing, fully lowered by inductor during compilation + # "custom_ops": temporary bucketing using custom ops to hide parts from inductor + # "custom_ops_multidtype": same as custom_ops but buckets multiple dtypes + # (e.g. bf16 and fp32) into one bucket + # "coalesced": zero-copy batching via reduce_scatter_tensor_coalesced + # (reduce_scatter only; all_gather falls back to default) + # None means "auto" — the compiler picks the best mode + bucket_mode: ( + Literal["default", "custom_ops", "custom_ops_multidtype", "coalesced"] | None + ) = None + + # Prioritize bucketing during overlap scheduling by grouping candidates by bucket key + prioritize_bucketing_during_scheduling: bool = True + + # Verify FX graphs are identical across ranks before overlap scheduling. + # Detects non-SPMD graphs that would cause NCCL collective ordering + # mismatches and hangs. + # Disabled: when one rank has a cache hit while another has a cache miss, + # the check itself causes an NCCL hang. Re-enable once that is fixed. + spmd_check: bool = False + + # Action on SPMD graph mismatch: "warn" logs a warning, "error" raises + # RuntimeError. "error" fails fast instead of risking silent NCCL hang. + # TODO(ivankobzarev): change default to "error" after real-world testing. + spmd_mismatch: Literal["warn", "error"] = "warn" + + # When True, automatically remove extra deps that create cycles instead of + # raising an error. Set this to True as a workaround if overlap scheduling + # fails with a cycle error, and file a bug so the root cause can be fixed. + overlap_scheduling_autofix_cycles: bool = False + + # Replace NCCL collectives with low-contention variants that use + # copy engine instead of SMs, freeing SMs for overlapping compute. + enable_low_contention_collectives: bool = False + + # Replace collectives unconditionally, without checking for overlap. + low_contention_skip_overlap_check: bool = False + + # Minimum per-rank bytes for LC replacement. Below this, LC barrier + # overhead exceeds the benefit. Set to 0 to disable. + low_contention_min_bytes_per_rank: int = 16 * 1024 * 1024 + + # Pre-bucket FSDP collectives before overlap scheduling. + # Merges per-parameter FSDP collectives into buckets sized to + # saturate the process group's network bandwidth. + pre_bucketing_fsdp_collectives: bool = True + + # Override bucket cap in MB for pre-bucketing. When None, auto-computes + # from the NCCL analytical model using the configs below. + pre_bucketing_fsdp_collectives_bucket_cap_mb: float | None = None + + # Floor for auto-computed bucket cap in MB. + pre_bucketing_fsdp_collectives_min_bucket_cap_mb: float = 10.0 + + # Ceiling for auto-computed bucket cap in MB. + pre_bucketing_fsdp_collectives_max_bucket_cap_mb: float = 500.0 + + # Verbose logging: per-collective sizes and bucket composition + # via logger and trace_structured. + pre_bucketing_fsdp_collectives_verbose: bool = False + + # Multiplier on the empirical saturation model's output. + # With the empirical profiles this should be 1.0; kept for manual tuning. + pre_bucketing_fsdp_collectives_saturation_calibration_multiplier: float = 1.0 + + # Direct-input NVLS multicast + Copy Engine variant. Requires NVSwitch / + # NVLink SHARP and uses cudaMemcpyAsync to the multicast pointer. + low_contention_all_gather_ce_multicast: bool = False + + # Decompose collective patterns when mathematically equivalent local + # computation exists. See torch/_inductor/fx_passes/decomp_comms.py. + allow_comms_decompositions: bool = False + + +def parallel_compile_enabled_internally() -> bool: + """ + TODO: Remove when parallel compiled is fully enabled internally. For rollout, use a + knob to enable / disable. The justknob should not be performed at import, however. + So for fbcode, we assign compile_threads to 'None' below and initialize lazily in + async_compile.py. + """ + ENABLE_PARALLEL_COMPILE_VERSION = 1 + + jk_name = "pytorch/inductor:enable_parallel_compile_version" + version = torch._utils_internal.justknobs_getval_int(jk_name) + return ENABLE_PARALLEL_COMPILE_VERSION >= version + + +def decide_compile_threads() -> int: + """ + Here are the precedence to decide compile_threads + 1. User can override it by TORCHINDUCTOR_COMPILE_THREADS. One may want to disable async compiling by + setting this to 1 to make pdb happy. + 2. Set to 1 if it's win32 platform + 3. decide by the number of CPU cores + """ + import logging + + # Defined locally so install_config_module doesn't try to parse + # as a config option. + log = logging.getLogger(__name__) + + if "TORCHINDUCTOR_COMPILE_THREADS" in os.environ: + compile_threads = int(os.environ["TORCHINDUCTOR_COMPILE_THREADS"]) + log.info("compile_threads set to %d via env", compile_threads) + elif sys.platform == "win32": + compile_threads = 1 + log.info("compile_threads set to 1 for win32") + elif is_fbcode() and not parallel_compile_enabled_internally(): + compile_threads = 1 + log.info("compile_threads set to 1 in fbcode") + else: + cpu_count = torch._utils.cpu_count() + if not cpu_count: + raise AssertionError(f"expected nonzero cpu_count, got {cpu_count}") + compile_threads = min(32, cpu_count) + log.info("compile_threads set to %d", compile_threads) + + return compile_threads + + +# TODO: Set directly after internal rollout. +compile_threads: int | None = None if is_fbcode() else decide_compile_threads() + +# Whether to quiesce the Triton-compile subprocess pool at the end of each compilation. +quiesce_async_compile_pool: bool = Config( + justknob="pytorch/inductor:quiesce_async_compile_pool", + env_name_force="TORCHINDUCTOR_QUIESCE_ASYNC_COMPILE_POOL", + default=True, +) + +# Time in seconds to wait before quiescing +quiesce_async_compile_time: int = Config( + default=60, +) + +# Whether or not to enable statically launching CUDA kernels +# compiled by triton (instead of using triton's own launcher) +use_static_cuda_launcher: bool = static_cuda_launcher_default() + +# Alias of use_static_cuda_launcher, used by both CUDA/XPU. +use_static_triton_launcher: bool = Config( + alias="torch._inductor.config.use_static_cuda_launcher" +) + +# Attempt to statically launch user defined triton kernels +# Requires use_static_cuda_launcher +static_launch_user_defined_triton_kernels: bool = Config( + justknob="pytorch/inductor:static_launch_user_defined_triton_kernels", + env_name_force="TORCHINDUCTOR_STATIC_LAUNCH_USER_DEFINED_TRITON_KERNELS", + default=False, +) + +# Raise error if we bypass the launcher +strict_static_cuda_launcher: bool = ( + os.environ.get("TORCHINDUCTOR_STRICT_STATIC_CUDA_LAUNCHER", "0") == "1" +) + +# Alias of strict_static_cuda_launcher, used by both CUDA/XPU. +strict_static_triton_launcher: bool = Config( + alias="torch._inductor.config.strict_static_cuda_launcher" +) + +# Retain raw cubin bytes on statically-launchable Triton kernels when caching +# them, instead of dropping them and relying on the per-kernel cubin files left +# in the local Triton cache dir. Makes a cached CachingAutotuner portable across +# machines (e.g. a remote cache restored on a cold container), where +# reload_cubin_path can rehydrate from the retained bytes instead of forcing a +# recompile. Trades cache size for portability. +keep_static_cubin_raw: bool = ( + os.environ.get("TORCHINDUCTOR_KEEP_STATIC_CUBIN_RAW", "0") == "1" +) + +# Use _FastCudaLauncher (vectorcall C extension) instead of +# StaticallyLaunchedCudaKernel.run for the CachingAutotuner fast path. +# Pre-binds kernel metadata at first launch and uses THPVariable_Unpack + +# tensor.data_ptr() in C++ to bypass PyArg_ParseTuple, cuPointerGetAttribute, +# and cuCtxGetCurrent. +use_fast_triton_launcher: bool = ( + os.environ.get("TORCHINDUCTOR_USE_FAST_TRITON_LAUNCHER", "1") == "1" +) + +# Use the Level 0 launch_metadata_schema from CompiledKernel.bin +# (versioned, stable contract) instead of hasattr probing of +# CompiledKernel internals in save_gpu_kernel(). +# When True (default), prefers schema["entry_name"]/["num_warps"]/["shared_mem"]. +# When False, forces the legacy hasattr fallback path. +use_launch_metadata_schema: bool = ( + os.environ.get("TORCHINDUCTOR_USE_LAUNCH_METADATA_SCHEMA", "1") == "1" +) + +# gemm autotuning global cache dir +global_cache_dir: str | None +if is_fbcode(): + try: + from libfb.py import parutil + + if __package__: + global_cache_dir = parutil.get_dir_path( + os.path.join(__package__.replace(".", os.sep), "fb/cache") + ) + else: + global_cache_dir = parutil.get_dir_path("fb/cache") + except (ValueError, ImportError): + global_cache_dir = None + +else: + global_cache_dir = None + +# If kernel is fused, the name is generated from the origin node op names +# for larger kernels limit this +kernel_name_max_ops = 10 + +# Pad input tensors of matmul/bmm/addmm to leverage Tensor Cores in NVIDIA GPUs +shape_padding = os.environ.get("TORCHINDUCTOR_SHAPE_PADDING", "1") == "1" + +# Control if we will do padding for pointwise/reductions +comprehensive_padding = ( + os.environ.get("TORCHINDUCTOR_COMPREHENSIVE_PADDING", "1") == "1" +) +pad_channels_last = False + +# Control if we will do padding on dynamic shapes +pad_dynamic_shapes = False + +# Disable comprehensive padding on the CPU +disable_padding_cpu = True + +# Control if we will expand the dimension of pointwise nodes to fuse +expand_dimension_for_pointwise_nodes = False + +# The width of comprehensive padding, in bytes. +# CUDA max memory transaction size is 128 bytes for a warp. +padding_alignment_bytes = 128 + +# Threshold on the minimum stride that will be padded. +# +# Don't align a too small stride since that causes too much memory increase. +# Pad too small stride may also cause perf loss. We may result in many tiny data blocks +# with gaps in between. That causes less coalesced GPU memory access! +# +# Initially we pick 320 as the threshold since for alignment=16, +# that results in at most 5% memory cost. +# +# But later on we raise the threshold to 1024 to avoid interfere with persistent reduction. +# Let's say an inner reduction has a row size 513. Inductor will generate +# persistent reduction code. +# If we do padding, the strides are not contiguous any more. Inductor +# uses a much smaller threshold for persistent reduction in this case and +# generates potentially worse non-persistent reduction code. +# +# This change turns HF AllenaiLongformerBase amp training from a loss of 1.09x to a win of 1.05x. +# (baseline: 71.09ms, padding w/o this change: 77.38ms, padding with this change: 67.77ms) +padding_stride_threshold = 1024 + +# Enable padding outputs, even if they would not be padded in eager mode. +# By default, we use the same strides as eager mode. +pad_outputs = False + +# Whether to treat output of the backward graph as user visible. +# For user visible outputs, inductor will make sure the stride matches with eager. +bw_outputs_user_visible = True + +# Whether to always use shape padding if it is enabled and possible +force_shape_pad: bool = False + +# Fx-based linear/matmul/bmm + permute/transpose vertical fusion +permute_fusion = os.environ.get("TORCHINDUCTOR_PERMUTE_FUSION", "0") == "1" + +# Mark the wrapper call in PyTorch profiler +profiler_mark_wrapper_call = False + +# Generate hook calls to torch._inductor.hooks.run_intermediate_hooks for +# every intermediate for which we can correlate it with an intermediate +# from the original FX graph +generate_intermediate_hooks = False + +# Populate traceback field on IRNode; good for debugging why origin_node is +# not populated, or finding out where an IRNode was constructed +debug_ir_traceback = False + +# used for debugging to make sure config is properly set +_raise_error_for_testing = False + +# Use fp64 for unbacked float scalars (from .item()) in Triton kernel signatures +# to preserve precision. When False, uses fp32 (legacy behavior with precision loss). +_use_fp64_for_unbacked_floats: bool = not is_fbcode() + +_profile_var = os.environ.get("TORCHINDUCTOR_PROFILE", "") +profile_bandwidth = _profile_var != "" +profile_bandwidth_regex = "" if _profile_var == "1" else _profile_var +# Specify a file where we print out the profiling results. +# None means we do not dump results to a file. +profile_bandwidth_output: str | None = os.environ.get( + "TORCHINDUCTOR_PROFILE_OUTPUT", None +) +# Switch to do_bench_using_profiling to exclude the CPU overheads +profile_bandwidth_with_do_bench_using_profiling = ( + os.environ.get("TORCHINDUCTOR_PROFILE_WITH_DO_BENCH_USING_PROFILING") == "1" +) + + +# TODO: remove later +# incompatible with cpp_wrapper +disable_cpp_codegen = False + + +# Freezing will attempt to inline weights as constants in optimization +# and run constant folding and other optimizations on them. After freezing, weights +# can no longer be updated. +freezing: bool = os.environ.get("TORCHINDUCTOR_FREEZING", "0") == "1" + +# Make freezing invalidate the eager Parameters of nn modules, to avoid memory overhead +# of potentially keeping multiple copies of weights. +freezing_discard_parameters: bool = False + +# decompose some memory bound matmul/bmm to mul +decompose_mem_bound_mm: bool = False + +# Wrap compiled regions in inductor_compiled_code HOP to make them visible to +# TorchDispatchModes like DebugMode and Selective Activation Checkpointing. +wrap_inductor_compiled_regions: bool = False + +# assume_aligned_inputs means that we assume that inputs will be aligned; we generate +# code using this assumption, and clone tensors before use if they aren't aligned. +# In the common case, most inputs will be aligned. +assume_aligned_inputs: bool = False + +# assume_32bit_indexing means that we assume 32-bit indexing is always safe; we always +# use 32-bit indices regardless of tensor sizes. If assume_32bit_indexing contradicts +# with example inputs we throw. This is useful when all dynamic shapes are unbacked and +# you know you only operate with 32-bit sizes. +assume_32bit_indexing: bool = False + +# For the user-written Triton kernels compiled with the model, ignore the unsupported +# arguments passed to the @triton.autotune in the user's code; this is unsafe, as +# ignoring the unsupported args may lead to unexpected autotuning behavior: don't +# set unless you know what you're doing. +unsafe_ignore_unsupported_triton_autotune_args: bool = False + +# When True, we will check in scheduler.py _codegen that there are no "loops" +# in the call stack; that is to say, the same frame multiple times. This +# ensures that a cProfile trace to this frame will be a straight line without +# any cycles. Incompatible with cpp_wrapper. +check_stack_no_cycles_TESTING_ONLY: bool = False + +# When True, all compiled graphs report a cudagraph fail reason. Used by tests +# that need to exercise the cudagraph-skip path. +force_disable_cudagraph_TESTING_ONLY: bool = False + +# enable linear binary folding +enable_linear_binary_folding = ( + os.environ.get("TORCHINDUCTOR_ENABLE_LINEAR_BINARY_FOLDING", "0") == "1" +) + + +# Adds NVTX annotations around training phases +annotate_training: bool = os.environ.get("TORCHINDUCTOR_ANNOTATE_TRAINING", "0") == "1" + +# Enable caching codegen of triton templates. +enable_caching_generated_triton_templates: bool = True + +# Lookup table for overriding autotune configs based on hash of Triton source code +autotune_lookup_table: dict[str, dict[str, Any]] = {} + +file_lock_timeout: int = int(os.environ.get("TORCHINDUCTOR_FILE_LOCK_TIMEOUT", "600")) + +# Per-future timeout (seconds) for AsyncCompile._wait_futures. 0 (the +# default) means no timeout; a positive value raises a RuntimeError naming +# the kernel when a compile worker does not finish in time. CI sets this +# via TORCHINDUCTOR_COMPILE_WORKER_WAIT_TIMEOUT (300s) so a stuck compile +# doesn't burn the whole shard budget, while non-CI users with legitimately +# long compiles are not affected. +compile_worker_wait_timeout: int = int( + os.environ.get("TORCHINDUCTOR_COMPILE_WORKER_WAIT_TIMEOUT", "0") +) + +enable_autograd_for_aot: bool = False + + +def get_worker_log_path() -> str | None: + log_loc = None + if is_fbcode(): + mast_job_name = os.environ.get("MAST_HPC_JOB_NAME", None) + global_rank = os.environ.get("ROLE_RANK", "0") + + if mast_job_name is not None: + log_loc = f"/logs/dedicated_log_torch_compile_worker_rank{global_rank}" + + return log_loc + + +torchinductor_worker_logpath: str = Config( + env_name_force="TORCHINDUCTOR_WORKER_LOGPATH", + default="", +) + + +class auto_chunker: + enable: bool = os.environ.get("TORCHINDUCTOR_AUTO_CHUNKER") == "1" + + # Don't chunk from a node if the output size is not large enough + output_size_threshold: int = 1024 * 1024 + + # Don't chunk from a node if it does not 'amplify' the inputs a lot + amplify_ratio_threshold: int = 8 + + num_chunk: int | None = ( + int(os.environ.get("TORCHINDUCTOR_CHUNKER_NUM_CHUNKS")) # type: ignore[arg-type] + if os.environ.get("TORCHINDUCTOR_CHUNKER_NUM_CHUNKS") is not None + else None + ) # If not None, use this to force number of chunks + + +# config specific to codegen/cpp.py +class cpp: + """ + Settings for cpp backend. + This class provides a centralized location for managing cpp backend settings. + """ + + # set to torch.get_num_threads() + threads = -1 + + # Do not generate loops when the condition doesn't hold, like: + # for(long i0=4096; i0<4096; i0+=1) + no_redundant_loops = ( + os.environ.get("TORCHINDUCTOR_CPP_NO_REDUNDANT_LOOPS", "1") == "1" + ) + + # Assume number of threads is dynamic, don't specialize thread number. + # Kernels don't recompile on thread number changes with this flag on. + # For single-threaded workload, turning it on would incur a slight + # performance degradation. + dynamic_threads = os.environ.get("TORCHINDUCTOR_CPP_DYNAMIC_THREADS", "0") == "1" + + simdlen: int | None = None + min_chunk_size = int(os.environ.get("TORCHINDUCTOR_CPP_MIN_CHUNK_SIZE", "512")) + + cxx: tuple[None, str] = ( + None, # download gcc12 from conda-forge if conda is installed + os.environ.get("CXX", "clang++" if sys.platform == "darwin" else "g++"), + ) # type: ignore[assignment] + + # Target CPU architecture for C++ wrapper compilation. When unset, Inductor + # uses the platform default. Set to "" to suppress the architecture flag. + march: str | None = os.environ.get("TORCHINDUCTOR_CPP_MARCH") + + # Allow kernel performance profiling via PyTorch profiler + enable_kernel_profile = ( + os.environ.get("TORCHINDUCTOR_CPP_ENABLE_KERNEL_PROFILE", "0") == "1" + ) + + # Allow emitting KernelContextGuard metadata alongside kernel profiling. + # This switch only works when enable_kernel_profile is set to 1. + enable_kernel_context_guard = ( + os.environ.get("TORCHINDUCTOR_CPP_ENABLE_KERNEL_CONTEXT_GUARD", "0") == "1" + ) + + # enable weight prepacking to get a better performance; may lead to large memory footprint + weight_prepack = os.environ.get("TORCHINDUCTOR_CPP_WEIGHT_PREPACK", "1") == "1" + + # Inject a bug into our relu implementation; useful for testing our repro + # extraction and minification functionality. + # Valid values: "compile_error", "runtime_error", "accuracy" + inject_relu_bug_TESTING_ONLY: str | None = None + inject_log1p_bug_TESTING_ONLY: str | None = None + + # If None, autodetect whether or not AVX512/AVX2 can be used. Otherwise, + # force usage as specified, without testing. Default None. + vec_isa_ok: bool | None = get_tristate_env("TORCHINDUCTOR_VEC_ISA_OK") + + # similar to config.triton.descriptive_names + descriptive_names: Literal["torch", "original_aten", "inductor_node"] = ( + "original_aten" + ) + + # how many nodes to allow into a single horizontal fusion + max_horizontal_fusion_size = int( + os.environ.get("TORCHINDUCTOR_CPP_MAX_HORIZONTAL_FUSION_SIZE", "16") + ) + + # Make scatter_reduce fallback when reduce is sum to avoid performance regression + # using atomic_add. + fallback_scatter_reduce_sum = ( + os.environ.get("TORCHINDUCTOR_CPP_FALLBACK_SCATTER_REDUCE_SUM", "1") == "1" + ) + + # Use funsafe-math-optimizations when compiling + enable_unsafe_math_opt_flag = ( + os.environ.get("TORCHINDUCTOR_CPP_ENABLE_UNSAFE_MATH_OPT_FLAG", "0") == "1" + ) + + # Use ffp-contract when compiling + # Options: "off" (default), "on", "fast" + # Per https://godbolt.org/z/bf4bvfc9r , clang/gcc has different behavior for "fast" + enable_floating_point_contract_flag = os.environ.get( + "TORCHINDUCTOR_CPP_ENABLE_FLOATING_POINT_CONTRACT_FLAG", "off" + ) + + # Disable the tiling select heuristic + enable_tiling_heuristics = ( + os.environ.get("TORCHINDUCTOR_CPP_ENABLE_TILING_HEURISTIC", "1") == "1" + ) + + # Enable the Grouped GEMM Fusion + enable_grouped_gemm_template = False + + # Maximal allowed number of slices on K-dim for a GEMM kernel. This controls + # the maximal parallelism of K-slicing. Since K-slicing requires extra thread + # synchronization and buffers, the maximal number of slices is limited to + # mitigate the sync overhead and memory usage. + # When set to 0, the number of slices is unlimited. + gemm_max_k_slices = int(os.environ.get("TORCHINDUCTOR_CPP_GEMM_MAX_K_SLICES", "1")) + + # For perf tuning and debugging purpose, configure the pre-defined cache blocking for + # MxNxK dims respectively. The blockings are separated by comma and the unit is + # the number of register blocks. + # For example, "4,1,10" means 4 register blocks on M, 1 on N and 10 on K respectively. + gemm_cache_blocking = os.environ.get("TORCHINDUCTOR_CPP_GEMM_CACHE_BLOCKING", None) + + # For perf tuning and debugging purpose, configure the pre-defined thread blocking factors for + # MxNxK dims respectively. The factors are separated by comma and their product + # should be the same as the total number of threads. + # For example, if the total number of threads is 56, "7,4,2" means the work is + # decomposed into 7x4x2 thread blocks along MxNxK of a GEMM. + gemm_thread_factors = os.environ.get("TORCHINDUCTOR_CPP_GEMM_THREAD_FACTORS", None) + + # Whether to enable masked vectorization for the tail_loop. + enable_loop_tail_vec = True + + # Whether to enable concat linear for cpu device + # Currently concat linear on CPU not always have benefit, depends on linear'shape or + # computing resource. We set this default to False to avoid regressions. User and + # enable this feature by their need. + enable_concat_linear = False + + # Whether to use decomposed tanh for cpu device + # Disable by default due to https://github.com/pytorch/pytorch/issues/148241 + use_decompose_tanh = ( + os.environ.get("TORCHINDUCTOR_CPP_USE_DECOMPOSE_TANH", "0") == "1" + ) + + # Use a small dequant buffer for wgt of woq int4 size as: [q_group_size, Nr] + use_small_dequant_buffer = False + + force_inline_kernel = ( + os.environ.get("TORCHINDUCTOR_CPP_FORCE_INLINE_KERNEL", "0") == "1" + ) + + # Use static constexpr or static const for int array + use_constexpr_for_int_array = ( + os.environ.get("TORCHINDUCTOR_CPP_USE_CONSTEXPR_FOR_INT_ARRAY", "1") == "1" + ) + + # threshold between two step reduction algorithm and welford reduction algorithm + use_two_step_variance_threshold = 1024 + + +def tlx_mode_from_env() -> Literal["allow", "force"] | None: + # Only the explicit values "allow"/"force" enable torchTLX. Any other + # value -- unset, empty, a typo, or a legacy "default" -- maps to None so + # TLX stays off. See the "Knob" section of the torchTLX README under + # third-party/triton/.../tlx/language/tlx/inductor/README.md. + mode = os.environ.get("TORCHINDUCTOR_TLX_MODE") + if mode in ("allow", "force"): + return cast("Literal['allow', 'force']", mode) + return None + + +class triton: + """ + Config specific to codegen/triton.py + """ + + # torchTLX enablement. None (the default) means TLX is never considered + # (standard Inductor behavior); "allow" lets TLX compete via autotuning; + # "force" uses only TLX templates plus forced epilogue fusion. Also a + # no-op unless the active Triton is the fbtriton fork (the integration + # import in template_heuristics/tlx.py fails cleanly otherwise). + tlx_mode: Literal["allow", "force"] | None = tlx_mode_from_env() + + # Use cudagraphs on output code + cudagraphs = os.environ.get("TORCHINDUCTOR_CUDAGRAPHS") == "1" + + # Use cudagraph trees for memory pooling if `cudagraphs` is True + cudagraph_trees = True + + # Should we skip cudagraphing graphs with dynamic shape inputs + # If False, we will re-record a graph for each unique set of shape inputs + cudagraph_skip_dynamic_graphs = False + + # Specify dynamic shapes to capture cudagraphs and skip cudagraph for other shapes. + # Default to None, which means we capture cudagraphs for all shapes. + cudagraph_capture_sizes: tuple[int | tuple[int, ...]] | None = None + + # Minimum number of nodes (kernels) required for a cudagraph partition. + # If a partition has fewer nodes than this threshold, it won't be cudagraphed. + # This helps avoid overhead for very small partitions where cudagraph + # recording/replay cost outweighs the benefits. + # Set to 0 to disable this check. + cudagraph_min_partition_size = 0 + + # assertions not on the fast path, steady state + slow_path_cudagraph_asserts = True + + # TODO - need to debug why this prevents cleanup + cudagraph_trees_history_recording = False + + # Emit objgraph backref dumps for leaked cudagraph pool tensors + cudagraph_trees_objgraph = False + + # Which live cudagraph tree storages to clone before starting a new + # generation. None keeps the existing stale-output error behavior. + # "user_visible" clones live user-visible output storages out of + # the graph pool. Backward graph outputs are not selected for cloning. + # This mode can add overhead because live outputs that cross generations + # are explicitly copied and stop using cached TensorImpl outputs. Users + # can leave this unset and manually clone/copy those outputs instead. + cudagraph_trees_generation_cloning: Literal["user_visible"] | None = None + + # Enable cudagraph support for mutated inputs from prior cudagraph pool + cudagraph_support_input_mutation = not is_fbcode() + + # Maximal number of allowed cudagraph re-record for a function and + # a cudagraph node due to static input tensor address changes or + # cudagraph managed tensor data pointer changed. + # i.e., allow num_recording <= cudagraph_unexpected_rerecord_limit + # note: we are conservative here and choose a large limit. + cudagraph_unexpected_rerecord_limit = 128 + + # Warn loudly when the number of cudagraphs due to dynamic shape + # exceeds this limit + cudagraph_dynamic_shape_warn_limit: int | None = 8 + + # synchronize after cudagraph invocation + force_cudagraph_sync = False + + # always run cudagraphs in the eager warmup stage + # instead of recording and executing cudagraphs + force_cudagraphs_warmup = False + + # If False (default), torch.compile skips cudagraph for a graph if it + # contains cudagraph-unsafe ops. If True, we require that all cuda ops + # be captured into cudagraph. If this is not possible, this will raise + # an error. + cudagraph_or_error: bool = Config( + env_name_force="TORCHINDUCTOR_CUDAGRAPH_OR_ERROR", + default=False, + ) + + # reorder nodes to minimize the number of graph partitions while + # not incurring large memory overhead + reorder_for_reducing_graph_partitions: bool = True + + # Memory budget multiplier for cudagraph partition reordering. + # When reordering nodes to minimize partitions, the reordering is only + # applied if the peak memory increase is within this budget. + cudagraph_partition_memory_budget: float = 1.1 + + # assertions on the fast path + fast_path_cudagraph_asserts = False + + # skip warmup for cudagraph trees + skip_cudagraph_warmup = False + + # Synchronize before and after every compiled graph. + debug_sync_graph = False + + # Synchronize after every kernel launch, to help pinpoint bugs + debug_sync_kernel = False + + # Always load full blocks (rather than broadcasting inside the block) + dense_indexing = False + + coalesce_tiling_analysis: bool = Config( + justknob="pytorch/inductor:coalesce_tiling_analysis", + env_name_force="TORCHINDUCTOR_COALESCE_TILING_ANALYSIS", + default=True, + ) + + # limit tiling dimensions + # - max_tiles=1 disables tiling + # - max_tiles=2 + # - max_tiles=3 is experimental and may have bugs + # higher values are unsupported + + # We use a max of 3 if coalesce_tiling_analysis is True, and 2 otherwise. + # Note - coalesce_tiling_analysis does not yet apply to dynamic shapes. + max_tiles: int | None = None + + # Prefer higher dimensional tilings. This simplifies indexing expressions, making + # it easier to identify block pointers. + prefer_nd_tiling: bool = False + + # use triton.autotune for pointwise ops with complex layouts + # this should only be disabled for debugging/testing + autotune_pointwise = True + + # max autotune gemm with cublasLt + autotune_cublasLt = True + + # Tune the generated Triton kernels at compile time instead of first time they run + # Setting to None means uninitialized + autotune_at_compile_time: bool | None = autotune_at_compile_time_default() + + # We use random tensors for autotune by default. Setting this as true will let us + # use inputs from sample inputs to autotune user defined triton kernels. + # Side effect for this option is increased memory footprint during first pass compilation. + autotune_with_sample_inputs: bool = False + + # Allows tiling reductions into multiple dimensions. + # For best results, this should be used with prefer_nd_tiling. + tile_reductions: bool = False + + # Codegen matmul natively with tl.dot without using a template. + # This option makes Inductor generate matrix multiplication from scratch, + # instead of calling predefined Triton templates (mm, bmm, mm_plus_mm). + # Compile time may be longer because native matmul benchmarks more Triton configs + # than regular pointwise or reduction kernels. + # Native matmul often aggressively fuses operations around the matrix multiply, + # which can make it faster or slower depending on your program. + # + # This option takes priority over other GEMM implementations. If Inductor determines + # that a matmul can be generated, it will always generate it with native_matmul. + # That means optimized kernels such as decompose_k or persistent_tma_matmul will + # not be called when this option is enabled. + # + # Note: Native matmul does not currently support block pointers or TMA matmul. + # If both native_matmul and (use_block_ptr or enable_persistent_tma_matmul) are enabled, + # an error will be thrown. + native_matmul: bool = os.getenv("TORCHINDUCTOR_NATIVE_MATMUL", "0") == "1" + + # should we stop a fusion to allow better tiling? + tiling_prevents_pointwise_fusion = True + tiling_prevents_reduction_fusion = True + + # should we give different names to kernels + # Note: This is orthogonal to descriptive_names - this is deciding whether + # our triton kernel names should all be `triton_` (to maximize caching) or + # whether they should be unique. + unique_kernel_names = ( + os.environ.get("TORCHINDUCTOR_UNIQUE_KERNEL_NAMES", "1") == "1" + ) + + # similar to the option above, but this is specific to user defined kernels, + # while unique_kernel_name is for kernels generated by inductor. + # We have this option because sometimes we reuse user's kernel code with different + # configs which would result in the same name. + # Note: This MODIFIES the user's kernel function name within inductor phase. + unique_user_kernel_names = ( + os.environ.get("TORCHINDUCTOR_UNIQUE_USER_KERNEL_NAMES", "0") == "1" + ) + + # should we put op names in kernel names + # "torch": Maps to the fx op in the Dynamo graph (module name, method name, etc.) + # "original_aten": Maps to the highest-level aten op (i.e. pre-decompositions) + # "inductor_node": Maps to the node name in the FX graph passed to Inductor + descriptive_names: Literal["torch", "original_aten", "inductor_node"] = ( + "original_aten" + ) + + # use alternate codegen for smaller reductions + persistent_reductions = ( + os.environ.get("TORCHINDUCTOR_PERSISTENT_REDUCTIONS", "1") == "1" + ) + + # Decompose sort-based ops (sort, mode, median) to generate Triton + # kernels instead of falling back to ATen eager. When enabled, sort + # removes the default 512-element dimension limit and uses int32 + # indices (up to 2^31-1 elements), and mode/median decompose into + # sort + reduction / pointwise ops that Inductor can lower to Triton. + decompose_sort_ops: bool = ( + os.environ.get("TORCHINDUCTOR_DECOMPOSE_SORT_OPS", "0") == "1" + ) + + # For small output size reductions uses cross thread-block synchronization to gain more parallelism + cooperative_reductions = ( + os.environ.get("TORCHINDUCTOR_COOPERATIVE_REDUCTIONS", "0") == "1" + ) + + # used for debugging cooperative reduction codegen, always generate cooperative_reductions + force_cooperative_reductions = False + + # Lower/upper bounds between two-step variance and Welford variance for + # non-split CUDA Triton half/bfloat16 reductions. Mid-sized reductions use + # two-step for throughput; smaller reductions keep the old heuristic because + # training gradients are more sensitive to the different accumulation order. + use_two_step_variance_min_numel = 1024 + use_two_step_variance_threshold = 32768 + + # 0: disable + # 1/True: enable, use tuning to pick between different subkernels + # 2: enable, force using persistent reduction (for debugging) + # 3: enable, force using non-persistent reduction (for debugging) + # pyrefly: ignore [bad-assignment] + multi_kernel: Literal[0, 1, 2, 3] = int( + os.environ.get("TORCHINDUCTOR_MULTI_KERNEL", "0") + ) # type: ignore[assignment] + + # hint to Triton when arguments are divisible by 16 + divisible_by_16 = os.environ.get("TORCHINDUCTOR_DIVISIBLE_BY_16", "1") == "1" + + # On AMD/HIP, annotate pointer args with tt.pointer_range=32 when the + # tensor storage provably fits in 2 GB. This lets Triton emit efficient + # buffer load/store ops. Disable if a Triton compiler bug is triggered. + emit_pointer_range_32 = ( + os.environ.get("TORCHINDUCTOR_EMIT_POINTER_RANGE_32", "1") == "1" + ) + + # Minimum R0_BLOCK to be used for a TritonSplitScanKernel + # NOTE: This also indirectly controls the size of workspace buffer required + min_split_scan_rblock = 256 + + # Store the generated cubin files for cpp wrapper code to load + store_cubin = False + + # the max number of spills we allow for the configs we benchmark. + # Setting this to 0 means we skip a config if it spills even a single + # register. + # Setting it to a larger value allows a config spilling a small amount + # of registers being benchmarked. + # + # NOTE: triton will always report >0 register spills for kernels using sin/cos. + # (check this issue https://github.com/triton-lang/triton/issues/1756 ) + # So far we see a fixed 8 spilled registers for kernels using sin/cos. + # Raise the threshold to 16 to be safe. + # We should revisit this once we understand more of the source of register spills. + spill_threshold: int = 32 if torch.version.hip else 16 + + # Generate code containing the newer tl.make_block_ptr() API for loads/store + use_block_ptr = False + + # (Experimental) + # Generate code using the tl.make_tensor_descriptor() API for loads/store + # [Note: TMA API Restrictions] Currently the TMA API requires the following: + # - For Nvidia GPUs, the compute capability should be >= 9.0 + # - The innermost stride of a descriptor should be 1 + # - The size of the block shape in the innermost dimension should load / store + # at least 16 bytes. + # - Tensors are 16 byte aligned. Enabling this option therefore requires + # assume_aligned_inputs to also be enabled + # TMA descriptors are only going to be generated if the above conditions + # can be satisfied, along with any existing requirements for index expressions + use_tensor_descriptor = False + + # (Experimental) + # Whether to allow reordering tensor descriptor matches with descending + # strides, at the expense of transposing values after load / before store. + transpose_discontiguous_tensor_descriptor = True + + # Inject a bug into our relu implementation; useful for testing our repro + # extraction and minification functionality. + # Valid values: "compile_error", "runtime_error", "accuracy" + inject_relu_bug_TESTING_ONLY: str | None = None + + # Whether to upcast float16 / bfloat16 to float32 in triton codegen (Experimental) + codegen_upcast_to_fp32 = True + + # Whether persistent matmul kernels should be enabled. On NVIDIA H100+ with TMA support, + # this enables TMA persistent kernels. On AMD GPUs without TMA, this enables + # non-TMA persistent kernels as a fallback. + enable_persistent_tma_matmul = ( + os.environ.get("ENABLE_PERSISTENT_TMA_MATMUL", "0") == "1" + ) + # Should TMA store be enable from templates. TODO: Remove once we + # can autotune over the result. + enable_template_tma_store = os.environ.get("ENABLE_TEMPLATE_TMA_STORE", "0") == "1" + # Controls TMA load enablement in template epilogues + enable_tma_load_for_template_epilogue = ( + os.environ.get("ENABLE_TMA_LOAD_FOR_TEMPLATE_EPILOGUE", "0") == "1" + ) + # Host-side TMA: build TensorDescriptors on the host and pass them as kernel + # args instead of creating them device-side inside the kernel. Selects the + # descriptor flavor only; requires use_tensor_descriptor and + # assume_aligned_inputs to also be enabled (no effect otherwise). + enable_host_side_tma = os.environ.get("ENABLE_HOST_SIDE_TMA", "0") == "1" + + # Expand the Blackwell GEMM search space with Meta Triton autoWS knobs + # (no-op on archs/Triton builds without meta-WS). + enable_template_autows = os.environ.get("ENABLE_TEMPLATE_AUTOWS", "0") == "1" + + # Skip L1 cache for buffers that are used only once. Disabled by default + skip_l1_cache = os.environ.get("TORCHINDUCTOR_SKIP_L1", "0") == "1" + + # During autotuning, if one of the kernels/configs fails for some reason, + # Inductor will usually skip it (and assign its latency to inf). + # For testing it's helpful to be able to assert that none of the configs fail. + # Note: it may also need to be used with config.compile_threads = 1 + disallow_failing_autotune_kernels_TESTING_ONLY = False + + # specify number of splits to autotune on for decompose_k. 0 disables decompose_k + # Disabled on ROCm by default pending performance validation. + num_decompose_k_splits = int( + os.environ.get( + "TORCHINDUCTOR_NUM_DECOMPOSE_K_SPLITS", "0" if torch.version.hip else "10" + ) + ) + + # specify minimum ratio of K to M AND N in order to autotune on decompose_k. 0 enables + # it as an autotuning choice for all matmuls + decompose_k_threshold = int( + os.environ.get("TORCHINDUCTOR_DECOMPOSE_K_THRESHOLD", "32") + ) + + # Programmatic Dependent Launch improves launch latency on Nvidia Hopper+ devices + # If set to true, will generate PDL code on devices that support it. + # If set to false, will never generate PDL code. + enable_pdl = os.environ.get("TORCHINDUCTOR_ENABLE_PDL", "0") == "1" + + mix_order_reduction = ( + os.environ.get("TORCHINDUCTOR_MIX_ORDER_REDUCTION", "0" if is_fbcode() else "1") + == "1" + ) + mix_order_reduction_initial_xblock = 1 + + mix_order_reduction_split_size: int | None = None + mix_order_reduction_autotune_split_size = ( + os.environ.get("TORCHINDUCTOR_MIX_ORDER_REDUCTION_AUTOTUNE_SPLIT_SIZE", "0") + == "1" + ) + # If set to true, will skip some non-critical checks in the mix order reduction + # this could be helpful to avoid recompilations in some cases + mix_order_reduction_non_strict_mode = False + + # Maximum external read buffers (loads) in a mix-order reduction + # kernel. Set to 0 to disable the check. + mix_order_reduction_max_reads = 10 + + # Don't allow multi-stages by default to avoid out of shared memory + mix_order_reduction_allow_multi_stages = ( + os.environ.get("TORCHINDUCTOR_MIX_ORDER_REDUCTION_ALLOW_MULTI_STAGES", "1") + == "1" + ) + + # Fuse dependent cross-axis reductions (e.g., RMSNorm over D followed + # by per-block amax over a small group dimension like FP8 block size) + # into a single kernel with two sequential reduction passes. + nested_reduction = os.environ.get("TORCHINDUCTOR_NESTED_REDUCTION", "0") == "1" + + # Map for storing the amount of kernel runs with dumped input tensors + # Based on hash of Triton source code to avoid bloating the folder + debug_dump_kernel_inputs: dict[str, int] = {} + + # Value for the maximum amount of runs with dumped kernel input tensors + # When the maximum is reached the first values get overwritten + # This ensures the last N runs are saved, where N is this value + max_kernel_dump_occurrences = 3 + + proton_profiling: bool = ( + os.environ.get("TORCHINDUCTOR_TRITON_PROTON_PROFILING", "0") == "1" + ) + # If not specified, proton traces will be saved to the debug directory + proton_output_dir: str | None = os.environ.get( + "TORCHINDUCTOR_TRITON_PROTON_OUTPUT_DIR" + ) + # Group CTAs by SM in proton trace files. + proton_group_by_sm: bool = ( + os.environ.get("TORCHINDUCTOR_TRITON_PROTON_GROUP_BY_SM", "1") == "1" + ) + # Split proton trace files by kernel invocation. + proton_split_invocations: bool = ( + os.environ.get("TORCHINDUCTOR_TRITON_PROTON_SPLIT_INVOCATIONS", "1") == "1" + ) + # Process warp tracks into CTA tracks (min warp start, max warp end) and + # assign CTAs to slots per SM such that CTAs do not overlap. + proton_per_cta_occupancy: bool = ( + os.environ.get("TORCHINDUCTOR_TRITON_PROTON_PER_CTA_OCCUPANCY", "1") == "1" + ) + + dynamic_disable_pipelining = True + + +class aot_inductor: + """ + Settings for Ahead-Of-Time Inductor Compilation + """ + + # When True, each kernel in the autotune code allocates fresh tensors, + # runs, then immediately dels all tensors. Shared tensors are re-allocated + # for each consumer kernel. This prevents OOM from simultaneous live + # tensors in star-shaped graphs at the cost of more allocations during + # autotuning. When False (default), tensors are shared across kernels + # and del'd at their last consumer (faster but higher peak memory). + autotune_per_kernel_alloc: bool = False + + # AOTInductor output path + # If an absolute path is specified, the generated lib files will be stored under the directory; + # If a relative path is specified, it will be used as a subdirectory under the default caching path; + # If not specified, a temp directory will be created under the default caching path. + # If the specified path contains something like "model.so", the sub-string will be used + # to name the generated library. + output_path = "" + + debug_compile = os.environ.get("AOT_INDUCTOR_DEBUG_COMPILE", "0") == "1" + debug_symbols = os.environ.get("AOT_INDUCTOR_DEBUG_SYMBOLS", "0") == "1" + + # Enable frame pointers for profiling tools (e.g. strobelight) + enable_frame_pointer = ( + os.environ.get("AOT_INDUCTOR_ENABLE_FRAME_POINTER", "1") == "1" + ) + + # Enable lightweight line tables for profiling tools (e.g. strobelight) + enable_line_tables = os.environ.get("AOT_INDUCTOR_ENABLE_LINE_TABLES", "1") == "1" + + # Annotate generated main wrapper function, i.e. AOTInductorModel::run_impl, + # to use which cpp compiler optimization level, default to O1 + compile_wrapper_opt_level = os.environ.get( + "AOT_INDUCTOR_COMPILE_WRAPPER_OPT_LEVEL", "O1" + ) + + # option for debug printing/saving for intermediate tensor values for aot inductor + # 0: disable debug dumping + # 1: enable saving intermediate tensor values + # 2: enable printing intermediate tensor values + # 3: enable printing kernel names only (useful for pinpointing troublesome kernels) + # pyrefly: ignore [bad-assignment] + debug_intermediate_value_printer: Literal["0", "1", "2", "3"] = os.environ.get( + "AOT_INDUCTOR_DEBUG_INTERMEDIATE_VALUE_PRINTER", "0" + ) # type: ignore[assignment] + + # filtered nodes to be printed for debug values. Specify this option when debug_intermediate_value_printer is set to 2 + filtered_kernel_names = os.environ.get( + "AOT_INDUCTOR_FILTERED_KERNELS_TO_PRINT", None + ) + + # Serialized tree spec for flattening inputs + # TODO: Move this into metadata + serialized_in_spec = "" + + # Serialized tree spec for flattening outputs + # TODO: Move this into metadata + serialized_out_spec = "" + + # flag to decide whether to create a submodule for constant graph. + use_runtime_constant_folding: bool = False + + # flag to force weight to be appended to the shared library and mapped by the runtime + # rather than embedded into the data section. Needed to support 1B+ parameter models + force_mmap_weights: bool = False + + # Default value of use_consts_asm_build is True, it will build by assembly language. + # When the value is False, it will build by c++ language. + use_consts_asm_build = True + + package: bool = False + package_cpp_only: bool | None = None + + # If package_cpp_only is True, whether cpp files will be compiled to a + # dynamically linked library or static linked library + dynamic_linkage: bool = True + + # Dictionary of metadata users might want to save to pass to the runtime. + # TODO: Move this somewhere else, since it's no longer really a config + metadata: dict[str, str] = {} + + # fbcode only. Whether to raise error if C++ codegen is too big to optimize + raise_error_on_ignored_optimization: bool = ( + os.environ.get("AOTINDUCTOR_RAISE_ERROR_ON_IGNORED_OPTIMIZATION", "1") == "1" + ) + + # Whether to check lowerbound constraints on dynamic shapes during runtime. + # When disabled, allows models with dynamic sizes of 0 or 1 to work with + # AOTI_RUNTIME_CHECK_INPUTS=1, avoiding errors from the [2+, ...] lowerbound + # restriction when backed_size_oblivious is off. + check_lowerbound: bool = True + + # dump an aoti minifier if program errors + dump_aoti_minifier: bool = os.environ.get("DUMP_AOTI_MINIFIER", "0") == "1" + + # Compiler compilation debug info + # 1: Dumps the original graph out to repro.py if compilation fails + # 2: Dumps a minifier_launcher.py if aoti fails. + # 3: Always dumps a minifier_launcher.py. Good for segfaults. + # 4: Dumps a minifier_launcher.py if the accuracy fails. + repro_level: int = int(os.environ.get("AOTINDUCTOR_REPRO_LEVEL", 2)) + + # Dictionary of presets that can be passed in + presets: dict[str, Any] = {} + + # Kill switch for allowing temporary tensors to be allocated as stack arrays. Tests + # should be run with this flag both on and off to make sure we have coverage. + allow_stack_allocation: bool = False + + # Enables an alternate DSO interface (the "minimal ArrayRef interface") intended + # to maximize performance for use cases that it can accommodate at the expense of + # generality. In brief: + # - inputs and outputs are ArrayRefTensor (note that strides are required, but the + # tensor must be contiguous) + # - constant handling is unchanged because it is not a per-inference-iteration bottleneck + # + # When the DSO is generated in this mode, the usual interface will also be supported, + # but performance for that interface may be degraded. + use_minimal_arrayref_interface: bool = False + + # Set to True if we want to use Pytorch's CUDACachingAllocator for weight management + weight_use_caching_allocator: bool = ( + os.environ.get("AOT_INDUCTOR_WEIGHT_USE_CACHING_ALLOCATOR", "0") == "1" + ) + + # Experimental. Flag to control whether to include weight in .so + # Not supported for cross_target_platform="windows". + package_constants_in_so: bool = True + + # Experimental. Flag to control whether to package weight separately on disk and which + # format to package it in. + # Options: + # None: + # Do not package weight separately on disk. + # "pickle_weights": + # Each weight is pickled and stored separately in data/weights. We also store the + # FQN names of each weight in a weights_config.json in each model's data/aot_inductor/model folder. + # Can only be load back from python using torch._inductor.aoti_load_package API now. + # "binary_blob": + # Stores all weights in a single binary blob in data/aot_inductor/model folder for each model. + # This option and config.aot_inductor.force_mmap_weights cannot both be True + package_constants_on_disk_format: str | None = None + + # Experimental. Controls automatic precompiling of common AOTI include files. + precompile_headers: bool = not is_fbcode() + + # Embed generated kernel binary files into model.so + embed_kernel_binary: bool | None = None + + # Generate kernel files that support multiple archs. + # For CUDA, this means generating fatbin files for kernels. The fatbin files + # contain PTX for the compile target architecture (config.cuda.arch, or the + # current GPU when unset), plus SASS for the compile target and compatible + # TORCH_CUDA_ARCH_LIST architectures. + # For XPU, this means generating SPIR-V files for kernels, and the SPIR-V files + # will be compiled to target different XPU architectures at runtime. + emit_multi_arch_kernel: bool | None = None + + # If not None, the generated files with use this name in file stem. + # If None, we will use a hash to name files. + # + # If package_cpp_only, this name is also used for the target name in CMakelists.txt + # The default target name is "aoti_model" + # + # If compile_standalone, the aoti model class name is f"AOTInductorModel{name}" + # + # This name can only contain letters, numbers, and underscores. + model_name_for_generated_files: str | None = None + + # Custom ops that have implemented C shim wrappers, defined as an op to C shim declaration dict + custom_ops_to_c_shims: dict[torch._ops.OpOverload, list[str]] = {} + # custom op libs that have implemented C shim wrappers + custom_op_libs: list[str] | None = None + + # Whether to enable link-time-optimization + enable_lto = os.environ.get("AOT_INDUCTOR_ENABLE_LTO", "0") == "1" + + # Whether the compiled .so should link to libtorch + link_libtorch: bool = True + + # Currently the only valid option is "windows". + # We'll use x86_64-w64-mingw32-gcc to cross-compile a .dll file + # If using cuda, you also need to set WINDOWS_CUDA_HOME env var + # to point to windows CUDA toolkit. + # Example: WINDOWS_CUDA_HOME=cuda-windows-base/cuda_cudart/cudart/ + # The path should contain lib cuda and lib cudart + cross_target_platform: str | None = None + + # If link_libtorch is False and cross_target_platform is windows, + # a library needs to be provided to provide the shim implementations. + aoti_shim_library: str | list[str] | None = None + aoti_shim_library_path: str | None = None + + +# a convenient class that automatically sets a group of the configs in aot_inductor +# it should only control the flags in aot_inductor. +# it should not do anything else. +class aot_inductor_mode: + # dynamic_linkage=False + # link_libtorch=False + # package_cpp_only=True + # embed_kernel_binary=True + # emit_multi_arch_kernel=True + compile_standalone: bool = False + + +class cutlass: + """ + Config specific to cutlass backend. + """ + + compile_opt_level: Literal["-O0", "-O1", "-O2", "-O3", "-OS"] = "-O1" + + # Whether to enable debug info, e.g. line number, cutlass debug info. + enable_debug_info = False + + # Whether to use fast math. + use_fast_math = False + + # Path to the CUTLASS repo root directory. + # The default path only works under PyTorch local development environment. + cutlass_dir = os.path.realpath( + os.environ.get( + "TORCHINDUCTOR_CUTLASS_DIR", + os.path.join( + os.path.dirname(torch.__file__), + "../third_party/cutlass/", + ), + ) + ) + + # Configures the maximum number of CUTLASS configs to profile in max_autotune. + # By default it's None, so that all CUTLASS configs are tuned. + # This is mainly used to reduce test time in CI. + cutlass_max_profiling_configs: int | None = None + + # The L2 swizzle values to consider when profiling CUTLASS configs in max_autotune. + cutlass_max_profiling_swizzle_options: list[int] = [1, 2, 4, 8] + + cutlass_dynamic_cluster_shape: tuple[int, int, int] = cast( + tuple[int, int, int], + tuple( + int(x) + for x in os.environ.get( + "TORCHINDUCTOR_CUTLASS_DYNAMIC_CLUSTER_SHAPE", "2,1,1" + ).split(",") + ), + ) + cutlass_dynamic_cluster_fallback: tuple[int, int, int] = cast( + tuple[int, int, int], + tuple( + int(x) + for x in os.environ.get( + "TORCHINDUCTOR_CUTLASS_DYNAMIC_CLUSTER_FALLBACK", + ",".join(str(v) for v in cutlass_dynamic_cluster_shape), + ).split(",") + ), + ) + + # Whether to use CUTLASS EVT for epilogue fusion + cutlass_epilogue_fusion_enabled = ( + os.environ.get("CUTLASS_EPILOGUE_FUSION", "0") == "1" + ) + + # Whether to only use TMA-compatible kernels in CUTLASS + cutlass_tma_only = False + + # Minimum value of M*N*K to consider the CUTLASS backend for GEMM ops. + cutlass_backend_min_gemm_size: int = 1 + + # enable generation of inline standalone runner in CUDA CPP generated code + # which allows to compile the generated code into a standalone executable. + generate_test_runner: bool = ( + os.environ.get("INDUCTOR_CUDA_BACKEND_GENERATE_TEST_RUNNER_CODE", "0") == "1" + ) + + # Keep only Cutlass op configs which contain this regular expression pattern + # Set this to "warpspecialized_cooperative_epi_tma" to enable only SM90 TMA Cutlass Kernels for large GEMMs + cutlass_op_allowlist_regex: str | None = os.environ.get( + "TORCHINDUCTOR_CUTLASS_ALLOWLIST" + ) + + # Note: Names of Cutlass ops names can be obtained by calling + # op.configuration_name() on a Cutlass op instance, for example those + # returned from cutlass_utils.gen_ops() or the op argument passed to + # CUTLASSGemmTemplate.render(...) + + # Filter Cutlass configs which contain this regular expression pattern + # Set this to "pingpong" to avoid numerical issues + # caused by the op ordering of the "pingpong" memory access + # pattern used by some Cutlass Kernels. + cutlass_op_denylist_regex: str | None = os.environ.get( + "TORCHINDUCTOR_CUTLASS_DENYLIST" + ) + + # Non-negative integer which determines how many kernels are instantiated. + # 0 = 0000 generates the fewest kernels, 9999 generates all possible combinations. + # increasing first digit reduces schedule / mixed type pruning, + # increasing second digit generates more cluster sizes, + # increasing third digit generates more MMA multipliers, + # increasing fourth digit generates more instruction shapes. + cutlass_instantiation_level: str = os.environ.get( + "TORCHINDUCTOR_CUTLASS_INSTANTIATION_LEVEL", "0" + ) + + # use compile command to create kernel .cu and .so name + cutlass_hash_with_compile_cmd: bool = ( + os.environ.get("TORCHINDUCTOR_CUTLASS_HASH_WITH_COMPILE_CMD", "0") == "1" + ) + + # Experimental. Prescreen top x configs before tuning on swizzle. + cutlass_prescreening: bool = ( + os.environ.get("TORCHINDUCTOR_CUTLASS_PRESCREENING", "1") == "1" + ) + + # Specify which operations should use CUTLASS backend + # Comma-separated list like "mm,addmm,bmm", "all" for all operations, and "" for none. + # Acceptable operations: mm, int_mm, addmm, sparse_semi_structured_mm, bmm, scaled_mm + cutlass_enabled_ops: str = os.environ.get( + "TORCHINDUCTOR_CUTLASS_ENABLED_OPS", "all" + ) + + # Whether to consult the binary remote cache + use_binary_remote_cache: bool = True + + # Whether to upload compiled kernels to remote cache + upload_to_binary_remote_cache: bool = False + + # Whether to force upload if the key already exists + # Use this to overwrite and handle cache pollution + binary_remote_cache_force_write: bool = False + + # Enable caching codegen of cuda templates. + enable_caching_codegen: bool = True + + +@inherit_fields_from(cutlass) +class cuda(cutlass): + # CUDA arch to use for CUDA template kernel compilation. + # e.g. "70", "75", "80", "90", etc. + # When arch is None, Inductor uses torch.cuda.get_device_capability(0). + arch: str | None = None + + # CUDA version to use for CUDA template kernel compilation. + # e.g. "11.4", "12.1", etc. + # When version is None, Inductor uses torch.version.cuda. + version: str | None = None + + # Path to CUDA NVCC. + # NVCC search order: + # 1) cuda_cxx set in this config + # 2) CUDACXX environment variable + # 3) CUDA_HOME environment variable + # 4) default system search PATH. + cuda_cxx: str | None = None + + # Whether to enable device LTO (link-time-optimization). + enable_cuda_lto = False + + # Whether to keep intermediate files dring compilation. + enable_ptxas_info = False + + +@inherit_fields_from(cutlass) +class xpu(cutlass): + # Xe arch to use for SYCL kernel compilation. + # eg. 12, 20, which corresponding to Xe12(PVC) and Xe20 (BMG) + arch: str | None = None + # oneAPI version to use for SYCL kernel compilation. + # e.g. "20250201". + version: str | None = None + + # Path to Intel OneAPI. + oneapi_root: str | None = None + + cutlass_dir = os.path.realpath(os.environ.get("TORCHINDUCTOR_CUTLASS_DIR", "")) + + +class rocm: + # Offload arch list for device code compilation, e.g. ["gfx90a", "gfx942"]. + # If empty, the `native` arch is used + arch: list[str] = [] + + # Enable the CK backend for CDNA2 and CDNA3 only (for now) + # Processor name reference: https://llvm.org/docs/AMDGPUUsage.html#processors + ck_supported_arch: list[Literal["gfx90a", "gfx942", "gfx950"]] = [ + "gfx90a", + "gfx942", + "gfx950", + ] + + # Optimization level, use to balance compilation speed and runtime performance. + # The type will not necessarily be comprehensive and won't be enforced at runtime. + compile_opt_level: Literal[ + "-O0", "-O1", "-O2", "-O3", "-Os", "-Oz", "-Omin", "-Ofast", "-Omax" + ] = "-O2" + + # Flag to keep debug information in compiled objects + is_debug = False + + # Flag to keep intermediate files (assembly listings, preprocessed sources, etc.) + save_temps = False + + # Flag to add `-ffast-math`` to compile flags + use_fast_math = True + + # Flag to add `-fgpu-flush-denormals-to-zero` to compile flags + flush_denormals = True + + # Flag to print register and LDS usage during compilation + print_kernel_resource_usage = False + + # Path to ROCm installation, if None, use env variable ROCM_HOME. + # In fbcode see triton/fb/TARGETS for how ROCM_HOME gets set. + rocm_home: str | None = None + + # Path to Composable Kernel library. + # Install with `pip install git+https://github.com/rocm/composable_kernel@develop`. + ck_dir = os.environ.get("TORCHINDUCTOR_CK_DIR") + + # generate standalone executables for instances generated with the CK backend + generate_test_runner: bool = ( + os.environ.get("INDUCTOR_CK_BACKEND_GENERATE_TEST_RUNNER_CODE", "0") == "1" + ) + + # Deprecated, use CK and/or CK-tile specific settings + n_max_profiling_configs: int | None = None + + # Number of op instance choices to trade off between runtime perf and compilation time + # For CK Kernels + ck_max_profiling_configs: int | None = None + + # Number of op instance choices to trade off between runtime perf and compilation time + # For CK-Tile Kernels + ck_tile_max_profiling_configs: int | None = None + + # Flag to use a short list of CK instances which perform well across a variety of shapes. + # Currently RCR and F16 only + use_preselected_instances: bool = False + + # List to determine kBatch parameters to sweep over. By default, we calculate one in splitK + # scenarios, and run on kBatch=1 in non-splitK scenarios + kBatch_sweep: list[int] | None = None + + # The threshold at which we trigger a splitK config - K // max(M,N) has to be greater than this + split_k_threshold: int = 16 + + # The threshold at which we trigger a contiguous subgraph transformation + contiguous_threshold: int = 16 + # Enable origami GEMM autotuning on Triton templates (ROCm only). + # + # When True, the rocm-origami pip package is consulted at GEMM compile time + # to pre-select a top-K of Triton configs from the DEFAULT search space, + # reducing autotuning cost while keeping runtime within ~5% of full + # max_autotune. Read once at config import from TORCHINDUCTOR_ORIGAMI; + # toggling at runtime via config.patch has no effect because the rocm-origami + # module import is cached at heuristics/template/triton.py load time. + # + # Active only when all of these hold: + # - IS_ROCM (torch.version.hip is not None) + # - config.max_autotune + # - config.rocm.origami (this knob) + # - config.max_autotune_gemm_search_space == "DEFAULT" + # - rocm-origami is installed (else the import gate sets it inert) + # Outside DEFAULT (e.g. EXHAUSTIVE) origami is silently bypassed with a + # one-time warning; the regular config generator runs instead. + # + # Side-effect: when this is True, choices._need_to_fix_layout() returns True + # so flexible layouts are disabled. Origami's grid/workgroup mappings depend + # on exact strides and would mis-compile under flexible layouts. + origami: bool = os.environ.get("TORCHINDUCTOR_ORIGAMI") in (None, "1") + + # Number of top configs origami selects per GEMM. Read once from + # TORCHINDUCTOR_ORIGAMI_TOPK; defaults to 6 (sweet spot between compile + # time and runtime within the validated 4-8 range). + origami_topk: int = int(os.environ.get("TORCHINDUCTOR_ORIGAMI_TOPK", "6")) + + +# Backend to use for CPU codegen either "cpp" or "triton" (experimental) or "halide" (experimental) or "pallas" (experimental) +cpu_backend: Literal["cpp", "triton", "halide", "pallas"] = "cpp" + +# Backend to use for CUDA codegen either +# "triton", "halide" (experimental) or "pallas" (experimental) +cuda_backend: Literal["triton", "halide", "pallas"] = "triton" + +# Backend to use for TPU codegen +tpu_backend: Literal["pallas"] = "pallas" + +# Backend to use for XPU codegen either "triton" +xpu_backend: Literal["triton"] = "triton" + + +class mtia: + # Configuration to force inductor to never use welford reductions for MTIA backend + disable_welford_reduction = False + + +class halide: + # Base halide target to use for CPU devices + cpu_target = "host" + + # Base halide target to use for CUDA devices + gpu_target = "host-cuda" + + # Halide autoscheduler to use, choices are: + # "Anderson2021" (gpu-only), "Li2018", "Adams2019" (cpu-only), or "Mullapudi2016" (cpu-only) + scheduler_cuda: Literal["Anderson2021", "Li2018", "Adams2019", "Mullapudi2016"] = ( + "Anderson2021" + ) + scheduler_cpu: Literal["Anderson2021", "Li2018", "Adams2019", "Mullapudi2016"] = ( + "Adams2019" + ) + + # Controls `no_asserts` flag passed to Halide target (warning: can false positive) + asserts = False + + # Controls `debug` flag passed to Halide target + debug = False + + # Enable (or fallback on) scan kernels such as cumsum + # Halide autoschedulers struggle with these kernels + scan_kernels = False + + +# create a directory containing lots of debug information +def _get_debug_graph_format(format_env_name: str, legacy_svg_env_name: str) -> str: + if format_env_name in os.environ: + return os.environ[format_env_name] + if os.environ.get(legacy_svg_env_name, "0") == "1": + return "svg" + return os.environ.get("TORCH_COMPILE_GRAPH_FORMAT", "svg") + + +class trace: + """Configuration for torch.compile debug trace artifacts.""" + + # master switch for all debugging flags below + enabled = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1" + + # save real tensors + save_real_tensors = os.environ.get("TORCH_COMPILE_DEBUG_SAVE_REAL", "0") == "1" + + # Save debug information to a temporary directory + # If not specified, a temp directory will be created by system + debug_dir: str | None = None + + # Save python logger call >=logging.DEBUG + debug_log = False + + # Save python logger call >=logging.INFO + info_log = False + + # Save input FX graph (post decomps, pre optimization) + fx_graph = True + + # Save FX graph after transformations + fx_graph_transformed = True + + # Save TorchInductor IR before fusion pass + ir_pre_fusion = True + + # Save TorchInductor IR after fusion pass + ir_post_fusion = True + + # Copy generated code to trace dir + output_code = True + + # Diagram showing post-fusion graph. INDUCTOR_POST_FUSION_SVG is the + # legacy spelling for SVG output; INDUCTOR_POST_FUSION_GRAPH enables the + # same dump for any graph_diagram_format. + graph_diagram = ( + os.environ.get("INDUCTOR_POST_FUSION_SVG", "0") == "1" + or os.environ.get("INDUCTOR_POST_FUSION_GRAPH", "0") == "1" + ) + + # Output format for post-fusion graph_diagram dumps. Defaults to svg when + # the legacy INDUCTOR_POST_FUSION_SVG flag is used; otherwise defaults to + # the shared torch.compile graph format. Set to "dot" to dump raw DOT text + # without invoking Graphviz layout. + graph_diagram_format = _get_debug_graph_format( + "INDUCTOR_POST_FUSION_GRAPH_FORMAT", + "INDUCTOR_POST_FUSION_SVG", + ) + + # Diagram showing FX with fusion. INDUCTOR_ORIG_FX_SVG is the legacy + # spelling for SVG output; INDUCTOR_ORIG_FX_GRAPH enables the same dump for + # any orig_fx_graph_diagram_format. + draw_orig_fx_graph = ( + os.environ.get("INDUCTOR_ORIG_FX_SVG", "0") == "1" + or os.environ.get("INDUCTOR_ORIG_FX_GRAPH", "0") == "1" + ) + + # Output format for original FX graph dumps. Defaults to svg when the + # legacy INDUCTOR_ORIG_FX_SVG flag is used; otherwise defaults to the + # shared torch.compile graph format. Set to "dot" to dump raw DOT text + # without invoking Graphviz layout. + orig_fx_graph_diagram_format = _get_debug_graph_format( + "INDUCTOR_ORIG_FX_GRAPH_FORMAT", + "INDUCTOR_ORIG_FX_SVG", + ) + + # We draw our fx graphs with the "record" shape attribute by default. + # Sometimes, when the graph is very complex, we may hit dot errors like below: + # "flat edge between adjacent nodes one of which has a record shape - + # replace records with HTML-like labels" + # and thus fail to generate a graph. So, let's give the user an option + # to specify the shape attribute for the dot graph. For example, passing + # INDUCTOR_DOT_GRAPH_SHAPE_SVG = "none" would let us generate HTML-like labels + # to workaround the above failure. + dot_graph_shape = os.environ.get("INDUCTOR_DOT_GRAPH_SHAPE_SVG", None) + + # If not None, this is the URL that saves the SVG files of the input/output + # graph of each pass that changed the graph + # The nodes that are being transformed in each pass will be colored in yellow + # URL only supports local directory for now + log_url_for_graph_xform = os.environ.get("INDUCTOR_LOG_URL_FOR_GRAPH_XFORM", None) + + # Store cProfile (see snakeviz to view) + compile_profile = False + + # Upload the .tar.gz file + # Needs to be overridden based on specific environment needs + upload_tar: Callable[[str], None] | None = None + + log_autotuning_results = os.environ.get("LOG_AUTOTUNE_RESULTS", "0") == "1" + + # Add Inductor kernel stack traces back into exported PyTorch profiler timelines. + provenance_tracking_to_timeline = ( + os.environ.get("TORCH_COMPILE_DEBUG_EXTEND", "0") == "1" + ) + + # Maximum number of trace events to process in profiler timeline post-processing. + # If the trace exceeds this limit, provenance tracking will be skipped to avoid OOM. + # Set to 0 to disable this protection. + provenance_tracking_max_events: int = int( + os.environ.get("TORCH_COMPILE_DEBUG_MAX_EVENTS", "500000") + ) + + # Save mapping info from inductor generated kernel to post_grad/pre_grad fx nodes + # Levels: + # 0 - disabled (default) + # 1 - normal + # 2 - basic + # Backward compatibility: + # If TORCH_COMPILE_DEBUG=1, level is set to at least 1. + # If INDUCTOR_PROVENANCE is set, use its integer value. + provenance_tracking_level: int = int( + os.environ.get( + "INDUCTOR_PROVENANCE", os.environ.get("TORCH_COMPILE_DEBUG", "0") + ) + ) + + +def effective_provenance_tracking_level() -> int: + if trace.provenance_tracking_to_timeline: + return max(trace.provenance_tracking_level, 1) + return trace.provenance_tracking_level + + +_save_config_ignore: list[str] = [ + # workaround: "Can't pickle " + "trace.upload_tar", + "joint_custom_pre_pass", + "joint_custom_post_pass", + "pre_grad_custom_pass", + "aot_inductor.repro_level", + "aot_inductor.dump_aoti_minifier", + "post_grad_custom_pre_pass", + "post_grad_custom_post_pass", + "_fuse_ddp_communication_passes", + "_pre_fusion_custom_pass", + # CUDAGraphPolicy objects are not picklable and only affect + # post_compile wrapping, not compiled code itself. + "cudagraph_policy", +] + +_cache_config_ignore_prefix: list[str] = [ + # trace functions are not relevant to config caching + "trace", + # uses absolute path + "cuda.cutlass_dir", + "cutlass.cutlass_dir", + "xpu.cutlass_dir", + # not relevant + "worker_start_method", + "compile_threads", + # see CustomGraphPass; these are handled specially + "post_grad_custom_post_pass", + "post_grad_custom_pre_pass", + "joint_custom_pre_pass", + "joint_custom_post_pass", + "pre_grad_custom_pass", + "_fuse_ddp_communication_passes", + "_pre_fusion_custom_pass", + # CUDAGraphPolicy only affects post_compile, not compiled output + "cudagraph_policy", + # tests assume that changes here don't invalidate cache + "force_disable_cudagraph_TESTING_ONLY", + # timing affects cache structure, not cache content + "pre_grad_pass_timing", + # cache related options are not relevant to cache results + "fx_graph_cache", + "fx_graph_remote_cache", + "autotune_local_cache", + "autotune_remote_cache", +] + +# Config keys whose values are callable factories. save_config_portable will +# instantiate the factory and use .uuid() for serialization. +_cache_config_factory_keys: list[str] = [ + "inductor_choices_class", +] + +# External callable for matmul tuning candidates +external_matmul: list[Callable[[torch.Tensor, torch.Tensor, torch.Tensor], None]] = [] + +write_are_deterministic_algorithms_enabled = ( + os.getenv("TORCHINDUCTOR_WRITE_ARE_DETERMINISTIC_ALGORITHMS_ENABLED", "1") == "1" +) + + +class lookup_table: + # Lookup table for template config overrides + table: dict[str, list[dict[str, Any]]] | None = None + + # Enable template src_hash checking in lookup table to prevent using stale configs. + # If True, configs with 'template_hash' field will be compared against the template's + # src_hash at runtime and filtered out if they don't match. If False, no + # hash checking is performed. + check_src_hash: bool = True + + +class test_configs: + force_extern_kernel_in_multi_template: bool = False + + # Force custom op autotuning choice selection: + # - None: normal autotuning (default) + # - True: force decomposition to win + # - False: force fallback to win + force_custom_op_decomposition: bool | None = None + + # Force custom op autotuning to prevent grouping ranges by implementation. + # When True, each range is treated as a separate impl group, forcing torch.cond dispatch. + force_no_impl_grouping: bool = False + + max_mm_configs: int | None = None + max_flex_configs: int | None = None + + runtime_triton_dtype_assert = False + runtime_triton_shape_assert = False + static_cpp_dtype_assert = False + + # regex to control the set of considered autotuning + # choices (aka configs) by name and / or description + # Can be set via TORCHINDUCTOR_AUTOTUNE_CHOICE_NAME_REGEX and + # TORCHINDUCTOR_AUTOTUNE_CHOICE_DESC_REGEX environment variables + + autotune_choice_name_regex: str | None = os.environ.get( + "TORCHINDUCTOR_AUTOTUNE_CHOICE_NAME_REGEX" + ) + autotune_choice_desc_regex: str | None = os.environ.get( + "TORCHINDUCTOR_AUTOTUNE_CHOICE_DESC_REGEX" + ) + + graphsafe_rng_func_ignores_fallback_random = False + + track_memory_lifecycle: Literal["assert", "log"] | None = None + + # If set to True, AOTI-generated CMakelists.txt will still use libtorch + # for unit testing + use_libtorch = False + + # Assume bucketing reduces latency (mostly for testing) + assume_bucketing_reduces_latency: bool = True + + # A test config to ease the test for perf of reduction config filtering + force_filter_reduction_configs = ( + os.getenv("TORCHINDUCTOR_FORCE_FILTER_REDUCTION_CONFIGS") == "1" + ) + + # a testing config to distort benchmarking result + # - empty string to disable + # - "inverse" to inverse the numbers + # - "random" return a random value + distort_benchmarking_result = os.getenv( + "TORCHINDUCTOR_DISTORT_BENCHMARKING_RESULT", "" + ) + + bisect_pre_grad_graph = False + bisect_keep_custom_backend_for_inductor = False + + +if TYPE_CHECKING: + from torch.utils._config_typing import * # noqa: F403 + + +class eager_numerics: + # x / y in Triton is lowered to div.full which is approx + # PyTorch eager uses the equivalent of Triton's div_rn, which can + # come at a performance penalty + division_rounding: bool = ( + os.environ.get("TORCHINDUCTOR_EMULATE_DIVISION_ROUNDING", "0") == "1" + ) + + disable_ftz: bool = False + + # Use the CUDA toolkit's libdevice instead of Triton's bundled version. + # Triton bundles its own libdevice.10.bc which may use different polynomial + # approximations than the installed CUDA toolkit, causing ~1 ULP differences + # in transcendental functions such as pow and erf. The erf difference is + # particularly visible in explicit GELU kernels + # (0.5 * x * (1 + erf(x * sqrt(0.5)))) where a 1 ULP change in erf output + # can flip the result of a subsequent ceil(log2(...)) and produce a + # different uint8 encoded value (see gh-178045). + # This can be enabled directly; Inductor also enables it while + # emulate_precision_casts is active. + use_pytorch_libdevice: bool = False + + +# Mode to emulate PyTorch eager numerics when doing lower precision compute +# (fp16, bf16). PyTorch eager computes bf16/fp16 by upcasting inputs to fp32 +# and downcasting after. When two low precision operators are fused together, +# Inductor will elide the downcast-upcast pairs (effectively a precision +# truncation) that would occur between these two operators. Typically, +# Inductor's behavior should be closer to fp64 ref numerics. However, with +# this knob you can ensure the downcast-upcast are preserved so that you can +# emulate the eager numerics. +emulate_precision_casts: bool = ( + os.environ.get("TORCHINDUCTOR_EMULATE_PRECISION_CASTS", "0") == "1" +) + + +# Targeted variant of emulate_precision_casts for saved low-precision outputs. +# When a low-precision pointwise result is saved for backward and also used by +# later forward math, this inserts a downcast-upcast at the saved value so +# forward and backward consume the same precision. +emulate_precision_casts_on_saved_tensors: bool = ( + os.environ.get("TORCHINDUCTOR_EMULATE_PRECISION_CASTS_ON_SAVED_TENSORS", "1") == "1" +) + +# adds patch, save_config, etc +install_config_module(sys.modules[__name__]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/config_comms.py b/.venv/lib/python3.12/site-packages/torch/_inductor/config_comms.py new file mode 100644 index 0000000000000000000000000000000000000000..be0647b57f52945a1a564fdaa4f29c102f5f53c1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/config_comms.py @@ -0,0 +1,71 @@ +import os +import sys + +from torch.utils._config_module import install_config_module + + +# Whether to use c10d._time_estimator for collectives runtime estimations. +runtime_estimations_use_nccl_lib_estimations: bool = False + +# Config to enable sync of runtime estimations across distributed ranks, +# To prevent passes using this runtime estimations to make different +# decisions on different distributed ranks. +runtime_estimations_align_across_all_distributed_ranks: bool = False + +reorder_iterative_debug_memory_recompute: bool = False +reorder_iterative_debug_limit_to_reorder: int | None = ( + None + if (env_str := os.getenv("PYTORCH_REORDER_COLLECTIVES_LIMIT")) is None + else int(env_str) +) +sink_waits_iterative_debug_limit_to_sink: int | None = ( + # pyrefly: ignore[unbound-name] + None if (env_str := os.getenv("PYTORCH_SINK_WAITS_LIMIT")) is None else int(env_str) +) + + +# Should be used with config.runtime_estimations_mms_benchmark = True +reorder_iterative_use_runtime_estimations: bool = False +sink_iterative_use_runtime_estimations: bool = False + +# Broadcast runtime estimations doing real Collective operation between all ranks. +# If non-deterministic runtime estimations are used this must be used to make +# all ranks to do identical decisions and prevent global Collectives reordering, +# (that will result in NCCL hangs) +reorder_for_compute_comm_overlap_broadcast_runtime_estimations: bool = False + +# Block of Ratios to workaround imperfection of current runtime estimations +# for collectives and compute for different scenarios. +# Multiplier of collectives estimated durations +reorder_sink_runtime_estimations_comm_mult: float = 2.0 +# Multiplier of compute estimated durations +reorder_sink_runtime_estimations_non_comm_mult: float = 1.0 +# The reordering will stop to reorder +# when overlap_comp >= (1 + extra_overlap_ratio) * comm_time +# Allows to configure more aggressive overlap +reorder_iterative_extra_comm_comp_overlap: float = 0.5 +# The sink waits reordering will stop to reorder +# when overlap_comp >= (1 + extra_overlap_ratio) * comm_time +# Allows to configure more aggressive sink waits +sink_iterative_extra_comm_comp_overlap: float = 0.5 + +# Allow reorder iterative pass to increase peak memory +# up to peak_memory_before_pass * (1 + budget) +reorder_iterative_peak_memory_budget: float = 0.2 +# Allow sink waits iterative pass to increase peak memory +# up to peak_memory_before_pass * (1 + budget) +sink_iterative_peak_memory_budget: float = 0.2 + +# Experimental unsafe configuration that allows changing relative collectives order. +# Must be used with runtime_estimations_align_across_all_distributed_ranks = True +reorder_iterative_unsafe_collectives_reorder: bool = True +sink_waits_iterative_unsafe_collectives_reorder: bool = True + +# Allow group and move other collectives during reordering +reorder_iterative_group_with_collectives: bool = False +sink_waits_iterative_swap_with_collectives: bool = False + +reorder_sink_verbose_logging: bool = False + +# adds patch, save_config, etc +install_config_module(sys.modules[__name__]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/constant_folding.py b/.venv/lib/python3.12/site-packages/torch/_inductor/constant_folding.py new file mode 100644 index 0000000000000000000000000000000000000000..6e0ea4ebf46defedaaa5325585526d1cdd85d770 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/constant_folding.py @@ -0,0 +1,429 @@ +import collections +import typing_extensions +from collections.abc import Callable +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._inductor.freezing_utils import maybe_set_is_frozen_param +from torch.utils._ordered_set import OrderedSet + + +aten = torch.ops.aten + +# We would like to split modules into two subgraphs for runtime weight updates to work correctly. +# The use case and more information could be found at: +# https://docs.google.com/document/d/1inZC-8KarJ6gKB7G9egmYLx1V_dKX_apxon0w4zPC0Q/edit?usp=sharing +META_TAG = "MODULE_TYPE" +MODULE_TAG = "_MAIN_MODULE" +CONST_MODULE_TAG = "_CONST_MODULE" + +_dont_constant_fold: list[torch.fx.node.Target] = [] + + +def add_dont_constant_fold(op: torch.fx.node.Target) -> None: + global _dont_constant_fold + _dont_constant_fold.append(op) + + +def clear_dont_constant_fold() -> None: + global _dont_constant_fold + _dont_constant_fold.clear() + + +def replace_node_with_constant( + gm: torch.fx.GraphModule, + node: torch.fx.Node, + constant: torch.Tensor | None = None, + name: str | None = None, +) -> None: + g = gm.graph + + if name: + qualname = name + else: + if not hasattr(gm, "_frozen_param_count"): + gm._frozen_param_count = 0 # type: ignore[assignment] + i = gm._frozen_param_count + # pyrefly: ignore [bad-assignment] + while True: + qualname = f"_frozen_param{i}" + if not hasattr(gm, qualname): + break + i += 1 # type: ignore[assignment, operator] + + gm._frozen_param_count = i + 1 # type: ignore[assignment, operator] + + with g.inserting_before(node): + if constant is not None: + new_input_node = g.create_node("get_attr", qualname, (), {}) + else: + # this is the case for lifted constants + new_input_node = g.create_node("placeholder", qualname, (), {}) + node.replace_all_uses_with(new_input_node) + new_input_node.meta.update(node.meta) + g.erase_node(node) + new_input_node.name = node.name + + if constant is not None: + # needed to suppress `does not reference an nn.Module, nn.Parameter, or buffer` warning + gm.register_buffer(qualname, constant) + setattr(gm, qualname, constant) + # mark any constants created during freezing + maybe_set_is_frozen_param(constant) + + +def is_const_source( + node: torch.fx.Node, lifted_constant_names: list[str] | None +) -> bool: + return node.op == "get_attr" or node.name in (lifted_constant_names or ()) + + +class ConstantFolder(torch.fx.Interpreter): + def __init__( + self, + gm: torch.fx.GraphModule, + skip_constructors: bool = False, + lifted_constant_names: list[str] | None = None, + skip_folding_node_fn: Callable[[torch.fx.Node], bool] | None = None, + ) -> None: + super().__init__(gm) + self.node_replacements: dict[torch.fx.Node, Any] = {} + self.replaced_uses: dict[torch.fx.Node, int] = collections.Counter() + self.unknown_value = object() + self.skip_constructors: bool = skip_constructors + + # overwrite this to deallocate env values if their only remaining use + # is the output + self.user_to_last_uses = self.node_to_last_non_output_use() + self.lifted_constant_names = lifted_constant_names + self.deferred_value = object() + self.skip_folding_node_fn = skip_folding_node_fn + + def _support_dynamic_shape(self) -> bool: + # ConstantFolder not support dynamic shape now + return False + + def _deduce_value(self, node: torch.fx.Node) -> Any: + if self.lifted_constant_names is None: + return super().run_node(node) + # if lifted_constant_names is passed in, no concrete value is available + # so we just check if all inputs have values + if self.skip_folding_node_fn is not None and self.skip_folding_node_fn(node): + return self.unknown_value + flattened_node_inps = pytree.arg_tree_leaves(*node.args, **node.kwargs) + for inp in flattened_node_inps: + if ( + isinstance(inp, torch.fx.Node) + and inp.name not in (self.lifted_constant_names or ()) + and self.env[inp] is not self.deferred_value + ): + return self.unknown_value + return self.deferred_value + + def is_impure(self, node: torch.fx.node.Node) -> bool: + def is_woq_int8_pattern(node: torch.fx.node.Node) -> bool: + return ( + node.target is torch.ops.prims.convert_element_type.default # type: ignore[return-value] + and isinstance(node.args[0], torch.fx.Node) + and "val" in node.args[0].meta + and node.args[0].meta["val"].dtype == torch.int8 # type: ignore[union-attr] + and node.args[1] == torch.bfloat16 + ) + + if ( + is_woq_int8_pattern(node) + or ( + node.target is torch.ops.aten.permute.default + and len(node.users) == 1 + and is_woq_int8_pattern(next(iter(node.users))) + ) + ) and is_const_source( + node.args[0], # type: ignore[arg-type] + self.lifted_constant_names, + ): + # Case 1: int8_weight -> dq -> bf16_weight + # Case 2: int8_weight -> permute -> dq -> bf16_weight + return True + + quant_registered = ( + getattr(torch.ops.quantized_decomposed, "dequantize_per_channel", None) + is not None + ) + if quant_registered and node.target in [ + torch.ops.quantized_decomposed.dequantize_per_channel.default, + torch.ops.quantized_decomposed.dequantize_per_tensor.default, + torch.ops.quantized_decomposed.dequantize_per_tensor.tensor, + torch.ops.quantized_decomposed.convert_element_type.no_fuse, + ]: + # For the pattern fp32_weight -> q -> dq + # We only folding fp32_weight -> q + # int8_weight and leave dq in graph to be fused + return True + + if node.target in _dont_constant_fold: + return True + return False + + def node_to_last_non_output_use(self) -> dict[torch.fx.Node, list[torch.fx.Node]]: + last_non_output_use = collections.defaultdict(list) + seen_uses = OrderedSet[torch.fx.Node]() + output_node = next(iter(reversed(self.module.graph.nodes))) # type: ignore[arg-type, union-attr] + + for node in reversed(self.module.graph.nodes): # type: ignore[arg-type, union-attr] + if node.target == "output": + continue + + def add_use(inp: torch.fx.Node) -> None: + if inp in seen_uses: + return + + seen_uses.add(inp) + last_non_output_use[node].append(inp) + + # In-place is fine since we don't mutate + pytree.tree_map_only_(torch.fx.Node, add_use, (node.args, node.kwargs)) + + # if this node is only used in output, we want to gc it right away + if len(node.users) == 1 and output_node in node.users: + last_non_output_use[node].append(node) + + return last_non_output_use + + @typing_extensions.override + def run_node(self, node: torch.fx.Node) -> Any: + if node.target == "output": + # because we remove nodes from env on last non output use, + # re-define them now or we'll get error in interpreter + def set_env(arg: torch.fx.Node) -> None: + self.env[arg] = self.unknown_value + + # In-place is fine since we don't mutate + pytree.tree_map_only_(torch.fx.Node, set_env, node.args) + return super().run_node(node) + + args, kwargs = self.fetch_args_kwargs_from_env(node) + flattened_inputs = pytree.arg_tree_leaves(*args, **kwargs) + + # We need to do this weird thing because in cases where flattened_inputs + # contains a ScriptObject, equality checking results in a type error if + # the types are different. + if any( + type(self.unknown_value) is type(input_) and self.unknown_value == input_ + for input_ in flattened_inputs + ): + return self.unknown_value + + # TODO - fix errors with this + if ( + node.op == "call_function" + and node.target is aten._efficientzerotensor.default + ): + return self.unknown_value + + # TODO - constant folding triton kernel returns the inputs -- fix this + if ( + node.op == "call_function" + and node.name == "triton_kernel_wrapper_functional_proxy" + ): + return self.unknown_value + + # skip constructors, since inductor generates optimal code for them already + # and turning into tensor would result in an additional global memory read + # TODO - more complicated strategy + if ( + self.skip_constructors + and not is_const_source(node, self.lifted_constant_names) + and not any(isinstance(e, torch.Tensor) for e in flattened_inputs) + ): + return self.unknown_value + + # All mutations should either be removed or on inputs which we did not make constant + if ( + isinstance(node.target, torch._ops.OpOverload) + and torch.Tag.nondeterministic_seeded in node.target.tags + ): + return self.unknown_value + + if node.op == "call_function" and isinstance( + node.target, torch._ops.HigherOrderOperator + ): + return self.unknown_value + + out = self._deduce_value(node) + + if isinstance( + out, + ( + torch._C.ScriptObject, + torch._library.fake_class_registry.FakeScriptObject, + ), + ): + return out + + if out is self.unknown_value: + return self.unknown_value + + if not is_const_source(node, self.lifted_constant_names) and ( + isinstance(out, torch.Tensor) or out is self.deferred_value + ): + if ( + out is not self.deferred_value + and out.device.type == "meta" # pyrefly: ignore[missing-attribute] + ): + return out + + if not self.insertable_tensor_check( + out # pyrefly: ignore[bad-argument-type] + ): + return out + + if self.is_impure(node): + return self.unknown_value + + self.add_node_replacement(node, out) # pyrefly: ignore[bad-argument-type] + + flattened_node_inps = pytree.arg_tree_leaves(*node.args, **node.kwargs) + + for n in flattened_node_inps: + if not isinstance(n, torch.fx.Node): + continue + + self.replaced_uses[n] += 1 + + for to_delete in self.user_to_last_uses.get(node, []): + if self.replaced_uses[to_delete] == len(to_delete.users): + self.node_replacements.pop(to_delete, None) + + return out + + def insertable_tensor_check(self, tensor: torch.Tensor) -> bool: + return True + + def add_node_replacement(self, node: torch.fx.Node, tensor: torch.Tensor) -> None: + self.node_replacements[node] = tensor + + def run(self) -> Any: # type: ignore[override] + env: dict[torch.fx.Node, Any] = {} + self.insert_placerholder_values(env) + return super().run(initial_env=env) + + def insert_placerholder_values(self, env: dict[torch.fx.Node, Any]) -> None: + for n in self.module.graph.find_nodes(op="placeholder"): # type: ignore[operator, union-attr] + env[n] = self.unknown_value # type: ignore[assignment] + if self.lifted_constant_names is None: + return + for n in self.module.graph.nodes: # type: ignore[union-attr] + if n.name in (self.lifted_constant_names or ()): + env[n] = self.deferred_value + + +def constant_fold( + gm: torch.fx.GraphModule, + constraint_fn: Callable[[torch.fx.Node], bool] | None = None, +) -> None: + with torch.utils._python_dispatch._disable_current_modes(): + cf = ConstantFolder(gm, skip_constructors=True) + cf.run() + + for node, constant in cf.node_replacements.items(): + if constraint_fn is not None and not constraint_fn(node): + continue + replace_node_with_constant(gm, node, constant) + + erased_params = [] + for node in gm.graph.find_nodes(op="get_attr"): + if len(node.users) == 0: + if hasattr(gm, node.target): + delattr(gm, node.target) + erased_params.append(node) + + for node in erased_params: + gm.graph.erase_node(node) + + gm.graph.eliminate_dead_code() + gm.graph.lint() + gm.recompile() + + +def constant_graph_tag( + gm: torch.fx.GraphModule, + skip_constructors: bool = True, + lifted_constant_names: list[str] | None = None, + skip_folding_node_fn: Callable[[torch.fx.Node], bool] | None = None, +) -> None: + with torch.utils._python_dispatch._disable_current_modes(): + cf = ConstantFolder( + gm, + skip_constructors=skip_constructors, + lifted_constant_names=lifted_constant_names, + skip_folding_node_fn=skip_folding_node_fn, + ) + cf.run() + + for node in gm.graph.nodes: + if skip_folding_node_fn is not None and skip_folding_node_fn(node): + node.meta[META_TAG] = MODULE_TAG + continue + if ( + is_const_source(node, lifted_constant_names) + or node in cf.node_replacements + or node in cf.replaced_uses + ): + node.meta[META_TAG] = CONST_MODULE_TAG + else: + node.meta[META_TAG] = MODULE_TAG + + +def run_and_get_constant_graph( + gm: torch.fx.GraphModule, + skip_constructors: bool = True, + lifted_constant_names: list[str] | None = None, + skip_folding_node_fn: Callable[[torch.fx.Node], bool] | None = None, +) -> torch.fx.GraphModule: + """ + Construct a GraphModule which corresponds to the part which could be + constant folded in provided gm. + """ + + constant_graph_tag( + gm, skip_constructors, lifted_constant_names, skip_folding_node_fn + ) + + def untag(node: torch.fx.Node) -> bool: + used_to_fold = False + for u in node.users: + if u.meta[META_TAG] == CONST_MODULE_TAG: + used_to_fold = True + break + if not used_to_fold: + node.meta[META_TAG] = MODULE_TAG + return used_to_fold + + # We rewrite the tags, if it's a constant being directly consumed, without + # any folding opportunity, we keep it in main gm. + for node in gm.graph.nodes: + if node.op == "get_attr" or (node.name in (lifted_constant_names or ())): + untag(node) + + new_graph = torch.fx.Graph() + + node_remapping: dict[torch.fx.Node, torch.fx.Node] = {} + output_nodes = [] + for node in gm.graph.nodes: + if node.meta[META_TAG] == MODULE_TAG: + continue + + new_node = new_graph.node_copy(node, lambda x: node_remapping[x]) + node_remapping[node] = new_node + + for user in node.users: + if user.meta[META_TAG] == MODULE_TAG: + output_nodes.append(new_node) + break + + new_graph.output(tuple(output_nodes)) + new_graph.lint() + new_gm = torch.fx.GraphModule(gm, new_graph) + + return new_gm diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/cpp_builder.py b/.venv/lib/python3.12/site-packages/torch/_inductor/cpp_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..abb14bc180f93d3180ee87dfa86445294758f65d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/cpp_builder.py @@ -0,0 +1,2943 @@ +# This CPP builder is designed to support both Windows and Linux OS. +# The design document please check this RFC: https://github.com/pytorch/pytorch/issues/124245 + +import copy +import ctypes +import errno +import functools +import json +import locale +import logging +import os +import platform +import re +import shlex +import shutil +import subprocess +import sys +import sysconfig +import tempfile +import textwrap +import warnings +from collections.abc import Sequence +from ctypes import cdll, wintypes +from ctypes.util import find_library +from pathlib import Path +from typing import Any + +import torch +from torch._dynamo.utils import dynamo_timed +from torch._inductor import config, exc +from torch._inductor.cpu_vec_isa import invalid_vec_isa, VecISA +from torch._inductor.runtime.runtime_utils import cache_dir +from torch.torch_version import TorchVersion +from torch.utils._ordered_set import OrderedSet + + +if config.is_fbcode(): + from triton.fb.build import _run_build_command, build_paths + + from torch._inductor.fb.utils import ( + log_global_cache_errors, + log_global_cache_stats, + log_global_cache_vals, + use_global_cache, + ) +else: + + def log_global_cache_errors(*args: Any, **kwargs: Any) -> None: # type: ignore[misc] + pass + + def log_global_cache_stats(*args: Any, **kwargs: Any) -> None: # type: ignore[misc] + pass + + def log_global_cache_vals(*args: Any, **kwargs: Any) -> None: # type: ignore[misc] + pass + + def use_global_cache() -> bool: # type: ignore[misc] + return False + + +# Windows need setup a temp dir to store .obj files. +_BUILD_TEMP_DIR = "CxxBuild" +_HERE = os.path.abspath(__file__) +_TORCH_PATH = os.path.dirname(os.path.dirname(_HERE)) +_LINKER_SCRIPT = os.path.join(_TORCH_PATH, "_inductor/script.ld") + +# initialize variables for compilation +_IS_LINUX = sys.platform.startswith("linux") +_IS_MACOS = sys.platform.startswith("darwin") +_IS_WINDOWS = sys.platform == "win32" + +MINGW_GXX = "x86_64-w64-mingw32-g++" + +SUBPROCESS_DECODE_ARGS = ( + (locale.getpreferredencoding(), "replace") if _IS_WINDOWS else () +) + +log = logging.getLogger(__name__) + + +# =============================== toolchain =============================== +def _split_compiler_command(compiler: str) -> list[str]: + if _IS_WINDOWS: + return [compiler] + command = shlex.split(compiler) + if not command: + raise ValueError("empty compiler command") + return command + + +def _compiler_command(compiler: str, *args: str) -> list[str]: + return [*_split_compiler_command(compiler), *args] + + +@functools.cache +def _compiler_version_string(cpp_compiler: str) -> str: + try: + return ( + subprocess.check_output( + _compiler_command(cpp_compiler, "--version"), + stderr=subprocess.DEVNULL, + ) + .strip() + .decode(*SUBPROCESS_DECODE_ARGS) + ) + except (FileNotFoundError, subprocess.SubprocessError, ValueError): + return "" + + +def _compiler_version_first_line(cpp_compiler: str) -> str: + version_string = _compiler_version_string(cpp_compiler) + return version_string.splitlines()[0] if version_string else "" + + +@functools.lru_cache(1) +def cpp_compiler_search(search: Sequence[str | None]) -> str: + from torch._inductor.codecache import get_lock_dir, LOCK_TIMEOUT + + for cxx in search: + try: + if cxx is None: + # gxx package is only available for Linux + # according to https://anaconda.org/conda-forge/gxx/ + if sys.platform != "linux": + continue + # Do not install GXX by default + if not os.getenv("TORCH_INDUCTOR_INSTALL_GXX"): + continue + from torch.utils._filelock import FileLock + + lock_dir = get_lock_dir() + lock = FileLock( + os.path.join(lock_dir, "g++.lock"), timeout=LOCK_TIMEOUT + ) + with lock: + cxx = install_gcc_via_conda() + subprocess.check_output(_compiler_command(cxx, "--version")) + return cxx + except ( + subprocess.SubprocessError, + FileNotFoundError, + ImportError, + ValueError, + ): + continue + raise exc.InvalidCxxCompiler + + +def install_gcc_via_conda() -> str: + """On older systems, this is a quick way to get a modern compiler""" + prefix = os.path.join(cache_dir(), "gcc") + cxx_path = os.path.join(prefix, "bin", "g++") + if not os.path.exists(cxx_path): + log.info("Downloading GCC via conda") + conda = os.environ.get("CONDA_EXE", "conda") + if conda is None: + conda = shutil.which("conda") + if conda is not None: + subprocess.check_call( + [ + conda, + "create", + f"--prefix={prefix}", + "--channel=conda-forge", + "--quiet", + "-y", + "python=3.8", + "gxx", + ], + stdout=subprocess.PIPE, + ) + return cxx_path + + +@functools.cache +def check_compiler_exist_windows(compiler: str) -> None: + """ + Check if compiler is ready, in case end user not activate MSVC environment. + """ + try: + subprocess.check_output( + _compiler_command(compiler, "/help"), stderr=subprocess.STDOUT + ) + except FileNotFoundError as e: + raise exc.InvalidCxxCompiler(compiler) from e + except subprocess.SubprocessError: + # Expected that some compiler(clang, clang++) is exist, but they not support `/help` args. + pass + + +class WinPeFileVersionInfo: + def __init__(self, file_path: str) -> None: + self.file_path = file_path + self.version_dll = ctypes.WinDLL("version.dll") # type: ignore[attr-defined] + self._setup_functions() + self._get_version_info() + + def _setup_functions(self) -> None: + self.version_dll.GetFileVersionInfoSizeW.argtypes = [ + wintypes.LPCWSTR, + wintypes.LPDWORD, + ] + self.version_dll.GetFileVersionInfoSizeW.restype = wintypes.DWORD + + self.version_dll.GetFileVersionInfoW.argtypes = [ + wintypes.LPCWSTR, + wintypes.DWORD, + wintypes.DWORD, + wintypes.LPVOID, + ] + self.version_dll.GetFileVersionInfoW.restype = wintypes.BOOL + + self.version_dll.VerQueryValueW.argtypes = [ + wintypes.LPCVOID, + wintypes.LPCWSTR, + ctypes.POINTER(ctypes.c_void_p), + ctypes.POINTER(wintypes.UINT), + ] + self.version_dll.VerQueryValueW.restype = wintypes.BOOL + + def _get_version_info(self) -> None: + dummy = wintypes.DWORD() + size = self.version_dll.GetFileVersionInfoSizeW( + self.file_path, ctypes.byref(dummy) + ) + + if size == 0: + raise RuntimeError(f"Can't get version info size of {self.file_path}.") + + self.version_info = ctypes.create_string_buffer(size) + success = self.version_dll.GetFileVersionInfoW( + self.file_path, 0, size, self.version_info + ) + + if not success: + raise RuntimeError(f"Can't get version info of {self.file_path}.") + + def get_language_id(self) -> int: + lp_buffer = ctypes.c_void_p() + u_len = wintypes.UINT() + + success = self.version_dll.VerQueryValueW( + self.version_info, + r"\VarFileInfo\Translation", + ctypes.byref(lp_buffer), + ctypes.byref(u_len), + ) + + if not success or u_len.value == 0: + return 0 + + translations = [] + lang_id: int = 0 + if lp_buffer.value is not None: + for i in range(u_len.value // 4): + offset = i * 4 + data = ctypes.string_at(lp_buffer.value + offset, 4) + lang_id = int.from_bytes(data[:2], "little") + code_page = int.from_bytes(data[2:4], "little") + translations.append((lang_id, code_page)) + else: + # Handle the case where lp_buffer.value is None + print("Buffer is None") + + return lang_id + + +@functools.cache +def check_msvc_cl_language_id(compiler: str) -> None: + """ + Torch.compile() is only work on MSVC with English language pack well. + Check MSVC's language pack: https://github.com/pytorch/pytorch/issues/157673#issuecomment-3051682766 + """ + + def get_msvc_cl_path() -> tuple[bool, str]: + """ + Finds the path to cl.exe using vswhere.exe. + """ + vswhere_path = os.path.join( + os.environ.get("ProgramFiles(x86)", "C:\\Program Files (x86)"), + "Microsoft Visual Studio", + "Installer", + "vswhere.exe", + ) + if not os.path.exists(vswhere_path): + vswhere_path = os.path.join( + os.environ.get("ProgramFiles", "C:\\Program Files"), + "Microsoft Visual Studio", + "Installer", + "vswhere.exe", + ) + if not os.path.exists(vswhere_path): + return False, "" # vswhere.exe not found + + try: + # Get the Visual Studio installation path + cmd = [ + vswhere_path, + "-latest", + "-prerelease", + "-products", + "*", + "-requires", + "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", + "-property", + "installationPath", + ] + vs_install_path = subprocess.check_output( + cmd, text=True, encoding="utf-8" + ).strip() + + if not vs_install_path: + return False, "" + + # Find the latest MSVC toolset version within the installation + msvc_tools_path = os.path.join(vs_install_path, "VC", "Tools", "MSVC") + if not os.path.exists(msvc_tools_path): + return False, "" + + # Get the latest toolset version directory + toolset_versions = [ + d + for d in os.listdir(msvc_tools_path) + if os.path.isdir(os.path.join(msvc_tools_path, d)) + ] + if not toolset_versions: + return False, "" + latest_toolset_version = sorted(toolset_versions, reverse=True)[0] + + # Construct the full cl.exe path + cl_path = os.path.join( + msvc_tools_path, + latest_toolset_version, + "bin", + "HostX64", + "x64", + "cl.exe", + ) + if os.path.exists(cl_path): + return True, cl_path + else: + # Fallback for older versions or different architectures if needed + cl_path = os.path.join( + msvc_tools_path, + latest_toolset_version, + "bin", + "HostX86", + "x86", + "cl.exe", + ) + if os.path.exists(cl_path): + return True, cl_path + + except (subprocess.CalledProcessError, FileNotFoundError): + return False, "" + + return False, "" + + if not _is_msvc_cl(compiler): + return + + if os.path.exists(compiler): + # Passed compiler with path. + cl_exe_path = compiler + else: + b_ret, cl_exe_path = get_msvc_cl_path() + if b_ret is False: + return + + version_info = WinPeFileVersionInfo(cl_exe_path) + lang_id = version_info.get_language_id() + if lang_id != 1033: + # MSVC English language id is 0x0409, and the DEC value is 1033. + raise RuntimeError( + "Torch.compile() is only support MSVC with English language pack," + "Please reinstall its language pack to English." + ) + + +@functools.cache +def check_mingw_win32_flavor(compiler: str) -> str: + """ + Check if MinGW `compiler` exists and return it's flavor (win32 or posix). + """ + try: + out = subprocess.check_output( + _compiler_command(compiler, "-v"), + stderr=subprocess.STDOUT, + text=True, + ) + except FileNotFoundError as e: + raise RuntimeError(f"Compiler: {compiler} is not found.") from e + except Exception as e: + raise RuntimeError(f"Failed to run {compiler} -v") from e + + flavor: str | None = None + for line in out.splitlines(): + if "Thread model" in line: + flavor = line.split(":", 1)[-1].strip().lower() + + if flavor is None: + raise RuntimeError( + f"Cannot determine the flavor of {compiler} (win32 or posix). No Thread model found in {compiler} -v" + ) + + if flavor not in ("win32", "posix"): + raise RuntimeError( + f"Only win32 and pofix flavor of {compiler} is supported. The flavor is {flavor}" + ) + + return flavor + + +def get_cpp_compiler() -> str: + if ( + config.aot_inductor.cross_target_platform == "windows" + and sys.platform != "win32" + ): + # we're doing cross-compilation + compiler = MINGW_GXX + if not config.aot_inductor.package_cpp_only: + check_mingw_win32_flavor(compiler) + return compiler + + if _IS_WINDOWS: + compiler = os.environ.get("CXX", "cl") + compiler = normalize_path_separator(compiler) + check_compiler_exist_windows(compiler) + check_msvc_cl_language_id(compiler) + else: + if config.is_fbcode(): + return build_paths.cc + if isinstance(config.cpp.cxx, (list, tuple)): + search = tuple(config.cpp.cxx) + else: + search = (config.cpp.cxx,) + compiler = cpp_compiler_search(search) + return compiler + + +def get_ld_and_objcopy(use_relative_path: bool) -> tuple[str, str]: + if _IS_WINDOWS: + raise RuntimeError("Windows is not supported yet.") + else: + if config.is_fbcode(): + ld = build_paths.ld + objcopy = ( + build_paths.objcopy_fallback + if use_relative_path + else build_paths.objcopy + ) + else: + ld = "ld" + objcopy = "objcopy" + return ld, objcopy + + +def convert_cubin_to_obj( + cubin_file: str, + kernel_name: str, + ld: str, + objcopy: str, +) -> str: + obj_file = cubin_file + ".o" + # Convert .cubin to .o + cmd = f"{ld} -r -b binary -z noexecstack -o {obj_file} {cubin_file}" + subprocess.run(cmd.split(), capture_output=True, text=True, check=True) + # Rename .data to .rodata + cmd = f"{objcopy} --rename-section .data=.rodata,alloc,load,readonly,data,contents {obj_file}" + subprocess.run(cmd.split(), capture_output=True, text=True, check=True) + # By default objcopy will create *_start, *_size, *_end symbols using the full path + # Rename to use the unique kernel name + file_name = re.sub(r"[\W]", "_", cubin_file) + cmd = ( + objcopy + + f" --redefine-sym _binary_{file_name}_start=__{kernel_name}_start " + + f"--redefine-sym _binary_{file_name}_size=__{kernel_name}_size " + + f"--redefine-sym _binary_{file_name}_end=__{kernel_name}_end " + + obj_file + ) + subprocess.run(cmd.split(), capture_output=True, text=True, check=True) + return obj_file + + +def batch_convert_cubins_to_obj( + cubins: list[tuple[str, str]], + output_dir: str, + cpp_compiler: str = "gcc", +) -> str: + """Convert multiple cubin files to a single .o using batched .incbin assembly. + + Instead of spawning 3 subprocesses per cubin (ld + 2x objcopy), generates + a single .S file with .incbin directives for all cubins and compiles it + with one compiler invocation. Produces bit-identical rodata and symbols + as the per-cubin convert_cubin_to_obj approach. + + Args: + cubins: list of (cubin_file_path, kernel_name) tuples. + output_dir: directory for the generated .S and .o files. + cpp_compiler: C compiler to use for assembling (default: gcc). + + Returns: + Path to the combined .o file. + """ + asm_path = os.path.join(output_dir, "cubins_combined.S") + obj_path = os.path.join(output_dir, "cubins_combined.o") + + with open(asm_path, "w") as f: + f.write(".section .rodata\n") + for cubin_file, kernel_name in cubins: + # Use absolute path to avoid issues with working directory + abs_cubin = os.path.abspath(cubin_file) + escaped_path = abs_cubin.replace("\\", "\\\\").replace('"', '\\"') + f.write( + f".balign 16\n" + f".global __{kernel_name}_start\n" + f".global __{kernel_name}_end\n" + f"__{kernel_name}_start:\n" + f'.incbin "{escaped_path}"\n' + f"__{kernel_name}_end:\n" + f".global __{kernel_name}_size\n" + f".set __{kernel_name}_size, " + f"__{kernel_name}_end - __{kernel_name}_start\n" + ) + + subprocess.run( + _compiler_command(cpp_compiler, "-c", asm_path, "-o", obj_path), + capture_output=True, + text=True, + check=True, + ) + return obj_path + + +@functools.cache +def _is_apple_clang(cpp_compiler: str) -> bool: + first_line = _compiler_version_first_line(cpp_compiler) + return bool(re.search(r"\bApple\b.*\bclang\b", first_line)) + + +@functools.cache +def _is_clang(cpp_compiler: str) -> bool: + if _IS_WINDOWS: + # clang suite have many compilers, and only clang-cl is supported. + if re.search(r"((clang$)|(clang\+\+$))", cpp_compiler): + raise RuntimeError( + "Please use clang-cl, due to torch.compile only support MSVC-like CLI (compiler flags syntax)." + ) + return bool(re.search(r"(clang-cl)", cpp_compiler)) + + if sys.platform == "darwin" and _is_apple_clang(cpp_compiler): + return True + + first_line = _compiler_version_first_line(cpp_compiler) + if "Intel" not in first_line and re.search( + r"(^|[\s/-])clang version\b", first_line + ): + return True + + return bool(re.search(r"(^|[/\s-])(clang\+\+|clang)(?=[\s-]|$)", cpp_compiler)) + + +@functools.cache +def _is_gcc(cpp_compiler: str) -> bool: + # Since "clang++" ends with "g++", the regex match below would validate on it. + if _is_clang(cpp_compiler): + return False + + first_line = _compiler_version_first_line(cpp_compiler) + if re.search( + r"(^|[\s/-])(gcc|g\+\+|gnu-c\+\+)(?=[\s(-]|$)", + first_line, + re.IGNORECASE, + ): + return True + + return bool(re.search(r"(^|[/\s-])(gcc|g\+\+|gnu-c\+\+)(?=[\s-]|$)", cpp_compiler)) + + +@functools.cache +def _is_gcc_version_less_than(cpp_compiler: str, major: int) -> bool: + if not _is_gcc(cpp_compiler): + return False + + try: + output_msg = ( + subprocess.check_output( + _compiler_command(cpp_compiler, "-dumpfullversion", "-dumpversion"), + stderr=subprocess.DEVNULL, + ) + .strip() + .decode(*SUBPROCESS_DECODE_ARGS) + ) + except (FileNotFoundError, subprocess.SubprocessError): + return False + + version_search = re.search(r"\d+(?:\.\d+)*", output_msg) + if version_search is None: + return False + + return TorchVersion(version_search.group(0)) < TorchVersion(str(major)) + + +@functools.cache +def _is_msvc_cl(cpp_compiler: str) -> bool: + if not _IS_WINDOWS: + return False + + try: + result = subprocess.run( + _compiler_command(cpp_compiler, "/help"), + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + check=False, + ) + + lines = (result.stdout or b"").strip().splitlines() + + return bool(lines) and b"Microsoft" in lines[0] + + except OSError: + return False + + +@functools.cache +def _is_intel_compiler(cpp_compiler: str) -> bool: + def _check_minimal_version(compiler_version: TorchVersion) -> None: + """ + On Windows: early version icx has `-print-file-name` issue, and can't preload correctly for inductor. + """ + min_version = "2024.2.1" if _IS_WINDOWS else "0.0.0" + if compiler_version < TorchVersion(min_version): + raise RuntimeError( + f"Intel Compiler error: less than minimal version {min_version}." + ) + + try: + output_msg = _compiler_version_string(cpp_compiler) + lines = output_msg.splitlines() + is_intel_compiler = bool(lines) and "Intel" in lines[0] + if is_intel_compiler: + if _IS_WINDOWS: + if re.search(r"((icx$)|(icx-cc$))", cpp_compiler): + raise RuntimeError( + "Please use icx-cl, due to torch.compile only support MSVC-like CLI (compiler flags syntax)." + ) + + # Version check + icx_ver_search = re.search(r"(\d+[.]\d+[.]\d+[.]\d+)", output_msg) + if icx_ver_search is not None: + icx_ver = icx_ver_search.group(1) + _check_minimal_version(TorchVersion(icx_ver)) + + return is_intel_compiler + except FileNotFoundError: + return False + except subprocess.SubprocessError: + # --version args not support. + return False + + # pyrefly: ignore [unreachable] + return False + + +@functools.cache +def is_gcc() -> bool: + return _is_gcc(get_cpp_compiler()) + + +@functools.cache +def is_clang() -> bool: + return _is_clang(get_cpp_compiler()) + + +@functools.cache +def is_intel_compiler() -> bool: + return _is_intel_compiler(get_cpp_compiler()) + + +@functools.cache +def is_apple_clang() -> bool: + return _is_apple_clang(get_cpp_compiler()) + + +@functools.cache +def is_msvc_cl() -> bool: + return _is_msvc_cl(get_cpp_compiler()) + + +@functools.cache +def get_compiler_version_info(compiler: str) -> str: + env = os.environ.copy() + env["LC_ALL"] = "C" # Don't localize output + try: + version_string = subprocess.check_output( + _compiler_command(compiler, "-v"), + stderr=subprocess.STDOUT, + env=env, + ).decode(*SUBPROCESS_DECODE_ARGS) + except Exception: + try: + version_string = subprocess.check_output( + _compiler_command(compiler, "--version"), + stderr=subprocess.STDOUT, + env=env, + ).decode(*SUBPROCESS_DECODE_ARGS) + except Exception: + return "" + # Multiple lines to one line string. + version_string = version_string.replace("\r", "_") + version_string = version_string.replace("\n", "_") + return version_string + + +# =============================== cpp builder =============================== +def _append_list(dest_list: list[str], src_list: list[str]) -> None: + dest_list.extend(copy.deepcopy(item) for item in src_list) + + +def _remove_duplication_in_list(orig_list: list[str]) -> list[str]: + new_list: list[str] = [] + for item in orig_list: + if item not in new_list: + new_list.append(item) + return new_list + + +def _create_if_dir_not_exist(path_dir: str) -> None: + if not os.path.exists(path_dir): + try: + Path(path_dir).mkdir(parents=True, exist_ok=True) + except OSError as exc: # Guard against race condition + if exc.errno != errno.EEXIST: + raise RuntimeError(f"Fail to create path {path_dir}") from exc + + +def _remove_dir(path_dir: str) -> None: + if os.path.exists(path_dir): + for root, dirs, files in os.walk(path_dir, topdown=False): + for name in files: + file_path = os.path.join(root, name) + os.remove(file_path) + for name in dirs: + dir_path = os.path.join(root, name) + os.rmdir(dir_path) + os.rmdir(path_dir) + + +def _run_compile_cmd(cmd_line: str, cwd: str) -> None: + cmd = shlex.split(cmd_line) + try: + subprocess.run( + cmd, cwd=cwd, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT + ) + except subprocess.CalledProcessError as e: + output = e.stdout.decode(*SUBPROCESS_DECODE_ARGS) + openmp_problem = "'omp.h' file not found" in output or "libomp" in output + if openmp_problem and sys.platform == "darwin": + instruction = ( + "\n\nOpenMP support not found. Please try one of the following solutions:\n" + "(1) Set the `CXX` environment variable to a compiler other than Apple clang++/g++ " + "that has builtin OpenMP support;\n" + "(2) install OpenMP via conda: `conda install llvm-openmp`;\n" + "(3) install libomp via brew: `brew install libomp`;\n" + "(4) manually setup OpenMP and set the `OMP_PREFIX` environment variable to point to a path" + " with `include/omp.h` under it." + ) + output += instruction + raise exc.CppCompileError(cmd, output) from e + + +def run_compile_cmd(cmd_line: str, cwd: str) -> None: + with dynamo_timed("compile_file"): + _run_compile_cmd(cmd_line, cwd) + + +def normalize_path_separator(orig_path: str) -> str: + if _IS_WINDOWS: + return orig_path.replace(os.sep, "/") + return orig_path + + +class BuildOptionsBase: + """ + This is the Base class for store cxx build options, as a template. + Actually, to build a cxx shared library. We just need to select a compiler + and maintains the suitable args. + """ + + def __init__( + self, + compiler: str = "", + definitions: list[str] | None = None, + include_dirs: list[str] | None = None, + cflags: list[str] | None = None, + ldflags: list[str] | None = None, + libraries_dirs: list[str] | None = None, + libraries: list[str] | None = None, + passthrough_args: list[str] | None = None, + aot_mode: bool = False, + use_relative_path: bool = False, + compile_only: bool = False, + precompiling: bool = False, + preprocessing: bool = False, + ) -> None: + self._compiler = compiler + self._definitions: list[str] = definitions or [] + self._include_dirs: list[str] = include_dirs or [] + self._cflags: list[str] = cflags or [] + self._ldflags: list[str] = ldflags or [] + self._libraries_dirs: list[str] = libraries_dirs or [] + self._libraries: list[str] = libraries or [] + # Some args are hard to abstract to OS compatible, passthrough directly. + self._passthrough_args: list[str] = passthrough_args or [] + + # Optionally, the path to a precompiled header which should be included on the + # build command line. + self.precompiled_header: str | None = None + + self._aot_mode: bool = aot_mode + self._use_relative_path: bool = use_relative_path + self._compile_only: bool = compile_only + self._precompiling: bool = precompiling + self._preprocessing: bool = preprocessing + + def _process_compile_only_options(self) -> None: + if self._compile_only or self._precompiling or self._preprocessing: + self._libraries_dirs = [] + self._libraries = [] + self._ldflags = [] + + def _remove_duplicate_options(self) -> None: + self._definitions = _remove_duplication_in_list(self._definitions) + self._include_dirs = _remove_duplication_in_list(self._include_dirs) + self._cflags = _remove_duplication_in_list(self._cflags) + self._ldflags = _remove_duplication_in_list(self._ldflags) + self._libraries_dirs = _remove_duplication_in_list(self._libraries_dirs) + self._libraries = _remove_duplication_in_list(self._libraries) + self._passthrough_args = _remove_duplication_in_list(self._passthrough_args) + + def _finalize_options(self) -> None: + self._process_compile_only_options() + self._remove_duplicate_options() + + def get_compiler(self) -> str: + return self._compiler + + def get_definitions(self) -> list[str]: + return self._definitions + + def get_include_dirs(self) -> list[str]: + return self._include_dirs + + def get_cflags(self) -> list[str]: + return self._cflags + + def get_ldflags(self) -> list[str]: + return self._ldflags + + def get_libraries_dirs(self) -> list[str]: + return self._libraries_dirs + + def get_libraries(self) -> list[str]: + return self._libraries + + def get_passthrough_args(self) -> list[str]: + return self._passthrough_args + + def get_aot_mode(self) -> bool: + return self._aot_mode + + def get_use_relative_path(self) -> bool: + return self._use_relative_path + + def get_compile_only(self) -> bool: + return self._compile_only + + def get_precompiling(self) -> bool: + return self._precompiling + + def get_preprocessing(self) -> bool: + return self._preprocessing + + def save_flags_to_json(self, file: str) -> None: + attrs = { + "compiler": self.get_compiler(), + "definitions": self.get_definitions(), + "include_dirs": self.get_include_dirs(), + "cflags": self.get_cflags(), + "ldflags": self.get_ldflags(), + "libraries_dirs": self.get_libraries_dirs(), + "libraries": self.get_libraries(), + "passthrough_args": self.get_passthrough_args(), + "aot_mode": self.get_aot_mode(), + "use_relative_path": self.get_use_relative_path(), + "compile_only": self.get_compile_only(), + } + + with open(file, "w") as f: + json.dump(attrs, f) + + +def _get_warning_all_cflag(warning_all: bool = True) -> list[str]: + if not _IS_WINDOWS: + return ["Wall"] if warning_all else [] + else: + return [] + + +def _get_cpp_std_cflag(std_num: str = "c++20") -> list[str]: + if _IS_WINDOWS: + """ + On Windows, only c++20 can support `std::enable_if_t`. + Ref: https://learn.microsoft.com/en-us/cpp/overview/cpp-conformance-improvements-2019?view=msvc-170#checking-for-abstract-class-types # noqa: B950 + Note: + Only setup c++20 for Windows inductor. I tried to upgrade all project to c++20, but it is failed: + https://github.com/pytorch/pytorch/pull/131504 + """ + std_num = "c++20" + return [f"std:{std_num}"] + else: + return [f"std={std_num}"] + + +def _get_os_related_cpp_cflags(cpp_compiler: str) -> list[str]: + if _IS_WINDOWS: + cflags = [ + "wd4819", + "wd4251", + "wd4244", + "wd4267", + "wd4275", + "wd4018", + "wd4190", + "wd4624", + "wd4067", + "wd4068", + "EHsc", + # For Intel oneAPI, ref: https://learn.microsoft.com/en-us/cpp/build/reference/zc-cplusplus?view=msvc-170 + "Zc:__cplusplus", + # Enable max compatible to msvc for oneAPI headers. + # ref: https://github.com/pytorch/pytorch/blob/db38c44ad639e7ada3e9df2ba026a2cb5e40feb0/cmake/public/utils.cmake#L352-L358 + "permissive-", + ] + else: + cflags = ["Wno-unused-variable", "Wno-unknown-pragmas"] + if _is_clang(cpp_compiler): + ignored_optimization_argument = ( + "Werror=ignored-optimization-argument" + if config.aot_inductor.raise_error_on_ignored_optimization + else "Wno-ignored-optimization-argument" + ) + cflags.append(ignored_optimization_argument) + if _is_gcc(cpp_compiler): + # Issue all the warnings demanded by strict ISO C and ISO C++. + # Ref: https://github.com/pytorch/pytorch/issues/153180#issuecomment-2986676878 + cflags.append("pedantic") + return cflags + + +def _get_os_related_cpp_definitions(cpp_compiler: str) -> list[str]: + os_definitions: list[str] = [] + if _IS_WINDOWS: + # On Windows, we need disable min/max macro to avoid C2589 error, as PyTorch CMake: + # https://github.com/pytorch/pytorch/blob/9a41570199155eee92ebd28452a556075e34e1b4/CMakeLists.txt#L1118-L1119 + os_definitions.append("NOMINMAX") + return os_definitions + + +def _get_ffast_math_flags() -> list[str]: + if _IS_WINDOWS: + flags = [] + else: + # This starts from the flags implied by -ffast-math, as in + # https://github.com/gcc-mirror/gcc/blob/4700ad1c78ccd7767f846802fca148b2ea9a1852/gcc/opts.cc#L3458-L3468 + # however gcc<13 sets the FTZ/DAZ flags for runtime on x86 even if we have + # -ffast-math -fno-unsafe-math-optimizations because the flags for runtime + # are added by linking in crtfastmath.o. This is done by the spec file which + # only does globbing for -ffast-math. + flags = [ + "fno-trapping-math", + "funsafe-math-optimizations", + "ffinite-math-only", + "fno-signed-zeros", + ] + + flags.append("fno-finite-math-only") + if not config.cpp.enable_unsafe_math_opt_flag: + flags.append("fno-unsafe-math-optimizations") + # Keep errno-preserving libm semantics. With -fno-math-errno, GCC can + # inline/transform libm call pairs like sin(atan(x)) in ways that do not + # preserve NaN values (see https://github.com/pytorch/pytorch/issues/143978). + flags.append("fmath-errno") + flags.append(f"ffp-contract={config.cpp.enable_floating_point_contract_flag}") + + if is_gcc(): + flags.append("fexcess-precision=fast") + + return flags + + +def _get_inductor_debug_symbol_cflags() -> tuple[list[str], list[str]]: + """ + When we turn on generate debug symbol. + On Windows, it should create a [module_name].pdb file. It helps debug by WinDBG. + On Linux, it should create some debug sections in binary file. + """ + cflags: list[str] = [] + ldflags: list[str] = [] + + if _IS_WINDOWS: + cflags = ["ZI", "_DEBUG"] + ldflags = ["DEBUG", "ASSEMBLYDEBUG ", "OPT:REF", "OPT:ICF"] + else: + cflags.append("g") + + return cflags, ldflags + + +@functools.cache +def _get_linux_aarch64_cpu_flags() -> OrderedSet[str]: + flags: OrderedSet[str] = OrderedSet() + + if platform.machine() not in ("aarch64", "arm64"): + return flags + + if not sys.platform.startswith("linux"): + return flags + + capabilities = torch.cpu.get_capabilities() + flags.update( + capability + for capability in ("bf16", "sve", "sve2") + if capabilities.get(capability, False) + ) + + return flags + + +@functools.cache +def _get_linux_aarch64_arch_flag(cpp_compiler: str) -> str: + flags = _get_linux_aarch64_cpu_flags() + + if _is_gcc(cpp_compiler) and _is_gcc_version_less_than(cpp_compiler, 13): + if OrderedSet(["bf16", "sve", "sve2"]).issubset(flags): + return "march=armv8.6-a+sve+sve2+bf16" + + if OrderedSet(["bf16", "sve"]).issubset(flags): + return "march=armv8.6-a+sve+bf16" + + return "march=native" + + +def _get_cpu_arch_cflags(cpp_compiler: str) -> list[str]: + if config.is_fbcode(): + return [] + + march = config.cpp.march + if march == "": + return [] + + # -march=native is not recognized on Apple Silicon, so the default macOS + # behavior is no architecture flag unless the user explicitly configures one. + if sys.platform == "darwin" and march is None: + return [] + + machine = platform.machine() + if march is None: + if machine == "ppc64le": + return ["mcpu=native"] + if machine == "riscv64": + return ["march=rv64gc"] + if machine == "riscv32": + return ["march=rv32gc"] + if machine in ("aarch64", "arm64"): + return [_get_linux_aarch64_arch_flag(cpp_compiler)] + return ["march=native"] + + if machine == "ppc64le": + return [f"mcpu={march}"] + return [f"march={march}"] + + +def _get_optimization_cflags( + cpp_compiler: str, min_optimize: bool = False +) -> tuple[list[str], list[str]]: + cflags: list[str] = [] + ldflags: list[str] = [] + + should_use_optimized_flags = not ( + config.aot_inductor.debug_compile + or os.environ.get("TORCHINDUCTOR_DEBUG_COMPILE", "0") == "1" + ) + should_add_debug_symbol_flags = ( + config.aot_inductor.debug_compile + or config.aot_inductor.debug_symbols + or os.environ.get("TORCHINDUCTOR_DEBUG_COMPILE", "0") == "1" + or os.environ.get("TORCHINDUCTOR_DEBUG_SYMBOL", "0") == "1" + ) + if should_use_optimized_flags: + if _IS_WINDOWS: + cflags += ["O1" if min_optimize else "O2"] + else: + cflags += [ + config.aot_inductor.compile_wrapper_opt_level if min_optimize else "O3", + "DNDEBUG", + ] + else: + if _IS_WINDOWS: + cflags += ["Od", "Ob0", "Oy-"] + else: + cflags += ["O0"] + + if should_add_debug_symbol_flags: + debug_cflags, debug_ldflags = _get_inductor_debug_symbol_cflags() + cflags += debug_cflags + ldflags += debug_ldflags + + if config.aot_inductor.enable_frame_pointer: + if _IS_WINDOWS: + cflags.append("Oy-") + else: + cflags.append("fno-omit-frame-pointer") + + if config.aot_inductor.enable_line_tables and not should_add_debug_symbol_flags: + if not _IS_WINDOWS: + if _is_clang(cpp_compiler): + cflags.append("gline-tables-only") + else: + cflags.append("g1") + + cflags += _get_ffast_math_flags() + + if _IS_WINDOWS: + pass + else: + # on macos, unknown argument: '-fno-tree-loop-vectorize' + if sys.platform != "darwin" and _is_gcc(cpp_compiler): + cflags.append("fno-tree-loop-vectorize") + cflags += _get_cpu_arch_cflags(cpp_compiler) + + if config.aot_inductor.enable_lto and _is_clang(cpp_compiler): + cflags.append("flto=thin") + + return cflags, ldflags + + +def _get_shared_cflags(cpp_compiler: str, do_link: bool) -> list[str]: + if _IS_WINDOWS: + """ + MSVC `/MD` using python `ucrtbase.dll` lib as runtime. + https://learn.microsoft.com/en-us/cpp/c-runtime-library/crt-library-features?view=msvc-170 + """ + return ["DLL", "MD"] + if platform.system() == "Darwin" and _is_clang(cpp_compiler): + # This causes undefined symbols to behave the same as linux + return ["shared", "fPIC", "undefined dynamic_lookup"] + flags = [] + if do_link: + flags.append("shared") + + flags.append("fPIC") + return flags + + +def get_cpp_options( + cpp_compiler: str, + do_link: bool, + warning_all: bool = True, + extra_flags: Sequence[str] = (), + min_optimize: bool = False, +) -> tuple[list[str], list[str], list[str], list[str], list[str], list[str], list[str]]: + definitions: list[str] = [] + include_dirs: list[str] = [] + cflags: list[str] = [] + ldflags: list[str] = [] + libraries_dirs: list[str] = [] + libraries: list[str] = [] + passthrough_args: list[str] = [] + + opt_cflags, opt_ldflags = _get_optimization_cflags(cpp_compiler, min_optimize) + + cflags = ( + opt_cflags + + _get_shared_cflags(cpp_compiler, do_link) + + _get_warning_all_cflag(warning_all) + + _get_cpp_std_cflag() + + _get_os_related_cpp_cflags(cpp_compiler) + ) + + definitions += _get_os_related_cpp_definitions(cpp_compiler) + + if not _IS_WINDOWS and config.aot_inductor.enable_lto and _is_clang(cpp_compiler): + ldflags.append("fuse-ld=lld") + ldflags.append("flto=thin") + + passthrough_args.append(" ".join(extra_flags)) + + if config.aot_inductor.cross_target_platform == "windows": + passthrough_args.extend(["-static-libstdc++", "-static-libgcc"]) + if check_mingw_win32_flavor(MINGW_GXX) == "posix": + # winpthread provides clock_gettime, referenced by static libstdc++'s + # chrono. The driver places libstdc++ after these args, so force the + # symbol undefined up front to pull winpthread in regardless of order. + passthrough_args.append( + "-Wl,-u,clock_gettime -Wl,-Bstatic -lwinpthread -Wl,-Bdynamic" + ) + + return ( + definitions, + include_dirs, + cflags, + ldflags + opt_ldflags, + libraries_dirs, + libraries, + passthrough_args, + ) + + +class CppOptions(BuildOptionsBase): + """ + This class is inherited from BuildOptionsBase, and as cxx build options. + This option need contains basic cxx build option, which contains: + 1. OS related args. + 2. Toolchains related args. + 3. Cxx standard related args. + Note: + 1. This Options is good for assist modules build, such as x86_isa_help. + """ + + def __init__( + self, + compile_only: bool = False, + warning_all: bool = True, + extra_flags: Sequence[str] = (), + use_relative_path: bool = False, + compiler: str = "", + min_optimize: bool = False, + precompiling: bool = False, + preprocessing: bool = False, + ) -> None: + super().__init__( + compile_only=compile_only, + use_relative_path=use_relative_path, + precompiling=precompiling, + preprocessing=preprocessing, + ) + self._compiler = compiler if compiler else get_cpp_compiler() + + ( + definitions, + include_dirs, + cflags, + ldflags, + libraries_dirs, + libraries, + passthrough_args, + ) = get_cpp_options( + cpp_compiler=self._compiler, + do_link=not (compile_only or precompiling or preprocessing), + extra_flags=extra_flags, + warning_all=warning_all, + min_optimize=min_optimize, + ) + + _append_list(self._definitions, definitions) + _append_list(self._include_dirs, include_dirs) + _append_list(self._cflags, cflags) + _append_list(self._ldflags, ldflags) + _append_list(self._libraries_dirs, libraries_dirs) + _append_list(self._libraries, libraries) + _append_list(self._passthrough_args, passthrough_args) + self._finalize_options() + + +def _get_torch_cpp_wrapper_definition() -> list[str]: + defs = ["TORCH_INDUCTOR_CPP_WRAPPER", "STANDALONE_TORCH_HEADER"] + if config.cpp_cache_precompile_headers: + defs.append("TORCH_INDUCTOR_PRECOMPILE_HEADERS") + return defs + + +def _use_custom_generated_macros() -> list[str]: + return [" C10_USING_CUSTOM_GENERATED_MACROS"] + + +def _use_fb_internal_macros() -> list[str]: + if not _IS_WINDOWS: + if config.is_fbcode(): + fb_internal_macros = [ + "C10_USE_GLOG", + "C10_USE_MINIMAL_GLOG", + "C10_DISABLE_TENSORIMPL_EXTENSIBILITY", + ] + if platform.machine() == "x86_64": + fb_internal_macros += [ + "ATEN_MKL_ENABLED_FBCODE=1", + "ATEN_MKLDNN_ENABLED_FBCODE=1", + ] + return fb_internal_macros + else: + return [] + else: + return [] + + +def _setup_standard_sys_libs( + cpp_compiler: str, + aot_mode: bool, + use_relative_path: bool, +) -> tuple[list[str], list[str], list[str], list[str]]: + cflags: list[str] = [] + include_dirs: list[str] = [] + passthrough_args: list[str] = [] + ldflags: list[str] = [] + if _IS_WINDOWS: + return cflags, include_dirs, passthrough_args, ldflags + + if config.is_fbcode(): + # TODO(T203137008) Can we unify these flags with triton_cc_command? + cflags.append("nostdinc") + # Note that the order of include paths do matter, as a result + # we need to have several branches interleaved here + include_dirs.append(build_paths.sleef_include) + include_dirs.append(build_paths.openmp_include) + include_dirs.append(build_paths.python_include) + include_dirs.append(build_paths.cc_include) + include_dirs.append(build_paths.libgcc_include) + include_dirs.append(build_paths.libgcc_arch_include) + include_dirs.append(build_paths.libgcc_backward_include) + include_dirs.append(build_paths.glibc_include) + include_dirs.append(build_paths.linux_kernel_include) + include_dirs.append("include") + + if aot_mode and not use_relative_path: + linker_script = _LINKER_SCRIPT + else: + linker_script = os.path.basename(_LINKER_SCRIPT) + + if _is_clang(cpp_compiler): + passthrough_args.append(" --rtlib=compiler-rt") + passthrough_args.append(" -B" + build_paths.glibc_lib) + ldflags.append("fuse-ld=lld") + ldflags.append(f"Wl,--script={linker_script}") + ldflags.append("L" + build_paths.glibc_lib) + + return cflags, include_dirs, passthrough_args, ldflags + + +def _get_build_args_of_chosen_isa(vec_isa: VecISA) -> tuple[list[str], list[str]]: + macros: list[str] = [] + build_flags: list[str] = [] + if vec_isa != invalid_vec_isa: + # Add Windows support later. + macros.extend(copy.deepcopy(x) for x in vec_isa.build_macro()) + + build_flags = [vec_isa.build_arch_flags()] + + if config.is_fbcode(): + cap = str(vec_isa).upper() + macros = [ + f"CPU_CAPABILITY={cap}", + f"CPU_CAPABILITY_{cap}", + f"HAVE_{cap}_CPU_DEFINITION", + ] + + return macros, build_flags + + +def _get_torch_related_args( + include_pytorch: bool, aot_mode: bool +) -> tuple[list[str], list[str], list[str]]: + from torch.utils.cpp_extension import include_paths, TORCH_LIB_PATH + + libraries = [] + include_dirs = include_paths() + + if config.aot_inductor.link_libtorch: + libraries_dirs = [TORCH_LIB_PATH] + if sys.platform != "darwin" and not config.is_fbcode(): + libraries.extend(["torch", "torch_cpu"]) + if _IS_WINDOWS: + libraries.append("c10") + if not aot_mode: + libraries.append("torch_python") + else: + libraries_dirs = [] + if config.aot_inductor.cross_target_platform == "windows": + aoti_shim_library = config.aot_inductor.aoti_shim_library + + if not aoti_shim_library: + raise AssertionError( + "'config.aot_inductor.aoti_shim_library' must be set when 'cross_target_platform' is 'windows'." + ) + if isinstance(aoti_shim_library, str): + libraries.append(aoti_shim_library) + else: + if not isinstance(aoti_shim_library, list): + raise AssertionError( + f"expected aoti_shim_library to be a list, got {type(aoti_shim_library)}" + ) + libraries.extend(aoti_shim_library) + + if config.aot_inductor.cross_target_platform == "windows": + if not config.aot_inductor.aoti_shim_library_path: + raise AssertionError( + ( + "'config.aot_inductor.aoti_shim_library_path' must be set to the path of the AOTI shim library", + " when 'cross_target_platform' is 'windows'.", + ) + ) + libraries_dirs.append(config.aot_inductor.aoti_shim_library_path) + + if _IS_WINDOWS: + libraries.append("sleef") + + return include_dirs, libraries_dirs, libraries + + +def _get_python_include_dirs() -> list[str]: + include_dir = Path(sysconfig.get_path("include")) + # On Darwin Python executable from a framework can return + # non-existing /Library/Python/... include path, in which case + # one should use Headers folder from the framework + if not include_dir.exists() and platform.system() == "Darwin": + std_lib = Path(sysconfig.get_path("stdlib")) + include_dir = (std_lib.parent.parent / "Headers").absolute() + if not (include_dir / "Python.h").exists(): + warnings.warn(f"Can't find Python.h in {str(include_dir)}") + return [str(include_dir)] + + +def _get_python_related_args() -> tuple[list[str], list[str]]: + python_include_dirs = _get_python_include_dirs() + python_include_path = sysconfig.get_path( + "include", scheme="nt" if _IS_WINDOWS else "posix_prefix" + ) + if python_include_path is not None: + python_include_dirs.append(python_include_path) + + if _IS_WINDOWS: + python_lib_path = [ + str( + ( + Path(sysconfig.get_path("include", scheme="nt")).parent / "libs" + ).absolute() + ) + ] + else: + python_lib_path = [sysconfig.get_config_var("LIBDIR")] + + if config.is_fbcode(): + python_include_dirs.append(build_paths.python_include) + + return python_include_dirs, python_lib_path + + +@functools.cache +def is_conda_llvm_openmp_installed() -> bool: + try: + command = "conda list llvm-openmp --json" + output = subprocess.check_output(command.split()).decode("utf8") + return len(json.loads(output)) > 0 + except (subprocess.SubprocessError, FileNotFoundError): + return False + + +@functools.cache +def homebrew_libomp() -> tuple[bool, str]: + try: + # check if `brew` is installed + if shutil.which("brew") is None: + return False, "" + # get the location of `libomp` if it is installed + # this is the location that `libomp` **would** be installed + # see https://github.com/Homebrew/brew/issues/10261#issuecomment-756563567 for details + libomp_path = ( + subprocess.check_output(["brew", "--prefix", "libomp"]) + .decode("utf8") + .strip() + ) + # check if `libomp` is installed + omp_available = os.path.exists(libomp_path) + return omp_available, libomp_path + except subprocess.SubprocessError: + return False, "" + + +@functools.cache +def perload_clang_libomp_win(cpp_compiler: str, omp_name: str) -> None: + try: + output = subprocess.check_output( + _compiler_command(cpp_compiler, "-print-file-name=bin") + ).decode("utf8") + omp_path = os.path.join(output.rstrip(), omp_name) + if os.path.isfile(omp_path): + os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" + cdll.LoadLibrary(omp_path) + except subprocess.SubprocessError: + pass + + +@functools.cache +def perload_icx_libomp_win(cpp_compiler: str) -> None: + def _load_icx_built_in_lib_by_name(cpp_compiler: str, lib_name: str) -> bool: + try: + output = subprocess.check_output( + _compiler_command(cpp_compiler, f"-print-file-name={lib_name}"), + stderr=subprocess.DEVNULL, + ).decode(*SUBPROCESS_DECODE_ARGS) + omp_path = output.rstrip() + if os.path.isfile(omp_path): + os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" + cdll.LoadLibrary(omp_path) + return True + except subprocess.SubprocessError: + pass + return False + + """ + Intel Compiler implemented more math libraries than clang, for performance purposes. + We need to preload them like openmp library. + """ + preload_list = [ + "libiomp5md.dll", # openmp + "svml_dispmd.dll", # svml library + "libmmd.dll", # libm + ] + + for lib_name in preload_list: + _load_icx_built_in_lib_by_name(cpp_compiler, lib_name) + + +def _get_openmp_args( + cpp_compiler: str, +) -> tuple[list[str], list[str], list[str], list[str], list[str], list[str]]: + cflags: list[str] = [] + ldflags: list[str] = [] + include_dir_paths: list[str] = [] + lib_dir_paths: list[str] = [] + libs: list[str] = [] + passthrough_args: list[str] = [] + + if config.aot_inductor.cross_target_platform == "windows": + return cflags, ldflags, include_dir_paths, lib_dir_paths, libs, passthrough_args + if _IS_MACOS: + # Per https://mac.r-project.org/openmp/ right way to pass `openmp` flags to MacOS is via `-Xclang` + cflags.append("Xclang") + cflags.append("fopenmp") + + # only Apple builtin compilers (Apple Clang++) require openmp + omp_available = not _is_apple_clang(cpp_compiler) + + # check the `OMP_PREFIX` environment first + omp_prefix = os.getenv("OMP_PREFIX") + if omp_prefix is not None: + header_path = os.path.join(omp_prefix, "include", "omp.h") + valid_env = os.path.exists(header_path) + if valid_env: + include_dir_paths.append(os.path.join(omp_prefix, "include")) + lib_dir_paths.append(os.path.join(omp_prefix, "lib")) + else: + warnings.warn("environment variable `OMP_PREFIX` is invalid.") + omp_available = omp_available or valid_env + + if not omp_available: + libs.append("omp") + + # prefer to use openmp from `conda install llvm-openmp` + conda_prefix = os.getenv("CONDA_PREFIX") + if not omp_available and conda_prefix is not None: + omp_available = is_conda_llvm_openmp_installed() + if omp_available: + conda_lib_path = os.path.join(conda_prefix, "lib") + include_dir_paths.append(os.path.join(conda_prefix, "include")) + lib_dir_paths.append(conda_lib_path) + # Prefer Intel OpenMP on x86 machine + if os.uname().machine == "x86_64" and os.path.exists( + os.path.join(conda_lib_path, "libiomp5.dylib") + ): + libs.append("iomp5") + + # next, try to use openmp from `brew install libomp` + if not omp_available: + omp_available, libomp_path = homebrew_libomp() + if omp_available: + include_dir_paths.append(os.path.join(libomp_path, "include")) + lib_dir_paths.append(os.path.join(libomp_path, "lib")) + + # if openmp is still not available, we let the compiler to have a try, + # and raise error together with instructions at compilation error later + elif _IS_WINDOWS: + """ + On Windows, `clang` and `icx` have their specific openmp implenmention. + And the openmp lib is in compiler's some sub-directory. + For dynamic library(DLL) load, the Windows native APIs are `LoadLibraryA` and `LoadLibraryExA`, and their search + dependencies have some rules: + https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexa#searching-for-dlls-and-dependencies + In some case, the rules may not include compiler's sub-directories. + So, it can't search and load compiler's openmp library correctly. + And then, the whole application would be broken. + + To avoid the openmp load failed, we can automatic locate the openmp binary and preload it. + 1. For clang, the function is `perload_clang_libomp_win`. + 2. For icx, the function is `perload_icx_libomp_win`. + """ + if _is_clang(cpp_compiler): + cflags.append("openmp") + libs.append("libomp") + perload_clang_libomp_win(cpp_compiler, "libomp.dll") + elif _is_intel_compiler(cpp_compiler): + cflags.append("Qiopenmp") + libs.append("libiomp5md") + perload_icx_libomp_win(cpp_compiler) + else: + # /openmp, /openmp:llvm + # llvm on Windows, new openmp: https://devblogs.microsoft.com/cppblog/msvc-openmp-update/ + # msvc openmp: https://learn.microsoft.com/zh-cn/cpp/build/reference/openmp-enable-openmp-2-0-support?view=msvc-170 + cflags.append("openmp") + cflags.append("openmp:experimental") # MSVC CL + else: + if config.is_fbcode(): + include_dir_paths.append(build_paths.openmp_include) + + passthrough_args.append("-Wp,-fopenmp") + lib_dir_paths.append(os.path.dirname(build_paths.openmp_lib_so)) + + libs.append("omp") + else: + if _is_clang(cpp_compiler): + # TODO: fix issue, can't find omp.h + cflags.append("fopenmp") + libs.append("gomp") + elif _is_intel_compiler(cpp_compiler): + cflags.append("fiopenmp") + else: + cflags.append("fopenmp") + libs.append("gomp") + + return cflags, ldflags, include_dir_paths, lib_dir_paths, libs, passthrough_args + + +def _get_libstdcxx_args() -> tuple[list[str], list[str]]: + """ + For fbcode cpu case, we should link stdc++ instead assuming the binary where dlopen is executed is built with dynamic stdc++. + """ + lib_dir_paths: list[str] = [] + libs: list[str] = [] + if config.is_fbcode(): + lib_dir_paths = [sysconfig.get_config_var("LIBDIR")] + libs.append("stdc++") + + return lib_dir_paths, libs + + +def get_mmap_self_macro( + use_mmap_weights: bool, use_mmap_weights_external: bool +) -> list[str]: + macros = [] + + if use_mmap_weights and use_mmap_weights_external: + raise RuntimeError( + "Only one of use_mmap_weights and use_mmap_weights_external should be true" + ) + if use_mmap_weights: + macros.append(" USE_MMAP_SELF") + elif use_mmap_weights_external: + macros.append(" USE_MMAP_EXTERNAL") + return macros + + +def get_caching_allocator_macro() -> list[str]: + from torch._inductor import config + + macros = [] + if config.aot_inductor.weight_use_caching_allocator: + macros.append(" AOT_INDUCTOR_USE_CACHING_ALLOCATOR") + return macros + + +def get_cpp_torch_options( + cpp_compiler: str, + vec_isa: VecISA, + include_pytorch: bool, + aot_mode: bool, + use_relative_path: bool, + use_mmap_weights: bool, + use_mmap_weights_external: bool, +) -> tuple[list[str], list[str], list[str], list[str], list[str], list[str], list[str]]: + """ + This function is used to get the build args of torch related build options. + 1. Torch include_directories, libraries, libraries_directories. + 2. Python include_directories, libraries, libraries_directories. + 3. OpenMP related. + 4. Torch MACROs. + 5. MISC + 6. Return the build args + """ + definitions: list[str] = [] + include_dirs: list[str] = [] + cflags: list[str] = [] + ldflags: list[str] = [] + libraries_dirs: list[str] = [] + libraries: list[str] = [] + passthrough_args: list[str] = [] + + torch_cpp_wrapper_definitions = _get_torch_cpp_wrapper_definition() + use_custom_generated_macros_definitions = _use_custom_generated_macros() + + ( + sys_libs_cflags, + sys_libs_include_dirs, + sys_libs_passthrough_args, + sys_libs_ldflags, + ) = _setup_standard_sys_libs(cpp_compiler, aot_mode, use_relative_path) + + isa_macros, isa_ps_args_build_flags = _get_build_args_of_chosen_isa(vec_isa) + + ( + torch_include_dirs, + torch_libraries_dirs, + torch_libraries, + ) = _get_torch_related_args(include_pytorch=include_pytorch, aot_mode=aot_mode) + + python_include_dirs, python_libraries_dirs = _get_python_related_args() + + ( + omp_cflags, + omp_ldflags, + omp_include_dir_paths, + omp_lib_dir_paths, + omp_lib, + omp_passthrough_args, + ) = _get_openmp_args(cpp_compiler) + + fb_macro_passthrough_args = _use_fb_internal_macros() + + mmap_self_macros = get_mmap_self_macro(use_mmap_weights, use_mmap_weights_external) + caching_allocator_macros = get_caching_allocator_macro() + + definitions = ( + torch_cpp_wrapper_definitions + + use_custom_generated_macros_definitions + + isa_macros + + fb_macro_passthrough_args + + mmap_self_macros + + caching_allocator_macros + ) + include_dirs = ( + sys_libs_include_dirs + + python_include_dirs + + torch_include_dirs + + omp_include_dir_paths + ) + cflags = sys_libs_cflags + omp_cflags + ldflags = sys_libs_ldflags + omp_ldflags + libraries_dirs = python_libraries_dirs + torch_libraries_dirs + omp_lib_dir_paths + libraries = torch_libraries + omp_lib + passthrough_args = ( + sys_libs_passthrough_args + isa_ps_args_build_flags + omp_passthrough_args + ) + + return ( + definitions, + include_dirs, + cflags, + ldflags, + libraries_dirs, + libraries, + passthrough_args, + ) + + +class CppTorchOptions(CppOptions): + """ + This class is inherited from CppTorchOptions, which automatic contains + base cxx build options. And then it will maintains torch related build + args. + 1. Torch include_directories, libraries, libraries_directories. + 2. Python include_directories, libraries, libraries_directories. + 3. OpenMP related. + 4. Torch MACROs. + 5. MISC + """ + + def __init__( + self, + vec_isa: VecISA = invalid_vec_isa, + include_pytorch: bool = False, + warning_all: bool = True, + aot_mode: bool = False, + compile_only: bool = False, + use_relative_path: bool = False, + use_mmap_weights: bool = False, + use_mmap_weights_external: bool = False, + shared: bool = True, + extra_flags: Sequence[str] = (), + compiler: str = "", + min_optimize: bool = False, + precompiling: bool = False, + preprocessing: bool = False, + ) -> None: + super().__init__( + compile_only=compile_only, + warning_all=warning_all, + extra_flags=extra_flags, + use_relative_path=use_relative_path, + compiler=compiler, + min_optimize=min_optimize, + precompiling=precompiling, + preprocessing=preprocessing, + ) + + self._aot_mode = aot_mode + + ( + torch_definitions, + torch_include_dirs, + torch_cflags, + torch_ldflags, + torch_libraries_dirs, + torch_libraries, + torch_passthrough_args, + ) = get_cpp_torch_options( + cpp_compiler=self._compiler, + vec_isa=vec_isa, + include_pytorch=include_pytorch, + aot_mode=aot_mode, + use_relative_path=use_relative_path, + use_mmap_weights=use_mmap_weights, + use_mmap_weights_external=use_mmap_weights_external, + ) + + _append_list(self._definitions, torch_definitions) + _append_list(self._include_dirs, torch_include_dirs) + _append_list(self._cflags, torch_cflags) + _append_list(self._ldflags, torch_ldflags) + _append_list(self._libraries_dirs, torch_libraries_dirs) + _append_list(self._libraries, torch_libraries) + _append_list(self._passthrough_args, torch_passthrough_args) + self._finalize_options() + + +def _set_gpu_runtime_env() -> None: + if ( + config.is_fbcode() + and torch.version.hip is None + and "CUDA_HOME" not in os.environ + and "CUDA_PATH" not in os.environ + ): + os.environ["CUDA_HOME"] = build_paths.sdk_home + + +@functools.lru_cache(8) +def _find_libcudart_static(path: str) -> Path | None: + lib_dirs = list(Path(path).rglob("libcudart_static.a")) + if lib_dirs: + return lib_dirs[0].resolve().parent + log_msg = f'"libcudart_static.a" not found under {path}' + log.info(log_msg) + return None + + +def _gen_mingw_import_lib(dll_path: str, def_path: str, import_lib_path: str) -> None: + """Generate a MinGW import library (.a) from a DLL using gendef and dlltool.""" + dll_name = os.path.basename(dll_path) + with open(def_path, "w") as def_file: + subprocess.run( + ["gendef", "-", dll_path], + stdout=def_file, + stderr=subprocess.PIPE, + check=True, + ) + + subprocess.run( + [ + "x86_64-w64-mingw32-dlltool", + "-d", + def_path, + "-l", + import_lib_path, + "-D", + dll_name, + ], + stderr=subprocess.PIPE, + check=True, + ) + log.info("Generated MinGW import library %s from %s", import_lib_path, dll_name) + + +# MSVC /GS and Control Flow Guard stubs for MinGW cross-compilation. +# CUDA 13.0+ cudart.lib contains MSVC-compiled static objects that reference the +# /GS symbols (__security_cookie, __security_check_cookie, __GSHandlerCheck); the +# CUDA 13.2 cudart.lib is additionally built with Control Flow Guard (/guard:cf) +# and references the CFG dispatch/check function pointers. When cross-compiling +# with MinGW (no MSVC runtime), we provide stubs so the linker can resolve them. +# At runtime on Windows the CUDA runtime DLL handles its own security/CFG checks; +# the static loader code that references these symbols is a thin shim. The /GS +# and CFG-check stubs are safe no-ops, but the CFG *dispatch* stub must tail-jump +# to the real target (in rax on x86_64) -- a no-op would drop the indirect call. +_MSVC_GS_STUBS_SOURCE = """\ +#include +uint64_t __security_cookie = 0x00002B992DDFA232ULL; +void __security_check_cookie(uint64_t cookie) { (void)cookie; } +void __GSHandlerCheck(void) {} +void __guard_check_icall_nop(void *target) { (void)target; } +void (*__guard_check_icall_fptr)(void *target) = __guard_check_icall_nop; +__attribute__((naked)) void __guard_dispatch_icall_nop(void) { + __asm__ __volatile__("jmp *%rax"); +} +void (*__guard_dispatch_icall_fptr)(void) = __guard_dispatch_icall_nop; +""" + + +def _create_msvc_gs_stubs_lib(output_dir: str) -> str | None: + """ + Create a static library with MSVC GS security symbol stubs for MinGW. + + Returns the library name (without lib prefix / .a suffix) if successful, + or None on failure. + """ + stubs_lib = os.path.join(output_dir, "libmsvc_gs_stubs.a") + if os.path.exists(stubs_lib): + return "msvc_gs_stubs" + + src_path = "" + obj_path = "" + try: + src_path = os.path.join(output_dir, "_msvc_gs_stubs.c") + obj_path = os.path.join(output_dir, "_msvc_gs_stubs.o") + with open(src_path, "w") as f: + f.write(_MSVC_GS_STUBS_SOURCE) + + mingw_gcc = MINGW_GXX.replace("g++", "gcc") + subprocess.run( + [mingw_gcc, "-c", src_path, "-o", obj_path], + stderr=subprocess.PIPE, + check=True, + ) + mingw_ar = MINGW_GXX.replace("g++", "ar") + subprocess.run( + [mingw_ar, "rcs", stubs_lib, obj_path], + stderr=subprocess.PIPE, + check=True, + ) + log.info("Created MSVC GS stubs library: %s", stubs_lib) + return "msvc_gs_stubs" + except (FileNotFoundError, subprocess.CalledProcessError): + log.warning( + "Failed to create MSVC GS stubs library.", + exc_info=True, + ) + if os.path.exists(stubs_lib): + os.remove(stubs_lib) + return None + finally: + for f in [src_path, obj_path]: + if f and os.path.exists(f): + os.remove(f) + + +def _ensure_mingw_cudart_import_lib(libraries_dirs: list[str]) -> list[str]: + """ + Auto-generate a MinGW-compatible import library (libcudart.a) + from the CUDA runtime DLL. This avoids linking against the hybrid cudart.lib + which contains MSVC-compiled static objects with /GS security symbols that + MinGW cannot resolve. + + Falls back to creating MSVC GS security stubs if the DLL is unavailable, + and falls back gracefully to the original cudart.lib if that also fails. + + Returns a list of extra library names to link (e.g. ["msvc_gs_stubs"]). + """ + import glob + + windows_cuda_home = os.environ.get("WINDOWS_CUDA_HOME") + if not windows_cuda_home: + log.debug( + "WINDOWS_CUDA_HOME not set, skipping MinGW cudart import lib generation" + ) + return [] + + for lib_dir in libraries_dirs: + if os.path.exists(os.path.join(lib_dir, "libcudart.a")): + log.debug("libcudart.a already exists in %s, skipping generation", lib_dir) + return [] + + # Find the CUDA runtime DLL for import lib generation + bin_dir = os.path.join(windows_cuda_home, "bin", "x64") + if not os.path.isdir(bin_dir): + bin_dir = os.path.join(windows_cuda_home, "bin") + dll_candidates = glob.glob(os.path.join(bin_dir, "cudart64_*.dll")) + + # Find a writable directory containing cudart.lib for output + output_dir = None + for lib_dir in libraries_dirs: + if os.path.isdir(lib_dir) and os.access(lib_dir, os.W_OK): + if os.path.exists(os.path.join(lib_dir, "cudart.lib")): + output_dir = lib_dir + break + + if not dll_candidates: + log.warning( + "No cudart64_*.dll found in %s. Cannot generate MinGW import library. " + "Will create MSVC GS security stubs as fallback.", + bin_dir, + ) + # Fallback: create GS stubs so the hybrid cudart.lib can link + if output_dir is not None: + stub_lib = _create_msvc_gs_stubs_lib(output_dir) + if stub_lib: + return [stub_lib] + return [] + + if output_dir is None: + log.warning( + "No writable directory containing cudart.lib found. " + "Cannot generate MinGW import library. " + "If linking fails with undefined references to __security_cookie, " + "ensure cudart.lib is present in one of: %s", + libraries_dirs, + ) + return [] + + dll_path = dll_candidates[0] + dll_name = os.path.basename(dll_path) + + def_path = os.path.join(output_dir, dll_name.replace(".dll", ".def")) + import_lib_path = os.path.join(output_dir, "libcudart.a") + + try: + _gen_mingw_import_lib(dll_path, def_path, import_lib_path) + return [] + except (FileNotFoundError, subprocess.CalledProcessError): + log.warning( + "Failed to generate MinGW cudart import library. " + "Falling back to MSVC GS stubs.", + exc_info=True, + ) + for f in [def_path, import_lib_path]: + if os.path.exists(f): + os.remove(f) + # Fallback: create GS stubs + stub_lib = _create_msvc_gs_stubs_lib(output_dir) + if stub_lib: + return [stub_lib] + return [] + + +def _transform_cuda_paths(lpaths: list[str]) -> None: + # This handles two cases: + # 1. Cases where libs are in (e.g.) lib/cuda-12 and lib/cuda-12/stubs + # 2. Linux machines may have CUDA installed under either lib64/ or lib/ + for i, path in enumerate(lpaths): + if "CUDA_HOME" in os.environ and path.startswith(os.environ["CUDA_HOME"]): + lib_dir: Path | None = _find_libcudart_static(path) + if lib_dir is None: + continue + lpaths[i] = str(lib_dir) + stub_dir = lib_dir / "stubs" + if stub_dir.exists(): + lpaths.append(str(stub_dir)) + + # Internal path needs special care, using the SDK lib path directly. + if config.is_fbcode(): + # Add sdk_lib and its stubs/ (which hold the CUDA libs) unconditionally: + # an existence gate fails on the not-yet-materialized EdenFS path, and a + # nonexistent -L is harmless to the linker. + for cuda_lib_dir in ( + build_paths.sdk_lib, + os.path.join(build_paths.sdk_lib, "stubs"), + ): + if cuda_lib_dir not in lpaths: + lpaths.append(cuda_lib_dir) + + +def _transform_rocm_paths(lpaths: list[str]) -> None: + # Internal path needs special care, using the SDK lib path directly. + if config.is_fbcode(): + sdk_lib = build_paths.sdk_lib + if os.path.isdir(sdk_lib) and sdk_lib not in lpaths: + lpaths.append(sdk_lib) + + +def get_cpp_torch_device_options( + device_type: str, + aot_mode: bool = False, + compile_only: bool = False, +) -> tuple[list[str], list[str], list[str], list[str], list[str], list[str], list[str]]: + """ + This function is used to get the build args of device related build options. + 1. Device include_directories, libraries, libraries_directories. + 2. Device MACROs. + 3. MISC + 4. Return the build args + """ + definitions: list[str] = [] + include_dirs: list[str] = [] + cflags: list[str] = [] + ldflags: list[str] = [] + libraries_dirs: list[str] = [] + libraries: list[str] = [] + passthrough_args: list[str] = [] + if ( + config.is_fbcode() + and "CUDA_HOME" not in os.environ + and "CUDA_PATH" not in os.environ + ): + os.environ["CUDA_HOME"] = build_paths.sdk_home + + _set_gpu_runtime_env() + from torch.utils import cpp_extension + + # cpp_extension resolves CUDA_HOME into a module-level global at import time, + # so an fbcode process that imported it before the env var above was written + # caches None; refresh the global here so the just-set CUDA_HOME env actually + # takes effect for include_paths/library_paths below. + if cpp_extension.CUDA_HOME is None and os.environ.get("CUDA_HOME"): + cpp_extension.CUDA_HOME = os.environ["CUDA_HOME"] + + include_dirs = cpp_extension.include_paths( + device_type, config.aot_inductor.link_libtorch is None + ) + link_libtorch = config.aot_inductor.link_libtorch + libraries_dirs = cpp_extension.library_paths( + device_type, + torch_include_dirs=link_libtorch, + cross_target_platform=config.aot_inductor.cross_target_platform, + ) + if device_type == "cuda": + definitions.append(" USE_ROCM" if torch.version.hip else " USE_CUDA") + + if torch.version.hip is not None: + if config.is_fbcode() or not link_libtorch: + libraries += ["amdhip64"] + else: + libraries += ["torch_hip"] + definitions.append(" __HIP_PLATFORM_AMD__") + _transform_rocm_paths(libraries_dirs) + else: + if config.is_fbcode() or not link_libtorch: + libraries += ["cuda"] + else: + libraries += ["cuda", "torch_cuda"] + if config.aot_inductor.cross_target_platform == "windows": + extra_libs = _ensure_mingw_cudart_import_lib(libraries_dirs) + libraries += ["cudart"] + extra_libs + _transform_cuda_paths(libraries_dirs) + + if device_type == "xpu": + definitions.append(" USE_XPU") + xpu_error_string = ( + "Intel GPU driver is not properly installed, please follow the instruction " + "in https://github.com/pytorch/pytorch?tab=readme-ov-file#intel-gpu-support." + ) + if _IS_WINDOWS: + ze_root = os.getenv("LEVEL_ZERO_V1_SDK_PATH") + if ze_root is None: + raise OSError(xpu_error_string) + include_dirs += [os.path.join(ze_root, "include")] + libraries_dirs += [os.path.join(ze_root, "lib")] + else: + # Suppress multi-line comment warnings in sycl headers + cflags += ["Wno-comment"] + if not find_library("ze_loader"): + raise OSError(xpu_error_string) + + libraries += ["ze_loader", "sycl"] + if link_libtorch: + libraries += ["torch_xpu"] + + if device_type == "mps": + definitions.append(" USE_MPS") + + if config.is_fbcode(): + include_dirs.append(build_paths.sdk_include) + + if aot_mode and device_type == "cuda": + if torch.version.hip is None: + if not compile_only: + # Only add link args, when compile_only is false. + passthrough_args = ["-Wl,-Bstatic -lcudart_static -Wl,-Bdynamic"] + + if device_type == "cpu": + ( + stdcxx_lib_dir_paths, + stdcxx_libs, + ) = _get_libstdcxx_args() + libraries_dirs += stdcxx_lib_dir_paths + libraries += stdcxx_libs + + if config.aot_inductor.custom_op_libs: + libraries += config.aot_inductor.custom_op_libs + + return ( + definitions, + include_dirs, + cflags, + ldflags, + libraries_dirs, + libraries, + passthrough_args, + ) + + +class CppTorchDeviceOptions(CppTorchOptions): + """ + This class is inherited from CppTorchOptions, which automatic contains + base cxx build options and torch common build options. And then it will + maintains cuda/xpu device related build args. + """ + + def __init__( + self, + vec_isa: VecISA = invalid_vec_isa, + include_pytorch: bool = False, + device_type: str = "cuda", + aot_mode: bool = False, + compile_only: bool = False, + use_relative_path: bool = False, + use_mmap_weights: bool = False, + use_mmap_weights_external: bool = False, + shared: bool = True, + extra_flags: Sequence[str] = (), + min_optimize: bool = False, + precompiling: bool = False, + preprocessing: bool = False, + compiler: str = "", + ) -> None: + super().__init__( + vec_isa=vec_isa, + include_pytorch=include_pytorch, + aot_mode=aot_mode, + compile_only=compile_only, + use_relative_path=use_relative_path, + use_mmap_weights=use_mmap_weights, + use_mmap_weights_external=use_mmap_weights_external, + extra_flags=extra_flags, + min_optimize=min_optimize, + precompiling=precompiling, + preprocessing=preprocessing, + compiler=compiler, + ) + + device_definitions: list[str] = [] + device_include_dirs: list[str] = [] + device_cflags: list[str] = [] + device_ldflags: list[str] = [] + device_libraries_dirs: list[str] = [] + device_libraries: list[str] = [] + device_passthrough_args: list[str] = [] + + ( + device_definitions, + device_include_dirs, + device_cflags, + device_ldflags, + device_libraries_dirs, + device_libraries, + device_passthrough_args, + ) = get_cpp_torch_device_options( + device_type=device_type, + aot_mode=aot_mode, + compile_only=compile_only, + ) + _append_list(self._definitions, device_definitions) + _append_list(self._include_dirs, device_include_dirs) + _append_list(self._cflags, device_cflags) + _append_list(self._ldflags, device_ldflags) + _append_list(self._libraries_dirs, device_libraries_dirs) + _append_list(self._libraries, device_libraries) + _append_list(self._passthrough_args, device_passthrough_args) + self._finalize_options() + + def _finalize_options(self) -> None: + super()._finalize_options() + if config.is_fbcode(): + # Re-order library search paths in case there are lib conflicts + # that also live in the FBCode python lib dir. + _, python_lib_dirs = _get_python_related_args() + if len(python_lib_dirs) != 1: + raise AssertionError(f"Python lib dirs: {python_lib_dirs}") + if python_lib_dirs[0] in self._libraries_dirs: + self._libraries_dirs.remove(python_lib_dirs[0]) + self._libraries_dirs.append(python_lib_dirs[0]) + + +def get_name_and_dir_from_output_file_path( + file_path: str, +) -> tuple[str, str]: + """ + This function help prepare parameters to new cpp_builder. + Example: + input_code: /tmp/tmpof1n5g7t/5c/c5crkkcdvhdxpktrmjxbqkqyq5hmxpqsfza4pxcf3mwk42lphygc.cpp + name, dir = get_name_and_dir_from_output_file_path(input_code) + Run result: + name = c5crkkcdvhdxpktrmjxbqkqyq5hmxpqsfza4pxcf3mwk42lphygc + dir = /tmp/tmpof1n5g7t/5c/ + + put 'name' and 'dir' to CppBuilder's 'name' and 'output_dir'. + CppBuilder --> get_target_file_path will format output path according OS: + Linux: /tmp/tmppu87g3mm/zh/czhwiz4z7ca7ep3qkxenxerfjxy42kehw6h5cjk6ven4qu4hql4i.so + Windows: [Windows temp path]/tmppu87g3mm/zh/czhwiz4z7ca7ep3qkxenxerfjxy42kehw6h5cjk6ven4qu4hql4i.dll + """ + name_and_ext = os.path.basename(file_path) + name, _ext = os.path.splitext(name_and_ext) + dir = os.path.dirname(file_path) + + return name, dir + + +class CppBuilder: + """ + CppBuilder is a cpp jit builder, and it supports both Windows, Linux and MacOS. + Args: + name: + 1. Build target name, the final target file will append extension type automatically. + 2. Due to the CppBuilder is supports multiple OS, it will maintains ext for OS difference. + sources: + Source code file list to be built. + BuildOption: + Build options to the builder. + output_dir: + 1. The output_dir the target file will output to. + 2. The default value is empty string, and then the use current dir as output dir. + 3. Final target file: output_dir/name.ext + """ + + @staticmethod + def __get_python_module_flags() -> tuple[str, str]: + extension = ".pyd" if _IS_WINDOWS else ".so" + output_flags = "/Fe" if _IS_WINDOWS else "-o" + return extension, output_flags + + @staticmethod + def __get_object_flags() -> tuple[str, str]: + extension = ".obj" if _IS_WINDOWS else ".o" + output_flags = "/c /Fo" if _IS_WINDOWS else "-c -o" # codespell:ignore + return extension, output_flags + + @staticmethod + def __get_precompiled_header_flags() -> tuple[str, str]: + extension = ".pch" if _IS_WINDOWS or not is_gcc() else ".gch" + output_flags = "/Fp" if _IS_WINDOWS else "-o" + return extension, output_flags + + @staticmethod + def __get_preprocessor_output_flags() -> tuple[str, str]: + extension = ".i" + output_flags = "/EP /P" if _IS_WINDOWS else "-E -P -o" + return extension, output_flags + + def __init__( + self, + name: str, + sources: str | list[str], + BuildOption: BuildOptionsBase, + output_dir: str = "", + ) -> None: + self._compiler = "" + self._cflags_args = "" + self._definitions_args = "" + self._include_dirs_args = "" + self._ldflags_args = "" + self._libraries_dirs_args = "" + self._libraries_args = "" + self._passthrough_parameters_args = "" + + # When relative path is used, we need to maintain the source dir list. + self._orig_source_paths = [] + self._output_dir = "" + self._target_file = "" + + self._use_relative_path: bool = False + self._aot_mode: bool = False + + self._name = name + self._target_name = ( + config.aot_inductor.model_name_for_generated_files or "aoti_model" + ) + + # Code start here, initial self internal variables firstly. + self._build_option = BuildOption + self._compiler = BuildOption.get_compiler() + self._use_relative_path = BuildOption.get_use_relative_path() + self._aot_mode = BuildOption.get_aot_mode() + + self._output_dir = output_dir + + self._compile_only = BuildOption.get_compile_only() + self._precompiling = BuildOption.get_precompiling() + self._preprocessing = BuildOption.get_preprocessing() + # Only one of these options (if any) should be true at any given time. + if sum((self._compile_only, self._precompiling, self._preprocessing)) > 1: + raise AssertionError( + "at most one of compile_only, precompiling, preprocessing may be set" + ) + self._do_link = not ( + self._compile_only or self._precompiling or self._preprocessing + ) + + # MSVC produces two files when precompiling: the actual .pch file, as well as an + # object file which must be linked into the final library. This class assumes + # only one output file of note, so for now we'll error out here. + if _IS_WINDOWS and self._precompiling: + raise AssertionError("Cannot currently precompile headers on Windows!") + + if self._compile_only: + file_ext, output_flags = self.__get_object_flags() + elif self._precompiling: + file_ext, output_flags = self.__get_precompiled_header_flags() + elif self._preprocessing: + file_ext, output_flags = self.__get_preprocessor_output_flags() + else: + file_ext, output_flags = self.__get_python_module_flags() + self._target_file = os.path.join(self._output_dir, f"{self._name}{file_ext}") + + relative_target_file = ( + os.path.basename(self._target_file) + if self._use_relative_path + else self._target_file + ) + if _IS_WINDOWS: + if self._preprocessing: + # The target file name is automatically determined by MSVC. + self._output = output_flags + else: + self._output = f"{output_flags}{relative_target_file}" + else: + self._output = f"{output_flags} {relative_target_file}" + + if isinstance(sources, str): + sources = [sources] + + # Use relative paths only when requested (typically for remote builds) + if config.is_fbcode() and self._use_relative_path: + # Will create another temp directory for building, so do NOT use the + # absolute path. + self._orig_source_paths = list(sources) + sources = [os.path.basename(i) for i in sources] + + if self._precompiling: + if len(sources) != 1: + raise AssertionError( + f"expected exactly one source when precompiling, got {len(sources)}" + ) + # See above; we can currently assume this is not on MSVC. + self._sources_args = f"-x c++-header {sources[0]}" + if self._use_relative_path and _is_clang(BuildOption.get_compiler()): + # Store PCH paths relative to -isysroot so the .pch can + # be used from a different build directory. The matching + # -isysroot is injected by build_fbcode_re(). + self._cflags_args += " -relocatable-pch -Xclang -fno-pch-timestamp " + else: + self._sources_args = " ".join(sources) + + for cflag in BuildOption.get_cflags(): + if _IS_WINDOWS: + self._cflags_args += f"/{cflag} " + else: + self._cflags_args += f"-{cflag} " + + for definition in BuildOption.get_definitions(): + if _IS_WINDOWS: + self._definitions_args += f"/D {definition} " + else: + self._definitions_args += f"-D {definition} " + + if precompiled_header := BuildOption.precompiled_header: + if _IS_WINDOWS: + log.warning( + "Precompiled header support for MSVC is currently unavailable; ignoring %s", + precompiled_header, + ) + else: + self._include_dirs_args = f"-include {precompiled_header} " + if self._use_relative_path and _is_clang(BuildOption.get_compiler()): + # Skip clang's own PCH validation during consumption. + # _precompile_header() already handles cache invalidation + # via content hashing, and -fno-validate-pch allows the + # PCH to be used even when the original source file is at + # a different path (e.g. across Remote Execution workers). + self._cflags_args += " -Xclang -fno-validate-pch " + + for inc_dir in BuildOption.get_include_dirs(): + if _IS_WINDOWS: + self._include_dirs_args += f'/I "{inc_dir}" ' + else: + self._include_dirs_args += f"-I{shlex.quote(inc_dir)} " + + for ldflag in BuildOption.get_ldflags(): + if _IS_WINDOWS: + self._ldflags_args += f"/{ldflag} " + else: + self._ldflags_args += f"-{ldflag} " + + for lib_dir in BuildOption.get_libraries_dirs(): + if _IS_WINDOWS: + self._libraries_dirs_args += f'/LIBPATH:"{lib_dir}" ' + else: + self._libraries_dirs_args += f"-L{shlex.quote(lib_dir)} " + + for lib in BuildOption.get_libraries(): + if _IS_WINDOWS: + self._libraries_args += f'"{lib}.lib" ' + else: + self._libraries_args += f"-l{lib} " + + for passthrough_arg in self._stage_passthrough_paths( + BuildOption.get_passthrough_args() + ): + self._passthrough_parameters_args += f"{passthrough_arg} " + + def get_command_line(self) -> str: + def format_build_command( + compiler: str, + sources: str, + include_dirs_args: str, + definitions_args: str, + cflags_args: str, + ldflags_args: str, + libraries_args: str, + libraries_dirs_args: str, + passthrough_args: str, + output: str, + ) -> str: + if _IS_WINDOWS: + # https://learn.microsoft.com/en-us/cpp/build/walkthrough-compile-a-c-program-on-the-command-line?view=msvc-1704 + # https://stackoverflow.com/a/31566153 + cmd = ( + f"{compiler} {include_dirs_args} {definitions_args} {cflags_args} " + f"{sources} {passthrough_args} {output}" + ) + if self._do_link: + cmd += f" /LD /link {libraries_dirs_args} {libraries_args} {ldflags_args}" + cmd = normalize_path_separator(cmd) + else: + cmd = ( + f"{compiler} {sources} {definitions_args} {cflags_args} " + f"{include_dirs_args} {passthrough_args} {output}" + ) + if self._do_link: + cmd += f" {ldflags_args} {libraries_args} {libraries_dirs_args}" + return cmd + + command_line = format_build_command( + compiler=self._compiler, + sources=self._sources_args, + include_dirs_args=self._include_dirs_args, + definitions_args=self._definitions_args, + cflags_args=self._cflags_args, + ldflags_args=self._ldflags_args, + libraries_args=self._libraries_args, + libraries_dirs_args=self._libraries_dirs_args, + passthrough_args=self._passthrough_parameters_args, + output=self._output, + ) + return command_line + + def get_target_file_path(self) -> str: + return normalize_path_separator(self._target_file) + + def _stage_passthrough_paths(self, args: list[str]) -> list[str]: + """For fbcode remote builds, treat any absolute file path that appears + as a passthrough arg (e.g. precompiled .so kernels passed in via + ``extra_flags``) the same way as a source: stage the file into the + remote build sandbox and rewrite the command to reference it by + basename. Without this the linker is handed a path that only exists on + the submitting host and the remote build fails to find the file.""" + if not (config.is_fbcode() and self._use_relative_path): + return args + rewritten = [] + rpath_dirs: OrderedSet[str] = OrderedSet() + for arg in args: + tokens = shlex.split(arg) + new_tokens = [] + for tok in tokens: + if os.path.isabs(tok) and os.path.isfile(tok): + self._orig_source_paths.append(tok) + # Rewriting the absolute path to a basename makes the + # linker record a bare-basename DT_NEEDED entry, because + # the staged kernel .so files carry no DT_SONAME. That + # basename is unresolvable when the wrapper .so is later + # dlopen'd, so add rpath entries the runtime loader can + # search: $ORIGIN for a kernel .so co-staged next to the + # wrapper, and the kernel .so's original directory as a + # fallback when it is loaded from its cache location. + if self._do_link and tok.endswith(".so"): + rpath_dirs.add(os.path.dirname(tok)) + new_tokens.append(os.path.basename(tok)) + else: + new_tokens.append(tok) + rewritten.append(" ".join(shlex.quote(t) for t in new_tokens)) + if rpath_dirs: + rewritten.append("-Wl,-rpath," + shlex.quote("$ORIGIN")) + for rpath_dir in rpath_dirs: + rewritten.append(f"-Wl,-rpath,{shlex.quote(rpath_dir)}") + return rewritten + + def build_fbcode_re( + self, + ) -> None: + with dynamo_timed("compile_file"): + command = shlex.split(self.get_command_line()) + try: + output_path = self._target_file + # When we build remotely, we need to make sure to carefully copy any files + # that are required during the compilation process into our build directly. + # This is where all of the ATen/c10/Torch includes come from. + torch_includes_path = os.path.join(_TORCH_PATH, "include") + with tempfile.TemporaryDirectory() as tmp_dir: + # Copy everything to tmp compilation folder + shutil.copy(_LINKER_SCRIPT, os.path.join(tmp_dir, "script.ld")) + for src in self._orig_source_paths: + shutil.copy(src, os.path.join(tmp_dir, os.path.basename(src))) + dest_include_path = os.path.join(tmp_dir, "include") + shutil.copytree(torch_includes_path, dest_include_path) + + # Copy precompiled header (.h and .gch/.pch) into the + # build directory and rewrite the -include flag so the + # compiler can find it. + pch_header = self._build_option.precompiled_header + if pch_header and os.path.isfile(pch_header): + pch_ext = ".pch" if _IS_WINDOWS or not is_gcc() else ".gch" + pch_compiled = pch_header + pch_ext + pch_basename = os.path.basename(pch_header) + shutil.copy(pch_header, os.path.join(tmp_dir, pch_basename)) + if os.path.isfile(pch_compiled): + shutil.copy( + pch_compiled, + os.path.join(tmp_dir, pch_basename + pch_ext), + ) + command = [ + pch_basename if arg == pch_header else arg + for arg in command + ] + + # Relocatable PCH stores include paths relative to + # -isysroot. Set sysroot to the tmp build dir so + # paths resolve correctly in both precompilation and + # later kernel compilations that consume the PCH. + if self._precompiling or ( + pch_header and os.path.isfile(pch_header) + ): + command[1:1] = ["-isysroot", "."] + + # Run the build, raising RuntimeError on failure instead of + # SkipFrame so compilation errors propagate rather than + # silently falling back to eager execution. + tmp_output_path = _run_build_command( + command, + tmp_dir, + os.path.basename(output_path), + exception_class=RuntimeError, + ) + # Copy output from the build + if os.path.exists(output_path): + os.remove(output_path) + shutil.copy(tmp_output_path, output_path) + if output_path.endswith(".o"): + os.chmod(output_path, 0o644) + elif output_path.endswith(".so"): + os.chmod(output_path, 0o755) + except subprocess.CalledProcessError as e: + raise exc.CppCompileError(command, e.output.decode("utf-8")) from e + + def build(self) -> None: + """ + It is must need a temporary directory to store object files in Windows. + After build completed, delete the temporary directory to save disk space. + """ + if self._use_relative_path: + # remote build uses relative path + return self.build_fbcode_re() + _create_if_dir_not_exist(self._output_dir) + _build_tmp_dir = os.path.join( + self._output_dir, f"{self._name}_{_BUILD_TEMP_DIR}" + ) + _create_if_dir_not_exist(_build_tmp_dir) + + build_cmd = self.get_command_line() + run_compile_cmd(build_cmd, cwd=_build_tmp_dir) + _remove_dir(_build_tmp_dir) + + def save_compile_cmd_to_cmake( + self, + cmake_path: str, + device_type: str, + ) -> None: + """ + Save global cmake settings here, e.g. compiler options. + If targeting CUDA, also emit a custom function to embed CUDA kernels. + """ + + definitions = " ".join(self._build_option.get_definitions()) + target_library_type = ( + "STATIC" if not config.aot_inductor.dynamic_linkage else "SHARED" + ) + + contents = textwrap.dedent( + f""" + cmake_minimum_required(VERSION 3.27 FATAL_ERROR) + project({self._target_name} LANGUAGES CXX) + set(CMAKE_CXX_STANDARD 20) + + # Set a library target + add_library({self._target_name} {target_library_type}) + + """ + ) + + if config.aot_inductor.link_libtorch or config.test_configs.use_libtorch: + # When compile_standalone is True, the generated cpp project should + # not use Torch. But for unit testing purpose, we need to use Torch here. + contents += textwrap.dedent( + """ + # May need to point CMAKE_PREFIX_PATH to the right torch location + find_package(Torch REQUIRED) + + """ + ) + # flags and macros here are mostly CPU specific. Not emitting them for GPU models + # will make the generated CMake file more portable and won't really hurt performance. + # NOTE: standalone focuses on GPU now. For CPU, some of the flags and macros may + # be still needed. + contents += textwrap.dedent( + f""" + # Add macro definitions + target_compile_definitions({self._target_name} PRIVATE {definitions}) + + # Add compile flags + target_compile_options({self._target_name} PRIVATE {self._cflags_args}) + + # Backend-specific flags + target_compile_options({self._target_name} PRIVATE {self._passthrough_parameters_args} -c) + + """ + ) + else: + # When compile_standalone is True, use TorchStandalone instead of Torch + contents += textwrap.dedent( + f""" + find_package(TorchStandalone REQUIRED) + # Set up include directories to find headers at the correct paths + target_include_directories({self._target_name} PRIVATE ${{TorchStandalone_INCLUDE_DIRS}}) + target_include_directories({self._target_name} PRIVATE ${{TorchStandalone_INCLUDE_DIRS}}/standalone) + + """ + ) + + if device_type == "cuda" and torch.version.hip is None: + from torch._inductor.codegen.cuda import compile_utils + + cuda_arch = compile_utils._aoti_cuda_target_arch() + cuda_gencode_flags = "\n ".join( + f"-gencode {option}" + for option in compile_utils._cuda_multi_arch_gencode_options(cuda_arch) + ) + contents += textwrap.dedent( + f""" + enable_language(CUDA) + set(CMAKE_CUDA_STANDARD 17) + find_package(CUDAToolkit REQUIRED) + target_include_directories({self._target_name} PRIVATE ${{CUDAToolkit_INCLUDE_DIRS}}) + target_compile_definitions({self._target_name} PRIVATE USE_CUDA) + target_link_libraries({self._target_name} PRIVATE cuda CUDA::cudart_static) + + find_program(OBJCOPY_EXECUTABLE objcopy) + if(NOT OBJCOPY_EXECUTABLE) + message(FATAL_ERROR "objcopy not found. Cannot embed fatbin as object file") + endif() + + set(KERNEL_TARGETS "") + set(KERNEL_OBJECT_FILES "") + # Function to embed a single kernel + function(embed_gpu_kernel KERNEL_NAME PTX_FILE) + set(FATBIN_BASENAME ${{KERNEL_NAME}}.fatbin) + set(FATBIN_FILE ${{CMAKE_CURRENT_BINARY_DIR}}/${{FATBIN_BASENAME}}) + set(OBJECT_BASENAME ${{KERNEL_NAME}}.fatbin.o) + set(OBJECT_FILE ${{CMAKE_CURRENT_BINARY_DIR}}/${{OBJECT_BASENAME}}) + + # --- Define UNIQUE C symbol names --- + set(SYMBOL_START __${{KERNEL_NAME}}_start) + set(SYMBOL_END __${{KERNEL_NAME}}_end) + set(SYMBOL_SIZE __${{KERNEL_NAME}}_size) + string(REGEX REPLACE "[^a-zA-Z0-9]" "_" MANGLED_BASENAME ${{FATBIN_FILE}}) + set(OBJCOPY_START_SYM _binary_${{MANGLED_BASENAME}}_start) + set(OBJCOPY_END_SYM _binary_${{MANGLED_BASENAME}}_end) + set(OBJCOPY_SIZE_SYM _binary_${{MANGLED_BASENAME}}_size) + + # --- PTX to FATBIN Command & Target --- + add_custom_command( + OUTPUT ${{FATBIN_FILE}} + COMMAND ${{CUDAToolkit_NVCC_EXECUTABLE}} --fatbin ${{PTX_FILE}} -o ${{FATBIN_FILE}} ${{NVCC_GENCODE_FLAGS}} + {cuda_gencode_flags} + DEPENDS ${{PTX_FILE}} + ) + + # --- FATBIN to Object File (.o) Command --- + add_custom_command( + OUTPUT ${{OBJECT_FILE}} + COMMAND ${{CMAKE_LINKER}} -r -b binary -z noexecstack -o ${{OBJECT_FILE}} ${{FATBIN_FILE}} + COMMAND ${{OBJCOPY_EXECUTABLE}} --rename-section .data=.rodata,alloc,load,readonly,data,contents + ${{OBJECT_FILE}} + COMMAND ${{OBJCOPY_EXECUTABLE}} + --redefine-sym ${{OBJCOPY_START_SYM}}=${{SYMBOL_START}} + --redefine-sym ${{OBJCOPY_END_SYM}}=${{SYMBOL_END}} + --redefine-sym ${{OBJCOPY_SIZE_SYM}}=${{SYMBOL_SIZE}} + ${{OBJECT_FILE}} + DEPENDS ${{FATBIN_FILE}} + ) + add_custom_target(build_kernel_object_${{KERNEL_NAME}} DEPENDS ${{OBJECT_FILE}}) + + # --- Add to a list for linking later --- + set(KERNEL_TARGETS ${{KERNEL_TARGETS}} build_kernel_object_${{KERNEL_NAME}} PARENT_SCOPE) + set(KERNEL_OBJECT_FILES ${{KERNEL_OBJECT_FILES}} ${{OBJECT_FILE}} PARENT_SCOPE) + endfunction() + + """ + ) + elif device_type == "xpu": + contents += textwrap.dedent( + """ + find_program(OBJCOPY_EXECUTABLE objcopy) + if(NOT OBJCOPY_EXECUTABLE) + message(FATAL_ERROR "objcopy not found. Cannot embed spv as object file") + endif() + + set(KERNEL_TARGETS "") + set(KERNEL_OBJECT_FILES "") + # Function to embed a single kernel + function(embed_gpu_kernel KERNEL_NAME SPV_FILE) + set(OBJECT_BASENAME ${KERNEL_NAME}.spv.o) + set(OBJECT_FILE ${CMAKE_CURRENT_BINARY_DIR}/${OBJECT_BASENAME}) + + # --- Define UNIQUE C symbol names --- + set(SYMBOL_START __${KERNEL_NAME}_start) + set(SYMBOL_END __${KERNEL_NAME}_end) + set(SYMBOL_SIZE __${KERNEL_NAME}_size) + string(REGEX REPLACE "[^a-zA-Z0-9]" "_" MANGLED_BASENAME ${SPV_FILE}) + set(OBJCOPY_START_SYM _binary_${MANGLED_BASENAME}_start) + set(OBJCOPY_END_SYM _binary_${MANGLED_BASENAME}_end) + set(OBJCOPY_SIZE_SYM _binary_${MANGLED_BASENAME}_size) + + # --- SPV_FILE to Object File (.o) Command --- + add_custom_command( + OUTPUT ${OBJECT_FILE} + COMMAND ${CMAKE_LINKER} -r -b binary -z noexecstack -o ${OBJECT_FILE} ${SPV_FILE} + COMMAND ${OBJCOPY_EXECUTABLE} --rename-section .data=.rodata,alloc,load,readonly,data,contents + ${OBJECT_FILE} + COMMAND ${OBJCOPY_EXECUTABLE} + --redefine-sym ${OBJCOPY_START_SYM}=${SYMBOL_START} + --redefine-sym ${OBJCOPY_END_SYM}=${SYMBOL_END} + --redefine-sym ${OBJCOPY_SIZE_SYM}=${SYMBOL_SIZE} + ${OBJECT_FILE} + DEPENDS ${SPV_FILE} + ) + add_custom_target(build_kernel_object_${KERNEL_NAME} DEPENDS ${OBJECT_FILE}) + + # --- Add to a list for linking later --- + set(KERNEL_TARGETS ${KERNEL_TARGETS} build_kernel_object_${KERNEL_NAME} PARENT_SCOPE) + set(KERNEL_OBJECT_FILES ${KERNEL_OBJECT_FILES} ${OBJECT_FILE} PARENT_SCOPE) + endfunction() + + """ + ) + + with open(cmake_path, "w") as f: + f.write(contents) + + def save_src_to_cmake(self, cmake_path: str, src_path: str) -> None: + # Remove the directory part of file_path + src_path = "${CMAKE_CURRENT_SOURCE_DIR}/" + Path(src_path).name + with open(cmake_path, "a") as f: + f.write(f"target_sources({self._target_name} PRIVATE {src_path})\n") + + def save_kernel_asm_to_cmake(self, cmake_path: str, asm_files: list[str]) -> None: + # TODO: make this work beyond CUDA + with open(cmake_path, "a") as f: + for asm_file in asm_files: + kernel_name = Path(asm_file).name.split(".")[0] + asm_file = f"${{CMAKE_CURRENT_SOURCE_DIR}}/{Path(asm_file).name}" + contents = textwrap.dedent( + f""" + embed_gpu_kernel({kernel_name} {asm_file}) + """ + ) + f.write(contents) + if asm_files: + f.write(f"add_dependencies({self._target_name} ${{KERNEL_TARGETS}})\n") + f.write( + f"target_link_libraries({self._target_name} PRIVATE ${{KERNEL_OBJECT_FILES}})\n" + ) + + def save_link_cmd_to_cmake(self, cmake_path: str) -> None: + lflags = " ".join(self._build_option.get_ldflags()) + libs = " ".join(self._build_option.get_libraries()) + contents = textwrap.dedent( + f""" + # Add linker flags + target_link_options({self._target_name} PRIVATE {lflags}) + + # Add libraries + target_link_libraries({self._target_name} PRIVATE {libs}) + """ + ) + + if not os.path.exists(cmake_path): + raise AssertionError( + f"save_link_cmd_to_cmakefile expects {cmake_path} to already exist" + ) + with open(cmake_path, "a") as f: + f.write(contents) + + +def run_asm_build_object(src: str, target: str, cwd: str) -> None: + def get_asm_compiler() -> str: + if _IS_WINDOWS: + ASM_CC = "ml64" + else: + ASM_CC = get_cpp_compiler() + # Intel compiler is not support to compile asm, switch to gcc. + if _is_intel_compiler(ASM_CC): + ASM_CC = "gcc" + return ASM_CC + + def get_command_line(asm_cc: str, src: str, target: str) -> str: + if _IS_WINDOWS: + # Format reference: + # https://learn.microsoft.com/en-us/cpp/assembler/masm/ml-and-ml64-command-line-reference?view=msvc-170 + cmd = f"{asm_cc} {src} /c /Fo {target}" # codespell:ignore /Fo + else: + cmd = f"{asm_cc} -c {src} -o {target}" + + return cmd + + asm_cc = get_asm_compiler() + cmd = get_command_line( + asm_cc=asm_cc, + src=normalize_path_separator(src), + target=normalize_path_separator(target), + ) + run_compile_cmd(cmd, cwd=normalize_path_separator(cwd)) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/cpu_vec_isa.py b/.venv/lib/python3.12/site-packages/torch/_inductor/cpu_vec_isa.py new file mode 100644 index 0000000000000000000000000000000000000000..c847b532bdf4c35d866fada28a92bac9627b34f8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/cpu_vec_isa.py @@ -0,0 +1,690 @@ +# mypy: allow-untyped-defs +import dataclasses +import functools +import os +import platform +import re +import subprocess +import sys +import warnings +from collections.abc import Callable +from typing import Any + +import torch +from torch._inductor import config +from torch._inductor.utils import python_subprocess_env + + +_IS_WINDOWS = sys.platform == "win32" + + +def _get_isa_dry_compile_fingerprint(isa_flags: str) -> str: + # ISA dry compile will cost about 1 sec time each startup time. + # Please check the issue: https://github.com/pytorch/pytorch/issues/100378 + # Actually, dry compile is checking compile capability for ISA. + # We just record the compiler version, isa options and pytorch version info, + # and generated them to output binary hash path. + # It would optimize and skip compile existing binary. + from torch._inductor.cpp_builder import get_compiler_version_info, get_cpp_compiler + + compiler_info = get_compiler_version_info(get_cpp_compiler()) + torch_version = torch.__version__ + fingerprint = f"{compiler_info}={isa_flags}={torch_version}" + return fingerprint + + +class VecISA: + """Describes a CPU SIMD ISA (AVX2, AVX512, NEON, SVE, VSX, ZVECTOR) for + inductor's CPU vectorization. + + Carries the bit width, ``CPU_CAPABILITY_*`` build macros, compiler arch + flags, and the per-dtype lane count used by the codegen. Subclasses (one + per ISA) override the class-level fields; instances are hashable by their + string representation and usable as a dict key. ``bool(vec_isa)`` runs the + dry-compile + dlopen probe described in + `Note [Checking for Vectorized Support in Inductor]`_ to verify the host + toolchain actually produces a working ``.so`` for this ISA. + """ + + _bit_width: int + _macro: list[str] + _arch_flags: str + _dtype_nelements: dict[torch.dtype, int] + + # Note [Checking for Vectorized Support in Inductor] + # TorchInductor CPU vectorization reuses PyTorch vectorization utility functions + # Hence, TorchInductor would depend on Sleef* to accelerate mathematical functions + # like exp, pow, sin, cos and etc. + # But PyTorch and TorchInductor might use different compilers to build code. If + # PyTorch uses gcc-7/g++-7 to build the release package, the libtorch_cpu.so + # will not expose the Sleef* AVX512 symbols since gcc-7/g++-7 cannot pass + # avx512 check in CMake - FindAVX.cmake. But TorchInductor install the latest + # gcc/g++ compiler by default while it could support the AVX512 compilation. + # Therefore, there would be a conflict sleef version between PyTorch and + # TorchInductor. Hence, we dry-compile the following code to check whether current + # HW platform and PyTorch both could support AVX512 or AVX2. And suppose ARM + # also needs the logic + # In fbcode however, we are using the same compiler for pytorch and for inductor codegen, + # making the runtime check unnecessary. + _avx_code = """ +#if defined(CPU_CAPABILITY_AVX512) || defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_ZVECTOR) || defined(CPU_CAPABILITY_NEON) || defined(CPU_CAPABILITY_VSX) || defined(CPU_CAPABILITY_SVE) +#include +#include +#endif + +alignas(64) float in_out_ptr0[16] = {0.0}; + +extern "C" void __avx_chk_kernel() { + auto tmp0 = at::vec::Vectorized(1); + auto tmp1 = tmp0.exp(); + tmp1.store(in_out_ptr0); +} +""" + + # Skip the slow `import torch` (which has hung under load in CI) on Linux + # only: the parent puts torch's lib dir on LD_LIBRARY_PATH so the linker + # resolves libtorch_cpu for the test .so on its own. macOS can't do this -- + # SIP strips DYLD_LIBRARY_PATH from the child -- so it falls back to import. + # Some wheels only resolve their native deps once `import torch` has run. + # ROCm wheels bundle ROCm libs under unversioned names but keep some + # DT_NEEDED refs on the versioned soname (e.g. libamd_comgr.so.3), which + # only resolves against the copy torch has already loaded; TheRock-based + # wheels preload ROCm libs from separate rocm-sdk packages with no rpath. + # So a cold dlopen can fail even though the ISA is fine; retry after + # importing torch before giving up (#189194). + # TODO: extend the no-import path to Windows once its CI build is green + # enough to validate it. + _avx_py_load = """ +import sys +if sys.platform != "linux": + import torch # noqa: F401 +from ctypes import cdll +try: + cdll.LoadLibrary("__lib_path__") +except OSError: + if sys.platform != "linux": + raise + import torch # noqa: F401 + cdll.LoadLibrary("__lib_path__") +""" + + def bit_width(self) -> int: + return self._bit_width + + def nelements(self, dtype: torch.dtype = torch.float) -> int: + return self._dtype_nelements[dtype] + + def build_macro(self) -> list[str]: + return self._macro + + def build_arch_flags(self) -> str: + return self._arch_flags + + def __hash__(self) -> int: + return hash(str(self)) + + @staticmethod + def _build_probe_env() -> dict[str, str]: + """Construct the child env for the dlopen probe. + + Make libtorch_cpu (and other torch shlibs) findable by the Linux + dynamic linker via LD_LIBRARY_PATH so the probe child does not need to + ``import torch`` to bring them into its address space. Prepend rather + than append so a successful probe is guaranteed to bind against the + torch we are currently running, not an older install on the user's + loader path. macOS and Windows do not use this fast path; they + ``import torch`` in the child instead (see ``_avx_py_load``). + """ + lib_dir = os.path.join(os.path.dirname(torch.__file__), "lib") + env = python_subprocess_env() + existing = env.get("LD_LIBRARY_PATH", "") + env["LD_LIBRARY_PATH"] = ( + os.pathsep.join([lib_dir, existing]) if existing else lib_dir + ) + return env + + def _probe_load(self, output_path: str) -> bool: + """Spawn a child Python that ``dlopen``s ``output_path``. + + Bound the dlopen probe so a stuck child cannot hang the parent for + the whole 30-minute outer timeout (observed in CI). ``subprocess.run`` + kills the child on ``TimeoutExpired`` (``check_call`` leaks it). + Returns ``False`` on timeout or load failure, ``True`` on success. + """ + probe_cmd = [ + sys.executable, + "-c", + VecISA._avx_py_load.replace("__lib_path__", output_path), + ] + try: + subprocess.run( + probe_cmd, + stderr=subprocess.DEVNULL, + env=self._build_probe_env(), + timeout=60, + check=True, + ) + except subprocess.TimeoutExpired: + warnings.warn( + f"VecISA dlopen probe for {self} hung after 60s", + stacklevel=2, + ) + return False + except subprocess.CalledProcessError: + return False + return True + + def check_build(self, code: str) -> bool: + """Dry-compile ``code`` with this ISA's flags and verify the resulting + shared library can be loaded. + + Compiles into the inductor codecache, then spawns a short-lived + subprocess to ``dlopen`` the ``.so``. Returns ``True`` if both build + and load succeed, ``False`` on compile error, load failure, or dlopen + probe timeout. + """ + from torch._inductor.codecache import get_lock_dir, LOCK_TIMEOUT, write + from torch._inductor.cpp_builder import ( + CppBuilder, + CppTorchOptions, + normalize_path_separator, + ) + + key, input_path = write( + code, + "cpp", + extra=_get_isa_dry_compile_fingerprint(self.build_arch_flags()), + ) + from torch.utils._filelock import FileLock + + lock_dir = get_lock_dir() + lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT) + with lock: + output_dir = os.path.dirname(input_path) + buid_options = CppTorchOptions(vec_isa=self, warning_all=False) + x86_isa_help_builder = CppBuilder( + key, + [input_path], + buid_options, + output_dir, + ) + try: + # Check if the output file exist, and compile when not. + output_path = normalize_path_separator( + x86_isa_help_builder.get_target_file_path() + ) + if not os.path.isfile(output_path): + x86_isa_help_builder.build() + except Exception: + return False + + load_ok_marker = output_path + ".load_ok" + if os.path.isfile(load_ok_marker): + return True + + load_ok = self._probe_load(output_path) + if load_ok: + with open(load_ok_marker, "w") as f: + f.write("") + return load_ok + + def __bool__(self) -> bool: + return self.__bool__impl(config.cpp.vec_isa_ok) + + @functools.cache # noqa: B019 + def __bool__impl(self, vec_isa_ok) -> bool: + if vec_isa_ok is not None: + return vec_isa_ok + + if config.is_fbcode(): + return True + + return self.check_build(VecISA._avx_code) + + +@dataclasses.dataclass +class VecNEON(VecISA): + _bit_width = 128 # This is required to leverage the compute implemented in aten/src/ATen/cpu/vec/vec128/vec128_float_neon.h + _macro = ["CPU_CAPABILITY_NEON", "AT_BUILD_ARM_VEC256_WITH_SLEEF"] + _arch_flags = "" # Unused + _dtype_nelements = {torch.float: 4, torch.bfloat16: 8, torch.float16: 8} + + def __str__(self) -> str: + if config.is_fbcode(): + return "neon" + return "asimd" # detects the presence of advanced SIMD on armv8-a kernels + + __hash__: Callable[[VecISA], Any] = VecISA.__hash__ # type: ignore[assignment] + + +@dataclasses.dataclass +class VecSVE(VecISA): + _bit_width: int = 256 + _armv9a_supported: bool | None = dataclasses.field( + default=None, init=False, compare=False + ) + + def __post_init__(self) -> None: + if self._bit_width not in (128, 256): + raise AssertionError(f"unsupported SVE bit width: {self._bit_width}") + nelements = self._bit_width // 32 + self._macro = [ + "CPU_CAPABILITY_SVE", + f"CPU_CAPABILITY_SVE{self._bit_width}", + "AT_BUILD_ARM_VEC256_WITH_SLEEF", + "__ARM_FEATURE_BF16", + ] + self._arch_flags = ( + f"-march=armv8-a+sve+bf16 -msve-vector-bits={self._bit_width}" + ) + self._armv9a_arch_flags = ( + "-march=armv9-a+sve2+fp16fml+sha3+bf16+i8mm " + f"-msve-vector-bits={self._bit_width}" + ) + self._dtype_nelements = { + torch.float: nelements, + torch.bfloat16: nelements * 2, + torch.float16: nelements * 2, + } + + def __str__(self) -> str: + if config.is_fbcode(): + return "neon" + return "asimd" + + def _has_armv9a(self) -> bool: + if self._armv9a_supported is None: + try: + self._armv9a_supported = bool( + torch.cpu.get_capabilities().get("sve2", False) + ) + except Exception: + self._armv9a_supported = False + return self._armv9a_supported + + def build_arch_flags(self) -> str: + if self._has_armv9a(): + return self._armv9a_arch_flags + return self._arch_flags + + __hash__: Callable[[VecISA], Any] = VecISA.__hash__ # type: ignore[assignment] + + +@dataclasses.dataclass +class VecAVX512(VecISA): + _bit_width = 512 + _macro = ["CPU_CAPABILITY_AVX512"] + _arch_flags = ( + "-mavx512f -mavx512dq -mavx512vl -mavx512bw -mfma" + if not _IS_WINDOWS + else "/arch:AVX512" + ) # TODO: use cflags + _dtype_nelements = {torch.float: 16, torch.bfloat16: 32, torch.float16: 32} + _is_avx512_bf16_supported = False + + def __str__(self) -> str: + return "avx512" + + __hash__: Callable[[VecISA], Any] = VecISA.__hash__ # type: ignore[assignment] + + _avx512_bf16_code = """ +#include +#include + +extern "C" __m512bh __avx512_bf16_chk_kernel(__m512 a, __m512 b) { + return _mm512_cvtne2ps_pbh(a, b); +} +""" + + @functools.cache # noqa: B019 + # pyrefly: ignore [bad-override] + def __bool__(self) -> bool: + if super().__bool__(): + if config.is_fbcode(): + return False + # check avx512_bf16 + if torch.cpu._is_avx512_bf16_supported() and not _IS_WINDOWS: + # save _arch_flags + base_flags = self._arch_flags + # temporarily change _arch_flags for avx512_bf16 check_build + self._arch_flags += " -mavx512bf16" + if self.check_build(self._avx512_bf16_code): + self._is_avx512_bf16_supported = True + # restore _arch_flags + self._arch_flags = base_flags + + return True + return False + + @functools.lru_cache(None) # noqa: B019 + def is_avx512_bf16_supported(self) -> bool: + return self._is_avx512_bf16_supported + + def build_arch_flags(self) -> str: + if self._is_avx512_bf16_supported: + return self._arch_flags + " -mavx512bf16" + else: + return self._arch_flags + + +@dataclasses.dataclass +class VecAVX512VNNI(VecAVX512): + _bit_width = 512 + _arch_flags = VecAVX512._arch_flags + " -mavx512vnni -mavx512vl" + _dtype_nelements = { + torch.float: 16, + torch.bfloat16: 32, + torch.float16: 32, + torch.int8: 64, + torch.uint8: 64, + } + + def __str__(self) -> str: + return super().__str__() + " avx512_vnni" + + __hash__: Callable[[VecISA], Any] = VecISA.__hash__ # type: ignore[assignment] + + _avx512_vnni_code = """ +#include +#include + +extern "C" __m256i __avx512_vnni_chk_kernel_1(__m256i src, __m256i a, __m256i b) { + return _mm256_dpbusd_epi32(src, a, b); +} + +extern "C" __m512i __avx512_vnni_chk_kernel_2(__m512i src, __m512i a, __m512i b) { + return _mm512_dpbusd_epi32(src, a, b); +} +""" + + @functools.cache # noqa: B019 + def __bool__(self) -> bool: + if super().__bool__(): + if config.is_fbcode(): + return False + if ( + torch.cpu._is_vnni_supported() + and not _IS_WINDOWS + and self.check_build(self._avx512_vnni_code) + ): + return True + return False + + def build_arch_flags(self) -> str: + return self._arch_flags + + +@dataclasses.dataclass +class VecAMX(VecAVX512VNNI): + _arch_flags = VecAVX512VNNI._arch_flags + " -mamx-tile -mamx-bf16 -mamx-int8" + # check amx_fp16 separately since it is not always supported when amx is supported + # amx_fp16 intrinsic compilation need gcc >=13 on platforms which support amx_fp16 + _is_amx_fp16_supported = False + + def __str__(self) -> str: + return super().__str__() + " amx_tile" + + __hash__: Callable[[VecISA], Any] = VecISA.__hash__ + + _amx_code = """ +#include +#include + +struct amx_tilecfg { + uint8_t palette_id; + uint8_t start_row; + uint8_t reserved_0[14]; + uint16_t colsb[16]; + uint8_t rows[16]; +}; + +extern "C" void __amx_chk_kernel() { + amx_tilecfg cfg = {0}; + _tile_loadconfig(&cfg); + _tile_zero(0); + _tile_dpbf16ps(0, 1, 2); + _tile_dpbusd(0, 1, 2); +} +""" + + _amx_fp16_code = _amx_code.replace("_tile_dpbf16ps", "_tile_dpfp16ps") + + @functools.cache # noqa: B019 + def __bool__(self) -> bool: + if super().__bool__(): + if config.is_fbcode(): + return False + if self.check_build(VecAMX._amx_code) and torch.cpu._init_amx(): + # check amx-fp16 as well when check amx + if torch.cpu._is_amx_fp16_supported(): + # save _arch_flags + base_flags = self._arch_flags + # temporarily change _arch_flags for amx-fp16 check_build + self._arch_flags += " -mamx-fp16" + if self.check_build(VecAMX._amx_fp16_code): + self._is_amx_fp16_supported = True + # restore _arch_flags + self._arch_flags = base_flags + + return True + return False + + @functools.lru_cache(None) # noqa: B019 + def is_amx_fp16_supported(self) -> bool: + return self._is_amx_fp16_supported + + def build_arch_flags(self) -> str: + extra_flags = "" + if self._is_avx512_bf16_supported: + # avx512_bf16 is not among the base flags, so we need to check and add it here + # And we need this flag in the WOQ case for dequantization + extra_flags += " -mavx512bf16" + if self._is_amx_fp16_supported: + extra_flags += " -mamx-fp16" + return self._arch_flags + extra_flags + + +@dataclasses.dataclass +class VecAVX2(VecISA): + _bit_width = 256 + _macro = ["CPU_CAPABILITY_AVX2"] + _arch_flags = ( + "-mavx2 -mfma -mf16c" if not _IS_WINDOWS else "/arch:AVX2" + ) # TODO: use cflags + _dtype_nelements = {torch.float: 8, torch.bfloat16: 16, torch.float16: 16} + + def __str__(self) -> str: + return "avx2" + + __hash__: Callable[[VecISA], Any] = VecISA.__hash__ # type: ignore[assignment] + + +@dataclasses.dataclass +class VecZVECTOR(VecISA): + _bit_width = 256 + _macro = [ + "CPU_CAPABILITY_ZVECTOR", + "CPU_CAPABILITY=ZVECTOR", + "HAVE_ZVECTOR_CPU_DEFINITION", + ] + _arch_flags = "-mvx -mzvector" + _dtype_nelements = {torch.float: 8, torch.bfloat16: 16, torch.float16: 16} + + def __str__(self) -> str: + return "zvector" + + __hash__: Callable[[VecISA], Any] = VecISA.__hash__ # type: ignore[assignment] + + +@dataclasses.dataclass +class VecVSX(VecISA): + _bit_width = 256 # VSX simd supports 128 bit_width, but aten is emulating it as 256 + _macro = ["CPU_CAPABILITY_VSX"] + _arch_flags = "-mvsx" + _dtype_nelements = {torch.float: 8, torch.bfloat16: 16, torch.float16: 16} + + def __str__(self) -> str: + return "vsx" + + __hash__: Callable[[VecISA], Any] = VecISA.__hash__ # type: ignore[assignment] + + +class InvalidVecISA(VecISA): + _bit_width = 0 + _macro = [""] + _arch_flags = "" + _dtype_nelements = {} + + def __str__(self) -> str: + return "INVALID_VEC_ISA" + + def __bool__(self) -> bool: # type: ignore[override] + return False + + __hash__: Callable[[VecISA], Any] = VecISA.__hash__ # type: ignore[assignment] + + +def x86_isa_checker() -> list[str]: + supported_isa: list[str] = [] + + def _check_and_append_supported_isa( + dest: list[str], isa_supported: bool, isa_name: str + ) -> None: + if isa_supported: + dest.append(isa_name) + + Arch = platform.machine() + """ + Arch value is x86_64 on Linux, and the value is AMD64 on Windows. + """ + if Arch != "x86_64" and Arch != "AMD64": + return supported_isa + + avx2 = torch.cpu._is_avx2_supported() + avx512 = torch.cpu._is_avx512_supported() + avx512_vnni = avx512 and torch.cpu._is_vnni_supported() + amx_tile = torch.cpu._is_amx_tile_supported() + + _check_and_append_supported_isa(supported_isa, avx2, "avx2") + _check_and_append_supported_isa(supported_isa, avx512, "avx512") + _check_and_append_supported_isa(supported_isa, avx512_vnni, "avx512_vnni") + _check_and_append_supported_isa(supported_isa, amx_tile, "amx_tile") + + return supported_isa + + +invalid_vec_isa = InvalidVecISA() +supported_vec_isa_list = [ + VecAMX(), + VecAVX512VNNI(), + VecAVX512(), + VecAVX2(), + VecNEON(), + VecSVE(256), +] + + +def get_isa_from_cpu_capability( + capability: str | None, + vec_isa_list: list[VecISA], + invalid_vec_isa: InvalidVecISA, +): + # AMX setting is not supported in eager + # VecAMX will be prioritized for selection when setting ATEN_CPU_CAPABILITY to avx512 + # TODO add sve256 support + capability_to_isa_str = { + "default": "INVALID_VEC_ISA", + "zvector": "zvector", + "vsx": "vsx", + "avx2": "avx2", + "avx512": "avx512", + } + if capability in capability_to_isa_str: + # pyrefly: ignore [bad-index, index-error] + isa_str = capability_to_isa_str[capability] + if isa_str == "INVALID_VEC_ISA": + return invalid_vec_isa + for vec_isa in vec_isa_list: + if isa_str in str(vec_isa): + return vec_isa + + if capability: + warnings.warn(f"ignoring invalid value for ATEN_CPU_CAPABILITY {capability}") + + return vec_isa_list[0] + + +# Cache the cpuinfo to avoid I/O overhead. Meanwhile, the cpuinfo content +# might have too much redundant content that is useless for ISA check. Hence, +# we only cache some key isa information. +@functools.cache +def valid_vec_isa_list() -> list[VecISA]: + isa_list: list[VecISA] = [] + if sys.platform == "darwin" and platform.processor() == "arm": + isa_list.append(VecNEON()) + + if sys.platform not in ["linux", "win32"]: + return isa_list + + arch = platform.machine() + if arch == "s390x": + with open("/proc/cpuinfo") as _cpu_info: + while True: + line = _cpu_info.readline() + if not line: + break + # process line + featuresmatch = re.match(r"^features\s*:\s*(.*)$", line) + if featuresmatch: + for group in featuresmatch.groups(): + if re.search(r"[\^ ]+vxe[\$ ]+", group): + isa_list.append(VecZVECTOR()) + break + elif arch == "ppc64le": + isa_list.append(VecVSX()) + elif arch == "aarch64": + caps = torch.cpu.get_capabilities() + if (caps.get("sve2", False) or caps.get("sve", False)) and caps.get( + "bf16", False + ): + if caps.get("sve_max_length") == 128: + isa_list.append(VecSVE(128)) + else: + isa_list.append(VecSVE(256)) + else: + isa_list.append(VecNEON()) + + elif arch in ["x86_64", "AMD64"]: + """ + arch value is x86_64 on Linux, and the value is AMD64 on Windows. + """ + _cpu_supported_x86_isa = x86_isa_checker() + isa_list.extend( + isa + for isa in supported_vec_isa_list + if all(flag in _cpu_supported_x86_isa for flag in str(isa).split()) and isa + ) + + return isa_list + + +def pick_vec_isa() -> VecISA: + if config.is_fbcode() and (platform.machine() in ["x86_64", "AMD64"]): + return VecAVX2() + + _valid_vec_isa_list: list[VecISA] = valid_vec_isa_list() + if not _valid_vec_isa_list: + return invalid_vec_isa + + # If the simdlen is None, set simdlen based on the environment ATEN_CPU_CAPABILITY + # to control CPU vec ISA + if config.cpp.simdlen is None: + return get_isa_from_cpu_capability( + os.getenv("ATEN_CPU_CAPABILITY"), _valid_vec_isa_list, invalid_vec_isa + ) + + for isa in _valid_vec_isa_list: + if config.cpp.simdlen == isa.bit_width(): + return isa + + return invalid_vec_isa diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/cudagraph_trees.py b/.venv/lib/python3.12/site-packages/torch/_inductor/cudagraph_trees.py new file mode 100644 index 0000000000000000000000000000000000000000..61d5daade5ef4981d197983448bfa92555c9c286 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/cudagraph_trees.py @@ -0,0 +1,3229 @@ +""" +CUDA graph trees are a safety abstraction over CUDAGraphs, similar to make_graph_callables, +which share the same memory pool. Sharing a memory pool is an extremely +important optimization when chaining multiple CUDA graphs together, as it +prevents you from needing to copy intermediate tensors from one graph to the +next, and reduces overall memory usage by allowing dead memory from the first +pool to be reused in the second. + +The standard graph/make_graph_callables support sharing memory pool, but +with a lot of caveats. CUDA graph trees remove these restrictions: + +* Previously, if you recorded graphs A, B, you had to replay A, B in that + order. With CUDA graph trees, after replaying A, you can change your + mind and record/replay a different graph B'; we will support efficient + execution of both A, B and A, B', using only max(mem(A, B), mem(A, B')). In + other words: we support arbitrary trees of CUDA graph operations, not just + sequences (this is why this feature is called CUDA graph trees.) + +* Previously, if you executed graph A, some non-CUDA graph code, and then + graph B, after executing graph B, it was not safe to retain any references + to intermediates produced by A. With CUDA graph trees, we track if any +outputs of graph A are still live by the time graph B is run, and make + sure graph B doesn't clobber there memory when reusing the CUDA graphs + pool. You'll get a separate recording of B depending on what tensors + stay live or dead. + +CUDA graph trees are flexible enough to be used in Dynamo across graph breaks, +which is their primary use case. + +The ability to switch from replay to record is fairly nontrivial: remember that +when you replay a CUDA graph, you only replay CUDA operations; no CPU side state +is updated. In particular, the CPU-side book-keeping for the allocator is not +reconstructed. However, to record a new child CUDA graph, we must restore this +book-keeping. This is what checkpoint pool state is used for. +""" + +from __future__ import annotations + +import contextlib +import dataclasses +import functools +import gc +import itertools +import logging +import operator +import sys +import threading +import traceback +import warnings +import weakref +from collections import defaultdict +from contextlib import AbstractContextManager +from enum import auto, Enum +from typing import Any, cast, TYPE_CHECKING, TypeVar + +import torch.fx +from torch import Tensor +from torch._custom_class_base import CustomClassBase +from torch._dynamo.callback import CallbackTrigger +from torch._dynamo.graph_bytecode_inputs import ( + CURRENT_STREAM_INDEX, + set_external_object_by_index, +) +from torch._dynamo.mutation_guard import GenerationTracker +from torch._dynamo.utils import counters, dynamo_timed, preserve_rng_state +from torch._higher_order_ops.cudagraph_conditional_nodes import ( + ControlFlowOpWarmupDispatchMode, + CUDAGraphCaptureControlFlowOpDispatchMode, +) +from torch._inductor.compile_fx import ( + align_inputs_from_check_idxs, + copy_misaligned_inputs, + copy_strided_storage_, + get_expanded_dims, + get_input_idxs_to_check, + index_expanded_dims, + remove_unaligned_input_idxs, + static_input, +) +from torch._inductor.cudagraph_utils import ( + check_for_mutation, + CheckInvariantStatus, + collect_cuda_data_ptrs, + FunctionID, + log_cudagraph_skip_and_bump_counter, + log_data_ptr_mismatch, + maybe_warning_due_to_dynamic_shape, + ModelType, + OutputType, + PlaceholderInfo, + WrappedFunction, +) +from torch._library.opaque_object import is_custom_class_obj +from torch.multiprocessing.reductions import StorageWeakRef +from torch.storage import UntypedStorage +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet +from torch.utils.weak import TensorWeakRef + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, Iterable, Iterator, Sequence + + from torch._guards import CompileId + from torch._inductor.utils import InputType + from torch.cuda import _POOL_HANDLE + from torch.types import _bool + +StorageWeakRefPointer = int +StorageDataPtr = int +NBytes = int +S = TypeVar("S", bound="StorageWeakRefWrapper") + + +if torch.backends.cuda.is_built(): + from torch._C import ( + _cuda_CUDAAllocator_AllocatorState as AllocatorState, + _set_cached_tensors_enabled, + ) +else: + + class AllocatorState: # type: ignore[no-redef] + pass + + def _set_cached_tensors_enabled(enabled: _bool) -> None: + pass + + +log = torch._logging.getArtifactLogger(__name__, "cudagraphs") + + +def format_inputs_log(inputs: list[Any]) -> str: + def format_item(i: int, inp: Any) -> str: + if isinstance(inp, torch.Tensor): + return ( + f"[{i}]: Tensor(size={list(inp.size())}, stride={inp.stride()}, " + f"dtype={inp.dtype}, data_ptr=0x{inp.data_ptr():X})" + ) + elif inp is None: + return f"[{i}]: None" + else: + return f"[{i}]: {type(inp).__name__}({inp})" + + n = len(inputs) + if n == 0: + return "[]" + + # Only display the first 10 inputs if the input list is too long + max_items = 10 + parts = [format_item(i, inp) for i, inp in enumerate(inputs[:max_items])] + if n > max_items: + parts.append(f"... ({n - max_items} more items)") + + return ", ".join(parts) + + +from . import config + + +@dataclasses.dataclass(frozen=True) +class GraphID: + "Unique counter of a cuda graph recording" + + id: int + + +def clear_cublass_cache() -> None: + """ + Cublas keeps a persistent workspace allocation for running matmuls. This poses a problem for + doing warmup within a CUDAGraph private pool because we do not want persistent allocations from + one one run to the next. When we begin a new run of a cudagraphs path (generation), all tensors + from the previous generation are freed. This frees them the memory pool, but not elsewhere. + A tensor in the cublas workspace would continue to be in use the workspace but would also get allocated + in the next run. The memory would be in use in two places. + + To solve this, we clear cublas caches before and after warming up or recording. If a workspace is required + it will be allocated to the cudagraph private pool and accounted for in the allocator for the duration of the + program. There is no overhead to this on replay since cudagraphs removes allocation overhead. + """ + torch._C._cuda_clearCublasWorkspaces() + + +@contextlib.contextmanager +def clear_cublas_manager() -> Generator[None, None, None]: + "Context manager around clearing cublas caches that will clear on enter and exit" + clear_cublass_cache() + try: + yield + finally: + clear_cublass_cache() + + +@contextlib.contextmanager +def disable_conv_cache_emptying() -> Generator[None, None, None]: + prev = torch._C._cuda_get_conv_benchmark_empty_cache() + torch._C._cudnn_set_conv_benchmark_empty_cache(False) + try: + yield + finally: + torch._C._cudnn_set_conv_benchmark_empty_cache(prev) + + +@contextlib.contextmanager +def enable_history_recording() -> Generator[None, None, None]: + "Turns on history recording in the CUDA Caching Allocator" + enabled = torch._C._cuda_isHistoryEnabled() + try: + if not enabled: + torch.cuda.memory._record_memory_history() + yield + finally: + if not enabled: + torch.cuda.memory._record_memory_history(None) + + +def get_history_recording() -> AbstractContextManager[None]: + # TODO - remove, prevents cleanup + if not config.triton.cudagraph_trees_history_recording: + return contextlib.nullcontext() + return enable_history_recording() + + +class TreeManagerContainer: + """ + Manages the lifetime of the tree manager. Like `PrivatePool` in cuda caching allocator, + the tree and its corresponding memory pool should be kept alive as long as any outstanding + graph or tensor which is an output of a graph remains alive. + + There is a single tree manager container per device. + + The lifecycle of a tree_manager is: + - Is constructed, no graph, no fns, no tensors + - Tree manager is fetched, resulting in tree manager being allocated + - We generate a bunch of functions, calling add_strong_reference + - These functions die, calling finalize_reference + - When all the functions die, we finalize_tree_manager. + + TODO: in the future, we would like to do the following once storage weak refs land + - We look for all the live storages and add references to THOSE + - We count as storages die + - All the storages are dead, we deallocate the tree manager + """ + + def __init__(self, device_index: int) -> None: + # This class keeps a strong reference to tree_manager, + # but upon all other strong references to the tree_manager will reset it to None. + # We need a strong reference so that we can still access its attributes upon cleanup. + self.tree_manager: CUDAGraphTreeManager | None = None + + # Number of outstanding references to the current tree manager + self.live_cudagraphify_fns = 0 + + self.device_index = device_index + + # Following two objects are only set in the case that Tensor outputs outlive + # the cudagraphify_fns. Reference to the Graph is needed to keep the private pool from + # deallocation. + self.live_storages_count = 0 + self.graph: torch.cuda.CUDAGraph | None = None + + self.lock = threading.Lock() + + def _finalize_tensor(self) -> None: + with self.lock: + self.live_storages_count -= 1 + if self.live_storages_count == 0: + self.graph = None + + # manager was used again after existing cleanup, + # we shouldn't set it to None + if self.live_cudagraphify_fns == 0: + self.tree_manager = None + + def finalize_cudagraphify_fn(self) -> None: + with self.lock: + self.live_cudagraphify_fns -= 1 + if self.live_cudagraphify_fns == 0: + self._finalize_tree_manager() + + def _finalize_tree_manager(self) -> None: + if not self.lock.locked(): + raise AssertionError("expected lock to be held") + self.tree_manager = None + + # TODO - when issue #91395 is landed, we can set a weakref on + # storages and trigger a deallocation when all outputs of the + # cudagraph are dead. + + # live_storages = list( + # tree_manager.live_cudagraph_pool_storages_in_curr_execution() + # ) + + # # Maintain reference to graph to keep tensors alive + # assert len(tree_manager.roots) > 0, "expected at least one use" + # root = next(tree_manager.get_roots()) + # self.graph = root.graph + # seen_storages = set() + # for stor in live_storages: + # if stor in seen_storages: + # continue + # seen_storages.add(stor) + # self.live_storages_count += 1 + # . weakref.finalize(stor, self._finalize_tensor) + + def add_strong_reference(self, fn: Callable[..., Any]) -> None: + with self.lock: + self.live_cudagraphify_fns += 1 + + weakref.finalize(fn, self.finalize_cudagraphify_fn) + + def get_tree_manager(self) -> CUDAGraphTreeManager: + with self.lock: + if self.tree_manager is None: + self.tree_manager = CUDAGraphTreeManager(self.device_index) + return self.tree_manager + + +def _initialize_tls(local: threading.local) -> None: + # one tree manager per device + local.tree_manager_containers = {} + local.tree_manager_locks = defaultdict(threading.Lock) + + # We need to register this as an object that will be copied over as TLS when new + # threads are created in autograd + torch._C._stash_obj_in_tls("tree_manager_containers", local.tree_manager_containers) + torch._C._stash_obj_in_tls("tree_manager_locks", local.tree_manager_locks) + + +local = threading.local() +_initialize_tls(local) + + +# CUDA graph capture and private-pool warmup are process-wide CUDA states. Keep +# them serialized across Python threads so a synchronize or allocator-pool switch +# in one thread does not invalidate another thread's capture. +graph_capture_lock = threading.Lock() + + +# only incremented by user call of mark_step_begin +class MarkStepBox: + mark_step_counter = 0 + + +def mark_step_begin() -> None: + "Indicates that a new iteration of inference or training is about to begin." + + # iterate down to distinguish from GenerationTracking counter + MarkStepBox.mark_step_counter -= 1 + + +def mark_warmup_incomplete() -> None: + """Request another warmup for the active CUDA Graph Trees function. + + This is a no-op unless called synchronously from a function currently running + in CUDA Graph Trees warmup. + """ + manager = get_manager(create_if_none_exists=False) + if manager is not None: + manager.mark_warmup_incomplete() + + +def reset_cudagraph_trees() -> None: + "Clear all cudagraph trees" + # see shutdown below for why this is necessary + # Note: get_obj may fail if called from a thread that wasn't spawned by + # autograd (e.g., test threads). In that case, there's nothing to reset. + if not torch._C._is_key_in_tls("tree_manager_containers"): + # TLS not set up for this thread, nothing to reset + return + container_dict = get_obj(local, "tree_manager_containers") + locks_dict = get_obj(local, "tree_manager_locks") + for device, lock in locks_dict.items(): + with lock: + container = container_dict.get(device) + if not container or not container.tree_manager: + continue + + container.tree_manager.shutdown() + + _set_cached_tensors_enabled(False) + container_dict.clear() + + MarkStepBox.mark_step_counter = 0 + + +def get_obj(local: Any, attr_name: str) -> Any: + if hasattr(local, attr_name): + return getattr(local, attr_name) + if not torch._C._is_key_in_tls(attr_name): + _initialize_tls(local) + return getattr(local, attr_name) + return torch._C._get_obj_in_tls(attr_name) + + +def get_container(device_index: int) -> TreeManagerContainer: + container_dict = get_obj(local, "tree_manager_containers") + lock = get_obj(local, "tree_manager_locks")[device_index] + + with lock: + if device_index not in container_dict: + container_dict[device_index] = TreeManagerContainer(device_index) + + return container_dict[device_index] + + +def get_manager( + device_index: int | None = None, create_if_none_exists: bool = True +) -> CUDAGraphTreeManager | None: + if device_index is None: + if not torch.cuda.is_initialized(): + return None + device_index = torch.cuda.current_device() + + if create_if_none_exists: + return get_container(device_index).get_tree_manager() + + container = get_obj(local, "tree_manager_containers").get(device_index) + return None if container is None else container.tree_manager + + +def is_cudagraph_capture_sizes(int_key: int | tuple[int, ...]) -> bool: + """ + Returns true if all dynamic shapes should be captured or the dynamic shape + int_key should be captured. + """ + return ( + config.triton.cudagraph_capture_sizes is None + or int_key in config.triton.cudagraph_capture_sizes + ) + + +def cudagraphify_impl( + model: ModelType, + inputs: list[InputType], + static_input_idxs: Sequence[int], + *args: Any, + **kwargs: Any, +) -> ModelType: + fn_cache: dict[tuple[int, ...], Callable[..., Any]] = {} + + # Detect int inputs: we need to index on these + int_key = [i for i, v in enumerate(inputs) if isinstance(v, int)] + get_ints: Any = operator.itemgetter(*int_key) if int_key else lambda _: None + + has_warn = False + + del inputs + + def deferred_cudagraphify(inputs: list[InputType]) -> OutputType: + nonlocal has_warn + + int_key = get_ints(inputs) + + if not is_cudagraph_capture_sizes(int_key): + return model(inputs) + + fn = fn_cache.get(int_key) + if fn is not None: + return fn(inputs) + compile_id = kwargs.get("compile_id", "") + if int_key is None: + log.info( + "[%s] Recording cudagraph tree for graph without symints", compile_id + ) + else: + log.info( + "[%s] Recording cudagraph tree for symint key %s", compile_id, int_key + ) + + if not has_warn: + has_warn = maybe_warning_due_to_dynamic_shape(fn_cache, int_key) + + # first get indices we need to check to align, then update our static inputs, + # and finally copy + check_input_idxs = get_input_idxs_to_check(inputs, static_input_idxs) + new_static_input_idxs = remove_unaligned_input_idxs(inputs, static_input_idxs) + copy_misaligned_inputs(inputs, check_input_idxs) + + fn, out = cudagraphify(model, inputs, new_static_input_idxs, *args, **kwargs) + # cudagraph will already clones input locally, no need to copy back + mutated_input_idxs: OrderedSet[int] = OrderedSet() + fn = align_inputs_from_check_idxs( + fn, inputs_to_check=check_input_idxs, mutated_input_idxs=mutated_input_idxs + ) + + fn_cache[int_key] = fn + + return out + + return deferred_cudagraphify + + +@contextlib.contextmanager +def dynamo_timed_cudagraph( + name: str, + compile_id: CompileId | None, + mode: CompilationMode | None, +) -> Generator[Any, None, None]: + """ + Makes usages of dynamo_timed in this file less verbose. NOTE: This CM sums + all durations into a single column in the dynamo_compile table. Use only if + you consider the timed region to be part of the runtime overhead associated + with the compiler. + """ + with dynamo_timed( + name, + log_pt2_compile_event=True, + compile_id=compile_id, + is_backward=mode == CompilationMode.BACKWARD, + dynamo_compile_column_us="runtime_cudagraphify_time_us", + ): + yield + + +def cudagraphify( + model: ModelType, + inputs: list[InputType], + static_input_idxs: Sequence[int] = (), + *, + device_index: int, + is_backward: bool, + is_inference: bool, + stack_traces: StackTraces | None = None, + constants: tuple[torch.Tensor, ...] = (), + placeholders: tuple[PlaceholderInfo, ...] = (), + mutated_input_idxs: tuple[int, ...] = (), + kernel_free_cudagraph: bool = False, + user_visible_output_idxs: tuple[int, ...] = (), + compile_id: CompileId | None = None, +) -> tuple[ModelType, OutputType]: + if is_backward and is_inference: + raise AssertionError("expected not (is_backward and is_inference)") + mode = ( + CompilationMode.BACKWARD + if is_backward + else (CompilationMode.INFERENCE if is_inference else CompilationMode.FORWARD) + ) + + with dynamo_timed_cudagraph("cudagraphify.get_container", compile_id, mode): + manager = get_container(device_index).get_tree_manager() + + return manager.add_function( + model, + inputs, + static_input_idxs, + stack_traces, + mode, + constants, + placeholders, + mutated_input_idxs, + kernel_free_cudagraph, + user_visible_output_idxs, + compile_id, + ) + + +class StorageWeakRefWrapper: + """ + Wrapper around a storage weak ref. Will deallocate it upon expiration if invoked. + """ + + __slots__ = ["ref", "_data_ptr", "extra_ref_check"] + + storage_ref: StorageWeakRef | None + + def __init__( + self, + inp: Tensor | UntypedStorage, + extra_ref_check: Callable[[], bool] | None = None, + ) -> None: + """ + extra_ref_check is an additional check we need to run to check if the + weak ref has expired. in checking storage use count we assume extra_ref_check + will hold an additional reference to the storage. + """ + if isinstance(inp, Tensor): + stor = inp.untyped_storage() + else: + if not isinstance(inp, UntypedStorage): + raise AssertionError(f"expected UntypedStorage, got {type(inp)}") + stor = inp + self.ref = StorageWeakRef(stor) + self._data_ptr = stor.data_ptr() + self.extra_ref_check = extra_ref_check + + @classmethod + def from_weakref_and_data_ptr( + cls: type[StorageWeakRefWrapper], + cdata: Any, + data_ptr: int, + extra_ref_check: Callable[[], bool] | None = None, + ) -> StorageWeakRefWrapper: + instance = cls.__new__(cls) + instance._data_ptr = data_ptr + instance.ref = StorageWeakRef.from_weakref(cdata) + instance.extra_ref_check = extra_ref_check + return instance + + def __call__(self) -> StorageWeakRefPointer | None: + if self.expired(): + return None + + return self.ref.cdata + + def swap_weakref(self, cdata: Any) -> None: + self.ref.__del__() + self.ref.cdata = cdata + + def data_ptr(self) -> int: + "NB: returns the data ptr even if the storage has expired" + return self._data_ptr + + def remove_extra_reference(self) -> None: + self.extra_ref_check = None + + def expired(self) -> bool: + if self.extra_ref_check is not None and not self.extra_ref_check(): + return False + + stor_count = torch._C._storage_Use_Count(self.ref.cdata) + if self.extra_ref_check is not None: + # if extra_ref_check is not None we expect two additional references: + # - one from the Python storage object + # - one from the cached Tensor + stor_count -= 2 + if stor_count < 0: + raise AssertionError(f"expected stor_count >= 0, got {stor_count}") + return stor_count == 0 + + def __repr__(self) -> str: + if self.ref is None or self.ref.expired(): + return f"StorageWeakRefWrapper to {self.data_ptr()}; dead" + else: + return f"StorageWeakRefWrapper to {self.data_ptr()}; alive" + + +def is_live(weak_ref: StorageWeakRefWrapper | None) -> bool: + return maybe_deref(weak_ref) is not None + + +def maybe_deref( + weak_ref: StorageWeakRefWrapper | None, +) -> tuple[StorageWeakRefPointer, int] | None: + if weak_ref is None: + return None + r = weak_ref() + if r is None: + return None + # NB: r.data_ptr() does not necessarily equal weak_ref.data_ptr() + return r, weak_ref.data_ptr() + + +@contextlib.contextmanager +def _use_cuda_memory_pool_manager( + device: int, mem_pool: tuple[int, int], stream: torch.cuda.Stream +) -> Generator[None, None, None]: + """ + Context manager to use cuda graph pool for new allocations. If you use this manager + all cudagraph tensors in use should be reflected in the allocator or they will be overwritten. + existing_graph should already have been used in a capture, and the mem_pool must already exist, + because this manager will not preserve a reference to the pool which keeps it alive. + """ + torch.cuda.synchronize() + stream.wait_stream(torch.cuda.current_stream()) + + with torch.cuda.stream(stream), torch.device(device): + # Begin allocate to mem pool for all memory allocation on the current thread. + # This is thread safe since a thread can only warmup or record 1 cudagraph + # at the same time. + torch._C._cuda_beginAllocateCurrentThreadToPool(device, mem_pool) + try: + yield + finally: + torch._C._cuda_endAllocateToPool(device, mem_pool) + torch._C._cuda_releasePool(device, mem_pool) + + torch.cuda.current_stream().wait_stream(stream) + + +@contextlib.contextmanager +def _update_current_stream_external_object() -> Generator[None, None, None]: + """Update the external object registry so custom ops see the capture stream. + + During cudagraph recording/warmup the current stream differs from the + trace-time default stream. The external object at CURRENT_STREAM_INDEX + must reflect the actual current stream so that custom ops (e.g. event + record/wait) executed during capture use the right stream. + """ + set_external_object_by_index(CURRENT_STREAM_INDEX, torch.cuda.current_stream()) + yield + + +def map_to_ref(t: Tensor | None) -> StorageWeakRefWrapper | None: + if not isinstance(t, torch.Tensor): + if t is not None: + raise AssertionError(f"expected t to be None, got {t}") + return None + return StorageWeakRefWrapper(t) + + +# A path index of (depth, offset) indices into a graph that is `depth`` number of nodes from the root +# at graph output offset +PathOutputIndex = tuple[int, int] +# Cached per-node lists and output index to check for user-visible output cloning. +PathUserVisibleOutputEntry = tuple[ + list[StorageWeakRefWrapper | None], + list[TensorWeakRef | None], + list[Tensor | None] | None, + int, +] +PathUserVisibleStorageGroup = tuple[PathUserVisibleOutputEntry, ...] + +# For each node in the path, for each output, is the output alive +PathLiveness = list[list[bool]] + +StackTraces = list[str | None] + + +class CUDAWarmupNode: + """ + Simplified Wrapper around A CUDA Model that wraps outputs in storage refs and exposes + apis to get the live storages in the current chain of warmup. + + A CUDAWarmupNode may have either CUDAGraphNode or CUDAWarmupNode as a parent, but may only have + CUDAWarmupNode as children, because we cannot record or execute with tensors which do not have stable + memory addresses. + + CUDAWarmupNode and CUDAGraphNode have a number of differences that make it easier to use separate classes. + - Much of the CUDAGraphNode logic & initialization is based on the tensor properties of first recording. In the + first instance of warmup, these are not finalized yet. + - All Inputs to the RecordedFunction must be copied over to the cuda graph memory pool, this is unnecessary in warmup. + - CUDAWarmup is only used once and so does not need to optimize as much bookkeeping. It is much simpler. + + NB: this class and CUDAGraphNode need to expose `path_live_weakrefs`, `all_outputs_are_dead`, and + `self.outputs_weakrefs`, `stack_traces`, and `tensor_weakrefs` for compatibility. + """ + + def __init__( + self, + wrapped_function: WrappedFunction, + parent: CUDAGraphNode | CUDAWarmupNode | None, + cuda_graphs_pool: tuple[int, int], + existing_cuda_graph: torch.cuda.CUDAGraph | None, + device_index: int, + stack_traces: StackTraces | None, + stream: torch.cuda.Stream, + already_warm: bool, + id: GraphID, + ) -> None: + self.wrapped_function = wrapped_function + self.user_visible_output_idxs = wrapped_function.user_visible_output_idxs + self.parent: CUDAGraphNode | CUDAWarmupNode | None = parent + self.cuda_graphs_pool = cuda_graphs_pool + self.outputs_weakrefs: list[StorageWeakRefWrapper | None] = [] + self.tensor_weakrefs: list[TensorWeakRef | None] = [] + self.existing_cuda_graph = existing_cuda_graph + self.has_run = False + self.device_index = device_index + self.stack_traces = stack_traces + self.stream = stream + self.already_warm = already_warm + self.id = id + + @functools.cached_property + def path_user_visible_storage_groups( + self, + ) -> tuple[PathUserVisibleStorageGroup, ...]: + return collect_path_user_visible_storage_groups(tuple(self._path_from_root)) + + def run(self, new_inputs: Any) -> OutputType: + if self.has_run: + raise AssertionError("Wrapped function should never be run twice") + + # See: output_is_alias_of_persistent_static_inputs below. We should only be returning freshly created + # storages in path_live_weakrefs. + existing_path_data_ptrs = OrderedSet( + [t.data_ptr() for t in self.path_live_weakrefs() if t()] + ) + + def get_non_cudagraph_inps() -> list[weakref.ReferenceType[UntypedStorage]]: + non_cudagraph_inps = [ + weakref.ref(t.untyped_storage()) + for t in itertools.chain(new_inputs, self.wrapped_function.constants) + if isinstance(t, torch.Tensor) + and t.untyped_storage().data_ptr() not in existing_path_data_ptrs + ] + return non_cudagraph_inps + + non_cudagraph_inps_storages = get_non_cudagraph_inps() + + if config.triton.slow_path_cudagraph_asserts and not self.already_warm: + refs = list(self.path_live_weakrefs()) + check_memory_pool(self.device_index, self.cuda_graphs_pool, refs) + + with ( + torch.cuda.device(self.device_index), + disable_conv_cache_emptying(), + clear_cublas_manager(), + _use_cuda_memory_pool_manager( + self.device_index, self.cuda_graphs_pool, self.stream + ), + # NB: must go after _use_cuda_memory_pool_manager which switches the stream + _update_current_stream_external_object(), + ControlFlowOpWarmupDispatchMode(), + get_history_recording(), + ): + out = self.wrapped_function.model(new_inputs) + + # We need to know which outputs are allocated within the cudagraph pool + # so that we can deallocate them at the beginning of the next cudagraph step, + # and set their access to error. + # We use a weakref to the inputs storage, in case a block which was previously + # allocated to the general caching allocator pool gets reallocated to a private pool. + + non_cudagraph_inps_storage_ptrs = OrderedSet[Any]() + for storage in non_cudagraph_inps_storages: + s = storage() + if s is not None: + non_cudagraph_inps_storage_ptrs.add(s._cdata) + + if len(new_inputs) != 0: + raise AssertionError( + f"expected new_inputs to be empty, got {len(new_inputs)}" + ) + + # sdpa returns cpu tensors when not recording cuda graph + def add_ref(o: Any) -> bool: + return ( + isinstance(o, torch.Tensor) + and o.is_cuda + and o.untyped_storage()._cdata not in non_cudagraph_inps_storage_ptrs + and o.untyped_storage().data_ptr() != 0 + ) + + self.outputs_weakrefs.extend( + [map_to_ref(o) if add_ref(o) else None for o in out] + ) + self.tensor_weakrefs.extend( + [TensorWeakRef(o) if add_ref(o) else None for o in out] + ) + + if config.triton.slow_path_cudagraph_asserts and not self.already_warm: + out_refs = list(self.path_live_weakrefs()) + check_memory_pool(self.device_index, self.cuda_graphs_pool, out_refs) + + return out + + @property + def _path_from_root( + self, + ) -> Generator[CUDAGraphNode | CUDAWarmupNode, None, None]: + nodes = [] + node: CUDAGraphNode | CUDAWarmupNode = self + while node: + nodes.append(node) + node = node.parent # type: ignore[assignment] + + yield from reversed(nodes) + + def path_live_weakrefs(self) -> Iterator[StorageWeakRefWrapper]: + "Returns all live storages weakrefs that created by nodes in this path" + for node in self._path_from_root: + for output in node.outputs_weakrefs: + if is_live(output): + yield output # type: ignore[misc] + + def all_outputs_are_dead(self) -> bool: + return not list(self.path_live_weakrefs()) + + def _is_cuda_graph_recorded_tensor(self, t: torch.Tensor) -> bool: + for storage_weak_ref in self.path_live_weakrefs(): + if t.untyped_storage().data_ptr() == storage_weak_ref.data_ptr(): + return True + return False + + +# Aliases for List that say what the indices denote +InputList = list # input indexes +OutputList = list # output indexes +LevelList = list # levels (distance from root of tree) + + +class OutputAliasInfo: + __slots__ = [] + + +class _UnaliasedStorage(OutputAliasInfo): + "Singleton to mark that the graph output constructs a new alias or is None" + + +UnaliasedStorage = _UnaliasedStorage() + + +class AliasesPriorGraphOutput(OutputAliasInfo): + "Marks that the graph output aliases an output of a prior graph" + + __slots__ = ["index"] + + index: PathOutputIndex + + def __init__(self, index: PathOutputIndex) -> None: + if not isinstance(index, tuple): + raise AssertionError(f"expected index to be a tuple, got {type(index)}") + self.index = index + + +class AliasesNewOutput(OutputAliasInfo): + "Marks that the graph output aliases an index in the new, returned outputs" + + __slots__ = ["index"] + + index: int + + def __init__(self, index: int) -> None: + if not isinstance(index, int): + raise AssertionError(f"expected index to be an int, got {type(index)}") + self.index = index + + +class CUDAGraphNode: + """ + A single recording of a function into a CUDA Graph. Recordings of CUDA Graphs share a single memory pool + and are structured into a tree, where there is a single recording that can precede it (parent) and multiple + subsequent recordings that may follow (children). A node will have no parent if it is the first recording + in a tree; i.e., when it is first recorded, there are no live tensors from a previous recording which + would force a dependency. + + On first recording, all of the live tensors in the current CUDA Graph Node path will be + reflected in the corresponding private pool. On subsequent executions, the caching allocator + is unaffected when the graph is replayed. + + In order to support recording a subsequent cuda graph recording after execution of this graph, + we checkpoint the state of the memory pool so that it may later be resumed. + + WrappedFunction should have already been warmed up prior to invocation. + + See [setCheckpointPoolState] for further explanation, as well as + https://user-images.githubusercontent.com/13564/222815509-374f3400-f83d-4f7d-8fa6-4a092b3250bb.png + """ + + def __init__( + self, + wrapped_function: WrappedFunction, + id: GraphID, + parent: CUDAGraphNode | None, + inputs: list[InputType], + cuda_graphs_pool: _POOL_HANDLE, + device_index: int, + stack_traces: StackTraces | None, + stream: torch.cuda.Stream, + mode: CompilationMode | None, + compile_id: CompileId | None, + ) -> None: + if not isinstance(inputs, (list, tuple)): + raise AssertionError( + f"expected inputs to be list or tuple, got {type(inputs)}" + ) + + self.wrapped_function = wrapped_function + self.user_visible_output_idxs = wrapped_function.user_visible_output_idxs + self.id = id + self.device = device_index + self.stack_traces = stack_traces + self.stream = stream + + # Enable re-record a cudagraph when static tensor address changed. + # if not we should error when it changed. + self.rerecord_if_static_inputs_change = True + + # if this is a root parent will be None. use weakref to prevent reference cycle + self._parent = weakref.ref(parent) if parent is not None else None + # reference to the shared memory pool for the entire cuda graphs tree + self.cuda_graphs_pool = cuda_graphs_pool + + # A single wrapped function may be recorded multiple times if memory patterns or + # invariants change from one execution to the next + self.children: dict[FunctionID, list[CUDAGraphNode]] = defaultdict(list) + + # StorageWeakRef maintains whether the Storage C++ object remains allocated, + # not whether the corresponding memory has been deallocated. In order + # to use them to track memory deallocations we must maintain a single StorageWeakRef + # for all Storages that reference that memory (even if we are constructing Storages + # that do not have a deallocator function). We maintain one single storage_cache + # as we execute any tree path. When we retrieve a storage from the cache we + # check that it is still alive, and we hash based on observed recording data ptr + # and storage cdata. + + # we preserve a single reference to executed outputs that is then referenced + # in children to avoid children having to chase parent pointers in the hot path + # DO NOT reassign output_weakrefs, only call `clear()` + # Path is a series of nodes from root to the current node + self.outputs_weakrefs: OutputList[StorageWeakRefWrapper | None] = [] + self.path_weakrefs: LevelList[OutputList[StorageWeakRefWrapper | None]] = [ + node.outputs_weakrefs for node in self._path_from_root + ] + self.path_stacktraces: LevelList[StackTraces | None] = [ + node.stack_traces for node in self._path_from_root + ] + self.tensor_weakrefs: OutputList[TensorWeakRef | None] = [] + + # tensors which are outputs of previous graphs in the tree + self.cudagraph_managed_idxs: list[int] = [ + idx + for idx, t in enumerate(inputs) + if isinstance(t, torch.Tensor) and self._is_cuda_graph_recorded_tensor(t) + ] + + # (depth, offset) of live tensors which are alias of previous graph outputs + self.live_cudagraph_managed_path_refs: InputList[PathOutputIndex | None] = [ + ( + self._is_alias_of_live_recorded_tensor(t) + if isinstance(t, torch.Tensor) + else None + ) + for t in inputs + ] + + # when replay, preserve the liveness of an input if it AliasesPriorGraphOutput + # and also aliases an output of the current CUDAGraphNode + self.preserved_aliased_inputs: InputList[bool] = [False] * len(inputs) + + # Opaque values (e.g. DeviceMesh, ProcessGroup) are non-tensor + # inputs that cannot be copied like tensors. We include them in + # static_input_idxs to keep them out of non_static_input_idx + # (which drives the tensor-copy path during replay). "Static" + # here just means "don't try to copy this as a tensor" — it + # does NOT mean the object is semantically immutable. + # + # Opaque indices must also be excluded from any list passed to + # _tensors_data_ptrs_at_indices_equal (the C++ data-pointer + # stability check), because opaque objects have no data_ptr. + # That is why tensor_static_input_idxs and + # non_managed_static_input_idxs filter them out below. + opaque_input_idxs = OrderedSet( + i for i, inp in enumerate(inputs) if is_custom_class_obj(inp) + ) + static_input_idxs = OrderedSet(wrapped_function.static_input_idxs) + cudagraph_managed_idxs = OrderedSet(self.cudagraph_managed_idxs) + + self.static_input_idxs: list[int] = list( + static_input_idxs | cudagraph_managed_idxs | opaque_input_idxs + ) + + self.non_static_input_idx: LevelList[int] = [ + i for i in range(len(inputs)) if i not in self.static_input_idxs + ] + + counters["inductor"]["cudagraph_recorded_non_static_inputs"] += len( + self.non_static_input_idx + ) + + self.non_managed_static_input_idxs: LevelList[int] = LevelList( + static_input_idxs - cudagraph_managed_idxs - opaque_input_idxs + ) + + self.tensor_static_input_idxs: list[int] = list( + static_input_idxs | cudagraph_managed_idxs + ) + + def maybe_get_static_data_ptr( + idx: int, + inputs: list[InputType], + static_input_idxs: list[int], + ) -> int | None: + inp = inputs[idx] + if isinstance(inp, torch.Tensor) and idx in static_input_idxs: + return inp.data_ptr() + return None + + self.static_input_data_ptrs: InputList[int | None] = [ + maybe_get_static_data_ptr(i, inputs, self.static_input_idxs) + for i in range(len(inputs)) + ] + + # When we checkpoint, and free generations, we will be manually freeing the outputs + # of CUDAGraphNodes. We should not be freeing parameters, not do we need to account for + # their liveness (they are static), so we need to compute which outputs are aliases of + # parameters. Some static inputs are saved tensors from the forward that die in the backward. + # Their locations are static but lifetimes are not. We only include the persistent static + # data ptrs below because the non persistent data ptrs may be outputs of this record and + # fresh allocations. + + # precompute expanded dims to avoid computing in the hot path + self.expanded_dims: list[list[int]] = [ + get_expanded_dims(x) + if isinstance(x, torch.Tensor) and idx not in self.static_input_idxs + else [] + for idx, x in enumerate(inputs) + ] + + # For each node in path, which outputs were observed to be live + # before invoking graph recording, and after graph recording + self.recorded_liveness_before_graph: LevelList[OutputList[bool]] = [] + self.recorded_liveness_after_graph: LevelList[OutputList[bool]] = [] + + # List of tuples of (depth, output_index) that index into node at depth + # number of nodes from root and output_index of outputs. Will index into + # path_weakrefs. + self.expected_dead_indices_before_graph: list[PathOutputIndex] = [] + self.expected_dead_indices_after_graph: list[PathOutputIndex] = [] + + # all live indices after graph recording + self.live_indices_after_graph: list[PathOutputIndex] = [] + + if self.parent is not None: + previous_liveness = self.parent.recorded_liveness_after_graph + curr_liveness = self._get_liveness(self.path_weakrefs) + + different_indices = self._get_different_indices( + previous_liveness, curr_liveness + ) + + self.recorded_liveness_before_graph = curr_liveness + self.expected_dead_indices_before_graph = different_indices + + recording_inputs = self._allocate_and_copy_recording_inputs(inputs) + # recording inputs will copy over memory, so we can free non recording inputs + + inputs.clear() + del inputs + + self.graph: torch.cuda.CUDAGraph | None = ( + None if wrapped_function.kernel_free_cudagraph else torch.cuda.CUDAGraph() + ) + + # we allocate non-static inputs within the same memory pool as the CUDAGraph + # which we will record the model with. For memory efficiency, it is important + # to reclaim the input memory when the inputs are no longer live. To accomplish this, + # we reconstruct tensors at the correct data pointers of our inputs which are + # non owning and do not prevent deallocation. On subsequent executions, input values + # will be copied over to these tensors. + self.reconstructed_inputs: list[InputType] = [ + self._reconstruct_from_tensor_metadata(self._tensor_metadata(x)) + if isinstance(x, torch.Tensor) + else x + for x in recording_inputs + ] + + # DO THE RECORDING!!! + # We record the CUDA graph in the constructor of CUDAGraphNode, which + # gives you what the CPU side compute of the function would do. We + # don't throw the recording outputs away: their memory is + # correctly accounted for in the CUDAGraphs caching allocator. This + # means on the very FIRST run of the CUDA graph node, we can directly + # do more recording, because we have a valid caching allocator state. + # NB: This relies on run() being called immediately after the + # constructor, otherwise this optimization would not be valid. + + # initialized below in _record + + self.checkpointed_caching_state: AllocatorState | None = None + + # Output Storage Alias information, can be: + # - A new, unaliased storage, or the output is None + # - An alias of an output of a prior graph + # - An alias of an output already created in the reconstructed outputs + # This is None if the output in question is an int + self.output_storage_alias: OutputList[OutputAliasInfo | None] = [] + + # is the output Storage unaliased in subsequent outputs, of all subsequent paths + # If a descendant node discovers it has an alias of a prior output, then the output + # will no longer be cached in the ancestor. + # The large majority of tensors are unaliased, and preserving aliased output tensors would add + # significant additional complexity with marginal gains + # The cached tensor outputs are added on the first execution, and cleared whenever we need + # to do subsequent recording + self.unaliased_in_all_paths: OutputList[bool] = [] + self.cached_tensor_outputs: OutputList[Tensor | None] = [] + + # if an output aliases a static, persistent input then the corresponding Tensor will + # be set here. These are different than cached tensors, because they are tensors that + # are aliases of parameters that are always live. + self.static_output_tensors: OutputList[Tensor | None] = [] + + # Cleared after recording + with dynamo_timed_cudagraph("CUDAGraphNode.record", compile_id, mode): + self.recording_outputs: OutputType | None = self._record( + wrapped_function.model, recording_inputs + ) + self.outputs_metadata: OutputList[dict[str, Any] | int | None] = [] + + # As with inputs, we do not want to keep the outputs permanently alive because that would prevent + # their memory being reclaimed in subsequent cuda graph recordings. We record the tensor metadata + # needed to reconstruct instead. + if self.recording_outputs is None: + raise AssertionError("expected recording_outputs to not be None") + for out in self.recording_outputs: + if isinstance(out, torch.Tensor): + self.outputs_metadata.append( + self._tensor_metadata(out, ignore_storage_offset=False) + ) + else: + if not isinstance(out, (int, type(None))): + raise AssertionError(type(out)) + self.outputs_metadata.append(out) + + if self.graph is not None: + self.graph.replay() + + @functools.cached_property + def path_user_visible_storage_groups( + self, + ) -> tuple[PathUserVisibleStorageGroup, ...]: + return collect_path_user_visible_storage_groups(tuple(self._path_from_root)) + + def _copy_inputs_and_remove_from_src( + self, dsts: list[InputType], srcs: list[InputType] + ) -> None: + dst_tensors = [] + src_tensors = [] + for idx in self.non_static_input_idx: + if not isinstance(srcs[idx], torch.Tensor): + continue + expanded_dims = self.expanded_dims[idx] + indexed_dst = index_expanded_dims(dsts[idx], expanded_dims) # type: ignore[arg-type] + if torch._debug_has_internal_overlap(indexed_dst) != 0: + # rare path: dst still self-overlaps after dropping expanded dims + copy_strided_storage_(dsts[idx], srcs[idx]) # type: ignore[arg-type] + srcs[idx] = None # type: ignore[call-overload] + continue + dst_tensors.append(indexed_dst) + src_tensors.append(index_expanded_dims(srcs[idx], expanded_dims)) # type: ignore[arg-type] + srcs[idx] = None # type: ignore[call-overload] + # Fails on empty lists + if dst_tensors: + torch._foreach_copy_(dst_tensors, src_tensors) + + def check_static_inputs_are_stable(self, new_inputs: list[InputType]) -> None: + # avoid checking managed tensor static points since we already checked those in check_invariants + if ( + not self.rerecord_if_static_inputs_change + and not torch._C._tensors_data_ptrs_at_indices_equal( + new_inputs, # type: ignore[arg-type] + self.static_input_data_ptrs, + self.non_managed_static_input_idxs, + ) + ): + # this should error + error_msg = log_data_ptr_mismatch( + self.wrapped_function.placeholders, + new_inputs, + self.static_input_data_ptrs, + self.non_managed_static_input_idxs, + CheckInvariantStatus.StaticInputIdxMismatch, + ) + torch._check(False, lambda: error_msg) + + def run_first_inputs(self, new_inputs: list[InputType]) -> OutputType: + if config.triton.fast_path_cudagraph_asserts: + self.debug_check_invariants_before_invocation() + + # graph is already invoked in the __init__ + # inputs are copied over in _allocate_recording_inputs and subsequently cleared + if len(new_inputs) != 0: + raise AssertionError( + f"expected new_inputs to be empty, got {len(new_inputs)}" + ) + outputs = self.recording_outputs + self.recording_outputs = None + if outputs is None: + raise AssertionError("expected outputs to not be None") + return outputs + + def run(self, new_inputs: list[InputType]) -> OutputType: + self.check_static_inputs_are_stable(new_inputs) + + self._copy_inputs_and_remove_from_src(self.reconstructed_inputs, new_inputs) + + self.run_graph() + + outputs = self.reconstruct_outputs() + new_inputs.clear() + + if config.triton.fast_path_cudagraph_asserts: + self.debug_check_invariants_after_invocation() + + if config.triton.force_cudagraph_sync: + torch.cuda.synchronize() + + # Reset this to run the check in the future + self.static_inputs_stable = False + + return outputs + + def reconstruct_outputs(self) -> OutputType: + "Reconstruct output tensors according to their saved metadata and alias information" + + # Cached tensors will not yet be set on the first execution + # They are also cleared in checkpointing, so if we checkpoint this node + # and then execute it again we will need to repopulate cached tensors + if not self.cached_tensor_outputs: + self._initialize_cached_tensors() + + outputs: OutputType = [] + user_visible_output_idxs = self.user_visible_output_idxs + + for i, (storage_info, metadata) in enumerate( + zip(self.output_storage_alias, self.outputs_metadata) + ): + if not isinstance(metadata, dict): # tensor metadata + if not isinstance(metadata, (int, type(None))): + raise AssertionError(f"expected int or None, got {type(metadata)}") + outputs.append(metadata) + continue + + cached_t = self.cached_tensor_outputs[i] + if cached_t is not None: + # this output represents a fresh allocated tensor. + # We return the same TensorImpl from run to run to avoid overhead. + # autograd.Function will reset the Autograd meta of output tensors + # as part of aot_autograd, but _backward_hooks are stored on tensors separately, + # so we need to manually reset hooks. + if cached_t._backward_hooks is not None: + cached_t._backward_hooks = None + + # No need to update weakrefs, already correctly initialized + outputs.append(cached_t) + continue + + static_t = self.static_output_tensors[i] + if static_t is not None: + if self.outputs_weakrefs[i] is not None: + raise AssertionError(f"expected outputs_weakrefs[{i}] to be None") + outputs.append(static_t) + continue + + storage = self.prepare_alias_info_for_tensor_construction( + storage_info, metadata + ) + + if isinstance(storage, UntypedStorage) or storage is None: + out = self._reconstruct_from_tensor_metadata(metadata, storage) + else: + if not isinstance(storage, int): + raise AssertionError( + f"expected storage to be int, got {type(storage)}" + ) + out = self._reconstruct_from_tensor_metadata( + metadata, cast(torch.Tensor, outputs[storage]).untyped_storage() + ) + + outputs.append(out) + w = self.outputs_weakrefs[i] + if w is None: + raise AssertionError("expected w to not be None") + w.swap_weakref(out.untyped_storage()._weak_ref()) + if user_visible_output_idxs and i in user_visible_output_idxs: + self.tensor_weakrefs[i] = TensorWeakRef(out) + + return outputs + + def prepare_alias_info_for_tensor_construction( + self, + out_alias_info: OutputAliasInfo | None, + metadata: dict[str, Any] | int | None, + ) -> UntypedStorage | None | int: + if ( + isinstance(metadata, (int, type(None))) + or out_alias_info is UnaliasedStorage + ): + return None + + if isinstance(out_alias_info, AliasesPriorGraphOutput): + depth, existing_output_index = out_alias_info.index + ref = self.path_weakrefs[depth][existing_output_index] + if ref is None: + raise AssertionError("expected ref to not be None") + return torch.UntypedStorage._new_with_weak_ptr(ref()) + + if not isinstance(out_alias_info, AliasesNewOutput): + raise AssertionError( + f"expected AliasesNewOutput, got {type(out_alias_info)}" + ) + return out_alias_info.index + + def prepare_storages_for_construction( + self, + ) -> list[UntypedStorage | None | int]: + output_storages = [] + for output_storage_alias, metadata in zip( + self.output_storage_alias, self.outputs_metadata + ): + output_storages.append( + self.prepare_alias_info_for_tensor_construction( + output_storage_alias, metadata + ) + ) + + return output_storages + + def run_graph(self) -> None: + if self.wrapped_function.kernel_free_cudagraph: + return + if self.graph is None: + raise AssertionError("expected graph to not be None") + self.graph.replay() + + def all_outputs_are_dead(self) -> bool: + "All outputs of the path from this node to its root are dead" + for depth, output_index in self.live_indices_after_graph: + if is_live(self.path_weakrefs[depth][output_index]): + return False + return True + + def _record(self, model: ModelType, inputs: list[InputType]) -> OutputType: + "Record the model" + + def static_input_iter() -> Generator[torch.Tensor, None, None]: + for i in self.wrapped_function.static_input_idxs: + _inp = inputs[i] + if isinstance( + _inp, torch.Tensor + ) and not self._is_cuda_graph_recorded_tensor(_inp): + yield _inp + + # see: output_is_alias_of_persistent_static_inputs above + static_input_persistent_storage_ptrs: dict[int, StorageWeakRefWrapper] = { + inp.untyped_storage().data_ptr(): StorageWeakRefWrapper(inp) + for inp in itertools.chain( + static_input_iter(), self.wrapped_function.constants + ) + } + + if self.wrapped_function.kernel_free_cudagraph: + with ( + preserve_rng_state(), + torch.cuda.device(self.device), + clear_cublas_manager(), + _use_cuda_memory_pool_manager( + self.device, self.cuda_graphs_pool, self.stream + ), + # NB: must go after _use_cuda_memory_pool_manager which switches the stream + _update_current_stream_external_object(), + ControlFlowOpWarmupDispatchMode(), + get_history_recording(), + ): + static_outputs = model(inputs) + if len(inputs) != 0: + raise AssertionError(f"expected inputs to be empty, got {len(inputs)}") + + if not isinstance(static_outputs, (list, tuple)): + static_outputs = [static_outputs] + elif isinstance(static_outputs, tuple): + static_outputs = list(static_outputs) + static_outputs = cast(OutputType, static_outputs) + self._add_first_outputs( + static_outputs, static_input_persistent_storage_ptrs + ) + return static_outputs + + if self.graph is None: + raise AssertionError("expected graph to not be None") + + if config.triton.slow_path_cudagraph_asserts: + # need to use parent live weakrefs because live_indices isn't set yet + memory = ( + [] if self.parent is None else list(self.parent.path_live_weakrefs()) + ) + memory += [ + StorageWeakRefWrapper(elem) + for i, elem in enumerate(inputs) + if isinstance(elem, torch.Tensor) + and i not in self.wrapped_function.static_input_idxs + and elem.untyped_storage().data_ptr() != 0 + ] + check_memory_pool(self.device, self.cuda_graphs_pool, memory) + + with ( + preserve_rng_state(), + torch.cuda.device(self.device), + clear_cublas_manager(), + torch.cuda.graph( + self.graph, + stream=self.stream, + pool=self.cuda_graphs_pool, + capture_error_mode="thread_local", + ), + # NB: must go after torch.cuda.graph which switches the stream + _update_current_stream_external_object(), + CUDAGraphCaptureControlFlowOpDispatchMode(), + get_history_recording(), + ): + static_outputs = model(inputs) + + # running model should reclaim memory + if len(inputs) != 0: + raise AssertionError(f"expected inputs to be empty, got {len(inputs)}") + + if not isinstance(static_outputs, (list, tuple)): + static_outputs = (static_outputs,) + + # pyrefly: ignore [bad-argument-type] + self._add_first_outputs(static_outputs, static_input_persistent_storage_ptrs) + + # pyrefly: ignore [bad-return] + return static_outputs + + def _add_first_outputs( + self, + outputs: OutputType, + static_input_persistent_storage_ptrs: dict[int, StorageWeakRefWrapper], + ) -> None: + "Add the outputs from the first invocation of the node and set up metadata" + + # getting liveness before we have added the outputs to path, so the length + # of the two lists is equal + prev_liveness = self.recorded_liveness_before_graph + curr_liveness = self._get_liveness(self.path_weakrefs) + + delta = self._get_different_indices(prev_liveness, curr_liveness) + self.expected_dead_indices_after_graph = delta + + if len(self.outputs_weakrefs) != 0: + raise AssertionError( + f"expected outputs_weakrefs to be empty, got {len(self.outputs_weakrefs)}" + ) + # index from data pointer to index in outputs + output_new_storages_index: dict[StorageDataPtr, int] = {} + + self.unaliased_in_all_paths = [False for _ in range(len(outputs))] + self.static_output_tensors = [None for _ in range(len(outputs))] + + for i, o in enumerate(outputs): + if o is None or not isinstance(o, torch.Tensor): + self.output_storage_alias.append(UnaliasedStorage) + continue + + torch._check( + o.is_cuda or o.untyped_storage().data_ptr() == 0, + lambda: ( + "Expected all cuda outputs in cuda graph recording. Non cuda output " + f"from {self.stack_traces[i] if self.stack_traces else '(unknown)'}" + ), + ) + + ref = static_input_persistent_storage_ptrs.get( + o.untyped_storage().data_ptr() + ) + # also treat empty storages as static outputs because we do not need to manage their lifetime + # and they should not participate in checkpointing + is_empty_storage = o.untyped_storage().data_ptr() == 0 + if (ref and ref() is not None) or is_empty_storage: + self.output_storage_alias.append(None) + self.static_output_tensors[i] = o + continue + + path_ref = self._is_alias_of_live_recorded_tensor(o) + if path_ref is not None: + self._mark_prior_graph_output_as_aliased(path_ref) + + for idx, inp_path_ref in enumerate( + self.live_cudagraph_managed_path_refs + ): + if path_ref == inp_path_ref: + self.preserved_aliased_inputs[idx] = True + self.output_storage_alias.append(AliasesPriorGraphOutput(path_ref)) + continue + + if o.untyped_storage().data_ptr() in output_new_storages_index: + index = output_new_storages_index[o.untyped_storage().data_ptr()] + self.unaliased_in_all_paths[index] = False + self.output_storage_alias.append(AliasesNewOutput(index)) + continue + + output_new_storages_index[o.untyped_storage().data_ptr()] = i + self.output_storage_alias.append(UnaliasedStorage) + self.unaliased_in_all_paths[i] = True + + if self.stack_traces is None: + self.stack_traces = [None for _ in range(len(outputs))] + else: + if len(self.stack_traces) != len(outputs): + raise AssertionError("Wrong number of stack traces passed in") + + if self.outputs_weakrefs: + raise AssertionError("expected outputs_weakrefs to be empty") + for out, static_output_tensor in zip(outputs, self.static_output_tensors): + if not isinstance(out, torch.Tensor) or static_output_tensor is not None: + self.outputs_weakrefs.append(None) + self.tensor_weakrefs.append(None) + else: + self.outputs_weakrefs.append(StorageWeakRefWrapper(out)) + self.tensor_weakrefs.append(TensorWeakRef(out)) + + self.recorded_liveness_after_graph = self._get_liveness(self.path_weakrefs) + self.checkpointed_caching_state = torch._C._cuda_getCheckpointState( + self.device, self.cuda_graphs_pool + ) + + # now, get liveness with outputs added + for depth in range(len(self.path_weakrefs)): + for output_index in range(len(self.path_weakrefs[depth])): + if is_live(self.path_weakrefs[depth][output_index]): + self.live_indices_after_graph.append((depth, output_index)) + + self.debug_check_invariants_after_invocation() + if config.triton.slow_path_cudagraph_asserts: + check_memory_pool( + self.device, self.cuda_graphs_pool, list(self.path_live_weakrefs()) + ) + + def _mark_prior_graph_output_as_aliased(self, index: PathOutputIndex) -> None: + "Remove a graph output from the unaliased, cached tensors in an ancestor node" + depth, output_index = index + node = list(self._path_from_root)[depth] + node.unaliased_in_all_paths[output_index] = False + x = self.path_weakrefs[depth][output_index] + if x is None: + raise AssertionError("expected x to not be None") + x.remove_extra_reference() + + def _initialize_cached_tensors(self) -> None: + # we should not be clearing output_weakrefs, and they should be set in the first + # record run + if len(self.outputs_weakrefs) != len(self.outputs_metadata): + raise AssertionError( + "expected len(outputs_weakrefs) == len(outputs_metadata)" + ) + for i, (storage_info, metadata, make_cached) in enumerate( + zip( + self.output_storage_alias, + self.outputs_metadata, + self.unaliased_in_all_paths, + ) + ): + if not make_cached: + self.cached_tensor_outputs.append(None) + continue + + if storage_info is not UnaliasedStorage: + raise AssertionError( + f"expected storage_info to be UnaliasedStorage, got {storage_info}" + ) + if not isinstance(metadata, dict): + raise AssertionError( + f"expected metadata to be dict, got {type(metadata)}" + ) + s = self.create_storage(metadata) + out = self._reconstruct_from_tensor_metadata(metadata, storage=s) # type: ignore[arg-type] + + # XXX: let autograd know that there will be an additional reference to the tensor + # that can be ignored when deciding whether to do gradient buffer inplacing. + # Otherwise, inplacing could differ between tracing and subsequent execution. + # For some models we tested this led to inputs no longer being in cudagraph pools, + # leading to spurious re-recordings. + # It also tells AMP cache that even though the tensor impls cannot be cached + # in dtype conversions. + + torch._C._add_cached_tensor(out) + + self_ref = weakref.ref(self) + + # one reference in our array, and calling sys.getrefcount bumps the refcount by one + def check_refcount(i: int) -> bool: + self_loc = self_ref() + if self_loc is None: + return False + refcount = self_loc.get_output_refcount(i) + # pyrefly: ignore + if self_loc.cached_tensor_outputs[i]._use_count() > 1: + # c10::Tensor may also holds one reference count + if refcount < 3: + raise AssertionError(f"expected refcount >= 3, got {refcount}") + return refcount == 3 + else: + if refcount < 2: + raise AssertionError(f"expected refcount >= 2, got {refcount}") + return refcount == 2 + + check = functools.partial(check_refcount, i=i) + + self.outputs_weakrefs[i] = StorageWeakRefWrapper(out, extra_ref_check=check) + self.cached_tensor_outputs.append(out) + + def get_output_refcount(self, index: int) -> int: + return sys.getrefcount(self.cached_tensor_outputs[index]) + + @property + def parent(self) -> CUDAGraphNode | None: + "unwraps the weakref to _parent" + return self._parent() if self._parent is not None else None + + @property + def _path_to_root(self) -> Generator[CUDAGraphNode, None, None]: + "Returns all nodes in the path starting at self and ending at root" + node = self + # pyrefly: ignore [bad-assignment] + while node: + yield node + node = node.parent # type: ignore[assignment] + + @property + def _path_from_root(self) -> Generator[CUDAGraphNode, None, None]: + "Returns all nodes in the path starting at the root and ending at self" + nodes = reversed(list(self._path_to_root)) + yield from nodes + + def _is_cuda_graph_recorded_tensor(self, t: torch.Tensor) -> bool: + "Is this tensor an output of a node in this path" + for output_refs in self.path_weakrefs: + for storage_weak_ref in output_refs: + if storage_weak_ref is None: + continue + # don't need to check liveness of storage since the cuda graph managed + # memory is never released. + data_ptr = storage_weak_ref.data_ptr() + if t.untyped_storage().data_ptr() == data_ptr: + return True + + return False + + def _is_alias_of_live_recorded_tensor( + self, t: torch.Tensor + ) -> PathOutputIndex | None: + for depth, output_refs in enumerate(self.path_weakrefs): + for output_index, storage_ref in enumerate(output_refs): + if (storage_and_ptr := maybe_deref(storage_ref)) is not None: + _storage, ptr = storage_and_ptr + if ptr == t.untyped_storage().data_ptr(): + return (depth, output_index) + + return None + + @staticmethod + def _check_liveness( + indices: list[PathOutputIndex], + output_refs: list[list[StorageWeakRefWrapper | None]], + ) -> bool: + "Check that all of the indices specified are dead references" + for depth, output_index in indices: + w = output_refs[depth][output_index] + if w is None: + raise AssertionError("expected w to not be None") + if w() is not None: + return False + return True + + def add_child(self, function_id: FunctionID, node: CUDAGraphNode) -> None: + "Adds node as a child of self" + self.children[function_id].append(node) + + @staticmethod + def _get_different_indices( + prev: list[list[bool]], curr: list[list[bool]] + ) -> list[PathOutputIndex]: + "Find indices where the two lists differ." + dead_indices = [] + if len(prev) > len(curr): + raise AssertionError( + f"expected len(prev) <= len(curr), got {len(prev)} > {len(curr)}" + ) + for i, (outputs1, outputs2) in enumerate(zip(prev, curr)): + if len(outputs1) != len(outputs2): + raise AssertionError( + f"expected len(outputs1) == len(outputs2), got {len(outputs1)} != {len(outputs2)}" + ) + for j, (output1, output2) in enumerate(zip(outputs1, outputs2)): + if output1 != output2: + dead_indices.append((i, j)) + + return dead_indices + + @staticmethod + def _get_liveness( + weakrefs: list[list[StorageWeakRefWrapper | None]], + ) -> list[list[bool]]: + "Maps weakrefs to true if the reference is alive and false otherwise" + if len(weakrefs) == 0: + return [] + + return [pytree.tree_map(is_live, outputs) for outputs in weakrefs] + + def debug_assert_invariants( + self, expected_liveness: list[list[bool]], newly_dead: list[PathOutputIndex] + ) -> None: + if not config.triton.fast_path_cudagraph_asserts: + return + + for i, node in enumerate(self._path_from_root): + if self.path_weakrefs[i] is not node.outputs_weakrefs: + raise AssertionError( + "expected path_weakrefs[i] to be node.outputs_weakrefs" + ) + + nodes = list(self._path_from_root) + + live_blocks = get_block_addrs(self.cuda_graphs_pool) + + live_storage_data_ptrs = OrderedSet[Any]() + live_storage_weak_ptrs = OrderedSet[Any]() + + for depth, outputs_liveness in enumerate(expected_liveness): + for output_idx, output_liveness in enumerate(outputs_liveness): + # tensor can die early, but it can't be alive when it should be dead + w = self.path_weakrefs[depth][output_idx] + if (stor_weak_ptr_and_data_ptr := maybe_deref(w)) is not None: + if not output_liveness: + raise AssertionError("expected output_liveness to be truthy") + stor_weak_ptr, stor_data_ptr = stor_weak_ptr_and_data_ptr + if not ( + (stor_data_ptr in live_storage_data_ptrs) + == (stor_weak_ptr in live_storage_weak_ptrs) + ): + raise AssertionError( + "expected data_ptr and weak_ptr liveness to agree" + ) + live_storage_data_ptrs.add(stor_data_ptr) + live_storage_weak_ptrs.add(stor_weak_ptr) + + is_persistent_alias = ( + nodes[depth].static_output_tensors[output_idx] is not None + ) + + if is_persistent_alias: + if stor_data_ptr in live_blocks: + raise AssertionError( + "expected stor_data_ptr not in live_blocks" + ) + + for depth, output_index in newly_dead: + if is_live(self.path_weakrefs[depth][output_index]): + raise AssertionError( + "expected path_weakrefs[depth][output_index] to not be live" + ) + + def debug_check_invariants_before_invocation(self) -> None: + self.debug_assert_invariants( + self.recorded_liveness_before_graph, self.expected_dead_indices_before_graph + ) + + def debug_check_invariants_after_invocation(self) -> None: + self.debug_assert_invariants( + self.recorded_liveness_before_graph, self.expected_dead_indices_after_graph + ) + + def data_ptrs_dead_since_invocation(self) -> list[int]: + """ + Since this node was invoked, return data ptrs of all tensor outputs that have died + in the current executing tree path. + """ + curr_liveness = self._get_liveness(self.path_weakrefs) + _get_different_indices = self._get_different_indices( + self.recorded_liveness_after_graph, curr_liveness + ) + + path = list(self._path_from_root) + ptrs_to_deallocate = [] + for depth, output_index in _get_different_indices: + ptrs_to_deallocate.append( + path[depth].outputs_metadata[output_index]["data_ptr"] # type: ignore[index] + ) + + return ptrs_to_deallocate + + def path_live_weakrefs(self) -> Iterator[StorageWeakRefWrapper]: + for i, j in self.live_indices_after_graph: + out = self.path_weakrefs[i][j] + if out is not None and is_live(out): + yield out + + def remove_node_cached_tensors(self) -> None: + for t in self.cached_tensor_outputs: + if t is not None: + torch._C._remove_cached_tensor(t) + self.cached_tensor_outputs.clear() + + for i, unaliased in enumerate(self.unaliased_in_all_paths): + if unaliased: + n = self.outputs_weakrefs[i] + if n is None: + raise AssertionError("expected n to not be None") + n.remove_extra_reference() + + def remove_path_cached_tensors(self) -> None: + for node in self._path_from_root: + node.remove_node_cached_tensors() + + def clear_path_state(self) -> None: + "Clear the path state in this current executing node" + # this doesn't actually do anything right now, leaving it as placeholder + + @staticmethod + def _tensor_metadata( + x: torch.Tensor, ignore_storage_offset: bool = True + ) -> dict[str, Any]: + if not isinstance(x, torch.Tensor): + raise AssertionError(f"expected x to be a torch.Tensor, got {type(x)}") + # We ignore the storage offset for inputs, but not for outputs + # TODO: - should we make the storage resizable ? + return { + "nbytes": x.untyped_storage().nbytes(), + "data_ptr": x.untyped_storage().data_ptr(), + "size": x.shape, + "stride": x.stride(), + "dtype": x.dtype, + "device": x.device, + "storage_offset": x.storage_offset() if not ignore_storage_offset else 0, + } + + def _reconstruct_from_tensor_metadata( + self, metadata: dict[str, Any], storage: UntypedStorage | None = None + ) -> Tensor: + s = self.create_storage(metadata) if storage is None else storage + return torch._C._construct_CUDA_Tensor_From_Storage_And_Metadata(metadata, s) # type: ignore[arg-type] + + def create_storage(self, metadata: dict[str, Any]) -> torch.types.Storage: + return torch._C._construct_storage_from_data_pointer( + metadata["data_ptr"], metadata["device"], metadata["nbytes"] + ) + + def _allocate_and_copy_recording_inputs( + self, inputs: list[InputType] + ) -> list[InputType]: + """ + Allocate inputs for non static, non cudagraph managed tensors in the memory pool + and copy over the tensor values. + """ + + torch.cuda.synchronize() + self.stream.wait_stream(torch.cuda.current_stream()) + recording_inputs: list[InputType] = [] + + with ( + warnings.catch_warnings(record=True), + torch.cuda.device(self.device), + _use_cuda_memory_pool_manager( + self.device, + mem_pool=self.cuda_graphs_pool, + stream=self.stream, + ), + ): + for i, inp in enumerate(inputs): + if not isinstance(inp, torch.Tensor): + if not isinstance(inp, (int, torch.Generator, CustomClassBase)): + raise AssertionError( + f"expected int, Generator, or CustomClassBase, got {type(inp)}" + ) + + recording_inputs.append(inp) + elif i not in self.static_input_idxs: + # static_input does an allocation! + recording_inputs.append(static_input(inp)) + else: + recording_inputs.append(inp) + + self._copy_inputs_and_remove_from_src(recording_inputs, inputs) + + return recording_inputs + + def check_invariants( + self, inputs: list[InputType] + ) -> tuple[CheckInvariantStatus, Callable[..., str]]: + """ + Checks if this node can be run. The same pattern of tensor liveness, static inputs, + and tensors managed in the cudagraph private pool must remain stable. + """ + + _logger = functools.partial( + log_data_ptr_mismatch, + self.wrapped_function.placeholders, + inputs, + self.static_input_data_ptrs, + ) + + # previously managed data pointers remain stable + # this is on the hot path so moved to C++. equivalent to: + # return all(t.data_ptr() == data_ptr for (t, data_ptr) in zip(tensors, data_ptrs)) + if not torch._C._tensors_data_ptrs_at_indices_equal( + inputs, # type: ignore[arg-type] + self.static_input_data_ptrs, + self.cudagraph_managed_idxs, + ): + status = CheckInvariantStatus.CudagraphManagedIdxMismatch + _logger = functools.partial( + _logger, + self.cudagraph_managed_idxs, + status, + ) + return status, _logger + + if not self._check_liveness( + self.expected_dead_indices_before_graph, self.path_weakrefs + ): + status = CheckInvariantStatus.ExpectedDeadIndicesBeforeGraphMismatch + return status, lambda: f"{status}" + + # static input data pointers should remain stable + # if we are inlining builtin nn modules we re-record in this case + # if we are not inlining builtin nn modules, we check this in check_static_inputs_are_stable + # and error if they are not stable + if ( + self.rerecord_if_static_inputs_change + and not torch._C._tensors_data_ptrs_at_indices_equal( + inputs, # type: ignore[arg-type] + self.static_input_data_ptrs, + self.tensor_static_input_idxs, + ) + ): + status = CheckInvariantStatus.StaticInputIdxMismatch + _logger = functools.partial( + _logger, + self.tensor_static_input_idxs, + status, + ) + return status, _logger + + # the cudagraph managed tensors which died upon recording must also die upon + # this invocation. it is too late to check after we've replayed the graph, + # because we would have already written over their memory. + for idx in self.cudagraph_managed_idxs: + if not self.preserved_aliased_inputs[idx]: + inputs[idx] = None # type: ignore[call-overload] + + torch._check( + self._check_liveness( + self.expected_dead_indices_after_graph, self.path_weakrefs + ), + lambda: "TODO: graph recording observed an input tensor deallocate during graph " + " recording that did not occur during replay. Please file an issue.", + ) + return CheckInvariantStatus.SUCCESS, lambda: f"{CheckInvariantStatus.SUCCESS}" + + def num_descendants(self) -> int: + "Total number of descendents of this node" + num_desc = 0 + for children in self.children.values(): + for child in children: + num_desc += 1 + num_desc += child.num_descendants() + return num_desc + + +def canonical_path_output_index( + node: CUDAGraphNode | CUDAWarmupNode, depth: int, idx: int +) -> PathOutputIndex: + if isinstance(node, CUDAGraphNode): + alias_info = node.output_storage_alias[idx] + if isinstance(alias_info, AliasesPriorGraphOutput): + return alias_info.index + if isinstance(alias_info, AliasesNewOutput): + return (depth, alias_info.index) + return (depth, idx) + + +def collect_path_user_visible_storage_groups( + path: tuple[CUDAGraphNode | CUDAWarmupNode, ...], +) -> tuple[PathUserVisibleStorageGroup, ...]: + """Return path storage-alias groups for user-visible output cloning. + + Starts from user-visible outputs, then includes outputs on the same path + that may alias those outputs by recorded storage pointer or alias metadata. + This is cached per node path so aliases discovered on a different tree path + do not affect the current generation transition. + """ + selected_outputs: OrderedSet[PathOutputIndex] = OrderedSet() + selected_alias_outputs: OrderedSet[PathOutputIndex] = OrderedSet() + selected_data_ptrs: OrderedSet[int] = OrderedSet() + + # First, collect storage pointers and canonical outputs referenced by + # user-visible outputs. + for depth, node in enumerate(path): + for idx in node.user_visible_output_idxs: + if idx >= len(node.outputs_weakrefs): + raise AssertionError( + "expected user_visible_output_idxs to index outputs_weakrefs" + ) + selected_outputs.add((depth, idx)) + selected_alias_outputs.add(canonical_path_output_index(node, depth, idx)) + + storage_ref = node.outputs_weakrefs[idx] + if storage_ref is not None: + selected_data_ptrs.add(storage_ref.data_ptr()) + + # Then, collect outputs that may alias a user-visible output. + for depth, node in enumerate(path): + for idx, storage_ref in enumerate(node.outputs_weakrefs): + output_index = (depth, idx) + + alias_index = canonical_path_output_index(node, depth, idx) + if ( + output_index in selected_outputs + or alias_index in selected_alias_outputs + or storage_ref is not None + and storage_ref.data_ptr() in selected_data_ptrs + ): + selected_outputs.add(output_index) + + entries_by_data_ptr: dict[int, list[PathUserVisibleOutputEntry]] = {} + for depth, idx in selected_outputs: + node = path[depth] + output_weakrefs = node.outputs_weakrefs + storage_ref = output_weakrefs[idx] + if storage_ref is None: + continue + + cached_tensor_outputs = ( + node.cached_tensor_outputs if isinstance(node, CUDAGraphNode) else None + ) + data_ptr = storage_ref.data_ptr() + entries_by_data_ptr.setdefault(data_ptr, []).append( + ( + output_weakrefs, + node.tensor_weakrefs, + cached_tensor_outputs, + idx, + ) + ) + + return tuple(tuple(entries) for entries in entries_by_data_ptr.values()) + + +def get_cudagraph_segments(pool_id: tuple[int, int]) -> Any: + segments = torch.cuda.memory_snapshot() + return [segment for segment in segments if segment["segment_pool_id"] == pool_id] + + +def get_block_addrs(pool_id: tuple[int, int], live_only: bool = True) -> list[int]: + blocks = [] + + for segment in get_cudagraph_segments(pool_id): + addr = segment["address"] + for block in segment["blocks"]: + if block["state"] == "active_allocated" or not live_only: + blocks.append(addr) + + addr += block["size"] + + return blocks + + +def format_tb(frames: list[Any]) -> str: + formatted_traceback = [ + traceback.FrameSummary(entry["filename"], entry["line"], entry["name"]) + for entry in frames + ] + + return "".join(traceback.format_list(formatted_traceback)) + + +def check_memory_pool( + device: int, + pool_id: tuple[int, int], + live_storages_ptrs: list[StorageWeakRefWrapper], +) -> None: + """Validate cudagraph pool allocations against tracked live storages and surface leaks.""" + if not all(isinstance(elem, StorageWeakRefWrapper) for elem in live_storages_ptrs): + raise AssertionError( + "expected all live_storages_ptrs to be StorageWeakRefWrapper" + ) + unique_storages = {stor.data_ptr() for stor in live_storages_ptrs if stor()} # noqa: set_linter + + # check if there is a divergence first, then do the expensive snapshot call after + # we know it will error + if torch._C._cuda_checkPoolLiveAllocations(device, pool_id, unique_storages): + return + + # at this point we are past the fast-path. we have seen rare cases where a dead tensor is dead, + # but hasn't been gc'd yet, and gives false positive for allocated_not_in_live_storages + gc.collect() + torch.cuda.synchronize() + + segments = get_cudagraph_segments(pool_id) + + allocated_not_in_live_storages = {} + + for segment in segments: + addr = segment["address"] + for block in segment["blocks"]: + if block["state"] == "active_allocated": + if addr not in unique_storages: + allocated_not_in_live_storages[addr] = block + else: + unique_storages.remove(addr) + + addr += block["size"] + + torch._check( + len(unique_storages) == 0, + lambda: ( + f"These storage data ptrs are not allocated in pool {pool_id} but should be: {unique_storages}. " + f"This could be a bug in inductor aliasing tracking or in a custom op's meta function. Please file an issue." + ), + ) + + if len(allocated_not_in_live_storages) != 0: + formatted = [] + for dp, block in allocated_not_in_live_storages.items(): + trace = format_tb(block.get("frames", [])) + # pyrefly: ignore [bad-argument-type] + formatted.append(f"Data Pointer: {dp}, history: \n{trace}") + formatted_s = "\n".join(formatted) + + history_hint = "" + if not config.triton.cudagraph_trees_history_recording: + history_hint = "- Set torch._inductor.config.triton.cudagraph_trees_history_recording = True for allocation origins\n" + + objgraph_hint = ( + ( + "- Objgraph backrefs disabled; set torch._inductor.config.triton.cudagraph_trees_objgraph = True " + "(refs_live_tensor_{index}.svg)\n" + ) + if not config.triton.cudagraph_trees_objgraph + else "" + ) + objgraph_files_hint = "" + + if config.triton.cudagraph_trees_objgraph: + # pyrefly: ignore # import-error + import objgraph + + generated_files: list[str] = [] + + tensors = objgraph.by_type("torch.Tensor") + for index, bad_dp in enumerate(allocated_not_in_live_storages): + bad_tensor = next( + (t for t in tensors if bad_dp in collect_cuda_data_ptrs(t)), None + ) + if bad_tensor is None: + continue + filename = f"refs_live_tensor_{index}.svg" + objgraph.show_backrefs(bad_tensor, filename=filename, max_depth=5) + generated_files.append(filename) + if generated_files: + objgraph_files_hint = ( + f"- Objgraph backrefs written: {', '.join(generated_files)}\n" + ) + + dangling_addrs = OrderedSet(allocated_not_in_live_storages.keys()) + msg = ( + f"Detected {len(allocated_not_in_live_storages)} tensor(s) in the cudagraph pool not tracked as outputs. " + f"All live allocations must be tracked for correctness.\n" + f"Debugging:\n" + f"{history_hint}" + f"{objgraph_hint}" + f"- Search gc.get_objects() for tensors with data_ptr() in {dangling_addrs}\n" + f"- Use refcycle to find what is preventing cleanup\n" + f"{objgraph_files_hint}" + f"Allocations:\n{formatted_s}" + ) + raise RuntimeError(msg) + + +class ExecutionState(Enum): + """ + Represents the state of the CUDAGraph Tree. Will be None if there is no live current memory allocated + in the cuda graph pool. Otherwise will reflect the state of the most recently executed node. + """ + + NONE = auto() + WARMUP = auto() + RECORDING = auto() + EXECUTION = auto() + + +class CompilationMode(Enum): + FORWARD = auto() + BACKWARD = auto() + INFERENCE = auto() + + +class CUDAGraphTreeManager: + """ + Groups individual recordings or executions of cuda graphs into a tree of recordings, + and checks required invariants, and manages warmups of graphs. + + When graphs are recorded in the same tree, it enforces subsequent execution + to follow the same order and have the same output tensor livespans. To remove + unnecessary coupling of cuda graphs (and additional imposed invariants), + the tree manager will end a currently recording tree whenever it is valid - when + the memory pool no longer has any live allocations. + + We ignore outputs from a previous generation that correspond to prior model outputs. + Currently this is hardcoded `GenerationTracker.generation` tracked in torch dynamo. + # TODO: make generation increment configurable, warn on overwrite. + + We run graph warmups in the cudagraph memory pool and return the result on the first invocation + of a function. For many models it is important to reclaim activations as you run the backward. + If we were to warm up the model and keep an extra copy of the inputs around to subsequently + use for recording, we would incur a memory penalty. Additionally, if we are part way through training + your model and need to recompile, memory will be allocated to the cuda graph pool, so we run this + warmup run in the cuda graph memory pool. As for recording, warm up needs the state of live tensors + to be accurately reflected so we checkpoint the allocator state if we need to warm up following graph + replay. + """ + + def __init__(self, device_index: int) -> None: + # roots are functions which have no dependencies on an other node. I.e., + # when they are first invoked, none of their inputs are outputs are outputs + # of another node, nor are there any live outputs of another node whose + # liveness would create a dependency. + self.roots: dict[FunctionID, list[CUDAGraphNode]] = defaultdict(list) + + # mapping from function id to wrapped function + self.ids_to_funcs: dict[FunctionID, WrappedFunction] = {} + + self.ids_to_stack_traces: dict[FunctionID, StackTraces | None] = {} + + self.warmed_up_functions: OrderedSet[FunctionID] = OrderedSet() + # if we fail to increment generation, and are stuck warming up, + # only warn on each function once + self.warned_functions: OrderedSet[FunctionID] = OrderedSet() + torch._C._set_cached_tensors_enabled(True) + + # warn only once if a function mutates inputs + self.warned_mutation: OrderedSet[FunctionID] = OrderedSet() + + # NB: cuda caching allocator will remember the stream a segment is allocated to + # and only allocate that segment to the same stream. we need to use a single stream + # for all allocations to the memory pool, otherwise the allocations to separate streams + # will not be reused; separate recordings would have use the same memory pool, but not + # the same memory. + + with graph_capture_lock, torch.cuda.device(device_index): + torch.cuda.synchronize() + self.stream = torch.cuda.Stream() + self.stream.wait_stream(torch.cuda.current_stream()) + + # Keeps Memory Pool Alive + self.graph: torch.cuda.CUDAGraph | None = torch.cuda.CUDAGraph() + self.cuda_graphs_thread_pool = torch.cuda.graph_pool_handle() + + with ( + warnings.catch_warnings(record=True), + torch.cuda.graph( + self.graph, + pool=self.cuda_graphs_thread_pool, + stream=self.stream, + capture_error_mode="thread_local", + ), + ): + pass + + self.graph_counter = itertools.count(0) + self.func_counter = itertools.count(0) + + # mapping from graph_id to (function id to mutation type hint) since we are + # specializing on a particular combination of Parent Node -> Function ID. + self.non_cudagraph_managed_mutation_hint: dict[ + GraphID | None, dict[FunctionID, bool] + ] = defaultdict(dict) + self.warmup_node_counter = itertools.count(start=-1, step=-1) + + # mapping from graph_id to (function id to re-record count). We fall back to + # eager function if a function is re-recorded frequently on a node. + self.num_rerecord: dict[GraphID | None, dict[FunctionID, int]] = defaultdict( + lambda: defaultdict(lambda: 0) + ) + + # whether we the current node is in a state of warmup, recording, execution. If + # there is no current node the state will be ExecutionState.None. + self.path_state = ExecutionState.NONE + self.active_warmup_function: FunctionID | None = None + self.device_index = device_index + + # the most recently invoked cudagraph wrapping of a function. Will be None + # when there is no output from a previous recording or execution whose memory + # we need to respect in the cuda caching allocation. If you incremented generation, + # this will also be none, as ignore those allocations. + self.current_node: CUDAGraphNode | CUDAWarmupNode | None = None + + # current generation of cudagraph invocations. when torch.compile is run + # we increment the current generation. are willing to ignore live outputs + # of a previous generation in checking liveness. + self.current_gen: int = -1 + + # number of instances we are in execution and failed to match to an + # existing child + self.debug_fail_counter = 0 + # number of instances we had to checkpoint the function + self.debug_checkpointing_counter = 0 + + self.id_to_mode: dict[FunctionID, CompilationMode] = {} + self.id_to_compile_id: dict[FunctionID, CompileId | None] = {} + self.has_live_user_visible_output_cloning = False + + # Note: [Backward Generation Handling] + # We generally perform a sequence of forward executions followed by backward executions. + # If multiple torch.compile wrapped forwards are executed with their backwards pending, + # we should not disregard the outputs from a prior torch.compile since the entire training + # loop hasn't completed. Occasionally, a backward pass corresponding to a forward pass may + # not be executed, so we cannot wait for all pending forward pass backward completions, so + # we cannot wait for all backwards to have been invoked. Instead we wait for a single backward + # invocation. Triggering a backward pass typically doesn't lead to another torch.compile + # invocation, making it less likely for the generation to increase between multiple + # backward calls. The following use case is covered by this approach: + # mod1 = torch.compile(...) + # mod2 = torch.compile(...) + # mod2(mod1(x)).sum().backward() + + self.running_forwards_with_pending_backwards = False + self.mode: CompilationMode | None = None + + self.disable_invalidate_aliases = ( + False + if not torch._environment.is_fbcode() + else torch._utils_internal.justknobs_check( + "pytorch/inductor:disable_cudagraph_alias_invalidation" + ) + ) + + def run(self, new_inputs: list[InputType], function_id: FunctionID) -> OutputType: + if self.graph is None: + raise AssertionError("Running CUDAGraph after shutdown") + self.mode = self.id_to_mode[function_id] + self.compile_id = self.id_to_compile_id[function_id] + out = self._run(new_inputs, function_id) + + # The forwards are only pending following invocation, not before + if self.mode == CompilationMode.FORWARD: + self.running_forwards_with_pending_backwards = True + elif self.mode == CompilationMode.BACKWARD: + self.running_forwards_with_pending_backwards = False + + return out + + def set_to_running_backward(self) -> None: + self.running_forwards_with_pending_backwards = False + self.mode = CompilationMode.BACKWARD + + def _get_cuda_graph_recorded_tensor_checker(self) -> Callable[[Tensor], bool]: + return ( + self.current_node._is_cuda_graph_recorded_tensor + if isinstance(self.current_node, (CUDAGraphNode, CUDAWarmupNode)) + else lambda _: False + ) + + def new_warmup_node_id(self) -> GraphID: + return GraphID(next(self.warmup_node_counter)) + + def _update_non_cudagraph_managed_mutation( + self, function_id: FunctionID, inputs: list[InputType] + ) -> None: + node_id = self._get_node_id() + if maybe_mutation_str := check_for_mutation( + self.ids_to_funcs[function_id], + inputs, + self._get_cuda_graph_recorded_tensor_checker(), + ): + self.non_cudagraph_managed_mutation_hint[node_id][function_id] = True + # warn once per function_id + if function_id in self.warned_mutation: + return + self.warned_mutation.add(function_id) + log_cudagraph_skip_and_bump_counter(maybe_mutation_str) + else: + self.non_cudagraph_managed_mutation_hint[node_id][function_id] = False + + def _get_node_id(self) -> GraphID | None: + if self.current_node is None: + return None + elif isinstance(self.current_node, (CUDAGraphNode, CUDAWarmupNode)): + return self.current_node.id + else: + raise RuntimeError(f"Unknown node type {type(self.current_node)}") + + def exceed_rerecord_limit( + self, node_id: GraphID | None, function_id: FunctionID + ) -> bool: + return ( + self.num_rerecord[node_id][function_id] + > torch._inductor.config.triton.cudagraph_unexpected_rerecord_limit + ) + + def _run(self, new_inputs: list[InputType], function_id: FunctionID) -> OutputType: + # we will try to end the current execution lazily, since + # we don't want to do unnecessary checking of the existing outputs + # on the hot path, but both recording and warmup only happen once + # so we check up front + if self.in_recording: + self.try_end_curr_recording(function_id) + + if self.in_warmup: + self.try_end_curr_warmup(function_id) + + if ( + self.has_live_user_visible_output_cloning + and self.path_state == ExecutionState.EXECUTION + ): + curr_generation = self.get_curr_generation() + # current_node is cleared lazily, so the first invocation in a new + # generation may still see children from the previous generation. + # Enforce the existing generation boundary before matching children. + if self.in_new_torch_compile_invocation(curr_generation): + self.try_end_curr_execution( + curr_generation, + skip_dead_output_cleanup=True, + ) + + node_id = self._get_node_id() + if function_id not in self.non_cudagraph_managed_mutation_hint[node_id]: + self._update_non_cudagraph_managed_mutation(function_id, new_inputs) + + # Early exit if the function mutates inputs which are neither parameters/buffers nor + # cudagraph recorded tensors. This check should happen after `try_end_curr_recording` + # and `try_end_curr_warmup` which may change self.current_node. + if self.non_cudagraph_managed_mutation_hint[node_id][ + function_id + ] or self.exceed_rerecord_limit(node_id, function_id): + return self.ids_to_funcs[function_id].model(new_inputs) + + # warming up a function and subsequentally recording may use different memory addresses + # because both depend on the state of the caching allocator. if we warm up graph A, + # then warm up graph B and make more allocations, the subsequent recording of A will not + # necessarily use the same addresses as in the warm up. Thus any warm up of a node can only + # be followed by warm up runs. + if ( + ( + not ( + function_id in self.warmed_up_functions + or config.triton.skip_cudagraph_warmup + ) + ) + or self.in_warmup + or config.triton.force_cudagraphs_warmup + ): + # If we are in the middle of executing cuda graphs, then we need to checkpoint memory state. + # Both Recording and Warmup will be reflected in the allocator and don't need changes + if self.path_state == ExecutionState.EXECUTION: + self.apply_checkpoint_execution_state_in_allocator() + + with graph_capture_lock: + return self.run_eager(new_inputs, function_id) + + if isinstance(self.current_node, CUDAWarmupNode): + raise AssertionError("expected current_node to not be a CUDAWarmupNode") + child_nodes = ( + self.roots if self.current_node is None else self.current_node.children + ) + + if not self.in_recording: + unexpected_rerecord = False + unexpected_rerecord_reason = None + for child in child_nodes[function_id]: + # here we are checking memory consistency between recording and execution, + # as well as things like stability of tensor locations, etc + # and other + status, status_logger = child.check_invariants(new_inputs) + if status == CheckInvariantStatus.SUCCESS: + return self.execute_node(child, new_inputs) + + if status != CheckInvariantStatus.SUCCESS: + # StaticInputIdxMismatch fires on non-cudagraph-managed + # static inputs (nn parameters and mark_static_address + # tensors) whose identity can churn under + # inline_inbuilt_nn_modules. We re-record but don't count + # those toward cudagraph_unexpected_rerecord_limit. All + # other mismatch reasons do count. + if status != CheckInvariantStatus.StaticInputIdxMismatch: + unexpected_rerecord = True + # Only compute detailed reason when debug logging is enabled + if log.isEnabledFor(logging.DEBUG): + unexpected_rerecord_reason = status_logger() + log.debug( + "[%s] Re-recording function=%s, mode=%s, reason=%s", + self.compile_id, + self.get_func_name(function_id), + self.id_to_mode[function_id].name, + unexpected_rerecord_reason, + ) + else: + # Defer reason computation until needed (for exceed_rerecord_limit) + unexpected_rerecord_reason = status_logger + + # now that we know the new function can't be run as a child of the + # current node, if it is a root, try to end the current execution. + # as noted above, we want to do this lazily to avoid having to + # check all existing outputs + if self.current_node is not None and function_id in self.roots: + self.try_end_curr_execution() + + # run again to hit the root matching case which must succeed + if self.current_node is None: + return self.run(new_inputs, function_id) + + if len(self.ids_to_funcs[function_id].mutated_input_idxs) > 0: + self._update_non_cudagraph_managed_mutation(function_id, new_inputs) + if self.non_cudagraph_managed_mutation_hint[self._get_node_id()][ + function_id + ]: + return self.ids_to_funcs[function_id].model(new_inputs) + + # nb: run before checkpointing because checkpointing is slow, and we will + # be using the eager caching allocator pool which does not require live + # accounting of tensors in cudagraph allocator + if unexpected_rerecord: + curr_node_id = self._get_node_id() + self.num_rerecord[curr_node_id][function_id] += 1 + if self.exceed_rerecord_limit(curr_node_id, function_id): + _id = curr_node_id.id if curr_node_id else None + # unexpected_rerecord_reason is either a string (if debug was enabled) + # or a callable (if debug was disabled) + if unexpected_rerecord_reason is None: + raise AssertionError( + "expected unexpected_rerecord_reason to not be None" + ) + reason = ( + unexpected_rerecord_reason + if isinstance(unexpected_rerecord_reason, str) + else unexpected_rerecord_reason() + ) + log_cudagraph_skip_and_bump_counter( + f"skipping cudagraph due to function {function_id.id} exceeding max " + f"re-recording limit " + f"(={torch._inductor.config.triton.cudagraph_unexpected_rerecord_limit}) " + f"on cudagraph node {_id} due to {reason}." + ) + return self.ids_to_funcs[function_id].model(new_inputs) + + # at this point, we necessarily will do a new recording + self.debug_fail_counter += 1 + + self.try_end_curr_execution() + if self.current_node is not None: + self.apply_checkpoint_execution_state_in_allocator() + + # now, we are in a recording state ! + with graph_capture_lock: + return self.record_function(new_inputs, function_id) + + def shutdown(self) -> None: + """ + Remove all cached tensors in all nodes. Because cached tensors can hold gradients which in turn + might reference a backward which invokes a CUDA Graph Node, we have to manually clear them on shutdown + to avoid a reference cycle. + """ + nodes = [] + for roots in self.roots.values(): + nodes.extend(roots) + + while nodes: + node = nodes.pop() + for children in node.children.values(): + nodes.extend(children) + node.remove_node_cached_tensors() + node.graph = None + + self.graph = None + self.roots = None # type: ignore[assignment] + self.current_node = None + + def record_function( + self, new_inputs: list[InputType], function_id: FunctionID + ) -> OutputType: + if isinstance(self.current_node, CUDAWarmupNode): + raise AssertionError("expected current_node to not be a CUDAWarmupNode") + with torch._dynamo.callback_handler.install_callbacks( + CallbackTrigger.CUDAGRAPH_RECORDING, str(self.compile_id) + ): + graph_id = self.new_graph_id() + log.debug( + "[%s] Recording function=%s, mode=%s, cuda_graph_id=%d, inputs: %s", + self.compile_id, + self.get_func_name(function_id), + self.id_to_mode[function_id].name, + graph_id.id, + format_inputs_log(new_inputs), + ) + torch.cuda.synchronize() + node = CUDAGraphNode( + self.ids_to_funcs[function_id], + graph_id, + self.current_node, + new_inputs, + self.cuda_graphs_thread_pool, + self.device_index, + self.ids_to_stack_traces[function_id], + self.stream, + self.mode, + self.compile_id, + ) + if self.current_node is None: + self.roots[function_id].append(node) + else: + self.current_node.add_child(function_id, node) + self.current_node = node + self.path_state = ExecutionState.RECORDING + self.update_generation() + torch.cuda.synchronize() + return node.run_first_inputs(new_inputs) + + def execute_node( + self, node: CUDAGraphNode, new_inputs: list[InputType] + ) -> OutputType: + self.current_node = node + self.path_state = ExecutionState.EXECUTION + self.update_generation() + return node.run(new_inputs) + + def run_eager( + self, new_inputs: list[InputType], function_id: FunctionID + ) -> OutputType: + # this is only stored on current node, because when we start a new path, + # we will deallocate it + already_warm = function_id in self.warmed_up_functions + func_name = self.get_func_name(function_id) + if not already_warm: + log.debug( + "[%s] Running warmup function=%s, mode=%s", + self.compile_id, + func_name, + self.id_to_mode[function_id].name, + ) + else: + log.debug( + "[%s] Running eager function=%s", + self.compile_id, + func_name, + ) + self.warmed_up_functions.add(function_id) + node = CUDAWarmupNode( + self.ids_to_funcs[function_id], + self.current_node, + self.cuda_graphs_thread_pool, + self.graph, + self.device_index, + self.ids_to_stack_traces[function_id], + self.stream, + already_warm, + self.new_warmup_node_id(), + ) + self.current_node = node + self.path_state = ExecutionState.WARMUP + self.update_generation() + self.active_warmup_function = function_id + result = node.run(new_inputs) + self.active_warmup_function = None + return result + + def mark_warmup_incomplete(self) -> None: + if self.active_warmup_function is not None: + self.warmed_up_functions.discard(self.active_warmup_function) + + def new_graph_id(self) -> GraphID: + return GraphID(next(self.graph_counter)) + + def new_func_id(self) -> FunctionID: + return FunctionID(next(self.func_counter)) + + def get_func_name(self, function_id: FunctionID) -> str: + return getattr(self.ids_to_funcs[function_id].model, "__name__", "unknown") + + def add_function( + self, + model: ModelType, + inputs: list[InputType], + static_input_idxs: Sequence[int], + stack_traces: StackTraces | None, + mode: CompilationMode, + constants: tuple[torch.Tensor, ...], + placeholders: tuple[PlaceholderInfo, ...], + mutated_input_idxs: tuple[int, ...], + kernel_free_cudagraph: bool, + user_visible_output_idxs: tuple[int, ...], + compile_id: CompileId | None, + ) -> tuple[ + ModelType, + OutputType, + ]: + id = self.new_func_id() + if mode == CompilationMode.BACKWARD: + user_visible_output_idxs = () + user_visible_output_idxs_set = frozenset(user_visible_output_idxs) + if user_visible_output_idxs_set: + self.has_live_user_visible_output_cloning = True + self.ids_to_stack_traces[id] = stack_traces + self.ids_to_funcs[id] = WrappedFunction( + model, + list(static_input_idxs), + id, + tuple(t for t in constants if isinstance(t, torch.Tensor) and t.is_cuda), + placeholders, + mutated_input_idxs, + kernel_free_cudagraph, + user_visible_output_idxs_set, + ) + self.id_to_mode[id] = mode + self.id_to_compile_id[id] = compile_id + fn = functools.partial(self.run, function_id=id) + + # container needs to set clean up when fn dies + get_container(self.device_index).add_strong_reference(fn) + return fn, fn(inputs) + + @property + def in_recording(self) -> bool: + return self.path_state == ExecutionState.RECORDING + + @property + def in_warmup(self) -> bool: + return self.path_state == ExecutionState.WARMUP + + def get_roots(self) -> Iterator[CUDAGraphNode]: + for nodes in self.roots.values(): + yield from nodes + + @property + def current_node(self) -> CUDAGraphNode | CUDAWarmupNode | None: + return self._current_node + + @current_node.setter + def current_node(self, value: CUDAGraphNode | CUDAWarmupNode | None) -> None: + self._current_node = value + if value is None: + self.path_state = ExecutionState.NONE + + def update_generation(self) -> None: + self.current_gen = self.get_curr_generation() + + @staticmethod + def get_curr_generation() -> int: + if MarkStepBox.mark_step_counter != 0: + return MarkStepBox.mark_step_counter + + return GenerationTracker.generation + + @staticmethod + def user_invoked_mark_step() -> bool: + return MarkStepBox.mark_step_counter != 0 + + def can_start_new_generation(self, curr_generation: int | None = None) -> bool: + if not self.in_new_torch_compile_invocation(curr_generation): + return False + + if self.user_invoked_mark_step(): + return True + + return not self.running_forwards_with_pending_backwards + + def in_new_torch_compile_invocation( + self, curr_generation: int | None = None + ) -> bool: + if curr_generation is None: + curr_generation = self.get_curr_generation() + return self.current_gen != curr_generation + + def _clone_current_path_live_user_visible_outputs(self) -> None: + if self.current_node is None: + raise AssertionError("expected current_node to not be None") + path_user_visible_storage_groups = ( + self.current_node.path_user_visible_storage_groups + ) + if not path_user_visible_storage_groups: + return + + storages_to_clone: list[ + tuple[StorageWeakRefPointer, PathUserVisibleStorageGroup] + ] = [] + + for output_entries in path_user_visible_storage_groups: + for ( + output_weakrefs, + _tensor_weakrefs, + _cached_tensor_outputs, + idx, + ) in output_entries: + storage_and_ptr = maybe_deref(output_weakrefs[idx]) + if storage_and_ptr is not None: + storage_ptr, _data_ptr = storage_and_ptr + storages_to_clone.append((storage_ptr, output_entries)) + break + + if storages_to_clone: + self._clone_live_user_visible_storages(storages_to_clone) + + def _clone_live_user_visible_storages( + self, + storages_to_clone: Iterable[ + tuple[ + StorageWeakRefPointer, + PathUserVisibleStorageGroup, + ] + ], + ) -> None: + replacements: list[ + tuple[ + UntypedStorage, + UntypedStorage, + PathUserVisibleStorageGroup, + ] + ] = [] + + with torch.cuda.device(self.device_index): + source_tensors = [] + replacement_tensors = [] + + for storage_ptr, entries in storages_to_clone: + source_storage = torch.UntypedStorage._new_with_weak_ptr(storage_ptr) + replacement = torch.empty( + (source_storage.nbytes(),), + dtype=torch.uint8, + device=source_storage.device, + ) + replacement_storage = replacement.untyped_storage() + source_tensors.append( + torch.empty( + (), dtype=torch.uint8, device=source_storage.device + ).set_(source_storage, 0, (source_storage.nbytes(),), (1,)) + ) + replacement_tensors.append(replacement) + replacements.append((source_storage, replacement_storage, entries)) + + torch._foreach_copy_(replacement_tensors, source_tensors) + + for source_storage, replacement_storage, entries in replacements: + # pyrefly: ignore[missing-attribute] + source_storage._swap_data_ptr_(replacement_storage) + placeholder_weakrefs = [ + replacement_storage._weak_ref() for _ in entries + ] + + # Warmup/recording storages own the graph-pool block after + # the swap. Reconstructed replay storages are non-owning. + if torch._C._has_Standard_Deleter(replacement_storage._cdata): + torch._C._free_And_Remove_DeleterFn(replacement_storage._cdata) + torch._C._set_storage_data_ptr_access_error_msg( + replacement_storage._cdata, + "CUDAGraph output storage was cloned before a new generation.", + ) + + for ( + output_weakrefs, + tensor_weakrefs, + cached_tensor_outputs, + idx, + ), placeholder_weakref in zip( + entries, placeholder_weakrefs, strict=True + ): + cached_t = ( + cached_tensor_outputs[idx] if cached_tensor_outputs else None + ) + output_ref = cast(StorageWeakRefWrapper, output_weakrefs[idx]) + tensor_weakrefs[idx] = None + output_ref.remove_extra_reference() + output_ref.swap_weakref(placeholder_weakref) + + if cached_tensor_outputs is not None and cached_t is not None: + torch._C._remove_cached_tensor(cached_t) + cached_tensor_outputs[idx] = None + + def try_end_curr_recording(self, function_id: FunctionID) -> None: + """ + Check if the current recording can be terminated, either because all outputs of the + previously recorded node are dead or because it was executed in a different + generation. Will set current_node to None and in_recording to False if successful. + """ + if not self.in_recording: + raise AssertionError("expected in_recording to be True") + if self.current_node is None: + raise AssertionError("expected current_node to not be None") + + # multiple invocations, allow overwriting the previous generation + if self.can_start_new_generation(): + self.clear_current_path_state_and_set_to_none( + clone_live_user_visible_outputs=True, + dealloc_current_path_weakrefs=True, + ) + return + + if self.current_node.all_outputs_are_dead(): + self.clear_current_path_state_and_set_to_none() + return + + self.check_warn_on_unable_to_start_executing(function_id) + + def try_end_curr_execution( + self, + curr_generation: int | None = None, + *, + skip_dead_output_cleanup: bool = False, + ) -> None: + """ + Check if the current executing node can be terminated, either because all outputs of the + previously executed node are dead or because it was executed in a different generation. + Will set current_node to None if successful. + """ + + if self.in_recording: + raise AssertionError("expected in_recording to be False") + if self.current_node is None: + return + + if self.can_start_new_generation(curr_generation): + self.clear_current_path_state_and_set_to_none( + clone_live_user_visible_outputs=True + ) + return + + if skip_dead_output_cleanup: + return + + if self.current_node.all_outputs_are_dead(): + self.clear_current_path_state_and_set_to_none() + + def try_end_curr_warmup(self, function_id: FunctionID) -> None: + if self.current_node is None: + raise AssertionError("expected current_node to not be None") + if self.can_start_new_generation(): + self._clone_current_path_live_user_visible_outputs() + self.dealloc_current_path_weakrefs() + self.current_node = None + return + + if self.current_node.all_outputs_are_dead(): + self.current_node = None + return + + self.check_warn_on_unable_to_start_executing(function_id) + + def check_warn_on_unable_to_start_executing(self, function_id: FunctionID) -> None: + "Warn if we in a potential loop where we are unable to hit fast path" + if ( + function_id in self.warned_functions + or not self.in_new_torch_compile_invocation() + ): + return + + if self.current_node is None: + raise AssertionError("expected current_node to not be None") + existing_nodes = [ + node + for node in self.current_node._path_from_root + if node.wrapped_function.id == function_id + ] + + if len(existing_nodes) <= 1: + return + + # repeated same pattern + parents = OrderedSet( + [ + n.parent.wrapped_function.id + for n in itertools.chain(existing_nodes, (self.current_node,)) + if n.parent is not None + ] + ) + if len(parents) == len(existing_nodes): + return + + self.warned_functions.add(function_id) + warnings.warn( + "Unable to hit fast path of CUDAGraphs because outputs from a previous step " + "still require backward. Ensure backward() is invoked or detach outputs. " + "You may also call torch.compiler.cudagraph_mark_step_begin() before each model invocation." + ) + + @staticmethod + def format_dealloc_msg( + stack_trace: str | None, *, is_grad_output: bool = False + ) -> str: + stack_trace = ( + stack_trace.strip() if stack_trace else "[Could not find stack trace]" + ) + if is_grad_output: + return ( + "Error: accessing gradient tensor output of CUDAGraphs that has been overwritten " + f"by a subsequent run. Stack trace: {stack_trace}. " + "This can happen with torch.compile(mode='reduce-overhead') and gradient " + "accumulation when a .grad tensor is allocated during CUDAGraph capture. " + "If you need gradient accumulation, allocate stable .grad buffers outside " + "CUDAGraph capture before the compiled backward runs, for example by running " + "an eager warmup iteration or by preallocating zeroed .grad tensors. " + "If you do not need gradient accumulation, set .grad to None before each backward." + ) + return ( + "Error: accessing tensor output of CUDAGraphs that has been overwritten by a subsequent run. " + f"Stack trace: {stack_trace}. " + "To prevent overwriting, call torch.compiler.cudagraph_mark_step_begin() " + "before each model invocation. If a tensor is a user-visible output " + "that must remain live across generations, manually clone the tensor " + "outside torch.compile(), or set torch._inductor.config.triton." + "cudagraph_trees_generation_cloning = 'user_visible' to clone all " + "user-visible tensors that persist across generations." + ) + + def dealloc_current_path_weakrefs(self) -> None: + if self.current_node is None: + raise AssertionError("expected current_node to not be None") + # TODO: we could also allow the these weak refs to continue to be allocated, + # but that adds some complications. + + stor_dealloc_info: dict[int, tuple[str | None, bool]] = {} + for node in self.current_node._path_from_root: + if node.stack_traces is None: + raise AssertionError("expected node.stack_traces to not be None") + # tensor_weakrefs and stack_traces are paired below with zip(), + # matching the defensive handling for outputs_weakrefs and + # stack_traces. + if len(node.tensor_weakrefs) != len(node.stack_traces): + log.warning( + "tensor_weakrefs length (%d) != stack_traces length (%d)", + len(node.tensor_weakrefs), + len(node.stack_traces), + ) + is_grad_output = ( + self.id_to_mode[node.wrapped_function.id] == CompilationMode.BACKWARD + ) + for t, stack_trace in zip(node.tensor_weakrefs, node.stack_traces): + ten = None if t is None else t() + if ten is None: + continue + + torch._C._set_storage_access_error_msg( + ten, + self.format_dealloc_msg(stack_trace, is_grad_output=is_grad_output), + ) + + # we would to enable the following assertion, but an internal model failed with a command + # that does not repro. len(node.outputs_weakrefs) == len(node.stack_traces) + # so, pessimistically assume that they might differ by doing the debug info + # loop separately from the dealloc loop + if self.disable_invalidate_aliases: + continue + + for storage_ref, stack_trace in zip( + node.outputs_weakrefs, node.stack_traces + ): + if not storage_ref: + continue + + stor_dealloc_info[storage_ref.data_ptr()] = ( + stack_trace, + is_grad_output, + ) + + deleted = OrderedSet[Any]() + for storage_ref in self.current_node.path_live_weakrefs(): + _storage_deref = storage_ref() + if _storage_deref and storage_ref.data_ptr() not in deleted: + deleted.add(storage_ref.data_ptr()) + + stack_trace, is_grad_output = stor_dealloc_info.get( + storage_ref.data_ptr(), (None, False) + ) + msg = self.format_dealloc_msg( + stack_trace, is_grad_output=is_grad_output + ) + torch._C._free_And_Remove_DeleterFn(_storage_deref) + + if self.disable_invalidate_aliases: + continue + + torch._C._set_storage_data_ptr_access_error_msg(_storage_deref, msg) + + def clear_current_path_state_and_set_to_none( + self, + *, + clone_live_user_visible_outputs: bool = False, + dealloc_current_path_weakrefs: bool = False, + ) -> None: + if not isinstance(self.current_node, CUDAGraphNode): + raise AssertionError( + f"expected current_node to be a CUDAGraphNode, got {type(self.current_node)}" + ) + if clone_live_user_visible_outputs: + self._clone_current_path_live_user_visible_outputs() + if dealloc_current_path_weakrefs: + self.dealloc_current_path_weakrefs() + self.current_node.clear_path_state() + self.current_node = None + + def apply_checkpoint_execution_state_in_allocator(self) -> None: + """ + Checkpoint the current execution state in the caching allocator so that + additional cudagraph recordings can be made respecting existent live storages. + """ + if not isinstance(self.current_node, CUDAGraphNode): + raise AssertionError( + f"expected current_node to be a CUDAGraphNode, got {type(self.current_node)}" + ) + self.debug_checkpointing_counter += 1 + log.debug( + "Checkpointing cuda caching allocator state. Number of checkpoints %d", + self.debug_checkpointing_counter, + ) + + state = self.current_node.checkpointed_caching_state + device = self.current_node.device + if not (state is not None and device is not None): + raise AssertionError("expected state and device to not be None") + + # currently we deallocate on instead of allowing stale recordings + stale_storages: list[int] = [] + + # remove cached tensors, otherwise they would prevent memory from being + # reclaimed in subsequent recordings + self.current_node.remove_path_cached_tensors() + live_storages_wrappers = list(self.current_node.path_live_weakrefs()) + + # path_live_weakrefs guarantees that t() will not be None + live_storages_weak_refs: list[int] = [t() for t in live_storages_wrappers] # type: ignore[misc] + ptrs_to_deallocate = self.current_node.data_ptrs_dead_since_invocation() + torch._C._cuda_setCheckpointPoolState( + device, + # pyrefly: ignore [bad-argument-type] + state, + stale_storages, + live_storages_weak_refs, + ) + + # NB: deduplicate aliased outputs + for ptr in OrderedSet(ptrs_to_deallocate): + torch._C._cuda_cudaCachingAllocator_raw_delete(ptr) + + # Now the live blocks should be exactly equal to the live storages in private pool + if config.triton.slow_path_cudagraph_asserts: + check_memory_pool( + self.device_index, self.cuda_graphs_thread_pool, live_storages_wrappers + ) + for wrapper in live_storages_wrappers: + storage_ptr = wrapper() + if storage_ptr is None: + raise AssertionError("expected storage_ptr to not be None") + if not torch._C._has_Standard_Deleter(storage_ptr): + raise AssertionError( + "expected storage_ptr to have standard deleter" + ) + if wrapper.data_ptr() in ptrs_to_deallocate: + raise AssertionError( + "expected wrapper.data_ptr() not in ptrs_to_deallocate" + ) + + def live_cudagraph_pool_storages_in_curr_execution( + self, + ) -> list[StorageWeakRefPointer]: + if self.current_node is None: + return [] + # explicitly ignoring previous recorded outputs from past path + # path_live_weakrefs() guarantees that t() will not be None + return [t() for t in self.current_node.path_live_weakrefs()] # type: ignore[misc] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/cudagraph_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/cudagraph_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..80ca9022be86dfb1ce911af3b4a5557f4453c6be --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/cudagraph_utils.py @@ -0,0 +1,662 @@ +# mypy: disallow-untyped-defs +from __future__ import annotations + +import dataclasses +from collections.abc import Callable +from enum import Enum +from typing import Any, Literal, TYPE_CHECKING, TypeVar + +import torch +from torch._dynamo.utils import counters, get_metrics_context +from torch._inductor.utils import GraphPartitionMap, InputType +from torch._subclasses.fake_tensor import get_plain_tensors, is_fake +from torch.utils._ordered_set import OrderedSet + +from . import config +from .utils import is_using_cudagraph_partition + + +if TYPE_CHECKING: + from collections.abc import Sequence, Set as AbstractSet + + from torch._inductor.output_code import OutputCode + +_OC = TypeVar("_OC", bound="OutputCode") + + +cudagraphs_log = torch._logging.getArtifactLogger(__name__, "cudagraphs") +static_inputs_log = torch._logging.getArtifactLogger( + __name__, "cudagraph_static_inputs" +) + + +OutputType = list[int | torch.Tensor | None] +ModelType = Callable[[list[InputType]], OutputType] + + +def cudagraph_trees_generation_cloning() -> Literal["user_visible"] | None: + mode = config.triton.cudagraph_trees_generation_cloning + if mode not in (None, "user_visible"): + raise AssertionError( + "Expected torch._inductor.config.triton." + "cudagraph_trees_generation_cloning to be None or 'user_visible', " + f"got {mode!r}" + ) + return mode + + +def cudagraph_trees_clone_live_user_visible_outputs() -> bool: + return cudagraph_trees_generation_cloning() == "user_visible" + + +INPUT_STORAGE_MUTATION_TARGETS = ( + torch.ops.aten.set_.default, + torch.ops.aten.set_.source_Storage, + torch.ops.aten.set_.source_Storage_storage_offset, + torch.ops.aten.set_.source_Tensor, + torch.ops.aten.set_.source_Tensor_storage_offset, + torch.ops.aten.shallow_copy_data_.default, +) + + +class CUDAGraphPolicy: + """Pluggable policy controlling CUDA graph wrapping in Inductor's post_compile. + + Override methods to customize: + - HOW compiled functions are cudagraph-wrapped (cudagraphify) + - WHETHER inner CompiledFxGraphs should be wrapped (should_wrap) + - OUTER wrapping of compound outputs like RegionalOutputCode (wrap_output) + + Set via ``torch._inductor.config.cudagraph_policy``. When ``None`` + (the default), the existing built-in behaviour is used unchanged. + + Example usage:: + + class MyCUDAGraphPolicy(CUDAGraphPolicy): + def cudagraphify(self, model, example_inputs, static_input_idxs, **kwargs): + return my_custom_wrapper(model, example_inputs, static_input_idxs) + + + with torch._inductor.config.patch("cudagraph_policy", MyCUDAGraphPolicy()): + compiled_fn = deserialize_artifacts(...) + """ + + def cudagraphify( + self, + model: Callable[..., Any], + example_inputs: Sequence[InputType], + static_input_idxs: Sequence[int], + *, + device_index: int, + is_backward: bool, + is_inference: bool, + **kwargs: Any, + ) -> Callable[..., Any]: + """Wrap a single compiled callable with CUDA graph capture/replay. + + Called by ``cudagraph_post_compile`` for each ``CompiledFxGraph``. + The default delegates to ``compile_fx.cudagraphify`` (cudagraph_trees). + + ``example_inputs`` are the example inputs at post_compile time. + The default implementation does not forward them because + ``compile_fx.cudagraphify`` defers graph recording to the first + real call via an inner closure. Subclasses that need the + example inputs for warmup or static-input detection may use them. + + When ``config.graph_partition=True``, setting a CUDAGraphPolicy + bypasses ``cudagraph_partition_post_compile`` (which wraps each + partition individually) and routes through ``cudagraph_post_compile`` + instead, so this method wraps the *entire* callable, not individual + partitions. Subclasses that need per-partition control should + handle partitioning internally. + """ + from torch._inductor.compile_fx import cudagraphify + + return cudagraphify( + model, + static_input_idxs, + device_index=device_index, + is_backward=is_backward, + is_inference=is_inference, + **kwargs, + ) + + def should_wrap(self, compiled_graph: OutputCode) -> bool: + """Whether to apply cudagraph wrapping to this CompiledFxGraph. + + Called for each inner ``CompiledFxGraph`` during ``post_compile``. + Return ``False`` to skip wrapping (e.g. when wrapping at the outer + level via ``wrap_output`` instead). + + Default: ``True`` (wrap everything, same as current behaviour). + """ + return True + + def wrap_output(self, output_code: _OC) -> _OC: + """Optional outer-level wrapping after inner post_compile completes. + + Called by ``_compile_fx_inner``, ``BundledOutputCodeLoadable.post_compile``, + and ``FxGraphCacheLoadable.post_compile`` on the ``OutputCode`` returned + from ``post_compile``. Subclasses that only want to wrap specific + output types should check ``isinstance`` and return the input + unchanged for types they don't handle. + + Default: identity (no outer wrapping). + """ + return output_code + + +@dataclasses.dataclass(frozen=True, slots=True) +class FunctionID: + "Unique counter of a function wrapped in cudagraphify_impl" + + id: int + + +@dataclasses.dataclass(frozen=True, slots=True) +class PlaceholderInfo: + """ + A serializable version of torch.fx.Node that contains information + pertinent to placeholder stack traces. We use these in logging and error messages + related to cudagraphs, and will cache these results. + """ + + name: str + stack_trace: str | None + # This field is recursive, but never cyclic (since a node never uses itself) + users: list[PlaceholderInfo] + mutating_use_stack_trace: str | None + + +@dataclasses.dataclass(frozen=True, slots=True) +class InputStorageMutationInfo: + input_idxs: OrderedSet[int] + stack_trace: str | None + + +@dataclasses.dataclass(frozen=True, slots=True) +class WrappedFunction: + """ + Represents a function that you want to record for CUDA graph replay, + with a little more metadata so we can identify if we have an applicable + CUDA graph in our CUDA graph tree for it. + """ + + model: Callable[..., Any] + static_input_idxs: Sequence[int] + id: FunctionID + constants: tuple[torch.Tensor, ...] + placeholders: Sequence[PlaceholderInfo] + mutated_input_idxs: Sequence[int] + kernel_free_cudagraph: bool = False + user_visible_output_idxs: frozenset[int] = dataclasses.field( + default_factory=frozenset + ) + + +def get_mutating_use_stack_trace_from_node( + placeholder_node: torch.fx.Node, +) -> str | None: + # reinplaced uses might have a single, non-copy_ use + if len(placeholder_node.users) == 1: + return next(iter(placeholder_node.users)).meta.get("stack_trace", None) + + for use in placeholder_node.users: + if use.target is torch.ops.aten.copy_.default: + if stack_trace := use.meta.get("stack_trace", None): + return stack_trace + + return None + + +def get_mutating_use_stack_trace(placeholder_info: PlaceholderInfo) -> str | None: + return placeholder_info.mutating_use_stack_trace + + +def get_input_storage_mutation_info( + gm: torch.fx.GraphModule, +) -> InputStorageMutationInfo: + placeholders = [node for node in gm.graph.nodes if node.op == "placeholder"] + placeholder_indices = {node: idx for idx, node in enumerate(placeholders)} + storage_mutation_input_idxs: OrderedSet[int] = OrderedSet() + stack_trace: str | None = None + + for node in gm.graph.nodes: + if ( + node.op != "call_function" + or node.target not in INPUT_STORAGE_MUTATION_TARGETS + ): + continue + + mutated_arg = node.args[0] if node.args else None + # Only direct graph-input set_ rebinds the tensor object that lives + # outside this graph. set_ on a temporary view/alias does not rebind the + # input TensorImpl and is handled by the usual mutation checks. + if ( + isinstance(mutated_arg, torch.fx.Node) + and mutated_arg in placeholder_indices + ): + storage_mutation_input_idxs.add(placeholder_indices[mutated_arg]) + if stack_trace is None: + stack_trace = node.meta.get("stack_trace", None) + + return InputStorageMutationInfo(storage_mutation_input_idxs, stack_trace) + + +def get_input_storage_mutation_reason( + storage_mutation_info: InputStorageMutationInfo, +) -> str | None: + storage_mutation_input_idxs = storage_mutation_info.input_idxs + if not storage_mutation_input_idxs: + return None + + msg = f"input storage mutation ({len(storage_mutation_input_idxs)} instances)" + if storage_mutation_info.stack_trace: + return f"{msg}. Found from:\n {storage_mutation_info.stack_trace}" + + return msg + + +def to_placeholder_info(placeholder_node: torch.fx.Node) -> PlaceholderInfo: + name = placeholder_node.name + stack_trace = placeholder_node.meta.get("stack_trace", None) + users = [] + mutating_use_stack_trace = None + # Only recurse to users once, since we only care about user's stack traces + if placeholder_node.op == "placeholder": + users = [to_placeholder_info(i) for i in placeholder_node.users] + mutating_use_stack_trace = get_mutating_use_stack_trace_from_node( + placeholder_node + ) + + return PlaceholderInfo(name, stack_trace, users, mutating_use_stack_trace) + + +def get_placeholder_info(graph: torch.fx.Graph) -> list[PlaceholderInfo]: + return [ + to_placeholder_info(node) for node in graph.nodes if node.op == "placeholder" + ] + + +def format_default_skip_message(reason: str) -> str: + return f"skipping cudagraphs due to {reason}" + + +def get_mutation_stack_trace( + placeholders: Sequence[PlaceholderInfo], + mutation_indices: AbstractSet[int] | Sequence[int], +) -> str: + stack_trace: str | None = "" + + for idx in mutation_indices: + placeholder = placeholders[idx] + if stack_trace := get_mutating_use_stack_trace(placeholder): + break + + msg = format_default_skip_message( + f"mutated inputs ({len(mutation_indices)} instances)" + ) + if stack_trace: + return f"{msg}. Found from : \n {stack_trace}" + + return msg + + +def check_for_mutation( + func: WrappedFunction, + inputs: list[InputType], + is_cuda_graph_recorded_tensor: Callable[[torch.Tensor], bool], +) -> str | None: + # doesn't work for non-trees because the warmup run would apply mutation twice + if torch._inductor.config.triton.cudagraph_trees: + # checking if mutation is only on parameters/static inputs + mutation_indices: Sequence[int] = [ + idx + for idx in func.mutated_input_idxs + if not ( + idx in func.static_input_idxs + or is_cuda_graph_recorded_tensor(inputs[idx]) # type: ignore[arg-type] + ) + ] + else: + mutation_indices = func.mutated_input_idxs + + static_inputs_log.debug( + "check mutation static input indices: %s", func.static_input_idxs + ) + static_inputs_log.debug("check mutation indices: %s", mutation_indices) + + return ( + get_mutation_stack_trace(func.placeholders, mutation_indices) + if mutation_indices + else None + ) + + +def _get_use_stack_trace(node: torch.fx.Node) -> str | None: + for use in node.users: + if stack_trace := use.meta.get("stack_trace", None): + return stack_trace + return None + + +def check_multiple_devices_or_any_cpu_nodes( + device_node_mapping: dict[torch.device, torch.fx.Node], +) -> str | None: + # meta tensors are supported since there is no compute + device_node_mapping.pop(torch.device("meta"), None) + + # dynamo cudagraph does not support graph partition + if is_using_cudagraph_partition(): + # graph partition supports splitting on cpu op. So we can ignore cpu nodes. + device_node_mapping.pop(torch.device("cpu"), None) + + if cpu_node := device_node_mapping.get(torch.device("cpu")): + msg = f"cpu device ({cpu_node.name})" + if stack_trace := _get_use_stack_trace(cpu_node): + return format_default_skip_message(f"{msg}. Found from : \n {stack_trace}") + + return format_default_skip_message(msg) + + if ( + len(device_node_mapping) == 1 + and next(iter(device_node_mapping.keys())).type == "cuda" + ): + return None + + keys_repr = (repr(key) for key in device_node_mapping) + return format_default_skip_message(f"multiple devices: {', '.join(keys_repr)}") + + +def check_caching_allocator_for_cudagraphs() -> str | None: + """Skip cudagraphs when the CUDA/HIP caching allocator is disabled + (via ``torch.cuda.caching_allocator_enable(False)`` or the env-var + bypass ``PYTORCH_NO_(CUDA|HIP)_MEMORY_CACHING``). Cudagraph capture + pools allocations through the caching allocator; with it bypassed, + capture appears to succeed but pool tracking diverges (see + check_memory_pool in cudagraph_trees.py), surfacing as 'storage data + ptrs not allocated in pool ...' at replay time.""" + if ( + torch.cuda.is_available() + # pyrefly: ignore [missing-attribute] + and not torch._C._cuda_cudaCachingAllocator_is_enabled() + ): + return format_default_skip_message( + "cudagraph capture requires the caching allocator; " + "current allocator is uncached" + ) + return None + + +def check_lowering_disable_cudagraph( + device_node_mapping: dict[torch.device, torch.fx.Node], +) -> str | None: + return ( + check_caching_allocator_for_cudagraphs() + or check_multiple_devices_or_any_cpu_nodes(device_node_mapping) + ) + + +def log_cudagraph_skip_and_bump_counter(msg: str) -> None: + cudagraphs_log.warning(msg) + counters["inductor"]["cudagraph_skips"] += 1 + + if torch._inductor.config.triton.cudagraph_or_error: + raise RuntimeError(msg) + + metrics_context = get_metrics_context() + if metrics_context.in_progress(): + metrics_context.set("cudagraph_skip_reason", msg, overwrite=True) + + +@dataclasses.dataclass +class BoxedDeviceIndex: + value: int | None + + def set(self, device_idx: int | None) -> None: + if not (device_idx is None or isinstance(device_idx, int)): + raise AssertionError( + f"expected device_idx to be None or int, got {device_idx!r}" + ) + self.value = device_idx + + +def check_for_mutation_ignore_cuda_graph_managed_tensor( + gm: torch.fx.GraphModule, + mutated_inputs: OrderedSet[str], + mutated_input_idxs: OrderedSet[int], + static_input_idxs: Sequence[int], +) -> str | None: + default_msg = format_default_skip_message("mutated inputs") + + # doesn't work for non-trees because the warmup run would apply mutation twice + if torch._inductor.config.triton.cudagraph_trees: + unique_idxs = OrderedSet(static_input_idxs) + # checking if mutation is only on parameters/static inputs + mutation_indices = [idx for idx in mutated_input_idxs if idx not in unique_idxs] + has_mutation = len(mutation_indices) != 0 + if not has_mutation: + return None + placeholders = get_placeholder_info(gm.graph) + return get_mutation_stack_trace(placeholders, mutation_indices) + + else: + has_mutation = len(mutated_inputs) != 0 + return None if not has_mutation else default_msg + + +def get_placeholder_stack_trace(placeholder: PlaceholderInfo) -> str | None: + """ + Gets the first non-empty stack trace of a placeholder or its users. + """ + if placeholder.stack_trace: + return placeholder.stack_trace + + for user in placeholder.users: + if user.stack_trace: + return user.stack_trace + + return None + + +class CheckInvariantStatus(Enum): + # Check invariant succeeded + SUCCESS = 1 + + # Previously managed data pointers are not stable + CudagraphManagedIdxMismatch = 2 + + # Static tensor input addresses are not stable + StaticInputIdxMismatch = 3 + + # Expected dead indices before graph are live + ExpectedDeadIndicesBeforeGraphMismatch = 4 + + def __str__(self) -> str: + if self.name == "CudagraphManagedIdxMismatch": + return "cudagraph managed tensor data pointer changed" + elif self.name == "StaticInputIdxMismatch": + return "static input data pointer changed" + elif self.name == "ExpectedDeadIndicesBeforeGraphMismatch": + return "expected dead indices before graph are live" + else: + return f"{self.name}: {self.value}" + + +def log_data_ptr_mismatch( + placeholders: Sequence[PlaceholderInfo], + inputs: list[InputType], + recorded_data_ptr: Sequence[int | None], + target_idxs: Sequence[int], + mismatch: CheckInvariantStatus, +) -> str: + """ + Logs the mismatch between input data pointers and recorded data pointers. + This checks only idxs in target_idxs. + """ + if not (len(inputs) == len(recorded_data_ptr) and len(inputs) == len(placeholders)): + raise AssertionError( + "length mismatch between inputs, recorded_data_ptr, and placeholders" + ) + + t_tensors = [inputs[i] for i in target_idxs] + t_data_ptrs = [recorded_data_ptr[i] for i in target_idxs] + error_msg = f"{mismatch}.\n" + for i, (tensor, data_ptr) in enumerate(zip(t_tensors, t_data_ptrs)): + if not isinstance(tensor, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(tensor)}") + index = target_idxs[i] + if tensor.data_ptr() != data_ptr: + placeholder = placeholders[index] + error_msg = ( + f"{error_msg}input name: {placeholder.name}. " + f"data pointer changed from {data_ptr} to {tensor.data_ptr()}. " + f"input stack trace: {get_placeholder_stack_trace(placeholder)}\n" + ) + return error_msg + + +def maybe_warning_due_to_dynamic_shape( + fn_cache: dict[tuple[int, ...], Callable[..., Any]], + new_int_key: Any, +) -> bool: + num_cudagraphs = len(fn_cache.keys()) + 1 + + def warn_msg() -> str: + return ( + "CUDAGraph supports dynamic shapes by recording a new graph for each " + "distinct input size. Recording too many CUDAGraphs may lead to " + f"extra overhead. We have observed {num_cudagraphs} distinct sizes. " + "Please consider the following options for better performance: " + "a) padding inputs to a few fixed number of shapes; or b) set " + "torch._inductor.config.triton.cudagraph_skip_dynamic_graphs=True. " + "Set torch._inductor.config.triton.cudagraph_dynamic_shape_warn_limit=None " + "to silence this warning." + ) + + if ( + torch._inductor.config.triton.cudagraph_dynamic_shape_warn_limit + and num_cudagraphs + > torch._inductor.config.triton.cudagraph_dynamic_shape_warn_limit + ): + cudagraphs_log.warning(warn_msg()) + return True + + return False + + +@dataclasses.dataclass(frozen=True) +class CudagraphCachedInfo: + """ + Info needed to realign inputs + """ + + placeholders: Sequence[PlaceholderInfo] + stack_traces: list[str | None] + user_visible_output_idxs: Sequence[int] + cudagraph_fail_reasons: list[str] + + +@dataclasses.dataclass(frozen=True) +class CudagraphMetadata: + """ + Metadata for recording a CUDA graph. + """ + + placeholders: Sequence[PlaceholderInfo] + static_input_idxs: OrderedSet[int] + mutated_input_idxs: OrderedSet[int] + stack_traces: list[str | None] + user_visible_output_idxs: OrderedSet[int] + constants: dict[str, torch.Tensor] + + +def get_partition_cudagraph_metadata( + partition_map: GraphPartitionMap, + metadata: CudagraphMetadata, +) -> CudagraphMetadata: + """ + Convert the cudagraph metadata at the graph level to the graph partition level, + given the graph partition info (i.e., mapping from partition input/output index + to graph input/output index). + """ + + partition_placeholders = [] + partition_static_input_idxs: OrderedSet[int] = OrderedSet() + partition_mutated_input_idxs: OrderedSet[int] = OrderedSet() + for partition_input_idx, graph_input_idx in enumerate( + partition_map.input_index_mapping + ): + if graph_input_idx in metadata.static_input_idxs: + partition_static_input_idxs.add(partition_input_idx) + + if graph_input_idx in metadata.mutated_input_idxs: + partition_mutated_input_idxs.add(partition_input_idx) + + if graph_input_idx is not None: + placeholder = metadata.placeholders[graph_input_idx] + else: + # create a dummy placeholder info since this partition input is not a graph input + placeholder = PlaceholderInfo( + name=f"partition_{partition_map.id}_placeholder_{partition_input_idx}", + stack_trace=None, + users=[], + mutating_use_stack_trace=None, + ) + partition_placeholders.append(placeholder) + + partition_stack_traces = [] + partition_user_visible_output_idxs: OrderedSet[int] = OrderedSet() + # Graph output metadata must be remapped to the partition output indices + # passed to cudagraphify. + for partition_output_idx, graph_output_idxs in enumerate( + partition_map.output_index_mapping + ): + if not graph_output_idxs: + partition_stack_traces.append(None) + continue + + user_visible_graph_output_idxs = [ + graph_output_idx + for graph_output_idx in graph_output_idxs + if graph_output_idx in metadata.user_visible_output_idxs + ] + stack_trace_idx = ( + user_visible_graph_output_idxs[0] + if user_visible_graph_output_idxs + else graph_output_idxs[0] + ) + partition_stack_traces.append(metadata.stack_traces[stack_trace_idx]) + if user_visible_graph_output_idxs: + partition_user_visible_output_idxs.add(partition_output_idx) + + partition_constants = { + name: metadata.constants[name] for name in partition_map.constant_names + } + + return CudagraphMetadata( + partition_placeholders, + partition_static_input_idxs, + partition_mutated_input_idxs, + partition_stack_traces, + partition_user_visible_output_idxs, + partition_constants, + ) + + +def collect_cuda_data_ptrs(obj: object) -> OrderedSet[int]: + """Debug helper that collects the data pointers of all CUDA tensors in the object.""" + if not isinstance(obj, torch.Tensor): + return OrderedSet() + + ptrs: OrderedSet[int] = OrderedSet() + for base in get_plain_tensors(obj, out=[]): + if type(base) is not torch.Tensor: + continue + if is_fake(base) or base.is_meta or base.device.type != "cuda": + continue + try: + ptrs.add(base.data_ptr()) + except Exception: + pass + return ptrs diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/custom_graph_pass.py b/.venv/lib/python3.12/site-packages/torch/_inductor/custom_graph_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..5de820bd30e796a8dbe015f410c2ffc1d16923d1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/custom_graph_pass.py @@ -0,0 +1,278 @@ +import hashlib +from abc import ABC, abstractmethod +from collections.abc import Callable, Sequence +from functools import lru_cache +from typing import Any, TYPE_CHECKING, TypeAlias + +import torch.fx.graph + + +if TYPE_CHECKING: + from torch._functorch.partitioners import NodeInfo + from torch._inductor.scheduler import BaseSchedulerNode + + +class CustomPassBase(ABC): + """ + Implement this interface for custom passes: + + The uuid() method enables inductor to cache compiled graphs when your custom + passes are applied. This method can return any identifier as long as it uniquely + identifies your implementation (and can be pickled). The caching logic includes this + identifier in its key calculation, i.e., any new value will effectively invalidate + existing entries. We expect custom passes would typically depend purely on the + textual representation of the implementation. In that case, we recommend using the + 'get_hash_for_files' helper below to compute a unique hash from the contents of a + static list of source files, i.e., the source(s) containing the custom pass + implementation. That approach ensures that any change to the implementation will + mean a new uuid. + + ** IMPORTANT ** If your custom pass's behavior depends on some external state, then + you'll need to implement something more complicated (or disable caching). + + EXAMPLE: + + class MyCustomGraphPass(CustomGraphPass): + def __call__(self, graph: torch.fx.graph.Graph) -> None: + # my custom graph optimization pass + # ... + + def uuid(self) -> Optional[Any]: + return get_hash_for_files((__file__,)) + + """ + + @abstractmethod + def uuid(self) -> Any | None: + """ + Return an ID to uniquely identify your custom pass implementation. Return None + to skip inductor code caching entirely. + """ + + +class CustomGraphPass(CustomPassBase): + """ + Implement this interface for custom Graph passes: + + 1) The __call__() method contains the implementation of the custom pass. + + 2) See CustomPassBase.uuid() docstring for implementing the uuid() method. + + EXAMPLE: + + class MyCustomGraphPass(CustomGraphPass): + def __call__(self, graph: torch.fx.graph.Graph) -> None: + # my custom graph optimization pass + # ... + + def uuid(self) -> Optional[Any]: + return get_hash_for_files((__file__,)) + + """ + + @abstractmethod + def __call__(self, graph: torch.fx.graph.Graph) -> None: + """ + Implementation of the custom pass. + """ + + +class CustomGraphModulePass(CustomPassBase): + """ + Implement this interface for custom passes that operate on GraphModule: + + 1) The __call__() method contains the implementation of the custom pass. + + 2) See CustomPassBase.uuid() docstring for implementing the uuid() method. + """ + + @abstractmethod + def __call__(self, gm: torch.fx.GraphModule) -> None: + """ + Implementation of the custom pass. + """ + + +class CustomSchedulerPass(CustomPassBase): + """ + Implement this interface for custom Scheduler passes: + + 1) The __call__() method contains the implementation of the custom pass. + + 2) See CustomPassBase.uuid() docstring for implementing the uuid() method. + """ + + @abstractmethod + def __call__(self, nodes: list["BaseSchedulerNode"]) -> list["BaseSchedulerNode"]: + """ + Implementation of the custom pass. + """ + + +class CustomInferenceAwareGraphPass(CustomGraphPass): + """ + Implement this interface for custom inference aware Graph passes. + """ + + @abstractmethod + def __call__(self, graph: torch.fx.graph.Graph, is_inference: bool) -> None: + """ + Implementation of the custom pass. + """ + + +CustomGraphPassCallable: TypeAlias = ( + CustomGraphPass | Callable[[torch.fx.graph.Graph], None] +) +CustomGraphPassType: TypeAlias = ( + CustomGraphPassCallable + | list[CustomGraphPassCallable] + | tuple[CustomGraphPassCallable, ...] + | None +) + +CustomSchedulerPassCallable: TypeAlias = ( + CustomSchedulerPass + | Callable[[list["BaseSchedulerNode"]], list["BaseSchedulerNode"]] +) + + +def get_custom_graph_passes( + custom_pass: CustomGraphPassType, +) -> tuple[CustomGraphPassCallable, ...]: + if custom_pass is None: + return () + if isinstance(custom_pass, (list, tuple)): + return tuple(custom_pass) + return (custom_pass,) + + +@lru_cache(1) +def get_hash_for_files(paths: tuple[str, ...], extra: str = "") -> bytes: + """ + Helper to compute a unique string by hashing the contents of a list of files. + """ + hasher = hashlib.sha256() + hasher.update(extra.encode("utf-8")) + for path in paths: + with open(path, "rb") as f: + hasher.update(f.read()) + return hasher.digest() + + +class CustomPartitionerFn(CustomPassBase): + """ + Implement this interface for custom partitioner: + + 1) The __call__() method contains the implementation of the custom partitioner. + + 2) See CustomPassBase.uuid() docstring for implementing the uuid() method. + + EXAMPLE: + + from torch._inductor.custom_graph_pass import get_hash_for_files + + class MyCustomPartitionerFn(CustomPartitionerFn): + def __call__( + self, + gm: torch.fx.GraphModule, + joint_inputs: Sequence[object], + **kwargs: Any + ) -> tuple[torch.fx.GraphModule, torch.fx.GraphModule]: + # my custom partitioner implementation + # ... + + def uuid(self) -> Optional[Any]: + return get_hash_for_files((__file__,)) + + """ + + @abstractmethod + def __call__( + self, gm: torch.fx.GraphModule, joint_inputs: Sequence[object], **kwargs: Any + ) -> tuple[torch.fx.GraphModule, torch.fx.GraphModule]: + """ + Implementation of the custom partitioner. + """ + + @abstractmethod + def uuid(self) -> Any | None: + """ + Return an ID to uniquely identify your custom partitioner implementation. + Return None to skip inductor code caching entirely. + """ + + +CustomPartitionerFnType: TypeAlias = CustomPartitionerFn | None + + +class CustomRuntimeEstimator(CustomPassBase): + """ + Implement this interface for custom runtime estimators: + + 1) The __call__() method contains the implementation of the runtime estimation. + + 2) See CustomPassBase.uuid() docstring for implementing the uuid() method. + + EXAMPLE: + + class MyCustomRuntimeEstimator(CustomRuntimeEstimator): + def __call__(self, node: fx.Node) -> float: + # my custom runtime estimation logic + return estimated_runtime + + def uuid(self) -> Optional[Any]: + return get_hash_for_files((__file__,)) + """ + + @abstractmethod + def __call__(self, node: "torch.fx.Node") -> float: + """ + Implementation of the custom runtime estimator. + + Args: + node: An fx.Node object whose runtime is to be estimated. + + Returns: + float: The estimated runtime for the node. + """ + + +class CustomKnapsackSolver(CustomPassBase): + """ + Implement this interface for custom knapsack solvers: + + 1) The __call__() method contains the implementation of the knapsack solver. + + 2) See CustomPassBase.uuid() docstring for implementing the uuid() method. + + EXAMPLE: + + class MyCustomKnapsackSolver(CustomKnapsackSolver): + def __call__( + self, + memory: list[float], + joint_graph: fx.Graph, + max_memory: float, + node_info: NodeInfo, + all_recomputable_banned_nodes: list[fx.Node], + ) -> tuple[list[int], list[int]]: + # my custom knapsack solver logic + return saved_node_idx, recomp_node_idx + + def uuid(self) -> Optional[Any]: + return get_hash_for_files((__file__,)) + """ + + @abstractmethod + def __call__( + self, + memory: list[float], + joint_graph: "torch.fx.Graph", + max_memory: float, + node_info: "NodeInfo", + all_recomputable_banned_nodes: list["torch.fx.Node"], + ) -> tuple[list[int], list[int]]: + """ + Implementation of the custom knapsack solver. + """ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/debug.py b/.venv/lib/python3.12/site-packages/torch/_inductor/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..c1cbcc49f41fbbafccda54b6c06843f7efe481f2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/debug.py @@ -0,0 +1,1612 @@ +import collections +import contextlib +import copy +import dataclasses +import functools +import io +import itertools +import json +import logging +import os +import os.path +import pickle +import pstats +import shutil +import tempfile +import traceback +from collections.abc import Callable, Iterator, Sequence +from typing import Any, IO +from unittest.mock import patch + +import torch +from functorch.compile import draw_graph, get_aot_graph_name, get_graph_being_compiled +from torch import fx +from torch._dynamo.repro.after_aot import save_graph_repro +from torch._dynamo.utils import get_debug_dir +from torch._functorch import config as functorch_config +from torch._inductor import utils +from torch._logging import getArtifactLogger +from torch._logging._internal import trace_structured +from torch._utils_internal import signpost_event +from torch.fx.graph_module import GraphModule +from torch.fx.passes.shape_prop import _extract_tensor_metadata, TensorMetadata +from torch.fx.passes.tools_common import legalize_graph +from torch.types import FileLike +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import tree_leaves, tree_map + +from . import config, ir +from .ir import ExternKernel +from .scheduler import ( + BaseSchedulerNode, + FusedSchedulerNode, + NopKernelSchedulerNode, + OutputNode, + SchedulerNode, +) +from .virtualized import V + + +log = logging.getLogger(__name__) + +# Graph execution tracking for debugging +GRAPH_EXECUTION_ORDER: list[dict[str, object]] | None = None +RECORD_GRAPH_EXECUTION: bool = False +GRAPH_COMPILE_IDS: dict[int, str | None] | None = None + +ir_pre_fusion_log = getArtifactLogger(__name__, "ir_pre_fusion") +ir_post_fusion_log = getArtifactLogger(__name__, "ir_post_fusion") +SchedulerNodeList = list[Any] +BufMeta = collections.namedtuple("BufMeta", ["name", "n_origin"]) +GRAPHVIZ_COMMAND_SCALABLE = ["dot", "-Gnslimit=2", "-Gnslimit1=2", "-Gmaxiter=5000"] +_RAW_DOT_GRAPH_FORMATS = OrderedSet(["dot", "raw"]) + + +@functools.cache +def has_dot() -> bool: + return shutil.which("dot") is not None + + +def _get_graph_output_format(fname: str | None) -> str: + if fname is not None: + _, ext = os.path.splitext(fname) + if ext: + return ext.lstrip(".") + return functorch_config.torch_compile_graph_format + + +def draw_buffers( + nodes: list[BaseSchedulerNode], + print_graph: bool = False, + fname: str | None = None, +) -> None: + """ + Draw a graph in fname. + """ + graph_format = _get_graph_output_format(fname) + if graph_format not in _RAW_DOT_GRAPH_FORMATS and not has_dot(): + log.warning("draw_buffers() requires `graphviz` package") + return + + if fname is None: + fname = get_graph_being_compiled() + + graph = create_fx_from_snodes(nodes) + + for node in graph.nodes: + if "fusion_meta" not in node.meta: + continue + group = node.meta["fusion_meta"].group + if isinstance(group, tuple): + if isinstance(group[1], int): + group = (group[1],) + else: + group = group[1] + elif isinstance(group, str): + # extern / template / nop nodes store a string like "extern" + # as the group instead of a shape tuple. Extract the real + # output shape from the scheduler node's first output buffer. + try: + snode = node.meta["fusion_meta"].snode + size = snode.get_outputs()[0].node.maybe_get_size() + group = tuple(size) if size else () + except Exception: + group = () + + # gather meta data + dtype = None + if isinstance(node, ir.ComputedBuffer): + dtype = node.data.dtype + + metadata = TensorMetadata(group, dtype, None, None, None, None, None) # type: ignore[arg-type] + + node.meta["tensor_meta"] = metadata + + if print_graph: + print(graph) + + gm = GraphModule({}, graph) + legalize_graph(gm) + gm.graph.lint() + draw_graph( + gm, fname, clear_meta=False, dot_graph_shape=config.trace.dot_graph_shape + ) + + +def create_fx_from_snodes(snodes: list[BaseSchedulerNode]) -> fx.Graph: + """ + Creates a FX Graph from a list of SchedulerNode objects. + """ + + def get_fake_func(name: str) -> Callable[..., int]: + def func1(*args: Any) -> int: + return 0 + + func1.__name__ = name + return func1 + + FusionMeta = collections.namedtuple("FusionMeta", ["group", "snode", "type"]) + + buf_to_fx_node = {} + node_to_fx_node = {} + graph = torch.fx.Graph() + first_node = None + + outputs = [] + group: Any = None + # create call_function node for each Buffer and Kernel + # pyrefly: ignore [bad-assignment] + for snode in snodes: + if snode.is_extern(): + node_type = "extern" + group = node_type + elif snode.is_template(): + node_type = "template" + group = node_type + elif isinstance(snode, NopKernelSchedulerNode): + node_type = "nop" + group = node_type + elif isinstance(snode, SchedulerNode): + node_type = "compute" + group = snode.group + elif isinstance(snode, FusedSchedulerNode): + node_type = "fused" + group = snode.group + else: + raise RuntimeError("Unknown node type") + + fused_name = torch._inductor.utils.get_fused_kernel_name( + snode.get_nodes(), "original_aten" + ) + func_name = f"{node_type}: {fused_name}" + node_func = get_fake_func(func_name) + kwargs = {} + if hasattr(snode, "get_device"): + kwargs = {"device": snode.get_device()} + fx_node = graph.call_function(node_func, args=(), kwargs=kwargs) # type: ignore[arg-type] + + def in_output(snode: BaseSchedulerNode | FusedSchedulerNode) -> bool: + if isinstance(snode, FusedSchedulerNode): + return any(in_output(x) for x in snode.snodes) + return any( + isinstance(user.node, OutputNode) + for buf in snode.get_outputs() + for user in buf.users + ) + + if in_output(snode): + outputs.append(fx_node) + name = snode.get_name() + fx_node.name = name + + fx_node.meta["fusion_meta"] = FusionMeta(group, snode, node_type) + + node_to_fx_node[name] = fx_node + for buf in snode.get_outputs(): + buf_to_fx_node[buf.get_name()] = fx_node + + if first_node is None: + first_node = fx_node + + # create edges between nodes + for snode in snodes: + name = snode.get_name() + deps = snode.read_writes.reads + + fx_node = node_to_fx_node[name] + new_args = [] + for dep in deps: + if dep.name in buf_to_fx_node: + dep_node = buf_to_fx_node[dep.name] + else: + with graph.inserting_before(first_node): + dep_node = graph.placeholder(dep.name) + buf_to_fx_node[dep.name] = dep_node + if dep_node == fx_node: # to avoid cycles + continue + new_args.append(dep_node) + + fx_node.args = tuple(new_args) + + graph.output(outputs[0] if len(outputs) == 1 else tuple(outputs)) + return graph + + +def update_orig_fx_node_name_to_buf_name( + nodes: SchedulerNodeList | None, + node_name_to_buf_name: dict[str, str], + parent_buf_name: str | None = None, + n_origins: int = 0, +) -> None: + if nodes is None: + return + for node in nodes: + # for FusedSchedulerNode, traverse recursively into get_nodes() + buf_name = node.get_name() + children_nodes = node.get_nodes() + if children_nodes is not None and len(children_nodes) > 1: + update_orig_fx_node_name_to_buf_name( + children_nodes, + node_name_to_buf_name, + buf_name if parent_buf_name is None else parent_buf_name, + ) + continue + else: + # pyrefly: ignore [bad-argument-type, unsupported-operation] + if not (len(children_nodes) == 1 and children_nodes[0] == node): + raise AssertionError( + "expected a single child node equal to the current node" + ) + + ir_node = node.node + if ir_node is None or ir_node.origins is None: + continue + for origin in ir_node.origins: + node_name = origin.name + # when buf1 and buf2 both have origin=node1 + # we draw node1 according to buf1 + if node_name not in node_name_to_buf_name: + node_name_to_buf_name[node_name] = ( + buf_name if parent_buf_name is None else parent_buf_name + ) + + +def get_node_name_to_buf_meta( + node_name_to_buf_name: dict[str, str], +) -> dict[str, BufMeta]: + buf_name_to_n_node = {} + for node_name, buf_name in node_name_to_buf_name.items(): + if buf_name not in buf_name_to_n_node: + buf_name_to_n_node[buf_name] = OrderedSet([node_name]) + else: + # pyrefly: ignore [missing-attribute] + buf_name_to_n_node[buf_name].add(node_name) + + node_name_to_buf_meta = {} + for node_name, buf_name in node_name_to_buf_name.items(): + n_node = len(buf_name_to_n_node[buf_name]) + node_name_to_buf_meta[node_name] = BufMeta(buf_name, n_node) + return node_name_to_buf_meta + + +def annotate_orig_fx_with_snodes( + gm: torch.fx.GraphModule, + snodes: SchedulerNodeList, +) -> None: + """ + Creates a FX Graph from a list of SchedulerNode objects. + """ + node_name_to_buf_name: dict[str, str] = {} + update_orig_fx_node_name_to_buf_name(snodes, node_name_to_buf_name) + if node_name_to_buf_name is None: + return + node_name_to_buf_meta = get_node_name_to_buf_meta(node_name_to_buf_name) + for node in gm.graph.nodes: + if node.name in node_name_to_buf_meta: + node.meta["buf_meta"] = node_name_to_buf_meta.get(node.name) + + +@contextlib.contextmanager +def enable_aot_logging() -> Iterator[None]: + compile_debug = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1" + + import torch._functorch.aot_autograd + + log = logging.getLogger(torch._functorch.aot_autograd.__name__) + + stack = contextlib.ExitStack() + if not compile_debug: + try: + yield + finally: + stack.close() + return + + # Enable all graphs to be logged to a file by setting the flags to True + # and the log level of the file logger to DEBUG + stack.enter_context(patch("functorch.compile.config.debug_partitioner", True)) + + path = os.path.join(get_debug_dir(), "torchinductor") + os.makedirs(path, exist_ok=True) + + fh = logging.FileHandler( + os.path.join( + path, + f"aot_{get_aot_graph_name()}_debug.log", + ) + ) + fh.setLevel(logging.DEBUG) + fh.setFormatter( + logging.Formatter("[%(filename)s:%(lineno)d %(levelname)s] %(message)s") + ) + log.addHandler(fh) + try: + yield + finally: + log.removeHandler(fh) + stack.close() + + +# Used for provenance tracking +# They are not stored in DebugContext because they are not set in +# _inductor_triton_kernel_to_post_grad_node_info's Debug Context +_inductor_post_to_pre_grad_nodes: dict[str, dict[str, list[str]]] = {} +_inductor_triton_kernel_to_post_grad_node_info: dict[str, list[str]] = {} +_pre_grad_graph_id: int | None = None +_inductor_pre_grad_node_stack_trace: dict[str, str] = {} +_inductor_kernel_stack_trace: dict[str, list[str]] = {} +_kernel_information_jsons: dict[str, dict[str, Any]] = {} +_inductor_kernel_provenance_debug_handle: int = 0 + + +@dataclasses.dataclass +class _KernelExternInfo: + is_extern: bool = False + semantic_key: str | None = None + shapes: dict[str, Any] | None = None + + +_inductor_kernel_extern_info: dict[str, _KernelExternInfo] = {} + + +def get_kernel_information_jsons() -> dict[str, dict[str, Any]]: + return _kernel_information_jsons + + +def alias_kernel_provenance(original_kernel_name: str, alias_kernel_name: str) -> None: + """Expose existing kernel provenance under an additional generated name.""" + if original_kernel_name in _inductor_kernel_stack_trace: + _inductor_kernel_stack_trace[alias_kernel_name] = _inductor_kernel_stack_trace[ + original_kernel_name + ] + if original_kernel_name in _inductor_triton_kernel_to_post_grad_node_info: + _inductor_triton_kernel_to_post_grad_node_info[alias_kernel_name] = ( + _inductor_triton_kernel_to_post_grad_node_info[original_kernel_name] + ) + + +def reset_inductor_kernel_provenance_debug_handle() -> None: + global _inductor_kernel_provenance_debug_handle + _inductor_kernel_provenance_debug_handle = 0 + + +@contextlib.contextmanager +def reset_provenance_globals() -> Iterator[None]: + """Context manager that resets provenance tracking globals upon entering + and restores their original values when exiting.""" + global _pre_grad_graph_id + global _inductor_post_to_pre_grad_nodes + global _inductor_triton_kernel_to_post_grad_node_info + global _inductor_pre_grad_node_stack_trace + global _inductor_kernel_stack_trace + global _inductor_kernel_provenance_debug_handle + global _inductor_kernel_extern_info + + # Store original values + original_pre_grad_graph_id = _pre_grad_graph_id + original_post_to_pre_grad_nodes = _inductor_post_to_pre_grad_nodes.copy() + original_triton_kernel_to_post_grad_node_info = ( + _inductor_triton_kernel_to_post_grad_node_info.copy() + ) + original_inductor_pre_grad_node_stack_trace = ( + _inductor_pre_grad_node_stack_trace.copy() + ) + original_inductor_kernel_stack_trace = _inductor_kernel_stack_trace.copy() + original_inductor_kernel_provenance_debug_handle = ( + _inductor_kernel_provenance_debug_handle + ) + original_inductor_kernel_extern_info = dict(_inductor_kernel_extern_info) + + # Reset to default values + _pre_grad_graph_id = -1 + _inductor_post_to_pre_grad_nodes = {} + _inductor_triton_kernel_to_post_grad_node_info = {} + _inductor_pre_grad_node_stack_trace = {} + _inductor_kernel_stack_trace = {} + # Kernel timeline information is populated from compile_fx_inner while this + # context is active. It must outlive the reset scope so the profiler can + # consume it during export_chrome_trace, which then clears it. + _inductor_kernel_provenance_debug_handle = 0 + _inductor_kernel_extern_info = {} + + try: + yield + finally: + # Restore original values + _pre_grad_graph_id = original_pre_grad_graph_id + _inductor_post_to_pre_grad_nodes = original_post_to_pre_grad_nodes + _inductor_triton_kernel_to_post_grad_node_info = ( + original_triton_kernel_to_post_grad_node_info + ) + _inductor_kernel_stack_trace = original_inductor_kernel_stack_trace + _inductor_pre_grad_node_stack_trace = ( + original_inductor_pre_grad_node_stack_trace + ) + _inductor_kernel_provenance_debug_handle = ( + original_inductor_kernel_provenance_debug_handle + ) + _inductor_kernel_extern_info = original_inductor_kernel_extern_info + + +class DebugContext: + _counter = itertools.count() + + @staticmethod + def create_debug_dir(folder_name: str) -> str | None: + debug_dir = config.trace.debug_dir or get_debug_dir() + for n in DebugContext._counter: + dirname = os.path.join( + debug_dir, + "torchinductor", + f"{folder_name}.{n}", + ) + try: + os.makedirs(dirname, exist_ok=False) + return dirname + except FileExistsError: + # Another process (e.g. a peer rank with the same debug_dir) + # created this counter slot first; advance to the next n. + continue + return None + + def __init__(self) -> None: + self._prof = None + self._path = None + self._stack = contextlib.ExitStack() + + def copy(self, new_path: str) -> None: + if not self._path: + return + if not new_path.endswith(".debug"): + raise AssertionError(new_path) + from filelock import FileLock + + try: + with FileLock(f"{new_path}.lock"): + if os.path.exists(new_path): + shutil.rmtree(new_path) + shutil.copytree(self._path, new_path) + except OSError: + log.warning( + "Failed to copy debug files from %s to %s", self._path, new_path + ) + + def fopen( + self, + filename: str, + write_mode: str = "w", + *args: Any, + **kwargs: Any, + ) -> IO[Any]: + if not self._path: + raise AssertionError("expected self._path to be set") + return open(os.path.join(self._path, filename), write_mode, *args, **kwargs) + + @contextlib.contextmanager + def fopen_context( + self, + filename: str, + write_mode: str = "w", + *args: Any, + **kwargs: Any, + ) -> Iterator[IO[Any]]: + if not self._path: + raise AssertionError("expected self._path to be set") + with open(os.path.join(self._path, filename), write_mode, *args, **kwargs) as f: + yield f + + def filename(self, suffix: str) -> str: + if not self._path: + raise AssertionError("expected self._path to be set") + return os.path.join(self._path, suffix) + + def upload_tar(self) -> None: + if config.trace.upload_tar is not None: + import tarfile + + if not self._path: + raise AssertionError("expected self._path to be set") + tar_file = os.path.join( + self._path, f"{os.path.basename(self._path)}.tar.gz" + ) + with tarfile.open(tar_file, "w:gz") as tar: + tar.add(self._path, arcname=os.path.basename(self._path)) + config.trace.upload_tar(tar_file) + + def __enter__(self) -> None: + if config.debug: + log = logging.getLogger("torch._dynamo") + prev_level = log.level + log.setLevel(logging.DEBUG) + + def reset_log_level(level: Any) -> None: + log.setLevel(level) + + self._stack.callback(reset_log_level, prev_level) + + self._stack.enter_context(V.set_debug_handler(self)) + + if not config.trace.enabled: + return + + self._path = self.create_debug_dir(get_aot_graph_name()) # type: ignore[assignment] + + if config.trace.debug_log: + self._setup_log_capture("debug.log", logging.DEBUG) + if config.trace.info_log: + self._setup_log_capture("info.log", logging.INFO) + + def _setup_log_capture( + self, + filename: str, + level: int, + ) -> None: + log = logging.getLogger("torch._inductor") + fd = self._stack.enter_context(self.fopen(filename)) + ch = logging.StreamHandler(fd) + ch.setLevel(level) + ch.setFormatter( + logging.Formatter("[%(filename)s:%(lineno)d %(levelname)s] %(message)s") + ) + log.addHandler(ch) + log.setLevel(min(log.level, level)) + self._stack.callback(log.removeHandler, ch) + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: Any | None, + ) -> None: + if self._prof: + self._prof.disable() + self._save_profile_data() + + if self._path: + self.upload_tar() + log.warning("%s debug trace: %s", get_graph_being_compiled(), self._path) + self._stack.close() + + def _save_profile_data(self) -> None: + if not self._prof: + raise AssertionError("expected self._prof to be set") + self._prof.dump_stats(self.filename("compile.prof")) + with self.fopen("compile.stats") as fd: + stats = pstats.Stats(self._prof, stream=fd) + stats.strip_dirs() + stats.sort_stats("cumtime") + stats.print_stats(100) + stats.sort_stats("tottime") + stats.print_stats(100) + + def __getattr__(self, name: str) -> Callable[..., None] | None: + if config.trace.enabled and getattr(config.trace, name): + try: + return getattr(DebugFormatter(self), name) + except Exception: + log.warning("Ignoring exception in debug code", exc_info=True) + return None + else: + + def ignored(*args: Any, **kwargs: Any) -> None: + pass + + return ignored + + +class DebugFormatter: + def __init__(self, handler: DebugContext) -> None: + self.fopen = handler.fopen + self.fopen_context = handler.fopen_context + self.filename = handler.filename + self.handler = handler + + def fx_graph( + self, + gm: torch.fx.GraphModule, + inputs: list[torch.Tensor], + ) -> None: + with self.fopen("fx_graph_runnable.py") as fd: + save_dir = None + if torch._inductor.config.trace.save_real_tensors: + inputs = torch._subclasses.fake_utils.try_convert_fake_to_real(inputs) + save_dir = os.path.dirname(fd.name) + + # don't try to use stable hash torchinductor compilation if saving real tensors + # and avoid recursively trying to save real tensors inside of the inductor compilation + # regardless + stable_hash = torch._inductor.config.trace.save_real_tensors + with torch._inductor.config.patch( + {"trace.enabled": False, "trace.save_real_tensors": False} + ): + save_graph_repro( + fd, + gm, + inputs, + "inductor", + save_dir=save_dir, + stable_hash=stable_hash, + ) + + with self.fopen("fx_graph_readable.py") as fd: + fd.write(gm.print_readable(print_output=False)) + + def fx_graph_transformed( + self, + gm: torch.fx.GraphModule, + inputs: list[torch.Tensor], + ) -> None: + with self.fopen("fx_graph_transformed.py") as fd: + fd.write(gm.print_readable(print_output=False)) + + def ir_pre_fusion(self, nodes: SchedulerNodeList) -> None: + with self.fopen("ir_pre_fusion.txt") as fd: + fd.write(self._write_ir(nodes)) + + def ir_post_fusion(self, nodes: SchedulerNodeList) -> None: + with self.fopen("ir_post_fusion.txt") as fd: + fd.write(self._write_ir(nodes)) + + @staticmethod + def _write_ir(nodes: SchedulerNodeList) -> str: + buf = io.StringIO() + for node in nodes: + buf.write(node.debug_str()) + buf.write("\n\n\n") + return buf.getvalue() + + def graph_diagram(self, nodes: SchedulerNodeList) -> None: + draw_buffers( + nodes, + fname=self.filename(f"graph_diagram.{config.trace.graph_diagram_format}"), + ) + + def draw_orig_fx_graph( + self, + gm: torch.fx.GraphModule, + nodes: SchedulerNodeList, + ) -> None: + annotate_orig_fx_with_snodes(gm, nodes) + draw_graph( + gm, + fname=self.filename( + f"orig_fx_graph_diagram.{config.trace.orig_fx_graph_diagram_format}" + ), + clear_meta=False, + prog=GRAPHVIZ_COMMAND_SCALABLE, + parse_stack_trace=True, + dot_graph_shape=config.trace.dot_graph_shape, + ) + + def output_code(self, filename: str, extension: str = "py") -> None: + shutil.copy(filename, self.filename(f"output_code.{extension}")) + + def log_autotuning_results( + self, + name: str, + input_nodes: list[ir.IRNode], + timings: dict["ChoiceCaller", float], # type: ignore[name-defined] # noqa: F821 + elapse: float, + precompile_elapse: float, + prescreening_elapse: float | None, + ) -> None: + from .ir import FixedLayout + + def build_node_info(node: ir.IRNode) -> dict[str, str]: + if hasattr(node, "name"): + node_name = node.name + else: + node_name = "" + node_info = { + "name": node_name, + "type": type(node).__name__, + } + try: + layout = node.get_output_spec() + if isinstance(layout, FixedLayout): + static_layout = FixedLayout( + layout.device, + dtype=layout.dtype, + size=V.graph.sizevars.optimization_hints(layout.size), + stride=V.graph.sizevars.optimization_hints(layout.stride), + offset=V.graph.sizevars.optimization_hint( + layout.offset, fallback=0 + ), + ) + node_info["layout"] = str(static_layout) + else: + node_info["layout"] = str(layout) + except Exception: + pass + try: + node_info["dtype"] = str(node.get_dtype()) + except Exception: + pass + try: + node_info["device"] = str(node.get_device()) + except Exception: + pass + try: + node_info["stride"] = str( + V.graph.sizevars.optimization_hints(node.get_stride()) + ) + except Exception: + pass + try: + node_info["size"] = str( + V.graph.sizevars.optimization_hints(node.get_size()) + ) # type: ignore[arg-type] + except Exception: + pass + try: + node_info["numel"] = str( + V.graph.sizevars.optimization_hint(node.get_numel()) + ) + except Exception: + pass + if hasattr(node, "data") and isinstance(node.data, ir.IRNode): + node_info["data"] = build_node_info(node.data) + return node_info + + general_properties = { + "op_name": name, + "cuda_device_name": torch.cuda.get_device_name(), + "cuda_device_count": torch.cuda.device_count(), + "input_nodes": [build_node_info(node) for node in input_nodes], + "autotuning_time": elapse, + "precompile_time": precompile_elapse, + "prescreening_time": prescreening_elapse, + } + with self.fopen_context( + "autotuning_result_json_list.txt", "at", encoding="utf-8" + ) as fd: + for caller, time in timings.items(): + info_dict = dict(caller.info_dict()) + info_dict.update(general_properties) + info_dict["benchmark_result"] = time + json.dump(info_dict, fd) + fd.write("\n") + + +def log_ir_pre_fusion(nodes: SchedulerNodeList) -> None: + if ir_pre_fusion_log.isEnabledFor(logging.INFO): + ir_pre_fusion_log.info("BEFORE FUSION\n%s", DebugFormatter._write_ir(nodes)) + + V.debug.ir_pre_fusion(nodes) + + +def log_ir_post_fusion(nodes: SchedulerNodeList) -> None: + if ir_post_fusion_log.isEnabledFor(logging.INFO): + ir_post_fusion_log.info("AFTER FUSION\n%s", DebugFormatter._write_ir(nodes)) + + V.debug.ir_post_fusion(nodes) + + +def _dump_collective_schedule(schedule: list[str | None]) -> None: + try: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_collective_schedule", + "encoding": "json", + }, + payload_fn=lambda: schedule, + ) + except Exception: + log.debug( + "Failed to log inductor_collective_schedule via structured logging", + exc_info=True, + ) + + +def log_collective_schedule(nodes: Sequence[BaseSchedulerNode]) -> None: + schedule = [ + getattr(op, "python_kernel_name", None) + for node in nodes + if isinstance(op := getattr(node, "node", None), ir._CollectiveKernel) + ] + + # Only log when there is at least one collective op + if schedule: + _dump_collective_schedule(schedule) + + +def log_runtime_and_tensor_meta(node_runtimes: Sequence[tuple[Any, float]]) -> None: + """Log per-op runtime estimates and output tensor metadata for TLParse.""" + + try: + to_optimization_hints = V.graph.sizevars.optimization_hints + + def to_list(x: Sequence[Any] | None) -> list[Any]: + return list(to_optimization_hints(x)) if x is not None else [] + + def dtype_to_str(dtype: Any) -> str | None: + if dtype is None: + return None + s = str(dtype) + s = s.removeprefix("torch.") + return s + + ops: list[dict[str, Any]] = [] + for s, runtime_ns in node_runtimes: + name = getattr(s.node, "python_kernel_name", s.get_name()) + op_type = "collective" if utils.is_collective(s.node) else "compute" + + # Build outputs metadata if available + outputs: list[dict[str, Any]] = [] + try: + for buf in s.get_outputs(): + irnode = buf.node + shape = irnode.maybe_get_size() + stride = ( + irnode.get_stride() + if isinstance(irnode.layout, ir.Layout) + else None + ) + dtype = irnode.maybe_get_dtype() + outputs.append( + { + "shape": to_list(shape), + "stride": to_list(stride), + "dtype": dtype_to_str(dtype), + } + ) + except Exception: + pass + + ops.append( + { + "name": name, + "type": op_type, + "estimated_runtime_ns": runtime_ns, + "outputs": outputs, + } + ) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_runtime_and_tensor_meta", + "encoding": "json", + }, + payload_fn=lambda: {"ops": ops}, + ) + except Exception: + log.debug("Failed to log inductor_runtime_and_tensor_meta", exc_info=True) + + +def log_graph_execution() -> None: + """Emit a structured artifact with the graph execution order.""" + if not GRAPH_EXECUTION_ORDER: + return + try: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "graph_execution", + "encoding": "json", + }, + payload_fn=lambda: {"graph_execution_order": GRAPH_EXECUTION_ORDER}, + ) + except Exception: + log.debug("Failed to log graph_execution", exc_info=True) + + +@contextlib.contextmanager +def record_and_log_graph_execution_order() -> Iterator[None]: + """Record graph execution order and log it once on exit.""" + global RECORD_GRAPH_EXECUTION, GRAPH_EXECUTION_ORDER, GRAPH_COMPILE_IDS + GRAPH_EXECUTION_ORDER = [] + GRAPH_COMPILE_IDS = {} + RECORD_GRAPH_EXECUTION = True + try: + yield + finally: + log_graph_execution() + RECORD_GRAPH_EXECUTION = False + GRAPH_EXECUTION_ORDER = None + GRAPH_COMPILE_IDS = None + + +@dataclasses.dataclass +class TensorMetadataHolder: + tensor_metadata: TensorMetadata + device: torch.device + + +@dataclasses.dataclass +class SymExprMetadataHolder: + pytype: str + expr: Any + hint: int | float | bool | None + symbol_hints: dict[str, int | float | bool] + + +save_args_cnt = itertools.count() + + +def create_mapping_pre_post_grad_nodes( + pre_grad_graph_id: int | None, + post_to_pre_grad_nodes_json: dict[str, Any], +) -> dict[str, dict[str, list[str]]]: + """ + Create bidirectional mappings between pre_grad graph nodes + and post_grad graph code nodes, and vice versa. + """ + # return a dummy dict if there's any error + empty_return: dict[str, dict[str, list[str]]] = { + "preToPost": {}, + "postToPre": {}, + } + + if not isinstance(post_to_pre_grad_nodes_json, dict): + log.error( + "Provenance tracking error: post_to_pre_grad_nodes_json is not a dict" + ) + return empty_return + + if not isinstance(pre_grad_graph_id, int): + # pre_grad_graph_id may be empty if there's no pre_grad graph + # and there's only a backward graph from backward pass engine + return empty_return + + pre_to_post: dict[str, Any] = collections.defaultdict(OrderedSet) + post_to_pre: dict[str, Any] = collections.defaultdict(OrderedSet) + + try: + + def check_format(node: dict[str, Any]) -> bool: + if not isinstance(node, dict): + log.error( + "Provenance tracking error: node provenance in post_to_pre_grad_nodes_json is not a dict" + ) + return False + if "graph_id" not in node or "name" not in node or "from_node" not in node: + log.error( + "Provenance tracking error: node provenance in post_to_pre_grad_nodes_json has wrong format" + ) + return False + return True + + for outer_key, node_array in post_to_pre_grad_nodes_json.items(): + if not isinstance(node_array, list): + log.error( + "Provenance tracking error: post_to_pre_grad_nodes_json value is not a list" + ) + return empty_return + for node in node_array: + if not check_format(node): + return empty_return + # Check the current node first + if node.get("graph_id") == pre_grad_graph_id: + pre_to_post[node["name"]].add(outer_key) + post_to_pre[outer_key].add(node["name"]) + + # Check nested from_node array recursively, add node with the right graph_id to the map + stack = [(n, outer_key) for n in node.get("from_node", [])] + while stack: + current_node, parent_key = stack.pop() + if not check_format(current_node): + return empty_return + if current_node.get("graph_id") == pre_grad_graph_id: + pre_to_post[current_node["name"]].add(parent_key) + post_to_pre[parent_key].add(current_node["name"]) + stack.extend( + (n, parent_key) for n in current_node.get("from_node", []) + ) + + def convert_sets_to_lists(d: dict[str, Any]) -> None: + for key in d: + d[key] = list(d[key]) + d = dict(d) + + # convert to list because set is not JSON serializable + convert_sets_to_lists(pre_to_post) + convert_sets_to_lists(post_to_pre) + return { + "preToPost": pre_to_post, + "postToPre": post_to_pre, + } + except Exception as e: + # Since this is just logging code, it should never interfere with regular + # program execution, so we use this try-except to guard against any error + signpost_event( + "inductor", + "provenance_tracking_error", + { + "function": "create_mapping_pre_post_grad_nodes", + "error_msg": str(e), + "stack_trace": traceback.format_exc(), + }, + ) + log.error("post_to_pre_grad_nodes_json: %s", post_to_pre_grad_nodes_json) + log.error("pre_grad_graph_id: %s", pre_grad_graph_id) + return empty_return + + +def create_node_mapping_kernel_to_post_grad( + triton_kernel_to_post_grad_json: dict[str, Any], +) -> dict[str, dict[str, Any]]: + """Create bidirectional mappings between triton kernel name and post_grad + graph code nodes, and vice versa. + """ + + # return a dummy dict if there's any error + empty_return: dict[str, dict[str, Any]] = { + "cppCodeToPost": {}, + "postToCppCode": {}, + } + + if not isinstance(triton_kernel_to_post_grad_json, dict): + log.error( + "Provenance tracking error: triton_kernel_to_post_grad_json is not a dict" + ) + return empty_return + + post_to_cpp_code: dict[str, Any] = collections.defaultdict(OrderedSet) + + try: + for outer_key, node_array in triton_kernel_to_post_grad_json.items(): + if not isinstance(node_array, list): + log.error( + "Provenance tracking error: triton_kernel_to_post_grad_json value is not a list" + ) + return empty_return + for curr_node in node_array: + post_to_cpp_code[curr_node].add(outer_key) + + def convert_sets_to_lists(d: dict[str, Any]) -> None: + for key in d: + d[key] = list(d[key]) + d = dict(d) + + # convert to list because set is not JSON serializable + convert_sets_to_lists(post_to_cpp_code) + return { + "cppCodeToPost": triton_kernel_to_post_grad_json, + "postToCppCode": post_to_cpp_code, + } + except Exception as e: + # Since this is just logging code, it should never interfere with regular + # program execution, so we use this try-except to guard against any error + signpost_event( + "inductor", + "provenance_tracking_error", + { + "function": "create_mapping_kernel_to_post_grad", + "error_msg": str(e), + "stack_trace": traceback.format_exc(), + }, + ) + log.error( + "triton_kernel_to_post_grad_json: %s", triton_kernel_to_post_grad_json + ) + return empty_return + + +def dump_inductor_provenance_info() -> dict[str, Any]: + try: + global _pre_grad_graph_id + global _inductor_post_to_pre_grad_nodes + global _inductor_triton_kernel_to_post_grad_node_info + node_mapping: dict[str, Any] = {} + if _pre_grad_graph_id: + node_mapping_kernel = create_node_mapping_kernel_to_post_grad( + _inductor_triton_kernel_to_post_grad_node_info + ) + node_mapping = { + **_inductor_post_to_pre_grad_nodes, + **node_mapping_kernel, + } + if config.trace.enabled: + with V.debug.fopen( + "inductor_provenance_tracking_node_mappings.json", "w" + ) as fd: + json.dump(node_mapping, fd) + # we need to update the node mapping version when node mapping format changes + # so the tlparse tool knows which node mapping version it is looking at + node_mapping["version"] = 2.0 + return node_mapping + except Exception as e: + # Since this is just debugging, it should never interfere with regular + # program execution, so we use this try-except to guard against any error + signpost_event( + "inductor", + "provenance_tracking_error", + { + "function": "dump_inductor_provenance_info", + "error_msg": str(e), + "stack_trace": traceback.format_exc(), + }, + ) + return {} + + +def _serialize_provenance_shape(size: Sequence[Any]) -> list[int | str]: + shape: list[int | str] = [] + for dim in size: + if ir._is_static(dim): + shape.append(int(dim)) + else: + shape.append(str(dim)) + return shape + + +def _get_tensor_metadata(node: ir.IRNode) -> tuple[list[int | str], str] | None: + if not node.has_tensor_output(): + return None + + size = node.maybe_get_size() + dtype = node.maybe_get_dtype() + if size is None or dtype is None: + return None + + return _serialize_provenance_shape(size), str(dtype) + + +def create_kernel_information_json() -> dict[str, dict[str, Any]]: + """Create kernel information JSON with extended metadata for cross-hardware comparison.""" + try: + global _inductor_post_to_pre_grad_nodes + global _inductor_kernel_stack_trace + global _inductor_triton_kernel_to_post_grad_node_info + global _inductor_kernel_extern_info + + post_to_pre = _inductor_post_to_pre_grad_nodes.get("postToPre", {}) + all_kernels = OrderedSet(_inductor_kernel_stack_trace.keys()) | OrderedSet( + _inductor_triton_kernel_to_post_grad_node_info.keys() + ) + + result = {} + for kernel_key in all_kernels: + post_grad_nodes = _inductor_triton_kernel_to_post_grad_node_info.get( + kernel_key, [] + ) + + pre_grad_nodes: OrderedSet[str] = OrderedSet() + for post_node in post_grad_nodes: + pre_grad_nodes.update(post_to_pre.get(post_node, [])) + + stack_traces = _inductor_kernel_stack_trace.get(kernel_key, []) + pre_grad_list = list(pre_grad_nodes) + + # extern_semantic_key precedence: + # 1. Explicit annotation (e.g., FP8 bridge) — highest priority + # 2. Single-element pre_grad_nodes for externs — derived identity + # 3. None + info = _inductor_kernel_extern_info.get(kernel_key) + if info is not None and info.semantic_key is not None: + extern_semantic_key = info.semantic_key + elif info is not None and info.is_extern and len(pre_grad_list) == 1: + extern_semantic_key = pre_grad_list[0] + else: + extern_semantic_key = None + + result[kernel_key] = { + "stack_traces": stack_traces, + "post_grad_nodes": post_grad_nodes, + "pre_grad_nodes": pre_grad_list, + "extern_semantic_key": extern_semantic_key, + } + + # Merge shape metadata if available (extern ops only) + if info is not None and info.shapes: + result[kernel_key].update(info.shapes) + + return result + except Exception as e: + signpost_event( + "inductor", + "provenance_tracking_error", + { + "function": "create_kernel_information_json", + "error_msg": str(e), + "stack_trace": traceback.format_exc(), + }, + ) + log.warning("create_kernel_information_json: exception: %s", e) + return {} + + +def set_kernel_post_grad_provenance_tracing( + node_schedule: Sequence[BaseSchedulerNode] | ExternKernel, + kernel_name: str, + is_extern: bool = False, +) -> int | None: + """ + Set the mapping between `kernel_name` and the post_grad nodes in `node_schedule`. + + Returns a unique int debug handler for each call to this function. + """ + + if config.effective_provenance_tracking_level() == 0: + return None + + try: + from .codegen.simd_kernel_features import DisableReduction, EnableReduction + + global _inductor_triton_kernel_to_post_grad_node_info + global _inductor_kernel_stack_trace + global _inductor_kernel_provenance_debug_handle + global _inductor_kernel_extern_info + + _inductor_kernel_provenance_debug_handle += 1 + stack_traces: list[str] = [] + kernel_name = f"{kernel_name}:{_inductor_kernel_provenance_debug_handle}" + if is_extern: + if not isinstance(node_schedule, ExternKernel): + raise AssertionError( + f"expected ExternKernel, got {type(node_schedule)}" + ) + extern_info = _inductor_kernel_extern_info.setdefault( + kernel_name, _KernelExternInfo() + ) + extern_info.is_extern = True + curr_node_info = _inductor_triton_kernel_to_post_grad_node_info.setdefault( + kernel_name, [] + ) + # 'origins' on IR nodes gives what FX IR nodes contributed to any given fused kernel. + # "origin_node" is more precise and says that the contents of this node corresponds + # EXACTLY to the output of a particular FX node, but it's not always available + if node_schedule.origin_node: + origin_node_name = node_schedule.origin_node.name + if origin_node_name not in curr_node_info: + curr_node_info.append(origin_node_name) + else: + curr_node_info.extend( + origin.name + for origin in node_schedule.origins + if origin.name not in curr_node_info + ) + # Extract extern_semantic_key if stamped by a transform pass (e.g., FP8) + if node_schedule.origin_node and "extern_semantic_key" in getattr( + node_schedule.origin_node, "meta", {} + ): + extern_info.semantic_key = node_schedule.origin_node.meta[ + "extern_semantic_key" + ] + else: + for origin in node_schedule.origins: + if "extern_semantic_key" in getattr(origin, "meta", {}): + extern_info.semantic_key = origin.meta["extern_semantic_key"] + break + # Extract input/output shapes and dtypes for extern ops + try: + input_shapes: list[list[int | str]] = [] + input_dtypes: list[str] = [] + for inp in tree_leaves(node_schedule.inputs): + if isinstance(inp, ir.IRNode): + metadata = _get_tensor_metadata(inp) + if metadata is None: + continue + shape, dtype = metadata + input_shapes.append(shape) + input_dtypes.append(dtype) + + shape_metadata: dict[str, Any] = { + "input_shapes": input_shapes, + "input_dtypes": input_dtypes, + } + output_metadata = _get_tensor_metadata(node_schedule) + if output_metadata is not None: + output_shape, output_dtype = output_metadata + shape_metadata.update( + { + "output_shape": output_shape, + "output_dtype": output_dtype, + } + ) + extern_info.shapes = shape_metadata + except Exception as e: + log.debug("Shape extraction failed for %s: %s", kernel_name, e) + stack_traces = list(node_schedule.get_stack_traces()) + else: + if not isinstance(node_schedule, list): + raise AssertionError(f"expected list, got {type(node_schedule)}") + stack_traces_set: OrderedSet[str] = OrderedSet() + for snode in node_schedule: + if snode not in (EnableReduction, DisableReduction): + if snode.node is not None: + curr_node_info = ( + _inductor_triton_kernel_to_post_grad_node_info.setdefault( + kernel_name, [] + ) + ) + # pyrefly: ignore [missing-attribute] + stack_traces_set.update(snode.node.get_stack_traces()) + curr_node_info.extend( + origin.name + # pyrefly: ignore [missing-attribute] + for origin in snode.node.origins + if origin.name not in curr_node_info + ) + stack_traces = list(stack_traces_set) + _inductor_kernel_stack_trace.setdefault(kernel_name, []).extend(stack_traces) + return _inductor_kernel_provenance_debug_handle + except Exception as e: + # Since this is just debugging, it should never interfere with regular + # program execution, so we use this try-except to guard against any error + signpost_event( + "inductor", + "provenance_tracking_error", + { + "function": "set_kernel_post_grad_provenance_tracing", + "error_msg": str(e), + "stack_trace": traceback.format_exc(), + }, + ) + return None + + +def save_args_for_compile_fx_inner(*args: Any, **kwargs: Any) -> None: + """ + This function is used to save arguments for a compile_fx_inner function call + to the file system. Later on one can replay the compile_fx_inner call + with the saved arguments using load_args_and_run_compile_fx_inner. + """ + + folder = os.path.join(tempfile.gettempdir(), "inductor_saved_args") + if not os.path.exists(folder): + os.mkdir(folder) + + def python_value(value: Any) -> int | float | bool | None: + if value is None: + return None + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return value + # SymPy numbers expose is_integer as a tri-state property. + if getattr(value, "is_integer", None) is False: + return float(value) + try: + return int(value) + except (TypeError, ValueError): + return float(value) + + def handle_sym_expr(x: Any, pytype: str) -> SymExprMetadataHolder: + node = x.node + shape_env = node.shape_env + symbol_hints: dict[str, int | float | bool] = {} + if shape_env is not None: + for symbol in node.expr.free_symbols: + hint = shape_env.backed_var_to_val.get(symbol) + if hint is not None: + python_hint = python_value(hint) + if python_hint is not None: + symbol_hints[str(symbol)] = python_hint + return SymExprMetadataHolder( + pytype, + node.expr, + python_value(node.hint), + symbol_hints, + ) + + def handle_tensor(x: Any) -> Any: + """ + Pickle FakeTensor/SymInt will result in errors like: + AttributeError: Can't pickle local object 'WeakValueDictionary.__init__..remove' + + Convert tensors and symbolic values to metadata. This may also make + pickle faster. + """ + if isinstance(x, GraphModule): + gm = copy.deepcopy(x) + for node in gm.graph.nodes: + node.meta = tree_map(handle_tensor, node.meta) + return gm + if isinstance(x, torch.Tensor): + return TensorMetadataHolder( + tree_map(handle_tensor, _extract_tensor_metadata(x)), x.device + ) + elif isinstance(x, torch.SymInt): + return handle_sym_expr(x, "int") + elif isinstance(x, torch.SymFloat): + return handle_sym_expr(x, "float") + elif isinstance(x, torch.SymBool): + return handle_sym_expr(x, "bool") + else: + return x + + args_to_save, kwargs_to_save = tree_map(handle_tensor, (args, kwargs)) + + fn_name = "compile_fx_inner" + path = f"{folder}/{fn_name}_{next(save_args_cnt)}.pkl" + with open(path, "wb") as f: + pickle.dump((args_to_save, kwargs_to_save), f) + + if log.isEnabledFor(logging.DEBUG): + message = f""" +Arguments for a compile_fx_inner call is saved to {path}. To replay the call, +run the following: + +from torch._inductor.debug import load_args_and_run_compile_fx_inner +load_args_and_run_compile_fx_inner({path!r}) + """ + # call print rather than log.debug. log.debug will print message + # prefix for each line which makes the code snippet harder to be + # copied. + # Not a big deal since the code is already been guarded by checking + # the log level. + print(message) + + +def load_args_and_run_compile_fx_inner(path: str) -> Any: + from torch._dynamo.source import ConstantSource + from torch._inductor.compile_fx import compile_fx_inner + from torch.fx.experimental.symbolic_shapes import DimDynamic, ShapeEnv + + with open(path, "rb") as f: + args, kwargs = pickle.load(f) + + shape_env = ShapeEnv() + symbol_cache: dict[str, Any] = {} + + def restore_sym_expr(x: SymExprMetadataHolder) -> Any: + expr = x.expr + if isinstance(expr, str): + import sympy + + import torch.utils._sympy.functions as sympy_functions + + expr = sympy.sympify(expr, locals=sympy_functions.__dict__) + replacements = {} + for symbol in expr.free_symbols: + symbol_name = str(symbol) + if symbol_name not in symbol_cache: + hint = x.symbol_hints.get(symbol_name) + if hint is None: + if x.hint is not None and expr == symbol: + hint = x.hint + else: + symbol_cache[symbol_name] = shape_env.create_unbacked_symint( + ConstantSource(symbol_name) + ).node.expr + replacements[symbol] = symbol_cache[symbol_name] + continue + symbol_cache[symbol_name] = shape_env.create_symbol( + hint, + ConstantSource(symbol_name), + dynamic_dim=DimDynamic.DYNAMIC, + do_not_specialize_zero_one=True, + ) + replacements[symbol] = symbol_cache[symbol_name] + expr = expr.xreplace(replacements) + if x.pytype == "int": + return shape_env.create_symintnode(expr, hint=x.hint) + elif x.pytype == "float": + return shape_env.create_symfloatnode(expr, hint=x.hint) + elif x.pytype == "bool": + return shape_env.create_symboolnode(expr) + else: + raise AssertionError(f"Unexpected symbolic expression type: {x.pytype}") + + def handle_tensor(x: Any) -> Any: + if isinstance(x, GraphModule): + for node in x.graph.nodes: + node.meta = tree_map(handle_tensor, node.meta) + return x + elif isinstance(x, TensorMetadataHolder): + tensor_metadata = tree_map(handle_tensor, x.tensor_metadata) + return torch._dynamo.testing.rand_strided( + tensor_metadata.shape, + tensor_metadata.stride, + tensor_metadata.dtype, + x.device, + ) + elif isinstance(x, SymExprMetadataHolder): + return restore_sym_expr(x) + else: + return x + + fake_mode = torch._subclasses.FakeTensorMode( + allow_non_fake_inputs=True, shape_env=shape_env + ) + with fake_mode, config.patch("save_args", False): + args, kwargs = tree_map(handle_tensor, (args, kwargs)) + return compile_fx_inner(*args, **kwargs) + + +def aot_inductor_minifier_wrapper( + func: Callable[..., str], + exported_program: torch.export.ExportedProgram, + *, + inductor_configs: dict[str, Any], + package_path: FileLike | None = None, +) -> str: + from torch._dynamo.debug_utils import AccuracyError + from torch._dynamo.repro.aoti import dump_to_minify + from torch._inductor import config + from torch._inductor.compile_fx import _aoti_flatten_inputs + + use_minifier = config.aot_inductor.dump_aoti_minifier + + gm = exported_program.module(check_guards=False) + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"expected torch.fx.GraphModule, got {type(gm)}") + + args, kwargs = exported_program.example_inputs + + try: + if use_minifier and config.aot_inductor.repro_level == 3: + # Always dump the original module in case we have segfaults + dump_to_minify( + exported_program, + "aot_inductor", + options=inductor_configs, + ) + if use_minifier and config.aot_inductor.repro_level == 4: + # Check for accuracy + # We will first flatten the inputs before compiling and checking for accuracy. + # This is ok because we will flatten the inputs in the minifier anyway. + gm_copy = copy.deepcopy(gm) + example_inputs_copy = copy.deepcopy(exported_program.example_inputs) + config_copy = copy.deepcopy(inductor_configs) + flat_example_inputs, config_copy = _aoti_flatten_inputs( + gm_copy, + example_inputs_copy[0], + example_inputs_copy[1], + options=config_copy, + ) + tuple_inputs = tuple(flat_example_inputs) + flattened_ep = torch.export.export(gm_copy, tuple_inputs, strict=False) + func( + flattened_ep.module(check_guards=False), + tuple_inputs, + inductor_configs=config_copy, + package_path=package_path, + load_and_run=True, + check_accuracy="accuracy", + ) + + return func( + gm, + args, + kwargs, + inductor_configs=inductor_configs, + package_path=package_path, + load_and_run=use_minifier, + ) + except AccuracyError as e: + dump_to_minify( + exported_program, + "aot_inductor_accuracy", + command="minify", + options=inductor_configs, + ) + log.warning("Accuracy failed") + raise e + except Exception as e: + if use_minifier: + command = "minify" + + if config.aot_inductor.repro_level == 1: + command = "run" + + dump_to_minify( + exported_program, + "aot_inductor", + command=command, + options=inductor_configs, + ) + raise e diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/decomposition.py b/.venv/lib/python3.12/site-packages/torch/_inductor/decomposition.py new file mode 100644 index 0000000000000000000000000000000000000000..64daf558db78c29ca3186ff24406897bc83abe4e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/decomposition.py @@ -0,0 +1,1533 @@ +# mypy: allow-untyped-decorators +import functools +import logging +import math +import operator +import sys +from collections.abc import Callable +from typing import Any, cast, TypeAlias, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch._decomp as decomp +import torch._prims_common as utils +import torch.ao.quantization.fx._decomposed +from torch._decomp import ( + core_aten_decompositions, + get_decompositions, + remove_decompositions, +) +from torch._decomp.decompositions import ( + _grid_sampler_2d as decomp_grid_sampler_2d, + _index_add, + embedding_dense_backward as decomp_embedding_dense_backward, + pw_cast_for_opmath, + pw_cast_for_opmath_non_tensor_args, +) +from torch._decomp.decompositions_for_rng import extra_random_decomps +from torch._dynamo.utils import counters +from torch._environment import is_fbcode +from torch._higher_order_ops.out_dtype import out_dtype +from torch._inductor.utils import pad_listlike +from torch._prims_common import ( + elementwise_dtypes, + ELEMENTWISE_TYPE_PROMOTION_KIND, + suggest_memory_format, + type_to_dtype, +) +from torch._refs import native_layer_norm as decomp_native_layer_norm +from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + statically_known_true, + sym_eq, +) + +from . import config, inductor_prims +from .utils import ( + is_gpu, + needs_fallback_due_to_atomic_add_limitations, + use_scatter_fallback, +) + + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +_GenericOperator: TypeAlias = torch._ops.OperatorBase | torch._ops.OpOverloadPacket + +log = logging.getLogger(__name__) +aten = torch.ops.aten +prims = torch.ops.prims +quantized = torch.ops.quantized +_quantized = torch.ops._quantized +quantized_decomposed = torch.ops.quantized_decomposed + +inductor_decompositions = get_decompositions( + [ + aten._adaptive_avg_pool2d_backward, + aten.adaptive_max_pool2d, + aten.adaptive_max_pool3d, + aten.index_select, + aten.addmv, + aten.arange, + aten.bitwise_and_, + aten.bitwise_or_, + aten.clamp_min_, + aten.dist, + aten.elu, + aten.empty_like, + aten.flip, + aten.gelu, + aten.hardtanh, + aten.lcm, + aten.leaky_relu, + aten.linalg_vector_norm, + aten._log_softmax, + aten.max_pool2d_with_indices_backward, + aten._native_batch_norm_legit, + aten._native_batch_norm_legit_functional, + aten._native_batch_norm_legit_no_training, + aten._batch_norm_with_update, + aten._batch_norm_with_update_functional, + aten._batch_norm_no_update, + aten.batch_norm_backward, + aten.native_batch_norm, + aten.native_group_norm, + aten.native_layer_norm, + aten.nll_loss2d_backward, + aten.permute_copy, + aten.rrelu_with_noise_backward, + aten._softmax, + aten.sin_, + aten.sqrt_, + out_dtype, + aten._to_copy, + aten.tril_indices, + aten.triu_indices, + aten.unbind_copy.int, + aten.upsample_bilinear2d.vec, + aten.hann_window, + quantized.linear_dynamic_fp16_unpacked_weight, + _quantized.wrapped_quantized_linear, + ] +) +decompositions = {**core_aten_decompositions(), **inductor_decompositions} + +# Remove unwanted decompositions included via the core ATen decompositions from +# the Inductor decomp table. +decomps_to_exclude: list[torch._ops.OpOverload | torch._ops.OpOverloadPacket] = [ + aten._unsafe_index, + aten._unsafe_masked_index, + aten._unsafe_masked_index_put_accumulate, + aten._scaled_dot_product_flash_attention_for_cpu.default, # See comments in torch/_decomp/decompositions.py + aten._softmax_backward_data, + aten.clamp_max, + aten.clamp_min, + aten.embedding_dense_backward, # we fall back on xpu + aten.native_layer_norm, # we fall back on mtia + aten.index_add, # we conditionally call this decomp + aten.glu, # inductor lowers this directly + aten.select_scatter, # need to be in the ATen graph in order for it to work with the re-inplacing pass + aten.slice_scatter, # need to be in the ATen graph in order for it to work with the re-inplacing pass + aten.silu, # inductor uses exact eager decomposition + aten.split.Tensor, # inductor lowers this directly + aten.squeeze, # inductor lowers this directly + aten.sum, # inductor lowers this directly + aten.unbind, # inductor lowers this directly + aten.baddbmm, # upcasts to fp32, perf issue + # FMA ops - we have lowerings that use FMA to match eager CUDA behavior + aten.addcmul, + aten.addcmul_, + aten._foreach_addcmul.Scalar, + aten._foreach_addcmul_, + aten.addcdiv, + aten.addcdiv_, + aten._foreach_addcdiv.Scalar, + aten._foreach_addcdiv_, + aten.lerp, + aten.lerp_, +] + +remove_decompositions(decompositions, decomps_to_exclude) + + +def register_decomposition( + ops: _GenericOperator | list[_GenericOperator], +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + for op in ops if isinstance(ops, list) else [ops]: + if op in decompositions: + log.warning("duplicate decomp: %s", ops) + return decomp.register_decomposition(ops, decompositions) + + +if torch.distributed.is_available(): + + @register_decomposition([torch.ops._dtensor.shard_dim_alltoall.default]) + def shard_dim_alltoall_decomp( + inp: torch.Tensor, + gather_dim: int, + shard_dim: int, + group_name: str, + ) -> torch.Tensor: + if not config.decompose_shard_dim_alltoall: + return NotImplemented + if inp.dtype.is_complex: + return NotImplemented + + ndim = inp.dim() + gather_dim = gather_dim + ndim if gather_dim < 0 else gather_dim + shard_dim = shard_dim + ndim if shard_dim < 0 else shard_dim + if not (0 <= gather_dim < ndim and 0 <= shard_dim < ndim): + return NotImplemented + if gather_dim == shard_dim: + return NotImplemented + + try: + from torch.distributed.distributed_c10d import ( + _get_group_size_by_name, + GroupName, + ) + + group_size = _get_group_size_by_name(GroupName(group_name)) + except (RuntimeError, ValueError): + return NotImplemented + + input_shape = list(inp.shape) + shard_dim_size = input_shape[shard_dim] + # Match eager shard_dim_alltoall semantics. DTensor pads uneven logical + # shards before reaching this op, so the local shard dim should split + # evenly across the process group here. If the guard fails at runtime, + # Dynamo recompiles and may keep the original shard_dim_alltoall fallback. + if not guard_or_false(sym_eq(shard_dim_size % group_size, 0)): + return NotImplemented + local_shard_dim_size = shard_dim_size // group_size + + pre_view_shape = list(input_shape) + pre_view_shape[shard_dim] = local_shard_dim_size + pre_view_shape.insert(shard_dim, group_size) + + post_view_shape = list(input_shape) + post_view_shape[shard_dim] = local_shard_dim_size + post_view_shape[gather_dim] = post_view_shape[gather_dim] * group_size + + out = aten.view.default(inp, pre_view_shape) + out = aten.movedim.int(out, shard_dim, 0) + out = aten.clone.default(out, memory_format=torch.contiguous_format) + out = torch.ops._c10d_functional.all_to_all_single.default( + out, + [1] * group_size, + [1] * group_size, + group_name, + ) + out = torch.ops._c10d_functional.wait_tensor.default(out) + out = aten.movedim.int(out, 0, gather_dim) + out = aten.clone.default(out, memory_format=torch.contiguous_format) + counters["inductor"]["decompose_shard_dim_alltoall"] += 1 + return aten.view.default(out, post_view_shape) + + +@register_decomposition([aten.lerp.Scalar]) +def _lerp_scalar(start: torch.Tensor, end: torch.Tensor, weight: float) -> torch.Tensor: + # Decompose into sub + add(alpha=weight) so that the add lowering emits FMA, + # matching eager CUDA's dual-formula (see aten/src/ATen/native/Lerp.h). + # Convert end to start's memory format so the output preserves start's layout, + # matching eager TensorIterator behavior. + fmt = suggest_memory_format(start) + if fmt != torch.contiguous_format: + end = end.contiguous(memory_format=fmt) + diff = end - start + if weight >= 0.5 or weight <= -0.5: + return torch.add(end, diff, alpha=-(1.0 - weight)) + return torch.add(start, diff, alpha=weight) + + +@register_decomposition([aten.lerp.Tensor]) +def _lerp_tensor( + start: torch.Tensor, end: torch.Tensor, weight: torch.Tensor +) -> torch.Tensor: + # Same dual-formula as foreach_lerp polyfill: decompose into sub + addcmul. + # Convert end to start's memory format so the output preserves start's layout. + fmt = suggest_memory_format(start) + if fmt != torch.contiguous_format: + end = end.contiguous(memory_format=fmt) + diff = end - start + mask = weight.abs() >= 0.5 + neg_omw = -(1.0 - weight) + w = torch.where(mask, neg_omw, weight) + base = torch.where(mask, end, start) + return torch.addcmul(base, w, diff, value=1) + + +@register_decomposition([aten.embedding_dense_backward]) +def _embedding_dense_backward( + grad_output: torch.Tensor, + indices: torch.Tensor, + num_weights: int, + padding_idx: int, + scale_grad_by_freq: bool, +) -> torch.Tensor: + # TODO: check if XE4 still need this fallback + # check torch.xpu.get_device_properties(grad_output.device).architecture + if grad_output.is_xpu: + return NotImplemented + # We can write a util function to update decomp table if we have more ops to fallback. + return decomp_embedding_dense_backward( + grad_output, indices, num_weights, padding_idx, scale_grad_by_freq + ) + + +@register_decomposition(aten.native_layer_norm) +def _native_layer_norm( + input: torch.Tensor, + normalized_shape: utils.ShapeType, + weight: torch.Tensor | None, + bias: torch.Tensor | None, + eps: float, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if input.is_mtia: + return NotImplemented + # We can write a util function to update decomp table if we have more ops to fallback. + return decomp_native_layer_norm(input, normalized_shape, weight, bias, eps) + + +@register_decomposition([aten.sym_constrain_range_for_size.default]) +def sym_constrain_range_for_size( + symbol: torch.SymInt, + *, + min: torch.types.Number | None = None, + max: torch.types.Number | None = None, +) -> None: + return + + +@register_decomposition([aten.clamp]) +@pw_cast_for_opmath_non_tensor_args +def clamp( + x: torch.Tensor, + min: torch.types.Number | None = None, + max: torch.types.Number | None = None, +) -> torch.Tensor: + if min is not None: + x = x.clamp_min(min) + if max is not None: + x = x.clamp_max(max) + return x + + +# Inductor-specific SiLU decomposition for exact eager matching. +# The core decomposition uses x * sigmoid(x), but this form +# x / (1 + exp(-x)) matches eager execution more precisely. +@register_decomposition([aten.silu]) +@pw_cast_for_opmath +def silu(x: torch.Tensor) -> torch.Tensor: + return x / (1 + x.neg().exp()) + + +@register_decomposition([aten.full]) +def full( + size: list[int | torch.SymInt], + fill_value: torch.types.Number, + **kwargs: Any, +) -> torch.Tensor: + dtype = kwargs.get("dtype") + if dtype is None: + kwargs["dtype"] = type_to_dtype(type(fill_value)) + return torch.full(size, fill_value, **kwargs) + return NotImplemented + + +@register_decomposition([aten.index_add]) +def index_add( + x: torch.Tensor, + dim: int, + index: torch.Tensor, + tensor: torch.Tensor, + *, + alpha: torch.types.Number = 1, +) -> torch.Tensor: + # If we are not in fbcode and dtype is bfloat16 + # fallback to index_add kernel + # see https://github.com/pytorch/pytorch/issues/137425 for details + if not is_fbcode() and x.dtype == torch.bfloat16: + return NotImplemented + else: + return _index_add(x, dim, index, tensor, inplace=False, alpha=alpha) + + +# Not really sure how to put this into the main library. PrimTorch wants +# empty_permuted to go to the prim, and typically users don't really want +# to decompose to empty_strided (but inductor is OK with it, because we are +# cool with strides and everything goes to empty_strided) +@register_decomposition([aten.empty_permuted.default]) +def empty_permuted( + size: list[int | torch.SymInt], + physical_layout: list[int], + **kwargs: Any, +) -> torch.Tensor: + is_identity = list(physical_layout) == list(range(len(physical_layout))) + + if is_identity: + return torch.empty(size, **kwargs) + else: + perm = [0] * len(size) + for p, l in enumerate(physical_layout): + perm[l] = p + return torch.empty([size[l] for l in physical_layout], **kwargs).permute(perm) + + +@register_decomposition([aten.convolution_backward]) +def convolution_backward( + grad_output: torch.Tensor, + input: torch.Tensor, + weight: torch.Tensor, + bias_sizes: list[int], + stride: int | list[int], + padding: int | list[int], + dilation: int | list[int], + transposed: bool, + output_padding: list[int], + groups: int, + output_mask: list[bool], +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if not output_mask[2] or not is_gpu(grad_output.device.type): + return NotImplemented + if statically_known_true(input.size(1) == 0) and statically_known_true( + bias_sizes[0] != 0 + ): + # deal with the `input_channel=0` case + grad_bias = grad_output.new_zeros(bias_sizes) + else: + grad_bias = aten.sum(grad_output, [0] + list(range(2, grad_output.dim()))) + grad_inp, grad_weight, _ = aten.convolution_backward( + grad_output, + input, + weight, + bias_sizes, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + [output_mask[0], output_mask[1], False], + ) + return (grad_inp, grad_weight, grad_bias) + + +@register_decomposition([aten.round.decimals]) +def round_dec(x: torch.Tensor, decimals: int = 0) -> torch.Tensor: + ten_pow_decimals = 10.0**decimals + return aten.round(x * ten_pow_decimals) * (1.0 / ten_pow_decimals) + + +@register_decomposition([aten.bmm]) +@pw_cast_for_opmath +def bmm( + self: torch.Tensor, + batch2: torch.Tensor, + out_dtype: torch.dtype | None = None, +) -> torch.Tensor: + # Outer-product specialization: [B, M, 1] x [B, 1, N] -> [B, M, N]. + # This avoids introducing a reduction and maps directly to broadcasted mul. + if statically_known_true(self.shape[2] == 1) and statically_known_true( + batch2.shape[1] == 1 + ): + return (self * batch2).contiguous() + + # TODO: Re-enable for mps once our reductions are performant enough + # (https://github.com/pytorch/pytorch/issues/150121) + if config.coordinate_descent_tuning and self.device.type not in ["cpu", "mps"]: + if statically_known_true(self.shape[1] == 1) or statically_known_true( + batch2.shape[2] == 1 + ): + out = (self.unsqueeze(-1) * batch2.unsqueeze(1)).sum(dim=2) + return out + if self.device.type == "cpu": + if statically_known_true(self.size(1) == 1) and statically_known_true( + batch2.size(-1) == 1 + ): + counters["inductor"]["decompose_bmm"] += 1 + return torch.sum( + self.squeeze(1) * batch2.squeeze(-1), dim=1, keepdim=True + ).unsqueeze(1) + return NotImplemented + + +@register_decomposition([aten.addmm]) +@pw_cast_for_opmath +def addmm( + self: torch.Tensor, + mat1: torch.Tensor, + mat2: torch.Tensor, + out_dtype: torch.dtype | None = None, + beta: torch.types.Number = 1, + alpha: torch.types.Number = 1, +) -> torch.Tensor: + def add_input(out: torch.Tensor) -> torch.Tensor: + if alpha != 1: + out = alpha * out + if beta != 1: + return out + beta * self + return out + self + + if mat1.device.type not in ["cpu", "mps"]: + if beta == 0 and mat1.device.type == "cuda": + return NotImplemented + if ( + statically_known_true(mat1.size(-1) == 1) + and statically_known_true(mat1.size(0) != 1) + and statically_known_true(mat2.size(1) != 1) + ): + counters["inductor"]["decompose_addmm"] += 1 + out = mat1 * mat2 + return add_input(out) + + if self.device.type == "cpu": + if statically_known_true(mat1.size(0) == 1) and statically_known_true( + mat2.size(-1) == 1 + ): + counters["inductor"]["decompose_addmm"] += 1 + out = torch.sum( + mat1.squeeze(0) * mat2.squeeze(-1), dim=0, keepdim=True + ).unsqueeze(0) + return alpha * out + beta * self + if ( + statically_known_true(mat1.size(0) == 1) + and guard_or_false(mat2.size(0) <= 16) + and guard_or_false(mat2.size(1) <= 16) + ): + counters["inductor"]["decompose_addmm"] += 1 + out = (mat1.T * mat2).sum(dim=0, keepdim=True) + return alpha * out + beta * self + return NotImplemented + + +@register_decomposition([aten.mm]) +@pw_cast_for_opmath +def mm( + self: torch.Tensor, + input2: torch.Tensor, + out_dtype: torch.dtype | None = None, +) -> torch.Tensor: + # Our matrix vector multiplies only achieve peak bandwidth with coordinate descent tuning. + # todo: Look into why and fix it (hopefully) + + # TODO: Re-enable for mps once our reductions are performant enough + # (https://github.com/pytorch/pytorch/issues/150121) + if config.coordinate_descent_tuning and self.device.type not in ["cpu", "mps"]: + if statically_known_true(self.shape[0] == 1) or statically_known_true( + input2.shape[1] == 1 + ): + return (self.unsqueeze(2) * input2.unsqueeze(0)).sum(dim=1) + # Non-CPU/MPS: always decompose. CPU: only for small tensors. + if ( + statically_known_true(self.size(-1) == 1) + and statically_known_true(self.size(0) != 1) + and statically_known_true(input2.size(1) != 1) + ): + if self.device.type not in ["cpu", "mps"] or ( + self.device.type == "cpu" + and statically_known_true(self.size(0) > 0) + and statically_known_true(input2.size(0) == 1) + and (self.dtype == input2.dtype) + and guard_or_false((torch.numel(self) + torch.numel(input2)) <= 32) + ): + counters["inductor"]["decompose_mm"] += 1 + return self * input2 + if self.device.type == "cpu": + if statically_known_true(self.size(0) == 1) and statically_known_true( + input2.size(-1) == 1 + ): + counters["inductor"]["decompose_mm"] += 1 + return torch.sum( + self.squeeze(0) * input2.squeeze(-1), dim=0, keepdim=True + ).unsqueeze(0) + return NotImplemented + + +# This pass does two things: +# - Eliminate cat when there is only one tensor input +# - Normalize cat calls, so that legacy empty 1-D tensors are removed (NB: we +# don't remove ALL empty tensors, only the naughty ones) +@register_decomposition([aten.cat.default]) +def cat( + tensors: list[torch.Tensor], + dim: int = 0, +) -> torch.Tensor: + def non_empty_tensor(x: torch.Tensor) -> bool: + # For better or worse, this is a valid cat: + # + # torch.cat([torch.randn(2, 2, 4), torch.randn(0), torch.randn(3, 2, 4)]) + # + # We'd like to eliminate naughtiness like this for downstream passes + # like split_cat. The easiest way is to just drop such inputs + # (guarding that they are non-zero). + # + # Is it permissible for this filtering to be size-oblivious? A case + # where this could matter is cat([(2, 2), (u0,)], dim=0); if u0 + # happened to be zero, we would have liked to have filtered it out. + # But actually, the ONLY way this could have passed is if u0 == 0, + # so by the time we get here we have already installed a deferred + # runtime assert forcing u0 to be zero. So if this hasn't happened, + # we know that the unbacked SymInt has appropriate size and there are + # no problems. + if len(x.shape) == 1 and guard_or_false(x.shape[0] == 0): + return False + + if dim < len(x.shape) and guard_or_false(x.shape[dim] == 0): + return False + + return True + + filtered_tensors = list(filter(non_empty_tensor, tensors)) + + if len(filtered_tensors) == 1: + # check dtype promotion + promoted_dtype = elementwise_dtypes( + *tensors, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + )[1] + filtered_t = filtered_tensors[0] + return ( + filtered_t.clone() + if promoted_dtype == filtered_t.dtype + else filtered_t.to(dtype=promoted_dtype) + ) + elif 1 < len(filtered_tensors) < len(tensors): + # on the first call, when we remove empty tensors, we redispatch recursively + return aten.cat.default(filtered_tensors, dim) + + # optimization, avoid concat for single, repeated input + if len(filtered_tensors) > 1 and all( + t is filtered_tensors[0] for t in filtered_tensors + ): + inp = filtered_tensors[0] + shape = list(inp.shape) + dim = dim + len(inp.shape) if dim < 0 else dim + shape.insert(dim, len(filtered_tensors)) + return inp.unsqueeze(dim).expand(*shape).flatten(dim, dim + 1).clone() + + # when no 'filtering' has occurred, we raise to prevent infinite recursion (no more decomposition needed) + return NotImplemented + + +@register_decomposition([aten.angle]) +def angle(x: torch.Tensor) -> torch.Tensor: + if x.is_complex(): + return torch.where( + torch.isnan(x.real), float("nan"), torch.atan2(x.imag, x.real) + ) + + # when x is real number + # if x >= 0, return 0 + # if x < 0, return pi + # if x is nan, return nan + _, dtype = elementwise_dtypes( + x, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + pi = torch.scalar_tensor(math.pi, dtype=dtype, device=x.device) + ret = torch.where(x < 0, pi, 0.0) + return torch.where(torch.isnan(x), float("nan"), ret) + + +@register_decomposition([aten.add]) +def add( + x: torch.Tensor, + y: torch.Tensor, + *, + alpha: torch.types.Number | None = None, +) -> torch.Tensor: + # Require both x and y to be complex tensors. + x_is_complex_tensor = torch.is_tensor(x) and x.is_complex() + y_is_complex_tensor = torch.is_tensor(y) and y.is_complex() + if not x_is_complex_tensor or not y_is_complex_tensor: + return NotImplemented + + def _requires_fallback(tensor: torch.Tensor) -> bool: + if tensor.ndim == 0: + return False + # Viewing complex tensors as their real dtype requires the last stride to be 1. + return tensor.stride()[-1] != 1 + + output_size_zero = False + if x.ndim == 0 and y.ndim == 0: + output_size_zero = True + + if x.ndim == 0: + x = x.reshape(1) + if y.ndim == 0: + y = y.reshape(1) + + z = y + if alpha is not None: + z = alpha * y + complex_type = torch.promote_types(x.dtype, y.dtype) + + if _requires_fallback(x) or _requires_fallback(z): + return NotImplemented + + # For complex typed `x`, `x.view(x.real.dtype)` doubles the last dimension and can cause problem + # when broadcasting the add. + def reshape_tensor_complex(tensor: torch.Tensor) -> torch.Tensor: + """Reshape tensor from [*initial_dims, last_dim] to *initial_dims, last_dim/2, 2]""" + # Get the current shape of the tensor + *initial_dims, last_dim = tensor.shape + + # Check if the last dimension is even. We should never reach here since `x.view(x.real.dtype)` + # doubles the last dimension for complex numbers. + if last_dim % 2 != 0: + raise AssertionError( + "The size of the last dimension must be even to reshape it to [..., last_dim/2, 2]" + ) + + # Reshape the tensor + new_shape = (*initial_dims, last_dim // 2, 2) + reshaped_tensor = tensor.view(new_shape) + return reshaped_tensor + + # Manually resolve complex tensors, as .is_conj() is unreliable after cloning during compilation. + x = x + 0 + z = z + 0 + + x_reshaped = reshape_tensor_complex(x.view(x.real.dtype)) + z_reshaped = reshape_tensor_complex(z.view(y.real.dtype)) + result = torch.flatten(x_reshaped + z_reshaped, start_dim=-2).view(complex_type) + + if output_size_zero: + return result[0] + return result + + +@register_decomposition([aten.conj_physical]) +def conj_physical(self: torch.Tensor) -> torch.Tensor: + if self.is_complex(): + return NotImplemented + return self + + +@register_decomposition([aten.lift, aten.detach_]) +def lift(self: torch.Tensor) -> torch.Tensor: + return self + + +@register_decomposition([aten.fmin, prims.fmin]) +def fmin(self: torch.Tensor, other: torch.Tensor) -> torch.Tensor: + return torch.where(torch.isnan(other) | (other > self), self, other) + + +@register_decomposition([aten.fmax, prims.fmax]) +def fmax(self: torch.Tensor, other: torch.Tensor) -> torch.Tensor: + return torch.where(torch.isnan(other) | (other < self), self, other) + + +@register_decomposition(prims.normal) +def normal( + shape: list[int | torch.SymInt], + *, + mean: torch.types.Number, + std: torch.types.Number, + dtype: torch.dtype, + device: torch.device, + requires_grad: bool, + generator: torch.Generator | None = None, +) -> torch.Tensor: + if generator is None: + normal_samples = torch.randn( + shape, + dtype=dtype, + device=device, + requires_grad=requires_grad, + ) + else: + normal_samples = torch.randn( + shape, + generator=generator, + dtype=dtype, + device=device, + requires_grad=requires_grad, + ) + return std * normal_samples + mean + + +@register_decomposition(aten.amax) +def amax( + self: torch.Tensor, + dim: int | None = None, + keepdim: bool = False, +) -> torch.Tensor: + if self.dtype == torch.bool: + return torch.any(self, dim=dim, keepdim=keepdim) + return NotImplemented + + +@register_decomposition(aten.amin) +def amin( + self: torch.Tensor, + dim: int | None = None, + keepdim: bool = False, +) -> torch.Tensor: + if self.dtype == torch.bool: + return torch.all(self, dim=dim, keepdim=keepdim) + return NotImplemented + + +@register_decomposition([aten.narrow_copy]) +def narrow_copy( + self: torch.Tensor, + dim: int, + start: int, + length: int, +) -> torch.Tensor: + # Use memory_format=torch.contiguous_format to ensure correct strides. + # For empty tensors, a plain clone() preserves the input view's strides. + return torch.narrow(self, dim, start, length).clone( + memory_format=torch.contiguous_format + ) + + +@register_decomposition([aten.view_copy.default]) +def view_copy_default( + self: torch.Tensor, + size: list[int | torch.SymInt], +) -> torch.Tensor: + return aten.view(self, size).clone() + + +@register_decomposition([aten.view_copy.dtype]) +def view_copy_dtype( + self: torch.Tensor, + dtype: torch.dtype, +) -> torch.Tensor: + return self.clone().view(dtype) + + +def _get_shape_permutation_like( + self: torch.Tensor, +) -> tuple[utils.ShapeType, utils.StrideType]: + physical_layout, _ = utils.compute_elementwise_output_logical_to_physical_perm(self) + shape = [self.shape[l] for l in physical_layout] + + permutation = [0] * len(shape) + for p, l in enumerate(physical_layout): + permutation[l] = p + + return (shape, permutation) + + +@register_decomposition(aten.full_like) +def full_like( + self: torch.Tensor, + fill_value: int | float, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: torch.device | None = None, + pin_memory: bool = False, + requires_grad: bool = False, + memory_format: torch.memory_format = torch.preserve_format, +) -> torch.Tensor: + dtype = self.dtype if dtype is None else dtype + layout = self.layout if layout is None else layout + device = self.device if device is None else device + + if memory_format != torch.preserve_format: + result = torch.full( + self.shape, + fill_value, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + return result.to(memory_format=memory_format) + + else: + if layout != torch.strided: + raise AssertionError(f"expected torch.strided layout, got {layout}") + shape, permutation = _get_shape_permutation_like(self) + result = torch.full( + shape, + fill_value, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + if permutation == list(range(len(permutation))): + return result + return result.permute(permutation).clone() + + +def _rand_like( + rand_fn: Callable[..., torch.Tensor], + self: torch.Tensor, + *, + dtype: torch.dtype | None = None, + device: torch.device | None = None, + memory_format: torch.memory_format = torch.preserve_format, + **kwargs: Any, +) -> torch.Tensor: + dtype = self.dtype if dtype is None else dtype + device = self.device if device is None else device + + if memory_format != torch.preserve_format: + return rand_fn( + self.shape, + dtype=dtype, + device=device, + **kwargs, + ).to(memory_format=memory_format) + + shape, permutation = _get_shape_permutation_like(self) + result = rand_fn( + shape, + dtype=dtype, + device=device, + **kwargs, + ) + if permutation == list(range(len(permutation))): + return result + return result.permute(permutation).clone() + + +@decomp.register_decomposition([aten.rand_like], extra_random_decomps) +def rand_like(self: torch.Tensor, **kwargs: Any) -> torch.Tensor: + return _rand_like(torch.rand, self, **kwargs) + + +@decomp.register_decomposition([aten.randn_like], extra_random_decomps) +def randn_like(self: torch.Tensor, **kwargs: Any) -> torch.Tensor: + return _rand_like(torch.randn, self, **kwargs) + + +@decomp.register_decomposition([aten.randint_like.default], extra_random_decomps) +def randint_like(self: torch.Tensor, high: int, **kwargs: Any) -> torch.Tensor: + return _rand_like(functools.partial(aten.randint.low, 0, high), self, **kwargs) + + +@decomp.register_decomposition([aten.randint_like.low_dtype], extra_random_decomps) +def randint_like_low( + self: torch.Tensor, low: int, high: int, **kwargs: Any +) -> torch.Tensor: + return _rand_like(functools.partial(aten.randint.low, low, high), self, **kwargs) + + +@register_decomposition(aten.randint.default) +def randint( + high: int, + size: list[int | torch.SymInt], + **kwargs: Any, +) -> torch.Tensor: + return aten.randint.low(0, high, size, **kwargs) + + +@register_decomposition(prims.uniform) +def uniform( + shape: list[int | torch.SymInt], + *, + low: torch.types.Number, + high: torch.types.Number, + dtype: torch.dtype, + device: torch.device, + stride: list[int | torch.SymInt], + generator: torch.Generator | None = None, +) -> torch.Tensor: + storage_len = utils.compute_required_storage_length( + cast(list[int], shape), cast(list[int], stride), 0 + ) + sample_shape: list[int | torch.SymInt] = [storage_len] + if generator is None: + rand_samples = torch.rand(sample_shape, dtype=dtype, device=device) + else: + rand_samples = torch.rand( + sample_shape, generator=generator, dtype=dtype, device=device + ) + res = (high - low) * rand_samples + low + return res.as_strided(shape, stride) + + +@register_decomposition(quantized.linear_dynamic_fp16_unpacked_weight.default) +def linear_dynamic_fp16_unpacked_weight( + input: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor | None = None, +) -> torch.Tensor: + packed_weight = torch.ops._quantized.wrapped_fbgemm_pack_gemm_matrix_fp16(weight) + return torch.ops._quantized.wrapped_fbgemm_linear_fp16_weight( + input, packed_weight, bias, weight.size()[0] + ) + + +@register_decomposition(_quantized.wrapped_quantized_linear.default) +def wrapped_quantized_linear( + input: torch.Tensor, + input_scale: torch.Tensor, + input_zero_point: torch.Tensor, + weight: torch.Tensor, + weight_scale: torch.Tensor, + weight_zero_point: torch.Tensor, + bias: torch.Tensor, + out_scale: torch.Tensor, + out_zero_point: torch.Tensor, + out_channel: int, +) -> torch.Tensor: + packed_weight = torch.ops._quantized._wrapped_linear_prepack( + weight, weight_scale, weight_zero_point, bias + ) + return torch.ops._quantized._wrapped_quantized_linear_prepacked( + input, + input_scale, + input_zero_point, + packed_weight, + out_scale, + out_zero_point, + out_channel, + ) + + +@register_decomposition(torch.ops.quantized.embedding_bag_byte_unpack) +def q_embedding_bag_byte_unpack_decomp(packed: torch.Tensor) -> torch.Tensor: + def bitcast_u8_to_f32(u8: torch.Tensor) -> torch.Tensor: + x, y, z, w = (u8[..., n].to(torch.int32) for n in (0, 1, 2, 3)) + if sys.byteorder == "little": + return (x + (y << 8) + (z << 16) + (w << 24)).view(torch.float32)[..., None] + else: + return ((x << 24) + (y << 16) + (z << 8) + w).view(torch.float32)[..., None] + + scales = bitcast_u8_to_f32(packed[..., -8:-4]) + offsets = bitcast_u8_to_f32(packed[..., -4:]) + return packed[..., :-8].to(torch.float32) * scales + offsets + + +@register_decomposition([aten.grid_sampler_2d]) +@pw_cast_for_opmath +def grid_sampler_2d( + a: torch.Tensor, + grid: torch.Tensor, + interpolation_mode: int = 0, + padding_mode: int = 0, + align_corners: bool = False, +) -> torch.Tensor: + # We do not expand the grid (_expand_grid=False) on cpu for performance reasons + # Experimenting locally it was found that compiled CUDA code is accelerated by ~5x + # and CPU code by ~2x on bicubic mode, if we expand the grid from (N, H, W, 2) into (N, C, H, W, 2) + # However, this leads to a slowdown around ~0.8x on CPU bilinear mode, channels first. + # Thus we apply this hack to not expand the grid for this case. + _expand_grid = not ( + a.device == torch.device("cpu") + and interpolation_mode == 0 + and a.is_contiguous(memory_format=torch.contiguous_format) + ) + + output = decomp_grid_sampler_2d( + a, + grid=grid, + interpolation_mode=interpolation_mode, + padding_mode=padding_mode, + align_corners=align_corners, + _expand_grid=_expand_grid, + ) + return output + + # _foreach_addcmul and _foreach_addcdiv decompositions removed — + # the inductor lowering in lowering.py handles these with FMA. + + +@register_decomposition(aten._foreach_lerp.Scalar) +def _foreach_lerp_scalar( + start_tensors: list[torch.Tensor], + end_tensors: list[torch.Tensor], + weight: torch.types.Number, +) -> list[torch.Tensor]: + def opmath_dtype(t: torch.Tensor) -> torch.dtype: + if t.dtype in (torch.float16, torch.bfloat16): + return torch.float32 + return t.dtype + + def cast_weight(dtype: torch.dtype) -> float | complex: + if isinstance(weight, complex) and not dtype.is_complex: + if weight.imag != 0: + return torch.tensor(weight, dtype=dtype).item() + return torch.tensor(weight.real, dtype=dtype).item() + return torch.tensor(weight, dtype=dtype).item() + + def use_high_formula(dtype: torch.dtype) -> bool: + casted_weight = cast_weight(dtype) + if isinstance(casted_weight, complex): + return ( + casted_weight.real * casted_weight.real + + casted_weight.imag * casted_weight.imag + >= 0.25 + ) + return casted_weight >= 0.5 or casted_weight <= -0.5 + + def scalar_tensor( + dtype: torch.dtype, device: torch.device, high_weight: bool + ) -> torch.Tensor: + if isinstance(weight, complex) and not dtype.is_complex: + if weight.imag != 0: + weight_tensor = torch.tensor(weight, dtype=dtype, device=device) + if high_weight: + return -(1.0 - weight_tensor) + return weight_tensor + weight_tensor = torch.tensor(weight.real, dtype=dtype, device=device) + if high_weight: + return -(1.0 - weight_tensor) + return weight_tensor + weight_tensor = torch.tensor(weight, dtype=dtype, device=device) + if high_weight: + return -(1.0 - weight_tensor) + return weight_tensor + + dtype = start_tensors[0].dtype + device = start_tensors[0].device + compute_dtype = opmath_dtype(start_tensors[0]) + use_foreach = dtype not in (torch.float16, torch.bfloat16) and all( + t.dtype == dtype and t.device == device for t in start_tensors + ) + if use_foreach: + high_weight = use_high_formula(compute_dtype) + bases = end_tensors if high_weight else start_tensors + diff = aten._foreach_sub.List(end_tensors, start_tensors) + scalar = scalar_tensor(dtype, device, high_weight) + return aten._foreach_addcmul.Scalar(bases, [scalar] * len(diff), diff) + + return [ + torch.addcmul( + (end if high_weight else t).to(compute_dtype), + scalar_tensor(compute_dtype, t.device, high_weight), + end.to(compute_dtype) - t.to(compute_dtype), + ).to(t.dtype) + for t, end, compute_dtype, high_weight in ( + ( + t, + end, + opmath_dtype(t), + use_high_formula(opmath_dtype(t)), + ) + for t, end in zip(start_tensors, end_tensors) + ) + ] + + +@register_decomposition(aten._foreach_lerp.ScalarList) +def _foreach_lerp_scalarlist( + start_tensors: list[torch.Tensor], + end_tensors: list[torch.Tensor], + scalars: list[torch.types.Number], +) -> list[torch.Tensor]: + return aten._foreach_add.List( + start_tensors, + aten._foreach_mul.ScalarList( + aten._foreach_sub.List(end_tensors, start_tensors), scalars + ), + ) + + +@aten.miopen_batch_norm.default.py_impl(torch._C.DispatchKey.Autograd) +@register_decomposition(aten.miopen_batch_norm) +def miopen_batch_norm( + input: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor | None, + running_mean: torch.Tensor | None, + running_var: torch.Tensor | None, + training: bool, + exponential_average_factor: float, + epsilon: float, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + a, b, c = aten.native_batch_norm( + input, + weight, + bias, + running_mean, + running_var, + training, + exponential_average_factor, + epsilon, + ) + + if training: + return (a, b, c) + return ( + a, + weight.new_zeros((0,)), + weight.new_zeros((0,)), + ) + + +@functools.cache +def fast_random_decomps() -> dict[Any, Callable[..., Any]]: + return {**decompositions, **extra_random_decomps} + + +# TODO(aakhundov): replace this (and the above) Any by more +# specific type and fix all the cascading mypy errors +def select_decomp_table() -> dict[Any, Callable[..., Any]]: + """decomps can change based on config""" + if config.fallback_random: + return decompositions + if config.fallback_embedding_bag_byte_unpack: + # remove q_embedding_bag_byte_unpack_decomp from decompositions + decompositions.pop(torch.ops.quantized.embedding_bag_byte_unpack.default, None) + return decompositions + result = fast_random_decomps() + return result + + +@register_decomposition(aten.masked_scatter) +def masked_scatter( + self: torch.Tensor, + mask: torch.Tensor, + source: torch.Tensor, +) -> torch.Tensor: + from .codegen.common import BackendFeature, has_backend_feature + + if has_backend_feature(self.device, BackendFeature.MASKED_SCATTER_WITH_INDEX): + # This two-step algorithm is the same as eager CUDA, for eager CPU we + # use a 1-shot serial iteration. + self, mask = aten.broadcast_tensors([self, mask]) + source_idx = mask.reshape(-1).cumsum(0) - 1 + self_flat, mask_flat, source_flat = (x.flatten() for x in (self, mask, source)) + result = aten._unsafe_masked_index(source_flat, mask_flat, [source_idx], 0) + return torch.where(mask_flat, result, self_flat).view(self.shape) + return NotImplemented + + +@register_decomposition(quantized_decomposed.choose_qparams.tensor) +def choose_qparams_tensor( + input: torch.Tensor, + quant_min: int, + quant_max: int, + eps: float, + dtype: torch.dtype, +) -> tuple[torch.Tensor, torch.Tensor]: + min_val, max_val = torch.aminmax(input) + scale = (max_val - min_val) / float(quant_max - quant_min) + scale = torch.max(scale, torch.Tensor([eps])) + zero_point = quant_min - torch.round(min_val / scale).to(torch.int) + zero_point = torch.clamp(zero_point, quant_min, quant_max) + return scale.to(torch.float64), zero_point.to(torch.int64) + + +@register_decomposition(aten.put) +def put( + self: torch.Tensor, + index: torch.Tensor, + source: torch.Tensor, + accumulate: bool = False, +) -> torch.Tensor: + flattened = self.flatten() + flattened = torch.index_put( + flattened, [index], source.reshape(index.shape), accumulate + ) + return flattened.reshape(self.shape) + + +@register_decomposition(aten.put_) +def put_( + self: torch.Tensor, + index: torch.Tensor, + source: torch.Tensor, + accumulate: bool = False, +) -> torch.Tensor: + out = aten.put(self, index, source, accumulate=accumulate) + return self.copy_(out) + + +@register_decomposition(aten._softmax_backward_data.default) +@pw_cast_for_opmath +def _softmax_backward_data( + grad_output: torch.Tensor, + output: torch.Tensor, + dim: int, + input_dtype: torch.dtype, +) -> torch.Tensor: + new_grad_output = grad_output * output + sum_new_grad = torch.sum(new_grad_output, dim=dim, keepdim=True) + # grad_input = new_grad_output - output * sum_new_grad + grad_input = inductor_prims.fma(-output, sum_new_grad, new_grad_output) + + # CPU kernel doesn't respect input_dtype, but following check doesn't work for meta tensor + # if grad_output.device == torch.device("cpu"): + # return grad_input.contiguous() + + if grad_output.dtype != input_dtype: + grad_input = grad_input.to(input_dtype) + return grad_input.contiguous() + + +@register_decomposition(aten.index_reduce) +def index_reduce( + self: torch.Tensor, + dim: int, + index: torch.Tensor, + src: torch.Tensor, + reduction_type: str, + *, + include_self: bool = True, +) -> torch.Tensor: + torch._check( + self.device == index.device and self.device == src.device, + lambda: ( + f"index_reduce(): self, index and source expected to be in the same device, " + f"but got (self) {self.device}, (index) {index.device}, " + f"and (source) {src.device}" + ), + ) + if reduction_type == "mean" and not needs_fallback_due_to_atomic_add_limitations( + self.dtype + ): + true_division = self.dtype.is_floating_point or self.dtype.is_complex + ones = torch.ones_like(src) + if include_self: + out = self + counts = torch.ones_like(self).index_add(dim, index, ones) + else: + out = self.index_fill(dim, index, 0) + counts = torch.zeros_like(self).index_add(dim, index, ones) + counts = counts.masked_fill(counts < 1, 1) + out = out.index_add(dim, index, src) + return out / counts if true_division else out // counts + + if use_scatter_fallback( + aten.scatter_reduce_.two, + reduction_type, + self.dtype, + src.dtype, + src.device.type, + True, + ): + return NotImplemented + + # pyrefly: ignore [missing-attribute] + repeats = self.shape[dim + 1 :].numel() * self.shape[:dim].numel() + index_shape = (index.numel(), *self.shape[dim + 1 :], *self.shape[:dim]) + perm = (*range(self.ndim - dim, self.ndim), 0, *range(1, self.ndim - dim)) + scatter_index = ( + index.to(torch.int64) + .repeat_interleave(repeats) + .reshape(index_shape) + .permute(perm) + ) + return self.scatter_reduce( + dim, + scatter_index, + src, + reduction_type, + include_self=include_self, + ) + + +def _max_pool_with_indices( + x: torch.Tensor, + kernel_size: list[int], + stride: int | list[int] | None, + padding: int | list[int], + dilation: int | list[int], + ceil_mode: bool, + dim: int, +) -> tuple[torch.Tensor, torch.Tensor]: + if dilation == 1: + dilation = [1] * dim + + if padding == 0: + padding = [0] * dim + + if not stride: + stride = kernel_size + + # pyrefly: ignore [bad-assignment] + kernel_size = pad_listlike(kernel_size, dim) + # pyrefly: ignore [bad-assignment] + dilation = pad_listlike(dilation, dim) + # pyrefly: ignore [bad-assignment] + padding = pad_listlike(padding, dim) + # pyrefly: ignore [bad-assignment] + stride = pad_listlike(stride, dim) + + window_size = functools.reduce(operator.mul, kernel_size) + # We fallback when using non-default dilation or when the window size is too large + if ( + torch._inductor.lowering.should_fallback_max_pool_with_indices( + kernel_size, n_dim=dim + ) + or window_size > torch.iinfo(torch.int8).max + ): + return NotImplemented + + vals, offsets = prims._low_memory_max_pool_with_offsets( + x, + kernel_size, + stride, + padding, + dilation, + ceil_mode, + ) + indices = prims._low_memory_max_pool_offsets_to_indices( + offsets, + kernel_size, + x.shape[-dim:], + stride, + padding, + dilation, + ) + return vals, indices + + +@register_decomposition(aten.max_pool2d_with_indices) +def max_pool2d_with_indices( + x: torch.Tensor, + kernel_size: list[int], + stride: int | list[int] | None = None, + padding: int | list[int] = 0, + dilation: int | list[int] = 1, + ceil_mode: bool = False, +) -> tuple[torch.Tensor, torch.Tensor]: + return _max_pool_with_indices( + x, kernel_size, stride, padding, dilation, ceil_mode, dim=2 + ) + + +@register_decomposition(aten.max_pool3d_with_indices) +def max_pool3d_with_indices( + x: torch.Tensor, + kernel_size: list[int], + stride: int | list[int] | None = None, + padding: int | list[int] = 0, + dilation: int | list[int] = 1, + ceil_mode: bool = False, +) -> tuple[torch.Tensor, torch.Tensor]: + return _max_pool_with_indices( + x, kernel_size, stride, padding, dilation, ceil_mode, dim=3 + ) + + +@register_decomposition(aten.searchsorted.Scalar) +def searchsorted_scalar( + sorted_sequence: torch.Tensor, + self: torch.types.Number, + *, + out_int32: bool = False, + right: bool = False, + side: str | None = None, + sorter: torch.Tensor | None = None, +) -> torch.Tensor: + return aten.searchsorted( + sorted_sequence, + torch.tensor([self], device=sorted_sequence.device), + out_int32=out_int32, + right=right, + side=side, + sorter=sorter, + )[0] + + +@register_decomposition(aten.bucketize.Scalar) +def bucketize_scalar( + self: torch.types.Number, + boundaries: torch.Tensor, + *, + out_int32: bool = False, + right: bool = False, +) -> torch.Tensor: + return aten.bucketize( + torch.tensor([self], device=boundaries.device), + boundaries, + out_int32=out_int32, + right=right, + ).squeeze(0) + + +@decomp.register_decomposition(aten.rrelu_with_noise_functional, extra_random_decomps) +def rrelu_with_noise_functional( + self: torch.Tensor, + noise: torch.Tensor, + lower: float = 0.125, + upper: float = 0.3333333333333333, + training: bool = False, + generator: torch.Generator | None = None, +) -> tuple[torch.Tensor, torch.Tensor]: + if training: + not_positive = self <= 0 + r = aten.uniform(self, lower, upper, generator=generator) + output = torch.where(not_positive, self * r, self) + noise_out = torch.where(not_positive, r, 1) + return output, noise_out + else: + negative_slope = (lower + upper) / 2 + return aten.leaky_relu(self, negative_slope), torch.Tensor() + + +@register_decomposition(aten.repeat_interleave.Tensor) +def repeat_interleave_Tensor( + repeat: torch.Tensor, + output_size: int | None = None, +) -> torch.Tensor: + if config.triton.autotune_at_compile_time: + # We can't compile-time auto-tune this because + # it expects specific data in `repeat` + return NotImplemented + if output_size is None or type(output_size) is not int: + return NotImplemented + if repeat.device.type == "mps": + return NotImplemented + if repeat.dtype not in [torch.int32, torch.int64]: + raise AssertionError( + f"expected repeat dtype int32 or int64, got {repeat.dtype}" + ) + if repeat.ndim != 1: + raise AssertionError(f"expected repeat.ndim == 1, got {repeat.ndim}") + cumsum = repeat.cumsum(0) + pos = torch.arange(output_size, device=repeat.device) + indices = torch.searchsorted( + cumsum, pos, out_int32=(repeat.dtype == torch.int32), right=True + ) + return torch.clamp(indices, max=repeat.size(0) - 1) + + +# intentionally not registered +def conv1d_to_conv2d( + input: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor | None = None, + stride: tuple[int] = (1,), + padding: tuple[int] = (0,), + dilation: tuple[int] = (1,), + groups: int = 1, +) -> torch.Tensor: + # Shapes: + # input: (N, C_in, L_in) + # weight: (C_out, C_in // groups, K) + # bias: (C_out,) + if not (input.dim() == 3 and weight.dim() == 3): + raise AssertionError("Expect (N,C_in,L) and (C_out,C_in//groups,K)") + + # pyrefly: ignore [bad-assignment] + stride = stride[0] + # pyrefly: ignore [bad-assignment] + padding = padding[0] + # pyrefly: ignore [bad-assignment] + dilation = dilation[0] + + # Unsqueeze to make input 2D: (N,C,L) -> (N,C,L,1) + input_2d = input.unsqueeze(-1) + # Unsqueeze kernel: (C_out,C_in/groups,K) -> (C_out,C_in/groups,K,1) + weight_2d = weight.unsqueeze(-1) + + # Call conv2d with adjusted args + out_2d = aten.conv2d.default( + input_2d, + weight_2d, + bias, + stride=(stride, 1), + padding=(padding, 0), + dilation=(dilation, 1), + groups=groups, + ) + + # Squeeze dummy dimension back out: (N,C_out,L_out,1) -> (N,C_out,L_out) + return out_2d.squeeze(-1) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/dependencies.py b/.venv/lib/python3.12/site-packages/torch/_inductor/dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..1ebcc98a5eb4945340830f57ed65b2903df8a4f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/dependencies.py @@ -0,0 +1,918 @@ +import abc +import dataclasses +import itertools +import logging +import re +from collections.abc import Callable, Iterable, Sequence +from typing import Any, TypeVar +from typing_extensions import Self +from unittest.mock import patch + +import sympy + +import torch +from torch._inductor.utils import get_free_symbols +from torch.fx.experimental.symbolic_shapes import free_symbols, free_unbacked_symbols +from torch.utils._ordered_set import OrderedSet + +from ..utils._sympy.symbol import make_symbol, SymT +from .codegen.common import index_prevent_reordering +from .ops_handler import DefaultHandler +from .utils import ( + get_dtype_size, + reduction_num_outputs, + sympy_index_symbol, + sympy_subs, + VarRanges, +) +from .virtualized import ReductionType, V + + +T = TypeVar("T") + +log = logging.getLogger(__name__) +is_indirect = re.compile(r"indirect|tmp").search + + +class Dep(abc.ABC): + name: str + index: sympy.Expr + + @abc.abstractmethod + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + pass + + @abc.abstractmethod + def rename(self, renames: dict[str, str]) -> Self: + pass + + @abc.abstractmethod + def get_numel(self) -> sympy.Expr: + pass + + @abc.abstractmethod + def numbytes_hint(self) -> int: + pass + + @abc.abstractmethod + def numel_hint(self) -> int: + pass + + @abc.abstractmethod + def has_unbacked_symbols(self) -> bool: + pass + + @abc.abstractmethod + def is_contiguous(self) -> bool: + pass + + def normalize_with_stride_order(self, prefix: str = "t") -> Self: + return self + + +@dataclasses.dataclass(frozen=True) +class MemoryDep(Dep): + # pyrefly: ignore [bad-override] + name: str + # pyrefly: ignore [bad-override] + index: sympy.Expr + var_names: tuple[sympy.Symbol, ...] + size: tuple[sympy.Expr, ...] + mode: str | None = None + + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return ( + get_free_symbols(self.index, unbacked_only) + | get_free_symbols(self.size, unbacked_only) + | get_free_symbols(self.var_names, unbacked_only) + ) + + def __repr__(self) -> str: + maybe_mode = "" + if self.mode is not None: + maybe_mode = f", {self.mode}" + return f"MemoryDep({self.name!r}, {self.index}, {self.ranges}{maybe_mode})" + + @property + def num_vars(self) -> int: + return len(self.var_names) + + def decide_loop_order_to_match(self, other: "MemoryDep") -> list[int] | None: + """ + Can return None if not able to decide loop orders. + """ + if self.num_vars != other.num_vars: + raise AssertionError( + f"expected num_vars to match, got {self.num_vars} and {other.num_vars}" + ) + + # ignore broadcast for now since broadcast causes extra 0 strides + # which makes it hard to decide the correct loop orders. + if self.num_vars != len(self.index.free_symbols): + return None + if other.num_vars != len(other.index.free_symbols): + return None + + # bail out if any size is 0 or 1 + # For size == 0, it's an empty tensor, any strides for that dimension + # are equivalent. Skip for simplicity and it may not matter that much. + # + # For size == 1, it cause tie for strides of different dimensions. + # Also when we first time create LoopBody in ComputedBuffer.simplify_and_reorder + # we can dependencies.index_vars_squeeze which should already squeeze + # the size == 1 dimensions. + if any(s == 0 or s == 1 for s in itertools.chain(self.size, other.size)): + return None + + # Extract strides for both expression + self_strides = V.graph.sizevars.stride_hints(self.index, self.var_names) + other_strides = V.graph.sizevars.stride_hints(other.index, other.var_names) + + # Even if the shape contains no 0/1, some complex index expression may + # still have duplicate stride values. Here is an example: + # https://gist.github.com/shunting314/511a7e1ec88aa2e1a8ec85d8445ab129 + # We don't reorder the loop for these cases for now, but in theory + # we could improve the algorithm to detect the correct loop orders. + if len(OrderedSet(self_strides)) != len(self_strides) or len( + OrderedSet(other_strides) + ) != len(other_strides): + log.debug( + "unable to decide loop order. self_dep=%s v.s. other_dep=%s, self_strides=%s v.s. other_strides=%s", + self, + other, + self_strides, + other_strides, + ) + return None + + # May happen if self and other are as follows + # MemoryDep('addmm_6', 393216*d0 + 768*d1 + d2, {d0: 16, d1: 512, d2: 768}, None) + # MemoryDep('addmm_6', 98304*d0 + d1 + 768*d2, {d0: 64, d1: 768, d2: 128}, None) + if OrderedSet(self_strides) != OrderedSet(other_strides): + return None + + stride_to_index = {s: i for i, s in enumerate(self_strides)} + order = [stride_to_index[s] for s in other_strides] + + if OrderedSet(order) != OrderedSet(range(self.num_vars)): + raise AssertionError( + f"expected order to be a permutation of range({self.num_vars}), got {order}" + ) + return order + + def get_offset(self) -> sympy.Expr: + """ + Return the offset by setting every variable to be 0. + """ + return sympy_subs(self.index, dict.fromkeys(self.var_names, 0)) + + def normalize(self) -> "MemoryDep": + """ + Normalize by merging loops. The difference from normalize_with_stride_order is, + this method does not reorder loops while normalize_with_stride_order reorders + loops based on stride order. + """ + return MemoryDep( + self.name, + *_RecordLoadStoreInner._normalize(self.index, self.ranges), # type: ignore[arg-type] + self.mode, + ) + + def normalize_with_stride_order(self, prefix: str = "t") -> "MemoryDep": + r""" + Used to decide if two MemoryDep does not equal due to different loop orders. + More specifically, when dep1 and dep2 are not equal, we can normalize + both and check if they are equal after that. If yes, then the mismatch is + caused by different loop orders. + """ + # import here to avoid circular import + from torch._inductor import ir + + strides = V.graph.sizevars.stride_hints(self.index, self.var_names) + + # pick a loop order with stride ordered decreasingly + order = sorted(range(len(strides)), key=strides.__getitem__, reverse=True) + stride_reorder = ir.same_reorder(order) + sizes = self.size + var_names = self.var_names + + new_reordered_sizes = stride_reorder(sizes) + new_reordered_var_names = stride_reorder(var_names) + + new_simplified_sizes, reindex, _prune = V.graph.sizevars._simplify_loops( + new_reordered_var_names, + new_reordered_sizes, + index_prevent_reordering( + [self.index], new_reordered_var_names, new_reordered_sizes + ), + ) + + # now let's create new symbols with the passed in prefix + var_ranges, add_var = var_builder(prefix) + replacement = dict( + zip( + new_reordered_var_names, + reindex([add_var(x) for x in new_simplified_sizes]), + ) + ) + new_index = sympy_subs(sympy.expand(self.index), replacement) # type: ignore[arg-type] # next PR + + out = MemoryDep( + self.name, new_index, tuple(var_ranges.keys()), tuple(var_ranges.values()) + ) # type: ignore[arg-type] + return out + + @property + def ranges(self) -> dict[sympy.Symbol, sympy.Expr]: + """{c0: 128, c1: 512, ...}""" + return dict(zip(self.var_names, self.size)) + + def simplify_with_ranges(self) -> "MemoryDep": + return MemoryDep( + name=self.name, + index=V.graph.sizevars.simplify_with_ranges(self.index, self.ranges), + var_names=self.var_names, + size=self.size, + mode=self.mode, + ) + + def get_numel(self) -> sympy.Expr: + if self.is_indirect(): + numel = V.graph.get_numel(self.name) + else: + vars: OrderedSet[sympy.Basic] = OrderedSet(self.index.free_symbols) + numel = sympy.S.One + for var, size in zip(self.var_names, self.size): + if var in vars: + numel = numel * size + return numel # type: ignore[return-value] + + def rename(self, renames: dict[str, str]) -> "MemoryDep": + if self.name in renames: + return MemoryDep( + renames[self.name], + self.index, + var_names=self.var_names, + size=self.size, + mode=self.mode, + ) + return self + + def numbytes_hint(self) -> int: + try: + return V.graph.sizevars.optimization_hint( + self.get_numel(), fallback=0 + ) * get_dtype_size(V.graph.get_dtype(self.name)) + except NotImplementedError: # NoneLayout + return 0 + + def numel_hint(self) -> int: + try: + return V.graph.sizevars.optimization_hint(self.get_numel(), fallback=0) + except NotImplementedError: # NoneLayout + return 0 + + def has_unbacked_symbols(self) -> bool: + return len(free_unbacked_symbols(self.get_numel())) > 0 + + def is_contiguous(self) -> bool: + if isinstance(self.index, sympy.Integer): + return True + return isinstance(self.index, sympy.Symbol) and self.index in self.var_names + + def stride1_for_last_dim(self, result_for_complex_expression: bool = True) -> bool: + """ + Whether the stride for the last dimension is 1. + """ + # python test/inductor/test_torchinductor_opinfo.py -k test_comprehensive_masked_scatter_cuda_float16 + # will exercise thru this corner case. + if len(self.var_names) == 0: + return True + + terms = self.index.args if isinstance(self.index, sympy.Add) else [self.index] + + last_sym = self.var_names[-1] + for term in terms: + if term == last_sym: + return True + + # Having a >1 stride for the last dimension is bad for perf + # return False. + if ( + isinstance(term, sympy.Mul) + and len(term.args) == 2 + and term.args[1] == last_sym + and isinstance(term.args[0], (int, sympy.Integer)) + and term.args[0] > 1 + ): + return False + + return result_for_complex_expression + + def is_scalar(self) -> bool: + if isinstance(self.index, sympy.Symbol): + return self.index not in self.var_names and not self.is_indirect() + return isinstance(self.index, (int, sympy.Integer)) + + def is_indirect(self) -> bool: + return any(is_indirect(v.name) for v in self.index.free_symbols) # type: ignore[attr-defined] + + +@dataclasses.dataclass(frozen=True) +class StarDep(Dep): + # pyrefly: ignore [bad-override] + name: str + mode: str | None = None + + # depends on the entire buffer + @property + # pyrefly: ignore [bad-override] + def index(self) -> sympy.Expr: + raise NotImplementedError("StarDep does not have an index") + + def get_numel(self) -> sympy.Expr: + return V.graph.get_numel(self.name) # type: ignore[return-value] + + def rename(self, renames: dict[str, str]) -> "StarDep": + if self.name in renames: + return StarDep(renames[self.name], self.mode) + return self + + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def numbytes_hint(self) -> int: + try: + return V.graph.sizevars.optimization_hint( + self.get_numel(), fallback=0 + ) * get_dtype_size(V.graph.get_dtype(self.name)) + except NotImplementedError: + return 0 # NoneLayout, MultiOutputLayout, etc + + def numel_hint(self) -> int: + try: + return V.graph.sizevars.optimization_hint(self.get_numel(), fallback=0) + except NotImplementedError: + return 0 # NoneLayout, MultiOutputLayout, etc + + def has_unbacked_symbols(self) -> bool: + return len(free_unbacked_symbols(self.get_numel())) > 0 + + def is_contiguous(self) -> bool: + return False + + def is_scalar(self) -> bool: + return False + + def is_indirect(self) -> bool: + return False + + +# Used for tracking mutation ordering +# if A reads a buffer and B mutates it +# B must be ordered after A +# +# This is useful for a variety of reasons. +# For example, if A's read is never actually used, we can eliminate it. +# Another case is if A's buffer ends up being fused away, we never need to +# materialize that buffer +@dataclasses.dataclass(frozen=True) +class WeakDep(Dep): + # Fake dependency on unused buffer + # pyrefly: ignore [bad-override] + name: str + # Buffer that is doing the mutation + mutating_buf: str + # WeakDep's are also used to add dependencies to prevent some specific reordering, + # E.g. collectives global ordering. + # But if other pass guarantees proper ordering by its logic, + # This additional "fake" deps will be holding optimizations. + # This flag is used to identify those additional deps. + is_fake: bool = False + + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + @property + # pyrefly: ignore [bad-override] + def index(self) -> sympy.Expr: + raise NotImplementedError("WeakDep does not have an index") + + def get_numel(self) -> sympy.Expr: + return sympy.S.One + + def rename(self, renames: dict[str, str]) -> "WeakDep": + if self.name in renames: + return WeakDep(renames[self.name], self.mutating_buf, self.is_fake) + return self + + def numbytes_hint(self) -> int: + return 1 # Purely inserted for ordering, not an actual dep + + def numel_hint(self) -> int: + return 1 # Purely inserted for ordering, not an actual dep + + def has_unbacked_symbols(self) -> bool: + return False + + def is_contiguous(self) -> bool: + return False + + +@dataclasses.dataclass(frozen=True) +class IndexExprDep: + index: sympy.Expr # type: ignore[assignment] + var_names: tuple[sympy.Symbol, ...] + size: tuple[sympy.Expr, ...] + + +@dataclasses.dataclass +class ReadWrites: + reads: OrderedSet[Dep] + writes: OrderedSet[Dep] + index_exprs: OrderedSet[IndexExprDep] + range_vars: list[sympy.Expr] | None = None + var_ranges: VarRanges | None = None + + def rename(self, renames: dict[str, str]) -> "ReadWrites": + return ReadWrites( + OrderedSet(dep.rename(renames) for dep in self.reads), + OrderedSet(dep.rename(renames) for dep in self.writes), + self.index_exprs, + self.range_vars, + self.var_ranges, + ) + + def with_read(self, dep: Dep | OrderedSet[Dep]) -> "ReadWrites": + if not isinstance(dep, (WeakDep, StarDep, OrderedSet)): + raise AssertionError( + f"expected WeakDep, StarDep, or OrderedSet, got {type(dep)}" + ) + if not isinstance(dep, OrderedSet): + dep = OrderedSet([dep]) + return ReadWrites( + OrderedSet.union(self.reads, dep), + self.writes, + self.index_exprs, + self.range_vars, + self.var_ranges, + ) + + def merge(self, other: "ReadWrites") -> "ReadWrites": + reads = OrderedSet.union(self.reads, other.reads) + writes = OrderedSet.union(self.writes, other.writes) + index_exprs = OrderedSet.union(self.index_exprs, other.index_exprs) + return ReadWrites(reads - writes, writes, index_exprs) + + @staticmethod + def merge_list(read_writes: list["ReadWrites"]) -> "ReadWrites": + all_writes = OrderedSet.union(*[rw.writes for rw in read_writes]) + all_reads = OrderedSet.union(*[rw.reads for rw in read_writes]) - all_writes + all_index_exprs = OrderedSet.union(*[rw.index_exprs for rw in read_writes]) + return ReadWrites(all_reads, all_writes, all_index_exprs) + + def remove_reads(self, rem_reads: OrderedSet[Dep]) -> "ReadWrites": + return ReadWrites( + self.reads - rem_reads, + self.writes, + self.index_exprs, + self.range_vars, + self.var_ranges, + ) + + def reads_and_writes(self) -> Iterable[Dep]: + return itertools.chain(self.reads, self.writes) + + def buffer_names(self, ignore_integer_index: bool = True) -> OrderedSet[str]: + """ + Integer index is used for load_seed. + """ + names: OrderedSet[str] = OrderedSet() + for dep in self.reads_and_writes(): + if not isinstance(dep, MemoryDep): + continue + if not ignore_integer_index or not isinstance( + dep.index, (int, sympy.Integer) + ): + names.add(dep.name) + return names + + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + result: OrderedSet[sympy.Symbol] = OrderedSet() + + for dep in self.reads_and_writes(): + result |= dep.get_free_symbol_uses(unbacked_only) + return result + + +class _RecordLoadStoreInner(V.MockHandler): # type: ignore[name-defined] + def __init__(self, var_ranges: VarRanges, normalize: bool) -> None: + super().__init__() + self._reads: OrderedSet[Dep] = OrderedSet() + self._writes: OrderedSet[MemoryDep] = OrderedSet() + self._index_exprs: OrderedSet[IndexExprDep] = OrderedSet() + self._var_ranges: VarRanges = var_ranges + self._should_normalize: bool = normalize + + @staticmethod + def drop_unused_symbols( + index: int | sympy.Expr, + var_names: list[sympy.Expr], + sizes: list[sympy.Expr], + ) -> None: + """ + Reduction has last (reduced) dim in its sizes, but + downstream users won't. Normalize this away. + """ + if not isinstance(index, sympy.Expr): + # index can be an int + return + free_symbols = index.free_symbols + while var_names and var_names[-1] not in free_symbols: + var_names.pop() + sizes.pop() + + @classmethod + def _normalize( + cls, index: sympy.Expr, var_ranges: VarRanges + ) -> tuple[sympy.Expr, tuple[sympy.Symbol, ...], tuple[sympy.Expr, ...]]: + # Try to further simplify the indexes even if simplify_loops didn't + # convert it to the simplest form because of the interference from + # different indexing formulas. + index_vars = [*var_ranges.keys()] + sizes = tuple(var_ranges.values()) # type: ignore[assignment] + new_sizes, reindex, _prune = V.graph.sizevars._simplify_loops( + index_vars, + sizes, + index_prevent_reordering([index], index_vars, sizes), + ) + + # assign new variables each dimension to deal with numbering mismatches + # d0, d1, d2 could become d0, d2 -- which won't match d0, d1 + new_vars, add_var = var_builder(canonicalization_prefix()) + replacement = dict(zip(index_vars, reindex([add_var(x) for x in new_sizes]))) + index = sympy_subs(sympy.expand(index), replacement) + + new_vars = [*new_vars.keys()] + new_sizes = [*new_sizes] + cls.drop_unused_symbols(index, new_vars, new_sizes) + return index, tuple(new_vars), tuple(new_sizes) # type: ignore[arg-type] + + def canonicalize( + self, index: sympy.Expr + ) -> tuple[sympy.Expr, tuple[sympy.Symbol, ...], tuple[sympy.Expr, ...]]: + if not self._should_normalize: + sizes = [V.graph.sizevars.simplify(x) for x in self._var_ranges.values()] + var_names = [k for k, v in zip(self._var_ranges.keys(), sizes) if v != 1] + sizes = [v for v in sizes if v != 1] + + self.drop_unused_symbols(index, var_names, sizes) + + return index, tuple(var_names), tuple(sizes) # type: ignore[return-value, arg-type] + var_ranges = { + k: V.graph.sizevars.simplify(v) + for k, v in self._var_ranges.items() + # TODO(jansel): explore this further normalization + # if k in free_symbols + } + return self._normalize(index, var_ranges) + + def load(self, name: str, index: sympy.Expr) -> None: + self._reads.add(MemoryDep(name, *self.canonicalize(index))) + + def load_seed(self, name: str, index: int) -> None: + if not isinstance(index, int): + raise AssertionError(f"expected index to be int, got {type(index)}") + self.load(name, sympy.Integer(index)) + + def store( + self, name: str, index: sympy.Expr, value: str, mode: str | None = None + ) -> None: + self._writes.add(MemoryDep(name, *self.canonicalize(index), mode=mode)) + + def store_reduction(self, name: str, index: sympy.Expr, value: str) -> None: + self.store(name, index, f"store_reduction({value})") + + def index_expr(self, index: sympy.Expr, dtype: torch.dtype | None) -> None: + self._index_exprs.add(IndexExprDep(*self.canonicalize(index))) + + def value_expr(self, index: sympy.Expr, dtype: torch.dtype | None) -> None: + self._index_exprs.add(IndexExprDep(*self.canonicalize(index))) + + def bucketize( + self, + values: T, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: T, + indexing_dtype: torch.dtype, + right: bool, + sorter: tuple[str, sympy.Expr] | None = None, + sorter_indices: T | None = None, + ) -> None: + """Records the names of the buffers that bucketize will read from.""" + self._reads.add(StarDep(boundaries[0])) + if sorter is not None: + self._reads.add(StarDep(sorter[0])) + + +class RecordLoadStore(V.KernelFormatterHandler): # type: ignore[name-defined] + def __init__(self, var_ranges: VarRanges, normalize: bool) -> None: + parent_handler = _RecordLoadStoreInner( + var_ranges=var_ranges, normalize=normalize + ) + super().__init__(parent_handler=parent_handler) + + +# TODO: check call sites +def var_builder(prefix: str) -> tuple[VarRanges, Callable[[sympy.Expr], sympy.Symbol]]: + cnt = itertools.count() + var_ranges: VarRanges = {} + + def add_var(length: sympy.Expr) -> sympy.Symbol: + v = sympy_index_symbol(f"{prefix}{next(cnt)}") + var_ranges[v] = length + return v + + return var_ranges, add_var + + +def index_vars_no_squeeze( + *argsizes: Sequence[sympy.Expr], prefix: str +) -> tuple[list[list[sympy.Symbol]], VarRanges]: + var_ranges, add_var = var_builder(prefix) + args: list[list[sympy.Symbol]] = [list(map(add_var, size)) for size in argsizes] + return args, var_ranges + + +def index_vars_squeeze( + *argsizes: Sequence[sympy.Expr], prefix: str = "d" +) -> tuple[list[Sequence[sympy.Expr]], VarRanges]: + from .ir import SqueezeView + + var_ranges, add_var = var_builder(prefix) + args: list[Sequence[sympy.Expr]] = [] + for size in argsizes: + new_size, reindex = SqueezeView.squeezer(size) + args.append(reindex(list(map(add_var, new_size)))) + return args, var_ranges + + +def extract_read_writes( + fn: Callable[..., Any], + *argsizes: Sequence[sympy.Expr], + normalize: bool = False, + prefix: str = "d", + hidden_args: Sequence[list[sympy.Expr]] = (), +) -> ReadWrites: + args, var_ranges = index_vars_squeeze(*argsizes, prefix=prefix) + + from .loop_body import LoopBody + + if isinstance(fn, LoopBody): + inner = extract_loop_body_with_args( + fn, + [*args, *hidden_args], # type: ignore[list-item] + var_ranges, + normalize, + ) + else: + # Slow path tracing the function + rw = RecordLoadStore(var_ranges, normalize=normalize) + with V.set_ops_handler(rw): + fn(*args, *hidden_args) + inner = rw.parent_handler + + if normalize: + range_vars = [] # Number of vars could differ due to normalization + else: + range_vars = [*itertools.chain.from_iterable(args)] + + return ReadWrites( + # pyrefly: ignore [missing-attribute] + OrderedSet(inner._reads), + # pyrefly: ignore [missing-attribute] + OrderedSet(inner._writes), + # pyrefly: ignore [missing-attribute] + inner._index_exprs, + range_vars, + var_ranges, + ) + + +def extract_loop_body_with_args( + fn: Any, + args: list[list[sympy.Expr]], + var_ranges: VarRanges, + normalize: bool = False, +) -> _RecordLoadStoreInner: + from .loop_body import MemoryUsageType + + # Fast path to avoid tracing when we already have a LoopBody + inner = _RecordLoadStoreInner(var_ranges=var_ranges, normalize=normalize) + name_to_index = fn.indexing_from_args(args) + if fn.indirect_vars: + # mimic the `tmpX` naming tracing gives us + repl = {v: make_symbol(SymT.TMP, i) for i, v in enumerate(fn.indirect_vars)} + name_to_index = {k: sympy_subs(v, repl) for k, v in name_to_index.items()} # type: ignore[arg-type] + for entry in fn.memory_usage[MemoryUsageType.LOAD]: + inner.load(entry.buffer_name, name_to_index[entry.index_name]) # type: ignore[arg-type] + for entry in fn.memory_usage[MemoryUsageType.LOAD_SEED]: + inner.load_seed(entry.buffer_name, int(name_to_index[entry.index_name])) # type: ignore[arg-type] + for entry in fn.memory_usage[MemoryUsageType.STORE]: + inner.store( + entry.buffer_name, + name_to_index[entry.index_name], + None, # type: ignore[arg-type] + entry.mode, + ) + for entry in fn.memory_usage[MemoryUsageType.STORE_REDUCTION]: + inner.store_reduction( + entry.buffer_name, + name_to_index[entry.index_name], + None, # type: ignore[arg-type] + ) + for entry in fn.memory_usage[MemoryUsageType.INDEX_EXPR]: + inner.index_expr(name_to_index[entry.index_name], None) + for entry in fn.memory_usage[MemoryUsageType.BUCKETIZE]: + # All that matters is that we record the buffer name, so place it in the + # "boundaries" name position to ensure that it's recorded. + inner.bucketize( + None, + (entry.buffer_name, None, None, None), + None, + None, # type: ignore[arg-type] + None, # type: ignore[arg-type] + ) + # fn.memory_usage[MemoryUsageType.CHECK_BOUNDS] intentionally skipped + return inner + + +def extract_input_node_reduction_ranges( + input_node: "torch._inductor.ir.IRNode", +) -> tuple[list[sympy.Expr] | None, list[sympy.Expr] | None]: + """ + Returns the size and reduction size of all inputs, if the sizes and reduction_sizes (if exist) are all the same. + It's possible that a node has multiple inputs, some are Reduction nodes and others are Pointwise nodes. + In this case, reduction_sizes of the Reduction nodes need to be the same. + Otherwise returns (None, None). + """ + + from .ir import ComputedBuffer, ExternKernel, Loops + + size: list[sympy.Expr] | None + reduction_size: list[sympy.Expr] | None + + if isinstance(input_node.get_defining_op(), ComputedBuffer): + # Input node has already been realized. Return its size and reduction_size. + size = [*input_node.get_size()] + reduction_size = [*input_node.get_reduction_size()] + if len(reduction_size) > 0: + return (size, reduction_size) + else: + return (None, None) + + if not isinstance(input_node.data.data, Loops): # type: ignore[attr-defined] + # Other IRNodes do not have reduction_ranges. + return (None, None) + + # There is one issue: what if there are views / permutations between the input node and its dependent realized nodes? + # The current method still uses reduction ranges from the dependent realized node, which is not ideal. + # Is there a way to check whether there are permutations in between? + reads = input_node.get_reads() + reduction_size: list[sympy.Expr] | None = None + size: list[sympy.Expr] | None = None + while reduction_size is None and len(reads) > 0: + seen: OrderedSet[str] = OrderedSet() + new_reads: list[Dep] = [] + for read in reads: + if not isinstance(read, MemoryDep): + continue + if read.name in seen: + continue + seen.add(read.name) + buffer = V.graph.try_get_buffer(read.name) + if buffer is None: + continue + op = buffer.get_defining_op() + if op is None or isinstance(op, ExternKernel): + continue + + if isinstance(op, ComputedBuffer) and len(op.get_reduction_size()) > 0: + if reduction_size is None: + reduction_size = [*op.get_reduction_size()] + size = [*op.get_size()] + elif reduction_size != [*op.get_reduction_size()] or size != [ + *op.get_size() + ]: + return (None, None) + else: + new_reads.extend(op.get_reads()) + if reads == new_reads: + return (size, reduction_size) + else: + reads = OrderedSet(new_reads) + return (size, reduction_size) + + +def canonicalization_prefix() -> str: + return "c" + + +# ops handler which computes all the free symbols for an IR +class FreeSymbolsOpsHandler(DefaultHandler): + symbols: OrderedSet[sympy.Symbol] + + def __init__(self, unbacked_only: bool = True) -> None: + self.symbols = OrderedSet() + self.get_symbols = free_unbacked_symbols if unbacked_only else free_symbols + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + for a in itertools.chain(args, kwargs.values()): + if isinstance(a, (sympy.Expr, sympy.logic.boolalg.Boolean)): + self.symbols |= self.get_symbols(a) + + def indirect_indexing( + self, + index_var: Any, + size: int | sympy.Expr, + check: bool = True, + wrap_neg: bool = True, + ) -> sympy.Symbol: + if isinstance(index_var, (sympy.Expr, sympy.logic.boolalg.Boolean)): + raise AssertionError( + f"index_var must not be a sympy Expr or Boolean, got {type(index_var)}" + ) + self.symbols |= self.get_symbols(size) + return sympy_index_symbol(f"({str(index_var)})") + + def frexp(self, x: Any) -> tuple[None, ...]: + return (None,) * 2 + + def scan( + self, dtypes: Any, combine_fn: Any, values: Sequence[Any] + ) -> tuple[None, ...]: + return (None,) * len(values) + + def sort( + self, dtypes: Any, values: Sequence[Any], stable: Any, descending: Any + ) -> tuple[None, ...]: + return (None,) * len(values) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: None | tuple[None, ...], + ) -> None | tuple[None, ...]: + num_values = reduction_num_outputs(reduction_type) + return (None,) * num_values if num_values > 1 else None + + def masked(self, mask: Any, body: Callable[..., Any], other: Any) -> None: + if not callable(body): + raise AssertionError("masked body must always be callable.") + # The body can make additional calls, for e.g. ops.indirect_indexing + body() + + +def extract_free_symbols( + fn: Callable[..., Any], + index: Sequence[sympy.Expr], + rindex: Sequence[sympy.Expr] | None = None, + unbacked_only: bool = True, +) -> OrderedSet[sympy.Symbol]: + from .ir import FlexibleLayout + + args = [index, rindex] if rindex is not None else [index] + handler = FreeSymbolsOpsHandler(unbacked_only) + # NB: I cargo culted the allow_indexing patch here, I don't understand why + # people do this all over + with ( + V.set_ops_handler(handler), + patch.object(FlexibleLayout, "allow_indexing", True), + ): + fn(*args) + return handler.symbols + + +class SymbolUsageCollectorOpsHandler(DefaultHandler): + usages: OrderedSet[str] + + def __init__(self, symbol: sympy.Symbol) -> None: + self.symbol = symbol + self.usages = OrderedSet() + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + used_here = self.symbol in args or self.symbol in kwargs.values() + if used_here: + self.usages.add(name) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/distributed_autotune.py b/.venv/lib/python3.12/site-packages/torch/_inductor/distributed_autotune.py new file mode 100644 index 0000000000000000000000000000000000000000..cde507abfc08ba06b96252b865bff13ce2259305 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/distributed_autotune.py @@ -0,0 +1,413 @@ +from __future__ import annotations + +import contextlib +import dataclasses +from typing import Any, TYPE_CHECKING +from unittest.mock import patch + +import sympy + +import torch._logging +import torch.distributed as dist +import torch.fx +from torch.utils._ordered_set import OrderedSet + +from . import config, select_algorithm +from .ir import ( + Buffer, + ChoiceCaller, + Layout, + MultiTemplateBuffer, + OperationBuffer, + StorageBox, + TensorBox, +) +from .kernel_inputs import KernelInputs, MMKernelInputs +from .scheduler import SchedulerNode +from .virtualized import NullHandler, V + + +if TYPE_CHECKING: + from collections.abc import Generator, Sequence + + +_DISTRIBUTED_AUTOTUNE_KEY = "distributed_autotune" + +_AUTOTUNE_PG: dist.ProcessGroup | None = None + + +@dataclasses.dataclass +class _DistributedAutotuneState: + """ + State used to track autotuning during a graph_context() + """ + + # This is the next operator index. Used to figure out which rank should do + # the autotuning. + autotuned_index: int = 0 + + # For debugging - used to make sure that we autotune the same number of + # local operators that we expected to. + autotuned_local_count: int = 0 + + +@dataclasses.dataclass +class _DistributedAutotuneInfo: + index: int + local: bool + + +def get_autotune_pg() -> dist.ProcessGroup | None: + if dist.is_available() and dist.is_initialized(): + global _AUTOTUNE_PG + if _AUTOTUNE_PG is None: + autotune_pg = dist.distributed_c10d._new_group_with_tag( + pg_tag="pt2_distributed_autotune_pg" + ) + if autotune_pg == dist.GroupMember.NON_GROUP_MEMBER: + raise AssertionError("Autotune process group must include all ranks") + _AUTOTUNE_PG = autotune_pg + return _AUTOTUNE_PG + + return None + + +def schedule(scheduler: torch._inductor.scheduler.Scheduler) -> None: + """ + Finish the distributed autotuning by propagating the autotuning results + between the ranks and then replacing the placeholder with the real Buffer. + """ + if not config.distributed_max_autotune_gemm: + raise AssertionError("distributed_max_autotune_gemm config must be enabled") + autotune_results = _autotune_local_nodes(scheduler) + choices_by_index = _sync(autotune_results) + _autotune_remote_nodes(scheduler, choices_by_index) + + +@contextlib.contextmanager +def graph_context() -> Generator[None, None, None]: + """ + Wrapped around processing a graph, sets up figuring out which ranks tune + which shapes. + """ + if isinstance( + V.get_distributed_autotune_state(check_poisoned=False), # type: ignore[call-arg] + _DistributedAutotuneState, + ): + raise AssertionError( + "distributed autotune state is already active, nested graph_context is not allowed" + ) + V.set_distributed_autotune_state(_DistributedAutotuneState()) + try: + yield + finally: + V.set_distributed_autotune_state(NullHandler()) + + +def maybe_autotune_remote( + name: str, choices: list[ChoiceCaller], inputs: list[Buffer], layout: Layout +) -> TensorBox | None: + """ + Used by an op (like `mm`) to determine if the op should be autotuned + locally (returns None) or remotely (returns a placeholder Buffer). + """ + if not config.distributed_max_autotune_gemm: + return None + + if not (autotune_pg := get_autotune_pg()): + return None + + if len(choices) <= 1: + return None + + state = V.distributed_autotune_state + index = state.autotuned_index + state.autotuned_index += 1 + local = index % autotune_pg.size() == autotune_pg.rank() + + V.current_node.meta[_DISTRIBUTED_AUTOTUNE_KEY] = _DistributedAutotuneInfo( + index, local + ) + if local: + state.autotuned_local_count += 1 + return None + + return torch._inductor.ir.TensorBox.create( + _DistributedAutotuneBuffer(name, inputs, layout) + ) + + +class _DistributedAutotuneBuffer(MultiTemplateBuffer): + """ + A MultiTemplateBuffer which represents a kernel being autotuned on a + different rank. When `schedule` is called this will be replaced by the + "real" buffer. + """ + + # Name of the kernel being autotuned. + _kernel_name: str + + def __init__( + self, + kernel_name: str, + inputs: list[Buffer], + layout: Layout, + ) -> None: + super().__init__( + layout, + inputs, + choice_timings_fn=self._dummy_choice_timings, + unfiltered_choices=[], + allowed_prologue_inps=OrderedSet({}), + ) + + self._kernel_name = kernel_name + + def _dummy_choice_timings( + self, _hint_override: int | None + ) -> dict[ChoiceCaller, float]: + # This should never get called. It means that a remote autotune was + # scheduled but never filled in. + raise NotImplementedError + + def autotune(self, ser_choice: _SerializedChoice) -> TensorBox: + """ + Given a _SerializedChoice (autotune results from another rank) + compute the final TensorBox. + """ + + from .select_algorithm import autotune_select_algorithm + + with patch.object(V.graph, "scheduler", None): + kernel_inputs = MMKernelInputs([*self.original_inputs]) + if not isinstance(self.layout, Layout): + raise AssertionError(f"Expected Layout, got {type(self.layout)}") + choice = ser_choice.get_choice(self.layout, kernel_inputs) + buffer, _ = autotune_select_algorithm( + self._kernel_name, + [choice], + kernel_inputs.nodes(), + self.layout, + ) + if not isinstance(buffer, TensorBox): + raise AssertionError(f"Expected TensorBox, got {type(buffer)}") + return buffer + + +# Can we make this async? +def _sync(autotune_results: list[_SerializedChoice]) -> Sequence[_SerializedChoice]: + """ + Perform the all_gather to collect the autotune results from all the ranks. + """ + + autotune_pg = get_autotune_pg() + if not autotune_pg: + raise AssertionError("autotune process group is not initialized") + + # Perform allgather + all_states: list[list[_SerializedChoice]] = [None] * autotune_pg.size() # type: ignore[list-item] + torch.distributed.all_gather_object(all_states, autotune_results, group=autotune_pg) + + node_count = sum(len(x) for x in all_states) + # It's faster to briefly lie about the type than to unzip the results and append. + choices_by_index: list[_SerializedChoice] = [None] * node_count # type: ignore[list-item] + + check_count = 0 + for other_results in all_states: + for choice in other_results: + if not isinstance(choice, _SerializedChoice): + raise AssertionError(f"Expected _SerializedChoice, got {type(choice)}") + if choices_by_index[choice.index] is not None: + raise AssertionError(f"duplicate choice for index {choice.index}") + choices_by_index[choice.index] = choice + check_count += 1 + + if node_count != check_count: + raise AssertionError(f"count mismatch: {node_count} != {check_count}") + return choices_by_index + + +class _SerializedChoice: + """ + This is a serializer for the autotune choice. KernelTemplateChoice can't + be serialized directly (the template and inputs prevent this) so we need to + serialize it by parts and reconstruct later on. + """ + + def __init__(self, index: int, choice: ChoiceCaller) -> None: + self.index = index + self.template_uid = _SerializedChoice._template_uid_from_choice(choice) + self.kwargs = self._compute_kwargs(choice.description) + + def get_choice(self, layout: Layout, inputs: KernelInputs) -> ChoiceCaller | None: + """ + Deserialize the ChoiceCaller and return it. + """ + + template = self._template_from_uid() + + kwargs = {**self.kwargs} + if "BLOCK_K" in kwargs: + # TODO: Do we really need to externally compute this value? If it's + # needed I'm surprised it's not just part of the original template + # description. + # This needs the actual 'k' to figure out the value. + k = inputs.nodes()[0].get_size()[1] + kwargs["EVEN_K"] = sympy.gcd(k, kwargs["BLOCK_K"]) == kwargs["BLOCK_K"] + + extra_kwargs: dict[str, Any] = {} + from .kernel_template_choice import ( + DictKernelTemplateParams, + KernelTemplateChoice, + ) + + params = DictKernelTemplateParams(kwargs) + ktc = KernelTemplateChoice(template, params, extra_kwargs, layout, inputs) + return ktc.choice + + @staticmethod + def _compute_kwargs(description: str) -> dict[str, int | str | bool]: + """ + Given a template description turn it into input kwargs. + """ + if not description: + return {} + + # TODO: It seems like it would be better if the template could provide + # this directly instead of having to parse a string. + kwargs: dict[str, int | str | bool] = {} + for cfg in description.split(","): + key, val = cfg.split("=", 1) + key, val = key.strip(), val.strip() + if val == "True": + kwargs[key] = True + elif val == "False": + kwargs[key] = False + elif val.isdigit(): + kwargs[key] = int(val) + else: + if not (val.startswith("'") and val.endswith("'")): + raise AssertionError( + f"expected string value to be single-quoted, got {val!r}" + ) + kwargs[key] = val[1:-1] + return kwargs + + @staticmethod + def _template_uid_from_choice(choice: ChoiceCaller) -> str: + """ + Given a ChoiceCaller figure out which template represents it. This + is reversed by _template_from_uid(). + """ + + # We need a better way to do this - right now we need to add each + # supported template directly. + if isinstance(choice, select_algorithm.ExternKernelCaller): + if choice.choice.name == "mm": + return "torch._inductor.kernel.mm.aten_mm" + else: + raise RuntimeError(f"TODO: kernel {choice.choice.name!r}") + elif isinstance(choice, select_algorithm.TritonTemplateCaller): + return "torch._inductor.kernel.mm.mm_template" + else: + raise RuntimeError(f"TODO: {type(choice)}") + + def _template_from_uid(self) -> Any: + """ + See _template_uid_from_choice(). + """ + parts = self.template_uid.split(".") + obj = globals()[parts[0]] + for k in parts[1:]: + obj = getattr(obj, k) + return obj + + +def _autotune_local_nodes( + scheduler: torch._inductor.scheduler.Scheduler, +) -> list[_SerializedChoice]: + """ + Go through the nodes in the scheduler and autotune the kernels which + should be autotuned by this rank. + """ + + autotune_results: list[_SerializedChoice] = [] + + for node in scheduler.nodes: + if not isinstance(node, SchedulerNode): + continue + + if (inner_node := node.node) is None: + continue + + if isinstance(inner_node, _DistributedAutotuneBuffer): + # This is marked for remote autotuning. + continue + + if not isinstance(inner_node, MultiTemplateBuffer): + continue + + if (origin_node := inner_node.origin_node) is None: + continue + + if (meta := origin_node.meta) is None: + continue + + info = meta.get(_DISTRIBUTED_AUTOTUNE_KEY) + if info is None: + continue + + if not info.local: + raise AssertionError( + "expected info.local to be True for locally autotuned node" + ) + + # We force autotuning here + # Still takes advantage of async precompile + # We need all the configs before fusion + min_choice, _ = inner_node.get_min_choice() + + choice = _SerializedChoice(info.index, min_choice) + autotune_results.append(choice) + + state = V.distributed_autotune_state + if len(autotune_results) != state.autotuned_local_count: + raise AssertionError( + f"incorrect local autotuned nodes found ({len(autotune_results)} != {state.autotuned_local_count})" + ) + return autotune_results + + +def _autotune_remote_nodes( + scheduler: torch._inductor.scheduler.Scheduler, + choices_by_index: Sequence[_SerializedChoice], +) -> None: + """ + Go through the nodes in the scheduler and autotune the nodes that were + autotuned on remote ranks. + """ + + for i, node in enumerate(scheduler.nodes): + if isinstance(node, SchedulerNode) and isinstance( + (dist_node := node.node), _DistributedAutotuneBuffer + ): + if dist_node.origin_node is None: + raise AssertionError("dist_node.origin_node must not be None") + info = dist_node.origin_node.meta[_DISTRIBUTED_AUTOTUNE_KEY] + out_tensorbox = dist_node.autotune(choices_by_index[info.index]) + + out_storage = out_tensorbox.data + if not isinstance(out_storage, StorageBox): + raise AssertionError(f"Expected StorageBox, got {type(out_storage)}") + out_buffer = out_storage.data + if not isinstance(out_buffer, OperationBuffer): + raise AssertionError( + f"Expected OperationBuffer, got {type(out_buffer)}" + ) + + if out_buffer.layout != dist_node.layout: + raise AssertionError( + f"layout mismatch: {out_buffer.layout} != {dist_node.layout}" + ) + + scheduler._replace_node(out_buffer, dist_node, i, node) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/dtype_propagation.py b/.venv/lib/python3.12/site-packages/torch/_inductor/dtype_propagation.py new file mode 100644 index 0000000000000000000000000000000000000000..2171fecae9cd26b4c52af856455543392901e034 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/dtype_propagation.py @@ -0,0 +1,505 @@ +# mypy: allow-untyped-defs +import functools +from collections.abc import Callable, Sequence +from typing import Any, Optional, Protocol, TYPE_CHECKING, TypeVar + +import sympy + +import torch +from torch._prims_common import ( + ELEMENTWISE_TYPE_PROMOTION_KIND, + is_integer_dtype, + type_to_dtype, +) +from torch.utils._ordered_set import OrderedSet + +from .ops_handler import OP_NAMES, OpsHandler +from .utils import upcast_compute_type +from .virtualized import OpsValue, V + + +T = TypeVar("T") +_MISSING_SHAPE = object() +_UNSIGNED_INT_DTYPES: frozenset[torch.dtype] = frozenset( + ( + torch.uint8, + torch.uint16, + torch.uint32, + torch.uint64, + ) +) + + +class DTypeVar(Protocol): + @property + def dtype(self) -> torch.dtype: ... + + +DTypeArg = DTypeVar | torch.types.Number | str | OpsValue + + +# Inputs need to be cacheable (e.g., not a CSEVar) in order for the cache to be effective +# So first decompose CSEVars -> tuple before calling this + + +@functools.cache +def get_promoted_dtype( + *args: Sequence[tuple[torch.dtype, bool]], + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND | None = None, +): + def construct_input(inp): + if inp[1]: + return torch.empty([], dtype=inp[0]) + else: + return torch.empty([1], dtype=inp[0]) + + inps = [construct_input(arg) for arg in args] + _, dtype = torch._prims_common.elementwise_dtypes( + *inps, + type_promotion_kind=( + type_promotion_kind + if type_promotion_kind + else ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ), + ) + return dtype + + +def promote_types( + args: Sequence[DTypeArg], + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND | None = None, +): + dtype_prop_candidates = [] + + for arg in args: + if isinstance(arg, str): + raise AssertionError(f"expected non-str arg, got {type(arg)}") + if isinstance(arg, OpsValue): + arg = arg.value + if not ( + isinstance(arg, torch._prims_common.Number) or hasattr(arg, "dtype") + ): + raise AssertionError("expected a Number or an object with a dtype") + + if isinstance(arg, torch._prims_common.Number): + dtype_prop_candidates.append((type_to_dtype(type(arg)), True)) + continue + + # pyrefly: ignore [missing-attribute] + dtype_prop_candidates.append((arg.dtype, getattr(arg, "is_scalar", False))) + + dtype = get_promoted_dtype( + *dtype_prop_candidates, + type_promotion_kind=type_promotion_kind, + ) + + return dtype + + +def _unwrap_dtype_arg(arg: DTypeArg) -> DTypeVar | torch.types.Number | str: + if isinstance(arg, OpsValue): + return arg.value + return arg + + +def _is_scalar_dtype_arg(arg: DTypeArg) -> bool: + arg = _unwrap_dtype_arg(arg) + if isinstance(arg, torch._prims_common.Number): + return True + + is_scalar = getattr(arg, "is_scalar", False) + if callable(is_scalar): + if is_scalar(): + return True + elif is_scalar: + return True + + shape = getattr(arg, "shape", _MISSING_SHAPE) + if shape is _MISSING_SHAPE: + return False + + if shape is None: + return True + if not isinstance(shape, Sequence): + return False + + return len(shape) == 0 + + +def _has_known_nonnegative_scalar_int_value(arg: DTypeArg) -> bool: + arg = _unwrap_dtype_arg(arg) + + if isinstance(arg, bool): + return True + if isinstance(arg, int): + return arg >= 0 + + dtype = getattr(arg, "dtype", None) + if dtype is None or not is_integer_dtype(dtype): + return False + if dtype in _UNSIGNED_INT_DTYPES: + return True + + lower = getattr(getattr(arg, "bounds", None), "lower", None) + if lower is None: + return False + if isinstance(lower, sympy.Expr): + return lower.is_nonnegative is True + return lower >= 0 + + +class DtypePropagationOpsHandler: + """ + Propagate dtype from args to output + """ + + # Singleton DtypePropagationOpsHandler, because we meta program over a number of op rules. + # Those are only defined after other inductor state has run. + + _instance: Optional["DtypePropagationOpsHandler"] = None + + def __new__(cls): + if cls._instance is None: + cls._instance = super().__new__(cls) + return cls._instance + + def __init__(self) -> None: + for op, rule in torch._inductor.utils.op_dtype_propagation_rules.items(): + fn = ( + functools.partial(self.return_dtype, dtype=rule.override_return_dtype) + if rule.override_return_dtype + else functools.partial( + self.op_dtype_rule, type_promotion_kind=rule.type_promotion_kind + ) + ) + setattr(self, op, fn) + + # Set pointwise operation rules + for op in torch._inductor.codegen.common.pointwise_overrides_data.values(): + if not hasattr(self, op.name): + setattr( + self, + op.name, + functools.partial( + self.op_dtype_rule, type_promotion_kind=op.type_promotion_kind + ), + ) + + # Set boolean operation rules + for op in torch._inductor.utils.boolean_ops(): + if not hasattr(self, op): + setattr( + self, op, functools.partial(self.return_dtype, dtype=torch.bool) + ) + + unimplemented_ops = OP_NAMES - OrderedSet(dir(self)) + torch._check( + len(unimplemented_ops) == 0, + lambda: f"Unimplemented dtype rule for ops: {unimplemented_ops}", + ) + + # metaprogrammed in __init__ + + @staticmethod + def op_dtype_rule( + *args: DTypeArg, type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND + ) -> torch.dtype: + return promote_types(args, type_promotion_kind=type_promotion_kind) + + @staticmethod + def return_dtype(*args: DTypeArg, dtype: torch.dtype) -> torch.dtype: + return dtype + + # op rules + + @staticmethod + def constant(value: torch.types.Number, dtype: torch.dtype) -> torch.dtype: + return upcast_compute_type(dtype) + + @staticmethod + def load_seed(name: str, offset: int) -> torch.dtype: + return upcast_compute_type(V.graph.get_dtype(name)) + + @staticmethod + def randint64(seed: int, offset: int, low: int, high: int) -> torch.dtype: + return torch.int64 + + @staticmethod + def masked( + mask: DTypeArg, body: Callable[[], DTypeArg], other: DTypeArg + ) -> torch.dtype: + from .loop_body import LoopBodyBlock + + if not isinstance(body, LoopBodyBlock): + raise AssertionError("body must be a LoopBodyBlock") + # TODO - we avoid calling this in codegen, needs work for non codegen use cases + loads = body.graph.find_nodes(op="call_method", target="load") + if len(loads) <= 1: + return promote_types([other]) + + return upcast_compute_type(V.graph.get_dtype(loads[-1].args[1])) + + @staticmethod + def where(a: DTypeArg, b: DTypeArg, c: DTypeArg) -> torch.dtype: + return promote_types([b, c]) + + @staticmethod + def index_expr(expr: sympy.Expr, dtype: torch.dtype) -> torch.dtype: + # `index_expr` is for indexing-style uses: the kernel's chosen + # indexing dtype wins over the requested int dtype. For uses that + # must honor `dtype` (e.g. user-typed `arange(int64)` whose result + # participates in tensor computation), `value_expr` is the right op + # - see `convert_index_expr_to_value_expr` which rewrites accordingly. + if dtype not in (torch.int32, torch.int64) or not hasattr( + V.kernel, "index_dtype" + ): + return upcast_compute_type(dtype) + + return V.kernel.get_index_dtype_as_torch_dtype() + + @staticmethod + def value_expr(expr: sympy.Expr, dtype: torch.dtype) -> torch.dtype: + # Unlike `index_expr`, `value_expr` always honors the requested + # dtype because the result feeds tensor-value computation. The + # sympy expression is emitted literally, so there is no + # bf16/fp16 -> fp32 compute-type promotion here. + return dtype + + @staticmethod + def to_dtype( + x: DTypeArg, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types=True, + ) -> torch.dtype: + return upcast_compute_type(dtype) if use_compute_types else dtype + + @staticmethod + def to_dtype_bitcast( + x: DTypeArg, dtype: torch.dtype, src_dtype: torch.dtype + ) -> torch.dtype: + return upcast_compute_type(dtype) + + @staticmethod + def gelu(x: DTypeArg) -> torch.dtype: + return promote_types([x]) + + @staticmethod + def mul(a: DTypeArg, b: DTypeArg) -> torch.dtype: + return promote_types([a, b]) + + @staticmethod + def truediv(a: DTypeArg, b: DTypeArg) -> torch.dtype: + return promote_types([a, b]) + + @staticmethod + def div_rn(a: DTypeArg, b: DTypeArg) -> torch.dtype: + return promote_types([a, b]) + + @staticmethod + def pow(a: DTypeArg, b: DTypeArg) -> torch.dtype: + dtype = promote_types([a, b]) + if ( + is_integer_dtype(dtype) + and _is_scalar_dtype_arg(a) + and _is_scalar_dtype_arg(b) + and not _has_known_nonnegative_scalar_int_value(b) + ): + # Scalar integer pow follows Python semantics: negative exponents + # produce a floating result, even though tensor integer pow stays + # integral or errors out in separate lowering paths. + return torch.float64 + return dtype + + @staticmethod + def mod(a: DTypeArg, b: DTypeArg) -> torch.dtype: + return promote_types([a, b]) + + @staticmethod + def indirect_indexing( + x: DTypeArg, size: int, check: bool = True, wrap_neg: bool = True + ) -> torch.dtype: + return torch.int64 + + @staticmethod + def randn(seed: int, offset: int) -> torch.dtype: + return torch.float + + @staticmethod + def rand(seed: int, offset: int) -> torch.dtype: + return torch.float + + @staticmethod + def rand_eager(seed, offset, threads_per_round, tid, vec) -> torch.dtype: + return torch.float + + @staticmethod + def store_reduction(name: str, index, value: DTypeArg) -> None: + return None + + @staticmethod + def reduction( + dtype: torch.dtype, src_dtype: torch.dtype, reduction_type: str, value: DTypeArg + ) -> torch.dtype: + return dtype + + @staticmethod + def store(name: str, index, value: DTypeArg, mode: str | None = None) -> None: + return None + + @staticmethod + def partial_accumulate( + name: str, + reduction_type: str, + value: DTypeArg, + extra_meta: dict[str, Any], + ) -> None: + return None + + @staticmethod + def load(name: str, index) -> torch.dtype: + return upcast_compute_type(V.graph.get_dtype(name)) + + @staticmethod + def floor(x: DTypeArg) -> torch.dtype: + return promote_types( + [x], type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT + ) + + @staticmethod + def ceil_to_int(x: DTypeArg, dtype: torch.dtype) -> torch.dtype: + return dtype + + @staticmethod + def int_truediv(x: DTypeArg, y: DTypeArg) -> torch.dtype: + return promote_types( + [x, y], type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT + ) + + @staticmethod + def scan( + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[[tuple[T, ...], tuple[T, ...]], tuple[T, ...]], + values: tuple[T, ...], + ) -> tuple[torch.dtype, ...]: + return dtypes + + @staticmethod + def fmod(x: DTypeArg, y: DTypeArg) -> torch.dtype: + return promote_types([x, y]) + + @staticmethod + def round_to_int(x: DTypeArg, dtype: torch.dtype) -> torch.dtype: + return dtype + + @staticmethod + def identity(x: DTypeArg) -> torch.dtype: + return promote_types([x]) + + @staticmethod + def frexp(x: DTypeArg) -> tuple[torch.dtype, torch.dtype]: + # TODO - need to handle multiple outputs + return (promote_types([x]), torch.int32) + + @staticmethod + def sort( + dtypes: tuple[torch.dtype, ...], + values: tuple[T, ...], + stable: bool, + descending: bool, + ) -> tuple[torch.dtype, ...]: + return dtypes + + @staticmethod + def trunc(x: DTypeArg) -> torch.dtype: + return promote_types([x]) + + @staticmethod + def bucketize( + values: DTypeArg, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: DTypeArg, + indexing_dtype: torch.dtype, + right: bool, + sorter: tuple[str, sympy.Expr] | None = None, + sorter_indices: T | None = None, + ) -> torch.dtype: + return indexing_dtype + + @staticmethod + def rshift(x: DTypeArg, y: DTypeArg) -> torch.dtype: + return promote_types([x]) + + @staticmethod + def round(x: DTypeArg) -> torch.dtype: + return promote_types( + [x], type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT + ) + + @staticmethod + def trunc_to_int(x: DTypeArg, dtype: torch.dtype) -> torch.dtype: + return dtype + + @staticmethod + def floor_to_int(x: DTypeArg, dtype: torch.dtype) -> torch.dtype: + return dtype + + @staticmethod + def truncdiv(x: DTypeArg, y: DTypeArg) -> torch.dtype: + return promote_types([x, y]) + + @staticmethod + def floordiv(x: DTypeArg, y: DTypeArg) -> torch.dtype: + return promote_types([x, y]) + + @staticmethod + def halide_clamp(value, size, check): + # TODO - way of registering dtype for op in backend + return torch.int32 + + @staticmethod + def dot(x: DTypeArg, y: DTypeArg) -> torch.dtype: + # triton tl.dot out_dtype is tl.float32 by default. + return torch.float32 + + @staticmethod + def inline_asm_elementwise( + *inputs, + asm, + constraints=None, + dtype=torch.float32, + is_pure=True, + pack=1, + input_dtypes=None, + ): + return dtype + + @staticmethod + def lshift(x: DTypeArg, y: DTypeArg) -> torch.dtype: + return promote_types([x]) + + @staticmethod + def check_bounds( + expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + return None + + def output(self, *args: DTypeArg) -> None: + raise AssertionError( + f"{type(self).__name__}: ops.output should not appear here" + ) + + def placeholder(self, index: int) -> torch.dtype: + raise AssertionError( + f"{type(self).__name__}: ops.placeholder should not appear here" + ) + + @staticmethod + def device_assert_async(cond, msg: str) -> None: + return None + + +if TYPE_CHECKING: + # pyrefly: ignore [inconsistent-inheritance] + class _typecheck_DtypePropagation(DtypePropagationOpsHandler, OpsHandler[Any]): + pass # mypy will error if we got any of the signatures wrong diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/exc.py b/.venv/lib/python3.12/site-packages/torch/_inductor/exc.py new file mode 100644 index 0000000000000000000000000000000000000000..b30fda0df44dcaf3e4ec39f72926f01bb650bbb3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/exc.py @@ -0,0 +1,175 @@ +from __future__ import annotations + +import os +import tempfile +import textwrap +from functools import lru_cache +from typing import Any, TYPE_CHECKING + +from torch._dynamo.exc import BackendCompilerFailed, ShortenTraceback + + +if TYPE_CHECKING: + import types + + from torch.cuda import _CudaDeviceProperties + +if os.environ.get("TORCHINDUCTOR_WRITE_MISSING_OPS") == "1": + + @lru_cache(None) + def _record_missing_op(target: Any) -> None: + with open(f"{tempfile.gettempdir()}/missing_ops.txt", "a") as fd: + fd.write(str(target) + "\n") + +else: + + def _record_missing_op(target: Any) -> None: # type: ignore[misc] + pass + + +class OperatorIssue(RuntimeError): + @staticmethod + def operator_str(target: Any, args: list[Any], kwargs: dict[str, Any]) -> str: + lines = [f"target: {target}"] + [ + f"args[{i}]: {arg}" for i, arg in enumerate(args) + ] + if kwargs: + lines.append(f"kwargs: {kwargs}") + return textwrap.indent("\n".join(lines), " ") + + +class MissingOperatorWithoutDecomp(OperatorIssue): + def __init__(self, target: Any, args: list[Any], kwargs: dict[str, Any]) -> None: + _record_missing_op(target) + super().__init__(f"missing lowering\n{self.operator_str(target, args, kwargs)}") + + +class MissingOperatorWithDecomp(OperatorIssue): + def __init__(self, target: Any, args: list[Any], kwargs: dict[str, Any]) -> None: + _record_missing_op(target) + super().__init__( + f"missing decomposition\n{self.operator_str(target, args, kwargs)}" + + textwrap.dedent( + f""" + + There is a decomposition available for {target} in + torch._decomp.get_decompositions(). Please add this operator to the + `decompositions` list in torch._inductor.decomposition + """ + ) + ) + + +class LoweringException(OperatorIssue): + def __init__( + self, + exc: Exception, + target: Any, + args: list[Any], + kwargs: dict[str, Any], + stack_trace: str | None = None, + ) -> None: + msg = f"{type(exc).__name__}: {exc}\n{self.operator_str(target, args, kwargs)}" + if stack_trace: + msg += f"{msg}\nFound from : \n {stack_trace}" + super().__init__(msg) + + +class SubgraphLoweringException(RuntimeError): + pass + + +class InvalidCxxCompiler(RuntimeError): + def __init__(self, compiler: str | None = None) -> None: + from . import config + + if compiler is None: + msg = ( + f"No working C++ compiler found in {config.__name__}.cpp.cxx: " + f"{config.cpp.cxx}" + ) + else: + msg = f"Compiler: {compiler} is not found." + super().__init__(msg) + + +class CppWrapperCodegenError(RuntimeError): + def __init__(self, msg: str) -> None: + super().__init__(f"C++ wrapper codegen error: {msg}") + + +class CppCompileError(RuntimeError): + def __init__(self, cmd: list[str], output: str) -> None: + if isinstance(output, bytes): + output = output.decode("utf-8") + + self.cmd = cmd + self.output = output + + super().__init__( + textwrap.dedent( + """ + C++ compile error + + Command: + {cmd} + + Output: + {output} + """ + ) + .strip() + .format(cmd=" ".join(cmd), output=output) + ) + + def __reduce__(self) -> tuple[type, tuple[list[str], str]]: + return (self.__class__, (self.cmd, self.output)) + + +class CUDACompileError(CppCompileError): + pass + + +class XPUCompileError(CppCompileError): + pass + + +class TritonMissing(ShortenTraceback): + def __init__(self, first_useful_frame: types.FrameType | None) -> None: + super().__init__( + "Cannot find a working triton installation. " + "Either the package is not installed or it is too old. " + "More information on installing Triton can be found at: https://github.com/triton-lang/triton", + first_useful_frame=first_useful_frame, + ) + + +class GPUTooOldForTriton(ShortenTraceback): + def __init__( + self, + # pyrefly: ignore [not-a-type] + device_props: _CudaDeviceProperties, + first_useful_frame: types.FrameType | None, + ) -> None: + super().__init__( + f"Found {device_props.name} which is too old to be supported by the triton GPU compiler, " + "which is used as the backend. Triton only supports devices of CUDA Capability >= 7.0, " + f"but your device is of CUDA capability {device_props.major}.{device_props.minor}", + first_useful_frame=first_useful_frame, + ) + + +class InductorError(BackendCompilerFailed): + backend_name = "inductor" + + def __init__( + self, + inner_exception: Exception, + first_useful_frame: types.FrameType | None, + ) -> None: + self.inner_exception = inner_exception + ShortenTraceback.__init__( + self, + f"{type(inner_exception).__name__}: {inner_exception}", + first_useful_frame=first_useful_frame, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/extern_node_serializer.py b/.venv/lib/python3.12/site-packages/torch/_inductor/extern_node_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..a265d315e683d8930f86311179a18642323c4224 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/extern_node_serializer.py @@ -0,0 +1,27 @@ +import json + +from torch._export.serde.schema import ExternKernelNode, ExternKernelNodes, Node +from torch._export.serde.serialize import _dataclass_to_dict, EnumEncoder +from torch._inductor.ir import ExternKernelNode as inductor_ExternKernelNode + + +def serialize_extern_kernel_node( + extern_kernel_node: inductor_ExternKernelNode, +) -> ExternKernelNode: + if not isinstance(extern_kernel_node.node, Node): + raise AssertionError( + f"expected node to be a Node, got {type(extern_kernel_node.node)}" + ) + return ExternKernelNode( + name=extern_kernel_node.name, + node=extern_kernel_node.node, + ) + + +def extern_node_json_serializer( + extern_kernel_nodes: list[inductor_ExternKernelNode], +) -> str: + serialized_nodes = ExternKernelNodes( + nodes=[serialize_extern_kernel_node(node) for node in extern_kernel_nodes] + ) + return json.dumps(_dataclass_to_dict(serialized_nodes), cls=EnumEncoder) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/freezing.py b/.venv/lib/python3.12/site-packages/torch/_inductor/freezing.py new file mode 100644 index 0000000000000000000000000000000000000000..f9e8d4e99ea43f1e68be92e324f20da8cd4f65f6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/freezing.py @@ -0,0 +1,301 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import itertools +import logging +import weakref +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._dynamo.utils import dynamo_timed, lazy_format_graph_code +from torch._functorch.aot_autograd import MutationType +from torch._functorch.compile_utils import fx_graph_cse +from torch._inductor.constant_folding import constant_fold, replace_node_with_constant +from torch._inductor.freezing_utils import enter_freezing, record_has_frozen_params +from torch._inductor.fx_passes.freezing_patterns import freezing_passes +from torch._inductor.fx_passes.post_grad import view_to_reshape + +from . import config + + +aten = torch.ops.aten +prims = torch.ops.prims + +log = logging.getLogger(__name__) + + +def replace_params_with_constants( + gm: torch.fx.GraphModule, + flat_params: list[Any], + fw_metadata: torch._functorch.aot_autograd.ViewAndMutationMeta, +) -> list[int]: + """ + Replaces the parameters of a PyTorch GraphModule with constants wherever possible. + Returns a list of indices representing the input parameters that were not converted to constants. + """ + params = gm.graph.find_nodes(op="placeholder") + fake_inp_nodes = params[: len(params)] + preserved_arg_indices = [] + aliased_input_args = [ + out_info.base_idx + for out_info in fw_metadata.output_info + if out_info.base_idx is not None + ] + + # TODO (tmanlaibaatar) figure out why this is different + # from mutated_inp_runtime_indices + mutated_inps = [ + i + for i, m in enumerate(fw_metadata.input_info) + if m.mutation_type + in (MutationType.MUTATED_IN_GRAPH, MutationType.MUTATED_OUT_GRAPH) + ] + + static_indices_new = [] + static_indices_offset = 0 + for i, (real_input, node) in enumerate(zip(flat_params, fake_inp_nodes)): + if i in mutated_inps or i in aliased_input_args: + preserved_arg_indices.append(i) + if i in fw_metadata.static_input_indices: + new_static_index = i - static_indices_offset + static_indices_new.append(new_static_index) + else: + replace_node_with_constant(gm, node, real_input) + static_indices_offset += 1 + # add on non param inputs + preserved_arg_indices.extend(range(len(flat_params), len(params))) + # is this necessary ? + fw_metadata.static_input_indices = static_indices_new + gm.recompile() + return preserved_arg_indices + + +def freeze( + dynamo_gm: torch.fx.GraphModule, + aot_autograd_gm: torch.fx.GraphModule, + example_inputs: list[torch._subclasses.FakeTensor], +) -> tuple[torch.fx.GraphModule, list[int]]: + """ + Inlines parameters that are not mutated into constants and optimizes the graph through constant propagation + and other techniques. If enabled, the function also discards the original parameters of the module for memory efficiency. + + Assumes that this function is run in dynamo tracing post aot_autograd. + + Args: + dynamo_gm (torch.fx.GraphModule): The Dynamo constructed GraphModule. + aot_autograd_gm (torch.fx.GraphModule): The aot_autograd constructed GraphModule to be frozen. + example_inputs (List[torch.Tensor]): A list of example input tensors to be used in the freezing process. + + Returns: + Tuple[torch.fx.GraphModule, List[int]]: A tuple containing the frozen GraphModule and a list of indices + of the inputs that were preserved (not turned into constants). + """ + with enter_freezing(): + return _freeze(dynamo_gm, aot_autograd_gm, example_inputs) + + +def _freeze( + dynamo_gm: torch.fx.GraphModule, + aot_autograd_gm: torch.fx.GraphModule, + example_inputs: list[torch._subclasses.FakeTensor], +) -> tuple[torch.fx.GraphModule, list[int]]: + # We have converted conv's weight to channels last which may meet error for .view + # when doing fake_tensor_prop. So we need to convert view to reshape first. + # See the details in fx_codegen_and_compile of compile_fx.py. + view_to_reshape(aot_autograd_gm) + + if tracing_context := torch._guards.TracingContext.try_get(): + fw_metadata = tracing_context.fw_metadata + if tracing_context.params_flat_unwrap_subclasses is None: + raise AssertionError( + "expected tracing_context.params_flat_unwrap_subclasses to be set" + ) + params_flat = tracing_context.params_flat_unwrap_subclasses + if not (fw_metadata is not None and params_flat is not None): + raise AssertionError("expected fw_metadata and params_flat to be set") + + preserved_arg_indices = replace_params_with_constants( + aot_autograd_gm, params_flat, fw_metadata + ) + else: + inputs = aot_autograd_gm.graph.find_nodes(op="placeholder") + preserved_arg_indices = list(range(len(inputs))) + + # TODO - further restrict cse ? right now needed to dedup aliasing ops + cse_graph = fx_graph_cse(aot_autograd_gm.graph) + aot_autograd_gm.graph = cse_graph + aot_autograd_gm.recompile() + + aot_example_inputs = [example_inputs[ind] for ind in preserved_arg_indices] + freezing_passes(aot_autograd_gm, aot_example_inputs) + + constant_fold(aot_autograd_gm) + # invalidate nn Modules + if config.freezing_discard_parameters: + invalidate_eager_modules() + discard_traced_gm_params(dynamo_gm) + + log.debug( + "%s", lazy_format_graph_code("FROZEN GRAPH", aot_autograd_gm, colored=True) + ) + + record_has_frozen_params(aot_autograd_gm) + return aot_autograd_gm, preserved_arg_indices + + +class ErasedTensor(torch.Tensor): + @staticmethod + def __new__(cls, elem, name, owning_mod): + return super().__new__(cls, elem.to(device="meta")) + + def __init__(self, elem, name: str | None, mod) -> None: + self.erased_name = name + self.owning_mod_ref = weakref.ref(mod) + + @classmethod + def __torch_dispatch__(cls, func, types, args=(), kwargs=None): # type: ignore[override] + erased_tensors = [ + e + # pyrefly: ignore [bad-unpacking] + for e in pytree.arg_tree_leaves(*args, **kwargs) + if isinstance(e, ErasedTensor) + ] + if len(erased_tensors) == 0: + raise AssertionError("expected at least one ErasedTensor argument") + e = erased_tensors[0] + + raise RuntimeError( + f"Trying to run Pytorch Eager Module after Dynamo Freezing. " + "The original parameters have been discarded for memory efficiency. " + f"Found in op {func} for erased parameter {e.erased_name} of {e.owning_mod_ref()}" + ) + + +def invalidate_eager_modules(): + with torch.utils._python_dispatch._disable_current_modes(): + for ( + mod + ) in torch._guards.TracingContext.get().module_context.nn_modules.values(): + if not isinstance(mod, torch.nn.Module): + continue + + for attr_name, tensor in list( + itertools.chain( + mod.named_parameters(recurse=False), + # pyrefly: ignore [bad-argument-type] + mod.named_buffers(recurse=False), + ) + ): + with torch._dispatch.python.no_python_dispatcher(): + e_t = ErasedTensor(tensor, attr_name, mod) + if isinstance(tensor, torch.nn.Parameter): + e_t.requires_grad_(True) + e_t._is_param = True + setattr(mod, attr_name, e_t) + + +def discard_traced_gm_params(mod: torch.fx.GraphModule): + with torch.utils._python_dispatch._disable_current_modes(): + for attr_name, tensor in list( + itertools.chain( + mod.named_parameters(recurse=False), + # pyrefly: ignore [bad-argument-type] + mod.named_buffers(recurse=False), + ) + ): + with torch._dispatch.python.no_python_dispatcher(): + e_t = ErasedTensor(tensor, attr_name, mod) + if isinstance(tensor, torch.nn.Parameter): + e_t.requires_grad_(True) + e_t._is_param = True + setattr(mod, attr_name, e_t) + + +def enforce_output_layout(gm: torch.fx.GraphModule): + """ + Make sure the output node's layout does not change due to compiler optimizations + by adding aten.as_strided nodes with the expected strides. + + Only used for inference so we can assume all graph outputs are model outputs. + """ + *_, output_node = gm.graph.nodes + out_list = output_node.args[0] + with gm.graph.inserting_before(output_node): + for n in out_list: + if not isinstance( + n.meta["val"], torch.Tensor + ) or not torch._prims_common.is_non_overlapping_and_dense_or_false( + n.meta["val"] + ): + continue + + # Use materialize_symints intentionally; see its docstring for why. + ft = n.meta["val"] + stride_args = tuple(gm.graph.materialize_symints(ft.stride())) + new_node = gm.graph.call_function( + prims.inductor_force_stride_order.default, (n, stride_args) + ) + + # can not call + # n.replace_all_uses_with(new_node) + # since it will replace the usage of n in new_node itself. + output_node.replace_input_with(n, new_node) + + gm.graph.lint() + gm.recompile() + + +def enforce_as_strided_input_layout(gm: torch.fx.GraphModule): + """ + Make sure the as_strided node's input's layout does not change due to compiler + optimizations, because the as_strided strides info depends on input tensor stride info. + """ + + as_strided_ops = [ + torch.ops.aten.as_strided.default, + torch.ops.aten.as_strided_.default, + torch.ops.aten.as_strided_scatter.default, + ] + strided_nodes = [n for n in gm.graph.nodes if n.target in as_strided_ops] + for n in strided_nodes: + with gm.graph.inserting_before(n): + # Use materialize_symints intentionally; see its docstring for why. + ft = n.args[0].meta["val"] + stride_args = tuple(gm.graph.materialize_symints(ft.stride())) + new_node = gm.graph.call_function( + prims.inductor_force_stride_order.default, (n.args[0], stride_args) + ) + n.replace_input_with(n.args[0], new_node) + + gm.graph.lint() + gm.recompile() + + +def convert_conv_weights_to_channels_last(gm: torch.fx.GraphModule): + """ + Convert 4d convolution weight tensor to channels last format. + + This pass is performed before freezing so the added nodes can be constant + folded by freezing. + """ + with dynamo_timed("convert_conv_weights_to_channels_last"): + convs = [n for n in gm.graph.nodes if n.target is aten.convolution.default] + for conv in convs: + weight_node = conv.args[1] + if len(weight_node.meta["val"].size()) != 4 or weight_node.meta[ + "val" + ].is_contiguous(memory_format=torch.channels_last): + # not a 4d tensor or already channels last, skip + continue + + with gm.graph.inserting_before(conv): + new_node = gm.graph.call_function( + aten.clone.default, + (weight_node,), + {"memory_format": torch.channels_last}, + ) + conv.replace_input_with(weight_node, new_node) + + enforce_as_strided_input_layout(gm) + enforce_output_layout(gm) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/freezing_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/freezing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8a14890aacbd76acd0e49726d9eba99c590e83c8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/freezing_utils.py @@ -0,0 +1,55 @@ +import contextlib +import threading +from collections.abc import Generator +from typing import Any + +import torch + + +_TLS = threading.local() + + +def _freezing_active() -> bool: + return getattr(_TLS, "freezing_active", False) + + +@contextlib.contextmanager +def enter_freezing() -> Generator[Any, None, None]: + """ + Context manager to designate when freezing is active. + """ + prev = _freezing_active() + _TLS.freezing_active = True + try: + yield + finally: + _TLS.freezing_active = prev + + +def record_has_frozen_params(gm: torch.fx.GraphModule) -> None: + """ + Mark the gm as having frozen params. + """ + gm._has_frozen_params = True # type: ignore[assignment] + + +def has_frozen_params(gm: torch.fx.GraphModule) -> bool: + """ + Return True if the gm has frozen parameters. + """ + return getattr(gm, "_has_frozen_params", False) + + +def maybe_set_is_frozen_param(t: torch.Tensor) -> None: + """ + Mark the provided tensor as a frozen param if freezing is active. + """ + if _freezing_active(): + t._is_frozen_param = True # type: ignore[attr-defined] + + +def is_frozen_param(t: torch.Tensor) -> bool: + """ + Return True if the tensor is a frozen param. + """ + return getattr(t, "_is_frozen_param", False) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fuzzer.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fuzzer.py new file mode 100644 index 0000000000000000000000000000000000000000..a7284c5b894728feb6de635490655cf26dd0802a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fuzzer.py @@ -0,0 +1,1007 @@ +import importlib +import itertools +import logging +import pickle +import random +import signal +import string +import traceback +import types +from collections.abc import Callable, KeysView, Sequence +from enum import Enum +from functools import partial, wraps +from types import FrameType +from typing import Any, get_args, get_origin, Literal, TypeVar, Union + +import torch +from functorch.compile import min_cut_rematerialization_partition +from torch._inductor.custom_graph_pass import CustomGraphPass, CustomPartitionerFn +from torch._inductor.scheduler import BaseSchedulerNode +from torch.utils._config_module import _ConfigEntry, ConfigModule +from torch.utils._ordered_set import OrderedSet + + +log = logging.getLogger(__name__) + + +def is_type(type_hint, comp_type) -> bool: # type: ignore[no-untyped-def] + """ + Determines if type_hint is comp_type. There are some type annotations that this doesn't work for. + I think it's because some Type annotations are Type Objects and some are Special Forms, but not sure. + There's definite room for improvement to make this more general for someone who deeply understands + Python types. + """ + return type_hint is comp_type or get_origin(type_hint) is comp_type + + +def is_optional_type(type_hint) -> bool: # type: ignore[no-untyped-def] + """ + Special case of is_type. + """ + origin = get_origin(type_hint) + + if origin is Union: + args = get_args(type_hint) + return type(None) in args + + return False + + +def is_callable_type(type_hint) -> bool: # type: ignore[no-untyped-def] + """ + Special Case of is_type. + """ + return type_hint.__name__ == "Callable" + + +class DummyPass(CustomGraphPass): + """ + A Dummy pass to be used by ConfigFuzzer + """ + + def __call__(self, graph: torch.fx.graph.Graph) -> None: + return None + + def uuid(self) -> Any | None: + return None + + +class DummyPartitionerFn(CustomPartitionerFn): + """ + A Dummy partitioner function to be used by ConfigFuzzer + """ + + def __call__( + self, gm: torch.fx.GraphModule, joint_inputs: Sequence[object], **kwargs: Any + ) -> tuple[torch.fx.GraphModule, torch.fx.GraphModule]: + return min_cut_rematerialization_partition(gm, joint_inputs, **kwargs) + + def uuid(self) -> Any | None: + return None + + +T = TypeVar("T") + + +class TypeExemplars: + """ + This class returns examples of a Type, given its class name. + """ + + TYPE_EXEMPLARS: dict[str, Any] = { + CustomGraphPass.__name__: DummyPass(), + CustomPartitionerFn.__name__: DummyPartitionerFn(), + torch.fx.graph.Graph.__name__: torch.fx.graph.Graph(), + BaseSchedulerNode.__name__: BaseSchedulerNode(None), # type: ignore[arg-type] + } + + @staticmethod + def example(t: type[T]) -> T | None: + """ + Return an example of a class. + """ + + return TypeExemplars.TYPE_EXEMPLARS.get(t.__name__, None) + + @staticmethod + def contains(t: type[T]) -> bool: + return t.__name__ in TypeExemplars.TYPE_EXEMPLARS + + +def check_halide_import() -> bool: + """checks if we have halide available""" + try: + importlib.import_module("halide") + return True + except ModuleNotFoundError: + return False + + +if check_halide_import(): + CUDA_BACKEND = ["triton", "halide"] +else: + CUDA_BACKEND = ["triton"] + + +class Status(Enum): + """ + The Status return value enum for Config Fuzzer + """ + + # ConfigFuzzer skipped the test + SKIPPED = "skipped" + # ConfigFuzzer compiled and ran the test and function it passed. + PASSED = "passed" + # ConfigFuzzer failed to compile the test function + FAILED_COMPILE = "failed_compile" + # ConfigFuzzer compiled the test function and running it raised an exception + FAILED_RUN_COMPILE_EXCEPTION = "failed_run_compile_exception" + # ConfigFuzzer ran eager and it raised an exception + FAILED_RUN_EAGER_EXCEPTION = "failed_run_eager_exception" + # ConfigFuzzer compiled the test function, but the return value indicated that the compiled value didn't match the + # value from eager (or however else you set up the comparison in the test function) + FAILED_RUN_RETURN = "failed_run_return" + + def failing(self) -> bool: + """ + Convenience method to check whether these status represent failure. + """ + return ( + self == Status.FAILED_COMPILE + or self == Status.FAILED_RUN_EAGER_EXCEPTION + or self == Status.FAILED_RUN_COMPILE_EXCEPTION + or self == Status.FAILED_RUN_RETURN + ) + + +# Sometime the types of configs aren't expressive enough to be captured by python type system, so the options can be +# manually specified here: +# TODO this needs to be indexed to the module, like inductor or dynamo, for name collisions +TYPE_OVERRIDES: dict[str, list[Any]] = { + "cuda_backend": CUDA_BACKEND, + "post_grad_fusion_options": [ + { + "batch_linear_post_grad": { + "shape_broadcast_batch_linear": True, + "fuse_nodes_with_same_users": True, + }, + "batch_aten_mul": {"fuse_nodes_with_same_parent": False}, + "batch_aten_sigmoid": {"fuse_nodes_with_same_parent": True}, + "batch_aten_add": {"fuse_nodes_with_same_parent": True}, + "normalization_aten_pass": {}, + "unbind_stack_aten_pass": {}, + }, + { + "batch_aten_add": {}, + "batch_aten_mul": {}, + "batch_aten_sub": {}, + "batch_aten_div": {}, + "group_linear": {"require_fbgemm": True}, + }, + ], + "autoheuristic_collect": [ + {"pad_mm": True, "mixed_mm": True}, + {"pad_mm": True, "mixed_mm": False}, + {"pad_mm": False, "mixed_mm": True}, + {"pad_mm": False, "mixed_mm": False}, + ], + "autoheuristic_use": [ + {"pad_mm": True, "mixed_mm": True}, + {"pad_mm": True, "mixed_mm": False}, + {"pad_mm": False, "mixed_mm": True}, + {"pad_mm": False, "mixed_mm": False}, + ], + "traceable_tensor_subclasses": [OrderedSet()], + "nontraceable_tensor_subclasses": [OrderedSet()], +} +SamplingType = Callable[[str, type[Any], Any], Any] + + +class SamplingMethod(Enum): + """ + This class handles the process of assigning concrete values to type annotations. So a type annotation of + ```python + foo: Optional[int] = None + ``` + Will be assigned an int if the dispatch function gets TOGGLE, or a 50/50 split between an int and None if it gets + RANDOM. + """ + + TOGGLE = "TOGGLE" # toggle to the opposite value + RANDOM = "RANDOM" # randomly choose an option + + @staticmethod + def _generate_value_for_type( + random_sample: bool, field_name: str, type_hint: type[Any], default: Any + ) -> Any: + """ + Generates a value of a type based on the setting. + """ + # look for name in type overrides + if field_name in TYPE_OVERRIDES: + return random.choice(TYPE_OVERRIDES[field_name]) + + if type_hint is bool: + return random.choice([True, False]) if random_sample else not default + elif type_hint is int: + # NOTE initially tried to use negation of the value, but it doesn't work because most types are ints + # when they should be natural numbers + zero. Python types to cover these values aren't super convenient. + return random.randint(0, 1000) + elif type_hint is float: + return random.uniform(0, 1000) + elif type_hint is str: + characters = string.ascii_letters + string.digits + string.punctuation + return "".join( + random.choice(characters) for _ in range(random.randint(1, 20)) + ) + elif is_type(type_hint, list): + elem_type = ( + get_args(type_hint) + or ([type(default[0])] if default and len(default) else [type(None)]) + )[0] + new_default = default[0] if default and len(default) > 0 else None + return [ + SamplingMethod._generate_value_for_type( + random_sample, field_name, elem_type, new_default + ) + for _ in range(random.randint(1, 3)) + ] + elif is_type(type_hint, set): # noqa: set_linter + indexable = list(default) + elem_type = ( + get_args(type_hint) + or ([type(indexable[0])] if default and len(default) else [type(None)]) + )[0] + new_default = indexable[0] if default and len(default) > 0 else None + return { # noqa: set_linter + SamplingMethod._generate_value_for_type( + random_sample, field_name, elem_type, new_default + ) + for _ in range(random.randint(1, 3)) + } + elif is_type(type_hint, OrderedSet): + indexable = list(default) + elem_type = ( + get_args(type_hint) + or ([type(indexable[0])] if default and len(default) else [type(None)]) + )[0] + new_default = indexable[0] if default and len(default) > 0 else None + return OrderedSet( + [ + SamplingMethod._generate_value_for_type( + random_sample, field_name, elem_type, new_default + ) + for _ in range(random.randint(1, 3)) + ] + ) + elif is_type(type_hint, dict): + key_type, value_type = get_args(type_hint) or ( + tuple(map(type, next(iter(default.items())))) + if (default is not None and len(default)) + else (type(None), type(None)) + ) + if default is not None and len(default.items()) > 0: + default_key, default_val = next(iter(default.items())) + else: + default_key, default_val = None, None + return { + SamplingMethod._generate_value_for_type( + random_sample, field_name, key_type, default_key + ): SamplingMethod._generate_value_for_type( + random_sample, field_name, value_type, default_val + ) + for _ in range(random.randint(0, 3)) + } + elif is_type(type_hint, Union) or is_type(type_hint, types.UnionType): + # do whatever is not the type of default + union_args = get_args(type_hint) + if len(union_args) <= 1: + raise ValueError("Union type with no args") + if random_sample: + new_type = random.choice(union_args) + else: + new_type = random.choice( + [t for t in union_args if t is not type(default)] + ) + try: + new_default = new_type() + except Exception: + # if default constructor doesn't work, try None + new_default = None + + return SamplingMethod._generate_value_for_type( + random_sample, field_name, new_type, new_default + ) + elif is_type(type_hint, tuple): + args = get_args(type_hint) or tuple(map(type, default)) + zipped = zip(args, default) + return tuple( + map( # noqa: C417 + lambda x: SamplingMethod._generate_value_for_type( + random_sample, field_name, x[0], x[1] + ), + zipped, + ) + ) + elif is_type(type_hint, Literal): + literal_args = get_args(type_hint) + if not literal_args: + raise ValueError("Literal type with no args") + if random_sample: + return random.choice(literal_args) + else: + choices = [t for t in literal_args if t != default] + if choices: + return random.choice(choices) + else: + return default + elif is_optional_type(type_hint): + optional_args = get_args(type_hint) + if not optional_args: + raise ValueError("Optional type with no args") + elem_type = optional_args[0] + if random_sample: + return random.choice( + [ + None, + SamplingMethod._generate_value_for_type( + random_sample, field_name, elem_type, default + ), + ] + ) + else: + if default is None: + return SamplingMethod._generate_value_for_type( + random_sample, field_name, elem_type, None + ) + else: + return None + elif type_hint is type(None): + return None + elif is_callable_type(type_hint): + callable_args = get_args(type_hint) + if not callable_args: + raise ValueError("Callable type with no args") + return_type = callable_args[-1] + + @wraps(lambda *args, **kwargs: None) + def dummy_function(*args, **kwargs): # type: ignore[no-untyped-def] + return SamplingMethod._generate_value_for_type( + random_sample, field_name, return_type, None + ) + + return dummy_function + elif type_hint == torch._ops.OpOverload: + return torch.ops.aten.add.default + elif TypeExemplars.contains(type_hint): + return TypeExemplars.example(type_hint) + elif type_hint == Any: + return 1 if default != 1 else 2 + else: + raise ValueError(f"Unable to process type {type_hint}. PRs welcome :)") + + @staticmethod + def dispatch(sm: "SamplingMethod") -> SamplingType: + """ + Returns a function that will generate values from a type, based on the SamplingMethod passed in. + """ + if sm == SamplingMethod.RANDOM: + return partial(SamplingMethod._generate_value_for_type, True) + elif sm == SamplingMethod.TOGGLE: + return partial(SamplingMethod._generate_value_for_type, False) + else: + raise ValueError(f"malformed sampling method: {sm}") + + +class Default: + """ + Singleton default object that will cause the ConfigFuzzer to always use the default value set in the config. + """ + + +DEFAULT = Default() + +# The combination of config settings being set (based on their strings) +ComboType = tuple[str, ...] + + +class ResultType: + """ + The mapping of the combo strings to the result status after running the config fuzzer. + """ + + _vals: dict[ComboType, Status] + + def __repr__(self) -> str: + return f"ResultType[{self._vals}]" + + def __init__(self) -> None: + self._vals = {} + + def __len__(self) -> int: + return len(self._vals) + + def num_ran(self) -> int: + """ + Returns how many combos actually ran (weren't skipped). + """ + ret = len(self._vals) + for status in self._vals.values(): + if status == Status.SKIPPED: + ret -= 1 + return ret + + def set(self, combo: ComboType, status: Status) -> None: + combo = tuple(sorted(combo)) + self._vals[combo] = status + + def lookup(self, combo: ComboType) -> Status | None: + combo = tuple(sorted(combo)) + return self._vals.get(combo, None) + + def keys(self) -> KeysView[ComboType]: + return self._vals.keys() + + +# Type that maps config strings to their default value +ConfigType = dict[str, Any] +# Callable that returns a bool +FactoryOutputType = Callable[[], bool] +# input function factory +FactoryType = Callable[[], FactoryOutputType] + +# Why are some configs disabled by default? Because if we don't the fuzzer produces uninteresting results. +# It will always hone-in on these failures, even with the most basic model, making it useless for +# debugging more complex models. +# +# More explicit explanations are below: +# Out of Scope: We can't fuzz, say, the cuda version because that comes from the environment and will +# produce a failure if not aligned with env. +# Known Failure: Disabled due to known failure. Hopefully re-enable. Known failures are listed in the +# docstring of this file. +# Required: Required for the fuzzer to operate (removing caching, etc.) +# FSDP: Flag meant for FSDP that fails in non FSDP envs. Re-enable these if you're testing FSDP. +# Typing: disabled because the type annotation of the config isn't constrained enough to produce +# meaningful fuzz values. These could be improved. +# Timing: These take too long to compile, feel free to enable. +MODULE_DEFAULTS: dict[str, ConfigType] = { + "torch._inductor.config": { + "force_disable_caches": True, # Required + "cpp.cxx": DEFAULT, # Out of Scope + "TYPE_CHECKING": DEFAULT, # Not a config + "max_autotune_pointwise": DEFAULT, # Timing + "max_autotune_gemm": DEFAULT, # Timing, re-enable when autotune speed improvements merged. + "max_autotune_gemm_backends": DEFAULT, # Timing + "max_autotune_conv_backends": DEFAULT, # Timing + "max_autotune_gemm_search_space": DEFAULT, # Timing + "max_autotune_subproc_result_timeout_seconds": DEFAULT, # Timing + "max_autotune_subproc_graceful_timeout_seconds": DEFAULT, # Timing + "max_autotune_subproc_terminate_timeout_seconds": DEFAULT, # Timing + "aot_inductor.presets": DEFAULT, # Typing + "cuda.arch": DEFAULT, # Out of Scope + "cuda.version": DEFAULT, # Out of Scope + "cuda.cutlass_dir": DEFAULT, # Out of Scope + "cuda.cuda_cxx": DEFAULT, # Out of Scope + "rocm.arch": DEFAULT, # Out of Scope + "rocm.ck_supported_arch": DEFAULT, # Out of Scope + "rocm.ck_dir": DEFAULT, # Out of Scope + "rocm.rocm_home": DEFAULT, # Out of Scope + "check_stack_no_cycles_TESTING_ONLY": DEFAULT, # Testing + "sleep_sec_TESTING_ONLY": DEFAULT, # Testing + "triton.inject_relu_bug_TESTING_ONLY": DEFAULT, # Testing + "reorder_for_compute_comm_overlap": DEFAULT, # FSDP + "enabled_metric_tables": DEFAULT, # Typing + "profile_bandwidth_regex": DEFAULT, # Known Failure + "disable_cpp_codegen": DEFAULT, # Known Failure + "trace.save_real_tensors": DEFAULT, # Known Failure + "pre_grad_fusion_options": DEFAULT, # Typing + "external_matmul": DEFAULT, # Typing, need to add this to type overrides or type exemplars. + "test_configs.autotune_choice_name_regex": DEFAULT, # Typing + "test_configs.autotune_choice_desc_regex": DEFAULT, # Typing + "cpp.enable_floating_point_contract_flag": DEFAULT, # Typing + "post_grad_custom_pre_pass": DEFAULT, # Typing + "post_grad_custom_post_pass": DEFAULT, # Typing + "reorder_for_compute_comm_overlap_passes": DEFAULT, # Typing + "joint_custom_post_pass": DEFAULT, # Typing + "joint_custom_pre_pass": DEFAULT, # Typing + "pre_grad_custom_pass": DEFAULT, # Typing + "custom_partitioner_fn": DEFAULT, # Typing + "inductor_choices_class": DEFAULT, # Typing + "cudagraph_policy": DEFAULT, # Typing + }, + "torch._dynamo.config": { + "traceable_tensor_subclasses": DEFAULT, # Typing + "nontraceable_tensor_subclasses": DEFAULT, # Typing + "compiled_autograd_kwargs_override": DEFAULT, # Typing + "fail_on_recompile_limit_hit": DEFAULT, # fails in combo with suppress_errors + "suppress_errors": DEFAULT, + "caching_precompile": False, # Required + }, +} + + +class ConfigFuzzer: + """ + This tool makes it easy to search through config state-space with a minimal reproduction or test, either for + debugging or just bug hunting. + It has two entry points: + - bisect, which randomly flips configs and tries to find the minimal reproduction upon failure. + - fuzz_n_tuple, which tries every combination of n configs. This grows quickly as a function of n, so beware. + bisect is recommended, but fuzz_n_tuple can give you peace of mind that a new config will compose with + every other config. + + The main interface is a function factory that will return Callables to be torch.compiled. This function factory + should return a test function when it's called. Said test function returns a boolean, which determines whether + the ConfigFuzzer considers it a successful run or not. Throwing an exception from within the function will be + considered a failure as well. + + # Example usage: + + ```python + import torch._inductor.config as cfg + + + def create_simple_test_model_gpu() -> FactoryOutputType: + batch_size = 32 + seq_length = 50 + hidden_size = 768 + + def test_fn() -> bool: + inp = torch.randn(batch_size, seq_length, hidden_size, device="cuda") + weight = torch.randn(hidden_size, hidden_size, device="cuda") + matmul_output = inp @ weight + final_output = torch.nn.LayerNorm(hidden_size, device="cuda")(matmul_output) + return True + + return test_fn + + + fuzzer = ConfigFuzzer(cfg, create_simple_test_model_gpu, seed=2) + + # Test every pair of configs: + results = fuzzer.fuzz_n_tuple(n, max_combinations=10000000) + + visualize_results(n, results) + + # Test random configs with bisection: + ret = fuzzer.bisect(num_attempts=10) + + # reproduce a failing config + fuzzer.reproduce( + [{"triton.autotune_pointwise": ..., "coordinate_descent_tuning": ...}] + ) + ``` + + The list of known failures on inductor config are: + cpp_wrapper, disable_cpp_codegen + combo_kernels, benchmark_combo_kernel, profile_bandwidth, profile_bandwidth_regex + trace.enabled, trace.save_real_tensors + """ + + sample: SamplingType + default: ConfigType + + def __init__( + self, + config_module: ConfigModule, + test_model_fn_factory: FactoryType, + seed: int, + default: ConfigType | None = None, + sm: SamplingMethod = SamplingMethod.TOGGLE, + test_timeout: int = 3600, + ): + """ + Args: + config_module: The module containing the configs to fuzz + test_model_fn_factory: Function that returns a test model, which runs and returns True if successful, or + the outputs if they should be compared with eager + seed: Randomness seed. + default: Default values for the config. Inductor has preset based on known failures. + sm: How type value samples are generated, default TOGGLE. + test_timeout: max time a test can take. + """ + self.seed = seed + self.test_timeout = test_timeout + self.detailed_results: dict[ComboType, dict[str, Any]] = {} + self.config_module = config_module + self.test_model_fn_factory = test_model_fn_factory + self.fields: dict[str, _ConfigEntry] = self.config_module._config + self.sample = SamplingMethod.dispatch(sm) + + if default is None: + if self.config_module.__name__ in MODULE_DEFAULTS: + self.default = MODULE_DEFAULTS[self.config_module.__name__] + else: + raise ValueError("No default passed to ConfigFuzzer.") + else: + self.default = default + + def __repr__(self) -> str: + return ( + f"ConfigFuzzer(config_module={self.config_module}, " + f"test_model_fn_factory={self.test_model_fn_factory}, seed={self.seed}, default={self.default})" + ) + + def _set_config(self, field_name: str, value: Any) -> None: + """Set a config value in the module.""" + setattr(self.config_module, field_name, value) + + def _reset_configs(self) -> None: + """Reset all configs to their default values.""" + for field_name, field_obj in self.fields.items(): + self._set_config(field_name, field_obj.default) + + def new_config(self) -> ConfigType: + """creates a new config from the default""" + ret = { + name: val if val != DEFAULT else self.fields[name].default + for name, val in self.default.items() + } + return ret + + def reproduce(self, configs: Sequence[ConfigType]) -> ResultType: + """entrypoint to reproduce any failure""" + results = ResultType() + for conf in configs: + self._reproduce_single_helper(conf, results) + return results + + def _reproduce_single_helper(self, conf: ConfigType, results: ResultType) -> None: + print(f"Starting repro of {conf}") + new_config = self.new_config() + new_config.update(conf) + self.test_config(results, new_config) + print(f"Status of {conf}:\n{results.lookup(tuple(conf.keys()))}") + + def reproduce_single(self, config: ConfigType) -> ResultType: + results = ResultType() + self._reproduce_single_helper(config, results) + return results + + def _fuzz_helper(self, results: ResultType, combo: ComboType) -> Status: + print(combo) + if st := results.lookup(combo): + # we already processed this config + return st + + config = self.new_config() + + skip = False + for field_name in combo: + if field_name in config: + # don't break here because we need to build the config dict + skip = True + if field_name.startswith("_"): + skip = True + field = self.fields[field_name] + value = self.sample(field_name, field.value_type, field.default) + config[field_name] = value + if skip: + results.set(combo, Status.SKIPPED) + return Status.SKIPPED + + return self.test_config(results, config) + + def fuzz_n_tuple(self, n: int, max_combinations: int = 1000) -> ResultType: + """ + Test every combination of n configs. + + returns a dict of this shape: {(config-1, config-2... config-n): status} + """ + results = ResultType() + print(f"Starting {n}-tuple testing with seed {self.seed}") + random.seed(self.seed) + + for combo in itertools.combinations(self.fields, n): + st = self._fuzz_helper(results, combo) + if st != Status.SKIPPED: + max_combinations -= 1 + if max_combinations <= 0: + print("Reached maximum combinations limit") + break + + return results + + def save_state(self, filename: str = "fuzzer_state.pkl") -> None: + """Save the current fuzzer state to a file""" + with open(filename, "wb") as f: + pickle.dump( + {"results": self.results, "detailed_results": self.detailed_results}, f + ) + + def load_state(self, filename: str = "fuzzer_state.pkl") -> None: + """Load fuzzer state from a file""" + with open(filename, "rb") as f: + state = pickle.load(f) + self.results = state["results"] + self.detailed_results = state.get("detailed_results", {}) + + def timeout_handler(self, signum: int, frame: FrameType | None) -> None: + raise TimeoutError("Test execution timed out") + + def test_config(self, results: ResultType, config: ConfigType) -> Status: + """ + Tests a config by calling the function produced by the factory function. + """ + original_handler = signal.signal(signal.SIGALRM, self.timeout_handler) + signal.alarm(self.test_timeout) + print(f"Testing config {config}") + config_tuple = tuple(config.keys()) + if ret := results.lookup(config_tuple): + signal.signal(signal.SIGALRM, original_handler) + return ret + + def print_config() -> None: + for field, value in config.items(): + print(f"{field} = {value}") + + def get_error_info(exc: Exception) -> dict[str, Any]: + return { + "exception": str(exc), + "traceback": traceback.format_exc(), + "config": config.copy(), + } + + def handle_return( + message: str, + return_status: Status, + print_traceback: bool, + exc: Exception | None, + ) -> Status: + signal.signal(signal.SIGALRM, original_handler) + print(f"{message} with config combination:") + print_config() + if exc: + self.detailed_results[config_tuple] = get_error_info(exc) + if print_traceback: + traceback.print_exc() + results.set(config_tuple, return_status) + return return_status + + # reset config + torch._dynamo.reset() + self._reset_configs() + for name, value in config.items(): + self._set_config(name, value) + + # try running eager + test_model_fn = self.test_model_fn_factory() + try: + test_model_fn() + except Exception as exc: + return handle_return( + "Eager exception", Status.FAILED_RUN_EAGER_EXCEPTION, True, exc + ) + + # try compilation + try: + test_model_fn2 = self.test_model_fn_factory() + comp = torch.compile(test_model_fn2, backend="inductor") + except Exception as exc: + return handle_return( + "Exception compiling", Status.FAILED_COMPILE, True, exc + ) + + # try running compiled + try: + compile_result = comp() + except Exception as exc: + return handle_return( + "Exception running compiled", + Status.FAILED_RUN_COMPILE_EXCEPTION, + True, + exc, + ) + + # bool return value means don't compare with eager + if not compile_result: + return handle_return( + "Function returned False", Status.FAILED_RUN_RETURN, False, None + ) + else: + return handle_return("Function succeeded", Status.PASSED, False, None) + + def bisect(self, num_attempts: int = 100, p: float = 0.5) -> list[ConfigType]: + """ + Test configs and bisect to minimal failing configuration. + """ + print(f"Starting random testing with bisection, seed {self.seed}, and p {p}") + random.seed(self.seed) + self._reset_configs() + results = ResultType() + ret: list[ConfigType] = [] + + for attempt in range(num_attempts): + print(f"Random attempt {attempt + 1}/{num_attempts}") + + config = self.new_config() + + for field_name, config_entry in self.fields.items(): + if ( + field_name not in config + and not field_name.startswith("_") + and "TESTING_ONLY" not in field_name + and random.random() < p + ): + value = self.sample( + field_name, config_entry.value_type, config_entry.default + ) + config[field_name] = value + + status = self.test_config(results, config) + if status not in OrderedSet([Status.PASSED, Status.SKIPPED]): + if minimal_failing_config := self._bisect_failing_config( + results, config + ): + print(f"Minimum failing config: {minimal_failing_config}") + ret.append(minimal_failing_config) + + return ret + + def _bisect_failing_config( + self, results: ResultType, failing_config: ConfigType + ) -> ConfigType | None: + return self._bisect_failing_config_helper(results, list(failing_config.items())) + + def _bisect_failing_config_helper( + self, results: ResultType, failing_config: list[tuple[str, Any]] + ) -> ConfigType | None: + """ + Bisect a failing configuration to find minimal set of configs that cause failure. + + Splits it into halves, then fourths, then tries dropping configs one-by-one. + """ + print(f"bisecting config: {failing_config}") + + if not failing_config: + return None + + def test(x: list[tuple[str, Any]]) -> Status: + d = dict(x) + result = self.test_config(results, d) + return result + + if len(failing_config) <= 1: + return dict(failing_config) if test(failing_config).failing() else None + + random.shuffle(failing_config) + + mid = len(failing_config) // 2 + first_half = failing_config[:mid] + second_half = failing_config[mid:] + if test(first_half).failing(): + return self._bisect_failing_config_helper(results, first_half) + if test(second_half).failing(): + return self._bisect_failing_config_helper(results, second_half) + + if len(failing_config) >= 8: + low = len(failing_config) // 4 + high = mid + low + quart1 = failing_config[low:] + if test(quart1).failing(): + return self._bisect_failing_config_helper(results, quart1) + quart2 = failing_config[:low] + second_half + if test(quart2).failing(): + return self._bisect_failing_config_helper(results, quart2) + quart3 = first_half + failing_config[:high] + if test(quart3).failing(): + return self._bisect_failing_config_helper(results, quart3) + quart4 = failing_config[high:] + if test(quart4).failing(): + return self._bisect_failing_config_helper(results, quart4) + # try dropping one value at a time + for i in range(len(failing_config)): + new_list = [x for j, x in enumerate(failing_config) if j != i] + if test(new_list).failing(): + return self._bisect_failing_config_helper(results, new_list) + # we have the minimal set + return dict(failing_config) + + +def visualize_results( + n: int, results: ResultType, filename: str = "results.html" +) -> None: + """ + Creates an HTML document representing the results of running the fuzzer with fuzz_n_tuple, with n = 2. + """ + # TODO support more dimensions + if n != 2: + raise AssertionError(f"expected n == 2, got {n}") + if len(results) <= 0: + raise AssertionError("expected non-empty results") + + input_set: OrderedSet[str] = OrderedSet({}) + for key in results.keys(): # noqa: SIM118 + input_set.add(key[0]) + input_set.add(key[1]) + input_list = sorted(input_set) + + # Start the HTML content + html_content = """ + + + + + + Fuzzer Visualization + + + +

Fuzzer Visualization

+ + + """ + + html_content += "" + for col_name in input_list: + col = "
".join(col_name) + html_content += f"" + html_content += "" + + # Add table rows + for row_name in input_list: + html_content += f"" + for col_name in input_list: + # Determine the status class for the cell + status_enum = results.lookup((row_name, col_name)) + status_class = "" + status_val = "" + if status_enum == Status.SKIPPED: + status_class = "skipped" + status_val = "-" + elif status_enum == Status.PASSED: + status_class = "passed" + status_val = "O" + elif status_enum == Status.FAILED_RUN_EAGER_EXCEPTION: + status_class = "failed" + status_val = "e" + elif status_enum == Status.FAILED_RUN_COMPILE_EXCEPTION: + status_class = "failed" + status_val = "E" + elif status_enum == Status.FAILED_RUN_RETURN: + status_class = "failed" + status_val = "R" + elif status_enum == Status.FAILED_COMPILE: + status_class = "failed" + status_val = "C" + else: + status_class = "skipped" + status_val = "-" + + html_content += f'' + html_content += "" + + html_content += """ + +
\\{col}
{row_name}{status_val}
+ + + """ + + with open(filename, "w") as file: + file.write(html_content) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e6d5fd077841b8fedd9eb6e17955809f7ff062c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/apply_gumbel_max_trick.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/apply_gumbel_max_trick.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..524e649a90da88ad85c7cc19e179e2cf452548f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/apply_gumbel_max_trick.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/b2b_gemm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/b2b_gemm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0065949d41c300153934113dffd575711e3f269 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/b2b_gemm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/binary_folding.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/binary_folding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3daadcf5b339fbe101a4f4ef700d361d4cfa534d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/binary_folding.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/bucketing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/bucketing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d3b7ff1081953c8b3c604c13fe7a531e0ea50f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/bucketing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/control_dependencies.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/control_dependencies.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1f03ce1b1a0aeab9e2962e743627b91968b13c0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/control_dependencies.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/ddp_fusion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/ddp_fusion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c16414ef7a7ce7ebe13b181be10ca3af07ab5061 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/ddp_fusion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/decomp_comms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/decomp_comms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35f9214bf8ad3796e077c29be319a9dd96926c9e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/decomp_comms.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/decompose_mem_bound_mm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/decompose_mem_bound_mm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cef55446bd39ce26689313a99687a936ffb8ee26 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/decompose_mem_bound_mm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/dedupe_symint_uses.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/dedupe_symint_uses.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63deb0355323ec2f73897c1abed0bf52ba92d029 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/dedupe_symint_uses.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/efficient_conv_bn_eval.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/efficient_conv_bn_eval.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..323d9d118a9cce48f394a0965d20f1cae1ae7d71 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/efficient_conv_bn_eval.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/freezing_patterns.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/freezing_patterns.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41051ae88cce184d2a6236ae01c5d3bbf9fd2d2d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/freezing_patterns.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/fsdp.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/fsdp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e23607fff6ebcc7262b59285cfa97e8a13fb7fe2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/fsdp.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/fuse_attention.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/fuse_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e6afd2cb43a06359ab41fdb84804bde2b24e18b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/fuse_attention.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/fusion_regions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/fusion_regions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a449194fa5ab2b74dccd1f8a75e1967c2dfc20f6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/fusion_regions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/graph_view.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/graph_view.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3afb781bb06d424040b6f96e54282046c8b3637b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/graph_view.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/group_batch_fusion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/group_batch_fusion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86141a786486a53397748b40c41e83e49be84943 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/group_batch_fusion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/joint_graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/joint_graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a23da04121c14bb0e92883ca080572c35a86ab34 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/joint_graph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/low_contention_collectives.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/low_contention_collectives.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0cc4171f5a3a4191b9567c845936dd072525d35 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/low_contention_collectives.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/memory_estimator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/memory_estimator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77ad1173e8bf7de8d9f2d1bcb2f22d4b9df14bc0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/memory_estimator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/micro_pipeline_tp.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/micro_pipeline_tp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc2d1ca64599bfce828b8f2b521dbc374e18b837 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/micro_pipeline_tp.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/misc_patterns.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/misc_patterns.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45c41f00882787d51361c1df1ee26c6a13080171 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/misc_patterns.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/mkldnn_fusion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/mkldnn_fusion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d4bd5615cd477f9495d11fe5bceadc935037625 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/mkldnn_fusion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/node_runtime_estimation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/node_runtime_estimation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7dcd1f8124b8f958e8961a9d2d97dd37486cec6b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/node_runtime_estimation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/numeric_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/numeric_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55d57284311192e68677ae1bef88df86b6c9917b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/numeric_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/overlap_manual_scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/overlap_manual_scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9d1fef65cb168c4d0dd331727df06f2e25c5161 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/overlap_manual_scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/overlap_preserving_bucketer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/overlap_preserving_bucketer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c226ef8e5bd34609429020ac8684f565e33a6542 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/overlap_preserving_bucketer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/overlap_scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/overlap_scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b32d01ef73a4df3edf12737b1434e74dbc90771a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/overlap_scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/pad_mm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/pad_mm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43e823c24cf5c10e7605e39f7f97ccb1a5c5e70d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/pad_mm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/post_grad.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/post_grad.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc9202136caff8fdd947293b7bcc34687a09272b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/post_grad.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e2b168cf69c21123b3ace36147bbdcdcbebd44a93596b9e8154da5ce202caf8 +size 110589 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/pre_grad.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/pre_grad.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f79c371e9acff589bd79a227bc8762133441e7f3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/pre_grad.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/profile_guided_estimation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/profile_guided_estimation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d092029904d9f7dfe3b94fbdbb27a3d73b18d845 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/profile_guided_estimation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/quantization.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/quantization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..468fee35bc13332bb2b5335a04b9c885aa1a3b85 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/quantization.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/reduced_atomic_contention.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/reduced_atomic_contention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ace4705325e781d0a8634d649f513cf3440266e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/reduced_atomic_contention.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/reinplace.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/reinplace.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3cf5807981e8fefa65721d96c07f593eec44ba9f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/reinplace.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/replace_random.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/replace_random.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5c8a24ace44c2cf61836351e5442a85c3f5304e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/replace_random.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/split_cat.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/split_cat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46a22b0d3ae8399f978dac0db4df808661c19fd9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/split_cat.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8419c4ee1dbe7fc0eafd843663788c84763eb63ef2affdb8e59f8ede7f2341b +size 124071 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/spmd_check.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/spmd_check.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b60520afddc30428f0f5e81f26759fc4a6ad9d78 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/spmd_check.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b186d2f3b270ba5ce5b65f8b089f915ae927fd74 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/apply_gumbel_max_trick.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/apply_gumbel_max_trick.py new file mode 100644 index 0000000000000000000000000000000000000000..bbe2a8cb8b540e4c178c17e954d444a8d658a2f2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/apply_gumbel_max_trick.py @@ -0,0 +1,68 @@ +import operator + +import torch +from torch._dynamo.utils import counters + +from ..pattern_matcher import CallFunction, KeywordArg, Match, register_graph_pattern +from .pre_grad import apply_gumbel_max_trick_pass + + +@register_graph_pattern( + CallFunction( + torch.argmax, + CallFunction( + operator.truediv, + # we don't rely on PatternMatcher to match softmax + # and exponential_ due to the mutation op + KeywordArg("softmax"), + KeywordArg("rand_exp"), + ), + dim=-1, + keepdim=True, + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=apply_gumbel_max_trick_pass, +) +def apply_gumbel_max_trick(match: Match, softmax, rand_exp): + if not torch._inductor.config.apply_gumbel_max_trick: + return + + if ( + rand_exp.op != "call_method" + or rand_exp.target != "exponential_" + or len(rand_exp.users) != 1 + ): + return + + empty_node, rate = rand_exp.args + if rate != 1.0: + return + + if len(empty_node.users) != 1: + return + + if ( + softmax.op != "call_function" + or softmax.target != torch.nn.functional.softmax + or len(softmax.users) != 1 + ): + return + logits = softmax.args[0] + + truediv, argmax = match.nodes + nodes_to_erase = [truediv, softmax] + + graph = match.graph + + with graph.inserting_before(argmax): + log = graph.call_function(torch.log, (rand_exp,)) + gumbel_noise = graph.call_function(operator.neg, (log,)) + argmax_input = graph.call_function(operator.add, (logits, gumbel_noise)) + # pyrefly: ignore [missing-attribute] + argmax.args[0].replace_all_uses_with(argmax_input) + + # erase nodes + for n in nodes_to_erase: + match.graph.erase_node(n) + + counters["inductor"]["apply_gumbel_max_trick"] += 1 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2781691a50e4d3ca339e475b2a4b8a72d12b2932 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__init__.py @@ -0,0 +1,81 @@ +import dataclasses +import functools +import itertools +import logging +import operator +import os +from collections.abc import Sequence +from typing import Optional + +import torch +from torch._dynamo.utils import detect_fake_mode +from torch._inductor import config, metrics +from torch._inductor.utils import cache_on_self +from torch.fx import GraphModule +from torch.fx.passes.fake_tensor_prop import FakeTensorProp +from torch.utils import _pytree +from torch.utils._ordered_set import OrderedSet + +from .applier import ChunkingApplier +from .common import CantChunk +from .core import find_amplifier_node +from .propagator import propagate +from .utils import get_tangent_nodes, tangent_has_chunking_meta + + +aten = torch.ops.aten +prims = torch.ops.prims +log = torch._logging.getArtifactLogger(__name__, "auto_chunker") + + +def decide_num_chunks(gm: GraphModule) -> int: + # TODO: this is just a placeholder for now. + # We should either create heuristics or do autotuning to + # decide the number of chunks. + return 8 + + +def chunk(gm: GraphModule) -> GraphModule: + """ + Chunk input tensors for operations that amplify the tensor size significantly. + The chunking operation is propagated thru the fx graph until a point we should + re-generate non-chunked tensors. + + Only chunk across the batch dimension of the tensor for now. + """ + graph = gm.graph + + if torch._inductor.config.cpp_wrapper: + raise CantChunk("cpp wrapper does not support codegening invoke_subgraph") + + if gm.meta.get("produced_by_chunker", False): + # Don't chunk a graph produced by the chunker + return gm + + if len(get_tangent_nodes(gm.graph)) == 0: + # no tangents. Can be the optimizer graph. Skip chunking + return gm + + if log.isEnabledFor(logging.DEBUG): + log.debug("Joint graph before chunking:\n%s", gm.print_readable(False)) + + amplifier_node = find_amplifier_node(graph) + if amplifier_node is None: + raise CantChunk("Skip chunking due to no amplifier node found") + + if amplifier_node.meta["val"]._has_symbolic_sizes_strides: + raise CantChunk("Can't chunk due to dynamic shape") + + propagate(amplifier_node) + if not tangent_has_chunking_meta(gm): + raise CantChunk( + "Skip chunking either because the graph is for inference only or " + "because the chunking metadata does not propagate to the backward " + "(e.g. due to too trivial loss function)" + ) + + num_chunks = config.auto_chunker.num_chunk or decide_num_chunks(gm) + out_gm = ChunkingApplier(gm, num_chunks).apply() + metrics.num_auto_chunking += 1 + log.debug("AutoChunker being applied with %s chunks", num_chunks) + return out_gm diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f42202d1dfedcfde9072766be72cbed670dd9f52 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/applier.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/applier.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7938ac4e37f8d961b1eb9112d70223b9bfb7cf7c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/applier.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d163274562263e205123ab94d3e42f0d46caca24 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..182823beac6249ca062c0187a4090ce2422b7874 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/propagate_scale_by.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/propagate_scale_by.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d6265e11d0cf8f398f9958502c17d1ee16747ea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/propagate_scale_by.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/propagator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/propagator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d422d33c872aa29f066230cad18a168aac44ef2a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/propagator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6d1f85a78e79195514900232eb4ec2088673082 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/applier.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/applier.py new file mode 100644 index 0000000000000000000000000000000000000000..e575f605680a2b398639ef2f83c9aea62347c461 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/applier.py @@ -0,0 +1,457 @@ +import copy +import logging +import operator +from typing import Any + +import torch +from torch import Tensor +from torch._dynamo.utils import detect_fake_mode +from torch.fx import Graph, GraphModule, Node +from torch.fx.passes.fake_tensor_prop import FakeTensorProp + +from .core import get_chunking_meta, reorder_nodes +from .utils import get_args_of_node_type, get_fake_tensor_from_node_arg, is_tangent_node + + +log = torch._logging.getArtifactLogger(__name__, "auto_chunker") +aten = torch.ops.aten +prims = torch.ops.prims + + +def _factory_args(fake_tensor: Tensor) -> dict[str, Any]: + return { + "device": fake_tensor.device, + "dtype": fake_tensor.dtype, + } + + +def fake_tensor_prop(gm: GraphModule) -> None: + inputs = [] + for node in gm.graph.find_nodes(op="placeholder", sort=False): + fake_tensor = get_fake_tensor_from_node_arg(node) + if fake_tensor is not None: + inputs.append(fake_tensor) + else: + inputs.append(node) + + fake_mode = detect_fake_mode(inputs) + FakeTensorProp(gm, mode=fake_mode).propagate_dont_convert_inputs(*inputs) + + +def is_chunking_subgraph_input(node: Node) -> bool: + meta = get_chunking_meta(node) + if meta is None or is_tangent_node(node): + return False + arg_nodes = get_args_of_node_type(node) + arg_nodes_no_meta = [node for node in arg_nodes if get_chunking_meta(node) is None] + return len(arg_nodes_no_meta) > 0 or node.op == "placeholder" + + +class ChunkingApplier: + """ + A class that chunks the graph assuming chunking metadata has already + been attached to the nodes in the chunking subgraph. + """ + + def __init__(self, parent_gm: GraphModule, num_chunk: int): + self.gm = parent_gm + self.parent_graph = reorder_nodes(self.gm.graph) + # From this point on self.parent_graph is not equal to self.gm.graph + # due to reordering. We create a new copy of the graph so it's + # easier to fallback if chunking fails. + self.num_chunk = num_chunk + + # tangent node to the all-one tensor + self.overriden_tangent: dict[Node, Node | None] = {} + + self.subgraph_input: list[Node] = [] + self.subgraph_body: list[Node] = [] + self.subgraph_output: list[Node] = [] + self._categorize_subgraph_nodes() + + self.chunk_sizes: list[int] | None = None + + # First index is node index, + # Second index is chunk index. + # Node index may be different to the index for self.subgraph_input + # since not every subgraph_input may be chunked. + # check self.chunk_subgraph_input for more details + self.chunked_subgraph_input: list[list[Node]] = [] + + self.accumulators: dict[Node, Node | None] = {} + self.chunks_for_recovering: dict[Node, list[Node]] = {} + for node in self.subgraph_output: + meta = get_chunking_meta(node) + if not meta: + raise AssertionError("expected chunking meta for subgraph output node") + if meta.chunk_dim is not None: + self.chunks_for_recovering[node] = [] + else: + # the accumulator nodes is created later + self.accumulators[node] = None + + self.chunk_size_to_gm_attr: dict[int, str] = {} + + def _categorize_subgraph_nodes(self) -> None: + """ + For each chunked node, decide if it's an input/body/output node of the + chunking subgraph. + """ + for node in self.parent_graph.nodes: + meta = get_chunking_meta(node) + + # The node does not have chunking metadata, skip + if meta is None: + continue + + # skip tangent nodes since they are overridden as 1 and + # reapplied later in the bwd graph + if is_tangent_node(node): + self.overriden_tangent[node] = None # will update the value later + continue + + # To check if a node is a placeholder for the chunking + # subgraph there are 2 alternatives + # 1. decide it's a placeholder if it's using any non-chunked node as argument + # 2. decide it's a placeholder if it's not using any chunked nodes as argument + # These 2 rules are almost equivalent since we don't mix + # chunked and non-chunked arguments for a fx.Node. + # But one subtle difference is for aten.full node. + # We don't need to pass in aten.full as a placeholder since + # we can just add the chunked aten.full in the subgraph + # directly. + # Alternative 2 does not work for this case, so we implement + # alternative 1. + + user_nodes = node.users + user_nodes_no_meta = [ + node for node in user_nodes if get_chunking_meta(node) is None + ] + + if is_chunking_subgraph_input(node): + # None of the node's arguments are chunked. It's a placeholder + self.subgraph_input.append(node) + elif len(user_nodes_no_meta) > 0: + self.subgraph_output.append(node) + else: + self.subgraph_body.append(node) + + if len(self.subgraph_body) <= 0: + raise AssertionError("expected non-empty subgraph body") + + def replace_tangent_to_one(self) -> None: + for idx, node in enumerate(self.overriden_tangent): + if not is_tangent_node(node): + raise AssertionError(f"expected tangent node, got {node}") + + fake_tensor = node.meta["val"] + one = self.parent_graph.call_function( + aten.full.default, (fake_tensor.shape, 1), _factory_args(fake_tensor) + ) + + name = "tangent_overriden_as_one_{idx}" + one._rename(name) + one.meta = copy.copy(node.meta) + node.replace_all_uses_with(one) + self.overriden_tangent[node] = one + + def chunk_subgraph_input(self) -> None: + """ + Chunk subgraph inputs if necessary. Note that not every subgraph + input needs to be chunked. + E.g. the weight for matmul does not need to be chunked. + """ + for node_idx, subgraph_input in enumerate(self.subgraph_input): + meta = get_chunking_meta(subgraph_input) + if meta is None: + raise AssertionError("expected chunking meta for subgraph input") + + # not chunked + if meta.chunk_dim is None: + continue + + chunk_node = self.parent_graph.call_function( + aten.chunk.default, (subgraph_input, self.num_chunk, meta.chunk_dim) + ) + chunks = [ + self.parent_graph.call_function(operator.getitem, (chunk_node, i)) + for i in range(self.num_chunk) + ] + + self.chunked_subgraph_input.append(chunks) + + # let's do a small meta propagation to get the size of each chunk + if self.chunk_sizes is None: + input_tensor = subgraph_input.meta["val"] + tensors = torch.chunk(input_tensor, self.num_chunk) + self.chunk_sizes = [t.size(0) for t in tensors] + + def create_accumulators(self) -> None: + for node in self.accumulators: + # use fp32 for accumulators + fake_tensor = node.meta["val"] + if fake_tensor.numel() == 1: + # TODO(shunting) revisit + # This tensor may be fused with mm and becomes a addmm + # if we upcast here, addmm may fail due to incompatible + # dtypes for input arguments. + override_dtype = torch.float32 + else: + override_dtype = fake_tensor.dtype + + kwargs = _factory_args(fake_tensor) + kwargs["dtype"] = override_dtype + accum = self.parent_graph.call_function( + aten.full.default, (fake_tensor.shape, 0), kwargs + ) + # reuse the meta['val'] + accum.meta = {"val": fake_tensor.to(override_dtype)} + self.accumulators[node] = accum + + def build_subgraph(self, chunk_size: int) -> GraphModule: + """ + Build a subgraph for the given chunk size. + The last chunk can be smaller and a new subgraph will be created + to avoid involving dynamic shapes. + """ + new_graph = Graph() + env: dict[Node, Node] = {} + + def _create_placeholder_node(input_node: Node) -> Node: + new_node = new_graph.placeholder(input_node.name) + fake_tensor = input_node.meta["val"] + chunking_meta = get_chunking_meta(input_node) + if chunking_meta is not None and chunking_meta.chunk_dim is not None: + # the node is chunked and we need update the + # fake tensor + # TODO any better way to do this? + new_tensor = aten.slice.Tensor( + fake_tensor, chunking_meta.chunk_dim, 0, chunk_size + ) + fake_tensor = new_tensor + new_node.meta = {"val": fake_tensor} + return new_node + + for node_idx, input_node in enumerate(self.subgraph_input): + env[input_node] = _create_placeholder_node(input_node) + + for overriden_tangent_node in self.overriden_tangent.values(): + if overriden_tangent_node is None: + raise AssertionError("expected tangent node to be set") + env[overriden_tangent_node] = _create_placeholder_node( + overriden_tangent_node + ) + + for accum in self.accumulators.values(): + if accum is None: + raise AssertionError("expected accumulator to be set") + env[accum] = _create_placeholder_node(accum) + + for original_node in self.subgraph_body + self.subgraph_output: + if original_node.op == "placeholder": + raise AssertionError( + f"unexpected placeholder node in subgraph body/output: {original_node}" + ) + + # Chunk aten.full + if ( + original_node.target == aten.full.default + and (meta := get_chunking_meta(original_node)) is not None + and meta.chunk_dim is not None + ): + shape = list(original_node.args[0]) # type: ignore[arg-type] + # pyrefly: ignore [unsupported-operation] + shape[meta.chunk_dim] = chunk_size + env[original_node] = new_graph.call_function( + aten.full.default, + (shape, original_node.args[1]), + original_node.kwargs, + ) + continue + # Chunk aten.expand: adjust the target shape at the chunk dimension + if ( + original_node.target == aten.expand.default + and isinstance(original_node.args[0], torch.fx.Node) + and (meta := get_chunking_meta(original_node)) is not None + and meta.chunk_dim is not None + ): + shape = list(original_node.args[1]) # type: ignore[arg-type] + # pyrefly: ignore [unsupported-operation] + shape[meta.chunk_dim] = chunk_size + env[original_node] = new_graph.call_function( + aten.expand.default, + (env.get(original_node.args[0], original_node.args[0]), shape), # type: ignore[arg-type] + original_node.kwargs, + ) + continue + + # Chunk aten.view: adjust the target shape at the chunk dimension + if ( + original_node.target == aten.view.default + and isinstance(original_node.args[0], torch.fx.Node) + and (meta := get_chunking_meta(original_node)) is not None + and meta.chunk_dim is not None + ): + shape = list(original_node.args[1]) # type: ignore[arg-type] + # pyrefly: ignore [unsupported-operation] + shape[meta.chunk_dim] = chunk_size + env[original_node] = new_graph.call_function( + aten.view.default, + (env[original_node.args[0]], shape), # type: ignore[arg-type] + original_node.kwargs, + ) + continue + + # create the node with chunked inputs + env[original_node] = new_graph.node_copy(original_node, lambda x: env[x]) + + # Do the accumulation inside this subgraph + for node, accum in self.accumulators.items(): + lhs = env[node] + if accum is None: + raise AssertionError("expected accumulator to be set") + rhs = env[accum] + + # add `addend` and `accum` + add_out = new_graph.call_function(aten.add.Tensor, (lhs, rhs)) + + # override the chunk value + env[node] = add_out + + out_values = [] + for node in self.subgraph_output: + out_values.append(env[node]) + + new_graph.output(tuple(out_values)) + new_graph.eliminate_dead_code() + new_graph.lint() + + sub_gm = torch.fx._lazy_graph_module._make_graph_module(self.gm, new_graph) + fake_tensor_prop(sub_gm) + return sub_gm + + def build_subgraphs(self) -> None: + if self.chunk_sizes is None: + raise AssertionError("expected chunk_sizes to be set") + for chunk_size in self.chunk_sizes: + if chunk_size in self.chunk_size_to_gm_attr: + continue + + sub_gm = self.build_subgraph(chunk_size) + gm_attr = f"chunking_subgraph_{len(self.chunk_size_to_gm_attr)}" + self.chunk_size_to_gm_attr[chunk_size] = gm_attr + setattr(self.gm, gm_attr, sub_gm) + + # Mark this sub graph module so we don't recursively chunking + # it. + sub_gm.meta["produced_by_chunker"] = True + + def call_subgraph_for_each_chunk(self) -> None: + for chunk_id in range(self.num_chunk): + if self.chunk_sizes is None: + raise AssertionError("expected chunk_sizes to be set") + chunk_size = self.chunk_sizes[chunk_id] + subgraph_id = self.chunk_size_to_gm_attr[chunk_size] + sub_gm = self.parent_graph.get_attr(subgraph_id) + + args = [] + chunks_iter = iter(self.chunked_subgraph_input) + for node in self.subgraph_input: + chunking_meta = get_chunking_meta(node) + if chunking_meta is None: + raise AssertionError("expected chunking meta for subgraph input") + if chunking_meta.chunk_dim is not None: + args.append(next(chunks_iter)[chunk_id]) + else: + # not chunked + args.append(node) + + args += list(self.overriden_tangent.values()) # type: ignore[arg-type] + + for accum in self.accumulators.values(): + if accum is None: + raise AssertionError("expected accumulator to be set") + args.append(accum) + + output_node = self.parent_graph.call_function( + torch.ops.higher_order.invoke_subgraph, (sub_gm, subgraph_id, *args), {} + ) + + output_node_dict = {} + for i, orig_node in enumerate(self.subgraph_output): + output_node_dict[orig_node] = self.parent_graph.call_function( + operator.getitem, (output_node, i) + ) + + for orig_node, node_list in self.chunks_for_recovering.items(): + chunk = output_node_dict[orig_node] + node_list.append(chunk) + + for orig_node in self.accumulators: + self.accumulators[orig_node] = output_node_dict[orig_node] + + def recover_to_unchunked_nodes(self) -> None: + """ + Recover the node from chunks and do the replacement. + """ + for node in self.subgraph_output: + meta = get_chunking_meta(node) + if meta is None: + raise AssertionError("expected chunking meta for subgraph output") + + recovered: torch.fx.Node = node + + if meta.chunk_dim is not None: + chunks = self.chunks_for_recovering[node] + recovered = self.parent_graph.call_function( + aten.cat.default, (chunks, meta.chunk_dim) + ) + elif meta.need_sum: + recovered = self.accumulators[node] # type: ignore[assignment] + + # do scaling last + if meta.scale_by is not None: + recovered = self.parent_graph.call_function( + aten.mul.Tensor, (recovered, meta.scale_by) + ) + + # convert back to the original dtype + if meta.need_sum: + original_dtype = node.meta["val"].dtype + # TODO(shunting): do we always uses a fp32 accumulator? + if original_dtype != torch.float32: + recovered = self.parent_graph.call_function( + prims.convert_element_type.default, (recovered, original_dtype) + ) + + if recovered is node: + raise AssertionError("expected recovered node to differ from original") + node.replace_all_uses_with(recovered) + + def erase_original_nodes(self) -> None: + # Traverse reversely to erase user first + for node in reversed(tuple(self.subgraph_body + self.subgraph_output)): + if node.op == "placeholder": + continue + + self.parent_graph.erase_node(node) + + def apply(self) -> GraphModule: + with self.parent_graph.inserting_before(self.subgraph_body[0]): + self.replace_tangent_to_one() + self.chunk_subgraph_input() + self.create_accumulators() + self.build_subgraphs() + self.call_subgraph_for_each_chunk() + self.recover_to_unchunked_nodes() + self.erase_original_nodes() + + newgm = torch.fx._lazy_graph_module._make_graph_module( + self.gm, + self.parent_graph, + ) + fake_tensor_prop(newgm) + if log.isEnabledFor(logging.DEBUG): + print("Graph module after chunking:") + newgm.print_readable() + return newgm diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/common.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/common.py new file mode 100644 index 0000000000000000000000000000000000000000..4a6139ceb5b269afad45012d7a36c6af78d38281 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/common.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +import dataclasses +from typing import Any, TYPE_CHECKING + + +if TYPE_CHECKING: + from torch.fx import Node + + +class CantChunk(RuntimeError): + pass + + +@dataclasses.dataclass +class ChunkingMeta: + # The value of the current node having this ChunkingMeta should be scaled by the specified scalar + # tensor in the `scale_by` field. Need this since we pretend tangent to be 1 first and + # scale the affected tensor later. Need propagate such information + # to downstream. + scale_by: Node | None = None + + # The dimension of the current tensor that get chunked. + # Can be None if the current tensor is not chunked. E.g., when + # the current tensor is a scalar tensor generated by summing a chunked tensor. + # + # To recover a tensor with non-None chunk_dim, we need concat each + # chunk at the 'chunk_dim' dimension. + chunk_dim: int | None = None + + # The original tensor is the sum of each tensor in the chunking subgraph. + # `chunk_dim` and `need_sum` are exclusive! A node can not have both a non + # None chunk_dim and a need_sum with True value. + # + # Note for some special cases like the tangent placeholder node, both + # chunk_dim can be None and need_sum can be false, but scale_by + # in that case is the tangent node itself. + need_sum: bool = False + + def __post_init__(self) -> None: + if self.chunk_dim is not None and self.need_sum: + raise AssertionError( + f"Can not have both a non-None chunk_dim and a true need_sum: {self.chunk_dim}" + ) + + def copy(self, **kwargs: Any) -> ChunkingMeta: + meta = ChunkingMeta(**self.__dict__) + for k, v in kwargs.items(): + setattr(meta, k, v) + return meta + + @staticmethod + def equal( + lhs_meta: ChunkingMeta, rhs_meta: ChunkingMeta, skip_scale_by: bool = False + ) -> bool: + if skip_scale_by: + lhs_meta = lhs_meta.copy(scale_by=None) + rhs_meta = rhs_meta.copy(scale_by=None) + return lhs_meta == rhs_meta + + def chunked_by_dim(self, dim: int) -> bool: + return self.chunk_dim == dim + + @staticmethod + def is_nop(meta: ChunkingMeta | None) -> bool: + return meta is None or meta == ChunkingMeta() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/core.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/core.py new file mode 100644 index 0000000000000000000000000000000000000000..2af7be493a2a6d49d1c4882526f9738f04090156 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/core.py @@ -0,0 +1,226 @@ +import logging +from collections.abc import Callable, Sequence +from typing import Any + +import torch +from torch._inductor import config +from torch.fx import Graph, Node +from torch.utils._ordered_set import OrderedSet + +from .common import ChunkingMeta +from .utils import ( + compute_tensor_size, + get_args_of_node_type, + get_fake_tensor_from_node_arg, + use_tangent, +) + + +aten = torch.ops.aten +log = torch._logging.getArtifactLogger(__name__, "auto_chunker") + + +def set_chunking_meta( + node: Node, meta: ChunkingMeta | None = None, **kwargs: Any +) -> bool: + """ + kwargs can override fields in the passed in `meta` + """ + if meta is None: + meta = ChunkingMeta(**kwargs) + else: + # make a copy to avoid override the passed in instance + meta = meta.copy() + for k, v in kwargs.items(): + setattr(meta, k, v) + + old_meta = get_chunking_meta(node) + node.meta["chunking"] = meta + return old_meta is None or old_meta != meta + + +def update_chunking_meta(node: Node, **kwargs: Any) -> bool: + """ + Unlike set_chunking_meta, this function keeps the existing chunking + metadata if it's not overridden. + """ + changed = False + meta = get_chunking_meta(node) + if meta is None: + meta = ChunkingMeta() + changed = True + for k, v in kwargs.items(): + if getattr(meta, k, None) != v: + changed = True + setattr(meta, k, v) + + node.meta["chunking"] = meta + return changed + + +def set_chunking_meta_if_none( + nodes: Sequence[Node], + meta: ChunkingMeta, + filter_for_nop: Callable[[Node], bool] | None = None, +) -> bool: + """ + If filter_for_nop returns true for a node, we set the chunking + meta to nop instead. + """ + changed = False + for node in nodes: + if get_chunking_meta(node) is None: + changed = True + if filter_for_nop and filter_for_nop(node): + set_chunking_meta(node) + else: + set_chunking_meta(node, meta) + return changed + + +def copy_chunking_meta(dst_node: Node, src_node: Node | ChunkingMeta) -> bool: + if isinstance(src_node, torch.fx.Node): + src_meta = get_chunking_meta(src_node) + else: + if not isinstance(src_node, ChunkingMeta): + raise AssertionError( + f"expected src_node to be ChunkingMeta, got {type(src_node)}" + ) + src_meta = src_node + if not src_meta: + raise AssertionError("expected src_meta to be truthy") + return set_chunking_meta(dst_node, src_meta) + + +def get_chunking_meta(node: Node) -> ChunkingMeta | None: + return node.meta.get("chunking") + + +def has_nop_chunking_meta(node: Node) -> bool: + return ChunkingMeta.is_nop(get_chunking_meta(node)) + + +def get_chunking_metas( + nodes: Sequence[Node], skip_none: bool = False +) -> Sequence[ChunkingMeta | None]: + return [ + get_chunking_meta(node) + for node in nodes + if not skip_none or get_chunking_meta(node) is not None + ] + + +eligible_amplifier_node = OrderedSet( + [ + aten.mm.default, + aten.addmm.default, + ] +) + + +def find_amplifier_node(graph: Graph) -> Node | None: + r""" + Find the 'amplifier' node which is a node that generates large + output with small/medium input. + + If there are multiple amplifier nodes, return the one with the largest + amplification ratio. + """ + + amplifier_nodes_ratio = [] + + for node in graph.nodes: + if use_tangent(node): + # enter backward part of the graph + break + + # Only trigger chunking for a small set of nodes like matmul for now + if node.op != "call_function" or node.target not in eligible_amplifier_node: + continue + + input_size = compute_tensor_size(node.args, node.kwargs) + output_size = compute_tensor_size(node) + + if input_size == 0: + continue + + ratio = output_size / input_size + if ( + output_size > config.auto_chunker.output_size_threshold + and ratio > config.auto_chunker.amplify_ratio_threshold + ): + amplifier_nodes_ratio.append((node, ratio)) + + amplifier_nodes_ratio = sorted( + amplifier_nodes_ratio, key=lambda x: x[1], reverse=True + ) + return amplifier_nodes_ratio[0][0] if len(amplifier_nodes_ratio) > 0 else None + + +def reorder_nodes(graph: Graph) -> Graph: + """ + Create a new graph to be like: + 1. all nodes run before `chunking_subgraph_nodes` + 2. all nodes in `chunking_subgraph_nodes` + 3. all nodes run after `chunking_subgraph_nodes` + + Return a new graph so it's easier to fallback. + """ + from .applier import is_chunking_subgraph_input + + # `pre_chunking_nodes` are all nodes that only depends on + # nodes inside `pre_chuning_nodes` + pre_chunking_nodes: OrderedSet[Node] = OrderedSet() + + for node in graph.nodes: + if node.op == "placeholder" or is_chunking_subgraph_input(node): + # these nodes have chunking meta but they should be placed + # before we do chunking + pre_chunking_nodes.add(node) + + if get_chunking_meta(node) is not None: + continue + if all(arg in pre_chunking_nodes for arg in get_args_of_node_type(node)): + pre_chunking_nodes.add(node) + + post_chunking_nodes = [] + + def _copy_node(typestr: str, node: Node) -> None: + if log.isEnabledFor(logging.DEBUG): + fake_tensor = get_fake_tensor_from_node_arg(node) + shape = list(fake_tensor.shape) if fake_tensor is not None else "?" + log.debug(" - %s: %s %s", typestr, shape, node.format_node()) + env[node] = new_graph.node_copy(node, lambda x: env[x]) + + # add pre_chunking_nodes + new_graph = Graph() + env: dict[Node, Node] = {} + for node in pre_chunking_nodes: + _copy_node("prechunking", node) + + # add nodes in the chunking subgraph + for node in graph.nodes: + if node in pre_chunking_nodes: + continue + elif get_chunking_meta(node): + _copy_node("chunking", node) + else: + post_chunking_nodes.append(node) + + for node in post_chunking_nodes: + _copy_node("postchuking", node) + + if graph._len != new_graph._len: + raise AssertionError( + f"expected graph._len == new_graph._len, got {graph._len} and {new_graph._len}" + ) + new_graph.eliminate_dead_code() + new_graph.lint() + + # Need replace the scale_by node in the chunking meta with the new node + for node in new_graph.nodes: + meta = get_chunking_meta(node) + if meta and meta.scale_by is not None: + meta.scale_by = env[meta.scale_by] + + return new_graph diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/propagate_scale_by.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/propagate_scale_by.py new file mode 100644 index 0000000000000000000000000000000000000000..b402df561d333c3a690575da98fd9367e4c1a2bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/propagate_scale_by.py @@ -0,0 +1,271 @@ +import functools +import logging +from collections.abc import Callable, Sequence +from typing import TypeAlias + +import torch +from torch.fx import Node + +from .common import CantChunk +from .core import get_chunking_meta, get_chunking_metas, log, update_chunking_meta +from .utils import ( + format_node_with_chunking_meta, + get_args_of_node_type, + get_scale_by_from_metas, + get_scale_by_from_node, +) + + +aten = torch.ops.aten +prims = torch.ops.prims + +_HandlerType: TypeAlias = Callable[[Node], bool] +propagate_rules: dict[torch._ops.OpOverload, _HandlerType] = {} + + +def _register_propagate_rule( + aten_op: torch._ops.OpOverload | Sequence[torch._ops.OpOverload], + handler: _HandlerType, +) -> _HandlerType: + if not isinstance(aten_op, (list, tuple)): + aten_op = [aten_op] # type: ignore[assignment, list-item] + + if not isinstance(aten_op, (list, tuple)): + raise AssertionError(f"{type(aten_op)=}") + for op in aten_op: + if not isinstance(op, torch._ops.OpOverload): + raise AssertionError(f"expected OpOverload, got {type(op)}") + propagate_rules[op] = handler + return handler + + +def register_propagate_rule( + aten_op: torch._ops.OpOverload | Sequence[torch._ops.OpOverload], +) -> Callable[[_HandlerType], _HandlerType]: + return functools.partial(_register_propagate_rule, aten_op) + + +def propagate_scale_by(nodes_with_chunking_meta: Sequence[Node]) -> None: + """ + The input is a list of nodes that have chunking metadata. + The nodes are already sorted in topological order. + """ + for node in nodes_with_chunking_meta: + arg_nodes = get_args_of_node_type(node) + arg_metas = get_chunking_metas(arg_nodes) + + if all(arg_meta is None for arg_meta in arg_metas): + # should be graph input of the chunking subgraph + continue + + if log.isEnabledFor(logging.DEBUG): + print("Propagate scale_by:") + format_node_with_chunking_meta(node, True) + + if not all(arg_meta is not None for arg_meta in arg_metas): + raise AssertionError(node.format_node()) + + # None of the input has scale_by set + if all(arg_meta.scale_by is None for arg_meta in arg_metas): # type: ignore[union-attr] + continue + + target = node.target + if ( + not isinstance(target, torch._ops.OpOverload) + or target not in propagate_rules + ): + raise CantChunk( + f"Missing scale_by propagation rule for target {target}: {node.format_node()}" + ) + + if not propagate_rules[target](node): + raise CantChunk( + f"scale_by propagate rule for {target} fail: {node.format_node()}" + ) + + +@register_propagate_rule( + [ + aten.div.Tensor, + ] +) +def propagate_div(div_node: Node) -> bool: + lhs_node, rhs_node = div_node.args[:2] + if not isinstance(lhs_node, Node): + raise AssertionError(f"expected lhs_node to be Node, got {type(lhs_node)}") + lhs_scale_by = get_scale_by_from_node(lhs_node) + + # When gradient accumulation is enabled, rhs_node can be a constant + # representing the gradient accumulation steps + rhs_scale_by = ( + get_scale_by_from_node(rhs_node) if isinstance(rhs_node, Node) else None + ) + if lhs_scale_by and rhs_scale_by is None: + update_chunking_meta(div_node, scale_by=lhs_scale_by) + return True + return False + + +@register_propagate_rule( + [ + aten.where.self, + ] +) +def propagate_where(where_node: Node) -> bool: + cond_node, true_node, false_node = where_node.args + if not isinstance(cond_node, Node): + raise AssertionError(f"expected cond_node to be Node, got {type(cond_node)}") + if not isinstance(true_node, Node): + raise AssertionError(f"expected true_node to be Node, got {type(true_node)}") + if not isinstance(false_node, Node): + raise AssertionError(f"expected false_node to be Node, got {type(false_node)}") + cond_meta, true_meta, false_meta = get_chunking_metas( + [cond_node, true_node, false_node] + ) + out_meta = get_chunking_meta(where_node) + + if true_meta is None: + raise AssertionError("expected true_meta to be not None") + if false_meta is None: + raise AssertionError("expected false_meta to be not None") + if true_meta.scale_by and not false_meta.scale_by: + # the false_node must be all zero + if false_node.target != aten.full.default: + return False + if false_node.args[1] != 0.0: + return False + if out_meta is None: + raise AssertionError("expected out_meta to be not None") + out_meta.scale_by = true_meta.scale_by + return True + return False + + +@register_propagate_rule( + [ + aten.exp.default, + aten.log.default, + aten.tanh.default, + aten.eq.Tensor, + ] +) +def propagate_requires_no_scaling(out_node: Node) -> bool: + """ + For nonlinear ops (exp, log, tanh) scale_by cannot be propagated + through since f(S*x) != S*f(x). For boolean-output ops (eq) scale_by + is meaningless. These ops only appear in the chunking subgraph when + scale_by is None (e.g. the final gradient is 1). + """ + args_node = get_args_of_node_type(out_node) + args_meta = get_chunking_metas(args_node) + out_meta = get_chunking_meta(out_node) + + scale_by = get_scale_by_from_metas(*args_meta) # type: ignore[arg-type] + if scale_by is not None: + raise AssertionError( + f"Nonlinear op {out_node.target} requires scale_by=None, got {scale_by}" + ) + if out_meta is None: + raise AssertionError("expected out_meta to be not None") + out_meta.scale_by = None + return True + + +@register_propagate_rule( + [ + aten.mul.Tensor, + prims.convert_element_type.default, + aten.neg.default, + aten.sum.dim_IntList, + aten.sum.default, # sum to scalar + aten.amax.default, + aten.mm.default, + aten.permute.default, + aten.expand.default, + aten.squeeze.dim, + aten.unsqueeze.default, + aten.gather.default, + aten.scatter_add.default, + aten.view.default, + ] +) +def propagate_general_copy(out_node: Node) -> bool: + """ + A rule that holds for multiple ops: the scale_by of the output is + set to the only scale_by of input nodes or None if no input has scale_by + set. + """ + args_node = get_args_of_node_type(out_node) + args_meta = get_chunking_metas(args_node) + out_meta = get_chunking_meta(out_node) + + scale_by = get_scale_by_from_metas(*args_meta) # type: ignore[arg-type] + if out_meta is None: + raise AssertionError("expected out_meta to be not None") + out_meta.scale_by = scale_by + return True + + +@register_propagate_rule(aten.scatter.value) +def propagate_scatter_value(out_node: Node) -> bool: + # The backward of scatter.value always has value=0 (gradient of a constant), + # so S * scatter(x, idx, 0) = scatter(S*x, idx, 0) holds. + value = out_node.args[3] + if value != 0: + return False + return propagate_general_copy(out_node) + + +@register_propagate_rule( + [ + aten.add.Tensor, + aten.sub.Tensor, + ] +) +def propagate_add_sub(out_node: Node) -> bool: + """ + The scale_by node of the two arguments must be the same. + """ + lhs_node, rhs_node = get_args_of_node_type(out_node) + if not isinstance(lhs_node, Node): + raise AssertionError(f"expected lhs_node to be Node, got {type(lhs_node)}") + if not isinstance(rhs_node, Node): + raise AssertionError(f"expected rhs_node to be Node, got {type(rhs_node)}") + lhs_meta, rhs_meta = get_chunking_metas([lhs_node, rhs_node]) + if lhs_meta is None: + raise AssertionError("expected lhs_meta to be not None") + if rhs_meta is None: + raise AssertionError("expected rhs_meta to be not None") + if lhs_meta.scale_by is rhs_meta.scale_by: + update_chunking_meta(out_node, scale_by=lhs_meta.scale_by) + return True + return False + + +@register_propagate_rule( + [ + prims.fma.default, + ] +) +def propagate_fma(out_node: Node) -> bool: + mul_lhs, mul_rhs, add_rhs = out_node.args[:3] + if not isinstance(mul_lhs, Node): + raise AssertionError(f"expected mul_lhs to be Node, got {type(mul_lhs)}") + if not isinstance(mul_rhs, Node): + raise AssertionError(f"expected mul_rhs to be Node, got {type(mul_rhs)}") + if not isinstance(add_rhs, Node): + raise AssertionError(f"expected add_rhs to be Node, got {type(add_rhs)}") + mul_lhs_meta, mul_rhs_meta, add_rhs_meta = get_chunking_metas( + [mul_lhs, mul_rhs, add_rhs] + ) + if mul_lhs_meta is None: + raise AssertionError("expected mul_lhs_meta to be not None") + if mul_rhs_meta is None: + raise AssertionError("expected mul_rhs_meta to be not None") + add_lhs_scale_by = get_scale_by_from_metas(mul_lhs_meta, mul_rhs_meta) + if add_rhs_meta is None: + raise AssertionError("expected add_rhs_meta to be not None") + if add_lhs_scale_by is add_rhs_meta.scale_by: + update_chunking_meta(out_node, scale_by=add_lhs_scale_by) + return True + return False diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/propagator.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/propagator.py new file mode 100644 index 0000000000000000000000000000000000000000..dab45841ae1ed4315b8b793c3743c530b262545d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/propagator.py @@ -0,0 +1,960 @@ +import functools +import logging +import math +from collections.abc import Callable, Sequence +from enum import Enum +from queue import Queue +from typing import Any, TypeAlias + +import torch +from torch.fx import Graph, Node + +from .common import CantChunk +from .core import ( + ChunkingMeta, + copy_chunking_meta, + get_chunking_meta, + has_nop_chunking_meta, + set_chunking_meta, + set_chunking_meta_if_none, + update_chunking_meta, +) +from .propagate_scale_by import propagate_scale_by +from .utils import ( + format_node_with_chunking_meta, + get_args_of_node_type, + get_fake_tensor_from_node_arg, + get_first_chunking_meta, + get_node_is_scalar, + get_node_ndim, + get_nodes_with_chunking_meta, + has_any_chunking_meta, + is_chunked_by_dim, + is_tangent_node, +) + + +log = torch._logging.getArtifactLogger(__name__, "auto_chunker") +aten = torch.ops.aten +prims = torch.ops.prims + + +""" +NOTE [Why we need both fwd and bwd chunking metadata propagation?] +The starting point of chunking is we found an op that creates much larger outputs +than the inputs size. We attach chunking metadata upon the op and propagate it forward. + +But for backward rules like NLLLossBackward, we do a scatter upon a zero matrix. That +zero matrix is created by torch.full. We will only know we should chunk that tensor +by propagating chunking metadata backward. +""" + +""" +NOTE [Why we need a separate pass to propagate ChunkingMeta.scale_by?] + +ChunkingMeta.scale_by only need to be propagated forward from the tangent placeholder nodes. +If we do this together with propagating other metadata, we can not fully control the propagating +order and end up with cases like: + out = aten.sub(lhs, rhs) +where `lhs` has scale_by set, while `rhs` and `out` don't. +For sub op, we could propagate `scale_by` to `rhs` and `out` since that's the +only way to make sense. But overall this is unsafe since maybe this is a case +that chunking does not work and we should bail out. +Another example is, we can not really propagate `scale_by` backward for +aten.mul since we don't know which of the input should have this `scale_by` metadata. + +But it's safer that we only propagate `scale_by` metadata in the topological order. + +Have the `scale_by` handled in a separate pass also makes the fwd/bwd +chunking metadata propagation much simpler. We don't need special rules +for mul/div/where etc due to the special handling of scale_by: +https://gist.github.com/shunting314/324e57881f168009784991300acab852 +""" + + +class PropagateStatus(Enum): + SUCCEED_NO_CHANGE = 0 + SUCCEED_WITH_CHANGE = 1 + FAIL = 2 + + +_HandlerRetType: TypeAlias = PropagateStatus | tuple[PropagateStatus, PropagateStatus] + +_HandlerType: TypeAlias = Callable[[Node], _HandlerRetType] + +# Rules to propagate chunking metadata from inputs to the current node +# or from the current node back to its inputs +propagate_rules: dict[torch._ops.OpOverload, _HandlerType] = {} + + +def _register_propagate_rule( + aten_op: torch._ops.OpOverload | Sequence[torch._ops.OpOverload], + handler: _HandlerType, +) -> _HandlerType: + if not isinstance(aten_op, (list, tuple)): + aten_op = [aten_op] # type: ignore[assignment, list-item] + + @functools.wraps(handler) + def wrapper(node: Node, *args: Any, **kwargs: Any) -> PropagateStatus: + fwd_bwd_status = handler(node, *args, **kwargs) + if isinstance(fwd_bwd_status, PropagateStatus): + return fwd_bwd_status + if not (isinstance(fwd_bwd_status, (list, tuple)) and len(fwd_bwd_status) == 2): + raise AssertionError( + f"expected (list, tuple) of len 2, got {type(fwd_bwd_status)}" + ) + fwd_status, bwd_status = fwd_bwd_status + log.debug( + "Chunking metadata propagation for %s: Fwd status %s, bwd status %s", + node, + fwd_status, + bwd_status, + ) + if fwd_status == PropagateStatus.FAIL or bwd_status == PropagateStatus.FAIL: + return PropagateStatus.FAIL + if ( + fwd_status == PropagateStatus.SUCCEED_WITH_CHANGE + or bwd_status == PropagateStatus.SUCCEED_WITH_CHANGE + ): + return PropagateStatus.SUCCEED_WITH_CHANGE + return PropagateStatus.SUCCEED_NO_CHANGE + + if not isinstance(aten_op, (list, tuple)): + raise AssertionError(f"{type(aten_op)=}") + for op in aten_op: + if not isinstance(op, torch._ops.OpOverload): + raise AssertionError(f"expected OpOverload, got {type(op)}") + propagate_rules[op] = wrapper + return wrapper + + +def register_propagate_rule( + aten_op: torch._ops.OpOverload | Sequence[torch._ops.OpOverload], +) -> Callable[[_HandlerType], _HandlerType]: + return functools.partial(_register_propagate_rule, aten_op) + + +def _is_success(*statuslist: PropagateStatus) -> bool: + return not any(status == PropagateStatus.FAIL for status in statuslist) + + +def _enqueue(queue: Queue, item: Node) -> None: # type: ignore[type-arg] + """ + Have a function to make it easier to do debug logging in a central place + """ + queue.put(item) + log.debug("Enqueue: %s", item) + + +def can_reach_amplified_node( + graph: Graph, amplifier_node: Node, is_fwd: bool +) -> dict[Node, bool]: + """ + A amplified node means a node with the same numel as `amplifier_node` + """ + filter_obj: dict[Node, bool] = {} + nodelist = reversed(graph.nodes) if is_fwd else graph.nodes + target_numel = get_fake_tensor_from_node_arg(amplifier_node).numel() # type: ignore[union-attr] + + for node in nodelist: + reach = False + if node.op == "output": + # output node does not have a meta['val'] + reach = False + + elif get_fake_tensor_from_node_arg(node) is None: + reach = False + + # for the back propagation, we should continue propagate if we can + # reach a tangent node + elif get_fake_tensor_from_node_arg(node).numel() == target_numel or ( # type: ignore[union-attr] + not is_fwd and is_tangent_node(node) + ): + reach = True + else: + neighbors = node.users if is_fwd else get_args_of_node_type(node) + reach = any(filter_obj[neighbor] for neighbor in neighbors) + filter_obj[node] = reach + return filter_obj + + +def propagate(amplifier_node: Node) -> None: + log.debug("amplifier_node is %s", amplifier_node.format_node()) + # Chunk the batch dimension (dim 0) of the amplifier_node + graph = amplifier_node.graph + + fwd_filter = can_reach_amplified_node(graph, amplifier_node, True) + bwd_filter = can_reach_amplified_node(graph, amplifier_node, False) + + log.debug("fwd_filter %s", fwd_filter) + log.debug("bwd_filter %s", bwd_filter) + + if len(get_nodes_with_chunking_meta(graph)) != 0: + raise AssertionError("Expect no nodes with chunking meta yet") + + set_chunking_meta(amplifier_node, chunk_dim=0) + + queue: Queue[Node] = Queue() + _enqueue(queue, amplifier_node) + + while not queue.empty(): + propagate_single_node(queue, fwd_filter, bwd_filter, queue.get()) + + nodes_with_chunking_meta = get_nodes_with_chunking_meta(graph) + propagate_scale_by(nodes_with_chunking_meta) + + if log.isEnabledFor(logging.DEBUG): + print("All nodes with chunking metadata set:") + for node in nodes_with_chunking_meta: + format_node_with_chunking_meta(node) + + +def propagate_single_node( + queue: Queue, fwd_filter: dict[Node, bool], bwd_filter: dict[Node, bool], node: Node +) -> None: # type: ignore[type-arg] + log.debug("Propagate_single_node: %s", node.format_node()) + + if node.op != "call_function": + raise CantChunk( + "Chunker can only propagate chunking metadata thru call_function nodes" + ) + + target = node.target + if log.isEnabledFor(logging.DEBUG): + log.debug("Before propagation, the node has the following chunking meta:") + format_node_with_chunking_meta(node, True) + + if not isinstance(target, torch._ops.OpOverload) or target not in propagate_rules: + raise CantChunk( + f"Missing propagation rule for target {target}: {node.format_node()}" + ) + + status = propagate_rules[target](node) + + if log.isEnabledFor(logging.DEBUG): + log.debug("After propagation, the node has the following chunking meta:") + format_node_with_chunking_meta(node, True) + + if status == PropagateStatus.FAIL: + raise CantChunk(f"Propagate rule for {target} fail: {node.format_node()}") + elif status == PropagateStatus.SUCCEED_WITH_CHANGE: + # propagate to used nodes + for arg in get_args_of_node_type(node): + # don't propagate back thru a placeholder node + if arg.op == "placeholder": + if "tangent" in arg.target: # type: ignore[operator] + # we have a separate pass to propagate scale_by information fwd. + set_chunking_meta(arg, scale_by=arg) + elif bwd_filter[arg]: + _enqueue(queue, arg) + + # propagate to user nodes + if fwd_filter[node]: + for user in node.users: + _enqueue(queue, user) + else: + if status != PropagateStatus.SUCCEED_NO_CHANGE: + raise AssertionError(f"status type {type(status)}, value {status}") + + +def _bool_to_status(changed: bool) -> PropagateStatus: + """ + Return the variant of the success flag depending on whether there is any change. + """ + return ( + PropagateStatus.SUCCEED_WITH_CHANGE + if changed + else PropagateStatus.SUCCEED_NO_CHANGE + ) + + +@register_propagate_rule(aten.addmm.default) +def propagate_addmm(addmm_node: Node) -> _HandlerRetType: + bias_node, input_node, weight_node = addmm_node.args + + def propagate_addmm_fwd() -> PropagateStatus: + if not isinstance(bias_node, Node): + raise AssertionError( + f"expected bias_node to be a Node, got {type(bias_node)}" + ) + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + if not isinstance(weight_node, Node): + raise AssertionError( + f"expected weight_node to be a Node, got {type(weight_node)}" + ) + if not has_any_chunking_meta(bias_node, input_node, weight_node): + return PropagateStatus.SUCCEED_NO_CHANGE + + # only input is chunked by dim 0 + if ( + has_nop_chunking_meta(bias_node) + and has_nop_chunking_meta(weight_node) + and is_chunked_by_dim(input_node, 0) + ): + # set a nop chunking metadata on bias_node & weight_node + # to indicate that they should be a part of the chunking + # subgraph. (i.e. we pass in them as placeholder node) + return _bool_to_status( + copy_chunking_meta(addmm_node, input_node) + | set_chunking_meta(bias_node) + | set_chunking_meta(weight_node) + ) + return PropagateStatus.FAIL + + def propagate_addmm_bwd() -> PropagateStatus: + if not isinstance(bias_node, Node): + raise AssertionError( + f"expected bias_node to be a Node, got {type(bias_node)}" + ) + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + if not isinstance(weight_node, Node): + raise AssertionError( + f"expected weight_node to be a Node, got {type(weight_node)}" + ) + + if not (meta := get_chunking_meta(addmm_node)): + return PropagateStatus.SUCCEED_NO_CHANGE + + if meta.chunked_by_dim(0): + # if the output is chunked by the batch dimension, then + # bias and input should as well + changed = set_chunking_meta(input_node, meta) | set_chunking_meta( + weight_node + ) + + # We should chunk the bias only if it's not broadcasted + bias_node_ft = get_fake_tensor_from_node_arg(bias_node) + input_node_ft = get_fake_tensor_from_node_arg(input_node) + if bias_node_ft is None: + raise AssertionError("expected bias_node_ft to not be None") + if input_node_ft is None: + raise AssertionError("expected input_node_ft to not be None") + if bias_node_ft.ndim < input_node_ft.ndim: + changed |= set_chunking_meta(bias_node) + else: + changed |= set_chunking_meta(bias_node, meta) + return _bool_to_status(changed) + + return PropagateStatus.FAIL + + return propagate_addmm_fwd(), propagate_addmm_bwd() + + +@register_propagate_rule(aten.mm.default) +def propagate_mm(mm_node: Node) -> _HandlerRetType: + lhs_node, rhs_node = mm_node.args[:2] + + def fwd() -> PropagateStatus: + if not isinstance(lhs_node, Node): + raise AssertionError( + f"expected lhs_node to be a Node, got {type(lhs_node)}" + ) + if not isinstance(rhs_node, Node): + raise AssertionError( + f"expected rhs_node to be a Node, got {type(rhs_node)}" + ) + lhs_meta = get_chunking_meta(lhs_node) + rhs_meta = get_chunking_meta(rhs_node) + + if has_nop_chunking_meta(lhs_node) and has_nop_chunking_meta(rhs_node): + return _bool_to_status(False) + + # only lhs is chunked + if not has_nop_chunking_meta(lhs_node) and has_nop_chunking_meta(rhs_node): + if lhs_meta is None: + raise AssertionError("expected lhs_meta to not be None") + return _bool_to_status( + copy_chunking_meta(mm_node, lhs_meta) | set_chunking_meta(rhs_node) + ) + + # either lhs or rhs is chunked at the reduction dimension + if (lhs_meta is not None and lhs_meta.chunk_dim == 1) or ( + rhs_meta is not None and rhs_meta.chunk_dim == 0 + ): + # The output is not chunked, but need to be sum'ed up! + return _bool_to_status( + set_chunking_meta(mm_node, chunk_dim=None, need_sum=True) + | update_chunking_meta(lhs_node, chunk_dim=1) + | update_chunking_meta(rhs_node, chunk_dim=0) + ) + + return PropagateStatus.FAIL + + def bwd() -> PropagateStatus: + if not isinstance(lhs_node, Node): + raise AssertionError( + f"expected lhs_node to be a Node, got {type(lhs_node)}" + ) + if not isinstance(rhs_node, Node): + raise AssertionError( + f"expected rhs_node to be a Node, got {type(rhs_node)}" + ) + out_meta = get_chunking_meta(mm_node) + if out_meta is None: + return _bool_to_status(False) + + # first dim of a 2D output is chunked + ft = get_fake_tensor_from_node_arg(mm_node) + if ft is None: + raise AssertionError("expected ft to not be None") + if ft.ndim == 2 and out_meta.chunk_dim == 0: + rhs_meta = get_chunking_meta(rhs_node) + if not ChunkingMeta.is_nop(rhs_meta): + raise AssertionError("expected rhs_meta to be a nop ChunkingMeta") + return _bool_to_status( + copy_chunking_meta(lhs_node, mm_node) | set_chunking_meta(rhs_node) + ) + + if out_meta.need_sum: + changed = set_chunking_meta(lhs_node, chunk_dim=1) | set_chunking_meta( + rhs_node, chunk_dim=0 + ) + return _bool_to_status(changed) + + return PropagateStatus.FAIL + + return fwd(), bwd() + + +@register_propagate_rule( + [ + prims.convert_element_type.default, + aten.exp.default, + aten.log.default, + aten.tanh.default, + aten.add.Tensor, + aten.sub.Tensor, + aten.div.Tensor, + aten.mul.Tensor, + prims.fma.default, + aten.where.self, + aten.neg.default, + aten.eq.Tensor, + ] +) +def propagate_general_copy_metadata( + out_node: Node, ignore_broadcast: bool = False +) -> _HandlerRetType: + """ + A general propagation rules that basically copy around the chunking + metadata. + """ + node_args = get_args_of_node_type(out_node) + node_is_scalar = get_node_is_scalar(node_args) + node_ndim = get_node_ndim(node_args) + + scalar_args = [node for node in node_args if node_is_scalar[node]] + non_scalar_args = [node for node in node_args if not node_is_scalar[node]] + + out_ndim = out_node.meta["val"].ndim + + # This general rule only allow scalar tensors without chunking meta + if scalar_args and not all( + ChunkingMeta.is_nop(get_chunking_meta(arg)) for arg in scalar_args + ): + return PropagateStatus.FAIL + + def _chunk_broadcasted_tensor(chunk_dim: int) -> bool: + for node in non_scalar_args: + if node_ndim[node] != out_ndim and chunk_dim >= out_ndim - node_ndim[node]: + return True + return False + + def propagate_fwd() -> PropagateStatus: + if len(node_args) == 0: + return PropagateStatus.FAIL + + first_meta = get_first_chunking_meta(*non_scalar_args) + if first_meta is None: + return _bool_to_status(False) + + need_handle_broadcast = ( + not ignore_broadcast and first_meta.chunk_dim is not None + ) + if ( + need_handle_broadcast + and first_meta.chunk_dim is not None + and _chunk_broadcasted_tensor(first_meta.chunk_dim) + ): + # We don't chunk a broadcasted tensor for now. + # Can add the rule if such a use case comes up + return PropagateStatus.FAIL + + changed = set_chunking_meta_if_none( + non_scalar_args, first_meta, lambda node: node_ndim[node] != out_ndim + ) + + for other_node in non_scalar_args: + other_meta = get_chunking_meta(other_node) + + if need_handle_broadcast and node_ndim[other_node] != out_ndim: + if not ChunkingMeta.is_nop(other_meta): + return PropagateStatus.FAIL + else: + if other_meta != first_meta: + return PropagateStatus.FAIL + + changed |= copy_chunking_meta(out_node, first_meta) + return _bool_to_status(changed) + + def propagate_bwd() -> PropagateStatus: + if not (meta := get_chunking_meta(out_node)): + return PropagateStatus.SUCCEED_NO_CHANGE + + need_handle_broadcast = not ignore_broadcast and meta.chunk_dim is not None + if ( + need_handle_broadcast + and meta.chunk_dim is not None + and _chunk_broadcasted_tensor(meta.chunk_dim) + ): + return PropagateStatus.FAIL + + # apply any to a list to avoid short-circuit + changed = any( + [ # noqa: C419 + copy_chunking_meta(node, meta) + if not need_handle_broadcast or node_ndim[node] == out_ndim + else set_chunking_meta(node) + for node in non_scalar_args + ] + ) + + # [NOTE: NOP Chunking metadata] + # For scalar node arguments, we add a nop ChunkingMeta so the + # propagation continues. This is mainly needed to reach the point + # where we attach chunking metadata to tangents that need to be + # included in the chunking subgraph. + # This is different to having a None ChunkingMeta + changed |= any( + [ # noqa: C419 + set_chunking_meta(node) + for node in scalar_args + if get_chunking_meta(node) is None + ] + ) + + return _bool_to_status(changed) + + return propagate_fwd(), propagate_bwd() + + +@register_propagate_rule( + [ + aten.squeeze.dim, + aten.gather.default, + aten.scatter.value, + aten.scatter_add.default, + ] +) +def propagate_general_copy_metadata_ignore_broadcast(out_node: Node) -> _HandlerRetType: + return propagate_general_copy_metadata(out_node, ignore_broadcast=True) # type: ignore[call-arg] + + +@register_propagate_rule( + [ + aten.amax.default, + aten.sum.dim_IntList, + ] +) +def propagate_reduce(reduce_node: Node) -> _HandlerRetType: + arg_node, reduce_dims = reduce_node.args[0:2] + + def propagate_fwd() -> PropagateStatus: + if not isinstance(arg_node, Node): + raise AssertionError( + f"expected arg_node to be a Node, got {type(arg_node)}" + ) + if not isinstance(reduce_dims, (tuple, list)): + raise AssertionError( + f"expected reduce_dims to be a tuple or list, got {type(reduce_dims)}" + ) + arg_meta = get_chunking_meta(arg_node) + if arg_meta is None: + return PropagateStatus.SUCCEED_NO_CHANGE + if arg_meta.chunk_dim not in reduce_dims: + # Reduce across the non chunked dimension + return _bool_to_status(copy_chunking_meta(reduce_node, arg_meta)) + + # sum across the chunked dimension. E.g. happens for computing + # the gradient of bias for an addmm + if reduce_node.target == aten.sum.dim_IntList and list(reduce_dims) == [ + arg_meta.chunk_dim + ]: + return _bool_to_status( + set_chunking_meta(reduce_node, arg_meta, chunk_dim=None, need_sum=True) + ) + + return PropagateStatus.FAIL + + def propagate_bwd() -> PropagateStatus: + if not isinstance(arg_node, Node): + raise AssertionError( + f"expected arg_node to be a Node, got {type(arg_node)}" + ) + if not isinstance(reduce_dims, (tuple, list)): + raise AssertionError( + f"expected reduce_dims to be a tuple or list, got {type(reduce_dims)}" + ) + out_meta = get_chunking_meta(reduce_node) + if out_meta is None: + return PropagateStatus.SUCCEED_NO_CHANGE + if out_meta.chunk_dim is not None: + if out_meta.chunk_dim in reduce_dims: + raise AssertionError( + f"expected chunk_dim {out_meta.chunk_dim} not in {reduce_dims}" + ) + return _bool_to_status(copy_chunking_meta(arg_node, out_meta)) + + if out_meta.chunk_dim is None and out_meta.need_sum and len(reduce_dims) == 1: + if reduce_node.target != aten.sum.dim_IntList: + raise AssertionError( + f"expected target aten.sum.dim_IntList, got {reduce_node.target}" + ) + return _bool_to_status( + set_chunking_meta( + arg_node, out_meta, chunk_dim=reduce_dims[0], need_sum=False + ) + ) + + return PropagateStatus.FAIL + + return propagate_fwd(), propagate_bwd() + + +@register_propagate_rule(aten.permute.default) +def propagate_permute(permute_node: Node) -> _HandlerRetType: + input_node, order = permute_node.args[:2] + + def propagate_fwd() -> PropagateStatus: + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + if not isinstance(order, (tuple, list)): + raise AssertionError( + f"expected order to be a tuple or list, got {type(order)}" + ) + input_meta = get_chunking_meta(input_node) + output_meta = get_chunking_meta(permute_node) + if input_meta is None: + return _bool_to_status(False) + + if input_meta.chunk_dim is None: + return PropagateStatus.FAIL + + orig_chunk_dim = input_meta.chunk_dim + # pyrefly: ignore [bad-argument-type, bad-assignment] + reverse_lookup: dict[int, int] = {v: k for k, v in enumerate(order)} + new_chunk_dim = reverse_lookup[orig_chunk_dim] + + # sanity check + if output_meta is not None: + if output_meta.chunk_dim != new_chunk_dim: + raise AssertionError( + f"expected chunk_dim {new_chunk_dim}, got {output_meta.chunk_dim}" + ) + return _bool_to_status( + set_chunking_meta(permute_node, meta=input_meta, chunk_dim=new_chunk_dim) + ) + + def propagate_bwd() -> PropagateStatus: + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + if not isinstance(order, (tuple, list)): + raise AssertionError( + f"expected order to be a tuple or list, got {type(order)}" + ) + + input_meta = get_chunking_meta(input_node) + output_meta = get_chunking_meta(permute_node) + if output_meta is None: + return _bool_to_status(False) + + if output_meta.chunk_dim is None: + return PropagateStatus.FAIL + + orig_chunk_dim = output_meta.chunk_dim + + new_chunk_dim = order[orig_chunk_dim] + + # sanity check + if input_meta is not None: + if input_meta.chunk_dim != new_chunk_dim: + raise AssertionError( + f"expected chunk_dim {new_chunk_dim}, got {input_meta.chunk_dim}" + ) + return _bool_to_status( + set_chunking_meta(input_node, meta=output_meta, chunk_dim=new_chunk_dim) + ) + + return propagate_fwd(), propagate_bwd() + + +@register_propagate_rule( + [ + aten.full.default, # nop since there is no inputs for fwd/bwd metadata propagation + ] +) +def propagate_nop(node: Node) -> _HandlerRetType: + def fwd() -> PropagateStatus: + return _bool_to_status(False) + + def bwd() -> PropagateStatus: + return _bool_to_status(False) + + return fwd(), bwd() + + +@register_propagate_rule(aten.unsqueeze.default) +def propagate_unsqueeze(unsqueeze_node: Node) -> _HandlerRetType: + input_node, unsqueeze_dim = unsqueeze_node.args[:2] + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + if not isinstance(unsqueeze_dim, int): + raise AssertionError( + f"expected unsqueeze_dim to be an int, got {type(unsqueeze_dim)}" + ) + input_ndim = get_fake_tensor_from_node_arg(input_node).ndim # type: ignore[union-attr] + # Normalize negative dim: unsqueeze valid range is [-(ndim+1), ndim] + normalized_dim = ( + unsqueeze_dim + input_ndim + 1 if unsqueeze_dim < 0 else unsqueeze_dim + ) + + def fwd() -> PropagateStatus: + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + input_meta = get_chunking_meta(input_node) + if input_meta is None: + return _bool_to_status(False) + if input_meta.chunk_dim is None: + return _bool_to_status(copy_chunking_meta(unsqueeze_node, input_meta)) + + # pyrefly: ignore[unsupported-operation] + new_dim = input_meta.chunk_dim + ( + 1 if input_meta.chunk_dim >= normalized_dim else 0 + ) + return _bool_to_status( + set_chunking_meta(unsqueeze_node, meta=input_meta, chunk_dim=new_dim) + ) + + def bwd() -> PropagateStatus: + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + output_meta = get_chunking_meta(unsqueeze_node) + if output_meta is None: + return _bool_to_status(False) + if output_meta.chunk_dim is None: + return _bool_to_status(copy_chunking_meta(input_node, output_meta)) + # pyrefly: ignore[unsupported-operation] + new_dim = output_meta.chunk_dim - ( + 1 if output_meta.chunk_dim > normalized_dim else 0 + ) + return _bool_to_status( + set_chunking_meta(input_node, meta=output_meta, chunk_dim=new_dim) + ) + + return fwd(), bwd() + + +def _find_chunk_dim_after_reshape( + old_shape: Sequence[int], new_shape: Sequence[int], chunk_dim: int +) -> int | None: + """ + Find the equivalent chunk_dim position after a reshape by matching + the prefix product (number of elements before the dimension) and + the dimension size. Returns None if the chunk dimension is merged + or split by the reshape, making it unsafe to propagate. + + Examples: + [M, N] -> [M, N, 1], chunk_dim=0: returns 0 (trailing dim added) + [M] -> [M, 1], chunk_dim=0: returns 0 + [M, N] -> [M1, M2, N] where M1*M2=M, chunk_dim=0: returns None (split) + [M, N] -> [M*N], chunk_dim=0: returns None (merged) + """ + chunk_size = old_shape[chunk_dim] + old_offset = math.prod(old_shape[:chunk_dim]) + new_offset = 1 + for new_dim in range(len(new_shape)): + if new_offset == old_offset and new_shape[new_dim] == chunk_size: + return new_dim + new_offset *= new_shape[new_dim] + return None + + +@register_propagate_rule(aten.view.default) +def propagate_view(view_node: Node) -> _HandlerRetType: + input_node = view_node.args[0] + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + input_shape = list(get_fake_tensor_from_node_arg(input_node).shape) # type: ignore[union-attr] + output_shape = list(get_fake_tensor_from_node_arg(view_node).shape) # type: ignore[union-attr] + + def fwd() -> PropagateStatus: + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + input_meta = get_chunking_meta(input_node) + if input_meta is None: + return _bool_to_status(False) + if input_meta.chunk_dim is None: + return _bool_to_status(copy_chunking_meta(view_node, input_meta)) + new_dim = _find_chunk_dim_after_reshape( + input_shape, output_shape, input_meta.chunk_dim + ) + if new_dim is None: + return PropagateStatus.FAIL + return _bool_to_status( + set_chunking_meta(view_node, meta=input_meta, chunk_dim=new_dim) + ) + + def bwd() -> PropagateStatus: + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + output_meta = get_chunking_meta(view_node) + if output_meta is None: + return _bool_to_status(False) + if output_meta.chunk_dim is None: + return _bool_to_status(copy_chunking_meta(input_node, output_meta)) + new_dim = _find_chunk_dim_after_reshape( + output_shape, input_shape, output_meta.chunk_dim + ) + if new_dim is None: + return PropagateStatus.FAIL + return _bool_to_status( + set_chunking_meta(input_node, meta=output_meta, chunk_dim=new_dim) + ) + + return fwd(), bwd() + + +@register_propagate_rule( + [ + aten.expand.default, + ] +) +def propagate_expand(expand_node: Node) -> _HandlerRetType: + input_node = expand_node.args[0] + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + + input_ft = get_fake_tensor_from_node_arg(input_node) + if input_ft is None: + raise AssertionError("expected input_ft to not be None") + output_ft = get_fake_tensor_from_node_arg(expand_node) + if output_ft is None: + raise AssertionError("expected output_ft to not be None") + input_shape = list(input_ft.shape) + output_shape = list(output_ft.shape) + + if input_ft.numel() == 1: + # Scalar input: combined fwd/bwd rule + output_meta = get_chunking_meta(expand_node) + if output_meta is None: + return _bool_to_status(False) + return _bool_to_status(set_chunking_meta(input_node)) + + # How many leading dims are added by expand + dim_offset = len(output_shape) - len(input_shape) + + def is_expand_dim(out_dim: int) -> bool: + """Check if out_dim is a broadcast dimension (newly added or size 1 in input).""" + return out_dim < dim_offset or input_shape[out_dim - dim_offset] == 1 + + def fwd() -> PropagateStatus: + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + input_meta = get_chunking_meta(input_node) + if input_meta is None: + return _bool_to_status(False) + # Fail if chunk_dim is an expand dimension (input size 1 broadcast to larger size) + if input_meta.chunk_dim is not None and is_expand_dim( + input_meta.chunk_dim + dim_offset + ): + return PropagateStatus.FAIL + return _bool_to_status(copy_chunking_meta(expand_node, input_meta)) + + def bwd() -> PropagateStatus: + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + output_meta = get_chunking_meta(expand_node) + if output_meta is None: + return _bool_to_status(False) + # Fail if chunk_dim is an expand dimension (input size 1 broadcast to larger size) + if output_meta.chunk_dim is not None and is_expand_dim(output_meta.chunk_dim): + return PropagateStatus.FAIL + return _bool_to_status(copy_chunking_meta(input_node, output_meta)) + + return fwd(), bwd() + + +@register_propagate_rule( + [ + aten.sum.default, + ] +) +def propagate_sum_to_scalar(sum_node: Node) -> _HandlerRetType: + input_node = sum_node.args[0] + if not isinstance(input_node, Node): + raise AssertionError( + f"expected input_node to be a Node, got {type(input_node)}" + ) + + def fwd() -> PropagateStatus: + input_meta = get_chunking_meta(input_node) # pyrefly: ignore[bad-argument-type] + if has_nop_chunking_meta(input_node): # pyrefly: ignore[bad-argument-type] + return _bool_to_status(False) + + if input_meta is None: + raise AssertionError("expected input_meta to not be None") + if input_meta.chunk_dim is not None: + changed = update_chunking_meta(sum_node, need_sum=True, chunk_by=None) + return _bool_to_status(changed) + return PropagateStatus.FAIL + + def bwd() -> PropagateStatus: + input_meta = get_chunking_meta(input_node) # pyrefly: ignore[bad-argument-type] + if has_nop_chunking_meta(sum_node): + return _bool_to_status(False) + + # We won't know how the input is chunked if sum_node.meta.need_sum is True. + # On the other hand, sum_node.meta.need_sum is True can only happen + # by propagating from input_node. Doing sanity check here is fine + # since the input_node.meta should have already been properly + # setup. + output_meta = get_chunking_meta(sum_node) + if ( + output_meta is not None + and output_meta.need_sum + and input_meta is not None + and input_meta.chunk_dim is not None + ): + return _bool_to_status(False) + + return PropagateStatus.FAIL + + return fwd(), bwd() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..aed9ef89c09bf8c71141d3f2fd71ade1d3db1fee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/auto_chunker/utils.py @@ -0,0 +1,185 @@ +from collections.abc import Sequence +from typing import Any + +import torch +from torch.fx import Graph, GraphModule, Node +from torch.utils._pytree import tree_flatten + +from .common import CantChunk, ChunkingMeta + + +def is_tangent_node(node: Node) -> bool: + return node.op == "placeholder" and "tangent" in node.name + + +def get_args_of_node_type(node: Node) -> Sequence[Node]: + return [x for x in tree_flatten((node.args, node.kwargs))[0] if isinstance(x, Node)] + + +def use_tangent(node: Node) -> bool: + """ + Whether the fx node uses tangent input. + """ + + return any( + is_tangent_node(arg) # type: ignore[operator] + for arg in get_args_of_node_type(node) + ) + + +def compute_tensor_size(*args: Any, count_bytes: bool = True, **kwargs: Any) -> int: + """ + Compute total tensor sizes from fx.Node in args & kwargs. + """ + flat_args, _ = tree_flatten((args, kwargs)) + tot = 0 + for arg in flat_args: + if (fake_tensor := get_fake_tensor_from_node_arg(arg)) is None: + continue + tot += fake_tensor.numel() * (fake_tensor.dtype.itemsize if count_bytes else 1) + return tot + + +def get_fake_tensor_from_node_arg( + node: torch.fx.node.Argument, +) -> torch.Tensor | None: + if ( + not hasattr(node, "meta") + or ("val" not in node.meta) # type: ignore[union-attr] + or not isinstance(node.meta["val"], torch.Tensor) # type: ignore[union-attr] + ): + return None + return node.meta["val"] # type: ignore[union-attr] + + +def get_nodes_with_chunking_meta(graph: torch.fx.Graph) -> Sequence[Node]: + from .core import get_chunking_meta + + output = [] + for node in graph.nodes: + if get_chunking_meta(node): + output.append(node) + return output + + +def format_node_with_chunking_meta( + node: torch.fx.Node, include_args: bool = False +) -> None: + """ + Print the node with chunking metadata for the current node if exists. + + If include_args is True, also print chunking metadata for Node arguments. + """ + from torch._inductor.runtime.runtime_utils import green_text + + from .core import get_chunking_meta + + fake_tensor = get_fake_tensor_from_node_arg(node) + shape = list(fake_tensor.shape) if fake_tensor is not None else "?" + print(f" {shape} {node.format_node()}") + + if meta := get_chunking_meta(node): + print(f" {green_text(str(meta))}") + + if include_args: + for arg in get_args_of_node_type(node): + if arg_meta := get_chunking_meta(arg): + print(f" {arg}: {green_text(str(arg_meta))}") + + +def has_any_chunking_meta(*node_list: Node) -> bool: + from .core import get_chunking_meta + + return any(get_chunking_meta(node) for node in node_list) + + +def get_first_chunking_meta(*node_list: Node) -> ChunkingMeta | None: + """ + Get the first non-none chunking metadata if there is any. + """ + from .core import get_chunking_meta + + for node in node_list: + if (meta := get_chunking_meta(node)) is not None: + return meta + + return None + + +def get_scale_by_from_metas(*metas: ChunkingMeta) -> Node | None: + """ + If there are multiple ChunkingMeta having the scale_by field, + raise a CantChunk exception. + + If no ChunkingMeta has scale_by field, return None. + Otherwise return the only scale_by field. + """ + + scale_by_list = [] + + # don't do dedup on the scale_by field on purpose for this API + for meta in metas: + if meta.scale_by is not None: + scale_by_list.append(meta.scale_by) + + if len(scale_by_list) > 1: + raise CantChunk("Multiple scale_by") + + return scale_by_list[0] if len(scale_by_list) == 1 else None + + +def get_scale_by_from_node(node: Node) -> Node | None: + from .core import get_chunking_meta + + meta = get_chunking_meta(node) + return meta.scale_by if meta is not None else None + + +def get_node_is_scalar(nodes: Sequence[Node]) -> dict[Node, bool]: + """ + Returns a dict map a node to 'is_scalar'. + """ + node_is_scalar = {} + for node in nodes: + ft = get_fake_tensor_from_node_arg(node) + if ft is None: + raise AssertionError(f"expected a fake tensor for node {node}, got None") + node_is_scalar[node] = ft.numel() == 1 + return node_is_scalar + + +def get_node_ndim(nodes: Sequence[Node]) -> dict[Node, int]: + """ + Returns a dict map a node to 'ndim'. + """ + node_ndim = {} + for node in nodes: + ft = get_fake_tensor_from_node_arg(node) + if ft is None: + raise AssertionError(f"expected a fake tensor for node {node}, got None") + node_ndim[node] = ft.ndim + return node_ndim + + +def is_chunked_by_dim(node: Node, dim: int) -> bool: + from .core import get_chunking_meta + + meta = get_chunking_meta(node) + return meta is not None and meta.chunked_by_dim(dim) + + +def tangent_has_chunking_meta(gm: GraphModule) -> bool: + from .core import get_chunking_meta + + return any( + is_tangent_node(node) and get_chunking_meta(node) is not None + for node in gm.graph.find_nodes(op="placeholder", sort=False) + ) + + +def get_tangent_nodes(graph: Graph) -> Sequence[Node]: + tangents = [] + for node in graph.find_nodes(op="placeholder", sort=False): + if is_tangent_node(node): + tangents.append(node) + return tangents diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/b2b_gemm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/b2b_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..ce23cf84ae5ee9d3ed891f00b68813915daf43ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/b2b_gemm.py @@ -0,0 +1,800 @@ +# mypy: allow-untyped-defs +import functools +from collections import deque + +import torch +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import tree_map + +from ..._dynamo.utils import counters +from ..ir import ( + ComputedBuffer, + FixedLayout, + FlexibleLayout, + InputBuffer, + StorageBox, + Subgraph, + TensorBox, +) +from ..lowering import lowerings +from ..pattern_matcher import ( + Arg, + CallFunction, + Match, + PatternMatcherPass, + register_graph_pattern, +) +from ..select_algorithm import ( + autotune_select_algorithm, + SymbolicGridFn, + TritonTemplate, + TritonTemplateCaller, +) +from ..utils import ceildiv + + +B2B_GEMM_PASS = PatternMatcherPass( + pass_name="b2b_gemm_pass", +) + + +@SymbolicGridFn +def b2b_gemm_grid(M, P, meta, *, cdiv): + return (cdiv(M, meta["BLOCK_SIZE_M"]) * cdiv(P, meta["BLOCK_SIZE_P"]), 1, 1) + + +b2b_gemm_left_template = TritonTemplate( + name="b2b_gemm_left", + grid=b2b_gemm_grid, + debug=False, + source=r""" +{{def_kernel("A", "B", "C")}} + + + # B2B_GEMM_LEFT_TRITON_ENTRANCE + + # dynamic shapes + M = {{size("A", 0)}} + N = {{size("A", 1)}} + O = {{size("C", 0)}} + P = {{size("C", 1)}} + + # dynamic strides + stride_am = {{stride("A", 0)}} + stride_an = {{stride("A", 1)}} + stride_bn = {{stride("B", 0)}} + stride_bo = {{stride("B", 1)}} + stride_co = {{stride("C", 0)}} + stride_cp = {{stride("C", 1)}} + + # output block counts + num_m_block = tl.cdiv(M, BLOCK_SIZE_M) + num_p_block = tl.cdiv(P, BLOCK_SIZE_P) + + # internal block counts + num_n_block = tl.cdiv(N, BLOCK_SIZE_N) + num_o_block = tl.cdiv(O, BLOCK_SIZE_O) + + # output block ids + pid = tl.program_id(axis=0) + m_block_id = pid // num_p_block + p_block_id = pid % num_p_block + + # accumulator + acc = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_P), dtype=tl.float32) + + # main loop + offs_m = (m_block_id * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) + offs_p = (p_block_id * BLOCK_SIZE_P + tl.arange(0, BLOCK_SIZE_P)) + # (subgraph(A @ B) @ C) + offs_o = tl.arange(0, BLOCK_SIZE_O) + for _ in range(num_o_block): + c_mask = (offs_o[:, None] < O) & (offs_p[None, :] < P) + c_ptrs = C + (offs_o[:, None] * stride_co + offs_p[None, :] * stride_cp) + c = tl.load(c_ptrs, mask=c_mask, other=0.0).to(tl.float32) # BLOCK_SIZE_O * BLOCK_SIZE_P + acc_ab = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_O), dtype=tl.float32) + offs_n = tl.arange(0, BLOCK_SIZE_N) + for __ in range(num_n_block): + a_mask = (offs_m[:, None] < M) & (offs_n[None, :] < N) + a_ptrs = A + (offs_m[:, None] * stride_am + offs_n[None, :] * stride_an) + a = tl.load(a_ptrs, mask=a_mask, other=0.0).to(tl.float32) # BLOCK_SIZE_M * BLOCK_SIZE_N + b_mask = (offs_n[:, None] < N) & (offs_o[None, :] < O) + b_ptrs = B + (offs_n[:, None] * stride_bn + offs_o[None, :] * stride_bo) + b = tl.load(b_ptrs, mask=b_mask, other=0.0).to(tl.float32) # BLOCK_SIZE_N * BLOCK_SIZE_O + acc_ab += tl.dot(a, b, out_dtype=tl.float32) + offs_n += BLOCK_SIZE_N + # apply the subgraph + {{ modification( + subgraph_number=0, + output_name="post_subgraph_acc_ab", + inner_mm="acc_ab" + ) | indent_except_first(2) }} + acc += tl.dot(post_subgraph_acc_ab, c, out_dtype=tl.float32) + offs_o += BLOCK_SIZE_O + + # type conversion + acc = acc.to(tl.float16) + + # store preparation + idx_m = offs_m[:, None] + idx_p = offs_p[None, :] + out_mask = (idx_m < M) & (idx_p < P) + + {{store_output(("idx_m", "idx_p"), "acc", "out_mask", val_shape=("BLOCK_SIZE_M", "BLOCK_SIZE_P"))}} +""", +) + + +b2b_gemm_right_template = TritonTemplate( + name="b2b_gemm_right", + grid=b2b_gemm_grid, + debug=False, + source=r""" +{{def_kernel("A", "B", "C")}} + + + # B2B_GEMM_RIGHT_TRITON_ENTRANCE + + # dynamic shapes + M = {{size("A", 0)}} + N = {{size("A", 1)}} + O = {{size("C", 0)}} + P = {{size("C", 1)}} + + # dynamic strides + stride_am = {{stride("A", 0)}} + stride_an = {{stride("A", 1)}} + stride_bn = {{stride("B", 0)}} + stride_bo = {{stride("B", 1)}} + stride_co = {{stride("C", 0)}} + stride_cp = {{stride("C", 1)}} + + # output block counts + num_m_block = tl.cdiv(M, BLOCK_SIZE_M) + num_p_block = tl.cdiv(P, BLOCK_SIZE_P) + + # internal block counts + num_n_block = tl.cdiv(N, BLOCK_SIZE_N) + num_o_block = tl.cdiv(O, BLOCK_SIZE_O) + + # output block ids + pid = tl.program_id(axis=0) + m_block_id = pid // num_p_block + p_block_id = pid % num_p_block + + # accumulator + acc = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_P), dtype=tl.float32) + + # main loop (two cases) + offs_m = (m_block_id * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) + offs_p = (p_block_id * BLOCK_SIZE_P + tl.arange(0, BLOCK_SIZE_P)) + # (A @ subgraph(B @ C)) + offs_n = tl.arange(0, BLOCK_SIZE_N) + for _ in range(num_n_block): + a_mask = (offs_m[:, None] < M) & (offs_n[None, :] < N) + a_ptrs = A + (offs_m[:, None] * stride_am + offs_n[None, :] * stride_an) + a = tl.load(a_ptrs, mask=a_mask, other=0.0).to(tl.float32) # BLOCK_SIZE_M * BLOCK_SIZE_N + acc_bc = tl.zeros((BLOCK_SIZE_N, BLOCK_SIZE_P), dtype=tl.float32) + offs_o = tl.arange(0, BLOCK_SIZE_O) + for __ in range(num_o_block): + b_mask = (offs_n[:, None] < N) & (offs_o[None, :] < O) + b_ptrs = B + (offs_n[:, None] * stride_bn + offs_o[None, :] * stride_bo) + b = tl.load(b_ptrs, mask=b_mask, other=0.0).to(tl.float32) # BLOCK_SIZE_N * BLOCK_SIZE_O + c_mask = (offs_o[:, None] < O) & (offs_p[None, :] < P) + c_ptrs = C + (offs_o[:, None] * stride_co + offs_p[None, :] * stride_cp) + c = tl.load(c_ptrs, mask=c_mask, other=0.0).to(tl.float32) # BLOCK_SIZE_O * BLOCK_SIZE_P + acc_bc += tl.dot(b, c, out_dtype=tl.float32) + offs_o += BLOCK_SIZE_O + # apply the subgraph + {{ modification( + subgraph_number=0, + output_name="post_subgraph_acc_bc", + inner_mm="acc_bc" + ) | indent_except_first(2) }} + acc += tl.dot(a, post_subgraph_acc_bc, out_dtype=tl.float32) + offs_n += BLOCK_SIZE_N + + # type conversion + acc = acc.to(tl.float16) + + # store preparation + idx_m = offs_m[:, None] + idx_p = offs_p[None, :] + out_mask = (idx_m < M) & (idx_p < P) + + {{store_output(("idx_m", "idx_p"), "acc", "out_mask", val_shape=("BLOCK_SIZE_M", "BLOCK_SIZE_P"))}} +""", +) + + +# Note: load_ratio_left and load_ratio_right are only calculating numbers +# in the trivial subgraph case; i.e. (A @ (B @ C)) or ((A @ B) @ C) + + +def load_ratio_left( + M: int, N: int, O: int, P: int, m: int, n: int, o: int, p: int +) -> float: + """ + compute the ratio of estimated numbers of loads in baseline and b2bgemm + M, N, O, P are matrix sizes + m, n, o, p are block sizes + | | baseline (lower bound) | b2bgemm + | load | M * N + N * O + M * O + O * P | M / m * P / p * O / o * (o * p + N / n * (m * n + n * o)) + | store | M * O + M * P | M * P + b2bgemm is always better on stores, but for loads we need to find out beneficial cases using this function + """ + base = M * N + N * O + M * O + O * P + gemm = ( + ceildiv(M, m) + * ceildiv(P, p) + * ceildiv(O, o) + * (o * p + ceildiv(N, n) * (m * n + n * o)) + ) + return base / gemm + + +def load_ratio_right( + M: int, N: int, O: int, P: int, m: int, n: int, o: int, p: int +) -> float: + """ + compute the ratio of estimated numbers of loads in baseline and b2bgemm + M, N, O, P are matrix sizes + m, n, o, p are block sizes + | | baseline (lower bound) | b2bgemm + | load | N * O + O * P + M * N + N * P | M / m * P / p * N / n * (m * n + O / o * (n * o + o * p)) + | store | N * P + M * P | M * P + b2bgemm is always better on stores, but for loads we need to find out beneficial cases using this function + """ + base = N * O + O * P + M * N + N * P + gemm = ( + ceildiv(M, m) + * ceildiv(P, p) + * ceildiv(N, n) + * (m * n + ceildiv(O, o) * (n * o + o * p)) + ) + return base / gemm + + +# the block sizes are limited by hardware (the shared memory) +# intuitively, the optimization works when the intermediate matrix is large +# and we assign large block sizes to large dimensions +b2b_gemm_configs = [ + { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_O": 16, + "BLOCK_SIZE_P": 16, + "num_stages": 4, + "num_warps": 8, + }, + { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_O": 32, + "BLOCK_SIZE_P": 32, + "num_stages": 2, + "num_warps": 4, + }, + { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_O": 64, + "BLOCK_SIZE_P": 64, + "num_stages": 2, + "num_warps": 4, + }, + { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_O": 128, + "BLOCK_SIZE_P": 16, + "num_stages": 4, + "num_warps": 8, + }, + { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_O": 128, + "BLOCK_SIZE_P": 32, + "num_stages": 2, + "num_warps": 4, + }, + { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_O": 128, + "BLOCK_SIZE_P": 64, + "num_stages": 2, + "num_warps": 4, + }, + { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_O": 16, + "BLOCK_SIZE_P": 128, + "num_stages": 4, + "num_warps": 8, + }, + { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_O": 32, + "BLOCK_SIZE_P": 128, + "num_stages": 2, + "num_warps": 4, + }, + { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_O": 64, + "BLOCK_SIZE_P": 128, + "num_stages": 2, + "num_warps": 4, + }, + { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_O": 16, + "BLOCK_SIZE_P": 128, + "num_stages": 4, + "num_warps": 8, + }, + { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_O": 32, + "BLOCK_SIZE_P": 128, + "num_stages": 2, + "num_warps": 4, + }, + { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_O": 64, + "BLOCK_SIZE_P": 128, + "num_stages": 2, + "num_warps": 4, + }, +] + + +def is_b2b_gemm_good_on( + is_left_assoc: bool, + A_node: torch.fx.Node, + B_node: torch.fx.Node, + C_node: torch.fx.Node, +) -> bool: + """ + checks whether the sizes are good for b2b_gemm + """ + # basic checks + if not all(["val" in A_node.meta, "val" in B_node.meta, "val" in C_node.meta]): + return False + fake_tensors = ( + A_node.meta["val"], + B_node.meta["val"], + C_node.meta["val"], + ) # torch._subclasses.fake_tensor.FakeTensor + + A, B, C = fake_tensors + + def check_all_attr_true(objects, attr): + return all(hasattr(obj, attr) and getattr(obj, attr) for obj in objects) + + if not check_all_attr_true(fake_tensors, "is_cuda") and not check_all_attr_true( + fake_tensors, "is_xpu" + ): + return False + if not all([len(A.shape) == 2, len(B.shape) == 2, len(C.shape) == 2]): + return False + if not ((A.shape[1] == B.shape[0]) and (B.shape[1] == C.shape[0])): + return False + # size checks: we only dispatch to B2B-GEMM when the average load ratio is > 1 + M, N = A.shape + O, P = C.shape + ratios = [] + if is_left_assoc: + for config in b2b_gemm_configs: + ratio = load_ratio_left( + M, + N, + O, + P, + config["BLOCK_SIZE_M"], + config["BLOCK_SIZE_N"], + config["BLOCK_SIZE_O"], + config["BLOCK_SIZE_P"], + ) + ratios.append(ratio) + else: + for config in b2b_gemm_configs: + ratio = load_ratio_right( + M, + N, + O, + P, + config["BLOCK_SIZE_M"], + config["BLOCK_SIZE_N"], + config["BLOCK_SIZE_O"], + config["BLOCK_SIZE_P"], + ) + ratios.append(ratio) + ratios.sort(reverse=True) + average_ratio = 1.0 + for r in ratios[:3]: # top 3 choices + average_ratio *= r + average_ratio = average_ratio ** (1 / 3) + return ( + average_ratio > 1 + ) # even if average_ratio is close to 1, the number of stores is always better + + +def _make_unoptimized_b2b_gemm_choice( + is_left_assoc: bool, + subgraph: Subgraph, + input_nodes: list[TensorBox], + layout: FixedLayout, +): # -> SubgraphChoiceCaller (local import) + from ..codegen.subgraph import SubgraphChoiceCaller + + tag = "left" if is_left_assoc else "right" + epilogue = subgraph.graph_module + + def make_fx_graph(*args: torch.Tensor) -> torch.fx.GraphModule: + from torch.fx.experimental.proxy_tensor import make_fx + + from ..decomposition import select_decomp_table + + A, B, C = args + + def computation(A, B, C): + if is_left_assoc: + return torch.mm(epilogue(torch.mm(A, B)), C) + else: + return torch.mm(A, epilogue(torch.mm(B, C))) + + return make_fx( + computation, + decomposition_table=select_decomp_table(), + tracing_mode="symbolic", + )(A, B, C) + + return SubgraphChoiceCaller( + name=f"unoptimized_b2b_gemm_{tag}", + # pyrefly: ignore [bad-argument-type] + input_nodes=input_nodes, + layout=layout, + description=f"unoptimized b2b_gemm ({tag}-associative)", + make_fx_graph=make_fx_graph, + ) + + +def build_subgraph_buffer( + args: list[TensorBox], + subgraph: Subgraph, +): + """ + This function is adapted from ../kernel/flex_attention.py. + The goal is to take in the required args and produce the subgraph buffer + The subgraph buffer is a ComputedBuffer that will be inlined into the triton template + + Args: + args: The args that are passed into the subgraph + subgraph: The Subgraph ir for which to produce the output node + """ + cnt = 0 + env = {} + for node in subgraph.graph_module.graph.nodes: + if node.op == "placeholder": + env[node] = args[cnt] + cnt += 1 + elif node.op == "call_function": + # For call_function we use the default lowerings and pass in the + # already created TensorBoxes as args + args, kwargs = tree_map(lambda x: env.get(x, x), (node.args, node.kwargs)) + env[node] = lowerings[node.target](*args, **kwargs) + elif node.op == "output": + + def convert_output_node_to_buffer(output): + if output is None: + return None + output_node = output + output_buffer = env[output_node] + if not isinstance(output_buffer, TensorBox): + raise AssertionError( + ( + "The output node for B2B-GEMM's subgraph must be a TensorBox, but got: ", + type(output_buffer), + ) + ) + if not isinstance(output_buffer.data, StorageBox): + raise AssertionError( + ( + "The output node for B2B-GEMM's subgraph must be a StorageBox, but got: ", + type(output_buffer), + ) + ) + device = output_buffer.data.get_device() + if device is None: + raise AssertionError("expected output buffer to have a device") + subgraph_buffer = ComputedBuffer( + name=None, + layout=FlexibleLayout( + device=device, + dtype=output_buffer.data.get_dtype(), + size=output_buffer.data.get_size(), + ), + data=output_buffer.data.data, # type: ignore[arg-type] + ) + return subgraph_buffer + + # node.args[0] should be a single element representing the output of the subgraph + return tree_map(convert_output_node_to_buffer, node.args[0]) + + raise ValueError("B2B-GEMM was passed a subgraph with no output node!") + + +def create_placeholder( + name: str, dtype: torch.dtype, device: torch.device +) -> TensorBox: + """ + Creates a placeholder input buffers for producing subgraph_output + """ + input_buffer = InputBuffer(name=name, layout=FixedLayout(device, dtype, [], [])) + return TensorBox.create(input_buffer) + + +def tuned_b2b_gemm( + is_left_assoc: bool, + subgraph: Subgraph, + A: torch._inductor.ir.TensorBox, + B: torch._inductor.ir.TensorBox, + C: torch._inductor.ir.TensorBox, + *, + layout=None, +) -> torch._inductor.ir.TensorBox: + # call .realize() to get rid of Pointwise + A.realize() + B.realize() + C.realize() + layout = FixedLayout( + A.get_device_or_error(), + A.get_dtype(), + [A.shape[0], C.shape[1]], # type: ignore[index] + ) + placeholders = [ + create_placeholder("inner_mm", A.get_dtype(), A.get_device_or_error()) + ] + subgraph_buffer = build_subgraph_buffer( + placeholders, # type: ignore[arg-type, list-item] + subgraph, + ) + choices: list[TritonTemplateCaller] = [] + for config in b2b_gemm_configs: + if is_left_assoc: + b2b_gemm_left_template.maybe_append_choice( + choices, + input_nodes=(A, B, C), + layout=layout, + subgraphs=[subgraph_buffer], + **config, + ) + else: + b2b_gemm_right_template.maybe_append_choice( + choices, + input_nodes=(A, B, C), + layout=layout, + subgraphs=[subgraph_buffer], + **config, + ) + # add the unoptimized choice to mitigate performance degradation + choices.append( + _make_unoptimized_b2b_gemm_choice(is_left_assoc, subgraph, [A, B, C], layout) + ) + # autotune + node, _ = autotune_select_algorithm("b2b_gemm", choices, [A, B, C], layout) + return node + + +# match the inner mm of a potential b2b_gemm +@register_graph_pattern( + CallFunction(torch.ops.aten.mm, Arg(), Arg()), + # pyrefly: ignore [bad-argument-type] + pass_dict=B2B_GEMM_PASS, +) +def b2b_gemm_handler(match: Match, mat1: torch.fx.Node, mat2: torch.fx.Node) -> None: + # match.args: list[torch.fx.Node] + + def is_pointwise_node(node: torch.fx.Node) -> bool: + return ( + node.op == "call_function" + and isinstance(node.target, torch._ops.OpOverload) + and (torch.Tag.pointwise in node.target.tags) + ) + + def is_mm(node: torch.fx.Node) -> bool: + return node.target is torch.ops.aten.mm.default + + # the inner MM + inner_mm = match.nodes[-1] + + # find the (candidate) outer MM, which will be re-checked below to ensure every path reaches it + # In a real (A @ f(B @ C)), every path starting from (B @ C) must reach (A @ _). + outer_mm = None + node = inner_mm + while len(node.users) > 0: + node = next(iter(node.users)) + if is_mm(node): + outer_mm = node + break + elif is_pointwise_node(node): + continue + else: + break + if not outer_mm: + return + + # find the unique input node for outer_mm representing f(B @ C) in (A @ f(B @ C)) + # we call it the "f_node" + # when the pattern is simply (A @ (B @ C)), f_node is just inner_mm + f_node = inner_mm + while next(iter(f_node.users)) is not outer_mm: + f_node = next(iter(f_node.users)) + + def all_reach_via_pointwise_with_no_other_inputs( + src: torch.fx.Node, + dst: torch.fx.Node, + ) -> tuple[bool, OrderedSet[torch.fx.Node]]: + """ + check whether every user path from src reaches dst via pointwise nodes, + with no other input nodes for the intermediates and dst; + return + (1) the Boolean value + (2) the subgraph node set including src and dst (which only makes sense when the Boolean value is True) + """ + visited = OrderedSet[torch.fx.Node]() + input_counter: dict[torch.fx.Node, int] = {} + + all_reachable = True + queue = deque([src]) + while queue: + node = queue.popleft() + if node not in visited: + if node is dst: + visited.add(node) + elif (node is src) or is_pointwise_node(node): + for user in node.users: + # for nodes other than dst, bookkeep their users' input counts + if user not in input_counter: + input_counter[user] = len(user.all_input_nodes) + input_counter[user] -= 1 + # continue BFS + queue.append(user) + visited.add(node) + else: + all_reachable = False + break + + return ( + all_reachable and all(count == 0 for count in input_counter.values()), + visited, + ) + + # check inner_mm reaches f_node on every user path via pointwise nodes with no outside input_nodes + ok, subgraph_node_set = all_reach_via_pointwise_with_no_other_inputs( + inner_mm, f_node + ) + if not ok: + return + + # check inner_mm's inputs and f_node's outputs + if not (len(inner_mm.all_input_nodes) == 2 and len(f_node.users) == 1): + return + + # at this point, the nodes between inner_mm and f_node (both included) + # are all used internally inside (A @ subgraph(B @ C)) + # i.e. they neither have other users nor have other inputs + + # original graph and module + graph = inner_mm.graph + module = graph.owning_module + if module is None: + raise AssertionError("graph.owning_module must not be None") + + # construct the new (sub)graph + subgraph_node_list: list[ + torch.fx.Node + ] = [] # ordered list of nodes used for node removal later + new_graph: torch.fx.Graph = torch.fx.Graph() + node_remapping: dict[torch.fx.Node, torch.fx.Node] = {} + new_input_anchor: torch.fx.Node # inner_mm, to be changed to an input node + new_output_anchor: torch.fx.Node # f_node, to be used to construct an output node + new_input_node: torch.fx.Node + new_output_node: torch.fx.Node + for node in graph.nodes: # preserve the order of nodes + if node in subgraph_node_set: + subgraph_node_list.append(node) + new_node = new_graph.node_copy(node, lambda x: node_remapping.get(x, x)) + node_remapping[node] = new_node + if node is inner_mm: + new_input_anchor = new_node + if node is f_node: + new_output_anchor = new_node + # pyrefly: ignore [unbound-name] + if new_input_anchor is not new_output_anchor: # subgraph is non-trivial + # update the input node + # pyrefly: ignore [unbound-name] + with new_graph.inserting_before(new_input_anchor): + new_input_node = new_graph.placeholder(name="subgraph_input") + # pyrefly: ignore [unbound-name] + new_input_node.meta.update(new_input_anchor.meta) + # pyrefly: ignore [unbound-name] + new_input_anchor.replace_all_uses_with(new_input_node) + # pyrefly: ignore [unbound-name] + new_graph.erase_node(new_input_anchor) + # add the output node + # pyrefly: ignore [unbound-name] + new_output_node = new_graph.output(new_output_anchor) + # pyrefly: ignore [unbound-name] + new_output_node.meta.update(new_output_anchor.meta) + else: # subgraph is trivial, e.g. (A @ (B @ C)) + # update the input node + # pyrefly: ignore [unbound-name] + with new_graph.inserting_before(new_input_anchor): + new_input_node = new_graph.placeholder(name="subgraph_input") + # pyrefly: ignore [unbound-name] + new_input_node.meta.update(new_input_anchor.meta) + # pyrefly: ignore [unbound-name] + new_input_anchor.replace_all_uses_with(new_input_node) + # pyrefly: ignore [unbound-name] + new_graph.erase_node(new_input_anchor) + # update the output node (don't use new_output_anchor since it has been erased) + new_output_node = new_graph.output(new_input_node) + new_output_node.meta.update(new_input_node.meta) + new_graph.lint() + + # construct the subgraph + subgraph = Subgraph( + name="subgraph", graph_module=torch.fx.GraphModule(module, new_graph) + ) + + # two cases + # (1) (subgraph(A @ B) @ C), called "left_assoc" + # (2) (A @ subgraph(B @ C)), called "right_assoc" + is_left_assoc = outer_mm.args[0] is f_node + + # find the nodes A, B, C and check the sizes + A: torch.fx.Node + B: torch.fx.Node + C: torch.fx.Node + if is_left_assoc: + A = inner_mm.args[0] # type: ignore[assignment] + B = inner_mm.args[1] # type: ignore[assignment] + C = outer_mm.args[1] # type: ignore[assignment] + else: + A = outer_mm.args[0] # type: ignore[assignment] + B = inner_mm.args[0] # type: ignore[assignment] + C = inner_mm.args[1] # type: ignore[assignment] + if not is_b2b_gemm_good_on(is_left_assoc, A, B, C): + return + + # finally update the original graph + counters["inductor"]["b2b_gemm"] += 1 + graph = match.graph + with graph.inserting_before(outer_mm): + function = functools.partial(tuned_b2b_gemm, is_left_assoc, subgraph) + function.__name__ = tuned_b2b_gemm.__name__ # type: ignore[attr-defined] + function._inductor_lowering_function = True # type: ignore[attr-defined] + function._inductor_lowering_output_metadata_ignores_input_storage = True # type: ignore[attr-defined] + replacement: torch.fx.Node = graph.call_function( + function, + (A, B, C), + match.kwargs, + ) + replacement.meta.update(outer_mm.meta) + outer_mm.replace_all_uses_with(replacement) + # erase unnecessary nodes + graph.erase_node(outer_mm) + for node in reversed(subgraph_node_list): + graph.erase_node(node) + graph.lint() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/binary_folding.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/binary_folding.py new file mode 100644 index 0000000000000000000000000000000000000000..e2bd5da94bda2c0f9a49005640db6e970258f3c1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/binary_folding.py @@ -0,0 +1,520 @@ +# mypy: allow-untyped-defs +import functools +import itertools + +import torch + +from ..._dynamo.utils import counters +from .. import config +from ..pattern_matcher import Arg, CallFunction, KeywordArg +from .freezing_patterns import register_binary_folding_pattern + + +aten = torch.ops.aten +prims = torch.ops.prims + + +def mark_mixed_dtype(computation_node): + computation_node_dtype = computation_node.meta["val"].dtype + if computation_node_dtype not in (torch.float16, torch.bfloat16): + return + + if len(computation_node.users) != 1: + return + + computation_node_user = next(iter(computation_node.users.keys())) + if not isinstance(computation_node_user.meta["val"], torch.Tensor): + return + + if computation_node_user.meta["val"].dtype != torch.float32: + return + + while computation_node_user.target in _binary_ops: + if len(computation_node_user.users) != 1: + return + + computation_node_user = next(iter(computation_node_user.users.keys())) + + if computation_node_user.target != prims.convert_element_type.default: + return + + computation_node.meta["_allow_mixed_dtype_folding"] = computation_node_dtype + + +def mark_mixed_dtype_allowed_computation_ops(gm): + """ + Mark convolutions/linear which we will binary fold even with mixed precision constants. We constant fold in the higher precision + for better accuracy and then recover the original precision after. + """ + for target in [aten.convolution.default, aten.addmm.default, aten.mm.default]: + for node in gm.graph.find_nodes(op="call_function", target=target): + mark_mixed_dtype(node) + + +def recover_original_precision_folded_computation_ops(gm): + """ + After binary folding conv/linear weights and biases to a higher dtype, recover the original precision they were in. + """ + graph = gm.graph + for target, idx in ( + (aten.convolution.default, (1, 2)), + (aten.addmm.default, (0, 2)), + (aten.mm.default, (1,)), + ): + for node in graph.find_nodes(op="call_function", target=target): + orig_dtype = node.meta.get("_allow_mixed_dtype_folding", None) + if orig_dtype is None: + continue + + with graph.inserting_before(node): + for i in idx: + old_input = node.args[i] + if old_input is None: + continue + + new_input = graph.create_node( + "call_function", + prims.convert_element_type.default, + (old_input, orig_dtype), + ) + node.replace_input_with(old_input, new_input) + + +_binary_ops = [aten.add.Tensor, aten.sub.Tensor, aten.mul.Tensor, aten.div.Tensor] + + +@functools.cache +def binary_folding_init(): + _conv_args = [Arg() for _ in range(9)] + _addmm_args = [Arg() for _ in range(3)] + _mm_args = [Arg() for _ in range(2)] + _computation_ops = [aten.convolution.default, aten.addmm.default, aten.mm.default] + _computation_calls = [ + CallFunction(aten.convolution.default, *_conv_args, _users=1), + CallFunction(aten.addmm.default, *_addmm_args, _users=1), + CallFunction( + aten.reshape.default, + CallFunction(aten.addmm.default, *_addmm_args, _users=1), + Arg(), + _users=1, + ), + CallFunction(aten.mm.default, *_mm_args, _users=1), + CallFunction( + aten.reshape.default, + CallFunction(aten.mm.default, *_mm_args, _users=1), + Arg(), + _users=1, + ), + ] + + """ + In order to fuse add/sub/mul/div with conv/linear, the dimensions of its + constant tensor must satisfy the following: + - with resizing, broadcast to w/ weight/bias tensor shape + - broadcast to the conv/linear output shape + It needs to have a shape that can resize to weight/bias + tensor shape because we need to run the op with the conv/linear + weights/bias without changing their sizes. + It needs to broadcast to the conv/linear output shape so that we do + accidentally change the shape of op output by pre-fusing it + compared to eager. + The only dimension value shared by weight, bias, and conv/linear output + is they all contain a dim with value = channels-out. In the + conv/linear output tensor, this is in the second dimension, + so the pointwise op tensor may have a second dimension of + value == channels-out, but all the other dimensions have to be 1 + """ + + def _op_not_broadcasting_with_conv(weight_tensor, other_tensor): + # According to opDoesNotBroadCastWithConv of frozen_conv_folding.cpp + weight_shape = weight_tensor.shape + other_shape = other_tensor.shape + if len(weight_shape) < len(other_shape): + return False + if len(weight_shape) == len(other_shape) + 1: + # weight shape is [o, i, *], other_shape is [o, 1...]. + for i in reversed(range(len(other_shape))): + if i == 0 and weight_shape[0] == other_shape[i]: + continue + if other_shape[i] != 1: + return False + else: + # weight shape is [o, i, *], other_shape is [1, i, *] + for i in reversed(range(len(other_shape))): + if i == 1 and weight_shape[0] == other_shape[i]: + continue + if other_shape[i] != 1: + return False + return True + + def _op_not_broadcasting_with_linear(weight_tensor, other_tensor, has_reshape): + weight_shape = weight_tensor.shape + other_shape = other_tensor.shape + other_shapes = [ + torch.Size( + [ + weight_shape[1], + ] + ), + torch.Size([1, weight_shape[1]]), + torch.Size( + [ + 1, + ] + ), + torch.Size([1, 1]), + ] + if has_reshape: + other_shapes.extend( + [ + torch.Size([1, 1, weight_shape[1]]), + torch.Size([1, 1, 1]), + ] + ) + return other_shape in other_shapes + + def _check_conv_and_broadcast_op(conv_node, other): + # According to checkConvAndBroadcastingOpPreConditions of frozen_conv_folding.cpp. + # conv.weight + if conv_node.args[1].op != "get_attr": + return False + # conv.bias + bias_node = conv_node.args[2] + if bias_node is not None and bias_node.op != "get_attr": + return False + if ( + not isinstance(other, int) + and not isinstance(other, float) + and other.op != "get_attr" + ): + return False + + if len(conv_node.args[1].users) != 1: + return False + + weight_meta_value = conv_node.args[1].meta.get("val") + if weight_meta_value is None: + return False + # Avoid fusing op that causes type promotion + # restricting to float avoids int/float difficulties with scalar overload + if not weight_meta_value.is_floating_point(): + return False + if isinstance(other, torch.fx.Node) and other.op == "get_attr": + other_meta_value = other.meta.get("val") + if not other_meta_value.is_floating_point(): # type: ignore[union-attr] + return False + if ( + torch.promote_types(other_meta_value.dtype, weight_meta_value.dtype) # type: ignore[union-attr] + != weight_meta_value.dtype + ): + if not conv_node.meta.get("_allow_mixed_dtype_folding", False): + return False + + if ( + other_meta_value.dtype != torch.float # type: ignore[union-attr] + and weight_meta_value.dtype not in (torch.float16, torch.bfloat16) + ): + return False + + if not _op_not_broadcasting_with_conv(weight_meta_value, other_meta_value): + return False + elif not isinstance(other, float): + return False + + return True + + def _check_linear_and_broadcast_op(linear_node, other, has_reshape): + weight_node = ( + linear_node.args[2] + if linear_node.target is aten.addmm.default + else linear_node.args[1] + ) + bias_node = ( + linear_node.args[0] if linear_node.target is aten.addmm.default else None + ) + if weight_node.op != "get_attr": + return False + if bias_node is not None and bias_node.op != "get_attr": + return False + if ( + not isinstance(other, int) + and not isinstance(other, float) + and other.op != "get_attr" + ): + return False + + if len(weight_node.users) != 1: + return False + + weight_meta_value = weight_node.meta.get("val") + if weight_meta_value is None: + return False + # Avoid fusing op that causes type promotion + # restricting to float avoids int/float difficulties with scalar overload + if not weight_meta_value.is_floating_point(): + return False + if isinstance(other, torch.fx.Node) and other.op == "get_attr": + other_meta_value = other.meta.get("val") + if not other_meta_value.is_floating_point(): # type: ignore[union-attr] + return False + if ( + torch.promote_types(other_meta_value.dtype, weight_meta_value.dtype) # type: ignore[union-attr] + != weight_meta_value.dtype + ): + if not linear_node.meta.get("_allow_mixed_dtype_folding", False): + return False + + if ( + other_meta_value.dtype != torch.float # type: ignore[union-attr] + and weight_meta_value.dtype not in (torch.float16, torch.bfloat16) + ): + return False + + if not _op_not_broadcasting_with_linear( + weight_meta_value, other_meta_value, has_reshape + ): + return False + elif not isinstance(other, float): + return False + + return True + + def _is_foldable_pattern(match): + binary_node = match.output_node() + has_reshape = False + if binary_node.args[0].target in _computation_ops: + computation_node = binary_node.args[0] + other = binary_node.args[1] + elif binary_node.args[0].target is aten.reshape.default: + computation_node = binary_node.args[0].args[0] + other = binary_node.args[1] + has_reshape = True + elif binary_node.args[1].target in _computation_ops: + computation_node = binary_node.args[1] + other = binary_node.args[0] + else: + computation_node = binary_node.args[1].args[0] + other = binary_node.args[0] + has_reshape = False + if computation_node.target is aten.convolution.default: + return _check_conv_and_broadcast_op(computation_node, other) + elif computation_node.target in [aten.addmm.default, aten.mm.default]: + return ( + config.enable_linear_binary_folding + and _check_linear_and_broadcast_op(computation_node, other, has_reshape) + ) + + return False + + def resize_scalar_or_tensor_to_shape(graph, other, shape, weight): + if isinstance(other, float): + with torch.utils._python_dispatch._disable_current_modes(): + other_tensor = torch.tensor( + other, dtype=weight.dtype, device=weight.device + ) + graph.owning_module.register_buffer("other_tensor", other_tensor) + res = graph.create_node("get_attr", "other_tensor") + res = graph.create_node( + "call_function", + aten.reshape.default, + (res, (1,)), + ) + res = graph.create_node( + "call_function", + aten.expand.default, + (res, shape), + ) + elif other.meta.get("val").numel() == 1: + # expand errors if the shape input has less # dims than the tensor input + res = graph.create_node( + "call_function", + aten.reshape.default, + (other, (1,)), + ) + res = graph.create_node( + "call_function", + aten.expand.default, + (res, shape), + ) + else: + res = graph.create_node( + "call_function", + aten.reshape.default, + (other, shape), + ) + return res + + def _create_new_conv_node(graph, conv_node, binary_node, other): + if conv_node.target is not aten.convolution.default: + raise AssertionError( + f"expected aten.convolution.default, got {conv_node.target}" + ) + conv_args = list(conv_node.args) + weight_meta_value = conv_node.args[1].meta.get("val") + bias = conv_args[2] + if binary_node.target in [aten.add.Tensor, aten.sub.Tensor]: + other_reshape = resize_scalar_or_tensor_to_shape( + graph, + other, + (weight_meta_value.size(0),), + weight_meta_value, + ) + new_bias = graph.create_node( + "call_function", + binary_node.target, + (0 if bias is None else bias, other_reshape), + ) + conv_args[2] = new_bias + else: + if binary_node.target not in [aten.mul.Tensor, aten.div.Tensor]: + raise AssertionError( + f"expected mul or div binary node, got {binary_node.target}" + ) + weight_broadcast_shape = [1 for _ in range(len(weight_meta_value.shape))] + weight_broadcast_shape[0] = weight_meta_value.size(0) + other_reshape1 = resize_scalar_or_tensor_to_shape( + graph, + other, + tuple(weight_broadcast_shape), + weight_meta_value, + ) + new_weight = graph.create_node( + "call_function", binary_node.target, (conv_args[1], other_reshape1) + ) + new_weight.meta.update(conv_args[1].meta) + conv_args[1] = new_weight + if bias is not None: + other_reshape = resize_scalar_or_tensor_to_shape( + graph, + other, + (weight_meta_value.size(0),), + weight_meta_value, + ) + new_bias = graph.create_node( + "call_function", binary_node.target, (bias, other_reshape) + ) + new_bias.meta.update(bias.meta) + conv_args[2] = new_bias + return graph.create_node("call_function", conv_node.target, tuple(conv_args)) + + def _create_new_linear_node(graph, linear_node, binary_node, other): + if linear_node.target not in [aten.addmm.default, aten.mm.default]: + raise AssertionError(f"expected addmm or mm, got {linear_node.target}") + input_node = ( + linear_node.args[1] + if linear_node.target is aten.addmm.default + else linear_node.args[0] + ) + weight_node = ( + linear_node.args[2] + if linear_node.target is aten.addmm.default + else linear_node.args[1] + ) + bias_node = ( + linear_node.args[0] if linear_node.target is aten.addmm.default else None + ) + weight_meta_value = weight_node.meta.get("val") + if binary_node.target in [aten.add.Tensor, aten.sub.Tensor]: + other_reshape = resize_scalar_or_tensor_to_shape( + graph, + other, + (weight_meta_value.size(1),), + weight_meta_value, + ) + new_bias_node = graph.create_node( + "call_function", + binary_node.target, + (0 if bias_node is None else bias_node, other_reshape), + ) + return graph.create_node( + "call_function", + aten.addmm.default, + (new_bias_node, input_node, weight_node), + ) + else: + if binary_node.target not in [aten.mul.Tensor, aten.div.Tensor]: + raise AssertionError( + f"expected mul or div binary node, got {binary_node.target}" + ) + weight_broadcast_shape = [1, weight_meta_value.size(1)] + other_reshape1 = resize_scalar_or_tensor_to_shape( + graph, + other, + tuple(weight_broadcast_shape), + weight_meta_value, + ) + new_weight_node = graph.create_node( + "call_function", binary_node.target, (weight_node, other_reshape1) + ) + new_weight_node.meta.update(weight_node.meta) + if bias_node is not None: + other_reshape = resize_scalar_or_tensor_to_shape( + graph, + other, + (weight_meta_value.size(1),), + weight_meta_value, + ) + new_bias_node = graph.create_node( + "call_function", binary_node.target, (bias_node, other_reshape) + ) + new_bias_node.meta.update(bias_node.meta) + return graph.create_node( + "call_function", + linear_node.target, + (new_bias_node, input_node, new_weight_node), + ) + else: + return graph.create_node( + "call_function", linear_node.target, (input_node, new_weight_node) + ) + + for _computation_call, binary_op in itertools.product( + _computation_calls, _binary_ops + ): + + @register_binary_folding_pattern( + CallFunction(binary_op, _computation_call, KeywordArg("other")), + extra_check=_is_foldable_pattern, + ) + def folded_op(match, *args, **kwargs): + counters["inductor"]["binary_folding"] += 1 + other = kwargs.get("other") + binary_node = match.output_node() + reshape_node = None + if binary_node.args[0].target in _computation_ops: + computation_node = binary_node.args[0] + elif binary_node.args[0].target is aten.reshape.default: + computation_node = binary_node.args[0].args[0] + reshape_node = binary_node.args[0] + elif binary_node.args[1].target in _computation_ops: + computation_node = binary_node.args[1] + else: + computation_node = binary_node.args[1].args[0] + reshape_node = binary_node.args[1] + graph = match.graph + with graph.inserting_before(reshape_node if reshape_node else binary_node): + if computation_node.target not in _computation_ops: + raise AssertionError( + f"expected a computation op, got {computation_node.target}" + ) + if computation_node.target is aten.convolution.default: + counters["inductor"]["binary_folding_conv"] += 1 + new_computation_node = _create_new_conv_node( + graph, computation_node, binary_node, other + ) + else: + new_computation_node = _create_new_linear_node( + graph, computation_node, binary_node, other + ) + new_computation_node.meta.update(computation_node.meta) + if reshape_node: + if reshape_node.target is not aten.reshape.default: + raise AssertionError( + f"expected aten.reshape.default, got {reshape_node.target}" + ) + computation_node.replace_all_uses_with(new_computation_node) + binary_node.replace_all_uses_with(reshape_node) + else: + binary_node.replace_all_uses_with(new_computation_node) + graph.erase_node(binary_node) + graph.erase_node(computation_node) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/bucketing.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/bucketing.py new file mode 100644 index 0000000000000000000000000000000000000000..fd188e1c3c8da923b16f2e63f2c44fc71aad37aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/bucketing.py @@ -0,0 +1,1628 @@ +import collections +import contextlib +import logging +import operator +from collections import defaultdict +from collections.abc import Callable +from typing import Any, Literal, TYPE_CHECKING, TypeAlias + +import sympy + +import torch +import torch.distributed as dist +import torch.utils._pytree as pytree +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.utils import detect_fake_mode +from torch._inductor.comm_analysis import ( + get_collective_type_from_kernel_name, + NCCL_COLL, +) +from torch._inductor.fx_passes.utils import BitsetAncestors +from torch._inductor.runtime.runtime_utils import dynamo_timed +from torch._logging import trace_structured +from torch.fx.experimental.proxy_tensor import make_fx +from torch.fx.traceback import NodeSource, NodeSourceAction +from torch.utils._ordered_set import OrderedSet + + +if TYPE_CHECKING: + from torch.distributed.distributed_c10d import GroupName + + +logger: logging.Logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +overlap_log = torch._logging.getArtifactLogger(__name__, "overlap") + + +def _resolve_group_name(group_name: Any) -> "GroupName": + """Resolve group_name to a GroupName string. + + In compile-on-one-rank graphs, collective ops receive their + group_name argument as an FX Node reference (pointing to a + mesh_get_process_group call) rather than a string literal. For + bucketing key purposes we resolve via the ProcessGroup stored in + node.meta["val"]. + """ + if isinstance(group_name, str): + return group_name # pyrefly: ignore [bad-return] + pg = group_name.meta["val"] + return pg.group_name + + +BucketMode: TypeAlias = Literal[ + "default", "custom_ops", "custom_ops_multidtype", "coalesced" +] + + +def _default_bucket_mode() -> BucketMode: + from torch._inductor import config + + return config.aten_distributed_optimizations.bucket_mode or "default" + + +# Helper functions moved to top for better organization +def _ag_group_key(node: torch.fx.Node) -> tuple[str, torch.dtype]: # type: ignore[name-defined] + _, group_size, group_name = node.args + dtype = node.meta["val"].dtype + return (_resolve_group_name(group_name), dtype) + + +def _ag_group_key_multidtype(node: torch.fx.Node) -> tuple[str]: + _, group_size, group_name = node.args + return (_resolve_group_name(group_name),) + + +def _rs_group_key(node: torch.fx.Node) -> tuple[str, str, torch.dtype]: # type: ignore[name-defined] + _, reduce_op, group_size, group_name = node.args + dtype = node.meta["val"].dtype + if not isinstance(reduce_op, str): + raise AssertionError(f"expected reduce_op to be str, got {type(reduce_op)}") + return (_resolve_group_name(group_name), reduce_op, dtype) + + +def _ar_group_key(node: torch.fx.Node) -> tuple[str, str, torch.dtype]: + _, reduce_op, group_name = node.args + dtype = node.meta["val"].dtype + if not isinstance(reduce_op, str): + raise AssertionError(f"expected reduce_op to be str, got {type(reduce_op)}") + return (_resolve_group_name(group_name), reduce_op, dtype) + + +def _compute_foreach_groups( + ag_ins: list[torch.Tensor], + out_dtypes: list[torch.dtype], # type: ignore[name-defined] +) -> list[int] | None: + """ + Compute groups of indices that have the same src/dst dtype and shape. + + Groups tensors by (src_dtype, dst_dtype, shape) to avoid falling back to the foreach slow path. + + Returns a flat list with -1 as group delimiter, or None if only one group exists. + For example, groups [[0, 2], [1]] would be encoded as [0, 2, -1, 1]. + """ + groups: defaultdict[tuple[torch.dtype, torch.dtype, tuple[int, ...]], list[int]] = ( + defaultdict(list) + ) + for i, (ag_in, out_dtype) in enumerate(zip(ag_ins, out_dtypes)): + shape = tuple( + _hint_int_or_raise(s, context="all-gather foreach grouping") + for s in ag_in.shape + ) + key = (ag_in.dtype, out_dtype, shape) + groups[key].append(i) + + if len(groups) <= 1: + return None + + # Encode as flat list with -1 as delimiter + result: list[int] = [] + for i, group_indices in enumerate(groups.values()): + result.extend(group_indices) + if i < len(groups) - 1: + result.append(-1) + + return result + + +# Bucketing has two separate shape contracts: +# +# 1. Semantic tensor shapes stay symbolic. The traced bucket merge graph must +# preserve runtime tensor expressions such as numel(), split sizes, +# torch.empty extents, narrow offsets/lengths, and reshape shapes. Those +# values describe actual tensor semantics and must not be specialized from +# optimization hints. +# +# 2. Optimization-policy choices may use hints. Bucket byte accounting and +# foreach grouping need Python integers to decide how to group collectives. +# For those policy-only decisions, concrete ints, backed SymInts, hinted +# unbacked SymInts, and derived expressions from hinted symbols are valid. +# Unhinted symbolic values fail fast instead of forcing guards or guessing. +# +# In short: hints may decide which bucket/group we choose, but they must never +# replace symbolic sizes in the graph we trace for the bucketed collective. +def _hint_int_or_raise(value: object, *, context: str) -> int: + if type(value) is int: + return value + + if not isinstance(value, torch.SymInt): + raise AssertionError(f"Expected int or SymInt for {context}, got {type(value)}") + + node = value.node + if node._hint is not None: + return int(node._hint) + shape_env = node.shape_env + if shape_env is None: + raise AssertionError(f"ShapeEnv is required to hint {context}: {value}") + + expr = sympy.sympify(node.expr).xreplace(shape_env.replacements) + expr = expr.xreplace(shape_env.backed_var_to_val) + expr = expr.xreplace(shape_env.var_to_hint_override) + if isinstance(expr, sympy.Expr): + expr = expr.expand(identity=True) + if getattr(expr, "free_symbols", None): + raise RuntimeError( + f"Could not extract optimization hint for {context}: {value}. " + "Collective bucketing requires hinted symbolic sizes for policy " + "decisions." + ) + return int(expr) + + +def _numel_hint_or_raise(tensor: torch.Tensor, *, context: str) -> int: + return _hint_int_or_raise(tensor.numel(), context=context) + + +def _size_bytes_hint_or_raise( + tensor: torch.Tensor, + *, + dtype: torch.dtype | None = None, + context: str, +) -> int: + element_size = tensor.element_size() if dtype is None else dtype.itemsize + return _numel_hint_or_raise(tensor, context=context) * element_size + + +def _get_collective_node_from_wait(node: torch.fx.Node) -> torch.fx.Node | None: + """Given a wait node, return the collective it waits on. + + Handles both standard (wait -> collective) and coalesced + (wait -> getitem -> coalesced_collective) patterns. + Returns None if the node is not a wait on a recognized NCCL collective. + """ + if not is_wait_tensor(node): + return None + arg = node.args[0] + if not isinstance(arg, torch.fx.Node): + raise AssertionError(f"expected arg to be a Node, got {type(arg)}") + if arg.op != "call_function": + return None + if arg.target is operator.getitem: + if not isinstance(arg.args[0], torch.fx.Node): + raise AssertionError( + f"expected arg.args[0] to be a Node, got {type(arg.args[0])}" + ) + arg = arg.args[0] + if arg.op != "call_function": + return None + if not isinstance(arg.target, Callable): + return None + # pyrefly: ignore [missing-attribute] + coll: NCCL_COLL = get_collective_type_from_kernel_name(arg.target.name()) + if coll == NCCL_COLL.UNSUPPORTED: + return None + return arg + + +def _schedulable_wait_node(node: torch.fx.Node) -> bool: + """Check if this wait node is schedulable (waits on a recognized NCCL collective).""" + return _get_collective_node_from_wait(node) is not None + + +def _populate_node_meta( + bucket_nodes: list[torch.fx.Node], new_nodes: list[torch.fx.Node] +): + if bucket_nodes: + for n in new_nodes: + # For the following keys, we only store the information of the first node so + # gm.print_readable shows some information + # Full information is stored in "bucketing_{key}_sources" + for key, default in [ + ("nn_module_stack", ""), + ("fwd_nn_module_stack", ""), + ("stack_trace", ""), + ("custom", {}), + ]: + n.meta[key] = bucket_nodes[0].meta.get(key, default) + + # Collect sources from all bucket nodes for this metadata key, for debugging purposes only + bucketing_sources_key = f"bucketing_{key}_sources" + # Use set to remove duplicates + if key == "stack_trace": + sources = OrderedSet( + [ + node.meta.get(key, default) + for node in bucket_nodes + if node.meta.get(key, default) + ] + ) + else: + # type might not be hashable + sources = [ + node.meta.get(key, default) + for node in bucket_nodes + if node.meta.get(key, default) + ] + n.meta[bucketing_sources_key] = sources + + # used by inductor provenance tracking + n.meta["from_node"] = [ + NodeSource( + original_node, + "bucketing_pass", + [NodeSourceAction.CREATE, NodeSourceAction.REPLACE], + ) + for original_node in bucket_nodes + ] + + +def _meta_arg(arg: object) -> object: + if isinstance(arg, torch.fx.Node): + return arg.meta.get("val", arg) + return arg + + +def _same_tensor_metadata(lhs: torch.Tensor, rhs: torch.Tensor) -> bool: + def same_dim(lhs_dim: object, rhs_dim: object) -> bool: + from torch.fx.experimental.symbolic_shapes import statically_known_true + + try: + return statically_known_true(lhs_dim == rhs_dim) + except Exception: + return lhs_dim == rhs_dim + + def same_dims(lhs_dims: tuple[object, ...], rhs_dims: tuple[object, ...]) -> bool: + return len(lhs_dims) == len(rhs_dims) and all( + same_dim(lhs_dim, rhs_dim) for lhs_dim, rhs_dim in zip(lhs_dims, rhs_dims) + ) + + return ( + lhs.dtype == rhs.dtype + and lhs.device == rhs.device + and lhs.layout == rhs.layout + and same_dims(tuple(lhs.shape), tuple(rhs.shape)) + and same_dims(tuple(lhs.stride()), tuple(rhs.stride())) + and same_dim(lhs.storage_offset(), rhs.storage_offset()) + ) + + +def _same_metadata(lhs: object, rhs: object) -> bool: + lhs_leaves, lhs_spec = pytree.tree_flatten(lhs) + rhs_leaves, rhs_spec = pytree.tree_flatten(rhs) + if lhs_spec != rhs_spec or len(lhs_leaves) != len(rhs_leaves): + return False + for lhs_leaf, rhs_leaf in zip(lhs_leaves, rhs_leaves): + if isinstance(lhs_leaf, torch.Tensor) or isinstance(rhs_leaf, torch.Tensor): + if not isinstance(lhs_leaf, torch.Tensor) or not isinstance( + rhs_leaf, torch.Tensor + ): + return False + if not _same_tensor_metadata(lhs_leaf, rhs_leaf): + return False + return True + + +def _recompute_changed_user_metadata(start_users: list[torch.fx.Node]) -> None: + """ + Repair fake metadata after bucketing replaces a value with a layout-different + equivalent. The replacement is semantically valid, but downstream stride + metadata is no longer valid until consumers are re-run from metadata. + """ + worklist = collections.deque(start_users) + queued: OrderedSet[torch.fx.Node] = OrderedSet(start_users) + while worklist: + node = worklist.popleft() + queued.discard(node) + if node.op != "call_function" or not callable(node.target): + continue + if "val" not in node.meta: + continue + + args = pytree.tree_map(_meta_arg, node.args) + kwargs = pytree.tree_map(_meta_arg, node.kwargs) + if any( + isinstance(leaf, torch.fx.Node) + for leaf in pytree.tree_leaves((args, kwargs)) + ): + continue + + fake_mode = detect_fake_mode((node.meta.get("val"), args, kwargs)) + try: + with fake_mode if fake_mode is not None else contextlib.nullcontext(): + new_val = node.target(*args, **kwargs) + except Exception: + logger.debug( + "Skipping metadata repair for bucketing user %s", + node.name, + exc_info=True, + ) + continue + + if _same_metadata(node.meta["val"], new_val): + continue + + node.meta["val"] = new_val + for user in node.users: + if user not in queued: + queued.add(user) + worklist.append(user) + + +def bucket_key(node: torch.fx.Node, mode: BucketMode | None = None) -> object | None: + if is_all_gather_into_tensor(node): + group_key_fn = ( + _ag_group_key_multidtype if mode and "multidtype" in mode else _ag_group_key + ) + return group_key_fn(node) + elif is_reduce_scatter_tensor(node): + return _rs_group_key(node) + elif is_all_reduce_tensor(node): + return _ar_group_key(node) + else: + return None + + +def pick_bucket_dtype(dtypes: list[torch.dtype]) -> torch.dtype: # type: ignore[name-defined] + if len(dtypes) == 0: + raise AssertionError("expected at least one dtype, got empty list") + return min(dtypes, key=operator.attrgetter("itemsize")) + + +def bucket_cap_mb_by_bucket_idx_default(bucket_id: int) -> float: + """ + Determine the size of a bucket based on its ID. + + Args: + bucket_id (int): The ID of the bucket. + + Returns: + float: The size of the bucket. + """ + return 2000.0 + + +def bucket_all_gather( + gm: torch.fx.GraphModule, + bucket_cap_mb_by_bucket_idx: Callable[[int], float] | None = None, + mode: BucketMode | None = None, +) -> None: + mode = mode or _default_bucket_mode() + if bucket_cap_mb_by_bucket_idx is None: + from torch._inductor.fx_passes.bucketing import ( + bucket_cap_mb_by_bucket_idx_default, # pyrefly: ignore [missing-module-attribute] + ) + + bucket_cap_mb_by_bucket_idx = bucket_cap_mb_by_bucket_idx_default + ag_buckets = bucket_all_gather_by_mb(gm, bucket_cap_mb_by_bucket_idx, None, mode) + if len(ag_buckets) == 0: + return + merge_all_gather(gm, ag_buckets, mode) + + +def bucket_reduce_scatter( + gm: torch.fx.GraphModule, + bucket_cap_mb_by_bucket_idx: Callable[[int], float] | None = None, + mode: BucketMode | None = None, +) -> None: + mode = mode or _default_bucket_mode() + if bucket_cap_mb_by_bucket_idx is None: + from torch._inductor.fx_passes.bucketing import ( + bucket_cap_mb_by_bucket_idx_default, # pyrefly: ignore [missing-module-attribute] + ) + + bucket_cap_mb_by_bucket_idx = bucket_cap_mb_by_bucket_idx_default + rs_buckets = bucket_reduce_scatter_by_mb( + gm, bucket_cap_mb_by_bucket_idx, None, mode + ) + if len(rs_buckets) == 0: + return + merge_reduce_scatter(gm, rs_buckets, mode) + + +def is_all_gather_into_tensor(node: torch.fx.Node) -> bool: # type: ignore[arg-type] + return node.op == "call_function" and ( + node.target == torch.ops._c10d_functional.all_gather_into_tensor.default + or node.target == torch.ops._c10d_functional.all_gather_into_tensor_out.default + ) + + +def is_reduce_scatter_tensor(node: torch.fx.Node) -> bool: + return ( + node.op == "call_function" + and node.target is torch.ops._c10d_functional.reduce_scatter_tensor.default + ) + + +def is_wait_tensor(node: torch.fx.Node) -> bool: + return ( + node.op == "call_function" + and node.target is torch.ops._c10d_functional.wait_tensor.default + ) + + +def is_all_reduce_tensor(node: torch.fx.Node) -> bool: + return ( + node.op == "call_function" + and node.target is torch.ops._c10d_functional.all_reduce.default + ) + + +def is_all_to_all_tensor(node: torch.fx.Node) -> bool: + return ( + node.op == "call_function" + and node.target is torch.ops._c10d_functional.all_to_all_single.default + ) + + +def get_collective_type(node: torch.fx.Node) -> str: + """Get the collective type name for a node.""" + if is_all_gather_into_tensor(node): + return "all_gather" + elif is_reduce_scatter_tensor(node): + return "reduce_scatter" + elif is_all_reduce_tensor(node): + return "all_reduce" + return "" + + +def get_full_bucket_key( + node: torch.fx.Node, bucket_mode: BucketMode | None +) -> tuple[str, Any]: + """Get the full bucket key including collective type and bucket key.""" + return (get_collective_type(node), bucket_key(node, mode=bucket_mode)) + + +def is_wait_tensor_from_all_gather_into_tensor(node: torch.fx.Node) -> bool: + return is_wait_tensor(node) and is_all_gather_into_tensor(node.args[0]) # type: ignore[arg-type] + + +def is_fsdp_all_gather( + node: torch.fx.Node, + all_node_ancestors: BitsetAncestors | None = None, +) -> bool: + """Check if an all_gather derives from exactly one placeholder (parameter). + + When all_node_ancestors is provided, uses it for O(|ancestors|) lookup. + Otherwise delegates to the BFS implementation in fsdp.py. + """ + if not is_all_gather_into_tensor(node): + return False + if all_node_ancestors is not None: + phs = ( + a for a in all_node_ancestors.iter_ancestors(node) if a.op == "placeholder" + ) + return next(phs, None) is not None and next(phs, None) is None + from torch._inductor.fx_passes.fsdp import is_fsdp_all_gather as _is_fsdp_all_gather + + return _is_fsdp_all_gather(node) + + +def is_fsdp_reduce_scatter(node: torch.fx.Node) -> bool: + """ + Check if a reduce_scatter node is FSDP-related by verifying its output flows + directly to graph outputs through only unary ops (e.g., to_copy, wait). + """ + if not is_reduce_scatter_tensor(node): + return False + + visited: OrderedSet[torch.fx.Node] = OrderedSet() + stack = [node] + + while stack: + curr = stack.pop() + if curr in visited: + continue + visited.add(curr) + + for user in curr.users: + if user.op == "output": + continue + # Non-unary op means computation with external data + if len(user.all_input_nodes) != 1: + return False + stack.append(user) + + return True + + +def collect_node_descendants( + graph: torch.fx.Graph, +) -> dict[torch.fx.Node, OrderedSet[torch.fx.Node]]: + """ + Collects the descendants of each node in the graph. + Args: + graph (torch.fx.Graph): The graph to collect descendants from. + Returns: + dict[torch.fx.Node, OrderedSet[torch.fx.Node]]: A dictionary mapping each node to its descendants. + """ + node_descendants: dict[torch.fx.Node, OrderedSet[torch.fx.Node]] = ( + collections.defaultdict(OrderedSet) + ) + outdegree = collections.defaultdict(int) + queue = [] + + for node in graph.nodes: + n_outdegree = len(node.users) + if n_outdegree == 0: + queue.append(node) + else: + outdegree[node] = len(node.users) + + while queue: + node = queue.pop() + for input_node in node.all_input_nodes: + node_descendants[input_node] |= node_descendants[node] + node_descendants[input_node].add(node) + outdegree[input_node] -= 1 + + if outdegree[input_node] == 0: + queue.append(input_node) + + return node_descendants + + +def greedy_bucket_collective_by_mb( + gm: torch.fx.GraphModule, + bucket_cap_mb_by_bucket_idx: Callable[[int], float], + filter_node: Callable[[torch.fx.Node], bool], + node_group_key: Callable[[torch.fx.Node], Any], + filter_wait_node: Callable[[torch.fx.Node], bool] | None = None, +) -> list[list[torch.fx.Node]]: + """ + Bucketing adjacent collectives with equal node_group_key. + We can not bucket non adjacent collectives, + as this will effectively change the order of collectives. + Reordering can lead to different order on different ranks. + """ + g = gm.graph + found_candidates = False + for node in g.nodes: + if filter_node(node): + found_candidates = True + break + if not found_candidates: + return [] + + # Build forward adjacency list for incremental descendant tracking + children: dict[torch.fx.Node, list[torch.fx.Node]] = collections.defaultdict(list) + for node in g.nodes: + for inp in node._input_nodes: + children[inp].append(node) + + nodes_groups: list[list[torch.fx.Node]] = [] + cur_group: list[torch.fx.Node] = [] + cur_group_key = None + + for node in g.nodes: + if is_wait_tensor(node) and filter_node(node.args[0]): + if (filter_wait_node is None) or filter_wait_node(node): + coll_node = node.args[0] + group_key = node_group_key(coll_node) + if group_key == cur_group_key: + cur_group.append(coll_node) + else: + if len(cur_group) > 1: + nodes_groups.append(cur_group) + cur_group = [coll_node] + cur_group_key = group_key + + if len(cur_group) > 1: + nodes_groups.append(cur_group) + + def _add_descendants(node: torch.fx.Node, desc: OrderedSet[torch.fx.Node]) -> None: + """Forward BFS from node, adding all reachable nodes to desc.""" + stack = [node] + while stack: + n = stack.pop() + for child in children[n]: + if child not in desc: + desc.add(child) + stack.append(child) + + buckets: list[list[torch.fx.Node]] = [] + for nodes in nodes_groups: + cur_bucket: list[torch.fx.Node] = [] + cur_bucket_descendents: OrderedSet[torch.fx.Node] = OrderedSet() + cur_bucket_size_bytes: int = 0 + cur_bucket_id: int = 0 + bucket_size_bytes = int( + bucket_cap_mb_by_bucket_idx(cur_bucket_id) * 1024 * 1024 + ) + for node in nodes: + if node in cur_bucket_descendents: + # if there is a path from node to the current bucket, we cannot horizontally fuse (bucket) + continue + if "val" not in node.meta: + raise AssertionError(f"expected 'val' in node.meta for {node}") + n_val = node.meta["val"] + out_size_bytes = _size_bytes_hint_or_raise( + n_val, context="collective bucket output size" + ) + n_input_val = node.all_input_nodes[0].meta["val"] + in_size_bytes = _size_bytes_hint_or_raise( + n_input_val, context="collective bucket input size" + ) + size_bytes = max(out_size_bytes, in_size_bytes) + if cur_bucket_size_bytes + size_bytes > bucket_size_bytes and cur_bucket: + # Current bucket is full, create new bucket + if len(cur_bucket) > 1: + buckets.append(cur_bucket) + cur_bucket = [] + cur_bucket_size_bytes = 0 + cur_bucket_id += 1 + cur_bucket_descendents = OrderedSet() + cur_bucket_size_bytes += size_bytes + cur_bucket.append(node) + _add_descendants(node, cur_bucket_descendents) + if len(cur_bucket) > 1: + buckets.append(cur_bucket) + return buckets + + +def bucket_all_gather_by_mb( + gm: torch.fx.GraphModule, + bucket_cap_mb_by_bucket_idx: Callable[[int], float], + filter_wait_node: Callable[[torch.fx.Node], bool] | None = None, + mode: BucketMode | None = None, +) -> list[list[torch.fx.Node]]: + """ + Identifies all all_gather nodes and groups them into buckets, + based on size limit `bucket_cap_mb_by_bucket_idx`. + + Args: + gm (torch.fx.GraphModule): GraphModule where to bucket all_gathers. + bucket_cap_mb_by_bucket_idx (Callable[[int], float]): Callable to specify cap of the bucket + in megabytes by bucket idx. The idea of `bucket_cap_mb_by_bucket_idx` is to allow + to specify different sizes of the buckets at the start, + as first all_gather is usually exposed. Interface of bucket_cap_mb_by_bucket_idx + is `bucket_cap_mb_by_bucket_idx_default` function that is default value for `bucket_cap_mb_by_bucket_idx`. + filter_wait_node (Callable[[torch.fx.Node], bool] | None): If specified, + only all_gather nodes with wait_node that satisfy `filter_wait_node` will be bucketed. + + Returns: + list[list[torch.fx.Node]]: List of buckets, where each bucket is a list of all_gather nodes. + """ + mode = mode or _default_bucket_mode() + + group_key_fn = ( + _ag_group_key_multidtype if mode and "multidtype" in mode else _ag_group_key + ) + + return greedy_bucket_collective_by_mb( + gm, + bucket_cap_mb_by_bucket_idx, + is_all_gather_into_tensor, + group_key_fn, + filter_wait_node, + ) + + +def bucket_reduce_scatter_by_mb( + gm: torch.fx.GraphModule, + bucket_cap_mb_by_bucket_idx: Callable[[int], float], + filter_wait_node: Callable[[torch.fx.Node], bool] | None = None, + mode: BucketMode | None = None, +) -> list[list[torch.fx.Node]]: + """ + Identifies all reduce_scatter nodes and groups them into buckets, + based on size limit `bucket_cap_mb_by_bucket_idx`. + + Args: + gm (torch.fx.GraphModule): GraphModule where to bucket reduce_scatters. + bucket_cap_mb_by_bucket_idx (Callable[[int], float]): Callable to specify cap of the bucket + in megabytes by bucket idx. The idea of `bucket_cap_mb_by_bucket_idx` is to allow + to specify different sizes of the buckets. + filter_wait_node (Callable[[torch.fx.Node], bool] | None): If specified, + only reduce_scatter nodes with wait_node that satisfy `filter_wait_node` will be bucketed. + + Returns: + list[list[torch.fx.Node]]: List of buckets, where each bucket is a list of reduce_scatter nodes. + """ + mode = mode or _default_bucket_mode() + + if mode is not None and "multidtype" in mode: + raise AssertionError("reduce scatter bucketing does not support multidtype") + + return greedy_bucket_collective_by_mb( + gm, + bucket_cap_mb_by_bucket_idx, + is_reduce_scatter_tensor, + _rs_group_key, + filter_wait_node, + ) + + +def bucket_all_reduce_by_mb( + gm: torch.fx.GraphModule, + bucket_cap_mb_by_bucket_idx: Callable[[int], float], + filter_wait_node: Callable[[torch.fx.Node], bool] | None = None, +) -> list[list[torch.fx.Node]]: + return greedy_bucket_collective_by_mb( + gm, + bucket_cap_mb_by_bucket_idx, + is_all_reduce_tensor, + _ar_group_key, + filter_wait_node, + ) + + +def bucket_all_reduce( + gm: torch.fx.GraphModule, + bucket_cap_mb_by_bucket_idx: Callable[[int], float] | None = None, + mode: str | None = None, +) -> None: + if bucket_cap_mb_by_bucket_idx is None: + from torch._inductor.fx_passes.bucketing import ( + bucket_cap_mb_by_bucket_idx_default, # pyrefly: ignore [missing-module-attribute] + ) + + bucket_cap_mb_by_bucket_idx = bucket_cap_mb_by_bucket_idx_default + ar_buckets = bucket_all_reduce_by_mb(gm, bucket_cap_mb_by_bucket_idx) + if len(ar_buckets) == 0: + return + for bucket in ar_buckets: + merge_all_reduce_bucket(gm.graph, bucket, mode) + + +@torch.library.custom_op("bucketing::_pre_bucket_reduce_scatter", mutates_args={}) +def _pre_bucket_reduce_scatter( + rs_ins: list[torch.Tensor], + group_size: int, +) -> torch.Tensor: + rs_ins_flattened = [x.reshape(group_size, -1) for x in rs_ins] + new_rs_in = torch.cat(rs_ins_flattened, dim=1).flatten() + return new_rs_in + + +def _pre_bucket_reduce_scatter_fake( + rs_ins: list[torch.Tensor], + group_size: int, +) -> torch.Tensor: + out_numel = sum(rs_in.numel() for rs_in in rs_ins) + return torch.empty((out_numel,), device=rs_ins[0].device, dtype=rs_ins[0].dtype) + + +_pre_bucket_reduce_scatter.register_fake(_pre_bucket_reduce_scatter_fake) + + +def reduce_scatter_merge_fn_to_trace_custom_ops( + rs_ins: list[torch.Tensor], + group_name: Any, + group_size: int, + reduce_op: str, + reduce_dtype: torch.dtype, # type: ignore[name-defined] + device: torch.device, # type: ignore[name-defined] +) -> list[torch.Tensor]: # type: ignore[no-untyped-def] + new_out_sizes = [(x.shape[0] // group_size,) + x.shape[1:] for x in rs_ins] + new_out_numels = [x.numel() // group_size for x in rs_ins] + + new_rs_in = torch.ops.bucketing._pre_bucket_reduce_scatter(rs_ins, group_size) + + # TODO - either use torch.cat or make sure inductor foreach codegen + # fires more reliably + new_rs_out = torch.ops.c10d_functional.wait_tensor( + torch.ops._c10d_functional.reduce_scatter_tensor.default( + new_rs_in, reduce_op, group_size, group_name + ) + ) + new_out_flat = new_rs_out.split(new_out_numels, 0) + new_outs = [x.reshape(s) for x, s in zip(new_out_flat, new_out_sizes)] + return new_outs + + +def reduce_scatter_merge_fn_to_trace( + rs_ins: list[torch.Tensor], + group_name: Any, + group_size: int, + reduce_op: str, + reduce_dtype: torch.dtype, # type: ignore[name-defined] + device: torch.device, # type: ignore[name-defined] +) -> list[torch.Tensor]: # type: ignore[no-untyped-def] + rs_ins_flattened = [x.reshape(group_size, -1) for x in rs_ins] + + new_out_sizes = [(x.shape[0] // group_size,) + x.shape[1:] for x in rs_ins] + new_out_numels = [x.numel() // group_size for x in rs_ins] + + new_rs_in = torch.cat(rs_ins_flattened, dim=1).flatten() + + new_rs_out = torch.ops.c10d_functional.wait_tensor( + torch.ops._c10d_functional.reduce_scatter_tensor.default( + new_rs_in, reduce_op, group_size, group_name + ) + ) + new_out_flat = new_rs_out.split(new_out_numels, 0) + new_outs = [x.reshape(s) for x, s in zip(new_out_flat, new_out_sizes)] + return new_outs + + +def reduce_scatter_merge_fn_coalesced( + rs_ins: list[torch.Tensor], + group_name: Any, + group_size: int, + reduce_op: str, + reduce_dtype: torch.dtype, + device: torch.device, +) -> list[torch.Tensor]: + """Bucketed RS via NCCL's coalesced API (ncclGroupStart/End). + + Avoids cat-ing inputs into one buffer; instead passes the tensor list + directly to reduce_scatter_tensor_coalesced for zero-copy batching. + """ + rs_ins_flat = [x.reshape(-1) for x in rs_ins] + new_out_sizes = [(x.shape[0] // group_size,) + x.shape[1:] for x in rs_ins] + + rs_outs = torch.ops._c10d_functional.reduce_scatter_tensor_coalesced( + rs_ins_flat, reduce_op, group_size, group_name + ) + rs_outs = [torch.ops.c10d_functional.wait_tensor(o) for o in rs_outs] + return [o.reshape(s) for o, s in zip(rs_outs, new_out_sizes)] + + +def all_reduce_merge_fn_to_trace( + ar_ins: list[torch.Tensor], + group_name: Any, + reduce_op: str, + reduce_dtype: torch.dtype, # type: ignore[name-defined] + device: torch.device, # type: ignore[name-defined] +) -> list[torch.Tensor]: # type: ignore[no-untyped-def] + ar_ins_flattened = [x.reshape(-1) for x in ar_ins] + new_ar_in = torch.cat(ar_ins_flattened) + new_ar_out = torch.ops.c10d_functional.wait_tensor( + torch.ops._c10d_functional.all_reduce.default(new_ar_in, reduce_op, group_name) + ) + split_sizes = [x.numel() for x in ar_ins] + new_outs_flat = new_ar_out.split(split_sizes) + new_outs = [x.reshape(ar_in.shape) for x, ar_in in zip(new_outs_flat, ar_ins)] + return new_outs + + +# List of all torch dtypes for serialization through custom ops +# TODO: custom ops support list[dtype] input +_ALL_DTYPES = tuple( + [ + getattr(torch, attr) + for attr in dir(torch) + if isinstance(getattr(torch, attr), torch.dtype) + ] +) + + +@torch.library.custom_op("bucketing::_pre_bucket_all_gather", mutates_args={}) +def _pre_bucket_all_gather( + ag_ins: list[torch.Tensor], + group_size: int, + dtype: torch.dtype, # type: ignore[name-defined] + out_dtype_ints: list[ + int + ], # dtype enum values, that inputs are converted to before all_gather + rank: int, + foreach_group_indices: list[int] | None = None, +) -> torch.Tensor: + """ + Pre-bucket all gather operation. + + Args: + ag_ins: Input tensors to gather + group_size: Size of the process group + dtype: Target dtype for the bucket + out_dtype_ints: Dtype enum values for each input + rank: Current rank + foreach_group_indices: Optional flat list of grouped indices with -1 as delimiter. + E.g., [0, 2, -1, 1] means groups [[0, 2], [1]]. + """ + # Convert int indices back to torch.dtype + out_dtypes = [_ALL_DTYPES[d] for d in out_dtype_ints] + ins_split_sizes_bytes = [ + ag_in.numel() * out_dtype.itemsize + for ag_in, out_dtype in zip(ag_ins, out_dtypes, strict=True) + ] + bucket_dtype_size_bytes = dtype.itemsize + ins_split_sizes = [ + _bytes // bucket_dtype_size_bytes for _bytes in ins_split_sizes_bytes + ] + ag_input_numel = sum(ins_split_sizes) + device = ag_ins[0].device + new_ag_out = torch.empty(ag_input_numel * group_size, dtype=dtype, device=device) + new_ag_in = new_ag_out.narrow(0, ag_input_numel * rank, ag_input_numel) + foreach_copy_dsts = torch.split(new_ag_in, ins_split_sizes) + # View each destination slice as its output dtype, then copy + # The copy operation handles dtype conversion from input dtype to output dtype + foreach_copy_dsts_typed = [ + dst.view(out_dtype) + for dst, out_dtype in zip(foreach_copy_dsts, out_dtypes, strict=True) + ] + ag_ins_flattened = [ag_in.reshape(-1) for ag_in in ag_ins] + + # Parse pre-computed groups from flat list with -1 delimiters + if foreach_group_indices is not None: + groups_list: list[list[int]] = [] + current_group: list[int] = [] + for idx in foreach_group_indices: + if idx == -1: + if current_group: + groups_list.append(current_group) + current_group = [] + else: + current_group.append(idx) + # Add last group if not empty + if current_group: + groups_list.append(current_group) + + # Call foreach_copy_ per group + for group_indices in groups_list: + group_dsts = [foreach_copy_dsts_typed[idx] for idx in group_indices] + group_srcs = [ag_ins_flattened[idx] for idx in group_indices] + torch._foreach_copy_(group_dsts, group_srcs) + else: + # No grouping provided - single foreach_copy_ call + torch._foreach_copy_(foreach_copy_dsts_typed, ag_ins_flattened) + return new_ag_out + + +def _pre_bucket_all_gather_fake( + ag_ins: list[torch.Tensor], + group_size: int, + dtype: torch.dtype, # type: ignore[name-defined] + out_dtype_ints: list[int], + rank: int, + foreach_group_indices: list[int] | None = None, +) -> torch.Tensor: + out_dtypes = [_ALL_DTYPES[d] for d in out_dtype_ints] + ins_split_sizes_bytes = [ + ag_in.numel() * out_dtype.itemsize + for ag_in, out_dtype in zip(ag_ins, out_dtypes, strict=True) + ] + bucket_dtype_size_bytes = dtype.itemsize + ins_split_sizes = [ + _bytes // bucket_dtype_size_bytes for _bytes in ins_split_sizes_bytes + ] + ag_input_numel = sum(ins_split_sizes) + device = ag_ins[0].device + new_ag_out = torch.empty(ag_input_numel * group_size, dtype=dtype, device=device) + return new_ag_out + + +_pre_bucket_all_gather.register_fake(_pre_bucket_all_gather_fake) + + +def all_gather_merge_fn_to_trace_custom_ops( + _ag_ins: list[torch.Tensor], + group_name: Any, + group_size: int, + dtype: torch.dtype, # type: ignore[name-defined] + out_dtypes: list[torch.dtype], # type: ignore[name-defined] + rank: int, +) -> list[torch.Tensor]: + # Don't create convert_element_type ops - _pre_bucket_all_gather handles conversion + # by viewing destination slices as output dtypes and letting copy do the conversion + ag_ins = _ag_ins + ins_sizes = [ag_in.shape for ag_in in ag_ins] + ins_split_sizes_bytes = [ + ag_in.numel() * out_dtype.itemsize + for ag_in, out_dtype in zip(ag_ins, out_dtypes) + ] + bucket_dtype_size_bytes = dtype.itemsize + ins_split_sizes = [ + _bytes // bucket_dtype_size_bytes for _bytes in ins_split_sizes_bytes + ] + ag_input_numel = sum(ins_split_sizes) + + # Convert out_dtypes to indices for custom_op + # TODO: custom ops support list[dtype] input + out_dtype_ints = [_ALL_DTYPES.index(dt) for dt in out_dtypes] + + # Pre-compute foreach groups for better foreach_copy_ performance + foreach_group_indices = _compute_foreach_groups(ag_ins, out_dtypes) + + new_ag_out = torch.ops.bucketing._pre_bucket_all_gather( + ag_ins, + group_size, + dtype, + out_dtype_ints, + rank, + foreach_group_indices, + ) + new_ag_in = new_ag_out.narrow(0, ag_input_numel * rank, ag_input_numel) + wait_tensor = torch.ops.c10d_functional.wait_tensor( + torch.ops._c10d_functional.all_gather_into_tensor_out.default( + new_ag_in, group_size, group_name, out=new_ag_out + ) + ) + new_ag_out_reshaped = wait_tensor.reshape(group_size, -1) + outs_bucket_dtype = torch.split_with_sizes( + new_ag_out_reshaped, + ins_split_sizes, + dim=1, + ) + outs_reshaped = [ + o.view(out_dtype).reshape((shape[0] * group_size,) + shape[1:]) + for o, shape, out_dtype in zip(outs_bucket_dtype, ins_sizes, out_dtypes) + ] + return outs_reshaped + + +def all_gather_merge_fn_to_trace( + ag_ins: list[torch.Tensor], + group_name: Any, + group_size: int, + dtype: torch.dtype, # type: ignore[name-defined] + out_dtypes: list[torch.dtype], # type: ignore[name-defined] + rank: int, +) -> list[torch.Tensor]: + ins_sizes = [ag_in.shape for ag_in in ag_ins] + ins_split_sizes = [ag_in.numel() for ag_in in ag_ins] + ag_input_numel = sum(ins_split_sizes) + device = ag_ins[0].device + new_ag_out = torch.empty(ag_input_numel * group_size, dtype=dtype, device=device) + new_ag_in = new_ag_out.narrow(0, ag_input_numel * rank, ag_input_numel) + ag_ins_flattened = [ag_in.reshape(-1) for ag_in in ag_ins] + # Inductor fuses copy_(cat(...)) into 1 Triton kernel with no allocation for cat. + # _foreach_copy_(..., ag_ins_flattened) emits separate kernel per item, + # resulting in large number of small triton kernels to launch. + new_ag_in.copy_(torch.cat(ag_ins_flattened)) + wait_tensor = torch.ops.c10d_functional.wait_tensor( + torch.ops._c10d_functional.all_gather_into_tensor_out.default( + new_ag_in, group_size, group_name, out=new_ag_out + ) + ) + new_ag_out_reshaped = wait_tensor.reshape(group_size, -1) + outs = torch.split_with_sizes( + new_ag_out_reshaped, + ins_split_sizes, + dim=1, + ) + outs_reshaped = [ + o.reshape((shape[0] * group_size,) + shape[1:]) + for o, shape in zip(outs, ins_sizes) + ] + return outs_reshaped + + +def all_gather_merge_fn_to_trace_functional( + ag_ins: list[torch.Tensor], + group_name: Any, + group_size: int, + dtype: torch.dtype, # type: ignore[name-defined] + out_dtypes: list[torch.dtype], # type: ignore[name-defined] + rank: int, + use_fsdp_ag_copy_in: bool = False, +) -> list[torch.Tensor]: + # Implementation that is functional in graph, + # but uses custom op torch.ops.fsdp.all_gather_copy_in. + ins_sizes = [ag_in.shape for ag_in in ag_ins] + ins_split_sizes = [ag_in.numel() for ag_in in ag_ins] + ag_input_numel = sum(ins_split_sizes) + device = ag_ins[0].device + new_ag_out = torch.empty(ag_input_numel * group_size, dtype=dtype, device=device) + ag_ins_flattened = [ag_in.reshape(-1) for ag_in in ag_ins] + if use_fsdp_ag_copy_in: + new_ag_in, new_ag_out = torch.ops.fsdp.all_gather_copy_in( + ag_ins_flattened, new_ag_out, ins_split_sizes, ag_input_numel, rank + ) + else: + new_ag_in = torch.cat(ag_ins_flattened, dim=0) + wait_tensor = torch.ops.c10d_functional.wait_tensor( + torch.ops._c10d_functional.all_gather_into_tensor_out.default( + new_ag_in, group_size, group_name, out=new_ag_out + ) + ) + new_ag_out_reshaped = wait_tensor.reshape(group_size, -1) + outs = torch.split_with_sizes( + new_ag_out_reshaped, + ins_split_sizes, + dim=1, + ) + outs_reshaped = [ + o.reshape((shape[0] * group_size,) + shape[1:]) + for o, shape in zip(outs, ins_sizes) + ] + return outs_reshaped + + +def _trace(fn, inps) -> torch.fx.GraphModule: # type: ignore[no-untyped-def] + with dynamo_timed("fx.bucketing._trace", log_pt2_compile_event=True): + fake_mode = detect_fake_mode(inps) + if fake_mode is None: + raise AssertionError("expected a fake mode to be detected, got None") + shape_env = fake_mode.shape_env + pending_unbacked = None + ignorable_unbacked = None + if shape_env is not None: + pending_unbacked = list(shape_env.pending_fresh_unbacked_symbols) + ignorable_unbacked = list(shape_env.ignorable_fresh_unbacked_symbols) + shape_env.pending_fresh_unbacked_symbols.clear() + shape_env.ignorable_fresh_unbacked_symbols.clear() + try: + with fake_mode, enable_python_dispatcher(): + out = make_fx(fn)(*inps) + finally: + if shape_env is not None: + if pending_unbacked is None: + raise AssertionError("expected pending_unbacked to be set") + if ignorable_unbacked is None: + raise AssertionError("expected ignorable_unbacked to be set") + shape_env.pending_fresh_unbacked_symbols[:] = pending_unbacked + shape_env.ignorable_fresh_unbacked_symbols[:] = ignorable_unbacked + for node in out.graph.find_nodes( + op="call_function", target=torch.ops.aten.detach.default + ): + node.replace_all_uses_with(node.args[0]) + out.graph.erase_node(node) + return out + + +def _insert_fn_trace_before_node( # type: ignore[no-untyped-def] + g: torch.fx.Graph, + fn_to_trace, + inps, + insert_before_node: torch.fx.Node, + g_fn_inps: list[torch.fx.Node], + g_fn_outs: list[torch.fx.Node], +) -> tuple[dict[torch.fx.Node, torch.fx.Node], list[torch.fx.Node]]: # type: ignore[no-untyped-def] + """ + Helper function that traces :attr:`fn_to_trace` with inputs + :attr:`inps`. + The result function graph will be inserted before :attr:`insert_before_node`, + using :attr:`g_fn_inps` nodes of original graph as inputs of function graph, + function graph outputs will replace :attr:`g_fn_outs` in original graph. + + Returns: + (replacements, new_nodes): Dictionary mapping old to new nodes, and list of all newly inserted nodes + """ + with dynamo_timed( + "fx.bucketing._insert_fn_trace_before_node", log_pt2_compile_event=True + ): + fn_gm = _trace( + fn_to_trace, + inps, + ) + fn_g = fn_gm.graph + fn_g_ins = fn_g.find_nodes(op="placeholder") + env = {fn_g_ins[idx]: g_fn_inps[idx] for idx in range(len(g_fn_inps))} + g_fn_new_outs: list[torch.fx.Node] = [] + new_nodes: list[torch.fx.Node] = [] # Track all newly inserted nodes + + with g.inserting_before(insert_before_node): + for _n in fn_g.nodes: + if _n.op == "placeholder": + continue + _new_n = g.node_copy(_n, lambda x: env[x]) + env[_n] = _new_n + if _n.op == "output": + g_fn_new_outs = _new_n.args[0] # type: ignore[assignment] + g.erase_node(_new_n) + else: + new_nodes.append(_new_n) # Track non-output nodes + + replacements = { # noqa: C416 + orig_out: new_out for orig_out, new_out in zip(g_fn_outs, g_fn_new_outs) + } + replaced_users = [] + for orig_out, new_out in zip(g_fn_outs, g_fn_new_outs): + replaced_users.extend(orig_out.users) + orig_out.replace_all_uses_with(new_out) + _recompute_changed_user_metadata(replaced_users) + + return replacements, new_nodes + + +def has_mergeable_all_gather_convert_dtype(n: torch.fx.Node) -> bool: + node_in = n.args[0] + return ( + is_all_gather_into_tensor(n) + and isinstance(node_in, torch.fx.Node) + and node_in.op == "call_function" + and ( + node_in.target is torch.ops.prims.convert_element_type.default + or node_in.target is torch.ops.aten._to_copy.default + ) + and len(node_in.users) == 1 + ) + + +def _sort_bucket_region( + g: torch.fx.Graph, + new_nodes: list[torch.fx.Node], + new_nodes_inputs: list[torch.fx.Node], +) -> None: + """Topologically sort the smallest region spanning *new_nodes* and their inputs. + + After bucketing inserts *new_nodes*, some *new_nodes_inputs* may sit after + the new collective in the linked list. This sorts just the affected + region so every input precedes its consumer. + + Complexity: O(D) where D = distance between the farthest input and + new_nodes in the linked list. No full-graph enumeration. + """ + if not new_nodes or not new_nodes_inputs: + return + + new_set: OrderedSet[torch.fx.Node] = OrderedSet(new_nodes) + external: OrderedSet[torch.fx.Node] = OrderedSet( + [inp for inp in new_nodes_inputs if inp not in new_set] + ) + if not external: + return + + # Walk backward/forward from the new_nodes span to find all external + # inputs. ``remaining`` counts how many we still need to locate; + # each walk stops as soon as its share is found. + first = new_nodes[0] + last = new_nodes[-1] + remaining = len(external) + + cursor: torch.fx.Node | None = first.prev + while cursor is not None and cursor.op != "placeholder" and remaining > 0: + if cursor in external: + first = cursor + remaining -= 1 + cursor = cursor.prev + + cursor = last.next + while cursor is not None and cursor.op != "output" and remaining > 0: + if cursor in external: + last = cursor + remaining -= 1 + cursor = cursor.next + + if first is last: + return + + region: OrderedSet[torch.fx.Node] = OrderedSet() + cursor = first + while cursor is not None: + region.add(cursor) + if cursor is last: + break + cursor = cursor.next + + from torch._dynamo.graph_deduplication import _stable_topological_sort_region + + _stable_topological_sort_region(g, region) + + +def process_collective_bucket( + g: torch.fx.Graph, + bucket_nodes: list[torch.fx.Node], + fn_to_trace: Callable[..., list[torch.Tensor]], + trace_args_fn: Callable[[list[torch.fx.Node]], tuple[Any, ...]], + insert_before: torch.fx.Node | None = None, + wait_insertion_point: torch.fx.Node | None = None, + extra_graph_inps: list[torch.fx.Node] | None = None, +) -> tuple[list[torch.fx.Node], dict[torch.fx.Node, torch.fx.Node]]: + """ + Process a single bucket of collective operation nodes with flexible insertion control. + + Args: + g: The graph to modify + bucket_nodes: Nodes in the current bucket to process + fn_to_trace: Function to trace and insert + trace_args_fn: Function to create trace arguments from inputs + insert_before: Where to insert the traced function (default: after last bucket node) + wait_insertion_point: If provided, move all nodes from wait() onwards to before this node + extra_graph_inps: Additional non-tensor graph nodes to wire as traced + inputs (appended after tensor inputs). Used for compile-on-one-rank + graphs where group_name is a Node reference that make_fx proxies + as an opaque input. + + Returns: + new_nodes: List of all newly inserted nodes + replacements: Dictionary mapping old wait nodes to new output nodes + """ + # Collect inputs and waits from current bucket + bucket_ins: list[torch.fx.Node] = [] + bucket_waits: list[torch.fx.Node] = [] + ag_node_to_pre_nodes: dict[torch.fx.Node, list[torch.fx.Node]] = defaultdict(list) + + for n in bucket_nodes: + if len(n.users) != 1: + raise AssertionError(f"Expected single user for {n}, got {n.users}") + wait_n = next(iter(n.users)) + + # Handle convert_element_type operations (for all_gather) + node_in = n.args[0] + if has_mergeable_all_gather_convert_dtype(n): + # pyrefly: ignore [bad-argument-type] + ag_node_to_pre_nodes[n].append(node_in) + # pyrefly: ignore [missing-attribute] + node_in = node_in.args[0] + + if not isinstance(node_in, torch.fx.Node): # Ensure node_in is a Node + raise AssertionError(f"expected node_in to be a Node, got {type(node_in)}") + bucket_ins.append(node_in) + bucket_waits.append(wait_n) + + # Create trace arguments + trace_args = trace_args_fn(bucket_ins) + + # Determine insertion point + if insert_before is None: + insert_before = bucket_nodes[-1].next + + g_fn_inps = bucket_ins + (extra_graph_inps or []) + + # Insert traced function and get replacements + new nodes + replacements, new_nodes = _insert_fn_trace_before_node( + g, + fn_to_trace, + trace_args, + insert_before, + g_fn_inps, + bucket_waits, + ) + + # If requested, move wait nodes and everything after to specified location + if wait_insertion_point is not None: + # Find the first wait node in new_nodes + wait_start_idx = None + for i, node in enumerate(new_nodes): + if is_wait_tensor(node): + wait_start_idx = i + break + + # Move all nodes from wait onwards (including the wait) + if wait_start_idx is not None: + nodes_to_move = new_nodes[wait_start_idx:] + for node in nodes_to_move: + wait_insertion_point.prepend(node) + + # Preserve metadata from original collective nodes to new bucketed nodes + if bucket_nodes: + overlap_log.debug( + "Bucketing nodes: %s, New nodes: %s", + ",".join([n.name for n in bucket_nodes]), + ",".join([n.name for n in new_nodes]), + ) + _populate_node_meta(bucket_nodes, new_nodes) + + # Erase old nodes + for node, wait_n in zip(bucket_nodes, bucket_waits): + g.erase_node(wait_n) + g.erase_node(node) + # Erase any convert_element_type nodes we tracked + for pre_node in reversed(ag_node_to_pre_nodes[node]): + g.erase_node(pre_node) + + _sort_bucket_region(g, new_nodes, g_fn_inps) + + return new_nodes, replacements + + +def merge_reduce_scatter_bucket( + g: torch.fx.Graph, + rs_nodes: list[torch.fx.Node], + mode: BucketMode | None = None, + insert_before: torch.fx.Node | None = None, + wait_insertion_point: torch.fx.Node | None = None, +) -> tuple[list[torch.fx.Node], dict[torch.fx.Node, torch.fx.Node]]: + mode = mode or _default_bucket_mode() + # Validate bucket consistency + rs0 = rs_nodes[0] + rs0_val = rs0.meta["val"] + _, reduce_op, group_size, group_name = rs0.args + group_name_str = _resolve_group_name(group_name) + reduce_dtype = rs0_val.dtype + device = rs0_val.device + + for n in rs_nodes: + rs_val = n.meta["val"] + if not ( + n.args[1] == reduce_op + and n.args[2] == group_size + and _resolve_group_name(n.args[3]) == group_name_str + and rs_val.device == device + and rs_val.dtype == reduce_dtype + ): + raise AssertionError( + f"reduce_scatter node {n} does not match bucket parameters" + ) + + # Choose merge function based on mode + rs_merge_fn = reduce_scatter_merge_fn_to_trace + if mode == "coalesced": + rs_merge_fn = reduce_scatter_merge_fn_coalesced + elif mode and "custom_ops" in mode: + rs_merge_fn = reduce_scatter_merge_fn_to_trace_custom_ops + + group_name_val = ( + group_name.meta["val"] if isinstance(group_name, torch.fx.Node) else group_name + ) + + def create_trace_args(bucket_ins: list[torch.fx.Node]) -> tuple[Any, ...]: + return ( + pytree.tree_map(lambda node: node.meta["val"], bucket_ins), + group_name_val, + group_size, + reduce_op, + reduce_dtype, + device, + ) + + return process_collective_bucket( + g, + rs_nodes, + rs_merge_fn, + create_trace_args, + insert_before=insert_before, + wait_insertion_point=wait_insertion_point, + extra_graph_inps=( + [group_name] if isinstance(group_name, torch.fx.Node) else None + ), + ) + + +def merge_all_reduce_bucket( + g: torch.fx.Graph, + ar_nodes: list[torch.fx.Node], + mode: str | None = None, + insert_before: torch.fx.Node | None = None, + wait_insertion_point: torch.fx.Node | None = None, +) -> tuple[list[torch.fx.Node], dict[torch.fx.Node, torch.fx.Node]]: + ar0 = ar_nodes[0] + ar0_val = ar0.meta["val"] + _, reduce_op, group_name = ar0.args + group_name_str = _resolve_group_name(group_name) + reduce_dtype = ar0_val.dtype + device = ar0_val.device + + for n in ar_nodes: + ar_val = n.meta["val"] + if not ( + n.args[1] == reduce_op + and _resolve_group_name(n.args[2]) == group_name_str + and ar_val.device == device + and ar_val.dtype == reduce_dtype + ): + raise AssertionError( + f"all_reduce node {n} does not match bucket parameters" + ) + + ar_merge_fn = all_reduce_merge_fn_to_trace + + group_name_val = ( + group_name.meta["val"] if isinstance(group_name, torch.fx.Node) else group_name + ) + + def create_trace_args(bucket_ins: list[torch.fx.Node]) -> tuple[Any, ...]: + return ( + pytree.tree_map(lambda node: node.meta["val"], bucket_ins), + group_name_val, + reduce_op, + reduce_dtype, + device, + ) + + return process_collective_bucket( + g, + ar_nodes, + ar_merge_fn, + create_trace_args, + insert_before=insert_before, + wait_insertion_point=wait_insertion_point, + extra_graph_inps=( + [group_name] if isinstance(group_name, torch.fx.Node) else None + ), + ) + + +def merge_all_gather_bucket( + g: torch.fx.Graph, + ag_nodes: list[torch.fx.Node], + mode: BucketMode | None = None, + insert_before: torch.fx.Node | None = None, + wait_insertion_point: torch.fx.Node | None = None, +) -> tuple[list[torch.fx.Node], dict[torch.fx.Node, torch.fx.Node]]: + mode = mode or _default_bucket_mode() + from torch.distributed.distributed_c10d import _resolve_process_group + + ag0 = ag_nodes[0] + _, group_size, group_name = ag0.args + group_name_str = _resolve_group_name(group_name) + _ag_dtypes: list[torch.dtype] = [] # type: ignore[name-defined] + + for n in ag_nodes: + if not ( + n.args[1] == group_size and _resolve_group_name(n.args[2]) == group_name_str + ): + raise AssertionError( + f"all_gather node {n} does not match bucket parameters" + ) + _ag_dtypes.append(n.meta["val"].dtype) + + bucket_dtype = pick_bucket_dtype(_ag_dtypes) + + # Choose merge function based on mode + ag_merge_fn = all_gather_merge_fn_to_trace + if mode == "coalesced": + logger.info("coalesced bucket_mode not supported for all_gather, using default") + elif mode and "custom_ops" in mode: + ag_merge_fn = all_gather_merge_fn_to_trace_custom_ops # type: ignore[assignment] + + # pyrefly: ignore [bad-argument-type] + rank: int = dist.get_rank(_resolve_process_group(group_name_str)) + + group_name_val = ( + group_name.meta["val"] if isinstance(group_name, torch.fx.Node) else group_name + ) + + def create_trace_args(bucket_ins: list[torch.fx.Node]) -> tuple[Any, ...]: + return ( + pytree.tree_map(lambda node: node.meta["val"], bucket_ins), + group_name_val, + group_size, + bucket_dtype, + _ag_dtypes, + rank, + ) + + return process_collective_bucket( + g, + ag_nodes, + ag_merge_fn, + create_trace_args, + insert_before=insert_before, + wait_insertion_point=wait_insertion_point, + extra_graph_inps=( + [group_name] if isinstance(group_name, torch.fx.Node) else None + ), + ) + + +def merge_reduce_scatter( + gm: torch.fx.GraphModule, + rs_buckets: list[list[torch.fx.Node]], + mode: BucketMode | None = None, +) -> None: + """ + Merges specified buckets of reduce_scatter to joint reduce_scatter. + """ + mode = mode or _default_bucket_mode() + with dynamo_timed("fx.bucketing.merge_reduce_scatter", log_pt2_compile_event=True): + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "fx_bucketing_passes_reduce_scatter_buckets", + "encoding": "string", + }, + payload_fn=lambda: str(rs_buckets), + ) + + g = gm.graph + + for rs_nodes in rs_buckets: + merge_reduce_scatter_bucket(g, rs_nodes, mode) + + +def merge_all_gather( + gm: torch.fx.GraphModule, + ag_buckets: list[list[torch.fx.Node]], + mode: BucketMode | None = None, +) -> None: + """ + Merges specified buckets of all_gather to joint all_gather. + """ + mode = mode or _default_bucket_mode() + with dynamo_timed("fx.bucketing.merge_all_gather", log_pt2_compile_event=True): + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "fx_bucketing_passes_all_gather_buckets", + "encoding": "string", + }, + payload_fn=lambda: str(ag_buckets), + ) + + g = gm.graph + + for ag_nodes in ag_buckets: + merge_all_gather_bucket(g, ag_nodes, mode) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/control_dependencies.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/control_dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..16cd90505d31d96149fa3d03f61795c111fd5118 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/control_dependencies.py @@ -0,0 +1,295 @@ +# mypy: allow-untyped-defs +""" +Effect ordering pass for inductor. + +This pass adds ordering dependencies to FX graphs using the control_deps HOP +for precise control over scheduling constraints. When you need exact ordering between +operations (e.g., collective_start -> mm -> wait), this pass wraps operations +with control_deps to make dependencies explicit. +""" + +from operator import attrgetter +from typing import Any + +import torch.fx as fx +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import register_fake +from torch._ops import HigherOrderOperator +from torch.fx._lazy_graph_module import _LazyGraphModule +from torch.utils._ordered_set import OrderedSet + + +class ControlDeps(HigherOrderOperator): + """ + Higher-order operator that enforces ordering by making dependencies explicit. + + Schema: control_deps(additional_deps, subgraph, *args, **kwargs) -> result + where: + - additional_deps: tuple of tensors that must be computed before this op + (ordering-only, not a real data use) + - subgraph: GraphModule containing the exact operation to execute + - *args: pass-through arguments forwarded to the subgraph + + Semantics: + - All tensors in additional_deps are computed before the subgraph executes. + - Pass-through args (inputs returned unchanged by the subgraph) are + versioned: future readers are ordered after all subgraph operations + via a rename chain (OrderingOutput). This ensures that consumers of + a pass-through value cannot be scheduled before the subgraph's sync + ops (e.g. wait_event) complete. + """ + + def __init__(self) -> None: + super().__init__("control_deps") + + def __call__(self, additional_deps, subgraph, *args, **kwargs): + """Call the operator with dependencies and subgraph. + + Args: + additional_deps: Tuple of tensors that must be computed first + subgraph: GraphModule containing the exact operation to execute + *args: Arguments to pass to the subgraph + """ + if not isinstance(additional_deps, (tuple, list)): + raise TypeError( + f"additional_deps must be tuple/list, got {type(additional_deps).__name__}" + ) + if not (isinstance(subgraph, fx.GraphModule) or callable(subgraph)): + raise TypeError( + f"subgraph must be GraphModule or callable, got {type(subgraph).__name__}" + ) + # pyrefly: ignore [missing-attribute] + return super().__call__(additional_deps, subgraph, *args, **kwargs) + + +control_deps = ControlDeps() + +# control_deps wraps side-effecting ops (e.g. record_event, wait_event) +# and must not be eliminated by DCE even when its outputs are unused. +from torch.fx.node import has_side_effect + + +has_side_effect(control_deps) + + +# Register fake implementation for tracing +@register_fake(control_deps) +def _(additional_deps, subgraph, *args, **kwargs): + """Fake tensor implementation - execute the subgraph.""" + return subgraph(*args, **kwargs) + + +# Register eager execution implementation +@control_deps.py_impl(DispatchKey.CompositeExplicitAutograd) +def control_deps_eager(additional_deps, subgraph, *args, **kwargs): + """Eager implementation - just execute the subgraph.""" + return subgraph(*args, **kwargs) + + +# Autograd impl needed because additional_deps tensors may have autograd state, +# causing dispatch through AutogradCUDA even in post-autograd graphs. +@control_deps.py_impl(DispatchKey.Autograd) +def control_deps_autograd(additional_deps, subgraph, *args, **kwargs): + return subgraph(*args, **kwargs) + + +def get_subgraph_name(gm: fx.GraphModule, name): + name = f"subgraph_{name}" + + if not hasattr(gm, name): + return name + + i = 0 + while hasattr(gm, f"{name}_{i}"): + i += 1 + + return f"{name}_{i}" + + +def _extract_unique_nodes( + args: tuple[Any, ...], kwargs: dict[str, Any] +) -> tuple[list[fx.Node], list[Any], Any]: + """Extract unique fx.Node instances from args/kwargs using pytree. + + Args: + args: The positional arguments (may contain nested structures with fx.Node) + kwargs: The keyword arguments (may contain nested structures with fx.Node) + + Returns: + - Ordered list of unique fx.Node instances (preserves first occurrence order) + - Flattened list of all items from args/kwargs + - The pytree spec for reconstructing the original structure + """ + flat_args_kwargs, spec = pytree.tree_flatten((args, kwargs)) + unique_nodes: list[fx.Node] = [] + seen: OrderedSet[fx.Node] = OrderedSet() + for item in flat_args_kwargs: + if isinstance(item, fx.Node) and item not in seen: + unique_nodes.append(item) + seen.add(item) + return unique_nodes, flat_args_kwargs, spec + + +def preserve_node_ordering( + graph: fx.Graph, + additional_deps_map: dict[fx.Node, OrderedSet[fx.Node]], + verbose: bool = False, +) -> None: + """ + Preserve node ordering using control_deps HOP with subgraph. + + This function wraps operations with control_deps that: + 1. Makes additional dependencies explicit (first argument) + 2. Creates a subgraph internally to preserve the exact original operation + 3. Preserves the original node names + + Args: + graph: The FX graph to modify + additional_deps_map: Mapping from dependent nodes to their dependencies + verbose: If True, print debug information + """ + if not additional_deps_map: + return + + # Track replacements so we can update dependencies + replacements: dict[fx.Node, fx.Node] = {} + + # Process each node that needs additional dependencies + for dependent_node, dep_nodes in additional_deps_map.items(): + if dependent_node.op != "call_function": + raise AssertionError(dependent_node.op) + + original_name = dependent_node.name + original_args = dependent_node.args + original_kwargs = dependent_node.kwargs + original_meta = dependent_node.meta.copy() + + updated_dep_nodes = [replacements.get(dep, dep) for dep in dep_nodes] + + # Create a subgraph that preserves the exact original operation + subgraph_module = _create_subgraph_for_node(graph, dependent_node) + + owning_mod = graph.owning_module + if owning_mod is None: + raise AssertionError("expected graph to have an owning_module") + subgraph_attr_name = get_subgraph_name(owning_mod, original_name) + setattr(graph.owning_module, subgraph_attr_name, subgraph_module) + + # Create control_deps call with: + # 1. Additional dependencies as first arg (explicit) + # 2. Subgraph via get_attr (like b2b gemm pass) + # 3. Original arguments (only fx.Node args and kwargs are passed) + with graph.inserting_before(dependent_node): + # Create get_attr node for the subgraph + get_subgraph = graph.get_attr(subgraph_attr_name) + + # Extract unique nodes from nested args/kwargs + node_args, _, _ = _extract_unique_nodes(original_args, original_kwargs) + + # Create with temporary name first + ordered_node = graph.call_function( + control_deps, + args=( + tuple(updated_dep_nodes), # additional_deps + get_subgraph, # subgraph via get_attr (like b2b gemm) + *node_args, # original node arguments (from both args and kwargs) + ), + kwargs={}, + name=f"__temp_{original_name}", # Temporary name to avoid conflict + ) + + # Copy metadata from original node + ordered_node.meta = original_meta + # this will be constrained on the target node in subgraph if it exists + ordered_node.meta.pop("eager_input_vals", None) + + # Replace all uses of the original node with the ordered version + dependent_node.replace_all_uses_with(ordered_node) + + # Remove the original node from the graph + graph.erase_node(dependent_node) + + # Now rename the ordered node to the original name + ordered_node.name = original_name # PRESERVE ORIGINAL NAME + + # Track the replacement for future dependencies + replacements[dependent_node] = ordered_node + + +def _create_subgraph_for_node( + graph: fx.Graph, node: fx.Node, additional_deps=None +) -> fx.GraphModule: + """ + Create a subgraph that exactly recreates a node's operation optionally passing through additional dependencies. + + The subgraph takes only the fx.Node arguments and recreates the operation + with the exact target, args structure, and kwargs. + + Args: + graph: The parent graph + node: The node to wrap in a subgraph + additional_deps: Additional dependencies to pass through the subgraph + + Returns: + A GraphModule containing the subgraph + """ + # Get the owning module + owning_module = graph.owning_module + if owning_module is None: + raise AssertionError("graph.owning_module must not be None") + + # Create a new graph for the subgraph + subgraph = fx.Graph(owning_module) + + # Extract unique nodes and get flattened structure + spec + unique_nodes, flat_args_kwargs, spec = _extract_unique_nodes(node.args, node.kwargs) + + # Create placeholders for each unique node + node_to_placeholder: dict[fx.Node, fx.Node] = {} + for idx, orig_node in enumerate(unique_nodes): + placeholder = subgraph.placeholder(f"arg_{idx}") + if "val" in orig_node.meta: + placeholder.meta.update(orig_node.meta) + elif orig_node.op == "get_attr" and isinstance(orig_node.target, str): + placeholder.meta["val"] = attrgetter(orig_node.target)(owning_module) + node_to_placeholder[orig_node] = placeholder + + # Replace fx.Node instances with their placeholders + def replace_nodes(item: Any) -> Any: + if isinstance(item, fx.Node): + return node_to_placeholder[item] + return item + + additional_deps_placeholders = [] + for idx, dep in enumerate(additional_deps or ()): + placeholder = subgraph.placeholder(f"dep_{idx}") + if "val" in dep.meta: + placeholder.meta.update(dep.meta) + additional_deps_placeholders.append(placeholder) + + new_flat = [replace_nodes(item) for item in flat_args_kwargs] + new_args, new_kwargs = pytree.tree_unflatten(new_flat, spec) + + # Recreate the exact original operation in the subgraph + if not callable(node.target): + raise AssertionError(f"expected node.target to be callable, got {node.target}") + result = subgraph.call_function( + node.target, + tuple(new_args), + new_kwargs, # type: ignore[arg-type] + ) + + # Copy metadata from the original node + result.meta.update(node.meta) + + if additional_deps_placeholders: + outputs = tuple([result] + additional_deps_placeholders) + out = subgraph.output(outputs) + out.meta["val"] = tuple(output.meta.get("val") for output in outputs) + else: + out = subgraph.output(result) + if "val" in result.meta: + out.meta["val"] = result.meta["val"] + + return _LazyGraphModule(owning_module, subgraph) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/ddp_fusion.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/ddp_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..a15c89916f1be03779ebe30f8967c7ac7c806d43 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/ddp_fusion.py @@ -0,0 +1,599 @@ +# Owner(s): ["oncall: distributed"] +import collections +import inspect +import logging +import math +import operator +from collections.abc import Callable, Generator +from dataclasses import dataclass +from functools import partial +from typing import Any, cast + +import torch +import torch.fx as fx +from torch._dynamo.utils import counters +from torch.fx.passes.graph_transform_observer import GraphTransformObserver +from torch.fx.passes.shape_prop import _extract_tensor_metadata, TensorMetadata +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import tree_flatten, tree_map, tree_unflatten + +from ..fx_utils import get_fake_args_kwargs +from ..virtualized import V + + +aten = torch.ops.aten +logger: logging.Logger = logging.getLogger("comm_fusion") + + +def move_block_after(block: list[fx.Node], target_node: fx.Node) -> None: + for node in block: + target_node.append(node) + target_node = node + + +def move_block_before(block: list[fx.Node], target_node: fx.Node) -> None: + for node in block: + target_node.prepend(node) + target_node = node + + +def call_function( + graph: fx.Graph, + target: str | Callable[..., Any], + args: tuple[fx.node.Argument, ...] | None = None, + kwargs: dict[str, fx.node.Argument] | None = None, +) -> fx.Node: + # We accept target as a str to avoid typing error as the type of + # a node.target is str | Callable[..., Any]. + # This also allows us to avoid writing check for every call. + if isinstance(target, str): + raise RuntimeError(f"Call function should not get a str target {target=}") + node = graph.call_function(target, args, kwargs) + _, args, kwargs = get_fake_args_kwargs(node) + with V.fake_mode: + node.meta["val"] = target(*args, **kwargs) + # node.meta["val"] may be a container. So we use tree_map here + # to recursively extract the tensor metadata. + node.meta["tensor_meta"] = tree_map( + _extract_tensor_metadata, (node.meta["val"],) + )[0] + return node + + +@dataclass(unsafe_hash=True) +class CommBlock: + shape: torch.Size | list[torch.Size] + node_list: list[fx.Node] + inputs: list[fx.Node] + wait_nodes: list[fx.Node] + comm_node: fx.Node + outputs: OrderedSet[fx.Node] + + +def get_comm_block(comm_node: fx.Node) -> CommBlock | None: + """ + Given a collective node (e.g., allreduce), find out all the nodes belong to + this communication. + + Args: + comm_node(fx.Node): The target communication/collective node. + Returns: + The CommBlock that encapsulates the related nodes (e.g., wait_node) of + the given comm_node. + """ + node_list = [] + wait_nodes = [] + inputs, _ = tree_flatten((comm_node.args, comm_node.kwargs)) + input_nodes = [inp for inp in inputs if isinstance(inp, fx.Node)] + # If the users of the wait node are following items, we consider them + # to be a part of the output. + intermediate_outputs = ("split", "reshape", "getitem", "detach", "alias") + + first_user = next(iter(comm_node.users)) + if ( + len(comm_node.users) == 1 + and first_user.target is torch.ops._c10d_functional.wait_tensor.default + ): + # Collective with only one output + node_list = [comm_node, first_user] + wait_nodes.append(first_user) + elif len(comm_node.users) > 1 and first_user.target is operator.getitem: + # Collective with only more than one output + node_list.append(comm_node) + for user in comm_node.users: + if user.target != operator.getitem: + return None + if len(user.users) != 1: + return None + wait_node = next(iter(user.users)) + if wait_node.target != torch.ops._c10d_functional.wait_tensor.default: + return None + wait_nodes.append(wait_node) + node_list.append(user) + node_list.extend(wait_nodes) + else: + return None + + # Identify all the outputs of this collective block. + outputs = OrderedSet[fx.Node]() + nodes = collections.deque(wait_nodes) + while nodes: + node = nodes.popleft() + for user in node.users: + if isinstance(user, fx.Node) and user.name.startswith(intermediate_outputs): + nodes.append(user) + node_list.append(user) + else: + outputs.add(node) + break + + tensor_meta = input_nodes[0].meta["tensor_meta"] + shape: torch.Size | list[torch.Size] + if isinstance(tensor_meta, TensorMetadata): + shape = tensor_meta.shape + elif isinstance(tensor_meta, (list, tuple)): + shape = [tm.shape for tm in tensor_meta] + else: + logger.warning("Unexpected type of tensor_meta %s", type(tensor_meta)) + return None + + return CommBlock( + shape=shape, + node_list=node_list, + wait_nodes=wait_nodes, + comm_node=comm_node, + inputs=input_nodes, + outputs=outputs, + ) + + +def get_all_comm_blocks( + graph: fx.Graph, + comm_ops: tuple[torch._ops.OpOverload, ...], + comm_filter: Callable[..., bool] | None = None, +) -> list[CommBlock]: + if comm_filter is None: + + def always_true(comm_block: CommBlock) -> bool: + return True + + comm_filter = always_true + + blocks = [] + for node in graph.nodes: + if node.target not in comm_ops: + continue + comm_block = get_comm_block(node) + if comm_block is not None and comm_filter(comm_block): + blocks.append(comm_block) + return blocks + + +def _fuse_allreduce_by_concat( + graph: fx.Graph, + last_input_node: fx.Node, + all_input_nodes: list[fx.Node], + last_comm_block: CommBlock, +) -> CommBlock: + """Given a list of inputs in order, create a fused allreduce using concat.""" + # Flatten all the inputs to the all_reduce nodes. + with graph.inserting_after(last_input_node): + cat_inputs = [] + for input_node in all_input_nodes: + if not isinstance(input_node.args[0], fx.Node): + raise AssertionError( + f"expected input_node.args[0] to be an fx.Node, got " + f"{type(input_node.args[0])}" + ) + input_node = input_node.args[0] + cat_inputs.append( + call_function(graph, aten.flatten.using_ints, (input_node,)) + ) + + # Concat all the flattened nodes. + with graph.inserting_after(cat_inputs[0]): + cat_node = call_function(graph, aten.cat, (cat_inputs,)) + + # Insert the fused div node and remove the input div nodes. + # This is an optimization and is not mandatory for fusion. + divisors = [div.args[1] for div in all_input_nodes] + if not all(divisor == divisors[0] for divisor in divisors): + raise AssertionError("expected all divisors to be equal") + with graph.inserting_after(cat_node): + div_node = call_function(graph, last_input_node.target, (cat_node, divisors[0])) + + # Create a new Comm/all_reduce node. + last_comm_node = last_comm_block.comm_node + last_wait_node = last_comm_block.wait_nodes[0] + with graph.inserting_after(div_node): + flatten_args, spec = tree_flatten((last_comm_node.args, last_comm_node.kwargs)) + flatten_args[0] = div_node + args, kwargs = tree_unflatten(flatten_args, spec) + fused_comm_node = call_function(graph, last_comm_node.target, args, kwargs) + + # Create a new Wait node. + with graph.inserting_after(fused_comm_node): + flatten_args, spec = tree_flatten((last_wait_node.args, last_wait_node.kwargs)) + flatten_args[0] = fused_comm_node + args, kwargs = tree_unflatten(flatten_args, spec) + fused_wait_node = call_function(graph, last_wait_node.target, args, kwargs) + + # Move the fused all_reduce and its args to right after the input node + nodes_to_move = cat_inputs + [cat_node, div_node, fused_comm_node, fused_wait_node] + # pyrefly: ignore [bad-argument-type] + move_block_after(nodes_to_move, last_input_node) + + return CommBlock( + shape=cast(TensorMetadata, cat_node.meta.get("tensor_meta")).shape, + node_list=[fused_comm_node, fused_wait_node], + wait_nodes=[fused_wait_node], + comm_node=fused_comm_node, + inputs=[div_node], + outputs=OrderedSet([fused_wait_node]), + ) + + +def _fuse_with_coalesced_op( + graph: fx.Graph, + last_input_node: fx.Node, + all_input_nodes: list[fx.Node], + last_comm_block: CommBlock, +) -> CommBlock: + """Given a list of inputs in order, create a fused allreduce by coalesced.""" + last_comm_node = last_comm_block.comm_node + last_wait_node = last_comm_block.wait_nodes[0] + + # Insert the fused div node and remove the input div nodes. + # This is an optimization and is not mandatory for fusion. + dividends = [div.args[0] for div in all_input_nodes] + divisors = [div.args[1] for div in all_input_nodes] + if not all(divisor == divisors[0] for divisor in divisors): + raise AssertionError("expected all divisors to be equal") + with graph.inserting_before(last_input_node): + last_input_node = call_function( + graph, aten._foreach_div.Scalar, (dividends, divisors[0]) + ) + input_node = last_input_node + + # Create a new Comm/all_reduce_coalesced node. + with graph.inserting_after(last_comm_node): + flatten_args, spec = tree_flatten((last_comm_node.args, last_comm_node.kwargs)) + flatten_args[0] = input_node + args, kwargs = tree_unflatten(flatten_args, spec) + fused_comm_node = call_function( + graph, torch.ops._c10d_functional.all_reduce_coalesced.default, args, kwargs + ) + + # Create a new wait node. + getitem_nodes = [] + wait_nodes = [] + flatten_args, spec = tree_flatten((last_wait_node.args, last_wait_node.kwargs)) + for idx in range(len(all_input_nodes)): + with graph.inserting_after(fused_comm_node): + gi_node = call_function(graph, operator.getitem, (fused_comm_node, idx)) + getitem_nodes.append(gi_node) + flatten_args[0] = gi_node + args, kwargs = tree_unflatten(flatten_args, spec) + with graph.inserting_after(gi_node): + wait_nodes.append(call_function(graph, last_wait_node.target, args, kwargs)) + + # Move the new all_reduce_coalesced and its args to right after the input node + nodes_to_move = [fused_comm_node] + getitem_nodes + wait_nodes + move_block_after(nodes_to_move, last_input_node) + + return CommBlock( + shape=[ + tm.shape + for tm in cast( + list[TensorMetadata], fused_comm_node.meta.get("tensor_meta") + ) + ], + node_list=[fused_comm_node] + getitem_nodes + wait_nodes, + wait_nodes=wait_nodes, + comm_node=fused_comm_node, + inputs=[input_node], + outputs=OrderedSet(wait_nodes), + ) + + +def _scatter_fused_allreduce_waits( + graph: fx.Graph, + fused_comm_block: CommBlock, + orig_comm_blocks: list[CommBlock], + node_indices: dict[fx.Node, int], + split_and_reshape: bool = True, +) -> None: + """ + Scatters the result of the fused communication node to the original users. + If the fused method is concat splitting the output and reshape will be inserted, + before inserting getitem. Otherwise getitem will be used as the users of the + wait node. + """ + + # Before we mass up the order, we need to get the index of the last wait node + # in orig_comm_blocks. This index will be later used to determine what users + # nodes need to be move to maintain a correct topological sort order. + last_wait_node_idx = 0 + + for node in graph.nodes: + last_wait_node_idx = max( + node_indices.get(node, last_wait_node_idx), last_wait_node_idx + ) + if node == orig_comm_blocks[-1].wait_nodes[0]: + break + + if split_and_reshape: + fused_wait_node = fused_comm_block.wait_nodes[0] + with graph.inserting_after(fused_wait_node): + split_node = call_function( + graph, + aten.split, + ( + fused_wait_node, + [math.prod(cast(list[int], cb.shape)) for cb in orig_comm_blocks], + ), + ) + with graph.inserting_after(split_node): + fused_outputs = [] + for idx, comm_block in enumerate(orig_comm_blocks): + split_idx_node = call_function( + graph, operator.getitem, (split_node, idx) + ) + with graph.inserting_after(split_idx_node): + fused_outputs.append( + call_function( + graph, aten.reshape, (split_idx_node, comm_block.shape) + ) + ) + else: + fused_outputs = fused_comm_block.wait_nodes + + # Scatter the fused outputs. + incorrect_order_nodes = [] + for comm_block, fused_output in zip(orig_comm_blocks, fused_outputs): + # Some descendant users of the orig_comm_blocks may be scheduled before + # the fused all_reduce. For example, the user nodes of the very first + # all_reduce may be scheduled before the second all_reduce. Since the + # fused all_reduce is inserted right after the last all_reduce, the + # order can be wrong. + # `incorrect_order_nodes` records these nodes. + + orig_wait = comm_block.wait_nodes[0] + nodes = collections.deque(list(orig_wait.users)) + while nodes: + user_node = nodes.popleft() + if not isinstance(user_node, fx.Node): + continue + + if node_indices[user_node] < last_wait_node_idx: + incorrect_order_nodes.append(user_node) + nodes.extend(list(user_node.users)) + + orig_wait.replace_all_uses_with(fused_output) + + last_fused_result = fused_outputs[0] + fused_outputs_set = OrderedSet(fused_outputs) + for node in graph.nodes: + if node in fused_outputs_set: + last_fused_result = node + + # Move the incorrect_order_nodes to right after the last fused_result. + incorrect_order_nodes = sorted( + incorrect_order_nodes, key=lambda node: node_indices[node] + ) + move_block_after(incorrect_order_nodes, last_fused_result) + + +def _fuse_allreduce( + graph: fx.Graph, + comm_blocks: list[CommBlock], + node_indices: dict[fx.Node, int], + use_concat: bool, +) -> CommBlock: + """Given a list of allreduce CommBlock, fuse the CommBlocks into one CommBlock.""" + + if len(comm_blocks) == 1: + return comm_blocks[0] + + # Find the last input node of all the CommBlocks. This node will be served + # as the inserting point of the new collective op. + last_input_node = comm_blocks[0].inputs[0] + last_input_index = -1 + all_input_nodes = [] + for comm_block in comm_blocks: + input_node = comm_block.inputs[0] + all_input_nodes.append(input_node) + index = node_indices[input_node] + if index >= last_input_index: + if index == last_input_index: + raise AssertionError(f"expected index != last_input_index, got {index}") + last_input_node = input_node + last_input_index = index + + if use_concat: + fused_comm_block = _fuse_allreduce_by_concat( + graph, last_input_node, all_input_nodes, comm_blocks[-1] + ) + else: + fused_comm_block = _fuse_with_coalesced_op( + graph, last_input_node, all_input_nodes, comm_blocks[-1] + ) + + _scatter_fused_allreduce_waits( + graph, fused_comm_block, comm_blocks, node_indices, split_and_reshape=use_concat + ) + + for comm_block in comm_blocks: + for wait in comm_block.wait_nodes: + graph.erase_node(wait) + graph.erase_node(comm_block.comm_node) + graph.eliminate_dead_code() + + return fused_comm_block + + +def _bucket_size_fusion( + graph: fx.Graph, comm_blocks: list[CommBlock], bucket_size_mb: int +) -> Generator[list[CommBlock], None, None]: + MB = 1024**2 + bucket_size = 1 * MB + bucket_cap_size = bucket_size_mb * MB + curr_size = 0 + curr_blocks = [] + + count = 0 + fuse_count = 0 + for i, block in enumerate(comm_blocks): + curr_blocks.append(block) + itemsize = block.comm_node.meta["tensor_meta"].dtype.itemsize + curr_size += cast(torch.Size, block.shape).numel() * itemsize + count += 1 + if curr_size < bucket_size and i != len(comm_blocks) - 1: + continue + + fuse_count += 1 + if torch.distributed.get_rank() == 0: + logger.info( + "DDP bucketing: block%d, count=%d, curr_size=%d, bucket_size=%d", + fuse_count, + count, + curr_size, + bucket_size, + ) + + # Set the debug counters + counters["inductor"]["ddp_buckets"] = fuse_count + yield curr_blocks + + bucket_size = bucket_cap_size + curr_blocks = [] + curr_size = 0 + count = 0 + + +def _fuse_ddp_communication( + graph: fx.Graph, algorithm_fn: Callable[..., Any], fusion_fn: Callable[..., Any] +) -> None: + for output in reversed(graph.nodes): + if output.op == "output": + break + + def ddp_reducer_filter(block: CommBlock) -> bool: + if ( + not isinstance(block.comm_node.args[0], fx.Node) + or block.comm_node.args[0].target != aten.div.Tensor + ): + return False + + if len(block.wait_nodes[0].users) != 1: + # gradient/wait node should only be used by one user + return False + + # Two cases: + # 1. gradient/wait node should be directly used by the output + # if gradient is None before bwd. + # 2. gradient/wait node should be directly used by copy_. + if ( + output not in block.wait_nodes[0].users + and next(iter(block.wait_nodes[0].users)).target != aten.copy_.default + ): + return False + + return True + + ops = ( + torch.ops._c10d_functional.all_reduce_.default, + torch.ops._c10d_functional.all_reduce.default, + ) + comm_blocks = get_all_comm_blocks(graph, ops, comm_filter=ddp_reducer_filter) + node_indices = {node: i for i, node in enumerate(graph.nodes)} + + for block in algorithm_fn(graph, comm_blocks): + fusion_fn(graph, block, node_indices) + + +def fuse_ddp_with_coalesced_op(graph: fx.Graph, bucket_size_mb: int) -> None: + _fuse_ddp_communication( + graph, + partial(_bucket_size_fusion, bucket_size_mb=bucket_size_mb), + partial(_fuse_allreduce, use_concat=False), + ) + + +def fuse_ddp_with_concat_op(graph: fx.Graph, bucket_size_mb: int) -> None: + _fuse_ddp_communication( + graph, + partial(_bucket_size_fusion, bucket_size_mb=bucket_size_mb), + partial(_fuse_allreduce, use_concat=True), + ) + + +def schedule_comm_wait(graph: fx.Graph) -> None: + """ + Delay the execution of wait tensors of allreduce until its first user. + + This algorithm considers the intermediate users, like split, getitem, + of the wait node and schedule those intermediate users as well. + This will result in a better overlapping result. + """ + ops = ( + torch.ops._c10d_functional.all_reduce_.default, + torch.ops._c10d_functional.all_reduce.default, + torch.ops._c10d_functional.all_reduce_coalesced.default, + torch.ops._c10d_functional.all_reduce_coalesced_.default, + ) + comm_blocks = get_all_comm_blocks(graph, ops) + if not comm_blocks: + return + + # Find all the end users. + allreduce_users = OrderedSet[fx.Node]() + for allreduce in comm_blocks: + for output in allreduce.outputs: + allreduce_users.update(output.users) + + node_indices = {node: i for i, node in enumerate(graph.nodes)} + for allreduce in comm_blocks: + # Find the earliest/first user -- target_node. + if len(allreduce.outputs) < 1: + raise AssertionError( + f"Found an allreduce that has zero outputs/users -- {allreduce}." + ) + # Initialize the target node to avoid typing issues. + target_node = next(iter(next(iter(allreduce.outputs)).users)) + target_node_index = 2**31 + for user in (user for output in allreduce.outputs for user in output.users): + index = node_indices[user] + if index < target_node_index: + target_node = user + target_node_index = index + + # Move wait nodes and all the subsequent nodes in the comm_block to + # before the first user -- target_node. + wait_idx = -1 + for wait_idx, node in enumerate(allreduce.node_list): + if node == allreduce.wait_nodes[0]: + break + if wait_idx < 0: + raise AssertionError(f"expected wait_idx >= 0, got {wait_idx}") + move_block_before(allreduce.node_list[wait_idx:], target_node) + + +def fuse_ddp_communication( + graph: fx.Graph, passes: list[Callable[..., None] | str], bucket_size_mb: int +) -> None: + for i, pa in enumerate(passes): + with GraphTransformObserver( + graph.owning_module, # pyrefly: ignore[bad-argument-type] + f"fuse_ddp_communication_pass_{i}", + ): + if isinstance(pa, str): + func = globals()[pa] + else: + func = pa + if "bucket_size_mb" in OrderedSet( + v.name for v in inspect.signature(func).parameters.values() + ): + func(graph, bucket_size_mb=bucket_size_mb) + else: + func(graph) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/decomp_comms.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/decomp_comms.py new file mode 100644 index 0000000000000000000000000000000000000000..584564a16a13f3c42498a1b8cd5e7d24c6f8c519 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/decomp_comms.py @@ -0,0 +1,604 @@ +""" +Decompose collective communication patterns into mathematically equivalent +local computation + lighter collectives. + +Current passes: +- decomp_gram_matrix_all_gather: + all_gather + mm(X.T, X) -> local mm(Xi.T, Xi) + all_reduce(sum) + Exploits X.T @ X = sum_i(Xi.T @ Xi). + +Gated by config.aten_distributed_optimizations.allow_comms_decompositions. +""" + +import logging +import operator +from collections import defaultdict +from typing import NamedTuple + +import torch +import torch.fx as fx +from torch._inductor.fx_passes.bucketing import get_collective_type, is_wait_tensor +from torch._inductor.fx_utils import get_fake_args_kwargs +from torch._inductor.virtualized import V +from torch.utils._ordered_set import OrderedSet + + +aten = torch.ops.aten +c10d = torch.ops._c10d_functional +logger = logging.getLogger(__name__) + +# Require >= 2 Gram mms: targets iterative optimizers (Newton-Schulz), +# skips single fwd/bwd Grams (decomposable but not yet validated). +# TODO: validate single-Gram fwd/bwd decomposition on a real model. +_MIN_GRAM_MMS = 2 + + +def _get_fake_mode(node: fx.Node) -> torch._subclasses.fake_tensor.FakeTensorMode: + """Get FakeTensorMode: V.fake_mode during compilation, from node meta in tests.""" + mode = V.fake_mode + if isinstance(mode, torch._subclasses.fake_tensor.FakeTensorMode): + return mode + # Standalone call (tests) -- extract from node metadata + for inp in node.all_input_nodes: + val = inp.meta.get("val") + fake_mode = torch._subclasses.fake_tensor.maybe_get_fake_mode(val) + if fake_mode is not None: + return fake_mode + raise RuntimeError(f"No FakeTensorMode available for {node.name}") + + +def _retrace_node_meta(node: fx.Node) -> None: + """Recompute node.meta["val"] by running the op on input FakeTensors.""" + if node.op != "call_function": + return + valid, args, kwargs = get_fake_args_kwargs(node) + if not valid: + return + target = node.target + if not callable(target): + raise AssertionError(f"node target is not callable: {target}") + with _get_fake_mode(node): + node.meta["val"] = target(*args, **kwargs) + + +def _is_2d_transpose(node: fx.Node) -> bool: + """True if node is aten.t, permute([1,0]), or transpose(0,1) on a 2D input.""" + if node.op != "call_function": + return False + inp_val = ( + node.args[0].meta.get("val") + if node.args and isinstance(node.args[0], fx.Node) + else None + ) + if inp_val is not None and inp_val.dim() != 2: + return False + if node.target is aten.t.default: + return True + if node.target is aten.permute.default: + dims = node.args[1] if len(node.args) > 1 else None + return isinstance(dims, (list, tuple)) and list(dims) == [1, 0] + if node.target is aten.transpose.int and len(node.args) >= 3: + d0, d1 = node.args[1], node.args[2] + return (d0, d1) in ((0, 1), (1, 0), (-2, -1), (-1, -2)) + return False + + +def is_gram_mm(node: fx.Node) -> bool: + """True if node computes mm(X, X.T) or mm(X.T, X).""" + if node.op != "call_function" or node.target is not aten.mm.default: + return False + a, b = node.args[0], node.args[1] + if not isinstance(a, fx.Node) or not isinstance(b, fx.Node): + return False + return (_is_2d_transpose(a) and a.args[0] is b) or ( + _is_2d_transpose(b) and b.args[0] is a + ) + + +def gram_source(gram_node: fx.Node) -> fx.Node: + """Return the base tensor X (non-transposed arg) from a Gram mm.""" + a = gram_node.args[0] + b = gram_node.args[1] + if not (isinstance(a, fx.Node) and isinstance(b, fx.Node)): + raise AssertionError("gram mm args must both be fx.Node") + return b if _is_2d_transpose(a) else a + + +class AllGatherInfo(NamedTuple): + shard: fx.Node + group_name: str + ag_node: fx.Node + wait_node: fx.Node + # Full gathered tensor consumed downstream: an identity/trim slice + # wrapping the wait when present, else the wait itself. + entry_node: fx.Node + + +def find_all_gather_ancestor( + node: fx.Node, max_depth: int = 30 +) -> AllGatherInfo | None: + """Walk backward from node to find an all_gather -> wait [-> slice] chain. + + The trailing slice is optional. Inductor folds the FSDP identity slice + slice(wait, 0, 0, gathered_rows) when sharding is even (it is a no-op), so + we anchor on the wait and use a slice that wraps it as the entry node only + when one is present (FSDP padding trims, or overlap scheduling keeps it). + """ + visited: OrderedSet[fx.Node] = OrderedSet() + queue = [(node, 0)] + while queue: + n, depth = queue.pop(0) + if n in visited or depth > max_depth or n.op == "placeholder": + continue + visited.add(n) + for inp in n.all_input_nodes: + queue.append((inp, depth + 1)) + if n.op != "call_function" or n.target is not c10d.wait_tensor.default: + continue + ag_node = n.args[0] + if ( + not isinstance(ag_node, fx.Node) + or ag_node.target is not c10d.all_gather_into_tensor.default + ): + continue + # all_gather_into_tensor(shard, world_size, group_name) + shard, group_name = ag_node.args[0], ag_node.args[2] + if not isinstance(shard, fx.Node) or not isinstance(group_name, str): + continue + entry_node = n + if len(n.users) == 1: + (only_user,) = n.users + if ( + only_user.op == "call_function" + and only_user.target is aten.slice.Tensor + ): + entry_node = only_user + return AllGatherInfo( + shard=shard, + group_name=group_name, + ag_node=ag_node, + wait_node=n, + entry_node=entry_node, + ) + return None + + +def _select_getitem(split_node: fx.Node, rank: int | None) -> fx.Node | None: + """Pick getitem from a split: by rank if known, else lowest-index with users.""" + getitems = [ + u + for u in split_node.users + if u.op == "call_function" and u.target is operator.getitem + ] + if not getitems: + return None + if rank is not None: + matches = [g for g in getitems if len(g.args) > 1 and g.args[1] == rank] + return matches[0] if matches else None + used = sorted( + (g for g in getitems if g.users), + key=lambda g: g.args[1] if len(g.args) > 1 else 0, + ) + return used[0] if used else None + + +def find_split_getitem( + start: fx.Node, rank: int | None = None, max_search: int = 3000 +) -> tuple[fx.Node, fx.Node] | None: + """Walk forward from start to find split(dim=0) -> getitem[rank].""" + chain: OrderedSet[fx.Node] = OrderedSet([start]) + searched = 0 + node = start.next + while node is not None and searched < max_search: + searched += 1 + if node.op != "call_function" or not any( + inp in chain for inp in node.all_input_nodes + ): + node = node.next + continue + if get_collective_type(node) != "" or is_wait_tensor(node): + return None + if node.target is aten.split.Tensor: + if (node.args[2] if len(node.args) > 2 else 0) != 0: + return None + gi = _select_getitem(node, rank) + return (node, gi) if gi else None + chain.add(node) + node = node.next + return None + + +def _is_reduction(node: fx.Node) -> bool: + """True if node is a reduction op (sum, mean, norm, etc.).""" + return ( + node.op == "call_function" + and isinstance(node.target, torch._ops.OpOverload) + and torch.Tag.reduction in node.target.tags + ) + + +def _is_l2_norm_op(node: fx.Node) -> bool: + """True if node computes an L2 (Frobenius) norm.""" + if node.op != "call_function": + return False + if node.target in (aten.frobenius_norm.dim, aten.norm.Scalar): + return True + if node.target in (aten.linalg_vector_norm.default, aten.norm.ScalarOpt_dim): + ord_arg = node.args[1] if len(node.args) > 1 else 2 + return ord_arg in (2, 2.0) + return False + + +# Reductions whose global result decomposes from per-shard results +# via all_reduce: L2 norms (pow2 + sum + sqrt), sums (sum). +# Unknown reductions cause the transform to bail out entirely. +_DECOMPOSABLE_REDUCTIONS = ( + aten.sum.default, + aten.sum.dim_IntList, + aten.linalg_vector_norm.default, + aten.norm.ScalarOpt_dim, + aten.norm.Scalar, + aten.frobenius_norm.dim, +) + + +def _valid_entry_slice(node: fx.Node) -> bool: + val = node.meta.get("val") + dim = node.args[1] if len(node.args) > 1 else node.kwargs.get("dim", 0) + start = node.args[2] if len(node.args) > 2 else node.kwargs.get("start", 0) + end = node.args[3] if len(node.args) > 3 else node.kwargs.get("end", None) + step = node.args[4] if len(node.args) > 4 else node.kwargs.get("step", 1) + if ( + not isinstance(val, torch.Tensor) + or not isinstance(dim, int) + or not isinstance(start, int) + or not isinstance(step, int) + or (end is not None and not isinstance(end, int)) + ): + return False + return ( + -val.dim() <= dim < val.dim() + and dim % val.dim() == 0 + and start == 0 + and step == 1 + and (end is None or end >= int(val.shape[0])) + ) + + +def _reduction_includes_sharded_dim(node: fx.Node) -> bool: + """True if a reduction reduces over dim 0 (the sharded dimension). + + Returns False for reductions over only non-sharded dims. Unknown reduction + ops are assumed to include the sharded dim so the caller bails out. + """ + if not _is_reduction(node): + return False + + def _dims_include_zero(dims: object) -> bool: + if isinstance(dims, int): + dims = [dims] + elif not isinstance(dims, (list, tuple)): + return True + inp = node.args[0] if node.args else None + inp_val = inp.meta.get("val") if isinstance(inp, fx.Node) else None + ndim: int = inp_val.dim() if inp_val is not None else 2 + return any(int(d) % ndim == 0 for d in dims) + + # Norms with dim arg + if node.target in ( + aten.linalg_vector_norm.default, + aten.norm.ScalarOpt_dim, + aten.frobenius_norm.dim, + ): + dims = node.args[2] if len(node.args) > 2 else None + return dims is None or _dims_include_zero(dims) + + # sum/mean with dim arg + if node.target in (aten.sum.dim_IntList, aten.mean.dim): + dims = node.args[1] if len(node.args) > 1 else None + return dims is None or _dims_include_zero(dims) + + if len(node.args) > 1 and isinstance(node.args[1], (int, list, tuple)): + return _dims_include_zero(node.args[1]) + return True + + +def _gram_shape_is_decomposable(gram_node: fx.Node, gathered_rows: int) -> bool: + """True if the Gram output shape doesn't depend on the gathered row count. + + X.T @ X = sum(Xi.T @ Xi) only when the contraction dim is the sharded + dim. If any output dim equals gathered_rows, the decomposition is invalid. + """ + mm_val = gram_node.meta.get("val") + if mm_val is None: + return False + return ( + int(mm_val.shape[0]) != gathered_rows and int(mm_val.shape[1]) != gathered_rows + ) + + +def _insert_all_reduce_wait(graph: fx.Graph, node: fx.Node, group_name: str) -> fx.Node: + """Insert all_reduce(sum) + wait_tensor after node, rewire users.""" + with graph.inserting_before(node.next): + ar = graph.call_function( + c10d.all_reduce.default, args=(node, "sum", group_name) + ) + wait_ar = graph.call_function(c10d.wait_tensor.default, args=(ar,)) + for user in list(node.users): + if user is not ar: + user.replace_input_with(node, wait_ar) + return wait_ar + + +def _collect_dependent_chain(start: fx.Node, stop: fx.Node) -> OrderedSet[fx.Node]: + """Collect call_function nodes transitively dependent on start, up to stop.""" + chain: OrderedSet[fx.Node] = OrderedSet([start]) + n = start.next + while n is not None and n is not stop: + if n.op == "call_function" and any(inp in chain for inp in n.all_input_nodes): + chain.add(n) + n = n.next + return chain + + +def _collect_split_path_chain(start: fx.Node, stop: fx.Node) -> OrderedSet[fx.Node]: + chain = _collect_dependent_chain(start, stop) + path: OrderedSet[fx.Node] = OrderedSet() + stack = [stop] + while stack: + node = stack.pop() + if node in path: + continue + path.add(node) + stack.extend(inp for inp in node.all_input_nodes if inp in chain) + return OrderedSet(n for n in chain if n in path) + + +def _has_unsupported_sharded_reduction( + chain: OrderedSet[fx.Node], gram_set: OrderedSet[fx.Node] +) -> bool: + """True if chain contains a reduction over dim 0 we can't correct.""" + for node in chain: + if node in gram_set: + continue + if not _reduction_includes_sharded_dim(node): + continue + if _is_l2_norm_op(node) or node.target in ( + aten.sum.default, + aten.sum.dim_IntList, + ): + continue + logger.debug( + "decomp_gram: unsupported reduction %s (%s)", node.name, node.target + ) + return True + return False + + +def decomp_gram_matrix_all_gather(gm: fx.GraphModule) -> fx.GraphModule: + """Eliminate all_gather when the gathered tensor feeds Gram matrix computation. + + Replaces all_gather + mm(X.T, X) with local mm(Xi.T, Xi) + all_reduce(sum). + The Gram identity X.T @ X = sum(Xi.T @ Xi) makes each rank's partial + Gram summable via all_reduce, eliminating the O(S*W*K) all_gather in + favor of O(K^2) all_reduces. + + Also corrects reductions over the sharded dim: L2 norms become + pow(2) + all_reduce(sum) + sqrt, sums become all_reduce(sum). + """ + # Lazy: a module-level distributed import breaks test_circular_dependencies. + from torch.distributed.distributed_c10d import _resolve_process_group, GroupName + + graph = gm.graph + transformed = 0 + + # Find Gram mms and trace each to its all_gather source + ag_to_grams: dict[fx.Node, list[fx.Node]] = defaultdict(list) + ag_infos: dict[fx.Node, AllGatherInfo] = {} + + for mm_node in graph.find_nodes(op="call_function", target=aten.mm.default): + if not is_gram_mm(mm_node): + continue + info = find_all_gather_ancestor(gram_source(mm_node)) + if info is None: + continue + ag_to_grams[info.ag_node].append(mm_node) + ag_infos[info.ag_node] = info + + for ag_node, gram_mms in ag_to_grams.items(): + info = ag_infos[ag_node] + + # ag must feed only its wait. The wait may have multiple users when no + # slice wraps it (the gathered tensor feeds the chain directly); those + # users are validated to stay inside the dependent chain below. + if len(ag_node.users) != 1: + continue + + rank = _resolve_process_group(GroupName(info.group_name)).rank() + split_result = find_split_getitem(info.entry_node, rank=rank) + if split_result is None: + continue + split_node, getitem_node = split_result + + split_size = split_node.args[1] if len(split_node.args) > 1 else None + if not isinstance(split_size, int): + continue + + # Validate: gathered rows must differ from shard rows + entry_val = info.entry_node.meta.get("val") + shard_val = ( + info.shard.meta.get("val") if isinstance(info.shard, fx.Node) else None + ) + if entry_val is None or shard_val is None: + continue + gathered_rows = int(entry_val.shape[0]) + shard_rows = int(shard_val.shape[0]) + if gathered_rows == shard_rows: + continue + if info.entry_node is not info.wait_node and not _valid_entry_slice( + info.entry_node + ): + continue + + valid_grams = [ + mm for mm in gram_mms if _gram_shape_is_decomposable(mm, gathered_rows) + ] + + if len(valid_grams) < _MIN_GRAM_MMS: + logger.debug( + "decomp_gram: skip %s -- %d < %d decomposable Gram mms", + ag_node.name, + len(valid_grams), + _MIN_GRAM_MMS, + ) + continue + gram_mms = valid_grams + + # Even split: all getitems must have the same shape (SPMD constraint) + all_getitems = [ + u + for u in split_node.users + if u.op == "call_function" and u.target is operator.getitem + ] + + # Collapsing the split into the rank-local result invalidates sibling + # getitems; in real SPMD only the rank's own getitem is consumed, so bail. + if any(g is not getitem_node and len(g.users) > 0 for g in all_getitems): + logger.debug( + "decomp_gram: skip %s -- split has other consumed getitems", + ag_node.name, + ) + continue + + shapes = [ + tuple(int(d) for d in u.meta["val"].shape) + for u in all_getitems + if u.meta.get("val") is not None + ] + if len(OrderedSet(shapes)) > 1: + logger.debug("decomp_gram: skip -- uneven split shapes %s", shapes[:3]) + continue + + getitem_val = getitem_node.meta.get("val") + if getitem_val is None: + continue + expected_rows = int(getitem_val.shape[0]) + + # Shard trimming for FSDP padding + replacement: fx.Node = info.shard + if expected_rows < shard_rows: + with graph.inserting_before(info.entry_node): + replacement = graph.call_function( + aten.slice.Tensor, + args=(info.shard, 0, 0, expected_rows), + ) + _retrace_node_meta(replacement) + elif expected_rows > shard_rows: + continue + + # Verify the rewritten region is closed over the path to split. + chain = _collect_split_path_chain(info.entry_node, split_node) + if any(u is not split_node and u not in chain for n in chain for u in n.users): + continue + + gram_set: OrderedSet[fx.Node] = OrderedSet(gram_mms) + if _has_unsupported_sharded_reduction(chain, gram_set): + continue + + # === Transform === + + info.entry_node.replace_all_uses_with(replacement) + + for mm_node in gram_mms: + _insert_all_reduce_wait(graph, mm_node, info.group_name) + + # Correct reductions over the sharded dim + for node in list(chain): + if node in gram_set or not _reduction_includes_sharded_dim(node): + continue + if _is_l2_norm_op(node): + # L2: global = sqrt(all_reduce_sum(local^2)) + with graph.inserting_before(node.next): + sq = graph.call_function(aten.pow.Tensor_Scalar, args=(node, 2.0)) + ar = graph.call_function( + c10d.all_reduce.default, + args=(sq, "sum", info.group_name), + ) + wait_ar = graph.call_function(c10d.wait_tensor.default, args=(ar,)) + corrected = graph.call_function( + aten.pow.Tensor_Scalar, args=(wait_ar, 0.5) + ) + for user in list(node.users): + if user is not sq: + user.replace_input_with(node, corrected) + elif _is_reduction(node): + _insert_all_reduce_wait(graph, node, info.group_name) + + # Result is already shard-sized, bypass split+getitem + pre_split = split_node.args[0] + if not isinstance(pre_split, fx.Node): + raise AssertionError(f"split input must be fx.Node, got {pre_split}") + getitem_node.replace_all_uses_with(pre_split) + + # Retrace meta["val"] for nodes whose shapes changed + affected: OrderedSet[fx.Node] = OrderedSet([replacement]) + n = replacement.next + while n is not None and n is not split_node: + if n.op == "call_function" and any( + inp in affected for inp in n.all_input_nodes + ): + _retrace_node_meta(n) + affected.add(n) + n = n.next + + # entry_node may be the wait itself; dedup so we don't erase twice. + for dead in OrderedSet( + [getitem_node, split_node, info.entry_node, info.wait_node, ag_node] + ): + if len(dead.users) == 0: + graph.erase_node(dead) + + transformed += 1 + + if transformed > 0: + graph.eliminate_dead_code() + graph.lint() + gm.recompile() + logger.info("decomp_gram: transformed %d pattern(s)", transformed) + + return gm + + +def decomp_comms(gm: fx.GraphModule) -> fx.GraphModule: + """Run all collective decomposition passes.""" + from torch._logging import trace_structured + + logger.info( + "decomp_comms: running on graph with %d nodes", + len(list(gm.graph.nodes)), + ) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "pre_decomp_comms", + "encoding": "string", + }, + payload_fn=lambda: gm.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + decomp_gram_matrix_all_gather(gm) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "post_decomp_comms", + "encoding": "string", + }, + payload_fn=lambda: gm.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + return gm diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/decompose_mem_bound_mm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/decompose_mem_bound_mm.py new file mode 100644 index 0000000000000000000000000000000000000000..3613ab1ed17b5e35815d1bca359b94b29b511abc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/decompose_mem_bound_mm.py @@ -0,0 +1,285 @@ +# mypy: allow-untyped-defs +import logging + +import torch +from torch import Tensor +from torch._dynamo.utils import counters, is_node_meta_valid +from torch.fx.experimental.symbolic_shapes import ( + statically_known_false, + statically_known_true, +) + +from .. import config +from ..pattern_matcher import Arg, CallFunction, Match, register_graph_pattern +from .split_cat import construct_pattern_matcher_pass + + +aten = torch.ops.aten +log = logging.getLogger(__name__) + +# TODO: need a better strategy for decomposing mm +# The following two constants are for CUDA device only +MIN_FIRST_DIMENSION_DECOMPOSITION = 10240 +MAX_OTHER_DIMENSION_DECOMPOSITION = 32 +# The following two constants are for CPU device only +CPU_MAX_FIRST_DIMENSION_DECOMPOSITION = 1 +CPU_MAX_OTHER_DIMENSION_DECOMPOSITION = 2048 + +min_first_dimension_decomposition = MIN_FIRST_DIMENSION_DECOMPOSITION +max_other_dimension_decomposition = MAX_OTHER_DIMENSION_DECOMPOSITION +cpu_max_first_dimension_decomposition = CPU_MAX_FIRST_DIMENSION_DECOMPOSITION +cpu_max_other_dimension_decomposition = CPU_MAX_OTHER_DIMENSION_DECOMPOSITION +if "decompose_mm_pass" in config.post_grad_fusion_options: + min_first_dimension_decomposition = config.post_grad_fusion_options[ + "decompose_mm_pass" + ].get("min_first_dimension_decomposition", MIN_FIRST_DIMENSION_DECOMPOSITION) + max_other_dimension_decomposition = config.post_grad_fusion_options[ + "decompose_mm_pass" + ].get("max_other_dimension_decomposition", MAX_OTHER_DIMENSION_DECOMPOSITION) + cpu_max_first_dimension_decomposition = config.post_grad_fusion_options[ + "decompose_mm_pass" + ].get( + "cpu_max_first_dimension_decomposition", CPU_MAX_FIRST_DIMENSION_DECOMPOSITION + ) + cpu_max_other_dimension_decomposition = config.post_grad_fusion_options[ + "decompose_mm_pass" + ].get( + "cpu_max_other_dimension_decomposition", CPU_MAX_OTHER_DIMENSION_DECOMPOSITION + ) + + +def check_device(a: Tensor, b: Tensor, device="cuda") -> bool: + return (a.device.type == b.device.type) and (b.device.type == device) + + +def realize_inputs(inputs: list[torch.fx.Node]): + for inp in inputs: + if isinstance(inp, torch.fx.node.Node): + inp.meta["inductor_realize_to_strides"] = True + + +def should_decompose_bmm(mat1, mat2) -> bool: + if is_node_meta_valid(mat1) and is_node_meta_valid(mat2): + mat1 = mat1.meta["val"] + mat2 = mat2.meta["val"] + else: + return False + if len(mat1.shape) != 3 or len(mat2.shape) != 3: + return False + if check_device(mat1, mat2, device="cuda") or check_device( + mat1, mat2, device="xpu" + ): + if mat1.shape[0] < min_first_dimension_decomposition: + return False + # 2 of m, n, k must be <= MAX_OTHER_DIMENSION_DECOMPOSITION + # use bool() to deal with BooleanAtom type + if ( + bool(mat1.shape[1] < max_other_dimension_decomposition) + + bool(mat1.shape[2] < max_other_dimension_decomposition) + + bool(mat2.shape[2] < max_other_dimension_decomposition) + < 2 + ): + return False + return True + elif check_device(mat1, mat2, device="cpu"): + if ( + mat1.shape[0] <= cpu_max_first_dimension_decomposition + and mat2.shape[0] <= cpu_max_first_dimension_decomposition + ): + return True + return False + + +def should_decompose_mm(mat1, mat2) -> bool: + """ + Determines whether matrix multiplication (mm) should be decomposed into pointwise operations + based on the input matrices' metadata, shapes, device placement, and configuration options. + Args: + mat1: The first matrix operand. Expected to be an object with a `.meta` attribute containing + a "val" key, or a tensor-like object with a `.shape` attribute. + mat2: The second matrix operand. Same requirements as `mat1`. + Returns: + bool: True if the matrix multiplication should be decomposed according to the following logic: + - Both inputs must have valid node metadata. + - Both matrices must be 2-dimensional. + - If the configuration option `skip_dynamic_shape_dim_check` is False: + - Decomposition is only considered for statically-shaped matrices. + - For CUDA devices: `mat1.shape[0]` must be at least `min_first_dimension_decomposition`, + and both dimensions of `mat2` must be less than `max_other_dimension_decomposition`. + - For CPU devices: All relevant dimensions must be less than or equal to their respective + CPU decomposition thresholds. + - If `skip_dynamic_shape_dim_check` is True: + - Decomposition is considered for dynamic shapes as well, using a combination of + `statically_known_true` and `statically_known_false` checks to handle uncertainty. + - The same dimension and device checks apply, but allow for dynamic/static uncertainty. + - Returns False if any of the above conditions are not met. + Notes: + - Relies on helper functions such as `is_node_meta_valid`, `check_device`, `statically_known_true`, + and `statically_known_false`, as well as configuration values like + `min_first_dimension_decomposition`, `max_other_dimension_decomposition`, etc. + - Designed for use in graph optimization or fusion passes where decomposing large or dynamic + matrix multiplications can improve performance or memory usage. + """ + if is_node_meta_valid(mat1) and is_node_meta_valid(mat2): + mat1 = mat1.meta["val"] + mat2 = mat2.meta["val"] + else: + return False + if len(mat1.shape) != 2 or len(mat2.shape) != 2: + return False + # case 1: we skip decompose mm if the input is dynamic shape + if not config.post_grad_fusion_options["decompose_mm_pass"].get( + "skip_dynamic_shape_dim_check", False + ): + return ( + ( + check_device(mat1, mat2, device="cuda") + or check_device(mat1, mat2, device="xpu") + ) + and statically_known_true( + mat1.shape[0] >= min_first_dimension_decomposition + ) + and statically_known_true(mat2.shape[0] < max_other_dimension_decomposition) + and statically_known_true(mat2.shape[1] < max_other_dimension_decomposition) + ) or ( + check_device(mat1, mat2, device="cpu") + and statically_known_true( + mat1.shape[0] <= cpu_max_first_dimension_decomposition + ) + and statically_known_true( + mat2.shape[0] <= cpu_max_other_dimension_decomposition + ) + and statically_known_true( + mat2.shape[1] <= cpu_max_other_dimension_decomposition + ) + ) + # case 2: we decompose mm if the input is dynamic shape + else: + return ( + ( + check_device(mat1, mat2, device="cuda") + or check_device(mat1, mat2, device="xpu") + ) + and ( + statically_known_true( + mat1.shape[0] >= min_first_dimension_decomposition + ) + or not statically_known_false( + mat1.shape[0] >= min_first_dimension_decomposition + ) + ) + and ( + statically_known_true(mat2.shape[0] < max_other_dimension_decomposition) + or not statically_known_false( + mat2.shape[0] < max_other_dimension_decomposition + ) + ) + and ( + statically_known_true(mat2.shape[1] < max_other_dimension_decomposition) + or not statically_known_false( + mat2.shape[1] < max_other_dimension_decomposition + ) + ) + ) or ( + check_device(mat1, mat2, device="cpu") + and ( + statically_known_true( + mat1.shape[0] <= cpu_max_first_dimension_decomposition + ) + or not statically_known_false( + mat1.shape[0] <= cpu_max_first_dimension_decomposition + ) + ) + and ( + statically_known_true( + mat2.shape[0] <= cpu_max_other_dimension_decomposition + ) + or not statically_known_false( + mat2.shape[0] <= cpu_max_other_dimension_decomposition + ) + ) + and ( + statically_known_true( + mat2.shape[1] <= cpu_max_other_dimension_decomposition + ) + or not statically_known_false( + mat2.shape[1] <= cpu_max_other_dimension_decomposition + ) + ) + ) + + +def print_decompose_pattern(match: Match, inputs: list[torch.fx.Node]): + node = match.nodes[-1] + log.debug( + "Decompose %s with input shape: %s", + node.target, + ", ".join( + str(input.meta["val"].shape) if "val" in input.meta else "None" + for input in inputs + ), + ) + + +@register_graph_pattern( + CallFunction(aten.bmm, Arg(), Arg()), + pass_dict=construct_pattern_matcher_pass("decompose_mm_pass"), +) +def decompose_bmm(match: Match, mat1: torch.fx.Node, mat2: torch.fx.Node): + def repl(mat1, mat2): + return torch.sum(mat1[:, :, :, None] * mat2[:, None, :, :], dim=-2).to( + mat1.dtype + ) + + if should_decompose_bmm(mat1, mat2): + counters["inductor"]["decompose_bmm"] += 1 + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(repl, [mat1, mat2]) + print_decompose_pattern(match, [mat1, mat2]) + realize_inputs([mat1, mat2]) + return + + +@register_graph_pattern( + CallFunction(aten.addmm, Arg(), Arg(), Arg()), + pass_dict=construct_pattern_matcher_pass("decompose_mm_pass"), +) +def decompose_addmm( + match: Match, + mat1: torch.fx.Node, + mat2: torch.fx.Node, + mat3: torch.fx.Node, +): + def repl(mat1, mat2, mat3): + return ( + torch.sum(mat2[:, :, None] * mat3[None, :, :], dim=-2).to(mat2.dtype) + mat1 + ) + + if should_decompose_mm(mat2, mat3): + counters["inductor"]["decompose_addmm"] += 1 + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(repl, [mat1, mat2, mat3]) + print_decompose_pattern(match, [mat1, mat2, mat3]) + realize_inputs([mat1, mat2, mat3]) + return + + +@register_graph_pattern( + CallFunction(aten.mm, Arg(), Arg()), + pass_dict=construct_pattern_matcher_pass("decompose_mm_pass"), +) +def decompose_mm( + match: Match, + mat1: torch.fx.Node, + mat2: torch.fx.Node, +): + def repl(mat1, mat2): + return torch.sum(mat1[:, :, None] * mat2[None, :, :], dim=-2).to(mat1.dtype) + + if should_decompose_mm(mat1, mat2): + counters["inductor"]["decompose_mm"] += 1 + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(repl, [mat1, mat2]) + print_decompose_pattern(match, [mat1, mat2]) + realize_inputs([mat1, mat2]) + return diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/dedupe_symint_uses.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/dedupe_symint_uses.py new file mode 100644 index 0000000000000000000000000000000000000000..7b431c2f17117ae0c9e570072759a72417711562 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/dedupe_symint_uses.py @@ -0,0 +1,81 @@ +# mypy: allow-untyped-defs +from dataclasses import dataclass +from typing import Any + +import torch +from torch import SymBool, SymFloat, SymInt +from torch.types import py_sym_types +from torch.utils._ordered_set import OrderedSet + + +@dataclass +class _SymExprHash: + """ + Hash for a py_sym_types that will use the underlying sympy expression + """ + + sym_obj: SymInt | SymFloat | SymBool + + def __hash__(self) -> int: + return hash((type(self.sym_obj), self.sym_obj.node.expr)) + + def __eq__(self, value) -> bool: + if not isinstance(value, _SymExprHash): + return False + return self.sym_obj.node.expr == value.sym_obj.node.expr + + +class _SymHashingDict: + """ + Wrapper around a dictionary that will convert sym types to hash with _SymExprHash and reuse + existing sym proxies. + + SymPy hash is not always reliable so optimistically hash sympy expression, and if those fail, + fallback to symnodes. + """ + + def __init__(self): + self.sym_hash_dict = {} + + def __setitem__(self, key, value): + self.sym_hash_dict.__setitem__(self._wrap_to_sym_expr_hash(key), value) + + def __getitem__(self, key): + return self.sym_hash_dict[self._wrap_to_sym_expr_hash(key)] + + def __contains__(self, key): + return self._wrap_to_sym_expr_hash(key) in self.sym_hash_dict + + def get(self, key, default=None): + return self.sym_hash_dict.get(self._wrap_to_sym_expr_hash(key), default) + + def _wrap_to_sym_expr_hash(self, key): + return _SymExprHash(key) if isinstance(key, py_sym_types) else key + + +def dedupe_symints(graph: torch.fx.Graph): + """ + Dedupes sym ints in the graph to nodes are resolvable to symint graph inputs. + + We only dedupe from graph inputs to avoid adding a potential dependency in the forward + from the backward. + + """ + + sym_dict = _SymHashingDict() + resolvable_from_input_symints = OrderedSet[Any]() + + for node in graph.nodes: + val = node.meta.get("val", None) + if val is None or not isinstance(val, py_sym_types): + continue + + if node.op == "placeholder": + resolvable_from_input_symints.add(node) + sym_dict[val] = node + elif existing_node := sym_dict.get(val): + node.replace_all_uses_with(existing_node) + graph.erase_node(node) + elif all(n in resolvable_from_input_symints for n in node.all_input_nodes): + sym_dict[val] = node + resolvable_from_input_symints.add(node) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/efficient_conv_bn_eval.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/efficient_conv_bn_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..f85d931821022f7aa9f5606e57137dd70d6fa53c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/efficient_conv_bn_eval.py @@ -0,0 +1,445 @@ +# mypy: allow-untyped-defs +import inspect + +import torch +import torch.nn as nn +from torch._dynamo.utils import counters +from torch._inductor import config as inductor_config +from torch.func import functional_call + +from ..pattern_matcher import ( + CallFunctionVarArgs, + CallModuleVarArgs, + Match, + register_graph_pattern, +) +from .pre_grad import efficient_conv_bn_eval_pass + + +# Cache the signature of F.batch_norm at module load time to avoid repeated +# introspection during graph transformation (fixes performance regression). +_BATCH_NORM_SIGNATURE = inspect.signature(torch.nn.functional.batch_norm) + + +def efficient_conv_bn_eval( + bn: nn.modules.batchnorm._BatchNorm, conv: nn.modules.conv._ConvNd, x: torch.Tensor +): + """ + Implementation based on https://arxiv.org/abs/2305.11624 + "Efficient ConvBN Blocks for Transfer Learning and Beyond" + It leverages the associative law between convolution and affine transform, + i.e., normalize (weight conv feature) = (normalize weight) conv feature. + It works for Eval mode of ConvBN blocks during validation, and can be used + for **training** as well, but only if one sets `bn.training=False`. It + reduces memory footprint and computation cost, at the cost of slightly + reduced numerical stability. + Args: + bn (nn.modules.batchnorm._BatchNorm): a BatchNorm module. + conv (nn.modules.conv._ConvNd): a conv module + x (torch.Tensor): Input feature map. + """ + + if bn.running_var is None: + raise AssertionError("expected bn.running_var to not be None") + if bn.running_mean is None: + raise AssertionError("expected bn.running_mean to not be None") + + # These lines of code are designed to deal with various cases + # like bn without affine transform, and conv without bias + weight_on_the_fly = conv.weight + if conv.bias is not None: + bias_on_the_fly = conv.bias + else: + bias_on_the_fly = torch.zeros_like(bn.running_var) + + if bn.weight is not None: + bn_weight = bn.weight + else: + bn_weight = torch.ones_like(bn.running_var) + + if bn.bias is not None: + bn_bias = bn.bias + else: + bn_bias = torch.zeros_like(bn.running_var) + + # shape of [C_out, 1, 1, 1] in Conv2d + target_shape = [-1] + [1] * (conv.weight.ndim - 1) + if isinstance(conv, nn.modules.conv._ConvTransposeNd): + # for transposed conv, the C_out dimension should be at index 1. + target_shape[:2] = [target_shape[1], target_shape[0]] + weight_coeff = torch.rsqrt(bn.running_var + bn.eps).reshape(target_shape) + # shape of [C_out, 1, 1, 1] in Conv2d + coefff_on_the_fly = bn_weight.view_as(weight_coeff) * weight_coeff + + # shape of [C_out, C_in, k, k] in Conv2d + weight_on_the_fly = weight_on_the_fly * coefff_on_the_fly + # shape of [C_out] in Conv2d + bias_on_the_fly = bn_bias + coefff_on_the_fly.flatten() * ( + bias_on_the_fly - bn.running_mean + ) + + input = x + params = {"weight": weight_on_the_fly, "bias": bias_on_the_fly} + output = functional_call(conv, params, input) + return output + + +def efficient_conv_bn_eval_decomposed( + bn_weight, + bn_bias, + bn_running_mean, + bn_running_var, + bn_eps, + conv: torch._ops.OpOverload, + conv_weight, + conv_bias, + x, + conv_remaining_args, +): + """ + Implementation based on https://arxiv.org/abs/2305.11624 + "Efficient ConvBN Blocks for Transfer Learning and Beyond" + It leverages the associative law between convolution and affine transform, + i.e., normalize (weight conv feature) = (normalize weight) conv feature. + It works for Eval mode of ConvBN blocks during validation, and can be used + for **training** as well, but only if one sets `bn.training=False`. It + reduces memory footprint and computation cost, at the cost of slightly + reduced numerical stability. + Args: + """ + if bn_running_var is None: + raise AssertionError("expected bn_running_var to not be None") + + # These lines of code are designed to deal with various cases + # like bn without affine transform, and conv without bias + weight_on_the_fly = conv_weight + if conv_bias is not None: + bias_on_the_fly = conv_bias + else: + bias_on_the_fly = torch.zeros_like(bn_running_var) + + if bn_weight is None: + bn_weight = torch.ones_like(bn_running_var) + + if bn_bias is None: + bn_bias = torch.zeros_like(bn_running_var) + + # shape of [C_out, 1, 1, 1] in Conv2d + target_shape = [-1] + [1] * (conv_weight.ndim - 1) + if "conv_transpose" in conv.__str__(): + # for transposed conv, the C_out dimension should be at index 1. + target_shape[:2] = [target_shape[1], target_shape[0]] + weight_coeff = torch.rsqrt(bn_running_var + bn_eps).reshape(target_shape) + # shape of [C_out, 1, 1, 1] in Conv2d + coefff_on_the_fly = bn_weight.view_as(weight_coeff) * weight_coeff + + # shape of [C_out, C_in, k, k] in Conv2d + weight_on_the_fly = weight_on_the_fly * coefff_on_the_fly + # shape of [C_out] in Conv2d + bias_on_the_fly = bn_bias + coefff_on_the_fly.flatten() * ( + bias_on_the_fly - bn_running_mean + ) + + input = x + return conv(*((input, weight_on_the_fly, bias_on_the_fly) + conv_remaining_args)) + + +@register_graph_pattern( + CallFunctionVarArgs( + [ + torch.nn.functional.batch_norm, + ] + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=efficient_conv_bn_eval_pass, + extra_check=lambda match: not inductor_config.freezing + and inductor_config.efficient_conv_bn_eval_fx_passes, +) +def efficient_conv_bn_eval_graph_transform_inlined(match: Match, *args, **kwargs): + """ + Graph transformation pass for fusing F.batch_norm with preceding conv operations. + + This pass handles F.batch_norm calls with default arguments by normalizing + the args tuple using inspect.signature. It fuses batch normalization with + the preceding convolution for more efficient evaluation. + """ + bn_node = match.nodes[0] + graph = match.graph + + # Normalize arguments by binding to cached signature and applying defaults. + # This handles cases where F.batch_norm is called with fewer than 8 args. + bound_args = _BATCH_NORM_SIGNATURE.bind(*bn_node.args, **bn_node.kwargs) + bound_args.apply_defaults() + # Use bound_args.args instead of mutating bn_node.args + normalized_args = bound_args.args + + # We can only use efficient conv-bn for eval mode with track_running_stats + # normalized_args[5] is the "training" argument + training_arg = normalized_args[5] + + # Safety check: if 'training' is a symbolic Node (from tracing/export), + # we cannot optimize since we don't know the value at compile time. + if isinstance(training_arg, torch.fx.Node): + return + + if training_arg: + return + + # Check if the input is Conv + input_node = normalized_args[0] + + if input_node.op != "call_function": # type: ignore[union-attr] + return + + input_fn = input_node.target # type: ignore[arg-type, union-attr] + supported_convs = [ + torch._C._nn.linear, + torch.conv1d, + torch.conv2d, + torch.conv3d, + torch.conv_transpose1d, + torch.conv_transpose2d, + torch.conv_transpose3d, + ] + + if not any(input_fn is cls for cls in supported_convs): + return + + conv_node = input_node + # Output of conv is used by other nodes, cannot optimize + if len(conv_node.users) > 1: # type: ignore[union-attr] + return + + counters["inductor"]["efficient_conv_bn_eval"] += 1 + + with graph.inserting_before(bn_node): + # prepare args for the fused function + bn_running_mean = normalized_args[1] + bn_running_var = normalized_args[2] + bn_weight = normalized_args[3] + bn_bias = normalized_args[4] + bn_eps = normalized_args[7] + if len(conv_node.args) < 2: # type: ignore[union-attr] + raise AssertionError( + f"expected at least 2 conv_node args, got {len(conv_node.args)}" # type: ignore[union-attr] + ) + conv_input = conv_node.args[0] # type: ignore[union-attr] + conv_weight = conv_node.args[1] # type: ignore[union-attr] + conv_bias = conv_node.args[2] if len(conv_node.args) >= 3 else None # type: ignore[union-attr] + conv_remaining_args = conv_node.args[3:] # type: ignore[union-attr] + args = ( + bn_weight, + bn_bias, + bn_running_mean, + bn_running_var, + bn_eps, + conv_node.target, # type: ignore[union-attr] + conv_weight, + conv_bias, + conv_input, + conv_remaining_args, + ) + + # create a new node + new_node = graph.create_node( + op="call_function", + target=efficient_conv_bn_eval_decomposed, + args=args, # type: ignore[arg-type] + name="efficient_conv_bn_eval", + ) + + # this node replaces the original conv + bn, and therefore + # should replace the uses of bn_node + bn_node.replace_all_uses_with(new_node) + # take care of the deletion order: + # delete bn_node first, and then conv_node + graph.erase_node(bn_node) + graph.erase_node(conv_node) # type: ignore[arg-type] + + return + + +@register_graph_pattern( + CallFunctionVarArgs( + [ + torch.ops.aten.batch_norm.default, + ] + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=efficient_conv_bn_eval_pass, + extra_check=lambda match: not inductor_config.freezing + and inductor_config.efficient_conv_bn_eval_fx_passes, +) +def efficient_conv_bn_eval_graph_transform_decomposed(match: Match, *args, **kwargs): + bn_node = match.nodes[0] + graph = match.graph + if len(bn_node.args) != 9: + raise AssertionError(f"expected 9 bn_node args, got {len(bn_node.args)}") + + # We can only use efficient conv-bn for eval mode with track_running_stats + # bn_node.args is `training` + if bn_node.args[-4]: + return + + # Check if the input is Conv + input_node = bn_node.args[0] + + if input_node.op != "call_function": # type: ignore[union-attr] + return + + input_fn = input_node.target # type: ignore[arg-type, union-attr] + supported_convs = [ + torch.ops.aten.linear.default, + torch.ops.aten.conv1d.default, + torch.ops.aten.conv2d.default, + torch.ops.aten.conv3d.default, + torch.ops.aten.conv_transpose1d.default, + torch.ops.aten.conv_transpose2d.input, + torch.ops.aten.conv_transpose3d.input, + ] + + if not any(input_fn is cls for cls in supported_convs): + return + + conv_node = input_node + # Output of conv is used by other nodes, cannot optimize + if len(conv_node.users) > 1: # type: ignore[union-attr] + return + + counters["inductor"]["efficient_conv_bn_eval"] += 1 + + with graph.inserting_before(bn_node): + # prepare args for the fused function + bn_weight = bn_node.args[1] + bn_bias = bn_node.args[2] + bn_running_mean = bn_node.args[3] + bn_running_var = bn_node.args[4] + bn_eps = bn_node.args[7] + if len(conv_node.args) < 2: # type: ignore[union-attr] + raise AssertionError( + f"expected at least 2 conv_node args, got {len(conv_node.args)}" # type: ignore[union-attr] + ) + conv_input = conv_node.args[0] # type: ignore[union-attr] + conv_weight = conv_node.args[1] # type: ignore[union-attr] + conv_bias = conv_node.args[2] if len(conv_node.args) >= 3 else None # type: ignore[union-attr] + conv_remaining_args = conv_node.args[3:] # type: ignore[union-attr] + args = ( + bn_weight, + bn_bias, + bn_running_mean, + bn_running_var, + bn_eps, + conv_node.target, # type: ignore[union-attr] + conv_weight, + conv_bias, + conv_input, + conv_remaining_args, + ) + + # create a new node + new_node = graph.create_node( + op="call_function", + target=efficient_conv_bn_eval_decomposed, + args=args, # type: ignore[arg-type] + name="efficient_conv_bn_eval", + ) + + # this node replaces the original conv + bn, and therefore + # should replace the uses of bn_node + bn_node.replace_all_uses_with(new_node) + # take care of the deletion order: + # delete bn_node first, and then conv_node + graph.erase_node(bn_node) + graph.erase_node(conv_node) # type: ignore[arg-type] + + return + + +@register_graph_pattern( + CallModuleVarArgs( + [ + nn.modules.batchnorm._BatchNorm, + nn.BatchNorm1d, + nn.BatchNorm2d, + nn.BatchNorm3d, + nn.SyncBatchNorm, + ], + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=efficient_conv_bn_eval_pass, + extra_check=lambda match: not inductor_config.freezing + and inductor_config.efficient_conv_bn_eval_fx_passes, +) +def efficient_conv_bn_eval_graph_transform(match: Match, *args, **kwargs): + # We matched a BN node + bn_node = match.nodes[0] + graph = match.graph + gm = graph.owning_module + bn_mod = getattr(gm, bn_node.target) # type: ignore[arg-type] + + # We can only use efficient conv-bn for eval mode with track_running_stats + if not bn_mod.track_running_stats or bn_mod.training: + return + + # Check if the input is Conv + if bn_node.args: + input_node = bn_node.args[0] + else: + input_node = bn_node.kwargs["input"] + if input_node.op != "call_module": # type: ignore[union-attr] + return + if not hasattr(gm, input_node.target): # type: ignore[arg-type, union-attr] + return + input_mod = getattr(gm, input_node.target) # type: ignore[arg-type, union-attr] + supported_convs = [ + nn.Linear, + nn.Conv1d, + nn.Conv2d, + nn.Conv3d, + nn.ConvTranspose1d, + nn.ConvTranspose2d, + nn.ConvTranspose3d, + ] + if not any(isinstance(input_mod, cls) for cls in supported_convs): + return + conv_node = input_node + # Output of conv is used by other nodes, cannot optimize + if len(conv_node.users) > 1: # type: ignore[union-attr] + return + + # Find a pair of conv and bn computation nodes to optimize. + counters["inductor"]["efficient_conv_bn_eval"] += 1 + + with graph.inserting_before(conv_node): # type: ignore[arg-type] + # create `get_attr` node to access modules + # note that we directly call `create_node` to fill the `name` + # argument. `graph.get_attr` and + # `graph.call_function` does not allow the `name` argument. + conv_get_node = graph.create_node( + op="get_attr", + target=conv_node.target, # type: ignore[union-attr] + name="get_conv", + ) + bn_get_node = graph.create_node( + op="get_attr", target=bn_node.target, name="get_bn" + ) + if conv_node.args: # type: ignore[union-attr] + conv_input = conv_node.args[0] # type: ignore[union-attr] + else: + conv_input = conv_node.kwargs["input"] # type: ignore[union-attr] + # prepare args for the fused function + args = (bn_get_node, conv_get_node, conv_input) + # create a new node + new_node = graph.create_node( + op="call_function", + target=efficient_conv_bn_eval, + args=args, + name="efficient_conv_bn_eval", + ) + # this node replaces the original conv + bn, and therefore + # should replace the uses of bn_node + bn_node.replace_all_uses_with(new_node) + # take care of the deletion order: + # delete bn_node first, and then conv_node + graph.erase_node(bn_node) + graph.erase_node(conv_node) # type: ignore[arg-type] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/freezing_patterns.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/freezing_patterns.py new file mode 100644 index 0000000000000000000000000000000000000000..48a940ae625fe31a4f6cb1d8b620befcdc22da4c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/freezing_patterns.py @@ -0,0 +1,313 @@ +# mypy: allow-untyped-defs +import functools + +import torch +from torch._inductor.compile_fx import fake_tensor_prop +from torch._inductor.utils import GPU_TYPES + +from ..._dynamo.utils import counters +from .. import config +from ..pattern_matcher import ( + _return_true, + CallFunction, + fwd_only, + Ignored, + init_once_fakemode, + KeywordArg, + Match, + PatternMatcherPass, + register_graph_pattern, + register_replacement, + stable_topological_sort, +) + + +aten = torch.ops.aten + +# First pass_patterns[0] are applied, then [1], then [2] +pass_patterns = [ + PatternMatcherPass(), + PatternMatcherPass(), + PatternMatcherPass(), +] + +binary_folding_pass = PatternMatcherPass() + + +def freezing_passes(gm: torch.fx.GraphModule, aot_example_inputs): + """ + Passes that are applied to the graph to freeze pass. + """ + + from ..freezing import constant_fold + + lazy_init() + # We need a few rounds of binary folding to get rid of all the + # unnecessary nodes, but may need a good method to chose the rounds number. + # works like: conv+binary+binary. + binary_folding = counters["inductor"]["binary_folding"] + fake_tensor_prop(gm, aot_example_inputs, True) + + torch._inductor.fx_passes.binary_folding.mark_mixed_dtype_allowed_computation_ops( + gm + ) + for _ in range(4): + constant_fold(gm) + # Make sure meta['val'] is properly set for all nodes + fake_tensor_prop(gm, aot_example_inputs, True) + binary_folding_pass.apply(gm.graph) # type: ignore[arg-type] + # If we don't have binary folding, we don't need to run the pass again. + # TODO: remove the need to run fake_tensor_prop on the whole model. + if counters["inductor"]["binary_folding"] == binary_folding: + break + binary_folding = counters["inductor"]["binary_folding"] + + torch._inductor.fx_passes.binary_folding.recover_original_precision_folded_computation_ops( + gm + ) + + constant_fold(gm) + fake_tensor_prop(gm, aot_example_inputs, True) + + for pattern in pass_patterns: + pattern.apply(gm.graph) # type: ignore[arg-type] + + # The CPU weight packing always assume the conv's weight is channels last, + # So make sure the layout_optimization is on when doing it. + if ( + torch._C._has_mkldnn + and config.cpp.weight_prepack + and config.layout_optimization + ): + from .mkldnn_fusion import _eliminate_duplicate_packed_nodes + + _eliminate_duplicate_packed_nodes(gm) + + stable_topological_sort(gm.graph) + gm.recompile() + gm.graph.lint() + + +@init_once_fakemode +def lazy_init(input_device: torch.device | None = None): + if torch._C._has_mkldnn and config.cpp.weight_prepack: + from .mkldnn_fusion import _mkldnn_weight_pack_init + + _mkldnn_weight_pack_init() + + from .binary_folding import binary_folding_init + + addmm_patterns_init() + binary_folding_init() + + +def register_freezing_graph_pattern(pattern, extra_check=_return_true, pass_number=0): + while pass_number > len(pass_patterns) - 1: + pass_patterns.append(PatternMatcherPass()) + return register_graph_pattern( + pattern, + extra_check=extra_check, + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[pass_number], + ) + + +def register_binary_folding_pattern(pattern, extra_check=_return_true): + return register_graph_pattern( + pattern, + extra_check=extra_check, + # pyrefly: ignore [bad-argument-type] + pass_dict=binary_folding_pass, + ) + + +@functools.cache +def addmm_patterns_init(): + """ + addmm related patterns. + To avoid duplication, also includes int8 WoQ GEMM pattern without bias. + """ + device = next( + (gpu for gpu in GPU_TYPES if getattr(torch, gpu).is_available()), "cpu" + ) + val = functools.partial(torch.empty, (10, 10), device=device, requires_grad=False) + scale = functools.partial(torch.empty, (10,), device=device, requires_grad=False) + + def check_int8_woq_concat_linear_weights(match): + is_cpu = match.kwargs["inp"].meta["val"].is_cpu + if not is_cpu or not config.cpp.enable_concat_linear: + # Currently, this pattern is only supported on CPU + return False + + weight_inputs = ["w1", "w2"] + if "w3" in match.kwargs: + weight_inputs.append("w3") + + if not all( + match.kwargs[wgt].target is torch.ops.prims.convert_element_type.default + for wgt in weight_inputs + ): + return False + + if not all( + next(iter(match.kwargs[wgt]._input_nodes.keys())).meta["val"].dtype + is torch.int8 + for wgt in weight_inputs + ): + return False + + if not all( + match.kwargs[wgt].meta["val"].dtype is torch.bfloat16 + for wgt in weight_inputs + ): + return False + + return True + + def check_concat_weights(match): + is_cpu = match.kwargs["inp"].meta["val"].is_cpu + if is_cpu and not config.cpp.enable_concat_linear: + return False + + weight_inputs = ["w1", "w2"] + if "w3" in match.kwargs: + weight_inputs.append("w3") + + equal_shape_inputs = [weight_inputs] + + if "b1" in match.kwargs: + bias_inputs = ["b1", "b2"] + if "b3" in match.kwargs: + bias_inputs.append("b3") + + equal_shape_inputs.append(bias_inputs) + + for equal_shape_group in equal_shape_inputs: + inps = [match.kwargs[name] for name in equal_shape_group] + + if not all( + inp.op == "get_attr" + and inp.meta["val"].shape[:-1] == inps[0].meta["val"].shape[:-1] + for inp in inps + ): + return False + return True + + def int8_woq_fusion_pattern(inp, w1, w2, w3, s1, s2, s3): + return ((inp @ w1) * s1, (inp @ w2) * s2, (inp @ w3) * s3) + + def int8_woq_fusion_replacement(inp, w1, w2, w3, s1, s2, s3): + cat_w = torch.cat((w1, w2, w3), dim=1) + cat_s = torch.cat((s1, s2, s3), dim=0) + mm = (inp @ cat_w).mul(cat_s) + n1, n2 = w1.size(1), w2.size(1) + return mm.tensor_split([n1, n1 + n2], dim=-1) + + register_replacement( + # pyrefly: ignore [bad-argument-type] + int8_woq_fusion_pattern, + # pyrefly: ignore [bad-argument-type] + int8_woq_fusion_replacement, + [val(), val(), val(), val(), scale(), scale(), scale()], + # pyrefly: ignore [bad-argument-type] + fwd_only, + # pyrefly: ignore [bad-argument-type] + pass_patterns[0], + extra_check=check_int8_woq_concat_linear_weights, + exclusive_arg_names=("w1", "w2", "w3", "s1", "s2", "s3"), + ) + + def matmul_fuse_pattern(inp, w1, w2, w3): + return (inp @ w1, inp @ w2, inp @ w3) + + def matmul_replacement(inp, w1, w2, w3): + weights = (w1, w2, w3) + cat_t = torch.cat(weights, dim=1) + mm = inp @ cat_t + return mm.split([w.size(1) for w in weights], dim=1) + + register_replacement( + # pyrefly: ignore [bad-argument-type] + matmul_fuse_pattern, + # pyrefly: ignore [bad-argument-type] + matmul_replacement, + [val(), val(), val(), val()], + # pyrefly: ignore [bad-argument-type] + fwd_only, + # pyrefly: ignore [bad-argument-type] + pass_patterns[0], + extra_check=check_concat_weights, + exclusive_arg_names=("w1", "w2", "w3"), + ) + + def matmul_fuse_pattern_two(inp, w1, w2): + return (inp @ w1, inp @ w2) + + def matmul_replacement_two(inp, w1, w2): + weights = (w1, w2) + cat_t = torch.cat(weights, dim=1) + mm = inp @ cat_t + return mm.split([w.size(1) for w in weights], dim=1) + + register_replacement( + # pyrefly: ignore [bad-argument-type] + matmul_fuse_pattern_two, + # pyrefly: ignore [bad-argument-type] + matmul_replacement_two, + [val(), val(), val()], + # pyrefly: ignore [bad-argument-type] + fwd_only, + # pyrefly: ignore [bad-argument-type] + pass_patterns[0], + extra_check=check_concat_weights, + exclusive_arg_names=("w1", "w2"), + ) + + def addmm_fuse_pattern_second(inp, w1, w2, w3, b1, b2, b3): + return ( + aten.addmm(b1, inp, w1), + aten.addmm(b2, inp, w2), + aten.addmm(b3, inp, w3), + ) + + def addmm_fuse_replacement_second(inp, w1, w2, w3, b1, b2, b3): + weights = (w1, w2, w3) + cat_w = torch.cat(weights, dim=1) + cat_b = torch.cat((b1, b2, b3)) + return aten.addmm(cat_b, inp, cat_w).split([w.size(1) for w in weights], dim=1) + + register_replacement( + # pyrefly: ignore [bad-argument-type] + addmm_fuse_pattern_second, + # pyrefly: ignore [bad-argument-type] + addmm_fuse_replacement_second, + [val() for _ in range(7)], + # pyrefly: ignore [bad-argument-type] + fwd_only, + # pyrefly: ignore [bad-argument-type] + pass_patterns[0], + extra_check=check_concat_weights, + exclusive_arg_names=("w1", "w2", "w3", "b1", "b2", "b3"), + ) + + +def same_dtype(match): + return match.output_node().args[0].meta["val"].dtype == match.kwargs["dtype"] + + +@register_graph_pattern( + CallFunction( + torch.ops.prims.convert_element_type.default, + Ignored(), + KeywordArg("dtype"), + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[0], + extra_check=same_dtype, +) +def unnecessary_dtype_convert(match: Match, **kwargs): + """Remove unnecessary dtype conversion op, probably left as a result of Conv-Bn folding""" + graph = match.graph + node = match.output_node() + node.replace_all_uses_with(node.args[0]) # type: ignore[arg-type] + graph.erase_node(node) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/fsdp.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/fsdp.py new file mode 100644 index 0000000000000000000000000000000000000000..12934f32a482e81726e4e7ccfbb2e15acabcf654 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/fsdp.py @@ -0,0 +1,582 @@ +import json +import logging +import math +from collections.abc import Callable + +import torch +import torch.fx as fx +from torch._inductor.fx_passes.bucketing import ( + bucket_all_gather_by_mb, + bucket_all_reduce_by_mb, + bucket_reduce_scatter_by_mb, + BucketMode, + is_all_gather_into_tensor as is_all_gather, + is_all_reduce_tensor, + merge_all_gather, + merge_all_reduce_bucket, + merge_reduce_scatter, +) +from torch._inductor.pattern_matcher import ( + CallFunction, + KeywordArg, + Match, + PatternMatcherPass, + register_graph_pattern, +) +from torch._logging import trace_structured +from torch.utils._ordered_set import OrderedSet + + +logger: logging.Logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +def is_fsdp_all_gather(n: torch.fx.Node) -> bool: + """Check if an all_gather derives from exactly one placeholder (parameter). + + Uses backward BFS to count placeholder ancestors across all input branches. + Handles multi-input chains (e.g. cat(param, zeros) for padding) that the old + single-input-chain walk would miss. + """ + if not is_all_gather(n): + raise AssertionError(f"expected an all_gather node, got {n}") + visited: OrderedSet[torch.fx.Node] = OrderedSet() + queue = list(n.all_input_nodes) + placeholders = 0 + while queue: + node = queue.pop() + if node in visited: + continue + visited.add(node) + if node.op == "placeholder": + placeholders += 1 + if placeholders > 1: + return False + else: + queue.extend(node.all_input_nodes) + return placeholders == 1 + + +def is_fsdp_all_gather_wait(wait: torch.fx.Node) -> bool: + ag_node = wait.args[0] # type: ignore[arg-type, union-attr] + return is_fsdp_all_gather(ag_node) # type: ignore[arg-type] + + +def is_fsdp_reduce_scatter_wait(wait: torch.fx.Node) -> bool: + """Check if a reduce_scatter wait flows only to graph outputs through unary ops. + + Uses forward walk to verify every path from *wait* reaches an output node and + every intermediate node is unary (single input). This is conservative: it + rejects multi-input nodes even if all inputs derive from the RS, but that is + sufficient for current FSDP2 patterns where RS→output is always a unary chain + (view/reshape/cast). + + Returns False for compiled multi-microbatch gradient accumulation where + add(existing_grad, rs_result) appears in the chain. Current FSDP2 compile + patterns don't produce this (each microbatch is compiled separately). + """ + if not wait.users: + return False + visited: OrderedSet[torch.fx.Node] = OrderedSet() + queue = [wait] + while queue: + node = queue.pop() + if node in visited: + continue + visited.add(node) + for user in node.users: + if user.op == "output": + continue + if len(user.all_input_nodes) != 1: + return False + queue.append(user) + return True + + +_LINEAR_REDUCE_OPS = OrderedSet(["sum", "avg"]) + +_dedup_rs_pass: PatternMatcherPass | None = None + + +def _get_dedup_rs_pass() -> PatternMatcherPass: + global _dedup_rs_pass + + if _dedup_rs_pass is not None: + return _dedup_rs_pass + + c10d = torch.ops._c10d_functional + aten = torch.ops.aten + dedup_rs_pass = PatternMatcherPass(pass_name="dedup_reduce_scatter") + + def wait_rs(name: str) -> CallFunction: + return CallFunction( + c10d.wait_tensor.default, + CallFunction( + c10d.reduce_scatter_tensor.default, + KeywordArg(name), + KeywordArg("reduce_op"), + KeywordArg("group_size"), + KeywordArg("group_name"), + ), + ) + + def dedup_rs_extra_check(match: Match) -> bool: + if match.kwargs["reduce_op"] not in _LINEAR_REDUCE_OPS: + return False + for node in match.nodes: + if node.target is aten.add.Tensor: + continue + if node.target not in ( + c10d.wait_tensor.default, + c10d.reduce_scatter_tensor.default, + ): + return False + if len(node.users) != 1: + return False + input_a = match.kwargs["input_a"] + input_b = match.kwargs["input_b"] + if input_a.meta["val"].dtype != input_b.meta["val"].dtype: + return False + return True + + @register_graph_pattern( + CallFunction( + aten.add.Tensor, + wait_rs("input_a"), + wait_rs("input_b"), + ), + extra_check=dedup_rs_extra_check, + # pyrefly: ignore[bad-argument-type] + pass_dict=dedup_rs_pass, + ) + def _(match: Match, input_a, input_b, reduce_op, group_size, group_name): + def repl(input_a, input_b): + combined = aten.add.Tensor(input_a, input_b) + rs = c10d.reduce_scatter_tensor.default( + combined, reduce_op, group_size, group_name + ) + return c10d.wait_tensor.default(rs) + + # pyrefly: ignore[bad-argument-type] + match.replace_by_example(repl, [input_a, input_b]) + + _dedup_rs_pass = dedup_rs_pass + return dedup_rs_pass + + +def dedup_fsdp_reduce_scatter(gm: torch.fx.GraphModule) -> None: + """ + Fuse duplicate reduce_scatter ops whose waited results are summed. + + RS is linear, so RS(a) + RS(b) = RS(a + b). This pass rewrites + rs_a = reduce_scatter(input_a, ...); wait_a = wait(rs_a) + rs_b = reduce_scatter(input_b, ...); wait_b = wait(rs_b) + result = add(wait_a, wait_b) + into + combined = add(input_a, input_b) + rs = reduce_scatter(combined, ...) + result = wait(rs) + + For N-way add trees (N > 2), the pattern is applied repeatedly + until fixpoint — each iteration fuses one leaf pair. + """ + dedup_rs_pass = _get_dedup_rs_pass() + while dedup_rs_pass.apply(gm): + pass + gm.graph.lint() + gm.recompile() + + +def bucket_fsdp_all_gather( + gm: torch.fx.GraphModule, + bucket_cap_mb_by_bucket_idx: Callable[[int], float] | None = None, + mode: BucketMode = "default", +) -> None: + """ + Bucketing pass for SimpleFSDP all_gather ops. + + Attributes: + gm (torch.fx.GraphModule): Graph module of the graph. + bucket_cap_mb_by_bucket_idx (Callable[[int], float] | None): callback function that + takes in bucket id and returns size of a bucket in megabytes. + """ + if bucket_cap_mb_by_bucket_idx is None: + from torch._inductor.fx_passes.bucketing import ( + bucket_cap_mb_by_bucket_idx_default, + ) + + bucket_cap_mb_by_bucket_idx = bucket_cap_mb_by_bucket_idx_default + if bucket_cap_mb_by_bucket_idx is None: + raise AssertionError("expected bucket_cap_mb_by_bucket_idx to be set") + ag_buckets = bucket_all_gather_by_mb( + gm, + bucket_cap_mb_by_bucket_idx, + filter_wait_node=is_fsdp_all_gather_wait, + ) + if len(ag_buckets) == 0: + return + merge_all_gather(gm, ag_buckets, mode) + + +def bucket_fsdp_reduce_scatter( + gm: torch.fx.GraphModule, + bucket_cap_mb_by_bucket_idx: Callable[[int], float] | None = None, + mode: BucketMode = "default", +) -> None: + """ + Bucketing pass for SimpleFSDP reduce_scatter ops. + + Attributes: + gm (torch.fx.GraphModule): Graph module of the graph. + bucket_cap_mb_by_bucket_idx (Callable[[int], float] | None): callback function that + takes in bucket idx and returns size of a bucket in megabytes. By default + torch._inductor.fx_passes.bucketing.bucket_cap_mb_by_bucket_idx_default is used. + + """ + if bucket_cap_mb_by_bucket_idx is None: + from torch._inductor.fx_passes.bucketing import ( + bucket_cap_mb_by_bucket_idx_default, + ) + + bucket_cap_mb_by_bucket_idx = bucket_cap_mb_by_bucket_idx_default + # reduce_scatter bucketing does not support multidtype mode; + # resolve None to the default and strip multidtype if present. + rs_bucket_mode: BucketMode = mode or "default" + if "multidtype" in rs_bucket_mode: + rs_bucket_mode = rs_bucket_mode.replace("_multidtype", "") # type: ignore[assignment] + rs_buckets = bucket_reduce_scatter_by_mb( + gm, + bucket_cap_mb_by_bucket_idx, + filter_wait_node=is_fsdp_reduce_scatter_wait, + mode=rs_bucket_mode, + ) + if len(rs_buckets) == 0: + return + merge_reduce_scatter(gm, rs_buckets, mode) + + +def bucket_fsdp_all_reduce( + gm: torch.fx.GraphModule, + bucket_cap_mb_by_bucket_idx: Callable[[int], float] | None = None, + fsdp_groups: OrderedSet[str] | None = None, +) -> None: + """Bucketing pass for FSDP all_reduce ops. + + For all_gather and reduce_scatter we use structural heuristics + (single-placeholder ancestry for AG, unary-chain-to-output for RS) + to identify FSDP collectives. For all_reduce there is no reliable + structural pattern, so we identify FSDP groups via AG/RS first and + filter by group name here. + """ + if bucket_cap_mb_by_bucket_idx is None: + from torch._inductor.fx_passes.bucketing import ( + bucket_cap_mb_by_bucket_idx_default, + ) + + bucket_cap_mb_by_bucket_idx = bucket_cap_mb_by_bucket_idx_default + + def is_fsdp_all_reduce_wait(wait: torch.fx.Node) -> bool: + ar_node = wait.args[0] + if not is_all_reduce_tensor(ar_node): # type: ignore[arg-type] + return False + if fsdp_groups is None: + return True + return _get_group_name(ar_node) in fsdp_groups # type: ignore[arg-type] + + ar_buckets = bucket_all_reduce_by_mb( + gm, bucket_cap_mb_by_bucket_idx, filter_wait_node=is_fsdp_all_reduce_wait + ) + for bucket in ar_buckets: + merge_all_reduce_bucket(gm.graph, bucket) + + +def _get_collective_kwargs(n: fx.Node) -> dict[str, object]: + """Normalize a collective node's args into keyword args.""" + from torch.fx.operator_schemas import normalize_function + + opt = normalize_function( + n.target, # type: ignore[arg-type] + args=n.args, + kwargs=n.kwargs, + normalize_to_only_use_kwargs=True, + ) + if opt is None: + raise AssertionError(f"normalize_function returned None for {n.target}") + _, kwargs = opt + return kwargs + + +def _get_group_name(n: fx.Node) -> str: + return _get_collective_kwargs(n)["group_name"] # type: ignore[return-value] + + +def _get_group_size_from_node(n: fx.Node) -> int: + return _get_collective_kwargs(n)["group_size"] # type: ignore[return-value] + + +def _find_all_gathers(graph: torch.fx.Graph) -> list[torch.fx.Node]: + """Return all all_gather nodes (both default and _out variants) via O(1) lookup.""" + return [ + *graph.find_nodes( + op="call_function", + target=torch.ops._c10d_functional.all_gather_into_tensor.default, + ), + *graph.find_nodes( + op="call_function", + target=torch.ops._c10d_functional.all_gather_into_tensor_out.default, + ), + ] + + +def _find_reduce_scatters(graph: torch.fx.Graph) -> list[torch.fx.Node]: + """Return all reduce_scatter nodes via O(1) lookup.""" + return graph.find_nodes( + op="call_function", + target=torch.ops._c10d_functional.reduce_scatter_tensor.default, + ) + + +def _find_all_reduces(graph: torch.fx.Graph) -> list[torch.fx.Node]: + """Return all all_reduce nodes via O(1) lookup.""" + return graph.find_nodes( + op="call_function", + target=torch.ops._c10d_functional.all_reduce.default, + ) + + +def identify_fsdp_groups( + gm: torch.fx.GraphModule, +) -> tuple[OrderedSet[str], int | None]: + """Identify FSDP process groups and return (group_names, group_size). + + Uses is_fsdp_all_gather heuristic on all_gather nodes to find FSDP groups, + then returns those group names plus the group_size from the first match. + All collectives on these groups (AG, RS, AR) are considered FSDP via + group-name transitivity. + """ + fsdp_groups: OrderedSet[str] = OrderedSet() + group_size: int | None = None + for n in _find_all_gathers(gm.graph): + if is_fsdp_all_gather(n): + fsdp_groups.add(_get_group_name(n)) + if group_size is None: + group_size = _get_group_size_from_node(n) + return fsdp_groups, group_size + + +def compute_pre_bucket_cap_mb( + group_size: int, + bucket_cap_mb_override: float | None = None, +) -> float: + """Compute the bucket cap for pre-bucketing based on bandwidth saturation. + + Returns a bucket size in MB that targets saturation of the process group's + network bandwidth. Uses empirical per-interconnect profiles with auto-detection + of GPU generation and intra/inter-node topology. + + If bucket_cap_mb_override is set, returns that directly. + """ + if bucket_cap_mb_override is not None: + return bucket_cap_mb_override + + import torch._inductor.config as inductor_config + + dist_opts = inductor_config.aten_distributed_optimizations + cal_mult = ( + dist_opts.pre_bucketing_fsdp_collectives_saturation_calibration_multiplier + ) + floor_mb = dist_opts.pre_bucketing_fsdp_collectives_min_bucket_cap_mb + ceil_mb = dist_opts.pre_bucketing_fsdp_collectives_max_bucket_cap_mb + + min_bytes = 0 + try: + from torch._inductor.comm_analysis import ( + compute_min_saturation_bytes, # pyrefly: ignore [missing-module-attribute] + NCCL_COLL, + ) + + min_bytes = compute_min_saturation_bytes( + group_size, NCCL_COLL.ALL_GATHER, target_efficiency=0.9 + ) + cap_mb = cal_mult * min_bytes / (1024 * 1024) + except ImportError: + cap_mb = floor_mb + cap_mb = max(floor_mb, min(ceil_mb, cap_mb)) + + if dist_opts.pre_bucketing_fsdp_collectives_verbose: + try: + from torch._inductor.comm_analysis import ( + detect_interconnect, # pyrefly: ignore [missing-module-attribute] + get_inter_node_bw, # pyrefly: ignore [missing-module-attribute] + get_intra_node_bw, # pyrefly: ignore [missing-module-attribute] + ) + + logger.info( + "pre_bucket_cap: interconnect=%s intra_bw=%.0f inter_bw=%.0f " + "saturation_bytes=%d (%.1f MB) cal_mult=%.2f cap_mb=%.1f", + detect_interconnect(group_size).name, + get_intra_node_bw(), + get_inter_node_bw(), + min_bytes, + min_bytes / (1024 * 1024), + cal_mult, + cap_mb, + ) + except ImportError: + logger.info("pre_bucket_cap: cap_mb=%.1f (fallback)", cap_mb) + + return cap_mb + + +def _tensor_size_mb(val: torch.Tensor) -> float: + """Return tensor size in MB, using size hints for dynamic shapes.""" + from torch.fx.experimental.symbolic_shapes import optimization_hint + + numel = optimization_hint(val.numel(), fallback=0) + return numel * val.element_size() / (1024 * 1024) + + +def _collect_collective_sizes( + gm: torch.fx.GraphModule, fsdp_groups: OrderedSet[str] +) -> list[dict[str, object]]: + """Collect per-collective transfer sizes (MB) for FSDP collectives in graph order. + + AG: output tensor size (the gathered result, i.e. bytes on the wire). + RS: input tensor size (the pre-scatter tensor, i.e. bytes on the wire). + AR: input tensor size (in-place, same size in and out). + """ + sizes: list[dict[str, object]] = [] + for n in _find_all_gathers(gm.graph): + if _get_group_name(n) in fsdp_groups: + size_mb = _tensor_size_mb(n.meta["val"]) + sizes.append({"type": "AG", "size_mb": round(size_mb, 3), "name": n.name}) + for n in _find_reduce_scatters(gm.graph): + if _get_group_name(n) in fsdp_groups: + size_mb = _tensor_size_mb(n.all_input_nodes[0].meta["val"]) + sizes.append({"type": "RS", "size_mb": round(size_mb, 3), "name": n.name}) + for n in _find_all_reduces(gm.graph): + if _get_group_name(n) in fsdp_groups: + size_mb = _tensor_size_mb(n.all_input_nodes[0].meta["val"]) + sizes.append({"type": "AR", "size_mb": round(size_mb, 3), "name": n.name}) + return sizes + + +def pre_bucket_fsdp_collectives( + gm: torch.fx.GraphModule, + mode: BucketMode | None = None, + bucket_cap_mb: float | None = None, +) -> None: + """Pre-bucket FSDP collectives before overlap scheduling. + + Identifies FSDP process groups via all_gather structural heuristics, + then merges all_gather, reduce_scatter, and all_reduce ops on those + groups into bandwidth-saturating buckets. + """ + import torch._inductor.config as inductor_config + + dist_opts = inductor_config.aten_distributed_optimizations + verbose = dist_opts.pre_bucketing_fsdp_collectives_verbose + + fsdp_groups, group_size = identify_fsdp_groups(gm) + if not fsdp_groups: + return + + def _count_fsdp(nodes: list[fx.Node]) -> int: + return sum(1 for n in nodes if _get_group_name(n) in fsdp_groups) + + ag_count = _count_fsdp(_find_all_gathers(gm.graph)) + rs_count = _count_fsdp(_find_reduce_scatters(gm.graph)) + ar_count = _count_fsdp(_find_all_reduces(gm.graph)) + + if verbose: + coll_sizes = _collect_collective_sizes(gm, fsdp_groups) + logger.info( + "pre_bucket_fsdp: %d collectives before bucketing, sizes (MB): %s", + len(coll_sizes), + ", ".join(f"{s['type']}({s['size_mb']})" for s in coll_sizes[:50]), + ) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "pre_bucketing_collective_sizes", + "encoding": "json", + }, + payload_fn=lambda: json.dumps(coll_sizes), + ) + + if group_size is not None: + cap_mb = compute_pre_bucket_cap_mb(group_size, bucket_cap_mb) + else: + # Reachable when fsdp_groups were identified from all-gathers that + # were subsequently erased by an earlier pass, or when only RS/AR remain. + logger.warning("pre_bucket_fsdp: no FSDP all_gather found for group_size") + cap_mb = bucket_cap_mb if bucket_cap_mb is not None else 500.0 + + def bucket_cap_fn(_idx: int) -> float: + return cap_mb + + resolved_mode: BucketMode = mode or "default" + bucket_fsdp_all_gather( + gm, bucket_cap_mb_by_bucket_idx=bucket_cap_fn, mode=resolved_mode + ) + bucket_fsdp_reduce_scatter( + gm, bucket_cap_mb_by_bucket_idx=bucket_cap_fn, mode=resolved_mode + ) + bucket_fsdp_all_reduce( + gm, bucket_cap_mb_by_bucket_idx=bucket_cap_fn, fsdp_groups=fsdp_groups + ) + + ag_count_after = _count_fsdp(_find_all_gathers(gm.graph)) + rs_count_after = _count_fsdp(_find_reduce_scatters(gm.graph)) + ar_count_after = _count_fsdp(_find_all_reduces(gm.graph)) + + gpus_per_node = torch.cuda.device_count() if torch.cuda.is_available() else 8 + nNodes = math.ceil(group_size / gpus_per_node) if group_size is not None else 1 + + # Verbose: log per-collective sizes after bucketing + if verbose: + coll_sizes_after = _collect_collective_sizes(gm, fsdp_groups) + logger.info( + "pre_bucket_fsdp: %d collectives after bucketing, sizes (MB): %s", + len(coll_sizes_after), + ", ".join(f"{s['type']}({s['size_mb']})" for s in coll_sizes_after[:50]), + ) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "pre_bucketing_collective_sizes_after", + "encoding": "json", + }, + payload_fn=lambda: json.dumps(coll_sizes_after), + ) + + logger.info( + "pre_bucket_fsdp_collectives: fsdp_groups=%s, group_size=%s, nNodes=%d, " + "bucket_cap_mb=%.1f, all_gather %d->%d, reduce_scatter %d->%d, " + "all_reduce %d->%d", + list(fsdp_groups), + group_size, + nNodes, + cap_mb, + ag_count, + ag_count_after, + rs_count, + rs_count_after, + ar_count, + ar_count_after, + ) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "pre_bucketing_fsdp_collectives", + "encoding": "string", + }, + payload_fn=lambda: ( + f"fsdp_groups={list(fsdp_groups)}, group_size={group_size}, " + f"nNodes={nNodes}, bucket_cap_mb={cap_mb:.1f}, " + f"all_gather {ag_count}->{ag_count_after}, " + f"reduce_scatter {rs_count}->{rs_count_after}, " + f"all_reduce {ar_count}->{ar_count_after}" + ), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/fuse_attention.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/fuse_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..ac8046063fd0e42e906ee505baedee4f99a83613 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/fuse_attention.py @@ -0,0 +1,1513 @@ +# mypy: allow-untyped-defs +import functools +import inspect +import logging + +import torch +from torch.utils._ordered_set import OrderedSet + +from ..._dynamo.utils import counters +from ..pattern_matcher import ( + filter_nodes, + fwd_only, + gen_register_replacement, + joint_fwd_bwd, +) + + +log = logging.getLogger(__name__) +perf_hint_log = torch._logging.getArtifactLogger(__name__, "perf_hints") +aten = torch.ops.aten + +_scaled_dot_product_attention = aten.scaled_dot_product_attention + + +_INFERENCE_ONLY_SFDP_PATTERNS = frozenset( + OrderedSet( + [ + "_sfdp_pattern_13", + "_sfdp_pattern_15", + "_sfdp_pattern_17", + "_sfdp_pattern_18", + "_sfdp_pattern_19", + "_sfdp_pattern_20", + "_sfdp_pattern_21", + "_sfdp_pattern_22", + "_sfdp_pattern_23", + "_sfdp_pattern_24", + ] + ) +) + + +def _sfdp_pattern_1(query, key, value, inv_scale): + return ( + torch.matmul(query, key.transpose(-2, -1)) + .div(inv_scale) + .softmax(dim=-1) + .matmul(value) + ) + + +def _sfdp_replacement_1(query, key, value, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query, + key, + value, + attn_mask=None, + dropout_p=0.0, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_2(query, key, value, scale_factor): + return ( + torch.matmul(query, key.transpose(-2, -1)) + .mul(scale_factor) + .softmax(dim=-1) + .matmul(value) + ) + + +def _sfdp_replacement_2(query, key, value, scale_factor): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query, + key, + value, + attn_mask=None, + dropout_p=0.0, + is_causal=False, + scale=scale_factor, + ) + + +def _sfdp_pattern_3(query, key, value, inv_scale_factor, dropout_p): + return torch.nn.functional.dropout( + torch.matmul(query, key.transpose(-2, -1)) + .div(inv_scale_factor) + .softmax(dim=-1), + p=dropout_p, + ).matmul(value) + + +def _sfdp_replacement_3(query, key, value, inv_scale_factor, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query, + key, + value, + attn_mask=None, + dropout_p=dropout_p, + is_causal=False, + scale=1.0 / inv_scale_factor, + ) + + +def _sfdp_pattern_4(query, key, value, scale_factor, dropout_p): + return torch.nn.functional.dropout( + torch.matmul(query, key.transpose(-2, -1)).mul(scale_factor).softmax(dim=-1), + p=dropout_p, + ).matmul(value) + + +def _sfdp_replacement_4(query, key, value, scale_factor, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query, + key, + value, + attn_mask=None, + dropout_p=dropout_p, + is_causal=False, + scale=scale_factor, + ) + + +def _sfdp_pattern_5(query, key, value, attn_mask, inv_scale): + attn_weight = torch.softmax( + (query @ key.transpose(-2, -1) / (inv_scale)) + attn_mask, dim=-1 + ) + # attn_weight = torch.dropout(attn_weight, dropout_p) + return attn_weight @ value + + +def _sfdp_replacement_5(query, key, value, attn_mask, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query, + key, + value, + attn_mask=attn_mask.to(dtype=query.dtype), + dropout_p=0.0, + scale=1.0 / inv_scale, + is_causal=False, + ) + + +def _sfdp_pattern_6(query, key, value, attn_mask, inv_scale, dropout_p): + attn_weight = torch.softmax( + (query @ key.transpose(-2, -1) / inv_scale) + attn_mask, dim=-1 + ) + attn_weight = torch.dropout(attn_weight, dropout_p, True) + return attn_weight @ value + + +def _sfdp_replacement_6(query, key, value, attn_mask, inv_scale, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query, + key, + value, + attn_mask=attn_mask.to(dtype=query.dtype), + dropout_p=dropout_p, + scale=1.0 / inv_scale, + is_causal=False, + ) + + +def _sfdp_pattern_7(query, key, value, inv_scale, dropout_p): + # in real workloads inputs to matmul are permuted + # causing matmul to expand to a series of expand and clone calls + # we want the same to happen during pattern tracing + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + div = q @ k.transpose(-2, -1) / inv_scale + div = div.to(torch.float32) + attn_weight = torch.softmax(div, dim=-1) + attn_weight = torch.dropout(attn_weight, dropout_p, True) + attn_weight = attn_weight.to(torch.float16) + v = v.to(attn_weight.dtype) + return attn_weight @ v + + +def _sfdp_replacement_7(query, key, value, inv_scale, dropout_p): + # sdpa prefers inputs in permuted format + # it makes a copy to put them in this format + # if they aren't already + # to make replacement efficient ensure that inputs to sdpa + # are in required order + counters["inductor"]["fuse_attention"] += 1 + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + return _scaled_dot_product_attention( + q, + k, + v, + attn_mask=None, # attn_mask, + dropout_p=dropout_p, + scale=1.0 / inv_scale, + is_causal=False, + ) + + +def _sfdp_pattern_8(query, key, value, inv_scale): + # no dropout version of pattern 7 + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + div = q @ k.transpose(-2, -1) / inv_scale + div = div.to(torch.float32) + attn_weight = torch.softmax(div, dim=-1) + attn_weight = attn_weight.to(torch.float16) + v = v.to(attn_weight.dtype) + return attn_weight @ v + + +def _sfdp_replacement_8(query, key, value, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + return _scaled_dot_product_attention( + q, + k, + v, + attn_mask=None, # attn_mask, + dropout_p=0.0, + scale=1.0 / inv_scale, + is_causal=False, + ) + + +def _sfdp_pattern_9(query, key, value, inv_scale, dropout_p): + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + q = q / inv_scale + div = q @ k.transpose(-2, -1) + div = div.to(torch.float32) + attn_weight = torch.softmax(div, dim=-1) + attn_weight = torch.dropout(attn_weight, dropout_p, True) + attn_weight = attn_weight.to(torch.float16) + v = v.to(attn_weight.dtype) + return attn_weight @ v + + +def _sfdp_replacement_9(query, key, value, inv_scale, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + return _scaled_dot_product_attention( + q, + k, + v, + attn_mask=None, # attn_mask, + dropout_p=dropout_p, + scale=1.0 / inv_scale, + is_causal=False, + ) + + +def _sfdp_pattern_10(query, key, value, inv_scale): + # no dropout version of 9 + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + q = q / inv_scale + div = q @ k.transpose(-2, -1) + div = div.to(torch.float32) + attn_weight = torch.softmax(div, dim=-1) + attn_weight = attn_weight.to(torch.float16) + v = v.to(attn_weight.dtype) + return attn_weight @ v + + +def _sfdp_replacement_10(query, key, value, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + return _scaled_dot_product_attention( + q, + k, + v, + attn_mask=None, # attn_mask, + dropout_p=0.0, + scale=1.0 / inv_scale, + is_causal=False, + ) + + +def _sfdp_pattern_11(query, key, value, inv_scale): + # Mainly for huggingface models + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + return torch.matmul(q, k.transpose(-2, -1)).div(inv_scale).softmax(dim=-1).matmul(v) + + +def _sfdp_replacement_11(query, key, value, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=None, + dropout_p=0.0, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_12(query, key, value, inv_scale_factor, dropout_p): + q = query.permute(0, 2, 1, 3) + k = key.permute(0, 2, 1, 3) + v = value.permute(0, 2, 1, 3) + return torch.nn.functional.dropout( + torch.matmul(q, k.transpose(-2, -1)).div(inv_scale_factor).softmax(dim=-1), + p=dropout_p, + ).matmul(v) + + +def _sfdp_replacement_12(query, key, value, inv_scale_factor, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=None, + dropout_p=dropout_p, + is_causal=False, + scale=1.0 / inv_scale_factor, + ) + + +def _sfdp_pattern_13(query, key, value, dropout_p): + attn_weight = torch.bmm(query, key.transpose(1, 2)).softmax(dim=-1) + attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p) + return torch.bmm(attn_weight, value) + + +def _sfdp_replacement_13(query, key, value, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query.unsqueeze(0), + key.unsqueeze(0), + value.unsqueeze(0), + dropout_p=dropout_p, + scale=1.0, + ).squeeze(0) + + +def _sfdp_pattern_14(query, key, value, attn_mask, inv_scale): + # for BertLarge + # Permutations are needed to create clones in graph. + q = query.permute([0, 2, 1, 3]) + k = key.permute([0, 2, 1, 3]) + v = value.permute([0, 2, 1, 3]) + return ( + (torch.matmul(q, k.transpose(-2, -1)).div(inv_scale) + attn_mask) + .softmax(dim=-1) + .matmul(v) + ) + + +def _sfdp_replacement_14(query, key, value, attn_mask, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=attn_mask.to(dtype=query.dtype), + dropout_p=0.0, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_15(query, key, value, attn_mask, inv_scale): + # for DistilBert + # Permutations are needed to create clones in graph. + # Ref: https://github.com/pytorch/pytorch/issues/119911 + q = query.permute([0, 2, 1, 3]) + k = key.permute([0, 2, 1, 3]) + v = value.permute([0, 2, 1, 3]) + bs = q.size(0) + k_len = k.size(-2) + scores = q @ k.transpose(-2, -1) + scores = scores.div(inv_scale) + fill_value = torch.full((), -float("inf"), dtype=query.dtype, device=query.device) + attn_mask = (attn_mask == 0).view((bs, 1, 1, k_len)).expand_as(scores) + return torch.softmax(scores.masked_fill(attn_mask, fill_value), dim=-1) @ v + + +def _sfdp_replacement_15(query, key, value, attn_mask, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + bs = query.size(0) + n_head = query.size(2) + q_len = query.size(1) + k_len = key.size(1) + # do attn_mask->logical_not() in _scaled_dot_product_attention + attn_mask = ( + (attn_mask == 1).view((bs, 1, 1, k_len)).expand((bs, n_head, q_len, k_len)) + ) + return _scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=attn_mask.to(dtype=torch.bool), + dropout_p=0.0, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_16(query, key, value, attn_mask, inv_scale, dropout_p): + # for BertLarge with dropout + q = query.permute([0, 2, 1, 3]) + k = key.permute([0, 2, 1, 3]) + v = value.permute([0, 2, 1, 3]) + return ( + torch.nn.functional.dropout( + (torch.matmul(q, k.transpose(-2, -1)).div(inv_scale) + attn_mask).softmax( + dim=-1 + ), + dropout_p, + ) + .to(dtype=query.dtype) + .matmul(v) + ) + + +def _sfdp_replacement_16(query, key, value, attn_mask, inv_scale, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + query = query.transpose(1, 2) + key = key.transpose(1, 2) + value = value.transpose(1, 2) + if query.device.type == "cuda" and torch.version.hip is None: + # Keep the Bert CUDA pattern on its original math path; generic SDPA can + # pick fused backends whose scaling/dropout numerics fail tight checks. + attn_weight = torch.matmul(query, key.transpose(-2, -1)) + attn_weight = attn_weight.div(inv_scale) + attn_mask + attn_weight = attn_weight.softmax(dim=-1) + if dropout_p != 0.0: + attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p) + return attn_weight.to(dtype=query.dtype).matmul(value) + attn_mask = attn_mask.to(dtype=query.dtype) + return _scaled_dot_product_attention( + query, + key, + value, + attn_mask=attn_mask, + dropout_p=dropout_p, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_17(query, key, value, attn_mask, inv_scale, dropout_p): + # for DistilBert with dropout + q = query.permute([0, 2, 1, 3]) + k = key.permute([0, 2, 1, 3]) + v = value.permute([0, 2, 1, 3]) + bs = q.size(0) + k_len = k.size(-2) + scores = q @ k.transpose(-2, -1) + scores = scores.div(inv_scale) + fill_value = torch.full((), -float("inf"), dtype=query.dtype, device=query.device) + attn_mask = (attn_mask == 0).view((bs, 1, 1, k_len)).expand_as(scores) + return ( + torch.nn.functional.dropout( + torch.softmax(scores.masked_fill(attn_mask, fill_value), dim=-1), dropout_p + ) + @ v + ) + + +def _sfdp_replacement_17(query, key, value, attn_mask, inv_scale, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + bs = query.size(0) + n_head = query.size(2) + q_len = query.size(1) + k_len = key.size(1) + # do attn_mask->logical_not() in _scaled_dot_product_attention + attn_mask = ( + (attn_mask == 1).view((bs, 1, 1, k_len)).expand((bs, n_head, q_len, k_len)) + ) + return _scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=attn_mask.to(dtype=torch.bool), + dropout_p=dropout_p, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_18(query, key, value, causal_mask, inv_scale, dropout_p): + # for hf_GPT2 with dropout (introduces clone node) for inference + # it also returns permuted key & value + query = query.permute([0, 2, 1, 3]) + key = key.permute([0, 2, 1, 3]) + value = value.permute([0, 2, 1, 3]) + attn_weights = torch.matmul(query, key.permute(0, 1, 3, 2)) + inv_scale = torch.full( + [], + inv_scale, + dtype=attn_weights.dtype, + device=attn_weights.device, + ) + attn_weights = attn_weights.div(inv_scale) + causal_mask_value = torch.full( + (), torch.finfo(query.dtype).min, dtype=query.dtype, device=query.device + ) + attn_weights = torch.where(causal_mask, attn_weights, causal_mask_value) + return ( + ( + torch.nn.functional.dropout(attn_weights.softmax(dim=-1), dropout_p).matmul( + value + ) + ), + key, + value, + ) + + +def _sfdp_replacement_18(query, key, value, causal_mask, inv_scale, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + permuted_key = key.transpose(1, 2) + permuted_value = value.transpose(1, 2) + return ( + _scaled_dot_product_attention( + query.transpose(1, 2), + permuted_key, + permuted_value, + attn_mask=causal_mask, + dropout_p=dropout_p, + is_causal=False, + scale=1.0 / inv_scale, + ), + permuted_key, + permuted_value, + ) + + +def _sfdp_pattern_19(query, key, value, causal_mask, attn_mask, inv_scale, dropout_p): + # for token-classification+gpt2 / text-generation+gpt2 + attn_weights = torch.matmul(query, key.permute(0, 1, 3, 2)) + inv_scale = torch.full( + [], + inv_scale, + dtype=attn_weights.dtype, + device=attn_weights.device, + ) + attn_weights = attn_weights.div(inv_scale) + causal_mask_value = torch.full( + (), torch.finfo(query.dtype).min, dtype=query.dtype, device=query.device + ) + attn_weights = torch.where(causal_mask, attn_weights, causal_mask_value) + attn_weights = attn_weights + attn_mask + attn_weights = attn_weights.softmax(dim=-1).type(value.dtype) + return torch.nn.functional.dropout(attn_weights, dropout_p).matmul(value) + + +def _sfdp_replacement_19( + query, key, value, causal_mask, attn_mask, inv_scale, dropout_p +): + counters["inductor"]["fuse_attention"] += 1 + fill_value = torch.full((), -float("inf"), dtype=query.dtype, device=query.device) + attn_mask = torch.where(causal_mask, attn_mask, fill_value) + return _scaled_dot_product_attention( + query, + key, + value, + attn_mask=attn_mask, + dropout_p=dropout_p, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_20(query, key, value, attn_mask, inv_scale, dropout_p): + # for DistilBert with dropout transformers==4.44.2 + q = query.permute([0, 2, 1, 3]) + k = key.permute([0, 2, 1, 3]) + v = value.permute([0, 2, 1, 3]) + bs = q.size(0) + k_len = k.size(-2) + q = q.div(inv_scale) + scores = q @ k.transpose(-2, -1) + fill_value = torch.full((), -float("inf"), dtype=query.dtype, device=query.device) + attn_mask = (attn_mask == 0).view((bs, 1, 1, k_len)).expand_as(scores) + return ( + torch.nn.functional.dropout( + torch.softmax(scores.masked_fill(attn_mask, fill_value), dim=-1), dropout_p + ) + @ v + ) + + +def _sfdp_replacement_20(query, key, value, attn_mask, inv_scale, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + bs = query.size(0) + n_head = query.size(2) + q_len = query.size(1) + k_len = key.size(1) + # do attn_mask->logical_not() in _scaled_dot_product_attention + attn_mask = ( + (attn_mask == 1).view((bs, 1, 1, k_len)).expand((bs, n_head, q_len, k_len)) + ) + return _scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=attn_mask.to(dtype=torch.bool), + dropout_p=dropout_p, + is_causal=False, + scale=1.0 / inv_scale, + ) + + +def _sfdp_pattern_21(query, key, value, attn_mask): + # for T5 with inplace add + query = query.permute([0, 2, 1, 3]) + key = key.permute([0, 2, 1, 3]) + value = value.permute([0, 2, 1, 3]) + score = torch.matmul(query, key.permute(0, 1, 3, 2)) + masked_score = score + attn_mask + score = masked_score.type_as(query) + return score.float().softmax(dim=-1).type_as(query).matmul(value) + + +def _sfdp_replacement_21(query, key, value, attn_mask): + counters["inductor"]["fuse_attention"] += 1 + query = query.permute(0, 2, 1, 3) + key = key.permute(0, 2, 1, 3) + value = value.permute(0, 2, 1, 3) + return _scaled_dot_product_attention( + query, + key, + value, + attn_mask=attn_mask.to(dtype=query.dtype), + is_causal=False, + scale=1.0, + ) + + +def _sfdp_pattern_22(query, key, value, attn_mask): + # for T5 with inplace add and return key and value + query = query.permute([0, 2, 1, 3]) + key = key.permute([0, 2, 1, 3]) + value = value.permute([0, 2, 1, 3]) + score = torch.matmul(query, key.permute(0, 1, 3, 2)) + masked_score = score + attn_mask + score = masked_score.type_as(query) + return score.float().softmax(dim=-1).type_as(query).matmul(value), key, value + + +def _sfdp_replacement_22(query, key, value, attn_mask): + counters["inductor"]["fuse_attention"] += 1 + query = query.permute(0, 2, 1, 3) + key = key.permute(0, 2, 1, 3) + value = value.permute(0, 2, 1, 3) + return ( + _scaled_dot_product_attention( + query, + key, + value, + attn_mask=attn_mask.to(dtype=query.dtype), + is_causal=False, + scale=1.0, + ), + key, + value, + ) + + +def _sfdp_pattern_23(query, key, value): + # for T5 with inplace add and + # return key and value and + # attn_mask is generated by atem.full(..., 0) + query = query.permute([0, 2, 1, 3]) + key = key.permute([0, 2, 1, 3]) + value = value.permute([0, 2, 1, 3]) + score = torch.matmul(query, key.permute(0, 1, 3, 2)) + fp32_score = score.float() + score = fp32_score.type_as(query) + return score.float().softmax(dim=-1).type_as(query).matmul(value), key, value + + +def _sfdp_replacement_23(query, key, value): + counters["inductor"]["fuse_attention"] += 1 + query = query.permute(0, 2, 1, 3) + key = key.permute(0, 2, 1, 3) + value = value.permute(0, 2, 1, 3) + return ( + _scaled_dot_product_attention( + query, + key, + value, + attn_mask=None, + is_causal=False, + scale=1.0, + ), + key, + value, + ) + + +def _sfdp_pattern_24(query, key, value, attention_mask): + """ + this pattern is for MBartForCausalLM/PLBartForCausalLM. + attn_mask has a different dtype with QKV. + there is no scale in sdpa. + """ + bs = query.size(0) + n_head = query.size(1) + seq_len = query.size(2) + head_size = query.size(3) + q = query.view(bs * n_head, -1, head_size) + k = key.reshape(bs * n_head, -1, head_size) + v = value.reshape(bs * n_head, -1, head_size) + attn_weights = torch.bmm(q, k.transpose(1, 2)) + attn_weights = attn_weights.view(bs, n_head, seq_len, -1) + attention_mask + attn_weights = attn_weights.view(bs * n_head, seq_len, -1) + attn_weights = torch.nn.functional.softmax(attn_weights, dim=-1) + if query.dtype == torch.half: + attn_weights = attn_weights.to(torch.half) + attn_output = torch.bmm(attn_weights, v) + attn_output = attn_output.view(bs, n_head, seq_len, head_size) + return attn_output + + +def _sfdp_replacement_24(query, key, value, attention_mask): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query, + key, + value, + attn_mask=attention_mask.to(dtype=query.dtype), + is_causal=False, + scale=1, + ) + + +def _sfdp_pattern_25(query, key, value, attn_mask, dropout_p): + # for T5 with inplace add + query = query.permute([0, 2, 1, 3]) + key = key.permute([0, 2, 1, 3]) + value = value.permute([0, 2, 1, 3]) + score = torch.matmul(query, key.permute(0, 1, 3, 2)) + masked_score = score + attn_mask + return torch.nn.functional.dropout( + masked_score.float().softmax(dim=-1).type_as(query), dropout_p + ).matmul(value) + + +def _sfdp_replacement_25(query, key, value, attn_mask, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + query = query.permute(0, 2, 1, 3) + key = key.permute(0, 2, 1, 3) + value = value.permute(0, 2, 1, 3) + if attn_mask.device.type == "xpu": + attn_mask = attn_mask.contiguous() + return _scaled_dot_product_attention( + query, + key, + value, + attn_mask=attn_mask, + dropout_p=dropout_p, + is_causal=False, + scale=1.0, + ) + + +def _sfdp_pattern_26(query, key, value, attn_mask, dropout_p): + # for T5 with inplace add and return key and value + query = query.permute([0, 2, 1, 3]) + key = key.permute([0, 2, 1, 3]) + value = value.permute([0, 2, 1, 3]) + score = torch.matmul(query, key.permute(0, 1, 3, 2)) + masked_score = score + attn_mask + return ( + torch.nn.functional.dropout( + masked_score.float().softmax(dim=-1).type_as(query), dropout_p + ).matmul(value), + key, + value, + ) + + +def _sfdp_replacement_26(query, key, value, attn_mask, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + query = query.permute(0, 2, 1, 3) + key = key.permute(0, 2, 1, 3) + value = value.permute(0, 2, 1, 3) + if attn_mask.device.type == "xpu": + attn_mask = attn_mask.contiguous() + return ( + _scaled_dot_product_attention( + query, + key, + value, + attn_mask=attn_mask, + dropout_p=dropout_p, + is_causal=False, + scale=1.0, + ), + key, + value, + ) + + +def _sfdp_pattern_27(query, key, value, dropout_p): + # for T5 with inplace add and + # return key and value and + # attn_mask is generated by atem.full(..., 0) + query = query.permute([0, 2, 1, 3]) + key = key.permute([0, 2, 1, 3]) + value = value.permute([0, 2, 1, 3]) + score = torch.matmul(query, key.permute(0, 1, 3, 2)) + return ( + torch.nn.functional.dropout( + score.float().softmax(dim=-1).type_as(query), dropout_p + ).matmul(value), + key, + value, + ) + + +def _sfdp_replacement_27(query, key, value, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + query = query.permute(0, 2, 1, 3) + key = key.permute(0, 2, 1, 3) + value = value.permute(0, 2, 1, 3) + return ( + _scaled_dot_product_attention( + query, + key, + value, + attn_mask=None, + dropout_p=dropout_p, + is_causal=False, + scale=1.0, + ), + key, + value, + ) + + +def _sfdp_pattern_28(query, key, value, scale_factor, dropout_p): + # Visformer pattern + # same as pattern 4 but non-contiguous q/k/v + return _sfdp_pattern_4(query, key, value, scale_factor, dropout_p) + + +def _sfdp_replacement_28(query, key, value, scale_factor, dropout_p): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query.contiguous(), + key.contiguous(), + value.contiguous(), + attn_mask=None, + dropout_p=dropout_p, + is_causal=False, + scale=scale_factor, + ) + + +def _sfdp_pattern_29(query, key, value, attn_mask, inv_scale): + # Matches _scaled_dot_product_attention_math decomposition for + # BERT-like models calling F.scaled_dot_product_attention with attn_mask. + # Scale is split as sqrt across Q and K (mul.Scalar in fp16), bmm stays + # in fp16, and _safe_softmax upcasts to fp32 internally. + # Permutations are needed to create clones in graph since real workloads + # have non-contiguous inputs from .transpose(1, 2). + q = query.permute([0, 2, 1, 3]) + k = key.permute([0, 2, 1, 3]) + v = value.permute([0, 2, 1, 3]) + q = torch.ops.aten.mul.Scalar(q, inv_scale) + k = torch.ops.aten.mul.Scalar(k.transpose(-2, -1), inv_scale) + attn_weight = (q @ k) + attn_mask + attn_weight = torch.ops.aten._safe_softmax(attn_weight, -1) + return attn_weight @ v + + +def _sfdp_replacement_29(query, key, value, attn_mask, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=attn_mask.to(dtype=query.dtype), + dropout_p=0.0, + is_causal=False, + scale=inv_scale * inv_scale, + ) + + +def _sfdp_pattern_30(query, key, value, inv_scale): + # Same as pattern 29 but without attention mask. + # Permutations are needed to create clones in graph. + q = query.permute([0, 2, 1, 3]) + k = key.permute([0, 2, 1, 3]) + v = value.permute([0, 2, 1, 3]) + q = torch.ops.aten.mul.Scalar(q, inv_scale) + k = torch.ops.aten.mul.Scalar(k.transpose(-2, -1), inv_scale) + attn_weight = q @ k + attn_weight = torch.ops.aten._safe_softmax(attn_weight, -1) + return attn_weight @ v + + +def _sfdp_replacement_30(query, key, value, inv_scale): + counters["inductor"]["fuse_attention"] += 1 + return _scaled_dot_product_attention( + query.transpose(1, 2), + key.transpose(1, 2), + value.transpose(1, 2), + attn_mask=None, + dropout_p=0.0, + is_causal=False, + scale=inv_scale * inv_scale, + ) + + +@functools.lru_cache(None) +def _warn_tf32_disabled() -> None: + if ( + torch.cuda.is_available() + and torch.backends.cuda.matmul.fp32_precision != "tf32" + and torch.cuda.get_device_capability() >= (8, 0) + ): + perf_hint_log.info( + "TensorFloat32 tensor cores for float32 matrix multiplication available but not enabled. " + "Skipping pattern matching to fused flash-attention. " + "Consider setting `torch.set_float32_matmul_precision('high')` for better performance." + ) + + +def _sfdp_params_check(match): + if not all(k in match.kwargs for k in ("query", "key", "value")): + raise AssertionError("expected query, key, value in match.kwargs") + query = match.kwargs["query"].meta["val"] + key = match.kwargs["key"].meta["val"] + value = match.kwargs["value"].meta["val"] + if not (query.dtype == key.dtype == value.dtype) or not ( + query.device == key.device == value.device + ): + return False + # fused kernels use tf32 + if ( + query.device.type == "cuda" + and query.dtype == torch.float32 + and torch.backends.cuda.matmul.fp32_precision != "tf32" + ): + _warn_tf32_disabled() + return False + + add_mask_node = filter_nodes(match.nodes, aten.add.Tensor) + # Has attn_mask add. + if len(add_mask_node) > 0: + attn_mask_node = add_mask_node[0].args[1] + # attn_mask_node may be a float/int number. + if not hasattr(attn_mask_node, "meta"): + return False + attn_mask = attn_mask_node.meta["val"] # type: ignore[union-attr] + # Make sure attn_mask.dtype == query.dtype or attn_mask.dtype == torch.bool + # attn_mask.dtype == torch.float for models like albert. + if ( + not isinstance(attn_mask, torch.Tensor) + or not ( + attn_mask.dtype == query.dtype + or attn_mask.dtype == torch.bool + or attn_mask.dtype == torch.float + ) + or query.device != attn_mask.device + # When we tensorify floats we end up turning floats + # into 0d scalar tensors. It doesn't make any sense + # to have a 0d scalar tensor attention mask so + # conveniently we can insert this check to get + # tests that erroneously passing in a float + # attention mask to fail as expected. + or attn_mask.dim() == 0 + ): + return False + return True + + +def _sfdp_pattern_13_check(match): + if not _sfdp_params_check(match): + return False + permutes = filter_nodes(match.nodes, aten.permute.default) + if len(permutes) != 1: + return False + # The serialized pattern wildcard-matches the permute dimensions. + permute_dims = permutes[0].args[1] + return isinstance(permute_dims, (list, tuple)) and tuple(permute_dims) == (0, 2, 1) + + +def _sfdp_extra_check(scale_factor_op=None, disable_cuda=False): + def fn(match): + if ( + disable_cuda + and "query" in match.kwargs + and "cuda" in str(match.kwargs["query"].meta["val"].device) + ): + return False + if scale_factor_op is not None: + scale_factor_node = filter_nodes(match.nodes, scale_factor_op)[0] + # Note: args[1] of the scale_factor_node is always the scale_factor for the current patterns. + scale_factor = scale_factor_node.args[1] + # make sure the scale_factor a float/int. SymInt? + if not isinstance(scale_factor, (float, int)): + return False + return _sfdp_params_check(match) + + return fn + + +def partialize_and_update_signature(func, **kwargs): + """ + Equivalent to functools.partial but also updates the signature on returned function + """ + original_sig = inspect.signature(func) + parameters = original_sig.parameters + + new_parameters = { + key: value for key, value in parameters.items() if key not in kwargs + } + new_sig = inspect.Signature(parameters=list(new_parameters.values())) + + partial_func = functools.partial(func, **kwargs) + + def wrapper(*args, **kwargs): + return partial_func(*args, **kwargs) + + wrapper.__signature__ = new_sig # type: ignore[attr-defined] + wrapper.__name__ = func.__name__ + + return wrapper + + +def _get_sfdp_patterns(input_device: torch.device | None = None): + from .joint_graph import patterns + + if input_device: + device = str(input_device) + else: + if torch.cuda.is_available(): + # workaround https://github.com/pytorch/pytorch/issues/97894 + device = "cuda" + elif torch.xpu.is_available(): + device = "xpu" + else: + device = "cpu" + + # sizes/values don't actually matter for initial trace + # once we get a possible match we re-trace with the actual values and verify the match still holds + g_inp = functools.partial( + torch.empty, (2, 4, 8, 16), device=device, requires_grad=True + ) + # non-contiguous input to cover more patterns. + gn_inp = functools.partial( + torch.empty_strided, + (2, 6, 16, 8), + (2304, 128, 1, 16), + device=device, + requires_grad=True, + ) + # attn_mask + b_inp = functools.partial(torch.empty, (1, 1, 8, 8), device=device) + m_inp = functools.partial(torch.empty, (2, 1, 1, 4), device=device) + # need 2d attn_mask to generate patterns with view op + m_inp_2d = functools.partial(torch.empty, (2, 4), device=device) + # inv_scale + c_inp = functools.partial(torch.tensor, 2.0, device=device) + # workaround https://github.com/pytorch/pytorch/issues/97894 + # 0.113377 is a "magic" value that lets us recover the lost input arg relationship + d = {"dropout_p": 0.113377} + s = {"inv_scale": 0.66666} + sd = {"inv_scale": 0.66666, "dropout_p": 0.113377} + + # we could also generate all these patterns in 3d.. TODO + g_3d_inp = functools.partial( + torch.empty, (1024, 128, 128), device=device, requires_grad=True + ) + + # reshape in matmul decomposition generates a clone when batch_size>1 due to the memory layout change. + # however when batch_size=1, reshape does not change the memory layout, so clone would not be generated. + # here we need to trace with input of batch_size=1 to generate a pattern graph without clone. + g_bs1_inp = functools.partial( + torch.empty, (1, 4, 8, 16), device=device, requires_grad=True + ) + m_bs1_inp = functools.partial(torch.empty, (1, 1, 1, 4), device=device) + + # For patterns with permute([0,2,1,3]) inside (e.g. BERT-like models), + # input is [B, S, H, D] and after permute becomes [B, H, S, D]. + # S must match the mask dimension (8) so Q@K^T shape [B, H, S, S] matches b(). + # gp = "generic with permute"; gp_bs1 is the batch_size=1 variant (no clone). + gp_inp = functools.partial( + torch.empty, (2, 8, 4, 16), device=device, requires_grad=True + ) + gp_bs1_inp = functools.partial( + torch.empty, (1, 8, 4, 16), device=device, requires_grad=True + ) + + # softmax will generate a dtype conversion on inputs if they are in half, + # but will not in float, so we generate a pattern for both + for dtype in [torch.float, torch.half]: + g = functools.partial(g_inp, dtype=dtype) + gn = functools.partial(gn_inp, dtype=dtype) + b = functools.partial(b_inp, dtype=dtype) + b_float = functools.partial(b_inp, dtype=torch.float) + b_bool = functools.partial(b_inp, dtype=torch.bool) + m = functools.partial(m_inp, dtype=dtype) + m_float = functools.partial(m_inp, dtype=torch.float) + m_bool = functools.partial(m_inp, dtype=torch.bool) + m_2d = functools.partial(m_inp_2d, dtype=dtype) + c = functools.partial(c_inp, dtype=dtype) + g_3d = functools.partial(g_3d_inp, dtype=dtype) + g_bs1 = functools.partial(g_bs1_inp, dtype=dtype) + gp = functools.partial(gp_inp, dtype=dtype) + gp_bs1 = functools.partial(gp_bs1_inp, dtype=dtype) + m_bs1 = functools.partial(m_bs1_inp, dtype=dtype) + m_bs1_float = functools.partial(m_bs1_inp, dtype=torch.float) + m_bs1_bool = functools.partial(m_bs1_inp, dtype=torch.bool) + + candidates = [ + ( + _sfdp_pattern_1, + _sfdp_replacement_1, + [g(), g(), g(), c()], + {}, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_2, + _sfdp_replacement_2, + [g(), g(), g(), c()], + {}, + _sfdp_extra_check(aten.mul.Tensor), + ), + ( + _sfdp_pattern_3, + _sfdp_replacement_3, + [g(), g(), g(), c()], + d, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_4, + _sfdp_replacement_4, + [g(), g(), g(), c()], + d, + _sfdp_extra_check(aten.mul.Tensor), + ), + ( + _sfdp_pattern_5, + _sfdp_replacement_5, + [g(), g(), g(), b()], + s, + _sfdp_params_check, + ), + ( + _sfdp_pattern_6, + _sfdp_replacement_6, + [g(), g(), g(), b()], + sd, + _sfdp_params_check, + ), + ( + _sfdp_pattern_7, + _sfdp_replacement_7, + [g(), g(), g()], + sd, + _sfdp_params_check, + ), + ( + _sfdp_pattern_8, + _sfdp_replacement_8, + [g(), g(), g()], + s, + _sfdp_params_check, + ), + ( + _sfdp_pattern_9, + _sfdp_replacement_9, + [g(), g(), g()], + sd, + _sfdp_params_check, + ), + ( + _sfdp_pattern_10, + _sfdp_replacement_10, + [g(), g(), g()], + s, + _sfdp_params_check, + ), + ( + _sfdp_pattern_11, + _sfdp_replacement_11, + [g(), g(), g(), c()], + {}, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_12, + _sfdp_replacement_12, + [g(), g(), g(), c()], + d, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_13, + _sfdp_replacement_13, + [g_3d(), g_3d(), g_3d()], + d, + _sfdp_pattern_13_check, + ), + ( + _sfdp_pattern_14, + _sfdp_replacement_14, + [g(), g(), g(), m(), c()], + {}, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_15, + _sfdp_replacement_15, + [g(), g(), g(), m_2d(), c()], + {}, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_16, + _sfdp_replacement_16, + [g(), g(), g(), m(), c()], + d, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_16, + _sfdp_replacement_16, + [g_bs1(), g_bs1(), g_bs1(), m_bs1(), c()], + d, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_17, + _sfdp_replacement_17, + [g(), g(), g(), m_2d(), c()], + d, + _sfdp_extra_check(aten.div.Tensor), + ), + ( + _sfdp_pattern_18, + _sfdp_replacement_18, + [g(), g(), g(), m_bool()], + sd, + _sfdp_params_check, + ), + ( + _sfdp_pattern_18, + _sfdp_replacement_18, + [g_bs1(), g_bs1(), g_bs1(), m_bs1_bool()], + sd, + _sfdp_params_check, + ), + ( + _sfdp_pattern_19, + _sfdp_replacement_19, + [g(), g(), g(), b_bool(), b_float()], + sd, + _sfdp_params_check, + ), + ( + _sfdp_pattern_20, + _sfdp_replacement_20, + [g(), g(), g(), m_2d()], + sd, + _sfdp_params_check, + ), + ( + _sfdp_pattern_21, + _sfdp_replacement_21, + [g(), g(), g(), m_float()], + {}, + _sfdp_params_check, + ), + ( + _sfdp_pattern_21, + _sfdp_replacement_21, + [g_bs1(), g_bs1(), g_bs1(), m_bs1_float()], + {}, + _sfdp_params_check, + ), + ( + _sfdp_pattern_22, + _sfdp_replacement_22, + [g(), g(), g(), m_float()], + {}, + _sfdp_params_check, + ), + ( + _sfdp_pattern_22, + _sfdp_replacement_22, + [g_bs1(), g_bs1(), g_bs1(), m_bs1_float()], + {}, + _sfdp_params_check, + ), + ( + _sfdp_pattern_23, + _sfdp_replacement_23, + [g(), g(), g()], + {}, + _sfdp_params_check, + ), + ( + _sfdp_pattern_23, + _sfdp_replacement_23, + [g_bs1(), g_bs1(), g_bs1()], + {}, + _sfdp_params_check, + ), + ( + _sfdp_pattern_24, + _sfdp_replacement_24, + [g(), g(), g(), b_float()], + {}, + _sfdp_extra_check, + ), + ( + _sfdp_pattern_25, + _sfdp_replacement_25, + [g(), g(), g(), m()], + d, + _sfdp_extra_check(disable_cuda=True), + ), + ( + _sfdp_pattern_25, + _sfdp_replacement_25, + [g_bs1(), g_bs1(), g_bs1(), m_bs1()], + d, + _sfdp_extra_check(disable_cuda=True), + ), + ( + _sfdp_pattern_26, + _sfdp_replacement_26, + [g(), g(), g(), m()], + d, + _sfdp_extra_check(disable_cuda=True), + ), + ( + _sfdp_pattern_26, + _sfdp_replacement_26, + [g_bs1(), g_bs1(), g_bs1(), m_bs1()], + d, + _sfdp_extra_check(disable_cuda=True), + ), + ( + _sfdp_pattern_27, + _sfdp_replacement_27, + [g(), g(), g()], + d, + _sfdp_extra_check(disable_cuda=True), + ), + ( + _sfdp_pattern_27, + _sfdp_replacement_27, + [g_bs1(), g_bs1(), g_bs1()], + d, + _sfdp_extra_check(disable_cuda=True), + ), + ( + _sfdp_pattern_28, + _sfdp_replacement_28, + [gn(), gn(), gn(), c()], + d, + _sfdp_extra_check(aten.mul.Tensor), + ), + ( + _sfdp_pattern_29, + _sfdp_replacement_29, + [gp(), gp(), gp(), b()], + s, + _sfdp_extra_check(aten.mul.Scalar), + ), + ( + _sfdp_pattern_29, + _sfdp_replacement_29, + [gp_bs1(), gp_bs1(), gp_bs1(), b()], + s, + _sfdp_extra_check(aten.mul.Scalar), + ), + ( + _sfdp_pattern_30, + _sfdp_replacement_30, + [gp(), gp(), gp()], + s, + _sfdp_extra_check(aten.mul.Scalar), + ), + ( + _sfdp_pattern_30, + _sfdp_replacement_30, + [gp_bs1(), gp_bs1(), gp_bs1()], + s, + _sfdp_extra_check(aten.mul.Scalar), + ), + ] + mask_fp32_patterns = ["pattern_16"] + if dtype == torch.half: + # Add inputs of bf16 q/k/v and fp32 mask, for models like albert. + candidates.append( + ( + _sfdp_pattern_16, + _sfdp_replacement_16, + [g(), g(), g(), m_float(), c()], + d, + _sfdp_extra_check( + aten.div.Tensor, disable_cuda=torch.version.hip is None + ), + ) + ) + candidates.append( + ( + _sfdp_pattern_16, + _sfdp_replacement_16, + [g_bs1(), g_bs1(), g_bs1(), m_bs1_float(), c()], + d, + _sfdp_extra_check( + aten.div.Tensor, disable_cuda=torch.version.hip is None + ), + ) + ) + + for pattern, replacement, args, workaround, extra_check in candidates: + # XXX: when adding a new pattern, re-run `gen_attention_patterns` so the pattern + # gets serialized to a python file and does not require tracing at runtime. + if not isinstance(workaround, dict): + raise AssertionError( + f"expected workaround to be a dict, got {type(workaround)}" + ) + name = pattern.__name__ + pattern_name = name + + if dtype != torch.float: + name += "_half" + if ( + any(p in name for p in mask_fp32_patterns) + and args[3].dtype == torch.float32 + ): + name += "_mask_fp32" + if args[0].size(0) == 1: + name += "_bs1" + + if pattern_name not in _INFERENCE_ONLY_SFDP_PATTERNS: + training_name = name + "_training" + yield ( + training_name, + { + "search_fn": pattern, + "replace_fn": replacement, + "example_inputs": args, + "trace_fn": joint_fwd_bwd, + "pass_dicts": patterns, + "extra_check": extra_check, + "scalar_workaround": workaround, + "skip_duplicates": True, + }, + ) + inference_workaround = {} + if workaround: + if len(workaround) > 2: + raise AssertionError( + f"expected len(workaround) <= 2, got {len(workaround)}" + ) + if "inv_scale" in workaround: + inference_workaround["inv_scale"] = workaround["inv_scale"] + if "dropout_p" in workaround: + # functools.partial insufficient because we look at signature downstream + pattern = partialize_and_update_signature(pattern, dropout_p=0.0) + replacement = partialize_and_update_signature( + replacement, dropout_p=0.0 + ) + + inference_name = name + "_inference" + yield ( + inference_name, + { + "search_fn": pattern, + "replace_fn": replacement, + "example_inputs": args, + "trace_fn": fwd_only, + "pass_dicts": patterns, + "extra_check": extra_check, + "scalar_workaround": inference_workaround, + # with dropout turned into clone, we end up with a number of + # semantically identical graphs + "skip_duplicates": True, + }, + ) + + +@functools.cache +def _sfdp_init(input_device: torch.device | None = None): + for key, register_replacement_kwargs in _get_sfdp_patterns(input_device): + gen_register_replacement(key, **register_replacement_kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/fusion_regions.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/fusion_regions.py new file mode 100644 index 0000000000000000000000000000000000000000..2c56f45dc493417d25543c15260e1d1fa3a602cf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/fusion_regions.py @@ -0,0 +1,217 @@ +"""Detect fusion regions for overlap scheduling.""" + +import torch +import torch.fx as fx +from torch.utils._ordered_set import OrderedSet + + +def is_view_node(n: fx.Node) -> bool: + """Check if a node is a view operation (zero cost, no memory allocation).""" + + return isinstance(n.target, torch._ops.OpOverload) and ( + n.target.is_view and n.target.namespace in ("aten", "prims") + ) + + +def is_fusible_node(n: fx.Node) -> bool: + """Check if a node is fusible based on whether it has an inductor lowering. + + A node is fusible if: + - It has a lowering in torch._inductor.lowering.lowerings + - It does NOT have a flop counter (expensive compute ops like mm/conv) + - It is NOT a registered fallback (ops that fall back to eager) + - It is NOT a collective or wait op + - For aten.cat, it must have <= max_pointwise_cat_inputs inputs + """ + if n.op != "call_function": + return False + + target = n.target + if not isinstance(target, torch._ops.OpOverload): + return False + + # Exclude collectives and waits (they have their own scheduling) + if target.namespace == "_c10d_functional": + return False + + from torch._inductor.lowering import fallbacks, lowerings + from torch.utils.flop_counter import flop_registry + + # Must have a lowering + if target not in lowerings: + return False + + # Exclude fallbacks (ops that fall back to eager execution) + if target in fallbacks: + return False + + # Exclude ops with flop counters (expensive compute ops like mm, conv, etc.) + overload_packet = target.overloadpacket + if overload_packet in flop_registry: + return False + + # Special case: cat is only fusible if it has few enough inputs + if target == torch.ops.aten.cat.default: + inputs = n.args[0] if n.args else [] + if isinstance(inputs, (list, tuple)): + import torch._inductor.config as inductor_config + + if len(inputs) > inductor_config.max_pointwise_cat_inputs: + return False + + return True + + +def _get_contiguous_fusible_spans(gm: fx.GraphModule) -> list[list[fx.Node]]: + """Get contiguous spans of fusible nodes from the graph. + + Walks the graph in topological order and groups consecutive fusible + nodes into spans. Non-fusible nodes act as span boundaries. + """ + spans: list[list[fx.Node]] = [] + current_span: list[fx.Node] = [] + + for node in gm.graph.nodes: + if is_fusible_node(node): + current_span.append(node) + else: + # Non-fusible node ends the current span + if current_span: + spans.append(current_span) + current_span = [] + + if current_span: + spans.append(current_span) + + return spans + + +def _find_connected_components(span: list[fx.Node]) -> list[list[fx.Node]]: + """Find connected components within a span of fusible nodes. + + Two nodes are connected if one is an input to the other (direct data dependency). + """ + if not span: + return [] + + from torch.fx.experimental.optimization import UnionFind + + span_set = OrderedSet(span) + node_to_idx = {n: i for i, n in enumerate(span)} + + uf = UnionFind(len(span)) + for i in range(len(span)): + uf.make_set(i) + + # Union nodes based on input edges + for node in span: + node_idx = node_to_idx[node] + for inp in node.all_input_nodes: + if inp in span_set: + uf.join(node_idx, node_to_idx[inp]) + + # Group by root + root_to_nodes: dict[int, list[fx.Node]] = {} + for node in span: + root = uf.find(node_to_idx[node]) + if root not in root_to_nodes: + root_to_nodes[root] = [] + root_to_nodes[root].append(node) + + return list(root_to_nodes.values()) + + +def build_fusion_regions( + gm: fx.GraphModule, +) -> dict[fx.Node, OrderedSet[fx.Node]]: + """Build fusion regions from contiguous spans of fusible nodes. + + 1. Identify contiguous spans of fusible nodes (separated by non-fusible nodes) + 2. Find connected components within each span + 3. Return regions that have 2+ non-view nodes + + This ensures fusion regions are strictly local - no reordering across + non-fusible node boundaries. + + Returns a dict mapping each node to its fusion group (OrderedSet of nodes). + """ + # Build node -> topo index map for sorting + node_to_idx: dict[fx.Node, int] = {n: i for i, n in enumerate(gm.graph.nodes)} + + # Step 1: Get contiguous spans of fusible nodes + spans = _get_contiguous_fusible_spans(gm) + + # Step 2: Find connected components within each span + region_of: dict[fx.Node, OrderedSet[fx.Node]] = {} + + for span in spans: + if len(span) < 2: + continue + + components = _find_connected_components(span) + + for component in components: + # Skip regions with fewer than 2 non-view nodes (views have no cost) + non_view_count = sum(1 for n in component if not is_view_node(n)) + if non_view_count < 2: + continue + + # Sort nodes in topological order to preserve original ordering + sorted_component = sorted(component, key=lambda n: node_to_idx[n]) + node_set = OrderedSet(sorted_component) + + for node in sorted_component: + region_of[node] = node_set + + return region_of + + +def estimate_fused_node_costs( + region_of: dict[fx.Node, OrderedSet[fx.Node]], +) -> dict[fx.Node, float]: + """Estimate per-node costs accounting for fusion (no graph collapse). + + For each node in a fusion region, only count I/O that crosses the + region boundary (external reads/writes). Internal intermediates + won't be materialized by inductor, so they shouldn't count. + + Nodes with only internal I/O get cost 0. Nodes with external I/O + get the bandwidth cost of just those external tensors. + """ + from torch.utils._pytree import tree_flatten + from torch.utils._runtime_estimation import get_transfer_time + + costs: dict[fx.Node, float] = {} + seen: OrderedSet[int] = OrderedSet() + + for node_set in region_of.values(): + rid = id(node_set) + if rid in seen: + continue + seen.add(rid) + + for n in node_set: + # External inputs: values from nodes outside this region + ext_inputs = [] + for inp in n.all_input_nodes: + if inp not in node_set: + val = inp.meta.get("val") + if val is not None: + ext_inputs.append(val) + + # External outputs: this node's value is used outside the region + ext_outputs = [] + has_external_user = any(u not in node_set for u in n.users) + if has_external_user: + val = n.meta.get("val") + if val is not None: + ext_outputs.append(val) + + if not ext_inputs and not ext_outputs: + costs[n] = 0.0 + else: + flat_in, _ = tree_flatten(ext_inputs) + flat_out, _ = tree_flatten(ext_outputs) + costs[n] = get_transfer_time(flat_in, flat_out) / 1e6 + + return costs diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/graph_view.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/graph_view.py new file mode 100644 index 0000000000000000000000000000000000000000..58927d7ad4e12d52c512584a48c6731f9f6654a3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/graph_view.py @@ -0,0 +1,238 @@ +from __future__ import annotations + +import itertools +import re +from typing import Any, TYPE_CHECKING + +import torch.fx as fx # noqa: TC001 +from torch.utils._ordered_set import OrderedSet + + +if TYPE_CHECKING: + from collections.abc import Callable + + +def _get_module_stack(node: fx.Node) -> list[tuple[str, type[Any]]]: + nn_stack = node.meta.get("nn_module_stack", "") + if nn_stack: + return list(nn_stack.values()) + + fwd_nn_stack = node.meta.get("fwd_nn_module_stack", "") + if fwd_nn_stack: + return list(fwd_nn_stack.values()) + + return [] + + +def _addindent(s_: str, num_spaces: int) -> str: + s: list[str] = s_.split("\n") + # don't do anything for single-line stuff + if len(s) == 1: + return s_ + first: str = s.pop(0) + s: list[str] = [(num_spaces * " ") + line for line in s] + joint_s: str = "\n".join(s) + joint_s = first + "\n" + joint_s + return joint_s + + +class GraphView: + """ + A hierarchical class for organizing and managing torch.fx nodes by their module stack. + + This class provides a tree-like structure where each node in the hierarchy corresponds + to a module or submodule in a traced FX graph. Each `GraphView` instance can hold a list + of FX nodes (`self.data`) belonging to that module scope, maintain a unique set of nodes + (`self.unique_nodes`), and manage its child containers (`self.children`). + + Attributes: + name (str): The name of the module or container scope. + klass (type[Any]): The class type associated with this module/container. + data (list[fx.Node]): A list of FX graph nodes belonging to this module. + unique_nodes (OrderedSet[fx.Node]): A deduplicated set of nodes to ensure no duplicates. + children (dict[str, GraphView]): A mapping of child module names to their corresponding GraphView instances. + """ + + def __init__(self, name: str, klass: type[Any]) -> None: + self.name: str = name + self.klass: type[Any] = klass + self.data: list[fx.Node] = [] + self.unique_nodes: OrderedSet[fx.Node] = OrderedSet() + self.children: dict[str, GraphView] = {} + + def add(self, data: fx.Node) -> None: + if data not in self.unique_nodes: + self.data.append(data) + self.unique_nodes.add(data) + + def get_child(self, module_stack: str, klass: type[Any] | None = None) -> GraphView: + if module_stack not in self.children: + new_stack = GraphView(module_stack, klass or self.klass) + self.children[module_stack] = new_stack + return self.children[module_stack] + + def __getitem__(self, name: str) -> GraphView: + return self.children[name] + + def __getattr__(self, name: str) -> GraphView: + return self.children[name] + + def __repr__(self) -> str: + child_lines: list[str] = [] + for name, child in self.children.items(): + mod_str = repr(child) + mod_str = _addindent(mod_str, 2) + child_lines.append(f"({name}): {mod_str}") + main_str = f"{self.klass.__name__}(" + if child_lines: + main_str += "\n " + "\n ".join(child_lines) + "\n" + main_str += ")" + return main_str + + +def _clean_stack_name(stack_name: str) -> str: + """ + Clean up FX node's nn_module_stack metadata string to match the module name hierarchies + + Example: + Input: "L['self']._modules['layers']['0']._modules['attention']" + Output: "layers.0.attention" + """ + cleaned = re.sub(r"^L\['self'\]\.?", "", stack_name) + parts = re.findall(r"\['([^']+)'\]", cleaned) + return ".".join(parts) if parts else cleaned + + +def _is_root(stack: str) -> bool: + return stack == "" + + +def make_graph_view( + graph: fx.Graph, + module_stack_fn: Callable[[fx.Node], list[tuple[str, type[Any]]]] | None = None, +) -> GraphView | None: + """ + Code from: https://github.com/meta-pytorch/autoparallel/pull/158 + + Make a graph view from the fx.Graph. This is a tree structure that + represents the module hierarchy of the graph, and enables us to + easily find the nodes that belong to each module, and gives a slightly + easier way of visualize different parts of the graph by extracting + subgraphs that belong to a particular module FQN. + + For example, if we have the following model with module hierarchy: + + Transformer( + (tok_embeddings): Embedding(128256, 4096) + (layers): ModuleDict( + (0): TransformerBlock( + (attention): Attention( + (wq): Linear(in_features=4096, out_features=4096, bias=False) + (wk): Linear(in_features=4096, out_features=1024, bias=False) + (wv): Linear(in_features=4096, out_features=1024, bias=False) + (wo): Linear(in_features=4096, out_features=4096, bias=False) + (sdpa): ScaledDotProductAttention() + ) + (feed_forward): FeedForward( + (w1): Linear(in_features=4096, out_features=14336, bias=False) + (w2): Linear(in_features=14336, out_features=4096, bias=False) + (w3): Linear(in_features=4096, out_features=14336, bias=False) + ) + (attention_norm): RMSNorm((4096,), eps=1e-05, elementwise_affine=True) + (ffn_norm): RMSNorm((4096,), eps=1e-05, elementwise_affine=True) + ) + ) + (norm): RMSNorm((4096,), eps=1e-05, elementwise_affine=True) + (output): Linear(in_features=4096, out_features=128256, bias=False) + ) + + Then we can get a GraphView for the fx.Graph that enables us to do + + graph_view = make_graph_view(graph) + subgraph = get_subgraph_by_path(graph_view, "layers.0") + + where subgraph contains all the nodes that belong to this region + + module_stack_fn: Optional callable for extracting module hierarchy information from nodes. + + Signature: Callable[[fx.Node], list[tuple[str, type[Any]]]] + + Takes an FX node and returns a list of (module_path, module_class) tuples representing + the nested module hierarchy for that node, ordered from outermost to innermost scope. + + - module_path (str): Dot-separated path identifying the module in the hierarchy + (e.g., "layers.0.attention.wq") + - module_class (type): The Python class type of the module + + This enables custom logic for determining module membership, useful for: + - Graphs without standard nn_module_stack metadata + - Filtering or grouping nodes by custom criteria + + Example of getting the module stack from annotation: + + def module_stack_fn(node): + module_stack = node.meta.get("custom", {}).get("module_path", "") + return [(module_stack, torch.nn.Module)] + + If None, defaults to extracting from node.meta["nn_module_stack"] or + node.meta["fwd_nn_module_stack"]. + """ + + def nn_module_stack_meta(node: fx.Node) -> list[tuple[str, type[Any]]]: + result = [] + for module_stack, module_class in _get_module_stack(node): + module_stack = _clean_stack_name(module_stack) + result.append((module_stack, module_class)) + return result + + if module_stack_fn is None: + module_stack_fn = nn_module_stack_meta + nodes: list[fx.Node] = list(graph.nodes) + nodes_by_module_stack_root: GraphView | None = None + for node in nodes: + for module_stack, module_class in module_stack_fn(node): + nodes_by_module_stack: GraphView | None = nodes_by_module_stack_root + for name in module_stack.split("."): + if nodes_by_module_stack is None: + nodes_by_module_stack = GraphView(name, module_class) + nodes_by_module_stack_root = nodes_by_module_stack + if _is_root(module_stack): + new_stack: GraphView = nodes_by_module_stack + else: + new_stack = nodes_by_module_stack.get_child(name, module_class) + nodes_by_module_stack = new_stack + nodes_by_module_stack.add(node) + + return nodes_by_module_stack_root + + +def get_subgraph_by_path( + graph_view: GraphView, paths: str | list[str] +) -> list[fx.Node]: + """ + Get subgraph by path(s). + Args: + graph_view (object): Root graph view object. + paths (str or list of str): Path(s) to subgraph. + Returns: + list[fx.Node]: fx nodes belong to the subgraph + """ + + def get_node_by_path(node: GraphView, path: str) -> GraphView: + for p in path.split("."): + if p in node.children: + node = node.children[p] + else: + return GraphView("", object) + return node + + if isinstance(paths, list): + nodes = list( + itertools.chain.from_iterable( + get_node_by_path(graph_view, p).data for p in paths + ) + ) + return nodes + else: + node = get_node_by_path(graph_view, paths) + return node.data diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/group_batch_fusion.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/group_batch_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..bb63bed12a00f205d539153fedeeb88807af4665 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/group_batch_fusion.py @@ -0,0 +1,1719 @@ +# mypy: allow-untyped-defs +import collections +import logging +import operator +from collections import OrderedDict +from collections.abc import Iterable, Iterator +from typing import Any + +import torch +from torch._dynamo.utils import counters, is_node_meta_valid +from torch._logging import trace_structured +from torch._subclasses.fake_tensor import FakeTensor +from torch.fx.experimental.symbolic_shapes import free_symbols +from torch.fx.passes.graph_transform_observer import GraphTransformObserver +from torch.utils._ordered_set import OrderedSet + +from .. import config +from ..pattern_matcher import ( + CallFunctionVarArgs, + CallMethodVarArgs, + get_arg_value, + MatchResult, + stable_topological_sort, +) +from ..utils import OPTIMUS_EXCLUDE_POST_GRAD + + +try: + # importing this will register fbgemm lowerings for inductor + import deeplearning.fbgemm.fbgemm_gpu.fb.inductor_lowerings # noqa: F401 + + has_fbgemm = True +except Exception: + has_fbgemm = False + +aten = torch.ops.aten + +log = logging.getLogger(__name__) + +DEFAULT_BETA = 1 +DEFAULT_ALPHA = 1 + +MIN_FUSE_SET_SIZE = 5 +MAX_FUSE_SET_SIZE = 300 +MAX_FUSE_SEARCH_DEPTH = 5 +# The maximum tensor size that can go into the fusion group +MAX_FUSE_TENSOR_SIZE_GROUP_LINEAR = 4096 +# Whether we only fuse nodes with same parent node +FUSE_NODES_WITH_SAME_PARENT = False +# Whether we enable the add broadcast in batch linear +SHAPE_BROADCAST_BATCH_LINEAR = False +# Whether we enable the fuse nodes with same users +Fuse_NODES_WITH_SAME_USERS = False + +# exclude these nodes from BFS +# excluding get item improves optimizer compilation time by 60s +SEARCH_EXCLUSIONS = OrderedSet([operator.getitem]) + + +default_graph_search_options = { + "min_fuse_set_size": MIN_FUSE_SET_SIZE, + "max_fuse_set_size": MAX_FUSE_SET_SIZE, + "max_fuse_search_depth": MAX_FUSE_SEARCH_DEPTH, + "max_fuse_tensor_size_group_linear": MAX_FUSE_TENSOR_SIZE_GROUP_LINEAR, + "fuse_nodes_with_same_parent": FUSE_NODES_WITH_SAME_PARENT, + "shape_broadcast_batch_linear": SHAPE_BROADCAST_BATCH_LINEAR, + "fuse_nodes_with_same_users": Fuse_NODES_WITH_SAME_USERS, +} + +graph_search_options = default_graph_search_options + + +def update_stack_example_value(node, metadata, dim=0, op=torch.stack): + """ + Update the example value of the node in the graph to enable followup split cat opt. + """ + if node is not None and hasattr(node, "meta"): + if op is torch.stack: + example_value = torch.stack(metadata, dim=dim) + elif op is torch.unbind: + example_value = torch.unbind(metadata, dim=dim) # type: ignore[assignment] + else: + return + node.meta["example_value"] = example_value + + +def update_pointwise_example_value(pointwise_node, input, other, op): + """ + Update the example value of the add node in the graph to enable followup split cat opt. + """ + if pointwise_node is not None and hasattr(pointwise_node, "meta"): + if op is torch.add: + example_value = torch.add(input, other) + elif op is torch.mul: + example_value = torch.mul(input, other) + else: + return + pointwise_node.meta["example_value"] = example_value + + +class GroupBatchFusionBase: + def __init__(self, **kwargs) -> None: + self.graph_search_options = kwargs.pop( + "graph_search_options", default_graph_search_options + ) + + def match(self, node): + raise NotImplementedError("match called on base") + + def fuse(self, graph, subset): + raise NotImplementedError("fuse called on base") + + +PRE_GRAD_FUSIONS: dict[str, GroupBatchFusionBase] = {} +POST_GRAD_FUSIONS: dict[str, GroupBatchFusionBase] = {} + + +def register_fusion(name: str, pre_grad=True): + def decorator(fusion_cls: GroupBatchFusionBase): + if pre_grad: + PRE_GRAD_FUSIONS[name] = fusion_cls + else: + POST_GRAD_FUSIONS[name] = fusion_cls + return fusion_cls + + return decorator + + +def list_group_batch_fusions(pre_grad=True) -> list[str]: + if pre_grad: + return list(PRE_GRAD_FUSIONS.keys()) + else: + return list(POST_GRAD_FUSIONS.keys()) + + +def decompose_stack(graph: torch.fx.GraphModule, input_tensors: list[Any]) -> Any: + unsqueezed_inputs = [] + unsqueezed_inputs_meta = [] + for input_tensor in input_tensors: + unsqueezed_input = graph.call_function( # type: ignore[operator] + aten.unsqueeze, args=(input_tensor,), kwargs={"dim": 0} + ) + unsqueezed_inputs.append(unsqueezed_input) + unsqueezed_input.meta["val"] = aten.unsqueeze(input_tensor.meta["val"], dim=0) # type: ignore[assignment] + unsqueezed_inputs_meta.append(unsqueezed_input.meta["val"]) + stacked_inputs = graph.call_function( # type: ignore[operator] + aten.cat, args=(unsqueezed_inputs,), kwargs={"dim": 0} + ) + stacked_inputs.meta["val"] = aten.cat(unsqueezed_inputs_meta, dim=0) # type: ignore[assignment] + return stacked_inputs + + +class GroupFusion(GroupBatchFusionBase): + """ + Fuse ops in a group way, e.g, fuse mm/addmm of arbitrary input shapes with fbgemm.gmm. + """ + + +class BatchFusion(GroupBatchFusionBase): + """ + Fuse ops in a batch way, e.g, fuse mm/addmm of same input shapes with bmm. + """ + + +class BatchPointwiseOpsFusionFactory(BatchFusion): + def __init__(self, op, **kwargs) -> None: + super().__init__(**kwargs) + self.op = op + + +@register_fusion("batch_linear_post_grad", pre_grad=False) +class PostGradBatchLinearFusion(BatchFusion): + """ + Fuse ops in a batch way in post grad (aten level). + """ + + def _addmm_node_can_be_fused(self, node: torch.fx.Node) -> bool: + # pyre-fixme[7]: Incompatible return type + return ( + # pyrefly: ignore [bad-return] + node.kwargs.get("beta", DEFAULT_BETA) == DEFAULT_BETA + and node.kwargs.get("alpha", DEFAULT_ALPHA) == DEFAULT_ALPHA # type: ignore[return-value] + ) + + def _is_input_2d(self, input: torch.fx.Node) -> bool: + input_shapes = input.meta["val"].shape + return ( + len(input_shapes) == 2 + and isinstance(input_shapes[0], int) + and isinstance(input_shapes[1], int) + ) + + def match(self, node: torch.fx.Node) -> tuple[str, int, int, int, bool, str] | None: + if CallFunctionVarArgs(aten.mm).match(node): + input_m, weight_m = node.args + bias_m = None + + elif CallFunctionVarArgs(aten.addmm.default).match( + node + ) and self._addmm_node_can_be_fused(node): + bias_m, input_m, weight_m = node.args + else: + return None + # get the user of the node + if self.graph_search_options.get("fuse_nodes_with_same_users", False): + users = [user.target for user in node.users] + else: + users = "" # type: ignore[assignment] + # only handle the cases where inputs are 2D tensors + if not self._is_input_2d(input_m) or not self._is_input_2d(weight_m): # type: ignore[arg-type] + return None + m, k = input_m.meta["val"].shape # type: ignore[union-attr] + n = weight_m.meta["val"].shape[1] # type: ignore[union-attr] + batch_key = ("batch_linear_post_grad", m, k, n, bias_m is not None, str(users)) + return batch_key + + def fuse(self, graph: torch.fx.GraphModule, subset: list[torch.fx.Node]): + batch_inputs = [] + batch_weights = [] + batch_biases = [] + batch_nodes = [] + batch_inputs_meta = [] + batch_weights_meta = [] + batch_biases_meta = [] + + for node in subset: + if CallFunctionVarArgs(aten.addmm.default).match(node): + bias, input, weight = node.args + elif CallFunctionVarArgs(aten.mm.default).match(node): + input, weight = node.args + bias = None + batch_nodes.append(node) + batch_inputs.append(input) # type: ignore[possibly-undefined] + batch_weights.append(weight) # type: ignore[possibly-undefined] + batch_biases.append(bias) # type: ignore[possibly-undefined] + batch_inputs_meta.append(input.meta) # type: ignore[possibly-undefined, union-attr] + batch_weights_meta.append(weight.meta) # type: ignore[possibly-undefined, union-attr] + if bias is not None: # type: ignore[possibly-undefined] + batch_biases_meta.append(bias.meta) # type: ignore[possibly-undefined, union-attr] + else: + batch_biases_meta.append(None) + + with graph.inserting_before(subset[-1]): # type: ignore[operator] + fused_inputs = decompose_stack(graph, batch_inputs) + fused_weights = decompose_stack(graph, batch_weights) + fused_inputs_meta_val = torch.stack( + [input["val"] for input in batch_inputs_meta] + ) + fused_weights_meta_val = torch.stack( + [weight["val"] for weight in batch_weights_meta] + ) + fused_bmm = graph.call_function( # type: ignore[operator] + aten.bmm, + args=(fused_inputs, fused_weights), + ) + fused_bmm.meta["val"] = aten.bmm( + fused_inputs_meta_val, fused_weights_meta_val + ) + for i, original_mm in enumerate(batch_nodes): + has_bias = False + with graph.inserting_after(fused_bmm): # type: ignore[operator] + new_mm = graph.call_function(aten.select, args=((fused_bmm, 0, i))) # type: ignore[operator] + new_mm.meta["val"] = aten.select(fused_bmm.meta["val"], 0, i) + if batch_biases[i]: + has_bias = True + # broadcast the bias to the same shape as the mm output + if self.graph_search_options.get( + "shape_broadcast_batch_linear", False + ): + broadcast_shape = torch.broadcast_shapes( + batch_biases_meta[i]["val"].shape, new_mm.meta["val"].shape + ) + broadcast_bias = graph.call_function( # type: ignore[operator] + aten.broadcast_to.default, + args=(batch_biases[i],), + kwargs={"size": broadcast_shape}, + ) + broadcast_bias.meta["val"] = aten.broadcast_to( + batch_biases_meta[i]["val"], broadcast_shape + ) # type: ignore[assignment] + new_bias_add = graph.call_function( # type: ignore[operator] + aten.add.Tensor, args=((broadcast_bias, new_mm)) + ) + new_bias_add.meta["val"] = aten.add.Tensor( + broadcast_bias.meta["val"], new_mm.meta["val"] + ) + else: + new_bias_add = graph.call_function( # type: ignore[operator] + aten.add, args=((batch_biases[i], new_mm)) + ) + new_bias_add.meta["val"] = aten.add.Tensor( + batch_biases_meta[i]["val"], new_mm.meta["val"] + ) + new_mm_cont = new_bias_add if has_bias else new_mm # type: ignore[possibly-undefined] + original_mm.replace_all_uses_with(new_mm_cont) + new_mm_cont.meta.update(original_mm.meta) + graph.erase_node(original_mm) # type: ignore[operator] + counters["inductor"]["batch_linear_post_grad"] += 1 + + +@register_fusion("group_linear", pre_grad=False) +class GroupLinearFusion(GroupFusion): + def _addmm_node_can_be_fused(self, node: torch.fx.Node): + input_shape = node.args[1].meta["val"].shape # type: ignore[union-attr] + weight_shape = node.args[2].meta["val"].shape # type: ignore[union-attr] + return ( + node.kwargs.get("beta", DEFAULT_BETA) == DEFAULT_BETA + and node.kwargs.get("alpha", DEFAULT_ALPHA) == DEFAULT_ALPHA + and len(input_shape) == 2 + and len(weight_shape) == 2 + and all(x % 2 == 0 for x in input_shape + weight_shape) + and all( + shape <= self.graph_search_options["max_fuse_tensor_size_group_linear"] + for shape in input_shape + weight_shape + ) + ) + + def _mm_node_can_be_fused(self, node: torch.fx.Node): + input_shape = node.args[0].meta["val"].shape # type: ignore[union-attr] + weight_shape = node.args[1].meta["val"].shape # type: ignore[union-attr] + return ( + len(input_shape) == 2 + and len(weight_shape) == 2 + and all(x % 2 == 0 for x in input_shape + weight_shape) + and all( + shape <= self.graph_search_options["max_fuse_tensor_size_group_linear"] + for shape in input_shape + weight_shape + ) + ) + + def match(self, node: torch.fx.Node) -> tuple[str, bool] | None: + if CallFunctionVarArgs(aten.mm.default).match( + node + ) and self._mm_node_can_be_fused(node): + group_key = ("group_linear", True) + elif CallFunctionVarArgs(aten.addmm.default).match( + node + ) and self._addmm_node_can_be_fused(node): + bias = node.args[0] + group_key = ("group_linear", bias is None) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: list[torch.fx.Node]): + group_inputs = [] + group_weights = [] + group_biases = [] + group_nodes = [] + for node in subset: + if CallFunctionVarArgs(aten.addmm.default).match(node): + bias, input, weight = node.args + else: + if not CallFunctionVarArgs(aten.mm.default).match(node): + raise AssertionError(f"expected aten.mm node, got {node}") + input, weight = node.args + bias = None + + group_nodes.append(node) + group_inputs.append(input) + group_weights.append(weight) + group_biases.append(bias) + + if all(bias is None for bias in group_biases): + group_biases = None # type: ignore[assignment] + + with graph.inserting_before(subset[0]): # type: ignore[operator] + fused_mm = graph.call_function( # type: ignore[operator] + torch.ops.fbgemm.gmm.default, + args=(group_inputs, group_weights, group_biases), + kwargs={"smart_fused": True}, + ) + + for i, original_mm in enumerate(group_nodes): + with graph.inserting_after(fused_mm): # type: ignore[operator] + new_mm = graph.call_function(operator.getitem, args=(fused_mm, i)) # type: ignore[operator] + original_mm.replace_all_uses_with(new_mm) + new_mm.meta.update(original_mm.meta) + graph.erase_node(original_mm) # type: ignore[operator] + counters["inductor"]["group_linear"] += 1 + + +class BatchPointwiseMathOpsPostGradFusion(BatchPointwiseOpsFusionFactory): + """ + Batch pointwise math operator (e.g., add, mul) in post grad pass. + """ + + def __init__(self, op, **kwargs) -> None: + super().__init__(op, **kwargs) + self.op = op + + def _pointwise_node_can_be_fused(self, node: torch.fx.Node): + # note: we only consider the case where the inputs are tensors + # for mixed precision training, we need to make sure the inputs + # of the aten.cat when do the stack should be the same dtype + # otherwise, the output of the aten.cat may be not the same as + # its inputs, and cause dtype not same error in mm or addmm + input, other = node.args + return ( + input.meta["val"].shape == other.meta["val"].shape # type: ignore[union-attr] + # input and other can be scalars, where they have no attribute 'meta' + if hasattr(input, "meta") + and hasattr(other, "meta") + and is_node_meta_valid(input) # type: ignore[arg-type, union-attr] + and is_node_meta_valid(other) # type: ignore[arg-type, union-attr] + # torch.SymInt or torch.SymFloat object has no attribute 'shape' + and isinstance(input.meta["val"], torch.Tensor) # type: ignore[union-attr] + and isinstance(other.meta["val"], torch.Tensor) # type: ignore[union-attr] + else False + ) + + def match(self, node: torch.fx.Node): + if CallFunctionVarArgs(self.op).match( + node + ) and self._pointwise_node_can_be_fused(node): + alpha = node.kwargs.get("alpha", DEFAULT_ALPHA) + rounding_mode = node.kwargs.get("rounding_mode", None) + input, other = node.args + shape = list(input.meta["val"].shape) # type: ignore[union-attr] + if self.graph_search_options.get("fuse_nodes_with_same_parent", False): + # only consider the linear case so far + # pyre-fixme[16] + if input.target is aten.select or other.target is aten.select: # type: ignore[union-attr] + parent = ( + # pyre-fixme[16] + input.args[0] # type: ignore[union-attr] + # pyre-fixme[16] + if input.target is aten.select # type: ignore[union-attr] + else other.args[0] # type: ignore[union-attr] + ) + else: + parent = "" + else: + parent = "" + group_key = ( + "batch_aten_" + self.op.__name__.lower().split(".")[0], + str(shape), + str(input.meta["val"].dtype), # type: ignore[union-attr] + str(other.meta["val"].dtype), # type: ignore[union-attr] + str(alpha), + str(rounding_mode), + str(parent), + ) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: list[torch.fx.Node]): + batch_inputs, batch_others = [], [] + alpha = subset[0].kwargs.get("alpha", DEFAULT_ALPHA) + batch_inputs_meta, batch_others_meta = [], [] + + for node in subset: + input, other = node.args + batch_inputs.append(input) + batch_others.append(other) + batch_inputs_meta.append(input.meta) # type: ignore[possibly-undefined, union-attr] + batch_others_meta.append(other.meta) # type: ignore[possibly-undefined, union-attr] + + with graph.inserting_before(subset[0]): # type: ignore[operator] + stack_inputs = decompose_stack(graph, batch_inputs) + stack_others = decompose_stack(graph, batch_others) + stack_inputs_meta = torch.stack( + [input["val"] for input in batch_inputs_meta] + ) + stack_others_meta = torch.stack( + [other["val"] for other in batch_others_meta] + ) + + batch_op = graph.call_function( # type: ignore[operator] + self.op, + args=(stack_inputs, stack_others), + kwargs={"alpha": alpha} if self.op == aten.add.Tensor else {}, + ) + batch_op.meta["val"] = self.op(stack_inputs_meta, stack_others_meta) + for i, original_add in enumerate(subset): + with graph.inserting_after(batch_op): # type: ignore[operator] + new_add = graph.call_function( # type: ignore[operator] + torch.ops.aten.select, args=((batch_op, 0, i)) + ) + original_add.replace_all_uses_with(new_add) + new_add.meta.update(original_add.meta) + graph.erase_node(original_add) # type: ignore[operator] + counters["inductor"][ + "batch_aten_" + self.op.__name__.lower().split(".")[0] + ] += 1 + + +@register_fusion("batch_linear_lhs") +class BatchLinearLHSFusion(BatchFusion): + """ + Batch linear left-hand side fusion. This pass tries to fuse the following patterns: + + torch.nn.functional.linear(x, w1), linear(x, w2),... * linear(x, wn) + -> torch.mm(x, torch.cat([w1, w2,... * wn]).transpose(0, 1)) + + We have a separate pass to eliminate contiguous transpose in a generic way. + """ + + def match(self, node: torch.fx.Node) -> tuple[str, int | None, Any] | None: + if CallFunctionVarArgs([torch.nn.functional.linear, torch._C._nn.linear]).match( + node + ) and is_linear_node_can_be_fused(node): + input = get_arg_value(node, 0, "input") + weight = get_arg_value(node, 1, "weight") + bias = get_arg_value(node, 2, "bias") + # Skip fusion when weight is a tensor subclass that can't handle aten.cat. + # fuse() calls torch.cat on the weight example_values, which fails for + # subclasses lacking aten.cat dispatch. Probe it here so subclasses that + # do implement aten.cat (e.g. future torchao versions) still get fused. + weight_val = weight.meta.get("example_value", weight.meta.get("val")) + if weight_val is not None and type(weight_val) not in ( + torch.Tensor, + FakeTensor, + ): + try: + _ = torch.cat([weight_val[:1], weight_val[:1]], dim=0) + except (RuntimeError, TypeError): + return None + bias_tensor = None + if bias is not None: + bias_tensor = bias.meta.get("val", bias.meta.get("example_value")) + bias_dim = None if bias_tensor is None else bias_tensor.ndim # type: ignore[union-attr] + group_key = ("batch_linear_lhs", bias_dim, input) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: list[torch.fx.Node]): + batch_nodes = [] + batch_input = None + batch_weights, batch_weights_meta = [], [] + batch_biases, batch_biases_meta = [], [] + split_sections = [] + for node in subset: + input = get_arg_value(node, 0, "input") + weight = get_arg_value(node, 1, "weight") + bias = get_arg_value(node, 2, "bias") + batch_nodes.append(node) + if batch_input is None: + batch_input = input + else: + if batch_input is not input: + raise AssertionError( + f"expected batch_input to be input, got {batch_input}" + ) + batch_weights.append(weight) + batch_weights_meta.append(weight.meta["example_value"]) + if bias: + batch_biases.append(bias) + batch_biases_meta.append(bias.meta["example_value"]) + split_sections.append(weight.meta["example_value"].shape[0]) + + with graph.inserting_before(subset[0]): # type: ignore[operator] + cat_weights = graph.call_function( # type: ignore[operator] + torch.cat, args=(batch_weights,), kwargs={"dim": 0} + ) + cat_weights.meta["example_value"] = torch.cat(batch_weights_meta, dim=0) + transposed_weights = graph.call_function( # type: ignore[operator] + torch.transpose, args=(cat_weights, 0, 1) + ) + transposed_weights.meta["example_value"] = torch.transpose( + cat_weights.meta["example_value"], 0, 1 + ) + if len(batch_biases) > 0: + cat_biases = graph.call_function( # type: ignore[operator] + torch.cat, args=(batch_biases,), kwargs={"dim": 0} + ) + cat_biases.meta["example_value"] = torch.cat(batch_biases_meta, dim=0) + fused_lhs = graph.call_function( # type: ignore[operator] + torch.addmm, + args=(cat_biases, batch_input, transposed_weights), + ) + fused_lhs.meta["example_value"] = torch.addmm( + cat_biases.meta["example_value"], + batch_input.meta["example_value"], # type: ignore[union-attr] + transposed_weights.meta["example_value"], + ) + else: + fused_lhs = graph.call_function( # type: ignore[operator] + torch.mm, + args=(batch_input, transposed_weights), + ) + fused_lhs.meta["example_value"] = torch.mm( + batch_input.meta["example_value"], # type: ignore[union-attr] + transposed_weights.meta["example_value"], + ) + fused_lhs_list = graph.call_function( # type: ignore[operator] + torch.split, args=(fused_lhs, split_sections), kwargs={"dim": 1} + ) + + for i, node in enumerate(batch_nodes): + with graph.inserting_after(fused_lhs_list): # type: ignore[operator] + new_node = graph.call_function( # type: ignore[operator] + operator.getitem, args=(fused_lhs_list, i) + ) + node.replace_all_uses_with(new_node) + new_node.meta.update(node.meta) + graph.erase_node(node) # type: ignore[operator] + counters["inductor"]["batch_linear_lhs"] += 1 + + +# Poor person's check for if a node in the graph mutates its input. +# (the graph is torch IR, so we will see torch fns and python operators) +def _is_mutable_node(tgt): + if str(tgt).endswith("_"): + # e.g. torch.mul_, torch.Tensor.mul_ + return True + if ( + hasattr(tgt, "__module__") + and tgt.__module__ == "_operator" + and tgt.__name__.startswith("i") + ): + # e.g. operator.iand, operator.imul + return True + return False + + +def is_linear_node_can_be_fused(node: torch.fx.Node): + input = get_arg_value(node, 0, "input") + weight = get_arg_value(node, 1, "weight") + return ( + is_node_meta_valid(node) + and is_node_meta_valid(input) + and is_node_meta_valid(weight) + and len(input.meta["example_value"].shape) == 2 + and len(weight.meta["example_value"].shape) == 2 + # the mm -> bmm transform adds an unbind() op, + # which is not safe for autograd when the output of the mm is mutated. + # don't pattern match if any users of the mm mutate the input. + and not any(_is_mutable_node(user.target) for user in node.users) + ) + + +@register_fusion("batch_linear") +class PreGradBatchLinearFusion(BatchFusion): + """ + Batch linear fusion in pre grad pass. + Fuse linear with same size with torch.baddbmm + """ + + def _getitem_args(self, getitem_node: torch.fx.Node): + if getitem_node.target != operator.__getitem__ or ( + getitem_node.op != "call_function" + ): + return None + return getitem_node.args[0] + + def match(self, node: torch.fx.Node): + if CallFunctionVarArgs([torch.nn.functional.linear, torch._C._nn.linear]).match( + node + ) and is_linear_node_can_be_fused(node): + input = get_arg_value(node, 0, "input") + weight = get_arg_value(node, 1, "weight") + bias = get_arg_value(node, 2, "bias") + if self.graph_search_options.get("fuse_nodes_with_same_users", False): + users = [user.target for user in node.users] + else: + users = "" # type: ignore[assignment] + group_key = ( + "batch_linear", + self._getitem_args(input), + str(input.meta["example_value"].shape), + str(weight.meta["example_value"].shape), + bias is None, + str(users), + ) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: list[torch.fx.Node]): + batch_nodes = [] + batch_inputs = [] + batch_weights = [] + batch_biases = [] + batch_inputs_metadata = [] + batch_weights_metadata = [] + batch_biases_metadata = [] + for node in subset: + batch_nodes.append(node) + input = get_arg_value(node, 0, "input") + batch_inputs.append(input) + batch_inputs_metadata.append(input.meta["example_value"]) + weight = get_arg_value(node, 1, "weight") + batch_weights.append(weight) + batch_weights_metadata.append(weight.meta["example_value"]) + bias = get_arg_value(node, 2, "bias") + batch_biases.append(bias) + if bias is not None and hasattr(bias, "meta"): + batch_biases_metadata.append(bias.meta["example_value"]) + + with graph.inserting_before(subset[0]): # type: ignore[operator] + stack_inputs = graph.call_function( # type: ignore[operator] + torch.stack, args=(batch_inputs,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_inputs, batch_inputs_metadata) + stack_weights = graph.call_function( # type: ignore[operator] + torch.stack, args=(batch_weights,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_weights, batch_weights_metadata) + transpose_weight = graph.call_function( # type: ignore[operator] + torch.transpose, args=(stack_weights, 1, 2) + ) + transpose_weight.meta["example_value"] = torch.transpose( + stack_weights.meta["example_value"], 1, 2 + ) + if all(bias is None for bias in batch_biases): + bmm = graph.call_function( # type: ignore[operator] + torch.bmm, + args=(stack_inputs, transpose_weight), + ) + bmm.meta["example_value"] = torch.bmm( + stack_inputs.meta["example_value"], + transpose_weight.meta["example_value"], + ) + bmm_meta = bmm.meta["example_value"] + else: + stack_biases = graph.call_function( # type: ignore[operator] + torch.stack, args=(batch_biases,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_biases, batch_biases_metadata) + unsqueeze_biases = graph.call_function( # type: ignore[operator] + torch.unsqueeze, args=(stack_biases, 1) + ) + unsqueeze_biases.meta["example_value"] = torch.unsqueeze( + stack_biases.meta["example_value"], 1 + ) + bmm = graph.call_function( # type: ignore[operator] + torch.baddbmm, + args=(unsqueeze_biases, stack_inputs, transpose_weight), + ) + try: + # it will have runtime error to broadcast when it has dynamic shape included + # in the meta data, so we need to skip the update meta data + bmm.meta["example_value"] = torch.baddbmm( + unsqueeze_biases.meta["example_value"], + stack_inputs.meta["example_value"], + transpose_weight.meta["example_value"], + ) + bmm_meta = bmm.meta["example_value"] + except Exception as e: + log.debug( + f" exception when update bmm meta data with stack error traceback {e}" # noqa: G004 + ) + bmm_meta = None + + bmm = graph.call_function(torch.unbind, args=(bmm,), kwargs={"dim": 0}) # type: ignore[operator] + if bmm_meta is not None: + bmm.meta["example_value"] = torch.unbind(bmm_meta, dim=0) + for i, linear in enumerate(batch_nodes): + with graph.inserting_after(bmm): # type: ignore[operator] + getitem = graph.call_function(operator.getitem, args=(bmm, i)) # type: ignore[operator] + linear.replace_all_uses_with(getitem) + getitem.meta.update(linear.meta) + graph.erase_node(linear) # type: ignore[operator] + counters["inductor"]["batch_linear"] += 1 + + +# Profitability gates for cat_linear (opt-in; numbers come from the sweep in the +# PR description). The split only wins for a narrow output fed by a large, +# memory-bound concat, so gate on output width and concat traffic. +# Widest win output is 96; first loss at N=128. +CAT_LINEAR_MAX_OUTPUT_WIDTH = 96 +# Only the concat's M*K_total*dtype_bytes of HBM traffic is removed, so it has to +# cover the per-piece launch + reduce. Bytes, so fp32 trips it at half the bf16 +# element count. +CAT_LINEAR_CAT_TRAFFIC_FLOOR_BYTES = 512 * 1024 * 1024 +# Skip slivers: a piece this thin is a launch-bound matmul with no upside. +CAT_LINEAR_MIN_PIECE_WIDTH = 8 +# More parts means more launches and reduce-adds; >3 lost in the sweep. +CAT_LINEAR_MAX_PARTS = 3 + + +def _weight_hoist_anchor(graph, weight): + # Insert hoisted slices after the weight's own def, or after the last + # placeholder when it's a lifted input (can't insert a call between placeholders). + if weight.op == "placeholder": + anchor = weight + for n in graph.nodes: + if n.op == "placeholder": + anchor = n + else: + break + return anchor + return weight + + +def _meta_shape(node): + if not isinstance(node, torch.fx.Node) or not is_node_meta_valid(node): + return None + val = node.meta.get("example_value") + if val is None: + val = node.meta.get("val") + if val is None or not hasattr(val, "shape"): + return None + shape = val.shape + # static shapes only: bail on symbolic so we never specialize a backed + # SymInt or trip over an unbacked one (same free_symbols guard split_cat uses) + if free_symbols(shape): + return None + return tuple(int(s) for s in shape) + + +def match_cat_linear(node: torch.fx.Node): + """Match linear(cat([parts...], dim=-1), weight, bias). + + Returns (parts, weight, bias, offsets) or None. Conservative on purpose: + last-dim cat only, total width and part count capped, no thin slivers, and + a weight whose contraction dim lines up with the cat. The cat must have a + single user so it can actually be erased once the linear is rewritten. + """ + cat_in = get_arg_value(node, 0, "input") + weight = get_arg_value(node, 1, "weight") + bias = get_arg_value(node, 2, "bias") + if not isinstance(cat_in, torch.fx.Node) or not CallFunctionVarArgs( + [torch.cat] + ).match(cat_in): + return None + if len(cat_in.users) != 1: + return None + + parts = get_arg_value(cat_in, 0, "tensors") + if not isinstance(parts, (list, tuple)) or not ( + 2 <= len(parts) <= CAT_LINEAR_MAX_PARTS + ): + return None + if not all(isinstance(p, torch.fx.Node) for p in parts): + return None + + cat_shape = _meta_shape(cat_in) + if cat_shape is None or len(cat_shape) < 2: + return None + rank = len(cat_shape) + cat_dim = get_arg_value(cat_in, 1, "dim") + if cat_dim is None: + cat_dim = 0 + if not isinstance(cat_dim, int): + return None + if (cat_dim + rank if cat_dim < 0 else cat_dim) != rank - 1: + return None + + k_total = int(cat_shape[-1]) + + offsets = [0] + for p in parts: + sh = _meta_shape(p) + if sh is None or len(sh) != rank: + return None + k_i = int(sh[-1]) + if k_i < CAT_LINEAR_MIN_PIECE_WIDTH: + return None + offsets.append(offsets[-1] + k_i) + if offsets[-1] != k_total: + return None + + w_shape = _meta_shape(weight) + if w_shape is None or len(w_shape) != 2 or int(w_shape[-1]) != k_total: + return None + + # N is the profit variable; wide outputs are compute-bound and lose the split. + n_out = int(w_shape[0]) + if n_out > CAT_LINEAR_MAX_OUTPUT_WIDTH: + return None + + # traffic = prod(leading dims) * k_total * dtype_bytes. + cat_val = cat_in.meta.get("example_value") + if cat_val is None: + cat_val = cat_in.meta.get("val") + item_bytes = getattr(getattr(cat_val, "dtype", None), "itemsize", 2) + m_lead = 1 + for d in cat_shape[:-1]: + m_lead *= int(d) + if m_lead * k_total * item_bytes < CAT_LINEAR_CAT_TRAFFIC_FLOOR_BYTES: + return None + + return parts, weight, bias, offsets + + +@register_fusion("cat_linear") +class CatLinearFusion(BatchFusion): + """ + Rewrite linear(cat([x0, x1, ...], dim=-1), weight, bias) into a sum of + per-piece linears on contiguous last-dim weight slices, so the concatenated + activation is never materialised in forward or backward. + + Unlike the other fusions here this is a per-node rewrite (one linear(cat) + splits into several smaller linears) rather than a batch of like-shaped ops, + so every match forms its own group of one. Off by default; opt in via + pre_grad_fusion_options["cat_linear"]. + """ + + def __init__(self, **kwargs) -> None: + super().__init__(**kwargs) + self.graph_search_options = { + **self.graph_search_options, + "min_fuse_set_size": 1, + } + # Dedup hoisted weight slices across the several fuse() calls this rule + # makes on one graph (weight-tied blocks match at multiple sites). A fresh + # rule instance is built per compile in generate_fusion_from_config and + # only ever runs on a single graph, so an instance-level cache is safe. + self._piece_cache: dict = {} + + def match(self, node: torch.fx.Node): + if not CallFunctionVarArgs( + [torch.nn.functional.linear, torch._C._nn.linear] + ).match(node): + return None + if not is_node_meta_valid(node): + return None + # match() runs on every linear during the candidate BFS, including nodes + # that never fuse, so keep it side-effect-free: recompute in fuse() rather + # than stashing on node.meta (which would leave stale meta behind). + if match_cat_linear(node) is None: + return None + return ("cat_linear", node) + + def fuse(self, graph: torch.fx.GraphModule, subset: list[torch.fx.Node]): + # Slice+clone each weight once and hoist to entry, so a weight matched by + # several cat_linears (weight-tied blocks) isn't re-sliced at every site. + cache = self._piece_cache + + for node in subset: + matched = match_cat_linear(node) + if matched is None: + continue + parts, weight, bias, offsets = matched + weight_val = weight.meta.get("example_value", weight.meta.get("val")) + bias_val = None + if bias is not None: + bias_val = bias.meta.get("example_value", bias.meta.get("val")) + anchor = _weight_hoist_anchor(graph, weight) + + with graph.inserting_before(node): # type: ignore[operator] + partials = [] + for i, part in enumerate(parts): + key = (weight, offsets[i], offsets[i + 1]) + w_cont = cache.get(key) + if w_cont is None: + # slice is a differentiable view of the full weight; the + # clone makes each GEMM operand contiguous. Folds to a const + # when frozen; in training it's a cheap weight-only op. + # pyrefly: ignore [not-callable] + with graph.inserting_after(anchor): + w_slice = graph.call_function( # type: ignore[operator] + aten.slice.Tensor, + args=(weight, 1, offsets[i], offsets[i + 1]), + ) + # pyrefly: ignore [not-callable] + with graph.inserting_after(w_slice): + w_cont = graph.call_function( # type: ignore[operator] + aten.clone.default, + args=(w_slice,), + kwargs={"memory_format": torch.contiguous_format}, + ) + if weight_val is not None: + sv = aten.slice.Tensor( # type: ignore[operator] + weight_val, 1, offsets[i], offsets[i + 1] + ) + w_slice.meta["example_value"] = sv + w_cont.meta["example_value"] = sv.contiguous() # type: ignore[operator] + cache[key] = w_cont + # bias rides on the first piece only; folding it into the + # reduce-add would just be an extra node. + out_i = graph.call_function( # type: ignore[operator] + torch.nn.functional.linear, + args=(part, w_cont, bias if i == 0 else None), + ) + # Each synthesized node gets its own fake val computed from its + # own operands, the way BatchLinearLHSFusion does. The old code + # aliased the whole linear's fake tensor onto every piece and + # every reduce-add, sharing one FakeTensor object across + # distinct nodes. + part_val = part.meta.get("example_value", part.meta.get("val")) + w_cont_val = w_cont.meta.get("example_value") + if part_val is not None and w_cont_val is not None: + out_i.meta["example_value"] = torch.nn.functional.linear( + part_val, w_cont_val, bias_val if i == 0 else None + ) + partials.append(out_i) + + acc = partials[0] + for out_i in partials[1:]: + prev = acc + acc = graph.call_function(operator.add, args=(prev, out_i)) # type: ignore[operator] + prev_val = prev.meta.get("example_value") + out_val = out_i.meta.get("example_value") + if prev_val is not None and out_val is not None: + acc.meta["example_value"] = torch.add(prev_val, out_val) + + node.replace_all_uses_with(acc) + graph.erase_node(node) # type: ignore[operator] + counters["inductor"]["cat_linear"] += 1 + + +@register_fusion("batch_layernorm") +class BatchLayernormFusion(BatchFusion): + """ + Batch layer norm fusion in pre grad pass + """ + + def match(self, node: torch.fx.Node): + if CallFunctionVarArgs(torch.nn.functional.layer_norm).match(node): + input = get_arg_value(node, 0, "input") + weight = get_arg_value(node, 2, "weight") + bias = get_arg_value(node, 3, "bias") + if self.graph_search_options.get("fuse_nodes_with_same_users", False): + users = [user.target for user in node.users] + else: + users = "" # type: ignore[assignment] + group_key = ( + ( + "batch_layernorm", + str(input.meta["example_value"].shape), + str(weight.meta["example_value"].shape) + if weight is not None + else "", + str(bias.meta["example_value"].shape) if bias is not None else "", + str(get_arg_value(node, 1, "normalized_shape")), + str(get_arg_value(node, 4, "eps")), + str(users), + ) + if "example_value" in input.meta + and is_node_meta_valid(weight) + and is_node_meta_valid(bias) + else None + ) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: list[torch.fx.Node]): + group_inputs = [] + group_shapes = [] + group_weights = [] + group_biases = [] + group_epss = [] + group_nodes = [] + group_inputs_metadata = [] + group_biases_metadata = [] + group_weights_metadata = [] + for node in subset: + group_nodes.append(node) + input = get_arg_value(node, 0, "input") + group_inputs.append(input) + group_inputs_metadata.append(input.meta["example_value"]) + group_shapes.append(get_arg_value(node, 1, "normalized_shape")) + weight = get_arg_value(node, 2, "weight") + group_weights.append(weight) + if weight is not None and hasattr(weight, "meta"): + group_weights_metadata.append(weight.meta["example_value"]) + bias = get_arg_value(node, 3, "bias") + group_biases.append(bias) + if bias is not None and hasattr(bias, "meta"): + group_biases_metadata.append(bias.meta["example_value"]) + eps = get_arg_value(node, 4, "eps") + if eps is None: + eps = 1e-5 + group_epss.append(eps) + stack_dim = -1 - len(group_shapes[-1]) + + if all(bias is None for bias in group_biases): + group_biases = None # type: ignore[assignment] + if all(weight is None for weight in group_weights): + group_weights = None # type: ignore[assignment] + if not all(eps == group_epss[0] for eps in group_epss): + raise AssertionError("all epsilon values must be equal") + + with graph.inserting_before(subset[0]): # type: ignore[operator] + stack_input = graph.call_function( # type: ignore[operator] + torch.stack, args=(group_inputs,), kwargs={"dim": stack_dim} + ) + update_stack_example_value(stack_input, group_inputs_metadata, stack_dim) + if group_weights is not None: + stack_weight = graph.call_function( # type: ignore[operator] + torch.stack, args=(group_weights,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_weight, group_weights_metadata) + else: + stack_weight = None + if group_biases is not None: + stack_bias = graph.call_function( # type: ignore[operator] + torch.stack, args=(group_biases,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_bias, group_biases_metadata) + else: + stack_bias = None + + batch_layer_norm = graph.call_function( # type: ignore[operator] + torch.nn.functional.layer_norm, + args=(stack_input, group_shapes[-1]), + kwargs={"eps": group_epss[-1]}, + ) + batch_layer_norm.meta["example_value"] = stack_input.meta["example_value"] + + if group_weights is not None and group_biases is not None: + previous_batch_layer_norm_meta = batch_layer_norm.meta["example_value"] + batch_layer_norm = graph.call_function( # type: ignore[operator] + torch.mul, args=(stack_weight, batch_layer_norm) + ) + update_pointwise_example_value( + batch_layer_norm, + # pyrefly: ignore [missing-attribute] + stack_weight.meta["example_value"], + previous_batch_layer_norm_meta, + torch.mul, + ) + previous_batch_layer_norm_meta = batch_layer_norm.meta["example_value"] + batch_layer_norm = graph.call_function( # type: ignore[operator] + torch.add, args=(stack_bias, batch_layer_norm) + ) + update_pointwise_example_value( + batch_layer_norm, + # pyrefly: ignore [missing-attribute] + stack_bias.meta["example_value"], + previous_batch_layer_norm_meta, + torch.add, + ) + elif group_weights is not None and group_biases is None: + previous_batch_layer_norm_meta = batch_layer_norm.meta["example_value"] + # pyrefly: ignore [not-callable] + batch_layer_norm = graph.call_function( + torch.mul, args=(stack_weight, batch_layer_norm) + ) + update_pointwise_example_value( + batch_layer_norm, + # pyrefly: ignore [missing-attribute] + stack_weight.meta["example_value"], + previous_batch_layer_norm_meta, + torch.mul, + ) + elif group_weights is None and group_biases is not None: + previous_batch_layer_norm_meta = batch_layer_norm.meta["example_value"] + # pyrefly: ignore [not-callable] + batch_layer_norm = graph.call_function( + torch.add, args=(stack_bias, batch_layer_norm) + ) + update_pointwise_example_value( + batch_layer_norm, + # pyrefly: ignore [missing-attribute] + stack_bias.meta["example_value"], + previous_batch_layer_norm_meta, + torch.add, + ) + + batch_layer_norm_unbind = graph.call_function( # type: ignore[operator] + torch.unbind, + args=(batch_layer_norm,), + kwargs={"dim": stack_dim}, + ) + update_stack_example_value( + batch_layer_norm_unbind, + batch_layer_norm.meta["example_value"], + op=torch.unbind, + dim=stack_dim, + ) + + for i, node in enumerate(group_nodes): + with graph.inserting_after(batch_layer_norm_unbind): # type: ignore[operator] + new_node = graph.call_function( # type: ignore[operator] + operator.getitem, args=(batch_layer_norm_unbind, i) + ) + node.replace_all_uses_with(new_node) + new_node.meta.update(node.meta) + graph.erase_node(node) # type: ignore[operator] + counters["inductor"]["batch_layernorm"] += 1 + + +class BatchPointwiseOpsPreGradFusion(BatchPointwiseOpsFusionFactory): + """ + Batch pointwise ops (e.g., sigmoid, relu, tanh) fusion in pre grad pass. + We fuse it in random place, and the introduced stack node may be merged in split cat. + """ + + def __init__(self, op, **kwargs) -> None: + super().__init__(op, **kwargs) + self.op = op + + def match(self, node: torch.fx.Node): + input = get_arg_value(node, 0, "input") + if CallFunctionVarArgs(self.op).match(node) and is_node_meta_valid(node): + if self.graph_search_options.get("fuse_nodes_with_same_parent", False): + # pyre-fixme[16] + parent = node.args[0] + parent = parent.target if parent is not None else "" # type: ignore[union-attr] + else: + parent = "" + # for relu op, we also use the inplace to construct the key + group_key = ( + "batch_" + self.op.__name__.lower().split(".")[0], + str(input.meta["example_value"].shape), + str(node.kwargs.get("inplace", False)), + str(parent), + ) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: list[torch.fx.Node]): + batch_nodes = [] + batch_inputs = [] + batch_inputs_metadata = [] + + for node in subset: + batch_nodes.append(node) + input = get_arg_value(node, 0, "input") + batch_inputs.append(input) + batch_inputs_metadata.append(input.meta["example_value"]) + + with graph.inserting_before(subset[0]): # type: ignore[operator] + stack_inputs = graph.call_function( # type: ignore[operator] + torch.stack, args=(batch_inputs,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_inputs, batch_inputs_metadata) + if self.op is torch.nn.functional.relu: + batch_op = graph.call_function( # type: ignore[operator] + self.op, + args=(stack_inputs,), + kwargs={"inplace": subset[0].kwargs.get("inplace", False)}, + ) + batch_op.meta["example_value"] = self.op( + stack_inputs.meta["example_value"], + # pyrefly: ignore [bad-argument-type] + inplace=subset[0].kwargs.get("inplace", False), + ) + else: + batch_op = graph.call_function( # type: ignore[operator] + self.op, + args=(stack_inputs,), + ) + batch_op.meta["example_value"] = self.op( + stack_inputs.meta["example_value"] + ) + unbind_op = graph.call_function( # type: ignore[operator] + torch.unbind, args=(batch_op,), kwargs={"dim": 0} + ) + unbind_op.meta["example_value"] = torch.unbind( + batch_op.meta["example_value"], dim=0 + ) + for i, node in enumerate(batch_nodes): + with graph.inserting_after(unbind_op): # type: ignore[operator] + getitem = graph.call_function(operator.getitem, args=(unbind_op, i)) # type: ignore[operator] + node.replace_all_uses_with(getitem) + getitem.meta.update(node.meta) + graph.erase_node(node) # type: ignore[operator] + counters["inductor"]["batch_" + self.op.__name__.lower().split(".")[0]] += 1 + + +class BatchPointwiseOpsPostGradFusion(BatchPointwiseOpsFusionFactory): + """ + Batch pointwise ops (e.g., sigmoid, relu, tanh) fusion in post grad pass. + The introduced stack node may be merged in split cat. + """ + + def __init__(self, op, **kwargs) -> None: + super().__init__(op, **kwargs) + self.op = op + + def match(self, node: torch.fx.Node): + input = get_arg_value(node, 0, "input") + if CallFunctionVarArgs(self.op).match(node) and is_node_meta_valid(node): + # for relu op, we also use the inplace to construct the key + # we batch the ops with same parent to enable followup split cat + parent = node.args[0] + parent = ( + parent.target # type: ignore[union-attr] + if self.graph_search_options.get("fuse_nodes_with_same_parent", False) + else "" + ) + group_key = ( + "batch_aten_" + self.op.__name__.lower().split(".")[0], + str(input.meta["val"].shape), + str(node.kwargs.get("inplace", False)), + # pyre-fixme[16] + str(parent), + ) + else: + group_key = None + return group_key + + def fuse(self, graph: torch.fx.GraphModule, subset: list[torch.fx.Node]): + batch_nodes = [] + batch_inputs = [] + batch_inputs_metadata = [] + + for node in subset: + batch_nodes.append(node) + input = get_arg_value(node, 0, "input") + batch_inputs.append(input) + batch_inputs_metadata.append(input.meta["val"]) + + with graph.inserting_before(subset[0]): # type: ignore[operator] + stack_inputs = decompose_stack(graph, batch_inputs) + update_stack_example_value(stack_inputs, batch_inputs_metadata) + batch_op = graph.call_function( # type: ignore[operator] + self.op, + args=(stack_inputs,), + ) + for i, node in enumerate(batch_nodes): + with graph.inserting_after(batch_op): # type: ignore[operator] + getitem = graph.call_function(aten.select, args=(batch_op, 0, i)) # type: ignore[operator] + node.replace_all_uses_with(getitem) + getitem.meta.update(node.meta) + graph.erase_node(node) # type: ignore[operator] + counters["inductor"][ + "batch_aten_" + self.op.__name__.lower().split(".")[0] + ] += 1 + + +class BatchMathOpsPreGradFusion(BatchPointwiseOpsFusionFactory): + """ + Batch simple math related ops such as nan_to_num in pre grad pass. + """ + + def __init__(self, op, **kwargs): + super().__init__(op, **kwargs) + self.op = op + + def match(self, node: torch.fx.Node): + input = get_arg_value(node, 0, "input") + if self._match_op(node) and is_node_meta_valid(node): + # check the input has the same shape and its users have the same target + # check all clamp operators have the same min and max values, and + # nan_to_num operators use the same default value. + child = next(iter(node.users.keys())) + group_key = ( + str(input.meta["example_value"].shape) + + str(node.args[1:]) + + str(node.kwargs) + + str(child.target) + ) + else: + group_key = None + return group_key + + def _match_op(self, node: torch.fx.Node) -> MatchResult: + return CallFunctionVarArgs(self.op).match(node) + + def fuse(self, graph: torch.fx.GraphModule, subset: list[torch.fx.Node]): + batch_nodes = [] + batch_inputs = [] + batch_inputs_metadata = [] + args = subset[0].args[1:] + kwargs = subset[0].kwargs + + for node in subset: + batch_nodes.append(node) + input = get_arg_value(node, 0, "input") + batch_inputs.append(input) + batch_inputs_metadata.append(input.meta["example_value"]) + + with graph.inserting_before(subset[0]): # type: ignore[operator] + stack_inputs = graph.call_function( # type: ignore[operator] + torch.stack, args=(batch_inputs,), kwargs={"dim": 0} + ) + update_stack_example_value(stack_inputs, batch_inputs_metadata) + batch_op = graph.call_function( # type: ignore[operator] + self.op, + args=(stack_inputs, *args), + kwargs=kwargs, + ) + batch_op.meta["example_value"] = self.op( + stack_inputs.meta["example_value"], *args, **kwargs + ) + unbind_op = graph.call_function( # type: ignore[operator] + torch.unbind, args=(batch_op,), kwargs={"dim": 0} + ) + unbind_op.meta["example_value"] = torch.unbind( + batch_op.meta["example_value"], dim=0 + ) + for i, node in enumerate(batch_nodes): + with graph.inserting_after(unbind_op): # type: ignore[operator] + getitem = graph.call_function(operator.getitem, args=(unbind_op, i)) # type: ignore[operator] + node.replace_all_uses_with(getitem) + getitem.meta.update(node.meta) + graph.erase_node(node) # type: ignore[operator] + counters["inductor"]["batch_" + self.op.__name__.lower().split(".")[0]] += 1 + + +@register_fusion("batch_tanh") +class BatchTanhPreGradFusion(BatchPointwiseOpsPreGradFusion): + def __init__(self, **kwargs) -> None: + super().__init__(torch.tanh, **kwargs) + + +@register_fusion("batch_sigmoid") +class BatchSigmoidPreGradFusion(BatchPointwiseOpsPreGradFusion): + def __init__(self, **kwargs) -> None: + super().__init__(torch.sigmoid, **kwargs) + + +@register_fusion("batch_relu") +class BatchReLuPreGradFusion(BatchPointwiseOpsPreGradFusion): + def __init__(self, **kwargs) -> None: + super().__init__(torch.nn.functional.relu, **kwargs) + + +@register_fusion("batch_detach") +class BatchDetachPreGradFusion(BatchMathOpsPreGradFusion): + def __init__(self, **kwargs): + super().__init__(torch.detach, **kwargs) + + def _match_op(self, node: torch.fx.Node) -> MatchResult: + return CallFunctionVarArgs(torch.detach).match(node) or CallMethodVarArgs( + "detach" + ).match(node) + + +@register_fusion("batch_nan_to_num") +class BatchNanToNumPreGradFusion(BatchMathOpsPreGradFusion): + def __init__(self, **kwargs): + super().__init__(torch.nan_to_num, **kwargs) + + +@register_fusion("batch_clamp") +class BatchClampPreGradFusion(BatchMathOpsPreGradFusion): + def __init__(self, **kwargs): + super().__init__(torch.clamp, **kwargs) + + +@register_fusion("batch_dropout") +class BatchDropoutPreGradFusion(BatchMathOpsPreGradFusion): + def __init__(self, **kwargs): + super().__init__(torch.nn.functional.dropout, **kwargs) + + +@register_fusion("batch_aten_tanh", pre_grad=False) +class BatchTanhPostGradFusion(BatchPointwiseOpsPostGradFusion): + def __init__(self, **kwargs) -> None: + super().__init__(aten.tanh.default, **kwargs) + + +@register_fusion("batch_aten_sigmoid", pre_grad=False) +class BatchSigmoidPostGradFusion(BatchPointwiseOpsPostGradFusion): + def __init__(self, **kwargs) -> None: + super().__init__(aten.sigmoid.default, **kwargs) + + +@register_fusion("batch_aten_relu", pre_grad=False) +class BatchReLuPostGradFusion(BatchPointwiseOpsPostGradFusion): + def __init__(self, **kwargs) -> None: + super().__init__(aten.relu.default, **kwargs) + + +@register_fusion("batch_aten_add", pre_grad=False) +class BatchAddPostGradFusion(BatchPointwiseMathOpsPostGradFusion): + def __init__(self, **kwargs) -> None: + super().__init__(aten.add.Tensor, **kwargs) + + +@register_fusion("batch_aten_sub", pre_grad=False) +class BatchSubPostGradFusion(BatchPointwiseMathOpsPostGradFusion): + def __init__(self, **kwargs) -> None: + super().__init__(aten.sub.Tensor, **kwargs) + + +@register_fusion("batch_aten_div", pre_grad=False) +class BatchDivPostGradFusion(BatchPointwiseMathOpsPostGradFusion): + def __init__(self, **kwargs) -> None: + super().__init__(aten.div.Tensor, **kwargs) + + +@register_fusion("batch_aten_mul", pre_grad=False) +class BatchMulPostGradFusion(BatchPointwiseMathOpsPostGradFusion): + def __init__(self, **kwargs) -> None: + super().__init__(aten.mul.Tensor, **kwargs) + + +class _OrderedSet: + def __init__(self, param=None) -> None: + if param: + self.rep = OrderedDict(dict.fromkeys(param)) + else: + self.rep = OrderedDict() + + def __contains__(self, o) -> bool: + return o in self.rep + + def __len__(self) -> int: + return self.rep.__len__() + + def append(self, o): + self.rep[o] = None + + def __iter__(self): + return self.rep.keys().__iter__() + + +def find_independent_subset_greedy( + node_list: Iterable[torch.fx.Node], + graph_search_options: dict[str, Any], +) -> Iterator[Iterable[torch.fx.Node]]: + """ + Yields a list of subsets of `node_list` where no element in the subset + depends on any other element in the subset. This results in a set of + independent nodes which can be fused together. + + The order of `node_list` is preserved within each subset so we can benefit + from split-cat elimination in later passes. + + During iteration it is only safe to mutate the graph by changing the nodes + that have been returned. + + graph_search_options: + - min_fuse_set_size: Minimum size of the subset to consider. Subsets below + this size will be ignored. + - max_fuse_set_size: Maximum size of the subset to consider. Subsets will + be broken to be at most this size. + """ + + # Compute all the children of `node` which are members of + # `interesting_nodes`. + def find_dependent_nodes(node, interesting_nodes): + visited_node_set = OrderedSet[torch.fx.Node]() + dep_set = OrderedSet[torch.fx.Node]() + + work = [node] + while work: + node = work.pop() + for input_node in node.all_input_nodes: + if input_node in interesting_nodes: + dep_set.add(input_node) + + if input_node not in visited_node_set: + visited_node_set.add(input_node) + work.append(input_node) + + return dep_set + + min_fuse_set_size = graph_search_options["min_fuse_set_size"] + max_fuse_set_size = graph_search_options["max_fuse_set_size"] + + # node_list needs to be a set because we only track the nodes that are left + # in it (and we want to do the `in` on a set, not a list). But we want to + # keep the correct order. + node_list = _OrderedSet(node_list) + + cache: dict[torch.fx.Node, OrderedSet[torch.fx.Node]] = {} + while node_list: + subset: list[torch.fx.Node] = [] + subset_deps = OrderedSet[torch.fx.Node]() + + next_round_node_list = _OrderedSet() + for node in node_list: + if len(subset) >= max_fuse_set_size or node in subset_deps: + next_round_node_list.append(node) + continue + + dep_set = cache.pop(node, None) + if dep_set is None: + dep_set = find_dependent_nodes(node, node_list) + + if not dep_set.intersection(subset): + subset.append(node) + subset_deps.update(dep_set) + else: + next_round_node_list.append(node) + cache[node] = dep_set + + if len(subset) >= min_fuse_set_size: + # Careful here - the caller uses the subsets to fuse nodes together + # so we need to clear any cache entry that contains one of the + # returned nodes because the dependency list could be different + # (larger) after the merge. + cache = {k: v for k, v in cache.items() if v.isdisjoint(subset)} + yield subset + + node_list = next_round_node_list + + +def get_fusion_candidates( + rule: GroupBatchFusionBase, + root_node: torch.fx.Node, + fused_set: OrderedSet[torch.fx.Node], +) -> collections.defaultdict[Any, list[torch.fx.Node]]: + """ + Search fusion candidates for a specific rule using BFS starting from the root node. + We only search the subgraph within graph_search_options["max_fuse_search_depth"]. + """ + q: collections.deque[tuple[int, torch.fx.Node]] = collections.deque() + + candidate_dict: collections.defaultdict[Any, list[torch.fx.Node]] = ( + collections.defaultdict(list) + ) + + if root_node.target in SEARCH_EXCLUSIONS: + return candidate_dict + + visited_set = OrderedSet[torch.fx.Node]() + + for next_node in root_node.all_input_nodes: + q.append((1, next_node)) + visited_set.add(next_node) + + while len(q) > 0: + depth, node = q.popleft() + + if node in fused_set: + continue + + key = rule.match(node) + if key is not None: + candidate_nodes = candidate_dict[key] + if node not in candidate_nodes: + candidate_nodes.append(node) + else: + if depth < rule.graph_search_options["max_fuse_search_depth"]: + for next_node in node.all_input_nodes: + if next_node not in visited_set: + visited_set.add(next_node) + q.append((depth + 1, next_node)) + + return candidate_dict + + +def apply_group_batch_fusion(graph: torch.fx.GraphModule, rule: GroupBatchFusionBase): + stable_topological_sort(graph) # type: ignore[arg-type] + fused_set = OrderedSet[torch.fx.Node]() + log_to_scuba = False + + for node in reversed(graph.nodes): # type: ignore[arg-type] + candidates = get_fusion_candidates(rule, node, fused_set) + + for key, candidate_nodes in candidates.items(): + if len(candidate_nodes) < rule.graph_search_options["min_fuse_set_size"]: + continue + + for subset in find_independent_subset_greedy( + candidate_nodes, rule.graph_search_options + ): + rule.fuse(graph, subset) + fused_set.update(subset) + log.debug( + f"{rule.__class__.__name__}: key = {key}; subset size = {len(list(subset))}" # noqa: G004 + ) + log_to_scuba = True + if log_to_scuba: + from torch.fx._lazy_graph_module import _LazyGraphModule + + # Force graph to re-compile otherwise the output python code may be broken + gm = graph._owning_module + if isinstance(gm, _LazyGraphModule): + _LazyGraphModule.recompile() + else: + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"expected torch.fx.GraphModule, got {type(gm)}") + gm.recompile() + graph_str = gm.print_readable( + print_output=False, include_stride=True, include_device=True + ) + + name = f"optimus_{str(rule.__class__.__name__)}" + if "MTIA" in name: + name = f"cff_{str(rule.__class__.__name__)}" + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": name, + "encoding": "string", + }, + payload_fn=lambda: graph_str, + ) + + +def generate_fusion_from_config(config_options: dict[str, Any], pre_grad=True): + fusions: list[GroupBatchFusionBase] = [] + for name, options in config_options.items(): + # we skip all patterns from pattern_matcher passes (e.g., split_cat) + if name not in PRE_GRAD_FUSIONS and name not in POST_GRAD_FUSIONS: + continue + fusion_cls = PRE_GRAD_FUSIONS[name] if pre_grad else POST_GRAD_FUSIONS[name] + _options = graph_search_options.copy() + _options.update({k: v for k, v in options.items() if k != "devices"}) + fusions.append(fusion_cls(graph_search_options=_options)) # type: ignore[operator] + return fusions + + +def group_batch_fusion_passes( + graph: torch.fx.Graph, pre_grad=True, fusion_options=None +): + fusions: list[GroupBatchFusionBase] = [] + # we keep all current pre grad fusions to keep + # current implementation, will remove this later + if pre_grad: + fusions += generate_fusion_from_config( + fusion_options + if fusion_options is not None + else config.pre_grad_fusion_options, + pre_grad=True, + ) + else: + fbgemm_fusion_keys = [ + x + for x in config.post_grad_fusion_options + if ( + x not in OPTIMUS_EXCLUDE_POST_GRAD + and config.post_grad_fusion_options[x].get("require_fbgemm", False) + ) + ] + fbgemm_fusions = { + fusion: config.post_grad_fusion_options[fusion] + for fusion in fbgemm_fusion_keys + } + non_fbgemm_fusions = { + fusion: config.post_grad_fusion_options[fusion] + for fusion in config.post_grad_fusion_options + if fusion not in fbgemm_fusion_keys + } + fusions += generate_fusion_from_config(non_fbgemm_fusions, pre_grad=False) + if has_fbgemm: + fusions += generate_fusion_from_config(fbgemm_fusions, pre_grad=False) + + for i, rule in enumerate(fusions): + with GraphTransformObserver( + graph.owning_module, # pyrefly: ignore[bad-argument-type] + f"group_batch_fusion_{i}", + ): + apply_group_batch_fusion(graph, rule) # type: ignore[arg-type] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/joint_graph.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/joint_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..6eba340a8507a49a15a217cc989340690fa41780 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/joint_graph.py @@ -0,0 +1,1244 @@ +# mypy: allow-untyped-defs +import functools +import itertools +import logging +import operator +import typing +from collections import Counter +from collections.abc import Sequence +from typing import Any + +import torch +import torch._guards +import torch.utils._pytree as pytree +from torch._dynamo.utils import counters +from torch._higher_order_ops.flex_gemm import _PRESERVE_FLEX_GEMM_GEMM_OP +from torch._inductor.constant_folding import ConstantFolder +from torch._inductor.fx_passes.dedupe_symint_uses import _SymHashingDict +from torch._inductor.utils import get_gpu_type +from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + guard_or_true, + statically_known_true, +) +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._ordered_set import OrderedSet + +from .. import config +from ..custom_graph_pass import get_custom_graph_passes +from ..pattern_matcher import ( + Arg, + CallFunction, + init_once_fakemode, + KeywordArg, + Match, + MULTIPLE, + PatternMatcherPass as PatternMatcherPassBase, + register_graph_pattern, + stable_topological_sort, +) +from .decompose_mem_bound_mm import check_device +from .replace_random import replace_random_passes + + +PatternMatcherPass = functools.partial( + PatternMatcherPassBase, subsystem="joint_graph_passes" +) + +log = logging.getLogger(__name__) +early_patterns = PatternMatcherPass() +patterns = PatternMatcherPass() +aten = torch.ops.aten +prims = torch.ops.prims + +pass_patterns = [ + patterns, + PatternMatcherPass(), +] + + +def _is_lossless_fp_widening_cast( + src_dtype: torch.dtype, dst_dtype: torch.dtype +) -> bool: + if src_dtype == dst_dtype: + return True + + if not (src_dtype.is_floating_point and dst_dtype.is_floating_point): + return False + + src_info = torch.finfo(src_dtype) + dst_info = torch.finfo(dst_dtype) + + # A floating-point cast is only pointless if the first conversion cannot + # discard precision or range from the source values. + return ( + dst_info.eps <= src_info.eps + and dst_info.max >= src_info.max + and dst_info.tiny <= src_info.tiny + ) + + +@init_once_fakemode +def lazy_init(input_device: torch.device | None = None): + from .fuse_attention import _sfdp_init + from .misc_patterns import _misc_patterns_init + from .pad_mm import _pad_mm_init + + _pad_mm_init(input_device) + _sfdp_init(input_device) + _misc_patterns_init(input_device) + + +def remove_no_ops( + gm: torch.fx.GraphModule, + zeros: OrderedSet[torch.fx.Node], + ones: OrderedSet[torch.fx.Node], +): + """ + Removes operations that are essentially no-ops e.g. (+ 0, - 0, * 1, / 1) + """ + with torch.utils._python_dispatch._disable_current_modes(): + graph = gm.graph + + def fake_tensors_eq(t1, t2, fields=("shape", "dtype", "device")): + if any(not isinstance(t, torch.Tensor) for t in (t1, t2)): + return False + for field in fields: + if getattr(t1, field) != getattr(t2, field): + return False + return True + + def is_mutated(n): + """Check if a node is mutated by any in-place operation.""" + for user in n.users: + if user.op != "call_function" or not hasattr(user.target, "_schema"): + continue + for i, arg in enumerate(user.args): + if arg is n: + schema_arg = user.target._schema.arguments[i] + if schema_arg.alias_info and schema_arg.alias_info.is_write: + return True + return False + + def isScalarValue(arg): + return isinstance(arg, (int, float)) + + def replace_no_op(node, replace_input_index): + replacement = node.args[replace_input_index] + + # https://github.com/pytorch/pytorch/issues/86128 causes + # non-Tensor inputs even for ops with only Tensor inputs. + # TODO - decompose/type promote to avoid this + if not all(isinstance(arg, torch.fx.Node) for arg in node.args): + if all(isScalarValue(arg) for arg in node.args) or not isinstance( + replacement, torch.fx.Node + ): + return + + # https://github.com/pytorch/pytorch/issues/174187 + # Don't replace if the replacement value is mutated in-place. + # The original node acts as an implicit copy; removing it would + # cause users to observe the post-mutation value instead. + if is_mutated(replacement): + return + + if not fake_tensors_eq(node.meta["val"], replacement.meta["val"]): + if fake_tensors_eq( + node.meta["val"], + replacement.meta["val"], + ("shape", "device"), + ): + with graph.inserting_after(node): + replacement = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(replacement, node.meta["val"].dtype), + ) + else: + return + + node.replace_all_uses_with(replacement) + replacement.meta.update(node.meta) + graph.erase_node(node) + + for node in graph.find_nodes(op="call_function", target=aten.add.Tensor): + if len(node.args) == 2: + if ( + not any( + e in zeros or (isScalarValue(e) and e == 0) for e in node.args + ) + or node.kwargs.get("alpha", 1) != 1 + ): + continue + + replace_index = ( + 1 + if node.args[0] in zeros + or (isScalarValue(node.args[0]) and node.args[0] == 0) + else 0 + ) + replacement = node.args[replace_index] + if isinstance(replacement, torch.fx.Node): + val = replacement.meta.get("val") + if isinstance(val, torch.Tensor) and val.is_conj(): + continue + replace_no_op(node, replace_index) + + for node in graph.find_nodes(op="call_function", target=aten.sub.Tensor): + if len(node.args) == 2: + if ( + not ( + node.args[1] in zeros + or (isScalarValue(node.args[1]) and node.args[1] == 0) + ) + or node.kwargs.get("alpha", 1) != 1 + ): + continue + + replace_no_op(node, 0) + + for node in graph.find_nodes(op="call_function", target=aten.mul.Tensor): + if len(node.args) == 2: + if not any( + e in ones or (isScalarValue(e) and e == 1) for e in node.args + ): + continue + + replace_input_index = ( + 1 + if node.args[0] in ones + or (isScalarValue(node.args[0]) and node.args[0] == 1) + else 0 + ) + replace_no_op(node, replace_input_index) + + for node in graph.find_nodes(op="call_function", target=aten.div.Tensor): + if len(node.args) == 2 and ( + node.args[1] in ones + or (isScalarValue(node.args[1]) and node.args[1] == 1) + ): + replace_no_op(node, 0) + + # meta tensors returned from the graph have no data and can be replaced with empty_strided + for output_node in graph.find_nodes(op="output"): + had_meta_return = False + + def visit(n): + nonlocal had_meta_return + val = n.meta.get("val") + if isinstance(val, torch.Tensor) and val.device.type == "meta": + with graph.inserting_before(output_node): + # size/stride may be symbolic under dynamic shapes; + # materialize them so we never pass raw SymInts as args. + # Use materialize_symints (roots backed sizes on input + # placeholders) rather than create_size_node(n, d), which + # would query `n` and pin it alive, blocking the + # eliminate_dead_code() that removes this meta tensor. + size = graph.materialize_symints(val.size()) + stride = graph.materialize_symints(val.stride()) + n.replace_all_uses_with( + graph.call_function( + torch.ops.aten.empty_strided.default, + args=(size, stride), + kwargs={"dtype": val.dtype, "device": val.device}, + ) + ) + had_meta_return = True + + torch.fx.map_arg(output_node.args, visit) + if had_meta_return: + graph.eliminate_dead_code() + + +def remove_redundant_views(gm: torch.fx.GraphModule): + """ + Removes redundant views by reusing existing ones. + """ + with torch.utils._python_dispatch._disable_current_modes(): + # A dictionary mapping a tensor to all aliased views. + views: dict[torch.fx.Node, dict[torch.dtype, torch.fx.Node]] = {} + graph = gm.graph + + for node in graph.find_nodes( + op="call_function", target=torch.ops.aten.view.dtype + ): + src = node.args[0] + to_type = node.args[1] + existing_views = views.get(src) + is_needed = True + + if existing_views: + # Replace the view with an existing view if available. + alias = existing_views.get(to_type) + if alias: + is_needed = False + node.replace_all_uses_with(alias) + alias.meta.update(node.meta) + graph.erase_node(node) + else: + from_type = src.meta["val"].dtype + existing_views = {from_type: src} + views[src] = existing_views + + if is_needed: + # Save the new alias but do not replace existing one. + existing_views.setdefault(to_type, node) + views[node] = existing_views + + # Clean up unused views. + while True: + unused_views = [alias for alias in views if not alias.users] + if len(unused_views) == 0: + break + for unused in unused_views: + views.pop(unused) + graph.erase_node(unused) + + +class UniformValueConstantFolder(ConstantFolder): + """ + Runs constant folding and replaces tensors that have a uniform value + with a tensor constructor call: aten.full([shape], value, ...) + """ + + def __init__(self, gm, skip_constructors=False) -> None: + super().__init__(gm, skip_constructors) + self.node_storages_ptrs: dict[torch.fx.Node, int] = {} + self.constant_data_ptrs: dict[torch.fx.Node, StorageWeakRef] = {} + # we may constant fold a tensor which in the graph has a sym size + # see: [constant folding refining of symints] + self.node_replacements_shapes: dict[torch.fx.Node, list[int]] = {} + + # initialize symint -> node mapping so that we can + # use symint nodes in full constructors + self.symint_nodes = _SymHashingDict() + for n in self.module.graph.nodes: # type: ignore[union-attr] + if "val" in n.meta and isinstance(n.meta["val"], torch.SymInt): + if n.meta["val"] not in self.symint_nodes: + self.symint_nodes[n.meta["val"]] = n + + # reference from torch/_funtorch/partitioners.py:get_default_op_list + self.view_op_packets = [ + aten.squeeze, + aten.unsqueeze, + aten.alias, + aten.view, + aten.slice, + aten.t, + prims.broadcast_in_dim, + aten.expand, + aten.as_strided, + aten.permute, + ] + + self.indexing_op_packets = OrderedSet( + [ + aten.slice, + ] + ) + + self._add_peephole_patterns() + + def _add_peephole_patterns(self) -> None: + """ + Add peephole patterns for nodes where we can infer constant value even if some inputs + of the node are unknown. + """ + for op in itertools.chain( + self.module.graph.find_nodes( # type: ignore[operator, union-attr] + op="call_function", target=torch.ops.aten.mul.Tensor + ), + self.module.graph.find_nodes( # type: ignore[operator, union-attr] + op="call_function", target=torch.ops.aten.mul.Scalar + ), + ): + tensor_val = op.meta.get("val", None) + if not isinstance(tensor_val, torch.Tensor): + continue + + def is_zero_int(arg: Any) -> bool: + return isinstance(arg, int) and arg == 0 + + if not any(is_zero_int(a) for a in op.args): + continue + + # x * 0 is only uniformly 0 for integer/bool dtypes. For floating + # point (and complex) dtypes nan * 0 == nan and (+/-inf) * 0 == nan, + # so folding x * 0 -> 0 would incorrectly drop NaN/Inf when x is not + # known to be finite. + if tensor_val.dtype.is_floating_point or tensor_val.dtype.is_complex: + continue + + t = torch.full( + [1], # shape + 0, # value + dtype=tensor_val.dtype, + device=tensor_val.device, + pin_memory=False, + ) + self.add_node_replacement(op, t) + + def _support_dynamic_shape(self): + return True + + def insertable_tensor_check(self, t: torch.Tensor) -> bool: + return True + + def add_node_replacement(self, node: torch.fx.Node, tensor: torch.Tensor) -> None: + self.node_replacements[node] = tensor.flatten()[0].item() + self.node_replacements_shapes[node] = node.meta["val"].shape + self.constant_data_ptrs[node] = StorageWeakRef(tensor.untyped_storage()) + + def insert_placerholder_values(self, env: dict[torch.fx.Node, Any]) -> None: + for n in self.module.graph.find_nodes(op="placeholder"): # type: ignore[operator, union-attr] + if "val" in n.meta and isinstance(n.meta["val"], torch.SymInt): + env[n] = n.meta["val"] + else: + env[n] = self.unknown_value + + def _deduce_value(self, node: torch.fx.Node): + # deduce value for full-like nodes + # 1. for constructors, substitute value is a tensor of size [1] + # 2. for view ops/indexing, substitute value is the same as the input + # 3. for pointwise ops, run node to get the substitute value + # 4. deal with some special ops + # otherwise, stop deduce value and return unknown value + + # TODO: cat, more indexing + # TODO - do on cpu to avoid syncs + + # single-elem attrs + if node.op == "get_attr" or ( + node.op == "call_function" + and node.target is torch.ops.aten.lift_fresh_copy.default + ): + out = super(ConstantFolder, self).run_node(node) + if isinstance(out, torch.Tensor) and out.numel() == 1: + return out + + # handle device_put op + if node.target == prims.device_put.default: + return super(ConstantFolder, self).run_node(node) + + # constructors ops + if ( + node.op == "call_function" + and node.target is aten.full.default + and len(node.args) == 2 + ): + args, kwargs = self.fetch_args_kwargs_from_env(node) + value = args[1] + # Don't specialize symbolic value. + if not isinstance(value, (torch.SymInt, torch.SymFloat, torch.SymBool)): + new_args = [[1], value] + return aten.full.default(*new_args, **node.kwargs) + + # handle before view ops because this changes value + if node.target is aten.view.dtype: + (input_tensor, output_dtype), kwargs = self.fetch_args_kwargs_from_env(node) + # view.dtype with different element sizes changes element count + # (e.g., complex64 [1+0j] viewed as float32 becomes [1.0, 0.0]), + # making uniform values non-uniform. Also crashes on 0-d tensors. + if input_tensor.element_size() != output_dtype.itemsize: + return self.unknown_value + return super(ConstantFolder, self).run_node(node) + + # view ops, return input tensor, the first argument + if hasattr(node.target, "overloadpacket") and ( + node.target.overloadpacket in self.view_op_packets + or node.target.overloadpacket in self.indexing_op_packets + ): + if not isinstance(node.args[0], torch.fx.Node): + raise AssertionError(f"expected fx.Node, got {type(node.args[0])}") + return self.env[node.args[0]] + + # we don't want to return unknown value for symints so that we can + # still constant fold through their use in constructors or views + # if we see them in a pointwise node (e.g., tensor * symint) + # we will bail + if "val" in node.meta and isinstance(node.meta["val"], torch.SymInt): + return node.meta["val"] + + # pointwise ops + if isinstance(node.target, torch._ops.OpOverload) and ( + torch.Tag.pointwise in node.target.tags + or node.target is torch.ops.aten.scalar_tensor.default + ): + args, kwargs = self.fetch_args_kwargs_from_env(node) + flattened_inputs = pytree.arg_tree_leaves(*args, **kwargs) + + if any(isinstance(inp, torch.SymInt) for inp in flattened_inputs): + return self.unknown_value + + # we run the ops with dim 1, so remove memory_format to avoid error + kwargs = dict(kwargs) + kwargs.pop("memory_format", None) + + return node.target(*args, **kwargs) + + return self.unknown_value + + +def _has_self_referential_shape( + shapes: list[int | torch.fx.Node], node: torch.fx.Node +) -> bool: + """ + Check if any shape in `shapes` depends on `node`. + + This is used to detect cycles when constant_fold_uniform_value creates a + replacement full() node whose shape includes a sym_size computed from the + original tensor being replaced. + + Checks direct args only - shape nodes typically come from sym_size(tensor, dim) + where tensor is a direct arg. + """ + for shape_node in shapes: + if isinstance(shape_node, torch.fx.Node): + if node in shape_node.args: + return True + return False + + +def constant_fold_uniform_value(gm: torch.fx.GraphModule): + """Runs constant folding and replaces constants which can be constructed with a single `full` call. Calls into remove_no_ops.""" + with torch.utils._python_dispatch._disable_current_modes(): + aten = torch.ops.aten + + # Constant folding can leak memory, especially with repeated compilation, so we are only going to + # remove constants which can be replaced with a constructor. + cf = UniformValueConstantFolder(gm) + cf.run() + + node_replacements = cf.node_replacements + + # note: [constant folding refining of symints] + # constant folding will partially evaluate a graph such that values which have dependencies which + # are entirely known at compile time may also become compile time constants. in some cases, + # this will include symints which we had not yet previously deduced are guaranteed a + # constant value and is then deduced in constant folding. an example is: + # unbacked_symint_eq_11 = torch.full((), 11).item() + # torch.full((unbacked_symint_eq_11,), 0) + node_replacements_shapes = cf.node_replacements_shapes + + graph = gm.graph + + zeros = OrderedSet[Any]() + ones = OrderedSet[Any]() + + # Got failures in `test_is_set_to_cuda` if we change aliasing on constants, + # so just constant-ify if a Tensor is unaliased + constant_data_ptr_count: typing.Counter[StorageWeakRef] = Counter() + + for node in cf.node_replacements: + constant_data_ptr_count[cf.constant_data_ptrs[node]] += 1 + + for node, value in node_replacements.items(): + # we don't have a functional way right now of instantiating a non-contiguous tensor with full/zeros/ones right now + # hasn't shown up to be important yet + if "val" not in node.meta: + # This can only happen in AOTI + continue + + fake_tensor = node.meta["val"] + if not fake_tensor.is_contiguous(memory_format=torch.contiguous_format): + continue + + # TODO - not sure about lossy uint->python value->uint conversions + if fake_tensor.dtype in ( + torch.uint8, + torch.uint16, + torch.uint32, + torch.uint64, + ): + continue + + if constant_data_ptr_count[cf.constant_data_ptrs[node]] > 1: + continue + + with graph.inserting_after(node): + # the conversion from tensor and back to value can be lossy, just use the original full ctor value + if ( + node.op == "call_function" + and node.target is aten.full.default + and len(node.args) == 2 + ): + value = node.args[1] + + # refines symints, see [constant folding refining of symints] above + for runtime_size, compile_time_size in zip( + node_replacements_shapes[node], fake_tensor.shape + ): + torch._check(runtime_size == compile_time_size) + + # replace SymInt as Node before creating a new full node + # e.g. (1, s0) -> (1, arg0_1) + node_shape = node_replacements_shapes[node] + if not all( + not isinstance(s, torch.SymInt) or s in cf.symint_nodes + for s in node_shape + ): + continue + + shapes = [ + cf.symint_nodes[s] if isinstance(s, torch.SymInt) else s + for s in node_replacements_shapes[node] + ] + + # Check if any shape depends on a symint that was computed from + # the node being replaced - this would create a cycle + if _has_self_referential_shape(shapes, node): + continue + + # zeros and ones just get traced into full, so we insert those + new_node = graph.call_function( + aten.full.default, + args=(shapes, value), + kwargs={ + "dtype": fake_tensor.dtype, + "layout": torch.strided, + "device": fake_tensor.device, + "pin_memory": node.kwargs.get("pin_memory", False), + }, + ) + + new_node.meta.update(node.meta) + node.replace_all_uses_with(new_node) + graph.erase_node(node) + + if value == 0: + zeros.add(new_node) + elif value == 1: + ones.add(new_node) + + remove_no_ops(gm, zeros, ones) + remove_redundant_views(gm) + + +def canonicalize_quant_mapping(gm: torch.fx.GraphModule): + """ + + + torch.ops.higher_order.invoke_quant_packed(repeated_subgraph0, 'quant_invoke_0_0', (arg0_1, arg1_1)); + -> + torch.ops.higher_order.invoke_quant(repeated_subgraph0, arg0_1, arg1_1, scheme = 'nf4'); + """ + graph = gm.graph + invoke_quant_invocations = graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_quant_packed + ) + for invoke_quant in invoke_quant_invocations: + kwargs = dict(invoke_quant.kwargs) + + quant_options_node = kwargs.pop("quant_options", None) + if quant_options_node is not None: + if not isinstance(quant_options_node, torch.fx.Node): + raise AssertionError( + f"expected fx.Node, got {type(quant_options_node)}" + ) + quant_options = torch._higher_order_ops.InvokeQuant( + *invoke_quant.kwargs["quant_options"].args, + **invoke_quant.kwargs["quant_options"].kwargs, + ) + else: + quant_options = torch._higher_order_ops.InvokeQuant() + + subgraph, *args = invoke_quant.args + with gm.graph.inserting_before(invoke_quant): + invoke_quant_replacement = graph.call_function( + torch._higher_order_ops.invoke_quant, + (subgraph, *args), + # pyrefly: ignore [bad-argument-type] + kwargs, + ) + invoke_quant_replacement.meta.update(subgraph.meta) + invoke_quant_replacement.meta["quant_options"] = quant_options + + invoke_quant.replace_all_uses_with(invoke_quant_replacement) + graph.erase_node(invoke_quant) + + if quant_options_node and len(quant_options_node.users) == 0: + graph.erase_node(quant_options_node) + + first_user = next(iter(invoke_quant_replacement.users)) + + if ( + len(invoke_quant_replacement.users) == 1 + and len(subgraph.users) == 1 + and first_user.target is operator.getitem + and first_user.args[1] == 0 + ): + subgraph_graph = getattr(gm, subgraph.target) + output_node = torch._inductor.utils.output_node(subgraph_graph) + if not ( + isinstance(output_node.args[0], (list, tuple)) + and len(output_node.args[0]) == 1 + ): + raise AssertionError( + "expected subgraph output to be a single-element list or tuple" + ) + + unpacked_output = output_node.args[0][0] + # pyrefly: ignore [bad-argument-type] + output_node.args = (unpacked_output,) + if "val" in output_node.meta: + output_node.meta["val"] = output_node.meta["val"][0] + subgraph_graph.recompile() + + invoke_quant_replacement.meta.update(first_user.meta) + first_user.replace_all_uses_with(invoke_quant_replacement) + graph.erase_node(first_user) + + +def canonicalize_aten_ir_passes(gm: torch.fx.GraphModule): + """ + Canonicalization passes that will run immediately after aot autograd + tracing. Thsis must be run before all other graph passes. + """ + canonicalize_quant_mapping(gm) + + +def joint_graph_passes( + graph: torch.fx.GraphModule, + input_device: torch.device | None = None, +): + """ + Run FX transformations on the joint forwards+backwards graph. + """ + GraphTransformObserver = functools.partial( + torch.fx.passes.graph_transform_observer.GraphTransformObserver, + subsystem="joint_graph_passes", + ) + + lazy_init(input_device) + count = 0 + + # must occur before other passes + canonicalize_aten_ir_passes(graph) + + for joint_custom_pre_pass in get_custom_graph_passes(config.joint_custom_pre_pass): + GraphTransformObserver(graph, "joint_custom_pre_pass").apply_graph_pass( + joint_custom_pre_pass + ) + count += 1 + + from .post_grad import remove_noop_ops + + GraphTransformObserver(graph, "remove_noop_ops").apply_graph_pass(remove_noop_ops) + + if config.joint_graph_constant_folding: + GraphTransformObserver(graph, "constant_fold_uniform_value").apply_gm_pass( + constant_fold_uniform_value + ) + + if config.pattern_matcher: + count += early_patterns.apply(graph.graph) + + # Make sure AutoChunker happens before pad_mm so we don't need + # to handle padding when searching for chunking patterns. + if config.auto_chunker.enable: + from .auto_chunker import CantChunk, chunk + + try: + graph = chunk(graph) + except CantChunk: + auto_chunker_log = torch._logging.getArtifactLogger( + __name__, "auto_chunker" + ) + auto_chunker_log.debug("AutoChunker fail.", exc_info=True) + + if config.pattern_matcher: + for i, patterns in enumerate(pass_patterns): + maybe_count = GraphTransformObserver( + graph, f"pass_pattern_{i}" + ).apply_graph_pass(patterns.apply) + count += maybe_count if maybe_count is not None else 0 + + if not config.fallback_random: + # not trying into the bisector because decomps may have already affected rng reproducibility + # we'll instead explicitly turn off the config + count += replace_random_passes(graph) + + for joint_custom_post_pass in get_custom_graph_passes( + config.joint_custom_post_pass + ): + GraphTransformObserver(graph, "joint_custom_post_pass").apply_graph_pass( + joint_custom_post_pass + ) + count += 1 + + if count: + stable_topological_sort(graph.graph) + graph.graph.lint() + graph.recompile() + return graph + + +@register_graph_pattern( + CallFunction( + torch.ops.prims.iota.default, + KeywordArg("length"), + start=KeywordArg("start"), + step=KeywordArg("step"), + dtype=KeywordArg("dtype"), + device=KeywordArg("device"), + requires_grad=KeywordArg("requires_grad"), + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=patterns, +) +def fix_iota_device(match: Match, length, start, step, dtype, device, requires_grad): + """ + Eager supports: + + aten.index(cuda_tensor, torch.arange(..., device="cpu")) + + But this results in an implicit host-device-copy and breaks cudagraphs. + Rewrite the arange to use CUDA. + """ + (node,) = match.nodes + user_devices = OrderedSet[torch.device]() + for user in node.users: + if ( + user.op == "call_function" + and user.target in (aten.index.Tensor, aten.index_put.default) + and hasattr(user.meta.get("val"), "device") + ): + user_devices.add(user.meta["val"].device) # type: ignore[union-attr] + else: + return # bail out + + if len(user_devices) == 1 and "val" in node.meta: + (user_device,) = user_devices + if device.type != user_device.type: + repl = match.graph.call_function( + torch.ops.prims.iota.default, + (length,), + { + "start": start, + "step": step, + "dtype": dtype, + "device": user_device, + "requires_grad": requires_grad, + }, + ) + repl.meta.update(node.meta) + repl.meta["val"] = repl.meta["val"].to(user_device) + node.replace_all_uses_with(repl) + match.erase_nodes() + + +@register_graph_pattern( + CallFunction( + torch.ops.prims.convert_element_type.default, + CallFunction( + torch.ops.prims.convert_element_type.default, + KeywordArg("arg"), + KeywordArg("dtype1"), + ), + KeywordArg("dtype2"), + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=patterns, +) +def pointless_convert(match: Match, arg, dtype1: torch.dtype, dtype2: torch.dtype): + """Remove chain of dtype conversions often created by AMP""" + graph = match.graph + node = match.output_node() + allowed = torch.float16, torch.bfloat16, torch.float32, torch.float64 + arg_val = arg.meta.get("val", None) + if not isinstance(arg_val, torch.Tensor): + return + + if arg_val.dtype in allowed and dtype1 in allowed and dtype2 in allowed: + # A narrower intermediate can be worth materializing before upcasting. + if dtype1.itemsize < dtype2.itemsize: + return + if config.emulate_precision_casts and not _is_lossless_fp_widening_cast( + arg_val.dtype, dtype1 + ): + return + repl = graph.call_function( + torch.ops.prims.convert_element_type.default, (arg, dtype2) + ) + repl.meta.update(node.meta) + node.replace_all_uses_with(repl) + match.erase_nodes() + + +def definitely_equal( + old_sizes: Sequence[torch.SymInt | int], + new_sizes: Sequence[torch.SymInt | torch.fx.Node | int], +) -> bool: + """ + Leverage guard_or_true/false to compare if two lists of int/symint are equal. + Useful to compare sizes, strides etc. + + Can handle -1 in new_sizes which happens in the size arguments of a + view op. old_sizes is supposed to be the tensor shape and should not + contain -1. + + new_sizes can contains fx.Node when dynamic shape is enabled. In that + case new_sizes[i].meta['val'] contains the real torch.SymInt. + """ + + num_neg1 = 0 + + if len(old_sizes) != len(new_sizes): + return False + + for lhs_item, rhs_item in zip(old_sizes, new_sizes): + if isinstance(rhs_item, torch.fx.Node): + rhs_item = rhs_item.meta["val"] + + if not isinstance(lhs_item, (int, torch.SymInt)): + raise AssertionError(type(lhs_item)) + if not isinstance(rhs_item, (int, torch.SymInt)): + raise AssertionError(type(rhs_item)) + + # It still makes sense to call guard_or_true/false since lhs_item + # rhs_item are torch.SymInt rather than sympy expressions when + # dynamic shape is enabled. + if guard_or_false(lhs_item == rhs_item): + continue + + if guard_or_true(rhs_item != -1): + return False + + num_neg1 += 1 + + if num_neg1 > 1: + return False + return True + + +@register_graph_pattern( + CallFunction(torch.ops.aten.view.default, KeywordArg("arg"), KeywordArg("size")), + # pyrefly: ignore [bad-argument-type] + pass_dict=early_patterns, +) +def pointless_view(match: Match, arg, size): + """Remove no-op view""" + node = match.output_node() + arg_size = list(node.args[0].meta["val"].shape) # type: ignore[union-attr] + if definitely_equal(arg_size, size): + node.replace_all_uses_with(node.args[0]) # type: ignore[arg-type] + match.erase_nodes() + + +@register_graph_pattern( + CallFunction( + aten.view.default, + CallFunction(aten.view.default, KeywordArg("arg"), KeywordArg("size1")), + KeywordArg("size2"), + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=early_patterns, +) +def pointless_view_pair(match: Match, arg, size1, size2): + """ + Remove a pair of views that are pointless. + """ + node = match.output_node() + arg_size = list(arg.meta["val"].shape) + if definitely_equal(arg_size, size2): + node.replace_all_uses_with(arg) + match.erase_nodes() + counters["inductor"]["removed_pointless_view_pair"] += 1 + + +@register_graph_pattern( + CallFunction( + aten.permute.default, + CallFunction(aten.permute.default, KeywordArg("arg"), KeywordArg("perm1")), + KeywordArg("perm2"), + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=early_patterns, +) +def pointless_permute_pair(match: Match, arg, perm1, perm2): + rank = len(perm1) + if len(perm2) != rank: + raise AssertionError(f"expected len(perm2) == {rank}, got {len(perm2)}") + + for i in range(rank): + if perm1[perm2[i]] != i: + return # bail out + node = match.output_node() + node.replace_all_uses_with(arg) + match.erase_nodes() + + +@register_graph_pattern( + CallFunction( + aten.bmm, + Arg(), + Arg(), + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=patterns, +) +def bmm_to_mm(match: Match, mat1: torch.fx.Node, mat2: torch.fx.Node): + """Convert bmm to mm when batch size is 1""" + # See Note [Preserving FlexGEMM body GEMMs]. + if match.output_node().meta.get(_PRESERVE_FLEX_GEMM_GEMM_OP): + return + + def repl(a, b): + return torch.mm(a.squeeze(0), b.squeeze(0)).unsqueeze(0) + + if ( + check_device(mat1.meta["val"], mat2.meta["val"], get_gpu_type()) + and statically_known_true(mat1.meta["val"].shape[0] == 1) + and statically_known_true(mat2.meta["val"].shape[0] == 1) + ): + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(repl, [mat1, mat2]) + + +# When softmax is used with temperature or other scaling, we get the pattern +# +# scale(x) - scale(x).amax(dim, keepdim=True) +# +# which is expected to be at most zero, but we may end up with numerical +# discrepancies # between the recomputed values of scale(x) inside and out +# of the reduction, # depending on compiler optimizations, e.g. use of fma +# instructions. +# +# Here we replace it with the mathematically equivalent, +# +# scale(x - x.amax(dim, keepdim=True)) +# +# which is more stable as we only compute the scaling once. +# +# NOTE: This pattern must come after fused attention matching! + + +def _partial_softmax_pattern(linear_func, reverse=False, to_dtype=False): + # Allow matching inp * other and other * input + if reverse: + scaled = CallFunction( + linear_func, KeywordArg("other"), KeywordArg("inp"), _users=MULTIPLE + ) + else: + scaled = CallFunction( + linear_func, KeywordArg("inp"), KeywordArg("other"), _users=MULTIPLE + ) + if to_dtype: + scaled = CallFunction( + prims.convert_element_type, scaled, KeywordArg("dtype"), _users=MULTIPLE + ) + amax = CallFunction( + aten.amax.default, scaled, KeywordArg("dim"), KeywordArg("keepdim") + ) + return CallFunction(aten.sub.Tensor, scaled, amax) + + +def _preserve_scaled_softmax_nonfinite_semantics(scaled, stable, dim, keepdim): + # This pattern also matches the raw scaled - amax(scaled) expression. Only + # use the stable form when it preserves that expression's nonfinite behavior. + original = scaled - torch.amax(scaled, dim=dim, keepdim=keepdim) + finite_scaled = torch.all(torch.isfinite(scaled), dim=dim, keepdim=True) + return torch.where(finite_scaled, stable, original) + + +def _other_is_broadcasted_in_dim(match): + # Check that the scaling factor is constant across the reduction dim, + # so scaling doesn't change which index corresponds to the maximum value + other = match.kwargs["other"] + if isinstance(other, (int, float)): + return True + + inp = match.kwargs["inp"] + if not all(isinstance(x, torch.fx.Node) for x in (inp, other)): + return False + + inp_example = inp.meta["val"] + other_example = other.meta["val"] + if isinstance(other_example, (torch.SymInt, torch.SymFloat)): + return True + + if not all(isinstance(x, torch.Tensor) for x in (inp_example, other_example)): + return False + + inp_ndim = inp_example.ndim + other_shape = other_example.shape + if inp_ndim < len(other_shape): + return False + + # Pad other_shape to the same ndim as inp + other_shape = [1] * (inp_ndim - len(other_shape)) + list(other_shape) + + dim = match.kwargs["dim"] + if isinstance(dim, int): + dim = (dim,) + + if any(d >= len(other_shape) for d in dim): + return False + + return all(statically_known_true(other_shape[d] == 1) for d in dim) + + +def mul_softmax_pattern(match: Match, *, inp, other, dim, keepdim, dtype=None): + def repl(inp, other): + scaled = inp * other + if dtype is not None: + scaled = scaled.to(dtype) + inp = inp.to(dtype) + + sign: int | float | torch.Tensor + if isinstance(other, (int, float, torch.SymInt, torch.SymFloat)): + sign = 1 if other >= 0 else -1 + else: + one = torch.scalar_tensor(1, dtype=inp.dtype, device=inp.device) + sign = torch.where(other >= 0, one, -one) + + inp = inp * sign + max_ = torch.amax(inp, dim=dim, keepdim=keepdim) + + stable = (inp - max_) * (sign * other) + return _preserve_scaled_softmax_nonfinite_semantics( + scaled, stable, dim, keepdim + ) + + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(repl, [inp, other]) + + +for reverse, to_dtype in itertools.product((False, True), repeat=2): + register_graph_pattern( + _partial_softmax_pattern(aten.mul.Tensor, reverse=reverse, to_dtype=to_dtype), + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[1], + extra_check=_other_is_broadcasted_in_dim, + )(mul_softmax_pattern) + + +def div_softmax_pattern(match: Match, *, inp, other, dim, keepdim, dtype=None): + def repl(inp, other): + scaled = inp / other + if dtype is not None: + scaled = scaled.to(dtype) + inp = inp.to(dtype) + + sign: int | float | torch.Tensor + if isinstance(other, (int, float, torch.SymInt, torch.SymFloat)): + sign = 1 if other >= 0 else -1 + else: + one = torch.scalar_tensor(1, dtype=inp.dtype, device=inp.device) + sign = torch.where(other >= 0, one, -one) + + inp = inp * sign + max_ = torch.amax(inp, dim=dim, keepdim=keepdim) + + stable = (inp - max_) / (sign * other) + return _preserve_scaled_softmax_nonfinite_semantics( + scaled, stable, dim, keepdim + ) + + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(repl, [inp, other]) + + +for to_dtype in (False, True): + register_graph_pattern( + _partial_softmax_pattern(aten.div.Tensor, to_dtype=to_dtype), + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[1], + extra_check=_other_is_broadcasted_in_dim, + )(div_softmax_pattern) + + +def scatter_upon_const_tensor_extra_check(m): + if not config.optimize_scatter_upon_const_tensor: + return False + full_shape = m.kwargs["shape"] + selector = m.kwargs["selector"] + dim = m.kwargs["dim"] + if dim < 0: + dim += len(full_shape) + + selector_ft = selector.meta["val"] + if selector_ft.dim() != len(full_shape): + raise AssertionError( + f"expected selector_ft.dim() == {len(full_shape)}, got {selector_ft.dim()}" + ) + + for idx, select_sz, full_sz in zip( + itertools.count(), selector_ft.shape, full_shape + ): + if idx == dim: + continue + + # TODO: the pattern can be updated to support the case that index tensor + # is shorter. But that will need a more complex condition expression + # especially for multi-dimensional tensors. + # Skip it for now. + if isinstance(full_sz, torch.fx.Node): + full_sz = full_sz.meta["val"] + if select_sz < full_sz: + return False + + # Actually we can support small size larger than 1. It would be a bit + # tedious. E.g., we load all the index values (not many) and compare + # them with the position in tensor to decide what value to return. + return selector_ft.size(dim) == 1 + + +@register_graph_pattern( + CallFunction( + aten.scatter.value, + CallFunction( + aten.full, + KeywordArg("shape"), + KeywordArg("background_val"), + dtype=KeywordArg("dtype"), + ), + KeywordArg("dim"), + KeywordArg("selector"), + KeywordArg("val"), # scalar value + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=patterns, + extra_check=scatter_upon_const_tensor_extra_check, +) +def scatter_upon_const_tensor( + match: Match, shape, background_val, dtype, dim, selector, val +): + """ + Match the pattern of full+scatter into a pointwise operation in joint graph. + + TODO: Right now the scatter value must be a scalar. But we could support it + when it is a tensor as well. + """ + from torch._inductor import metrics + + # pyrefly: ignore # bad-assignment + metrics.num_matches_for_scatter_upon_const_tensor += 1 + + # Create a replacement that uses torch.where for the pointwise operation + def repl_fn(shape, background_val, dim, selector, val): + # Create a tensor of indices for the scatter dimension + length = shape[dim] + indices = torch.arange(length, device=selector.device, dtype=torch.int64) + + # Reshape indices to have size 'length' at dim, then broadcast + view_shape = [1] * len(shape) + view_shape[dim] = length + indices_view = indices.view(*view_shape) + + # Broadcast selector to match full tensor shape + selector_expanded = selector.expand(shape) + + # Create a mask for where to scatter + mask = selector_expanded == indices_view + + # Use torch.where to implement the scatter pointwise operation. + # When val and background_val are Python scalars, torch.where promotes + # the result to the default floating dtype (float32), which loses the + # const tensor's dtype. Cast back to dtype so the rewrite preserves + # aten.scatter.value semantics (the result has self's dtype, with the + # scalar value cast to it). + return torch.where(mask, val, background_val).to(dtype) + + # replace the scatter operation with pointwise equivalent + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(repl_fn, [shape, background_val, dim, selector, val]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/low_contention_collectives.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/low_contention_collectives.py new file mode 100644 index 0000000000000000000000000000000000000000..9defe56cc1fc3ab368e51b0432e1135c5f4c3ce2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/low_contention_collectives.py @@ -0,0 +1,357 @@ +from __future__ import annotations + +import logging +import warnings + +import torch +from torch.utils._ordered_set import OrderedSet + + +log = logging.getLogger(__name__) + + +def _get_collective_info(node): + """Return (is_ag, group_name) if node is an AG/RS collective, else None.""" + from torch._inductor.fx_passes.bucketing import ( + is_all_gather_into_tensor, + is_reduce_scatter_tensor, + ) + from torch._inductor.fx_passes.overlap_scheduling import get_group_name + + if is_all_gather_into_tensor(node): + return True, get_group_name(node) + if is_reduce_scatter_tensor(node): + return False, get_group_name(node) + return None + + +def replace_collectives_with_low_contention( + graph: torch.fx.Graph, +) -> None: + """Replace FSDP collectives with copy-engine symm_mem variants.""" + symm_mem = torch.ops.symm_mem + + collectives = [] + groups: OrderedSet[str] = OrderedSet() + for node in list(graph.nodes): + info = _get_collective_info(node) + if info is None: + continue + is_ag, group_name = info + collectives.append((node, is_ag, group_name)) + groups.add(group_name) + + if not collectives: + return + + # Some group names can't be resolved at compile time — skip them. + valid_groups: OrderedSet[str] = OrderedSet() + for group_name in groups: + if _enable_symm_mem(group_name): + valid_groups.add(group_name) + + # Filter to collectives whose groups we can actually resolve + collectives = [ + (node, is_ag, gn) for node, is_ag, gn in collectives if gn in valid_groups + ] + if not collectives: + return + + from torch._inductor import config + + cfg = config.aten_distributed_optimizations + min_bytes = cfg.low_contention_min_bytes_per_rank + skip_overlap_check = cfg.low_contention_skip_overlap_check + use_ag_ce_multicast = cfg.low_contention_all_gather_ce_multicast + + replacements = 0 + skipped_small = 0 + skipped_no_overlap = 0 + skipped_nvlink_contention = 0 + skipped_out_variant = 0 + for node, is_ag, group_name in collectives: + coll_type = "AG" if is_ag else "RS" + + # Size filter: LC barrier overhead dominates for small messages + if min_bytes > 0: + per_rank_bytes = _get_per_rank_bytes(node, is_ag) + if per_rank_bytes is not None and per_rank_bytes < min_bytes: + skipped_small += 1 + log.debug( + "LC skip %s %s: size %d < min_bytes %d", + coll_type, + node.name, + per_rank_bytes, + min_bytes, + ) + continue + + if not skip_overlap_check: + # Skip collectives with no compute to hide behind + if not _has_compute_bound_overlap(node, graph): + skipped_no_overlap += 1 + log.debug( + "LC skip %s %s: no compute-bound overlap", coll_type, node.name + ) + continue + + # Skip if other groups' NCCL collectives overlap on NVLink + if _has_other_group_collectives(node, group_name, graph): + skipped_nvlink_contention += 1 + log.debug( + "LC skip %s %s: overlaps other-group collectives (NVLink contention)", + coll_type, + node.name, + ) + continue + + target = None + if is_ag: + target = _select_low_contention_all_gather_target( + symm_mem, + input_node=node.args[0], + use_ag_ce_multicast=use_ag_ce_multicast, + ) + + if not _replace_collective( + node, + graph, + symm_mem, + is_ag, + group_name, + target=target, + ): + skipped_out_variant += 1 + continue + replacements += 1 + + log.info( + "Replaced %d/%d FSDP collectives " + "(skipped_small=%d, skipped_no_overlap=%d, " + "skipped_nvlink_contention=%d, skipped_out_variant=%d, " + "min_bytes=%d, skip_overlap_check=%s)", + replacements, + len(collectives), + skipped_small, + skipped_no_overlap, + skipped_nvlink_contention, + skipped_out_variant, + min_bytes, + skip_overlap_check, + ) + + +def _enable_symm_mem(group_name): + """Try to enable symmetric memory for a group. Returns True on success.""" + from torch.distributed._symmetric_memory import ( + enable_symm_mem_for_group, + is_symm_mem_enabled_for_group, + ) + + if is_symm_mem_enabled_for_group(group_name): + return True + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + enable_symm_mem_for_group(group_name) + return True + except (TypeError, RuntimeError, KeyError) as e: + log.debug("LC: cannot enable symm_mem for group %s: %s", group_name, e) + return False + + +def _has_multicast_support(device_index: int) -> bool: + try: + from torch._C._autograd import DeviceType + from torch._C._distributed_c10d import _SymmetricMemory + + return bool( + _SymmetricMemory.has_multicast_support(DeviceType.CUDA, device_index) + ) + except Exception: + return False + + +def _select_low_contention_all_gather_target( + symm_mem, + input_node, + use_ag_ce_multicast=False, +): + if not use_ag_ce_multicast: + return symm_mem._low_contention_all_gather.default + + device_index = None + input_val = input_node.meta.get("val") + if isinstance(input_val, torch.Tensor) and input_val.device.type == "cuda": + device_index = input_val.device.index + if device_index is None: + device_index = torch.cuda.current_device() + + if _has_multicast_support(device_index): + return symm_mem._low_contention_all_gather_ce_multicast.default + log.info( + "low_contention_all_gather_ce_multicast requested but multicast is not " + "supported on device %d; falling through.", + device_index, + ) + + return symm_mem._low_contention_all_gather.default + + +def _replace_collective( + node, + graph, + symm_mem, + is_ag, + group_name, + target=None, +) -> bool: + input_node = node.args[0] + if is_ag: + if target is None: + return False + if node.target is torch.ops._c10d_functional.all_gather_into_tensor_out.default: + out = node.kwargs["out"] + if target is symm_mem._low_contention_all_gather_ce_multicast.default: + target = symm_mem._low_contention_all_gather_ce_multicast_out.default + else: + # The existing low-contention all-gather has no out variant. + return False + args = (input_node, group_name, out) + else: + args = (input_node, group_name) + else: + reduce_op = node.args[1] + target = symm_mem._low_contention_reduce_scatter.default + args = (input_node, reduce_op, group_name) + + with graph.inserting_before(node): + new_node = graph.call_function(target, args=args) + new_node.meta.update(node.meta) + node.replace_all_uses_with(new_node) + graph.erase_node(node) + return True + + +def _get_per_rank_bytes(node, is_ag): + """Return per-rank message bytes for a collective, or None if unknown.""" + input_val = node.args[0].meta.get("val") if node.args else None + if not isinstance(input_val, torch.Tensor): + return None + total_bytes = input_val.nelement() * input_val.element_size() + if is_ag: + return total_bytes + # For RS, input is the full tensor; per-rank = total / group_size + group_size = node.args[2] if len(node.args) > 2 else None + if not isinstance(group_size, int) or group_size <= 0: + return None + return total_bytes // group_size + + +def _is_compute_or_contains_compute(node, graph_module): + """Check if a node is compute, including inside control_deps subgraphs.""" + from torch._inductor.fx_passes.overlap_scheduling import is_compute_node + + if is_compute_node(node): + return True + from torch._inductor.fx_passes.control_dependencies import ControlDeps + + if node.op == "call_function" and isinstance(node.target, ControlDeps): + subgraph_node = node.args[1] if len(node.args) > 1 else None + if isinstance(subgraph_node, torch.fx.Node) and subgraph_node.op == "get_attr": + if not isinstance(subgraph_node.target, str): + raise AssertionError( + f"expected str get_attr target, got {type(subgraph_node.target)}" + ) + subgraph = getattr(graph_module, subgraph_node.target, None) + if isinstance(subgraph, torch.fx.GraphModule): + for n in subgraph.graph.nodes: + if is_compute_node(n): + return True + return False + + +def _has_compute_bound_overlap(start_node, graph): + """Check if compute-bound ops exist between collective start and wait.""" + wait_node = _find_wait_for_collective(start_node) + if wait_node is None: + return False + + graph_module = graph.owning_module + in_range = False + for node in graph.nodes: + if node is start_node: + in_range = True + continue + if node is wait_node: + break + if in_range and _is_compute_or_contains_compute(node, graph_module): + return True + return False + + +def _has_other_group_collectives(start_node, group_name, graph): + """Check if other groups' collectives overlap, competing for NVLink.""" + wait_node = _find_wait_for_collective(start_node) + if wait_node is None: + return False + + in_range = False + for node in graph.nodes: + if node is start_node: + in_range = True + continue + if node is wait_node: + break + if not in_range: + continue + info = _get_collective_info(node) + if info is not None: + _, other_group = info + if other_group != group_name: + log.debug( + "LC contention %s: found %s (group %s) between start/wait", + start_node.name, + node.name, + other_group, + ) + return True + return False + + +def _is_wait_tensor(node): + """Check if node is a wait_tensor op (direct or wrapped in ControlDeps).""" + if node.op != "call_function": + return False + if node.target is torch.ops._c10d_functional.wait_tensor.default: + return True + # Handles public namespace (c10d_functional.wait_tensor) and + # ControlDeps-wrapped wait_tensor (from TBB manual scheduling) + return "wait_tensor" in node.name + + +def _find_wait_for_collective(start_node): + """Find the wait_tensor node for a collective. + + Handles multiple graph patterns: + 1. Direct: start -> wait_tensor(start) + 2. _out variant: start(out=buf) -> wait_tensor(buf) + 3. ControlDeps-wrapped: start -> control_deps(wait_tensor_subgraph, start) + """ + for user in start_node.users: + if _is_wait_tensor(user): + return user + + # For _out variants, check users of the out-buffer keyword argument. + c10d = torch.ops._c10d_functional + if start_node.target in ( + c10d.all_gather_into_tensor_out.default, + c10d.reduce_scatter_tensor_out.default, + ): + out_buf = start_node.kwargs.get("out") + if isinstance(out_buf, torch.fx.Node): + for user in out_buf.users: + if _is_wait_tensor(user): + return user + + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/memory_estimator.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/memory_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..596db64a9232f72a5d52d93daac54db5e6467f2a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/memory_estimator.py @@ -0,0 +1,454 @@ +import itertools +import logging +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass + +import torch +import torch.fx as fx +from torch.fx.experimental.symbolic_shapes import optimization_hint +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import tree_map_only + + +log = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class StorageKey: + storage: torch.UntypedStorage + device: torch.device + + def __hash__(self) -> int: + return self.storage._cdata + + def __eq__(self, other: object) -> bool: + if not isinstance(other, StorageKey): + return False + return ( + self.storage._cdata == other.storage._cdata and self.device == other.device + ) + + +class GraphAliasTracker: + """ + Tracks storage allocation and usage relationships in an FX graph. + + Differentiates between: + - Fresh allocations: nodes that allocate new storage (not views/aliases) + - Uses: nodes that use a storage as input + """ + + def __init__(self, nodes: list[fx.Node]): + # Map from node to the fresh storages it allocates (not views/aliases) + self.node_to_fresh_allocations: dict[fx.Node, OrderedSet[StorageKey]] = {} + + # Map from storage to the node that originally allocated it + self.storage_to_allocator: dict[StorageKey, fx.Node] = {} + + # Map from node to all storages it uses as inputs + self.node_to_storage_uses: dict[fx.Node, OrderedSet[StorageKey]] = {} + + # Map from storage to all nodes that use it + self.storage_to_uses: dict[StorageKey, OrderedSet[fx.Node]] = defaultdict( + OrderedSet + ) + + # Map from storage to the last node that uses it + self.storage_to_last_user: dict[StorageKey, fx.Node] = {} + + # Map from node to storages that have their last use at that node + self.node_to_storages_last_used: dict[fx.Node, OrderedSet[StorageKey]] = ( + defaultdict(OrderedSet) + ) + + # Track all output storages for each node (for building usage graph) + self.node_to_output_storages: dict[fx.Node, OrderedSet[StorageKey]] = {} + + # First pass: build storage allocations and track uses + for node in nodes: + # Get output storages + output_storages = self._get_output_storages(node) + self.node_to_output_storages[node] = output_storages + + # Track fresh allocations + fresh_allocations: OrderedSet[StorageKey] = OrderedSet() + for storage_key in output_storages: + if storage_key not in self.storage_to_allocator: + self.storage_to_allocator[storage_key] = node + fresh_allocations.add(storage_key) + self.node_to_fresh_allocations[node] = fresh_allocations + + # Track input storage uses (safe because inputs were already processed) + input_storages = self._get_input_storages(node) + self.node_to_storage_uses[node] = input_storages + for storage_key in input_storages: + self.storage_to_uses[storage_key].add(node) + + # Second pass: find last users (iterate in reverse) + for node in reversed(nodes): + input_storages = self.node_to_storage_uses[node] + for storage_key in input_storages: + if storage_key not in self.storage_to_last_user: + self.storage_to_last_user[storage_key] = node + self.node_to_storages_last_used[node].add(storage_key) + + @staticmethod + def _get_output_storages(node: fx.Node) -> OrderedSet[StorageKey]: + """ + Get all storages from a node's outputs. + + Uses pytree to handle arbitrary nested structures. + """ + val = node.meta.get("val") + if val is None: + return OrderedSet() + + storages: OrderedSet[StorageKey] = OrderedSet() + + def collect_storage(tensor: torch._subclasses.FakeTensor) -> None: + storages.add(StorageKey(tensor.untyped_storage(), tensor.device)) + + # Use tree_map_only to handle FakeTensors in nested structures + tree_map_only(torch._subclasses.FakeTensor, collect_storage, val) + + return storages + + def _get_input_storages(self, node: fx.Node) -> OrderedSet[StorageKey]: + """ + Get all storages from a node's inputs. + """ + input_storages: OrderedSet[StorageKey] = OrderedSet() + + for input_node in node.all_input_nodes: + input_storages.update(self.node_to_output_storages[input_node]) + + return input_storages + + def get_fresh_allocations(self, node: fx.Node) -> OrderedSet[StorageKey]: + """Get all fresh storage allocations by this node (not views/aliases).""" + return self.node_to_fresh_allocations[node] + + def get_storage_uses(self, node: fx.Node) -> OrderedSet[StorageKey]: + """Get all storages that this node uses as inputs.""" + return self.node_to_storage_uses[node] + + def get_storages_last_used( + self, + node: fx.Node, + ) -> OrderedSet[StorageKey]: + """ + Get storages whose last use is at this node. + """ + return self.node_to_storages_last_used[node] + + +def _size_of_default(num_bytes: int | torch.SymInt) -> int: + return optimization_hint(num_bytes) + + +def device_filter(device: torch.device) -> bool: + return device.type != "cpu" + + +def build_memory_profile( + graph: fx.Graph, + is_releasable: Callable[[fx.Node], bool], + size_of: Callable[[int | torch.SymInt], int] | None = None, +) -> list[int]: + """ + Function to estimate the memory profile of an input FX graph. + + Args: + - graph (fx.Graph): The input FX graph for which the memory profile + is to be estimated. + - is_releasable (Callable[[fx.Node], bool]): A function that + determines if a node's memory can be released (e.g. primal nodes + cannot be released). + - size_of (Callable[[int | torch.SymInt], int]): A function that converts + byte counts (possibly symbolic) to concrete integers. + + Returns: + - List[int]: A list representing the memory profile over the execution + of the graph, where each entry corresponds to the memory usage at + a particular point in the execution. + """ + + size_of = size_of or _size_of_default + nodes = list(graph.nodes) + alias_info = GraphAliasTracker(nodes) + + # Build memory profile + current_memory = 0 + + for node in itertools.chain( + graph.find_nodes(op="placeholder"), graph.find_nodes(op="get_attr") + ): + for storage_key in alias_info.get_fresh_allocations(node): + if device_filter(storage_key.device): + current_memory += size_of(storage_key.storage.nbytes()) + + memory_profile = [current_memory] + + for node in nodes: + if node.op in ("placeholder", "get_attr", "output"): + continue + + # Process allocations + for storage_key in alias_info.get_fresh_allocations(node): + if device_filter(storage_key.device): + current_memory += size_of(storage_key.storage.nbytes()) + + memory_profile.append(current_memory) + + # Process deallocations + # pyrefly: ignore [bad-assignment] + for storage_key in alias_info.get_storages_last_used(node): + allocator = alias_info.storage_to_allocator[storage_key] + if is_releasable(allocator): + if device_filter(storage_key.device): + current_memory -= size_of(storage_key.storage.nbytes()) + + memory_profile.append(current_memory) + + return memory_profile + + +def get_fwd_bwd_interactions( + fwd_graph: fx.Graph, + bwd_graph: fx.Graph, + size_of: Callable[[int | torch.SymInt], int] | None = None, +) -> tuple[int, OrderedSet[str]]: + """ + Analyze the interactions between the forward (fwd) and backward (bwd) graphs + to determine memory usage characteristics. + + Args: + - fwd_graph (fx.Graph): The forward graph representing the forward pass. + - bwd_graph (fx.Graph): The backward graph representing the backward pass. + - size_of (Callable[[int | torch.SymInt], int]): A function that converts + byte counts (possibly symbolic) to concrete integers. + + Returns: + - tuple[int, OrderedSet[str]]: A tuple containing: + 1. The baseline memory usage during the backward pass, accounting for + storages that persist from the forward pass (i.e., in fwd output but + not in bwd input). + 2. A set of node names whose storage cannot be released during the bwd pass. + These include nodes that use storage from primals or are in bwd input + but not in fwd output. + """ + + size_of = size_of or _size_of_default + + # Build alias info for forward graph + fwd_nodes = list(fwd_graph.nodes) + fwd_alias_info = GraphAliasTracker(fwd_nodes) + + # Identify storages allocated by primal placeholder nodes + primal_storages: OrderedSet[StorageKey] = OrderedSet() + for node in fwd_graph.find_nodes(op="placeholder"): + if node.name.startswith("primals"): + primal_storages.update(fwd_alias_info.get_fresh_allocations(node)) + + # Get storages in forward output + fwd_output_node = next(iter(reversed(fwd_graph.nodes)))[-1] + if fwd_output_node.op != "output": + raise AssertionError(f"expected output node, got op {fwd_output_node.op}") + fwd_output_storages = fwd_alias_info.get_storage_uses(fwd_output_node) + + # Node names that should not be deleted during memory profile estimation of bwd_graph + do_not_delete: OrderedSet[str] = OrderedSet() + + # Collect all storages in backward inputs and identify nodes to not delete + bwd_input_storages: OrderedSet[StorageKey] = OrderedSet() + for node in bwd_graph.find_nodes(op="placeholder"): + node_storages = GraphAliasTracker._get_output_storages(node) + bwd_input_storages.update(node_storages) + + # Check if this node uses primal storage + if node_storages & primal_storages: + do_not_delete.add(node.name) + + # Check if this node's storages are not in forward outputs + # (meaning it's an external input to backward pass) + if not (node_storages & fwd_output_storages): + do_not_delete.add(node.name) + + # Calculate baseline memory: storages in fwd output but not in bwd input + # These storages persist throughout the backward pass + baseline_storages = fwd_output_storages - bwd_input_storages + bwd_baseline_memory = 0 + for storage_key in baseline_storages: + if storage_key.device.type != "cpu": + bwd_baseline_memory += size_of(storage_key.storage.nbytes()) + + return bwd_baseline_memory, do_not_delete + + +def _is_releasable(n: fx.Node) -> bool: + # Storages of primals cannot be released during fwd or bwd pass. + return not n.name.startswith("primals") + + +def get_peak_memory( + fwd_graph: fx.Graph, + bwd_graph: fx.Graph, +) -> int: + fwd_peak_memory = max(build_memory_profile(fwd_graph, _is_releasable)) + + bwd_baseline_memory, bwd_do_not_delete = get_fwd_bwd_interactions( + fwd_graph, + bwd_graph, + ) + + def _is_bwd_releasable(n: fx.Node) -> bool: + # Storages of nodes in bwd_do_not_delete cannot be released + # during the bwd pass. + return _is_releasable(n) and n.name not in bwd_do_not_delete + + bwd_peak_memory = bwd_baseline_memory + max( + build_memory_profile(bwd_graph, _is_bwd_releasable) + ) + return max( + fwd_peak_memory, + bwd_peak_memory, + ) + + +class MemoryTracker: + """ + Tracks memory usage for alternative scheduling orders of an FX graph. + + This class enables tracking memory usage as nodes are scheduled in a different + order than the original graph. + """ + + def __init__( + self, + graph: fx.Graph, + is_releasable: Callable[[fx.Node], bool] | None = None, + device_filter: Callable[[torch.device], bool] | None = None, + ): + """ + Initialize memory tracker for alternative scheduling of the given graph. + + Args: + graph: FX graph to track memory for under alternative scheduling + is_releasable: do we consider this input to the graph to release memory + upon final use, or is allocated for the duration of the graph ? + by default, we assume all nodes but those that start with "primals" to be releasable + device_filter: Function to determine which devices to track (default: non-CPU) + """ + + self.graph = graph + self.nodes = list(graph.nodes) + self.device_filter = device_filter or (lambda device: device.type != "cpu") + self.scheduled: OrderedSet[fx.Node] = OrderedSet() + + # Memory tracking using GraphAliasTracker + self.alias_tracker = GraphAliasTracker(self.nodes) + self.current_live_storages: OrderedSet[StorageKey] = OrderedSet() + self.current_memory_bytes = 0 + self.is_releasable = _is_releasable if is_releasable is None else is_releasable + + # Initialize live storages with placeholders and get_attr nodes + for node in self.nodes: + if node.op in ("placeholder", "get_attr"): + fresh_allocations = self.alias_tracker.get_fresh_allocations(node) + for storage_key in fresh_allocations: + if self.device_filter(storage_key.device): + self.current_live_storages.add(storage_key) + self.current_memory_bytes += self._get_storage_size(storage_key) + + self.peak_memory = self.current_memory_bytes + + log.debug( + "Memory tracker initialized with initial memory: %d MB", + self.current_memory_bytes // (1024 * 1024), + ) + + def schedule_node(self, node: fx.Node) -> None: + """ + Schedule a node and update memory tracking for the new scheduling order. + + Args: + node: The node being scheduled (potentially out of original order) + """ + if node in self.scheduled: + raise AssertionError("should not schedule node twice") + self.scheduled.add(node) + self._update_memory_for_node(node) + + def get_current_memory_bytes(self) -> int: + """Get current live memory in bytes under the current scheduling.""" + return self.current_memory_bytes + + def _get_storage_size(self, storage_key: StorageKey) -> int: + """Get the size of a storage in bytes, handling symbolic shapes.""" + size_bytes = storage_key.storage.nbytes() + return optimization_hint(size_bytes) + + def _get_storages_freed_by_node(self, node: fx.Node) -> OrderedSet[StorageKey]: + """Get storages that would be freed if we schedule this node.""" + freed_storages: OrderedSet[StorageKey] = OrderedSet() + + input_storages = self.alias_tracker.get_storage_uses(node) + for storage_key in input_storages: + if not self.device_filter(storage_key.device): + continue + + # Invariant: if a node uses a storage, it must be live + if storage_key not in self.current_live_storages: + raise AssertionError("all input storages should be currently allocated") + + if not self.is_releasable( + self.alias_tracker.storage_to_allocator[storage_key] + ): + continue + + all_uses = self.alias_tracker.storage_to_uses[storage_key] + + # If no more unscheduled uses remain, the storage can be freed + if all(u in self.scheduled for u in all_uses): + freed_storages.add(storage_key) + + return freed_storages + + def _update_memory_for_node(self, node: fx.Node) -> None: + """Update memory tracking when a node is scheduled.""" + if node.op in ("placeholder", "get_attr", "output"): + return + + # Add fresh allocations + fresh_allocations = self.alias_tracker.get_fresh_allocations(node) + alloc_bytes = 0 + for storage_key in fresh_allocations: + if ( + self.device_filter(storage_key.device) + and storage_key not in self.current_live_storages + ): + size = self._get_storage_size(storage_key) + self.current_live_storages.add(storage_key) + self.current_memory_bytes += size + alloc_bytes += size + + self.peak_memory = max(self.current_memory_bytes, self.peak_memory) + + # Remove storages that are no longer used + storages_to_free = self._get_storages_freed_by_node(node) + freed_bytes = 0 + for storage_key in storages_to_free: + if storage_key in self.current_live_storages: + size = self._get_storage_size(storage_key) + self.current_live_storages.remove(storage_key) + self.current_memory_bytes -= size + freed_bytes += size + + log.debug( + "Scheduled %s: memory change %d allocs, %d frees, current memory: %d MB", + node.name, + len(fresh_allocations), + len(storages_to_free), + self.current_memory_bytes // (1024 * 1024), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/micro_pipeline_tp.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/micro_pipeline_tp.py new file mode 100644 index 0000000000000000000000000000000000000000..7f08579b1948aa63979bb71ad255efe08c2c0550 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/micro_pipeline_tp.py @@ -0,0 +1,1326 @@ +# mypy: allow-untyped-defs +import logging +import operator +from collections import defaultdict +from dataclasses import dataclass, field +from math import prod +from typing import Any, cast + +import torch +from torch.utils._ordered_set import OrderedSet + +from .. import config, inductor_prims +from ..pattern_matcher import ( + CallFunction, + Ignored, + KeywordArg, + ListOf, + Match, + MULTIPLE, + PatternExpr, + PatternMatcherPass, +) + + +log = logging.getLogger(__name__) +aten = torch.ops.aten +patterns = PatternMatcherPass() + + +def _is_last_dim(t: torch.Tensor, dim: int) -> bool: + return dim == t.ndim - 1 or dim == -1 + + +def _is_backward(graph: torch.fx.Graph) -> bool: + placeholders = [] + for node in graph.nodes: + if node.op != "placeholder": + break + placeholders.append(node) + return not all(node.name.startswith("primal") for node in placeholders) + + +def _compute_mm_arithmetic_intensity(M: int, N: int, K: int) -> float: + return M * N * K / (M * K + N * K + M * N) + + +def _filter_nodes_by_target(nodes: list[torch.fx.Node], target) -> list[torch.fx.Node]: + return [x for x in nodes if x.target == target] + + +def _find_ancestors(node: torch.fx.Node) -> OrderedSet[torch.fx.Node]: + ancestors = OrderedSet[torch.fx.Node]() + ancestors.add(node) + cur_nodes = [node] + while len(cur_nodes) > 0: + new_nodes = [] + for node in cur_nodes: + for inp in node.all_input_nodes: + if inp not in ancestors: + ancestors.add(inp) + new_nodes.append(inp) + cur_nodes = new_nodes + return OrderedSet(node for node in ancestors if node.op != "placeholder") + + +def _get_tensor(node: torch.fx.Node) -> torch.Tensor: + val = node.meta["val"] + if not isinstance(val, torch.Tensor): + raise AssertionError(f"expected node val to be a Tensor, got {type(val)}") + return val + + +@dataclass +class _AllGatherMatch: + match: Match | list[torch.fx.Node] + shard_node: torch.fx.Node + ag_node: torch.fx.Node + res_node: torch.fx.Node + gather_dim: int + group_name: "torch.distributed.distributed_c10d.GroupName" + + def replace_with(self, new_node: torch.fx.Node) -> None: + self.res_node.replace_all_uses_with(new_node) + + def erase(self) -> None: + nodes = self.match.nodes if isinstance(self.match, Match) else self.match + for node in reversed(nodes): + if len(node.users) == 0: + node.graph.erase_node(node) + + +def find_all_gather_patterns(graph: torch.fx.Graph): + """Find all-gather outputs that can fuse with downstream matmul users. + + This recognizes both the direct all-gather form and slice/cat reassembly + forms that preserve the same tensor-parallel communication contract. + """ + c10d = torch.ops._c10d_functional + split_targets = [aten.split.Tensor, aten.split.sizes, aten.split_with_sizes.default] + + def make_zero_dim_all_gather_pattern(shard): + return CallFunction( + c10d.wait_tensor.default, + CallFunction( + c10d.all_gather_into_tensor.default, + shard, + Ignored(), + KeywordArg("group_name"), + ), + ) + + # Matches funcol.all_gather_single with gather_dim == 0 + zero_dim_all_gather_pattern = make_zero_dim_all_gather_pattern(KeywordArg("shard")) + + def make_all_gather_split_pattern(shard): + return CallFunction( + operator.getitem, + CallFunction( + split_targets, + make_zero_dim_all_gather_pattern(shard), + Ignored(), + _users=MULTIPLE, + ), + Ignored(), + ) + + def make_cat_pattern(splits): + return CallFunction( + aten.cat.default, + ListOf(splits), + KeywordArg("gather_dim"), + ) + + # Matches funcol.all_gather_single with gather_dim > 0 + non_zero_dim_all_gather_pattern = make_cat_pattern( + make_all_gather_split_pattern(KeywordArg("shard")), + ) + + # Match a zero-dim all-gather in which the data is transferred as uint8 and + # viewed back as the original dtype. + zero_dim_type_erased_all_gather_pattern = CallFunction( + aten.view.dtype, + make_zero_dim_all_gather_pattern( + KeywordArg("shard"), + ), + Ignored(), + ) + + # Match a non-zero dim all-gather in which the data is transferred as uint8 + # and viewed back as the original dtype. + non_zero_dim_type_erased_all_gather_pattern = CallFunction( + aten.view.dtype, + make_cat_pattern( + CallFunction( + aten.view.dtype, + make_all_gather_split_pattern( + KeywordArg("shard"), + ), + Ignored(), + ), + ), + Ignored(), + ) + + # If two patterns with the same res_node_target have the same suffix, the + # longer pattern should appear first in the list. + # e.g. supposed we have (1) A -> B -> C -> D and (2) B -> C -> D, (1) + # should appear before (2) in the list. + res_node_target_to_patterns = { + aten.cat.default: [ + (non_zero_dim_all_gather_pattern, 0), + ], + aten.view.dtype: [ + (non_zero_dim_type_erased_all_gather_pattern, 0), + (zero_dim_type_erased_all_gather_pattern, 0), + ], + c10d.wait_tensor.default: [ + (zero_dim_all_gather_pattern, 0), + ], + } + + # Match in reverse to ensure longer patterns is prioritized + all_gathers = [] + visited_ag_nodes = OrderedSet[torch.fx.Node]() + + def _match_slice_cat_all_gather( + node: torch.fx.Node, + ) -> _AllGatherMatch | None: + res_node = node + trim_node = None + if node.target is aten.slice.Tensor: + if len(node.args) < 4 or not isinstance(node.args[0], torch.fx.Node): + return None + trim_node = node + node = node.args[0] + + if node.target is not aten.cat.default: + return None + cat_inputs = node.args[0] + if not isinstance(cat_inputs, (list, tuple)) or len(cat_inputs) == 0: + return None + gather_dim = node.args[1] if len(node.args) > 1 else node.kwargs.get("dim", 0) + if not isinstance(gather_dim, int): + return None + if trim_node is not None and ( + len(trim_node.args) < 4 + or trim_node.args[1] != gather_dim + or trim_node.args[2] != 0 + ): + return None + + slice_nodes: list[torch.fx.Node] = [] + wait_node = None + for inp in cat_inputs: + if not ( + isinstance(inp, torch.fx.Node) + and inp.target is aten.slice.Tensor + and len(inp.args) >= 2 + and inp.args[1] == 0 + ): + return None + cur_wait = inp.args[0] + if not ( + isinstance(cur_wait, torch.fx.Node) + and cur_wait.target is c10d.wait_tensor.default + ): + return None + if wait_node is None: + wait_node = cur_wait + elif wait_node is not cur_wait: + return None + slice_nodes.append(inp) + + if wait_node is None: + return None + ag_node = wait_node.args[0] + if not ( + isinstance(ag_node, torch.fx.Node) + and ag_node.target is c10d.all_gather_into_tensor.default + ): + return None + group_name = ag_node.kwargs.get("group_name") + if group_name is None and len(ag_node.args) >= 3: + group_name = ag_node.args[2] + if group_name is None: + return None + + return _AllGatherMatch( + match=[ + ag_node, + wait_node, + *slice_nodes, + node, + *((trim_node,) if trim_node is not None else ()), + ], + shard_node=cast("torch.fx.Node", ag_node.args[0]), + ag_node=ag_node, + res_node=res_node, + gather_dim=gather_dim, + group_name=cast("torch.distributed.distributed_c10d.GroupName", group_name), + ) + + for node in reversed(graph.nodes): + if ag_match := _match_slice_cat_all_gather(node): + if ag_match.ag_node not in visited_ag_nodes: + visited_ag_nodes.add(ag_match.ag_node) + all_gathers.append(ag_match) + continue + for target, patterns in res_node_target_to_patterns.items(): + if node.target != target: + continue + for pattern, ag_node_idx in patterns: + match = pattern.match(node) + if not match: + continue + + if not isinstance(match, Match): + raise AssertionError(f"expected a Match, got {type(match)}") + ag_node = match.nodes[ag_node_idx] + if ag_node.target != c10d.all_gather_into_tensor.default: + raise AssertionError( + "expected ag_node target to be " + f"all_gather_into_tensor, got {ag_node.target}" + ) + + if ag_node in visited_ag_nodes: + continue + visited_ag_nodes.add(ag_node) + + ag_match = _AllGatherMatch( + match=match, + shard_node=match.kwargs["shard"], + ag_node=ag_node, + res_node=node, + gather_dim=match.kwargs.get("gather_dim", 0), + group_name=match.kwargs["group_name"], + ) + all_gathers.append(ag_match) + + return list(reversed(all_gathers)) + + +@dataclass +class _ReduceScatterMatch: + match: Match | list[torch.fx.Node] + input_node: torch.fx.Node + reduce_scatter_node: torch.fx.Node + wait_tensor_node: torch.fx.Node + reduce_op: str + scatter_dim: int + group_name: "torch.distributed.distributed_c10d.GroupName" + + def replace_with(self, new_node: torch.fx.Node) -> None: + # Replace all uses of the result node (wait_tensor) with the fused node. + self.wait_tensor_node.replace_all_uses_with(new_node) + + # If the reduce-scatter result is saved for backward, save the fused node for backward instead. + self._update_save_for_backward(new_node) + + def _update_save_for_backward(self, new_node: torch.fx.Node) -> None: + """ + If the output node is a user of the reduce_scatter node (indicating the reduce_scatter + result is saved for backward), this method will update the output node to use the fused node instead. + """ + output_node = None + for user in self.reduce_scatter_node.users: + if user.target == "output": + output_node = user + break + if output_node is not None: + output_node.replace_input_with(self.reduce_scatter_node, new_node) + + # Assert that now the reduce scatter node has only one user (the wait_tensor) and it's not + # saved for backward anymore. + if len(self.reduce_scatter_node.users) != 1: + raise AssertionError( + "Reduce scatter node has multiple users, this is not expected" + ) + + def erase(self) -> None: + nodes = self.match.nodes if isinstance(self.match, Match) else self.match + for node in reversed(nodes): + if len(node.users) == 0: + node.graph.erase_node(node) + + +def find_reduce_scatter_patterns(graph: torch.fx.Graph): + """Find matmul outputs that can fuse with downstream reduce-scatter users. + + This recognizes both the direct reduce-scatter form and slice/cat forms + that reassemble the same tensor-parallel communication payload. + """ + c10d = torch.ops._c10d_functional + split_targets = [aten.split.Tensor, aten.split.sizes, aten.split_with_sizes.default] + + def reduce_scatter_template(inp: PatternExpr, users: int): + return CallFunction( + c10d.wait_tensor.default, + CallFunction( + c10d.reduce_scatter_tensor.default, + inp, + KeywordArg("reduce_op"), + Ignored(), + KeywordArg("group_name"), + _users=users, + ), + ) + + # Matches funcol.reduce_scatter_single with scatter_dim == 0 + zero_dim_reduce_scatter_pattern_single_user = reduce_scatter_template( + KeywordArg("input"), users=1 + ) + + # Two users will occur when the reduce-scatter result is saved for backward + zero_dim_reduce_scatter_pattern_multi_user = reduce_scatter_template( + KeywordArg("input"), users=2 + ) + + # Matches funcol.reduce_scatter_single with scatter_dim > 0 + non_zero_dim_reduce_scatter_pattern_single_user = reduce_scatter_template( + CallFunction( + aten.cat.default, + ListOf( + CallFunction( + operator.getitem, + CallFunction( + split_targets, + KeywordArg("input"), + Ignored(), + KeywordArg("scatter_dim"), + _users=MULTIPLE, + ), + Ignored(), + ) + ), + ), + users=1, + ) + + # Two users will occur when the reduce-scatter result is saved for backward + non_zero_dim_reduce_scatter_pattern_multi_user = reduce_scatter_template( + CallFunction( + aten.cat.default, + ListOf( + CallFunction( + operator.getitem, + CallFunction( + split_targets, + KeywordArg("input"), + Ignored(), + KeywordArg("scatter_dim"), + _users=MULTIPLE, + ), + Ignored(), + ) + ), + ), + users=2, + ) + + reduce_scatters = [] + + def _match_slice_cat_reduce_scatter( + wait_node: torch.fx.Node, + ) -> _ReduceScatterMatch | None: + if wait_node.target is not c10d.wait_tensor.default: + return None + reduce_scatter_node = wait_node.args[0] + if not ( + isinstance(reduce_scatter_node, torch.fx.Node) + and reduce_scatter_node.target is c10d.reduce_scatter_tensor.default + ): + return None + cat_node = reduce_scatter_node.args[0] + if not ( + isinstance(cat_node, torch.fx.Node) and cat_node.target is aten.cat.default + ): + return None + cat_dim = ( + cat_node.args[1] + if len(cat_node.args) > 1 + else cat_node.kwargs.get("dim", 0) + ) + if cat_dim != 0: + return None + cat_inputs = cat_node.args[0] + if not isinstance(cat_inputs, (list, tuple)) or len(cat_inputs) == 0: + return None + + slice_nodes: list[torch.fx.Node] = [] + input_node = None + scatter_dim = None + for inp in cat_inputs: + if not ( + isinstance(inp, torch.fx.Node) + and inp.target is aten.slice.Tensor + and len(inp.args) >= 2 + ): + return None + cur_input = inp.args[0] + cur_dim = inp.args[1] + if not isinstance(cur_input, torch.fx.Node) or not isinstance(cur_dim, int): + return None + if input_node is None: + input_node = cur_input + scatter_dim = cur_dim + elif input_node is not cur_input or scatter_dim != cur_dim: + return None + slice_nodes.append(inp) + + if input_node is None or scatter_dim is None: + return None + group_name = reduce_scatter_node.kwargs.get("group_name") + if group_name is None and len(reduce_scatter_node.args) >= 4: + group_name = reduce_scatter_node.args[3] + reduce_op = reduce_scatter_node.kwargs.get("reduce_op") + if reduce_op is None and len(reduce_scatter_node.args) >= 2: + reduce_op = reduce_scatter_node.args[1] + if group_name is None or reduce_op is None: + return None + + return _ReduceScatterMatch( + match=[*slice_nodes, cat_node, reduce_scatter_node, wait_node], + input_node=input_node, + reduce_scatter_node=reduce_scatter_node, + wait_tensor_node=wait_node, + reduce_op=cast(str, reduce_op), + scatter_dim=scatter_dim, + group_name=cast("torch.distributed.distributed_c10d.GroupName", group_name), + ) + + for node in reversed(graph.nodes): + if node.target == c10d.wait_tensor.default: + if rs_match := _match_slice_cat_reduce_scatter(node): + reduce_scatters.append(rs_match) + elif match := non_zero_dim_reduce_scatter_pattern_single_user.match(node): + if not isinstance(match, Match): + raise AssertionError(f"expected a Match, got {type(match)}") + reduce_scatters.append( + _ReduceScatterMatch( + match=match, + input_node=match.kwargs["input"], + reduce_scatter_node=match.nodes[-2], + wait_tensor_node=node, + reduce_op=match.kwargs["reduce_op"], + scatter_dim=match.kwargs["scatter_dim"], + group_name=match.kwargs["group_name"], + ) + ) + elif match := zero_dim_reduce_scatter_pattern_single_user.match(node): + if not isinstance(match, Match): + raise AssertionError(f"expected a Match, got {type(match)}") + reduce_scatters.append( + _ReduceScatterMatch( + match=match, + input_node=match.kwargs["input"], + reduce_scatter_node=match.nodes[0], + wait_tensor_node=node, + reduce_op=match.kwargs["reduce_op"], + scatter_dim=0, + group_name=match.kwargs["group_name"], + ) + ) + elif match := non_zero_dim_reduce_scatter_pattern_multi_user.match(node): + if not isinstance(match, Match): + raise AssertionError(f"expected a Match, got {type(match)}") + reduce_scatters.append( + _ReduceScatterMatch( + match=match, + input_node=match.kwargs["input"], + reduce_scatter_node=match.nodes[-2], + wait_tensor_node=node, + reduce_op=match.kwargs["reduce_op"], + scatter_dim=match.kwargs["scatter_dim"], + group_name=match.kwargs["group_name"], + ) + ) + elif match := zero_dim_reduce_scatter_pattern_multi_user.match(node): + if not isinstance(match, Match): + raise AssertionError(f"expected a Match, got {type(match)}") + reduce_scatters.append( + _ReduceScatterMatch( + match=match, + input_node=match.kwargs["input"], + reduce_scatter_node=match.nodes[0], + wait_tensor_node=node, + reduce_op=match.kwargs["reduce_op"], + scatter_dim=0, + group_name=match.kwargs["group_name"], + ) + ) + return list(reversed(reduce_scatters)) + + +@dataclass +class _Matmul: + nodes: list[torch.fx.Node] + arg_ancestor_nodes: OrderedSet[torch.fx.Node] = field(init=False) + A_node: torch.fx.Node + B_node: torch.fx.Node + pre_mm_reshape: torch.fx.Node | None + post_mm_reshape: torch.fx.Node | None + + def __post_init__(self): + if len(self.nodes) not in (1, 3): + raise AssertionError(f"expected 1 or 3 nodes, got {len(self.nodes)}") + if len(self.nodes) == 1: + if self.nodes[0].target not in (aten.mm.default, aten._scaled_mm.default): + raise AssertionError( + f"expected mm or _scaled_mm, got {self.nodes[0].target}" + ) + else: + if self.nodes[0].target is not aten.reshape.default: + raise AssertionError(f"expected reshape, got {self.nodes[0].target}") + if self.nodes[1].target not in (aten.mm.default, aten._scaled_mm.default): + raise AssertionError( + f"expected mm or _scaled_mm, got {self.nodes[1].target}" + ) + if self.nodes[2].target is not aten.reshape.default: + raise AssertionError(f"expected reshape, got {self.nodes[2].target}") + self.arg_ancestor_nodes = _find_ancestors(self.B_node) + + def replace_with(self, new_node: torch.fx.Node) -> None: + """ + Replace the matmul with the new node. + """ + graph = new_node.graph + + # For 2D-matmuls, we simply replace the mm node with `new_node`. + if len(self.nodes) == 1: + mm_node = self.nodes[0] + if mm_node.target not in (aten.mm.default, aten._scaled_mm.default): + raise AssertionError(f"expected mm or _scaled_mm, got {mm_node.target}") + mm_node.replace_all_uses_with(new_node) + return + + # An ND-matmul is reshape -> mm -> reshape sequence. We first replace + # the second reshape node with `new_node`. Then, we ensure that the + # original mm node in the sequence ends up with zero users by replacing + # it with a reverse reshape of `new_node`. + graph = new_node.graph + if len(self.nodes) != 3: + raise AssertionError(f"expected 3 nodes, got {len(self.nodes)}") + mm_node = self.nodes[1] + output_reshape_node = self.nodes[2] + + if mm_node.target not in (aten.mm.default, aten._scaled_mm.default): + raise AssertionError(f"expected mm or _scaled_mm, got {mm_node.target}") + if output_reshape_node.target is not aten.reshape.default: + raise AssertionError(f"expected reshape, got {output_reshape_node.target}") + + output_reshape_node.replace_all_uses_with(new_node) + if len(mm_node.users) > 1: + with graph.inserting_after(new_node): + new_mm_node = graph.call_function( + aten.reshape.default, + args=(new_node, list(_get_tensor(mm_node).shape)), + ) + mm_node.replace_all_uses_with(new_mm_node) + + def erase(self) -> None: + for node in reversed(self.nodes): + if len(node.users) == 0: + node.graph.erase_node(node) + + @classmethod + def from_match(cls, match: list[torch.fx.Node]) -> "_Matmul": + if len(match) not in (1, 3): + raise AssertionError(f"expected 1 or 3 nodes, got {len(match)}") + if match[0].target not in ( + aten.mm.default, + aten.reshape.default, + ): + raise AssertionError(f"expected mm or reshape, got {match[0].target}") + mm_node = match[0] if len(match) == 1 else match[1] + return _Matmul( + nodes=match, + A_node=cast("torch.fx.Node", match[0].args[0]), + B_node=cast("torch.fx.Node", mm_node.args[1]), + # _Matmul handles reshapes via custom graph manipulation logic, see `replace_with()` method. + # TODO: explore unifying the _Matmul and _ScaledMatmul approaches to handling reshapes. + pre_mm_reshape=None, + post_mm_reshape=None, + ) + + +@dataclass +class _ScaledMatmul(_Matmul): + A_scale_node: torch.fx.Node + B_scale_node: torch.fx.Node + bias_node: torch.fx.Node | None + result_scale_node: torch.fx.Node | None + out_dtype: torch.dtype | None + use_fast_accum: bool + pre_mm_reshape: torch.fx.Node | None + post_mm_reshape: torch.fx.Node | None + + def __post_init__(self): + super().__post_init__() + self.arg_ancestor_nodes |= _find_ancestors(self.A_scale_node) + self.arg_ancestor_nodes |= _find_ancestors(self.B_scale_node) + + @classmethod + def from_match(cls, match: list[torch.fx.Node]) -> "_ScaledMatmul": + if len(match) not in (1, 3): + raise AssertionError(f"expected 1 or 3 nodes, got {len(match)}") + if match[0].target not in ( + aten._scaled_mm.default, + aten.reshape.default, + ): + raise AssertionError( + f"expected _scaled_mm or reshape, got {match[0].target}" + ) + + def get_arg(node: torch.fx.Node, idx: int, default: Any) -> Any: + if idx >= len(node.args): + return default + return node.args[idx] + + # Use mm_node with 2D args for both A and B, even if this is a "reshape -> mm -> reshape" pattern. + # We will store the reshapes in pre_mm_reshape and post_mm_reshape, to be referenced later to + # produce the correct output shapes, reduce-scatter along the correct dimensions, etc. + is_reshape_mm_reshape_pattern = match[0].target is aten.reshape.default + mm_node = match[1] if is_reshape_mm_reshape_pattern else match[0] + pre_mm_reshape = match[0] if is_reshape_mm_reshape_pattern else None + post_mm_reshape = match[-1] if is_reshape_mm_reshape_pattern else None + A_node = cast("torch.fx.Node", mm_node.args[0]) + B_node = cast("torch.fx.Node", mm_node.args[1]) + A_scale_node = cast("torch.fx.Node", mm_node.args[2]) + B_scale_node = cast("torch.fx.Node", mm_node.args[3]) + + return _ScaledMatmul( + nodes=match, + A_node=A_node, + B_node=B_node, + A_scale_node=A_scale_node, + B_scale_node=B_scale_node, + bias_node=get_arg(mm_node, 4, None), + result_scale_node=get_arg(mm_node, 5, None), + out_dtype=get_arg(mm_node, 6, None), + use_fast_accum=get_arg(mm_node, 7, False), + pre_mm_reshape=pre_mm_reshape, + post_mm_reshape=post_mm_reshape, + ) + + +def _find_reshape_mm_reshape(node: torch.fx.Node) -> list[_Matmul]: + if node.target != aten.reshape.default: + return [] + + matches = [] + for mm_node in node.users: + if mm_node.target not in (aten.mm.default, aten._scaled_mm.default): + continue + for reshape_node in mm_node.users: + if reshape_node.target != aten.reshape.default: + continue + + # Since the reshape -> mm -> reshape pattern would be subsumed into + # the fused op, we only match the patterns where the shape of the + # second reshape is matches the mm result produced by the fused op. + matmul_input_node = cast("torch.fx.Node", node.args[0]) + B_node = cast("torch.fx.Node", mm_node.args[1]) + matmul_out_shape = torch.Size( + [ + *_get_tensor(matmul_input_node).shape[:-1], + _get_tensor(B_node).shape[-1], + ] + ) + if _get_tensor(reshape_node).shape != matmul_out_shape: + continue + matches.append([node, mm_node, reshape_node]) + # If for some rare reason mm_node is being reshaped by two + # different reshape nodes, we only include mm_node once in the + # parsing result. + break + + matmuls = [] + for match in matches: + mm_node = match[1] + if mm_node.target is aten.mm.default: + matmul = _Matmul.from_match(match) + matmuls.append(matmul) + elif mm_node.target is aten._scaled_mm.default: + matmul = _ScaledMatmul.from_match(match) + matmuls.append(matmul) + else: + raise AssertionError( + "Expect the node's target to be either aten.mm.default or " + f"aten._scaled_mm.default. Got {mm_node.target}." + ) + return matmuls + + +def _find_consumer_matmuls(node: torch.fx.Node) -> list[_Matmul]: + """ + Find the matmuls that use `node` as the lhs argument. + """ + matmuls = [] + for user in node.users: + # ND matmuls + if user.target is aten.reshape.default: + matmuls.extend(_find_reshape_mm_reshape(user)) + # 2D matmuls + elif user.target is aten.mm.default: + matmul = _Matmul.from_match(match=[user]) + matmuls.append(matmul) + elif user.target is aten._scaled_mm.default: + matmul = _ScaledMatmul.from_match([user]) + matmuls.append(matmul) + return matmuls + + +def _insert_fused_all_gather_matmul( + graph: torch.fx.Graph, + matmuls: list[_Matmul], + shard_node: torch.fx.Node, + gather_dim: int, + group_name: "torch.distributed.distributed_c10d.GroupName", +) -> torch.fx.Node: + mm_types = OrderedSet(map(type, matmuls)) + if len(mm_types) != 1: + raise AssertionError(f"expected exactly one matmul type, got {len(mm_types)}") + mm_type = next(iter(mm_types)) + if mm_type == _Matmul: + B_nodes = [matmul.B_node for matmul in matmuls] + return graph.call_function( + torch.ops.symm_mem.fused_all_gather_matmul.default, + args=(shard_node, B_nodes, gather_dim, group_name), + kwargs={"return_A": True}, + ) + elif mm_type == _ScaledMatmul: + scaled_matmuls = cast("list[_ScaledMatmul]", matmuls) + return graph.call_function( + torch.ops.symm_mem.fused_all_gather_scaled_matmul.default, + args=( + shard_node, + [matmul.B_node for matmul in scaled_matmuls], + scaled_matmuls[0].A_scale_node, + [matmul.B_scale_node for matmul in scaled_matmuls], + gather_dim, + group_name, + [matmul.bias_node for matmul in scaled_matmuls], + [matmul.result_scale_node for matmul in scaled_matmuls], + [matmul.out_dtype for matmul in scaled_matmuls], + [matmul.use_fast_accum for matmul in scaled_matmuls], + ), + ) + else: + raise AssertionError(f"Unexpected matmul match type: {mm_type}") + + +def fuse_all_gather_matmul(all_gather: _AllGatherMatch) -> None: + """ + Fused the pattern + + A = all_gather_single(A_shard, gather_dim, group_name) + C_0 = torch.matmul(A, B_0) + C_1 = torch.matmul(A, B_1) + C_2 = torch.matmul(A, B_2) + ... + + into + + A, Cs = torch.ops.symm_mem.fused_all_gather_matmul( + A_shard, [B_0, B_1, B_2, ...], gather_dim, group_name, + ) + """ + if not ( + torch.distributed.is_available() + and ( + torch.distributed.is_nccl_available() + or torch.distributed.is_xccl_available() + ) + ): + return + + from torch.distributed._symmetric_memory import ( + is_symm_mem_enabled_for_group, + restride_A_shard_for_fused_all_gather_matmul, + ) + + shard_node, ag_node, ag_res_node, gather_dim, group_name = ( + all_gather.shard_node, + all_gather.ag_node, + all_gather.res_node, + all_gather.gather_dim, + all_gather.group_name, + ) + + if not is_symm_mem_enabled_for_group(group_name): + return + + filter_matmul = None + if _is_last_dim(_get_tensor(shard_node), gather_dim): + # Decomposed mms should not be too small + if _get_tensor(shard_node).shape[-1] < 1024: + return + + # scaled_mm is not supported yet for last dim + def _filter_out_scaled_matmul(matmul: _Matmul): + return not isinstance(matmul, _ScaledMatmul) + + filter_matmul = _filter_out_scaled_matmul + + # Find consumer matmuls + matmuls = _find_consumer_matmuls(ag_res_node) + + # The matmuls are only fusible if non-A args don't depend on the all-gather + # result node + matmuls = [ + matmul + for matmul in matmuls + if all_gather.res_node not in matmul.arg_ancestor_nodes + ] + + if len(matmuls) == 0 or len(OrderedSet(map(type, matmuls))) != 1: + return + + if _is_last_dim(_get_tensor(shard_node), gather_dim) and len( + all_gather.res_node.users + ) > len(matmuls): + # The result of ag-split-cat is used not only in matmuls. + # Then it has to be materialized, which can have overhead. + return + + if filter_matmul and not filter_matmul(matmuls[0]): + return + + # Fuse the all_gather_single with the eligible matmuls + graph = ag_node.graph + with graph.inserting_before(ag_node): + if not _is_last_dim(_get_tensor(shard_node), gather_dim): + if "val" in shard_node.meta: + restrided = restride_A_shard_for_fused_all_gather_matmul( + _get_tensor(shard_node), + gather_dim, + ) + shard_node = graph.call_function( + inductor_prims.force_stride_order, + args=(shard_node, restrided.stride()), + ) + + fused_node = _insert_fused_all_gather_matmul( + graph, matmuls, shard_node, gather_dim, group_name + ) + new_ag_node = graph.call_function( + operator.getitem, + args=(fused_node, 0), + ) + new_out_nodes = graph.call_function( + operator.getitem, + args=(fused_node, 1), + ) + for idx, matmul in enumerate(matmuls): + new_out_node = graph.call_function( + operator.getitem, + args=(new_out_nodes, idx), + ) + matmul.replace_with(new_out_node) + matmul.erase() + all_gather.replace_with(new_ag_node) + all_gather.erase() + + # If the new_ag_node has no users, we tell the fused op to not return + # it. This creates more optimization opportunities. + if len(new_ag_node.users) == 0: + graph.erase_node(new_ag_node) + kwargs = dict(fused_node.kwargs) + if "return_A" in kwargs: + kwargs["return_A"] = False + fused_node.kwargs = kwargs + + # Raise ancestors of non-A args that are topologically ordered between + # ag_res_node and the matmul above fused_node. + order = {node: idx for idx, node in enumerate(graph.nodes)} + nodes_to_raise = sorted( + OrderedSet(x for matmul in matmuls for x in matmul.arg_ancestor_nodes), + key=lambda x: order[x], + ) + for node in nodes_to_raise: + if order[node] > order[fused_node]: + fused_node.prepend(node) + + +def _scatter_dim_after_reshape( + reshape_node: torch.fx.Node, orig_scatter_dim: int +) -> int: + """ + Given a reshape node and the original scatter dim for the target tensor, + returns the new scatter dim for the reshaped tensor. + """ + # if there was no pre-mm reshape, scatter dim will not change. + if not reshape_node: + return orig_scatter_dim + + reshape_op_output_tensor = _get_tensor(reshape_node) + if reshape_op_output_tensor.ndim != 2: + raise AssertionError("reshape must produce 2D tensor for scaled_mm") + + if len(reshape_node.args) < 1: + raise AssertionError("reshape node must have at least 1 arg") + input_tensor_node = cast(torch.fx.Node, reshape_node.args[0]) + reshape_op_input_tensor = _get_tensor(input_tensor_node) + if reshape_op_input_tensor.ndim <= reshape_op_output_tensor.ndim: + raise AssertionError("reshape must be from 3D+ to 2D") + + # Note: for a N-D tensor to be reshaped into 2D, either the leading dims or ending dims must + # be collapsed to a single dim. First determine which of these happened. + input_shape = reshape_op_input_tensor.shape + output_shape = reshape_op_output_tensor.shape + leading_dims_collapsed = output_shape[0] == prod(input_shape[:-1]) + + # Case 1: scatter dim 0 always maps to 0 after any reshape from 3D+ to 2D, regardless if + # leading dims or ending dims were collapsed. + if orig_scatter_dim == 0: + return 0 + + # Case 2: scatter dim "ndim-1" always maps to 1 after any reshape from 3D+ to 2D, regardless if + # leading dims or ending dims were collapsed. + if orig_scatter_dim == reshape_op_input_tensor.ndim - 1: + return 1 + + # Case 3: scatter dim was one of the middle dims (between 0 and ndim-1). + # if the leading dims were collapsed, the new scatter dim will be 0. + # if the ending dims were collapsed, the new scatter dim will be 1. + return 0 if leading_dims_collapsed else 1 + + +def _find_producer_matmul(node: torch.fx.Node) -> _Matmul | None: + """ + Returns producer matmul node if found, otherwise returns None. + """ + if node.target is aten.mm.default: + return _Matmul.from_match(match=[node]) + elif node.target is aten._scaled_mm.default: + return _ScaledMatmul.from_match(match=[node]) + elif node.target is aten.reshape.default: + reshape_node_1 = node + + mm_node = reshape_node_1.args[0] + if not isinstance(mm_node, torch.fx.Node): + raise AssertionError(f"expected an fx Node, got {type(mm_node)}") + if mm_node.target not in (aten.mm.default, aten._scaled_mm.default): + return None + + reshape_node_0 = mm_node.args[0] + if not isinstance(reshape_node_0, torch.fx.Node): + raise AssertionError(f"expected an fx Node, got {type(reshape_node_0)}") + if reshape_node_0.target != aten.reshape.default: + return None + + if mm_node.target is aten.mm.default: + return _Matmul.from_match(match=[reshape_node_0, mm_node, reshape_node_1]) + elif mm_node.target is aten._scaled_mm.default: + return _ScaledMatmul.from_match( + match=[reshape_node_0, mm_node, reshape_node_1] + ) + return None + + +def _insert_fused_matmul_reduce_scatter( + graph: torch.fx.Graph, + matmul: _Matmul, + reduce_op: str, + orig_scatter_dim: int, + group_name: "torch.distributed.distributed_c10d.GroupName", + scatter_dim_after_reshape: int, # only used for reshape -> scaled_mm -> reshape pattern + output_shape: list[int], # only used for reshape -> scaled_mm -> reshape pattern +) -> torch.fx.Node: + if type(matmul) is _Matmul: + return graph.call_function( + torch.ops.symm_mem.fused_matmul_reduce_scatter.default, + args=( + matmul.A_node, + matmul.B_node, + reduce_op, + orig_scatter_dim, + group_name, + ), + ) + elif type(matmul) is _ScaledMatmul: + return graph.call_function( + torch.ops.symm_mem.fused_scaled_matmul_reduce_scatter.default, + args=( + matmul.A_node, + matmul.B_node, + matmul.A_scale_node, + matmul.B_scale_node, + reduce_op, + orig_scatter_dim, + scatter_dim_after_reshape, + group_name, + output_shape, + matmul.bias_node, + matmul.result_scale_node, + matmul.out_dtype, + matmul.use_fast_accum, + ), + ) + else: + raise AssertionError(f"Unexpected matmul match type: {type(matmul)}") + + +def fuse_matmul_reduce_scatter(reduce_scatter: _ReduceScatterMatch) -> None: + """ + Fused the pattern + + reduce_scatter_single(A @ B, scatter_dim, group_name) + + into + + torch.ops.symm_mem.fused_matmul_reduce_scatter( + A, B, scatter_dim, group_name, + ) + + Returns boolean indicating if fusion was successful or not. + """ + if not ( + torch.distributed.is_available() + and ( + torch.distributed.is_nccl_available() + or torch.distributed.is_xccl_available() + ) + ): + return + + from torch.distributed._symmetric_memory import ( + is_symm_mem_enabled_for_group, + restride_A_for_fused_matmul_reduce_scatter, + ) + + ( + input_node, + _reduce_scatter_node, + rs_wait_tensor_node, + reduce_op, + orig_scatter_dim, + group_name, + ) = ( + reduce_scatter.input_node, + reduce_scatter.reduce_scatter_node, + reduce_scatter.wait_tensor_node, + reduce_scatter.reduce_op, + reduce_scatter.scatter_dim, + reduce_scatter.group_name, + ) + + if not is_symm_mem_enabled_for_group(group_name): + return + + filter_matmul = None + if _is_last_dim(_get_tensor(input_node), orig_scatter_dim): + # scaled_mm is not supported yet for last dim mm+rs + def _filter_out_scaled_matmul(matmul: _Matmul): + return not isinstance(matmul, _ScaledMatmul) + + filter_matmul = _filter_out_scaled_matmul + + matmul = _find_producer_matmul(input_node) + if matmul is None: + log.debug( + "no producer matmul found for reduce scatter, skipping fuse_matmul_reduce_scatter fusion" + ) + return + + # Currently fused_matmul_reduce_scatter doesn't return the matmul result, + # so we can't apply the fusion if the matmul result is used by multiple + # users. This is not a fundamental limitation of the fused op and can be + # addressed if needed. + match_nodes = ( + reduce_scatter.match.nodes + if isinstance(reduce_scatter.match, Match) + else reduce_scatter.match + ) + if len(input_node.users) != 1 and not all( + user in match_nodes for user in input_node.users + ): + log.warning( + "matmul result has more than one user, skipping fused_matmul_reduce_scatter fusion." + ) + return + + if filter_matmul and not filter_matmul(matmul): + return + + if rs_wait_tensor_node in matmul.arg_ancestor_nodes: + log.warning( + "reduce-scatter result node is an ancestor of matmul, skipping fuse_matmul_reduce_scatter fusion" + ) + return + + # We need to track 3 values for the fused scaled mm reduce scatter implementation: + # 1. The scatter dim before the reshape, which was assigned using the original (a,b,c) @ (c,d) = (a,b,d) dims. + # 2. The scatter dim after the reshape, to use when we are doing the 2D (a*b,c) @ (c,d) = (a,b,d) scaled mm op. + # 3. Store expected potentially 3D+ mm output shape, so we can reshape the 2D mm output to the intended + # 3D+ shape before applying reduce-scatter, and to prevent shape errors with subsequent ops. + + # If 'A' was reshaped from 3D+ -> 2D for the mm, we need to determine the new scattter dim after the reshape + # for the fused matmul reduce scatter implementation to use. + if matmul.pre_mm_reshape: + scatter_dim_after_maybe_reshape = _scatter_dim_after_reshape( + matmul.pre_mm_reshape, orig_scatter_dim + ) + else: + scatter_dim_after_maybe_reshape = orig_scatter_dim + + # If the 2D mm output was reshaped from 2D -> 3D+, we need to store the intended output shape for the + # fused matmul reduce scatter implementation to use. + if matmul.post_mm_reshape: + output_shape = list(_get_tensor(matmul.post_mm_reshape).shape) + else: + A_orig_shape = list(_get_tensor(matmul.A_node).shape) + B_shape = list(_get_tensor(matmul.B_node).shape) + output_shape = [*A_orig_shape[:-1], B_shape[-1]] + + graph = rs_wait_tensor_node.graph + with graph.inserting_before(rs_wait_tensor_node): + # Restride A tensor before fused op, for optimal perf in fused matmul reduce scatter + if "val" in matmul.A_node.meta: + restrided = restride_A_for_fused_matmul_reduce_scatter( + _get_tensor(matmul.A_node), + scatter_dim_after_maybe_reshape, + ) + matmul.A_node = graph.call_function( + inductor_prims.force_stride_order, + args=(matmul.A_node, restrided.stride()), + ) + + # Replace matched subgraph with fused matmul reduce scatter node + fused_node = _insert_fused_matmul_reduce_scatter( + graph, + matmul, + reduce_op, + orig_scatter_dim, + group_name, + scatter_dim_after_maybe_reshape, + output_shape, + ) + reduce_scatter.replace_with(fused_node) + reduce_scatter.erase() + matmul.erase() + + order = {node: idx for idx, node in enumerate(graph.nodes)} + nodes_to_raise = sorted( + matmul.arg_ancestor_nodes, + key=lambda x: order[x], + ) + for node in nodes_to_raise: + if order[node] > order[fused_node]: + fused_node.prepend(node) + + log.debug("successfully fused matmul reduce scatter") + + +def _get_node_to_ancestors( + graph: torch.fx.Graph, +) -> dict[torch.fx.Node, OrderedSet[torch.fx.Node]]: + """ + Compute the ancestors for all nodes in a graph. + """ + node_to_ancestors = defaultdict(OrderedSet[torch.fx.Node]) # type: ignore[var-annotated] + for node in graph.nodes: + node_to_ancestors[node] = OrderedSet(node.all_input_nodes) + for dep in node.all_input_nodes: + node_to_ancestors[node] |= node_to_ancestors[dep] + + return node_to_ancestors + + +def _get_collective_to_overlappable_nodes( + graph: torch.fx.Graph, +) -> dict[torch.fx.Node, list[torch.fx.Node]]: + """ + For each collective in the graph, find nodes that are neither ancestors nor + descendants of the collective. + """ + + def is_collective(node) -> bool: + # Only consider all-gather and reduce-scatter in the context of + # micro-pipeline TP. + return node.target in [ + torch.ops._c10d_functional.all_gather_into_tensor.default, + torch.ops._c10d_functional.reduce_scatter_tensor.default, + ] + + node_to_ancestors = _get_node_to_ancestors(graph) + collective_to_overlappable_nodes = defaultdict(list) + for node in graph.nodes: + if not is_collective(node): + continue + for x in graph.nodes: + if ( + node not in node_to_ancestors[x] + and x not in node_to_ancestors[node] + and x.op == "call_function" + ): + collective_to_overlappable_nodes[node].append(x) + + return collective_to_overlappable_nodes + + +def _get_unexposed_collectives(graph: torch.fx.Graph) -> list[torch.fx.Node]: + """ + Find all unexposed collectives in the graph. + + Because we don't have the runtime estimate, this function is a rough + estimation using the following strong/hand-wavy assumptions: + + - Only a predefined set of "compute intensive" operation can hide a collective. + - Any "compute intensive" operation can hide exactly one collective. + """ + + def _is_compute_intensive(node: torch.fx.Node) -> bool: + return node.target is torch.ops.aten.mm.default + + collective_to_overlapping_candidates = defaultdict(list) + available_nodes = OrderedSet[torch.fx.Node]() + collective_to_overlappable_nodes = _get_collective_to_overlappable_nodes(graph) + for collective, overlappable_nodes in collective_to_overlappable_nodes.items(): + candidates = [x for x in overlappable_nodes if _is_compute_intensive(x)] + collective_to_overlapping_candidates[collective] = candidates + available_nodes.update(candidates) + + unexposed_collectives = [] + for ( + collective, + overlapping_candidates, + ) in collective_to_overlapping_candidates.items(): + # Each collective consumes exactly one overlapping candidate + for x in overlapping_candidates: + if x in available_nodes: + unexposed_collectives.append(collective) + available_nodes.remove(x) + break + return unexposed_collectives + + +def micro_pipeline_tp_pass(graph: torch.fx.Graph): + all_gathers = find_all_gather_patterns(graph) + reduce_scatters = find_reduce_scatter_patterns(graph) + + # When a collective can be hidden through either simple overlapping or + # micro-pipeline TP, we prefer simple overlapping to avoid the overhead + # associated with decomposition. If reorder_for_compute_comm_overlap is + # enabled, we identify collectives that can be hidden through simple + # overlapping and exclude them from micro-pipeline TP candidates. + if config.reorder_for_compute_comm_overlap: + unexposed_collectives = _get_unexposed_collectives(graph) + all_gathers = [x for x in all_gathers if x.ag_node not in unexposed_collectives] + reduce_scatters = [ + x + for x in reduce_scatters + if x.reduce_scatter_node not in unexposed_collectives + ] + + if not all_gathers and not reduce_scatters: + log.warning( + "async TP found no matching all-gather/reduce-scatter patterns for fusion" + ) + + for all_gather in all_gathers: + fuse_all_gather_matmul(all_gather) + + for reduce_scatter in reduce_scatters: + fuse_matmul_reduce_scatter(reduce_scatter) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/misc_patterns.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/misc_patterns.py new file mode 100644 index 0000000000000000000000000000000000000000..da4c340b1761a03f2fa678e2037500c189acae58 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/misc_patterns.py @@ -0,0 +1,278 @@ +# mypy: allow-untyped-defs +import functools + +import torch +from torch._dynamo.utils import counters +from torch._ops import OpOverload, OpOverloadPacket +from torch.utils._ordered_set import OrderedSet + +from ..pattern_matcher import fwd_only, register_replacement +from ..utils import is_nvidia_sm100_or_later + + +aten = torch.ops.aten + + +@functools.cache +def _misc_patterns_init(input_device: torch.device | None = None): + from .joint_graph import patterns as joint_graph_patterns + from .post_grad import pass_patterns as post_grad_patterns_all + + post_grad_patterns = post_grad_patterns_all[1] # medium priority + + if input_device: + device = str(input_device) + else: + if torch.cuda.is_available(): + # workaround https://github.com/pytorch/pytorch/issues/97894 + device = "cuda" + else: + device = "cpu" + + # These patterns do 2 things + # 1. Since we know that index is completely unique, we can codegen it using + # stores instead of atomic adds, which is quite a bit faster. + # 2. Also, since we are guaranteed that they are completely within bounds, + # we can use unsafe indexing and skip debug asserts + def randperm_index_add_pattern(x, y): + index = torch.randperm(x.shape[0], device=x.device)[: y.shape[0]] + return torch.index_add(x, dim=0, source=y, index=index), index + + def randperm_index_add_replacement(x, y): + index = torch.randperm(x.shape[0], device=x.device)[: y.shape[0]] + return ( + torch.ops.aten._unsafe_index_put( + x, (index,), aten._unsafe_index(x, (index,)) + y, accumulate=False + ), + index, + ) + + register_replacement( + # pyrefly: ignore [bad-argument-type] + randperm_index_add_pattern, + # pyrefly: ignore [bad-argument-type] + randperm_index_add_replacement, + [torch.empty(4, 8, device=device), torch.empty(2, 8, device=device)], + # pyrefly: ignore [bad-argument-type] + fwd_only, + # pyrefly: ignore [bad-argument-type] + [post_grad_patterns, joint_graph_patterns], + skip_duplicates=True, + ) + + def randperm_index_full_pattern(x): + index = torch.randperm(x.shape[0], device=x.device) + return torch.ops.aten.index(x, (index,)), index + + def randperm_index_full_replacement(x): + index = torch.randperm(x.shape[0], device=x.device) + return torch.ops.aten._unsafe_index(x, (index,)), index + + register_replacement( + # pyrefly: ignore [bad-argument-type] + randperm_index_full_pattern, + # pyrefly: ignore [bad-argument-type] + randperm_index_full_replacement, + [torch.empty(4, 8, device=device)], + # pyrefly: ignore [bad-argument-type] + fwd_only, + # pyrefly: ignore [bad-argument-type] + [post_grad_patterns, joint_graph_patterns], + skip_duplicates=True, + ) + + def randperm_index_pattern(x, slice_shape): + index = torch.randperm(x.shape[0], device=x.device)[:slice_shape] + return torch.ops.aten.index(x, (index,)), index + + def randperm_index_replacement(x, slice_shape): + index = torch.randperm(x.shape[0], device=x.device)[:slice_shape] + return torch.ops.aten._unsafe_index(x, (index,)), index + + register_replacement( + # pyrefly: ignore [bad-argument-type] + randperm_index_pattern, + # pyrefly: ignore [bad-argument-type] + randperm_index_replacement, + [torch.empty(4, 8, device=device)], + # pyrefly: ignore [bad-argument-type] + fwd_only, + # pyrefly: ignore [bad-argument-type] + [post_grad_patterns, joint_graph_patterns], + # Keep this smaller than the example input dim so tracing preserves the slice. + scalar_workaround={"slice_shape": 2}, + skip_duplicates=True, + ) + + # Pattern: e8m0 extraction with ceiling rounding (for MX format scaling) + if device.startswith("cuda"): + + def e8m0_extra_check(match): + inp = match.kwargs.get("inp") + if inp is None: + return False + inp_val = inp.meta.get("val") + return ( + inp_val is not None + and inp_val.device.type == "cuda" + and inp_val.dtype == torch.float32 + ) + + is_sm100_plus = is_nvidia_sm100_or_later() + + if is_sm100_plus: + from .. import inductor_prims + + # Pattern 1: Bit manipulation approach (NVIDIA SM100+ only - uses PTX instruction) + def e8m0_rceil_pattern(inp): + inp_bits = inp.view(torch.int32) + biased_exp = (inp_bits >> 23) & 0xFF + mantissa = inp_bits & 0x7FFFFF + needs_round_up = mantissa != 0 + e8m0_biased = biased_exp + needs_round_up.to(torch.int32) + e8m0_biased = torch.clamp(e8m0_biased, 0, 255) + return e8m0_biased.to(torch.uint8) + + def e8m0_rceil_replacement(inp): + return inductor_prims.cvt_e8m0_rceil(inp) + + register_replacement( + # pyrefly: ignore [bad-argument-type] + e8m0_rceil_pattern, + # pyrefly: ignore [bad-argument-type] + e8m0_rceil_replacement, + [torch.randn(32, device="cuda", dtype=torch.float32)], + # pyrefly: ignore [bad-argument-type] + fwd_only, + # pyrefly: ignore [bad-argument-type] + [post_grad_patterns], + extra_check=e8m0_extra_check, + skip_duplicates=True, + ) + + # Pattern 2: log2 + ceil approach (used by torchao MX formats) + # Matches: (clamp(ceil(log2(x)), -127, 127) + 127).to(uint8) + # + # Registered on ALL CUDA hardware. On NVIDIA SM100+ uses the PTX instruction; + # on earlier hardware uses exact IEEE 754 bit-manipulation. + # + # The bit-manipulation replacement is preferred over the software + # log2+ceil because Triton's fused kernels can produce inputs that + # differ by ~1 ULP from eager mode (e.g. due to FMA or libdevice + # polynomial differences in erf-based GELU). When such an input falls + # exactly on a power-of-2 boundary, software log2 may round the result + # to the integer below, making ceil return the wrong value and the + # uint8 output differ by 1. The bit-manipulation approach reads the + # IEEE 754 biased exponent directly, which is always correct for any + # representable positive normal float32 value. + E8M0_BIAS = 127 + + def e8m0_rceil_log2_pattern(inp): + log2_val = torch.log2(inp) + ceil_val = torch.ceil(log2_val) + clamped = torch.clamp(ceil_val, min=-E8M0_BIAS, max=E8M0_BIAS) + biased = clamped + E8M0_BIAS + return biased.to(torch.uint8) + + if is_sm100_plus: + + def e8m0_rceil_log2_replacement(inp): + return inductor_prims.cvt_e8m0_rceil(inp) + + else: + # Bit-manipulation fallback: extract IEEE 754 biased exponent with + # ceiling rounding. Equivalent to clamp(ceil(log2(inp)), -127, 127) + # + 127 for all positive normal float32 values, but avoids software + # log2 imprecision near exact powers of 2. + # Clamp to [0, 254] to match the satfinite semantics of the original + # pattern (clamp(ceil_val, -127, 127) + 127 gives at most 254). + def e8m0_rceil_log2_replacement(inp): + inp_bits = inp.view(torch.int32) + biased_exp = (inp_bits >> 23) & 0xFF + mantissa = inp_bits & 0x7FFFFF + needs_round_up = mantissa != 0 + e8m0_biased = biased_exp + needs_round_up.to(torch.int32) + e8m0_biased = torch.clamp(e8m0_biased, 0, 254) + return e8m0_biased.to(torch.uint8) + + register_replacement( + # pyrefly: ignore [bad-argument-type] + e8m0_rceil_log2_pattern, + # pyrefly: ignore [bad-argument-type] + e8m0_rceil_log2_replacement, + [torch.randn(32, device="cuda", dtype=torch.float32).abs() + 1e-10], + # pyrefly: ignore [bad-argument-type] + fwd_only, + # pyrefly: ignore [bad-argument-type] + [post_grad_patterns], + extra_check=e8m0_extra_check, + skip_duplicates=True, + ) + + # TODO: Add pattern for cvt.rn.bf16x2.ue8m0x2 (e8m0 -> bf16 conversion) + # This is the inverse operation for MX format dequantization + + +class NumpyCompatNormalization: + numpy_compat: dict[str, tuple[str, ...]] = { + "dim": ("axis",), + "keepdim": ("keepdims",), + "input": ("x", "a", "x1"), + "other": ("x2",), + } + inverse_mapping: dict[str, str] + cache: dict["torch.fx.graph.Target", OrderedSet[str]] + + def __init__(self) -> None: + self.cache = {} # callable -> tuple of replaceable args e.g. ["axis"] + self.inverse_mapping = {} + for actual_kwarg, numpy_kwargs in self.numpy_compat.items(): + for numpy_kwarg in numpy_kwargs: + if numpy_kwarg in self.inverse_mapping: + raise AssertionError( + f"duplicate numpy kwarg mapping for {numpy_kwarg}" + ) + self.inverse_mapping[numpy_kwarg] = actual_kwarg + + def __call__(self, graph: torch.fx.Graph): + for node in graph.nodes: + if node.op != "call_function": + continue + if isinstance(node.target, (OpOverload, OpOverloadPacket)): + # only applies to torch ops; e.g. torch.stack(axis=1) works, torch.ops.aten.stack(axis=1) doesn't. + continue + kwargs = node.kwargs + + if node.target in self.cache: + replaceable_kwargs = self.cache[node.target] + else: + signatures = torch.fx.operator_schemas.get_signature_for_torch_op( + node.target + ) + signatures = () if signatures is None else signatures + replaceable_kwargs = OrderedSet() + for sig in signatures: + for param_name in sig.parameters: + if param_name in self.numpy_compat: + replaceable_kwargs.update(self.numpy_compat[param_name]) + + self.cache[node.target] = replaceable_kwargs + + if not replaceable_kwargs: + continue + + new_kwargs = {} + kwargs_changed = False + for k, v in kwargs.items(): + if k in replaceable_kwargs: + kwargs_changed = True + new_kwargs[self.inverse_mapping[k]] = v + else: + new_kwargs[k] = v + + if kwargs_changed: + node.kwargs = torch.fx.immutable_collections.immutable_dict(new_kwargs) + counters["inductor"]["numpy_compat_normalization"] += 1 + + +numpy_compat_normalization = NumpyCompatNormalization() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/mkldnn_fusion.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/mkldnn_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..59424e087c1274e0e1121955d3b747b2e7c3231a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/mkldnn_fusion.py @@ -0,0 +1,1637 @@ +# mypy: allow-untyped-defs +import functools +import operator +from functools import reduce +from typing import Any, TYPE_CHECKING + +import torch +from torch._dynamo.utils import counters +from torch.fx.experimental.symbolic_shapes import has_free_symbols, optimization_hint +from torch.utils._ordered_set import OrderedSet + +from .. import ir, mkldnn_ir +from ..lowering import lowerings as L +from ..pattern_matcher import ( + Arg, + CallFunction, + filter_nodes, + get_arg_value, + KeywordArg, + MULTIPLE, +) +from ..utils import ( + is_mkldnn_bf16_supported, + is_mkldnn_fp16_supported, + SUPPORTED_MKLDNN_DEVICES, +) +from ..virtualized import ops, V +from .freezing_patterns import register_freezing_graph_pattern +from .post_grad import register_lowering_pattern +from .quantization import ( + _register_int8_woq_concat_linear_pattern, + _register_quantization_lowerings, + _register_woq_lowerings, +) + + +if TYPE_CHECKING: + from collections.abc import Callable + + +if torch._C._has_mkldnn: + aten = torch.ops.aten + mkldnn = torch.ops.mkldnn + prims = torch.ops.prims + + _conv_args = [Arg() for _ in range(10)] + _linear_args = [Arg() for _ in range(6)] + _conv_transpose_args = [Arg() for _ in range(11)] + + class MkldnnDeviceOpBase: + def get_linear_transpose_weight(self, weight_node): + raise NotImplementedError + + def pack_conv_weight( + self, + graph, + is_transposed, + weight, + constant_args, + input_size, + ): + raise NotImplementedError + + def pack_linear_weight( + self, graph, is_lp_weight, transpose_weight_node, batch_size + ): + raise NotImplementedError + + def pack_linear( + self, graph, is_lp_weight, batch_size, input, packed_weight_node, bias + ): + raise NotImplementedError + + class CpuMkldnnDeviceOp(MkldnnDeviceOpBase): + def get_linear_transpose_weight(self, weight_node): + packed_weight_node = weight_node + if packed_weight_node.target != mkldnn._reorder_linear_weight: + raise AssertionError( + "expected packed_weight_node.target to be " + "mkldnn._reorder_linear_weight, got " + f"{packed_weight_node.target}" + ) + transpose_weight_node = packed_weight_node.args[0] + if transpose_weight_node.target is not aten.permute.default: + raise AssertionError( + "expected transpose_weight_node.target to be " + f"aten.permute.default, got {transpose_weight_node.target}" + ) + return transpose_weight_node + + def pack_conv_weight( + self, + graph, + is_transposed, + weight, + constant_args, + input_size, + ): + packed_weight_op = mkldnn._reorder_convolution_weight + if is_transposed: + packed_weight_op = mkldnn._reorder_convolution_transpose_weight + + # mkldnn_reorder_conv_weight(self, padding, stride, dilation, groups, input_size) + packed_weight_inputs = (weight,) + tuple(constant_args) + (input_size,) + return graph.create_node( + "call_function", packed_weight_op, args=packed_weight_inputs + ) + + def pack_linear_weight( + self, graph, is_lp_weight, transpose_weight_node, batch_size + ): + # For bfloat16 dynamic shape path, using input size hint to pack weight for a better performance. + packed_weight_inputs = ( + transpose_weight_node, + optimization_hint(batch_size) + if has_free_symbols(batch_size) + else batch_size, + ) + + # MKL packed matrix can't be copied to a different address because the internal implementation + # depends on the alignment of internally-stored metadata. + # In aot mode, we need to firstly save the packed weight, when loading it, + # it will be in a different address which doesn't work. + # Disable MKL prepack linear in AOT mode. + # Disable MKL prepack linear when batch_size has free symbols. + packed_weight_op = ( + mkldnn._reorder_linear_weight + if ( + is_lp_weight + or mkldnn._is_mkldnn_acl_supported() + or V.aot_compilation + or has_free_symbols(batch_size) + ) + else torch.ops.mkl._mkl_reorder_linear_weight + ) + return graph.create_node( + "call_function", packed_weight_op, args=packed_weight_inputs + ) + + def pack_linear( + self, graph, is_lp_weight, batch_size, input, packed_weight_node, bias + ): + packed_linear_inputs: tuple[Any, ...] = (input, packed_weight_node) + transpose_weight_node = packed_weight_node.args[0] + if ( + is_lp_weight + or mkldnn._is_mkldnn_acl_supported() + or V.aot_compilation + or has_free_symbols(batch_size) + ): + packed_linear_inputs += (bias, "none", [], "") + packed_linear_op: Callable[..., Any] = mkldnn._linear_pointwise.default + else: + packed_linear_inputs += (transpose_weight_node, bias, batch_size) + packed_linear_op = torch.ops.mkl._mkl_linear + + return graph.create_node( + "call_function", packed_linear_op, packed_linear_inputs + ) + + class XpuMkldnnDeviceOp(MkldnnDeviceOpBase): + def pack_conv_weight( + self, + graph, + is_transposed, + weight, + constant_args, + input_size, + ): + if is_transposed: + raise AssertionError( + "'mkldnn::_convolution_transpose_pointwise' is not currently implemented for the XPU device." + ) + return weight + + def _get_mkldnn_device_op(device_type: str) -> MkldnnDeviceOpBase: + """ + Returns the MKLDNN device operation class based on the current device type. + """ + if device_type == "cpu": + return CpuMkldnnDeviceOp() + elif device_type == "xpu": + return XpuMkldnnDeviceOp() + else: + raise RuntimeError(f"MKLDNN is not supported on {device_type} device.") + + def _is_valid_grouped_gemm_fusion(computation_nodes): + """ + Here we check: + 1. More than 1 GEMM nodes has been found. + 2. All the GEMM nodes share the same activation. + 3. All the GEMM nodes have same weight size but different wgt node. + """ + computation_op = mkldnn._linear_pointwise.default + act = computation_nodes[0].args[0] + wgt = computation_nodes[0].args[1] + wgt_size = wgt.meta.get("val").size() # type: ignore[union-attr] + return len(computation_nodes) >= 2 and all( + ( + node.target == computation_op + and node.args[0] == act + and (node.args[1].meta.get("val").size() == wgt_size) + and (node.args[1] != wgt or gemm_idx == 0) + ) + for gemm_idx, node in enumerate(computation_nodes) + ) + + def grouped_gemm_pass(graph: torch.fx.Graph): + """ + Group GEMM has multi output nodes which is complicated to define a Pattern. + Use below way to connect the pattern to the lowering. + TODO: Use MultiOutputPattern, current limitation is the pattern requires + fixed number of output nodes. Extend to support Group GEMM for pattern matcher. + """ + computation_op = mkldnn._linear_pointwise.default + from ..mkldnn_lowerings import grouped_gemm_lowering + + for node in graph.find_nodes(op="call_function", target=computation_op): + if ( + not node._erased + and isinstance(node.meta.get("val"), torch.Tensor) + and node.meta["val"].device.type == "cpu" + ): + act = node.args[0] + users = list(act.users) + if _is_valid_grouped_gemm_fusion(users): + with graph.inserting_before(node): + grouped_gemm_node = graph.create_node( + "call_function", + grouped_gemm_lowering, + ( + act, + [user.args[1] for user in users], + [user.args[2] for user in users], + ), + ) + grouped_gemm_node.meta["val"] = [ + user.meta["val"] for user in users + ] + with graph.inserting_after(grouped_gemm_node): + for gemm_idx, user in enumerate(users): + if user.target != computation_op: + raise AssertionError( + "expected user.target to be " + f"{computation_op}, got {user.target}" + ) + get_item = graph.create_node( + "call_function", + operator.getitem, + ( + grouped_gemm_node, + gemm_idx, + ), + ) + user.replace_all_uses_with(get_item) + graph.erase_node(user) + return + + def _conv_call(users=1): + return CallFunction( + mkldnn._convolution_pointwise.default, *_conv_args, _users=users + ) + + def _linear_call(users=1): + return CallFunction( + mkldnn._linear_pointwise.default, *_linear_args, _users=users + ) + + def _conv_transpose_call(users=1): + return CallFunction( + mkldnn._convolution_transpose_pointwise.default, + *_conv_transpose_args, + _users=users, + ) + + def _to_float(input_call, users=1): + return CallFunction( + prims.convert_element_type.default, + input_call, + KeywordArg("to_float"), + _users=users, + ) + + def _to_bf16(input_call): + return CallFunction( + prims.convert_element_type.default, + input_call, + KeywordArg("to_bf16"), + _users=1, + ) + + def _to_fp16(input_call): + return CallFunction( + prims.convert_element_type.default, + input_call, + KeywordArg("to_fp16"), + _users=1, + ) + + def _unary_fusion_pattern(unary_fusion, call_fn, users, lowp_dtype): + # only insert to_dtype if lowp_dtype is True + computation_call = ( + _to_float(call_fn(), users=users) if lowp_dtype else call_fn(users=users) + ) + out = unary_fusion(computation_call) + if lowp_dtype == torch.bfloat16: + return _to_bf16(out) + elif lowp_dtype == torch.float16: + return _to_fp16(out) + else: + return out + + def _gelu_fusion_1(computation_call): + return CallFunction( + aten.mul, + CallFunction(aten.mul, computation_call, 0.5), + CallFunction( + aten.add, + CallFunction( + aten.erf, + CallFunction(aten.mul, computation_call, 0.7071067811865476), + ), + 1, + ), + ) + + def _gelu_fusion_2(computation_call): + return CallFunction( + aten.mul, + CallFunction(aten.mul, computation_call, 0.5), + CallFunction( + aten.add, + CallFunction( + aten.tanh, + CallFunction( + aten.mul, + CallFunction( + aten.add, + computation_call, + CallFunction( + aten.mul, + CallFunction( + aten.mul, + CallFunction( + aten.mul, computation_call, computation_call + ), + computation_call, + ), + 0.044715, + ), + ), + 0.7978845608028654, + ), + ), + 1, + ), + ) + + def _hardswish_fusion(computation_call): + return CallFunction( + aten.div, + CallFunction( + aten.mul, + computation_call, + CallFunction( + aten.clamp_max, + CallFunction( + aten.clamp_min, CallFunction(aten.add, computation_call, 3), 0 + ), + 6, + ), + ), + 6, + ) + + def _silu_fusion(computation_call): + # Match: x / (exp(-x) + 1) pattern used by inductor's silu decomposition + return CallFunction( + aten.div, + computation_call, + CallFunction( + aten.add, + CallFunction(aten.exp, CallFunction(aten.neg, computation_call)), + 1, + ), + ) + + def _hardsigmoid_fusion(computation_call): + return CallFunction( + aten.div, + CallFunction( + aten.clamp_max, + CallFunction( + aten.clamp_min, CallFunction(aten.add, computation_call, 3), 0 + ), + 6, + ), + 6, + ) + + def _leaky_relu_fusion(computation_call): + return CallFunction( + aten.where, + CallFunction(aten.gt, computation_call, 0), + computation_call, + CallFunction(aten.mul, computation_call, KeywordArg("negative_slope")), + ) + + def _hardtanh_fusion(computation_call): + return CallFunction( + aten.clamp_max, + CallFunction(aten.clamp_min, computation_call, KeywordArg("min_value")), + KeywordArg("max_value"), + ) + + def _combined_fusion(computation_call, elementwise_op): + return CallFunction(elementwise_op, computation_call) + + # binary_op(other, computation_op) + def _binary_fusion_v1(computation_call, binary_fn): + return CallFunction(binary_fn, KeywordArg("other"), computation_call) + + # binary_op(computation_op, other) + def _binary_fusion_v2(computation_call, binary_fn): + return CallFunction(binary_fn, computation_call, KeywordArg("other")) + + def _is_single_computation_op(computation_op, lowp_dtype=None): + def fn(match): + computation_nodes = filter_nodes(match.nodes, computation_op) + + if lowp_dtype: + output_node_meta = match.output_node().meta.get("val") + if output_node_meta.dtype != lowp_dtype: + return False + + if len(computation_nodes) < 1: + return False + if any(n.args[-3] != "none" for n in computation_nodes): + return False + return True + + return fn + + def _is_valid_computation_unary_fusion(computation_op, lowp_dtype=None): + def fn(match): + matched = _is_single_computation_op(computation_op, lowp_dtype)(match) + computation_node = filter_nodes(match.nodes, computation_op)[0] + if lowp_dtype: + conversion_dtype_nodes = filter_nodes( + match.nodes, prims.convert_element_type.default + ) + if len(conversion_dtype_nodes) != 2: + return False + # fusion pattern is always in the form of computation_op + to_float32 + unary_op + to_bfloat16 + if computation_node == conversion_dtype_nodes[0].args[0]: + to_float = conversion_dtype_nodes[0].args[1] + to_lp = conversion_dtype_nodes[1].args[1] + else: + to_float = conversion_dtype_nodes[1].args[1] + to_lp = conversion_dtype_nodes[0].args[1] + matched = matched and to_float == torch.float and to_lp == lowp_dtype + return matched + + return fn + + def _register_unary_fusion_lowering( + pattern, unary_attr, computation_op, lowp_dtype=None + ): + @register_lowering_pattern( + pattern, + extra_check=_is_valid_computation_unary_fusion(computation_op, lowp_dtype), + output_metadata_ignores_input_storage=True, + ) + def fn(match, *args, **kwargs): + computation_args = list(args)[:-3] + [ + unary_attr.op_name, + unary_attr.scalars_attr, + unary_attr.algorithm_attr, + ] + counters["inductor"]["mkldnn_unary_fusion_matcher_count"] += 1 + counters["inductor"]["mkldnn_unary_fusion_matcher_nodes"] += len( + match.nodes + ) + return L[computation_op](*computation_args) + + return fn + + def _register_leaky_relu_fusion_lowering(pattern, computation_op, lowp_dtype=None): + @register_lowering_pattern( + pattern, + extra_check=_is_single_computation_op(computation_op, lowp_dtype), + output_metadata_ignores_input_storage=True, + ) + def fn(match, *args, **kwargs): + negative_slope = kwargs.get("negative_slope") + if isinstance(negative_slope, ir.TensorBox): + matched = False + else: # inp is a Number + matched = True + if lowp_dtype: + dtype1 = kwargs.get("to_float") + dtype2 = ( + kwargs.get("to_bf16") + if lowp_dtype == torch.bfloat16 + else kwargs.get("to_fp16") + ) + matched = matched and dtype1 == torch.float and dtype2 == lowp_dtype + computation_args = list(args) + counters["inductor"]["mkldnn_unary_fusion_matcher_count"] += 1 + counters["inductor"]["mkldnn_unary_fusion_matcher_nodes"] += len( + match.nodes + ) + if matched: + computation_args = computation_args[:-3] + [ + "leaky_relu", + [negative_slope], + "", + ] + return L[computation_op](*computation_args) + else: + # computation_args += ["none", [], ""] + out = L[computation_op](*computation_args) + if lowp_dtype: + out = L[prims.convert_element_type.default](out, dtype=torch.float) + out = L[aten.where]( + L[aten.gt](out, 0), + out, + L[aten.mul](out, negative_slope), + ) + if lowp_dtype: + out = L[prims.convert_element_type.default](out, dtype=dtype2) # type: ignore[possibly-undefined] + return out + + return fn + + def _register_hardtanh_fusion_lowering(pattern, computation_op, lowp_dtype=None): + @register_lowering_pattern( + pattern, + extra_check=_is_single_computation_op(computation_op, lowp_dtype), + output_metadata_ignores_input_storage=True, + ) + def fn(match, *args, **kwargs): + min_value = kwargs.get("min_value") + max_value = kwargs.get("max_value") + if isinstance(min_value, ir.TensorBox) or isinstance( + max_value, ir.TensorBox + ): + matched = False + else: # inp is a Number + if max_value is None: + raise AssertionError("expected max_value to not be None") + matched = min_value <= max_value + if lowp_dtype: + dtype1 = kwargs.get("to_float") + dtype2 = ( + kwargs.get("to_bf16") + if lowp_dtype == torch.bfloat16 + else kwargs.get("to_fp16") + ) + matched = matched and dtype1 == torch.float and dtype2 == lowp_dtype + computation_args = list(args) + counters["inductor"]["mkldnn_unary_fusion_matcher_count"] += 1 + counters["inductor"]["mkldnn_unary_fusion_matcher_nodes"] += len( + match.nodes + ) + if matched: + computation_args = computation_args[:-3] + [ + "hardtanh", + [min_value, max_value], + "", + ] + return L[computation_op](*computation_args) + else: + out = L[computation_op](*computation_args) + if lowp_dtype: + out = L[prims.convert_element_type.default](out, dtype=torch.float) + out = L[aten.clamp_max](L[aten.clamp_min](out, min_value), max_value) + if lowp_dtype: + out = L[prims.convert_element_type.default](out, dtype=dtype2) # type: ignore[possibly-undefined] + return out + + return fn + + _binary_attr = { + aten.add: "add", + ops.add: "add", + aten.sub: "sub", + ops.sub: "sub", + } + + def _is_valid_binary(match, computation_op, binary_op): + binary_nodes = filter_nodes(match.nodes, binary_op) + if len(binary_nodes) < 1: + return False + + def get_meta_value(argument: torch.fx.node.Argument): + # Only torch.fx.Node is expected to have meta. + if isinstance(argument, torch.fx.Node): + return argument.meta.get("val", None) + return None + + if any( + not isinstance(get_meta_value(n.args[0]), torch.Tensor) + or not isinstance(get_meta_value(n.args[1]), torch.Tensor) + for n in binary_nodes + ): + return False + # check alpha is one. + if any( + get_arg_value(n, 2, kwarg_name="alpha") != 1.0 + and get_arg_value(n, 2, kwarg_name="alpha") is not None + for n in binary_nodes + ): + return False + + def _check_input_sizes(n, computation_op): + # Check if the tensor shape of the 'other' node is the same as or + # can be broadcasted to the tensor shape of the computation node. + computation_node = ( + n.args[0] if n.args[1] is match.kwargs["other"] else n.args[1] + ) + if computation_node.target != computation_op: + raise AssertionError( + "expected computation_node.target to be " + f"{computation_op}, got {computation_node.target}" + ) + computation_node_size = get_meta_value(computation_node).size() + if computation_op is mkldnn._linear_pointwise.default: + broadcast_sizes = [] + if len(computation_node_size) >= 2: + broadcast_sizes = [ + torch.Size( + [1 for _ in range(len(computation_node_size) - 1)] + + [computation_node_size[-1]] + ), + ] + else: + if not len(computation_node_size) > 2: + raise AssertionError( + "expected len(computation_node_size) > 2, got " + f"{len(computation_node_size)}" + ) + broadcast_sizes = [ + torch.Size( + [computation_node_size[0], computation_node_size[1]] + + [1 for _ in range(len(computation_node_size) - 2)] + ), + torch.Size( + [1, computation_node_size[1]] + + [1 for _ in range(len(computation_node_size) - 2)] + ), + torch.Size([1 for _ in range(len(computation_node_size))]), + ] + return ( + get_meta_value(match.kwargs["other"]).size() + in [ + computation_node_size, + ] + + broadcast_sizes + ) + + if any( + not _check_input_sizes(n, computation_op) + or get_meta_value(n.args[0]).device != get_meta_value(n.args[1]).device + or get_meta_value(n.args[0]).dtype != get_meta_value(n.args[1]).dtype + for n in binary_nodes + ): + return False + # check args[0] and args[1] is not same + if any(n.args[0] == n.args[1] for n in binary_nodes): + return False + return True + + def _is_valid_computation_binary(computation_op, binary_op, other_index=None): + def fn(match): + if not _is_single_computation_op(computation_op)(match): + return False + if not _is_valid_binary(match, computation_op, binary_op): + return False + return True + + return fn + + def _get_remaining_users(extra_input_node, compute_node): + # Think about this pattern: + # ReLU + # / \ + # Conv1 + # / \ + # Conv2 + # \ / + # Add + # Although, the extra input node (ReLU) has more than 1 users: Conv1 and Add. + # The Conv1 is the ancestor node of the current compute node (Conv2). + # This indicates that the buffer of ReLU has completed all its usage, + # So we can safely make changes to it now by doing Conv2->Add inplace fusion. + # Take above case as example: + # * extra_input_node: ReLU + # * compute_node: Conv2 + # _get_remaining_users will return the users of extra_input_node which are not + # ancestor node of compute_node. + def _is_ancestor_node(_current_node, _ancestor_node): + # Check whether _ancestor_node is the ancestor node of _current_node + _node_list = [_current_node] + _visited_nodes = OrderedSet[torch.fx.Node]() + while len(_node_list) != 0: + _current_node = _node_list.pop(0) + if _current_node not in _visited_nodes: + _visited_nodes.add(_current_node) + if _current_node == _ancestor_node: + return True + elif isinstance( + _current_node, torch.fx.Node + ) and _current_node.op not in ["placeholder", "output", "get_attr"]: + for input in _current_node.all_input_nodes: + _node_list.append(input) # noqa: PERF402 + return False + + return [ + user + for user in list(extra_input_node.users) + if not _is_ancestor_node(compute_node, user) + ] + + def _is_valid_computation_binary_inplace(computation_op, binary_op, other_index): + def fn(match): + if not _is_valid_computation_binary(computation_op, binary_op)(match): + return False + binary_nodes = filter_nodes(match.nodes, binary_op) + + def _get_compute_node(_binary_node, _other_index): + if len(_binary_node.all_input_nodes) != 2: + raise AssertionError("Binary node should have 2 input nodes.") + _compute_index = 1 if (_other_index == 0) else 0 + return _binary_node.args[_compute_index] + + def _other_input_not_inplaceable(_binary_node, _other_index): + _compute_node = _get_compute_node(_binary_node, _other_index) + return ( + len( + _get_remaining_users( + _binary_node.args[_other_index], _compute_node + ) + ) + > 1 + or _binary_node.args[_other_index] == _compute_node.args[0] + ) + + if any(_other_input_not_inplaceable(n, other_index) for n in binary_nodes): + return False + if any( + n.args[other_index].op in ["placeholder", "output"] + for n in binary_nodes + ): + return False + return True + + return fn + + def _register_binary_unary_fusion_lowering( + pattern, + computation_op, + binary_op, + fusion_op, + unary_attr=None, + ): + @register_lowering_pattern( + pattern, + extra_check=_is_valid_computation_binary(computation_op, binary_op), + output_metadata_ignores_input_storage=True, + ) + def fn(match, *args, **kwargs): + other = kwargs.get("other") + if not isinstance(other, ir.TensorBox): + raise AssertionError( + f"expected other to be ir.TensorBox, got {type(other)}" + ) + binary_attr = _binary_attr[binary_op] + args_list = list(args) + computation_args = [args_list[0], other] + args_list[1:-3] + [binary_attr] + if len(args_list) > 6: + if unary_attr is not None: + computation_args += [ + 1.0, + unary_attr.op_name, + unary_attr.scalars_attr, + unary_attr.algorithm_attr, + ] + else: + computation_args += [1.0, None, [], None] + counters["inductor"]["mkldnn_conv_binary_unary_fusion_matcher_count"] += 1 + counters["inductor"]["mkldnn_conv_binary_unary_fusion_matcher_nodes"] += ( + len(match.nodes) + ) + return L[fusion_op](*computation_args) + + return fn + + def _can_be_inplace(_other): + return not ( + isinstance(_other.data, ir.BaseView) + or len(_other.get_inputs_that_alias_output()) > 0 + ) + + def _qlinear_binary_can_be_inplace(_other): + if isinstance(_other.data, ir.BaseView): + + def unwrap_buffer(data): + if isinstance(data, ir.StorageBox): + return data.data + return data + + data = _other.data.unwrap_view() + if isinstance(unwrap_buffer(data), ir.CppTemplateBuffer): + # It can be inplaced when _other is the 2D to 3D view of + # a CppTemplateBuffer because if there is a view of CppTemplateBuffer, + # CppTemplateBuffer will not be used directly but the view. + return True + else: + # The case of QLinearPointwiseBinaryPT2E(sum) -> QLinearPointwiseBinaryPT2E(sum) + # is similar to CppTemplateBuffer above. + # The output of previous QLinearPointwiseBinaryPT2E is + # the input x2 of current QLinearPointwiseBinaryPT2E. + # Use V.graph.operations to check if _other is a view of the output + # of previous QLinearPointwiseBinaryPT2E (the inputs[6]). + for op in V.graph.operations: + if ( + isinstance(op, mkldnn_ir.QLinearPointwiseBinaryPT2E) + and unwrap_buffer(data) == op.inputs[6] # type: ignore[attr-defined] + ): + return True + return False + elif len(_other.get_inputs_that_alias_output()) > 0: + return False + else: + return True + + def _register_binary_unary_maybe_inplace_fusion_lowering( + pattern, + computation_op, + binary_op, + inplace_fusion_op, + outplace_fusion_op, + unary_attr=None, + other_index=None, + ): + @register_lowering_pattern( + pattern, + extra_check=_is_valid_computation_binary_inplace( + computation_op, binary_op, other_index + ), + output_metadata_ignores_input_storage=True, + ) + def fn(match, *args, **kwargs): + other = kwargs.get("other") + if not isinstance(other, ir.TensorBox): + raise AssertionError( + f"expected other to be ir.TensorBox, got {type(other)}" + ) + binary_attr = _binary_attr[binary_op] + args_list = list(args) + computation_args = [args_list[0], other] + args_list[1:-3] + [binary_attr] + if len(args_list) > 6: + if unary_attr is not None: + computation_args += [ + 1.0, + unary_attr.op_name, + unary_attr.scalars_attr, + unary_attr.algorithm_attr, + ] + else: + computation_args += [1.0, None, [], None] + counters["inductor"]["mkldnn_conv_binary_unary_fusion_matcher_count"] += 1 + counters["inductor"]["mkldnn_conv_binary_unary_fusion_matcher_nodes"] += ( + len(match.nodes) + ) + # Make sure the other is not an alias or mutation (fx side doesn't have such info). + other.realize() + if not _can_be_inplace(other) or other.data.shape != list( + match.nodes[0].meta["val"].size() + ): + return L[outplace_fusion_op](*computation_args) + return L[inplace_fusion_op](*computation_args) + + return fn + + computation_ops = [ + mkldnn._convolution_pointwise.default, + mkldnn._linear_pointwise.default, + mkldnn._convolution_transpose_pointwise.default, + ] + + class UnaryAttr: + def __init__( + self, op_name: str, scalars_attr=None, algorithm_attr=None + ) -> None: + self.op_name = op_name + self.scalars_attr = scalars_attr if scalars_attr else [] + self.algorithm_attr = algorithm_attr if algorithm_attr else "" + + def _register_unary_fusion(): + computation_call_fns = [_conv_call, _linear_call, _conv_transpose_call] + + def _unary_fusion_patterns(lowp_dtype): + replacement_unary_fusion_patterns = { + UnaryAttr("gelu", algorithm_attr="tanh"): [ + _unary_fusion_pattern(_gelu_fusion_2, call_fn, 4, lowp_dtype) + for call_fn in computation_call_fns + ], + UnaryAttr("gelu", algorithm_attr="none"): [ + _unary_fusion_pattern(_gelu_fusion_1, call_fn, 2, lowp_dtype) + for call_fn in computation_call_fns + ], + UnaryAttr("hardswish"): [ + _unary_fusion_pattern(_hardswish_fusion, call_fn, 2, lowp_dtype) + for call_fn in computation_call_fns + ], + UnaryAttr("hardsigmoid"): [ + _unary_fusion_pattern(_hardsigmoid_fusion, call_fn, 1, lowp_dtype) + for call_fn in computation_call_fns + ], + UnaryAttr("swish"): [ + _unary_fusion_pattern(_silu_fusion, call_fn, 2, lowp_dtype) + for call_fn in computation_call_fns + ], + } + if not lowp_dtype: + call_user1 = [call_fn(users=1) for call_fn in computation_call_fns] + replacement_unary_fusion_patterns.update( + { + UnaryAttr("relu"): [ + _combined_fusion(u, aten.relu) for u in call_user1 + ], + UnaryAttr("sigmoid"): [ + _combined_fusion(u, aten.sigmoid) for u in call_user1 + ], + UnaryAttr("tanh"): [ + _combined_fusion(u, aten.tanh) for u in call_user1 + ], + } + ) + + return replacement_unary_fusion_patterns + + for lowp_dtype in [torch.bfloat16, torch.float16, None]: + replace_patterns = _unary_fusion_patterns(lowp_dtype) + for unary_attr, patterns in replace_patterns.items(): + _register_unary_fusion_lowering( + patterns[0], unary_attr, computation_ops[0], lowp_dtype + ) + _register_unary_fusion_lowering( + patterns[1], unary_attr, computation_ops[1], lowp_dtype + ) + _register_unary_fusion_lowering( + patterns[2], unary_attr, computation_ops[2], lowp_dtype + ) + _leaky_relu_patterns = [ + _unary_fusion_pattern(_leaky_relu_fusion, call_fn, 3, lowp_dtype) + for call_fn in computation_call_fns + ] + for pattern, computation_op in zip(_leaky_relu_patterns, computation_ops): + _register_leaky_relu_fusion_lowering( + pattern, computation_op, lowp_dtype + ) + hardtanh_patterns = [ + _unary_fusion_pattern(_hardtanh_fusion, call_fn, 1, lowp_dtype) + for call_fn in computation_call_fns + ] + for pattern, computation_op in zip(hardtanh_patterns, computation_ops): + _register_hardtanh_fusion_lowering(pattern, computation_op, lowp_dtype) + + def _register_inplace_fusion(): + binary_ops = [aten.add, ops.add] + inplace_fusion_op = mkldnn._convolution_pointwise_.binary + outplace_fusion_op = mkldnn._convolution_pointwise.binary + conv_call = _conv_call(users=1) + conv_op = computation_ops[0] + for binary_op in binary_ops: + binary_v1 = _binary_fusion_v1(conv_call, binary_op) + binary_unary_v1 = _combined_fusion(binary_v1, aten.relu) + _register_binary_unary_maybe_inplace_fusion_lowering( + binary_unary_v1, + conv_op, + binary_op, + inplace_fusion_op, + outplace_fusion_op, + other_index=0, + unary_attr=UnaryAttr("relu"), + ) + _register_binary_unary_maybe_inplace_fusion_lowering( + binary_v1, + conv_op, + binary_op, + inplace_fusion_op, + outplace_fusion_op, + other_index=0, + ) + binary_v2 = _binary_fusion_v2(conv_call, binary_op) + binary_unary_v2 = _combined_fusion(binary_v2, aten.relu) + _register_binary_unary_maybe_inplace_fusion_lowering( + binary_unary_v2, + conv_op, + binary_op, + inplace_fusion_op, + outplace_fusion_op, + other_index=1, + unary_attr=UnaryAttr("relu"), + ) + _register_binary_unary_maybe_inplace_fusion_lowering( + binary_v2, + conv_op, + binary_op, + inplace_fusion_op, + outplace_fusion_op, + other_index=1, + ) + + def _register_binary_fusion(): + binary_ops = [aten.add, ops.add, aten.sub, ops.sub] + fusion_ops = [ + mkldnn._convolution_pointwise.binary, + mkldnn._linear_pointwise.binary, + ] + _computation_user_1 = [_conv_call(users=1), _linear_call(users=1)] + for computation_call, computation_op, fusion_op in zip( + _computation_user_1, computation_ops[:-1], fusion_ops + ): + for binary_op in binary_ops: + pattern = _binary_fusion_v2(computation_call, binary_op) + _register_binary_unary_fusion_lowering( + pattern, computation_op, binary_op, fusion_op + ) + + for binary_op in [aten.add, ops.add]: + pattern = _binary_fusion_v1(computation_call, binary_op) + _register_binary_unary_fusion_lowering( + pattern, computation_op, binary_op, fusion_op + ) + + def _register_binary_unary_fusion(): + binary_ops = [aten.add, ops.add, aten.sub, ops.sub] + fusion_ops = [mkldnn._convolution_pointwise.binary] + _computation_user_1 = [_conv_call(users=1)] + for computation_call, computation_op, fusion_op in zip( + _computation_user_1, computation_ops[:-1], fusion_ops + ): + for binary_op in binary_ops: + pattern_v1 = _combined_fusion( + _binary_fusion_v2(computation_call, binary_op), aten.relu + ) + _register_binary_unary_fusion_lowering( + pattern_v1, + computation_op, + binary_op, + fusion_op, + unary_attr=UnaryAttr("relu"), + ) + for binary_op in [aten.add, ops.add]: + pattern_v2 = _combined_fusion( + _binary_fusion_v1(computation_call, binary_op), aten.relu + ) + _register_binary_unary_fusion_lowering( + pattern_v2, + computation_op, + binary_op, + fusion_op, + unary_attr=UnaryAttr("relu"), + ) + + def _recover_linear(): + # convert reshape+linear+reshape to a single linear for applying fusion path. + # concat_linear (pass_number=0) -> mkldnn_linear_pack (pass_number=1) -> _recover_linear(pass_number=2) + @register_freezing_graph_pattern( + CallFunction( + aten.reshape.default, + CallFunction( + mkldnn._linear_pointwise.default, + CallFunction( + aten.reshape.default, + Arg(), + KeywordArg("reshape_1"), + _users=MULTIPLE, + ), + Arg(), + Arg(), + Arg(), + Arg(), + Arg(), + ), + KeywordArg("reshape_2"), + ), + pass_number=2, + ) + def reshape_linear_reshape_pattern(match, *args, **kwargs): + def get_val(val): + return val if isinstance(val, int) else val.meta.get("val") + + reshape_1 = kwargs.get("reshape_1") + reshape_2 = kwargs.get("reshape_2") + if not isinstance(reshape_1, list): + raise AssertionError( + f"expected reshape_1 to be list, got {type(reshape_1)}" + ) + if not isinstance(reshape_2, list): + raise AssertionError( + f"expected reshape_2 to be list, got {type(reshape_2)}" + ) + if len(reshape_1) != 2: + raise AssertionError( + f"expected len(reshape_1) == 2, got {len(reshape_1)}" + ) + + graph = match.graph + reshape_2_node = match.output_node() + linear_input_node = reshape_2_node.args[0].args[0].args[0] + # check linear's input's shape[:-1] == reshape_2[:-1] + # and check product(reshape_2[:-1]) == reshape_1[0] + can_remove_reshape = linear_input_node.meta.get("val").shape[ + :-1 + ] == torch.Size([get_val(val) for val in reshape_2[:-1]]) + can_remove_reshape = can_remove_reshape and ( + reduce( + operator.mul, + [get_val(val) for val in reshape_2[:-1]], + ) + == get_val(reshape_1[0]) + ) + + if can_remove_reshape: + repl = graph.call_function(mkldnn._linear_pointwise.default, args) + repl.meta.update(reshape_2_node.meta) + reshape_2_node.replace_all_uses_with(repl) + old_linear_node = reshape_2_node.args[0] + reshape_1_node = old_linear_node.args[0] + graph.erase_node(reshape_2_node) + graph.erase_node(old_linear_node) + if len(reshape_1_node.users) == 0: + graph.erase_node(reshape_1_node) + counters["inductor"]["mkldnn_reshape_linear_reshape_matcher_count"] += 1 + counters["inductor"]["mkldnn_reshape_linear_reshape_matcher_nodes"] += len( + match.nodes + ) + + def is_linear_add_bias(match): + add_node = match.output_node() + linear_node = add_node.args[0] + device_type = add_node.meta.get("val").device.type + mkldnn_device_op = _get_mkldnn_device_op(device_type) + transpose_weight_node = mkldnn_device_op.get_linear_transpose_weight( + linear_node.args[1] + ) + weight_meta = transpose_weight_node.args[0].meta.get("val") + bias_node = add_node.args[1] + if not isinstance(bias_node, torch.fx.Node): + return False + bias_meta = bias_node.meta.get("val") + if weight_meta is None or bias_meta is None: + return False + + if bias_meta.dtype != weight_meta.dtype: + return False + return ( + linear_node.args[2] is None + and bias_meta.dim() == 1 + and bias_meta.size(0) == weight_meta.size(1) + ) + + # convert linear+bias to a single linear for applying fusion path. + @register_freezing_graph_pattern( + CallFunction( + aten.add.Tensor, + CallFunction(mkldnn._linear_pointwise.default, *_linear_args), + Arg(), + ), + pass_number=2, + extra_check=is_linear_add_bias, + ) + def linear_bias_pattern(match, *args): + graph = match.graph + add_node = match.output_node() + linear_node = add_node.args[0] + new_args = list(linear_node.args) + new_args[2] = add_node.args[1] + repl = graph.call_function( + mkldnn._linear_pointwise.default, tuple(new_args) + ) + repl.meta.update(add_node.meta) + add_node.replace_all_uses_with(repl) + match.erase_nodes() + counters["inductor"]["mkldnn_linear_bias_matcher_count"] += 1 + counters["inductor"]["mkldnn_linear_bias_matcher_nodes"] += len(match.nodes) + + def _is_packable_mkldnn_rnn_layer(match): + lstm_node = match.output_node() + POS_WEIGHTS = [1, 2] + POS_INPUTS = [0, 5, 6] + POS_ARGS = POS_WEIGHTS + POS_INPUTS + # Weights should be Constant + if any( + lstm_node.args[POS_WEIGHT].op != "get_attr" for POS_WEIGHT in POS_WEIGHTS + ): + return False + + # Meta info for weights and inputs should be available + if any(lstm_node.args[POS_ARG].meta.get("val") is None for POS_ARG in POS_ARGS): + return False + + # Check device + if any( + lstm_node.args[POS_ARG].meta.get("val").device.type != "cpu" + for POS_ARG in POS_ARGS + ): + return False + + # Check dtype + if any( + lstm_node.args[POS_ARG].meta.get("val").dtype == torch.bfloat16 + and not is_mkldnn_bf16_supported("cpu") + for POS_ARG in POS_ARGS + ): + return False + if any( + lstm_node.args[POS_ARG].meta.get("val").dtype == torch.float16 + and not is_mkldnn_fp16_supported("cpu") + for POS_ARG in POS_ARGS + ): + return False + + return True + + def _is_packable_convolution(match): + """ + Check if the node is supported for MKLDNN convolution. + """ + conv_node = match.output_node() + device_type = conv_node.meta.get("val").device.type + # The operator 'mkldnn::_convolution_transpose_pointwise' is not currently implemented for the XPU device. + if match.kwargs["is_transposed"] and device_type == "xpu": + return False + + input_meta_value = conv_node.args[0].meta.get("val") + weight_meta_value = conv_node.args[1].meta.get("val") + if input_meta_value is None or weight_meta_value is None: + return False + input_size = input_meta_value.shape + if conv_node.args[1].op != "get_attr": + return False + for meta_value in [input_meta_value, weight_meta_value]: + if ( + meta_value is None + or meta_value.device.type not in SUPPORTED_MKLDNN_DEVICES + or (meta_value.dim() != 4 and meta_value.dim() != 5) + ): + return False + + if ( + input_meta_value.dtype == torch.bfloat16 + or weight_meta_value.dtype == torch.bfloat16 + ): + if not is_mkldnn_bf16_supported(device_type): + return False + if ( + input_meta_value.dtype == torch.float16 + or weight_meta_value.dtype == torch.float16 + ): + if not is_mkldnn_fp16_supported(device_type): + return False + is_transposed = conv_node.args[-3] + if is_transposed: + # TODO: Support dynamic shape case for MKLDNN conv transpose. + if has_free_symbols(input_size): + return False + groups = conv_node.args[-1] + in_channels = weight_meta_value.size(0) + # doesn't support group_depthwise_conv_transpose. + if groups > 1 and groups == in_channels: + return False + # Port from: aten/src/ATen/native/Convolution.cpp:is_output_padding_big + output_paddings = conv_node.args[-2] + strides = conv_node.args[3] + if any( + output_padding >= stride + for output_padding, stride in zip(output_paddings, strides) + ): + return False + return True + + def _is_packable_linear(match): + """ + Check if the node is supported for MKLDNN linear. + """ + + def is_const_or_cat_by_const(weight): + if weight.op == "get_attr": + return True + if weight.target != aten.cat.default: + return False + return all(arg.op == "get_attr" for arg in weight.args[0]) + + linear_node = match.output_node() + # mkldnn linear only supports beta=1 or 0 and alpha=1 + if linear_node.target is aten.addmm.default: + alpha = linear_node.kwargs.get("alpha", 1.0) + beta = linear_node.kwargs.get("beta", 1.0) + if (beta != 0.0 and beta != 1.0) or alpha != 1.0: + return False + # weight_idx is 1 for aten.mm and is 2 for aten.addmm + weight_idx = 2 if linear_node.target is aten.addmm.default else 1 + if not is_const_or_cat_by_const(linear_node.args[weight_idx]): + return False + input_meta_value = linear_node.args[weight_idx - 1].meta.get("val") + weight_meta_value = linear_node.args[weight_idx].meta.get("val") + if input_meta_value is None or weight_meta_value is None: + return False + if ( + input_meta_value.dtype == torch.float64 + or weight_meta_value.dtype == torch.float64 + ): + return False + is_lp_weight = weight_meta_value.dtype in ( + torch.bfloat16, + torch.float16, + ) + reduced_f32_matmul_enabled = torch.backends.mkldnn.matmul.fp32_precision in [ # type: ignore[attr-defined] + "bf16", + "tf32", + ] + use_reduced_f32_for_fp32_weight = ( + reduced_f32_matmul_enabled and weight_meta_value.dtype == torch.float32 + ) + compute_with_lp = is_lp_weight or use_reduced_f32_for_fp32_weight + # on x86, for fp32, mkl should be enabled. + # on aarch64, use mkldnn op for fp32 as well if acl is enabled + if ( + not compute_with_lp + and not mkldnn._is_mkldnn_acl_supported() + and not torch._C.has_mkl + ): + return False + for meta_value in [input_meta_value, weight_meta_value]: + if ( + meta_value is None + or meta_value.device.type != "cpu" + or meta_value.dim() != 2 + ): + return False + if weight_idx == 2: + bias_meta_value = linear_node.args[0].meta.get("val") + if ( + bias_meta_value is None + or meta_value.device.type != "cpu" + or bias_meta_value.dim() != 1 + or bias_meta_value.size(0) != weight_meta_value.size(1) + ): + return False + + device_type = input_meta_value.device.type + if ( + input_meta_value.dtype == torch.bfloat16 + or weight_meta_value.dtype == torch.bfloat16 + ): + if not is_mkldnn_bf16_supported(device_type): + return False + if ( + input_meta_value.dtype == torch.float16 + or weight_meta_value.dtype == torch.float16 + ): + if not is_mkldnn_fp16_supported(device_type): + return False + return True + + _aten_conv_args = ( + Arg(), + Arg(), + Arg(), + Arg(), + Arg(), + Arg(), + KeywordArg("is_transposed"), + Arg(), + Arg(), + ) + + _aten_mkldnn_rnn_layer_args = ( + Arg(), # input + Arg(), # weight0 + Arg(), # weight1 + Arg(), # weight2 + Arg(), # weight3 + Arg(), # hx_ + Arg(), # cx_ + KeywordArg("reverse"), # reverse + Arg(), # batch_sizes + Arg(), # mode + Arg(), # hidden_size + Arg(), # num_layers + Arg(), # has_biases + Arg(), # bidirectional + Arg(), # batch_first + Arg(), # train + ) + + def _register_weight_pack_pass(): + @register_freezing_graph_pattern( + CallFunction(aten.convolution.default, *_aten_conv_args), + extra_check=_is_packable_convolution, + ) + def convolution(match, *args, **kwargs): + is_transposed = kwargs.get("is_transposed") + if not isinstance(is_transposed, bool): + raise AssertionError( + f"expected is_transposed to be bool, got {type(is_transposed)}" + ) + graph = match.graph + conv_node = match.output_node() + device_type = conv_node.args[0].meta.get("val").device.type + mkldnn_device_op = _get_mkldnn_device_op(device_type) + input_size = conv_node.args[0].meta.get("val").shape + with graph.inserting_before(conv_node): + constant_args = [args[4], args[3], args[5], args[-1]] + packed_conv_op = mkldnn._convolution_pointwise.default + if is_transposed: + constant_args.insert(1, args[-2]) # output_padding + packed_conv_op = mkldnn._convolution_transpose_pointwise.default + + if not has_free_symbols(input_size): + packed_weight_node = mkldnn_device_op.pack_conv_weight( + graph, + is_transposed, + args[1], + constant_args, + input_size, + ) + else: + if is_transposed: + raise AssertionError("expected is_transposed to be False") + # For dynamic shape case, we need to pack weight in runtime. + packed_weight_node = args[1] + + packed_conv_inputs = ( + (args[0], packed_weight_node, args[2]) + + tuple(constant_args) + + ("none", [], "") + ) + packed_conv_node = graph.create_node( + "call_function", packed_conv_op, tuple(packed_conv_inputs) + ) + conv_node.replace_all_uses_with(packed_conv_node) + packed_conv_node.meta.update(conv_node.meta) + graph.erase_node(conv_node) + counters["inductor"]["mkldnn_conv_weight_pack_matcher_count"] += 1 + counters["inductor"]["mkldnn_conv_weight_pack_matcher_nodes"] += len( + match.nodes + ) + + @register_freezing_graph_pattern( + CallFunction(aten.mkldnn_rnn_layer.default, *_aten_mkldnn_rnn_layer_args), + extra_check=_is_packable_mkldnn_rnn_layer, + ) + def mkldnn_rnn_layer(match, *args, **kwargs): + def get_item(graph, node, index): + return graph.call_function(operator.getitem, (node, index)) + + graph = match.graph + lstm_node = match.output_node() + weight0, weight1 = args[1:3] + reverse = kwargs.get("reverse") + packed_lstm_op = aten.mkldnn_rnn_layer.default + hidden_size = args[9] + has_biases = args[11] + batch_first = args[13] + with graph.inserting_before(lstm_node): + packed_weight_op = mkldnn._reorder_mkldnn_rnn_layer_weight.default + packed_weight_inputs = ( + weight0, + weight1, + hidden_size, + reverse, + has_biases, + batch_first, + ) + packed_weight_node = graph.create_node( + "call_function", packed_weight_op, packed_weight_inputs, {}, "name" + ) + packed_weight_items = [ + get_item(graph, packed_weight_node, i) for i in range(2) + ] + pack_lstm_inputs = ( + args[0], + *packed_weight_items, + args[3], + args[4], + args[5], + args[6], + reverse, + *args[7:], + ) + + packed_lstm_node = graph.create_node( + "call_function", packed_lstm_op, args=pack_lstm_inputs + ) + lstm_node.replace_all_uses_with(packed_lstm_node) + packed_lstm_node.meta.update(lstm_node.meta) + graph.erase_node(lstm_node) + counters["inductor"]["mkldnn_rnn_weight_pack_matcher_count"] += 1 + counters["inductor"]["mkldnn_rnn_weight_pack_matcher_nodes"] += len( + match.nodes + ) + + @register_freezing_graph_pattern( + CallFunction( + aten.addmm.default, + Arg(), + Arg(), + Arg(), + beta=KeywordArg("beta"), + alpha=KeywordArg("alpha"), + ), + extra_check=_is_packable_linear, + pass_number=1, + ) + @register_freezing_graph_pattern( + CallFunction(aten.mm.default, Arg(), Arg()), + extra_check=_is_packable_linear, + pass_number=1, + ) + def linear(match, *args, **kwargs): + graph = match.graph + linear_node = match.output_node() + input = args[0] if linear_node.target is aten.mm.default else args[1] + bias = ( + None + if linear_node.target is aten.mm.default + or ( + linear_node.target is aten.addmm.default + and linear_node.kwargs.get("beta", 1.0) == 0.0 + ) + else args[0] + ) + weight = args[1] if linear_node.target is aten.mm.default else args[2] + device_type = input.meta.get("val").device.type + mkldnn_device_op = _get_mkldnn_device_op(device_type) + with graph.inserting_before(linear_node): + transpose_weight_node = graph.create_node( + "call_function", aten.permute.default, (weight, (1, 0)) + ) + weight_dtype = weight.meta.get("val").dtype + is_lp_weight = weight_dtype in ( + torch.bfloat16, + torch.float16, + ) + reduced_f32_matmul_enabled = ( + torch.backends.mkldnn.matmul.fp32_precision in ["bf16", "tf32"] # type: ignore[attr-defined] + ) + use_reduced_f32_for_fp32_weight = ( + reduced_f32_matmul_enabled and weight_dtype == torch.float32 + ) + compute_with_lp = is_lp_weight or use_reduced_f32_for_fp32_weight + batch_size = input.meta.get("val").shape[0] + packed_weight_node = mkldnn_device_op.pack_linear_weight( + graph, compute_with_lp, transpose_weight_node, batch_size + ) + packed_linear_node = mkldnn_device_op.pack_linear( + graph, compute_with_lp, batch_size, input, packed_weight_node, bias + ) + + linear_node.replace_all_uses_with(packed_linear_node) + packed_linear_node.meta.update(linear_node.meta) + graph.erase_node(linear_node) + counters["inductor"]["mkldnn_linear_weight_pack_matcher_count"] += 1 + counters["inductor"]["mkldnn_linear_weight_pack_matcher_nodes"] += len( + match.nodes + ) + + def _eliminate_duplicate_packed_nodes(gm): + """ + Combine packed weight nodes with the same inputs to reduce memory usage. + for example: + class Model(nn.Module): + def __init__(self) -> None: + super().__init__() + self.linear = nn.Linear(32, 32, bias=True) + + def forward(self, x): + return self.linear(self.linear(x)) + + the above's packed weight nodes are duplicate if two linear calls have same input size. + """ + if not (torch.backends.mkldnn.enabled and torch.backends.mkldnn.is_available()): + return gm + + packed_weight_ops = [ + torch._C._nn.mkldnn_reorder_conv2d_weight, + torch._C._nn.mkldnn_reorder_conv3d_weight, + mkldnn._reorder_convolution_transpose_weight, + mkldnn._reorder_linear_weight, + mkldnn._reorder_mkldnn_rnn_layer_weight, + ] + if torch._C.has_mkl: + packed_weight_ops.append(torch.ops.mkl._mkl_reorder_linear_weight) + + for node in gm.graph.nodes: + if node.target in packed_weight_ops and len(node.args[0].users) > 1: + for user_node in list(node.args[0].users.keys()): + if ( + user_node.target == node.target + and user_node != node + and user_node.args == node.args + ): + user_node.replace_all_uses_with(node) + gm.graph.erase_node(user_node) + + @functools.cache + def _mkldnn_fusion_init(): + # TODO: aarch64: enable op fusion for acl once it supports fused operators. Disabling it for now. + # Otherwise even the matmul or innerproduct can not be accelerated with acl + if ( + not torch.backends.mkldnn.enabled + or not torch.backends.mkldnn.is_available() + ): + return + + if not torch.ops.mkldnn._is_mkldnn_acl_supported(): + _register_unary_fusion() + _register_inplace_fusion() + _register_binary_unary_fusion() + _register_binary_fusion() + _register_quantization_lowerings() + + _register_woq_lowerings() + + @functools.cache + def _mkldnn_weight_pack_init(): + if torch.backends.mkldnn.enabled and torch.backends.mkldnn.is_available(): + _register_weight_pack_pass() + _recover_linear() + _register_int8_woq_concat_linear_pattern() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/node_runtime_estimation.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/node_runtime_estimation.py new file mode 100644 index 0000000000000000000000000000000000000000..e22cb330d58a67237aa21c0ab85def745702f205 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/node_runtime_estimation.py @@ -0,0 +1,457 @@ +""" +Node runtime estimation for overlap scheduling. +""" + +from __future__ import annotations + +import functools +import itertools +import operator +from functools import lru_cache +from typing import Any + +import torch +import torch.fx as fx +from torch._inductor import config +from torch._inductor.fx_passes.bucketing import ( + _resolve_group_name, + _schedulable_wait_node, +) +from torch._inductor.utils import clear_on_fresh_cache +from torch._logging import getArtifactLogger, trace_structured +from torch.fx.experimental.symbolic_shapes import optimization_hint +from torch.fx.operator_schemas import normalize_function + + +def _format_csv(headers: list[str], rows: list[list[str]]) -> str: + """Format data as CSV. Human-readable and easily parseable.""" + lines = [",".join(headers)] + for row in rows: + lines.append(",".join(str(v) for v in row)) + return "\n".join(lines) + + +def _get_collective_key(coll_node: fx.Node) -> str: + """Extract a unique key for a collective node including group info and tensor size.""" + from torch._inductor import fx_utils + + opt_args_kwargs = normalize_function( + coll_node.target, # type: ignore[arg-type] + args=coll_node.args, + kwargs=coll_node.kwargs, + normalize_to_only_use_kwargs=True, + ) + if opt_args_kwargs is None: + raise AssertionError("normalize_function returned None for collective node") + _, kwargs = opt_args_kwargs + raw_group_name = kwargs.get("group_name", None) + group_name = ( + _resolve_group_name(raw_group_name) if raw_group_name is not None else None + ) + group_size = kwargs.get("group_size", None) + + tensor_bytes: int | None = None + success, args, kw = fx_utils.get_fake_args_kwargs(coll_node) + if success: + + def extract_first_tensor_bytes(t: torch.Tensor) -> torch.Tensor: + nonlocal tensor_bytes + if tensor_bytes is None: + shape = [get_hint(dim) for dim in t.shape] + if all(s is not None for s in shape): + numel = functools.reduce(operator.mul, shape, 1) + tensor_bytes = numel * t.dtype.itemsize + return t + + torch.utils._pytree.tree_map_only( + torch.Tensor, extract_first_tensor_bytes, (args, kw) + ) + + return f"{coll_node.target} group_size:{group_size} group_name:{group_name} input_bytes:{tensor_bytes}" + + +def _get_collective_estimations(coll_node: fx.Node) -> tuple[float, float]: + """Get NCCL and Inductor analytical estimations for a collective node. + + Returns: (nccl_ms, inductor_ms) + """ + nccl_ms = ( + torch._inductor.comm_analysis.estimate_nccl_collective_runtime_from_fx_node( + coll_node, None, use_nccl_estimator=True + ) + ) + inductor_ms = ( + torch._inductor.comm_analysis.estimate_nccl_collective_runtime_from_fx_node( + coll_node, None, use_nccl_estimator=False + ) + ) + return nccl_ms, inductor_ms + + +# Setup logger for artifact logging +log = getArtifactLogger(__name__, "node_runtime_estimation") + + +# TODO: Consider using a distributed-aware cache or rank-local disk cache +# not using local cache because different ranks might write to it concurrently. +# solvable in future, potentially with workflow to seed cache +@clear_on_fresh_cache +@lru_cache +def _get_collective_cache() -> dict[str, float]: + """Get process-local cache for collective benchmarks.""" + return {} + + +def get_cached_runtime(key: str) -> float | None: + """Get cached runtime from process-local cache.""" + return _get_collective_cache().get(key) + + +def set_cached_runtime(key: str, value: float) -> None: + """Set cached runtime in process-local cache.""" + _get_collective_cache()[key] = value + + +def get_hint(x: int | torch.SymInt) -> int | None: + if isinstance(x, int): + return x + if not isinstance(x, torch.SymInt): + raise AssertionError(f"expected int or SymInt, got {type(x)}") + return x.hint if x.has_hint() else None + + +def can_benchmark_collective() -> bool: + """Check if we can benchmark collectives (not fake process group).""" + import torch.distributed as c10d + + if not c10d.is_initialized(): + return False + + pg = c10d.distributed_c10d._get_default_group() + if ( + torch.distributed.distributed_c10d.get_backend(pg) + == torch.distributed.distributed_c10d.Backend.FAKE + ): + return False + + return True + + +def _median(lst): + if len(lst) == 0: + raise AssertionError("expected non-empty list for median") + return torch.median(torch.tensor(lst)).item() + + +def _benchmark_collective_with_cuda_events_impl( + n: torch.fx.Node, + args: tuple[Any, ...], + kwargs: dict[str, Any], + nruns: int, +) -> float | None: + """ + Core benchmarking logic using CUDA events and barriers. + Returns runtime in ms or None on failure. + """ + from torch._dynamo.testing import rand_strided + + # Convert FakeTensors to real tensors before benchmarking + def to_real(t: torch.Tensor) -> torch.Tensor: + shape = [get_hint(dim) for dim in t.shape] + stride = [get_hint(s) for s in t.stride()] + + if any(s is None for s in itertools.chain(shape, stride)): + # This should not happen, as can_benchmark_collective checks for unbacked + raise ValueError("Cannot convert tensor with symbolic dimensions") + + return rand_strided(shape, stride, device=t.device, dtype=t.dtype) # type: ignore[arg-type] + + args, kwargs = torch.utils._pytree.tree_map_only( + torch.Tensor, + to_real, + (args, kwargs), + ) + + args, kwargs = torch.utils._pytree.tree_map_only( + torch.SymInt, + lambda s: optimization_hint(s, fallback=config.unbacked_symint_fallback), + (args, kwargs), + ) + + # Warmup: call collective once and wait + torch.accelerator.synchronize() + result = n.target(*args, **kwargs) # type: ignore[operator] + torch.ops._c10d_functional.wait_tensor(result) + torch.accelerator.synchronize() + + # Benchmark with CUDA events + comm_times = [] + for _ in range(nruns): + start_evt = torch.Event(enable_timing=True) + end_evt = torch.Event(enable_timing=True) + + start_evt.record() + result = n.target(*args, **kwargs) # type: ignore[operator] + torch.ops._c10d_functional.wait_tensor(result) + end_evt.record() + end_evt.synchronize() + + comm_times.append(start_evt.elapsed_time(end_evt)) + + return _median(comm_times) + + +def benchmark_collective_with_cuda_events( + n: torch.fx.Node, + nruns: int = 2, +) -> tuple[float | None, str]: + """ + Benchmark collective with CUDA events. Returns (runtime_ms, cache_key) or (None, "") on failure. + """ + # context manager not allowed with profiler. + with torch.utils._python_dispatch._disable_current_modes(): + return benchmark_collective_with_cuda_events_impl(n, nruns) + + +def benchmark_collective_with_cuda_events_impl( + n: torch.fx.Node, + nruns: int = 3, +) -> tuple[float | None, str]: + """ + Benchmark collective with CUDA events. Returns (runtime_ms, cache_key) or (None, "") on failure. + """ + from torch._inductor import fx_utils + from torch.distributed.distributed_c10d import _get_group_size_by_name + + # Early check: can we actually run collectives? + if not can_benchmark_collective(): + return None, "" + + success, args, kwargs = fx_utils.get_fake_args_kwargs(n) + + opt_args_kwargs = normalize_function( + n.target, # type: ignore[arg-type] + args=n.args, + kwargs=n.kwargs, + normalize_to_only_use_kwargs=True, + ) + if opt_args_kwargs is None: + raise AssertionError("normalize_function returned None for collective node") + group_name = _resolve_group_name(opt_args_kwargs[1]["group_name"]) + group_size = _get_group_size_by_name(group_name) + + if not success: + return None, "" + + # Extract actual input size in BYTES (first tensor argument) + actual_bytes: int | None = None + + def extract_tensor_info(t: torch.Tensor) -> torch.Tensor: + nonlocal actual_bytes + if actual_bytes is None: + shape = [get_hint(dim) for dim in t.shape] + if any(s is None for s in shape): + return t + + total_elems = 1 + for dim in shape: + if dim is None: + raise AssertionError(f"expected non-None dim, got {dim}") + total_elems *= dim + + actual_bytes = total_elems * t.dtype.itemsize + else: + # out-variants (e.g. all_gather_into_tensor_out) can have multiple tensors + pass + return t + + torch.utils._pytree.tree_map_only(torch.Tensor, extract_tensor_info, (args, kwargs)) + + if actual_bytes is None: + return None, "" + + # Cache key by BYTES (dtype-agnostic) + key = f"{n.target}: ({group_size} group size, {actual_bytes} bytes)" + + # Check cache + if (cached := get_cached_runtime(key)) is not None: + return cached, key + + # Benchmark using CUDA events with actual args/kwargs + runtime = _benchmark_collective_with_cuda_events_impl(n, args, kwargs, nruns) + + if runtime is None: + return None, key + + # Cache the result + set_cached_runtime(key, runtime) + return runtime, key + + +def _log_compute_estimations( + compute_nodes: list[fx.Node], + benchmarked_estimations: list[float], + analytical_estimations: list[float], +) -> None: + """Log compute node runtime estimations comparing benchmarked vs analytical.""" + import torch.utils._pytree as pytree + from torch._inductor.fx_utils import count_flops_fx + from torch.utils._dtype_abbrs import dtype_abbrs + + def _node_summary(n: fx.Node) -> str: + ret = str(n) + for arg in pytree.arg_tree_leaves(n.args, n.kwargs): + if not isinstance(arg, torch.fx.Node): + continue + if "val" in arg.meta: + t = arg.meta["val"] + if isinstance(t, torch.Tensor): + ret += f" {dtype_abbrs[t.dtype]}{tuple(t.shape)}" + elif isinstance(t, torch.SymInt): + ret += f" SymInt({t})" + return ret + + headers = [ + "Node", + "Benchmarked Est(us)", + "Analytical Est(us)", + "Diff(ratio)", + "Diff(us)", + "Flops", + ] + + def _fmt(v: object) -> str: + if isinstance(v, torch.types.py_sym_types): + if v.node.has_hint(): + return f"{v}({v.node.hint:.4f})" + return str(v) + return f"{v:.4f}" + + rows = [ + [ + _node_summary(node), + _fmt(est_b * 1e3), + _fmt(est_a * 1e3), + _fmt((est_a / est_b) if est_b > 0 else 0), + _fmt((est_a - est_b) * 1e3), + str(count_flops_fx(node)), + ] + for node, est_b, est_a in zip( + compute_nodes, benchmarked_estimations, analytical_estimations + ) + ] + + log_str = _format_csv(headers, rows) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "fx_compute_nodes_runtime_estimation", + "encoding": "string", + }, + payload_fn=lambda: log_str, + ) + + +def _log_graph_collective_benchmarks(gm: fx.GraphModule, artifact_name: str) -> None: + collective_nodes = [] + collective_keys = [] + benchmarked = [] + + for node in gm.graph.nodes: + if _schedulable_wait_node(node): + start = node.args[0] + collective_nodes.append(start) + collective_keys.append(_get_collective_key(start)) + benchmarked_ms, _ = benchmark_collective_with_cuda_events(start, nruns=5) + benchmarked.append(benchmarked_ms if benchmarked_ms else 0.0) + + if collective_nodes: + world_size = ( + torch.distributed.get_world_size() + if torch.distributed.is_initialized() + else 1 + ) + _log_collective_benchmarks( + collective_nodes, + collective_keys, + benchmarked, + world_size, + artifact_name, + ) + + +def _log_collective_benchmarks( + collective_nodes: list[fx.Node], + collective_keys: list[str] | None = None, + benchmarked_medians: list[float] | None = None, + world_size: int | None = None, + artifact_name: str = "fx_collectives_analytical_estimation", +) -> None: + """Log collective estimations for tlparse. Includes benchmarks if provided.""" + if world_size is None: + world_size = ( + torch.distributed.get_world_size() + if torch.distributed.is_initialized() + else 1 + ) + + has_benchmarks = benchmarked_medians is not None + + if has_benchmarks: + headers = [ + "Collective Key", + "Benchmarked(ms)", + "NCCL Est(ms)", + "Inductor Est(ms)", + "NCCL Diff(ratio)", + "Inductor Diff(ratio)", + ] + else: + headers = [ + "Collective Key", + "NCCL Est(ms)", + "Inductor Est(ms)", + ] + + rows = [] + for i, coll_node in enumerate(collective_nodes): + key = collective_keys[i] if collective_keys else _get_collective_key(coll_node) + nccl_ms, inductor_ms = _get_collective_estimations(coll_node) + + if benchmarked_medians is not None: + benchmarked_ms = benchmarked_medians[i] + nccl_diff_pct = (nccl_ms / benchmarked_ms) if benchmarked_ms > 0 else 0 + inductor_diff_pct = ( + (inductor_ms / benchmarked_ms) if benchmarked_ms > 0 else 0 + ) + rows.append( + [ + key, + f"{benchmarked_ms:.4f}", + f"{nccl_ms:.4f}", + f"{inductor_ms:.4f}", + f"{nccl_diff_pct:.2f}", + f"{inductor_diff_pct:.2f}", + ] + ) + else: + rows.append( + [ + key, + f"{nccl_ms:.4f}", + f"{inductor_ms:.4f}", + ] + ) + + log_str = f"# World size: {world_size}\n" + log_str += _format_csv(headers, rows) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": artifact_name, + "encoding": "string", + }, + payload_fn=lambda: log_str, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/numeric_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/numeric_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..486d047852b8f34cc7b2ef4acf257538f41d414b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/numeric_utils.py @@ -0,0 +1,213 @@ +# mypy: allow-untyped-defs +import gc +import logging +import os +import random +import traceback + +import numpy + +import torch +import torch.optim as optim +from torch.utils._ordered_set import OrderedSet + +from .. import config + + +logger: logging.Logger = logging.getLogger(__name__) + +MAIN_RANDOM_SEED = 1337 + +# Set the CUBLAS_WORKSPACE_CONFIG environment variable +os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8" + + +# If the two forward functions involve any non-deterministic operations, +# such as certain types of parallelism or asynchronous execution, +# this can also lead to different outputs. +def set_deterministic() -> None: + """Make torch manual seed deterministic.""" + + torch.manual_seed(MAIN_RANDOM_SEED) + random.seed(MAIN_RANDOM_SEED) + numpy.random.seed(MAIN_RANDOM_SEED) + torch.use_deterministic_algorithms(True) + + +def clean_memory() -> None: + """Clean memory to avoid OOM.""" + gc.collect() + torch.cuda.empty_cache() + + +# We compare the numerical results before and after pre/post grad fx passes +# transformation to make sure the numerical results are the same. +def compare_dict_tensors(dict_base, dict_control, precision): + if len(OrderedSet(dict_base.keys())) != len(OrderedSet(dict_control.keys())): + logger.warning("Mismatch keys found before and after pre/post grad fx passes.") + logger.debug("keys before pre/post grad fx passes %s", dict_base.keys()) + logger.debug("keys after pre/post grad fx passes %s", dict_control.keys()) + return False + is_allclose = True + for key in dict_base: + if key not in dict_control: + logger.warning( + "Mismatch parameter name %s does not exist after pre/post grad fx passes", + key, + ) + # Some parameters have `None`, and not every param has a valid .grad field, we skip them + if dict_base[key] is None or dict_control[key] is None: + continue + if not torch.allclose( + dict_base[key], + dict_control[key], + rtol=precision, + atol=precision, + equal_nan=True, + ): + logger.warning( + "Mismatch parameter values found before and after pre/post grad fx passes." + ) + logger.debug("value before pre/post grad fx passes %s", dict_base[key]) + logger.debug("value after pre/post grad fx passes %s", dict_control[key]) + is_allclose = False + return is_allclose + + +def compare_tuple_tensors(tuple_base, tuple_control, precision): + if len(tuple_base) != len(tuple_control): + logger.warning( + "Mismatch fw output length. before transformation: %s, after transformation: %s", + len(tuple_base), + len(tuple_control), + ) + return False + is_allclose = True + for i in range(len(tuple_base)): + # Some parameters have `None`, we skip them + if tuple_base[i] is None or tuple_control[i] is None: + continue + if not torch.allclose( + tuple_base[i], + tuple_control[i], + rtol=precision, + atol=precision, + equal_nan=True, + ): + logger.debug( + "forward output before pre/post grad fx passes %s", tuple_base[i] + ) + logger.debug( + "forward output after pre/post grad fx passes %s", tuple_control[i] + ) + is_allclose = False + return is_allclose + + +def compare_parameters(model_base, model_control, precision): + return compare_dict_tensors( + dict(model_base.named_parameters()), + dict(model_control.named_parameters()), + precision, + ) + + +def compare_forward_output(pred_base, pred_control, precision): + return compare_tuple_tensors( + pred_base, + pred_control, + precision, + ) + + +def compare_gradients(model_base, model_control, precision): + grad_base = {key: param.grad for key, param in model_base.named_parameters()} + grad_pt2 = {key: param.grad for key, param in model_control.named_parameters()} + return compare_dict_tensors( + grad_base, + grad_pt2, + precision, + ) + + +def run_model( + model_base, model_control, model_input, num_iterations=10, precision=1e-4 +): + clean_memory() + for i in range(num_iterations): + logger.info("start %s iteration", i) + set_deterministic() + pred_base = model_base(*model_input) + set_deterministic() + pred_control = model_control(*model_input) + + res = compare_parameters(model_base, model_control, precision) + logger.info("compare parameters. Numerical result : %s", res) + + res = compare_forward_output(pred_base, pred_control, precision) + logger.info("compare loss/predict. Numerical result : %s", res) + # tensor may not have a grad_fn + try: + _ = pred_base[0].sum().backward(retain_graph=True) + _ = pred_control[0].sum().backward(retain_graph=True) + res = compare_gradients(model_base, model_control, precision) + logger.info("compare param grad. Numerical result : %s", res) + except Exception: + logger.exception("Exception when comparing gradients") + traceback.print_exc() + + if config.fx_passes_numeric_check["requires_optimizer"]: + try: + optimizer_base = optim.SGD( + [param for name, param in model_base.named_parameters()], lr=0.01 + ) + optimizer_base.step() + + optimizer_control = optim.SGD( + [param for name, param in model_control.named_parameters()], lr=0.01 + ) + optimizer_control.step() + + res = compare_parameters(model_base, model_control, precision) + logger.info( + "compare parameters with optimizer added. Numerical result : %s", + res, + ) + except Exception: + logger.exception( + "Exception when optimizer is added to check parameter names" + ) + traceback.print_exc() + else: + logger.warning( + "no parameter with optimizer to compare with length %s before transformation" + " and the length %s after transformation", + len(dict(model_base.named_parameters())), + len(dict(model_control.named_parameters())), + ) + + +def numeric_check_if_enabled( + gm_before_fx_passes, + gm_after_fx_passes, + example_inputs, + num_iterations, + precision, +): + # need to topo-sort graphmodule before we run the model, + # otherwise it may fail as refer before def + # fail silently in order not to block the model run + try: + with torch.autograd.set_detect_anomaly(True): + run_model( + gm_before_fx_passes, + gm_after_fx_passes, + example_inputs, + num_iterations=num_iterations, + precision=precision, + ) + except Exception as e: + logger.warning( + "Runtime numeric check failed in pre grad fx passes with error: %s", e + ) + traceback.print_exc() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/overlap_manual_scheduling.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/overlap_manual_scheduling.py new file mode 100644 index 0000000000000000000000000000000000000000..570c2d03f424bebbd0f823a7bddc3bd522d00d67 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/overlap_manual_scheduling.py @@ -0,0 +1,644 @@ +from __future__ import annotations + +import heapq +from collections import Counter, defaultdict +from typing import Any, TYPE_CHECKING + +import torch +import torch.fx as fx +from torch._inductor.fx_passes.bucketing import ( + _get_collective_node_from_wait, + _schedulable_wait_node, + BucketMode, + has_mergeable_all_gather_convert_dtype, + is_all_gather_into_tensor as is_all_gather, + is_all_reduce_tensor, + is_fsdp_all_gather, + is_fsdp_reduce_scatter, + is_reduce_scatter_tensor as is_reduce_scatter, + merge_all_gather_bucket, + merge_all_reduce_bucket, + merge_reduce_scatter_bucket, +) +from torch._inductor.fx_passes.overlap_preserving_bucketer import ( + get_full_bucket_key, + OverlapPreservingBucketer, +) +from torch._inductor.fx_passes.overlap_scheduling import ( + CollectiveInfo, + is_compute_node, + OverlapScheduler, +) +from torch.utils._ordered_set import OrderedSet + +from .graph_view import get_subgraph_by_path, GraphView, make_graph_view + + +if TYPE_CHECKING: + from collections.abc import Callable + +import logging + + +logger = logging.getLogger(__name__) + + +def _collect_nodes_must_be_after(node: fx.Node) -> list[fx.Node]: + """BFS forward collecting node and its transitive users with no external inputs.""" + result: list[fx.Node] = [node] + result_set: OrderedSet[fx.Node] = OrderedSet([node]) + i = 0 + while i < len(result): + for user in result[i].users: + if user not in result_set and all( + inp in result_set for inp in user.all_input_nodes + ): + result_set.add(user) + result.append(user) + i += 1 + return result + + +def _collect_nodes_must_be_before( + node: fx.Node, node_positions: dict[fx.Node, int] +) -> list[fx.Node]: + """BFS backward collecting node and its non-placeholder dependencies, topo-sorted.""" + visited: OrderedSet[fx.Node] = OrderedSet() + queue = [node] + while queue: + cur = queue.pop() + if cur in visited or cur.op == "placeholder": + continue + visited.add(cur) + queue.extend(cur.all_input_nodes) + return sorted(visited, key=lambda n: node_positions[n]) + + +def _bucket_trace_inputs( + coll_node: fx.Node, node_in: object, group_name_arg: int +) -> list[fx.Node]: + if not isinstance(node_in, fx.Node): + raise AssertionError(f"expected node input to be a Node, got {type(node_in)}") + inputs = [node_in] + + group_name = coll_node.args[group_name_arg] + if isinstance(group_name, fx.Node): + inputs.append(group_name) + return inputs + + +def _all_gather_bucket_trace_inputs(coll_node: fx.Node) -> list[fx.Node]: + node_in: object = coll_node.args[0] + # The dtype conversion is erased by the all-gather bucket trace, so anchor + # insertion on the tensor that remains as a graph input to the bucket. + if has_mergeable_all_gather_convert_dtype(coll_node): + if not isinstance(node_in, fx.Node): + raise AssertionError( + f"expected node input to be a Node, got {type(node_in)}" + ) + node_in = node_in.args[0] + return _bucket_trace_inputs(coll_node, node_in, group_name_arg=2) + + +def _reduce_scatter_bucket_trace_inputs(coll_node: fx.Node) -> list[fx.Node]: + return _bucket_trace_inputs(coll_node, coll_node.args[0], group_name_arg=3) + + +def _all_reduce_bucket_trace_inputs(coll_node: fx.Node) -> list[fx.Node]: + # all_reduce(tensor, reduce_op, group_name): tensor at 0, group_name at 2. + return _bucket_trace_inputs(coll_node, coll_node.args[0], group_name_arg=2) + + +def _move_wait_users_after_latest_inputs( + graph: fx.Graph, + replacements: dict[fx.Node, fx.Node], + replaced_users: dict[fx.Node, list[fx.Node]], +) -> None: + node_positions = {n: i for i, n in enumerate(graph.nodes)} + initial_users: OrderedSet[fx.Node] = OrderedSet() + for old_out, new_out in replacements.items(): + if new_out not in node_positions: + continue + for user in replaced_users.get(old_out, []): + if ( + user in node_positions + and user.op != "output" + and node_positions[user] < node_positions[new_out] + ): + initial_users.add(user) + + pending = sorted(initial_users, key=lambda n: node_positions[n]) + queued = OrderedSet(pending) + while pending: + node = pending.pop(0) + queued.discard(node) + + node_positions = {n: i for i, n in enumerate(graph.nodes)} + if node not in node_positions: + continue + + input_nodes = [inp for inp in node.all_input_nodes if inp in node_positions] + if not input_nodes: + continue + + latest_input = max(input_nodes, key=lambda n: node_positions[n]) + if node_positions[node] >= node_positions[latest_input]: + continue + + # Replacing old waits can leave existing consumers before the new bucket + # outputs. Pull each affected consumer after its latest input. + latest_input.append(node) + node_positions = {n: i for i, n in enumerate(graph.nodes)} + for user in node.users: + if user in node_positions and user.op != "output" and user not in queued: + queued.add(user) + pending.append(user) + + +def _move_overlap_nodes( + graph: fx.Graph, + overlap_deps: dict[fx.Node, OrderedSet[fx.Node]], + bucketed_node_types: dict[fx.Node, str], +) -> None: + if not overlap_deps: + return + + rs_defer: dict[fx.Node, list[fx.Node]] = defaultdict(list) + ag_prefetch: dict[fx.Node, list[fx.Node]] = defaultdict(list) + + for target, sources in overlap_deps.items(): + for source in sources: + source_type = bucketed_node_types.get(source, "") + if source_type.startswith( + ("bucketed_reduce_scatter", "bucketed_all_reduce") + ): + rs_defer[target].append(source) + elif source_type.startswith("bucketed_all_gather"): + ag_prefetch[target].append(source) + + node_positions = {n: i for i, n in enumerate(graph.nodes)} + + for rs_wait, rs_starts in rs_defer.items(): + latest_rs_start = max(rs_starts, key=lambda n: node_positions[n]) + node_insert_after = latest_rs_start + for node in _collect_nodes_must_be_after(rs_wait): + node_insert_after.append(node) + node_insert_after = node + + # Recompute positions after RS moves + node_positions = {n: i for i, n in enumerate(graph.nodes)} + + for ag_wait, ag_prefetch_starts in ag_prefetch.items(): + ag_wait_pos = node_positions[ag_wait] + sorted_starts = sorted(ag_prefetch_starts, key=lambda n: node_positions[n]) + for ag_start in sorted_starts: + if node_positions[ag_start] < ag_wait_pos: + continue + for node in _collect_nodes_must_be_before(ag_start, node_positions): + ag_wait.prepend(node) + + +class ManualOverlapPreservingBucketer(OverlapPreservingBucketer): + """ + Buckets collective operations based on user specifications. + The actual bucket happens in bucket_collectives, where all-gathers/reduce-scatters in + `nodes` will be buckted one single all-gather/reduce-scatter. + """ + + def __init__( + self, + *args: Any, + **kwargs: Any, + ): + super().__init__(*args, **kwargs) + self.node_to_wait_map: dict[fx.Node, fx.Node] = defaultdict() + # Maps bucketed nodes to their type string, scoped to this bucketer + # instance so metadata doesn't leak across separate invocations. + self.bucketed_node_types: dict[fx.Node, str] = {} + + def _bucket_group(self, coll_nodes: list[fx.Node]) -> None: + if len(coll_nodes) <= 0: + raise AssertionError("bucketed coll_nodes should have nonzero node") + + # Graph order changes after each bucket, so positions must be fresh. + node_positions = {n: i for i, n in enumerate(self.graph.nodes)} + waits = [self.collective_info[n].wait_node for n in coll_nodes] + first_wait = min(waits, key=lambda w: node_positions[w]) + first = min(coll_nodes, key=lambda n: node_positions[n]) + replaced_users = {wait: list(wait.users) for wait in waits} + + if is_all_gather(first): + bucket_trace_inputs = _all_gather_bucket_trace_inputs + merge_bucket = merge_all_gather_bucket + node_type = "bucketed_all_gather" + elif is_reduce_scatter(first): + bucket_trace_inputs = _reduce_scatter_bucket_trace_inputs + merge_bucket = merge_reduce_scatter_bucket + node_type = "bucketed_reduce_scatter" + elif is_all_reduce_tensor(first): + bucket_trace_inputs = _all_reduce_bucket_trace_inputs + merge_bucket = merge_all_reduce_bucket + node_type = "bucketed_all_reduce" + else: + raise ValueError( + "bucket non all_gather/reduce_scatter/all_reduce node is not supported" + ) + + # coll_nodes order is used for tensor packing and may differ from + # graph order. Insert the bucketed collective after its latest input. + bucket_inputs = [inp for n in coll_nodes for inp in bucket_trace_inputs(n)] + anchor = max([first, *bucket_inputs], key=lambda n: node_positions[n]) + next_node = anchor.next + coll_node_set = OrderedSet(coll_nodes) + while next_node in coll_node_set: + next_node = next_node.next + # Use the earliest old wait unless it precedes the bucket insertion + # point; otherwise keep wait/output nodes with the traced bucket. + wait_insertion_point = max( + (first_wait, next_node), key=lambda n: node_positions[n] + ) + + new_nodes, replacements = merge_bucket( + self.graph, + coll_nodes, + wait_insertion_point=wait_insertion_point, + insert_before=next_node, + mode=self.bucket_mode, + ) + _move_wait_users_after_latest_inputs(self.graph, replacements, replaced_users) + + logger.debug(f"bucketing nodes: {coll_nodes} into {new_nodes}") # noqa: G004 + + # Identify the new wait(s) and their collective start in a single pass + wait_to_start = { + n: start + for n in new_nodes + if (start := _get_collective_node_from_wait(n)) is not None + } + if len(wait_to_start) < 1: + raise AssertionError( + f"Expected at least one new wait, got none in {new_nodes}" + ) + new_waits = list(wait_to_start) + new_start: fx.Node = wait_to_start[new_waits[0]] + # Use last wait as the canonical wait for scheduling (same node when len == 1) + new_wait = new_waits[-1] + + # Track bucketed node types on this bucketer instance so it doesn't leak + # when the same graph is processed by multiple ManualOverlapScheduler + # invocations (e.g. separate forward and backward passes). + wait_set = OrderedSet(new_waits) + for n in new_nodes: + if n in wait_set: + self.bucketed_node_types[n] = node_type + "_wait" + self.node_to_wait_map[n] = new_wait + elif n is new_start: + self.bucketed_node_types[n] = node_type + + def _split_independent_collectives( + self, coll_nodes: OrderedSet[fx.Node], scope_nodes: list[fx.Node] + ) -> list[list[fx.Node]]: + """Partition same-key collectives so no bucket contains a collective that + depends on another member's result. + + Bucketing fuses collectives into one op: inputs are concatenated before + the fused collective and outputs split after. If collective B's input + depends on collective A's output (A's wait), fusing A and B makes the + merged collective's input depend on its own output -- a graph cycle that + later fails region topological sort. This arises e.g. in loss-parallel + cross-entropy, which emits a sumexp and a result sum-all_reduce on the + same (group, reduce_op, dtype) key where result depends on sumexp. + + Each collective is placed in the bucket equal to the longest chain of + same-key collectives ending at it (its Mirsky level). Collectives at the + same level are mutually independent, so grouping by level gives the + minimum number of dependency-free buckets. Levels are computed with a + single topological forward pass over ``scope_nodes`` that propagates, + along real graph edges, the deepest same-key chain reaching each node -- + O(len(scope_nodes)) rather than O(len(coll_nodes)^2) pairwise ancestor + queries. This is exact because same-key collectives in one bucketing + scope depend on each other only through in-scope nodes. + """ + wait_to_start = {self.collective_info[c].wait_node: c for c in coll_nodes} + + # ``reach[node]`` = deepest same-key collective chain in node's cone; + # ``level[c]`` = that chain length including c (its bucket index + 1). + reach: dict[fx.Node, int] = {} + level: dict[fx.Node, int] = {} + for node in sorted(scope_nodes, key=lambda n: self.node_idx[n]): + incoming = max( + (reach.get(inp, 0) for inp in node.all_input_nodes), default=0 + ) + node_reach = incoming + if node in coll_nodes: + level[node] = incoming + 1 + # A collective's chain becomes reachable through its wait (its result). + start = wait_to_start.get(node) + if start is not None: + node_reach = max(node_reach, level[start]) + reach[node] = node_reach + + buckets: dict[int, list[fx.Node]] = defaultdict(list) + for c in coll_nodes: + buckets[level[c]].append(c) + return [buckets[lvl] for lvl in sorted(buckets)] + + def manual_bucket_collectives(self, nodes: list[fx.Node]) -> None: + """ + Bucket all all-gather/reduce-scatter nodes from nodes into one all-gather/reduce-scatter. + """ + # Filter out valid collectives + collectives = [n for n in nodes if n in self.collective_info] + if collectives == []: + return + grouped_collectives: dict[object, OrderedSet[fx.Node]] = defaultdict(OrderedSet) + for node in collectives: + if not ( + is_fsdp_all_gather(node, self.node_ancestors) + or is_fsdp_reduce_scatter(node) + or is_all_reduce_tensor(node) + ): + continue + key = get_full_bucket_key(node, "custom_ops") + if key is not None: + grouped_collectives[key].add(node) + + # Split each key-group into dependency-free sub-buckets so fusing never + # makes a bucketed collective's input depend on its own output. + sub_buckets: list[list[fx.Node]] = [] + for key, key_nodes in grouped_collectives.items(): + sub_buckets.extend(self._split_independent_collectives(key_nodes, nodes)) + + for sub_bucket in sub_buckets: + self._bucket_group(sub_bucket) + + +class ManualOverlapScheduler(OverlapScheduler): + """ + Scheduler that manual buckets and reorders collective nodes based on module_bucket_plans + """ + + def __init__( + self, + gm: fx.GraphModule, + module_bucket_plans: list[list[str] | str], + insert_overlap_deps: bool, + module_stack_fn: Callable[[fx.Node], list[tuple[str, type[Any]]]] | None = None, + bucket_mode: BucketMode | None = None, + ): + # Manual overlap historically used "custom_ops" mode for bucketing + bucket_mode = bucket_mode or "custom_ops" + super().__init__( + gm, + max_in_flight_gb=0.0, + max_compute_pre_fetch=0, + collective_bucketing=True, + insert_overlap_deps=insert_overlap_deps, + compute_overlap_multipler=0.0, + max_coll_distance=0, + # ManualOverlapScheduler doesn't use runtime estimates (it + # hardcodes estimated_time_ms=0 in _identify_collectives and + # schedules purely from module_bucket_plans). Providing a + # no-op estimator avoids the analytical NCCL path, which + # crashes in compile-on-one-rank graphs where group_name is + # an FX Node and the distributed runtime may not be available. + custom_runtime_estimation=lambda node, size: 0.0, + collective_estimator="analytical", + max_memory_increase_gb=None, + max_memory_increase_ratio=None, + bucket_mode=bucket_mode, + ) + self.module_bucket_plans = module_bucket_plans + self.nodes_in_subgraph: list[list[fx.Node]] = [] + + self.bucketer = ManualOverlapPreservingBucketer( + graph=self.graph, + collective_info=self.collective_info, + scheduled=OrderedSet(self.graph.nodes), + bucket_mode=bucket_mode, + ) + self.insert_overlap_deps = insert_overlap_deps + + self.module_stack_fn = module_stack_fn + + def _identify_collectives(self) -> None: + """Identify all collective operations.""" + for node in self.nodes: + if _schedulable_wait_node(node): + start = node.args[0] + info = CollectiveInfo( + start_node=start, + wait_node=node, + size_bytes=0, + estimated_time_ms=0, + exposed_time_ms=0, + ) + self.collective_info[start] = info + self.wait_to_start[node] = start + self.unscheduled_collectives.add(start) + + def _add_to_ready_queue(self, node: fx.Node) -> None: + """Manual scheduling uses single queue ordered by original node index.""" + heapq.heappush(self.on_path_ready, (self.node_idx[node], node)) + + def run(self) -> torch.fx.GraphModule: + """Entry point to run the manual bucket algorithm""" + # Bucket collectives in each bucket_module + self._manual_bucket_collectives() + + # Reorder collectives with last/next bucket_module + self._manual_reorder_graph() + + return self.gm + + def _manual_reorder_graph(self) -> None: + """ + Reorder nodes in the FX graph to enforce manual overlap dependencies. + + forward graph (all-gathers only): + modules are processed in order: module 0, 1, 2, ... + + before reordering: + ag_start_0 -> ag_wait_0 -> compute_0 -> ag_start_1 -> ag_wait_1 -> compute_1 -> ... + + Reordering prefetches module i+1's parameters while computing module i + It adds dependencies: ag_wait_i should depend on ag_start_(i+1) + This enforces ag_start_(i+1) to happen before ag_wait_i so it overlaps with module i's compute + + after reordering: + ag_start_0 -> ag_start_1 -> ag_wait_0 -> compute_0 -> ag_wait_1 -> compute_1 -> ... + + backward graph (all-gathers and reduce-scatters): + modules are processed in reverse order: module N, N-1, N-2, ... + + before reordering: + ag_start_N -> ag_wait_N -> compute_N -> rs_start_N -> rs_wait_N -> ... + + For all-gathers, prefetch module i-1's parameters while computing module i + Adds dependencies: ag_wait_i should depend on ag_start_(i-1) + So ag_start_(i-1) overlaps with module i's compute + + For reduce-scatters, defer rs_wait_i to happen after rs_start_(i-1) + Adds dependencies: rs_wait_i should depend on rs_start_(i-1) + So rs_start_i overlaps with module i-1's compute + + """ + delayed_rs_wait_nodes: list[fx.Node] = [] + current_rs_start_nodes: list[fx.Node] = [] + overlap_deps: dict[fx.Node, OrderedSet[fx.Node]] = defaultdict(OrderedSet) + + # Re-initialize after graph modification in _manual_bucket_collectives + self.node_idx = {n: i for i, n in enumerate(self.nodes)} + self.on_path_ready = [] + self.scheduled = OrderedSet() + for node in self.nodes: + if self.in_degree[node] == 0: + self._add_to_ready_queue(node) + + # schedule reduce scatter normally in self._schedule + while self.on_path_ready: + _, node = heapq.heappop(self.on_path_ready) + node_type = self.bucketer.bucketed_node_types.get(node, "") + + if node in self.scheduled: + continue + + if node_type in ("bucketed_reduce_scatter", "bucketed_all_reduce"): + # Collect grad-reduction start nodes (pre_bucket_rs and rs, or + # the HSDP/DDP replicate all_reduce). + current_rs_start_nodes.append(node) + + elif node_type in ( + "bucketed_reduce_scatter_wait", + "bucketed_all_reduce_wait", + ): + # When we see a wait node from a new RS/AR, flush delayed waits + # with dependencies on previously collected start nodes + if current_rs_start_nodes: + for delayed in delayed_rs_wait_nodes: + for rs_start in current_rs_start_nodes: + overlap_deps[delayed].add(rs_start) + delayed_rs_wait_nodes.clear() + current_rs_start_nodes.clear() + delayed_rs_wait_nodes.append(node) + + self._schedule(node) + + self.scheduled = OrderedSet(reversed(list(self.scheduled))) + picked_ag: list[fx.Node] = [] + last_compute: fx.Node | None = None + + for node in self.scheduled: + node_type = self.bucketer.bucketed_node_types.get(node, "") + if node_type == "bucketed_all_gather": + picked_ag.append(node) + continue + + if node_type == "bucketed_all_gather_wait": + # Connect corresponding all_gather_wait -> all_gather edges + if picked_ag: + for ag in picked_ag: + overlap_deps[self.bucketer.node_to_wait_map[node]].add(ag) + picked_ag.clear() + if is_compute_node(node): + last_compute = node + + if last_compute is not None: + if not any( + self.node_ancestors.is_ancestor(ag, last_compute) for ag in picked_ag + ): + for ag in picked_ag: + overlap_deps[last_compute].add(ag) + + _move_overlap_nodes(self.graph, overlap_deps, self.bucketer.bucketed_node_types) + self.graph.lint() + + if self.insert_overlap_deps: + from torch._inductor.fx_passes.control_dependencies import ( + preserve_node_ordering, + ) + + preserve_node_ordering(self.graph, overlap_deps) + + def _manual_bucket_collectives(self) -> None: + """Bucket nodes in each module_bucket from module_bucket_plans.""" + self._obtain_nodes_in_subgraph() + for i, nodes in enumerate(self.nodes_in_subgraph): + self.bucketer.manual_bucket_collectives(nodes=nodes) + + self.graph.lint() + self.nodes = list(self.graph.nodes) + self.in_degree = Counter(user for node in self.nodes for user in node.users) + + def _schedule(self, node: fx.Node) -> None: + """Schedule a node.""" + if node in self.scheduled: + raise AssertionError(f"node already scheduled: {node}") + if not all(n in self.scheduled for n in node.all_input_nodes): + raise AssertionError(f"all input nodes must be scheduled before {node}") + self.scheduled.add(node) + for user in node.users: + self.in_degree[user] -= 1 + if self.in_degree[user] == 0: + self._add_to_ready_queue(user) + + def _obtain_nodes_in_subgraph(self) -> None: + """ + Obtain nodes in each subgraph from module_bucket_plans + """ + graph_view: GraphView | None = make_graph_view(self.graph, self.module_stack_fn) + if graph_view is None: + return + + for module in self.module_bucket_plans: + subgraph_view = get_subgraph_by_path(graph_view, module) + self.nodes_in_subgraph.append(subgraph_view) + + all_subgraph_nodes = [ + node for sublist in self.nodes_in_subgraph for node in sublist + ] + unique_subgraph_nodes = list(OrderedSet(all_subgraph_nodes)) + if len(all_subgraph_nodes) > len(unique_subgraph_nodes): + raise AssertionError( + f"Overlapping FX nodes detected across subgraphs in `module_bucket_plans`. " + f"Expected disjoint node sets but found " + f"{len(all_subgraph_nodes) - len(unique_subgraph_nodes)} duplicated node(s)." + ) + + +def manual_overlap_bucketing( + gm: torch.fx.GraphModule, + module_bucket_plans: list[list[str] | str], + insert_overlap_deps: bool = False, + module_stack_fn: Callable[[fx.Node], list[tuple[str, type[Any]]]] | None = None, + bucket_mode: BucketMode | None = None, +) -> torch.fx.GraphModule: + """Schedule nodes based on user specifications in module_bucket_plans + The manual overlapping consists of two steps: + Step 1: bucket all-gather/reduce-scatter in each module in module_bucket_plans + Step 2: reorder all-gather to overlap with last module_bucket & + reorder reduce-scatter to overlap with next module_bucket + TODO(ruisizhang123): allow users to explicitly specify which + module_bucket they want to overlap. + + Args: + gm: input graph module to optimize. + module_bucket_plans: user specified FQNs + module_stack_fn: Optional callable for extracting module hierarchy from nodes. + Used to construct a GraphView for identifying nodes in module_bucket_plans. + The module_class component of the returned tuples is not used by this pass. + + See the `module_stack_fn` parameter in `make_graph_view` (graph_view.py) for + detailed documentation on signature, return format, and usage examples. + bucket_mode: Bucket mode for collective bucketing. None uses default. + """ + # decode abbreviated FQNs to actual FQNs + overlapped_gm = ManualOverlapScheduler( + gm, + module_bucket_plans, + insert_overlap_deps, + module_stack_fn, + bucket_mode=bucket_mode, + ).run() + overlapped_gm.recompile() + return overlapped_gm diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/overlap_preserving_bucketer.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/overlap_preserving_bucketer.py new file mode 100644 index 0000000000000000000000000000000000000000..384653248b0300b6d094f7ccd608b039877aab88 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/overlap_preserving_bucketer.py @@ -0,0 +1,1079 @@ +import logging +from collections import defaultdict +from dataclasses import dataclass +from typing import Any, Literal, Optional + +import torch +import torch.fx as fx +from torch._dynamo.utils import counters +from torch._inductor.augmented_graph_helper import AugmentedGraphHelper +from torch._inductor.fx_passes.bucketing import ( + _default_bucket_mode, + _get_collective_node_from_wait, + _schedulable_wait_node, + BucketMode, + get_full_bucket_key, + has_mergeable_all_gather_convert_dtype, + is_all_gather_into_tensor as is_all_gather, + is_reduce_scatter_tensor as is_reduce_scatter, +) +from torch._inductor.fx_passes.fsdp import is_fsdp_all_gather +from torch._inductor.fx_passes.overlap_scheduling import ( + CollBucket, + CollectiveInfo, + get_group_name, + is_compute_node, + log as overlap_scheduling_log, +) +from torch._inductor.fx_passes.utils import BitsetAncestors +from torch._logging import trace_structured +from torch.utils._ordered_set import OrderedSet + + +bucket_log = logging.getLogger(__name__) + + +@dataclass +class WhyNoBucket: + name1: str + name2: str + reason: str + args: tuple[Any, ...] + + def __init__(self, node1: fx.Node, node2: fx.Node) -> None: + self.name1 = node1.name + self.name2 = node2.name + self.reason = "" + self.args = () + + def __call__(self, reason: str, *args: Any) -> None: + if bucket_log.isEnabledFor(logging.DEBUG): + bucket_log.debug( + "cannot bucket %s with %s: " + reason, + self.name1, + self.name2, + *args, + ) + + +def is_collective_or_wait(n: fx.Node) -> bool: + """Check if node is a collective start or wait.""" + if _schedulable_wait_node(n): + return True + # Collective starts have exactly one use: the wait_tensor + if len(n.users) == 1: + user = next(iter(n.users.keys())) + if _schedulable_wait_node(user): + return True + return False + + +@dataclass +class PGEvent: + """ + Represents an important event in a process group timeline. Either + a collective start, wait, or hiding compute. Each node is linked + to its prev and next and these dependencies are reflected + in the augmented graph. + + We want to enforce a sequential ordering of collective starts and waits + because NCCL collectives on the same process group execute on the same CUDA + stream, creating implicit dependencies between all operations on that PG. + + A wait of a particular collective will implicitly force realization of all collectives + enqueued prior to that collective. + """ + + node: fx.Node + event_type: Literal["compute", "starts", "waits"] + position: int + prev: Optional["PGEvent"] = None + next: Optional["PGEvent"] = None + + @property + def is_start(self) -> bool: + return self.event_type == "starts" + + @property + def is_wait(self) -> bool: + return self.event_type == "waits" + + @property + def is_compute(self) -> bool: + return self.event_type == "compute" + + def unlink(self) -> tuple[Optional["PGEvent"], Optional["PGEvent"]]: + """Remove this event from the linked list, return (prev, next).""" + prev_event, next_event = self.prev, self.next + if self.prev: + self.prev.next = self.next + if self.next: + self.next.prev = self.prev + self.prev = None + self.next = None + return prev_event, next_event + + def insert_between( + self, prev_event: Optional["PGEvent"], next_event: Optional["PGEvent"] + ) -> None: + """Insert this event between prev_event and next_event in the linked list.""" + if prev_event: + prev_event.next = self + self.prev = prev_event + + if next_event: + next_event.prev = self + self.next = next_event + + +class OverlapPreservingBucketer: + """ + Buckets collective operations while preserving compute-collective overlap relationships. + Uses an augmented graph to track dependencies between compute and collective operations. + """ + + def __init__( + self, + graph: fx.Graph, + collective_info: dict[fx.Node, CollectiveInfo], + scheduled: OrderedSet[fx.Node], + max_bucket_memory_gb: float = 1.0, + max_coll_distance: int = 1000, + insert_overlap_deps: bool = False, + collective_bucketing: bool = True, + bucket_mode: BucketMode | None = None, + bucket_exposed_first: bool | None = None, + bucket_only_internode_comms: bool = False, + ): + self.graph = graph + self.collective_info = collective_info + self.scheduled = scheduled + self.max_bucket_memory_gb = max_bucket_memory_gb + self.node_idx = {n: i for i, n in enumerate(scheduled)} + self.max_coll_distance = max_coll_distance + self.insert_overlap_deps = insert_overlap_deps + self.bucket_exposed_first = bucket_exposed_first + self.bucket_only_internode_comms = bucket_only_internode_comms + self.bucket_mode = bucket_mode or _default_bucket_mode() + self.collective_bucketing = collective_bucketing + self.node_to_event: dict[fx.Node, PGEvent] = {} + self.all_hiding_nodes: OrderedSet[fx.Node] = OrderedSet() + + # Compute ancestors including original graph edges and hiding interval dependencies + self.node_ancestors = self._compute_node_ancestors() + self.aug_graph = AugmentedGraphHelper(self.graph, self.node_ancestors) + + # Build timelines and add constraints to aug_graph + self.pg_to_timeline_head: dict[str, PGEvent | None] = self.build_timelines() + self._add_hiding_interval_constraints() + + def _compute_node_ancestors(self) -> BitsetAncestors: + """Compute ancestor sets including hiding interval deps using bitsets.""" + extra_inputs: dict[fx.Node, OrderedSet[fx.Node]] = defaultdict(OrderedSet) + for start, info in self.collective_info.items(): + if info.is_exposed: + continue + for hiding_node in info.hiding_nodes: + extra_inputs[hiding_node].add(start) + extra_inputs[info.wait_node].add(hiding_node) + + return BitsetAncestors(list(self.scheduled), extra_inputs=extra_inputs) + + def build_timelines(self) -> dict[str, PGEvent | None]: + "Construct each process groups ordered series of event" + all_pgs: OrderedSet[str] = OrderedSet() + for start in self.collective_info: + pg = get_group_name(start) + all_pgs.add(pg) + + pg_timeline: dict[str, PGEvent | None] = {} + for pg in all_pgs: + pg_timeline[pg] = self.build_timeline(pg) + + return pg_timeline + + def build_timeline(self, pg: str) -> PGEvent | None: + """ + Build a timeline of important events (starts, waits, hiding compute) for this process group + and constrain this ordering in the augmented graph. + + Sequential dependencies are added between all events because NCCL collectives on the same + process group execute on the same CUDA stream, enforcing LIFO semantics where later-issued + collectives must complete before earlier ones can finish. + """ + + head = None + prev_event = None + position = 0 + hiding_nodes = OrderedSet() + + for node in self.scheduled: + node_type = None + + # Determine if this node is relevant for this PG + if node in self.collective_info and get_group_name(node) == pg: + node_type = "starts" + hiding_nodes |= self.collective_info[node].hiding_nodes + elif _schedulable_wait_node(node): + wait_coll = _get_collective_node_from_wait(node) + if isinstance(wait_coll, fx.Node) and get_group_name(wait_coll) == pg: + node_type = "waits" + # Wait for a different PG but hiding a collective on this PG + elif node in hiding_nodes: + node_type = "compute" + elif is_compute_node(node) or node in hiding_nodes: + node_type = "compute" + + if node_type is None: + continue + + event = PGEvent(node=node, event_type=node_type, position=position) # type: ignore[arg-type] + + event.insert_between(prev_event, None) + + # Add sequential dependency to augmented graph + if prev_event: + self.aug_graph.add_extra_dep(n=event.node, dep=prev_event.node) + else: + head = event + + prev_event = event + position += 1 + + return head + + def _populate_node_to_event(self, pg: str) -> None: + """Populate node_to_event mapping for a specific PG's timeline.""" + self.node_to_event.clear() + head = self.pg_to_timeline_head[pg] + curr = head + while curr is not None: + self.node_to_event[curr.node] = curr + curr = curr.next + + def _add_hiding_interval_constraints(self) -> None: + """ + Add hiding interval constraints: start -> compute -> wait. + """ + for start, info in self.collective_info.items(): + if info.is_exposed: + continue + for hn in info.hiding_nodes: + # Enforce: start -> compute -> wait + self.aug_graph.add_extra_dep(n=hn, dep=start) + self.aug_graph.add_extra_dep(n=info.wait_node, dep=hn) + + self.all_hiding_nodes |= info.hiding_nodes + + def identify_internode_group_names(self) -> OrderedSet[str]: + # Identify internode comm groups. + # Temporary uses FSDP pattern as heuristic for outer groups. + checked_pgs = OrderedSet() + internode_pgs = OrderedSet() + for start in self.collective_info: + pg = get_group_name(start) + if is_all_gather(start) and pg not in checked_pgs: + if is_fsdp_all_gather(start): + internode_pgs.add(pg) + checked_pgs.add(pg) + return internode_pgs + + def _bucket_collectives_impl(self) -> list[CollBucket]: + """Find and apply bucket transformations for collectives.""" + pg_collectives: dict[str, OrderedSet[fx.Node]] = defaultdict(OrderedSet) + internode_pgs = self.identify_internode_group_names() + + for start in self.collective_info: + pg = get_group_name(start) + pg_collectives[pg].add(start) + + all_buckets: list[CollBucket] = [] + for pg, collectives in pg_collectives.items(): + if self.bucket_only_internode_comms and pg not in internode_pgs: + continue + + # Populate node_to_event for this PG's timeline + self._populate_node_to_event(pg) + + grouped_collectives: dict[object, OrderedSet[fx.Node]] = defaultdict( + OrderedSet + ) + for start in collectives: + key = get_full_bucket_key(start, self.bucket_mode) + if key[1] is not None: + grouped_collectives[key].add(start) + + for key, collective_group in grouped_collectives.items(): + bucket_log.debug( + "bucketing collective group with key %s: %s", + key, + [n.name for n in collective_group], + ) + buckets = self._find_buckets(collective_group, internode_pgs) + all_buckets.extend(buckets) + + for coll_bucket in all_buckets: + if len(coll_bucket.collectives) <= 1: + continue + + counters["inductor"]["collective_buckets"] += 1 + self._apply_bucket(coll_bucket) + return all_buckets + + def _apply_deps_and_effect_tokens(self) -> None: + """Apply topological sort and effect tokens to preserve overlap.""" + from torch._dynamo.graph_deduplication import _stable_topological_sort + + # Clean up any remaining erased node references and cycles + self.aug_graph.remove_erased_extra_deps() + autofix = torch._inductor.config.aten_distributed_optimizations.overlap_scheduling_autofix_cycles + self.aug_graph.check_and_maybe_autofix_cyclic_extra_deps(autofix=autofix) + additional_deps = self.aug_graph.get_all_extra_deps() + + for n, deps in additional_deps.items(): + torch._check( + not n._erased, lambda: f"Erased node deps not transferred: {n}" + ) + for d in deps: + torch._check( + not d._erased, lambda: f"Erased node deps not transferred: {d}" + ) + + _stable_topological_sort(self.graph, additional_deps) + + if self.insert_overlap_deps: + # Filter out collective-to-collective deps (handled by NCCL stream ordering) + filtered_deps: dict[fx.Node, OrderedSet[fx.Node]] = {} + for node, deps in additional_deps.items(): + filtered_node_deps: OrderedSet[fx.Node] = OrderedSet() + for dep in deps: + if not (is_collective_or_wait(node) and is_collective_or_wait(dep)): + filtered_node_deps.add(dep) + if filtered_node_deps: + filtered_deps[node] = filtered_node_deps + + if filtered_deps: + from torch._inductor.fx_passes.control_dependencies import ( + preserve_node_ordering, + ) + + preserve_node_ordering(self.graph, filtered_deps) + + def bucket_collectives(self) -> None: + """Run the full bucketing and dep application flow.""" + # Step 1: Bucket collectives + all_buckets: list[CollBucket] | None = None + if self.collective_bucketing: + all_buckets = self._bucket_collectives_impl() + + # Step 2: Add control deps + self._apply_deps_and_effect_tokens() + self.graph.lint() + + if ( + overlap_scheduling_log.isEnabledFor(logging.DEBUG) + and all_buckets is not None + ): + log_strs: list[str] = [] + stats_num_buckets_per_key = defaultdict(int) + stats_num_bucketed_collectives_per_key = defaultdict(int) + stats_num_total_collectives_per_key = defaultdict(int) + + def _bucket_key(node): + return get_full_bucket_key(node, self.bucket_mode) + + for start, info in self.collective_info.items(): + stats_num_total_collectives_per_key[_bucket_key(start)] += 1 + + for i, bucket in enumerate(all_buckets): + bucket_n = len(bucket.collectives) + if bucket_n == 0: + continue + node = bucket.collectives[0] + key = _bucket_key(node) + stats_num_buckets_per_key[key] += 1 + stats_num_bucketed_collectives_per_key[key] += bucket_n + log_strs.append(f"bucket[{i}] key:{key} len:{bucket_n}:{bucket}") + for coll in bucket.collectives: + info = self.collective_info[coll] + hns = info.hiding_nodes + log_strs.append(f"coll:{coll} hiding_nodes:{hns}") + + bucket_log_strs: list[str] = [] + for key, num_buckets in stats_num_buckets_per_key.items(): + num_colls = stats_num_bucketed_collectives_per_key[key] + bucket_log_strs.append( + f"bucket key stats {key}: {num_colls} in {num_buckets}" + f" buckets of total:{stats_num_total_collectives_per_key[key]}" + ) + bucket_log_strs.append("") + # Add stats to the beginning + log_strs[:0] = bucket_log_strs + bucket_logs = "\n".join(log_strs) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_fx_passes_overlap_bucketing", + "encoding": "string", + }, + payload_fn=lambda: bucket_logs, + ) + + def _compute_overlap_ratio(self, node: fx.Node) -> float: + """ + Compute what fraction of the collective's time is hidden by compute. + Returns 0.0 for fully exposed, 1.0 for fully hidden. + """ + info = self.collective_info[node] + if info.estimated_time_ms <= 0: + return 0.0 + hidden_time = info.estimated_time_ms - info.exposed_time_ms + return hidden_time / info.estimated_time_ms + + def _should_bucket_exposed_first( + self, + collective_group: OrderedSet[fx.Node], + current_pg: str, + internode_pgs: OrderedSet[str], + ) -> bool: + """Determine whether to bucket exposed collectives first.""" + if self.bucket_exposed_first is None: + return current_pg in internode_pgs + return self.bucket_exposed_first + + def _find_buckets( + self, + collective_group: OrderedSet[fx.Node], + internode_pgs: OrderedSet[str], + ) -> list[CollBucket]: + """Find valid buckets within a group of similar collectives.""" + max_bucket_bytes = int(self.max_bucket_memory_gb * 1024 * 1024 * 1024) + buckets = [] + processed: OrderedSet[fx.Node] = OrderedSet() + if len(collective_group) == 0: + return [] + + current_pg = get_group_name(next(iter(collective_group))) + + bucket_exposed_first = self._should_bucket_exposed_first( + collective_group, current_pg, internode_pgs + ) + if bucket_exposed_first: + # Sort by overlap ratio (ascending) to bucket least hidden collectives first. + # Exposed collectives benefit most from bucketing since their latency is on the + # critical path. Prioritizing them also preserves hiding relationships for + # already-hidden collectives, which have less to gain from bucketing. + sorted_collectives = sorted( + collective_group, + key=lambda n: (self._compute_overlap_ratio(n), self.node_idx[n]), + ) + else: + sorted_collectives = sorted( + collective_group, + key=lambda n: self.node_idx[n], + ) + + for i, start_node in enumerate(sorted_collectives): + if start_node in processed: + continue + + if ( + start_node in self.all_hiding_nodes + or self.collective_info[start_node].wait_node in self.all_hiding_nodes + ): + continue + + # Initialize bucket with first collective + bucket_info = CollBucket( + collectives=[start_node], + total_bytes=self.collective_info[start_node].size_bytes, + ) + processed.add(start_node) + + # Greedy optimization: stop after consecutive failures + consecutive_failures = 0 + max_consecutive_failures = 20 + start_node_idx = self.node_idx[start_node] + + # Check candidates in sorted order, break when beyond max distance + for candidate in sorted_collectives[i + 1 : i + 1 + self.max_coll_distance]: + candidate_bytes = self.collective_info[candidate].size_bytes + # proxy on memory use, if we see a too large bucket, + # don't look for another, later bucket + if bucket_info.total_bytes + candidate_bytes > max_bucket_bytes: + break + + if candidate in processed: + continue + + candidate_node_idx = self.node_idx[candidate] + if ( + bucket_exposed_first + and abs(candidate_node_idx - start_node_idx) + > max_consecutive_failures + ): + # Since collectives are sorted by overlap ratio rather than graph + # position, skip candidates too far apart in the graph to avoid + # creating buckets that block future bucketing opportunities. + continue + + if self._can_add_to_bucket(bucket_info, candidate): + bucket_info.collectives.append(candidate) + bucket_info.total_bytes += candidate_bytes + processed.add(candidate) + consecutive_failures = 0 # Reset on success + else: + consecutive_failures += 1 + if consecutive_failures >= max_consecutive_failures: + break + + if len(bucket_info.collectives) > 1: + buckets.append(bucket_info) + + return buckets + + def _ancestor_dep(self, n1: fx.Node, n2: fx.Node) -> bool: + """Check if there's an ancestor relationship between two nodes.""" + return self.node_ancestors.has_dep(n1, n2) + + def _get_intervals( + self, event: PGEvent + ) -> tuple[tuple[int, int] | None, list[tuple[int, int]]]: + """Get (execution_interval, hiding_intervals) for a collective event. + + Returns: + (execution_interval, hiding_intervals) where: + - execution_interval is (start_pos, wait_pos) or None + - hiding_intervals is a list of (start_pos, compute_pos) tuples, one for each hiding node + + Works for both start and wait events by looking up the collective info. + """ + # For start events, directly use the node + if event.is_start: + coll = event.node + # For wait events, look up the start node from the event's args + elif event.is_wait: + coll = _get_collective_node_from_wait(event.node) + if coll is None: + return None, [] + else: + return None, [] + + if coll not in self.collective_info: + return None, [] + + info = self.collective_info[coll] + start_event = self.node_to_event[coll] + wait_event = self.node_to_event[info.wait_node] + + execution_interval = (start_event.position, wait_event.position) + + hiding_intervals = [] + if info.hiding_nodes: + for hiding_node in info.hiding_nodes: + hiding_intervals.append( + ( + start_event.position, + self.node_to_event[hiding_node].position, + ) + ) + + return execution_interval, hiding_intervals + + def _preserves_hiding_intervals( + self, + bucket_info: CollBucket, + candidate: fx.Node, + start_pos: fx.Node, + wait_pos: fx.Node, + why: WhyNoBucket, + ) -> bool: + """ + Check that (start_pos, wait_pos) doesn't violate any hiding intervals or collectives. + + Collects all execution and hiding intervals in the affected timeline regions, + then checks: + 1. All bucket hiding compute stays between new start/wait + 2. No other collective's compute interval is enclosed by bucket execution interval + 3. No other collective's execution interval encloses bucket compute intervals + """ + # Collect all collectives being bucketed + all_bucketed_colls = [candidate] + list(bucket_info.collectives) + all_bucketed_waits = [ + self.collective_info[coll].wait_node for coll in all_bucketed_colls + ] + + # Collect hiding compute positions for the bucket + bucket_hiding_compute_positions = [] + for coll in all_bucketed_colls: + for coll_hiding_node in self.collective_info[coll].hiding_nodes: + bucket_hiding_compute_positions.append( + self.node_to_event[coll_hiding_node].position + ) + + # Get new positions + new_start_event = self.node_to_event[start_pos] + new_wait_event = self.node_to_event[wait_pos] + + # Check 1: All bucket hiding compute must be between new start and wait + for compute_pos in bucket_hiding_compute_positions: + if not (new_start_event.position < compute_pos < new_wait_event.position): + why( + "hiding compute at pos %d not between start %d and wait %d", + compute_pos, + new_start_event.position, + new_wait_event.position, + ) + return False + + def get_wait(n: fx.Node) -> fx.Node: + return self.collective_info[n].wait_node + + def get_pos(n: fx.Node) -> int: + return self.node_to_event[n].position + + latest_start_pos = max(get_pos(candidate), get_pos(bucket_info.collectives[0])) + earliest_wait_pos = min( + get_pos(get_wait(candidate)), get_pos(get_wait(bucket_info.collectives[0])) + ) + + # Bucket execution interval + bucket_execution_interval = (new_start_event.position, new_wait_event.position) + + # Because collectives on the same PG operate under LIFO semantics, + # it's only possible for us to force an early realization of an unrelated collective + # by delaying a start or raising a wait. + # We search in the interval from old_start -> new_start, to see if would be + # forcing another collective to be realized prior to its hiding nodes. + # Similarly, we search from old_wait -> new_wait, in the reverse direction, + # to check the same thing. + + execution_intervals = [bucket_execution_interval] + hiding_intervals = [ + (bucket_execution_interval[0], pos) + for pos in bucket_hiding_compute_positions + ] + + curr_event = new_start_event.next + while curr_event is not None and curr_event.position < latest_start_pos: + if ( + curr_event.node not in all_bucketed_colls + and curr_event.node not in all_bucketed_waits + ): + exec_interval, hiding_interval_list = self._get_intervals(curr_event) + if exec_interval: + execution_intervals.append(exec_interval) + hiding_intervals.extend(hiding_interval_list) + curr_event = curr_event.next + + curr_event = new_wait_event.prev + while curr_event is not None and curr_event.position > earliest_wait_pos: + if ( + curr_event.node not in all_bucketed_colls + and curr_event.node not in all_bucketed_waits + ): + exec_interval, hiding_interval_list = self._get_intervals(curr_event) + if exec_interval: + execution_intervals.append(exec_interval) + hiding_intervals.extend(hiding_interval_list) + curr_event = curr_event.prev + + # Check: no hiding interval should be enclosed by any execution interval + def enclosed_interval(inner: tuple[int, int], outer: tuple[int, int]) -> bool: + return outer[0] < inner[0] and inner[1] < outer[1] + + for hiding_interval in hiding_intervals: + for execution_interval in execution_intervals: + if enclosed_interval(hiding_interval, execution_interval): + why( + "hiding interval %s enclosed by execution interval %s", + hiding_interval, + execution_interval, + ) + return False + + return True + + def remove_from_event(self, node: fx.Node) -> tuple[PGEvent | None, PGEvent | None]: + """Remove node from timeline and return (prev_event, next_event).""" + event = self.node_to_event[node] + if event.is_compute: + raise AssertionError("Cannot remove compute events from timeline") + + prev_event, next_event = event.unlink() + + # Remove augmented graph dependency + if prev_event: + self.aug_graph.remove_extra_dep(n=node, dep=prev_event.node) + if next_event: + self.aug_graph.remove_extra_dep(n=next_event.node, dep=node) + + # Add bypass dependency + if prev_event and next_event: + self.aug_graph.add_extra_dep(n=next_event.node, dep=prev_event.node) + + return prev_event, next_event + + def restore_to_event( + self, + node: fx.Node, + prev_event: PGEvent | None, + next_event: PGEvent | None, + ) -> None: + """Restore node to timeline after failed merge attempt.""" + event = self.node_to_event[node] + + # Reinsert into linked list + event.insert_between(prev_event, next_event) + if prev_event: + self.aug_graph.add_extra_dep(n=node, dep=prev_event.node) + if next_event and not prev_event: + self.aug_graph.add_extra_dep(n=next_event.node, dep=node) + + # Remove bypass dependency + if prev_event and next_event: + self.aug_graph.remove_extra_dep(n=next_event.node, dep=prev_event.node) + + def _try_timeline_position( + self, + bucket_info: CollBucket, + candidate: fx.Node, + start_pos: fx.Node, + wait_pos: fx.Node, + why: WhyNoBucket, + ) -> bool: + """ + Try a specific timeline position for the candidate. + Returns True if valid and merges are successful. + """ + candidate_info = self.collective_info[candidate] + candidate_wait = candidate_info.wait_node + + # Quick check: does this violate hiding intervals? + if not self._preserves_hiding_intervals( + bucket_info, candidate, start_pos, wait_pos, why + ): + return False + + # Determine which start needs to move + existing_coll = bucket_info.collectives[0] + if start_pos == existing_coll: + start_to_move = candidate + else: + if start_pos != candidate: + raise AssertionError( + f"expected start_pos == candidate, got {start_pos}" + ) + start_to_move = existing_coll + + # Remove start from timeline + start_prev, start_next = self.remove_from_event(start_to_move) + + # Check if starts can be merged + if self.aug_graph.has_path(existing_coll, candidate) or self.aug_graph.has_path( + candidate, existing_coll + ): + # Restore start constraints + self.restore_to_event(start_to_move, start_prev, start_next) + why("path exists between starts") + return False + + # Merge starts + self.aug_graph.merge_to_set(existing_coll, candidate) + + # Determine which wait needs to move + existing_wait = self.collective_info[existing_coll].wait_node + candidate_wait = self.collective_info[candidate].wait_node + + if wait_pos == existing_wait: + wait_to_move = candidate_wait + else: + wait_to_move = existing_wait + + # Remove wait from timeline + wait_prev, wait_next = self.remove_from_event(wait_to_move) + + # Check if waits can be merged + if self.aug_graph.has_path( + existing_wait, candidate_wait + ) or self.aug_graph.has_path(candidate_wait, existing_wait): + # Restore wait constraints + self.restore_to_event(wait_to_move, wait_prev, wait_next) + # Unmerge the start we just merged + self.aug_graph.unmerge_node(candidate) + # Restore start constraints + self.restore_to_event(start_to_move, start_prev, start_next) + why("path exists between waits") + return False + + # Merge waits - success! + self.aug_graph.merge_to_set(existing_wait, candidate_wait) + + # Update node_to_event for moved nodes + target_start_event = self.node_to_event[start_pos] + target_wait_event = self.node_to_event[wait_pos] + + self.node_to_event[candidate] = target_start_event + self.node_to_event[candidate_wait] = target_wait_event + self.node_to_event[existing_coll] = target_start_event + self.node_to_event[existing_wait] = target_wait_event + + return True + + def _has_ancestor_conflicts( + self, bucket_info: CollBucket, candidate: fx.Node + ) -> bool: + """ + Check if candidate has ancestor conflicts with bucket collectives. + Returns True if there are conflicts. + """ + candidate_info = self.collective_info[candidate] + candidate_wait = candidate_info.wait_node + + for coll in bucket_info.collectives: + if self.node_ancestors.has_dep(coll, candidate): + return True + + # Check if waits are ancestors of each other + coll_wait = self.collective_info[coll].wait_node + if self.node_ancestors.has_dep(coll_wait, candidate_wait): + return True + + # Check if existing hiding node conflicts with candidate wait + for old_hiding_node in self.collective_info[coll].hiding_nodes: + if self.node_ancestors.is_ancestor(candidate_wait, old_hiding_node): + return True + + # Check if candidate hiding node conflicts with existing wait + for new_hiding_node in candidate_info.hiding_nodes: + if self.node_ancestors.is_ancestor(coll_wait, new_hiding_node): + return True + + return False + + def _can_add_to_bucket( + self, + bucket_info: CollBucket, + candidate: fx.Node, + ) -> bool: + """ + Check if candidate can be added to bucket without breaking comm/compute overlap. + + Strategy: Try all timeline positions - combinations of [existing_start, candidate_start] + x [existing_wait, candidate_wait]. For each position, verify: + 1. Hiding intervals preserved - for any (start, hiding_compute, wait) interval, no other + collective's (start, wait) pair falls between start and hiding_compute, which would + force realization and break overlap due to LIFO semantics + 2. Topologically valid (no dependency cycles) + + Return True if any timeline position satisfies both constraints. + """ + existing_coll = bucket_info.collectives[0] + why = WhyNoBucket(existing_coll, candidate) + + candidate_info = self.collective_info[candidate] + + if ( + candidate in self.all_hiding_nodes + or candidate_info.wait_node in self.all_hiding_nodes + ): + why("nyi: bucketing collective used for overlap") + return False + + # Step 1: Quick check using precomputed ancestors + # These ancestors are computed prior to adding augmented dependencies and not updated, + # so if any of these checks fail then the merge will not be topologically valid + # even ignoring comm/compute overlap + if self._has_ancestor_conflicts(bucket_info, candidate): + why("has ancestor conflicts") + return False + + # Step 2: Try different rail positions + existing_wait = self.collective_info[existing_coll].wait_node + + candidate_start = candidate + candidate_wait = candidate_info.wait_node + + # Try combinations in order of likelihood to succeed + # (early start, later wait is most likely to work) + combinations = [ + ( + existing_coll, + candidate_wait, + ), # Move candidate start early, keep wait late + ( + existing_coll, + existing_wait, + ), # Move candidate start early, move wait early + (candidate_start, candidate_wait), # Keep both in place + (candidate_start, existing_wait), # Keep start in place, move wait early + ] + + for i, (start_pos, wait_pos) in enumerate(combinations): + if self._try_timeline_position( + bucket_info, candidate, start_pos, wait_pos, why + ): + bucket_log.debug( + "bucketed %s with %s using timeline position %d: (start=%s, wait=%s)", + candidate.name, + existing_coll.name, + i + 1, + start_pos.name, + wait_pos.name, + ) + return True + + why("all timeline positions failed") + return False + + def _apply_bucket(self, bucket_info: CollBucket) -> None: + """ + Apply bucketing transformation. + + Dependencies are added to aug_graph.extra_deps and transferred from old nodes. + """ + + from torch._inductor.fx_passes.bucketing import ( + is_all_reduce_tensor, + merge_all_gather_bucket, + merge_all_reduce_bucket, + merge_reduce_scatter_bucket, + ) + + bucket = bucket_info.collectives + + # Collect old nodes BEFORE they're erased + old_starts = list(bucket) + old_waits = [self.collective_info[n].wait_node for n in bucket] + + fused_convert_dtypes = [] + for n in old_starts: + if has_mergeable_all_gather_convert_dtype(n): + fused_convert_dtypes.append(n.args[0]) + + # Find where to place the bucketed operations + next_node = bucket[0] + while next_node in bucket: + next_node = next_node.next + + # Don't use wait_insertion_point - let merge functions place waits naturally + # The wait_insertion_point feature tries to move waits to a specific location, + # but this can cause issues when that location is one of the nodes being erased + # Create bucketed collective (this will erase old nodes) + if is_all_gather(bucket[0]): + new_nodes, replacements = merge_all_gather_bucket( + self.graph, + bucket, + insert_before=next_node, + mode=self.bucket_mode, + ) + elif is_all_reduce_tensor(bucket[0]): + new_nodes, replacements = merge_all_reduce_bucket( + self.graph, + bucket, + mode=self.bucket_mode, + insert_before=next_node, + ) + else: + if not is_reduce_scatter(bucket[0]): + raise AssertionError(f"expected reduce_scatter, got {bucket[0]}") + new_nodes, replacements = merge_reduce_scatter_bucket( + self.graph, + bucket, + insert_before=next_node, + mode=self.bucket_mode, + ) + + # Identify the new wait(s) and their collective start in a single pass + wait_to_start = { + n: start + for n in new_nodes + if (start := _get_collective_node_from_wait(n)) is not None + } + new_waits = list(wait_to_start) + + # Create mapping of all erased nodes to their replacements + erased_to_new: dict[fx.Node, fx.Node | None] = {} + new_start = wait_to_start[new_waits[0]] + if len(new_waits) == 1: + # Standard bucketing: single start + single wait + new_wait = new_waits[0] + for old_start in old_starts: + erased_to_new[old_start] = new_start + for old_wait in old_waits: + erased_to_new[old_wait] = new_wait + else: + # Coalesced bucketing: single start + N waits (one per original tensor) + if len(new_waits) != len(old_waits): + raise AssertionError( + f"expected len(new_waits) == len(old_waits), " + f"got {len(new_waits)} != {len(old_waits)}" + ) + for old_start in old_starts: + erased_to_new[old_start] = new_start + erased_to_new.update(dict(zip(old_waits, new_waits))) + + # Handle convert_element_type nodes that were fused and erased + # The bucketed operation may have a _pre_bucket op that handles dtype conversion + if fused_convert_dtypes: + # In custom_ops mode, the _pre_bucket_all_gather node handles dtype conversion + # In default mode, convert nodes are just erased — map them to new_start + new_convert_dtypes_node = new_start.kwargs.get("out") + if ( + isinstance(new_convert_dtypes_node, fx.Node) + and new_convert_dtypes_node.target + == torch.ops.bucketing._pre_bucket_all_gather.default + ): + replacement = new_convert_dtypes_node + else: + replacement = new_start + + for n in fused_convert_dtypes: + erased_to_new[n] = replacement + + # Transfer all dependencies from old nodes to new nodes + self.aug_graph.transfer_erased_node_deps(erased_to_new) + + +def finalize_overlap_scheduling( + gm: fx.GraphModule, + collective_info: dict[fx.Node, CollectiveInfo], + scheduled: OrderedSet[fx.Node], + *, + collective_bucketing: bool = False, + insert_overlap_deps: bool = False, + max_bucket_memory_gb: float = 2.0, + max_coll_distance: int = 1000, + bucket_exposed_first: bool | None = None, + bucket_only_internode_comms: bool = False, + bucket_mode: BucketMode | None = None, +) -> None: + """ + Finalize overlap scheduling by applying deps and optionally bucketing. + + This is the main entry point for post-scheduling graph transformations: + 1. Bucket collectives (if collective_bucketing=True) + 2. Apply topological sort and effect tokens + + Args: + gm: The graph module to modify + collective_info: Dict mapping collective start nodes to their CollectiveInfo + scheduled: Ordered set of scheduled nodes + collective_bucketing: Whether to bucket collectives + insert_overlap_deps: Whether to insert effect tokens for overlap deps + max_bucket_memory_gb: Maximum memory for a bucket in GB + max_coll_distance: Maximum distance for bucketing candidates + """ + bucketer = OverlapPreservingBucketer( + graph=gm.graph, + collective_info=collective_info, + scheduled=scheduled, + max_bucket_memory_gb=max_bucket_memory_gb, + max_coll_distance=max_coll_distance, + insert_overlap_deps=insert_overlap_deps, + collective_bucketing=collective_bucketing, + bucket_exposed_first=bucket_exposed_first, + bucket_only_internode_comms=bucket_only_internode_comms, + bucket_mode=bucket_mode, + ) + bucketer.bucket_collectives() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/overlap_scheduling.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/overlap_scheduling.py new file mode 100644 index 0000000000000000000000000000000000000000..8de616ec4c7fe13a7cd9c22f54b8dbbe7e268158 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/overlap_scheduling.py @@ -0,0 +1,1996 @@ +import functools +import heapq +import itertools +import logging +import sys +from collections import Counter, defaultdict +from collections.abc import Callable, Iterable +from dataclasses import dataclass, field +from typing import Any, Literal + +import torch +import torch.fx as fx +from torch._dynamo.utils import counters, dynamo_timed +from torch._inductor import config +from torch._inductor.comm_analysis import estimate_fx_collective_memory_footprint +from torch._inductor.fx_passes.bucketing import ( + _default_bucket_mode, + _get_collective_node_from_wait, + _resolve_group_name, + _schedulable_wait_node, + bucket_key, + BucketMode, + get_full_bucket_key, + is_wait_tensor, +) +from torch._inductor.fx_passes.memory_estimator import MemoryTracker +from torch._inductor.fx_passes.utils import BitsetAncestors +from torch._logging import trace_structured +from torch.fx.experimental.symbolic_shapes import optimization_hint +from torch.fx.operator_schemas import normalize_function +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import _disable_current_modes + + +log = logging.getLogger(__name__) + +from torch._inductor.pattern_matcher import stable_topological_sort + + +def make_all_device_put_sync(gm: torch.fx.GraphModule) -> int: + """ + Convert all non_blocking=True device_put operations to non_blocking=False. + + Only performs the conversion if at least one non_blocking=True device_put + exists in the graph. + + Returns: + The number of device_put operations converted to sync. + """ + g = gm.graph + device_put_nodes = list( + g.find_nodes(op="call_function", target=torch.ops.prims.device_put.default) + ) + + # Check if any non_blocking=True device_put exists + has_async_device_put = False + for n in device_put_nodes: + opt_args_kwargs = normalize_function( + n.target, + args=n.args, + kwargs=n.kwargs, + normalize_to_only_use_kwargs=True, + ) + if opt_args_kwargs is not None: + _, kwargs = opt_args_kwargs + if kwargs.get("non_blocking", False): + has_async_device_put = True + break + + if not has_async_device_put: + return 0 + + # Convert all non_blocking=True to non_blocking=False + count = 0 + for n in device_put_nodes: + opt_args_kwargs = normalize_function( + n.target, + args=n.args, + kwargs=n.kwargs, + normalize_to_only_use_kwargs=True, + ) + if opt_args_kwargs is not None: + _, kwargs = opt_args_kwargs + if kwargs.get("non_blocking", False): + kwargs["non_blocking"] = False + n.args = n.args[0], kwargs["device"], kwargs["non_blocking"] + n.kwargs = {} + count += 1 + + return count + + +@dataclass +class WhyNoOverlap: + """Track reasons why a collective cannot overlap with compute.""" + + compute_name: str + collective_name: str + + def __init__(self, compute_node: fx.Node, collective_node: fx.Node) -> None: + self.compute_name = compute_node.name + self.collective_name = collective_node.name + + def __call__(self, reason: str, *args: Any) -> None: + if log.isEnabledFor(logging.DEBUG): + log.debug( + "cannot overlap %s with %s: " + reason, # noqa: G003 + self.collective_name, + self.compute_name, + *args, + ) + + +@functools.cache +def get_group_name(n: fx.Node) -> str: + """Extract the group name from a collective operation node.""" + opt_args_kwargs = normalize_function( + n.target, # type: ignore[arg-type] + args=n.args, + kwargs=n.kwargs, + normalize_to_only_use_kwargs=True, + ) + if opt_args_kwargs is None: + raise AssertionError("failed to normalize args/kwargs for node") + _, kwargs = opt_args_kwargs + return _resolve_group_name(kwargs["group_name"]) + + +def get_custom_estimation( + n: fx.Node, + custom_runtime_estimation: Callable[[fx.Node, int | None], float | None] + | None = None, + override_size: int | None = None, +) -> float | None: + if custom_runtime_estimation is None: + return None + + return custom_runtime_estimation(n, override_size) + + +def estimate_collective_time( + n: fx.Node, + override_size: int | None = None, + custom_runtime_estimation: Callable[[fx.Node, int | None], float | None] + | None = None, + collective_estimator: Literal["analytical", "benchmark"] = "analytical", +) -> float: + """Estimate the runtime of a collective operation, optionally with an overridden size.""" + if ( + est := get_custom_estimation(n, custom_runtime_estimation, override_size) + ) is not None: + return est + + if collective_estimator == "benchmark": + from torch._inductor.fx_passes.node_runtime_estimation import ( + benchmark_collective_with_cuda_events, + ) + + cuda_val, _ = benchmark_collective_with_cuda_events(n, nruns=5) + if cuda_val is not None: + return cuda_val + + # Analytical model (also fallback when benchmark returns None) + return torch._inductor.comm_analysis.estimate_nccl_collective_runtime_from_fx_node( + n, override_size + ) + + +def _get_flop_registry_key(target: Any) -> Any | None: + """Return the flop_registry key for a node target, or None if not registered.""" + key = getattr(target, "overloadpacket", None) + if key in torch.utils.flop_counter.flop_registry: + return key + if target in torch.utils.flop_counter.flop_registry: + return target + return None + + +def is_compute_node(n: fx.Node) -> bool: + """ + Should we consider this node computationally expensive ? + Currently uses flop registration, but we could expand more generally. + """ + return _get_flop_registry_key(n.target) is not None + + +def estimate_roofline_runtime_ms(node: fx.Node) -> float: + """Estimate runtime using roofline model (max of compute and memory bound). + + Uses FLOPs for compute-bound estimate if op is in flop_registry, + and memory bandwidth for memory-bound estimate. + Returns 0 for view nodes (no cost). + """ + from torch._inductor.fx_passes.fusion_regions import is_view_node + from torch.utils._pytree import tree_flatten, tree_map + from torch.utils._runtime_estimation import get_compute_time, get_transfer_time + + if is_view_node(node): + return 0.0 + + def _get_val(n: Any) -> Any: + if isinstance(n, fx.Node): + return n.meta.get("val") + return n + + args = tree_map(_get_val, node.args) + kwargs = tree_map(_get_val, node.kwargs) + out = _get_val(node) + + if out is None: + return 0.0 + + flat_args_kwargs, _ = tree_flatten((args, kwargs)) + flat_outs, _ = tree_flatten(out) + out_dtypes = OrderedSet([t.dtype for t in flat_outs if isinstance(t, torch.Tensor)]) + + # Compute time (FLOPs-based, only if op is in flop_registry) + compute_ns: float = 0.0 + flop_key = _get_flop_registry_key(node.target) + if flop_key is not None and len(out_dtypes) >= 1: + # Use a single dtype for peak-flops lookup. For mixed-dtype outputs + # (e.g. flex_attention returns bf16 out + fp32 logsumexp), use the + # first output tensor's dtype as the compute dtype. + compute_dtypes = ( + OrderedSet(out_dtypes) + if len(out_dtypes) == 1 + else OrderedSet( + [next(t.dtype for t in flat_outs if isinstance(t, torch.Tensor))] + ) + ) + compute_ns = get_compute_time( + flop_key, args, kwargs, out, compute_dtypes, node_meta=node.meta + ) + if isinstance(compute_ns, (torch.SymInt, torch.SymFloat)): + compute_ns = hint if (hint := compute_ns.hint) is not None else 0.0 + + # Transfer time (memory bandwidth-based, uses size_hint internally) + transfer_ns = get_transfer_time(flat_args_kwargs, flat_outs) + + # Roofline: max of compute and transfer, convert ns to ms + return max(float(compute_ns), float(transfer_ns)) / 1e6 + + +def get_hint(x: int | torch.SymInt) -> int | None: + if isinstance(x, int): + return x + return x.hint + + +def get_collective_do_bench() -> Callable[[Callable[[], Any]], float]: + with dynamo_timed("collective_compute_do_bench"): + return functools.partial( + # pyrefly: ignore [bad-argument-type] + torch._inductor.runtime.benchmarking.benchmarker.benchmark_gpu, + warmup=5, + ) + + +def benchmark_node_with_cache_key( + n: fx.Node, + custom_runtime_estimation: Callable[[fx.Node, int | None], float | None] + | None = None, +) -> tuple[float, str | None]: + """Benchmark a compute node and return (runtime, cache_key).""" + if not is_compute_node(n): + raise AssertionError(f"expected a compute node, got {n}") + + # HOPs can't be benchmarked standalone (args include subgraphs) — use analytical + from torch._ops import HigherOrderOperator + + if isinstance(n.target, HigherOrderOperator): + return estimate_roofline_runtime_ms(n), None + + from torch._dynamo.testing import rand_strided + + # todo - skip unbacked, symbolic + success, args, kwargs = torch._inductor.fx_utils.get_fake_args_kwargs(n) + + if not success: + return 0, None + + unbacked_tensor = False + + key = f"{str(n.target)}: " + + def to_real(t: torch.Tensor) -> torch.Tensor | None: + shape = [get_hint(dim) for dim in t.shape] + stride = [get_hint(s) for s in t.stride()] + + if any(s is None for s in itertools.chain(shape, stride)): + nonlocal unbacked_tensor + unbacked_tensor = True + return None + + nonlocal key + key += f"T: {shape, stride, t.dtype} " + return rand_strided(shape, stride, device=t.device, dtype=t.dtype) # type: ignore[arg-type] + + with _disable_current_modes(): + args, kwargs = torch.utils._pytree.tree_map_only( + torch.Tensor, + lambda t: to_real(t), + (args, kwargs), + ) + + args, kwargs = torch.utils._pytree.tree_map_only( + torch.SymInt, + lambda s: optimization_hint(s, fallback=config.unbacked_symint_fallback), + (args, kwargs), + ) + + if val := get_cached_node_time(key): + return val, key + + if unbacked_tensor: + return 0, key + + if ( + est := get_custom_estimation(n, custom_runtime_estimation, None) + ) is not None: + set_cached_node_time(key, est) + return est, key + + bench = get_collective_do_bench() + out = bench(lambda: n.target(*args, **kwargs)) # type: ignore[operator] + set_cached_node_time(key, out) + return out, key + + +def benchmark_node( + n: fx.Node, + custom_runtime_estimation: Callable[[fx.Node, int | None], float | None] + | None = None, +) -> float: + return benchmark_node_with_cache_key(n, custom_runtime_estimation)[0] + + +@functools.cache +def get_benchmark_cache() -> torch._inductor.codecache.LocalCache: + return torch._inductor.codecache.LocalCache() + + +def get_cached_node_time(key: str) -> float: + return get_benchmark_cache().lookup(key) # type: ignore[return-value] + + +def set_cached_node_time(key: str, value: float) -> None: + return get_benchmark_cache().set_value(key, value=value) + + +@dataclass +class CollectiveInfo: + """Track info about a collective operation""" + + start_node: fx.Node + wait_node: fx.Node + size_bytes: int + estimated_time_ms: float + exposed_time_ms: float # How much of this collective is still exposed + hiding_nodes: OrderedSet[fx.Node] = field(default_factory=OrderedSet) + + @property + def is_exposed(self) -> bool: + return self.exposed_time_ms != 0 + + +@dataclass +class CollBucket: + """Track information about a bucket of collectives.""" + + collectives: list[fx.Node] # Original collective starts + bucketed_start: fx.Node | None = None # After bucketing + bucketed_wait: fx.Node | None = None # After bucketing + total_bytes: int = 0 + + +def gb_to_bytes(gb: float) -> int: + """Convert gigabytes to bytes.""" + return int(gb * 1024 * 1024 * 1024) + + +class OverlapScheduler: + """ + Scheduler that reorders operations to maximize compute-collective overlap. + + The reordering is done as a scheduling pass. We maintain a priority queue of + schedulable nodes. The nodes are ranked by: + + 1) the compute node index they dominate. this allows reordering locally, such as with + parallel mms, and also allows overlapping reduce scatter nodes outputs in the backward + with compute by deferring their waits. + + 2) whether the current node is a collective or wait that is currently exposed but has a compute + node which it could be overlapped with. + + 3) original order in the graph for stability. + + When we schedule compute nodes, we first overlap exposed in-flight collectives, then look for unscheduled + collectives that can be scheduled concurrently. + + TODO: + - experiment with other priority scores / allow other mechanisms of reorder / more strict adherence to original graph + - memory limit for deferred scheduling of reduce_scatter nodes. + """ + + def __init__( + self, + gm: torch.fx.GraphModule, + max_in_flight_gb: float, + max_compute_pre_fetch: int, + collective_bucketing: bool, + insert_overlap_deps: bool, + compute_overlap_multipler: float, + max_coll_distance: int, + custom_runtime_estimation: Callable[[fx.Node, int | None], float | None] + | None = None, + collective_estimator: Literal["analytical", "benchmark"] = "analytical", + compute_estimator: Literal["analytical", "benchmark"] = "benchmark", + max_memory_increase_gb: float | None = 1.0, + max_memory_increase_ratio: float | None = 0.05, + log_final_collectives_estimations: bool = False, + bucket_exposed_first: bool | None = None, + enable_fusion_regions: bool = False, + bucket_only_internode_comms: bool = False, + bucket_mode: BucketMode | None = None, + max_off_bucket_gb: float | None = 0.5, + prioritize_bucketing_during_scheduling: bool = True, + pge_profile_path: str | None = None, + ): + self.gm = gm + self.graph = gm.graph + self.compute_overlap_multipler = compute_overlap_multipler + self.max_node_distance = max_coll_distance + self.max_in_flight_bytes: int = gb_to_bytes(max_in_flight_gb) + + # Profile-guided estimation: create estimator from profile path + if pge_profile_path and custom_runtime_estimation is None: + from torch._inductor.fx_passes.profile_guided_estimation import ( + ProfileGuidedEstimator, + ) + + custom_runtime_estimation = ProfileGuidedEstimator( + pge_profile_path, diagnostics_gm=gm + ) + + self.custom_runtime_estimation = custom_runtime_estimation + self.collective_bucketing = collective_bucketing + self.insert_overlap_deps = insert_overlap_deps + self.max_compute_pre_fetch = max_compute_pre_fetch + # In deterministic mode, force analytical estimation to avoid GPU sync + if config.deterministic: + self.collective_estimator = "analytical" + self.compute_estimator = "analytical" + else: + self.collective_estimator = collective_estimator + self.compute_estimator = compute_estimator + self.log_final_collectives_estimations = log_final_collectives_estimations + self.bucket_exposed_first = bucket_exposed_first + self.bucket_only_internode_comms = bucket_only_internode_comms + self.bucket_mode = bucket_mode or _default_bucket_mode() + self.max_off_bucket_bytes: int | None = ( + gb_to_bytes(max_off_bucket_gb) if max_off_bucket_gb is not None else None + ) + self.prioritize_bucketing_during_scheduling = ( + prioritize_bucketing_during_scheduling + ) + + # Make all to(device) non_blocking=False, + # They can be implicitly depending by user logic on other to(device) non_blocking=True. + # OverlapScheduler can put reads of non_blocking device_put before blocking one. + # This results in dirty reads. + num_device_put_converted = make_all_device_put_sync(gm) + if num_device_put_converted > 0: + log.warning( + "overlap_scheduling converted %d device_put operations from " + "non_blocking=True to non_blocking=False. This may affect performance.", + num_device_put_converted, + ) + + # Compute initial node runtime estimates. Compute nodes use roofline model + # here; the alignment step in run() replaces them with benchmarked + + # cross-rank-aligned values. + self.node_estimations = gather_node_runtime_estimations( + gm, + custom_runtime_estimation, + enable_fusion_regions=enable_fusion_regions, + log_estimations=True, + ) + # Build structures + stable_topological_sort(self.graph) + self.nodes = list(self.graph.nodes) + self.node_idx = {n: i for i, n in enumerate(self.nodes)} + self._parent_lists: list[list[fx.Node]] = [ + list(n._input_nodes) for n in self.nodes + ] + self.node_ancestors: BitsetAncestors = self._collect_node_ancestors() + + # Identify collectives and compute nodes + self.collective_info: dict[fx.Node, CollectiveInfo] = {} + self.unscheduled_collectives: OrderedSet[fx.Node] = OrderedSet() + + # Identify compute nodes early (needed for baseline memory computation) + self.compute_nodes = [n for n in self.nodes if is_compute_node(n)] + self.current_compute_index = 0 + + self.original_mem_before_compute_index: list[int] = [] + needs_memory_tracking = ( + max_memory_increase_gb is not None or max_memory_increase_ratio is not None + ) + if needs_memory_tracking: + self.original_peak_memory = self._compute_baseline_memory() + memory_increase_bytes = None + if max_memory_increase_gb is not None: + memory_increase_bytes = gb_to_bytes(max_memory_increase_gb) + if max_memory_increase_ratio is not None: + ratio_increase = int( + self.original_peak_memory * max_memory_increase_ratio + ) + memory_increase_bytes = ( + max(memory_increase_bytes, ratio_increase) + if memory_increase_bytes is not None + else ratio_increase + ) + self.allowed_peak_memory_bytes = self.original_peak_memory + ( + memory_increase_bytes or 0 + ) + self.memory_tracker = MemoryTracker(self.graph) + else: + self.original_peak_memory = 0 + self.allowed_peak_memory_bytes = sys.maxsize + self.memory_tracker = None # type: ignore[assignment] + + self.cumulative_prefetch_mem_by_compute_index: list[int] = [ + 0 for _ in range(len(self.compute_nodes)) + ] + + self.wait_to_start: dict[fx.Node, fx.Node] = {} + self._identify_collectives() + self.wasted_compute = 0.0 + + # Bitset masks for O(N/64) pre-filtering in _find_schedulable_path. + # + # _scheduled_bits: bit i is set when node i has been scheduled. + # Updated incrementally in _schedule() via: _scheduled_bits |= 1 << idx + # + # _compute_bits: bit i is set for every compute node (fixed at init). + # Used to detect "is any unscheduled ancestor a compute node?" in O(N/64) + # instead of doing a full BFS + per-node is_compute_node() check. + self._scheduled_bits: int = 0 + self._compute_bits: int = 0 + for n in self.compute_nodes: + self._compute_bits |= self.node_ancestors.node_bit(n) + + # Calculate domination indices for both compute and reduce_scatter nodes + self.reduce_scatter_nodes = self.graph.find_nodes( + op="call_function", + target=torch.ops._c10d_functional.reduce_scatter_tensor.default, + ) + self.compute_index_domination = self._calculate_domination_index( + self.compute_nodes + ) + self.reduce_scatter_domination = self._calculate_domination_index( + self.reduce_scatter_nodes + ) + + self.in_degree = Counter(user for node in self.nodes for user in node.users) + + # Two separate queues: on-path (domination-based) and off-path (node_idx-based) + self.on_path_ready: list[tuple[object, fx.Node]] = [] + self.off_path_ready: list[tuple[object, fx.Node]] = [] + # Track potential bucket sizes for off-path collectives (for batch scheduling) + self.off_path_ready_potential_buckets: dict[object, int] = defaultdict(int) + + for node in self.nodes: + if self.in_degree[node] == 0: + self._add_to_ready_queue(node) + + self.in_flight: dict[fx.Node, CollectiveInfo] = {} # start -> info + self.in_flight_bytes = 0 + self.scheduled: OrderedSet[fx.Node] = OrderedSet() + self.max_compute_pre_fetch = max_compute_pre_fetch + + self.last_on_path_node_idx = -1 + + def _add_to_ready_queue(self, node: fx.Node) -> None: + if self.off_compute_path(node): + score = self._compute_off_path_score(node) + heapq.heappush(self.off_path_ready, (score, node)) + # Track potential bucket sizes for off-path ready collectives + if node in self.collective_info: + bucket_key = get_full_bucket_key(node, self.bucket_mode) + node_bytes = self.collective_info[node].size_bytes + self.off_path_ready_potential_buckets[bucket_key] += node_bytes + else: + score = self._compute_on_path_score(node) + heapq.heappush(self.on_path_ready, (score, node)) + + def _collect_node_ancestors(self) -> BitsetAncestors: + """Collect all ancestors for each node using int-bitset representation.""" + return BitsetAncestors(self.nodes) + + def _compute_baseline_memory(self) -> int: + """ + Simulate the original schedule to compute baseline memory profile. + Returns the peak memory observed during simulation. + """ + baseline_tracker = MemoryTracker(self.graph) + + last_compute_max_memory = 0 + peak_memory = 0 + + for node in self.nodes: + baseline_tracker.schedule_node(node) + current_mem = baseline_tracker.current_memory_bytes + + # Record the max memory between this and previous compute node + last_compute_max_memory = max(last_compute_max_memory, current_mem) + + if is_compute_node(node): + self.original_mem_before_compute_index.append(last_compute_max_memory) + last_compute_max_memory = current_mem + + peak_memory = max(peak_memory, current_mem) + + return peak_memory + + def _prefetch_would_exceed_memory_budget(self, start_node: fx.Node) -> bool: + """ + Check if prefetching this collective would exceed memory budget at ANY compute node + between now and when it's used. + """ + info = self.collective_info[start_node] + size = info.size_bytes + + domination_index = self.compute_index_domination[start_node] + + # If off-path, assume it doesn't increase memory + if domination_index == sys.maxsize: + return False + + # check current mem + if ( + self.memory_tracker.current_memory_bytes + size + > self.allowed_peak_memory_bytes + ): + return True + + start_index = self.current_compute_index + + # then, check future mem + for compute_idx in range(start_index, domination_index): + cumulative_prefetch = self.cumulative_prefetch_mem_by_compute_index[ + compute_idx + ] + + # Check 1: Would cumulative prefetch exceed in-flight limit? + if (cumulative_prefetch + size) > self.max_in_flight_bytes: + return True + + # Check 2: Would total memory (baseline + cumulative prefetch) exceed budget? + baseline_mem = self.original_mem_before_compute_index[compute_idx] + projected = baseline_mem + cumulative_prefetch + size + + if projected > self.allowed_peak_memory_bytes: + return True + + return False + + def _update_cumulative_prefetch_memory( + self, collective: fx.Node, info: CollectiveInfo + ) -> None: + """ + Update cumulative prefetch memory for all compute indices this collective will be live. + """ + domination_index = self.compute_index_domination[collective] + if domination_index == sys.maxsize: + return + + for compute_idx in range(self.current_compute_index, domination_index): + self.cumulative_prefetch_mem_by_compute_index[compute_idx] += ( + info.size_bytes + ) + + def off_compute_path(self, n: fx.Node) -> bool: + """Check if a node is off the compute path (doesn't block any compute).""" + return self.compute_index_domination[n] == sys.maxsize + + def dominates_reduce_scatter(self, n: fx.Node) -> bool: + """Check if a node dominates (blocks) any reduce_scatter.""" + return self.reduce_scatter_domination[n] != sys.maxsize + + def _identify_collectives(self) -> None: + """Identify all collective operations and process groups.""" + self.all_pgs: OrderedSet[str] = OrderedSet() + + for node in self.nodes: + if _schedulable_wait_node(node): + start = _get_collective_node_from_wait(node) + if start is None: + raise AssertionError("wait node has no associated collective") + if start not in self.node_estimations: + raise AssertionError( + f"Missing estimation for collective {start.name}. " + f"Ensure custom_runtime_estimation returns a value for this node." + ) + self.wait_to_start[node] = start + # For coalesced collectives, multiple waits share the same + # start node. Only register the first wait as the representative. + if start in self.collective_info: + continue + coll_time_ms = self.node_estimations[start] + + info = CollectiveInfo( + start_node=start, + wait_node=node, + size_bytes=estimate_fx_collective_memory_footprint(start), + estimated_time_ms=coll_time_ms, + exposed_time_ms=coll_time_ms, # Initially fully exposed + ) + self.collective_info[start] = info + self.unscheduled_collectives.add(start) + self.all_pgs.add(get_group_name(start)) + + def _calculate_domination_index( + self, target_nodes: list[fx.Node] + ) -> dict[fx.Node, int]: + """ + Calculate the topological index of the earliest target node each node dominates. + + target_nodes are assigned indices based on their topological order (0, 1, 2, ...). + For each node, returns the minimum index of target nodes it blocks/dominates. + Returns sys.maxsize if the node doesn't block any target nodes. + """ + target_set = OrderedSet(target_nodes) + target_node_index: dict[fx.Node, int] = {} + for node in self.graph.nodes: + if node in target_set: + target_node_index[node] = len(target_node_index) + + domination_index: dict[fx.Node, int] = {} + for node in reversed(self.graph.nodes): + if node in target_node_index: + domination_index[node] = target_node_index[node] + else: + domination_index[node] = min( + (domination_index[succ] for succ in node.users), default=sys.maxsize + ) + + return domination_index + + def _align_compute_nodes_runtime_estimations_across_all_distributed_ranks( + self, + ) -> None: + """Align runtime estimations across ranks (compute + collectives).""" + log.info( + "Overlap scheduling: Aligning runtime estimations across all distributed ranks" + ) + + # Benchmark compute nodes + runtime_estimations_keys: list[str | None] = [] + runtime_estimations: list[float] = [] + compute_key_count = 0 + + # Also collect analytical estimations for logging + runtime_estimations_analytical: list[float] = [] + + for n in self.compute_nodes: + # Compute analytical estimation using roofline model + val_analytical = estimate_roofline_runtime_ms(n) + runtime_estimations_analytical.append(val_analytical) + + if self.compute_estimator == "benchmark": + val, key = benchmark_node_with_cache_key( + n, self.custom_runtime_estimation + ) + else: + # Use analytical estimation + val, key = val_analytical, None + + runtime_estimations.append(val) + runtime_estimations_keys.append(key) + compute_key_count += 1 + + # Log compute estimations + from torch._inductor.fx_passes.node_runtime_estimation import ( + _log_compute_estimations, + ) + + _log_compute_estimations( + self.compute_nodes, + runtime_estimations, + runtime_estimations_analytical, + ) + + # Benchmark collectives if enabled (only CUDA events - others are deterministic) + # Skip if custom estimation is provided for collectives + collective_nodes: list[fx.Node] = [] + benchmarked_collective_nodes: list[ + fx.Node + ] = [] # Track which were actually benchmarked + if self.collective_estimator == "benchmark": + from torch._inductor.fx_passes.node_runtime_estimation import ( + benchmark_collective_with_cuda_events, + ) + + collective_nodes = [ + info.start_node for info in self.collective_info.values() + ] + + # Benchmark CUDA events (non-deterministic, needs alignment) + # Skip collectives with custom estimation + for n in collective_nodes: + if ( + get_custom_estimation(n, self.custom_runtime_estimation, None) + is not None + ): + continue + + # Benchmark actual size + cuda_val, cuda_key = benchmark_collective_with_cuda_events(n, nruns=5) + if cuda_val is not None: + runtime_estimations.append(cuda_val) + runtime_estimations_keys.append(cuda_key) + benchmarked_collective_nodes.append(n) + + # When both estimators are analytical, estimates are deterministic across ranks + # (same shapes = same estimates), so skip the all_gather to avoid sync. + import torch.distributed as dist + + world_size = dist.get_world_size() + + if ( + self.compute_estimator == "analytical" + and self.collective_estimator == "analytical" + ): + median_runtime_estimations = runtime_estimations + else: + # Single all_gather and compute medians + from torch._subclasses.fake_tensor import unset_fake_temporarily + from torch.distributed.distributed_c10d import _get_default_group + + pg = _get_default_group() + with unset_fake_temporarily(): + gathered_runtime_estimations: list[list[float]] = [ + [] for _ in range(world_size) + ] + dist.all_gather_object( + gathered_runtime_estimations, runtime_estimations, pg + ) + median_runtime_estimations = torch.median( + torch.tensor(gathered_runtime_estimations), dim=0 + ).values.tolist() + + # Cache medians + collective_keys = [] + collective_medians = [] + for idx, (key, median_runtime_estimation) in enumerate( + zip(runtime_estimations_keys, median_runtime_estimations) + ): + if key is None: + continue + if idx < compute_key_count: + # Compute node + self.node_estimations[self.compute_nodes[idx]] = ( + median_runtime_estimation + ) + set_cached_node_time(key, median_runtime_estimation) + else: + # Collective CUDA event benchmark + from torch._inductor.fx_passes.node_runtime_estimation import ( + set_cached_runtime, + ) + + set_cached_runtime(key, median_runtime_estimation) + + # Update CollectiveInfo with aligned benchmark + coll_idx = idx - compute_key_count + coll_node = benchmarked_collective_nodes[coll_idx] + info = self.collective_info[coll_node] + info.estimated_time_ms = median_runtime_estimation + info.exposed_time_ms = median_runtime_estimation + self.node_estimations[coll_node] = median_runtime_estimation + + collective_keys.append(key) + collective_medians.append(median_runtime_estimation) + + # Log benchmarks with analytical comparisons + if collective_keys: + from torch._inductor.fx_passes.node_runtime_estimation import ( + _log_collective_benchmarks, + ) + + _log_collective_benchmarks( + benchmarked_collective_nodes, + collective_keys, + collective_medians, + world_size, + "fx_collectives_node_runtime_estimation", + ) + else: + # No benchmarking - log analytical estimations for all collectives + from torch._inductor.fx_passes.node_runtime_estimation import ( + _log_collective_benchmarks, + ) + + all_collective_nodes = [ + info.start_node for info in self.collective_info.values() + ] + if all_collective_nodes: + _log_collective_benchmarks( + all_collective_nodes, + artifact_name="fx_collectives_analytical_estimation", + ) + + log.info("Overlap scheduling: Runtime estimations aligned") + + def _get_next_nodes(self) -> list[fx.Node]: + """ + Get next node(s) to schedule. + + When max_off_bucket_bytes is set, off-path collectives of the same type + (same bucket_key) are batched together to enable bucketing them in + overlap_preserving_bucketer. Bucket size is limited by max_off_bucket_bytes. + """ + if self.off_path_ready: + _, node = self.off_path_ready[0] + + should_schedule = False + if not self.on_path_ready or node in self.scheduled: + should_schedule = True + elif _schedulable_wait_node(node): + # Defer exposed waits until hidden or over memory budget + info = self.collective_info[self.wait_to_start[node]] + over_budget = ( + self.memory_tracker.current_memory_bytes + > self.allowed_peak_memory_bytes + ) + should_schedule = not info.is_exposed or over_budget + elif self.max_off_bucket_bytes is not None and node in self.collective_info: + # Batch off-path collectives: schedule when bucket threshold is reached + bucket_key = get_full_bucket_key(node, self.bucket_mode) + bucket_size = self.off_path_ready_potential_buckets[bucket_key] + should_schedule = bucket_size >= self.max_off_bucket_bytes + elif self.dominates_reduce_scatter(node): + # Only schedule off-path nodes that dominate reduce_scatters after original position + should_schedule = self.node_idx[node] <= self.last_on_path_node_idx + + if should_schedule: + heapq.heappop(self.off_path_ready) + + # If batching enabled and this is a collective, gather same-type collectives + if ( + self.max_off_bucket_bytes is not None + and node in self.collective_info + ): + node_key = get_full_bucket_key(node, self.bucket_mode) + if node_key is not None: + same_type_nodes = [node] + total_bytes = self.collective_info[node].size_bytes + indices_to_remove = [] + + # Scan the off_path_ready queue for same-key collectives + for i, (_, candidate) in enumerate(self.off_path_ready): + if candidate in self.scheduled: + continue + if candidate not in self.collective_info: + continue + candidate_key = get_full_bucket_key( + candidate, self.bucket_mode + ) + if candidate_key == node_key: + candidate_bytes = self.collective_info[ + candidate + ].size_bytes + # Check bucket size limit before adding + if ( + total_bytes + candidate_bytes + > self.max_off_bucket_bytes + ): + continue # Skip but keep looking for smaller ones + same_type_nodes.append(candidate) + total_bytes += candidate_bytes + indices_to_remove.append(i) + + # Remove collected nodes from heap (reverse order to preserve indices) + for i in reversed(indices_to_remove): + self.off_path_ready.pop(i) + if indices_to_remove: + heapq.heapify(self.off_path_ready) + + return same_type_nodes + + return [node] + + return [heapq.heappop(self.on_path_ready)[1]] + + def run(self) -> torch.fx.GraphModule: + """Run the scheduling algorithm.""" + # All ranks must make identical decisions on overlap reordering, + # Thus we must have identical runtime estimations across ranks. + # For now we do benchmarking only for compute nodes. + self._align_compute_nodes_runtime_estimations_across_all_distributed_ranks() + + while self.on_path_ready or self.off_path_ready: + if self._should_force_wait_for_memory(): + self._force_oldest_wait() + continue + + nodes = self._get_next_nodes() + + for node in nodes: + # we don't always remove nodes from the heap when we schedule them + if node in self.scheduled: + continue + + if node.op == "placeholder": + self._schedule(node) + elif node in self.collective_info: + self._handle_collective_start(node) + elif _schedulable_wait_node(node): + self._handle_wait(node) + else: + self._handle_compute_or_other(node) + + # Track progress for off-path scheduling - only for nodes from main queue + if not self.off_compute_path(node): + self.last_on_path_node_idx = max( + self.last_on_path_node_idx, self.node_idx[node] + ) + else: + # Decrement off-path bucket bytes when scheduling + if node in self.collective_info: + bucket_key = get_full_bucket_key(node, self.bucket_mode) + node_bytes = self.collective_info[node].size_bytes + self.off_path_ready_potential_buckets[bucket_key] -= node_bytes + + self._reorder_graph() + + # Finalize: bucket collectives (if enabled), apply deps + from torch._inductor.fx_passes.overlap_preserving_bucketer import ( + finalize_overlap_scheduling, + ) + + finalize_overlap_scheduling( + gm=self.gm, + collective_info=self.collective_info, + scheduled=self.scheduled, + collective_bucketing=self.collective_bucketing, + insert_overlap_deps=self.insert_overlap_deps, + max_bucket_memory_gb=2.0, + max_coll_distance=self.max_node_distance, + bucket_exposed_first=self.bucket_exposed_first, + bucket_only_internode_comms=self.bucket_only_internode_comms, + bucket_mode=self.bucket_mode, + ) + + if self.log_final_collectives_estimations: + from torch._inductor.fx_passes.node_runtime_estimation import ( + _log_graph_collective_benchmarks, + ) + + _log_graph_collective_benchmarks( + self.gm, "fx_collectives_estimations_after_overlap_bucketing" + ) + + return self.gm + + def _reduce_exposed_time_of_in_flight_collectives( + self, + node: fx.Node, + available_compute: float, + exclude_pg: str | None = None, + ) -> dict[str, float]: + """ + Reduce exposed time of in-flight collectives using available compute time. + + Collectives on different process groups can overlap simultaneously with the same + compute, so we track remaining time separately per PG. + """ + # Initialize all PGs with full available compute (except excluded) + remaining_time_per_pg: dict[str, float] = { + pg: available_compute for pg in self.all_pgs if pg != exclude_pg + } + + for start_node, info in self.in_flight.items(): + if info.exposed_time_ms == 0: + continue + + pg_name = get_group_name(start_node) + if pg_name == exclude_pg: + continue + + pg_remaining = remaining_time_per_pg[pg_name] + if pg_remaining <= 0: + continue + + overlap_amount = min(info.exposed_time_ms, pg_remaining) + info.exposed_time_ms -= overlap_amount + remaining_time_per_pg[pg_name] -= overlap_amount + info.hiding_nodes.add(node) + + return remaining_time_per_pg + + def _handle_compute_or_other(self, node: fx.Node) -> None: + """Handle scheduling compute or other nodes and attempt to overlap with collectives.""" + runtime_estimate = self.node_estimations.get(node) + + # TODO: we could consider skipping overlapping for overlapable, unary chains to collectives. + # using these nodes for overlap prevents bucketing. potentially if chain time < latency + if runtime_estimate is None: + if is_compute_node(node): + raise AssertionError("should have estimate for compute nodes") + self._schedule(node) + return + if runtime_estimate == 0 and not is_compute_node(node): + self._schedule(node) + return + + available_compute = runtime_estimate * self.compute_overlap_multipler + + # First, reduce exposed time of in-flight collectives (per PG) + remaining_time_per_pg = self._reduce_exposed_time_of_in_flight_collectives( + node, available_compute + ) + # Then, schedule new collectives for overlap + self._schedule_collectives_for_overlap(node, remaining_time_per_pg) + self._schedule(node) + + if is_compute_node(node): + self.current_compute_index += 1 + + def _schedule(self, node: fx.Node) -> None: + """Schedule a node.""" + if node in self.scheduled: + raise AssertionError(f"node {node} already scheduled") + if not all(n in self.scheduled for n in node.all_input_nodes): + raise AssertionError(f"node {node} has unscheduled input nodes") + self.scheduled.add(node) + self._scheduled_bits |= self.node_ancestors.node_bit(node) + self.memory_tracker.schedule_node(node) + + log.debug( + "Scheduled node %s: current_memory=%d bytes, total_scheduled=%d", + node.name, + self.memory_tracker.get_current_memory_bytes(), + len(self.scheduled), + ) + + for user in node.users: + self.in_degree[user] -= 1 + if self.in_degree[user] == 0: + self._add_to_ready_queue(user) + + def _compute_on_path_score(self, node: fx.Node) -> object: + """Compute priority score for on-path nodes (domination-based).""" + if _schedulable_wait_node(node): + info = self.collective_info[self.wait_to_start[node]] + # defer waits locally if they are exposed. + compute_local_priority = int(info.is_exposed) + else: + # if we're scheduling this collective via its queue, then it was not + # pre-fetched. we might as well maximize overlap for the + # local, non-mm nodes prior to the next compute node. + if self.in_overlappable_collective_unary_chain(node): + compute_local_priority = -1 + else: + compute_local_priority = 0 + + return ( + self.compute_index_domination[node], # what index compute it blocks + compute_local_priority, # collective_start=-1, wait=1, or neither=0 + self.node_idx[node], # Original order for stability + ) + + def _compute_off_path_score(self, node: fx.Node) -> object: + """ + Off-path priority scoring. + + Nodes that dominate reduce_scatters are prioritized (lower score = higher priority) + to ensure they get scheduled eagerly for potential overlap. + """ + dominates_rs = 0 if self.dominates_reduce_scatter(node) else 1 + return (dominates_rs, self.node_idx[node]) + + @staticmethod + def is_cheap_fn(node: fx.Node) -> bool: + return getattr(node.target, "is_view", False) or torch.Tag.pointwise in getattr( + node.target, "tags", () + ) + + def in_overlappable_collective_unary_chain(self, curr: fx.Node) -> bool: + while True: + if len(curr.users) != 1: + return False + + user = next(iter(curr.users)) + if len(user.all_input_nodes) != 1: + return False + + if user in self.unscheduled_collectives: + return True + + if not self.is_cheap_fn(user): + return False + + curr = user + + return False + + def _should_force_wait_for_memory(self) -> bool: + """Check if we need to force a wait due to memory pressure""" + if not self.in_flight: + return False + + return self.in_flight_bytes >= self.max_in_flight_bytes + + def _force_oldest_wait(self) -> None: + """Schedule the oldest in flight wait""" + self._handle_wait(self._get_oldest_wait()) + + def _handle_collective_start(self, node: fx.Node) -> None: + """Handle scheduling a collective start.""" + info = self.collective_info[node] + + if self.should_assume_bucketed(node): + latency = estimate_collective_time( + node, 0, custom_runtime_estimation=self.custom_runtime_estimation + ) + info.exposed_time_ms = max(0, info.exposed_time_ms - latency) + + self.in_flight[node] = info + self.in_flight_bytes += info.size_bytes + self.unscheduled_collectives.discard(node) + self._schedule(node) + + def _handle_wait(self, node: fx.Node) -> None: + """Handle scheduling a wait.""" + if node not in self.wait_to_start: + raise AssertionError(f"wait node {node} has no associated start") + coll_start = self.wait_to_start[node] + # For coalesced collectives, multiple waits share the same start node. + # The first wait completes the collective; subsequent waits just schedule. + if coll_start not in self.in_flight: + self._schedule(node) + return + + # Scheduling a wait of a collective also forces the wait + # of every node enqueued prior to the collective on the + # same process group + group_name = get_group_name(coll_start) + to_schedule: list[fx.Node] = [] + for in_flight_coll in self.in_flight: + if in_flight_coll == coll_start: + break + if get_group_name(in_flight_coll) == group_name: + to_schedule.append(in_flight_coll) + + for coll_to_schedule in to_schedule: + self._handle_wait(self.collective_info[coll_to_schedule].wait_node) + + # If we are waiting on an exposed collective, use this time to + # overlap on other PGs. + info = self.collective_info[coll_start] + if info.exposed_time_ms > 0: + exposed_time = info.exposed_time_ms + exclude_pg = group_name + + remaining_time_per_pg = self._reduce_exposed_time_of_in_flight_collectives( + node, exposed_time, exclude_pg=exclude_pg + ) + self._schedule_collectives_for_overlap( + node, remaining_time_per_pg, exclude_pg=exclude_pg + ) + + self.in_flight_bytes -= self.in_flight[coll_start].size_bytes + del self.in_flight[coll_start] + self._schedule(node) + + def _schedule_collectives_for_overlap( + self, + overlap_node: fx.Node, + remaining_time_per_pg: dict[str, float], + exclude_pg: str | None = None, + ) -> None: + """Opportunistically schedule collectives that can be hidden by available overlap time.""" + if not remaining_time_per_pg or all( + t <= 0 for t in remaining_time_per_pg.values() + ): + return + + # Compile candidates - limit by number of plausible candidates to bound + # compile time. Do not stop after seeing max_node_distance raw entries: + # early entries may be filtered by PG/prefetch distance, while later + # entries can still use the current overlap window. + candidates = [] + for collective in self.unscheduled_collectives: + pg_name = get_group_name(collective) + if pg_name == exclude_pg: + continue + + pg_available_time = remaining_time_per_pg.get(pg_name, 0.0) + if pg_available_time <= 0: + continue + + if ( + not self.off_compute_path(collective) + and self.compute_index_domination[collective] + - self.current_compute_index + > self.max_compute_pre_fetch + ): + continue + + candidates.append(collective) + if len(candidates) >= self.max_node_distance: + break + + def get_priority(n: fx.Node) -> int: + dominates_next_compute = ( + self.compute_index_domination[n] == self.current_compute_index + 1 + ) + if dominates_next_compute: + return 0 # Dominates next compute layer - most urgent + elif self.off_compute_path(n) and self.dominates_reduce_scatter(n): + return 1 # Off-path but blocks reduce_scatter + elif not self.off_compute_path(n): + return 2 # On-path but not immediate + else: + return 3 # Off-path, doesn't block reduce_scatter + + def overlap_priority(n: fx.Node) -> tuple[int, int, float, int]: + return ( + get_priority(n), + self.compute_index_domination[n], + -min( + remaining_time_per_pg.get(get_group_name(n), 0.0), + self.collective_info[n].exposed_time_ms, + ), + self.node_idx[n], + ) + + candidates.sort(key=overlap_priority) + + if self.prioritize_bucketing_during_scheduling: + # group candidates by bucket key first so same-bucket + # collectives are scheduled together, maximizing bucketing opportunities + bucket_groups: dict[object, list[fx.Node]] = defaultdict(list) + for coll in candidates: + key = get_full_bucket_key(coll, self.bucket_mode) + bucket_groups[key].append(coll) + + # Sort bucket groups by the best candidate priority in each group, + # with larger groups first as tiebreaker. + sorted_bucket_keys = sorted( + bucket_groups.keys(), + key=lambda k: ( + min(overlap_priority(c) for c in bucket_groups[k]), + -len(bucket_groups[k]), + ), + ) + + # Flatten back to ordered candidate list + candidates = [] + for b_key in sorted_bucket_keys: + group = bucket_groups[b_key] + group.sort(key=overlap_priority) + candidates.extend(group) + + for collective in candidates: + pg_name = get_group_name(collective) + pg_available_time = remaining_time_per_pg[pg_name] + + if pg_available_time <= 0: + continue + + why = WhyNoOverlap(overlap_node, collective) + info = self.collective_info[collective] + + if self.node_ancestors.has_dep(overlap_node, collective): + why("dependency conflict") + continue + + # Check if prefetching would exceed memory budget + if self._prefetch_would_exceed_memory_budget(collective): + why("prefetch would exceed memory budget") + continue + + # Try to free memory by forcing hidden waits + while ( + self.in_flight + and (self.max_in_flight_bytes - self.in_flight_bytes) < info.size_bytes + and self._wait_is_hidden(self._get_oldest_wait(), overlap_node) + ): + self._force_oldest_wait() + + if (self.max_in_flight_bytes - self.in_flight_bytes) < info.size_bytes: + why("in-flight memory limit") + continue + + # Check if we can reach this collective without scheduling compute, other collectives, or waits + path = self._find_schedulable_path(collective, overlap_node, why) + if path is None: + continue + + log.debug( + "Overlapping collective %s with node %s: coll_domination=%d, current_depth=%d", + collective.name, + overlap_node.name, + self.compute_index_domination[collective], + self.current_compute_index, + ) + + # TODO: We previously tracked path compute time and added it back to available + # overlap time. With per-PG tracking this is complex: if there were in-flight + # collectives on one PG but not another, we can't add path time back to the PG + # that wasn't in-flight + + # Schedule path and collective + self._schedule_path_to_collective(path, overlap_node) + self._handle_collective_start(collective) + self._update_cumulative_prefetch_memory(collective, info) + + # Update exposed time for this collective + overlap_amount = min(pg_available_time, info.exposed_time_ms) + info.exposed_time_ms -= overlap_amount + info.hiding_nodes.add(overlap_node) + + # Update available time for this PG + remaining_time_per_pg[pg_name] -= overlap_amount + + if sum(remaining_time_per_pg.values()) == 0: + break + + if remaining_time_per_pg: + self.wasted_compute += min(remaining_time_per_pg.values()) + + def _find_schedulable_path( + self, target: fx.Node, curr_overlap_node: fx.Node | None, why: WhyNoOverlap + ) -> OrderedSet[fx.Node] | None: + """Find path to target by collecting unscheduled dependencies. + + Called O(C * K) times where C = compute nodes and K = unscheduled + collectives. Most calls return None because the collective has + unscheduled compute ancestors. The bitset pre-filter below answers + this in O(N/64) using three bitwise operations, avoiding a full + backward BFS in the majority of cases. + """ + # Bitset pre-filter: O(N/64) check that avoids BFS in most cases. + ancestor_bits = self.node_ancestors.get_ancestor_bits(target) + unscheduled_bits = ancestor_bits & ~self._scheduled_bits + if unscheduled_bits & self._compute_bits: + why("bitset: unscheduled compute ancestor") + return None + + # No unscheduled ancestors at all -- path is trivially clear. + if not unscheduled_bits: + return OrderedSet() + + # Pre-filter passed (rare): fall through to BFS for exact check + # (the pre-filter only checks compute nodes; BFS also checks for + # unscheduled collectives and wait-node conflicts). + + # Backward BFS from target; stops at scheduled nodes. + target_idx = self.node_idx[target] + unscheduled_ancestors: OrderedSet[fx.Node] = OrderedSet() + seen: OrderedSet[fx.Node] = OrderedSet() + parent_lists = self._parent_lists + node_idx = self.node_idx + stack = parent_lists[target_idx][:] + scheduled = self.scheduled + while stack: + n = stack.pop() + if n in seen or n in scheduled: + continue + seen.add(n) + unscheduled_ancestors.add(n) + stack.extend(parent_lists[node_idx[n]]) + + # only schedule non distributed, non compute nodes + for node in unscheduled_ancestors: + if is_compute_node(node): + why("path blocked by compute node %s", node.name) + return None + + if node in self.unscheduled_collectives: + why("path blocked by unscheduled collective %s", node.name) + return None + + # if we schedule a wait tensor whose start collective is hidden by the + # current compute node we are scheduling, then we are effectively exposing it. + # similarly, don't schedule a wait of a collective that could be otherwise hidden, + # thus forcing it to be exposed. + # however, if it is already hidden it's fine to schedule it + if _schedulable_wait_node(node): + info = self.collective_info[self.wait_to_start[node]] + if (not info.is_exposed) and ( + curr_overlap_node not in info.hiding_nodes + ): + continue + + why( + "path blocked by wait node %s (exposed=%s, hidden_by_curr_overlap=%s)", + node.name, + info.is_exposed, + curr_overlap_node in info.hiding_nodes, + ) + return None + + # Skip c10 ops and dtensor shard ops - they should be scheduled via main loop + target_str = str(node.target) + if "c10" in target_str or "_dtensor" in target_str: + log.debug( + "Skipping c10/dtensor op %s in path to collective", + node.name, + ) + return None + + return unscheduled_ancestors + + def should_assume_bucketed(self, node: fx.Node) -> bool: + """ + Check if there's an in-flight collective that can be bucketed with the given node. If so, assume they will bucket. + This is a optimistic heuristic to account for latency reduction with bucketing. The two nodes may not get bucketed. + """ + if not torch._inductor.config.test_configs.assume_bucketing_reduces_latency: + return False + + key = bucket_key(node, mode=self.bucket_mode) + if key is None: + return False + + for in_flight_coll in self.in_flight: + if bucket_key(in_flight_coll, mode=self.bucket_mode) == key: + return True + + return False + + def _get_oldest_wait(self) -> fx.Node: + oldest_start = next(iter(self.in_flight)) + return self.collective_info[oldest_start].wait_node + + def _wait_is_hidden( + self, wait_node: fx.Node, overlap_node: fx.Node | None = None + ) -> bool: + if not is_wait_tensor(wait_node): + raise AssertionError(f"expected a wait tensor node, got {wait_node}") + info = self.collective_info[self.wait_to_start[wait_node]] + return not info.is_exposed and overlap_node not in info.hiding_nodes + + def _schedule_path_to_collective( + self, path: OrderedSet[fx.Node], curr_overlap_node: fx.Node + ) -> None: + """Schedule all nodes needed to reach a collective.""" + + if not all(n not in self.scheduled for n in path): + raise AssertionError("path contains already-scheduled nodes") + for node in sorted(path, key=lambda n: self.node_idx[n]): + if is_compute_node(node) or node in self.unscheduled_collectives: + raise AssertionError( + f"unexpected compute or unscheduled collective node {node} in path" + ) + if _schedulable_wait_node(node): + # When we schedule wait tensors, we also force realization of all + # collectives enqueued prior to their corresponding collective. + # It's possible the scheduling of one wait tensor here has forced + # another in the path. If so, skip scheduling it. + if node in self.scheduled: + continue + + info = self.collective_info[self.wait_to_start[node]] + if curr_overlap_node in info.hiding_nodes: + raise AssertionError( + "overlap node unexpectedly in collective hiding_nodes" + ) + self._handle_wait(node) + continue + + self._schedule(node) + + def reorder_graph(self) -> None: + output_node = self.graph.output_node() + for node in self.scheduled: + if node.op == "placeholder": + continue + output_node.prepend(node) + self.graph.lint() + + def _reorder_graph(self) -> None: + """Reorder graph based on schedule.""" + exposed = [ + c + for c in self.collective_info.values() + if c.exposed_time_ms == c.estimated_time_ms + ] + + potentially_hidden_collectives = self.compute_potential_hidden_collectives() + bad_exposed = [ + c for c in exposed if c.start_node in potentially_hidden_collectives + ] + + # Compute total exposed and potential exposed time + total_exposed = sum(c.exposed_time_ms for c in self.collective_info.values()) + hideable_exposed_ms = sum( + self.collective_info[c].exposed_time_ms + for c in potentially_hidden_collectives + ) + total_potential_exposed = sum( + c.estimated_time_ms for c in self.collective_info.values() + ) + + counters["inductor"]["overlap_scheduling_exposed"] += len(exposed) + counters["inductor"]["overlap_scheduling_bad_exposed"] += len(bad_exposed) + counters["inductor"]["overlap_scheduling_potentially_hidden"] += len( + potentially_hidden_collectives + ) + counters["inductor"]["overlap_original_mem"] = self.original_peak_memory + counters["inductor"]["rescheduled_mem"] = self.memory_tracker.peak_memory + + log.info( + "Overlap scheduling results: exposed=%d, bad_exposed=%d, potentially_hidden=%d, " + "original_peak_memory=%d bytes, rescheduled_peak_memory=%d bytes, " + "total_exposed_ms=%.2f, hideable_exposed_ms=%.2f, total_potential_exposed_ms=%.2f, " + "wasted_compute_ms=%.2f", + len(exposed), + len(bad_exposed), + len(potentially_hidden_collectives), + self.original_peak_memory, + self.memory_tracker.peak_memory, + total_exposed, + hideable_exposed_ms, + total_potential_exposed, + self.wasted_compute, + ) + + self.reorder_graph() + + def _bucket_collectives(self) -> None: + from torch._inductor.fx_passes.overlap_preserving_bucketer import ( + OverlapPreservingBucketer, + ) + + bucketer = OverlapPreservingBucketer( + graph=self.graph, + collective_info=self.collective_info, + scheduled=self.scheduled, + max_bucket_memory_gb=2.0, # Could make this configurable + max_coll_distance=self.max_node_distance, + insert_overlap_deps=self.insert_overlap_deps, + bucket_mode=self.bucket_mode, + bucket_exposed_first=self.bucket_exposed_first, + bucket_only_internode_comms=self.bucket_only_internode_comms, + ) + bucketer.bucket_collectives() + + def compute_potential_hidden_nodes( + self, nodes_to_check: Iterable[fx.Node] + ) -> dict[fx.Node, fx.Node]: + """ + Returns a dict containing a mapping of nodes which could potentially be hidden to their hiding node + """ + + def could_be_hidden(start: fx.Node) -> fx.Node | None: + for compute_node in self.compute_nodes: + if not self.node_ancestors.has_dep(compute_node, start): + return compute_node + + return None + + # TODO: We could potentially limit compute nodes per overlap time, + # today, this is optimistic, and just serves to avoid deferring + # collectives/waits that have no possible overlap as well as for analysis of how + # successfully we hid compute + potentially_hidden = {} + for node in nodes_to_check: + if mm := could_be_hidden(node): + potentially_hidden[node] = mm + + return potentially_hidden + + def compute_potential_hidden_collectives(self) -> dict[fx.Node, fx.Node]: + """Compute which collective operations could be hidden by compute.""" + return self.compute_potential_hidden_nodes(self.collective_info.keys()) + + def compute_potential_hidden_waits(self) -> dict[fx.Node, fx.Node]: + """Compute which wait operations could be hidden by compute.""" + wait_nodes = [info.wait_node for info in self.collective_info.values()] + return self.compute_potential_hidden_nodes(wait_nodes) + + +def gather_node_runtime_estimations( + gm: torch.fx.GraphModule, + custom_runtime_estimation: Callable[[fx.Node, int | None], float | None] + | None = None, + collective_estimator: Literal["analytical", "benchmark"] = "analytical", + enable_fusion_regions: bool = False, + log_estimations: bool = False, +) -> dict[fx.Node, float]: + """Gather initial runtime estimations for all nodes without scheduling. + + Uses analytical models (roofline) for compute nodes -- the alignment step + in OverlapScheduler.run() replaces these with benchmarked + cross-rank-aligned + values. Collectives use bandwidth formulas or CUDA events depending on + collective_estimator. + + When enable_fusion_regions is True, builds fusion regions and corrects + per-node I/O costs to account for fusion (no graph mutation). + + Args: + collective_estimator: "analytical" uses bandwidth formulas, + "benchmark" uses CUDA events for collectives. + log_estimations: When True, log compute and collective estimations + via trace_structured for tlparse. + + Returns estimations mapping fx.Node to runtime in ms. + """ + fused_costs: dict[fx.Node, float] = {} + if enable_fusion_regions: + from torch._inductor.fx_passes.fusion_regions import ( + build_fusion_regions, + estimate_fused_node_costs, + ) + + raw_regions = build_fusion_regions(gm) + if raw_regions: + fused_costs = estimate_fused_node_costs(raw_regions) + + estimations: dict[fx.Node, float] = {} + nodes = list(gm.graph.nodes) + + # Collectives + collective_nodes: list[fx.Node] = [] + for node in nodes: + if _schedulable_wait_node(node): + start = _get_collective_node_from_wait(node) + if start is None: + raise AssertionError("wait node has no associated collective") + if start in estimations: + continue + estimations[start] = estimate_collective_time( + start, + custom_runtime_estimation=custom_runtime_estimation, + collective_estimator=collective_estimator, + ) + collective_nodes.append(start) + + # Compute nodes (matmul, bmm, etc.) — analytical estimates only. + # The alignment step in run() replaces these with benchmarked + aligned values. + compute_nodes: list[fx.Node] = [] + compute_analytical: list[float] = [] + + for node in nodes: + if is_compute_node(node): + est = estimate_roofline_runtime_ms(node) + if custom_runtime_estimation is not None: + custom_est = custom_runtime_estimation(node, None) + if custom_est is not None: + est = custom_est + estimations[node] = est + compute_nodes.append(node) + compute_analytical.append(est) + elif node.op == "call_function" and node not in estimations: + if custom_runtime_estimation is not None: + est = custom_runtime_estimation(node, None) + if est is not None: + estimations[node] = est + else: + est = estimate_roofline_runtime_ms(node) + if est > 0: + estimations[node] = est + + # Apply fused costs: replace individual I/O estimates with fusion-aware ones + estimations.update(fused_costs) + + # Logging + if log_estimations and compute_nodes: + from torch._inductor.fx_passes.node_runtime_estimation import ( + _log_compute_estimations, + ) + + _log_compute_estimations( + compute_nodes, + compute_analytical, + compute_analytical, + ) + + # Skip analytical logging when a custom estimator is provided: the + # analytical estimates weren't used for scheduling, and the logging + # path calls into NCCL estimation which can crash when group_name + # is an FX Node (compile-on-one-rank graphs). + if log_estimations and collective_nodes and custom_runtime_estimation is None: + from torch._inductor.fx_passes.node_runtime_estimation import ( + _log_collective_benchmarks, + ) + + _log_collective_benchmarks( + collective_nodes, + artifact_name="fx_collectives_analytical_estimation", + ) + + return estimations + + +def align_estimations_across_ranks( + estimations: dict[fx.Node, float], +) -> dict[fx.Node, float]: + """Align runtime estimations across distributed ranks using median. + + All ranks must make identical scheduling decisions, so we gather each + rank's values and take the median. All nodes in estimations are aligned. + + Returns a new estimations dict with aligned values. + """ + import torch.distributed as dist + from torch._subclasses.fake_tensor import unset_fake_temporarily + from torch.distributed.distributed_c10d import _get_default_group + + nodes = list(estimations.keys()) + if not nodes: + return {} + + local_values = [estimations[n] for n in nodes] + + world_size = dist.get_world_size() + pg = _get_default_group() + + with unset_fake_temporarily(): + gathered: list[list[float]] = [[] for _ in range(world_size)] + dist.all_gather_object(gathered, local_values, pg) + medians = torch.median(torch.tensor(gathered), dim=0).values.tolist() + + return dict(zip(nodes, medians)) + + +def schedule_overlap_bucketing( + gm: torch.fx.GraphModule, + max_in_flight_gb: float = 5, + max_compute_pre_fetch: int = 200, + collective_bucketing: bool = False, + insert_overlap_deps: bool = False, + compute_overlap_multipler: float = 1.0, + max_coll_distance: int = 200, + custom_runtime_estimation: Callable[[fx.Node, int | None], float | None] + | None = None, + collective_estimator: Literal["analytical", "benchmark"] = "analytical", + compute_estimator: Literal["analytical", "benchmark"] = "benchmark", + max_memory_increase_gb: float | None = 1.0, + max_memory_increase_ratio: float | None = 0.05, + log_final_collectives_estimations: bool = False, + bucket_exposed_first: bool | None = None, + enable_fusion_regions: bool = False, + bucket_only_internode_comms=False, + prioritize_bucketing_during_scheduling: bool = True, + max_off_bucket_gb: float | None = 0.5, + bucket_mode: BucketMode | None = None, + pge_profile_path: str | None = None, + pre_bucketing_fsdp_collectives: bool = True, + pre_bucketing_fsdp_collectives_bucket_cap_mb: float | None = None, +) -> torch.fx.GraphModule: + """Schedule nodes to maximize compute-collective overlap. + + Args: + gm: Input graph module to optimize. + max_in_flight_gb: Maximum GB of concurrent collective data. Too much in flight memory + can cause memory fragmentation within the CUDA Caching Allocator. + max_compute_pre_fetch: Maximum mm nodes to pre fetch. Note: should already be limited by max_in_flight_gb and + max_memory_increase_gb + collective_bucketing: Enable overlap-preserving collective bucketing. + insert_overlap_deps: Insert overlap dependencies using control deps operator. This should only be used if + compiling with inductor, or for subsequent passes before removing the ops prior to execution. + compute_overlap_multipler: Scale factor for compute time used to hide collectives. This can be used + to address over or under aggressive overlapping. + max_coll_distance: Maximum pre fetch or bucketing candidates. Mainly intended for compile time + custom_runtime_estimation: Override runtime estimation for specific nodes. Called as + custom_runtime_estimation(node, override_size) -> float | None. To pass pre-computed + estimations, wrap a dict: lambda node, _: estimations.get(node). + collective_estimator: Method for estimating collective runtime. "analytical" uses bandwidth formulas, + "benchmark" uses CUDA events with power-of-2 rounding and interpolation. + compute_estimator: Method for estimating compute (ATen op) runtime. "analytical" uses roofline model + estimates (deterministic, no GPU sync), "benchmark" uses GPU benchmarking (more accurate). + max_memory_increase_gb: Maximum GB increase above baseline memory (absolute cap). If None, no absolute limit. + max_memory_increase_ratio: Maximum increase as ratio of baseline peak memory. If None, no ratio limit. + Uses minimum of absolute and ratio limits when both are specified. + enable_fusion_regions: Enable fusion region detection and cost estimation for fusible ops. + bucket_mode: Bucketing mode for grouping collectives. + pre_bucketing_fsdp_collectives: Pre-bucket FSDP collectives into bandwidth-saturating + buckets before overlap scheduling. + pre_bucketing_fsdp_collectives_bucket_cap_mb: Override bucket cap in MB for pre-bucketing. + When None, auto-computes based on NCCL bandwidth model. + """ + if not gm.graph.find_nodes( + op="call_function", + target=torch.ops._c10d_functional.wait_tensor.default, + ): + return gm + + if pre_bucketing_fsdp_collectives: + from torch._inductor.fx_passes.fsdp import pre_bucket_fsdp_collectives + + pre_bucket_fsdp_collectives( + gm, + mode=bucket_mode, + bucket_cap_mb=pre_bucketing_fsdp_collectives_bucket_cap_mb, + ) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "overlap_scheduling_graph_before", + "encoding": "string", + }, + payload_fn=lambda: gm.print_readable(False), + ) + ret = OverlapScheduler( + gm, + compute_overlap_multipler=compute_overlap_multipler, + max_in_flight_gb=max_in_flight_gb, + max_coll_distance=max_coll_distance, + max_compute_pre_fetch=max_compute_pre_fetch, + custom_runtime_estimation=custom_runtime_estimation, + collective_bucketing=collective_bucketing, + insert_overlap_deps=insert_overlap_deps, + collective_estimator=collective_estimator, + compute_estimator=compute_estimator, + max_memory_increase_gb=max_memory_increase_gb, + max_memory_increase_ratio=max_memory_increase_ratio, + log_final_collectives_estimations=log_final_collectives_estimations, + bucket_exposed_first=bucket_exposed_first, + enable_fusion_regions=enable_fusion_regions, + bucket_only_internode_comms=bucket_only_internode_comms, + prioritize_bucketing_during_scheduling=prioritize_bucketing_during_scheduling, + max_off_bucket_gb=max_off_bucket_gb, + bucket_mode=bucket_mode, + pge_profile_path=pge_profile_path, + ).run() + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "overlap_scheduling_graph_after", + "encoding": "string", + }, + payload_fn=lambda: ret.print_readable(False), + ) + + return ret + + +def schedule_overlap_bucketing_from_inductor_configs( + gm: torch.fx.GraphModule, +) -> torch.fx.GraphModule: + """Schedule nodes to maximize compute-collective overlap using inductor configs. + + Reads configuration from torch._inductor.config.aten_distributed_optimizations + and calls schedule_overlap_bucketing with those settings. + """ + if not gm.graph.find_nodes( + op="call_function", + target=torch.ops._c10d_functional.wait_tensor.default, + ): + return gm + + from torch._inductor import config + + dist_opts = config.aten_distributed_optimizations + + kwargs: dict[str, object] = {} + + config_keys = ( + "collective_bucketing", + "max_compute_pre_fetch", + "custom_runtime_estimation", + "insert_overlap_deps", + "collective_estimator", + "compute_estimator", + "max_memory_increase_gb", + "max_memory_increase_ratio", + "compute_overlap_multipler", + "max_in_flight_gb", + "max_coll_distance", + "log_final_collectives_estimations", + "bucket_exposed_first", + "bucket_only_internode_comms", + "enable_fusion_regions", + "prioritize_bucketing_during_scheduling", + "bucket_mode", + "pre_bucketing_fsdp_collectives", + "pre_bucketing_fsdp_collectives_bucket_cap_mb", + ) + for key in config_keys: + if (val := getattr(dist_opts, key, None)) is not None: + kwargs[key] = val + + # Profile-guided latency estimation + pge_path = dist_opts.profile_guided_estimations_profile_path + if pge_path and "custom_runtime_estimation" not in kwargs: + kwargs["pge_profile_path"] = pge_path + + return schedule_overlap_bucketing(gm, **kwargs) # type: ignore[arg-type] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/pad_mm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/pad_mm.py new file mode 100644 index 0000000000000000000000000000000000000000..2d52df9717fea03cd67c8b9177ef6cda04d48c7a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/pad_mm.py @@ -0,0 +1,1025 @@ +import functools +import itertools +import operator +import typing +from collections.abc import Callable, Sequence +from typing import Any + +import torch +import torch._inductor.runtime.runtime_utils +from torch import Tensor +from torch._dynamo.utils import counters +from torch._inductor import utils +from torch._inductor.autoheuristic.autoheuristic import ( + AHContext, + AutoHeuristic, + LocalFeedback, +) +from torch._inductor.autoheuristic.autoheuristic_utils import ( + context_add_strides, + context_add_using_tf32, + pad_mm_operations, + pad_mm_precondition, +) +from torch._inductor.runtime.caching import encoders, memoizers +from torch._subclasses.fake_tensor import is_fake_tensor +from torch.fx.experimental.symbolic_shapes import statically_known_true +from torch.utils._mode_utils import no_dispatch + +from ...utils._triton import has_triton +from ..pattern_matcher import ( + fwd_only, + gen_register_replacement, + joint_fwd_bwd, + Match, + ReplaceFn, + SearchFn, +) + + +aten = torch.ops.aten + + +# This flag is only used for testing purpose. +# Changing it to True will ignore comparing do_bench times +# between original pattern and padded one. +_skip_do_bench_times = False + + +def fetch_fake_tensors(match: Match, kwarg_names: Sequence[str]) -> list[Tensor]: + kwargs = match.kwargs + return [kwargs[name].meta["val"] for name in kwarg_names] + + +def unwrap_fake_args( + *arg_names: str, +) -> Callable[[Callable[..., Any]], Callable[[Match], Any]]: + def decorator(func: Callable[..., Any]) -> Callable[[Match], Any]: + def wrapper(match: Match) -> Any: + fake_tensors = fetch_fake_tensors(match, arg_names) + return func(*fake_tensors) + + return wrapper + + return decorator + + +def get_alignment_size(x: Tensor) -> int: + return get_alignment_size_dtype(x.dtype) + + +def get_alignment_size_dtype(dtype: torch.dtype) -> int: + if dtype == torch.float16 or dtype == torch.half or dtype == torch.bfloat16: + return 8 + elif dtype == torch.float32 or dtype == torch.float: + return 4 + else: + return 0 + + +def check_device(a: Tensor, b: Tensor) -> bool: + return (a.is_cuda and b.is_cuda) or (a.is_xpu and b.is_xpu) + + +def check_dtype(a: Tensor, b: Tensor) -> bool: + return a.is_floating_point() and b.is_floating_point() + + +def hint_symbols( + ds: Sequence[int | torch.SymInt], +) -> list[int]: + """Helper to convert symbolic dimensions to their concrete hint values.""" + from torch.fx.experimental.symbolic_shapes import optimization_hint + + return [optimization_hint(d) for d in ds] + + +def can_pad( + mat1: Tensor, + mat2: Tensor, + op: torch._ops.OpOverloadPacket, + input: Tensor | None = None, +) -> bool: + """ + Determines if an operation CAN be padded (safety checks). + All logic related to whether it's safe to pad should be here. + """ + + # Can't pad if there is no static dims, we pad static dims only. + def has_one_static_dim(t: Tensor) -> bool: + """Return False if all dimensions are symbolic — nothing concrete to pad.""" + for x in t.size(): + if isinstance(x, int): + return True + elif not isinstance(x, torch.SymInt): + raise RuntimeError("not expected size") + return False + + # Basic safety checks + if not torch._inductor.config.shape_padding: + return False + + if not check_device(mat1, mat2): + return False + + if not check_dtype(mat1, mat2): + return False + + # For padding to be vaible each tensor should have at least one static dim. + tensors = [t for t in (mat1, mat2, input) if t is not None] + if not all(has_one_static_dim(t) for t in tensors): + return False + + # Skip zero-sized dimensions — padding would be wasteful (mm on empty tensors) + from torch.fx.experimental.symbolic_shapes import optimization_hint + + if any( + optimization_hint(dim) == 0 for dim in itertools.chain(mat1.shape, mat2.shape) + ): + return False + + # Calculate padding lengths to check if padding is needed + with no_dispatch(): + if op is torch.ops.aten.mm or op is torch.ops.aten.addmm: + m = mat1.shape[0] + k = mat1.shape[1] + n = mat2.shape[1] + elif op is torch.ops.aten.bmm: + m = mat1.shape[1] + k = mat1.shape[2] + n = mat2.shape[2] + else: + return False + + k_padded_length = get_padded_length(k, get_alignment_size(mat1)) + n_padded_length = get_padded_length(n, get_alignment_size(mat2)) + m_padded_length = get_padded_length(m, get_alignment_size(mat1)) + + # No padding needed - can't pad if there's nothing to pad + if m_padded_length == k_padded_length == n_padded_length == 0: + return False + + # In deterministic mode, we can't safely benchmark - disallow padding + # Check this after other basic checks so force_shape_pad/autoheuristic can override + if ( + torch._inductor.config.deterministic + and not torch._inductor.config.force_shape_pad + and not torch._inductor.config.use_autoheuristic("pad_mm") + ): + return False + + # Triton availability check - required for padding to work + if not has_triton(): + return False + + return True + + +def get_padded_length(x: int | torch.SymInt, alignment_size: int) -> int: + # we don't pad x if it is symbolic + if isinstance(x, torch.SymInt) or alignment_size == 0 or x % alignment_size == 0: + return 0 + + # ignore dim that can be squeezed away + if x == 1: + return 0 + + return int((x // alignment_size + 1) * alignment_size) - x + + +def pad_dim(x: Tensor, padded_length: int, dim: int) -> Tensor: + if padded_length == 0: + return x + pad = x.new_zeros(*x.shape[:dim], padded_length, *x.shape[dim + 1 :]) + return torch.cat([x, pad], dim=dim) + + +def addmm_pattern( + input: Tensor, mat1: Tensor, mat2: Tensor, beta: float, alpha: float +) -> Tensor: + return aten.addmm(input, mat1, mat2, beta=beta, alpha=alpha) + + +def _is_statically_expandable_to(shape: torch.Size, desired: Sequence[Any]) -> bool: + if len(shape) > len(desired): + return False + return all( + statically_known_true(dim == desired_dim) or statically_known_true(dim == 1) + for dim, desired_dim in zip(reversed(shape), reversed(desired)) + ) + + +def should_pad_addmm(match: Match) -> bool: + mat1, mat2, input = fetch_fake_tensors(match, ("mat1", "mat2", "input")) + beta = match.kwargs["beta"] + if ( + beta == 0 + and input.is_cuda + and not _is_statically_expandable_to( + input.shape, (mat1.shape[0], mat2.shape[1]) + ) + ): + return False + return should_pad(match, mat1, mat2, torch.ops.aten.addmm, input=input) + + +def pad_addmm( + input: Tensor | None, + mat1: Tensor, + mat2: Tensor, + m_padded_length: int, + k_padded_length: int, + n_padded_length: int, + beta: float = 1.0, + alpha: float = 1.0, + mat1_pre_padded: bool = False, + mat2_pre_padded: bool = False, +) -> Tensor: + # for paddings, dim order is reversed for some reasons + # and for every dim, we need to specify left and right padding + if not mat1_pre_padded: + mat1 = pad_mat1( + mat1, m_padded_length=m_padded_length, k_padded_length=k_padded_length + ) + if not mat2_pre_padded: + mat2 = pad_mat2( + mat2, k_padded_length=k_padded_length, n_padded_length=n_padded_length + ) + + # the add broadcasts, so we only pad if the dimension != 1 + if input is not None: + if n_padded_length != 0: + if input.dim() == 2 and input.shape[1] != 1: + input = pad_dim(input, n_padded_length, 1) + elif input.dim() == 1 and input.shape[0] != 1: + input = pad_dim(input, n_padded_length, 0) + if m_padded_length != 0 and input.dim() == 2 and input.shape[0] != 1: + input = pad_dim(input, m_padded_length, 0) + + res = aten.addmm(input, mat1, mat2, beta=beta, alpha=alpha) + + if m_padded_length != 0: + res = res[:-m_padded_length, :] + if n_padded_length != 0: + res = res[:, :-n_padded_length] + return res + + +def addmm_replace( + input: Tensor | None, + mat1: Tensor, + mat2: Tensor, + beta: float = 1.0, + alpha: float = 1.0, +) -> Tensor: + k_padded_length = get_padded_length(mat1.shape[1], get_alignment_size(mat1)) + n_padded_length = get_padded_length(mat2.shape[1], get_alignment_size(mat2)) + m_padded_length = get_padded_length(mat1.shape[0], get_alignment_size(mat1)) + return pad_addmm( + input, + mat1, + mat2, + m_padded_length, + k_padded_length, + n_padded_length, + beta, + alpha, + ) + + +def is_mm_compute_bound(M: int, K: int, N: int, dtype: torch.dtype) -> bool: + denominator = M * K + N * K + M * N + if denominator == 0: + return False + arithmetic_intensity = (M * N * K) / denominator + + # we have experienced some large perf hits in this case, even in bandwidth bound regimes + if ( + dtype is torch.bfloat16 + and K > M + and K > N + and (torch.xpu.is_available() or torch.cuda.get_device_capability() < (9, 0)) + ): # doesn't repro on h100s: + return True + + # Fails with AMD + try: + machine_balance = ( + 1000 * utils.get_device_tflops(dtype) + ) / utils.get_gpu_dram_gbps() + except Exception: + return True + + # dram_gbps might be underestimating bandwidth because of cache. + # if we estimate machine balance too low we might miss some speedups, + # if we estimate too high there will be unnecessary compilation time increase. + # TODO - finetune coefficient here. As a reference point, Triton mm model assumes + # 80% of reads are in cache and cache is 4x faster than dram_gbps + machine_balance = machine_balance * 0.5 + + return arithmetic_intensity > machine_balance + + +@functools.cache +def get_pad_cache() -> torch._inductor.codecache.LocalCache: + return torch._inductor.codecache.LocalCache() + + +def get_cached_should_pad(key: str) -> bool: + return get_pad_cache().lookup(key) # type: ignore[return-value] + + +def set_cached_should_pad(key: str, value: bool) -> None: + return get_pad_cache().set_value(key, value=value) + + +def get_cached_base_mm_benchmark_time(key: str) -> float: + return get_pad_cache().lookup(key) # type: ignore[return-value] + + +def set_cached_base_mm_benchmark_time(key: str, value: float) -> None: + return get_pad_cache().set_value(key, value=value) + + +def should_pad_bench_key( + match: Match, + mat1: Tensor, + mat2: Tensor, + op: torch._ops.OpOverloadPacket, + input: Tensor | None = None, + is_base_time_key: bool = False, +) -> str: + def tensor_key(t: Tensor) -> tuple[torch.Size, tuple[int, ...], torch.dtype]: + return (t.shape, t.stride(), t.dtype) + + tf32_key = ( + None + if mat1.dtype != torch.float32 + else torch.backends.cuda.matmul.fp32_precision == "tf32" + or torch.backends.mkldnn.fp32_precision == "tf32" + ) + + def fmt_pad(name: str) -> str | None: + if is_base_time_key: + return None + return f"exclude_pad:{should_exclude_padding_time(match, name)}" + + key = ( + tensor_key(mat1), + tensor_key(mat2), + fmt_pad("mat1"), + fmt_pad("mat2"), + op, + input if input is None else tensor_key(input), + tf32_key, + ) + + key = str(key) + if is_base_time_key: + key = f"base mm time: {key}" + return key + + +def get_non_view_def(node: torch.fx.Node) -> torch.fx.Node: + if node.op == "call_function" and node.target is operator.getitem: + return get_non_view_def(node.args[0]) # type: ignore[arg-type] + + if ( + node.op == "call_function" + and isinstance(node.target, torch._ops.OpOverload) + and utils.is_view(node.target) + ): + return get_non_view_def(node.all_input_nodes[0]) + + return node + + +def should_exclude_padding_time(match: Match, arg_name: str) -> bool: + from torch._prims_common import is_contiguous_or_false + + node_def = get_non_view_def(match.kwargs[arg_name]) + + # constant padding converts tensors to contiguous so even if the input tensor + # can be planned layout transform is not free. TODO - way to pad and preserve layout ? + # Use is_contiguous_or_false to avoid guarding on data-dependent expressions + # with unbacked symints - returns False instead of raising an error. + if not is_contiguous_or_false(fetch_fake_tensors(match, (arg_name,))[0]): + return False + + # TODO - see issue https://github.com/pytorch/pytorch/issues/128889 + # We would only able to completely plan these out if we were only doing + # first dimension padding. non-first we would still need a copy + # because these outputs are fixed dense. + cannot_plan_output = [ + aten.mm.default, + aten.convolution.default, + aten.convolution_backward.default, + aten.bmm.default, + aten.addmm.default, + aten._scaled_dot_product_flash_attention.default, + aten._scaled_dot_product_efficient_attention.default, + ] + + if node_def.target in cannot_plan_output: + return False + + if ( + node_def.target is aten.cat.default + and len(node_def.all_input_nodes) + > torch._inductor.config.max_pointwise_cat_inputs + ): + return False + + # optimistically assume we should be able to memory plan away + # all non inputs + return node_def.op != "placeholder" + + +def is_padded_faster(key: str, ori_time: float, pad_time: float) -> bool: + """ + Determines if padding is beneficial by comparing benchmark times. + Helper function that applies a multiplier to account for memory ops overhead. + """ + multiplier = 1.1 + # Shape padding introduces additional memory ops. Based on microbenchmarks, 1.1x represents a reasonable + # tradeoff between performance improvement from shape padding and overhead from additional memory ops + # TODO: Build a learned model which would be better than this heuristic + if "shape_padding_multiplier" in torch._inductor.config.post_grad_fusion_options: + multiplier = torch._inductor.config.post_grad_fusion_options[ + "shape_padding_multiplier" + ].get("value", 1.1) + counters["inductor"]["shape_padding_multiplier"] += 1 + padded_is_faster = _skip_do_bench_times or ori_time > pad_time * multiplier + set_cached_should_pad(key, padded_is_faster) + return padded_is_faster + + +def should_pad_mm_bf16(dtype: torch.dtype, M: int, N: int, K: int) -> bool: + # always force pad for mm with bf16 when the following are satisfied to avoid perf regression + large_k_threshold_to_pad = torch._inductor.config.post_grad_fusion_options[ + "pad_aten_mm_pass" + ].get("k_threshold_to_pad", 8388608) + if ( + dtype is torch.bfloat16 + and K > M + and K > N + and N % 2 == 1 + and K >= large_k_threshold_to_pad + and (torch.xpu.is_available() or torch.cuda.get_device_capability() < (9, 0)) + ): # doesn't repro on h100s: + return True + return False + + +def should_pad( + match: Match, + mat1: Tensor, + mat2: Tensor, + op: torch._ops.OpOverloadPacket, + input: Tensor | None = None, +) -> bool: + _can_pad = can_pad(mat1, mat2, op, input) + # Note that if you're tempted to insert a dynamo_timed call here, this function can + # be called enough that the dynamo_timed overhead is not negligible. + return _can_pad and _should_pad(match, mat1, mat2, op, input) + + +def get_do_bench() -> Callable[[Callable[[], Any]], float]: + return functools.partial( + # pyrefly: ignore [bad-argument-type] + torch._inductor.runtime.benchmarking.benchmarker.benchmark_gpu, + warmup=5, + ) + + +@memoizers.should_pad_memoizer.memoize( + custom_params_encoder=encoders.should_pad_params_encoder +) +def _should_pad( + match: Match, + mat1: Tensor, + mat2: Tensor, + op: torch._ops.OpOverloadPacket, + input: Tensor | None = None, +) -> bool: + """ + Determines if an operation SHOULD be padded (performance checks). + All logic related to whether padding would be performant should be here. + """ + do_bench = get_do_bench() + + with no_dispatch(): + if op is torch.ops.aten.mm or op is torch.ops.aten.addmm: + m = mat1.shape[0] + k = mat1.shape[1] + n = mat2.shape[1] + k_padded_length = get_padded_length(k, get_alignment_size(mat1)) + n_padded_length = get_padded_length(n, get_alignment_size(mat2)) + m_padded_length = get_padded_length(m, get_alignment_size(mat1)) + elif op is torch.ops.aten.bmm: + m = mat1.shape[1] + k = mat1.shape[2] + n = mat2.shape[2] + k_padded_length = get_padded_length(k, get_alignment_size(mat1)) + m_padded_length = get_padded_length(m, get_alignment_size(mat1)) + n_padded_length = get_padded_length(n, get_alignment_size(mat2)) + else: + return False + + # Force padding when explicitly requested - performance override + if torch._inductor.config.force_shape_pad: + return True + + # Resolve symbolic dims to concrete hints for heuristic checks below. + # These are performance decisions, not correctness — optimization_hint is safe. + m_concrete, k_concrete, n_concrete = hint_symbols((m, k, n)) + + # Performance heuristic for bf16 large K scenarios + if ( + "pad_aten_mm_pass" in torch._inductor.config.post_grad_fusion_options + and should_pad_mm_bf16(mat1.dtype, m_concrete, n_concrete, k_concrete) + ): + return True + + # Check if operation is compute bound (performance check) + if not is_mm_compute_bound(m_concrete, k_concrete, n_concrete, mat1.dtype): + return False + + # We don't want to look up the cache for cases that are trivially false + # since it does file io + key = should_pad_bench_key(match, mat1, mat2, op, input) + + cached_pad = get_cached_should_pad(key) + if cached_pad is not None: + return cached_pad + + def realize_tensor(t): + if is_fake_tensor(t): + size_hints = hint_symbols(t.size()) + # pyrefly: ignore [bad-argument-type] + stride_hint = hint_symbols(t.stride()) + real_size = ( + sum((d - 1) * s for d, s in zip(size_hints, stride_hint)) + 1 + ) + real_t = torch.randn(real_size, dtype=t.dtype, device=t.device) + return torch.as_strided(real_t, size_hints, stride_hint) + else: + return torch.randn_like(t) + + mat1 = realize_tensor(mat1) + mat2 = realize_tensor(mat2) + + # since we key on whether or not the inputs can be memory planned, set cache for the + # original time which is unaffected by whether or not the input can be planned + ori_time_key = should_pad_bench_key( + match, mat1, mat2, op, input, is_base_time_key=True + ) + ori_time = get_cached_base_mm_benchmark_time(ori_time_key) + if ori_time is None and op is torch.ops.aten.addmm and input is not None: + # realize bias for addmm + input = realize_tensor(input) + + mat1_pad = mat1 + mat2_pad = mat2 + + is_bmm = op is torch.ops.aten.bmm + + mat1_pre_padded = should_exclude_padding_time(match, "mat1") + fns = [] + if mat1_pre_padded and (m_padded_length or k_padded_length): + mat1_pad = pad_mat1( + mat1_pad, + m_padded_length=m_padded_length, + k_padded_length=k_padded_length, + is_bmm=is_bmm, + ) + + def write_pad(): + if is_bmm: + mat1_pad[:, -m_padded_length:, -k_padded_length:].fill_(0) + else: + mat1_pad[-m_padded_length:, -k_padded_length:].fill_(0) + + fns.append(write_pad) + + mat2_pre_padded = should_exclude_padding_time(match, "mat2") + if mat2_pre_padded and (k_padded_length or n_padded_length): + mat2_pad = pad_mat2( + mat2_pad, + k_padded_length=k_padded_length, + n_padded_length=n_padded_length, + is_bmm=is_bmm, + ) + + def write_pad(): + if is_bmm: + mat2_pad[:, -k_padded_length:, -n_padded_length:].fill_(0) + else: + mat2_pad[-k_padded_length:, -n_padded_length:].fill_(0) + + fns.append(write_pad) + + if op is torch.ops.aten.addmm: + input_pad = None + if input is not None and (input.is_cuda or input.is_xpu): + input_pad = torch.randn_like(input) + fns.append( + lambda: pad_addmm( + input_pad, + mat1_pad, + mat2_pad, + m_padded_length, + k_padded_length, + n_padded_length, + mat1_pre_padded=mat1_pre_padded, + mat2_pre_padded=mat2_pre_padded, + ) + ) + elif op is torch.ops.aten.mm: + fns.append( + lambda: pad_mm( + mat1_pad, + mat2_pad, + m_padded_length, + k_padded_length, + n_padded_length, + mat1_pre_padded=mat1_pre_padded, + mat2_pre_padded=mat2_pre_padded, + ) + ) + else: + fns.append( + lambda: pad_bmm( + mat1_pad, + mat2_pad, + m_padded_length, + k_padded_length, + n_padded_length, + mat1_pre_padded=mat1_pre_padded, + mat2_pre_padded=mat2_pre_padded, + ) + ) + + def orig_bench_fn(): + if op is torch.ops.aten.bmm or op is torch.ops.aten.mm: + op(mat1, mat2) + else: + op(input, mat1, mat2) + + def pad_bench_fn(): + for fn in fns: + fn() + + if ( + torch._inductor.config.run_autoheuristic("pad_mm") + and op is torch.ops.aten.mm + ): + ah_should_pad = run_autoheuristic( + mat1, + mat2, + orig_bench_fn, + pad_bench_fn, + m_padded_length, + k_padded_length, + n_padded_length, + do_bench, + mat1_pre_padded, + mat2_pre_padded, + ori_time, + ori_time_key, + key, + ) + if ah_should_pad is not None: + return ah_should_pad + + # AH didn't make a decision, so if we're in deterministic mode, we should return false + if torch._inductor.config.deterministic: + return False + + if ori_time is None: + ori_time = do_bench(orig_bench_fn) + set_cached_base_mm_benchmark_time(ori_time_key, ori_time) + + pad_time = do_bench(pad_bench_fn) + + counters["inductor"]["pad_mm_bench"] += 1 + return is_padded_faster(key, ori_time, pad_time) + + +def get_context( + mat1: Tensor, + mat2: Tensor, + mat1_pre_padded: bool, + mat2_pre_padded: bool, + m_padded_length: int, + k_padded_length: int, + n_padded_length: int, +) -> AHContext: + context = AHContext() + + context.add_feature("m", mat1.shape[0]) + context.add_feature("k", mat1.shape[1]) + context.add_feature("n", mat2.shape[1]) + + context_add_strides(context, "mat1", mat1.stride()) + context_add_strides(context, "mat2", mat2.stride()) + + context.add_feature("m_padded_length", m_padded_length) + context.add_feature("k_padded_length", k_padded_length) + context.add_feature("n_padded_length", n_padded_length) + + context.add_feature("mat1_align_size", get_alignment_size(mat1)) + context.add_feature("mat2_align_size", get_alignment_size(mat2)) + + context.add_feature("mat1_dtype", mat1.dtype, is_categorical=True) + context.add_feature("mat2_dtype", mat2.dtype, is_categorical=True) + + context.add_feature("prepadded_mat1", mat1_pre_padded, is_categorical=True) + context.add_feature("prepadded_mat2", mat2_pre_padded, is_categorical=True) + + context_add_using_tf32(context, mat1.dtype) + return context + + +def run_autoheuristic( + mat1: Tensor, + mat2: Tensor, + orig_bench_fn: Callable[[], None], + pad_bench_fn: Callable[[], None], + m_padded_length: int, + k_padded_length: int, + n_padded_length: int, + do_bench: Callable[[Callable[[], Any]], float], + mat1_pre_padded: bool, + mat2_pre_padded: bool, + ori_time: float, + ori_time_key: str, + key: str, +) -> bool | None: + def feedback_fn( + choice: str, + ) -> float | None: + if choice == orig_choice: + return do_bench(orig_bench_fn) + elif choice == pad_choice: + return do_bench(pad_bench_fn) + return None + + def fallback() -> str: + return "autotune" + + orig_choice = "orig" + pad_choice = "pad" + choices = [orig_choice, pad_choice] + feedback = LocalFeedback(feedback_fn) # type: ignore[arg-type] + context = get_context( + mat1, + mat2, + mat1_pre_padded, + mat2_pre_padded, + m_padded_length, + k_padded_length, + n_padded_length, + ) + name = "pad_mm" + autoheuristic = AutoHeuristic( + fallback=fallback, + choices=choices, + feedback=feedback, + context=context, + name=name, + augment_context=pad_mm_operations(), + precondition=pad_mm_precondition, + ) + choice = autoheuristic.get_choice() + choice2should_pad = {orig_choice: False, pad_choice: True, "autotune": None} + ah_should_pad = choice2should_pad.get(choice) + + if torch._inductor.config.collect_autoheuristic(name): + ah_ori_time = autoheuristic.get_collected_feedback(orig_choice) + ah_pad_time = autoheuristic.get_collected_feedback(pad_choice) + + # if precondition is not satisfied, autoheuristic does not collect data + if ah_ori_time is not None and ah_pad_time is not None: + if ori_time is None: + set_cached_base_mm_benchmark_time(ori_time_key, ah_ori_time) + return is_padded_faster(key, ah_ori_time, ah_pad_time) + if ah_should_pad is not None: + set_cached_should_pad(key, ah_should_pad) + return ah_should_pad + + +def mm_pattern(mat1: Tensor, mat2: Tensor) -> Tensor: + return aten.mm(mat1, mat2) + + +def should_pad_mm(match: Match) -> bool: + mat1, mat2 = fetch_fake_tensors(match, ("mat1", "mat2")) + return should_pad(match, mat1, mat2, torch.ops.aten.mm) + + +def pad_mat1( + mat1: Tensor, *, m_padded_length: int, k_padded_length: int, is_bmm: bool = False +) -> Tensor: + if k_padded_length != 0 or m_padded_length != 0: + # dim order is reversed for constant_pad_nd, for every dim we specify right and left padding + pad_arg = [0, k_padded_length, 0, m_padded_length] + if is_bmm: + pad_arg.extend((0, 0)) + return aten.constant_pad_nd(mat1, pad_arg) + else: + return mat1 + + +def pad_mat2( + mat2: Tensor, *, k_padded_length: int, n_padded_length: int, is_bmm: bool = False +) -> Tensor: + if k_padded_length != 0 or n_padded_length != 0: + # dim order is reversed for constant_pad_nd, for every dim we specify right and left padding + pad_arg = [0, n_padded_length, 0, k_padded_length] + if is_bmm: + pad_arg.extend((0, 0)) + return aten.constant_pad_nd(mat2, pad_arg) + else: + return mat2 + + +def pad_mm( + mat1: Tensor, + mat2: Tensor, + m_padded_length: int, + k_padded_length: int, + n_padded_length: int, + mat1_pre_padded: bool = False, + mat2_pre_padded: bool = False, +) -> Tensor: + if not mat1_pre_padded: + mat1 = pad_mat1( + mat1, m_padded_length=m_padded_length, k_padded_length=k_padded_length + ) + if not mat2_pre_padded: + mat2 = pad_mat2( + mat2, k_padded_length=k_padded_length, n_padded_length=n_padded_length + ) + res = aten.mm(mat1, mat2) + if m_padded_length != 0: + res = res[:-m_padded_length, :] + if n_padded_length != 0: + res = res[:, :-n_padded_length] + return res + + +def mm_replace(mat1: Tensor, mat2: Tensor) -> Tensor: + k_padded_length = get_padded_length(mat1.shape[1], get_alignment_size(mat1)) + m_padded_length = get_padded_length(mat1.shape[0], get_alignment_size(mat1)) + n_padded_length = get_padded_length(mat2.shape[1], get_alignment_size(mat2)) + return pad_mm( + mat1, + mat2, + m_padded_length, + k_padded_length, + n_padded_length, + ) + + +def bmm_pattern(mat1: Tensor, mat2: Tensor) -> Tensor: + return aten.bmm(mat1, mat2) + + +def should_pad_bmm(match: Match) -> bool: + mat1, mat2 = fetch_fake_tensors(match, ("mat1", "mat2")) + return should_pad(match, mat1, mat2, torch.ops.aten.bmm) + + +def pad_bmm( + mat1: Tensor, + mat2: Tensor, + m_padded_length: int, + k_padded_length: int, + n_padded_length: int, + mat1_pre_padded: bool = False, + mat2_pre_padded: bool = False, +) -> Tensor: + if not mat1_pre_padded: + mat1 = pad_mat1( + mat1, + m_padded_length=m_padded_length, + k_padded_length=k_padded_length, + is_bmm=True, + ) + if not mat2_pre_padded: + mat2 = pad_mat2( + mat2, + k_padded_length=k_padded_length, + n_padded_length=n_padded_length, + is_bmm=True, + ) + res = aten.bmm(mat1, mat2) + if m_padded_length != 0: + res = res[:, :-m_padded_length, :] + if n_padded_length != 0: + res = res[:, :, :-n_padded_length] + return res + + +def bmm_replace(mat1: Tensor, mat2: Tensor) -> Tensor: + k_padded_length = get_padded_length(mat1.shape[2], get_alignment_size(mat1)) + n_padded_length = get_padded_length(mat2.shape[2], get_alignment_size(mat2)) + m_padded_length = get_padded_length(mat1.shape[1], get_alignment_size(mat1)) + return pad_bmm( + mat1, + mat2, + m_padded_length, + k_padded_length, + n_padded_length, + ) + + +@functools.cache +def _pad_mm_init(input_device: torch.device | None = None) -> None: + from .joint_graph import patterns + + if input_device: + device = str(input_device) + else: + if torch.cuda.is_available(): + # workaround https://github.com/pytorch/pytorch/issues/97894 + device = "cuda" + elif torch.xpu.is_available(): + device = "xpu" + else: + device = "cpu" + + # sizes/values don't actually matter for initial trace + # once we get a possible match we re-trace with the actual values and verify the match still holds + + dim2a = functools.partial(torch.empty, (4, 4), device=device, requires_grad=True) + dim2b = functools.partial(torch.empty, (4, 4), device=device, requires_grad=True) + + dim3a = functools.partial(torch.empty, (4, 4, 4), device=device, requires_grad=True) + dim3b = functools.partial(torch.empty, (4, 4, 4), device=device, requires_grad=True) + + dim1a = functools.partial(torch.empty, (4), device=device, requires_grad=True) + + # workaround https://github.com/pytorch/pytorch/issues/97894 + # 0.113377 is a "magic" value that lets us recover the lost input arg relationship + rep = {"beta": 0.213377, "alpha": 0.113377} + + for pattern, replacement, args, workaround, extra_check in [ + ( + typing.cast(SearchFn, mm_pattern), + typing.cast(ReplaceFn, mm_replace), + [dim2a(), dim2b()], + {}, + should_pad_mm, + ), + ( + typing.cast(SearchFn, bmm_pattern), + typing.cast(ReplaceFn, bmm_replace), + [dim3a(), dim3b()], + {}, + should_pad_bmm, + ), + ( + typing.cast(SearchFn, addmm_pattern), + typing.cast(ReplaceFn, addmm_replace), + [dim1a(), dim2a(), dim2b()], + rep, + should_pad_addmm, + ), + ]: + if not isinstance( + workaround, dict + ): # mypy is unable to infer the type properly + raise AssertionError( + f"expected workaround to be a dict, got {type(workaround)}" + ) + name = pattern.__name__ + + gen_register_replacement( + f"{name}_training", + pattern, + replacement, + args, + # pyrefly: ignore [bad-argument-type] + joint_fwd_bwd, + # pyrefly: ignore [bad-argument-type] + patterns, + extra_check=extra_check, + scalar_workaround=workaround, + skip_duplicates=True, + ) + + gen_register_replacement( + f"{name}_inference", + pattern, + replacement, + args, + # pyrefly: ignore [bad-argument-type] + fwd_only, + # pyrefly: ignore [bad-argument-type] + patterns, + extra_check=extra_check, + scalar_workaround=workaround, + skip_duplicates=True, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/post_grad.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/post_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..1cafcb82109a26ebc5ed5b569627488c6cf349ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/post_grad.py @@ -0,0 +1,2505 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import functools +import itertools +import logging +import operator +from collections import Counter, defaultdict +from collections.abc import Callable, Sequence +from typing import Any, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch._inductor as inductor +import torch.utils._pytree as pytree +from torch import fx +from torch._decomp import register_decomposition +from torch._dynamo.utils import counters +from torch._higher_order_ops.flex_gemm import _PRESERVE_FLEX_GEMM_GEMM_OP +from torch._inductor.custom_graph_pass import ( + CustomInferenceAwareGraphPass, + get_custom_graph_passes, +) +from torch._inductor.virtualized import ops # noqa: F401 +from torch._logging import trace_structured +from torch._prims_common import is_boolean_dtype, is_expandable_to, is_integer_dtype +from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq +from torch.utils._ordered_set import OrderedSet + +from .. import config, ir, pattern_matcher # noqa: F401 +from ..codegen.common import custom_backend_passes +from ..fx_utils import FakeTensorUpdater, get_fake_args_kwargs, get_node_storage +from ..lowering import lowerings as L +from ..pattern_matcher import ( + _return_true, + Arg, + CallFunction, + CallFunctionVarArgs, + filter_nodes, + fwd_only, + get_arg_value, + get_mutation_region_id, + Ignored, + init_once_fakemode, + KeywordArg, + ListOf, + Match, + MultiOutputPattern, + MULTIPLE, + PatternMatcherPass as PatternMatcherPassBase, + register_graph_pattern, + register_replacement, + stable_topological_sort, +) +from ..utils import ( + decode_device, + get_all_devices, + get_gpu_type, + is_gpu, + is_pointwise_use, + OPTIMUS_EXCLUDE_POST_GRAD, +) +from ..virtualized import V +from .b2b_gemm import B2B_GEMM_PASS +from .control_dependencies import control_deps, preserve_node_ordering +from .ddp_fusion import fuse_ddp_communication +from .group_batch_fusion import group_batch_fusion_passes, POST_GRAD_FUSIONS +from .micro_pipeline_tp import micro_pipeline_tp_pass +from .pre_grad import is_same_dict, save_inductor_dict +from .reduced_atomic_contention import partitioned_scatter_optimization_pass +from .reinplace import reinplace_inplaceable_ops +from .split_cat import POST_GRAD_PATTERNS + + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +PatternMatcherPass = functools.partial( + PatternMatcherPassBase, subsystem="post_grad_passes" +) + +log = logging.getLogger(__name__) +aten = torch.ops.aten +prims = torch.ops.prims + +# First pass_patterns[0] are applied, then [1], then [2] +pass_patterns = [ + PatternMatcherPass(), + PatternMatcherPass(), + PatternMatcherPass(), +] + + +def _remove_profiler_ops(graph: torch.fx.Graph) -> None: + """ + Remove profiler ops (record_function) from the graph. + These ops are side-effectful but don't affect computation, + and we don't want them to block fusion. + """ + profiler_ops = OrderedSet( + [ + torch.ops.profiler._record_function_enter.default, + torch.ops.profiler._record_function_enter_new.default, + torch.ops.profiler._record_function_exit._RecordFunction, + ] + ) + + nodes_to_remove = [] + + for node in graph.nodes: + if node.op == "call_function" and node.target in profiler_ops: + nodes_to_remove.append(node) + + for node in reversed(nodes_to_remove): + graph.erase_node(node) + + +def _is_nondeterministic_seeded_node(node: torch.fx.Node) -> bool: + return ( + node.op == "call_function" + and isinstance(node.target, torch._ops.OpOverload) + and torch.Tag.nondeterministic_seeded in node.target.tags + ) + + +def _chain_random_ops_for_ordering(graph: torch.fx.Graph) -> None: + """Chain nondeterministic_seeded ops with control_deps to preserve program order. + + When fallback_random=True, random ops use the global CUDA RNG and must + execute in their original program order. + """ + if not config.fallback_random: + return + + random_nodes = [n for n in graph.nodes if _is_nondeterministic_seeded_node(n)] + if len(random_nodes) < 2: + return + + additional_deps_map: dict[torch.fx.Node, OrderedSet[torch.fx.Node]] = {} + for i in range(1, len(random_nodes)): + additional_deps_map[random_nodes[i]] = OrderedSet([random_nodes[i - 1]]) + + preserve_node_ordering(graph, additional_deps_map) + + +def respecialize_current_device_nodes(graph: torch.fx.Graph) -> None: + """[device-as-parameter] Re-specialize CooR _coor_current_device() device nodes. + + Under compile-on-one-rank, make_fx rewrites a baked accelerator device operand to a + ``_coor_current_device()`` node so the FX graph is rank-agnostic. Inductor has no + device-valued IR, so before lowering we replace each use of that node with the node's + own runtime value -- the concrete current device (``_coor_current_device()``), the + authoritative source, not the consumer's meta. Runs in post_grad, before GraphLowering, + so the node never reaches the call_function OpOverload assertion. ``_coor_current_device`` + lives in core fx and only reads torch.accelerator, so this never imports + torch.distributed for a non-distributed compile. + """ + # Importing proxy_tensor registers the coor::current_device op (core fx, no + # torch.distributed) and gives us its impl for the concrete value. + from torch.fx.experimental.proxy_tensor import _coor_current_device + + target = torch.ops.coor.current_device.default + nodes = graph.find_nodes(op="call_function", target=target) + if not nodes: + return + device = _coor_current_device() + for node in nodes: + for user in list(node.users): + user.args = torch.fx.map_arg( + user.args, lambda n: device if n is node else n + ) + user.kwargs = torch.fx.map_arg( + user.kwargs, lambda n: device if n is node else n + ) + graph.erase_node(node) + + +def post_grad_passes(gm: torch.fx.GraphModule, is_inference: bool): + """ + Passes that run on after grad. This is called once on the forwards + graph and once on the backwards graph. + + The IR here has been normalized and functionalized. + """ + GraphTransformObserver = functools.partial( + torch.fx.passes.graph_transform_observer.GraphTransformObserver, + subsystem="post_grad_passes", + ) + + if config.dce: + # has some issues with mutation in inference mode + gm.graph.eliminate_dead_code() + + if config.reorder_for_locality and ( + is_inference or config.reorder_for_locality_in_training + ): + GraphTransformObserver(gm, "reorder_for_locality").apply_graph_pass( + reorder_for_locality + ) + + fake_tensor_updater = FakeTensorUpdater(gm) + + for post_grad_custom_pre_pass in get_custom_graph_passes( + config.post_grad_custom_pre_pass + ): + if isinstance(post_grad_custom_pre_pass, CustomInferenceAwareGraphPass): + post_grad_custom_pre_pass = functools.partial( + post_grad_custom_pre_pass, is_inference=is_inference + ) + GraphTransformObserver(gm, "post_grad_custom_pre_pass").apply_graph_pass( + post_grad_custom_pre_pass + ) + + if torch._C._has_mkldnn: + if ( + config.cpp.enable_grouped_gemm_template + and config.max_autotune + and "CPP" in config.max_autotune_gemm_backends + ): + from .mkldnn_fusion import grouped_gemm_pass + + grouped_gemm_pass(gm.graph) + + if config.cpp.enable_concat_linear: + from .quantization import concat_linear_woq_int4 + + # Concat linear optimization for WOQ int4 + concat_linear_woq_int4(gm) + + # Remove profiler ops (record_function) to prevent them blocking fusion + GraphTransformObserver(gm, "remove_profiler_ops").apply_graph_pass( + _remove_profiler_ops + ) + + # [device-as-parameter] Re-specialize CooR current_device() device nodes before + # lowering (inductor has no device-valued IR). + GraphTransformObserver(gm, "respecialize_current_device").apply_graph_pass( + respecialize_current_device_nodes + ) + + if config.pattern_matcher: + lazy_init() + GraphTransformObserver(gm, "post_grad_custom_pre_pass").apply_graph_pass( + functools.partial(group_batch_fusion_passes, pre_grad=False) + ) + GraphTransformObserver(gm, "remove_noop_ops").apply_graph_pass(remove_noop_ops) + GraphTransformObserver(gm, "remove_assert_ops").apply_graph_pass( + remove_assert_ops + ) + for i, patterns in enumerate(pass_patterns): + GraphTransformObserver(gm, f"pass_pattern_{i}").apply_graph_pass( + patterns.apply + ) + if config.partitioned_scatter_enabled: + GraphTransformObserver( + gm, "partitioned_scatter_optimization" + ).apply_graph_pass(partitioned_scatter_optimization_pass) + for pass_name in config.post_grad_fusion_options: + # skip all patterns for group batch fusions or quantization patterns + if pass_name in POST_GRAD_FUSIONS or pass_name in OPTIMUS_EXCLUDE_POST_GRAD: + continue + pattern_matcher_pass = POST_GRAD_PATTERNS[pass_name] + inductor_before_change = save_inductor_dict( + [pattern_matcher_pass.pass_name] + ) + GraphTransformObserver(gm, pass_name).apply_graph_pass( + pattern_matcher_pass.apply + ) + if not is_same_dict(counters["inductor"], inductor_before_change): + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": f"{pattern_matcher_pass.pass_name}_post_grad", + "encoding": "string", + }, + payload_fn=lambda: gm.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + if config.b2b_gemm_pass: + B2B_GEMM_PASS.apply(gm.graph) # type: ignore[arg-type] + + if config._micro_pipeline_tp: + micro_pipeline_tp_pass(gm.graph) + + if config._fuse_ddp_communication: + GraphTransformObserver(gm, "fuse_ddp_communication").apply_graph_pass( + lambda graph: fuse_ddp_communication( + graph, + config._fuse_ddp_communication_passes, + config._fuse_ddp_bucket_size, + ) + ) + + for post_grad_custom_post_pass in get_custom_graph_passes( + config.post_grad_custom_post_pass + ): + if isinstance(post_grad_custom_post_pass, CustomInferenceAwareGraphPass): + post_grad_custom_post_pass = functools.partial( + post_grad_custom_post_pass, is_inference=is_inference + ) + GraphTransformObserver(gm, "post_grad_custom_post_pass").apply_graph_pass( + post_grad_custom_post_pass + ) + + if config.fallback_random: + GraphTransformObserver(gm, "chain_random_ops_ordering").apply_graph_pass( + _chain_random_ops_for_ordering + ) + + GraphTransformObserver(gm, "stable_sort").apply_graph_pass(stable_topological_sort) + + GraphTransformObserver(gm, "move_constructors_to_cuda").apply_graph_pass( + move_constructors_to_gpu + ) + + fake_tensor_updater.incremental_update() + + for device, custom_backend_pass in custom_backend_passes.items(): + if custom_backend_pass is not None: + gm_devices = [d.type for d in get_all_devices(gm)] + if device in gm_devices: + pass_name = "custom_backend_passes_" + device + GraphTransformObserver(gm, pass_name).apply_gm_pass(custom_backend_pass) + + # SPMD verification — before collective reordering passes. + if ( + config.aten_distributed_optimizations.spmd_check + and _needs_spmd_graph_preservation() + ): + from torch._inductor.fx_passes.spmd_check import spmd_check + + spmd_check(gm) + + if config.aten_distributed_optimizations.allow_comms_decompositions: + from torch._inductor.fx_passes.decomp_comms import decomp_comms + + GraphTransformObserver(gm, "decomp_comms").apply_gm_pass(decomp_comms) + + collectives_bucketing: bool = False + + if config.dedup_reduce_scatters: + from torch._inductor.fx_passes.fsdp import dedup_fsdp_reduce_scatter + + GraphTransformObserver(gm, "dedup_reduce_scatters").apply_gm_pass( + dedup_fsdp_reduce_scatter + ) + + if config.bucket_reduce_scatters_fx != "none": + from torch._inductor.fx_passes.bucketing import bucket_reduce_scatter + from torch._inductor.fx_passes.fsdp import bucket_fsdp_reduce_scatter + + p = ( + bucket_fsdp_reduce_scatter + if "fsdp" in config.bucket_reduce_scatters_fx + else bucket_reduce_scatter + ) + GraphTransformObserver(gm, "bucket_reduce_scatters").apply_graph_pass( + lambda graph: p( + graph.owning_module, # pyrefly: ignore[bad-argument-type] + config.bucket_reduce_scatters_fx_bucket_size_determinator, + config.bucket_reduce_scatters_bucket_mode, # type: ignore[arg-type] + ) + ) + collectives_bucketing = True + + if config.bucket_all_reduces_fx != "none": + from torch._inductor.fx_passes.bucketing import bucket_all_reduce + + GraphTransformObserver(gm, "bucket_all_reduce").apply_graph_pass( + lambda graph: bucket_all_reduce( + graph.owning_module, # pyrefly: ignore[bad-argument-type] + config.bucket_all_reduces_fx_bucket_size_determinator, + config.bucket_all_reduces_fx, # type: ignore[arg-type] + ) + ) + collectives_bucketing = True + + # Fx all_gather bucketing introduces mutation op + # Keeping it in the end to keep invariant of functional graph for previous passes. + if config.bucket_all_gathers_fx != "none": + from torch._inductor.fx_passes.bucketing import bucket_all_gather + from torch._inductor.fx_passes.fsdp import bucket_fsdp_all_gather + + p = ( + bucket_fsdp_all_gather # type: ignore[assignment] + if "fsdp" in config.bucket_all_gathers_fx + else bucket_all_gather + ) + GraphTransformObserver(gm, "bucket_all_gathers").apply_graph_pass( + lambda graph: p( + graph.owning_module, # pyrefly: ignore[bad-argument-type] + config.bucket_all_gathers_fx_bucket_size_determinator, + config.bucket_all_gathers_bucket_mode, # type: ignore[arg-type] + ) + ) + collectives_bucketing = True + + if collectives_bucketing: + # Fx collectives bucketing passes require topological sort for the cases: + # when bucketed collectives have users before the last collective in the bucket + # AND when inputs of bucketed collective have ancestors after the first collective in the bucket. + # + # In this case we can not manually pick the place for bucketed collective insertion. + # But we are guaranteed by the bucketing (independent collectives in the bucket), + # that it is possible to reorder nodes to satisfy all ordering requirements. + # + # --- before bucketing --- + # in0 = ... + # wait_ag0 = ag(in0) + # user0(wait_ag0) + # ... + # pre_in1 = ... + # in1 = transform(pre_in1) + # wait_ag1 = ag(in1) + # user1(wait_ag1) + # + # --- after bucketing --- + # + # in0 = ... + # user(wait_ag0) <--- wait_ag0 is defined only after bucketed collective. + # + # pre_in1 = ... + # in1 = transform(pre_in1) + # ag_bucket(in0+in1) + # wait_bucket + # wait_ag0 = wait_bucket[0] + # wait_ag1 = wait_bucket[1] + # user1(wait_ag1) + stable_topological_sort(gm.graph) + + # Apply overlap scheduling if enabled + if config.aten_distributed_optimizations.enable_overlap_scheduling: + from torch._inductor.fx_passes.overlap_scheduling import ( + schedule_overlap_bucketing_from_inductor_configs, + ) + + overlap_deps = config.aten_distributed_optimizations.insert_overlap_deps + + # by default, insert overlap deps within inductor + with config.patch( + { + "aten_distributed_optimizations.insert_overlap_deps": ( + True if overlap_deps is None else overlap_deps + ), + } + ): + GraphTransformObserver(gm, "overlap_scheduling").apply_graph_pass( + lambda graph: schedule_overlap_bucketing_from_inductor_configs( + graph.owning_module, # pyrefly: ignore[bad-argument-type] + ) + ) + + if config.aten_distributed_optimizations.enable_low_contention_collectives: + from torch._inductor.fx_passes.low_contention_collectives import ( + replace_collectives_with_low_contention, + ) + + GraphTransformObserver( + gm, "replace_collectives_with_low_contention" + ).apply_graph_pass(replace_collectives_with_low_contention) + + # Keep these last, since they introduce mutation. Look at + # ./fx_passes/README.md for a discussion of mutation invariants. + GraphTransformObserver(gm, "reinplace_inplaceable_ops").apply_graph_pass( + functools.partial(reinplace_inplaceable_ops, fake_tensor_updater), + ) + + # Fix aliasing detection for dtype views AFTER reinplace determines cloning needs + GraphTransformObserver(gm, "fix_auto_functionalized_dtype_views").apply_graph_pass( + fix_auto_functionalized_dtype_views + ) + + GraphTransformObserver( + gm, "decompose_triton_kernel_wrapper_functional" + ).apply_graph_pass(decompose_triton_kernel_wrapper_functional) + GraphTransformObserver(gm, "decompose_auto_functionalized").apply_graph_pass( + decompose_auto_functionalized + ) + GraphTransformObserver(gm, "decompose_scan_to_while_loop").apply_gm_pass( + decompose_scan_to_while_loop + ) + GraphTransformObserver(gm, "decompose_map_to_while_loop").apply_gm_pass( + decompose_map_to_while_loop + ) + + gm.recompile() + gm.graph.lint() + + +def prepare_softmax_pattern(x, dim): + xmax = x.amax(dim=dim, keepdim=True) + xsub = x - xmax + xexp = xsub.exp() + xsum = xexp.sum(dim=dim, keepdim=True) + return xmax, xsum, xsub, xexp + + +def prepare_softmax_replacement(x, dim): + """ + Return xsub since otherwise log-softmax can not be matched + due to a use of this intermediate node. Same reason to return + xsub.exp() for softmax. + """ + from torch._inductor.inductor_prims import prepare_softmax_online + + xmax, xsum = prepare_softmax_online(x, dim) + xsub = x - xmax + return xmax, xsum, xsub, xsub.exp() + + +def prepare_softmax_extra_check(match): + """ + We only have triton online softmax kernels currently. + """ + device_type = match.kwargs["x"].meta["val"].device.type + return ( + config.online_softmax + and device_type in ["cuda", "xpu"] + and getattr(config, f"{device_type}_backend") == "triton" + ) + + +def decompose_map_to_while_loop(gm: torch.fx.GraphModule): + """This is similar to decompose_scan_to_while_loop.""" + graph_pass = PatternMatcherPass() + + @register_graph_pattern( + CallFunctionVarArgs(torch.ops.higher_order.map_impl), + # pyrefly: ignore [bad-argument-type] + pass_dict=graph_pass, + ) + def _(match: Match, *args, **kwargs): + if len(kwargs) != 0: + raise AssertionError( + "kwargs of map are not merged into args before entering decompose_map_to_while_loop_pass" + ) + subgraph, fx_xs, fx_additional_inputs = args + sub_gm: torch.fx.GraphModule = getattr(gm, subgraph.target) + cur_node = match.nodes[0] + mapped_outputs = cur_node.meta["val"] + + def lower_to_while_loop(*args, **kwargs): + if len(kwargs) != 0: + raise AssertionError(f"expected no kwargs, got {kwargs}") + xs, additional_inputs = pytree.tree_unflatten(args, tree_spec) + if not ( + isinstance(xs, (tuple, list)) + and isinstance(additional_inputs, (tuple, list)) + ): + raise AssertionError((xs, additional_inputs)) + map_length = xs[0].size(0) + loop_idx = torch.zeros([], dtype=torch.int64, device=torch.device("cpu")) + + # Similar to NOTE [Pre-allocate scan's output buffer] + bound_symbols = { + arg.node.expr: arg + for arg in pytree.tree_leaves((args, map_length)) + if isinstance(arg, torch.SymInt) + } + out_buffers = [ + torch.empty_strided( + resolve_shape_to_proxy(out.size(), bound_symbols), + resolve_shape_to_proxy(out.stride(), bound_symbols), + device=out.device, + dtype=out.dtype, + layout=out.layout, + requires_grad=out.requires_grad, + ) + for out in mapped_outputs + ] + + while_loop_operands = (loop_idx, out_buffers, xs) + while_loop_flat_operands, operands_spec = pytree.tree_flatten( + while_loop_operands + ) + while_loop_additional_inputs = additional_inputs + _, operands_and_additional_inputs_spec = pytree.tree_flatten( + (*while_loop_operands, additional_inputs) + ) + + def cond_fn(*flat_args): + loop_idx, _, _, _ = pytree.tree_unflatten( + flat_args, + operands_and_additional_inputs_spec, + ) + return loop_idx < map_length + + def body_fn(*flat_args): + loop_idx, out_bufs, xs, additional_inputs = pytree.tree_unflatten( + flat_args, + operands_and_additional_inputs_spec, + ) + + idx_int = loop_idx.item() + torch.ops.aten._assert_scalar.default(idx_int >= 0, "") + torch.ops.aten._assert_scalar.default(idx_int < map_length, "") + sub_xs = [torch.ops.aten.select.int(x, 0, idx_int) for x in xs] + outs = sub_gm(*sub_xs, *additional_inputs) + + for out, buffer in zip(outs, out_bufs): + buffer_slice = torch.ops.aten.select.int(buffer, 0, idx_int) + buffer_slice.copy_(out) + return loop_idx + 1, *out_bufs, *xs + + _, final_out, _ = pytree.tree_unflatten( + torch.ops.higher_order.while_loop( + cond_fn, + body_fn, + tuple(while_loop_flat_operands), + tuple(while_loop_additional_inputs), + ), + operands_spec, + ) + return (final_out,) + + lower_to_while_loop_args, tree_spec = pytree.tree_flatten( + (fx_xs, fx_additional_inputs) + ) + match.replace_by_example( + lower_to_while_loop, lower_to_while_loop_args, run_functional_passes=False + ) + + graph_pass.apply(gm) + + for _node in gm.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.map_impl + ): + raise AssertionError("map is not lowered to while_loop") + + +def resolve_shape_to_proxy( + shape: list[int | torch.SymInt], bound_symbols: dict[Any, Any] +): + """ + Given a list of symints/ints, this function returns a calculated expression of bound_symbols' values. + When we trace this function, we'll get a graph with call_function nodes that describes how the shape expr is + computed from bound_symbols' values. + + Suppose shape = (s1*s2, s1+s2) and bound_symbols = {s1: arg0, s2: arg1}, the result will be + (arg0 * arg1, arg0 + arg1). + """ + from torch.utils._sympy.interp import sympy_interp + from torch.utils._sympy.reference import PythonReferenceAnalysis + + ret = [] + for s in shape: + if isinstance(s, torch.SymInt): + ret.append( + sympy_interp( + PythonReferenceAnalysis, + bound_symbols, + s.node.expr, + ), + ) + else: + if not isinstance(s, int): + raise AssertionError(f"expected int, got {type(s).__name__}") + ret.append(s) + return ret + + +def decompose_scan_to_while_loop(gm: torch.fx.GraphModule): + """ + NOTE [decompose scan to while_loop] + This pass decomposes `scan` to `while_loop` by replacing the scan fx_node with a while_loop hop. + + Suppose we have a function f: + + def f(): + init = torch.zeros([]) + xs = torch.arange(4) + ys = [] + for i in range(xs.size(0)): + init = xs[i] + init + ys.append(init) + + # Return the final carry and stack the intermediates + return init, torch.stack(ys) + + We could rewrite it with a scan with the benefits of reducing compilation time/binary size, reducing + memory usage, supporting loops over unbacked shapes and cudagraph etc. + + def g(): + def step_fn(init: torch.Tensor, x: torch.Tensor): + next_init = x + init + return next_init, next_init + + init = torch.zeros([]) + xs = torch.arange(4) + final_carry, ys = torch._higher_order.scan(step_fn, init, xs) + return final_carry, ys + + This pass will rewrite scan into: + + def k(): + init = torch.zeros([]) + xs = torch.arange(4) + + # we create a loop_idx and loop through xs.shape[0] + loop_idx = torch.zeros([]) + ys = torch.empty_strided(_shape_stride_of_ys) + def cond_fn(loop_idx, ys, init, xs): + return loop_idx < xs.shape[0] + + # we pre-allocate the output buffer ys and inplace + # copy the y of each intermediate into a slice. + # NOTE [Pre-allocate scan's output buffer]. + def body_fn(loop_idx, ys, init, xs): + int_idx = loop_idx.item() + next_init, y = step_fn(init, xs[int_idx]) + ys[int_idx].copy_(y) + return loop_idx + 1, ys, next_init, xs + + final_carry, _, _, ys = torch._higher_order.while_loop(cond_fn, body_fn, (loop_idx, ys, init, xs)) + return final_carry, ys + """ + + graph_pass = PatternMatcherPass() + + @register_graph_pattern( + CallFunctionVarArgs(torch.ops.higher_order.scan), + # pyrefly: ignore [bad-argument-type] + pass_dict=graph_pass, + ) + def _(match: Match, *args, **kwargs): + from torch._higher_order_ops.scan import _extract_carry_and_out + + if len(kwargs) != 0: + raise AssertionError( + "kwargs of scan are not merged into args before entering decompose_scan_to_while_loop_pass" + ) + + combine_subgraph, fx_init, fx_xs, fx_additional_inputs = args + if combine_subgraph.op != "get_attr": + raise AssertionError("first arg is not combine_subgraph") + sub_gm: torch.fx.GraphModule = getattr(gm, combine_subgraph.target) + cur_node = match.nodes[0] + num_init_leaves = len(fx_init) + _, ys_outputs = _extract_carry_and_out(cur_node.meta["val"], num_init_leaves) + + def lower_to_while_loop(*args, **kwargs): + """ + The traced graph of this function will be used to replace the original scan fx_node. + """ + if len(kwargs) != 0: + raise AssertionError(f"expected no kwargs, got {kwargs}") + + # Step 1: construct necessary inputs to while_loop based on scan's input. + ( + init, + xs, + additional_inputs, + ) = pytree.tree_unflatten(args, tree_spec) + scan_length = xs[0].size(0) + if scan_length == 0: + empty_ys = [ + torch.empty( + [0] + list(ys_out.shape[1:]), + dtype=ys_out.dtype, + device=ys_out.device, + ) + for ys_out in ys_outputs + ] + return list(init) + empty_ys + + loop_idx = torch.zeros([], dtype=torch.int64, device=torch.device("cpu")) + + # NOTE [Pre-allocate scan's output buffer] + # In order to pre-allocate the output buffer for ys, we rely on the meta of scan's fx_node. + # However, the meta consists of concrete symints, we need to bind those symints with + # proxies in order to trace the torch.empty_strided call correctly. + # + # Also note that basic free symbols of tensor's shapes are guaranteed to be lifted as subgraph inputs + # in dynamo so we can always re-construct the sym expression from placeholders. + # See Note [Auto lift basic free symbols when create_graph_input] for how this is done. + bound_symbols = { + arg.node.expr: arg + for arg in pytree.tree_leaves((args, scan_length)) + if isinstance(arg, torch.SymInt) + } + ys_outs = [ + torch.empty_strided( + resolve_shape_to_proxy(ys_out.size(), bound_symbols), + resolve_shape_to_proxy(ys_out.stride(), bound_symbols), + device=ys_out.device, + dtype=ys_out.dtype, + layout=ys_out.layout, + requires_grad=ys_out.requires_grad, + ) + for ys_out in ys_outputs + ] + + while_loop_operands = (loop_idx, ys_outs, init, xs) + flat_operands, operands_spec = pytree.tree_flatten(while_loop_operands) + _, operands_and_additional_inputs_spec = pytree.tree_flatten( + (*while_loop_operands, additional_inputs) + ) + + # Step 2: create the cond_fn and body_fn for while_loop + def cond_fn(*flat_args): + loop_idx, _, _, _, _ = pytree.tree_unflatten( + flat_args, operands_and_additional_inputs_spec + ) # type: ignore[has-type] + return loop_idx < scan_length # type: ignore[has-type] + + def body_fn(*flat_args): + loop_idx, ys_outs, carry, xs, additional_inputs = pytree.tree_unflatten( + flat_args, + operands_and_additional_inputs_spec, # type: ignore[has-type] + ) + + idx_int = loop_idx.item() + torch.ops.aten._assert_scalar.default(idx_int >= 0, "") + torch.ops.aten._assert_scalar.default(idx_int < scan_length, "") + sub_xs = [torch.ops.aten.select.int(x, 0, idx_int) for x in xs] + next_carry, ys = _extract_carry_and_out( + sub_gm(*(list(carry) + sub_xs + list(additional_inputs))), + num_init_leaves, + ) + for y, y_out in zip(ys, ys_outs): + y_out_slice = torch.ops.aten.select.int(y_out, 0, idx_int) + y_out_slice.copy_(y) + return loop_idx + 1, *ys_outs, *next_carry, *xs + + # Step 3: call the while_loop operator + _, ys_outs, last_carry, _ = pytree.tree_unflatten( + torch.ops.higher_order.while_loop( + cond_fn, + body_fn, + tuple(flat_operands), + tuple(additional_inputs), + ), + operands_spec, + ) + return list(last_carry) + list(ys_outs) + + lower_to_while_loop_args, tree_spec = pytree.tree_flatten( + ( + fx_init, + fx_xs, + fx_additional_inputs, + ) + ) + match.replace_by_example( + lower_to_while_loop, + lower_to_while_loop_args, + run_functional_passes=False, + ) + + graph_pass.apply(gm) + + for _node in gm.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.scan + ): + raise AssertionError("scan is not lowered to while_loop") + + +@init_once_fakemode +def lazy_init(input_device: torch.device | None = None): + if torch._C._has_mkldnn: + from . import decompose_mem_bound_mm # noqa: F401 + from .mkldnn_fusion import _mkldnn_fusion_init + + _mkldnn_fusion_init() + else: + from .quantization import _register_woq_lowerings + + _register_woq_lowerings() + + # Put this patterns in post-grad pass rather than joint-graph + # pass since otherwise there will be perf/peak-memory regression: + # https://github.com/pytorch/pytorch/issues/148141 + register_replacement( + # pyrefly: ignore [bad-argument-type] + prepare_softmax_pattern, + # pyrefly: ignore [bad-argument-type] + prepare_softmax_replacement, + [torch.empty(4, 8)], + scalar_workaround=dict(dim=-1), + # pyrefly: ignore [bad-argument-type] + trace_fn=fwd_only, + # pyrefly: ignore [bad-argument-type] + pass_dicts=pass_patterns[1], + extra_check=prepare_softmax_extra_check, + ) + + +def reorder_for_locality(graph: torch.fx.Graph): + if torch.distributed.is_available(): + + def check(): + # This is a wait node, and `other_node`` is some collective node. + # Eager semantics allow waits to be issued in a different order than + # the collectives. Reordering this wait node might reorder collectives + # which cause hangs. Once we have SPMD mode, we can safely reorder them. + # However, increasing the locality between a collective and its wait node + # is generally worse for performance. + return node.target != torch.ops._c10d_functional.wait_tensor.default + else: + + def check(): + return True + + def consumes_rng_state(node: torch.fx.Node) -> bool: + return ( + node.op == "call_function" + and isinstance(node.target, torch._ops.OpOverload) + and torch.Tag.nondeterministic_seeded in node.target.tags + ) + + def visit(other_node): + if ( + other_node.op == "call_function" + and other_node.target != operator.getitem + and all((n in seen_nodes) for n in other_node.users) + and get_mutation_region_id(graph, node) + == get_mutation_region_id(graph, other_node) + and check() + ): + # Ops that consume RNG state are order-sensitive and must not be + # reordered during locality optimization. + if consumes_rng_state(other_node): + return + + # move node's producers right before it + node.prepend(other_node) + + seen_nodes = OrderedSet[torch.fx.Node]() + + # only reorder nodes before the first copy_ in the graph. + # copy_ will appear at the end of functionalized graphs when there is mutation on inputs, + # and this reordering doesn't work well with mutation + first_copy = next( + iter(graph.find_nodes(op="call_function", target=torch.ops.aten.copy_.default)), + None, + ) + past_mutating_epilogue = first_copy is None + + for node in reversed(graph.nodes): + seen_nodes.add(node) + if not past_mutating_epilogue: + past_mutating_epilogue = node is first_copy + continue + + torch.fx.map_arg((node.args, node.kwargs), visit) + + +def register_lowering_pattern( + pattern, + extra_check=_return_true, + pass_number=1, + *, + output_metadata_ignores_input_storage: bool = True, + output_metadata_is_input: int | str | None = None, + output_metadata_fn: Callable[..., Any] | None = None, +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + """ + Register an aten to inductor IR replacement pattern + """ + return pattern_matcher.register_lowering_pattern( + pattern, + extra_check, + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[pass_number], + output_metadata_ignores_input_storage=output_metadata_ignores_input_storage, + output_metadata_is_input=output_metadata_is_input, + output_metadata_fn=output_metadata_fn, + ) + + +################################################################################ +# Actual patterns below this point. +# Priority of patterns is: +# - later output nodes first +# - order patterns are defined in +################################################################################ + + +def is_valid_mm_plus_mm(match: Match): + if not (config.max_autotune or config.max_autotune_gemm): + return False + + # Check if all required values exist + mat1_val = match.kwargs["mat1"].meta.get("val") + mat2_val = match.kwargs["mat2"].meta.get("val") + mat3_val = match.kwargs["mat3"].meta.get("val") + mat4_val = match.kwargs["mat4"].meta.get("val") + + if mat1_val is None or mat2_val is None or mat3_val is None or mat4_val is None: + return False + + *_b1, m1, k1 = mat1_val.shape + *_b2, k2, n1 = mat2_val.shape + if k1 != k2: + return False + + *_b1, m2, k3 = mat3_val.shape + *_b2, k4, n2 = mat4_val.shape + if k3 != k4: + return False + + if m1 != m2 or n1 != n2: + return False + + return True + + +@register_lowering_pattern( + CallFunction( + aten.add, + CallFunction(aten.mm, KeywordArg("mat1"), KeywordArg("mat2")), + CallFunction(aten.mm, KeywordArg("mat3"), KeywordArg("mat4")), + ), + extra_check=is_valid_mm_plus_mm, +) +def mm_plus_mm(match: Match, mat1, mat2, mat3, mat4): + return inductor.kernel.mm_plus_mm.tuned_mm_plus_mm(mat1, mat2, mat3, mat4) + + +@register_graph_pattern( + CallFunction( + aten.cumsum.default, + CallFunction( + torch.ops.aten.full.default, + KeywordArg("shape"), + KeywordArg("fill_value"), + dtype=KeywordArg("dtype"), + layout=Ignored(), + device=KeywordArg("device"), + pin_memory=False, + _users=MULTIPLE, + ), + KeywordArg("dim"), + _users=MULTIPLE, + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[1], +) +def pointless_cumsum_replacement(match: Match, shape, fill_value, device, dtype, dim): + """Based on a pattern in OPTForCausalLM""" + + if is_integer_dtype(dtype) or is_boolean_dtype(dtype): + # match full()'s fill_value cast + fill_value = int(bool(fill_value) if is_boolean_dtype(dtype) else fill_value) + # cumsum promotes all integral types to int64 + dtype = torch.int64 + + out_dtype = match.output_node().kwargs.get("dtype") or dtype + bool_out = is_boolean_dtype(out_dtype) # pyrefly: ignore[bad-argument-type] + # pyrefly: ignore[bad-argument-type] + integral_out = bool_out or is_integer_dtype(out_dtype) + if integral_out: + fill_value = int(bool(fill_value) if bool_out else fill_value) + acc_dtype = torch.int64 if integral_out else torch.float64 + + def repl(*shape): + dim_size = shape[dim] + idx = torch.arange(1, dim_size + 1, device=device, dtype=acc_dtype) + + inter_shape = [1] * len(shape) + inter_shape[dim] = dim_size + return (idx * fill_value).view(inter_shape).expand(shape).to(out_dtype) + + # only replace the output node, not all nodes + match.nodes = [match.output_node()] + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(repl, list(shape)) + + +_cat_1 = CallFunction(aten.cat, Arg(), 1, _users=2) + + +@register_lowering_pattern( + CallFunction( + aten.cat, + [ + _cat_1, + CallFunction( + aten.slice, + _cat_1, + 1, + 0, + KeywordArg("size"), + ), + ], + 1, + ) +) +def cat_slice_cat(match, cat_input, size, dim=1): + """ + This is an example of a more complex pattern where cat_1 is used + multiple times inside the pattern. We fold 2 calls to cat into one. + + Matches: + cat_1: f32[1024, 4077] = torch.ops.aten.cat.default([add_26, primals_217], 1) + slice_1: f32[1024, 4077] = torch.ops.aten.slice.Tensor(cat_1, 0, 0, 9223372036854775807) + slice_2: f32[1024, 19] = torch.ops.aten.slice.Tensor(slice_1, 1, 0, 19) + cat_2: f32[1024, 4096] = torch.ops.aten.cat.default([cat_1, slice_2], 1) + + + Rewrite to: + slice_2 = torch.ops.aten.slice.Tensor(add_26, 1, 0, 19) + cat_2 = torch.ops.aten.cat.default([add_26, primals_217, slice2], 1) + """ + first, *rest = cat_input + # Optimization is optional, because we can just not fold the cat + # size should be within first.get_size()[dim] such that the optimization is valid. + # For negative `end`, we currently fallback to not optimizing. + if size >= 0 and V.graph.sizevars.statically_known_leq(size, first.get_size()[dim]): + # fold 2 cats into 1 cat + return L[aten.cat]( + [ + first, + *rest, + L[aten.slice](first, dim, 0, size), + ], + dim, + ) + else: + # don't expect to hit this case, just fall back + tmp = L[aten.cat](cat_input, dim) + return L[aten.cat]( + [ + tmp, + L[aten.slice](tmp, dim, 0, size), + ], + dim, + ) + + +def is_valid_splitwithsizes_cat(match): + split_nodes = filter_nodes(match.nodes, aten.split_with_sizes) + cat_nodes = filter_nodes(match.nodes, aten.cat) + get_item_nodes = filter_nodes(match.nodes, operator.getitem) + if len(split_nodes) != 1 or len(cat_nodes) != 1: + return False + split_node, cat_node = split_nodes[0], cat_nodes[0] + # The dim of split and cat should match for passthrough + if get_arg_value(split_node, 2, "dim") != get_arg_value(cat_node, 1, "dim"): + return False + get_item_args = OrderedSet( + get_arg_value(get_item_node, 1) for get_item_node in get_item_nodes + ) + if None in get_item_args: + raise AssertionError(f"expected no None in get_item_args, got {get_item_args}") + split_sizes = get_arg_value(split_node, 1, "split_sizes") + # All parts of split should be included in the cat + if get_item_args != OrderedSet(range(len(split_sizes))): + return False + # The order of get_item_args should same with cat_node used. + # For example, if the split_node like split_with_sizes(input, [2, 2, 3], 1), + # the cat node should be like cat([get_item(0), get_item(1), get_item(2)], 1). + cat_items_args_order = [ + get_arg_value(item_node, 1) for item_node in get_arg_value(cat_node, 0) + ] + if cat_items_args_order != list(range(len(split_sizes))): + return False + + return True + + +def same_meta(node1: torch.fx.Node, node2: torch.fx.Node): + """True if two nodes have the same metadata""" + val1 = node1.meta.get("val") + val2 = node2.meta.get("val") + return ( + val1 is not None + and val2 is not None + and isinstance(val1, torch.Tensor) + and isinstance(val2, torch.Tensor) + and statically_known_true(sym_eq(val1.size(), val2.size())) + and val1.layout == val2.layout + and val1.dtype == val2.dtype + and val1.device == val2.device + and ( + val1.layout != torch.strided + or statically_known_true(sym_eq(val1.stride(), val2.stride())) + ) + # Check conjugate and negative bits - a clone that resolves these is not a no-op + and val1.is_conj() == val2.is_conj() + and val1.is_neg() == val2.is_neg() + ) + + +noop_registry: dict[Any, Any] = {} + + +def register_noop_decomp(targets, nop_arg=0): + def register_fun(cond): + register_decomposition(targets, registry=noop_registry, unsafe=True)( + (cond, nop_arg) # type: ignore[arg-type] + ) + return cond + + return register_fun + + +def _needs_spmd_graph_preservation() -> bool: + """Check if SPMD graph preservation is needed for distributed overlap.""" + return ( + config.aten_distributed_optimizations.enable_overlap_scheduling + or config.reorder_for_compute_comm_overlap + ) + + +@register_noop_decomp(aten.slice) +def slice_noop(self, dim=0, start=None, end=None, step=1): + if _needs_spmd_graph_preservation(): + # Keep no-op slices so all ranks produce identical FX graphs (SPMD) + # with matching op counts and runtime estimations. + return False + if start is None or end is None: + return False + + slice_dim_size = self.shape[dim] + if ( + statically_known_true(sym_eq(start, 0)) + and ( + statically_known_true(end >= 2**63 - 1) + or statically_known_true(end >= slice_dim_size) + ) + and statically_known_true(sym_eq(step, 1)) + ): + return True + return False + + +@register_noop_decomp(aten.slice_scatter, 1) +def slice_scatter_noop(self, src, dim=0, start=None, end=None, step=1): + if start is None: + start = 0 + if end is None: + end = 2**63 - 1 + slice_scatter_dim_size = self.shape[dim] + if ( + self.shape == src.shape + and start == 0 + and ( + statically_known_true(end >= 2**63 - 1) + or statically_known_true(end >= slice_scatter_dim_size) + ) + and step == 1 + ): + return True + return False + + +@register_noop_decomp(aten.repeat) +def repeat_noop(self, repeats): + return all(r == 1 for r in repeats) + + +@register_noop_decomp(aten.constant_pad_nd) +def constant_pad_nd(x, padding, fill_value=0): + if _needs_spmd_graph_preservation(): + # Keep no-op pads so all ranks produce identical FX graphs (SPMD) + # with matching op counts and runtime estimations. + return False + return all(p == 0 for p in padding) + + +@register_noop_decomp(torch.ops.prims.convert_element_type) +def convert_element_type_noop(x, dtype: torch.dtype): + return x.dtype == dtype + + +@register_noop_decomp(torch.ops.prims.device_put) +def device_put_noop(x, device, non_blocking=True): + return x.device == decode_device(device) + + +@register_noop_decomp([aten.ceil, aten.floor, aten.round, aten.trunc]) +def int_noop(x): + return is_integer_dtype(x.dtype) + + +@register_noop_decomp([aten.pow]) +def pow_noop(a, b): + return isinstance(b, int) and b == 1 + + +@register_noop_decomp([aten.cat], lambda args: args[0][0]) +def cat_noop(inputs, dim=0): + return len(inputs) == 1 + + +@register_noop_decomp(aten.view.default) +def view_default_noop(arg, size): + return statically_known_true(sym_eq(arg.shape, tuple(size))) + + +@register_noop_decomp(aten.view.dtype) +def view_dtype_noop(arg, dtype): + return arg.dtype == dtype + + +# Note, we also always have a check for identical metadata, which is why these +# are safe +@register_noop_decomp([aten.copy], nop_arg=1) +@register_noop_decomp([aten.alias, aten.clone]) +def true_noop(*args, **kwargs): + return True + + +def remove_noop_ops(graph: torch.fx.Graph): + """ + Removes both operations that are essentially aten.clone and operations that are essentially aten.alias from the graph. + """ + inputs = OrderedSet[torch.fx.Node]() + input_storages = OrderedSet[int | None]() + output_storages = OrderedSet[int | None]() + + for node in graph.find_nodes(op="placeholder"): + inputs.add(node) + input_storages.add(get_node_storage(node)) + + output_node = next(iter(reversed(graph.nodes))) + if output_node.op != "output": + raise AssertionError(f"expected output node, got {output_node.op}") + outputs = output_node.args[0] + if not isinstance(outputs, (list, tuple)): + # nested subgraphs can have singleton outputs + outputs = (outputs,) + for out in outputs: + if isinstance(out, torch.fx.Node): + output_storages.add(get_node_storage(out)) + + for node in graph.nodes: + if node.target in noop_registry: + cond, src_index = noop_registry[node.target] + if isinstance(src_index, int): + src = node.args[src_index] + else: + src = src_index(node.args) + if not isinstance(src, torch.fx.Node): + continue + + if node.target is torch.ops.aten.copy.default: + dst = node.args[0] + if ( + isinstance(dst, torch.fx.Node) + and dst.op == "call_function" + and dst.kwargs.get("pin_memory") is True + ): + continue + + # Don't introduce new aliasing between inputs and outputs. + # See fx_passes/README.md for a discussion of why this is + # necessary. + node_storage = get_node_storage(node) + src_storage = get_node_storage(src) + node_is_view = node_storage == src_storage + if ( + not node_is_view + and node_storage in output_storages + and (src_storage in input_storages or src_storage in output_storages) + ): + continue + + # Even if input and outputs are expected to alias, + # don't make "node is src" True + if ( + node_is_view + and node in output_node.args + and (src in inputs or src in output_node.args) + ): + continue + + is_valid, args, kwargs = get_fake_args_kwargs(node) + if not is_valid: + continue + if same_meta(node, src) and cond(*args, **kwargs): + node.replace_all_uses_with(src) + graph.erase_node(node) + + +def remove_assert_ops(graph: torch.fx.Graph): + """ + Removes aten._assert_tensor_metadata.default op because + 1) it will be lowered to a no-op in inductor + 2) it can block fusion, such as unfuse_bias_add_to_pointwise fusion. + + This op could come from aten.to functionalization in export. + + For example, if we have a graph like below + + %addmm = aten.addmm.default(%linear_bias, %arg3_1, %permute) + %_assert_tensor_metadata = aten._assert_tensor_metadata.default(%addmm, None, None, torch.float16) + %convert_element_type_3 = prims.convert_element_type.default(%addmm, torch.float32) + %pow_1 = aten.pow.Tensor_Scalar(%convert_element_type_3, 2) + + We still want to fuse add from addmm with pow, instead of fusing add with mm, according to unfuse_bias_add_to_pointwise fusion. + + However, aten._assert_tensor_metadata.default is not a pointwise op, and would fail the should_prefer_unfused_addmm check. + + We remove this op so it doesn't block fusion decisions. It's safe because this op is lowered to a no-op with @register_lowering. + + """ + for node in graph.find_nodes( + op="call_function", target=torch.ops.aten._assert_tensor_metadata.default + ): + graph.erase_node(node) + + +def apply_pass_to_subgraphs(pass_fn: Callable[[fx.Graph], None], graph: fx.Graph): + """Recursively apply a pass function to all subgraphs referenced by get_attr nodes.""" + gm = graph.owning_module + if gm is None: + return + subgraph_names: OrderedSet[str] = OrderedSet( + x.target for x in graph.find_nodes(op="get_attr") + ) + for child_name, child_mod in gm.named_children(): + if child_name in subgraph_names and isinstance(child_mod, torch.fx.GraphModule): + pass_fn(child_mod.graph) + + +def apply_pass_to_control_deps_subgraphs( + pass_fn: Callable[[fx.Graph], None], graph: fx.Graph +): + """Recursively apply a pass function to subgraphs referenced by control_deps.""" + gm = graph.owning_module + if gm is None: + return + + for node in graph.find_nodes(op="call_function", target=control_deps): + if len(node.args) < 2: + continue + subgraph_attr = node.args[1] + if ( + not isinstance(subgraph_attr, torch.fx.Node) + or subgraph_attr.op != "get_attr" + or not isinstance(subgraph_attr.target, str) + ): + continue + subgraph = getattr(gm, subgraph_attr.target, None) + if isinstance(subgraph, torch.fx.GraphModule): + pass_fn(subgraph.graph) + + +def _get_single_replacement_node( + replacement_nodes: Sequence[torch.fx.Node], target: torch.fx.node.Target +) -> torch.fx.Node: + nodes = [ + node + for node in replacement_nodes + if node.op == "call_function" and node.target is target + ] + if len(nodes) != 1: + raise AssertionError(f"Expected exactly one replacement node for {target}") + return nodes[0] + + +def _propagate_triton_eager_input_vals( + replacement_nodes: Sequence[torch.fx.Node], + hop_node: torch.fx.Node, +) -> None: + eager_input_vals = hop_node.meta.get("eager_input_vals") + if eager_input_vals is None: + return + + _, eager_kwargs = eager_input_vals + mutation_eager_kwargs = { + key: value for key, value in eager_kwargs.items() if key != "tensors_to_clone" + } + # The dense decomposition introduces clones plus the mutation HOP, but only + # the mutation HOP should receive the eager-mode tensor metadata. + mutation_node = _get_single_replacement_node( + replacement_nodes, torch.ops.higher_order.triton_kernel_wrapper_mutation + ) + mutation_node.meta["eager_input_vals"] = ((), mutation_eager_kwargs) + + +def decompose_triton_kernel_wrapper_functional(graph): + """Decomposes triton_kernel_wrapper_functional nodes into clones and the underlying + mutation node. + + We assume that the reinplacing pass runs before this; the reinplacing pass + tells us (via rewriting the arguments or .meta to those nodes) which + Tensors we should clone and which Tensors are safe to reinplace. + """ + # First, recursively process any subgraphs + apply_pass_to_subgraphs(decompose_triton_kernel_wrapper_functional, graph) + + graph_pass = PatternMatcherPass() + + @register_graph_pattern( + CallFunctionVarArgs(torch.ops.higher_order.triton_kernel_wrapper_functional), + # pyrefly: ignore [bad-argument-type] + pass_dict=graph_pass, + ) + def _(match: Match, *args, **kwargs): + from torch._higher_order_ops.triton_kernel_wrap import ( + triton_kernel_wrapper_functional_dense, + ) + + hop_node = match.nodes[0] + flat_args, spec = pytree.tree_flatten((args, kwargs)) + + # NB: we combine (args, kwargs) into flat args for replacing. + # This is replace_by_example uses make_fx which does not support + # tracing a function with kwargs. + def decomp(*flat_args): + args, kwargs = pytree.tree_unflatten(flat_args, spec) + return (triton_kernel_wrapper_functional_dense(*args, **kwargs),) + + # pyrefly: ignore [bad-argument-type] + replacement_nodes = match.replace_by_example( + decomp, flat_args, run_functional_passes=False + ) + _propagate_triton_eager_input_vals(replacement_nodes, hop_node) + + graph_pass.apply(graph) + + for _ in graph.find_nodes( + op="call_function", + target=torch.ops.higher_order.triton_kernel_wrapper_functional, + ): + raise AssertionError("triton_kernel_wrapper_functional was not removed") + + +def fix_auto_functionalized_dtype_views(graph: torch.fx.Graph) -> None: + """ + Fix aliasing detection for dtype views in auto_functionalized_v2. + + When a dtype view shares storage with a graph input, we can skip cloning + it during decomposition because the view can be safely regenerated. + + This pass identifies such cases and updates the reinplace metadata to + indicate no clone is needed. + """ + storage_to_input: dict[int, torch.fx.Node] = {} + for node in graph.find_nodes(op="placeholder"): + storage = get_node_storage(node) + if storage is not None: + storage_to_input[storage] = node + + for node in graph.find_nodes( + op="call_function", target=torch.ops.higher_order.auto_functionalized_v2 + ): + all_bases = node.kwargs.get("_all_bases") + only_clone_these = node.meta.get("only_clone_these_tensors") + if all_bases is None or only_clone_these is None: + continue + + keep = [] + for idx in only_clone_these: + if idx >= len(all_bases): + keep.append(idx) + continue + base = all_bases[idx] + if not isinstance(base, torch.fx.Node): + keep.append(idx) + continue + base_storage = get_node_storage(base) + if base_storage is None or base_storage not in storage_to_input: + keep.append(idx) + continue + input_val = storage_to_input[base_storage].meta["val"] + if input_val.dtype == base.meta["val"].dtype: + keep.append(idx) + continue + counters["inductor"]["fix_auto_functionalized_dtype_views"] += 1 + + if len(keep) != len(only_clone_these): + node.meta["only_clone_these_tensors"] = keep + + +def decompose_auto_functionalized(graph): + """Decomposes auto_functionalized nodes into clones and the underlying + mutation node. + + We assume that the reinplacing pass runs before this; the reinplacing pass + tells us (via rewriting the arguments or .meta to those nodes) which + Tensors we should clone and which Tensors are safe to reinplace. + """ + apply_pass_to_control_deps_subgraphs(decompose_auto_functionalized, graph) + + graph_pass = PatternMatcherPass() + + @register_graph_pattern( + CallFunctionVarArgs(torch.ops.higher_order.auto_functionalized), + # pyrefly: ignore [bad-argument-type] + pass_dict=graph_pass, + ) + def _(match: Match, *args, **kwargs): + from torch._higher_order_ops.auto_functionalize import auto_functionalized_dense + + only_clone_these_tensors = match.nodes[0].meta.get("only_clone_these_tensors") + if only_clone_these_tensors is not None: + only_clone_these_tensors = tuple(only_clone_these_tensors) + + flat_args, spec = pytree.tree_flatten((args, kwargs)) + + # NB: we combine (args, kwargs) into flat args for replacing. + # This is replace_by_example uses make_fx which does not support + # tracing a function with kwargs. + def decomp(*flat_args): + args, kwargs = pytree.tree_unflatten(flat_args, spec) + if len(args) != 1: + raise AssertionError(f"expected 1 arg, got {len(args)}") + mode = args[0] + return auto_functionalized_dense(mode, only_clone_these_tensors, **kwargs) + + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(decomp, flat_args, run_functional_passes=False) + + @register_graph_pattern( + CallFunctionVarArgs(torch.ops.higher_order.auto_functionalized_v2), + # pyrefly: ignore [bad-argument-type] + pass_dict=graph_pass, + ) + def _(match: Match, *args, **kwargs): + from torch._higher_order_ops.auto_functionalize import ( + auto_functionalized_v2_dense, + ) + + only_clone_these_bases = match.nodes[0].meta.get("only_clone_these_tensors") + if only_clone_these_bases is not None: + only_clone_these_bases = tuple(only_clone_these_bases) + + flat_args, spec = pytree.tree_flatten((args, kwargs)) + + def _maybe_resolve_constant_get_attr(node): + # Resolve getattr node to its value because they don't always have meta["val"] + if ( + isinstance(node, torch.fx.Node) + and node.op == "get_attr" + and "val" not in node.meta + ): + const_attr = getattr(graph.owning_module, node.target) # type: ignore[arg-type] + if not isinstance(const_attr, (torch.fx.GraphModule, pytree.TreeSpec)): + raise AssertionError((type(const_attr), const_attr)) + return const_attr + return node + + flat_args = [_maybe_resolve_constant_get_attr(arg) for arg in flat_args] + + # NB: we combine (args, kwargs) into flat args for replacing. + # This is replace_by_example uses make_fx which does not support + # tracing a function with kwargs. + def decomp(*flat_args): + args, kwargs = pytree.tree_unflatten(flat_args, spec) + if len(args) != 1: + raise AssertionError(f"expected 1 arg, got {len(args)}") + mutable_op = args[0] + return auto_functionalized_v2_dense( + mutable_op, only_clone_these_bases, **kwargs + ) + + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(decomp, flat_args, run_functional_passes=False) + + graph_pass.apply(graph) + + # Remove unused get_attr nodes and their corresponding attributes from the graph module. + # When auto_functionalizing a hop, we need to clean up get_attr nodes for _constant_schema + # and the auto_functionalized graph module that are no longer referenced. + unused_get_attr_nodes = [] + removable_attrs: OrderedSet[torch.fx.node.Target] = OrderedSet() + protected_attrs: OrderedSet[torch.fx.node.Target] = OrderedSet() + + # First pass: identify unused get_attr nodes and track attribute usage + for node in graph.nodes: + if node.op != "get_attr": + continue + + if len(node.users) == 0: + # Node is unused, mark for removal + unused_get_attr_nodes.append(node) + + # Check if the attribute can be removed from the module + if ( + hasattr(graph.owning_module, node.target) + and isinstance( + getattr(graph.owning_module, node.target), torch.fx.GraphModule + ) + and node.target not in protected_attrs + ): + removable_attrs.add(node.target) + else: + # Node is used, protect its attribute from removal + if node.target in removable_attrs: + removable_attrs.remove(node.target) + protected_attrs.add(node.target) + + # Second pass: clean up unused nodes and attributes + for node in unused_get_attr_nodes: + graph.erase_node(node) + + for attr_name in removable_attrs: + if not isinstance(attr_name, str): + raise AssertionError(f"expected str, got {type(attr_name).__name__}") + delattr(graph.owning_module, attr_name) + + graph.lint() + + for _ in graph.find_nodes( + op="call_function", target=torch.ops.higher_order.auto_functionalized + ): + raise AssertionError("auto_functionalized was not removed") + + for _ in graph.find_nodes( + op="call_function", target=torch.ops.higher_order.auto_functionalized_v2 + ): + raise AssertionError("auto_functionalized_v2 was not removed") + + +@register_lowering_pattern( + CallFunction( + aten.cat, + ListOf( + CallFunction( + operator.getitem, + CallFunction( + aten.split_with_sizes, + KeywordArg("input_"), + Ignored(), + Ignored(), + _users=MULTIPLE, + ), + Ignored(), + ), + ), + Ignored(), + ), + pass_number=2, + extra_check=is_valid_splitwithsizes_cat, + output_metadata_is_input="input_", +) +def splitwithsizes_cat_replace(match, input_): + return input_ + + +def is_valid_cat_splitwithsizes(match): + cat_nodes = filter_nodes(match.nodes, aten.cat) + split_nodes = filter_nodes(match.nodes, aten.split_with_sizes) + if len(split_nodes) != 1 or len(cat_nodes) != 1: + return False + split_node, cat_node = split_nodes[0], cat_nodes[0] + + # the cat node has other users: can't eliminate + if len(cat_node.users) > 1: + return False + + # the dim of the cat and split should match + dim = get_arg_value(split_node, 2, "dim") + if dim != get_arg_value(cat_node, 1, "dim"): + return False + + cat_inputs = list(get_arg_value(cat_node, 0)) + split_sizes = get_arg_value(split_node, 1, "split_sizes") + # the number of input tensors in cat and the + # length of the split sizes should match + if len(cat_inputs) != len(split_sizes): + return False + + for cat_input, split_size in zip(cat_inputs, split_sizes): + # each cat input tensor's size along dim + # should match the corresponding split size + if "val" not in cat_input.meta: + return False + cat_input_size = cat_input.meta["val"].size(dim) + if cat_input_size != split_size: + return False + + return True + + +@register_lowering_pattern( + CallFunction( + aten.split_with_sizes, + CallFunction( + aten.cat, + KeywordArg("input_"), + Ignored(), + _users=MULTIPLE, + ), + Ignored(), + Ignored(), + ), + pass_number=2, + extra_check=is_valid_cat_splitwithsizes, + output_metadata_is_input="input_", +) +def cat_splitwithsizes_replace(match, input_): + return input_ + + +# reciprocal(sqrt(x)) -> rsqrt(x): an unconditional algebraic identity +# (1 / sqrt(x) == rsqrt(x)) that saves one op per element in the generated kernel. +@register_graph_pattern( + CallFunction( + aten.reciprocal.default, + CallFunction(aten.sqrt.default, KeywordArg("x")), + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[1], +) +def reciprocal_sqrt_to_rsqrt(match: Match, x): + """reciprocal(sqrt(x)) -> rsqrt(x)""" + + def repl(x): + return aten.rsqrt(x) + + match.replace_by_example(repl, [x]) + + +def view_to_reshape(gm): + """ + Replace view ops in the GraphModule to reshape ops. + """ + + def _view_to_reshape_graph(graph): + for nd in graph.find_nodes( + op="call_function", target=torch.ops.aten.view.default + ): + nd.target = torch.ops.aten.reshape.default + + def _recursive_view_to_reshape(graph): + apply_pass_to_subgraphs(_recursive_view_to_reshape, graph) + _view_to_reshape_graph(graph) + + _recursive_view_to_reshape(gm.graph) + + +def _is_bias_like_addmm_input(inp: torch.fx.Node, output: torch.fx.Node) -> bool: + if inp.op in ("placeholder", "get_attr"): + return True + + inp_val = inp.meta.get("val") + output_val = output.meta.get("val") + if not (isinstance(inp_val, torch.Tensor) and isinstance(output_val, torch.Tensor)): + return False + + if len(inp_val.shape) != len(output_val.shape): + return True + + same_shape = statically_known_true(sym_eq(inp_val.shape, output_val.shape)) + if not same_shape: + for inp_dim, output_dim in zip(inp_val.shape, output_val.shape): + if statically_known_true(sym_eq(inp_dim, 1)) and not statically_known_true( + sym_eq(output_dim, 1) + ): + return True + return False + + return inp_val.layout == torch.strided and any( + statically_known_true(sym_eq(stride, 0)) for stride in inp_val.stride() + ) + + +def should_prefer_unfused_addmm(match): + inp = match.kwargs["inp"] + if not is_gpu(inp.meta["val"].device.type): + return False + if match.output_node().meta.get(_PRESERVE_FLEX_GEMM_GEMM_OP): + return False + mat1, mat2 = match.args + inp_val = inp.meta["val"] + mat1_val = mat1.meta["val"] + mat2_val = mat2.meta["val"] + if inp_val.dtype != mat1_val.dtype or inp_val.dtype != mat2_val.dtype: + return False + if inp_val.device != mat1_val.device or inp_val.device != mat2_val.device: + return False + beta = match.kwargs.get("beta", 1) + if inp_val.device.type != "cuda" and beta == 0: + mm_shape = mat1_val.shape[0], mat2_val.shape[1] + if not is_expandable_to(inp_val.shape, mm_shape): + return False + + output = match.output_node() + if not _is_bias_like_addmm_input(inp, output): + return False + return all(is_pointwise_use(use) for use in output.users) + + +def should_prefer_unfused_baddbmm(match): + inp = match.kwargs["inp"] + if not is_gpu(inp.meta["val"].device.type): + return False + if match.output_node().meta.get(_PRESERVE_FLEX_GEMM_GEMM_OP): + return False + + output = match.output_node() + if not _is_bias_like_addmm_input(inp, output): + return False + return all(is_pointwise_use(use) for use in output.users) + + +@register_graph_pattern( + CallFunction( + aten.addmm, + KeywordArg("inp"), + Arg(), + Arg(), + beta=KeywordArg("beta"), + alpha=KeywordArg("alpha"), + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[2], + extra_check=should_prefer_unfused_addmm, +) +def unfuse_bias_add_to_pointwise(match: Match, mat1, mat2, *, inp, alpha, beta): + if config.keep_addmm_fused_for_half_dtypes and inp.meta["val"].dtype in ( + torch.bfloat16, + torch.float16, + ): + # Narrowing-cast unfuse (PR #183680) is XPU-only: it preserves + # precision on XPU pointwise but regresses accuracy on ROCm + # (basic_gnn_edgecnn training+amp fails on gfx950 otherwise). + if inp.meta["val"].device.type != "xpu": + return + if not ( + inp.op == "call_function" + and inp.target is torch.ops.prims.convert_element_type.default + and inp.args[0].meta["val"].dtype.is_floating_point + and torch.finfo(inp.args[0].meta["val"].dtype).bits + > torch.finfo(inp.meta["val"].dtype).bits + ): + return + + drop_input_for_beta_zero = inp.meta["val"].device.type == "cuda" + + def repl(inp, x1, x2, alpha, beta): + if alpha == 0 and beta == 0 and drop_input_for_beta_zero: + return x1.new_zeros((x1.shape[0], x2.shape[1])) + mm_result = x1 @ x2 + if alpha != 1: + mm_result = alpha * mm_result + if beta == 0 and drop_input_for_beta_zero: + return mm_result + if beta != 1: + inp = beta * inp + return inp + mm_result + + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(repl, [inp, mat1, mat2, alpha, beta]) + + +@register_graph_pattern( + CallFunction( + aten.baddbmm, + KeywordArg("inp"), + Arg(), + Arg(), + beta=KeywordArg("beta"), + alpha=KeywordArg("alpha"), + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[2], + extra_check=should_prefer_unfused_baddbmm, +) +def unfuse_bias_baddbmm_to_pointwise(match: Match, mat1, mat2, *, inp, alpha, beta): + if config.keep_addmm_fused_for_half_dtypes and inp.meta["val"].dtype in ( + torch.bfloat16, + torch.float16, + ): + if inp.meta["val"].device.type != "xpu": + return + if not ( + inp.op == "call_function" + and inp.target is torch.ops.prims.convert_element_type.default + and inp.args[0].meta["val"].dtype.is_floating_point + and torch.finfo(inp.args[0].meta["val"].dtype).bits + > torch.finfo(inp.meta["val"].dtype).bits + ): + return + + def repl(inp, x1, x2, alpha, beta): + bmm_result = torch.bmm(x1, x2) + if alpha != 1: + bmm_result = alpha * bmm_result + if beta != 1: + inp = beta * inp + return inp + bmm_result + + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(repl, [inp, mat1, mat2, alpha, beta]) + + +def is_valid_addmm_fusion(match): + if any( + node.target is aten.mm.default and node.meta.get(_PRESERVE_FLEX_GEMM_GEMM_OP) + for node in match.nodes + ): + return False + + mat1, mat2 = match.args + inp = match.kwargs["inp"] + + if not ( + isinstance(inp, torch.fx.Node) and isinstance(inp.meta["val"], torch.Tensor) + ): + return False # Input is a number + + in_shape = inp.meta["val"].shape + mm_shape = mat1.meta["val"].shape[0], mat2.meta["val"].shape[1] + matched = is_expandable_to(in_shape, mm_shape) + if not matched: + return False # Shape mismatch + + inp_dtype = inp.meta["val"].dtype + + # aten cublas integration assumes equal dtypes + if inp_dtype != mat1.meta["val"].dtype or inp_dtype != mat2.meta["val"].dtype: + return False + + return not should_prefer_unfused_addmm(match) + + +@register_graph_pattern( + CallFunction( + aten.add, + CallFunction(aten.mm, Arg(), Arg()), + KeywordArg("inp"), + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[2], + extra_check=is_valid_addmm_fusion, +) +@register_graph_pattern( + CallFunction( + aten.add, + KeywordArg("inp"), + CallFunction(aten.mm, Arg(), Arg()), + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[2], + extra_check=is_valid_addmm_fusion, +) +def addmm(match, mat1, mat2, *, inp): + def repl(inp, mat1, mat2): + return aten.addmm(inp, mat1, mat2) + + match.replace_by_example(repl, [inp, mat1, mat2]) + + +def _is_addcdiv_fma_eligible(match: Match) -> bool: + """Guards for the addcdiv FMA re-fusion pass.""" + # aten.addcdiv requires floating-point self; check inp, not output, because + # aten.div promotes integers to float so the output is float even for int inp. + inp_val = match.kwargs["inp"].meta.get("val") + if not (isinstance(inp_val, torch.Tensor) and inp_val.dtype.is_floating_point): + return False + # tl.fma / div_rn are Triton GPU-only + out_val = match.output_node().meta.get("val") + if not ( + isinstance(out_val, torch.Tensor) and out_val.device.type in ("cuda", "xpu") + ): + return False + # aten.addcdiv requires all tensor args to be floating-point; integer + # constants and SymInts can appear as t1/t2 in decomposed graphs. + for key in ("t1", "t2"): + node = match.kwargs.get(key) + val = node.meta.get("val") if isinstance(node, torch.fx.Node) else node + if not (isinstance(val, torch.Tensor) and val.dtype.is_floating_point): + return False + # aten.addcdiv requires a scalar value, not a tensor + return not isinstance(match.kwargs.get("value"), torch.fx.Node) + + +@register_graph_pattern( + CallFunction( + aten.add.Tensor, + KeywordArg("inp"), + CallFunction( + aten.mul.Tensor, + CallFunction(aten.div.Tensor, KeywordArg("t1"), KeywordArg("t2")), + KeywordArg("value"), + ), + ), + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[2], + extra_check=_is_addcdiv_fma_eligible, +) +def _fuse_addcdiv_to_fma(match: Match, inp, t1, t2, value) -> None: + """Re-fuse ``inp + (t1/t2)*value`` back into ``aten.addcdiv``. + + torch.addcdiv is CompositeImplicitAutograd: it decomposes into + aten.div + aten.mul + aten.add before Inductor sees the graph, making the + FMA-aware lowering in lowering.py unreachable. Re-inserting a single + aten.addcdiv node lets that lowering fire (tl.fma + triton.language.div_rn). + """ + + def repl( + inp: torch.Tensor, t1: torch.Tensor, t2: torch.Tensor, value + ) -> torch.Tensor: + return torch.ops.aten.addcdiv(inp, t1, t2, value=value) + + counters["inductor"]["addcdiv_fma_fused"] += 1 + match.replace_by_example(repl, [inp, t1, t2, value]) + + +def register_partial_reduction_pattern(): + "Reuse partial reductions in complete reductions" + + # post grad equivalents + equiv_red = { + aten.amax.default: aten.max.default, + aten.amin.default: aten.min.default, + } + + # TODO: to support other reductions like sum, would need to skip + # lower precision reductions since partial output would need to be kept at fp32. + for red_op in (aten.amax.default, aten.amin.default): + inp = KeywordArg("input") + partial_reduc = CallFunction( + red_op, inp, KeywordArg("reduced_dims"), KeywordArg("keepdim") + ) + full_reduc = CallFunction([red_op, equiv_red[red_op]], inp) + + @register_graph_pattern( + MultiOutputPattern([partial_reduc, full_reduc]), + # pyrefly: ignore [bad-argument-type] + pass_dict=pass_patterns[2], + ) + def reuse_partial(match, input, reduced_dims, keepdim): + partial_red, full_red = match.output_nodes() + + # if they're small, reuse not worth it + if not statically_known_true(input.meta["val"].numel() >= 4096): + return True + + def replacement(inp: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + partial = partial_red.target(inp, reduced_dims, keepdim) + complete = full_red.target(partial) + return (partial, complete) + + counters["inductor"]["partial_reduction_reuse"] += 1 + match.replace_by_example(replacement, [input]) + + +register_partial_reduction_pattern() + + +def check_shape_cuda_and_fused_int_mm_mul_enabled(match): + return ( + config.force_fuse_int_mm_with_mul + and len(getattr(match.args[2].meta.get("val"), "shape", [])) == 2 + and getattr(match.args[2].meta.get("val"), "is_cuda", False) + ) + + +def is_index_put_and_requires_h2d_sync_for_gpu_value(node): + from torch.fx.operator_schemas import normalize_function + + if node.target not in [ + torch.ops.aten.index_put.default, + torch.ops.aten.index_put_.default, + ]: + return False + # Inductor falls back to aten.index_put_. + # index_put_ will call nonzero() and perform a H2D sync if + # any of its indices are bool/byte tensors + # However, it will short-circuit this H2D sync and run mask_fill_ + # if the value we are putting is a cpu scalar. + # Therefore, when inductor sees an index_put_ with byte tensor indices, + # it should *not* convert the cpu scalar value into a gpu tensor. + args_, _kwargs = normalize_function(node.target, node.args, node.kwargs) # type: ignore[misc] + any_byte_bool_indices = False + indices = args_[1] + for i in indices: + if i is not None and i.meta["val"].dtype in [torch.bool, torch.int8]: + any_byte_bool_indices = True + + val = args_[2].meta["val"] + val_is_cpu_scalar = val.device.type == "cpu" and val.numel() == 1 + # If both these conditions hold, then converting the val + # to a gpu tensor will incur a H2D sync when inductor calls aten.index_put_ + return any_byte_bool_indices and val_is_cpu_scalar + + +class ConstructorMoverPass: + def __init__( + self, target: str, allow_outputs: bool = False, allow_inputs: bool = False + ) -> None: + """ + Move constructors from cpu to the target_device. + + Sweeps through the module, looking for constructor nodes that can be moved + to the target_device. + + A constructor node can be moved to the target_device iff all of its users + can also be moved (tested by cannot_be_moved). Otherwise, all dependent + constructor nodes won't be moved. + + - target: target device type + - allow_outputs: allow outputs to be moved + - allow_inputs: allow inputs to be moved + """ + + self.target = target + self.allow_inputs = allow_inputs + self.allow_outputs = allow_outputs + + if not isinstance(target, str): + raise AssertionError( + "target should be a string representing the device type. " + f"Got: {type(target).__name__}" + ) + + def allow_cpu_device(self, node: fx.Node) -> bool: + """ + Returns whether a node that returns a tensor on the target device may have + cpu tensors as input. + """ + return node.target in ( + torch.ops.aten.index.Tensor, + torch.ops.aten.index_put.default, + torch.ops.aten.index_put_.default, + torch.ops.aten.copy.default, + torch.ops.aten.copy_.default, + torch.ops.aten.slice_scatter.default, + ) + + def is_on_target_device(self, node: fx.Node) -> bool: + """ + Returns whether a node is on the target device. + """ + node_device = self.get_node_device(node) + return node_device is not None and node_device.type == self.target + + def is_cpu_scalar_tensor(self, node: fx.Node) -> bool: + """ + Returns whether a node is a cpu scalar tensor. + """ + device = self.get_node_device(node) + is_cpu = device is not None and device.type == "cpu" + ten = node.meta.get("val") + is_scalar = isinstance(ten, torch.Tensor) and len(ten.size()) == 0 + return is_cpu and is_scalar + + def all_inputs_are_cpu_scalar_or_on_target_device(self, node: fx.Node) -> bool: + """ + Returns whether a node's inputs are either cpu scalar tensors or + on the target device. + """ + inputs = ( + inp + for inp in itertools.chain(node.args, node.kwargs.values()) + if isinstance(inp, fx.Node) + ) + return all( + self.is_cpu_scalar_tensor(inp) or self.is_on_target_device(inp) + for inp in inputs + ) + + def cannot_be_moved(self, node: fx.Node) -> bool: + """ + Returns whether a node can be moved to the target device. + + If this function returns False, it means that this node and all of its users + won't be moved into the target device. + """ + if node.target == "output": + return not self.allow_outputs + + if not ( + isinstance(node.target, torch._ops.OpOverload) + and node.target.namespace in ("prims", "aten") + ): + return True + + if is_index_put_and_requires_h2d_sync_for_gpu_value(node): + return True + + return False + + def get_node_device(self, node: fx.Node) -> torch.device | None: + """ + Get the device of a node. + """ + ten = node.meta.get("val") + return None if not isinstance(ten, torch.Tensor) else ten.device + + def get_cpu_indeg_count(self, graph: fx.Graph) -> dict[fx.Node, int]: + """ + Get the number of cpu inputs to a node + """ + cpu_indeg: dict[fx.Node, int] = Counter() + + for node in graph.nodes: + cpu_count = 0 + + def add_cpu_inp(node): + nonlocal cpu_count + device = self.get_node_device(node) + cpu_count += device is not None and device.type == "cpu" + + pytree.tree_map_only(fx.Node, add_cpu_inp, (node.args, node.kwargs)) + + # pyrefly: ignore [redundant-condition] + if cpu_count: + cpu_indeg[node] = cpu_count + + return cpu_indeg + + def __call__(self, graph: fx.Graph) -> None: + target_devices = OrderedSet[torch.device]() + constructors = [] + cpu_placeholders: OrderedSet[fx.Node] = OrderedSet() + + for node in graph.nodes: + device = self.get_node_device(node) + if device and device.type == self.target: + target_devices.add(device) + + if ( + self.allow_inputs + and node.op == "placeholder" + and self.is_cpu_scalar_tensor(node) + ): + cpu_placeholders.add(node) + constructors.append(node) + continue + + if not ( + isinstance(node.target, torch._ops.OpOverload) + and node.target.namespace in ("prims", "aten") + ): + continue + + if not torch._subclasses.fake_tensor._is_tensor_constructor(node.target): + continue + + if node.kwargs.get("device") != torch.device("cpu"): + continue + + if ( + torch._inductor.config.fallback_random + and torch.Tag.nondeterministic_seeded in node.target.tags + ): + continue + + constructors.append(node) + + # not handling multiple target devices initially + if not constructors or len(target_devices) != 1: + return + + movable_constructors = self.find_movable_constructors(graph, constructors) + + target_device = next(iter(target_devices)) + movable_cpu_placeholders = movable_constructors & cpu_placeholders + if movable_cpu_placeholders: + node = next(iter(reversed(movable_cpu_placeholders))) + last_node = node + unsqueezed_nodes = [] + for elem in movable_cpu_placeholders: + with graph.inserting_after(last_node): + unsqueezed_nodes.append( + graph.call_function(torch.ops.aten.unsqueeze.default, (elem, 0)) + ) + last_node = unsqueezed_nodes[-1] + with graph.inserting_after(last_node): + cpu_concat = graph.call_function( + torch.ops.aten.cat.default, (unsqueezed_nodes,) + ) + last_node = cpu_concat + with graph.inserting_after(last_node): + gpu_concat = graph.call_function( + torch.ops.prims.device_put.default, + (cpu_concat, target_device, True), + ) + last_node = gpu_concat + with graph.inserting_after(last_node): + gpu_split = graph.call_function( + torch.ops.aten.unbind.int, (gpu_concat,) + ) + last_node = gpu_split + for idx, node in enumerate(movable_cpu_placeholders): + with graph.inserting_after(last_node): + gpu_node = graph.call_function(operator.getitem, (gpu_split, idx)) + node.replace_all_uses_with( + gpu_node, + lambda x: x + not in [cpu_concat, gpu_concat, gpu_split, gpu_node] + + unsqueezed_nodes + and x.target != torch.ops.aten.copy_.default + and x.target != "output", + ) + last_node = gpu_node + + # noop elimination if there are other device_put for gpu_node to + # target device. Alternatively, we could just move the other device_put + # earlier in the graph, but that is not supported in fx graph yet. + noop_device_puts = [ + user + for user in gpu_node.users + if user.target is torch.ops.prims.device_put.default + and user.args[1] == target_device + ] + for noop in noop_device_puts: + noop.replace_all_uses_with(gpu_node) + graph.erase_node(noop) + + movable_constructors -= movable_cpu_placeholders + for node in movable_constructors: + kwargs = node.kwargs.copy() + kwargs["device"] = target_device + node.kwargs = kwargs + + def find_movable_constructors( + self, graph: fx.Graph, constructors: list[fx.Node] + ) -> OrderedSet[fx.Node]: + """ + Starting from the cpu constructors, iterate through the graph and test that all of their + downstream uses can safely be moved to cpu. + """ + cpu_indeg: dict[fx.Node, int] = self.get_cpu_indeg_count(graph) + + # which constructors cannot be moved to gpu + cannot_move_to_gpu = OrderedSet[fx.Node]() + + # For any node in the graph, which constructors does it have a dependency on + constructor_dependencies: dict[fx.Node, OrderedSet[fx.Node]] = defaultdict( + OrderedSet + ) + + # if a cpu node has a dependency on two different cpu constructors, + # then if either constructor cannot be moved to gpu, the other cannot as well. + # In this case any node with a dependency on one will have a dependency on the other + equal_constructor_sets: dict[fx.Node, OrderedSet[fx.Node]] = { + c: OrderedSet([c]) for c in constructors + } + + def make_dependencies_equivalent( + set1: OrderedSet[fx.Node], set2: OrderedSet[fx.Node] + ) -> OrderedSet[fx.Node]: + # could use union find but not worth complexity here + set1.update(set2) + for obj in set1: + equal_constructor_sets[obj] = set1 + return set1 + + queue: list[fx.Node] = list(constructors) + + for c in queue: + constructor_dependencies[c].add(c) + + while queue: + node = queue.pop() + dependencies = constructor_dependencies[node] + + for user in node.users: + if self.cannot_be_moved(user): + cannot_move_to_gpu.update(dependencies) + break + + # this node was used on an op which takes in multiple devices and output a gpu + # tensor. we can convert its cpu input to gpu without making further changes + if self.allow_cpu_device(user) and self.is_on_target_device(user): + del cpu_indeg[user] + elif ( + self.allow_inputs + and self.is_on_target_device(user) + and self.all_inputs_are_cpu_scalar_or_on_target_device(user) + ): + # this node takes only cpu scalar tensors or gpu tensors as inputs + # and outputs a gpu tensor. we can convert its cpu scalar inputs to gpu + # without making further changes + del cpu_indeg[user] + else: + # otherwise, we should continue look at its downstream uses + cpu_indeg[user] -= 1 + if cpu_indeg[user] == 0: + del cpu_indeg[user] + queue.append(user) + + unioned_set = make_dependencies_equivalent( + dependencies, constructor_dependencies[user] + ) + constructor_dependencies[user] = unioned_set + + for node in cpu_indeg: + if constructor_dependencies[node]: + cannot_move_to_gpu.update(constructor_dependencies[node]) + + all_cannot_move_to_gpu = cannot_move_to_gpu.copy() + for constructor in cannot_move_to_gpu: + all_cannot_move_to_gpu.update(equal_constructor_sets[constructor]) + + return OrderedSet(constructors) - all_cannot_move_to_gpu + + +def move_constructors_to_gpu(graph: fx.Graph) -> None: + """ + Moves intermediary tensors which are constructed on the cpu to gpu when safe + """ + + # cudagraph does not support cpu tensors. In this pass, we update the graph + # by explicitly moving cpu scalar tensors to gpu when profitable, relying on + # graph partition to split off this data copy, and cudagraphifying + # the remaining gpu ops. + allow_inputs_outputs = bool( + torch._inductor.config.triton.cudagraphs + and torch._inductor.config.graph_partition + ) + ConstructorMoverPass( + get_gpu_type(), + allow_inputs=allow_inputs_outputs, + allow_outputs=allow_inputs_outputs, + )(graph) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/pre_grad.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/pre_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..61305837c005cc7fcc35769880710ac626babde3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/pre_grad.py @@ -0,0 +1,986 @@ +# mypy: allow-untyped-defs +import copy +import functools +import itertools +import logging +import types +from collections.abc import Sequence + +import torch +import torch.nn as nn +from torch._dynamo.utils import counters, detect_fake_mode +from torch._logging import trace_structured +from torch.fx.experimental.optimization import ( + matches_module_pattern, + replace_node_module, +) +from torch.fx.passes.graph_transform_observer import ( + GraphTransformObserver as GraphTransformObserverBase, +) +from torch.fx.passes.shape_prop import ShapeProp +from torch.nn import functional as F +from torch.nn.utils.fusion import fuse_conv_bn_eval, fuse_conv_bn_weights +from torch.utils._ordered_set import OrderedSet + +from .. import config +from ..custom_graph_pass import get_custom_graph_passes +from ..fx_utils import matches_module_function_pattern +from ..pattern_matcher import ( + init_once_fakemode, + PatternMatcherPass as PatternMatcherPassBase, + stable_topological_sort, +) +from ..utils import is_cpu_device, pass_execution_and_save +from .group_batch_fusion import group_batch_fusion_passes, PRE_GRAD_FUSIONS +from .misc_patterns import numpy_compat_normalization +from .split_cat import PRE_GRAD_PATTERNS + + +PatternMatcherPass = functools.partial( + PatternMatcherPassBase, subsystem="pre_grad_passes" +) +GraphTransformObserver = functools.partial( + GraphTransformObserverBase, subsystem="pre_grad_passes" +) + +log = logging.getLogger(__name__) + +apply_gumbel_max_trick_pass = PatternMatcherPass( + pass_name="apply_gumbel_max_trick_pass" +) + +efficient_conv_bn_eval_pass = PatternMatcherPass( + pass_name="efficient_conv_bn_eval_pass" +) + +fuse_split_linear_add_pass = PatternMatcherPass( + pass_name="fuse_split_linear_add_pass", +) +fuse_chunk_squeeze_cat_pass = PatternMatcherPass( + pass_name="fuse_chunk_squeeze_cat_pass", +) +remove_reshape_pass = PatternMatcherPass( + pass_name="remove_reshape_pass", +) + +# based on predispatch aten IR +normalization_pass_aten = PatternMatcherPass(pass_name="normalization_pass_aten") +merge_splits_pass_aten = PatternMatcherPass(pass_name="merge_splits_pass_aten") +split_cat_pass_aten = PatternMatcherPass(pass_name="split_cat_pass_aten") +unbind_stack_pass_aten = PatternMatcherPass(pass_name="unbind_stack_pass_aten") +merge_getitem_cat_pass_aten = PatternMatcherPass( + pass_name="merge_getitem_cat_pass_aten" +) +merge_stack_tahn_unbind_pass_aten = PatternMatcherPass( + pass_name="merge_stack_tahn_unbind_pass_aten" +) +mutate_cat_pass_aten = PatternMatcherPass(pass_name="mutate_cat_pass_aten") +remove_split_with_size_one_pass_aten = PatternMatcherPass( + pass_name="remove_split_with_size_one_pass_aten" +) + + +def save_inductor_dict(pass_to_compare=None): + if not pass_to_compare: + pass_to_compare = list(config.pre_grad_fusion_options.keys()) + list( + config.post_grad_fusion_options.keys() + ) + return {p: dict(counters["inductor"]).get(p, 0) for p in pass_to_compare} + + +def is_same_dict(inductor_dict, optimus_dict): + for pass_name, count in optimus_dict.items(): + if count != dict(inductor_dict).get(pass_name, 0): + return False + return True + + +def shape_prop(mod) -> None: + return None + + +def normalize_node_kwargs_pass(graph): + return None + + +def fuse_parallel_linear_pass(graph): + return None + + +def remove_split_ops(graph, shape_prop): + return None + + +def remove_split_ops_pass(graph): + remove_split_ops(graph.owning_module, shape_prop) + + +def fuse_chunk_reshape_unsqueeze_concat_pass(graph): + return None + + +def fuse_chunk_reshape_concat_pass(graph): + return None + + +def remove_noop_pass(graph): + return None + + +def stack_to_unsqueeze_pass(graph): + return None + + +def merge_concats_pass(graph): + return None + + +def relu_nan_to_num(graph): + return None + + +def fuse_split_getitem_squeeze_cat(graph): + return None + + +def use_triton_dot_compress(graph): + return None + + +def use_triton_lce_replace_simple_LCE_helper(gm, shape_prop): + return None + + +def use_triton_lce_replace_simple_LCE(graph): + return use_triton_lce_replace_simple_LCE_helper(graph.owning_module, shape_prop) + + +def use_triton_lce_replace_normal_LCE_helper(gm, shape_prop): + return None + + +def use_triton_lce_replace_normal_LCE(graph): + return use_triton_lce_replace_simple_LCE_helper(graph.owning_module, shape_prop) + + +def use_matmul_lce_replace_normal_LCE(graph): + return None + + +def use_matmul_fuse_lce_replace_first_LCE(graph): + return None + + +@init_once_fakemode +def lazy_init(input_device: torch.device | None = None): + from . import ( # noqa: F401 # noqa: F401 + apply_gumbel_max_trick, + efficient_conv_bn_eval, + split_cat, + ) + + if config.is_fbcode(): + from . import fb # type: ignore[attr-defined] # noqa: F401 + + +def _get_pass_name_func(p): + if isinstance(p, PatternMatcherPassBase): + pass_name = p.pass_name + pass_func = p.apply + elif isinstance(p, types.FunctionType): + pass_name = p.__name__.lstrip("_") + pass_func = p + else: + pass_name = None + pass_func = None + + return pass_name, pass_func + + +def _run_pre_dispatch_passes( + gm: torch.fx.GraphModule, + example_inputs: Sequence[object] = (), + add_passes: str | None = None, + remove_passes: str | None = None, +) -> None: + # Wrapper that resolves pre_grad_fusion_options by device before + # calling group_batch_fusion_passes, so the predispatch path + # gets the same device filtering as the non-predispatch path. + def _group_batch_fusion_passes_wrapper(graph: torch.fx.Graph) -> None: + group_batch_fusion_passes( + graph, + pre_grad=True, + fusion_options=_resolve_pre_grad_fusion_options( + config.pre_grad_fusion_options, example_inputs + ), + ) + + _group_batch_fusion_passes_wrapper.__name__ = "group_batch_fusion_passes" + + # order matters + default_pass_list = [ + # normalize passes, must be called as the first passes + normalization_pass_aten, + normalize_node_kwargs_pass, + remove_noop_pass, + relu_nan_to_num, + fuse_chunk_reshape_concat_pass, + _group_batch_fusion_passes_wrapper, + normalize_node_kwargs_pass, + fuse_chunk_squeeze_cat_pass, + merge_concats_pass, + fuse_split_linear_add_pass, + remove_reshape_pass, + fuse_parallel_linear_pass, + remove_split_ops_pass, + stack_to_unsqueeze_pass, # run before fuse_chunk_reshape_unsqueeze_concat_pass + fuse_chunk_reshape_unsqueeze_concat_pass, + ] + + full_pass_list = default_pass_list + [ + fuse_split_getitem_squeeze_cat, + use_triton_dot_compress, + use_triton_lce_replace_simple_LCE, + use_triton_lce_replace_normal_LCE, + use_matmul_fuse_lce_replace_first_LCE, + use_matmul_lce_replace_normal_LCE, + ] + + log.info( + f"pre_grad_passes: add_passes: {add_passes}, remove_pass: {remove_passes}" # noqa: G004 + ) + add_passes_list = [] + remove_passes_list = [] + if add_passes: + add_passes_list = add_passes.split(",") + if remove_passes: + remove_passes_list = remove_passes.split(",") + + shape_prop = lambda mod: ShapeProp( # noqa: E731 + gm=mod, + # pyre-fixme[16]: Module `torch._dynamo.utils` has no attribute `detect_fake_mode` + fake_mode=detect_fake_mode(example_inputs), + ).propagate(*tuple(example_inputs)) + + for p in default_pass_list: + pass_name, pass_func = _get_pass_name_func(p) + # should not happen + if pass_name is None or pass_func is None: + continue + if pass_name in remove_passes_list: + continue + pass_execution_and_save( + pass_func, + gm, + example_inputs, + f"[Pre grad(predispatch IR)] Apply {pass_name} pass", + ) + + for p in full_pass_list: + pass_name, pass_func = _get_pass_name_func(p) + if pass_name is None or pass_func is None: + continue + if pass_name in add_passes_list: + pass_execution_and_save( + pass_func, + gm, + example_inputs, + f"[Pre grad(predispatch IR)] Apply {pass_name} pass", + ) + + if "remove_noop" not in remove_passes_list: + # Remove noops at the end, which may be generated by other passes. + pass_execution_and_save( + remove_noop_pass, + gm, + example_inputs, + "[Pre grad(predispatch IR)]Apply remove_noop pass", + ) + shape_prop(gm) + + +def _resolve_pre_grad_fusion_options( + fusion_options: dict[str, dict[str, object]], + example_inputs: Sequence[object] | None, +) -> dict[str, dict[str, object]]: + """Filter pre_grad_fusion_options by device compatibility. + + If an option has a "devices" key, only include it when at least one + example input tensor's device type matches. Fusions without a "devices" + key always pass through (user explicitly opted in). The "devices" key + is stripped from the returned options. + """ + if example_inputs is None: + resolved: dict[str, dict[str, object]] = {} + for pass_name, options in fusion_options.items(): + resolved[pass_name] = {k: v for k, v in options.items() if k != "devices"} + return resolved + + example_device_types = OrderedSet( + t.device.type for t in example_inputs if isinstance(t, torch.Tensor) + ) + + resolved = {} + for pass_name, options in fusion_options.items(): + devices = options.get("devices") + if ( + devices is not None + and isinstance(devices, (list, tuple, OrderedSet)) + and example_device_types.isdisjoint(OrderedSet(devices)) + ): + continue + resolved[pass_name] = {k: v for k, v in options.items() if k != "devices"} + return resolved + + +def pre_grad_passes( + gm: torch.fx.GraphModule, + example_inputs: Sequence[object] = (), + add_passes: str | None = None, + remove_passes: str | None = None, +) -> torch.fx.GraphModule: + """ + Apply passes on the input FX graph using Torch IR. + + WARNING: + The IR before grad is not functional or normalized, so it is harder + to write passes on this IR. Passes must be safe with respect to + aliasing and mutation and need to handle all possible arg schemas. + + Consider adding a new pass to post_grad.py or joint_graph.py which + are after functionalization and normalization. + """ + if config.pattern_matcher: + lazy_init() + if hasattr( + config, "fx_passes_numeric_check" + ) and config.fx_passes_numeric_check.get("pre_grad", False): + gm_before_fx_passes = gm.__copy__() + # explicitly run with predispatch atenIR based passes + if config.is_predispatch: + _run_pre_dispatch_passes(gm, example_inputs, add_passes, remove_passes) + else: + # We only log the graph with changes to avoid the excessive compilation time + # https://fb.workplace.com/groups/257735836456307/permalink/633533465543207/ + numpy_compat_normalization(gm.graph) + if example_inputs is not None: + gm = fuse_fx(gm, example_inputs) + # Resolve pre_grad_fusion_options by filtering on device type + # declared in each fusion's "devices" config key. Fusions without + # a "devices" key always pass through. Uses a local copy to avoid + # mutating global config. + fusion_options = _resolve_pre_grad_fusion_options( + config.pre_grad_fusion_options, example_inputs + ) + # We should always do the normalization_pass first + if "normalization_pass" in fusion_options: + pattern_matcher_pass = PRE_GRAD_PATTERNS["normalization_pass"] + pattern_matcher_pass.apply(gm.graph) # type: ignore[arg-type] + GraphTransformObserver(gm, "group_batch_fusion_passes").apply_graph_pass( + lambda graph: group_batch_fusion_passes( + graph, pre_grad=True, fusion_options=fusion_options + ) + ) + for pass_name in fusion_options: + # skip all patterns for group batch fusions + if pass_name in PRE_GRAD_FUSIONS or pass_name == "normalization_pass": + continue + # skip auto-enabled fusion options that are not registered + # as pattern matcher passes (e.g., batch_linear_lhs when + # PRE_GRAD_FUSIONS is mocked by tests) + if pass_name not in PRE_GRAD_PATTERNS: + continue + pattern_matcher_pass = PRE_GRAD_PATTERNS[pass_name] + inductor_before_change = save_inductor_dict( + [pattern_matcher_pass.pass_name] + ) + # we support run same pattern multiple times, the default is to run only once + counter_raw = fusion_options[pass_name].get("counter", 1) + if not isinstance(counter_raw, int): + raise AssertionError(f"expected int, got {type(counter_raw)}") + for _ in range(counter_raw): + pattern_matcher_pass.apply(gm.graph) # type: ignore[arg-type] + if not is_same_dict(counters["inductor"], inductor_before_change): + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": f"{pattern_matcher_pass.pass_name}_pre_grad", + "encoding": "string", + }, + payload_fn=lambda: gm.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + # TODO: move efficient_conv_bn_eval_pass to the fusions dict too. + GraphTransformObserver(gm, "efficient_conv_bn_eval_pass").apply_graph_pass( + efficient_conv_bn_eval_pass.apply + ) + GraphTransformObserver(gm, "apply_gumbel_max_trick_pass").apply_graph_pass( + apply_gumbel_max_trick_pass.apply + ) + + for pre_grad_custom_pass in get_custom_graph_passes(config.pre_grad_custom_pass): + GraphTransformObserver(gm, "pre_grad_custom_pass").apply_graph_pass( + pre_grad_custom_pass + ) + + stable_topological_sort(gm.graph) + + from .quantization import quant_lift_up + + quant_lift_up(gm) + + gm.graph.lint() + gm.recompile() + + if ( + config.pattern_matcher + and hasattr(config, "fx_passes_numeric_check") + and config.fx_passes_numeric_check.get("pre_grad", False) + and example_inputs is not None + ): + from .numeric_utils import numeric_check_if_enabled + + gm_after_fx_passes = gm.__copy__() + numeric_check_if_enabled( + gm_before_fx_passes, # type: ignore[possibly-undefined] + gm_after_fx_passes, + example_inputs, + config.fx_passes_numeric_check.get("num_iterations", 1), + config.fx_passes_numeric_check.get("precision", 1e-4), + ) + + return gm + + +def fuse_fx(gm: torch.fx.GraphModule, example_inputs) -> torch.fx.GraphModule: + is_cpu = is_cpu_device(example_inputs) + # pyre-fixme[16]: Module `torch._dynamo.utils` has no attribute `detect_fake_mode` + fake_mode = detect_fake_mode(example_inputs) + + gm = sink_cat_after_pointwise(gm) + if config.permute_fusion and not is_cpu: + # For linear permute fusion, we need to check input info to identify + # and perform proper permutation/transpose + ShapeProp(gm, fake_mode=fake_mode).propagate(*example_inputs) + with GraphTransformObserver(gm, "linear_permute_fusion"): + gm = linear_permute_fusion(gm) + with GraphTransformObserver(gm, "permute_linear_fusion"): + gm = permute_linear_fusion(gm) + with GraphTransformObserver(gm, "permute_matmul_fusion"): + gm = permute_matmul_fusion(gm) + + # make sure the autograd is disabled. + if torch.is_grad_enabled() or not is_cpu: + return gm + if config.freezing: + with GraphTransformObserver(gm, "remove_identity"): + gm = remove_identity(gm) + with GraphTransformObserver(gm, "fuse_conv_bn"): + gm = fuse_conv_bn(gm) + return gm + + +def fetch_attr(target: str, mod): + target_atoms = target.split(".") + attr_itr = mod + for i, atom in enumerate(target_atoms): + if not hasattr(attr_itr, atom): + raise RuntimeError( + f"Node referenced nonexistent target {'.'.join(target_atoms[:i])}" + ) + attr_itr = getattr(attr_itr, atom) + return attr_itr + + +def remove_identity(gm: torch.fx.GraphModule) -> torch.fx.GraphModule: + """ + Removes all identity layers from the module. + """ + graph = gm.graph + work_done = False + for module_name, module in gm.named_modules(): + if type(module) is nn.Identity: + for node in list(graph.find_nodes(op="call_module", target=module_name)): + if len(node.args) != 1: + raise AssertionError( + f"expected 1 arg for identity node, got {len(node.args)}" + ) + input_node = node.args[0] + node.replace_all_uses_with(input_node) + graph.erase_node(node) + work_done = True + if work_done: + graph.lint() + gm.recompile() + return gm + + +def fuse_conv_bn(gm: torch.fx.GraphModule, inplace=False) -> torch.fx.GraphModule: + """ + Fuses Convolution/BN layers for inference purposes. + """ + modules_patterns = [ + (torch.nn.Conv1d, torch.nn.BatchNorm1d), + (torch.nn.Conv2d, torch.nn.BatchNorm2d), + (torch.nn.Conv3d, torch.nn.BatchNorm3d), + ] + module_function_patterns = [ + (torch.nn.Conv1d, F.batch_norm), + (torch.nn.Conv2d, F.batch_norm), + (torch.nn.Conv3d, F.batch_norm), + ] + modules = dict(gm.named_modules()) + + class ConvBNFusion: + def __init__( + self, + bn_node, + conv_module, + bn_module=None, # For BN Module + bn_running_mean=None, # For Functional BN + bn_running_var=None, + bn_eps=None, + bn_weight=None, + bn_bias=None, + ) -> None: + self.bn_nodes = [ + bn_node, + ] + self.conv_module = conv_module + self.bn_module = bn_module + self.bn_running_mean = bn_running_mean + self.bn_running_var = bn_running_var + self.bn_eps = bn_eps + self.bn_weight = bn_weight + self.bn_bias = bn_bias + self.fusion_enabled = True + + def add_bn_node(self, bn_node): + self.bn_nodes.append(bn_node) + + def disable_fusion(self): + self.fusion_enabled = False + + def is_fusion_enabled(self): + return self.fusion_enabled + + conv_bn_to_fuse: dict[int, ConvBNFusion] = {} + for pattern in modules_patterns: + conv_bn_to_fuse.clear() + for node in gm.graph.nodes: + if matches_module_pattern(pattern, node, modules): + if len(node.args[0].users) > 1: # Output of conv is used by other nodes + continue + conv = modules[node.args[0].target] + bn = modules[node.target] + eval_mode = all(not n.training for n in [conv, bn]) + if not eval_mode: + continue + if not bn.track_running_stats: + continue + + # Do hash based on the module name of conv + hash_id = hash(node.args[0].target) + if hash_id not in conv_bn_to_fuse: + conv_bn_to_fuse[hash_id] = ConvBNFusion(node, conv, bn) + else: + if bn == conv_bn_to_fuse[hash_id].bn_module: + # Do fusion if same bn module + conv_bn_to_fuse[hash_id].add_bn_node(node) + else: + # Disable the conv bn folding if conv shared by different bn + conv_bn_to_fuse[hash_id].disable_fusion() + + for conv_bn_fusion in conv_bn_to_fuse.values(): + if conv_bn_fusion.is_fusion_enabled(): + bn_nodes = conv_bn_fusion.bn_nodes + conv = conv_bn_fusion.conv_module + bn = conv_bn_fusion.bn_module + + # pyrefly: ignore [bad-argument-type] + fused_conv = fuse_conv_bn_eval(conv, bn) + for bn_node in bn_nodes: + replace_node_module(bn_node.args[0], modules, fused_conv) + bn_node.replace_all_uses_with(bn_node.args[0]) + gm.graph.erase_node(bn_node) + + gm.graph.lint() + for pattern in module_function_patterns: + conv_bn_to_fuse.clear() + for node in gm.graph.nodes: + if matches_module_function_pattern(pattern, node, modules): + # TODO: support kwargs. + if len(node.args) != 8: + continue + conv = modules[node.args[0].target] + bn_training = node.args[5] + bn_eps = node.args[7] + if conv.training or bn_training: + continue + if type(bn_eps) is not float: + continue + + def _used_by_same_conv_module(users): + conv_module_name = users[0].args[0].target + return all( + conv_module_name == user.args[0].target for user in users + ) + + bn_args_is_constant = all( + n.op == "get_attr" + and (len(n.users) == 1 or _used_by_same_conv_module(list(n.users))) + for n in node.args[1:5] + ) + if not bn_args_is_constant: + continue + bn_running_mean = fetch_attr(node.args[1].target, gm) + bn_running_var = fetch_attr(node.args[2].target, gm) + bn_weight = fetch_attr(node.args[3].target, gm) + bn_bias = fetch_attr(node.args[4].target, gm) + if bn_running_mean is None or bn_running_var is None: + continue + + # Do hash based on the module name of conv + hash_id = hash(node.args[0].target) + if hash_id not in conv_bn_to_fuse: + conv_bn_to_fuse[hash_id] = ConvBNFusion( + node, + conv, + bn_running_mean=bn_running_mean, + bn_running_var=bn_running_var, + bn_eps=bn_eps, + bn_weight=bn_weight, + bn_bias=bn_bias, + ) + else: + if ( + hash(bn_running_mean) + == hash(conv_bn_to_fuse[hash_id].bn_running_mean) + and hash(bn_running_var) + == hash(conv_bn_to_fuse[hash_id].bn_running_var) + and torch.allclose( + torch.tensor(bn_eps), + torch.tensor(conv_bn_to_fuse[hash_id].bn_eps), + ) + and hash(bn_weight) == hash(conv_bn_to_fuse[hash_id].bn_weight) + and hash(bn_bias) == hash(conv_bn_to_fuse[hash_id].bn_bias) + ): + # Do fusion if same functional bn + conv_bn_to_fuse[hash_id].add_bn_node(node) + else: + # Disable the conv bn folding if conv shared by different bn + conv_bn_to_fuse[hash_id].disable_fusion() + + for conv_bn_fusion in conv_bn_to_fuse.values(): + if conv_bn_fusion.is_fusion_enabled(): + bn_nodes = conv_bn_fusion.bn_nodes + conv = conv_bn_fusion.conv_module + bn_running_mean = conv_bn_fusion.bn_running_mean + bn_running_var = conv_bn_fusion.bn_running_var + bn_eps = conv_bn_fusion.bn_eps + bn_weight = conv_bn_fusion.bn_weight + bn_bias = conv_bn_fusion.bn_bias + + fused_conv = copy.deepcopy(conv) + fused_conv.weight, fused_conv.bias = fuse_conv_bn_weights( + fused_conv.weight, + fused_conv.bias, + # pyrefly: ignore [bad-argument-type] + bn_running_mean, + # pyrefly: ignore [bad-argument-type] + bn_running_var, + # pyrefly: ignore [bad-argument-type] + bn_eps, + bn_weight, + bn_bias, + ) + for bn_node in bn_nodes: + replace_node_module(bn_node.args[0], modules, fused_conv) + bn_node.replace_all_uses_with(bn_node.args[0]) + gm.graph.erase_node(bn_node) + gm.graph.lint() + gm.recompile() + + return gm + + +class NormalizedLinearNode: + def __init__(self, node: torch.fx.Node) -> None: + if node.op != "call_function": + raise AssertionError(f"expected call_function node, got {node.op}") + if node.target is not torch.nn.functional.linear: + raise AssertionError( + f"expected torch.nn.functional.linear target, got {node.target}" + ) + self.node: torch.fx.Node = node + + def get_input(self) -> torch.fx.Node: + if len(self.node.args) > 0: + return self.node.args[0] # type: ignore[return-value] + else: + return self.node.kwargs["input"] # type: ignore[return-value] + + def get_weight(self) -> torch.fx.Node: + if len(self.node.args) > 1: + return self.node.args[1] # type: ignore[return-value] + else: + return self.node.kwargs["weight"] # type: ignore[return-value] + + def get_bias(self) -> torch.fx.Node: + if len(self.node.args) > 2: + return self.node.args[2] # type: ignore[return-value] + else: + return self.node.kwargs.get("bias", None) # type: ignore[return-value] + + +class NormalizedMatmulNode: + def __init__(self, node: torch.fx.Node) -> None: + if node.op != "call_function": + raise AssertionError(f"expected call_function node, got {node.op}") + if node.target not in [torch.bmm, torch.matmul]: + raise AssertionError( + f"expected torch.bmm or torch.matmul target, got {node.target}" + ) + self.node: torch.fx.Node = node + + def get_input(self) -> torch.fx.Node: + if len(self.node.args) > 0: + return self.node.args[0] # type: ignore[return-value] + else: + return self.node.kwargs["input"] # type: ignore[return-value] + + def get_other(self) -> torch.fx.Node: + if len(self.node.args) > 1: + return self.node.args[1] # type: ignore[return-value] + else: + return self.node.kwargs["other"] # type: ignore[return-value] + + +def check_permute(node: torch.fx.Node) -> bool: + ranks = len(node.meta["tensor_meta"].shape) + if len(node.args) > 3: + permutation = [node.args[i] % ranks for i in range(1, ranks + 1)] # type: ignore[operator] + elif ( + "permutation" in node.kwargs + and node.kwargs["permutation"] is not None + and len(node.kwargs["permutation"]) > 2 # type: ignore[arg-type] + ): + permutation = [i % ranks for i in node.kwargs["permutation"]] # type: ignore[operator, union-attr] + else: + return False + allowed_permutation = list(range(ranks)) + allowed_permutation[-1] = ranks - 2 + allowed_permutation[-2] = ranks - 1 + return permutation == allowed_permutation + + +def sink_cat_after_pointwise(module: torch.fx.GraphModule) -> torch.fx.GraphModule: + def one_user(node): + users = list(node.users) + return users[0] if len(users) == 1 else None + + def is_view(node): + return node.op == "call_method" and node.target == "view" + + def is_pointwise_unary(node): + ops = "call_function", "call_method" + pointwise = torch.relu, torch.tanh, "relu", "tanh" + return node.op in ops and node.target in pointwise + + g = module.graph + for node in g.nodes: + if node.op != "call_function" or node.target != torch.cat: + continue + + cat_or_view = node + while True: + user = one_user(cat_or_view) + if not user or not is_view(user): + break + cat_or_view = user + + if user and is_pointwise_unary(user): + with g.inserting_before(node): + arg_not_provided = object() + + def cat_args( + tensors, + dim=arg_not_provided, + axis=arg_not_provided, + out=None, + ): + if dim is arg_not_provided: + dim = 0 + if axis is not arg_not_provided: + dim = axis + return tensors, dim, out + + tensors, dim, out = cat_args(*node.args, **node.kwargs) + if out is not None or dim is None: + continue + new_kwargs = { + name: val for name, val in user.kwargs.items() if name != "input" + } + new_tensors = [ + g.create_node(user.op, user.target, args=(arg,), kwargs=new_kwargs) + for arg in tensors + ] + new_cat = g.create_node( + "call_function", torch.cat, args=(new_tensors, dim) + ) + user.replace_all_uses_with(cat_or_view) + node.replace_all_uses_with(new_cat) + g.erase_node(user) + g.erase_node(node) + g.lint() + module.recompile() + return module + + +def linear_permute_fusion(module: torch.fx.GraphModule) -> torch.fx.GraphModule: + for node in module.graph.find_nodes(op="call_method", target="permute"): + if check_permute(node): + if len(node.args) > 0: + input_node = node.args[0] + else: + input_node = node.kwargs["input"] + if ( + input_node.op == "call_function" + and input_node.target is torch.nn.functional.linear + ): + normalized = NormalizedLinearNode(input_node) + input = normalized.get_input() + weight = normalized.get_weight() + bias = normalized.get_bias() + with module.graph.inserting_before(node): + fused_node = module.graph.call_function( + linear_transpose, args=(input, weight, bias) + ) + node.replace_all_uses_with(fused_node) + module.graph.erase_node(node) + if len(input_node.users) == 0: + module.graph.erase_node(input_node) + + module.graph.lint() + module.recompile() + return module + + +# Y1 = X * W^T + bias +# Y2 = Y1.permute(0, 2, 1) +# ----> +# Y2 = (W * X^T + bias.unsqueeze(-1))^T +def linear_transpose( + input: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None +) -> torch.Tensor: + if bias is None: + return torch.matmul(weight, input.transpose(-1, -2)) + return torch.matmul(weight, input.transpose(-1, -2)) + bias.unsqueeze(-1) + + +def permute_linear_fusion(module: torch.fx.GraphModule) -> torch.fx.GraphModule: + for node in module.graph.find_nodes( + op="call_function", target=torch.nn.functional.linear + ): + if len(node.args) > 0: + input_node = node.args[0] + else: + input_node = node.kwargs["input"] + if ( + input_node.op == "call_method" + and input_node.target == "permute" + and check_permute(input_node) + ): + normalized = NormalizedLinearNode(node) + if len(input_node.args) > 0: + input = input_node.args[0] + else: + input = input_node.kwargs["input"] + weight = normalized.get_weight() + bias = normalized.get_bias() + with module.graph.inserting_before(node): + fused_node = module.graph.call_function( + transpose_linear, args=(input, weight, bias) + ) + node.replace_all_uses_with(fused_node) + module.graph.erase_node(node) + if len(input_node.users) == 0: + module.graph.erase_node(input_node) + + module.graph.lint() + module.recompile() + return module + + +def permute_matmul_fusion(module: torch.fx.GraphModule) -> torch.fx.GraphModule: + for node in itertools.chain( + module.graph.find_nodes(op="call_function", target=torch.bmm), + module.graph.find_nodes(op="call_function", target=torch.matmul), + ): + normalized = NormalizedMatmulNode(node) + input_A_node = normalized.get_input() + input_B_node = normalized.get_other() + input_A = input_A_node + input_B = input_B_node + Atrans = Btrans = False + if ( + input_A_node.op == "call_method" + and input_A_node.target == "permute" + and check_permute(input_A_node) + ): + Atrans = True + if len(input_A_node.args) > 0: + input_A = input_A_node.args[0] # type: ignore[assignment] + else: + input_A = input_A_node.kwargs["input"] # type: ignore[assignment] + + if ( + input_B_node.op == "call_method" + and input_B_node.target == "permute" + and check_permute(input_B_node) + ): + Btrans = True + if len(input_B_node.args) > 0: + input_B = input_B_node.args[0] # type: ignore[assignment] + else: + input_B = input_B_node.kwargs["input"] # type: ignore[assignment] + + if Atrans or Btrans: + with module.graph.inserting_before(node): + fused_node = module.graph.call_function( + transpose_matmul, + args=(input_A, input_B, Atrans, Btrans), + ) + node.replace_all_uses_with(fused_node) + module.graph.erase_node(node) + if Atrans and len(input_A_node.users) == 0: + module.graph.erase_node(input_A_node) + if Btrans and len(input_B_node.users) == 0: + module.graph.erase_node(input_B_node) + + module.graph.lint() + module.recompile() + return module + + +# X1 = X.permute(0, 2, 1) +# Y1 = X1 * W1^T + bias1 +# ----> +# Y2 = X1.transpose(-1, -2) * W1^T + bias1 +def transpose_linear( + input: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None +) -> torch.Tensor: + if bias is None: + return torch.matmul(input.transpose(-1, -2), weight.t()) + return torch.matmul(input.transpose(-1, -2), weight.t()) + bias + + +def transpose_matmul( + A: torch.Tensor, B: torch.Tensor, Atrans: bool, Btrans: bool +) -> torch.Tensor: + if Atrans: + A = A.transpose(-1, -2) + if Btrans: + B = B.transpose(-1, -2) + return torch.matmul(A, B) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/profile_guided_estimation.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/profile_guided_estimation.py new file mode 100644 index 0000000000000000000000000000000000000000..d70d649eaa26b03980a219845942187b89633e15 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/profile_guided_estimation.py @@ -0,0 +1,828 @@ +""" +Profile-Guided Estimation (PGE) for overlap scheduling. + +Parses a Chrome Trace JSON (from torch.profiler) and builds lookup tables +for kernel runtimes (collectives, matmuls, attention, custom ops, etc.). +Used as a custom_runtime_estimation hook in the overlap scheduler. + +When the same profile is loaded on all ranks, estimates are deterministic +and no cross-rank synchronization is needed. +""" + +from __future__ import annotations + +import functools +import json +import logging +import math +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Any + +import torch +import torch.fx as fx +from torch._inductor.analysis.profile_analysis import ( + _create_extern_mapping, + _dtype_map, + _get_size_from_string, + ParseException, +) +from torch._inductor.fx_passes.bucketing import ( + is_all_gather_into_tensor, + is_all_reduce_tensor, + is_all_to_all_tensor, + is_reduce_scatter_tensor, +) +from torch._logging import trace_structured +from torch.utils._ordered_set import OrderedSet + + +log = logging.getLogger(__name__) + + +def _rank_stride(ranks: tuple[int, ...]) -> int | None: + """Compute the stride of a sorted rank tuple, or None if non-uniform. + + Examples: + (0, 2, 4, 6) → stride 2 + (0, 1) → stride 1 + (1, 3, 5, 7) → stride 2 + (0, 1, 4, 5) → None (non-uniform) + """ + if len(ranks) <= 1: + return None + stride = ranks[1] - ranks[0] + if stride <= 0: + return None + for i in range(2, len(ranks)): + if ranks[i] - ranks[i - 1] != stride: + return None + return stride + + +@dataclass +class CollectiveRecord: + """A single collective kernel observation from the profile.""" + + collective_name: str # "all_gather_into_tensor", "reduce_scatter_tensor", etc. + pg_ranks: tuple[int, ...] # sorted rank tuple + group_size: int + in_nelems: int # "In msg nelems" from profile + out_nelems: int # "Out msg nelems" from profile + dtype: str # "Float", "BFloat16", etc. + duration_us: float + + +@dataclass +class OpRecord: + """A single op observation from the profile (any CPU op with GPU kernels).""" + + op_name: str # normalized name, e.g. "aten::mm", "mylib::my_custom_op" + input_shapes: tuple[tuple[int, ...], ...] + input_strides: tuple[tuple[int, ...], ...] + dtype: torch.dtype | None + duration_us: float # sum of all GPU kernels for this CPU op + + +def _to_nested_tuple(x: Any) -> Any: + """Recursively convert nested lists to tuples for hashability.""" + if isinstance(x, (list, tuple)): + return tuple(_to_nested_tuple(i) for i in x) + return x + + +@dataclass +class ProfileData: + """Parse Chrome Trace JSON and build lookup tables for kernel runtimes.""" + + collectives: list[CollectiveRecord] = field(default_factory=list) + ops: list[OpRecord] = field(default_factory=list) + pg_configs: dict[str, tuple[int, ...]] = field(default_factory=dict) + + # Lookup indices built after loading + _collective_index: dict[ + tuple[str, tuple[int, ...], str], list[tuple[int, float]] + ] = field(default_factory=dict) + # Fallback index by mesh dimension (name, stride, group_size, dtype). + # Matches PGs belonging to the same mesh dimension regardless of specific ranks. + # E.g. (0,2,4,6) and (1,3,5,7) both have stride=2, size=4 → same mesh dim. + _collective_index_by_mesh_dim: dict[ + tuple[str, int, int, str], list[tuple[int, float]] + ] = field(default_factory=dict) + # Count of distinct PGs per mesh dimension (stride, group_size) — used for + # ambiguity check (skip fallback if multiple PGs share the same mesh dim). + _pg_count_by_mesh_dim: dict[tuple[int, int], int] = field(default_factory=dict) + # Generic op index: (op_name, input_shapes, input_strides, dtype) -> avg_dur_us + _op_index: dict[ + tuple[ + str, + tuple[tuple[int, ...], ...], + tuple[tuple[int, ...], ...], + torch.dtype | None, + ], + float, + ] = field(default_factory=dict) + # Peak observed bandwidth per PG (GB/s), computed from largest messages + _pg_peak_bw: dict[tuple[int, ...], float] = field(default_factory=dict) + # Mesh-dimension fallback: (stride, group_size) -> peak BW (GB/s) + _mesh_dim_peak_bw: dict[tuple[int, int], float] = field(default_factory=dict) + + def load(self, trace_path: str) -> None: + """Load and parse a Chrome Trace JSON file.""" + import os + + if not os.path.isfile(trace_path): + raise FileNotFoundError( + f"PGE trace file not found: {trace_path}. " + f"Check config.aten_distributed_optimizations.profile_guided_estimations_profile_path" + ) + with open(trace_path) as f: + data = json.load(f) + + self._parse_pg_configs(data) + self._parse_events(data) + self._build_indices() + + log.info( + "PGE loaded: %d collectives, %d op records (%d distinct shapes), %d PGs", + len(self.collectives), + len(self.ops), + len(self._op_index), + len(self.pg_configs), + ) + + def _parse_pg_configs(self, data: dict[str, Any]) -> None: + dist_info = data.get("distributedInfo", {}) + pg_config = dist_info.get("pg_config", {}) + # pg_config can be a list of dicts or a dict of dicts + if isinstance(pg_config, list): + for pg_info in pg_config: + pg_name = str(pg_info.get("pg_name", "")) + ranks = pg_info.get("ranks", []) + if ranks: + self.pg_configs[pg_name] = tuple(sorted(ranks)) + elif isinstance(pg_config, dict): + for pg_name, pg_info in pg_config.items(): + ranks = pg_info.get("ranks", []) + if ranks: + self.pg_configs[pg_name] = tuple(sorted(ranks)) + + def _parse_events(self, data: dict[str, Any]) -> None: + events = data.get("traceEvents", []) + # Reuse profile_analysis's External id -> CPU op mapping + try: + extern_mapping = _create_extern_mapping(data) + except (ParseException, KeyError): + # Malformed trace (e.g. duplicate External ids, missing traceEvents) + extern_mapping = defaultdict(list) + for ev in events: + if ( + isinstance(ev, dict) + and ev.get("cat") == "cpu_op" + and "args" in ev + and "External id" in ev["args"] + ): + extern_mapping[ev["args"]["External id"]].append(ev) + + # Build External id -> total GPU kernel duration + gpu_dur: dict[int, float] = defaultdict(float) + for ev in events: + if not isinstance(ev, dict) or ev.get("cat") != "kernel": + continue + args = ev.get("args", {}) + eid = args.get("External id") + dur = ev.get("dur", 0.0) + if eid is not None and dur > 0: + gpu_dur[eid] += dur + + # Parse collectives from GPU kernel events directly + # (NCCL kernels carry collective metadata in args) + for ev in events: + if not isinstance(ev, dict) or ev.get("cat") != "kernel": + continue + args = ev.get("args", {}) + coll_name = args.get("Collective name") + if coll_name is None: + continue + pg_name = args.get("Process Group Name", "") + pg_ranks_str = args.get("Process Group Ranks", "") + group_size = args.get("Group size", 0) + in_nelems = args.get("In msg nelems", 0) + out_nelems = args.get("Out msg nelems", 0) + dtype = args.get("dtype", "") + dur = ev.get("dur", 0.0) + if dur <= 0: + continue + + pg_ranks = self._parse_ranks(pg_ranks_str, pg_name) + + self.collectives.append( + CollectiveRecord( + collective_name=coll_name, + pg_ranks=pg_ranks, + group_size=group_size, + in_nelems=in_nelems, + out_nelems=out_nelems, + dtype=dtype, + duration_us=dur, + ) + ) + + # Parse all CPU ops that have associated GPU kernels + for eid, cpu_evs in extern_mapping.items(): + if not cpu_evs: + continue + total_dur = gpu_dur.get(eid, 0.0) + if total_dur <= 0: + continue + cpu_ev = cpu_evs[0] + self._parse_op(cpu_ev.get("name", ""), cpu_ev.get("args", {}), total_dur) + + def _parse_ranks(self, ranks_str: str, pg_name: str) -> tuple[int, ...]: + """Parse rank list from profile string or fall back to pg_configs.""" + if isinstance(ranks_str, str) and ranks_str.startswith("["): + try: + ranks = json.loads(ranks_str) + return tuple(sorted(ranks)) + except (json.JSONDecodeError, TypeError): + pass + # Fall back to pg_configs + if pg_name in self.pg_configs: + return self.pg_configs[pg_name] + return () + + def _parse_op(self, name: str, args: dict[str, Any], total_dur: float) -> None: + """Parse any CPU op into a generic OpRecord.""" + input_dims = args.get("Input Dims", []) + input_strides = args.get("Input Strides", []) + input_types = args.get("Input type", []) + if not input_dims: + return + dtype_str = input_types[0] if input_types else "" + dtype = _dtype_map.get(dtype_str) + # Skip empty entries (non-tensor args like scalars/None) so the + # tuples match what _get_node_input_shapes/strides extract from FX nodes. + shapes = tuple( + _to_nested_tuple(d) + for d in input_dims + if isinstance(d, (list, tuple)) and d + ) + strides = tuple( + _to_nested_tuple(d) + for d in input_strides + if isinstance(d, (list, tuple)) and d + ) + if not shapes: + return + self.ops.append( + OpRecord( + op_name=name, + input_shapes=shapes, + input_strides=strides, + dtype=dtype, + duration_us=total_dur, + ) + ) + + def _build_indices(self) -> None: + """Build lookup indices from parsed records.""" + coll_idx: dict[tuple[str, tuple[int, ...], str], list[tuple[int, float]]] = ( + defaultdict(list) + ) + coll_idx_by_mesh_dim: dict[ + tuple[str, int, int, str], list[tuple[int, float]] + ] = defaultdict(list) + # Track distinct PG rank sets per mesh dimension for ambiguity check + pg_sets_by_mesh_dim: dict[tuple[int, int], OrderedSet[tuple[int, ...]]] = ( + defaultdict(OrderedSet) + ) + for rec in self.collectives: + norm_name = self._normalize_collective_name(rec.collective_name) + gs = len(rec.pg_ranks) if rec.pg_ranks else rec.group_size + coll_idx[(norm_name, rec.pg_ranks, rec.dtype)].append( + (rec.out_nelems, rec.duration_us) + ) + stride = _rank_stride(rec.pg_ranks) + if stride is not None: + coll_idx_by_mesh_dim[(norm_name, stride, gs, rec.dtype)].append( + (rec.out_nelems, rec.duration_us) + ) + pg_sets_by_mesh_dim[(stride, gs)].add(rec.pg_ranks) + # Sort by nelems for interpolation + self._collective_index = { + k: sorted(v, key=lambda x: x[0]) for k, v in coll_idx.items() + } + self._collective_index_by_mesh_dim = { + k: sorted(v, key=lambda x: x[0]) for k, v in coll_idx_by_mesh_dim.items() + } + self._pg_count_by_mesh_dim = { + k: len(pgs) for k, pgs in pg_sets_by_mesh_dim.items() + } + + op_groups: defaultdict[ + tuple[ + str, + tuple[tuple[int, ...], ...], + tuple[tuple[int, ...], ...], + torch.dtype | None, + ], + list[float], + ] = defaultdict(list) + for rec in self.ops: + key = (rec.op_name, rec.input_shapes, rec.input_strides, rec.dtype) + op_groups[key].append(rec.duration_us) + self._op_index = {k: sum(v) / len(v) for k, v in op_groups.items()} + + # Per-PG peak bandwidth: compute bytes/us for each collective observation, + # then take the max from the top-N largest messages per PG (where bandwidth + # is most representative of hardware speed, not dominated by startup latency). + # Uses output-convention bytes (matching _estimate_with_pg_bandwidth). + _TOP_N = 5 # consider top N largest messages for peak BW + pg_bw_samples: dict[tuple[int, ...], list[tuple[int, float]]] = defaultdict( + list + ) + mesh_dim_bw_samples: dict[tuple[int, int], list[tuple[int, float]]] = ( + defaultdict(list) + ) + for rec in self.collectives: + if rec.out_nelems <= 0 or rec.duration_us <= 0: + continue + gs = len(rec.pg_ranks) if rec.pg_ranks else rec.group_size + elem_bytes = self._dtype_elem_bytes(rec.dtype) + total_bytes = rec.out_nelems * elem_bytes + bw_gbps = total_bytes / (rec.duration_us * 1e-6) / 1e9 # GB/s + pg_bw_samples[rec.pg_ranks].append((total_bytes, bw_gbps)) + stride = _rank_stride(rec.pg_ranks) + if stride is not None: + mesh_dim_bw_samples[(stride, gs)].append((total_bytes, bw_gbps)) + + def _peak_bw_from_samples( + samples: list[tuple[int, float]], + ) -> float: + """Get peak BW from the top-N largest messages.""" + # Sort by message size descending, take top N, return max BW + sorted_samples = sorted(samples, key=lambda x: x[0], reverse=True) + top = sorted_samples[:_TOP_N] + return max(bw for _, bw in top) if top else 0.0 + + self._pg_peak_bw = { + pg: _peak_bw_from_samples(samples) + for pg, samples in pg_bw_samples.items() + if samples + } + self._mesh_dim_peak_bw = { + key: _peak_bw_from_samples(samples) + for key, samples in mesh_dim_bw_samples.items() + if samples + } + + def get_collective_keys(self) -> list[tuple[str, tuple[int, ...], str]]: + """Return the collective index keys: (name, pg_ranks, dtype).""" + return list(self._collective_index.keys()) + + @property + def op_count(self) -> int: + """Number of distinct op shapes in the index.""" + return len(self._op_index) + + def get_op_names(self) -> list[str]: + """Return distinct op names in the op index.""" + return list(OrderedSet(name for name, _, _, _ in self._op_index)) + + @staticmethod + def _dtype_elem_bytes(dtype: str) -> int: + """Return bytes per element for a dtype string (NCCL CamelCase or TypeMeta).""" + return _get_size_from_string(dtype.lower()) + + @staticmethod + def _normalize_collective_name(name: str) -> str: + """Normalize collective name between profile and FX conventions. + + Profile uses: _allgather_base, allreduce, reduce_scatter_tensor_coalesced + FX uses: all_gather_into_tensor, all_reduce, reduce_scatter_tensor + """ + n = name.lower() + if "allgather" in n or "all_gather" in n: + return "all_gather" + if "reduce_scatter" in n: + return "reduce_scatter" + if "allreduce" in n or "all_reduce" in n: + return "all_reduce" + if "all_to_all" in n or "alltoall" in n: + return "all_to_all" + return name + + # Maximum ratio of target_nelems / max_observed before switching from + # log-log extrapolation to bandwidth-based estimation. + EXTRAPOLATION_CAP = 2.0 + + def _estimate_with_pg_bandwidth( + self, + pg_ranks: tuple[int, ...], + nelems: int, + dtype: str, + ) -> float | None: + """Estimate collective duration using peak observed bandwidth for this PG. + + Used when the target size exceeds the extrapolation cap. Returns ms or None. + """ + bw_gbps = self._pg_peak_bw.get(pg_ranks) + if bw_gbps is None or bw_gbps <= 0: + # Try mesh-dimension fallback + stride = _rank_stride(pg_ranks) + gs = len(pg_ranks) + if stride is not None: + bw_gbps = self._mesh_dim_peak_bw.get((stride, gs)) + if bw_gbps is None or bw_gbps <= 0: + return None # fall through to analytical + elem_bytes = self._dtype_elem_bytes(dtype) + total_bytes = nelems * elem_bytes + dur_ms = total_bytes / (bw_gbps * 1e6) # GB/s → bytes/ms = 1e6 + return dur_ms + + def lookup_collective( + self, + collective_name: str, + pg_ranks: tuple[int, ...], + nelems: int, + dtype: str, + ) -> tuple[float, str] | None: + """Look up collective duration in ms. Returns (duration_ms, source) or None. + + ``source`` is ``"profile"`` for exact/interpolated matches, or + ``"pg_bandwidth"`` when bandwidth-based extrapolation was used. + + Tries exact rank match first, then falls back to mesh-dimension match + (e.g. (0,2,4,6) and (1,3,5,7) both have stride=2, size=4 → same mesh dim). + + When the target size exceeds EXTRAPOLATION_CAP * max_observed, uses + bandwidth-based estimation from peak observed bandwidth instead of + linear extrapolation (which overestimates for large messages). + """ + norm_name = self._normalize_collective_name(collective_name) + # Try exact rank match first + key = (norm_name, pg_ranks, dtype) + entries = self._collective_index.get(key) + if not entries: + # Fall back to mesh-dimension match + gs = len(pg_ranks) + stride = _rank_stride(pg_ranks) + if ( + stride is not None + and self._pg_count_by_mesh_dim.get((stride, gs), 0) == 1 + ): + mesh_dim_key = (norm_name, stride, gs, dtype) + entries = self._collective_index_by_mesh_dim.get(mesh_dim_key) + if not entries: + return None + + # Exact match + for n, dur in entries: + if n == nelems: + return (dur / 1e3, "profile") # us -> ms + + # Check extrapolation distance: if target is far beyond observed range, + # use bandwidth-based model instead of log-log extrapolation + max_observed = max((n for n, _ in entries if n > 0), default=0) + if max_observed > 0 and nelems > max_observed * self.EXTRAPOLATION_CAP: + est = self._estimate_with_pg_bandwidth(pg_ranks, nelems, dtype) + if est is not None: + return (est, "pg_bandwidth") + # Fall through to log-log if no BW data available + + # Interpolation in log-log space + result = self._interpolate_log_log(entries, nelems) + if result is not None: + return (result, "profile") + return None + + def _interpolate_log_log( + self, entries: list[tuple[int, float]], target_nelems: int + ) -> float | None: + """Interpolate duration in log-log space (log(nelems) vs log(dur)).""" + if not entries or target_nelems <= 0: + return None + + log_target = math.log(target_nelems) + + # Find bracketing entries + lower: tuple[int, float] | None = None + upper: tuple[int, float] | None = None + for n, dur in entries: + if n <= 0 or dur <= 0: + continue + if n <= target_nelems: + lower = (n, dur) + if n >= target_nelems and upper is None: + upper = (n, dur) + + if lower is not None and upper is not None: + log_n0, log_d0 = math.log(lower[0]), math.log(lower[1]) + log_n1, log_d1 = math.log(upper[0]), math.log(upper[1]) + if log_n1 == log_n0: + return lower[1] / 1e3 + t = (log_target - log_n0) / (log_n1 - log_n0) + log_dur = log_d0 + t * (log_d1 - log_d0) + return math.exp(log_dur) / 1e3 # us -> ms + elif lower is not None: + # Linear extrapolation (not log-log) from nearest lower; + # EXTRAPOLATION_CAP in lookup_collective limits how far this reaches. + return (lower[1] * target_nelems / lower[0]) / 1e3 + elif upper is not None: + # Linear extrapolation from nearest upper + return (upper[1] * target_nelems / upper[0]) / 1e3 + + return None + + def lookup_op( + self, + op_name: str, + input_shapes: tuple[tuple[int, ...], ...], + input_strides: tuple[tuple[int, ...], ...], + dtype: torch.dtype | None, + ) -> float | None: + """Look up op duration in ms by exact shape+stride match. Returns None on miss.""" + key = (op_name, input_shapes, input_strides, dtype) + dur_us = self._op_index.get(key) + if dur_us is not None: + return dur_us / 1e3 # us -> ms + return None + + +@functools.cache +def _dtype_to_nccl_str(dtype: torch.dtype) -> str: + """Convert torch.dtype to NCCL/ScalarType name (for collective matching). + + Derives the name from torch.Tensor.type() which returns e.g. + "torch.BFloat16Tensor" -> "BFloat16". + """ + return ( + torch.tensor([], dtype=dtype) + .type() + .removeprefix("torch.") + .removesuffix("Tensor") + ) + + +def _get_node_dtype(node: fx.Node) -> torch.dtype | None: + """Extract dtype from FX node metadata.""" + val = node.meta.get("val") + if isinstance(val, torch.Tensor): + return val.dtype + if isinstance(val, (list, tuple)) and val: + first = val[0] + if isinstance(first, torch.Tensor): + return first.dtype + return None + + +def _fx_target_to_profile_name(node: fx.Node) -> str | None: + """Convert FX node target to the profile op name format. + + FX: torch.ops.aten.mm.default → "aten::mm" + FX: torch.ops.deepep.dispatch.default → "deepep::dispatch" + """ + target = node.target + if isinstance(target, torch._ops.OpOverload): + # e.g. "aten::mm" from torch.ops.aten.mm.default + ns = target.namespace + op_name = target._schema.name.split("::")[-1] + return f"{ns}::{op_name}" + if hasattr(target, "__name__"): + return target.__name__ + return None + + +def _get_node_input_shapes_and_strides( + node: fx.Node, +) -> tuple[tuple[tuple[int, ...], ...], tuple[tuple[int, ...], ...]] | None: + """Extract input shapes and strides from FX node tensor args. + + Returns (shapes, strides) or None if no tensor args or symbolic dims. + """ + from torch._inductor.fx_passes.node_runtime_estimation import get_hint + + shapes: list[tuple[int, ...]] = [] + strides: list[tuple[int, ...]] = [] + for arg in node.args: + if not isinstance(arg, fx.Node): + continue + val = arg.meta.get("val") + if isinstance(val, torch.Tensor): + resolved_shape = [] + for s in val.shape: + h = get_hint(s) + if h is None: + return None + resolved_shape.append(h) + resolved_stride = [] + for s in val.stride(): + h = get_hint(s) + if h is None: + return None + resolved_stride.append(h) + shapes.append(tuple(resolved_shape)) + strides.append(tuple(resolved_stride)) + if not shapes: + return None + return tuple(shapes), tuple(strides) + + +def _is_collective_node(node: fx.Node) -> bool: + """Check if node is a collective communication op.""" + return ( + is_all_gather_into_tensor(node) + or is_reduce_scatter_tensor(node) + or is_all_reduce_tensor(node) + or is_all_to_all_tensor(node) + ) + + +def _get_collective_info( + node: fx.Node, +) -> tuple[str, tuple[int, ...], int, str] | None: + """Extract (collective_name, pg_ranks, nelems, dtype) from collective node.""" + import torch.distributed as c10d + from torch.fx.operator_schemas import normalize_function + + if not c10d.is_initialized(): + return None + + target = node.target + if not isinstance(target, torch._ops.OpOverload): + return None + collective_name = target.name().split("::")[-1].split(".")[0] + + opt = normalize_function( + target, + args=node.args, + kwargs=node.kwargs, + normalize_to_only_use_kwargs=True, + ) + if opt is None: + return None + _, kwargs = opt + group_name = kwargs.get("group_name", "") + + try: + from torch.distributed.distributed_c10d import ( + _resolve_process_group, + get_process_group_ranks, + ) + + pg = _resolve_process_group(group_name) + pg_ranks = tuple(sorted(get_process_group_ranks(pg))) + except (RuntimeError, KeyError, ValueError): + log.debug( + "PGE: failed to resolve process group for %s", node.name, exc_info=True + ) + return None + + # Get nelems from input tensor + val = node.meta.get("val") + if isinstance(val, torch.Tensor): + nelems = 1 + for s in val.shape: + nelems *= int(s) + dtype = _dtype_to_nccl_str(val.dtype) + else: + # Try first arg + if node.args and isinstance(node.args[0], fx.Node): + inp_val = node.args[0].meta.get("val") + if isinstance(inp_val, torch.Tensor): + nelems = 1 + for s in inp_val.shape: + nelems *= int(s) + dtype = _dtype_to_nccl_str(inp_val.dtype) + else: + return None + else: + return None + + return (collective_name, pg_ranks, nelems, dtype) + + +class ProfileGuidedEstimator: + """Profile-guided runtime estimator for FX nodes. + + Implements the ``custom_runtime_estimation`` interface: + ``(fx.Node, int | None) -> float | None`` (returns ms or None for fallback). + + Handles collectives via interpolation (latency + bandwidth model) and all + other ops (matmul, SDPA, custom ops, etc.) via exact shape match from the + profile trace. + """ + + def __init__( + self, + trace_path: str, + diagnostics_gm: torch.fx.GraphModule | None = None, + ) -> None: + self.profile = ProfileData() + self.profile.load(trace_path) + self._log_profile_vs_analytical_comparison(diagnostics_gm) + + def _log_profile_vs_analytical_comparison( + self, diagnostics_gm: torch.fx.GraphModule | None + ) -> None: + """Log profile data and PGE vs analytical comparison to trace_structured. + + Logs all profile entries (collectives, ops with durations). + If diagnostics_gm is provided, walks the graph and compares PGE + estimates with analytical (roofline / NCCL) for each matched node. + """ + profile = self.profile + op_entries = [ + { + "op": op_name, + "shapes": [list(s) for s in shapes], + "strides": [list(s) for s in strides], + "dtype": str(dtype) if dtype is not None else "", + "profile_ms": dur_us / 1e3, + } + for (op_name, shapes, strides, dtype), dur_us in profile._op_index.items() + ] + + diagnostics: list[dict[str, Any]] = [] + if diagnostics_gm is not None: + from torch._inductor.fx_passes.overlap_scheduling import ( + estimate_roofline_runtime_ms, + ) + + for node in diagnostics_gm.graph.nodes: + pge_est = self(node) + if pge_est is None: + continue + entry: dict[str, Any] = { + "node": node.name, + "op": str(node.target), + "pge_ms": pge_est, + } + if _is_collective_node(node): + try: + entry["analytical_ms"] = ( + torch._inductor.comm_analysis.estimate_nccl_collective_runtime_from_fx_node( + node + ) + ) + except (RuntimeError, ValueError, TypeError): + pass + else: + analytical = estimate_roofline_runtime_ms(node) + if analytical is not None and analytical > 0: + entry["analytical_ms"] = analytical + diagnostics.append(entry) + + payload: dict[str, Any] = { + "collective_count": len(profile.collectives), + "op_count": profile.op_count, + "op_entries": op_entries, + } + if diagnostics: + payload["diagnostics"] = diagnostics + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "pge_profile_vs_analytical", + "encoding": "json", + }, + payload_fn=lambda: json.dumps(payload), + ) + + def __call__(self, node: fx.Node, override_size: int | None = None) -> float | None: + if _is_collective_node(node): + return self._estimate_collective(node, override_size) + return self._estimate_op(node) + + def _estimate_collective( + self, node: fx.Node, override_size: int | None + ) -> float | None: + info = _get_collective_info(node) + if info is None: + return None + coll_name, pg_ranks, nelems, dtype = info + val = node.meta.get("val") + if override_size is not None: + if override_size == 0: + return None + if isinstance(val, torch.Tensor): + elem_size = val.element_size() + if elem_size > 0: + nelems = override_size // elem_size + result = self.profile.lookup_collective(coll_name, pg_ranks, nelems, dtype) + if result is not None: + return result[0] + return None + + def _estimate_op(self, node: fx.Node) -> float | None: + """Estimate any non-collective op via exact shape+stride match in profile.""" + profile_name = _fx_target_to_profile_name(node) + if profile_name is None: + return None + result = _get_node_input_shapes_and_strides(node) + if result is None: + return None + input_shapes, input_strides = result + dtype = _get_node_dtype(node) + return self.profile.lookup_op(profile_name, input_shapes, input_strides, dtype) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/quantization.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..702273726b9e12867ad960e81fa4099177d418ba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/quantization.py @@ -0,0 +1,1673 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import copy +import itertools +import math +import operator + +import torch +from torch._dynamo.utils import counters +from torch.fx.node import map_arg + +from .. import config +from ..lowering import lowerings as L, require_channels_last +from ..pattern_matcher import ( + Arg, + CallFunction, + filter_nodes, + KeywordArg, + ListOf, + Match, + stable_topological_sort, +) +from ..utils import pad_listlike +from .freezing_patterns import register_freezing_graph_pattern +from .post_grad import register_lowering_pattern + + +aten = torch.ops.aten +prims = torch.ops.prims +quantized_decomposed = torch.ops.quantized_decomposed +quantized = torch.ops.quantized + +# Only for per tensor quant since permute may change the channel idx +_PER_TENSOR_QUANTIZE_OPS = [ + quantized_decomposed.quantize_per_tensor.default, + quantized_decomposed.quantize_per_tensor.tensor, +] + +_VIEW_OPS = [ + aten.transpose.int, + aten.permute.default, + aten.view.default, + aten.reshape.default, +] + +""" +The quantization.py file primarily incorporates passes related to quantization fusion +in inductor, includes: +1. Lowering of qconv/qlinear (unary and binary post-op variants) from the + `onednn::qconv_pointwise` / `onednn::qlinear_pointwise` ops to Inductor IR. +2. Pointwise operators' quantization fusion like: qmaxpool2d, qcat, qreshape and more. +3. Weight-only quantization (WOQ) int8 mm / concat-linear patterns lowered to + `aten._weight_int8pack_mm` and the int4 concat-linear pass for + `aten._weight_int4pack_mm_for_cpu`. + +Note: the dequant promotion, qconv/qlinear weight prepack and qconv/qlinear +fusion patterns that used to live here have been moved to TorchAO. +""" + + +def _get_pattern_output_dtype(match: Match): + """ + Get the pattern's output dtype from node's meta + Assume only 1 output node in this matched pattern. + """ + pattern_output_nodes = match.output_nodes() + if len(pattern_output_nodes) != 1: + raise AssertionError( + f"expected exactly 1 output node, got {len(pattern_output_nodes)}" + ) + output_node = pattern_output_nodes[0] + if not isinstance(output_node, torch.fx.Node): + raise AssertionError(f"expected torch.fx.Node, got {type(output_node)}") + output_dtype = output_node.meta["val"].dtype + if output_dtype not in [ + torch.int8, + torch.uint8, + torch.float32, + torch.bfloat16, + torch.float8_e4m3fn, + ]: + raise AssertionError(f"unexpected output dtype {output_dtype}") + return output_dtype + + +def _may_generate_pattern_with_dtype_convert( + pattern, dtype=Arg(), with_dtype_convert=True, users=1 +): + if with_dtype_convert: + return CallFunction( + prims.convert_element_type.default, + pattern, + dtype, + _users=users, + ) + else: + return pattern + + +def _may_generate_pattern_with_reshape(pattern, reshape_size=Arg(), with_reshape=True): + if with_reshape: + return CallFunction( + torch.ops.aten.reshape.default, + pattern, + reshape_size, + ) + else: + return pattern + + +def _generate_linear_t_pattern( + _dequant_per_channel_pattern, + dtype, +): + if dtype not in [torch.float32, torch.bfloat16]: + raise AssertionError(f"expected float32 or bfloat16, got {dtype}") + t_pattern = CallFunction( + aten.permute.default, + _may_generate_pattern_with_dtype_convert( + _dequant_per_channel_pattern, + KeywordArg("autocast_wgt_dtype"), + dtype == torch.bfloat16, + ), + KeywordArg("permute_axes"), + ) + return t_pattern + + +def _unary_fusion_pattern(unary_fusion, call_fn, users, is_bf16): + # only insert to_dtype if is_bf16 is True + computation_call = _may_generate_pattern_with_dtype_convert( + call_fn, dtype=KeywordArg("to_float"), with_dtype_convert=is_bf16, users=users + ) + return unary_fusion(computation_call) + + +def get_dequantize_per_tensor_activation_pattern(is_tensor_overload=False): + dequantize_per_tensor_activation_pattern = CallFunction( + quantized_decomposed.dequantize_per_tensor.tensor + if is_tensor_overload + else quantized_decomposed.dequantize_per_tensor.default, + KeywordArg("x"), + KeywordArg("x_scale"), + KeywordArg("x_zp"), + KeywordArg("x_quant_min"), + KeywordArg("x_quant_max"), + KeywordArg("x_dq_dtype"), + ) + return dequantize_per_tensor_activation_pattern + + +dequantize_per_channel_weight_pattern = CallFunction( + quantized_decomposed.dequantize_per_channel.default, + KeywordArg("q_weight"), + KeywordArg("w_scale"), + KeywordArg("w_zp"), + KeywordArg("w_axis"), + KeywordArg("w_quant_min"), + KeywordArg("w_quant_max"), + KeywordArg("w_dtype"), +) + +dequantize_per_channel_to_bf16_weight_pattern = ( + _may_generate_pattern_with_dtype_convert( + dequantize_per_channel_weight_pattern, + KeywordArg("autocast_wgt_dtype"), + ) +) + +dequantize_per_channel_clone_weight_pattern = CallFunction( + aten.clone.default, + dequantize_per_channel_weight_pattern, + memory_format=KeywordArg("memory_format"), +) + +dequantize_per_channel_to_bf16_clone_weight_pattern = CallFunction( + aten.clone.default, + dequantize_per_channel_to_bf16_weight_pattern, + memory_format=KeywordArg("memory_format"), +) + + +def get_qconv_pt2e_pattern(x_scale_zp_are_tensors=False, users=1): + qconv_op = ( + torch.ops.onednn.qconv_pointwise.tensor + if x_scale_zp_are_tensors + else torch.ops.onednn.qconv_pointwise.default + ) + return CallFunction( + qconv_op, + KeywordArg("x"), + KeywordArg("x_scale"), + KeywordArg("x_zp"), + KeywordArg("packed_weight"), + KeywordArg("w_scale"), + KeywordArg("w_zp"), + KeywordArg("b"), + KeywordArg("stride"), + KeywordArg("padding"), + KeywordArg("dilation"), + KeywordArg("groups"), + KeywordArg("output_scale"), + KeywordArg("output_zero_point"), + KeywordArg("output_dtype"), + KeywordArg("postop_name"), + KeywordArg("postop_args"), + KeywordArg("postop_algorithm"), + _users=users, + ) + + +def get_qconv2d_binary_pt2e_pattern(x_scale_zp_are_tensors=False, users=1): + qconv_op = ( + torch.ops.onednn.qconv2d_pointwise.binary_tensor + if x_scale_zp_are_tensors + else torch.ops.onednn.qconv2d_pointwise.binary + ) + return CallFunction( + qconv_op, + KeywordArg("x"), + KeywordArg("x_scale"), + KeywordArg("x_zp"), + KeywordArg("packed_weight"), + KeywordArg("w_scale"), + KeywordArg("w_zp"), + KeywordArg("accum"), + KeywordArg("b"), + KeywordArg("stride"), + KeywordArg("padding"), + KeywordArg("dilation"), + KeywordArg("groups"), + KeywordArg("output_scale"), + KeywordArg("output_zero_point"), + KeywordArg("output_dtype"), + KeywordArg("accum_scale"), + KeywordArg("accum_zero_point"), + KeywordArg("binary_op_name"), + KeywordArg("alpha"), + KeywordArg("unary_op_name"), + KeywordArg("unary_op_args"), + KeywordArg("unary_op_algorithm"), + _users=users, + ) + + +def get_qlinear_pt2e_pattern(x_scale_zp_are_tensors, users=1): + qlinear_op = ( + torch.ops.onednn.qlinear_pointwise.tensor + if x_scale_zp_are_tensors + else torch.ops.onednn.qlinear_pointwise.default + ) + return CallFunction( + qlinear_op, + KeywordArg("x"), + KeywordArg("x_scale"), + KeywordArg("x_zp"), + KeywordArg("packed_weight"), + KeywordArg("w_scale"), + KeywordArg("w_zp"), + KeywordArg("b"), + KeywordArg("output_scale"), + KeywordArg("output_zero_point"), + KeywordArg("output_dtype"), + KeywordArg("postop_name"), + KeywordArg("postop_args"), + KeywordArg("postop_algorithm"), + _users=users, + ) + + +def get_qlinear_binary_pt2e_pattern(x_scale_zp_are_tensors, users=1): + qlinear_op = ( + torch.ops.onednn.qlinear_pointwise.binary_tensor + if x_scale_zp_are_tensors + else torch.ops.onednn.qlinear_pointwise.binary + ) + return CallFunction( + qlinear_op, + KeywordArg("x"), + KeywordArg("x_scale"), + KeywordArg("x_zp"), + KeywordArg("packed_weight"), + KeywordArg("w_scale"), + KeywordArg("w_zp"), + KeywordArg("x_2"), + KeywordArg("b"), + KeywordArg("output_scale"), + KeywordArg("output_zero_point"), + KeywordArg("output_dtype"), + KeywordArg("x2_scale"), + KeywordArg("x2_zp"), + KeywordArg("binary_op_name"), + KeywordArg("alpha"), + KeywordArg("unary_op_name"), + KeywordArg("unary_op_args"), + KeywordArg("unary_op_algorithm"), + _users=users, + ) + + +dequantize_accum_pattern = CallFunction( + quantized_decomposed.dequantize_per_tensor.default, + KeywordArg("accum"), + KeywordArg("accum_scale"), + KeywordArg("accum_zp"), + Arg(), + Arg(), + KeywordArg("accum_dq_dtype"), +) + + +def generate_pattern_with_binary( + binary_post_op, + computation_call, + extra_input_pattern, + dtype_convert=False, + swap_inputs=False, +): + binary_pattern = ( + CallFunction( + binary_post_op, + extra_input_pattern, + computation_call, + ) + if swap_inputs + else CallFunction( + binary_post_op, + computation_call, + extra_input_pattern, + ) + ) + return _may_generate_pattern_with_dtype_convert( + binary_pattern, + KeywordArg("convert_dtype_after_inplace_add"), + dtype_convert, + ) + + +def generate_pattern_with_unary(computation_call, unary_post_op): + if unary_post_op is not None: + return CallFunction( + unary_post_op, + computation_call, + ) + return computation_call + + +def generate_pattern_with_output_quant(computation_call, with_dtype_convert=False): + quantized_op_output_pattern_pt2e = CallFunction( + quantized_decomposed.quantize_per_tensor.default, + _may_generate_pattern_with_dtype_convert( + computation_call, + Arg(), + with_dtype_convert, + ), + KeywordArg("o_inv_scale"), + KeywordArg("o_zp"), + KeywordArg("o_qmin"), + KeywordArg("o_qmax"), + KeywordArg("o_dtype"), + ) + return quantized_op_output_pattern_pt2e + + +def _check_node_kwarg_arg_value(check_node, kwarg_name, args_index, expected_value): + if kwarg_name in check_node.kwargs: + actual_value = check_node.kwargs[kwarg_name] + return actual_value == expected_value + else: + if len(check_node.args) < (args_index + 1): + raise AssertionError( + f"expected at least {args_index + 1} args, got {len(check_node.args)}" + ) + actual_value = check_node.args[args_index] + return actual_value == expected_value + + +def _is_valid_quantized_conv_optimization_pattern(): + def fn(match): + output_dtype = _get_pattern_output_dtype(match) + if output_dtype in [torch.float32, torch.bfloat16]: + # Only keep matched pattern with same output_dtype + qconv_node_after_weight_prepack = filter_nodes( + match.nodes, torch.ops.onednn.qconv_pointwise + )[0] + return _check_node_kwarg_arg_value( + qconv_node_after_weight_prepack, "output_dtype", 13, output_dtype + ) + return True + + return fn + + +def _is_valid_qconv_post_op_fusion_pattern(has_binary_post_op=False): + return ( + _is_valid_qconv_binary_optimization_pattern() + if has_binary_post_op + else _is_valid_quantized_conv_optimization_pattern() + ) + + +def _is_valid_qconv_lowering_pattern(): + def fn(match): + if len(match.nodes) != 1: + return False + return match.nodes[0].target in ( + torch.ops.onednn.qconv_pointwise.default, + torch.ops.onednn.qconv_pointwise.tensor, + torch.ops.onednn.qconv2d_pointwise.binary, + torch.ops.onednn.qconv2d_pointwise.binary_tensor, + ) + + return fn + + +def _register_quantized_conv_lowering( + pattern, + pass_number, + computation_op, +): + @register_lowering_pattern( + pattern, + extra_check=_is_valid_qconv_lowering_pattern(), + pass_number=pass_number, + ) + def qconv(match: Match, *args, **kwargs): + # Activation QParams + x, x_scale, x_zp = ( + kwargs["x"], + kwargs["x_scale"], + kwargs["x_zp"], + ) + # Weight QParams + packed_weight, w_scale, w_zp = ( + kwargs["packed_weight"], + kwargs["w_scale"], + kwargs["w_zp"], + ) + # Conv Params + b, stride, padding, dilation, groups = ( + kwargs["b"], + kwargs["stride"], + kwargs["padding"], + kwargs["dilation"], + kwargs["groups"], + ) + output_dtype = _get_pattern_output_dtype(match) + if output_dtype not in [ + torch.int8, + torch.uint8, + torch.float8_e4m3fn, + torch.float32, + torch.bfloat16, + ]: + raise AssertionError(f"unexpected output dtype {output_dtype}") + # Output QParams + o_inv_scale = kwargs["output_scale"] + o_zero_point = kwargs["output_zero_point"] + output_dtype = kwargs["output_dtype"] + # post op + postop_name = kwargs["postop_name"] + postop_args = kwargs["postop_args"] + postop_algorithm = kwargs["postop_algorithm"] + + computation_args = ( + x, + x_scale, + x_zp, + packed_weight, + w_scale, + w_zp, + b, + stride, + padding, + dilation, + groups, + o_inv_scale, + o_zero_point, + output_dtype, + postop_name, + postop_args, + postop_algorithm, + ) + counters["inductor"]["qconv_unary_lower_count"] += 1 + counters["inductor"]["qconv_unary_lower_nodes"] += len(match.nodes) + return L[computation_op](*computation_args) + + return qconv + + +def _is_valid_quantized_linear_optimization_pattern(): + def fn(match): + output_dtype = _get_pattern_output_dtype(match) + if output_dtype in [torch.float32, torch.bfloat16]: + # Only keep matched pattern with same output_dtype + qlinear_node_after_weight_prepack = filter_nodes( + match.nodes, torch.ops.onednn.qlinear_pointwise + )[0] + return _check_node_kwarg_arg_value( + qlinear_node_after_weight_prepack, "output_dtype", 9, output_dtype + ) + return True + + return fn + + +def _is_valid_qlinear_post_op_fusion_pattern(has_binary_post_op=False): + return ( + _is_valid_qlinear_binary_optimization_pattern() + if has_binary_post_op + else _is_valid_quantized_linear_optimization_pattern() + ) + + +def _is_valid_qlinear_lowering_pattern(): + def fn(match): + if len(match.nodes) != 1: + return False + return match.nodes[0].target in ( + torch.ops.onednn.qlinear_pointwise.default, + torch.ops.onednn.qlinear_pointwise.tensor, + torch.ops.onednn.qlinear_pointwise.binary, + torch.ops.onednn.qlinear_pointwise.binary_tensor, + ) + + return fn + + +def _register_quantized_linear_unary_lowering( + pattern, + pass_number, + computation_op, +): + @register_lowering_pattern( + pattern, + extra_check=_is_valid_qlinear_lowering_pattern(), + pass_number=pass_number, + ) + def qlinear(match: Match, *args, **kwargs): + output_dtype = _get_pattern_output_dtype(match) + # Activation QParams + x, x_scale, x_zp = ( + kwargs["x"], + kwargs["x_scale"], + kwargs["x_zp"], + ) + # Weight QParams + packed_weight, w_scale, w_zp = ( + kwargs["packed_weight"], + kwargs["w_scale"], + kwargs["w_zp"], + ) + + # bias + b = kwargs.get("b") + + # Output QParams + o_inv_scale = kwargs["output_scale"] + o_zero_point = kwargs["output_zero_point"] + + # post op + postop_name = kwargs["postop_name"] + postop_args = kwargs["postop_args"] + postop_algorithm = kwargs["postop_algorithm"] + + computation_args = ( + x, + x_scale, + x_zp, + packed_weight, + w_scale, + w_zp, + b, + o_inv_scale, + o_zero_point, + output_dtype, + postop_name, + postop_args, + postop_algorithm, + ) + counters["inductor"]["qlinear_unary_lower_count"] += 1 + counters["inductor"]["qlinear_unary_lower_nodes"] += len(match.nodes) + return L[computation_op](*computation_args) + + return qlinear + + +def _register_quantized_linear_binary_lowering( + pattern, + pass_number, + computation_op, +): + @register_lowering_pattern( + pattern, + extra_check=_is_valid_qlinear_lowering_pattern(), + pass_number=pass_number, + ) + def qlinear_binary(match: Match, *args, **kwargs): + output_dtype = _get_pattern_output_dtype(match) + if output_dtype is None: + raise AssertionError("expected non-None output dtype") + # Activation QParams + x, x_scale, x_zp = ( + kwargs["x"], + kwargs["x_scale"], + kwargs["x_zp"], + ) + x2 = kwargs["x_2"] + x2_scale = kwargs["x2_scale"] + x2_zp = kwargs["x2_zp"] + # Weight QParams + packed_weight, w_scale, w_zp = ( + kwargs["packed_weight"], + kwargs["w_scale"], + kwargs["w_zp"], + ) + # bias + b = kwargs.get("b") + # Output QParams + o_inv_scale = kwargs["output_scale"] + o_zero_point = kwargs["output_zero_point"] + + x2.realize() + from .mkldnn_fusion import _qlinear_binary_can_be_inplace + + binary_op_name = kwargs["binary_op_name"] + alpha = kwargs["alpha"] + unary_op_name = kwargs["unary_op_name"] + unary_op_args = kwargs["unary_op_args"] + unary_op_algorithm = kwargs["unary_op_algorithm"] + if ( + # TODO Ensure sum is safe and remove such check, i.e., + # x2 is not used by other operations + # or current qlinear sum is the last user of x2. + # This needs to be ensured when registering + # the lowering pattern of quantized_linear_binary. + binary_op_name == "sum" and (not _qlinear_binary_can_be_inplace(x2)) + ): + binary_op_name = "add" + + computation_args = ( + x, + x_scale, + x_zp, + packed_weight, + w_scale, + w_zp, + x2, + b, + o_inv_scale, + o_zero_point, + output_dtype, + x2_scale, + x2_zp, + binary_op_name, + alpha, + unary_op_name, + unary_op_args, + unary_op_algorithm, + ) + counters["inductor"]["qlinear_binary_lower_count"] += 1 + counters["inductor"]["qlinear_binary_lower_nodes"] += len(match.nodes) + return L[computation_op](*computation_args) + + return qlinear_binary + + +def _is_valid_qconv_binary_optimization_pattern(): + return _is_valid_quantized_op_binary_optimization_pattern( + torch.ops.onednn.qconv_pointwise + ) + + +def _is_valid_qlinear_binary_optimization_pattern(): + return _is_valid_quantized_op_binary_optimization_pattern( + torch.ops.onednn.qlinear_pointwise, + # we don't insert q-dq for extra input due to accuracy issues + extra_input_from_dequant=False, + ) + + +def _is_valid_quantized_op_binary_optimization_pattern( + qop, extra_input_from_dequant=True +): + # Check if it's a valid Binary Pattern for qconv2d and qlinear: + # * qop_pointwise should only has one users + # * If extra_input_from_dequant is True, extra input of binary node should come from dequant pattern + # * the two inputs of binary node should have attribute "meta" and should be tensors + # * the two inputs of binary node should have the same shape + # * All users of the extra input in this pattern should be + # ancestor nodes of the compute node, except for the binary node + # connected to the compute node. + def fn(match): + output_dtype = _get_pattern_output_dtype(match) + compute_node = filter_nodes(match.nodes, qop)[0] + # qop_pointwise should only have one user + if len(compute_node.users) != 1: + return False + binary_node_inputs = next(iter(compute_node.users)).args + if len(binary_node_inputs) != 2: + raise AssertionError("Expects binary node with 2 inputs") + if output_dtype in [torch.float32, torch.bfloat16]: + extra_input_of_binary_node = None + for arg in binary_node_inputs: + if arg != compute_node: + extra_input_of_binary_node = arg + break + if extra_input_of_binary_node is None: + raise AssertionError("expected non-None extra input of binary node") + # Extra input of binary node comes from dequant pattern + if extra_input_from_dequant and ( + (not isinstance(extra_input_of_binary_node, torch.fx.Node)) + or ( + extra_input_of_binary_node.target + != quantized_decomposed.dequantize_per_tensor.default + ) + ): + return False + + # the two inputs of binary node should have attribute "meta" and should be tensors + if not ( + hasattr(binary_node_inputs[0], "meta") + and isinstance(binary_node_inputs[0].meta.get("val", None), torch.Tensor) # type: ignore[union-attr] + ) or not ( + hasattr(binary_node_inputs[1], "meta") + and isinstance(binary_node_inputs[1].meta.get("val", None), torch.Tensor) # type: ignore[union-attr] + ): + return False + # the two inputs of binary node should have the same shape + if ( + binary_node_inputs[0].meta["val"].size() # type: ignore[union-attr] + != binary_node_inputs[1].meta["val"].size() # type: ignore[union-attr] + ): + return False + + # All users of the extra input in this pattern should be + # ancestor nodes of the compute node, except for the binary node + # connected to the compute node. + + from .mkldnn_fusion import _get_remaining_users + + extra_input_of_pattern = ( + match.kwargs["other"] + if "other" in match.kwargs + else ( + match.kwargs["accum"] + if (output_dtype in [torch.uint8, torch.int8]) + or (not extra_input_from_dequant) + else match.kwargs["accum_after_dequant"] + ) + ) + if ( + len(_get_remaining_users(extra_input_of_pattern, compute_node)) > 1 + or extra_input_of_pattern == compute_node.args[0] + ): + return False + return True + + return fn + + +def _register_quantized_conv_binary_lowering( + pattern, + pass_number, + computation_op, +): + @register_lowering_pattern( + pattern, + extra_check=_is_valid_qconv_lowering_pattern(), + pass_number=pass_number, + ) + def qconv_binary(match: Match, *args, **kwargs): + output_dtype = _get_pattern_output_dtype(match) + if output_dtype is None: + raise AssertionError("expected non-None output dtype") + x, x_scale, x_zp = kwargs["x"], kwargs["x_scale"], kwargs["x_zp"] + accum = kwargs["accum"] + accum_scale = kwargs["accum_scale"] + accum_zp = kwargs["accum_zero_point"] + packed_weight, w_scale, w_zp = ( + kwargs["packed_weight"], + kwargs["w_scale"], + kwargs["w_zp"], + ) + b, stride, padding, dilation, groups = ( + kwargs["b"], + kwargs["stride"], + kwargs["padding"], + kwargs["dilation"], + kwargs["groups"], + ) + # Output QParams + output_scale = kwargs["output_scale"] + output_zero_point = kwargs["output_zero_point"] + + # post ops + binary_op_name = kwargs["binary_op_name"] + alpha = kwargs["alpha"] + unary_op_name = kwargs["unary_op_name"] + unary_op_args = kwargs["unary_op_args"] + unary_op_algorithm = kwargs["unary_op_algorithm"] + + accum.realize() + from .mkldnn_fusion import _can_be_inplace + + if not _can_be_inplace(accum): + raise AssertionError( + "QConv Binary Inplace Fusion requires accum is not an alias or mutation." + ) + + computation_args = ( + x, + x_scale, + x_zp, + packed_weight, + w_scale, + w_zp, + accum, + b, + stride, + padding, + dilation, + groups, + output_scale, + output_zero_point, + output_dtype, + accum_scale, + accum_zp, + binary_op_name, + alpha, + unary_op_name, + unary_op_args, + unary_op_algorithm, + ) + counters["inductor"]["qconv2d_binary_lower_count"] += 1 + counters["inductor"]["qconv2d_binary_lower_nodes"] += len(match.nodes) + return L[computation_op](*computation_args) + + return qconv_binary + + +def _register_quantization_unary_lowering(): + # QConv2d + for x_scale_zp_are_tensors, users in itertools.product([False, True], [1, 2]): + qconv_pattern = get_qconv_pt2e_pattern(x_scale_zp_are_tensors, users) + computation_op = ( + torch.ops.onednn.qconv_pointwise.tensor + if x_scale_zp_are_tensors + else torch.ops.onednn.qconv_pointwise.default + ) + _register_quantized_conv_lowering( + qconv_pattern, + 2, # pass_number + computation_op, + ) + + # QLinear + for x_scale_zp_are_tensors in (False, True): + qlinear_pattern = get_qlinear_pt2e_pattern(x_scale_zp_are_tensors) + computation_op = ( + torch.ops.onednn.qlinear_pointwise.tensor + if x_scale_zp_are_tensors + else torch.ops.onednn.qlinear_pointwise.default + ) + _register_quantized_linear_unary_lowering( + qlinear_pattern, + 2, # pass_number + computation_op, + ) + + +def _register_quantization_binary_lowering(): + # QConv2d + for x_scale_zp_are_tensors, users in itertools.product([False, True], [1, 2]): + qconv_pattern = get_qconv2d_binary_pt2e_pattern(x_scale_zp_are_tensors, users) + computation_op = ( + torch.ops.onednn.qconv2d_pointwise.binary_tensor + if x_scale_zp_are_tensors + else torch.ops.onednn.qconv2d_pointwise.binary + ) + _register_quantized_conv_binary_lowering( + qconv_pattern, + 2, # pass_number + computation_op, + ) + + # QLinear + for x_scale_zp_are_tensors in (False, True): + qlinear_pattern = get_qlinear_binary_pt2e_pattern(x_scale_zp_are_tensors) + computation_op = ( + torch.ops.onednn.qlinear_pointwise.binary_tensor + if x_scale_zp_are_tensors + else torch.ops.onednn.qlinear_pointwise.binary + ) + _register_quantized_linear_binary_lowering( + qlinear_pattern, + 2, # pass_number + computation_op, + ) + + +def _is_valid_quantized_maxpool2d_optimization_pattern(): + def fn(match): + # Only match the pattern which max_pool2d_with_indices returns value + # instead of indices. + get_item_node = filter_nodes(match.nodes, operator.getitem)[0] + return get_item_node.args[1] == 0 + + return fn + + +def _register_quantized_maxpool2d_lowering( + pattern, + computation_op, +): + @register_lowering_pattern( + pattern, + extra_check=_is_valid_quantized_maxpool2d_optimization_pattern(), + ) + def qmaxpool2d(match: Match, *args, **kwargs): + x = kwargs["x"] + kernel_size = kwargs["kernel_size"] + stride = kwargs.get("stride") + padding = kwargs.get("padding", 0) + dilation = kwargs.get("dilation", 1) + ceil_mode = kwargs.get("ceil_mode", False) + + if padding == 0: + padding = [0, 0] + if dilation == 1: + dilation = [1, 1] + if not stride: + stride = kernel_size + kernel_size = pad_listlike(kernel_size, 2) + stride = pad_listlike(stride, 2) + padding = pad_listlike(padding, 2) + dilation = pad_listlike(dilation, 2) + + if len(kernel_size) != 2: + raise AssertionError( + f"expected kernel_size of length 2, got {len(kernel_size)}" + ) + if len(stride) != 2: + raise AssertionError(f"expected stride of length 2, got {len(stride)}") + if len(padding) != 2: + raise AssertionError(f"expected padding of length 2, got {len(padding)}") + if len(dilation) != 2: + raise AssertionError(f"expected dilation of length 2, got {len(dilation)}") + + computation_args = ( + x, + kernel_size, + stride, + padding, + dilation, + ceil_mode, + ) + computation_args, _ = require_channels_last(computation_op, *computation_args) + counters["inductor"]["qmaxpool2d_matcher_count"] += 1 + counters["inductor"]["qmaxpool2d_matcher_nodes"] += len(match.nodes) + return L[computation_op](*computation_args) + + return qmaxpool2d + + +def _register_quantization_maxpool2d(): + # Currently, the default parameters are not in FX Graph generated by Dynamo export. + # So, if user defines nn.MaxPool2d with different assignment of default parameter, + # it will generate graph with different number of input nodes and hence + # different pattern to be matched. + # Refer to the issue: https://github.com/pytorch/pytorch/issues/105901 + max_pool2d_args_list = [ + [ + KeywordArg("stride"), + ], + [ + KeywordArg("stride"), + KeywordArg("padding"), + ], + [ + KeywordArg("stride"), + KeywordArg("padding"), + KeywordArg("dilation"), + ], + [ + KeywordArg("stride"), + KeywordArg("padding"), + KeywordArg("dilation"), + KeywordArg("ceil_mode"), + ], + ] + for max_pool2d_args in max_pool2d_args_list: + dequantize_maxpool2d_pattern = CallFunction( + aten.max_pool2d_with_indices.default, + get_dequantize_per_tensor_activation_pattern(), + KeywordArg("kernel_size"), + *max_pool2d_args, + ) + dequantize_lowmem_maxpool2d_pattern = CallFunction( + prims._low_memory_max_pool_with_offsets.default, + get_dequantize_per_tensor_activation_pattern(), + KeywordArg("kernel_size"), + *max_pool2d_args, + KeywordArg("offset_dtype"), + ) + dequantize_maxpool2d_get_item_pattern = CallFunction( + operator.getitem, + dequantize_maxpool2d_pattern, + Arg(), + ) + dequantize_lowmem_maxpool2d_get_item_pattern = CallFunction( + operator.getitem, + dequantize_lowmem_maxpool2d_pattern, + Arg(), + ) + _register_quantized_maxpool2d_lowering( + generate_pattern_with_output_quant(dequantize_maxpool2d_get_item_pattern), + quantized.max_pool2d.default, + ) + _register_quantized_maxpool2d_lowering( + generate_pattern_with_output_quant( + dequantize_lowmem_maxpool2d_get_item_pattern + ), + quantized.max_pool2d.default, + ) + + +def _is_input_output_same_scale_zp(check_node): + def fn(match): + # Ensure all the inputs and output has same scale and zero point + # Step 1: Check inputs/output zero point + # Get dequant nodes at input + dequant_nodes = filter_nodes( + match.nodes, quantized_decomposed.dequantize_per_tensor.default + ) + zero_points = [node.args[2] for node in dequant_nodes] + # Get quant nodes at output + quant_nodes = filter_nodes( + match.nodes, quantized_decomposed.quantize_per_tensor.default + ) + if len(quant_nodes) != 1: + raise AssertionError("expect only 1 add node at output quant pattern") + zero_points.append(quant_nodes[0].args[2]) + if not all(zero_point == zero_points[0] for zero_point in zero_points): + return False + + # Step 2: Check inputs/output scale + scales = [node.args[1] for node in dequant_nodes] + scales.append(quant_nodes[0].args[1]) + if not all(math.isclose(scale, scales[0], rel_tol=1e-5) for scale in scales): # type: ignore[arg-type] + return False + + return True + + return fn + + +def _register_quantized_cat_lowering( + pattern, + computation_op, +): + @register_lowering_pattern( + pattern, + extra_check=_is_input_output_same_scale_zp(aten.cat.default), + ) + def qcat(match: Match, inputs, dim, **kwargs): + # inputs is with format: [[x1, x1_dq_dtype, x1_zp, x1_scale], ...] + uint8_inputs = [input[0] for input in inputs] + counters["inductor"]["qcat_matcher_count"] += 1 + counters["inductor"]["qcat_matcher_nodes"] += len(match.nodes) + return L[computation_op](uint8_inputs, dim) + + return qcat + + +_raw_dequantize_per_tensor_activation_pattern = CallFunction( + quantized_decomposed.dequantize_per_tensor.default, + Arg(), + Arg(), + Arg(), + Arg(), + Arg(), + Arg(), +) + + +def _register_quantization_cat(): + dequantize_cat_pattern = CallFunction( + aten.cat.default, + ListOf(_raw_dequantize_per_tensor_activation_pattern), + KeywordArg("dim"), + ) + _register_quantized_cat_lowering( + generate_pattern_with_output_quant(dequantize_cat_pattern), + aten.cat, + ) + + +def _register_quantized_reshape_lowering( + pattern, + computation_op, +): + def qreshape_output_metadata(*args, **kwargs): + return aten.reshape.default(kwargs["x"], kwargs["shape"]) + + @register_lowering_pattern( + pattern, + extra_check=_is_input_output_same_scale_zp(aten.reshape.default), + output_metadata_ignores_input_storage=False, + output_metadata_fn=qreshape_output_metadata, + ) + def qreshape(match: Match, *args, **kwargs): + qx = kwargs["x"] + shape = kwargs["shape"] + counters["inductor"]["qreshape_matcher_count"] += 1 + counters["inductor"]["qreshape_matcher_nodes"] += len(match.nodes) + return L[computation_op](qx, shape) + + return qreshape + + +def _register_quantization_reshape(): + dequantize_reshape_pattern = CallFunction( + torch.ops.aten.reshape.default, + get_dequantize_per_tensor_activation_pattern(), + KeywordArg("shape"), + ) + _register_quantized_reshape_lowering( + generate_pattern_with_output_quant(dequantize_reshape_pattern), + aten.reshape, + ) + + +def _is_valid_concat_linear_int8_woq_optimization_pattern(): + def fn(match): + if not config.cpp.enable_concat_linear: + return False + if not all(k in match.kwargs for k in ("x", "w1", "w2", "w3", "scales")): + raise AssertionError("expected x, w1, w2, w3, scales in match kwargs") + if not all( + hasattr(match.kwargs[key], "meta") + for key in ["x", "w1", "w2", "w3", "scales"] + ): + return False + x = match.kwargs["x"].meta["val"] + w1 = match.kwargs["w1"].meta["val"] + w2 = match.kwargs["w2"].meta["val"] + w3 = match.kwargs["w3"].meta["val"] + scales = match.kwargs["scales"].meta["val"] + if len(match.kwargs["scales"].meta["val"].size()) > 1: + return False + num_scales = match.kwargs["scales"].meta["val"].numel() + w1_cols = match.kwargs["w1"].meta["val"].size()[0] + w2_cols = match.kwargs["w2"].meta["val"].size()[0] + w3_cols = match.kwargs["w3"].meta["val"].size()[0] + return ( + # For now, we only support woq mm kernels + # with x.type=bfloat16 and w.type=int8 + x.dtype == torch.bfloat16 + and w1.dtype == torch.int8 + and w2.dtype == torch.int8 + and w3.dtype == torch.int8 + and scales.dtype == torch.bfloat16 + and x.device.type in ("cpu", "cuda") + and x.device == w1.device + and w1.device == w2.device + and w2.device == w3.device + and x.device == scales.device + and num_scales == w1_cols + w2_cols + w3_cols + ) + + return fn + + +def _is_valid_woq_optimization_pattern(): + def fn(match): + if not all(k in match.kwargs for k in ("x", "weight", "scales")): + raise AssertionError("expected x, weight, scales in match kwargs") + if not all( + hasattr(match.kwargs[key], "meta") for key in ["x", "weight", "scales"] + ): + return False + x = match.kwargs["x"].meta["val"] + weight = match.kwargs["weight"].meta["val"] + scales = match.kwargs["scales"].meta["val"] + return ( + # For now, we only support woq mm kernels + # with x.type=bfloat16 and w.type=int8 + x.dtype == torch.bfloat16 + and weight.dtype == torch.int8 + and scales.dtype == torch.bfloat16 + and x.device.type in ("cpu", "cuda", "xpu") + and x.device == weight.device + and x.device == scales.device + ) + + return fn + + +def _register_concat_linear_int8_woq_lowering( + pattern, computation_woq, computation_reshape +): + @register_freezing_graph_pattern( + pattern, + extra_check=_is_valid_concat_linear_int8_woq_optimization_pattern(), + pass_number=4, + ) + def woq_int8(match: Match, *args, **kwargs): + x = kwargs["x"] + w1 = kwargs["w1"] + w2 = kwargs["w2"] + w3 = kwargs["w3"] + scales = kwargs["scales"] + counters["inductor"]["woq_matcher_count"] += 1 + counters["inductor"]["woq_matcher_nodes"] += len(match.nodes) + out_features = ( + w1.meta["val"].size()[0] + + w2.meta["val"].size()[0] + + w3.meta["val"].size()[0] + ) + origin_x_size = tuple(x.meta["val"].size()) + x_shape = [-1, origin_x_size[-1]] + out_shape = list(origin_x_size[:-1] + (out_features,)) + mm_node_of_x = None + for candidate in iter(x.users.keys()): + if ( + candidate.target is aten.mm.default + and list(candidate._input_nodes)[1].target is aten.cat.default + ): + mm_node_of_x = candidate + break + if mm_node_of_x is None: + raise AssertionError("unable to find mm node") + _, cat_wgt_node = mm_node_of_x._input_nodes + scaling_node = next(iter(mm_node_of_x.users.keys())) + user_of_scaling_node = next(iter(scaling_node.users.keys())) + # Some other pass is making some changes that entails + # adding a node before it's used, but it can only be found when + # lint is run. stable_topological_sort() is being run before lint, + # so that error was not being discovered. + # We call stable_topological_sort here as a workaround. + stable_topological_sort(match.graph) + with match.graph.inserting_before(user_of_scaling_node): + new_cat_node = match.graph.call_function( + aten.cat.default, + args=([w1, w2, w3], 0), + ) + x_reshape_node = match.graph.call_function( + computation_reshape, args=(x, x_shape) + ) + new_woq_node = match.graph.call_function( + computation_woq, + args=(x_reshape_node, new_cat_node, scales), + ) + new_woq_node.meta = copy.copy(x.meta) + output_reshape_node = match.graph.call_function( + computation_reshape, args=(new_woq_node, out_shape) + ) + scaling_node.replace_all_uses_with(output_reshape_node) + match.graph.erase_node(scaling_node) + match.graph.erase_node(mm_node_of_x) + match.graph.erase_node(cat_wgt_node) + match.graph.lint() + + return woq_int8 + + +def _register_woq_lowering(pattern, computation_woq, computation_reshape): + @register_lowering_pattern( + pattern, + extra_check=_is_valid_woq_optimization_pattern(), + ) + def woq_int8(match: Match, *args, **kwargs): + x = kwargs["x"] + weight = kwargs["weight"] + scales = kwargs["scales"] + counters["inductor"]["woq_matcher_count"] += 1 + counters["inductor"]["woq_matcher_nodes"] += len(match.nodes) + out_features = weight.get_size()[0] + origin_x_size = x.get_size() + x_shape = [-1, origin_x_size[-1]] + out_shape = origin_x_size[:-1] + [ + out_features, + ] + func1 = L[computation_reshape](x, x_shape) + func2 = L[computation_woq](func1, weight, scales) + return L[computation_reshape](func2, out_shape) + + return woq_int8 + + +def _register_woq_mm_int8_pattern1(): + # F.linear(x, weight.to(dtype=x.dtype)) * scales + # case of dispatching to mm, with x reshape + _woq_pattern = CallFunction( + aten.mul.Tensor, + CallFunction( + aten.reshape.default, + CallFunction( + aten.mm.default, + CallFunction(aten.reshape.default, KeywordArg("x"), Arg()), + CallFunction( + aten.permute.default, + CallFunction( + prims.convert_element_type.default, KeywordArg("weight"), Arg() + ), + Arg(), + ), + ), + Arg(), + ), + KeywordArg("scales"), + ) + _register_woq_lowering(_woq_pattern, aten._weight_int8pack_mm.default, aten.reshape) + + +def _register_woq_mm_int8_pattern2(): + # F.linear(x, weight.to(dtype=x.dtype)) * scales + # case of dispatching to mm, w/o x reshape + _woq_pattern = CallFunction( + aten.mul.Tensor, + CallFunction( + aten.reshape.default, + CallFunction( + aten.mm.default, + KeywordArg("x"), + CallFunction( + aten.permute.default, + CallFunction( + prims.convert_element_type.default, KeywordArg("weight"), Arg() + ), + Arg(), + ), + ), + Arg(), + ), + KeywordArg("scales"), + ) + _register_woq_lowering(_woq_pattern, aten._weight_int8pack_mm.default, aten.reshape) + + +def _register_woq_mm_int8_pattern3(): + # F.linear(x, weight.to(dtype=x.dtype)) * scales + # case of dispatching to bmm + _woq_pattern = CallFunction( + aten.mul.Tensor, + CallFunction( + aten.bmm.default, + CallFunction(aten.expand.default, KeywordArg("x"), Arg()), + CallFunction( + aten.expand.default, + CallFunction( + aten.permute.default, + CallFunction( + prims.convert_element_type.default, KeywordArg("weight"), Arg() + ), + Arg(), + ), + Arg(), + ), + ), + KeywordArg("scales"), + ) + _register_woq_lowering(_woq_pattern, aten._weight_int8pack_mm.default, aten.reshape) + + +def _register_woq_mm_int8_pattern4(): + _woq_pattern = CallFunction( + aten.mul.Tensor, + CallFunction( + aten.mm.default, + KeywordArg("x"), + CallFunction( + prims.convert_element_type.default, + CallFunction( + aten.permute.default, + KeywordArg("weight"), + Arg(), + ), + Arg(), + ), + ), + KeywordArg("scales"), + ) + _register_woq_lowering(_woq_pattern, aten._weight_int8pack_mm.default, aten.reshape) + + +def _register_int8_woq_concat_linear_pattern(): + def _create_wgt_node(wgt_node_name: str): + return CallFunction( + prims.convert_element_type.default, + CallFunction( + aten.permute.default, + KeywordArg(wgt_node_name), + Arg(), + ), + Arg(), + ) + + cat_wgt = CallFunction( + aten.cat.default, [_create_wgt_node(wgt) for wgt in ["w1", "w2", "w3"]], 1 + ) + + _woq_pattern = CallFunction( + aten.mul.Tensor, + CallFunction(aten.mm.default, KeywordArg("x"), cat_wgt), + KeywordArg("scales"), + ) + _register_concat_linear_int8_woq_lowering( + _woq_pattern, aten._weight_int8pack_mm.default, aten.reshape + ) + + +def _register_quantization_lowerings(): + _register_quantization_unary_lowering() + _register_quantization_binary_lowering() + _register_quantization_maxpool2d() + _register_quantization_cat() + _register_quantization_reshape() + + +def _register_woq_lowerings(): + _register_woq_mm_int8_pattern1() + _register_woq_mm_int8_pattern2() + _register_woq_mm_int8_pattern3() + _register_woq_mm_int8_pattern4() + + +def _is_valid_concat_linear_woq_int4_fusion(computation_nodes): + computation_op = torch.ops.aten._weight_int4pack_mm_for_cpu.default + act = computation_nodes[0].args[0] + wgt = computation_nodes[0].args[1] + in_feature_size = wgt.meta.get("val").size(1) # type: ignore[union-attr] + group_size = computation_nodes[0].args[2] + return len(computation_nodes) >= 2 and all( + ( + node.target == computation_op + and node.args[0] == act # share same activation + and ( + node.args[1].meta.get("val").size(1) == in_feature_size + ) # same in feature size + and (node.args[1] != wgt or gemm_idx == 0) + and node.args[1].op == "get_attr" # wgt are all constants + and node.args[2] == group_size # same group size + ) + for gemm_idx, node in enumerate(computation_nodes) + ) + + +def concat_linear_woq_int4(gm: torch.fx.GraphModule): + """ + Concat Linear optimization pass for WOQ int4 + This pass fuses the original pattern: + def ... + return (woq_int4(x, w1, group_size, scale_zp1), woq_int4(x, w2, group_size, scale_zp1) ...) + into a single operation: + def ... + concat_res = woq_int4(x, concat_w, group_size, concat_scale_zp) + return split(concat_res, split_size_list) + """ + + def concat_wgt(packed_wgts, scale_zps, group_size, act_dtype): + # Concat the wgts and scale_zps, and repack the wgt + unpacked_wgts = [] + for packed_wgt in packed_wgts: + # Get the unpacked weight list + # Same as https://github.com/pytorch/pytorch/pull/156174 + K = packed_wgt.size(1) * 2 + N = packed_wgt.size(0) + x = torch.eye(K).to(dtype=act_dtype) + qscales_and_zeros = ( + torch.tensor([1.0, 8.0]) + .to(dtype=act_dtype) + .expand(K // group_size, N, 2) + .contiguous() + ) + unpacked_wgts.append( + torch.ops.aten._weight_int4pack_mm_for_cpu( + x, + packed_wgt, + group_size, + qscales_and_zeros, + ) + .t() + .contiguous() + .to(torch.int32) # N, K + ) + concat_unpacked_wgt = torch.cat(unpacked_wgts, dim=0) + repack_w = torch.ops.aten._convert_weight_to_int4pack_for_cpu( + concat_unpacked_wgt, 1 + ) + concat_scale_zp = torch.cat(scale_zps, dim=1).contiguous() + return repack_w, concat_scale_zp + + graph = gm.graph + computation_op = torch.ops.aten._weight_int4pack_mm_for_cpu.default + for node in graph.find_nodes(op="call_function", target=computation_op): + if ( + not node._erased + and isinstance(node.meta.get("val"), torch.Tensor) + and node.meta["val"].device.type == "cpu" + ): + act = node.args[0] + users = list(act.users) + if _is_valid_concat_linear_woq_int4_fusion(users): + with graph.inserting_before(node): + if not all(user.args[1].op == "get_attr" for user in users): + raise AssertionError( + "expected all users to have get_attr weight" + ) + computation_node_0 = users[0] + packed_wgts = [getattr(gm, user.args[1].target) for user in users] + group_size = computation_node_0.args[2] + scale_zps = [getattr(gm, user.args[3].target) for user in users] + out_feature_size_list = [ + packed_wgt.size(0) for packed_wgt in packed_wgts + ] + repack_w, concat_scale_zp = concat_wgt( + packed_wgts, scale_zps, group_size, act.meta.get("val").dtype + ) + repack_w_node_name = computation_node_0.args[1].target + "_concat" + concat_scale_zp_node_name = ( + computation_node_0.args[3].target + "_concat" + ) + gm.register_buffer(repack_w_node_name, repack_w) + setattr(gm, repack_w_node_name, repack_w) + gm.register_buffer(concat_scale_zp_node_name, concat_scale_zp) + setattr(gm, concat_scale_zp_node_name, concat_scale_zp) + + repack_w_node = graph.create_node( + "get_attr", repack_w_node_name, (), {} + ) + with graph.inserting_after(repack_w_node): + concat_scale_zp_node = graph.create_node( + "get_attr", concat_scale_zp_node_name, (), {} + ) + + with graph.inserting_after(concat_scale_zp_node): + concat_int4_gemm_node = graph.create_node( + "call_function", + computation_op, + ( + act, + repack_w_node, + group_size, + concat_scale_zp_node, + ), + ) + with graph.inserting_after(concat_int4_gemm_node): + split_node = graph.create_node( + "call_function", + torch.ops.aten.split_with_sizes.default, + ( + concat_int4_gemm_node, + out_feature_size_list, + 1, # split dim + ), + ) + with graph.inserting_after(split_node): + for gemm_idx, user in enumerate(users): + if user.target != computation_op: + raise AssertionError( + f"expected target {computation_op}, got {user.target}" + ) + get_item = graph.create_node( + "call_function", + operator.getitem, + ( + split_node, + gemm_idx, + ), + ) + with graph.inserting_after(get_item): + clone_node = graph.create_node( + "call_function", + torch.ops.aten.clone.default, + (get_item,), + {"memory_format": torch.contiguous_format}, + ) + user.replace_all_uses_with(clone_node) + graph.erase_node(user) + + +def quant_lift_up(graph_module: torch.fx.GraphModule): + """ + Lift up the quant node before view like nodes. It can benefit performance + of Attention like block. For example, we have the pattern as: + + DQ + DQ LINEAR + LINEAR VIEW + VIEW PERMUTE + PERMUTE TRANSPOSE + Q Q + DQ DQ + Matmul + DIV + ADD + SOFTMAX + + We want to lift up the quant nodes from matmul before view like nodes + as the output of Linear node. + + DQ + DQ LINEAR + LINEAR Q + Q VIEW + VIEW PERMUTE + PERMUTE TRANSPOSE + DQ DQ + Matmul + DIV + ADD + SOFTMAX + + It produces a DQ->LINEAR->Q pattern which can be fused by backend. + """ + + def is_view_op(node): + return node.op == "call_function" and node.target in _VIEW_OPS + + for node in graph_module.graph.nodes: + # Leslie: Here we verify that the quant node has exactly + # one input FX node, with constant scalar value for scale and zero point. + # For the case input of quant node has more than one input FX nodes, + # extend the implementation to lift up all the connected nodes + # before the view nodes to keep the topological order. + if ( + node.op == "call_function" + and node.target in _PER_TENSOR_QUANTIZE_OPS + and len(node.all_input_nodes) == 1 + and is_view_op(node.all_input_nodes[0]) + ): + quant_node = node + input_node_of_quant = quant_node.args[0] + + # Check the nodes along lift up path has only 1 user node + # Propagate view like node to find where to insert the new quant node + could_lift_up = True + current_node = quant_node + input_node = current_node.args[0] + while is_view_op(input_node): + if len(input_node.users) != 1: + could_lift_up = False + break + current_node = input_node + input_node = current_node.args[0] + + # Further check the input node of the first view node has only 1 user node + if could_lift_up and len(input_node.users) == 1: + counters["inductor"]["quant_lift_up_count"] += 1 + # Replace dequant's input from quant to quant's input + quant_node.replace_all_uses_with(input_node_of_quant) + # Insert the new quant node + with graph_module.graph.inserting_before(current_node): + new_quant_node = graph_module.graph.node_copy(quant_node) + input_node.replace_all_uses_with(new_quant_node) + + # Update inputs of new_quant_node + def maybe_replace_node(n: torch.fx.Node) -> torch.fx.Node: + if n == input_node_of_quant: + return input_node + else: + return n + + new_args = map_arg(new_quant_node.args, maybe_replace_node) + new_kwargs = map_arg(new_quant_node.kwargs, maybe_replace_node) + new_quant_node.args = new_args # type: ignore[assignment] + new_quant_node.kwargs = new_kwargs # type: ignore[assignment] + graph_module.graph.erase_node(quant_node) + + graph_module.graph.lint() + graph_module.recompile() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/reduced_atomic_contention.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/reduced_atomic_contention.py new file mode 100644 index 0000000000000000000000000000000000000000..efd7921ce6f8cce25983f4b563acf86e2bf2bb0a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/reduced_atomic_contention.py @@ -0,0 +1,688 @@ +# mypy: allow-untyped-defs +""" +Partitioned scatter optimization for high-contention index_put operations. + +Algorithm: + 1. Assign each write operation a partition: partition_id = op_id & (P - 1) + 2. Scatter into an expanded buffer of size P * dim_size along scatter_dim + 3. Reshape to [..., P, dim_size, ...] and sum across partitions + 4. Add result to the original input +""" + +import logging +import math +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Any + +import torch +import torch.fx as fx +from torch._dynamo.utils import counters +from torch._inductor import config +from torch._inductor.fx_passes.memory_estimator import build_memory_profile +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + Match, + PatternMatcherPass, + register_graph_pattern, +) +from torch._logging import getArtifactLogger +from torch.fx.experimental.symbolic_shapes import optimization_hint + + +log = logging.getLogger(__name__) +_artifact_log = getArtifactLogger(__name__, "partitioned_scatter") +aten = torch.ops.aten +prims = torch.ops.prims + +_INDEX_PUT_TARGETS = (aten.index_put.default, aten.index_put_.default) + + +@dataclass +class ScatterCandidate: + """An index_put(accumulate=True) op that passed the cheap (non-memory) gates.""" + + output_node: fx.Node + index_node: fx.Node + scatter_dim: int + output_size: int + index_size: int + scatter_dim_size: int + element_bytes: int + contention_ratio: float + dtype: torch.dtype + + +@dataclass +class ScatterMemoryState: + # Peak live GPU bytes at each compute node in the original (un-transformed) + # graph, taken at the allocation phase (before this node's last-use inputs + # are freed) so the expanded scatter buffer is charged against the true peak. + peak_mem_by_node: list[int] + + node_to_idx: dict[fx.Node, int] + + # total_gpu_memory - non_model_floor_bytes + allowed_peak_bytes: int + + total_gpu_bytes: int + non_model_floor_bytes: int + + # Expanded-buffer bytes already granted to scatters transformed earlier in this + # invocation. peak_mem_by_node profiles the *original* graph, so without this every + # candidate is sized against the same baseline and each claims the whole budget. + # A running sum rather than a per-live-range charge because scatters sharing an + # input fuse into one kernel, which needs all their expanded buffers live at once. + committed_overhead_bytes: int = 0 + + +@dataclass +class ScatterPassContext: + """Per-invocation state, passed to the pattern callbacks via closures.""" + + # index_put nodes that survived the cheap pre-scan, keyed by output node. + candidates: dict[fx.Node, ScatterCandidate] = field(default_factory=dict) + + # Built lazily, only when at least one candidate survives the pre-scan. + memory: "ScatterMemoryState | None" = None + + n_candidates: int = 0 + n_applied: int = 0 + skip_reasons: dict[str, int] = field(default_factory=lambda: defaultdict(int)) + applied_partitions: list[int] = field(default_factory=list) + + +def _record_skip( + ctx: ScatterPassContext, reason: str, node_name: str, *args: Any +) -> None: + ctx.skip_reasons[reason] += 1 + counters["inductor"][f"partitioned_scatter_skipped_{reason}"] += 1 + if _artifact_log.isEnabledFor(logging.DEBUG): + fmt = f"partitioned_scatter: SKIP node=%s reason={reason}" + if args: + fmt += " " + " ".join(str(a) for a in args) + _artifact_log.debug(fmt, node_name) + + +def _evaluate_candidate( + output_node: fx.Node, force: bool, ctx: ScatterPassContext +) -> "ScatterCandidate | None": + """ + Cheap (non-memory) gates, in order: + 1. Single non-None index (multi-axis not supported) + 2. Valid tensor metadata + 3. Runs on a CUDA device (this optimization targets GPU atomic contention) + 4. Non-bool dtype + 5. scatter_dim in bounds + 6. Resolvable, non-zero sizes + 7. index_size >= min_index_size + 8. contention_ratio >= threshold (uses scatter_dim_size, not output_numel) + """ + node_name = output_node.name + + input_node = output_node.args[0] + indices_arg = output_node.args[1] + + if not isinstance(input_node, fx.Node): + _record_skip(ctx, "input_not_node", node_name) + return None + + scatter_dim, index_node = _extract_scatter_dim_and_index(indices_arg) + if scatter_dim is None or index_node is None: + _record_skip(ctx, "multi_index", node_name) + return None + + input_meta = _get_tensor_meta(input_node) + index_meta = _get_tensor_meta(index_node) + if not input_meta or not index_meta: + _record_skip(ctx, "no_meta", node_name) + return None + + # Only rewrite accelerator ops: the expanded-buffer trade-off targets GPU + # atomic contention and is a pessimization on CPU. Matches the non-CPU + # device_filter that the memory estimator uses. + if input_meta["device"].type == "cpu": + _record_skip(ctx, "cpu_device", node_name) + return None + + if input_meta["dtype"] == torch.bool or index_meta["dtype"] == torch.bool: + _record_skip(ctx, "bool_dtype", node_name) + return None + + if scatter_dim >= len(input_meta["shape"]): + _record_skip(ctx, "dim_out_of_bounds", node_name) + return None + + output_size = _resolve_numel(input_meta["numel"]) + index_size = _resolve_numel(index_meta["numel"]) + + if output_size is None or index_size is None: + _record_skip(ctx, "dynamic_no_hint", node_name) + return None + + if output_size == 0 or index_size == 0: + _record_skip(ctx, "zero_size", node_name) + return None + + # Contention is per scatter-dim slot, so use scatter_dim_size as denominator. + # For a [vocab, dim] output, ratio = N/vocab, not N/(vocab*dim). + scatter_dim_size = _resolve_numel(input_meta["shape"][scatter_dim]) + if scatter_dim_size is None or scatter_dim_size == 0: + _record_skip(ctx, "zero_size", node_name) + return None + + min_index_size: int = config.partitioned_scatter_min_index_size + if not force and index_size < min_index_size: + _record_skip( + ctx, + "index_too_small", + node_name, + f"index_size={index_size} min={min_index_size}", + ) + return None + + contention_ratio = index_size / scatter_dim_size + min_contention: float = config.partitioned_scatter_min_contention_ratio + if not force and contention_ratio < min_contention: + _record_skip( + ctx, + "low_contention", + node_name, + f"contention_ratio={contention_ratio:.3f} threshold={min_contention:.3f}", + ) + return None + + return ScatterCandidate( + output_node=output_node, + index_node=index_node, + scatter_dim=scatter_dim, + output_size=output_size, + index_size=index_size, + scatter_dim_size=scatter_dim_size, + element_bytes=input_meta["dtype"].itemsize, + contention_ratio=contention_ratio, + dtype=input_meta["dtype"], + ) + + +def _scan_candidates(graph: fx.Graph, ctx: ScatterPassContext) -> None: + """ + Cheap pre-scan for index_put(accumulate=True) ops that could be rewritten. + + Applies every gate that does not require the memory profile (device, dtype, + shape, min index size, contention ratio) so we can skip building the + memory profile entirely when no op would qualify. + """ + force: bool = config.partitioned_scatter_force + + for node in graph.nodes: + if node.op != "call_function" or node.target not in _INDEX_PUT_TARGETS: + continue + args = node.args + if len(args) < 4 or args[3] is not True: + continue + + ctx.n_candidates += 1 + candidate = _evaluate_candidate(node, force, ctx) + if candidate is not None: + ctx.candidates[node] = candidate + + +def _build_scatter_memory_state(graph: fx.Graph) -> "ScatterMemoryState | None": + """ + Build a per-node peak-memory profile of the original graph. + Returns None when CUDA is unavailable or the profile can't be built; the + pass then runs unconstrained by the memory budget. + """ + if not torch.cuda.is_available(): + return None + + _, total_gpu = torch.cuda.mem_get_info() + + floor_bytes: int = config.partitioned_scatter_non_model_floor_bytes + allowed_peak = max(0, total_gpu - floor_bytes) + + def is_releasable(n: fx.Node) -> bool: + return not n.name.startswith("primals") + + # build_memory_profile emits two entries per compute node: the first after + # its allocations (the node-local peak, while last-use inputs are still + # live) and the second after its deallocations. We key on the allocation + # entry so the expanded scatter buffer is charged against the real peak. + # Unbacked symbolic sizes have no optimization_hint, so sizing the profile + # can raise. Memory gating is a heuristic, so fall back to running the pass + # unconstrained rather than failing the compile. + try: + profile = build_memory_profile(graph, is_releasable) + except Exception as e: + _artifact_log.debug( + "partitioned_scatter: build_memory_profile failed (%s), " + "running without memory gating", + e, + ) + return None + + compute_nodes = [ + n for n in graph.nodes if n.op not in ("placeholder", "get_attr", "output") + ] + node_to_idx: dict[fx.Node, int] = {} + peak_mem: list[int] = [] + for i, node in enumerate(compute_nodes): + alloc_idx = 1 + 2 * i + if alloc_idx >= len(profile): + break + node_to_idx[node] = i + peak_mem.append(profile[alloc_idx]) + + _artifact_log.debug( + "partitioned_scatter: memory state built — " + "graph_nodes=%d compute_nodes=%d " + "total_gpu=%d MB floor=%d MB allowed_peak=%d MB", + sum(1 for _ in graph.nodes), + len(compute_nodes), + total_gpu // 1_000_000, + floor_bytes // 1_000_000, + allowed_peak // 1_000_000, + ) + + return ScatterMemoryState( + peak_mem_by_node=peak_mem, + node_to_idx=node_to_idx, + allowed_peak_bytes=allowed_peak, + total_gpu_bytes=total_gpu, + non_model_floor_bytes=floor_bytes, + ) + + +def _compute_num_partitions( + available_bytes: int, + output_size: int, + element_bytes: int, + min_p: int, + max_p: int, + index_size: int = 0, + scatter_dim_size: int = 0, + force: bool = False, +) -> int: + """ + Return the largest power-of-2 P in [min_p, max_p] satisfying: + 1. Memory: output_size * element_bytes * (P - 1) <= available_bytes + 2. Diminishing-returns cap (skipped when force=True): + P <= 4 * writes_per_slot, where writes_per_slot = index_size / scatter_dim_size. + Past ~4W partitions for a slot taking W writes most partition slots are + never written, so the zero-fill and reduce over them buy nothing. + + Returns 0 if min_p doesn't fit. Power-of-2 is required by the bitwise-AND + partition assignment. + """ + if available_bytes <= 0 or output_size == 0 or element_bytes == 0: + return 0 + + max_raw = available_bytes / (output_size * element_bytes) + 1 + if max_raw < min_p: + return 0 + + p = 2 ** int(math.log2(max_raw)) + p = min(p, max_p) + + if not force and index_size > 0 and scatter_dim_size > 0: + writes_per_slot = index_size / scatter_dim_size + contention_cap = max(min_p, 2 ** int(math.log2(max(1, 4 * writes_per_slot)))) + p = min(p, contention_cap) + + return p + + +def _check_memory( + state: ScatterMemoryState, + candidate: ScatterCandidate, + force: bool = False, +) -> int: + """ + Compute num_partitions for this candidate given the peak-memory profile. + Returns num_partitions >= min_p, or 0 if the memory constraint cannot be met. + """ + min_p = config.partitioned_scatter_min_partitions + max_p = config.partitioned_scatter_max_partitions + + idx = state.node_to_idx.get(candidate.output_node) + if idx is None: + # No profile entry means we cannot bound this scatter's peak, so fail + # closed: granting max_p here would allocate max_p-1 extra copies of the + # output with no memory check at all. + return 0 + + baseline = state.peak_mem_by_node[idx] + available = state.allowed_peak_bytes - baseline - state.committed_overhead_bytes + + num_partitions = _compute_num_partitions( + available, + candidate.output_size, + candidate.element_bytes, + min_p, + max_p, + index_size=candidate.index_size, + scatter_dim_size=candidate.scatter_dim_size, + force=force, + ) + + if _artifact_log.isEnabledFor(logging.DEBUG): + overhead = ( + candidate.output_size * candidate.element_bytes * max(0, num_partitions - 1) + ) + _artifact_log.debug( + "partitioned_scatter: memory check node=%s " + "baseline_peak=%d MB committed=%d MB available=%d MB " + "expanded_buffer_cost=%d MB num_partitions=%d " + "total_gpu=%d MB floor=%d MB allowed_peak=%d MB", + candidate.output_node.name, + baseline // 1_000_000, + state.committed_overhead_bytes // 1_000_000, + available // 1_000_000, + overhead // 1_000_000, + num_partitions, + state.total_gpu_bytes // 1_000_000, + state.non_model_floor_bytes // 1_000_000, + state.allowed_peak_bytes // 1_000_000, + ) + + return num_partitions + + +def _resolve_numel(numel: Any) -> int | None: + """Resolve numel to a concrete int, handling SymInt via optimization_hint.""" + if isinstance(numel, torch.SymInt): + hint = optimization_hint(numel) + if hint is None: + return None + return hint * 2 # 2× safety margin for dynamic shapes + return int(numel) + + +def _validate_memory(match: Match, ctx: ScatterPassContext, force: bool) -> bool: + """ + Second-stage gate (the memory budget) for a matched index_put node. + + The cheap gates already ran in the pre-scan; here we only look up the + surviving candidate and size the partition count against the memory budget. + """ + output_node = match.output_node() + candidate = ctx.candidates.get(output_node) + if candidate is None: + # Node failed a cheap gate in the pre-scan (already recorded). + return False + + min_p: int = config.partitioned_scatter_min_partitions + max_p: int = config.partitioned_scatter_max_partitions + + if ctx.memory is not None: + num_partitions = _check_memory(ctx.memory, candidate, force=force) + else: + num_partitions = _compute_num_partitions( + available_bytes=2**62, + output_size=candidate.output_size, + element_bytes=candidate.element_bytes, + min_p=min_p, + max_p=max_p, + index_size=candidate.index_size, + scatter_dim_size=candidate.scatter_dim_size, + force=force, + ) + + if num_partitions < min_p: + _record_skip( + ctx, + "memory_budget", + output_node.name, + f"num_partitions={num_partitions} min={min_p}", + ) + return False + + match._num_partitions = num_partitions # type: ignore[attr-defined] + match._scatter_dim = candidate.scatter_dim # type: ignore[attr-defined] + match._index_node = candidate.index_node # type: ignore[attr-defined] + match._output_size = candidate.output_size # type: ignore[attr-defined] + match._element_bytes = candidate.element_bytes # type: ignore[attr-defined] + + if _artifact_log.isEnabledFor(logging.DEBUG): + _artifact_log.debug( + "partitioned_scatter: APPLY node=%s " + "num_partitions=%d scatter_dim=%d " + "contention_ratio=%.1f (index_size=%d / scatter_dim_size=%d) " + "output_size=%d dtype=%s%s", + output_node.name, + num_partitions, + candidate.scatter_dim, + candidate.contention_ratio, + candidate.index_size, + candidate.scatter_dim_size, + candidate.output_size, + candidate.dtype, + " [force]" if force else "", + ) + + return True + + +def _create_replacement( + match: Match, ctx: ScatterPassContext, input_tensor, indices, values +) -> None: + """Replace high-contention index_put with partitioned scatter.""" + num_partitions: int = match._num_partitions # type: ignore[attr-defined] + scatter_dim: int = match._scatter_dim # type: ignore[attr-defined] + index_node = match._index_node # type: ignore[attr-defined] + + def repl(input_tensor, index_node, values): + dim_size = input_tensor.shape[scatter_dim] + num_operations = index_node.numel() + + # Flatten multi-dimensional indices to 1-D + if len(index_node.shape) > 1: + flat_index = index_node.reshape(num_operations) + values_ndim = len(index_node.shape) + flat_values = values.reshape( + [num_operations] + list(values.shape[values_ndim:]) + ) + else: + flat_index = index_node + flat_values = values + + # partition_id = op_id & (num_partitions - 1), requires power-of-2 + operation_ids = torch.ops.prims.iota.default( + num_operations, + start=0, + step=1, + dtype=flat_index.dtype, + device=flat_index.device, + requires_grad=False, + ) + partition_ids = torch.ops.aten.bitwise_and.Scalar( + operation_ids, num_partitions - 1 + ) + + # Expanded buffer: one copy per partition along scatter_dim + expanded_shape = list(input_tensor.shape) + expanded_shape[scatter_dim] *= num_partitions + expanded_buffer = torch.ops.aten.full.default( + expanded_shape, + 0, + dtype=flat_values.dtype, + layout=torch.strided, + device=flat_values.device, + pin_memory=False, + ) + + # Shift each write into its partition's slice + partition_offsets = partition_ids * dim_size + adjusted_index = flat_index + partition_offsets + + if isinstance(indices, (list, tuple)): + adjusted_indices = [ + adjusted_index if i == scatter_dim else idx + for i, idx in enumerate(indices) + ] + else: + adjusted_indices = [adjusted_index] + + scattered_buffer = torch.ops.aten.index_put.default( + expanded_buffer, adjusted_indices, flat_values, True + ) + + # Reshape to [..., num_partitions, dim_size, ...] then sum partitions + reduce_shape = list(expanded_shape) + reduce_shape[scatter_dim] = num_partitions + reduce_shape.insert(scatter_dim + 1, dim_size) + reshaped = torch.ops.aten.view.default(scattered_buffer, reduce_shape) + + # Preserve dtype for integer types that don't promote during sum + if flat_values.dtype in (torch.int8, torch.int16, torch.int32, torch.uint8): + reduced = torch.ops.aten.sum.dim_IntList( + reshaped, [scatter_dim], dtype=flat_values.dtype + ) + else: + reduced = torch.ops.aten.sum.dim_IntList(reshaped, [scatter_dim]) + + return input_tensor + reduced + + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(repl, [input_tensor, index_node, values]) + + # Charge this scatter's expanded buffer so later candidates in the same + # invocation see a correspondingly smaller budget. + if ctx.memory is not None: + output_size: int = match._output_size # type: ignore[attr-defined] + element_bytes: int = match._element_bytes # type: ignore[attr-defined] + ctx.memory.committed_overhead_bytes += ( + output_size * element_bytes * (num_partitions - 1) + ) + + ctx.n_applied += 1 + ctx.applied_partitions.append(num_partitions) + counters["inductor"]["partitioned_scatter_applied"] += 1 + + +def _build_pattern_pass(ctx: ScatterPassContext) -> PatternMatcherPass: + """ + Construct a per-invocation PatternMatcherPass whose callbacks close over + `ctx`, avoiding module-level global state (which is unsafe under concurrent + compilation). + """ + patterns = PatternMatcherPass(pass_name="partitioned_scatter_optimization") + force: bool = config.partitioned_scatter_force + + def extra_check(match: Match) -> bool: + return _validate_memory(match, ctx, force) + + def replacement(match: Match, input_tensor, indices, values) -> None: + _create_replacement(match, ctx, input_tensor, indices, values) + + for target in _INDEX_PUT_TARGETS: + register_graph_pattern( + CallFunction(target, Arg(), Arg(), Arg(), True), + extra_check=extra_check, + pass_dict=patterns, # type: ignore[arg-type] + )(replacement) + + return patterns + + +def _log_summary(ctx: ScatterPassContext, num_matches: int) -> None: + if ctx.n_candidates == 0: + return + + if ctx.memory is not None: + log.info( + "partitioned_scatter: candidates=%d applied=%d skipped=%d " + "partitions_per_op=%s " + "skip_breakdown=%s " + "total_gpu=%d MB floor=%d MB allowed_peak=%d MB", + ctx.n_candidates, + ctx.n_applied, + ctx.n_candidates - ctx.n_applied, + ctx.applied_partitions, + dict(ctx.skip_reasons), + ctx.memory.total_gpu_bytes // 1_000_000, + ctx.memory.non_model_floor_bytes // 1_000_000, + ctx.memory.allowed_peak_bytes // 1_000_000, + ) + else: + log.info( + "partitioned_scatter: candidates=%d applied=%d skipped=%d " + "partitions_per_op=%s skip_breakdown=%s (no memory state)", + ctx.n_candidates, + ctx.n_applied, + ctx.n_candidates - ctx.n_applied, + ctx.applied_partitions, + dict(ctx.skip_reasons), + ) + + +def partitioned_scatter_optimization_pass(graph: fx.Graph) -> fx.Graph: + """ + Apply partitioned scatter optimization to high-contention index_put operations. + Controlled by config.partitioned_scatter_enabled. + """ + if not config.partitioned_scatter_enabled: + return graph + + ctx = ScatterPassContext() + + # Stage 1: cheap pre-scan. If nothing qualifies we avoid building the + # (relatively expensive) memory profile entirely. + _scan_candidates(graph, ctx) + if not ctx.candidates: + _log_summary(ctx, 0) + return graph + + # Stage 2: build the memory profile and run the pattern matcher. + ctx.memory = _build_scatter_memory_state(graph) + patterns = _build_pattern_pass(ctx) + num_matches = patterns.apply(graph) + + _log_summary(ctx, num_matches) + + if num_matches > 0: + graph.lint() + + return graph + + +def _extract_scatter_dim_and_index( + indices_arg: Any, +) -> tuple[int | None, fx.Node | None]: + """Extract scatter dimension and index node from indices argument.""" + if not isinstance(indices_arg, (list, tuple)): + return 0, indices_arg + + index_node = None + scatter_dim = None + + for dim, idx in enumerate(indices_arg): + if idx is not None: + if index_node is not None: + return None, None + index_node = idx + scatter_dim = dim + + return scatter_dim, index_node + + +def _get_tensor_meta(node: fx.Node) -> dict[str, Any] | None: + """Extract tensor metadata from an FX node's meta['val'] FakeTensor.""" + if not hasattr(node, "meta") or "val" not in node.meta: + return None + + val = node.meta["val"] + if not hasattr(val, "shape") or not hasattr(val, "dtype"): + return None + + return { + "shape": tuple(val.shape), + "dtype": val.dtype, + "device": val.device, + "numel": val.numel(), + } + + +__all__ = ["partitioned_scatter_optimization_pass"] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/reinplace.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/reinplace.py new file mode 100644 index 0000000000000000000000000000000000000000..2e22e407d7f2bea8151c4e9563ee1b1ae98ac624 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/reinplace.py @@ -0,0 +1,1073 @@ +# mypy: allow-untyped-defs +import itertools +import logging +import operator +from collections import defaultdict +from collections.abc import Callable, Sequence +from contextlib import nullcontext +from dataclasses import dataclass +from typing import Any, cast + +import torch +import torch.fx.node +from torch._C._dynamo.guards import compute_overlapping_tensors +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.utils import ReinplaceCounters, ReInplaceTrigger +from torch._guards import detect_fake_mode +from torch._higher_order_ops.triton_kernel_wrap import ( + kernel_side_table, + triton_kernel_wrapper_functional, +) +from torch._inductor import config, inductor_prims +from torch._inductor.fx_utils import get_node_storage, is_node_realized +from torch._inductor.lowering import ( + inplaceable_foreach_ops as inplaceable_foreach_ops_lowerings, +) +from torch._inductor.virtualized import V +from torch.fx.experimental.symbolic_shapes import ( + compute_unbacked_bindings, + GuardOnDataDependentSymNode, + statically_known_true, + sym_eq, +) +from torch.fx.immutable_collections import immutable_dict, immutable_list +from torch.fx.passes.reinplace import _is_view_op +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet + + +log = logging.getLogger(__name__) +aten = torch.ops.aten + + +@dataclass(frozen=True) +class InplaceableOp: + inplace_op: Callable[..., Any] + mutated_arg: int | tuple[int, ...] # Single index or tuple of indices + extra_check: Callable[[torch.fx.Node], bool] = lambda node: True + + @property + def mutated_args(self) -> tuple[int, ...]: + """Return mutated_arg as a tuple for uniform handling.""" + if isinstance(self.mutated_arg, int): + return (self.mutated_arg,) + return self.mutated_arg + + +_SCATTER_OP_TO_VIEW = { + torch.ops.aten.diagonal_scatter.default: torch.ops.aten.diagonal.default, + torch.ops.aten.select_scatter.default: torch.ops.aten.select.int, + torch.ops.aten.slice_scatter.default: torch.ops.aten.slice.Tensor, + torch.ops.aten.as_strided_scatter.default: torch.ops.aten.as_strided.default, +} +_VIEW_OP_TO_SCATTER = {v: k for k, v in _SCATTER_OP_TO_VIEW.items()} + + +def graph_call_function(graph: torch.fx.Graph, fn, *args, **kwargs): + fake_args, fake_kwargs = pytree.tree_map( + lambda node: node.meta["val"] if isinstance(node, torch.fx.Node) else node, + (args, kwargs), + ) + with V.fake_mode: + fake_result = fn(*fake_args, **fake_kwargs) + + node = graph.call_function(fn, args, kwargs) + + node.meta["val"] = fake_result + if (V.fake_mode.shape_env) and ( + symbol_to_path := compute_unbacked_bindings(V.fake_mode.shape_env, fake_result) + ): + node.meta["unbacked_bindings"] = symbol_to_path + + return node + + +@dataclass +class ViewOp: + target: torch._ops.OpOverload + args: tuple[Any, ...] + kwargs: dict[str, Any] + + +def _inplace_generalized_scatter( + inp: torch.Tensor, src: torch.Tensor, view_ops: list[ViewOp] +) -> torch.Tensor: + tmp = inp + for view in view_ops: + fake_args, fake_kwargs = pytree.tree_map( + lambda node: node.meta["val"] if isinstance(node, torch.fx.Node) else node, + (view.args, view.kwargs), + ) + # slice and select can allocate new unbacked symints, but those won't be reflected + # in the output of this function, hence shall be ignored. + fake_mode = detect_fake_mode(fake_args) + with ( + fake_mode.shape_env.ignore_fresh_unbacked_symbols() + if fake_mode and fake_mode.shape_env + else nullcontext() + ): + tmp = view.target(tmp, *fake_args, **fake_kwargs) + try: + tmp.copy_(src) + except RuntimeError as e: + raise RuntimeError( + f"shape error in scatter op, can not broadcast {src.shape} to {tmp.shape}" + ) from e + return inp + + +def _generalized_scatter( + inp: torch.Tensor, src: torch.Tensor, view_ops: list[ViewOp] +) -> torch.Tensor: + out = inp.clone() + return _inplace_generalized_scatter(out, src, view_ops) + + +def _decompose_scatter_functional_helper( + graph: torch.fx.Graph, + inp: torch.Tensor, + src: torch.Tensor, + view_ops: list[ViewOp], +) -> torch.fx.Node: + view_op, view_ops_tail = view_ops[0], view_ops[1:] + + if view_ops_tail: + view = graph_call_function( + graph, view_op.target, inp, *view_op.args, **view_op.kwargs + ) + src = _decompose_scatter_functional_helper(graph, view, src, view_ops[1:]) # type: ignore[assignment] + + return graph_call_function( + graph, + _VIEW_OP_TO_SCATTER[view_op.target], + inp, + src, + *view_op.args, + **view_op.kwargs, + ) + + +def _decompose_scatter_functional( + graph: torch.fx.Graph, node: torch.fx.Node +) -> torch.fx.Node: + """Decompose _generalized_scatter to a sequence of view_scatter operations + + e.g. _generalized_scatter(inp, src, [(aten.slice, 0, 0, 10), (aten.slice, 1, 10, -10)]) + + will become + + view = aten.slice(inp, 0, 0, 10) + view_updated = aten.slice_scatter(view, src, 1, 10, -10) + inp_updated = aten.slice_scatter(inp, view_updated, 0, 0, 10) + """ + if node.target is not _generalized_scatter: + raise AssertionError( + f"expected node.target to be _generalized_scatter, got {node.target}" + ) + return _decompose_scatter_functional_helper(graph, *node.args) # type: ignore[arg-type] + + +def _decompose_scatter_mutating( + graph: torch.fx.Graph, node: torch.fx.Node +) -> torch.fx.Node: + """Decompose _generalized_scatter using mutations + + e.g. _generalized_scatter(inp, src, [(aten.slice, 0, 0, 10), (aten.slice, 1, 10, -10)]) + + will become + + inp_updated = aten.clone(inp) + slice1 = aten.slice(inp_updated, 0, 0, 10) + slice2 = aten.slice(slice1, 1, 10, -10) + slice2.copy_(src) + + """ + if node.target not in (_generalized_scatter, _inplace_generalized_scatter): + raise AssertionError(f"unexpected node.target: {node.target}") + inp, src, view_ops = node.args + if node.kwargs: + raise AssertionError(f"expected no kwargs, got {node.kwargs}") + + if node.target is _generalized_scatter: + inp = graph_call_function(graph, aten.clone, inp) + + tmp = inp + for view in view_ops: # type: ignore[union-attr] + tmp = graph_call_function(graph, view.target, tmp, *view.args, **view.kwargs) # type: ignore[union-attr] + + graph_call_function(graph, aten.copy_.default, tmp, src) + return inp # type: ignore[return-value] + + +# View ops whose view_scatter op is lowered into mutations anyway, +# so is never a pessimisation to decompose. +_ALWAYS_MUTATING_SCATTER_OPS = OrderedSet( + [ + aten.as_strided.default, + aten.diagonal.default, + ] +) + + +def scatter_always_uses_mutation(node: torch.fx.Node) -> bool: + _, _, view_ops = node.args + view_ops = cast(Sequence[torch.fx.node.Argument], view_ops) + return any( + target in _ALWAYS_MUTATING_SCATTER_OPS + for view in view_ops + if isinstance(target := getattr(view, "target", None), torch._ops.OpOverload) + ) + + +def should_reinplace_scatter(node: torch.fx.Node) -> bool: + """Choose between mutating and functional scatter decompositions + + Reinplacing view scatter ops can be pessimising as it blocks fusion with the + input or output tensor computations. However, it is still profitable if the + input and output would have been realized anyway. + + """ + inp, _src, _view_ops = node.args + + # Mutating scatter ops unconditionally realize input and output + if scatter_always_uses_mutation(node): + return True + + if is_node_realized(inp) and is_node_realized(node): # type: ignore[arg-type] + return True + + # If the output is copied back into the input, this forces both to be + # realized as the output is a user of the input + if inp.op in ("placeholder", "get_attr") and any( # type: ignore[union-attr] + user.target is aten.copy_.default and user.args[0] is inp for user in node.users + ): + return True + + # Otherwise, assume fusions will make functional variants profitable + return False + + +def decompose_generalized_scatter(graph: torch.fx.Graph) -> None: + """Replace _generalized_scatter with normal aten ops""" + for node in itertools.chain( + graph.find_nodes(op="call_function", target=_generalized_scatter), + graph.find_nodes(op="call_function", target=_inplace_generalized_scatter), + ): + use_mutation = ( + node.target is _inplace_generalized_scatter + or scatter_always_uses_mutation(node) + ) + + with graph.inserting_before(node): + if use_mutation: + new_node = _decompose_scatter_mutating(graph, node) + else: + new_node = _decompose_scatter_functional(graph, node) + + node.replace_all_uses_with(new_node) + graph.erase_node(node) + + +def canonicalize_view_scatter_ops(graph: torch.fx.Graph) -> None: + """ + This canonicalizes view scatter ops into a generalized form, defined as: + def scatter(inp, src, views): + tmp = inp.clone() + for view in views: + tmp = view(tmp) + tmp.copy_(src) + + We also fuse consecutive view scatter ops of the form + a = scatter(view2(self), src, [view1]) + b = scatter(self, a, [view2]) + which can be rewritten as + b = scatter(self, src, [view2, view1]) + a = view2(b) + + This is both more efficient as we only do a single scatter, and also + easier to reinplace since there is only one use of `self` + """ + + node_to_view_base: dict[torch.fx.Node, torch.fx.Node] = {} + node_to_view_op: dict[torch.fx.Node, list[ViewOp]] = defaultdict(list) + + def handle_views(node: torch.fx.Node): + inp = node.args[0] + node_to_view_base[node] = node_to_view_base.get(inp, inp) # type: ignore[arg-type, assignment] + node_to_view_op[node] = [ + *node_to_view_op[inp], # type: ignore[index] + ViewOp( + node.target, # type: ignore[arg-type] + args=node.args[1:], + kwargs=node.kwargs, + ), + ] + + def handle_view_scatter(node: torch.fx.Node): + if len(node.args) < 2: + raise AssertionError(f"expected at least 2 args, got {len(node.args)}") + inp, src = node.args[:2] + + if not isinstance(node.target, torch._ops.OpOverload): + raise AssertionError( + f"expected node.target to be an OpOverload, got {type(node.target)}" + ) + scatter_view_op = ViewOp( + _SCATTER_OP_TO_VIEW[node.target], + args=node.args[2:], + kwargs=node.kwargs, + ) + + def can_fuse(): + if src.target is not _generalized_scatter: # type: ignore[union-attr] + return False + src_inp, _src_src, _src_scatter_view_op = src.args # type: ignore[union-attr] + + inp_base = node_to_view_base.get(inp, inp) # type: ignore[arg-type] + src_base = node_to_view_base.get(src_inp, src_inp) # type: ignore[arg-type] + return inp_base is src_base and node_to_view_op[src_inp] == [ # type: ignore[index] + *node_to_view_op[inp], # type: ignore[index] + scatter_view_op, + ] + + if not can_fuse(): + with graph.inserting_before(node): + new_node = graph_call_function( + graph, + _generalized_scatter, + inp, + src, + [scatter_view_op], + ) + node.replace_all_uses_with(new_node) + graph.erase_node(node) + return + + _src_inp, src_src, src_scatter_view_op = src.args # type: ignore[union-attr] + with graph.inserting_before(src): # type: ignore[arg-type] + new_node = graph_call_function( + graph, + _generalized_scatter, + inp, + src_src, + [scatter_view_op, *src_scatter_view_op], # type: ignore[misc] + ) + node.replace_all_uses_with(new_node) + graph.erase_node(node) + + if src.users: # type: ignore[union-attr] + new_src = graph_call_function( + graph, + _SCATTER_OP_TO_VIEW[node.target], + new_node, + *node.args[2:], + **node.kwargs, + ) + + handle_views(new_src) + src.replace_all_uses_with(new_src) # type: ignore[union-attr] + + graph.erase_node(src) # type: ignore[arg-type] + + for node in graph.nodes: + if _is_view_op(node.target): + handle_views(node) + elif node.target in _SCATTER_OP_TO_VIEW: + handle_view_scatter(node) + + +inplaceable_ops: dict[Callable[..., Any], InplaceableOp] = { + aten.index_put.default: InplaceableOp(aten.index_put_.default, 0), + aten._unsafe_index_put.default: InplaceableOp(inductor_prims._unsafe_index_put_, 0), + _generalized_scatter: InplaceableOp( + _inplace_generalized_scatter, + 0, + extra_check=should_reinplace_scatter, + ), + # Stateless Philox RNG: reinplace the functionalized clone onto the dead + # output buffer, so out-of-place uniform()/normal() don't pay an extra copy. + aten._philox_uniform.default: InplaceableOp(aten._philox_uniform_.default, 0), + aten._philox_normal.default: InplaceableOp(aten._philox_normal_.default, 0), +} + +try: + c10d_functional = torch.ops._c10d_functional + inplaceable_collective_ops: dict[Callable[..., Any], InplaceableOp] = { + c10d_functional.all_reduce.default: InplaceableOp( + c10d_functional.all_reduce_.default, 0 + ), + c10d_functional.all_reduce_coalesced.default: InplaceableOp( + c10d_functional.all_reduce_coalesced_.default, 0 + ), + } + inplaceable_ops.update(inplaceable_collective_ops) +except AttributeError: + # _c10d_functional ops are only available when torch + # is built with USE_DISTRIBUTED=1. + pass + +inplaceable_foreach_ops: dict[torch._ops.OpOverload, InplaceableOp] = {} +for outplace_op, inplace_op in inplaceable_foreach_ops_lowerings.items(): + inplaceable_foreach_ops[outplace_op] = InplaceableOp(inplace_op, 0) + + +inplaceable_triton_ops = OrderedSet([triton_kernel_wrapper_functional]) + + +# Operators that don't depend on the tensor data +META_ONLY_OPS = OrderedSet( + [ + aten.sym_size.int, + aten.sym_stride.int, + aten.sym_numel.default, + aten.sym_storage_offset.default, + ] +) + + +def _get_view_base(node: torch.fx.Node) -> torch.fx.Node: + while _is_view_op(node.target) and node.args: + base = node.args[0] + if not isinstance(base, torch.fx.Node): + break + node = base + return node + + +def _same_tensor_metadata(lhs: torch.fx.Node, rhs: torch.fx.Node) -> bool: + lhs_val = lhs.meta.get("val") + rhs_val = rhs.meta.get("val") + if not isinstance(lhs_val, torch.Tensor) or not isinstance(rhs_val, torch.Tensor): + return False + + def same_value(lhs_value, rhs_value) -> bool: + return statically_known_true(sym_eq(lhs_value, rhs_value)) + + def same_sequence(lhs_values, rhs_values) -> bool: + return len(lhs_values) == len(rhs_values) and all( + same_value(lhs_value, rhs_value) + for lhs_value, rhs_value in zip(lhs_values, rhs_values) + ) + + return ( + same_sequence(lhs_val.size(), rhs_val.size()) + and same_sequence(lhs_val.stride(), rhs_val.stride()) + and same_value(lhs_val.storage_offset(), rhs_val.storage_offset()) + ) + + +def _is_layout_preserving_view_copy_back( + dst: torch.fx.Node, + src: torch.fx.Node, + mutated_arg: torch.fx.Node, + src_base: torch.fx.Node, +) -> bool: + return _same_tensor_metadata(src_base, mutated_arg) and _same_tensor_metadata( + src, dst + ) + + +def _is_control_deps_ordering_only_use( + user: torch.fx.Node, view: torch.fx.Node +) -> bool: + """Check if view appears only in control_deps' ordering-only additional_deps tuple. + + control_deps schema (control_dependencies.py): control_deps(additional_deps, subgraph, *args) + kwargs is always empty -- preserve_node_ordering threads all nodes positionally. + """ + if not ( + user.op == "call_function" + and isinstance(user.target, torch._ops.HigherOrderOperator) + and user.target._name == "control_deps" + ): + return False + additional_deps = cast(tuple[torch.fx.Node, ...], user.args[0]) + pass_through = cast(tuple[torch.fx.Node, ...], user.args[2:]) + return view in additional_deps and view not in pass_through + + +def reinplace_inplaceable_ops_core(graph: torch.fx.Graph) -> None: + """ + Reinplaces in-placeable operations. + If there are no uses of a view of the mutated arg after the current node, + it is possible to inplace the op. + This above algorithm could be justified by observing side effects. While + we traverse the graph in forwards direction, only latter nodes could view + side effects of the current node. If the current node is not used later as + well as no view of this node is used later in the graph, then it is safe to + inplace as there would be no way to observe the side effects. + This condition is slightly different for graph inputs where they can only + be inplaced if the above condition is true and there's a copy_ in the + epilogue that signals that the caller wants to observe the mutation. + + Unlike JIT Inductor, AOTInductor currently unlifts weights and buffers from + input args, so instead of checking mutation on placeholder, AOTInductor + checks mutation on get_attr. This is subject to change in future. + """ + + copy_args_to_copy_nodes = {} + # maps argument to the first copy_ node that mutates it. + copy_nodes = {} + # maps (view_arg, inplaceable_op_node) to copy_ nodes that copy a view of + # the op result back into the graph input that view_arg aliases. + copy_args_to_copy_nodes_via_views = {} + mutated_inputs = OrderedSet[Any]() + storage_to_nodes = defaultdict(list) + node_order: dict[Any, int] = {} + for i, node in enumerate(reversed(graph.nodes)): + node_order[node] = len(graph.nodes) - i - 1 + storage_to_nodes[get_node_storage(node)].append(node) + if node.target is aten.copy_.default and node.args[0].op in ( + "placeholder", + "get_attr", + ): + dst = node.args[0] + src = node.args[1] + # If the target is a getitem and it indexes a possible clone, + # then skip over it + if src.target is operator.getitem and ( + ( + src.args[0].target == triton_kernel_wrapper_functional + and src.args[0].kwargs["kwargs"][src.args[1]] == node.args[0] + ) + or (src.args[0].target in inplaceable_foreach_ops) + or (src.args[0].target is torch.ops.higher_order.auto_functionalized) + ): + src = src.args[0] + + copy_args_to_copy_nodes[(dst, src)] = node + copy_nodes[dst] = node + + mutated_inputs.add(node.args[0]) + + src_base = _get_view_base(src) + if src_base is not src and isinstance(src_base.target, Callable): + inplaceable_op = inplaceable_ops.get(src_base.target) + if inplaceable_op is not None: + for mutated_arg_idx in inplaceable_op.mutated_args: + mutated_arg = src_base.args[mutated_arg_idx] + if ( + isinstance(mutated_arg, torch.fx.Node) + and _get_view_base(mutated_arg) is dst + and _is_layout_preserving_view_copy_back( + dst, src, mutated_arg, src_base + ) + ): + copy_args_to_copy_nodes_via_views[ + (mutated_arg, src_base) + ] = node + + def any_use_of_views_after_node(node, shared_view_nodes, *, copy_node, mutated_arg): + node_loc = node_order[node] + copy_node_loc = node_order[copy_node] if copy_node is not None else None + + def is_meta_only_user(node): + if _is_view_op(node.target): + return all(is_meta_only_user(u) for u in node.users) + return node.target in META_ONLY_OPS + + for view in shared_view_nodes: + for user in view.users: + user_loc = node_order[user] + # Skip all users before node + if user_loc <= node_loc: + continue + # Ignore uses after the copy_ epilogue node, where the input + # has already been mutated anyway + if copy_node_loc is not None and copy_node_loc <= user_loc: + continue + # Reinplacing does not change shape metadata + if is_meta_only_user(user): + continue + # If our graph looks like: + # foo(mutated_arg) + # mutated_arg.copy_(other) + # then it's safe for us to reinplace foo because mutated_arg + # will get overwritten anyways. + if ( + user.target is torch.ops.aten.copy_.default + and mutated_arg is user.args[0] + ): + continue + # control_deps args[0] is an ordering-only deps tuple; + # appearing there does not constitute a real data use. + if _is_control_deps_ordering_only_use(user, view): + continue + return True + return False + + def can_inplace(node, mutated_arg): + # ls should be a list of tensors that all shares the same storage. + def _overlap(ls) -> bool: + try: + return len(compute_overlapping_tensors(ls)) != 0 + except GuardOnDataDependentSymNode: + # If we fail with data dependent error we assume they all overlap. + return True + + if isinstance(mutated_arg, (list, tuple)): + # TODO Using _overlap here causes a several issues. + unique_storages = OrderedSet(get_node_storage(arg) for arg in mutated_arg) + if len(unique_storages) != len(mutated_arg): + # At least two Tensors in mutated_arg alias each other, so we can't reinplace it. + # We can probably do better (that is, reinplace one of them and clone the other) + # but that requires more work and mutable List[Tensor] are not that common. + return False + return all(can_inplace(node, arg) for arg in mutated_arg) + + if get_node_storage(mutated_arg) is None: + return False + + if torch._debug_has_internal_overlap(mutated_arg.meta["val"]) == 1: + return False + + shared_view_nodes = storage_to_nodes[get_node_storage(mutated_arg)] + + # Only keep tensor that might overlap with mutated_arg. + shared_view_nodes = [ + v + for v in shared_view_nodes + if _overlap([mutated_arg.meta["val"], v.meta["val"]]) + ] + + if mutated_arg.op in ("placeholder", "get_attr"): + # Get the first copy_ node that mutates the mutated_arg. + copy_node = copy_nodes.get(mutated_arg) + if copy_node is None: + # There is no copy_ back to the candidate mutated_arg (which is a graph input). + # Therefore the semantics of the program are that it does not mutate + # mutated_arg, so we cannot re-inplace it. + return False + if any_use_of_views_after_node( + node, shared_view_nodes, copy_node=copy_node, mutated_arg=mutated_arg + ): + return False + + return True + elif any(view.op in ("placeholder", "get_attr") for view in shared_view_nodes): + # If mutated_arg is a view of a graph input, we can only reinplace + # when a later copy_ writes this op's result back to that input. + copy_node = copy_args_to_copy_nodes_via_views.get((mutated_arg, node)) + if copy_node is None: + return False + + mutated_arg_base = copy_node.args[0] + copy_src = copy_node.args[1] + if not ( + isinstance(mutated_arg_base, torch.fx.Node) + and isinstance(copy_src, torch.fx.Node) + and _is_layout_preserving_view_copy_back( + mutated_arg_base, copy_src, mutated_arg, node + ) + ): + return False + + if any_use_of_views_after_node( + node, + shared_view_nodes, + copy_node=copy_node, + mutated_arg=mutated_arg_base, + ): + return False + return True + else: + return not any_use_of_views_after_node( + node, shared_view_nodes, copy_node=None, mutated_arg=mutated_arg + ) + + def copy_node_for_reinplaced_arg(node, mutated_arg): + copy_node = copy_args_to_copy_nodes.get((mutated_arg, node)) + if copy_node is None: + copy_node = copy_args_to_copy_nodes_via_views.get((mutated_arg, node)) + if copy_node is not None: + copy_dst = copy_node.args[0] + copy_src = copy_node.args[1] + if not ( + isinstance(copy_dst, torch.fx.Node) + and isinstance(copy_src, torch.fx.Node) + and _is_layout_preserving_view_copy_back( + copy_dst, copy_src, mutated_arg, node + ) + ): + return None + return copy_node + + def all_can_inplace(node, mutated_args): + return all(can_inplace(node, arg) for arg in mutated_args) + + def log_inplace_results( + node_name, + old_tensors_to_clone, + tensors_to_clone, + missed_args, + missed_nodes, + trigger, + ): + # Total size of possibly_missed_reinplacing_opportunities for tensors with static shapes. + missed_bytes = 0 + + def bytes(node): + t = node.meta.get("val", None) + if ( + t is not None + and isinstance(t.element_size(), int) + and isinstance(t.numel(), int) + ): + return t.element_size() * t.numel() + else: + return 0 + + for node in missed_nodes: + if isinstance(node, (list, tuple)): + for n in node: + missed_bytes += bytes(n) + else: + missed_bytes += bytes(node) + + log.info( + "For node %s, attempted to reinplace %s. We were unable to reinplace %s; " + "%s (if non-empty) are possible missed reinplacing opportunities that may be bad for " + "memory usage and performance. Total size of missed opportunities with static shapes is" + " : %s bytes.", + node_name, + old_tensors_to_clone, + tensors_to_clone, + missed_args, + missed_bytes, + ) + + ReinplaceCounters.add_missed_opportunities(trigger, len(missed_args)) + ReinplaceCounters.add_missed_bytes(trigger, missed_bytes) + + replace_dict: dict[torch.fx.Node, torch.fx.Node] = {} + + def reinplace_and_refine_tensors_to_clone( + old_tensors_to_clone, kwargs, node_name, trigger + ): + tensors_to_clone: list[str] = [] + storage_of_reinplaced_args = OrderedSet[int | None]() + + # Those used to count possibly_missed_reinplacing_opportunities + missed_nodes = [] + missed_args = [] + + # TODO this logic can be made more precise using _overlap + def tensor_with_same_storage_already_reinplaced(arg): + if isinstance(arg, (list, tuple)): + return any( + get_node_storage(a) in storage_of_reinplaced_args for a in arg + ) + return get_node_storage(mutated_arg) in storage_of_reinplaced_args + + for arg in old_tensors_to_clone: + if arg not in kwargs: + raise AssertionError(f"expected {arg} to be in kwargs") + + mutated_arg = kwargs[arg] + + # Let's say we have: + # - op(x, y) that mutates both x and y + # - new_x, new_y = functional_op(x, y) is the functional variant + # If we are presented with functional_op(x, x), we must not reinplace + # this into op(x, x), because then it would be writing to the same Tensor. + # Instead, it's OK to reinplace one of them and to clone the other: + # >>> y = x.clone() + # >>> op(x, y) + # This also applies if we have views: functional_op(x, x[0]) + # should not reinplace into op(x, x[0]). + should_attempt_reinplace = not tensor_with_same_storage_already_reinplaced( + mutated_arg + ) + if should_attempt_reinplace and can_inplace(node, mutated_arg): + # In general, we probably do not need those optimizations. + copy_node = copy_node_for_reinplaced_arg(node, mutated_arg) + if copy_node is not None: + replace_dict[copy_node] = copy_node.args[0] + if trigger != ReInplaceTrigger.AUTO_FUNC_V2: + for user in node.users: + # For auto_functionalize_v2, arg is the index of the base, where base at index i corresponds to + # output at index size(out)+i. + # This used to compare string with integers before for auto_functionalize_v2. Not sure + # if it was needed for inplaceable_triton_ops? + if user.target is operator.getitem and user.args[1] == arg: + replace_dict[user] = mutated_arg + + if isinstance(mutated_arg, (list, tuple)): + for a in mutated_arg: + storage_of_reinplaced_args.add(get_node_storage(a)) + else: + storage_of_reinplaced_args.add(get_node_storage(mutated_arg)) + else: + if should_attempt_reinplace: + missed_args.append(arg) + missed_nodes.append(mutated_arg) + + tensors_to_clone.append(arg) + + log_inplace_results( + node_name, + old_tensors_to_clone, + tensors_to_clone, + missed_args, + missed_nodes, + trigger, + ) + return tensors_to_clone + + for node in graph.nodes: + if (inplaceable_op := inplaceable_ops.get(node.target)) is not None: + # Check if ALL mutated args can be inplaced + # Only convert if we don't need to clone any tensor + mutated_args = [node.args[idx] for idx in inplaceable_op.mutated_args] + if all_can_inplace(node, mutated_args) and inplaceable_op.extra_check(node): + for mutated_arg in mutated_args: + copy_node = copy_node_for_reinplaced_arg(node, mutated_arg) + if copy_node is not None: + replace_dict[copy_node] = copy_node.args[0] + node.target = inplaceable_op.inplace_op + elif node.target is torch.ops.higher_order.auto_functionalized_v2: + _mutable_op = node.args[0] + kwargs = node.kwargs + + all_bases = kwargs["_all_bases"] + bases_to_clone = range(len(all_bases)) + base_tensors_dct = dict(enumerate(all_bases)) + new_bases_to_clone: list[int] = reinplace_and_refine_tensors_to_clone( + bases_to_clone, + base_tensors_dct, + _mutable_op._name, + ReInplaceTrigger.AUTO_FUNC_V2, + ) + # Stash the metadata. There is a pass later on where we decompose + # auto_functionalized into clones + a mutable op; this metadata + # tells the decomp to only clone the following inputs + node.meta["only_clone_these_tensors"] = new_bases_to_clone + elif node.target is torch.ops.higher_order.auto_functionalized: + _mutable_op = node.args[0] + from torch._higher_order_ops.auto_functionalize import get_mutable_args + + tensors_to_clone, _ = get_mutable_args(_mutable_op) + # Don't try to reinplace Tensor | None args that are None. + tensors_to_clone = [ + t for t in tensors_to_clone if node.kwargs[t] is not None + ] + tensors_to_clone = reinplace_and_refine_tensors_to_clone( + tensors_to_clone, + node.kwargs, + _mutable_op._name, + ReInplaceTrigger.AUTO_FUNC_V1, + ) + + # Stash the metadata. There is a pass later on where we decompose + # auto_functionalized into clones + a mutable op; this metadata + # tells the decomp to only clone the following inputs + node.meta["only_clone_these_tensors"] = tensors_to_clone + elif node.target is torch.ops.higher_order.with_effects: + # Handle effectful ops wrapped with with_effects + # args[0] is the token, args[1] is the inner op, args[2:] are the op's args + inner_op = node.args[1] + log.debug( + "reinplace: checking with_effects node with inner_op=%s", inner_op + ) + if (inplaceable_op := inplaceable_ops.get(inner_op)) is not None: + log.debug("reinplace: found inplaceable_op for %s", inner_op) + # Get the mutated arg indices, offset by 2 (token + op) + mutated_arg_indices = inplaceable_op.mutated_args + + # Build flat list of tensors for can_inplace check + # and a mapping of output index -> replacement tensor(s) + mutated_tensors_flat = [] + output_idx_to_replacement: dict[int, Any] = {} + + for position, idx in enumerate(mutated_arg_indices): + actual_idx = idx + 2 # offset for token and op + if actual_idx >= len(node.args): + raise AssertionError( + f"mutated arg idx {actual_idx} out of range {len(node.args)}" + ) + arg = node.args[actual_idx] + + # Output index is position + 1 (index 0 is the token) + output_idx = position + 1 + output_idx_to_replacement[output_idx] = arg + + # Flatten for can_inplace check + if isinstance(arg, (list, tuple)): + mutated_tensors_flat.extend(arg) + else: + mutated_tensors_flat.append(arg) + + # Check if all mutated args can be inplaced + can_inplace_all = all_can_inplace(node, mutated_tensors_flat) + + log.debug( + "reinplace with_effects: mutated_tensors=%s, can_inplace_all=%s", + [str(a) for a in mutated_tensors_flat], + can_inplace_all, + ) + + if can_inplace_all and inplaceable_op.extra_check(node): + log.debug( + "reinplace with_effects: converting %s -> %s", + inner_op, + inplaceable_op.inplace_op, + ) + # Update the inner op to inplace version + node.update_arg(1, inplaceable_op.inplace_op) + + # The output structure changes: functional returns (token, tensors), + # inplace returns (token, None). We need to redirect tensor uses + # to the input tensors. + + def get_index_from_node(n): + """Extract the index from a getitem node.""" + if n.target is operator.getitem: + return n.args[1] + return None + + def is_getitem_node(n, parent): + """Check if node n is a getitem indexing into parent.""" + return n.target is operator.getitem and n.args[0] is parent + + def replace_and_collect(current_node, replacement_tensors): + """ + Collect replacements for getitem nodes into replace_dict. + Nodes are added in child-first order so children are erased before parents. + """ + # Find all users that are getitem nodes indexing into current_node + getitem_users = [ + u + for u in current_node.users + if is_getitem_node(u, current_node) + ] + + if not getitem_users: + # Leaf node - add to replace_dict with actual replacement + if isinstance(replacement_tensors, (list, tuple)): + if len(replacement_tensors) == 1: + replace_dict[current_node] = replacement_tensors[0] + return True + else: + # Multiple tensors but no indexing - can't replace + return False + else: + replace_dict[current_node] = replacement_tensors + return True + + # Process children first (so they're added to replace_dict before parent) + all_children_replaced = True + first_replacement = None + for getitem_user in getitem_users: + idx = get_index_from_node(getitem_user) + if idx is None or not isinstance(idx, int): + all_children_replaced = False + continue + + if not isinstance(replacement_tensors, (list, tuple)): + all_children_replaced = False + continue + + if idx >= len(replacement_tensors): + all_children_replaced = False + continue + + if first_replacement is None: + first_replacement = replacement_tensors[idx] + + if not replace_and_collect( + getitem_user, replacement_tensors[idx] + ): + all_children_replaced = False + + # Add this node to replace_dict after children (even if it has non-getitem users) + # Non-getitem users will have their input replaced via replace_all_uses_with + if all_children_replaced and first_replacement is not None: + replace_dict[current_node] = first_replacement + + return all_children_replaced + + # Find getitem nodes that extract tensor results + # Use the output_idx_to_replacement mapping built above + for user in list(node.users): + if not is_getitem_node(user, node): + continue + idx = get_index_from_node(user) + if idx is None or idx not in output_idx_to_replacement: + continue + replacement = output_idx_to_replacement[idx] + replace_and_collect(user, replacement) + elif node.target in inplaceable_triton_ops: + kernel_idx = node.kwargs["kernel_idx"] + kernel = kernel_side_table.get_kernel(kernel_idx) + from triton.runtime.autotuner import Autotuner + from triton.runtime.jit import JITFunction + + if isinstance(kernel, JITFunction): + kernel_name = kernel.fn.__name__ + elif isinstance(kernel, Autotuner): + if config.is_fbcode(): + # Autotuner has different implementations for AMD and NV + if torch.version.hip is None: + kernel_name = kernel.base_fn.__name__ + else: + kernel_name = kernel.fn.__name__ + else: + kernel_name = kernel.base_fn.__name__ + else: + raise AssertionError("Unknown triton kernel type") + + # inplaceable_triton_ops take an additional argument called + # tensors_to_clone which contain a list of tensors to clone + # This pass iterates over them and sees which ones are safe + # to eliminate (i.e. no longer need the clones) + tensors_to_clone = reinplace_and_refine_tensors_to_clone( + node.kwargs["tensors_to_clone"], + node.kwargs["kwargs"], + kernel_name, + ReInplaceTrigger.TRITON_OPS, + ) + + kwargs = dict(node.kwargs) + kwargs["tensors_to_clone"] = tensors_to_clone + node.kwargs = immutable_dict(kwargs) + if "eager_input_vals" in node.meta: + # We changed the kwargs, so we need to update eager_input_vals + # to something sane. + args, kwargs = node.meta["eager_input_vals"] + new_kwargs = {**kwargs} + new_kwargs["tensors_to_clone"] = immutable_list(tensors_to_clone) + new_kwargs = immutable_dict(new_kwargs) + node.meta["eager_input_vals"] = (args, new_kwargs) + elif (inplaceable_op := inplaceable_foreach_ops.get(node.target)) is not None: + mutated_args = node.args[inplaceable_op.mutated_arg] + + if not all((arg, node) in copy_args_to_copy_nodes for arg in mutated_args): + continue + + if can_inplace(node, mutated_args): + for arg in mutated_args: + copy_node = copy_args_to_copy_nodes[(arg, node)] + replace_dict[copy_node] = copy_node.args[0] + + node.target = inplaceable_op.inplace_op + for node, replacement in replace_dict.items(): + while replacement in replace_dict: + replacement = replace_dict[replacement] + replace_dict[node] = replacement + + node.replace_all_uses_with(replacement) + graph.erase_node(node) + + +def reinplace_inplaceable_ops( + fake_tensor_updater: torch._inductor.fx_utils.FakeTensorUpdater, + graph: torch.fx.Graph, +) -> None: + with enable_python_dispatcher(): + canonicalize_view_scatter_ops(graph) + # canonicalize_view_scatter_ops adds new operations to the graph. + # We run fake_tensor_updater to update the alias information. + # Correct alias information is required for `reinplace_inplaceable_ops_core`. + fake_tensor_updater.incremental_update() + reinplace_inplaceable_ops_core(graph) + decompose_generalized_scatter(graph) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/replace_random.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/replace_random.py new file mode 100644 index 0000000000000000000000000000000000000000..da0918e6e499afd09dd6eaabe3f0d579265610fa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/replace_random.py @@ -0,0 +1,265 @@ +# mypy: allow-untyped-defs +import collections +import logging + +import torch +from torch.fx.experimental.symbolic_shapes import guard_or_false, statically_known_true +from torch.fx.passes.graph_transform_observer import GraphTransformObserver +from torch.fx.passes.shape_prop import _extract_tensor_metadata + +from .. import config, inductor_prims +from ..pattern_matcher import ( + CallFunctionVarArgs, + Match, + PatternMatcherPass, + register_graph_pattern, +) +from ..virtualized import V + + +log = logging.getLogger(__name__) +patterns = PatternMatcherPass(subsystem="joint_graph_passes") +aten = torch.ops.aten + + +def _shape_to_offset(shape, device: torch.device): + # Modified from torch/_prims/rng_prims.py:philox_rand_offset + nelem = 1 + for s in shape: + nelem *= s + + # Empty tensor: no random numbers are generated/consumed. + is_empty = nelem == 0 + if statically_known_true(is_empty) or guard_or_false(is_empty): + return 0 + + if device is None: + device = torch.device("cpu") + elif isinstance(device, str): + device = torch.device(device) + + if device.type != "cuda": + return 0 + + block_size = 256 + unroll = 4 + curand4_engine_calls = 4 + + device_property = torch.cuda.get_device_properties(device) + + blocks_per_sm = device_property.max_threads_per_multi_processor // block_size + max_grid = device_property.multi_processor_count * blocks_per_sm + grid_size = (nelem + block_size - 1) // block_size + grid_size = -torch.sym_min(-grid_size, -1) + grid_size = torch.sym_min(grid_size, max_grid) + + return ((nelem - 1) // (block_size * grid_size * unroll) + 1) * curand4_engine_calls + + +def replace_random_passes(gm: torch.fx.GraphModule): + """Modify the given FX graph to use backend-native random ops""" + if config.fallback_random: + return 0 + + count = patterns.apply(gm) + with GraphTransformObserver(gm, "fuse_seed_creation_pass", "joint_graph_passes"): + count += fuse_seed_creation_pass(gm.graph) + if config.align_random_eager: + with GraphTransformObserver(gm, "fuse_offset_creation_pass"): + count += fuse_offset_creation_pass(gm.graph) + + return count + + +def fuse_offset_creation_pass(graph: torch.fx.Graph) -> int: + """ + Here offset node means seed << 32 + offset, will unpacked in lowering.py:inductor_random() + Horizontally fuse all the seed generation on each device + a = inductor_prims.rand_eager_offset(offset, dev) + b = inductor_prims.rand_eager_offset(offset, dev) + Becomes: + offsets = inductor_prims.rand_eager_offsets([offset1, offset2...], dev) + a = torch.ops.aten.select.int(offsets, 0, 0) + b = torch.ops.aten.select.int(offsets, 0, 1) + We do this because seed creation is entirely launch overhead bound. + """ + device_offsets = collections.defaultdict(list) + for node in graph.nodes: + if CallFunctionVarArgs(inductor_prims.rand_eager_offset).match(node): + device_offsets[node.args[1]].append(node) + + if not device_offsets: + return 0 + + for device, offsets in device_offsets.items(): + with graph.inserting_before(offsets[0]): + offs = [n.args[0] for n in offsets] + combined = graph.call_function( + inductor_prims.rand_eager_offsets, (offs, device) + ) + combined.meta.update(offsets[0].meta) + with V.fake_mode: + combined.meta["val"] = torch.empty( + [len(offsets), 2], device=device, dtype=torch.int64 + ) + combined.meta["tensor_meta"] = _extract_tensor_metadata( + combined.meta["val"] + ) + + for idx, offset in enumerate(offsets): + with graph.inserting_before(offset): + new_state = graph.call_function( + torch.ops.aten.select.int, (combined, 0, idx) + ) + offset.replace_all_uses_with(new_state) + new_state.meta.update(offset.meta) + graph.erase_node(offset) + + return len(device_offsets) + + +def fuse_seed_creation_pass(graph: torch.fx.Graph): + """ + Horizontally fuse all the seed generation on each device + + a = inductor_seed(dev) + b = inductor_seed(dev) + + Becomes: + seeds = inductor_seeds(2, dev) + a = inductor_lookup_seed(seeds, 0) + b = inductor_lookup_seed(seeds, 1) + + We do this because seed creation is entirely launch overhead bound. + """ + device_seeds = collections.defaultdict(list) + for node in graph.nodes: + if CallFunctionVarArgs(inductor_prims.seed).match(node): + device_seeds[node.args[0]].append(node) + + if not device_seeds: + return 0 + + for device, seeds in device_seeds.items(): + with graph.inserting_before(seeds[0]): + combined = graph.call_function(inductor_prims.seeds, (len(seeds), device)) + combined.meta.update(seeds[0].meta) + with V.fake_mode: + combined.meta["val"] = torch.empty( + [len(seeds)], device=device, dtype=torch.int64 + ) + combined.meta["tensor_meta"] = _extract_tensor_metadata( + combined.meta["val"] + ) + + for idx, seed in enumerate(seeds): + with graph.inserting_before(seed): + new_seed = graph.call_function( + inductor_prims.lookup_seed, (combined, idx) + ) + seed.replace_all_uses_with(new_seed) + new_seed.meta.update(seed.meta) + graph.erase_node(seed) + + return len(device_seeds) + + +def default_kwargs(device): + return {} + + +def get_device(device): + if device is not None: + return device + return torch.empty([]).device # default device + + +# pyrefly: ignore [bad-argument-type] +@register_graph_pattern(CallFunctionVarArgs(aten.rand.default), pass_dict=patterns) +# pyrefly: ignore [bad-argument-type] +@register_graph_pattern(CallFunctionVarArgs(aten.rand.generator), pass_dict=patterns) +# pyrefly: ignore [bad-argument-type] +@register_graph_pattern(CallFunctionVarArgs(aten.randn.default), pass_dict=patterns) +# pyrefly: ignore [bad-argument-type] +@register_graph_pattern(CallFunctionVarArgs(aten.randn.generator), pass_dict=patterns) +def replace_random( + match: Match, + size, + *, + generator=None, + dtype=None, + device=None, + layout=None, + pin_memory=None, +): + if generator is not None: + return + if pin_memory: + return + + def replacement(size): + result = inductor_prims.random( + size, inductor_prims.seed(device), mode, **default_kwargs(device) + ) + if dtype is not None: + result = result.to(dtype) + return result + + mode = { + aten.rand: "rand", + aten.randn: "randn", + }[ + match.output_node().target.overloadpacket # type: ignore[union-attr] + ] # type: ignore[union-attr] + device = get_device(device) + replacement_fn = replacement + + if mode == "rand" and config.align_random_eager and device.type == "cuda": + # Only enable when align_random_eager is on. + def replacement_align(size): + offset = _shape_to_offset(size, device) + + align_dtype = dtype + if isinstance(align_dtype, (tuple, list)): + align_dtype = align_dtype[0] if len(align_dtype) else None + + result = inductor_prims.random( + size, + inductor_prims.rand_eager_offset(offset, device), + mode, + **default_kwargs(device), + align_dtype=align_dtype, + ) + if dtype is not None: + result = result.to(dtype) + return result + + replacement_fn = replacement_align + + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(replacement_fn, [size]) + + +# pyrefly: ignore [bad-argument-type] +@register_graph_pattern(CallFunctionVarArgs(aten.randint.low), pass_dict=patterns) +def replace_randint( + match: Match, + low, + high, + size, + *, + dtype=torch.int64, + device=None, + layout=None, + pin_memory=None, +): + if pin_memory: + return + + def replacement(low, high, size): + result = inductor_prims.randint(low, high, size, inductor_prims.seed(device)) + return result.to(dtype) + + device = get_device(device) + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(replacement, [low, high, size]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9def81e25d69f0595c37de9b05509c4c441cc76 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_1.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_1.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d23d9fd1710493a76c61ce9e7bddd21866c21aa9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_1.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_10.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_10.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06928dbb770273f7160379cd3f97b8f0c9a295d3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_10.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_11.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_11.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..189830ee1a7dd1df78a55c0962c70659c04177e3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_11.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_12.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_12.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98cbaf72a6fa35f819b22f01df5dcbc52f194da2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_12.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_13.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_13.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ee00525cea3da865ce99a3a52135f181095a7ab Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_13.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_14.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_14.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2879a5c1e9fee46767dd8c0c57bdcbb5d4fa46e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_14.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_15.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_15.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4ac9d83c9ad088cc2e90b4d0604de4076b192d6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_15.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_16.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_16.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a62f0bea3542d1d402387a60972edd5433f3e8bd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_16.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_17.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_17.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5be279af60841a4857435fc5b80c6d03b4b01e9a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_17.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_18.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_18.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcb5f1e1ed451bb8467f72d19b0941940e658fcd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_18.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_19.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_19.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb03b2ad23695390703b74fe0b1e71d303fd28ce Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_19.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90bfbb5ed5d293d160204836af8ed418e982bf3e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_2.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_20.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_20.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c92d8b6e0ddc63365b67c5fdabe57227055eebfe Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_20.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_21.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_21.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9828635137478f39f9daf4a63b3f4efed6cf217 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_21.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_22.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_22.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..543f2eaff2b4e34238dedd41fdf64eeb72ec568b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_22.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_23.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_23.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a31dd30869824b86c538ed428a4f3dc9a5d18a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_23.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_24.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_24.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ae441227f35684fef13030532721871a5f0ff76 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_24.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_25.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_25.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..462643c043680fb6c42d327e6895b57d0751f0b8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_25.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_26.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_26.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e006f9def745b5aa3615c2a15ce10fca58f5de17 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_26.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_27.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_27.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e21e1526afc9dcf0e73697b9b45e697d93a4e0f8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_27.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_28.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_28.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..850c7898c44981b5e77f065cd375836005ec9d79 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_28.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_29.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_29.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e9d3bd4fec169f147c95450ca3be824bf4166a3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_29.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_3.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ae33eb881dab9ad7d961d12bfcd494a02da1fca Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_3.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_30.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_30.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90a915f5db8a6b001c9abd8ec09686ac4004b022 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_30.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_4.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_4.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57eaf59acfd3fee8d10de4b5736353bd82eddc95 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_4.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_5.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_5.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8a8993d7c8070c9781ae7de73d72f89a423655f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_5.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_6.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_6.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..364568d6b7445c4ad08a00363c56dd1e0dc3f971 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_6.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_7.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_7.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff425e0695546a5dbf6a731e0f66a0f578e95175 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_7.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_8.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_8.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1b1493507065af748b1b500296577e629e6cf9f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_8.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_9.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_9.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d66d786758324adcaa81df864c667cc6a44d8b5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_9.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/addmm_pattern.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/addmm_pattern.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8d5bb45f0909470895c6950df8271cba83bb3bc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/addmm_pattern.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/bmm_pattern.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/bmm_pattern.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d5478f2b8f4572058052a2828a87e713325b463 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/bmm_pattern.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/mm_pattern.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/mm_pattern.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d29054592e9411cd8d944fbc1edef027404cbc91 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/__pycache__/mm_pattern.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_1.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_1.py new file mode 100644 index 0000000000000000000000000000000000000000..a5a5b8862e9e92b22067c5a96337873da37f032e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_1.py @@ -0,0 +1,172 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_1_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_4, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_1_half_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_1_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_10.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_10.py new file mode 100644 index 0000000000000000000000000000000000000000..56d97bc75b18c3db7d01a5e7367785c454394601 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_10.py @@ -0,0 +1,207 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, div_Tensor, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, permute_default_3, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_2, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, view_default_9, KeywordArg('inv_scale')) +permute_default_6 = CallFunction(aten.permute.default, div_Tensor_2, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_11, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, convert_element_type_default_3, Ignored()) +_sfdp_pattern_10_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, div_Tensor, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, permute_default_3, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_10_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, div_Tensor, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_2, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +view_default_8 = CallFunction(aten.view.default, convert_element_type_default_3, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, view_default_9, KeywordArg('inv_scale')) +permute_default_6 = CallFunction(aten.permute.default, div_Tensor_2, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_10_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, div_Tensor, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_10_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_11.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_11.py new file mode 100644 index 0000000000000000000000000000000000000000..31f4b5fbed4939015bea0858ac890d8edc3979fd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_11.py @@ -0,0 +1,202 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_11_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_11_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_4, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_11_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_11_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_12.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_12.py new file mode 100644 index 0000000000000000000000000000000000000000..e81c91639bb55facca89fdca1bb125bd1d68a557 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_12.py @@ -0,0 +1,218 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale_factor'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale_factor')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_12_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale_factor'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_12_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale_factor')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_5, KeywordArg('inv_scale_factor')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_12_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale_factor')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_12_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_13.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_13.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb649db31aa8f2624ddaa39e6799ae9edffc969 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_13.py @@ -0,0 +1,51 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +bmm_default = CallFunction(aten.bmm.default, KeywordArg('query'), permute_default, _users=2) +amax_default = CallFunction(aten.amax.default, bmm_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, bmm_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +_sfdp_pattern_13_inference = CallFunction(aten.bmm.default, div_Tensor, KeywordArg('value'), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +bmm_default = CallFunction(aten.bmm.default, KeywordArg('query'), permute_default) +convert_element_type_default = CallFunction(prims.convert_element_type.default, bmm_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +_sfdp_pattern_13_half_inference = CallFunction(aten.bmm.default, convert_element_type_default_1, KeywordArg('value'), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_14.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_14.py new file mode 100644 index 0000000000000000000000000000000000000000..97e1eec4385f843a36568b126ac349646fc2ec86 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_14.py @@ -0,0 +1,208 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_14_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_14_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_4, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_14_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_14_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_15.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_15.py new file mode 100644 index 0000000000000000000000000000000000000000..0d7b1c259d47a1e3a46ba97809f3688d9a39ff9c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_15.py @@ -0,0 +1,95 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored()) +view_default = CallFunction(aten.view.default, eq_Scalar, Ignored()) +expand_default = CallFunction(aten.expand.default, view_default, Ignored()) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format) +view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2) +view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_3, KeywordArg('inv_scale')) +where_self = CallFunction(aten.where.self, expand_default, full_default, div_Tensor, _users=2) +amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_3 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format) +view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5) +_sfdp_pattern_15_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored()) +view_default = CallFunction(aten.view.default, eq_Scalar, Ignored()) +expand_default = CallFunction(aten.expand.default, view_default, Ignored()) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format) +view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2) +view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_3, KeywordArg('inv_scale')) +where_self = CallFunction(aten.where.self, expand_default, full_default, div_Tensor) +convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format) +view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5) +_sfdp_pattern_15_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_16.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_16.py new file mode 100644 index 0000000000000000000000000000000000000000..f2263219d1fcd775a6355d309a761390984287c1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_16.py @@ -0,0 +1,597 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_16_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_16_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_16_bs1_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_16_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_5, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_16_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_16_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_5, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_16_half_bs1_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_16_half_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, convert_element_type_default_1, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_3, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_16_half_mask_fp32_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_16_half_mask_fp32_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, convert_element_type_default_1, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_3, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_16_half_mask_fp32_bs1_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_16_half_mask_fp32_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_17.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_17.py new file mode 100644 index 0000000000000000000000000000000000000000..53cb451a913714aa044308048c6968632855c3b1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_17.py @@ -0,0 +1,95 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored()) +view_default = CallFunction(aten.view.default, eq_Scalar, Ignored()) +expand_default = CallFunction(aten.expand.default, view_default, Ignored()) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format) +view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2) +view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_3, KeywordArg('inv_scale')) +where_self = CallFunction(aten.where.self, expand_default, full_default, div_Tensor, _users=2) +amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_3 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format) +view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5) +_sfdp_pattern_17_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored()) +view_default = CallFunction(aten.view.default, eq_Scalar, Ignored()) +expand_default = CallFunction(aten.expand.default, view_default, Ignored()) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format) +view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2) +view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_3, KeywordArg('inv_scale')) +where_self = CallFunction(aten.where.self, expand_default, full_default, div_Tensor) +convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format) +view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5) +_sfdp_pattern_17_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_18.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_18.py new file mode 100644 index 0000000000000000000000000000000000000000..43cd1f943a05cb53d583938edc62d7690ac10559 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_18.py @@ -0,0 +1,163 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +full_default = CallFunction(aten.full.default, [], KeywordArg('inv_scale'), dtype=Ignored(), device=Ignored(), pin_memory=False) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default) +full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1, _users=2) +amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_18_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +full_default = CallFunction(aten.full.default, [], KeywordArg('inv_scale'), dtype=Ignored(), device=Ignored(), pin_memory=False) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default) +full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1, _users=2) +amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_18_bs1_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +full_default = CallFunction(aten.full.default, [], KeywordArg('inv_scale'), dtype=Ignored(), device=Ignored(), pin_memory=False) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default) +full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1) +convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_18_half_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +full_default = CallFunction(aten.full.default, [], KeywordArg('inv_scale'), dtype=Ignored(), device=Ignored(), pin_memory=False) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default) +full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1) +convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_18_half_bs1_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_19.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_19.py new file mode 100644 index 0000000000000000000000000000000000000000..f94d1564e71d0bd19305db05625860c296283ac9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_19.py @@ -0,0 +1,80 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +full_default = CallFunction(aten.full.default, [], KeywordArg('inv_scale'), dtype=Ignored(), device=Ignored(), pin_memory=False) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default) +full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1) +add_Tensor = CallFunction(aten.add.Tensor, where_self, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_19_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +full_default = CallFunction(aten.full.default, [], KeywordArg('inv_scale'), dtype=Ignored(), device=Ignored(), pin_memory=False) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default) +full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1) +add_Tensor = CallFunction(aten.add.Tensor, where_self, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_19_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_2.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_2.py new file mode 100644 index 0000000000000000000000000000000000000000..63f29082a2597da31bc0e638e4ebedabaee440ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_2.py @@ -0,0 +1,172 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor'), _users=2) +amax_default = CallFunction(aten.amax.default, mul_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, mul_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, view_default_7, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_1, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_1) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, fma_default, KeywordArg('scale_factor')) +view_default_8 = CallFunction(aten.view.default, mul_Tensor_2, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_2_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor'), _users=2) +amax_default = CallFunction(aten.amax.default, mul_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, mul_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_2_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_1, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_1) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, KeywordArg('scale_factor')) +view_default_8 = CallFunction(aten.view.default, mul_Tensor_2, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_2_half_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_2_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_20.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_20.py new file mode 100644 index 0000000000000000000000000000000000000000..dabba66907dfda32a06fce6e8341a219f6349ed0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_20.py @@ -0,0 +1,95 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored()) +view_default = CallFunction(aten.view.default, eq_Scalar, Ignored()) +expand_default = CallFunction(aten.expand.default, view_default, Ignored()) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, permute_default, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format) +view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2) +view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored()) +where_self = CallFunction(aten.where.self, expand_default, full_default, view_default_3, _users=2) +amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_3 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format) +view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5) +_sfdp_pattern_20_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored()) +view_default = CallFunction(aten.view.default, eq_Scalar, Ignored()) +expand_default = CallFunction(aten.expand.default, view_default, Ignored()) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, permute_default, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format) +view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2) +view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored()) +where_self = CallFunction(aten.where.self, expand_default, full_default, view_default_3) +convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format) +view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5) +_sfdp_pattern_20_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_21.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_21.py new file mode 100644 index 0000000000000000000000000000000000000000..856c7329cb309228e4ea5ae0fdfc8edc8b71e154 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_21.py @@ -0,0 +1,137 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_21_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_21_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, convert_element_type_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default_1, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default_1, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_2, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_21_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, convert_element_type_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default_1, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default_1, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_2, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_21_half_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_22.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_22.py new file mode 100644 index 0000000000000000000000000000000000000000..2be907157a92a01aafe01a6b2bcd3a88181d5528 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_22.py @@ -0,0 +1,153 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_22_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_22_bs1_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, convert_element_type_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default_1, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default_1, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_2, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_22_half_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, convert_element_type_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default_1, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default_1, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_2, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_22_half_bs1_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_23.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_23.py new file mode 100644 index 0000000000000000000000000000000000000000..688ffffb6d188775a54da32ffd76742752a19a53 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_23.py @@ -0,0 +1,151 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_23_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_23_bs1_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, convert_element_type_default, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_3, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_23_half_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, convert_element_type_default, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_3, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_23_half_bs1_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_24.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_24.py new file mode 100644 index 0000000000000000000000000000000000000000..26eecb958133597e78b4ec703cd995f3bb3ae08c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_24.py @@ -0,0 +1,64 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +view_default = CallFunction(aten.view.default, KeywordArg('query'), Ignored()) +view_default_1 = CallFunction(aten.view.default, KeywordArg('key'), Ignored()) +permute_default = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, permute_default) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attention_mask')) +view_default_3 = CallFunction(aten.view.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, view_default_3, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_3, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +view_default_4 = CallFunction(aten.view.default, KeywordArg('value'), Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, div_Tensor, view_default_4) +_sfdp_pattern_24_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +view_default = CallFunction(aten.view.default, KeywordArg('query'), Ignored()) +view_default_1 = CallFunction(aten.view.default, KeywordArg('key'), Ignored()) +permute_default = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, permute_default) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attention_mask')) +view_default_3 = CallFunction(aten.view.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, view_default_3, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_3, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +view_default_4 = CallFunction(aten.view.default, KeywordArg('value'), Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, convert_element_type_default, view_default_4) +_sfdp_pattern_24_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_25.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_25.py new file mode 100644 index 0000000000000000000000000000000000000000..166a5983310a1ef68d65ecb08664ae09876476d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_25.py @@ -0,0 +1,389 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_25_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_25_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_25_bs1_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_25_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +view_default_8 = CallFunction(aten.view.default, convert_element_type_default_4, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_25_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_25_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +view_default_8 = CallFunction(aten.view.default, convert_element_type_default_4, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_25_half_bs1_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_25_half_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_26.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_26.py new file mode 100644 index 0000000000000000000000000000000000000000..0b8edc5d0597c587ec0f923642f275cbccd4dea8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_26.py @@ -0,0 +1,413 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_26_training = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_26_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_26_bs1_training = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_26_bs1_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +view_default_8 = CallFunction(aten.view.default, convert_element_type_default_4, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_26_half_training = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_26_half_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +view_default_8 = CallFunction(aten.view.default, convert_element_type_default_4, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_26_half_bs1_training = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_26_half_bs1_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_27.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_27.py new file mode 100644 index 0000000000000000000000000000000000000000..e47b985a3dd511657f490f0cc7cacd9ca84f8d2b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_27.py @@ -0,0 +1,401 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_27_training = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_27_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_27_bs1_training = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_27_bs1_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +view_default_8 = CallFunction(aten.view.default, convert_element_type_default_4, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_27_half_training = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_27_half_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +view_default_8 = CallFunction(aten.view.default, convert_element_type_default_4, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_27_half_bs1_training = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +_sfdp_pattern_27_half_bs1_inference = MultiOutputPattern([view_default_5, + permute_default_1, + permute_default_3 +]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_28.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_28.py new file mode 100644 index 0000000000000000000000000000000000000000..d4b977c25eb83ff744b5b4fb96ef88db537166b0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_28.py @@ -0,0 +1,200 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor'), _users=2) +amax_default = CallFunction(aten.amax.default, mul_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, mul_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, mul_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_2, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_3) +mul_Tensor_5 = CallFunction(aten.mul.Tensor, mul_Tensor_4, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_5, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_5) +mul_Tensor_6 = CallFunction(aten.mul.Tensor, fma_default, KeywordArg('scale_factor')) +view_default_8 = CallFunction(aten.view.default, mul_Tensor_6, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_28_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor'), _users=2) +amax_default = CallFunction(aten.amax.default, mul_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, mul_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_28_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, mul_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_2, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_3) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_4, Ignored()) +mul_Tensor_5 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_5, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_5) +convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +mul_Tensor_6 = CallFunction(aten.mul.Tensor, convert_element_type_default_5, KeywordArg('scale_factor')) +view_default_8 = CallFunction(aten.view.default, mul_Tensor_6, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_28_half_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_28_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_29.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_29.py new file mode 100644 index 0000000000000000000000000000000000000000..b8c1d5dae3b749c576daf3f09410008e09c908fe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_29.py @@ -0,0 +1,435 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=3) +eq_Scalar = CallFunction(aten.eq.Scalar, add_Tensor, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, div_Tensor, _users=3) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, where_self) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, where_self, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +mul_Scalar_2 = CallFunction(aten.mul.Scalar, view_default_9, KeywordArg('inv_scale')) +permute_default_6 = CallFunction(aten.permute.default, mul_Scalar_2, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +mul_Scalar_3 = CallFunction(aten.mul.Scalar, view_default_10, KeywordArg('inv_scale')) +permute_default_8 = CallFunction(aten.permute.default, mul_Scalar_3, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_29_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=3) +eq_Scalar = CallFunction(aten.eq.Scalar, add_Tensor, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, div_Tensor) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_29_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=3) +eq_Scalar = CallFunction(aten.eq.Scalar, add_Tensor, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, div_Tensor, _users=3) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, where_self) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, where_self, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +mul_Scalar_2 = CallFunction(aten.mul.Scalar, view_default_9, KeywordArg('inv_scale')) +permute_default_6 = CallFunction(aten.permute.default, mul_Scalar_2, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +mul_Scalar_3 = CallFunction(aten.mul.Scalar, view_default_10, KeywordArg('inv_scale')) +permute_default_8 = CallFunction(aten.permute.default, mul_Scalar_3, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_29_bs1_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=3) +eq_Scalar = CallFunction(aten.eq.Scalar, add_Tensor, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, div_Tensor) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_29_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +eq_Scalar = CallFunction(aten.eq.Scalar, add_Tensor, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, convert_element_type_default_1, _users=2) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +view_default_8 = CallFunction(aten.view.default, convert_element_type_default_4, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +mul_Scalar_2 = CallFunction(aten.mul.Scalar, view_default_9, KeywordArg('inv_scale')) +permute_default_6 = CallFunction(aten.permute.default, mul_Scalar_2, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +mul_Scalar_3 = CallFunction(aten.mul.Scalar, view_default_10, KeywordArg('inv_scale')) +permute_default_8 = CallFunction(aten.permute.default, mul_Scalar_3, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_29_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +eq_Scalar = CallFunction(aten.eq.Scalar, add_Tensor, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, convert_element_type_default_1) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_29_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +eq_Scalar = CallFunction(aten.eq.Scalar, add_Tensor, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, convert_element_type_default_1, _users=2) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +view_default_8 = CallFunction(aten.view.default, convert_element_type_default_4, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +mul_Scalar_2 = CallFunction(aten.mul.Scalar, view_default_9, KeywordArg('inv_scale')) +permute_default_6 = CallFunction(aten.permute.default, mul_Scalar_2, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +mul_Scalar_3 = CallFunction(aten.mul.Scalar, view_default_10, KeywordArg('inv_scale')) +permute_default_8 = CallFunction(aten.permute.default, mul_Scalar_3, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_29_half_bs1_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +add_Tensor = CallFunction(aten.add.Tensor, view_default_2, KeywordArg('attn_mask'), _users=2) +eq_Scalar = CallFunction(aten.eq.Scalar, add_Tensor, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, convert_element_type_default_1) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_29_half_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_3.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_3.py new file mode 100644 index 0000000000000000000000000000000000000000..2e3de4c73f04249f9d3893d4778c893cf6b6d34e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_3.py @@ -0,0 +1,188 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale_factor'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale_factor')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_3_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale_factor'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_3_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale_factor')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_5, KeywordArg('inv_scale_factor')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_3_half_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale_factor')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_3_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_30.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_30.py new file mode 100644 index 0000000000000000000000000000000000000000..44231e23033c7c8954b9a3586e65e481392c744f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_30.py @@ -0,0 +1,423 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=3) +eq_Scalar = CallFunction(aten.eq.Scalar, view_default_2, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, div_Tensor, _users=3) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, where_self) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, where_self, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +mul_Scalar_2 = CallFunction(aten.mul.Scalar, view_default_9, KeywordArg('inv_scale')) +permute_default_6 = CallFunction(aten.permute.default, mul_Scalar_2, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +mul_Scalar_3 = CallFunction(aten.mul.Scalar, view_default_10, KeywordArg('inv_scale')) +permute_default_8 = CallFunction(aten.permute.default, mul_Scalar_3, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_30_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=3) +eq_Scalar = CallFunction(aten.eq.Scalar, view_default_2, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, div_Tensor) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_30_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=3) +eq_Scalar = CallFunction(aten.eq.Scalar, view_default_2, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, div_Tensor, _users=3) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, where_self) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, where_self, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +mul_Scalar_2 = CallFunction(aten.mul.Scalar, view_default_9, KeywordArg('inv_scale')) +permute_default_6 = CallFunction(aten.permute.default, mul_Scalar_2, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +mul_Scalar_3 = CallFunction(aten.mul.Scalar, view_default_10, KeywordArg('inv_scale')) +permute_default_8 = CallFunction(aten.permute.default, mul_Scalar_3, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_30_bs1_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=3) +eq_Scalar = CallFunction(aten.eq.Scalar, view_default_2, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, div_Tensor) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_30_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +eq_Scalar = CallFunction(aten.eq.Scalar, view_default_2, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, convert_element_type_default_1, _users=2) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +view_default_8 = CallFunction(aten.view.default, convert_element_type_default_4, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +mul_Scalar_2 = CallFunction(aten.mul.Scalar, view_default_9, KeywordArg('inv_scale')) +permute_default_6 = CallFunction(aten.permute.default, mul_Scalar_2, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +mul_Scalar_3 = CallFunction(aten.mul.Scalar, view_default_10, KeywordArg('inv_scale')) +permute_default_8 = CallFunction(aten.permute.default, mul_Scalar_3, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_30_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +eq_Scalar = CallFunction(aten.eq.Scalar, view_default_2, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, convert_element_type_default_1) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_30_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +eq_Scalar = CallFunction(aten.eq.Scalar, view_default_2, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, convert_element_type_default_1, _users=2) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +view_default_8 = CallFunction(aten.view.default, convert_element_type_default_4, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +mul_Scalar_2 = CallFunction(aten.mul.Scalar, view_default_9, KeywordArg('inv_scale')) +permute_default_6 = CallFunction(aten.permute.default, mul_Scalar_2, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +mul_Scalar_3 = CallFunction(aten.mul.Scalar, view_default_10, KeywordArg('inv_scale')) +permute_default_8 = CallFunction(aten.permute.default, mul_Scalar_3, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_30_half_bs1_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +mul_Scalar = CallFunction(aten.mul.Scalar, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, mul_Scalar, Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, permute_default_2, KeywordArg('inv_scale')) +expand_default_1 = CallFunction(aten.expand.default, mul_Scalar_1, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +eq_Scalar = CallFunction(aten.eq.Scalar, view_default_2, Ignored()) +logical_not_default = CallFunction(aten.logical_not.default, eq_Scalar) +any_dim = CallFunction(aten.any.dim, logical_not_default, Ignored(), True) +logical_not_default_1 = CallFunction(aten.logical_not.default, any_dim) +full_default = CallFunction(aten.full.default, Ignored(), Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored(), pin_memory=False) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +where_self = CallFunction(aten.where.self, logical_not_default_1, full_default, convert_element_type_default_1) +expand_default_2 = CallFunction(aten.expand.default, where_self, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_30_half_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_4.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_4.py new file mode 100644 index 0000000000000000000000000000000000000000..1476a1bf26ff501bffc059a501dc5db6a90604ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_4.py @@ -0,0 +1,188 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor'), _users=2) +amax_default = CallFunction(aten.amax.default, mul_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, mul_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, mul_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_2, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_3) +mul_Tensor_5 = CallFunction(aten.mul.Tensor, mul_Tensor_4, div_Tensor, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_5, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_5) +mul_Tensor_6 = CallFunction(aten.mul.Tensor, fma_default, KeywordArg('scale_factor')) +view_default_8 = CallFunction(aten.view.default, mul_Tensor_6, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_4_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor'), _users=2) +amax_default = CallFunction(aten.amax.default, mul_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, mul_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_4_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, mul_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_2, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_3) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_4, Ignored()) +mul_Tensor_5 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_5, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_5) +convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +mul_Tensor_6 = CallFunction(aten.mul.Tensor, convert_element_type_default_5, KeywordArg('scale_factor')) +view_default_8 = CallFunction(aten.view.default, mul_Tensor_6, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_4_half_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_4_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_5.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_5.py new file mode 100644 index 0000000000000000000000000000000000000000..62c2889ba95f6693954be4d0fdae9a7dc539973c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_5.py @@ -0,0 +1,178 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_5_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_5_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_4, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_5_half_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_5_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_6.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_6.py new file mode 100644 index 0000000000000000000000000000000000000000..b8580349b40a4e66321c16ba42b8f1af0e418467 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_6.py @@ -0,0 +1,194 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_6_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None, + None, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2) +amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_6_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored()) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_5, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +_sfdp_pattern_6_half_training = MultiOutputPattern([view_default_5, + view_default_9, + permute_default_4, + view_default_11, + None, + None, + None +]) + + +expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored()) +view_default = CallFunction(aten.view.default, expand_default, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_6_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_7.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_7.py new file mode 100644 index 0000000000000000000000000000000000000000..e69a8798e1b17fc777052e87549cf57bf6a5f57f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_7.py @@ -0,0 +1,223 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, permute_default_3, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, view_default_11, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, convert_element_type_default_4, Ignored()) +_sfdp_pattern_7_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, permute_default_3, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_7_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, mul_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_4, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_7_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_7_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_8.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_8.py new file mode 100644 index 0000000000000000000000000000000000000000..ab5d0676fb8a6f8f906482ba2deff6b2dbd00af1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_8.py @@ -0,0 +1,207 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, permute_default_3, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_2, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_11, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, convert_element_type_default_3, Ignored()) +_sfdp_pattern_8_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2) +amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, permute_default_3, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_8_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_2, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_3, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_8_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_8_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_9.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_9.py new file mode 100644 index 0000000000000000000000000000000000000000..426a921e33b1b62d1ad2ca9b376664c78ff03256 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_9.py @@ -0,0 +1,223 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, div_Tensor, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, permute_default_3, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, view_default_9, KeywordArg('inv_scale')) +permute_default_6 = CallFunction(aten.permute.default, div_Tensor_2, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, view_default_11, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, convert_element_type_default_4, Ignored()) +_sfdp_pattern_9_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, div_Tensor, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, permute_default_3, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_9_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, div_Tensor, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1) +mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored()) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, mul_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored()) +mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored()) +mul_Tensor_3 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, mul_Tensor_2) +mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +view_default_8 = CallFunction(aten.view.default, convert_element_type_default_4, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +div_Tensor_2 = CallFunction(aten.div.Tensor, view_default_9, KeywordArg('inv_scale')) +permute_default_6 = CallFunction(aten.permute.default, div_Tensor_2, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_9_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, permute_default, KeywordArg('inv_scale')) +expand_default = CallFunction(aten.expand.default, div_Tensor, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +_sfdp_pattern_9_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/addmm_pattern.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/addmm_pattern.py new file mode 100644 index 0000000000000000000000000000000000000000..4d11fee3090f9dfb92afd5b1b568b18f84f85d80 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/addmm_pattern.py @@ -0,0 +1,51 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +addmm_default = CallFunction(aten.addmm.default, KeywordArg('input'), KeywordArg('mat1'), KeywordArg('mat2'), beta=KeywordArg('beta'), alpha=KeywordArg('alpha')) +mul_Scalar = CallFunction(aten.mul.Scalar, KeywordArg('tangents_1'), KeywordArg('beta')) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, mul_Scalar, Ignored(), True) +view_default = CallFunction(aten.view.default, sum_dim_IntList, Ignored()) +permute_default = CallFunction(aten.permute.default, KeywordArg('mat2'), Ignored()) +mm_default = CallFunction(aten.mm.default, KeywordArg('tangents_1'), permute_default) +mul_Scalar_1 = CallFunction(aten.mul.Scalar, mm_default, KeywordArg('alpha')) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('mat1'), Ignored()) +mm_default_1 = CallFunction(aten.mm.default, permute_default_1, KeywordArg('tangents_1')) +mul_Scalar_2 = CallFunction(aten.mul.Scalar, mm_default_1, KeywordArg('alpha')) +addmm_pattern_training = MultiOutputPattern([addmm_default, + view_default, + mul_Scalar_1, + mul_Scalar_2, + None, + None +]) + + +addmm_pattern_inference = CallFunction(aten.addmm.default, KeywordArg('input'), KeywordArg('mat1'), KeywordArg('mat2'), beta=KeywordArg('beta'), alpha=KeywordArg('alpha'), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/bmm_pattern.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/bmm_pattern.py new file mode 100644 index 0000000000000000000000000000000000000000..b403ae09078ceb1368b86fefdabd82733925b89d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/bmm_pattern.py @@ -0,0 +1,43 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +bmm_default = CallFunction(aten.bmm.default, KeywordArg('mat1'), KeywordArg('mat2')) +permute_default = CallFunction(aten.permute.default, KeywordArg('mat2'), Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, KeywordArg('tangents_1'), permute_default) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('mat1'), Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, permute_default_1, KeywordArg('tangents_1')) +bmm_pattern_training = MultiOutputPattern([bmm_default, + bmm_default_1, + bmm_default_2 +]) + + +bmm_pattern_inference = CallFunction(aten.bmm.default, KeywordArg('mat1'), KeywordArg('mat2'), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/mm_pattern.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/mm_pattern.py new file mode 100644 index 0000000000000000000000000000000000000000..14f1dec1b6943574fdbc5964dff0d9ee3130e4c4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/serialized_patterns/mm_pattern.py @@ -0,0 +1,43 @@ +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor +import operator + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +mm_default = CallFunction(aten.mm.default, KeywordArg('mat1'), KeywordArg('mat2')) +permute_default = CallFunction(aten.permute.default, KeywordArg('mat2'), Ignored()) +mm_default_1 = CallFunction(aten.mm.default, KeywordArg('tangents_1'), permute_default) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('mat1'), Ignored()) +mm_default_2 = CallFunction(aten.mm.default, permute_default_1, KeywordArg('tangents_1')) +mm_pattern_training = MultiOutputPattern([mm_default, + mm_default_1, + mm_default_2 +]) + + +mm_pattern_inference = CallFunction(aten.mm.default, KeywordArg('mat1'), KeywordArg('mat2'), _users=0) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/split_cat.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/split_cat.py new file mode 100644 index 0000000000000000000000000000000000000000..1ac73fe32a23b78adf66fe2a136c33c48dbaa55f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/split_cat.py @@ -0,0 +1,3060 @@ +# mypy: allow-untyped-defs +import itertools +import logging +import operator +import os +from collections import defaultdict +from collections.abc import Callable, Sequence +from typing import Any, TypeAlias + +import torch +from torch._dynamo.utils import counters +from torch.fx.experimental.symbolic_shapes import free_symbols, guard_or_false +from torch.utils._ordered_set import OrderedSet + +from ..pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethodVarArgs, + FailedMatch, + get_arg_value, + Ignored, + KeywordArg, + ListOf, + Match, + MatchContext, + MULTIPLE, + PatternExpr, + PatternMatcherPass, + register_graph_pattern, + RepeatedExpr, +) +from .group_batch_fusion import is_node_meta_valid, POST_GRAD_FUSIONS, PRE_GRAD_FUSIONS + + +log = logging.getLogger(__name__) + +_Arguments: TypeAlias = tuple[torch.fx.node.Argument, ...] +_TransformParam: TypeAlias = tuple[ + _Arguments | None, + _Arguments | None, + _Arguments | None, + _Arguments | None, +] +_Range: TypeAlias = tuple[int, int] + + +PRE_GRAD_PATTERNS: dict[str, PatternMatcherPass] = {} +POST_GRAD_PATTERNS: dict[str, PatternMatcherPass] = {} + +pre_grad_pass_names = [ + "normalization_pass", + "remove_split_with_size_one_pass", + "merge_getitem_cat_pass", + "merge_stack_tahn_unbind_pass", + "merge_splits_pass", + "mutate_cat_pass", + "split_cat_pass", + "unbind_stack_pass", + "split_cat_to_slices_pass", + "unbind_cat_to_view_pass", + "split_stack_to_cats_pass", + "unbind_stack_to_slices_pass", + "move_reshape_out_of_split_stack_pass", + "einsum_to_pointwise_pass", +] + +post_grad_pass_names = [ + "normalization_aten_pass", + "decompose_mm_pass", + "unbind_stack_aten_pass", + "shape_padding_multiplier", + "pad_aten_mm_pass", + "split_cat_aten_pass", + "select_cat_aten_pass", + "move_view_after_cat_aten_pass", +] + +backend = os.environ.get("TORCHINDUCTOR_PATTERN_MATCH_BACKEND", "inductor") + +for pass_name in pre_grad_pass_names: + # exclude all passes from the group batch fusion + # they do not use pattern matcher + if pass_name in PRE_GRAD_FUSIONS: + continue + PRE_GRAD_PATTERNS[pass_name] = PatternMatcherPass( + pass_name=pass_name, + ) + +for pass_name in post_grad_pass_names: + # exclude all passes from the group batch fusion + # they do not use pattern matcher + if pass_name in POST_GRAD_FUSIONS: + continue + POST_GRAD_PATTERNS[pass_name] = PatternMatcherPass( + pass_name=pass_name, + ) + + +def construct_pattern_matcher_pass(pass_name: str): + """ + Return the specific pattern_matcher_pass given the pass name. + """ + if pass_name in PRE_GRAD_PATTERNS: + return PRE_GRAD_PATTERNS[pass_name] + else: + return POST_GRAD_PATTERNS[pass_name] + + +def _get_split_args_default(split_node): + input_kwarg = "tensor" + split_size_kwarg = "split_size_or_sections" + dim_kwarg = "dim" + default_dim_value = 0 + if split_node.op == "call_method": + split_size_kwarg = "split_size" + return ( + get_arg_value(split_node, 0, input_kwarg), + get_arg_value(split_node, 1, split_size_kwarg), + get_arg_value(split_node, 2, dim_kwarg) or default_dim_value, + ) + + +def _get_dim(node: Any): + if not isinstance(node, torch.fx.Node): + raise AssertionError(f"expected torch.fx.Node, got {type(node)}") + if "dim" in node.kwargs: + if not isinstance(node.kwargs["dim"], int): + raise AssertionError(f"expected int dim, got {node.kwargs['dim']}") + return node.kwargs["dim"] + if node.target is torch.unbind: + if len(node.args) == 2: + if not isinstance(node.args[-1], int): + raise AssertionError(f"expected int dim, got {node.args[-1]}") + return node.args[-1] + return 0 # defaults to dim=0 + if node.target is torch.split: + if len(node.args) == 3: + if not isinstance(node.args[-1], int): + raise AssertionError(f"expected int dim, got {node.args[-1]}") + return node.args[-1] + return 0 # defaults to dim=0 + raise AssertionError( + f"Can't extract `dim` from {node.target} {node.args} {node.kwargs}" + ) + + +# ############The pattern to be optimized is######### +# unbind (dim=0) +# / ... \ +# getitem getitem -> user=1 +# | | +# split split -> dim=1, user=1, split_section_size=1 +# | | +# getitem getitem -> user=1 +# \ / +# cat (dim=1) -> user=1 +# | + +# ################After transformation############# +# unbind (dim=0) +# / ... \ +# getitem getitem -> user=1 +# \ / +# cat (dim=1) -> user=1 +# | + + +def normalize_split_base( + match: Match, + _get_split_args: Callable[ + [torch.fx.Node], tuple[torch.fx.Node | None, Any | None, int | None] + ], +): + """ + Normalize split with split_size into split_with_sizes, so that we only deal with one type of split in + subsequent optimizations + """ + split_node = match.nodes[0] + graph = match.graph + split_input, split_size, split_dim = _get_split_args(split_node) + if split_input is None or split_dim is None or split_size is None: + log.debug("couldn't find split args") + return + if not is_node_meta_valid(split_node): + log.debug("example value absent for node: %s", split_node) + return + if not isinstance(split_node.meta["example_value"], (list, tuple)): + raise AssertionError( + f"expected list/tuple example_value, got {split_node.meta['example_value']}" + ) + split_sections = [t.size()[split_dim] for t in split_node.meta["example_value"]] + + if any(isinstance(section, torch.SymInt) for section in split_sections): + # TODO dynamic_shapes with assume_static_by_default=False fails while AOT Autograd tracing. + return + if split_dim < 0: # Normalize split dim + split_dim += split_input.meta["example_value"].dim() + + new_args = (split_input, split_sections) + new_kwargs = {"dim": split_dim} + if ( + split_node.args == new_args + and split_node.kwargs == new_kwargs + and split_node.op == "call_function" + ): + return + + with graph.inserting_after(split_node): + new_split_node = graph.call_function( + torch.split, + args=new_args, + kwargs=new_kwargs, # type: ignore[arg-type] + ) + split_node.replace_all_uses_with(new_split_node) + new_split_node.meta.update(split_node.meta) + graph.erase_node(split_node) + counters[backend]["normalization_pass"] += 1 + + +@register_graph_pattern( + CallFunctionVarArgs(torch.split, users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_pass"), +) +@register_graph_pattern( + CallMethodVarArgs("split", users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_pass"), +) +def normalize_split_default(match: Match, *args, **kwargs): + return normalize_split_base(match, _get_split_args_default) + + +@register_graph_pattern( + CallFunctionVarArgs(torch.split, users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("remove_split_with_size_one_pass"), +) +@register_graph_pattern( + CallMethodVarArgs("split", users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("remove_split_with_size_one_pass"), +) +def remove_split_with_size_one(match: Match, *args, **kwargs): + graph = match.graph + split_node = match.nodes[0] + split_input, split_size, split_dim = _get_split_args_default(split_node) + if split_input is None or split_dim is None or split_size is None: + log.debug("couldn't find split args") + return + if not is_node_meta_valid(split_node): + log.debug("example value absent for node: %s", split_node) + return + if not isinstance(split_node.meta["example_value"], (list, tuple)): + raise AssertionError( + f"expected list/tuple example_value, got {split_node.meta['example_value']}" + ) + split_sections = [t.size()[split_dim] for t in split_node.meta["example_value"]] + + if any(isinstance(section, torch.SymInt) for section in split_sections): + # TODO dynamic_shapes with assume_static_by_default=False fails while AOT Autograd tracing. + return + # remove the dummy split whose split sections size is one + # theoretically nodes with no users should be removed, but we have seen the corner case + # thus we add its users check to work around the StopIteration error. + if len(split_sections) == 1 and len(split_node.users.keys()) > 0: + # find the grand children of the split_node + next_users = find_next_users(split_node) + user = next(iter(split_node.users.keys())) + # replace the users of grand child node with the input node + for next_user in next_users: + next_user.replace_input_with(user, split_input) + # erase the split node and its child + graph.erase_node(user) + graph.erase_node(split_node) + counters[backend]["remove_split_with_size_one_pass"] += 1 + + +@register_graph_pattern( + CallFunctionVarArgs(torch.unbind, users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_pass"), +) +@register_graph_pattern( + CallMethodVarArgs("unbind", users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_pass"), +) +def normalize_unbind_default(match: Match, *args, **kwargs): + node = match.nodes[0] + graph = match.graph + input = get_arg_value(node, 0, "input") + dim = get_arg_value(node, 1, "dim") + if dim is None: + axis = node.kwargs.get("axis") + if axis is not None: + dim = axis + else: + dim = 0 + if input is None: + log.debug("couldn't find unbind args") + return + if not is_node_meta_valid(input): + log.debug("example value absent for node: %s", input) + return + ndim = input.meta["example_value"].ndim + + if dim < 0: # Normalize unbind dim + dim += ndim + with graph.inserting_after(node): + new_node = graph.call_function( + torch.unbind, + args=(input,), + kwargs={"dim": dim}, + ) + node.replace_all_uses_with(new_node) + new_node.meta.update(node.meta) + graph.erase_node(node) + counters[backend]["normalization_pass"] += 1 + + +@register_graph_pattern( + CallFunctionVarArgs([torch.cat, torch.concat], users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_pass"), +) +def normalize_cat_default(match: Match, *args, **kwargs): + cat_node = match.nodes[0] + graph = match.graph + tensors = get_arg_value(cat_node, 0, "tensors") + cat_dim = get_arg_value(cat_node, 1, "dim") + if cat_dim is None: + cat_axis = cat_node.kwargs.get("axis") + if cat_axis is not None: + cat_dim = cat_axis + else: + cat_dim = 0 + if tensors is None or cat_dim is None: + log.debug("couldn't find cat args") + return + if not isinstance(tensors, (list, tuple)): + raise AssertionError(f"expected list/tuple tensors, got {type(tensors)}") + for tensor in itertools.chain([cat_node], tensors): + if not is_node_meta_valid(tensor): + log.debug("example value absent for node: %s", tensor) + return + + ndim = cat_node.meta["example_value"].dim() + + def is_empty_tensor(x): + # special case where torch.cat supports cat'ing with an empty tensor + x_shape = x.meta["example_value"].shape + return len(x_shape) == 1 and guard_or_false(x_shape[0] == 0) + + if not all( + ndim == x.meta["example_value"].dim() or is_empty_tensor(x) for x in tensors + ): + raise AssertionError("expected all tensors to match ndim or be empty") + + if cat_dim < 0: # Normalize cat dim + cat_dim += ndim + + new_args = (tensors,) + new_kwargs = {"dim": cat_dim} + if ( + cat_node.args == new_args + and cat_node.kwargs == new_kwargs + and cat_node.op == "call_function" + and cat_node.target is torch.cat + ): + return + + with graph.inserting_after(cat_node): + new_cat_node = graph.call_function( + torch.cat, + args=new_args, + kwargs=new_kwargs, + ) + cat_node.replace_all_uses_with(new_cat_node) + new_cat_node.meta.update(cat_node.meta) + graph.erase_node(cat_node) + counters[backend]["normalization_pass"] += 1 + + +@register_graph_pattern( + CallFunctionVarArgs(torch.stack, users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_pass"), +) +def normalize_stack_default(match: Match, *args, **kwargs): + node = match.nodes[0] + graph = match.graph + tensors = get_arg_value(node, 0, "tensors") + dim = get_arg_value(node, 1, "dim") or 0 + if tensors is None or dim is None: + log.debug("couldn't find stack args") + return + if not isinstance(tensors, (list, tuple)): + raise AssertionError(f"expected list/tuple tensors, got {type(tensors)}") + + # A bug in pytorch, some nodes miss the example_value metadata + for tensor in itertools.chain([node], tensors): + if not is_node_meta_valid(tensor): + log.debug("example value absent for node: %s", tensor) + return + + ndim = node.meta["example_value"].dim() + if dim < 0: # Normalize dim + dim += ndim + + with graph.inserting_after(node): + new_node = graph.call_function( + node.target, # type: ignore[arg-type] + args=(tensors,), + kwargs={"dim": dim}, + ) + node.replace_all_uses_with(new_node) + new_node.meta.update(node.meta) + graph.erase_node(node) + counters[backend]["normalization_pass"] += 1 + + +def find_next_users(split_node: torch.fx.Node) -> list[torch.fx.Node]: + next_users = [] + for getitem_node in split_node.users: + for getitem_user in getitem_node.users: + if getitem_user not in next_users: + next_users.append(getitem_user) + return next_users + + +@register_graph_pattern( + CallMethodVarArgs("squeeze", users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_pass"), +) +def normalize_squeeze_default(match: Match, *args, **kwargs): + squeeze_node = match.nodes[0] + squeeze_input = get_arg_value(squeeze_node, 0) + + if "dim" in squeeze_node.kwargs: + if len(squeeze_node.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(squeeze_node.args)}") + dim = squeeze_node.kwargs["dim"] + elif len(squeeze_node.args) == 1: + # squeeze(Tensor) + dim = None + elif len(squeeze_node.args) == 2: + # squeeze(Tensor self, int dim) + # squeeze(Tensor self, int[] dim) + dim = squeeze_node.args[1] + else: + # squeeze(Tensor self, int[] dim) (called with varargs) + dim = squeeze_node.args[1:] + + if isinstance(dim, Sequence) and len(dim) == 1: + dim = dim[0] + + with match.graph.inserting_after(squeeze_node): + if dim is None: + new_squeeze_node = match.graph.call_function( + torch.squeeze, args=(squeeze_input,) + ) + else: + new_squeeze_node = match.graph.call_function( + torch.squeeze, args=(squeeze_input,), kwargs={"dim": dim} + ) + squeeze_node.replace_all_uses_with(new_squeeze_node) + new_squeeze_node.meta.update(squeeze_node.meta) + match.graph.erase_node(squeeze_node) + + +@register_graph_pattern( + CallMethodVarArgs("reshape", users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_pass"), +) +def normalize_reshape_default(match: Match, *args, **kwargs): + reshape_node = match.nodes[0] + if not is_node_meta_valid(reshape_node): + log.debug("example value absent for node: %s", reshape_node) + return + reshape_input = get_arg_value(reshape_node, 0) + + if free_symbols(reshape_node.meta["example_value"].shape): + log.debug("dynamic shape not supported: %s", reshape_node) + return + + with match.graph.inserting_after(reshape_node): + new_reshape_node = match.graph.call_function( + torch.reshape, + args=(reshape_input, tuple(reshape_node.meta["example_value"].shape)), + ) + reshape_node.replace_all_uses_with(new_reshape_node) + new_reshape_node.meta.update(reshape_node.meta) + match.graph.erase_node(reshape_node) + + +@register_graph_pattern( + CallMethodVarArgs("clamp", users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_pass"), +) +@register_graph_pattern( + CallFunctionVarArgs(torch.clamp, users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_pass"), +) +def normalize_clamp_default(match: Match, *args, **kwargs): + clamp_node = match.nodes[0] + if not is_node_meta_valid(clamp_node): + log.debug("example value absent for node: %s", clamp_node) + return + + if free_symbols(clamp_node.meta["example_value"].shape): + log.debug("dynamic shape not supported: %s", clamp_node) + return + if len(clamp_node.args) > 1: + args = (get_arg_value(clamp_node, 0),) + kwargs = { + "min": get_arg_value(clamp_node, 1, kwarg_name="min"), + "max": get_arg_value(clamp_node, 2, kwarg_name="max"), + } + else: + args = clamp_node.args + kwargs = clamp_node.kwargs + with match.graph.inserting_after(clamp_node): + new_clamp_node = match.graph.call_function( + torch.clamp, + args=args, + kwargs=kwargs, + ) + clamp_node.replace_all_uses_with(new_clamp_node) + new_clamp_node.meta.update(clamp_node.meta) + match.graph.erase_node(clamp_node) + + +@register_graph_pattern( + CallMethodVarArgs("detach", users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_pass"), +) +def normalize_detach_default(match: Match, *args, **kwargs): + detach_node = match.nodes[0] + if not is_node_meta_valid(detach_node): + log.debug("example value absent for node: %s", detach_node) + return + + if free_symbols(detach_node.meta["example_value"].shape): + log.debug("dynamic shape not supported: %s", detach_node) + return + + with match.graph.inserting_after(detach_node): + new_detach_node = match.graph.call_function( + torch.detach, + args=detach_node.args, + ) + detach_node.replace_all_uses_with(new_detach_node) + new_detach_node.meta.update(detach_node.meta) + match.graph.erase_node(detach_node) + + +class TorchSplit(CallFunction): + """ + Matches a call to torch.split if it is in a normalized form. Ensures that all users of + splits are unique getitems. + """ + + def __init__(self, arg, sizes, func=torch.split) -> None: + # using KeywordArg("dim") for `dim` checks they all match + super().__init__(func, arg, sizes, _users=MULTIPLE, dim=KeywordArg("dim")) + + def _match(self, node: torch.fx.Node, ctx: MatchContext): + m = super()._match(node, ctx) + if not m: + return m + split_sections = node.args[1] + if not isinstance(split_sections, (list, tuple)): + return FailedMatch("split not normalized") + # check users are all unique getitems + seen_idxs = OrderedSet[int]() + for user in node.users: + if not CallFunction(operator.getitem, Arg(), Arg()).match(user): + # This should ideally never happen. Split user should always be a getitem + return FailedMatch(f"user of split not a getitem: {user}") + if not isinstance(user.args[1], int): + return FailedMatch("only integer getitems are handled") + if user.args[1] in seen_idxs: + return FailedMatch(f"duplicate getitem {user.args[1]}") + if user.args[-1] < 0: # type: ignore[operator] + # This shouldn't ideally happen as dynamo normalizes indexes to positive + return FailedMatch("negative index") + seen_idxs.add(user.args[1]) + return m + + +@register_graph_pattern( + TorchSplit( + CallFunction( + operator.getitem, + TorchSplit( + KeywordArg("first_split_input"), + KeywordArg("first_split_sections"), + ), + Ignored(), + ), + KeywordArg("next_split_sections"), + ), + pass_dict=construct_pattern_matcher_pass("merge_splits_pass"), +) +def merge_splits( + match: Match, + first_split_input: torch.fx.Node, + first_split_sections: list[int], + next_split_sections: list[int], + # Note: dim is implicitly passed by TorchSplit, as it internally uses a pattern with dim + dim: int, +): + node = match.output_node() + # it is possible that the split has no users, + # we check the corner case and skip the pattern + if len(node.users.keys()) == 0: + return + graph = match.graph + first_split = node.args[0].args[0] # type: ignore[union-attr] + next_split_index = node.args[0].args[1] # type: ignore[union-attr] + + new_split_sections = list(first_split_sections) + new_split_sections[next_split_index : next_split_index + 1] = next_split_sections # type: ignore[operator, misc] + + first_split_dim = _get_dim(first_split) + + to_remove = [] + + with graph.inserting_before(first_split): # type: ignore[arg-type] + # Add the new split node + new_split = graph.call_function( + torch.split, + args=(first_split_input, new_split_sections), + kwargs={"dim": first_split_dim}, + ) + if is_node_meta_valid(first_split_input): + new_split.meta["example_value"] = torch.split( + first_split_input.meta["example_value"], + new_split_sections, + dim=first_split_dim, + ) + first_split_num_to_user = { + user.args[1]: user + for user in first_split.users # type: ignore[union-attr] + } + + new_split_num = 0 + for split_num in range(len(first_split_sections)): + if split_num not in first_split_num_to_user: + new_split_num += 1 + continue + old_getitem = first_split_num_to_user[split_num] + if split_num != next_split_index: + old_getitem.update_arg(0, new_split) + old_getitem.update_arg(1, new_split_num) + new_split_num += 1 + else: + next_split_num_to_user = {user.args[1]: user for user in node.users} + # It is not necessary all getitems from the split node are used. + for next_split_num in range(len(next_split_sections)): + with graph.inserting_after(new_split): + new_getitem = graph.call_function( + operator.getitem, args=(new_split, new_split_num) + ) + new_split_num += 1 + if next_split_num not in next_split_num_to_user: + continue + next_getitem = next_split_num_to_user[next_split_num] + new_getitem.meta.update(next_getitem.meta) + next_getitem.replace_all_uses_with(new_getitem) + to_remove.append(next_getitem) + to_remove.append(node) + to_remove.append(old_getitem) + + to_remove.append(first_split) # type: ignore[arg-type] + for node in to_remove: + graph.erase_node(node) + + counters[backend]["merge_splits_pass"] += 1 + + +class SplitCatSimplifier: + """ + Helper class to simplify split-cat pattern. In simple cases, both split and cat node can be removed in a "split->cat" + pattern. However, there are various cases where they can't and we need to simplify split/ add transforms before cat. + Some such cases are: + 1. Final node has additional args (not coming from the initial split) + 2. Shuffling of args between split/cat + 3. Some final nodes are non-(cat/stack) + 4. Split-dim != cat-dim (but equal split) + + Note that any combination of the above cases can happen. + + To deal with 1, 2, & 3 - we iterate over all users of split. And figure out common "ranges" that can be merged. + Then, we simplify the split accordingly. In the best case, split can be entirely removed. + + To deal with 4, we add some transformations (unflatten + movedim) (See `get_transform_params`). + + Finally, depending on final node being cat or stack, unsqueeze/flatten needs to be added. + + """ + + def simplify( + self, + graph: torch.fx.Graph, + split_node: torch.fx.Node, + split_sections: list[int], + ): + # Find the next users (i.e. users after the getitem) + next_users = find_next_users(split_node) + # Gather inputs of the next users. When inputs come from `split_node`, they are instead represented by + # a tuple indicating the split ranges. See `get_user_input_list` for more details + user_inputs_list = self.get_user_input_list(split_node, next_users) + # Simplify the split_sections based on user_inputs_list. In simpler cases, len(simplified_split_ranges) == 1 and + # we can simply replace the split node. Otherwise, we simplify it. + simplified_split_ranges = self.get_simplified_split_ranges( + split_sections, next_users, user_inputs_list + ) + if not simplified_split_ranges: # Simplification not possible + return + transform_params_list = self.get_transform_params( + split_node, next_users, user_inputs_list + ) + if not transform_params_list: + return + + # Start actual replacement + user_inputs_list_new = self.replace_split( + graph, split_node, split_sections, user_inputs_list, simplified_split_ranges + ) + self.replace_cat( + graph, + split_node, + next_users, + user_inputs_list_new, + transform_params_list, # type: ignore[arg-type] + ) + self.erase_old_nodes(graph, split_node, next_users) # type: ignore[arg-type] + counters[backend]["unbind_stack_pass"] += 1 + + def get_user_input_list( + self, split_node: torch.fx.Node, next_users: list[torch.fx.Node] + ) -> list[list[torch.fx.Node | _Range]]: + """ + Returns list of inputs to the following user nodes, in order. The outer list represents the user node. The inner + list represents the inputs to that particular node. This list can either contain + - a tuple representing the ranges of get_items that should go into the cat (closed interval) + - torch.fx.Node representing "other" inputs (which are not coming from our split) + """ + user_inputs_list: list[list[torch.fx.Node | _Range]] = [] + for user in next_users: + if user.target in (torch.cat, torch.stack): + user_inputs_list.append(self.get_merged_user_inputs(split_node, user)) + else: + user_inputs_list.append(self.get_non_cat_node_input(split_node, user)) # type: ignore[arg-type] + return user_inputs_list + + def get_merged_user_inputs( + self, split_node: torch.fx.Node, cat_node: torch.fx.Node + ) -> list[torch.fx.Node | _Range]: + user_inputs = get_arg_value(cat_node, 0, "tensors") + simplified_user_inputs = [] + split_users = OrderedSet(split_node.users.keys()) + for user_input in user_inputs: + if user_input not in split_users: + simplified_user_inputs.append(user_input) + else: + # Add which "getitem" cat depends on + simplified_user_inputs.append(user_input.args[1]) + return self.merge_consecutive_inputs(simplified_user_inputs) + + def get_non_cat_node_input( + self, split_node: torch.fx.Node, node: torch.fx.Node + ) -> list[_Range]: + """ + Get input for a non cat node in the same format as `get_merged_user_inputs` + """ + node_input = [] + split_users = OrderedSet(split_node.users.keys()) + for node_arg in node.all_input_nodes: + if node_arg in split_users: + getitem_num = get_arg_value(node_arg, 1) + node_input.append((getitem_num, getitem_num)) + return node_input + + def merge_consecutive_inputs( + self, inputs: list[torch.fx.Node | int] + ) -> list[torch.fx.Node | _Range]: + """ + Merge consecutive inputs going into a user node. + + For e.g. + [arg0, 0, 1, 2, arg1] -> [arg0, (0, 2), arg1] + """ + merged_ranges = [] + cur_range = None + # pyrefly: ignore [bad-assignment] + for input_ in inputs: + if isinstance(input_, int): + if not cur_range: + cur_range = [input_, input_] + elif input_ == cur_range[1] + 1: + cur_range[1] += 1 + else: + merged_ranges.append(tuple(cur_range)) + cur_range = [input_, input_] + else: + if cur_range: + merged_ranges.append(tuple(cur_range)) + cur_range = None + merged_ranges.append(input_) # type: ignore[arg-type] + if cur_range: + merged_ranges.append(tuple(cur_range)) + return merged_ranges # type: ignore[return-value] + + def get_simplified_split_ranges( + self, + split_sections, + next_users, + user_inputs_list: list[list[torch.fx.Node | _Range]], + ) -> list[_Range] | None: + ranges = OrderedSet[Any]() + for user_inputs in user_inputs_list: + ranges.update(u for u in user_inputs if isinstance(u, tuple)) + + cumulative_sizes = [0] + torch.cumsum(torch.tensor(split_sections), 0).tolist() + split_ranges = sorted( + [(cumulative_sizes[r[0]], cumulative_sizes[r[1] + 1]) for r in ranges] + ) + + if not self.has_non_overlapping_ranges( + split_ranges, + ): # This need not be a strict condition + # However, we keep it now for simplicity. + return None + split_ranges = self.fill_gaps(split_ranges, 0, cumulative_sizes[-1]) + if len(split_sections) == len(split_ranges): # Simplification not possible + return None + counters[backend]["scmerge_split_sections_removed"] = len(split_sections) - len( + split_ranges + ) + return split_ranges + + def has_non_overlapping_ranges(self, ranges: list[_Range]) -> bool: + for range_, next_range in itertools.pairwise(ranges): + if range_[1] > next_range[0]: + return False + return True + + def fill_gaps(self, ranges: list[_Range], min_: int, max_: int) -> list[_Range]: + cur = min_ + filled_ranges = [] + for a, b in ranges: + if cur < a: + filled_ranges.append((cur, a)) + filled_ranges.append((a, b)) + cur = b + if filled_ranges[-1][1] < max_: + filled_ranges.append((filled_ranges[-1][1], max_)) + return filled_ranges + + def get_transform_params( + self, + split_node: torch.fx.Node, + next_users: list[torch.fx.Node], + user_inputs_list: list[list[torch.fx.Node | _Range]], + ) -> list[list[_TransformParam]] | None: + """ + Figure out what transforms are needed for each input to each cat node. + + We replace a split node with an unflatten followed by a movedim + """ + split_dim = _get_dim(split_node) + split_sections = split_node.args[1] + transform_params_list: list[list[_TransformParam]] = [] + + for user_node, user_inputs in zip(next_users, user_inputs_list): + if user_node.target not in (torch.cat, torch.stack): + transform_params_list.append([]) + continue + + cat_dim = get_arg_value(user_node, 1, "dim") + transform_params: list[_TransformParam] = [] + for user_input in user_inputs: + if split_dim == cat_dim and user_node.target is torch.cat: + # No transform needed + transform_params.append((None, None, None, None)) + elif isinstance(user_input, tuple): # Split being simplified + # Verify equal split + subset_split_sections = split_sections[ # type: ignore[index] + # pyrefly: ignore [bad-index] + user_input[0] : user_input[1] + + 1 # type: ignore[index] + ] + # All sections should be equal + if len(OrderedSet(subset_split_sections)) != 1: # type: ignore[arg-type] + return None + + num_splits = len(subset_split_sections) # type: ignore[arg-type] + unflatten_params = (split_dim, (num_splits, -1)) + movedim_params = ( + (split_dim, cat_dim) if split_dim != cat_dim else None + ) + transform_params.append( + (unflatten_params, movedim_params, None, None) + ) + elif ( + user_node.target is torch.stack or split_dim != cat_dim + ): # We need to unsqueeze inputs not coming through split + transform_params.append((None, None, (cat_dim,), None)) + else: # Non-split inputs + transform_params.append((None, None, None, None)) + transform_params_list.append(transform_params) + return transform_params_list + + def replace_split( + self, + graph: torch.fx.Graph, + split_node: torch.fx.Node, + split_sections: list[int], + user_inputs_list: list[list[torch.fx.Node | _Range]], + split_ranges: list[_Range], + ) -> list[list[torch.fx.Node]]: + """ + Replace the split node. It can either remove the split node if len(split_ranges) == 1, or simplify it + into a split with lesser sections if len(split_ranges) > 1. + + Returns the new `user_inputs_list`, with tuples replaced with new getitems from the newer split node. + """ + split_input = split_node.args[0] + split_dim = _get_dim(split_node) + if len(split_ranges) == 1: # We can completely eliminate the split node + split_items = [split_input] + else: + with graph.inserting_after(split_node): + new_split = graph.call_function( + torch.split, + args=( + split_input, + [r[1] - r[0] for r in split_ranges], + ), + kwargs={"dim": split_dim}, + ) + if is_node_meta_valid(split_input): # type: ignore[arg-type, union-attr] + new_split.meta["example_value"] = torch.split( + split_input.meta["example_value"], # type: ignore[union-attr] + [r[1] - r[0] for r in split_ranges], + dim=split_dim, + ) + counters[backend]["scmerge_split_added"] += 1 + split_items = [] + with graph.inserting_after(new_split): + for i in range(len(split_ranges)): + getitem = graph.call_function(operator.getitem, args=(new_split, i)) + if is_node_meta_valid(new_split): + getitem.meta["example_value"] = new_split.meta["example_value"][ + i + ] + split_items.append(getitem) + # Now assign the right getitem to the right input + cumulative_sizes = [0] + torch.cumsum(torch.tensor(split_sections), 0).tolist() + new_user_inputs_list = [] + for user_inputs in user_inputs_list: + new_user_inputs = [] + for user_input in user_inputs: + if isinstance(user_input, tuple): + # Find the correct new getitem (present in split_items) + new_user_inputs.append( + # pyrefly: ignore [bad-argument-type] + split_items[ + split_ranges.index( + ( + cumulative_sizes[user_input[0]], + cumulative_sizes[user_input[1] + 1], + ) + ) + ] + ) + else: + new_user_inputs.append(user_input) + new_user_inputs_list.append(new_user_inputs) + return new_user_inputs_list # type: ignore[return-value] + + def replace_cat( + self, + graph: torch.fx.Graph, + split_node: torch.fx.Node, + next_users: list[torch.fx.Node], + user_inputs_list_new, + transform_params_list: list[list[_TransformParam]], + ): + split_dim = _get_dim(split_node) + split_users = split_node.users.keys() + new_cats = [] + for user_node, user_inputs_new, transform_params in zip( + next_users, user_inputs_list_new, transform_params_list + ): + if user_node.target not in (torch.cat, torch.stack): + # Change the args and kwargs of non-cat/stack nodes. Replace old getitems (belonging to + # the original split node) with the newer getitems + next_cat_input = 0 + for input_node in user_node.all_input_nodes: + if input_node in split_users: + user_node.replace_input_with( + input_node, user_inputs_new[next_cat_input] + ) + next_cat_input += 1 + continue + + # Handle cat/stack user nodes + cat_dim = get_arg_value(user_node, 1, "dim") + user_inputs_new_transformed, user_inputs_new_transformed_meta = [], [] + # For `unsqueeze` transform, we will combine consecutive inputs with the same unsqueeze params, and stack them + to_stack, to_stack_meta = [], [] + stack_dim = None + with graph.inserting_before(user_node): + # pyrefly: ignore [bad-assignment] + for user_input_new, transform_param in zip( + user_inputs_new, transform_params + ): + # pyrefly: ignore [bad-argument-type] + if not is_node_meta_valid(user_input_new): + log.debug("example value absent for node: %s", user_input_new) + return + # Apply transforms + ( + unflatten_params, + movedim_params, + unsqueeze_params, + flatten_params, + ) = transform_param + if unsqueeze_params and ( + stack_dim is None or stack_dim == unsqueeze_params[0] + ): + to_stack.append(user_input_new) + # pyrefly: ignore [missing-attribute] + to_stack_meta.append(user_input_new.meta["example_value"]) + stack_dim = unsqueeze_params[0] + continue + elif to_stack: + stacked_input = graph.call_function( + torch.stack, args=(to_stack,), kwargs={"dim": stack_dim} + ) + stacked_input.meta["example_value"] = torch.stack( # type: ignore[arg-type] + to_stack_meta, + dim=stack_dim, # type: ignore[arg-type] + ) + to_stack, to_stack_meta = [], [] + stack_dim = None + user_inputs_new_transformed.append(stacked_input) + user_inputs_new_transformed_meta.append( + stacked_input.meta["example_value"] + ) + if unsqueeze_params: + to_stack.append(user_input_new) + stack_dim = unsqueeze_params[0] + # pyrefly: ignore [missing-attribute] + to_stack_meta.append(user_input_new.meta["example_value"]) + continue + + if unflatten_params: + # pyrefly: ignore [missing-attribute] + user_input_new_meta = user_input_new.meta["example_value"] + user_input_new = graph.call_function( + torch.unflatten, args=(user_input_new, *unflatten_params) + ) + user_input_new.meta["example_value"] = torch.unflatten( # type: ignore[arg-type] + user_input_new_meta, # type: ignore[arg-type] + *unflatten_params, # type: ignore[arg-type] + ) + if movedim_params: + # pyrefly: ignore [missing-attribute] + user_input_new_meta = user_input_new.meta["example_value"] + user_input_new = graph.call_function( + torch.movedim, args=(user_input_new, *movedim_params) + ) + user_input_new.meta["example_value"] = torch.movedim( # type: ignore[arg-type] + user_input_new_meta, # type: ignore[arg-type] + *movedim_params, # type: ignore[arg-type] + ) + if flatten_params: + # pyrefly: ignore [missing-attribute] + user_input_new_meta = user_input_new.meta["example_value"] + user_input_new = graph.call_function( + torch.flatten, args=(user_input_new, *flatten_params) + ) + user_input_new.meta["example_value"] = torch.flatten( # type: ignore[arg-type] + user_input_new_meta, + *flatten_params, # type: ignore[arg-type] + ) + user_inputs_new_transformed.append(user_input_new) + user_inputs_new_transformed_meta.append( + # pyrefly: ignore [missing-attribute] + user_input_new.meta["example_value"] + ) + if to_stack: + stacked_input = graph.call_function( + torch.stack, args=(to_stack,), kwargs={"dim": stack_dim} + ) + stacked_input.meta["example_value"] = torch.stack( # type: ignore[arg-type] + to_stack_meta, + dim=stack_dim, # type: ignore[arg-type] + ) + user_inputs_new_transformed.append(stacked_input) + user_inputs_new_transformed_meta.append( + stacked_input.meta["example_value"] + ) + + with graph.inserting_after(user_node): + if len(user_inputs_new_transformed) > 1: + new_cat_node = graph.call_function( + torch.cat, + args=(user_inputs_new_transformed,), + kwargs={"dim": cat_dim}, + ) + new_cat_node.meta["example_value"] = torch.cat( + user_inputs_new_transformed_meta, + dim=cat_dim, + ) + counters[backend]["scmerge_cat_added"] += 1 + else: + new_cat_node = user_inputs_new_transformed[-1] + new_cat_node.meta["example_value"] = ( + user_inputs_new_transformed_meta[-1] + ) + + if ( + user_node.target is torch.cat + and split_dim != cat_dim + and split_node.target is torch.split + ): + with graph.inserting_after(new_cat_node): + new_cat_node_meta = new_cat_node.meta["example_value"] + new_cat_node = graph.call_function( + torch.flatten, args=(new_cat_node, cat_dim, cat_dim + 1) + ) + new_cat_node.meta["example_value"] = torch.flatten( + new_cat_node_meta, + cat_dim, + cat_dim + 1, + ) + user_node.replace_all_uses_with(new_cat_node) + new_cats.append(new_cat_node) + + def erase_old_nodes( + self, + graph: torch.fx.Graph, + split_node: torch.fx.Node, + next_users: list[torch.fx.Node], + ): + to_remove = [split_node] + counters[backend]["scmerge_split_removed"] += 1 + to_remove.extend(split_node.users.keys()) + for next_user in next_users: + if next_user.target not in (torch.cat, torch.stack): + continue + counters[backend]["scmerge_cat_removed"] += 1 + to_remove.append(next_user) + for node in reversed(to_remove): + if len(node.users.keys()) == 0: + graph.erase_node(node) + + +class UnbindCatRemover(SplitCatSimplifier): + """ + Helper class to merge Unbind->Cat/Stack. Many of the cases are similar to SplitCatSimplifier. + + Unbind can't be simplified like splits. So, we can only remove the unbind node. Other than this, + other cases like multiple users, additional args, dim mismatch are similar to `SplitCatSimplifier`, + hence we extend that class. + """ + + def remove_unbind( + self, + graph: torch.fx.Graph, + unbind_node: torch.fx.Node, + ): + if not is_node_meta_valid(unbind_node): + return + # we need to check if the getitem indices from unbind are consecutive and all go to the same cat node + # before we do the unbind remove, otherwise it will hit the error when we unbind part of them + getitem_indices = [getitem_node.args[1] for getitem_node in unbind_node.users] + if not is_sorted_and_consecutive(getitem_indices) or len( # type: ignore[arg-type] + getitem_indices + ) != len(unbind_node.meta["example_value"]): + return + num_unbind = len(getitem_indices) + split_sections = [1 for _ in range(num_unbind)] # type: ignore[operator, arg-type] + + super().simplify(graph, unbind_node, split_sections) + + def get_simplified_split_ranges( + self, + split_sections: list[int], + next_users: list[torch.fx.Node], + user_inputs_list: list[list[torch.fx.Node | _Range]], + ) -> list[_Range] | None: + simplified_split_ranges = super().get_simplified_split_ranges( + split_sections, next_users, user_inputs_list + ) + if not simplified_split_ranges or len(simplified_split_ranges) != 1: + return None + return simplified_split_ranges + + def get_transform_params( + self, + split_node: torch.fx.Node, + next_users: list[torch.fx.Node], + user_inputs_list: list[list[torch.fx.Node | _Range]], + ) -> list[list[_TransformParam]] | None: + """ + Figure out what transforms are needed for each input to each cat node. + + Here is the rough transforms we apply: + + x -> unbind -> stack => x -> movedim + + x -> unbind -> cat => x -> movedim -> flatten + + When cat/stack nodes have additional args: + + addn ---| addn -> unsqueeze ---| + x -> unbind -> stack => x -> movedim -> cat + + addn ---| addn ---| + x -> unbind -> cat => x -> movedim -> flatten -> cat + + (Note application of these depends on the dims as well) + + + """ + split_dim = _get_dim(split_node) + transform_params_list: list[list[_TransformParam]] = [] + for user_node, user_inputs in zip(next_users, user_inputs_list): + cat_dim = get_arg_value(user_node, 1, "dim") or 0 + transform_params: list[_TransformParam] = [] + for user_input in user_inputs: + if isinstance(user_input, tuple): + # User input is coming from unbind + movedim_params = ( + (split_dim, cat_dim) if split_dim != cat_dim else None + ) + flatten_params = None + if user_node.target is torch.cat: + flatten_params = (cat_dim, cat_dim + 1) + transform_params.append( + (None, movedim_params, None, flatten_params) + ) + elif ( + user_node.target is torch.stack + ): # We need to unsqueeze inputs not coming through unbind into cat + transform_params.append((None, None, (cat_dim,), None)) + else: # Non-unbind inputs + transform_params.append((None, None, None, None)) + transform_params_list.append(transform_params) + return transform_params_list + + +class GetItem(CallFunction): + def __init__(self, arg, index, _users=1) -> None: + super().__init__(operator.getitem, arg, index, _users=_users) + + def find_anchor_nodes(self, ctx: MatchContext, searched: OrderedSet[torch.fx.Node]): + # We generally match GetItem with arg being an Arg(). So, we never return the anchor + # nodes as the stored node in ctx.pattern_to_node is returned. Here we override find_anchor_nodes + # to not use ctx.pattern_to_node + for pattern in self.flat_args_kwargs[0]: + if isinstance(pattern, PatternExpr): + for other_node in pattern.find_anchor_nodes(ctx, searched): + if not isinstance(other_node, torch.fx.Node): + continue + for node in other_node.users: + if node not in searched: + if self._match_fns(node): + yield node + searched.add(node) + + +@register_graph_pattern( + RepeatedExpr( + CallFunction( + torch.squeeze, + GetItem( + TorchSplit( + KeywordArg("split_input"), + KeywordArg("split_sizes"), + ), + Ignored(), + ), + KeywordArg("dim"), + _users=MULTIPLE, + ), + ), + pass_dict=construct_pattern_matcher_pass("split_cat_pass"), +) +@register_graph_pattern( + RepeatedExpr( + CallFunction( + torch.squeeze, + GetItem( + TorchSplit( + KeywordArg("split_input"), + KeywordArg("split_sizes"), + ), + Ignored(), + ), + dim=KeywordArg("dim"), + _users=MULTIPLE, + ) + ), + pass_dict=construct_pattern_matcher_pass("split_cat_pass"), +) +def merge_split_squeeze( + match: Match, split_input: torch.fx.Node, split_sizes: list[int], dim: int +): + graph = match.graph + split = next(node for node in match.nodes if node.target is torch.split) + if not all(s == 1 for s in split_sizes): + return + if isinstance(dim, Sequence): + return + next_users = find_next_users(split) + if not all(node.target is torch.squeeze for node in next_users): + return + with graph.inserting_before(match.output_node()): + unbind = graph.call_function( + torch.unbind, args=(split_input,), kwargs={"dim": dim} + ) + if is_node_meta_valid(split_input): + unbind.meta["example_value"] = torch.unbind( + split_input.meta["example_value"], dim=dim + ) + for item_index, getitem_node in sorted( + [(getitem_node.args[1], getitem_node) for getitem_node in split.users] + ): + squeeze = next(iter(getitem_node.users.keys())) + new_get_item = graph.call_function( + operator.getitem, args=(unbind, item_index) + ) + squeeze.replace_all_uses_with(new_get_item) + new_get_item.meta.update(squeeze.meta) + graph.erase_node(squeeze) + graph.erase_node(getitem_node) + graph.erase_node(split) + counters[backend]["split_cat_pass"] += 1 + + +getitem_unbind = ListOf( + GetItem( + CallFunction( + torch.unbind, + KeywordArg("unbind_input"), + dim=KeywordArg("dim"), + _users=MULTIPLE, + ), + Ignored(), + _users=MULTIPLE, + ), + partial=True, +) + + +@register_graph_pattern( + CallFunction([torch.stack, torch.cat], getitem_unbind, Ignored(), _users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("unbind_stack_pass"), +) +@register_graph_pattern( + CallFunction( + [torch.stack, torch.cat], getitem_unbind, dim=Ignored(), _users=MULTIPLE + ), + pass_dict=construct_pattern_matcher_pass("unbind_stack_pass"), +) +@register_graph_pattern( + CallFunction( + [torch.stack, torch.cat], tensors=getitem_unbind, dim=Ignored(), _users=MULTIPLE + ), + pass_dict=construct_pattern_matcher_pass("unbind_stack_pass"), +) +def merge_unbind_stack(match: Match, unbind_input: torch.fx.Node, dim: int): + unbind_node = next(node for node in match.nodes if node.target is torch.unbind) + UnbindCatRemover().remove_unbind(match.graph, unbind_node) + + +getitem_split = ListOf( + CallFunction( + operator.getitem, + TorchSplit( + Ignored(), + KeywordArg("split_sections"), + ), + Ignored(), + _users=MULTIPLE, + ), + partial=True, +) + + +reshape_getitem_split = ListOf( + CallFunction( + torch.reshape, + CallFunction( + operator.getitem, + TorchSplit( + Ignored(), + KeywordArg("split_sections"), + ), + Ignored(), + _users=MULTIPLE, + ), + Arg(), + _users=MULTIPLE, + ), + partial=True, +) + + +@register_graph_pattern( + CallFunction( + [torch.stack, torch.cat], + tensors=getitem_split, + dim=Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("split_cat_pass"), +) +@register_graph_pattern( + CallFunction( + [torch.stack, torch.cat], + getitem_split, + dim=Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("split_cat_pass"), +) +@register_graph_pattern( + CallFunction( + [torch.stack, torch.cat], + getitem_split, + Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("split_cat_pass"), +) +def simplify_split_cat(match: Match, split_sections: list[int], dim: int): + if not isinstance(split_sections, (list, tuple)): # Unnormalized split + return + split_node = next(node for node in match.nodes if node.target is torch.split) + + SplitCatSimplifier().simplify(match.graph, split_node, split_sections) + + +# ############pattern to be optimized is######### + +# split_node(dim=1) +# / \ ... / \ +# getitem getitem getitem getitem -> user=1 +# \ / \ / +# cat (user=mul, dim=1) cat(user=mul, dim=1) +# | \ | \ + +# ################after transformation############# + +# split_node(dim=1) +# / ... \ +# getitem getitem +# | \ | \ + + +def has_same_parent_node(node: torch.fx.Node): + # the input nodes of the node should come from the same parent + prev_node = None + for getitem in node.args[0]: # type: ignore[union-attr] + if getitem.target != operator.getitem: # type: ignore[union-attr] + return False + if prev_node is None: + prev_node = getitem.args[0] # type: ignore[union-attr] + else: + if getitem.args[0] != prev_node: # type: ignore[union-attr] + return False + return True + + +def remove_zeros(split_sections: list[int]): + """ + Remove zeros from the list and get the index mapping dict from getitem + in split node to getitem in new split node + """ + new_split_sections, index_mapping = [], {} + idx = 0 + for i in range(len(split_sections)): + if split_sections[i] > 0: + new_split_sections.append(split_sections[i]) + index_mapping[i] = idx + idx += 1 + + return new_split_sections, index_mapping + + +def is_sorted_and_consecutive(arr: list[int]) -> bool: + # check if the array is sorted + if arr == sorted(arr): + # check if the differences between adjacent elements are all 1 + return all(x[1] - x[0] == 1 for x in itertools.pairwise(arr)) + else: + return False + + +def calculate_fused_tensor_size(split_node: torch.fx.Node, indices: list[int]) -> int: + """ + Calculate the fused tensor size in the indices + """ + fused_tensor_size = 0 + for i in range(len(split_node.args[1])): # type: ignore[arg-type] + if i in indices: + fused_tensor_size += split_node.args[1][i] # type: ignore[operator, assignment, index] + # pyrefly: ignore [bad-return] + return fused_tensor_size + + +@register_graph_pattern( + CallFunction( + torch.cat, + getitem_split, + dim=Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("merge_getitem_cat_pass"), +) +def merge_getitem_cat(match: Match, split_sections: list[int], dim: int): + if not isinstance(split_sections, (list, tuple)): # Unnormalized split + return + graph = match.graph + split_node = next(node for node in match.nodes if node.target is torch.split) + split_input, _split_size, split_dim = _get_split_args_default(split_node) + # if the cat and split have different dims, return + # Find the next users (i.e. users after the getitem) + next_users = find_next_users(split_node) + # 'immutable_list' object does not support mutation. Create a new copy of it + split_sections = list(split_sections) + for cat_user in next_users: + if cat_user.target is torch.cat: + cat_dim = get_arg_value(cat_user, 1, "dim") + # check the all getitems in the cat_user from the same node + # check the input of the cat has all getitem from the split + # check all getitem only has one single user + if ( + split_dim != cat_dim + or not has_same_parent_node(cat_user) + or not all(len(arg.users) == 1 for arg in cat_user.args[0]) # type: ignore[union-attr] + ): + continue + # find the index of getitems to be cated/stacked + # type: ignore[union-attr] + indices = [arg.args[1] for arg in cat_user.args[0]] # type: ignore[union-attr] + # the getitems to be merged must be consecutive, otherwise + # returned sliced tensor could be wrong + if not is_sorted_and_consecutive(indices): # type: ignore[arg-type] + continue + # update the arg of cat user, only keep the first getitem + cat_user.update_arg(0, cat_user.args[0][0]) # type: ignore[index] + # calculate the fused tensor sizes in the indices + fused_tensor_size = 0 + for i in range(len(split_node.args[1])): # type: ignore[arg-type] + if i in indices: + fused_tensor_size += split_node.args[1][i] # type: ignore[operator, assignment, index] + # update the split sections + split_sections[indices[0]] = calculate_fused_tensor_size( # type: ignore[index] + split_node, + indices, # type: ignore[arg-type] + ) + # padding others with zeros to keep the same dict size + for i in indices[1:]: + split_sections[i] = 0 # type: ignore[index] + # remove all unused indexes in the split_node + new_split_sections, index_mapping = remove_zeros(split_sections) + with graph.inserting_after(split_node): + new_split_node = graph.call_function( + torch.split, + args=(split_input, split_sections), + kwargs={"dim": split_dim}, + ) + split_node.replace_all_uses_with(new_split_node) + new_split_node.meta.update(split_node.meta) + # remove all unused getitem nodes + to_remove = [cat_user] + # dictionary keys changed during iteration + new_split_getitem_nodes = list(new_split_node.users.keys()) + for getitem_node in new_split_getitem_nodes: + if getitem_node.args[1] in indices[1:]: + to_remove.append(getitem_node) + # update meta data of getitem + elif getitem_node.args[1] == indices[0]: + cat_user.replace_all_uses_with(getitem_node) + getitem_node.meta.update(cat_user.meta) + else: + # update getitem index for new split node + getitem_node.update_arg(1, index_mapping[getitem_node.args[1]]) + graph.erase_node(split_node) + for getitem_node in to_remove: + graph.erase_node(getitem_node) + # update the split sections of new split node + new_split_node.update_arg(1, new_split_sections) + split_node = new_split_node + split_sections = new_split_sections + + counters[backend]["merge_getitem_cat_pass"] += 1 + + +# ############pattern to be optimized is######### + +# split_node(dim=1) -> user=multiple +# / \ ... / \ +# getitem getitem getitem getitem -> user=multiple +# \ \ / \ +# other_op /cat(user=mul, dim=1) other_op +# | + +# ################after transformation############# + +# split_node(dim=1) -> -> user=multiple +# / \ ... / \ +# getitem getitem getitem getitem -> user=multiple +# \ \ / \ +# other_op + + +@register_graph_pattern( + CallFunction( + torch.cat, + getitem_split, + dim=Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("mutate_cat_pass"), +) +def mutate_cat_node(match: Match, split_sections: list[int], dim: int): + if not isinstance(split_sections, (list, tuple)): # Unnormalized split + return + graph = match.graph + split_node = next(node for node in match.nodes if node.target is torch.split) + _split_input, _split_size, split_dim = _get_split_args_default(split_node) + # if the cat and split have different dims, return + # Find the next users (i.e. users after the getitem) + next_users = find_next_users(split_node) + for cat_user in next_users: + if cat_user.target is torch.cat: + cat_dim = get_arg_value(cat_user, 1, "dim") or 0 + # check that all getitems in the cat_user from the same node + # check the input of the cat has all getitem from the split + if split_dim != cat_dim or not has_same_parent_node(cat_user): + continue + # find the index of getitems to be cat + indices, idx_to_getitem = [], {} + for getitem in cat_user.args[0]: # type: ignore[union-attr] + indices.append(getitem.args[1]) # type: ignore[union-attr] + idx_to_getitem[getitem.args[1]] = getitem # type: ignore[union-attr] + # the getitems to be merged must be consecutive, otherwise + # returned sliced tensor could be wrong + if not is_sorted_and_consecutive(indices): # type: ignore[arg-type] + continue + # case 1: the cat uses all getitems from the split + if len(split_sections) == len(cat_user.args[0]): # type: ignore[arg-type] + # replace the users of the cat node to be the input of the split node + cat_user.replace_all_uses_with(split_node.args[0]) # type: ignore[arg-type] + # remove the cat node + graph.erase_node(cat_user) + counters[backend]["mutate_cat_pass"] += 1 + # case 2: the cat uses some getitems from the split + elif is_node_meta_valid(split_node.args[0]): # type: ignore[arg-type] + # check the split dim, and construct the slice tuple + start_fused_size = calculate_fused_tensor_size( + split_node, + list(range(indices[0])), # type: ignore[arg-type] + ) + end_fused_size = start_fused_size + calculate_fused_tensor_size( + split_node, + indices, # type: ignore[arg-type] + ) + slice_list = [] + for i in range(len(split_node.args[0].meta["example_value"].shape)): # type: ignore[union-attr] + if i != split_dim: + slice_list.append(slice(None, None, None)) + else: + slice_list.append(slice(start_fused_size, end_fused_size, None)) + with graph.inserting_after(split_node): + slice_node = graph.call_function( + operator.getitem, + args=(split_node.args[0], tuple(slice_list)), + ) + cat_user.replace_all_uses_with(slice_node) + slice_node.meta.update(cat_user.meta) + + # remove the cat node + graph.erase_node(cat_user) + counters[backend]["mutate_cat_pass"] += 1 + + +getitem_split_aten = ListOf( + CallFunction( + operator.getitem, + CallFunctionVarArgs([torch.ops.aten.split_with_sizes.default], users=MULTIPLE), + Ignored(), + _users=MULTIPLE, + ), + partial=True, +) + + +@register_graph_pattern( + CallFunctionVarArgs(torch.ops.aten.split.Tensor, users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_aten_pass"), +) +def normalize_split_default_aten(match: Match, *args, **kwargs): + split_node = match.nodes[0] + graph = match.graph + split_input, split_size, split_dim = _get_split_args_default(split_node) + if split_input is None or split_dim is None or split_size is None: + log.debug("couldn't find split args") + return + if not is_node_meta_valid(split_node): + log.debug("val absent for node: %s", split_node) + return + if not isinstance(split_node.meta["val"], (list, tuple)): + raise AssertionError(f"expected list/tuple val, got {split_node.meta['val']}") + split_sections = [t.size()[split_dim] for t in split_node.meta["val"]] + if any(isinstance(section, torch.SymInt) for section in split_sections): + # TODO dynamic_shapes with assume_static_by_default=False fails while AOT Autograd tracing. + return + if split_dim < 0: # Normalize split dim + split_dim += split_input.meta["val"].dim() + # we also need to check the input of the split_node + # primals =torch.randn(4096, 300) + # split = torch.ops.aten.split.Tensor(primals, 320, 1) -> truncate to 300 automatically + # split_2 = torch.ops.aten.split_with_sizes.default(primals, [320], dim = 1) -> runtime error + split_input_size = split_input.meta["val"].shape[split_dim] + split_size = min(split_size, split_input_size) + split_section_list = [split_size] * (len(split_node.meta["val"])) + new_args = (split_input, split_section_list) + new_kwargs = {"dim": split_dim} + if ( + split_node.args == new_args + and split_node.kwargs == new_kwargs + and split_node.op == "call_function" + ): + return + + with graph.inserting_after(split_node): + new_split_node = graph.call_function( + torch.ops.aten.split_with_sizes.default, + args=new_args, + kwargs=new_kwargs, # type: ignore[arg-type] + ) + split_node.replace_all_uses_with(new_split_node) + new_split_node.meta.update(split_node.meta) + graph.erase_node(split_node) + counters[backend]["normalization_aten_pass"] += 1 + + +@register_graph_pattern( + CallFunctionVarArgs(torch.ops.aten.split_with_sizes.default, users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_aten_pass"), +) +def normalize_split_with_size_default_aten(match: Match, *args, **kwargs): + split_node = match.nodes[0] + graph = match.graph + split_input, split_sections, split_dim = _get_split_args_default(split_node) + if split_input is None or split_dim is None or split_sections is None: + log.debug("couldn't find split args") + return + if not is_node_meta_valid(split_node): + log.debug("val absent for node: %s", split_node) + return + if any(isinstance(section, torch.SymInt) for section in split_sections): + # TODO dynamic_shapes with assume_static_by_default=False fails while AOT Autograd tracing. + return + if split_dim < 0: # Normalize split dim + split_dim += split_input.meta["val"].dim() + + new_args = (split_input, split_sections) + new_kwargs = {"dim": split_dim} + if ( + split_node.args == new_args + and split_node.kwargs == new_kwargs + and split_node.op == "call_function" + ): + return + + with graph.inserting_after(split_node): + new_split_node = graph.call_function( + torch.ops.aten.split_with_sizes.default, + args=new_args, + kwargs=new_kwargs, # type: ignore[arg-type] + ) + split_node.replace_all_uses_with(new_split_node) + new_split_node.meta.update(split_node.meta) + graph.erase_node(split_node) + counters[backend]["normalization_aten_pass"] += 1 + + +@register_graph_pattern( + CallFunction( + torch.ops.aten.cat.default, + getitem_split_aten, + dim=Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("split_cat_aten_pass"), +) +def merge_split_cat_aten(match: Match, *args, **kwargs): + graph = match.graph + split_node = match.nodes[0] + threshold_to_cat = torch._inductor.config.post_grad_fusion_options[ + "split_cat_aten_pass" + ].get("threshold_to_cat", 10) + # get the getitem nodes from the split node + getitem_nodes = list(split_node.users.keys()) + for cat_node in list(getitem_nodes[0].users.keys()): + cat_dim = get_arg_value(cat_node, 1, "dim") + cat_inputs = get_arg_value(cat_node, 0, "tensors") + try: + cat_input_len = len(cat_inputs) + except TypeError: + continue + if cat_input_len < threshold_to_cat: + continue + # check split node and cat node has same dim, and all getitem nodes have same parent node + parent_to_indices = defaultdict(list) # type: ignore[var-annotated] + parent_to_getitems = defaultdict(list) # type: ignore[var-annotated] + for cat_input in cat_inputs: + # skip all non-getitem cat input + if cat_input.target != operator.getitem: + continue + current_getitem_parent = cat_input.args[0] + split_dim = get_arg_value(current_getitem_parent, 2, "dim") + if split_dim != cat_dim: + break + getitem_idx = cat_input.args[1] + if ( + current_getitem_parent not in parent_to_indices + ) or getitem_idx != parent_to_indices[current_getitem_parent][-1][-1] + 1: + parent_to_indices[current_getitem_parent].append([getitem_idx]) + parent_to_getitems[current_getitem_parent].append([cat_input]) + else: + parent_to_getitems[current_getitem_parent][-1].append(cat_input) + parent_to_indices[current_getitem_parent][-1].append(getitem_idx) + + cat_inputs_list = list(cat_inputs) + update_cat_arg = [] + # iterate through the indices to construct the slice nodes + for parent, indices in parent_to_indices.items(): + for idx, indice in enumerate(indices): + start, end = indice[0], indice[-1] + split_sections = list(parent.args[1]) + input_of_current_getitem_parent = parent.args[0] + if len(indice) >= threshold_to_cat or len(indice) == len( + split_sections + ): + if len(indice) != len(split_sections): + # get the start and end slicing indices + slice_node = graph.call_function( + torch.ops.aten.slice.Tensor, + args=( + input_of_current_getitem_parent, + split_dim, # type: ignore[possibly-undefined] + sum(split_sections[:start]), + sum(split_sections[: end + 1]), + ), + ) + else: + slice_node = input_of_current_getitem_parent + # find the index in the cat_inputs_list given the getitem node + update_cat_arg.append( + ( + slice_node, + cat_inputs_list.index(parent_to_getitems[parent][idx][0]), + cat_inputs_list.index(parent_to_getitems[parent][idx][-1]), + ) + ) + + result = [] + i = 0 + for slice_tensor, start, end in update_cat_arg: + while i < start: + result.append(cat_inputs_list[i]) + i += 1 + result.append(slice_tensor) + i = end + 1 + while i < len(cat_inputs_list): + result.append(cat_inputs_list[i]) + i += 1 + + cat_node.update_arg(0, result) + for getitem_node in getitem_nodes: + if len(getitem_node.users) == 0: + graph.erase_node(getitem_node) + if len(split_node.users) == 0: + graph.erase_node(split_node) + counters[backend]["split_cat_aten_pass"] += 1 + + +@register_graph_pattern( + CallFunction( + torch.ops.aten.cat.default, + ListOf( + CallFunctionVarArgs(torch.ops.aten.select.int, users=MULTIPLE), + partial=True, + ), + dim=Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("select_cat_aten_pass"), +) +def merge_select_cat_aten(match: Match, *args, **kwargs): + graph = match.graph + node = match.nodes[0] + node_input = get_arg_value(node, 0, "tensors") + # get the select nodes from the node + select_nodes = list(node_input.users.keys()) + for cat_node in list(node.users.keys()): + if cat_node.target is torch.ops.aten.cat.default: + cat_dim = get_arg_value(cat_node, 1, "dim") + cat_inputs = get_arg_value(cat_node, 0, "tensors") + # check all select nodes has same slice dim + if not all( + select_node.args[1] == select_nodes[0].args[1] + for select_node in select_nodes + ): + continue + # We only consider the case where select slice dim and cat node has same dim + if select_nodes[0].args[1] != cat_dim: + continue + if not is_node_meta_valid(cat_node): + continue + # check the cat node has consecutive indices + indices = [select.args[2] for select in cat_node.args[0]] # type: ignore[union-attr] + if ( + not is_sorted_and_consecutive(indices) # type: ignore[arg-type] + or len(select_nodes) != len(cat_inputs) + ): + continue + # check all the select nodes can be merged to the cat node input + if len(indices) != select_nodes[0].args[0].meta["val"].shape[cat_dim]: # type: ignore[union-attr] + continue + # reshape the node input to be the same shape as the cat node + with graph.inserting_before(node): + view_node = graph.call_function( + torch.ops.aten.view.default, + args=(node_input, cat_node.meta["val"].shape), + ) + # replace the node input with the new node + cat_node.replace_all_uses_with(view_node) + view_node.meta.update(cat_node.meta) + # remove the cat node + graph.erase_node(cat_node) + for select_node in select_nodes: + if len(select_node.users) == 0: + graph.erase_node(select_node) + counters[backend]["select_cat_aten_pass"] += 1 + + +@register_graph_pattern( + CallFunctionVarArgs(torch.ops.aten.cat.default, users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("normalization_aten_pass"), +) +def normalize_cat_default_aten(match: Match, *args, **kwargs): + cat_node = match.nodes[0] + graph = match.graph + tensors = get_arg_value(cat_node, 0, "tensors") + cat_dim = get_arg_value(cat_node, 1, "dim") + if cat_dim is None: + cat_axis = cat_node.kwargs.get("axis") + if cat_axis is not None: + cat_dim = cat_axis + else: + cat_dim = 0 + if tensors is None or cat_dim is None: + log.debug("couldn't find cat args") + return + if not isinstance(tensors, (list, tuple)): + raise AssertionError(f"expected list/tuple tensors, got {type(tensors)}") + for tensor in itertools.chain([cat_node], tensors): + if "val" not in tensor.meta: + log.debug("val absent for node: %s", tensor) + return + + ndim = cat_node.meta["val"].dim() + + def is_empty_tensor(x: torch.fx.Node) -> bool: + # special case where torch.ops.aten.cat.default supports cat'ing with an empty tensor + x_shape = x.meta["val"].shape + return len(x_shape) == 1 and x_shape[0] == 0 + + if not all(ndim == x.meta["val"].dim() or is_empty_tensor(x) for x in tensors): + raise AssertionError("expected all tensors to match ndim or be empty") + + if cat_dim < 0: # Normalize cat dim + cat_dim += ndim + + with graph.inserting_after(cat_node): + new_cat_node = graph.call_function( + torch.ops.aten.cat.default, + args=(tensors,), + kwargs={"dim": cat_dim}, + ) + cat_node.replace_all_uses_with(new_cat_node) + new_cat_node.meta.update(cat_node.meta) + graph.erase_node(cat_node) + counters[backend]["normalization_aten_pass"] += 1 + + +@register_graph_pattern( + CallFunction( + torch.ops.aten.cat, + ListOf(CallFunctionVarArgs(torch.ops.aten.unsqueeze)), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("unbind_stack_aten_pass"), +) +def merge_unbind_stack_aten(match: Match, *args, **kwargs): + node = match.nodes[-1] + graph = match.graph + # pyre-fixme[6] + unsqueeze_nodes = list(node.args[0]) # type: ignore[arg-type] + cat_dim = get_arg_value(node, 1, "dim") + # check the unsqueeze nodes come from the select nodes + if not all( + # pyrefly: ignore [bad-argument-type] + get_arg_value(unsqueeze_node, 0, "input").target is torch.ops.aten.select + for unsqueeze_node in unsqueeze_nodes + ): + return + select_nodes = [ + # pyrefly: ignore [bad-argument-type] + get_arg_value(unsqueeze_node, 0, "input") + for unsqueeze_node in unsqueeze_nodes + ] + parent_of_select_node = get_arg_value(select_nodes[0], 0, "input") + # check the target of select_nodes are the same + if not all( + select_node.target is torch.ops.aten.select for select_node in select_nodes + ): + return + # check the select nodes come from the same parent node + if not all( + get_arg_value(select_node, 0, "input") == parent_of_select_node + for select_node in select_nodes + ): + return + if len(unsqueeze_nodes) != len(select_nodes): + return + # check the select nodes have the same dim + if not all( + get_arg_value(select_node, 1, "dim") == cat_dim for select_node in select_nodes + ): + return + # check the select nodes have consecutive indices starting from 0 + if get_arg_value(select_nodes[0], 2, "index") != 0 or not is_sorted_and_consecutive( + [get_arg_value(select_node, 2, "index") for select_node in select_nodes] + ): + return + # check the users of parent of select node only from unsqueeze nodes that go to the cat node + # we simply check the number of users of the parent of select node + if len(parent_of_select_node.users.keys()) != len(node.args[0]): # type: ignore[arg-type] + return + node.replace_all_uses_with(parent_of_select_node) + graph.erase_node(node) + for unsqueeze_node in unsqueeze_nodes: + # pyrefly: ignore [bad-argument-type] + graph.erase_node(unsqueeze_node) + for select_node in select_nodes: + if len(select_node.users) == 0: + graph.erase_node(select_node) + counters[backend]["unbind_stack_aten_pass"] += 1 + + +def divide_into_consecutive_sublists(indices: list[int]) -> list[list[int]]: + n = len(indices) + if n <= 1: + return [indices] + + # Initialize the list of sublists + sublists = [] + + # Iterate over the indices + i = 0 + while i < n: + # Initialize the current sublist + sublist = [indices[i]] + + # Iterate over the remaining indices + j = i + 1 + while j < n and indices[j] == indices[j - 1] + 1: + # Add the next index to the current sublist + sublist.append(indices[j]) + j += 1 + + # Add the current sublist to the list of sublists + sublists.append(sublist) + # Move to the next index + i = j + + return sublists + + +def update_args_from_split_getitem( + graph: torch.fx.Graph, + node: torch.fx.Node, + getitem_indices: list[int], + parents_seen: list[torch.fx.Node], + new_cat_args: list[torch.fx.Node], + new_cat_args_meta: list[torch.fx.Node], + idx_to_getitems: dict[int, torch.fx.Node], + threshold_to_cat: int = 2, +): + split_input, split_size, split_dim = _get_split_args_default(parents_seen[-1]) + # case 1: the number of getitems is the same as the split size, eliminate the split + if len(split_size) == len(getitem_indices) and is_sorted_and_consecutive( + getitem_indices + ): + # we can merge the getitems from the previous parent + new_cat_args.append(split_input) + new_cat_args_meta.append(split_input.meta["example_value"]) + else: + if len(getitem_indices) > 0: + # case 2: the number of getitems is smaller than the split size but larger than the threshold, and + # the indices of getitems are not all consecutive, we need to divide the indices into multiple groups + geitem_indices_sublist = divide_into_consecutive_sublists(getitem_indices) + for sublist in geitem_indices_sublist: + if len(sublist) >= threshold_to_cat: + # case 2: the number of getitems is smaller than the split size but larger than the threshold + # we need to slice the input of parent + start_fused_size = sum(split_size[: sublist[0]]) + end_fused_size = sum(split_size[: sublist[-1] + 1]) + slice_list = [] + for i in range(len(split_input.meta["example_value"].shape)): # type: ignore[union-attr] + if i != split_dim: + slice_list.append(slice(None, None, None)) + else: + slice_list.append( + slice(start_fused_size, end_fused_size, None) + ) + with graph.inserting_after(node): + slice_node = graph.call_function( + operator.getitem, + args=(split_input, tuple(slice_list)), + ) + slice_node.meta["example_value"] = split_input.meta[ + "example_value" + ][tuple(slice_list)] + new_cat_args.append(slice_node) + new_cat_args_meta.append(slice_node.meta["example_value"]) + else: + # case 3: the number of getitems is smaller than the threshold, no merge is done + # get the getitems based on the indexes + for i in sublist: + new_cat_args.append(idx_to_getitems[i]) + new_cat_args_meta.append( + idx_to_getitems[i].meta["example_value"] + ) + + +def reshape_cat_node( + graph: torch.fx.Graph, + cat_node: torch.fx.Node, + unbind_input: torch.fx.Node, + cat_dim: int, + unbind_dim: int, + cat_shape: torch.Size, +) -> torch.fx.Node: + if cat_dim != unbind_dim: + # construct the permute node args, which has the same shape as the slice node + # then it has the same dim as the unbind_input, i.e., shape of cat + 1 + with graph.inserting_after(cat_node): + permute_list = list(range(len(cat_shape) + 1)) + permute_list[unbind_dim], permute_list[cat_dim] = ( + permute_list[cat_dim], + permute_list[unbind_dim], + ) + permute_node = graph.call_function( + torch.permute, + args=(unbind_input, permute_list), + ) + permute_node.meta["example_value"] = torch.permute( + unbind_input.meta["example_value"], permute_list + ) # type: ignore[arg-type] + else: + permute_node = unbind_input + with graph.inserting_after(permute_node): + reshape_node = graph.call_function( + torch.reshape, args=(permute_node, tuple(cat_shape)) + ) + reshape_node.meta["example_value"] = torch.reshape( + permute_node.meta["example_value"], tuple(cat_shape) + ) # type: ignore[arg-type] + return reshape_node + + +def update_args_from_unbind_getitem( + graph: torch.fx.Graph, + node: torch.fx.Node, # cat or stack node + getitem_indices: list[int], + parents_seen: list[torch.fx.Node], + new_cat_args: list[torch.fx.Node], + new_cat_args_meta: list[torch.fx.Node], + idx_to_getitems: dict[int, torch.fx.Node], + threshold_to_cat: int = 2, +): + unbind_input = get_arg_value(parents_seen[-1], 0, "input") # split or unbind input + unbind_dim = get_arg_value(parents_seen[-1], 1, "dim") # split or unbind dim + cat_dim = get_arg_value(node, 1, "dim") # cat or stack dim + # case 1: the number of getitems is the same as the split size, eliminate the split + size = list(unbind_input.meta["example_value"].shape)[unbind_dim] + if size == len(getitem_indices): + cat_shape = torch.cat( + [idx_to_getitems[i].meta["example_value"] for i in getitem_indices], + dim=cat_dim, + ).shape + # we can merge the getitems from the previous parent + reshape_node = reshape_cat_node( + graph, node, unbind_input, cat_dim, unbind_dim, cat_shape + ) + new_cat_args.append(reshape_node) + new_cat_args_meta.append(reshape_node.meta["example_value"]) + elif len(getitem_indices) >= threshold_to_cat and is_sorted_and_consecutive( + getitem_indices + ): + # case 2: the number of getitems is smaller than the split size but larger than the threshold + # we need to slice the input of parent + cat_shape = torch.cat( + [idx_to_getitems[i].meta["example_value"] for i in getitem_indices], + dim=cat_dim, + ).shape + slice_list = [] + for i in range(len(cat_shape) + 1): + if i != unbind_dim: + slice_list.append(slice(None, None, None)) # start, end, step + else: + slice_list.append( + slice(getitem_indices[0], getitem_indices[-1] + 1, None) + ) + with graph.inserting_after(node): + slice_node = graph.call_function( + operator.getitem, + args=(unbind_input, tuple(slice_list)), + ) + slice_node.meta["example_value"] = torch.narrow( + unbind_input.meta["example_value"], + unbind_dim, + getitem_indices[0], + getitem_indices[-1] - getitem_indices[0] + 1, + ) + reshape_node = reshape_cat_node( + graph, node, slice_node, cat_dim, unbind_dim, cat_shape + ) + new_cat_args.append(reshape_node) + new_cat_args_meta.append(reshape_node.meta["example_value"]) + else: + # case 3: the number of getitems is smaller than the threshold, no merge is done + # get the getitems based on the indexes + for i in getitem_indices: + new_cat_args.append(idx_to_getitems[i]) + new_cat_args_meta.append(idx_to_getitems[i].meta["example_value"]) + + +def construct_cat_args( + graph: torch.fx.Graph, + cat_or_stack_node: torch.fx.Node, + inputs: list[torch.fx.Node], + split_or_unbind_node: torch.fx.Node, + threshold_to_cat: int = 2, + run_update_func: Callable = update_args_from_split_getitem, # type: ignore[type-arg] +) -> tuple[list[torch.fx.Node], list[torch.Tensor]]: + new_cat_args, parents_seen, getitem_indices, idx_to_getitems = [], [], [], {} # type: ignore[var-annotated] + new_cat_args_meta = [] # type: ignore[var-annotated] + for input in inputs: + if input.target != operator.getitem: + # update the last arg based on getitem_indices and parents_seens + if len(parents_seen) > 0: + run_update_func( # type: ignore[arg-type, union-attr] + graph, + cat_or_stack_node, + getitem_indices, + parents_seen, + new_cat_args, + new_cat_args_meta, + idx_to_getitems, # type: ignore[arg-type, union-attr] + threshold_to_cat, + ) + new_cat_args.append(input) + new_cat_args_meta.append(input.meta["example_value"]) + # reset the indices array + getitem_indices, idx_to_getitems = [], {} + else: + # get the parent node of the getitem input + parent, idx = input.args[0], input.args[1] # type: ignore[union-attr] + if parent.target != split_or_unbind_node.target: # type: ignore[union-attr] + new_cat_args.append(input) + new_cat_args_meta.append(input.meta["example_value"]) + continue + # cannot use parents_seen to check since the first item could be non getitem node + if len(parents_seen) == 0: + parents_seen.append(parent) + idx_to_getitems[idx] = input + getitem_indices.append(idx) + # case: we only have one getitem input, and it is in the last position + if input == inputs[-1]: + new_cat_args.append(input) + new_cat_args_meta.append(input.meta["example_value"]) + continue + # if it is the last input in the tensors, we also check if it can be optimized + if parent != parents_seen[-1] or input == inputs[-1]: + if input == inputs[-1]: + getitem_indices.append(idx) + idx_to_getitems[idx] = input + run_update_func( # type: ignore[arg-type, union-attr] + graph, + cat_or_stack_node, + getitem_indices, + parents_seen, + new_cat_args, + new_cat_args_meta, + idx_to_getitems, # type: ignore[arg-type, union-attr] + threshold_to_cat, + ) + # reset the indices array for the next parent + # remember to add the last element since it is the first + # item in this round of parent + # add the parent to the list of seen parents + parents_seen.append(parent) + getitem_indices, idx_to_getitems = [idx], {idx: input} + else: + getitem_indices.append(idx) + idx_to_getitems[idx] = input + return new_cat_args, new_cat_args_meta + + +def remove_split_unbind_children(graph: torch.fx.Graph, inputs: list[torch.fx.Node]): + nodes = OrderedSet[Any]() + for input in inputs: + if input.target is operator.getitem: + nodes.add(input.args[0]) # type: ignore[union-attr] + if len(input.users.keys()) == 0: + graph.erase_node(input) + # check the split node to remove if it has no users + for node in nodes: + if len(node.users.keys()) == 0: # type: ignore[union-attr] + graph.erase_node(node) # type: ignore[arg-type] + + +# ############pattern to be optimized is######### + +# split_node(dim=1) -> user=multiple +# / \ ... / \ +# other inputs getitem getitem getitem -> user=multiple +# \ / \ +# cat(user=mul, dim=1) other_op +# | + +# ################after transformation############# + +# split_node(dim=1) other inputs -> -> user=multiple +# / \ +# cat (user=mul, dim=1, split_node) + + +@register_graph_pattern( + CallFunction( + torch.cat, + getitem_split, + dim=Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("split_cat_to_slices_pass"), +) +def split_cat_to_slices(match: Match, split_sections: list[int], dim: int): + if not isinstance(split_sections, (list, tuple)): # Unnormalized split + return + split_nodes = [node for node in match.nodes if node.target is torch.split] + if split_nodes: + split_node = next(node for node in split_nodes) + else: + # Handle the case where there are no nodes with a target of torch.split + return + split_dim = get_arg_value(split_node, 2, "dim") or 0 + graph = match.graph + threshold_to_cat = torch._inductor.config.pre_grad_fusion_options[ + "split_cat_to_slices_pass" + ].get("threshold_to_cat", 10) + # get the cat_node and check its inputs and meta data + next_users = find_next_users(split_node) + for cat_node in next_users: + if cat_node.target != torch.cat or not is_node_meta_valid(cat_node): + continue + cat_inputs = get_arg_value(cat_node, 0, "tensors") # type: ignore[union-attr] + new_cat_args, _ = construct_cat_args( + graph, + cat_node, + cat_inputs, + split_node, + threshold_to_cat, + update_args_from_split_getitem, + ) + # At least one node would be in the returned new_cat_args + # case 1: if new cat args has length 1, we can remove the cat node + if len(new_cat_args) == 1: + cat_node.replace_all_uses_with(new_cat_args[0]) + # remove inputs of cat_node if they have no users + cat_inputs = cat_node.args[0] # type: ignore[union-attr] + graph.erase_node(cat_node) + remove_split_unbind_children(graph, cat_inputs) # type: ignore[arg-type] + counters[backend]["split_cat_to_slices_pass"] += 1 + continue + if len(new_cat_args) > 1 and len(new_cat_args) < len(cat_inputs): + new_args = (new_cat_args,) + with graph.inserting_after(cat_node): + new_cat_node = graph.call_function( + torch.cat, + args=new_args, + # split and cat have the same dim + kwargs={"dim": split_dim}, + ) + cat_node.replace_all_uses_with(new_cat_node) + new_cat_node.meta.update(cat_node.meta) + # remove the cat node + graph.erase_node(cat_node) + remove_split_unbind_children(graph, cat_inputs) + counters[backend]["split_cat_to_slices_pass"] += 1 + + +# ############pattern to be optimized is######### + +# unbind(dim=0) -> user=multiple +# / \ ... / \ +# getitem getitem getitem getitem -> user=multiple +# \ / \ +# cat(user=mul, dim=1) other_op +# | + +# ################after transformation############# + +# input_of_unbind +# | \ +# slice +# | +# view +# | + + +@register_graph_pattern( + CallFunction( + torch.cat, + getitem_unbind, + dim=Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("unbind_cat_to_view_pass"), +) +def unbind_cat_to_view(match: Match, unbind_input: torch.fx.Node, dim: int): + unbind_node = next(node for node in match.nodes if node.target is torch.unbind) + graph = match.graph + # get the cat_node and check its inputs and meta data + next_users = find_next_users(unbind_node) + threshold_to_cat = torch._inductor.config.pre_grad_fusion_options[ + "unbind_cat_to_view_pass" + ].get("threshold_to_cat", 10) + # get the cat_node and check its inputs and meta data + for cat_node in next_users: + if cat_node.target != torch.cat or not is_node_meta_valid(cat_node): + continue + inputs = get_arg_value(cat_node, 0, "tensors") # type: ignore[union-attr] + new_cat_args, new_cat_args_meta = construct_cat_args( + graph, + cat_node, + inputs, + unbind_node, + threshold_to_cat, + update_args_from_unbind_getitem, + ) + # get the view shape + # At least one node would be in the returned new_cat_args + # case 1: only one node in the new cat args, don't need to cat + if len(new_cat_args) == 1: + cat_node.replace_all_uses_with(new_cat_args[0]) + # remove inputs of cat_node if they have no users + cat_inputs = cat_node.args[0] # type: ignore[union-attr] + graph.erase_node(cat_node) + remove_split_unbind_children(graph, cat_inputs) # type: ignore[arg-type] + counters[backend]["unbind_cat_to_view_pass"] += 1 + continue + if len(new_cat_args) > 1 and len(new_cat_args) < len(inputs): + # get the view shape + cat_dim = get_arg_value(cat_node, 1, "dim") + with graph.inserting_after(cat_node): + new_cat_node = graph.call_function( + torch.cat, + args=(new_cat_args,), + kwargs={"dim": cat_dim}, + ) + new_cat_node.meta["example_value"] = torch.cat( + new_cat_args_meta, dim=cat_dim + ) # type: ignore[arg-type] + cat_node.replace_all_uses_with(new_cat_node) + new_cat_node.meta.update(cat_node.meta) + # remove inputs of cat_node if they have no users + cat_inputs = cat_node.args[0] # type: ignore[union-attr] + graph.erase_node(cat_node) + remove_split_unbind_children(graph, cat_inputs) # type: ignore[arg-type] + counters[backend]["unbind_cat_to_view_pass"] += 1 + + +def reshape_cat_node_to_stack( + graph: torch.fx.Graph, + cat_node: torch.fx.Node, + stack_node: torch.fx.Node, + split_or_unbind_dim: int, +) -> None: + # reshape the cat node to the stack node shape + stack_shape = stack_node.meta["example_value"].shape + stack_dim = _get_dim(stack_node) + if stack_dim != split_or_unbind_dim: + # case 1: the stack dim is not the same as the split dim + # we need to reshape the split input before we do the reshape + reshape_list = list(stack_shape) + reshape_list[stack_dim], reshape_list[split_or_unbind_dim] = ( + reshape_list[split_or_unbind_dim], + reshape_list[stack_dim], + ) + reshape_node = graph.call_function( + torch.reshape, + args=(cat_node, tuple(reshape_list)), + ) + reshape_node.meta["example_value"] = torch.reshape( + cat_node.meta["example_value"], + tuple(reshape_list), # pyrefly: ignore [bad-argument-type] + ) + permute_list = list(range(len(stack_shape))) + permute_list[stack_dim], permute_list[split_or_unbind_dim] = ( + permute_list[split_or_unbind_dim], + permute_list[stack_dim], + ) + permute_node = graph.call_function( + torch.permute, + args=(reshape_node, permute_list), + ) + permute_node.meta["example_value"] = torch.permute( + reshape_node.meta["example_value"], permute_list + ) + else: + # case 2: the stack dim is the same as the split dim + # we can directly reshape the split input + permute_node = cat_node + reshape_node = graph.call_function( + torch.Tensor.view, + args=(permute_node, *stack_shape), # type: ignore[arg-type] + ) + stack_node.replace_all_uses_with(reshape_node) + reshape_node.meta.update(stack_node.meta) + stack_inputs = stack_node.args[0] # type: ignore[union-attr] + # remove stack node + graph.erase_node(stack_node) + # check the input of stack node, and remove nodes that have no users + remove_split_unbind_children(graph, stack_inputs) # type: ignore[arg-type] + + +def convert_reshape_cat_arg_to_stack( + graph: torch.fx.Graph, + cat_node: torch.fx.Node, + stack_node: torch.fx.Node, + stack_node_shape: torch.Size, + stack_dim: int, + split_dim: int, +) -> torch.fx.Node: + # reshape the cat node to the stack node shape + cat_shape = cat_node.meta["example_value"].shape + if stack_dim != split_dim: + permute_list = list(range(len(cat_shape))) + permute_list[stack_dim], permute_list[split_dim] = ( + permute_list[split_dim], + permute_list[stack_dim], + ) + permute_node = graph.call_function( + torch.permute, + args=(cat_node, permute_list), + ) + permute_node.meta["example_value"] = torch.permute( + cat_node.meta["example_value"], permute_list + ) + else: + permute_node = cat_node + reshape_node = graph.call_function( + torch.Tensor.view, + args=(permute_node, tuple(stack_node_shape)), # type: ignore[arg-type] + ) + reshape_node.meta["example_value"] = torch.Tensor.view( + permute_node.meta["example_value"], + tuple(stack_node_shape), # type: ignore[arg-type] + ) + return reshape_node + + +# ############pattern to be optimized is######### +# | | +# split split (dim=1) +# / \ / \ +# getitem ... getitem other ops +# \ | / / +# stack(user=mul, dim=1 or 2) -> can be different dim +# | + +# ################after transformation############# + +# / \ ... / \ +# getitem getitem getitem getitem -> user=multiple +# \ / +# cat(user=mul, dim=1) cat_other_opts +# \ / +# cat +# | +# view +# | + + +@register_graph_pattern( + CallFunction( + torch.stack, + getitem_split, + dim=Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("split_stack_to_cats_pass"), +) +def split_stack_to_cats(match: Match, split_sections: list[int], dim: int): + if not isinstance(split_sections, (list, tuple)): # Unnormalized split + return + split_node = next(node for node in match.nodes if node.target is torch.split) + split_dim = get_arg_value(split_node, 2, "dim") or 0 + graph = match.graph + threshold_to_cat = torch._inductor.config.pre_grad_fusion_options[ + "split_stack_to_cats_pass" + ].get("threshold_to_cat", 10) + # get the stack_node and check its inputs and meta data + next_users = find_next_users(split_node) + for stack_node in next_users: + if stack_node.target != torch.stack or not is_node_meta_valid(stack_node): + continue + inputs = get_arg_value(stack_node, 0, "tensors") # type: ignore[union-attr] + new_cat_args, new_cat_args_meta = construct_cat_args( + graph, + stack_node, + inputs, + split_node, + threshold_to_cat, + update_args_from_split_getitem, + ) + # At least one node would be in the returned new_cat_args + # case 1: only one node in the new cat args, don't need to cat + if len(new_cat_args) == 1: + reshape_cat_node_to_stack(graph, new_cat_args[0], stack_node, split_dim) + counters[backend]["split_stack_to_cats_pass"] += 1 + continue + if len(new_cat_args) > 1 and len(new_cat_args) < len(inputs): + with graph.inserting_after(stack_node): + cat_node = graph.call_function( + torch.cat, + args=(new_cat_args,), + kwargs={"dim": split_dim}, + ) + cat_node.meta["example_value"] = torch.cat( # type: ignore[arg-type] + new_cat_args_meta, dim=split_dim + ) + reshape_cat_node_to_stack(graph, cat_node, stack_node, split_dim) + counters[backend]["split_stack_to_cats_pass"] += 1 + + +# ############pattern to be optimized is######### + +# unbind(dim=1) -> user=multiple +# \ ... / \ +# others getitem getitem getitem -> user=multiple +# \ \ / \ +# stack(user=mul, dim=1) other_op +# | + +# ################after transformation############# + +# input_of_unbind +# | \ +# slice +# | +# view others +# | / +# stack +# | + + +@register_graph_pattern( + CallFunction( + torch.stack, + getitem_unbind, + dim=Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("unbind_stack_to_slices_pass"), +) +def unbind_stack_to_slices(match: Match, unbind_input: torch.fx.Node, dim: int): + unbind_node = next(node for node in match.nodes if node.target is torch.unbind) + graph = match.graph + # get the cat_node and check its inputs and meta data + next_users = find_next_users(unbind_node) + threshold_to_cat = torch._inductor.config.pre_grad_fusion_options[ + "unbind_stack_to_slices_pass" + ].get("threshold_to_cat", 10) + # get the cat_node and check its inputs and meta data + for stack_node in next_users: + if stack_node.target != torch.stack or not is_node_meta_valid(stack_node): + continue + inputs = get_arg_value(stack_node, 0, "tensors") # type: ignore[union-attr] + new_cat_args, new_cat_args_meta = construct_cat_args( + graph, + stack_node, + inputs, + unbind_node, + threshold_to_cat, + update_args_from_unbind_getitem, + ) + unbind_dim = get_arg_value(unbind_node, 1, "dim") or 0 + # At least one node would be in the returned new_cat_args + # case 1: only one node in the new cat args, don't need to cat + if len(new_cat_args) == 1: + reshape_cat_node_to_stack(graph, new_cat_args[0], stack_node, unbind_dim) + counters[backend]["unbind_stack_to_slices_pass"] += 1 + continue + if len(new_cat_args) > 1 and len(new_cat_args) < len(inputs): + # get the view shape + cat_dim = get_arg_value(stack_node, 1, "dim") + with graph.inserting_after(stack_node): + new_cat_node = graph.call_function( + torch.cat, + args=(new_cat_args,), + kwargs={"dim": cat_dim}, + ) + new_cat_node.meta["example_value"] = torch.cat( + new_cat_args_meta, dim=cat_dim + ) + reshape_cat_node_to_stack(graph, new_cat_node, stack_node, unbind_dim) + counters[backend]["unbind_stack_to_slices_pass"] += 1 + + +# ############pattern to be optimized is######### +# input +# | +# split(dim=1) -> user=multiple +# \ \ +# others getitem getitem +# \ \ / +# reshape reshape reshape other_op +# \ \ / / +# stack(user=mul, dim=0) +# | + +# ################after transformation############# +# input +# | +# permute +# | +# reshape others +# | / +# cat (dim=0) +# | + + +def get_view_shape_list(cat_arg: torch.fx.Node, stack_dim: int) -> list[int]: + # cat_arg must be the split input + view_shape_list = [] + for user in cat_arg.users: + if user.target is torch.split: + for getitem in user.users: + if getitem.target is operator.getitem: + reshape_user = [ + user for user in getitem.users if user.target is torch.reshape + ] + if len(reshape_user) > 0: + view_shape_list = list( + reshape_user[0] + .meta["example_value"] + .unsqueeze(stack_dim) + .shape + ) + view_shape_list[stack_dim] = -1 + return view_shape_list + return view_shape_list + + +@register_graph_pattern( + CallFunction( + torch.stack, + reshape_getitem_split, + dim=Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("move_reshape_out_of_split_stack_pass"), +) +def move_reshape_out_of_split_stack(match: Match, *args, **kwargs): + split_node = next(node for node in match.nodes if node.target is torch.split) + split_dim = _get_dim(split_node) + split_users = list(split_node.users.keys()) + stack_nodes = [node for node in match.nodes if node.target is torch.stack] + graph = match.graph + threshold_to_cat = torch._inductor.config.pre_grad_fusion_options[ + "move_reshape_out_of_split_stack_pass" + ].get("threshold_to_cat", 10) + for stack_node in stack_nodes: + if not is_node_meta_valid(stack_node): + log.debug("example value absent for node: %s", stack_node) + continue + stack_dim = _get_dim(stack_node) + stack_inputs = get_arg_value(stack_node, 0, "tensors") # type: ignore[union-attr] + inputs = [] + for stack_input in stack_inputs: + if stack_input.target != torch.reshape: + inputs.append(stack_input) + else: + inputs.append(stack_input.args[0]) # type: ignore[union-attr] + new_cat_args, _new_cat_args_meta = construct_cat_args( + graph, + stack_node, + inputs, + split_node, + threshold_to_cat, + update_args_from_split_getitem, + ) + # At least one node would be in the returned new_cat_args + # case 1: only one node in the new cat args, don't need to cat + if len(new_cat_args) == 1: + reshape_node = convert_reshape_cat_arg_to_stack( + graph, + new_cat_args[0], + stack_node, + stack_node.meta["example_value"].shape, + stack_dim, + split_dim, + ) + stack_node.replace_all_uses_with(reshape_node) + # remove stack node + graph.erase_node(stack_node) + # check the input of stack node, and remove nodes that have no users + remove_split_unbind_children(graph, stack_inputs) # type: ignore[arg-type] + remove_split_unbind_children(graph, split_users) # type: ignore[arg-type] + counters[backend]["move_reshape_out_of_split_stack_pass"] += 1 + continue + if len(new_cat_args) > 1 and len(new_cat_args) < len(inputs): + # decompose the cat args into multiple stack nodes, i.e., we stack + # all the nodes exist in the stack inputs and reshape the rest followed by a cat + stack_node_input, stack_node_input_meta, cat_inputs = [], [], [] # type: ignore[var-annotated] + for cat_arg in new_cat_args: + if cat_arg not in stack_inputs: + if len(stack_node_input) > 0: + with graph.inserting_after(stack_node): + decomposed_stack_node = graph.call_function( + torch.stack, + args=(stack_node_input,), + kwargs={"dim": stack_dim}, + ) + decomposed_stack_node.meta["example_value"] = torch.stack( + stack_node_input_meta, dim=stack_dim + ) + cat_inputs.append(decomposed_stack_node) + # cat_arg must be the split input + view_shape_list = get_view_shape_list(cat_arg, stack_dim) + stack_node_shape = torch.reshape( + cat_arg.meta["example_value"], tuple(view_shape_list) + ).shape # type: ignore[union-attr] + cat_inputs.append( + convert_reshape_cat_arg_to_stack( + graph, + cat_arg, + stack_node, + stack_node_shape, + stack_dim, + split_dim, + ) + ) + stack_node_input, stack_node_input_meta = [], [] + else: + stack_node_input.append(cat_arg) + stack_node_input_meta.append(cat_arg.meta["example_value"]) + + if len(stack_node_input) > 0: + with graph.inserting_after(stack_node): + decomposed_stack_node = graph.call_function( + torch.stack, + args=(stack_node_input,), + kwargs={"dim": stack_dim}, + ) + decomposed_stack_node.meta["example_value"] = torch.stack( + stack_node_input_meta, dim=stack_dim + ) + cat_inputs.append(decomposed_stack_node) + + with graph.inserting_after(stack_node): + cat_node = graph.call_function( + torch.cat, + args=(cat_inputs,), + kwargs={"dim": stack_dim}, + ) + stack_node.replace_all_uses_with(cat_node) + cat_node.meta.update(stack_node.meta) + graph.erase_node(stack_node) + remove_split_unbind_children(graph, stack_inputs) # type: ignore[arg-type] + remove_split_unbind_children(graph, split_users) # type: ignore[arg-type] + counters[backend]["move_reshape_out_of_split_stack_pass"] += 1 + + +view_getitem_split_aten = ListOf( + CallFunction( + [torch.ops.aten.reshape.default], + CallFunction( + operator.getitem, + CallFunctionVarArgs( + torch.ops.aten.split_with_sizes.default, users=MULTIPLE + ), + Ignored(), + _users=MULTIPLE, + ), + Arg(), + _users=MULTIPLE, + ), + partial=True, +) + + +@register_graph_pattern( + CallFunction( + torch.ops.aten.cat.default, + view_getitem_split_aten, + dim=Ignored(), + _users=MULTIPLE, + ), + pass_dict=construct_pattern_matcher_pass("move_view_after_cat_aten_pass"), +) +def move_view_after_cat(match: Match, *args, **kwargs): + split_node = next( + node + for node in match.nodes + if node.target is torch.ops.aten.split_with_sizes.default + ) + split_input, split_section, split_dim = _get_split_args_default(split_node) + split_users = list(split_node.users.keys()) + getitem_indices = [ + getitem.args[1] for getitem in split_users if getitem.target is operator.getitem + ] + if not is_sorted_and_consecutive(getitem_indices): # type: ignore[arg-type] + return + cat_nodes = [ + node for node in match.nodes if node.target is torch.ops.aten.cat.default + ] + graph = match.graph + for cat_node in cat_nodes: + if not is_node_meta_valid(cat_node): + log.debug("example value absent for node: %s", cat_node) + continue + cat_dim = _get_dim(cat_node) + cat_inputs = get_arg_value(cat_node, 0, "tensors") # type: ignore[union-attr] + # we only consider the following special case + if len(cat_inputs) != len(split_section): + continue + # check if the cat inputs are all the view nodes + if not all( + view_node.target is torch.ops.aten.reshape.default + for view_node in cat_inputs + ): + continue + # check if the view nodes are all from getitem nodes + if not all( + view_node.args[0].target is operator.getitem for view_node in cat_inputs + ): + continue + view_indices = [view.args[0].args[1] for view in cat_inputs] + if not is_sorted_and_consecutive(view_indices): # type: ignore[arg-type] + continue + if cat_dim != split_dim: + # construct permute node + permute_list = list(range(len(cat_node.meta["val"].shape) + 1)) + permute_list[split_dim], permute_list[cat_dim] = ( + permute_list[cat_dim], + permute_list[split_dim], + ) + permute_node = graph.call_function( + torch.ops.aten.permute.default, + args=(split_input, permute_list), + ) + else: + permute_node = split_input + + with graph.inserting_before(cat_node): + view_node = graph.call_function( + torch.ops.aten.reshape.default, + args=(permute_node, list(cat_node.meta["val"].shape)), + ) + cat_node.replace_all_uses_with(view_node) + view_node.meta.update(cat_node.meta) + graph.erase_node(cat_node) + counters[backend]["move_view_after_cat_aten_pass"] += 1 + + +def match_einsum_strings(s: str) -> bool: + """ + This function takes a string s as input, where s is in the format "3 letter string, + 4 letter string -> 3 letter string". + It checks if the strings match the rule and returns True if they do, False otherwise. + + The rule is: + - The three strings have the same first two characters. + - The first two strings have the same third character. + - The second and third strings have the same last character. + """ + + # Split the input string into parts + parts = s.replace("->", ",").split(",") + + # Strip leading/trailing whitespaces from each part + parts = [part.strip() for part in parts] + + # Check if we have exactly three parts + if len(parts) != 3: + return False + + # Extract the strings + s1, s2, s3 = parts + + # Check if the strings have the correct lengths + if len(s1) != 3 or len(s2) != 4 or len(s3) != 3: + return False + + # Check the rule + return s1[:2] == s2[:2] == s3[:2] and s1[2] == s2[2] and s2[3] == s3[2] + + +@register_graph_pattern( + CallFunctionVarArgs(torch.functional.einsum, users=MULTIPLE), + pass_dict=construct_pattern_matcher_pass("einsum_to_pointwise_pass"), +) +def replace_einsum_to_pointwise(match: Match, *args, **kwargs): + def repl(input, weights): + return (input.unsqueeze(-1) * weights).sum(-2) + + def should_replace_einsum(einsum_node) -> bool: + equation = get_arg_value(einsum_node, 0) + users = einsum_node.users.keys() + # for now, we only consider the case of two operands + return ( + len(einsum_node.args) == 3 + and is_node_meta_valid(input) + and is_node_meta_valid(weights) + and any( + user.target == "add" or user.target is operator.add for user in users + ) + and match_einsum_strings(equation) + ) + + einsum_node = match.nodes[0] + input, weights = get_arg_value(einsum_node, 1), get_arg_value(einsum_node, 2) + if should_replace_einsum(einsum_node): + # pyrefly: ignore [bad-argument-type] + match.replace_by_example(repl, [input, weights]) + counters[backend]["einsum_to_pointwise_pass"] += 1 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/spmd_check.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/spmd_check.py new file mode 100644 index 0000000000000000000000000000000000000000..b51004107a10723f996fa5b78fca7ef6df0ddbda --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/spmd_check.py @@ -0,0 +1,228 @@ +"""SPMD graph verification for overlap scheduling. + +Verifies all ranks have identical FX graph structure before collective +reordering passes. Non-SPMD graphs cause NCCL collective ordering +mismatches and hangs. +""" + +import hashlib +import logging +from collections import Counter + +import torch +from torch._inductor import config +from torch._logging import trace_structured + + +log = logging.getLogger(__name__) + + +def _compute_hash(gm: torch.fx.GraphModule) -> int | None: + """Compute a structural hash of the graph including tensor metadata. + + Uses FxGraphCachePickler(device_id_agnostic=True) to serialize + (target, val) per call_function node, capturing op targets and + FakeTensor metadata (dtype, shape, stride, etc.) with device indices + normalized to 0. + + Returns None if the graph contains unpicklable objects. + """ + from torch._inductor.codecache import BypassFxGraphCache, FxGraphCachePickler + + try: + pickler = FxGraphCachePickler(gm, device_id_agnostic=True) + data = pickler.dumps( + tuple( + (str(n.target), n.meta.get("val")) + for n in gm.graph.nodes + if n.op == "call_function" + ) + ) + digest = hashlib.blake2b(data, digest_size=8).digest() + return int.from_bytes(digest, "big", signed=True) + except BypassFxGraphCache: + # FxGraphCachePickler can't serialize certain objects: + # mkldnn tensors, BackwardState, torchbind objects, or general + # pickle failures. Skip the SPMD check gracefully. + log.warning("SPMD check: skipping, unpicklable graph objects", exc_info=True) + return None + + +def _build_diag_fingerprint( + gm: torch.fx.GraphModule, +) -> tuple[tuple[str, str | None], ...]: + """Build human-readable fingerprint for mismatch diagnostics. + + Only called on the rare mismatch path. + """ + from torch._inductor.codecache import extract_tensor_metadata_for_cache_key + + entries: list[tuple[str, str | None]] = [] + for n in gm.graph.nodes: + if n.op != "call_function": + continue + target_str = str(n.target) + val = n.meta.get("val") + entries.append( + ( + target_str, + _format_val_metadata(val, extract_tensor_metadata_for_cache_key), + ) + ) + return tuple(entries) + + +def _format_val_metadata(val: object, extract_fn: object) -> str | None: + """Format node val metadata for human-readable diagnostics.""" + if val is None: + return None + if isinstance(val, torch.Tensor): + return str(extract_fn(val)) # type: ignore[operator] + if isinstance(val, (tuple, list)): + parts = [] + for v in val: + if isinstance(v, torch.Tensor): + parts.append(str(extract_fn(v))) # type: ignore[operator] + else: + parts.append(str(type(v).__name__)) + return f"({', '.join(parts)})" + return str(type(val).__name__) + + +def spmd_check(gm: torch.fx.GraphModule) -> bool: + """Verify all ranks have identical FX graph structure (SPMD). + + Computes a structural hash (op targets + tensor metadata including + shapes, dtypes, strides) and compares across ranks. + On mismatch, emits a diagnostic report to stdout, logging, and + trace_structured. + + Returns True if graphs match (SPMD), False on mismatch. + """ + import torch.distributed as dist + + if not dist.is_initialized() or dist.get_world_size() <= 1: + return True + + structure_hash = _compute_hash(gm) + if structure_hash is None: + return True + + from torch._subclasses.fake_tensor import unset_fake_temporarily + from torch.distributed.distributed_c10d import _get_default_group + + pg = _get_default_group() + world_size = dist.get_world_size() + rank = dist.get_rank() + + with unset_fake_temporarily(): + all_hashes: list[int] = [0] * world_size + dist.all_gather_object(all_hashes, structure_hash, pg) + + if all(h == all_hashes[0] for h in all_hashes): + return True + + # Mismatch detected — build and gather diagnostic fingerprints + fingerprint = _build_diag_fingerprint(gm) + with unset_fake_temporarily(): + all_fingerprints: list[tuple[object, ...]] = [() for _ in range(world_size)] + dist.all_gather_object(all_fingerprints, fingerprint, pg) + + report = _build_mismatch_report(all_fingerprints, rank, world_size) + + print(report, flush=True) + log.warning("\n%s", report) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_spmd_graph_mismatch", + "encoding": "string", + }, + payload_fn=lambda: report, + ) + + if config.aten_distributed_optimizations.spmd_mismatch == "error": + raise RuntimeError( + "SPMD graph verification failed. " + 'Set aten_distributed_optimizations.spmd_mismatch="warn" ' + "to warn instead of fail.\n" + report + ) + + return False + + +def _entry_target(entry: object) -> str: + """Extract the target string from a fingerprint entry.""" + if isinstance(entry, tuple): + return str(entry[0]) + return str(entry) + + +def _entry_metadata(entry: object) -> str: + """Format metadata from a fingerprint entry, if present.""" + if isinstance(entry, tuple) and len(entry) >= 2: + meta = entry[1] + if meta is not None: + return f" meta={meta}" + return "" + + +def _build_mismatch_report( + all_fingerprints: list[tuple[object, ...]], + rank: int, + world_size: int, +) -> str: + """Build diagnostic report for SPMD graph mismatch.""" + lines = [ + "=" * 80, + f"SPMD GRAPH MISMATCH — rank {rank}, world_size={world_size}", + "=" * 80, + ] + + # Node count per rank + counts = [len(t) for t in all_fingerprints] + lines.append("NODE COUNTS PER RANK:") + for r in range(world_size): + marker = " <--" if counts[r] != counts[0] else "" + lines.append(f" rank {r}: {counts[r]} call_function nodes{marker}") + lines.append("") + + # Find entries that differ + ref = all_fingerprints[0] + for r in range(1, world_size): + other = all_fingerprints[r] + if other == ref: + continue + lines.append(f"DIFFS rank 0 vs rank {r}:") + + # Show first few positional differences + max_diffs = 10 + shown = 0 + for i, (a, b) in enumerate(zip(ref, other)): + if a != b and shown < max_diffs: + lines.append(f" node {i}:") + lines.append(f" rank 0: {_entry_target(a)}{_entry_metadata(a)}") + lines.append(f" rank {r}: {_entry_target(b)}{_entry_metadata(b)}") + shown += 1 + + # Also show count-based diffs for op targets + ref_targets = [_entry_target(e) for e in ref] + other_targets = [_entry_target(e) for e in other] + + ref_counts = Counter(ref_targets) + other_counts = Counter(other_targets) + only_ref = ref_counts - other_counts + only_other = other_counts - ref_counts + if only_ref: + lines.append(" Only on rank 0:") + for op, cnt in only_ref.most_common(10): + lines.append(f" {op} (x{cnt})") + if only_other: + lines.append(f" Only on rank {r}:") + for op, cnt in only_other.most_common(10): + lines.append(f" {op} (x{cnt})") + lines.append("") + + lines.append("=" * 80) + return "\n".join(lines) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1e11dfb44e9b5779eeb0694deb77562549b0067e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/utils.py @@ -0,0 +1,122 @@ +import torch.fx as fx +from torch.utils._ordered_set import OrderedSet + + +class BitsetAncestors: + """Precomputed transitive ancestor sets using Python arbitrary-precision ints. + + Each node gets an index i (0..N-1) from topological order. A node's + ancestor set is a single Python ``int`` where bit j is set iff node j + is a transitive ancestor. Python ``int`` is arbitrary-precision, so for + N nodes each int is ~N/8 bytes internally (~N/64 machine words). + + The key advantage over ``dict[fx.Node, OrderedSet[fx.Node]]`` is that + CPython implements ``int |= int`` as a C-level loop over machine words, + making the transitive closure O(N^2 / 64) instead of O(N^2) in + Python-level set operations. + + Example -- diamond graph (edges point downward):: + + a index 0 + / \\ + b c index 1, 2 + \\ / + d index 3 + + Ancestor bitsets:: + + a: 0b0000 = 0 (no ancestors) + b: 0b0001 = 1 (bit 0 -> a) + c: 0b0001 = 1 (bit 0 -> a) + d: 0b0111 = 7 (bits 0,1,2 -> a, b, c) + + How d's bitset is built (d has parents b and c):: + + b = 0 + # parent b (idx=1): set bit 1, merge b's ancestors + b |= (1 << 1) | bits[1] # b = 0b0010 | 0b0001 = 0b0011 + # parent c (idx=2): set bit 2, merge c's ancestors + b |= (1 << 2) | bits[2] # b = 0b0011 | 0b0100 | 0b0001 = 0b0111 + bits[3] = 0b0111 + + Querying:: + + ancestors = BitsetAncestors(nodes) + ancestors.is_ancestor(a, d) # (bits[3] >> 0) & 1 -> True + ancestors.has_dep(a, d) # True (a is ancestor of d) + list(ancestors.iter_ancestors(d)) # [a, b, c] via bit-scan + + Iteration uses the x & -x trick to isolate the lowest set bit:: + + bits = 0b0111 + bits & -bits = 0b0001 -> idx 0 -> yield a, clear: 0b0110 + bits & -bits = 0b0010 -> idx 1 -> yield b, clear: 0b0100 + bits & -bits = 0b0100 -> idx 2 -> yield c, clear: 0b0000 + + Args: + nodes: topologically sorted list of FX nodes. + extra_inputs: optional additional edges beyond the FX graph + (e.g. hiding-interval deps in the overlap bucketer). + """ + + def __init__( + self, + nodes: list[fx.Node], + extra_inputs: dict[fx.Node, OrderedSet[fx.Node]] | None = None, + ): + n = len(nodes) + node_to_idx: dict[fx.Node, int] = {nd: i for i, nd in enumerate(nodes)} + bits = [0] * n + extra = extra_inputs or {} + + for i, node in enumerate(nodes): + b = 0 + for inp in node._input_nodes: + j = node_to_idx.get(inp) + if j is not None: + b |= (1 << j) | bits[j] + for inp in extra.get(node, ()): + j = node_to_idx.get(inp) + if j is not None: + b |= (1 << j) | bits[j] + bits[i] = b + + self._bits = bits + self._node_to_idx = node_to_idx + self._idx_to_node = nodes + + def is_ancestor(self, ancestor: fx.Node, descendant: fx.Node) -> bool: + """O(1) test: is ``ancestor`` a transitive ancestor of ``descendant``?""" + anc_idx = self._node_to_idx.get(ancestor) + desc_idx = self._node_to_idx.get(descendant) + if anc_idx is None or desc_idx is None: + return False + return bool((self._bits[desc_idx] >> anc_idx) & 1) + + def has_dep(self, n1: fx.Node, n2: fx.Node) -> bool: + """Check if either node is an ancestor of the other.""" + return self.is_ancestor(n1, n2) or self.is_ancestor(n2, n1) + + def get_ancestor_bits(self, node: fx.Node) -> int: + """Return the raw ancestor bitset for ``node``.""" + return self._bits[self._node_to_idx[node]] + + def node_bit(self, node: fx.Node) -> int: + """Return the single-bit mask ``1 << idx`` for ``node``.""" + return 1 << self._node_to_idx[node] + + def ancestors_intersect(self, node: fx.Node, mask: int) -> bool: + """Check if any ancestor of ``node`` is set in ``mask``.""" + idx = self._node_to_idx.get(node) + if idx is None: + return False + return bool(self._bits[idx] & mask) + + def iter_ancestors(self, node: fx.Node): + """Yield all ancestors of ``node`` via lowest-bit scan.""" + bits = self._bits[self._node_to_idx[node]] + idx_to_node = self._idx_to_node + while bits: + idx = (bits & -bits).bit_length() - 1 + yield idx_to_node[idx] + bits &= bits - 1 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/fx_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..54544d367bdef009064f9a0b4e8f10c0ff818a2d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/fx_utils.py @@ -0,0 +1,931 @@ +# mypy: allow-untyped-defs +import contextlib +import operator +import warnings +from collections import defaultdict +from collections.abc import ( + Callable, + Collection, + Container, + Generator, + Iterable, + Mapping, +) +from dataclasses import dataclass +from functools import partial +from itertools import chain +from typing import Any + +import sympy + +import torch +import torch.fx +from torch._dispatch.python import enable_python_dispatcher +from torch._inductor.fx_passes.control_dependencies import control_deps +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.fx.experimental.symbolic_shapes import ( + compute_unbacked_bindings, + rebind_unbacked, + statically_known_true, + sym_eq, +) +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import tree_map +from torch.utils._typing_utils import not_none +from torch.utils.flop_counter import flop_registry + +from .virtualized import V + + +# Check the pattern: (nn.module, F.function/torch.Tensor.method) matched. +# Works for length 2 patterns with 1 module and 1 function/method. +def matches_module_function_pattern( + pattern: tuple[type[torch.nn.modules.Module], Callable[..., Any]], + node: torch.fx.Node, + modules: dict[str, torch.nn.modules.Module], +) -> bool: + if len(node.args) == 0: + return False + if not isinstance(node.args[0], torch.fx.Node) or not isinstance( + node, torch.fx.Node + ): + return False + # the first node is call_module + if node.args[0].op != "call_module": + return False + if not isinstance(node.args[0].target, str): + return False + if node.args[0].target not in modules: + return False + if type(modules[node.args[0].target]) is not pattern[0]: + return False + # the second node is call_function or call_method + if node.op != "call_function" and node.op != "call_method": + return False + if node.target != pattern[1]: + return False + # make sure node.args[0] output is only used by current node. + if len(node.args[0].users) > 1: + return False + return True + + +def _is_fake_tensor_same( + new: Any, + old: Any, + existing_storages: Mapping[int, int], + *, + check_strides: bool = True, + check_storage: bool = True, + node: torch.fx.Node | None = None, + recursive_ids: OrderedSet[tuple[int, int]] | None = None, +) -> bool: + """Validate that two FakeTensors (or iterables thereof) are the same, including + storage locations if enabled. + + check_strides: disabling this flag will remove checks for striding. + check_storage: disabling this flag will remove checks for storage offset and + location. This is useful for subgraph argument and output updating, where storage + location can change without invalidating the subgraph. + recursive_ids: This is only for use when recursing through collections, and must not + be supplied by users of this function.""" + + def is_intlist_same(new, old): + # sym_eq builds a symbolic conjunction and statically_known_true then + # evaluates it, which is a lot of work for the common case where the + # two sizes/strides are the very same objects. Identity, or equality + # between concrete ints, already implies equality. + if len(new) == len(old) and all( + a is b or (type(a) is int and type(b) is int and a == b) + for a, b in zip(new, old) + ): + return True + return statically_known_true(sym_eq(new, old)) + + if type(new) is not type(old): + return False + + if not isinstance(new, torch.Tensor): + if new is None: + return old is None + + if isinstance(new, Collection): + if recursive_ids is None: + recursive_ids = OrderedSet() + + id_pair = (id(new), id(old)) + visited = id_pair in recursive_ids + recursive_ids.add(id_pair) + + # If we've visited this exact check before while recursing, all elements in + # this collection have already been validated (or will be validated in the + # future) by a call at a different layer of recursion. + return visited or ( + len(new) == len(old) + and all( + _is_fake_tensor_same( + new_i, + old_i, + existing_storages, + check_strides=check_strides, + check_storage=check_storage, + node=node, + recursive_ids=recursive_ids, + ) + for new_i, old_i in zip(new, old) + ) + ) + + if isinstance(new, torch.types.py_sym_types): + return ( + not_none(new.node.shape_env)._maybe_evaluate_static( + sympy.Eq(new.node.expr, old.node.expr) + ) + == sympy.true + ) + + # If this is not a Collection, a sym-type, or a Tensor, then check for Python + # equality. This should be fairly conservative, since an object with no + # implemented __eq__ method will compare IDs. + return new == old + + if ( + new.layout != old.layout + or new.dtype != old.dtype + or not is_intlist_same(new.shape, old.shape) + ): + return False + + if new.device != old.device: + return False + + if ( + check_strides + and new.layout == torch.strided + and not is_intlist_same(new.stride(), old.stride()) + ): + return False + + if not check_storage: + return True + + if not statically_known_true( + new.storage_offset() == old.storage_offset() + ) or get_storage(new) != get_storage(old): + return False + + def any_user_may_alias(node): + if not isinstance(node.meta["val"], torch.Tensor): + # analysis too complicated on lists, can support in the future + return True + + for user in node.users: + if not ( + isinstance(user.target, torch._ops.OperatorBase) + or user.target + is torch._inductor.fx_passes.reinplace._generalized_scatter + ): + return True + + if isinstance(user.target, torch._ops.HigherOrderOperator): + # HOPs that survive until inductor are all non-aliasing HOPs. We will + # likely never support HOPs that are aliasing. + continue + + # Strategy: do a FakeTensor prop, see if the storage aliases. If Inductor + # ever gets tighter invariants on OpOverloads (that is, we ban things like + # torch.ops.aten.reshape calls in the graph), then this could just be a fast + # schema lookup. + is_valid, args, kwargs = get_fake_args_kwargs(user) + if not is_valid: + return True + + with ( + V.fake_mode, + enable_python_dispatcher(), + contextlib.ExitStack() as stack, + ): + # Ignore unbacked symbols (if they exist): we're making this FakeTensor + # and then throwing it away. + if (shape_env := V.fake_mode.shape_env) is not None: + stack.enter_context(shape_env.ignore_fresh_unbacked_symbols()) + new_fake_tensor = user.target(*args, **kwargs) + + if not isinstance(new_fake_tensor, torch.Tensor): + # analysis too complicated on lists, can support in the future + return True + + if get_storage(new_fake_tensor) == get_storage(node.meta["val"]): + return True + + return False + + # This is the case where it returns a completely fresh storage that's used nowhere + # else. If the FakeTensor's storage is fresh and none of the node's users can alias + # it, then we don't need to update this node. + if ( + existing_storages[get_storage(old)] == 1 + and get_storage(new) not in existing_storages + and not any_user_may_alias(node) + ): + return True + + return False + + +def _extract_subgraphs_and_args( + node: torch.fx.Node, + valid_subgraphs: Container[torch.fx.GraphModule], + *args: Any, + **kwargs: Any, +) -> Generator[tuple[torch.fx.GraphModule, tuple[Any, ...] | None]]: + """HOPs that invoke subgraphs take a number of different forms. This function + regularizes them, yielding subgraphs from the args and kwargs coupled with + appropriate args to update those subgraphs. + + If the second yielded value is None, this function was unable to determine what args + to pass to the subgraph.""" + + def get_subgraph_args( + subgraph: torch.fx.GraphModule, + ) -> tuple[torch.Tensor, ...]: + return tuple( + get_fake(n, subgraph) for n in subgraph.graph.find_nodes(op="placeholder") + ) + + def is_integer(d: torch.dtype) -> bool: + return not d.is_floating_point and not d.is_complex + + if node.target is torch.ops.higher_order.associative_scan: + # Associative scan operates on slices of xs (see: scan), but multiple slices. + # Use the same slice twice to account for cases where only a single slice is + # input. first_slice_copy tolerates a zero-length scan dim. + from torch._higher_order_ops.utils import first_slice_copy + + sliced = [first_slice_copy(a) for a in args[1]] + yield args[0], (*sliced, *sliced, *args[2]) + elif node.target is torch.ops.higher_order.cond: + subgraph_args = tuple(args[3]) + yield args[1], subgraph_args + yield args[2], subgraph_args + elif node.target is torch.ops.higher_order.flex_attention: + # flex_attention currently yields two subgraphs. The first (the score + # calculation) has a signature starting with a scalar argument of the same dtype + # as the query (args[0]), followed by four scalar integer arguments and optional + # additional tensors. The second (the mask calculation) looks similar, with + # four scalar integer arguments and optional additional (different) tensors. We + # assume this format here (adding some defensive assertions), which means that + # the only inputs we may need to update are the optional additional tensors. See + # torch._higher_order_ops.flex_attention._math_attention_inner for more details. + + score_subgraph: torch.fx.GraphModule = args[3] + score_subgraph_args = get_subgraph_args(score_subgraph) + mask_subgraph = args[4][-1] + mask_subgraph_args = get_subgraph_args(mask_subgraph) + + integer_arg_dtypes = OrderedSet[torch.dtype]( + a.dtype for a in chain(score_subgraph_args[1:5], mask_subgraph_args[:4]) + ) + if not ( + score_subgraph_args[0].dtype == args[0].dtype + and len(integer_arg_dtypes) == 1 + and is_integer(integer_arg_dtypes.pop()) + and all( + len(a.size()) == 0 + for a in chain(score_subgraph_args[:5], mask_subgraph_args[:4]) + ) + ): + raise AssertionError("flex_attention subgraph arg format has changed!") + + yield score_subgraph, (*score_subgraph_args[:5], *args[7]) + yield args[4][-1], (*mask_subgraph_args[:4], *args[8]) + elif node.target is torch.ops.higher_order.flex_attention_backward: + fw_subgraph = args[7] + fw_subgraph_args = get_subgraph_args(fw_subgraph) + joint_subgraph = args[8] + joint_subgraph_args = get_subgraph_args(joint_subgraph) + mask_subgraph = args[9][-1] + mask_subgraph_args = get_subgraph_args(mask_subgraph) + + integer_arg_dtypes = OrderedSet[torch.dtype]( + a.dtype + for a in chain( + fw_subgraph_args[1:5], + joint_subgraph_args[1:5], + mask_subgraph_args[:4], + ) + ) + if not ( + fw_subgraph_args[0].dtype == args[0].dtype + and joint_subgraph_args[0].dtype == args[0].dtype + and len(integer_arg_dtypes) == 1 + and is_integer(integer_arg_dtypes.pop()) + and all( + len(a.size()) == 0 + for a in chain( + fw_subgraph_args[:5], + joint_subgraph_args[:6], + mask_subgraph_args[:4], + ) + ) + ): + raise AssertionError( + "flex_attention_backward subgraph arg format has changed!" + ) + + if fw_subgraph in valid_subgraphs: + yield fw_subgraph, (*fw_subgraph_args[:5], *args[12]) + if joint_subgraph in valid_subgraphs: + yield joint_subgraph, (*joint_subgraph_args[:6], *args[12]) + if mask_subgraph in valid_subgraphs: + yield mask_subgraph, (*mask_subgraph_args[:4], *args[13]) + elif node.target in ( + torch.ops.higher_order.foreach_map, + torch.ops.higher_order.invoke_quant_packed, + torch.ops.higher_order.invoke_quant, + ): + yield args[0], tuple(args[1:]) + elif node.target is torch.ops.higher_order.invoke_subgraph: + yield args[0], tuple(args[2:]) + elif node.target is torch.ops.higher_order.map_impl: + # Map is applied over slices from the first dimension of each value in args[1]. + yield args[0], (*(a[0] for a in args[1]), *args[2]) + elif node.target is torch.ops.higher_order.scan: + # Scans accept a dim keyword, but the dimensions will be reordered so that at + # this point we always scan over dim 0. + # first_slice_copy tolerates a zero-length scan dim. + from torch._higher_order_ops.utils import first_slice_copy + + yield args[0], (*args[1], *(first_slice_copy(a) for a in args[2]), *args[3]) + elif node.target in ( + torch.ops.higher_order.while_loop, + torch.ops.higher_order.while_loop_stack_output, + ): + subgraph_args = (*args[2], *args[3]) + yield args[0], subgraph_args + yield args[1], subgraph_args + elif node.target is torch.ops.higher_order.switch: + # args: (index, [branch_gm_0, ...], operands) + subgraph_args = tuple(args[2]) + for branch_gm in args[1]: + yield branch_gm, subgraph_args + elif node.target is control_deps: + if kwargs: + raise AssertionError( + "Subgraph arguments can be renamed, so we cannot consistently " + "handle kwargs at this point in the stack." + ) + control_deps_subgraph = args[1] + control_deps_args = tuple(args[2:]) + if control_deps_subgraph in valid_subgraphs: + yield control_deps_subgraph, control_deps_args + if isinstance( + control_deps_subgraph, torch.fx.GraphModule + ) and pytree.tree_any_only( + torch.fx.GraphModule, + lambda subgraph: subgraph in valid_subgraphs, + control_deps_args, + ): + placeholder_to_arg = dict( + zip( + control_deps_subgraph.graph.find_nodes(op="placeholder"), + control_deps_args, + strict=True, + ) + ) + wrapped_nodes = [ + n for n in control_deps_subgraph.graph.nodes if n.op == "call_function" + ] + if len(wrapped_nodes) != 1: + raise AssertionError( + f"expected exactly 1 wrapped call_function node, got {len(wrapped_nodes)}" + ) + wrapped_node = wrapped_nodes[0] + + def replace_placeholder(item: Any) -> Any: + if isinstance(item, torch.fx.Node): + return placeholder_to_arg.get(item, item) + return item + + wrapped_args, wrapped_kwargs = pytree.tree_map( + replace_placeholder, + (wrapped_node.args, wrapped_node.kwargs), + ) + yield from _extract_subgraphs_and_args( + wrapped_node, valid_subgraphs, *wrapped_args, **wrapped_kwargs + ) + elif node.target is torch.ops.higher_order.flex_gemm: + yield args[1], tuple(args[2]) + else: + warnings.warn( + f"Please add support for subgraph args to function {node.target}!" + ) + + # By default, just return the detected list of subgraphs so that we can run + # updates on all of them. + flat_args_kwargs, _ = pytree.tree_flatten((args, kwargs)) + yield from ( + (s, None) + for s in flat_args_kwargs + if isinstance(s, torch.fx.GraphModule) and s in valid_subgraphs + ) + + +@dataclass(frozen=True) +class _FxNodeHash: + node: torch.fx.Node + target: torch.fx.node.Target + arg_hashes: tuple[int, ...] + kwarg_hashes: tuple[int, ...] + + +class FakeTensorUpdater: + """ + The main idea here is that it's difficult to maintain accurate fake + tensors (our primary form of metadata) for each node in our graph as we + transform it. + + The most reliable way to obtain this information is by rerunning + faketensor propagation. However, in general, faketensor propagation is + fairly expensive. So, instead we'd like to only rerun faketensor + propagation on nodes that have changed. + + In order to detect which nodes have changed, we first hash its node, + target, and argument lists (which are immutable in FX). + + Then, whenever we call incremental_update, we check which FX nodes have a + new hash, and recompute the faketensor metadata for that node. Then, we + continue to recursively compute the faketensors for all users until the + fake tensors stop changing. + + Since this runs in the context of Inductor, we assume that the input and + output semantics for the outermost graph are not subject to change after class + initialization, but we allow striding changes for subgraphs. Any other changes will + result in errors or undefined behavior. + """ + + def __init__(self, gm: torch.fx.GraphModule) -> None: + self.processed_hashes = OrderedSet[_FxNodeHash]() + self.tracked_node_ids: OrderedSet[int] = OrderedSet() + self.gm = gm + + # Import here to avoid circular import issues. + from torch._inductor.compile_fx import _get_subgraph_names + + self.subgraph_updaters: dict[torch.fx.GraphModule, FakeTensorUpdater] = { + (subgraph := getattr(self.gm, subgraph_name)): FakeTensorUpdater(subgraph) + for subgraph_name in _get_subgraph_names(self.gm) + } + + for node in self.gm.graph.nodes: + self.processed_hashes.add(self.hash_node(node)) + self.tracked_node_ids.add(id(node)) + + def hash_node(self, node: torch.fx.Node) -> _FxNodeHash: + def get_hash_or_ids(n_iter: Iterable[Any]) -> tuple[int, ...]: + """Replace unhashable items from the input with the ids of those items, and + hash all other items. This is kludgy, but allows us to attempt to account + for unhashable classes like torch.fx.Node when hashing args and kwargs for + other nodes.""" + + def get_hash_or_id(o: object) -> int: + try: + return hash(o) + except Exception: + return id(o) + + return tuple(get_hash_or_id(n) for n in n_iter) + + return _FxNodeHash( + node, + node.target, + get_hash_or_ids(node.args), + get_hash_or_ids(chain.from_iterable(node.kwargs.items())), + ) + + def incremental_update(self) -> int: + """Update FakeTensors on self.graph. We will try to do the minimum amount of work. + + Returns the number of nodes updated, including recursive updates on subgraphs.""" + existing_storages: defaultdict[int, int] = defaultdict(int) + for node in self.gm.graph.nodes: + if storage := get_node_storage(node): + existing_storages[storage] += 1 + + def should_process_node(node: torch.fx.Node) -> bool: + return ( + callable(node.target) + # Dirty Inductor lowerings are handled by the guard below. Clean + # lowering nodes are skipped because their targets expect IR inputs. + and not hasattr(node.target, "_inductor_lowering_function") + ) + + def node_invokes_subgraph( + node: torch.fx.Node, *args: Any, **kwargs: Any + ) -> bool: + return ( + node.op == "call_function" + and node.target + not in ( + # auto_functionalized doesn't call a subgraph, but the pytree call + # below can return subgraphs if the functionalized call itself + # invokes a subgraph. + torch.ops.higher_order.auto_functionalized, + torch.ops.higher_order.auto_functionalized_v2, + ) + and pytree.tree_any_only( + torch.fx.GraphModule, + lambda s: s in self.subgraph_updaters, + (args, kwargs), + ) + ) + + def update_node_fake_tensor(node: torch.fx.Node, new_fake_tensor: Any) -> bool: + if "val" in node.meta and _is_fake_tensor_same( + new_fake_tensor, node.meta["val"], existing_storages, node=node + ): + return False + + storage_only_change = "val" in node.meta and _is_fake_tensor_same( + new_fake_tensor, + node.meta["val"], + existing_storages, + check_storage=False, + node=node, + ) + + rebind_unbacked(V.fake_mode.shape_env, node, new_fake_tensor) + + node.meta["val"] = new_fake_tensor + + if (shape_env := V.fake_mode.shape_env) and ( + symbol_to_path := compute_unbacked_bindings(shape_env, new_fake_tensor) + ): + # Refresh the bindings to the new symbols + + node.meta["unbacked_bindings"] = symbol_to_path + + if storage := get_node_storage(node): + existing_storages[storage] += 1 + + to_process.update( + id(user) + for user in node.users + if not ( + storage_only_change + and getattr( + user.target, + "_inductor_lowering_output_metadata_ignores_input_storage", + False, + ) + and getattr( + user.target, + "_inductor_lowering_output_metadata_is_input", + None, + ) + is None + ) + ) + + return True + + def get_lowering_input_metadata( + node: torch.fx.Node, input_name: int | str + ) -> Any: + raw_input = ( + node.args[input_name] + if isinstance(input_name, int) + else node.kwargs[input_name] + ) + + def has_missing_fake_metadata(input_node: torch.fx.Node) -> bool: + return not ( + "val" in input_node.meta + or "example_value" in input_node.meta + or ( + input_node.op == "get_attr" + and isinstance(input_node.target, str) + and hasattr(self.gm, input_node.target) + ) + ) + + if any( + isinstance(leaf, torch.fx.Node) and has_missing_fake_metadata(leaf) + for leaf in pytree.tree_leaves(raw_input) + ): + raise RuntimeError( + "FakeTensorUpdater cannot update pass-through " + "_inductor_lowering_function metadata because the input " + f"metadata is unavailable. Encountered node: {node.format_node()}" + ) + return tree_map(partial(get_fake, gm=self.gm), raw_input) + + # Update self.processed_hashes every time. This allows us to account for + # situations where a node gets modified, updated, then reverted to its original + # state. Without doing this, we wouldn't update downstream nodes, because the + # reverted node would already be in our cache. + current_graph_hashes = OrderedSet[_FxNodeHash]() + + nodes_updated: int = 0 + to_process = OrderedSet[int]() + # Value records whether subgraph outputs have been updated. + subgraph_updatings: dict[torch.fx.GraphModule, bool] = {} + for node in self.gm.graph.nodes: + current_graph_hashes.add(node_hash := self.hash_node(node)) + + # Lowering functions consume Inductor IR nodes, not FakeTensors, so + # FakeTensorUpdater cannot safely recompute their metadata. + if hasattr(node.target, "_inductor_lowering_function") and ( + node_hash not in self.processed_hashes or id(node) in to_process + ): + if metadata_fn := getattr( + node.target, + "_inductor_lowering_output_metadata_fn", + None, + ): + is_valid, args, kwargs = get_fake_args_kwargs(node, self.gm) + if not is_valid: + raise RuntimeError( + "FakeTensorUpdater cannot update " + "_inductor_lowering_function metadata because the " + "metadata provider inputs are unavailable. " + f"Encountered node: {node.format_node()}" + ) + with V.fake_mode, enable_python_dispatcher(): + new_fake_tensor = metadata_fn(*args, **kwargs) + if update_node_fake_tensor(node, new_fake_tensor): + nodes_updated += 1 + self.tracked_node_ids.add(id(node)) + continue + if ( + metadata_input := getattr( + node.target, + "_inductor_lowering_output_metadata_is_input", + None, + ) + ) is not None: + if update_node_fake_tensor( + node, get_lowering_input_metadata(node, metadata_input) + ): + nodes_updated += 1 + self.tracked_node_ids.add(id(node)) + continue + if id(node) in to_process: + raise RuntimeError( + "FakeTensorUpdater cannot recompute metadata for " + "_inductor_lowering_function nodes after their dependencies " + "change because those targets expect Inductor IR inputs rather " + "than FakeTensor inputs. " + f"Encountered node with changed dependency: {node.format_node()}" + ) + if id(node) in self.tracked_node_ids: + raise RuntimeError( + "FakeTensorUpdater cannot recompute metadata for tracked " + "_inductor_lowering_function nodes after their inputs or " + "dependencies change because those targets expect " + "Inductor IR inputs rather than FakeTensor inputs. " + f"Encountered changed node: {node.format_node()}" + ) + if "val" not in node.meta: + raise RuntimeError( + "FakeTensorUpdater requires newly inserted " + "_inductor_lowering_function nodes to already carry fake " + "metadata in node.meta['val']. " + f"Encountered new node without metadata: {node.format_node()}" + ) + self.tracked_node_ids.add(id(node)) + continue + + is_valid, args, kwargs = get_fake_args_kwargs(node, self.gm) + if not is_valid: + continue + + # NB: Be very careful about skipping nodes (via continues) here + # and ask for a careful review when changing this code. The + # consequence for incorrect FakeTensor metadata is difficult-to-debug + # silent incorrectness. + if ( + # Always run updates on nodes that invoke subgraphs + not (invokes_subgraph := node_invokes_subgraph(node, *args, **kwargs)) + and node_hash in self.processed_hashes + and id(node) not in to_process + ): + continue + + if not should_process_node(node): + continue + + if invokes_subgraph: + any_output_updated = False + + for subgraph, subgraph_args in _extract_subgraphs_and_args( + node, self.subgraph_updaters, *args, **kwargs + ): + update_subgraph = subgraph not in subgraph_updatings + if update_subgraph: + subgraph_updatings[subgraph] = False + + # If the arguments being passed into the subgraph differ from the + # existing args the first time we see the subgraph, update the + # placeholder nodes in the subgraph. Any updates past that point + # would make subgraph updates inconsistent, so throw errors. + if subgraph_args is not None: + for p, a in zip( + subgraph.graph.find_nodes(op="placeholder"), + subgraph_args, + strict=True, + ): + # Do an update iff anything except the storage has changed, + # since every invocation of the subgraph will use different + # storages. This implies potentially incorrect arg + # aliasing relationships. + if not _is_fake_tensor_same( + a, + p_fake := get_fake(p, subgraph), + existing_storages, + check_storage=False, + ): + if not update_subgraph: + raise AssertionError( + "subgraph args must have consistent values!" + ) + # Check that only the stride has changed. Other changes + # cannot be handled without manual intervention. + if not _is_fake_tensor_same( + a, + p_fake, + existing_storages, + check_strides=False, + check_storage=False, + ): + raise AssertionError( + "A subgraph argument other than striding has been " + "modified; FakeTensorUpdater cannot update this " + "argument!" + ) + + p.meta["val"] = a + nodes_updated += 1 + + if update_subgraph: + _, orig_output_args, _ = get_fake_args_kwargs( + subgraph.graph.output_node(), subgraph + ) + nodes_updated += self.subgraph_updaters[ + subgraph + ].incremental_update() + _, new_output_args, _ = get_fake_args_kwargs( + subgraph.graph.output_node(), subgraph + ) + + if not _is_fake_tensor_same( + new_output_args, + orig_output_args, + existing_storages, + ): + subgraph_updatings[subgraph] = True + + any_output_updated = ( + any_output_updated or subgraph_updatings[subgraph] + ) + + # If the outputs of the subgraphs have not changed (and have been + # previously cached), we can skip updating. If the outputs of the + # subgraph have changed, we'll run FakeTensor propagation for every + # invocation of the subgraph, so that each node gets unique FakeTensor + # values which maintain appropriate aliasing relationships. + if not any_output_updated and "val" in node.meta: + continue + + with V.fake_mode, enable_python_dispatcher(): + new_fake_tensor = node.target(*args, **kwargs) + + if update_node_fake_tensor(node, new_fake_tensor): + nodes_updated += 1 + + self.processed_hashes = current_graph_hashes + self.tracked_node_ids = OrderedSet(id(node) for node in self.gm.graph.nodes) + + return nodes_updated + + +def get_storage(t: torch.Tensor) -> int: + return t.untyped_storage()._cdata + + +def get_node_storage(node: torch.fx.Node) -> int | None: + if "val" not in node.meta: + return None + if not isinstance(node.meta["val"], torch.Tensor): + return None + if not torch._C._has_storage(node.meta["val"]): + return None + return get_storage(node.meta["val"]) + + +def get_fake(x: Any, gm: torch.fx.GraphModule | None) -> Any: + """Return a fake tensor from the meta values of an input FX node. If the input node + is a get_attr node, we attempt to resolve it as a member of gm.""" + if isinstance(x, torch.fx.Node): + if "val" in x.meta: + return x.meta["val"] + if "example_value" in x.meta: + return x.meta["example_value"] + if x.op == "get_attr" and isinstance(x.target, str) and hasattr(gm, x.target): + return getattr(gm, x.target) + # If a node has no available fake values and isn't a get_attr, it either returns + # None or is incorrectly configured. Since there are real nodes which return + # None, we can't error here. + return None + # If there are no example values, return x + return x + + +def get_fake_args_kwargs( + x: torch.fx.Node, gm: torch.fx.GraphModule | None = None +) -> tuple[bool, tuple[Any, ...], dict[str, Any]]: + """ + First value returns a boolean if any of the input nodes don't have a faketensor and + weren't resolved from gm. + """ + args, kwargs = tree_map(partial(get_fake, gm=gm), (x.args, x.kwargs)) + if any( + isinstance(a, torch.fx.Node) for a in pytree.arg_tree_leaves(*args, **kwargs) + ): + return False, args, kwargs + return True, args, kwargs + + +def is_node_realized(node: torch.fx.Node) -> bool: + """Returns true if a node is always realized when lowered to inductor IR. + + NOTE: This may return some false negatives. e.g. it doesn't + handle buffers realized heuristically during lowering, or + buffers realized indirectly through view ops. + """ + from torch._inductor.lowering import fallbacks, needs_realized_inputs + + def is_buffer(node: torch.fx.Node) -> bool: + if node.op == "call_function" and node.target is operator.getitem: + # For nodes with multiple outputs, we get the fx graph: + # foo = torch.ops.aten.foo(...) + # getitem = foo[0] + # getitem_1 = foo[1] + # where we need to check if foo is a fallback kernel + return is_buffer(node.args[0]) # type: ignore[arg-type] + return node.op in ("placeholder", "output") or node.target in fallbacks + + if is_buffer(node): + return True + + def realizes_inputs(node: torch.fx.Node) -> bool: + return node.op == "output" or node.target in needs_realized_inputs + + if any(realizes_inputs(user) for user in node.users): + return True + + # Otherwise, assume node isn't realized + return False + + +def count_flops_fx(node: torch.fx.Node) -> int | None: + if not countable_fx(node) or isinstance(node.target, str): + return None + with FakeTensorMode(allow_non_fake_inputs=True): + success, args, kwargs = get_fake_args_kwargs(node) + + if success: + # flex_attention HOPs have registered formulas, but invoking them + # here can require tracing-only context, e.g. TransformGetItemToIndex. + if node.target in ( + torch.ops.higher_order.flex_attention, + torch.ops.higher_order.flex_attention_backward, + ): + flop_formula = flop_registry.get(node.target) + if flop_formula is not None: + return flop_formula(*args, **kwargs, out_val=node.meta.get("val")) + + with torch.utils.flop_counter.FlopCounterMode( + display=False + ) as flop_counter_mode: + node.target(*args, **kwargs) + + counted_flops = flop_counter_mode.get_total_flops() + return counted_flops + return None + + +def countable_fx(node: torch.fx.Node) -> bool: + """ + Whether or not we can count the flops of an FX node. + """ + if not isinstance(node, torch.fx.Node): + raise AssertionError(f"expected torch.fx.Node, got {type(node)}") + if not hasattr(node, "target"): + return False + target = node.target + if not hasattr(target, "overloadpacket"): + return target in flop_registry + packet = target.overloadpacket + return packet in flop_registry diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/graph.py b/.venv/lib/python3.12/site-packages/torch/_inductor/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..35fc1b09d22d0674a0ac22202bd68e3543d36c94 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/graph.py @@ -0,0 +1,3226 @@ +from __future__ import annotations + +import contextlib +import functools +import itertools +import logging +import operator +import os +import re +import sys +import textwrap +import time +import typing_extensions +from collections import defaultdict +from contextlib import contextmanager +from typing import Any, cast, Literal, NoReturn, TYPE_CHECKING + +import sympy +from sympy import Expr + +import torch +import torch._logging +import torch.fx +from torch import device, Tensor +from torch._decomp import get_decompositions +from torch._dynamo.utils import defake, dynamo_timed +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import ( + is_custom_class, + is_opaque_constant_type, + is_opaque_symbolic_type, +) +from torch._library.utils import get_layout_constraint_tag +from torch._logging import LazyString, trace_structured +from torch._prims_common import ( + compute_required_storage_length, + make_channels_last_strides_for, +) +from torch._subclasses.fake_tensor import is_fake_tensor +from torch._utils_internal import full_aoti_runtime_assert +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.symbolic_shapes import ( + _get_placeholder_expr, + free_unbacked_symbols, + has_free_symbols, + resolve_unbacked_bindings, + RuntimeAssert, + ShapeEnv, + SympyBoolean, + SymTypes, +) +from torch.fx.node import Node +from torch.fx.passes.reinplace import _is_view_op +from torch.utils._mode_utils import no_dispatch +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.numbers import int_oo +from torch.utils._typing_utils import not_none + +from . import config, ir +from .codegen.common import ( + BackendFeature, + DeviceOpOverrides, + FileBackedGraphModule, + get_backend_features, + get_device_op_overrides, + get_wrapper_codegen_for_device, + init_backend_registration, + WorkspaceArg, +) +from .exc import ( + CppWrapperCodegenError, + LoweringException, + MissingOperatorWithDecomp, + MissingOperatorWithoutDecomp, +) +from .fx_utils import count_flops_fx +from .ir import ( + assign_origin_node, + Constant, + DonatedBuffer, + FixedLayout, + get_device_type, + GraphPartitionSignature, + InputBuffer, + Pointwise, + Reduction, + ShapeAsConstantBuffer, + StorageBox, + TensorBox, + TorchBindObject, +) +from .lowering import ( + constrain_to_fake_tensors, + constrain_to_fx_strides, + FALLBACK_ALLOW_LIST, + fallback_handler, + fallback_node_due_to_unsupported_type, + lowerings, + make_fallback, + maybe_layout_constraints, + needs_realized_inputs, + require_contiguous, + tag_to_layout_constraint, + unsupported_output_tensor, + user_lowerings, +) +from .runtime import autotune_cache +from .runtime.autotune_cache import AutotuneCacheBundler +from .sizevars import SizeVarAllocator +from .utils import ( + gather_origins, + get_cloned_parameter_buffer_name, + get_donated_idxs, + get_sympy_Expr_dtype, + GraphPartitionMap, + is_same_tensor, + maybe_get_suppress_shape_guards_ctx, + normalize_name, + should_assume_input_aligned, + should_fallback_by_default, + SUPPORTED_MKLDNN_DEVICES, + ValueWithLineMap, +) +from .virtualized import NullHandler, V + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Iterator, Sequence + from types import ModuleType + + from torch._higher_order_ops.effects import _EffectType + from torch.fx import GraphModule + from torch.fx.graph import Graph + + from .codegen.wrapper import PythonWrapperCodegen + from .dependencies import Dep + from .scheduler import BaseSchedulerNode + + CompiledModule = ModuleType | FileBackedGraphModule + +from torch._inductor.codecache import output_code_log + + +log = logging.getLogger(__name__) +perf_hint_log = torch._logging.getArtifactLogger(__name__, "perf_hints") + +aten = torch.ops.aten + +_post_grad_graph_counter = itertools.count() + +if config.is_fbcode(): + from torch._inductor.fb.triton_kernel_metadata import ( + save_triton_kernel_perf_artifact, + ) + from torch._inductor.fb.utils import log_module_code +else: + + def log_module_code(*args: Any, **kwargs: Any) -> None: + pass + + def save_triton_kernel_perf_artifact(*args: Any, **kwargs: Any) -> None: + pass + + +def may_get_constant_buffer_dtype(constant_buffer: sympy.Expr) -> torch.dtype | None: + if not isinstance( + constant_buffer, (sympy.Symbol, sympy.Expr, sympy.core.numbers.Integer) + ): + raise AssertionError( + "get_constant_buffer_dtype only supports input of sympy.Symbol, sympy.Expr or sympy.core.numbers.Integer" + ) + if isinstance(constant_buffer, sympy.core.numbers.Integer): + return torch.int64 + + if isinstance(constant_buffer, sympy.Expr): + return get_sympy_Expr_dtype(constant_buffer) + + if constant_buffer.is_integer: + return torch.int64 + elif constant_buffer.is_float: + return torch.float32 + else: + return None + + +def getattr_recursive( + obj: GraphModule, target: str +) -> Tensor | torch._C.ScriptObject | GraphModule: + target_atoms = target.split(".") + attr_itr = obj + for i, atom in enumerate(target_atoms): + if not hasattr(attr_itr, atom): + raise RuntimeError( + f"Node referenced nonexistent target {'.'.join(target_atoms[:i])}" + ) + attr_itr = getattr(attr_itr, atom) + return attr_itr + + +def get_user_visible_output_strides(g: Graph) -> dict[Node, tuple[int, ...]]: + ret: dict[Node, tuple[int, ...]] = {} + output_node = g.find_nodes(op="output")[0] + + if "user_visible_output_idxs" not in output_node.meta: + return ret + + if not isinstance(output_node.args[0], torch.fx.Node): + output_node_args = output_node.args[0] + else: + output_node_args = output_node.args + + for idx, node in enumerate(output_node_args): + if idx in output_node.meta["user_visible_output_idxs"]: + ret[node] = output_node.meta["original_output_strides"][idx] + return ret + + +def _is_cpu_strided_tensor_pinned(t: torch.Tensor) -> bool: + return t.device.type == "cpu" and t.layout == torch.strided and t.is_pinned() + + +def extend_user_visible_output_strides( + user_visible_outputs: dict[Node, tuple[int, ...]], +) -> dict[Node, object]: + """ + Extend user_visible_output_strides to include view ops that lead to user-visible outputs. + """ + result: dict[Node, object] = {**user_visible_outputs} + queue = [*result.keys()] + visited = OrderedSet([*queue]) + while queue: + current = queue.pop() + if ( + _is_view_op(current.target) + and current.args + and isinstance(current.args[0], torch.fx.Node) + ): + base = current.args[0] + if base not in visited: + result.setdefault(base, None) + visited.add(base) + queue.append(base) + return result + + +def mark_nodes_dislike_padding( + g: Graph, user_visible_output_strides: dict[Node, tuple[int, ...]] +) -> None: + """ + Nodes like convolution/convolution_backward want its input to be dense. + If we pad their inputs, we result in extra calls to copy kernels! On the other hand, padding usually helps reduction. + + The pass finds nodes that dislike padding. These are nodes that can be reached + from a convolution/convolution_backward in the backward direction without + going thru a reduction. + """ + if not config.comprehensive_padding: + return + + extended_user_visible_nodes = extend_user_visible_output_strides( + user_visible_output_strides + ) + ops_dislike_padding = OrderedSet( + [ + aten.convolution, + aten.convolution_backward, + aten._scaled_mm, + aten._scaled_mm_v2, + ] + ) + # what's a better way to collect the reduction ops? + ops_like_padding = OrderedSet( + [ + aten.var_mean, + aten.sum, + aten.mean, + aten.prod, + aten.any, + aten.amin, + aten.amax, + aten.min, + aten.max, + aten.argmin, + aten.argmax, + aten.scatter_reduce, + ] + ) + + def _get_overload_packet( + node: torch.fx.Node, + ) -> torch._ops.OpOverloadPacket | None: + return ( + node.target._overloadpacket + if node.op == "call_function" + # hasattr on OpOverloadPacket is slow, do isinstance first + and isinstance(node.target, torch._ops.OpOverload) + and hasattr(node.target, "_overloadpacket") + else None + ) + + for cur in reversed(g.nodes): + if isinstance( + cur.target, + torch._higher_order_ops.triton_kernel_wrap.TritonKernelWrapperMutation, + ): + cur.meta["dislike_padding"] = True + continue + + if ( + isinstance(cur.target, torch._ops.OpOverload) + and get_layout_constraint_tag(cur.target) + == torch._C.Tag.needs_exact_strides + ): + cur.meta["dislike_padding"] = True + continue + + op = _get_overload_packet(cur) + if not op: + continue + if op in ops_dislike_padding: + cur.meta["dislike_padding"] = True + + if cur.meta.get("dislike_padding", False): + # propagate + for prior in cur.all_input_nodes: + prior_op = _get_overload_packet(prior) + if not prior_op: + continue + if prior_op not in ops_like_padding: + prior.meta["dislike_padding"] = True + # We only want to mark output nodes. So, move it after the above prior nodes process. + if not config.pad_outputs and cur in extended_user_visible_nodes: + # Reductions (ops_like_padding) produce new output buffers with + # fresh strides, so their output stride constraint is already + # enforced by allow_padding=False in as_exact_strides. Setting + # dislike_padding here would suppress input padding during + # freeze, causing a stride mismatch when an earlier lowering + # step (e.g. is_contiguous_storage_and_layout) already mutated + # the input layout to padded strides. + if op not in ops_like_padding: + cur.meta["dislike_padding"] = True + + +def is_mkldnn_conv(node: Node) -> bool: + # When mkldnn_fusion is enabled, conv will be replaced by the lowering pattern function. + # See _register_unary_fusion_lowering in torch/_inductor/fx_passes/mkldnn_fusion.py. + if ( + getattr(torch.ops, "mkldnn", None) is not None + and getattr(torch.ops.mkldnn, "_convolution_pointwise", None) is not None + and isinstance(node.target, functools.partial) + and len(node.target.args) > 0 + and hasattr(node.target.args[0], "targets") + ): + for target in node.target.args[0].targets: + if target.fns[0] in [ + torch.ops.mkldnn._convolution_pointwise.default, + torch.ops.mkldnn._convolution_pointwise.binary, + torch.ops.mkldnn._convolution_pointwise_.binary, + ]: + return True + + return False + + +def _realize_efficient_zerotensor_output(r: ir.IRNode, fx_node: object) -> ir.IRNode: + if ( + isinstance(fx_node, torch.fx.Node) + and fx_node.target is torch.ops.aten._efficientzerotensor.default + and isinstance(r, (ir.TensorBox, ir.BaseView)) + ): + return ir.ExternKernel.realize_input( + fallback_handler( + torch.ops.aten._efficientzerotensor.default, + add_to_fallback_set=False, + )( + list(r.get_size()), + dtype=r.get_dtype(), + layout=torch.strided, + device=r.get_device(), + pin_memory=False, + ) + ) + return r + + +class GraphLowering(torch.fx.Interpreter): + """Lowers an FX graph to Inductor IR and drives backend code generation. + + Walks the FX graph node-by-node, materializing inputs/outputs and + constants, dispatching each call to an Inductor lowering, and accumulating + the resulting IR nodes. Holds graph-wide state needed by lowerings and + codegen (sizevars, scheduler inputs, device/dtype tracking, wrapper code, + etc.) and orchestrates the call into `codegen()` to produce a wrapper + + kernel module via the configured backend (Python/C++ wrappers, AOTI). + """ + + graph_outputs: list[ir.IRNode] + + def __init__( + self, + gm: torch.fx.GraphModule, + example_inputs: Sequence[object] | None = None, + shape_env: ShapeEnv | None = None, + graph_id: int | None = None, + cpp_wrapper: bool = False, + aot_mode: bool = False, + layout_opt: bool | None = None, + extern_node_serializer: Callable[[list[ir.ExternKernelNode]], Any] + | None = None, + is_inference: bool = False, + is_backward: bool = False, + is_const_graph: bool = False, + const_output_index: dict[str, int] | None = None, + const_wrapper_code: str | None = None, + const_kernel_code: str | None = None, + const_module: GraphLowering | None = None, + name: str | None = None, + inputs_to_check: Sequence[int] | None = None, + fx_wrapper: bool = False, + get_decomp_fn: Callable[..., dict[Any, Callable[..., Any]]] | None = None, + ) -> None: + super().__init__(gm) + self.get_decomp_fn = get_decomp_fn + self.example_inputs = example_inputs + self.layout_opt = ( + layout_opt + if layout_opt is not None + else self.decide_layout_opt(gm, is_inference=is_inference) + ) + self.num_channels_last_conv = 0 + self.is_inference = is_inference + self.is_backward = is_backward + self.is_const_graph = is_const_graph + self.const_wrapper_code = const_wrapper_code + self.const_kernel_code = const_kernel_code + self.const_module = const_module + self.inputs_to_check = inputs_to_check + self._defers_input_alignment = False + + self.extra_traceback = False # we do our own error wrapping + if shape_env is None: + shape_env = ShapeEnv() + self.reuse_shape_env = False + else: + self.reuse_shape_env = True + self._shape_env = shape_env + # We're going to mutate ras_by_symbol as we finish generating them + self.ras_by_symbol: dict[sympy.Symbol | None, list[RuntimeAssert]] = ( + shape_env.deferred_runtime_asserts.copy() + ) + self.bound_unbacked_symbols = OrderedSet[sympy.Symbol]() + + self.sizevars = SizeVarAllocator(shape_env) + self.graph_input_names: list[str] = [] + self.graph_inputs: dict[str, TensorBox | TorchBindObject | sympy.Expr] = {} + self.graph_inputs_original: dict[str, InputBuffer] = {} + # InputBuffer offsets are relative to input.data_ptr(); explicit FX + # as_strided storage offsets are relative to the input's storage. + self.graph_input_storage_offsets: dict[str, Expr] = {} + self.symbolic_input_sources: dict[ + sympy.Symbol, tuple[str, Literal["size", "stride"], int] + ] = {} + self.partition_maps: list[GraphPartitionMap] | None = None + self.zero_dim_cpu_tensor_list: OrderedSet[str] = OrderedSet() + self.device_types: OrderedSet[str] = ( + const_module.device_types if const_module else OrderedSet() + ) + self.device_idxs: OrderedSet[int] = ( + const_module.device_idxs if const_module else OrderedSet() + ) + self.device_type = "cpu" + self.additional_buffer_deps: dict[str, OrderedSet[str]] = defaultdict( + OrderedSet + ) + self.additional_star_deps: dict[str, OrderedSet[str]] = defaultdict(OrderedSet) + # Maps control_deps FX node to operation names created when lowering it, + # for void ops (e.g. record_event) that return None and therefore cannot + # be referenced by name in subsequent control_deps ordering constraints. + self._void_ctrl_dep_op_names: dict[torch.fx.Node, list[str]] = {} + + # Inplace padding may require Inductor to allocate slightly larger + # tensor for padding. + self.buffer_to_padded_size: dict[str, list[int]] = {} + + self.buffers: list[ir.Buffer] = [] + self.operations: list[ir.Operation] = [] + self.const_output_index: dict[str, int] = ( + const_output_index if const_output_index else {} + ) + self.folded_constants: OrderedSet[str] = ( + OrderedSet(const_output_index.keys()) + if const_output_index + else OrderedSet() + ) + self.constants: dict[str, torch.Tensor] = ( + const_module.constants if const_module else {} + ) + self.named_buffers: dict[str, torch.Tensor] = ( + const_module.named_buffers if const_module else {} + ) + self.mutated_named_buffers: OrderedSet[torch.Tensor] = gm.meta.get( + "mutated_named_buffers", OrderedSet() + ) + self.named_parameters: dict[str, torch.Tensor] = ( + const_module.named_parameters if const_module else {} + ) + self.torchbind_constants: dict[ + str, torch._C.ScriptObject | FakeScriptObject + ] = {} + self.torchbind_replay_objects: dict[ + str, torch._C.ScriptObject | FakeScriptObject + ] = {} + self.opaque_value_type_classes: dict[str, type] = {} + self.seen_subgraphs: dict[str, ir.Subgraph] = {} + self.constant_reprs: dict[str, str] = {} + self.removed_operations: OrderedSet[str] = OrderedSet() + self.removed_buffers: OrderedSet[str] = OrderedSet() + self.removed_inplace_buffers: OrderedSet[str] = OrderedSet() + self.mutated_buffers: OrderedSet[str] = OrderedSet() + self.sdpa_constraint_cache: dict[tuple, ir.IRNode] = {} + self.never_reuse_buffers: OrderedSet[str] = OrderedSet() + self.inplaced_to_remove: OrderedSet[str] = OrderedSet() + self.device_ops: DeviceOpOverrides = None # type: ignore[assignment] + self.wrapper_code: PythonWrapperCodegen = None # type: ignore[assignment] + + from torch._inductor.extern_node_serializer import extern_node_json_serializer + + self.extern_node_serializer: Callable[[list[ir.ExternKernelNode]], Any] = ( + extern_node_serializer + if config.is_fbcode() and extern_node_serializer + else extern_node_json_serializer + ) + + self.current_node: torch.fx.Node = None # type: ignore[assignment] + self.lists: dict[str, list[str]] = {} + self.mutated_inputs: OrderedSet[str] = OrderedSet() + self.mutated_input_idxs: list[int] = [] + self.name_to_buffer: dict[str, ir.Buffer] = {} + self.name_to_users: defaultdict[str, list[ir.IRNode]] = defaultdict(list) + self.name_to_op: dict[str, ir.Operation] = {} + # Side table for CuteDSL capture nodes (may include ReinterpretViews) + self._cutedsl_capture_nodes: dict[str, ir.IRNode] = {} + self.creation_time = time.time() + self.name = name # type: ignore[assignment] + self.cpp_wrapper = cpp_wrapper + self.fx_wrapper = fx_wrapper + + # record multi_kernel choice for cpp_wrapper so the second pass knows + # which sub-kernel is picked. Copy cpp_wrapper to another variable + # since cpp_wrapper flag is OrderedSet to false for the first pass of codegen. + self.record_multi_kernel_choice = cpp_wrapper + self.multi_kernel_to_choice: dict[str, str] = {} + + self.aot_mode = aot_mode + self.graph_id = graph_id + self.post_grad_graph_id = next(_post_grad_graph_counter) + self.scheduler: torch._inductor.scheduler.Scheduler = None # type: ignore[assignment] + + # record intermediate results for input of UsedDefinedTritonKernels + # This will be used if autotuning is done in one pass. + self.autotuning_inputs: list[torch.Tensor] | None = None + self.autotuning_mapping: dict[str, dict[str, int]] | None = None + self.autotuning_grids: dict[str, Any] | None = None + + # current_device is set only during codegen of a device-specific kernel + # a graph can have many devices + self.current_device: torch.device | None = None + + self.nodes_prefer_channels_last = ( + self.find_nodes_prefer_channels_last() if self.layout_opt else OrderedSet() + ) + self._warned_fallback = OrderedSet(["aten.convolution_backward"]) + self.user_visible_output_strides = get_user_visible_output_strides(gm.graph) + mark_nodes_dislike_padding(gm.graph, self.user_visible_output_strides) + self.cache_key: str = "" # This is the cache key for the compiled artifact + self.cache_path: str = "" # This is the path in the filesystem where the compiled artifact is stored + self.cache_linemap: list[ + tuple[int, str] + ] = [] # This is the linemap used by the profiler to mark custom compiled kernels getting run + # Used if lowering encounters cases where cudagraphs are not supported + self.disable_cudagraphs_reason: str | None = None + self.kernel_free_cudagraph: bool = False + + # only keeping one node per device for stack trace purposes + self.device_node_mapping: dict[torch.device, torch.fx.Node] = {} + self.orig_gm: torch.fx.GraphModule = gm.__copy__() + for k, v in self.orig_gm.named_buffers(): + self.named_buffers[k] = v + for k, v in self.orig_gm.named_parameters(): + self.named_parameters[k] = v + self.dynamo_flat_name_to_original_fqn = self.module.meta.get( # type: ignore[operator, union-attr] + "dynamo_flat_name_to_original_fqn", {} + ) + self.allocated_constant_name: dict[str, str] = ( + const_module.allocated_constant_name if const_module is not None else {} + ) + init_backend_registration() + self.get_backend_features = functools.lru_cache(None)(get_backend_features) + + self.effectful_ops: dict[_EffectType, ir.Buffer] = {} + # Track the buffers that we know is unaligned + # This can either be a graph input or the output of fallback + # kernels. + self.unaligned_buffers: OrderedSet[str] = OrderedSet() + self.no_fuse_buffer_names: OrderedSet[str] = OrderedSet() + + # Layout constraints for Triton template buffers. + # Maps buffer name -> expected FixedLayout (computed speculatively without freezing) + self.buffer_layout_constraints: dict[str, ir.FixedLayout] = {} + + self.low_precision_codegen_ops: OrderedSet[str] = OrderedSet() + # more aggressive prologue fusion + self.invoke_quant_ops: OrderedSet[str] = OrderedSet() + + # Below field is related to printing debug intermediate tensor values info for debugging + self.all_codegen_kernel_names: OrderedSet[str] = OrderedSet() + + # state used by for KernelArgs.workspace + self.workspace_id = itertools.count() + + # track the current placeholder index that we are processing + self.placeholder_idx = -1 + + self.bw_donated_idxs = get_donated_idxs() + + # Cache for dep size hints to avoid expensive recomputation + self.dep_size_hint_cache: dict[tuple[Dep, bool], int] = {} + + def freeze_runtime_asserts(self) -> None: + self._shape_env.freeze_runtime_asserts() + + def get_placeholder_sizes_strides( + self, ex: torch.Tensor + ) -> tuple[Sequence[int | Expr], Sequence[int | Expr]]: + sizes, strides, _ = self.symbolic_sizes_strides_storage_offset(ex) + return sizes, strides + + def symbolic_sizes_strides_storage_offset( + self, ex: torch.Tensor + ) -> tuple[Sequence[int | Expr], Sequence[int | Expr], Expr]: + """ + Support dynamic shapes and dynamic strides by assigning variables + to each dimension. We duck-shape tensors, so if two tensors + have the same size they get assigned the same symbolic variable. + """ + if self.reuse_shape_env: + size, stride = ex.size(), ex.stride() + storage_offset = ex.storage_offset() + else: + from torch._dynamo.source import ConstantSource + + # TODO: this should not be needed once #93059 lands + # https://github.com/pytorch/pytorch/pull/94031#discussion_r1096044816 + # TODO: make a dedicated UnknownSource for this? + # NB: This is using the legacy default behavior from + # transfer_symbols_from_foreign_shape_env but we hope we can + # just delete this entirely + source = ConstantSource( + f"__inductor_unknown_tensor_{len(self._shape_env.backed_var_to_val)}" + ) + ( + size, + stride, + storage_offset, + ) = self._shape_env.transfer_symbols_from_foreign_shape_env( + ex.size(), + ex.stride(), + ex.storage_offset(), + source, + ) + + r_size = [sympy.sympify(i) for i in size] + r_stride = [sympy.sympify(i) for i in stride] + r_storage_offset = ( + storage_offset.node.expr + if isinstance(storage_offset, torch.SymInt) + else sympy.sympify(storage_offset) + ) + return r_size, r_stride, r_storage_offset + + def static_sizes_strides( + self, ex: torch.Tensor + ) -> tuple[list[sympy.Expr], list[sympy.Expr]]: + """ + Primarily used to weights + """ + size = [sympy.Integer(i) for i in ex.size()] + stride = [sympy.Integer(i) for i in ex.stride()] + return size, stride + + def get_allocation_size( + self, + node: ir.TensorBox + | ir.StorageBox + | ir.Buffer + | WorkspaceArg + | ir.TorchBindObject, + ) -> Sequence[Expr]: + if isinstance(node, ir.TensorBox): + node = node.data # type: ignore[assignment] + if isinstance(node, ir.StorageBox): + node = node.data # type: ignore[assignment] + if ( + isinstance(node, ir.ComputedBuffer) + and node.name in self.buffer_to_padded_size + ): + # pyrefly: ignore [bad-index, index-error] + return self.buffer_to_padded_size[node.name] + else: + return node.get_size() + + def get_allocation_storage_size( + self, node: ir.Buffer | WorkspaceArg | ir.TorchBindObject + ) -> Expr: + layout = node.get_layout() + size = self.get_allocation_size(node) # consider inplace padding + stride = layout.stride + offset = layout.offset + return compute_required_storage_length(size, stride, offset) # type: ignore[arg-type] + + def has_feature( + self, + device: torch._inductor.ir.IRNode | device | None, + feature: BackendFeature, + ) -> bool: + if not isinstance(feature, BackendFeature): + raise AssertionError( + f"Expected BackendFeature, got {type(feature)}: {feature}" + ) + return feature in self.get_backend_features(get_device_type(device)) + + def get_dep_size_hint(self, dep: Dep, count_bytes: bool = True) -> int: + """ + Get the size hint for a dependency with caching to avoid expensive recomputation. + """ + if (dep, count_bytes) not in self.dep_size_hint_cache: + res = 0 + # Non-tensor graph inputs (TorchBindObject, OpaqueObjectState) + # have no meaningful size — skip the size computation entirely. + inp = self.graph_inputs.get(dep.name) + if isinstance(inp, ir.NonTensorObj): + self.dep_size_hint_cache[(dep, count_bytes)] = 0 + return 0 + try: + if ( + not dep.has_unbacked_symbols() + or self.sizevars.all_unbacked_explicitly_hinted(dep.get_numel()) + ): + if count_bytes: + res = dep.numbytes_hint() + else: + res = dep.numel_hint() + except KeyError: + # In at least one test (test/inductor/test_torchbind.py) we + # create a StarDep that doesn't exist in the graph and calling + # `has_unbacked_symbols()` throws an error. + pass + self.dep_size_hint_cache[(dep, count_bytes)] = res + return self.dep_size_hint_cache[(dep, count_bytes)] + + def get_current_device_or_throw(self) -> torch.device: + if device := self.current_device: + return device + else: + raise RuntimeError("No current device") + + @contextlib.contextmanager + def set_current_device(self, device: torch.device) -> Iterator[None]: + prior = self.current_device + self.current_device = device + try: + yield + finally: + self.current_device = prior + + def get_training_phase(self) -> str: + if self.is_inference: + return "inference" + if self.is_backward: + return "backward" + return "forward" + + @staticmethod + def decide_layout_opt(gm: GraphModule, *, is_inference: bool) -> bool: + """ + Decide if we should enable layout optimization for this graph based on + heuristics. + """ + if not config.layout_optimization: + return False + + if config.force_layout_optimization: + return True + + conv_nodes = [ + n for n in gm.graph.nodes if n.target is torch.ops.aten.convolution.default + ] + + for n in gm.graph.nodes: + if is_mkldnn_conv(n): + conv_nodes.append(n) + + nconv = len(conv_nodes) + + if nconv == 0: + return False + + # For cpu backend and mkldnn enabled, we always use channels_last for better performance. + if ( + torch.backends.mkldnn.enabled # pyrefly: ignore [unbound-name] + and torch.backends.mkldnn.is_available() # pyrefly: ignore [unbound-name] + and all( + n.args[idx].meta["val"].device.type in SUPPORTED_MKLDNN_DEVICES + for n in conv_nodes + for idx in [0, 1] + ) + ): + return True + + # Following models are skipped due to this: + # jx_nest_base + # volo_d1_224 + if len(list(gm.graph.nodes)) >= 300 * nconv: + log.debug("Skipped layout opt because only a few conv") + return False + + if any( + has_free_symbols(n.args[idx].meta["val"]) + for n in conv_nodes + for idx in [0, 1] + ): + log.debug( + "See perf regression with dynamic shape. Follow up in https://github.com/pytorch/pytorch/issues/102670" + ) + return False + + def is_grouped(n: Any) -> bool: + meta_val = n.args[1].meta["val"] # type: ignore[union-attr, operator] + if not isinstance(meta_val, torch.Tensor): + raise AssertionError(f"Expected torch.Tensor, got {type(meta_val)}") + return n.args[-1] > 1 and meta_val.size(1) > 1 # type: ignore[union-attr, operator] + + def is_in_out_channel(n: torch.fx.Node) -> bool: + return ( + n.args[1].meta["val"].size(0) * 2 <= n.args[1].meta["val"].size(1) # type: ignore[union-attr, operator] + and n.args[1].meta["val"].size(2) > 1 # type: ignore[union-attr, operator] + ) + + def is_small_channel(n: torch.fx.Node) -> bool: + return ( + n.args[1].meta["val"].size(0) <= 64 # type: ignore[union-attr, operator] + and n.args[1].meta["val"].size(1) <= 64 # type: ignore[union-attr, operator] + ) + + # only grouped convolutions benchmarked as slower in conv samples for inference only + if is_inference: + flop_counts: dict[str, float] = defaultdict(float) + for node in conv_nodes: + counted_flops = count_flops_fx(node) + if counted_flops is None: + continue + + if is_grouped(node): + node_type = "grouped" + elif is_small_channel(node): + node_type = "small" + elif is_in_out_channel(node): + node_type = "in_out" + else: + node_type = "default" + + flop_counts[node_type] += counted_flops + else: + log.debug("Conv inputs meta not found") + + # average benchmarked channels last speedup / slowdown, < 1 is speedup. + # taken from the set of convolution inputs in benchmarks/dynamo/microbenchmarks/operator_inp_logs/torchbench_train/ + # To regenerate these numbers follow https://gist.github.com/eellison/55d7a6ed6f39829d68ac56f95f4df5bb + GROUPED_MULTIPLIER = 1.358 + DEFAULT_MULTIPLIER = 0.823 + IN_OUT_MULTIPLIER = 0.725 + SMALL_MULTIPLIER = 0.783 + + total_flops = sum(flop_counts.values()) + # TODO - get different values per hardware + weighted_flops = ( + flop_counts["grouped"] * GROUPED_MULTIPLIER + + flop_counts["small"] * SMALL_MULTIPLIER + + flop_counts["in_out"] * IN_OUT_MULTIPLIER + + flop_counts["default"] * DEFAULT_MULTIPLIER + ) + do_layout_opt = weighted_flops <= total_flops + if not do_layout_opt: + log.debug( + "Skipped layout opt in inference because weighted flops indicate slowdown, default: %d, channels last: %d", + total_flops, + weighted_flops, + ) + return do_layout_opt + + # Channels last layout can dramatically hurt grouped conv perf. E.g. + # Conv with arguments like + # {"input_shape": [32, 224, 112, 112], "weight_shape": [224, 112, 3, 3], + # "stride": [2, 2], "padding": [1, 1], "groups": 2} + # slows down 31x using channels last.. + + # But a lot of timm models use depthwise separable convolution which will + # result in grouped convolution with in-channel size == 1. + # For those grouped convolution, channels last still helps a lot. + # E.g. + # Conv with arguments + # {"input_shape": [128, 58, 56, 56], "weight_shape": [58, 1, 3, 3], + # "stride": [2, 2], "padding": [1, 1], "groups": 58} + # get 1.86x speedup with channels last layout. + # + # The following heuristics skip using channels-last if the model contains + # grouped convolution with in-channels > 1. + if any(map(is_grouped, conv_nodes)): + log.debug( + "Skip layout opt because found grouped convolution with >1 in_channels!" + ) + return False + + # For some models that contain convolution with larger in-channel than out-channel, applying + # channels last hurts performance. + # Following models are skipped due to this: + # - pytorch_unet + # - phlippe_densenet (slightly worse) + # - Background_Matting (1.22x -> 0.821x) + # - pytorch_CycleGAN_and_pix2pix (1.597x -> 1.294x) + if any(map(is_in_out_channel, conv_nodes)): + log.debug( + "Skip layout opt because some convolutions have smaller out_channel" + ) + return False + + # Following models are skipped due to this: + # - functorch_maml_omniglot + if all(map(is_small_channel, conv_nodes)): + log.debug("Skip layout opt because all convolution channels are too small") + return False + + return True + + def qualify_name(self, name: str) -> str: + """Prepend the given name with the graph name if any.""" + if self.name is not None: + return f"{self.name}_{name}" + return name + + def make_subgraph( + self, + gm: torch.fx.GraphModule, + example_inputs: list[torch.Tensor], + subgraph_name: str, + ) -> SubgraphLowering: + """ + Make a subgraph of the current graph with all inherited parts, except + the graph module (`gm`) and `example_inputs`. The subgraphs are lowered + separately and lifted into a separate function in the parent output + wrapper code. The subgraph name is qualified by the parent graph's + name. Note that the lifting of subgraph is supported for python wrapper + only. For cpp wrapper, we inline the subgraphs in the parent wrapper. + """ + return SubgraphLowering( + parent=self, + gm=gm, + example_inputs=example_inputs, + shape_env=self._shape_env, + cpp_wrapper=self.cpp_wrapper, + aot_mode=self.aot_mode, + extern_node_serializer=self.extern_node_serializer, + is_inference=self.is_inference, + is_backward=self.is_backward, + name=self.qualify_name(subgraph_name), + ) + + def find_nodes_prefer_channels_last(self) -> OrderedSet[Node]: + """ + The rule to decide if a node prefers channels last is simple. + 1. if it's input/output of a convolution + 2. if one of its user prefers channels last + + We have rule 1 because cudnn runs a faster convolution kernel for channels last inputs; + Rule 2 is also important. It makes sure that indirect inputs to convolution also prefers + channels last. + + Consider the scenario: conv -> batch-norm -> relu -> conv + Without rule 2, batch-norm output may use a contiguous layout. That will cause 2 extra copies: + 1. the output of batch-norm should be channels last initially since its input is a conv's output. + Forcing the batch-norm's output to be contiguous results in the first copy + 2. The second conv's input is initially contiguous. This layout is propagated from the batch-norm's output. + We need to convert it to channels last layout which results in the second copy. + With rule 2, we make sure all the tensors in the chain use channels last layout. So both copies + can be saved. + """ + last_conv = None + nodes_cannot_propagate = [torch.ops.aten.bmm.default] + output_set = OrderedSet[Node]() + for n in reversed(self.module.graph.nodes): # type: ignore[arg-type, union-attr] + if n.target is torch.ops.aten.convolution.default: + output_set.add(n) + if last_conv is None: + last_conv = n + continue + if n.target in nodes_cannot_propagate: + continue + if is_mkldnn_conv(n): + output_set.add(n) + continue + for user in n.users: + if user in output_set: + output_set.add(n) + break + + # need a second pass to add downstream nodes of those channel last nodes to the sets. + # This pass is especially needed to avoid mix-layout kernel inputs in backward pass. + # + # Let's say a conv-batchnorm 's output is passed to relu whose output is in turn returned + # from the fwd graph. Without this second pass, we will force relu's output to be contiguous. + # Then in the kernel in backward pass, the contiguous output of relu may be mix with other channels last + # tensors and passed to a kernel. + # + # This pass improve yolov3 training speedup from 1.116x (worse than disabling layout optimization speedup 1.196x) to 1.457x. + # It also improves dla102 training speedup from 1.240x (worse than disabling layout optimization speedup 1.523x) to 1.835x . + # This also helps the following models: + # - res2net101_26w_4s + # - res2net50_14w_8s + # - sebotnet33ts_256 + for n in self.module.graph.nodes: # type: ignore[union-attr] + # layout propagation ends at last conv node, which will benefit vison transformers. + if last_conv is not None and n == last_conv: + break + if n in output_set: + for user in n.users: + if user.target in nodes_cannot_propagate: + continue + output_set.add(user) + + return output_set + + def warn_fallback(self, name: str) -> None: + if name not in self._warned_fallback: + self._warned_fallback.add(name) + perf_hint_log.info("Using FallbackKernel: %s", name) + + def add_device_info(self, device: torch.device) -> None: + self.device_types.add(device.type) + if device.index is not None: + self.device_idxs.add(device.index) + if V.graph.current_node and device not in self.device_node_mapping: + self.device_node_mapping[device] = V.graph.current_node + + @property + def fake_mode(self) -> torch._subclasses.fake_tensor.FakeTensorMode: + return V.fake_mode + + @property + def is_dual_wrapper_mode(self) -> bool: + """True when generating dual-wrapper-mode C++ for both JIT and AOTI. + + Dual-wrapper mode emits a JIT pass that drives Triton autotune/compile + alongside the AOTI output, so it is needed iff at least one device in + the graph uses the Triton backend. + """ + if not self.aot_mode or config.triton.autotune_at_compile_time: + return False + return any(ir.is_triton(d) for d in self.device_types) + + def try_get_buffer( + self, buffer_name: str + ) -> ir.TensorBox | ir.Buffer | ir.TorchBindObject | None: + if buffer_name in self.name_to_buffer: + return self.name_to_buffer[buffer_name] + if buffer_name in self.graph_inputs: + return self.graph_inputs[buffer_name] + if buffer_name in self.constants: + data = V.graph.constants[buffer_name] + return ir.ConstantBuffer( + name=buffer_name, + layout=ir.FixedLayout( + data.device, data.dtype, *V.graph.static_sizes_strides(data) + ), + ) + + return None + + def add_symbol_graph_input(self, symbol: sympy.Expr) -> None: + raise RuntimeError("Should not be called for the main graph") + + def get_buffer( + self, buffer_name: str + ) -> ir.TensorBox | ir.Buffer | ir.TorchBindObject: + buf = self.try_get_buffer(buffer_name) + if buf is not None: + return buf + raise RuntimeError(f"Failed to find buffer matching name {buffer_name}") + + def get_dtype(self, buffer_name: str) -> torch.dtype: + if buffer_name in self.constants: + return self.constants[buffer_name].dtype + # For a mutation op we should return the dtype of the buffer being mutated + if ( + hasattr(self.scheduler, "mutation_real_name") + and buffer_name in self.scheduler.mutation_real_name + ): + mutated_buf = self.scheduler.mutation_real_name[buffer_name] + if mutated_buf in self.name_to_buffer: + return self.name_to_buffer[mutated_buf].get_dtype() + if mutated_buf in self.graph_inputs: + return self.graph_inputs[mutated_buf].get_dtype() + if buffer_name in self.name_to_buffer: + return self.name_to_buffer[buffer_name].get_dtype() + if buffer_name in self.graph_inputs: + return self.graph_inputs[buffer_name].get_dtype() + m = re.match(r"(as_strided|reinterpret_tensor)\(([a-zA-Z0-9_]+),", buffer_name) + if m: + return self.get_dtype(m.group(1)) + raise KeyError(f"could not find {buffer_name}") + + def get_numel(self, buffer_name: str) -> int | Expr: + if buffer_name in self.constants: + return self.constants[buffer_name].numel() + if buffer_name in self.name_to_buffer: + buf = self.name_to_buffer[buffer_name] + if not buf.has_tensor_output(): + return 1 + return buf.get_numel() + if buffer_name in self.graph_inputs: + return self.graph_inputs[buffer_name].get_numel() + raise KeyError(f"could not find {buffer_name}") + + def run(self, *args: Any) -> Any: # type: ignore[override] + with dynamo_timed("GraphLowering.run"): + return super().run(*args) + + def register_operation(self, op: ir.Operation) -> str: + if op.operation_name is not None: + raise AssertionError(f"Operation registered twice: {op}") + if not isinstance(op, ir.Operation): + raise AssertionError(f"Expected ir.Operation, got {type(op)}") + name = self.qualify_name(f"op{len(self.operations)}") + self.operations.append(op) + self.name_to_op[name] = op + op.operation_name = name + return name + + def register_buffer(self, buffer: ir.Buffer, *, set_name: bool = False) -> str: + name = self.qualify_name(f"buf{len(self.buffers)}") + self.buffers.append(buffer) + self.name_to_buffer[name] = buffer + device = buffer.get_device() + if ( + # Skip empty CPU tensor so that CUDA graphs can succeed, see https://github.com/pytorch/pytorch/pull/114144 + device is not None + and not ( + isinstance(buffer, ir.ComputedBuffer) + and buffer.is_zero_elements() + and device == torch.device("cpu") + ) + ): + self.add_device_info(device) + + if set_name: + buffer.name = name + return name + + def register_operation_list(self, operation_names: list[str]) -> str: + name = self.qualify_name("list_" + "_".join(operation_names)) + self.lists[name] = operation_names + return name + + def register_users_of(self, node_output: Iterable[ir.IRNode] | ir.IRNode) -> None: + def register(value: Iterable[ir.IRNode] | ir.IRNode) -> None: + if isinstance(value, (list, tuple)): + for x in value: + register(x) + if isinstance(value, ir.TensorBox): + for read_name in value.get_read_names(): + self.name_to_users[read_name].append(value) + + register(node_output) + + def mark_buffer_mutated(self, name: str) -> None: + """ + When a buffer is mutated we need to make sure all the reads to + the old version are realized before the mutation happens. + """ + if not isinstance(name, str): + raise AssertionError(f"Expected str, got {type(name)}") + self.mutated_buffers.add(name) + + if name not in self.name_to_users: + return + + for user in self.name_to_users[name]: + user.realize() + + def get_original_value_of_constant(self, name: str) -> torch.Tensor: + """ + In AOTI, module buffers may have been mutated during the tracing and compilation. + Thus we need to read from previously stored original buffers, to make sure the + generated model.so uses correct initial values. + """ + if name not in self.allocated_constant_name or name not in self.constants: + raise AssertionError("Can not find the original value for " + name) + orig_name = get_cloned_parameter_buffer_name(self.allocated_constant_name[name]) + return ( + self.module.meta[orig_name] # type: ignore[index] + if orig_name in self.module.meta # type: ignore[operator] + else self.constants[name] + ) + + def allocate_non_dup_const_name(self, name: str | None, data: Tensor) -> str: + if not config.aot_inductor.use_runtime_constant_folding: + for constant_name, value in self.constants.items(): + if is_same_tensor(data, value): + return constant_name + + if name is None: + name = f"constant{len(self.constants)}" + orig_name = name + if name[0].isdigit(): + name = f"constant_{name}" + name = self.qualify_name(name) + # We may generate a var name for each constant in the codegen. + # Let's only keep sane characters. + prefix = normalize_name(name) + name = prefix + cnt = 0 + while name in self.constants: + name = f"{prefix}_{cnt}" + cnt += 1 + self.constants[name] = data + self.constant_reprs[name] = ( + f"{data.device!r} {data.dtype!r} " + f"{tuple(data.size())!r} {tuple(data.stride())!r} " + f"{hash(data):x}" + ) + self.allocated_constant_name[name] = orig_name # type: ignore[assignment] + return name + + def add_tensor_constant(self, data: Tensor, name: str | None = None) -> TensorBox: + new_name = self.allocate_non_dup_const_name(name, data) + return TensorBox.create( + ir.ConstantBuffer( + name=new_name, + layout=FixedLayout( + data.device, + data.dtype, + *self.static_sizes_strides(data), + is_pinned=_is_cpu_strided_tensor_pinned(data), + ), + ) + ) + + def constant_name(self, name: str, device_override: torch.device | None) -> str: + """ + We AOT copy constants to the devices they are needed on. + If device_override doesn't match the constant's device, then + copy it and return a different name. + """ + if self.constants[name].device == device_override or device_override is None: + return name + with torch.utils._python_dispatch._disable_current_modes(): + # caller might have OrderedSet fake tensor mode which will create a fake tensor + # when calling .to, so unset modes here + non_dup_const_name = self.allocate_non_dup_const_name( + f"{name}_{device_override.type}{device_override.index or 0}", + self.constants[name].to(device_override), + ) + + if non_dup_const_name not in self.constants: + raise AssertionError( + f"{non_dup_const_name} should be in V.graph.constants already" + ) + + # register device-copied buffers and parameters to graph as well + # to codegen correct torch::aot_inductor::ConstantType for them rather than `Unknown` + if any( + name == normalize_name(buffer_name) + for buffer_name in self.named_buffers + ): + self.named_buffers[non_dup_const_name] = self.constants[ + non_dup_const_name + ] + + if any( + name == normalize_name(param_name) + for param_name in self.named_parameters + ): + self.named_parameters[non_dup_const_name] = self.constants[ + non_dup_const_name + ] + + return non_dup_const_name + + @typing_extensions.override + def placeholder( # pyrefly: ignore [bad-override] + self, + target: str, # type: ignore[override] + args: tuple[object], # type: ignore[override] + kwargs: dict[str, object], + ) -> Expr | TensorBox | None: + self.placeholder_idx += 1 + example = super().placeholder(target, args, kwargs) # type: ignore[arg-type] + target = self.qualify_name(target) + if isinstance(example, SymTypes): + expr = _get_placeholder_expr(example.node) + self.graph_inputs[target] = expr + self.graph_input_names.append(target) + return expr + elif isinstance(example, (int, bool, float)): + expr = sympy.sympify(example) + self.graph_inputs[target] = expr + self.graph_input_names.append(target) + return expr + elif isinstance(example, FakeScriptObject): + obj = TorchBindObject(name=target, value=example) + self.graph_inputs[target] = obj + self.graph_input_names.append(target) + return obj + elif example is None: + self.graph_input_names.append(target) + return None + if isinstance(example, BackwardState): + # Ignored arg, must be unused + # Alternately we could filter this out in AotAutograd + self.graph_input_names.append(target) + return None + # See note: Note: [Generator arguments in AOTDispatcher] + elif isinstance(example, torch.Generator): + gen = ir.GeneratorState(name=target, device=example.device) + self.graph_inputs[target] = gen # type: ignore[assignment] + self.graph_input_names.append(target) + return gen + elif is_opaque_symbolic_type(type(example)): + opaque_obj = ir.OpaqueObjectState(name=target, value=example) + self.graph_inputs[target] = opaque_obj # type: ignore[assignment] + self.graph_input_names.append(target) + return opaque_obj + + if not isinstance(example, torch.Tensor): + raise AssertionError( + f"Expected torch.Tensor, got {type(example)}: {example}" + ) + # todo(chilli): We can remove the last check once we turn buffers into + # static shape tensors. That's a hack to workaround Inductor believing + # the buffer should be static but us passing in a fake tensor with + # symbolic shapes. + if not example._has_symbolic_sizes_strides: + # the first N inputs are weights + sizes, strides = self.static_sizes_strides(example) + storage_offset = sympy.Integer(example.storage_offset()) + else: + sizes, strides, storage_offset = self.symbolic_sizes_strides_storage_offset( + example + ) + + if ( + self.is_backward + and self.bw_donated_idxs + and self.placeholder_idx in self.bw_donated_idxs + ): + tensor = TensorBox.create( + DonatedBuffer( + name=target, + layout=FixedLayout(example.device, example.dtype, sizes, strides), + ) + ) + else: + # TODO(jansel): handle input aliasing + tensor = TensorBox.create( + InputBuffer( + name=target, + layout=FixedLayout(example.device, example.dtype, sizes, strides), + ) + ) + + self.graph_inputs[target] = tensor + self.graph_input_names.append(target) + self.graph_input_storage_offsets[target] = storage_offset + self.graph_inputs_original[target] = tensor.data.data # type: ignore[union-attr] + if self.current_node.users: # cudagraphs should work with an unused CPU input + self.add_device_info(example.device) + + # Note: [Input Alignment handling in Inductor] + # Alignment matters for generating efficient code. Some operations, + # e.g. vectorized loads, can only be performed on aligned inputs. + # + # But if we codegen assuming aligned inputs and then get unaligned + # inputs at runtime, then we are forced to clone - which is bad for + # both perf and memory usage. + # + # One option would be to guard on storage_offset%ALIGNMENT, and then + # codegen based on this. But storage_offset guards turned out to be + # expensive and cause recompiles; Instead, we're generating code + # based on the alignment of the example input without guarding. + with maybe_get_suppress_shape_guards_ctx(): + if not should_assume_input_aligned(example): + self.unaligned_buffers.add(target) + return tensor + + @typing_extensions.override + def call_function(self, target: Callable, args: Any, kwargs: dict[str, Any]) -> Any: # type: ignore[type-arg] + if target is operator.getitem and isinstance(args[0], (list, tuple, dict)): + return super().call_function(target, args, kwargs) + + # hasattr on OpOverloadPacket is slow, check isinstance first + if not isinstance(target, torch._ops.OpOverloadPacket) and hasattr( + target, "_inductor_lowering_function" + ): + # passthrough lowerings from .pattern_matcher + return target(*args, **kwargs) + + if target not in lowerings: + if not isinstance(target, torch._ops.OpOverload): + raise AssertionError(f"{target} is not an OpOverload") + base_name = target.name().split(".")[0] + if base_name in FALLBACK_ALLOW_LIST: + make_fallback( + target, + warn=False, + get_decomp_fn=self.get_decomp_fn, + override_decomp=True, + ) + elif config.implicit_fallbacks: + error = ( + MissingOperatorWithDecomp + if get_decompositions([target]) + else MissingOperatorWithoutDecomp + ) + log.info( + "Creating implicit fallback for:\n%s", + LazyString(error.operator_str, target, args, kwargs), + ) + + tag: torch._C.Tag | None = get_layout_constraint_tag( + target, with_default=False + ) + if ( + tag is None + and torch._library.utils.is_builtin(target) + and self.is_backward + ): + # for implicit fallback ATen ops during backward, if there + # is no layout constraint tag, we conservatively require contiguous + # input since some eager kernels do not + # support non-contiguous inputs. Otherwise they may silently cause + # accuracy problems. Check https://github.com/pytorch/pytorch/issues/140452 + # We only do this For ATen ops and for backward. + # + # TODO: should really switch to "needs_fixed_stride" constraint on these + # and identify them one by one. + decided_constraint: Callable[..., tuple[Any, Any]] | None = ( + require_contiguous + ) + else: + default_tag: torch._C.Tag = get_layout_constraint_tag( + target, with_default=True + ) + decided_constraint = tag_to_layout_constraint(default_tag) + + make_fallback( + target, + layout_constraint=decided_constraint, + get_decomp_fn=self.get_decomp_fn, + ) + + elif get_decompositions([target]): + # There isn't a good way to dynamically patch this in + # since AOT Autograd already ran. The error message tells + # the user how to fix it. + raise MissingOperatorWithDecomp(target, args, kwargs) + else: + raise MissingOperatorWithoutDecomp(target, args, kwargs) + + try: + log.debug(" via %s", lowerings[target]) # type: ignore[index] + + n = self.current_node + layout_constraints = maybe_layout_constraints(target) + if layout_constraints: + old_args, old_kwargs = args, kwargs + if layout_constraints is constrain_to_fake_tensors: + # only constrain_to_fake_tensor if this exists. + # otherwise, no constraints at all: the implication is + # that this operator was inserted by a custom pass + # so we'll give them the freedom. + if "eager_input_vals" in n.meta: + fake_args, fake_kwargs = n.meta["eager_input_vals"] + + # (fake_args, fake_kwargs) might not align with (args, kwargs). + # we need to normalize them based on the schema + if not isinstance(target, torch._ops.OpOverload): + raise AssertionError( + f"Expected torch._ops.OpOverload, got {type(target)}" + ) + + def normalize(args: Any, kwargs: Any) -> tuple[Any, Any]: + result = torch.fx.operator_schemas.normalize_function( + target, args, kwargs + ) + if result is None: + raise AssertionError( + f"normalize_function returned None for {target}" + ) + return result[0], result[1] + + fake_args, fake_kwargs = normalize(fake_args, fake_kwargs) + args, kwargs = normalize(args, kwargs) + old_args, old_kwargs = normalize(old_args, old_kwargs) + + args, kwargs = constrain_to_fake_tensors( + args, kwargs, fake_args, fake_kwargs + ) + else: + args, kwargs = layout_constraints(n, *args, **kwargs) + + if "should_fallback" in n.meta or n.meta.get("custom", {}).get( + "fallback_to_eager" + ): + out = fallback_handler(target, add_to_fallback_set=False)( + *args, **kwargs + ) + else: + out = None + + if ( + target in user_lowerings + and target not in V.active_user_lowering_ops + ): + # User-registered lowering takes priority, with recursion guard + V.active_user_lowering_ops.add(target) + try: + # pyrefly: ignore[bad-index] + out = user_lowerings[target](*args, **kwargs) + finally: + V.active_user_lowering_ops.discard(target) + + # If no user_lowering, or it returned None fall back to normal lowering + if out is None: + if target in lowerings: + out = lowerings[target](*args, **kwargs) + else: + # Fallback for ops not in lowerings (e.g., custom ops during recursion) + out = fallback_handler(target, add_to_fallback_set=False)( + *args, **kwargs + ) + + if layout_constraints: + # layout_constraints are allowed to make new copies of the inputs. + # if they do, and if the target is mutable, then we need to + # write the new values back into the original inputs. + self.propagate_mutation(n, old_args, old_kwargs, args, kwargs) # type: ignore[possibly-undefined] + + return out + except Exception as e: + stack_trace = None + if ( + hasattr(self, "current_node") + and self.current_node is not None + and hasattr(self.current_node, "meta") + and self.current_node.meta is not None + ): + stack_trace = self.current_node.meta.get("stack_trace", None) + raise LoweringException( + e, target, args, kwargs, stack_trace=stack_trace + ).with_traceback(e.__traceback__) from None + + @staticmethod + def can_inline_constant(t: torch.Tensor) -> bool: + """ + True if this is a small constant attr that will be inlined. + """ + return len(t.shape) == 1 and t.shape[0] <= 8 + + # pyrefly: ignore [bad-override] + def get_attr( + self, + target: str, # type: ignore[override] + args: tuple[()], # type: ignore[override] + kwargs: dict[str, object], + ) -> Constant | TensorBox | ShapeAsConstantBuffer | ir.Subgraph | TorchBindObject: + # this is a constant + value = getattr_recursive(self.module, target) # type: ignore[arg-type] + + if isinstance(value, torch.fx.GraphModule): + # Reuse the existing subgraph if we have seen it before already. + if target in self.seen_subgraphs: + return self.seen_subgraphs[target] + + nested_config = getattr(value, "meta", {}).get("nested_region_config") + inductor_config_patches = getattr( + nested_config, "inductor_config_patches", None + ) + out = ir.Subgraph( + name=target, + graph_module=value, + inductor_config_patches=inductor_config_patches, + ) + self.seen_subgraphs[target] = out + return out + + if isinstance(value, torch._C.ScriptObject): + self.torchbind_constants[target] = value + self.constant_reprs[target] = "" + return TorchBindObject(name=target, value=value) + elif isinstance(value, FakeScriptObject): + self.torchbind_constants[target] = value + self.constant_reprs[target] = "" + return TorchBindObject(name=target, value=value) + elif is_custom_class(type(value)): + self.torchbind_constants[target] = value # type: ignore[arg-type] + self.constant_reprs[target] = "" + return TorchBindObject(name=target, value=value) # type: ignore[arg-type] + + if not isinstance(value, torch.Tensor): + raise AssertionError(f"Expected torch.Tensor, got {type(value)}") + if ( + config.aot_inductor.use_runtime_constant_folding + or config.always_keep_tensor_constants + or unsupported_output_tensor(value) + or target in self.mutated_named_buffers + ): + return self.add_tensor_constant(value, target) + + with no_dispatch(): + if value.shape == (): + return Constant( + value=value.item(), dtype=value.dtype, device=value.device + ) + if self.can_inline_constant(value): + log.debug("Inlining constant: %s ", target) + # tensor lowering has constant inlining logic + from .lowering import tensor + + return tensor( + value.tolist(), + dtype=value.dtype, + device=value.device, + pin_memory=_is_cpu_strided_tensor_pinned(value), + ) + + return self.add_tensor_constant(value, target) + + def call_module(self, target: Any, args: Any, kwargs: Any) -> NoReturn: + raise AssertionError + + def call_method(self, target: Any, args: Any, kwargs: Any) -> NoReturn: + raise AssertionError + + @typing_extensions.override + def output( + self, + target: torch.fx.node.Target, + args: tuple[torch.fx.node.Argument, ...], + kwargs: dict[str, object], + ) -> None: + result = super().output(target, args, kwargs) # type: ignore[arg-type] + if not isinstance(result, (tuple, list)): + # nested subgraphs can have singleton outputs + result = (result,) + if not isinstance(result, (tuple, list)): + raise AssertionError(f"Expected tuple or list, got {type(result)}") + result = [ + ir.OpaqueValueTypeConstant(value=x) + if is_opaque_constant_type(type(x)) + else x + for x in result + ] + _allowed_output_types = ( + TensorBox, + ir.Constant, + type(None), + ir.ConstantBuffer, + sympy.Expr, + sympy.logic.boolalg.Boolean, + int, + ir.EffectfulKernel, + ir.ShapeAsConstantBuffer, + TorchBindObject, + ir.OpaqueMultiOutput, + ir.OpaqueValueTypeConstant, + ir.OpaqueObjectState, + ) + if not all(isinstance(x, _allowed_output_types) for x in result): + bad = [x for x in result if not isinstance(x, _allowed_output_types)] + raise AssertionError( + f"Unexpected output types: {[type(x) for x in bad]}, full result: {result}" + ) + + fx_node_args = V.graph.current_node.args[0] # type: ignore[arg-type] + if not isinstance(fx_node_args, (tuple, list)): + # nested subgraphs can have singleton outputs + fx_node_args = (fx_node_args,) + result = [ir.ExternKernel.realize_input(x) for x in result] + result_correct_strides = [] + + if len(fx_node_args) != len(result): + raise AssertionError( + f"Mismatch between fx_node_args length ({len(fx_node_args)}) and result length ({len(result)})" + ) + for r, fx_node in zip(result, fx_node_args): + r = _realize_efficient_zerotensor_output(r, fx_node) + if not isinstance(r, (ir.TensorBox, ir.BaseView)): + result_correct_strides.append(r) + elif isinstance(r.get_output_spec(), ir.CommBufferLayout): + # Active references to persistent comm buffers are not allowed + # outside of graphs + result_correct_strides.append(ir.ExternKernel.copy_input(r)) + else: + # AOT Autograd tries to detect stride divergence of inductor from output metadata. + # Here, we try to avoid spurious divergence by matching insignificant strides such as + + # should have already been realized + if not torch._inductor.ir.is_storage_and_layout(r): + raise AssertionError(f"Expected storage_and_layout, got {type(r)}") + meta_strides = [ + s.node.expr if isinstance(s, torch.SymInt) else s + # pyrefly: ignore [missing-attribute] + for s in fx_node.meta["val"].stride() + ] + result_correct_strides.append( + ir.try_match_insignificant_strides(r, meta_strides) + ) + + self.graph_outputs = result_correct_strides + value: ir.IRNode + for name, value in self.graph_inputs.items(): + if isinstance( + value, + ( + TorchBindObject, + sympy.Basic, + torch._inductor.ir.GeneratorState, + torch._inductor.ir.OpaqueObjectState, + ), + ): + continue + if not isinstance(value, TensorBox): + raise AssertionError( + f"Unsupported inductor graph input type: {type(value)}" + ) + value.realize() + if not isinstance(value, TensorBox): + raise AssertionError( + f"Expected TensorBox after realize(), got {type(value)}" + ) + value = value.data + if not isinstance(value, ir.StorageBox): + raise AssertionError(f"Expected ir.StorageBox, got {type(value)}") + value_storage_box = value + value = value.data + if not isinstance(value, InputBuffer) or value.get_name() != name: + # one of our inputs was mutated, need to turn that into a copy + ir.MutationLayoutSHOULDREMOVE.realize_into( + value, self.graph_inputs_original[name] + ) + # replace output with mutated input + try: + ind = self.graph_outputs.index(value_storage_box) + self.graph_outputs[ind] = self.graph_inputs_original[name] + except ValueError: + pass + + self.finalize() + log.debug( + "Force channels last inputs for %d conv for the current graph with id %d", + self.num_channels_last_conv, + self.graph_id if self.graph_id is not None else -1, + ) + + def finalize(self) -> None: + for buf in self.buffers: + buf.decide_layout() + + @contextmanager + def set_current_node(self, node: torch.fx.Node): # type: ignore[no-untyped-def] + old = self.current_node + try: + self.current_node = node + yield + finally: + self.current_node = old + + @contextmanager + def set_current_wrapper_code(self) -> Iterator[None]: + old = self.wrapper_code + try: + yield + finally: + self.wrapper_code = old + + def propagate_mutation( + self, + fx_node: torch.fx.Node, + old_args: tuple[Any], + old_kwargs: dict[str, Any], + new_args: tuple[Any], + new_kwargs: dict[str, Any], + ) -> None: + """Propagate mutations on new_args/new_kwargs back to old_args/old_kwargs. + + Assumes we may have cloned old_args/old_kwargs into new_args/new_kwargs + and then called fx_node(*new_args, **new_kwargs). + + If fx_node mutates any of new_args/new_kwargs, and they are different from + old_args/old_kwargs, then we need to update the original tensor. + """ + if len(old_args) != len(new_args): + raise AssertionError( + f"old_args length ({len(old_args)}) != new_args length ({len(new_args)})" + ) + if len(old_kwargs) != len(new_kwargs): + raise AssertionError( + f"old_kwargs length ({len(old_kwargs)}) != new_kwargs length ({len(new_kwargs)})" + ) + + def already_reflected(old_arg: Any, new_arg: Any) -> bool: + # No propagation is needed when new_arg already reflects the + # mutation of old_arg: either they are the same object, or they are + # distinct IR nodes aliasing the same buffer (e.g. an in-place op + # whose output was not cloned). Emitting copy_ in the aliasing case + # would lower to a self-referential (buf = buf) node, which the + # scheduler's compute_ancestors cannot represent (self-edge). + if old_arg is new_arg: + return True + if isinstance(old_arg, ir.IRNode) and isinstance(new_arg, ir.IRNode): + name = old_arg.maybe_get_name() + return name is not None and name == new_arg.maybe_get_name() + return False + + if fx_node.target is torch.ops.higher_order.triton_kernel_wrapper_mutation: + kwargs = fx_node.kwargs["kwargs"] + if not isinstance(kwargs, dict): + raise AssertionError(f"Expected dict, got {type(kwargs)}") + mutated = torch._higher_order_ops.triton_kernel_wrap.get_mutated_tensors( + old_kwargs["kernel_idx"], + old_kwargs["constant_args_idx"], + { + k: v.meta["val"] if isinstance(v, torch.fx.Node) else v + for k, v in kwargs.items() + }, + old_kwargs["tma_descriptor_metadata"], + ) + for name in mutated: + old_arg = old_kwargs["kwargs"][name] + new_arg = new_kwargs["kwargs"][name] + if already_reflected(old_arg, new_arg): + continue + + self.call_function(torch.ops.aten.copy_.default, (old_arg, new_arg), {}) + return + + if not isinstance(fx_node.target, torch._ops.OpOverload): + raise AssertionError( + f"Expected torch._ops.OpOverload, got {type(fx_node.target)}" + ) + + def maybe_propagate( + schema_arg: torch._C.Argument, old_arg: ir.IRNode, new_arg: ir.IRNode + ) -> None: + if old_arg is new_arg: + return + if schema_arg.alias_info is not None and schema_arg.alias_info.is_write: + # The lowering for copy_ is smart enough to "replace" old_arg with + # new_arg in all future uses so a copy_ kernel never gets emitted. + # old_arg, new_arg may be immutable_list + if isinstance(old_arg, ir.IRNode): + old_arg = (old_arg,) # type: ignore[assignment] + new_arg = (new_arg,) # type: ignore[assignment] + + for old_arg_item, new_arg_item in zip(old_arg, new_arg): # type: ignore[call-overload] + if already_reflected(old_arg_item, new_arg_item): + continue + self.call_function( + torch.ops.aten.copy_.default, (old_arg_item, new_arg_item), {} + ) + + schema = fx_node.target._schema + for idx, (old_arg, new_arg) in enumerate(zip(old_args, new_args)): + schema_arg = schema.arguments[idx] + maybe_propagate(schema_arg, old_arg, new_arg) + + schema_kwargs = {arg.name: arg for arg in schema.arguments} + + for key in old_kwargs: + old_arg = old_kwargs[key] + new_arg = new_kwargs[key] + schema_arg = schema_kwargs[key] + maybe_propagate(schema_arg, old_arg, new_arg) + + @staticmethod + def _get_node_stream(n: torch.fx.Node) -> int | None: + """Get the user-annotated stream index from FX node metadata.""" + return n.meta.get("custom", {}).get("stream") + + @staticmethod + def _get_node_mempool(n: torch.fx.Node) -> tuple[int, int] | None: + """Get the user-annotated CUDA MemPool from FX node metadata.""" + custom = n.meta.get("custom", {}) + if "mempool" not in custom: + return None + return custom["mempool"], custom["mempool_device"] + + def _realize_inputs_at_context_boundaries(self, n: torch.fx.Node) -> None: + """Realize IR inputs that are in a different stream or mempool context. + + Without this, pointwise ops across context boundaries would be inlined + into each other during lowering, making it impossible for the scheduler + to split them into separate kernels or allocate buffers in the right + memory pool. + + None means the default stream, so it is compared like any other value. + """ + node_stream = self._get_node_stream(n) + node_mempool = self._get_node_mempool(n) + for input_node in n.all_input_nodes: + input_stream = self._get_node_stream(input_node) + input_mempool = self._get_node_mempool(input_node) + if input_stream == node_stream and input_mempool == node_mempool: + continue + ir_value = self.env.get(input_node) + if isinstance(ir_value, ir.TensorBox): + ir_value.realize() + + def run_node(self, n: torch.fx.Node) -> object: + """Lower and execute a single FX node into Inductor IR.""" + + def debug(msg: str) -> None: + log.debug("lowering %s %s", LazyString(n.format_node), msg) # type: ignore[arg-type] + + # Use channels-last stride order for certain + # dense 4D intermediates when layout optimization determines a + # downstream consumer (typically conv) prefers channels-last. + def maybe_apply_channels_last_stride_order( + result: ir.IRNode, n: torch.fx.Node + ) -> ir.IRNode: + dense = torch._prims_common.is_non_overlapping_and_dense_or_false( + n.meta["val"] + ) + strides = n.meta["val"].stride() + unbacked_symbols_in_strides = len(free_unbacked_symbols(strides)) > 0 + if ( + not unbacked_symbols_in_strides + and dense + and len(result.get_size()) == 4 + and n in self.nodes_prefer_channels_last + and not is_user_visible + and not is_input_for_as_strided + ): + result = ir.ExternKernel.require_stride_order( + result, + ir.get_stride_order( + make_channels_last_strides_for(n.meta["val"].shape) + ), + ) + return result + + from torch._inductor.compiler_bisector import CompilerBisector + + buffer_watermark = len(self.buffers) + operation_watermark = len(self.operations) + + # origins: OrderedSet[Union[Node, ir.IRNode]] = OrderedSet([n]) + origins: OrderedSet[Any] = OrderedSet([n]) + is_call_function = n.op == "call_function" + if ( + is_call_function + and isinstance(n.target, torch._ops.OpOverload) + and n.target.name() in ("mempool::begin", "mempool::end") + ): + # Drop marker ops; codegen reintroduces use_mem_pool blocks from + # per-node metadata around scheduler nodes that may allocate. + return None + if is_call_function: + args, kwargs = self.fetch_args_kwargs_from_env(n) + origins |= gather_origins(args, kwargs) + self._realize_inputs_at_context_boundaries(n) + node_mempool = self._get_node_mempool(n) + if node_mempool is not None and self.disable_cudagraphs_reason is None: + # User MemPool regions must route allocations to the explicit pool. + # CUDA graphs use a private capture pool, so capture would violate + # that routing and trip cudagraph memory-pool assertions. + self.disable_cudagraphs_reason = ( + "user CUDA MemPool contexts are not compatible with CUDA graphs" + ) + with ( + ir.IRNode.current_origins(origins), + ir.IRNode.current_stream_idx(self._get_node_stream(n)), + ir.IRNode.current_mempool(node_mempool), + self.set_current_node(n), + V.set_current_node(n), + ): + if ( + is_call_function + # this path only for built-in operators + and n.target + and isinstance(n.target, torch._ops.OpOverload) + and torch._library.utils.is_builtin(n.target) + and ( + fallback_node_due_to_unsupported_type(n) + or CompilerBisector.disable_subsystem( + "inductor", "lowerings", lambda: repr(n) + ) + ) + ): + debug("fallback_handler") + result = fallback_handler(n.target, add_to_fallback_set=False)( + *args, # type: ignore[possibly-undefined] + **kwargs, # type: ignore[possibly-undefined] + ) + elif ( + n.op == "call_function" + and isinstance( + n.target, (torch._ops.OpOverload, torch._ops.HigherOrderOperator) + ) + and should_fallback_by_default(n) + ): + # this path supports fallback due to inductor lite mode. It supports + # both OpOverload and HOPs (e.g., triton_kernel_wrapper_functional). + debug("fallback_handler") + result = fallback_handler(n.target, add_to_fallback_set=False)( + *args, # type: ignore[possibly-undefined] + **kwargs, # type: ignore[possibly-undefined] + ) + elif ( + n.op == "call_function" + and n.target is torch.ops.higher_order.triton_kernel_wrapper_mutation + and config.triton_kernel_default_layout_constraint != "flexible_layout" + ): + debug("user_defined_triton_kernel_layout_constraints") + if ( + config.triton_kernel_default_layout_constraint + == "needs_fixed_stride_order" + ): + old_args = args # type: ignore[possibly-undefined] + old_kwargs = kwargs # type: ignore[possibly-undefined] + + if eager_input_vals := n.meta.get("eager_input_vals"): + inp_args = eager_input_vals[0] + inp_kwargs = eager_input_vals[1] + args, kwargs = constrain_to_fake_tensors( + # pyrefly: ignore [unbound-name] + args, + # pyrefly: ignore [unbound-name] + kwargs, + inp_args, + inp_kwargs, + ) + else: + args, kwargs = constrain_to_fx_strides(n, *args, **kwargs) # type: ignore[index] + result = self.call_function(n.target, args, kwargs) # type: ignore[arg-type] + self.propagate_mutation(n, old_args, old_kwargs, args, kwargs) # type: ignore[possibly-undefined] + else: + raise RuntimeError( + f"Unknown triton_kernel_default_layout_constraint: {config.triton_kernel_default_layout_constraint}" + ) + else: + debug("") + result = super().run_node(n) + + # require the same stride order for dense outputs, + # 1. user-land view() will not throw because inductor + # output different strides than eager + # long term the solution is to make view() always succeed + # with infallible strides. + # 2: as_strided ops, we need to make sure its input has same size/stride with + # eager model to align with eager behavior. + as_strided_ops = [ + torch.ops.aten.as_strided.default, + torch.ops.aten.as_strided_.default, + torch.ops.aten.as_strided_scatter.default, + torch.ops.aten.resize.default, + torch.ops.aten.resize_as.default, + ] + is_output = any(user.op == "output" for user in n.users) + is_user_visible = n in self.user_visible_output_strides + is_input_for_as_strided = any( + user.target in as_strided_ops for user in n.users + ) + + if n.meta.get("inductor_realize_to_strides", False) and isinstance( + result, TensorBox + ): + result.realize() + strides = n.meta["val"].stride() + sym_strides = torch._inductor.utils.any_is_symbolic(*strides) + if result.maybe_get_stride() != strides and not sym_strides: + stride_order = ir.get_stride_order(strides) + result = ir.ExternKernel.require_stride_order(result, stride_order) + if ( + is_output + and isinstance(result, TensorBox) + and isinstance(result.data, ir.BaseView) + ): + # Realize so that outputs are correctly aliased + result.realize() + + if (is_output or is_input_for_as_strided) and isinstance( + n.meta.get("val"), torch.Tensor + ): + if is_user_visible: + strides = self.user_visible_output_strides.get(n) + else: + strides = n.meta["val"].stride() + + if strides is not None and len(strides) > 0: + allow_padding = ( + config.pad_outputs or not is_user_visible + ) and not is_input_for_as_strided + dense = torch._prims_common.is_non_overlapping_and_dense_or_false( + n.meta["val"] + ) + unbacked_symbols_in_strides = ( + len(free_unbacked_symbols(strides)) > 0 + ) + if ( + not unbacked_symbols_in_strides + and dense + and len(result.get_size()) == 4 + and n in self.nodes_prefer_channels_last + and not is_user_visible + and not is_input_for_as_strided + ): + strides = ir.FlexibleLayout.stride_ordered_for_memory_format( + result.get_size(), torch.channels_last + ) + if not unbacked_symbols_in_strides and len(strides): + is_view = n.meta["val"]._is_view() or isinstance( + result.data, # type: ignore[missing-attribute] + ir.BaseView, + ) + if is_view and not (is_output and config.strict_output_strides): + result = ir.ExternKernel.require_stride_order( + result, + ir.get_stride_order(strides), + allow_padding=allow_padding, + ) + else: + if len(result.get_size()) == 0 and len(strides) > 0: + strides = [] + result = ir.ExternKernel.require_exact_strides( + result, strides, allow_padding=allow_padding + ) + + # Realize if (1) any user need inputs realized, or (2) there is + # already too many reads and rematerializing can be bad. + num_users = len(OrderedSet(n.users)) + if num_users > 1 and isinstance(result, TensorBox): + for user in n.users: + if user.target in needs_realized_inputs: + result.realize_hint() + # This inclusion is somewhat controversial (from + # discussion between Horace, Natalia, and Elias). + # Currently, it's not very clear why this is helpful. + # The general idea here is that even though a node may + # have FlexibleLayout, we still often *treat* it as if + # it was contiguous. This appears to sometimes result in + # suboptimal behavior. + # + # When we do a better job selecting layout, we should + # revisit this. + need_fixed_layout = [ + torch.ops.aten.convolution_backward.default, + torch.ops.aten.mm.default, + torch.ops.aten._int_mm.default, + ] + need_fixed_channels_last_layout = [] + if not self.layout_opt: + need_fixed_layout.append(torch.ops.aten.convolution.default) + if torch._C._has_mkldnn: + need_fixed_layout += [ + torch.ops.mkldnn._linear_pointwise.default, + torch.ops.mkldnn._linear_pointwise.binary, + torch.ops.aten.mkldnn_rnn_layer.default, + torch.ops.onednn.qlinear_pointwise.default, + torch.ops.onednn.qlinear_pointwise.tensor, + torch.ops.onednn.qlinear_pointwise.binary, + torch.ops.onednn.qlinear_pointwise.binary_tensor, + ] + need_fixed_channels_last_layout += [ + torch.ops.mkldnn._convolution_pointwise.default, + torch.ops.mkldnn._convolution_pointwise.binary, + torch.ops.mkldnn._convolution_pointwise_.binary, + torch.ops.mkldnn._convolution_transpose_pointwise.default, + torch.ops.onednn.qconv_pointwise.default, + torch.ops.onednn.qconv2d_pointwise.binary, + ] + if torch._C.has_mkl: + need_fixed_layout += [torch.ops.mkl._mkl_linear.default] + if user.target in need_fixed_layout: + result = ir.ExternKernel.require_stride_order( + result, + ir.get_stride_order(n.meta["val"].stride()), + allow_padding=True, + ) + if ( + user.target in need_fixed_channels_last_layout + and n is user.args[0] + ): + result = ir.ExternKernel.require_stride_order( + result, + ir.get_stride_order( + make_channels_last_strides_for(n.meta["val"].shape) + ), + ) + if user.op == "output": + # pyrefly: ignore [missing-attribute] + if isinstance(result.data.data, (Pointwise, Reduction)): + # Cheap-to-recompute nodes (0 buffer reads, e.g. + # index arithmetic or constant fills) can be + # deferred to realize_input at output processing. + # This prevents cascade materialization where + # shared constants inflate downstream read counts. + if ( + config.delay_realize_cheap_outputs + # pyrefly: ignore [missing-attribute] + and result.data.num_reads() == 0 + # pyrefly: ignore [missing-attribute] + and not result.data.has_large_inner_fn() + ): + continue + result.realize() + + _data = result.data # type: ignore[attr-defined] + while not isinstance(_data, StorageBox) and isinstance( + _data, (ir.BaseView, ir.MutableBox) + ): + _data = _data.data + + if isinstance(_data, StorageBox) and _data.should_realize_on_reuse( + len(n.users) + ): + result = maybe_apply_channels_last_stride_order(result, n) + + # TODO(jansel): introduce a store vs inline choice + result.mark_reuse(len(n.users)) + + # Realize if the IRNode already has accumulated lots of reads + if isinstance(result, TensorBox) and result.has_exceeded_max_reads(): + # Prevent excessive accumulation in a computed buffer, when + # there are multiple branches each with small number of memory + # reads, but they converge to a user. + result = maybe_apply_channels_last_stride_order(result, n) + result.realize_hint() + + # Realize if a Pointwise has too much stuff to be inlined. + # As this may cause RecursionError during Inductor's evaluation. + if isinstance(result, TensorBox) and isinstance(result.data, StorageBox): + curr = result.data.data + if isinstance(curr, Pointwise): + # Use inner fn as a rough proxy. Good enough. + if curr.has_large_inner_fn(threshold=100): + result.realize() + + assign_origin_node(result, n) + self.register_users_of(result) + + new_unbacked_defs = OrderedSet[sympy.Symbol]() + for buf in self.buffers[buffer_watermark:]: + new_unbacked_defs |= buf.get_unbacked_symbol_defs() + for op in self.operations[operation_watermark:]: + new_unbacked_defs |= op.get_unbacked_symbol_defs() + + shape_env = V.graph.sizevars.shape_env + + # An input can be unbacked symint i.e.: when mark_unbacked is used. + # in that case add it to new_unbacked_defs. + if ( + n.op == "placeholder" + and isinstance(result, sympy.Symbol) + and shape_env.is_unbacked_symint(result) + ): + new_unbacked_defs.add(result) + + def format_new_defs() -> str: + r = [ + f"unbacked_symbol_defs={buf.get_unbacked_symbol_defs()} in:\n{buf}\n" + for buf in self.buffers[buffer_watermark:] + ] + r.extend( + f"unbacked_symbol_defs={op.get_unbacked_symbol_defs()} in:\n{op}\n" + for op in self.operations[operation_watermark:] + ) + return "***\n".join(r) + + # We do not skip unbacked symints that are input for backward see the note below. + if V.graph.is_backward and n.op == "placeholder": + return result + + # Note [Backwards runtime asserts] + # Backwards poses an interesting problem for deferred runtime + # asserts. In the easy case, we may solely close over data + # dependent sized tensors, and there are no binding sites for + # unbacked SymInts. In this case, we can just drop all the + # runtime asserts on the floor: no non-placeholder bindings, no + # problem. + # + # However, it is *possible* for a fresh runtime assert to show up + # between forwards and backwards. Right now, the freezing process + # that happens when we lower forwards means that we will freeze + # runtime asserts, and then the moment the backwards lowering + # process attempts to add a new deferred runtime assert, we will + # fail. Let's say you remove that assert. Now when we get here, + # we need to make sure we actually emit these asserts (because we + # can't emit them in forwards, we already compiled it). So we + # have to do something here. But we don't want to reemit ALL + # deferred runtime asserts, we only want to emit the NEW ones. + # Therefore needing some sort of stratification in the ShapeEnv. + # This is all doable, it just hasn't been done yet. + + unbacked_bindings = resolve_unbacked_bindings( + V.graph.sizevars.shape_env, n.meta.get("unbacked_bindings", {}) + ) + if unbacked_bindings is None: + raise AssertionError("resolve_unbacked_bindings returned None") + # When we do lowering, it is possible we reallocate unbacked SymInts. + # So we need to line up the unbacked SymInts when performing the test + # here + # + # In principle, we could permit lowering to introduce MORE unbacked + # SymInts: as long as all the old unbacked ones are accounted for, + # it's fine for inductor to introduce extra calls to item()/unbacked() + # whatever. This actually happens in practice when an unbacked SymInt + # gets memoized away; naively, when Inductor reprocesses a kernel, it + # doesn't know that the memo still applies, and ends up allocating a + # new symbol. However, this is generally a bad thing: we may still + # end up needing to test equalities on the symbols, and a fresh + # symbol is likely to hit lots of GuardOnDataDependent errors that + # we already know facts for. + renamed_unbacked_bindings = OrderedSet( + # unbacked_renamings is not declared on every ShapeEnv path + # pyrefly: ignore[missing-attribute] + V.fake_mode.shape_env.unbacked_renamings.get(s, s) + for s in unbacked_bindings + ) + + if not (new_unbacked_defs >= renamed_unbacked_bindings): + raise AssertionError( + f"failed {new_unbacked_defs} >= {renamed_unbacked_bindings} (inductor >= fx)\n" + f"fx node is: {n.format_node()}\n" + f"new operations are:\n\n{format_new_defs()}" + ) + self.create_deferred_runtime_asserts(n, new_unbacked_defs) + return result + + def create_deferred_runtime_asserts( + self, n: torch.fx.Node, new_unbacked_defs: OrderedSet[sympy.Symbol] + ) -> None: + if config.do_not_emit_runtime_assertions: + return + # [NOTE] Codegen runtime asserts in Inductor + # + # We need to generate runtime asserts directly in Inductor instead + # of just reusing the asserts from input graphs because we reuse the + # same ShapeEnv as before. In particular, on subsequent graph passes, + # we would immediately turn all of these assertions into noops, + # because when we evaluated their expressions, we would see that + # because we had a deferred runtime assert in the ShapeEnv, we + # know "oh, of course this expression is True" already. + # One example is below: + # + # class Model(torch.nn.Module): + # def forward(self, a, b, c): + # nz = torch.nonzero(a) + # ones = a.new_ones([nz.size(0), b.size(0)]) + # torch._check(ones.size(0) >= 1) + # equals = torch.add(ones, c) + # return equals + # torch._dynamo.mark_dynamic(c, 0) + # When we reuse the ShapeEnv in Inductor lowering, the check that checks + # a and nonzero have the same shape would be evaluated to True after we resolve + # unbacked bindings using the ShapeEnv. + # See test_unbacked_equals_input_size_runtime_assertion in test_aot_inductor. + # + # + # In addition to the Inductor generated runtime asserts, we also + # need the runtime asserts from the input graph, because some derived + # runtime asserts on backed symints are not generated in Inductor. One example is + # this: `y = x.reshape(100, -1).clone()`. x.shape[0] needs to be a multiple of 100. + # See test_aoti_runtime_asserts_backed_symint in test_aot_inductor. + + def make_assert(expr: SympyBoolean, msg: str) -> None: + assert_op = ir.AssertScalar(expr, msg) + self.register_buffer(assert_op, set_name=True) + self.register_operation(assert_op) + + if ( + full_aoti_runtime_assert() + and n.target is torch.ops.aten._assert_scalar.default + and self.aot_mode + ): + node_args, _ = self.fetch_args_kwargs_from_env(n) + if node_args[0] != True: # noqa: E712 + make_assert(node_args[0], f"{node_args[0]} to be True") + else: + # bound_unbacked_symbols tracks the symbols that are created so far, + # we use it to make sure that runtime assertions are added after all + # symbols used in them are defined. + self.bound_unbacked_symbols |= new_unbacked_defs + + shape_env = V.graph.sizevars.shape_env + + # Emit code for runtime asserts that can be inserted at this point. + for i0 in new_unbacked_defs: + ras = self.ras_by_symbol.pop(i0, []) + # NB: size-like not needed, we won't retrace + vr = shape_env.var_to_range[i0] + if not shape_env._default_unspecified_value_range().issubset(vr): + + def is_convertible(s: Expr) -> bool: + if s in (int_oo, -int_oo): + return False + try: + int(s) + return True + except TypeError: + return False + + if is_convertible(vr.lower): + make_assert(i0 >= vr.lower, f"{i0} >= {vr.lower}") + if is_convertible(vr.upper): + make_assert(i0 <= vr.upper, f"{i0} <= {vr.upper}") + + for ra in ras: + fvs = free_unbacked_symbols(ra.expr) + missing = fvs - self.bound_unbacked_symbols + if missing: + i1 = min(missing, key=str) + self.ras_by_symbol.setdefault(i1, []).append(ra) + else: + make_assert(ra.expr, f"{ra.expr}") + + def validate_can_generate_cpp_wrapper(self) -> None: + if config.disable_cpp_codegen: + raise CppWrapperCodegenError("C++ codegen is disabled") + + if sys.platform not in ("linux", "darwin", "win32"): + raise CppWrapperCodegenError(f"Unsupported platform {sys.platform}") + + graph_module = cast(torch.fx.GraphModule, self.module) + if any( + "mempool" in node.meta.get("custom", {}) + for node in graph_module.graph.nodes + ): + raise CppWrapperCodegenError( + "torch.cuda.use_mem_pool is not supported with C++ wrapper codegen" + ) + + def init_wrapper_code( + self, + is_subgraph: bool = False, + subgraph_name: str | None = None, + parent_wrapper_code: PythonWrapperCodegen | None = None, + partition_signatures: GraphPartitionSignature | None = None, + ) -> None: + device_types = self.device_types.copy() + device_types.discard("cpu") + device_types.discard("meta") + # TODO(Eikan): Only support mixing cpu and other device now. + if len(device_types) > 1: + raise AssertionError( + "Does not support mixing {}".format("+".join(device_types)) + ) + only_cpu = len(device_types) == 0 + self.device_type = "cpu" if only_cpu else device_types.pop() + + if self.cpp_wrapper: + self.validate_can_generate_cpp_wrapper() + + self.device_ops = get_device_op_overrides(self.device_type) + wrapper_code_gen_cls = get_wrapper_codegen_for_device( + self.device_type, self.cpp_wrapper, self.fx_wrapper + ) + if wrapper_code_gen_cls is None: + raise AssertionError(f"Device {self.device_type} not supported") + self.wrapper_code = wrapper_code_gen_cls.create( + is_subgraph, + subgraph_name, + parent_wrapper_code, + partition_signatures, + ) + + if self.const_module: + self.wrapper_code._names_iter = self.const_module.wrapper_code._names_iter + + def extract_autotune_inputs( + self, example_inputs: list[int | float | torch.Tensor] + ) -> None: + import copy + + cloned_gm = copy.deepcopy(self.orig_gm) + example_inputs = copy.deepcopy(example_inputs) + triton_nodes = [] + for node in cloned_gm.graph.nodes: + if ( + node.op == "call_function" + and node.target is torch.ops.higher_order.triton_kernel_wrapper_mutation + ): + triton_nodes.append(node) + + # Store grid related nodes + grid_inputs: list[torch.fx.Node] = [] + visited_grids: dict[torch.fx.Node, int] = {} + # Store kwargs related nodes + triton_inputs: dict[str, Any] = {} + kwargs_inputs: list[torch.fx.Node] = [] + visited_kwargs: dict[Any, int] = {} + for node in triton_nodes: + # first check whether we have fx node in grid settings. + for grid in node.kwargs["grid"]: + for val in grid: + if val in visited_grids: + continue + + if isinstance(val, torch.fx.Node): + visited_grids[val] = len(grid_inputs) + grid_inputs.append(val) + + kwargs = node.kwargs["kwargs"] + # identify which args might be mutated, those should be cloned. + mutated = torch._higher_order_ops.triton_kernel_wrap.get_mutated_tensors( + node.kwargs["kernel_idx"], + node.kwargs["constant_args_idx"], + { + k: v.meta["val"] if isinstance(v, torch.fx.Node) else v + for k, v in kwargs.items() + }, + node.kwargs["tma_descriptor_metadata"], + ) + + new_kwargs: dict[str, int] = {} + with cloned_gm.graph.inserting_before(node): + for k, v in kwargs.items(): + if k in mutated: + new_node = cloned_gm.graph.call_function(torch.clone, args=(v,)) + new_kwargs[k] = len(kwargs_inputs) + kwargs_inputs.append(new_node) + continue + + if v in visited_kwargs: + new_kwargs[k] = visited_kwargs[v] + continue + visited_kwargs[v] = len(kwargs_inputs) + kwargs_inputs.append(v) + new_kwargs[k] = visited_kwargs[v] + triton_inputs[node.name] = new_kwargs + + new_outputs = kwargs_inputs + grid_inputs + for node in cloned_gm.graph.nodes: + if node.op == "output": + node.args = (tuple(new_outputs),) + break + + cloned_gm.recompile() + runner = torch.fx.Interpreter(cloned_gm) + returned_outputs = runner.run(example_inputs) + # Extract and store the grid for autotuning + if len(grid_inputs) > 0: + grid_outputs = returned_outputs[len(kwargs_inputs) :] + self.autotuning_grids = {} + for node in triton_nodes: + dynamic_grid = False + new_grids: list[tuple[Any]] = [] + for grid in node.kwargs["grid"]: + new_grid = [] + for val in grid: + if not isinstance(val, torch.fx.Node): + new_grid.append(val) + continue + dynamic_grid = True + new_grid.append(grid_outputs[visited_grids[val]]) + # pyrefly: ignore [bad-argument-type] + new_grids.append(tuple(new_grid)) + + if dynamic_grid: + self.autotuning_grids[node.name] = new_grids + # Store the kwargs input for autotuning + self.autotuning_inputs = returned_outputs[: len(kwargs_inputs)] + self.autotuning_mapping = triton_inputs + + def codegen_with_cpp_wrapper( + self, + ) -> tuple[ValueWithLineMap, ValueWithLineMap]: + """ + For GPU, Triton kernels are autotuned and stored as cubin files. + + For CPU with user-defined Triton kernels, AOTI also needs the + same two-pass compile when `autotune_at_compile_time` is off, + since `CpuTritonKernelCache` is otherwise only populated by the + autotune block (see `DeferredCpuTritonCallWrapper` in + `cpp_wrapper_cpu.py`). + """ + self.validate_can_generate_cpp_wrapper() + has_gpu = any(device in self.device_types for device in ["cuda", "xpu"]) + # CPU + user-defined Triton + AOTI + autotune block disabled is the + # only CPU configuration that needs the two-pass dance: the autotune + # block normally populates CpuTritonKernelCache, but here it doesn't run. + needs_cpu_triton_two_pass = ( + "cpu" in self.device_types + and self.aot_mode + and not config.triton.autotune_at_compile_time + and any( + isinstance(op, ir.UserDefinedTritonKernel) for op in self.operations + ) + ) + if has_gpu or needs_cpu_triton_two_pass: + + def extract_real_inputs() -> list[int | float | torch.Tensor]: + def materialize( + x: torch.SymInt | torch.SymFloat | torch.Tensor, + ) -> int | float | torch.Tensor: + if x is None: + # pyrefly: ignore [bad-return] + return None + elif isinstance(x, (torch.SymInt, torch.SymFloat)): + # Need concrete value to run dynamic shapes and tune the result + return not_none(x.hint) + elif is_fake_tensor(x): + return defake(x) + else: + if not isinstance(x, torch.Tensor): + raise AssertionError( + "Unknown type when creating real inputs" + str(type(x)) + ) + return x + + tracing_context = torch._guards.TracingContext.try_get() + if tracing_context is not None and not isinstance( + V.real_inputs, NullHandler + ): + if tracing_context.output_strides: + tracing_context.output_strides.clear() + + params_flat = [ + param + for param in tracing_context.params_flat # type: ignore[union-attr] + if param is not None + ] + real_inputs = [ + # pyrefly: ignore[bad-argument-type] + materialize(x) + for x in itertools.chain(params_flat, V.real_inputs) + ] + else: + # In the backward pass, V.real_inputs is not OrderedSet. + # Generating random inputs based on self.example_inputs sometimes can be problematic, + # e.g. illegal memory access. A comprehensive fix is to autotune in a separate process. + real_inputs = [ + materialize(x) # type:ignore[arg-type] + for x in ( + self.example_inputs # type:ignore[union-attr] + if isinstance(V.real_inputs, NullHandler) + else V.real_inputs + ) + ] + + if self.mutated_inputs: + from .compile_fx import clone_preserve_strides + + mutated_input_idxs = [ + idx + for idx, name in enumerate(self.graph_inputs) + if name in self.mutated_inputs + and isinstance(real_inputs[idx], torch.Tensor) + ] + for idx in mutated_input_idxs: + # clone mutated Tensor inputs to avoid mutating them in + # the first pass of the CPP wrapper-based compilation, as + # this will lead to a side effect on the example inputs: + # e.g. if torch.compile(f)(x) if called on input-mutating + # f, the inputs x will be mutated twice in the process: + # once here, and again when running the compiled model; + # this will also lead to a numerically incorrect output + mutated_inp = real_inputs[idx] + if not isinstance(mutated_inp, torch.Tensor): + raise AssertionError( + f"Expected torch.Tensor for mutated input, got {type(mutated_inp)}" + ) + real_inputs[idx] = clone_preserve_strides(mutated_inp) + del mutated_inp + return real_inputs + + if config.triton.autotune_at_compile_time: + # If autotune_at_compile_time is True, we can do the codegen in one-pass + # We will construct the autotuning values if user defined kernel exists. + if config.triton.autotune_with_sample_inputs: + user_defined_kernels = False + for op in self.operations: + if isinstance(op, ir.UserDefinedTritonKernel): + user_defined_kernels = True + break + if user_defined_kernels: + real_inputs = extract_real_inputs() + self.extract_autotune_inputs(real_inputs) + save_triton_kernel_perf_artifact(self) + return self.codegen() + else: + if not self.aot_mode: + # cpp_wrapper JIT does not require two passes + return self.codegen() + + # AOTI with lazy compile: single codegen pass producing + # two separate C++ files — JIT (for autotuning) and AOTI + # (for packaging) — via DualIndentedBuffer. + # wrapper_code is the JIT variant; the AOTI variant is + # populated into wrapper_codegen._aot_output. + from .codegen.cpp_wrapper_gpu import ( + CppWrapperGpu, + generate_aoti_kernel_config_header, + ) + + wrapper_code, kernel_code = self.codegen() + if not isinstance(self.wrapper_code, CppWrapperGpu): + raise AssertionError( + f"expected CppWrapperGpu, got {type(self.wrapper_code)}" + ) + lazy_kernel_names = list(self.wrapper_code._lazy_kernel_names) + if lazy_kernel_names: + try: + self._run_jit_variant_for_autotune( + wrapper_code, + kernel_code, + extract_real_inputs, + lazy_kernel_names, + ) + except Exception as exc: + raise RuntimeError( + "When autotune_at_compile_time is False, AOTInductor generates " + "both JIT code and AOT code. The JIT code failed to run." + ) from exc + + # Prepend config header with kernel compile results + # to the AOTI source for packaging. + config_header = generate_aoti_kernel_config_header(lazy_kernel_names) + aot_output: str | None = self.wrapper_code._aot_output + if aot_output is None: + raise RuntimeError( + "When autotune_at_compile_time is False, AOTInductor generates " + "both JIT code and AOT code. The AOT code should not be None." + ) + aoti_wrapper = ValueWithLineMap( + config_header + "\n" + aot_output, + wrapper_code.line_map, + ) + + return aoti_wrapper, kernel_code + else: + # cpu + return self.codegen() + + @staticmethod + def _python_source_literal(name: str, source: str | None) -> str: + if source is None: + return f"{name} = None\n" + if source == "": + return f"{name} = ''\n" + if '"""' in source: + return f"{name} = {source!r}\n" + return f'{name} = (\nr"""\n{source}"""\n)\n' + + @staticmethod + def _tensor_repro_expr(tensor: torch.Tensor) -> str: + return ( + f"_make_strided_tensor({tuple(tensor.size())!r}, " + f"{tuple(tensor.stride())!r}, {tensor.storage_offset()!r}, " + f"{tensor.dtype}, {str(tensor.device)!r})" + ) + + @classmethod + def _log_jit_variant_for_autotune_repro( + cls, + *, + cpp_source: str, + kernel_source: str | None, + device_type: str, + num_outputs: int, + kernel_names: list[str], + input_exprs: list[str], + ) -> None: + from .codecache import output_code_log, PyCodeCache + + if not ( + output_code_log.isEnabledFor(logging.DEBUG) + or output_code_log.isEnabledFor(logging.INFO) + ): + return + + input_lines = "".join(f" {expr},\n" for expr in input_exprs) + log_name = "JIT wrapper code for AOT lazy autotuning" + source = ( + textwrap.dedent( + """ + import torch + from torch._inductor import config + from torch._inductor.codecache import ( + CppWrapperCodeCache, + CudaKernelParamCache, + get_cpp_wrapper_cubin_path_name, + ) + + {cpp_wrapper_src} + {kernel_src} + kernel_names = {kernel_names!r} + + + def _make_strided_tensor(size, stride, storage_offset, dtype, device): + if 0 in size: + storage_size = storage_offset + 1 + else: + storage_size = storage_offset + 1 + sum( + (dim - 1) * stride_dim + for dim, stride_dim in zip(size, stride) + ) + base = torch.zeros((storage_size,), dtype=dtype, device=device) + return torch.as_strided(base, size, stride, storage_offset) + + + def make_inputs(): + return [ + {input_lines} ] + + + def main(): + for name in kernel_names: + CudaKernelParamCache.cache.pop(name, None) + with config.patch('aot_inductor.link_libtorch', True): + compiled_fn = CppWrapperCodeCache.load_pybinding( + argtypes=['std::vector'], + main_code=cpp_wrapper_src, + device_type={device_type!r}, + num_outputs={num_outputs!r}, + kernel_code=kernel_src, + ) + input_tensors = make_inputs() + input_handles = torch._C._aoti.unsafe_alloc_void_ptrs_from_tensors( + input_tensors + ) + output_handles = compiled_fn(input_handles) + output_tensors = torch._C._aoti.alloc_tensors_by_stealing_from_void_ptrs( + output_handles + ) + print(f'Produced {{len(output_tensors)}} outputs') + cubin_path_name = get_cpp_wrapper_cubin_path_name() + for name in kernel_names: + params = CudaKernelParamCache.get(name) + if params and cubin_path_name in params: + print(f'{{name}}: {{params[cubin_path_name]}}') + + + if __name__ == '__main__': + main() + """ + ) + .lstrip() + .format( + cpp_wrapper_src=cls._python_source_literal( + "cpp_wrapper_src", cpp_source + ), + kernel_src=cls._python_source_literal("kernel_src", kernel_source), + kernel_names=kernel_names, + input_lines=input_lines, + device_type=device_type, + num_outputs=num_outputs, + ) + ) + output_code_log.debug("%s: \n%s", log_name, source) + _, path = PyCodeCache.write(source) + output_code_log.info("%s written to: %s", log_name, path) + + def _run_jit_variant_for_autotune( + self, + wrapper_code, + kernel_code, + extract_real_inputs, + kernel_names: list[str], + ) -> None: + """Compile dual-wrapper-mode C++ as JIT variant and run to autotune kernels. + + Compiles the dual-wrapper-mode C++ source without -DAOT_INDUCTOR, which + activates the JIT path (inductor_entry_impl). Running this with + real inputs triggers lazy Triton compilation and autotuning, + populating CudaKernelParamCache for the AOTI packaging step. + """ + from .codecache import ( + CppWrapperCodeCache, + CudaKernelParamCache, + get_cpp_wrapper_cubin_path_name, + ) + + cpp_source = wrapper_code.value + kernel_source = kernel_code.value if kernel_code else None + + # The JIT wrapper keeps lazy kernel state in function-local statics. + # Compile a fresh wrapper for each first pass so autotuning always reruns. + cpp_source += f"\n// AOTI lazy autotune first pass: {id(self)}\n" + for name in kernel_names: + CudaKernelParamCache.cache.pop(name, None) + + # Prefer the GPU device for the JIT compile: the wrapper includes + # cpp_wrapper/.h which transitively pulls in cuda_runtime.h. + # A "cpu" device would precompile cpp_wrapper/cpu.h, which does not + # include the CUDA headers needed to compile the kernel call sites. + device_type = next( + (d for d in self.device_types if d in ("cuda", "xpu")), + next((d for d in self.device_types if d != "meta"), "cpu"), + ) + + # A const graph has no runtime graph inputs (its weights are read as + # constants, not placeholders), so its JIT entry point expects only the + # appended constant handles. extract_real_inputs() would return the main + # model's params/inputs, producing a handle-count/type mismatch, so pass + # an empty input list here and rely solely on the constants below. + real_inputs = [] if self.is_const_graph else extract_real_inputs() + + def materialize_constant(name: str) -> torch.Tensor: + constant = self.constants[name] + if is_fake_tensor(constant): + constant = defake(constant) + if not isinstance(constant, torch.Tensor): + raise AssertionError(f"Expected tensor constant for {name}") + return constant + + # Non-tensor scalars become 0-d CPU tensors; None and ints/floats + # that the graph specialized away aren't part of the C++ wrapper + # signature and must be skipped. + input_tensors: list[torch.Tensor] = [] + input_exprs: list[str] = [] + for arg in real_inputs: + if arg is None: + continue + if isinstance(arg, torch.Tensor): + input_tensors.append(arg) + input_exprs.append(self._tensor_repro_expr(arg)) + else: + input_tensors.append(torch.tensor(arg, device="cpu")) + input_exprs.append(f"torch.tensor({arg!r}, device='cpu')") + for name in self.constants: + constant = materialize_constant(name) + input_tensors.append(constant) + input_exprs.append(self._tensor_repro_expr(constant)) + + self._log_jit_variant_for_autotune_repro( + cpp_source=cpp_source, + kernel_source=kernel_source, + device_type=device_type, + num_outputs=len(self.graph_outputs), + kernel_names=kernel_names, + input_exprs=input_exprs, + ) + + # This temporary Python-loaded wrapper can depend on libtorch even when + # the final packaged AOTI artifact is built with link_libtorch=False. + with config.patch("aot_inductor.link_libtorch", True): + compiled_fn = CppWrapperCodeCache.load_pybinding( + argtypes=["std::vector"], + main_code=cpp_source, + device_type=device_type, + num_outputs=len(self.graph_outputs), + kernel_code=kernel_source, + ) + + input_handles = torch._C._aoti.unsafe_alloc_void_ptrs_from_tensors( + input_tensors + ) + del real_inputs, input_tensors, input_exprs + + output_handles = compiled_fn(input_handles) + output_tensors = torch._C._aoti.alloc_tensors_by_stealing_from_void_ptrs( + output_handles + ) + del output_tensors + + # Collect cubin files produced by lazy compilation for AOTI packaging + cubin_path_name = get_cpp_wrapper_cubin_path_name() + for name in kernel_names: + params = CudaKernelParamCache.get(name) + if params and cubin_path_name in params: + self.wrapper_code.additional_files.append(params[cubin_path_name]) + + def _update_scheduler(self) -> None: + """ + (Re)initializes the scheduler member. When initializing the scheduler, no CUBIN + files should be generated (to avoid biasing any benchmarks and pessimizing + fusion decisions). + """ + from .scheduler import Scheduler + + with config.patch("triton.store_cubin", False): + self.scheduler = Scheduler(self.operations) + + def codegen(self) -> tuple[ValueWithLineMap, ValueWithLineMap]: + with dynamo_timed("GraphLowering.codegen", log_pt2_compile_event=True): + self.init_wrapper_code() + + self._update_scheduler() + V.debug.draw_orig_fx_graph(self.orig_gm, self.scheduler.nodes) + + self.wrapper_code.push_codegened_graph(self) + self.scheduler.codegen() + + log.debug( + "Finished codegen for all nodes. The list of kernel names available: %s", + V.graph.all_codegen_kernel_names, + ) + + result = self.wrapper_code.generate(self.is_inference) + self.wrapper_code.pop_codegened_graph() + return result + + def codegen_subgraph(self, parent_graph: GraphLowering) -> None: + """ + This is a more compact version of the `codegen()` above + where we codegen this graph as a subgraph of some parent + graph. The parent graph is passed as an argument: the + intention is to inline codegening of the subgraph in + the parent graph's wrapper code (including the generated + kernels). The wrapper code is not finalized (via `.generate()` + call), as this will be done in the parent graph's `codegen()`. + """ + with dynamo_timed("GraphLowering.codegen_subgraph", log_pt2_compile_event=True): + self.wrapper_code = parent_graph.wrapper_code + self.device_ops = parent_graph.device_ops + self.cpp_wrapper = parent_graph.cpp_wrapper + self.device_types = parent_graph.device_types + self.device_idxs = parent_graph.device_idxs + self.device_type = parent_graph.device_type + + self._update_scheduler() + self.scheduler.codegen() + + def count_bytes( + self, + ) -> tuple[ + int, list[tuple[BaseSchedulerNode, int]], list[tuple[BaseSchedulerNode, float]] + ]: + total_bytes = 0 + node_counts = [] + node_runtimes = [] + for node in self.scheduler.nodes: + num_bytes = node.get_read_write_buffers_sizes() + total_bytes += num_bytes + node_counts.append((node, num_bytes // 4)) + node_runtimes.append((node, node.get_estimated_runtime())) + + return total_bytes, node_counts, node_runtimes + + # No-op to be patched for unit tests + save_output_code: Callable[[str], None] | None = None + + def compile_to_module(self) -> CompiledModule: + with dynamo_timed( + "GraphLowering.compile_to_module", + phase_name="code_gen", + log_pt2_compile_event=True, + dynamo_compile_column_us="inductor_code_gen_cumulative_compile_time_us", + ): + return self._compile_to_module() + + def _compile_to_module(self) -> CompiledModule: + # If we're here, we don't have to worry about the kernel code, which is only + # returned separately in AOTInductor mode. + wrapper_code, _ = ( + self.codegen_with_cpp_wrapper() if self.cpp_wrapper else self.codegen() + ) + + if isinstance(wrapper_code, ValueWithLineMap): + mod = self._compile_to_module_lines(wrapper_code) + elif isinstance(wrapper_code, FileBackedGraphModule): + mod = wrapper_code + else: + raise NotImplementedError( + f"Unrecognized wrapper code type: {type(wrapper_code)}" + ) + + # Logged twice as per https://github.com/pytorch/pytorch/pull/99038#discussion_r1167826029 + # TODO. Revisit this once the logging API is more mature + if mod.__file__ is None: + raise AssertionError("mod.__file__ is None") + + log_module_code(mod.__file__) + log.debug("Output code written to: %s", mod.__file__) + output_code_log.info("Output code written to: %s", mod.__file__) + if config.benchmark_kernel: + print(f"Compiled module path: {mod.__file__}", file=sys.stderr) + if isinstance(wrapper_code, FileBackedGraphModule): + V.debug.output_code(mod.__file__) + V.debug.copy(os.path.splitext(mod.__file__)[0] + ".debug") + + return mod + + def _compile_to_module_lines( + self, wrapper_code: ValueWithLineMap + ) -> CompiledModule: + from .codecache import PyCodeCache + + if config.triton.autotune_at_compile_time: + # sanitize docstrings in kernel defs (#155006) + kernel_autotune_defs = self.wrapper_code.kernel_autotune_defs.getvalue() + kernel_autotune_defs = kernel_autotune_defs.replace('"""', '\\"\\"\\"') + + tuning_code = ( + 'r"""\n' + + "Compile-time auto-tuning block: \n" + + kernel_autotune_defs + + self.wrapper_code.kernel_autotune_calls.getvalue() + + '"""\n' + ) + wrapper_code.value = tuning_code + wrapper_code.value + if GraphLowering.save_output_code is not None: + GraphLowering.save_output_code(wrapper_code.value) + output_code_log.debug("Output code: \n%s", wrapper_code.value) + + inductor_meta = autotune_cache.inductor_meta_from_config() + AutotuneCacheBundler.begin_compile(inductor_meta, code=wrapper_code.value) + + try: + linemap = [ + (line_no, node.stack_trace) # type: ignore[attr-defined] + for line_no, node in wrapper_code.line_map + ] + key, path = PyCodeCache.write(wrapper_code.value) + output_code_log.debug("Output code written to: %s", path) + + V.debug.output_code(path) + V.debug.copy(os.path.splitext(path)[0] + ".debug") + except Exception: + trace_structured( + "inductor_output_code", + # Just omit the filename, I still want the code though! + payload_fn=lambda: wrapper_code.value, + ) + raise + else: + trace_structured( + "inductor_output_code", + lambda: { + "filename": path, + "file_path": os.path.abspath(path), + }, + payload_fn=lambda: wrapper_code.value, + ) + with dynamo_timed("PyCodeCache.load_by_key_path", log_pt2_compile_event=True): + mod = PyCodeCache.load_by_key_path( + key, + path, + linemap=linemap, # type: ignore[arg-type] + attrs={ + **self.constants, + **self.torchbind_constants, + **self.opaque_value_type_classes, + }, + ) + self.cache_key = key + self.cache_path = path + self.cache_linemap = linemap # type: ignore[assignment] + + if config.benchmark_harness and config.profile_bandwidth_output: + # run the inputs code gen to get the bandwidth info + args = mod.get_args() + mod.benchmark_compiled_module(args, times=1, repeat=1) + + return mod + + def _get_output_names(self, graph_outputs: list[ir.IRNode]) -> list[str]: + names = [] + shape_counter = itertools.count(0) + none_counter = itertools.count(0) + for node in graph_outputs: + if isinstance(node, ir.NoneAsConstantBuffer): + names.append(f"{self.name}_none{next(none_counter)}") + elif isinstance(node, ir.ShapeAsConstantBuffer): + names.append(f"{self.name}_shape{next(shape_counter)}") + else: + names.append(node.get_name()) + return names + + def get_output_names(self) -> list[str]: + return self._get_output_names(self.graph_outputs) + + def is_unspec_arg(self, name: str) -> bool: + # dynamo wraps unspec variable as 0d CPU tensor, + # need to convert to scalar during codegen (triton only) + return ( + name in self.graph_inputs + and self.graph_inputs[name].get_numel() == 1 + and len(self.graph_inputs[name].get_size()) == 0 + and get_device_type(self.graph_inputs[name]) == "cpu" + ) or name in self.zero_dim_cpu_tensor_list + + +class SubgraphLowering(GraphLowering): + """ + Mostly a helper class for the subgraph lowering. The main goal is to call + init_wrapper_code with the subgraph related arguments. + """ + + def __init__(self, parent: GraphLowering, *args: Any, **kwargs: Any) -> None: + self.parent = parent + super().__init__(*args, **kwargs) + + def allocate_non_dup_const_name(self, name: str | None, data: Tensor) -> str: + name = super().allocate_non_dup_const_name(name, data) + # The generated subgraph wrapper shares the parent's module, but tensor + # constants are attached to the module from the root graph's constants + # dict at load time. Propagate the value up so it is not left as None. + root = self.parent + while isinstance(root, SubgraphLowering): + root = root.parent + root.constants[name] = data + return name + + def init_wrapper_code( + self, + is_subgraph: bool = False, + subgraph_name: str | None = None, + parent_wrapper_code: PythonWrapperCodegen | None = None, + partition_signatures: GraphPartitionSignature | None = None, + ) -> None: + super().init_wrapper_code( + is_subgraph=True, + subgraph_name=self.name, + parent_wrapper_code=self.parent.wrapper_code, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ceaf347c8d5e1c60fede7c8bead6abe4c97b40d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/__init__.py @@ -0,0 +1,11 @@ +""" +Unified device-scoped heuristic module for PyTorch Inductor. + +This module provides a single entry point for all device-specific heuristic +dispatch, covering both: + +- template: pre-written template kernels (mm, conv, flex_attention...) + used at compile time. +- triton_codegen: inductor-generated triton kernels (pointwise, reduction...) + used at runtime. +""" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d24c1cdc13d1d056daad078f9652fe5e59d4bb5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/__pycache__/registry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..227fadce22371ab53b11571625dd151df2ac2521 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/__pycache__/registry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/registry.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..97d54f705b739fc62332096964fc70f9f953dbbe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/registry.py @@ -0,0 +1,270 @@ +""" +Heuristic registry system for PyTorch Inductor. + +Provides centralized registration for both: +- Template heuristics (compile-time, keyed by template_name/device_type/op_name) +- Codegen heuristics (runtime, keyed by name/device_type) + +Both share one underlying registry dict and cascading fallback lookup. +""" + +from __future__ import annotations + +import contextlib +import logging +from typing import Any, TYPE_CHECKING + + +if TYPE_CHECKING: + from collections.abc import Iterator + + from .template.base import TemplateConfigHeuristics + + +_HEURISTIC_REGISTRY: dict[tuple[str | None, ...], Any] = {} +# Alias so tests can snapshot/restore the shared registry via the old name. +# This intentionally covers both template and codegen entries. +_TEMPLATE_HEURISTIC_REGISTRY = _HEURISTIC_REGISTRY +_HEURISTIC_CACHE: dict[tuple[str | None, ...], Any] = {} + +log = logging.getLogger(__name__) + + +# ----------------------------------------------------------------- +# Shared internals +# ----------------------------------------------------------------- + + +def _register( + key: tuple[str | None, ...], + target: Any, +) -> None: + _HEURISTIC_REGISTRY[key] = target + + +def _lookup(name: str, device_type: str, op_name: str | None) -> Any | None: + """Cascading fallback lookup: (name, device, op) -> (name, None, op) -> (name, device, None) -> (name, None, None).""" + keys = [ + (name, device_type, op_name), + (name, None, op_name), + (name, device_type, None), + (name, None, None), + ] + for key in keys: + if key in _HEURISTIC_REGISTRY: + return _HEURISTIC_REGISTRY[key] + return None + + +# ----------------------------------------------------------------- +# Template heuristic API +# ----------------------------------------------------------------- + + +def register_template_heuristic( + template_name: str, + device_type: str | None, + register: bool = True, + op_name: str | None = None, +) -> Any: + """ + Decorator to register template heuristic classes. + + Args: + template_name: Name of the template (e.g., "mm", "bmm", "scaled_mm") + device_type: Device type ("cuda", "cpu", "xpu"). + None means applicable to all device types. + register: Whether to register this heuristic. + op_name: Operator name for per-op specialization. + + Example: + @register_template_heuristic("mm", "cuda", register=torch.version.hip is None) + class CUDAMMTemplateConfigHeuristic(CUDAConfigHeuristic): + pass + """ + + def decorator( + cls: type[TemplateConfigHeuristics], + ) -> type[TemplateConfigHeuristics]: + if register: + key: tuple[str | None, ...] = (template_name, device_type, op_name) + _register(key, cls) + log.info( + "Registered template heuristic: %s for template_name=%s, device_type=%s, op_name=%s", + cls.__name__, + template_name, + device_type, + op_name, + ) + return cls + + return decorator + + +def get_template_heuristic( + template_name: str, device_type: str, op_name: str +) -> TemplateConfigHeuristics: + """ + Retrieve a template heuristic instance for the given template and device type. + + Returns a cached instance. Falls back to TemplateConfigHeuristics() if not found. + """ + cache_key: tuple[str | None, ...] = (template_name, device_type, op_name) + if cache_key in _HEURISTIC_CACHE: + return _HEURISTIC_CACHE[cache_key] + + heuristic_class = _lookup(template_name, device_type, op_name) + + if heuristic_class is None: + from .template.base import TemplateConfigHeuristics as _Base + + log.error( + "No template heuristic found - template_name=%s, device_type=%s, op_name=%s. " + "Available: %s. Using fallback.", + template_name, + device_type, + op_name, + list(_HEURISTIC_REGISTRY.keys()), + ) + return _Base() + + instance = heuristic_class() + _HEURISTIC_CACHE[cache_key] = instance + return instance + + +def get_registered_heuristic_class( + template_name: str, device_type: str, op_name: str +) -> None | type[TemplateConfigHeuristics]: + """Get the registered class (not instance) for the given template/device/op.""" + return _lookup(template_name, device_type, op_name) + + +# ----------------------------------------------------------------- +# Codegen heuristic API +# ----------------------------------------------------------------- + + +class CodegenConfigHeuristics: + """Base class for codegen heuristics (pointwise, reduction, etc.).""" + + def get_configs(self, *args: Any, **kwargs: Any) -> list[Any]: + raise NotImplementedError + + +def register_codegen_heuristic( + name: str, + device_type: str | None = None, + register: bool = True, +) -> Any: + """ + Decorator to register a codegen heuristic class. + + Args: + name: Heuristic name (e.g., "pointwise", "reduction"). + device_type: Device type ("hip", "xpu", "cuda"). + None means default/fallback for all devices. + register: Whether to actually register. + + Example: + @register_codegen_heuristic("pointwise", "hip", register=torch.version.hip is not None) + class ROCmPointwiseHeuristic(CodegenConfigHeuristics): + ... + """ + + def decorator(cls: type[CodegenConfigHeuristics]) -> type[CodegenConfigHeuristics]: + if register: + key: tuple[str | None, ...] = (name, device_type, None) + _register(key, cls) + log.info( + "Registered codegen heuristic: %s for name=%s, device_type=%s", + cls.__name__, + name, + device_type, + ) + return cls + + return decorator + + +def get_codegen_heuristic(name: str, device_type: str) -> CodegenConfigHeuristics: + """ + Retrieve a codegen heuristic instance for the given name and device type. + + Returns a cached instance. Uses cascading fallback: + (name, device_type, None) -> (name, None, None) + """ + cache_key: tuple[str | None, ...] = (name, device_type, None) + if cache_key in _HEURISTIC_CACHE: + return _HEURISTIC_CACHE[cache_key] + + heuristic_class = _lookup(name, device_type, None) + + if heuristic_class is None: + # Lazily import codegen heuristics to trigger registration + import torch._inductor.heuristics.triton_codegen # noqa: F401 + + heuristic_class = _lookup(name, device_type, None) + + if heuristic_class is None: + raise ValueError( + f"No codegen heuristic found - name={name}, device_type={device_type}. " + f"Available: {list(_HEURISTIC_REGISTRY.keys())}" + ) + + instance = heuristic_class() + _HEURISTIC_CACHE[cache_key] = instance + return instance + + +# ----------------------------------------------------------------- +# Utilities +# ----------------------------------------------------------------- + + +def clear_registry() -> None: + """Clear all registered heuristics. Primarily for testing.""" + _HEURISTIC_REGISTRY.clear() + _HEURISTIC_CACHE.clear() + + +@contextlib.contextmanager +def override_template_heuristics( + device_type: str, + template_op_pairs: list[tuple[str, str]], + override_heuristic_class: type[TemplateConfigHeuristics] | None = None, +) -> Iterator[None]: + """ + Context manager to temporarily override template heuristics. + + Args: + device_type: Device type ("cuda", "cpu", "xpu") + template_op_pairs: List of (template_name, op_name) pairs to override. + override_heuristic_class: Heuristic class to use for the override. + """ + if override_heuristic_class is None: + from .template.base import TemplateConfigHeuristics as _Base + + override_heuristic_class = _Base + original_entries: dict[tuple[str | None, ...], Any] = {} + new_keys: list[tuple[str | None, ...]] = [] + # Clears the shared cache (both template and codegen instances). + # Codegen instances are stateless so re-creation is cheap. + _HEURISTIC_CACHE.clear() + try: + for template_name, op_name in template_op_pairs: + if op_name is None: + raise AssertionError("op_name must not be None") + key: tuple[str | None, ...] = (template_name, device_type, op_name) + if key in _HEURISTIC_REGISTRY: + original_entries[key] = _HEURISTIC_REGISTRY[key] + _HEURISTIC_REGISTRY[key] = override_heuristic_class + new_keys.append(key) + yield + finally: + for key in new_keys: + _HEURISTIC_REGISTRY.pop(key, None) + if key in original_entries: + _HEURISTIC_REGISTRY[key] = original_entries[key] + # Same shared-cache clear on exit; see entry comment above. + _HEURISTIC_CACHE.clear() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0171788a6f84c3da6227ab1eb84f2f8c9206b5ba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__init__.py @@ -0,0 +1,28 @@ +""" +Template heuristics for pre-written template kernels (mm, conv, flex_attention...). + +These heuristics are used at compile time to generate autotuning configs +for template-based kernels (Triton, ATen, CuTe DSL, etc.). +""" + +from __future__ import annotations + +# expose the entry function +from torch._inductor.heuristics.registry import get_template_heuristic + +# NOTE: add new template heuristics here, so they get imported and registered +from . import ( + aten, + base, + contiguous_mm, + decompose_k, + nv_universal_gemm, + registry, + tlx, + triton, +) + + +__all__ = [ + "get_template_heuristic", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06e6e93360fd995d69c26de7e5a4c50323248e45 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/aten.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/aten.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad52bddd550650bee08c4c3adae8e5515319a07f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/aten.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..200fe48e4fbcaf5a9eb9ce066a9518f58040f180 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/contiguous_mm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/contiguous_mm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..465e7de77a4e9440ed456aa807ae04089739200f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/contiguous_mm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/cutedsl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/cutedsl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57e56280a9592e155fee7fff6f9f56457c4f2797 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/cutedsl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/decompose_k.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/decompose_k.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e4feb50bf8bb29ba1dddec465f815a5d9a98ea5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/decompose_k.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/flex_gemm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/flex_gemm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..757934dbe2893283960a1eff2e248917c153a6eb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/flex_gemm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/gemm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/gemm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..806d4b81858e13d2fe7af0ab3047e40c920e3e2c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/gemm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/nv_universal_gemm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/nv_universal_gemm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6921eeef0196e39a8ed4f7148a562b1efde3a2e5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/nv_universal_gemm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/params.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..608eb0b1a50c1faa1e507877d16a14c237c56ad5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/params.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/registry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7244fbd808204353a3eae102c5494cad271fd841 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/registry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/tlx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/tlx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92caeb428eab88ce12fd1dd1b57065a3b8438f59 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/tlx.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/triton.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/triton.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34a525b099e3dcde3fc3ce1c2cde9e6c44f88933 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/triton.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9eef618d8c0f43f584aa07a9775154f79c76cc1db9a0d119b1f2f9942c97477 +size 133527 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/triton_addmm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/triton_addmm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cba246563c85b24489050b0b1db55f10f45142b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/triton_addmm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/aten.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/aten.py new file mode 100644 index 0000000000000000000000000000000000000000..45044559685888fd02d420077f2729f82d4ad172 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/aten.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +from typing import Any, TYPE_CHECKING + +from torch._inductor import config as inductor_config +from torch._inductor.heuristics.registry import register_template_heuristic + +from ...kernel.bmm import aten_baddbmm, aten_bmm, aten_bmm_dtype +from ...kernel.mm import ( + aten__fp8_mm, + aten__int_mm, + aten_addmm, + aten_bias_addmm, + aten_mm, + aten_mm_dtype, +) +from ...kernel.mm_plus_mm import aten_mm_plus_mm +from .base import TemplateConfigHeuristics +from .gemm import GemmMaxAutotuneTemplateConfigHeuristics + + +if TYPE_CHECKING: + from collections.abc import Generator + + from ...kernel_inputs import KernelInputs + + +# These are all labeled as device type None to indicate that they +# are valid for all device types +@register_template_heuristic(aten_mm.uid, None) +@register_template_heuristic(aten_mm_dtype.uid, "cuda") +@register_template_heuristic(aten_mm_dtype.uid, "xpu") +@register_template_heuristic(aten__fp8_mm.uid, None) +@register_template_heuristic(aten__int_mm.uid, None) +@register_template_heuristic(aten_bmm.uid, None) +@register_template_heuristic(aten_mm_plus_mm.uid, None) +# bmm dtype is only valid on cuda +@register_template_heuristic(aten_bmm_dtype.uid, "cuda") +@register_template_heuristic(aten_bmm_dtype.uid, "xpu") +class ATenConfigHeuristics(TemplateConfigHeuristics): + """ + Pseudo heuristic to make ATen choices go through the same flow as other templates + + This is a single choice without kwargs + + If you want to use this with an ATen choice that has kwargs, just subclass + """ + + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> Generator[dict[str, Any], None, None]: + yield dict() + + +# None here indicates that this is valid for all device types on that op +# Note (None, op) takes precedence over (device_type, None) +@register_template_heuristic(aten_addmm.uid, None, op_name="addmm") +@register_template_heuristic(aten_baddbmm.uid, None, op_name="baddbmm") +class ATenAddMMConfigHeuristics(ATenConfigHeuristics): + def get_extra_kwargs( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> dict[str, Any]: + kwargs = super().get_extra_kwargs(kernel_inputs, op_name) + alpha = kernel_inputs.get_scalar("alpha") + beta = kernel_inputs.get_scalar("beta") + return { + **kwargs, + "alpha": alpha, + "beta": beta, + } + + +@register_template_heuristic(aten_bias_addmm.uid, None, op_name="addmm") +class ATenBiasAddMMConfigHeuristics( + ATenAddMMConfigHeuristics, GemmMaxAutotuneTemplateConfigHeuristics +): + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> Generator[dict[str, Any], None, None]: + nodes = kernel_inputs.nodes() + # for addmm, bias is the first input + bias = nodes[0] + if not ( + len(bias.get_size()) == 2 + and bias.get_stride()[0] == 0 + and inductor_config.triton.autotune_cublasLt + ): + raise AssertionError( + "Expected 2D bias with stride[0]==0 and autotune_cublasLt enabled" + ) + yield from super()._get_template_configs_impl(kernel_inputs, op_name) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/base.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/base.py new file mode 100644 index 0000000000000000000000000000000000000000..8369f35deb0433dbe0a4d629817b714e5277d87d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/base.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +from typing import Any, TYPE_CHECKING + +from .params import DictKernelTemplateParams, KernelTemplateParams + + +if TYPE_CHECKING: + from collections.abc import Generator + + from ...kernel_inputs import KernelInputs + + +class TemplateConfigHeuristics: + """Base class for generating sets of configs for an associated template.""" + + def should_run(self, inputs: KernelInputs) -> bool: + """ + hookup to check whether the configs are right to run at all e.g. you can check + max-autotune specific to your heuristic here or other things + If this returns False, get_template_configs will yield no configs + + Args: + inputs: KernelInputs + """ + return True + + def get_template_configs( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> Generator[KernelTemplateParams, None, None]: + """ + Get template configs for the given inputs. + + Prefer to override the _get_template_configs_impl method + to leverage things like should_run + """ + if not self.should_run(kernel_inputs): + return + + # Generate configs and fuse with extra_kwargs + for config_dict in self._get_template_configs_impl(kernel_inputs, op_name): + # Fuse extra_kwargs into config + yield DictKernelTemplateParams(config_dict) + + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> Generator[dict[str, Any], None, None]: + """ + Get template configs for the given inputs. + This is the main entry point for template-specific logic. + """ + # base implementation yields no entries + yield from [] + + def get_extra_kwargs( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> dict[str, Any]: + """ + Get extra kwargs for the given inputs/op for the template. + + Use this to return kwargs that are needed for the template, but + do not change depending on the config/choice, but are rather + always the same, for all configs + """ + return {} + + def adjust_kernel_inputs( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> KernelInputs: + """ + Adjust kernel inputs for the given inputs/op for the template. + + override this to adjust the kernel inputs e.g. (un)squeezing + """ + return kernel_inputs diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/contiguous_mm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/contiguous_mm.py new file mode 100644 index 0000000000000000000000000000000000000000..4e323ea390c7fea99d6d35ac4c97416a5d6f835c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/contiguous_mm.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from typing import Any, TYPE_CHECKING + +import torch +from torch._inductor.heuristics.registry import register_template_heuristic + +from ...ir import get_free_symbols +from ...kernel.mm import ( + addmm_contiguous_subgraph_template, + mm_contiguous_subgraph_template, +) +from ...kernel_inputs import KernelInputs, MMKernelInputs +from ...utils import use_contiguous +from .base import TemplateConfigHeuristics +from .gemm import GemmMaxAutotuneTemplateConfigHeuristics + + +if TYPE_CHECKING: + from collections.abc import Generator + + +@register_template_heuristic(mm_contiguous_subgraph_template.uid, None, op_name="mm") +@register_template_heuristic( + addmm_contiguous_subgraph_template.uid, None, op_name="addmm" +) +class EmptyContiguousMMConfigHeuristics(TemplateConfigHeuristics): + """empty heuristics to skip contiguous mm on not cuda""" + + +@register_template_heuristic( + mm_contiguous_subgraph_template.uid, + "cuda", + register=torch.version.hip is not None, + op_name="mm", +) +@register_template_heuristic( + addmm_contiguous_subgraph_template.uid, + "cuda", + register=torch.version.hip is not None, + op_name="addmm", +) +class ContiguousMMHeuristics(GemmMaxAutotuneTemplateConfigHeuristics): + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> Generator[dict[str, Any], None, None]: + """ + Get all the valid k_splits for the given m, n, k. + """ + if not isinstance(kernel_inputs, MMKernelInputs): + raise AssertionError(f"{self.__class__.__name__} requires MMKernelInputs") + # Check for unbacked symbols - if found, yield nothing + unbacked_symbols = any( + len(get_free_symbols(itr, unbacked_only=True)) > 0 + for itr in ( + *kernel_inputs.shapes_symbolic(), + *kernel_inputs.strides_symbolic(), + ) + ) + if unbacked_symbols: + return + mat2 = kernel_inputs.mat1mat2()[1] + if mat2.get_layout().is_contiguous(): + # no need for contiguous decomposition + return + m, n, k = kernel_inputs.mnk_symbolic() + if not use_contiguous(m, n, k): + return + yield {} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/cutedsl.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/cutedsl.py new file mode 100644 index 0000000000000000000000000000000000000000..e5a78b6468296feddd1c6adf84f1db8ef76a2aa1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/cutedsl.py @@ -0,0 +1,141 @@ +from dataclasses import dataclass +from enum import auto, Enum +from itertools import product + +import torch._inductor.config as config + + +class TensorMapUpdateMode(Enum): + """Enum mirroring cutlass.utils.TensorMapUpdateMode to decouple this file from a cutlass dependency.""" + + SMEM = auto() + GMEM = auto() + + +@dataclass(frozen=True) +class CuTeGemmConfig: + TILE_M: int = 128 + TILE_N: int = 192 + CLUSTER_M: int = 2 + CLUSTER_N: int = 1 + USE_2_CTA: bool = False + TENSORMAP_UPDATE_MODE: TensorMapUpdateMode = TensorMapUpdateMode.SMEM + + +def get_exhaustive_groupgemm_configs() -> list[CuTeGemmConfig]: + """ + Returns the exhaustive configuration set for the Blackwell CuTeDSL Grouped GEMM kernel. + For information regarding valid config sets, see: + https://github.com/NVIDIA/cutlass/blob/main/examples/python/CuTeDSL/cute/blackwell/kernel/grouped_gemm/grouped_gemm.py + """ + + # Tile_n is always the same regardless of 2cta + tile_n_vals = [32, 64, 96, 128, 160, 192, 224, 256] + + # Valid clusters + clusters_no_2cta = [ + (1, 1), + (1, 2), + (1, 4), + (1, 8), + (1, 16), + (2, 1), + (2, 2), + (2, 4), + (2, 8), + (4, 1), + (4, 2), + (4, 4), + (8, 1), + (8, 2), + (16, 1), + ] + clusters_2cta = [ + (2, 1), + (2, 2), + (2, 4), + (2, 8), + (4, 1), + (4, 2), + (4, 4), + (8, 1), + (8, 2), + (16, 1), + ] + + configs: list[CuTeGemmConfig] = [] + + for use_2cta, cluster_set, tile_m_range in [ + (False, clusters_no_2cta, [64, 128]), + (True, clusters_2cta, [128, 256]), + ]: + for tensormap_update_mode, tile_m, tile_n, (cluster_m, cluster_n) in product( + [TensorMapUpdateMode.SMEM, TensorMapUpdateMode.GMEM], + tile_m_range, + tile_n_vals, + cluster_set, + ): + configs.append( + CuTeGemmConfig( + tile_m, + tile_n, + cluster_m, + cluster_n, + USE_2_CTA=use_2cta, + TENSORMAP_UPDATE_MODE=tensormap_update_mode, + ) + ) + + return configs + + +def get_default_groupgemm_configs() -> list[CuTeGemmConfig]: + """ + Returns the default configuration set for the Blackwell CuTeDSL Grouped GEMM kernel. + """ + + config_tuples = [ + (128, 256, 2, 1, False, TensorMapUpdateMode.SMEM), + (256, 160, 2, 1, True, TensorMapUpdateMode.GMEM), + (256, 256, 2, 1, True, TensorMapUpdateMode.GMEM), + (64, 32, 1, 1, False, TensorMapUpdateMode.GMEM), + (64, 256, 1, 2, False, TensorMapUpdateMode.SMEM), + (128, 256, 1, 2, False, TensorMapUpdateMode.SMEM), + (256, 256, 2, 2, True, TensorMapUpdateMode.GMEM), + (128, 256, 1, 2, False, TensorMapUpdateMode.GMEM), + (64, 32, 1, 1, False, TensorMapUpdateMode.SMEM), + (256, 256, 2, 1, True, TensorMapUpdateMode.SMEM), + (128, 256, 1, 1, False, TensorMapUpdateMode.GMEM), + (256, 256, 8, 1, True, TensorMapUpdateMode.GMEM), + (64, 32, 1, 2, False, TensorMapUpdateMode.SMEM), + (256, 192, 2, 1, True, TensorMapUpdateMode.GMEM), + (256, 256, 2, 2, True, TensorMapUpdateMode.SMEM), + (128, 96, 1, 2, False, TensorMapUpdateMode.SMEM), + (64, 192, 1, 1, False, TensorMapUpdateMode.SMEM), + (64, 64, 1, 1, False, TensorMapUpdateMode.GMEM), + (64, 192, 1, 1, False, TensorMapUpdateMode.GMEM), + (128, 64, 1, 1, False, TensorMapUpdateMode.GMEM), + (64, 160, 1, 1, False, TensorMapUpdateMode.GMEM), + (64, 256, 1, 1, False, TensorMapUpdateMode.GMEM), + ] + + return [CuTeGemmConfig(*args) for args in config_tuples] + + +def get_groupgemm_configs() -> list[CuTeGemmConfig]: + """ + Returns the configuration set for the Blackwell CuTeDSL Grouped GEMM kernel. + + Note: CuTeDSL autotuning is still experimental — enabling it may trigger kernel launch failures + or unstable results. By default, autotuning is disabled and we return only + a single baseline config. + """ + if ( + config.cutedsl_enable_autotuning + and config.max_autotune_gemm_search_space == "EXHAUSTIVE" + ): + return get_exhaustive_groupgemm_configs() + elif config.cutedsl_enable_autotuning: + return get_default_groupgemm_configs() + else: + return [get_default_groupgemm_configs()[0]] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/decompose_k.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/decompose_k.py new file mode 100644 index 0000000000000000000000000000000000000000..eff399242c47c4984719f639613b27707ac90e0d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/decompose_k.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +from typing import Any, TYPE_CHECKING + +import sympy + +from torch._inductor.heuristics.registry import register_template_heuristic + +from ...ir import get_free_symbols +from ...kernel.mm import decompose_k_subgraph_template +from ...kernel_inputs import KernelInputs, MMKernelInputs +from ...utils import get_k_splits +from ...virtualized import V +from .base import TemplateConfigHeuristics +from .gemm import GemmMaxAutotuneTemplateConfigHeuristics + + +if TYPE_CHECKING: + from collections.abc import Generator + + +@register_template_heuristic(decompose_k_subgraph_template.uid, None, op_name="mm") +class EmptyDecomposeKConfigHeuristics(TemplateConfigHeuristics): + """empty heuristics to skip decompose k on anything not cuda""" + + +@register_template_heuristic( + decompose_k_subgraph_template.uid, + "xpu", + op_name="mm", +) +# Register on CUDA (both NVIDIA and ROCm/HIP) +# Runtime enablement is controlled by config.triton.num_decompose_k_splits (0 disables) +@register_template_heuristic( + decompose_k_subgraph_template.uid, + "cuda", + op_name="mm", +) +# TODO(coconutruben): enable decompose k on other devices (xpu, cpu, mps, mtia) +# by either adding specific register_template_heuristic tags, or setting the +# device to None (enabled on all devices) +class DecomposeKConfigHeuristics(GemmMaxAutotuneTemplateConfigHeuristics): + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> Generator[dict[str, Any], None, None]: + """ + Get all the valid k_splits for the given m, n, k. + """ + if not isinstance(kernel_inputs, MMKernelInputs): + raise AssertionError(f"{self.__class__.__name__} requires MMKernelInputs") + + # Check for unbacked symbols - if found, yield nothing + unbacked_symbols = any( + len(get_free_symbols(itr, unbacked_only=True)) > 0 + for itr in ( + *kernel_inputs.shapes_symbolic(), + *kernel_inputs.strides_symbolic(), + ) + ) + if unbacked_symbols: + return + + m, n, k = kernel_inputs.mnk_symbolic() + k_splits = get_k_splits(m, n, k) + for k_split in k_splits: + if not V.graph.sizevars.statically_known_true( + sympy.Eq(sympy.Mod(k, k_split), 0) + ): + continue + yield {"k_split": k_split} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/flex_gemm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/flex_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..22623f25117fcd8a98f9775dc713ec9c47cbc35f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/flex_gemm.py @@ -0,0 +1,258 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +from dataclasses import fields +from functools import cache +from typing import Any, TYPE_CHECKING, TypeAlias + +import sympy + +import torch +import torch._vendor.quack.gemm_config as quack_gemm_config +from torch.utils._ordered_set import OrderedSet + + +if TYPE_CHECKING: + from collections.abc import Sequence + +GemmConfigKey: TypeAlias = tuple[tuple[str, Any], ...] + + +def gemm_config_key(config: quack_gemm_config.GemmConfig) -> GemmConfigKey: + """Project a QuACK GEMM config using the dataclass schema as the contract.""" + return tuple( + (field.name, getattr(config, field.name)) + for field in fields(quack_gemm_config.GemmConfig) + ) + + +def gemm_config_from_key(config_key: GemmConfigKey) -> quack_gemm_config.GemmConfig: + """Reconstruct a QuACK GEMM config from its generated-code cache key.""" + return quack_gemm_config.GemmConfig(**dict(config_key)) + + +def explicit_gemm_configs_for_device( + config: dict[str, Any], device: torch.device +) -> tuple[quack_gemm_config.GemmConfig, ...]: + """Return device configs matching every explicitly pinned field. + + Exact type matching prevents bool/int aliases from selecting a different key. + """ + field_names = tuple(field.name for field in fields(quack_gemm_config.GemmConfig)) + unexpected = [name for name in config if name not in field_names] + if unexpected: + raise NotImplementedError( + "FlexGEMM explicit QUACK config contains unexpected GemmConfig fields: " + f"{unexpected}" + ) + + candidates = candidate_gemm_configs_for_device(device) + expected_device_capacity = candidates[0].device_capacity + requested_device_capacity = config.get("device_capacity") + if ( + type(requested_device_capacity) is type(expected_device_capacity) + and requested_device_capacity != expected_device_capacity + ): + raise NotImplementedError( + f"FlexGEMM explicit QUACK config targets SM{requested_device_capacity}0, " + f"but {device} uses SM{expected_device_capacity}0 configs" + ) + matches = tuple( + candidate + for candidate in candidates + if all( + type(value) is type(getattr(candidate, name)) + and value == getattr(candidate, name) + for name, value in config.items() + ) + ) + if matches: + return matches + raise NotImplementedError( + f"FlexGEMM explicit QUACK config constraints are not supported on {device}: " + f"{config}" + ) + + +@cache +def dense_gemm_config_priority_keys() -> tuple[GemmConfigKey, ...]: + """Return the measured dense FlexGEMM QuACK preference order.""" + configs = ( + quack_gemm_config.GemmConfig( + tile_m=128, + tile_n=256, + pingpong=False, + is_dynamic_persistent=True, + cluster_m=2, + device_capacity=10, + ), + quack_gemm_config.GemmConfig( + tile_m=128, + tile_n=192, + pingpong=False, + is_dynamic_persistent=True, + cluster_m=2, + device_capacity=10, + ), + quack_gemm_config.GemmConfig( + tile_m=256, + tile_n=256, + pingpong=False, + is_dynamic_persistent=True, + cluster_m=2, + device_capacity=10, + ), + quack_gemm_config.GemmConfig( + tile_m=256, + tile_n=256, + pingpong=False, + is_dynamic_persistent=True, + cluster_m=2, + cluster_n=2, + device_capacity=10, + ), + quack_gemm_config.GemmConfig( + tile_m=256, + tile_n=192, + pingpong=False, + is_dynamic_persistent=True, + cluster_m=2, + device_capacity=10, + ), + quack_gemm_config.GemmConfig( + tile_m=128, + tile_n=128, + pingpong=False, + is_dynamic_persistent=False, + cluster_m=1, + device_capacity=10, + ), + quack_gemm_config.GemmConfig( + tile_m=128, + tile_n=256, + pingpong=False, + is_dynamic_persistent=True, + cluster_m=1, + device_capacity=10, + ), + quack_gemm_config.GemmConfig( + tile_m=128, + tile_n=256, + pingpong=False, + is_dynamic_persistent=False, + cluster_m=1, + device_capacity=10, + ), + quack_gemm_config.GemmConfig( + tile_m=128, + tile_n=128, + pingpong=False, + is_dynamic_persistent=True, + cluster_m=2, + device_capacity=10, + ), + quack_gemm_config.GemmConfig( + tile_m=256, + tile_n=128, + pingpong=False, + is_dynamic_persistent=True, + cluster_m=2, + device_capacity=10, + ), + quack_gemm_config.GemmConfig( + tile_m=128, + tile_n=224, + pingpong=False, + is_dynamic_persistent=True, + cluster_m=1, + device_capacity=10, + ), + quack_gemm_config.GemmConfig( + tile_m=128, + tile_n=160, + pingpong=False, + is_dynamic_persistent=True, + cluster_m=1, + device_capacity=10, + ), + ) + return tuple(gemm_config_key(config) for config in configs) + + +def candidate_gemm_configs_for_device(device: torch.device): + """Return all device-compatible QuACK configs before shape-specific ranking.""" + device_capacity = torch.cuda.get_device_capability(device)[0] + if device_capacity == 11: + device_capacity = 10 + priority_map = { + key: priority for priority, key in enumerate(dense_gemm_config_priority_keys()) + } + configs = sorted( + ( + config + for config in quack_gemm_config.get_all_configs() + if config.device_capacity == device_capacity and not config.use_tma_gather + ), + key=lambda config: ( + priority_map.get(gemm_config_key(config), len(priority_map)), + config.tile_m, + config.tile_n, + config.cluster_m, + config.cluster_n, + int(config.is_dynamic_persistent), + ), + ) + if not configs: + raise RuntimeError( + f"FlexGEMM found no QuACK configs for CUDA device capability " + f"SM{device_capacity}0" + ) + return configs + + +def default_gemm_config_key( + device: torch.device, + m, + n, + configs: Sequence[quack_gemm_config.GemmConfig] | None = None, +) -> GemmConfigKey: + """Return the untuned default QuACK config key for generated code.""" + configs = candidate_gemm_configs_for_device(device) if configs is None else configs + config_keys = OrderedSet([gemm_config_key(config) for config in configs]) + default_key, skinny_key, large_rect_key, large_key = ( + dense_gemm_config_priority_keys()[:4] + ) + + from torch._inductor.virtualized import V + + guard_or_false = V.graph.sizevars.guard_or_false + if guard_or_false(sympy.Le(m, n)): + min_dim, max_dim = m, n + elif guard_or_false(sympy.Lt(n, m)): + min_dim, max_dim = n, m + else: + return ( + default_key if default_key in config_keys else gemm_config_key(configs[0]) + ) + + if guard_or_false(sympy.Lt(min_dim, 512)): + preferred_keys = (skinny_key, default_key) + elif guard_or_false(sympy.And(sympy.Eq(min_dim, 1024), sympy.Eq(max_dim, 1024))): + preferred_keys = (skinny_key, default_key) + elif guard_or_false( + sympy.And( + sympy.Ge(max_dim, 4096), sympy.Ge(min_dim, 768), sympy.Lt(min_dim, 1024) + ) + ): + preferred_keys = (large_key, default_key) + elif guard_or_false(sympy.And(sympy.Ge(max_dim, 4096), sympy.Eq(min_dim, 1024))): + preferred_keys = (large_rect_key, default_key) + elif guard_or_false(sympy.Ge(min_dim, 2048)): + preferred_keys = (large_key, default_key) + else: + preferred_keys = (default_key,) + + for key in preferred_keys: + if key in config_keys: + return key + return gemm_config_key(configs[0]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/gemm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..97b7ca98cd746a610e6408b23f07b570d22f00ca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/gemm.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ... import config as inductor_config +from .base import TemplateConfigHeuristics + + +if TYPE_CHECKING: + from ...kernel_inputs import KernelInputs + + +class GemmMaxAutotuneTemplateConfigHeuristics(TemplateConfigHeuristics): + def should_run(self, inputs: KernelInputs) -> bool: + """ + simple base override for GEMM family templates that run only in max-autotune + """ + return inductor_config.max_autotune or inductor_config.max_autotune_gemm diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/nv_universal_gemm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/nv_universal_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..46fe835e84c2005dc2bcfd95d4fd7751ae30e7c4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/nv_universal_gemm.py @@ -0,0 +1,462 @@ +from __future__ import annotations + +import logging +from collections import defaultdict +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import torch +from torch._inductor import config +from torch._inductor.utils import ensure_nvmatmul_heuristics_available +from torch._logging import getArtifactLogger +from torch.utils._ordered_set import OrderedSet + +from .gemm import GemmMaxAutotuneTemplateConfigHeuristics + + +if TYPE_CHECKING: + from ...kernel_inputs import KernelInputs, MMKernelInputs + + +log = logging.getLogger(__name__) +# Use autotuning artifact logger for detailed nvMatmulHeuristics logging +# Enable with TORCH_LOGS="+autotuning" +autotuning_log = getArtifactLogger(__name__, "autotuning") + +# Type alias for kernel config key tuple. +# Currently matches on (tile_m, tile_n, cluster_m, cluster_n). +# tile_k excluded because nvMatmulHeuristics and cutlass.operators use it to mean different things. +# TODO(nikhilap): Extend config key for stages/split_k https://github.com/pytorch/pytorch/issues/177578 +ConfigKey = tuple[int, int, int, int] + + +@dataclass +class HeuristicConfig: + """Configuration recommended by nvMatmulHeuristics.""" + + tile_m: int + tile_n: int + tile_k: int + cluster_m: int + cluster_n: int + stages: int + split_k: int + warp_tile_m: int + warp_tile_n: int + warp_tile_k: int + estimated_runtime: float + + +def _make_config_key_from_heuristic(cfg: HeuristicConfig) -> ConfigKey: + """Build config key from HeuristicConfig returned by nvMatmulHeuristics.""" + return (cfg.tile_m, cfg.tile_n, cfg.cluster_m, cfg.cluster_n) + + +def _make_config_key_from_kernel_design(design) -> ConfigKey | None: + """Build config key from cutlass.operators kernel metadata.design.""" + if ( + hasattr(design, "tile_shape") + and len(design.tile_shape) >= 2 + and hasattr(design, "cluster_shape") + and len(design.cluster_shape) >= 2 + ): + return ( + design.tile_shape[0], + design.tile_shape[1], + design.cluster_shape[0], + design.cluster_shape[1], + ) + return None + + +def _make_config_key_from_heuristics_kernel(kernel) -> ConfigKey: + """Build config key from nvMatmulHeuristics kernel config struct.""" + return ( + kernel.cta[0], + kernel.cta[1], + kernel.cluster[0], + kernel.cluster[1], + ) + + +class NVUniversalGemmHeuristics(GemmMaxAutotuneTemplateConfigHeuristics): + """ + Heuristics for NVGEMM kernel selection using nvMatmulHeuristics. + """ + + def should_run(self, inputs: KernelInputs) -> bool: + """Check if heuristics should be used. + + Args: + inputs: KernelInputs + """ + return super().should_run(inputs) and ensure_nvmatmul_heuristics_available() + + def filter_kernels( + self, + kernels: list, + inputs: MMKernelInputs, + count: int, + accumulator_type: torch.dtype = torch.float32, + ) -> list: + """ + Filter and rank kernels using nvMatmulHeuristics. + + Matches on (tile_m, tile_n, tile_k, cluster_m, cluster_n). + Returns kernels sorted by estimated runtime. + + If nvMatmulHeuristics is not installed or max_autotune is disabled, + returns the first `count` kernels without heuristic ranking. + + Args: + kernels: List of cutlass.operators.Operator objects + inputs: MMKernelInputs with matrix shapes, dtypes, and strides + count: Maximum number of kernels to return + accumulator_type: Accumulator dtype + + Returns: + Filtered list of kernels, sorted by estimated performance + """ + if not self.should_run(inputs): + return kernels[:count] + + m, n, k = inputs.mnk_hinted() + batch_size = inputs.batch_hinted() + dtype_a = inputs.dtype(inputs._mat1_idx) + dtype_b = inputs.dtype(inputs._mat2_idx) + out_dtype = inputs.out_dtype() + strides = inputs.strides_hinted() + layout_a = "row" if strides[inputs._mat1_idx][-1] == 1 else "col" + layout_b = "row" if strides[inputs._mat2_idx][-1] == 1 else "col" + + config_to_kernels = self._extract_config_to_kernels(kernels) + + if not config_to_kernels: + log.debug("Could not extract kernel configs, using first %d kernels", count) + return kernels[:count] + + heuristic_configs = self._get_heuristic_configs( + m, + n, + k, + dtype_a, + layout_a, + layout_b, + count, + OrderedSet(config_to_kernels.keys()), + accumulator_type, + batch_size, + dtype_b=dtype_b, + out_dtype=out_dtype, + ) + + if not heuristic_configs: + log.debug("No heuristic configs found, using first %d kernels", count) + return kernels[:count] + + # Match kernels to heuristic configs + matched: list[tuple] = [] + for cfg in heuristic_configs: + key = _make_config_key_from_heuristic(cfg) + kernels_for_key = config_to_kernels.get(key) + if not kernels_for_key: + continue + for kernel in kernels_for_key: + matched.append((kernel, cfg.estimated_runtime)) + + if not matched: + log.debug( + "No kernels matched heuristic configs, using first %d kernels", count + ) + return kernels[:count] + + matched.sort(key=lambda x: x[1]) + selected = matched[:count] + result = [k for k, _ in selected] + + # Supplement with hand-picked configs in the space nvMatmulHeuristics doesn't currently explore. + if config.nvgemm_supplement_configs: + _SUPPLEMENT_CONFIGS: OrderedSet[ConfigKey] = OrderedSet( + [ + (64, 128, 1, 1), + (64, 128, 1, 2), + (64, 128, 1, 4), + (64, 128, 1, 8), + (64, 128, 1, 16), + (64, 256, 1, 8), + (64, 256, 1, 16), + (64, 32, 1, 2), + (64, 32, 1, 4), + (128, 64, 1, 1), + (128, 64, 1, 4), + (128, 64, 2, 1), + (128, 128, 1, 8), + (128, 128, 1, 16), + (128, 128, 2, 2), + (128, 128, 2, 4), + (128, 128, 2, 8), + (128, 192, 1, 1), + (128, 192, 1, 2), + (128, 192, 1, 4), + (128, 192, 2, 1), + (128, 192, 2, 2), + (128, 256, 1, 4), + (128, 256, 1, 8), + (128, 256, 1, 16), + (128, 256, 2, 1), + (128, 256, 2, 8), + (256, 192, 1, 1), + (256, 192, 1, 2), + (256, 192, 1, 4), + (256, 192, 2, 1), + (256, 256, 2, 1), + (256, 256, 2, 4), + (256, 256, 4, 2), + (256, 256, 4, 4), + (256, 256, 8, 1), + (256, 256, 8, 2), + (256, 128, 2, 1), + (256, 128, 2, 2), + # NVFP4 oracle-best configs (per-shape autotune winners over + # an 83-shape LLM sweep) that nvMatmulHeuristics does not + # propose; adding them lets autotune reach the oracle-best + # config on 73/83 of those shapes. + (128, 64, 1, 2), + (128, 128, 1, 1), + (128, 128, 1, 4), + (128, 256, 1, 1), + (256, 64, 2, 1), + (256, 128, 4, 1), + (256, 192, 2, 2), + (256, 192, 4, 1), + (256, 192, 4, 2), + (256, 256, 4, 1), + ] + ) + selected_keys = OrderedSet( + [_make_config_key_from_kernel_design(k.metadata.design) for k in result] + ) + for key, key_kernels in config_to_kernels.items(): + if key not in selected_keys and key in _SUPPLEMENT_CONFIGS: + result.append(key_kernels[0]) + + log.debug( + "Heuristic filtered to %d kernels from %d total", len(result), len(kernels) + ) + + autotuning_log.info( + "nvMatmulHeuristics kernel filtering: %d heuristic configs matched %d " + "of %d available kernels, returning top %d", + len(heuristic_configs), + len(matched), + len(kernels), + len(result), + ) + for i, (kernel, runtime) in enumerate(selected): + design = kernel.metadata.design + autotuning_log.info( + " Selected kernel %d: tile=(%d, %d, %d), cluster=(%d, %d), " + "estimated_runtime=%.2f us", + i, + design.tile_shape[0], + design.tile_shape[1], + design.tile_shape[2], + design.cluster_shape[0], + design.cluster_shape[1], + runtime * 1e6, + ) + + return result + + def _extract_config_to_kernels(self, kernels: list) -> dict[ConfigKey, list]: + """Build a map from config key to kernels.""" + config_to_kernels: dict[ConfigKey, list] = defaultdict(list) + + for kernel in kernels: + key = _make_config_key_from_kernel_design(kernel.metadata.design) + if key is not None: + config_to_kernels[key].append(kernel) + + return config_to_kernels + + def _get_layout_enum(self, layout_a: str, layout_b: str): + """Map layout strings to NvMatmulHeuristicsMatmulLayout enum.""" + import nvMatmulHeuristics + + trans_a = "T" if layout_a == "row" else "N" + trans_b = "T" if layout_b == "row" else "N" + layout_str = f"{trans_a}{trans_b}_ROW_MAJOR" + return nvMatmulHeuristics.NvMatmulHeuristicsMatmulLayout[layout_str] + + def _make_validity_callback( + self, + valid_configs: OrderedSet[ConfigKey], + ): + """ + Create callback for nvMatmulHeuristics that only accepts configurations + matching the available cutlass.operators kernel tile/cluster shapes. + """ + + def validity_check(kernel_config_ptr, problem_ptr): + kernel = kernel_config_ptr.contents + key = _make_config_key_from_heuristics_kernel(kernel) + return 1 if key in valid_configs else 0 + + return validity_check + + def _get_heuristic_configs( + self, + m: int, + n: int, + k: int, + dtype_a: torch.dtype, + layout_a: str, + layout_b: str, + count: int, + valid_configs: OrderedSet[ConfigKey], + accumulator_type: torch.dtype = torch.float32, + batch_size: int = 1, + dtype_b: torch.dtype | None = None, + out_dtype: torch.dtype | None = None, + ) -> list[HeuristicConfig]: + """ + Get kernel configurations recommended by nvMatmulHeuristics. + + Uses validity callback to filter to cutlass.operators-compatible configs. + """ + import nvMatmulHeuristics + + dtype_to_cublas = { + torch.float64: "D", + torch.float32: "S", + torch.float16: "H", + torch.bfloat16: "T", + torch.float8_e4m3fn: "Q", + torch.float8_e5m2: "R", + torch.float4_e2m1fn_x2: "F4", + } + a_char = dtype_to_cublas.get(dtype_a, "H") + b_char = dtype_to_cublas.get(dtype_b or dtype_a, a_char) + out_char = dtype_to_cublas.get(out_dtype or dtype_a, a_char) + acc_char = dtype_to_cublas.get(accumulator_type, "S") + + # nvMatmulHeuristics precision string formats: + # - 3-letter {A}{B}{out}: used for standard GEMM and multi-char tokens (F4, BF) + # - 5-letter {A}{B}{C}{compute}{D}: used for single-char FP8 types (Q, R, O) + has_multichar = any(len(c) > 1 for c in (a_char, b_char, out_char)) + if has_multichar: + precision = f"{a_char}{b_char}{out_char}" + elif a_char != b_char or a_char in ("Q", "R", "O"): + precision = f"{a_char}{b_char}{out_char}{acc_char}{out_char}" + else: + precision = f"{a_char}{acc_char}{out_char}" + + # NvMatmulHeuristicsInterfaceEx configuration: + # - backend=CUTLASS3: Use CUTLASS 3.x kernel database for Hopper+ GPUs + # TODO(nikhilap): Update when nvMatmulHeuristics supports CUTLASS 4 + # - flags=PERF_MODEL_BASED_AUTO_TUNING: Rank kernels using analytical + # performance model (faster than empirical profiling) + # - load_discovery_implicitly=True: Auto-load kernel discovery sets on demand + lh = nvMatmulHeuristics.NvMatmulHeuristicsInterfaceEx( + backend=nvMatmulHeuristics.NvMatmulHeuristicsTarget.CUTLASS3, + flags=nvMatmulHeuristics.NvMatmulHeuristicsFlags.PERF_MODEL_BASED_AUTO_TUNING, + load_discovery_implicitly=True, + ) + + backend = lh.createBackend(nvMatmulHeuristics.NvMatmulHeuristicsTarget.CUTLASS3) + + validity_callback = self._make_validity_callback(valid_configs) + lh.setBackendCallbackProperty( + backend, + nvMatmulHeuristics.NvMatmulHeuristicsBackendPropertyCallbackKind.KERNEL_ADDITIONAL_VALIDITY_CHECK, + validity_callback, + ) + + layout = self._get_layout_enum(layout_a, layout_b) + + lh.loadInternalDiscoverySet(layout, precision=precision) + + problem = lh.makeNvMatmulHeuristicsProblem( + m, n, k, layout, batch_size=batch_size + ) + raw_configs = lh.getEx(problem, count, backend, precision=precision) + lh.destroyBackend(backend) + + if not raw_configs: + autotuning_log.debug( + "nvMatmulHeuristics returned 0 configs for M=%d, N=%d, K=%d, " + "dtype=%s, layout=(%s, %s), precision=%s", + m, + n, + k, + dtype_a, + layout_a, + layout_b, + precision, + ) + return [] + + configs = [] + for cfg in raw_configs: + kernel = cfg["kernel"] + configs.append( + HeuristicConfig( + tile_m=kernel.cta_tile_m, + tile_n=kernel.cta_tile_n, + tile_k=kernel.cta_tile_k, + cluster_m=kernel.cluster_m, + cluster_n=kernel.cluster_n, + stages=kernel.stages, + split_k=kernel.split_k, + warp_tile_m=kernel.warp_tile_m, + warp_tile_n=kernel.warp_tile_n, + warp_tile_k=kernel.warp_tile_k, + estimated_runtime=cfg["runtime"], + ) + ) + + autotuning_log.info( + "nvMatmulHeuristics for M=%d, N=%d, K=%d, dtype=%s, layout=(%s, %s), " + "precision=%s: %d configs returned", + m, + n, + k, + dtype_a, + layout_a, + layout_b, + precision, + len(configs), + ) + for i, cfg in enumerate(configs): + runtime_us = cfg.estimated_runtime * 1e6 + autotuning_log.info( + " Config %d: tile=(%d, %d, %d), cluster=(%d, %d), " + "stages=%d, split_k=%d, warp_tile=(%d, %d, %d), " + "estimated_runtime=%.2f us", + i, + cfg.tile_m, + cfg.tile_n, + cfg.tile_k, + cfg.cluster_m, + cfg.cluster_n, + cfg.stages, + cfg.split_k, + cfg.warp_tile_m, + cfg.warp_tile_n, + cfg.warp_tile_k, + runtime_us, + ) + + return configs + + +# Singleton instance for use in add_nv_universal_gemm_choices +_nvgemm_heuristics: NVUniversalGemmHeuristics | None = None + + +def get_nvgemm_heuristics() -> NVUniversalGemmHeuristics: + """Get the singleton NVUniversalGemmHeuristics instance.""" + global _nvgemm_heuristics + if _nvgemm_heuristics is None: + _nvgemm_heuristics = NVUniversalGemmHeuristics() + return _nvgemm_heuristics diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/params.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/params.py new file mode 100644 index 0000000000000000000000000000000000000000..92b130217e3d19507b51e7bd384072548c67abb4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/params.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import Any + + +class KernelTemplateParams(ABC): + """Abstract base class for kernel template parameters.""" + + @abstractmethod + def to_kwargs(self) -> dict[str, Any]: + """Convert params to kwargs dict for template.choice_or_none()""" + + @abstractmethod + def to_serializeable_dict(self) -> dict[str, Any]: + """Convert params to serializable dict for storage/caching""" + + @classmethod + @abstractmethod + def from_dict(cls, data: dict[str, Any]) -> KernelTemplateParams: + """Create params instance from dict""" + + +class DictKernelTemplateParams(KernelTemplateParams): + """Simple implementation that wraps a kwargs dict""" + + # NOTE: this is a compatibility layer, until every template + # has time to define their own params class, with meaningful + # defaults etc. + + def __init__(self, kwargs: dict[str, Any]): + self.kwargs = kwargs + + def to_kwargs(self) -> dict[str, Any]: + return self.kwargs.copy() + + def to_serializeable_dict(self) -> dict[str, Any]: + return self.kwargs.copy() + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> DictKernelTemplateParams: + return cls(data) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/registry.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..f8b8a42bc5b9d395fb4d84fbbbada32cb757bbd7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/registry.py @@ -0,0 +1,25 @@ +"""Backward-compatible re-exports from the shared heuristics registry.""" + +from torch._inductor.heuristics.registry import ( + _HEURISTIC_CACHE, + _TEMPLATE_HEURISTIC_REGISTRY, + clear_registry, + get_registered_heuristic_class, + get_template_heuristic, + override_template_heuristics, + register_template_heuristic, +) + +from .base import TemplateConfigHeuristics + + +__all__ = [ + "TemplateConfigHeuristics", + "_HEURISTIC_CACHE", + "_TEMPLATE_HEURISTIC_REGISTRY", + "clear_registry", + "get_registered_heuristic_class", + "get_template_heuristic", + "override_template_heuristics", + "register_template_heuristic", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/tlx.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/tlx.py new file mode 100644 index 0000000000000000000000000000000000000000..7130730453c10a21855a5cf9b2b97f8d3a17d325 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/tlx.py @@ -0,0 +1,10 @@ +# TorchTLX lives in the fbtriton, not in +# PyTorch. Importing the integration registers TLX template heuristics and +# installs config.inductor_choices_class; it succeeds only when the active +# Triton is the fbtriton fork +# and fails cleanly on trunk triton. Actual engagement is +# still gated at runtime by TORCHINDUCTOR_TLX_MODE (config.triton.tlx_mode). +try: + import triton.language.extra.tlx.inductor.registry # noqa: F401 # type: ignore[import-not-used] +except ImportError: + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/triton.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/triton.py new file mode 100644 index 0000000000000000000000000000000000000000..361f2e91c9a4ac2fe590aaaeca56c6ef67f507f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/triton.py @@ -0,0 +1,3669 @@ +from __future__ import annotations + +import dataclasses +import itertools +import logging +import math +import os +from functools import partial +from threading import Lock +from typing import Any, TYPE_CHECKING + +import sympy + +import torch +from torch._inductor.heuristics.registry import register_template_heuristic +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import Min, Mod +from torch.utils._triton import has_triton_stable_tma_api + +from ... import config +from ...autows_utils import meta_ws_enabled +from ...kernel.bmm import bmm_template +from ...kernel.mm import ( + blackwell_ws_persistent_device_tma_mm_template, + get_scaling_options, + get_tile_size, + mm_template, + persistent_mm_template, + persistent_tma_mm_template, + scaled_mm_device_tma_epilogue_scaling_template, + scaled_mm_device_tma_main_loop_scaling_template, +) +from ...kernel.mm_plus_mm import mm_plus_mm_template +from ...kernel_inputs import KernelInputs, MMKernelInputs +from ...runtime.hints import DeviceProperties +from ...utils import ( + get_backend_num_stages, + get_default_kpack, + get_num_sms, + get_tma_workspace_arg, + TMA_DESCRIPTOR_SIZE, + triton_type, + using_b200, + using_rocm_rdna3, +) +from ...virtualized import V +from .gemm import GemmMaxAutotuneTemplateConfigHeuristics +from .triton_addmm import AddMMConfigMixin + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator + + from triton import Config as TritonConfig + +else: + from torch._inductor.runtime.triton_compat import Config as TritonConfig +log = logging.getLogger(__name__) + + +def _origami_enabled() -> bool: + """Check if origami GEMM optimization is enabled.""" + return config.rocm.origami + + +USE_META_WS = meta_ws_enabled() + + +def _use_template_autows() -> bool: + """Whether to expand the Blackwell GEMM search space with Meta Triton autoWS + configs: opt-in flag plus an enabled meta-WS Triton build.""" + return config.triton.enable_template_autows and USE_META_WS + + +# Check if running on ROCm +IS_ROCM = torch.version.hip is not None + + +# rocm-origami pip pkg is only available on ROCm builds and is only used when +# both max_autotune and config.rocm.origami are enabled (env-var driven, set once +# at config import). Cache the import here so the hot path never pays an exception +# and CUDA/CPU/origami-disabled processes never attempt the import. +if IS_ROCM and config.max_autotune and config.rocm.origami: + try: + import origami # type: ignore[import-not-found] + except ImportError: + origami = None + log.info( + "rocm-origami not installed; ROCm origami GEMM selection disabled. " + "Install via pip install rocm-origami to enable." + ) +else: + origami = None + + +# TODO(rocm-origami): replace these wrappers with public accessors when the +# rocm-origami package exposes them. Centralizing the private-attribute access +# here keeps the noqa suppressions localized and makes the migration a one-line +# change per helper instead of ~10 scattered call sites. +def _origami_problem(selector): # type: ignore[no-untyped-def] + return selector._problem + + +def _origami_hardware(selector): # type: ignore[no-untyped-def] + return selector._hardware + + +def _origami_configs(selector): # type: ignore[no-untyped-def] + return selector._configs + + +# Gemm Configs +@dataclasses.dataclass +class BaseConfig: + """ + Base Gemm configuration used for most backends (CPU, CUDA) + """ + + block_m: int + block_n: int + block_k: int + num_stages: int + num_warps: int + hint_override: int | None = dataclasses.field(kw_only=True, default=None) + + +@dataclasses.dataclass +class GemmConfig(BaseConfig): + """ + Gemm configuration used for most backends (CPU, CUDA) + """ + + group_m: int = dataclasses.field(kw_only=True, default=8) + + +ConvConfig = BaseConfig + + +@dataclasses.dataclass +class DepthwiseConvConfig: + """ + Configuration for depthwise conv1d Triton template. + Uses BLOCK_N x BLOCK_L x BLOCK_C tiling (channels-last NLC layout). + Matches the hand-written NLC kernel from depthwise_conv1d_benchmark.py. + """ + + block_n: int + block_l: int + block_c: int + num_stages: int + num_warps: int + + +@dataclasses.dataclass +class BlackwellGPUGemmConfig(GemmConfig): + """ + Gemm configuration used for templates with features explicitly + targeting Nvidia Blackwell GPUs + """ + + # epilogue_subtile must be a power of 2 (1 means no subtiling) + epilogue_subtile: int = dataclasses.field(kw_only=True, default=1) + warp_specialize: bool = dataclasses.field(kw_only=True, default=True) + flatten: bool = dataclasses.field(kw_only=True, default=True) + # Meta Triton autoWS knobs (meta-WS builds only) + use_meta_ws: bool = dataclasses.field(kw_only=True, default=False) + data_partition_factor: int = dataclasses.field(kw_only=True, default=1) + separate_epilogue_store: bool = dataclasses.field(kw_only=True, default=False) + + +# FlexAttention Configs +@dataclasses.dataclass +class FlexConfig: + """ + Base Config class for flex attention + - FlexAttn forward and backward will use this. For flex decoding, + please use FlexDecodingConfig. + + NOTE: + For flex_attn bwd block_m and block_n are reused for block_m1, block_m2, block_n1, block_n2 + + """ + + block_m: int + block_n: int + num_stages: int + num_warps: int + + +@dataclasses.dataclass +class FlexBwDConfig: + """ + Base Config class for flex attention backward + - FlexAttn backward will use this. + + Note: flex bwd configs + + Kernel Constraints: + * BLOCK_N1 % BLOCK_M1 == 0 + * BLOCK_M2 % BLOCK_N2 == 0 + + Pattern 1 - Symmetric Pairing (M, N, N, M): + - Used in autotune configs + - block_m1=M, block_n1=N, block_m2=N, block_n2=M + - Only requires checking BLOCK_N % BLOCK_M == 0 + - Second constraint (BLOCK_M2 % BLOCK_N2) automatically satisfied + + Pattern 2 - Independent Parameters (M1, N1, M2, N2): + - Used in exhaustive search for maximum flexibility + - All four parameters can be set independently + - Requires checking both constraints + + """ + + block_m1: int + block_n1: int + block_m2: int + block_n2: int + num_stages: int + num_warps: int + + +@dataclasses.dataclass +class FlexDecodeConfig: + """ + Config class for flex decoding + """ + + block_n: int + num_stages: int + num_warps: int + + +# ROCm classes +@dataclasses.dataclass +class ROCmGemmConfig(GemmConfig): + """ + ROCm subclass for GEMMs, with AMD backend specific tuneable kernargs + """ + + matrix_instr_nonkdim: int = 16 + waves_per_eu: int = 0 + kpack: int = 1 + + +@dataclasses.dataclass +class ROCmConvConfig(ConvConfig): + """ + ROCm subclass for Conv, with AMD backend specific tuneable kernargs + """ + + matrix_instr_nonkdim: int = 16 + waves_per_eu: int = 0 + kpack: int = 1 + + +@dataclasses.dataclass +class ROCmFlexConfig(FlexConfig): + """ + ROCm subclass for FlexAttn, with AMD backend specific tuneable kernargs + """ + + matrix_instr_nonkdim: int = 0 + waves_per_eu: int = 0 + kpack: int = 1 + + +@dataclasses.dataclass +class ROCmFlexBwDConfig(FlexBwDConfig): + """ + ROCm subclass for FlexAttn backward, with AMD backend specific tuneable kernargs + """ + + matrix_instr_nonkdim: int = 0 + waves_per_eu: int = 0 + kpack: int = 1 + + +@dataclasses.dataclass +class ROCmFlexDecodeConfig(FlexDecodeConfig): + """ + ROCm subclass for FlexDecode, with AMD backend specific tuneable kernargs + """ + + matrix_instr_nonkdim: int = 0 + waves_per_eu: int = 0 + kpack: int = 1 + + +class BaseHeuristicSingleton(type): + """ + Thread-safe implementation of singleton to be used in the config heuristic subclasses + to ensure heavy __init__ calls are not repeatedly run + """ + + _instances: dict[type[Any], Any] = {} + _lock: Lock = Lock() + + def __call__( + cls: BaseHeuristicSingleton, *args: Any, **kwargs: Any + ) -> BaseConfigHeuristic: + with cls._lock: + if cls not in cls._instances: + instance = super().__call__() + cls._instances[cls] = instance + return cls._instances[cls] + + +class BaseConfigHeuristic(metaclass=BaseHeuristicSingleton): + """ + Base class for mm_configs, device specific triton kernels config inherit from here + """ + + def __init__(self) -> None: + # Whether the heuristic is used for int8. Use this when the heuristic is int8 exclusive + # but prefer the preprocess_mm_configs argument when it's used for both + self.has_int8_tensor: bool = False + # Whether to scale configs at all + # TODO(coconutruben): remove this once mm_plus_mm and tests support scaling + self.should_scale_configs: bool = True + # List of dictionaries to store the kernel configs. Configs that evaluate to true + # will be utilised on the target platform. The configs are as follows: + # (BLOCK_M, BLOCK_N, BLOCK_K, num_stages, num_warps) + self.mm_configs: list[BaseConfig] = [ + GemmConfig(32, 32, 16, 1, 2), + GemmConfig(32, 32, 128, 2, 4), + GemmConfig(32, 64, 32, 5, 8), + GemmConfig(64, 32, 32, 5, 8), + GemmConfig(64, 32, 128, 5, 4), + GemmConfig(64, 64, 16, 2, 4), + GemmConfig(64, 64, 32, 2, 4), + GemmConfig(64, 64, 64, 3, 8), + GemmConfig(64, 64, 128, 5, 4), + GemmConfig(64, 128, 32, 3, 4), + GemmConfig(64, 128, 32, 4, 8), + GemmConfig(64, 128, 64, 3, 4), + GemmConfig(64, 128, 128, 4, 4), + GemmConfig(128, 64, 32, 3, 4), + GemmConfig(128, 64, 32, 4, 8), + GemmConfig(128, 128, 32, 2, 8), + GemmConfig(128, 128, 32, 3, 4), + GemmConfig(128, 128, 64, 3, 4), + GemmConfig(128, 128, 64, 5, 8), + GemmConfig(128, 128, 128, 4, 8), + # 128x256x64 NS=4: larger N-tile that wins on Hopper-class matmul + GemmConfig(128, 256, 64, 4, 8), + ] + + # Exhaustive search for mm configs + self.exhaustive_configs: list[BaseConfig] = [ + GemmConfig( + BLOCK_M, BLOCK_N, BLOCK_K, num_stages, num_warps, group_m=group_m + ) + for BLOCK_M, BLOCK_N, BLOCK_K in itertools.product( + [16, 32, 64, 128, 256], repeat=3 + ) + for num_stages in [1, 2, 3, 4, 5] + for num_warps in [2, 4, 8] + for group_m in [8] + ] + + # these are only used in tuned_mm when AutoHeuristic is enabled + # the idea is that when AutoHeuristic collects data to learn a heuristic, more configs are autotuned + # when the learned heuristic is used, the learned heuristic reduces the number of configs down to 10 + # which saves compilation time (since less configs are autotuned) and potentially increase performance + # because the learned heuristic might predict a config that is not part mm_configs + self.extra_mm_configs: list[BaseConfig] = [ + GemmConfig(16, 32, 16, 3, 2), + GemmConfig(16, 32, 32, 4, 2), + GemmConfig(16, 32, 32, 5, 2), + GemmConfig(64, 64, 128, 3, 4), + GemmConfig(128, 64, 32, 2, 2), + GemmConfig(128, 64, 64, 3, 8), + GemmConfig(128, 64, 128, 4, 8), + GemmConfig(128, 128, 32, 4, 4), + GemmConfig(128, 128, 64, 3, 8), + GemmConfig(128, 128, 64, 5, 4), + ] + + self.int8_mm_configs: list[BaseConfig] = [ + GemmConfig(64, 64, 32, 2, 4), + GemmConfig(64, 128, 32, 3, 4), + GemmConfig(128, 64, 32, 3, 4), + GemmConfig(64, 128, 32, 4, 8), + GemmConfig(128, 64, 32, 4, 8), + GemmConfig(64, 32, 32, 5, 8), + GemmConfig(32, 64, 32, 5, 8), + GemmConfig(128, 128, 32, 2, 8), + GemmConfig(64, 64, 64, 3, 8), + GemmConfig(128, 256, 128, 3, 8), + GemmConfig(256, 128, 128, 3, 8), + ] + + self.mixed_mm_configs: list[BaseConfig] = [ + GemmConfig(16, 128, 256, 3, 4), + GemmConfig(16, 128, 256, 5, 8), + ] + + self.persistent_mm_configs: list[BaseConfig] = [ + GemmConfig(128, 256, 64, 3, 8), + GemmConfig(128, 128, 64, 3, 8), + GemmConfig(128, 128, 128, 3, 8), + GemmConfig(128, 128, 128, 3, 4), + GemmConfig(128, 128, 64, 4, 8), + GemmConfig(128, 128, 64, 5, 8), + GemmConfig(256, 128, 64, 4, 8), + GemmConfig(128, 128, 64, 5, 4), + ] + + self.blackwell_persistent_mm_configs: list[BaseConfig] = [ + BlackwellGPUGemmConfig( + 128, + 256, + 64, + 4, + 8, + epilogue_subtile=2, + warp_specialize=True, + flatten=True, + ), + BlackwellGPUGemmConfig( + 256, + 128, + 64, + 3, + 8, + epilogue_subtile=2, + warp_specialize=True, + flatten=True, + ), + BlackwellGPUGemmConfig( + 128, + 256, + 128, + 2, + 8, + epilogue_subtile=2, + warp_specialize=True, + flatten=True, + ), + BlackwellGPUGemmConfig( + 128, + 256, + 64, + 3, + 8, + epilogue_subtile=2, + warp_specialize=True, + flatten=True, + ), + BlackwellGPUGemmConfig( + 128, + 128, + 128, + 3, + 4, + epilogue_subtile=2, + warp_specialize=True, + flatten=True, + ), + BlackwellGPUGemmConfig( + 256, + 128, + 64, + 3, + 8, + epilogue_subtile=2, + warp_specialize=True, + flatten=True, + ), + BlackwellGPUGemmConfig( + 128, + 128, + 128, + 3, + 8, + epilogue_subtile=2, + warp_specialize=True, + flatten=True, + ), + # Include no-subtiling. Always required for testing. + BlackwellGPUGemmConfig( + 256, + 128, + 64, + 3, + 8, + epilogue_subtile=1, + warp_specialize=True, + flatten=True, + ), + BlackwellGPUGemmConfig( + 128, + 128, + 128, + 3, + 8, + epilogue_subtile=1, + warp_specialize=True, + flatten=True, + ), + # Include subtile=4. Always required for testing. + BlackwellGPUGemmConfig( + 256, + 128, + 64, + 4, + 8, + epilogue_subtile=4, + warp_specialize=True, + flatten=True, + ), + BlackwellGPUGemmConfig( + 128, + 128, + 128, + 4, + 8, + epilogue_subtile=4, + warp_specialize=True, + flatten=True, + ), + ] + + self.blackwell_persistent_addmm_configs: list[BaseConfig] = [ + # Include each subtiling factor for testing. + BlackwellGPUGemmConfig( + 256, + 128, + 64, + 2, + 4, + epilogue_subtile=2, + warp_specialize=True, + flatten=True, + ), + BlackwellGPUGemmConfig( + 256, + 128, + 64, + 2, + 4, + epilogue_subtile=1, + warp_specialize=True, + flatten=True, + ), + BlackwellGPUGemmConfig( + 256, + 128, + 64, + 2, + 4, + epilogue_subtile=4, + warp_specialize=True, + flatten=True, + ), + ] + + self.scaled_mm_configs: list[BaseConfig] = [ + GemmConfig(128, 256, 32, 3, 8), + GemmConfig(256, 128, 32, 3, 8), + GemmConfig(256, 64, 32, 4, 4), + GemmConfig(64, 256, 32, 4, 4), + GemmConfig(128, 128, 32, 4, 4), + GemmConfig(128, 64, 32, 4, 4), + GemmConfig(64, 128, 32, 4, 4), + GemmConfig(128, 32, 32, 4, 4), + GemmConfig(64, 32, 32, 5, 2), + GemmConfig(256, 128, 128, 3, 8), + GemmConfig(256, 64, 128, 4, 4), + GemmConfig(64, 256, 128, 4, 4), + GemmConfig(128, 128, 128, 4, 4), + GemmConfig(128, 64, 64, 4, 4), + GemmConfig(64, 128, 64, 4, 4), + GemmConfig(128, 32, 64, 4, 4), + GemmConfig(64, 32, 64, 5, 2), + GemmConfig(16, 32, 32, 2, 2), + GemmConfig(16, 64, 32, 2, 2), + GemmConfig(16, 128, 32, 2, 4), + GemmConfig(16, 256, 32, 2, 4), + GemmConfig(16, 32, 64, 2, 2), + GemmConfig(16, 64, 64, 2, 2), + GemmConfig(16, 128, 64, 2, 4), + GemmConfig(16, 256, 64, 2, 4), + GemmConfig(32, 32, 32, 2, 2), + GemmConfig(32, 64, 32, 2, 2), + GemmConfig(32, 128, 32, 2, 4), + GemmConfig(32, 256, 32, 2, 4), + GemmConfig(32, 32, 64, 2, 2), + GemmConfig(32, 64, 64, 2, 2), + GemmConfig(32, 128, 64, 2, 4), + GemmConfig(32, 256, 64, 2, 4), + GemmConfig(16, 32, 32, 3, 2), + GemmConfig(16, 64, 32, 3, 2), + GemmConfig(16, 128, 32, 3, 4), + GemmConfig(16, 256, 32, 3, 4), + GemmConfig(16, 32, 64, 3, 2), + GemmConfig(16, 64, 64, 3, 2), + GemmConfig(16, 128, 64, 3, 4), + GemmConfig(16, 256, 64, 3, 4), + GemmConfig(32, 32, 32, 3, 2), + GemmConfig(32, 64, 32, 3, 2), + GemmConfig(32, 128, 32, 3, 4), + GemmConfig(32, 256, 32, 3, 4), + GemmConfig(32, 32, 64, 3, 2), + GemmConfig(32, 64, 64, 3, 2), + GemmConfig(32, 128, 64, 3, 4), + GemmConfig(32, 256, 64, 3, 4), + GemmConfig(16, 32, 32, 4, 2), + GemmConfig(16, 64, 32, 4, 2), + GemmConfig(16, 128, 32, 4, 4), + GemmConfig(16, 256, 32, 4, 4), + GemmConfig(16, 32, 64, 4, 2), + GemmConfig(16, 64, 64, 4, 2), + GemmConfig(16, 128, 64, 4, 4), + GemmConfig(16, 256, 64, 4, 4), + GemmConfig(32, 32, 32, 4, 2), + GemmConfig(32, 64, 32, 4, 2), + GemmConfig(32, 128, 32, 4, 4), + GemmConfig(32, 256, 32, 4, 4), + GemmConfig(32, 32, 64, 4, 2), + GemmConfig(32, 64, 64, 4, 2), + GemmConfig(32, 128, 64, 4, 4), + GemmConfig(32, 256, 64, 4, 4), + GemmConfig(16, 32, 32, 5, 2), + GemmConfig(16, 64, 32, 5, 2), + GemmConfig(16, 128, 32, 5, 4), + GemmConfig(16, 256, 32, 5, 4), + GemmConfig(16, 32, 64, 5, 2), + GemmConfig(16, 64, 64, 5, 2), + GemmConfig(16, 128, 64, 5, 4), + GemmConfig(16, 256, 64, 5, 4), + GemmConfig(32, 32, 32, 5, 2), + GemmConfig(32, 64, 32, 5, 2), + GemmConfig(32, 128, 32, 5, 4), + GemmConfig(32, 256, 32, 5, 4), + GemmConfig(32, 32, 64, 5, 2), + GemmConfig(32, 64, 64, 5, 2), + GemmConfig(32, 128, 64, 5, 4), + GemmConfig(32, 256, 64, 5, 4), + GemmConfig(16, 32, 32, 6, 2), + GemmConfig(16, 64, 32, 6, 2), + GemmConfig(16, 128, 32, 6, 4), + GemmConfig(16, 256, 32, 6, 4), + GemmConfig(16, 32, 64, 6, 2), + GemmConfig(16, 64, 64, 6, 2), + GemmConfig(16, 128, 64, 6, 4), + GemmConfig(16, 256, 64, 6, 4), + GemmConfig(32, 32, 32, 6, 2), + GemmConfig(32, 64, 32, 6, 2), + GemmConfig(32, 128, 32, 6, 4), + GemmConfig(32, 256, 32, 6, 4), + GemmConfig(32, 32, 64, 6, 2), + GemmConfig(32, 64, 64, 6, 2), + GemmConfig(32, 128, 64, 6, 4), + GemmConfig(32, 256, 64, 6, 4), + GemmConfig(64, 16, 256, 5, 4), + GemmConfig(64, 32, 256, 5, 4), + GemmConfig(64, 128, 128, 2, 4), + GemmConfig(64, 128, 128, 3, 4), + GemmConfig(128, 128, 128, 2, 4), + GemmConfig(128, 256, 128, 4, 8), + GemmConfig(256, 128, 128, 2, 4), + GemmConfig(256, 128, 128, 2, 8), + ] + + self.scaled_persistent_mm_configs: list[BaseConfig] = [ + GemmConfig(128, 128, 64, 3, 8), + GemmConfig(128, 128, 128, 3, 8), + GemmConfig(128, 128, 128, 4, 8), + GemmConfig(128, 128, 128, 4, 4), + GemmConfig(128, 128, 128, 3, 4), + GemmConfig(128, 128, 128, 5, 4), + GemmConfig(128, 128, 128, 5, 8), + GemmConfig(128, 128, 128, 6, 8), + GemmConfig(128, 128, 64, 4, 8), + GemmConfig(64, 32, 256, 5, 4), + GemmConfig(128, 256, 128, 3, 8), + GemmConfig(64, 128, 256, 4, 4), + GemmConfig(64, 256, 128, 4, 4), + ] + + self.blackwell_scaled_persistent_mm_configs: list[BaseConfig] = [ + BlackwellGPUGemmConfig( + block_m=c.block_m, + block_n=c.block_n, + block_k=c.block_k, + num_stages=c.num_stages, + num_warps=c.num_warps, + hint_override=c.hint_override, + group_m=8, + epilogue_subtile=2, + warp_specialize=True, + flatten=True, + ) + for c in self.scaled_persistent_mm_configs + ] + + # TODO: Unify with other gemm patterns, mm_plus_mm currently follows + # slightly different pattern than rest + self.mm_plus_mm_configs: list[BaseConfig] = [ + GemmConfig(64, 64, 32, 2, 4), + GemmConfig(64, 64, 32, 3, 8), + GemmConfig(64, 64, 32, 4, 16), + GemmConfig(64, 32, 32, 4, 8), + GemmConfig(32, 64, 32, 4, 8), + GemmConfig(128, 128, 32, 1, 8), + GemmConfig(64, 64, 64, 1, 8), + GemmConfig(32, 32, 128, 1, 8), + GemmConfig(64, 64, 16, 2, 4), + GemmConfig(32, 32, 16, 1, 2), + ] + + self.conv_configs: list[BaseConfig] = [ + # BLOCK_K=16 configs + ConvConfig(64, 256, 16, 2, 4), + ConvConfig(256, 64, 16, 2, 4), + ConvConfig(1024, 16, 16, 1, 8), + # BLOCK_K=32 configs + ConvConfig(128, 128, 32, 2, 8), + ConvConfig(64, 64, 32, 2, 4), + ConvConfig(64, 256, 32, 2, 8), + ConvConfig(256, 64, 32, 2, 8), + # BLOCK_K=64 configs + ConvConfig(128, 128, 64, 3, 8), + ConvConfig(64, 128, 64, 4, 4), + ConvConfig(128, 64, 64, 4, 4), + ConvConfig(256, 128, 64, 2, 8), + ConvConfig(128, 256, 64, 2, 8), + # BLOCK_K=128 configs - optimal when IN_C=128 (single iteration over channels) + ConvConfig(128, 128, 128, 2, 8), + ConvConfig(128, 128, 128, 3, 8), + ConvConfig(64, 128, 128, 4, 4), + ConvConfig(256, 128, 128, 2, 8), + ConvConfig(128, 256, 128, 2, 8), + ] + + # Depthwise conv1d configs: BLOCK_N x BLOCK_L x BLOCK_C tiling + # Derived from autotuning results on H100 for depthwise conv1d + # channels-last (NLC) layout with shape x=[3072, 128, 202] + # Matches _nlc_autotune_configs from depthwise_conv1d_benchmark.py + self.depthwise_conv_configs: list[DepthwiseConvConfig] = [ + # BLOCK_C=32, BLOCK_L=32 + DepthwiseConvConfig( + block_n=16, block_l=32, block_c=32, num_stages=4, num_warps=8 + ), + DepthwiseConvConfig( + block_n=16, block_l=32, block_c=32, num_stages=4, num_warps=4 + ), + DepthwiseConvConfig( + block_n=32, block_l=32, block_c=32, num_stages=5, num_warps=8 + ), + DepthwiseConvConfig( + block_n=32, block_l=32, block_c=32, num_stages=4, num_warps=4 + ), + # BLOCK_C=32, BLOCK_L=64 + DepthwiseConvConfig( + block_n=16, block_l=64, block_c=32, num_stages=4, num_warps=8 + ), + DepthwiseConvConfig( + block_n=16, block_l=64, block_c=32, num_stages=4, num_warps=4 + ), + DepthwiseConvConfig( + block_n=32, block_l=64, block_c=32, num_stages=3, num_warps=8 + ), + # BLOCK_C=32, BLOCK_L=256 + DepthwiseConvConfig( + block_n=16, block_l=256, block_c=32, num_stages=5, num_warps=8 + ), + DepthwiseConvConfig( + block_n=16, block_l=256, block_c=32, num_stages=4, num_warps=4 + ), + DepthwiseConvConfig( + block_n=32, block_l=256, block_c=32, num_stages=3, num_warps=8 + ), + # BLOCK_C=64 + DepthwiseConvConfig( + block_n=16, block_l=32, block_c=64, num_stages=4, num_warps=8 + ), + DepthwiseConvConfig( + block_n=16, block_l=32, block_c=64, num_stages=4, num_warps=4 + ), + DepthwiseConvConfig( + block_n=16, block_l=64, block_c=64, num_stages=3, num_warps=8 + ), + # BLOCK_C=128 + DepthwiseConvConfig( + block_n=16, block_l=32, block_c=128, num_stages=3, num_warps=8 + ), + DepthwiseConvConfig( + block_n=16, block_l=32, block_c=128, num_stages=3, num_warps=4 + ), + ] + + self.flex_attn_fwd_autotune_configs: list[FlexConfig] = [ + FlexConfig(128, 64, 3, 4), + FlexConfig(128, 128, 3, 4), + FlexConfig(128, 128, 2, 8), + FlexConfig(128, 128, 1, 8), + FlexConfig(64, 128, 3, 4), + FlexConfig(64, 64, 3, 4), + ] + + self.flex_attn_bwd_autotune_configs: list[FlexBwDConfig] = [ + # See Note: flex bwd configs + FlexBwDConfig(BLOCK_M, BLOCK_N, BLOCK_N, BLOCK_M, s, w) + for BLOCK_M in [32, 64] + for BLOCK_N in [32, 64, 128] + for s in [1, 3, 4, 5] # num_stages + for w in ([4, 8] if BLOCK_M >= 128 or BLOCK_N >= 128 else [4]) + if BLOCK_N % BLOCK_M == 0 + ] + + self.flex_decode_autotune_configs: list[FlexDecodeConfig] = [ + FlexDecodeConfig(64, 3, 2), + FlexDecodeConfig(32, 3, 2), + FlexDecodeConfig(128, 3, 2), + ] + + self.exhaustive_flex_attn_fwd_configs: list[FlexConfig] = [ + FlexConfig(BLOCK_M, BLOCK_N, num_stages, num_warps) + for BLOCK_M in [16, 32, 64, 128] + for BLOCK_N in [32, 64, 128] + for num_stages in [1, 3, 4, 5] + for num_warps in [2, 4, 8] + ] + + self.exhaustive_flex_attn_bwd_configs: list[FlexBwDConfig] = [ + # See Note: flex bwd configs + FlexBwDConfig(BLOCK_M1, BLOCK_N1, BLOCK_M2, BLOCK_N2, num_stages, num_warps) + for BLOCK_M1 in [16, 32, 64, 128] + for BLOCK_N1 in [16, 32, 64, 128] + for BLOCK_M2 in [16, 32, 64, 128] + for BLOCK_N2 in [16, 32, 64, 128] + for num_stages in [1, 3, 4] + for num_warps in [2, 4, 8] + if BLOCK_N1 % BLOCK_M1 == 0 + and BLOCK_M2 % BLOCK_N2 == 0 # kernel static assertions + ] + + self.exhaustive_flex_decode_configs: list[FlexDecodeConfig] = [ + FlexDecodeConfig(block_n, num_stages, num_warps) + for block_n in [16, 32, 64, 128] + for num_stages in [1, 3, 4, 5] + for num_warps in [2, 4, 8] + ] + + def _get_extra_config_key_and_kwargs( + self, conf: BaseConfig + ) -> tuple[tuple[int | None, ...], dict[str, Any]]: + """Hook for subclasses to extend config dedup key and kwargs.""" + return (), {} + + def _finalize_mm_configs( + self, + configs: list[BaseConfig], + ) -> Generator[TritonConfig, None, None]: + """ + Finalizes configs after scaling, applying additional constraints. + """ + used: OrderedSet[tuple[int | None, ...]] = OrderedSet() + + max_mm_configs = config.test_configs.max_mm_configs + + for conf in configs: + # Each warp computes a 16x16 tile = 256 elements + num_warps = min(conf.num_warps, conf.block_m * conf.block_n // 256) + + # Construct key for finding duplicate configs + key: tuple[int | None, ...] = ( + conf.block_m, + conf.block_n, + conf.block_k, + conf.num_stages, + conf.hint_override, + num_warps, + ) + + # Check if gemm specific arg exists - add to key if does + group_m = getattr(conf, "group_m", None) + if group_m is not None: + key += (group_m,) + + # Add BlackwellGPUGemmConfig specific fields to key if present + if isinstance(conf, BlackwellGPUGemmConfig): + key += ( + conf.epilogue_subtile, + conf.warp_specialize, + conf.flatten, + conf.use_meta_ws, + conf.data_partition_factor, + conf.separate_epilogue_store, + ) + + extra_key, extra_kwargs = self._get_extra_config_key_and_kwargs(conf) + key += extra_key + + if key not in used and ( + max_mm_configs is None or len(used) < max_mm_configs + ): + used.add(key) + kwargs: dict[str, Any] = { + "BLOCK_M": conf.block_m, + "BLOCK_N": conf.block_n, + "BLOCK_K": conf.block_k, + "hint_override": conf.hint_override, + } + if group_m is not None: + kwargs["GROUP_M"] = group_m + + # Add BlackwellGPUGemmConfig specific fields if present + if isinstance(conf, BlackwellGPUGemmConfig): + kwargs["EPILOGUE_SUBTILE"] = conf.epilogue_subtile + kwargs["WARP_SPECIALIZE"] = conf.warp_specialize + kwargs["FLATTEN"] = conf.flatten + kwargs["USE_META_WS"] = conf.use_meta_ws + kwargs["DATA_PARTITION_FACTOR"] = conf.data_partition_factor + kwargs["SEPARATE_EPILOGUE_STORE"] = conf.separate_epilogue_store + + kwargs.update(extra_kwargs) + + yield self.triton_config(conf.num_stages, num_warps, **kwargs) + + def _scale_mm_configs( + self, + m: int, + n: int, + k: int, + configs: list[BaseConfig], + scale: float, + has_int8_tensor: bool, + exclude: Callable[[sympy.Integer, sympy.Integer, sympy.Integer], bool], + hint_override: int | None = None, + ) -> list[BaseConfig]: + """ + Scales and filters matrix multiplication configs based on input size. + """ + if not self.should_scale_configs: + return configs + from ...runtime.runtime_utils import next_power_of_2 + + min_block_size = 16 + min_block_size_k = 32 if (has_int8_tensor or self.has_int8_tensor) else 16 + + scaled_configs = [] + for hint_override in [None] + config.multi_kernel_hints: + m_hint = max( + next_power_of_2( + V.graph.sizevars.optimization_hint_with_override( + m, + hint_override=hint_override, + ) + ), + min_block_size, + ) + n_hint = max( + next_power_of_2( + V.graph.sizevars.optimization_hint_with_override( + n, + hint_override=hint_override, + ) + ), + min_block_size, + ) + k_hint = max( + next_power_of_2( + V.graph.sizevars.optimization_hint_with_override( + k, + hint_override=hint_override, + ) + ), + min_block_size_k, + ) + + for c in configs: + block_m = max(min(int(c.block_m * scale), m_hint), min_block_size) + block_n = max(min(int(c.block_n * scale), n_hint), min_block_size) + block_k = max(min(int(c.block_k * scale), k_hint), min_block_size_k) + if not exclude(block_m, block_n, block_k): + # This copy is expensive, so avoid it if we can. + if (block_m, block_n, block_k, hint_override) != ( + c.block_m, + c.block_n, + c.block_k, + c.hint_override, + ): + c = dataclasses.replace( + c, + block_m=block_m, + block_n=block_n, + block_k=block_k, + hint_override=hint_override, + ) + + scaled_configs.append(c) + + return scaled_configs + + # Estimate theoretical maximum shared memory + def get_shared_memory_estimation( + self, + gemm_config: BaseConfig, + dtype_size: int, + has_sm_layout_conversion: bool, + layout_conversion_byte_size: int, + ): + shared_mem_loads = dtype_size * ( + gemm_config.block_m * gemm_config.block_k + + gemm_config.block_n * gemm_config.block_k + ) + + # Extra bytes to account for barriers in boundary conditions + extra_bytes = 128 + + # In persistent tma case, the layout conversion from mma -> blocked layout + # is not free and takes additional shared memory, while next loads are prefetched + # For addmm, the conversion is in the acc dtype, as it is needed before the bias addition + # For mm, the conversion is in the output dtype, as it happens before the store + if has_sm_layout_conversion: + element_bits = layout_conversion_byte_size * 8 + # 8 bytes of padding for fp16/bf16 + max_padding = 128 // element_bits + block_n = max_padding + gemm_config.block_n + shared_mem_epilogue = ( + layout_conversion_byte_size * gemm_config.block_m * block_n + ) + else: + shared_mem_epilogue = 0 + + return ( + shared_mem_loads * gemm_config.num_stages + + shared_mem_epilogue + + extra_bytes + ) + + def _get_exceeding_shared_memory_checker( + self, + has_sm_layout_conversion: bool, + layout_conversion_byte_size: int, + ) -> Callable[[BaseConfig, int], bool] | None: + """ + Returns a function that checks whether a given configuration exceeds the available shared memory for the device. + based on the config's theoretical maximum shared memory used. + If the device does not report available shared memory, returns None. + """ + + try: + if torch.cuda.is_available(): + device = torch.cuda.current_device() + props = torch.cuda.get_device_properties(device) + if hasattr(props, "shared_memory_per_block_optin"): # for NVidia GPUs + sm_available = int(props.shared_memory_per_block_optin) + elif hasattr(props, "shared_memory_per_block"): # for ROCm + sm_available = int(props.shared_memory_per_block) + else: + return None + elif torch.xpu.is_available(): + props = torch.xpu.get_device_properties() + sm_available = int(props.local_mem_size) + else: + return None + except Exception: + # If device properties cannot be queried, return None + return None + + # TODO make a BaseDeviceConfigHeuristics to handle different device configuration in its own implementation. + def exceeds(gemm_config: BaseConfig, dtype_size: int) -> bool: + estimation = self.get_shared_memory_estimation( + gemm_config, + dtype_size, + has_sm_layout_conversion, + layout_conversion_byte_size, + ) + return estimation > sm_available + + return exceeds + + def _prune_exceeding_max_shared_mem_configs( + self, + configs: list[BaseConfig], + dtype_size: int, + has_sm_layout_conversion: bool = False, + layout_conversion_byte_size: int = 0, + ) -> list[BaseConfig]: + if dtype_size <= 0: + return configs + + is_exceeding_shared_memory = self._get_exceeding_shared_memory_checker( + has_sm_layout_conversion, layout_conversion_byte_size + ) + if is_exceeding_shared_memory is None: + return configs + + return [c for c in configs if not is_exceeding_shared_memory(c, dtype_size)] + + def _prune_reg_spill_configs( + self, + configs: list[BaseConfig], + ) -> list[BaseConfig]: + try: + device = torch.cuda.current_device() + props = torch.cuda.get_device_properties(device) + warp_size = props.warp_size + except (RuntimeError, AttributeError, AssertionError): + return configs + + pruned_configs = [] + # NVIDIA-oriented approximation for the per-thread register limit. + # TODO: generalize this threshold for ROCm devices. + NUM_REG = 255 + for gemm_config in configs: + acc_regs = math.ceil( + gemm_config.block_m + * gemm_config.block_n + / (gemm_config.num_warps * warp_size) + ) + # Lower bound for register spillage, if exceeds the kernel will certainly spill + if acc_regs > NUM_REG: + continue + + pruned_configs.append(gemm_config) + + return pruned_configs + + def _filter_configs(self, configs: list[BaseConfig]) -> list[BaseConfig]: + """ + Filter configs based on specific requirements. + Subclasses can override this to implement custom filtering logic. + """ + return configs + + def preprocess_mm_configs( + self, + m: int, + n: int, + k: int, + configs: list[BaseConfig], + has_int8_tensor: bool = False, + scale: float = 1.0, + exclude: Callable[ + [sympy.Integer, sympy.Integer, sympy.Integer], bool + ] = lambda m, n, k: False, + dtype_size: int = 0, + op_name: str = "mm", # For preprocessing overrides e.g. on CPU + **kwargs, + ) -> Generator[TritonConfig, None, None]: + configs = self._filter_configs(configs) + scaled_configs = self._scale_mm_configs( + m, n, k, configs, scale, has_int8_tensor, exclude + ) + + # Filter out configs that require more shared memory than is available. + # Theoretical upper bound, will over-prune configs. Off by default for maximum + # performance + if config.max_autotune_prune_choices_based_on_shared_mem: + scaled_configs = self._prune_exceeding_max_shared_mem_configs( + scaled_configs, + dtype_size, + kwargs.get("has_sm_layout_conversion", False), + kwargs.get("layout_conversion_byte_size", 0), + ) + + if config.max_autotune_gemm_search_space == "EXHAUSTIVE": + scaled_configs = self._prune_reg_spill_configs(scaled_configs) + return self._finalize_mm_configs(scaled_configs) + + def triton_config( + self, num_stages: int, num_warps: int, **kwargs: Any + ) -> TritonConfig: + return TritonConfig(kwargs, num_stages=num_stages, num_warps=num_warps) + + def get_mm_configs(self) -> partial[Generator[TritonConfig, None, None]]: + return partial(self.preprocess_mm_configs, configs=self.mm_configs) + + def get_exhaustive_mm_configs(self) -> partial[Generator[TritonConfig, None, None]]: + """Get exhaustive MM configs for origami optimization. + + Note: When these configs are used with origami (on ROCm with + _origami_enabled()=True and max_autotune_gemm_search_space="DEFAULT"), + origami will filter them to the top-K configurations. Origami currently + only supports Triton backend, so only Triton-compatible configs will be + used. ATEN backend is excluded from origami search space. + """ + return partial(self.preprocess_mm_configs, configs=self.exhaustive_configs) + + def get_conv_configs(self) -> partial[Generator[TritonConfig, None, None]]: + return partial( + self.preprocess_mm_configs, configs=self.conv_configs, op_name="conv" + ) + + def get_depthwise_conv_configs(self) -> list[TritonConfig]: + """Return TritonConfig list for depthwise conv1d autotuning.""" + return [ + TritonConfig( + { + "BLOCK_N": cfg.block_n, + "BLOCK_L": cfg.block_l, + "BLOCK_C": cfg.block_c, + }, + num_stages=cfg.num_stages, + num_warps=cfg.num_warps, + ) + for cfg in self.depthwise_conv_configs + ] + + # Flex attn helpers + def get_flex_attn_fwd_configs( + self, head_dim: int, seq_len: sympy.Expr, dtype: Any + ) -> list[FlexConfig]: + flex_attn_fwd_configs: list[FlexConfig] = [] + + if config.max_autotune: + if config.max_autotune_flex_search_space == "EXHAUSTIVE": + return self.exhaustive_flex_attn_fwd_configs + flex_attn_fwd_configs += self.flex_attn_fwd_autotune_configs + + if head_dim <= 256: + if dtype == torch.float32: + default_config = FlexConfig(64, 64, 3, 4) + else: + default_config = FlexConfig(128, 64, 3, 4) + else: + if dtype == torch.float32: + default_config = FlexConfig(32, 16, 3, 4) + else: + default_config = FlexConfig(64, 32, 3, 4) + + if default_config not in flex_attn_fwd_configs: + flex_attn_fwd_configs.append(default_config) + + return flex_attn_fwd_configs + + def get_flex_attn_bwd_configs( + self, head_dim: int, dtype: Any + ) -> list[FlexBwDConfig]: + flex_attn_bwd_configs: list[FlexBwDConfig] = [] + + if config.max_autotune: + if config.max_autotune_flex_search_space == "EXHAUSTIVE": + return self.exhaustive_flex_attn_bwd_configs + flex_attn_bwd_configs += self.flex_attn_bwd_autotune_configs + + default_config = FlexBwDConfig(16, 16, 16, 16, 1, 4) + + if default_config not in flex_attn_bwd_configs: + flex_attn_bwd_configs.append(default_config) + + return flex_attn_bwd_configs + + def get_flex_decode_configs( + self, head_dim: int, dtype: Any + ) -> list[FlexDecodeConfig]: + flex_decode_configs: list[FlexDecodeConfig] = [] + + if config.max_autotune: + if config.max_autotune_flex_search_space == "EXHAUSTIVE": + return self.exhaustive_flex_decode_configs + flex_decode_configs += self.flex_decode_autotune_configs + + default_config = FlexDecodeConfig(block_n=64, num_stages=1, num_warps=2) + + if default_config not in flex_decode_configs: + flex_decode_configs.append(default_config) + + return flex_decode_configs + + +class CPUConfigHeuristic(BaseConfigHeuristic): + """ + CPU-specific config heuristic with CPU-specific optimizations. + """ + + def _get_cpu_exclude_function( + self, method: str = "bmm" + ) -> Callable[[sympy.Integer, sympy.Integer, sympy.Integer], bool]: + """ + Get CPU-specific exclude function based on method type. + Returns a function that can be used as exclude condition. + Moved from mm_common._is_large_block_for_cpu and refactored to return a function. + """ + if method in ("conv"): + + def exclude_conv( + m: sympy.Integer, n: sympy.Integer, k: sympy.Integer + ) -> bool: + # Thresholds are experimentally determined to reduce Triton CPU compile times + if m > 256 or n > 256 or k > 256: + return True + return m * n * k > 2**17 + + return exclude_conv + elif method in ("mm", "addmm", "int_mm"): + + def exclude_mm( + m: sympy.Integer, n: sympy.Integer, k: sympy.Integer + ) -> bool: + return m * n > 2**13 + + return exclude_mm + else: # Default to bmm implementation for unknown methods + + def exclude_bmm( + m: sympy.Integer, n: sympy.Integer, k: sympy.Integer + ) -> bool: + if m > 128 or n > 128 or k > 128: + return True + return m * n > 2**12 + + return exclude_bmm + + def preprocess_mm_configs( + self, + m: int, + n: int, + k: int, + configs: list[BaseConfig], + has_int8_tensor: bool = False, + scale: float = 1.0, + exclude: Callable[ + [sympy.Integer, sympy.Integer, sympy.Integer], bool + ] = lambda m, n, k: False, + dtype_size: int = 0, + op_name: str = "mm", # For preprocessing overrides e.g. on CPU + **kwargs, + ) -> Generator[TritonConfig, None, None]: + """ + CPU-specific preprocessing that applies CPU-specific scaling (0.5) and exclusion logic. + """ + # Get CPU-specific exclude function based on operation type + cpu_exclude_fn = self._get_cpu_exclude_function(op_name) + + # Apply CPU-specific scaling (0.5) and exclusion logic + return super().preprocess_mm_configs( + m, + n, + k, + configs=configs, + has_int8_tensor=has_int8_tensor, + scale=0.5, + exclude=cpu_exclude_fn, + dtype_size=dtype_size, + op_name=op_name, + **kwargs, + ) + + +class CUDAConfigHeuristic(BaseConfigHeuristic): + """ + Child class for CUDA device specific gemm/flex attention/conv/ configs. + """ + + def __init__(self) -> None: + super().__init__() + self.sm_120_default_flex_config = { + (torch.float32, 64): FlexConfig(128, 32, 2, 4), + (torch.float32, 128): FlexConfig(128, 32, 2, 4), + (torch.float32, 256): FlexConfig(64, 16, 2, 4), + (torch.bfloat16, 64): FlexConfig(128, 64, 2, 4), + (torch.bfloat16, 128): FlexConfig(128, 64, 2, 8), + (torch.bfloat16, 256): FlexConfig(32, 64, 2, 4), + (torch.float16, 64): FlexConfig(128, 64, 2, 4), + (torch.float16, 128): FlexConfig(128, 64, 2, 8), + (torch.float16, 256): FlexConfig(32, 64, 2, 4), + } + + self.sm_100_default_flex_config = { + (torch.float32, 64): FlexConfig(128, 32, 3, 4), + (torch.float32, 128): FlexConfig(32, 64, 3, 4), + (torch.float32, 192): FlexConfig(32, 64, 2, 4), + (torch.float32, 256): FlexConfig(32, 32, 3, 4), + (torch.bfloat16, 64): FlexConfig(128, 64, 3, 4), + (torch.bfloat16, 128): FlexConfig(128, 128, 2, 8), + (torch.bfloat16, 192): FlexConfig(128, 128, 1, 8), + (torch.bfloat16, 256): FlexConfig(64, 32, 3, 4), + (torch.float16, 64): FlexConfig(128, 64, 3, 4), + (torch.float16, 128): FlexConfig(128, 128, 2, 8), + (torch.float16, 192): FlexConfig(128, 128, 1, 8), + (torch.float16, 256): FlexConfig(64, 32, 3, 4), + } + + self.h100_default_flex_config = { + (torch.float32, 64): FlexConfig(128, 32, 3, 4), + (torch.float32, 128): FlexConfig(32, 64, 3, 4), + (torch.float32, 192): FlexConfig(32, 64, 1, 8), + (torch.float32, 256): FlexConfig(32, 32, 3, 4), + (torch.bfloat16, 64): FlexConfig(128, 128, 3, 4), + (torch.bfloat16, 128): FlexConfig(128, 64, 3, 8), + (torch.bfloat16, 256): FlexConfig(64, 32, 3, 4), + (torch.float16, 64): FlexConfig(128, 128, 3, 4), + (torch.float16, 128): FlexConfig(128, 64, 3, 8), + (torch.float16, 256): FlexConfig(64, 32, 3, 4), + } + + self.a100_default_flex_config = { + (torch.float32, 64): FlexConfig(128, 32, 3, 4), + (torch.float32, 128): FlexConfig(128, 32, 3, 4), + (torch.float32, 256): FlexConfig(64, 16, 3, 4), + (torch.bfloat16, 64): FlexConfig(128, 64, 3, 4), + (torch.bfloat16, 128): FlexConfig(128, 64, 3, 8), + (torch.bfloat16, 192): FlexConfig(128, 32, 2, 8), + (torch.bfloat16, 256): FlexConfig(32, 64, 3, 4), + (torch.float16, 64): FlexConfig(128, 64, 3, 4), + (torch.float16, 128): FlexConfig(128, 64, 3, 8), + (torch.float16, 192): FlexConfig(128, 32, 2, 8), + (torch.float16, 256): FlexConfig(32, 64, 3, 4), + } + + # Overwriting the configs omitting BLOCK_N of size 128 that cause ULFs + self.flex_attn_bwd_autotune_configs: list[FlexBwDConfig] = [ + # See Note: flex bwd configs + FlexBwDConfig(BLOCK_M, BLOCK_N, BLOCK_N, BLOCK_M, s, 4) + for BLOCK_M in [32, 64] + for BLOCK_N in [32, 64] + for s in [1, 3, 4, 5] # num_stages + if BLOCK_N % BLOCK_M == 0 + ] + + def get_flex_attn_fwd_configs( + self, head_dim: int, seq_len: sympy.Expr, dtype: Any + ) -> list[FlexConfig]: + capability = torch.cuda.get_device_capability() + flex_attn_fwd_configs: list[FlexConfig] = [] + + if config.max_autotune: + if config.max_autotune_flex_search_space == "EXHAUSTIVE": + return self.exhaustive_flex_attn_fwd_configs + flex_attn_fwd_configs += self.flex_attn_fwd_autotune_configs + + if head_dim <= 256: + if dtype == torch.float32: + default_config = FlexConfig(64, 64, 3, 4) + else: + default_config = FlexConfig(64, 64, 3, 4) + # here we are using sm_120_default_flex_config on THOR as well + if capability >= (11, 0): + default_config = self.sm_120_default_flex_config.get( + (dtype, head_dim), default_config + ) + elif capability >= (10, 0): + default_config = self.sm_100_default_flex_config.get( + (dtype, head_dim), default_config + ) + elif capability == (9, 0): + default_config = self.h100_default_flex_config.get( + (dtype, head_dim), default_config + ) + elif capability >= (8, 0): + default_config = self.a100_default_flex_config.get( + (dtype, head_dim), default_config + ) + else: + if dtype == torch.float32: + default_config = FlexConfig(32, 16, 3, 4) + else: + default_config = FlexConfig(64, 32, 3, 4) + + if default_config not in flex_attn_fwd_configs: + flex_attn_fwd_configs.append(default_config) + + return flex_attn_fwd_configs + + def get_flex_attn_bwd_configs( + self, head_dim: int, dtype: Any + ) -> list[FlexBwDConfig]: + capability = torch.cuda.get_device_capability() + flex_attn_bwd_configs: list[FlexBwDConfig] = [] + if config.max_autotune: + if config.max_autotune_flex_search_space == "EXHAUSTIVE": + return self.exhaustive_flex_attn_bwd_configs + flex_attn_bwd_configs += self.flex_attn_bwd_autotune_configs + + major, minor = capability + if dtype == torch.float32: + capability_class = "float32" + elif major == 12: + capability_class = "sm12x" + elif major == 11: + capability_class = "sm11x" + elif major >= 10: + capability_class = "sm10x" + elif capability == (9, 0): + capability_class = "sm90" + elif major >= 8: + capability_class = "sm8x" + else: + capability_class = "baseline" + + # fmt: off + config_map = { + "float32": lambda h: FlexBwDConfig(16, 16, 16, 16, 1, 4), + "baseline": lambda h: FlexBwDConfig(16, 16, 16, 16, 1, 4), + "sm90": lambda h: ( + FlexBwDConfig(64, 64, 64, 64, 3, 4) if h < 64 else + FlexBwDConfig(64, 128, 128, 64, 3, 8) if h <= 128 else + FlexBwDConfig(64, 64, 64, 64, 2, 4) + ), + "sm10x": lambda h: ( + FlexBwDConfig(32, 64, 64, 32, 3, 4) if h <= 64 else + FlexBwDConfig(64, 128, 128, 64, 3, 4) if h <= 128 else + FlexBwDConfig(64, 64, 64, 64, 1, 8) if h <= 192 else + FlexBwDConfig(64, 64, 64, 64, 1, 4) + ), + "sm8x": lambda h: ( + FlexBwDConfig(32, 128, 128, 32, 3, 4) + if h < 64 + else FlexBwDConfig( + 64, 64, 64, 64, 3 if minor == 6 and h == 128 else 2, 4 + ) + ), + "sm11x": lambda h: ( + FlexBwDConfig(32, 128, 128, 32, 3, 4) + if h < 64 + else FlexBwDConfig( + 64, 64, 64, 64, 1 if h >= 128 else 2, 4 + ) + ), + "sm12x": lambda h: ( + FlexBwDConfig(32, 128, 128, 32, 3, 4) + if h < 64 + else FlexBwDConfig( + 64, 64, 64, 64, 1 if h >= 128 else 2, 4 + ) + ), + } + # fmt: on + + if head_dim <= 256: + default_config = config_map[capability_class](head_dim) + else: + default_config = FlexBwDConfig(16, 16, 16, 16, 1, 4) + + if default_config not in flex_attn_bwd_configs: + flex_attn_bwd_configs.append(default_config) + + return flex_attn_bwd_configs + + def get_flex_decode_configs( + self, head_dim: int, dtype: Any + ) -> list[FlexDecodeConfig]: + capability = torch.cuda.get_device_capability() + + default_config = FlexDecodeConfig(64, 1, 2) + + flex_decode_configs: list[FlexDecodeConfig] = [] + + if config.max_autotune: + if config.max_autotune_flex_search_space == "EXHAUSTIVE": + return self.exhaustive_flex_decode_configs + flex_decode_configs += self.flex_decode_autotune_configs + + if capability in [(9, 0), (10, 0), (10, 3)]: # sm_90, sm_100, sm_103 + if head_dim > 128 and dtype == torch.float32: + default_config = FlexDecodeConfig(64, 1, 2) + else: + default_config = FlexDecodeConfig(64, 3, 2) + if capability == (11, 0): + default_config = FlexDecodeConfig(16, 1, 2) + else: + default_config = FlexDecodeConfig(64, 1, 2) + + if default_config not in flex_decode_configs: + flex_decode_configs.append(default_config) + + return flex_decode_configs + + +class ROCmConfigHeuristic(BaseConfigHeuristic): + """ + Child class for ROCm specific gemm/flex attention/conv/ configs. + """ + + def __init__(self) -> None: + super().__init__() + + self.default_num_stages = get_backend_num_stages() + + self.mm_configs: list[BaseConfig] = [ + ROCmGemmConfig( + 16, 16, 256, self.default_num_stages, 4, group_m=4, waves_per_eu=2 + ), + ROCmGemmConfig(32, 16, 256, self.default_num_stages, 4, group_m=4), + ROCmGemmConfig( + 32, 32, 16, self.default_num_stages, 4, group_m=8, waves_per_eu=2 + ), + ROCmGemmConfig(32, 32, 128, self.default_num_stages, 4, group_m=8), + ROCmGemmConfig(32, 64, 64, self.default_num_stages, 4, group_m=8), + ROCmGemmConfig( + 64, 16, 128, self.default_num_stages, 4, group_m=8, waves_per_eu=2 + ), + ROCmGemmConfig(64, 32, 32, self.default_num_stages, 4, group_m=8), + ROCmGemmConfig(64, 32, 64, self.default_num_stages, 4, group_m=8), + ROCmGemmConfig(64, 32, 64, self.default_num_stages, 8, group_m=8), + ROCmGemmConfig(64, 32, 128, self.default_num_stages, 4, group_m=8), + ROCmGemmConfig(64, 64, 16, self.default_num_stages, 4, group_m=8), + ROCmGemmConfig(64, 64, 64, self.default_num_stages, 4, group_m=4), + ROCmGemmConfig(64, 64, 128, self.default_num_stages, 8, group_m=16), + ROCmGemmConfig(64, 64, 256, self.default_num_stages, 8, group_m=4), + ROCmGemmConfig( + 64, 128, 32, self.default_num_stages, 4, group_m=4, waves_per_eu=2 + ), + ROCmGemmConfig(64, 128, 32, self.default_num_stages, 8, group_m=8), + ROCmGemmConfig(64, 128, 64, self.default_num_stages, 8, group_m=4), + ROCmGemmConfig(64, 128, 128, self.default_num_stages, 8, group_m=4), + ROCmGemmConfig(128, 32, 32, self.default_num_stages, 4, group_m=8), + ROCmGemmConfig(128, 32, 64, self.default_num_stages, 4, group_m=8), + ROCmGemmConfig( + 128, 64, 32, self.default_num_stages, 4, group_m=8, waves_per_eu=2 + ), + ROCmGemmConfig(128, 64, 64, self.default_num_stages, 4, group_m=16), + ROCmGemmConfig(128, 64, 128, self.default_num_stages, 8, group_m=4), + ROCmGemmConfig( + 128, 128, 32, self.default_num_stages, 4, group_m=16, waves_per_eu=2 + ), + ROCmGemmConfig(128, 128, 32, self.default_num_stages, 8, group_m=16), + ROCmGemmConfig( + 128, 128, 32, self.default_num_stages, 8, group_m=16, waves_per_eu=2 + ), + ROCmGemmConfig(128, 128, 64, self.default_num_stages, 4, group_m=16), + ROCmGemmConfig(128, 128, 64, self.default_num_stages, 8, group_m=8), + ROCmGemmConfig(128, 128, 128, self.default_num_stages, 8, group_m=16), + ROCmGemmConfig( + 128, 256, 32, self.default_num_stages, 4, group_m=16, waves_per_eu=2 + ), + ROCmGemmConfig(128, 256, 64, self.default_num_stages, 8, group_m=4), + ROCmGemmConfig(256, 64, 64, self.default_num_stages, 8, group_m=4), + ROCmGemmConfig( + 256, 128, 32, self.default_num_stages, 4, group_m=4, waves_per_eu=2 + ), + ROCmGemmConfig(256, 128, 32, self.default_num_stages, 8, group_m=16), + ROCmGemmConfig(256, 128, 64, self.default_num_stages, 8, group_m=4), + ROCmGemmConfig(256, 256, 64, self.default_num_stages, 8, group_m=4), + ] + + # Exhaustive search for mm configs + self.exhaustive_configs: list[BaseConfig] = [ + ROCmGemmConfig( + BLOCK_M, + BLOCK_N, + BLOCK_K, + num_stages, + num_warps, + group_m=group_m, + matrix_instr_nonkdim=matrix_instr_nonkdim, + waves_per_eu=waves_per_eu, + kpack=kpack, + ) + for BLOCK_M, BLOCK_N, BLOCK_K in itertools.product( + [16, 32, 64, 128, 256], repeat=3 + ) + for num_stages in [1, self.default_num_stages] + for num_warps in [4, 8] + for group_m in [4, 8, 16] + for matrix_instr_nonkdim in [0, 16] + for waves_per_eu in [0, 2] + for kpack in [1, 2] + ] + + # Architecture-aware default kpack for flex configs + default_kpack = get_default_kpack() + + self.gfx950_default_flex_config = { + (torch.float32, 64): ROCmFlexConfig(128, 32, 1, 4, kpack=default_kpack), + (torch.float32, 128): ROCmFlexConfig(128, 32, 1, 4, kpack=default_kpack), + (torch.float32, 256): ROCmFlexConfig(64, 16, 1, 4, kpack=default_kpack), + (torch.bfloat16, 64): ROCmFlexConfig(128, 64, 2, 4, kpack=default_kpack), + (torch.bfloat16, 128): ROCmFlexConfig(128, 64, 2, 4, kpack=default_kpack), + (torch.bfloat16, 256): ROCmFlexConfig(32, 64, 2, 4, kpack=default_kpack), + (torch.float16, 64): ROCmFlexConfig(128, 64, 2, 4, kpack=default_kpack), + (torch.float16, 128): ROCmFlexConfig(128, 64, 2, 4, kpack=default_kpack), + (torch.float16, 256): ROCmFlexConfig(32, 64, 2, 4, kpack=default_kpack), + } + + self.gfx942_default_flex_config = { + (torch.float32, 64): ROCmFlexConfig(128, 32, 1, 4, kpack=default_kpack), + (torch.float32, 128): ROCmFlexConfig(128, 32, 1, 4, kpack=default_kpack), + (torch.float32, 256): ROCmFlexConfig(64, 16, 1, 4, kpack=default_kpack), + (torch.bfloat16, 64): ROCmFlexConfig(64, 64, 2, 8, kpack=default_kpack), + (torch.bfloat16, 128): ROCmFlexConfig(64, 64, 2, 8, kpack=default_kpack), + (torch.bfloat16, 256): ROCmFlexConfig(32, 64, 2, 8, kpack=default_kpack), + (torch.float16, 64): ROCmFlexConfig(64, 32, 1, 8, kpack=default_kpack), + (torch.float16, 128): ROCmFlexConfig(64, 32, 1, 8, kpack=default_kpack), + (torch.float16, 256): ROCmFlexConfig(32, 32, 1, 8, kpack=default_kpack), + } + + # RDNA3 (gfx11xx) optimal configs profiled on gfx1151 (head_dim=256). + # Three seq_len tiers to match CU occupancy on 16-CU RDNA3: + # short (seq < 128): BLOCK_M=16, tiny tiles keep all CUs busy + # medium (128 <= seq < 512): BLOCK_M=32, transitional tile size + # long (seq >= 512): BLOCK_M=64, enough seq rows to fill all CUs + self.rdna3_short_seq_flex_config = { + (torch.bfloat16, 256): ROCmFlexConfig(16, 16, 1, 4, waves_per_eu=2), + (torch.float16, 256): ROCmFlexConfig(16, 16, 1, 4, waves_per_eu=2), + } + self.rdna3_medium_seq_flex_config = { + (torch.bfloat16, 256): ROCmFlexConfig( + 32, 16, 1, 4, matrix_instr_nonkdim=16, waves_per_eu=2 + ), + (torch.float16, 256): ROCmFlexConfig( + 32, 16, 1, 4, matrix_instr_nonkdim=16, waves_per_eu=2 + ), + } + self.rdna3_default_flex_config = { + (torch.bfloat16, 256): ROCmFlexConfig(64, 16, 1, 4, waves_per_eu=2), + (torch.float16, 256): ROCmFlexConfig(64, 16, 1, 4, waves_per_eu=2), + } + + self.flex_attn_fwd_autotune_configs: list[FlexConfig] = [ + ROCmFlexConfig(BLOCK1, BLOCK2, 1, w, kpack=default_kpack) + for BLOCK1 in [16, 64, 128] + for BLOCK2 in [16, 32, 64, 128] + for w in [4, 8] + ] + + self.flex_attn_bwd_autotune_configs: list[FlexBwDConfig] = [ + # See Note: flex bwd configs + ROCmFlexBwDConfig( + BLOCK1, BLOCK2, BLOCK2, BLOCK1, 1, w, mfma, kpack=default_kpack + ) + for BLOCK1 in [16, 32, 64] + for BLOCK2 in [32, 64, 128] + for w in ([4, 8] if BLOCK1 >= 128 or BLOCK2 >= 128 else [4]) + for mfma in [0, 16] + if BLOCK2 % BLOCK1 == 0 + ] + + self.flex_decode_autotune_configs: list[FlexDecodeConfig] = [ + ROCmFlexDecodeConfig(32, 1, 4, kpack=default_kpack), + ROCmFlexDecodeConfig(64, 1, 4, kpack=default_kpack), + ROCmFlexDecodeConfig(128, 1, 4, kpack=default_kpack), + ROCmFlexDecodeConfig(32, 1, 8, kpack=default_kpack), + ROCmFlexDecodeConfig(64, 1, 8, kpack=default_kpack), + ROCmFlexDecodeConfig(128, 1, 8, kpack=default_kpack), + ] + + self.exhaustive_flex_attn_fwd_configs: list[FlexConfig] = [ + ROCmFlexConfig(BLOCK_M, BLOCK_N, num_stages, num_warps, mfma, wpeu, kpack) + for BLOCK_M in [16, 32, 64, 128] + for BLOCK_N in [32, 64, 128] + for num_stages in [1, 2] + for num_warps in [2, 4, 8] + for mfma in [0, 16] + for wpeu in [0, int(8 // num_warps)] + for kpack in [1, 2] + ] + + self.exhaustive_flex_attn_bwd_configs: list[FlexBwDConfig] = [ + # See Note: flex bwd configs + ROCmFlexBwDConfig( + BLOCK_M1, + BLOCK_N1, + BLOCK_M2, + BLOCK_N2, + num_stages, + num_warps, + mfma, + wpeu, + kpack, + ) + for BLOCK_M1 in [16, 32, 64, 128] + for BLOCK_N1 in [16, 32, 64, 128] + for BLOCK_M2 in [16, 32, 64, 128] + for BLOCK_N2 in [16, 32, 64, 128] + for num_stages in [1, 2] + for num_warps in [2, 4, 8] + for mfma in [0, 16] + for wpeu in [0, int(8 // num_warps)] + for kpack in [1, 2] + if BLOCK_N1 % BLOCK_M1 == 0 + and BLOCK_M2 % BLOCK_N2 == 0 # kernel static assertions + ] + + self.exhaustive_flex_decode_configs: list[FlexDecodeConfig] = [ + ROCmFlexDecodeConfig( + block_n, num_stages, num_warps, mfma, wpeu, kpack=kpack + ) + for block_n in [16, 32, 64, 128] + for num_stages in [1, 2] + for num_warps in [2, 4, 8] + for mfma in [0, 16] + for wpeu in [0, int(8 // num_warps)] + for kpack in [1, 2] + ] + + def _prune_exhaustive_configs( + self, + configs: list[BaseConfig], + dtype_size: int, + ) -> list[BaseConfig]: + # these cause AMD compile to crash + pruned_configs = [ + c + for c in configs + if not ( + ( + getattr(c, "matrix_instr_nonkdim", 0) == 2 + and getattr(c, "kpack", 0) == 2 + ) + or (c.block_k <= 16 and getattr(c, "kpack", 0) == 2) + ) + ] + return pruned_configs + + def _filter_configs(self, configs: list[BaseConfig]) -> list[BaseConfig]: + """ + ROCm specific filtering + """ + for c in configs: + c.num_stages = self.default_num_stages + return super()._filter_configs(configs) + + def _finalize_mm_configs( + self, + configs: list[BaseConfig], + ) -> Generator[TritonConfig, None, None]: + """ + Finalizes configs after scaling, applying additional constraints. + """ + used: OrderedSet[tuple[int, ...]] = OrderedSet() + + max_mm_configs = config.test_configs.max_mm_configs + + for conf in configs: + # Each warp computes a 16x16 tile = 256 elements + conf.num_warps = min(conf.num_warps, conf.block_m * conf.block_n // 256) + + # Defaults for AMD triton backend kern args if not set + matrix_instr_nonkdim: int = getattr(conf, "matrix_instr_nonkdim", 16) + waves_per_eu: int = getattr(conf, "waves_per_eu", 0) + # Use explicit kpack if set, otherwise determine optimal value based on + # architecture and BLOCK_K + kpack: int = getattr(conf, "kpack", get_default_kpack(conf.block_k)) + + if matrix_instr_nonkdim != 0 and ( + conf.block_m % matrix_instr_nonkdim != 0 + or conf.block_n % matrix_instr_nonkdim != 0 + ): + # block_m and block_n must be a multiple of matrix_instr_nonkdim + continue + + # Construct key for finding duplicate configs + key: tuple[int, ...] = ( + conf.block_m, + conf.block_n, + conf.block_k, + conf.num_stages, + conf.num_warps, + waves_per_eu, + matrix_instr_nonkdim, + kpack, + ) + + # Check if gemm specific arg exists - add to key if does + group_m = getattr(conf, "group_m", None) + # AMD GPU crashes if group_m = 0 + if group_m is not None and group_m <= 0: + group_m = 8 + if group_m is not None: + key += (group_m,) + + if waves_per_eu != 0: + waves_per_eu = int(8 // conf.num_warps) + + if key not in used and ( + max_mm_configs is None or len(used) < max_mm_configs + ): + used.add(key) + kwargs = { + "BLOCK_M": conf.block_m, + "BLOCK_N": conf.block_n, + "BLOCK_K": conf.block_k, + "num_stages": conf.num_stages, + "num_warps": conf.num_warps, + "matrix_instr_nonkdim": matrix_instr_nonkdim, + "waves_per_eu": waves_per_eu, + "kpack": kpack, + } + if group_m is not None: + kwargs["GROUP_M"] = group_m + yield self.triton_config(**kwargs) + + def get_flex_attn_fwd_configs( + self, head_dim: int, seq_len: sympy.Expr, dtype: Any + ) -> list[FlexConfig]: + flex_attn_fwd_configs: list[FlexConfig] = [] + + if config.max_autotune: + if config.max_autotune_flex_search_space == "EXHAUSTIVE": + return self.exhaustive_flex_attn_fwd_configs + flex_attn_fwd_configs += self.flex_attn_fwd_autotune_configs + + capability = torch.cuda.get_device_capability() + default_kpack = get_default_kpack() + + if head_dim <= 256: + if dtype == torch.float32: + default_config = ROCmFlexConfig(64, 64, 1, 4, kpack=default_kpack) + else: + default_config = ROCmFlexConfig(128, 64, 1, 4, kpack=default_kpack) + if using_rocm_rdna3(): + sizevars = V.graph.sizevars + if sizevars.statically_known_lt(seq_len, 128): + default_config = self.rdna3_short_seq_flex_config.get( + (dtype, head_dim), default_config + ) + elif sizevars.statically_known_lt(seq_len, 512): + default_config = self.rdna3_medium_seq_flex_config.get( + (dtype, head_dim), default_config + ) + else: + default_config = self.rdna3_default_flex_config.get( + (dtype, head_dim), default_config + ) + elif capability >= (9, 5): # gfx950 (MI350X/MI355X) + default_config = self.gfx950_default_flex_config.get( + (dtype, head_dim), default_config + ) + elif capability >= (9, 4): # gfx942 (MI300X/MI325X) + default_config = self.gfx942_default_flex_config.get( + (dtype, head_dim), default_config + ) + else: + if dtype == torch.float32: + default_config = ROCmFlexConfig(32, 16, 1, 4, kpack=default_kpack) + else: + default_config = ROCmFlexConfig(64, 32, 1, 4, kpack=default_kpack) + + if default_config not in flex_attn_fwd_configs: + flex_attn_fwd_configs.append(default_config) + + return flex_attn_fwd_configs + + def get_flex_attn_bwd_configs( + self, head_dim: int, dtype: Any + ) -> list[FlexBwDConfig]: + flex_attn_bwd_configs: list[FlexBwDConfig] = [] + + if config.max_autotune: + if config.max_autotune_flex_search_space == "EXHAUSTIVE": + return self.exhaustive_flex_attn_bwd_configs + flex_attn_bwd_configs += self.flex_attn_bwd_autotune_configs + + default_kpack = get_default_kpack() + if dtype == torch.float32: + default_config = ROCmFlexBwDConfig( + 16, 16, 16, 16, 1, 4, kpack=default_kpack + ) + elif head_dim <= 256: + if head_dim == 64: + default_config = ROCmFlexBwDConfig( + 64, 64, 64, 64, 1, 4, kpack=default_kpack + ) + elif head_dim == 128: + default_config = ROCmFlexBwDConfig( + 64, 128, 128, 64, 1, 4, kpack=default_kpack + ) + else: + default_config = ROCmFlexBwDConfig( + 64, 64, 64, 64, 1, 4, kpack=default_kpack + ) + else: + default_config = ROCmFlexBwDConfig( + 16, 16, 16, 16, 1, 4, kpack=default_kpack + ) + + if default_config not in flex_attn_bwd_configs: + flex_attn_bwd_configs.append(default_config) + + return flex_attn_bwd_configs + + def get_flex_decode_configs( + self, head_dim: int, dtype: Any + ) -> list[FlexDecodeConfig]: + flex_decode_configs: list[FlexDecodeConfig] = [] + + if config.max_autotune: + if config.max_autotune_flex_search_space == "EXHAUSTIVE": + return self.exhaustive_flex_decode_configs + flex_decode_configs += self.flex_decode_autotune_configs + + default_kpack = get_default_kpack() + default_config = ROCmFlexDecodeConfig(64, 1, 4, kpack=default_kpack) + + if default_config not in flex_decode_configs: + flex_decode_configs.append(default_config) + + return flex_decode_configs + + +class XPUConfigHeuristic(BaseConfigHeuristic): + """ + Placeholder child class for Intel GPU specific overrides. + """ + + def __init__(self) -> None: + super().__init__() + self.mm_configs = self.mm_configs + [ + GemmConfig(32, 64, 128, 2, 2), + GemmConfig(64, 64, 32, 2, 8), + ] + self.xpu_default_flex_config = { + (torch.float32, 64): FlexConfig(128, 32, 1, 16), + (torch.float32, 128): FlexConfig(128, 32, 1, 16), + (torch.float32, 256): FlexConfig(64, 16, 1, 8), + (torch.bfloat16, 64): FlexConfig(128, 64, 1, 16), + (torch.bfloat16, 128): FlexConfig(128, 64, 1, 16), + (torch.bfloat16, 256): FlexConfig(32, 64, 1, 4), + (torch.float16, 64): FlexConfig(128, 64, 1, 16), + (torch.float16, 128): FlexConfig(128, 64, 1, 16), + (torch.float16, 256): FlexConfig(32, 64, 1, 4), + } + self.flex_attn_fwd_autotune_configs: list[FlexConfig] = [ + FlexConfig(32, 16, 2, 4), + FlexConfig(128, 64, 2, 16), + FlexConfig(128, 64, 2, 8), + FlexConfig(128, 32, 2, 16), + FlexConfig(128, 32, 2, 8), + ] + self.flex_attn_bwd_autotune_configs: list[FlexBwDConfig] = [ + FlexBwDConfig(32, 32, 32, 32, 2, 4), + FlexBwDConfig(64, 64, 64, 64, 2, 4), + ] + self.flex_decode_autotune_configs: list[FlexDecodeConfig] = [] + + if not bool(os.getenv("CI")): + self.flex_attn_bwd_autotune_configs += [ + # See Note: flex bwd configs + FlexBwDConfig(BLOCK1, BLOCK2, BLOCK2, BLOCK1, s, w) + for BLOCK1 in [32, 64] + for BLOCK2 in [32, 64, 128] + for s in [1, 3, 4, 5] # num_stages + for w in ([4, 8] if BLOCK1 >= 128 or BLOCK2 >= 128 else [4]) + if BLOCK2 % BLOCK1 == 0 + ] + self.flex_decode_autotune_configs += [ + FlexDecodeConfig(32, 1, 2), + FlexDecodeConfig(32, 1, 1), + FlexDecodeConfig(32, 2, 2), + FlexDecodeConfig(32, 2, 1), + FlexDecodeConfig(64, 1, 2), + FlexDecodeConfig(64, 1, 1), + FlexDecodeConfig(64, 2, 2), + FlexDecodeConfig(64, 2, 1), + ] + + def get_flex_attn_fwd_configs( + self, head_dim: int, seq_len: sympy.Expr, dtype: Any + ) -> list[FlexConfig]: + flex_attn_fwd_configs: list[FlexConfig] = [] + + if config.max_autotune: + if config.max_autotune_flex_search_space == "EXHAUSTIVE": + return self.exhaustive_flex_attn_fwd_configs + flex_attn_fwd_configs += self.flex_attn_fwd_autotune_configs + + if head_dim <= 256: + if dtype == torch.float32: + default_config = FlexConfig(64, 64, 1, 8) + else: + default_config = FlexConfig(128, 64, 1, 16) + default_config = self.xpu_default_flex_config.get( + (dtype, head_dim), default_config + ) + else: + if dtype == torch.float32: + default_config = FlexConfig(32, 16, 1, 4) + else: + default_config = FlexConfig(64, 32, 1, 8) + + if default_config not in flex_attn_fwd_configs: + flex_attn_fwd_configs.append(default_config) + + return flex_attn_fwd_configs + + def get_flex_attn_bwd_configs( + self, head_dim: int, dtype: Any + ) -> list[FlexBwDConfig]: + flex_attn_bwd_configs: list[FlexBwDConfig] = [] + + if config.max_autotune: + if config.max_autotune_flex_search_space == "EXHAUSTIVE": + return self.exhaustive_flex_attn_bwd_configs + flex_attn_bwd_configs += self.flex_attn_bwd_autotune_configs + + if dtype == torch.float32: + default_config = FlexBwDConfig(16, 16, 16, 16, 1, 4) + elif head_dim <= 256: + if head_dim == 64: + default_config = FlexBwDConfig(64, 64, 64, 64, 1, 8) + elif head_dim == 128: + default_config = FlexBwDConfig(64, 64, 64, 64, 1, 8) + else: + default_config = FlexBwDConfig(64, 64, 64, 64, 1, 8) + else: # modest hardware or extremely large head_dim + default_config = FlexBwDConfig(16, 16, 16, 16, 1, 4) + + if default_config not in flex_attn_bwd_configs: + flex_attn_bwd_configs.append(default_config) + + return flex_attn_bwd_configs + + def get_flex_decode_configs( + self, head_dim: int, dtype: Any + ) -> list[FlexDecodeConfig]: + flex_decode_configs: list[FlexDecodeConfig] = [] + + if config.max_autotune: + if config.max_autotune_flex_search_space == "EXHAUSTIVE": + return self.exhaustive_flex_decode_configs + flex_decode_configs += self.flex_decode_autotune_configs + + default_config = FlexDecodeConfig(64, 1, 2) + + if default_config not in flex_decode_configs: + flex_decode_configs.append(default_config) + + return flex_decode_configs + + def _prune_exhaustive_configs( + self, + configs: list[BaseConfig], + dtype_size: int, + ) -> list[BaseConfig]: + return configs + + +class MTIAConfigHeuristic(BaseConfigHeuristic): + """ + Placeholder child class for MTIA specific overrides. + """ + + +# Template-specific mixin classes +class MMTemplateConfigMixin(GemmMaxAutotuneTemplateConfigHeuristics): + """ + Mixin class that converts config lists to template kwargs. + This handles the logic that was previously in choices.get_mm_configs. + + This mixin expects to be used with BaseConfigHeuristic or its subclasses. + """ + + # Type annotations to ensure the mixin works with BaseConfigHeuristic + get_mm_configs: Callable[[], partial[Generator[TritonConfig, None, None]]] + get_exhaustive_mm_configs: Callable[ + [], partial[Generator[TritonConfig, None, None]] + ] + _filter_configs: Callable[[list[BaseConfig]], list[BaseConfig]] + # Provided by ROCmConfigHeuristic / BaseConfigHeuristic when this mixin is + # combined with a backend heuristic. Annotated here so type-checkers see the + # attributes used by the origami branch in _get_template_configs_impl. + default_num_stages: int + exhaustive_configs: list[BaseConfig] + _get_exceeding_shared_memory_checker: Callable[ + [bool, int], Callable[[BaseConfig, int], bool] | None + ] + preprocess_mm_configs: Callable[..., Generator[TritonConfig, None, None]] + + def get_extra_kwargs( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> dict[str, Any]: + if not isinstance(kernel_inputs, MMKernelInputs): + raise AssertionError(f"Expected MMKernelInputs, got {type(kernel_inputs)}") + m, n, k = kernel_inputs.mnk_symbolic() + device_type = kernel_inputs.device_type + if device_type == "xpu": + # XPU eager matmul takes TF32 from the oneDNN flag, not the CUDA one. + allow_tf32 = torch.backends.mkldnn.allow_tf32 + elif device_type == "cuda": + # allow_tf32 alignment heuristics based on reverse engineering + # H100 CUDA 12.8 behavior + size_threshold = V.graph.sizevars.statically_known_true( + sympy.And(sympy.Ge(m, 16), sympy.Ge(Min(n, k), 512)) + ) + allow_tf32 = ( + torch.backends.cuda.matmul.fp32_precision == "tf32" and size_threshold + ) + else: + allow_tf32 = False + + return { + "ALLOW_TF32": allow_tf32, + } + + def _valid(self, kernel_inputs: KernelInputs) -> bool: + return True + + def _get_config_generator( + self, + ) -> partial[Generator[TritonConfig, None, None]]: + """ + Get the appropriate config generator based on search space. + Can be overridden by subclasses for template-specific behavior. + """ + # Handle exhaustive search case + if config.max_autotune_gemm_search_space == "EXHAUSTIVE": + return self.get_exhaustive_mm_configs() + else: + return self.get_mm_configs() + + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + **kwargs, + ) -> Generator[dict[str, Any], None, None]: + """ + Convert config lists to template kwargs. + This replaces the logic from choices.get_mm_configs and inlines mm_options. + """ + if not isinstance(kernel_inputs, MMKernelInputs): + raise AssertionError(f"{self.__class__.__name__} requires MMKernelInputs") + input_nodes = kernel_inputs.nodes() + if len(input_nodes) < 2: + raise ValueError(f"Need at least 2 input tensors, got {len(input_nodes)}") + if not self._valid(kernel_inputs): + return + + # Extract M, N, K from kernel_inputs + m, n, k = kernel_inputs.mnk_symbolic() + + # Extract dtype and device_type from kernel_inputs + dtype = kernel_inputs.dtype() + # Get the appropriate config generator + configs = self._get_config_generator() + # origami is a C++ perf model that requires concrete m, n, k; feeding it + # sympy symbols (dynamic shapes, e.g. torch.cat with k=s0+s1) yields no + # usable selection, so restrict origami to fully static problems and let + # symbolic shapes fall through to the regular config generator below. + mnk_static = all(not getattr(x, "free_symbols", None) for x in (m, n, k)) + if ( + origami is not None + and not mnk_static + and config.max_autotune_gemm_search_space == "DEFAULT" + ): + log.debug("Origami skipped: symbolic m/n/k, using regular config generator") + # `origami is not None` encodes the module-load gate (see top of file); + # only DEFAULT search space is supported here. + if ( + origami is not None + and config.max_autotune_gemm_search_space == "DEFAULT" + and mnk_static + ): + # Extract device and strides for origami GEMM + device = kernel_inputs.device() + strides = kernel_inputs.strides_symbolic() + a_stride = strides[kernel_inputs._mat1_idx] + b_stride = strides[kernel_inputs._mat2_idx] + # Pre-filter exhaustive_configs against LDS BEFORE origami sees them. + # Origami otherwise ranks LDS-busting tiles in its top-K and we'd + # have to drop its best picks at compile time (Triton OutOfResources + # is not always caught on the HIP backend). Check against + # self.default_num_stages because ROCmConfigHeuristic._filter_configs + # (triton.py:1728) clobbers num_stages to that value downstream. + lds_check = self._get_exceeding_shared_memory_checker(False, 0) + exhaustive = self.exhaustive_configs + if lds_check is not None: + exhaustive = [ + c + for c in self.exhaustive_configs + if not lds_check( + dataclasses.replace(c, num_stages=self.default_num_stages), + dtype.itemsize, + ) + ] + pruned = len(self.exhaustive_configs) - len(exhaustive) + if pruned: + log.info( + "Origami: pruned %d/%d exhaustive configs " + "exceeding LDS for dtype %s", + pruned, + len(self.exhaustive_configs), + dtype, + ) + allcfgs = self.preprocess_mm_configs( + m, + n, + k, + configs=exhaustive, + dtype_size=dtype.itemsize, + op_name=op_name, + ) + selector = origami.OrigamiMatmulSelector( + allcfgs, + m, + n, + k, + dtype, + dtype, + dtype, + device, + a_stride, + b_stride, + ) + # _origami_{problem,hardware,configs} wrap the private attrs; + # see TODO at top of file for the upstream-API migration plan. + topk_results = origami.select_topk_configs( + _origami_problem(selector), + _origami_hardware(selector), + _origami_configs(selector), + config.rocm.origami_topk, + ) + seen = OrderedSet() + # Collect origami-selected configs into a list before filtering + origami_configs: list[BaseConfig] = [] + # Map config key (immutable tile dimensions) to origami parameters + origami_triton_configs: dict[tuple[int, int, int], tuple[Any, Any]] = {} + + def _config_key(cfg: BaseConfig) -> tuple[int, int, int]: + """ + Generate a stable key for origami configs based on immutable tile dimensions. + Uses only block_m, block_n, block_k since these uniquely identify an origami + config and remain invariant across _filter_configs modifications (which may + change num_stages, num_warps, and other attributes). + """ + return ( + cfg.block_m, + cfg.block_n, + cfg.block_k, + ) + + for result in topk_results: + cfg = result.config + key = (cfg.mt.m, cfg.mt.n, cfg.mt.k, cfg.occupancy) + if key in seen: + continue + seen.add(key) + grid = origami.select_grid_size( + _origami_problem(selector), + _origami_hardware(selector), + cfg, + origami.grid_selection_t.data_parallel, + _origami_hardware(selector).N_CU, + ) + wgm_result = origami.select_workgroup_mapping( + _origami_problem(selector), + _origami_hardware(selector), + cfg, + grid, + ) + # One MFMA per warp, capped at 2 * parallel_mi_cu. + tile_area = cfg.mt.m * cfg.mt.n + try: + warp_size = DeviceProperties.create(device).warp_size or 64 + except (RuntimeError, AttributeError) as e: + # Fallback to standard warp size if device properties unavailable + log.warning( + "Failed to get device warp size: %s. Using default 64.", e + ) + warp_size = 64 + max_warps = 2 * _origami_hardware(selector).parallel_mi_cu + # mfma_dim from origami hardware object; fall back to 16. + mfma_dim = getattr(_origami_hardware(selector), "mfma_m", 16) + num_warps = min( + max_warps, + max(1, tile_area // (mfma_dim * warp_size)), + ) + # num_stages: ROCmConfigHeuristic._filter_configs (triton.py:1728) + # overwrites this to self.default_num_stages, so seed with that + # value to keep the in-flight GemmConfig consistent with the + # post-filter state. + base_config = GemmConfig( + block_m=cfg.mt.m, + block_n=cfg.mt.n, + block_k=cfg.mt.k, + num_stages=self.default_num_stages, + num_warps=num_warps, + group_m=wgm_result.wgm, + ) + origami_configs.append(base_config) + # Store triton config and its parameters for later conversion using stable key + config_key = _config_key(base_config) + origami_triton_configs[config_key] = ( + cfg.occupancy, + wgm_result.wgm, + ) + + # Apply backend filters (max block size, memory constraints, etc.). + # LDS-overflow prune already happened upstream against + # self.exhaustive_configs before origami selection. + filtered_configs = self._filter_configs(origami_configs) + + # If origami returned configs, use them; otherwise fall back to regular generator + if filtered_configs: + # Convert filtered configs to template kwargs and yield + for filtered_config in filtered_configs: + # Retrieve stored origami parameters using stable config key + config_key = _config_key(filtered_config) + origami_params = origami_triton_configs.get(config_key) + if origami_params is None: + # If not found, log a warning about the lookup failure + log.warning( + "Config lookup failed for %s. " + "This may indicate a config rebuilding issue in _filter_configs.", + config_key, + ) + continue + occupancy, group_m = origami_params + + # Create TritonConfig from filtered config + triton_config = self.triton_config( # pyright: ignore[attr-defined] + num_stages=filtered_config.num_stages, + num_warps=filtered_config.num_warps, + BLOCK_M=filtered_config.block_m, + BLOCK_N=filtered_config.block_n, + BLOCK_K=filtered_config.block_k, + GROUP_M=group_m, + waves_per_eu=occupancy, + ) + template_kwargs = self._convert_config_to_template_kwargs( + triton_config, + m, + n, + k, + kernel_inputs.out_dtype(), + ) + yield template_kwargs + else: + # No origami configs returned (e.g., topk=0), fall back to regular generator + log.warning( + "Origami returned no configs, falling back to regular config generator" + ) + for c in configs( + m, + n, + k, + dtype_size=dtype.itemsize, + op_name=op_name, + **kwargs, + ): + template_kwargs = self._convert_config_to_template_kwargs( + c, + m, + n, + k, + kernel_inputs.out_dtype(), + ) + yield template_kwargs + + else: + # Warn if origami was enabled but not used due to EXHAUSTIVE search space. + # `origami is not None` already covers IS_ROCM + max_autotune + rocm.origami. + if ( + origami is not None + and config.max_autotune_gemm_search_space == "EXHAUSTIVE" + ): + log.warning( + "Origami is enabled but not used: search space is set to EXHAUSTIVE. " + "Origami only operates with DEFAULT search space. " + "Set max_autotune_gemm_search_space='DEFAULT' to enable origami optimization." + ) + for c in configs( + m, + n, + k, + dtype_size=dtype.itemsize, + op_name=op_name, + **kwargs, + ): + template_kwargs = self._convert_config_to_template_kwargs( + c, + m, + n, + k, + kernel_inputs.out_dtype(), + ) + yield template_kwargs + + def _convert_config_to_template_kwargs( + self, + triton_config: TritonConfig, + m: sympy.Integer | sympy.Symbol, + n: sympy.Integer | sympy.Symbol, + k: sympy.Integer | sympy.Symbol, + out_dtype: torch.dtype, + ) -> dict[str, Any]: + """ + Convert triton config to template kwargs. + Moved from mm_common.mm_options. + """ + # Calculate EVEN_K symbolic. (It isn't worth guarding on this) + even_k_symbolic = sympy.Eq(Mod(k, triton_config.kwargs["BLOCK_K"]), 0) + even_k_symbolic = V.graph.sizevars.statically_known_true(even_k_symbolic) + + # Build options dict + + options_dict = dict( + EVEN_K=even_k_symbolic, + USE_FAST_ACCUM=False, # Option for _scaled_mm + ACC_TYPE=self._get_acc_type(out_dtype), + num_stages=triton_config.num_stages, + num_warps=triton_config.num_warps, + **triton_config.kwargs, + ) + + # If GROUP_M not specified then default to 8 + if "GROUP_M" not in triton_config.kwargs: + group_m = triton_config.kwargs.get("GROUP_M", 8) + options_dict["GROUP_M"] = group_m + + return options_dict + + @staticmethod + def _dtype_to_triton(dtype: torch.dtype) -> str: + """Convert a torch dtype to a triton type string.""" + return triton_type(dtype) + + def _get_acc_type(self, dtype: torch.dtype) -> str: + """ + Get accumulator type for the given dtype. + Moved from mm_common.acc_type. + """ + if dtype in ( + torch.float16, + torch.bfloat16, + torch.float8_e4m3fnuz, + torch.float8_e4m3fn, + ): + return "tl.float32" + return self._dtype_to_triton(dtype) + + +# INT8 specific mixin to filter correctly +class INT8MMTemplateConfigMixin(MMTemplateConfigMixin): + """ + Ensure that we feed in has_int8_tensor=True + """ + + def __init__(self) -> None: + super().__init__() + self.has_int8_tensor = True + + +# MMPlusMM specific mixin to avoid running _scale_mm_configs +class MMPlusMMTemplateConfigMixin(MMTemplateConfigMixin): + """ + Ensure that _should_scale_configs is False + """ + + # TODO(coconutruben): remove this once all tests work + # with proper scaling on mm_plus_mm + def __init__(self) -> None: + super().__init__() + self.should_scale_configs = False + + def preprocess_mm_configs( + self, + m: int, + n: int, + k: int, + configs: list[BaseConfig], + has_int8_tensor: bool = False, + scale: float = 1.0, + exclude: Callable[ + [sympy.Integer, sympy.Integer, sympy.Integer], bool + ] = lambda m, n, k: False, + dtype_size: int = 0, + op_name: str = "mm", + **kwargs, + ) -> Generator[TritonConfig, None, None]: + configs = [ + c for c in configs if V.graph.sizevars.statically_known_lt(c.block_k, k) + ] + return super().preprocess_mm_configs( + m, + n, + k, + configs=configs, + has_int8_tensor=has_int8_tensor, + scale=scale, + exclude=exclude, + dtype_size=dtype_size, + op_name=op_name, + **kwargs, + ) + + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + **kwargs, + ) -> Generator[dict[str, Any], None, None]: + if not isinstance(kernel_inputs, MMKernelInputs): + raise AssertionError("Expect MMKernelInputs") + m, n, k = kernel_inputs.mnk_symbolic() + for template_kwargs in super()._get_template_configs_impl( + kernel_inputs, op_name, **kwargs + ): + # Apply BLOCK_K constraint specific to mm_plus_mm + # see https://github.com/triton-lang/triton/issues/1298 + # BLOCK_K = K causes llvm error + if V.graph.sizevars.statically_known_lt( + template_kwargs.get("BLOCK_K", k), k + ): + yield template_kwargs + + +class TMAWorkspaceMixin(MMTemplateConfigMixin): + """ + Small mixin to ensure that the workspace arg is correct for TMA + and TMA specific filtering can happen. + """ + + def get_extra_kwargs( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> dict[str, Any]: + kwargs = super().get_extra_kwargs(kernel_inputs, op_name) + kwargs["workspace_arg"] = get_tma_workspace_arg( + num_tma_descriptors=2, + device=kernel_inputs.device(), + ) + return kwargs + + # pyrefly: ignore [bad-override] + def _filter_configs(self, configs: list[BaseConfig]) -> list[BaseConfig]: + """ + TMA specific filtering, as num_warps=2 not safe for TMA + """ + configs = [c for c in configs if c.num_warps != 2] + return super()._filter_configs(configs) + + +def get_shared_memory_checker_opts(op_name: str, dtype_size: int): + return { + "has_sm_layout_conversion": True, + # addmm requires the acc dtype for layout conversion due to adding bias + # mm just input dtype + "layout_conversion_byte_size": 4 if op_name == "addmm" else dtype_size, + } + + +# TMA-specific mixin for TMA templates +class TMATemplateConfigMixin(TMAWorkspaceMixin, MMTemplateConfigMixin): + """ + TMA-specific mixin that uses persistent configs and adds TMA options. + This inherits from MMTemplateConfigMixin and overrides config generation. + """ + + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + **kwargs, + ) -> Generator[dict[str, Any], None, None]: + """ + Generate TMA template configs by calling super and adding TMA-specific options. + """ + if not isinstance(kernel_inputs, MMKernelInputs): + raise AssertionError("TMATemplateConfigMixin requires MMKernelInputs") + mat1, mat2 = kernel_inputs.mat1mat2() + tma_opts = { + "A_ROW_MAJOR": not mat1.layout.is_transposed(), + "B_ROW_MAJOR": not mat2.layout.is_transposed(), + "NUM_SMS": get_num_sms(), + "TMA_SIZE": TMA_DESCRIPTOR_SIZE, + "TMA_EXPERIMENTAL_API": not has_triton_stable_tma_api(), + "tma_store": config.triton.enable_template_tma_store, + "tma_load_for_template_epilogue": config.triton.enable_tma_load_for_template_epilogue, + "transpose_discontiguous_tensor_descriptors_override": True, + } + + # Get base template configs from superclass + for template_kwargs in super()._get_template_configs_impl( + kernel_inputs, + op_name, + **get_shared_memory_checker_opts( + op_name, dtype_size=kernel_inputs.dtype().itemsize + ), + ): + yield {**template_kwargs, **tma_opts} + + +# TMA mixins for Blackwell templates +class BlackwellTMATemplateConfigMixin(TMATemplateConfigMixin): + """Config mixin for the Blackwell persistent-TMA GEMM template. + + Generates the fb-triton autoWS (meta-WS) config sweep and prunes the + combinations the lowering cannot support before they reach codegen. + """ + + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + **kwargs, + ) -> Generator[dict[str, Any], None, None]: + """ + Generate TMA template configs by calling super and adding TMA-specific options. + """ + # Get base template configs from superclass + for template_kwargs in super()._get_template_configs_impl( + kernel_inputs, + op_name, + **kwargs, + ): + use_meta_ws = template_kwargs.get("USE_META_WS", False) + # autoWS configs come from a full sweep; drop combos the lowering + # does not support so no invalid config reaches codegen. + if use_meta_ws and not self._autows_constraints_ok(template_kwargs): + continue + # Some Triton versions requires num_warps >= 4 for WS + # to avoid compilation issues. Triton disables WS if num_warps < 4 + # or num_stages < 2. Similar issues have been seen with num_stages=1 + constraints_violated = ( + template_kwargs["num_warps"] < 4 or template_kwargs["num_stages"] < 2 + ) + ws = ( + template_kwargs.get("WARP_SPECIALIZE", True) + and not constraints_violated + ) + # Meta WS pass has only validated flatten=False; OSS Triton uses flatten=True + flatten = ( + template_kwargs.get("FLATTEN", True) + and not constraints_violated + and not use_meta_ws + ) + yield { + **template_kwargs, + "NUM_SMS": get_num_sms(), + "WARP_SPECIALIZE": ws, + "FLATTEN": flatten, + } + + @staticmethod + def _autows_constraints_ok(template_kwargs: dict[str, Any]) -> bool: + """autoWS lowering constraints; swept configs violating these are pruned.""" + block_m = template_kwargs["BLOCK_M"] + block_n = template_kwargs["BLOCK_N"] + subtile = template_kwargs.get("EPILOGUE_SUBTILE", 1) + # each epilogue subtile is BLOCK_N // EPILOGUE_SUBTILE wide + if block_n // subtile < 32: + return False + # dp=2 splits the row tile into two MMA partitions; BLOCK_M=64 fails in + # the fb-triton WS pass pipeline, so keep the tile at 128 or 256 + dp = template_kwargs.get("DATA_PARTITION_FACTOR", 1) + if dp == 2 and block_m not in (128, 256): + return False + return True + + def _get_config_generator( + self, + ) -> partial[Generator[TritonConfig, None, None]]: + # No curated autoWS set yet: sweep the full autoWS space for both default + # and exhaustive search, and let _get_template_configs_impl prune it. + if _use_template_autows(): + return partial( + self.preprocess_mm_configs, configs=self._generate_autows_configs() + ) + return super()._get_config_generator() + + @staticmethod + def _generate_autows_configs() -> list[BaseConfig]: + configs: list[BaseConfig] = [] + for BLOCK_M, BLOCK_N, BLOCK_K in itertools.product( + [32, 64, 128, 256], repeat=3 + ): + for num_stages in [2, 3, 4, 5, 6]: + # AutoWS doesn't work with num_warps < 4 + for num_warps in [4, 8]: + for epilogue_subtile in [1, 2, 4, 8]: + for data_partition_factor in [1, 2]: + for separate_epilogue_store in [False, True]: + configs.append( + BlackwellGPUGemmConfig( + block_m=BLOCK_M, + block_n=BLOCK_N, + block_k=BLOCK_K, + num_stages=num_stages, + num_warps=num_warps, + group_m=8, + epilogue_subtile=epilogue_subtile, + use_meta_ws=True, + data_partition_factor=data_partition_factor, + separate_epilogue_store=separate_epilogue_store, + warp_specialize=True, + flatten=False, + ) + ) + return configs + + @staticmethod + def _generate_exhaustive_configs() -> list[BaseConfig]: + configs: list[BaseConfig] = [] + for BLOCK_M, BLOCK_N, BLOCK_K in itertools.product( + [32, 64, 128, 256], + repeat=3, + ): + for num_stages in [2, 3, 4, 5, 6]: + # AutoWS doesn't work with num_warps < 4 + for num_warps in [4, 8]: + for EPILOGUE_SUBTILE in [1, 2, 4]: + configs.append( + BlackwellGPUGemmConfig( + block_m=BLOCK_M, + block_n=BLOCK_N, + block_k=BLOCK_K, + num_stages=num_stages, + num_warps=num_warps, + group_m=8, + epilogue_subtile=EPILOGUE_SUBTILE, + warp_specialize=True, + flatten=True, + ) + ) + return configs + + +# Scaled MM-specific mixin for scaled MM templates +class BaseScaledMMConfigMixin(MMTemplateConfigMixin): + """ + This is a base that handles the common case for ScaledMM + + The TMA and non-TMA should build on top of this + """ + + def adjust_kernel_inputs( + self, kernel_inputs: KernelInputs, op_name: str + ) -> KernelInputs: + """ + for scaled_mm, we need to unsqueeze scale tensors, and bias + """ + if not isinstance(kernel_inputs, MMKernelInputs): + raise AssertionError("Expect MMKernelInputs for scaled MM") + inputs = super().adjust_kernel_inputs(kernel_inputs, op_name) + nodes = inputs.nodes() + mat_a, mat_b, scale_a, scale_b, *bias = nodes + bias = bias[0] if bias else None + # Prepare triton input nodes and create kernel_inputs at the top + from ...lowering import lowerings as L + + aten = torch.ops.aten + if bias and len(mat_b.get_size()) == len(bias.get_size()) + 1: + # Need to unsqueeze bias from [N] -> [1, N] + bias = L[aten.unsqueeze](bias, 0) + + def is_tensorwise_scale(scale: Any) -> bool: + size = scale.get_size() + return len(size) == 0 or all( + V.graph.sizevars.statically_known_equals(dim, 1) for dim in size + ) + + def normalize_tensorwise_scale(scale: Any, *, allow_high_rank: bool) -> Any: + if not is_tensorwise_scale(scale): + return scale + if not allow_high_rank and len(scale.get_size()) > 2: + raise RuntimeError( + f"t() expects a tensor with <= 2 dimensions, " + f"but self is {len(scale.get_size())}D" + ) + return L[aten.reshape](scale, [1, 1]) + + # The templates load scale suffixes with 2D output indices. Eager accepts + # high-rank all-ones scale_a, but scale_b is internally transposed and + # rank > 2 is invalid. + scale_a = normalize_tensorwise_scale(scale_a, allow_high_rank=True) + scale_b = normalize_tensorwise_scale(scale_b, allow_high_rank=False) + nodes = [mat_a, mat_b, scale_a, scale_b] + if bias: + nodes.append(bias) + return MMKernelInputs( + nodes, + scalars=kernel_inputs._scalars, + mat1_idx=kernel_inputs._mat1_idx, + mat2_idx=kernel_inputs._mat2_idx, + out_dtype=kernel_inputs._out_dtype, + ) + + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + **kwargs, + ) -> Generator[dict[str, Any], None, None]: + """ + Generate scaled MM template configs with scaled MM-specific options. + Handles the remaining logic from mm_common, including assertions. + """ + kernel_inputs = self.adjust_kernel_inputs(kernel_inputs, op_name) + input_nodes = kernel_inputs.nodes() + # Initial assertion from mm_common.scaled_mm_options + if len(input_nodes) < 4: + raise AssertionError( + f"scaled_mm requires at least 4 inputs, got {len(input_nodes)}" + ) + + # Extract scale tensors (typically scale_a and scale_b are input_nodes[2] and input_nodes[3]) + scale_a = input_nodes[2] + scale_b = input_nodes[3] + + # Scale compatibility assertion from mm_common.scaled_mm_options + def are_compatible_scales(size_a: Any, size_b: Any) -> bool: + # Same sized scales are compatible + if len(size_a) == len(size_b): + return True + + # Both need to be scalars or len(1) tensors + if len(size_a) <= 1 and len(size_b) <= 1: + return True + + return False + + size_a, size_b = scale_a.get_size(), scale_b.get_size() + if not are_compatible_scales(size_a, size_b): + raise AssertionError( + "Expect scale_a and scale_b to be either both scalars (including single-element tensors) " + f"or 1-dimensional tensors with the same size. Got scale_a: {len(size_a)} and scale_b: {len(size_b)}." + ) + + if not isinstance(kernel_inputs, MMKernelInputs): + raise AssertionError(f"{self.__class__.__name__} requires MMKernelInputs") + + if not self._valid(kernel_inputs): + return + + # Get base template configs from superclass + for template_kwargs in super()._get_template_configs_impl( + kernel_inputs, op_name, **kwargs + ): + # Add scaled MM-specific options (moved from mm_common.scaled_mm_options) + # Override accumulator type for scaled MM using dynamic type resolution + template_kwargs["ACC_TYPE"] = self._get_acc_type(kernel_inputs.out_dtype()) + + yield template_kwargs + + +class ScaledMMConfigMixin(BaseScaledMMConfigMixin): + """Mixin for scaled mm with the regular mm template""" + + def get_extra_kwargs( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> dict[str, Any]: + kwargs = super().get_extra_kwargs(kernel_inputs, op_name) + from ...kernel.mm_common import scale_mm_epilogue + + return { + **kwargs, + "suffix_args": kernel_inputs.count - 2, + "epilogue_fn": scale_mm_epilogue(), + "epilogue_fn_hash": "scale_mm_epilogue", + } + + def _valid(self, kernel_inputs: KernelInputs) -> bool: + if not isinstance(kernel_inputs, MMKernelInputs): + raise AssertionError("Expect MMKernelInputs for ScaledMMConfigMixin") + _, _, k = kernel_inputs.mnk_symbolic() + if V.graph.sizevars.guard_or_false(sympy.Le(k, 16)): + # Triton crashes however uncommon for real workloads + return False + + # On NVIDIA B200 GPUs, K dim must be >= 32 for tcgen05.mma.kind::f8f6f4.* PTX instruction to be valid + # source: https://docs.nvidia.com/cuda/parallel-thread-execution/#tcgen05-matrix-shape + if using_b200() and V.graph.sizevars.guard_or_false(sympy.Lt(k, 32)): + return False + return True + + # pyrefly: ignore [bad-override] + def _filter_configs(self, configs: list[BaseConfig]) -> list[BaseConfig]: + """ + Filter out bad configs for specific hardware. + On AMD MI350X (GFX 9.5+), skip configs with BLOCK_K<=64 due to lack of corresponding MFMA instructions. + """ + + def should_skip_mi350x_config(config: BaseConfig) -> bool: + """Skip config if BLOCK_K<=64 on MI350X (GFX 9.5+)""" + try: + return ( + config.block_k <= 64 + and IS_ROCM + and torch.cuda.get_device_capability() >= (9, 5) + ) + except RuntimeError: + # If no HIP GPUs are available, we can't check device capability + # so we don't skip any configs + return False + + filtered_configs = [c for c in configs if not should_skip_mi350x_config(c)] + return super()._filter_configs(filtered_configs) + + +# Scaled TMA-specific mixin for scaled MM templates with TMA +class ScaledTMAConfigMixin(TMAWorkspaceMixin, BaseScaledMMConfigMixin): + """ + Scaled TMA-specific mixin that extends BaseScaledMMConfigMixin with TMA functionality. + This is for scaled MM templates that use device TMA. + This inherits from BaseScaledMMConfigMixin and adds TMA-specific options. + """ + + # pyrefly: ignore [bad-override] + def _filter_configs(self, configs: list[BaseConfig]) -> list[BaseConfig]: + """ + TMA specific filtering: + - num_warps=2 not safe for TMA + - block_k >= 32 required for TMA (requires inner-most dimension >= 32) + """ + configs = [c for c in configs if c.num_warps != 2 and c.block_k >= 32] + return super()._filter_configs(configs) + + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + **kwargs, + ) -> Generator[dict[str, Any], None, None]: + """ + Generate scaled TMA template configs with both scaled MM and TMA-specific options. + """ + # Get base scaled MM template configs from superclass + for template_kwargs in super()._get_template_configs_impl( + kernel_inputs, + op_name, + **kwargs, + ): + # Add TMA-specific options for device TMA scaled MM + template_kwargs["TMA_SIZE"] = TMA_DESCRIPTOR_SIZE + template_kwargs["NUM_SMS"] = get_num_sms() + template_kwargs["TMA_EXPERIMENTAL_API"] = not has_triton_stable_tma_api() + + yield template_kwargs + + +# Scaled Blackwell TMA-specific mixin for scaled MM templates with TMA +class ScaledBlackwellTMAConfigMixin( + BlackwellTMATemplateConfigMixin, ScaledMMConfigMixin +): + """ + Scaled Blackwell TMA-specific mixin that extends ScaledMMConfigMixin with TMA functionality. + This is for scaled MM templates that use device TMA on Blackwell. + This inherits from ScaledMMConfigMixin, which inherits the scale_mm_epilogue, and adds TMA-specific options. + """ + + def _filter_configs(self, configs: list[BaseConfig]) -> list[BaseConfig]: + """ + Warp specialization-specific filtering (BlackwellTMATemplateConfigMixin) + (compilation issues occur in some versions of Triton) + - num_warps < 4 unsafe for warpspec + - num_stages < 2 unsafe for warpspec + + TMA-specific filtering: + - block_k >= 32 required for TMA (requires inner-most dimension >= 32) + """ + configs = [c for c in configs if c.block_k >= 32] + return super()._filter_configs(configs) + + +# Template-specific heuristic classes using multiple inheritance + + +@register_template_heuristic( + mm_template.uid, + "cuda", + register=torch.version.hip is None, +) +@register_template_heuristic( + bmm_template.uid, + "cuda", + register=torch.version.hip is None, +) +class CUDAMMTemplateConfigHeuristic(MMTemplateConfigMixin, CUDAConfigHeuristic): + """Standard MM template heuristic for CUDA""" + + +@register_template_heuristic( + mm_template.uid, "cuda", register=torch.version.hip is None, op_name="addmm" +) +@register_template_heuristic( + bmm_template.uid, "cuda", register=torch.version.hip is None, op_name="baddbmm" +) +class CUDAAddMMTemplateConfigHeuristic(AddMMConfigMixin, CUDAMMTemplateConfigHeuristic): + """Addmm specific mixin for CUDA""" + + +# TODO(coconutruben): deprecate once autoheuristic is deprecated +@register_template_heuristic( + mm_template.uid, + "cuda", + register=torch.version.hip is None, + op_name="mm-ah", +) +class CUDAMMAHTemplateConfigHeuristic(MMTemplateConfigMixin, CUDAConfigHeuristic): + """Standard MM template heuristic for CUDA using the extra mm configs only (for autoheuristic)""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use scaled_mm_configs + self.mm_configs = self.extra_mm_configs + self.exhaustive_configs = self.extra_mm_configs + + +@register_template_heuristic( + persistent_tma_mm_template.uid, + "cuda", + register=torch.version.hip is None, +) +class CUDAPersistentTMATemplateConfigHeuristic( + TMATemplateConfigMixin, CUDAConfigHeuristic +): + """Persistent TMA template heuristic for CUDA""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use persistent_mm_configs + self.mm_configs = self.persistent_mm_configs + + +@register_template_heuristic( + persistent_mm_template.uid, + "cuda", + register=IS_ROCM, +) +class PersistentMMTemplateConfigHeuristic( + MMTemplateConfigMixin, + ROCmConfigHeuristic, # type: ignore[misc] +): + """Persistent MM template heuristic (no TMA, standard pointer loads)""" + + def __init__(self) -> None: + super().__init__() + self.mm_configs = self.persistent_mm_configs + + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + **kwargs, + ) -> Generator[dict[str, Any], None, None]: + for template_kwargs in super()._get_template_configs_impl( + kernel_inputs, op_name, **kwargs + ): + yield {**template_kwargs, "NUM_SMS": get_num_sms()} + + +@register_template_heuristic( + blackwell_ws_persistent_device_tma_mm_template.uid, + "cuda", + register=torch.version.hip is None, +) +class CUDABlackwellPersistentTMATemplateConfigHeuristic( + BlackwellTMATemplateConfigMixin, CUDAConfigHeuristic +): + """Blackwell Persistent TMA template""" + + def __init__(self) -> None: + super().__init__() + self.mm_configs = self.blackwell_persistent_mm_configs + self.exhaustive_configs = self._generate_exhaustive_configs() + + +@register_template_heuristic( + persistent_tma_mm_template.uid, + "cuda", + register=torch.version.hip is None, + op_name="addmm", +) +class CUDAAddmmPersistentTMATemplateConfigHeuristic( + AddMMConfigMixin, CUDAPersistentTMATemplateConfigHeuristic +): + """Addmm specific mixin for CUDA""" + + +@register_template_heuristic( + blackwell_ws_persistent_device_tma_mm_template.uid, + "cuda", + register=torch.version.hip is None, + op_name="addmm", +) +class CUDABlackwellAddmmPersistentTMATemplateConfigHeuristic( + AddMMConfigMixin, CUDABlackwellPersistentTMATemplateConfigHeuristic +): + """Addmm extension for DataCenter Blackwell Templates""" + + def __init__(self) -> None: + super().__init__() + # NOTE: to ensure that we pass tests, addmm needs a small config + self.mm_configs = ( + self.blackwell_persistent_mm_configs + + self.blackwell_persistent_addmm_configs + ) + self.exhaustive_configs = self._generate_exhaustive_configs() + + +@register_template_heuristic( + mm_template.uid, "cuda", register=torch.version.hip is None, op_name="scaled_mm" +) +class CUDAScaledMMTemplateConfigHeuristic(ScaledMMConfigMixin, CUDAConfigHeuristic): + """Scaled MM template heuristic for CUDA""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use scaled_mm_configs + self.mm_configs = self.scaled_mm_configs + + def _filter_configs(self, configs: list[BaseConfig]) -> list[BaseConfig]: + configs = [c for c in configs if c.block_k >= 32] + return super()._filter_configs(configs) + + +@register_template_heuristic( + scaled_mm_device_tma_epilogue_scaling_template.uid, + "cuda", + register=torch.version.hip is None, + op_name="scaled_mm", +) +class CUDAScaledTMAEpilogueScalingTemplateConfigHeuristic( + ScaledTMAConfigMixin, CUDAConfigHeuristic +): + """Scaled TMA template heuristic for CUDA: epilogue scaling variants (TensorWise, RowWise)""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use scaled_persistent_mm_configs for TMA + self.mm_configs = self.scaled_persistent_mm_configs + + +@register_template_heuristic( + scaled_mm_device_tma_main_loop_scaling_template.uid, + "cuda", + register=torch.version.hip is None, + op_name="scaled_mm", +) +class CUDAScaledTMAMainLoopScalingTemplateConfigHeuristic( + ScaledTMAConfigMixin, CUDAConfigHeuristic +): + """ + Scaled TMA template heuristic for CUDA: + main loop scaling variants (BlockWise1x128, BlockWise1x32, BlockWise1x16, BlockWise128x128) + """ + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use scaled_persistent_mm_configs for TMA + self.mm_configs = self.scaled_persistent_mm_configs + + def _get_template_configs_impl( + self, + kernel_inputs: KernelInputs, + op_name: str, + **kwargs, + ) -> Generator[dict[str, Any], None, None]: + """ + Generate main loop scaling kernel inputs. + """ + mat_a, mat_b, scale_a, scale_b = kernel_inputs._input_nodes + scale_a_size, scale_b_size = scale_a.get_size(), scale_b.get_size() + + scale_option_a, scale_option_b = get_scaling_options( + mat_a, mat_b, scale_a_size, scale_b_size + ) + tile_size_a = get_tile_size(scale_option_a) + tile_size_b = get_tile_size(scale_option_b) + + # Get base scaled MM template configs from superclass + for template_kwargs in super()._get_template_configs_impl( + kernel_inputs, + op_name, + **kwargs, + ): + # Add scaling-specific options for main loop scaling variants + + # Inductor templates require compile-time constants passed in as tl.constexpr values. + # In cases in which the block size (BLOCK_*) is smaller than the tile size (128, 32, 16), + # scales must be broadcasted to BLOCK_* (rather than to a tile_sizextile_size chunk). + + template_kwargs["TILE_SIZE_A"] = tile_size_a + template_kwargs["TILE_SIZE_B"] = tile_size_b + + template_kwargs["MIN_BLOCK_TILE_AM"] = min( + template_kwargs["BLOCK_M"], tile_size_a + ) + template_kwargs["MIN_BLOCK_TILE_AK"] = min( + template_kwargs["BLOCK_K"], tile_size_a + ) + template_kwargs["MIN_BLOCK_TILE_BK"] = min( + template_kwargs["BLOCK_K"], tile_size_b + ) + template_kwargs["MIN_BLOCK_TILE_BN"] = min( + template_kwargs["BLOCK_N"], tile_size_b + ) + + yield template_kwargs + + +@register_template_heuristic( + # regular Blackwell MM template + scaling epilogue from ScaledMMConfigMixin + blackwell_ws_persistent_device_tma_mm_template.uid, + "cuda", + register=torch.version.hip is None, + op_name="scaled_mm", +) +class CUDAScaledBlackwellTMATemplateConfigHeuristic( + ScaledBlackwellTMAConfigMixin, CUDAConfigHeuristic +): + """Scaled Blackwell TMA template heuristic for CUDA""" + + def __init__(self) -> None: + super().__init__() + self.mm_configs = self.blackwell_scaled_persistent_mm_configs + + +@register_template_heuristic( + mm_plus_mm_template.uid, + "cuda", + register=torch.version.hip is None, +) +class CUDAMMPlusMMTemplateConfigHeuristic( + MMPlusMMTemplateConfigMixin, CUDAConfigHeuristic +): + """MM Plus MM template heuristic for CUDA""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use mm_plus_mm_configs + self.mm_configs = self.mm_plus_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.mm_plus_mm_configs + + +@register_template_heuristic( + mm_template.uid, + "cuda", + register=torch.version.hip is None, + op_name="int_mm", +) +class CUDAInt8MMTemplateConfigHeuristic(INT8MMTemplateConfigMixin, CUDAConfigHeuristic): + """Int8 MM template heuristic for CUDA""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use int8_mm_configs + self.mm_configs = self.int8_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.int8_mm_configs + + +# ROCm template-specific classes + + +@register_template_heuristic( + mm_template.uid, + "cuda", + register=IS_ROCM, +) +@register_template_heuristic( + bmm_template.uid, + "cuda", + register=IS_ROCM, +) +class ROCmMMTemplateConfigHeuristic(MMTemplateConfigMixin, ROCmConfigHeuristic): + """Standard MM template heuristic for ROCm""" + + +# TODO(coconutruben): replace with template.name once templates are importable +@register_template_heuristic(mm_template.uid, "cuda", register=IS_ROCM, op_name="addmm") +# TODO(coconutruben): replace with template.name once templates are importable +@register_template_heuristic( + bmm_template.uid, "cuda", register=IS_ROCM, op_name="baddbmm" +) +class ROCmAddMMTemplateConfigHeuristic(AddMMConfigMixin, ROCmMMTemplateConfigHeuristic): + """Addmm specific mixin for ROCm""" + + +@register_template_heuristic( + persistent_mm_template.uid, + "cuda", + register=IS_ROCM, + op_name="addmm", +) +class ROCmAddMMPersistentTemplateConfigHeuristic( + AddMMConfigMixin, PersistentMMTemplateConfigHeuristic +): + """Addmm specific mixin for persistent MM on ROCm""" + + +# TODO(coconutruben): deprecate once autoheuristic is deprecated +@register_template_heuristic("mm-ah", "cuda", register=IS_ROCM) +class ROCmMMAHTemplateConfigHeuristic(MMTemplateConfigMixin, ROCmConfigHeuristic): + """Standard MM template heuristic for ROCm using the extra mm configs only (for autoheuristic)""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use scaled_mm_configs + self.mm_configs = self.extra_mm_configs + self.exhaustive_configs = self.extra_mm_configs + + +@register_template_heuristic( + mm_template.uid, + "cuda", + register=IS_ROCM, + op_name="scaled_mm", +) +class ROCmScaledMMTemplateConfigHeuristic(ScaledMMConfigMixin, ROCmConfigHeuristic): + """Scaled MM template heuristic for ROCm (non-TMA)""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use scaled_mm_configs + self.mm_configs = self.scaled_mm_configs + + def _filter_configs(self, configs: list[BaseConfig]) -> list[BaseConfig]: + configs = [c for c in configs if c.block_k >= 32] + return super()._filter_configs(configs) + + +@register_template_heuristic( + mm_template.uid, + "cuda", + register=IS_ROCM, + op_name="int_mm", +) +class ROCmInt8MMTemplateConfigHeuristic(INT8MMTemplateConfigMixin, ROCmConfigHeuristic): + """Int8 MM template heuristic for ROCm""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use int8_mm_configs + self.mm_configs = self.int8_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.int8_mm_configs + + +@register_template_heuristic( + mm_plus_mm_template.uid, + "cuda", + register=IS_ROCM, +) +class ROCmMMPlusMMTemplateConfigHeuristic( + MMPlusMMTemplateConfigMixin, ROCmConfigHeuristic +): + """MM Plus MM template heuristic for ROCm""" + + def __init__(self) -> None: + super().__init__() + # self.default_num_stages is used to make sure all configs have that in ROCm land + # for mm_plus_mm, we actually just want stages = 1, as pipelining brings no benefits + self.default_num_stages = 1 + # Override mm_configs to use mm_plus_mm_configs + self.mm_configs = self.mm_plus_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.mm_plus_mm_configs + + +# CPU template-specific classes + + +@register_template_heuristic(mm_template.uid, "cpu") +@register_template_heuristic(bmm_template.uid, "cpu") +class CPUMMTemplateConfigHeuristic(MMTemplateConfigMixin, CPUConfigHeuristic): + """Standard MM template heuristic for CPU""" + + +@register_template_heuristic(mm_template.uid, "cpu", op_name="addmm") +@register_template_heuristic(bmm_template.uid, "cpu", op_name="baddbmm") +class CPUAddmmTemplateConfigHeuristic(AddMMConfigMixin, CPUMMTemplateConfigHeuristic): + """Addmm specific mixin for CPU""" + + +@register_template_heuristic(mm_template.uid, "cpu", op_name="scaled_mm") +class CPUScaledMMTemplateConfigHeuristic(ScaledMMConfigMixin, CPUConfigHeuristic): + """Scaled MM template heuristic for CPU (non-TMA)""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use scaled_mm_configs + self.mm_configs = self.scaled_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.scaled_mm_configs + + +@register_template_heuristic(mm_template.uid, "cpu", op_name="int_mm") +class CPUInt8MMTemplateConfigHeuristic(INT8MMTemplateConfigMixin, CPUConfigHeuristic): + """Int8 MM template heuristic for CPU""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use int8_mm_configs + self.mm_configs = self.int8_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.int8_mm_configs + + +@register_template_heuristic(mm_plus_mm_template.uid, "cpu") +class CPUMMPlusMMTemplateConfigHeuristic( + MMPlusMMTemplateConfigMixin, CPUConfigHeuristic +): + """MM Plus MM template heuristic for CPU""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use mm_plus_mm_configs + self.mm_configs = self.mm_plus_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.mm_plus_mm_configs + + +# XPU template-specific classes + + +@register_template_heuristic(mm_template.uid, "xpu") +@register_template_heuristic(bmm_template.uid, "xpu") +class XPUMMTemplateConfigHeuristic(MMTemplateConfigMixin, XPUConfigHeuristic): + """Standard MM template heuristic for XPU""" + + def __init__(self) -> None: + super().__init__() + + # TODO(etaf): Design proper exhaustive search space for XPU. + self.exhaustive_configs = self.mm_configs + + +@register_template_heuristic(mm_template.uid, "xpu", op_name="addmm") +@register_template_heuristic(bmm_template.uid, "xpu", op_name="baddbmm") +class XPUAddmmTemplateConfigHeuristic(AddMMConfigMixin, XPUMMTemplateConfigHeuristic): + """Addmm specific mixin for XPU""" + + +@register_template_heuristic( + persistent_tma_mm_template.uid, + "xpu", +) +class XPUPersistentTMATemplateConfigHeuristic( + TMATemplateConfigMixin, XPUConfigHeuristic +): + """Persistent TMA template heuristic for XPU""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use persistent_mm_configs + self.mm_configs = self.persistent_mm_configs + + +@register_template_heuristic(persistent_tma_mm_template.uid, "xpu", op_name="addmm") +class XPUAddmmPersistentTMATemplateConfigHeuristic( + AddMMConfigMixin, XPUPersistentTMATemplateConfigHeuristic +): + """Addmm specific mixin for XPU""" + + +@register_template_heuristic(mm_template.uid, "xpu", op_name="scaled_mm") +class XPUScaledMMTemplateConfigHeuristic(ScaledMMConfigMixin, XPUConfigHeuristic): + """Scaled MM template heuristic for XPU (non-TMA)""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use scaled_mm_configs + self.mm_configs = self.scaled_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.scaled_mm_configs + + +@register_template_heuristic(mm_template.uid, "xpu", op_name="int_mm") +class XPUInt8MMTemplateConfigHeuristic(INT8MMTemplateConfigMixin, XPUConfigHeuristic): + """Int8 MM template heuristic for XPU""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use int8_mm_configs + self.mm_configs = self.int8_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.int8_mm_configs + + +@register_template_heuristic(mm_plus_mm_template.uid, "xpu") +class XPUMMPlusMMTemplateConfigHeuristic( + MMPlusMMTemplateConfigMixin, XPUConfigHeuristic +): + """MM Plus MM template heuristic for XPU""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use mm_plus_mm_configs + self.mm_configs = self.mm_plus_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.mm_plus_mm_configs + + +# MTIA template-specific classes + + +@register_template_heuristic(mm_template.uid, "mtia") +@register_template_heuristic(bmm_template.uid, "mtia") +class MTIAMMTemplateConfigHeuristic(MMTemplateConfigMixin, MTIAConfigHeuristic): + """Standard MM template heuristic for MTIA""" + + +@register_template_heuristic(mm_template.uid, "mtia", op_name="addmm") +@register_template_heuristic(bmm_template.uid, "mtia", op_name="baddbmm") +class MTIAAddMMTemplateConfigHeuristic(AddMMConfigMixin, MTIAMMTemplateConfigHeuristic): + """Addmm specific mixin for MTIA""" + + +@register_template_heuristic(mm_template.uid, "mtia", op_name="scaled_mm") +class MTIAScaledMMTemplateConfigHeuristic(ScaledMMConfigMixin, MTIAConfigHeuristic): + """Scaled MM template heuristic for MTIA (non-TMA)""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use scaled_mm_configs + self.mm_configs = self.scaled_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.scaled_mm_configs + + +@register_template_heuristic(mm_template.uid, "mtia", op_name="int_mm") +class MTIAInt8MMTemplateConfigHeuristic(INT8MMTemplateConfigMixin, MTIAConfigHeuristic): + """Int8 MM template heuristic for MTIA""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use int8_mm_configs + self.mm_configs = self.int8_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.int8_mm_configs + + +@register_template_heuristic(mm_plus_mm_template.uid, "mtia") +class MTIAMMPlusMMTemplateConfigHeuristic( + MMPlusMMTemplateConfigMixin, MTIAConfigHeuristic +): + """MM Plus MM template heuristic for MTIA""" + + def __init__(self) -> None: + super().__init__() + # Override mm_configs to use mm_plus_mm_configs + self.mm_configs = self.mm_plus_mm_configs + # NOTE: overriding exhaustive configs here to be the same as mm_configs + # as we haven't validated exhaustive support here yet + # TODO(coconutruben): remove this once we have validated exhaustive support + # for scaled_mm + self.exhaustive_configs = self.mm_plus_mm_configs diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/triton_addmm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/triton_addmm.py new file mode 100644 index 0000000000000000000000000000000000000000..cfc4fe135b85a865143c0bec0fe344fe8289ce7b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/triton_addmm.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from typing import Any, TYPE_CHECKING + +from ...kernel.mm_common import addmm_epilogue +from .base import TemplateConfigHeuristics + + +if TYPE_CHECKING: + from ...kernel_inputs import KernelInputs + + +class AddMMConfigMixin(TemplateConfigHeuristics): + """ + Simple mixin to handle scalars for addmm like operators (addmm, baddbmm) + """ + + def get_extra_kwargs( + self, + kernel_inputs: KernelInputs, + op_name: str, + ) -> dict[str, Any]: + kwargs = super().get_extra_kwargs(kernel_inputs, op_name) + if op_name not in ["addmm", "baddbmm"]: + raise AssertionError(f"op_name={op_name} invalid for AddMMConfigMixin") + alpha = kernel_inputs.get_scalar("alpha") + beta = kernel_inputs.get_scalar("beta") + return { + **kwargs, + "epilogue_fn": addmm_epilogue(kernel_inputs.out_dtype(), alpha, beta), + "epilogue_fn_hash": str( + ["addmm_epilogue", kernel_inputs.out_dtype(), alpha, beta] + ), + "prefix_args": 1, + } diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..575157d85838f276552c320b859012f2ac5c7f84 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/__init__.py @@ -0,0 +1,27 @@ +""" +Codegen heuristics for inductor-generated Triton kernels. + +These heuristics control autotuning config generation for runtime-compiled +kernels: pointwise, reduction, persistent_reduction, etc. + +Device dispatch uses the shared registry in heuristics/registry.py +with name-based keys (e.g., "pointwise"). +""" + +from __future__ import annotations + +from torch._inductor.heuristics.registry import ( + CodegenConfigHeuristics, + get_codegen_heuristic, + register_codegen_heuristic, +) + +# Import submodules to trigger registration +from . import pointwise as pointwise, reduction as reduction + + +__all__ = [ + "CodegenConfigHeuristics", + "get_codegen_heuristic", + "register_codegen_heuristic", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38f6af836c9790269b41987d12ec05abf5b9c24c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/__pycache__/pointwise.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/__pycache__/pointwise.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f797430d2dec287bbe8015f24a8f3609baa7041 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/__pycache__/pointwise.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/__pycache__/reduction.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/__pycache__/reduction.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a25b671aa3a0e218aabfc6b418676b86bc1b024d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/__pycache__/reduction.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/pointwise.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/pointwise.py new file mode 100644 index 0000000000000000000000000000000000000000..4e014e9d1d3714ceda12d017ade719c632c812a3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/pointwise.py @@ -0,0 +1,246 @@ +"""Codegen heuristics for Triton pointwise kernel autotuning. + +Contains the default (CUDA) heuristic and device-specific overrides for +ROCm/HIP and XPU. Subclasses override only the dimension methods that +differ from the base. +""" + +from __future__ import annotations + +from typing import Any, TYPE_CHECKING + +import torch +from torch._inductor.heuristics.registry import ( + CodegenConfigHeuristics, + register_codegen_heuristic, +) +from torch._inductor.runtime.hints import TileHint, TRITON_MAX_BLOCK + + +if TYPE_CHECKING: + from collections.abc import Callable + + +# ---------------------------------------------------------------------- +# Default (CUDA) pointwise heuristic +# ---------------------------------------------------------------------- + + +@register_codegen_heuristic("pointwise") +class PointwiseHeuristic(CodegenConfigHeuristics): + """Default pointwise autotuning configs (CUDA non-ROCm).""" + + def get_configs( + self, + size_hints: dict[str, int], + bs: int, + triton_config_fn: Callable[..., Any], + hinted_configs: list[Any], + tile_hint: TileHint | None = None, + inductor_meta: dict[str, Any] | None = None, + ) -> list[Any]: + inductor_meta = inductor_meta or {} + n = len(size_hints) + if n == 1: + return self._configs_1d( + size_hints, bs, hinted_configs, triton_config_fn, inductor_meta + ) + if n == 2: + return self._configs_2d( + size_hints, + bs, + hinted_configs, + triton_config_fn, + tile_hint, + inductor_meta, + ) + if n == 3: + return self._configs_3d( + size_hints, bs, hinted_configs, triton_config_fn, inductor_meta + ) + raise NotImplementedError(f"size_hints: {size_hints}") + + def _configs_1d( + self, size_hints, bs, hinted_configs, triton_config_fn, inductor_meta + ): + if not inductor_meta.get("autotune_pointwise", True) and not ( + inductor_meta.get("max_autotune") + or inductor_meta.get("max_autotune_pointwise") + ): + return [triton_config_fn(size_hints, bs)] + return [ + triton_config_fn(size_hints, bs, num_elements_per_warp=256), + triton_config_fn(size_hints, bs // 2, num_elements_per_warp=64), + *hinted_configs, + ] + + def _configs_2d( + self, size_hints, bs, hinted_configs, triton_config_fn, tile_hint, inductor_meta + ): + if ( + not inductor_meta.get("autotune_pointwise", True) + or tile_hint == TileHint.SQUARE + ) and not ( + inductor_meta.get("max_autotune") + or inductor_meta.get("max_autotune_pointwise") + ): + return [triton_config_fn(size_hints, 32, 32)] + return [ + triton_config_fn(size_hints, 32, 32), + triton_config_fn(size_hints, 64, 64), # ~8% better for fp16 + triton_config_fn(size_hints, 256, 16), + triton_config_fn(size_hints, 16, 256), + triton_config_fn(size_hints, bs, 1), + triton_config_fn(size_hints, 1, bs), + *hinted_configs, + ] + + def _configs_3d( + self, size_hints, bs, hinted_configs, triton_config_fn, inductor_meta + ): + if not ( + inductor_meta.get("max_autotune") + or inductor_meta.get("max_autotune_pointwise") + ): + return [triton_config_fn(size_hints, 16, 16, 16)] + return [ + triton_config_fn(size_hints, 16, 16, 16), + triton_config_fn(size_hints, 64, 8, 8), + triton_config_fn(size_hints, 8, 64, 8), + triton_config_fn(size_hints, 8, 8, 64), + triton_config_fn(size_hints, bs, 1, 1), + triton_config_fn(size_hints, 1, bs, 1), + triton_config_fn(size_hints, 1, 1, bs), + *hinted_configs, + ] + + +# ---------------------------------------------------------------------- +# ROCm/HIP pointwise heuristic +# ---------------------------------------------------------------------- + + +@register_codegen_heuristic("pointwise", "hip", register=torch.version.hip is not None) +class ROCmPointwiseHeuristic(PointwiseHeuristic): + """Pointwise configs for ROCm/HIP devices. + + Inherits _configs_3d from PointwiseHeuristic (same configs). + """ + + def _configs_1d( + self, size_hints, bs, hinted_configs, triton_config_fn, inductor_meta + ): + configs = super()._configs_1d( + size_hints, bs, hinted_configs, triton_config_fn, inductor_meta + ) + if len(configs) > 1: + configs.extend( + [ + triton_config_fn(size_hints, TRITON_MAX_BLOCK["X"], waves_per_eu=2), + triton_config_fn( + size_hints, + 4096, # wrt: better than the max_block for some kernel + ), + triton_config_fn( + size_hints, + 2048, + num_warps=8, + num_stages=2, + waves_per_eu=1, # 20% improvement + ), + ] + ) + if inductor_meta.get("atomic_add_found"): + configs.append( + triton_config_fn( + size_hints, + 64, + num_warps=1, + num_stages=1, # 250% improvement + ) + ) + return configs + + def _configs_2d( + self, size_hints, bs, hinted_configs, triton_config_fn, tile_hint, inductor_meta + ): + # ROCm doesn't skip autotune for SQUARE tile hints + if not inductor_meta.get("autotune_pointwise", True) and not ( + inductor_meta.get("max_autotune") + or inductor_meta.get("max_autotune_pointwise") + ): + return [triton_config_fn(size_hints, 32, 32)] + return [ + triton_config_fn(size_hints, 32, 32), + triton_config_fn(size_hints, 64, 64), # ~8% better for fp16 + triton_config_fn(size_hints, 256, 16), + triton_config_fn(size_hints, 16, 256), + triton_config_fn(size_hints, bs, 1), + triton_config_fn(size_hints, 1, bs), + *hinted_configs, + triton_config_fn(size_hints, 64, 32), # better for some kernels + triton_config_fn(size_hints, 128, 16), # +10% for some kernels + triton_config_fn(size_hints, 128, 32), # additional 10% more + triton_config_fn(size_hints, 32, 512), # +30% for some kernels + ] + + +# ---------------------------------------------------------------------- +# XPU pointwise heuristic +# ---------------------------------------------------------------------- + + +@register_codegen_heuristic("pointwise", "xpu", register=torch.xpu._is_compiled()) +class XPUPointwiseHeuristic(PointwiseHeuristic): + """Pointwise configs for XPU devices.""" + + def _configs_1d( + self, size_hints, bs, hinted_configs, triton_config_fn, inductor_meta + ): + configs = super()._configs_1d( + size_hints, bs, hinted_configs, triton_config_fn, inductor_meta + ) + if len(configs) > 1: + configs.append( + # intel-xpu-backend-for-triton #5133 + triton_config_fn(size_hints, 32) + ) + return configs + + def _configs_2d( + self, size_hints, bs, hinted_configs, triton_config_fn, tile_hint, inductor_meta + ): + # XPU doesn't skip autotune for SQUARE tile hints + if not inductor_meta.get("autotune_pointwise", True) and not ( + inductor_meta.get("max_autotune") + or inductor_meta.get("max_autotune_pointwise") + ): + return [triton_config_fn(size_hints, 32, 32)] + return [ + triton_config_fn(size_hints, 32, 32), + triton_config_fn(size_hints, 64, 64), # ~8% better for fp16 + triton_config_fn(size_hints, 256, 16), + triton_config_fn(size_hints, 16, 256), + triton_config_fn(size_hints, bs, 1), + triton_config_fn(size_hints, 1, bs), + *hinted_configs, + # intel-xpu-backend-for-triton #5198 + triton_config_fn(size_hints, 32, 32, num_warps=8), + # intel-xpu-backend-for-triton #5199 + triton_config_fn(size_hints, 4, 256), + ] + + def _configs_3d( + self, size_hints, bs, hinted_configs, triton_config_fn, inductor_meta + ): + # XPU always uses full set of configs (no autotune gate) + return [ + triton_config_fn(size_hints, 16, 16, 16), + triton_config_fn(size_hints, 64, 8, 8), + triton_config_fn(size_hints, 8, 64, 8), + triton_config_fn(size_hints, 8, 8, 64), + triton_config_fn(size_hints, bs, 1, 1), + triton_config_fn(size_hints, 1, bs, 1), + triton_config_fn(size_hints, 1, 1, bs), + *hinted_configs, + ] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/reduction.py b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..c9ca2f1849da0b7b7fbd428ee101ebfe4e44cbe7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/heuristics/triton_codegen/reduction.py @@ -0,0 +1,760 @@ +"""Codegen heuristics for Triton reduction kernel autotuning. + +Contains the default (CUDA) heuristic and device-specific overrides for +ROCm/HIP and XPU. Subclasses override only the methods that differ +from the base. +""" + +from __future__ import annotations + +from typing import Any, TYPE_CHECKING + +import torch +from torch._inductor.heuristics.registry import ( + CodegenConfigHeuristics, + register_codegen_heuristic, +) +from torch._inductor.runtime.hints import ReductionHint, TRITON_MAX_BLOCK +from torch._inductor.runtime.runtime_utils import next_power_of_2 +from torch._inductor.utils import prefix_is_reduction +from torch.utils._ordered_set import OrderedSet + + +if TYPE_CHECKING: + from torch._inductor.runtime.triton_compat import Config + + +# ------------------------------------------------------------------ +# Helpers (moved from triton_heuristics.py, only used by reduction) +# ------------------------------------------------------------------ + + +def _get_tiling_scores( + inductor_meta: dict[str, Any], + size_hints: dict[str, int], +) -> dict[str, float]: + """Retrieve tiling scores, providing suitable defaults if missing.""" + return inductor_meta.get("tiling_scores") or dict.fromkeys(size_hints, 1) + + +def _match_target_block_product( + size_hints, + tiling_scores, + target_block_product, + min_block_size=1, + min_red_block: int | None = 4, +): + """ + Distribute block sizes across dimensions according to tiling scores, + aiming to match a target product of block sizes. + """ + min_red_block = ( + min_block_size if min_red_block is None else max(min_red_block, min_block_size) + ) + total_score = sum(tiling_scores.values()) + if total_score == 0: + min_block_size = 1 + tiling_scores = dict.fromkeys(tiling_scores.keys(), target_block_product) + total_score = target_block_product * len(tiling_scores) + + block_sizes: dict[str, int] = {} + relative_scores: dict[str, float] = {} + curr_block_product = 1 + + for dim, score in tiling_scores.items(): + if score == 0 and "r" not in dim: + block_sizes[dim] = 1 + relative_scores[dim] = 0 + continue + + size = min_block_size if "r" not in dim else min_red_block + block_sizes[dim] = size + curr_block_product *= size + relative_scores[dim] = score / total_score + + while curr_block_product < target_block_product and relative_scores: + dim, score = max(relative_scores.items(), key=lambda item: item[1]) + + if ( + block_sizes[dim] >= TRITON_MAX_BLOCK[dim.capitalize()] + or block_sizes[dim] >= size_hints[dim] + ): + del relative_scores[dim] + continue + + block_sizes[dim] *= 2 + relative_scores[dim] /= 2 + curr_block_product *= 2 + + return block_sizes + + +def _adapt_config_for_tiling( + size_hints, + tiling_scores, + original_x, + original_r, + num_warps=None, + num_stages=1, + register_intensive=False, + persistent_reduction=False, + waves_per_eu=None, + *, + warp_size: int = 32, +) -> Config: + """ + Create an adapted configuration based on tiling scores, + redistributing the same total block size (x * r) according to tiling scores. + """ + from torch._inductor.runtime.triton_heuristics import triton_config_tiled_reduction + + if not all(s in tiling_scores for s in size_hints): + raise AssertionError( + f"Missing size_hints in tiling_scores: {OrderedSet(size_hints) - OrderedSet(tiling_scores)}" + ) + target_block_product = original_x * original_r + block_sizes = _match_target_block_product( + size_hints, tiling_scores, target_block_product + ) + + return triton_config_tiled_reduction( + size_hints, + block_sizes["x"], + block_sizes["y"], + block_sizes["r0_"], + num_stages=num_stages, + register_intensive=register_intensive, + waves_per_eu=waves_per_eu, + warp_size=warp_size, + ) + + +def _outer_config_opt( + make_config, size_hints, rnumel, inductor_meta, num_dynamic, register_intensive +): + """Optimized outer config for CUDA (non-HIP).""" + max_x_block, x_block = 256, 64 + load_factor = inductor_meta.get("num_load", 0) + x = size_hints["x"] + num_warps = None + + if x <= 1024: + x_block = max(min(x // 128, 8), 2) + outer_r_block = min(rnumel, 64) + elif x // 4096 <= 8: + x_block = 16 + outer_r_block = 512 // x_block + elif num_dynamic > 1: + outer_r_block = max(min((rnumel // 64), 64), 8) + elif num_dynamic == 1: + outer_r_block = ( + 1 if load_factor >= 3 else min(next_power_of_2(max(rnumel, 128) // 128), 8) + ) + else: + x_block = max(min(max_x_block, next_power_of_2(x // 4096)), x_block) + if load_factor < 4 or rnumel <= 128: + outer_r_block = 512 // x_block + else: + if rnumel >= 2048: + outer_r_block = 64 + else: + outer_r_block = 32 + x_block = min(x_block, 32) + num_warps = 4 + + return make_config( + x_block, + outer_r_block, + num_warps=num_warps, + register_intensive=register_intensive, + ) + + +# ------------------------------------------------------------------ +# Default (CUDA) reduction heuristic +# ------------------------------------------------------------------ + + +@register_codegen_heuristic("reduction") +class ReductionHeuristic(CodegenConfigHeuristics): + """Default reduction autotuning configs (CUDA non-ROCm).""" + + def get_configs( + self, + *, + size_hints: dict[str, int], + inductor_meta: dict[str, Any], + triton_meta: dict[str, Any], + num_dynamic: int = 0, + ) -> list[Config]: + """Generate non-persistent reduction autotuning configs.""" + from torch._inductor.runtime.triton_heuristics import ( + get_total_reduction_numel, + make_matmul_triton_config, + triton_config_reduction, + triton_native_bmm_configs, + triton_native_mm_configs, + ) + + reduction_hint = inductor_meta.get("reduction_hint") + rnumel = get_total_reduction_numel(size_hints) + + max_autotune_enabled = inductor_meta.get("max_autotune") or inductor_meta.get( + "max_autotune_pointwise" + ) + + register_intensive = False + loads_and_red = inductor_meta.get("num_load", 0) + inductor_meta.get( + "num_reduction", 0 + ) + + device_major = triton_meta["device"].major + warp_size = triton_meta["device"].warp_size_or_default + MAX_R0_BLOCK = 1024 if device_major is not None and device_major >= 10 else 2048 + if size_hints["x"] >= 1024 and loads_and_red >= 10: + MAX_R0_BLOCK = 1024 + register_intensive = True + + if triton_meta.get("native_matmul"): + if len(size_hints) == 3: + return [ + make_matmul_triton_config(sizes, num_warps, num_stages) + for sizes, num_warps, num_stages in triton_native_mm_configs + ] + elif len(size_hints) == 4: + return [ + make_matmul_triton_config(sizes, num_warps, num_stages) + for sizes, num_warps, num_stages in triton_native_bmm_configs + ] + else: + raise NotImplementedError("native matmul only supports mm/bmm pattern") + + def make_config( + x, + r, + num_warps=None, + num_stages=1, + register_intensive=False, + dynamic_scale_rblock=True, + waves_per_eu=None, + ): + if "y" in size_hints: + tiling_scores = _get_tiling_scores(inductor_meta, size_hints) + return _adapt_config_for_tiling( + size_hints, + tiling_scores, + x, + r, + num_warps=num_warps, + num_stages=num_stages, + register_intensive=register_intensive, + waves_per_eu=waves_per_eu, + warp_size=warp_size, + ) + else: + return triton_config_reduction( + size_hints, + x, + r, + num_warps=num_warps, + num_stages=num_stages, + register_intensive=register_intensive, + waves_per_eu=waves_per_eu, + dynamic_scale_rblock=dynamic_scale_rblock, + reduction_hint=reduction_hint, + warp_size=warp_size, + ) + + contiguous_config = make_config( + # Default XBLOCK=2 launches too few programs to fill + # the device. Prefer XBLOCK=1 so the autotuner has a candidate + # that can saturate all CUs. + 1 + if (torch.version.hip and size_hints.get("x", 0) <= 64) + else (2 if rnumel <= 2048 else 1), + min(rnumel, MAX_R0_BLOCK), + register_intensive=register_intensive, + ) + tiny_config = make_config( + 2 * (256 // rnumel) if rnumel <= 256 else 1, + min(rnumel, MAX_R0_BLOCK), + register_intensive=register_intensive, + ) + + outer_config = self._get_outer_config( + make_config, + size_hints, + rnumel, + inductor_meta, + num_dynamic, + register_intensive, + ) + + configs: list[Config] = [] + + if inductor_meta.get("add_persistent_rblock") and loads_and_red <= 8: + xnumel = max(4096 // rnumel, 1) + c = make_config( + xnumel, + min(rnumel, 32768), + register_intensive=register_intensive, + dynamic_scale_rblock=False, + ) + configs.append(c) + + # For 3d tiling, default to more autotuning initially + if "y" in size_hints: + pass + elif max_autotune_enabled: + pass + elif reduction_hint == ReductionHint.INNER: + return configs + [contiguous_config] + elif reduction_hint == ReductionHint.OUTER: + return configs + [outer_config] + elif reduction_hint == ReductionHint.OUTER_TINY: + return configs + [tiny_config] + + result_configs = configs + [ + contiguous_config, + outer_config, + tiny_config, + make_config(64, 64), + make_config(8, 512), + make_config(64, 4, num_warps=8), + ] + + return self._finalize_configs( + result_configs, make_config, size_hints, inductor_meta + ) + + def get_persistent_configs( + self, + *, + size_hints: dict[str, int], + reduction_hint: Any = False, + inductor_meta: dict[str, Any], + triton_meta: dict[str, Any], + ) -> list[Config]: + """Generate persistent reduction autotuning configs.""" + from torch._inductor.runtime.triton_heuristics import ( + get_total_reduction_numel, + make_matmul_triton_config, + triton_config_reduction, + triton_config_tiled_reduction, + triton_native_persistent_bmm_configs, + triton_native_persistent_mm_configs, + ) + + inductor_meta = {} if inductor_meta is None else inductor_meta + # Under deterministic mode, canonicalize the batch-dim hint so the + # candidate-config branching below (e.g. xnumel // 8 < 128) doesn't pick + # a different (XBLOCK, num_warps) for bs=N vs bs=N/2. Different picks + # change the bf16 reduction order and break batch invariance in + # persistent reductions like LayerNorm. + if inductor_meta.get("batch_invariant"): + size_hints = dict(size_hints) + if "x" in size_hints: + size_hints["x"] = max(size_hints["x"], 4096) + + xnumel = size_hints["x"] + rnumel = get_total_reduction_numel(size_hints) + + MAX_PERSISTENT_BLOCK_NUMEL = 4096 + warp_size = triton_meta["device"].warp_size_or_default + + if triton_meta.get("native_matmul"): + from torch._inductor.runtime.hints import native_matmul_persistent_rblock + from torch._inductor.runtime.triton_heuristics import ( + _cap_native_matmul_configs, + ) + + native_matmul_rblock = inductor_meta.get("native_matmul_persistent_rblock") + if native_matmul_rblock is None: + native_matmul_rblock = native_matmul_persistent_rblock(rnumel) + + if len(size_hints) == 3: + configs = [ + make_matmul_triton_config(sizes, num_warps, num_stages) + for sizes, num_warps, num_stages in triton_native_persistent_mm_configs + ] + return _cap_native_matmul_configs(configs, native_matmul_rblock) + elif len(size_hints) == 4: + configs = [ + make_matmul_triton_config(sizes, num_warps, num_stages) + for sizes, num_warps, num_stages in triton_native_persistent_bmm_configs + ] + return _cap_native_matmul_configs(configs, native_matmul_rblock) + else: + raise NotImplementedError("native matmul only supports mm/bmm pattern") + + max_autotune_enabled = inductor_meta.get("max_autotune") or inductor_meta.get( + "max_autotune_pointwise" + ) + + xblock_vals = self._persistent_xblock_vals() + + if "y" not in size_hints: + configs = [ + triton_config_reduction( + size_hints, + xblock, + rnumel, + register_intensive=True, + reduction_hint=reduction_hint, + warp_size=warp_size, + ) + for xblock in xblock_vals + if xblock == 1 + or (rnumel * xblock <= MAX_PERSISTENT_BLOCK_NUMEL and xblock <= xnumel) + ] + else: + configs = [] + tiling_scores = _get_tiling_scores(inductor_meta, size_hints) + x_y_scores = {dim: tiling_scores[dim] for dim in ("x", "y")} + for target_block_size in xblock_vals: + if target_block_size * rnumel > MAX_PERSISTENT_BLOCK_NUMEL: + continue + + block_sizes = _match_target_block_product( + size_hints, x_y_scores, target_block_size + ) + configs.append( + triton_config_tiled_reduction( + size_hints, + block_sizes["x"], + block_sizes["y"], + rnumel, + warp_size=warp_size, + ) + ) + + tiny_configs = [ + triton_config_reduction( + size_hints, + 2 * (256 // rnumel) if rnumel <= 256 else 1, + rnumel, + warp_size=warp_size, + ) + ] + + # Defer to more autotuning for 3d tiling + if "y" in size_hints: + pass + elif not max_autotune_enabled: + if reduction_hint == ReductionHint.INNER and rnumel >= 256: + if ( + rnumel > 1024 + or xnumel // 8 < 128 + or inductor_meta.get("RSPLIT_SIZE") + ): + configs = configs[:1] + else: + configs = self._persistent_inner_config( + size_hints, + rnumel, + xnumel, + inductor_meta, + reduction_hint, + warp_size, + ) + elif reduction_hint == ReductionHint.OUTER: + configs = configs[-1:] + elif reduction_hint == ReductionHint.OUTER_TINY: + configs = tiny_configs + else: + configs = self._persistent_max_autotune_extras(configs, tiny_configs) + + for c in configs: + for p in size_hints: + if prefix_is_reduction(p): + c.kwargs.pop(f"{p.upper()}BLOCK") # type: ignore[union-attr] + + return configs + + # ------------------------------------------------------------------ + # Hook methods for device-specific overrides + # ------------------------------------------------------------------ + + def _get_outer_config( + self, + make_config, + size_hints, + rnumel, + inductor_meta, + num_dynamic, + register_intensive, + ): + """Outer config. CUDA uses optimized heuristic.""" + return _outer_config_opt( + make_config, + size_hints, + rnumel, + inductor_meta, + num_dynamic, + register_intensive, + ) + + def _finalize_configs(self, configs, make_config, size_hints, inductor_meta): + """Post-process non-persistent configs.""" + return configs + + def _persistent_xblock_vals(self) -> list[int]: + """XBLOCK values for persistent reduction.""" + return [1, 8, 32, 128] + + def _persistent_inner_config( + self, + size_hints, + rnumel, + xnumel, + inductor_meta, + reduction_hint, + warp_size: int = 32, + ) -> list[Config]: + """Config for INNER hint in persistent reduction.""" + from torch._inductor.runtime.triton_heuristics import triton_config_reduction + + x_block = min(1024 // rnumel, 8) + return [ + triton_config_reduction( + size_hints, + x_block, + rnumel, + register_intensive=True, + num_warps=1, + min_num_warps=1, + reduction_hint=reduction_hint, + warp_size=warp_size, + ) + ] + + def _persistent_max_autotune_extras(self, configs, tiny_configs): + """Extra processing in max_autotune mode for persistent reduction.""" + return configs + + def get_cooperative_configs( + self, + *, + size_hints: dict[str, int], + reduction_hint: Any, + inductor_meta: dict[str, Any], + triton_meta: dict[str, Any], + ) -> list[Config]: + """Generate configs for cooperative reduction (RSPLIT).""" + from torch._inductor.runtime.hints import TRITON_MAX_RSPLIT + from torch._inductor.runtime.runtime_utils import last_power_of_2 + + # Cooperative reductions currently only support a single reduction dimension. + if len(size_hints) != 2: + raise AssertionError( + "Cooperative reductions don't support tiling reduction dims" + ) + xnumel, rnumel = size_hints["x"], size_hints["r0_"] + + target = last_power_of_2(triton_meta["device"].multi_processor_count) + split = max(1, min((rnumel, target // xnumel, TRITON_MAX_RSPLIT))) + if inductor_meta["persistent_reduction"]: + configs = self.get_persistent_configs( + size_hints={"x": xnumel, "r0_": rnumel // split}, + reduction_hint=reduction_hint, + inductor_meta=inductor_meta, + triton_meta=triton_meta, + ) + else: + configs = self.get_configs( + size_hints={"x": xnumel, "r0_": rnumel // split}, + inductor_meta=inductor_meta, + triton_meta=triton_meta, + ) + for config in configs: + config.kwargs["RSPLIT"] = split # type: ignore[union-attr] + return configs + + def apply_rsplit_size( + self, + configs: list[Config], + *, + size_hints: dict[str, int], + inductor_meta: dict[str, Any], + ) -> list[Config]: + """Apply RSPLIT_SIZE / mix-order post-processing to persistent configs.""" + import copy + + from torch._inductor.runtime.triton_heuristics import unique_configs + + max_autotune_enabled = inductor_meta.get("max_autotune") or inductor_meta.get( + "max_autotune_pointwise" + ) + + rsplit_size = inductor_meta.get("RSPLIT_SIZE") + if not rsplit_size: + return configs + + rnumel_hint = size_hints["r0_"] + min_x_block = 1 + if rnumel_hint <= 512: + min_x_block = 4 + required_x_block = 1 + if ( + tma_min_block_sizes := inductor_meta.get("tma_min_block_sizes") + ) is not None: + required_x_block = max( + required_x_block, tma_min_block_sizes.get("XBLOCK", 1) + ) + x_block = min(max(rsplit_size // 32, min_x_block, required_x_block), 16) + + new_configs: list[Config] = [] + for c in configs: + c.kwargs["RSPLIT_SIZE"] = rsplit_size # type: ignore[union-attr] + c.kwargs["XBLOCK"] = x_block # type: ignore[union-attr] + + num_iters = rsplit_size // x_block + + if inductor_meta.get("mix_order_reduction_allow_multi_stages", True): + MAX_NUM_STAGES = 2 if rnumel_hint > 8192 else 3 + else: + MAX_NUM_STAGES = 1 + # Triton's tl.range pipeliner cannot predicate the ttng.tensormap_create + # emitted by device-side descriptors. + if inductor_meta.get("uses_device_tma"): + MAX_NUM_STAGES = 1 + c.kwargs["NUM_STAGES"] = min( # type: ignore[union-attr] + max(num_iters // 4, 1), MAX_NUM_STAGES + ) + + if rnumel_hint <= 1024: + c.num_warps //= 2 # type: ignore[union-attr] + c.num_warps = max(c.num_warps, 1) # type: ignore[union-attr] + new_configs.append(c) + + if max_autotune_enabled: + newc = copy.deepcopy(c) + newc.num_warps = 2 # type: ignore[union-attr] + new_configs.append(newc) + else: + new_configs.append(c) + + max_warps_limit = self._max_warps_limit() + if max_autotune_enabled and c.num_warps < max_warps_limit: # type: ignore[union-attr] + newc = copy.deepcopy(c) + newc.num_warps *= 2 # type: ignore[union-attr] + new_configs.append(newc) + return unique_configs(new_configs) + + def _max_warps_limit(self) -> int: + """Max warps limit for RSPLIT_SIZE processing.""" + return 32 + + def get_split_scan_configs( + self, + *, + size_hints: dict[str, int], + inductor_meta: dict[str, Any], + triton_meta: dict[str, Any], + ) -> list[Config]: + """Generate configs for split scan kernels.""" + configs = self.get_configs( + size_hints=size_hints, + inductor_meta=inductor_meta, + triton_meta=triton_meta, + ) + min_rblock = inductor_meta.get("min_split_scan_rblock", 256) + for cfg in configs: + for var in list(cfg.kwargs.keys()): # type: ignore[union-attr] + if var.startswith("R") and cfg.kwargs[var] < min_rblock: # type: ignore[union-attr] + cfg.kwargs[var] = min_rblock # type: ignore[union-attr] + return configs + + +# ------------------------------------------------------------------ +# ROCm/HIP reduction heuristic +# ------------------------------------------------------------------ + + +@register_codegen_heuristic("reduction", "hip", register=torch.version.hip is not None) +class ROCmReductionHeuristic(ReductionHeuristic): + """Reduction configs for ROCm/HIP devices.""" + + def _get_outer_config( + self, + make_config, + size_hints, + rnumel, + inductor_meta, + num_dynamic, + register_intensive, + ): + # HIP uses simple outer config (no outer_config_opt) + return make_config(64, 8, register_intensive=register_intensive) + + def _finalize_configs(self, configs, make_config, size_hints, inductor_meta): + hip_configs = [ + make_config(1024, 8, num_warps=4, num_stages=1, waves_per_eu=2), + make_config(512, 8, num_warps=4, num_stages=1, waves_per_eu=1), + ] + configs.extend(hip_configs) + + max_persistent_rblock = inductor_meta.get("max_persistent_rblock", 0) + if max_persistent_rblock > 0: + configs = [ + c + for c in configs + if c.kwargs.get("XBLOCK", 0) * max_persistent_rblock <= 4096 + ] + return configs + + def _persistent_xblock_vals(self) -> list[int]: + return [1, 4, 8, 16, 32, 64, 128, 256] + + def _persistent_max_autotune_extras(self, configs, tiny_configs): + for conf in tiny_configs: + if conf not in configs: + configs.append(conf) + return configs + + def _max_warps_limit(self) -> int: + return 16 + + +# ------------------------------------------------------------------ +# XPU reduction heuristic +# ------------------------------------------------------------------ + + +@register_codegen_heuristic("reduction", "xpu", register=torch.xpu._is_compiled()) +class XPUReductionHeuristic(ReductionHeuristic): + """Reduction configs for XPU devices.""" + + def _persistent_inner_config( + self, + size_hints, + rnumel, + xnumel, + inductor_meta, + reduction_hint, + warp_size: int = 32, + ) -> list[Config]: + from torch._inductor.runtime.triton_heuristics import triton_config_reduction + + # TODO(Intel): CUDA uses num_warps = 1 to disable shared memory. + # We apply different configurations from #168335. + # We currently let cost model in Triton to decide whether to use + # shared memory. + loads_and_stores = inductor_meta.get("num_load", 0) + inductor_meta.get( + "num_store", 0 + ) + x_block = 8 + if xnumel // x_block < 128 or loads_and_stores >= 5: + x_block = 1 + return [ + triton_config_reduction( + size_hints, + x_block, + rnumel, + register_intensive=True, + num_warps=None, + min_num_warps=None, + reduction_hint=None, + warp_size=warp_size, + ) + ] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/hooks.py b/.venv/lib/python3.12/site-packages/torch/_inductor/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..72a935fb5d272adc39e9bf5116f452d66addccdd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/hooks.py @@ -0,0 +1,31 @@ +# mypy: allow-untyped-defs +import contextlib +from collections.abc import Callable +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + import torch + +# Executed in the order they're registered +INTERMEDIATE_HOOKS: list[Callable[[str, "torch.Tensor"], None]] = [] + + +@contextlib.contextmanager +def intermediate_hook(fn): + INTERMEDIATE_HOOKS.append(fn) + try: + yield + finally: + INTERMEDIATE_HOOKS.pop() + + +def run_intermediate_hooks(name, val): + global INTERMEDIATE_HOOKS + hooks = INTERMEDIATE_HOOKS + INTERMEDIATE_HOOKS = [] + try: + for hook in hooks: + hook(name, val) + finally: + INTERMEDIATE_HOOKS = hooks diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/index_propagation.py b/.venv/lib/python3.12/site-packages/torch/_inductor/index_propagation.py new file mode 100644 index 0000000000000000000000000000000000000000..38bf2fab2e6a97834e7a5b8ec00f944ac8f12fb0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/index_propagation.py @@ -0,0 +1,394 @@ +# mypy: allow-untyped-defs +"""This file implements the IndexPropagation ops handler, which wraps an +underlying handler to add a limited form of constant propagation, as well as +propagation of sympy expressions downstream of ops.index_expr calls. + +For example, say we have the IR: + + tmp0 = ops.index_expr(x, torch.int32) + tmp1 = ops.constant(2, torch.int32) + tmp2 = ops.mul(tmp0, tmp1) + tmp3 = ops.indirect_indexing(tmp2, x_size) + tmp4 = ops.load("buf0", tmp3) + +The underlying handler would just see: + + ops.load("buf0", x * 2) + +This is limited by the set of operators handled in the sympy expression +printers. + +""" + +import itertools +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any, Literal, overload, TypeAlias + +import sympy + +import torch +from torch._prims_common import dtype_to_type, is_integer_dtype +from torch.utils._sympy.functions import FloorDiv, Max, Min, ModularIndexing, Where +from torch.utils._sympy.value_ranges import bound_sympy, ValueRanges + +from .ops_handler import DefaultHandler +from .sizevars import statically_known_true +from .utils import generate_assert +from .virtualized import V + + +_ExprType = sympy.Expr | float | int | bool + + +def _is_constant(val: _ExprType): + if isinstance(val, sympy.Basic): + return val.is_number + return isinstance(val, (int, float, bool)) + + +def upper_bound(val: _ExprType): + return bound_sympy(val).upper if isinstance(val, sympy.Expr) else val + + +@dataclass +class TypedExpr: + """A SymPy expression with associated type""" + + expr: _ExprType + dtype: torch.dtype + + def is_constant(self): + return _is_constant(self.expr) + + def __post_init__(self): + if _is_constant(self.expr): + expr = self.expr + if isinstance(expr, sympy.Expr): + expr = expr.expand(identity=True) + expr = dtype_to_type(self.dtype)(expr) + if is_integer_dtype(self.dtype): + bits = torch.iinfo(self.dtype).bits + if self.dtype.is_signed: + expr = expr + 2 ** (bits - 1) + expr = expr % 2**bits + if self.dtype.is_signed: + expr = expr - 2 ** (bits - 1) + self.expr = expr + + +class SymPyOps: + """An ops handler where all IR values are SymPy expressions + + When a value cannot be represented as a SymPy expression, the method is + either not defined, or returns NotImplemented + + """ + + @staticmethod + def identity(value: Any) -> Any: + return value + + @staticmethod + def constant(value: int | float | bool, dtype: torch.dtype) -> TypedExpr: + return TypedExpr(value, dtype) + + @staticmethod + def index_expr(value: sympy.Expr | int, dtype: torch.dtype) -> TypedExpr: + return TypedExpr(value, dtype) + + @staticmethod + def value_expr(value: sympy.Expr | int, dtype: torch.dtype) -> TypedExpr: + return TypedExpr(value, dtype) + + @staticmethod + def to_dtype( + value: TypedExpr, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types: bool = False, + ) -> TypedExpr: + return TypedExpr(value.expr, dtype) + + @staticmethod + def abs(x: TypedExpr) -> TypedExpr: + return TypedExpr(abs(x.expr), x.dtype) # type: ignore[arg-type] + + @staticmethod + def square(x: TypedExpr) -> TypedExpr: + return TypedExpr(x.expr * x.expr, x.dtype) + + @staticmethod + def add(x: TypedExpr, y: TypedExpr) -> TypedExpr: + result_type = torch.promote_types(x.dtype, y.dtype) + return TypedExpr(x.expr + y.expr, result_type) + + @staticmethod + def sub(x: TypedExpr, y: TypedExpr) -> TypedExpr: + result_type = torch.promote_types(x.dtype, y.dtype) + return TypedExpr(x.expr - y.expr, result_type) + + @staticmethod + def mul(x: TypedExpr, y: TypedExpr) -> TypedExpr: + result_type = torch.promote_types(x.dtype, y.dtype) + return TypedExpr(x.expr * y.expr, result_type) + + @staticmethod + def neg(x: TypedExpr) -> TypedExpr: + return TypedExpr(-x.expr, x.dtype) + + @staticmethod + def floordiv(x: TypedExpr, y: TypedExpr) -> TypedExpr: + result_type = torch.promote_types(x.dtype, y.dtype) + if not is_integer_dtype(result_type): + return NotImplemented + + return TypedExpr(FloorDiv(x.expr, y.expr), result_type) + + @staticmethod + def mod(x: TypedExpr, y: TypedExpr) -> TypedExpr | None: + result_type = torch.promote_types(x.dtype, y.dtype) + if not is_integer_dtype(result_type): + return NotImplemented + + result_expr = ModularIndexing(x.expr, sympy.S.One, y.expr) + return TypedExpr(result_expr, result_type) + + @staticmethod + def remainder(x: TypedExpr, y: TypedExpr) -> TypedExpr | None: + result_type = torch.promote_types(x.dtype, y.dtype) + if not is_integer_dtype(result_type): + return NotImplemented + + x_expr = sympy.sympify(x.expr) + y_expr = sympy.sympify(y.expr) + # In these cases, remainder in Python == remainder in C++, so this transformation + # is sound + if ( + x_expr.is_nonnegative is not None + and x_expr.is_nonnegative == y_expr.is_positive + ): + result_expr = ModularIndexing(x.expr, sympy.S.One, y.expr) + return TypedExpr(result_expr, result_type) + return NotImplemented + + @staticmethod + def minimum(x: TypedExpr, y: TypedExpr) -> TypedExpr: + result_type = torch.promote_types(x.dtype, y.dtype) + if result_type == torch.bool: + return NotImplemented + return TypedExpr(Min(x.expr, y.expr), result_type) + + @staticmethod + def maximum(x: TypedExpr, y: TypedExpr) -> TypedExpr: + result_type = torch.promote_types(x.dtype, y.dtype) + if result_type == torch.bool: + return NotImplemented + return TypedExpr(Max(x.expr, y.expr), result_type) + + +@dataclass +class IndexPropVar: + value: Any # Either an IR value, or TypedExpr if is_symbolic is true + is_symbolic: bool = False + + @staticmethod + def new_symbolic(expr: TypedExpr) -> "IndexPropVar": + return IndexPropVar(expr, is_symbolic=True) + + def __post_init__(self): + if not (not self.is_symbolic or isinstance(self.value, TypedExpr)): + raise AssertionError("Symbolic IndexPropVar must contain a TypedExpr") + + +IndexPropResult: TypeAlias = IndexPropVar | tuple["IndexPropResult", ...] + + +class IndexPropagation(DefaultHandler): + """Ops wrapper that tries to propagate constant and index_expr values through the computation. + + This aims to maximize the compile time simplification possible, and convert + indirect indexing from arange into normal static indexing. + + """ + + def __init__( + self, + inner: Any, + iter_ranges: dict[sympy.Symbol, sympy.Expr], + indirect_var_ranges: dict[sympy.Symbol, sympy.Expr], + ) -> None: + self._inner = inner + self.shape_env = V.graph.sizevars.shape_env + + var_to_range = { + k: ValueRanges(0, upper_bound(v) - 1) for k, v in iter_ranges.items() + } + self.var_to_range = tuple( + itertools.chain(self.shape_env.var_to_range.items(), var_to_range.items()) + ) + # NOTE: this is intentionally kept as a reference so the caller can + # update it in-place + self.indirect_var_ranges = indirect_var_ranges + + axioms = [] + for x, s in iter_ranges.items(): + axioms.append(0 <= x) + axioms.append(x < s) + self.axioms = tuple(axioms) + self.shape_env.get_axioms() + + def materialize_expr(self, expr: sympy.Expr, dtype: torch.dtype) -> Any: + # Construct a new constant/index_expr from the SymPy expression + if _is_constant(expr): + val = dtype_to_type(dtype)(expr) + return self._inner.constant(val, dtype) + return self._inner.index_expr(expr, dtype) + + def value_expr(self, expr: sympy.Expr, dtype: torch.dtype) -> IndexPropResult: + return self.wrap(self._inner.value_expr(expr, dtype)) + + def unwrap(self, a: Any | IndexPropVar) -> Any: + if isinstance(a, (list, tuple)): + return tuple(self.unwrap(v) for v in a) + + if not isinstance(a, IndexPropVar): + return a + + # Prefer the sympy representation if possible + if a.is_symbolic: + return self.materialize_expr(a.value.expr, a.value.dtype) + + return a.value + + def wrap(self, a) -> IndexPropResult: + if isinstance(a, (list, tuple)): + return tuple(self.wrap(v) for v in a) + return IndexPropVar(a) + + @overload + def fallback( + self, + name: Literal["indirect_indexing"], + args: Sequence[Any], + kwargs: dict[str, Any], + ) -> IndexPropVar: ... + + @overload + def fallback( + self, name: str, args: Sequence[Any], kwargs: dict[str, Any] + ) -> IndexPropResult: ... + + def fallback( + self, name: str, args: Sequence[Any], kwargs: dict[str, Any] + ) -> IndexPropResult: + # Fallback to the wrapped handler + new_args = [self.unwrap(a) for a in args] + new_kwargs = {k: self.unwrap(v) for k, v in kwargs.items()} + return self.wrap(getattr(self._inner, name)(*new_args, **new_kwargs)) + + def propagate_sympy( + self, name: str, args: Sequence[Any], kwargs: dict[str, Any] + ) -> IndexPropResult: + # Build a new SymPy expression from this ops call + def unwrap(a: Any | IndexPropVar) -> Any: + if not isinstance(a, IndexPropVar): + return a + return a.value + + new_args = [unwrap(a) for a in args] + new_kwargs = {k: unwrap(v) for k, v in kwargs.items()} + try: + new_expr = getattr(SymPyOps, name)(*new_args, **new_kwargs) + except (OverflowError, ValueError): + # e.g. int(inf) raises OverflowError, int(nan) raises ValueError + return self.fallback(name, args, kwargs) + is_valid_expr = new_expr is not NotImplemented and ( + # Inductor doesn't expect floating point in sympy expressions, but + # allow floating point constants to be propagated + new_expr.is_constant() or new_expr.expr.is_integer + ) + if not is_valid_expr: + return self.fallback(name, args, kwargs) + return IndexPropVar.new_symbolic(new_expr) + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + if not hasattr(SymPyOps, name): + return self.fallback(name, args, kwargs) + + var_arguments = [ + a + for a in itertools.chain(args, kwargs.values()) + if isinstance(a, IndexPropVar) + ] + if not all(v.is_symbolic for v in var_arguments): + return self.fallback(name, args, kwargs) + + return self.propagate_sympy(name, args, kwargs) + + def statically_true(self, e): + """ + Given some iter_ranges, return a function that given an expression, returns whether + it is true or false using value ranges, guard knowledge and runtime_asserts. + + FIXME I think this may not be entirely right, as we may not be able to use all runtime_asserts + If this is an issue, just use guards in `self.axioms`. + + The proper way of handling this would be to have a global shape_env that adds + runtime_asserts as they happen in the code. Then, it should be used in SimplifyIndexing + to perform wrap_expr and in CSEProxy.check_bounds to elide upper / lower bounds also + for indirect_indexing + """ + var_to_range = ( + *self.var_to_range, + *( + (k, ValueRanges(0, upper_bound(v) - 1)) + for k, v in self.indirect_var_ranges.items() + ), + ) + # pyrefly: ignore [bad-argument-type] + return statically_known_true(self.shape_env, e, self.axioms, var_to_range) + + def indirect_indexing( + self, + index: Any | IndexPropVar, + size: Any, + check: bool = True, + wrap_neg=True, + ) -> Any: + if isinstance(index, IndexPropVar) and index.is_symbolic: + # If we find something we can convert into a direct indexing we do so + # We still need to (perhaps) wrap the expression and add bound checks + # We want to do this "constant folding", as we don't allow to fuse + # kernels into indirect indexing + + expr = sympy.sympify(index.value.expr) + + # TODO Perhaps move this logic to the simplify indexing pass + def wrap_expr(expr): + # Positive, negative, mixed + if self.statically_true(0 <= expr): + return expr + elif self.statically_true(expr < 0): + return expr + size + else: + return Where(expr < 0, expr + size, expr) + + # -size <= expr only proves the lower bound after negative wrapping. + can_prove_lower = self.statically_true(0 <= expr) or ( + wrap_neg and self.statically_true(-size <= expr) + ) + can_prove_upper = self.statically_true(expr < size) + if wrap_neg: + expr = wrap_expr(expr) + if generate_assert(check): + self.fallback( + "check_bounds", + (expr, size), + dict(lower=not can_prove_lower, upper=not can_prove_upper), + ) + return expr + + indirect_var = self.fallback( + "indirect_indexing", (index, size, check, wrap_neg), {} + ).value + return indirect_var diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/inductor_prims.py b/.venv/lib/python3.12/site-packages/torch/_inductor/inductor_prims.py new file mode 100644 index 0000000000000000000000000000000000000000..8fecb666d4ee974f6780aa176c411abd6eea436d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/inductor_prims.py @@ -0,0 +1,401 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import functools +import logging +import operator +from typing import TYPE_CHECKING + +import torch +from torch import _prims, Tensor +from torch._utils import _get_device_index + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +log = logging.getLogger(__name__) + + +def make_prim( + schema: str, + impl_aten, + return_type=_prims.RETURN_TYPE.NEW, + doc: str = "", + tags: Sequence[torch.Tag] | None = None, +): + if isinstance(return_type, tuple): + + def meta(*args, **kwargs): + return tuple(_prims.TensorMeta(o) for o in impl_aten(*args, **kwargs)) + + else: + + def meta(*args, **kwargs): + return _prims.TensorMeta(impl_aten(*args, **kwargs)) + + return _prims._make_prim( + schema=schema, + return_type=return_type, + meta=meta, + impl_aten=impl_aten, + doc=doc, + tags=tags, + ) + + +def eager_force_stride(input_tensor: Tensor, stride) -> Tensor: + if input_tensor.stride() == stride: + return input_tensor + new_tensor = input_tensor.clone().as_strided( + input_tensor.shape, + stride, + ) + new_tensor.copy_(input_tensor) + return new_tensor + + +def eager_prepare_softmax(x: Tensor, dim: int) -> tuple[Tensor, Tensor]: + amax = torch.amax(x, dim, keepdim=True) + return amax, torch.sum(torch.exp(x - amax), dim, keepdim=True) + + +# Custom prims used for handling randomness +seed = make_prim( + "inductor_seed(Device device) -> Tensor", + lambda device: torch.randint(2**63 - 1, [], device=device), + doc="create a fresh seed (one per call) for use with inductor_rand", + tags=(torch.Tag.nondeterministic_seeded,), +) +seeds = make_prim( + "inductor_seeds(int count, Device device) -> Tensor", + lambda count, device: torch.randint(2**63 - 1, [count], device=device), + doc="Horizontal fusion of many inductor_seed() calls", + tags=(torch.Tag.nondeterministic_seeded,), +) +lookup_seed = make_prim( + # if inductor_lookup_seed changes, update partitioners.py + "inductor_lookup_seed(Tensor seeds, int index) -> Tensor", + lambda seeds, index: seeds[index].clone(), + doc="Extract a single seed from the result of inductor_seeds()", +) +# inductor_random() doesn't accept a dtype. +# instead, its lowering always burns in float32, and conversions to a different type +# are explicit in the graph. We therefore need this impl (used during tracing) to hardcode +# the dtype, so it always faithfully produces a float32 tensor during tracing, +# even if the default dtype is set to something else. +random = make_prim( + "inductor_random(SymInt[] size, Tensor seed, str mode, *, ScalarType? align_dtype=None) -> Tensor", + lambda size, seed, mode, *, align_dtype=None: getattr(torch, mode)( + size, device=seed.device, dtype=torch.float32 + ), + doc="torch.rand()/torch.randn() using backend-specific RNG that can be fused", +) +randint = make_prim( + "inductor_randint(SymInt low, SymInt high, SymInt[] size, Tensor seed) -> Tensor", + lambda low, high, size, seed: torch.randint(low, high, size, device=seed.device), + doc="torch.randint() using backend-specific RNG that can be fused", +) + + +def _reserve_rng_state(device: torch.device, used_offset): + """ + Reserve `used_offset` 32-bit Philox samples on the given CUDA device and + return (seed, base), where base is in Philox-4x32 units. + + This mirrors how Inductor accounts for Philox consumption so compiled + dropout kernels can reconstruct eager RNG state. + """ + dev = device if isinstance(device, torch.device) else torch.device(device) + if dev.type != "cuda": + # Only CUDA devices have Philox-based CUDAGenerator. For non-CUDA + # devices this prim should be dead code and never actually run. + return 0, 0 + + dev_index = _get_device_index(dev, optional=True) + if dev_index is None: + dev_index = torch.cuda.current_device() + + gen = torch.cuda.default_generators[dev_index] + seed_t, off_t, intra_t = torch.ops.inductor_prims.inductor_reserve_rng_state( + gen, used_offset + ) + + # NOTE: for correctness in eager, intra_t should be 0. + # Keep everything as tensor math to avoid host sync. + if intra_t.device.type != off_t.device.type: + intra = int(intra_t.item()) + base = torch.div(off_t + intra, 4, rounding_mode="floor") + else: + base = torch.div(off_t + intra_t, 4, rounding_mode="floor") + return seed_t, base + + +def _rand_eager_offset_impl(offset, device: torch.device) -> Tensor: + """ + Reserve `offset` 32-bit Philox samples and return a 1-element int64 tensor + Place-holder: will be replaced by rand_eager_offsets + In fx_passes/replace_random.py + fuse_offset_creation_pass() + """ + return torch.empty(2, dtype=torch.int64, device=device) + + +def _rand_eager_offsets_impl(offsets, device: torch.device) -> Tensor: + """ + Batched version of _rand_eager_offset_impl. For each entry in `offsets`, + reserve that many 32-bit Philox samples and return a 1D int64 tensor + containing the packed (seed, base) values for each reservation. + """ + states = [_reserve_rng_state(device, int(off)) for off in offsets] + seeds = [s for s, _ in states] + bases = [b for _, b in states] + + def _to_i64(x): + if isinstance(x, torch.Tensor): + return x + return torch.as_tensor(x, device=device, dtype=torch.int64) + + seeds_tensor = torch.stack([_to_i64(x) for x in seeds]).view(-1) + bases_tensor = torch.stack([_to_i64(x) for x in bases]).view(-1) + packed = torch.stack([seeds_tensor, bases_tensor], dim=1) + return packed + + +def _rand_eager_offsets_meta(offsets, device: torch.device): + return torch.empty((len(offsets), 2), dtype=torch.int64, device=device) + + +rand_eager_offset = make_prim( + "inductor_rand_eager_offset(SymInt offset, Device device) -> Tensor", + _rand_eager_offset_impl, + doc=( + "Reserve `offset` 32-bit Philox samples on `device` and return a " + "1-element int64 tensor containing packed (seed, base)." + ), + tags=(torch.Tag.nondeterministic_seeded,), +) + + +rand_eager_offsets = _prims._make_prim( + schema="inductor_rand_eager_offsets(SymInt[] offsets, Device device) -> Tensor", + return_type=_prims.RETURN_TYPE.NEW, + meta=_rand_eager_offsets_meta, + impl_aten=_rand_eager_offsets_impl, + doc=( + "Batched version of inductor_rand_eager_offset. For each entry in " + "`offsets`, reserves that many 64-bit Philox samples and returns " + "packed (seed, base) values." + ), + tags=(torch.Tag.nondeterministic_seeded,), +) + + +force_stride_order = make_prim( + "inductor_force_stride_order(Tensor input, SymInt[] stride) -> Tensor", + eager_force_stride, + doc="Force the stride order for input tensor. No-op if the input tensor already has the stride. Do a copy otherwise", +) +_unsafe_index_put_ = make_prim( + "_unsafe_index_put_(Tensor(a!) self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor(a!)", + lambda self, indices, values, accumulate=False: torch.ops.aten.index_put_( + self, indices, values, accumulate + ), + doc="Unsafe index_put_ (doesn't issue device asserts)", +) +fma = make_prim( + "fma(Tensor a, Tensor b, Tensor c) -> Tensor", + lambda a, b, c: (a * b) + c, + doc="Fused multiply add: fma(a, b, c) -> (a * b) + c without rounding after the multiplication", + tags=(torch.Tag.pointwise,), +) + + +def _fma_setup_context(ctx, inputs, output): + a, b, c = inputs + ctx.a_shape = a.shape + ctx.b_is_tensor = isinstance(b, Tensor) + if ctx.b_is_tensor: + ctx.b_shape = b.shape + ctx.save_for_backward(a, b) + else: + ctx.b = b + ctx.save_for_backward(a) + ctx.c_shape = c.shape + + +def _fma_backward(ctx, grad): + if ctx.b_is_tensor: + a, b = ctx.saved_tensors + else: + (a,) = ctx.saved_tensors + b = ctx.b + + grad_a = (grad * b).sum_to_size(ctx.a_shape) if ctx.needs_input_grad[0] else None + grad_b = ( + (grad * a).sum_to_size(ctx.b_shape) + if ctx.b_is_tensor and ctx.needs_input_grad[1] + else None + ) + grad_c = grad.sum_to_size(ctx.c_shape) if ctx.needs_input_grad[2] else None + return grad_a, grad_b, grad_c + + +torch.library.register_autograd( + fma, + _fma_backward, + setup_context=_fma_setup_context, +) + + +# Register DTensor sharding strategies for inductor prims ops. +# This must happen here (not in _pointwise_ops.py) because the ops +# don't exist until make_prim() is called above. +if torch.distributed.is_available(): + from torch.distributed.tensor._ops._pointwise_ops import register_inductor_prims + + register_inductor_prims() + +prepare_softmax_online = make_prim( + "prepare_softmax_online(Tensor a, int dim) -> (Tensor, Tensor)", + eager_prepare_softmax, + return_type=(_prims.RETURN_TYPE.NEW, _prims.RETURN_TYPE.NEW), + doc="Prepare the softmax by computing the max and sum.", +) + + +def _flattened_index_to_nd(indices, width): + import sympy + + from torch.utils._sympy.functions import FloorDiv + + dim = len(width) + + if dim == 1: + return [indices] + elif dim >= 2: + m = functools.reduce(operator.mul, width[1:]) + if isinstance(indices, sympy.Expr) or isinstance(m, sympy.Expr): + ih = FloorDiv(indices, m) + else: + ih = indices // m + indices_new = indices - (ih * m) + return [ih, *_flattened_index_to_nd(indices_new, width[1:])] + else: + raise ValueError(f"Unknown dim: {dim}") + + +def _flatten_index(indices, width): + result = indices[0] + for d in range(1, len(indices)): + result = width[d] * result + indices[d] + return result + + +def _low_memory_max_pool_with_offsets_aten( + self, + kernel_size, + stride, + padding, + dilation, + ceil_mode, +): + dim = len(kernel_size) + if dim == 2: + vals, indices = torch.ops.aten.max_pool2d_with_indices( + self, kernel_size, stride, padding, dilation, ceil_mode + ) + else: + vals, indices = torch.ops.aten.max_pool3d_with_indices( + self, kernel_size, stride, padding, dilation, ceil_mode + ) + + idhw = _flattened_index_to_nd(indices, self.shape[-dim:]) + + dhw_inc = [] + + for d in range(dim): + bh_shape = [1] * self.ndim + bh_shape[-dim + d] = -1 + bh = torch.arange( + indices.shape[-dim + d], dtype=torch.int64, device=self.device + ).view(bh_shape) + hbase = bh * stride[d] - padding[d] + h_inc = (idhw[d] - hbase) // dilation[d] + dhw_inc.append(h_inc) + + offsets = _flatten_index(dhw_inc, kernel_size) + + return vals, offsets.to(torch.int8) + + +def _low_memory_max_pool_offsets_to_indices_aten( + offsets, + kernel_size, + input_size, + stride, + padding, + dilation, +): + dim = len(kernel_size) + offsets = offsets.to(torch.int64) + dhw_inc = _flattened_index_to_nd(offsets, kernel_size) + + idhw = [] + for d in range(dim): + bh_shape = [1] * offsets.ndim + bh_shape[-dim + d] = -1 + bh = torch.arange( + offsets.shape[-dim + d], dtype=torch.int64, device=offsets.device + ).view(bh_shape) + hbase = bh * stride[d] - padding[d] + idhw.append(hbase + dhw_inc[d] * dilation[d]) + + return _flatten_index(idhw, input_size) + + +_low_memory_max_pool_with_offsets = make_prim( + "_low_memory_max_pool_with_offsets(Tensor self, SymInt[] kernel_size, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool ceil_mode) -> (Tensor, Tensor)", + _low_memory_max_pool_with_offsets_aten, + return_type=(_prims.RETURN_TYPE.NEW, _prims.RETURN_TYPE.NEW), + doc="Instead of returning indices, returns indices offsets.", +) + +_low_memory_max_pool_offsets_to_indices = make_prim( + "_low_memory_max_pool_offsets_to_indices(Tensor self, SymInt[] kernel_size, SymInt[] input_size, SymInt[] stride, SymInt[] padding, SymInt[] dilation) -> Tensor", + _low_memory_max_pool_offsets_to_indices_aten, + doc="Convert small int offsets to regular indices.", +) + + +def _cvt_e8m0_rceil_aten(inp: Tensor) -> Tensor: + """ + Convert float to e8m0 format with ceiling rounding and satfinite semantics. + + e8m0 format: 8-bit biased exponent (bias=127), no mantissa. + For MX format scaling, this extracts the exponent with ceiling rounding. + Uses satfinite semantics: inf is saturated to 254 (max finite e8m0). + Accepts float32, float16, or bfloat16 (upcasted to float32 internally). + """ + if inp.dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise ValueError( + f"cvt_e8m0_rceil requires float32, float16, or bfloat16 input, got {inp.dtype}" + ) + if inp.dtype != torch.float32: + inp = inp.to(torch.float32) + inp_bits = inp.view(torch.int32) + biased_exp = (inp_bits >> 23) & 0xFF + mantissa = inp_bits & 0x7FFFFF + needs_round_up = mantissa != 0 + e8m0_biased = biased_exp + needs_round_up.to(torch.int32) + # satfinite: clamp to max finite e8m0 value (254), not 255 (inf/nan) + e8m0_biased = torch.clamp(e8m0_biased, 0, 254) + return e8m0_biased.to(torch.uint8) + + +cvt_e8m0_rceil = make_prim( + "inductor_cvt_e8m0_rceil(Tensor input) -> Tensor", + _cvt_e8m0_rceil_aten, + doc="Convert float to e8m0 with ceiling rounding. Uses PTX cvt.rp.satfinite.ue8m0x2.f32 on SM100+.", +) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/invert_expr_analysis.py b/.venv/lib/python3.12/site-packages/torch/_inductor/invert_expr_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..dab206c8f7299ad7423f197041d500a2885cfe90 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/invert_expr_analysis.py @@ -0,0 +1,259 @@ +from dataclasses import dataclass, replace + +import sympy + +from torch._inductor.utils import _IntLike, argsort_sym +from torch.utils._sympy.functions import FloorDiv, ModularIndexing + +from .sizevars import join_dimensions +from .virtualized import V + + +def static_eq(a: _IntLike, b: _IntLike) -> bool: + return V.graph.sizevars.statically_known_equals(a, b) + + +@dataclass(frozen=True) +class Term: + coefficient: _IntLike + range: _IntLike | None # None for unbounded + original_expr: sympy.Expr + reconstruction_multiplier: _IntLike # The multiplier needed for reconstruction + + +def generate_inverse_formula( + expr: sympy.Expr, var: sympy.Symbol, var_range: _IntLike | None = None +) -> sympy.Expr | None: + """ + Analyze an expression to see if it matches a specific invertible pattern that we + know how to reverse. + + We're looking for expressions that are sums of terms where each term extracts a + distinct bounded range from the input variable, like: + + y = c₀*a₀ + c₁*a₁ + c₂*a₂ + ... + cₙ*aₙ + + where each aᵢ must be one of these specific patterns: + - ModularIndexing(var, divisor, modulo) + - FloorDiv(ModularIndexing(var, 1, modulo), divisor) + - FloorDiv(var, divisor) + - var (the variable itself) + + The key pattern we need is: + - Coefficients are strictly decreasing: c₀ > c₁ > c₂ > ... > cₙ + - Each coefficient matches the product of ranges of later terms (mixed-radix property) + - Each term extracts a bounded range, creating non-overlapping "slots" + + If we find this pattern, we can generate the reconstruction transformation that + decomposes the variable and rebuilds it using the correct multipliers. + + EXAMPLE: + Input: 100*((p//100)) + 10*((p%100)//10) + (p%10) + + Returns the reconstruction expression: + remainder₀ = p + component₀ = remainder₀ // 100 # hundreds digit + remainder₁ = remainder₀ % 100 + component₁ = remainder₁ // 10 # tens digit + remainder₂ = remainder₁ % 10 + component₂ = remainder₂ # ones digit + result = component₀*100 + component₁*10 + component₂*1 + + This decomposes p into its components and rebuilds it using the original + multipliers, which should equal the input expression. + + Args: + expr: Expression to analyze (sum of terms with ModularIndexing, FloorDiv, etc.) + var: The variable being decomposed + var_range: Optional exclusive upper bound for nonnegative var + + Returns: + None if not invertible, or the reconstruction expression + + References: + Mixed-radix systems: https://en.wikipedia.org/wiki/Mixed_radix + """ + # Collapse modular fragments introduced by view decomposition before parsing. + expr = sympy.Add( + *( + V.graph.sizevars.combine_modular_indexing_pairs(term) + for term in sympy.Add.make_args(expr) + ) + ) + expr = expr.replace(lambda subexpr: isinstance(subexpr, sympy.Add), join_dimensions) + + # Step 1: Parse all terms + terms = parse_terms(expr, var) + if not terms: + return None + + # Step 2: Sort by coefficient (descending) + coeffs = [t.coefficient for t in terms] + idxs = reversed(argsort_sym(V.graph.sizevars.shape_env, coeffs)) + terms = [terms[i] for i in idxs] + + # Step 3: Check invertibility conditions + if not check_invertibility(terms, var_range): + return None + + reconstruction = generate_reconstruction_expr(terms, var) + if var_range is not None: + reconstruction = V.graph.sizevars.simplify_with_ranges( + reconstruction, {var: var_range} + ) + return reconstruction + + +def parse_terms(expr: sympy.Expr, var: sympy.Symbol) -> list[Term] | None: + """Parse expression into terms.""" + if not isinstance(expr, sympy.Add): + # Single term + term = parse_single_term(expr, var) + return [term] if term else [] + + terms = [] + for arg in expr.args: + term = parse_single_term(arg, var) + if term: + terms.append(term) + else: + return None # If any term fails to parse, fail completely + + return terms + + +def parse_single_term(term: sympy.Expr, var: sympy.Symbol) -> Term | None: + """Parse a single term and extract coefficient, range, and reconstruction multiplier.""" + # Extract coefficient and expression parts + coefficient, expr_parts = term.as_coeff_mul() + + if len(expr_parts) == 0: + return None + elif len(expr_parts) == 1: + expr = expr_parts[0] + else: + # Multiple non-constant factors, too complex + return None + + # Now determine the range and reconstruction multiplier + range_val, reconstruction_multiplier = analyze_expression_properties(expr, var) + if reconstruction_multiplier is None: + return None + + return Term( + coefficient=coefficient, + range=range_val, + original_expr=expr, + reconstruction_multiplier=reconstruction_multiplier, + ) + + +def analyze_expression_properties( + expr: sympy.Expr, var: sympy.Symbol +) -> tuple[_IntLike | None, _IntLike | None]: + """Analyze an expression to determine its range and reconstruction multiplier.""" + # ModularIndexing(var, divisor, modulo) = (var // divisor) % modulo + if isinstance(expr, ModularIndexing): + x, div, mod = expr.args + if static_eq(x, var): + return mod, div # Range is mod, multiplier is div + + # FloorDiv cases + if isinstance(expr, FloorDiv): + base, divisor = expr.args + + # FloorDiv(ModularIndexing(var, 1, mod), div) = (var % mod) // div + if isinstance(base, ModularIndexing): + x, inner_div, mod = base.args + if static_eq(x, var) and static_eq(inner_div, 1): + if not V.graph.sizevars.statically_known_multiple_of(mod, divisor): + return None, None + range_val = FloorDiv(mod, divisor) + return range_val, divisor # Range is mod//div, multiplier is div + + # FloorDiv(var, divisor) = var // divisor (unbounded) + elif static_eq(base, var): + return None, divisor # Unbounded range, multiplier is div + + return None, None + + +def check_invertibility(terms: list[Term], var_range: _IntLike | None = None) -> bool: + """Check if the terms represent an invertible transformation.""" + if not terms: + return False + + effective_terms: list[Term] = [] + for term in terms: + if term.range is None and var_range is not None: + multiplier = term.reconstruction_multiplier + if not V.graph.sizevars.statically_known_multiple_of(var_range, multiplier): + return False + term = replace(term, range=FloorDiv(var_range, multiplier)) + effective_terms.append(term) + terms = effective_terms + + # Coefficients must be strictly decreasing + coeffs = [t.coefficient for t in terms] + if argsort_sym(V.graph.sizevars.shape_env, coeffs) != list( + reversed(range(len(coeffs))) + ): + return False + + # Check mixed-radix property: each coeff[i] = coeff[i+1] * range[i+1] + ascending_terms = list(reversed(terms)) + expected_coeff = 1 + for i, term in enumerate(ascending_terms): + if not static_eq(term.coefficient, expected_coeff): + return False + if term.range is None: + if i + 1 < len(ascending_terms): + return False + continue + expected_coeff = term.coefficient * term.range + + return check_reconstruction_coverage(terms, var_range) + + +def check_reconstruction_coverage( + terms: list[Term], + var_range: _IntLike | None = None, +) -> bool: + """Check that terms reconstruct non-overlapping contiguous source ranges.""" + if not terms: + return False + + multipliers = [t.reconstruction_multiplier for t in terms] + idxs = argsort_sym(V.graph.sizevars.shape_env, multipliers) + ascending_terms = [terms[i] for i in idxs] + + expected_multiplier = 1 + for i, term in enumerate(ascending_terms): + if not static_eq(term.reconstruction_multiplier, expected_multiplier): + return False + if term.range is None: + return i == len(ascending_terms) - 1 and var_range is None + expected_multiplier = term.reconstruction_multiplier * term.range + + if var_range is not None and not static_eq(var_range, expected_multiplier): + return False + + return True + + +def generate_reconstruction_expr(terms: list[Term], var: sympy.Symbol) -> sympy.Expr: + y = var + reconstruction = sympy.S.Zero + remainder = y + + for i, term in enumerate(terms): + if i < len(terms) - 1: + component = FloorDiv(remainder, term.coefficient) + remainder = ModularIndexing(remainder, 1, term.coefficient) + else: + # Last term should also divide by its coefficient + component = FloorDiv(remainder, term.coefficient) + + reconstruction += component * term.reconstruction_multiplier + + return reconstruction diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/ir.py b/.venv/lib/python3.12/site-packages/torch/_inductor/ir.py new file mode 100644 index 0000000000000000000000000000000000000000..b5ccaf721f14660621b2935f66e36fff255f84bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/ir.py @@ -0,0 +1,12166 @@ +from __future__ import annotations + +import contextlib +import copy +import dataclasses +import functools +import itertools +import logging +import operator +import textwrap +import traceback +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from contextlib import AbstractContextManager, nullcontext +from enum import Enum +from functools import partial +from numbers import Number +from typing import ( + Any, + cast, + ClassVar, + Literal, + overload, + Protocol, + SupportsFloat, + SupportsInt, + TYPE_CHECKING, + TypeAlias, + TypeVar, + Union, +) +from typing_extensions import ( + assert_never, + Never, + override, + ParamSpec, + Self, + TypedDict, + TypeIs, +) +from unittest.mock import patch + +import sympy +from sympy import Expr, Integer, Symbol + +import torch._export.serde.schema as export_schema +import torch._library.custom_ops as custom_ops +import torch._library.utils as library_utils +import torch._logging +import torch.fx +import torch.utils._pytree as pytree +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.utils import identity +from torch._export.serde.serialize import GraphModuleSerializer +from torch._higher_order_ops.auto_functionalize import can_auto_functionalize +from torch._inductor import metrics +from torch._inductor.utils import get_free_symbols +from torch._library.fake_class_registry import FakeScriptObject, maybe_to_fake_obj +from torch._library.opaque_object import get_opaque_obj_repr, is_custom_class_obj +from torch._native.ops.sum import inner_tree_plan +from torch._prims_common import ( + compute_required_storage_length, + is_boolean_dtype, + is_contiguous_for_memory_format_or_false, + is_float_dtype, + make_channels_last_strides_for, + StrideType, +) +from torch.fx.experimental.symbolic_shapes import ( + _remove_effect_token_unbacked_bindings, + compute_unbacked_bindings, + free_symbols, + free_unbacked_symbols, + GuardOnDataDependentSymNode, + has_free_unbacked_symbols, + IterateExprs, + rebind_unbacked, + resolve_unbacked_bindings, + ShapeEnv, + SymTypes, +) +from torch.fx.node import Node +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import _disable_current_modes +from torch.utils._sympy.functions import ( + CleanDiv, + FloorDiv, + Max, + Min, + Mod, + ModularIndexing, +) +from torch.utils._sympy.symbol import SymT + +from . import config, dependencies +from .codegen.common import ( + BackendFeature, + CodegenSymbol, + get_scheduling_for_device, + index_prevent_reordering, + Kernel, +) +from .dependencies import ( + Dep, + extract_free_symbols, + extract_input_node_reduction_ranges, + extract_read_writes, + SymbolUsageCollectorOpsHandler, + var_builder, +) +from .loop_body import LoopBody +from .ops_handler import OpCounterCSE, OpCountResult, ReductionType, StoreMode +from .runtime.benchmarking import benchmarker +from .runtime.hints import DeviceProperties, ReductionHint +from .utils import ( + argsort, + argsort_sym, + cache_on_self, + cache_on_self_and_args, + ceildiv, + convert_shape_to_inductor, + convert_shape_to_symint, + developer_warning, + do_bench_using_profiling, + dtype_from_size, + get_dtype_size, + get_kernel_metadata, + GPU_ALIGN_BYTES, + ir_dataclass, + is_dynamic, + is_gpu, + sympy_dot, + sympy_index_symbol, + sympy_index_symbol_with_prefix, + sympy_product, + sympy_subs, + tensor_is_aligned, + VarRanges, +) +from .virtualized import ops, OpsValue, V + + +if TYPE_CHECKING: + from torch.fx.experimental.symbolic_shapes import SympyBoolean + from torch.fx.node import Argument + from torch.types import IntLikeType + + from .codegen.cutlass.template import CUTLASSTemplate + from .codegen.wrapper import PythonWrapperCodegen + from .graph import GraphLowering + from .kernel.gemm_epilogue import GemmReductionPlan + from .utils import IndentedBuffer + +else: + CUTLASSTemplate: TypeAlias = object + + +try: + import triton + + triton_version = triton.__version__ + has_triton = True +except ImportError: + triton_version = None + has_triton = False + + +_P = ParamSpec("_P") +_T = TypeVar("_T") +_U = TypeVar("_U") +_V = TypeVar("_V") + +_IntLike: TypeAlias = int | Expr +_NumLike: TypeAlias = int | float | Expr + +_OpOverloads: TypeAlias = torch._ops.OpOverload | torch._ops.HigherOrderOperator + + +class ArgProperty(TypedDict, total=False): + name: str + type: torch.JitType + default_value: object + + +log = logging.getLogger(__name__) +indent = functools.partial(textwrap.indent, prefix=" ") +aten = torch.ops.aten + +""" [Note: Inductor IR] + +Inductor's IR is produced by executing 'lowering' code (see lowering.py). Each +lowering is registered to a particular aten operator, and expects inputs that +correspond to the aten schema. However, in place of torch Tensor inputs, lowerings +expect Inductor TensorBox inputs. + +TensorBox IR represents torch tensors. Tensors are sometimes single objects owning +storage, and sometimes views of another Tensor's storage. Mutating tensor operations +(such as add_()) affect the underlying storage and any associated views. Other operations +(such as .t_()) update metadata about the current view but don't modify the underlying storage. + +To model this in Inductor, the IR distinguishes between TensorBox, View, StorageBox and Buffer. + +TensorBox is the top level IR construct that any lowering should produce and maps to a torch.Tensor +output from an operation. But just as torch.Tensors take different forms, TensorBox IR can +reference View IR or directly reference StorageBox IRs. + +Some Inductor lowerings produce new sets of 'Box'es, while others (such as .t() or other view ops) +may take an existing TensorBox and point it to a new underlying View IR. + +Tensors that directly own storage are represented as a chain of: +TensorBox -> StorageBox -> Buffer +where Buffer is a simple (1D) allocation, and StorageBox introduces the concept of a Layout. + +If you mutate the data of such a tensor, we swing the StorageBox pointer to point to a new buffer +(leaving the old buffer unmodified and functionalizing the operation). + +Tensors backed by views add one more indirection to the IR. +TensorBox -> View -> StorageBox -> Buffer +In these cases, the underlying StorageBox/Buffer will be shared with the pre-view TensorBox. + +Computation is represented by Operation nodes, with each operation producing 1 +or more output Buffers. In the case of mutations, these will be new Buffers that have the +mutated buffer listed in its get_mutation_names(). + +It is also possible to have an InputBuffer for which there is no corresponding Operation, +e.g. it may be a graph input or compile time constant. + +""" + + +_NodeOrNodes: TypeAlias = Union[ + int, + "TensorBox", + dict[str, "TensorBox"], + "Symbol", + "IRNode", + Sequence[ + Union[int, dict[str, "TensorBox"], "TensorBox", "Symbol", "IRNode"] | None + ], +] + + +def _is_static(x: object) -> TypeIs[int | Integer]: + return isinstance(x, (int, Integer)) + + +@dataclasses.dataclass(frozen=True) +class GraphPartitionSignature: + # symbol inputs that are necessary for codegen + symbol_inputs: OrderedSet[sympy.Symbol] + + # mapping from partition input name to IRNode or Expr. Need the name str since + # we cannot get name from Expr. + input_nodes: dict[str, IRNode | Expr | TorchBindObject] + output_nodes: list[IRNode] + + # mapping from partition input name to a boolean for whether deallocating it + # in the partition function + input_deallocation: dict[str, bool] + skip_cudagraph: bool + + # name of constants read/written by the graph partition + constant_names: list[str] + + +def validate_ir(node_or_nodes: _NodeOrNodes | None) -> None: + def _check_tensorbox(nodes: _NodeOrNodes | None) -> None: + # Could expand this to check deeper properties + # (e.g. TensorBox points to View or StorageBox) + if nodes is None: + pass + elif isinstance(nodes, (list, tuple)): + for node in nodes: + _check_tensorbox(node) + elif isinstance(nodes, dict): + for node in nodes.values(): + _check_tensorbox(node) + else: + if not isinstance( + nodes, + ( + ExpandView, + DynamicScalar, + AssertScalar, + TensorBox, + sympy.logic.boolalg.Boolean, + Expr, + int, + EffectfulKernel, + ShapeAsConstantBuffer, + OpaqueMultiOutput, + ), + ): + raise AssertionError( + f"Found {type(nodes)}, which is not a supported top level IR node. See [Note: Inductor IR]" + ) + + # Be picky about the accepted data structure (don't use pytree here) + _check_tensorbox(node_or_nodes) + + +def ops_wrapper(name: str) -> Callable[..., OpsValue]: + if not isinstance(name, str): + raise AssertionError(type(name)) + + def fn(*args: object, **kwargs: object) -> OpsValue: + return getattr(ops, name)(*args, **kwargs) + + return fn + + +def inverse_reorder(order: Sequence[int]) -> Callable[[Sequence[_T]], Sequence[_T]]: + inv_order = dict(zip(order, range(len(order)))) + + def reindex(index: Sequence[_T]) -> Sequence[_T]: + if len(index) != len(inv_order): + raise AssertionError("Expected len(index) == len(inv_order)") + return [index[inv_order[i]] for i in range(len(index))] + + return reindex + + +def same_reorder(order: Sequence[int]) -> Callable[[Sequence[_T]], Sequence[_T]]: + def reindex(index: Sequence[_T]) -> Sequence[_T]: + if len(index) != len(order): + raise AssertionError("Expected len(index) == len(order)") + return [index[order[i]] for i in range(len(index))] + + return reindex + + +def fuse_reindexing( + reindex1: Callable[[Sequence[_U]], Sequence[_V]], + reindex2: Callable[[Sequence[_T]], Sequence[_U]], +) -> Callable[[Sequence[_T]], Sequence[_V]]: + def reindex(index: Sequence[_T]) -> Sequence[_V]: + return reindex1(reindex2(index)) + + return reindex + + +NHWC_STRIDE_ORDER = [3, 0, 2, 1] +NHWDC_STRIDE_ORDER = [4, 0, 3, 2, 1] + + +def get_fill_order( + seq: Sequence[int | torch.SymInt | Expr], shape_env: ShapeEnv | None = None +) -> Sequence[int]: + """ + Convert strides to fill order (argsort) + """ + if shape_env is None or all(isinstance(s, (int, sympy.Integer)) for s in seq): + sorted_idx: Sequence[int] = argsort(seq) + else: + # argsort_sym handles unbacked symints (with the help of the shape_env) + sorted_idx = argsort_sym(shape_env, seq) + return sorted_idx + + +def stride_order2fill_order(order: Sequence[int | Integer]) -> Sequence[int]: + """ + Convert stride order to fill order + For channel last format, + + stride order = [3, 0, 2, 1] and fill order = [1, 3, 2, 0] + """ + lookup = {pos: idx for idx, pos in enumerate(order)} + fill_order = [lookup[i] for i in range(len(order))] + return fill_order + + +def get_stride_order( + seq: Sequence[int | torch.SymInt | Expr], shape_env: ShapeEnv | None = None +) -> Sequence[int]: + """ + Convert strides to stride order + """ + sorted_idx: Sequence[int] = get_fill_order(seq, shape_env) + out = [0 for _ in range(len(seq))] + for i, elem in enumerate(sorted_idx): + out[elem] = i + return out + + +@overload +def ir_node_to_tensor(x: None, replace_symbols_with_hints: bool = False) -> None: ... + + +@overload +def ir_node_to_tensor( + x: IRNode, replace_symbols_with_hints: bool = False +) -> torch.Tensor: ... + + +def ir_node_to_tensor( + x: IRNode | None, replace_symbols_with_hints: bool = False +) -> torch.Tensor | None: + # When replace_symbols_with_hints=False (default), sizes/strides remain as + # symbolic expressions, so downstream operations on the resulting tensor (e.g., + # shape comparisons inside a kernel's meta function) may install guards. When + # True, symbolic expressions are replaced with concrete integer hints via + # size_hint, preventing any downstream guards. + if x is None: + return None + + shape_fn: Callable[[int | Expr], int | Expr] + if replace_symbols_with_hints: + shape_fn = V.graph.sizevars.optimization_hint + else: + shape_fn = identity + size = [shape_fn(s) for s in x.get_size()] + stride: StrideType + if is_storage_and_layout(x): + stride = [shape_fn(s) for s in x.get_layout().stride] + else: + stride = FlexibleLayout.contiguous_strides(size) + dtype = x.get_dtype() + device = x.get_device() + size = convert_shape_to_symint(size) + # pyrefly: ignore [bad-assignment] + stride = convert_shape_to_symint(stride) + with V.graph.sizevars.shape_env.suppress_guards(): + t = torch.empty_strided( + size=size, stride=stride, dtype=dtype, device=device + ).zero_() + return t + + +def may_convert_to_optional( + value: Sequence[_T] | None, +) -> Sequence[_T | None] | None: + if isinstance(value, list) and not value: + # [None] makes sure the cpp wrapper codegen will generate something like + # {std::nullopt} instead of {} + return [None] + return value + + +def get_device_type( + x: IRNode | OutputSpec | torch.device | None | str, +) -> str | None: + if isinstance(x, str) or x is None: + return x + elif isinstance(x, torch.device): + return x.type + elif isinstance(x, (IRNode, OutputSpec)): + return get_device_type(x.get_device()) + # pyrefly: ignore [bad-argument-type] + assert_never(f"get_device_type({x}: {type(x).__name__})") + + +def is_triton(x: IRNode | torch.device | None | str) -> bool: + device = get_device_type(x) + # Special case cpu and cuda as using the method below + # to determine if the scheduler is a triton scheduler subclass + # requires instantiating a scheduler for them + if device in ["cpu", "cuda", "xpu"]: + if getattr(config, f"{device}_backend") == "triton": + return True + return False + if ( + device is None + or (device_scheduling := get_scheduling_for_device(device)) is None + ): + return False + from .codegen.triton import TritonScheduling + + if not isinstance(device_scheduling, type): + raise AssertionError(type(device_scheduling)) + return issubclass(device_scheduling, TritonScheduling) + + +def is_cpu(x: IRNode | torch.device | None | str) -> bool: + return get_device_type(x) == "cpu" + + +def is_aligned_realized_tensor(x: Buffer | TensorBox, alignment: int) -> bool: + if ( + not isinstance(x, IRNode) + or x.maybe_get_stride() is None + or free_unbacked_symbols(x.get_stride()) + or free_unbacked_symbols(x.get_size()) + ): + return False + + aligned_strides = sympy.And( + *(sympy.Eq(Mod(s, alignment), 0) for s in x.get_stride()[:-1]) + ) + aligned_last_dim = sympy.Or( + sympy.Eq(x.get_stride()[-1], 1), sympy.Le(x.get_size()[-1], 1) + ) + is_aligned = sympy.And(aligned_strides, aligned_last_dim) + + # Make sure to guard to recompile when necessary. + return V.graph.sizevars.guard_or_false(is_aligned) + + +def significant_strides_equal( + strides1: Sequence[_IntLike], + strides2: Sequence[_IntLike], + shape: Sequence[_IntLike], +) -> bool: + """ + Returns true if the strides are equal, ignoring dimensions of size 0 or 1. + If any dimension is size 0, all strides are insignificant since the tensor + is empty. + """ + if not (len(shape) == len(strides1) and len(strides1) == len(strides2)): + raise AssertionError( + "Expected len(shape) == len(strides1) and len(strides1) == len(strides2)" + ) + if any(V.graph.sizevars.statically_known_equals(dim, 0) for dim in shape): + return True + for dim, s1, s2 in zip(shape, strides1, strides2): + if V.graph.sizevars.statically_known_leq(dim, 1): + continue + + if not V.graph.sizevars.guard_or_false(sympy.Eq(s1, s2)): + return False + return True + + +def try_match_insignificant_strides( + tensor: IRNode, + strides: Sequence[int | torch.SymInt], +) -> IRNode: + """ + Tries to match the strides of the tensor to those in the meta_strides. Strides of insignificant + dimensions - size 0 or 1 - will be updated. + + If there are real stride differences (NHWC vs NCHW), or the tensor is not realized, then the input will be returned + """ + if not is_storage_and_layout(tensor): + return tensor + + if all( + V.graph.sizevars.statically_known_equals(s1, s2) + for s1, s2 in zip(strides, tensor.get_stride()) + ): + return tensor + + if not significant_strides_equal(strides, tensor.get_stride(), tensor.get_size()): + return tensor + + storage, old_layout = as_storage_and_layout(tensor) + new_stride = [*old_layout.stride] + is_empty = tensor.is_zero_elements() + for i, s in enumerate(tensor.get_size()): + if is_empty or V.graph.sizevars.statically_known_leq(s, 1): + new_stride[i] = strides[i] + + new_layout = FixedLayout( + old_layout.device, + old_layout.dtype, + old_layout.size, + new_stride, + old_layout.offset, + old_layout.is_pinned, + ) + return TensorBox(ReinterpretView(data=storage, layout=new_layout)) + + +def gm_original_output_strides(gm: torch.fx.GraphModule) -> None: + output_node = gm.graph.find_nodes(op="output")[0] + output_node.meta["user_visible_output_idxs"] = [ + idx for idx, _ in enumerate(output_node.args) + ] + from torch._inductor.compile_fx import record_original_output_strides + + record_original_output_strides(gm) + + +def get_symbolic_inputs(inputs: Sequence[IRNode]) -> list[Expr]: + sym_vars: OrderedSet[Expr] = OrderedSet() + for inp in inputs: + sym_vars |= get_free_symbols(inp.get_size(), unbacked_only=False) + sym_vars |= get_free_symbols(inp.get_stride(), unbacked_only=False) + + return list(sym_vars) + + +def try_get_name(x): + if isinstance(x, TensorBox): + x = x.data + if isinstance(x, BaseView): + x = x.unwrap_view() + if isinstance(x, StorageBox): + x = x.data + return x.get_name() if isinstance(x, Buffer) else None + + +class IRNode: + """Base class for all intermediate representation (IR) nodes in TorchInductor. + + Note: + This is an abstract base class. Most methods raise NotImplementedError + and must be overridden by concrete subclasses. + """ + + _current_origins: ClassVar[OrderedSet[Any]] = OrderedSet() + _current_stream_idx: ClassVar[int | None] = None + _current_mempool: ClassVar[tuple[int, int] | None] = None + + # NB: These are kinda weird, + origins: OrderedSet[Any] = dataclasses.field(init=False) + # traces back to where the IRNode is created in Inductor + traceback: list[str] | None = dataclasses.field(init=False) + origin_node: torch.fx.Node | None = dataclasses.field(init=False) + # Annotations dict for storing metadata (e.g., KernelTemplateChoice) + annotations: dict[str, object] = dataclasses.field(init=False) + # User-annotated stream index from FX node metadata (set during lowering) + stream_idx: int | None = dataclasses.field(init=False) + # User-annotated CUDA MemPool from FX node metadata (set during lowering) + mempool: tuple[int, int] | None = dataclasses.field(init=False) + + @staticmethod + @contextlib.contextmanager + def current_origins(origins: OrderedSet[Node]) -> Generator[None, None, None]: + old = IRNode._current_origins + IRNode._current_origins = old | origins + try: + yield + finally: + IRNode._current_origins = old + + @staticmethod + @contextlib.contextmanager + def current_stream_idx( + stream_idx: int | None, + ) -> Generator[None, None, None]: + old = IRNode._current_stream_idx + IRNode._current_stream_idx = stream_idx + try: + yield + finally: + IRNode._current_stream_idx = old + + @staticmethod + @contextlib.contextmanager + def current_mempool( + mempool: tuple[int, int] | None, + ) -> Generator[None, None, None]: + old = IRNode._current_mempool + IRNode._current_mempool = mempool + try: + yield + finally: + IRNode._current_mempool = old + + @staticmethod + def is_realized_node(node: IRNode) -> bool: + return isinstance( + node, + ( + ComputedBuffer, + InputsKernel, + InputBuffer, + ReinterpretView, + TemplateBuffer, + ), + ) + + def wrap_for_lowering(self) -> IRNode: + return TensorBox.create(self) + + def _post_init_setattr(self, attr: str, value: Any) -> None: + # Intended for use in __post_init__ for enforcing an invariant on a dataclass + # If you must, can also be used for setting provenance info + # We would like to try and minimize these usages though + object.__setattr__(self, attr, value) + + def __post_init__(self) -> None: + origins = OrderedSet(self._current_origins) + self._post_init_setattr("origins", origins) + self._post_init_setattr( + "traceback", traceback.format_stack() if config.debug_ir_traceback else None + ) + self._post_init_setattr("origin_node", None) + # Annotations dict for storing metadata (e.g., KernelTemplateChoice) + self._post_init_setattr("annotations", {}) + self._post_init_setattr("stream_idx", self._current_stream_idx) + self._post_init_setattr("mempool", self._current_mempool) + + def get_read_names(self) -> OrderedSet[str]: + return OrderedSet(dep.name for dep in self.get_reads()) + + def get_traceback(self) -> list[str] | None: + return self.traceback + + def get_origin_node(self) -> torch.fx.Node | None: + return self.origin_node + + def get_defining_op(self) -> Operation | None: + return None + + def get_subgraphs(self) -> list[Subgraph]: + """Return subgraphs contained in this node""" + return [] + + def get_stack_traces(self) -> OrderedSet[str]: + # Return stack traces to user model code + # A single IRNode could correspond to multiple lines of code + stack_traces: OrderedSet[str] = OrderedSet() + origins = self.origins + if isinstance(self, ExternKernel): + origin_node = self.get_origin_node() + if self.origin_node: + origins = OrderedSet([origin_node]) + for node in origins: + if hasattr(node, "stack_trace") and node.stack_trace: + # nodes in the backward graph don't have mapping to pre_grad_graph + stack_traces.add(node.stack_trace) + else: + pre_grad_nodes = ( + torch._inductor.debug._inductor_post_to_pre_grad_nodes.get( + "postToPre", + {}, + # pyrefly: ignore [missing-attribute] + ).get(node.name, []) + ) + if not isinstance(pre_grad_nodes, list): + continue + for node_name in pre_grad_nodes: + stack_trace = ( + torch._inductor.debug._inductor_pre_grad_node_stack_trace.get( + node_name, None + ) + ) + if stack_trace: + stack_traces.add(stack_trace) + return stack_traces + + def common_repr(self, shorten: bool = True) -> Sequence[str]: + origins = f"origins={getattr(self, 'origins', '')}" + if shorten and len(origins) > 64: + # this can get *very* long + origins = f"{origins[:61]}..." + if not self.get_stack_traces(): + return [origins] + + stack_trace_str = [] + for stack_trace in self.get_stack_traces(): + stack_trace_str.append("stack_traces = {") + stack_trace_str += stack_trace.split("\n") + stack_trace_str.append("}") + return [origins] + stack_trace_str + + def str_helper( + self, lines: Sequence[object], shorten: bool = True, multiline: bool = True + ) -> str: + lines = list(lines) + list(self.common_repr(shorten)) + lines = list(map(str, lines)) + if multiline: + # pyrefly: ignore [no-matching-overload] + new_lines = indent(",\n".join(lines)) + return f"{type(self).__name__}(\n{new_lines}\n)" + else: + return f"{type(self).__name__}({lines})" + + def get_dtype(self) -> torch.dtype: + return self.dtype + + def maybe_get_dtype(self) -> torch.dtype | None: + try: + return self.get_dtype() + except NotImplementedError: + return None + + def get_layout(self) -> Layout: + raise NotImplementedError(f"get_layout() is not implemented by {type(self)}!") + + def maybe_get_layout(self) -> Layout | None: + try: + return self.get_layout() + except NotImplementedError: + return None + + def get_output_spec(self) -> OutputSpec: + return self.get_layout() + + def maybe_get_output_spec(self) -> OutputSpec | None: + try: + return self.get_output_spec() + except NotImplementedError: + return None + + def has_tensor_output(self) -> bool: + """True for single tensor output (excludes MultiOutput)""" + return isinstance(self.maybe_get_output_spec(), Layout) + + def get_size(self) -> Sequence[_IntLike]: + raise NotImplementedError(f"get_size() is not implemented by {type(self)}!") + + def maybe_get_size(self) -> Sequence[_IntLike] | None: + try: + return self.get_size() + except NotImplementedError: + return None + + @property + def shape(self) -> _IntLike | sympy.Rel | Sequence[_IntLike]: + return self.get_size() + + def get_numel(self) -> Expr: + return sympy_product(self.get_size()) + + def is_zero_elements(self) -> bool: + return V.graph.sizevars.statically_known_true(sympy.Eq(self.get_numel(), 0)) + + def realize(self) -> str | None: + """ + If the IRNode refers to data which has not been materialized (e.g., + it is a Pointwise/Reduction that could potentially have more + compute fused into it), realize the IRNode into physical memory, + ending the possibility of fusing into it, but allowing, e.g., multiple + users to access the data without having to recompute. + + Check StorageBox.realize for a particularly notable implementation. + + TODO(ezyang): I think, in principle, every IRNode should have an + implementation of this, and most of the time no-op is OK, but you + really do have to audit each IRNode for this, so for now, raise + an error if it's not implemented. Note that some code in graph.py + will catch this thrown error and suppress it with a warning. + """ + raise NotImplementedError(f"realize NYI on {type(self)}") + + def codegen_reference(self, writer: IndentedBuffer | None = None) -> str: + raise NotImplementedError(f"codegen_reference NYI on {type(self)}") + + def get_device(self) -> torch.device | None: + return None + + def get_device_or_error(self) -> torch.device: + device = self.get_device() + if device is None: + raise AssertionError("Expected device is not None") + return device + + def has_exceeded_max_reads(self) -> bool: + return False + + def make_loader(self) -> Callable[[Sequence[Expr]], OpsValue]: + raise NotImplementedError(type(self).__name__) + + def make_indexer(self) -> Callable[[Sequence[Expr]], Expr]: + raise NotImplementedError(type(self).__name__) + + def get_stride(self) -> Sequence[_IntLike]: + raise NotImplementedError(type(self).__name__) + + def maybe_get_stride(self) -> Sequence[_IntLike] | None: + try: + return self.get_stride() + except NotImplementedError: + return None + + def get_name(self) -> str: + raise NotImplementedError(type(self).__name__) + + def maybe_get_name(self) -> str | None: + try: + return self.get_name() + except NotImplementedError: + return None + + def is_input_buffer(self) -> bool: + try: + return self.get_name() in V.graph.graph_inputs + except NotImplementedError: + return False + + def has_large_inner_fn(self, threshold: int | None = None) -> bool: + return False + + def mark_reuse(self, users: int, *, graph_reuse: bool = True) -> None: + """ + Hint that this node's value will be reused. + + `users` estimates the reuse count. When `graph_reuse` is true, this + represents graph fanout and can trigger fanout-based realization + heuristics. When false, the reuse comes from loop-level indexing, such + as a broadcast expand, and should not be treated as graph fanout. + """ + + def realize_hint(self) -> None: + pass + + def unwrap_view(self) -> IRNode: + raise NotImplementedError(type(self).__name__) + + def freeze_layout(self) -> None: + raise NotImplementedError(type(self).__name__) + + def freeze_layout_with_stride_order( + self, order: Sequence[int], allow_padding: bool = False + ) -> None: + raise NotImplementedError(type(self).__name__) + + def freeze_layout_with_fill_order(self, order: Sequence[int]) -> None: + raise NotImplementedError(type(self).__name__) + + def freeze_layout_with_same_order(self, stride: Sequence[_IntLike]) -> None: + raise NotImplementedError(type(self).__name__) + + def freeze_layout_with_exact_strides( + self, exact_strides: Sequence[_IntLike], allow_padding: bool = False + ) -> None: + raise NotImplementedError(type(self).__name__) + + def get_read_writes(self) -> dependencies.ReadWrites: + raise NotImplementedError(type(self).__name__) + + def get_reads(self) -> OrderedSet[Dep]: + return self.get_read_writes().reads + + def num_reads(self) -> int: + return len(self.get_reads()) + + def get_storage_numel(self) -> _IntLike: + raise NotImplementedError(type(self).__name__) + + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + raise NotImplementedError(type(self).__name__) + + def get_reduction_type(self) -> str | None: + raise NotImplementedError(type(self).__name__) + + def get_reduction_size(self) -> Sequence[Expr]: + raise NotImplementedError(type(self).__name__) + + def is_extern(self) -> bool: + return False + + def is_no_op(self) -> bool: + return False + + def constant_to_device(self, device: torch.device) -> IRNode: + raise NotImplementedError(type(self).__name__) + + def get_mutation_names(self) -> Sequence[str]: + raise NotImplementedError(type(self).__name__) + + def get_operation_name(self) -> str: + raise NotImplementedError(type(self).__name__) + + def get_inputs_that_alias_output(self) -> Sequence[str]: + raise NotImplementedError(type(self).__name__) + + if TYPE_CHECKING: + + @property + def dtype(self) -> torch.dtype: ... + + +@ir_dataclass(frozen=False) +class Operation: + def __post_init__(self) -> None: + self.operation_name: str | None = None + self._config_patches: dict[str, Any] = {} + + def get_device(self) -> torch.device | None: + raise NotImplementedError + + def get_origin_node(self) -> torch.fx.Node | None: + if not hasattr(self, "origin_node"): + raise AssertionError('Expected hasattr(self, "origin_node")') + return self.origin_node + + def get_origins(self) -> OrderedSet[Any]: + if not hasattr(self, "origins"): + raise AssertionError('Expected hasattr(self, "origins")') + return self.origins + + def get_stream_idx(self) -> int | None: + if not hasattr(self, "stream_idx"): + raise AssertionError('Expected hasattr(self, "stream_idx")') + return self.stream_idx + + def get_mempool(self) -> tuple[int, int] | None: + if not hasattr(self, "mempool"): + raise AssertionError('Expected hasattr(self, "mempool")') + return self.mempool + + def get_operation_name(self) -> str: + if self.operation_name is None: + raise AssertionError("Expected self.operation_name is not None") + return self.operation_name + + def get_buffer_name(self) -> str | None: + return None + + def get_config_patches(self) -> dict[str, Any]: + """Get config patches for this operation (e.g., coordinate_descent_tuning).""" + return self._config_patches + + def set_config_patches(self, patches: dict[str, Any]) -> None: + """Set config patches for this operation.""" + self._config_patches = patches + + def is_extern(self) -> bool: + return False + + def is_no_op(self) -> bool: + return False + + def get_read_writes(self) -> dependencies.ReadWrites: + raise NotImplementedError + + def is_user_of(self, name: str) -> bool: + return name in self.get_read_names() + + def get_read_names(self) -> OrderedSet[str]: + return OrderedSet(dep.name for dep in self.get_reads()) + + def get_reads(self) -> OrderedSet[Dep]: + return self.get_read_writes().reads + + def get_outputs(self) -> list[Buffer]: + raise NotImplementedError + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + """ + When unbacked_only=True: + Returns the unbacked symbols which are required to be in scope in + order to successfully perform codegen for this buffer. For example, + a buffer that corresponds to an extern kernel call that takes i0 as + an argument would return {i0} here. This is used to generate necessary + dependencies that ensure we actually bind i0 in codegen before you + try to use it. + + Note that this is NOT transitive; in particular, if this buffer takes + in as input another buffer with dynamic shape (e.g., (i0,)), we will + not report it here, because you will already have a dependency + on that buffer, which will eventually have a dependency on i0 if + necessary. + + When unbacked_only=False: + Similar to `unbacked_only=True` but including all free symbols + instead of only free unbacked symbols. + """ + return OrderedSet() + + def get_workspace_size(self) -> int: + """ + Gets extra global memory size needed by this buffer. + Some algorithms (e.g. group gemm) may require extra global memory in the generated code. + """ + return 0 + + +@ir_dataclass +class Loops(IRNode): + """Base class for pointwise and reduction loop-body IR nodes.""" + + device: torch.device + dtype: torch.dtype + inner_fn: Callable[..., Any] + ranges: Sequence[_IntLike] + + @cache_on_self_and_args("Loops") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return OrderedSet().union( + *(get_free_symbols(e, unbacked_only) for e in self.ranges), + self.inner_fn_free_symbols(unbacked_only), + ) + + def _to_str(self, names: Sequence[str]) -> str: + return self.str_helper( + [ + f"'{self.device.type}'", + str(self.dtype), + self.inner_fn_str(), + ] + + [f"{name}={getattr(self, name)}" for name in names] + + [f"origin_node={self.origin_node!r}"] + ) + + def __str__(self) -> str: + return self._to_str(("ranges",)) + + __repr__ = __str__ + + def get_device(self) -> torch.device | None: + return self.device + + def get_origin_node(self) -> torch.fx.Node | None: + return self.origin_node + + def get_size(self) -> Sequence[_IntLike]: + return self.ranges + + def get_pointwise_size(self) -> Sequence[_IntLike]: + return self.ranges + + @classmethod + def create(cls, *args: Any, **kwargs: Any) -> TensorBox: + origin_node = kwargs.pop("origin_node", None) + tb = kwargs.pop("traceback", None) + r = cls(*args, **kwargs) + # Need to explicitly set origin_node here to propagate it down. + # todo(chilli): I think it would be better for IRNode to directly set + # origin_node + r._post_init_setattr("origin_node", origin_node) + r._post_init_setattr("traceback", tb or r.traceback) + return TensorBox.create(r) + + @staticmethod + def _index(ranges: Sequence[_IntLike], prefix: SymT = SymT.INDEX) -> Sequence[Expr]: + return [ + sympy.S.Zero if s == 1 else sympy_index_symbol_with_prefix(prefix, n) + for n, s in enumerate(ranges) + ] + + @cache_on_self + def inner_fn_opcount(self) -> OpCountResult: + opcounter = OpCounterCSE(V.MockHandler()) + with ( + V.set_ops_handler(opcounter), + patch.object(FlexibleLayout, "allow_indexing", True), + ): + self.inner_fn(*self.inner_fn_args()) + return opcounter.getvalue() + + def inner_fn_args(self) -> Sequence[Sequence[_IntLike]]: + return (self._index(self.ranges),) + + @cache_on_self + def inner_fn_str(self) -> str: + return V.KernelFormatterHandler.ir_to_string( + self.inner_fn, *self.inner_fn_args() + ) + + def get_realize_opcount_threshold(self, threshold: int | None = None) -> int: + if threshold is None: + threshold = 0 + realize_opcount_threshold = config.realize_opcount_threshold + if realize_opcount_threshold is None: + if is_cpu(self): + realize_opcount_threshold = config.realize_cpu_opcount_threshold + else: + realize_opcount_threshold = config._realize_opcount_threshold_default + else: + if not isinstance(realize_opcount_threshold, int): + raise AssertionError( + f"expected int realize_opcount_threshold, got {type(realize_opcount_threshold)}" + ) + return max(threshold, realize_opcount_threshold) + + def has_large_inner_fn(self, threshold: int | None = None) -> bool: + return self.inner_fn_opcount().num_ops > self.get_realize_opcount_threshold( + threshold + ) + + def inner_fn_free_symbols(self, unbacked_only: bool = False) -> OrderedSet[Symbol]: + index = self._index(self.ranges) + return extract_free_symbols(self.inner_fn, index, unbacked_only=unbacked_only) + + # returns a list of op names which references the symbol + def collect_inner_fn_symbol_usage(self, symbol: Symbol) -> OrderedSet[str]: + index = self._index(self.ranges) + handler = SymbolUsageCollectorOpsHandler(symbol) + with ( + V.set_ops_handler(handler), + ): + self.inner_fn(index) + return handler.usages + + def get_reads(self) -> OrderedSet[Dep]: + with patch.object(FlexibleLayout, "allow_indexing", True): + if self.get_reduction_type(): + return extract_read_writes( + self.make_loader(), + self.get_size(), + self.get_reduction_size(), + ).reads + else: + return extract_read_writes( + self.make_loader(), + self.get_size(), + ).reads + + def get_read_names(self) -> OrderedSet[str]: + return OrderedSet(self.inner_fn_opcount().read_buffers) + + def num_reads(self) -> int: + return len(self.inner_fn_opcount().read_buffers) + + def get_reduction_size(self) -> Sequence[Expr]: + raise NotImplementedError( + f"get_reduction_size() is not implemented by {type(self)}!" + ) + + def get_reduction_type(self) -> str | None: + raise NotImplementedError( + f"get_reduction_type() is not implemented by {type(self)}!" + ) + + def constant_to_device(self, device: torch.device) -> IRNode: + raise NotImplementedError( + f"constant_to_device() is not implemented by {type(self)}!" + ) + + +def nop_loader_fn(idx: Expr | Sequence[Expr], *, dtype: torch.dtype) -> OpsValue: + if dtype.is_floating_point: + return ops.constant(float("nan"), dtype) + else: + return ops.constant(0, dtype) + + +@ir_dataclass +class Pointwise(Loops): + def make_loader(self) -> Callable[[Sequence[Expr]], OpsValue]: + # Make zero-element loops into a no-op + if self.is_zero_elements(): + return partial(nop_loader_fn, dtype=self.dtype) + + return self.inner_fn + + def __str__(self) -> str: + return self._to_str(("ranges",)) + + __repr__ = __str__ + + def get_reduction_size(self) -> Sequence[_IntLike]: + return [] + + def get_reduction_type(self) -> str | None: + return None + + def store_output( + self, + output_name: str | None, + indexer: Callable[[Sequence[Expr]], Never], + vars: Sequence[Expr], + ) -> None: + loader = self.make_loader() + return ops.store(output_name or "unnamed", indexer(vars), loader(vars)) + + def constant_to_device(self, device: torch.device) -> IRNode: + """Move this to a given device. Requires that all reads are to constants.""" + loader = self.make_loader() + loader = patch.object(ConstantBuffer, "override_device", device)(loader) + return Pointwise( + device=device, + dtype=self.dtype, + inner_fn=loader, + ranges=self.ranges, + ) + + +@ir_dataclass +class Scatter(Pointwise): + output_indexer: Callable[[Sequence[Expr]], Expr] + scatter_mode: StoreMode = None + + def constant_to_device(self, device: torch.device) -> IRNode: + """Move this to a given device. Requires that all reads are to constants.""" + loader = self.make_loader() + loader = patch.object(ConstantBuffer, "override_device", device)(loader) + return Scatter( + device=device, + dtype=self.dtype, + inner_fn=loader, + ranges=self.ranges, + output_indexer=self.output_indexer, + scatter_mode=self.scatter_mode, + ) + + def store_output( + self, + output_name: str | None, + indexer: Callable[[Sequence[Expr]], Never], + vars: Sequence[Expr], + ) -> Any: + loader = self.make_loader() + if output_name is None: + output_name = "unnamed" + return ops.store( + output_name, + indexer(self.output_indexer(vars)), + loader(vars), + mode=self.scatter_mode, + ) + + +REDUCTION_COMBINE_FN: dict[str, Callable[..., OpsValue]] = { + "any": ops_wrapper("logical_or"), + "max": ops_wrapper("maximum"), + "fmax": ops_wrapper("fmaximum"), + "min": ops_wrapper("minimum"), + "prod": ops_wrapper("mul"), + "sum": ops_wrapper("add"), + "dot": ops_wrapper("add"), + "xor_sum": ops_wrapper("bitwise_xor"), +} + + +def get_reduction_combine_fn( + reduction_type: str, dtype: torch.dtype, arg_break_ties_left: bool = True +) -> Callable[..., object]: + if reduction_type in REDUCTION_COMBINE_FN: + combine_fn = REDUCTION_COMBINE_FN[reduction_type] + + if ( + config.strict_signed_zero + and reduction_type in ("max", "min") + and is_float_dtype(dtype) + ): + + def strict_signed_zero_combine_fn(a: object, b: object) -> OpsValue: + value = combine_fn(a, b) + return ops.where(ops.eq(a, b), b, value) + + return strict_signed_zero_combine_fn + + return combine_fn + + elif reduction_type in ( + "argmax", + "argmin", + "argmax_value", + "argmin_value", + "argmax_with_value", + "argmin_with_value", + ): + + def argmax_combine_fn( + a: tuple[object, object], b: tuple[object, object] + ) -> tuple[OpsValue, OpsValue]: + a_value, a_index = a + b_value, b_index = b + + if reduction_type in ("argmin", "argmin_value", "argmin_with_value"): + mask = ops.lt(a_value, b_value) + else: + mask = ops.gt(a_value, b_value) + + equal = ops.eq(a_value, b_value) + if is_float_dtype(dtype): + a_isnan = ops.ne(a_value, a_value) + b_isnan = ops.ne(b_value, b_value) + mask = ops.logical_or(mask, ops.gt(a_isnan, b_isnan)) + equal = ops.logical_or(equal, ops.logical_and(a_isnan, b_isnan)) + + tie = ( + ops.lt(a_index, b_index) + if arg_break_ties_left + else ops.gt(a_index, b_index) + ) + mask = ops.logical_or(mask, ops.logical_and(equal, tie)) + return ( + ops.where(mask, a_value, b_value), + ops.where(mask, a_index, b_index), + ) + + return argmax_combine_fn + + elif reduction_type == "welford_combine": + + def welford_combine_fn( + a: tuple[OpsValue, OpsValue, OpsValue], + b: tuple[OpsValue, OpsValue, OpsValue], + ) -> tuple[OpsValue, OpsValue, OpsValue]: + a_mean, a_m2, a_weight = a + b_mean, b_m2, b_weight = b + + # Guard against inf - inf = NaN when both means are infinite and + # equal. This occurs during FP16/BF16 LayerNorm when inputs + # overflow to inf. + delta = ops.where( + ops.logical_and(ops.isinf(a_mean), ops.eq(a_mean, b_mean)), + ops.constant(0.0, torch.float32), + b_mean - a_mean, + ) + new_weight = a_weight + b_weight + w2_over_w = b_weight / new_weight + return ( + a_mean + delta * w2_over_w, + a_m2 + b_m2 + delta * delta * a_weight * w2_over_w, + new_weight, + ) + + return welford_combine_fn + + else: + raise NotImplementedError(f"unknown reduction_type={reduction_type}") + + +@ir_dataclass +class Reduction(Loops): + r"""IR node representing a reduction over one or more iteration dimensions.""" + + reduction_ranges: Sequence[_IntLike] + reduction_type: ReductionType + # self.dtype represents the dst dtype + src_dtype: torch.dtype + reduction_hint: ReductionHint + # Exact eager tile; rblock 1 is the split final stage. + strict_sum_multirow: bool = False + strict_sum_rblock: int | None = None + + def __str__(self) -> str: + return self._to_str(("ranges", "reduction_ranges", "reduction_type")) + + __repr__ = __str__ + + @cache_on_self_and_args("Reduction") + def get_free_symbol_uses(self, unbacked_only: bool = False) -> OrderedSet[Symbol]: + return super().get_free_symbol_uses(unbacked_only) | OrderedSet().union( + *(get_free_symbols(e, unbacked_only) for e in self.reduction_ranges) + ) + + def get_reduction_size(self) -> Sequence[_IntLike]: + return self.reduction_ranges + + def get_reduction_type(self) -> str | None: + return self.reduction_type + + def store_reduction( + self, + output_name: str | None, + indexer: Callable[[Sequence[Expr]], Never], + vars: Sequence[Expr], + reduction_vars: Sequence[Symbol], + ) -> None: + value = ops.reduction( + self.dtype, + self.src_dtype, + self.reduction_type, + self.inner_fn(vars, reduction_vars), + ) + ops.store_reduction(output_name or "unnamed", indexer(vars), value) + + def index_length(self) -> int: + return len(self.ranges) + len(self.reduction_ranges) + + def inner_fn_args(self) -> Sequence[Sequence[Expr]]: + index = self._index(self.ranges) + rindex = self._index(self.reduction_ranges, SymT.R0_INDEX) + return (index, rindex) + + def inner_fn_free_symbols(self, unbacked_only: bool = False) -> OrderedSet[Symbol]: + index = self._index(self.ranges) + rindex = self._index(self.reduction_ranges, SymT.R0_INDEX) + return extract_free_symbols( + self.inner_fn, index, rindex, unbacked_only=unbacked_only + ) + + def constant_to_device(self, device: torch.device) -> IRNode: + """Move this to a given device. Requires that all reads are to constants.""" + loader = self.make_loader() + loader = patch.object(ConstantBuffer, "override_device", device)(loader) + return Reduction( + device=device, + dtype=self.dtype, + inner_fn=loader, + ranges=self.ranges, + reduction_ranges=self.reduction_ranges, + reduction_type=self.reduction_type, + src_dtype=self.src_dtype, + reduction_hint=ReductionHint.DEFAULT, + strict_sum_multirow=self.strict_sum_multirow, + strict_sum_rblock=self.strict_sum_rblock, + ) + + @staticmethod + def num_splits( + device: torch.device, + dst_dtype: torch.dtype, + src_dtype: torch.dtype, + inner_fn: Callable[_P, OpsValue], + ranges: Sequence[_IntLike], + reduction_ranges: Sequence[_IntLike], + reduction_type: ReductionType | Literal["scan"], + reduction_numel: Expr, + input_node: IRNode | None = None, + ) -> tuple[ReductionHint, _IntLike]: + """ + Choose the reduction hint and split count from shape and input stride information. + """ + # Use optimization_hint when all unbacked symbols have explicit hints, + # otherwise fall back conservatively. + exprs = [reduction_numel, sympy_product(ranges)] + if not V.graph.sizevars.all_unbacked_explicitly_hinted(exprs): + return ReductionHint.DEFAULT, 1 + reduction_numel_hint = V.graph.sizevars.optimization_hint(reduction_numel) + numel = sympy_product(ranges) + numel_hint = V.graph.sizevars.optimization_hint(numel) + + # The Triton backend adds REDUCE_TO_SINGLE_ELEMENT unconditionally if the + # cooperative_reductions feature flag is enabled, but we should still use a + # split scan if we don't actually do a cooperative reduction. + should_reduce_to_single_element = V.graph.has_feature( + device, BackendFeature.REDUCE_TO_SINGLE_ELEMENT + ) and ( + not is_triton(device) + or V.choices.should_use_cooperative_reduction( + device, numel, reduction_numel + ) + ) + arg_reduction_types = ( + "argmax", + "argmin", + "argmax_value", + "argmin_value", + "argmax_with_value", + "argmin_with_value", + ) + + should_split = reduction_type == "scan" or ( + not should_reduce_to_single_element + and reduction_type not in arg_reduction_types + and config.split_reductions + ) + + if reduction_type == "dot": + # Don't split when doing native matmul + return ReductionHint.DEFAULT, 1 + + props = DeviceProperties.create(device) + num_sm = props.multi_processor_count + min_elements_per_thread = 32 + if should_split: + inner_reduction_splits: Callable[[int, int], int] = functools.partial( + V.choices.reduction_split_factor, device, inner_reduction=True + ) + outer_reduction_splits: Callable[[int, int], int] = functools.partial( + V.choices.reduction_split_factor, device, inner_reduction=False + ) + else: + + def inner_reduction_splits( + reduction_numel_hint: int, + numel_hint: int, + ) -> int: + return 1 + + outer_reduction_splits = inner_reduction_splits + + # easy cases + if numel_hint == 1: + split = inner_reduction_splits(reduction_numel_hint, numel_hint) + if split == 1: + # No need to split. + return ReductionHint.INNER, split + if input_node is not None and isinstance(input_node, TensorBox): + with patch.object(FlexibleLayout, "allow_indexing", True): + ( + new_ranges, + new_reduction_ranges, + ) = extract_input_node_reduction_ranges(input_node) + if new_ranges is not None and new_reduction_ranges is not None: + extracted_numel_hint = ( + V.graph.sizevars.replace_backed_symbols_with_hints( + sympy_product(new_ranges + new_reduction_ranges) + ) + ) + if reduction_numel_hint == extracted_numel_hint: + log.debug( + "Use previous IRNode's range and reduction_ranges instead of split. " + "current ranges: %s, current reduction ranges: %s, current split: %d, " + "new ranges: %s, new reduction ranges: %s", + ranges, + reduction_ranges, + split, + new_ranges, + new_reduction_ranges, + ) + # If the input_node or its dependent nodes are also Reduction nodes, + # use reduction_sizes of this node or its dependent nodes directly. + return ReductionHint.INNER, -1 + return ReductionHint.INNER, split + if ( + reduction_numel_hint <= min_elements_per_thread + or numel_hint >= num_sm * 2 * 32 + ): + return ReductionHint.DEFAULT, 1 + + r = Reduction( + device=device, + dtype=dst_dtype, + inner_fn=inner_fn, + ranges=ranges, + reduction_ranges=reduction_ranges, + reduction_type=reduction_type if reduction_type != "scan" else "sum", + src_dtype=src_dtype, + reduction_hint=ReductionHint.DEFAULT, + ) + + def get_read_indices(r: Reduction) -> tuple[Sequence[Expr], bool]: + device = r.get_device() + if device is None: + raise AssertionError("Expected device is not None") + cb = ComputedBuffer( + name=None, + layout=FlexibleLayout( + device=device, + dtype=r.get_dtype(), + size=r.get_size(), + ), + data=r, + ) + read_writes = cb.get_read_writes() + # try finding the full size producer + # TODO this will fail for something like ((1, N) * (N, 1)).sum() + # this would also possibly be wrong for producers with the different contiguity but we hope those cases are rare + if read_writes.range_vars is None: + raise AssertionError("Expected read_writes.range_vars is not None") + range_vars = [ + var + for var in read_writes.range_vars + if isinstance(var, Expr) and not isinstance(var, sympy.Number) + ] + (_, reduction_vars), _ = dependencies.index_vars_squeeze( + r.get_size(), r.get_reduction_size() + ) + reduction_vars = [ + var + for var in reduction_vars + if isinstance(var, Expr) and not isinstance(var, sympy.Number) + ] + indices = [] + broadcasted_reduction_indices = [] + changed = False + for md in sorted(read_writes.reads, key=lambda x: x.name): + free_symbols = md.index.free_symbols + is_full_size_read = all(var in free_symbols for var in range_vars) + # Prefer full-size reads, but fall back to reads that still + # vary across the reduction. Missing reduction vars are + # zero-stride broadcasts, not proof of an inner reduction. + is_broadcasted_reduction_read = not is_full_size_read and any( + var in free_symbols for var in reduction_vars + ) + if is_full_size_read: + indices.append(md.index) + elif is_broadcasted_reduction_read: + broadcasted_reduction_indices.append(md.index) + if is_full_size_read or is_broadcasted_reduction_read: + if md.name in V.graph.name_to_buffer: + buf = V.graph.name_to_buffer[md.name] + original_stride = getattr(buf.layout, "stride", None) + buf.decide_layout() + if getattr(buf.layout, "stride", None) != original_stride: + changed = True + return indices or broadcasted_reduction_indices, changed + + indices, changed = get_read_indices(r) + if changed: + indices, _ = get_read_indices(r) + + if len(indices) == 0: + # TODO determine splits when all inputs are broadcast + return ReductionHint.DEFAULT, 1 + + (_, reduction_vars), ranges1 = dependencies.index_vars_squeeze( + r.get_size(), r.get_reduction_size() + ) + num_outer = 0 + num_inner = 0 + for i in indices: + j = V.graph.sizevars.simplify_with_ranges(i, ranges1) + strides = V.graph.sizevars.stride_hints( + j, reduction_vars, list(ranges1.keys()) + ) + # A 0 stride does not make a reduction contiguous. + # This can happen when the reduction ranges contains a 1. + outer = all(s == 0 or s > 1 for s in strides) + if outer: + num_outer += 1 + else: + num_inner += 1 + if num_inner > num_outer: + return ReductionHint.INNER, inner_reduction_splits( + reduction_numel_hint, numel_hint + ) + else: + return ReductionHint.OUTER, outer_reduction_splits( + reduction_numel_hint, numel_hint + ) + + @staticmethod + def _unroll_reduction_fn( + inner_fn: Callable[[Sequence[_IntLike], Sequence[_IntLike]], OpsValue], + reduction_ranges: Sequence[_IntLike], + reduction_type: str, + src_dtype: torch.dtype, + ) -> Callable[[Sequence[_IntLike]], OpsValue]: + """Convert inner_fn from a reduction to an pointwise""" + reduction_ranges = V.graph.sizevars.guard_int_seq(reduction_ranges) + + combine_fn = get_reduction_combine_fn(reduction_type, src_dtype) + + def fn(index: Sequence[_IntLike]) -> Any: + return functools.reduce( + combine_fn, + ( + value_fn(index, rindex) + for rindex in itertools.product( + *[range(x) for x in reduction_ranges] + ) + ), + ) + + value_fn: Callable[[Sequence[_IntLike], Sequence[_IntLike]], Any] + if reduction_type in ( + "argmin", + "argmax", + "argmin_value", + "argmax_value", + "argmin_with_value", + "argmax_with_value", + ): + flatten_index = _fixed_indexer( + reduction_ranges, + FlexibleLayout.contiguous_strides(reduction_ranges), + ) + + def value_fn( + index: Sequence[_IntLike], rindex: Sequence[_IntLike] + ) -> tuple[OpsValue, OpsValue]: + rindex = [sympy.expand(i) for i in rindex] + value = inner_fn(index, rindex) + if isinstance(value, tuple): + return value + return ( + value, + ops.index_expr(flatten_index(rindex), torch.int64), + ) + + if reduction_type in ("argmin_with_value", "argmax_with_value"): + return fn + if reduction_type in ("argmin_value", "argmax_value"): + return lambda index: fn(index)[0] + return lambda index: fn(index)[1] + else: + value_fn = inner_fn + return fn + + @classmethod + # pyrefly: ignore [bad-override] + def create( + cls, + device: torch.device, + dst_dtype: torch.dtype, + src_dtype: torch.dtype, + inner_fn: Callable[..., Any], + ranges: Sequence[_IntLike], + reduction_ranges: Sequence[_IntLike], + reduction_type: ReductionType, + reduction_hint: ReductionHint = ReductionHint.DEFAULT, + input_node: IRNode | None = None, + *, + strict_sum: bool = False, + ) -> TensorBox: + """ + Create a reduction node. May split the reduction to multiple layers to expose + more parallelism. + """ + reduction_numel = V.graph.sizevars.simplify(sympy_product(reduction_ranges)) + + if reduction_numel == 0: + # N.B. This is a hack to generate the literal of the given type + # Ideally, we should be fixing `def constant` in triton.py + # but it breaks due to hardcoded dtypes in other places + def py_cnst(val: object) -> bool | float | int: + if dst_dtype == torch.bool: + return bool(val) + elif dst_dtype.is_floating_point: + if not isinstance(val, SupportsFloat): + raise AssertionError(type(val)) + return float(val) + else: + if not isinstance(val, SupportsInt): + raise AssertionError(type(val)) + return int(val) + + rtypes_to_inits = { + "sum": py_cnst(0), + "xor_sum": py_cnst(0), + "prod": py_cnst(1), + "any": py_cnst(0), + # "all" is desugared to `!any(!val)` + } + + if reduction_type not in rtypes_to_inits: + raise AssertionError( + f"{reduction_type} not supported for zero-dimension tensors!" + ) + + def const_fn(index: int) -> OpsValue: + return ops.constant(rtypes_to_inits[reduction_type], dst_dtype) + + return Pointwise.create( + device=device, + dtype=src_dtype, + inner_fn=const_fn, + ranges=list(ranges), + ) + + strict_split = None + strict_sum_multirow = False + strict_sum_rblock = None + if strict_sum and reduction_hint in ( + ReductionHint.DEFAULT, + ReductionHint.INNER, + ): + num_outputs = sympy_product(ranges) + if V.graph.sizevars.all_unbacked_explicitly_hinted( + [reduction_numel, num_outputs] + ): + guarded_reduction_numel = V.graph.sizevars.guard_int(reduction_numel) + vector_size = inner_tree_plan.vec_size(src_dtype.itemsize) + num_batches_ub = ceildiv(guarded_reduction_numel, 32 * vector_size) + int32_max = 2**31 - 1 + indexing_safe = ( + guarded_reduction_numel <= int32_max + and V.graph.sizevars.evaluate_expr( + sympy.And( + sympy.Gt(num_outputs, 0), + sympy.Le(num_outputs, int32_max), + sympy.Le(num_outputs * num_batches_ub, int32_max), + ), + fallback_value=False, + ) + ) + if indexing_safe: + strict_split = 1 + strict_sum_multirow = ( + guarded_reduction_numel + <= vector_size * inner_tree_plan._K_MULTIROW_MAX_LOADS + ) + if strict_sum_multirow: + num_loads = ceildiv(guarded_reduction_numel, vector_size) + num_loads = 1 << (num_loads - 1).bit_length() + strict_sum_rblock = num_loads * vector_size + else: + params = inner_tree_plan.compute_inner_tree_params( + guarded_reduction_numel, + 1, + vector_size, + ) + strict_sum_rblock = params.batch_total_elements + if ( + params.num_batches > inner_tree_plan._K_TWO_KERNEL_THRESHOLD + and guarded_reduction_numel % strict_sum_rblock == 0 + ): + strict_split = params.num_batches + strict_sum = strict_split is not None + + if strict_sum_multirow: + if strict_sum_rblock is None: + raise AssertionError("strict multirow sum requires a reduction block") + actual_reduction_numel = reduction_numel + original_inner_fn = inner_fn + default = cls.default_value(reduction_type, dst_dtype) + + def padded_inner_fn( + index: Sequence[Symbol], reduction_index: Sequence[Symbol] + ) -> OpsValue: + (rindex,) = reduction_index + + index_dtype = dtype_from_size(actual_reduction_numel) + mask = ops.lt( + ops.index_expr(rindex, index_dtype), + ops.index_expr(actual_reduction_numel, index_dtype), + ) + body = functools.partial(original_inner_fn, index, reduction_index) + return ops.masked(mask, body, default) + + inner_fn = cast(Callable[..., Any], padded_inner_fn) + reduction_ranges = [sympy.Integer(strict_sum_rblock)] + reduction_numel = sympy.Integer(strict_sum_rblock) + + if reduction_numel == 1 and not strict_sum: + # this reduction is actually a pointwise op + if reduction_type in ("argmin", "argmax"): + + def fn(index: int) -> OpsValue: + return ops.constant(0, dst_dtype) + + else: + + def fn(index: int) -> OpsValue: + reduction_index = [sympy.S.Zero for _ in reduction_ranges] + return inner_fn(index, reduction_index) + + return Pointwise.create( + device=device, dtype=dst_dtype, inner_fn=fn, ranges=ranges + ) + + if ( + isinstance(reduction_numel, Integer) + and int(reduction_numel) < config.unroll_reductions_threshold + and (sympy_product(ranges) != 1 or is_gpu(device.type)) + and reduction_type != "dot" + and not strict_sum + ): + # When native matmul, don't unroll the dot reduction. + + # NB: This works around https://github.com/pytorch/pytorch/issues/140457 + # since turning reductions into pointwise ops can exacerbate this problem + return Pointwise.create( + device=device, + dtype=dst_dtype, + inner_fn=cls._unroll_reduction_fn( + inner_fn, reduction_ranges, reduction_type, src_dtype + ), + ranges=ranges, + ) + + # triton doesn't support reduce to single element well, so break it up + if strict_split is None: + hint, split = cls.num_splits( + device, + dst_dtype, + src_dtype, + inner_fn, + ranges, + reduction_ranges, + reduction_type, + reduction_numel, + input_node, + ) + else: + hint, split = ReductionHint.INNER, strict_split + + def _maybe_increase_split(split: int) -> int: + # don't apply min_num_split constraint for static shape case. + if _is_static(reduction_numel): + return split + if split > 1: + return max(split, config.min_num_split) + else: + return split + + if strict_split is None: + split = _maybe_increase_split(split) + + # intermediate reduction in split can contain complex indexing, + # and num_splits will fail to correctly set the hint + # reuse the passed hint if available + if reduction_hint == ReductionHint.DEFAULT: + reduction_hint = hint + if split == -1: + if input_node is None: + raise AssertionError("Expected input_node is not None") + with patch.object(FlexibleLayout, "allow_indexing", True): + new_ranges, new_reduction_ranges = extract_input_node_reduction_ranges( + input_node + ) + if new_ranges is None: + raise AssertionError("Expected new_ranges is not None") + if new_reduction_ranges is None: + raise AssertionError("Expected new_reduction_ranges is not None") + return cls.create_multilayer_existing_ranges( + device, + dst_dtype, + src_dtype, + inner_fn, + ranges, + reduction_ranges, + new_ranges, + new_reduction_ranges, + reduction_type, + reduction_hint, + ) + elif split > 1: + # triton doesn't support reduce to single element well, so break it up + out = cls.create_multilayer( + device, + dst_dtype, + src_dtype, + inner_fn, + ranges, + reduction_ranges, + reduction_type, + split, + reduction_hint, + input_node, + strict_sum=strict_sum, + ) + + # Find the reduction that get split + split_reduction = None + if config.triton.mix_order_reduction and isinstance(out, TensorBox): + + def _find_split_reduction( + cur_node: TensorBox, + ) -> ComputedBuffer | None: + read_names = cur_node.get_read_names() + if len(read_names) != 1: + return None + + bufname = next(iter(read_names)) + if bufname not in V.graph.name_to_buffer: + return None + buf = V.graph.name_to_buffer[bufname] + if not isinstance(buf, ComputedBuffer): + return None + + if buf.data.get_reduction_type() is None: + raise AssertionError( + "Expected buf.data.get_reduction_type() is not None" + ) + + return buf + + split_reduction = _find_split_reduction(out) + + if split_reduction: + # If a reduction is split to more than 2 layers, + # say there are 3 layers, + # we always have the correct setting for layer1 (top layer). + # The setting on layer2 may be incorrect but it's fine + # since they are never get used. + # TODO: should we skip setting these fields for layer2 + if not isinstance(split_reduction.data, Reduction): + raise AssertionError(f"{type(split_reduction.data)}") + split_reduction._split_size = split_reduction.data.reduction_ranges[0] + split_reduction._original_inner_fn = inner_fn + split_reduction._original_ranges = ranges + split_reduction._original_reduction_ranges = reduction_ranges + return out + + out = TensorBox.create( + Reduction( + device=device, + dtype=dst_dtype, + inner_fn=inner_fn, + ranges=ranges, + reduction_ranges=reduction_ranges, + reduction_type=reduction_type, + src_dtype=src_dtype, + reduction_hint=reduction_hint, + strict_sum_multirow=strict_sum_multirow, + strict_sum_rblock=strict_sum_rblock, + ) + ) + return out + + @staticmethod + def default_accumulator( + reduction_type: str, dtype: torch.dtype + ) -> _NumLike | Sequence[_NumLike]: + if reduction_type in ( + "max", + "fmax", + "argmax", + "argmax_value", + "argmax_with_value", + ): + if is_float_dtype(dtype): + return float("-inf") + elif is_boolean_dtype(dtype): + return False + else: + return torch.iinfo(dtype).min + if reduction_type in ("min", "argmin", "argmin_value", "argmin_with_value"): + if is_float_dtype(dtype): + return float("inf") + elif is_boolean_dtype(dtype): + return True + else: + return torch.iinfo(dtype).max + + zero = False if is_boolean_dtype(dtype) else 0 + one = True if is_boolean_dtype(dtype) else 1 + return { + "sum": zero, + "prod": one, + "dot": zero, + "xor_sum": zero, + "any": zero, + "welford_reduce": (zero, zero, zero), + "welford_combine": (zero, zero, zero), + "online_softmax_reduce": (float("-inf"), zero), + }[reduction_type] + + @staticmethod + def default_value( + reduction_type: str, dtype: torch.dtype + ) -> _NumLike | Sequence[_NumLike]: + if reduction_type == "welford_reduce": + return 0 + return Reduction.default_accumulator(reduction_type, dtype) + + @staticmethod + def _multilayer_second_step_hint( + split: _IntLike, numel_hint: int, reduction_hint: ReductionHint + ) -> ReductionHint: + if split == -1: + return reduction_hint + if split <= 512 and numel_hint <= 512 and reduction_hint == ReductionHint.OUTER: + return ReductionHint.OUTER_TINY + if ( + split <= 1024 + and numel_hint <= 256 + and reduction_hint == ReductionHint.OUTER + ): + return ReductionHint.OUTER_TINY + + return reduction_hint + + @classmethod + def check_for_split_dense_dim_reindexing( + cls, reduction_numel: _IntLike, input_node: IRNode | None + ) -> int | None: + """ + If we are reducing over the full tensor, and it is non-dense in the last dimension, + reindex so we reduce over the dense dimension. initially just handle complete + reduction case + """ + if input_node is None: + return None + + if not V.graph.sizevars.statically_known_equals( + input_node.get_numel(), reduction_numel + ): + return None + + input_node.realize() + try: + # finalize layout + as_storage_and_layout(input_node) + except NotImplementedError: + return None + + strides = input_node.get_stride() + + for i, s in enumerate(strides[:-1]): + if V.graph.sizevars.statically_known_equals(s, 1): + return i + + return None + + @classmethod + def _multilayer_wrap_loader( + cls, + loader: Callable[..., OpsValue], + reduction_ranges: Sequence[_IntLike], + reduction_numel: _IntLike, + split: _IntLike, + block_size: _IntLike, + default: _NumLike | Sequence[_NumLike], + input_node: IRNode | None = None, + ) -> Callable[..., object]: + dense_index = cls.check_for_split_dense_dim_reindexing( + reduction_numel, input_node + ) + reindex = View.dynamic_reshape_indexer( + reduction_ranges, [reduction_numel], dense_index + ) + need_mask = not V.graph.sizevars.statically_known_true( + sympy.Eq(Mod(reduction_numel, split), 0) + ) + + def wrapper_fn( + index: Sequence[Symbol], reduction_index: Sequence[Symbol] + ) -> OpsValue: + (reduction_index,) = reduction_index + *new_index, reduction_block = index + indices = block_size * reduction_block + reduction_index + + def body() -> OpsValue: + return loader(new_index, reindex([indices])) + + if need_mask: + index_dtype = dtype_from_size(reduction_numel) + mask = ops.lt( + ops.index_expr(indices, index_dtype), + ops.index_expr(reduction_numel, index_dtype), + ) + return ops.masked(mask, body, default) + else: + return body() + + return wrapper_fn + + @classmethod + def _multilayer_wrap_loader_existing_ranges( + cls, + loader: Callable[[Sequence[Expr], Sequence[Expr]], OpsValue], + original_ranges: Sequence[Expr], + original_reduction_ranges: Sequence[Expr], + new_ranges: Sequence[Integer], + new_reduction_ranges: Sequence[Integer], + ) -> Callable[[Sequence[Expr], Sequence[Expr]], OpsValue]: + if not all(r == 1 for r in original_ranges): + raise AssertionError( + f"Only enabled for numel_hint == 1, found {original_ranges=}" + ) + reindex = View.dynamic_reshape_indexer( + original_reduction_ranges, tuple(new_ranges) + tuple(new_reduction_ranges) + ) + + def wrapper_fn( + merged_index: Sequence[Expr], + new_reduction_index: Sequence[Expr], + ) -> OpsValue: + original_idx = merged_index[: len(original_ranges)] + new_index = merged_index[len(original_ranges) :] + return loader( + original_idx, + reindex(tuple(new_index) + tuple(new_reduction_index)), + ) + + return wrapper_fn + + @classmethod + def create_multilayer_helper( + cls, + device: torch.device, + dst_dtype: torch.dtype, + src_dtype: torch.dtype, + wrapper_fn: Callable[..., Any], + original_ranges: Sequence[Expr], + original_reduction_ranges: Sequence[Expr], + new_ranges: list[Expr], + new_reduction_ranges: list[Integer], + reduction_type: ReductionType, + split: _IntLike, + reduction_hint: ReductionHint, + strict_sum: bool = False, + ) -> TensorBox: + """ + Break a large reduction up into multiple smaller reductions + recursively + """ + # triton will automatically compute reductions in fp32 if reducing over fp16/bf16 + # within the kernel. keep the intermediate in fp32 so as to keep the whole reduction + # in fp32 and not reduce precision by breaking up the kernel into multiple layers + intermediate_dtype = ( + dst_dtype + if dst_dtype not in (torch.float16, torch.bfloat16) + else torch.float + ) + intermediate = Reduction.create( + device, + intermediate_dtype, + src_dtype, + wrapper_fn, + new_ranges, + new_reduction_ranges, + reduction_type, + reduction_hint, + strict_sum=strict_sum, + ) + intermediate.realize() + intermediate_loader = intermediate.make_loader() + + def intermediate_fn( + index: Sequence[_IntLike], reduction_index: Sequence[_IntLike] + ) -> OpsValue: + return intermediate_loader([*index, *reduction_index]) + + numel_hint = V.graph.sizevars.optimization_hint(sympy_product(original_ranges)) + reduction_hint = cls._multilayer_second_step_hint( + split, numel_hint, reduction_hint + ) + + if original_ranges != new_ranges[: len(original_ranges)]: + raise AssertionError( + "Expected original_ranges == new_ranges[: len(original_ranges)]" + ) + return TensorBox.create( + Reduction( + device=device, + dtype=dst_dtype, + inner_fn=intermediate_fn, + ranges=original_ranges, + reduction_ranges=new_ranges[len(original_ranges) :], + reduction_type=reduction_type, + src_dtype=src_dtype, + reduction_hint=reduction_hint, + strict_sum_rblock=1 if strict_sum else None, + ) + ) + + @classmethod + def create_multilayer( + cls, + device: torch.device, + dst_dtype: torch.dtype, + src_dtype: torch.dtype, + inner_fn: Callable[..., Any], + ranges: Sequence[_IntLike], + reduction_ranges: Sequence[_IntLike], + reduction_type: ReductionType, + split: _IntLike, + reduction_hint: ReductionHint, + input_node: IRNode | None = None, + *, + strict_sum: bool = False, + ) -> TensorBox: + """ + Break a large reduction up into multiple smaller reductions + recursively + """ + # TODO(jansel): realize the reduction so we can do dynamic indexing + reduction_numel = sympy_product(reduction_ranges) + block_size = FloorDiv(reduction_numel + (split - 1), split) + default = cls.default_value(reduction_type, dst_dtype) + wrapper_fn = cls._multilayer_wrap_loader( + inner_fn, + reduction_ranges, + reduction_numel, + split, + block_size, + default, + input_node, + ) + + return cls.create_multilayer_helper( + device, + dst_dtype, + src_dtype, + wrapper_fn, + ranges, + reduction_ranges, + [*ranges, split], + [block_size], + reduction_type, + split, + reduction_hint, + strict_sum, + ) + + @classmethod + def create_multilayer_existing_ranges( + cls, + device: torch.device, + dst_dtype: torch.dtype, + src_dtype: torch.dtype, + inner_fn: Callable[..., Any], + original_ranges: Sequence[_IntLike], + original_reduction_ranges: Sequence[_IntLike], + new_ranges: list[Integer], + new_reduction_ranges: list[Integer], + reduction_type: ReductionType, + reduction_hint: ReductionHint, + ) -> TensorBox: + """ + Break a large reduction up into multiple smaller reductions + recursively + """ + wrapper_fn = cls._multilayer_wrap_loader_existing_ranges( + inner_fn, + original_ranges, + original_reduction_ranges, + new_ranges, + new_reduction_ranges, + ) + return cls.create_multilayer_helper( + device, + dst_dtype, + src_dtype, + wrapper_fn, + original_ranges, + original_reduction_ranges, + [*original_ranges, *new_ranges], + new_reduction_ranges, + reduction_type, + -1, + reduction_hint, + ) + + +def _fixed_indexer( + size: Sequence[_IntLike], + stride: Sequence[_IntLike] | None = None, + offset: Expr = Integer(0), +) -> Callable[[Sequence[_IntLike]], Expr]: + """A closure containing math to read a given element""" + + def indexer(index: Sequence[_IntLike]) -> Expr: + if not (stride is not None and len(index) == len(stride)): + raise AssertionError( + "Expected stride is not None and len(index) == len(stride)" + ) + if len(index) != len(size): + raise AssertionError("Expected len(index) == len(size)") + result = offset + for idx, st, sz in zip(index, stride, size): + if sz != 1: + result = result + idx * st + return result + + return indexer + + +INNER_FN_TY: TypeAlias = Callable[[Sequence[Expr], Sequence[Expr]], OpsValue] + + +class MultiOutputReduction(Reduction): + output_index: int + + def __init__( + self, + device: torch.device, + dst_dtype: torch.dtype, + inner_fns: INNER_FN_TY | Sequence[INNER_FN_TY], + ranges: Sequence[Integer], + reduction_ranges: Sequence[Integer], + reduction_type: ReductionType, + src_dtype: torch.dtype, + reduction_hint: ReductionHint, + output_index: int, + ): + if callable(inner_fns): + inner_fns = (inner_fns,) + + loader: Callable[[Sequence[Expr], Sequence[Expr]], Any] + if len(inner_fns) == 1: + loader = inner_fns[0] + else: + + def loader( + idx: Sequence[Expr], reduction_idx: Sequence[Expr] + ) -> tuple[OpsValue, ...]: + return tuple(fn(idx, reduction_idx) for fn in inner_fns) + + super().__init__( + device=device, + dtype=dst_dtype, + inner_fn=loader, + ranges=ranges, + reduction_ranges=reduction_ranges, + reduction_type=reduction_type, + src_dtype=src_dtype, + reduction_hint=reduction_hint, + ) + self.output_index = output_index + + def store_reduction( + self, + output_name: str | None, + indexer: Callable[[Sequence[Expr]], Never], + vars: Sequence[Expr], + reduction_vars: Sequence[Symbol], + ) -> Any: + values = ops.reduction( + self.dtype, + self.src_dtype, + self.reduction_type, + self.inner_fn(vars, reduction_vars), + ) + if not isinstance(values, (tuple, list)): + raise AssertionError(type(values)) + value = values[self.output_index] + return ops.store_reduction(output_name or "unnamed", indexer(vars), value) + + +class ArgReduction(MultiOutputReduction): + """Multi-output arg reduction that returns both the selected value and index.""" + + @classmethod + def create( # type: ignore[override] + cls, + device: torch.device, + dst_dtype: torch.dtype, + src_dtype: torch.dtype, + inner_fn: Callable[..., Any], + ranges: Sequence[Expr], + reduction_ranges: Sequence[Expr], + reduction_type: ReductionType, + reduction_hint: ReductionHint = ReductionHint.DEFAULT, + input_node: IRNode | None = None, + ) -> Sequence[TensorBox]: + if reduction_type not in ("argmax_with_value", "argmin_with_value"): + raise AssertionError(f"unexpected reduction_type {reduction_type!r}") + reduction_numel = V.graph.sizevars.simplify(sympy_product(reduction_ranges)) + if reduction_numel == 0: + raise AssertionError( + f"{reduction_type} not supported for zero-dimension tensors!" + ) + + if reduction_numel == 1: + + def value_fn(index: Sequence[Expr]) -> OpsValue: + reduction_index = [sympy.S.Zero for _ in reduction_ranges] + value = inner_fn(index, reduction_index) + if isinstance(value, tuple): + return value[0] + return value + + def index_fn(index: Sequence[Expr]) -> OpsValue: + return ops.constant(0, torch.int64) + + return ( + Pointwise.create( + device=device, + dtype=dst_dtype, + inner_fn=value_fn, + ranges=list(ranges), + ), + Pointwise.create( + device=device, + dtype=torch.int64, + inner_fn=index_fn, + ranges=list(ranges), + ), + ) + + if ( + isinstance(reduction_numel, Integer) + and int(reduction_numel) < config.unroll_reductions_threshold + and (sympy_product(ranges) != 1 or is_gpu(device.type)) + ): + unrolled_fn = Reduction._unroll_reduction_fn( + inner_fn, reduction_ranges, reduction_type, src_dtype + ) + + def project(index: Sequence[Expr], output_index: int) -> OpsValue: + result = unrolled_fn(index) + if not isinstance(result, tuple): + raise AssertionError(f"expected tuple result, got {type(result)}") + return result[output_index] + + return tuple( + Pointwise.create( + device=device, + dtype=dtype, + inner_fn=partial(project, output_index=output_index), + ranges=list(ranges), + ) + for output_index, dtype in enumerate((dst_dtype, torch.int64)) + ) + + hint, split = Reduction.num_splits( + device, + dst_dtype, + src_dtype, + inner_fn, + ranges, + reduction_ranges, + reduction_type, + reduction_numel, + input_node, + ) + if split != 1: + raise AssertionError("arg reductions do not support split reductions") + if reduction_hint == ReductionHint.DEFAULT: + reduction_hint = hint + + results = tuple( + TensorBox.create( + cls( + device, + dtype, + inner_fn, + ranges, + reduction_ranges, + reduction_type, + src_dtype, + reduction_hint, + output_index, + ) + ) + for output_index, dtype in enumerate((dst_dtype, torch.int64)) + ) + for result in results: + result.realize() + return results + + +class OnlineSoftmaxReduction(MultiOutputReduction): + """Multi-output reduction that computes softmax max/sum in one pass.""" + + @classmethod + def _create_no_split( + cls, + device: torch.device, + dst_dtype: torch.dtype, + src_dtype: torch.dtype, + inner_fn: Callable[..., Any], + ranges: Sequence[Expr], + reduction_ranges: Sequence[Expr], + num_output: int, + reduction_hint: ReductionHint = ReductionHint.DEFAULT, + input_node: IRNode | None = None, + ) -> Sequence[TensorBox]: + results = tuple( + TensorBox.create( + MultiOutputReduction( + device, + dst_dtype, + inner_fn, + ranges, + reduction_ranges, + "online_softmax_reduce", + src_dtype, + reduction_hint, + output_idx, + ) + ) + for output_idx in range(num_output) + ) + for t in results: + t.realize() + return results + + @classmethod + def create( # type: ignore[override] + cls, + device: torch.device, + dst_dtype: torch.dtype, + src_dtype: torch.dtype, + inner_fn: Callable[..., Any], + ranges: Sequence[Expr], + reduction_ranges: Sequence[Expr], + num_output: int, + reduction_hint: ReductionHint = ReductionHint.DEFAULT, + input_node: IRNode | None = None, + ) -> Sequence[TensorBox]: + reduction_numel = V.graph.sizevars.simplify(sympy_product(reduction_ranges)) + hint, split = Reduction.num_splits( + device, + dst_dtype, + src_dtype, + inner_fn, + ranges, + reduction_ranges, + reduction_type="online_softmax_reduce", + reduction_numel=reduction_numel, + input_node=input_node, + ) + if reduction_hint == ReductionHint.DEFAULT: + reduction_hint = hint + if split > 1: + return cls.create_multilayer( + device, + dst_dtype, + src_dtype, + inner_fn, + ranges, + reduction_ranges, + num_output, + split, + reduction_hint, + input_node, + ) + return cls._create_no_split( + device, + dst_dtype, + src_dtype, + inner_fn, + ranges, + reduction_ranges, + num_output, + reduction_hint, + input_node, + ) + + @classmethod + def create_multilayer( + cls, + device: torch.device, + dst_dtype: torch.dtype, + src_dtype: torch.dtype, + inner_fn: Callable[..., Any], + ranges: Sequence[Expr], + reduction_ranges: Sequence[Expr], + num_output: int, + split: _IntLike, + reduction_hint: ReductionHint, + input_node: IRNode | None = None, + ) -> Sequence[TensorBox]: + reduction_numel = sympy_product(reduction_ranges) + block_size = FloorDiv(reduction_numel + (split - 1), split) + dense_index = cls.check_for_split_dense_dim_reindexing( + reduction_numel, input_node + ) + reindex = View.dynamic_reshape_indexer( + reduction_ranges, [reduction_numel], dense_index + ) + need_mask = not V.graph.sizevars.statically_known_true( + sympy.Eq(Mod(reduction_numel, split), 0) + ) + + def wrapper_fn( + index: Sequence[Symbol], reduction_index: Sequence[Symbol] + ) -> tuple[OpsValue, OpsValue]: + (reduction_index,) = reduction_index + *new_index, reduction_block = index + indices = block_size * reduction_block + reduction_index + + def body() -> OpsValue: + return inner_fn(new_index, reindex([indices])) + + one = ops.constant(1, src_dtype) + if need_mask: + index_dtype = dtype_from_size(reduction_numel) + mask = ops.lt( + ops.index_expr(indices, index_dtype), + ops.index_expr(reduction_numel, index_dtype), + ) + return ( + ops.masked(mask, body, float("-inf")), + ops.where(mask, one, ops.constant(0, src_dtype)), + ) + else: + return body(), one + + intermediate_dtype = ( + dst_dtype + if dst_dtype not in (torch.float16, torch.bfloat16) + else torch.float + ) + intermediates = cls._create_no_split( + device, + intermediate_dtype, + src_dtype, + wrapper_fn, + [*ranges, split], + [block_size], + num_output, + reduction_hint, + ) + for i in intermediates: + i.realize() + + intermediate_loaders = tuple(i.make_loader() for i in intermediates) + + def intermediate_fn( + index: Sequence[_IntLike], reduction_index: Sequence[_IntLike] + ) -> tuple[OpsValue, ...]: + return tuple( + loader([*index, *reduction_index]) for loader in intermediate_loaders + ) + + numel_hint = V.graph.sizevars.optimization_hint(sympy_product(ranges)) + reduction_hint = cls._multilayer_second_step_hint( + split, numel_hint, reduction_hint + ) + + return cls._create_no_split( + device, + dst_dtype, + intermediate_dtype, + intermediate_fn, + ranges, + [split], + num_output, + reduction_hint, + ) + + +class WelfordReduction(MultiOutputReduction): + @classmethod + def create( # type: ignore[override] + cls, + device: torch.device, + dtype: torch.dtype, + inner_fns: Sequence[Callable[..., Any]], + ranges: list[Integer], + reduction_ranges: list[Integer], + reduction_type: ReductionType, + reduction_hint: ReductionHint = ReductionHint.DEFAULT, + ) -> Sequence[TensorBox]: + if reduction_type not in ("welford_reduce", "welford_combine"): + raise AssertionError( + 'Expected reduction_type in ("welford_reduce", "welford_combine")' + ) + if config.mtia.disable_welford_reduction: + raise AssertionError( + "welford reduction usage is explicitly disabled, please check you config" + ) + + reduction_numel = V.graph.sizevars.simplify(sympy_product(reduction_ranges)) + + def const(val: int) -> TensorBox: + def inner_fn(idx: Sequence[Expr]) -> OpsValue: + return ops.constant( + val, + dtype, + ) + + return Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=list(ranges), + ) + + if reduction_numel == 0: + mean = const(0) + m2 = const(0) + weight = const(0) + return mean, m2, weight + + if reduction_numel == 1: + + def copy( + loader: Callable[[Sequence[Expr], Sequence[Expr]], OpsValue], + ) -> TensorBox: + def inner_fn(idx: Sequence[Expr]) -> OpsValue: + reduction_index = [sympy.S.Zero for _ in reduction_ranges] + return loader(idx, reduction_index) + + return Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=list(ranges), + ) + + if reduction_type == "welford_reduce": + return copy(inner_fns[0]), const(0), const(1) + else: + return tuple(copy(fn) for fn in inner_fns) + + # TODO: Unrolled reduction + # if ( + # isinstance(reduction_numel, Integer) + # and int(reduction_numel) + # < config.unroll_reductions_threshold + # and sympy_product(ranges) != 1 + # ): + # return Pointwise.create( + # device, + # dst_dtype, + # cls._unroll_reduction_fn( + # inner_fn, reduction_ranges, reduction_type, src_dtype, + # ), + # ranges, + # ) + + # triton doesn't support reduce to single element well, so break it up + hint, split = Reduction.num_splits( + device, + dtype, + dtype, + inner_fns[0], + ranges, + reduction_ranges, + reduction_type=reduction_type, + reduction_numel=reduction_numel, + ) + # intermediate reduction in split can contain complex indexing, + # and num_splits will fail to correctly set the hint + # reuse the passed hint if available + if reduction_hint == ReductionHint.DEFAULT: + reduction_hint = hint + if split > 1: + # triton doesn't support reduce to single element well, so break it up + return cls.create_multilayer( + device, + dtype, + inner_fns, + ranges, + reduction_ranges, + reduction_type, + split, + reduction_hint, + ) + + results = [ + TensorBox.create( + WelfordReduction( + device, + dtype, + inner_fns, + ranges, + reduction_ranges, + reduction_type, + dtype, + reduction_hint, + output_idx, + ) + ) + for output_idx in range(3) + ] + for t in results: + t.realize() + return results + + @staticmethod + def default_value( + reduction_type: str, dtype: torch.dtype + ) -> _NumLike | Sequence[_NumLike]: + return (0, 0, 0) + + @classmethod + def create_multilayer( # type: ignore[override] + cls, + device: torch.device, + dtype: torch.dtype, + inner_fns: Sequence[Callable[..., Any]], + ranges: list[Integer], + reduction_ranges: list[Integer], + reduction_type: ReductionType, + split: _IntLike, + reduction_hint: ReductionHint, + ) -> Sequence[TensorBox]: + """ + Break a large reduction up into multiple smaller reductions + recursively + """ + reduction_numel = sympy_product(reduction_ranges) + need_mask = not V.graph.sizevars.statically_known_true( + sympy.Eq(Mod(reduction_numel, split), 0) + ) + + if need_mask and reduction_type != "welford_combine": + # If we need mask, then "welford_reduce" doesn't work because + # masked inputs shouldn't count towards the welford weight + + def constant( + idx: Sequence[Expr], reduction_idx: Sequence[Expr], value: int + ) -> OpsValue: + return ops.constant(value, dtype) + + return cls.create_multilayer( + device=device, + dtype=dtype, + inner_fns=( + inner_fns[0], + partial(constant, value=0), + partial(constant, value=1), + ), + ranges=ranges, + reduction_ranges=reduction_ranges, + reduction_type="welford_combine", + split=split, + reduction_hint=reduction_hint, + ) + + block_size = FloorDiv(reduction_numel + (split - 1), split) + intermediates = WelfordReduction.create( + device, + dtype, + tuple( + cls._multilayer_wrap_loader( + loader, + reduction_ranges, + reduction_numel, + split, + block_size, + default=0, + ) + for loader in inner_fns + ), + [*ranges, split], + [block_size], + reduction_type, + reduction_hint, + ) + for i in intermediates: + i.realize() + + def intermediate_loader_fn( + index: Sequence[Expr], + reduction_index: Sequence[Expr], + loader: Callable[[Sequence[Expr]], OpsValue], + ) -> OpsValue: + return loader([*index, *reduction_index]) + + # numel_hint is only used to choose between ReductionHint.OUTER vs + # OUTER_TINY, which is a performance heuristic, not a correctness decision. + numel_hint = V.graph.sizevars.optimization_hint(sympy_product(ranges)) + reduction_hint = cls._multilayer_second_step_hint( + split, numel_hint, reduction_hint + ) + return WelfordReduction.create( + device, + dtype, + tuple( + partial(intermediate_loader_fn, loader=i.make_loader()) + for i in intermediates + ), + ranges, + [split], + # welford_reduce turns one input into three outputs, which are combined with welford_combine + "welford_combine", + reduction_hint, + ) + + +@ir_dataclass +class Scan(Loops): + scan_ranges: list[Integer] + size: list[Integer] + combine_fn: Callable[[tuple[Any, ...], tuple[Any, ...]], tuple[Any, ...]] + reindex: Callable[[Sequence[_IntLike], Sequence[_IntLike]], Sequence[_IntLike]] + reduction_hint: ReductionHint + output_index: int + # output_index indexes the following tuples + dtypes: tuple[torch.dtype, ...] + inner_fns: tuple[Callable[..., Any], ...] + + # HACK we mimic reduction + + @cache_on_self_and_args("Scan") + def get_free_symbol_uses(self, unbacked_only: bool = False) -> OrderedSet[Symbol]: + # TODO: Can combine_fn/reindex close over unbacked symbols? If so, we + # need to explicitly represent the closure so we can pull out unbacked + # symbols here + return ( + super().get_free_symbol_uses(unbacked_only) + | OrderedSet().union( + *(get_free_symbols(e, unbacked_only) for e in self.scan_ranges) + ) + | OrderedSet().union( + *(get_free_symbols(e, unbacked_only) for e in self.size) + ) + ) + + def __post_init__(self) -> None: + if len(self.ranges) + len(self.scan_ranges) != len(self.size): + raise AssertionError( + "Expected len(self.ranges) + len(self.scan_ranges) == len(self.size)" + ) + super().__post_init__() + + def store_reduction( + self, + output_name: str | None, + indexer: Callable[[Sequence[_IntLike]], Never], + vars: Sequence[Expr], + scan_vars: Sequence[Symbol], + ) -> Any: + idx = self.reindex(vars, scan_vars) + values = tuple(inner_fn(idx) for inner_fn in self.inner_fns) + result = ops.scan(self.dtypes, self.combine_fn, values) + return ops.store( + output_name or "unnamed", indexer(idx), result[self.output_index] + ) + + def get_reduction_type(self) -> str | None: + # return self.scan_op + return "custom" + + def get_reduction_size(self) -> Sequence[Expr]: + return self.scan_ranges + + def get_size(self) -> Sequence[Expr]: + return self.size + + def get_pointwise_size(self) -> Sequence[Expr]: + return self.ranges + + def index_length(self) -> int: + return len(self.ranges) + len(self.scan_ranges) + + def inner_fn_args(self) -> Sequence[Sequence[_IntLike]]: + index = self._index(self.ranges) + rindex = self._index(self.scan_ranges, SymT.R0_INDEX) + idx = self.reindex(index, rindex) + return (idx,) + + def inner_fn_free_symbols(self, unbacked_only: bool = False) -> OrderedSet[Symbol]: + index = self._index(self.ranges) + rindex = self._index(self.scan_ranges, SymT.R0_INDEX) + idx = self.reindex(index, rindex) + return extract_free_symbols(self.inner_fn, idx, unbacked_only=unbacked_only) + + @classmethod + def create( # type: ignore[override] + cls, + device: torch.device, + dtypes: tuple[torch.dtype, ...], + inner_fns: tuple[Callable[[Sequence[Expr]], Any], ...], + size: list[Integer], + axis: int, + combine_fn: Callable[[tuple[Any, ...], tuple[Any, ...]], tuple[Any, ...]], + reduction_hint: ReductionHint = ReductionHint.DEFAULT, + *, + # Whether we have the option to fallback to aten + can_fallback_to_aten: bool = True, + **kwargs: Any, + ) -> Sequence[TensorBox | None]: + pointwise_ranges = [*size[:axis], *size[axis + 1 :]] + scan_ranges = [size[axis]] + + if not V.graph.has_feature(device, BackendFeature.SCAN): + return [None] * len(dtypes) + + if len(dtypes) > 1 and not V.graph.has_feature( + device, BackendFeature.TUPLE_REDUCTION + ): + return [None] * len(dtypes) + + sizevars = V.graph.sizevars + scan_numel = sizevars.simplify(sympy_product(scan_ranges)) + + if len(dtypes) != len(inner_fns): + raise AssertionError("Expected len(dtypes) == len(inner_fns)") + + # Scan with a single element is just a copy + if sizevars.statically_known_true(sympy.Le(scan_numel, 1)): + return [ + Pointwise.create( + device=device, + dtype=dtypes[output_index], + inner_fn=inner_fns[output_index], + ranges=size, + ) + for output_index in range(len(dtypes)) + ] + + reduction_hint, num_splits = cls.num_splits( + device=device, + dtype=dtypes[0], + inner_fn=inner_fns[0], + axis=axis, + pointwise_ranges=pointwise_ranges, + scan_ranges=scan_ranges, + combine_fn=combine_fn, + scan_numel=scan_numel, + ) + scan_type = Scan + if num_splits > 1: + triton_supports_split = ( + # pyrefly: ignore [unsupported-operation] + torch.version.hip is None or (has_triton and triton_version >= "3.3.0") + ) + supports_split = ( + triton_supports_split + and len(dtypes) == 1 + and not torch.are_deterministic_algorithms_enabled() + ) + if not supports_split: + if can_fallback_to_aten: + # Fallback to ATen + return [None] * len(dtypes) + else: + num_splits = 1 + else: + scan_type = SplitScan + + def reindex(index: Sequence[Expr], scan_index: Sequence[Expr]) -> list[Expr]: + if len(scan_index) != len(scan_ranges): + raise AssertionError("Expected len(scan_index) == len(scan_ranges)") + if len(index) != len(pointwise_ranges): + raise AssertionError("Expected len(index) == len(pointwise_ranges)") + return [*index[:axis], *scan_index, *index[axis:]] + + results = [ + TensorBox.create( + scan_type( + device=device, + dtype=dtypes[output_index], + dtypes=dtypes, + inner_fn=inner_fns[output_index], + inner_fns=inner_fns, + size=size, + ranges=pointwise_ranges, + scan_ranges=scan_ranges, + combine_fn=combine_fn, + reindex=reindex, + reduction_hint=reduction_hint, + output_index=output_index, + **kwargs, + ) + ) + for output_index in range(len(dtypes)) + ] + + for result in results: + result.realize() + + return results + + @classmethod + def num_splits( + cls, + device: torch.device, + dtype: torch.dtype, + inner_fn: Callable[[Sequence[Expr]], OpsValue], + axis: int, + pointwise_ranges: list[Integer], + scan_ranges: list[Integer], + combine_fn: Callable[[tuple[Any, ...], tuple[Any, ...]], tuple[Any, ...]], + scan_numel: Expr, + ) -> tuple[ReductionHint, _IntLike]: + # TODO: custom splitting heuristic for scan + def wrapper_fn(idx: Sequence[Expr], reduction_idx: Sequence[Expr]) -> OpsValue: + return inner_fn([*idx[:axis], *reduction_idx, *idx[axis:]]) + + return Reduction.num_splits( + device=device, + dst_dtype=dtype, + src_dtype=dtype, + inner_fn=wrapper_fn, + ranges=pointwise_ranges, + reduction_ranges=scan_ranges, + reduction_type="scan", + reduction_numel=scan_numel, + ) + + +# This signifies a scan op that should go through TritonSplitScanKernel codegen on CUDA. +@ir_dataclass +class SplitScan(Scan): + pass + + +@ir_dataclass +class Sort(Loops): + # Sorts a tuple of key, value pairs + sort_ranges: list[Integer] + size: list[Integer] + reindex: Callable[[Sequence[Expr], Sequence[Expr]], Sequence[Expr]] + reduction_hint: ReductionHint + output_index: int + # output_index indexes the following tuples + dtypes: tuple[torch.dtype, ...] + inner_fns: tuple[Callable[..., Any], ...] + + stable: bool + descending: bool + + # HACK we mimic reduction + + @cache_on_self_and_args("Sort") + def get_free_symbol_uses(self, unbacked_only: bool = False) -> OrderedSet[Symbol]: + return ( + super().get_free_symbol_uses(unbacked_only) + | OrderedSet().union( + *(get_free_symbols(e, unbacked_only) for e in self.sort_ranges) + ) + | OrderedSet().union( + *(get_free_symbols(e, unbacked_only) for e in self.size) + ) + ) + + def __post_init__(self) -> None: + if len(self.ranges) + len(self.sort_ranges) != len(self.size): + raise AssertionError( + "Expected len(self.ranges) + len(self.sort_ranges) == len(self.size)" + ) + super().__post_init__() + + def store_reduction( + self, + output_name: str | None, + indexer: Callable[[Sequence[Expr]], Expr], + vars: Sequence[Expr], + reduction_vars: Sequence[Expr], + ) -> Any: + idx = self.reindex(vars, reduction_vars) + values = tuple(inner_fn(idx) for inner_fn in self.inner_fns) + result = ops.sort(self.dtypes, values, self.stable, self.descending) + return ops.store( + output_name or "unnamed", indexer(idx), result[self.output_index] + ) + + def get_reduction_type(self) -> str | None: + return "sort" + + def get_reduction_size(self) -> Sequence[Integer]: + return self.sort_ranges + + def get_size(self) -> Sequence[Integer]: + return self.size + + def get_pointwise_size(self) -> Sequence[_IntLike]: + return self.ranges + + def index_length(self) -> int: + return len(self.ranges) + len(self.sort_ranges) + + def inner_fn_args(self) -> Sequence[Sequence[Expr]]: + index = self._index(self.ranges) + rindex = self._index(self.sort_ranges, SymT.R0_INDEX) + idx = self.reindex(index, rindex) + return (idx,) + + def inner_fn_free_symbols(self, unbacked_only: bool = False) -> OrderedSet[Symbol]: + index = self._index(self.ranges) + rindex = self._index(self.sort_ranges, SymT.R0_INDEX) + idx = self.reindex(index, rindex) + return extract_free_symbols(self.inner_fn, idx, unbacked_only=unbacked_only) + + @classmethod + def create( # type: ignore[override] + cls, + device: torch.device, + dtypes: tuple[torch.dtype, ...], + inner_fns: tuple[Callable[[list[Expr]], Any], ...], + size: list[Integer], + axis: int, + stable: bool, + descending: bool, + reduction_hint: ReductionHint = ReductionHint.DEFAULT, + **kwargs: Any, + ) -> Sequence[TensorBox | None]: + pointwise_ranges = [*size[:axis], *size[axis + 1 :]] + sort_ranges = [size[axis]] + + if not V.graph.has_feature(device, BackendFeature.SORT): + return [None] * len(dtypes) + + sizevars = V.graph.sizevars + sort_numel = sizevars.simplify(sympy_product(sort_ranges)) + + # Heuristic, smallest rblock where triton usually outperforms aten.sort. + # It also isn't bandwidth bound so fusion is unlikely to help. + # When decompose_sort_ops is enabled, skip the size limit to always + # attempt Triton sort (index dtype is widened to int32 in lowering). + if config.triton.decompose_sort_ops: + is_persistent_kernel = config.triton.persistent_reductions + else: + max_rblock = 512 + is_persistent_kernel = ( + config.triton.persistent_reductions + and sizevars.statically_known_true(sympy.Le(sort_numel, max_rblock)) + ) + if not is_persistent_kernel: + # We only support persistent triton kernels + return [None] * len(dtypes) + + if len(dtypes) != len(inner_fns): + raise AssertionError("Expected len(dtypes) == len(inner_fns)") + + # Sort with a single element is just a copy + if sizevars.statically_known_true(sympy.Le(sort_numel, 1)): + return [ + Pointwise.create( + device=device, + dtype=dtypes[output_index], + inner_fn=inner_fns[output_index], + ranges=size, + ) + for output_index in range(len(dtypes)) + ] + + def reindex(index: Sequence[Expr], sort_index: Sequence[Expr]) -> list[Expr]: + if len(sort_index) != len(sort_ranges): + raise AssertionError("Expected len(sort_index) == len(sort_ranges)") + if len(index) != len(pointwise_ranges): + raise AssertionError("Expected len(index) == len(pointwise_ranges)") + return [*index[:axis], *sort_index, *index[axis:]] + + results = [ + TensorBox.create( + Sort( + device=device, + dtype=dtypes[output_index], + dtypes=dtypes, + inner_fn=inner_fns[output_index], + inner_fns=inner_fns, + size=size, + ranges=pointwise_ranges, + sort_ranges=sort_ranges, + reindex=reindex, + reduction_hint=reduction_hint, + output_index=output_index, + stable=stable, + descending=descending, + **kwargs, + ) + ) + for output_index in range(len(dtypes)) + ] + + for result in results: + result.realize() + + return results + + +def is_storage_and_layout(x: IRNode) -> bool: + try: + as_storage_and_layout(x, freeze=False) + return True + except NotImplementedError: + return False + + +def is_contiguous_storage_and_layout(x: IRNode) -> bool: + try: + _buffer, layout = as_storage_and_layout(x, freeze=False) + # pad the stride here so we will NOT claim a tensor as contiguous + # if a padding is gonna happen. + if layout.should_pad_strides(): + if not isinstance(layout, FlexibleLayout): + raise AssertionError(type(layout)) + layout = FixedLayout( + layout.device, + layout.dtype, + layout.size, + layout._pad_strides(layout.stride, layout.size, layout.dtype), + layout.offset, + layout.is_pinned, + ) + return layout.is_contiguous() + except NotImplementedError: + return False + + +def is_dense_contiguous_storage_and_layout(x: IRNode) -> bool: + try: + _buffer, layout = as_storage_and_layout(x, freeze=False) + if not layout.is_contiguous(): + return False + return V.graph.sizevars.statically_known_equals( + layout.storage_size(), layout.offset + sympy_product(layout.size) + ) + except NotImplementedError: + return False + + +def as_storage_and_layout( + x: IRNode, + freeze: bool = True, + want_contiguous: bool = False, + stride_order: Sequence[int | Integer] | None = None, + allow_padding: bool = False, + exact_strides: Sequence[int | Integer] | None = None, +) -> tuple[StorageBox, Layout]: + """ + Try to simplify x into a StorageBox and a Layout. + + allow_padding only affect how we apply stride_order. When allow_padding + is True, we have the freedom to add padding when applying the stride_order. + """ + if isinstance(x, TensorBox): + return as_storage_and_layout( + x.data, + freeze=freeze, + want_contiguous=want_contiguous, + stride_order=stride_order, + allow_padding=allow_padding, + exact_strides=exact_strides, + ) + if isinstance(x, StorageBox): + _, layout = as_storage_and_layout( + x.data, + freeze=freeze, + want_contiguous=want_contiguous, + stride_order=stride_order, + allow_padding=allow_padding, + exact_strides=exact_strides, + ) + return x, x.data.get_layout() + if isinstance(x, Buffer): + if freeze: + if want_contiguous: + x.freeze_layout() + if not x.get_layout().is_contiguous(): + raise AssertionError("Expected x.get_layout().is_contiguous()") + elif stride_order is not None: + x.freeze_layout_with_stride_order( + stride_order, allow_padding=allow_padding + ) + elif exact_strides is not None: + x.freeze_layout_with_exact_strides( + exact_strides, allow_padding=allow_padding + ) + else: + x.decide_layout() + return StorageBox(x), x.get_layout() + if isinstance(x, ReinterpretView): + # making the base of x contiguous or stride_ordered will not necessarily make + # the ReinterpretView either, so don't pass along those arguments + buffer, _ = as_storage_and_layout( + x.data, + freeze=freeze, + ) + return buffer, x.layout + raise NotImplementedError + + +def is_stride_order_storage_and_layout( + x: IRNode, stride_order: Sequence[int | Integer] +) -> bool: + try: + _buffer, layout = as_storage_and_layout(x, freeze=False) + return layout.is_stride_ordered(stride_order) + except NotImplementedError: + return False + + +def is_unaligned(node: IRNode) -> bool: + if isinstance(node, (TensorBox, StorageBox)): + return is_unaligned(node.data) + + if isinstance(node, ReinterpretView): + layout = node.layout + has_unaligned_layout = not V.graph.sizevars.statically_known_multiple_of( + layout.offset * get_dtype_size(layout.dtype), GPU_ALIGN_BYTES + ) + return is_unaligned(node.data) or has_unaligned_layout + + if isinstance(node, Buffer): + return node.get_name() in V.graph.unaligned_buffers + + # assume to be aligned otherwise + return False + + +@ir_dataclass +class BaseView(IRNode): + data: IRNode + + @cache_on_self_and_args("BaseView") + def get_free_symbol_uses(self, unbacked_only: bool = False) -> OrderedSet[Symbol]: + return self.data.get_free_symbol_uses(unbacked_only) + + def make_reindexer(self) -> Callable[[Sequence[Expr]], Sequence[Expr]]: + raise NotImplementedError(f"make_reindexer NYI on {self}") + + def make_indexer(self) -> Callable[[Sequence[Expr]], Expr]: + inner = self.data.make_indexer() + reindex = self.make_reindexer() + + def indexer(idx: Sequence[Expr]) -> Expr: + return inner(reindex(idx)) + + return indexer + + def make_loader(self) -> Callable[[Sequence[Expr]], OpsValue]: + inner = self.data.make_loader() + reindex = self.make_reindexer() + + def loader(idx: Sequence[Expr]) -> OpsValue: + return inner(reindex(idx)) + + return loader + + @property + def dtype(self) -> torch.dtype: + return self.data.get_dtype() + + def get_layout(self) -> Layout: + return self.data.get_layout() + + def get_device(self) -> torch.device | None: + return self.data.get_device() + + def get_origin_node(self) -> torch.fx.Node | None: + return None + + def get_name(self) -> str: + return self.data.get_name() + + def get_pointwise_size(self) -> Sequence[Expr]: + return self.get_size() + + def mark_reuse(self, users: int, *, graph_reuse: bool = True) -> None: + return self.data.mark_reuse(users, graph_reuse=graph_reuse) + + def has_exceeded_max_reads(self) -> bool: + return self.data.has_exceeded_max_reads() + + def realize(self) -> str | None: + return self.data.realize() + + def realize_hint(self) -> None: + self.data.realize_hint() + + def get_storage_numel(self) -> _IntLike: + return self.data.get_storage_numel() + + def is_extern(self) -> bool: + return self.data.is_extern() + + def is_module_buffer(self) -> bool: + if not isinstance(self.data, BaseView): + raise AssertionError(type(self.data)) + return self.data.is_module_buffer() + + def get_read_names(self) -> OrderedSet[str]: + return self.data.get_read_names() + + def get_reads(self) -> OrderedSet[Dep]: + with patch.object(FlexibleLayout, "allow_indexing", True): + return extract_read_writes( + self.make_loader(), + self.get_size(), + ).reads + + def unwrap_view(self) -> IRNode: + x: IRNode = self + while isinstance(x, BaseView): + x = x.data + return x + + def constant_to_device(self, device: torch.device) -> IRNode: + """Move this to a given device. Requires that all reads are to constants.""" + loader = self.make_loader() + loader = patch.object(ConstantBuffer, "override_device", device)(loader) + return Pointwise( + device=device, + dtype=self.get_dtype(), + inner_fn=loader, + ranges=self.get_size(), + ) + + +@ir_dataclass +class ExpandView(BaseView): + size: Sequence[Expr] + + @staticmethod + def _normalize_size(x: IRNode, new_size: Sequence[_IntLike]) -> Sequence[_IntLike]: + """Replace `-1` with correct sizes""" + sizevars = V.graph.sizevars + new_size = [sympy.expand(s) for s in new_size] + old_size = x.get_size() + old_size = [None] * (len(new_size) - len(old_size)) + list(old_size) + if len(new_size) != len(old_size): + raise AssertionError("Expected len(new_size) == len(old_size)") + for i in range(len(new_size)): + if new_size[i] == -1: + if old_size[i] is None: + raise AssertionError("Expected old_size[i] is not None") + new_size[i] = old_size[i] + elif old_size[i] is None or V.graph.sizevars.is_size_one_or_false( + old_size[i] + ): + pass + elif not has_free_unbacked_symbols( + old_size + ) and not has_free_unbacked_symbols(new_size): + # Sanity check: Expect broadcast compatibility + # + # NB: new_size[i] == old_size[i] is expected to already be + # guarded because the meta formula was expected to have taught + # us this equality. + v1 = new_size[i] + v2 = old_size[i] + if v1 is None: + raise AssertionError("Expected v1 is not None") + if v2 is None: + raise AssertionError("Expected v2 is not None") + diff = v1 - v2 + if ( + sizevars.optimization_hint( + diff, + fallback=0, + ) + != 0 + ): + raise AssertionError( + f"Broadcast failed in ExpandView({x.get_size()}, {new_size}) on dimension {i}" + ) + return new_size + + @classmethod + def create(cls, x: IRNode, new_size: Sequence[_IntLike]) -> BaseView: + new_size = cls._normalize_size(x, new_size) + + if is_storage_and_layout(x): + storage, old_layout = as_storage_and_layout(x) + skip = len(new_size) - len(old_layout.size) + if skip < 0: + raise AssertionError("Expected skip >= 0") + new_stride = [sympy.S.Zero] * skip + for stride, size in zip(old_layout.stride, old_layout.size): + new_stride.append( + stride + if not V.graph.sizevars.is_size_one_or_false(size) + else sympy.S.Zero + ) + new_layout = FixedLayout( + old_layout.device, + old_layout.dtype, + list(new_size), + new_stride, + old_layout.offset, + old_layout.is_pinned, + ) + return ReinterpretView(data=storage, layout=new_layout) + + return ExpandView(data=x, size=new_size) + + def get_size(self) -> Sequence[Expr]: + return self.size + + def make_reindexer( + self, + ) -> Callable[[Sequence[Expr]], Sequence[Expr]]: + target = self.get_size() + actual = self.data.get_size() + skip = len(target) - len(actual) + + def reindex( + index: Sequence[Expr], + ) -> Sequence[Expr]: + index = list(index[skip:]) + if len(index) != len(actual): + raise AssertionError("Expected len(index) == len(actual)") + for i in range(len(actual)): + if actual[i] == 1: + # zero out broadcast dimension + index[i] = sympy.S.Zero + return index + + return reindex + + +@ir_dataclass +class PermuteView(BaseView): + dims: list[Expr] + + @classmethod + def create(cls, x: IRNode, dims: Sequence[int]) -> BaseView: + dims = cls._map_neg_dims(dims) + if OrderedSet(dims) != OrderedSet(range(len(dims))): + raise AssertionError( + "Expected OrderedSet(dims) == OrderedSet(range(len(dims)))" + ) + + if is_storage_and_layout(x): + storage, old_layout = as_storage_and_layout(x) + new_layout = FixedLayout( + old_layout.device, + old_layout.dtype, + [old_layout.size[i] for i in dims], + [old_layout.stride[i] for i in dims], + old_layout.offset, + old_layout.is_pinned, + ) + return ReinterpretView(data=storage, layout=new_layout) + + return PermuteView(data=x, dims=dims) + + @classmethod + def _map_neg_dims(cls, dims: Sequence[int]) -> list[int]: + return [dim if dim >= 0 else len(dims) + dim for dim in dims] + + def get_size(self) -> Sequence[Expr]: + if OrderedSet(self._map_neg_dims(self.dims)) != OrderedSet( + range(len(self.dims)) + ): + raise AssertionError( + "Expected OrderedSet(self._map_neg_dims(self.dims)) == OrderedSet( range(len(self.dims)) )" + ) + size = self.data.get_size() + return [size[i] for i in self.dims] + + def get_stride(self) -> Sequence[Expr]: + if not ( + OrderedSet(self._map_neg_dims(self.dims)) + == OrderedSet(range(len(self.dims))) + ): + raise AssertionError("dims must be a permutation of range(len(dims))") + stride = self.data.get_stride() + return [stride[i] for i in self.dims] + + def make_reindexer( + self, + ) -> Callable[[Sequence[Expr]], Sequence[Expr]]: + inv = {j: i for i, j in enumerate(self.dims)} + inv = [inv[i] for i in range(len(self.dims))] + if OrderedSet(inv) != OrderedSet(range(len(self.dims))): + raise AssertionError( + "Expected OrderedSet(inv) == OrderedSet(range(len(self.dims)))" + ) + + def reindex( + index: Sequence[Expr], + ) -> Sequence[Expr]: + return [index[i] for i in inv] + + return reindex + + +@ir_dataclass +class SqueezeView(BaseView): + @classmethod + def create(cls, x: IRNode, *, dim: int | None = None) -> IRNode: + if is_storage_and_layout(x): + storage, old_layout = as_storage_and_layout(x) + new_size = [] + new_stride = [] + if dim is not None: + if not isinstance(dim, int): + raise AssertionError(type(dim)) + if not (0 <= dim and dim < len(old_layout.size)): + raise AssertionError( + "Expected 0 <= dim and dim < len(old_layout.size)" + ) + + for i, (size, stride) in enumerate(zip(old_layout.size, old_layout.stride)): + if dim is None: + # Only append if dim is not squeezed out + if not V.graph.sizevars.is_size_one_or_false(size): + new_size.append(size) + new_stride.append(stride) + else: + if i != dim: + new_size.append(size) + new_stride.append(stride) + else: + if size != 1: + raise AssertionError("expected squeezed size to be 1") + + new_layout = FixedLayout( + old_layout.device, + old_layout.dtype, + new_size, + new_stride, + old_layout.offset, + old_layout.is_pinned, + ) + return ReinterpretView(data=storage, layout=new_layout) + + if dim is None: + return View.create( + x, + [ + s + for s in x.get_size() + if not V.graph.sizevars.is_size_one_or_false(s) + ], + ) + else: + if x.get_size()[dim] != 1: + raise AssertionError("Expected x.get_size()[dim] == 1") + return View.create(x, [s for i, s in enumerate(x.get_size()) if i != dim]) + + @staticmethod + def squeezer( + size: Sequence[Expr], + ) -> tuple[list[int], Callable[[Sequence[Expr]], tuple[Expr, ...]]]: + new_size = [s for s in size if s != 1] + not_one = [i for i, s in enumerate(size) if s != 1] + length = len(size) + + def reindex(index: Sequence[Expr]) -> tuple[Expr, ...]: + if len(index) != len(not_one): + raise AssertionError(f"{index} {not_one}") + new_index: list[Expr] = [sympy.S.Zero] * length + for idx, s in zip(not_one, index): + new_index[idx] = s + return tuple(new_index) + + return new_size, reindex + + def __init__(self, data: Any) -> None: + raise AssertionError("use SqueezeView.create()") + + +@ir_dataclass +class GenericView(BaseView): + size: Sequence[Expr] + reindex: Callable[[Sequence[Expr]], Sequence[Expr]] + + def make_reindexer( + self, + ) -> Callable[[Sequence[Expr]], Sequence[Expr]]: + return self.reindex + + def reindex_str(self) -> str: + index_old = [ + sympy_index_symbol_with_prefix(SymT.INDEX, n) for n in range(len(self.size)) + ] + index_new = list(self.reindex(index_old)) + return f"lambda {', '.join(map(str, index_old))}: {index_new}" + + def __str__(self) -> str: + return self.str_helper( + [self.data, f"size={self.size}", f"reindex={self.reindex_str()}"] + ) + + __repr__ = __str__ + + @classmethod + def create( + cls, + x: IRNode, + new_size: Sequence[Expr], + reindex: Callable[[Sequence[Expr]], Sequence[Expr]], + ) -> BaseView: + return cls(data=x, size=list(new_size), reindex=reindex) + + def get_size(self) -> Sequence[Expr]: + return self.size + + +@ir_dataclass +class View(GenericView): + """ + This class handles tensor reshaping by computing appropriate index transformations + to map the new shape back to the original storage layout. + """ + + @staticmethod + def handle_negative_index(idx: Expr, size: Expr) -> Expr: + idx = sympy.expand(idx) + size = sympy.expand(size) + evaluate_expr = V.graph.sizevars.shape_env.evaluate_expr + if evaluate_expr(sympy.Lt(idx, 0)): + idx = idx + size + return idx + + @classmethod + @override + def create(cls, x: IRNode, new_size: Sequence[Expr]) -> IRNode: # type: ignore[override] + if not isinstance(new_size, Sequence): + raise AssertionError(type(new_size)) + old_size, new_size = cls.resolve_negative_size(x.get_size(), new_size) + + # Skip pointless views + if V.graph.sizevars.statically_known_list_equals(old_size, new_size): + return x + + unbacked_symbols_in_sizes = ( + len(free_unbacked_symbols(old_size)) > 0 + or len(free_unbacked_symbols(new_size)) > 0 + ) + is_contiguous = is_dense_contiguous_storage_and_layout(x) + + def create_reinterpret_view( + inp: IRNode, new_size: Sequence[Expr], new_stride: Sequence[Expr] + ) -> ReinterpretView: + inp = ExternKernel.require_exact_strides( + inp, FlexibleLayout.contiguous_strides(inp.get_size()) + ) + storage, old_layout = as_storage_and_layout(inp) + new_layout = FixedLayout( + old_layout.device, + old_layout.dtype, + new_size, + new_stride, + old_layout.offset, + old_layout.is_pinned, + ) + return ReinterpretView(data=storage, layout=new_layout) + + def handle_unbacked_or_dynamic_reshape( + x: IRNode, + ) -> IRNode: + """ + Handle the case where view is not possible with current strides. + Try dynamic_reshape_indexer first; if it fails with unbacked + symbols (guard_or_false can't resolve comparisons), fall back + to making the tensor contiguous. + """ + nonlocal old_size, new_size + try: + reindex = cls.dynamic_reshape_indexer(old_size, new_size) + return cls(data=x, size=list(new_size), reindex=reindex) + except GuardOnDataDependentSymNode: + # dynamic_reshape_indexer cannot handle unbacked SymInts + # because guard_or_false can't resolve size comparisons. + # https://github.com/pytorch/pytorch/issues/145561 + x = ExternKernel.require_contiguous(x) + return create_reinterpret_view( + x, new_size, FlexibleLayout.contiguous_strides(new_size) + ) + + if 0 in new_size: + + def fake_reindex(index: Any) -> tuple[int, ...]: + return tuple([0] * len(old_size)) + + return cls(data=x, size=list(new_size), reindex=fake_reindex) + + # TODO: a new class for FixedTransferLayout that output layout is constrained by input layout + elif is_contiguous: + # Input is contiguous, output can use contiguous strides + return create_reinterpret_view( + x, new_size, FlexibleLayout.contiguous_strides(new_size) + ) + + # Input is non-contiguous. Check if we can get storage/layout. + if not is_storage_and_layout(x): + # Can't get storage/layout (e.g., for Pointwise nodes) + return handle_unbacked_or_dynamic_reshape(x) + + # Try to compute valid output strides. + storage, old_layout = as_storage_and_layout(x, freeze=False) + + old_stride = old_layout.stride + + # Convert sympy exprs to SymInt for _compute_stride, then convert back + old_size_symint = V.graph.sizevars.to_symints_or_ints(old_size) + old_stride_symint = V.graph.sizevars.to_symints_or_ints(old_stride) + new_size_symint = V.graph.sizevars.to_symints_or_ints(new_size) + + from torch._subclasses.fake_impls import _compute_stride + + # Use size_oblivious=True for unbacked symbols to avoid DDE errors + new_stride_symint = _compute_stride( + old_size_symint, + old_stride_symint, + new_size_symint, + size_oblivious=unbacked_symbols_in_sizes, + ) + + if new_stride_symint is not None: + # Convert SymInt back to sympy expressions + new_stride = [ + s.node.expr if hasattr(s, "node") else sympy.Integer(s) + for s in new_stride_symint + ] + # View is possible with computed strides + new_layout = FixedLayout( + old_layout.device, + old_layout.dtype, + new_size, + new_stride, + old_layout.offset, + old_layout.is_pinned, + ) + return ReinterpretView(data=storage, layout=new_layout) + + # View not possible with current strides + return handle_unbacked_or_dynamic_reshape(x) + + @staticmethod + def resolve_negative_size( + old_size: Sequence[Expr], new_size: Sequence[Expr] + ) -> tuple[list[Expr], list[Expr]]: + new_size = [V.graph.sizevars.simplify(x) for x in new_size] + old_size = [V.graph.sizevars.simplify(x) for x in old_size] + + new_size = list(new_size) + for i in range(len(new_size)): + if new_size[i] == -1: + new_size[i] = sympy.S.One + new_size[i] = CleanDiv(sympy_product(old_size), sympy_product(new_size)) + break + + V.graph.sizevars.check_equals(sympy_product(old_size), sympy_product(new_size)) + return old_size, new_size + + @classmethod + def dynamic_reshape_indexer( + cls, + old_size: Sequence[_IntLike], + new_size: Sequence[_IntLike], + dense_dim: int | None = None, + ) -> Callable[[Sequence[_T]], Sequence[_V]]: + try: + reindex = cls._dynamic_reshape_indexer(old_size, new_size, dense_dim) + except (AssertionError, GuardOnDataDependentSymNode, IndexError): + # optimistic algorithm failed, lets do a fallback + flat = [sympy_product(old_size)] + reindex1 = cls._dynamic_reshape_indexer(old_size, flat) + reindex2 = cls._dynamic_reshape_indexer(flat, new_size) + reindex = fuse_reindexing(reindex1, reindex2) + return reindex + + @staticmethod + def _dynamic_reshape_indexer( + old_size: Sequence[Expr], + new_size: Sequence[Expr], + dense_dim: int | None = None, + ) -> Callable[[Sequence[Expr]], Sequence[Expr]]: + """ + Perform a reshape entirely by modifying indexing math + """ + guard_or_false = V.graph.sizevars.guard_or_false + + def compare_sizes(a: Expr, b: Expr) -> int: + """ + Compare two symbolic sizes, returning -1 if a < b, 0 if a == b, 1 if a > b. + + For unbacked symbols, guard_or_false returns False, so we fall back + to divisibility checks. + """ + if guard_or_false(sympy.Eq(a, b)): + return 0 + if guard_or_false(sympy.Lt(a, b)): + return -1 + if guard_or_false(sympy.Gt(a, b)): + return 1 + + # Divisibility fallback for unbacked symbols: + # e.g. comparing u0 vs u0*u1, statically_known_multiple_of(u0*u1, u0) + # returns True so we take the merge path (return -1). + # The merge reindex for old=[u0, u1] -> new=[u0*u1] is: + # for k in range(u0 * u1): + # i = k // u1 + # j = k % u1 + # z[k] = x[i, j] + 1 + # Two cases where this could seem wrong but is still safe: + # u1=1: the merge reindex is correct since the extra dim is + # size 1 (a no-op). e.g. k // 1 = k, k % 1 = 0. + # u0=0: loop is range(0), no kernel runs, result doesn't matter. + + if V.graph.sizevars.statically_known_multiple_of(b, a): + return -1 + if V.graph.sizevars.statically_known_multiple_of(a, b): + return 1 + + raise GuardOnDataDependentSymNode(sympy.Eq(a, b)) + + # TODO: These symbols may not escape, if they don't assert so and + # treat them as temporary + vars = [ + sympy_index_symbol_with_prefix(SymT.VIEW, i) for i in range(len(new_size)) + ] + + stack_new = list(zip(vars, new_size)) + stack_old = list(old_size) + + # process the dense dim first + reordering_dense_dim = ( + dense_dim is not None + and dense_dim != len(stack_old) - 1 + and len(new_size) == 1 + ) + if reordering_dense_dim: + if dense_dim is None: # mypy + raise AssertionError("Expected dense_dim is not None") + old_dim = stack_old.pop(dense_dim) + stack_old.append(old_dim) + + view_expr = [] + while stack_new and stack_old: + size_old = stack_old.pop() + var, size_new = stack_new.pop() + if size_old == 1: + view_expr.append(sympy.S.Zero) + stack_new.append((var, size_new)) # re-add + elif size_new == 1: + stack_old.append(size_old) # re-add + elif compare_sizes(size_new, size_old) == 0: + view_expr.append(var) + elif compare_sizes(size_new, size_old) < 0: + while compare_sizes(size_new, size_old) < 0: + var2, size_new2 = stack_new.pop() + var = var2 * size_new + var + size_new = size_new * size_new2 + view_expr.append(var) + V.graph.sizevars.check_equals(size_new, size_old) + elif compare_sizes(size_new, size_old) > 0: + divisor = sympy.S.One + modulus = size_old + view_expr.append(ModularIndexing(var, divisor, modulus)) + divisor = divisor * modulus + while compare_sizes(size_new, size_old) > 0: + modulus = stack_old.pop() + view_expr.append(ModularIndexing(var, divisor, modulus)) + divisor = divisor * modulus + size_old = size_old * modulus + V.graph.sizevars.check_equals(size_new, size_old) + else: + raise AssertionError + + while stack_old: + size_old = stack_old.pop() + V.graph.sizevars.check_equals(size_old, 1) + view_expr.append(sympy.S.Zero) + + while stack_new: + var, size_new = stack_new.pop() + V.graph.sizevars.check_equals(size_new, 1) + + if dense_dim is not None and len(new_size) == 1: + view_expr.reverse() + # Move the last expression (dense dim) to its original position + dense_expr = view_expr.pop() + view_expr.insert(dense_dim, dense_expr) + else: + view_expr.reverse() + + if len(view_expr) != len(old_size): + raise AssertionError("Expected len(view_expr) == len(old_size)") + + def reindex( + index: Sequence[Expr], + ) -> Sequence[Expr]: + if len(index) != len(vars): + raise AssertionError((len(index), len(vars))) + replacements = dict(zip(vars, index)) + return tuple(sympy_subs(x, replacements) for x in view_expr) + + return reindex + + +@ir_dataclass +class ReinterpretView(BaseView): + """Pretend our storage has a different layout""" + + layout: Layout + + def __post_init__(self) -> None: + super().__post_init__() + if isinstance(self.data, BaseView): + object.__setattr__(self, "data", self.data.unwrap_view()) + + def __str__(self) -> str: + return self.str_helper( + [ + self.data, + self.layout, + ] + ) + + __repr__ = __str__ + + def get_name(self) -> str: + return self.data.get_name() + + def get_device(self) -> torch.device | None: + return self.layout.device + + def get_origin_node(self) -> torch.fx.Node | None: + return None + + @property + def dtype(self) -> torch.dtype: + return self.layout.dtype + + def get_size(self) -> Sequence[Expr]: + return list(self.layout.size) + + def get_stride(self) -> Sequence[Expr]: + return list(self.layout.stride) + + def make_loader(self) -> Callable[[Sequence[Expr]], OpsValue]: + def loader(index: Sequence[Expr]) -> OpsValue: + indexer = self.layout.make_indexer() + tmp_loader = ops.load(self.get_name(), indexer(index)) + if self.layout.dtype != self.data.dtype: + return ops.to_dtype_bitcast(tmp_loader, self.dtype, self.data.dtype) + else: + return tmp_loader + + return loader + + def make_indexer(self) -> Callable[[Sequence[Expr]], Expr]: + return self.layout.make_indexer() + + def get_layout(self) -> Layout: + return self.layout + + def freeze_layout(self) -> None: + pass + + @cache_on_self_and_args("ReinterpretView") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return ( + get_free_symbols(self.layout.size, unbacked_only) + | get_free_symbols(self.layout.stride, unbacked_only) + | get_free_symbols(self.layout.offset, unbacked_only) + ) + + def codegen_reference(self, writer: IndentedBuffer | None = None) -> str: + # reinterpret_tensor is similar to as_strided except: + # - offset is added to the existing offset (rather than replacing it) + # - view tracking is disabled similar to unsafe_view + return V.graph.wrapper_code.codegen_reinterpret_view( + self.data, + self.layout.size, + self.layout.stride, + self.layout.offset, + writer.writeline if writer is not None else V.graph.wrapper_code.writeline, + dtype=self.layout.dtype, + ) + + def num_reads(self) -> int: + return 1 + + +@ir_dataclass +class DtypeView(BaseView): + """Pretend our storage has a different type""" + + target_dtype: torch.dtype + + @classmethod + def create(cls, x: IRNode, new_dtype: torch.dtype) -> BaseView: + if is_storage_and_layout(x): + storage, old_layout = as_storage_and_layout(x) + new_layout = FixedLayout( + old_layout.device, + new_dtype, + old_layout.size, + old_layout.stride, + old_layout.offset, + old_layout.is_pinned, + ) + return ReinterpretView(data=storage, layout=new_layout) + return DtypeView(data=x, target_dtype=new_dtype) + + def __str__(self) -> str: + return self.str_helper([self.data, self.target_dtype]) + + __repr__ = __str__ + + @property + def dtype(self) -> torch.dtype: + return self.target_dtype + + def get_size(self) -> Sequence[Expr]: + return self.data.get_size() + + def make_reindexer(self) -> Callable[[Sequence[Expr]], Sequence[Expr]]: + def reindex(index: Sequence[Expr]) -> Sequence[Expr]: + return index + + return reindex + + def make_loader(self) -> Callable[[Sequence[Expr]], OpsValue]: + inner = self.data.make_loader() + + def loader(idx: Sequence[Expr]) -> OpsValue: + return ops.to_dtype_bitcast(inner(idx), self.target_dtype, self.data.dtype) + + return loader + + +class SliceView(View): + """View that represents a slice along a single dimension. + + Corresponds to tensor[..., start:end:step, ...]. + """ + + @classmethod + def create_with_size( + cls, + x: IRNode, + dim: int, + start: Expr, + size: Expr, + step: Expr, + ) -> IRNode: + new_size = list(x.get_size()) + new_size[dim] = size + + def reindex( + index: Sequence[Expr], + ) -> Sequence[Expr]: + if len(index) != len(new_size): + raise AssertionError(f"wrong ndim {index} {new_size}") + index = list(index) + index[dim] = index[dim] * step + start + return index + + return cls(data=x, size=new_size, reindex=reindex) + + @classmethod + def normalize_start_end( + cls, x: IRNode, dim: int, start: int, end: int + ) -> tuple[int, int]: + """ + Normalize start and end such that both are in the range + [0, x.get_size()[dim]] and start <= end. + """ + sizevars = V.graph.sizevars + dim_size = x.get_size()[dim] + + if any(free_unbacked_symbols(x) for x in (start, end, dim_size)): + min_func = Min + max_func = Max + elif any( + # Only needed when backed_size_oblivious is on. + x.has(sympy.Min, sympy.Max, Min, Max) + for x in (start, end, dim_size) + if isinstance(x, Expr) + ): + min_func = Min + max_func = Max + else: + min_func = sizevars.evaluate_min + max_func = sizevars.evaluate_max + + def clamp(x: Expr, lower: int, upper: int) -> Expr: + clamped_lower = ( + x if sizevars.statically_known_geq(x, lower) else max_func(x, lower) + ) + clamped_full = ( + clamped_lower + if sizevars.statically_known_leq(clamped_lower, upper) + else min_func(clamped_lower, upper) + ) + return clamped_full + + def clamp_wrap( + val: int | None, lower: int, upper: int, default: Expr | int + ) -> Expr | int: + if val is None: + # TODO(rec): can this really happen? + return default + val = cls.handle_negative_index(val, dim_size) + return clamp(val, lower, upper) + + start = clamp_wrap(start, 0, dim_size, 0) + end = clamp_wrap(end, start, dim_size, dim_size) + return start, end + + @classmethod + def create( # type: ignore[override] + cls, + x: IRNode, + dim: int, + start: int, + end: int, + step: int = 1, + clamp: bool = True, + ) -> IRNode: + step = sympy.expand(step) + if not (isinstance(step, Expr) or step > 0): + raise AssertionError(step) + try: + if start == 0 and end >= 2**63 - 1 and step == 1: + return x + except TypeError: + pass + + new_size = list(x.get_size()) + + # NB: Ordinarily we default to clamping. + # We only don't clamp for split_with_sizes. For split_with_sizes, sizes should be already valid + # failing in this situation is ok, since invalid sizes could trigger silent errors. + if clamp: + start, end = cls.normalize_start_end(x, dim, start, end) + + new_size[dim] = FloorDiv(end - start + (step - 1), step) + + if is_storage_and_layout(x): + # Fast path + storage, old_layout = as_storage_and_layout(x) + new_stride = list(old_layout.stride) + new_stride[dim] = new_stride[dim] * step + new_layout = FixedLayout( + old_layout.device, + old_layout.dtype, + new_size, + new_stride, + old_layout.offset + old_layout.stride[dim] * start, + old_layout.is_pinned, + ) + return ReinterpretView(data=storage, layout=new_layout) + + # redirect to a generic view + return cls.create_with_size(x, dim, start, new_size[dim], step) + + +@ir_dataclass +class BaseConstant(IRNode): + dtype: torch.dtype + device: torch.device + + def get_size(self) -> Sequence[Expr]: + return () + + def get_device(self) -> torch.device | None: + return self.device + + def get_origin_node(self) -> torch.fx.Node | None: + return None + + def get_reads(self) -> OrderedSet[Dep]: + return OrderedSet() + + +@ir_dataclass +class Constant(BaseConstant): + value: Any + dtype: torch.dtype + device: torch.device + + def make_loader(self) -> Callable[[Sequence[Expr]], OpsValue]: + def loader(index: Sequence[Expr]) -> OpsValue: + return ops.constant(self.value, self.dtype) + + return loader + + def realize(self) -> str | None: + pass + + def constant_to_device(self, device: torch.device) -> IRNode: + return Constant(value=self.value, dtype=self.dtype, device=device) + + +@ir_dataclass +class IndexingConstant(BaseConstant): + index: Any + dtype: torch.dtype + device: torch.device + + def make_loader(self) -> Callable[[Sequence[Expr]], OpsValue]: + def loader(index: Sequence[Expr]) -> OpsValue: + return ops.index_expr(self.index, self.dtype) + + return loader + + def constant_to_device(self, device: torch.device) -> IRNode: + return IndexingConstant(index=self.index, dtype=self.dtype, device=device) + + +def is_contiguous_strides_for_shape( + stride: Sequence[_IntLike], shape: Sequence[_IntLike] +) -> bool: + expected_stride = 1 + expected_stride_max = 1 + for x, y in reversed(tuple(zip(shape, stride))): + if x == 1: + continue + + if not V.graph.sizevars.statically_known_equals( + y, expected_stride + ) and not V.graph.sizevars.statically_known_equals(y, expected_stride_max): + return False + + expected_stride_max *= Max(1, x) + expected_stride *= x + + return True + + +def get_align_for_dtype(dtype: torch.dtype) -> int: + return config.padding_alignment_bytes // dtype.itemsize + + +class OutputSpec: + """Abstract base for Layout, MultiOutputLayout, NoneLayout. + Represents the memory layout of the output of an Operation.""" + + def get_device(self) -> torch.device | None: + raise NotImplementedError(type(self).__name__) + + def storage_size(self) -> int: + raise NotImplementedError(type(self).__name__) + + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + raise NotImplementedError(type(self).__name__) + + +@ir_dataclass +class Layout(OutputSpec): + """ + Layout base class + + Carries tensor meta-information including offset and + whether it is pinned. + """ + + def __init__( + self, + device: torch.device, + dtype: torch.dtype, + size: Sequence[_IntLike], + stride: Sequence[Expr] | None = None, + offset: Expr = Integer(0), + is_pinned: bool = False, + ) -> None: + if stride is None: + stride = FlexibleLayout.contiguous_strides(size) + # pyrefly: ignore [read-only] + self.device = device + self.dtype = dtype + if len(size) != len(stride): + raise AssertionError(f"size={size}, stride={stride}") + if not all(isinstance(s, _IntLike) for s in size): + raise AssertionError("Expected all(isinstance(s, _IntLike) for s in size)") + self._size = size + self._stride = stride + self._offset = offset + self.is_pinned = is_pinned + # is_pinned implies cpu + if not ((not self.is_pinned) or (self.device.type == "cpu")): + raise AssertionError("Only CPU tensors can be pinned") + + @property + def size(self) -> Sequence[_IntLike]: + return self._size + + @size.setter + def size(self, value: Sequence[_IntLike]) -> None: + self._size = value + + @property + def stride(self) -> Sequence[Expr]: + return self._stride + + @stride.setter + def stride(self, value: Sequence[Expr]) -> None: + self._stride = value + + @property + def offset(self) -> Expr: + return self._offset + + @offset.setter + def offset(self, value: Expr) -> None: + self._offset = value + + def __str__(self) -> str: + offset = "" + if self.offset != 0: + offset = f", offset={self.offset}" + + device_index_str = "" if self.device.index is None else f":{self.device.index}" + is_pinned_str = "" + if self.is_pinned: + is_pinned_str = f", is_pinned={self.is_pinned}" + return ( + f"{type(self).__name__}('{self.device.type}{device_index_str}', {self.dtype}, " + f"size={self.size}, stride={self.stride}{offset}{is_pinned_str})" + ) + + __repr__ = __str__ + + def get_device(self) -> torch.device: + return self.device + + def get_example(self) -> torch.Tensor: + with V.fake_mode: + return torch.empty_strided( + convert_shape_to_symint(self.size), + convert_shape_to_symint(self.stride), + dtype=self.dtype, + device=self.device, + pin_memory=self.is_pinned, + ) + + def is_contiguous(self) -> bool: + return is_contiguous_strides_for_shape(self.stride, self.size) + + @staticmethod + def is_channels_last_contiguous( + shape: Sequence[_IntLike], strides: Sequence[_IntLike] + ) -> bool: + ndim = len(shape) + if ndim not in [4, 5] or shape[1] == 1: + return False + for left, right, size in zip( + # pyrefly: ignore [bad-specialization] + strides, + # pyrefly: ignore [bad-specialization] + make_channels_last_strides_for(shape), + shape, + ): + if size != 1 and left != right: + return False + return True + + def is_transposed(self) -> bool: + for left, right, size in zip( + self.stride, + reversed(FlexibleLayout.contiguous_strides(list(reversed(self.size)))), + self.size, + ): + if size != 1 and left != right: + return False + return True + + @staticmethod + def _stride_expr_ge_or_false(left: _IntLike, right: _IntLike) -> bool: + """ + Returns true if left is symbolically greater than or equal to right, + assuming both expressions are tensor strides. + """ + sizevars = V.graph.sizevars + if sizevars.guard_or_false(sympy.Eq(right, 0)): + return True + if sizevars.guard_or_false(sympy.Eq(left, 0)): + return False + # Prove unbacked divisibility structurally, and keep SymPy from + # introducing reciprocal powers into any backed-symbol guard. + return ( + sizevars.guard_or_false(sympy.Ge(left, right)) + or sizevars.statically_known_multiple_of(left, right) + or sizevars.guard_or_false(sympy.Eq(Mod(left, right), 0)) + ) + + def is_stride_ordered(self, order: Sequence[int]) -> bool: + if len(self.stride) != len(order): + raise AssertionError("Expected len(self.stride) == len(order)") + + # ignore dimensions of size 1, they don't affect layout + non_1_indices = [ + i + for i, dim in enumerate(self.size) + if not V.graph.sizevars.statically_known_equals(dim, 1) + ] + + stride = [self.stride[i] for i in non_1_indices] + order: Sequence[int] = [order[i] for i in non_1_indices] + + def sorted_indices(arr: Sequence[int]) -> Sequence[int]: + sorted_arr = sorted(arr) + return [sorted_arr.index(element) for element in arr] + + # since we may have removed dimensions, need to re-sort & re-index order + order = sorted_indices(order) + + # reorder the stride given order + stride_ordered = [-1] * len(order) + for i in range(len(order)): + stride_ordered[order[i]] = stride[i] + # check if it is in ascending order + for i in range(len(order) - 1): + left = stride_ordered[i] + right = stride_ordered[i + 1] + if V.graph.sizevars.guard_or_false(sympy.Eq(left, right)): + continue + if self._stride_expr_ge_or_false(left, right): + return False + if not self._stride_expr_ge_or_false(right, left): + return False + return True + + def is_channels_last_stride_ordered(self) -> bool: + # create channels_last order(NCHW, NCDHW, the C is the first order). + order = [0] + list(reversed(range(1, len(self.stride) - 1))) + order = [len(order)] + order + return self.is_stride_ordered(order) + + @staticmethod + def _pad_strides( + in_strides: Sequence[int], size: Sequence[Expr], dtype: torch.dtype + ) -> Sequence[int]: + """ + The padding does not change stride order but makes sure all strides larger + than the threshold are multiple of align. + """ + align = get_align_for_dtype(dtype) + if len(in_strides) == 0: + return in_strides + + if not config.pad_channels_last and Layout.is_channels_last_contiguous( + size, in_strides + ): + return in_strides + + current_fx_node = V.get_current_node() + if hasattr(current_fx_node, "meta") and current_fx_node.meta.get( + "dislike_padding", False + ): + return in_strides + + # Skip padding the strides for dynamic shapes based on config.pad_dynamic_shape + # Checking both shape and strides, as there are cases where only one is dynamic + is_dynamic = not all( + isinstance(s, (int, sympy.Integer)) + for s in itertools.chain(in_strides, size) + ) + if not config.pad_dynamic_shapes and is_dynamic: + return in_strides + + shape_env = V.graph._shape_env if hasattr(V.graph, "_shape_env") else None + + def contains_unbacked_symints(expr: Expr | int) -> bool: + if shape_env is None: + return False + if not isinstance(expr, Expr): + return False + return any(shape_env.is_unbacked_symint(s) for s in expr.free_symbols) + + # Skip padding the strides when it contains unbacked symints for now. + if shape_env and any(contains_unbacked_symints(s) for s in in_strides): + return in_strides + + stride_order = get_stride_order(in_strides, shape_env) + fill_order = stride_order2fill_order(stride_order) + + new_strides = [0 for _ in range(len(in_strides))] + # since we pad when the layout is flexible, we can decide the + # smallest stride to be 1. + new_strides[fill_order[0]] = 1 + + padded = False + for rank, idx in enumerate(fill_order[1:], start=1): + prev_idx = fill_order[rank - 1] + stride = new_strides[prev_idx] * size[prev_idx] + # Static stride and meets padding conditions OR + # Dynamic stride and config.pad_dynamic_shape=True + require_padding = ( + isinstance(stride, (int, sympy.Integer)) + and stride > config.padding_stride_threshold + and stride % align != 0 + ) or (isinstance(stride, Expr) and config.pad_dynamic_shapes) + new_strides[idx] = stride + if require_padding: + new_strides[idx] = ceildiv(stride, align) * align + padded = True + + if not padded: + # Consider a tensor with shape [256, 1, 5, 5] + # Avoid strides like [25, 5, 5, 1] being padded to equivalent strides + # [25, 25, 5, 1]. + return in_strides + + # pyrefly: ignore [bad-assignment] + metrics.num_comprehensive_padding += 1 + return new_strides + + def pad_strides(self) -> None: + if not isinstance(self, FlexibleLayout): + raise AssertionError(type(self)) + if self.stride is None: + raise AssertionError("Expected self.stride is not None") + self.stride = self._pad_strides(self.stride, self.size, self.dtype) + + def should_pad_strides(self) -> bool: + return config.comprehensive_padding and isinstance(self, FlexibleLayout) + + def as_fixed(self) -> FixedLayout: + if isinstance(self, FixedLayout): + return self + + if self.should_pad_strides(): + self.pad_strides() + return FixedLayout( + self.device, + self.dtype, + self.size, + self.stride, + self.offset, + self.is_pinned, + ) + + def make_indexer(self) -> Callable[[Sequence[Expr]], Expr]: + if not FlexibleLayout.allow_indexing: + raise AssertionError(f"convert {type(self).__name__} to FixedLayout first") + return self.as_fixed().make_indexer() + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, Layout) + and self.device == other.device + and self.dtype == other.dtype + and self.size == other.size + and self.stride == other.stride + and self.offset == other.offset + and self.is_pinned == other.is_pinned + ) + + def storage_size(self) -> Expr: + return compute_required_storage_length(self.size, self.stride, self.offset) # type: ignore[arg-type] + + @cache_on_self_and_args("Layout") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return ( + get_free_symbols(self.size, unbacked_only) + | get_free_symbols(self.stride, unbacked_only) + | get_free_symbols(self.offset, unbacked_only) + ) + + +class FixedLayout(Layout): + """A Tensor layout we cannot change""" + + def make_indexer(self) -> Callable[[Sequence[Expr]], Expr]: + """A closure containing math to read a given element""" + return _fixed_indexer(self.size, self.stride, self.offset) + + +class FlexibleLayout(Layout): + """ + A Tensor layout that we are allowed to change + + Assumption: layout change should NOT add or remove free symbols + """ + + allow_indexing = False + + def get_fixed_layout_without_freezing(self) -> FixedLayout: + """ + Compute what the strides would be if this layout were frozen, + without actually modifying the layout. This is used for speculative + stride computation during Triton template code generation. + """ + # Create a temporary copy and use as_fixed to keep freezing path in sync + return copy.deepcopy(self).as_fixed() + + # WARNING! This doesn't handle zero size tensors correctly + @staticmethod + def contiguous_strides(sizes: Sequence[int]) -> list[Expr]: + if len(sizes) == 0: + return [] + reversed_strides = [sympy.S.One] + for size in reversed(sizes[1:]): + reversed_strides.append(size * reversed_strides[-1]) + return list(reversed(reversed_strides)) + + @staticmethod + def fill_ordered(sizes: Sequence[int], order: Sequence[int]) -> list[Expr]: + """ + Create a stride based on the order the dimensions should be filled in. + + In this format, channels last would be: + [1, 3, 2, 0] + """ + if OrderedSet(range(len(sizes))) != OrderedSet(order): + raise AssertionError((sizes, order)) + next_stride = sympy.S.One + strides = [None] * len(order) + + for i in order: + strides[i] = next_stride + next_stride = next_stride * sizes[i] + return strides + + @staticmethod + def stride_ordered(sizes: Sequence[int], order: Sequence[int]) -> Sequence[Expr]: + """ + Create a stride based on the sorted order of a permuted range. + + In this format, channels last would be: + [3, 0, 2, 1] + """ + if OrderedSet(range(len(sizes))) != OrderedSet(order): + raise AssertionError( + "Expected OrderedSet(range(len(sizes))) == OrderedSet(order)" + ) + fill_order = stride_order2fill_order(order) + return FlexibleLayout.fill_ordered(sizes, fill_order) + + @staticmethod + def stride_ordered_for_memory_format( + sizes: Sequence[int], memory_format: torch.memory_format + ) -> Sequence[Expr]: + """ + Create a stride based on a memory format. + + Memory format is translasted into a stride order, + so channels_last is the same as: + FlexibleLayout.stride_ordered(sizes, [3, 0, 2, 1]) + + This interface does not support memory_format `torch.preserve_format` + which should be used to deduce a format from another source + """ + if memory_format == torch.channels_last: + return FlexibleLayout.stride_ordered(sizes, NHWC_STRIDE_ORDER) + elif memory_format == torch.channels_last_3d: + return FlexibleLayout.stride_ordered(sizes, NHWDC_STRIDE_ORDER) + elif memory_format == torch.contiguous_format: + return FlexibleLayout.contiguous_strides(sizes) + else: + log.debug( + "stride_ordered_for_memory_format, unsuppored memory_format: %s", + memory_format, + ) + raise NotImplementedError + + @staticmethod + def same_ordered( + sizes: Sequence[int], stride: Sequence[_IntLike] + ) -> Sequence[Expr]: + """ + Create a stride that has the same stride order as given stride + + For example, if given stride is [1000, 1, 100, 10], + the fill order should be [1, 3, 2, 0] + """ + if len(sizes) != len(stride): + raise AssertionError("Expected len(sizes) == len(stride)") + stride = V.graph.sizevars.guarding_hints_or_throw(stride) + fill_order = sorted(range(len(stride)), key=stride.__getitem__) + return FlexibleLayout.fill_ordered(sizes, fill_order) + + @property + def size(self) -> Sequence[Expr]: + return self._size + + @size.setter + def size(self, value: Sequence[Expr]) -> None: + self.assert_free_symbol_uses_unchanged("size", value) + self._size = value + + @property + def stride(self) -> Sequence[Expr]: + return self._stride + + @stride.setter + def stride(self, value: Sequence[Expr]) -> None: + self.assert_free_symbol_uses_unchanged("stride", value) + self._stride = value + + @property + def offset(self) -> Expr: + return self._offset + + @offset.setter + def offset(self, value: Expr) -> None: + self.assert_free_symbol_uses_unchanged("offset", value) + self._offset = value + + def as_stride_order( + self, order: Sequence[int], allow_padding: bool = False + ) -> FixedLayout: + new_stride = self.stride_ordered(self.size, order) + if self.should_pad_strides() and allow_padding: + new_stride = self._pad_strides(new_stride, self.size, self.dtype) + + return FixedLayout( + self.device, + self.dtype, + self.size, + new_stride, + self.offset, + self.is_pinned, + ) + + def as_exact_strides( + self, exact_strides: Sequence[_IntLike], allow_padding: bool = False + ) -> FixedLayout: + new_stride = exact_strides + if self.should_pad_strides() and allow_padding: + new_stride = self._pad_strides(new_stride, self.size, self.dtype) + + return FixedLayout( + self.device, + self.dtype, + self.size, + new_stride, + self.offset, + self.is_pinned, + ) + + def as_fill_order(self, order: Sequence[int]) -> FixedLayout: + new_stride: Sequence[int] = self.fill_ordered(self.size, order) + if self.should_pad_strides(): + new_stride = self._pad_strides(new_stride, self.size, self.dtype) + return FixedLayout( + self.device, + self.dtype, + self.size, + new_stride, + self.offset, + self.is_pinned, + ) + + def as_same_order(self, stride: Sequence[_IntLike]) -> FixedLayout: + new_stride = self.same_ordered(self.size, stride) + if self.should_pad_strides(): + new_stride = self._pad_strides(new_stride, self.size, self.dtype) + return FixedLayout( + self.device, + self.dtype, + self.size, + new_stride, + self.offset, + self.is_pinned, + ) + + def get_initial_free_symbol_uses(self) -> dict[tuple[str, bool], sympy.Symbol]: + initial_free_symbols = {} + for name in ["size", "stride", "offset"]: + for unbacked_only in [True, False]: + key = (name, unbacked_only) + initial_free_symbols[key] = OrderedSet( + get_free_symbols(getattr(self, name), unbacked_only) + ) + + return initial_free_symbols + + def assert_free_symbol_uses_unchanged(self, name: str, value: IterateExprs) -> None: + for unbacked_only in [True, False]: + old_free_symbols = self.initial_free_symbols[(name, unbacked_only)] + new_free_symbols = OrderedSet(get_free_symbols(value, unbacked_only)) + if new_free_symbols != old_free_symbols: + raise AssertionError( + f"Expected free symbols unchanged, but got {new_free_symbols} vs {old_free_symbols}" + ) + + def __init__( + self, + device: torch.device, + dtype: torch.dtype, + size: Sequence[Expr], + stride_order: Sequence[int | Integer] | None = None, + is_pinned: bool = False, + ) -> None: + if stride_order: + strides = FlexibleLayout.fill_ordered(size, stride_order) + else: + strides = FlexibleLayout.contiguous_strides(size) + super().__init__(device, dtype, size, strides, is_pinned=is_pinned) + + # record the initial free symbols to check that we do not add new free symbols + # later when modifying sizes, strides, and offsets. + self.initial_free_symbols = self.get_initial_free_symbol_uses() + + +class NonOwningLayout(Layout): + """Is a view into the storage of another tensor""" + + def __init__(self, view: BaseView | TensorBox) -> None: + layout = view.get_layout() + super().__init__( + layout.device, + layout.dtype, + layout.size, + layout.stride, + ) + self.view = view + + def make_indexer(self) -> Callable[[Sequence[Expr]], Expr]: + return self.as_fixed().make_indexer() + + def maybe_guard_aligned(self) -> bool: + offset = self.view.get_layout().offset + if offset == 0: + return True + from .utils import ALIGNMENT + + return V.graph.sizevars.statically_known_multiple_of(offset, ALIGNMENT) + + @cache_on_self_and_args("NonOwningLayout") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + if not isinstance(self.view, ReinterpretView): + raise AssertionError("Expected isinstance(self.view, ReinterpretView)") + box = self.view.data + if not isinstance(box, StorageBox): + raise AssertionError(type(box)) + input_buffer = box.data + if not isinstance(input_buffer, Buffer): + raise AssertionError(type(box)) + return input_buffer.layout.get_free_symbol_uses(unbacked_only) + + +class CommBufferType(Enum): + SYMM_MEM = "symm_mem" + + +class CommBufferLayout(FixedLayout): + """ + A layout that signifies the buffer is a comm buffer. + In terms of striding, the layout is identical to `FixedLayout`. + + Buffers with this layout do not participate in in-place reuse - it can be + neither the source nor the target for in-place reuse. + + For detailed motivation and usage of this layout, see + NOTE [lowering-time collective optimization]. + """ + + comm_buffer_type: CommBufferType + group_name: str + + def __init__( + self, + layout: FlexibleLayout | FixedLayout, + comm_buffer_type: CommBufferType, + group_name: str, + ): + fixed = layout.as_fixed() if isinstance(layout, FlexibleLayout) else layout + super().__init__( + device=fixed.device, + dtype=fixed.dtype, + size=fixed.size, + stride=fixed.stride, + offset=fixed.offset, + is_pinned=fixed.is_pinned, + ) + self.comm_buffer_type = comm_buffer_type + self.group_name = group_name + + +@ir_dataclass +class NoneLayout(OutputSpec): + # This is janky, I figured out what fields to populate by just running + # the model I was interested in and adding properties/methods as needed. + # This doesn't inherit from Layout because Layout assumes you have stuff + # like sizes, but I don't really have anything here. + # + # If you have an ir.Node with NoneLayout, you probably need to setup + # dependencies manually in scheduler + + device: torch.device | None + size: list[int] = dataclasses.field(default_factory=lambda: [0]) + stride: list[int] = dataclasses.field(default_factory=lambda: [0]) + + def storage_size(self) -> int: + return 0 + + def as_fixed(self) -> OutputSpec: + return self + + def get_device(self) -> torch.device | None: + return self.device + + +class MutationLayoutSHOULDREMOVE(Layout): + def __init__(self, target: IRNode) -> None: + super().__init__( + target.get_device_or_error(), + target.get_dtype(), + target.get_size(), + None, + ) + self.target = target + name = self.get_buffer().get_name() + V.graph.mark_buffer_mutated(name) + + @property + def stride(self) -> Sequence[Expr]: # type: ignore[override] + return self.real_layout().stride + + @stride.setter # type: ignore[override] + def stride(self, value: Never) -> None: + pass # ignore setting of stride + + def storage_size(self) -> Expr: + return self.real_layout().storage_size() + + def get_buffer(self) -> Buffer: + def unwrap_views(target: Any) -> Any: + if isinstance(target, MutationLayoutSHOULDREMOVE): + return unwrap_views(target.target) + if isinstance(target, BaseView): + return unwrap_views(target.unwrap_view()) + if isinstance(target, MutableBox): + return unwrap_views(target.data) + return target + + result = unwrap_views(self.target) + if not isinstance(result, Buffer): + raise AssertionError(type(result)) + return result + + def real_layout(self) -> Layout: + layout = self.get_buffer().layout + if not isinstance(layout, Layout): + raise AssertionError("Expected isinstance(layout, Layout)") + return layout + + @classmethod + def realize_into( + cls, src: IRNode, dst: IRNode, unsafe_alias: bool = False + ) -> IRNode: + dst.realize() + # NOTE: We must realize users of `dst` before we realize `src`, since + # realization order determines scheduling order. Otherwise, src's + # mutation would be scheduled before the existing users of dst! + V.graph.mark_buffer_mutated(dst.get_name()) + + if isinstance(src, TensorBox): + src = src.data + + # We copy the contents of src into dst. In most cases this should + # be fused into a single kernel by the scheduler. + # NOTE: We cannot change src's layout to mutate dst directly as this + # would alias src to dst, which is not correct as further mutations to + # dst would effect users of src. However if there are no more users of + # dst, we can alias src to dst. + src.realize_hint() + + if not unsafe_alias: + node = Pointwise.create( + device=src.get_device(), + dtype=src.get_dtype(), + inner_fn=src.make_loader(), + ranges=[ + V.graph.sizevars.check_equals_and_simplify(a, b) + for a, b in zip(src.get_size(), dst.get_size()) + ], + ) + if not isinstance(node, (BaseView, MutableBox)): + raise AssertionError( + "Expected isinstance(node, (BaseView, MutableBox))" + ) + src = node.data + + src.realize() + if not hasattr(src, "data"): + raise AssertionError(src) + if not isinstance(src.data.layout, FlexibleLayout): + raise AssertionError(type(src.data.layout)) + src.data.layout = MutationLayoutSHOULDREMOVE(dst) + return src.data + + def as_fixed(self) -> Self: # type: ignore[override] + return self + + def make_indexer(self) -> Callable[[Sequence[Expr]], Expr]: + return self.target.make_indexer() + + +@ir_dataclass(frozen=False) +class Buffer(IRNode, CodegenSymbol): + # Name is sometimes None; e.g., ForceInPlace, where there isn't + # a meaningful name + name: str | None + layout: OutputSpec + ordering_only: ClassVar[bool] = False + + # Multi-output buffers will define 'outputs: List[Buffer]'. Confusingly, + # MultiOutput does NOT define this! + + def __post_init__(self) -> None: + super().__post_init__() + self._post_init_setattr("origin_node", None) + + def make_indexer(self) -> Callable[[Sequence[Expr]], Expr]: + return self.get_layout().make_indexer() + + def get_name(self) -> str: + if not self.name: + raise AssertionError(self) + return self.name + + def get_buffer_name(self) -> str | None: + return self.name + + def get_example(self) -> torch.Tensor | torch.SymInt: + if isinstance(self.layout, Layout): + return self.layout.get_example() + raise NotImplementedError(type(self.layout).__name__) + + def get_device(self) -> torch.device | None: + return self.get_output_spec().get_device() + + def get_defining_op(self) -> Operation | None: + return None + + @property + def dtype(self) -> torch.dtype: + return self.get_layout().dtype + + def get_size(self) -> Sequence[Expr]: + return [*self.get_layout().size] + + def get_stride(self) -> list[Expr]: + return [*self.get_layout().stride] + + def get_offset(self) -> Expr: + return self.get_layout().offset + + def get_layout(self) -> Layout: + if isinstance(self.layout, Layout): + return self.layout + raise NotImplementedError(type(self.layout).__name__) + + def get_output_spec(self) -> OutputSpec: + return self.layout + + def get_storage_numel(self) -> int: + return self.get_numel() + + def get_is_pinned(self) -> bool: + return self.get_layout().is_pinned + + def freeze_layout(self) -> None: + if isinstance(self.layout, Layout) and not isinstance( + self.layout, NonOwningLayout + ): + self.layout = self.layout.as_fixed() + + def freeze_layout_with_stride_order( + self, order: Sequence[int], allow_padding: bool = False + ) -> None: + if not isinstance(self.layout, FlexibleLayout): + raise AssertionError(type(self.layout)) + self.layout = self.layout.as_stride_order(order, allow_padding=allow_padding) + + def freeze_layout_with_fill_order(self, order: Sequence[int]) -> None: + if not isinstance(self.layout, FlexibleLayout): + raise AssertionError(type(self.layout)) + self.layout = self.layout.as_fill_order(order) + + def freeze_layout_with_same_order(self, stride: Sequence[int]) -> None: + if not isinstance(self.layout, FlexibleLayout): + raise AssertionError(type(self.layout)) + self.layout = self.layout.as_same_order(stride) + + def freeze_layout_with_exact_strides( + self, exact_strides: Sequence[int], allow_padding: bool = False + ) -> None: + if not isinstance(self.layout, FlexibleLayout): + raise AssertionError(type(self.layout)) + self.layout = self.layout.as_exact_strides( + exact_strides, allow_padding=allow_padding + ) + + def is_zero_elements(self) -> bool: + return V.graph.sizevars.statically_known_true(sympy.Eq(self.get_numel(), 0)) + + def make_loader(self) -> Callable[[Sequence[Expr]], OpsValue]: + # Loading from a zero-element buffer is a no-op + if self.is_zero_elements(): + return partial(nop_loader_fn, dtype=self.get_dtype()) + + def loader(index: Sequence[Expr]) -> OpsValue: + indexer = self.make_indexer() + return ops.load(self.name or "unnamed", indexer(index)) + + return loader + + def codegen_reference(self, writer: IndentedBuffer | None = None) -> str: + return self.get_name() + + def decide_layout(self) -> None: + pass + + def get_inputs_that_alias_output(self) -> Sequence[str]: + if isinstance(self.layout, NonOwningLayout): + return [self.layout.view.get_name()] + return () + + def get_mutation_names(self) -> Sequence[str]: + if isinstance(self.layout, MutationLayoutSHOULDREMOVE): + return [self.layout.target.get_name()] + return () + + def get_read_names(self) -> OrderedSet[str]: + return OrderedSet([self.get_name()]) + + @cache_on_self_and_args("Buffer") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def realize(self) -> str | None: + pass + + def should_allocate(self) -> bool: + # Returns False by default. + return False + + +@ir_dataclass(frozen=False) +class OperationBuffer(Buffer, Operation): + # An operation that produces a single output buffer + def get_outputs(self) -> list[Buffer]: + return [self] + + def get_defining_op(self) -> Operation: + return self + + # Skip implementation in Buffer + get_operation_name = Operation.get_operation_name + + def __post_init__(self) -> None: + Buffer.__post_init__(self) + Operation.__post_init__(self) + + +class InputBuffer(Buffer): + def num_reads(self) -> int: + return 1 + + +class DonatedBuffer(InputBuffer): + """ + Represents a donated buffer which is a saved tensor that is not alias to any + fwd inputs, fwd user outputs, and bwd outputs. We generally cannot inplace + reuse the input tensor memory during backward since it might be used in another + function. However, donated buffer can be inplace reused during backward + to save memory. + """ + + +class ConstantBuffer(InputBuffer): + override_device: torch.device | None = None + + def make_loader(self) -> Callable[[Sequence[Expr]], OpsValue]: + def loader(index: Sequence[Expr]) -> OpsValue: + indexer = self.get_layout().make_indexer() + return ops.load( + V.graph.constant_name(self.get_name(), self.override_device), + indexer(index), + ) + + return loader + + def constant_to_device(self, device: torch.device) -> IRNode: + return ConstantBuffer( + name=V.graph.constant_name(self.get_name(), device), layout=self.layout + ) + + +@ir_dataclass +class NoneAsConstantBuffer(IRNode): + def get_reads(self) -> OrderedSet[Dep]: + return OrderedSet() + + @cache_on_self_and_args("NoneAsConstantBuffer") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def codegen_reference(self, writer: IndentedBuffer | None = None) -> str: + return V.graph.wrapper_code.none_str + + def get_output_spec(self) -> OutputSpec: + return NoneLayout(device=None) + + def has_tensor_output(self) -> bool: + return False + + +@ir_dataclass +class ShapeAsConstantBuffer(IRNode): + expr: Expr + + @cache_on_self_and_args("ShapeAsConstantBuffer") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return get_free_symbols(self.expr, unbacked_only) + + def codegen_reference(self, writer: IndentedBuffer | None = None) -> str: + return V.graph.wrapper_code.codegen_sizevar(self.expr) + + def has_tensor_output(self) -> bool: + return False + + +@dataclasses.dataclass(frozen=True) +class ExtraIndexingConstraints: + """Extra indexing constraints appended during simplify_and_reorder. + + Produced by the cpp fusion path to force compatible index/reduce ranges + across scheduler nodes, then threaded through simplify_and_reorder and + recompute_size_and_body. Replaces a bare tuple[VarRanges, list[Expr]]. + """ + + ranges: VarRanges + exprs: list[sympy.Expr] + + +@ir_dataclass(frozen=False) +class ComputedBuffer(OperationBuffer): + """ + Represents a buffer that is computed during kernel execution rather than being an input. + """ + + data: Loops + _force_realize: ClassVar[bool] = False + + # fields for split reduction + _split_size: int | None = None + _original_inner_fn: Callable[..., Any] | None = None + _original_ranges: Sequence[_IntLike] | None = None + _original_reduction_ranges: Sequence[_IntLike] | None = None + + @contextlib.contextmanager + def with_original_inner_fn(self) -> Iterator[None]: + if self._split_size is None: + raise AssertionError("Expected self._split_size is not None") + if self._original_inner_fn is None: + raise AssertionError("Expected self._original_inner_fn is not None") + if self._original_ranges is None: + raise AssertionError("Expected self._original_ranges is not None") + if self._original_reduction_ranges is None: + raise AssertionError("Expected self._original_reduction_ranges is not None") + + if not isinstance(self.data, Reduction): + raise AssertionError(f"{type(self.data)}") + old_data = self.data + old_layout = self.layout + try: + new_data = Reduction( + device=old_data.device, + dtype=old_data.dtype, + inner_fn=self._original_inner_fn, + ranges=self._original_ranges, + reduction_ranges=self._original_reduction_ranges, + reduction_type=old_data.reduction_type, + src_dtype=old_data.src_dtype, + reduction_hint=old_data.reduction_hint, + strict_sum_multirow=old_data.strict_sum_multirow, + strict_sum_rblock=old_data.strict_sum_rblock, + ) + self.data = new_data + # this layout does not matter since we skip tl.store + # later + self.layout = FixedLayout( + old_data.device, + old_data.dtype, + self._original_ranges, + ) + self.get_default_sizes_body.clear_cache(self) + yield + finally: + self.data = old_data + self.layout = old_layout + + @staticmethod + @contextlib.contextmanager + def force_realize() -> Iterator[None]: + old_value = ComputedBuffer._force_realize + try: + ComputedBuffer._force_realize = True + yield + finally: + ComputedBuffer._force_realize = old_value + + def get_computed_buffer_name(self) -> str | None: + """ + Returns self.name if it exists, otherwise returns the name of the data node if that exists. + If neither exist, returns None. + """ + if self.name is not None: + return self.name + if hasattr(self.data, "name"): + return self.data.name + return None + + def num_reads(self) -> int: + return self.data.num_reads() + + def get_reads(self) -> OrderedSet[Dep]: + return self.data.get_reads() + + def get_read_names(self) -> OrderedSet[str]: + return self.data.get_read_names() + + def get_read_writes(self) -> dependencies.ReadWrites: + if not isinstance(self.data, (Reduction, Scan, Sort, Pointwise)): + return dependencies.ReadWrites( + reads=OrderedSet(), + writes=OrderedSet(), + index_exprs=OrderedSet(), + ) + + with patch.object(FlexibleLayout, "allow_indexing", True): + if self.data.get_reduction_type(): + return extract_read_writes( + self.get_store_function(), + self.data.get_pointwise_size(), + self.data.get_reduction_size(), + ) + else: + return extract_read_writes( + self.get_store_function(), + self.data.get_size(), + ) + + @cache_on_self_and_args("ComputedBuffer") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + # Ordinarily, we'd like to just peek at the arguments list, + # but ComputedBuffers have no argument list. + # + # Morally, this logic needs to be synchronized with the + # KernelArgs.size calls, which are responsible for making symbols make + # there way as kernel arguments (and it is precisely passing in one of + # those symbols that establishes a dependency). However, we haven't + # started codegen yet so we can't directly reuse that logic. + # + # One thing you might wonder is if this is enough for a ComputedBuffer + # denoting a reduction over i0. Empirically, it is enough, but for an + # unusual reason: we only need accurate dependencies for item() call, + # but it's impossible to end up with a reduction over i0 from an + # item() call without a regular non-reduction buffer first. + result = self.layout.get_free_symbol_uses( + unbacked_only + ) | self.data.get_free_symbol_uses(unbacked_only) + + if self.has_store_function(): + result |= self.get_read_writes().get_free_symbol_uses(unbacked_only) + return result + + def make_loader(self) -> Callable[[Sequence[Expr]], OpsValue]: + if ( + not self.get_reduction_type() + and self.name not in V.graph.mutated_buffers + and self.num_reads() == 0 + and not self._force_realize + ): + # inline this op rather than generating ops.load() + return self.data.make_loader() + return super().make_loader() + + def has_store_function(self) -> bool: + return isinstance(self.data, (Reduction, Scan, Sort, Pointwise)) + + def get_store_function(self) -> Callable[..., None]: + indexer = self.get_layout().as_fixed().make_indexer() + if isinstance(self.data, (Reduction, Scan, Sort)): + return partial(self.data.store_reduction, self.name, indexer) + else: + if not isinstance(self.data, Pointwise): + raise AssertionError(type(self.data)) + return partial(self.data.store_output, self.name, indexer) + + def get_fill_order(self) -> list[int] | None: + """ + If our layout is still flexible, try to determine the stride order based on stride orders of reads. + + TODO(jansel): A better algorithm here would look at downstream consumers of this + value and try to do global graph-level layout optimization. + This is also something just begging to be autotuned. + """ + if isinstance(self.layout, FlexibleLayout): + (index_vars, reduction_vars), _ = dependencies.index_vars_squeeze( + self.data.get_pointwise_size(), self.data.get_reduction_size() + ) + reads = self.get_read_writes().reads + # only consider reads to buffer of same size + # ignore StarDeps because they don't contribute stride information + if not all( + isinstance(r, (dependencies.StarDep, dependencies.MemoryDep)) + for r in reads + ): + raise AssertionError( + "Expected all( isinstance(r, (dependencies.StarDep, dependencies.MemoryDep)) for r in reads )" + ) + reads = [ + sympy_subs(r.index, {v: sympy.S.Zero for v in reduction_vars if v != 0}) + for r in reads + if isinstance(r, dependencies.MemoryDep) + ] + + if reads: + if isinstance(self.data, (Scan, Sort)): + indices = self.data.reindex(index_vars, reduction_vars) + else: + indices = index_vars + stride_lengths = [ + V.graph.sizevars.stride_hints(expr, indices) for expr in reads + ] + from .scheduler import pick_loop_order + + return pick_loop_order(stride_lengths, self.get_size()) + + return None + + def decide_layout(self) -> None: + if isinstance(self.layout, FlexibleLayout): + order = self.get_fill_order() + if order: + self.freeze_layout_with_fill_order(order) + else: + self.freeze_layout() + + @cache_on_self + def get_default_sizes_body( + self, + ) -> tuple[ + tuple[list[Expr], list[Expr]], + LoopBody, + tuple[list[Expr], list[Expr]], + ]: + args, var_ranges = dependencies.index_vars_squeeze( + self.get_pointwise_size(), self.get_reduction_size(), prefix="q" + ) + with patch.object(ConstantBuffer, "override_device", self.get_device()): + body = LoopBody( + self.get_store_function(), + (args if self.get_reduction_type() else args[:1]), + var_ranges, + *args, + ) + index_vars = [] + reduce_vars: list[Any] = [] + index_size = [] + reduce_size = [] + for v, s in var_ranges.items(): + if v in args[0]: + if reduce_vars: + raise AssertionError("Expected not reduce_vars") + index_vars.append(v) + index_size.append(s) + else: + if v not in args[1]: + raise AssertionError("Expected v in args[1]") + reduce_vars.append(v) + reduce_size.append(s) + return (index_size, reduce_size), body, (index_vars, reduce_vars) + + def simplify_and_reorder( + self, + extra_indexing_constraints: ExtraIndexingConstraints | None = None, + recompute_sizes_body_func: Callable[..., Any] | None = None, + ) -> tuple[tuple[list[Expr], list[Expr]], LoopBody | None]: + """ + This is a main place where we do loop transformations in a + backend-agnostic way. + + Here we: + 1) Remove any 1 dimensions + 2) Fuse contiguous dimensions together + 3) Reorder dimensions based on stride orders + + Optional argument extra_indexing_constraints can be used to append additional + indexing expressions to existing ones derived from buffer's body. This can be useful + to fuse scheduler nodes with compatible ranges, e.g. (s0*s1*...,) and (s0, s1, s2, ...) + on CPU by preventing indexing simplifications and obtaining index/reduce ranges for + the scheduler node compatible with other nodes. + Optional argument recompute_sizes_body_func can be used to recompute sizes and body + on the default body. This can be useful to append additional loop transformations. + """ + ( + (index_size, reduce_size), + body, + (index_vars, reduce_vars), + ) = self.get_default_sizes_body() + + if recompute_sizes_body_func: + ( + (index_size, reduce_size), + body, + (index_vars, reduce_vars), + ) = recompute_sizes_body_func( + (index_size, reduce_size), body, (index_vars, reduce_vars) + ) + + index_formulas = [*body.indexing_exprs.values()] + if extra_indexing_constraints is not None: + expected_var_ranges = body.var_ranges + if expected_var_ranges != extra_indexing_constraints.ranges: + raise AssertionError( + ( + expected_var_ranges, + extra_indexing_constraints.ranges, + ) + ) + # remove already existing expressions + extra_indexing_expr = [ + e for e in extra_indexing_constraints.exprs if e not in index_formulas + ] + index_formulas += extra_indexing_expr + + memory_addrs = [*body.get_write_exprs()] + if not V.graph.has_feature(self, BackendFeature.PREFER_STORE_LOOP_ORDER): + memory_addrs.extend(body.get_read_exprs()) + + def simplify_and_reorder( + x_vars: Sequence[sympy.Symbol], + support_vars: Sequence[sympy.Symbol], + sizes: Sequence[int], + simplify_loops: bool, + ) -> tuple[ + list[int], + Callable[[Sequence[int]], Sequence[int]], + Callable[[Sequence[int]], Sequence[int]], + ]: + newsizes, reindex0, reindex1 = self._apply_loop_reordering( + x_vars, support_vars, sizes, memory_addrs + ) + + # When using native matmul, the codegen assumes the following loop order, + # regardless of the stride of A and B: + # + # for z -> y -> x -> r: C[z, y, x] += A[z, y, r] * B[z, r, x] + # or + # for z -> x -> y -> r: C[z, y, x] += A[z, y, r] * B[z, r, x] + # + # The critical point is the position of the "z" (batch) axis in bmm. + # It is fine to swap the y and x axes (e.g., (z, y, x, r) or (z, x, y, r)), + # but reordering the z axis (e.g., (y, x, z, r)) breaks codegen. + # + # Therefore, if loop reordering changes the "z" location in bmm, + # it should be reverted to the default. + # This may not always produce the optimal loop order when strides + # do not align with the default assumption. + # + # TODO: Consider extending tl.dot codegen to support arbitrary loop orders. + if self.get_reduction_type() == "dot" and len(sizes) == 3: + order = list(range(len(sizes))) # default order + + # if z axis is not the outermost, use the default reorder. + if reindex0(order)[0] != 0: + newsizes = [sizes[i] for i in order] + reindex0 = same_reorder(order) + reindex1 = inverse_reorder(order) + + # for NHWC: reindex0([0,1,2,3]) = [0,2,3,1], reindex1([0,1,2,3]) = [0,3,2,1] + x_vars = reindex0(x_vars) + + if simplify_loops: + newsizes, reindex2, _prune = V.graph.sizevars._simplify_loops( + x_vars, + newsizes, + index_prevent_reordering(index_formulas, x_vars, newsizes), + ) + reindex = fuse_reindexing(reindex1, reindex2) + else: + reindex = reindex1 + return newsizes, reindex, reindex1 + + support_vars = index_vars + reduce_vars + should_merge_loops = ( + not is_gpu(get_device_type(self)) or not config.loop_ordering_after_fusion + ) + iter_ranges, iter_reindex, _ = simplify_and_reorder( + index_vars, + support_vars, + index_size, + should_merge_loops, + ) + + # Like iteration dimensions, we may also want to delay merging reduction dimensions. + # E.g., if we reduce a tensor [M, N, K] for its M and N dimensions followed by a pointwise + # kernel, merging M and N dimension too early makes it hard to decide what loop order + # we should pick for the piontwise kernel so that it is fusible with the reduction. + reduce_ranges, reduce_reindex, _ = simplify_and_reorder( + reduce_vars, support_vars, reduce_size, should_merge_loops + ) + + # retrace the loop body with simplification and reordering applied + (iter_vars, reduce_vars), var_ranges = dependencies.index_vars_no_squeeze( + iter_ranges, + reduce_ranges, + prefix="p", + ) + body = LoopBody( + body, + [iter_reindex(iter_vars), reduce_reindex(reduce_vars)], + var_ranges, + iter_vars, + reduce_vars, + ) + return (iter_ranges, reduce_ranges), body + + @staticmethod + def _apply_loop_reordering( + index_vars: Sequence[sympy.Symbol], + support_vars: Sequence[sympy.Symbol], + sizes: Sequence[int], + memory_addrs: list[Expr], + priority_idx: list[int] | None = None, + ) -> tuple[ + list[int], + Callable[[Sequence[int]], Sequence[int]], + Callable[[Sequence[int]], Sequence[int]], + ]: + """ + Shuffle the order of loops around to hopefully improve performance. + """ + from .scheduler import pick_loop_order + + if priority_idx is None: + priority_idx = [] + + try: + strides = [ + V.graph.sizevars.stride_hints(expr, index_vars, support_vars) + for expr in memory_addrs + ] + if not ( + len(strides) == len(memory_addrs) and len(strides[0]) == len(index_vars) + ): + raise AssertionError( + "Expected len(strides) == len(memory_addrs) and len(strides[0]) == len( index_vars )" + ) + order = list(reversed(pick_loop_order(strides, sizes, priority_idx))) + except Exception: + if config.debug: + log.warning( + "Did not simplify complex index:\n%s\n%s", + dict(zip(index_vars, sizes)), + memory_addrs, + ) + order = list(range(len(sizes))) + sizes = [sizes[i] for i in order] + return sizes, same_reorder(order), inverse_reorder(order) + + def get_pointwise_size(self) -> Sequence[Expr]: + return self.data.get_pointwise_size() + + def get_reduction_size(self) -> Sequence[Expr]: + return self.data.get_reduction_size() + + def get_reduction_type(self) -> str | None: + return self.data.get_reduction_type() + + def is_no_op(self) -> bool: + return self.data.is_zero_elements() + + def should_allocate(self) -> bool: + return True + + def constant_to_device(self, device: torch.device) -> IRNode: + """Move this to a given device. Requires that all reads are to constants.""" + return self.data.constant_to_device(device) + + +@dataclasses.dataclass(frozen=True) +class FinalizeCodegenResult: + """Structured result from TemplateBuffer._finalize_codegen for external backends.""" + + source: str + imports: list[str] + call_preamble: list[str] + call_args: list[str] + + +class _HasAliasingOrMutation(Protocol): + """Minimal view of scheduler.BaseSchedulerNode used by prologue fusion. + + ir.py cannot import scheduler (circular), so this documents the single + method consumed by has_aliasing_or_mutation_for_prologue_fusion instead + of typing the argument as Any. + """ + + def has_aliasing_or_mutation(self) -> bool: ... + + +class TemplateBuffer(OperationBuffer): + """ + Base class for template operators that support epilogue and prologue fusion. + Subclasses: TritonTemplateBuffer (built-in Triton templates), + HelionTemplateBuffer (Helion kernels), etc. + """ + + def __init__( + self, + layout: OutputSpec, + inputs: Sequence[IRNode], + make_kernel_render: Callable[..., Any] | None, + mutated_inputs: Iterable[IRNode] | None = None, + allowed_prologue_inps: OrderedSet[str] | None = None, + named_inputs: dict[str, IRNode] | None = None, + ) -> None: + super().__init__(name=None, layout=layout) + self.inputs = InputsKernel.unwrap_storage(inputs) + self.make_kernel_render = make_kernel_render + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + # Annotations dict for storing metadata (e.g., KernelTemplateChoice) + self.annotations: dict[str, object] = {} + + # Output buffer names eligible for epilogue fusion. + # Maps buffer name → kernel parameter name (e.g. "buf3" → "result"). + self.epilogue_fusable_outputs: dict[str, str] = {} + # For multi-output kernels: maps child buffer name → MultiOutput + # node. Used by call_kernel to emit tuple-unpacking lines. + self._multi_output_children: dict[str, MultiOutput] = {} + # Maps kernel parameter name → IRNode for each tensor input. + # Used by ExternalTritonTemplateKernel to set up prologue fusion and + # by HelionTemplateBuffer to resolve call arguments. + self._named_inputs: dict[str, IRNode] = ( + dict(named_inputs) if named_inputs else {} + ) + + # Inputs that the kernel mutates in-place + self.mutated_inputs = mutated_inputs + self.mutation_outputs: list[MutationOutput] = [] + if mutated_inputs is not None: + first_input = self.inputs[0] + if not isinstance(first_input, IRNode): + raise AssertionError(type(first_input)) + device = first_input.get_device() + self.mutation_outputs = [ + MutationOutput(NoneLayout(device=device), buf, self) + for buf in mutated_inputs + ] + # Input buffer names eligible for prologue fusion. + self.allowed_prologue_inps: OrderedSet[str] = ( + allowed_prologue_inps or OrderedSet() + ) + # Per-template fusion overrides. None means fall back to global + # config.epilogue_fusion / config.prologue_fusion. + self.allow_epilogue_fusion: bool | None = None + self.allow_prologue_fusion: bool | None = None + + @property + def dtype(self) -> torch.dtype: + if isinstance(self.layout, MultiOutputLayout): + raise NotImplementedError( + "Multi-output templates do not have a single dtype" + ) + return self.get_layout().dtype + + def get_read_writes(self) -> dependencies.ReadWrites: + return self.extract_read_writes(normalize=True) + + def _read_deps_from_inputs(self, normalize: bool) -> OrderedSet[dependencies.Dep]: + """Build read dependencies from all inputs.""" + reads: OrderedSet[dependencies.Dep] = OrderedSet() + for inp_raw in self.inputs: + if not isinstance(inp_raw, (ReinterpretView, Buffer)): + raise AssertionError(type(inp_raw)) + inp: ReinterpretView | Buffer = inp_raw + if not isinstance(inp.layout, Layout): + raise AssertionError(type(inp.layout)) + inp_indexer = inp.layout.make_indexer() + + def dummy(index: Sequence[Any], rindex: Sequence[Any]) -> Any: + if len(rindex) != 0: + raise AssertionError("Expected len(rindex) == 0") + return ops.load(inp.get_name(), inp_indexer(index)) + + reads |= dependencies.extract_read_writes( + dummy, inp.get_size(), (), normalize=normalize + ).reads + return reads + + def extract_read_writes(self, normalize: bool = False) -> dependencies.ReadWrites: + """Extract read/write dependencies for this TemplateBuffer. + + When the layout is MultiOutputLayout (multi-output templates), the + buffer itself has no data layout, so we cannot build an indexer. + Instead, synthesize a trivial write dep and derive read deps from + the named tensor inputs (``_named_inputs``). For single-output + templates with a concrete layout, fall through to the standard path. + """ + if isinstance(self.layout, MultiOutputLayout): + writes: OrderedSet[dependencies.Dep] = OrderedSet( + [ + dependencies.MemoryDep( + self.get_name(), sympy.Integer(0), var_names=(), size=() + ), + ] + ) + return dependencies.ReadWrites( + reads=self._read_deps_from_inputs(normalize), + writes=writes, + index_exprs=OrderedSet(), + range_vars=None, + var_ranges=None, + ) + + name = self.get_name() + indexer = self.get_layout().make_indexer() + + def dummy(index: Sequence[Any], rindex: Sequence[Any]) -> Any: + if len(rindex) != 0: + raise AssertionError("Expected len(rindex) == 0") + return ops.store(name, indexer(index), "fake") + + deps = dependencies.extract_read_writes( + dummy, self.get_size(), (), normalize=normalize + ) + deps.reads |= self._read_deps_from_inputs(normalize) + return deps + + def get_reduction_size(self) -> Sequence[Expr]: + return sympy.S.One + + def get_reduction_type(self) -> str | None: + return None + + def should_allocate(self) -> bool: + return True + + def simplify_and_reorder( + self, + extra_indexing_constraints: ExtraIndexingConstraints | None = None, + recompute_sizes_body_func: Callable[..., Any] | None = None, + ) -> tuple[tuple[Sequence[Expr], list[Expr]], LoopBody | None]: + return ( + ( + self.get_size(), + [], + ), + None, + ) + + def is_multi_outputs_template(self) -> bool: + """Whether this template produces multiple outputs via MultiOutputLayout.""" + return isinstance(self.layout, MultiOutputLayout) + + def get_allowed_prologue_inps(self) -> OrderedSet[str]: + return self.allowed_prologue_inps + + def has_aliasing_or_mutation_for_prologue_fusion( + self, scheduler_node: _HasAliasingOrMutation + ) -> bool: + """Return whether this template's aliasing/mutation blocks prologue fusion. + + The default preserves the scheduler's conservative behavior. External + template subclasses may override this when they can prove a prologue + producer only feeds independent, non-mutated template inputs. + """ + return scheduler_node.has_aliasing_or_mutation() + + def _finalize_codegen( + self, hook_outputs: dict[str, str] + ) -> FinalizeCodegenResult | None: + """Called after epilogue/prologue subgraph codegen with rendered hook outputs. + + ``hook_outputs`` maps placeholder keys (e.g. ````, + ````) to the Triton code generated by Inductor for + each fused subgraph. + + Return a ``FinalizeCodegenResult`` to provide custom source code and + call metadata, or ``None`` to use the default codegen path. + """ + return None + + @classmethod + def realize_template_input(cls, tb: TensorBox) -> IRNode: + """Realize a TensorBox, preserving MultiOutput layout (unlike ExternKernel.realize_input).""" + if isinstance(tb, TensorBox) and isinstance(tb.data, MultiOutput): + return tb.data + result = ExternKernel.realize_input(tb) + if isinstance(result, StorageBox): + result = result.data + if isinstance(result.layout, FlexibleLayout): # type: ignore[union-attr] + result.freeze_layout() + return result + + @classmethod + def build_multi_outputs( + cls, + template_buf: TemplateBuffer, + structured: object, + *, + direct_alias_at_leaf: dict[int, IRNode] | None = None, + on_tensor_leaf: Callable[[str, MultiOutput, list[tuple[type, int]], int], None] + | None = None, + on_non_tensor_leaf: Callable[[int], None] | None = None, + ) -> tuple[TensorBox, ...]: + """Walk a structured output tree, creating MultiOutput nodes for tensor leaves.""" + seen_outputs: dict[int, TensorBox] = {} + leaf_counter = itertools.count() + + def walk(output: object, indices: list[tuple[type, int]]) -> list[TensorBox]: + if isinstance(output, (list, tuple)): + results: list[TensorBox] = [] + for i, item in enumerate(output): + results.extend(walk(item, [*indices, (type(output), i)])) + return results + leaf_idx = next(leaf_counter) + if isinstance(output, torch.Tensor): + if direct_alias_at_leaf and leaf_idx in direct_alias_at_leaf: + return [TensorBox.create(direct_alias_at_leaf[leaf_idx])] + tid = id(output) + if tid in seen_outputs: + return [seen_outputs[tid]] + mo = MultiOutput( + FallbackKernel.tensor_to_layout(output), template_buf, indices + ) + template_buf._multi_output_children[mo.get_name()] = mo + if on_tensor_leaf is not None: + on_tensor_leaf(mo.get_name(), mo, indices, leaf_idx) + tb = TensorBox(mo) + seen_outputs[tid] = tb + return [tb] + # Non-tensor leaf (int, SymInt, None, etc.) + if on_non_tensor_leaf is not None: + on_non_tensor_leaf(leaf_idx) + return [] + + return tuple(walk(structured, [])) + + +class TritonTemplateBuffer(TemplateBuffer): + def __init__( + self, + layout: Layout, + inputs: Sequence[IRNode], + make_kernel_render: Callable[_P, _T] | None, + mutated_inputs: Iterable[IRNode] | None = None, + allowed_prologue_inps: OrderedSet[str] | None = None, + ) -> None: + """ + NOTE:[TritonTemplates with multiple outputs] + We want the ability for TritonTemplates to output multiple tensors. Triton + kernels have no notion of outputs and this is done by creating tensors that + are then mutated by the kernel. Currently our STORE_OUTPUT codegen doesn't + support creating multinode outputs for triton templates. + We work around this by creating an extra input buffer during the lowering + and we mark them as mutated inputs. + """ + super().__init__( + layout, + inputs, + make_kernel_render, + mutated_inputs=mutated_inputs, + allowed_prologue_inps=allowed_prologue_inps, + ) + if self.name is None: + raise AssertionError("Expected self.name is not None") + self.epilogue_fusable_outputs = {self.name: self.name} + + self.subgraph_inps: list[IRNode | Expr | None] | None = None + self.subgraph_outs: list[IRNode | None] | None = None + + @cache_on_self_and_args("TritonTemplateBuffer") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + res = super().get_free_symbol_uses(unbacked_only) + subgraph_outs = self.subgraph_outs if self.subgraph_outs else [] + subgraph_inps = self.subgraph_inps if self.subgraph_inps else [] + + for inp in subgraph_inps: + if isinstance(inp, Expr): + res.update(get_free_symbols(inp, unbacked_only)) + elif isinstance(inp, IRNode): + res.update(inp.get_free_symbol_uses(unbacked_only)) + else: + if inp is not None: + raise AssertionError("Expected inp is None") + + for out in subgraph_outs: + if isinstance(out, IRNode): + res.update(out.get_free_symbol_uses(unbacked_only)) + else: + if out is not None: + raise AssertionError("Expected out is None") + + return res + + def get_outputs(self) -> list[Buffer]: + return [self, *self.mutation_outputs] + + def __str__(self) -> str: + out = f"TritonTemplateBuffer(layout={self.layout})" + return out + + +PrimitiveInfoType = int | float | bool | str | list[int | str | float | bool] + + +class ChoiceCaller: + """ + Represents a possible choice used in autotune_process.py. + During autotuning, self.benchmark() is first called to get benchmark result, + and if this choice is selected, self.output_node() is called to get the output_node. + + Children classes: TritonTemplateCaller, CUTLASSTemplateCaller. + """ + + def __init__( + self, + name: str, + input_nodes: list[Buffer], + layout: Layout, + description: str, + ) -> None: + super().__init__() + self.name = name + self.layout = layout + self.input_nodes = input_nodes + # An additional description used to describe the choice (useful for + # knowing what autotuning is choosing) + self.description = description + self.failed: bool = False + # When True, benchmark using CUDA graph capture/replay + self._benchmark_with_cudagraphs: bool = False + # A place to store annotations that can be read post benchmarking + # Use this to shuttle information between ChoieCaller generation + # and the end of benchmarking + self.annotations: dict[str, object] = {} + # Subclass-overridden attributes for subgraph-based choices + self.gm: torch.fx.GraphModule | None = None + self.decomposition: Callable[..., Any] | None = None + self.decomposition_kwargs: dict[str, object] = {} + self.config_patches: dict[str, Any] = {} + + def benchmark(self, *args: Any, out: torch.Tensor) -> float: + algo = self.to_callable() + if self._benchmark_with_cudagraphs: + return benchmarker.benchmark_gpu_with_cuda_graph(lambda: algo(*args)) + if config.profile_bandwidth_with_do_bench_using_profiling: + return do_bench_using_profiling(lambda: algo(*args)) # type: ignore[arg-type] + return benchmarker.benchmark(algo, args, {"out": out}, device=None) + + def call_name(self) -> str: + raise NotImplementedError + + def to_callable(self) -> Callable[..., Any]: + raise NotImplementedError + + def kernel_hash_key(self) -> str: + """ + Hash key for the underlying kernel. By default, we assume there are no + runtime params, so kernel hash key defaults to choice caller's hash key. + """ + return self.hash_key() + + def hash_key(self) -> str: + raise NotImplementedError + + def output_node(self) -> TensorBox: + raise NotImplementedError + + def info_dict(self) -> dict[str, PrimitiveInfoType | list[PrimitiveInfoType]]: + """Information returned here is logged to the autotune log file when that is enabled.""" + return {} + + def autoheuristic_id(self) -> str: + return "unsupported_choice" + + def mark_failed(self) -> None: + """ + Mark the choice as failed so that it can be + removed later. Useful for when we decouple + compilation and tuning. + """ + self.failed = True + + +class TritonTemplateCallerBase(ChoiceCaller): + def get_make_kernel_render(self) -> Any: + raise NotImplementedError + + +_NVUniversalGemmCallerClass: type | None = None + + +def _is_output_plannable_nvgemm_choice(choice: ChoiceCaller) -> bool: + global _NVUniversalGemmCallerClass + if _NVUniversalGemmCallerClass is None: + try: + from torch._inductor.codegen.nv_universal_gemm import NVUniversalGemmCaller + + _NVUniversalGemmCallerClass = NVUniversalGemmCaller + except ImportError: + return False + return isinstance(choice, _NVUniversalGemmCallerClass) + + +class MultiTemplateBuffer(TritonTemplateBuffer): + """ + Represents a Buffer with multiple backing implementation choices. + + Choices can be TritonTemplates or ExternKernels. During scheduling if there is a potential + epilogue we will benchmark each of the choices with the epilogue to determine an implementation. + Otherwise, the fastest base choice will be chosen. + """ + + def __init__( + self, + layout: Layout, + inputs: Sequence[IRNode], + choice_timings_fn: Callable[[int | None], dict[ChoiceCaller, float]], + unfiltered_choices: list[ChoiceCaller], + allowed_prologue_inps: OrderedSet[str], + ) -> None: + super().__init__( + layout=layout, + inputs=inputs, + make_kernel_render=None, + allowed_prologue_inps=allowed_prologue_inps, + ) + self._choice_timings_fn = choice_timings_fn + self._choice_timings: dict[int | None, dict[ChoiceCaller, float]] = {} + self._choices: list[ChoiceCaller] = unfiltered_choices + self.original_inputs = inputs + self._output_plannable = all( + isinstance(choice, TritonTemplateCallerBase) + or _is_output_plannable_nvgemm_choice(choice) + or ( + isinstance(choice, torch._inductor.select_algorithm.ExternKernelCaller) + and choice.has_out_variant + ) + for choice in unfiltered_choices + ) + self._make_kernel_renders: dict[int | None, Any] = {} + self._render_kind: str | None = None + # Tracks the bound caller so the fusion-benchmark loop's per-iteration + # swap is not silently overridden by re-selection from choice_timings(). + self._render_caller: ChoiceCaller | None = None + + @property + def output_plannable(self) -> bool: + """True when all choices are TritonTemplates, NVUniversalGemmCallers, or Extern Kernels with out variants.""" + return self._output_plannable + + @property + def choices(self) -> list[ChoiceCaller]: + return self._choices + + def choice_timings( + self, hint_override: int | None = None + ) -> dict[ChoiceCaller, float]: + if hint_override not in self._choice_timings: + self._choice_timings[hint_override] = self._choice_timings_fn(hint_override) + return self._choice_timings[hint_override] + + @contextlib.contextmanager + def swap_as_triton_caller(self, caller: TritonTemplateCallerBase) -> Iterator[None]: + if not isinstance( + caller, torch._inductor.select_algorithm.TritonTemplateCaller + ): + raise AssertionError(type(caller)) + if self.layout != caller.layout: + raise AssertionError("Expected self.layout == caller.layout") + + render = self.make_kernel_render + prev_kind = self._render_kind + prev_caller = self._render_caller + self.make_kernel_render = caller.get_make_kernel_render() + self._render_kind = "triton" + self._render_caller = caller + try: + yield + finally: + self.make_kernel_render = render + self._render_kind = prev_kind + self._render_caller = prev_caller + + def finalize_as_triton_caller(self, caller: TritonTemplateCallerBase) -> None: + if not isinstance( + caller, torch._inductor.select_algorithm.TritonTemplateCaller + ): + raise AssertionError(type(caller)) + if self.get_size() != caller.layout.size: + raise AssertionError("Expected self.get_size() == caller.layout.size") + if self.get_stride() != caller.layout.stride: + raise AssertionError("Expected self.get_stride() == caller.layout.stride") + self.make_kernel_render = caller.get_make_kernel_render() + self._render_kind = "triton" + self._render_caller = caller + + @contextlib.contextmanager + def swap_as_nvgemm_caller(self, caller: ChoiceCaller) -> Iterator[None]: + from torch._inductor.codegen.nv_universal_gemm import NVUniversalGemmCaller + + if not isinstance(caller, NVUniversalGemmCaller): + raise AssertionError(f"expected NVUniversalGemmCaller, got {type(caller)}") + if self.layout != caller.layout: + raise AssertionError("Expected self.layout == caller.layout") + + render = self.make_kernel_render + prev_kind = self._render_kind + prev_caller = self._render_caller + self.make_kernel_render = caller.get_make_kernel_render() + self._render_kind = "nvgemm" + self._render_caller = caller + try: + yield + finally: + self.make_kernel_render = render + self._render_kind = prev_kind + self._render_caller = prev_caller + + def finalize_as_nvgemm_caller(self, caller: ChoiceCaller) -> None: + from torch._inductor.codegen.nv_universal_gemm import NVUniversalGemmCaller + + if not isinstance(caller, NVUniversalGemmCaller): + raise AssertionError(f"expected NVUniversalGemmCaller, got {type(caller)}") + if self.get_size() != caller.layout.size: + raise AssertionError("Expected self.get_size() == caller.layout.size") + if self.get_stride() != caller.layout.stride: + raise AssertionError("Expected self.get_stride() == caller.layout.stride") + self.make_kernel_render = caller.get_make_kernel_render() + self._render_kind = "nvgemm" + self._render_caller = caller + + def get_min_choice( + self, hint_override: int | None = None + ) -> tuple[ChoiceCaller, float]: + timings = self.choice_timings(hint_override=hint_override) + min_choice = min(timings, key=timings.get) # type: ignore[arg-type] + return (min_choice, timings[min_choice]) + + def finalize_as_triton_callers( + self, callers: dict[int | None, TritonTemplateCallerBase] + ) -> None: + """Finalize with multiple callers for different hint overrides""" + for hint_override, caller in callers.items(): + self._make_kernel_renders[hint_override] = caller.get_make_kernel_render() + + # Set the default to be the one without hint override + self.make_kernel_render = self._make_kernel_renders[None] + self._render_kind = "triton" + self._render_caller = callers[None] + + +class CUTLASSTemplateBuffer(TemplateBuffer): + def __init__( + self, + layout: Layout, + inputs: Sequence[IRNode], + make_kernel_render: Callable[_P, _T], + workspace_size: int, + template: CUTLASSTemplate, + supports_epilogue_fusion: bool, + ) -> None: + super().__init__(layout, inputs, make_kernel_render) + # Global memory (in bytes) needed for this template. + self.workspace_size = workspace_size + self.template = template + self.supports_epilogue_fusion = supports_epilogue_fusion + + def get_workspace_size(self) -> int: + return self.workspace_size if self.workspace_size is not None else 0 + + def emulate_store_fn(self) -> None: + for output in self.get_outputs(): + ops.store(output.get_name(), None, None) + + +class CppTemplateBuffer(TemplateBuffer): + def __init__( + self, + layout: Layout, + inputs: Sequence[IRNode], + make_kernel_render: Callable[_P, _T], + template: CUTLASSTemplate, + choice: Any, + ) -> None: + super().__init__(layout, inputs, make_kernel_render) + self.template = template + self.choice = choice + self.outputs: list[Buffer] | None = None + + def get_layout(self) -> Layout: + if isinstance(self.layout, MultiOutputLayout): + if not isinstance(self.outputs, Iterable): + raise AssertionError(type(self.outputs)) + + first_output = self.outputs[0] + if not isinstance(first_output, Buffer): + raise AssertionError(type(first_output)) + layout = first_output.layout + if not isinstance(layout, Layout): + raise AssertionError(type(layout)) + return layout + else: + return super().get_layout() + + +class CuteDSLTemplateBuffer(TemplateBuffer): + """ + Buffer for CuteDSL (CUTLASS Python DSL) template kernels. + Similar to other template buffers but specialized for CuteDSL operations. + """ + + def __init__( + self, + layout: Layout, + inputs: Sequence[IRNode], + make_kernel_render: Callable[_P, _T], + template: Any, + mutated_inputs: Iterable[IRNode] | None = None, + ) -> None: + super().__init__(layout, inputs, make_kernel_render) + self.template = template + self.mutated_inputs = mutated_inputs + self.outputs: list[Buffer] = [self] + + if mutated_inputs is not None: + if not isinstance(self.inputs[0], IRNode): + raise AssertionError(type(self.inputs[0])) + device = self.inputs[0].get_device() + self.outputs += [ + MutationOutput(NoneLayout(device=device), buf, self) + for buf in mutated_inputs + ] + + def get_outputs(self) -> list[Buffer]: + return self.outputs + + +class NVUniversalGemmBuffer(TemplateBuffer): + """ + Buffer for NVIDIA Universal GEMM kernels. + + Unlike CuteDSL templates which use Jinja templates, this generates + simpler Python code that directly calls the cutlass.operators library. + """ + + def __init__( + self, + layout: Layout, + inputs: Sequence[IRNode], + kernel: Any, + accumulator_type: Any, + variant: Any, # GemmVariant, use Any to avoid circular import + workspace_size: int = 0, + scale_type_a: Any | None = None, + scale_type_b: Any | None = None, + swizzle_type_a: Any | None = None, + swizzle_type_b: Any | None = None, + supports_epilogue_fusion: bool = False, + swap_ab: bool = False, + bias_node: Buffer | None = None, + ) -> None: + # We pass None initially, then override with our method below + super().__init__(layout, inputs, make_kernel_render=None) + self.kernel = kernel + self.accumulator_type = accumulator_type + self.outputs: list[Buffer] = [self] + self.workspace_size = workspace_size + self.variant = variant + self.scale_type_a = scale_type_a + self.scale_type_b = scale_type_b + self.swizzle_type_a = swizzle_type_a + self.swizzle_type_b = swizzle_type_b + self.supports_epilogue_fusion = supports_epilogue_fusion + self.swap_ab = swap_ab + # When set, the last entry of `inputs` is an addmm bias consumed as a + # fixed bias-add epilogue; the GEMM operands are the remaining inputs. + self.bias_node = bias_node + # Store kernel metadata for code generation since kernels aren't serializeable yet + self.kernel_metadata = { + "kernel_name": kernel.metadata.operator_name, + "min_cc": kernel.designed_for_min_cc, + } + # Override the instance attribute set by parent with our method + # This is necessary because TemplateBuffer stores make_kernel_render as instance attr + self.make_kernel_render = self._make_kernel_render + + def get_workspace_size(self) -> int: + """Return the workspace size in bytes.""" + return self.workspace_size + + def get_outputs(self) -> list[Buffer]: + return self.outputs + + def _make_kernel_render( + self, + out_node: Any, + hint_override: int | None = None, + epilogue_fn_code: str | None = None, + epilogue_reads: list[str] | None = None, + epilogue_writes: list[str] | None = None, + epilogue_var_renames: dict[str, Any] | None = None, + local_reduce: GemmReductionPlan | None = None, + ) -> tuple[Any, Any]: + """ + Create a kernel renderer for code generation. + + Returns (kernel, render) tuple where: + - kernel: NVUniversalGemmKernel object with call_kernel() method + - render: function that returns source code string + """ + if epilogue_fn_code is not None: + if epilogue_var_renames is None: + raise AssertionError("epilogue_fn_code requires epilogue_var_renames") + + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import ( + NVUniversalGemmKernel, + ) + from torch._inductor.utils import Placeholder + + input_nodes: list[Any] = [] + for inp in self.inputs: + if isinstance(inp, TensorBox): + inp = inp.data + if isinstance(inp, StorageBox): + inp = inp.data + input_nodes.append(inp) + + # For a baked addmm bias, the bias is the last input and is consumed by + # the epilogue, not as a GEMM operand. + bias_node = None + if self.bias_node is not None: + bias_node = input_nodes[-1] + input_nodes = input_nodes[:-1] + + kernel_name = str(Placeholder.KERNEL_NAME) + + render_kernel = NVUniversalGemmKernel( + kernel_name=kernel_name, + input_nodes=input_nodes, + output_node=out_node, + kernel_metadata=self.kernel_metadata, + accumulator_type=self.accumulator_type, + workspace_size=self.workspace_size, + variant=self.variant, + scale_type_a=self.scale_type_a, + scale_type_b=self.scale_type_b, + swizzle_type_a=self.swizzle_type_a, + swizzle_type_b=self.swizzle_type_b, + epilogue_fn_code=epilogue_fn_code, + epilogue_reads=epilogue_reads, + epilogue_writes=epilogue_writes, + epilogue_var_renames=epilogue_var_renames, + local_reduce=local_reduce, + swap_ab=self.swap_ab, + bias_node=bias_node, + ) + + def render(): + return render_kernel.render() + + return render_kernel, render + + +def is_node_sequence( + nodes: Sequence[IRNode | Sequence[IRNode]], +) -> TypeIs[Sequence[IRNode]]: + return all(isinstance(n, IRNode) for n in nodes) + + +@ir_dataclass(frozen=False) +class InputsKernel(OperationBuffer): + inputs: Sequence[IRNode | Sequence[IRNode]] + + def input_name(self, i: int) -> str: + input = self.inputs[i] + if not isinstance(input, IRNode): + raise AssertionError("Expected isinstance(input, IRNode)") + return input.get_name() + + def get_read_writes(self) -> dependencies.ReadWrites: + reads = OrderedSet[dependencies.Dep]() + StarDep = dependencies.StarDep + for input in self.inputs: + if isinstance(input, Sequence): + reads.update(StarDep(x.get_name()) for x in input) + elif isinstance(input, ShapeAsConstantBuffer): + # Skip creating dependency for symbolics as they're visible globally + continue + else: + reads.add(StarDep(input.get_name())) + + writes = OrderedSet[dependencies.Dep]( + StarDep(buf.get_name()) for buf in self.get_outputs() + ) + + return dependencies.ReadWrites( + reads=reads, + writes=writes, + index_exprs=OrderedSet(), + ) + + def get_reads(self) -> OrderedSet[Dep]: + return self.get_read_writes().reads + + @classmethod + def unwrap_storage_for_input(cls, x: IRNode) -> IRNode: + if isinstance(x, TensorBox): + x = x.data + if isinstance(x, StorageBox): + x = x.data + if isinstance(x, BaseView) and not isinstance(x, ReinterpretView): + x = ExternKernel.realize_input(x) + if isinstance(x, TensorBox): + # when converting to ReinterpretView fails in the + # realize_input call above, the result will be wrapped + # into TensorBox / StorageBox pair as a result of the + # cls.copy_input call; so we should unwrap recursively + return cls.unwrap_storage_for_input(x) + if isinstance(x, TorchBindObject): + return x + if not isinstance(x, (Buffer, ReinterpretView)): + raise AssertionError(type(x)) + return x + + @staticmethod + def unwrap_storage( + inputs: Sequence[IRNode | Sequence[IRNode]], + ) -> list[IRNode | Sequence[IRNode]]: + inputs_new: list[IRNode | Sequence[IRNode]] = [] + for x in inputs: + if isinstance(x, Sequence): + x = [InputsKernel.unwrap_storage_for_input(i) for i in x] + else: + x = InputsKernel.unwrap_storage_for_input(x) + inputs_new.append(x) + return inputs_new + + def is_extern(self) -> bool: + return True + + def num_reads(self) -> int: + return 1 + + @cache_on_self_and_args("InputsKernel") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + r = OrderedSet[sympy.Symbol]() + for inp in self.inputs: + if isinstance(inp, IRNode): + r |= inp.get_free_symbol_uses(unbacked_only) + else: + for inner_inp in inp: + r |= inner_inp.get_free_symbol_uses(unbacked_only) + return r + + +class NopKernel(InputsKernel): + def is_no_op(self) -> bool: + return True + + def get_reads(self) -> OrderedSet[Dep]: + return OrderedSet() + + +class ConcatKernel(NopKernel): + """ + There isn't actually a real kernel for concat, we just change the + storage for the upstream data. + """ + + @classmethod + def create(cls, inputs: Sequence[IRNode], dim: int) -> StorageBox: + """ + Create the concat kernel from inputs + """ + device = inputs[0].get_device() + dtype = inputs[0].get_dtype() + new_size = list(inputs[0].get_size()) + offsets_start = [0] + offsets_end = [new_size[dim]] + if not (0 <= dim < len(new_size)): + raise AssertionError("Expected 0 <= dim < len(new_size)") + for i in range(1, len(inputs)): + input_size = inputs[i].get_size() + offsets_start.append(new_size[dim]) + if len(input_size) != len(new_size): + raise AssertionError("Expected len(input_size) == len(new_size)") + if inputs[i].get_dtype() != dtype: + raise AssertionError("Expected inputs[i].get_dtype() == dtype") + if inputs[i].get_device() != device: + raise AssertionError("Expected inputs[i].get_device() == device") + for j in range(len(new_size)): + if j == dim: + new_size[j] = new_size[j] + input_size[j] + else: + new_size[j] = V.graph.sizevars.check_equals_and_simplify( + new_size[j], input_size[j] + ) + offsets_end.append(new_size[dim]) + + output_stride: Sequence[int] = FlexibleLayout.contiguous_strides(new_size) + if config.comprehensive_padding: + # Ensure the output stride matches the alignment requirements + output_stride = Layout._pad_strides( + output_stride, new_size, inputs[0].dtype + ) + + # If any of the inputs is in CL format, use CL format for the output + for i in range(len(inputs)): + x = inputs[i] + if is_storage_and_layout(x): + layout = x.get_layout() + if isinstance( + layout, FixedLayout + ) and Layout.is_channels_last_contiguous(layout.size, layout.stride): + # use CL stride for the output + output_stride = make_channels_last_strides_for(new_size) + break + any_input_is_storage_and_layout = any(is_storage_and_layout(x) for x in inputs) + fx_node_args = V.graph.current_node.args[0] + # If any of the inputs has meta tensor and the meta tensor is in CL format, use CL format for the output + # Skip this check when fx_node_args is not a list (e.g., called from _pad_as_cat). + if ( + any_input_is_storage_and_layout is False + and isinstance(fx_node_args, list) + and any( + # pyrefly: ignore [missing-attribute] + "val" in arg.meta + and ( + is_contiguous_for_memory_format_or_false( + # pyrefly: ignore [missing-attribute] + arg.meta["val"], + memory_format=torch.channels_last, + ) + or is_contiguous_for_memory_format_or_false( + # pyrefly: ignore [missing-attribute] + arg.meta["val"], + memory_format=torch.channels_last_3d, + ) + ) + for arg in fx_node_args + ) + ): + output_stride = make_channels_last_strides_for(new_size) + + is_pinned = all( + is_storage_and_layout(x) and x.get_layout().is_pinned for x in inputs + ) + + if device is None: + raise AssertionError("Expected device is not None") + concat_kernel = ConcatKernel( + name=None, + layout=FixedLayout( + device=device, + dtype=dtype, + size=new_size, + stride=output_stride, + is_pinned=is_pinned, + ), + inputs=[], + ) + kernel = StorageBox(concat_kernel) + op_names = [] + for i, inp in enumerate(inputs): + if not isinstance(inp, (BaseView, MutableBox)): + raise AssertionError(type(inp)) + input_buffer = cls.realize_into( + inp, + SliceView.create( + kernel, dim, offsets_start[i], offsets_end[i], clamp=False + ), + ) + if not isinstance(input_buffer, Buffer): + raise AssertionError(type(input_buffer)) + if not isinstance(concat_kernel.inputs, list): + raise AssertionError(type(concat_kernel.inputs)) + concat_kernel.inputs.append(input_buffer) + + if isinstance(inp.data, BaseView): + input_unwrapped = inp.data.unwrap_view() + else: + input_unwrapped = inp.data + + if ( + isinstance(input_unwrapped, StorageBox) + and input_unwrapped.is_input_buffer() + and (dev := inp.get_device()) is not None + and is_gpu(dev.type) + and not is_dynamic(input_buffer) + ): + op_names.append(input_buffer.get_operation_name()) + + if len(op_names) > 1 and V.graph.has_feature(device, BackendFeature.FOREACH): + V.graph.register_operation_list(op_names) + + concat_kernel.name = V.graph.register_buffer(concat_kernel) + concat_kernel.inputs = cls.unwrap_storage(concat_kernel.inputs) + V.graph.register_operation(concat_kernel) + + return kernel + + @classmethod + def can_realize_into_without_copy( + cls, src: IRNode, dst: IRNode | None = None + ) -> bool: + if isinstance(src, TensorBox): + # unwrap a TensorBox + return cls.can_realize_into_without_copy(src.data, dst) + + if not isinstance(src, (BaseView, StorageBox)): + raise AssertionError(type(src)) + if isinstance(src.data, MultiTemplateBuffer): + if ( + not isinstance(src.data.layout, FixedLayout) + or not src.data.output_plannable + ): + return False + + # we call can_realize_into_without_copy in cat lowering before we've decided + # on output format, optimistically assume layout matches + if dst is None: + return True + + # otherwise, check equality of layouts + if len(src.get_stride()) != len(dst.get_stride()): + return False + + return all( + V.graph.sizevars.statically_known_equals(s1, s2) + for s1, s2 in zip(src.get_stride(), dst.get_stride()) + ) + + return ( + hasattr(src.data, "layout") + and isinstance(src.data.layout, FlexibleLayout) + and not isinstance(src.data, ExternKernelAlloc) + ) + + @cache_on_self_and_args("ConcatKernel") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return NopKernel.get_free_symbol_uses(self, unbacked_only) + + @classmethod + def realize_into(cls, src: IRNode, dst: IRNode) -> IRNode: + # Attempt to turn this into a ReinterpretView rather than assert. + # This has concessions around layout, as as_storage_and_layout + # can cause us to go from flexible to fixed layout. + if not isinstance(dst, ReinterpretView): + if is_storage_and_layout(dst): + storage, layout = as_storage_and_layout(dst) + dst = ReinterpretView(data=storage, layout=layout) + if not isinstance(dst, ReinterpretView): + raise AssertionError(type(dst)) + if isinstance(src, TensorBox): + # unwrap a TensorBox + return cls.realize_into(src.data, dst) + + if isinstance(src, StorageBox): + src.realize() + # ExternKernelAlloc has specific requirements for output layout, should create a copy + if not hasattr(src.data, "layout"): + raise AssertionError('Expected hasattr(src.data, "layout")') + if cls.can_realize_into_without_copy(src, dst): + # pyrefly: ignore [missing-attribute] + src.data.layout = NonOwningLayout(dst) + return src.data + # introduce a copy + pw = Pointwise.create( + device=src.get_device(), + dtype=src.get_dtype(), + inner_fn=src.make_loader(), + ranges=[ + V.graph.sizevars.check_equals_and_simplify(a, b) + for a, b in zip(src.get_size(), dst.get_size()) + ], + ) + return cls.realize_into(pw, dst) + + def should_allocate(self) -> bool: + return True + + +@contextlib.contextmanager +def _track_fresh_unbacked_symbols(shape_env: ShapeEnv) -> Iterator[None]: + prev = shape_env._ignore_fresh_unbacked_symbols_set(False) + try: + yield + finally: + shape_env._ignore_fresh_unbacked_symbols_set(prev) + + +def _fallback_kernel_symbol_tracking_context( + shape_env: ShapeEnv | None, +) -> AbstractContextManager[None]: + if shape_env is not None and shape_env._ignore_fresh_unbacked_symbols_tls(): + return _track_fresh_unbacked_symbols(shape_env) + return nullcontext() + + +@dataclasses.dataclass(frozen=True) +class ProcessKernelResult: + """Structured result of ExternKernel.process_kernel. + + Replaces the positional 5-tuple that was unpacked at every call site. + unflatten_args(new_tensor_args, new_non_tensor_args) reconstructs the + original (args, kwargs) tree from replacement lists. + """ + + example_output: Any + tensor_args: list[IRNode] + non_tensor_args: list[object] + unflatten_args: Callable[[Any, Any], Any] + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None + + +@ir_dataclass(frozen=False) +class ExternKernel(InputsKernel): + """ + A class that represents Kernels which are not directly lowered to Inductor + Loop Level IR, such as custom operators, or aten operators which we fallback to. + """ + + constant_args: Sequence[Any] = () + kwargs: dict[str, Any] = dataclasses.field(default_factory=dict) + output_view: ReinterpretView | None = None + python_kernel_name: str | None = None + cpp_kernel_name: str | None = None + # FIXME: in some cases we sill need to explicitly pass in ordered_kwargs_for_cpp_kernel + # We shouldn't need to do this since the information can be retrieved from op_overload._schema. + ordered_kwargs_for_cpp_kernel: Iterable[str] = dataclasses.field( + default_factory=list + ) + op_overload: _OpOverloads | None = None + arg_properties: list[ArgProperty] | None = None + allarg_properties: dict[str, ArgProperty] = dataclasses.field(default_factory=dict) + kwarg_properties: dict[str, ArgProperty] | None = None + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] = dataclasses.field( + default_factory=dict + ) + mutation_outputs: list[MutationOutput] = dataclasses.field(default_factory=list) + + def __init__( + self, + name: str | None, + layout: OutputSpec, + inputs: Sequence[IRNode | Sequence[IRNode]], + constant_args: Sequence[Any] = (), + kwargs: dict[str, Any] | None = None, + output_view: ReinterpretView | None = None, + python_kernel_name: str | None = None, + cpp_kernel_name: str | None = None, + ordered_kwargs_for_cpp_kernel: Iterable[str] = (), + op_overload: _OpOverloads | None = None, + ) -> None: + super().__init__( + name=name, + layout=layout, + inputs=inputs, + ) + self.constant_args = constant_args + self.kwargs = kwargs if kwargs else {} + self.output_view = output_view + self.op_overload = op_overload + self.set_cpp_kernel_name(cpp_kernel_name) + self.set_python_kernel_name(python_kernel_name) + self.ordered_kwargs_for_cpp_kernel = ordered_kwargs_for_cpp_kernel + self.collect_arg_kwarg_properties() + self.unbacked_bindings = {} + self.mutation_outputs = [] + self.fx_node = V.graph.current_node + # Annotations dict for storing metadata (e.g., KernelTemplateChoice) + self.annotations: dict[str, object] = {} + + def get_outputs(self) -> list[Buffer]: + return [self, *self.mutation_outputs] + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def get_read_writes(self) -> dependencies.ReadWrites: + read_writes = super().get_read_writes() + + def add_ir_read(value: Any) -> None: + if isinstance(value, IRNode): + name = value.maybe_get_name() + if name is not None: + read_writes.reads.add(dependencies.StarDep(name)) + + pytree.tree_map_( + add_ir_read, + (self.constant_args, self.kwargs), + is_leaf=lambda value: isinstance(value, IRNode), + ) + return read_writes + + def collect_arg_kwarg_properties(self) -> None: + # if self.op_overload is torch._ops.OpOverload, we can use its schema to collect additional + # information for args and kwargs, e.g. type and default value, to help with the cpp wrapper codegen + self.arg_properties = ( + [ + { + "name": x.name, + "type": x.real_type, + "default_value": x.default_value, + } + for x in self.op_overload._schema.arguments + if not x.kwarg_only + ] + if isinstance(self.op_overload, torch._ops.OpOverload) + else [{} for i in range(len(self.inputs))] + ) + self.allarg_properties = ( + { + x.name: {"type": x.real_type, "default_value": x.default_value} + for x in self.op_overload._schema.arguments + } + if isinstance(self.op_overload, torch._ops.OpOverload) + else {} + ) + # FIXME: self.kwargs does not always match kwargs defined in schema, so sometimes + # ordered_kwargs_for_cpp_kernel is explicitly passed in. + if isinstance(self.op_overload, torch._ops.OpOverload): + if not self.ordered_kwargs_for_cpp_kernel: + self.ordered_kwargs_for_cpp_kernel = [ + x.name for x in self.op_overload._schema.arguments if x.kwarg_only + ] + self.schema_kwargs = [ + x for x in self.op_overload._schema.arguments if x.kwarg_only + ] + else: + self.schema_kwargs = [] + + def decide_layout(self) -> None: + if isinstance(self.layout, FlexibleLayout): + self.apply_constraint() + self.freeze_layout() + + def codegen_comment( + self, wrapper: PythonWrapperCodegen, kernel_name: str | None = None + ) -> None: + origin_str, _detailed_origin_str = get_kernel_metadata(self, wrapper) + if origin_str: + wrapper.make_comment(origin_str) + + if not kernel_name: + kernel_name = self.try_get_kernel_name() + if kernel_name: + from .debug import set_kernel_post_grad_provenance_tracing + + debug_handle = set_kernel_post_grad_provenance_tracing( + self, kernel_name, is_extern=True + ) + wrapper.write_provenance_debug_handle(kernel_name, debug_handle) + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + raise NotImplementedError + + def set_cpp_kernel_name(self, cpp_kernel_name: str | None = None) -> None: + self.cpp_kernel_name = cpp_kernel_name + if not V.graph.cpp_wrapper or not isinstance( + self.op_overload, torch._ops.OpOverload + ): + return + + kernel = self.op_overload + if self.cpp_kernel_name is None: + # Try to construct cpp_kernel_name from op_overload + if kernel.namespace == "aten": + # Calling with the default kernel name can lead to ambiguous behavior like the following example. + # repeat_interleave(const at::Tensor & repeats, std::optional output_size=std::nullopt) + # repeat_interleave(const at::Tensor & self, int64_t repeats, + # std::optional dim=std::nullopt, std::optional output_size=std::nullopt) + opname = ( + kernel.__name__.split(".")[0] + if kernel._overloadname == "default" + else kernel.__name__.replace(".", "_") + ) + # If the op has a versioned c_shim entry, call the latest _v{N} + # variant so new AOTI artifacts match the current op schema. The + # unversioned shim is retained solely for BC with existing + # already-compiled artifacts. + from torchgen.aoti.fallback_ops import inductor_fallback_ops + + version_info = inductor_fallback_ops.get(f"aten.{kernel.__name__}", {}) + latest_version = max( + (int(v[1:]) for v in version_info if v.startswith("v")), + default=1, + ) + if latest_version > 1: + opname = f"{opname}_v{latest_version}" + self.cpp_kernel_name = f"at::_ops::{opname}::call" + else: + self.cpp_kernel_name = kernel._schema.name + + def set_python_kernel_name(self, python_kernel_name: str | None) -> None: + self.python_kernel_name = python_kernel_name + if python_kernel_name is not None: + return + + kernel = self.op_overload + if kernel is None: + pass + elif isinstance(kernel, torch._ops.HigherOrderOperator): + self.python_kernel_name = f"torch.ops.higher_order.{kernel.__name__}" + else: + self.python_kernel_name = ( + f"{kernel.__module__.replace('._ops.', '.ops.')}.{kernel.__name__}" + ) + + def try_get_kernel_name(self) -> str | None: + from .codegen.cpp_wrapper_cpu import CppWrapperCpu + + device = d.type if (d := self.get_device()) else V.graph.device_type + if V.graph.fx_wrapper: + return self.python_kernel_name + elif V.graph.cpp_wrapper: + if not isinstance(V.graph.wrapper_code, CppWrapperCpu): + raise AssertionError(type(V.graph.wrapper_code)) + if self.cpp_kernel_name is None: + return None + return V.graph.wrapper_code.get_c_shim_func_name( + self.cpp_kernel_name, device + ) + else: + return self.python_kernel_name + + def get_kernel_name(self) -> str: + name = self.try_get_kernel_name() + if name is None: + raise AssertionError("Expected name is not None") + return name + + @staticmethod + def copy_input(x: IRNode) -> TensorBox: + pw = Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=x.make_loader(), + ranges=x.get_size(), + origin_node=x.get_origin_node(), + traceback=x.get_traceback(), + ) + pw.realize() + return pw + + @classmethod + def process_kernel( + cls, kernel: _OpOverloads, *args: Any, **kwargs: Any + ) -> ProcessKernelResult: + """Partition kernel args into tensor and non-tensor, realize tensor inputs, + re-run fake tensor propagation with the realized strides, and return a + ProcessKernelResult (see that class for field semantics). + """ + binded_args = {"args": args, "kwargs": kwargs} + + args_flat, args_spec = pytree.tree_flatten(binded_args) + + args_flat_is_tensor: list[bool] = [] + # tensor_args can be either tensor or torchbind objects + tensor_args: list[IRNode] = [] + non_tensor_args: list[object] = [] + real_non_tensor_args: list[ + FakeScriptObject + | torch._C.Generator + | torch._C.ScriptObject + | torch.Tensor + | IntLikeType + ] = [] + for arg in args_flat: + match arg: + case Expr(): + node = V.graph.sizevars.shape_env.create_symintnode(arg, hint=None) + args_flat_is_tensor.append(False) + non_tensor_args.append(node) + real_non_tensor_args.append(node) + + case GeneratorState(): + args_flat_is_tensor.append(False) + non_tensor_args.append(arg) + device_index = arg.device.index + if not ( + arg.device.type in ["cuda", "xpu"] and device_index is not None + ): + raise AssertionError( + 'Expected arg.device.type in ["cuda", "xpu"] and device_index is not None' + ) + real_non_tensor_args.append( + torch._C._accelerator_getDefaultGenerator( + device_index + ).clone_state() + ) + + case OpaqueObjectState(): + args_flat_is_tensor.append(False) + non_tensor_args.append(arg) + real_non_tensor_args.append(arg.value) + + case IRNode(): + args_flat_is_tensor.append(True) + tensor_args.append(arg) + + case _: + args_flat_is_tensor.append(False) + non_tensor_args.append(arg) + real_non_tensor_args.append(arg) + + def unflatten_args( + new_tensor_args: Sequence[_T], new_non_tensor_args: Sequence[_T] + ) -> tuple[list[_T], dict[str, _T]]: + result = [] + it_tensors = iter(new_tensor_args) + it_non_tensors = iter(new_non_tensor_args) + for is_tensor in args_flat_is_tensor: + if is_tensor: + result.append(next(it_tensors)) + else: + result.append(next(it_non_tensors)) + r = pytree.tree_unflatten(result, args_spec) + return r.get("args", []), r.get("kwargs", {}) + + tensor_args = [cls.realize_input(x) for x in tensor_args] + + # freeze layout otherwise our output stride calculation might + # become incorrect + for x in tensor_args: + if is_storage_and_layout(x): + as_storage_and_layout(x, freeze=True) + + # Rerun fake tensor propagation, because Inductor may have changed the + # strides of inputs and we need to determine accurately what the + # output stride will be. + example_args: list[ + torch.Tensor | torch._C.ScriptObject | FakeScriptObject | torch.Generator + ] = [] + + # We need to retain the constant values of fake tensors that we originally + # propagated the graph with, because for some operators running without a + # constant would trigger an error / DataDependentException + # TorchBind fake objects are mutable and may have been advanced by AOT + # tracing. Replay effectful ops on a fresh per-graph copy of the guarded + # object state instead of the already-mutated lowering value. + replay_torchbind = ( + isinstance(kernel, torch._higher_order_ops.torchbind.CallTorchBind) + or V.current_node.target is torch._higher_order_ops.effects.with_effects + ) + for x in tensor_args: + # if x is a view of a constant, we need to realize the view + # (we can't pass the constant into the kernel directly) + if not isinstance(x, BaseView) and x.get_name() in V.graph.constants: + example_args.append(V.graph.constants[x.get_name()]) + elif ( + not isinstance(x, BaseView) + and x.get_name() in V.graph.torchbind_constants + ): + example_args.append(V.graph.torchbind_constants[x.get_name()]) + elif isinstance(x, TorchBindObject): + if replay_torchbind: + replay_objects = V.graph.torchbind_replay_objects + if x.get_name() not in replay_objects: + replay_objects[x.get_name()] = maybe_to_fake_obj( + V.fake_mode, x.get_real_obj() + ) + example_args.append(replay_objects[x.get_name()]) + else: + example_args.append(x.get_value()) + elif isinstance(x, OpaqueMultiOutput): + example_args.append(x.opaque_example_value) + elif isinstance(x, torch._inductor.ir.GeneratorState): + device_index = x.device.index + if not (x.device.type in ["cuda", "xpu"] and device_index is not None): + raise AssertionError( + 'Expected x.device.type in ["cuda", "xpu"] and device_index is not None' + ) + example_args.append( + torch._C._accelerator_getDefaultGenerator( + device_index + ).clone_state() + ) + else: + example_args.append(ir_node_to_tensor(x)) + + new_args, new_kwargs = unflatten_args(example_args, real_non_tensor_args) + shape_env = V.fake_mode.shape_env + with ( + enable_python_dispatcher(), + _fallback_kernel_symbol_tracking_context(shape_env), + ): + example_output = kernel(*new_args, **new_kwargs) + + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None = None + if shape_env: + node_meta_val = V.current_node.meta.get("val") + ctx: AbstractContextManager[None] = nullcontext() + if V.current_node.target is torch._higher_order_ops.effects.with_effects: + # remove the first effect token in meta["val"] and meta["unbacked_bindings"] + # pyrefly: ignore[unsupported-operation] + node_meta_val = node_meta_val[1] + ctx = _remove_effect_token_unbacked_bindings(V.current_node) + + with ctx: + rebind_unbacked(shape_env, V.current_node, example_output) + unbacked_bindings = compute_unbacked_bindings( + shape_env, example_output, node_meta_val + ) + + example_out_li = ( + [example_output] + if not isinstance(example_output, (list, tuple)) + else example_output + ) + # When graph_partition is enabled, skip - partitioning handles sparse outputs + for t in example_out_li: + if ( + isinstance(t, torch.Tensor) + and t.is_sparse + and not config.graph_partition + ): + msg = "sparsity not handled. Please file issue for sparse inference weights." + if stack_trace := V.graph.current_node.meta.get("stack_trace", None): + msg = f"{msg} Found from : \n {stack_trace}" + V.graph.disable_cudagraphs_reason = msg + + return ProcessKernelResult( + example_output=example_output, + tensor_args=tensor_args, + non_tensor_args=non_tensor_args, + unflatten_args=unflatten_args, + unbacked_bindings=unbacked_bindings, + ) + + @classmethod + def convert_to_reinterpret_view(cls, x: IRNode) -> ReinterpretView: + """ + In order to pass this to an extern kernel we need a + ReinterpretView not a View. This allows us to avoid some + unneeded copies. + """ + if not isinstance(x, BaseView): + raise AssertionError(type(x)) + if isinstance(x, ReinterpretView): + return x + + # NOTE: Don't use extract_read_writes here as it fails when + # make_loader() inlines the computation + x_unwrap_view = x.unwrap_view() + buf = V.graph.get_buffer(x_unwrap_view.get_name()) + if buf is None: + raise AssertionError("Expected buf is not None") + x_unwrap_view_fx_node = buf.get_origin_node() + # Prefer channels last format according to how the format is set from eager. + if ( + x_unwrap_view_fx_node is not None + and "val" in x_unwrap_view_fx_node.meta + and isinstance(x_unwrap_view, (ReinterpretView, Buffer, MutableBox)) + and isinstance(x_unwrap_view.layout, FlexibleLayout) + and ( + is_contiguous_for_memory_format_or_false( + x_unwrap_view_fx_node.meta["val"], + memory_format=torch.channels_last, + ) + or is_contiguous_for_memory_format_or_false( + x_unwrap_view_fx_node.meta["val"], + memory_format=torch.channels_last_3d, + ) + ) + ): + x_unwrap_view.freeze_layout_with_same_order( + make_channels_last_strides_for(x_unwrap_view.get_size()) + ) + else: + x_unwrap_view.freeze_layout() + + index_args, var_ranges = dependencies.index_vars_squeeze( + x.get_size(), prefix="r" + ) + range_vars = index_args[0] + index = x.make_indexer()(range_vars) + + index = V.graph.sizevars.simplify_with_ranges(index, var_ranges) + strides = V.graph.sizevars.stride_vars(index, range_vars) + offset = V.graph.sizevars.offset_var(index, range_vars) + expected = sympy_dot(range_vars, strides) + offset + + if index != expected: + log.debug( + "convert_to_reinterpret_view failed: stride=%s offset=%s index=%s", + strides, + offset, + index, + ) + raise NotImplementedError + + return ReinterpretView( + data=x.data, + layout=FixedLayout( + device=x.get_device_or_error(), + dtype=x.get_dtype(), + size=x.get_size(), + stride=strides, + offset=offset, + is_pinned=False, + ), + ) + + @classmethod + def realize_input(cls, x: IRNode) -> IRNode: + if x is None: + return NoneAsConstantBuffer() + if isinstance(x, (Expr, sympy.logic.boolalg.Boolean, int)): + return ShapeAsConstantBuffer(expr=x) + if isinstance(x, Constant): + # We need to unset fake mode, or else the torch.tensor() call will + # turn into a FakeTensor + with _disable_current_modes(): + return V.graph.add_tensor_constant( + torch.tensor(x.value, dtype=x.get_dtype(), device=x.get_device()) + ) + if isinstance(x, ConstantBuffer): + return x + if isinstance(x, TensorBox): + return cls.realize_input(x.data) + if isinstance(x, ReinterpretView): + return ReinterpretView( + data=cls.realize_input(x.data), layout=x.get_layout() + ) + if isinstance(x, BaseView): + x.realize() + if is_storage_and_layout(x.unwrap_view()): + try: + return cls.convert_to_reinterpret_view(x) + except NotImplementedError: + pass + if isinstance(x, StorageBox): + # TODO(jansel): impose layout preference on realized buffer + x.realize() + return x + if isinstance(x, (NonTensorObj, ShapeAsConstantBuffer, OpaqueMultiOutput)): + return x + return cls.copy_input(x) + + @classmethod + def require_stride1(cls, x: IRNode) -> IRNode: + if is_storage_and_layout(x): + if len(x.get_stride()) == 0: + return x + for stride in x.get_stride(): + if stride == 1: + return x + return cls.copy_input(x) + + @classmethod + def require_strides( + cls, + x: IRNode, + order: Sequence[int] | None = None, + exact_strides: Sequence[_IntLike] | None = None, + allow_padding: bool = False, + ) -> IRNode: + """Ensure x has the requested stride order or exact strides, inserting a copy if needed.""" + if not (order is not None or exact_strides is not None): + raise AssertionError( + "Expected order is not None or exact_strides is not None" + ) + # Layout generally doesn't matter, but some consuming external ops might have requirements + if x.get_numel() in (0, 1) and not exact_strides: + return x + + # require x to have the layout + if is_storage_and_layout(x): + if isinstance(x.get_layout(), FlexibleLayout): + if order: + # If the FlexibleLayout already has the size and stride in the required order, + # freeze it to a FixedLayout by using its current size and stride. + # The behavior of using its current size and stride or the given order can be different + # if the size and stride has ambiguilty, for example for a 4D input where the iC = 1: + # size=[s0, 1, 28, 28], stride=[784, 784, 28, 1]. If the required order is [3, 0, 2, 1] (channels last), + # the current size and stride already satisfies this order. + # However by freezing it to the required order, the layout will be changed to: + # size=[s0, 1, 28, 28], stride=[784, 1, 28, 1]), which is not actually necessary. + use_current_stride_order = is_stride_order_storage_and_layout( + x, order + ) + if use_current_stride_order: + x.freeze_layout() + else: + # fix flexiblelayout to be FixedLayout with stride_order + as_storage_and_layout( + x, + freeze=True, + want_contiguous=False, + stride_order=order, + allow_padding=allow_padding, + ) + return x + else: + # If the exact_strides is given, freeze the FlexibleLayout to a FixedLayout with the exact_strides. + as_storage_and_layout( + x, + freeze=True, + want_contiguous=False, + stride_order=None, + allow_padding=allow_padding, + exact_strides=exact_strides, + ) + return x + + # When padding is allowed, check if the buffer's existing strides + # match padded versions of the requested strides (e.g. concat graph + # outputs that were already padded by ConcatKernel). + padded_exact_strides = None + if allow_padding and exact_strides: + padded_exact_strides = list( + Layout._pad_strides(exact_strides, x.get_size(), x.get_dtype()) + ) + + if isinstance(x.get_layout(), (FixedLayout, NonOwningLayout)) and ( + (order and x.get_layout().is_stride_ordered(order)) + or ( + exact_strides + and significant_strides_equal( + exact_strides, x.get_layout().stride, x.get_size() + ) + ) + ): + return ( + try_match_insignificant_strides(x, exact_strides) + if exact_strides is not None + else x + ) + # Accept already-padded buffers when padding is allowed + elif ( + padded_exact_strides is not None + and isinstance(x.get_layout(), (FixedLayout, NonOwningLayout)) + and significant_strides_equal( + padded_exact_strides, x.get_layout().stride, x.get_size() + ) + ): + return try_match_insignificant_strides(x, padded_exact_strides) + elif isinstance( + (mutation_layout := x.get_layout()), MutationLayoutSHOULDREMOVE + ): + if isinstance( + (real_layout := mutation_layout.real_layout()), FlexibleLayout + ): + raise AssertionError( + "the MutationLayoutSHOULDREMOVE's real layout shouldn't be FlexibleLayout" + ) + elif isinstance(real_layout, FixedLayout) and ( + (order and real_layout.is_stride_ordered(order)) + or ( + exact_strides + and significant_strides_equal( + exact_strides, real_layout.stride, x.get_size() + ) + ) + ): + return x + + # TODO - Storage to InputBuffer + if isinstance(x, InputBuffer) and ( + (order and x.get_layout().is_stride_ordered(order)) + or ( + exact_strides + and significant_strides_equal( + exact_strides, x.get_layout().stride, x.get_size() + ) + ) + ): + return x + if ( + isinstance(x, TensorBox) + and isinstance(x.data, BaseView) + and not isinstance(x.data, ReinterpretView) + and is_storage_and_layout(unwrap_view := x.unwrap_view()) + and hasattr(unwrap_view, "data") + and not isinstance(unwrap_view.data, ExternKernelAlloc) + ): + try: + x.data = cls.convert_to_reinterpret_view(x.data) + if order: + return cls.require_stride_order( + x, order, allow_padding=allow_padding + ) + elif exact_strides: + return cls.require_exact_strides( + x, exact_strides, allow_padding=allow_padding + ) + except NotImplementedError: + pass + + # Preserve ExpandView representation that would be lost during copy_input + # Without representation of the expand in inductor IR, in codegen we end up + # launching a grid for the full size tensor and doing redundant computation + # across expanded dims. + # TODO: could also be good to have a codegen fix to recognize overlapping elements + + expanded_dims: list[int] | None = None + orig_size = x.get_size() + if exact_strides is not None: + sizevars = V.graph.sizevars + expanded_dims = [ + i + for i in range(len(x.get_size())) + if sizevars.statically_known_equals(exact_strides[i], 0) + and sizevars.statically_known_geq(x.get_size()[i], 2) + ] + + for dim in expanded_dims: + x = torch._inductor.lowering.slice_(x, dim, 0, 1) + + if x.get_dtype().is_complex: + # Triton signature codegen has no complex pointer dtype, so avoid + # materializing complex layout constraints through a pointwise copy. + if exact_strides is not None: + layout = FlexibleLayout( + x.get_device_or_error(), x.get_dtype(), x.get_size() + ).as_exact_strides(exact_strides, allow_padding=allow_padding) + else: + if order is None: + raise AssertionError( + "Expected order is not None when exact_strides is None" + ) + layout = FlexibleLayout( + x.get_device_or_error(), x.get_dtype(), x.get_size() + ).as_stride_order(order, allow_padding=allow_padding) + + src = x + x = torch._inductor.lowering.empty_strided( + x.get_size(), + layout.stride, + dtype=x.get_dtype(), + device=x.get_device_or_error(), + ) + InplaceCopyFallback.create(x, src) + else: + # Although this is a clone, inductor is good about fusing clones into previous + # operations if they weren't realized and their layouts were flexible. + x = cls.copy_input(x) + + as_storage_and_layout( + x, + freeze=True, + want_contiguous=False, + stride_order=order, + allow_padding=allow_padding, + exact_strides=exact_strides, + ) + if ( + order + and not free_unbacked_symbols(x.get_size()) + and not free_unbacked_symbols(x.get_stride()) + ): + if not is_stride_order_storage_and_layout(x, order): + raise AssertionError( + "Expected is_stride_order_storage_and_layout(x, order)" + ) + elif expanded_dims: + if not (orig_size is not None and exact_strides is not None): + raise AssertionError( + "Expected orig_size is not None and exact_strides is not None" + ) + x = torch._inductor.lowering.expand(x, orig_size) + # the expand will sometimes may change insignificant strides, so match them back + return try_match_insignificant_strides(x, exact_strides) + + return x + + @classmethod + def require_exact_strides( + cls, x: IRNode, exact_strides: Sequence[_IntLike], allow_padding: bool = False + ) -> IRNode: + return cls.require_strides( + x, + exact_strides=[ + s.node.expr if isinstance(s, torch.SymInt) else s for s in exact_strides + ], + allow_padding=allow_padding, + ) + + @classmethod + def require_stride_order( + cls, x: IRNode, order: Sequence[int], allow_padding: bool = False + ) -> IRNode: + return cls.require_strides(x, order=order, allow_padding=allow_padding) + + @classmethod + def require_channels_last(cls, x: IRNode) -> IRNode: + return cls.require_stride_order(x, NHWC_STRIDE_ORDER) + + @classmethod + def require_channels_last_3d(cls, x: IRNode) -> IRNode: + return cls.require_stride_order(x, NHWDC_STRIDE_ORDER) + + @classmethod + def require_contiguous(cls, x: IRNode) -> IRNode: + def is_mkldnn_tensor(x: IRNode) -> bool: + try: + name = x.get_name() + except (AttributeError, NotImplementedError): + return False + + return name in V.graph.constants and V.graph.constants[name].is_mkldnn + + # TODO move this to the more proper places + if is_mkldnn_tensor(x): + return x + else: + return cls.require_exact_strides( + x, FlexibleLayout.contiguous_strides(x.get_size()) + ) + + @classmethod + def require_contiguous_strides(cls, x: IRNode) -> IRNode: + # TODO: combine this with require_contiguous after + # https://github.com/pytorch/pytorch/pull/148235 lands. + return cls.require_exact_strides( + x, FlexibleLayout.contiguous_strides(x.get_size()) + ) + + def apply_constraint(self) -> None: + pass + + def fill_non_provided_args( + self, args: Sequence[Any], kwargs: dict[str, Any] + ) -> Sequence[Any]: + # Previously, we want to maintain forward-compatibility by skipping + # default args in the serialized artifacts in fbcode. However, + # some of our shim interfaces require default values being OrderedSet. + # Discussed with Sherlock offline and we decided to allow serializing + # default args into the C++ wrapper code for now. We will refine this + # part if we see real FC requirement. More details related to FC + # can be found at: + # https://docs.google.com/document/d/1FzWm-sHYwmRi3x_g036kOxd99KaYquUsA-L5JwOn8ys/edit?usp=sharing + if not isinstance(args, Sequence): + raise AssertionError(type(args)) + if not isinstance(args, list): + args = list(args) + if not self.arg_properties: + raise AssertionError("ExternKernel.arg_properties should not be empty") + + n_args = len(args) + n_pos_args = len(self.arg_properties) + # For cpp wrapper, if some positional args are not provided, we need to check + # if they're in the kwargs or use their default value + if n_args < n_pos_args: + log.debug( + "%s has %d unprovided positional arguments. " + "Will check if they are in the keyword arguments or will use default values.", + self.op_overload, + n_pos_args - n_args, + ) + for i in range(n_args, n_pos_args): + arg_name = self.arg_properties[i]["name"] + args.append( + kwargs[arg_name] + if arg_name in kwargs + else self.arg_properties[i]["default_value"] + ) + return args + + def codegen_const_args(self, names: list[str] | None = None) -> list[str]: + if V.graph.cpp_wrapper: + result = [] + # Aten ops follow the convention that tensor args are before non-tensor args, + # in which case the following 'len(self.inputs) + i' logic works. But this + # may not be true for other ops, and if that is the case, caller needs to + # pass in a list of const arg names for arg_properties lookup. + name_to_arg_properties: dict[str, ArgProperty] | None = None + if names and self.arg_properties: + if len(self.constant_args) != len(names): + raise AssertionError( + "names passed to codegen_const_args does not match self.constant_args" + ) + name_to_arg_properties = { + name: arg + for arg in self.arg_properties + if (name := arg.get("name")) is not None + } + + for i, x in enumerate(self.constant_args): + if name_to_arg_properties is not None: + if names is None: + raise AssertionError("Expected names is not None") + prop = name_to_arg_properties.get(names[i]) + type_ = prop.get("type") if prop else None + else: + idx = len(self.inputs) + i + type_ = ( + self.arg_properties[idx].get("type") + if self.arg_properties and idx < len(self.arg_properties) + else None + ) + result.append(V.graph.wrapper_code.val_to_arg_str(x, type_)) + return result + else: + return [V.graph.wrapper_code.val_to_arg_str(a) for a in self.constant_args] + + def codegen_args(self) -> list[str]: + if V.graph.cpp_wrapper and self.op_overload is not None: + # cpp wrapper needs special logic to fill in missing args with default values + inputs = self.fill_non_provided_args( + [*self.inputs, *self.constant_args], self.kwargs + ) + # fill_non_provided_args has handled constant args, so no need to codegen for that later + need_codegen_constant_args = False + else: + inputs = self.inputs + need_codegen_constant_args = True + + args = [] + for i, x in enumerate(inputs): + if V.graph.cpp_wrapper: + if not (self.arg_properties and i < len(self.arg_properties)): + raise AssertionError( + "Invalid access to ExternKernel.arg_properties" + ) + type_ = self.arg_properties[i].get("type") + args.append(V.graph.wrapper_code.val_to_arg_str(x, type_)) + else: + args.append(V.graph.wrapper_code.val_to_arg_str(x)) + if need_codegen_constant_args: + args.extend(self.codegen_const_args()) + return args + + def get_kwargs_value(self, arg_name: str, **kwargs: Any) -> Any: + """Given an argument name, queries for values in (in order): + 1. any provided kwargs for this function. + 2. the class self.kwargs member. + 3. any available default arguments in self.allarg_properties.""" + if arg_name in kwargs: + return kwargs.get(arg_name) + if arg_name in self.kwargs: + return self.kwargs.get(arg_name) + if (arg := self.allarg_properties.get(arg_name)) is not None: + return arg.get("default_value") + raise AssertionError(f"{arg_name} not in self.allarg_properties") + + def codegen_kwargs(self, skip_out: bool = False) -> list[str]: + if V.graph.cpp_wrapper: + if self.op_overload is not None and len(self.schema_kwargs) == 0: + # All the args should have been generated by fill_non_provided_args in codegen_args + return [] + + kwargs = [] + for arg_name in self.ordered_kwargs_for_cpp_kernel: + if skip_out and arg_name == "out": + # ExternKernelOut has its own logic for inserting the out parameter + continue + + v = self.get_kwargs_value(arg_name) + if isinstance(v, Expr): + kwargs.append(v) + else: + if self.allarg_properties is None: + raise AssertionError( + "Expected self.allarg_properties is not None" + ) + type_ = self.allarg_properties.get(arg_name, {}).get("type") + kwargs.append(V.graph.wrapper_code.val_to_arg_str(v, type_)) + else: + kwargs = [ + f"{k}={V.graph.wrapper_code.val_to_arg_str(v)}" + for k, v in self.kwargs.items() + ] + return kwargs + + def get_op_name(self) -> str: + if self.fx_node is not None: + target = self.fx_node.target + op_namespace = getattr(target, "__module__", "unknown_namespace") + op_namespace = op_namespace.replace("._ops.", ".ops.") + op_namespace = op_namespace.rsplit(".", 1)[0] + op_name = f"{op_namespace}.{target}" + else: + op_name = "unknown_op" + return op_name + + def is_inplace_view(self) -> bool: + return ( + isinstance(self.op_overload, torch._ops.OpOverload) + and torch.Tag.inplace_view in self.op_overload.tags + ) + + def should_assert_dtype(self, op_name: str) -> bool: + # FakeTensor does not support quantized meta tensors today, so + # quantize_per_tensor's fake dtype intentionally remains non-quantized. + return ( + not self.is_inplace_view() + and not op_name.startswith("torch.ops.aten.quantize_per_tensor.") + and ( + self.op_overload + not in ( + torch.ops.aten.quantize_per_tensor.default, + torch.ops.aten.quantize_per_tensor.tensor_qparams, + ) + ) + ) + + def codegen_size_asserts(self, wrapper: PythonWrapperCodegen) -> None: + if not config.size_asserts: + return + if self.is_inplace_view() and not V.graph.cpp_wrapper: + return + op_name = self.get_op_name() + name = self.get_name() + if V.graph.cpp_wrapper: + # inplace_view ops (e.g. set_.source_Tensor) don't declare an + # output variable; assert on the mutated input instead. + if self.is_inplace_view(): + if not isinstance(self.inputs[0], IRNode): + raise AssertionError("Expected isinstance(self.inputs[0], IRNode)") + name = self.inputs[0].get_name() + size = V.graph.wrapper_code.codegen_shape_tuple(self.get_size()) + stride = V.graph.wrapper_code.codegen_shape_tuple(self.get_stride()) + dtype = self.get_dtype() if self.should_assert_dtype(op_name) else None + wrapper.write_assert_size_stride(name, size, stride, op_name, dtype) + + def codegen_alignment_asserts(self, wrapper: PythonWrapperCodegen) -> None: + if config.alignment_asserts and not V.graph.cpp_wrapper: + name = self.get_name() + aligned = name not in V.graph.unaligned_buffers + op_name = self.get_op_name() + if aligned: + wrapper.writeline( + f"assert_alignment({name}, {GPU_ALIGN_BYTES}, {op_name!r})" + ) + else: + wrapper.writeline( + f"# buffer {name} (op: {op_name}) is assumed to be not aligned" + ) + + def codegen_memory_tracking(self, wrapper: PythonWrapperCodegen) -> None: + """ + Track outputs of fallback operators if config.test_configs.track_memory_lifecycle + """ + if not config.test_configs.track_memory_lifecycle or V.graph.cpp_wrapper: + return + + wrapper.write_memory_track_allocation_once() + name = self.get_name() + wrapper.writeline(f"track_tensor({name}, '{name}')") + + def get_group_stride(self) -> tuple[list[Sequence[Expr]], list[Expr]]: + """ + get output sizes and strides, for template_codegen + """ + _size = self.get_size() + _stride = self.get_stride() + # iter_ranges = _size of output tensor, reduce_range = [] because no reduction + return [_size, []], _stride + + def canonicalize(self) -> tuple[Expr, Sequence[Expr]]: + """ + Manually get canonicalization of the output index + """ + # manually generate index formula for conv + sizevars = V.graph.sizevars + sizes = self.get_size() + strides = self.get_stride() + # Stride hints are only used as sort keys to determine dimension + # ordering for canonicalization, not for correctness. + strides = [sizevars.optimization_hint(x) for x in strides] + # TODO: I can't tell if the symbols here are temporary + index_vars = [sympy_index_symbol(f"d{i}") for i in range(len(sizes))] + # reorder index vars according to stride + index_order = sorted(range(len(strides)), key=strides.__getitem__, reverse=True) + lookup = {pos: idx for idx, pos in enumerate(index_order)} + order = [lookup[i] for i in range(len(lookup))] + index_vars = [index_vars[i] for i in order] + indexer = self.make_indexer() + index = indexer(index_vars) + + new_sizes, reindex, _prune = V.graph.sizevars._simplify_loops( + index_vars, sizes, [index] + ) + + # assign new variables each dimension to deal with numbering mismatches + # d0, d1, d2 could become d0, d2 -- which won't match d0, d1 + _, add_var = var_builder("c") + replacement = dict(zip(index_vars, reindex([add_var(x) for x in new_sizes]))) + + index = sympy_subs(sympy.expand(index), replacement) + return index, tuple(new_sizes) + + @cache_on_self_and_args("ExternKernel") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + # NB: It's not necessary to check regular inputs as we automatically + # have dependencies on them + maybe_get_symbols = ( + maybe_free_unbacked_symbols if unbacked_only else maybe_free_symbols + ) + r = InputsKernel.get_free_symbol_uses(self, unbacked_only) + for arg in self.constant_args: + r |= maybe_get_symbols(arg) + for arg in self.kwargs.values(): + r |= maybe_get_symbols(arg) + return r + + def __str__(self) -> str: + kernel_name = getattr(self, "python_kernel_name", None) + lines = [ + f"python_kernel_name={kernel_name!r}", + ] + lines += [ + f"{field.name}={getattr(self, field.name)}" + for field in dataclasses.fields(self) + ] + lines.append(f"origin_node={self.origin_node!r}") + return self.str_helper(lines) + + __repr__ = __str__ + + +@ir_dataclass(frozen=False) +class ExternKernelOut(ExternKernel): + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.generate_extern_kernel_out(self) + + def __init__( + self, + layout: Layout, + inputs: Sequence[IRNode], + constant_args: Sequence[Any] = (), + kwargs: dict[str, Any] | None = None, + output_view: ReinterpretView | None = None, + python_kernel_name: str | None = None, + cpp_kernel_name: str | None = None, + ordered_kwargs_for_cpp_kernel: Sequence[Any] = (), + op_overload: _OpOverloads | None = None, + ) -> None: + unwrapped_inputs = self.unwrap_storage(inputs) + if not isinstance(unwrapped_inputs, Sequence): + raise AssertionError(type(unwrapped_inputs)) + super().__init__( + None, + layout, + unwrapped_inputs, + constant_args, + kwargs or {}, + None, + python_kernel_name, + cpp_kernel_name, + ordered_kwargs_for_cpp_kernel, + op_overload, + ) + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + + def should_allocate(self) -> bool: + return True + + +class RandomSeeds(ExternKernelOut): + def __init__(self, count: int, device: torch.device) -> None: + limits = torch.iinfo(torch.int64) + super().__init__( + layout=FixedLayout( + device=device, + dtype=torch.int64, + size=[count], + ), + inputs=[], + constant_args=[limits.min, limits.max, [count]], + python_kernel_name="aten.randint.low_out", + # FIXME: Ideally we should only use at::_ops::randint_low_out::call here, + # but the signature is different from is at::randint_out. Again, + # we can simplify the code when only keeping an ABI-compatible version. + cpp_kernel_name="at::_ops::randint_low_out::call", + op_overload=aten.randint.low_out, + ) + + +class ExternKernelAlloc(ExternKernel): + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.generate_extern_kernel_alloc(self) + + def __init__( + self, + layout: OutputSpec, + inputs: Sequence[IRNode], + constant_args: Sequence[Any] = (), + kwargs: dict[str, Any] | None = None, + python_kernel_name: str | None = None, + cpp_kernel_name: str | None = None, + ordered_kwargs_for_cpp_kernel: Sequence[Any] = (), + op_overload: _OpOverloads | None = None, + ) -> None: + unwrapped_inputs = self.unwrap_storage(inputs) + if not all(isinstance(i, IRNode) for i in unwrapped_inputs): + raise AssertionError( + "Expected all(isinstance(i, IRNode) for i in unwrapped_inputs)" + ) + super().__init__( + None, + layout, + cast(Sequence[IRNode], unwrapped_inputs), + constant_args, + kwargs or {}, + None, + python_kernel_name, + cpp_kernel_name, + ordered_kwargs_for_cpp_kernel, + op_overload, + ) + # We need output buffers for generating kernel arguments in the + # abi-compatible mode, where we retrieve outputs by pass each individual + # output through the abi-compatible interface. + self.outputs: Sequence[Any] = [] + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + + def should_allocate(self) -> bool: + return False + + def apply_constraint(self) -> None: + raise NotImplementedError + + +class MutationOutput(Buffer): + """ + An output buffer that represents the mutation of a pre-existing buffer + """ + + def __init__( + self, layout: OutputSpec, mutated_node: IRNode, mutating_node: Operation + ) -> None: + super().__init__(name=None, layout=layout) + mutated_node_name = mutated_node.get_name() + V.graph.mark_buffer_mutated(mutated_node_name) + self.mutation_names = [mutated_node_name] + self.mutating_node: Operation = mutating_node + self.name = V.graph.register_buffer(self) + + def get_defining_op(self) -> Operation: + return self.mutating_node + + def get_mutation_names(self) -> Sequence[str]: + return self.mutation_names + + def should_allocate(self) -> bool: + return False + + def get_mutation_buffers(self) -> Sequence[IRNode]: + mutation_names = self.get_mutation_names() + return [ + buf + for buf in (V.graph.try_get_buffer(name) for name in mutation_names) + if buf is not None + ] + + +class OrderingBarrier(NopKernel): + """A no-op that creates a rename chain for scheduling order. + + Takes a source buffer and produces a new buffer name. The scheduler + sees this as a node with a rename (source -> self), so future readers + of the source are redirected through this barrier. + + Uses WeakDep(is_fake=True) instead of StarDep via the ``ordering_only`` + flag, avoiding lifetime extension and mark_buffer_mutated side effects. + No kernel is generated and no allocation occurs. + """ + + ordering_only = True + + def __init__(self, source_node: IRNode) -> None: + source_node.realize() + super().__init__( + name=None, + layout=NoneLayout(device=source_node.get_device()), + inputs=[source_node], + ) + self.mutation_names = [source_node.get_name()] + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + + def get_mutation_names(self) -> Sequence[str]: + return self.mutation_names + + def should_allocate(self) -> bool: + return False + + +class TMADescriptor(ExternKernel): + """ + An IR node representing a generic host-side TMA descriptor in the Triton API + Mostly useful for user-defined Triton kernels relying on host-side TMA; + but can, in principle, be used for Inductor's Triton templates, too. + + See TMADescriptorExperimental and TMADescriptorStable for the two implementations + (the old API and the new API) + """ + + # as TMA descriptors are immutable, + # we can dedup them by the input args + _CACHE: dict[Any, TMADescriptor] = {} + + @classmethod + def _create_impl( + cls, tensor: IRNode, tma_meta: tuple[str, tuple[Any, ...]] + ) -> TMADescriptor: + if len(tma_meta) != 2: + raise AssertionError("Expected len(tma_meta) == 2") + if tma_meta[0] == "experimental": + return TMADescriptorExperimental(tensor, *tma_meta[1]) + else: + if tma_meta[0] != "stable": + raise AssertionError('Expected tma_meta[0] == "stable"') + return TMADescriptorStable(tensor, *tma_meta[1]) + + @classmethod + def create( + cls, tensor: IRNode, tma_meta: tuple[str, tuple[Any, ...]] + ) -> TMADescriptor: + key = (id(tensor), tma_meta) + if key not in cls._CACHE: + cls._CACHE[key] = cls._create_impl(tensor, tma_meta) + return cls._CACHE[key] + + def __init__( + self, tensor: IRNode, inputs: Sequence[Any], constant_args: Sequence[Any] + ) -> None: + super().__init__( + None, + # link back to the underlying tensor in terms of ownership + # to avoid getting the underlying tensor deleted *before* + # the TMADescriptor node can be deleted. + NonOwningLayout( + ReinterpretView( + data=tensor, + layout=tensor.get_layout(), + ) + ), + cast(Sequence[Buffer], inputs), + tuple(constant_args), + None, + ) + + self.tensor = tensor + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.generate_tma_descriptor(self) + + def get_tensor(self) -> IRNode: + return self.tensor + + +class TMADescriptorExperimental(TMADescriptor): + """ + the new host-side TMA Descriptor API: + (the ones obtained via create_{1d,2d}_tma_descriptor calls). + + See also TMADescriptorStable for the new API. + """ + + def __init__( + self, + tensor: IRNode, + dims: list[int | torch.SymInt], + block_dims: list[int | torch.SymInt], + element_size: int | None = None, + ) -> None: + if len(dims) not in (1, 2): + raise AssertionError("Expected len(dims) in (1, 2)") + if len(dims) != len(block_dims): + raise AssertionError("Expected len(dims) == len(block_dims)") + + if element_size is None: + element_size = tensor.get_dtype().itemsize + + self.dims = dims + self.block_dims = block_dims + self.element_size = element_size + self.rank = len(self.dims) + + inputs = [tensor] + constant_args = [ + *self.dims, + *self.block_dims, + self.element_size, + ] + + super().__init__( + tensor=tensor, + inputs=inputs, + constant_args=constant_args, + ) + + +class TMADescriptorStable(TMADescriptor): + """ + the new host-side TMA descriptor API + (the ones obtained via TensorDescriptor.from_tensor). + + See also TMADescriptorExperimental for the old API. + """ + + def __init__(self, tensor: IRNode, block_shape: list[int | torch.SymInt]): + self.block_shape = block_shape + + super().__init__( + tensor=tensor, + inputs=[tensor], + constant_args=block_shape, + ) + + +class SubgraphBuffer(ExternKernel): + def __init__( + self, + layout: Layout, + input_nodes: list[Buffer], + gm: torch.fx.GraphModule, + example_inputs: list[Any], + subgraph_name: str, + config_patches: dict[str, Any] | None = None, + ): + super().__init__(None, layout, input_nodes) + self.gm = gm + self.example_inputs = example_inputs + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + + self.subgraph = V.graph.make_subgraph(self.gm, example_inputs, subgraph_name) + + if not is_node_sequence(self.inputs): + raise AssertionError("Expected is_node_sequence(self.inputs)") + sym_inputs = get_symbolic_inputs(self.inputs) + + for sym_inp in sym_inputs: + self.subgraph.graph_inputs[sym_inp.name] = sym_inp + self.subgraph.graph_input_names.append(sym_inp.name) + + self.sym_inputs = [sym_var.name for sym_var in sym_inputs] + + import torch._inductor.config as inductor_config + + with V.set_graph_handler(self.subgraph): + # Base config: don't autotune Triton, but allow other optimizations + base_patches = { + "max_autotune": False, + "max_autotune_gemm": False, + "max_autotune_gemm_backends": "ATEN", + } + # Merge with user config_patches (e.g., coordinate_descent_tuning) + merged_patches: dict[str, Any] = {**base_patches, **(config_patches or {})} + with inductor_config.patch(merged_patches): + self.subgraph.run(*self.example_inputs) + + # Tag all operations in subgraph with config_patches + # These will be applied during kernel codegen via SIMD scheduling + if config_patches: + for op in self.subgraph.operations: + op.set_config_patches(config_patches.copy()) + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + class CodegenGraph: + def __init__(self, graph: GraphLowering): + self.graph = graph + self.name = graph.name + + if not is_node_sequence(self.inputs): + raise AssertionError("Expected is_node_sequence(self.inputs)") + outer_inputs = [t.codegen_reference() for t in self.inputs] + + wrapper.codegen_subgraph_with_flattened_outputs( + CodegenGraph(self.subgraph), + [*self.sym_inputs, *outer_inputs], + [self.name], + ) + + +class UserDefinedTritonKernel(ExternKernel): + """ + A user-defined triton kernel (e.g. via @triton.jit). + """ + + def get_kernel_and_metadata(self) -> tuple[Kernel, Any, list[str], list[str]]: + from triton.runtime.autotuner import Autotuner + + from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table + + kernel = kernel_side_table.get_kernel(self.kernel_idx) + configs = [] + restore_value_args: list[str] = [] + reset_to_zero_args: list[str] = [] + if isinstance(kernel, Autotuner): + # https://github.com/triton-lang/triton/pull/5083 + # changes kernel.restore_idx to kernel.restore_value + if hasattr(kernel, "restore_idx"): + restore_value_args.extend( + kernel.fn.arg_names[i] for i in kernel.restore_idx + ) + else: + if not hasattr(kernel, "restore_value"): + raise AssertionError('Expected hasattr(kernel, "restore_value")') + restore_value_args.extend(kernel.restore_value) + + if hasattr(kernel, "reset_idx"): + for i in kernel.reset_idx: + reset_to_zero_args.append(kernel.fn.arg_names[i]) + else: + if not hasattr(kernel, "reset_to_zero"): + raise AssertionError('Expected hasattr(kernel, "reset_to_zero")') + reset_to_zero_args.extend(kernel.reset_to_zero) + + configs = kernel.configs + kernel = kernel.fn + + return kernel, configs, restore_value_args, reset_to_zero_args + + def can_fuse_epilogue(self) -> bool: + """ + For kernels like + + @triton.jit + def add_kernel(in_ptr0, in_ptr1, out_ptr, n_elements, BLOCK_SIZE: tl.constexpr): + pid = tl.program_id(0) + offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + mask = offs < n_elements + x = tl.load(in_ptr0 + offs, mask=mask) + y = tl.load(in_ptr1 + offs, mask=mask) + tl.store(out_ptr + offs, x + y, mask=mask) + + @torch.compile + def fn(a, b): + out = torch.empty_like(a) + grid = (triton.cdiv(a.numel(), 1024),) + add_kernel[grid](a, b, out, a.numel(), BLOCK_SIZE=1024) + return out.relu() + + We can potentially fuse the relu epilogue into the add_kernel. + We do this by pruning the `out` tensor allocation and directly writing the relu-output. + """ + + if not config.epilogue_fusion_user_defined_triton_kernel: + return False + + if not self.arg_accesses.can_fuse_epilogue: + return False + + # We achieve fusion by parsing the original src into a python AST, + # then identify the expr containing the original value written via tl.store(). + # We generate an expr for the value after the epilogue and replace that into the tl.store. + # So far we only support the simple case where there is a single tl.store in the kernel. + if len(self.kernel_stores.stores) != 1: + return False + + # Only fuse if the mutated arg is originally an "empty" tensor. + # This is because we don't know exactly which element of that tensor is being written to. + # If the kernel only writes to a subset of the tensor, then we only apply the epilogue to that subset. + # In these edge cases, our fusion is only correct if the original tensor is empty, + # where the semantics is that content values are UB, and we can rely on the fact that `epilogue(UB) == UB`. + if len(self.mutable_args) != 1: + raise AssertionError("Expected len(self.mutable_args) == 1") + if not isinstance(self.mutable_args[0], TensorBox): + return False + if not isinstance(self.mutable_args[0].data, StorageBox): + return False + if not isinstance(self.mutable_args[0].data.data, ComputedBuffer): + return False + if not isinstance(self.mutable_args[0].data.data.data, Pointwise): + return False + if not all(r == 0 for r in self.mutable_args[0].data.data.data.ranges): + return False + + return True + + @override + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + return self._codegen(wrapper, epilogue_fusion=None) + + def codegen_with_epilogue_fusion( + self, wrapper: PythonWrapperCodegen, epilogue_fusion: tuple[ComputedBuffer, str] + ) -> None: + """ + epilogue_fusion: (fused epilogue node, modified kerel src code) + """ + return self._codegen(wrapper, epilogue_fusion) + + def _codegen( + self, + wrapper: PythonWrapperCodegen, + epilogue_fusion: tuple[ComputedBuffer, str] | None, + ) -> None: + """Overrides the parent member. + See https://github.com/pytorch/pytorch/issues/151692""" + + from torch._inductor.utils import triton_version_uses_attrs_dict + + ( + kernel, + configs, + restore_value_args, + reset_to_zero_args, + ) = self.get_kernel_and_metadata() + + # For an epilogue containing a cast, the output arg in kwargs must point to the + # epilogue's output so that the compiled signature uses the correct dtype. + kernel_kwargs = self.kwargs + epilogue_out_override: dict[str, Any] = {} + if epilogue_fusion: + if len(self.arg_accesses.read_writes.writes) != 1: + raise AssertionError( + f"expected one write, got {len(self.arg_accesses.read_writes.writes)}" + ) + mutable_arg_name = next(iter(self.arg_accesses.read_writes.writes)).name + epilogue_computed_buffer, _ = epilogue_fusion + kernel_kwargs = {**self.kwargs, mutable_arg_name: epilogue_computed_buffer} + epilogue_out_override = {mutable_arg_name: epilogue_computed_buffer} + + ( + new_name, + triton_meta, + inductor_meta, + extra_launch_args, + ) = wrapper.define_user_defined_triton_kernel( + kernel, + configs, + kernel_kwargs, + restore_value_args, + reset_to_zero_args, + self.grid, + epilogue_fusion, + self.launch_kwargs, + ) + named_args = { + k: self.get_kwargs_value(k) for k in self.ordered_kwargs_for_cpp_kernel + } + named_args.update(epilogue_out_override) + + arg_names = [p.name for p in kernel.params] # type: ignore[attr-defined] + constexprs = [p.num for p in kernel.params if p.is_constexpr] # type: ignore[attr-defined] + constexpr_names = OrderedSet(arg_names[i] for i in constexprs) + + args: list[Any] = [] + arg_types: list[Any] = [] + raw_keys_filtered: list[Any] = [] + raw_args_filtered: list[Any] = [] + for name, arg in itertools.chain( + named_args.items(), zip(itertools.repeat(""), extra_launch_args) + ): + if name in constexpr_names and triton_version_uses_attrs_dict(): + # see #160000 - we don't pass in constexpr args to speed up runtime. + continue + raw_keys_filtered.append(name) + raw_args_filtered.append(arg) + if isinstance(arg, IRNode): + args.append(arg.codegen_reference()) + arg_types.append(arg.get_dtype()) + elif isinstance(arg, (int, float, bool, Expr)): + args.append(arg) + arg_types.append(type(arg)) + elif name in constexpr_names: + # insert a dummy value for constexpr args of unsupported type + # constexprs will end up getting baked into the kernel at compile time + args.append(-1) + arg_types.append(int) + elif arg is None: + """ + Filter out None args. + + see https://github.com/pytorch/pytorch/issues/115344 + + Two cases for a None arg: + 1. The arg is already tl.constexpr, so leave it in + 2. The arg is not tl.constexpr so we have to remove it + """ + if triton_version_uses_attrs_dict(): + args.append(-1) + arg_types.append(int) + else: + raw_keys_filtered.pop() + raw_args_filtered.pop() + else: + raise NotImplementedError(f"Unsupported arg type: {type(arg)}: {arg}") + + self.codegen_comment(wrapper, new_name) + wrapper.generate_kernel_call( + new_name, + args, + arg_types=arg_types, + raw_args=raw_args_filtered, + raw_keys=raw_keys_filtered, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + triton=True, + device=self.get_device(), + original_fxnode_name=self.fx_node.name, + ) + + @cache_on_self_and_args("UserDefinedTritonKernel") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + # add unbacked symbols used in the grid to the ones used + # in the kwargs (the latter is generated by ExternKernel) + return super().get_free_symbol_uses(unbacked_only) | get_free_symbols( + self.grid, unbacked_only + ) + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def __init__( + self, + *, + kernel_idx: int, + grid: Any, + tma_descriptor_metadata: dict[str, Any], + kernel_args: dict[str, Any], + launch_kwargs: tuple[str, ...], + ) -> None: + inputs: list[IRNode] = [] + kwargs: dict[str, IRNode] = {} + constant_args: list[IRNode] = [] + + for k, v in kernel_args.items(): + if isinstance(v, TensorBox): + t = InputsKernel.unwrap_storage_for_input(self.realize_input(v)) + if k in tma_descriptor_metadata: + t = TMADescriptor.create(t, tma_descriptor_metadata[k]) + inputs.append(t) + kwargs[k] = t + else: + constant_args.append(v) + kwargs[k] = v + + if len(inputs) == 0: + raise AssertionError("Expected len(inputs) != 0") + self.device = inputs[0].get_device() + + if not isinstance(inputs, Sequence): + raise AssertionError(type(inputs)) + super().__init__( + None, + NoneLayout(device=self.device), + inputs, + tuple(constant_args), + kwargs, + ) + self.kernel_idx = kernel_idx + self.grid = grid + self.launch_kwargs = launch_kwargs + + kernel, configs, _, _ = self.get_kernel_and_metadata() + + # If we are autotuning, not all arguments will be passed + if not hasattr(kernel, "arg_names"): + raise AssertionError('Expected hasattr(kernel, "arg_names")') + self.ordered_kwargs_for_cpp_kernel = [ + arg for arg in kernel.arg_names if arg in kernel_args + ] + + from torch._higher_order_ops.triton_kernel_wrap import ( + identify_accessed_tensors, + identify_triton_stores, + ) + + autotuned_kwargs = configs[0].kwargs if len(configs) > 0 else {} + + import ast + + # pyrefly: ignore [missing-attribute] + self.kernel_src = kernel.src + self.kernel_ast = ast.parse(self.kernel_src) + self.kernel_stores = identify_triton_stores(self.kernel_src) + self.kernel_args = kernel_args + # names in `arg_accesses.read_writes` are names of formal arguments in the kernel's prototype + self.arg_accesses = identify_accessed_tensors( + kernel, + {**kernel_args, **autotuned_kwargs}, + tma_descriptor_metadata, + ) + + # Filter to only tensor args: with Triton 3.7+, ordered_arg_names + # includes scalars, so writes may reference non-tensor args like SymInts. + self.mutable_args = [ + kernel_args[key.name] + for key in self.arg_accesses.read_writes.writes + if isinstance(kernel_args.get(key.name), TensorBox) + ] + + self.mutation_outputs = [ + MutationOutput(NoneLayout(device=self.device), buf, self) + for buf in self.mutable_args + ] + V.graph.register_operation(self) + + def get_outputs(self) -> list[Buffer]: + return list(self.mutation_outputs) + + def get_device(self) -> torch.device | None: + return self.device + + +class InplaceBernoulliFallback(ExternKernel): + """ + This needs to be a custom class to handle mutation properly + """ + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + if not all(isinstance(t, IRNode) for t in self.inputs): + raise AssertionError( + "Expected all(isinstance(t, IRNode) for t in self.inputs)" + ) + (x,) = (cast(IRNode, t).codegen_reference() for t in self.inputs) + + if V.graph.cpp_wrapper: + # Inductor doesn't really support aten Generator, so the Generator kwarg is always NULL here, + # which needs to be explicitly generated for cpp wrapper + wrapper.writeline( + f"{self.get_kernel_name()}({x}, {', '.join(map(repr, self.constant_args))}, NULL){wrapper.ending}" + ) + else: + wrapper.writeline( + f"{self.get_kernel_name()}({x}, {', '.join(map(repr, self.constant_args))}){wrapper.ending}" + ) + + def should_allocate(self) -> bool: + return False + + def get_mutation_names(self) -> Sequence[str]: + return [self.input_name(0)] + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def __init__( + self, op_overload: _OpOverloads, x: IRNode, *constant_args: Any + ) -> None: + super().__init__( + None, + NoneLayout(device=x.get_device()), + self.unwrap_storage([x]), + constant_args, + op_overload=op_overload, + ) + V.graph.mark_buffer_mutated(x.get_name()) + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + + +# Used to deal with torch.complex types +class InplaceCopyFallback(ExternKernel): + """ + This needs to be a custom class to handle mutation properly + """ + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + (dst, src, non_blocking) = self.codegen_args() + wrapper.codegen_device_copy(src, dst, non_blocking) + + def should_allocate(self) -> bool: + return False + + def get_mutation_names(self) -> Sequence[str]: + return [self.input_name(0)] + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def __init__( + self, + layout: OutputSpec, + inputs: Sequence[IRNode], + constant_args: Sequence[Any], + ) -> None: + super().__init__( + None, + layout, + inputs, + constant_args, + python_kernel_name="aten.copy_", + cpp_kernel_name="aoti_torch_copy_", + ) + V.graph.mark_buffer_mutated(inputs[0].get_name()) + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + + @classmethod + def create( + cls, dst: IRNode, src: IRNode, non_blocking: bool = False + ) -> InplaceCopyFallback: + inputs = [cls.realize_input(t) for t in [dst, src]] + constant_args = (non_blocking,) + result = InplaceCopyFallback( + NoneLayout(device=dst.get_device()), + inputs, + constant_args, + ) + return result + + +class MutatingFirstArgExternKernel(ExternKernel): + """ + This needs to be a custom class to handle mutation properly + """ + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + if not is_node_sequence(self.inputs): + raise AssertionError("Expected is_node_sequence(self.inputs)") + argrefs = [ + *(t.codegen_reference() for t in self.inputs), + *map(repr, self.constant_args), + ] + wrapper.writeline( + f"{self.get_kernel_name()}({', '.join(argrefs)}){wrapper.ending}" + ) + + def should_allocate(self) -> bool: + return False + + def get_mutation_names(self) -> Sequence[str]: + return [self.input_name(0)] + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def has_side_effects(self) -> bool: + return True + + +class ResizeStorageBytes(MutatingFirstArgExternKernel): + def __init__(self, variable: IRNode, new_size: int) -> None: + if not isinstance(new_size, int): + raise AssertionError("TODO: dynamic shapes") + super().__init__( + None, + NoneLayout(device=variable.get_device()), + self.unwrap_storage([variable]), + constant_args=(new_size,), + ) + V.graph.mark_buffer_mutated(variable.get_name()) + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + self.python_kernel_name = "inductor_ops.resize_storage_bytes_" + self.cpp_kernel_name = "torch::inductor::resize_storage_bytes_" + if not isinstance(variable, (BaseView, StorageBox, TensorBox)): + raise AssertionError(type(variable)) + V.graph.never_reuse_buffers.add(variable.data.get_name()) + + +class SetSourceTensorKernel(ExternKernelAlloc): + def __init__(self, self_tensor: IRNode, storage_tensor: IRNode) -> None: + storage_tensor = self.realize_input(storage_tensor) + storage_tensor.freeze_layout() + super().__init__( + storage_tensor.get_layout(), + [self_tensor, storage_tensor], + python_kernel_name="torch.ops.aten.set_.source_Tensor", + op_overload=torch.ops.aten.set_.source_Tensor, + ) + if not isinstance(self_tensor, (BaseView, StorageBox, TensorBox)): + raise AssertionError(type(self_tensor)) + V.graph.never_reuse_buffers.add(self_tensor.data.get_name()) + V.graph.never_reuse_buffers.add(storage_tensor.get_name()) + V.graph.never_reuse_buffers.add(self.get_name()) + device = storage_tensor.get_device() + self.mutation_outputs = [ + MutationOutput(NoneLayout(device=device), self_tensor, self), + MutationOutput(NoneLayout(device=device), storage_tensor, self), + ] + + def get_inputs_that_alias_output(self) -> Sequence[str]: + return [self.input_name(0), self.input_name(1)] + + +class ShallowCopyDataKernel(ExternKernelAlloc): + def __init__(self, self_tensor: IRNode, storage_tensor: IRNode) -> None: + storage_tensor = self.realize_input(storage_tensor) + storage_tensor.freeze_layout() + super().__init__( + storage_tensor.get_layout(), + [self_tensor, storage_tensor], + python_kernel_name="torch.ops.aten.shallow_copy_data_", + op_overload=torch.ops.aten.set_.source_Tensor, + ) + if not isinstance(self_tensor, (BaseView, StorageBox, TensorBox)): + raise AssertionError(type(self_tensor)) + V.graph.never_reuse_buffers.add(self_tensor.data.get_name()) + V.graph.never_reuse_buffers.add(storage_tensor.get_name()) + V.graph.never_reuse_buffers.add(self.get_name()) + device = storage_tensor.get_device() + self.mutation_outputs = [ + MutationOutput(NoneLayout(device=device), self_tensor, self), + MutationOutput(NoneLayout(device=device), storage_tensor, self), + ] + + def get_inputs_that_alias_output(self) -> Sequence[str]: + return [self.input_name(0), self.input_name(1)] + + +class ScatterFallback(ExternKernel): + """ + This needs to be a custom class to handle mutation properly. + This class handles both aten.scatter_ and aten.scatter_reduce_. + It also handle the case `src` being a scalar properly. + """ + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.generate_scatter_fallback(self) + + def should_allocate(self) -> bool: + return False + + def get_mutation_names(self) -> list[str]: + inp = self.inputs[0] + if not isinstance(inp, IRNode): + raise AssertionError("Expected isinstance(inp, IRNode)") + return [inp.get_name()] + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def __init__( + self, + op_overload: _OpOverloads, + x: IRNode, + dim: int, + index: IRNode, + src: IRNode, + *, + reduce: str | None = None, + include_self: bool = True, + ) -> None: + self.src_is_tensor = isinstance(src, TensorBox) + + constant_args: tuple[Any, ...] + if self.src_is_tensor: + tensors = [self.realize_input(t) for t in [x, index, src]] + constant_args = (dim,) + else: + tensors = [self.realize_input(t) for t in [x, index]] + constant_args = (dim, src) + + super().__init__( + None, + NoneLayout(device=x.get_device()), + self.unwrap_storage(tensors), + constant_args, + {"reduce": reduce, "include_self": include_self}, + python_kernel_name=str(op_overload), + ordered_kwargs_for_cpp_kernel=["reduce", "include_self"], + op_overload=op_overload, + ) + V.graph.mark_buffer_mutated(x.get_name()) + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + + +class IndexPutFallback(ExternKernel): + """ + This needs to be a custom class to handle mutation and indices properly + """ + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.generate_index_put_fallback(self) + + def should_allocate(self) -> bool: + return False + + def get_mutation_names(self) -> Sequence[str]: + return [self.input_name(0)] + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def __init__( + self, + op_overload: torch._ops.OpOverload, + x: IRNode, + indices: list[Any], + values: Sequence[Any], + accumulate: Any, + ) -> None: + self.indices = indices + valid_indices = [i for i in indices if i is not None] + # pyrefly: ignore [bad-argument-type] + tensors = [self.realize_input(x) for x in [x, values, *valid_indices]] + cpp_kernel_name = "aoti_torch_index_put_out" + super().__init__( + None, + NoneLayout(device=x.get_device()), + self.unwrap_storage(tensors), + (accumulate,), + python_kernel_name="aten.index_put_", + cpp_kernel_name=cpp_kernel_name, + op_overload=op_overload, + ) + V.graph.mark_buffer_mutated(self.input_name(0)) + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + + +class DeviceCopy(ExternKernelOut): + @classmethod + def create(cls, x: IRNode, device: torch.device, non_blocking: bool) -> IRNode: + x_device = x.get_device() + if x_device is None: + raise AssertionError("Expected x_device is not None") + if ( + not x.is_extern() + # Can not apply this optimization if x has been mutated + and try_get_name(x) not in V.graph.mutated_buffers + and all(r in V.graph.constants for r in x.get_read_names()) + and not config.aot_inductor.use_runtime_constant_folding + ): + if V.graph.cpp_wrapper: + # Even if x is promoted to be a device constant, we still need to + # register device info to construct the correct CppWrapper class later + V.graph.add_device_info(device) + V.graph.add_device_info(x_device) + return x.constant_to_device(device) + + V.graph.add_device_info(device) + V.graph.add_device_info(x_device) + developer_warning("DeviceCopy in input program") + constant_args = (non_blocking,) + # Device Copy should keep the same layout as input + x = ExternKernel.require_contiguous(x) + stride = None + if x.get_size(): + # x.get_stride() may be unimplemented if x's size is empty + stride = x.get_stride() + is_destination_pinned = ( + is_gpu(x_device.type) and device.type == "cpu" and non_blocking + ) + is_source_pinned = ( + x_device.type == "cpu" and is_gpu(device.type) and non_blocking + ) + if is_source_pinned and is_storage_and_layout(x): + x.get_layout().is_pinned = True + return DeviceCopy( + FixedLayout( + device, + x.get_dtype(), + x.get_size(), + stride, + is_pinned=is_destination_pinned, + ), + [cls.realize_input(x)], + constant_args, + ) + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + args = self.codegen_args() + if len(args) != 2: + raise AssertionError("Expected len(args) == 2") + if self.output_view: + wrapper.codegen_device_copy( + args[0], self.output_view.codegen_reference(), args[1] + ) + else: + wrapper.codegen_device_copy(args[0], self.codegen_reference(), args[1]) + if isinstance(self.layout, Layout) and self.layout.is_pinned: + wrapper.sync_d2h_copy(self.get_name()) + + +class DynamicSelectStorageOffset(ExternKernel): + """ + The result of computing a dynamic selection index is determined as follows: when the index in the + select operation is unbacked, the actual index calculation is ambiguous for negative indices + (index + size) versus non-negative indices (just index). To resolve this, we allocate an unbacked + SymInt to represent the storage offset and decompose the select operation into a call to as_strided, + computing the storage offset at runtime with this node. + """ + + def get_reads(self) -> OrderedSet[Dep]: + return OrderedSet() + + def should_allocate(self) -> bool: + return False + + def __init__( + self, + unbacked_offset_symbol: sympy.Symbol, + index: sympy.Symbol, + base_offset: sympy.Symbol | int, + base_dim_stride: sympy.Symbol | int, + size: sympy.Symbol | int, + clamp: bool, + ) -> None: + super().__init__(None, NoneLayout(device=torch.device("cpu")), []) + # This node codegen the following: + # unbacked_offset_symbol = base_offset + base_dim_stride * (index if index >=0 else index + size) + self.unbacked_offset_symbol = unbacked_offset_symbol + self.index = index + self.base_offset = base_offset + self.base_dim_stride = base_dim_stride + self.size = size + self.clamp = clamp + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet([self.unbacked_offset_symbol]) + + @cache_on_self_and_args("DynamicSelectStorageOffset") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return ( + get_free_symbols(self.index, unbacked_only) + .union(get_free_symbols(self.size, unbacked_only)) + .union(get_free_symbols(self.base_offset, unbacked_only)) + .union(get_free_symbols(self.base_dim_stride, unbacked_only)) + ) + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.codegen_dynamic_select_index(self, clamp=self.clamp) + + +class DynamicSliceSize(ExternKernel): + """ + Computes the output size of a slice call, handling the correct semantics in codegen. + We do this for flexible handling for unbacked indices (to not data-dependent error). + + Slicing has 4 semantics for indices, i.e. x[start:] could be: + 1) start < -x.size(0) -> x[0:] # negative out-of-bounds + 2) start in [-x.size(0), 0) -> x[x.size(0) + start:] # negative slicing + 3) start in [0, x.size(0)) -> x[start:] # standard slicing + 4) start >= x.size(0) -> empty slice # positive out-of-bounds + + If the appropriate semantics are known beforehand, the output size is computed based on + the start & end indices. If not (with unbacked indices), a new unbacked symbol is created + to represent the output size, and codegen handles computing the correct case. + """ + + def get_reads(self) -> OrderedSet[Dep]: + return OrderedSet() + + def should_allocate(self) -> bool: + return False + + def __init__( + self, + unbacked_size_symbol: sympy.Symbol, + start: sympy.Symbol | int, + end: sympy.Symbol | int, + step: sympy.Symbol | int, + size: sympy.Symbol | int, + ): + super().__init__(None, NoneLayout(device=torch.device("cpu")), []) + # This node codegen + self.unbacked_size_symbol = unbacked_size_symbol + self.start = start + self.end = end + self.step = step + self.size = size + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet([self.unbacked_size_symbol]) + + @cache_on_self_and_args("DynamicSliceSize") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return ( + get_free_symbols(self.start, unbacked_only) + .union(get_free_symbols(self.end, unbacked_only)) + .union(get_free_symbols(self.size, unbacked_only)) + .union(get_free_symbols(self.step, unbacked_only)) + ) + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.codegen_dynamic_slice_size(self) + + +class DynamicScalar(ExternKernel): + """ + The result of a call to aten._local_scalar_dense. + """ + + def get_reads(self) -> OrderedSet[Dep]: + return OrderedSet() + + def should_allocate(self) -> bool: + return False + + def __init__( + self, sym: sympy.Symbol, keypath: pytree.KeyPath, data: IRNode + ) -> None: + data.realize() + super().__init__( + None, NoneLayout(device=torch.device("cpu")), self.unwrap_storage([data]) + ) + self.sym = sym + self.keypath = keypath + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet([self.sym]) + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.codegen_dynamic_scalar(self) + + +class AssertScalar(ExternKernel): + """ + The result of a call to aten._assert_scalar + """ + + def get_reads(self) -> OrderedSet[Dep]: + return OrderedSet() + + def should_allocate(self) -> bool: + return False + + def __init__(self, scalar: SympyBoolean, msg: str) -> None: + super().__init__( + # Buffer(name, layotu) + None, + NoneLayout(device=torch.device("cpu")), + # InputsKernel(inputs) + [], + ) + self.scalar = scalar + self.msg = msg + + def has_side_effects(self) -> bool: + return True + + @cache_on_self_and_args("AssertScalar") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return get_free_symbols(self.scalar, unbacked_only) + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + if not config.scalar_asserts: + return + # NB: It is EXTREMELY important not to simplify the scalar under assertion here, + # because simplify is done with respect to runtime asserts. So if you have + # "u0 == 0" in the runtime asserts, if you subsequently try to + # simplify(u0 == 0), you will get True (because we've already runtime assert'ed + # that it's true). But we're code generating the actual runtime assert here!! + symbol = next(iter(self.get_free_symbol_uses(unbacked_only=False))) + if V.graph.fx_wrapper: + # TODO fix + pass + elif V.graph.cpp_wrapper: + symbol_str = f"std::to_string({symbol})" + sizevar = V.graph.wrapper_code.codegen_cpp_sizevar( + self.scalar, simplify=False + ) + # TODO: when we start compiling in C++20, annotate with [[unlikely]]. + wrapper.writeline( + f'if (!({sizevar})) {{ throw std::runtime_error("Expected {self.msg} but received " + {symbol_str}); }}' + ) + else: + sizevar = V.graph.wrapper_code.codegen_python_sizevar( + self.scalar, simplify=False + ) + wrapper.writeline(f"if not ({sizevar}):") + wrapper.writeline(f" raise RuntimeError({repr(self.msg)})") + # No one should ever use this buffer, but for uniformity + # define the variable and assign it None + wrapper.writeline(f"{self.get_name()} = None") + + +@ir_dataclass(frozen=False) +class ExternKernelNode: + name: str + node: export_schema.Node + + +class FallbackKernel(ExternKernelAlloc): + """ + A class that represents a fallback kernel for handling operators that are not + directly support by inductor. It currently supports functional ops, view ops, + inplace aten ops, and mutating ops that are auto-functionalizable. + """ + + def __init__( + self, + layout: OutputSpec, + kernel: _OpOverloads, + tensor_args: Sequence[IRNode], + nontensor_args: Sequence[Any], + unflatten_args: Callable[..., Any], + kwargs: dict[str, Any] | None = None, + *, + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None = None, + ) -> None: + super().__init__( + layout, + tuple(tensor_args), + tuple(nontensor_args), + op_overload=kernel, + ) + + self.use_runtime_dispatch = False + self.unbacked_bindings = unbacked_bindings or {} + + if not isinstance( + kernel, (torch._ops.OpOverload, torch._ops.HigherOrderOperator) + ): + raise AssertionError( + f"Fails to create FallbackKernel for {kernel}: {type(kernel)} not supported" + ) + self.op_overload = kernel + self.unflatten_args = unflatten_args + self.kwargs = {} if kwargs is None else kwargs + if self.python_kernel_name is None: + raise AssertionError("Expected self.python_kernel_name is not None") + V.graph.warn_fallback(self.python_kernel_name) + + # args that are aliased + self.alias_names: list[str] = [] + # args that are mutated AND returned from the op + self.mutation_names: list[str] = [] + + if isinstance(self.op_overload, torch._ops.HigherOrderOperator): + # We assume here that HOPs with FallbackKernel are functional. + # This may not always be true! HOPs must individually opt-in to + # FallbackKernel, so please check this if you opt-in. + return + + if "_c10d_functional" in self.op_overload.name(): + # _c10d_functional kernels are lowered into _CollectiveKernel which + # derives from FallbackKernel for the cpp codegen. The kernels + # don't pass the can_auto_functionalize check, but their mutation + # is handled properly by _CollectiveKernel. + return + + schema = self.op_overload._schema + + # NOTE: [FallbackKernel supported operators] + # We only support three types of operators: + # - functional ops + # - view ops + # - inplace aten ops + # - mutating ops that are auto-functionalizable. That is, + # the operator may mutate any number of inputs, but its outputs + # may not alias any of the inputs. + # + # The unsupported cases usually do not show up here (because + # AOTAutograd functionalized them away); the only way for an in-place + # op to show up here is if a lowering or pass introduced it. + if torch._library.utils.mutates_and_returns_first_arg(self.op_overload): + self.mutation_names.append(tensor_args[0].get_name()) + # Record aliasing relationship so memory planning doesn't wrongly + # reuse its storage. + self.alias_names.append(tensor_args[0].get_name()) + return + + def has_functionalize_impl(op: torch._ops.OpOverload) -> bool: + return torch._C._dispatch_has_kernel_for_dispatch_key( + op.name(), torch._C.DispatchKey.Functionalize + ) or ( + hasattr(op, "py_kernels") + and torch._C.DispatchKey.Functionalize in op.py_kernels + ) + + if ( + schema.is_mutable + and not can_auto_functionalize(self.op_overload) + and not has_functionalize_impl(self.op_overload) + ): + raise NotImplementedError( + f"NYI: Can't generate FallbackKernel for {self.op_overload}" + ) + + args, kwargs = self.unflatten_args(self.inputs, self.constant_args) + + def handle_aliasing_and_mutation(info: torch._C.Argument, arg: Any) -> None: + # Assertions to make sure we didn't mismatch args + if isinstance(info.type, torch.ListType): + if not isinstance(arg, (list, tuple)): + raise AssertionError(type(arg)) + if library_utils.is_tensor_like_type(info.type): + # PyTorch also accepts None and scalar types for args marked as "Tensor". + # We're not going to check all of them here. + if isinstance(arg, (tuple, list)): + raise AssertionError("Expected not isinstance(arg, (tuple, list))") + + if arg is None: + return + if info.alias_info is None: + return + + def add_alias(t: IRNode) -> None: + self.alias_names.append(t.get_name()) + if info.alias_info is None: + raise AssertionError("Expected info.alias_info is not None") + if info.alias_info.is_write: + self.mutation_outputs.append( + MutationOutput(NoneLayout(device=t.get_device()), t, self) + ) + + def add_alias_if_graph_buffer(t: Any) -> None: + if t is None: + return + if isinstance(t, (Number, Expr, *SymTypes)): + # The dispatcher accepts Python scalars for some Tensor + # schema arguments by boxing them into temporary scalar tensors. + # Those temporaries cannot alias or mutate graph buffers. + return + if not isinstance(t, IRNode): + raise AssertionError(type(t)) + add_alias(t) + + if library_utils.is_tensorlist_like_type(info.type): + if arg is not None: + for optional_tensor_arg in arg: + add_alias_if_graph_buffer(optional_tensor_arg) + else: + if not library_utils.is_tensor_like_type(info.type): + raise AssertionError( + "Expected library_utils.is_tensor_like_type(info.type)" + ) + + add_alias_if_graph_buffer(arg) + + for info, arg in torch._library.utils.zip_schema(schema, args, kwargs): + handle_aliasing_and_mutation(info, arg) + + def get_read_writes(self) -> dependencies.ReadWrites: + read_writes = super().get_read_writes() + + if self.op_overload is torch._prims.rng_prims.graphsafe_run_with_rng_state: + for arg in self.constant_args: + if isinstance(arg, GeneratorState): + read_writes = read_writes.with_read( + dependencies.StarDep(arg.get_name()) + ) + + return read_writes + + def codegen_unbacked_symbol_defs(self, wrapper: PythonWrapperCodegen) -> None: + return wrapper.codegen_unbacked_symbol_defs_for_outputs( + self.get_name(), + self.codegen_outputs(), + getattr(self, "unbacked_bindings", None), + ) + + def codegen_outputs(self) -> Sequence[Any]: + if self.outputs: + return self.outputs + if isinstance(self.layout, Layout): + return [self] + return self.mutation_outputs + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + if unbacked_bindings := getattr(self, "unbacked_bindings", None): + resolved = resolve_unbacked_bindings( + V.graph.sizevars.shape_env, unbacked_bindings + ) + if resolved is None: + raise AssertionError("Expected resolved is not None") + return OrderedSet(resolved.keys()) + else: + return OrderedSet() + + def codegen_args(self) -> list[str]: + @dataclasses.dataclass + class Shim: + ref: Any + + def __repr__(self) -> str: + return self.ref + + if not is_node_sequence(self.inputs): + raise AssertionError("Expected is_node_sequence(self.inputs)") + tensor_args = [Shim(x.codegen_reference()) for x in self.inputs] + args, kwargs = self.unflatten_args(tensor_args, self.constant_args) + if V.graph.cpp_wrapper and isinstance(self.op_overload, torch._ops.OpOverload): + args = self.fill_non_provided_args(args, kwargs) + args = [ + V.graph.wrapper_code.val_to_arg_str(x, param.real_type) + for param, x in zip(self.op_overload._schema.arguments, args) + ] + else: + args = [V.graph.wrapper_code.val_to_arg_str(x) for x in args] + + # let self.codegen_kwargs handle kwargs + self.kwargs.update(kwargs) + return args + + @staticmethod + def find_device( + tensor_args: Sequence[IRNode] | None, example_output: Sequence[Any] + ) -> Any: + non_torch_bind_tensor_args = ( + [t for t in tensor_args if not isinstance(t, TorchBindObject)] + if tensor_args + else None + ) + if non_torch_bind_tensor_args: + if not tensor_args: + raise AssertionError("Expected tensor_args") + devices = [arg.get_device() for arg in tensor_args if arg.get_device()] + return devices[0] + if isinstance(example_output, torch.Tensor): + return example_output.device + if isinstance( + example_output, (torch._C.ScriptObject, FakeScriptObject) + ) or is_custom_class_obj(example_output): + return torch.device("cpu") + if isinstance(example_output, (list, tuple)): + device_set = OrderedSet( + # pyrefly: ignore [bad-argument-type] + FallbackKernel.find_device(None, x) + for x in example_output + ) + # Remove None + devices = [device for device in device_set if device] + if len(devices) == 1: + return devices[0] + if not devices: + return None + for device in devices: + if not isinstance(device, torch.device): + raise AssertionError("Expected isinstance(device, torch.device)") + if is_gpu(device.type): + return device + return devices[0] + return None + + def has_side_effects(self) -> bool: + from torch._library.utils import is_impure + + # Note: We don't pass args/kwargs here because they're IRNodes, not actual values + # The check is done on the op_overload itself + return is_impure(self.op_overload) # pyrefly: ignore[bad-argument-type] + + def get_inputs_that_alias_output(self) -> Sequence[str]: + if not isinstance( + self.op_overload, (torch._ops.OpOverload, torch._ops.HigherOrderOperator) + ): + raise AssertionError( + f"Fails to create FallbackKernel for {self.op_overload}: " + f"{type(self.op_overload)} not supported" + ) + + # See [Note: FallbackKernel supported operators]: for a mutating + # op that is auto-functionalizable, its outputs does NOT + # alias any of the inputs. + if ( + not isinstance(self.op_overload, torch._ops.HigherOrderOperator) + and "_c10d_functional" not in self.op_overload.name() + and self.op_overload._schema.is_mutable + and can_auto_functionalize(self.op_overload) + ): + return [] + else: + return self.alias_names + + def get_mutation_names(self) -> Sequence[str]: + if len(self.mutation_names) > 1: + raise AssertionError("Expected len(self.mutation_names) <= 1") + return self.mutation_names + + def export_extern_kernel_node(self): # type: ignore[no-untyped-def] + """ + ProxyExecutor Design Note + We export the ExternFallbackNodes (for custom ops) into a serialized file + and run it with a host side proxy executor to address the ABI problem + This is currently only implemented for fbcode. Eventually, we will also make this work for OSS. + Detailed design doc can be found at + https://docs.google.com/document/d/1wC4DOZFaYym2t1Esz0X5yxlLI3RDnSiyRbUus3bkJ64/edit?usp=sharing + """ + log.debug( + "Extern kernel node added for node %s with target %s.", + self.get_name(), + self.op_overload, + ) + + if not isinstance(self, FallbackKernel): + raise AssertionError(type(self)) + args, kwargs = self.unflatten_args(self.inputs, self.constant_args) + args = self.fill_non_provided_args(args, kwargs) + ordered_kwargs = [ + self.get_kwargs_value(key, **kwargs) + for key in self.ordered_kwargs_for_cpp_kernel + ] + target = self.op_overload + + if not V.graph.aot_mode: + # No need to serialize in the cpp wrapper JIT mode + return [*args, *ordered_kwargs] + + serializer = GraphModuleSerializer(None, []) # type: ignore[arg-type] + named_arguments = serializer.serialize_inputs(target, args, kwargs) + + # serialize_outputs + def handle_single_output( + return_type: torch.TensorType | torch.ListType | torch.JitType, + output: IRNode | Sequence[IRNode], + ) -> export_schema.Argument: + if isinstance(return_type, (torch.TensorType, torch.NoneType)): + # For single Tensor or None + out = output + if isinstance(output, (list, tuple)): + if len(output) != 1: + raise AssertionError("Expected len(output) == 1") + out = output[0] + if isinstance(return_type, torch.TensorType): + if not isinstance(out, IRNode): + raise AssertionError("Expected isinstance(out, IRNode)") + return export_schema.Argument.create( + as_tensor=export_schema.TensorArgument(name=out.get_name()) + ) + else: # NoneType + if out is not None: + raise AssertionError("Expected out is None") + return export_schema.Argument.create(as_none=True) + elif isinstance(return_type, torch.ListType) and isinstance( + return_type.getElementType(), torch.TensorType + ): + if not isinstance(output, Sequence): + raise AssertionError(type(output)) + # For single TensorList + return export_schema.Argument.create( + as_tensors=[ + export_schema.TensorArgument(name=out.get_name()) + for out in output + ] + ) + elif isinstance(return_type, torch.OptionalType) and isinstance( + return_type.getElementType(), torch.TensorType + ): + # For OptionalTensor + if output is None: + return export_schema.Argument.create( + as_optional_tensor=export_schema.OptionalTensorArgument.create( + as_none=True + ) + ) + else: + if not isinstance(output, IRNode): + raise AssertionError("Expected isinstance(output, IRNode)") + return export_schema.Argument.create( + as_optional_tensor=export_schema.OptionalTensorArgument.create( + as_tensor=export_schema.TensorArgument( + name=output.get_name() + ) + ) + ) + elif isinstance(return_type, torch.IntType): + return export_schema.Argument.create(as_int=output) + else: + raise RuntimeError(f"Unsupported return type {type(return_type)}") + + if isinstance(target, torch._higher_order_ops.torchbind.CallTorchBind): + returns = target.schema(args[0], args[1]).returns + else: + returns = target._schema.returns # type: ignore[union-attr] + if len(returns) == 1: + # NOTE: [special handling of all_reduce_coalesced_'s return value] + # all_reduce_coalesced_ return a list of tensors via self.mutation_outputs + outputs = self.codegen_outputs() + return_type = returns[0].real_type + output_arguments = [handle_single_output(return_type, outputs)] + else: + # For tuple returns, e.g "-> (Tensor, Tensor)" or "-> (Tensor, Tensor[])" + # Not generating output args for self.mutation_outputs + output_arguments = [ + handle_single_output( + return_schema.real_type, # type: ignore[attr-defined] + output, + ) + for return_schema, output in zip(returns, self.outputs) + ] + + if self.op_overload is None: + raise AssertionError("Expected self.op_overload is not None") + metadata = {} + if ( + isinstance(self.op_overload, torch._ops.OpOverload) + and custom_ops._maybe_get_opdef(self.op_overload) is not None + ): + metadata["torch_library_custom_op"] = "1" + + node = ExternKernelNode( + name=self.get_name(), + node=export_schema.Node( + target=self.op_overload.name(), + inputs=named_arguments, + outputs=output_arguments, + metadata=metadata, + ), + ) + + V.extern_kernel_nodes.append(node) + + return [*args, *ordered_kwargs] + + @override + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + """Overrides the parent member. + See https://github.com/pytorch/pytorch/issues/151692""" + kernel = self.op_overload + if kernel is None: + raise AssertionError("Expected kernel is not None") + if kernel.namespace == "aten": + # Aten Fallback Ops + if not isinstance(kernel, torch._ops.OpOverload): + raise AssertionError(type(kernel)) + if V.graph.cpp_wrapper: + from torchgen.aoti.fallback_ops import inductor_fallback_ops + + if str(kernel) not in inductor_fallback_ops: + # C shim v2 is torchgen-ed, which should cover all aten ops. + # If you do hit a missed op, please update fallback_ops.py. + log.warning( + "%s is missing a c-shim implementation, using proxy executor as fallback", + kernel, + ) + self.use_runtime_dispatch = True + elif kernel.namespace == "_quantized": + # Internal Quantized Fallback Ops + if not isinstance(kernel, torch._ops.OpOverload): + raise AssertionError(type(kernel)) + elif V.graph.cpp_wrapper: + # For non-aten OpOverload, i.e. custom ops + # If the op is in custom_ops_to_c_shims, generate direct function call + self.use_runtime_dispatch = ( + kernel not in config.aot_inductor.custom_ops_to_c_shims + ) + + # Handle the special case where a complex number is input to a C-shim kernel for + # a scalar input. The torchgen'ed shim API will use type "double", which is + # incompatible with complex numbers, forcing a fallback to runtime dispatch. + if ( + V.graph.cpp_wrapper + and isinstance(kernel, torch._ops.OpOverload) + and not self.use_runtime_dispatch + ): + + def is_number(t: torch.JitType) -> bool: + if isinstance(t, torch.OptionalType): + return is_number(t.getElementType()) + return isinstance(t, torch.NumberType) + + # Using unflatten_args is a bit of a hack, but all the complex arguments we + # care about are in self.constant_args, and calling unflatten_args puts them + # in the correct order without triggering codegen. + args, kwargs = self.unflatten_args(self.inputs, self.constant_args) + # Append kwarg values to args. ordered_kwargs_for_cpp_kernel is guaranteed + # to be set, since this is an OpOverload kernel. + args_iter = itertools.chain( + args, + ( + self.get_kwargs_value(k, **kwargs) + for k in self.ordered_kwargs_for_cpp_kernel + ), + ) + self.use_runtime_dispatch = any( + isinstance(v, complex) and is_number(a.real_type) + for v, a in zip(args_iter, kernel._schema.arguments) + ) + + self.codegen_comment(wrapper) + if self.use_runtime_dispatch: + exported_args = self.export_extern_kernel_node() + if self.python_kernel_name is None: + raise AssertionError("Expected self.python_kernel_name is not None") + if self.op_overload is None: + raise AssertionError("Expected self.op_overload is not None") + + wrapper.generate_fallback_kernel_with_runtime_lookup( + self.get_name(), + self.python_kernel_name, + lambda: [*self.codegen_args(), *self.codegen_kwargs()], + self.op_overload, + exported_args, + # NOTE: [special handling of all_reduce_coalesced_'s return value] + self.codegen_outputs(), + ) + else: + wrapper.generate_fallback_kernel(self) + + self.codegen_unbacked_symbol_defs(wrapper) + if isinstance(self.layout, Layout): + self.codegen_size_asserts(wrapper) + self.codegen_alignment_asserts(wrapper) + self.codegen_memory_tracking(wrapper) + + @staticmethod + def tensor_to_layout(output: torch.Tensor) -> FixedLayout: + is_pinned = False + try: + is_pinned = output.is_pinned() + except RuntimeError: + # dispatch not implemented + pass + return FixedLayout( + output.device, + output.dtype, + convert_shape_to_inductor(output.size()), + convert_shape_to_inductor(output.stride()), + is_pinned=is_pinned, + ) + + @classmethod + def _maybe_realize_symm_mem_args( + cls, kernel: torch._ops.OpOverload, *args: Any, **kwargs: Any + ) -> None: + """Realize symm_mem args as comm buffers based on registry metadata.""" + from torch._library.simple_registry import singleton + + qualname = kernel.__qualname__ + entry = singleton.get(qualname) + if entry is None or not entry.symm_mem_args.is_registered(): + return + + from .comm_lowering import can_realize_as_comm_buffer, realize_as_comm_buffer + + symm_mem_args = entry.symm_mem_args.get() + if symm_mem_args is None: + return + + from torch.fx.operator_schemas import normalize_function + + normalized = normalize_function( + kernel, args, kwargs, normalize_to_only_use_kwargs=True + ) + if normalized is None: + log.warning( + "Failed to normalize arguments for symm_mem realization: %s", + qualname, + ) + return + + _, all_args = normalized + + group_name = all_args.get("group_name") + if group_name is None: + return + + for arg_name in symm_mem_args: + arg_value = all_args.get(arg_name) + tensors, _ = pytree.tree_flatten(arg_value) + for t in tensors: + if not isinstance(t, TensorBox): + continue + if can_realize_as_comm_buffer(t, CommBufferType.SYMM_MEM): + realize_as_comm_buffer(t, CommBufferType.SYMM_MEM, group_name) + else: + log.warning( + "Failed to realize %s as a symmetric memory buffer for %s", + arg_name, + qualname, + ) + + @classmethod + def create(cls, kernel: _OpOverloads, *args: Any, **kwargs: Any) -> FallbackKernel: + """Create an instance of FallbackKernel from an _OpOverloads""" + fake_incorrect_kernels = (aten._fused_moving_avg_obs_fq_helper_functional,) + if kernel not in fake_incorrect_kernels: + context = cast(AbstractContextManager[None], V.graph.fake_mode) + else: + context = nullcontext() + + with context: + result = cls.process_kernel(kernel, *args, **kwargs) + example_output = result.example_output + tensor_args = result.tensor_args + non_tensor_args = result.non_tensor_args + unflatten_args = result.unflatten_args + unbacked_bindings = result.unbacked_bindings + + # For ops with registered symm_mem args, realize those args as + # symmetric memory buffers before creating the FallbackKernel. + if isinstance(kernel, torch._ops.OpOverload): + cls._maybe_realize_symm_mem_args(kernel, *args, **kwargs) + + # Try to lower single output functional custom ops to their out-variant. + if ( + isinstance(kernel, torch._ops.OpOverload) + and not torch._library.utils.is_builtin(kernel) + and isinstance(example_output, torch.Tensor) + ): + from torch._library._out_variant import ( + _is_functional, + get_out_arg_names, + lookup_manual_out_variant, + to_out_variant, + ) + + out_op = None + if _is_functional(kernel._schema): + out_op = to_out_variant(kernel) + if out_op is None: + out_op = lookup_manual_out_variant(kernel) + + if out_op is not None and len(get_out_arg_names(out_op)) == 1: + layout = cls.tensor_to_layout(example_output) + return ExternKernelOut( # type: ignore[return-value] + layout=layout, + inputs=list(tensor_args), + constant_args=list(non_tensor_args), + kwargs=kwargs, + python_kernel_name=_make_out_variant_kernel_name(out_op), + op_overload=out_op, + ) + + # We need this extra check for input alignment since the example + # inputs we created are always aligned. + has_unaligned_input = any(is_unaligned(arg) for arg in tensor_args) + + device = cls.find_device(tensor_args, example_output) + + # Default to CPU for torchbind methods or HOPs that don't produce tensors + if not device and ( + isinstance(kernel, torch._higher_order_ops.torchbind.CallTorchBind) + or kernel is torch.ops.higher_order.print + ): + device = torch.device("cpu") + + def create_direct_output(output: torch.Tensor) -> FallbackKernel: + if not device: + raise AssertionError("Not sure where to find device info") + packed = cls( + cls.tensor_to_layout(output), + kernel, + tensor_args, + non_tensor_args, + unflatten_args, + kwargs=kwargs, + unbacked_bindings=unbacked_bindings, + ) + if ( + config.assume_unaligned_fallback_output + or has_unaligned_input + or not tensor_is_aligned(output) + ): + V.graph.unaligned_buffers.add(packed.get_name()) + return packed + + # Try multi-output .out() lowering for custom ops with the out tag. + if ( + isinstance(kernel, torch._ops.OpOverload) + and not torch._library.utils.is_builtin(kernel) + and not V.graph.cpp_wrapper + and device + ): + out_result = ExternKernelMultiOut.try_create( + kernel, + example_output, + device, + tensor_args, + non_tensor_args, + unflatten_args, + kwargs, + unbacked_bindings=unbacked_bindings, + has_unaligned_input=has_unaligned_input, + ) + if out_result is not None: + return out_result # type: ignore[return-value] + + if example_output is None: + packed = cls( + NoneLayout(device=device), + kernel, + tensor_args, + non_tensor_args, + unflatten_args, + kwargs=kwargs, + unbacked_bindings=unbacked_bindings, + ) + + elif isinstance(example_output, torch.Tensor): + return create_direct_output(example_output) + + else: + if not device: + raise AssertionError("Not sure where to find device info") + packed = cls( + MultiOutputLayout(device=device), + kernel, + tensor_args, + non_tensor_args, + unflatten_args, + kwargs=kwargs, + unbacked_bindings=unbacked_bindings, + ) + + def generate_output(output: Any, indices: list[tuple[Any, int]]) -> Any: + if isinstance(output, (list, tuple)): + return type(output)( + generate_output(output[i], indices + [(type(output), i)]) + for i in range(len(output)) + ) + elif isinstance(output, dict): + return { + key: generate_output(val, indices + [(type(output), key)]) + for key, val in output.items() + } + elif isinstance(output, torch.Tensor): + buf = MultiOutput( + cls.tensor_to_layout(output), + packed, + indices, + ) + if ( + config.assume_unaligned_fallback_output + or has_unaligned_input + or not tensor_is_aligned(output) + ): + V.graph.unaligned_buffers.add(buf.name) # type: ignore[arg-type] + return buf + elif isinstance(output, int): + return output + elif isinstance(output, torch.SymInt): + return output.node.expr + elif isinstance( + output, (torch._C.ScriptObject, FakeScriptObject) + ) or is_custom_class_obj(output): + return OpaqueMultiOutput( + NoneLayout(device=device), + packed, + indices, + output, + ) + else: + if output is not None: + raise AssertionError( + f"FallbackKernel output type {type(output)} is not supported" + ) + return None + + outputs = generate_output(example_output, []) + if isinstance(outputs, (list, tuple)): + packed.outputs = outputs + elif isinstance(outputs, dict): + packed.outputs = tuple(outputs) + else: + packed.outputs = [outputs] + + return outputs + + +@ir_dataclass(frozen=False) +class ComplexView(FallbackKernel): + """View a complex number as two dtyped numbers or vice versa""" + + def should_allocate(self) -> bool: + return False + + def get_inputs_that_alias_output(self) -> Sequence[str]: + # Signal to codegen that our output buffer isn't safe to reuse + return [self.input_name(0)] + + def __init__( + self, + layout: OutputSpec, + kernel: _OpOverloads, + tensor_args: Sequence[IRNode], + nontensor_args: Sequence[Any], + unflatten_args: Callable[..., Any], + *, + kwargs: dict[str, Any] | None = None, + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None = None, + ) -> None: + super().__init__( + layout, + kernel, + tensor_args, + nontensor_args, + unflatten_args, + kwargs=kwargs, + unbacked_bindings=unbacked_bindings, + ) + + +class MemoryCheckKernel(FallbackKernel): + """ + Custom kernel for memory checking that generates direct function calls + + TODO - the custom op was erroring with str inputs. should be able to custom op directly. + """ + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + """Override codegen to write direct function call""" + # Extract our arguments from nontensor_args + wrapper.write_memory_track_allocation_once() + alive_list, dead_list, is_final_step = self.constant_args + + alive_repr = repr(alive_list) + dead_repr = repr(dead_list) + if is_final_step: + wrapper.writeline( + "# note: don't currently distinguish between buffers returned and dealloc'd in last step" + ) + call = f"check_memory_step(allocated={alive_repr}, freed={dead_repr}, is_final_step={is_final_step})" + else: + call = f"check_memory_step(allocated={alive_repr}, freed={dead_repr})" + wrapper.writeline(call) + + +@ir_dataclass +class MultiOutputLayout(OutputSpec): + device: torch.device + + def get_device(self) -> torch.device | None: + return self.device + + +class MultiOutput(ExternKernel): + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.codegen_multi_output(self) + if not self.skip_size_stride_alignment_checks: + self.codegen_size_asserts(wrapper) + self.codegen_alignment_asserts(wrapper) + + def __init__( + self, + layout: OutputSpec, + input: IRNode, + indices: list[tuple[Any, ...]], + skip_size_stride_alignment_checks: bool = False, + ) -> None: + super().__init__(None, layout, [input], ()) + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + self.indices = indices + self.skip_size_stride_alignment_checks = skip_size_stride_alignment_checks + + @cache_on_self_and_args("MultiOutput") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + input_node = self.inputs[0] + if not isinstance(input_node, IRNode): + raise AssertionError(input_node) + return input_node.get_free_symbol_uses(unbacked_only) + + def should_allocate(self) -> bool: + return len(self.inputs) == 1 and ( + isinstance(self.inputs[0], CppTemplateBuffer) # Grouped GEMM + ) + + def get_inputs_that_alias_output(self) -> Sequence[str]: + return [ + inp.get_name() + for inp in self.inputs + if isinstance(inp, FallbackKernel) + and len(inp.get_inputs_that_alias_output()) > 0 + ] + + def get_read_writes(self) -> dependencies.ReadWrites: + # Reads: StarDep on parent (we don't know which elements of the + # packed output we index into — conservative is correct). + reads: OrderedSet[dependencies.Dep] = OrderedSet() + for inp in self.inputs: + if isinstance(inp, IRNode): + reads.add(dependencies.StarDep(inp.get_name())) + + # Writes: build proper MemoryDep from our FixedLayout so the + # scheduler can match our write with downstream epilogue reads. + # Normalize using the same policy as SchedulerNode so that the + # index expressions are directly comparable during fusion checks. + name = self.get_name() + indexer = self.get_layout().make_indexer() + + def dummy(index: Sequence[Any], rindex: Sequence[Any]) -> Any: + if len(rindex) != 0: + raise AssertionError("Expected len(rindex) == 0") + return ops.store(name, indexer(index), "fake") + + device = self.get_device() + should_normalize = ( + not config.loop_ordering_after_fusion + or device is None + or not is_gpu(device.type) + ) + write_rw = dependencies.extract_read_writes( + dummy, self.get_size(), (), normalize=should_normalize + ) + return dependencies.ReadWrites( + reads=reads, + writes=write_rw.writes, + index_exprs=OrderedSet(), + ) + + +class OpaqueMultiOutput(MultiOutput): + """MultiOutput for opaque objects.""" + + def __init__( + self, + layout: OutputSpec, + input: IRNode, + indices: list[tuple[Any, ...]], + opaque_value: Any, + ) -> None: + super().__init__(layout, input, indices, skip_size_stride_alignment_checks=True) + self.opaque_example_value = opaque_value + + @property # type: ignore[override] + def dtype(self) -> Never: + raise AttributeError("OpaqueMultiOutput has no dtype") + + def wrap_for_lowering(self) -> OpaqueMultiOutput: + return self + + def get_read_writes(self) -> dependencies.ReadWrites: + reads: OrderedSet[dependencies.Dep] = OrderedSet() + for inp in self.inputs: + if isinstance(inp, IRNode): + reads.add(dependencies.StarDep(inp.get_name())) + writes: OrderedSet[dependencies.Dep] = OrderedSet( + [dependencies.StarDep(self.get_name())] + ) + return dependencies.ReadWrites( + reads=reads, + writes=writes, + index_exprs=OrderedSet(), + ) + + +class AllocatingMultiOutput(MultiOutput): + """MultiOutput with Inductor-controlled allocation for .out() variant ops. + + Overrides should_allocate()=True so Inductor allocates the output buffer, + and skips tuple-indexing codegen since .out() writes directly into these buffers. + """ + + def should_allocate(self) -> bool: + return True + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + if not self.skip_size_stride_alignment_checks: + self.codegen_size_asserts(wrapper) + self.codegen_alignment_asserts(wrapper) + + +def _make_out_variant_kernel_name(out_op: torch._ops.OpOverload) -> str: + """Build fully-qualified kernel name for an out-variant op.""" + ns = out_op.namespace + op_name = out_op._schema.name.split("::")[1] + overload = out_op._overloadname + return f"torch.ops.{ns}.{op_name}.{overload}" + + +class ExternKernelMultiOut(FallbackKernel): + """Multi-output .out() variant lowering. + + Subclass of FallbackKernel that emits .out() calls with pre-allocated + output buffers. Uses AllocatingMultiOutput child nodes for each output. + """ + + out_arg_names: list[str] + out_variant_output_nodes: list[AllocatingMultiOutput] + + def __init__( + self, + *args: Any, + out_op: torch._ops.OpOverload, + out_arg_names: list[str], + **kwargs: Any, + ) -> None: + super().__init__(*args, **kwargs) + self.out_arg_names = out_arg_names + self.out_variant_output_nodes = [] + self.python_kernel_name = _make_out_variant_kernel_name(out_op) + self.op_overload = out_op + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + self.codegen_comment(wrapper) + wrapper.generate_extern_kernel_multi_out(self) + + @classmethod + def try_create( + cls, + kernel: torch._ops.OpOverload, + example_output: Any, + device: torch.device, + tensor_args: Sequence[IRNode], + non_tensor_args: Sequence[Any], + unflatten_args: Callable[..., Any], + kwargs: dict[str, Any] | None, + *, + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None = None, + has_unaligned_input: bool = False, + ) -> Sequence[AllocatingMultiOutput] | None: + """Create an ExternKernelMultiOut if the op has a matching .out() variant.""" + from torch._library._out_variant import ( + _is_functional, + get_out_arg_names, + to_out_variant, + ) + + if not _is_functional(kernel._schema): + return None + + if not isinstance(example_output, (tuple, list)): + return None + + out_op = to_out_variant(kernel) + if out_op is None: + return None + + out_arg_names = get_out_arg_names(out_op) + if not all(isinstance(t, torch.Tensor) for t in example_output): + return None + if len(example_output) != len(out_arg_names): + return None + + packed = cls( + MultiOutputLayout(device=device), + kernel, + tensor_args, + non_tensor_args, + unflatten_args, + kwargs=kwargs, + unbacked_bindings=unbacked_bindings, + out_op=out_op, + out_arg_names=out_arg_names, + ) + + outputs: list[AllocatingMultiOutput] = [] + for i, tensor_out in enumerate(example_output): + layout = FixedLayout( + device=tensor_out.device, + dtype=tensor_out.dtype, + size=[*tensor_out.shape], + stride=[*tensor_out.stride()], + ) + multi_out = AllocatingMultiOutput( + layout=layout, + input=packed, + indices=[(type(example_output), i)], + ) + if ( + config.assume_unaligned_fallback_output + or has_unaligned_input + or not tensor_is_aligned(tensor_out) + ): + V.graph.unaligned_buffers.add(multi_out.name) # type: ignore[arg-type] + outputs.append(multi_out) + + packed.out_variant_output_nodes = outputs + packed.outputs = outputs + + if isinstance(example_output, tuple): + return tuple(outputs) # type: ignore[return-value] + return list(outputs) + + +# We just use a normal dataclass for MutableBox/TensorBox/StorageBox since +# they're mainly lowering-time constructs that we expect to mutate and such. +@dataclasses.dataclass +class MutableBox(IRNode): + """ + TensorBox / StorageBox allow in-place mutation of Tensors + """ + + data: IRNode + + def has_exceeded_max_reads(self) -> bool: + return self.data.has_exceeded_max_reads() + + def get_device(self) -> torch.device | None: + return self.data.get_device() + + def make_loader(self) -> Callable[[Sequence[Expr]], OpsValue]: + return self.data.make_loader() + + def make_indexer(self) -> Callable[[Sequence[Expr]], Expr]: + return self.data.make_indexer() + + def get_stride(self) -> Sequence[_IntLike]: + return self.data.get_stride() + + def get_name(self) -> str: + return self.data.get_name() + + def has_large_inner_fn(self, threshold: int | None = None) -> bool: + return self.data.has_large_inner_fn(threshold) + + def mark_reuse(self, users: int, *, graph_reuse: bool = True) -> None: + return self.data.mark_reuse(users, graph_reuse=graph_reuse) + + def realize_hint(self) -> None: + return self.data.realize_hint() + + def unwrap_view(self) -> IRNode: + return self.data.unwrap_view() + + def is_input_buffer(self) -> bool: + return self.data.is_input_buffer() + + def freeze_layout(self) -> None: + return self.data.freeze_layout() + + def freeze_layout_with_stride_order( + self, order: Sequence[int], allow_padding: bool = False + ) -> None: + return self.data.freeze_layout_with_stride_order(order, allow_padding) + + def freeze_layout_with_fill_order(self, order: Sequence[int]) -> None: + return self.data.freeze_layout_with_fill_order(order) + + def freeze_layout_with_same_order(self, stride: Sequence[_IntLike]) -> None: + return self.data.freeze_layout_with_same_order(stride) + + def freeze_layout_with_exact_strides( + self, exact_strides: Sequence[_IntLike], allow_padding: bool = False + ) -> None: + return self.data.freeze_layout_with_exact_strides(exact_strides, allow_padding) + + def get_read_writes(self) -> dependencies.ReadWrites: + return self.data.get_read_writes() + + def get_reads(self) -> OrderedSet[Dep]: + return self.data.get_reads() + + def num_reads(self) -> int: + return self.data.num_reads() + + def get_storage_numel(self) -> _IntLike: + return self.data.get_storage_numel() + + def get_reduction_type(self) -> str | None: + return self.data.get_reduction_type() + + def get_reduction_size(self) -> Sequence[Expr]: + return self.data.get_reduction_size() + + def is_extern(self) -> bool: + return self.data.is_extern() + + def is_no_op(self) -> bool: + return self.data.is_no_op() + + def constant_to_device(self, device: torch.device) -> IRNode: + return self.data.constant_to_device(device) + + def get_mutation_names(self) -> Sequence[str]: + return self.data.get_mutation_names() + + def get_operation_name(self) -> str: + return self.data.get_operation_name() + + def get_inputs_that_alias_output(self) -> Sequence[str]: + return self.data.get_inputs_that_alias_output() + + def realize(self) -> str | None: + return self.data.realize() + + @cache_on_self_and_args("MutableBox") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return self.data.get_free_symbol_uses(unbacked_only) + + def get_read_names(self) -> OrderedSet[str]: + return self.data.get_read_names() + + def get_defining_op(self) -> Operation | None: + return self.data.get_defining_op() + + def codegen_reference(self, writer: IndentedBuffer | None = None) -> str: + return self.data.codegen_reference(writer) + + @property + def layout(self) -> OutputSpec: + # we intentionally call get_output_spec (rather than get_layout) since Buffer.layout is an OutputSpec + return self.data.get_output_spec() + + def get_layout(self) -> Layout: + return self.data.get_layout() + + def get_output_spec(self) -> OutputSpec: + return self.data.get_output_spec() + + def get_size(self) -> Sequence[Expr]: + return self.data.get_size() + + @property + def dtype(self) -> torch.dtype: + return self.data.dtype + + def __str__(self) -> str: + if isinstance(self.data, MutableBox): + line0 = f"{type(self).__name__}({type(self.data).__name__}(" + endl = "))" + inner = self.data.data + else: + line0 = f"{type(self).__name__}(" + inner = self.data + endl = ")" + + lines = [ + line0, + indent(str(inner)), + endl, + ] + return "\n".join(lines) + + __repr__ = __str__ + + +class TensorBox(MutableBox): + @overload + @staticmethod + def create(data: ShapeAsConstantBuffer) -> ShapeAsConstantBuffer: ... + @overload + @staticmethod + def create(data: IRNode) -> TensorBox: ... + + @staticmethod + def create(data: IRNode): + if isinstance(data, ShapeAsConstantBuffer): + return data + return TensorBox(StorageBox(data)) + + +class StorageBox(MutableBox): + """ + StorageBox allow in-place mutation of Tensors + """ + + def is_input_buffer(self) -> bool: + if isinstance(self.data, (InputBuffer, ReinterpretView)): + return self.data.get_name() in V.graph.graph_inputs + return False + + def is_module_buffer(self) -> bool: + return ( + isinstance(self.data, (ConstantBuffer)) + and self.data.get_name() in V.graph.constants + ) + + def realize(self) -> str | None: + if IRNode.is_realized_node(self.data): + return self.data.get_name() + + if not isinstance(self.data, (Pointwise, Reduction, Scan, Sort)): + raise AssertionError(type(self.data)) + origin_node = self.data.get_origin_node() + traceback = self.data.get_traceback() + device = self.data.get_device() + if device is None: + raise AssertionError("Expected device is not None") + + self.data = ComputedBuffer( + name=None, + layout=FlexibleLayout( + device=device, + dtype=self.data.get_dtype(), + size=self.data.get_size(), + is_pinned=False, + ), + data=self.data, + ) + self.data.name = V.graph.register_buffer(self.data) + V.graph.register_operation(self.data) + self.data.origins = self.origins + self.data.origin_node = origin_node + self.data.traceback = traceback + self.data.stream_idx = self.data.data.stream_idx + self.data.mempool = self.data.data.mempool + return self.data.name + + def realize_hint(self) -> None: + """ + Called on buffers we expect to be forced to realize later. + """ + if ( + isinstance(self.data, (Pointwise, Reduction)) + and self.data.inner_fn_opcount().nontrivial_read_count > 1 + ): + self.realize() + + def has_accumulated_enough_reads_by_size(self, threshold: int) -> bool: + from torch._inductor.utils import is_nonfreeable_buffers + + size_of_reads = [ + V.graph.get_dep_size_hint(dep) + for dep in self.get_reads() + if not is_nonfreeable_buffers(dep) + ] + if not size_of_reads: + return False + total_size = sum(size_of_reads) + max_size = max(size_of_reads) + min_size = min(size_of_reads) + return ( + total_size >= threshold + and total_size / max_size >= 2 + and max_size == min_size + ) + + def has_exceeded_max_reads(self) -> bool: + realize_acc_reads_threshold = config.realize_acc_reads_threshold + if realize_acc_reads_threshold is None: + if is_cpu(self.data): + realize_acc_reads_threshold = config.realize_cpu_acc_reads_threshold + else: + realize_acc_reads_threshold = ( + config._realize_acc_reads_threshold_default + ) + else: + if not isinstance(realize_acc_reads_threshold, int): + raise AssertionError( + f"expected int realize_acc_reads_threshold, got {type(realize_acc_reads_threshold)}" + ) + return isinstance(self.data, Pointwise) and ( + self.num_reads() > realize_acc_reads_threshold + or self.has_large_inner_fn() + or ( + config.realize_acc_reads_size_threshold is not None + and self.has_accumulated_enough_reads_by_size( + config.realize_acc_reads_size_threshold + ) + ) + ) + + def should_realize_on_reuse(self, users: int, *, graph_reuse: bool = True) -> bool: + """ + A heuristic to decide if we should realize a tensor + that is used multiple times. + """ + if users > 1 and isinstance(self.data, (Pointwise, Reduction)): + opcount = self.data.inner_fn_opcount() + if "inline_asm_elementwise" in opcount.used_ops: + return True + if is_cpu(self.data): + # Heuristic for realizing reused result of heavy ops on cpu + heavy_ops = [ + "exp", + "log", + "log10", + "log1p", + "log2", + "sigmoid", + "tanh", + ] + if any(x in opcount.used_ops for x in heavy_ops): + return True + realize_threshold = self.data.get_realize_opcount_threshold() + if ( + isinstance(self.data, Pointwise) + and graph_reuse + and users > config.realize_opusers_threshold + and opcount.num_ops > max(0, realize_threshold - 2) + ): + return True + if self.has_large_inner_fn(): + return True + return graph_reuse and self.num_reads() > config.realize_reads_threshold + return False + + def mark_reuse(self, users: int, *, graph_reuse: bool = True) -> None: + if self.should_realize_on_reuse(users, graph_reuse=graph_reuse): + self.realize() + + def num_reads(self) -> int: + return self.data.num_reads() + + +@ir_dataclass(frozen=False) +class Subgraph(IRNode): + name: str + graph_module: torch.fx.GraphModule + inductor_config_patches: dict[str, Any] | None = None + graph: GraphLowering | None = None + + +def _has_aliased_buffers(buffers: Sequence[IRNode]) -> bool: + buffers = [ + buffer.unwrap_view() if isinstance(buffer, ReinterpretView) else buffer + for buffer in buffers + ] + # assuming the same buffer is represented by the same IRNode object + return len(OrderedSet(id(buffer) for buffer in buffers)) < len(buffers) + + +@ir_dataclass(frozen=False) +class InvokeSubgraph(ExternKernel): + """ + Ir node for the invoke_subgraph HOP. + """ + + subgraph: Subgraph | None = None + operands: Sequence[IRNode] | None = None + outputs: Sequence[IRNode] | None = None + + def __init__( + self, subgraph: Subgraph, operands: Sequence[IRNode], layout: MultiOutputLayout + ) -> None: + super().__init__( + name=None, + layout=layout, + inputs=operands, + ) + self.subgraph = subgraph + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + + def get_subgraphs(self) -> list[Subgraph]: + return [self.subgraph] if self.subgraph else [] + + @classmethod + def create( + cls, subgraph: Subgraph, *operands: IRNode + ) -> list[ShapeAsConstantBuffer | NoneAsConstantBuffer | MultiOutput]: + """For each operand, get a realized input, force it to have the same + strides as the subgraph inputs, then use an InvokeSubgraph""" + from .lowering import constrain_to_fake_tensor + + # TODO(anijain2305) - Support sym expr as operands in future. + current_node = V.graph.current_node + + fake_operands = None + if eager_input_vals := current_node.meta.get("eager_input_vals"): + # eager_input_vals is (args_values, kwargs_values). We need args for invoke_subgraph + offset = 2 + if current_node.target is torch.ops.higher_order.with_effects: + # Aruguments eagerly are (token, subgraph, identifier, *operands) + if current_node.args[1] is not torch.ops.higher_order.invoke_subgraph: + raise AssertionError( + "Expected current_node.args[1] is torch.ops.higher_order.invoke_subgraph" + ) + offset = 3 + fake_operands = eager_input_vals[0][offset:] + else: + offset = 2 + if current_node.target is torch.ops.higher_order.with_effects: + # with_effects args: (token, invoke_subgraph, subgraph, identifier, *operands) + if current_node.args[1] is not torch.ops.higher_order.invoke_subgraph: + raise AssertionError( + "Expected current_node.args[1] is torch.ops.higher_order.invoke_subgraph" + ) + offset = 4 + + # For the partitioned backward graph, we do not have + # eager_input_vals. Here, we rely on the recorded example values. + fx_operands = current_node.args[offset:] + fake_operands = [x.meta["val"] for x in fx_operands] # type: ignore[union-attr] + + # Realize the inputs. Also intermediates can have different strides than + # the inputs of the subgraph. So, force the intermediates to have same + # strides as that of subgraph inputs. + # pyrefly: ignore [annotation-mismatch, redefinition] + operands: list[IRNode] = [cls.realize_input(x) for x in operands] + new_operands: list[IRNode] = [] + + for idx, operand in enumerate(operands): + if isinstance( + operand, (ShapeAsConstantBuffer, GeneratorState, OpaqueObjectState) + ): + new_operands.append(operand) + else: + new_operands.append( + constrain_to_fake_tensor(operand, fake_operands[idx]) + ) + + # pyrefly: ignore [bad-assignment] + operands = new_operands + + if subgraph.inductor_config_patches is None: + nested_config = current_node.meta.get("custom", {}).get( + "nested_region_config" + ) + subgraph.inductor_config_patches = getattr( + nested_config, "inductor_config_patches", None + ) + + if subgraph.graph is None: + # create and lower subgraphs + ctx = ( + config.patch(subgraph.inductor_config_patches) + if subgraph.inductor_config_patches + else nullcontext() + ) + with ctx: + subgraph.graph = V.graph.make_subgraph( + gm=subgraph.graph_module, + example_inputs=fake_operands, + subgraph_name=subgraph.name, + ) + with V.set_graph_handler(subgraph.graph): + subgraph.graph.run(*fake_operands) + + outputs = subgraph.graph.graph_outputs + + # Find the device - operands could be integers from shapes, so we can't + # use operands[0] + device = None + for operand in operands: + if not isinstance(operand, ShapeAsConstantBuffer): + device = operand.get_device() + break + if device is None: + raise AssertionError("Expected device is not None") + invoke_subgraph = InvokeSubgraph( + subgraph=subgraph, + operands=operands, + layout=MultiOutputLayout(device=device), + ) + + def create_output( + output: IRNode, ind: int + ) -> ShapeAsConstantBuffer | NoneAsConstantBuffer | MultiOutput: + if isinstance(output, (ShapeAsConstantBuffer, NoneAsConstantBuffer)): + return output + else: + device = output.get_device() + if device is None: + raise AssertionError("Expected device is not None") + + return MultiOutput( + FixedLayout( + device=device, + dtype=output.get_dtype(), + size=output.get_size(), + stride=output.get_stride(), + offset=output.get_layout().offset, + is_pinned=output.get_layout().is_pinned, + ), + invoke_subgraph, # type: ignore[has-type] + [(list, ind)], + skip_size_stride_alignment_checks=True, + ) + + outs = [create_output(output, i) for i, output in enumerate(outputs)] + invoke_subgraph.outputs = outs # type: ignore[assignment] + return outs + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.codegen_invoke_subgraph(self) + + +def _maybe_expr(s: int | torch.SymInt) -> int | Expr: + """Convert an int or SymInt to a plain int or sympy Expr for use in IR layouts.""" + if isinstance(s, int): + return s + return s.node.expr + + +@ir_dataclass(frozen=False) +class Switch(ExternKernel): + """ + IR node representing torch.cond and torch.switch. + + For torch.cond: ``selector`` is a boolean scalar tensor, branches contains exactly + two subgraphs (true branch, false branch), and is_cond=True. + For torch.switch: ``selector`` is an integer scalar tensor, branches contains one + subgraph per case, and is_cond=False. + + Attributes: + selector: A scalar tensor selecting which branch to execute. + branches: Non-empty sequence of subgraphs representing the individual branches. + operands: Input tensors passed to the individual subgraphs. + is_cond: True when this node represents a torch.cond (boolean 2-branch select). + outputs: MultiOutput nodes representing the node's outputs. + """ + + selector: IRNode | None = None + branches: Sequence[Subgraph] | None = None + operands: Sequence[IRNode] | None = None + is_cond: bool = False + outputs: Sequence[MultiOutput] | None = None + + def __init__( + self, + selector: IRNode, + branches: Sequence[Subgraph], + operands: Sequence[IRNode], + layout: MultiOutputLayout, + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None, + is_cond: bool = False, + ) -> None: + self.selector = selector + self.branches = branches + self.operands = operands + self.is_cond = is_cond + + sym_args, tensor_args = _split_by_sym_type([selector, *operands]) + + super().__init__( + name=None, + layout=layout, + inputs=tensor_args, + constant_args=sym_args, + ) + if unbacked_bindings is not None: + self.unbacked_bindings = unbacked_bindings + + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + + def get_subgraphs(self) -> list[Subgraph]: + return list(self.branches) if self.branches is not None else [] + + @classmethod + def create( + cls, + selector: TensorBox, + branches: list[Subgraph], + operands: list[TensorBox], + is_cond: bool = False, + ) -> list[MultiOutput]: + """Create a sequence of IRNodes from a switch/cond statement.""" + # pyrefly: ignore [bad-assignment] + selector = cls.realize_input(selector) + # pyrefly: ignore [bad-assignment] + operands = [cls.realize_input(x) for x in operands] + fx_operands: Argument = V.graph.current_node.args[-1] + + if not isinstance(fx_operands, Sequence): + raise AssertionError(type(fx_operands)) + # Build fake_operands from FX nodes' metadata + # For FX Nodes, get the fake tensor from meta["val"] + # For non-Nodes (e.g., symbolic integers from sym_size lowering), pass directly + fake_operands: list[Any] = [] + for fx_op in fx_operands: + if isinstance(fx_op, Node): + fake_operands.append(fx_op.meta["val"]) + else: + # Symbolic integer or constant - pass directly + fake_operands.append(fx_op) + fake_outputs = V.graph.current_node.meta["val"] + + def _require_exact_strides( + graph_outputs: Sequence[IRNode], + fake_tensors: Sequence[torch.Tensor], + branch_fakes: Sequence[torch.Tensor | int | None], + ) -> list[IRNode]: + ret = [] + for output, fake, branch_fake in zip( + graph_outputs, fake_tensors, branch_fakes + ): + if isinstance(output, ShapeAsConstantBuffer): + ret.append(output) + else: + strides = fake.stride() + # merged strides can contain unbacked symbols (from mismatched + # branch output shapes) undefined inside the subgraph + if has_free_unbacked_symbols(strides): + # pyrefly: ignore [missing-attribute] + strides = branch_fake.stride() + ret.append( + # pyrefly: ignore [bad-argument-type] + ExternKernel.require_exact_strides( + TensorBox(output), strides, allow_padding=False + ) + ) + # pyrefly: ignore [bad-return] + return ret + + for subgraph in branches: + if subgraph.graph is None: + # create and lower subgraphs + subgraph.graph = V.graph.make_subgraph( + gm=subgraph.graph_module, + example_inputs=fake_operands, + subgraph_name=subgraph.name, + ) + branch_out_args = subgraph.graph_module.graph.output_node().args[0] + if not isinstance(branch_out_args, Sequence): + raise AssertionError(type(branch_out_args)) + branch_fakes: list[Any] = [ + a.meta["val"] if isinstance(a, Node) else a for a in branch_out_args + ] + with V.set_graph_handler(subgraph.graph): + subgraph.graph.run(*fake_operands) + # Force subgraph outputs to the expected strides from + # FakeTensor metadata. Branches share the merged strides + # unless those carry an unbacked symbol (mismatched inner + # dims), in which case each branch keeps its own strides. + subgraph.graph.graph_outputs = _require_exact_strides( + subgraph.graph.graph_outputs, fake_outputs, branch_fakes + ) + + if any(branch.graph is None for branch in branches): + raise AssertionError("Expected all branch.graph to be not None") + + branch_outputs = [branch.graph.graph_outputs for branch in branches] # type: ignore[union-attr] + + op_name = "torch.cond" if is_cond else "torch.switch" + for branch, b_outputs in zip(branches, branch_outputs): + if _has_aliased_buffers(b_outputs): + raise AssertionError( + f"Output aliasing is currently not supported in compiled {op_name}. " + f"The outputs of the {branch.name} subgraph of {op_name} are aliased: {b_outputs}" + ) + + # All branches must produce structurally equivalent outputs (same count, + # device, dtype, and layout offset). + ref_outputs = branch_outputs[0] + for b_outputs in branch_outputs[1:]: + if len(ref_outputs) != len(b_outputs): + raise AssertionError((ref_outputs, b_outputs)) + for i, (r_o, b_o) in enumerate(zip(ref_outputs, b_outputs)): + if r_o.get_device() != b_o.get_device(): + raise AssertionError((i, r_o, b_o)) + if r_o.get_dtype() != b_o.get_dtype(): + raise AssertionError((i, r_o, b_o)) + if r_o.get_layout().offset != b_o.get_layout().offset: + raise AssertionError((i, r_o, b_o)) + + # Determine device from operands and predicate + # The predicate can be on a different device (e.g., CPU for control flow) + # while the data operands and outputs should be on the compute device, so + # using predicate device as a fallback. + device = next( + o.get_device() + for o in operands + [selector] + if not isinstance(o, ShapeAsConstantBuffer) + ) + unbacked_bindings = resolve_unbacked_bindings( + V.graph.sizevars.shape_env, + V.graph.current_node.meta.get("unbacked_bindings", None), + ) + if device is None: + raise AssertionError("cannot determine device") + switch = Switch( + selector=selector, + branches=branches, + operands=operands, + layout=MultiOutputLayout(device=device), + unbacked_bindings=unbacked_bindings, + is_cond=is_cond, + ) + + outputs = [ + MultiOutput( + FixedLayout( + # pyrefly: ignore [bad-argument-type] + device=output.get_device() + if output.get_device() is not None + else device, # type: ignore[arg-type] + dtype=output.get_dtype(), + size=[_maybe_expr(sz) for sz in merged_output.size()], + stride=[_maybe_expr(sz) for sz in merged_output.stride()], + offset=output.get_layout().offset, + is_pinned=output.get_layout().is_pinned, + ), + switch, + [(list, i)], + ) + # as the true and false outputs are equivalent, + # we can use either of them here as a "template" + for i, (output, merged_output) in enumerate( + zip(ref_outputs, V.graph.current_node.meta["val"]) + ) + ] + + switch.outputs = outputs # type: ignore[assignment] + + from torch._higher_order_ops.utils import ( + check_input_alias_and_mutation_return_outputs, + ) + + mutated_operand_indices: OrderedSet[int] = OrderedSet() + for branch in branches: + (_, _, _, branch_mutated, _) = ( + check_input_alias_and_mutation_return_outputs(branch.graph_module) + ) + mutated_operand_indices |= OrderedSet(branch_mutated) + + # Create MutationOutput for each mutated operand (for scheduler dependencies) + switch.mutation_outputs = [ + MutationOutput(operands[idx].layout, operands[idx], switch) # type: ignore[union-attr] + for idx in sorted(mutated_operand_indices) + ] + + return outputs + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.codegen_switch(self) + wrapper.codegen_unbacked_symbol_defs_for_outputs( + self.get_name(), self.outputs, getattr(self, "unbacked_bindings", {}) + ) + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + if unbacked_bindings := getattr(self, "unbacked_bindings", None): + resolved = resolve_unbacked_bindings( + V.graph.sizevars.shape_env, unbacked_bindings + ) + if resolved is None: + raise AssertionError("Expected resolved is not None") + return OrderedSet(resolved.keys()) + else: + return OrderedSet() + + +def _split_by_sym_type( + args: list[Any], +) -> tuple[list[ShapeAsConstantBuffer], list[Any]]: + non_sym_args = [] + sym_args = [] + for arg in args: + if isinstance(arg, ShapeAsConstantBuffer): + sym_args.append(arg.expr) + else: + non_sym_args.append(arg) + + return sym_args, non_sym_args + + +@ir_dataclass(frozen=False) +class WhileLoop(ExternKernel): + """The IR node for while_loop and while_loop_stack_output. It supports input mutation.""" + + carried_inputs: Sequence[IRNode] | None = None + additional_inputs: Sequence[IRNode] | None = None + cond_subgraph: Subgraph | None = None + body_subgraph: Subgraph | None = None + outputs: Sequence[MultiOutput] | None = None + + def __init__( + self, + carried_inputs: Sequence[IRNode], + additional_inputs: Sequence[IRNode], + cond_subgraph: Subgraph, + body_subgraph: Subgraph, + layout: MultiOutputLayout, + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None, + stack_output: bool, + ) -> None: + self.carried_inputs = carried_inputs + self.additional_inputs = additional_inputs + self.cond_subgraph = cond_subgraph + self.body_subgraph = body_subgraph + + sym_args, tensor_args = _split_by_sym_type( + [*carried_inputs, *additional_inputs] + ) + super().__init__( + name=None, + layout=layout, + inputs=tensor_args, + constant_args=sym_args, + ) + if unbacked_bindings is not None: + self.unbacked_bindings = unbacked_bindings + self.stack_output = stack_output + + self.name = V.graph.register_buffer(self) + V.graph.register_operation(self) + + def get_subgraphs(self) -> list[Subgraph]: + subgraphs = [] + if self.cond_subgraph: + subgraphs.append(self.cond_subgraph) + if self.body_subgraph: + subgraphs.append(self.body_subgraph) + return subgraphs + + # Accidental aliasing can be created due to cse, where the empty buffers we + # allocated for backward to use gets csed into the same buffer in function fx_graph_cse. + # See test_scan_multiple_layers_gradient for a concrete example. + @staticmethod + def _clone_aliased_inputs(carried_inputs: Sequence[IRNode]) -> Sequence[IRNode]: + if not _has_aliased_buffers(carried_inputs): + return carried_inputs + + # Import clone from lowering module + + # Unwrap views to get the underlying buffers for comparison + unwrapped_buffers = [ + buffer.unwrap_view() if isinstance(buffer, ReinterpretView) else buffer + for buffer in carried_inputs + ] + + # Track which buffers we've seen and their indices + seen_buffers: OrderedSet[int] = OrderedSet() + result: list[IRNode | TensorBox] = [] + + for original_input, unwrapped_buffer in zip(carried_inputs, unwrapped_buffers): + if id(unwrapped_buffer) in seen_buffers: + result.append(ExternKernel.copy_input(original_input)) + else: + seen_buffers.add(id(unwrapped_buffer)) + result.append(original_input) + + return result + + @staticmethod + def _maybe_wrap_as_tensor_box(out: IRNode) -> IRNode: + if isinstance(out, TensorBox): + return out + elif isinstance(out, (StorageBox, ReinterpretView)): + return TensorBox(out) + elif isinstance(out, MultiOutput): + return TensorBox.create(out) + else: + raise RuntimeError(f"NYI unsupported output type: {type(out)}") + + @classmethod + def create( + cls, + cond_fn: Subgraph, + body_fn: Subgraph, + carried_inputs: Sequence[IRNode], + additional_inputs: Sequence[IRNode], + stack_output: bool, + ) -> IRNode | Sequence[IRNode]: + """create the while_loop IR node. stack_output controls whether it stack + each iterations' output, which is necessary for training. + """ + from torch._higher_order_ops.utils import check_input_alias_and_mutation + + def _require_exact_strides( + tensor_boxes: Sequence[IRNode], + fake_tensors: list[int | torch.SymInt | torch.Tensor], + ) -> list[IRNode]: + if len(tensor_boxes) != len(fake_tensors): + raise AssertionError("Expected len(tensor_boxes) == len(fake_tensors)") + ret = [] + for tb, fk in zip(tensor_boxes, fake_tensors): + if isinstance(fk, torch.Tensor): + # Subgraph lowering always return StorageBox as graph_outputs because + # it realizes the outputs. + # + # However, require_exact_strides is expecting TensorBox + # e.g. in require_exact_strides when an expand happens, + # the fake tensor's stride is (0, 0, 0) but the storage + # box might have a different stride so lowering.slice_ + # is used to make the stride consistent and it expects input to + # be TensorBox. + # + # So we wrap the inputs as tensor boxes if they're not yet. + new_tb = WhileLoop._maybe_wrap_as_tensor_box(tb) + ret.append( + ExternKernel.require_exact_strides( + new_tb, fk.stride(), allow_padding=False + ) + ) + else: + ret.append(tb) + return ret + + fx_carried_inputs = V.graph.current_node.args[-2] + fx_additional_inputs = V.graph.current_node.args[-1] + fx_all_inputs = fx_carried_inputs + fx_additional_inputs # type: ignore[operator] + fake_all_inputs = [x.meta["val"] for x in fx_all_inputs] # type: ignore[union-attr] + fake_carried_inputs = [x.meta["val"] for x in fx_carried_inputs] # type: ignore[union-attr] + fake_additional_inputs = [x.meta["val"] for x in fx_additional_inputs] # type: ignore[union-attr] + + carried_inputs_ = [cls.realize_input(x) for x in carried_inputs] + carried_inputs_ = WhileLoop._clone_aliased_inputs(carried_inputs_) + carried_inputs_ = _require_exact_strides(carried_inputs_, fake_carried_inputs) + additional_inputs_ = [cls.realize_input(x) for x in additional_inputs] + additional_inputs_ = _require_exact_strides( + additional_inputs_, fake_additional_inputs + ) + all_inputs = carried_inputs_ + additional_inputs_ + + for subgraph in (cond_fn, body_fn): + if subgraph.graph is None: + # create and lower subgraphs + if not isinstance(fx_all_inputs, Sequence): + raise AssertionError(type(fx_all_inputs)) + subgraph.graph = V.graph.make_subgraph( + gm=subgraph.graph_module, + example_inputs=fx_all_inputs, # type: ignore[arg-type] + subgraph_name=subgraph.name, + ) + with V.set_graph_handler(subgraph.graph): + subgraph.graph.run(*fake_all_inputs) + # For body_fn, we require its output to have the exact same stride + # as inputs because the previous output is the input of next iteration. + # + # This cannot be automatically done in graph lowering because body_fn's graph outputs + # are not user-facing so the special handling for strides of user-facing output in graph + # lowering is not applicable. + if subgraph is body_fn: + if len(subgraph.graph.graph_outputs) != len( + fake_carried_inputs + ): + raise AssertionError( + "Expected len(subgraph.graph.graph_outputs) == len( fake_carried_inputs )" + ) + subgraph.graph.graph_outputs = _require_exact_strides( # type: ignore[assignment] + subgraph.graph.graph_outputs, + fake_carried_inputs, + ) + + if not (cond_fn.graph and body_fn.graph): + raise AssertionError("Expected cond_fn.graph and body_fn.graph") + cond_outputs = cond_fn.graph.graph_outputs + body_outputs = body_fn.graph.graph_outputs + + if _has_aliased_buffers(body_outputs): + raise AssertionError( + "Output aliasing is currently not supported in compiled torch.while_loop. " + f"The outputs of the body_fn subgraph of torch.while_loop are aliased: {body_outputs}" + ) + + # make sure cond_fn returns a boolean scalar Tensor + if len(cond_outputs) != 1: + raise AssertionError(cond_outputs) + p = cond_outputs[0] + if not isinstance(p, ShapeAsConstantBuffer): + if p.get_dtype() != torch.bool: + raise AssertionError(p) + if len(p.get_size()) != 0: + raise AssertionError(p) + + if len(all_inputs) <= 0: + raise AssertionError( + "torch.while_loop is assumed to have at least one operand." + ) + + device = all_inputs[0].get_device() + + if device is None: # to make linter happy + raise AssertionError("Expected device is not None") + # make sure carried_inputs_ and body outputs are structurally equivalent + if len(carried_inputs_) != len(body_outputs): + raise AssertionError( + ( + carried_inputs_, + body_outputs, + ) + ) + for i, (op, bo) in enumerate(zip(carried_inputs_, body_outputs)): + + def _guard_list_equals( + lhs_exprs: Sequence[int | Expr], + rhs_exprs: Sequence[int | Expr], + ) -> None: + if len(lhs_exprs) != len(rhs_exprs): + raise AssertionError("Expected len(lhs_exprs) == len(rhs_exprs)") + for lhs, rhs in zip(lhs_exprs, rhs_exprs): + V.graph.sizevars.check_equals(lhs, rhs) + + _guard_list_equals(op.get_size(), bo.get_size()) + _guard_list_equals(op.get_stride(), bo.get_stride()) + # assume all carried_inputs_ and outputs are on the same device + # as the MultiOutputLayout below requires single device + if op.get_device() != bo.get_device(): + raise AssertionError((i, op, bo, device)) + if op.get_dtype() != bo.get_dtype(): + raise AssertionError((i, op, bo)) + + if device is None: + raise AssertionError("Expected device is not None") + + unbacked_bindings = resolve_unbacked_bindings( + V.graph.sizevars.shape_env, + V.graph.current_node.meta.get("unbacked_bindings", None), + ) + + while_loop = WhileLoop( + carried_inputs=carried_inputs_, + additional_inputs=additional_inputs_, + cond_subgraph=cond_fn, + body_subgraph=body_fn, + # asserted above that there is at least one operand + layout=MultiOutputLayout(device=device), + unbacked_bindings=unbacked_bindings, + stack_output=stack_output, + ) + + if not ( + body_fn.graph is not None + and isinstance(body_fn.graph.module, torch.fx.GraphModule) + ): # to make linter happy + raise AssertionError( + "Expected body_fn.graph is not None and isinstance( body_fn.graph.module, torch.fx.GraphModule )" + ) + + # Handling input mutations + mutated_idxs = check_input_alias_and_mutation( + body_fn.graph.module, fake_all_inputs + )[3] + mutated_idx_set = OrderedSet(mutated_idxs) + mutated_inputs = [all_inputs[idx] for idx in mutated_idx_set] + + # Create all outputs first + mutated_inputs_iter = iter(mutated_inputs) + all_outputs: list[IRNode] = [] + while_loop.outputs = [] + while_loop.mutation_outputs = [] + if stack_output: + if len(mutated_idx_set) != 0: + raise AssertionError("NYI: while_loop_stack_output input mutations.") + for idx, output in enumerate(V.graph.current_node.meta["val"]): + # Create MultiOutput for regular outputs + multi_out = MultiOutput( + FixedLayout( + device=output.device, # type: ignore[arg-type] + dtype=output.dtype, + size=[_maybe_expr(sz) for sz in output.size()], + stride=[_maybe_expr(st) for st in output.stride()], + ), + while_loop, + [(list, idx)], + ) + while_loop.outputs.append(multi_out) + all_outputs.append(multi_out) + else: + for idx, output in enumerate(body_outputs): + if idx in mutated_idx_set: + if idx >= len(carried_inputs): + raise AssertionError("only carries can be mutated.") + # Create MutationOutput for mutated inputs + mutated_input = next(mutated_inputs_iter) + while_loop.mutation_outputs.append( + MutationOutput(mutated_input.layout, mutated_input, while_loop) # type: ignore[attr-defined, union-attr] + ) + all_outputs.append(mutated_input) + else: + multi_out = MultiOutput( + FixedLayout( + device=output.get_device(), # type: ignore[arg-type] + dtype=output.get_dtype(), + size=output.get_size(), + stride=output.get_stride(), + offset=output.get_layout().offset, + ), + while_loop, + [(list, idx)], + ) + while_loop.outputs.append(multi_out) + all_outputs.append(multi_out) + + for inp, out in zip(carried_inputs, all_outputs): + if inp.get_name() in V.graph.graph_inputs: + # if a carried input of the while_loop is a graph input, + # it can be returned as is when the number of iterations + # is zero. due to this, we can't (generally) reuse the + # output buffers corresponding to the graph inputs, as + # the inputs may end up being mutated. + V.graph.never_reuse_buffers.add(out.get_name()) + return all_outputs + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.codegen_while_loop(self, self.stack_output) + wrapper.codegen_unbacked_symbol_defs_for_outputs( + self.get_name(), self.outputs, getattr(self, "unbacked_bindings", {}) + ) + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + if unbacked_bindings := getattr(self, "unbacked_bindings", None): + resolved = resolve_unbacked_bindings( + V.graph.sizevars.shape_env, unbacked_bindings + ) + if resolved is None: + raise AssertionError("Expected resolved is not None") + return OrderedSet(resolved.keys()) + else: + return OrderedSet() + + +class EffectfulKernel(FallbackKernel): + def __init__( + self, + layout: OutputSpec, + kernel: _OpOverloads, + tensor_args: Sequence[IRNode], + nontensor_args: Sequence[Any], + unflatten_args: Callable[..., Any], + kwargs: dict[str, Any] | None = None, + *, + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None = None, + ) -> None: + super().__init__( + layout, + kernel, + tensor_args, + nontensor_args, + unflatten_args, + kwargs=None, + unbacked_bindings=unbacked_bindings, + ) + + from torch._higher_order_ops.effects import _get_effect + + effect_type = _get_effect(kernel) + if effect_type is None: + raise AssertionError("Expected effect_type is not None") + self.effect_type = effect_type + self.prev_effect_buffer = V.graph.effectful_ops.get(effect_type, None) + V.graph.effectful_ops[effect_type] = self + + def get_read_writes(self) -> dependencies.ReadWrites: + read_writes = super().get_read_writes() + + if self.prev_effect_buffer is not None: + read_writes.reads.add( + dependencies.StarDep(self.prev_effect_buffer.get_name()) + ) + + return read_writes + + def has_side_effects(self) -> bool: + return True + + +class NonTensorObj(IRNode): + @cache_on_self_and_args("NonTensorObj") + def get_free_symbol_uses( + self, unbacked_only: bool = False + ) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + def realize(self) -> str | None: + return None + + +@ir_dataclass +class TorchBindObject(NonTensorObj): + name: str + value: FakeScriptObject | torch.ScriptObject + + def get_name(self) -> str: + return self.name + + def codegen_reference(self, writer: IndentedBuffer | None = None) -> str: + return self.name + + def get_value(self) -> FakeScriptObject | torch.ScriptObject: + return self.value + + def get_real_obj(self) -> torch.ScriptObject: + if isinstance(self.value, torch.ScriptObject): + return self.value + else: + return self.value.real_obj + + def get_buf_bytes(self) -> int: + # Returns the sum of all tensors in the flattened object + real_script_obj = self.get_real_obj() + + if is_custom_class_obj(real_script_obj): + return 0 + + if not hasattr(real_script_obj, "__obj_flatten__"): + raise AssertionError('Expected hasattr(real_script_obj, "__obj_flatten__")') + flat_dict = dict(real_script_obj.__obj_flatten__()) + flat_elems = pytree.tree_flatten(flat_dict)[0] + flat_sizes = [ + x.element_size() * x.numel() + for x in flat_elems + if isinstance(x, torch.Tensor) + ] + return functools.reduce(operator.add, flat_sizes, 0) + + +@ir_dataclass +class OpaqueValueTypeConstant(NonTensorObj): + """IR node for opaque value type constants that appear directly in graph outputs. + + Unlike TorchBindObject (which references named constants loaded at runtime), + this inlines the value's repr into the generated code since value types are + reconstructed from their repr. + """ + + value: Any + + def get_name(self) -> str: + return repr(self.value) + + def codegen_reference(self, writer: IndentedBuffer | None = None) -> str: + obj_repr, opaque_types = get_opaque_obj_repr(self.value) + for n, t in opaque_types.items(): + V.graph.opaque_value_type_classes[n] = t + return obj_repr + + +@ir_dataclass +class GeneratorState(NonTensorObj): + name: str + device: torch.device + + def get_name(self) -> str: + return self.name + + def codegen_reference(self, writer: IndentedBuffer | None = None) -> str: + return self.name + + +@ir_dataclass +class OpaqueObjectState(NonTensorObj): + """ + Represents an opaque object (e.g., ProcessGroup) that is passed through + as a graph input. Similar to GeneratorState, this wraps the object with + its placeholder name so codegen can reference it properly. + """ + + name: str + value: Any # The actual opaque object (for reference, not used in codegen) + + def get_name(self) -> str: + return self.name + + def codegen_reference(self, writer: IndentedBuffer | None = None) -> str: + return self.name + + +class _CollectiveKernel(FallbackKernel): + def should_allocate(self) -> bool: + return False + + def has_side_effects(self) -> bool: + return True + + # This is identical to FallbackKernel.set_cpp_kernel(), minus the + # part that checks against input aliasing and mutation. + def set_cpp_kernel_name(self, cpp_kernel_name: str | None = None) -> None: + if type(self.op_overload) is not torch._ops.OpOverload: + raise AssertionError("Setting cpp kernel needs a valid op_overload") + kernel = self.op_overload + if cpp_kernel_name is not None: + self.cpp_kernel_name = cpp_kernel_name + else: + self.cpp_kernel_name = kernel._schema.name + + self.ordered_kwargs_for_cpp_kernel = [ + x.name for x in kernel._schema.arguments if x.kwarg_only + ] + + # NOTE: [In-Place Collective Safety] + # Between the initiation and completion of an in-place collective, the + # input buffers are subject to both volatile reads and volatile writes. + # They must not be read, written to or reused by another kernel. To ensure + # the constraints, we model collective -> wait_tensor as a two-step + # mutation of the input buffers. + @classmethod + def create_inplace( + cls, + kernel: _OpOverloads, + inputs: IRNode | list[IRNode], + *args: Any, + **kwargs: Any, + ) -> None: + with V.graph.fake_mode: + result = cls.process_kernel(kernel, inputs, *args, **kwargs) + tensor_args = result.tensor_args + non_tensor_args = result.non_tensor_args + unflatten_args = result.unflatten_args + if result.unbacked_bindings: + raise AssertionError(f"{kernel} {result.unbacked_bindings}") + device = None + for tensor_arg in tensor_args: + if isinstance(tensor_arg, NonTensorObj): + continue + tensor_arg.realize() + V.graph.mark_buffer_mutated(tensor_arg.get_name()) + if device is None: + device = tensor_arg.get_device() + if device is None: + raise AssertionError( + f"In-place collective {kernel} requires at least one tensor " + f"argument; got only non-tensor IR nodes." + ) + packed = cls( + NoneLayout(device=device), + kernel, + tensor_args, + non_tensor_args, + unflatten_args, + ) + + inps = pytree.tree_leaves(inputs) + packed.mutation_outputs.extend( + [MutationOutput(NoneLayout(device=device), buf, packed) for buf in inps] + ) + + # For inplace collective ops, the input is guaranteed to be alias of the returned value of op. + packed.alias_names.extend([inp.get_name() for inp in inps]) + if "out" in kwargs: + packed.mutation_outputs.append( + MutationOutput(NoneLayout(device=device), kwargs["out"], packed) + ) + # For out-variant collective ops, the `out=` arg is guaranteed to be alias of the returned value of op. + packed.alias_names.append(kwargs["out"].get_name()) + + # NOTE: [Out-of-Place Collective Safety] + # Between the initiation and completion of an out-of-place collective: + # + # Input buffers: + # - Are subject to volatile reads + # - Can be read by another kernel + # - Must not be written to or reused by another kernel + # + # Output buffers: + # - Are subject to volatile writes + # - Must not be read, written to or reused by another kernel + # + # To ensure the safety of input buffers without sacrificing read + # availability, we add input buffers as read deps of wait_tensor kernels. + # + # To ensure the safety of output buffers, we model wait_tensor as a + # mutation to the output buffer. Note we also assumes the user program being + # correct and the output buffer is not consumed by kernels other than + # wait_tensor. + # + # TODO(yifu): add a pre-grad pass to validate the correctness of collective + # usage in the user program. + @classmethod + def create_out_of_place( + cls, + kernel: _OpOverloads, + inputs: TensorBox | list[TensorBox], + *args: Any, + **kwargs: Any, + ) -> list[MultiOutput] | _CollectiveKernel: + with V.graph.fake_mode: + result = cls.process_kernel(kernel, inputs, *args, **kwargs) + example_output = result.example_output + tensor_args = result.tensor_args + non_tensor_args = result.non_tensor_args + unflatten_args = result.unflatten_args + if result.unbacked_bindings: + raise AssertionError(f"{kernel}, {result.unbacked_bindings}") + for tensor_arg in tensor_args: + if not isinstance(tensor_arg, TorchBindObject): + tensor_arg.realize() + + if isinstance(example_output, list): + device = cls.find_device(tensor_args, example_output) + if device is None: + raise AssertionError("Expected device is not None") + packed = cls( + MultiOutputLayout(device=device), + kernel, + tensor_args, + non_tensor_args, + unflatten_args, + ) + packed.outputs = [ + MultiOutput( + cls.tensor_to_layout(tensor), + packed, + [(list, i)], + ) + for i, tensor in enumerate(example_output) + ] + for buf, tensor in zip(packed.outputs, example_output): + if config.assume_unaligned_fallback_output or not tensor_is_aligned( + tensor + ): + V.graph.unaligned_buffers.add(buf.name) # type: ignore[arg-type] + return packed.outputs + else: + packed = cls( + cls.tensor_to_layout(example_output), + kernel, + tensor_args, + non_tensor_args, + unflatten_args, + ) + if config.assume_unaligned_fallback_output or not tensor_is_aligned( + example_output + ): + V.graph.unaligned_buffers.add(packed.name) # type: ignore[arg-type] + packed.outputs = [packed] + return packed + + +class _AllReduce_Kernel(_CollectiveKernel): + def __init__( + self, + layout: OutputSpec, + kernel: _OpOverloads, + tensor_args: Sequence[IRNode], + nontensor_args: Sequence[Any], + unflatten_args: Callable[..., Any], + kwargs: dict[str, Any] | None = None, + *, + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None = None, + ) -> None: + super().__init__( + layout, + kernel, + tensor_args, + nontensor_args, + unflatten_args, + kwargs=None, + unbacked_bindings=unbacked_bindings, + ) + self.set_cpp_kernel_name("aoti_torch_cpu__c10d_functional_all_reduce_") + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.include_extra_header("torch/csrc/inductor/aoti_torch/c/shim_cpu.h") + wrapper.generate_extern_kernel_alloc(self) + + if isinstance(self.layout, Layout): + self.codegen_size_asserts(wrapper) + + +class _AllReduceKernel(_CollectiveKernel): + def __init__( + self, + layout: OutputSpec, + kernel: _OpOverloads, + tensor_args: Sequence[IRNode], + nontensor_args: Sequence[Any], + unflatten_args: Callable[..., Any], + kwargs: dict[str, Any] | None = None, + *, + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None = None, + ) -> None: + super().__init__( + layout, + kernel, + tensor_args, + nontensor_args, + unflatten_args, + kwargs=None, + unbacked_bindings=unbacked_bindings, + ) + self.set_cpp_kernel_name("aoti_torch_cpu__c10d_functional_all_reduce") + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.include_extra_header("torch/csrc/inductor/aoti_torch/c/shim_cpu.h") + wrapper.generate_extern_kernel_alloc(self) + + if isinstance(self.layout, Layout): + self.codegen_size_asserts(wrapper) + + +class _WaitKernel(_CollectiveKernel): + def __init__( + self, + layout: OutputSpec, + kernel: _OpOverloads, + tensor_args: Sequence[IRNode], + nontensor_args: Sequence[Any], + unflatten_args: Callable[..., Any], + kwargs: dict[str, Any] | None = None, + *, + unbacked_bindings: dict[sympy.Symbol, pytree.KeyPath] | None = None, + ) -> None: + super().__init__( + layout, + kernel, + tensor_args, + nontensor_args, + unflatten_args, + kwargs=None, + unbacked_bindings=unbacked_bindings, + ) + self.set_cpp_kernel_name("aoti_torch_cpu__c10d_functional_wait_tensor") + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + wrapper.include_extra_header("torch/csrc/inductor/aoti_torch/c/shim_cpu.h") + wrapper.generate_extern_kernel_alloc(self) + + if isinstance(self.layout, Layout): + self.codegen_size_asserts(wrapper) + + def get_volatile_reads(self) -> Sequence[IRNode]: + inp = self.inputs[0] + if not isinstance(inp, IRNode): + raise AssertionError("Expected isinstance(inp, IRNode)") + if isinstance(inp, _CollectiveKernel): + # Out-of-place single-output + i = inp.inputs[0] + if not isinstance(i, IRNode): + raise AssertionError(type(i)) + return [i] + elif isinstance(inp, MultiOutput): + # This can be two things: + # 1. Out-of-place multi-output coll + # 2. In-place coll with inputs coming from another MultiOutput + coll = inp.inputs[0] + # Case 1 + if isinstance(coll, _CollectiveKernel): + _, idx = inp.indices[0] + + return [coll.inputs[idx]] + # Case 2 + return [] + else: + # In-place requires no additional deps handling for volatile + # reads since the inputs are mutated. + return [] + + @classmethod + def create_wait(cls, kernel: _OpOverloads, inp: TensorBox) -> None: + with V.graph.fake_mode: + result = cls.process_kernel(kernel, inp) + if result.unbacked_bindings: + raise AssertionError(f"{kernel} {result.unbacked_bindings}") + packed = cls( + NoneLayout(device=inp.get_device()), + kernel, + result.tensor_args, + result.non_tensor_args, + result.unflatten_args, + ) + packed.mutation_outputs.append( + MutationOutput(NoneLayout(device=inp.get_device()), inp, packed) + ) + + def get_read_writes(self) -> dependencies.ReadWrites: + read_writes = super().get_read_writes() + # See [Out-of-Place Collective Safety]. + volatile_reads = self.get_volatile_reads() + for vr in volatile_reads: + read_writes.reads.add(dependencies.StarDep(vr.get_name())) + return read_writes + + +# NB: recursive structure here reflects val_to_arg_str, avoid +# calling free_unbacked_symbols on "exotic" types that don't get pexpr +# treatment +def maybe_free_unbacked_symbols(s: object) -> OrderedSet[Symbol]: + if isinstance(s, (SymTypes, Expr)): + # This branch should be impossible in return position + return free_unbacked_symbols(s) + elif isinstance(s, (tuple, list)): + r = OrderedSet[sympy.Symbol]() + for t in s: + r |= maybe_free_unbacked_symbols(t) + return r + elif isinstance(s, torch.Tensor): + # This branch is impossible in constant-args position + return free_unbacked_symbols(s) + else: + return OrderedSet() + + +def maybe_free_symbols(s: object) -> OrderedSet[Symbol]: + if isinstance(s, (SymTypes, Expr)): + # This branch should be impossible in return position + return free_symbols(s) + elif isinstance(s, (tuple, list)): + r = OrderedSet[sympy.Symbol]() + for t in s: + r |= maybe_free_symbols(t) + return r + elif isinstance(s, torch.Tensor): + # This branch is impossible in constant-args position + return free_symbols(s) + else: + return OrderedSet() + + +def assign_origin_node(result: Any, n: torch.fx.Node) -> None: + # This is not complete, but it doesn't have to be: origin_node + # tracking is best effort. The logic here critically relies on direct + # TensorBox -> StorageBox denoting a non-view; we don't bother trying + # to get views to work. Feel free to add any extra cases as needed. + # + # Note: we can't YOLO tree_map over this result, because if there are + # buffers or a view involved, we might not be able to validly assign + # the origin_node here. + if isinstance(result, TensorBox) and isinstance(result.data, StorageBox): + if isinstance(result.data.data, Loops): + result.data.data._post_init_setattr("origin_node", n) + elif isinstance(result.data.data, Buffer): + result.data.data._post_init_setattr("origin_node", n) + if isinstance(result.data.data, ComputedBuffer) and isinstance( + result.data.data.data, Loops + ): + result.data.data.data._post_init_setattr("origin_node", n) + # Not really multi-output, can straightforwardly recurse in + elif ( + isinstance(result.data.data, MultiOutput) + and not result.data.data.indices + ): + if isinstance(result.data.data.inputs[0], Buffer): + result.data.data.inputs[0]._post_init_setattr("origin_node", n) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/jagged_lowerings.py b/.venv/lib/python3.12/site-packages/torch/_inductor/jagged_lowerings.py new file mode 100644 index 0000000000000000000000000000000000000000..3a8e404133c4ea1ca2976c931fb96ce36e7bb991 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/jagged_lowerings.py @@ -0,0 +1,269 @@ +# mypy: allow-untyped-defs + +import sympy + +import torch + +from .ir import Pointwise, TensorBox +from .virtualized import ops + + +# pyre-ignore[2,3] +def dense_idx_to_jagged_idx(batch_idx, seq_idx, offsets_loader, jagged_len): + # jagged_len + 1 is used as the upper bound, + # because the last sequence length may be zero + begin_idx = ops.indirect_indexing( + offsets_loader([batch_idx]), + jagged_len + 1, + ) + end_idx = offsets_loader([batch_idx + 1]) + jagged_idx = begin_idx + seq_idx + return jagged_idx, end_idx + + +def get_inverse_offsets( + offsets: TensorBox, + jagged_len: int | sympy.Expr, + realize: bool = True, +) -> TensorBox: + """ + Returns "inverse_offsets" - the inverse of the offsets array. + offsets maps batch index (dense) to jagged index (i.e. offset into jagged tensor). + inverse_offsets maps jagged index to batch index. + + e.g. for offsets [0, 3, 4, 9, 10] this will return + inverse_offsets = [0, 0, 0, 1, 2, 2, 2, 2, 2, 3] + + For the given offsets, the computed inverse_offsets are cached + on the first call and reused in the further calls. + """ + + if hasattr(offsets, "inverse_offsets"): + # inverse_offsets are already computed + # for these offsets: can reuse + return offsets.inverse_offsets + + # ops.bucketize takes offsets.get_name() which doesn't exist on Pointwise + # kernels, i.e. we need to realize it before using. In other words, we need + # offsets to be in global memory so that we can binary search over the + # entire tensor + offsets.realize() + device: torch.device = offsets.get_device_or_error() + dtype: torch.dtype = offsets.get_dtype() + + # pyre-ignore[2,3] + def inner_fn(index): + idx = index[0] + bucket = ops.bucketize( + values=ops.index_expr(idx, dtype), + boundaries=( + offsets.get_name(), + offsets.get_size()[-1], + offsets.get_size()[0] * offsets.get_stride()[0], + offsets.get_stride()[-1], + ), + boundary_indices=0, + indexing_dtype=dtype, + right=True, + ) + # ops.bucketize above returns 1-based bucket indices, + # but we need 0-based, hence we subtract 1 from batch + return bucket - 1 + + inverse_offsets = Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=[jagged_len], + ) + + if realize: + # "freeze" the node so that it doesn't get inlined downstream. + inverse_offsets.realize() + + # cache inverse_offsets for further reuse + offsets.inverse_offsets = inverse_offsets # type: ignore[attr-defined] + + return inverse_offsets + + +def jagged_idx_to_dense_idx( + jagged_idx, # pyre-ignore[2] + inverse_offsets_loader, # pyre-ignore[2] + offsets_loader, # pyre-ignore[2] + batch_size: int | sympy.Expr, + max_seq_len: int | sympy.Expr, + offsets_dtype: torch.dtype, +) -> tuple[sympy.Expr, sympy.Expr]: + batch_idx = ops.indirect_indexing( + inverse_offsets_loader([jagged_idx]), + batch_size + 1, + ) + batch_start = offsets_loader([batch_idx]) + seq = ops.index_expr(jagged_idx, offsets_dtype) - batch_start + # check=False because there may be sequences longer than max_seq_len + seq_idx = ops.indirect_indexing(seq, max_seq_len, check=False) + return batch_idx, seq_idx + + +def register_jagged_ops(): + # Avoid circular import by importing here + from .lowering import fallback_handler, is_integer_type, register_lowering + + # pyre-ignore[56] + @register_lowering(torch.ops.aten._jagged_to_padded_dense_forward.default) + def _jagged_to_padded_dense_forward( + jagged_values: TensorBox, + jagged_offsets: list[TensorBox], + max_lengths: list[int], # list of ints/SymInts + padding_value: float = 0.0, + ) -> TensorBox: + device = jagged_values.get_device_or_error() + dtype = jagged_values.get_dtype() + + jagged_values_size = jagged_values.get_size() + + # only handle the common case of a single jagged dimension + if ( + len(jagged_offsets) != 1 + or device.type != "cuda" + or device != jagged_offsets[0].get_device() + or len(jagged_values_size) != 2 + or len(jagged_offsets[0].get_size()) != 1 + or len(max_lengths) != len(jagged_offsets) + or not is_integer_type(jagged_offsets[0]) + ): + return fallback_handler( + torch.ops.aten._jagged_to_padded_dense_forward.default, + add_to_fallback_set=False, + )( + jagged_values, + jagged_offsets, + max_lengths, + padding_value, + ) + + offsets: TensorBox = jagged_offsets[0] # type: ignore[assignment] + offsets_len = offsets.get_size()[0] + offsets_dtype = offsets.get_dtype() + batch_size = offsets_len - 1 + max_seq_len = max_lengths[0] + embedding_len = jagged_values_size[1] + jagged_len = jagged_values_size[0] + + output_size = [batch_size, max_seq_len, embedding_len] + + values_loader = jagged_values.make_loader() + offsets_loader = offsets.make_loader() + + # pyre-ignore[2,3,53] + def inner_fn(index): + # dense tensor size: [B, N, D] + batch_idx, seq_idx, emb_idx = index + jagged_idx, end_idx = dense_idx_to_jagged_idx( + batch_idx=batch_idx, + seq_idx=seq_idx, + offsets_loader=offsets_loader, + jagged_len=jagged_len, + ) + return ops.masked( + ops.lt( + ops.index_expr(jagged_idx, offsets_dtype), + end_idx, + ), + lambda: values_loader([jagged_idx, emb_idx]), + padding_value, + ) + + return Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=output_size, + ) + + def _dense_to_jagged_forward_impl( + fallback_op, # pyre-ignore[2] + dense: TensorBox, + jagged_offsets: list[TensorBox], + jagged_len: int | None = None, + ) -> TensorBox: + device = dense.get_device_or_error() + dtype = dense.get_dtype() + + dense_size = dense.get_size() + + # only handle the common case of a single jagged dimension + if ( + len(jagged_offsets) != 1 + or device.type != "cuda" + or device != jagged_offsets[0].get_device() + or len(jagged_offsets[0].get_size()) != 1 + or len(dense_size) != 3 + or jagged_len is None + or not is_integer_type(jagged_offsets[0]) + ): + return fallback_handler(fallback_op, add_to_fallback_set=False)( + dense, + jagged_offsets, + jagged_len, + ) + + offsets: TensorBox = jagged_offsets[0] # type: ignore[assignment] + offsets_dtype = offsets.get_dtype() + batch_size = dense_size[0] + max_seq_len = dense_size[1] + embedding_len = dense_size[-1] + + output_size = [jagged_len, embedding_len] + + dense_loader = dense.make_loader() + offsets_loader = offsets.make_loader() + + inverse_offsets = get_inverse_offsets( + offsets=offsets, + jagged_len=jagged_len, + ) + inverse_offsets_loader = inverse_offsets.make_loader() + + # pyre-ignore[2,3,53] + def inner_fn(index): + # jagged tensor size: [sum_B(N_B), D] + jagged_idx, emb_idx = index + batch_idx, seq_idx = jagged_idx_to_dense_idx( + jagged_idx=jagged_idx, + offsets_loader=offsets_loader, + inverse_offsets_loader=inverse_offsets_loader, + batch_size=batch_size, + max_seq_len=max_seq_len, + offsets_dtype=offsets_dtype, + ) + return ops.masked( + ops.lt( + ops.index_expr(seq_idx, offsets_dtype), + ops.index_expr(max_seq_len, offsets_dtype), + ), + lambda: dense_loader([batch_idx, seq_idx, emb_idx]), + 0.0, # jagged sequence longer than max_seq_len + ) + + return Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=output_size, + ) + + # pyre-ignore[56] + @register_lowering(torch.ops.aten._padded_dense_to_jagged_forward) + def _dense_to_jagged_forward( + dense: TensorBox, + jagged_offsets: list[TensorBox], + jagged_len: int | None = None, + ) -> TensorBox: + return _dense_to_jagged_forward_impl( + fallback_op=torch.ops.aten._padded_dense_to_jagged_forward.default, + dense=dense, + jagged_offsets=jagged_offsets, + jagged_len=jagged_len, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aee458957bfa5dc96abc647b870ecc94eb231f2e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__init__.py @@ -0,0 +1,2 @@ +from . import flex, mm, mm_common, mm_plus_mm +from .flex_gemm import lowering as flex_gemm_lowering diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c46db92fa5d8f7dba74864ea3f86e45e249d9ea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/bmm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/bmm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cca8f93cb5cbc0399f4d5370b2a27a5210f3ef78 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/bmm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/conv.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/conv.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7252edcd9af3179d7d9f9ddb3b1324e82bbe231 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/conv.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/custom_op.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/custom_op.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..615a6442a8f791651737d29f3a035092c44a8927 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/custom_op.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/gemm_epilogue.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/gemm_epilogue.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77f83a6d5ccebc44227887e1028798cbb26e98ee Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/gemm_epilogue.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/gemm_epilogue_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/gemm_epilogue_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b588716d66a4768d29c27de7e3b61ea183740465 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/gemm_epilogue_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/gemm_epilogue_codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/gemm_epilogue_codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99c70f1018d0d09dbbb32ec1550e04d8a79ab51f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/gemm_epilogue_codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/gemm_epilogue_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/gemm_epilogue_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a86ab719126eb767d75505310f747870dd681ff Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/gemm_epilogue_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/loop_ir_cutedsl_codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/loop_ir_cutedsl_codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b29dcb9aff595bf6aa0eb3ee09bc3886905691c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/loop_ir_cutedsl_codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/loop_ir_epilogue_lowering.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/loop_ir_epilogue_lowering.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..667e06d8992063d2defa6a7b4932fee31db5fc26 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/loop_ir_epilogue_lowering.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/mm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/mm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0431b0bb2b29bfcc382d613d4343109b3dab3f80 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/mm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/mm_common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/mm_common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39f47f3408f04c14378236351d0b6eced814f5b0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/mm_common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/mm_grouped.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/mm_grouped.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ed6b6690465f4974cb4187389fefc2e0341e884 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/mm_grouped.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/mm_plus_mm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/mm_plus_mm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7effc4cb7a6dee3a6eae522da91036e5a572f95e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/mm_plus_mm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/bmm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/bmm.py new file mode 100644 index 0000000000000000000000000000000000000000..e2324a127e75b8f4c11d5c100893366b8f1bdf63 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/bmm.py @@ -0,0 +1,335 @@ +# mypy: allow-untyped-defs +import logging +from typing import TYPE_CHECKING + +import torch +from torch._dynamo.utils import counters +from torch._inductor.codegen.rocm.ck_universal_gemm_template import CKGemmTemplate +from torch._inductor.kernel.mm_common import load_kernel_template + +from .. import config as inductor_config, ir, lowering as L +from ..kernel_inputs import MMKernelInputs +from ..lowering import lowerings, make_pointwise, make_reduction, transform_args +from ..runtime.runtime_utils import get_max_y_grid +from ..select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, + SymbolicGridFn, + TritonTemplate, +) +from ..utils import ( + _use_cutlass_for_op, + use_aten_gemm_kernels, + use_ck_gemm_template, + use_cpp_bmm_template, + use_cutlass_template, + use_nv_universal_gemm_template, + use_triton_template, +) +from ..virtualized import ops, V +from .mm_common import ( + _is_static_problem, + is_batch_stride_largest_or_zero, + mm_args, + use_native_matmul, +) + + +if TYPE_CHECKING: + from ..ir import ChoiceCaller + from ..select_algorithm import KernelTemplate + +log = logging.getLogger(__name__) +aten = torch.ops.aten + + +@SymbolicGridFn +def bmm_grid(b, m, n, meta, *, cdiv, max): + tiles = cdiv(m, meta["BLOCK_M"]) * cdiv(n, meta["BLOCK_N"]) + # Split batch across grid_y and grid_z to avoid exceeding CUDA grid_y limit. + # When b <= max_y_grid, grid_z = 1 and behavior is identical to the original. + max_y_grid = get_max_y_grid() + grid_z = max(cdiv(b, max_y_grid), 1) + grid_y = cdiv(b, grid_z) + return (tiles, grid_y, grid_z) + + +# We define each template kernel in a separate file which is the name of the input to load_kernel_template +# (e.g. triton_bmm for templates/triton_bmm.py.jinja). +# If you are adding a new template, please follow that pattern and add a new file with your implementation in the templates folder. +bmm_template = TritonTemplate( + name="bmm", + grid=bmm_grid, + source=load_kernel_template("triton_bmm"), + cache_codegen_enabled_for_template=True, +) + +aten_bmm = ExternKernelChoice(torch.bmm, "at::bmm_out", op_overload=aten.bmm.out) +aten_bmm_dtype = ExternKernelChoice( + torch.bmm, + "at::_bmm_out_dtype_xpu" if torch.xpu._is_compiled() else "at::_bmm_out_dtype_cuda", + name="bmm_dtype", + op_overload=aten.bmm.dtype_out, +) +aten_baddbmm = ExternKernelChoice( + torch.baddbmm, "at::baddbmm_out", op_overload=aten.baddbmm.out +) + +# This path targets vmapped dot products and similar tiny vector contractions, +# where extern bmm launch overhead and lost fusion dominate. Keep the threshold +# conservative so reductions proven to be larger than the threshold continue +# through the normal bmm machinery. +_BMM_DOT_K_DECOMPOSE_THRESHOLD = 32 +_BMM_DOT_DECOMPOSE_DTYPES = ( + torch.float16, + torch.bfloat16, + torch.float32, + torch.float64, +) + + +@L.register_lowering(aten.bmm) +def tuned_bmm(mat1, mat2, out_dtype=None, *, layout=None): + """ + Lowering for autotuning aten.bmm with different backends (Aten, Triton, CUTLASS, etc.) + """ + sizevars = V.graph.sizevars + dtype = mat1.get_dtype() + device_type = mat1.get_device().type + + def dim_is_one_or_hint(dim): + # The mul+sum decomposition is valid for any M/N. The size-1 hint is + # only a profitability signal, so avoid specializing dynamic dims here. + return sizevars.optimization_hint(dim, fallback=2) == 1 + + def dim_is_not_known_gt(dim, threshold): + # Do not use optimization_hint() for K: the same symbolic FX graph can + # be code-cache reused across different concrete K values. + return not sizevars.statically_known_gt(dim, threshold) + + if ( + out_dtype is None + and device_type in ("cuda", "xpu") + and device_type == mat2.get_device().type + and dtype == mat2.get_dtype() + and dtype in _BMM_DOT_DECOMPOSE_DTYPES + and dim_is_one_or_hint(mat1.get_size()[1]) + and dim_is_one_or_hint(mat2.get_size()[2]) + and dim_is_not_known_gt(mat1.get_size()[2], _BMM_DOT_K_DECOMPOSE_THRESHOLD) + ): + # Preserve dot-shaped bmm as pointwise/reduction IR so surrounding + # operations can fuse instead of dispatching a tiny extern bmm. + mat1 = L.unsqueeze(mat1, -1) + mat2 = L.unsqueeze(mat2, 1) + return L.sum_(L.mul(mat1, mat2), axis=2) + + if all(x.get_device().type == "cpu" for x in [mat1, mat2]): + # decompose to small ops when memory bound + if mat1.get_size()[1] == 1 or mat2.get_size()[2] == 1: + mat1 = L.unsqueeze(mat1, -1) + mat2 = L.unsqueeze(mat2, 1) + return L.sum_(L.mul(mat1, mat2), axis=2) + + def is_valid_to_require_contiguous(t): + if not ir.is_storage_and_layout(t): + return True + _, layout = ir.as_storage_and_layout(t, freeze=False) + return isinstance(layout, ir.FlexibleLayout) + + def is_preferred_layout_as_bmm_input(sizes, strides): + # contiguous on one of the last two dims + return ( + strides[-1] == 1 and (sizes[-2] == 1 or strides[-2] >= sizes[-1]) + ) or (strides[-2] == 1 and (sizes[-1] == 1 or strides[-1] >= sizes[-2])) + + # Make the input of bmm contiguous + # if it is not contiguous on either of the last two dims, + # because bmm cpu implementation would do contiguous() if not. + # This is to avoid additional copies in bmm. + def may_require_contiguous(t, meta_t): + sizes = meta_t.meta["val"].size() + strides = meta_t.meta["val"].stride() + if not is_preferred_layout_as_bmm_input(sizes, strides): + t = ir.ExternKernel.require_contiguous(t) + return t + + if is_valid_to_require_contiguous(mat1): + meta_mat1 = V.graph.current_node.args[0] + mat1 = may_require_contiguous(mat1, meta_mat1) + if is_valid_to_require_contiguous(mat2): + meta_mat2 = V.graph.current_node.args[1] + mat2 = may_require_contiguous(mat2, meta_mat2) + + if use_native_matmul(mat1, mat2): + mat1 = lowerings[aten.unsqueeze](mat1, -1) + mat2 = lowerings[aten.unsqueeze](mat2, 1) + args, kwargs = transform_args( + args=[mat1, mat2], + kwargs={}, + broadcast=True, + type_promotion_kind=None, + convert_input_to_bool=False, + ) # Handles broadcasting the arguments + + if inductor_config.triton.codegen_upcast_to_fp32 and mat1.dtype in [ + torch.float16, + torch.bfloat16, + ]: + + def _to_dtype(x): + return ops.to_dtype(x, mat1.dtype, use_compute_types=False) + + args = [make_pointwise(_to_dtype)(x) for x in args] + + mul_pointwise = make_pointwise(ops.dot)(*args) + dot_reduction = make_reduction("dot")(mul_pointwise, 2) + + return dot_reduction + + # TODO(coconutruben): integrate into MMKernelInputs when all callsites use that + m, n, k, layout, mat1, mat2 = mm_args( + mat1, mat2, layout=layout, out_dtype=out_dtype + ) + name = "bmm" + + # Create MMKernelInputs for BMM at the top + kernel_inputs = MMKernelInputs([mat1, mat2], out_dtype=out_dtype) + + # below is for getting an overview logging info of inductor mms + batch_size = mat1.get_size()[0] # Extract batch dimension + counters["aten_mm_info"][f"aten.bmm_{batch_size}_{m}_{n}_{k}"] += 1 + log.info( + "Tuned aten.bmm: batch=%s, m=%s, n=%s, k=%s, mat1_dtype=%s, mat2_dtype=%s, output_layout=%s", + batch_size, + m, + n, + k, + mat1.get_dtype(), + mat2.get_dtype(), + layout, + ) + + aten_handler: ExternKernelChoice = aten_bmm + aten_extra_kwargs = {} + if out_dtype: + if mat1.get_device().type not in ("cuda", "xpu"): + raise AssertionError("out_dtype is only supported for CUDA or XPU") + aten_handler = aten_bmm_dtype + aten_extra_kwargs = {"out_dtype": out_dtype} + + choices: list[ChoiceCaller] = [] + + # Collect all templates for unified call + templates_to_use: list[ExternKernelChoice | KernelTemplate] = [] + kwarg_overrides = {} + + if use_aten_gemm_kernels(): + templates_to_use.append(aten_handler) + kwarg_overrides[aten_handler.uid] = aten_extra_kwargs + + if use_triton_template(layout, check_max_autotune=False): + templates_to_use.append(bmm_template) + + # Single unified call for all templates + choices.extend( + V.choices.get_template_configs( + kernel_inputs, + templates_to_use, + name, + kwarg_overrides=kwarg_overrides, + ) + ) + _, is_nonzero = _is_static_problem(layout) + batch_stride_largest_or_zero = is_batch_stride_largest_or_zero(mat1, mat2, layout) + if ( + batch_stride_largest_or_zero + and is_nonzero + and use_cutlass_template(layout, m, n, k) + and _use_cutlass_for_op(name) + ): + from ..codegen.cutlass.gemm_template import CUTLASS3xGemmTemplate + + CUTLASS3xGemmTemplate.add_cutlass_gemm_choices( + choices, layout, kernel_inputs.nodes() + ) # type: ignore[arg-type] + + if use_cpp_bmm_template(layout, mat1, mat2): + from ..codegen.cpp_bmm_template import CppBmmTemplate + + CppBmmTemplate.add_choices( + choices, + layout, + kernel_inputs.nodes(), + ) + + if use_ck_gemm_template(layout, m, n, k): + CKGemmTemplate.add_ck_gemm_choices(choices, layout, kernel_inputs.nodes()) + + if is_nonzero and use_nv_universal_gemm_template(layout, m, n, k, mat1, mat2): + from ..codegen.nv_universal_gemm import add_nv_universal_gemm_choices + + add_nv_universal_gemm_choices(choices, layout, kernel_inputs) + + node, _ = autotune_select_algorithm(name, choices, kernel_inputs.nodes(), layout) + return node + + +@L.register_lowering(aten.baddbmm) +def tuned_baddbmm(inp, mat1, mat2, *, alpha=1, beta=1, layout=None): + """ + Lowering for autotuning aten.mm with different backends (Aten, Triton, CUTLASS, etc.) + """ + if use_native_matmul(mat1, mat2): + if beta == 0: + arg1 = 0 + else: + arg1 = lowerings[aten.mul](beta, inp) + + if alpha == 0: + arg2 = 0 + else: + arg2 = lowerings[aten.mul](alpha, lowerings[aten.bmm](mat1, mat2)) + + return lowerings[aten.add](arg1, arg2) + + # TODO(coconutruben): integrate into MMKernelInputs when all callsites use that + m, n, k, layout, mat1, mat2, inp = mm_args(mat1, mat2, inp, layout=layout) + + # Create MMKernelInputs for BadDBMM at the top + kernel_inputs = MMKernelInputs( + [inp, mat1, mat2], scalars=dict(alpha=alpha, beta=beta) + ) + + # below is for getting an overview logging info of inductor mms + batch_size = mat1.get_size()[0] + counters["aten_mm_info"][f"aten.baddbmm_{batch_size}_{m}_{n}_{k}"] += 1 + log.info( + "Tuned aten.baddbmm: batch_size=%s, m=%s, n=%s, k=%s, mat1_dtype=%s, mat2_dtype=%s, inp=%s, output_layout=%s", + batch_size, + m, + n, + k, + mat1.get_dtype(), + mat2.get_dtype(), + inp.get_dtype(), + layout, + ) + name = "baddbmm" + # options to tune from + choices: list[ChoiceCaller] = [] + + # Collect all templates for unified call + templates_to_use: list[ExternKernelChoice | KernelTemplate] = [] + if use_aten_gemm_kernels(): + templates_to_use.append(aten_baddbmm) + + if use_triton_template(layout, check_max_autotune=False): + templates_to_use.append(bmm_template) + + # Single unified call for all templates + choices.extend( + V.choices.get_template_configs(kernel_inputs, templates_to_use, name) + ) + + node, _ = autotune_select_algorithm(name, choices, kernel_inputs.nodes(), layout) + return node diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/conv.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..2429067d255441b51486765a447dbc13ffdf9fce --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/conv.py @@ -0,0 +1,1303 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, TypedDict + +import torch +from torch._inductor.codegen.rocm.ck_conv_template import CKGroupedConvFwdTemplate + +from .. import config, ir +from ..lowering import ( + add_layout_constraint, + constrain_to_fx_strides, + fallback_handler, + lowerings as L, + register_lowering, +) +from ..select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, + SymbolicGridFn, + TritonTemplate, +) +from ..utils import ( + is_ones, + is_zeros, + pad_listlike, + sympy_product, + use_ck_conv_template, + use_triton_template, +) +from ..virtualized import V +from .mm_common import load_kernel_template + + +if TYPE_CHECKING: + from collections.abc import Sequence + + from ..ir import TensorBox + +log = logging.getLogger(__name__) + + +aten = torch.ops.aten + + +@SymbolicGridFn +def conv2d_grid(n, c, h, w, meta, *, cdiv): + return ( + cdiv(n * h * w, meta["BLOCK_M"]), + cdiv(c, meta["BLOCK_N"]), + meta["GROUPS"], + ) + + +@SymbolicGridFn +def conv3d_grid(n, c, d, h, w, meta, *, cdiv): + return ( + cdiv(n * d * h * w, meta["BLOCK_M"]), + cdiv(c, meta["BLOCK_N"]), + meta["GROUPS"], + ) + + +# ============================================================================= +# Depthwise conv1d (groups == in_channels == out_channels) +# Uses direct element-wise multiply-accumulate instead of implicit GEMM. +# Channels-last (NLC) layout with 3D tiling: BLOCK_N x BLOCK_L x BLOCK_C. +# ============================================================================= + + +@SymbolicGridFn +def depthwise_conv1d_grid(n, c, l, meta, *, cdiv): + return ( + cdiv(n, meta["BLOCK_N"]), + cdiv(l, meta["BLOCK_L"]), + cdiv(c, meta["BLOCK_C"]), + ) + + +depthwise_conv1d_template = TritonTemplate( + name="depthwise_conv1d", + grid=depthwise_conv1d_grid, + source=load_kernel_template("triton_depthwise_conv"), + cache_codegen_enabled_for_template=True, +) + +LOOP_BODY_2D = """ + idx_x_h = i - PADDING_H + idx_y_h * STRIDE_H + idx_x_w = j - PADDING_W + idx_y_w * STRIDE_W + idx_x_c = tl.arange(0, BLOCK_K) + k + + x_ptrs = x_base + ( + (idx_x_h * stride_xh)[:, None] + + (idx_x_w * stride_xw)[:, None] + + (idx_x_c * stride_xc)[None, :] + ) + mask_x = ( + (idx_n < BATCH)[:, None] + & (idx_x_h >= 0)[:, None] + & (idx_x_h < IN_H)[:, None] + & (idx_x_w >= 0)[:, None] + & (idx_x_w < IN_W)[:, None] + & (idx_x_c < GROUP_IN_C)[None, :] + ) + matrix_x = tl.load(x_ptrs, mask=mask_x, other=0.0) + + w_ptrs = w_base + ( + (idx_x_c * stride_wc_in)[:, None] + (i * stride_wh) + (j * stride_ww) + ) + mask_w = (idx_x_c[:, None] < GROUP_IN_C) & (idx_y_c[None, :] < GROUP_OUT_C) + matrix_w = tl.load(w_ptrs, mask=mask_w, other=0.0) + acc += tl.dot(matrix_x, matrix_w, allow_tf32=ALLOW_TF32) +""" + +""" +This is a relatively simple conv implementation that can likely be +improved. Many alternate conv versions can be found here: +https://github.com/pytorch/torchdynamo/pull/971 +""" +conv2d_template = TritonTemplate( + name="convolution2d", + grid=conv2d_grid, + source=r""" +{{def_kernel("X", "W")}} + # Tensor dimensions + BATCH = {{size("X", 0)}} + IN_C = {{size("X", 1)}} + IN_H = {{size("X", 2)}} + IN_W = {{size("X", 3)}} + OUT_C = {{size(None, 1)}} + OUT_H = {{size(None, 2)}} + OUT_W = {{size(None, 3)}} + + # Strides: + stride_xn = {{stride("X", 0)}} + stride_xc = {{stride("X", 1)}} + stride_xh = {{stride("X", 2)}} + stride_xw = {{stride("X", 3)}} + stride_wc_out = {{stride("W", 0)}} + stride_wc_in = {{stride("W", 1)}} + stride_wh = {{stride("W", 2)}} + stride_ww = {{stride("W", 3)}} + + nhw = tl.program_id(0).to(INDEX_DTYPE) * BLOCK_M + tl.arange(0, BLOCK_M) + idx_y_w = nhw % OUT_W + nh = nhw // OUT_W + idx_y_h = nh % OUT_H + idx_n = nh // OUT_H + idx_y_c = tl.program_id(1).to(INDEX_DTYPE) * BLOCK_N + tl.arange(0, BLOCK_N) + +{% if GROUPS == 1 %} + group = 0 + GROUP_IN_C = IN_C + GROUP_OUT_C = OUT_C +{% else %} + group = tl.program_id(2).to(INDEX_DTYPE) + GROUP_IN_C = IN_C // GROUPS + GROUP_OUT_C = OUT_C // GROUPS +{% endif %} + + x_base = X + (group * stride_xc * GROUP_IN_C + idx_n * stride_xn)[:, None] + w_base = ( + W + (group * stride_wc_out * GROUP_OUT_C + idx_y_c * stride_wc_out)[None, :] + ) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + +{% if UNROLL %} +{% for i in range(KERNEL_H) %} +{% for j in range(KERNEL_W) %} + i = {{i}} + j = {{j}} + for k in range(0, GROUP_IN_C, BLOCK_K): + """ + + LOOP_BODY_2D + + """ +{% endfor %} +{% endfor %} +{% else %} + # Could be simplified, but slightly slower: + # for i in range(KERNEL_H): + # for j in range(KERNEL_W): + # for k in range(0, GROUP_IN_C, BLOCK_K): + BLOCK_K_COUNT = (GROUP_IN_C + BLOCK_K - 1) // BLOCK_K + for ijk in range(KERNEL_H * KERNEL_W * BLOCK_K_COUNT): + k = (ijk % BLOCK_K_COUNT) * BLOCK_K + ij = ijk // BLOCK_K_COUNT + i = ij // KERNEL_W + j = ij % KERNEL_W + """ + + LOOP_BODY_2D + + """ +{% endif %} + + mask = ( + (idx_n < BATCH)[:, None] + & (idx_y_h < OUT_H)[:, None] + & (idx_y_w < OUT_W)[:, None] + & (idx_y_c < GROUP_OUT_C)[None, :] + ) + idx_n = idx_n[:, None] + idx_c = idx_y_c[None, :] + group * GROUP_OUT_C + idx_h = idx_y_h[:, None] + idx_w = idx_y_w[:, None] + + # inductor generates a suffix + {{store_output(("idx_n", "idx_c", "idx_h", "idx_w"), "acc", "mask", val_shape=("BLOCK_M", "BLOCK_N"))}} +""", +) + +LOOP_BODY_3D = """ + idx_x_d = d - PADDING_D + idx_y_d * STRIDE_D + idx_x_h = i - PADDING_H + idx_y_h * STRIDE_H + idx_x_w = j - PADDING_W + idx_y_w * STRIDE_W + idx_x_c = tl.arange(0, BLOCK_K) + k + + x_ptrs = x_base + ( + (idx_x_d * stride_xd)[:, None] + + (idx_x_h * stride_xh)[:, None] + + (idx_x_w * stride_xw)[:, None] + + (idx_x_c * stride_xc)[None, :] + ) + mask_x = ( + (idx_n < BATCH)[:, None] + & (idx_x_d >= 0)[:, None] + & (idx_x_d < IN_D)[:, None] + & (idx_x_h >= 0)[:, None] + & (idx_x_h < IN_H)[:, None] + & (idx_x_w >= 0)[:, None] + & (idx_x_w < IN_W)[:, None] + & (idx_x_c < GROUP_IN_C)[None, :] + ) + matrix_x = tl.load(x_ptrs, mask=mask_x, other=0.0) + + w_ptrs = w_base + ( + (idx_x_c * stride_wc_in)[:, None] + + (d * stride_wd) + (i * stride_wh) + (j * stride_ww) + ) + mask_w = (idx_x_c[:, None] < GROUP_IN_C) & (idx_y_c[None, :] < GROUP_OUT_C) + matrix_w = tl.load(w_ptrs, mask=mask_w, other=0.0) + acc += tl.dot(matrix_x, matrix_w, allow_tf32=ALLOW_TF32) +""" + +conv3d_template = TritonTemplate( + name="convolution3d", + grid=conv3d_grid, + source=r""" +{{def_kernel("X", "W")}} + # Tensor dimensions + BATCH = {{size("X", 0)}} + IN_C = {{size("X", 1)}} + IN_D = {{size("X", 2)}} + IN_H = {{size("X", 3)}} + IN_W = {{size("X", 4)}} + OUT_C = {{size(None, 1)}} + OUT_D = {{size(None, 2)}} + OUT_H = {{size(None, 3)}} + OUT_W = {{size(None, 4)}} + + # Strides: + stride_xn = {{stride("X", 0)}} + stride_xc = {{stride("X", 1)}} + stride_xd = {{stride("X", 2)}} + stride_xh = {{stride("X", 3)}} + stride_xw = {{stride("X", 4)}} + stride_wc_out = {{stride("W", 0)}} + stride_wc_in = {{stride("W", 1)}} + stride_wd = {{stride("W", 2)}} + stride_wh = {{stride("W", 3)}} + stride_ww = {{stride("W", 4)}} + + ndhw = tl.program_id(0).to(INDEX_DTYPE) * BLOCK_M + tl.arange(0, BLOCK_M) + idx_y_w = ndhw % OUT_W + ndh = ndhw // OUT_W + idx_y_h = ndh % OUT_H + nd = ndh // OUT_H + idx_y_d = nd % OUT_D + idx_n = nd // OUT_D + idx_y_c = tl.program_id(1).to(INDEX_DTYPE) * BLOCK_N + tl.arange(0, BLOCK_N) + +{% if GROUPS == 1 %} + group = 0 + GROUP_IN_C = IN_C + GROUP_OUT_C = OUT_C +{% else %} + group = tl.program_id(2).to(INDEX_DTYPE) + GROUP_IN_C = IN_C // GROUPS + GROUP_OUT_C = OUT_C // GROUPS +{% endif %} + + x_base = X + (group * stride_xc * GROUP_IN_C + idx_n * stride_xn)[:, None] + w_base = ( + W + (group * stride_wc_out * GROUP_OUT_C + idx_y_c * stride_wc_out)[None, :] + ) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + +{% if UNROLL %} +{% for d in range(KERNEL_D) %} +{% for i in range(KERNEL_H) %} +{% for j in range(KERNEL_W) %} + d = {{d}} + i = {{i}} + j = {{j}} + for k in range(0, GROUP_IN_C, BLOCK_K): + """ + + LOOP_BODY_3D + + """ +{% endfor %} +{% endfor %} +{% endfor %} +{% else %} + # Could be simplified, but slightly slower: + # for d in range(KERNEL_D): + # for i in range(KERNEL_H): + # for j in range(KERNEL_W): + # for k in range(0, GROUP_IN_C, BLOCK_K): + BLOCK_K_COUNT = (GROUP_IN_C + BLOCK_K - 1) // BLOCK_K + for dijk in range(KERNEL_D * KERNEL_H * KERNEL_W * BLOCK_K_COUNT): + k = (dijk % BLOCK_K_COUNT) * BLOCK_K + dij = dijk // BLOCK_K_COUNT + j = dij % KERNEL_W + di = dij // KERNEL_W + i = di % KERNEL_H + d = di // KERNEL_H + """ + + LOOP_BODY_3D + + """ +{% endif %} + + mask = ( + (idx_n < BATCH)[:, None] + & (idx_y_d < OUT_D)[:, None] + & (idx_y_h < OUT_H)[:, None] + & (idx_y_w < OUT_W)[:, None] + & (idx_y_c < GROUP_OUT_C)[None, :] + ) + idx_n = idx_n[:, None] + idx_c = idx_y_c[None, :] + group * GROUP_OUT_C + idx_d = idx_y_d[:, None] + idx_h = idx_y_h[:, None] + idx_w = idx_y_w[:, None] + + # inductor generates a suffix + {{store_output(("idx_n", "idx_c", "idx_d", "idx_h", "idx_w"), "acc", "mask", val_shape=("BLOCK_M", "BLOCK_N"))}} +""", +) + +aten_convolution = ExternKernelChoice( + torch.convolution, + "at::convolution", + has_out_variant=False, + op_overload=aten.convolution.default, +) + + +def conv1x1_via_mm(x, w, *, out): + w = torch.squeeze(torch.squeeze(w, -1), -1) + return torch.matmul( + x.permute(0, 2, 3, 1), w.permute(1, 0), out=out.permute(0, 2, 3, 1) + ) + + +aten_conv1x1_via_mm = ExternKernelChoice(conv1x1_via_mm, None) + + +class ConvLayoutParams(TypedDict): + stride: tuple[int, ...] + padding: tuple[int, ...] + dilation: tuple[int, ...] + transposed: bool + output_padding: tuple[int, ...] + groups: int + + +def conv_layout( + x: TensorBox, + weight: TensorBox, + bias: TensorBox | None, + stride: Sequence[int], + padding: tuple[int, ...], + dilation: tuple[int, ...], + transposed: bool, + output_padding: tuple[int, ...], + groups: int, +) -> ir.Layout: + """Determine output layout for a convolution""" + # We use guard_int_seq rather than size_hints because the output shape + # depends on these values — if they ever contained symbols, size_hints + # would silently substitute a hint that could be wrong, producing an + # incorrect layout. guard_int_seq will install a proper guard instead. + # Note: stride and padding are already guarded via guard_int_seq in + # convolution() above, but we guard all four here so conv_layout is + # self-contained and doesn't rely on callers. + guard = V.graph.sizevars.guard_int_seq + with V.graph.fake_mode: + output = torch.ops.aten.convolution( + ir.ir_node_to_tensor(x), + ir.ir_node_to_tensor(weight), + ir.ir_node_to_tensor(bias), + guard(stride), + guard(padding), + guard(dilation), + transposed, + guard(output_padding), + groups, + ) + sizes = ir.convert_shape_to_inductor(output.size()) + stride = ir.convert_shape_to_inductor(output.stride()) # type: ignore[assignment] + + return ir.FixedLayout( + x.get_device_or_error(), + x.get_dtype(), + sizes, + stride, + ) + + +def channels_last_order(rank): + order = list(reversed(range(rank))) + order.insert(1, order.pop(-1)) + return order + + +def convert_1x1_conv_to_mm(x, weight, bias): + # special case for 1x1 convolution, which is actually just a matmul + rank = len(weight.get_size()) + for _ in range(rank - 2): + weight = L[aten.squeeze](weight, dim=-1) + weight = L[aten.permute](weight, [1, 0]) + + x = ir.ExternKernel.require_stride_order(x, channels_last_order(rank)) + x_permute = list(range(rank)) + x_permute.append(x_permute.pop(1)) + x = L[aten.permute](x, x_permute) + *sizes, in_chan = x.get_size() + x = L[aten.reshape](x, [sympy_product(sizes), in_chan]) + if bias is None: + result = L[aten.mm](x, weight) + else: + result = L[aten.addmm](bias, x, weight) + result = L[aten.reshape](result, [*sizes, -1]) + result_permute = list(range(rank)) + result_permute.insert(1, result_permute.pop(-1)) + return L[aten.permute](result, result_permute) + + +@register_lowering(aten.convolution) +def convolution( + x: TensorBox, + weight: TensorBox, + bias: TensorBox | None, + stride: Sequence[int], + padding: Sequence[int], + dilation: Sequence[int], + transposed: bool, + output_padding: Sequence[int], + groups: int, +): + """Lower aten.convolution using Inductor convolution kernels or fallbacks.""" + stride = tuple(stride) + padding = tuple(padding) + dilation = tuple(dilation) + output_padding = tuple(output_padding) + if not isinstance(groups, int): + groups = V.graph.sizevars.guard_int(groups) + if not isinstance(groups, int): + raise AssertionError(f"Expected int for groups, got {type(groups)}") + + # Need use hint for triton template since the template does not + # work with a dynamic shape. + # + # Dilation must also be guarded for transposed convolutions because the + # backward-input template substitutes DILATION_H/W as tl.constexpr. + # For non-transposed convolutions the forward template gates on + # dilation==1, so guarding is unnecessary. + stride = tuple(V.graph.sizevars.guard_int_seq(stride)) + padding = tuple(V.graph.sizevars.guard_int_seq(padding)) + if transposed: + dilation = tuple(V.graph.sizevars.guard_int_seq(dilation)) + + kwargs: ConvLayoutParams = { + "stride": stride, + "padding": padding, + "dilation": dilation, + "transposed": transposed, + "output_padding": output_padding, + "groups": groups, + } + + device_type = ir.get_device_type(x) + + if len(x.get_size()) == len(weight.get_size()) - 1: + # add batch dimension to simplify rest of function + return L[aten.squeeze]( + convolution(L[aten.expand](x, [1, *x.get_size()]), weight, bias, **kwargs), + dim=0, + ) + + out_chan, in_chan, *kernel_shape = V.graph.sizevars.guard_int_seq(weight.get_size()) + + # Always convert conv1D to 2D for Intel GPU. + # Only conv2D can be converted to channel last layout, + # which have much better performance. + if len(x.get_size()) == 3 and len(kernel_shape) == 1 and device_type == "xpu": + kwargs.update( + { + "stride": (1,) + stride, + "padding": (0,) + padding, + "dilation": (1,) + dilation, + "output_padding": (0,) + output_padding, + } + ) + # (N, C, L) -> (N, C, 1, L) + x = L[aten.unsqueeze](x, dim=2) + weight = L[aten.unsqueeze](weight, dim=2) + + return L[aten.squeeze]( + convolution(x, weight, bias, **kwargs), + dim=2, + ) + + ndim = len(kernel_shape) + stride = pad_listlike(stride, ndim) + padding = pad_listlike(padding, ndim) + dilation = pad_listlike(dilation, ndim) + output_padding = pad_listlike(output_padding, ndim) + + def channels_last_conv(): + if V.graph.layout_opt and ndim == 2: + return True + + layout = conv_layout(x, weight, None, **kwargs) + # TODO: This does not guard on the stride order decision, + # shall we use optimization_hint to handle unbacked? + req_stride_order = ir.get_stride_order( + V.graph.sizevars.guarding_hints_or_throw(layout.stride) + ) + return req_stride_order == ir.NHWC_STRIDE_ORDER + + autotuning_gemm = config.max_autotune or config.max_autotune_gemm + + if ( + (config.conv_1x1_as_mm or (autotuning_gemm and channels_last_conv())) + and is_ones(kernel_shape) + and is_ones(stride) + and is_zeros(padding) + and is_ones(dilation) + and not transposed + and is_zeros(output_padding) + and groups == 1 + and V.graph.sizevars.statically_known_gt(sympy_product(x.get_size()), 0) + ): + return convert_1x1_conv_to_mm(x, weight, bias) + + if bias is not None and device_type != "cpu": + # peel off the bias, cudnn is slower with it + result = convolution(x, weight, None, **kwargs) + if V.graph.sizevars.statically_known_equals(result.get_size()[1], 0): + # we should not add bias when the output channel is 0 + return result + return L[aten.add]( + result, L[aten.view](bias, [result.get_size()[1]] + ndim * [1]) + ) + + x.realize() + weight.realize() + + # ndim can be 1 for convolution in models such as demucs + # TODO: check if it's beneficial to convert Conv1d to Conv2d and then + # apply channels last. + if V.graph.layout_opt and ndim == 2: + V.graph.num_channels_last_conv += 1 + x = ir.ExternKernel.require_channels_last(x) # type: ignore[assignment] + # TODO maybe we can convert weights to channels last just once before + # running the model. + weight = ir.ExternKernel.require_channels_last(weight) # type: ignore[assignment] + layout = conv_layout(x, weight, None, **kwargs) + else: + layout = conv_layout(x, weight, None, **kwargs) + # TODO: This does not guard on the stride order decision, + # shall we use optimization_hint to handle unbacked? + req_stride_order = ir.get_stride_order( + V.graph.sizevars.guarding_hints_or_throw(layout.stride) + ) + x = ir.ExternKernel.require_stride_order(x, req_stride_order) # type: ignore[assignment] + weight = ir.ExternKernel.require_stride_order(weight, req_stride_order) # type: ignore[assignment] + + ordered_kwargs_for_cpp_kernel = [ + "stride", + "padding", + "dilation", + "transposed", + "output_padding", + "groups", + ] + if bias is None: + args = [x, weight] + kwargs["bias"] = None # type: ignore[typeddict-unknown-key] + ordered_kwargs_for_cpp_kernel.insert(0, "bias") + else: + bias = ir.ExternKernel.realize_input(bias) # type: ignore[assignment] + if bias is None: + raise AssertionError("bias must not be None after realize_input") + args = [x, weight, bias] + bias.freeze_layout() + V.graph.sizevars.guard_int_seq(bias.get_size()) + + choices = [] + if torch._inductor.utils._use_conv_autotune_backend("ATEN"): + choices = [ + aten_convolution.bind( + args, + layout, + ordered_kwargs_for_cpp_kernel, + **kwargs, + ) + ] + + if ( + torch._inductor.utils._use_conv_autotune_backend("TRITON") + and use_triton_template(layout) + # templates only support these: + and is_ones(dilation) + and not transposed + and is_zeros(output_padding) + # there are some odd models where this check fails (e.g. shufflenet_v2_x1_0) + and V.graph.sizevars.statically_known_equals(in_chan * groups, x.get_size()[1]) # type: ignore[arg-type] + ): + if ( + is_ones(kernel_shape) + and is_ones(stride) + and is_zeros(padding) + and groups == 1 + ): + choices.append(aten_conv1x1_via_mm.bind(args, layout)) + + is_depthwise = groups > 1 and in_chan == 1 and out_chan == groups + if is_depthwise and ndim == 1: + depthwise_configs = V.choices.get_depthwise_conv_configs(device_type) + for cfg in depthwise_configs: + depthwise_conv1d_template.maybe_append_choice( + choices, + input_nodes=(x, weight), + layout=layout, + KERNEL_SIZE=kernel_shape[0], + CONV_STRIDE=stride[0], + PADDING=padding[0], + num_stages=cfg.num_stages, + num_warps=cfg.num_warps, + **cfg.kwargs, + ) + + conv_configs = V.choices.get_conv_configs(device_type) + + dtype_size = x.get_dtype().itemsize + for cfg in conv_configs( + sympy_product([x.get_size()[0], *x.get_size()[2:]]), + out_chan, + in_chan, + dtype_size=dtype_size, + ): + unroll = is_ones(kernel_shape) + # The non-unrolled loop in these templates triggers triton#1254 + # with 8 warps, producing incorrect results for non-1x1 kernels. + num_warps = cfg.num_warps if unroll else min(cfg.num_warps, 4) + + if ndim == 2: + conv2d_template.maybe_append_choice( + choices, + input_nodes=(x, weight), + layout=layout, + KERNEL_H=kernel_shape[0], + KERNEL_W=kernel_shape[1], + STRIDE_H=stride[0], + STRIDE_W=stride[1], + PADDING_H=padding[0], + PADDING_W=padding[1], + GROUPS=groups, + # TODO(jansel): try unroll for bigger kernels once fixed: + # https://github.com/triton-lang/triton/issues/1254 + UNROLL=unroll, + ALLOW_TF32=torch.backends.cudnn.fp32_precision == "tf32", + num_stages=cfg.num_stages, + num_warps=num_warps, + **cfg.kwargs, + ) + elif ndim == 3: + conv3d_template.maybe_append_choice( + choices, + input_nodes=(x, weight), + layout=layout, + KERNEL_D=kernel_shape[0], + KERNEL_H=kernel_shape[1], + KERNEL_W=kernel_shape[2], + STRIDE_D=stride[0], + STRIDE_H=stride[1], + STRIDE_W=stride[2], + PADDING_D=padding[0], + PADDING_H=padding[1], + PADDING_W=padding[2], + GROUPS=groups, + # TODO(jansel): try unroll for bigger kernels once fixed: + # https://github.com/triton-lang/triton/issues/1254 + UNROLL=unroll, + ALLOW_TF32=torch.backends.cudnn.fp32_precision == "tf32", + num_stages=cfg.num_stages, + num_warps=num_warps, + **cfg.kwargs, + ) + # The Triton conv2d backward-input kernels miscompile on CUDA (wrong results + # on sm90, ptxas illegal memory access on sm100) with no perf win, so keep + # them on ROCm and fall back to ATEN on CUDA. Same rationale as the + # convolution_backward lowering. See + # https://github.com/pytorch/pytorch/issues/187081. + disable_triton_conv_bwd = device_type == "cuda" and not torch.version.hip + if ( + torch._inductor.utils._use_conv_autotune_backend("TRITON") + and use_triton_template(layout) + and transposed + and ndim == 2 + and not disable_triton_conv_bwd + ): + # ConvTranspose2d is mathematically identical to conv_backward_input: + # the input plays the role of grad_output and the same weight layout + # is used. Reuse the backward-input Triton template. + conv_configs = V.choices.get_conv_configs(device_type) + dtype_size = x.get_dtype().itemsize + for cfg in conv_configs( + sympy_product([layout.size[0], layout.size[2], layout.size[3]]), + out_chan, + in_chan, + dtype_size=dtype_size, + ): + conv2d_bwd_input_template.maybe_append_choice( + choices, + input_nodes=(x, weight), + layout=layout, + KERNEL_H=kernel_shape[0], + KERNEL_W=kernel_shape[1], + PADDING_H=padding[0], + PADDING_W=padding[1], + STRIDE_H=stride[0], + STRIDE_W=stride[1], + DILATION_H=dilation[0], + DILATION_W=dilation[1], + GROUPS=groups, + ALLOW_TF32=torch.backends.cudnn.fp32_precision == "tf32", + num_stages=cfg.num_stages, + num_warps=cfg.num_warps, + **cfg.kwargs, + ) + + if use_ck_conv_template(layout): + CKGroupedConvFwdTemplate.add_ck_conv_choices( + choices, + layout, + input_nodes=(x, weight) + ((bias,) if bias is not None else tuple()), + stride=stride, + padding=padding, + dilation=dilation, + groups=groups, + n_spatial_dimensions=ndim, + ) + + if not choices and config.max_autotune_conv_backends.strip(): + choices.append( + aten_convolution.bind( + args, + layout, + ordered_kwargs_for_cpp_kernel, + **kwargs, + ) + ) + + node, _ = autotune_select_algorithm("convolution", choices, args, layout) + return node + + +@register_lowering(aten._convolution) +def _convolution( + x, + weight, + bias, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + benchmark, + deterministic, + cudnn_enabled, + allow_tf32, +): + return convolution( + x, weight, bias, stride, padding, dilation, transposed, output_padding, groups + ) + + +def constrain_conv_to_fx_strides(fx_node, *args, **kwargs): + if fx_node.target is not torch.ops.aten.convolution.default: + raise AssertionError(f"Expected aten.convolution.default, got {fx_node.target}") + if V.graph.layout_opt: + return args, kwargs + else: + return constrain_to_fx_strides(fx_node, *args, **kwargs) + + +add_layout_constraint(aten.convolution, constrain_conv_to_fx_strides) + + +def conv_bwd_input_layout( + grad_out: TensorBox, + input: TensorBox, + weight: TensorBox, + stride: Sequence[int], + padding: tuple[int, ...], + dilation: tuple[int, ...], + transposed: bool, + output_padding: tuple[int, ...], + groups: int, +) -> ir.Layout: + guard = V.graph.sizevars.guard_int_seq + with V.graph.fake_mode: + go = ir.ir_node_to_tensor(grad_out) + x = ir.ir_node_to_tensor(input) + w = ir.ir_node_to_tensor(weight) + + dx, _, _ = torch.ops.aten.convolution_backward( + go, + x, + w, + None, # bias_sizes + guard(stride), + guard(padding), + guard(dilation), + transposed, + guard(output_padding), + groups, + (True, False, False), + ) + sizes = ir.convert_shape_to_inductor(dx.size()) + stride_ = ir.convert_shape_to_inductor(dx.stride()) + + return ir.FixedLayout( + input.get_device_or_error(), + input.get_dtype(), + sizes, + stride_, + ) + + +def conv_bwd_weight_layout( + grad_out: TensorBox, + input: TensorBox, + weight: TensorBox, + stride: Sequence[int], + padding: tuple[int, ...], + dilation: tuple[int, ...], + transposed: bool, + output_padding: tuple[int, ...], + groups: int, +) -> ir.Layout: + guard = V.graph.sizevars.guard_int_seq + with V.graph.fake_mode: + go = ir.ir_node_to_tensor(grad_out) + x = ir.ir_node_to_tensor(input) + w = ir.ir_node_to_tensor(weight) + + _, dw, _ = torch.ops.aten.convolution_backward( + go, + x, + w, + None, # bias_sizes + guard(stride), + guard(padding), + guard(dilation), + transposed, + guard(output_padding), + groups, + (False, True, False), + ) + sizes = ir.convert_shape_to_inductor(dw.size()) + stride_ = ir.convert_shape_to_inductor(dw.stride()) + + return ir.FixedLayout( + weight.get_device_or_error(), + weight.get_dtype(), + sizes, + stride_, + ) + + +def call_aten_dw( + x_t, + go_t, + *, + w_shape, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + out, +): + if x_t.is_contiguous(memory_format=torch.channels_last): + memory_fmt = torch.channels_last + else: + memory_fmt = torch.contiguous_format + + dummy_weight = torch.empty( + w_shape, dtype=out.dtype, device=x_t.device, memory_format=memory_fmt + ) + + torch.ops.aten.convolution_backward.out( + out1=None, + out2=out, + out3=None, + grad_output=go_t, + input=x_t, + weight=dummy_weight, + bias_sizes=None, + stride=stride, + padding=padding, + dilation=dilation, + transposed=transposed, + output_padding=output_padding, + groups=groups, + output_mask=(False, True, False), + ) + return out + + +ext_kn_aten_dw = ExternKernelChoice(call_aten_dw, None) + + +def call_aten_dx( + go_t, + w_t, + *, + x_shape, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + out, +): + if go_t.is_contiguous(memory_format=torch.channels_last): + memory_fmt = torch.channels_last + else: + memory_fmt = torch.contiguous_format + + dummy_input = torch.empty( + x_shape, dtype=out.dtype, device=go_t.device, memory_format=memory_fmt + ) + + torch.ops.aten.convolution_backward.out( + out1=out, + out2=None, + out3=None, + grad_output=go_t, + input=dummy_input, + weight=w_t, + bias_sizes=None, + stride=stride, + padding=padding, + dilation=dilation, + transposed=transposed, + output_padding=output_padding, + groups=groups, + output_mask=(True, False, False), + ) + return out + + +ext_kn_aten_dx = ExternKernelChoice(call_aten_dx, None) + + +@SymbolicGridFn +def conv2d_bwd_weight_grid(cout, cin, kh, kw, meta, *, cdiv): + g = meta["GROUPS"] + return ( + cdiv(cin * kh * kw, meta["BLOCK_M"]), + cdiv(cout // g, meta["BLOCK_N"]), + g, + ) + + +conv2d_bwd_weight_template = TritonTemplate( + name="convolution2d_bwd_weight", + grid=conv2d_bwd_weight_grid, + source=load_kernel_template("triton_conv2d_bwd_weight"), +) + + +@SymbolicGridFn +def conv2d_bwd_input_grid(n, cin, h, w, meta, *, cdiv): + g = meta["GROUPS"] + return ( + cdiv(n * h * w, meta["BLOCK_M"]), + cdiv(cin // g, meta["BLOCK_N"]), + g, + ) + + +conv2d_bwd_input_template = TritonTemplate( + name="convolution2d_bwd_input", + grid=conv2d_bwd_input_grid, + source=load_kernel_template("triton_conv2d_bwd_input"), +) + + +aten_convolution_backward_fallback = fallback_handler(aten.convolution_backward.default) + + +@register_lowering(aten.convolution_backward.default) +def convolution_backward_lowering( + grad_out: TensorBox, + input: TensorBox, + weight: TensorBox, + bias_sizes: Sequence[int] | None, + stride: Sequence[int], + padding: Sequence[int], + dilation: Sequence[int], + transposed: bool, + output_padding: Sequence[int], + groups: int, + output_mask: Sequence[bool], +): + """ + Lowering function for backward convolution operator. + + TRITON kernels are only registered for supported configurations (currently 2D convolutions). + For unsupported dimensions or configurations, the choices list remains empty, + triggering an automatic fallback to the ATen reference implementation. + This ensures correctness for all cases while enabling TRITON optimizations only where implemented. + """ + stride = tuple(stride) + padding = tuple(padding) + dilation = tuple(dilation) + output_padding = tuple(output_padding) + if not isinstance(groups, int): + groups = V.graph.sizevars.guard_int(groups) + + out_chan, in_chan, *kernel_shape = V.graph.sizevars.guard_int_seq(weight.get_size()) + + # The Triton bwd templates substitute DILATION_H/W into the generated + # kernel source, so they must be concrete Python ints. The fwd template + # gates on is_ones(dilation) and hard-codes dilation=1, so it can skip + # this guard. + stride = tuple(V.graph.sizevars.guard_int_seq(stride)) + padding = tuple(V.graph.sizevars.guard_int_seq(padding)) + dilation = tuple(V.graph.sizevars.guard_int_seq(dilation)) + + input.realize() + weight.realize() + grad_out.realize() + + kwargs: ConvLayoutParams = { + "stride": stride, + "padding": padding, + "dilation": dilation, + "transposed": transposed, + "output_padding": output_padding, + "groups": groups, + } + + ndim = len(kernel_shape) + stride = pad_listlike(stride, ndim) + padding = pad_listlike(padding, ndim) + dilation = pad_listlike(dilation, ndim) + output_padding = pad_listlike(output_padding, ndim) + + device_type = ir.get_device_type(input) + + # The Triton conv2d backward kernels hit a ptxas miscompile (illegal memory + # access) on NVIDIA sm100 and show no perf win on CUDA, so keep them on ROCm + # only and fall back to ATEN. See + # https://github.com/pytorch/pytorch/issues/187081. + disable_triton_conv_bwd = device_type == "cuda" and not torch.version.hip + + conv_configs = V.choices.get_conv_configs(device_type) + dtype_size = input.get_dtype().itemsize + + has_triton_dw_choices = False + dw = None + choices_dw = [] + args_w = [] + layout_dw = conv_bwd_weight_layout(grad_out, input, weight, **kwargs) + if output_mask[1]: + if V.graph.layout_opt and ndim == 2: + V.graph.num_channels_last_conv += 1 + input = ir.ExternKernel.require_channels_last(input) # type: ignore[assignment] + grad_out = ir.ExternKernel.require_channels_last(grad_out) # type: ignore[assignment] + layout_dw = conv_bwd_weight_layout(grad_out, input, weight, **kwargs) + else: + guard = V.graph.sizevars.guard_int_seq + stride_order = ir.get_stride_order(guard(layout_dw.stride)) + input = ir.ExternKernel.require_stride_order(input, stride_order) # type: ignore[assignment] + grad_out = ir.ExternKernel.require_stride_order(grad_out, stride_order) # type: ignore[assignment] + + args_w = [input, grad_out] + + if ( + not disable_triton_conv_bwd + and torch._inductor.utils._use_conv_bwd_weight_autotune_backend("TRITON") + and use_triton_template(layout_dw) + and not transposed + and is_zeros(output_padding) + ): + for cfg in conv_configs( + sympy_product([input.get_size()[0], *input.get_size()[2:]]), + out_chan, + in_chan, + dtype_size=dtype_size, + ): + if ndim == 2: + has_triton_dw_choices = True + conv2d_bwd_weight_template.maybe_append_choice( + choices_dw, + input_nodes=(input, grad_out), + layout=layout_dw, + KERNEL_H=kernel_shape[0], + KERNEL_W=kernel_shape[1], + PADDING_H=padding[0], + PADDING_W=padding[1], + STRIDE_H=stride[0], + STRIDE_W=stride[1], + DILATION_H=dilation[0], + DILATION_W=dilation[1], + GROUPS=groups, + ALLOW_TF32=torch.backends.cudnn.allow_tf32, + num_stages=cfg.num_stages, + num_warps=cfg.num_warps, + **cfg.kwargs, + ) + + # TODO: backward weight 3D + + has_triton_dx_choices = False + dx = None + choices_dx = [] + args_x = [] + layout_dx = conv_bwd_input_layout(grad_out, input, weight, **kwargs) + if output_mask[0]: + if V.graph.layout_opt and ndim == 2: + V.graph.num_channels_last_conv += 1 + grad_out = ir.ExternKernel.require_channels_last(grad_out) # type: ignore[assignment] + weight = ir.ExternKernel.require_channels_last(weight) # type: ignore[assignment] + layout_dx = conv_bwd_input_layout(grad_out, input, weight, **kwargs) + else: + guard = V.graph.sizevars.guard_int_seq + stride_order = ir.get_stride_order(guard(layout_dx.stride)) + grad_out = ir.ExternKernel.require_stride_order(grad_out, stride_order) # type: ignore[assignment] + weight = ir.ExternKernel.require_stride_order(weight, stride_order) # type: ignore[assignment] + + args_x = [grad_out, weight] + + if ( + not disable_triton_conv_bwd + and torch._inductor.utils._use_conv_bwd_input_autotune_backend("TRITON") + and use_triton_template(layout_dx) + and not transposed + and is_zeros(output_padding) + ): + # TODO: Use the autotune configuration specific to backward convolution. + for cfg in conv_configs( + sympy_product([input.get_size()[0], *input.get_size()[2:]]), + out_chan, + in_chan, + dtype_size=dtype_size, + ): + if ndim == 2: + has_triton_dx_choices = True + conv2d_bwd_input_template.maybe_append_choice( + choices_dx, + input_nodes=(grad_out, weight), + layout=layout_dx, + KERNEL_H=kernel_shape[0], + KERNEL_W=kernel_shape[1], + PADDING_H=padding[0], + PADDING_W=padding[1], + STRIDE_H=stride[0], + STRIDE_W=stride[1], + DILATION_H=dilation[0], + DILATION_W=dilation[1], + GROUPS=groups, + ALLOW_TF32=torch.backends.cudnn.allow_tf32, + num_stages=cfg.num_stages, + num_warps=cfg.num_warps, + **cfg.kwargs, + ) + + # TODO: backward input 3D + + # Fallback when no TRITON choices available, i.e., ndim != 2, backend config = ATEN,... + if not has_triton_dx_choices and not has_triton_dw_choices: + return aten_convolution_backward_fallback( + grad_out, + input, + weight, + bias_sizes, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + output_mask, + ) + + if output_mask[1]: + if ( + torch._inductor.utils._use_conv_bwd_weight_autotune_backend("ATEN") + or not has_triton_dw_choices + ): + choices_dw.append( + ext_kn_aten_dw.bind( + input_nodes=args_w, + layout=layout_dw, + ordered_kwargs_for_cpp_kernel=[ + "w_shape", + "stride", + "padding", + "dilation", + "transposed", + "output_padding", + "groups", + ], + w_shape=weight.get_size(), + stride=stride, + padding=padding, + dilation=dilation, + transposed=transposed, + output_padding=output_padding, + groups=groups, + ) + ) + + # TODO: use_ck_conv_template for bwd conv + + dw, _ = autotune_select_algorithm( + "convolution_bwd_weight", choices_dw, args_w, layout_dw + ) + + if output_mask[0]: + if ( + torch._inductor.utils._use_conv_bwd_input_autotune_backend("ATEN") + or not has_triton_dx_choices + ): + choices_dx.append( + ext_kn_aten_dx.bind( + input_nodes=args_x, + layout=layout_dx, + ordered_kwargs_for_cpp_kernel=[ + "x_shape", + "stride", + "padding", + "dilation", + "transposed", + "output_padding", + "groups", + ], + x_shape=input.get_size(), + stride=stride, + padding=padding, + dilation=dilation, + transposed=transposed, + output_padding=output_padding, + groups=groups, + ) + ) + + # TODO: use_ck_conv_template for bwd conv + + dx, _ = autotune_select_algorithm( + "convolution_bwd_input", choices_dx, args_x, layout_dx + ) + + db = None + if output_mask[2] and bias_sizes is not None: + db = L[aten.sum](grad_out, axis=[0] + list(range(2, ndim + 2))) + + return (dx, dw, db) + + +def constrain_conv_bwd_to_fx_strides(fx_node, *args, **kwargs): + if fx_node.target != torch.ops.aten.convolution_backward.default: + raise AssertionError( + f"expected convolution_backward target, got {fx_node.target}" + ) + if V.graph.layout_opt: + return args, kwargs + else: + return constrain_to_fx_strides(fx_node, *args, **kwargs) + + +add_layout_constraint(aten.convolution_backward, constrain_conv_bwd_to_fx_strides) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/custom_op.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/custom_op.py new file mode 100644 index 0000000000000000000000000000000000000000..67dc9fcad7e893a621345928ad4b411eb024d121 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/custom_op.py @@ -0,0 +1,1347 @@ +# Owner(s): ["module: inductor"] + +import contextlib +import functools +import logging +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import Any, cast, Protocol +from typing_extensions import NotRequired, TypedDict + +import torch +from torch._dynamo.utils import counters +from torch._inductor.codegen.subgraph import SubgraphTemplate +from torch._inductor.ir import ( + Buffer, + FixedLayout, + ir_node_to_tensor, + Layout, + StorageBox, + TensorBox, +) +from torch._inductor.lowering import user_lowerings, validate_ir +from torch._inductor.select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, +) +from torch._inductor.utils import convert_symint_to_expr +from torch._inductor.virtualized import V + + +log = logging.getLogger(__name__) + +DEFAULT_RANGE_UPPER_BOUND = 65536 + + +class DispatchOnConfig(TypedDict): + """Range-based dispatch spec for register_custom_op_autotuning(dispatch_on=...).""" + + tensor_name: str + dim: int + range_upper_bound: NotRequired[int] + + +class _AutotuneChoice(Protocol): + """Winning-choice surface consumed after autotuning. + + Structurally satisfied by ChoiceCaller and its SubgraphChoiceCaller subclass; + lets callers read choice metadata without getattr fallbacks. + """ + + name: str + gm: torch.fx.GraphModule | None + config_patches: dict[str, Any] + decomposition: Callable[..., Any] | None + decomposition_kwargs: dict[str, Any] + layout: Layout + + def output_node(self) -> TensorBox: ... + + +@dataclass(frozen=True) +class RangeBounds: + """Inclusive range [start, end] for dimension-based dispatch.""" + + start: int + end: int | float # float('inf') for unbounded + + def __post_init__(self) -> None: + if self.start < 1: + raise ValueError(f"Range start must be >= 1, got {self.start}") + if self.end != float("inf") and self.start > self.end: + raise ValueError(f"Invalid range: start={self.start} > end={self.end}") + + def contains(self, value: int) -> bool: + if self.end == float("inf"): + return value >= self.start + return self.start <= value <= int(self.end) + + def __str__(self) -> str: + end_str = "inf" if self.end == float("inf") else str(int(self.end)) + return f"[{self.start}, {end_str}]" + + +@dataclass(frozen=True) +class ImplConfig: + """Implementation config with semantic identity (name + kwargs) for hashing.""" + + impl_name: str + impl_func: Callable[..., Any] = field(compare=False, hash=False, repr=False) + kwargs: dict[str, Any] = field(default_factory=dict) + config_patches: dict[str, Any] = field( + default_factory=dict, compare=False, hash=False, repr=False + ) + + def __hash__(self) -> int: + return hash((self.impl_name, tuple(sorted(self.kwargs.items())))) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ImplConfig): + return False + return self.impl_name == other.impl_name and self.kwargs == other.kwargs + + def __str__(self) -> str: + if self.kwargs: + kwargs_str = ", ".join(f"{k}={v}" for k, v in sorted(self.kwargs.items())) + return f"{self.impl_name}({kwargs_str})" + return self.impl_name + + +@dataclass +class RangeImplGroup: + """Groups non-adjacent ranges using the same implementation.""" + + impl_config: ImplConfig + ranges: list[RangeBounds] = field(default_factory=list) + + def add_range(self, range_bounds: RangeBounds) -> None: + self.ranges.append(range_bounds) + self.ranges.sort(key=lambda r: r.start) + + def __str__(self) -> str: + ranges_str = ", ".join(str(r) for r in self.ranges) + return f"{self.impl_config.impl_name}: {ranges_str}" + + @property + def impl_name(self) -> str: + return self.impl_config.impl_name + + @property + def impl_func(self) -> Callable[..., Any]: + return self.impl_config.impl_func + + @property + def impl_kwargs(self) -> dict[str, Any]: + return self.impl_config.kwargs + + @property + def config_patches(self) -> dict[str, Any]: + return self.impl_config.config_patches + + +def _detect_collective_ops(choices: list) -> bool: + """ + Detect if choices contain collective operations. + """ + from torch._inductor.utils import is_collective_op + + for choice in choices: + if not hasattr(choice, "gm") or choice.gm is None: + continue + + for node in choice.gm.graph.nodes: + if node.op == "call_function" and node.target is not None: + op_name = str(node.target) + + if is_collective_op(op_name) or is_collective_op( + f"torch.ops.{op_name}" + ): + return True + + return False + + +class CustomOpConfig: + """Config for custom op autotuning. + + Specifies optional decomposition function with parameter values. + Each config creates exactly one variant. + + Args: + decomposition: Optional functions to autotune. If not provided, default will be used. + config_patches: Optional dict of config patches to apply during kernel codegen + (e.g., {"coordinate_descent_tuning": True}) + **params: Parameters passed to the function + + Examples: + CustomOpConfig(attention_impl, head_dim=32, method='chunked') + CustomOpConfig(head_dim=32, method='chunked') + CustomOpConfig(decomposition, config_patches={"coordinate_descent_tuning": True}) + """ + + def __init__( + self, + decomposition: Callable[..., Any] | None = None, + config_patches: dict[str, Any] | None = None, + **params: Any, + ): + if decomposition is not None and not callable(decomposition): + raise TypeError( + f"decomposition must be callable, got {type(decomposition)}" + ) + + self.decomposition = decomposition + self.config_patches = config_patches or {} + self.params = params + + def get_decomposition( + self, default_impl: Callable[..., Any] | None = None + ) -> Callable[..., Any]: + """Return the decomposition function for this config. + When decomposition is not specified, return the default implementation. + """ + if self.decomposition is not None: + return self.decomposition + + if default_impl is not None and callable(default_impl): + return default_impl + + raise TypeError( + "No decomposition specified in config and no default implementation provided. " + "Please provide a decomposition function in CustomOpConfig." + ) + + def __repr__(self) -> str: + decomp_name = self.decomposition.__name__ if self.decomposition else "default" + if self.params: + params_str = ", ".join(f"{k}={v}" for k, v in self.params.items()) + return f"CustomOpConfig({decomp_name}, {params_str})" + return f"CustomOpConfig({decomp_name})" + + +__all__ = [ + "autotune_custom_op", + "register_custom_op_autotuning", + "CustomOpConfig", +] + + +def _extract_tensor_inputs( + args: tuple[Any, ...], + kwargs: dict[str, Any], + op_overload: torch._ops.OpOverload, +) -> tuple[list[Any], dict[str, Any]]: + """Extract tensor inputs from mixed args/kwargs. + Separates tensors (for autotuning input_nodes) from non-tensor parameters. + + Args: + args: Positional arguments (mix of tensors and scalars) + kwargs: Keyword arguments (mix of tensors and scalars) + op_overload: Custom Op overload to get parameter names from schema. + + Returns: + Tuple of (tensor_inputs_list, non_tensor_kwargs) + """ + tensor_inputs = [] + non_tensor_kwargs = {} + + # Get schema names and extend with fallback names for any extra args + schema_names = [arg.name for arg in op_overload._schema.arguments] + param_names = schema_names + [ + f"arg_{i}" for i in range(len(schema_names), len(args)) + ] + + for i, arg in enumerate(args): + if isinstance(arg, (TensorBox, Buffer, StorageBox)): + tensor_inputs.append(arg) + else: + non_tensor_kwargs[param_names[i]] = arg + + for key, value in kwargs.items(): + if isinstance(value, (TensorBox, Buffer, StorageBox)): + tensor_inputs.append(value) + else: + non_tensor_kwargs[key] = value + + return tensor_inputs, non_tensor_kwargs + + +def _merge_config_and_runtime_kwargs( + config_params: dict[str, Any], + runtime_kwargs: dict[str, Any], +) -> dict[str, Any]: + """Merge config parameters with runtime kwargs. Config params take precedence, + since they represent the values being autotuned. + + Args: + config_params: Parameters from CustomOpConfig (autotuning knobs) + runtime_kwargs: Runtime non-tensor kwargs from _extract_tensor_inputs + + Returns: + Merged kwargs dictionary with config values taking precedence + """ + merged_kwargs = runtime_kwargs.copy() + merged_kwargs.update(config_params) + return merged_kwargs + + +def _adapt_user_input_gen_fns( + inputs: list[Any], + op_overload: torch._ops.OpOverload, + user_input_gen_fns: dict[str, Callable[[torch.Tensor], torch.Tensor]], +) -> dict[int, Callable[[Any], torch.Tensor]]: + """Convert user input generators from name-based to index-based format. + Inductor autotune's input_gen_fns expects index of arg_names as key. + """ + arg_names = [arg.name for arg in op_overload._schema.arguments] + name_to_index = {name: i for i, name in enumerate(arg_names)} + index_based_fns = {} + + for name, gen_fn in user_input_gen_fns.items(): + if name in name_to_index: + index_based_fns[name_to_index[name]] = gen_fn + else: + raise ValueError( + f"Unknown argument name '{name}' in input_gen_fns. " + f"Available argument names: {list(name_to_index.keys())}" + ) + + def create_internal_input_gen_fn( + user_function: Callable[[torch.Tensor], torch.Tensor], arg_name: str + ) -> Callable[[Any], torch.Tensor]: + """Create internal input generator that converts IR buffer to user's fake tensor.""" + + def internal_input_gen_fn(ir_buffer: Any) -> torch.Tensor: + fake_tensor = ir_node_to_tensor(ir_buffer, replace_symbols_with_hints=True) + if fake_tensor is None: + raise AssertionError("ir_node_to_tensor returned None") + return user_function(fake_tensor) + + return internal_input_gen_fn + + return { + i: create_internal_input_gen_fn( + user_gen_fn, arg_names[i] if i < len(arg_names) else f"arg_{i}" + ) + for i, user_gen_fn in index_based_fns.items() + if i < len(inputs) + } + + +def _group_ranges_by_impl( + range_to_best_impl: dict[RangeBounds, ImplConfig], +) -> list[RangeImplGroup]: + """Group ranges by implementation using semantic identity (name + kwargs).""" + from torch._inductor import config + + if not range_to_best_impl: + return [] + + # Test mode: skip grouping to force torch.cond dispatch path + if config.test_configs.force_no_impl_grouping: + log.info("Test mode: skipping impl grouping, each range is separate group") + groups = [] + for range_bounds, impl_config in sorted( + range_to_best_impl.items(), key=lambda x: x[0].start + ): + group = RangeImplGroup(impl_config) + group.add_range(range_bounds) + groups.append(group) + return groups + + # Group ranges by impl_config (uses __hash__ and __eq__ based on semantic identity) + impl_to_group: dict[ImplConfig, RangeImplGroup] = {} + + for range_bounds, impl_config in range_to_best_impl.items(): + if impl_config not in impl_to_group: + impl_to_group[impl_config] = RangeImplGroup(impl_config) + impl_to_group[impl_config].add_range(range_bounds) + + # Sort groups by first range start for deterministic codegen + groups = sorted(impl_to_group.values(), key=lambda g: g.ranges[0].start) + + # Log grouping info + original_count = len(range_to_best_impl) + grouped_count = len(groups) + + if grouped_count < original_count: + log.info( + "Implementation grouping: reduced from %d ranges to %d impl groups", + original_count, + grouped_count, + ) + + return groups + + +def _create_ranges_from_split_points( + split_points: list[int], +) -> list[tuple[int, int] | tuple[int, float]]: + """Convert split points into ranges for autotuning dispatch. + + Example: + split_points=[512, 2048] + returns: + [(1, 512), (513, 2048), (2049, float('inf'))] + """ + ranges: list[tuple[int, int] | tuple[int, float]] = [] + start = 1 + + for split_point in split_points: + ranges.append((start, split_point)) + start = split_point + 1 + + ranges.append((start, float("inf"))) + + return ranges + + +def _create_range_input_gen_fn( + base_gen_fn: Callable[[torch.Tensor], torch.Tensor], + dim_index: int, + range_start: int, + range_end: int | float, + range_upper_bound: int, +) -> Callable[[torch.Tensor], torch.Tensor]: + """Create input generator that modifies target dimension to top of range. + range_upper_bound: Size to use for benchmarking when range_end is unbounded. + Default is DEFAULT_RANGE_UPPER_BOUND = 65536 + """ + from torch._inductor.ir import get_fill_order + from torch._inductor.kernel.flex.common import construct_strides + + target_dim = range_upper_bound if range_end == float("inf") else int(range_end) + + def constrained_gen_fn(fake_tensor: torch.Tensor) -> torch.Tensor: + result = base_gen_fn(fake_tensor) + shape = list(result.shape) + shape[dim_index] = target_dim + + # We modified the shape of the result, so we need to recalculate the strides + # TODO: Refine this to a better way to more directly preserve strides + fill_order = get_fill_order(result.stride(), shape_env=None) + new_stride = construct_strides(shape, fill_order) + + storage_size = sum((s - 1) * st for s, st in zip(shape, new_stride)) + 1 + storage = torch.randn(storage_size, dtype=result.dtype, device=result.device) + return storage.as_strided(shape, tuple(new_stride)) + + return constrained_gen_fn + + +def _default_input_gen_fn(fake_tensor: torch.Tensor) -> torch.Tensor: + """Default input generator that creates a real tensor matching the fake tensor's shape.""" + return torch.randn( + fake_tensor.shape, dtype=fake_tensor.dtype, device=fake_tensor.device + ) + + +def _create_fallback_choice( + op_overload: torch._ops.OpOverload, +) -> ExternKernelChoice: + """Create or reuse fallback choice that calls the op eagerly. + + Since kwargs are passed at bind time via maybe_append_choice rather than + baked into the kernel, the same ExternKernelChoice is reused across + compilations for the same op_overload. + """ + fallback_name = ( + f"{op_overload.name().replace('::', '_').replace('.', '_')}_fallback" + ) + + existing = ExternKernelChoice.lookup(fallback_name) + if existing is not None: + return existing + + return ExternKernelChoice( + kernel=op_overload, + name=fallback_name, + has_out_variant=False, + op_overload=op_overload, + use_fallback_kernel=True, + ) + + +def autotune_custom_op( + name: str, + decompositions: list[Callable[..., Any]], + inputs: list[torch.fx.Node], + non_tensor_args: list[dict[str, Any]], + op_overload: torch._ops.OpOverload, + user_input_gen_fns: dict[str, Callable[[torch.Tensor], torch.Tensor]] | None = None, + config_patches_list: list[dict[str, Any]] | None = None, + min_speedup_threshold: float = 1.0, + benchmark_with_cudagraphs: bool = False, +) -> tuple[TensorBox, _AutotuneChoice]: + """Autotune custom operations by comparing multiple decomposition implementations. + + Currently supports SINGLE OUTPUT custom ops only. + TODO: Add support for multiple output custom ops (tuple/list returns). + + This function generates multiple implementation choices for a custom operation and + uses Inductor's autotuning system to select the best performing variant at runtime. + After selecting the best choice, applies inline fusion if the winning choice has a graph. + + Args: + name: Unique identifier for the autotuning operation + decompositions: List of alternative implementation functions to benchmark + inputs: Input tensor IR nodes from compilation (TensorBox/Buffer objects) + non_tensor_args: List of kwargs dicts, paired with corresponding decompositions arg + op_overload: OpOverload of the custom op, used as fallback implementation + user_input_gen_fns: Optional custom input generators for benchmarking. + Maps input indices to functions that take fake tensors + and return real tensors for performance measurement. + + Returns: + Tuple of (IR node representing the optimized operation result, winning choice) + + Raises: + TypeError: If decompositions is not a list/tuple + RuntimeError: If no inputs or no valid choices generated + """ + if not isinstance(decompositions, (list, tuple)): + raise TypeError( + f"decompositions must be a list or tuple of callables, got {type(decompositions)}" + ) + + if not inputs: + raise RuntimeError(f"Custom op '{name}' requires tensor inputs for autotuning") + + if len(decompositions) != len(non_tensor_args): + raise ValueError( + f"decompositions and non_tensor_args must have same length, " + f"got {len(decompositions)} decompositions and {len(non_tensor_args)} kwargs" + ) + + # Convert user input generation functions BEFORE creating choices + input_gen_fns: dict[int, Callable[[Any], torch.Tensor]] = {} + if user_input_gen_fns: + input_gen_fns = _adapt_user_input_gen_fns( + inputs, op_overload, user_input_gen_fns + ) + + template = SubgraphTemplate(name=name) + choices = template.generate_custom_op_choices( + name=name, + decompositions=decompositions, + # pyrefly: ignore [bad-argument-type, no-matching-overload] + input_nodes=list(inputs), + non_tensor_args=non_tensor_args, + input_gen_fns=input_gen_fns if input_gen_fns else None, + config_patches_list=config_patches_list, + ) + + # Add fallback choice that calls the op eagerly (not through inductor lowering) + # This provides a baseline to compare decompositions against + from torch._inductor import config + + fallback_kwargs = non_tensor_args[0] if non_tensor_args else {} + + with V.fake_mode: + # pyrefly: ignore [no-matching-overload] + fake_inputs = [ir_node_to_tensor(inp) for inp in inputs] + fake_output = op_overload(*fake_inputs, **fallback_kwargs) + + output_size = tuple(convert_symint_to_expr(s) for s in fake_output.shape) + output_stride = tuple(convert_symint_to_expr(s) for s in fake_output.stride()) + + fallback_choice = _create_fallback_choice(op_overload) + fallback_choice.maybe_append_choice( + choices=choices, + input_nodes=list(inputs), + layout=FixedLayout( + device=fake_output.device, + dtype=fake_output.dtype, + size=output_size, + stride=output_stride, + ), + **fallback_kwargs, + ) + + if not choices: + raise RuntimeError(f"No valid choices generated for {name}") + + is_collective = _detect_collective_ops(choices) + + # Run autotuning and get both result and winning choice. The selector returns + # the base ChoiceCaller type, so cast to the structural winning-choice surface. + selected_result, winning_choice_base = autotune_select_algorithm( + name=name, + choices=choices, + input_nodes=list(inputs), + layout=choices[0].layout, + input_gen_fns=input_gen_fns, + is_collective=is_collective, + min_speedup_threshold=min_speedup_threshold, + benchmark_with_cudagraphs=benchmark_with_cudagraphs, + ) + winning_choice: _AutotuneChoice = cast(_AutotuneChoice, winning_choice_base) + + # Test mode: force specific choice to win + force_choice = config.test_configs.force_custom_op_decomposition + if force_choice is True and winning_choice.gm is None: + # Force decomposition: pick first choice with a graph + for choice in choices: + if choice.gm is not None: + log.info( + "Test mode: forcing decomposition %s over fallback", + choice.name, + ) + winning_choice = choice + selected_result = choice.output_node() + break + elif force_choice is False and winning_choice.gm is not None: + # Force fallback: pick first choice without a graph + for choice in choices: + if choice.gm is None: + log.info( + "Test mode: forcing fallback %s over decomposition", + choice.name, + ) + winning_choice = choice + selected_result = choice.output_node() + break + + # Always inline when winning_choice has a graph; callers extract choice metadata separately + if winning_choice.gm is not None: + log.debug( + "Inlining winning choice: %s (name=%s)", + winning_choice.name, + name, + ) + from torch._inductor.codegen.subgraph import inline_subgraph_to_ir_nodes + + ops_before = len(V.graph.operations) + result = inline_subgraph_to_ir_nodes(winning_choice.gm, inputs, name) + + # Tag inlined operations with config_patches from the winning choice + config_patches = winning_choice.config_patches + if config_patches: + for op in V.graph.operations[ops_before:]: + op.set_config_patches(config_patches.copy()) + + return result, winning_choice + + log.debug( + "Winning choice does not support inlining: %s (name=%s)", + winning_choice.name, + name, + ) + return selected_result, winning_choice + + +def _generate_dynamic_configs( + tensor_inputs: list[Buffer], + config_generator: Callable[[dict[str, torch.Tensor]], list[CustomOpConfig]], + op_overload: torch._ops.OpOverload, + operation_name: str, +) -> list[CustomOpConfig]: + """Generate configs dynamically based on input tensors at lowering time.""" + # Get parameter names from op schema instead of impl signature + schema = op_overload._schema + param_names = [arg.name for arg in schema.arguments if not arg.kwarg_only] + + with V.fake_mode: + fake_tensors = [ir_node_to_tensor(inp) for inp in tensor_inputs] + + fake_tensors_dict = dict(zip(param_names, fake_tensors)) + + configs = config_generator(fake_tensors_dict) + + if not isinstance(configs, (list, tuple)): + raise TypeError( + f"config_generator must return a list or tuple of CustomOpConfig, " + f"got {type(configs)}" + ) + if not configs: + log.info( + "config_generator returned empty list for %s, will use default lowering", + operation_name, + ) + return [] + + return list(configs) + + +def _prepare_configs_and_decompositions( + processed_configs: list[CustomOpConfig] | None, + config_generator: Callable[[dict[str, torch.Tensor]], list[CustomOpConfig]] | None, + tensor_inputs: list[Any], + default_impl: Callable[..., Any], + op_overload: torch._ops.OpOverload, + runtime_kwargs: dict[str, Any], + name: str, +) -> tuple[list[Callable], list[dict[str, Any]], list[dict[str, Any]]]: + """Prepare decompositions and merged kwargs from configs. + + Handles both static configs and dynamic config generation. + Merges config params with runtime kwargs (runtime takes precedence). + """ + # Get configs: either generate dynamically or use static configs + if config_generator is not None: + configs_to_use = _generate_dynamic_configs( + tensor_inputs, config_generator, op_overload, name + ) + else: + if processed_configs is None: + raise AssertionError("processed_configs must not be None") + configs_to_use = processed_configs + + # Prepare decompositions and kwargs for autotuning + decompositions = [] + non_tensor_args = [] + config_patches_list = [] + + for cfg in configs_to_use: + decomp = cfg.get_decomposition(default_impl=default_impl) + decompositions.append(decomp) + + # Merge config params with runtime kwargs (runtime takes precedence) + merged_kwargs = _merge_config_and_runtime_kwargs(cfg.params, runtime_kwargs) + non_tensor_args.append(merged_kwargs) + + # Collect config_patches for each config + config_patches_list.append(cfg.config_patches) + + return decompositions, non_tensor_args, config_patches_list + + +def _standard_lowering_fn( + processed_configs: list[CustomOpConfig], + default_impl: Callable[..., Any], + name: str, + op_overload: torch._ops.OpOverload, + input_gen_fns: dict[str, Callable[[torch.Tensor], torch.Tensor]] | None, + tensor_inputs: list[Any], + runtime_kwargs: dict[str, Any], + config_generator: Callable[[dict[str, torch.Tensor]], list[CustomOpConfig]] + | None = None, + min_speedup_threshold: float = 1.0, + benchmark_with_cudagraphs: bool = False, +) -> Any: + """Standard autotuning lowering function. + + Returns None if no configs/decompositions available, signaling caller to + use normal lowering. + """ + decompositions, non_tensor_args, config_patches_list = ( + _prepare_configs_and_decompositions( + processed_configs, + config_generator, + tensor_inputs, + default_impl, + op_overload, + runtime_kwargs, + name, + ) + ) + + # If no decompositions, signal caller to use normal lowering + if not decompositions: + return None + + result, _ = autotune_custom_op( + name=name, + decompositions=decompositions, + inputs=tensor_inputs, + non_tensor_args=non_tensor_args, + config_patches_list=config_patches_list, + op_overload=op_overload, + user_input_gen_fns=input_gen_fns, + min_speedup_threshold=min_speedup_threshold, + benchmark_with_cudagraphs=benchmark_with_cudagraphs, + ) + + validate_ir(result) + return result + + +def _apply_config_patches_recursive( + operations: list, + config_patches: dict[str, Any], +) -> None: + """Apply config_patches to operations, including those inside subgraphs.""" + for op in operations: + if hasattr(op, "set_config_patches"): + op.set_config_patches(config_patches.copy()) + + # Recurse into any subgraphs (Switch, WhileLoop, InvokeSubgraph, etc.) + for subgraph in op.get_subgraphs(): + if subgraph.graph: + _apply_config_patches_recursive( + subgraph.graph.operations, config_patches + ) + + +def _lower_single_impl( + impl: Callable[..., Any], + impl_kwargs: dict[str, Any], + runtime_kwargs: dict[str, Any], + tensor_inputs: list[Any], + name: str, + config_patches: dict[str, Any] | None = None, +) -> Any: + """Lower a single implementation by tracing and inlining it. + + Uses error_on_new_guards() during tracing to detect if the impl adds guards. + Returns None if the impl adds guards, signaling caller to skip this choice. + """ + from torch._inductor.codegen.subgraph import inline_subgraph_to_ir_nodes + from torch.fx.experimental.proxy_tensor import make_fx + from torch.fx.experimental.symbolic_shapes import _ShapeEnvGuardError + + from ..decomposition import select_decomp_table + + merged_kwargs = _merge_config_and_runtime_kwargs(impl_kwargs, runtime_kwargs) + + def impl_wrapper(*tensors): + return impl(*tensors, **merged_kwargs) + + shape_env = V.fake_mode.shape_env + + with V.fake_mode: + fake_inputs = tuple(ir_node_to_tensor(inp) for inp in tensor_inputs) + decomposition_table = select_decomp_table() + + context = ( + shape_env.error_on_new_guards + if shape_env is not None + else contextlib.nullcontext + ) + try: + with context(): + impl_gm = make_fx( + impl_wrapper, + decomposition_table=decomposition_table, + tracing_mode="symbolic", + )(*fake_inputs) + except (_ShapeEnvGuardError, AssertionError) as e: + is_guard_error = isinstance(e, _ShapeEnvGuardError) or ( + isinstance(e, AssertionError) + and "Guard attempted while ShapeEnv guards are frozen" in str(e) + ) + if not is_guard_error: + raise + log.info( + "Implementation %s adds guards, skipping custom op lowering", + impl.__name__, + ) + counters["inductor"]["custom_op_decomp_guard_skips"] += 1 + return None + + log.info("Inlining implementation: %s", impl.__name__) + ops_before = len(V.graph.operations) + result = inline_subgraph_to_ir_nodes(impl_gm, tensor_inputs, name) + + if config_patches: + _apply_config_patches_recursive(V.graph.operations[ops_before:], config_patches) + + validate_ir(result) + return result + + +def _range_based_lowering_fn( + processed_configs: list[CustomOpConfig], + default_impl: Callable[..., Any], + name: str, + op_overload: torch._ops.OpOverload, + input_gen_fns: dict[str, Callable[[torch.Tensor], torch.Tensor]] | None, + tensor_name: str, + dim_index: int, + ranges: list[tuple[int, int | float]], + tensor_inputs: list[Any], + runtime_kwargs: dict[str, Any], + range_upper_bound: int, + config_generator: Callable[[dict[str, torch.Tensor]], list[CustomOpConfig]] + | None = None, + min_speedup_threshold: float = 1.0, + benchmark_with_cudagraphs: bool = False, +) -> Any: + """Range-based autotuning lowering function.""" + from torch._inductor.codegen.subgraph import inline_subgraph_to_ir_nodes + from torch.fx.experimental.proxy_tensor import make_fx + + from ..decomposition import select_decomp_table + + log.info("=== Range-based Autotuning for %s ===", name) + log.info("Dispatch on: %s[%d], Ranges: %s", tensor_name, dim_index, ranges) + + decompositions, non_tensor_args, config_patches_list = ( + _prepare_configs_and_decompositions( + processed_configs, + config_generator, + tensor_inputs, + default_impl, + op_overload, + runtime_kwargs, + name, + ) + ) + + range_to_best_impl_map: dict[RangeBounds, ImplConfig] = {} + + # Benchmark each range and collect winning implementations + for range_start, range_end in ranges: + if input_gen_fns and tensor_name in input_gen_fns: + base_gen_fn = input_gen_fns[tensor_name] + else: + base_gen_fn = _default_input_gen_fn + + range_gen_fn = _create_range_input_gen_fn( + base_gen_fn, dim_index, range_start, range_end, range_upper_bound + ) + range_input_gen_fns = {**(input_gen_fns or {}), tensor_name: range_gen_fn} + + range_name = f"{name}_range_{int(range_start)}_{int(range_end) if range_end != float('inf') else 'inf'}" + + # pyrefly: ignore [not-iterable] + autotuned_result, winning_choice = autotune_custom_op( + name=range_name, + decompositions=decompositions, + inputs=tensor_inputs, + non_tensor_args=non_tensor_args, + op_overload=op_overload, + user_input_gen_fns=range_input_gen_fns, + min_speedup_threshold=min_speedup_threshold, + benchmark_with_cudagraphs=benchmark_with_cudagraphs, + config_patches_list=config_patches_list, + ) + + if winning_choice.decomposition is not None: + winning_impl = winning_choice.decomposition + winning_kwargs = winning_choice.decomposition_kwargs + else: + # Fallback was selected (ExternKernelCaller) + winning_impl = default_impl + winning_kwargs = non_tensor_args[0] if non_tensor_args else {} + log.info( + " Range [%s, %s]: Fallback (default_impl) selected", + range_start, + range_end if range_end != float("inf") else "inf", + ) + + winning_config_patches = winning_choice.config_patches or {} + + # Create dataclass instances for cleaner code + range_bounds = RangeBounds(range_start, range_end) + impl_config = ImplConfig( + impl_name=winning_impl.__name__, + impl_func=winning_impl, + kwargs=winning_kwargs, + config_patches=winning_config_patches, + ) + range_to_best_impl_map[range_bounds] = impl_config + + log.info( + " Range %s -> %s", + range_bounds, + impl_config.impl_name, + ) + + # Group ranges by implementation + from torch.fx.experimental.symbolic_shapes import _ShapeEnvGuardError + + impl_groups = _group_ranges_by_impl(range_to_best_impl_map) + + log.info("After grouping by implementation: %d impl groups", len(impl_groups)) + for group in impl_groups: + log.info(" %s", group) + + # If only one impl group remains, just inline that implementation + if len(impl_groups) == 1: + group = impl_groups[0] + log.info("Only one implementation after grouping, directly inlining") + return _lower_single_impl( + group.impl_func, + group.impl_kwargs, + runtime_kwargs, + tensor_inputs, + name, + config_patches=group.config_patches, + ) + + def dispatch_fn(*fake_tensors): + """Build nested torch.cond dispatch: cond(pred1, impl1, cond(pred2, impl2, ...)).""" + num_impl_groups = len(impl_groups) + if num_impl_groups < 2: + raise RuntimeError( + f"dispatch_fn requires at least 2 impl groups, got {num_impl_groups}" + ) + + dim_value = fake_tensors[0].size(dim_index) + + def build_range_predicate(ranges_list: list[RangeBounds]) -> torch.Tensor: + predicates = [] + for rb in ranges_list: + end = int(rb.end) if rb.end != float("inf") else None + if end is None: + predicates.append(dim_value >= rb.start) + else: + predicates.append((dim_value >= rb.start) & (dim_value <= end)) + + result = predicates[0] + for pred in predicates[1:]: + result = result | pred + return result # pyrefly: ignore [bad-return] + + def build_nested_cond(idx: int): + if idx >= num_impl_groups: + raise RuntimeError(f"Invalid impl group index: {idx}") + + group = impl_groups[idx] + merged_kwargs = _merge_config_and_runtime_kwargs( + group.impl_kwargs, runtime_kwargs + ) + + @torch._dynamo.dont_skip_tracing + def group_fn(*ops): + return group.impl_func(*ops, **merged_kwargs) + + if idx == num_impl_groups - 1: + return group_fn + + next_fn = build_nested_cond(idx + 1) + + @torch._dynamo.dont_skip_tracing + def cond_wrapper(*ops, _ranges=group.ranges): + return torch.cond( + pred=build_range_predicate(_ranges), + true_fn=group_fn, + false_fn=next_fn, + operands=ops, + ) + + return cond_wrapper + + return build_nested_cond(0)(*fake_tensors) + + with V.fake_mode: + fake_inputs = tuple(ir_node_to_tensor(inp) for inp in tensor_inputs) + decomposition_table = select_decomp_table() + shape_env = V.fake_mode.shape_env + + log.info("Tracing torch.cond dispatch with symbolic shapes...") + + try: + context = ( + shape_env.error_on_new_guards + if shape_env is not None + else contextlib.nullcontext + ) + with context(): + dispatch_gm = make_fx( + dispatch_fn, + decomposition_table=decomposition_table, + tracing_mode="symbolic", + )(*fake_inputs) + + log.info("Successfully traced torch.cond dispatch") + log.info("Traced graph:\n%s", dispatch_gm.graph) + + except (_ShapeEnvGuardError, AssertionError) as e: + is_guard_error = isinstance(e, _ShapeEnvGuardError) or ( + isinstance(e, AssertionError) + and "Guard attempted while ShapeEnv guards are frozen" in str(e) + ) + if not is_guard_error: + raise + log.info("Dispatch function adds guards, skipping custom op lowering") + counters["inductor"]["custom_op_decomp_guard_skips"] += 1 + return None + + except Exception: + log.exception("make_fx tracing FAILED") + raise + + ops_before = len(V.graph.operations) + result = inline_subgraph_to_ir_nodes(dispatch_gm, tensor_inputs, f"{name}_dispatch") + + # Apply config_patches from all impl groups to inlined operations + # TODO - consider conflicting patches + merged_patches: dict[str, Any] = {} + for group in impl_groups: + merged_patches.update(group.config_patches) + if merged_patches: + _apply_config_patches_recursive(V.graph.operations[ops_before:], merged_patches) + + log.info( + "Successfully created torch.cond dispatch for %d impl groups", len(impl_groups) + ) + + validate_ir(result) + return result + + +def _create_autotuning_lowering( + processed_configs: list[CustomOpConfig], + default_impl: Callable[..., Any], + name: str, + op_overload: torch._ops.OpOverload, + input_gen_fns: dict[str, Callable[[torch.Tensor], torch.Tensor]] | None, + range_upper_bound: int, + is_range_based: bool = False, + config_generator: Callable[[dict[str, torch.Tensor]], list[CustomOpConfig]] + | None = None, + dispatch_on: tuple[str, int] | None = None, + split_points: list[int] | None = None, + min_speedup_threshold: float = 1.0, + benchmark_with_cudagraphs: bool = False, +) -> Callable[..., Any]: + """Create the lowering function for autotuning.""" + if not is_range_based: + # Standard autotuning path + @functools.wraps(op_overload) + def standard_lowering_wrapper(*args: Any, **kwargs: Any) -> Any: + tensor_inputs, runtime_kwargs = _extract_tensor_inputs( + args, kwargs, op_overload + ) + return _standard_lowering_fn( + processed_configs=processed_configs, + default_impl=default_impl, + name=name, + op_overload=op_overload, + input_gen_fns=input_gen_fns, + tensor_inputs=tensor_inputs, + runtime_kwargs=runtime_kwargs, + config_generator=config_generator, + min_speedup_threshold=min_speedup_threshold, + benchmark_with_cudagraphs=benchmark_with_cudagraphs, + ) + + return standard_lowering_wrapper + + # Range-based autotuning path + # pyrefly: ignore [not-iterable] + tensor_name, dim_index = dispatch_on + # pyrefly: ignore [bad-argument-type] + ranges = _create_ranges_from_split_points(split_points) + + @functools.wraps(op_overload) + def range_based_lowering_wrapper(*args: Any, **kwargs: Any) -> Any: + tensor_inputs, runtime_kwargs = _extract_tensor_inputs( + args, kwargs, op_overload + ) + return _range_based_lowering_fn( + processed_configs=processed_configs, + default_impl=default_impl, + name=name, + op_overload=op_overload, + input_gen_fns=input_gen_fns, + tensor_name=tensor_name, + dim_index=dim_index, + ranges=ranges, + tensor_inputs=tensor_inputs, + runtime_kwargs=runtime_kwargs, + range_upper_bound=range_upper_bound, + config_generator=config_generator, + min_speedup_threshold=min_speedup_threshold, + benchmark_with_cudagraphs=benchmark_with_cudagraphs, + ) + + return range_based_lowering_wrapper + + +def register_custom_op_autotuning( + custom_op: torch._library.custom_ops.CustomOpDef | torch._ops.OpOverload, + configs: list[CustomOpConfig] | list[Callable[..., Any]] | None = None, + config_generator: Callable[[dict[str, torch.Tensor]], list[CustomOpConfig]] + | None = None, + name: str | None = None, + input_gen_fns: dict[str, Callable[[torch.Tensor], torch.Tensor]] | None = None, + dispatch_on: DispatchOnConfig | None = None, + split_points: list[int] | None = None, + min_speedup_threshold: float = 1.0, + benchmark_with_cudagraphs: bool = False, +) -> None: + """Register custom op for autotuning with custom_op configs where each config + specifies a decomposition implementation function with its parameter values. + It also supports Range-based autotuning to benchmark per range and generate + runtime dispatch. + + Args: + custom_op: Custom operation (CustomOpDef from @torch.library.custom_op) or + OpOverload (e.g., torch.ops.aten.mm.default) + configs: List of CustomOpConfig objects for static inputs. Mutually exclusive with config_generator. + config_generator: Dynamic config generator function that takes a dict mapping + parameter names to fake tensors, and returns list[CustomOpConfig] + based on input tensor properties. Mutually exclusive with configs. + name: Operation name (default: "{op_name}_autotuned") + input_gen_fns: Custom input generators for benchmarking + dispatch_on: Dict for range-based dispatch with keys: + - 'tensor_name': Name of tensor parameter to dispatch on + - 'dim': Dimension index to check size + - 'unbounded_size' (optional): Benchmark size for the unbounded (last) range, such + as [2048, inf] -> [2048, unbounded_size]. Set based on your expected workload size. + Default is DEFAULT_RANGE_UPPER_BOUND=65536. + split_points: List of range endpoints in ascending order for range-based autotuning + min_speedup_threshold: Only pick a non-fallback choice if it beats the fallback + by at least this ratio. Default is 1.0 (any speedup wins). Set to e.g. 1.1 + to require 10% speedup over fallback. + benchmark_with_cudagraphs: If True, benchmark the fallback kernel using CUDA graph + capture and replay for fair comparison with compiled kernels. Default is False. + + The default/fallback implementation is automatically derived: + - For CustomOpDef: Uses the decorated function + - For OpOverload: Traces the op call, which falls through to normal inductor lowering + + Examples: + # Static configs + @torch.library.custom_op("mylib::attention", mutates_args=()) + def my_attention(query, key, value, head_dim=32): + ... + + register_custom_op_autotuning( + my_attention, + configs=[ + CustomOpConfig(attention_impl, head_dim=32, method='chunked'), + CustomOpConfig(attention_impl, head_dim=64, method='tiled'), + CustomOpConfig(head_dim=128), # No decomposition specified, use default + ], + input_gen_fns={ + "query": lambda fake: torch.randn_like(fake, device='cuda'), + "key": lambda fake: torch.randn_like(fake, device='cuda'), + "value": lambda fake: torch.randn_like(fake, device='cuda'), + }, + ) + + # Dynamic config generation based on input tensor properties + def generate_k_split_configs(fake_tensors: dict[str, torch.Tensor]) -> list[CustomOpConfig]: + # Access tensor shapes, dtypes, devices, etc. + m, k = fake_tensors["mat1"].shape + _, n = fake_tensors["mat2"].shape + k_splits = ... # compute possible k splits based on tensor properties + return [CustomOpConfig(k_splits=k) for k in k_splits] + + register_custom_op_autotuning( + matmul_decomposeK_op, + config_generator=generate_k_split_configs, + input_gen_fns={...}, + ) + + Range-based Example: + register_custom_op_autotuning( + my_op, + configs=[CustomOpConfig(impl1), CustomOpConfig(impl2), CustomOpConfig(impl3)], + dispatch_on={ + # Dispatch based on x.shape[1] + "tensor_name": "x", + "dim": 1, + # Optional Benchmark size used for the unbounded range [2049, inf]. + # Since inf is not a concrete value, we use range_upper_bound as the benchmark size. + # Default value is 65536 (DEFAULT_RANGE_UPPER_BOUND) if not provided. + "range_upper_bound": 8192, + }, + split_points=[512, 2048], # Creates ranges: [1,512], [513,2048], [2049, 8192] + ) + """ + from torch._library.custom_ops import CustomOpDef + + # Handle both CustomOpDef and OpOverload - derive impl_fn automatically + # Both cases call through op_overload so fake handlers are used during tracing + if isinstance(custom_op, CustomOpDef): + op_overload = custom_op._opoverload + elif isinstance(custom_op, torch._ops.OpOverload): + op_overload = custom_op + else: + raise TypeError( + f"custom_op must be a CustomOpDef or OpOverload, got {type(custom_op)}." + ) + + # impl_fn calls through op_overload so fake handlers are used during tracing + def impl_fn(*args, **kwargs): + return op_overload(*args, **kwargs) + + # Validate configs and config_generator are mutually exclusive + if configs is not None and config_generator is not None: + raise ValueError( + "Cannot specify both 'configs' and 'config_generator'. " + "Use 'config_generator' for shape-dependent configs." + ) + + if configs is None and config_generator is None: + raise ValueError("Must specify either 'configs' or 'config_generator'") + + # Process and validate static configs at registration time + static_configs = None + if configs is not None: + if not isinstance(configs, (list, tuple)): + raise TypeError(f"configs must be a list or tuple, got {type(configs)}") + + static_configs = [] + for cfg in configs: + if isinstance(cfg, CustomOpConfig): + static_configs.append(cfg) + else: + raise TypeError( + f"Each config must be a CustomOpConfig object, got {type(cfg)}" + ) + + if not static_configs: + raise ValueError("At least one config must be provided") + + if name is None: + name = f"{op_overload._name}_autotuned" + + # Validate range-based parameters + is_range_based = dispatch_on is not None or split_points is not None + dispatch_on_tuple: tuple[str, int] | None = None + range_upper_bound = DEFAULT_RANGE_UPPER_BOUND + if is_range_based: + if dispatch_on is None or split_points is None: + raise ValueError( + "Both dispatch_on and split_points must be specified for range-based autotuning" + ) + if not isinstance(dispatch_on, dict): + raise ValueError( + "dispatch_on must be a dict with 'tensor_name' and 'dim' keys, " + f"e.g., {{'tensor_name': 'x', 'dim': 1}}. Got: {type(dispatch_on)}" + ) + if "tensor_name" not in dispatch_on or "dim" not in dispatch_on: + raise ValueError( + "dispatch_on must contain 'tensor_name' and 'dim' keys, " + f"e.g., {{'tensor_name': 'x', 'dim': 1}}. Got keys: {list(dispatch_on.keys())}" + ) + if not isinstance(dispatch_on["tensor_name"], str): + raise ValueError( + f"dispatch_on['tensor_name'] must be a string (tensor parameter name), " + f"got {type(dispatch_on['tensor_name'])}" + ) + if not isinstance(dispatch_on["dim"], int): + raise ValueError( + f"dispatch_on['dim'] must be an integer (dimension index), " + f"got {type(dispatch_on['dim'])}" + ) + dispatch_on_tuple = (dispatch_on["tensor_name"], dispatch_on["dim"]) + range_upper_bound = dispatch_on.get( + "range_upper_bound", DEFAULT_RANGE_UPPER_BOUND + ) + if not isinstance(range_upper_bound, int) or range_upper_bound <= 0: + raise ValueError( + f"dispatch_on['range_upper_bound'] must be a positive integer, " + f"got {range_upper_bound}" + ) + if not isinstance(split_points, list) or len(split_points) == 0: + raise ValueError("split_points must be a non-empty list of integers") + if sorted(split_points) != split_points: + raise ValueError("split_points must be sorted in ascending order") + + # Create and register the lowering function + lowering_fn = _create_autotuning_lowering( + # pyrefly: ignore [bad-argument-type] + processed_configs=static_configs, + default_impl=impl_fn, + name=name, + op_overload=op_overload, + input_gen_fns=input_gen_fns, + is_range_based=is_range_based, + config_generator=config_generator, + dispatch_on=dispatch_on_tuple, + split_points=split_points, + range_upper_bound=range_upper_bound, + min_speedup_threshold=min_speedup_threshold, + benchmark_with_cudagraphs=benchmark_with_cudagraphs, + ) + + # Register in user_lowerings which takes priority over built-in lowerings + # The dispatch in graph.py checks user_lowerings first with recursion guard + user_lowerings[op_overload] = lowering_fn diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67a604adcb1e6057015f7fa1833d766b37d7c61b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__init__.py @@ -0,0 +1,3 @@ +# mypy: allow-untyped-defs +# Import so here and then reimport above so that register_lowering gets triggered +from . import flex_attention, flex_decoding diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..488275b43b4d5de2780af5e642301d53cde45f0d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/aux_vectorization.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/aux_vectorization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..549fbdb846501bac8cc89c67d5e76796a60e36f5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/aux_vectorization.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3901a2002225d1df044bf5053e9c398b33e5de9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_attention.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..540d0d62c0c346979296acee16ccc066fc61102c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_attention.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_cpu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_cpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a650d17e85f26feebc8cceeba0c1787f7b350c51 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_cpu.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_decoding.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_decoding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac64d7c64d891ae7326d62bc5c28b31eb8325aa4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_decoding.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_flash_attention.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_flash_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e090e84760384ee8400d5624ef08d48cf95e222 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_flash_attention.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_mps.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_mps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e2e4e4cdad9e68894bd626a01e6f0bc7dde7327 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/flex_mps.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/interval_mask_packing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/interval_mask_packing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcff69c148194415ada3ac15b44569a1326ccd5f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/__pycache__/interval_mask_packing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/aux_vectorization.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/aux_vectorization.py new file mode 100644 index 0000000000000000000000000000000000000000..1223436e755663bd5d4b865833705921d21ff119 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/aux_vectorization.py @@ -0,0 +1,417 @@ +# mypy: allow-untyped-defs +"""Captured aux tensor vectorization analysis for flex attention.""" + +import dataclasses +from collections.abc import Callable, Mapping, Sequence +from enum import auto, Enum + +import sympy + +import torch +from torch.fx import GraphModule +from torch.utils._sympy.functions import FloorDiv, Max, Min, ModularIndexing + +from ...codegen.cutedsl.lane_analysis import classify_lane_expr +from ...ir import TensorBox +from ...virtualized import V + + +# Match one vectorized mask_mod call to one 32-bit R2P keep mask; on Blackwell, +# vec32 aux loads are close to vec16. +DEFAULT_MASK_MOD_VEC_SIZE = 32 + + +class LoadKind(Enum): + """How a captured aux tensor load behaves across vectorized KV lanes. + + GATHER: Cannot use a direct vector load. + LANE_UNIFORM: The same value is used for every KV lane. + CONTIGUOUS: Consecutive KV lanes map to contiguous storage. + """ + + GATHER = auto() + LANE_UNIFORM = auto() + CONTIGUOUS = auto() + + +@dataclasses.dataclass(frozen=True) +class AuxLoadVecInfo: + """Vectorization classification for one captured aux tensor load. + + kind: Load classification. + vec_size: Direct vector width for contiguous loads; None otherwise. + """ + + kind: LoadKind + vec_size: int | None = None + + def __post_init__(self) -> None: + """Validate that only contiguous loads carry a vector width.""" + if self.kind is LoadKind.CONTIGUOUS: + if self.vec_size is None: + raise AssertionError("CONTIGUOUS load requires a vec_size") + else: + if self.vec_size is not None: + raise AssertionError( + f"non-CONTIGUOUS load must not carry vec_size, got {self.vec_size}" + ) + + @classmethod + def gather(cls) -> "AuxLoadVecInfo": + """Create a gather-load classification.""" + return cls(LoadKind.GATHER) + + @classmethod + def lane_uniform(cls) -> "AuxLoadVecInfo": + """Create a lane-uniform-load classification.""" + return cls(LoadKind.LANE_UNIFORM) + + @classmethod + def contiguous(cls, vec_size: int) -> "AuxLoadVecInfo": + """Create a contiguous direct-vector-load classification.""" + return cls(LoadKind.CONTIGUOUS, vec_size) + + +@dataclasses.dataclass(frozen=True) +class AuxVecPolicy: + """ABI-specific rules for selecting an aux tensor vector width. + + q_idx_placeholder: Placeholder index for the query lane. + kv_idx_placeholder: Placeholder index for the vectorized KV lane. + max_vec_size: Largest direct captured-tensor load width to consider. + min_index_rank_for_contiguous_load: Minimum indexed rank for direct vector loads. + mask_mod uses rank 2 so 1-D KV masks remain scalar per-lane gathers; + otherwise a short 1-D mask can shrink the packed-mask vector width. + non_lane_placeholder_start: First non-lane placeholder participating in indices. + """ + + q_idx_placeholder: int + kv_idx_placeholder: int + max_vec_size: int + min_index_rank_for_contiguous_load: int = 1 + non_lane_placeholder_start: int = 0 + + +MASK_MOD_AUX_VEC_POLICY = AuxVecPolicy( + q_idx_placeholder=2, + kv_idx_placeholder=3, + max_vec_size=32, + min_index_rank_for_contiguous_load=2, +) +SCORE_MOD_AUX_VEC_POLICY = AuxVecPolicy( + q_idx_placeholder=3, + kv_idx_placeholder=4, + max_vec_size=8, + non_lane_placeholder_start=1, +) + + +@dataclasses.dataclass(frozen=True) +class AuxIndexedTensor: + """Captured tensor plus any safe partial indices already accumulated.""" + + buffer: TensorBox + indices: tuple[object, ...] + + +def make_fx_index_symbols( + q_idx_node: torch.fx.Node, + kv_idx_node: torch.fx.Node, + non_lane_index_nodes: Sequence[torch.fx.Node] = (), + *, + kv_expr: sympy.Expr | None = None, +) -> tuple[sympy.Symbol, sympy.Symbol, dict[torch.fx.Node, sympy.Expr]]: + """Build symbolic replacements for lane and non-lane FX index nodes.""" + q_idx = sympy.Symbol("q_idx", integer=True, nonnegative=True) + kv_idx = sympy.Symbol("kv_idx", integer=True, nonnegative=True) + index_symbols = { + node: sympy.Symbol(node.name, integer=True, nonnegative=True) + for node in non_lane_index_nodes + } + index_symbols[q_idx_node] = q_idx + index_symbols[kv_idx_node] = kv_idx if kv_expr is None else kv_expr + return q_idx, kv_idx, index_symbols + + +def select_mask_mod_vec_size( + *, + has_mask_mod: bool, + has_mask_aux_tensors: bool, + supports_mask_mod_vec: bool, + graph_module: GraphModule | None, + other_buffers: Sequence[TensorBox], +) -> int | None: + """Use mask_mod's (b, h, q, kv) ABI; vec32 matches the packed R2P mask width.""" + if not has_mask_mod or not supports_mask_mod_vec: + return None + if not has_mask_aux_tensors: + return DEFAULT_MASK_MOD_VEC_SIZE + + vec_size = select_aux_mod_vec_size( + graph_module, + other_buffers, + MASK_MOD_AUX_VEC_POLICY, + ) + return vec_size if vec_size > 1 else None + + +def select_score_mod_vec_size( + *, + has_score_mod: bool, + has_aux_tensors: bool, + is_sm100_or_later: bool, + graph_module: GraphModule | None, + other_buffers: Sequence[TensorBox], +) -> int | None: + """Select score_mod vector width for captured aux loads. + + A return value of None means there are no captured tensor loads constraining + score_mod.__vec_size__. For captured tensors, direct vector loads are capped + to the SM100 CuTe score_mod aux-load path's supported width of 8. + """ + if not has_score_mod or not has_aux_tensors: + return None + if not is_sm100_or_later: + return 1 + return select_aux_mod_vec_size( + graph_module, + other_buffers, + SCORE_MOD_AUX_VEC_POLICY, + ) + + +def select_aux_mod_vec_size( + graph_module: GraphModule | None, + other_buffers: Sequence[TensorBox], + policy: AuxVecPolicy, +) -> int: + """Choose a safe vector width for captured tensor loads. + + The analysis follows aten.index chains from captured tensor placeholders, + accumulates partial indices that do not depend on the vectorized KV lane, + classifies complete loads, and picks the narrowest required contiguous + width. Gather-like loads stay scalar per lane and can coexist with any + vectorizable load that selects a non-scalar width. + """ + if graph_module is None: + return 1 + + placeholders = [ + node for node in graph_module.graph.nodes if node.op == "placeholder" + ] + num_fixed_placeholders = policy.kv_idx_placeholder + 1 + if len(placeholders) < num_fixed_placeholders: + return 1 + + aux_indexed_tensors = { + placeholder: AuxIndexedTensor(buffer, ()) + for placeholder, buffer in zip( + placeholders[num_fixed_placeholders:], other_buffers + ) + } + non_lane_index_nodes = placeholders[ + policy.non_lane_placeholder_start : policy.q_idx_placeholder + ] + selected_vec_size = policy.max_vec_size + found_vectorizable_load = False + for node in graph_module.graph.nodes: + if node.op != "call_function" or node.target != torch.ops.aten.index.Tensor: + continue + buffer_node, indices = node.args + if buffer_node not in aux_indexed_tensors: + continue + indexed_tensor = aux_indexed_tensors[buffer_node] + if not isinstance(indices, (list, tuple)) or not indices: + continue + full_indices = indexed_tensor.indices + tuple(indices) + rank = len(indexed_tensor.buffer.get_size()) + if len(full_indices) < rank: + # Chained indexing is safe to track only until the KV lane is used. + if is_safe_partial_aux_index( + full_indices, + placeholders[policy.q_idx_placeholder], + placeholders[policy.kv_idx_placeholder], + non_lane_index_nodes, + ): + aux_indexed_tensors[node] = AuxIndexedTensor( + indexed_tensor.buffer, full_indices + ) + continue + if len(full_indices) > rank: + continue + aux_load_vec_info = direct_aux_load_vec_size_and_kind( + full_indices, + indexed_tensor.buffer, + placeholders[policy.q_idx_placeholder], + placeholders[policy.kv_idx_placeholder], + non_lane_index_nodes=non_lane_index_nodes, + max_vec_size=policy.max_vec_size, + min_index_rank_for_contiguous_load=policy.min_index_rank_for_contiguous_load, + ) + match aux_load_vec_info.kind: + case LoadKind.LANE_UNIFORM: + found_vectorizable_load = True + case LoadKind.GATHER: + pass + case LoadKind.CONTIGUOUS: + contiguous_vec_size = aux_load_vec_info.vec_size + if contiguous_vec_size is None: + raise AssertionError("CONTIGUOUS load must have a vec_size") + selected_vec_size = min(selected_vec_size, contiguous_vec_size) + found_vectorizable_load = True + + return selected_vec_size if found_vectorizable_load else 1 + + +def is_safe_partial_aux_index( + indices: tuple[object, ...], + q_idx_node: torch.fx.Node, + kv_idx_node: torch.fx.Node, + non_lane_index_nodes: Sequence[torch.fx.Node], +) -> bool: + """Return whether partial indices can be chained before the KV-lane index.""" + _, kv_idx, index_symbols = make_fx_index_symbols( + q_idx_node, kv_idx_node, non_lane_index_nodes + ) + for index in indices: + expr = fx_aux_index_to_sympy(index, index_symbols) + if expr is None or kv_idx in expr.free_symbols: + return False + return True + + +def direct_aux_load_vec_size_and_kind( + indices: object, + buffer: TensorBox, + q_idx_node: torch.fx.Node, + kv_idx_node: torch.fx.Node, + non_lane_index_nodes: Sequence[torch.fx.Node] = (), + max_vec_size: int = 8, + min_index_rank_for_contiguous_load: int = 1, +) -> AuxLoadVecInfo: + """Return vector-load information for a captured aux load. + + The load is lane-uniform if none of its indices depend on KV. Otherwise, + only the final indexed dimension may depend on KV, the storage for that + dimension must be contiguous and vector-aligned, and the lane expression + must enumerate consecutive values for the chosen vector width. + """ + if not isinstance(indices, (list, tuple)) or not indices: + return AuxLoadVecInfo.gather() + if not (max_vec_size >= 2 and max_vec_size.bit_count() == 1): + raise AssertionError( + f"max_vec_size must be a power of two >= 2, got {max_vec_size}" + ) + + _, kv_idx, index_symbols = make_fx_index_symbols( + q_idx_node, kv_idx_node, non_lane_index_nodes + ) + index_exprs = [fx_aux_index_to_sympy(index, index_symbols) for index in indices] + if any(expr is None for expr in index_exprs): + return AuxLoadVecInfo.gather() + if all(kv_idx not in expr.free_symbols for expr in index_exprs): + return AuxLoadVecInfo.lane_uniform() + + last_expr = index_exprs[-1] + if kv_idx not in last_expr.free_symbols: + return AuxLoadVecInfo.gather() + if len(indices) < min_index_rank_for_contiguous_load: + return AuxLoadVecInfo.gather() + + prefix_exprs = index_exprs[:-1] + if any(kv_idx in expr.free_symbols for expr in prefix_exprs): + return AuxLoadVecInfo.gather() + + sizes = buffer.get_size() + strides = buffer.get_stride() + if not V.graph.sizevars.statically_known_equals(strides[-1], 1): + return AuxLoadVecInfo.gather() + + # FlashAttention groups vectorized mod calls across consecutive KV lanes. + offset = buffer.get_layout().offset + vec_size = max_vec_size + while vec_size >= 2: + lane_info = classify_lane_expr(last_expr, kv_idx, max_width=vec_size) + if ( + V.graph.sizevars.statically_known_multiple_of(sizes[-1], vec_size) + and V.graph.sizevars.statically_known_multiple_of(offset, vec_size) + and all( + V.graph.sizevars.statically_known_multiple_of(stride, vec_size) + for stride in strides[:-1] + ) + and lane_info.is_contiguous + ): + return AuxLoadVecInfo.contiguous(vec_size) + vec_size //= 2 + return AuxLoadVecInfo.gather() + + +def fx_aux_index_to_sympy( + index: object, + index_symbols: Mapping[torch.fx.Node, sympy.Expr], + node_to_sympy: Callable[[torch.fx.Node], sympy.Expr | None] | None = None, +) -> sympy.Expr | None: + """Translate the supported FX integer index operations to sympy.""" + if isinstance(index, int | sympy.Integer): + return sympy.Integer(index) + if not isinstance(index, torch.fx.Node): + return None + if index in index_symbols: + return index_symbols[index] + if node_to_sympy is not None: + expr = node_to_sympy(index) + if expr is not None: + return expr + if index.op != "call_function": + return None + + args = index.args + target = index.target + match target: + case torch.ops.aten.abs.default: + operand = fx_aux_index_to_sympy(args[0], index_symbols, node_to_sympy) + return None if operand is None else sympy.Abs(operand) + case torch.ops.aten.neg.default: + operand = fx_aux_index_to_sympy(args[0], index_symbols, node_to_sympy) + return None if operand is None else -operand + case torch.ops.aten.clamp.default: + operand = fx_aux_index_to_sympy(args[0], index_symbols, node_to_sympy) + if operand is None: + return None + lo = args[1] if len(args) > 1 else index.kwargs.get("min") + hi = args[2] if len(args) > 2 else index.kwargs.get("max") + for bound, combine in ((lo, Max), (hi, Min)): + if bound is not None: + bound_expr = fx_aux_index_to_sympy( + bound, index_symbols, node_to_sympy + ) + if bound_expr is None: + return None + operand = combine(operand, bound_expr) + return operand + + if len(args) < 2: + return None + lhs = fx_aux_index_to_sympy(args[0], index_symbols, node_to_sympy) + rhs = fx_aux_index_to_sympy(args[1], index_symbols, node_to_sympy) + if lhs is None or rhs is None: + return None + match target: + case torch.ops.aten.add.Tensor | torch.ops.aten.add.Scalar: + return V.graph.sizevars.simplify(lhs + rhs) + case torch.ops.aten.sub.Tensor | torch.ops.aten.sub.Scalar: + return V.graph.sizevars.simplify(lhs - rhs) + case torch.ops.aten.mul.Tensor | torch.ops.aten.mul.Scalar: + return V.graph.sizevars.simplify(lhs * rhs) + case torch.ops.aten.minimum.default: + return Min(lhs, rhs) + case torch.ops.aten.maximum.default: + return Max(lhs, rhs) + case torch.ops.aten.remainder.Tensor | torch.ops.aten.remainder.Scalar: + return ModularIndexing(lhs, 1, rhs) + case torch.ops.aten.div.Tensor_mode if ( + index.kwargs.get("rounding_mode") == "floor" + ): + return FloorDiv(lhs, rhs) + case _: + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/common.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/common.py new file mode 100644 index 0000000000000000000000000000000000000000..82ef70b717adac3e9f7b85f1b8a67d7d9080e9c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/common.py @@ -0,0 +1,507 @@ +# mypy: allow-untyped-defs +"""Common utilities and functions for flex attention kernels""" + +import math +from collections.abc import Sequence +from functools import partial +from pathlib import Path +from typing import Any, TYPE_CHECKING + +import sympy + +import torch +from torch._inductor.virtualized import V +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import tree_map, tree_map_only +from torch.utils._sympy.functions import Mod + + +if TYPE_CHECKING: + from torch._inductor.codegen.cuda_combined_scheduling import _IntLike +else: + _IntLike = int | sympy.Expr + + +from ...ir import ( + ComputedBuffer, + ExternKernel, + FixedLayout, + FlexibleLayout, + get_fill_order, + InputBuffer, + IRNode, + MutationLayoutSHOULDREMOVE, + Scatter, + StorageBox, + Subgraph, + TensorBox, +) +from ...lowering import ( + _full, + check_and_broadcast_indices, + expand, + index_output_size_and_inner_fn, + to_dtype, +) +from ...select_algorithm import realize_inputs +from ...utils import load_template + + +SubgraphResults = list[ComputedBuffer | None] | ComputedBuffer | None + + +def can_skip_boundary_checks(seq_len, sparse_block_size) -> bool: + """True when per-tile bounds masking can be skipped along this dim. + + This is decided before a config is chosen, so divisibility is checked + against 128, the max (and LCM) of all candidate pow2 tile sizes for + inner block_m/n. + """ + return V.graph.sizevars.statically_known_true( + sympy.And( + sympy.Eq(Mod(seq_len, 128), 0), + sympy.Or( + sympy.Eq(Mod(seq_len, sparse_block_size), 0), + sympy.Ge(sparse_block_size, seq_len), + ), + ) + ) + + +def is_tensor_ir_node(node: object) -> bool: + return isinstance(node, IRNode) and node.has_tensor_output() + + +def _flex_kernel_options_example(kind: str) -> str: + match kind: + case "backward": + return ( + "kernel_options={'bwd_BLOCK_M1': 32, 'bwd_BLOCK_N1': 32, " + "'bwd_BLOCK_M2': 32, 'bwd_BLOCK_N2': 32, " + "'bwd_num_stages': 1, 'bwd_num_warps': 4}" + ) + case _: + return ( + "kernel_options={'fwd_BLOCK_M': 32, 'fwd_BLOCK_N': 64, " + "'fwd_num_stages': 1, 'fwd_num_warps': 4}" + ) + + +def _flex_kernel_tuning_options(kind: str) -> str: + match kind: + case "backward": + return ( + "BLOCK_M1, BLOCK_N1, BLOCK_M2, BLOCK_N2, num_warps, and " + "num_stages; use the bwd_ prefix to set backward-only options" + ) + case "decode": + return ( + "BLOCK_M, BLOCK_N, num_warps, and num_stages; use the fwd_ " + "prefix to set decode-only options" + ) + case _: + return ( + "BLOCK_M, BLOCK_N, num_warps, and num_stages; use the fwd_ " + "prefix to set forward-only options" + ) + + +def zeros_and_scatter_lowering(shape: list[int], indices, values): + """To support backwards on captured buffers we register a specific lowering for our specific custom up""" + # Always accumulate into fp32 then cast + grad = _full(0, values.get_device(), torch.float32, shape) + if not isinstance(grad, TensorBox): + raise AssertionError(f"Expected TensorBox, got {type(grad)}") + grad.realize() + x_size = grad.get_size() + values = to_dtype(values, grad.get_dtype()) + device = grad.get_device() + if device is None: + raise AssertionError("device must not be None") + if not indices: + if shape: + raise AssertionError( + "zeros_and_scatter with no indices only supports scalar outputs" + ) + expected_vals_size = values.get_size() + + def inner_fn(index): + return [] + + else: + indices_loaders = [i.make_loader() if i is not None else None for i in indices] + indices, tensor_indices = check_and_broadcast_indices( + indices, grad.get_device() + ) + # We can use the first one since they are all required to be the same size + tensor_size = list(indices[tensor_indices[0]].get_size()) + indexed_size = [x_size[i] for i in range(len(indices))] + + expected_vals_size, inner_fn = index_output_size_and_inner_fn( + x_size, + indices, + tensor_indices, + tensor_size, + indices_loaders, + indexed_size, + None, + check=True, + ) + values = expand(values, expected_vals_size) + scatter = Scatter( + device=device, + dtype=grad.get_dtype(), + inner_fn=values.make_loader(), + ranges=expected_vals_size, # iter_ranges, + output_indexer=inner_fn, + scatter_mode="atomic_add", + ) + + buffer = ComputedBuffer( + name=grad.data.data.name, # type: ignore[attr-defined] + layout=MutationLayoutSHOULDREMOVE(grad), + data=scatter, + ) + return buffer + + +def get_fwd_subgraph_outputs( + subgraph_buffer: SubgraphResults, mask_graph_buffer: SubgraphResults +) -> list[ComputedBuffer | None]: + subgraph_buffer = ( + subgraph_buffer if isinstance(subgraph_buffer, Sequence) else [subgraph_buffer] + ) + mask_graph_buffer = ( + mask_graph_buffer + if isinstance(mask_graph_buffer, Sequence) + else [mask_graph_buffer] + ) + + return [*subgraph_buffer, *mask_graph_buffer] + + +def build_subgraph_module_buffer( + args: list[TensorBox], + graph_module: torch.fx.GraphModule, +) -> SubgraphResults: + """This function's goal is to take in the required args and produce the subgraph buffer + The subgraph buffer is a ComputedBuffer that will be inlined into the triton template + + Args: + args: The args that are passed into the subgraph. Contains both fixed and lifted inputs. + subgraph: The Subgraph ir for which to produce the output node + """ + # This one we gotta keep lazy + from ...subgraph_lowering import PointwiseSubgraphLowering + + pw_subgraph = PointwiseSubgraphLowering( + graph_module, + root_graph_lowering=V.graph, + allowed_mutations=OrderedSet([torch.ops.flex_lib.zeros_and_scatter.default]), + additional_lowerings={ + torch.ops.flex_lib.zeros_and_scatter.default: zeros_and_scatter_lowering + }, + ) + with V.set_graph_handler(pw_subgraph): # type: ignore[arg-type] + pw_subgraph.run(*args) + + def convert_output_node_to_buffer(output_buffer) -> ComputedBuffer | None: + if output_buffer is None: + return None + if isinstance(output_buffer, ComputedBuffer): + # These nodes are coming from the output of zeros_and_scatter + return output_buffer + if not isinstance(output_buffer, TensorBox): + raise AssertionError( + f"The output node for flex attention's subgraph must be a TensorBox, but got: {type(output_buffer)}" + ) + if not isinstance(output_buffer.data, StorageBox): + raise AssertionError( + f"The output node for the flex attention subgraph must be a StorageBox, but got: {type(output_buffer.data)}" + ) + device = output_buffer.data.get_device() + if device is None: + raise AssertionError("device must not be None for output buffer") + subgraph_buffer = ComputedBuffer( + name=None, + layout=FlexibleLayout( + device=device, + dtype=output_buffer.data.get_dtype(), + size=output_buffer.data.get_size(), + ), + data=output_buffer.data.data, # type: ignore[arg-type] + ) + return subgraph_buffer + + return tree_map(convert_output_node_to_buffer, pw_subgraph.graph_outputs) + + +def build_subgraph_buffer(args: list[TensorBox], subgraph: Subgraph) -> SubgraphResults: + return build_subgraph_module_buffer(args, subgraph.graph_module) + + +def maybe_realize(args: list[IRNode | None]): + """Accepts a list of optional IRNodes and returns a list of realized IRNodes""" + return tree_map( + lambda x: ( + realize_inputs(x) if x is not None and not isinstance(x, sympy.Expr) else x + ), + args, + ) + + +def realize_captures_for_cutedsl(buffers): + """Realize captured buffers for CuteDSL, preserving views and plain inputs. + + Unlike maybe_realize (used by the Triton path), CuteDSL needs physical + tensors passed at runtime. Pointwise/computed captures must be materialized + into a fresh buffer whose layout matches the logical shape the subgraph + indexes. ReinterpretView captures use unique synthetic inputs so aliased + views keep distinct call-site size/stride/offset metadata while the kernel + indexes each captured view argument from offset zero. + + Realized captures are registered on V.graph so the CuteDSL template can + resolve view nodes without explicit plumbing from callers. + """ + from ...ir import ExternKernel, FixedLayout, InputBuffer, ReinterpretView + + view_captures: dict[str, ReinterpretView] = {} + + def _add_alignment_check_for_input(input_buffer: InputBuffer) -> None: + # Preserved captures can be used by vectorized CuteDSL loads, so make + # sure the wrapper still emits copy_if_misaligned for graph inputs. + # Normal template inputs are already in inputs_to_check; captures need + # to be added explicitly because they were not direct template inputs + # when alignment-check inputs were selected. + name = input_buffer.get_name() + graph_input_names = getattr(V.graph, "graph_input_names", []) + if name in graph_input_names: + idx = graph_input_names.index(name) + inputs_to_check = list(V.graph.inputs_to_check or ()) + if idx not in inputs_to_check: + V.graph.inputs_to_check = [*inputs_to_check, idx] + + def _realize(x): + if x is None or isinstance(x, sympy.Expr): + return x + realized = ExternKernel.realize_input(x) + if isinstance(realized, StorageBox) and realized.is_input_buffer(): + # Plain graph inputs are commonly represented as + # TensorBox(StorageBox(InputBuffer(...))). Preserve the underlying + # input/view instead of materializing it with ExternKernel.copy_input. + realized = realized.data + if isinstance(realized, ReinterpretView): + layout = realized.get_layout() + capture_index = len(V.graph._cutedsl_capture_nodes) + len(view_captures) + name = V.graph.qualify_name(f"cutedsl_capture{capture_index}") + view_captures[name] = realized + # Give each captured view a logical input name so aliasing views do + # not collapse to their shared base buffer. + return InputBuffer( + name=name, + layout=FixedLayout( + layout.device, + layout.dtype, + layout.size, + layout.stride, + is_pinned=layout.is_pinned, + ), + ) + if isinstance(realized, InputBuffer): + _add_alignment_check_for_input(realized) + return realized + return ExternKernel.copy_input(realized) + + buffers = tree_map(_realize, buffers) + freeze_irnodes(buffers) + + for buf in tree_map_only(IRNode, lambda x: x, buffers) if buffers else []: + if isinstance(buf, IRNode) and (name := buf.maybe_get_name()): + V.graph._cutedsl_capture_nodes[name] = buf + # Keep the original view nodes for call-site reinterpret_tensor emission. + V.graph._cutedsl_capture_nodes.update(view_captures) + + return buffers + + +def freeze_irnodes(tree: Any) -> Any: + """Freeze layouts for every IRNode contained in a pytree.""" + + if tree is None: + return None + + def _freeze(node: IRNode) -> IRNode: + try: + node.freeze_layout() + except NotImplementedError: + pass + return node + + return tree_map_only(IRNode, _freeze, tree) + + +def create_placeholder( + name: str, + dtype: torch.dtype, + device: torch.device, + size: list[int] | None = None, +) -> TensorBox: + """Creates a placeholder input buffers for producing subgraph_output.""" + input_buffer = InputBuffer( + name=name, + layout=FixedLayout( + device, + dtype, + size if size else [], + FlexibleLayout.contiguous_strides(size) if size else [], + ), + ) + return TensorBox.create(input_buffer) + + +def construct_strides( + sizes: Sequence[_IntLike], + fill_order: Sequence[int], +) -> Sequence[_IntLike]: + """From a list of sizes and a fill order, construct the strides of the permuted tensor.""" + # Initialize strides + if len(sizes) != len(fill_order): + raise AssertionError("Length of sizes must match the length of the fill order") + strides: list[_IntLike] = [0] * len(sizes) + + # Start with stride 1 for the innermost dimension + current_stride: _IntLike = 1 + + # Iterate through the fill order populating strides + for dim in fill_order: + strides[dim] = current_stride + current_stride *= sizes[dim] + + return strides + + +def infer_dense_strides( + size: Sequence[_IntLike], + orig_strides: Sequence[_IntLike], +): + """This is a mirror of the same function in aten/src/ATen/ExpandUtils.cpp + + Args: + size: The size of the output tensor + orig_strides: The strides of the input tensor + Returns: + List[int]: Dense non-overlapping strides that preserve the input tensor's layout permutation. + The returned strides follow the same stride propagation rules as TensorIterator. This matches + The behavior of empty_like() + """ + fill_order = get_fill_order(orig_strides, V.graph.sizevars.shape_env) + strides = construct_strides(size, fill_order) + + # Attention kernels require stride[-1]=1 for efficient memory access. + # Ensure this by moving last dim to front of fill_order if needed. + if strides[-1] != 1: + last_dim = len(size) - 1 + fill_order = list(fill_order) + fill_order.remove(last_dim) + fill_order = [last_dim] + fill_order + strides = construct_strides(size, fill_order) + + return strides + + +def create_indices_fake(x) -> torch.Tensor: + """Create a fake indices that is used for autotuning.""" + size = V.graph.sizevars.optimization_hints(x.get_size()) + indices = torch.arange(0, size[-1], dtype=x.get_dtype(), device=x.get_device()) + indices = indices.expand(size).contiguous() + return indices + + +def create_num_blocks_fake_generator(sparse_indices): + """Create a fake num_blocks that is used for autotuning. + + The idea here is that we need to create a real tensor with real data + that's representative for benchmarking. + For example, returning all zeros for the `kv_num_blocks` input would mean + that we are computing 0 blocks for each row, which would provide bogus + autotuning results. + + In this case, we choose to use min(16, max_block) blocks, because I + (Horace) think it'll probably result in pretty representative performance. + If it's too short then prefetching won't help. If it's too long then + autotuning will take longer for no good reason. + """ + + def create_num_blocks_fake(x) -> torch.Tensor: + num_blocks_for_autotuning = V.graph.sizevars.optimization_hint( + sparse_indices.shape[-1] + ) + size = V.graph.sizevars.optimization_hints(x.get_size()) + return torch.full( + size, + num_blocks_for_autotuning, + dtype=x.get_dtype(), + device=x.get_device(), + ) + + return create_num_blocks_fake + + +def contiguous_last_dim(x): + """Ensure that realized IR node has a contiguous stride in the last dimension.""" + strides = x.maybe_get_stride() + if strides and strides[-1] != 1: + contiguous_stride_order = list(reversed(range(len(x.get_size())))) + return ExternKernel.require_stride_order(x, contiguous_stride_order) + return x + + +def set_head_dim_values( + kernel_options: dict[str, Any], qk_head_dim, v_head_dim, graph_sizevars +): + """ + Mutates kernel options, adding head dimension calculations. + + Args: + kernel_options: Dictionary to populate with options + qk_head_dim: Query/Key head dimension + v_head_dim: Value head dimension + graph_sizevars: Graph size variables object with guard_int method + + """ + # QK dimensions + qk_head_dim_static = graph_sizevars.guard_int(qk_head_dim) + kernel_options.setdefault("QK_HEAD_DIM", qk_head_dim_static) + kernel_options.setdefault( + "QK_HEAD_DIM_ROUNDED", next_power_of_two(qk_head_dim_static) + ) + + # V dimensions + v_head_dim_static = graph_sizevars.guard_int(v_head_dim) + kernel_options.setdefault("V_HEAD_DIM", v_head_dim_static) + kernel_options.setdefault( + "V_HEAD_DIM_ROUNDED", next_power_of_two(v_head_dim_static) + ) + + # Safety flag + kernel_options.setdefault( + "SAFE_HEAD_DIM", + is_power_of_2(qk_head_dim_static) and is_power_of_2(v_head_dim_static), + ) + + +def is_power_of_2(n): + return n != 0 and ((n & (n - 1)) == 0) + + +def next_power_of_two(n): + if n <= 0: + return 1 + return 2 ** math.ceil(math.log2(n)) + + +_FLEX_TEMPLATE_DIR = Path(__file__).parent / "templates" +load_flex_template = partial(load_template, template_dir=_FLEX_TEMPLATE_DIR) + + +# Template strings have been moved to templates/common.py.jinja diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_attention.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..0a397c05f569df06059de1ac2f07c240121e204e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_attention.py @@ -0,0 +1,1249 @@ +# mypy: allow-untyped-defs +"""Triton Implementation of the flex_attention Kernel""" + +from __future__ import annotations + +import logging +import math +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any, cast, TYPE_CHECKING + +import sympy + +import torch +from torch._inductor.virtualized import V +from torch.nn.attention.flex_attention import _Backend +from torch.utils._sympy.functions import FloorDiv + +from ...ir import ComputedBuffer, ExternKernel, FixedLayout, TensorBox +from ...lowering import empty, empty_strided, lowerings, register_lowering, to_dtype +from ...runtime.runtime_utils import is_power_of_2 +from ...select_algorithm import ( + autotune_select_algorithm, + SymbolicGridFn, + TritonTemplate, +) +from ...utils import can_use_tma +from .common import ( + _flex_kernel_options_example, + _flex_kernel_tuning_options, + build_subgraph_buffer, + can_skip_boundary_checks, + create_indices_fake, + create_num_blocks_fake_generator, + create_placeholder, + freeze_irnodes, + get_fwd_subgraph_outputs, + infer_dense_strides, + is_tensor_ir_node, + load_flex_template, + maybe_realize, + realize_captures_for_cutedsl, + set_head_dim_values, + SubgraphResults, +) +from .flex_cpu import lower_cpu +from .flex_decoding import _use_flex_decoding, create_flex_decoding_kernel +from .flex_flash_attention import ( + _use_flex_flash_attention, + _use_flex_flash_attention_backward, + create_flex_flash_attention_backward_kernel, + create_flex_flash_attention_kernel, + has_unsupported_cpu_scalar_tensor_captures, + is_trivial_mask_graph, + is_trivial_score_graph, +) + + +if TYPE_CHECKING: + from ...heuristics.template.triton import FlexBwDConfig, FlexConfig + + +log = logging.getLogger(__name__) +aten = torch.ops.aten +prims = torch.ops.prims +Expr = sympy.Expr + + +def _sanitize_kernel_options_for_triton( + kernel_options: dict[str, Any], +) -> tuple[dict[str, Any], _Backend]: + """We always strip quotes around str values, we only need this in lowering, so we pop it here + to avoid passing to triton constexpr dict + """ + sanitized = dict(kernel_options) + backend = cast(_Backend, sanitized.pop("BACKEND", "AUTO")) + return sanitized, backend + + +def raise_flex_kernel_options_error( + kernel_name: str, + kernel_options: dict[str, Any], + option_names: Sequence[str], + sparse_q_block_size: int, + sparse_kv_block_size: int, +) -> None: + option_values = ", ".join(f"{name}={kernel_options[name]}" for name in option_names) + raise ValueError( + f"Invalid FlexAttention {kernel_name} kernel options: Q and KV block sizes " + f"must be divisible by the selected tile sizes. Got " + f"SPARSE_Q_BLOCK_SIZE={sparse_q_block_size}, " + f"SPARSE_KV_BLOCK_SIZE={sparse_kv_block_size}, and {option_values}. " + f"Pass compatible values with kernel_options. Available {kernel_name} " + f"tuning options are {_flex_kernel_tuning_options(kernel_name)}. For example: " + f"{_flex_kernel_options_example(kernel_name)}. If you did not pin " + f"these options, and the default choice errors, compiling with " + f"mode='max-autotune-no-cudagraphs' can also fix this by trying more " + f"FlexAttention configs." + ) + + +def _check_flash_supported_scalar_captures( + score_mod_other_buffers, + mask_mod_other_buffers, + *, + backward: bool = False, +) -> None: + if has_unsupported_cpu_scalar_tensor_captures( + score_mod_other_buffers, mask_mod_other_buffers + ): + direction = " backward" if backward else "" + raise RuntimeError( + f"BACKEND='FLASH' but flash attention{direction} cannot be used: " + "NYI: score_mod or mask_mod captures a 0-dim CPU tensor scalar. " + "Workarounds: use BACKEND='TRITON' or pass the value as a tensor " + "on device instead of capturing a CPU scalar tensor." + ) + + +@SymbolicGridFn +def flex_attention_grid(batch_size, q_heads, num_queries, d_model, meta, *, cdiv): + """How is this kernel parallelized? + We create a grid of (ceil_div(n_queries, query_block_size), batch_size, num_heads) + Each block is responsible for iterating over blocks of keys and values calculating + the final attention output. + """ + return (cdiv(num_queries, meta["BLOCK_M"]), batch_size, q_heads) + + +def get_float32_precision(): + if ( + ( + torch.backends.cuda.matmul.fp32_precision == "ieee" + if torch.backends.cuda.matmul.fp32_precision != "none" + else torch.get_float32_matmul_precision() == "highest" + ) + or torch.version.hip + or torch.mtia.is_available() + ): + return "'ieee'" + else: + return "'tf32'" + + +flex_attention_template = TritonTemplate( + name="flex_attention", + grid=flex_attention_grid, + source=load_flex_template("flex_attention") + + load_flex_template("utilities") + + load_flex_template("common"), + always_freeze_layout=True, +) + + +@register_lowering(torch.ops.higher_order.flex_attention, type_promotion_kind=None) +def flex_attention( + query, + key, + value, + subgraph, + block_mask, + scale, + kernel_options: dict[str, Any], + score_mod_other_buffers, + mask_mod_other_buffers, +): + """The main lowering for the flex_attention hop + This can currently lower to one of 4 templates: + 1. Base Triton Template + 2. Flex Decode Triton Template + 3. Cpu specific CPP template + 4. MPS specific Metal template + """ + if query.get_device().type == "cpu": + return lower_cpu( + query, + key, + value, + subgraph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + if query.get_device().type == "mps": + from .flex_mps import lower_mps + + return lower_mps( + query, + key, + value, + subgraph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + # below is cuda path if device is not cpu or mps + # tl.dot does not support embedding size less than 16 + small_dqk = V.graph.sizevars.evaluate_expr(sympy.Lt(query.get_size()[-1], 16)) + small_dv = V.graph.sizevars.evaluate_expr(sympy.Lt(value.get_size()[-1], 16)) + if small_dqk or small_dv: + raise NotImplementedError( + f"NYI: embedding dimension of the query, key, and value must be " + f"at least 16 but got E={query.get_size()[-1]} and Ev={value.get_size()[-1]}" + ) + + ( + _, # q_length + _, # kv_length + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + q_num_blocks, + q_indices, + full_q_num_blocks, + full_q_indices, + _, # dq_write_order (backward-only) + _, # dq_write_order_full (backward-only) + _, # dq_kv_order (backward-only) + _, # dq_kv_order_spt (backward-only) + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + mask_graph, + ) = block_mask + + kernel_options, backend = _sanitize_kernel_options_for_triton(kernel_options) + + # Early check for FLASH backend: reject scalar captures that cannot be + # represented by flash-attn aux_scalars before building subgraph buffers. + if backend == "FLASH": + _check_flash_supported_scalar_captures( + score_mod_other_buffers, mask_mod_other_buffers + ) + + if backend == "FLASH": + score_mod_other_buffers = realize_captures_for_cutedsl(score_mod_other_buffers) + mask_mod_other_buffers = realize_captures_for_cutedsl(mask_mod_other_buffers) + + placeholder_inps = [ + create_placeholder(name, dtype, query.get_device()) + for name, dtype in [ + ("score", query.get_dtype()), + ("b", torch.int32), + ("h", torch.int32), + ("m", torch.int32), + ("n", torch.int32), + ] + ] + subgraph_buffer = build_subgraph_buffer( + placeholder_inps + list(score_mod_other_buffers), subgraph + ) + freeze_irnodes(subgraph_buffer) + + mask_graph_placeholder_inps = [ + create_placeholder(name, dtype, query.get_device()) + for name, dtype in [ + ("b", torch.int32), + ("h", torch.int32), + ("m", torch.int32), + ("n", torch.int32), + ] + ] + mask_graph_buffer = build_subgraph_buffer( + mask_graph_placeholder_inps + list(mask_mod_other_buffers), mask_graph + ) + freeze_irnodes(mask_graph_buffer) + # Mark symbols in custom kernel options as static shapes and add guards. + kernel_options = { + k: V.graph.sizevars.guard_int(v) if isinstance(v, sympy.Symbol) else v + for k, v in kernel_options.items() + } + kernel_options.setdefault("FLOAT32_PRECISION", get_float32_precision()) + enable_gqa = V.graph.sizevars.evaluate_expr( + sympy.Ne(query.get_size()[1], key.get_size()[1]), + ) + + can_use_decode = _use_flex_decoding( + query, kv_indices, value, kernel_options, enable_gqa + ) + use_decode = (backend == "TRITON_DECODE") or (backend == "AUTO" and can_use_decode) + + if backend == "TRITON_DECODE" and not can_use_decode: + raise RuntimeError( + "BACKEND='TRITON_DECODE' was specified but flex_decoding cannot be used for this input. " + "flex_decoding is only available for short sequence lengths with specific configurations." + ) + + if use_decode: + return create_flex_decoding_kernel( + query, + key, + value, + block_mask, + scale, + kernel_options, + subgraph_buffer, + mask_graph_buffer, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + ( + query, + key, + value, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + q_num_blocks, + q_indices, + full_q_num_blocks, + full_q_indices, + ) = maybe_realize( + [ + query, + key, + value, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + q_num_blocks, + q_indices, + full_q_num_blocks, + full_q_indices, + ] + ) + + if _use_flex_flash_attention( + subgraph, + mask_graph, + kernel_options, + num_score_mod_placeholders=len(placeholder_inps), + backend=backend, + ): + return create_flex_flash_attention_kernel( + query, + key, + value, + block_mask, + scale, + kernel_options, + subgraph_buffer, + mask_graph_buffer, + score_mod_other_buffers, + mask_mod_other_buffers, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + mask_graph=mask_graph, + subgraph=subgraph, + ) + + score_mod_other_buffers = maybe_realize(score_mod_other_buffers) + mask_mod_other_buffers = maybe_realize(mask_mod_other_buffers) + + freeze_irnodes(score_mod_other_buffers) + freeze_irnodes(mask_mod_other_buffers) + + Bq, Hq, seq_len_q, qk_head_dim = query.get_size() + Bkv, Hkv, seq_len_kv, v_head_dim = value.get_size() + if not V.graph.sizevars.evaluate_expr(sympy.Eq(Bq, Bkv) | sympy.Eq(Bkv, 1)): + raise AssertionError( + f"Bq and Bkv must broadcastable. Got Bq={Bq} and Bkv={Bkv}" + ) + if not V.graph.sizevars.evaluate_expr(sympy.Gt(seq_len_q, 0)): + raise AssertionError("Query length must be greater than 0") + if not V.graph.sizevars.evaluate_expr(sympy.Gt(seq_len_kv, 0)): + raise AssertionError("Key length must be greater than 0") + + B = Bq + + seq_q_divisible = can_skip_boundary_checks(seq_len_q, SPARSE_Q_BLOCK_SIZE) + seq_kv_divisible = can_skip_boundary_checks(seq_len_kv, SPARSE_KV_BLOCK_SIZE) + if seq_q_divisible and seq_kv_divisible: + kernel_options.setdefault("IS_DIVISIBLE", True) + else: + kernel_options.setdefault("IS_DIVISIBLE", False) + + # NB it is okay that the v_head_dim is different + # We are using these to match fill order of the output. + q_strides = query.get_stride() + # Construct output layout with strides matching the query. + out_size = [B, Hq, seq_len_q, v_head_dim] + out_strides = infer_dense_strides(out_size, q_strides) + + layout = FixedLayout( + query.get_device(), + query.get_dtype(), + [B, Hq, seq_len_q, v_head_dim], + stride=[sympy.sympify(s) for s in out_strides], + ) + # see NOTE:[TritonTemplates with multiple outputs] + logsumexp_shape = [B, Hq, seq_len_q] + logsumexp = empty_strided( + logsumexp_shape, + None, + dtype=torch.float32, # The logsumexp is always stored in fp32 regardless of the input dtype + device=query.get_device(), + ) + max_scores = empty_strided( + logsumexp_shape, # Same shape as logsumexp + None, + dtype=torch.float32, # The max scores are always stored in fp32 regardless of the input dtype + device=query.get_device(), + ) + kernel_options.setdefault("SM_SCALE", scale) + + # Determine GQA broadcast factor. + gqa_shared_heads = FloorDiv(Hq, Hkv) + kernel_options.setdefault("GQA_SHARED_HEADS", gqa_shared_heads) + + # Inside of Triton kernel, only apply partial masking if partial blocks are computed. + # full_kv_num_blocks is None if partial blocks are not computed + has_full_blocks = full_kv_num_blocks is not None + kernel_options.setdefault("HAS_FULL_BLOCKS", has_full_blocks) + if not has_full_blocks: + full_kv_num_blocks, full_kv_indices = ( + empty(0, device=query.get_device()) for _ in range(2) + ) + + set_head_dim_values(kernel_options, qk_head_dim, v_head_dim, V.graph.sizevars) + + choices: list[Any] = [] + + dtype = query.get_dtype() + head_dim = V.graph.sizevars.guard_int(query.get_size()[-1]) + configs: list[FlexConfig] = V.choices.get_flex_attention_fwd_configs( + head_dim, seq_len_q, dtype, query.get_device().type + ) + + # Mark SPARSE_KV_BLOCK_SIZE & SPARSE_Q_BLOCK_SIZE as static shapes and add guards. + SPARSE_KV_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_KV_BLOCK_SIZE) + SPARSE_Q_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_Q_BLOCK_SIZE) + + # Note, we don't need to pass in the captured buffers explicitly + # because they're implicitly added by the score_mod function + # We do need to explicitly pass it in for autotuning though. + original_kernel_options = kernel_options.copy() + # Default config for warp specialization + num_consumer_groups, num_buffers_warp_spec = 0, 0 + invalid_block_options: dict[str, Any] | None = None + + for conf in configs: + cur_kernel_options = original_kernel_options.copy() + # Performance tuning + # Triton parameters + # Remove prefix for forward kernels options and delete backward kernel options. + for k in list(cur_kernel_options.keys()): + if k.startswith("fwd_"): + v = cur_kernel_options.pop(k) + cur_kernel_options[k[4:]] = v + if k.startswith("bwd_"): + cur_kernel_options.pop(k) + cur_kernel_options.setdefault("num_stages", conf.num_stages) + cur_kernel_options.setdefault("num_warps", conf.num_warps) + if cur_kernel_options.get("num_consumer_groups", False): + cur_kernel_options.setdefault("num_consumer_groups", num_consumer_groups) + cur_kernel_options.setdefault( + "num_buffers_warp_spec", num_buffers_warp_spec + ) + + # Intel GPU enables TMA by default + cur_kernel_options.setdefault("USE_TMA", bool(torch.xpu.is_available())) + + if cur_kernel_options["USE_TMA"] and not can_use_tma(query, key, value): + cur_kernel_options["USE_TMA"] = False + + # Shrink default tiles to fit smaller pow2 sparse block sizes; + # user-pinned tiles and non-pow2 sparse sizes still error out below. + block_m, block_n = conf.block_m, conf.block_n + if len(configs) == 1 and all( + is_power_of_2(s) and s >= 16 + for s in (SPARSE_Q_BLOCK_SIZE, SPARSE_KV_BLOCK_SIZE) + ): + block_m = min(block_m, SPARSE_Q_BLOCK_SIZE) + block_n = min(block_n, SPARSE_KV_BLOCK_SIZE) + cur_kernel_options.setdefault("BLOCK_M", block_m) + cur_kernel_options.setdefault("BLOCK_N", block_n) + # Blocksparse options + cur_kernel_options.setdefault("SPARSE_Q_BLOCK_SIZE", SPARSE_Q_BLOCK_SIZE) + cur_kernel_options.setdefault("SPARSE_KV_BLOCK_SIZE", SPARSE_KV_BLOCK_SIZE) + + if ( + cur_kernel_options["SPARSE_KV_BLOCK_SIZE"] % cur_kernel_options["BLOCK_N"] + != 0 + or cur_kernel_options["SPARSE_Q_BLOCK_SIZE"] % cur_kernel_options["BLOCK_M"] + != 0 + ): + invalid_block_options = cur_kernel_options + if len(configs) == 1: + raise_flex_kernel_options_error( + "forward", + cur_kernel_options, + ("BLOCK_M", "BLOCK_N"), + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + ) + continue + + # ROCm specific kernargs + for attrib in ["kpack", "matrix_instr_nonkdim", "waves_per_eu"]: + if hasattr(conf, attrib): + cur_kernel_options[attrib] = getattr(conf, attrib) + + error = flex_attention_template.maybe_append_choice( + choices=choices, + input_nodes=[ + query, + key, + value, + logsumexp, + max_scores, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + ], + layout=layout, + subgraphs=[ + subgraph_buffer, + mask_graph_buffer, + ], + mutated_inputs=[ + logsumexp, + max_scores, + ], + call_sizes=query.get_size(), + **cur_kernel_options, + ) + if error is not None and len(configs) == 1: + raise error + + # Let the active choices handler append any backend-specific flex-attention + # template choices (e.g. TLX on Blackwell in fbcode). No-op by default. + choices = V.choices.append_flex_attention_choices( + choices, + configs, + [ + query, + key, + value, + logsumexp, + max_scores, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + ], + [subgraph_buffer, mask_graph_buffer], + layout, + original_kernel_options, + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + ) + + if not choices and invalid_block_options is not None: + raise_flex_kernel_options_error( + "forward", + invalid_block_options, + ("BLOCK_M", "BLOCK_N"), + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + ) + + inputs_for_autotuning = ( + [ + query, + key, + value, + logsumexp, + max_scores, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + ] + + list(score_mod_other_buffers) + + list(mask_mod_other_buffers) + ) + input_gen_fns = { + 5: create_num_blocks_fake_generator(kv_indices), + 6: create_indices_fake, + 7: create_num_blocks_fake_generator(full_kv_indices), + 8: create_indices_fake, + } + + out, _ = autotune_select_algorithm( + "flex_attention", + choices, + # Autotuning materializes benchmark tensors. Scalar shape captures stay + # in subgraph_inps below for dependency tracking and codegen. + [x for x in inputs_for_autotuning if is_tensor_ir_node(x)], + layout, + input_gen_fns=input_gen_fns, + ) + + # need subgraph inputs and outputs to analyze all symints used in flex attention + out.data.data.subgraph_inps = list(score_mod_other_buffers) + list( + mask_mod_other_buffers + ) + out.data.data.subgraph_outs = get_fwd_subgraph_outputs( + subgraph_buffer, mask_graph_buffer + ) + + return (out, logsumexp, max_scores) + + +# ---------------------------- Backward HOP Implementation ---------------------------- + + +@SymbolicGridFn +def flex_attention_backward_grid( + batch_size, q_heads, num_queries, d_model, kv_heads, num_key_value, meta, *, cdiv +): + """How is this kernel parallelized? + We create a grid of (ceil_div(n_queries, query_block_size) * heads_ratio + ceil_div(n_kv, kv_block_size), batch_size, kv_heads) + Currently this is only parallelizing over batch* kv_heads, but we can, and want to + parallelize over ceil_div(q_heads//kv_heads * num_key_value, key_value_block_size). + To do this will either require atomic updates to some grad values or to have a two pass kernel design. + """ + return ( + cdiv(num_queries, meta["BLOCK_M2"]) * (q_heads // kv_heads) + + cdiv(num_key_value, meta["BLOCK_N1"]), + batch_size, + kv_heads, + ) + + +flex_attention_backward_template = TritonTemplate( + name="flex_attention_backward", + grid=flex_attention_backward_grid, + source=load_flex_template("flex_backwards") + load_flex_template("utilities"), + always_freeze_layout=True, +) + + +def validate_joint_graph(joint_graph: torch.fx.Graph): + """We do some pre lowering graph checks in order to raise nicer error messages""" + for node in joint_graph.nodes: + if ( + node.op == "call_function" + and node.target is torch.ops.flex_lib.zeros_and_scatter.default + ): + for user in node.users: + if user.op != "output": + raise NotImplementedError( + "Using multiple indexing operations on the same tensor that requires gradients " + "in a score_mod function is not currently supported. " + "This typically happens when indexing the same tensor multiple times, like:\n\n" + " def score_mod(score, b, h, q_idx, kv_idx):\n" + " return score + bias[q_idx] + bias[kv_idx] # bias used twice!\n\n" + "A valid workaround is to clone() the tensors that will be indexed multiple times. For example:\n\n" + " bias1 = bias.clone()\n" + " def score_mod(score, b, h, q_idx, kv_idx):\n" + " return score + bias[q_idx] + bias1[kv_idx]\n\n" + "Note that this solution will use additional memory." + ) + return + + +@dataclass(frozen=True) +class JointOutputResult: + """Results from processing joint outputs.""" + + grad_input: ComputedBuffer + captured_grads_compute: list[ComputedBuffer] + captured_grads: list[TensorBox | None] + mutated_grads: list[TensorBox] + + +def process_joint_outputs( + all_joint_outputs: SubgraphResults, num_placeholders: int +) -> JointOutputResult: + """Process joint outputs and extract various buffers needed for lowering + + Args: + all_joint_outputs: List of all the outputs from build_subgraphs + num_placeholders: The number of placeholder inputs, used to skip over unused backward compute buffers + + Returns: + JointOutputResult containing processed buffers and gradients + """ + if not isinstance(all_joint_outputs, list): + raise AssertionError(f"Expected list, got {type(all_joint_outputs)}") + if all_joint_outputs[0] is None: + raise AssertionError("joint_subgraph_buffer is None - this is a bug!") + + joint_buffer = all_joint_outputs[0] + other_grads = all_joint_outputs[num_placeholders - 1 :] + + # outer_grads has the structure: Len(other_buffer_grads) if buffer doesn't require grad than it will be None + # We only grab the buffers that require grad for inlining into kernel + grads_compute = [buf for buf in other_grads if buf is not None] + + def get_out(buf): + if buf is None: + return None + if not isinstance(buf, ComputedBuffer): + raise AssertionError(f"Expected ComputedBuffer, got {type(buf)}") + if buf.name is None: + raise AssertionError("ComputedBuffer name must not be None") + return TensorBox.create(V.graph.get_buffer(buf.name)) + + grads_out = [get_out(x) for x in other_grads] + mutated_grads = [buf for buf in grads_out if buf is not None] + + return JointOutputResult( + grad_input=joint_buffer, + captured_grads_compute=grads_compute, + captured_grads=grads_out, + mutated_grads=mutated_grads, + ) + + +# TODO: We probably also need a layout constraint? +@register_lowering( + torch.ops.higher_order.flex_attention_backward, type_promotion_kind=None +) +def flex_attention_backward(*args, **kwargs): + """Lowering for the flex_attention_backward op in triton""" + ( + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + fw_graph, + joint_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) = args + if query.get_device().type == "mps": + raise NotImplementedError( + "flex_attention backward is not yet supported on MPS. " + "Use torch.no_grad() for inference." + ) + ( + _, # q_length + _, # kv_length + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + q_num_blocks, + q_indices, + full_q_num_blocks, + full_q_indices, + dq_write_order, + dq_write_order_full, + dq_kv_order, + dq_kv_order_spt, + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + mask_graph, + ) = block_mask + + ( + query, + key, + value, + logsumexp, + grad_out, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + q_num_blocks, + q_indices, + full_q_num_blocks, + full_q_indices, + dq_write_order, + dq_write_order_full, + dq_kv_order, + ) = maybe_realize( + [ + query, + key, + value, + logsumexp, + grad_out, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + q_num_blocks, + q_indices, + full_q_num_blocks, + full_q_indices, + dq_write_order, + dq_write_order_full, + dq_kv_order, + ] + ) + + device = query.get_device() + dtype = query.get_dtype() + Bq, Hq, seq_len_q, qk_head_dim = query.get_size() + Bkv, Hkv, seq_len_kv, v_head_dim = value.get_size() + + if not V.graph.sizevars.evaluate_expr(sympy.Eq(Bq, Bkv) | sympy.Eq(Bkv, 1)): + raise AssertionError( + f"Bq and Bkv must broadcastable. Got Bq={Bq} and Bkv={Bkv}" + ) + + kernel_options, backend = _sanitize_kernel_options_for_triton(kernel_options) + if backend == "FLASH": + _check_flash_supported_scalar_captures( + score_mod_other_buffers, mask_mod_other_buffers, backward=True + ) + score_mod_other_buffers = realize_captures_for_cutedsl(score_mod_other_buffers) + mask_mod_other_buffers = realize_captures_for_cutedsl(mask_mod_other_buffers) + + # Add check for mixed dtypes + if query.dtype != key.dtype or query.dtype != value.dtype: + raise ValueError( + f"Backward pass with mixed query, key, and value dtype is not supported, " + f"got query.dtype={query.dtype}, key.dtype={key.dtype}, " + f"and value.dtype={value.dtype}" + ) + # Mark symbols in custom kernel options as static shapes and add guards. + kernel_options = { + k: V.graph.sizevars.guard_int(v) if isinstance(v, sympy.Symbol) else v + for k, v in kernel_options.items() + } + kernel_options.setdefault("FLOAT32_PRECISION", get_float32_precision()) + kernel_options.setdefault("PRESCALE_QK", False) + kernel_options.setdefault("ROWS_GUARANTEED_SAFE", False) + kernel_options.setdefault("BLOCKS_ARE_CONTIGUOUS", False) + kernel_options.setdefault("WRITE_DQ", True) + seq_q_divisible = can_skip_boundary_checks(seq_len_q, SPARSE_Q_BLOCK_SIZE) + seq_kv_divisible = can_skip_boundary_checks(seq_len_kv, SPARSE_KV_BLOCK_SIZE) + if seq_q_divisible and seq_kv_divisible: + kernel_options.setdefault("IS_DIVISIBLE", True) + else: + kernel_options.setdefault("IS_DIVISIBLE", False) + + fwd_placeholder_inps = [ + create_placeholder(name, dtype, device) + for name, dtype in [ + ("score", dtype), + ("b", torch.int32), + ("h", torch.int32), + ("m", torch.int32), + ("n", torch.int32), + ] + ] + fw_subgraph_buffer = build_subgraph_buffer( + fwd_placeholder_inps + list(score_mod_other_buffers), fw_graph + ) + freeze_irnodes(fw_subgraph_buffer) + + joint_placeholder_inps = fwd_placeholder_inps + [ + create_placeholder("grad_score_mod", dtype, device) + ] + # Sometimes we have weird unused nodes here + joint_graph.graph_module.graph.eliminate_dead_code() + + # It is hard to raise nice errors for some joint graphs during subgraph lowering + # This lets us do some checks before attempting to lower + validate_joint_graph(joint_graph.graph_module.graph) + + all_joint_outputs = build_subgraph_buffer( + joint_placeholder_inps + list(score_mod_other_buffers), + joint_graph, + ) + + freeze_irnodes(all_joint_outputs) + + joint_outputs = process_joint_outputs( + all_joint_outputs, len(joint_placeholder_inps) + ) + + mask_graph_placeholder_inps = [ + create_placeholder(name, dtype, query.get_device()) + for name, dtype in [ + ("b", torch.int32), + ("h", torch.int32), + ("m", torch.int32), + ("n", torch.int32), + ] + ] + mask_graph_buffer = build_subgraph_buffer( + mask_graph_placeholder_inps + list(mask_mod_other_buffers), mask_graph + ) + freeze_irnodes(mask_graph_buffer) + + if _use_flex_flash_attention_backward( + fw_graph, + mask_graph, + backend=backend, + joint_outputs=joint_outputs, + score_mod_other_buffers=score_mod_other_buffers, + ): + needs_block_mask = not is_trivial_mask_graph(mask_graph.graph_module) + if grad_logsumexp is not None: + (grad_logsumexp,) = maybe_realize([grad_logsumexp]) + + score_is_trivial = is_trivial_score_graph(fw_graph.graph_module) + return create_flex_flash_attention_backward_kernel( + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + scale, + kernel_options, + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + fw_subgraph_buffer=None if score_is_trivial else fw_subgraph_buffer, + joint_subgraph_buffer=None + if score_is_trivial + else joint_outputs.grad_input, + score_mod_other_buffers=list(score_mod_other_buffers), + mask_graph_buffer=mask_graph_buffer if needs_block_mask else None, + mask_mod_other_buffers=list(mask_mod_other_buffers), + q_num_blocks=q_num_blocks if needs_block_mask else None, + q_indices=q_indices if needs_block_mask else None, + full_q_num_blocks=full_q_num_blocks if needs_block_mask else None, + full_q_indices=full_q_indices if needs_block_mask else None, + dq_write_order=dq_write_order if needs_block_mask else None, + dq_write_order_full=dq_write_order_full if needs_block_mask else None, + dq_kv_order=dq_kv_order if needs_block_mask else None, + dq_kv_order_spt=dq_kv_order_spt, + ) + + # Construct layout with stride order matching K + key_size = [Bq, Hkv, seq_len_kv, qk_head_dim] + key_strides = infer_dense_strides(key_size, key.get_stride()) + + layout_broadcasted_k = FixedLayout( + key.get_device(), + key.get_dtype(), + key_size, + stride=[sympy.sympify(s) for s in key_strides], + ) + + # Create delta which will is needed for the bwd's kernel + mul_delta = lowerings[aten.mul](out, grad_out) + delta = lowerings[aten.sum](mul_delta, axis=-1) + delta = lowerings[prims.convert_element_type](delta, torch.float32) + if grad_logsumexp is not None: + grad_lse_exp2 = lowerings[aten.mul](grad_logsumexp, 1 / math.log(2)) + grad_lse_exp2 = ExternKernel.require_contiguous(grad_lse_exp2) + delta = lowerings[aten.sub](delta, grad_lse_exp2) + delta = ExternKernel.require_contiguous(delta) + delta, grad_lse_exp2 = maybe_realize([delta, grad_lse_exp2]) + else: + delta = ExternKernel.require_contiguous(delta) + (delta,) = maybe_realize([delta]) + + # # see NOTE:[TritonTemplates with multiple outputs] + query_size = [Bq, Hq, seq_len_q, qk_head_dim] + grad_query_strides = infer_dense_strides(query_size, query.get_stride()) + grad_query = empty_strided( + query_size, + stride=[sympy.sympify(s) for s in grad_query_strides], + dtype=query.get_dtype(), + device=query.get_device(), + ) + + # Construct output layout with stride order matching value + value_size = [Bq, Hkv, seq_len_kv, v_head_dim] + value_strides = infer_dense_strides(value_size, value.get_stride()) + + broadcasted_grad_value = empty_strided( + value_size, + stride=[sympy.sympify(s) for s in value_strides], + dtype=value.get_dtype(), + device=value.get_device(), + ) + + kernel_options.setdefault("SM_SCALE", scale) + + # Determine GQA factor + gqa_shared_heads = FloorDiv(Hq, Hkv) + kernel_options.setdefault("GQA_SHARED_HEADS", gqa_shared_heads) + + # Inside of Triton kernel, only apply partial masking if partial blocks are computed. + # full_kv_num_blocks is torch.zeros([1, 1, 1]) if partial blocks are not computed. + has_full_blocks = full_kv_num_blocks is not None + kernel_options.setdefault("HAS_FULL_BLOCKS", has_full_blocks) + if not has_full_blocks: + full_kv_num_blocks, full_kv_indices, full_q_num_blocks, full_q_indices = ( + empty(0, device=query.get_device()) for _ in range(4) + ) + + set_head_dim_values(kernel_options, qk_head_dim, v_head_dim, V.graph.sizevars) + + SPARSE_Q_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_Q_BLOCK_SIZE) + SPARSE_KV_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_KV_BLOCK_SIZE) + + choices: list[Any] = [] + + dtype = query.get_dtype() + head_dim = V.graph.sizevars.guard_int(query.get_size()[-1]) + configs: list[FlexBwDConfig] = V.choices.get_flex_attention_bwd_configs( + head_dim, dtype, query.get_device().type + ) + + # Default config for warp specialization + num_consumer_groups, num_buffers_warp_spec = 0, 0 + invalid_block_options: dict[str, Any] | None = None + + original_kernel_options = kernel_options.copy() + + for conf in configs: + # Performance tuning + # Triton heuristics + cur_kernel_options = original_kernel_options.copy() + # Remove prefix for backward kernels options and delete forward kernel options. + for k in list(cur_kernel_options.keys()): + if k.startswith("bwd_"): + v = cur_kernel_options.pop(k) + cur_kernel_options[k[4:]] = v + if k.startswith("fwd_"): + cur_kernel_options.pop(k) + cur_kernel_options.setdefault("num_warps", conf.num_warps) + cur_kernel_options.setdefault("num_stages", conf.num_stages) + + if cur_kernel_options.get("num_consumer_groups", False): + cur_kernel_options.setdefault("num_consumer_groups", num_consumer_groups) + cur_kernel_options.setdefault( + "num_buffers_warp_spec", num_buffers_warp_spec + ) + + # Intel GPU enables TMA by default + cur_kernel_options.setdefault("USE_TMA", bool(torch.xpu.is_available())) + + if cur_kernel_options["USE_TMA"] and not can_use_tma(query, key, value): + cur_kernel_options["USE_TMA"] = False + + # Shrink default tiles to fit smaller pow2 sparse block sizes; + # user-pinned tiles and non-pow2 sparse sizes still error out below. + block_m1, block_n1 = conf.block_m1, conf.block_n1 + block_m2, block_n2 = conf.block_m2, conf.block_n2 + if len(configs) == 1 and all( + is_power_of_2(s) and s >= 16 + for s in (SPARSE_Q_BLOCK_SIZE, SPARSE_KV_BLOCK_SIZE) + ): + block_m1 = min(block_m1, SPARSE_Q_BLOCK_SIZE) + block_n1 = min(block_n1, SPARSE_KV_BLOCK_SIZE) + block_m2 = min(block_m2, SPARSE_Q_BLOCK_SIZE) + block_n2 = min(block_n2, SPARSE_KV_BLOCK_SIZE) + # Kernel static asserts: BLOCK_N1 % BLOCK_M1 == BLOCK_M2 % BLOCK_N2 == 0 + block_m1 = min(block_m1, block_n1) + block_n2 = min(block_n2, block_m2) + cur_kernel_options.setdefault("BLOCK_M1", block_m1) + cur_kernel_options.setdefault("BLOCK_N1", block_n1) + cur_kernel_options.setdefault("BLOCK_M2", block_m2) + cur_kernel_options.setdefault("BLOCK_N2", block_n2) + + # Blocksparse options + cur_kernel_options.setdefault("SPARSE_Q_BLOCK_SIZE", SPARSE_Q_BLOCK_SIZE) + cur_kernel_options.setdefault("SPARSE_KV_BLOCK_SIZE", SPARSE_KV_BLOCK_SIZE) + + if ( + cur_kernel_options["SPARSE_KV_BLOCK_SIZE"] % cur_kernel_options["BLOCK_N1"] + != 0 + or cur_kernel_options["SPARSE_Q_BLOCK_SIZE"] + % cur_kernel_options["BLOCK_M1"] + != 0 + or cur_kernel_options["SPARSE_KV_BLOCK_SIZE"] + % cur_kernel_options["BLOCK_N2"] + != 0 + or cur_kernel_options["SPARSE_Q_BLOCK_SIZE"] + % cur_kernel_options["BLOCK_M2"] + != 0 + # Kernel static asserts; validate here for a friendly error. + or cur_kernel_options["BLOCK_N1"] % cur_kernel_options["BLOCK_M1"] != 0 + or cur_kernel_options["BLOCK_M2"] % cur_kernel_options["BLOCK_N2"] != 0 + ): + invalid_block_options = cur_kernel_options + if len(configs) == 1: + raise_flex_kernel_options_error( + "backward", + cur_kernel_options, + ("BLOCK_M1", "BLOCK_N1", "BLOCK_M2", "BLOCK_N2"), + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + ) + continue + + # ROCm specific kernargs + for attrib in ["kpack", "matrix_instr_nonkdim", "waves_per_eu"]: + if hasattr(conf, attrib): + cur_kernel_options[attrib] = getattr(conf, attrib) + + flex_attention_backward_template.maybe_append_choice( + choices=choices, + input_nodes=[ + query, + key, + value, + logsumexp, + delta, + grad_out, + grad_query, + broadcasted_grad_value, + kv_num_blocks, + kv_indices, + q_num_blocks, + q_indices, + full_kv_num_blocks, + full_kv_indices, + full_q_num_blocks, + full_q_indices, + ], + layout=layout_broadcasted_k, # We use store_output only for grad_key + subgraphs=[ + fw_subgraph_buffer, + joint_outputs.grad_input, + mask_graph_buffer, + joint_outputs.captured_grads_compute, + ], + mutated_inputs=[ + grad_query, + broadcasted_grad_value, + *joint_outputs.mutated_grads, + ], + call_sizes=query.get_size() + key.get_size()[1:3], + **cur_kernel_options, + ) + + if not choices and invalid_block_options is not None: + raise_flex_kernel_options_error( + "backward", + invalid_block_options, + ("BLOCK_M1", "BLOCK_N1", "BLOCK_M2", "BLOCK_N2"), + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + ) + + score_mod_other_buffers = maybe_realize(score_mod_other_buffers) + mask_mod_other_buffers = maybe_realize(mask_mod_other_buffers) + + inputs_for_autotuning = ( + [ + query, + key, + value, + logsumexp, + delta, + grad_out, + grad_query, + broadcasted_grad_value, + kv_num_blocks, + kv_indices, + q_num_blocks, + q_indices, + full_kv_num_blocks, + full_kv_indices, + full_q_num_blocks, + full_q_indices, + ] + + list(score_mod_other_buffers) + + list(mask_mod_other_buffers) + + joint_outputs.mutated_grads + ) + input_gen_fns = { + 8: create_num_blocks_fake_generator(kv_indices), # kv_num_blocks + 9: create_indices_fake, + 10: create_num_blocks_fake_generator(q_indices), # q_num_blocks + 11: create_indices_fake, + 12: create_num_blocks_fake_generator(full_kv_indices), # full_kv_num_blocks + 13: create_indices_fake, + 14: create_num_blocks_fake_generator(full_q_indices), # full_q_num_blocks + 15: create_indices_fake, + } + + broadcasted_grad_key, _ = autotune_select_algorithm( + "flex_attention_backward", + choices, + # Autotuning materializes benchmark tensors. Scalar shape captures stay + # in subgraph_inps below for dependency tracking and codegen. + [x for x in inputs_for_autotuning if is_tensor_ir_node(x)], + layout_broadcasted_k, + input_gen_fns=input_gen_fns, + ) # [Bq, Hkv, seq_len_kv, k_head_dim] + + # need subgraph inputs and outputs to analyze all symints used in flex attention + broadcasted_grad_key.data.data.subgraph_inps = list(score_mod_other_buffers) + list( + mask_mod_other_buffers + ) + broadcasted_grad_key.data.data.subgraph_outs = get_bwd_subgraph_outputs( + fw_subgraph_buffer, mask_graph_buffer, joint_outputs + ) + + if V.graph.sizevars.evaluate_expr(sympy.Eq(Bq, Bkv)): + grad_key = broadcasted_grad_key + grad_value = broadcasted_grad_value + else: + if not V.graph.sizevars.evaluate_expr(sympy.Gt(Bq, 1) & sympy.Eq(Bkv, 1)): + raise AssertionError( + f"Bq and Bkv must broadcastable. " + f"Got Bq={V.graph.sizevars.evaluate_expr(Bq)} " + f"and Bkv={V.graph.sizevars.evaluate_expr(Bkv)}" + ) + grad_key = lowerings[aten.sum](broadcasted_grad_key, axis=0, keepdims=True) + grad_value = lowerings[aten.sum](broadcasted_grad_value, axis=0, keepdims=True) + + # Cast captured grads to match original buffer dtypes. Gradients are accumulated + # in fp32 for precision, then cast to the original dtype (e.g., bf16) here. + captured_grads = tuple( + to_dtype(g, orig.get_dtype()) + if g is not None and g.get_dtype() != orig.get_dtype() + else g + for g, orig in zip(joint_outputs.captured_grads, score_mod_other_buffers) + ) + + return (grad_query, grad_key, grad_value, captured_grads) + + +def get_bwd_subgraph_outputs( + subgraph_buffer: SubgraphResults, + mask_graph_buffer: SubgraphResults, + joint_outputs: JointOutputResult, +) -> list[ComputedBuffer | TensorBox | None]: + subgraph_buffer = ( + subgraph_buffer if isinstance(subgraph_buffer, Sequence) else [subgraph_buffer] + ) + mask_graph_buffer = ( + mask_graph_buffer + if isinstance(mask_graph_buffer, Sequence) + else [mask_graph_buffer] + ) + joint_output_buffers = [ + joint_outputs.grad_input, + *joint_outputs.captured_grads_compute, + *joint_outputs.captured_grads, + *joint_outputs.mutated_grads, + ] + + return [*subgraph_buffer, *mask_graph_buffer, *joint_output_buffers] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_cpu.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..7b7b5797fb35c2b9e2a438b8054567245a1b4e83 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_cpu.py @@ -0,0 +1,369 @@ +# mypy: allow-untyped-defs +"""CPU-specific implementations for flex attention""" + +import copy +import os +import sys +from typing import Any + +import sympy + +import torch +from torch._inductor.virtualized import V +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.numbers import int_oo +from torch.utils._sympy.value_ranges import ValueRanges + +from ...codegen.cpp_flex_attention_template import CppFlexAttentionTemplate +from ...ir import Buffer, ExternKernel, FixedLayout, TensorBox +from ...select_algorithm import autotune_select_algorithm +from .common import ( + build_subgraph_buffer, + build_subgraph_module_buffer, + contiguous_last_dim, + create_placeholder, + get_fwd_subgraph_outputs, + infer_dense_strides, + maybe_realize, +) + + +def check_cpu_supported(): + requires_avx2_on_cpu = ( + torch.cpu._is_avx2_supported() and os.getenv("ATEN_CPU_CAPABILITY") != "default" + ) + supported = ( + requires_avx2_on_cpu + and not torch.xpu.is_available() + and sys.platform != "darwin" + ) + return supported + + +def _realize_duplicate_buffer_inputs(inputs): + names = [inp.get_name() for inp in inputs] + duplicate_names = OrderedSet(name for name in names if names.count(name) > 1) + if not duplicate_names: + return inputs + + # The C++ template names pointer arguments by storage buffer name. + # ReinterpretView inputs that share storage (for example, q/k from + # qk.chunk()) need distinct realized buffers so their view offsets are + # represented correctly at the template boundary. + return [ + ExternKernel.copy_input(inp) if inp.get_name() in duplicate_names else inp + for inp in inputs + ] + + +def lower_cpu( + query, + key, + value, + subgraph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, +): + """CPP based template for flex attention for x86 CPUs""" + ( + _, # q_length + _, # kv_length + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + q_num_blocks, + q_indices, + full_q_num_blocks, + full_q_indices, + _, # dq_write_order + _, # dq_write_order_full + _, # dq_kv_order + _, # dq_kv_order_spt + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + mask_graph, + ) = block_mask + + if query.dtype != key.dtype or query.dtype != value.dtype: + raise ValueError( + f"Mixed query, key, and value dtype is not supported on this platform, " + f"got query.dtype: {query.dtype}, key.dtype: {key.dtype}, " + f"and value.dtype: {value.dtype}." + ) + + if kernel_options["OUTPUT_LOGSUMEXP"]: + raise NotImplementedError( + "torch.compile on CPU only supports inference and `return_lse` is not supported yet." + ) + if not check_cpu_supported(): + raise NotImplementedError( + "torch.compile on current platform is not supported for CPU." + ) + + fake_buffers: list[Buffer] = [] + + # [Note] Handle the case where the split sizes are not statically known. + # The value of cur_qSplitSize and cur_kvSplitSize are decided during runtime. + # We use symbols to represent them during the compilation here. + # They'll be replaced by the string "cur_qSplitSize" and "cur_kvSplitSize" in + # the modification function of the CppFlexAttentionTemplate class. + cur_qSplitSize = V.graph.sizevars.shape_env.create_unbacked_symint().node.expr + cur_kvSplitSize = V.graph.sizevars.shape_env.create_unbacked_symint().node.expr + shape_env = V.graph.sizevars.shape_env + + # We don't know the concrete value of cur_qSplitSize and cur_kvSplitSize during the compilation. + # Mark symbols > 1 to ensure broadcasting is always applied. + # This avoids treating them as equal when `eq(var, 1)` is evaluated in `broadcast_symbolic_shapes`. + shape_env.var_to_range[cur_qSplitSize] = ValueRanges(2, int_oo) + shape_env.var_to_range[cur_kvSplitSize] = ValueRanges(2, int_oo) + + score_dtype = torch.float + placeholder_inps = [ + create_placeholder(name, dtype, query.get_device(), size) + for name, dtype, size in [ + ("score", score_dtype, [cur_qSplitSize, cur_kvSplitSize]), + ("b", torch.int64, []), + ("h", torch.int64, []), + ("q_idx", torch.int64, [cur_qSplitSize, 1]), + ("kv_idx", torch.int64, [1, cur_kvSplitSize]), + ] + ] + subgraph_buffer = build_subgraph_buffer( + placeholder_inps + list(score_mod_other_buffers), subgraph + ) + if subgraph_buffer is not None: + if isinstance(subgraph_buffer, list): + for _buf in subgraph_buffer: + if _buf is not None: + _buf.freeze_layout() + else: + subgraph_buffer.freeze_layout() + mask_graph_placeholder_inps = [ + create_placeholder(name, dtype, query.get_device(), size) + for name, dtype, size in [ + ("score", score_dtype, [cur_qSplitSize, cur_kvSplitSize]), + ("b", torch.int64, []), + ("h", torch.int64, []), + ("q_idx", torch.int64, [cur_qSplitSize, 1]), + ("kv_idx", torch.int64, [1, cur_kvSplitSize]), + ] + ] + + # The original mask_graph works on a scalar and only includes + # the logic of calculating the mask value. + # We need to add the logic of applying the mask to the qk_data tensor + # into the graph for the later codegen of this part. + # Example: + # mask_graph: + # def mask_fn(b, h, q_idx, kv_idx): + # mask = q_idx >= kv_idx + # return mask + # The converted_mask_graph should be: + # def converted_mask_fn(qk_data, b, h, q_idx, kv_idx): + # mask = q_idx >= kv_idx + # qk_data = torch.where(mask, qk_data, torch.full_like(qk_data, -float("inf"))) + # return qk_data + def convert_mask_graph_module(mask_graph): + gm = copy.deepcopy(mask_graph.graph_module) + graph = gm.graph + # Add qk_data as the first input + with graph.inserting_before(next(iter(graph.nodes))): + qk_data_node = graph.placeholder("qk_data") + + # Find the node that returns the mask + output_node = None + for node in graph.nodes: + if node.op == "output": + output_node = node + break + + # Get the mask node + if output_node is None: + raise AssertionError("output_node must not be None") + mask_node = output_node.args[0] + + size_node = [cur_qSplitSize, cur_kvSplitSize] + # Create a new node for torch.full + with graph.inserting_after(mask_node): + full_node = graph.call_function( + torch.full, + args=(size_node, -float("inf")), + kwargs={"dtype": score_dtype}, + ) + + # Create a new node for torch.where + with graph.inserting_after(full_node): + where_node = graph.call_function( + torch.ops.aten.where, args=(mask_node, qk_data_node, full_node) + ) + + # Update the output node to return the result of torch.where + output_node.args = (where_node,) + + graph.lint() + converted = torch.fx.GraphModule(gm, graph) + return converted + + converted_mask_graph_module = convert_mask_graph_module(mask_graph) + + mask_graph_buffer = build_subgraph_module_buffer( + mask_graph_placeholder_inps + list(mask_mod_other_buffers), + converted_mask_graph_module, + ) + + # Clear the pending fresh unbacked symbols that are created for cur_qSplitSize and cur_kvSplitSize in the current kernel. + pending = V.graph.sizevars.shape_env.pending_fresh_unbacked_symbols + V.graph.sizevars.shape_env.pending_fresh_unbacked_symbols = [ + x for x in pending if x not in (cur_qSplitSize, cur_kvSplitSize) + ] + + buffer_list = ( + placeholder_inps + + list(score_mod_other_buffers) + + mask_graph_placeholder_inps + + list(mask_mod_other_buffers) + ) + for item in buffer_list: + if isinstance(item, TensorBox): + fake_buffers.append(item.data.data) # type: ignore[attr-defined] + + # CPU kernel requires last dim to be contiguous + query, key, value = map(contiguous_last_dim, [query, key, value]) + + ( + query, + key, + value, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + q_num_blocks, + q_indices, + full_q_num_blocks, + full_q_indices, + ) = maybe_realize( + [ + query, + key, + value, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + q_num_blocks, + q_indices, + full_q_num_blocks, + full_q_indices, + ] + ) + + query, key, value = _realize_duplicate_buffer_inputs([query, key, value]) + if query.get_dtype() not in [torch.float, torch.bfloat16, torch.float16]: + raise NotImplementedError( + "`torch.float` , `torch.float16` and `torch.bfloat16` are supported in FlexAttention for CPU device. " + f"Found input tensors are `{query.get_dtype()}`." + ) + score_mod_other_buffers = maybe_realize(score_mod_other_buffers) + mask_mod_other_buffers = maybe_realize(mask_mod_other_buffers) + Bq, Hq, seq_len_q, qk_head_dim = query.get_size() + Bkv, Hkv, seq_len_kv, v_head_dim = value.get_size() + B = Bq + + # Construct output layout with strides matching the query. + out_size = [B, Hq, seq_len_q, v_head_dim] + out_strides = infer_dense_strides(out_size, query.get_stride()) + + layout = FixedLayout( + query.get_device(), + query.get_dtype(), + [B, Hq, seq_len_q, v_head_dim], + stride=[sympy.sympify(s) for s in out_strides], + ) + _choices: list[Any] = [] + input_nodes = [query, key, value, kv_num_blocks, kv_indices] + if not full_kv_num_blocks: + no_full_kv_block = True + else: + no_full_kv_block = False + input_nodes += [full_kv_num_blocks] + input_nodes += [full_kv_indices] + has_other_buffer = False + kernel_input_name_to_buffer = {} + if score_mod_other_buffers or mask_mod_other_buffers: + has_other_buffer = True + + for prefix, buffers in [ + ("score_others", score_mod_other_buffers), + ("mask_others", mask_mod_other_buffers), + ]: + kernel_input_name_to_buffer.update( + {f"{prefix}_{i}": buf for i, buf in enumerate(buffers)} + ) + input_nodes += [ + value + for value in kernel_input_name_to_buffer.values() + if not isinstance(value, sympy.Expr) + ] + + skip_mask_score = kernel_options.get("SKIP_MASK_SCORE", False) + # Mark SPARSE_KV_BLOCK_SIZE & SPARSE_Q_BLOCK_SIZE as static shapes and add guards. + SPARSE_KV_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_KV_BLOCK_SIZE) + SPARSE_Q_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_Q_BLOCK_SIZE) + # In flash decoding, the partition size of doing the parallelism on KV length dim + PARTITION_SIZE = kernel_options.get("PARTITION_SIZE", 128) + if not V.graph.sizevars.evaluate_expr( + sympy.Le(seq_len_q, sympy.Mul(kv_indices.get_size()[-2], SPARSE_Q_BLOCK_SIZE)) + ): + raise AssertionError( + "Q seqlen must be smaller than the block_mask size in the Q dimension, considering pass a larger block_mask." + ) + if not V.graph.sizevars.evaluate_expr( + sympy.Le(seq_len_kv, sympy.Mul(kv_indices.get_size()[-1], SPARSE_KV_BLOCK_SIZE)) + ): + raise AssertionError( + "KV seqlen must be smaller than the block_mask size in the KV dimension, considering pass a larger block_mask." + ) + CppFlexAttentionTemplate.add_choices( + choices=_choices, + input_nodes=input_nodes, + layout=layout, + scale=scale, + score_mod=None if skip_mask_score else subgraph_buffer, + mask_mod=None if skip_mask_score else mask_graph_buffer, + kv_block_size=SPARSE_KV_BLOCK_SIZE, + q_block_size=SPARSE_Q_BLOCK_SIZE, + partition_size=PARTITION_SIZE, + has_other_buffer=has_other_buffer, + no_full_kv_block=no_full_kv_block, + fake_buffers=fake_buffers, + len_score_other=len(score_mod_other_buffers), + len_mask_other=len(mask_mod_other_buffers), + kernel_input_name_to_buffer=kernel_input_name_to_buffer, + block_vars=(cur_qSplitSize, cur_kvSplitSize), + ) + inputs_for_autotuning = [ + query, + key, + value, + ] + res, _ = autotune_select_algorithm( + "flex_attention", + _choices, + inputs_for_autotuning, + layout, + ) + + # need subgraph inputs and outputs to analyze all symints used in flex attention + res.data.data.subgraph_inps = list(score_mod_other_buffers) + list( + mask_mod_other_buffers + ) + res.data.data.subgraph_outs = get_fwd_subgraph_outputs( + subgraph_buffer, mask_graph_buffer + ) + + return (res,) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_decoding.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_decoding.py new file mode 100644 index 0000000000000000000000000000000000000000..c2a076ae0e988af953b6ae9a30651da2c4ab29c5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_decoding.py @@ -0,0 +1,509 @@ +# mypy: allow-untyped-defs +"""Triton Implementation of the flex_attention Kernel for short query length (FlexDecoding)""" + +import logging +from typing import Any + +import sympy + +import torch +from torch._inductor.virtualized import V +from torch.utils._sympy.functions import FloorDiv, Mod + +from ... import ir +from ...ir import FixedLayout, FlexibleLayout +from ...lowering import empty, empty_strided, lowerings +from ...runtime.runtime_utils import ceildiv, is_power_of_2, next_power_of_2 +from ...select_algorithm import ( + autotune_select_algorithm, + SymbolicGridFn, + TritonTemplate, +) +from ...utils import can_use_tma +from .common import ( + _flex_kernel_options_example, + _flex_kernel_tuning_options, + can_skip_boundary_checks, + create_indices_fake, + create_num_blocks_fake_generator, + freeze_irnodes, + get_fwd_subgraph_outputs, + is_tensor_ir_node, + load_flex_template, + maybe_realize, + set_head_dim_values, +) + + +aten = torch.ops.aten +prims = torch.ops.prims + +log = logging.getLogger(__name__) + + +def raise_flex_decoding_kernel_options_error( + kernel_options: dict[str, Any], + sparse_q_block_size: int, + sparse_kv_block_size: int, +) -> None: + formated_kernel_options = ", ".join( + f"{name}={kernel_options[name]}" for name in ("BLOCK_M", "BLOCK_N") + ) + raise ValueError( + "Invalid FlexAttention decode kernel options: Q and KV block sizes must " + "be divisible by the selected tile sizes. Got " + f"SPARSE_Q_BLOCK_SIZE={sparse_q_block_size}, " + f"SPARSE_KV_BLOCK_SIZE={sparse_kv_block_size}, and " + f"{formated_kernel_options}. " + "Pass compatible values with kernel_options. Available decode tuning " + f"options are {_flex_kernel_tuning_options('decode')}. For example: " + f"{_flex_kernel_options_example('decode')}. If you did not pin " + "these options, compiling with mode='max-autotune-no-cudagraphs' " + "can also fix this by trying more FlexAttention configs." + ) + + +def _use_flex_decoding(query, kv_indices, value, kernel_options, enable_gqa) -> bool: + """Decide which kernel to use, return true if use flex decoding kernel. + Note: + Since the number of splits is calculated based on the number of batch and head dims + we need to ensure that the batch and head dims are statically known. Otherwise we just + use the main flex_attention kernel. + """ + force_flex = kernel_options.get("FORCE_USE_FLEX_ATTENTION", False) + + # Decode eligibility is an optimization choice, not a user-visible contract, + # so every predicate below uses guard_or_false (case 2 of Note [guard_or_]: + # the program behaves equivalently whether we pick decode or the general + # kernel). guard_or_false returns the real result when ShapeEnv can prove or + # guard it, and conservatively returns False for an unprovable unbacked size. + # We deliberately do NOT use torch._check here: failing to prove eligibility + # must fall back to the general FlexAttention kernel, never impose a runtime + # constraint on the user's shapes. We also do NOT use guard_or_true: an + # unknown predicate should disable decode, not silently enable it. + short_query_length = V.graph.sizevars.guard_or_false( + sympy.Lt(query.get_size()[-2], 128) + ) + non_zero_length = V.graph.sizevars.guard_or_false(sympy.Gt(query.get_size()[-2], 0)) + static_batch = isinstance(query.get_size()[0], (int, sympy.Integer)) + static_num_heads = isinstance(query.get_size()[1], (int, sympy.Integer)) + if enable_gqa: + # in the current flex decoding triton kernel, grouped query heads for the + # same kv head are handled by the same block. So it's hard to support different + # kv num blocks for grouped query heads. We just fall back to main flex_attention + # kernel where each query head is handled by a separate block. + valid_block_mask_num_heads = V.graph.sizevars.guard_or_false( + sympy.Eq(kv_indices.get_size()[1], 1) + ) + else: + valid_block_mask_num_heads = V.graph.sizevars.guard_or_false( + sympy.Or( + sympy.Eq(kv_indices.get_size()[1], 1), + sympy.Eq(kv_indices.get_size()[1], query.get_size()[1]), + ) + ) + + Hq = query.get_size()[1] + Hkv = value.get_size()[1] + ratio = FloorDiv(Hq, Hkv) + + pw_of_two = V.graph.sizevars.guard_or_false( + sympy.And(sympy.Gt(ratio, 0), sympy.Eq(ratio & (ratio - 1), 0)) + ) + + out = ( + not force_flex + and not kernel_options.get("OUTPUT_MAX", False) + and short_query_length + and static_batch + and static_num_heads + and non_zero_length + and valid_block_mask_num_heads + and pw_of_two + ) + log.debug( + "Use flex decoding %s, force_flex_attention=%s, short_query_length=%s, static_batch=%s, static_num_heads=%s", + out, + force_flex, + short_query_length, + static_batch, + static_num_heads, + ) + return out + + +@SymbolicGridFn +def flex_decoding_grid(batch_size, kv_heads, gqa_group_size, seq_len_q, d_model, meta): + """How is this kernel parallelized? + We create a grid of (batch_size * kv_heads, SPLIT_KV, 1) + Each block is responsible for iterating over blocks of keys and values calculating + the local output for their tile of keys and values over all full length of query. + groups of SPLIT_KV blocks then combine their output to produce the final result. + """ + + BLOCK_M = meta["BLOCK_M"] + num_block_m = ceildiv(seq_len_q * gqa_group_size, BLOCK_M) + return (num_block_m, batch_size * kv_heads, meta["SPLIT_KV"]) + + +flex_decoding_template = TritonTemplate( + name="flex_decoding", + grid=flex_decoding_grid, + source=load_flex_template("flex_decode") + + load_flex_template("utilities") + + load_flex_template("common"), + always_freeze_layout=True, +) + + +def get_split_k(B: int, H: int, Mk: int) -> int: + if torch.xpu.is_available(): + num_SM = torch.xpu.get_device_properties("xpu").gpu_subslice_count + else: + num_SM = torch.cuda.get_device_properties("cuda").multi_processor_count + bh = max(B * H, 1) # NOTE: Handle B*h=0 case + if not isinstance(bh, (int, sympy.Integer)): + raise AssertionError("B and H must be concrete integers") + split_k = num_SM // bh * 2 # Each SM should at least get one block. + # TODO: workload evening at runtime for splits fully masked out. + # Before we have runtime workload evening, assign 2 splits per SM. + split_k = max(split_k, 1) + + return split_k + + +def create_flex_decoding_kernel(*args, **kwargs): + """Flex decode lowering that is optimized for small Q_LEN and GQA packing""" + ( + query, + key, + value, + block_mask, + scale, + kernel_options, + score_mod_subgraph, + mask_mod_subgraph, + score_mod_other_buffers, + mask_mod_other_buffers, + ) = args + ( + _, # q_length + _, # kv_length + kv_num_blocks, + kv_indices, + full_kv_num_blocks, # full_kv_num_blocks, + full_kv_indices, # full_kv_indices, + _, # q_num_blocks + _, # q_indices + _, # full_q_num_blocks, + _, # full_q_indices, + _, # dq_write_order + _, # dq_write_order_full + _, # dq_kv_order + _, # dq_kv_order_spt + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + _, + ) = block_mask + + Bq, Hq, seq_len_q, qk_head_dim = query.get_size() + Bkv, Hkv, seq_len_kv, v_head_dim = value.get_size() + + if not V.graph.sizevars.evaluate_expr(sympy.Eq(Bq, Bkv) | sympy.Eq(Bkv, 1)): + raise AssertionError( + f"Bq and Bkv must broadcastable. Got Bq={Bq} and Bkv={Bkv}" + ) + + B = Bq + kernel_options = dict(kernel_options) + # Mark symbols in custom kernel options as static shapes and add guards. + kernel_options = { + k: V.graph.sizevars.guard_int(v) if isinstance(v, sympy.Symbol) else v + for k, v in kernel_options.items() + } + + seq_q_divisible = can_skip_boundary_checks(seq_len_q, SPARSE_Q_BLOCK_SIZE) + seq_kv_divisible = can_skip_boundary_checks(seq_len_kv, SPARSE_KV_BLOCK_SIZE) + if seq_q_divisible and seq_kv_divisible: + kernel_options.setdefault("IS_DIVISIBLE", True) + else: + kernel_options.setdefault("IS_DIVISIBLE", False) + + # Calculate GQA head sharing + gqa_shared_heads = FloorDiv(Hq, Hkv) + if not is_power_of_2(gqa_shared_heads): + raise ValueError( + "Number of shared query heads sharing the same KV head must be power of 2. " + ) + kernel_options.setdefault("GQA_SHARED_HEADS", gqa_shared_heads) + + # Determine if there are "full" blocks where we only need to apply score_mod, and can skip mask_mod + has_full_blocks = full_kv_num_blocks is not None + kernel_options.setdefault("HAS_FULL_BLOCKS", has_full_blocks) + if not has_full_blocks: + # Create a placeholder full block list in case it is empty + full_kv_num_blocks, full_kv_indices = ( + empty(0, device=query.get_device()) for _ in range(2) + ) + + ( + query, + key, + value, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + ) = maybe_realize( + [ + query, + key, + value, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + ] + ) + score_mod_other_buffers = maybe_realize(score_mod_other_buffers) + mask_mod_other_buffers = maybe_realize(mask_mod_other_buffers) + + freeze_irnodes(score_mod_other_buffers) + freeze_irnodes(mask_mod_other_buffers) + + choices: list[Any] = [] + dtype = key.get_dtype() + head_dim = V.graph.sizevars.guard_int(key.get_size()[-1]) + configs = V.choices.get_flex_decode_configs( + head_dim, dtype, query.get_device().type + ) + + # TODO: fix autotuning. + + kernel_options.setdefault("SM_SCALE", scale) + kernel_options.setdefault("SPLIT_KV", get_split_k(B, Hkv, seq_len_kv)) + MAX_SPLIT_KV = kernel_options["SPLIT_KV"] + + # create config dependent intermediate buffers + buf_ACC_shape = [B, MAX_SPLIT_KV, Hq, seq_len_q, v_head_dim] + buf_ML_shape = buf_ACC_shape[:-1] + buf_M = empty_strided( + buf_ML_shape, + None, + dtype=torch.float32, # The rowmax is always stored in fp32 regardless of the input dtype + device=query.get_device(), + ) + buf_L = empty_strided( + buf_ML_shape, + None, + dtype=torch.float32, # The intermediate sumexp is always stored in fp32 regardless of the input dtype + device=query.get_device(), + ) + + layout_acc = FixedLayout( + query.get_device(), + torch.float32, + buf_ACC_shape, + FlexibleLayout.contiguous_strides(buf_ACC_shape), + ) + + set_head_dim_values(kernel_options, qk_head_dim, v_head_dim, V.graph.sizevars) + + kernel_options.setdefault( + "BLOCK_M", + ( + # m + # if V.graph.sizevars.evaluate_expr(sympy.Lt(query.get_size()[-2], 0)) + # else # Always use a BLOCK_M > 16 before Triton fix https://github.com/triton-lang/triton/pull/4061 is in pin + max( + next_power_of_2( + V.graph.sizevars.optimization_hint(seq_len_q) * gqa_shared_heads + ), + 1 if torch.xpu.is_available() else 16, + ) + ), + ) + + query = ir.ExternKernel.realize_input(query) + stride_b, stride_hq, stride_seq_len_q, stride_qk_head_dim = query.get_stride() + + # Reshape query for GQA: [B, Hq, Mq, D] -> [B, Hkv, G, Mq, D] + gqa_query_shape = (B, Hkv, gqa_shared_heads, seq_len_q, qk_head_dim) + gqa_query_stride = ( + stride_b, + stride_hq * gqa_shared_heads, + stride_hq, + stride_seq_len_q, + stride_qk_head_dim, + ) + query = lowerings[aten.as_strided](query, gqa_query_shape, gqa_query_stride) + + kernel_options.setdefault( + "SAFE_M_BOUNDARY", + Mod(seq_len_q * gqa_shared_heads, kernel_options["BLOCK_M"]) == 0, + ) + # TODO: This feels sketchy + kernel_options.setdefault("SAFE_N_BOUNDARY", True) + # Mark SPARSE_KV_BLOCK_SIZE as static shapes and add guards. + SPARSE_Q_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_Q_BLOCK_SIZE) + SPARSE_KV_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_KV_BLOCK_SIZE) + + original_kernel_options = kernel_options.copy() + # Note, we don't need to pass in the captured buffers explicitly + # because they're implicitly added by the score_mod function + # We do need to explicitly pass it in for autotuning though. + + # Default config for warp specialization + num_consumer_groups, num_buffers_warp_spec = 0, 0 + invalid_block_options: dict[str, Any] | None = None + + for conf in configs: + cur_kernel_options = original_kernel_options.copy() + # Remove prefix for forward kernels options and delete backward kernel options. + for k in list(cur_kernel_options.keys()): + if k.startswith("fwd_"): + v = cur_kernel_options.pop(k) + cur_kernel_options[k[4:]] = v + if k.startswith("bwd_"): + cur_kernel_options.pop(k) + # Performance tuning + cur_kernel_options.setdefault( + "BLOCK_N", min(conf.block_n, SPARSE_KV_BLOCK_SIZE) + ) + cur_kernel_options.setdefault("SPARSE_Q_BLOCK_SIZE", SPARSE_Q_BLOCK_SIZE) + cur_kernel_options.setdefault("SPARSE_KV_BLOCK_SIZE", SPARSE_KV_BLOCK_SIZE) + cur_kernel_options.setdefault("num_warps", conf.num_warps) + cur_kernel_options.setdefault("num_stages", conf.num_stages) + + if ( + cur_kernel_options["SPARSE_Q_BLOCK_SIZE"] % cur_kernel_options["BLOCK_M"] + != 0 + or cur_kernel_options["SPARSE_KV_BLOCK_SIZE"] + % cur_kernel_options["BLOCK_N"] + != 0 + ): + invalid_block_options = cur_kernel_options + if len(configs) == 1: + raise_flex_decoding_kernel_options_error( + cur_kernel_options, + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + ) + continue + + if cur_kernel_options.get("num_consumer_groups", False): + cur_kernel_options.setdefault("num_consumer_groups", num_consumer_groups) + cur_kernel_options.setdefault( + "num_buffers_warp_spec", num_buffers_warp_spec + ) + + # Intel GPU enables TMA by default + cur_kernel_options.setdefault("USE_TMA", bool(torch.xpu.is_available())) + + if cur_kernel_options["USE_TMA"] and not can_use_tma(query, key, value): + cur_kernel_options["USE_TMA"] = False + + # Add ROCm-specific parameters if they exist in the config + for attrib in ["kpack", "matrix_instr_nonkdim", "waves_per_eu"]: + if hasattr(conf, attrib): + cur_kernel_options[attrib] = getattr(conf, attrib) + + flex_decoding_template.maybe_append_choice( + choices=choices, + input_nodes=[ + query, + key, + value, + buf_M, + buf_L, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + ], + layout=layout_acc, + subgraphs=[ + score_mod_subgraph, + mask_mod_subgraph, + ], + mutated_inputs=[buf_M, buf_L], + call_sizes=query.get_size(), + **cur_kernel_options, + ) + + if not choices and invalid_block_options is not None: + raise_flex_decoding_kernel_options_error( + invalid_block_options, + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + ) + + inputs_for_flex_decoding = ( + [ + query, + key, + value, + buf_M, + buf_L, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + ] + + list(score_mod_other_buffers) + + list(mask_mod_other_buffers) + ) + + input_gen_fns = { + 5: create_num_blocks_fake_generator(kv_indices), + 6: create_indices_fake, + 7: create_num_blocks_fake_generator(full_kv_indices), + 8: create_indices_fake, + } + + buf_ACC, _ = autotune_select_algorithm( + "flex_decoding", + choices, + # Autotuning materializes benchmark tensors. Scalar shape captures stay + # in subgraph_inps below for dependency tracking and codegen. + [x for x in inputs_for_flex_decoding if is_tensor_ir_node(x)], + layout_acc, + input_gen_fns=input_gen_fns, + ) + + # need subgraph inputs and outputs to analyze all symints used in flex attention + buf_ACC.data.data.subgraph_inps = list(score_mod_other_buffers) + list( + mask_mod_other_buffers + ) + buf_ACC.data.data.subgraph_outs = get_fwd_subgraph_outputs( + score_mod_subgraph, mask_mod_subgraph + ) + + # Reduction + + g_M = lowerings[aten.max](buf_M, dim=1, keepdim=True)[0] + # See [Note] Handle fully masked out rows: + # g_M Is the global max among split kv blocks. + masked_rows = lowerings[aten.eq](g_M, -float("inf")) + adj_M = lowerings[aten.sub](buf_M, g_M) + adj_M = lowerings[aten.where](masked_rows, 0, adj_M) + alpha = lowerings[aten.exp2](adj_M) + + buf_L = lowerings[aten.mul](buf_L, alpha) + g_L = lowerings[aten.sum](buf_L, axis=1) + masked_rows_squeezed = lowerings[aten.squeeze](masked_rows, dim=1) + g_L = lowerings[aten.where](masked_rows_squeezed, 1.0, g_L) + logsumexp = lowerings[aten.log2](g_L) + logsumexp = lowerings[aten.add](logsumexp, lowerings[aten.squeeze](g_M, dim=1)) + + alpha_unseq = lowerings[aten.unsqueeze](alpha, 4) + buf_ACC = lowerings[aten.mul](buf_ACC, alpha_unseq) + output = lowerings[aten.sum](buf_ACC, axis=1) + L_unseq = lowerings[aten.unsqueeze](g_L, 3) + output = lowerings[aten.div](output, L_unseq) + output = lowerings[prims.convert_element_type](output, query.get_dtype()) + + return ( + output, + logsumexp, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_flash_attention.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_flash_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..77e92637ea22deda069a5f0a70f0304e748654c3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_flash_attention.py @@ -0,0 +1,935 @@ +# mypy: allow-untyped-defs +"""Call into flash-attention 4 for flexattention""" + +import dataclasses +import functools +import importlib +import inspect +import warnings +from collections.abc import Callable, Sequence +from contextlib import contextmanager +from typing import Any, cast, Literal + +import sympy +from sympy import Expr, Integer + +import torch +from torch.fx import GraphModule + +from ...codegen.cutedsl.aux_scalars import CuteDSLAuxScalarBindings +from ...ir import FixedLayout, ShapeAsConstantBuffer, Subgraph, TensorBox +from ...lowering import empty_strided +from ...select_algorithm import autotune_select_algorithm +from ...virtualized import V +from .aux_vectorization import ( + DEFAULT_MASK_MOD_VEC_SIZE, + select_mask_mod_vec_size, + select_score_mod_vec_size, +) +from .common import ( + create_indices_fake, + create_num_blocks_fake_generator, + infer_dense_strides, + load_flex_template, + SubgraphResults, +) +from .interval_mask_packing import PackedMaskInterval, select_packed_mask_intervals + + +@dataclasses.dataclass +class FlexFlashConfig: + """Autotuning configuration for CuteDSL flex flash attention kernels. + + score_mod_vec_size: Number of elements processed per thread in the score_mod + application loop. Maps to score_mod.__vec_size__ in CuTe flash attention. + None uses the kernel default. Only effective for forward; backward does + not currently support vectorized score_mod. + mask_mod_vec_size: Number of consecutive KV lanes evaluated per mask_mod + call. Maps to mask_mod.__vec_size__ in CuTe flash attention and to + the direct captured-tensor vector-load width for mask_mod. + mask_mod_packed_intervals: Precomputed 32-lane packed mask intervals. + """ + + score_mod_vec_size: int | None = None + mask_mod_vec_size: int | None = None + mask_mod_packed_intervals: tuple[PackedMaskInterval, ...] | None = None + + +def collect_aux_scalar_symbols( + *buffer_groups: Sequence[Any], +) -> tuple[sympy.Symbol, ...]: + symbols: dict[sympy.Symbol, None] = {} + for buffers in buffer_groups: + for buffer in buffers: + if isinstance(buffer, sympy.Expr): + for symbol in sorted(buffer.free_symbols, key=lambda s: s.name): + symbols.setdefault(symbol, None) + return tuple(symbols) + + +def get_flex_flash_fwd_configs( + has_score_mod: bool, + has_aux_tensors: bool, + device: torch.device | None = None, + score_mod_graph_module: GraphModule | None = None, + score_mod_other_buffers: Sequence[TensorBox] = (), + has_mask_mod: bool = False, + has_mask_aux_tensors: bool = False, + mask_mod_graph_module: GraphModule | None = None, + mask_mod_other_buffers: Sequence[TensorBox] = (), + aux_scalar_symbols: Sequence[sympy.Symbol] = (), +) -> list[FlexFlashConfig]: + cuda_major = None + if torch.cuda.is_available() and ( + has_mask_mod or (has_score_mod and has_aux_tensors) + ): + device_index = None if device is None else device.index + cuda_major = torch.cuda.get_device_capability(device_index)[0] + mask_mod_vec_size = select_mask_mod_vec_size( + has_mask_mod=has_mask_mod, + has_mask_aux_tensors=has_mask_aux_tensors, + supports_mask_mod_vec=cuda_major in (10, 11), + graph_module=mask_mod_graph_module, + other_buffers=mask_mod_other_buffers, + ) + score_mod_vec_size = select_score_mod_vec_size( + has_score_mod=has_score_mod, + has_aux_tensors=has_aux_tensors, + is_sm100_or_later=cuda_major is not None and cuda_major >= 10, + graph_module=score_mod_graph_module, + other_buffers=score_mod_other_buffers, + ) + mask_mod_packed_intervals = None + if has_mask_mod and cuda_major in (10, 11) and mask_mod_graph_module is not None: + mask_mod_packed_intervals = select_packed_mask_intervals( + mask_mod_graph_module, + mask_mod_other_buffers, + CuteDSLAuxScalarBindings(tuple(aux_scalar_symbols)).symbol_codes(), + ) + if mask_mod_packed_intervals is not None: + mask_mod_vec_size = DEFAULT_MASK_MOD_VEC_SIZE + + if ( + has_score_mod + and score_mod_vec_size is None + and torch._inductor.config.max_autotune + ): + # None means no captured tensor load constrained the score_mod vector width. + # Scalar captures are lane-uniform aux_scalars, so any kernel-supported + # power-of-two vector width is legal. + score_mod_vec_sizes = (1, 2, 4, 8, 16, 32, 64, 128) + else: + score_mod_vec_sizes = (score_mod_vec_size,) + configs = [ + FlexFlashConfig( + score_mod_vec_size=v, + mask_mod_vec_size=mask_mod_vec_size, + mask_mod_packed_intervals=mask_mod_packed_intervals, + ) + for v in score_mod_vec_sizes + ] + max_configs = torch._inductor.config.test_configs.max_flex_configs + if max_configs is not None and len(configs) > max_configs: + configs = configs[:max_configs] + return configs + + +def _get_flex_flash_bwd_configs() -> list[FlexFlashConfig]: + return [FlexFlashConfig()] + + +aten = torch.ops.aten +prims = torch.ops.prims + +FLASH_ATTENTION_INSTALL_MESSAGE = ( + "Install a compatible Flash Attention package, for example " + '`pip install --pre flash-attn-4` (`pip install --pre "flash-attn-4[cu13]"` ' + "for CUDA 13), and see https://pypi.org/project/flash-attn-4/ " + "for PyPI packaging details." +) + + +def _flash_attention_unavailable_message() -> str: + return ( + "CUTE flash attention library is not available. " + f"{FLASH_ATTENTION_INSTALL_MESSAGE}" + ) + + +@functools.lru_cache(maxsize=1) +def ensure_flash_available() -> bool: + """Check if flash-attn is importable; cache the result for reuse. + + Call ensure_flash_available.cache_clear() after installing flash-attn + in the same interpreter to retry the import. + """ + try: + return importlib.util.find_spec("flash_attn.cute") is not None # type: ignore[attr-defined] + except ImportError: + return False + + +@functools.lru_cache(maxsize=1) +def flash_supports_aux_scalars() -> bool: + """Check whether the installed FA4 package supports scalar captures.""" + try: + interface = importlib.import_module("flash_attn.cute.interface") + except ImportError: + return False + return ( + "aux_scalars" in inspect.signature(interface._flash_attn_fwd).parameters + and "aux_scalars" in inspect.signature(interface._flash_attn_bwd).parameters + ) + + +from ...codegen.cutedsl.cutedsl_template import CuteDSLTemplate + + +flash_attention_cutedsl_template = CuteDSLTemplate( + name="flash_attention_cutedsl", source=load_flex_template("flash_attention") +) +flash_attention_backward_cutedsl_template = CuteDSLTemplate( + name="flash_attention_backward_cutedsl", + source=load_flex_template("flash_attention_backward"), +) + + +class HierarchicalIndex(sympy.Function): + """ + Inert wrapper to carry an N-D index tuple through Inductor's SymPy-based IR. + + Inductor generally represents a tensor index as a single `sympy.Expr` (often a + flattened linear offset in memory). CuteDSL, however, wants structured coordinates so it + can emit `tensor[i, j, ...]` and handle strides internally. We therefore wrap + the per-dimension indices in a `sympy.Function` node: this keeps the value a + `sympy.Expr` for existing substitution/CSE machinery, while letting CuteDSL + codegen pattern-match and unpack the coordinates via `index.args`. + + `eval()` returns None to keep the node inert (no simplification/flattening). + + These nodes are intended to be short-lived wrappers and are only interpreted by + CuteDSL codegen (see `ModificationWrapperCuteDSL.load` in + `torch/_inductor/codegen/cutedsl/cutedsl_kernel.py`). + """ + + @classmethod + def eval(cls, *args): + return None + + +def _hierarchical_indexer_cute( + size: Sequence[int], + stride: Sequence[int] | None = None, + offset: Expr = Integer(0), +) -> Callable[[Sequence[Expr]], Expr]: + """Return an indexer that preserves multi-dimensional indices for CuteDSL.""" + + def indexer(indices: Sequence[Expr]) -> Expr: + if offset != Integer(0): + raise AssertionError("Offset not supported for hierarchical indexing") + if len(indices) != len(size): + raise AssertionError( + f"Rank mismatch: got {len(indices)} indices for tensor of rank {len(size)}" + ) + if not indices: + return Integer(0) + if len(indices) == 1: + return indices[0] + return HierarchicalIndex(*indices) + + return indexer + + +@contextmanager +def patch_fixed_layout_indexer_for_cutedsl(): + """ + Temporarily swap FixedLayout.make_indexer so CuteDSL sees hierarchical indexing. + + Note [CuteDSL indexer patch]: + Flex flash attention only supports a limited set of IR ops (pointwise, reads, no stores), + so temporarily changing the indexing behavior is safe for the kernels we emit today. + TODO(dynamic shapes): Reconfirm once flex flash attention supports dynamic shapes. + """ + original_make_indexer = FixedLayout.make_indexer + + def cutedsl_make_indexer(self): + return _hierarchical_indexer_cute(self.size, self.stride, self.offset) + + FixedLayout.make_indexer = cutedsl_make_indexer # type: ignore[assignment] + try: + yield + finally: + FixedLayout.make_indexer = original_make_indexer # type: ignore[assignment] + + +def wrap_choice_render_with_cutedsl_indexer(choice: Any) -> None: + """ + Wrap a template choice's kernel render to apply CuteDSL indexer patching. + + See Note [CuteDSL indexer patch]: + CuteDSL handles tensor strides internally, so template rendering must use + hierarchical indexing. + """ + original_make_kernel_render = choice.make_kernel_render + + def make_kernel_render_with_patch(*args, **kwargs): + render_kernel, render = original_make_kernel_render(*args, **kwargs) + + def render_with_patch(): + with patch_fixed_layout_indexer_for_cutedsl(): + return render() + + return render_kernel, render_with_patch + + choice.make_kernel_render = make_kernel_render_with_patch + + +def input_buffers_require_grads(graph_module, num_score_mod_placeholders: int): + """Check if any of the input buffers (beyond the score mod placeholders) require gradients.""" + inputs = [] + for node in graph_module.graph.nodes: + if node.op == "placeholder": + inputs.append(node) + if len(inputs) <= num_score_mod_placeholders: + return False + + def requires_grad(n): + tensor_meta = n.meta.get("tensor_meta") + return tensor_meta.requires_grad if tensor_meta is not None else False + + return any(requires_grad(n) for n in inputs[num_score_mod_placeholders:]) + + +def is_trivial_score_graph(graph_module: GraphModule) -> bool: + """Backwards currently doesn't support score_mods, match against identity""" + graph = graph_module.graph + nodes = list(graph.nodes) + placeholders = [n for n in nodes if n.op == "placeholder"] + output = [n for n in nodes if n.op == "output"] + if len(output) != 1: + raise AssertionError("Got graph w/ multiple outputs") + output_val = output[0].args[0] + # The identity graph just sends the score straight through + return output_val == placeholders[0] + + +def is_trivial_mask_graph(graph_module: GraphModule) -> bool: + """Mask graph is trivial when it only gates via the default full op.""" + graph = graph_module.graph + nodes = list(graph.nodes) + placeholders = [n for n in nodes if n.op == "placeholder"] + output = [n for n in nodes if n.op == "output"] + if len(output) != 1: + raise AssertionError("Got graph w/ multiple outputs") + output_val = output[0].args[0] + + # mask mod graph is empty if we have 4 inputs and full_default output + return len(placeholders) == 4 and output_val.target is torch.ops.aten.full.default + + +def has_unsupported_cpu_scalar_tensor_captures( + score_mod_other_buffers: Sequence[Any], + mask_mod_other_buffers: Sequence[Any], +) -> bool: + """Return True for CPU 0-d tensor captures that need scalarization first.""" + for buf in list(score_mod_other_buffers) + list(mask_mod_other_buffers): + if isinstance(buf, TensorBox): + device = buf.get_device() + size = buf.get_size() + if device is not None and device.type == "cpu" and len(size) == 0: + return True + return False + + +def _can_use_flex_flash_attention( + subgraph: Subgraph, + mask_graph: Subgraph, + num_score_mod_placeholders: int, +) -> tuple[bool, str]: + """Check if flex flash attention can be used for the given inputs. + + Returns: + tuple: (can_use, reason) where reason explains why it can't be used if can_use is False + """ + if not ensure_flash_available(): + return False, _flash_attention_unavailable_message() + + if input_buffers_require_grads(subgraph.graph_module, num_score_mod_placeholders): + return ( + False, + "Input buffers require gradients (not supported by flash attention)", + ) + + return True, "" + + +def _use_flex_flash_attention( + subgraph: Subgraph, + mask_graph: Subgraph, + kernel_options: dict[str, Any], + num_score_mod_placeholders: int, + backend: Literal["AUTO", "TRITON", "FLASH", "TRITON_DECODE"], +) -> bool: + """Determine if we should use flex flash attention for the given inputs. + + Args: + subgraph: The score modification subgraph + mask_graph: The mask modification subgraph + kernel_options: Kernel configuration options + num_score_mod_placeholders: Number of placeholders in score_mod + backend: Implementation selector (AUTO, TRITON, FLASH, TRITON_DECODE) + + Returns: + True if flash attention should be used, False otherwise + """ + # Flash is experimental and must be explicitly requested + if backend != "FLASH": + return False + + can_use, reason = _can_use_flex_flash_attention( + subgraph, + mask_graph, + num_score_mod_placeholders, + ) + + if not can_use: + raise RuntimeError( + f"BACKEND='FLASH' but flash attention cannot be used: {reason}" + ) + + return True + + +def create_flex_flash_attention_kernel( + query: TensorBox, + key: TensorBox, + value: TensorBox, + block_mask: tuple[Any, ...], + scale: float, + kernel_options: dict[str, Any], + subgraph_buffer: SubgraphResults, + mask_graph_buffer: SubgraphResults, + score_mod_other_buffers: list[TensorBox], + mask_mod_other_buffers: list[TensorBox], + kv_num_blocks: TensorBox | None, + kv_indices: TensorBox | None, + full_kv_num_blocks: TensorBox | None, + full_kv_indices: TensorBox | None, + sparse_q_block_size: int, + sparse_kv_block_size: int, + mask_graph: Subgraph, + subgraph: Subgraph | None = None, +) -> tuple[TensorBox, TensorBox]: + """Create a flex flash attention kernel using CuteDSL template.""" + if query.dtype != key.dtype or query.dtype != value.dtype: + raise ValueError( + f"Mixed query, key, and value dtype is not supported on this platform, " + f"got query.dtype: {query.dtype}, key.dtype: {key.dtype}, " + f"and value.dtype: {value.dtype}." + ) + if not ensure_flash_available(): + raise RuntimeError(_flash_attention_unavailable_message()) + + # Get dimensions + batch_size, num_heads, seq_len_q, head_dim = query.get_size() + v_head_dim = value.get_size()[-1] + device = query.get_device() + dtype = query.get_dtype() + if device is None: + raise AssertionError("Device must be specified") + + # Match stride pattern from query tensor + q_strides = query.get_stride() + out_size = [batch_size, num_heads, seq_len_q, v_head_dim] + out_strides = infer_dense_strides(out_size, q_strides) + + output = empty_strided( + size=out_size, + stride=out_strides, + dtype=dtype, + device=device, + ) + + lse = empty_strided( + size=[batch_size, num_heads, seq_len_q], + stride=None, # LSE can be contiguous + dtype=torch.float32, # LSE is always fp32 + device=device, + ) + + # Create layout for primary output + output_layout = FixedLayout( + device=device, + dtype=dtype, + size=[batch_size, num_heads, seq_len_q, v_head_dim], + stride=[sympy.sympify(s) for s in output.get_stride()], + ) + + mask_graph_is_trivial = is_trivial_mask_graph(mask_graph.graph_module) + score_graph_is_trivial = subgraph is None or is_trivial_score_graph( + subgraph.graph_module + ) + + if kv_num_blocks is None or kv_indices is None: + raise AssertionError("kv block metadata is required for flex FLASH") + + has_score_mod = not score_graph_is_trivial + has_mask_mod = not mask_graph_is_trivial + has_full_blocks = full_kv_num_blocks is not None + if has_full_blocks and full_kv_indices is None: + raise AssertionError("full_kv_indices must be provided with full_kv_num_blocks") + is_noop_block_mask = not has_full_blocks and V.graph.sizevars.statically_known_true( + sympy.And( + sympy.Eq(sparse_q_block_size, 1 << 30), + sympy.Eq(sparse_kv_block_size, 1 << 30), + ) + ) + needs_block_mask = not (mask_graph_is_trivial and is_noop_block_mask) + sparse_q_block_size = V.graph.sizevars.guard_int(sparse_q_block_size) + sparse_kv_block_size = V.graph.sizevars.guard_int(sparse_kv_block_size) + + choices: list[Any] = [] + if flash_attention_cutedsl_template is None: + raise AssertionError("flash_attention_cutedsl_template must not be None") + + input_nodes = [query, key, value, lse] + if needs_block_mask: + input_nodes.extend([kv_num_blocks, kv_indices]) + if has_full_blocks: + input_nodes.extend([full_kv_num_blocks, full_kv_indices]) + + subgraphs = [] + if has_score_mod: + subgraphs.append(subgraph_buffer) + if has_mask_mod: + subgraphs.append(mask_graph_buffer) + + aux_scalar_symbols = collect_aux_scalar_symbols( + score_mod_other_buffers, mask_mod_other_buffers + ) + if aux_scalar_symbols and not flash_supports_aux_scalars(): + raise RuntimeError( + "CUTE flash attention scalar captures require flash-attn-4>=4.0.0b17. " + f"{FLASH_ATTENTION_INSTALL_MESSAGE}" + ) + has_score_aux_tensors = any( + not isinstance(buffer, sympy.Expr) for buffer in score_mod_other_buffers + ) + has_mask_aux_tensors = any( + not isinstance(buffer, sympy.Expr) for buffer in mask_mod_other_buffers + ) + + configs = get_flex_flash_fwd_configs( + has_score_mod=has_score_mod, + has_aux_tensors=has_score_aux_tensors, + device=device, + score_mod_graph_module=( + subgraph.graph_module if has_score_mod and subgraph is not None else None + ), + score_mod_other_buffers=score_mod_other_buffers, + has_mask_mod=has_mask_mod, + has_mask_aux_tensors=has_mask_aux_tensors, + mask_mod_graph_module=mask_graph.graph_module, + mask_mod_other_buffers=mask_mod_other_buffers, + aux_scalar_symbols=aux_scalar_symbols, + ) + error: NotImplementedError | None = None + for conf in configs: + with patch_fixed_layout_indexer_for_cutedsl(): + error = flash_attention_cutedsl_template.maybe_append_choice( + choices, + input_nodes=input_nodes, + layout=output_layout, + mutated_inputs=[lse], + subgraphs=subgraphs, + SM_SCALE=scale, + HAS_SCORE_MOD=has_score_mod, + SCORE_MOD_VEC_SIZE=conf.score_mod_vec_size, + MASK_MOD_VEC_SIZE=conf.mask_mod_vec_size, + MASK_MOD_PACKED_INTERVALS=conf.mask_mod_packed_intervals, + MASK_MOD_OTHER_BUFFERS=mask_mod_other_buffers, + AUX_SCALAR_SYMBOLS=aux_scalar_symbols, + NEEDS_BLOCK_MASK=needs_block_mask, + HAS_MASK_MOD=has_mask_mod, + HAS_FULL_BLOCKS=has_full_blocks, + SPARSE_Q_BLOCK_SIZE=sparse_q_block_size, + SPARSE_KV_BLOCK_SIZE=sparse_kv_block_size, + ) + if error is not None and len(configs) == 1: + raise RuntimeError(f"CuteDSL template failed: {error}") + + for choice in choices: + wrap_choice_render_with_cutedsl_indexer(choice) + + if not choices: + raise RuntimeError(f"CuteDSL template failed: {error}") + + input_gen_fns: dict[int, Callable] | None = None + if needs_block_mask: + input_gen_fns = { + 4: create_num_blocks_fake_generator(kv_indices), + 5: create_indices_fake, + } + if has_full_blocks: + input_gen_fns.update( + { + 6: create_num_blocks_fake_generator(full_kv_indices), + 7: create_indices_fake, + } + ) + + template_output, _ = autotune_select_algorithm( + "flex_flash_attention", + choices, + input_nodes, + output_layout, + input_gen_fns=input_gen_fns, + return_multi_template=False, + ) + + return (template_output, lse) + + +def _can_use_flex_flash_attention_backward( + fw_subgraph: Subgraph, + mask_graph: Subgraph, + joint_outputs: Any | None = None, + score_mod_other_buffers: Sequence[TensorBox] | None = None, + num_score_mod_placeholders: int = 5, +) -> tuple[bool, str]: + if not ensure_flash_available(): + return False, _flash_attention_unavailable_message() + + if input_buffers_require_grads( + fw_subgraph.graph_module, num_score_mod_placeholders + ): + return ( + False, + "Input buffers require gradients (not supported by flash attention backward)", + ) + + if joint_outputs is not None: + if joint_outputs.captured_grads_compute: + return ( + False, + "NYI: Flex Flash Attention bwd doesn't support captured grads yet.", + ) + if joint_outputs.mutated_grads: + return ( + False, + "NYI: Flex Flash Attention bwd doesn't support mutated grads yet.", + ) + + return True, "" + + +def _use_flex_flash_attention_backward( + fw_subgraph: Subgraph, + mask_graph: Subgraph, + backend: Literal["AUTO", "TRITON", "FLASH", "TRITON_DECODE"], + joint_outputs: Any | None = None, + score_mod_other_buffers: Sequence[TensorBox] | None = None, +) -> bool: + """Determine if we should use flex flash attention for the given inputs. + + Args: + fw_subgraph: The forward score modification subgraph + mask_graph: The mask modification subgraph + backend: Implementation selector (AUTO, TRITON, FLASH, TRITON_DECODE) + joint_outputs: Processed joint outputs (for PR1 constraint checking) + score_mod_other_buffers: Additional buffers used by score_mod + + Returns: + True if flash attention should be used, False otherwise + """ + # Flash is experimental and must be explicitly requested + if backend != "FLASH": + return False + + can_use, reason = _can_use_flex_flash_attention_backward( + fw_subgraph, + mask_graph, + joint_outputs, + score_mod_other_buffers, + ) + + if not can_use: + raise RuntimeError( + f"BACKEND='FLASH' but flash attention cannot be used: {reason}" + ) + + return True + + +def create_flex_flash_attention_backward_kernel( + query: TensorBox, + key: TensorBox, + value: TensorBox, + out: TensorBox, + logsumexp: TensorBox, + grad_out: TensorBox, + grad_logsumexp: TensorBox | None, + scale: float, + kernel_options: dict[str, Any], + sparse_q_block_size: int, + sparse_kv_block_size: int, + fw_subgraph_buffer: SubgraphResults | None = None, + joint_subgraph_buffer: Any | None = None, + score_mod_other_buffers: list[TensorBox] | None = None, + mask_graph_buffer: SubgraphResults | None = None, + mask_mod_other_buffers: list[TensorBox] | None = None, + q_num_blocks: TensorBox | None = None, + q_indices: TensorBox | None = None, + full_q_num_blocks: TensorBox | None = None, + full_q_indices: TensorBox | None = None, + dq_write_order: TensorBox | None = None, + dq_write_order_full: TensorBox | None = None, + dq_kv_order: TensorBox | None = None, + dq_kv_order_spt: bool | None = None, +) -> tuple[TensorBox | ShapeAsConstantBuffer, TensorBox, TensorBox, tuple]: + """Create a CuteDSL flash attention backward kernel for the default mod path.""" + if not ensure_flash_available(): + raise RuntimeError(_flash_attention_unavailable_message()) + + batch_size, num_heads, seq_len_q, head_dim = query.get_size() + _, num_heads_kv, seq_len_kv, v_head_dim = value.get_size() + device = query.get_device() + dtype = query.get_dtype() + if device is None: + raise AssertionError("Device must not be None") + + grad_query_strides = infer_dense_strides( + [batch_size, num_heads, seq_len_q, head_dim], query.get_stride() + ) + grad_query = empty_strided( + size=[batch_size, num_heads, seq_len_q, head_dim], + stride=grad_query_strides, + dtype=dtype, + device=device, + ) + + grad_key_strides = infer_dense_strides( + [batch_size, num_heads_kv, seq_len_kv, head_dim], key.get_stride() + ) + grad_key = empty_strided( + size=[batch_size, num_heads_kv, seq_len_kv, head_dim], + stride=grad_key_strides, + dtype=dtype, + device=device, + ) + + grad_value_strides = infer_dense_strides( + [batch_size, num_heads_kv, seq_len_kv, v_head_dim], value.get_stride() + ) + grad_value = empty_strided( + size=[batch_size, num_heads_kv, seq_len_kv, v_head_dim], + stride=grad_value_strides, + dtype=dtype, + device=device, + ) + + # we use dq as the output layout + output_layout = FixedLayout( + device=device, + dtype=dtype, + size=[batch_size, num_heads, seq_len_q, head_dim], + stride=[sympy.sympify(s) for s in grad_query.get_stride()], + ) + + sparse_q_block_size = V.graph.sizevars.guard_int(sparse_q_block_size) + sparse_kv_block_size = V.graph.sizevars.guard_int(sparse_kv_block_size) + + has_dlse = grad_logsumexp is not None + if ( + has_dlse + and V.graph.sizevars.statically_known_equals(head_dim, 256) + and V.graph.sizevars.statically_known_equals(v_head_dim, 256) + and torch.cuda.get_device_capability(device)[0] in (10, 11) + ): + raise NotImplementedError( + "FLASH backend dLSE is not supported by the SM100/SM110 dedicated " + "head_dim=256 FA4 backward kernel. Use BACKEND='TRITON' for this " + "configuration." + ) + + choices: list[Any] = [] + + input_nodes: list[TensorBox] = [ + query, + key, + value, + out, + grad_out, + logsumexp, + grad_key, + grad_value, + ] + + has_block_mask = mask_graph_buffer is not None + if has_block_mask: + if q_indices is None: + raise AssertionError("q_indices required when block mask is present") + if full_q_num_blocks is None: + raise AssertionError( + "full_q_num_blocks required when block mask is present" + ) + if full_q_indices is None: + raise AssertionError("full_q_indices required when block mask is present") + input_nodes.extend( + [ + cast(TensorBox, q_num_blocks), + q_indices, + full_q_num_blocks, + full_q_indices, + ] + ) + + has_dq_write_order = dq_write_order is not None + if has_dq_write_order: + input_nodes.append(dq_write_order) + if dq_write_order_full is not None: + input_nodes.append(dq_write_order_full) + has_dq_kv_order = dq_kv_order is not None and has_dq_write_order + dq_kv_order_spt_for_flash = dq_kv_order_spt if has_dq_write_order else None + if has_dq_kv_order: + input_nodes.append(dq_kv_order) + if has_dlse: + input_nodes.append(cast(TensorBox, grad_logsumexp)) + + supports_dq_kv_order = False + supports_spt = False + if has_block_mask: + # pyrefly: ignore[missing-import] + from flash_attn.cute.block_sparsity import BlockSparseTensorsTorch + + block_sparse_fields = getattr(BlockSparseTensorsTorch, "_fields", ()) + supports_dq_kv_order = "dq_kv_order" in block_sparse_fields + supports_spt = "spt" in block_sparse_fields + if has_dq_kv_order and not supports_dq_kv_order: + raise NotImplementedError( + "Explicit tensor dq_kv_order requires flash-attn-4 with dq_kv_order support" + ) + if dq_kv_order_spt_for_flash is not None and not ( + supports_dq_kv_order or supports_spt + ): + raise NotImplementedError( + "Boolean dq_kv_order requires flash-attn-4 with dq_kv_order or spt support" + ) + + deterministic_requested = torch.are_deterministic_algorithms_enabled() + warn_only = torch.is_deterministic_algorithms_warn_only_enabled() + deterministic_backward_enabled = deterministic_requested + if deterministic_requested and has_block_mask: + major, _ = torch.cuda.get_device_capability(device) + missing_dq_write_order = dq_write_order is None or ( + full_q_num_blocks is not None and dq_write_order_full is None + ) + missing_dq_kv_order = not ( + has_dq_kv_order or dq_kv_order_spt_for_flash is not None + ) + if major < 10: + if warn_only: + deterministic_backward_enabled = False + else: + raise NotImplementedError( + "Deterministic backward for flex_attention with block_mask and BACKEND='FLASH' " + "requires SM100+ (compute capability >= 10.0). " + "Use BACKEND='TRITON' for deterministic backward on older architectures." + ) + elif missing_dq_write_order: + if warn_only: + deterministic_backward_enabled = False + else: + raise ValueError( + "Deterministic backward for flex_attention with block_mask and BACKEND='FLASH' " + "requires dQ write-order metadata. Create the block mask with " + "create_block_mask(..., compute_dq_write_order=True)." + ) + elif missing_dq_kv_order: + if warn_only: + deterministic_backward_enabled = False + else: + raise ValueError( + "Deterministic backward for flex_attention with block_mask and BACKEND='FLASH' " + "requires dQ KV scheduler-order metadata. Create the block mask with " + "create_block_mask(..., compute_dq_write_order=True)." + ) + if deterministic_requested and not deterministic_backward_enabled: + warnings.warn( + "flex_attention backward with block_mask and BACKEND='FLASH' does not have " + "a deterministic implementation for this configuration, but you set " + "'torch.use_deterministic_algorithms(True, warn_only=True)'. " + "Running non-deterministic backward.", + ) + + has_score_mod = fw_subgraph_buffer is not None and joint_subgraph_buffer is not None + subgraphs = [] + if has_score_mod: + subgraphs.append(fw_subgraph_buffer) + subgraphs.append(joint_subgraph_buffer) + if has_block_mask: + subgraphs.append(mask_graph_buffer) + + aux_scalar_symbols = collect_aux_scalar_symbols( + score_mod_other_buffers or (), mask_mod_other_buffers or () + ) + if aux_scalar_symbols and not flash_supports_aux_scalars(): + raise RuntimeError( + "CUTE flash attention scalar captures require flash-attn-4>=4.0.0b17. " + f"{FLASH_ATTENTION_INSTALL_MESSAGE}" + ) + configs = _get_flex_flash_bwd_configs() + + error: NotImplementedError | None = None + for conf in configs: + with patch_fixed_layout_indexer_for_cutedsl(): + error = flash_attention_backward_cutedsl_template.maybe_append_choice( + choices, + input_nodes=input_nodes, + layout=output_layout, + mutated_inputs=[grad_key, grad_value], + subgraphs=subgraphs or None, + SM_SCALE=scale, + HAS_SCORE_MOD=has_score_mod, + SCORE_MOD_VEC_SIZE=conf.score_mod_vec_size, + HAS_BLOCK_MASK=has_block_mask, + HAS_DQ_WRITE_ORDER=has_dq_write_order, + HAS_DQ_WRITE_ORDER_FULL=dq_write_order_full is not None, + HAS_DQ_KV_ORDER=has_dq_kv_order, + DQ_KV_ORDER_SPT=dq_kv_order_spt_for_flash, + HAS_DLSE=has_dlse, + AUX_SCALAR_SYMBOLS=aux_scalar_symbols, + SUPPORTS_DQ_KV_ORDER=supports_dq_kv_order, + SUPPORTS_SPT=supports_spt, + DETERMINISTIC_BACKWARD_ENABLED=deterministic_backward_enabled, + SPARSE_Q_BLOCK_SIZE=sparse_q_block_size, + SPARSE_KV_BLOCK_SIZE=sparse_kv_block_size, + ) + if error is not None and len(configs) == 1: + raise RuntimeError(f"CuteDSL template failed: {error}") + + for choice in choices: + wrap_choice_render_with_cutedsl_indexer(choice) + + if not choices: + raise RuntimeError(f"CuteDSL template failed: {error}") + + input_gen_fns: dict[int, Callable] | None = None + if has_block_mask: + input_gen_fns = { + 8: create_num_blocks_fake_generator(q_indices), + 9: create_indices_fake, + 10: create_num_blocks_fake_generator(full_q_indices), + 11: create_indices_fake, + } + + template_output, _ = autotune_select_algorithm( + "flex_flash_attention_backward", + choices, + input_nodes, + output_layout, + input_gen_fns=input_gen_fns, + return_multi_template=False, + ) + + return (template_output, grad_key, grad_value, tuple()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_mps.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_mps.py new file mode 100644 index 0000000000000000000000000000000000000000..4d90569758ad54aa0abb9e9a119bff97f3bbe6c3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/flex_mps.py @@ -0,0 +1,289 @@ +# mypy: allow-untyped-defs +"""MPS-specific lowering for flex attention.""" + +import sympy + +import torch +from torch._inductor.virtualized import V + +from ...ir import FixedLayout, ShapeAsConstantBuffer, TensorBox +from ...lowering import empty_strided +from ...select_algorithm import realize_inputs +from ...utils import expr_fits_within_32bit +from .common import infer_dense_strides, maybe_realize + + +BLOCK_M = 32 + + +def lower_mps( + query, + key, + value, + subgraph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, +): + """Lower flex_attention to a Metal shader for MPS.""" + from ...codegen.metal_flex_attention_template import ( + _generate_metal_shader, + MetalFlexAttentionNode, + ) + + ( + _, # q_length + _, # kv_length + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + _, # q_num_blocks + _, # q_indices + _, # full_q_num_blocks + _, # full_q_indices + _, # dq_write_order (backward-only) + _, # dq_write_order_full (backward-only) + _, # dq_kv_order (backward-only) + _, # dq_kv_order_spt (backward-only) + SPARSE_Q_BLOCK_SIZE, + SPARSE_KV_BLOCK_SIZE, + mask_graph, + ) = block_mask + + if query.get_dtype() not in (torch.float32, torch.float16, torch.bfloat16): + raise NotImplementedError( + f"flex_attention on MPS supports float32/float16/bfloat16, got {query.get_dtype()}" + ) + if query.get_dtype() != key.get_dtype() or query.get_dtype() != value.get_dtype(): + raise NotImplementedError( + "Mixed dtypes for query, key, value not supported on MPS" + ) + + write_lse = bool(kernel_options.get("OUTPUT_LOGSUMEXP", False)) + write_max = bool(kernel_options.get("OUTPUT_MAX", False)) + + dtype = query.get_dtype() + + ( + query, + key, + value, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + ) = maybe_realize( + [ + query, + key, + value, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + ] + ) + + B, Hq, seq_len_q, qk_head_dim = query.get_size() + Bkv, Hkv, seq_len_kv, v_head_dim = value.get_size() + _, _, _, k_head_dim = key.get_size() + + has_full_blocks = full_kv_num_blocks is not None + + d_qk = V.graph.sizevars.guard_int(qk_head_dim) + d_v = V.graph.sizevars.guard_int(v_head_dim) + d_k = V.graph.sizevars.guard_int(k_head_dim) + if d_k != d_qk: + raise NotImplementedError( + f"flex_attention on MPS requires query and key to share head dim, " + f"got d_qk={d_qk} d_k={d_k}" + ) + + sizevars = V.graph.sizevars + if not sizevars.evaluate_expr(sympy.Eq(B, Bkv) | sympy.Eq(Bkv, 1)): + raise AssertionError(f"Bq and Bkv must broadcastable. Got Bq={B} and Bkv={Bkv}") + + SPARSE_KV_BLOCK_SIZE_val = sizevars.guard_int(SPARSE_KV_BLOCK_SIZE) + SPARSE_Q_BLOCK_SIZE_val = sizevars.guard_int(SPARSE_Q_BLOCK_SIZE) + if SPARSE_Q_BLOCK_SIZE_val < BLOCK_M or SPARSE_Q_BLOCK_SIZE_val % BLOCK_M != 0: + # Each threadgroup tiles BLOCK_M query rows and looks up sparse-mask info + # at sparse_q_idx = m_base / SPARSE_Q_BLOCK_SIZE; a smaller/non-multiple + # SPARSE_Q_BLOCK_SIZE makes one threadgroup span multiple sparse blocks. + raise NotImplementedError( + f"flex_attention on MPS requires SPARSE_Q_BLOCK_SIZE to be a positive " + f"multiple of {BLOCK_M}, got {SPARSE_Q_BLOCK_SIZE_val}" + ) + + if not sizevars.statically_known_multiple_of(Hq, Hkv): + raise NotImplementedError( + f"flex_attention on MPS requires Hq to be a positive multiple of " + f"Hkv, got Hq={Hq} Hkv={Hkv}" + ) + gqa_shared_heads = Hq // Hkv + + scale_val = float(scale) + + # Tensor captures become extra Metal buffers; their sizes/strides are baked + # into the index offset math. SymInt captures (from dynamic-shape closures) + # become extra packed scalars, evaluated at the call site. maybe_realize + # passes SymInts through untouched. `metas` keeps the placeholder order so + # the subgraph codegen can bind each capture (tensor or scalar) by position. + def _capture_meta(items): + metas, tensors, scalars = [], [], [] + for cap in maybe_realize(list(items)): + if isinstance(cap, ShapeAsConstantBuffer): + cap = cap.expr + if isinstance(cap, (int, sympy.Expr)): + metas.append(("scalar",)) + scalars.append(cap) + continue + metas.append( + ( + "tensor", + [sizevars.guard_int(s) for s in cap.get_size()], + [sizevars.guard_int(s) for s in cap.get_stride()], + cap.get_dtype(), + ) + ) + tensors.append(cap) + return metas, tensors, scalars + + score_meta, score_tensors, score_scalars = _capture_meta(score_mod_other_buffers) + mask_meta, mask_tensors, mask_scalars = _capture_meta(mask_mod_other_buffers) + + int32_max = torch.iinfo(torch.int32).max + all_scalars = [sympy.sympify(cap) for cap in (*score_scalars, *mask_scalars)] + captures_fit_int32 = all(expr_fits_within_32bit(cap) for cap in all_scalars) + if captures_fit_int32: + for cap in all_scalars: + sizevars.check_leq(cap, int32_max) + + shader_source = _generate_metal_shader( + dtype=dtype, + d_qk=d_qk, + d_v=d_v, + score_mod_graph=subgraph.graph_module, + mask_mod_graph=mask_graph.graph_module, + has_full_blocks=has_full_blocks, + block_m=BLOCK_M, + scale=scale_val, + score_captured=score_meta, + mask_captured=mask_meta, + write_lse=write_lse, + write_max=write_max, + captures_fit_int32=captures_fit_int32, + ) + + out_size = [B, Hq, seq_len_q, v_head_dim] + out_strides = infer_dense_strides(out_size, query.get_stride()) + layout = FixedLayout( + query.get_device(), + dtype, + out_size, + stride=[sympy.sympify(s) for s in out_strides], + ) + + kv_nb_strides = _get_strides(kv_num_blocks) + kv_idx_strides = _get_strides(kv_indices) + full_kv_nb_strides = _get_strides(full_kv_num_blocks) if has_full_blocks else [] + full_kv_idx_strides = _get_strides(full_kv_indices) if has_full_blocks else [] + + # Buffer order: 0=Out, 1=Q, 2=K, 3=V, 4=kv_num_blocks, 5=kv_indices, + # 6=(full_kv_num_blocks), 7=(full_kv_indices), then score/mask captured + # buffers, then the packed scalar buffer. + input_nodes = [query, key, value, kv_num_blocks, kv_indices] + if has_full_blocks: + input_nodes += [full_kv_num_blocks, full_kv_indices] + input_nodes += [*score_tensors, *mask_tensors] + + realized_inputs = realize_inputs(*input_nodes) + + # Left-pad to (Z, H, Q_blocks); a sliced kv_num_blocks may be 1D or 2D. + kv_nb_sizes = list(kv_num_blocks.get_size()) + while len(kv_nb_sizes) < 3: + kv_nb_sizes.insert(0, sympy.Integer(1)) + sparse_z = kv_nb_sizes[0] + sparse_hq = kv_nb_sizes[1] + + # Order must match the unpack in metal_flex_attention_template's `scalar_names`. + scalar_args = [ + B, + Bkv, + Hq, + Hkv, + seq_len_q, + seq_len_kv, + *query.get_stride(), + *key.get_stride(), + *value.get_stride(), + *[sympy.sympify(s) for s in out_strides], + sympy.Integer(SPARSE_KV_BLOCK_SIZE_val), + gqa_shared_heads, + sparse_z, + sparse_hq, + *_pad_strides(kv_nb_strides, 3), + *_pad_strides(kv_idx_strides, 4), + sympy.Integer(SPARSE_Q_BLOCK_SIZE_val), + ] + if has_full_blocks: + scalar_args += [ + *_pad_strides(full_kv_nb_strides, 3), + *_pad_strides(full_kv_idx_strides, 4), + ] + + # SymInt captures trail the fixed scalars; order (score then mask) matches + # the scalar_capture_names appended in _generate_metal_shader. + scalar_args += [*score_scalars, *mask_scalars] + + # (num_q_blocks, Hq, B); each threadgroup owns BLOCK_M query rows. + grid = ( + sympy.ceiling(seq_len_q / BLOCK_M), + Hq, + B, + ) + + lse_shape = [B, Hq, seq_len_q] + logsumexp = empty_strided( + lse_shape, None, dtype=torch.float32, device=query.get_device() + ) + max_scores = empty_strided( + lse_shape, None, dtype=torch.float32, device=query.get_device() + ) + node_inputs = [*realized_inputs] + if write_lse: + logsumexp.realize() + node_inputs.append(logsumexp) + if write_max: + max_scores.realize() + node_inputs.append(max_scores) + + node = MetalFlexAttentionNode( + layout=layout, + inputs=node_inputs, + shader_source=shader_source, + scalar_args=scalar_args, + grid=grid, + block_m=BLOCK_M, + num_mutated_outputs=int(write_lse) + int(write_max), + ) + + return (TensorBox.create(node), logsumexp, max_scores) + + +def _get_strides(node): + if node is None: + return [] + return list(node.get_stride()) + + +def _pad_strides(strides, target_len): + """Left-pad strides to target_len with 0 (broadcast over missing leading dims).""" + strides = list(strides) + if len(strides) > target_len: + strides = strides[-target_len:] + while len(strides) < target_len: + strides.insert(0, sympy.Integer(0)) + return strides diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/interval_mask_packing.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/interval_mask_packing.py new file mode 100644 index 0000000000000000000000000000000000000000..a8fe12bb730ee0f5327f5d56a22452dd15a339c6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/interval_mask_packing.py @@ -0,0 +1,740 @@ +# mypy: allow-untyped-defs +"""Packed interval mask analysis for flex flash attention. + +Flex attention can evaluate arbitrary ``mask_mod`` functions lane by lane, but +SM100 packed masks can use a cheaper path when the kept KV lanes in each +32-lane chunk are window-like. This pass recognizes mask graphs where, after +substituting ``kv_idx + mask_lane`` for the per-lane KV index, the predicate can +be represented as a small union of half-open intervals over ``mask_lane``. + +This works for causal, sliding-window, block, and document-bound masks whose +bounds depend only on lane-uniform values such as ``q_idx``, ``b_idx``, or aux +loads indexed by them. It intentionally rejects masks that need arbitrary +per-lane inclusion, such as ``doc_ids[b, kv_idx] == doc_ids[b, q_idx]`` or +``kv_idx % 2 == 0``; those would degenerate into many singleton intervals and +are better handled by the generic mask path. +""" + +import dataclasses +from collections.abc import Mapping, Sequence +from itertools import product + +import sympy + +import torch +from torch.fx import GraphModule +from torch.utils._sympy.functions import FloorDiv, Max, Min + +from ...codegen.cutedsl.lane_analysis import decompose_affine_lane_expr +from ...virtualized import NullHandler, V +from .aux_vectorization import fx_aux_index_to_sympy + + +perf_hint_log = torch._logging.getArtifactLogger(__name__, "perf_hints") + + +# Fall back to scalar mask lowering before interval expansion makes generated CuTe too large. +MAX_PACKED_MASK_INTERVALS_FOR_CODE_SIZE = 8 +LANE_UNIFORM_BINARY_OPS: Mapping[object, str] = { + torch.ops.aten.add.Tensor: "+", + torch.ops.aten.add.Scalar: "+", + torch.ops.aten.sub.Tensor: "-", + torch.ops.aten.sub.Scalar: "-", + torch.ops.aten.mul.Tensor: "*", + torch.ops.aten.mul.Scalar: "*", + torch.ops.aten.remainder.Tensor: "%", + torch.ops.aten.remainder.Scalar: "%", +} + + +@dataclasses.dataclass(frozen=True) +class PackedMaskInterval: + """Half-open keep interval [lower_lane, upper_lane_exclusive) for a packed mask. + + Packed interval lowering replaces per-lane boolean mask evaluation with one + 32-bit keep mask when the mask predicate can be expressed as lane bounds. + For example, ``q_idx >= kv_idx`` over a 32-lane KV window starting at + ``kv_idx`` keeps lanes ``[0, q_idx - kv_idx + 1)``. + """ + + lower_lane: sympy.Expr + upper_lane_exclusive: sympy.Expr + # CuTe code for temporary symbols that stand in for lane-uniform aux loads. + symbol_codes: Mapping[sympy.Symbol, str] = dataclasses.field( + default_factory=dict, compare=False, repr=False + ) + + @classmethod + def full(cls) -> "PackedMaskInterval": + return cls(sympy.Integer(0), sympy.Integer(32)) + + def is_full(self) -> bool: + return self.lower_lane == 0 and self.upper_lane_exclusive == 32 + + def with_symbol_codes( + self, symbol_codes: Mapping[sympy.Symbol, str] + ) -> "PackedMaskInterval": + return dataclasses.replace(self, symbol_codes=dict(symbol_codes)) + + def render_lower(self) -> str: + return self._render(self.lower_lane) + + def render_upper(self) -> str: + return self._render(self.upper_lane_exclusive) + + def keep_mask_expr(self) -> str: + """Render the 32-bit CuTe keep-mask expression for this interval.""" + lower = self.render_lower() + upper = self.render_upper() + return ( + "(utils.shr_u32(cutlass.Uint32(0xFFFFFFFF), " + "cutlass.Uint32(min(max(cutlass.Int32(32) - " + f"{upper}, cutlass.Int32(0)), cutlass.Int32(32)))) & " + "utils.shl_u32(cutlass.Uint32(0xFFFFFFFF), " + "cutlass.Uint32(min(max(" + f"{lower}, cutlass.Int32(0)), cutlass.Int32(32)))))" + ) + + def _render(self, expr: sympy.Expr) -> str: + rendered = sympy_to_cute_index(expr, self.symbol_codes) + if rendered is None: + raise AssertionError(f"failed to render expr to cute index: {expr}") + return rendered + + +IntervalSet = tuple[PackedMaskInterval, ...] +MaybeIntervalSet = IntervalSet | None + + +def is_bool_full_node(node: torch.fx.Node, value: bool) -> bool: + return ( + node.op == "call_function" + and node.target is torch.ops.aten.full.default + and len(node.args) >= 2 + and node.args[0] == [] + and node.args[1] is value + ) + + +def _simplify_expr(expr: sympy.Expr) -> sympy.Expr: + """Simplify with Inductor sizevars when available, otherwise use SymPy.""" + if isinstance(V.graph, NullHandler): + return sympy.simplify(expr) + return V.graph.sizevars.simplify(expr) + + +def render_sympy_args( + args: Sequence[sympy.Expr], + symbol_codes: Mapping[sympy.Symbol, str] | None, +) -> list[str] | None: + """Render every child expression, returning ``None`` if any is unsupported.""" + rendered = [] + for arg in args: + cute_arg = sympy_to_cute_index(arg, symbol_codes) + if cute_arg is None: + return None + rendered.append(cute_arg) + return rendered + + +def sympy_to_cute_index( + expr: sympy.Expr, symbol_codes: Mapping[sympy.Symbol, str] | None = None +) -> str | None: + """Render a supported SymPy integer expression as CuTe index code.""" + expr = _simplify_expr(expr) + match expr: + case sympy.Integer(): + return f"cutlass.Int32({int(expr)})" + case sympy.Symbol(): + if symbol_codes is not None and expr in symbol_codes: + return symbol_codes[expr] + if expr.name == "q_idx": + return "q_idx[0]" + if expr.name == "kv_idx": + return "kv_idx[0]" + case FloorDiv(): + args = render_sympy_args(expr.args, symbol_codes) + if args is not None: + return f"({args[0]} // {args[1]})" + case sympy.Add() | sympy.Mul(): + args = render_sympy_args(expr.args, symbol_codes) + if args is None: + return None + separator = " + " if isinstance(expr, sympy.Add) else " * " + return "(" + separator.join(args) + ")" + case Min() | Max(): + args = render_sympy_args(expr.args, symbol_codes) + if args is None: + return None + op = "min" if isinstance(expr, Min) else "max" + return f"{op}(" + ", ".join(args) + ")" + if isinstance(expr, (sympy.Min, sympy.Max)): + args = render_sympy_args(expr.args, symbol_codes) + if args is None: + return None + op = "min" if isinstance(expr, sympy.Min) else "max" + return f"{op}(" + ", ".join(args) + ")" + return None + + +def is_aten_index_node(node: torch.fx.Node) -> bool: + return node.op == "call_function" and node.target is torch.ops.aten.index.Tensor + + +def fx_node_dtype(expr: torch.fx.Node) -> torch.dtype | None: + """Read an FX node dtype from metadata, following aten.index bases if needed.""" + tensor_meta = expr.meta.get("tensor_meta") + if tensor_meta is not None: + return tensor_meta.dtype + val = expr.meta.get("val") + if isinstance(val, torch.Tensor): + return val.dtype + if is_aten_index_node(expr): + base = expr.args[0] + if isinstance(base, torch.fx.Node): + return fx_node_dtype(base) + return None + + +def fx_node_shape(expr: torch.fx.Node) -> tuple[int, ...] | None: + """Read an FX node shape from tensor metadata or fake tensor value.""" + tensor_meta = expr.meta.get("tensor_meta") + if tensor_meta is not None: + return tuple(tensor_meta.shape) + val = expr.meta.get("val") + if isinstance(val, torch.Tensor): + return tuple(val.shape) + return None + + +@dataclasses.dataclass +class PackedMaskAnalyzer: + """Lower one Flex mask_mod FX graph to packed 32-lane mask intervals. + + The analyzer treats each packed mask as a 32-lane window starting at kv_idx, + rewrites supported mask predicates into bounds over mask_lane, and records + renderable code for lane-uniform aux loads used by those bounds. For example, + a document mask like ``doc_offsets[b_idx] <= kv_idx and kv_idx < q_idx + 128`` + is analyzed over the packed lane expression ``kv_idx + mask_lane`` and + becomes the interval ``[doc_offsets[b_idx] - kv_idx, q_idx + 128 - kv_idx)``. + + nonnegative_indices: FX index placeholders that do not need wraparound handling. + q_idx: FX placeholder for the scalar query index. + kv_idx: FX placeholder for the first KV index in the packed 32-lane window. + q_symbol: SymPy symbol used for q_idx during interval analysis. + kv_symbol: SymPy symbol used for the packed window base KV index. + lane_symbol: SymPy symbol for the lane offset within the packed window. + symbol_codes: CuTe renderings for temporary symbols introduced for aux loads. + placeholder_codes: CuTe renderings for lane-uniform ABI and captured placeholders. + placeholder_exprs: SymPy expressions for captured scalar placeholders. + aux_load_symbols: Stable symbols assigned to supported lane-uniform aux loads. + next_symbol_id: Counter for naming temporary aux-load symbols. + """ + + nonnegative_indices: tuple[torch.fx.Node, ...] + q_idx: torch.fx.Node + kv_idx: torch.fx.Node + q_symbol: sympy.Symbol = dataclasses.field( + default_factory=lambda: sympy.Symbol("q_idx", integer=True, nonnegative=True) + ) + kv_symbol: sympy.Symbol = dataclasses.field( + default_factory=lambda: sympy.Symbol("kv_idx", integer=True, nonnegative=True) + ) + lane_symbol: sympy.Symbol = dataclasses.field( + default_factory=lambda: sympy.Symbol( + "mask_lane", integer=True, nonnegative=True + ) + ) + symbol_codes: dict[sympy.Symbol, str] = dataclasses.field(default_factory=dict) + placeholder_codes: Mapping[torch.fx.Node, str] = dataclasses.field( + default_factory=dict + ) + placeholder_exprs: Mapping[torch.fx.Node, sympy.Expr] = dataclasses.field( + default_factory=dict + ) + aux_load_symbols: dict[torch.fx.Node, sympy.Symbol] = dataclasses.field( + default_factory=dict + ) + next_symbol_id: int = 0 + + def node_to_intervals(self, node: torch.fx.Node) -> MaybeIntervalSet: + """Lower one supported boolean FX node into packed mask intervals.""" + if is_bool_full_node(node, True): + return (PackedMaskInterval.full(),) + if is_bool_full_node(node, False): + return () + if node.op != "call_function": + return None + match node.target: + case torch.ops.aten.bitwise_and.Tensor | torch.ops.aten.logical_and.default: + return self.combine_binary_intervals(node, intersect=True) + case torch.ops.aten.bitwise_or.Tensor | torch.ops.aten.logical_or.default: + return self.combine_binary_intervals(node, intersect=False) + case torch.ops.aten.le.Tensor | torch.ops.aten.le.Scalar: + return self.comparison_to_intervals( + node.args[0], node.args[1], strict=False + ) + case torch.ops.aten.lt.Tensor | torch.ops.aten.lt.Scalar: + return self.comparison_to_intervals( + node.args[0], node.args[1], strict=True + ) + case torch.ops.aten.ge.Tensor | torch.ops.aten.ge.Scalar: + return self.comparison_to_intervals( + node.args[1], node.args[0], strict=False + ) + case torch.ops.aten.gt.Tensor | torch.ops.aten.gt.Scalar: + return self.comparison_to_intervals( + node.args[1], node.args[0], strict=True + ) + case torch.ops.aten.eq.Tensor | torch.ops.aten.eq.Scalar: + return self.equality_to_intervals(node.args[0], node.args[1]) + case torch.ops.aten.ne.Tensor | torch.ops.aten.ne.Scalar: + return self.complement_intervals( + self.equality_to_intervals(node.args[0], node.args[1]) + ) + case ( + torch.ops.aten.logical_not.default | torch.ops.aten.bitwise_not.default + ): + child = node.args[0] + if not isinstance(child, torch.fx.Node): + return None + return self.complement_intervals(self.node_to_intervals(child)) + case _: + return None + + def combine_binary_intervals( + self, node: torch.fx.Node, *, intersect: bool + ) -> MaybeIntervalSet: + lhs, rhs = node.args + if not isinstance(lhs, torch.fx.Node) or not isinstance(rhs, torch.fx.Node): + return None + lhs_intervals = self.node_to_intervals(lhs) + rhs_intervals = self.node_to_intervals(rhs) + if intersect: + return self.intersect_interval_sets(lhs_intervals, rhs_intervals) + return self.union_interval_sets(lhs_intervals, rhs_intervals) + + def comparison_to_intervals( + self, + lhs: object, + rhs: object, + *, + strict: bool, + ) -> MaybeIntervalSet: + exprs = self.mask_operands_to_sympy(lhs, rhs) + if exprs is None: + return None + return self.lane_comparison_to_intervals(*exprs, strict=strict) + + def equality_to_intervals(self, lhs: object, rhs: object) -> MaybeIntervalSet: + exprs = self.mask_operands_to_sympy(lhs, rhs) + if exprs is None: + return None + return self.lane_equality_to_intervals(*exprs) + + def mask_operands_to_sympy( + self, lhs: object, rhs: object + ) -> tuple[sympy.Expr, sympy.Expr] | None: + lhs_expr = self.fx_mask_expr_to_sympy(lhs) + rhs_expr = self.fx_mask_expr_to_sympy(rhs) + if lhs_expr is None or rhs_expr is None: + return None + return lhs_expr, rhs_expr + + def lane_comparison_to_intervals( + self, + lhs_expr: sympy.Expr, + rhs_expr: sympy.Expr, + *, + strict: bool, + ) -> MaybeIntervalSet: + """Convert ``lhs_expr < rhs_expr`` or ``lhs_expr <= rhs_expr`` to an interval. + + The caller normalizes ``>`` and ``>=`` by swapping operands, so this method + only has to lower ``lhs_expr - rhs_expr < 0`` when ``strict`` is true and + ``lhs_expr - rhs_expr <= 0`` otherwise. The difference decomposes as + ``lane_coeff * mask_lane + rest``, and each unit coefficient maps to a mask + shape: + + - ``1``: kv on the small side, e.g. ``kv_idx < q_idx`` (causal-style) -> + prefix interval ``[0, upper)``. + - ``-1``: kv on the large side, e.g. ``start[b] <= kv_idx`` (window or + document starts) -> suffix interval ``[lower, 32)``. + - ``0``: no kv dependence, e.g. ``q_idx < seq_lens[b]`` (padding or other + row/batch/head bounds) -> the whole window is kept or dropped. Truth is + encoded as the upper bound ``32 * keep`` with ``keep`` positive iff the + predicate holds; keep-mask rendering clamps bounds to ``[0, 32]``, so any + positive multiple of 32 keeps all lanes and any non-positive value keeps + none. + + Other coefficients (e.g. ``2 * kv_idx < q_idx``, dilated/strided patterns) + describe non-interval lane sets and fall back to per-lane evaluation. + """ + diff = V.graph.sizevars.simplify(lhs_expr - rhs_expr) + affine = decompose_affine_lane_expr(diff, self.lane_symbol) + if affine is None: + return None + lane_coeff, rest = affine + match lane_coeff: + case 0: + keep = -rest if strict else 1 - rest + upper = V.graph.sizevars.simplify(sympy.Integer(32) * keep) + return self.interval_if_renderable(sympy.Integer(0), upper) + case 1: + upper = V.graph.sizevars.simplify(-rest if strict else -rest + 1) + return self.interval_if_renderable(sympy.Integer(0), upper) + case -1: + lower = V.graph.sizevars.simplify(rest + 1 if strict else rest) + return self.interval_if_renderable(lower, sympy.Integer(32)) + case _: + return None + + def lane_equality_to_intervals( + self, lhs_expr: sympy.Expr, rhs_expr: sympy.Expr + ) -> MaybeIntervalSet: + """Convert ``lhs_expr == rhs_expr`` to packed keep intervals. + + Matching ``FloorDiv`` expressions can describe a contiguous block, e.g. + ``q_idx // B == kv_idx // B``, and are handled before the generic + lane-affine path. Otherwise the difference decomposes as + ``lane_coeff * mask_lane + rest``: + + - ``1`` or ``-1``: exactly one lane can satisfy the equality, e.g. + ``kv_idx == q_idx + c`` -> singleton interval ``[v, v + 1)``. + - ``0``: no kv dependence, e.g. ``head_type[h] == 0`` -> the whole window + is kept or dropped. ``Min(32 * (1 - rest), 32 * (1 + rest))`` is >= 32 + iff ``rest == 0`` and non-positive otherwise, reusing the clamped + all-or-none upper-bound encoding from the comparison case. + + Other coefficients are rejected rather than emitting strided or + divisibility-dependent masks. + """ + if isinstance(lhs_expr, FloorDiv) and isinstance(rhs_expr, FloorDiv): + intervals = self._floor_div_equality_to_intervals(lhs_expr, rhs_expr) + if intervals is not None: + return intervals + diff = V.graph.sizevars.simplify(lhs_expr - rhs_expr) + affine = decompose_affine_lane_expr(diff, self.lane_symbol) + if affine is None: + return None + lane_coeff, rest = affine + match lane_coeff: + case 0: + scale = sympy.Integer(32) + upper = V.graph.sizevars.simplify( + Min(scale * (1 - rest), scale * (1 + rest)) + ) + return self.interval_if_renderable(sympy.Integer(0), upper) + case 1 | -1: + lane_value = -rest if lane_coeff == 1 else rest + lower = V.graph.sizevars.simplify(lane_value) + upper = V.graph.sizevars.simplify(lane_value + 1) + return self.interval_if_renderable(lower, upper) + case _: + return None + + def _floor_div_equality_to_intervals( + self, lhs_expr: FloorDiv, rhs_expr: FloorDiv + ) -> MaybeIntervalSet: + """Convert matching block-id equality into a contiguous lane interval.""" + lhs_base, lhs_divisor = lhs_expr.args + rhs_base, rhs_divisor = rhs_expr.args + if lhs_divisor != rhs_divisor: + return None + if lhs_base == self.q_symbol and rhs_base == self.kv_symbol + self.lane_symbol: + q_block = lhs_expr + elif ( + rhs_base == self.q_symbol and lhs_base == self.kv_symbol + self.lane_symbol + ): + q_block = rhs_expr + else: + return None + block_start = V.graph.sizevars.simplify(q_block * lhs_divisor - self.kv_symbol) + block_end = V.graph.sizevars.simplify(block_start + lhs_divisor) + return self.interval_if_renderable(block_start, block_end) + + def interval_if_renderable( + self, lower: sympy.Expr, upper: sympy.Expr + ) -> MaybeIntervalSet: + if ( + sympy_to_cute_index(lower, self.symbol_codes) is not None + and sympy_to_cute_index(upper, self.symbol_codes) is not None + ): + return (PackedMaskInterval(lower, upper),) + return None + + def complement_intervals(self, intervals: MaybeIntervalSet) -> MaybeIntervalSet: + """Complement a keep-set within the 32-lane window via De Morgan. + + The complement of a union of intervals is the intersection of each + interval's two complement pieces, which stays interval-representable. + Interval bounds may be symbolic, so this composes existing renderable + bounds instead of sorting; intersect_interval_sets caps the blowup. + """ + if intervals is None: + return None + result: MaybeIntervalSet = (PackedMaskInterval.full(),) + for interval in intervals: + result = self.intersect_interval_sets( + result, + ( + PackedMaskInterval(sympy.Integer(0), interval.lower_lane), + PackedMaskInterval( + interval.upper_lane_exclusive, sympy.Integer(32) + ), + ), + ) + return result + + def union_interval_sets( + self, intervals: MaybeIntervalSet, new_intervals: MaybeIntervalSet + ) -> MaybeIntervalSet: + """Union supported interval sets while enforcing the code-size cap.""" + if intervals is None or new_intervals is None: + return None + if ( + len(intervals) + len(new_intervals) + > MAX_PACKED_MASK_INTERVALS_FOR_CODE_SIZE + ): + return None + return intervals + new_intervals + + def intersect_interval_sets( + self, + intervals: MaybeIntervalSet, + new_intervals: MaybeIntervalSet, + ) -> MaybeIntervalSet: + """Intersect supported interval sets while enforcing the code-size cap.""" + if intervals is None or new_intervals is None: + return None + if ( + len(intervals) * len(new_intervals) + > MAX_PACKED_MASK_INTERVALS_FOR_CODE_SIZE + ): + return None + return tuple( + PackedMaskInterval( + V.graph.sizevars.simplify(Max(lhs.lower_lane, rhs.lower_lane)), + V.graph.sizevars.simplify( + Min(lhs.upper_lane_exclusive, rhs.upper_lane_exclusive) + ), + ) + for lhs, rhs in product(intervals, new_intervals) + ) + + def fx_mask_expr_to_sympy(self, expr: object) -> sympy.Expr | None: + """Translate a mask expression with kv_idx expanded by mask_lane.""" + index_symbols = { + self.q_idx: self.q_symbol, + self.kv_idx: self.kv_symbol + self.lane_symbol, + } + index_symbols.update(self.placeholder_exprs) + return fx_aux_index_to_sympy(expr, index_symbols, self.mask_aux_load_to_symbol) + + def mask_aux_load_to_symbol(self, node: torch.fx.Node) -> sympy.Expr | None: + """Assign a temporary SymPy symbol to a supported aux tensor load.""" + if not is_aten_index_node(node): + return None + if node in self.aux_load_symbols: + return self.aux_load_symbols[node] + lane_uniform_code = self.render_lane_uniform_scalar_expr(node) + if lane_uniform_code is None: + return None + symbol = sympy.Symbol(f"mask_bound_{self.next_symbol_id}", integer=True) + self.next_symbol_id += 1 + self.symbol_codes[symbol] = lane_uniform_code + self.aux_load_symbols[node] = symbol + return symbol + + def render_lane_uniform_scalar_expr( + self, + expr: object, + *, + for_index: bool = False, + index_dim_size: int | sympy.Expr | None = None, + ) -> str | None: + """Render an expression that is invariant across the packed KV lanes.""" + if isinstance(expr, int | sympy.Integer): + index = int(expr) + if for_index and index < 0: + if index_dim_size is None: + return None + index = V.graph.sizevars.guard_int(index + index_dim_size) + return f"cutlass.Int32({index})" + if not isinstance(expr, torch.fx.Node): + return None + + if expr is self.kv_idx: + return None + if expr in self.placeholder_codes: + return self.placeholder_codes[expr] + + if is_aten_index_node(expr): + return self._render_lane_uniform_index_expr(expr, for_index=for_index) + if expr.op != "call_function": + return None + match expr.target: + case torch.ops.aten.div.Tensor_mode: + if expr.kwargs.get("rounding_mode") != "floor": + return None + op = "//" + case _: + op = LANE_UNIFORM_BINARY_OPS.get(expr.target) + if op is None: + return None + args = expr.args + if len(args) < 2: + return None + lhs = self.render_lane_uniform_scalar_expr(args[0]) + rhs = self.render_lane_uniform_scalar_expr(args[1]) + if lhs is None or rhs is None: + return None + return f"({lhs} {op} {rhs})" + + def _render_lane_uniform_index_expr( + self, + expr: torch.fx.Node, + *, + for_index: bool, + ) -> str | None: + """Render a scalar integer aten.index load that is uniform across lanes.""" + if fx_node_dtype(expr) not in ( + torch.int8, + torch.int16, + torch.int32, + torch.int64, + torch.uint8, + ): + return None + result_shape = fx_node_shape(expr) + if result_shape is not None and len(result_shape) != 0: + return None + base, indices = expr.args + base_code = self.render_lane_uniform_scalar_expr(base) + base_shape = fx_node_shape(base) if isinstance(base, torch.fx.Node) else None + if base_code is None or not isinstance(indices, (list, tuple)): + return None + if base_shape is None or len(indices) != len(base_shape): + return None + index_codes = [] + for dim, index in enumerate(indices): + dim_size = base_shape[dim] + index_code = self.render_lane_uniform_scalar_expr( + index, for_index=True, index_dim_size=dim_size + ) + if index_code is None: + return None + if ( + dim_size is not None + and isinstance(index, torch.fx.Node) + and index not in self.nonnegative_indices + ): + if not isinstance(dim_size, int | sympy.Integer): + return None + dtype = fx_node_dtype(index) + integer_type = "Int64" if dtype == torch.int64 else "Int32" + size_code = f"cutlass.{integer_type}({dim_size})" + zero_code = f"cutlass.{integer_type}(0)" + index_code = ( + f"({index_code} + {size_code} " + f"if {index_code} < {zero_code} else {index_code})" + ) + index_codes.append(index_code) + load = f"{base_code}[{', '.join(index_codes)}]" + if for_index and fx_node_dtype(expr) == torch.int64: + return load + return f"cutlass.Int32({load})" + + +@dataclasses.dataclass(frozen=True) +class PackedMaskAuxPlaceholderMap: + """Maps mask_mod aux placeholders to runtime scalar expressions or tensors.""" + + codes: Mapping[torch.fx.Node, str] + exprs: Mapping[torch.fx.Node, sympy.Expr] + + @classmethod + def from_placeholders( + cls, + placeholders: Sequence[torch.fx.Node], + other_buffers: Sequence[object], + symbol_codes: Mapping[sympy.Symbol, str], + ) -> "PackedMaskAuxPlaceholderMap | None": + """Render lane-uniform mask_mod captures for packed interval analysis.""" + codes: dict[torch.fx.Node, str] = {} + exprs: dict[torch.fx.Node, sympy.Expr] = {} + tensor_idx = 0 + for placeholder, buffer in zip(placeholders, other_buffers): + if isinstance(buffer, sympy.Expr): + rendered = sympy_to_cute_index(buffer, symbol_codes) + if rendered is None: + return None + codes[placeholder] = rendered + exprs[placeholder] = buffer + else: + codes[placeholder] = f"aux_tensors[{tensor_idx}]" + tensor_idx += 1 + for placeholder in placeholders[len(other_buffers) :]: + codes[placeholder] = f"aux_tensors[{tensor_idx}]" + tensor_idx += 1 + return cls(codes, exprs) + + +def select_packed_mask_intervals( + graph_module: GraphModule, + other_buffers: Sequence[object] = (), + aux_scalar_symbol_codes: Mapping[sympy.Symbol, str] | None = None, +) -> MaybeIntervalSet: + """Entry point for selecting packed mask intervals from a mask_mod graph. + + Returns ``None`` when the graph is unsupported, when interval packing would + increase code size too much, or when analysis reduces the whole mask to the + unconditional ``[0, 32)`` interval. + """ + graph = graph_module.graph + nodes = list(graph.nodes) + placeholders = [node for node in nodes if node.op == "placeholder"] + output = [node for node in nodes if node.op == "output"] + if len(placeholders) < 4 or len(output) != 1: + return None + + b_idx, h_idx, q_idx, kv_idx, *aux_placeholders = placeholders + output_val = output[0].args[0] + if not isinstance(output_val, torch.fx.Node): + return None + + symbol_codes = dict(aux_scalar_symbol_codes or {}) + placeholder_map = PackedMaskAuxPlaceholderMap.from_placeholders( + aux_placeholders, other_buffers, symbol_codes + ) + if placeholder_map is None: + return None + + analyzer = PackedMaskAnalyzer( + nonnegative_indices=(b_idx, h_idx, q_idx), + q_idx=q_idx, + kv_idx=kv_idx, + symbol_codes=symbol_codes, + placeholder_codes={ + b_idx: "b_idx[0]", + h_idx: "h_idx[0]", + q_idx: "q_idx[0]", + **placeholder_map.codes, + }, + placeholder_exprs=placeholder_map.exprs, + ) + intervals = analyzer.node_to_intervals(output_val) + if intervals is None: + perf_hint_log.info( + "flex FLASH: mask_mod could not be lowered to packed 32-lane intervals; " + "partial blocks will evaluate the mask per lane, which can be much " + "slower. Prefer comparisons of q_idx/kv_idx against lane-uniform bounds " + "(e.g. seq_lens[b]) over per-token gathers. mask graph:\n%s", + graph, + ) + return None + if len(intervals) == 1 and intervals[0].is_full(): + return None + return tuple( + interval.with_symbol_codes(analyzer.symbol_codes) for interval in intervals + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/common.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/common.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..cd0538c40a86047b64031cc8cb78d9b1f0741be6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/common.py.jinja @@ -0,0 +1,227 @@ + + +# Common Imports +@triton.jit +def forward_block_mn( + {{gen_argdefs()}}, + q, K, V, desc_k, desc_v, Q_LEN, KV_LEN, + # accumulated values + acc, l_i, m_i, + # Offsets + off_z, off_h, offs_m, offs_n, + # Offsets needed for TMA loads + kv_start, + kv_offset, + MATMUL_PRECISION, RCP_LN2, + # Strides for K and V + stride_kk, stride_kn, stride_vn, stride_vk, + IS_FULL_BLOCKS, CHECK_BLOCK_BOUNDARY=False, + +): + # Redefines all kernel parameters (BLOCK_M, etc.) so we don't need to plumb them all through + {{gen_defines() | indent_except_first(1)}} + + # -- load k -- + # NB reversed order to since K is transposed + kv_base_offset = kv_start + kv_offset + {%- if USE_TMA %} + k = tl.load_tensor_descriptor( + desc_k, + [kv_base_offset, 0], + ) + {%- else %} + + # Load K as [BLOCK_N, QK_HEAD_DIM_ROUNDED] then transpose to [QK_HEAD_DIM_ROUNDED, BLOCK_N] + offs_k = tl.arange(0, QK_HEAD_DIM_ROUNDED) + offs_n_load = kv_base_offset + tl.arange(0, BLOCK_N) + k = load_checked_2d(K, offs_n_load, offs_k, stride_kn, stride_kk, IS_DIVISIBLE, SAFE_HEAD_DIM, KV_LEN, QK_HEAD_DIM, INDEX_DTYPE) + {%- endif %} + + k = tl.trans(k) + k = k.to(q.dtype) + # -- compute qk --- + qk = tl.dot(q, k, input_precision=FLOAT32_PRECISION) # TODO: use cuda matmul when q_len <= 2. + if not PRESCALE_QK: + qk *= SM_SCALE + # ~~~~~~~~~~~~~~~~~~~ Apply score modification ~~~~~~~~~~~~~~~~~~~ + # If this is the last block of a non divisible seqlen, we still need to load [BLOCK_M, BLOCK_N] elements, + # which is larger than the actual number of elements. To avoid access memory out of bound, + # we need to mask out the elements that are out of Q_LEN & KV_LEN. + m = get_bounded_indices(offs_m, Q_LEN if CHECK_BLOCK_BOUNDARY else None) + n = get_bounded_indices(offs_n, KV_LEN if CHECK_BLOCK_BOUNDARY else None) + + {{ modification( + subgraph_number=0, + output_name="post_mod_scores", + score="qk", + b="off_z", + h="off_h", + m="m", + n="n", + out="qk", + input_shapes={ + "score": ("BLOCK_M", "BLOCK_N"), + "m": ("BLOCK_M", "1"), + "n": ("1", "BLOCK_N"), + }, + input_dtypes={ + "b": "index", + "h": "index", + "m": "index", + "n": "index", + } + ) | indent_except_first(1) }} + + if CHECK_BLOCK_BOUNDARY: + # Mask out the elements that are out of the KV_LEN for non divisible seqlen. + post_mod_scores = tl.where(offs_n < KV_LEN, post_mod_scores, float("-inf")) + + if not IS_FULL_BLOCKS: + {{ modification( + subgraph_number=1, + output_name="mask_mod_output", + score="qk", + b="off_z", + h="off_h", + m="m", + n="n", + input_shapes={ + "score": ("BLOCK_M", "BLOCK_N"), + "m": ("BLOCK_M", "1"), + "n": ("1", "BLOCK_N"), + }, + input_dtypes={ + "b": "index", + "h": "index", + "m": "index", + "n": "index", + } + ) | indent_except_first(2) }} + + if CHECK_BLOCK_BOUNDARY: + mask_mod_output = tl.where(offs_n < KV_LEN, mask_mod_output, False) + # apply mask for partially unmasked blocks + post_mod_scores = tl.where(mask_mod_output, post_mod_scores, float("-inf")) + + if not PRESCALE_QK: + post_mod_scores *= RCP_LN2 + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + # -- compute scaling constant --- + m_ij = tl.maximum(m_i, tl.max(post_mod_scores, 1)) + if not ROWS_GUARANTEED_SAFE: + masked_out_rows = (m_ij == float("-inf")) + m_ij_masked = tl.where(masked_out_rows, 0, m_ij) + else: + m_ij_masked = m_ij + + alpha = tl.math.exp2(m_i - m_ij_masked) + p = tl.math.exp2(post_mod_scores - m_ij_masked[:, None]) + + # NB: l_i update is pulled up here since it's a bit faster + # NB: For headdim=256, it's faster to move it back down to after m_i = + # m_ij + l_i = l_i * alpha + tl.sum(p, 1) + # # -- scale and update acc -- + acc = acc * alpha[:, None] + {%- if USE_TMA %} + v = tl.load_tensor_descriptor( + desc_v, + [kv_base_offset, 0], + ) + {%- else %} + # Calculate offsets for V loading - reuse kv_base_offset from K loading + offs_v = tl.arange(0, V_HEAD_DIM_ROUNDED) + v = load_checked_2d(V, offs_n_load, offs_v, stride_vn, stride_vk, IS_DIVISIBLE, SAFE_HEAD_DIM, KV_LEN, V_HEAD_DIM, INDEX_DTYPE) + {%- endif %} + acc = tl.dot(p.to(MATMUL_PRECISION), v.to(q.dtype), acc, input_precision=FLOAT32_PRECISION) + + # -- update m_i + m_i = m_ij + + return acc, l_i, m_i + +@triton.jit +def forward_inner( + {{gen_argdefs()}}, + q, K, V, + desc_k, desc_v, Q_LEN, KV_LEN, + # accumulated values + acc, l_i, m_i, + # Offsets used as inputs to score_mod & mask_mod + # of size [BLOCK_M, BLOCK_N] or scalar. + off_z, off_h, offs_m, offs_n, + # Offsets needed for TMA loads + kv_start, + # blocksparse data + kv_indices, kv_num_blocks, + # start kv and end kv block + block_n_start, block_n_end, + MATMUL_PRECISION, + # Strides for K and V + stride_kk, stride_kn, stride_vn, stride_vk, + IS_FULL_BLOCKS, +): + # Redefines all kernel parameters (BLOCK_M, etc.) so we don't need to plumb them all through + {{gen_defines() | indent_except_first(1)}} + + SPARSE_KV_MULTIPLE: tl.constexpr = (SPARSE_KV_BLOCK_SIZE // BLOCK_N) + RCP_LN2: tl.constexpr = 1.44269504 + + if PRESCALE_QK: + q = (q * SM_SCALE * RCP_LN2).to(MATMUL_PRECISION) + + kv_offset = 0 + + # loop over k, v and update accumulator until block_n_end + for start_n in range(block_n_start, block_n_end): + # Here IS_DIVISIBLE acts are the start_n = tl.multiple_of(start_n, BLOCK_N) from triton_fused_attention. + if IS_DIVISIBLE: + acc, l_i, m_i = forward_block_mn( + {{gen_argdefs()}}, + q, K, V, desc_k, desc_v, Q_LEN, KV_LEN, + # accumulated values + acc, l_i, m_i, + # Offsets + off_z, off_h, offs_m, offs_n, + # Offsets needed for TMA loads + kv_start, + kv_offset, + MATMUL_PRECISION, RCP_LN2, + # Strides for K and V + stride_kk, stride_kn, stride_vn, stride_vk, + IS_FULL_BLOCKS, + ) + else: + # Benchmark shows even we applied mod & mask to each block for non divisible seqlen, + # it's on par or slightly faster than only applying to the last block in fwd. + # However, we choose different strategy for bwd, where we only apply mod & mask + # to the last block because it's faster a lot. + acc, l_i, m_i = forward_block_mn( + {{gen_argdefs()}}, + q, K, V, desc_k, desc_v, Q_LEN, KV_LEN, + # accumulated values + acc, l_i, m_i, + # Offsets + off_z, off_h, offs_m, offs_n, + # Offsets needed for TMA loads + kv_start, + kv_offset, + MATMUL_PRECISION, RCP_LN2, + # Strides for K and V + stride_kk, stride_kn, stride_vn, stride_vk, + IS_FULL_BLOCKS, CHECK_BLOCK_BOUNDARY=True, + ) + + + + offset = get_offset_for_next_block( + start_n, kv_indices, kv_num_blocks, + SPARSE_KV_BLOCK_SIZE, SPARSE_KV_MULTIPLE, BLOCK_N, BLOCKS_ARE_CONTIGUOUS + ) + + offs_n = offs_n + offset + kv_offset += offset + + + return acc, l_i, m_i diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flash_attention.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flash_attention.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..de849a8cd3ab41956923dc3cd0671eeadcbfb761 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flash_attention.py.jinja @@ -0,0 +1,149 @@ +{% if NEEDS_BLOCK_MASK and HAS_FULL_BLOCKS %} +{{def_kernel("Q", "K", "V", "LOGSUMEXP", "KV_NUM_BLKS", "KV_IDX", "FULL_KV_NUM_BLKS", "FULL_KV_IDX")}} +{% elif NEEDS_BLOCK_MASK %} +{{def_kernel("Q", "K", "V", "LOGSUMEXP", "KV_NUM_BLKS", "KV_IDX")}} +{% else %} +{{def_kernel("Q", "K", "V", "LOGSUMEXP")}} +{% endif %} + from flash_attn.cute.interface import _flash_attn_fwd + {% if NEEDS_BLOCK_MASK %} + from flash_attn.cute.block_sparsity import BlockSparseTensorsTorch + {% endif %} + {% if MASK_MOD_PACKED_INTERVALS is not none %} + import flash_attn.cute.utils as utils + {% endif %} + + # Transpose tensors for _flash_attn_fwd compatibility (B,H,M,D) -> (B,M,H,D) + q_transposed = Q.transpose(1, 2) + k_transposed = K.transpose(1, 2) + v_transposed = V.transpose(1, 2) + aux_scalars = {{ define_aux_scalars(AUX_SCALAR_SYMBOLS) }} + + {# FA4 omits aux_scalars when it is None for compatibility with older callables. #} + {# Keep the default so generated mods accept both FA4 call forms. #} + {% if HAS_SCORE_MOD %} + @cute.jit + def score_mod( + tSrS_ssa, + b_idx, + h_idx, + q_idx, + kv_idx, + seqlen_info, + aux_tensors, + aux_scalars=None, + ): + {{unpack_buffers("aux_tensors", indent_width=8)}} + {{ modification( + subgraph_number=0, + output_name="tSrS_ssa", + score="tSrS_ssa", + b="b_idx", + h="h_idx", + m="q_idx", + n="kv_idx", + out="tSrS_ssa", + vector_load_vec_size=SCORE_MOD_VEC_SIZE, + vector_load_index="kv_idx", + vector_load_dim=-1 + ) | indent_except_first(2) }} + return tSrS_ssa.to(cutlass.Float32) + {{ set_cute_hash("score_mod", "score") }} + {% if SCORE_MOD_VEC_SIZE %} + score_mod.__vec_size__ = {{SCORE_MOD_VEC_SIZE}} + {% endif %} + {% else %} + score_mod = None + {% endif %} + + # (B,M,H,D) -> (B,H,M,D) + output = {{get_output()}} + output_transposed = output.transpose(1, 2) + + {% if HAS_MASK_MOD %} + {# mask_mod is subgraph 1 when HAS_SCORE_MOD, else subgraph 0 #} + {% set mask_subgraph_idx = 1 if HAS_SCORE_MOD else 0 %} + @cute.jit + def mask_mod(b_idx, h_idx, q_idx, kv_idx, seqlen_info, aux_tensors, aux_scalars=None): + {{unpack_buffers("aux_tensors", indent_width=8)}} + {% if MASK_MOD_PACKED_INTERVALS is not none %} + {% set tensor_buffers = add_tensor_inputs(MASK_MOD_OTHER_BUFFERS) %} + {% if tensor_buffers %} + {# Packed interval expressions are rendered against mask_mod aux buffers only. #} + aux_tensors = [{{ tensor_buffers | join(", ") }}] + {% endif %} + mask_mod_packed = cute.make_rmem_tensor(1, dtype=cutlass.Uint32) + mask_mod_packed[0] = cutlass.Uint32(0) + {% for interval in MASK_MOD_PACKED_INTERVALS %} + mask_mod_packed[0] = mask_mod_packed[0] | {{ interval.keep_mask_expr() }} + {% endfor %} + return mask_mod_packed.load() + {% else %} + {{ modification( + subgraph_number=mask_subgraph_idx, + output_name="mask_mod_output", + b="b_idx", + h="h_idx", + m="q_idx", + n="kv_idx", + vector_load_vec_size=MASK_MOD_VEC_SIZE, + vector_load_index="kv_idx", + vector_load_dim=-1, + ) | indent_except_first(2) }} + {% if MASK_MOD_VEC_SIZE %} + mask_mod_packed = cute.make_rmem_tensor(1, dtype=cutlass.Uint32) + mask_mod_packed[0] = cutlass.Uint32(0) + for mask_lane_idx in cutlass.range_constexpr({{ MASK_MOD_VEC_SIZE }}): + mask_mod_packed[0] = ( + mask_mod_packed[0] | (cutlass.Uint32(1) << mask_lane_idx) + if cutlass.Boolean(mask_mod_output[mask_lane_idx]) + else mask_mod_packed[0] + ) + return mask_mod_packed.load() + {% else %} + return mask_mod_output + {% endif %} + {% endif %} + {{ set_cute_hash("mask_mod", "mask") }} + {% if MASK_MOD_VEC_SIZE %} + mask_mod.__vec_size__ = {{ MASK_MOD_VEC_SIZE }} + {% endif %} + {% else %} + mask_mod = None + {% endif %} + {% if NEEDS_BLOCK_MASK %} + block_sparse_tensors = BlockSparseTensorsTorch( + KV_NUM_BLKS, + KV_IDX, + {% if HAS_FULL_BLOCKS %}FULL_KV_NUM_BLKS{% else %}KV_NUM_BLKS.new_zeros(KV_NUM_BLKS.shape){% endif %}, + {% if HAS_FULL_BLOCKS %}FULL_KV_IDX{% else %}KV_IDX.new_zeros(KV_IDX.shape){% endif %}, + block_size=({{SPARSE_Q_BLOCK_SIZE}}, {{SPARSE_KV_BLOCK_SIZE}}), + ) + {% else %} + block_sparse_tensors = None + {% endif %} + + # Collect any additional tensor buffers that were added during modifications + {% set tensor_buffers = get_tensor_buffers() -%} + {% if tensor_buffers -%} + buffers = [{% for buffer in tensor_buffers %}{{buffer}}{% if not loop.last %}, {% endif %}{% endfor %}] + buffers = list(buffers) + {% else -%} + buffers = None + {% endif -%} + + # Out and LSE filled inplace + _flash_attn_fwd( + q_transposed, + k_transposed, + v_transposed, + softmax_scale={{SM_SCALE}}, + return_lse=True, + score_mod=score_mod, + mask_mod=mask_mod, + out=output_transposed, + lse=LOGSUMEXP, + block_sparse_tensors=block_sparse_tensors, + aux_tensors=buffers{% if AUX_SCALAR_SYMBOLS %}, + aux_scalars=aux_scalars{% endif %} + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flash_attention_backward.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flash_attention_backward.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..0513487e400e60ff29240fd948d650834d3cdd45 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flash_attention_backward.py.jinja @@ -0,0 +1,162 @@ +{% if HAS_BLOCK_MASK and HAS_DQ_WRITE_ORDER and HAS_DQ_WRITE_ORDER_FULL and HAS_DQ_KV_ORDER %} +{{def_kernel("Q", "K", "V", "OUT", "D_OUT", "LSE", "DK", "DV", "Q_NUM_BLKS", "Q_IDX", "FULL_Q_NUM_BLKS", "FULL_Q_IDX", "DQ_WRITE_ORDER", "DQ_WRITE_ORDER_FULL", "DQ_KV_ORDER", "DLSE")}} +{% elif HAS_BLOCK_MASK and HAS_DQ_WRITE_ORDER and HAS_DQ_WRITE_ORDER_FULL %} +{{def_kernel("Q", "K", "V", "OUT", "D_OUT", "LSE", "DK", "DV", "Q_NUM_BLKS", "Q_IDX", "FULL_Q_NUM_BLKS", "FULL_Q_IDX", "DQ_WRITE_ORDER", "DQ_WRITE_ORDER_FULL", "DLSE")}} +{% elif HAS_BLOCK_MASK and HAS_DQ_WRITE_ORDER and HAS_DQ_KV_ORDER %} +{{def_kernel("Q", "K", "V", "OUT", "D_OUT", "LSE", "DK", "DV", "Q_NUM_BLKS", "Q_IDX", "FULL_Q_NUM_BLKS", "FULL_Q_IDX", "DQ_WRITE_ORDER", "DQ_KV_ORDER", "DLSE")}} +{% elif HAS_BLOCK_MASK and HAS_DQ_WRITE_ORDER %} +{{def_kernel("Q", "K", "V", "OUT", "D_OUT", "LSE", "DK", "DV", "Q_NUM_BLKS", "Q_IDX", "FULL_Q_NUM_BLKS", "FULL_Q_IDX", "DQ_WRITE_ORDER", "DLSE")}} +{% elif HAS_BLOCK_MASK and HAS_DQ_KV_ORDER %} +{{def_kernel("Q", "K", "V", "OUT", "D_OUT", "LSE", "DK", "DV", "Q_NUM_BLKS", "Q_IDX", "FULL_Q_NUM_BLKS", "FULL_Q_IDX", "DQ_KV_ORDER", "DLSE")}} +{% elif HAS_BLOCK_MASK %} +{{def_kernel("Q", "K", "V", "OUT", "D_OUT", "LSE", "DK", "DV", "Q_NUM_BLKS", "Q_IDX", "FULL_Q_NUM_BLKS", "FULL_Q_IDX", "DLSE")}} +{% else %} +{{def_kernel("Q", "K", "V", "OUT", "D_OUT", "LSE", "DK", "DV", "DLSE")}} +{% endif %} + from flash_attn.cute.interface import _flash_attn_bwd + + q_transposed = Q.transpose(1, 2) + k_transposed = K.transpose(1, 2) + v_transposed = V.transpose(1, 2) + out_transposed = OUT.transpose(1, 2) + d_out_transposed = D_OUT.transpose(1, 2) + + dq_out = {{get_output()}} + dq_out_transposed = dq_out.transpose(1, 2) + dk_out_transposed = DK.transpose(1, 2) + dv_out_transposed = DV.transpose(1, 2) + aux_scalars = {{ define_aux_scalars(AUX_SCALAR_SYMBOLS) }} + + {# FA4 omits aux_scalars when it is None for compatibility with older callables. #} + {# Keep the default so generated mods accept both FA4 call forms. #} + {% if HAS_SCORE_MOD %} + @cute.jit + def score_mod( + tSrS_ssa, + b_idx, + h_idx, + q_idx, + kv_idx, + seqlen_info, + aux_tensors, + aux_scalars=None, + ): + {{unpack_buffers("aux_tensors", indent_width=8)}} + {{ modification( + subgraph_number=0, + output_name="tSrS_ssa", + score="tSrS_ssa", + b="b_idx", + h="h_idx", + m="q_idx", + n="kv_idx", + out="tSrS_ssa" + ) | indent_except_first(2) }} + return tSrS_ssa.to(cutlass.Float32) + {{ set_cute_hash("score_mod", "score") }} + + @cute.jit + def score_mod_bwd( + grad_score_mod_ssa, + tSrS_ssa, + b_idx, + h_idx, + q_idx, + kv_idx, + seqlen_info, + aux_tensors, + aux_scalars=None, + ): + {{unpack_buffers("aux_tensors", indent_width=8)}} + {{ modification( + subgraph_number=1, + output_name="grad_score_mod_ssa_out", + score="tSrS_ssa", + grad_score_mod="grad_score_mod_ssa", + b="b_idx", + h="h_idx", + m="q_idx", + n="kv_idx" + ) | indent_except_first(2) }} + return grad_score_mod_ssa_out.to(cutlass.Float32) + {{ set_cute_hash("score_mod_bwd", "score_bwd") }} + {% else %} + score_mod = None + score_mod_bwd = None + {% endif %} + + {% if HAS_BLOCK_MASK %} + from flash_attn.cute.block_sparsity import BlockSparseTensorsTorch + {# mask_mod is subgraph 2 when HAS_SCORE_MOD, else subgraph 0 #} + {% set mask_subgraph_idx = 2 if HAS_SCORE_MOD else 0 %} + @cute.jit + def mask_mod(b_idx, h_idx, q_idx, kv_idx, seqlen_info, aux_tensors, aux_scalars=None): + {{unpack_buffers("aux_tensors", indent_width=8)}} + {{ modification( + subgraph_number=mask_subgraph_idx, + output_name="mask_mod_output", + b="b_idx", + h="h_idx", + m="q_idx", + n="kv_idx" + ) | indent_except_first(2) }} + return mask_mod_output + {{ set_cute_hash("mask_mod", "mask") }} + block_sparse_kwargs = { + "block_size": ({{SPARSE_Q_BLOCK_SIZE}}, {{SPARSE_KV_BLOCK_SIZE}}), + } + {% if HAS_DQ_WRITE_ORDER %} + block_sparse_kwargs["dq_write_order"] = DQ_WRITE_ORDER + {% endif %} + {% if HAS_DQ_WRITE_ORDER_FULL %} + block_sparse_kwargs["dq_write_order_full"] = DQ_WRITE_ORDER_FULL + {% endif %} + {% if SUPPORTS_DQ_KV_ORDER %} + {% if HAS_DQ_KV_ORDER %} + block_sparse_kwargs["dq_kv_order"] = DQ_KV_ORDER + {% elif DQ_KV_ORDER_SPT is not none %} + block_sparse_kwargs["dq_kv_order"] = {{DQ_KV_ORDER_SPT}} + {% endif %} + {% elif SUPPORTS_SPT %} + {% if HAS_DQ_KV_ORDER %} + raise RuntimeError("Explicit tensor dq_kv_order requires flash-attn-4 with dq_kv_order support") + {% elif DQ_KV_ORDER_SPT is not none %} + block_sparse_kwargs["spt"] = {{DQ_KV_ORDER_SPT}} + {% endif %} + {% endif %} + block_sparse_tensors = BlockSparseTensorsTorch( + Q_NUM_BLKS, Q_IDX, FULL_Q_NUM_BLKS, FULL_Q_IDX, **block_sparse_kwargs + ) + {% else %} + mask_mod = None + block_sparse_tensors = None + {% endif %} + + {% set tensor_buffers = get_tensor_buffers() -%} + {% if tensor_buffers -%} + buffers = [{% for buffer in tensor_buffers %}{{buffer}}{% if not loop.last %}, {% endif %}{% endfor %}] + buffers = list(buffers) + {% else -%} + buffers = None + {% endif -%} + + _flash_attn_bwd( + q_transposed, + k_transposed, + v_transposed, + out_transposed, + d_out_transposed, + LSE, + softmax_scale={{SM_SCALE}}, + score_mod=score_mod, + score_mod_bwd=score_mod_bwd, + mask_mod=mask_mod, + aux_tensors=buffers,{% if AUX_SCALAR_SYMBOLS %} + aux_scalars=aux_scalars,{% endif %} + dq=dq_out_transposed, + dk=dk_out_transposed, + dv=dv_out_transposed, + block_sparse_tensors=block_sparse_tensors, + deterministic={{DETERMINISTIC_BACKWARD_ENABLED}},{% if HAS_DLSE %} + dlse=DLSE,{% endif %} + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flex_attention.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flex_attention.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..ab177f2c3f8197c3e841f36edbb2461ac32a05ec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flex_attention.py.jinja @@ -0,0 +1,224 @@ +{{def_kernel("Q", "K", "V", "LSE", "MAX", "KV_NUM_BLKS", "KV_IDX", "FULL_KV_NUM_BLKS", "FULL_KV_IDX")}} + # Sub notation for this kernel: + # + # Q: Query, K: Key, V: Value + # M: Number of queries, N: Number of keys/values, D: Model dimension + # QK_HEAD_DIM: The dimension of the query and key embeddings + # V_HEAD_DIM: The dimension of the value embeddings + # z: Batch size, h: Number of heads, m: Number of queries per head, k: Number of keys per head + # GQA_SHARED_HEADS: number of query heads sharing one kv head in GQA setups. + # + # The following FULL_* and PARTIAL_* is defined in the block sparse mask grid, rather than the thread block grid. + # KV_NUM_BLKS: The number of KV blocks (that may or may not require masking) for each query. + # KV_IDX: The indices of KV blocks (that may or may not require masking) for each query. + # FULL_KV_NUM_BLKS: The number of fully unmasked KV blocks (so we don't need masking) for each query. + # FULL_KV_IDX: The indices of fully unmasked KV blocks (so we don't need masking) for each query. + # + # OUTPUT_LOGSUMEXP: We only need to store the logsumexp if we require grad + # + # (Modifiable) Performance tuning options + # BLOCK_M: The thread block size across the seqlen dim of Q. + # BLOCK_N: Iterate over BLOCK_N across the seqlen dim of K/V in each thread block. + + # The below are kernel options that can be applied for certain score_mods, + # or involve a numerics vs. perf tradeoff + # PRESCALE_QK: Whether to pre-scale QK by 1/sqrt(d) and change of base. Has + # about 20% more numerical error, but slightly faster. + # ROWS_GUARANTEED_SAFE: Is it guaranteed that at least one value in each row + # is not masked out? If so, we can skip an extra safety check + # BLOCKS_ARE_CONTIGUOUS: Is it guaranteed that all blocks in the mask are + # contiguous? If so, we don't need to do an indirect jump for every block + + tl.static_assert(SPARSE_Q_BLOCK_SIZE >= BLOCK_M and SPARSE_Q_BLOCK_SIZE % BLOCK_M == 0) + tl.static_assert(SPARSE_KV_BLOCK_SIZE >= BLOCK_N and SPARSE_KV_BLOCK_SIZE % BLOCK_N == 0) + + # Define strides of inputs + stride_qz, stride_qh, stride_qm, stride_qk = {{stride("Q")}} + stride_kz, stride_kh, stride_kn, stride_kk = {{stride("K")}} + stride_vz, stride_vh, stride_vn, stride_vk = {{stride("V")}} + + ZQ = {{size("Q", 0)}} + HQ = {{size("Q", 1)}} + Q_LEN = {{size("Q", 2)}} + ZKV = {{size("K", 0)}} + KV_LEN = {{size("K", 2)}} + + MATMUL_PRECISION = Q.dtype.element_ty + + q_start = tl.program_id(0).to(INDEX_DTYPE) + off_zq = tl.program_id(1).to(INDEX_DTYPE) + off_hq = tl.program_id(2).to(INDEX_DTYPE) + + # We support two cases for batch dimension. a) (ZKV == ZQ) where off_zkv = off_zq. + # b) (ZKV == 1 and ZQ > 1) where KV is broadcasted along the batch dimension and off_zkv=0. + off_zkv = off_zq % ZKV + off_hkv = off_hq // GQA_SHARED_HEADS + off_g = off_hq % GQA_SHARED_HEADS + + q_offset = off_zq * stride_qz + off_hq * stride_qh + k_offset = off_zkv * stride_kz + off_hkv * stride_kh + v_offset = off_zkv * stride_vz + off_hkv * stride_vh + + Q = Q + q_offset + K = K + k_offset + V = V + v_offset + + # Setting up the TMA descriptors for Q, K, V + desc_q = None + desc_k = None + desc_v = None + {%- if USE_TMA %} + desc_q = tl.make_tensor_descriptor( + base=Q, + shape=[Q_LEN, QK_HEAD_DIM], + strides=[stride_qm, 1], + block_shape=[BLOCK_M, QK_HEAD_DIM_ROUNDED], + ) + + desc_k = tl.make_tensor_descriptor( + base=K, + shape=[KV_LEN, QK_HEAD_DIM], + strides=[stride_kn, 1], + block_shape=[BLOCK_N, QK_HEAD_DIM_ROUNDED], + ) + + desc_v = tl.make_tensor_descriptor( + base=V, + shape=[KV_LEN, V_HEAD_DIM], + strides=[stride_vn, 1], + block_shape=[BLOCK_N, V_HEAD_DIM_ROUNDED], + ) + {%- endif %} + + SPARSE_Z = {{size("KV_NUM_BLKS", 0)}} + SPARSE_HQ = {{size("KV_NUM_BLKS", 1)}} + + sparse_idx_z = off_zq % SPARSE_Z + sparse_idx_hq = off_hq % SPARSE_HQ + + SPARSE_Q_MULTIPLE: tl.constexpr = (SPARSE_Q_BLOCK_SIZE // BLOCK_M) + SPARSE_KV_MULTIPLE: tl.constexpr = (SPARSE_KV_BLOCK_SIZE // BLOCK_N) + + stride_kv_num_blks_h = {{stride("KV_NUM_BLKS", 1)}} + stride_kv_idx_h = {{stride("KV_IDX", 1)}} + stride_kv_idx_m = {{stride("KV_IDX", 2)}} + {%- if HAS_FULL_BLOCKS %} + stride_full_kv_num_blks_h = {{stride("FULL_KV_NUM_BLKS", 1)}} + stride_full_kv_idx_h = {{stride("FULL_KV_IDX", 1)}} + stride_full_kv_idx_m = {{stride("FULL_KV_IDX", 2)}} + {%- endif %} + + # initialize pointer to m and l + m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") + l_i = tl.zeros([BLOCK_M], dtype=tl.float32) + acc = tl.zeros([BLOCK_M, V_HEAD_DIM_ROUNDED], dtype=tl.float32) + + offs_m = q_start * BLOCK_M + tl.arange(0, BLOCK_M) + + # KV_IDX and KV_NUM_BLKS are always contiguous. + sparse_hz_offset = sparse_idx_z * SPARSE_HQ + sparse_idx_hq + sparse_kv_num_blks_offset = sparse_hz_offset * stride_kv_num_blks_h + q_start // SPARSE_Q_MULTIPLE + sparse_kv_idx_offset = sparse_hz_offset * stride_kv_idx_h + (q_start // SPARSE_Q_MULTIPLE) * stride_kv_idx_m # noqa: B950 + {%- if HAS_FULL_BLOCKS %} + sparse_full_kv_num_blks_offset = sparse_hz_offset * stride_full_kv_num_blks_h + q_start // SPARSE_Q_MULTIPLE + sparse_full_kv_idx_offset = sparse_hz_offset * stride_full_kv_idx_h + (q_start // SPARSE_Q_MULTIPLE) * stride_full_kv_idx_m # noqa: B950 + {%- endif %} + + {%- if USE_TMA %} + q = tl.load_tensor_descriptor( + desc_q, + [(q_start * BLOCK_M).to(tl.int32), 0], + ) + {%- else %} + offs_m = q_start * BLOCK_M + tl.arange(0, BLOCK_M) + offs_k = tl.arange(0, QK_HEAD_DIM_ROUNDED) + q = load_checked_2d(Q, offs_m, offs_k, stride_qm, stride_qk, IS_DIVISIBLE, SAFE_HEAD_DIM, Q_LEN, QK_HEAD_DIM, INDEX_DTYPE) + {%- endif %} + + # ~~~~~~~~~~~~~~ normal blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # We don't know anything "special" about these blocks, so we need to apply + # both score_mod and mask_mod to it + kv_indices = KV_IDX + sparse_kv_idx_offset + kv_start = tl.load(kv_indices) * SPARSE_KV_BLOCK_SIZE # first kv block we're loading + kv_num_blocks = tl.load(KV_NUM_BLKS + sparse_kv_num_blks_offset) + block_n_end = tl.minimum(kv_num_blocks * SPARSE_KV_MULTIPLE, tl.maximum(tl.cdiv(KV_LEN, BLOCK_N), 1)) + + + # K and V pointers will be passed directly to forward_inner + + offs_n = kv_start + tl.arange(0, BLOCK_N) + + + acc, l_i, m_i = forward_inner( + {{gen_argdefs()}}, + q, K, V, + desc_k, desc_v, Q_LEN, KV_LEN, + acc, l_i, m_i, + off_zq, off_hq, offs_m[:, None], offs_n[None, :], + kv_start, + kv_indices, kv_num_blocks, + 0, block_n_end, + MATMUL_PRECISION, + stride_kk, stride_kn, stride_vn, stride_vk, + IS_FULL_BLOCKS=False, + ) + + # ~~~~~~~~~~~~~~ "full" blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # We know these blocks are guaranteed to be "full", so we don't need to + # apply mask_mod to them - only score_mod + if HAS_FULL_BLOCKS: + # FULL_KV_IDX and FULL_KV_NUM_BLKS are always contiguous. + kv_indices = FULL_KV_IDX + sparse_full_kv_idx_offset + kv_start = tl.load(kv_indices) * SPARSE_KV_BLOCK_SIZE # first kv block we're loading + kv_num_blocks = tl.load(FULL_KV_NUM_BLKS + sparse_full_kv_num_blks_offset) + block_n_end = tl.minimum(kv_num_blocks * SPARSE_KV_MULTIPLE, tl.maximum(tl.cdiv(KV_LEN, BLOCK_N), 1)) + # K and V pointers will be passed directly to forward_inner + offs_n = kv_start + tl.arange(0, BLOCK_N) + + acc, l_i, m_i = forward_inner( + {{gen_argdefs()}}, + q, K, V, + desc_k, desc_v, Q_LEN, KV_LEN, + acc, l_i, m_i, + off_zq, off_hq, offs_m[:, None], offs_n[None, :], + kv_start, + kv_indices, kv_num_blocks, + 0, block_n_end, + MATMUL_PRECISION, + stride_kk, stride_kn, stride_vn, stride_vk, + IS_FULL_BLOCKS=True, + ) + + + # [Note] Handle fully masked out rows: + # Li will be the sum(e^(-inf)) == 0.0 for masked out rows, mi will be -inf. + # We set Li to 1.0 which will result in lse/out = 0.0 | after the log(li) + mi(0.0) step + l_i = tl.where(l_i == 0.0, 1, l_i) + + acc = acc / l_i[:, None] + idx_zq = tl.program_id(1).to(INDEX_DTYPE) + idx_hq = tl.program_id(2).to(INDEX_DTYPE) + idx_m = offs_m[:, None].to(INDEX_DTYPE) + idx_d = tl.arange(0, V_HEAD_DIM_ROUNDED)[None, :].to(INDEX_DTYPE) + + mask = (idx_m < Q_LEN) & (idx_d < V_HEAD_DIM) + + tl.static_assert(acc.shape == [BLOCK_M, V_HEAD_DIM_ROUNDED]) + {{store_output(("idx_zq", "idx_hq", "idx_m", "idx_d"), "acc", "mask", val_shape=("BLOCK_M", "V_HEAD_DIM_ROUNDED"))}} + + if OUTPUT_LOGSUMEXP: + off_hz = off_zq * HQ + off_hq + l_ptrs = LSE + off_hz * Q_LEN + offs_m + lse = m_i + tl.math.log2(l_i) + if IS_DIVISIBLE: + tl.store(l_ptrs, lse) + else: + tl.store(l_ptrs, lse, mask=offs_m < Q_LEN) + + if OUTPUT_MAX: + off_hz = off_zq * HQ + off_hq + max_ptrs = MAX + off_hz * Q_LEN + offs_m + if IS_DIVISIBLE: + tl.store(max_ptrs, m_i) + else: + tl.store(max_ptrs, m_i, mask=offs_m < Q_LEN) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flex_backwards.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flex_backwards.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..c0fe550d678962e828f4581c88f75769d1f606c2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flex_backwards.py.jinja @@ -0,0 +1,844 @@ +{{def_kernel("Q", "K", "V", "LSE", "DELTA", "DO", "DQ", "DV", "KV_NUM_BLKS", "KV_IDX", "Q_NUM_BLKS", "Q_IDX", "FULL_KV_NUM_BLKS", "FULL_KV_IDX", "FULL_Q_NUM_BLKS", "FULL_Q_IDX")}} + # Sub notation for this kernel: + # + # Q: Query, K: Key, V: Value + # LSE: logsumexp (logsumexp is always stored in fp32 regardless of the input dtype) + # DELTA: Precomputed sum(OUT*DO, axis=-1) + # DO: Derivative of Output, DQ: Derivative of Query, DV: Derivative of Value + # DK: Derivative of Key, is the written to via the store_output call due to some limitations with + # inductor codegen + # M: Number of queries, N: Number of keys/values + # QK_HEAD_DIM: The dimension of the query and key embeddings + # V_HEAD_DIM: The dimension of the value embeddings + # z: Batch size, h: Number of heads, m: Number of queries or keys/values, d: Head dim + # GQA_SHARED_HEADS: number of query heads sharing one kv head in GQA setups. + # (Modifiable) Performance tuning options + # BLOCK_M1: when calculating DK & DV, iterate over BLOCK_M1 across the seqlen dim of Q in each thread block. + # BLOCK_N1: when calculating DK & DV, the thread block size across the seqlen dim of K/V. + # BLOCK_M2: when calculating DQ, the thread block size across the seqlen dim of Q. + # BLOCK_N2: when calculating DQ, iterate over BLOCK_N2 across the seqlen dim of K/V in each thread block. + # + # The following FULL_* and PARTIAL_* is defined in the block sparse mask grid, rather than the thread block grid. + # KV_NUM_BLKS: The number of KV blocks (that may or may not require masking) for each query. + # KV_IDX: The indices of KV blocks (that may or may not require masking) for each query. + # Q_NUM_BLKS: The number of Q blocks (that may or may not require masking) for each query. + # Q_IDX: The indices of Q blocks (that may or may not require masking) for each query. + # FULL_KV_NUM_BLKS: The number of fully unmasked KV blocks (so we don't need masking) for each query. + # FULL_KV_IDX: The indices of fully unmasked KV blocks (so we don't need masking) for each query. + # FULL_Q_NUM_BLKS: The number of fully unmasked Q blocks (so we don't need masking) for each query. + # FULL_Q_IDX: The indices of fully unmasked Q blocks (so we don't need masking) for each query. + + # The below are kernel options that can be applied for certain score_mods, + # or involve a numerics vs. perf tradeoff + # PRESCALE_QK: Whether to pre-scale QK by 1/sqrt(d) and change of base. Has + # about 20% more numerical error, but slightly faster. + + # Define strides of inputs + stride_qz, stride_qh, stride_qm, stride_qd = {{stride("Q")}} + stride_kz, stride_kh, stride_kn, stride_kd = {{stride("K")}} + stride_vz, stride_vh, stride_vn, stride_vd = {{stride("V")}} + stride_doz, stride_doh, stride_dom, stride_dod = {{stride("DO")}} + + stride_dqz, stride_dqh, stride_dqm, stride_dqd = {{stride("DQ")}} + stride_dvz, stride_dvh, stride_dvm, stride_dvd = {{stride("DV")}} + + ZQ = {{size("Q", 0)}} + HQ = {{size("Q", 1)}} + HKV = {{size("K", 1)}} + Q_LEN = {{size("Q", 2)}} + ZKV = {{size("K", 0)}} + KV_LEN = {{size("K", 2)}} + + MATMUL_PRECISION = Q.dtype.element_ty + + pid = tl.program_id(0).to(INDEX_DTYPE) + NUM_KV_BLOCKS = tl.cdiv(KV_LEN, BLOCK_N1) + NUM_Q_BLOCKS = tl.cdiv(Q_LEN, BLOCK_M2) + + off_zq = tl.program_id(1).to(INDEX_DTYPE) # q batch idx + off_hkv = tl.program_id(2).to(INDEX_DTYPE) # kv head idx + off_zkv = off_zq % ZKV # kv batch idx + + SPARSE_Z = {{size("KV_NUM_BLKS", 0)}} + SPARSE_HQ = {{size("KV_NUM_BLKS", 1)}} + + sparse_idx_z = off_zq % SPARSE_Z + + k_adj = (stride_kh * off_hkv + stride_kz * off_zkv).to(tl.int64) + v_adj = (stride_vh * off_hkv + stride_vz * off_zkv).to(tl.int64) + # first compute broadcasted dv of shape [Bq, Hkv, KV_LEN, V_HEAD_DIM] + # then reduce to dv of shape [Bkv, Hkv, KV_LEN, V_HEAD_DIM] + dv_adj = (stride_dvh * off_hkv + stride_dvz * off_zq).to(tl.int64) + + # offset K, V, DV pointers for batch/kv-head + K += k_adj + V += v_adj + DV += dv_adj + + RCP_LN2 = 1.44269504 + offs_k = tl.arange(0, QK_HEAD_DIM_ROUNDED) + offs_v = tl.arange(0, V_HEAD_DIM_ROUNDED) + + if pid >= NUM_KV_BLOCKS: + off_pid = pid - NUM_KV_BLOCKS + # THIS BLOCK DOES DQ + SPARSE_Q_MULTIPLE = (SPARSE_Q_BLOCK_SIZE // BLOCK_M2) + SPARSE_KV_MULTIPLE = (SPARSE_KV_BLOCK_SIZE // BLOCK_N2) + off_hq2 = off_pid // NUM_Q_BLOCKS + off_hkv * GQA_SHARED_HEADS + start_m2_block = off_pid % NUM_Q_BLOCKS + off_pid_mask = start_m2_block // SPARSE_Q_MULTIPLE + stride_kv_num_blks_h = {{stride("KV_NUM_BLKS", 1)}} + stride_kv_idx_h = {{stride("KV_IDX", 1)}} + stride_kv_idx_m = {{stride("KV_IDX", 2)}} + {%- if HAS_FULL_BLOCKS %} + stride_full_kv_num_blks_h = {{stride("FULL_KV_NUM_BLKS", 1)}} + stride_full_kv_idx_h = {{stride("FULL_KV_IDX", 1)}} + stride_full_kv_idx_m = {{stride("FULL_KV_IDX", 2)}} + {%- endif %} + + sparse_idx_hq2 = off_hq2 % SPARSE_HQ + sparse_hz_offset = sparse_idx_z * SPARSE_HQ + sparse_idx_hq2 + + sparse_kv_num_blks_offset = sparse_hz_offset * stride_kv_num_blks_h + off_pid_mask + sparse_kv_idx_offset = sparse_hz_offset * stride_kv_idx_h + off_pid_mask * stride_kv_idx_m # noqa: B950 + {%- if HAS_FULL_BLOCKS %} + sparse_full_kv_num_blks_offset = sparse_hz_offset * stride_full_kv_num_blks_h + off_pid_mask + sparse_full_kv_idx_offset = sparse_hz_offset * stride_full_kv_idx_h + off_pid_mask * stride_full_kv_idx_m # noqa: B950 + {%- endif %} + + # Offset Q, DQ, DO, DELTA & LSE. These inputs are offsetted by query heads. + q_adj2 = (stride_qh * off_hq2 + stride_qz * off_zq).to(tl.int64) + do_adj2 = (stride_doh * off_hq2 + stride_doz * off_zq).to(tl.int64) + dq_adj2 = (stride_dqh * off_hq2 + stride_dqz * off_zq).to(tl.int64) + off_chz2 = ((off_zq * HQ + off_hq2) * Q_LEN).to(tl.int64) + + Q2 = Q + q_adj2 + DO2 = DO + do_adj2 + # TODO: This does not work if DQ is not the same layout as Q (for example, + # if Q is broadcasted) + DQ2 = DQ + dq_adj2 + LSE2 = LSE + off_chz2 + DELTA2 = DELTA + off_chz2 + + dq = tl.zeros([BLOCK_M2, QK_HEAD_DIM_ROUNDED], dtype=tl.float32) + + start_m2 = start_m2_block * BLOCK_M2 + offs_m2 = start_m2 + tl.arange(0, BLOCK_M2) + + desc_q = None + desc_do = None + desc_k_dq = None + desc_v_dq = None + {%- if USE_TMA %} + desc_q = tl.make_tensor_descriptor( + base=Q2, + shape=(Q_LEN, QK_HEAD_DIM), + strides=(stride_qm, 1), + block_shape=[BLOCK_M2, QK_HEAD_DIM_ROUNDED], + ) + desc_do = tl.make_tensor_descriptor( + base=DO2, + shape=(Q_LEN, V_HEAD_DIM), + strides=(stride_dom, 1), + block_shape=[BLOCK_M2, V_HEAD_DIM_ROUNDED], + ) + desc_k_dq = tl.make_tensor_descriptor( + base=K, + shape=(KV_LEN, QK_HEAD_DIM), + strides=(stride_kn, 1), + block_shape=[BLOCK_N2, QK_HEAD_DIM_ROUNDED], + ) + desc_v_dq = tl.make_tensor_descriptor( + base=V, + shape=(KV_LEN, V_HEAD_DIM), + strides=(stride_vn, 1), + block_shape=[BLOCK_N2, V_HEAD_DIM_ROUNDED], + ) + q = tl.load_tensor_descriptor( + desc_q, + [start_m2.to(tl.int32), 0], + ) + do = tl.load_tensor_descriptor( + desc_do, + [start_m2.to(tl.int32), 0], + ) + {%- else %} + # load Q and do: they stay in SRAM throughout the inner loop. + q = load_checked_2d(Q2, offs_m2, offs_k, stride_qm, stride_qd, IS_DIVISIBLE, SAFE_HEAD_DIM, Q_LEN, QK_HEAD_DIM, INDEX_DTYPE) + do = load_checked_2d(DO2, offs_m2, offs_v, stride_dom, stride_dod, IS_DIVISIBLE, SAFE_HEAD_DIM, Q_LEN, V_HEAD_DIM, INDEX_DTYPE) + {%- endif %} + if PRESCALE_QK: + q = (q * SM_SCALE * RCP_LN2).to(MATMUL_PRECISION) + + if IS_DIVISIBLE: + Di = tl.load(DELTA2 + offs_m2) + lse = tl.load(LSE2 + offs_m2) + else: + Di = tl.load(DELTA2 + offs_m2, mask=offs_m2 < Q_LEN) + lse = tl.load(LSE2 + offs_m2, mask=offs_m2 < Q_LEN) + lse = tl.where(lse == -float("inf"), 0.0, lse) + lse = lse[:, None] + + # ~~~~~~~~~~~ fully unmasked blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # KV_IDX and KV_NUM_BLKS are always contiguous. + kv_indices = KV_IDX + sparse_kv_idx_offset + kv_start = tl.load(kv_indices) * SPARSE_KV_BLOCK_SIZE # first kv block we're loading + sparse_kv_num_blocks = tl.load(KV_NUM_BLKS + sparse_kv_num_blks_offset) + + dq = bwd_dq_inner( + {{gen_argdefs()}}, + K, V, desc_k_dq, desc_v_dq, kv_start, start_m2, + dq, q, do, Di, lse, + off_zq, off_hq2, + stride_kn, stride_kd, stride_vn, stride_vd, + kv_indices, sparse_kv_num_blocks, + MATMUL_PRECISION, + IS_FULL_BLOCKS=False, + ) + + if HAS_FULL_BLOCKS: + # ~~~~~~~~~~~ partial unmasked blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # FULL_KV_IDX and FULL_KV_NUM_BLKS are always contiguous. + kv_indices = FULL_KV_IDX + sparse_full_kv_idx_offset + kv_start = tl.load(kv_indices) * SPARSE_KV_BLOCK_SIZE # first kv block we're loading + sparse_kv_num_blocks = tl.load(FULL_KV_NUM_BLKS + sparse_full_kv_num_blks_offset) + + offs_n2 = kv_start + tl.arange(0, BLOCK_N2) + dq = bwd_dq_inner( + {{gen_argdefs()}}, + K, V, desc_k_dq, desc_v_dq, kv_start, start_m2, + dq, q, do, Di, lse, + off_zq, off_hq2, + stride_kn, stride_kd, stride_vn, stride_vd, + kv_indices, sparse_kv_num_blocks, + MATMUL_PRECISION, + IS_FULL_BLOCKS=True, + ) + + # Write back dQ. + dq_ptrs = DQ2 + offs_m2[:, None].to(INDEX_DTYPE) * stride_dqm + offs_k[None, :].to(INDEX_DTYPE) * stride_dqd + dq *= SM_SCALE + if IS_DIVISIBLE and SAFE_HEAD_DIM: + tl.store(dq_ptrs, dq) + else: + tl.store(dq_ptrs, dq, mask=(offs_m2[:, None] < Q_LEN) & (offs_k[None, :] < QK_HEAD_DIM)) + else: + # THIS BLOCK DOES DK & DV + SPARSE_Q_MULTIPLE = (SPARSE_Q_BLOCK_SIZE // BLOCK_M1) + SPARSE_KV_MULTIPLE = (SPARSE_KV_BLOCK_SIZE // BLOCK_N1) + + pid_mask = pid // SPARSE_KV_MULTIPLE + + stride_q_num_blks_h = {{stride("Q_NUM_BLKS", 1)}} + stride_q_idx_h = {{stride("Q_IDX", 1)}} + stride_q_idx_n = {{stride("Q_IDX", 2)}} + {%- if HAS_FULL_BLOCKS %} + stride_full_q_num_blks_h = {{stride("FULL_Q_NUM_BLKS", 1)}} + stride_full_q_idx_h = {{stride("FULL_Q_IDX", 1)}} + stride_full_q_idx_n = {{stride("FULL_Q_IDX", 2)}} + {%- endif %} + + + dv = tl.zeros([BLOCK_N1, V_HEAD_DIM_ROUNDED], dtype=tl.float32) + dk = tl.zeros([BLOCK_N1, QK_HEAD_DIM_ROUNDED], dtype=tl.float32) + + start_n1 = pid * BLOCK_N1 + offs_n1 = start_n1 + tl.arange(0, BLOCK_N1) + + {%- if USE_TMA %} + desc_k_dkdv = tl.make_tensor_descriptor( + base=K, + shape=(KV_LEN, QK_HEAD_DIM), + strides=(stride_kn, 1), + block_shape=[BLOCK_N1, QK_HEAD_DIM_ROUNDED], + ) + desc_v_dkdv = tl.make_tensor_descriptor( + base=V, + shape=(KV_LEN, V_HEAD_DIM), + strides=(stride_vn, 1), + block_shape=[BLOCK_N1, V_HEAD_DIM_ROUNDED], + ) + k = tl.load_tensor_descriptor( + desc_k_dkdv, + [start_n1.to(tl.int32), 0], + ) + v = tl.load_tensor_descriptor( + desc_v_dkdv, + [start_n1.to(tl.int32), 0], + ) + {%- else %} + # load K and V: they stay in SRAM throughout the inner loop. + k = load_checked_2d(K, offs_n1, offs_k, stride_kn, stride_kd, IS_DIVISIBLE, SAFE_HEAD_DIM, KV_LEN, QK_HEAD_DIM, INDEX_DTYPE) + v = load_checked_2d(V, offs_n1, offs_v, stride_vn, stride_vd, IS_DIVISIBLE, SAFE_HEAD_DIM, KV_LEN, V_HEAD_DIM, INDEX_DTYPE) + {%- endif %} + if PRESCALE_QK: + k = (k * SM_SCALE * RCP_LN2).to(MATMUL_PRECISION) + + for off_g in range(0, GQA_SHARED_HEADS): + off_hq1 = off_hkv * GQA_SHARED_HEADS + off_g + + # Offset Q, DQ, DO, DELTA & LSE. These inputs are offsetted by query heads. + q_adj1 = (stride_qh * off_hq1 + stride_qz * off_zq).to(tl.int64) + do_adj1 = (stride_doh * off_hq1 + stride_doz * off_zq).to(tl.int64) + dq_adj1 = (stride_dqh * off_hq1 + stride_dqz * off_zq).to(tl.int64) + off_chz1 = ((off_zq * HQ + off_hq1) * Q_LEN).to(tl.int64) + + Q1 = Q + q_adj1 + DO1 = DO + do_adj1 + # TODO: This does not work if DQ is not the same layout as Q (for example, + # if Q is broadcasted) + LSE1 = LSE + off_chz1 + DELTA1 = DELTA + off_chz1 + + sparse_idx_hq1 = off_hq1 % SPARSE_HQ + sparse_hz_offset = sparse_idx_z * SPARSE_HQ + sparse_idx_hq1 + + sparse_q_num_blks_offset = sparse_hz_offset * stride_q_num_blks_h + pid_mask + sparse_q_idx_offset = sparse_hz_offset * stride_q_idx_h + pid_mask * stride_q_idx_n # noqa: B950 + {%- if HAS_FULL_BLOCKS %} + sparse_full_q_num_blks_offset = sparse_hz_offset * stride_full_q_num_blks_h + pid_mask + sparse_full_q_idx_offset = sparse_hz_offset * stride_full_q_idx_h + pid_mask * stride_full_q_idx_n # noqa: B950 + {%- endif %} + + # ~~~~~~~~~~~~~~~ fully unmasked blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # Q_IDX and Q_NUM_BLKS are always contiguous. + q_indices = Q_IDX + sparse_q_idx_offset + q_start = tl.load(q_indices) * SPARSE_Q_BLOCK_SIZE # first q block we're loading + sparse_q_num_blocks = tl.load(Q_NUM_BLKS + sparse_q_num_blks_offset) + + offs_m1 = q_start + tl.arange(0, BLOCK_M1) + desc_q = None + desc_do = None + {%- if USE_TMA %} + desc_q = tl.make_tensor_descriptor( + base=Q1, + shape=(Q_LEN, QK_HEAD_DIM), + strides=(stride_qm, 1), + block_shape=[BLOCK_M1, QK_HEAD_DIM_ROUNDED], + ) + desc_do = tl.make_tensor_descriptor( + base=DO1, + shape=(Q_LEN, V_HEAD_DIM), + strides=(stride_dom, 1), + block_shape=[BLOCK_M1, V_HEAD_DIM_ROUNDED], + ) + {%- endif %} + dk, dv = bwd_dkdv_inner( + {{gen_argdefs()}}, + Q1, DO1, DELTA1, LSE1, + desc_q, desc_do, q_start, + dk, dv, k, v, + off_zq, off_hq1, offs_n1, offs_m1, + stride_qm, stride_qd, stride_dom, stride_dod, + q_indices, sparse_q_num_blocks, + MATMUL_PRECISION, + IS_FULL_BLOCKS=False, + ) + + + if HAS_FULL_BLOCKS: + # ~~~~~~~~~~~~~~~ fully unmasked blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # FULL_Q_IDX and FULL_Q_NUM_BLKS are always contiguous. + q_indices = FULL_Q_IDX + sparse_full_q_idx_offset + q_start = tl.load(q_indices) * SPARSE_Q_BLOCK_SIZE # first q block we're loading + sparse_q_num_blocks = tl.load(FULL_Q_NUM_BLKS + sparse_full_q_num_blks_offset) + + offs_m1 = q_start + tl.arange(0, BLOCK_M1) + dk, dv = bwd_dkdv_inner( + {{gen_argdefs()}}, + Q1, DO1, DELTA1, LSE1, + desc_q, desc_do, q_start, + dk, dv, k, v, + off_zq, off_hq1, offs_n1, offs_m1, + stride_qm, stride_qd, stride_dom, stride_dod, + q_indices, sparse_q_num_blocks, + MATMUL_PRECISION, + IS_FULL_BLOCKS=True, + ) + + # Write back dV and dK. + dv_ptrs = DV + offs_n1[:, None].to(INDEX_DTYPE) * stride_dvm + offs_v[None, :].to(INDEX_DTYPE) * stride_dvd + + index_n = offs_n1[:, None] + index_k = offs_k[None, :] + index_v = offs_v[None, :] + + if IS_DIVISIBLE and SAFE_HEAD_DIM: + tl.store(dv_ptrs, dv) + else: + tl.store(dv_ptrs, dv, mask=(index_n < KV_LEN) & (index_v < V_HEAD_DIM)) + + dk *= SM_SCALE + + if SAFE_HEAD_DIM: + mask = index_n < KV_LEN + else: + mask = (index_n < KV_LEN) & (index_k < QK_HEAD_DIM) + + # first compute broadcasted dk of shape [Bq, Hkv, KV_LEN, V_HEAD_DIM] + # then reduce to dk of shape [Bkv, Hkv, KV_LEN, V_HEAD_DIM] + tl.static_assert(dk.shape == [BLOCK_N1, QK_HEAD_DIM_ROUNDED]) + {{store_output(("off_zq", "off_hkv", "index_n", "index_k"), "dk", "mask", indent_width=8, val_shape=("BLOCK_N1", "QK_HEAD_DIM_ROUNDED"))}} + +@triton.jit +def bwd_dq_inner( + {{gen_argdefs()}}, + K, V, desc_k, desc_v, kv_start, start_m2, + dq, q, do, Di, lse, + off_z, off_hq, + stride_kn, stride_kd, stride_vn, stride_vd, + kv_indices, sparse_kv_num_blocks, + MATMUL_PRECISION, + IS_FULL_BLOCKS, +): + + {{gen_defines() | indent_except_first(1) }} + SPARSE_KV_MULTIPLE: tl.constexpr = (SPARSE_KV_BLOCK_SIZE // BLOCK_N2) + RCP_LN2: tl.constexpr = 1.44269504 + Q_LEN = {{size("Q", 2)}} + KV_LEN = {{size("K", 2)}} + + offs_k = tl.arange(0, QK_HEAD_DIM_ROUNDED) + offs_v = tl.arange(0, V_HEAD_DIM_ROUNDED) + + # BLOCK_M2 must be a multiple of BLOCK_N2, otherwise the code wouldn't work. + tl.static_assert(BLOCK_M2 % BLOCK_N2 == 0) + + hi = tl.minimum(sparse_kv_num_blocks * SPARSE_KV_MULTIPLE, tl.maximum(tl.cdiv(KV_LEN, BLOCK_N2), 1)) + + kv_offset = 0 + for start_n in range(0, hi): + dq = bwd_dq_block_mn( + {{gen_argdefs()}}, + dq, q, K, V, desc_k, desc_v, kv_start, kv_offset, start_m2, + do, Di, lse, Q_LEN, KV_LEN, + off_z, off_hq, offs_k, offs_v, + stride_kn, stride_kd, stride_vn, stride_vd, + kv_indices, sparse_kv_num_blocks, + MATMUL_PRECISION, RCP_LN2, + IS_FULL_BLOCKS, + ) + + # Increment pointers. + offset = get_offset_for_next_block( + start_n, kv_indices, sparse_kv_num_blocks, + SPARSE_KV_BLOCK_SIZE, SPARSE_KV_MULTIPLE, BLOCK_N2, BLOCKS_ARE_CONTIGUOUS + ) + + kv_offset += offset + + return dq + + +@triton.jit +def bwd_dq_block_mn( + {{gen_argdefs()}}, + dq, q, K, V, desc_k, desc_v, kv_start, kv_offset, start_m2, + do, Di, lse, Q_LEN, KV_LEN, + off_z, off_hq, offs_k, offs_v, + stride_kn, stride_kd, stride_vn, stride_vd, + kv_indices, sparse_kv_num_blocks, + MATMUL_PRECISION, RCP_LN2, + IS_FULL_BLOCKS, +): + {{gen_defines() | indent_except_first(1)}} + + offs_n2 = kv_start + kv_offset + tl.arange(0, BLOCK_N2) + offs_m2 = start_m2 + tl.arange(0, BLOCK_M2) + {%- if USE_TMA %} + k = tl.load_tensor_descriptor( + desc_k, + [(kv_start + kv_offset).to(tl.int32), 0], + ) + kT = tl.trans(k) + {%- else %} + kT_ptrs = K + offs_n2[None, :].to(INDEX_DTYPE) * stride_kn + offs_k[:, None].to(INDEX_DTYPE) * stride_kd + vT_ptrs = V + offs_n2[None, :].to(INDEX_DTYPE) * stride_vn + offs_v[:, None].to(INDEX_DTYPE) * stride_vd + # NB reversed order to since K is transposed + kT = load_checked_2d(kT_ptrs, offs_k, offs_n2, None, None, SAFE_HEAD_DIM, IS_DIVISIBLE, QK_HEAD_DIM, KV_LEN, INDEX_DTYPE) + {%- endif %} + qk = tl.dot(q, kT, input_precision=FLOAT32_PRECISION) + if not PRESCALE_QK: + qk *= SM_SCALE + # ~~~~~~~~~~~~~~~~~~~ Apply score modification ~~~~~~~~~~~~~~~~~~~ + pre_mod_scores = qk + n = get_bounded_indices(offs_n2[None, :], KV_LEN if not IS_DIVISIBLE else None) + # The boundary check is done for the outer loop, but here it's possible since we're iterating across N dim + # that the M reads out of bounds for the PIDS spanning the Q_LEN boundary + m = get_bounded_indices(offs_m2[:, None], Q_LEN if not IS_DIVISIBLE else None) + + {{ modification( + subgraph_number=0, + output_name="post_mod_scores", + score="qk", + b="off_z", + h="off_hq", + m="m", + n="n", + out="qk", + input_shapes={ + "score": ("BLOCK_M2", "BLOCK_N2"), + "m": ("BLOCK_M2", "1"), + "n": ("1", "BLOCK_N2"), + }, + input_dtypes={ + "b": "index", + "h": "index", + "m": "index", + "n": "index", + } + ) | indent_except_first(1) }} + + + {# Note: Selective masking DQ + We load elements beyond KV_LEN w/ zero, some score mods may convert these elements to NaN + Example: lambda x, *_: 1 / score, this NaN would propagate regardless of other masking + We only need to do this on the m1 dim since these elements take part in the final reduction + for DQ #} + if not IS_DIVISIBLE: + post_mod_scores = tl.where(offs_n2[None, :] < KV_LEN, post_mod_scores, float("-inf")) + + if not IS_FULL_BLOCKS: + {{ modification( + subgraph_number=2, + output_name="mask_mod_output", + score="qk", + b="off_z", + h="off_hq", + m="m", + n="n", + input_shapes={ + "score": ("BLOCK_M2", "BLOCK_N2"), + "m": ("BLOCK_M2", "1"), + "n": ("1", "BLOCK_N2"), + }, + input_dtypes={ + "b": "index", + "h": "index", + "m": "index", + "n": "index", + } + ) | indent_except_first(2) }} + + # apply mask for partial masked block + post_mod_scores = tl.where(mask_mod_output, post_mod_scores, float("-inf")) + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if not PRESCALE_QK: + post_mod_scores *= RCP_LN2 + p = tl.math.exp2(post_mod_scores - lse) + # Compute dP and dS. + # NB reversed order to since V is transposed + {%- if USE_TMA %} + v = tl.load_tensor_descriptor( + desc_v, + [(kv_start + kv_offset).to(tl.int32), 0], + ) + vT = tl.trans(v) + {%- else %} + vT = load_checked_2d(vT_ptrs, offs_v, offs_n2, None, None, SAFE_HEAD_DIM, IS_DIVISIBLE, V_HEAD_DIM, KV_LEN, INDEX_DTYPE) + {%- endif %} + dp = tl.dot(do, vT, input_precision=FLOAT32_PRECISION) + ds = p * (dp - Di[:, None]) + # ~~~~~~~~~~~~~~~~~~~ Apply joint modification ~~~~~~~~~~~~~~~~~~~ + {{ modification( + subgraph_number=1, + output_name = "grad_scores", + score="pre_mod_scores", + b="off_z", + h="off_hq", + m="m", + n="n", + grad_score_mod="ds", + input_shapes={ + "score": ("BLOCK_M2", "BLOCK_N2"), + "grad_score_mod": ("BLOCK_M2", "BLOCK_N2"), + "m": ("BLOCK_M2", "1"), + "n": ("1", "BLOCK_N2"), + }, + input_dtypes={ + "b": "index", + "h": "index", + "m": "index", + "n": "index", + } + ) | indent_except_first(1) }} + {# See Note Selective masking DQ #} + if not IS_DIVISIBLE: + grad_scores = tl.where(offs_n2[None, :] < KV_LEN, grad_scores, 0.0) + + # ~~~~~~~~~~~~~~~~~~~ Apply other buffer grad writes ~~~~~~~~~~~~~ + if WRITE_DQ: + scatter_mask = (offs_m2[:, None] < Q_LEN ) & (offs_n2[None, :] < KV_LEN) + {{ modification( + subgraph_number=3, + output_name=None, + mask="scatter_mask", + input_shapes={ + "score": ("BLOCK_M2", "BLOCK_N2"), + "grad_score_mod": ("BLOCK_M2", "BLOCK_N2"), + "m": ("BLOCK_M2", "1"), + "n": ("1", "BLOCK_N2"), + "b": ("1", "1"), + "h": ("1", "1"), + }, + input_dtypes={ + "b": "index", + "h": "index", + "m": "index", + "n": "index", + }, + score="pre_mod_scores", + b="off_z", + h="off_hq", + m="m", + n="n", + grad_score_mod="ds" + ) | indent_except_first(2) }} + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ds = grad_scores + + if not IS_FULL_BLOCKS: + # (grads) apply mask for partially unmasked block + ds = tl.where(mask_mod_output, ds, 0.0) + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ds = ds.to(MATMUL_PRECISION) + # Compute dQ. + dq += tl.dot(ds, tl.trans(kT), input_precision=FLOAT32_PRECISION) + + return dq + + +@triton.jit +def bwd_dkdv_inner( + {{gen_argdefs()}}, + Q, DO, DELTA, LSE, # pointers + desc_q, desc_do, q_start, + dk, dv, k, v, + off_z, off_hq, offs_n1, offs_m1, + stride_qm, stride_qd, stride_dom, stride_dod, + q_indices, sparse_q_num_blocks, + MATMUL_PRECISION, + IS_FULL_BLOCKS, +): + {{gen_defines() | indent_except_first(1) }} + SPARSE_Q_MULTIPLE: tl.constexpr = (SPARSE_Q_BLOCK_SIZE // BLOCK_M1) + RCP_LN2: tl.constexpr = 1.44269504 + Q_LEN = {{size("Q", 2)}} + KV_LEN = {{size("K", 2)}} + + offs_k = tl.arange(0, QK_HEAD_DIM_ROUNDED) + offs_v = tl.arange(0, V_HEAD_DIM_ROUNDED) + + # BLOCK_N1 must be a multiple of BLOCK_M1, otherwise the code wouldn't work. + tl.static_assert(BLOCK_N1 % BLOCK_M1 == 0) + + # The minimum is needed to handle the case where we run with a super large + # SPARSE_BLOCK_SIZE (i.e. no block-mask!) + hi = tl.minimum(sparse_q_num_blocks * SPARSE_Q_MULTIPLE, tl.maximum(tl.cdiv(Q_LEN, BLOCK_M1), 1)) + + offset_block = 0 + for start_m in range(0, hi): + dk, dv = bwd_dkdv_block_mn( + {{gen_argdefs()}}, + dk, dv, Q, k, v, DO, DELTA, LSE, + desc_q, desc_do, q_start, offset_block, Q_LEN, KV_LEN, + off_z, off_hq, offs_n1, offs_m1, offs_k, offs_v, + stride_qm, stride_qd, stride_dom, stride_dod, + q_indices, sparse_q_num_blocks, + MATMUL_PRECISION, RCP_LN2, + IS_FULL_BLOCKS, + ) + # Increment pointers. + offset = get_offset_for_next_block( + start_m, q_indices, sparse_q_num_blocks, + SPARSE_Q_BLOCK_SIZE, SPARSE_Q_MULTIPLE, BLOCK_M1, BLOCKS_ARE_CONTIGUOUS + ) + offs_m1 += offset + offset_block += offset + + return dk, dv + + +@triton.jit +def bwd_dkdv_block_mn( + {{gen_argdefs()}}, + dk, dv, Q, k, v, DO, DELTA, LSE, + desc_q, desc_do, q_start, offset, Q_LEN, KV_LEN, + off_z, off_hq, offs_n1, offs_m1, offs_k, offs_v, + stride_qm, stride_qd, stride_dom, stride_dod, + q_indices, sparse_q_num_blocks, + MATMUL_PRECISION, RCP_LN2, + IS_FULL_BLOCKS, +): + {{gen_defines() | indent_except_first(1) }} + + {%- if USE_TMA %} + q = tl.load_tensor_descriptor( + desc_q, + [(q_start + offset).to(tl.int32), 0], + ) + qT = tl.trans(q) + {%- else %} + qT_ptrs = Q + offs_m1[None, :].to(INDEX_DTYPE) * stride_qm + offs_k[:, None].to(INDEX_DTYPE) * stride_qd + do_ptrs = DO + offs_m1[:, None].to(INDEX_DTYPE) * stride_dom + offs_v[None, :].to(INDEX_DTYPE) * stride_dod + # NB reversed order since Q is transposed + qT = load_checked_2d(qT_ptrs, offs_k, offs_m1, None, None, SAFE_HEAD_DIM, IS_DIVISIBLE, QK_HEAD_DIM, Q_LEN, INDEX_DTYPE) + {%- endif %} + # Load LSE before computing qk to reduce pipeline stall. + if IS_DIVISIBLE: + lse = tl.load(LSE + offs_m1) + else: + lse = tl.load(LSE + offs_m1, mask=offs_m1 < Q_LEN) + lse = tl.where(lse == -float("inf"), 0.0, lse) + qkT = tl.dot(k, qT, input_precision=FLOAT32_PRECISION) + if not PRESCALE_QK: + qkT *= SM_SCALE + # ~~~~~~~~~~~~~~~~~~~ Apply score modification ~~~~~~~~~~~~~~~~~~~ + m = get_bounded_indices(offs_m1[None, :], Q_LEN if not IS_DIVISIBLE else None) + # The boundary check is done for the outer loop, but here it's possible since we're iterating across M dim + # that the n reads out of bounds for the PIDS spanning the KV_LEN boundary + n = get_bounded_indices(offs_n1[:, None], KV_LEN if not IS_DIVISIBLE else None) + + pre_mod_scores = qkT + {{ modification( + subgraph_number=0, + output_name="post_mod_scores", + score="qkT", + b="off_z", + h="off_hq", + m="m", + n="n", + out="qkT", + input_shapes={ + "score": ("BLOCK_N1", "BLOCK_M1"), + "m": ("1", "BLOCK_M1"), + "n": ("BLOCK_N1", "1"), + }, + input_dtypes={ + "b": "index", + "h": "index", + "m": "index", + "n": "index", + } + ) | indent_except_first(1) }} + + {# Note: Selective masking DK/DV + We load elements beyond Q_LEN w/ zero, some score mods may convert these elements to NaN + Example: lambda x, *_: 1 / score, this NaN would propagate regardless of other masking + We only need to do this on the m1 dim since these elements take part in the final reduction + for DK/DV #} + if not IS_DIVISIBLE: + post_mod_scores = tl.where(offs_m1[None, :] < Q_LEN, post_mod_scores, float("-inf")) + + if not IS_FULL_BLOCKS: + {{ modification( + subgraph_number=2, + output_name="mask_mod_output", + b="off_z", + h="off_hq", + m="m", + n="n", + input_shapes={ + "m": ("1", "BLOCK_M1"), + "n": ("BLOCK_N1", "1"), + }, + input_dtypes={ + "b": "index", + "h": "index", + "m": "index", + "n": "index", + } + ) | indent_except_first(2) }} + # (grads) apply mask for fully masked block + post_mod_scores = tl.where(mask_mod_output, post_mod_scores, float("-inf")) + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + if not PRESCALE_QK: + post_mod_scores *= RCP_LN2 + pT = tl.math.exp2(post_mod_scores - lse[None, :]) + {%- if USE_TMA %} + do = tl.load_tensor_descriptor( + desc_do, + [(q_start + offset).to(tl.int32), 0], + ) + {%- else %} + do = load_checked_2d(do_ptrs, offs_m1, offs_v, None, None, IS_DIVISIBLE, SAFE_HEAD_DIM, Q_LEN, V_HEAD_DIM, INDEX_DTYPE) + {%- endif %} + # Compute dV. + ppT = pT + dv += tl.dot(ppT.to(MATMUL_PRECISION), do, input_precision=FLOAT32_PRECISION) + if IS_DIVISIBLE: + Di = tl.load(DELTA + offs_m1) + else: + Di = tl.load(DELTA + offs_m1, mask=offs_m1 < Q_LEN) + # Compute dP and dS. + dpT = tl.dot(v, tl.trans(do), input_precision=FLOAT32_PRECISION) + dsT = pT * (dpT - Di[None, :]) + # ~~~~~~~~~~~~~~~~~~~ Apply joint modification ~~~~~~~~~~~~~~~~~~~ + {{ modification( + subgraph_number=1, + output_name = "grad_scores", + score="pre_mod_scores", + b="off_z", + h="off_hq", + m="m", + n="n", + grad_score_mod="dsT", + input_shapes={ + "score": ("BLOCK_N1", "BLOCK_M1"), + "grad_score_mod": ("BLOCK_N1", "BLOCK_M1"), + "m": ("1", "BLOCK_M1"), + "n": ("BLOCK_N1", "1"), + }, + input_dtypes={ + "b": "index", + "h": "index", + "m": "index", + "n": "index", + } + ) | indent_except_first(1) }} + + {# See Note: Selective masking DK/DV#} + if not IS_DIVISIBLE: + grad_scores = tl.where(offs_m1[None, :] < Q_LEN, grad_scores, 0.0) + + # ~~~~~~~~~~~~~~~~~~~ Apply other buffer grad writes ~~~~~~~~~~~~~ + if not WRITE_DQ: + idx_b = off_z + idx_h = off_hq + idx_m = m + idx_n = n + scatter_mask = (offs_m1[None, :] < Q_LEN) & (offs_n1[:, None] < KV_LEN) + {{ modification( + subgraph_number=3, + output_name=None, + mask="scatter_mask", + input_shapes={ + "score": ("BLOCK_N1", "BLOCK_M1"), + "grad_score_mod": ("BLOCK_N1", "BLOCK_M1"), + "m": ("1", "BLOCK_M1"), + "n": ("BLOCK_N1", "1"), + "b": ("1", "1"), + "h": ("1", "1"), + }, + input_dtypes={ + "b": "index", + "h": "index", + "m": "index", + "n": "index", + }, + score="pre_mod_scores", + b="idx_b", + h="idx_h", + m="idx_m", + n="idx_n", + grad_score_mod="dsT" + ) | indent_except_first(2) }} + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + dsT = grad_scores + if not IS_FULL_BLOCKS: + # (grads) apply mask for partially unmasked block + dsT = tl.where(mask_mod_output, dsT, 0.0) + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + dk += tl.dot(dsT.to(MATMUL_PRECISION), tl.trans(qT), input_precision=FLOAT32_PRECISION) + + return dk, dv diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flex_decode.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flex_decode.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..03b8c4af8ff9a2b561d2221cbd49a1a9bff1f747 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/flex_decode.py.jinja @@ -0,0 +1,243 @@ + {{def_kernel("Q", "K", "V", "M", "L", "KV_NUM_BLKS", "KV_IDX", "FULL_KV_NUM_BLKS", "FULL_KV_IDX")}} + # Sub notation for this kernel: + # Q: Query, K: Key, V: Value + # reduction buffers: M rowmax across local KV split, L local sumexp across local KV split + # M: Number of queries, N: Number of keys/values + # QK_HEAD_DIM: The dimension of the query and key embeddings + # V_HEAD_DIM: The dimension of the value embeddings + # BLOCK_M, QK_HEAD_DIM: M, and D dimension are always assigned to the same block + # z: Batch size, h: Number of heads, m: Number of queries per head, k: Number of keys per head t: Number of kv splits + # (Modifiable) Config options: + # SPLIT_KV: number of blocks K & V are split into + # TILE_KV: length of each local KV split + # BLOCK_M: block size that Q is padded along seqlen dim. + # BLOCK_N: block size of K & V along N dimension. + # GQA_SHARED_HEADS: number of query heads sharing one kv head in GQA setups. + # + # change of base out of the loop + # ROWS_GUARANTEED_SAFE: Is it guaranteed that at least one value in each row + # is not masked out? If so, we can skip an extra safety check + # SAFE_M_BOUNDARY: Is Q seqlen a multiple of BLOCK_M? If so, we can skip an extra boundary check for loading query. + # SAFE_N_BOUNDARY: Is KV seqlen a multiple of BLOCK_N? If so, we can skip an extra boundary check for loading key/value. + + # PRESCALE_QK: Whether to pre-scale QK by 1/sqrt(d) and change of base. + # + # SPARSE_KV_BLOCK_SIZE: sparse mask block size along KV seqlen dim. + # KV_NUM_BLKS: The number of KV blocks (that may or may not require masking) for each query. + # KV_IDX: The indices of KV blocks (that may or may not require masking) for each query. + # + # + # Output: ACC output accumulated across local KV split. + + tl.static_assert(SPARSE_KV_BLOCK_SIZE >= BLOCK_N and SPARSE_KV_BLOCK_SIZE % BLOCK_N == 0) + + # Define Q Strides + stride_qz, stride_qh, stride_qg, stride_qm, stride_qk = {{stride("Q")}} + stride_kz, stride_kh, stride_kn, stride_kk = {{stride("K")}} + stride_vz, stride_vh, stride_vn, stride_vk = {{stride("V")}} + stride_mz, stride_mt, stride_mh, stride_mm = {{stride("M")}} + stride_lz, stride_lt, stride_lh, stride_lm = {{stride("L")}} + + + Z = {{size("Q", 0)}} + ZKV = {{size("K", 0)}} + HKV = {{size("Q", 1)}} + G: tl.constexpr = GQA_SHARED_HEADS + HQ = HKV * G + Q_LEN = {{size("Q", 3)}} + KV_LEN = {{size("K", 2)}} + + MATMUL_PRECISION = Q.dtype.element_ty + + NUM_BLOCK_M = tl.cdiv(Q_LEN * G, BLOCK_M) + + off_block_m = tl.program_id(0).to(INDEX_DTYPE) + + off_z = tl.program_id(1).to(INDEX_DTYPE) // HKV + off_zkv = off_z % ZKV + off_hkv = tl.program_id(1).to(INDEX_DTYPE) % HKV + off_t = tl.program_id(2).to(INDEX_DTYPE) + + q_offset = off_z * stride_qz + off_hkv * stride_qh + k_offset = off_zkv * stride_kz + off_hkv * stride_kh + v_offset = off_zkv * stride_vz + off_hkv * stride_vh + + K = K + k_offset + V = V + v_offset + + SPARSE_Z = {{size("KV_NUM_BLKS", 0)}} + SPARSE_HQ = {{size("KV_NUM_BLKS", 1)}} + + sparse_idx_z = off_z % SPARSE_Z + sparse_idx_h = off_hkv % SPARSE_HQ + + SPARSE_KV_MULTIPLE: tl.constexpr = (SPARSE_KV_BLOCK_SIZE // BLOCK_N) + SPARSE_KV_BLOCK_CNT = tl.cdiv(KV_LEN, SPARSE_KV_BLOCK_SIZE) + + # initialize pointer to m and l + m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") + l_i = tl.zeros([BLOCK_M], dtype=tl.float32) + acc = tl.zeros([BLOCK_M, V_HEAD_DIM_ROUNDED], dtype=tl.float32) + + # initialize offsets + tl.device_assert(BLOCK_M % G == 0) + BLOCK_M_PER_HQ: tl.constexpr = BLOCK_M // G + off_g = tl.arange(0, G) # [G] + offs_g = tl.ravel(tl.broadcast_to(off_g[:, None], [G, BLOCK_M_PER_HQ])) # [BLOCK_M] + offs_hq = offs_g + off_hkv * G + off_m = tl.arange(0, BLOCK_M_PER_HQ) + off_block_m * BLOCK_M_PER_HQ + offs_m = tl.ravel(tl.broadcast_to(off_m[None, :], [G, BLOCK_M_PER_HQ])) # [BLOCK_M] + offs_d = tl.arange(0, QK_HEAD_DIM_ROUNDED) + offs_vd = tl.arange(0, V_HEAD_DIM_ROUNDED) + + # Get HZ offsets for KV_NUM_BLKS and KV_IDX + sparse_idx_m = off_block_m * BLOCK_M_PER_HQ // SPARSE_Q_BLOCK_SIZE + stride_block_z, stride_block_h, stride_block_row = {{stride("KV_NUM_BLKS")}} + sparse_block_zhm_offset = sparse_idx_z * stride_block_z + sparse_idx_h * stride_block_h + sparse_idx_m * stride_block_row + stride_kv_z, stride_kv_h, stride_kv_row, stride_kv_col = {{stride("KV_IDX")}} + sparse_idx_zhm_offset = sparse_idx_z * stride_kv_z + sparse_idx_h * stride_kv_h + sparse_idx_m * stride_kv_row + + q_range = stride_qg * off_g[:, None, None] + stride_qm * off_m[None, :, None] + stride_qk * offs_d[None, None, :] + + if not SAFE_M_BOUNDARY and not SAFE_HEAD_DIM: + q = tl.load(Q + q_offset + q_range, mask=(offs_d[None, None, :] < QK_HEAD_DIM) & (off_m[None, :, None] < Q_LEN)) + elif SAFE_M_BOUNDARY and not SAFE_HEAD_DIM: + q = tl.load(Q + q_offset + q_range, mask=offs_d[None, None, :] < QK_HEAD_DIM) + elif not SAFE_M_BOUNDARY and SAFE_HEAD_DIM: + q = tl.load(Q + q_offset + q_range, mask=off_m[None, :, None] < Q_LEN) + else: + q = tl.load(Q + q_offset + q_range) + + q = tl.reshape(q, [BLOCK_M, QK_HEAD_DIM_ROUNDED]) + + + # ~~~~~~~~~~~~~~ normal blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # find first kv block we are loading and the number of blocks we are loading + # Offset the kv_indices tensor by the correct batch and head + kv_indices = KV_IDX + sparse_idx_zhm_offset + kv_num_blocks = tl.load(KV_NUM_BLKS + sparse_block_zhm_offset) + + # Make sure each split is a multiple of BLOCK_N + if HAS_FULL_BLOCKS: + # TODO do the optimization as partial blocks once vllm is + # able to pass in full blocks: + # https://github.com/vllm-project/vllm/blob/61249b177de1566027fc74e9b51b45a4c973eb47/vllm/v1/attention/backends/flex_attention.py#L615-L616 + TILE_KV_OG = tl.cdiv(KV_LEN, SPLIT_KV) + else: + TILE_KV_OG = tl.cdiv(kv_num_blocks * SPARSE_KV_BLOCK_SIZE, SPLIT_KV) + TILE_KV = tl.cdiv(TILE_KV_OG, BLOCK_N) * BLOCK_N + TILE_KV_MULTIPLE: tl.constexpr = (TILE_KV // BLOCK_N) + + # Calculate KV blocks that belong to this CTA. + block_n_start = off_t * TILE_KV_MULTIPLE # n_offset inside sparse block + block_n_end = block_n_start + TILE_KV_MULTIPLE # end BLOCK_N + + MAX_KV_IDX = {{size("KV_IDX", -1)}} + indices_idx = (block_n_start // SPARSE_KV_MULTIPLE) % (MAX_KV_IDX) + off_n_block_in_sparse = block_n_start % SPARSE_KV_MULTIPLE + off_n = tl.load(kv_indices + indices_idx) * SPARSE_KV_BLOCK_SIZE + off_n_block_in_sparse * BLOCK_N + # first kv block we're loading + + # last valid block according to sparse mask + block_n_last_valid = tl.minimum(kv_num_blocks * SPARSE_KV_MULTIPLE, tl.maximum(tl.cdiv(KV_LEN, BLOCK_N), 1)) + + offs_n = tl.arange(0, BLOCK_N) + off_n + + desc_k = None + desc_v = None + {%- if USE_TMA %} + desc_k = tl.make_tensor_descriptor( + base=K, + shape=[KV_LEN, QK_HEAD_DIM], + strides=[stride_kn, 1], + block_shape=[BLOCK_N, QK_HEAD_DIM_ROUNDED], + ) + + desc_v = tl.make_tensor_descriptor( + base=V, + shape=[KV_LEN, V_HEAD_DIM], + strides=[stride_vn, 1], + block_shape=[BLOCK_N, V_HEAD_DIM_ROUNDED], + ) + {%- endif %} + + acc, l_i, m_i = forward_inner( + {{gen_argdefs()}}, + q, K, V, desc_k, desc_v, Q_LEN, KV_LEN, + # accumulatd values + acc, l_i, m_i, + #offsets + off_z, offs_hq[:, None], offs_m[:, None], offs_n[None, :], + off_n, + #block sparse data + kv_indices, kv_num_blocks, + block_n_start, block_n_end if block_n_end <= block_n_last_valid else block_n_last_valid, + MATMUL_PRECISION, + stride_kk, stride_kn, stride_vn, stride_vk, + IS_FULL_BLOCKS=False, + ) + + + # ~~~~~~~~~~~~~~ "full" blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # We know these blocks are guaranteed to be "full", so we don't need to + # apply mask_mod to them - only score_mod + if HAS_FULL_BLOCKS: + kv_indices = FULL_KV_IDX + sparse_idx_zhm_offset + kv_num_blocks = tl.load(FULL_KV_NUM_BLKS + sparse_block_zhm_offset) + # Assign full block in a reverse order for off_t. Prioritize the last CTA. + block_n_start = (SPLIT_KV - off_t - 1) * TILE_KV_MULTIPLE + block_n_end = block_n_start + TILE_KV_MULTIPLE + indices_idx = (block_n_start // SPARSE_KV_MULTIPLE) % (MAX_KV_IDX) + off_n_block_in_sparse = block_n_start % SPARSE_KV_MULTIPLE + off_n = tl.load(kv_indices + indices_idx) * SPARSE_KV_BLOCK_SIZE + off_n_block_in_sparse * BLOCK_N + + # last valid block according to sparse mask + block_n_last_valid = tl.minimum(kv_num_blocks * SPARSE_KV_MULTIPLE, tl.maximum(tl.cdiv(KV_LEN, BLOCK_N), 1)) + + offs_n = tl.arange(0, BLOCK_N) + off_n + + acc, l_i, m_i = forward_inner( + {{gen_argdefs()}}, + q, K, V, desc_k, desc_v, Q_LEN, KV_LEN, + # accumulatd values + acc, l_i, m_i, + #offsets + off_z, offs_hq[:, None], offs_m[:, None], offs_n[None, :], + off_n, + #block sparse data + kv_indices, kv_num_blocks, + block_n_start, block_n_end if block_n_end <= block_n_last_valid else block_n_last_valid, + MATMUL_PRECISION, + stride_kk, stride_kn, stride_vn, stride_vk, + IS_FULL_BLOCKS=True, + ) + + m_offset = off_t * stride_mt + off_z * stride_mz + l_offset = off_t * stride_lt + off_z * stride_lz + + ml_h_offsets = off_hkv * G + off_g[:, None] + ml_m_offsets = off_m[None, :] + m_ptrs = M + m_offset + ml_h_offsets * stride_mh + ml_m_offsets * stride_mm + l_ptrs = L + l_offset + ml_h_offsets * stride_lh + ml_m_offsets * stride_lm + + # Store output, logsumexp and rowmax for cross CTA reduction. (all in float32, even when input data are in fp16) + m_i = m_i.reshape(G, BLOCK_M_PER_HQ) + l_i = l_i.reshape(G, BLOCK_M_PER_HQ) + if SAFE_M_BOUNDARY: + tl.store(m_ptrs, m_i) + tl.store(l_ptrs, l_i) + else: + ml_mask = ml_m_offsets < Q_LEN + tl.store(m_ptrs, m_i, mask=ml_mask) + tl.store(l_ptrs, l_i, mask=ml_mask) + + # -- store output + idx_z = off_z + idx_t = off_t + idx_hq = off_hkv*G + off_g[:, None, None] + idx_m = off_m[None, :, None] + idx_d = offs_vd[None, None, :] + + mask = (idx_m < Q_LEN) & (idx_d < V_HEAD_DIM) + acc = acc.reshape(G, BLOCK_M_PER_HQ, V_HEAD_DIM_ROUNDED) + {{store_output(("idx_z", "idx_t", "idx_hq", "idx_m", "idx_d"), "acc", "mask", val_shape=("GQA_SHARED_HEADS", "BLOCK_M_PER_HQ", "V_HEAD_DIM_ROUNDED"))}} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/utilities.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/utilities.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..8a3453c312bb24144a2aab7bb2e48d7e8dc41076 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex/templates/utilities.py.jinja @@ -0,0 +1,60 @@ + + +# Utility triton funcs +@triton.jit +def get_offset_for_next_block( + loop_iter, col_indices, total_blocks, + SPARSE_BLOCK, SPARSE_BLOCK_MULTIPLE, BLOCK, + BLOCKS_ARE_CONTIGUOUS: tl.constexpr +): + if BLOCKS_ARE_CONTIGUOUS: + return BLOCK + cur_block_idx = loop_iter // SPARSE_BLOCK_MULTIPLE + cur_block = tl.load(col_indices + cur_block_idx, eviction_policy="evict_last") + next_block = tl.load(col_indices + cur_block_idx + 1, eviction_policy="evict_last", mask=cur_block_idx + 1 < total_blocks) + needs_jump = (loop_iter + 1) % SPARSE_BLOCK_MULTIPLE == 0 + jump_to_block = (next_block - cur_block ) * SPARSE_BLOCK - (SPARSE_BLOCK_MULTIPLE - 1) * BLOCK + offset = jump_to_block * needs_jump + (1 - needs_jump) * BLOCK + return offset + +@triton.jit +def get_bounded_indices(indices, max_len=None): + return indices % max_len if max_len is not None else indices + +@triton.jit +def load_checked_block(block_ptr, IS_DIVISIBLE: tl.constexpr, SAFE_HEAD_DIM: tl.constexpr): + if IS_DIVISIBLE and SAFE_HEAD_DIM: + return tl.load(block_ptr) + elif IS_DIVISIBLE and not SAFE_HEAD_DIM: + return tl.load(block_ptr, boundary_check=(1,), padding_option="zero") + elif not IS_DIVISIBLE and SAFE_HEAD_DIM: + return tl.load(block_ptr, boundary_check=(0,), padding_option="zero") + else: + return tl.load(block_ptr, boundary_check=(0, 1), padding_option="zero") + +@triton.jit +def load_checked_2d( + ptr, + offs_m, + offs_n, + stride_m, + stride_n, + IS_DIVISIBLE_M: tl.constexpr, + IS_DIVISIBLE_N: tl.constexpr, + M_LEN: tl.constexpr, + N_LEN: tl.constexpr, + INDEX_DTYPE: tl.constexpr, +): + # Calculate final pointer if strides are provided + if stride_m is not None and stride_n is not None: + ptr = ptr + offs_m[:, None].to(INDEX_DTYPE) * stride_m + offs_n[None, :].to(INDEX_DTYPE) * stride_n + + # Handle all masking cases + if not IS_DIVISIBLE_M and not IS_DIVISIBLE_N: + return tl.load(ptr, mask=(offs_m[:, None] < M_LEN) & (offs_n[None, :] < N_LEN), other=0.0) + elif IS_DIVISIBLE_M and not IS_DIVISIBLE_N: + return tl.load(ptr, mask=(offs_n[None, :] < N_LEN), other=0.0) + elif not IS_DIVISIBLE_M and IS_DIVISIBLE_N: + return tl.load(ptr, mask=(offs_m[:, None] < M_LEN), other=0.0) + else: # Both divisible + return tl.load(ptr) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4cc19e904da85ecf7923217bc2fc6f7b5ac38a6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/constraints.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/constraints.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f517c132861e5a70cf7b5c90d28446a3b6eeb761 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/constraints.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/debug.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/debug.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e181866229f785d67a8a95708cb76927a2c87fc7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/debug.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/fx_cutedsl_codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/fx_cutedsl_codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..812df7d29c62f26c9fee0cfb07a978b5bf100b96 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/fx_cutedsl_codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/lowering.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/lowering.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebaaf9e4fc3ab3f024c2ea0f7ae2b896bf77813d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/lowering.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/quack_reductions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/quack_reductions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2f751783f11aa2042ae42c6f99dc9860ec091e6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/quack_reductions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/runtime.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/runtime.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e159cd9ae34dce3e3f5b4f2850ab2bc4bdd259fe Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/runtime.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26660d7a6fb42ebfcdad468231a7a5571cc2e8b5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/__pycache__/template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/constraints.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..1446cf738a6ff5336573ea66ebbf852035fde6cb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/constraints.py @@ -0,0 +1,504 @@ +# mypy: allow-untyped-defs +"""Shared FlexGEMM local-reduce geometry, constants, and validation helpers.""" + +import dataclasses +from collections.abc import Sequence +from typing import Any, Final + +from torch._inductor.kernel.gemm_epilogue import GemmReductionGeometry +from torch._inductor.kernel.gemm_epilogue_utils import ( + statically_known, + statically_known_shape_equal, +) + + +LOCAL_REDUCE_FEED_MAIN_ARG_NAME: Final = "local_reduce0" +LOCAL_REDUCE_COMBINE_FN_SUFFIX: Final = "_local_reduce_combine_fn" +LOCAL_REDUCE_FINALIZE_FN_SUFFIX: Final = "_local_reduce_finalize_fn" +LOCAL_REDUCE_COMBINE_KEY_SUFFIX: Final = ":local_reduce_combine" +LOCAL_REDUCE_FINALIZE_KEY_SUFFIX: Final = ":local_reduce_finalize" + + +# The physical feed-main path currently reduces only within one lane-layout M +# group; cross-warp M stitching needs the two-phase/replay path used by +# compressed aux reductions. Axis-1 feeds whose groups fit in one TensorSSA +# fragment lower as plain generated TensorSSA without a feed plan. +LOCAL_REDUCE_FRAGMENT_WIDTH = 32 +LOCAL_REDUCE_FEED_MAIN_AXIS_ERROR = ( + "FlexGEMM local-reduce feed-main currently supports only axis 0" +) +LOCAL_REDUCE_FEED_MAIN_SAME_WARP_ERROR = ( + "FlexGEMM local-reduce feed-main currently supports only same-warp axis-0 " + f"groups <= {LOCAL_REDUCE_FRAGMENT_WIDTH}" +) +LOCAL_REDUCE_FEED_MAIN_AXIS1_FRAGMENT_ERROR = ( + "FlexGEMM local-reduce feed-main for axis-1 groups larger than one " + "TensorSSA fragment is not supported yet" +) +LOCAL_REDUCE_DIVISIBLE_SHAPE_ERROR = ( + "local_reduce_group must divide the selected FlexGEMM output dimension" +) +LOCAL_REDUCE_GROUP_POSITIVE_ERROR = "local_reduce_group must be positive" +LOCAL_REDUCE_AXIS_ERROR = "local_reduce_axis must be 0 or 1" +LOCAL_REDUCE_TENSORSSA_GROUP_SIZE_ERROR = ( + "FlexGEMM local reductions require group size greater than 1" +) +LOCAL_REDUCE_TENSORSSA_FRAGMENT_MULTIPLE_ERROR = ( + "FlexGEMM local reductions larger than TensorSSA fragment width 32 " + "require group size to be a multiple of 32" +) +LOCAL_REDUCE_TENSORSSA_FRAGMENT_DIVISIBLE_ERROR = ( + "FlexGEMM local reductions require group size to divide TensorSSA fragment width 32" +) +LOCAL_REDUCE_PARTIAL_OUTPUT_CONTRACT_ERROR = ( + "unsupported FlexGEMM epilogue partial-output contract: FlexGEMM does not " + "support this local-reduce output contract yet. Please file an issue with " + "the FlexGEMM epilogue expression." +) +LOCAL_REDUCE_MIXED_GROUPED_LAYOUT_ERROR = ( + "FlexGEMM local reductions do not support mixing grouped TensorSSA " + "values with different grouped layouts" +) +LOCAL_REDUCE_DENSE_MM_SCOPE_ERROR = ( + "FlexGEMM local reductions currently support only aten.mm" +) +LOCAL_REDUCE_C_ALPHA_BETA_ERROR = ( + "FlexGEMM local reductions cannot be combined with C/alpha/beta yet" +) +LOCAL_REDUCE_SWAP_AB_ERROR = ( + "FlexGEMM local reductions do not support swap_ab configs yet" +) +LOCAL_REDUCE_AUX_TENSORSSA_ERROR = ( + "FlexGEMM local-reduce aux output must be produced by a grouped TensorSSA reduction" +) +LOCAL_REDUCE_AUX_OUTPUT_CONTRACT_ERROR = ( + "FlexGEMM does not support this aux output shape yet. Please file an issue " + "with the FlexGEMM epilogue expression." +) +LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR = ( + "FlexGEMM local-reduce broadcast values support one generated physical reduction" +) +LOCAL_REDUCE_SINGLE_PHYSICAL_FINALIZE_ERROR = ( + "FlexGEMM physical finalize expressions support a single physical local reduction" +) +LOCAL_REDUCE_POST_POINTWISE_FINALIZE_ERROR = ( + "FlexGEMM physical local reductions do not support post-reduction " + "pointwise transforms yet. Please file an issue with the FlexGEMM epilogue " + "expression." +) +LOCAL_REDUCE_FINALIZE_SCALAR_ONLY_ERROR = ( + "FlexGEMM physical local reductions require finalize expressions to depend " + "only on the reduced value and scalar constants" +) +LOCAL_REDUCE_SOURCE_EXPRESSION_ERROR = ( + "FlexGEMM physical local-reduce feed-main source expressions require " + "two-phase local-reduce source lowering" +) +LOCAL_REDUCE_CONFIG_ERROR = ( + "FlexGEMM local-reduce aux outputs require a non-swap_ab config whose CTA " + "tile axis is divisible by group" +) +LOCAL_REDUCE_EXPLICIT_DTYPE_ERROR = ( + "FlexGEMM does not support explicit reduction dtype yet" +) +LOCAL_REDUCE_INNERMOST_GROUPED_DIM_ERROR = ( + "FlexGEMM local reductions currently support only reductions over the " + "innermost grouped dimension" +) +LOCAL_REDUCE_GROUPED_RESHAPE_ERROR = ( + "FlexGEMM local-reduce grouped reshape must split exactly one GEMM output dimension" +) +LOCAL_REDUCE_MIXED_MATCH_ERROR = ( + "FlexGEMM local reductions do not support mixing different grouped layouts" +) +LOCAL_REDUCE_FEED_MAIN_MIXED_MATCH_ERROR = ( + "FlexGEMM local-reduce broadcast values must share one grouped layout" +) +FLEX_GEMM_OUTPUT_PLAN_NODE_ERROR = "FlexGEMM output plans require tensor output nodes" +FLEX_GEMM_OUTPUT_TENSOR_ERROR = "FlexGEMM expects tensor outputs" +LOCAL_REDUCE_MATCH_NODE_ERROR = "local-reduce matches require tensor nodes" +LOCAL_REDUCE_OUTPUT_PLAN_NODE_ERROR = "local-reduce output plans require tensor nodes" +LOCAL_REDUCE_RUNTIME_OUT_ERROR = "compressed local reductions require local_reduce_out" +LOCAL_REDUCE_RUNTIME_DENSE_MM_ERROR = ( + "FlexGEMM local reductions currently support only 2-D aten.mm" +) +LOCAL_REDUCE_OUT_SHAPE_ERROR = "local_reduce_out shape must be {expected}, got {actual}" +LOCAL_REDUCE_CALLBACKS_REQUIRED_ERROR = ( + "physical local reductions require generated local-reduce callbacks" +) +FLEX_GEMM_OUTPUT_CONTRACTION_COMPOSITION_ERROR = ( + "FlexGEMM output contractions do not compose with aux outputs, local " + "reductions, C, alpha/beta, or batched GEMMs yet" +) +FLEX_GEMM_OUTPUT_CONTRACTION_CAPTURE_ERROR = ( + "FlexGEMM output contractions currently support only numeric [1, 1] and " + "[M, 1] captured tensors" +) +FLEX_GEMM_CHUNKED_OUTPUT_CONTRACTION_REDUCE_ERROR = ( + "FlexGEMM concat-layout output contractions do not compose with grouped " + "reductions because concat layout permutes accumulator columns" +) +FLEX_GEMM_CHUNKED_CONTIGUOUS_B_ERROR = ( + "FlexGEMM concat-layout output contractions require B's output dimension to " + "be non-contiguous, as in linear weight.t()" +) +FLEX_GEMM_OUTPUT_CONTRACTION_SHAPE_ERROR = ( + "unsupported FlexGEMM epilogue: contracted output shape must equal the " + "physical GEMM output shape with N divided by the contraction group" +) +FLEX_GEMM_MAIN_OUTPUT_SHAPE_ERROR = ( + "unsupported FlexGEMM epilogue: main output shape must equal the physical " + "GEMM output shape" +) + + +def statically_known_multiple(value: Any, divisor: int) -> bool: + """Return whether a symbolic shape value is known divisible without guards.""" + return statically_known(value % divisor == 0) + + +def is_flex_gemm_partial_reduction_shape( + aux_size: Sequence[Any], output_size: Sequence[Any] +) -> bool: + """Recognize aux shapes that imply a final PyTorch reduction, not local reduce. + + FlexGEMM's generic aux-output path supports one same-shape aux tensor beside + the main output. Reduced shapes such as ``[]``, ``[M]``, ``[N]``, ``[M, 1]``, + ``[1, N]``, or exact 2-D divisors of ``[M, N]`` mean the epilogue tried to + return a final PyTorch reduction/block reduction. Those are different from + QuACK local-reduce aux outputs, which are only accepted after the epilogue + exposes an explicit grouped view such as ``acc.view(M, -1, group).sum(-1)``. + """ + if len(output_size) != 2: + return False + aux_shape = tuple(aux_size) + m, n = output_size + if any( + statically_known_shape_equal(aux_shape, candidate) + for candidate in ((), (m,), (n,), (1, 1), (m, 1), (1, n)) + ): + return True + if len(aux_shape) != 2: + return False + aux_m, aux_n = aux_shape + return ( + statically_known(aux_m > 0) + and statically_known(aux_n > 0) + and statically_known(aux_m <= m) + and statically_known(aux_n <= n) + and (statically_known(aux_m < m) or statically_known(aux_n < n)) + and statically_known_multiple(m, aux_m) + and statically_known_multiple(n, aux_n) + ) + + +def local_reduce_unsupported_tensorssa_error( + reduction: Any, *, value_only: bool = False +) -> NotImplementedError: + """Explain why a grouped reduction is outside the current TensorSSA subset.""" + suffix = " value-only reduction" if value_only else "" + return NotImplementedError( + "FlexGEMM does not support this grouped local reduction yet: " + f"{reduction} does not map to a CuTe TensorSSA{suffix}. Please file " + "an issue with the FlexGEMM epilogue expression." + ) + + +def validate_local_reduce_group_axis(group: int, axis: int) -> None: + """Keep local-reduce specs inside the GEMM tile's M/N grouping model.""" + if group <= 0: + raise RuntimeError(LOCAL_REDUCE_GROUP_POSITIVE_ERROR) + if axis not in (0, 1): + raise RuntimeError(LOCAL_REDUCE_AXIS_ERROR) + + +def validate_local_reduce_selected_dim_divisible( + shape: Sequence[Any], group: int, axis: int +) -> None: + """Reject selected M/N dimensions known not to have an integral compressed shape.""" + validate_local_reduce_group_axis(group, axis) + selected_dim = shape[axis - 2] + if statically_known_multiple(selected_dim, group): + return + if statically_known(selected_dim % group != 0): + raise RuntimeError(LOCAL_REDUCE_DIVISIBLE_SHAPE_ERROR) + + +def validate_local_reduce_tensorssa_group_size(axis: int, group: int) -> None: + """Mirror the TensorSSA fragment tiling constraints used by QuACK. + + Groups within one fragment must divide the 32-lane TensorSSA width. Larger + groups are handled as 32-lane TensorSSA partials plus physical combine, so + they must be exact multiples of that fragment width. + """ + if group <= 1: + raise NotImplementedError(LOCAL_REDUCE_TENSORSSA_GROUP_SIZE_ERROR) + validate_local_reduce_group_axis(group, axis) + if group > LOCAL_REDUCE_FRAGMENT_WIDTH and group % LOCAL_REDUCE_FRAGMENT_WIDTH != 0: + raise NotImplementedError(LOCAL_REDUCE_TENSORSSA_FRAGMENT_MULTIPLE_ERROR) + if ( + group <= LOCAL_REDUCE_FRAGMENT_WIDTH + and LOCAL_REDUCE_FRAGMENT_WIDTH % group != 0 + ): + raise NotImplementedError(LOCAL_REDUCE_TENSORSSA_FRAGMENT_DIVISIBLE_ERROR) + + +def local_reduce_needs_physical_callbacks(axis: int, group: int) -> bool: + """Return whether QuACK must merge TensorSSA partials outside the fragment path.""" + return axis == 0 or group > LOCAL_REDUCE_FRAGMENT_WIDTH + + +def validate_local_reduce_runtime_dense_mm(ndim: int) -> None: + """Keep runtime wrappers on the only layout QuACK currently supports. + + Local-reduce group/axis semantics are defined relative to dense ``mm`` output + dimensions. Batched or vectorized matmul layouts would need separate shape + compression and epilogue argument mapping rules before the same ABI is valid. + """ + if ndim != 2: + raise NotImplementedError(LOCAL_REDUCE_RUNTIME_DENSE_MM_ERROR) + + +def validate_local_reduce_out_shape( + actual_shape: Sequence[Any], expected_shape: Sequence[Any] +) -> None: + """Ensure caller-provided aux storage matches the structural reduce plan. + + Runtime cannot reinterpret an arbitrary aux tensor as the compressed local- + reduce domain: QuACK writes exactly the shape produced by dividing the chosen + GEMM output dimension by the group size, so mismatches would corrupt memory + or silently expose the wrong logical tensor. + """ + actual = tuple(actual_shape) + expected = tuple(expected_shape) + if not statically_known_shape_equal(actual, expected): + raise RuntimeError( + LOCAL_REDUCE_OUT_SHAPE_ERROR.format(expected=expected, actual=actual) + ) + + +def validate_local_reduce_feed_main_capability(axis: int, group: int) -> None: + """Limit feed-main reducers to the physical path QuACK can re-inject today. + + Feeding a reduction back into the main epilogue needs the physical row-lane + combine result to be available as a scalar value for each output element. + That is currently implemented only for same-warp M-axis groups. + """ + if axis != 0: + raise NotImplementedError(LOCAL_REDUCE_FEED_MAIN_AXIS_ERROR) + if group > LOCAL_REDUCE_FRAGMENT_WIDTH: + raise NotImplementedError(LOCAL_REDUCE_FEED_MAIN_SAME_WARP_ERROR) + + +def local_reduce_compressed_shape( + shape: Sequence[Any], group: int, axis: int +) -> tuple[Any, ...]: + """Compute the explicit aux shape that mirrors QuACK's grouped store.""" + validate_local_reduce_selected_dim_divisible(shape, group, axis) + result = list(shape) + result[axis - 2] //= group + return tuple(result) + + +def validate_local_reduce_no_c_alpha_beta( + effective_C: Any | None, alpha: float, beta: float +) -> None: + """Reject C/alpha/beta composition until local-reduce ordering is explicit.""" + if effective_C is not None or alpha != 1.0 or beta != 1.0: + raise NotImplementedError(LOCAL_REDUCE_C_ALPHA_BETA_ERROR) + + +def validate_flex_gemm_local_reduce_config(config: Any, group: int, axis: int) -> bool: + """Return whether a QuACK config has a validated grouped-reduction layout. + + This matches ``GemmConfig`` fields against layout families covered by forced + kernel tests; tile divisibility alone is not sufficient. Axis-1 groups within + one 32-value epilogue fragment need no cross-fragment combine. Some SM100 + two-CTA layouts expose only 16 contiguous N values, reducing that local limit. + + Axis-0 groups and larger axis-1 groups use ``GroupedLocalReduce``'s physical + callback path, which combines epilogue fragments inside one CTA and directly + stores one value per ``(row, group)``. For two-CTA ``tile_m=128`` kernels, each + CTA has a 64-row epilogue tile whose warps are split 2x2 across M and N. An + axis-1 group spanning the full N tile therefore crosses N-warp ownership that + the temporal fragment combine does not stitch; strict subgroups remain valid. + + Two-CTA ``tile_m=256`` kernels instead have a 128-row epilogue tile with a 4x1 + warp layout, so one N-warp partition owns each row's full N tile. Their axis-1 + temporal fragment combine supports a full-tile group without cross-CTA state. + Axis-0 full groups still exceed the per-CTA M tile and remain unsupported. + """ + match axis: + case 0: + tile = config.tile_m + case 1: + tile = config.tile_n + case _: + return False + if group <= 0 or config.swap_ab: + return False + if config.tile_n % LOCAL_REDUCE_FRAGMENT_WIDTH != 0 or tile % group != 0: + return False + + fragment_width = LOCAL_REDUCE_FRAGMENT_WIDTH + has_half_n_fragment = ( + axis == 1 + and config.tile_m == 128 + and config.tile_n in (128, 160, 224) + and config.cluster_m > 1 + ) + if has_half_n_fragment: + fragment_width //= 2 + if group <= LOCAL_REDUCE_FRAGMENT_WIDTH: + return fragment_width % group == 0 and group < tile + + if group % LOCAL_REDUCE_FRAGMENT_WIDTH != 0 or config.cluster_n != 1: + return False + + is_single_cta_layout = config.tile_m == 128 and config.cluster_m == 1 + is_wide_m_two_cta_layout = config.tile_m == 256 and config.cluster_m == 2 + is_split_n_warp_two_cta_layout = ( + axis == 1 + and config.tile_m == 128 + and config.tile_n == 256 + and config.cluster_m == 2 + ) + if is_single_cta_layout: + return True + if is_wide_m_two_cta_layout: + return axis == 1 or group < tile + return is_split_n_warp_two_cta_layout and group < tile + + +def flex_gemm_local_reduce_candidate_groups(config: Any, axis: int) -> tuple[int, ...]: + """Enumerate group sizes worth checking against the config capability gate.""" + match axis: + case 0: + tile = config.tile_m + case 1: + tile = config.tile_n + case _: + return () + return (2, 4, 8, 16, 32, *range(64, tile + 1, 32)) + + +def max_flex_gemm_local_reduce_group_for_configs( + configs: Sequence[Any], axis: int +) -> int | None: + """Return the largest group accepted by the current local-reduce config gate.""" + candidates = [ + group + for config in configs + for group in flex_gemm_local_reduce_candidate_groups(config, axis) + if validate_flex_gemm_local_reduce_config(config, group, axis) + ] + return max(candidates) if candidates else None + + +def flex_gemm_local_reduce_config_error( + configs: Sequence[Any], group: int, axis: int +) -> str: + """Explain the current config-filter frontier for local-reduce groups.""" + max_group = max_flex_gemm_local_reduce_group_for_configs(configs, axis) + if max_group is None: + return LOCAL_REDUCE_CONFIG_ERROR + return ( + f"{LOCAL_REDUCE_CONFIG_ERROR}; requested group={group}, " + f"max supported group={max_group} for axis={axis}" + ) + + +# NOTE [Non-shape-preserving FlexGEMM outputs] +# FlexGEMM normally returns one value per physical GEMM accumulator. Output +# contraction is the current exception: it exposes grouped physical N values to +# the ordinary FX epilogue, requires the main expression to consume the complete +# group, and stores one logical value per group. Interleaved groups use +# ``view(M, logical_N, group)``; chunked groups use +# ``view(M, group, logical_N)`` or ``split(logical_N, dim=-1)``. This covers +# SwiGLU-like pointwise combinations without claiming to support arbitrary slices, +# permutations, expansions, or M-axis contraction. +# +# Numeric ``[1, 1]`` and ``[M, 1]`` captures are N-invariant. QuACK loads their +# one value per epilogue thread and lets generated pointwise code broadcast it in +# either the physical or contracted layout. N-varying ``[1, N]`` and ``[M, N]`` +# captures need the same concat-to-interleave mapping as B for chunked outputs. +@dataclasses.dataclass(frozen=True) +class FlexGemmOutputContraction: + """Describe the contraction in NOTE [Non-shape-preserving FlexGEMM outputs]. + + Attributes: + group: Number of physical N values contracted into each logical output. + chunked: Whether group values are contiguous N chunks rather than interleaved. + """ + + group: int + chunked: bool = False + + def __post_init__(self) -> None: + if self.group <= 0: + raise ValueError("output-contraction group must be positive") + + @property + def concat_layout(self) -> tuple[str, ...]: + """Return the QuACK ABI tag that interleaves chunked B columns.""" + return ("B",) if self.chunked else () + + def validate_quack(self, device_capacity: int) -> None: + if device_capacity == 12: + raise NotImplementedError( + "FlexGEMM output contractions are not yet supported on SM120" + ) + if device_capacity not in (10, 11): + raise NotImplementedError( + "FlexGEMM output contractions are currently validated only on " + "SM100 and SM110" + ) + if self.group == 2 or ( + self.group == 4 and not self.chunked and device_capacity == 10 + ): + return + raise NotImplementedError( + "FlexGEMM output-contraction stores support group 2 on SM100 and " + "SM110, plus interleaved group 4 on SM100" + ) + + +def output_contraction_capture_supported(kind: str, is_boolean: bool) -> bool: + """Return whether output-contraction codegen can broadcast a captured tensor.""" + return kind in ("scalar", "col") and not is_boolean + + +def output_contraction_config_supported(config: Any, n: Any) -> bool: + """Return whether a config has validated output-contraction store ownership. + + Keep the physical M/N orientation, one CTA per cluster along N, and require + the physical N tile not to exceed the problem. Admit only M-cluster families + whose row ownership has been validated: a single M CTA or the wide-M two-CTA + layout. Multiple N tiles and partial final tiles are supported by the ordinary + tile scheduler and store predicates. + """ + supported_m_cluster = config.cluster_m == 1 or ( + config.tile_m == 256 and config.cluster_m == 2 + ) + return ( + not config.swap_ab + and supported_m_cluster + and config.cluster_n == 1 + and statically_known(config.tile_n <= n) + ) + + +FlexGemmLocalReduceGeometry = GemmReductionGeometry + + +@dataclasses.dataclass(frozen=True) +class FlexGemmLocalReduceCallbacks: + """Carry generated physical combine/finalize functions.""" + + combine_fn: Any + finalize_fn: Any + + def __post_init__(self) -> None: + """Keep physical reducers from existing without their generated code.""" + if self.combine_fn is None or self.finalize_fn is None: + raise RuntimeError(LOCAL_REDUCE_CALLBACKS_REQUIRED_ERROR) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/debug.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..704cc25f8dbe8c63225f1def8ea221d7c9855f85 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/debug.py @@ -0,0 +1,374 @@ +"""Format and emit opt-in FlexGEMM compilation diagnostics. + +The ``flex_gemm`` logger follows lowering from the captured FX body through +semantic analysis, buffer planning, generated CuTeDSL, and kernel selection. +Each phase is also available as a structured trace artifact. +""" + +import logging +from collections.abc import Callable, Iterable, Sequence +from typing import Any, TYPE_CHECKING + +import torch +from torch._inductor.kernel.gemm_epilogue import ( + NormalizedGetItem, + NormalizedPrepareSoftmax, + NormalizedReduction, + NormalizedSelect, + NormalizedSplit, + NormalizedSqueeze, + NormalizedUnsupportedReduction, + NormalizedView, +) +from torch._logging import LazyString, trace_structured + + +if TYPE_CHECKING: + from torch._inductor import ir + from torch._inductor.heuristics.template.flex_gemm import GemmConfigKey + from torch._inductor.kernel.flex_gemm.fx_cutedsl_codegen import ( + FlexGemmEpilogueAnalysis, + ) + + +flex_gemm_log = logging.getLogger(__name__) + + +def log_flex_gemm_artifact( + name: str, + payload_fn: Callable[[], str], + *, + lowering_name: str | None = None, + verbose: bool = False, +) -> None: + """Emit one lazily rendered local and structured FlexGEMM phase.""" + heading = "FLEXGEMM LOWERING" + if lowering_name is not None: + heading += f" [{lowering_name}]" + flex_gemm_log.log( + logging.DEBUG if verbose else logging.INFO, + "%s\n ===== %s =====\n%s", + heading, + name.replace("_", " ").upper(), + LazyString(payload_fn), + ) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": f"flex_gemm_{name}", + "encoding": "string", + "verbosity": "verbose" if verbose else "concise", + **({} if lowering_name is None else {"lowering_name": lowering_name}), + }, + payload_fn=payload_fn, + ) + + +def _append_items(lines: list[str], label: str, items: Iterable[str]) -> None: + """Append an indented report section, including an explicit empty marker.""" + values = tuple(items) + lines.append(f"{label}:") + lines.extend(f" {value}" for value in values or ("(none)",)) + + +def _format_ir_tensor(name: str, node: "ir.IRNode") -> str: + """Format the tensor contract visible to Inductor lowering.""" + stride = node.maybe_get_stride() + return ( + f"{name}: shape={tuple(node.get_size())}, " + f"stride={'unrealized' if stride is None else tuple(stride)}, " + f"dtype={node.get_dtype()}, device={node.get_device_or_error()}" + ) + + +def format_flex_gemm_problem( + graph_module: torch.fx.GraphModule, + gemm_op: torch._ops.OpOverload, + gemm_inputs: Sequence[tuple[str, "ir.IRNode"]], + captures: Sequence[tuple[str, "ir.IRNode"]], + *, + alpha: float, + beta: float, + tuned: bool, + fast_math: bool, + explicit_config: dict[str, Any] | None, +) -> str: + """Render the inputs and captured body entering FlexGEMM analysis.""" + lines = [ + f"gemm_op: {gemm_op}", + "kernel_options:", + " backend: QUACK", + f" tuned: {tuned}", + f" fast_math: {fast_math}", + f" config: {explicit_config!r}", + f"alpha: {alpha}", + f"beta: {beta}", + ] + _append_items( + lines, + "gemm_inputs", + (_format_ir_tensor(name, node) for name, node in gemm_inputs), + ) + _append_items( + lines, + "captures", + (_format_ir_tensor(name, node) for name, node in captures), + ) + lines.extend( + ( + "body:", + graph_module.print_readable( + print_output=False, + include_stride=True, + include_device=True, + ).strip(), + ) + ) + return "\n".join(lines) + + +def _format_fx_tensor(node: torch.fx.Node) -> str: + """Format an FX node using its captured fake-tensor metadata.""" + meta = node.meta.get("val") + if not isinstance(meta, torch.Tensor): + return node.name + return ( + f"{node.name}: shape={tuple(meta.shape)}, stride={tuple(meta.stride())}, " + f"dtype={meta.dtype}" + ) + + +def _format_geometry(geometry: Any) -> str: + """Format grouped GEMM geometry in logical M/N terms.""" + axis = "M" if geometry.axis == 0 else "N" + return f"axis={axis}, group={geometry.group}" + + +def _format_output_contraction(contraction: Any | None) -> str: + """Format the logical contraction applied to the main output.""" + if contraction is None: + return "none" + layout = "chunked" if contraction.chunked else "interleaved" + return f"N-axis, group={contraction.group}, layout={layout}" + + +def _format_normalized_dataflow(node: torch.fx.Node, normalized: Any) -> str: + """Render one normalized FX operation as compact dataflow.""" + match normalized: + case NormalizedView(shape=shape): + operation = f"view(shape={shape})" + case NormalizedReduction( + dim=dim, + keepdim=keepdim, + reduction_type=reduction_type, + ): + operation = f"{reduction_type}(dim={dim}, keepdim={keepdim})" + case NormalizedPrepareSoftmax(dim=dim): + operation = f"prepare_softmax(dim={dim})" + case NormalizedSqueeze(): + operation = "squeeze" + case NormalizedGetItem(index=index): + operation = f"getitem(index={index})" + case NormalizedSplit(split_size=split_size, dim=dim): + operation = f"split(size={split_size}, dim={dim})" + case NormalizedSelect(dim=dim, index=index): + operation = f"select(dim={dim}, index={index})" + case NormalizedUnsupportedReduction(): + operation = f"unsupported_reduction({node.target})" + case _: + return repr(normalized) + return f"{normalized.source.name} -> {operation}" + + +def format_flex_gemm_analysis(analysis: "FlexGemmEpilogueAnalysis") -> str: + """Render the semantic decisions a FlexGEMM developer acts on first.""" + outputs = analysis.outputs + lines = [ + "outputs:", + f" main: {_format_fx_tensor(outputs.output)}", + f" output_contraction: {_format_output_contraction(outputs.output_contraction)}", + ] + if outputs.aux_outputs: + lines.append(" auxiliary:") + lines.extend( + f" {_format_fx_tensor(output)}" for output in outputs.aux_outputs + ) + else: + lines.append(" auxiliary: (none)") + + lines.append("") + if outputs.local_reduce is None: + lines.append("local_reduction: none") + else: + local_reduce = outputs.local_reduce + store = local_reduce.store + consumers = [] + if local_reduce.feeds_main: + consumers.append("main") + if store is not None: + consumers.append("returned") + normalized = analysis.local_reduce.graph.normalized_nodes.get( + local_reduce.match.value_node + ) + dataflow = ( + str(local_reduce.match.value_node.target) + if normalized is None + else _format_normalized_dataflow(local_reduce.match.value_node, normalized) + ) + lines.extend( + ( + "local_reduction:", + f" value: {local_reduce.match.value_node.name}", + f" dataflow: {dataflow}", + f" geometry: {_format_geometry(local_reduce.match.geometry)}", + f" consumers: {' + '.join(consumers)}", + ) + ) + if store is not None: + lines.extend( + ( + f" returned_as: {store.node.name}", + " output_layout: dense", + ) + ) + + lines.append("") + _append_items( + lines, + "config_constraints", + map(_format_geometry, analysis.required_geometries), + ) + return "\n".join(lines) + + +def format_flex_gemm_analysis_details( + analysis: "FlexGemmEpilogueAnalysis", +) -> str: + """Render normalized nodes and recognizer records for deep debugging.""" + lines: list[str] = [] + for label, values in ( + ("normalized_nodes", analysis.local_reduce.graph.normalized_nodes), + ("grouped_layouts", analysis.local_reduce.grouped_tensors), + ("local_reduce_matches", analysis.local_reduce.matches), + ( + "output_contraction_select_indices", + analysis.output_contraction_select_indices, + ), + ): + _append_items( + lines, + label, + (f"{node.name}: {value!r}" for node, value in values.items()), + ) + lines.append("") + return "\n".join(lines).rstrip() + + +def _format_tensor_meta(meta: torch.Tensor) -> str: + """Format output metadata used for allocation and ABI planning.""" + return ( + f"shape={tuple(meta.shape)}, stride={tuple(meta.stride())}, dtype={meta.dtype}" + ) + + +def format_flex_gemm_lowering_plan( + logical_output_size: Sequence[Any], + physical_output_size: Sequence[Any], + output_dtype: torch.dtype, + capture_kinds: Sequence[tuple[str, str]], + aux_metas: Sequence[torch.Tensor], + local_reduce_metas: Sequence[torch.Tensor], +) -> str: + """Render buffer allocation and runtime-ABI decisions.""" + lines = [ + "output_storage:", + f" logical: shape={tuple(logical_output_size)}, dtype={output_dtype}", + f" physical: shape={tuple(physical_output_size)}", + "", + ] + _append_items( + lines, + "captures", + (f"{name} -> {kind}" for name, kind in capture_kinds), + ) + lines.append("") + _append_items(lines, "auxiliary_storage", map(_format_tensor_meta, aux_metas)) + lines.append("") + if local_reduce_metas: + _append_items( + lines, + "local_reduction_storage", + ( + f"output {index}: {_format_tensor_meta(meta)}" + for index, meta in enumerate(local_reduce_metas) + ), + ) + lines.append(" layout: dense") + else: + lines.append("local_reduction_storage: (none)") + return "\n".join(lines) + + +def format_flex_gemm_config_key(config_key: "GemmConfigKey") -> str: + """Render every config field so new GemmConfig fields remain visible.""" + return "\n".join( + f"{name}: {'auto' if value is None else repr(value)}" + for name, value in config_key + ) + + +def format_flex_gemm_config_candidates( + config_keys: Sequence["GemmConfigKey"], +) -> str: + """Render every lowering-approved config for verbose diagnostics.""" + lines: list[str] = [] + for index, config_key in enumerate(config_keys): + _append_items( + lines, + f"candidate {index}", + format_flex_gemm_config_key(config_key).splitlines(), + ) + lines.append("") + return "\n".join(lines).rstrip() if lines else "(none)" + + +def format_flex_gemm_selection( + choice: "ir.ChoiceCaller | None", + config_key: "GemmConfigKey | None", + *, + candidate_count: int, + tuned: bool, +) -> str: + """Render the search summary and selected FlexGEMM template.""" + lines = [ + "search:", + f" mode: {'autotuned' if tuned else 'fixed'}", + f" lowering_approved_candidates: {candidate_count}", + "", + "selected:", + ] + if choice is None: + lines.append(" deferred to a multi-template buffer") + else: + lines.append(f" template: {choice.name}") + lines.append(" config:") + lines.extend( + " " + line + for line in ( + ("(unavailable)",) + if config_key is None + else format_flex_gemm_config_key(config_key).splitlines() + ) + ) + lines.extend( + ( + "", + "more_detail_commands:", + ' analysis/codegen: TORCH_LOGS="+flex_gemm"', + ' autotune timings: TORCH_LOGS="flex_gemm,autotuning"', + ' generated kernel: TORCH_LOGS="flex_gemm,kernel_code"', + ' final wrapper: TORCH_LOGS="flex_gemm,output_code"', + ' candidate failures: TORCH_LOGS="+inductor,flex_gemm"', + ) + ) + return "\n".join(lines) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/fx_cutedsl_codegen.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/fx_cutedsl_codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..7bceb4d161425c1e45fd5de81c0a12d402b65770 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/fx_cutedsl_codegen.py @@ -0,0 +1,1065 @@ +# mypy: allow-untyped-defs +"""Analyze FlexGEMM epilogue FX graphs and materialize CuTeDSL source. + +``analyze_flex_gemm_epilogue`` indexes FX dependencies, identifies nodes that +carry grouped TensorSSA layouts, matches supported local reductions, and plans +the main, auxiliary, and local-reduction consumers. + +``materialize_flex_gemm_epilogue`` uses that analysis to generate the CuTeDSL +epilogue and physical reduction callbacks. +""" + +import dataclasses +import hashlib +from typing import Any + +from sympy import Max, Min + +import torch +from torch._inductor.codegen.cutedsl.cutedsl_op_overrides import ( + CuteDSLCSEVariable, + upcast_compute_type, + use_cutedsl_fast_math, +) +from torch._inductor.kernel import gemm_epilogue_analysis as _epilogue_analysis +from torch._inductor.kernel.flex_gemm.constraints import ( + FLEX_GEMM_CHUNKED_OUTPUT_CONTRACTION_REDUCE_ERROR, + FLEX_GEMM_MAIN_OUTPUT_SHAPE_ERROR, + FLEX_GEMM_OUTPUT_CONTRACTION_COMPOSITION_ERROR, + FLEX_GEMM_OUTPUT_CONTRACTION_SHAPE_ERROR, + FLEX_GEMM_OUTPUT_TENSOR_ERROR, + FlexGemmLocalReduceGeometry, + FlexGemmOutputContraction, + LOCAL_REDUCE_AUX_TENSORSSA_ERROR, + LOCAL_REDUCE_COMBINE_FN_SUFFIX, + LOCAL_REDUCE_FEED_MAIN_ARG_NAME, + LOCAL_REDUCE_FINALIZE_FN_SUFFIX, + LOCAL_REDUCE_FINALIZE_SCALAR_ONLY_ERROR, + LOCAL_REDUCE_MIXED_MATCH_ERROR, + LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR, + LOCAL_REDUCE_POST_POINTWISE_FINALIZE_ERROR, + LOCAL_REDUCE_SINGLE_PHYSICAL_FINALIZE_ERROR, + local_reduce_unsupported_tensorssa_error, +) +from torch._inductor.kernel.flex_gemm.quack_reductions import ( + _cute_arg, + _cute_call, + _cute_op_name, + _keepdim_and_broadcast, + _local_reduce_store_arg, + FlexGemmPhysicalReduction, + GroupedTensorSSALayout, + is_shape_preserving_pointwise_node, + lower_full_scalar, + lower_getitem, + lower_grouped_n_select, + lower_grouped_n_split, + lower_prepare_softmax_online, + lower_squeeze, + lower_tensorssa_reduce, + lower_view_or_reshape, + tensor_meta_shape, +) +from torch._inductor.kernel.gemm_epilogue import ( + GemmReductionPlan, + iter_fx_node_inputs, + NormalizedDtypeView, + NormalizedGetItem, + NormalizedPrepareSoftmax, + NormalizedReduction, + NormalizedSelect, + NormalizedSplit, + NormalizedSqueeze, + NormalizedUnsupportedReduction, + NormalizedView, +) +from torch._inductor.kernel.gemm_epilogue_codegen import ( + GemmEpilogueCuteDSLKernel, + GemmEpilogueCuteDSLOpOverrides, +) +from torch._inductor.kernel.gemm_epilogue_utils import ( + guarded_int, + statically_known_shape_equal, +) +from torch._inductor.virtualized import V +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.value_ranges import ValueRanges + + +FlexGemmEpilogueGraph = _epilogue_analysis.GemmEpilogueGraph +FlexGemmLocalReduceAnalysis = _epilogue_analysis.GemmLocalReduceAnalysis +FlexGemmLocalReduceMatch = _epilogue_analysis.GemmLocalReduceMatch +FlexGemmLocalReduceStore = _epilogue_analysis.GemmLocalReduceStore +FlexGemmOutputLocalReducePlan = _epilogue_analysis.GemmOutputLocalReducePlan + + +@dataclasses.dataclass(frozen=True) +class FlexGemmOutputPlan(_epilogue_analysis.GemmOutputPlan): + """Extend output planning with contraction and terminal storage metadata.""" + + output_contraction: FlexGemmOutputContraction | None = None + output_storage: torch.fx.Node | None = None + + +FlexGemmCuteDSLKernel = GemmEpilogueCuteDSLKernel + + +class FlexGemmCuteDSLOpOverrides(GemmEpilogueCuteDSLOpOverrides): + """Add FlexGEMM-specific NaN-propagating clamp semantics.""" + + @staticmethod + def clamp(x: Any, min: Any = None, max: Any = None) -> Any: + result = x + if min is not None: + result = FlexGemmCuteDSLOpOverrides.clamp_min(result, min) + if max is not None: + result = FlexGemmCuteDSLOpOverrides.clamp_max(result, max) + return result + + @staticmethod + def clamp_min(x: Any, min: Any) -> Any: + return GemmEpilogueCuteDSLOpOverrides._apply_binary_op( + x, + min, + "cutlass_math.max({a}, {b}, propagate_nan=True)", + Max, + ) + + @staticmethod + def clamp_max(x: Any, max: Any) -> Any: + return GemmEpilogueCuteDSLOpOverrides._apply_binary_op( + x, + max, + "cutlass_math.min({a}, {b}, propagate_nan=True)", + Min, + ) + + +def tuple_output_plan( + output: Any, + aux_outputs: tuple[Any, ...], + analysis: FlexGemmLocalReduceAnalysis, +) -> FlexGemmOutputPlan: + """Classify multi-output epilogues after checking local-reduce consumers.""" + if not isinstance(output, torch.fx.Node) or not all( + isinstance(aux_output, torch.fx.Node) for aux_output in aux_outputs + ): + raise NotImplementedError(FLEX_GEMM_OUTPUT_TENSOR_ERROR) + feed_match = analysis.common_feed_main_match((output, *aux_outputs)) + compressed_aux_plans = tuple( + (index, match, plan) + for index, aux_output in enumerate(aux_outputs) + if (match := analysis.matches.get(aux_output)) is not None + if (plan := analysis.compressed_aux_plan(output, aux_output, index)) is not None + ) + if len(compressed_aux_plans) > 1: + raise NotImplementedError(LOCAL_REDUCE_MIXED_MATCH_ERROR) + if compressed_aux_plans: + local_reduce_index, compressed_match, compressed_aux_plan = ( + compressed_aux_plans[0] + ) + if feed_match is not None: + if feed_match.value_node is not compressed_match.value_node: + raise NotImplementedError(LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR) + compressed_aux_plan = feed_match.to_plan( + store=FlexGemmLocalReduceStore( + aux_outputs[local_reduce_index], local_reduce_index + ), + feeds_main=True, + ) + return FlexGemmOutputPlan( + output, + tuple( + aux_output + for index, aux_output in enumerate(aux_outputs) + if index != local_reduce_index + ), + local_reduce=compressed_aux_plan, + ) + feed_main_plan = analysis.feed_main_output_plan(output, aux_outputs) + if feed_main_plan is not None: + return FlexGemmOutputPlan( + feed_main_plan.output, + feed_main_plan.aux_outputs, + feed_main_plan.local_reduce, + ) + return FlexGemmOutputPlan(output, aux_outputs) + + +def output_plan( + graph_module: torch.fx.GraphModule, + local_reduce: FlexGemmLocalReduceAnalysis, +) -> FlexGemmOutputPlan: + """Classify output consumers from one shared local-reduce analysis.""" + output_nodes = [node for node in graph_module.graph.nodes if node.op == "output"] + if len(output_nodes) != 1: + raise NotImplementedError("FlexGEMM expects one output node") + output_value = output_nodes[0].args[0] + if isinstance(output_value, (tuple, list)): + if len(output_value) == 1: + output_value = output_value[0] + else: + output, *aux_outputs = output_value + return tuple_output_plan(output, tuple(aux_outputs), local_reduce) + if not isinstance(output_value, torch.fx.Node): + raise NotImplementedError("FlexGEMM expects one tensor output") + feed_main_plan = local_reduce.feed_main_output_plan(output_value) + if feed_main_plan is None: + return FlexGemmOutputPlan(output_value) + return FlexGemmOutputPlan( + feed_main_plan.output, + feed_main_plan.aux_outputs, + feed_main_plan.local_reduce, + ) + + +def bind_terminal_output_storage( + graph: FlexGemmEpilogueGraph, outputs: FlexGemmOutputPlan +) -> FlexGemmOutputPlan: + """Record the physical value beneath a terminal same-width dtype view.""" + normalized = graph.normalized_nodes.get(outputs.output) + if not isinstance(normalized, NormalizedDtypeView): + return outputs + source_meta = normalized.source.meta.get("val") + output_meta = outputs.output.meta.get("val") + if ( + not isinstance(source_meta, torch.Tensor) + or not isinstance(output_meta, torch.Tensor) + or normalized.dtype is not output_meta.dtype + or source_meta.dtype.itemsize != output_meta.dtype.itemsize + or not statically_known_shape_equal(source_meta.shape, output_meta.shape) + or not statically_known_shape_equal(source_meta.stride(), output_meta.stride()) + ): + raise NotImplementedError( + "FlexGEMM terminal dtype views must preserve shape, stride, and element size" + ) + return dataclasses.replace(outputs, output_storage=normalized.source) + + +@dataclasses.dataclass(frozen=True) +class OutputContractionUse: + """Describe one supported use of grouped GEMM values in the main output.""" + + source: torch.fx.Node + group: int + chunked: bool + group_indices: tuple[int, ...] + layout_node: torch.fx.Node | None = None + + +@dataclasses.dataclass(frozen=True) +class OutputContractionPlan: + """Stage one complete output contraction until analysis commits it.""" + + contraction: FlexGemmOutputContraction + select_indices: dict[torch.fx.Node, int] + grouped_tensors: dict[torch.fx.Node, FlexGemmLocalReduceGeometry] + + def commit( + self, + outputs: FlexGemmOutputPlan, + local_reduce: FlexGemmLocalReduceAnalysis, + ) -> FlexGemmOutputPlan: + """Validate composition and install this output contraction.""" + if outputs.aux_outputs or outputs.local_reduce is not None: + raise NotImplementedError(FLEX_GEMM_OUTPUT_CONTRACTION_COMPOSITION_ERROR) + if self.contraction.chunked and any( + local_reduce.graph.depends_on(outputs.output, reduced) + for reduced in local_reduce.matches + ): + raise NotImplementedError(FLEX_GEMM_CHUNKED_OUTPUT_CONTRACTION_REDUCE_ERROR) + local_reduce.grouped_tensors.update(self.grouped_tensors) + return dataclasses.replace(outputs, output_contraction=self.contraction) + + +def canonical_output_contraction_source( + node: torch.fx.Node, + gemm: torch.fx.Node, + local_reduce: FlexGemmLocalReduceAnalysis, +) -> torch.fx.Node: + """Find one contraction use's GEMM provenance through pointwise wrappers.""" + while node is not gemm and is_shape_preserving_pointwise_node(node): + inputs = [ + arg + for arg in iter_fx_node_inputs((node.args, node.kwargs)) + if local_reduce.graph.depends_on(arg, gemm) + ] + if len(inputs) != 1: + break + node = inputs[0] + return node + + +def match_output_contraction_use( + node: torch.fx.Node, + gemm: torch.fx.Node, + gemm_shape: tuple[Any, ...] | None, + local_reduce: FlexGemmLocalReduceAnalysis, +) -> OutputContractionUse | None: + """Match one supported use of grouped GEMM values in the main output.""" + if gemm_shape is None: + return None + normalized = local_reduce.graph.normalized_nodes.get(node) + + if isinstance(normalized, NormalizedGetItem): + split = normalized.source + split_normalized = local_reduce.graph.normalized_nodes.get(split) + if not isinstance(split_normalized, NormalizedSplit): + return None + shape = tensor_meta_shape(split_normalized.source) + if ( + shape is None + or len(shape) != 2 + or not statically_known_shape_equal(shape, gemm_shape) + or not local_reduce.graph.depends_on(split_normalized.source, gemm) + or not isinstance(shape[-1], int) + or split_normalized.dim not in (-1, 1) + ): + return None + split_size = guarded_int(split_normalized.split_size) + if split_size is None or split_size <= 0 or shape[-1] % split_size != 0: + return None + group = shape[-1] // split_size + if group <= 1: + return None + return OutputContractionUse( + source=split_normalized.source, + group=group, + chunked=True, + group_indices=(normalized.index,), + layout_node=split, + ) + + if not isinstance(normalized, NormalizedSelect): + return None + view = normalized.source + view_normalized = local_reduce.graph.normalized_nodes.get(view) + shape = tensor_meta_shape(view) + if ( + not isinstance(view_normalized, NormalizedView) + or not local_reduce.graph.depends_on(view_normalized.source, gemm) + or shape is None + or len(shape) != 3 + or not statically_known_shape_equal((shape[0], shape[1] * shape[2]), gemm_shape) + or not -len(shape) <= normalized.dim < len(shape) + ): + return None + index = guarded_int(normalized.index) + if index is None: + return None + dim = normalized.dim % len(shape) + if dim == 1: + group = guarded_int(shape[1]) + if group is None or group <= 1: + return None + chunked = True + layout_node = view + elif dim == len(shape) - 1: + grouped_layout = local_reduce.grouped_tensors.get(view) + if grouped_layout is None or grouped_layout.axis != 1: + return None + group = grouped_layout.group + chunked = False + layout_node = None + else: + return None + return OutputContractionUse( + source=view_normalized.source, + group=group, + chunked=chunked, + group_indices=(index,), + layout_node=layout_node, + ) + + +def collect_output_contraction_uses( + output: torch.fx.Node, + gemm: torch.fx.Node, + local_reduce: FlexGemmLocalReduceAnalysis, +) -> list[tuple[torch.fx.Node, OutputContractionUse]] | None: + """Collect contraction uses without mutating analysis state.""" + gemm_shape = tensor_meta_shape(gemm) + uses: list[tuple[torch.fx.Node, OutputContractionUse]] = [] + seen: OrderedSet[torch.fx.Node] = OrderedSet() + stack: list[Any] = [output] + while stack: + node = stack.pop() + if not isinstance(node, torch.fx.Node) or node in seen: + continue + seen.add(node) + match = match_output_contraction_use(node, gemm, gemm_shape, local_reduce) + if match is not None: + uses.append((node, match)) + continue + if node is gemm or ( + node in local_reduce.grouped_tensors + and local_reduce.graph.depends_on(node, gemm) + ): + return None + stack.extend(reversed(tuple(iter_fx_node_inputs((node.args, node.kwargs))))) + return uses or None + + +def build_output_contraction_plan( + output: torch.fx.Node, + gemm: torch.fx.Node, + local_reduce: FlexGemmLocalReduceAnalysis, +) -> OutputContractionPlan | None: + """Build a plan when all grouped GEMM values form one output contraction.""" + collected = collect_output_contraction_uses(output, gemm, local_reduce) + if collected is None: + return None + first = collected[0][1] + source = canonical_output_contraction_source(first.source, gemm, local_reduce) + group_indices: OrderedSet[int] = OrderedSet() + select_indices: dict[torch.fx.Node, int] = {} + grouped_tensors: dict[torch.fx.Node, FlexGemmLocalReduceGeometry] = {} + for node, match in collected: + if ( + canonical_output_contraction_source(match.source, gemm, local_reduce) + is not source + or match.group != first.group + or match.chunked != first.chunked + ): + return None + for index in match.group_indices: + if not -first.group <= index < first.group: + return None + group_indices.add(index % first.group) + if isinstance(local_reduce.graph.normalized_nodes.get(node), NormalizedSelect): + select_indices[node] = match.group_indices[0] % first.group + if match.layout_node is not None: + grouped_tensors[match.layout_node] = FlexGemmLocalReduceGeometry( + group=match.group, axis=1 + ) + if group_indices != OrderedSet(range(first.group)): + return None + gemm_meta = gemm.meta.get("val") + output_meta = output.meta.get("val") + if gemm_meta is None or output_meta is None or len(gemm_meta.shape) != 2: + return None + expected_shape = (gemm_meta.shape[0], gemm_meta.shape[1] // first.group) + if not statically_known_shape_equal(output_meta.shape, expected_shape): + raise NotImplementedError(FLEX_GEMM_OUTPUT_CONTRACTION_SHAPE_ERROR) + return OutputContractionPlan( + FlexGemmOutputContraction(group=first.group, chunked=first.chunked), + select_indices, + grouped_tensors, + ) + + +def validate_shape_preserving_main_output( + outputs: FlexGemmOutputPlan, + gemm: torch.fx.Node, + local_reduce: FlexGemmLocalReduceAnalysis, +) -> None: + """Reject incomplete grouped selects and other shape-changing main outputs.""" + # TODO: Consider DCE before analysis if dead grouped selects become common. + if any( + isinstance(normalized, NormalizedSelect) + and normalized.source in local_reduce.grouped_tensors + and local_reduce.grouped_tensors[normalized.source].axis == 1 + for normalized in local_reduce.graph.normalized_nodes.values() + ): + raise NotImplementedError( + "FlexGEMM grouped selects must form a complete output contraction" + ) + output_shape = tensor_meta_shape(outputs.output) + gemm_shape = tensor_meta_shape(gemm) + if ( + output_shape is None + or gemm_shape is None + or not statically_known_shape_equal(output_shape, gemm_shape) + ): + raise NotImplementedError(FLEX_GEMM_MAIN_OUTPUT_SHAPE_ERROR) + + +@dataclasses.dataclass(frozen=True) +class FlexGemmEpilogueAnalysis: + """Bundle the immutable analysis consumed by FlexGEMM lowering and emission. + + Attributes: + gemm: The validated GEMM node shared by lowering and emission. + outputs: Classification of main, auxiliary, and local-reduction outputs. + local_reduce: Grouped layouts and local-reduction matches from the FX graph. + output_contraction_select_indices: Select indices committed by the contraction plan. + """ + + gemm: torch.fx.Node + outputs: FlexGemmOutputPlan + local_reduce: FlexGemmLocalReduceAnalysis + output_contraction_select_indices: dict[torch.fx.Node, int] = dataclasses.field( + default_factory=dict + ) + + @classmethod + def from_graph_module( + cls, graph_module: torch.fx.GraphModule, gemm: torch.fx.Node + ) -> "FlexGemmEpilogueAnalysis": + """Analyze grouped values and classify logical output consumers.""" + local_reduce = FlexGemmLocalReduceAnalysis.from_graph_module(graph_module) + outputs = bind_terminal_output_storage( + local_reduce.graph, output_plan(graph_module, local_reduce) + ) + contraction_plan = build_output_contraction_plan( + outputs.output, gemm, local_reduce + ) + if contraction_plan is None: + validate_shape_preserving_main_output(outputs, gemm, local_reduce) + output_contraction_select_indices = {} + else: + outputs = contraction_plan.commit(outputs, local_reduce) + output_contraction_select_indices = contraction_plan.select_indices + return cls(gemm, outputs, local_reduce, output_contraction_select_indices) + + @property + def required_geometries(self) -> tuple[FlexGemmLocalReduceGeometry, ...]: + """Return every grouped geometry that constrains kernel configuration.""" + geometries = OrderedSet( + match.geometry for match in self.local_reduce.matches.values() + ) + if self.outputs.local_reduce is not None: + geometries.add(self.outputs.local_reduce.match.geometry) + if self.outputs.output_contraction is not None: + geometries.add( + FlexGemmLocalReduceGeometry( + group=self.outputs.output_contraction.group, + axis=1, + ) + ) + return tuple(geometries) + + @property + def reduction_plan(self) -> GemmReductionPlan | None: + """Return the backend-neutral reduction plan produced by FX analysis.""" + return self.outputs.reduction_plan + + +def analyze_flex_gemm_epilogue( + graph_module: torch.fx.GraphModule, + gemm: torch.fx.Node, +) -> FlexGemmEpilogueAnalysis: + """Analyze FlexGEMM body for output planning and epilogue code generation. + + This is the analysis entry point called by FlexGEMM lowering. It builds a + dependency index, performs topological local-reduction analysis, and + returns the shared immutable plan consumed by config selection and + ``materialize_flex_gemm_epilogue``. + + Args: + graph_module: FlexGEMM body graph containing GEMM and epilogue nodes. + + Returns: + Output and local-reduction analysis shared by later lowering phases. + """ + return FlexGemmEpilogueAnalysis.from_graph_module(graph_module, gemm) + + +def gemm_node( + graph_module: torch.fx.GraphModule, gemm_op: torch._ops.OpOverload +) -> torch.fx.Node: + gemm_nodes = [ + node + for node in graph_module.graph.nodes + if node.op == "call_function" and node.target == gemm_op + ] + if len(gemm_nodes) != 1: + raise NotImplementedError("FlexGEMM expects one GEMM body") + return gemm_nodes[0] + + +class FlexGemmEpilogueEmitter: + """Visit an analyzed FlexGEMM FX graph and emit its CuTeDSL epilogue. + + The analysis dataclasses flow into each other as follows: + + :: + + FlexGemmEpilogueGraph + `--> FlexGemmLocalReduceAnalysis + +--> grouped_tensors + `--> matches + `--> FlexGemmLocalReduceMatch + `--> FlexGemmOutputLocalReducePlan + `--> optional FlexGemmLocalReduceStore + + FlexGemmLocalReduceAnalysis + `--> output_plan() + `--> FlexGemmOutputPlan + + FlexGemmLocalReduceAnalysis + FlexGemmOutputPlan + `--> FlexGemmEpilogueAnalysis + `--> FlexGemmEpilogueEmitter + + At emitter construction, ``analysis.outputs`` becomes ``self.outputs``; + its local-reduce match and optional store initialize ``self.feed_main`` and + ``self.aux``. ``analysis.local_reduce.grouped_tensors`` is copied into + mutable emission state, while ``analysis.required_geometries`` determines + the active grouped layouts. + + The emitter owns all mutable code-generation state: FX values lowered so far, + grouped TensorSSA layouts, compressed-store expressions, and physical + reduction callbacks. ``lower_graph`` performs a topological traversal and + delegates each ``call_function`` node to ordered handlers; ``render`` turns + the resulting state into the generated epilogue and callback source. + """ + + def __init__( + self, + graph_module: torch.fx.GraphModule, + analysis: FlexGemmEpilogueAnalysis, + epilogue_arg_placeholders: tuple[torch.fx.Node, ...] = (), + *, + fast_math: bool = False, + ) -> None: + self.graph_module = graph_module + self.epilogue_arg_placeholders = epilogue_arg_placeholders + self.fast_math = fast_math + self.gemm = analysis.gemm + self.graph = analysis.local_reduce.graph + self.outputs = analysis.outputs + self.output_contraction_select_indices = ( + analysis.output_contraction_select_indices + ) + self.kernel = FlexGemmCuteDSLKernel() + self.env: dict[torch.fx.Node, Any] = { + self.gemm: CuteDSLCSEVariable( + "acc", ValueRanges.unknown(), dtype=torch.float32, shape=(1,) + ) + } + self.grouped_tensors = { + node: GroupedTensorSSALayout(group=layout.group, axis=layout.axis) + for node, layout in analysis.local_reduce.grouped_tensors.items() + } + self.active_grouped_layouts = OrderedSet( + GroupedTensorSSALayout(group=geometry.group, axis=geometry.axis) + for geometry in analysis.required_geometries + ) + self.store_sources: dict[torch.fx.Node, Any] = {} + self.physical_reductions: dict[torch.fx.Node, FlexGemmPhysicalReduction] = {} + self.local_reduce = self.outputs.local_reduce + self.feed_main: torch.fx.Node | None = None + self.aux: torch.fx.Node | None = None + self.feed_main_input: torch.fx.Node | None = None + match self.local_reduce: + case FlexGemmOutputLocalReducePlan( + match=local_reduce_match, store=store, feeds_main=True + ): + self.feed_main = local_reduce_match.value_node + reduction = self.graph.normalized_nodes.get( + local_reduce_match.value_node + ) + if not isinstance(reduction, NormalizedReduction): + raise AssertionError("feed-main plans require a matched reduction") + self.feed_main_input = reduction.source + self.aux = None if store is None else store.node + case FlexGemmOutputLocalReducePlan( + store=FlexGemmLocalReduceStore(node=store_node) + ): + self.aux = store_node + case None: + pass + + def bind_epilogue_args(self) -> None: + """Bind captured tensor placeholders to generated CuTeDSL parameters.""" + for index, node in enumerate(self.epilogue_arg_placeholders): + epilogue_arg_meta = node.meta["val"] + physical_dtype = ( + torch.uint8 + if epilogue_arg_meta.dtype is torch.bool + else epilogue_arg_meta.dtype + ) + logical_dtype = upcast_compute_type(epilogue_arg_meta.dtype) + self.env[node] = CuteDSLCSEVariable( + f"aux{index}", + ValueRanges.unknown(), + dtype=physical_dtype, + shape=(1,), + is_scalar_expr=self.outputs.output_contraction is not None, + ) + if logical_dtype != physical_dtype: + self.env[node] = FlexGemmCuteDSLOpOverrides.to_dtype( + self.env[node], logical_dtype, use_compute_types=False + ) + + def bind_reduction(self, node: torch.fx.Node, lowered_reduce: Any) -> None: + """Bind a generated reduction or replace it with the feed-main parameter.""" + if self.feed_main is not None and node is self.feed_main: + self.env[node] = CuteDSLCSEVariable( + LOCAL_REDUCE_FEED_MAIN_ARG_NAME, + ValueRanges.unknown(), + dtype=lowered_reduce.dtype, + shape=lowered_reduce.shape, + ) + if self.feed_main_input in self.grouped_tensors: + self.grouped_tensors[node] = self.grouped_tensors[self.feed_main_input] + return + self.env[node] = lowered_reduce + + def lower_compact_inline_asm(self, node: torch.fx.Node) -> bool: + """Apply inline asm before broadcasting a compact reduction value.""" + if ( + self.feed_main is not None + or _cute_op_name(node.target) != "inline_asm_elementwise" + or len(node.args) != 1 + ): + return False + tensor_inputs = [ + input_node + for input_node in node.all_input_nodes + if tensor_meta_shape(input_node) is not None + ] + if len(tensor_inputs) != 1: + return False + source = tensor_inputs[0] + normalized = self.graph.normalized_nodes.get(source) + compact_source = _cute_arg(source, self.env) + if not isinstance(normalized, NormalizedReduction): + if not is_shape_preserving_pointwise_node(source): + return False + source_inputs = [ + input_node + for input_node in source.all_input_nodes + if tensor_meta_shape(input_node) is not None + ] + if len(source_inputs) != 1: + return False + normalized = self.graph.normalized_nodes.get(source_inputs[0]) + if not isinstance(normalized, NormalizedReduction): + return False + compact_source = _cute_call( + source, + tuple(_cute_arg(arg, self.env) for arg in source.args), + { + key: _cute_arg(value, self.env) + for key, value in source.kwargs.items() + }, + ) + reduction_input = normalized.source + layout = self.grouped_tensors.get(reduction_input) + if layout is None: + return False + self.env[node] = _cute_call( + node, + (compact_source,), + {key: _cute_arg(value, self.env) for key, value in node.kwargs.items()}, + ) + _, self.store_sources[node] = _keepdim_and_broadcast( + self.kernel, + self.env[node], + layout, + _cute_arg(reduction_input, self.env), + ) + return True + + def lower_pointwise_store(self, node: torch.fx.Node) -> bool: + """Lower pointwise expressions that consume a compressed store value.""" + if ( + self.feed_main is not None + or not is_shape_preserving_pointwise_node(node) + or not any( + arg in self.store_sources + for arg in iter_fx_node_inputs((node.args, tuple(node.kwargs.values()))) + ) + ): + return False + store_args = tuple( + _local_reduce_store_arg(arg, self.env, self.store_sources) + for arg in node.args + ) + store_kwargs = { + key: _local_reduce_store_arg(value, self.env, self.store_sources) + for key, value in node.kwargs.items() + } + self.env[node] = _cute_call(node, store_args, store_kwargs) + self.store_sources[node] = self.env[node] + return True + + def propagate_physical_reduction(self, node: torch.fx.Node, source: Any) -> None: + """Preserve physical callback provenance through shape-only wrappers.""" + if isinstance(source, torch.fx.Node) and source in self.physical_reductions: + self.physical_reductions[node] = self.physical_reductions[source] + + def physical_finalize_arg(self, value: Any) -> Any: + """Replace physical reduction inputs with their generated value expression.""" + if isinstance(value, torch.fx.Node) and value in self.physical_reductions: + return self.physical_reductions[value].finalize_expr + if isinstance(value, (tuple, list)): + return type(value)(self.physical_finalize_arg(item) for item in value) + return _cute_arg(value, self.env) + + def compose_physical_finalize(self, node: torch.fx.Node) -> Any | None: + """Fold a pointwise consumer into one generated physical finalizer.""" + physical_inputs = list( + OrderedSet( + arg + for arg in iter_fx_node_inputs((node.args, node.kwargs)) + if arg in self.physical_reductions + ) + ) + if not physical_inputs: + return None + if len(physical_inputs) > 1: + raise NotImplementedError(LOCAL_REDUCE_SINGLE_PHYSICAL_FINALIZE_ERROR) + base = physical_inputs[0] + args = tuple(self.physical_finalize_arg(arg) for arg in node.args) + kwargs = { + key: self.physical_finalize_arg(value) for key, value in node.kwargs.items() + } + finalize_expr = _cute_call(node, args, kwargs) + if not isinstance(finalize_expr, str): + raise NotImplementedError(LOCAL_REDUCE_FINALIZE_SCALAR_ONLY_ERROR) + self.store_sources[node] = self.store_sources[base] + self.physical_reductions[node] = dataclasses.replace( + self.physical_reductions[base], finalize_expr=finalize_expr + ) + return finalize_expr + + def lower_call_function(self, node: torch.fx.Node) -> None: + """Lower one call_function node using the ordered FlexGEMM handlers.""" + lowered = lower_full_scalar(node) + if lowered is not None: + self.env[node] = lowered + return + normalized = self.graph.normalized_nodes.get(node) + match normalized: + case NormalizedDtypeView(): + if ( + node is not self.outputs.output + or normalized.source is not self.outputs.output_storage + ): + raise NotImplementedError( + "FlexGEMM supports dtype views only as terminal same-width main outputs" + ) + self.env[node] = _cute_arg(normalized.source, self.env) + return + case NormalizedSqueeze(): + lowered = lower_squeeze(node, normalized, self.env, self.store_sources) + if lowered is not None: + self.env[node] = lowered + self.propagate_physical_reduction(node, normalized.source) + return + case NormalizedSplit(): + lowered = lower_grouped_n_split( + node, normalized, self.env, self.kernel, self.grouped_tensors + ) + if lowered is not None: + self.env[node] = lowered + return + case NormalizedSelect(): + index = self.output_contraction_select_indices.get(node) + if index is not None: + self.env[node] = lower_grouped_n_select( + normalized, index, self.env, self.kernel + ) + return + case NormalizedGetItem(): + lowered = lower_getitem(node, normalized, self.env, self.store_sources) + if lowered is not None: + self.env[node] = lowered + self.propagate_physical_reduction(node, normalized.source) + return + case NormalizedPrepareSoftmax(): + self.env[node] = lower_prepare_softmax_online( + node, + normalized, + self.env, + self.kernel, + self.grouped_tensors, + self.store_sources, + ) + return + case NormalizedView(): + lowered = lower_view_or_reshape( + node, + normalized, + self.env, + self.kernel, + self.grouped_tensors, + self.active_grouped_layouts, + self.store_sources, + node is self.feed_main_input, + ) + if lowered is not None: + self.env[node] = lowered + self.propagate_physical_reduction(node, normalized.source) + return + case NormalizedReduction(): + self.bind_reduction( + node, + lower_tensorssa_reduce( + node, + normalized, + self.env, + self.kernel, + self.grouped_tensors, + self.store_sources, + self.physical_reductions, + ), + ) + return + case NormalizedUnsupportedReduction(): + raise local_reduce_unsupported_tensorssa_error( + normalized.target, value_only=True + ) + is_shape_preserving = is_shape_preserving_pointwise_node(node) + if is_shape_preserving and self.feed_main is None: + if self.aux is None and any( + arg in self.physical_reductions + for arg in iter_fx_node_inputs((node.args, node.kwargs)) + ): + raise NotImplementedError(LOCAL_REDUCE_POST_POINTWISE_FINALIZE_ERROR) + physical_finalize = self.compose_physical_finalize(node) + if physical_finalize is not None: + self.env[node] = physical_finalize + return + if self.lower_compact_inline_asm(node) or self.lower_pointwise_store(node): + return + node_args = tuple(_cute_arg(arg, self.env) for arg in node.args) + node_kwargs = { + key: _cute_arg(value, self.env) for key, value in node.kwargs.items() + } + self.env[node] = _cute_call(node, node_args, node_kwargs) + + def lower_graph(self) -> None: + """Lower body nodes in FX topological order.""" + for node in self.graph_module.graph.nodes: + if node is self.gemm or node.op in ("placeholder", "output"): + continue + if isinstance(node.meta.get("val"), (int, torch.SymInt)): + continue + with V.set_current_node(node): + if node.op != "call_function": + raise NotImplementedError( + f"unsupported FlexGEMM epilogue node: {node.format_node()}" + ) + self.lower_call_function(node) + + @staticmethod + def aux_result( + aux: torch.fx.Node | None, store_sources: dict[torch.fx.Node, Any] + ) -> Any | None: + """Return the compressed-aux expression or reject missing TensorSSA.""" + if aux is None: + return None + result = store_sources.get(aux) + if result is None: + raise NotImplementedError(LOCAL_REDUCE_AUX_TENSORSSA_ERROR) + return result + + def render(self) -> tuple[str, str]: + """Render the generated epilogue and physical callback source.""" + from torch._inductor.codegen.cutedsl._inline_asm import inline_asm_cache_key + + body = "\n".join(f" {line}" for line in self.kernel.body.lines) + if body: + body += "\n" + aux_args = [ + f"aux{index}" for index in range(len(self.epilogue_arg_placeholders)) + ] + feed_main_args = ( + [LOCAL_REDUCE_FEED_MAIN_ARG_NAME] if self.feed_main is not None else [] + ) + epilogue_params = ", ".join(["acc", *aux_args, *feed_main_args]) + result = _cute_arg(self.outputs.output, self.env) + aux_result = self.aux_result(self.aux, self.store_sources) + if self.outputs.aux_outputs or aux_result is not None: + tuple_items = [result] + tuple_items.extend( + _cute_arg(aux_output, self.env) + for aux_output in self.outputs.aux_outputs + ) + if aux_result is not None: + tuple_items.append(aux_result) + result = f"({', '.join(str(item) for item in tuple_items)})" + physical_reduction = ( + None + if self.local_reduce is None + else self.physical_reductions.get(self.local_reduce.match.value_node) + ) + physical_reduction_payload = ( + "" + if physical_reduction is None + else ( + f"\ncombine {physical_reduction.combine_expr}" + f"\nfinalize {physical_reduction.finalize_expr}" + ) + ) + key_payload = ( + f"inline_asm={inline_asm_cache_key()}\n" + f"fast_math={self.fast_math}\n{self.graph_module.code}\n" + f"{body}\nreturn {result}{physical_reduction_payload}" + ) + key = hashlib.sha256(key_payload.encode()).hexdigest()[:16] + name = f"flex_gemm_epilogue_{key}" + local_reduce_source = "" + if physical_reduction is not None: + combine_name = f"{name}{LOCAL_REDUCE_COMBINE_FN_SUFFIX}" + finalize_name = f"{name}{LOCAL_REDUCE_FINALIZE_FN_SUFFIX}" + local_reduce_source = ( + f"@cute.jit\ndef {combine_name}(lhs, rhs):\n" + f" return {physical_reduction.combine_expr}\n" + f"{combine_name}.__cache_key__ = lambda: {combine_name!r}\n\n" + f"@cute.jit\ndef {finalize_name}(value):\n" + f" return {physical_reduction.finalize_expr}\n" + f"{finalize_name}.__cache_key__ = lambda: {finalize_name!r}\n\n" + ) + return ( + name, + "import cutlass\n" + "import cutlass.cute as cute\n" + "import operator\n" + "from cutlass._mlir.dialects import math as mlir_math\n" + "from cutlass._mlir_helpers import math as cutlass_math\n" + "from torch._inductor.codegen.cutedsl._inline_asm import (\n" + " inline_asm_elementwise_intrinsic,\n" + ")\n\n" + f"{local_reduce_source}" + f"@cute.jit\ndef {name}({epilogue_params}):\n" + f"{body} return {result}\n", + ) + + def materialize(self) -> tuple[str, str]: + """Lower and render this epilogue under the CuTeDSL virtualized handlers.""" + with ( + V.set_kernel_handler(self.kernel), + V.set_ops_handler(FlexGemmCuteDSLOpOverrides()), + use_cutedsl_fast_math(self.fast_math), + ): + self.bind_epilogue_args() + self.lower_graph() + return self.render() + + +def materialize_flex_gemm_epilogue( + graph_module: torch.fx.GraphModule, + analysis: FlexGemmEpilogueAnalysis, + epilogue_arg_placeholders: tuple[torch.fx.Node, ...] = (), + *, + fast_math: bool = False, +) -> tuple[str, str]: + """Materialize an analyzed FlexGEMM body as generated CuTeDSL source. + + This is the code-generation entry point called by FlexGEMM lowering after + ``analyze_flex_gemm_epilogue`` has classified outputs and local-reduction + matches. The emitter visits the FX graph once in topological order while + owning the environment and reduction state needed across nodes. + + Args: + graph_module: FlexGEMM body graph containing the GEMM and epilogue nodes. + gemm_op: GEMM overload expected to occur exactly once in the body. + analysis: Shared output and local-reduction analysis for the graph. + epilogue_arg_placeholders: Captured tensor placeholders exposed as + generated epilogue parameters. + fast_math: Whether supported CuTeDSL math operations may use approximate + fast-math lowering. + + Returns: + The generated epilogue function name and complete CuTeDSL source. + """ + return FlexGemmEpilogueEmitter( + graph_module, + analysis, + epilogue_arg_placeholders, + fast_math=fast_math, + ).materialize() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/lowering.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/lowering.py new file mode 100644 index 0000000000000000000000000000000000000000..1f53138d4892a300707dd6588c76956cb6e28781 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/lowering.py @@ -0,0 +1,714 @@ +# mypy: allow-untyped-defs +"""Lower FlexGEMM HOP bodies and connect epilogue analysis to backend templates. + +``flex_gemm_lowering`` is the main entry point. Non-QUACK +requests execute the captured body through ordinary Inductor lowering. Although this +is stale and will fix up later on. See ``lower_quack_flex_gemm`` for the flow. +""" + +from __future__ import annotations + +from functools import partial +from typing import Any, TYPE_CHECKING + +import torch +import torch.utils._pytree as pytree +from torch._higher_order_ops.flex_gemm import ( + _SUPPORTED_FLEX_GEMM_OP_NAMES, + flex_gemm_hop, + FLEX_GEMM_OP_SPECS, +) +from torch._inductor import config +from torch.utils._ordered_set import OrderedSet + +from ... import ir +from ...ir import IRNode, TensorBox +from ...lowering import empty_strided, process_subgraph_nodes, register_lowering +from ...utils import ceildiv, has_free_symbols +from .constraints import ( + FLEX_GEMM_CHUNKED_CONTIGUOUS_B_ERROR, + flex_gemm_local_reduce_config_error, + FLEX_GEMM_OUTPUT_CONTRACTION_CAPTURE_ERROR, + FLEX_GEMM_OUTPUT_CONTRACTION_COMPOSITION_ERROR, + FlexGemmOutputContraction, + is_flex_gemm_partial_reduction_shape, + LOCAL_REDUCE_AUX_OUTPUT_CONTRACT_ERROR, + LOCAL_REDUCE_DENSE_MM_SCOPE_ERROR, + LOCAL_REDUCE_PARTIAL_OUTPUT_CONTRACT_ERROR, + output_contraction_capture_supported, + output_contraction_config_supported, + statically_known_shape_equal, + validate_flex_gemm_local_reduce_config, +) +from .debug import ( + format_flex_gemm_analysis, + format_flex_gemm_analysis_details, + format_flex_gemm_config_candidates, + format_flex_gemm_lowering_plan, + format_flex_gemm_problem, + format_flex_gemm_selection, + log_flex_gemm_artifact, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + +def decompose_nvgemm_additive_gemm(graph_module: torch.fx.GraphModule) -> None: + graph = graph_module.graph + changed = False + for node in list(graph.nodes): + if node.target not in ( + torch.ops.aten.addmm.default, + torch.ops.aten.baddbmm.default, + ): + continue + bias, mat1, mat2 = node.args[:3] + alpha = node.kwargs.get("alpha", 1.0) + beta = node.kwargs.get("beta", 1.0) + gemm_target = ( + torch.ops.aten.mm.default + if node.target is torch.ops.aten.addmm.default + else torch.ops.aten.bmm.default + ) + with graph.inserting_before(node): + result = graph.call_function(gemm_target, (mat1, mat2)) + if alpha != 1: + result = graph.call_function(torch.ops.aten.mul.Tensor, (result, alpha)) + if beta != 0: + if beta != 1: + bias = graph.call_function(torch.ops.aten.mul.Tensor, (bias, beta)) + result = graph.call_function(torch.ops.aten.add.Tensor, (result, bias)) + result.meta = node.meta + node.replace_all_uses_with(result) + graph.erase_node(node) + changed = True + if changed: + graph.eliminate_dead_code() + graph.lint() + graph_module.recompile() + + +def flex_gemm_tensor_placeholders( + graph_module: torch.fx.GraphModule, +) -> list[torch.fx.Node]: + """Return placeholders QuACK can bind as tensor epilogue arguments. + + FlexGEMM identifies the GEMM A/B inputs from the mm node, then treats the + remaining tensor-valued placeholders as closed-over epilogue tensors. Scalar + SymInt placeholders are shape values, not tensor arguments; the current QuACK + FlexGEMM entrypoint has no scalar epilogue-argument slots for them. + """ + return [ + node + for node in graph_module.graph.nodes + if node.op == "placeholder" and isinstance(node.meta.get("val"), torch.Tensor) + ] + + +def flex_gemm_epilogue_arg_placeholders( + graph_module: torch.fx.GraphModule, gemm_fx_node: torch.fx.Node +) -> tuple[torch.fx.Node, ...]: + """Find tensor inputs captured by epilogue loads, excluding GEMM operands.""" + gemm_placeholders = OrderedSet( + arg + for arg in pytree.tree_leaves((gemm_fx_node.args, gemm_fx_node.kwargs)) + if isinstance(arg, torch.fx.Node) + ) + return tuple( + node + for node in flex_gemm_tensor_placeholders(graph_module) + if node not in gemm_placeholders + ) + + +def infer_flex_gemm_epilogue_arg_kinds( + gemm_op: torch._ops.OpOverload, + epilogue_args: list[IRNode], + output_size: list[Any], +) -> tuple[str, ...]: + """Classify realized captured epilogue tensors for static wrapper kwargs.""" + if not epilogue_args: + return () + if gemm_op is not torch.ops.aten.mm.default: + raise NotImplementedError( + "FlexGEMM generated epilogues with captured tensor reads currently support only aten.mm" + ) + m, n = output_size[-2], output_size[-1] + epilogue_arg_kinds = [] + for epilogue_arg in epilogue_args: + epilogue_arg_size = epilogue_arg.get_size() + if statically_known_shape_equal(epilogue_arg_size, [1, 1]): + epilogue_arg_kinds.append("scalar") + elif statically_known_shape_equal(epilogue_arg_size, output_size): + epilogue_arg_kinds.append("tile") + elif statically_known_shape_equal(epilogue_arg_size, [1, n]): + epilogue_arg_kinds.append("row") + elif statically_known_shape_equal(epilogue_arg_size, [m, 1]): + epilogue_arg_kinds.append("col") + else: + raise NotImplementedError( + "FlexGEMM captured tensor epilogue args currently must match " + "the GEMM output shape or broadcast as [1, N] / [M, 1] / [1, 1]" + ) + return tuple(epilogue_arg_kinds) + + +def validate_flex_gemm_aux_outputs( + gemm_op: torch._ops.OpOverload, + aux_outputs: tuple[torch.fx.Node, ...], + output_size: list[Any], +) -> tuple[Any, ...]: + """Validate QUACK aux-output support and return fake tensor metadata.""" + if not aux_outputs: + return () + if gemm_op is not torch.ops.aten.mm.default: + raise NotImplementedError( + "FlexGEMM generic aux tuple epilogues currently support only aten.mm" + ) + aux_metas = [] + for aux_output in aux_outputs: + aux_meta = aux_output.meta.get("val") + if aux_meta is None: + raise NotImplementedError( + "FlexGEMM generic aux tuple epilogues require aux output metadata" + ) + aux_size = ir.convert_shape_to_inductor(aux_meta.shape) + if not statically_known_shape_equal(aux_size, output_size): + if is_flex_gemm_partial_reduction_shape(aux_size, output_size): + raise NotImplementedError(LOCAL_REDUCE_PARTIAL_OUTPUT_CONTRACT_ERROR) + raise NotImplementedError(LOCAL_REDUCE_AUX_OUTPUT_CONTRACT_ERROR) + aux_metas.append(aux_meta) + return tuple(aux_metas) + + +def allocate_flex_gemm_aux_outs( + aux_metas: tuple[Any, ...], mat1: TensorBox +) -> tuple[TensorBox, ...]: + """Allocate same-shape aux output buffers beside the main GEMM output.""" + return tuple( + empty_strided( + ir.convert_shape_to_inductor(aux_meta.shape), + ir.convert_shape_to_inductor(aux_meta.stride()), + dtype=aux_meta.dtype, + device=mat1.get_device_or_error(), + ) + for aux_meta in aux_metas + ) + + +def flex_gemm_ordered_outputs(result, aux_outs, local_reduce_outs, local_reduce_index): + """Return generated outputs in the user-visible tuple order.""" + match local_reduce_outs, local_reduce_index: + case (), _: + return (result, *aux_outs) + case (local_reduce_out,), None: + return (result, *aux_outs, local_reduce_out) + case (local_reduce_out,), index: + return ( + result, + *aux_outs[:index], + local_reduce_out, + *aux_outs[index:], + ) + case _: + raise AssertionError("FlexGEMM expects at most one local-reduce output") + + +def flex_gemm_local_reduce_metas(local_reduce) -> tuple[Any, ...]: + """Return metadata for the optional compressed local-reduce output.""" + if local_reduce is None or local_reduce.store is None: + return () + return (local_reduce.store.node.meta["val"],) + + +def flex_gemm_autotune_view_input(node: ir.ReinterpretView) -> torch.Tensor: + """Rebuild a logical view for Python-backed template benchmarks.""" + from torch._inductor.select_algorithm import ( + AlgorithmSelectorCache, + get_strides_with_layout_constraints, + ) + from torch._inductor.virtualized import V + + value = AlgorithmSelectorCache.benchmark_example_value(node) + base = value if value._base is None else value._base + sizevars = V.graph.sizevars + sizes = sizevars.optimization_hints(node.get_size()) + strides = sizevars.optimization_hints(get_strides_with_layout_constraints(node)) + offset = sizevars.optimization_hint(node.get_layout().offset) + return torch.as_strided(base, sizes, strides, offset) + + +def filter_gemm_configs( + configs: Sequence[Any], + predicate: Callable[[Any], bool], + *, + explicit_config: dict[str, Any] | None, + explicit_error: str, + inferred_error: str, +) -> tuple[Any, ...]: + """Filter configs while preserving explicit and inferred failure diagnostics.""" + supported = tuple(config for config in configs if predicate(config)) + if supported: + return supported + raise NotImplementedError( + explicit_error if explicit_config is not None else inferred_error + ) + + +def flex_gemm_config_keys( + device, + m: int, + n: int, + local_reduce_geometries: tuple[Any, ...], + tuned: bool, + output_contraction: FlexGemmOutputContraction | None = None, + explicit_config: dict[str, Any] | None = None, +) -> tuple[tuple[Any, ...], ...]: + """Select QuACK config keys after applying grouped-layout config constraints. + + Every grouped geometry constrains the config the same way, whether it backs + a runtime local-reduce plan or a plan-less grouped TensorSSA fragment + reshape in the generated epilogue: swap_ab reorients the accumulator + fragment and non-divisible tiles split groups across fragments. Output + contractions additionally require tile_n not to oversubscribe physical N and + a single CTA along N until QuACK predicates those layouts correctly. Explicit + config fields constrain the candidate set; untuned selection fills omitted + fields from the normal default, while tuned selection benchmarks the matches. + """ + if output_contraction is not None: + output_contraction.validate_quack(torch.cuda.get_device_capability(device)[0]) + if has_free_symbols((n,)): + raise NotImplementedError( + "FlexGEMM output contractions require statically known physical N" + ) + + from torch._inductor.heuristics.template.flex_gemm import ( + candidate_gemm_configs_for_device, + default_gemm_config_key, + explicit_gemm_configs_for_device, + gemm_config_from_key, + gemm_config_key, + ) + + candidate_configs = ( + candidate_gemm_configs_for_device(device) + if explicit_config is None + else explicit_gemm_configs_for_device(explicit_config, device) + ) + if not tuned: + default_key = default_gemm_config_key(device, m, n, candidate_configs) + default_config = gemm_config_from_key(default_key) + if all( + validate_flex_gemm_local_reduce_config( + default_config, geometry.group, geometry.axis + ) + for geometry in local_reduce_geometries + ) and ( + output_contraction is None + or output_contraction_config_supported(default_config, n) + ): + return (default_key,) + + configs = candidate_configs + if output_contraction is not None: + configs = filter_gemm_configs( + configs, + lambda config: output_contraction_config_supported(config, n), + explicit_config=explicit_config, + explicit_error=( + "FlexGEMM explicit QUACK config constraints are incompatible with " + "output contraction" + ), + inferred_error=( + "FlexGEMM output contraction physical N is smaller than every " + "validated QuACK tile_n" + ), + ) + for geometry in local_reduce_geometries: + configs = filter_gemm_configs( + configs, + lambda config: validate_flex_gemm_local_reduce_config( + config, geometry.group, geometry.axis + ), + explicit_config=explicit_config, + explicit_error=( + "FlexGEMM explicit QUACK config constraints are incompatible with " + f"local reduction group={geometry.group}, axis={geometry.axis}" + ), + inferred_error=flex_gemm_local_reduce_config_error( + candidate_configs, + geometry.group, + geometry.axis, + ), + ) + if tuned: + return tuple(gemm_config_key(config) for config in configs) + return (gemm_config_key(configs[0]),) + + +def lower_quack_flex_gemm(gemm_op, subgraph, args, gemm_kwargs, kernel_options): + """Lower FlexGEMM through the generated QUACK CuTeDSL template. + + The current pipeline is: + + :: + + FlexGEMM HOP body (FX GraphModule) + | + v + find GEMM operands and captured epilogue args + | + v + analyze_flex_gemm_epilogue() + | + +--> output plan + buffer ABI + | `--> derive layout + allocate aux + | + +--> grouped/reduction geometry + | `--> filter QuACK configurations + | + `--> materialize_flex_gemm_epilogue() + `--> CuTeDSL epilogue + callbacks + | + v + combine into template choices -> autotune + | + v + restore captured output order + """ + if gemm_op not in FLEX_GEMM_OP_SPECS: + raise NotImplementedError( + f"FlexGEMM QUACK backend currently supports only aten.{_SUPPORTED_FLEX_GEMM_OP_NAMES}" + ) + tuned = kernel_options.get("tuned", False) + fast_math = kernel_options.get("fast_math", False) + explicit_config = kernel_options.get("config") + unsupported_options = OrderedSet(kernel_options) - OrderedSet( + ["backend", "tuned", "fast_math", "config"] + ) + if unsupported_options: + raise NotImplementedError( + f"unsupported FlexGEMM kernel options: {sorted(unsupported_options)}" + ) + if not isinstance(fast_math, bool): + raise NotImplementedError("FlexGEMM fast_math kernel option must be bool") + if "config" in kernel_options and not isinstance(explicit_config, dict): + raise NotImplementedError("FlexGEMM config kernel option must be a dict") + + from torch._inductor.kernel.flex_gemm.fx_cutedsl_codegen import ( + analyze_flex_gemm_epilogue, + gemm_node as flex_gemm_node, + materialize_flex_gemm_epilogue, + ) + from torch._inductor.kernel.flex_gemm.template import ( + flex_gemm_epilogue_template, + FlexGemmEpilogueConfig, + FlexGemmEpilogueLocalReduceConfig, + FlexGemmEpilogueOutputConfig, + ) + from torch._inductor.select_algorithm import autotune_select_algorithm + + op_spec = FLEX_GEMM_OP_SPECS[gemm_op] + mat1_index, mat2_index = op_spec.mat1_index, op_spec.mat2_index + unsupported_gemm_kwargs = OrderedSet(gemm_kwargs) - OrderedSet(["alpha", "beta"]) + if unsupported_gemm_kwargs: + raise NotImplementedError( + f"unsupported FlexGEMM GEMM kwargs: {sorted(unsupported_gemm_kwargs)}" + ) + gemm_fx_node = flex_gemm_node(subgraph.graph_module, gemm_op) + placeholders = [ + node for node in subgraph.graph_module.graph.nodes if node.op == "placeholder" + ] + placeholder_args = dict(zip(placeholders, args, strict=True)) + gemm_args: list[TensorBox] = [] + for arg in gemm_fx_node.args: + gemm_arg = placeholder_args[arg] if isinstance(arg, torch.fx.Node) else arg + if not isinstance(gemm_arg, TensorBox): + raise NotImplementedError("FlexGEMM lowering expects tensor GEMM operands") + gemm_args.append(gemm_arg) + epilogue_arg_placeholders = flex_gemm_epilogue_arg_placeholders( + subgraph.graph_module, gemm_fx_node + ) + epilogue_args: list[TensorBox] = [] + for arg in epilogue_arg_placeholders: + epilogue_arg = placeholder_args[arg] + if not isinstance(epilogue_arg, TensorBox): + raise NotImplementedError( + "FlexGEMM lowering expects tensor epilogue operands" + ) + epilogue_args.append(epilogue_arg) + alpha = gemm_fx_node.kwargs.get("alpha", gemm_kwargs.get("alpha", 1.0)) + beta = gemm_fx_node.kwargs.get("beta", gemm_kwargs.get("beta", 1.0)) + if not isinstance(alpha, (int, float)) or not isinstance(beta, (int, float)): + raise NotImplementedError("FlexGEMM alpha/beta must be static scalars") + gemm_input_names = tuple( + arg.name if isinstance(arg, torch.fx.Node) else f"gemm_arg{index}" + for index, arg in enumerate(gemm_fx_node.args) + ) + problem_report = partial( + format_flex_gemm_problem, + subgraph.graph_module, + gemm_op, + tuple(zip(gemm_input_names, gemm_args, strict=True)), + tuple( + zip( + (node.name for node in epilogue_arg_placeholders), + epilogue_args, + strict=True, + ) + ), + alpha=float(alpha), + beta=float(beta), + tuned=tuned, + fast_math=fast_math, + explicit_config=explicit_config, + ) + log_flex_gemm_artifact( + "problem", + problem_report, + lowering_name=subgraph.name, + ) + # This is where we figure out what the fx-graph body is doing + epilogue_analysis = analyze_flex_gemm_epilogue(subgraph.graph_module, gemm_fx_node) + log_flex_gemm_artifact( + "analysis", + lambda: format_flex_gemm_analysis(epilogue_analysis), + lowering_name=subgraph.name, + ) + log_flex_gemm_artifact( + "analysis_details", + lambda: format_flex_gemm_analysis_details(epilogue_analysis), + lowering_name=subgraph.name, + verbose=True, + ) + outputs = epilogue_analysis.outputs + if ( + epilogue_analysis.required_geometries + and gemm_op is not torch.ops.aten.mm.default + ): + error = ( + FLEX_GEMM_OUTPUT_CONTRACTION_COMPOSITION_ERROR + if outputs.output_contraction is not None + else LOCAL_REDUCE_DENSE_MM_SCOPE_ERROR + ) + raise NotImplementedError(error) + local_reduce_store = ( + None if outputs.local_reduce is None else outputs.local_reduce.store + ) + output_meta = outputs.output.meta.get("val") + if output_meta is None: + raise NotImplementedError( + "FlexGEMM generated epilogues require output metadata" + ) + output_storage = outputs.output_storage + output_storage_dtype = ( + output_meta.dtype + if output_storage is None + else output_storage.meta["val"].dtype + ) + logical_output_size = ir.convert_shape_to_inductor(output_meta.shape) + physical_output_size = [ + *gemm_args[mat1_index].get_size()[:-1], + gemm_args[mat2_index].get_size()[-1], + ] + output_contraction = outputs.output_contraction + if ( + output_contraction is not None + and output_contraction.chunked + and gemm_args[mat2_index].get_stride()[-1] == 1 + ): + raise NotImplementedError(FLEX_GEMM_CHUNKED_CONTIGUOUS_B_ERROR) + aux_metas = validate_flex_gemm_aux_outputs( + gemm_op, outputs.aux_outputs, physical_output_size + ) + local_reduce_metas = flex_gemm_local_reduce_metas(outputs.local_reduce) + output_stride = ir.convert_shape_to_inductor(output_meta.stride()) + if output_contraction is not None: + # Output contractions use TMA stores with 16-byte-aligned outer strides. + output_alignment = max(16 // output_storage_dtype.itemsize, 1) + output_stride[-2] = ( + ceildiv(logical_output_size[-1], output_alignment) * output_alignment + ) + layout = ir.FixedLayout( + gemm_args[mat1_index].get_device_or_error(), + output_storage_dtype, + logical_output_size, + output_stride, + ) + gemm_input_nodes = [ + ir.TemplateBuffer.realize_template_input(arg) for arg in gemm_args + ] + epilogue_input_nodes = [ + ir.TemplateBuffer.realize_template_input(arg) for arg in epilogue_args + ] + aux_outs = allocate_flex_gemm_aux_outs(aux_metas, gemm_args[mat1_index]) + local_reduce_outs = allocate_flex_gemm_aux_outs( + local_reduce_metas, gemm_args[mat1_index] + ) + aux_input_nodes = [ + ir.TemplateBuffer.realize_template_input(aux_out) for aux_out in aux_outs + ] + local_reduce_input_nodes = [ + ir.TemplateBuffer.realize_template_input(local_reduce_out) + for local_reduce_out in local_reduce_outs + ] + input_nodes = [ + *gemm_input_nodes, + *epilogue_input_nodes, + *aux_input_nodes, + *local_reduce_input_nodes, + ] + mutated_input_nodes = aux_input_nodes + local_reduce_input_nodes + aux_out_start = len(gemm_input_nodes) + len(epilogue_input_nodes) + aux_out_indices = tuple(range(aux_out_start, aux_out_start + len(aux_input_nodes))) + local_reduce_out_index = ( + aux_out_start + len(aux_input_nodes) if local_reduce_input_nodes else None + ) + epilogue_arg_kinds = infer_flex_gemm_epilogue_arg_kinds( + gemm_op, epilogue_input_nodes, physical_output_size + ) + if output_contraction is not None and any( + not output_contraction_capture_supported(kind, arg.get_dtype() is torch.bool) + for arg, kind in zip(epilogue_input_nodes, epilogue_arg_kinds, strict=True) + ): + raise NotImplementedError(FLEX_GEMM_OUTPUT_CONTRACTION_CAPTURE_ERROR) + log_flex_gemm_artifact( + "lowering_plan", + lambda: format_flex_gemm_lowering_plan( + logical_output_size, + physical_output_size, + output_meta.dtype, + tuple( + zip( + (node.name for node in epilogue_arg_placeholders), + epilogue_arg_kinds, + strict=True, + ) + ), + aux_metas, + local_reduce_metas, + ), + lowering_name=subgraph.name, + ) + template_local_reduce = FlexGemmEpilogueLocalReduceConfig.from_output_plan( + outputs.local_reduce, local_reduce_out_index + ) + epilogue_name, epilogue_source = materialize_flex_gemm_epilogue( + subgraph.graph_module, + epilogue_analysis, + epilogue_arg_placeholders, + fast_math=fast_math, + ) + log_flex_gemm_artifact( + "generated_epilogue", + lambda: epilogue_source.strip(), + lowering_name=subgraph.name, + verbose=True, + ) + quack_config_keys = flex_gemm_config_keys( + layout.device, + gemm_args[mat1_index].get_size()[-2], + gemm_args[mat2_index].get_size()[-1], + epilogue_analysis.required_geometries, + tuned, + output_contraction, + explicit_config, + ) + log_flex_gemm_artifact( + "config_candidates", + lambda: format_flex_gemm_config_candidates(quack_config_keys), + lowering_name=subgraph.name, + verbose=True, + ) + epilogue_arg_indices = tuple( + range( + len(gemm_input_nodes), + len(gemm_input_nodes) + len(epilogue_input_nodes), + ) + ) + choices: list[Any] = [] + choice_config_keys = {} + for quack_config_key in quack_config_keys: + choice_start = len(choices) + error = flex_gemm_epilogue_template.maybe_append_choice( + choices, + input_nodes=input_nodes, + layout=layout, + mutated_inputs=mutated_input_nodes or None, + config=FlexGemmEpilogueConfig( + epilogue_name=epilogue_name, + epilogue_source=epilogue_source, + gemm_op=op_spec, + alpha=float(alpha), + beta=float(beta), + quack_config_key=quack_config_key, + epilogue_arg_indices=epilogue_arg_indices, + epilogue_arg_kinds=epilogue_arg_kinds, + outputs=FlexGemmEpilogueOutputConfig( + aux_out_indices=aux_out_indices, + local_reduce=template_local_reduce, + output_contraction=output_contraction, + ), + ), + ) + if error is not None: + raise error + choice_config_keys.update( + (choice.name, quack_config_key) for choice in choices[choice_start:] + ) + input_gen_fns = { + index: flex_gemm_autotune_view_input + for index, input_node in enumerate(input_nodes) + if isinstance(input_node, ir.ReinterpretView) + } + result, selected_choice = autotune_select_algorithm( + "flex_gemm_epilogue", + choices, + input_nodes, + layout, + input_gen_fns=input_gen_fns or None, + **({"return_multi_template": False} if mutated_input_nodes else {}), + ) + if output_storage is not None and output_storage_dtype is not output_meta.dtype: + result = TensorBox(ir.DtypeView.create(result, output_meta.dtype)) + selected_config_key = ( + None + if selected_choice is None + else choice_config_keys.get(selected_choice.name) + ) + log_flex_gemm_artifact( + "selection", + lambda: format_flex_gemm_selection( + selected_choice, + selected_config_key, + candidate_count=len(quack_config_keys), + tuned=tuned, + ), + lowering_name=subgraph.name, + ) + return flex_gemm_ordered_outputs( + result, + aux_outs, + local_reduce_outs, + None if local_reduce_store is None else local_reduce_store.aux_index, + ) + + +@register_lowering(flex_gemm_hop, type_promotion_kind=None) +def flex_gemm_lowering(gemm_op, subgraph, args, gemm_kwargs, kernel_options): + """Dispatch FlexGEMM to ordinary Inductor lowering or the QUACK template.""" + backend = kernel_options.get("backend", "TRITON") + if backend == "NVGEMM": + decompose_nvgemm_additive_gemm(subgraph.graph_module) + with config.patch( + max_autotune=True, + max_autotune_gemm_backends="NVGEMM", + ): + return process_subgraph_nodes(subgraph.graph_module, list(args)) + if backend == "QUACK": + return lower_quack_flex_gemm( + gemm_op, subgraph, args, gemm_kwargs, kernel_options + ) + return process_subgraph_nodes(subgraph.graph_module, list(args)) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/quack_reductions.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/quack_reductions.py new file mode 100644 index 0000000000000000000000000000000000000000..d9a0a1da280629d15a382b3203555f67ec3f9a7e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/quack_reductions.py @@ -0,0 +1,481 @@ +# mypy: allow-untyped-defs +"""Lower FlexGEMM grouped local reductions into QuACK/CuTeDSL epilogues. + +FlexGEMM recognizes a narrow local-reduction contract inside the GEMM output +tile: an epilogue reshapes the accumulator to expose contiguous groups along M +or N, then reduces only that grouped dimension. N-axis groups up to one 32-lane +fragment lower as ordinary in-fragment TensorSSA reductions; larger N groups +produce TensorSSA partials that QuACK combines physically. +M-axis groups currently always use QuACK's physical row-lane/warp combine path, +even when the group is small enough to fit in one fragment. Inductor owns FX +normalization and output contracts; these helpers describe the supported +TensorSSA shapes and generated combine/finalize expressions QuACK needs. + +The main caller is ``materialize_flex_gemm_epilogue`` in ``fx_cutedsl_codegen.py``. +Shared GEMM epilogue analysis recognizes grouped layouts and reductions; +materialization wraps accepted geometries in ``GroupedTensorSSALayout`` and +routes FX nodes through ``lower_view_or_reshape``, +``lower_prepare_softmax_online``, and ``lower_tensorssa_reduce``. +""" + +import dataclasses +import math +from typing import Any, cast + +import torch +from torch._inductor.codegen.cutedsl.cutedsl_op_overrides import ( + CuteDSLOpOverrides, + tensorssa_reduction, +) +from torch._inductor.kernel.flex_gemm.constraints import ( + LOCAL_REDUCE_EXPLICIT_DTYPE_ERROR, + LOCAL_REDUCE_INNERMOST_GROUPED_DIM_ERROR, + LOCAL_REDUCE_PARTIAL_OUTPUT_CONTRACT_ERROR, +) +from torch._inductor.kernel.gemm_epilogue import ( + GemmReductionGeometry, + iter_fx_node_inputs, + NormalizedGetItem, + NormalizedPrepareSoftmax, + NormalizedReduction, + NormalizedSelect, + NormalizedSplit, + NormalizedSqueeze, + NormalizedView, +) +from torch._inductor.kernel.gemm_epilogue_utils import normalize_shape +from torch._inductor.ops_handler import ReductionType +from torch._inductor.shape_propagation import get_broadcasted_shape +from torch._inductor.virtualized import V +from torch.utils._ordered_set import OrderedSet + + +@dataclasses.dataclass(frozen=True) +class GroupedTensorSSALayout(GemmReductionGeometry): + """Describe a grouped M/N TensorSSA view inside the generated epilogue.""" + + def fragment_group_size_expr(self, source: Any) -> str: + """Return the local group size available in this epilogue fragment.""" + return ( + f"cutlass.const_expr(min({self.group_size}, " + f"cute.size({source}.shape, mode=[0])))" + ) + + def fragment_repeat_expr(self, source: Any) -> str: + """Return the repeat count needed to cover the current epilogue fragment.""" + return ( + f"cutlass.const_expr(cute.size({source}.shape, mode=[0]) " + f"// min({self.group_size}, cute.size({source}.shape, mode=[0])))" + ) + + def tensorssa_shape(self, source: Any) -> str: + fragment_group_size = self.fragment_group_size_expr(source) + repeats = self.fragment_repeat_expr(source) + if self.axis == 1: + return f"((1, {fragment_group_size}, {repeats}), 1, 1)" + return f"(({fragment_group_size}, 1, {repeats}), 1, 1)" + + def keepdim_shape(self, source: Any) -> str: + return f"((1, 1, {self.fragment_repeat_expr(source)}), 1, 1)" + + @property + def needs_physical_combine(self) -> bool: + return self.needs_physical_callbacks + + @property + def reduction_profile(self) -> str: + if self.axis == 1: + return "((None, 1, None), 1, 1)" + return "((1, None, None), 1, 1)" + + +def _cute_op_name(target: Any) -> str | None: + if isinstance(target, torch._ops.OpOverload): + op_name = target.overloadpacket.__name__ + elif isinstance(target, str): + op_name = target + else: + op_name = target.__name__ if callable(target) else None + return "truediv" if op_name == "div" else op_name + + +@dataclasses.dataclass(frozen=True) +class FlexGemmPhysicalReduction: + """Describe QuACK's physical combine/finalize callback for local reductions.""" + + combine_expr: str + finalize_expr: str = "value" + + +FLEX_GEMM_POINTWISE_OP_NAMES = frozenset( + ( + "_to_copy", + "clamp", + "clamp_max", + "clamp_min", + "convert_element_type", + "inline_asm_elementwise", + ) +) + + +def _cute_arg(value: Any, env: dict[torch.fx.Node, Any]) -> Any: + """Translate FX node references and constants into CuTeDSL epilogue values.""" + if isinstance(value, torch.fx.Node): + if value in env: + return env[value] + raise NotImplementedError( + f"unsupported FlexGEMM epilogue dependency: {value.format_node()}" + ) + if isinstance(value, float) and not math.isfinite(value): + if math.isnan(value): + return 'float("nan")' + return 'float("inf")' if value > 0 else 'float("-inf")' + if isinstance( + value, + ( + int, + float, + bool, + str, + torch.dtype, + torch.device, + torch.layout, + torch.memory_format, + ), + ): + return value + if isinstance(value, (tuple, list)): + return type(value)(_cute_arg(item, env) for item in value) + raise NotImplementedError(f"unsupported FlexGEMM epilogue constant: {value!r}") + + +def _generate_like( + kernel: Any, expr: str, ref: Any, shape_ref: Any | None = None +) -> Any: + """Emit CuTeDSL while preserving dtype and shape metadata from references.""" + if shape_ref is None: + shape_ref = ref + return kernel.cse.generate( + kernel.body, + expr, + dtype=getattr(ref, "dtype", None), + shape=getattr(shape_ref, "shape", None), + ) + + +def _keepdim_and_broadcast( + kernel: Any, reduced: Any, layout: GroupedTensorSSALayout, source: Any +) -> tuple[Any, Any]: + """Materialize keepdim and store-shaped forms of a grouped reduction.""" + keepdim_source = _generate_like( + kernel, f"{reduced}.reshape({layout.keepdim_shape(source)})", reduced + ) + return keepdim_source, _generate_like( + kernel, f"{keepdim_source}.broadcast_to({source}.shape)", keepdim_source, source + ) + + +def _cute_call( + node: torch.fx.Node, + args: tuple[Any, ...], + kwargs: dict[str, Any], +) -> Any: + """Lower one FX call through the active CuTeDSL operations handler.""" + target = node.target + op_name = _cute_op_name(target) + if op_name is None: + raise NotImplementedError(f"unsupported FlexGEMM epilogue op: {target}") + if op_name == "inline_asm_elementwise": + # The HOP spells the asm text `asm_str`; the ops handler spells it `asm`. + kwargs = dict(kwargs) + kwargs["asm"] = kwargs.pop("asm_str") + input_values = [] + for input_node in node.args[: len(args)]: + value = ( + input_node.meta.get("val") + if isinstance(input_node, torch.fx.Node) + else None + ) + if not isinstance(value, torch.Tensor): + raise NotImplementedError( + "FlexGEMM inline asm inputs require tensor metadata" + ) + input_values.append(value) + kwargs["input_dtypes"] = tuple(value.dtype for value in input_values) + kwargs["scalar_sources"] = tuple( + all(isinstance(dim, int) and dim == 1 for dim in value.shape) + for value in input_values + ) + try: + op = getattr(V.get_ops_handler(), op_name) + except AttributeError: + raise NotImplementedError( + f"unsupported FlexGEMM epilogue op: {target}" + ) from None + return op(*args, **kwargs) + + +def _local_reduce_store_arg( + value: Any, env: dict[torch.fx.Node, Any], sources: dict[torch.fx.Node, Any] +) -> Any: + if isinstance(value, torch.fx.Node) and value in sources: + return sources[value] + if isinstance(value, (tuple, list)): + return type(value)( + _local_reduce_store_arg(item, env, sources) for item in value + ) + return _cute_arg(value, env) + + +def tensor_meta_shape(node: torch.fx.Node) -> tuple[Any, ...] | None: + """Return fake-tensor shape metadata when the FX value is tensor-like.""" + meta = node.meta.get("val") + if isinstance(meta, torch.Tensor): + return tuple(meta.shape) + return None + + +def node_preserves_tensor_shapes(node: torch.fx.Node) -> bool: + """Reject pointwise broadcasts that cannot preserve a grouped TensorSSA input.""" + output_shape = tensor_meta_shape(node) + if output_shape is None: + return False + output_shape_key = tuple(str(dim) for dim in output_shape) + has_same_shape_input = False + for input_node in iter_fx_node_inputs((node.args, node.kwargs)): + input_shape = tensor_meta_shape(input_node) + if input_shape is None: + continue + input_shape_key = tuple(str(dim) for dim in input_shape) + if input_shape_key == output_shape_key: + has_same_shape_input = True + continue + try: + broadcast_shape = get_broadcasted_shape(input_shape_key, output_shape_key) + except AssertionError: + return False + if broadcast_shape is None or tuple(broadcast_shape) != output_shape_key: + return False + return has_same_shape_input + + +def is_pointwise_node(node: torch.fx.Node) -> bool: + if node.op != "call_function": + return False + return ( + isinstance(node.target, torch._ops.OpOverload) + and torch.Tag.pointwise in node.target.tags + ) or _cute_op_name(node.target) in FLEX_GEMM_POINTWISE_OP_NAMES + + +def is_shape_preserving_pointwise_node(node: torch.fx.Node) -> bool: + return is_pointwise_node(node) and node_preserves_tensor_shapes(node) + + +def lower_view_or_reshape( + node: torch.fx.Node, + normalized: NormalizedView, + env: dict[torch.fx.Node, Any], + kernel: Any, + grouped_tensors: dict[torch.fx.Node, GroupedTensorSSALayout], + active_grouped_layouts: OrderedSet[GroupedTensorSSALayout], + local_reduce_store_sources: dict[torch.fx.Node, Any], + preserve_value_layout: bool = False, +) -> Any | None: + """Emit an analyzed view using grouped provenance.""" + source_node = normalized.source + if source_node in local_reduce_store_sources: + local_reduce_store_sources[node] = local_reduce_store_sources[source_node] + return _cute_arg(source_node, env) + source = _cute_arg(source_node, env) + grouped_layout = grouped_tensors.get(node) + if grouped_layout is not None: + if preserve_value_layout or grouped_layout not in active_grouped_layouts: + return source + return _generate_like( + kernel, + f"{source}.reshape({grouped_layout.tensorssa_shape(source)})", + source, + ) + if source_node in grouped_tensors: + return source + return None + + +def lower_grouped_n_split( + node: torch.fx.Node, + normalized: NormalizedSplit, + env: dict[torch.fx.Node, Any], + kernel: Any, + grouped_tensors: dict[torch.fx.Node, GroupedTensorSSALayout], +) -> tuple[Any, ...] | None: + """Split an analyzed output contraction into grouped TensorSSA values.""" + layout = grouped_tensors.get(node) + if layout is None or layout.axis != 1: + return None + source = _cute_arg(normalized.source, env) + grouped = _generate_like( + kernel, f"{source}.reshape({layout.tensorssa_shape(source)})", source + ) + return tuple( + _generate_like( + kernel, + f"{grouped}[((0, {index}, None), None, None)]", + grouped, + ) + for index in range(layout.group) + ) + + +def lower_grouped_n_select( + normalized: NormalizedSelect, + index: int, + env: dict[torch.fx.Node, Any], + kernel: Any, +) -> Any: + """Select one analysis-validated output-contraction group value.""" + source = _cute_arg(normalized.source, env) + return _generate_like( + kernel, + f"{source}[((0, {index}, None), None, None)]", + source, + ) + + +def lower_full_scalar(node: torch.fx.Node) -> Any | None: + if node.op != "call_function" or node.target is not torch.ops.aten.full.default: + return None + shape = normalize_shape(node.args[0]) + if shape != (): + return None + value = node.args[1] + return value if isinstance(value, (bool, int, float)) else None + + +def lower_squeeze( + node: torch.fx.Node, + normalized: NormalizedSqueeze, + env: dict[torch.fx.Node, Any], + local_reduce_store_sources: dict[torch.fx.Node, Any], +) -> Any | None: + """Forward an analyzed squeeze alias.""" + source_node = normalized.source + if source_node not in env: + return None + if source_node in local_reduce_store_sources: + local_reduce_store_sources[node] = local_reduce_store_sources[source_node] + return _cute_arg(source_node, env) + + +def lower_getitem( + node: torch.fx.Node, + normalized: NormalizedGetItem, + env: dict[torch.fx.Node, Any], + local_reduce_store_sources: dict[torch.fx.Node, Any], +) -> Any | None: + """Index an analyzed aggregate value.""" + source_node, index = normalized.source, normalized.index + source = _cute_arg(source_node, env) + if not isinstance(source, (tuple, list)) or not -len(source) <= index < len(source): + return None + if source_node in local_reduce_store_sources: + local_reduce_store_sources[node] = local_reduce_store_sources[source_node][ + index + ] + return source[index] + + +def lower_prepare_softmax_online( + node: torch.fx.Node, + normalized: NormalizedPrepareSoftmax, + env: dict[torch.fx.Node, Any], + kernel: Any, + grouped_tensors: dict[torch.fx.Node, GroupedTensorSSALayout], + local_reduce_store_sources: dict[torch.fx.Node, Any], +) -> Any: + """Lower analyzed online-softmax preparation.""" + input_node, dim = normalized.source, normalized.dim + if input_node not in grouped_tensors: + raise NotImplementedError(LOCAL_REDUCE_PARTIAL_OUTPUT_CONTRACT_ERROR) + layout = grouped_tensors[input_node] + if layout.needs_physical_callbacks: + raise NotImplementedError( + "unsupported FlexGEMM physical local reduction: prepare_softmax_online " + "needs a multi-value generated physical reducer" + ) + if not layout.matches_reduction_dim(dim): + raise NotImplementedError( + "unsupported FlexGEMM epilogue local reduction: prepare_softmax_online " + "currently supports only the grouped dimension" + ) + source = _cute_arg(input_node, env) + max_reduced = _generate_like( + kernel, + f'{source}.reduce(cute.ReductionOp.MAX, init_val=float("-inf"), reduction_profile={layout.reduction_profile})', + source, + ) + _, max_store = _keepdim_and_broadcast(kernel, max_reduced, layout, source) + centered = _generate_like(kernel, f"({source} - {max_store})", source) + exp_centered = CuteDSLOpOverrides.exp(centered) + sum_reduced = _generate_like( + kernel, + f"{exp_centered}.reduce(cute.ReductionOp.ADD, init_val=0.0, reduction_profile={layout.reduction_profile})", + exp_centered, + ) + _, sum_store = _keepdim_and_broadcast(kernel, sum_reduced, layout, source) + local_reduce_store_sources[node] = (max_store, sum_store) + return max_store, sum_store + + +def lower_tensorssa_reduce( + node: torch.fx.Node, + normalized: NormalizedReduction, + env: dict[torch.fx.Node, Any], + kernel: Any, + grouped_tensors: dict[torch.fx.Node, GroupedTensorSSALayout], + local_reduce_store_sources: dict[torch.fx.Node, Any], + local_reduce_physical_reductions: dict[torch.fx.Node, FlexGemmPhysicalReduction], +) -> Any: + """Lower an analyzed reduction while deferring physical finalization.""" + input_node = normalized.source + dim = normalized.dim + keepdim = normalized.keepdim + dtype = normalized.dtype + reduction_type = normalized.reduction_type + if dtype is not None: + raise NotImplementedError(LOCAL_REDUCE_EXPLICIT_DTYPE_ERROR) + if input_node not in grouped_tensors: + raise NotImplementedError(LOCAL_REDUCE_PARTIAL_OUTPUT_CONTRACT_ERROR) + layout = grouped_tensors[input_node] + if not layout.matches_reduction_dim(dim): + raise NotImplementedError(LOCAL_REDUCE_INNERMOST_GROUPED_DIM_ERROR) + reduction_name = cast( + ReductionType, "sum" if reduction_type == "mean" else reduction_type + ) + desc = tensorssa_reduction(reduction_name) + finalize_expr = f"value / {layout.group}.0" if reduction_type == "mean" else "value" + source = _cute_arg(input_node, env) + needs_physical_callbacks = layout.needs_physical_callbacks + if needs_physical_callbacks: + local_reduce_physical_reductions[node] = FlexGemmPhysicalReduction( + desc.combine_expr, finalize_expr + ) + if layout.axis == 0: + local_reduce_store_sources[node] = source + return source + reduced = _generate_like( + kernel, + f"{source}.reduce({desc.cute_op}, init_val={desc.init_val}, reduction_profile={layout.reduction_profile})", + source, + ) + if reduction_type == "mean" and not needs_physical_callbacks: + reduced = _generate_like( + kernel, f"{reduced} / {float(layout.group)!r}", reduced + ) + keepdim_source, local_reduce_store_sources[node] = _keepdim_and_broadcast( + kernel, reduced, layout, source + ) + if keepdim: + return keepdim_source + return reduced diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/runtime.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..b2485ff2e5f0aaccdb25aca21fe9a73f2b14d4ba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/runtime.py @@ -0,0 +1,680 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import contextlib +import dataclasses +import os +from typing import Any, TYPE_CHECKING + +import torch +from torch._inductor.kernel.flex_gemm.constraints import ( + FLEX_GEMM_CHUNKED_CONTIGUOUS_B_ERROR, + FLEX_GEMM_OUTPUT_CONTRACTION_CAPTURE_ERROR, + FLEX_GEMM_OUTPUT_CONTRACTION_COMPOSITION_ERROR, + FLEX_GEMM_OUTPUT_CONTRACTION_SHAPE_ERROR, + FlexGemmLocalReduceCallbacks, + FlexGemmLocalReduceGeometry, + FlexGemmOutputContraction, + LOCAL_REDUCE_CALLBACKS_REQUIRED_ERROR, + LOCAL_REDUCE_COMBINE_KEY_SUFFIX, + local_reduce_compressed_shape, + LOCAL_REDUCE_FINALIZE_KEY_SUFFIX, + LOCAL_REDUCE_RUNTIME_OUT_ERROR, + LOCAL_REDUCE_SWAP_AB_ERROR, + output_contraction_capture_supported, + output_contraction_config_supported, + validate_local_reduce_feed_main_capability, + validate_local_reduce_no_c_alpha_beta, + validate_local_reduce_out_shape, + validate_local_reduce_runtime_dense_mm, + validate_local_reduce_selected_dim_divisible, +) +from torch._inductor.runtime.cache_dir_utils import cache_dir +from torch._prims_common import is_expandable_to + + +if TYPE_CHECKING: + from torch._inductor.heuristics.template.flex_gemm import GemmConfigKey + + +# swap_ab transposes the dispatched GEMM, so a row broadcast becomes a col +# broadcast (and vice versa) while tile broadcasts only transpose their data and +# scalars are orientation-invariant. +_SWAPPED_ARG_KIND = {"row": "col", "col": "row", "tile": "tile", "scalar": "scalar"} + + +def inductor_quack_cache_dir() -> str: + """Return the Inductor-owned QuACK cache root for generated FlexGEMM.""" + return os.path.join(cache_dir(), "quack") + + +def check_matrix( + name: str, tensor: torch.Tensor, expected_ndim: int | None = None +) -> None: + """Require a CUDA matrix operand with optional generated-op rank checking.""" + if expected_ndim is not None and tensor.ndim != expected_ndim: + raise RuntimeError( + f"FlexGEMM expected {expected_ndim}-D {name}, got {tensor.ndim}-D" + ) + if tensor.ndim not in (2, 3): + raise NotImplementedError(f"FlexGEMM currently supports only 2-D or 3-D {name}") + if not tensor.is_cuda: + raise RuntimeError(f"FlexGEMM requires CUDA {name}") + + +def check_same_device(a: torch.Tensor, b: torch.Tensor, *rest: torch.Tensor) -> None: + """Require all runtime tensors to live on the same CUDA device.""" + device = a.device + if b.device != device or any(tensor.device != device for tensor in rest): + raise RuntimeError("FlexGEMM inputs must be on the same device") + + +def check_broadcast_shape( + name: str, shape: torch.Size, expected_shape: tuple[int, ...] +) -> None: + """Require a tensor shape to broadcast exactly to the GEMM output shape.""" + if not is_expandable_to(tuple(shape), expected_shape): + raise RuntimeError( + f"{name} shape must broadcast to {expected_shape}, got {tuple(shape)}" + ) + + +def check_matrix_major_layout(name: str, tensor: torch.Tensor) -> None: + """Require row-major or column-major dense matrix strides.""" + if tensor.stride(-1) != 1 and tensor.stride(-2) != 1: + raise NotImplementedError( + f"FlexGEMM requires {name} to be row- or column-major" + ) + + +def check_matrix_row_major_layout(name: str, tensor: torch.Tensor) -> None: + """Require last-dim-contiguous matrix strides for QuACK-written aux storage.""" + if tensor.stride(-1) != 1: + raise NotImplementedError(f"FlexGEMM requires {name} to be row-major") + + +def check_epilogue_arg_kinds(epilogue_arg_kinds: tuple[str, ...]) -> None: + """Require each epilogue arg kind to be row, col, tile, or scalar.""" + for kind in epilogue_arg_kinds: + if kind not in ("tile", "row", "col", "scalar"): + raise NotImplementedError( + f"FlexGEMM supports only tile/row/col/scalar args, got {epilogue_arg_kinds}" + ) + + +def infer_epilogue_arg_kind(a: torch.Tensor, b: torch.Tensor, arg: torch.Tensor) -> str: + """Infer a captured epilogue tensor's broadcast kind from its shape.""" + m, n = a.shape[-2], b.shape[-1] + if tuple(arg.shape) == (1, 1): + return "scalar" + if tuple(arg.shape) == (m, n): + return "tile" + if tuple(arg.shape) == (1, n): + return "row" + if tuple(arg.shape) == (m, 1): + return "col" + raise NotImplementedError( + "FlexGEMM captured tensor args must match the GEMM output " + "shape or broadcast as [1, N] / [M, 1] / [1, 1]" + ) + + +def validate_epilogue_arg_shape( + a: torch.Tensor, + b: torch.Tensor, + arg: torch.Tensor, + kind: str, +) -> None: + """Require a captured epilogue tensor shape to match its declared kind.""" + m, n = a.shape[-2], b.shape[-1] + expected_shapes = { + "tile": (m, n), + "row": (1, n), + "col": (m, 1), + "scalar": (1, 1), + } + if tuple(arg.shape) != expected_shapes[kind]: + raise RuntimeError( + f"{kind} epilogue arg shape must be {expected_shapes[kind]}, " + f"got {tuple(arg.shape)}" + ) + + +def resolve_epilogue_arg_kinds( + a: torch.Tensor, + b: torch.Tensor, + epilogue_args: tuple[torch.Tensor, ...], + epilogue_arg_kinds: tuple[str, ...], +) -> tuple[str, ...]: + """Validate declared epilogue arg kinds or infer them from tensor shapes.""" + if epilogue_arg_kinds and len(epilogue_arg_kinds) != len(epilogue_args): + raise RuntimeError("epilogue_arg_kinds must match epilogue_args length") + check_epilogue_arg_kinds(epilogue_arg_kinds) + if not epilogue_arg_kinds: + return tuple(infer_epilogue_arg_kind(a, b, arg) for arg in epilogue_args) + for arg, kind in zip(epilogue_args, epilogue_arg_kinds): + validate_epilogue_arg_shape(a, b, arg, kind) + return epilogue_arg_kinds + + +# NOTE [Boolean epilogue tensor storage] +# PyTorch bool tensors are byte-addressed, but CuTeDSL models cutlass.Boolean as +# a 1-bit logical type. Keep the manual uint8 storage view +# see https://github.com/NVIDIA/cutlass/issues/3348 for details +def quack_epilogue_arg(arg: torch.Tensor) -> torch.Tensor: + """Adapt logical epilogue tensors to QuACK's physical tensor ABI.""" + return arg.view(torch.uint8) if arg.dtype is torch.bool else arg + + +def split_epilogue_args( + epilogue_args: tuple[torch.Tensor, ...], + epilogue_arg_kinds: tuple[str, ...], +) -> tuple[ + tuple[torch.Tensor, ...], + tuple[torch.Tensor, ...], + tuple[torch.Tensor, ...], + tuple[torch.Tensor, ...], +]: + """Group epilogue tensors into QuACK row, col, tile, and scalar argument lists.""" + row_args = [] + col_args = [] + tile_args = [] + scalar_args = [] + for arg, kind in zip(epilogue_args, epilogue_arg_kinds): + arg = quack_epilogue_arg(arg) + match kind: + case "row": + row_args.append(arg) + case "col": + col_args.append(arg.squeeze(-1).unsqueeze(0)) + case "tile": + tile_args.append(arg.unsqueeze(0)) + case "scalar": + scalar_args.append(arg.reshape(1)) + return tuple(row_args), tuple(col_args), tuple(tile_args), tuple(scalar_args) + + +def normalize_c( + C: torch.Tensor | None, expected_shape: tuple[int, ...], beta: float +) -> torch.Tensor | None: + """Return the effective C tensor that QuACK should read for alpha/beta GEMMs.""" + if C is None: + return None + check_broadcast_shape("C", C.shape, expected_shape) + if beta == 0: + return None + broadcast_C = torch.broadcast_to(C, expected_shape) + check_matrix("C", broadcast_C) + check_matrix_major_layout("C", broadcast_C) + return broadcast_C + + +@dataclasses.dataclass(frozen=True) +class FlexGemmRuntimeLocalReducePlan: + """Runtime plan for one local reduction and its output/feed-main consumers.""" + + geometry: FlexGemmLocalReduceGeometry + out: torch.Tensor | None = None + callbacks: FlexGemmLocalReduceCallbacks | None = None + feeds_main: bool = False + + def __post_init__(self) -> None: + """Reject plans without the output/callback state required by their consumer.""" + if self.out is None and not self.feeds_main: + raise RuntimeError(LOCAL_REDUCE_RUNTIME_OUT_ERROR) + if self.feeds_main: + if self.callbacks is None: + raise RuntimeError(LOCAL_REDUCE_CALLBACKS_REQUIRED_ERROR) + validate_local_reduce_feed_main_capability(self.axis, self.group) + elif self.geometry.needs_physical_callbacks and self.callbacks is None: + raise RuntimeError(LOCAL_REDUCE_CALLBACKS_REQUIRED_ERROR) + + @property + def group(self) -> int: + return self.geometry.group + + @property + def axis(self) -> int: + return self.geometry.axis + + +@dataclasses.dataclass(frozen=True) +class FlexGemmRuntimeOutputPlan: + """Bundle all user-visible output consumers into one generated ABI value.""" + + aux_outs: tuple[torch.Tensor, ...] = () + local_reduce: FlexGemmRuntimeLocalReducePlan | None = None + output_contraction: FlexGemmOutputContraction | None = None + + def __post_init__(self) -> None: + if self.output_contraction is not None and ( + self.aux_outs or self.local_reduce is not None + ): + raise NotImplementedError(FLEX_GEMM_OUTPUT_CONTRACTION_COMPOSITION_ERROR) + + def output_shape(self, physical_shape: tuple[int, ...]) -> tuple[int, ...]: + """Return the logical shape after applying the output contraction.""" + if self.output_contraction is None: + return physical_shape + if physical_shape[-1] % self.output_contraction.group != 0: + raise RuntimeError(FLEX_GEMM_OUTPUT_CONTRACTION_SHAPE_ERROR) + return ( + *physical_shape[:-1], + physical_shape[-1] // self.output_contraction.group, + ) + + +def validate_runtime_local_reduce( + plan: FlexGemmRuntimeLocalReducePlan | None, + a: torch.Tensor, + expected_shape: tuple[int, ...], + effective_C: torch.Tensor | None, + alpha: float, + beta: float, +) -> None: + """Validate local-reduce runtime tensor shapes and unsupported consumers.""" + if plan is None: + return + validate_local_reduce_runtime_dense_mm(a.ndim) + validate_local_reduce_selected_dim_divisible(expected_shape, plan.group, plan.axis) + validate_local_reduce_no_c_alpha_beta(effective_C, alpha, beta) + local_reduce_out = plan.out + if local_reduce_out is None: + return + check_matrix("local_reduce_out", local_reduce_out) + check_matrix_row_major_layout("local_reduce_out", local_reduce_out) + expected_local_reduce_shape = local_reduce_compressed_shape( + expected_shape, plan.group, plan.axis + ) + validate_local_reduce_out_shape(local_reduce_out.shape, expected_local_reduce_shape) + + +def local_reduce_callback_key(callback: Any, fallback_key: str) -> str: + """Use a generated callback cache key when present, otherwise its caller key.""" + cache_key = getattr(callback, "__cache_key__", None) + if cache_key is None: + return fallback_key + key = cache_key() if callable(cache_key) else cache_key + if not isinstance(key, str): + raise RuntimeError("local-reduce callback __cache_key__ must return a string") + return key + + +def register_runtime_local_reduce_callbacks( + local_reduce: FlexGemmRuntimeLocalReducePlan | None, + epilogue_key: str, +) -> tuple[str | None, str | None]: + """Register generated physical callbacks and return QuACK registry keys.""" + if local_reduce is None or local_reduce.callbacks is None: + return None, None + callbacks = local_reduce.callbacks + local_reduce_combine_key = local_reduce_callback_key( + callbacks.combine_fn, f"{epilogue_key}{LOCAL_REDUCE_COMBINE_KEY_SUFFIX}" + ) + local_reduce_finalize_key = local_reduce_callback_key( + callbacks.finalize_fn, f"{epilogue_key}{LOCAL_REDUCE_FINALIZE_KEY_SUFFIX}" + ) + from torch._vendor.quack.gemm_act import register_local_reduce_fns + + register_local_reduce_fns( + local_reduce_combine_key, + callbacks.combine_fn, + local_reduce_finalize_key, + callbacks.finalize_fn, + ) + return local_reduce_combine_key, local_reduce_finalize_key + + +def local_reduce_gemm_act_kwargs( + local_reduce: FlexGemmRuntimeLocalReducePlan | None, + local_reduce_out: torch.Tensor | None, + callback_keys: tuple[str | None, str | None], +) -> dict[str, Any]: + """Map a concrete runtime plan onto QuACK's public local-reduce kwargs.""" + if local_reduce is None: + return {} + local_reduce_combine_key, local_reduce_finalize_key = callback_keys + return { + "tensor_epilogue_returns_local_reduce": local_reduce_out is not None, + "local_reduce_feeds_main": local_reduce.feeds_main, + "local_reduce_out": local_reduce_out, + "local_reduce_group": local_reduce.group, + "local_reduce_axis": local_reduce.axis, + "local_reduce_combine_key": local_reduce_combine_key, + "local_reduce_finalize_key": local_reduce_finalize_key, + } + + +def dispatch_gemm_act( + a: torch.Tensor, + b: torch.Tensor, + C: torch.Tensor | None, + out: torch.Tensor, + output_plan: FlexGemmRuntimeOutputPlan, + local_reduce_callback_keys: tuple[str | None, str | None], + epilogue_key: str, + epilogue_arg_kinds: tuple[str, ...], + row_args: tuple[torch.Tensor, ...], + col_args: tuple[torch.Tensor, ...], + tile_args: tuple[torch.Tensor, ...], + scalar_args: tuple[torch.Tensor, ...], + alpha: float, + beta: float, + config, + device_capacity_override: tuple[int, int] | None = None, +) -> None: + """Dispatch one dense FlexGEMM call to the vendored QuACK GEMM kernel. + + ``config.swap_ab`` dispatches the transposed problem (only the tile schedule + changes, not numerics): it swaps the A/B operands, writes through transposed + ``out``/``C``/``aux_outs`` views, and swaps the row/col broadcast roles of + captured epilogue tensors so each still aligns with the transposed accumulator. + Tuple epilogues route the main result through QuACK ``D`` and aux outputs through + ``PostAct``/``mAuxOut``. Output contractions instead leave ``D`` unused and use + ``PostAct``/``mAuxOut`` as the contracted logical main store. + """ + from torch._vendor.quack.gemm_act import gemm_act as gemm_act_dispatch + + # QuACK consumes A as (l, m, k) and B as (l, n, k); b is (k, n) so b.mT is (n, k). + quack_a, quack_b = a, b.mT + output_contraction = output_plan.output_contraction + aux_outs = output_plan.aux_outs + local_reduce = output_plan.local_reduce + quack_out, quack_aux_outs, quack_local_reduce_out, quack_c = ( + out, + aux_outs, + None if local_reduce is None else local_reduce.out, + C, + ) + if config.swap_ab: + if output_contraction is not None: + raise NotImplementedError( + "FlexGEMM output contractions do not support swap_ab configs yet" + ) + quack_a, quack_b = quack_b, quack_a + quack_out = out.mT + if local_reduce is not None: + raise NotImplementedError(LOCAL_REDUCE_SWAP_AB_ERROR) + quack_aux_outs = tuple(aux_out.mT for aux_out in aux_outs) + quack_c = None if C is None else C.mT + row_args, col_args = col_args, row_args + tile_args = tuple(tile.mT for tile in tile_args) + epilogue_arg_kinds = tuple( + _SWAPPED_ARG_KIND[kind] for kind in epilogue_arg_kinds + ) + + # QuACK expects a leading batch dim; 2-D (non-batched) operands get one here. + quack_a = quack_a.unsqueeze(0) if quack_a.ndim == 2 else quack_a + quack_b = quack_b.unsqueeze(0) if quack_b.ndim == 2 else quack_b + quack_out = quack_out.unsqueeze(0) if quack_out.ndim == 2 else quack_out + quack_aux_outs = tuple(quack_epilogue_arg(aux_out) for aux_out in quack_aux_outs) + quack_aux_outs = tuple( + aux_out.unsqueeze(0) if aux_out.ndim == 2 else aux_out + for aux_out in quack_aux_outs + ) + if quack_local_reduce_out is not None and quack_local_reduce_out.ndim == 2: + quack_local_reduce_out = quack_local_reduce_out.unsqueeze(0) + if quack_c is not None and quack_c.ndim == 2: + quack_c = quack_c.unsqueeze(0) + + returns_aux = bool(quack_aux_outs) + quack_d = quack_out if returns_aux else None + quack_postact = quack_aux_outs if returns_aux else quack_out + local_reduce_kwargs = local_reduce_gemm_act_kwargs( + local_reduce, quack_local_reduce_out, local_reduce_callback_keys + ) + + gemm_act_dispatch( + quack_a, + quack_b, + quack_d, + quack_c, + quack_postact, + None, # tile_count_semaphore + None, # activation + config.tile_m, + config.tile_n, + config.cluster_m, + config.cluster_n, + tile_K=config.tile_k, + pingpong=config.pingpong, + persistent=True, + is_dynamic_persistent=config.is_dynamic_persistent, + tensor_epilogue_key=epilogue_key, + tensor_epilogue_returns_aux=returns_aux, + tensor_epilogue_arg_kinds=epilogue_arg_kinds, + **local_reduce_kwargs, + tensor_epilogue_rowvec_biases=row_args, + tensor_epilogue_colvec_biases=col_args, + tensor_epilogue_tile_biases=tile_args, + tensor_epilogue_scalar_biases=scalar_args, + main_output_transform_group=( + None if output_contraction is None else output_contraction.group + ), + concat_layout=( + () if output_contraction is None else output_contraction.concat_layout + ), + alpha=alpha, + beta=beta, + use_tma_gather=config.use_tma_gather, + device_capacity_override=device_capacity_override, + ) + + +def gemm_epilogue( + a: torch.Tensor, + b: torch.Tensor, + epilogue_fn, + epilogue_key: str, + *, + C: torch.Tensor | None = None, + alpha: float = 1.0, + beta: float = 1.0, + out_dtype: torch.dtype | None = None, + out: torch.Tensor | None = None, + output_plan: FlexGemmRuntimeOutputPlan = FlexGemmRuntimeOutputPlan(), + epilogue_args: tuple[torch.Tensor, ...] = (), + epilogue_arg_kinds: tuple[str, ...] = (), + config_key: GemmConfigKey | None = None, + config_is_lowering_validated: bool = False, + expected_ndim: int | None = None, + device_capacity_override: tuple[int, int] | None = None, + stream: int | None = None, + quack_cache_dir: str | None = None, +) -> torch.Tensor: + """Run a dense GEMM through QuACK with a CuTeDSL epilogue. + + Args: + a: Left operand with shape ``[M, K]`` or ``[B, M, K]``. + b: Right operand with shape ``[K, N]`` or ``[B, K, N]``. + epilogue_fn: CuTeDSL epilogue callable applied to the accumulator tile. + epilogue_key: Stable cache key component for the epilogue. + C: Optional bias/addend broadcastable to the output shape. + alpha: Scale applied to the GEMM accumulator. + beta: Scale applied to ``C`` when ``C`` is present. + out_dtype: Optional output dtype. Defaults to ``a.dtype``. + out: Optional preallocated output tensor with shape ``[M, N]`` or ``[B, M, N]``. + output_plan: Structural plan for auxiliary and contracted outputs. + epilogue_args: Optional tensor args captured by the epilogue. + epilogue_arg_kinds: Explicit ``tile``, ``row``, ``col``, or ``scalar`` kind per arg. + config_key: Optional explicit QuACK config key selected by Inductor autotune. + config_is_lowering_validated: Whether generated lowering already checked the + config against the output-contraction contract. + expected_ndim: Optional generated-op rank contract for A and B operands. + device_capacity_override: Parent-computed capability for compile-only workers. + stream: Optional raw CUDA stream pointer supplied by the generated wrapper. + quack_cache_dir: Optional scoped cache root for Inductor-generated QuACK work. + + Returns: + Tensor with shape ``[M, N]`` or ``[B, M, N]``. + """ + check_matrix("a", a, expected_ndim) + check_matrix("b", b, expected_ndim) + check_matrix_major_layout("a", a) + check_matrix_major_layout("b", b) + if a.ndim != b.ndim: + raise RuntimeError("FlexGEMM inputs must both be 2-D or both be 3-D") + if a.ndim == 3 and a.shape[0] != b.shape[0]: + raise RuntimeError("FlexGEMM batched inputs must have the same batch size") + if a.shape[-1] != b.shape[-2]: + raise RuntimeError( + f"mat1 and mat2 shapes cannot be multiplied ({a.shape} and {b.shape})" + ) + physical_output_shape = (*a.shape[:-2], a.shape[-2], b.shape[-1]) + aux_outs = output_plan.aux_outs + local_reduce = output_plan.local_reduce + output_contraction = output_plan.output_contraction + logical_output_shape = output_plan.output_shape(physical_output_shape) + if output_contraction is not None: + device_capacity = ( + torch.cuda.get_device_capability(a.device) + if device_capacity_override is None + else device_capacity_override + ) + output_contraction.validate_quack(device_capacity[0]) + if output_contraction.chunked and b.stride(-1) == 1: + raise NotImplementedError(FLEX_GEMM_CHUNKED_CONTIGUOUS_B_ERROR) + if a.ndim != 2 or C is not None or alpha != 1.0 or beta != 1.0: + raise NotImplementedError(FLEX_GEMM_OUTPUT_CONTRACTION_COMPOSITION_ERROR) + expected_dtype = out_dtype + if expected_dtype is None: + expected_dtype = out.dtype if out is not None else a.dtype + effective_C = normalize_c(C, physical_output_shape, beta) + if out is not None: + check_matrix("out", out) + check_matrix_major_layout("out", out) + if tuple(out.shape) != logical_output_shape: + raise RuntimeError( + f"out shape must be {logical_output_shape}, got {tuple(out.shape)}" + ) + if out.dtype != expected_dtype: + raise RuntimeError(f"out dtype must be {expected_dtype}, got {out.dtype}") + if aux_outs: + if a.ndim != 2: + raise NotImplementedError( + "FlexGEMM generic aux tuple epilogues currently support only 2-D aten.mm" + ) + if effective_C is not None or alpha != 1.0 or beta != 1.0: + raise NotImplementedError( + "FlexGEMM generic aux tuple epilogues cannot be combined with C/alpha/beta yet" + ) + for index, aux_out in enumerate(aux_outs): + check_matrix(f"aux_outs[{index}]", aux_out) + check_matrix_major_layout(f"aux_outs[{index}]", aux_out) + if tuple(aux_out.shape) != physical_output_shape: + raise RuntimeError( + f"aux_outs[{index}] shape must be {physical_output_shape}, " + f"got {tuple(aux_out.shape)}" + ) + validate_runtime_local_reduce( + local_reduce, + a, + physical_output_shape, + effective_C, + alpha, + beta, + ) + if a.ndim == 3 and epilogue_args: + raise NotImplementedError("FlexGEMM batched args are not supported yet") + if epilogue_args and effective_C is not None: + # TODO: Route this through the flex frontend so validated A/B/C metadata + # can be reused here. + raise NotImplementedError("FlexGEMM args cannot be combined with C yet") + if epilogue_args and (alpha != 1.0 or beta != 1.0): + raise NotImplementedError( + "FlexGEMM args cannot be combined with non-default alpha/beta yet" + ) + tensors = ( + C, + out, + *aux_outs, + None if local_reduce is None else local_reduce.out, + *epilogue_args, + ) + check_same_device(a, b, *(tensor for tensor in tensors if tensor is not None)) + inferred_arg_kinds = resolve_epilogue_arg_kinds( + a, b, epilogue_args, epilogue_arg_kinds + ) + if output_contraction is not None and any( + not output_contraction_capture_supported(kind, arg.dtype is torch.bool) + for arg, kind in zip(epilogue_args, inferred_arg_kinds, strict=True) + ): + raise NotImplementedError(FLEX_GEMM_OUTPUT_CONTRACTION_CAPTURE_ERROR) + for index, arg in enumerate(epilogue_args): + check_matrix_major_layout(f"epilogue_args[{index}]", arg) + row_args, col_args, tile_args, scalar_args = split_epilogue_args( + epilogue_args, inferred_arg_kinds + ) + + from torch._vendor.quack.gemm_act import register_tensor_epilogue_fn + + register_tensor_epilogue_fn(epilogue_key, epilogue_fn) + local_reduce_callback_keys = register_runtime_local_reduce_callbacks( + local_reduce, + epilogue_key, + ) + out = ( + torch.empty(logical_output_shape, device=a.device, dtype=expected_dtype) + if out is None + else out + ) + from torch._inductor.heuristics.template.flex_gemm import ( + candidate_gemm_configs_for_device, + gemm_config_from_key, + ) + from torch._vendor.quack.cache import cache_dir_override + + config = gemm_config_from_key(config_key) if config_key is not None else None + if config is None or ( + output_contraction is not None and not config_is_lowering_validated + ): + candidates = candidate_gemm_configs_for_device(a.device) + if config is not None and config not in candidates: + raise NotImplementedError( + "FlexGEMM explicit QUACK config is not supported on this device" + ) + if output_contraction is None: + config = candidates[0] + elif config is None: + config = next( + ( + candidate + for candidate in candidates + if output_contraction_config_supported( + candidate, physical_output_shape[-1] + ) + ), + None, + ) + elif not output_contraction_config_supported(config, physical_output_shape[-1]): + config = None + if config is None: + raise NotImplementedError( + "FlexGEMM QUACK config is incompatible with output contraction" + ) + + stream_context = ( + torch.cuda.stream(torch.cuda.ExternalStream(stream, device=a.device)) + if stream is not None + else contextlib.nullcontext() + ) + with cache_dir_override(quack_cache_dir), stream_context: + dispatch_gemm_act( + a, + b, + effective_C, + out, + output_plan, + local_reduce_callback_keys, + epilogue_key, + inferred_arg_kinds, + row_args, + col_args, + tile_args, + scalar_args, + alpha, + beta, + config=config, + device_capacity_override=device_capacity_override, + ) + return out diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/template.py new file mode 100644 index 0000000000000000000000000000000000000000..84bcf5b13d1414f7b38a57788e60d79e2a000926 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/flex_gemm/template.py @@ -0,0 +1,379 @@ +# mypy: allow-untyped-defs +import dataclasses +import logging +from typing_extensions import override + +import torch +from torch._dynamo.utils import counters +from torch._higher_order_ops.flex_gemm import FlexGemmOpSpec +from torch._inductor.codegen.common import IndentedBuffer +from torch._inductor.codegen.cutedsl.cutedsl_kernel import CuteDSLTemplateKernel +from torch._inductor.codegen.cutedsl.cutedsl_template import ( + CuteDSLTemplate, + CuteDSLTemplateCaller, +) +from torch._inductor.heuristics.template.flex_gemm import GemmConfigKey +from torch._inductor.kernel.flex_gemm.constraints import ( + FlexGemmLocalReduceGeometry, + FlexGemmOutputContraction, + LOCAL_REDUCE_COMBINE_FN_SUFFIX, + LOCAL_REDUCE_FINALIZE_FN_SUFFIX, +) +from torch._inductor.kernel.flex_gemm.runtime import inductor_quack_cache_dir +from torch._inductor.kernel.gemm_epilogue_analysis import GemmOutputLocalReducePlan +from torch._inductor.select_algorithm import PartialRender +from torch.utils._ordered_set import OrderedSet + + +log = logging.getLogger(__name__) + + +@dataclasses.dataclass(frozen=True) +class FlexGemmEpilogueLocalReduceConfig: + """Template-time local-reduce metadata for output and/or feed-main consumers.""" + + geometry: FlexGemmLocalReduceGeometry + out_index: int | None = None + feeds_main: bool = False + + @classmethod + def from_output_plan( + cls, + local_reduce: GemmOutputLocalReducePlan | None, + out_index: int | None, + ) -> "FlexGemmEpilogueLocalReduceConfig | None": + """Bind analyzed local-reduction consumers to FlexGEMM's runtime ABI.""" + if local_reduce is None: + return None + return FlexGemmEpilogueLocalReduceConfig( + FlexGemmLocalReduceGeometry( + local_reduce.match.geometry.group, + local_reduce.match.geometry.axis, + ), + out_index, + local_reduce.feeds_main, + ) + + @property + def group(self) -> int: + return self.geometry.group + + @property + def axis(self) -> int: + return self.geometry.axis + + @property + def needs_physical_callbacks(self) -> bool: + return self.geometry.needs_physical_callbacks + + +@dataclasses.dataclass(frozen=True) +class FlexGemmEpilogueOutputConfig: + """Template input indices and plans for all user-visible outputs.""" + + aux_out_indices: tuple[int, ...] = () + local_reduce: FlexGemmEpilogueLocalReduceConfig | None = None + output_contraction: FlexGemmOutputContraction | None = None + + +@dataclasses.dataclass(frozen=True) +class FlexGemmEpilogueConfig: + """Metadata needed to render one Inductor-owned QuACK GEMM epilogue choice. + + Attributes: + epilogue_name: Name of the generated CuTeDSL epilogue callable. + epilogue_source: Python source that defines ``epilogue_name``. + gemm_op: Original aten GEMM op spec used to map inputs into QuACK. + alpha: Static alpha multiplier for addmm/baddbmm inputs. + beta: Static beta multiplier for addmm/baddbmm bias inputs. + quack_config_key: Lossless key for the selected QuACK GEMM config. + epilogue_arg_indices: Template input indices for read-only epilogue captures. + epilogue_arg_kinds: Broadcast kind for each captured epilogue tensor. + outputs: Structural plans for auxiliary, reduced, or transformed outputs. + """ + + epilogue_name: str + epilogue_source: str + gemm_op: FlexGemmOpSpec + alpha: float + beta: float + quack_config_key: GemmConfigKey + epilogue_arg_indices: tuple[int, ...] = () + epilogue_arg_kinds: tuple[str, ...] = () + outputs: FlexGemmEpilogueOutputConfig = dataclasses.field( + default_factory=FlexGemmEpilogueOutputConfig + ) + + +class FlexGemmEpilogueKernel(CuteDSLTemplateKernel): + """Render generated FlexGEMM epilogue modules with a compile-only hook.""" + + @override + def render(self, template, **kwargs): + config = kwargs.pop("config") + if kwargs: + raise RuntimeError(f"unexpected FlexGEMM epilogue options: {kwargs}") + + self._template_input_args = [] + self._seen_input_args = OrderedSet() + for index, input_node in enumerate(self.input_nodes): + buf_name = input_node.get_name() + self.args.input(buf_name) + arg_name = f"arg{index}" + self.args.input_buffers[buf_name] = arg_name + self._template_input_args.append((arg_name, input_node)) + self._seen_input_args.add(arg_name) + + self.args.output(self.output_node.get_name()) + arg_defs, _, _, _ = self.args.python_argdefs() + params = [arg_name for arg_name, _ in self._template_input_args] + for arg_def in arg_defs: + if arg_def.full_name() not in self._seen_input_args: + params.append(arg_def.full_name()) + params.append("stream") + params.append("device_capacity_override=None") + quack_cache_dir_param = f"quack_cache_dir={inductor_quack_cache_dir()!r}" + params.append(quack_cache_dir_param) + + template_input_arg_names = [ + arg_name for arg_name, _ in self._template_input_args + ] + # Template inputs include GEMM operands plus closed-over epilogue tensors for reads and aux writes. + call_args, call_kwargs = self._gemm_call_args(template_input_arg_names, config) + call_kwargs += self._epilogue_kwargs(template_input_arg_names, config) + call_kwargs += ( + f", out={self.get_output()}, " + f"expected_ndim={config.gemm_op.input_ndim}, " + "stream=stream, " + "device_capacity_override=device_capacity_override, " + "quack_cache_dir=quack_cache_dir" + ) + call_kwargs += ( + f", config_key={config.quack_config_key!r}, " + "config_is_lowering_validated=True" + ) + + output_name = self.get_output() + + code = IndentedBuffer() + code.splice( + """ + import torch + from torch._inductor.kernel.flex_gemm.constraints import ( + FlexGemmOutputContraction, + FlexGemmLocalReduceCallbacks, + FlexGemmLocalReduceGeometry, + ) + from torch._inductor.kernel.flex_gemm.runtime import ( + FlexGemmRuntimeLocalReducePlan, + FlexGemmRuntimeOutputPlan, + gemm_epilogue as flex_gemm_epilogue, + ) + """ + ) + code.splice(config.epilogue_source) + code.splice( + f""" + def {self.kernel_name}_main({", ".join(params)}): + flex_gemm_epilogue( + {", ".join(call_args)}, + {config.epilogue_name}, + {config.epilogue_name!r}{call_kwargs}, + ) + + def {self.kernel_name}_precompile( + precompile_shapes, + precompile_strides, + precompile_dtypes, + device_index=0, + device_capability=None, + hw_info=None, + quack_cache_dir={inductor_quack_cache_dir()!r}, + ): + from torch._vendor.quack.cache import compile_only_mode + + device = f"cuda:{{device_index}}" + with compile_only_mode(): + """ + ) + with code.indent(): + with code.indent(): + for arg_name, _ in self._template_input_args: + code.writeline( + f"{arg_name} = torch.empty_strided(tuple(precompile_shapes[{arg_name!r}]), " + f"tuple(precompile_strides[{arg_name!r}]), device=device, " + f"dtype=getattr(torch, precompile_dtypes[{arg_name!r}]))" + ) + code.writeline( + f"{output_name} = torch.empty_strided(tuple(precompile_shapes['output']), " + "tuple(precompile_strides['output']), device=device, " + "dtype=getattr(torch, precompile_dtypes['output']))" + ) + code.writeline(f"{self.kernel_name}_main(") + with code.indent(): + for arg_name in template_input_arg_names: + code.writeline(f"{arg_name},") + code.writeline(f"{output_name}={output_name},") + code.writeline("stream=None,") + code.writeline("device_capacity_override=device_capability,") + code.writeline("quack_cache_dir=quack_cache_dir,") + code.writeline(")") + return PartialRender(code.getvalue(), self.render_hooks) + + def _gemm_call_args( + self, input_args: list[str], config: FlexGemmEpilogueConfig + ) -> tuple[list[str], str]: + """Return positional GEMM operands and scalar/bias kwargs for runtime dispatch.""" + op = config.gemm_op + call_args = [input_args[op.mat1_index], input_args[op.mat2_index]] + if op.bias_index is None: + return call_args, "" + return call_args, ( + f", C={input_args[op.bias_index]}, alpha={config.alpha!r}, beta={config.beta!r}" + ) + + def _local_reduce_callbacks(self, epilogue_name: str) -> str: + """Render generated physical reducer callbacks for runtime registration.""" + combine_name = f"{epilogue_name}{LOCAL_REDUCE_COMBINE_FN_SUFFIX}" + finalize_name = f"{epilogue_name}{LOCAL_REDUCE_FINALIZE_FN_SUFFIX}" + return ( + "FlexGemmLocalReduceCallbacks(" + f"combine_fn={combine_name}, finalize_fn={finalize_name})" + ) + + def _local_reduce_geometry( + self, local_reduce: FlexGemmEpilogueLocalReduceConfig + ) -> str: + """Render the shared grouped M/N local-reduce geometry.""" + return ( + "FlexGemmLocalReduceGeometry(" + f"group={local_reduce.group!r}, axis={local_reduce.axis!r})" + ) + + def _local_reduce_expr( + self, + input_args: list[str], + local_reduce: FlexGemmEpilogueLocalReduceConfig | None, + epilogue_name: str, + ) -> str: + """Render one structural local-reduce plan for runtime dispatch.""" + if local_reduce is None: + return "None" + geometry = self._local_reduce_geometry(local_reduce) + plan = f"FlexGemmRuntimeLocalReducePlan({geometry}" + if local_reduce.out_index is not None: + plan += f", out={input_args[local_reduce.out_index]}" + if local_reduce.feeds_main: + plan += ", feeds_main=True" + if local_reduce.feeds_main or local_reduce.needs_physical_callbacks: + plan += f", callbacks={self._local_reduce_callbacks(epilogue_name)}" + return f"{plan})" + + def _output_plan_expr( + self, input_args: list[str], config: FlexGemmEpilogueConfig + ) -> str: + """Render all output consumers into one runtime ABI value.""" + outputs = config.outputs + aux_outs = tuple(input_args[index] for index in outputs.aux_out_indices) + aux_expr = f"({', '.join(aux_outs)},)" if aux_outs else "()" + local_reduce_expr = self._local_reduce_expr( + input_args, outputs.local_reduce, config.epilogue_name + ) + contraction = outputs.output_contraction + contraction_expr = ( + "None" + if contraction is None + else "FlexGemmOutputContraction(" + f"group={contraction.group!r}, chunked={contraction.chunked!r})" + ) + return ( + "FlexGemmRuntimeOutputPlan(" + f"aux_outs={aux_expr}, local_reduce={local_reduce_expr}, " + f"output_contraction={contraction_expr})" + ) + + def _epilogue_kwargs( + self, input_args: list[str], config: FlexGemmEpilogueConfig + ) -> str: + """Render only values that differ from the runtime ABI defaults.""" + epilogue_args = [input_args[index] for index in config.epilogue_arg_indices] + kwargs: list[str] = [] + if epilogue_args: + kwargs.append( + f", epilogue_args=({', '.join(epilogue_args)},), " + f"epilogue_arg_kinds={config.epilogue_arg_kinds!r}" + ) + outputs = config.outputs + if ( + outputs.aux_out_indices + or outputs.local_reduce is not None + or outputs.output_contraction is not None + ): + kwargs.append(f", output_plan={self._output_plan_expr(input_args, config)}") + return "".join(kwargs) + + +class FlexGemmEpilogueCaller(CuteDSLTemplateCaller): + def precompile(self) -> None: + """Warm the generated FlexGEMM epilogue module's QuACK object cache.""" + metadata = self.precompile_metadata() + if metadata is None: + return + from torch._inductor.async_compile import AsyncCompile + + if not AsyncCompile.use_process_pool(): + AsyncCompile.wait_pool_ready() + if not AsyncCompile.use_process_pool(): + return + AsyncCompile().cutedsl( + self.bmreq.kernel_name, + self.bmreq.source_code, + precompile_metadata=metadata, + ).result() + + def precompile_metadata(self) -> dict[str, object] | None: + """Build the generated FlexGEMM precompile hook's tensor metadata.""" + precompile_shapes = {} + precompile_strides = {} + precompile_dtypes = {} + tensor_metas = [ + *( + (f"arg{index}", tensor_meta) + for index, tensor_meta in enumerate(self.bmreq.input_tensor_meta) + ), + ("output", self.bmreq.output_tensor_meta), + ] + try: + for name, tensor_meta in tensor_metas: + precompile_shapes[name] = [int(size) for size in tensor_meta.sizes] + precompile_strides[name] = [ + int(stride) for stride in tensor_meta.strides + ] + precompile_dtypes[name] = str(tensor_meta.dtype).removeprefix("torch.") + except (TypeError, RuntimeError, ValueError): + counters["inductor"]["flex_gemm_precompile_skipped_dynamic"] += 1 + log.debug("Skipping FlexGEMM precompile for symbolic tensor metadata") + return None + device_index = self.bmreq.output_tensor_meta.device.index or 0 + device_capability = None + if torch.cuda.is_available(): + device_capability = torch.cuda.get_device_capability(device_index) + return { + "precompile_shapes": precompile_shapes, + "precompile_strides": precompile_strides, + "precompile_dtypes": precompile_dtypes, + "device_index": device_index, + "device_capability": device_capability, + "quack_cache_dir": inductor_quack_cache_dir(), + } + + +class FlexGemmEpilogueTemplate(CuteDSLTemplate): + kernel_type = FlexGemmEpilogueKernel + caller_type = FlexGemmEpilogueCaller + + def __init__(self) -> None: + super().__init__("flex_gemm_epilogue", source="") + + +flex_gemm_epilogue_template = FlexGemmEpilogueTemplate() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/gemm_epilogue.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/gemm_epilogue.py new file mode 100644 index 0000000000000000000000000000000000000000..e1c6ef5a6bb0daaebcac5c95ab01b2cd81f83823 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/gemm_epilogue.py @@ -0,0 +1,498 @@ +# mypy: allow-untyped-defs +"""Backend-neutral FX graph and runtime argument helpers for GEMM epilogues.""" + +import dataclasses +import operator +from collections.abc import Iterator, Sequence +from typing import Any, ClassVar + +import torch +from torch._inductor import inductor_prims +from torch._inductor.virtualized import V +from torch.fx.experimental.symbolic_shapes import GuardOnDataDependentSymNode +from torch.utils._ordered_set import OrderedSet + +from .gemm_epilogue_utils import statically_known_shape_equal + + +@dataclasses.dataclass(frozen=True) +class GemmReductionGeometry: + """Grouped M/N reduction geometry shared by frontend and backend plans. + + Attributes: + group: Number of adjacent GEMM output elements in each reduction group. + axis: GEMM output axis grouped by the reduction, either M (0) or N (1). + """ + + group: int + axis: int + + def __post_init__(self) -> None: + if self.group <= 0: + raise RuntimeError("local_reduce_group must be positive") + if self.axis not in (0, 1): + raise RuntimeError("local_reduce_axis must be 0 or 1") + + @property + def needs_physical_callbacks(self) -> bool: + return self.axis == 0 or self.group > 32 + + @property + def group_size(self) -> int: + return self.group + + @classmethod + def from_output_shape( + cls, output_shape: Sequence[Any], gemm_shape: Sequence[Any] + ) -> "GemmReductionGeometry | None": + if len(output_shape) != 3 or len(gemm_shape) != 2: + return None + for axis, group_dim in ((0, 1), (1, 2)): + try: + group = V.graph.sizevars.optimization_hint(output_shape[group_dim]) + except (GuardOnDataDependentSymNode, TypeError, ValueError): + continue + geometry = cls(group=group, axis=axis) + if geometry.matches_output_shape(output_shape, gemm_shape): + return geometry + return None + + @property + def reduce_dims(self) -> tuple[int, ...]: + return (-1, 2) if self.axis == 1 else (-2, 1) + + def matches_reduction_dim(self, dim: Any) -> bool: + dims = tuple(dim) if isinstance(dim, (list, tuple)) else (dim,) + return len(dims) == 1 and dims[0] in self.reduce_dims + + def matches_output_shape( + self, output_shape: Sequence[Any], gemm_shape: Sequence[Any] + ) -> bool: + if len(gemm_shape) != 2: + return False + m, n = gemm_shape + grouped = ( + (m, n // self.group, self.group) + if self.axis == 1 + else (m // self.group, self.group, n) + ) + return statically_known_shape_equal( + output_shape, (m, n) + ) or statically_known_shape_equal(output_shape, grouped) + + +@dataclasses.dataclass(frozen=True) +class GemmReductionDescriptor: + """Backend lowering descriptor for a recognized reduction expression. + + Attributes: + kind: Canonical reduction or normalized-consumer expression name. + parameters: Compile-time scalar parameters encoded by that expression. + """ + + kind: str + parameters: tuple[float, ...] = () + + @classmethod + def parse(cls, value: str) -> "GemmReductionDescriptor": + kind, *parameters = value.split(":") + return cls(kind, tuple(float(parameter) for parameter in parameters)) + + def serialize(self) -> str: + if not self.parameters: + return self.kind + return ( + self.kind + + ":" + + ":".join(format(parameter, ".17g") for parameter in self.parameters) + ) + + +@dataclasses.dataclass(frozen=True) +class GemmReductionConfig: + """Reduction recognized from frontend graph or scheduler loop IR. + + This is an analysis result, before output ownership and feed-main behavior + are finalized into a :class:`GemmReductionPlan`. + + Attributes: + output_name: Buffer produced by the recognized reduction. + group: Number of adjacent GEMM output elements in each reduction group. + axis: GEMM output axis grouped by the reduction, either M (0) or N (1). + reduction_type: Reduction or normalized consumer expression to compute. + source_type: Transformation applied to GEMM accumulator values. + """ + + output_name: str + group: int + axis: int + reduction_type: str + source_type: str + + @property + def geometry(self) -> GemmReductionGeometry: + return GemmReductionGeometry(self.group, self.axis) + + @property + def contract(self) -> tuple[int, int, str, str]: + return self.group, self.axis, self.reduction_type, self.source_type + + +@dataclasses.dataclass(frozen=True) +class GemmReductionPlan: + """Backend-neutral reduction outputs passed from analysis to codegen. + + Attributes: + reduction_output: Optional compressed reduction output buffer. + group: Number of adjacent GEMM output elements in each reduction group. + axis: GEMM output axis grouped by the reduction, either M (0) or N (1). + reduction_type: Reduction or normalized consumer expression to compute. + source_type: Transformation applied to GEMM accumulator values. + primary_output: Buffer receiving the primary GEMM result. + feeds_main: Whether the reduction participates in the primary output. + feed_output: Optional full-shape output consuming the reduction. + secondary_feed_output: Optional second full-shape reduction consumer. + secondary_feed_type: Expression implemented by the secondary consumer. + """ + + reduction_output: str | None + group: int + axis: int + reduction_type: str + source_type: str + primary_output: str + feeds_main: bool = False + feed_output: str | None = None + secondary_feed_output: str | None = None + secondary_feed_type: str | None = None + + @property + def geometry(self) -> GemmReductionGeometry: + return GemmReductionGeometry(self.group, self.axis) + + @property + def auxiliary_outputs(self) -> tuple[str, ...]: + return tuple( + OrderedSet( + output + for output in ( + self.reduction_output, + self.feed_output, + self.secondary_feed_output, + ) + if output is not None and output != self.primary_output + ) + ) + + +@dataclasses.dataclass(frozen=True) +class GemmReductionArguments: + """Runtime tensors and compile-time parameters for a grouped GEMM reduction. + + Attributes: + output: Optional tensor receiving the compressed reduction. + feed_output: Optional full-shape tensor receiving the reduction consumer. + secondary_feed_output: Optional second full-shape reduction consumer. + secondary_feed_type: Expression implemented by ``secondary_feed_output``. + group: Number of adjacent GEMM output elements in each reduction group. + axis: GEMM output axis grouped by the reduction, either M (0) or N (1). + reduction_type: Reduction or normalized consumer expression to compute. + source_type: Transformation applied to GEMM accumulator values. + feeds_main: Whether the reduction also produces the primary GEMM output. + """ + + output: Any | None = None + feed_output: Any | None = None + secondary_feed_output: Any | None = None + secondary_feed_type: str | None = None + group: int = 0 + axis: int = 1 + reduction_type: str = "sum" + source_type: str = "identity" + feeds_main: bool = False + + SPECIALIZATION_FIELDS: ClassVar[tuple[str, ...]] = ( + "group", + "axis", + "reduction_type", + "source_type", + "feeds_main", + "secondary_feed_type", + ) + + @property + def enabled(self) -> bool: + return ( + any( + value is not None + for value in (self.output, self.feed_output, self.secondary_feed_output) + ) + or self.feeds_main + ) + + @property + def primary_enabled(self) -> bool: + return ( + self.output is not None or self.feed_output is not None or self.feeds_main + ) + + @property + def descriptor(self) -> GemmReductionDescriptor: + return GemmReductionDescriptor.parse(self.reduction_type) + + def tensors(self, attr: str) -> tuple[Any | None, Any | None, Any | None]: + def tensor(value: Any | None) -> Any | None: + return getattr(value, attr) if value is not None else None + + return ( + tensor(self.output), + tensor(self.feed_output), + tensor(self.secondary_feed_output), + ) + + +@dataclasses.dataclass(frozen=True) +class NormalizedView: + """Canonical source and shape for an FX view or reshape.""" + + source: torch.fx.Node + shape: tuple[Any, ...] + + +@dataclasses.dataclass(frozen=True) +class NormalizedDtypeView: + """Canonical source and target dtype for a storage reinterpretation.""" + + source: torch.fx.Node + dtype: torch.dtype + + +@dataclasses.dataclass(frozen=True) +class NormalizedReduction: + """Canonical arguments for a supported FX reduction.""" + + source: torch.fx.Node + dim: Any + keepdim: Any + dtype: Any + reduction_type: str + + +@dataclasses.dataclass(frozen=True) +class NormalizedPrepareSoftmax: + """Canonical source and dimension for online softmax preparation.""" + + source: torch.fx.Node + dim: Any + + +@dataclasses.dataclass(frozen=True) +class NormalizedSqueeze: + """Canonical source for an FX squeeze alias.""" + + source: torch.fx.Node + + +@dataclasses.dataclass(frozen=True) +class NormalizedGetItem: + """Canonical aggregate source and literal FX getitem index.""" + + source: torch.fx.Node + index: int + + +@dataclasses.dataclass(frozen=True) +class NormalizedSplit: + """Canonical source, width, and dimension for an FX tensor split.""" + + source: torch.fx.Node + split_size: Any + dim: int + + +@dataclasses.dataclass(frozen=True) +class NormalizedSelect: + """Canonical source, dimension, and index for an FX tensor select.""" + + source: torch.fx.Node + dim: int + index: Any + + +@dataclasses.dataclass(frozen=True) +class NormalizedUnsupportedReduction: + """Canonical source and target for an unsupported FX reduction.""" + + source: torch.fx.Node + target: str + + +NormalizedNode = ( + NormalizedView + | NormalizedDtypeView + | NormalizedReduction + | NormalizedPrepareSoftmax + | NormalizedSqueeze + | NormalizedGetItem + | NormalizedSplit + | NormalizedSelect + | NormalizedUnsupportedReduction +) + + +FUNCTION_REDUCTION_TYPES = { + torch.ops.aten.sum.dim_IntList: ("sum", True), + torch.ops.aten.mean.dim: ("mean", True), + torch.ops.aten.prod.dim_int: ("prod", True), + torch.ops.aten.amax.default: ("max", False), + torch.ops.aten.amin.default: ("min", False), +} + +FUNCTION_UNSUPPORTED_REDUCTIONS = frozenset( + ( + torch.ops.aten.all.dim, + torch.ops.aten.all.dims, + torch.ops.aten.all.default, + torch.ops.aten.any.dim, + torch.ops.aten.any.dims, + torch.ops.aten.any.default, + torch.ops.aten.argmax.default, + torch.ops.aten.argmin.default, + torch.ops.aten.std.correction, + torch.ops.aten.std.dim, + torch.ops.aten.var.correction, + torch.ops.aten.var.dim, + ) +) + + +def normalize_gemm_epilogue_fx_node(node: torch.fx.Node) -> NormalizedNode | None: + """Return canonical arguments for a selected epilogue FX node.""" + if node.op != "call_function": + return None + if node.target is torch.ops.aten.view.dtype: + source, dtype = node.args + if not isinstance(source, torch.fx.Node) or not isinstance(dtype, torch.dtype): + raise AssertionError( + f"malformed GEMM epilogue dtype view: {node.format_node()}" + ) + return NormalizedDtypeView(source, dtype) + if node.target in ( + torch.ops.aten.view.default, + torch.ops.aten.reshape.default, + ): + source = node.args[0] + shape = node.args[1] + if not isinstance(source, torch.fx.Node) or not isinstance( + shape, (tuple, list, torch.Size) + ): + raise AssertionError(f"malformed GEMM epilogue view: {node.format_node()}") + return NormalizedView( + source, + tuple( + arg.meta.get("val", arg) if isinstance(arg, torch.fx.Node) else arg + for arg in shape + ), + ) + if node.target in FUNCTION_REDUCTION_TYPES: + source = node.args[0] + if not isinstance(source, torch.fx.Node): + raise AssertionError( + f"malformed GEMM epilogue reduction: {node.format_node()}" + ) + reduction_type, has_dtype = FUNCTION_REDUCTION_TYPES[node.target] + dim = node.args[1] if len(node.args) > 1 else node.kwargs.get("dim") + keepdim = ( + node.args[2] if len(node.args) > 2 else node.kwargs.get("keepdim", False) + ) + dtype = node.args[3] if len(node.args) > 3 else node.kwargs.get("dtype") + return NormalizedReduction( + source, + dim, + keepdim, + dtype if has_dtype else None, + reduction_type, + ) + if node.target is inductor_prims.prepare_softmax_online: + source = node.args[0] + if not isinstance(source, torch.fx.Node): + raise AssertionError( + f"malformed GEMM epilogue softmax: {node.format_node()}" + ) + dim = node.args[1] if len(node.args) > 1 else node.kwargs.get("dim") + return NormalizedPrepareSoftmax(source, dim) + if node.target is torch.ops.aten.split.Tensor: + source = node.args[0] + dim = node.args[2] if len(node.args) > 2 else node.kwargs.get("dim", 0) + if not isinstance(source, torch.fx.Node) or not isinstance(dim, int): + raise AssertionError(f"malformed GEMM epilogue split: {node.format_node()}") + return NormalizedSplit(source, node.args[1], dim) + if node.target is torch.ops.aten.select.int: + source = node.args[0] + dim = node.args[1] + if not isinstance(source, torch.fx.Node) or not isinstance(dim, int): + raise AssertionError( + f"malformed GEMM epilogue select: {node.format_node()}" + ) + return NormalizedSelect(source, dim, node.args[2]) + if node.target in ( + torch.ops.aten.squeeze.dim, + torch.ops.aten.squeeze.dims, + torch.ops.aten.squeeze.default, + ): + source = node.args[0] + if not isinstance(source, torch.fx.Node): + raise AssertionError( + f"malformed GEMM epilogue squeeze: {node.format_node()}" + ) + return NormalizedSqueeze(source) + if node.target is operator.getitem: + source, index = node.args + if isinstance(source, torch.fx.Node) and isinstance(index, int): + return NormalizedGetItem(source, index) + return None + if node.target in FUNCTION_UNSUPPORTED_REDUCTIONS: + source = node.args[0] + if not isinstance(source, torch.fx.Node): + raise AssertionError( + f"malformed GEMM epilogue reduction: {node.format_node()}" + ) + return NormalizedUnsupportedReduction(source, str(node.target)) + return None + + +def iter_fx_node_inputs(value: Any) -> Iterator[torch.fx.Node]: + """Yield FX node inputs nested in args/kwargs-style containers.""" + result: list[torch.fx.Node] = [] + torch.fx.map_arg(value, lambda node: result.append(node)) + yield from result + + +@dataclasses.dataclass(frozen=True) +class GemmEpilogueGraph: + """Index dependencies and canonical interpretations of epilogue FX nodes.""" + + dependencies: dict[torch.fx.Node, frozenset[torch.fx.Node]] + normalized_nodes: dict[torch.fx.Node, NormalizedNode] + + @classmethod + def from_nodes(cls, nodes: Sequence[torch.fx.Node]) -> "GemmEpilogueGraph": + """Build the FX dependency and normalization indexes in one graph walk.""" + dependencies: dict[torch.fx.Node, frozenset[torch.fx.Node]] = {} + normalized_nodes: dict[torch.fx.Node, NormalizedNode] = {} + for node in nodes: + node_dependencies: OrderedSet[torch.fx.Node] = OrderedSet() + for input_node in iter_fx_node_inputs((node.args, node.kwargs)): + node_dependencies.add(input_node) + node_dependencies.update(dependencies.get(input_node, ())) + dependencies[node] = frozenset(node_dependencies) + if (normalized := normalize_gemm_epilogue_fx_node(node)) is not None: + normalized_nodes[node] = normalized + return cls(dependencies, normalized_nodes) + + def depends_on(self, value: Any, target: torch.fx.Node) -> bool: + """Return whether a value is or transitively depends on the target node.""" + return any( + node is target or target in self.dependencies.get(node, ()) + for node in iter_fx_node_inputs(value) + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/gemm_epilogue_analysis.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/gemm_epilogue_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..0248f04f83ebd10206c8dc301d6787a937211bd9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/gemm_epilogue_analysis.py @@ -0,0 +1,816 @@ +# mypy: allow-untyped-defs +"""Shared FX analysis and output planning for grouped GEMM epilogues.""" + +import dataclasses +from collections.abc import Sequence +from typing import Any + +import torch +from torch._inductor.kernel.flex_gemm.constraints import ( + FLEX_GEMM_OUTPUT_PLAN_NODE_ERROR, + local_reduce_compressed_shape, + LOCAL_REDUCE_EXPLICIT_DTYPE_ERROR, + LOCAL_REDUCE_FEED_MAIN_AXIS1_FRAGMENT_ERROR, + LOCAL_REDUCE_FEED_MAIN_MIXED_MATCH_ERROR, + LOCAL_REDUCE_FRAGMENT_WIDTH, + LOCAL_REDUCE_GROUPED_RESHAPE_ERROR, + LOCAL_REDUCE_INNERMOST_GROUPED_DIM_ERROR, + LOCAL_REDUCE_MATCH_NODE_ERROR, + LOCAL_REDUCE_MIXED_GROUPED_LAYOUT_ERROR, + LOCAL_REDUCE_MIXED_MATCH_ERROR, + LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR, + LOCAL_REDUCE_OUTPUT_PLAN_NODE_ERROR, + LOCAL_REDUCE_SOURCE_EXPRESSION_ERROR, + local_reduce_unsupported_tensorssa_error, + validate_local_reduce_feed_main_capability, + validate_local_reduce_tensorssa_group_size, +) +from torch._inductor.kernel.flex_gemm.quack_reductions import ( + is_shape_preserving_pointwise_node, + tensor_meta_shape, +) +from torch._inductor.kernel.gemm_epilogue import ( + GemmEpilogueGraph, + GemmReductionGeometry, + GemmReductionPlan, + iter_fx_node_inputs, + NormalizedGetItem, + NormalizedPrepareSoftmax, + NormalizedReduction, + NormalizedSqueeze, + NormalizedUnsupportedReduction, + NormalizedView, +) +from torch._inductor.kernel.gemm_epilogue_utils import ( + guarded_int, + normalize_shape, + statically_known_equal, + statically_known_shape_equal, +) +from torch.utils._ordered_set import OrderedSet + + +def _is_inferred_reshape_dim(value: Any) -> bool: + """Return whether a reshape dimension is the literal inferred-size marker.""" + return isinstance(value, int) and value == -1 + + +def _kept_dim_matches_source(kept_size: Any, source_size: Any) -> bool: + return _is_inferred_reshape_dim(kept_size) or statically_known_equal( + kept_size, source_size + ) + + +def _guard_grouped_reshape_group( + shape: tuple[Any, ...], source_shape: tuple[Any, ...] +) -> tuple[Any, ...]: + """Specialize a backed group dimension used to recognize a grouped reshape.""" + if len(shape) != 3: + return shape + for group_index, kept_index in ((-1, 0), (-2, -1)): + if not _kept_dim_matches_source(shape[kept_index], source_shape[kept_index]): + continue + group_value = shape[group_index] + symbolic = ( + group_value.meta.get("val") + if isinstance(group_value, torch.fx.Node) + else group_value + ) + if not isinstance(symbolic, torch.SymInt): + continue + group = guarded_int(group_value) + if group is not None: + result = list(shape) + result[group_index] = group + return tuple(result) + return shape + + +def _syntactic_grouped_tensor_layout( + shape: tuple[Any, ...], +) -> GemmReductionGeometry | None: + """Match grouped-reshape syntax before validating source geometry.""" + if len(shape) not in (3, 4): + return None + if ( + isinstance(shape[-1], int) + and shape[-1] > 0 + and _is_inferred_reshape_dim(shape[-2]) + ): + return GemmReductionGeometry(group=shape[-1], axis=1) + if ( + _is_inferred_reshape_dim(shape[-3]) + and isinstance(shape[-2], int) + and shape[-2] > 0 + ): + return GemmReductionGeometry(group=shape[-2], axis=0) + return None + + +def _group_count_matches_selected_dim( + group_count: Any, + selected_size: Any, + group: int, + kept_size: Any, +) -> bool: + """Match a group count, allowing -1 to infer the selected source dimension.""" + if _is_inferred_reshape_dim(group_count): + return True + return statically_known_equal(group_count * group, selected_size) or ( + not _is_inferred_reshape_dim(kept_size) + and statically_known_equal(group_count, selected_size // group) + ) + + +def _grouped_layout_matches_source_shape( + shape: tuple[Any, ...], + source_shape: tuple[Any, ...], + layout: GemmReductionGeometry, +) -> bool: + """Require a 2-D GEMM output reshape to split exactly M or N.""" + if len(shape) != 3: + return False + + m, n = source_shape + match layout.axis, shape: + case 1, (kept_m, group_count, group) if group == layout.group: + return _kept_dim_matches_source( + kept_m, m + ) and _group_count_matches_selected_dim(group_count, n, group, kept_m) + case 0, (group_count, group, kept_n) if group == layout.group: + return _kept_dim_matches_source( + kept_n, n + ) and _group_count_matches_selected_dim(group_count, m, group, kept_n) + case _: + return False + + +def grouped_tensor_layout( + shape: Any, source_shape: Any | None = None +) -> GemmReductionGeometry | None: + """Recognize grouped M/N geometry, specializing backed group dimensions.""" + shape = normalize_shape(shape) + if not isinstance(shape, tuple): + return None + if len(shape) == 1 and isinstance(shape[0], (list, tuple, torch.Size)): + shape = normalize_shape(shape[0]) + if source_shape is not None: + source_shape = normalize_shape(source_shape) + if isinstance(source_shape, tuple) and len(source_shape) == 2: + shape = _guard_grouped_reshape_group(shape, source_shape) + candidates = [] + match shape: + case (*_, int(group)) if group > 0: + candidates.append(GemmReductionGeometry(group=group, axis=1)) + match shape: + case (*_, int(group), _) if group > 0: + candidates.append(GemmReductionGeometry(group=group, axis=0)) + for layout in candidates: + if _grouped_layout_matches_source_shape(shape, source_shape, layout): + return layout + if _syntactic_grouped_tensor_layout(shape) is not None: + raise NotImplementedError(LOCAL_REDUCE_GROUPED_RESHAPE_ERROR) + return None + return _syntactic_grouped_tensor_layout(shape) + + +FEED_MAIN_BINARY_FUNCTIONS = frozenset( + ( + torch.ops.aten.add.Tensor, + torch.ops.aten.add.Scalar, + torch.ops.aten.div.Tensor, + torch.ops.aten.mul.Tensor, + torch.ops.aten.mul.Scalar, + torch.ops.aten.sub.Tensor, + torch.ops.aten.sub.Scalar, + ) +) + + +@dataclasses.dataclass(frozen=True) +class GemmLocalReduceMatch: + """Describe a supported grouped local-reduction value found in the FX graph. + + Attributes: + value_node: FX node that produces the matched local-reduction value. + geometry: Group size and GEMM output axis reduced by the value. + """ + + value_node: torch.fx.Node + geometry: GemmReductionGeometry + reduction_node: torch.fx.Node | None = None + reduction_type: str | None = None + + def __post_init__(self) -> None: + if not isinstance(self.value_node, torch.fx.Node): + raise RuntimeError(LOCAL_REDUCE_MATCH_NODE_ERROR) + if self.reduction_node is None: + object.__setattr__(self, "reduction_node", self.value_node) + + def to_plan( + self, + *, + store: "GemmLocalReduceStore | None", + feeds_main: bool, + ) -> "GemmOutputLocalReducePlan": + """Bind this matched value to its output consumers.""" + return GemmOutputLocalReducePlan(self, store=store, feeds_main=feeds_main) + + @classmethod + def common( + cls, + matches: list["GemmLocalReduceMatch"], + mixed_match_error: str, + ) -> "GemmLocalReduceMatch | None": + """Return the common match when all values use one reduction geometry.""" + if not matches: + return None + match = matches[0] + if any(item.geometry != match.geometry for item in matches): + raise NotImplementedError(mixed_match_error) + return match + + @classmethod + def common_value( + cls, + matches: list["GemmLocalReduceMatch"], + mixed_match_error: str, + ) -> "GemmLocalReduceMatch | None": + """Return the common match when all consumers use one physical value.""" + match = cls.common(matches, mixed_match_error) + if match is None: + return None + if any(item.value_node is not match.value_node for item in matches): + raise NotImplementedError(LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR) + return match + + +@dataclasses.dataclass(frozen=True) +class GemmLocalReduceStore: + """Describe where a compressed local reduction appears in graph outputs. + + Attributes: + node: FX node returned as the compressed local-reduction output. + aux_index: Position of that node among the graph's auxiliary outputs. + """ + + node: torch.fx.Node + aux_index: int + + def __post_init__(self) -> None: + if not isinstance(self.node, torch.fx.Node) or self.aux_index < 0: + raise RuntimeError(LOCAL_REDUCE_OUTPUT_PLAN_NODE_ERROR) + + +@dataclasses.dataclass(frozen=True) +class GemmOutputLocalReducePlan: + """Bind a matched local reduction to store and/or main-output consumers. + + Attributes: + match: Supported local-reduction value identified during FX analysis. + store: Compressed auxiliary output receiving the value, when requested. + feeds_main: Whether the reduced value is also consumed by the main output. + """ + + match: GemmLocalReduceMatch + store: GemmLocalReduceStore | None = None + feeds_main: bool = False + + def __post_init__(self) -> None: + if not isinstance(self.match, GemmLocalReduceMatch) or ( + self.store is None and not self.feeds_main + ): + raise RuntimeError(LOCAL_REDUCE_OUTPUT_PLAN_NODE_ERROR) + + @property + def needs_physical_callbacks(self) -> bool: + return self.match.geometry.needs_physical_callbacks + + +@dataclasses.dataclass(frozen=True) +class GemmOutputPlan: + """Classify the values returned by a FlexGEMM body. + + Attributes: + output: FX node returned as the main GEMM result. + aux_outputs: Same-shape auxiliary FX outputs returned after the main result. + local_reduce: Compressed or feed-main local-reduction output behavior. + """ + + output: torch.fx.Node + aux_outputs: tuple[torch.fx.Node, ...] = () + local_reduce: GemmOutputLocalReducePlan | None = None + + def __post_init__(self) -> None: + if not isinstance(self.output, torch.fx.Node) or not all( + isinstance(aux_output, torch.fx.Node) for aux_output in self.aux_outputs + ): + raise RuntimeError(FLEX_GEMM_OUTPUT_PLAN_NODE_ERROR) + + @property + def reduction_plan(self) -> GemmReductionPlan | None: + """Finalize FX ownership metadata into the shared reduction contract.""" + local_reduce = self.local_reduce + if local_reduce is None: + return None + match = local_reduce.match + reduction_type = match.reduction_type + if reduction_type is None: + return None + reduction_output = ( + local_reduce.store.node.name if local_reduce.store is not None else None + ) + return GemmReductionPlan( + reduction_output, + match.geometry.group, + match.geometry.axis, + reduction_type, + "identity", + self.output.name, + feeds_main=local_reduce.feeds_main, + feed_output=self.output.name if local_reduce.feeds_main else None, + ) + + +@dataclasses.dataclass +class GemmLocalReduceAnalysis: + """Collect grouped TensorSSA layouts and supported local-reduction matches. + + ``from_graph_module`` visits the FX graph in topological order. See + ``GemmReductionGeometry`` for the grouped layout attached to reshape and + pointwise nodes, and ``GemmLocalReduceMatch`` for each supported reduced + value found from those layouts. + + Attributes: + graph: Dependency index used by recursive feed-main matching. + grouped_tensors: FX nodes whose values carry a grouped TensorSSA layout. + matches: FX values matched to a supported grouped local reduction. + """ + + graph: GemmEpilogueGraph + grouped_tensors: dict[torch.fx.Node, GemmReductionGeometry] = dataclasses.field( + default_factory=dict + ) + matches: dict[torch.fx.Node, GemmLocalReduceMatch] = dataclasses.field( + default_factory=dict + ) + + @classmethod + def from_graph_module( + cls, graph_module: torch.fx.GraphModule + ) -> "GemmLocalReduceAnalysis": + """Build shared dependency and reduction state in one topological pass.""" + nodes = tuple(graph_module.graph.nodes) + analysis = cls(GemmEpilogueGraph.from_nodes(nodes)) + for node in nodes: + if node.op == "output": + break + analysis.visit_node(node) + return analysis + + def visit_node(self, node: torch.fx.Node) -> None: + """Record grouped layouts and local-reduction matches for one FX node.""" + if node.op != "call_function": + return + normalized = self.graph.normalized_nodes.get(node) + if isinstance(normalized, NormalizedView): + if self.propagate_local_reduce_match(node, normalized.source): + return + if self.bind_grouped_layout(node, normalized.shape, normalized.source): + return + elif isinstance(normalized, NormalizedReduction): + if self.bind_grouped_reduction( + node, + normalized.source, + normalized.dim, + normalized.dtype, + reduction_type=normalized.reduction_type, + ): + return + elif isinstance(normalized, NormalizedPrepareSoftmax): + if self.bind_grouped_reduction( + node, + normalized.source, + normalized.dim, + raise_invalid_dims=False, + ): + return + elif isinstance(normalized, NormalizedUnsupportedReduction): + if normalized.source in self.grouped_tensors: + raise local_reduce_unsupported_tensorssa_error(normalized.target) + elif isinstance(normalized, (NormalizedSqueeze, NormalizedGetItem)): + if self.propagate_local_reduce_match(node, normalized.source): + return + if is_shape_preserving_pointwise_node(node): + self.propagate_pointwise_match(node, LOCAL_REDUCE_MIXED_MATCH_ERROR) + + def bind_grouped_layout(self, node: torch.fx.Node, shape: Any, source: Any) -> bool: + """Attach a grouped TensorSSA layout introduced by a reshape.""" + source_shape = ( + tensor_meta_shape(source) if isinstance(source, torch.fx.Node) else None + ) + grouped_layout = grouped_tensor_layout(shape, source_shape) + if grouped_layout is None or not isinstance(source, torch.fx.Node): + return False + self.grouped_tensors[node] = grouped_layout + return True + + def propagate_local_reduce_match(self, node: torch.fx.Node, source: Any) -> bool: + """Copy a matched local-reduction value through an FX wrapper.""" + if not isinstance(source, torch.fx.Node): + return False + match = self.matches.get(source) + if match is None: + return False + self.matches[node] = match + return True + + def bind_grouped_reduction( + self, + node: torch.fx.Node, + input_node: Any, + dim: Any, + dtype: Any = None, + *, + reduction_type: str | None = None, + raise_invalid_dims: bool = True, + ) -> bool: + """Match and record a reduction over a grouped TensorSSA layout.""" + if not isinstance(input_node, torch.fx.Node): + return False + layout = self.grouped_tensors.get(input_node) + if layout is None: + return False + if dtype is not None: + raise NotImplementedError(LOCAL_REDUCE_EXPLICIT_DTYPE_ERROR) + validate_local_reduce_tensorssa_group_size(layout.axis, layout.group) + if not layout.matches_reduction_dim(dim): + if not raise_invalid_dims: + return False + raise NotImplementedError(LOCAL_REDUCE_INNERMOST_GROUPED_DIM_ERROR) + self.matches[node] = GemmLocalReduceMatch( + node, + layout, + reduction_node=node, + reduction_type=reduction_type, + ) + return True + + def has_physical_grouped_input(self, value: Any) -> bool: + """Return whether a value depends on a grouped layout needing callbacks.""" + active_geometries = OrderedSet( + match.geometry for match in self.matches.values() + ) + physical_grouped_nodes = OrderedSet( + node + for node, layout in self.grouped_tensors.items() + if layout.needs_physical_callbacks and layout in active_geometries + ) + return any( + node in physical_grouped_nodes + or any( + dependency in physical_grouped_nodes + for dependency in self.graph.dependencies.get(node, ()) + ) + for node in iter_fx_node_inputs(value) + ) + + def propagate_pointwise_match( + self, node: torch.fx.Node, mixed_match_error: str + ) -> bool: + """Propagate grouped layouts and local-reduction matches through pointwise ops.""" + grouped_layouts = [ + self.grouped_tensors[arg] + for arg in iter_fx_node_inputs((node.args, node.kwargs)) + if arg in self.grouped_tensors + ] + if grouped_layouts: + grouped_layout = grouped_layouts[0] + if any(layout != grouped_layout for layout in grouped_layouts): + raise NotImplementedError(LOCAL_REDUCE_MIXED_GROUPED_LAYOUT_ERROR) + self.grouped_tensors[node] = grouped_layout + match = GemmLocalReduceMatch.common( + [ + self.matches[arg] + for arg in iter_fx_node_inputs((node.args, node.kwargs)) + if arg in self.matches + ], + mixed_match_error, + ) + if match is None: + return False + self.matches[node] = dataclasses.replace(match, value_node=node) + return True + + def match_feed_value( + self, + value: Any, + grouped_source: torch.fx.Node, + layout: GemmReductionGeometry, + ) -> GemmLocalReduceMatch | None: + """Find the grouped reduction that produces a broadcast value.""" + if not isinstance(value, torch.fx.Node): + return None + normalized = self.graph.normalized_nodes.get(value) + if isinstance(normalized, NormalizedReduction): + if normalized.source is not grouped_source: + if self.graph.depends_on(normalized.source, grouped_source): + raise NotImplementedError(LOCAL_REDUCE_SOURCE_EXPRESSION_ERROR) + raise NotImplementedError(LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR) + if ( + normalized.dtype is not None + or not normalized.keepdim + or not layout.matches_reduction_dim(normalized.dim) + ): + raise NotImplementedError(LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR) + return GemmLocalReduceMatch( + value, + layout, + reduction_node=value, + reduction_type=normalized.reduction_type, + ) + if not is_shape_preserving_pointwise_node(value): + return None + matches = [ + match + for arg in iter_fx_node_inputs((value.args, value.kwargs)) + if (match := self.match_feed_value(arg, grouped_source, layout)) is not None + ] + return GemmLocalReduceMatch.common_value( + matches, LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR + ) + + def validate_hidden_feed_main_reduction_input( + self, + input_node: Any, + grouped_source: torch.fx.Node, + ) -> None: + """Reject reduction inputs that would need another physical feed-main value.""" + if input_node is grouped_source: + raise NotImplementedError(LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR) + if not isinstance(input_node, torch.fx.Node): + return + if self.graph.depends_on(input_node, grouped_source): + raise NotImplementedError(LOCAL_REDUCE_SOURCE_EXPRESSION_ERROR) + if self.has_physical_grouped_input(input_node): + raise NotImplementedError(LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR) + + def validate_feed_main_source_reductions( + self, + value: Any, + grouped_source: torch.fx.Node, + selected_reduction: torch.fx.Node, + seen: OrderedSet[torch.fx.Node] | None = None, + ) -> None: + """Reject hidden physical reductions outside the selected feed-main value.""" + if not isinstance(value, torch.fx.Node): + for arg in iter_fx_node_inputs(value): + self.validate_feed_main_source_reductions( + arg, grouped_source, selected_reduction, seen + ) + return + if value is selected_reduction: + return + if seen is None: + seen = OrderedSet() + if value in seen: + return + seen.add(value) + normalized = self.graph.normalized_nodes.get(value) + if isinstance(normalized, NormalizedReduction): + self.validate_hidden_feed_main_reduction_input( + normalized.source, grouped_source + ) + for arg in iter_fx_node_inputs((value.args, value.kwargs)): + self.validate_feed_main_source_reductions( + arg, grouped_source, selected_reduction, seen + ) + + def validate_feed_main_source_match( + self, + source: torch.fx.Node, + match: GemmLocalReduceMatch | None, + ) -> GemmLocalReduceMatch | None: + """Preserve the one-physical-value ABI across recursive source matching.""" + if match is None: + return None + normalized = self.graph.normalized_nodes.get(match.value_node) + if isinstance(normalized, NormalizedReduction): + self.validate_feed_main_source_reductions( + source, normalized.source, match.value_node + ) + return match + + @staticmethod + def feed_main_binary_candidates( + source: torch.fx.Node, + ) -> tuple[tuple[Any, Any], ...]: + """Return operand orderings for supported binary feed-main expressions.""" + if ( + len(source.args) < 2 + or source.op != "call_function" + or source.target not in FEED_MAIN_BINARY_FUNCTIONS + ): + return () + lhs, rhs = source.args[:2] + return ((lhs, rhs), (rhs, lhs)) + + def feed_main_grouped_reduction( + self, + value: Any, + grouped_source: torch.fx.Node, + layout: GemmReductionGeometry, + ) -> bool: + """Return whether a candidate contains a grouped feed-main reduction.""" + if not isinstance(value, torch.fx.Node): + return False + normalized = self.graph.normalized_nodes.get(value) + if isinstance(normalized, NormalizedReduction): + return ( + normalized.dtype is None + and bool(normalized.keepdim) + and layout.matches_reduction_dim(normalized.dim) + and ( + normalized.source is grouped_source + or self.graph.depends_on(normalized.source, grouped_source) + ) + ) + if not is_shape_preserving_pointwise_node(value): + return False + return any( + self.feed_main_grouped_reduction(arg, grouped_source, layout) + for arg in iter_fx_node_inputs((value.args, value.kwargs)) + ) + + def match_feed_main_candidate( + self, + grouped_source: Any, + value: Any, + output_meta: Any, + ) -> GemmLocalReduceMatch | None: + """Match one grouped-source and reduced-value operand ordering.""" + if not isinstance(grouped_source, torch.fx.Node) or not isinstance( + value, torch.fx.Node + ): + return None + normalized = self.graph.normalized_nodes.get(grouped_source) + if not isinstance(normalized, NormalizedView): + return None + source_node = normalized.source + layout = self.grouped_tensors.get(grouped_source) + if layout is None: + return None + if layout.axis != 0: + if not self.feed_main_grouped_reduction(value, grouped_source, layout): + return None + if layout.group <= LOCAL_REDUCE_FRAGMENT_WIDTH: + # Intentional fallthrough: axis-1 feeds within one TensorSSA + # fragment lower as plain generated TensorSSA without a feed plan. + return None + raise NotImplementedError(LOCAL_REDUCE_FEED_MAIN_AXIS1_FRAGMENT_ERROR) + validate_local_reduce_feed_main_capability(layout.axis, layout.group) + source_meta = source_node.meta.get("val") + if ( + output_meta is not None + and source_meta is not None + and not statically_known_shape_equal(output_meta.shape, source_meta.shape) + ): + return None + return self.match_feed_value(value, grouped_source, layout) + + def match_feed_main_source( + self, + source: torch.fx.Node, + output_meta: Any, + ) -> GemmLocalReduceMatch | None: + """Find one physical feed-main value inside a pointwise expression.""" + matches = [ + match + for grouped_source, value in self.feed_main_binary_candidates(source) + if ( + match := self.match_feed_main_candidate( + grouped_source, value, output_meta + ) + ) + is not None + ] + if matches: + return self.validate_feed_main_source_match( + source, + GemmLocalReduceMatch.common_value( + matches, LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR + ), + ) + if not is_shape_preserving_pointwise_node(source): + return None + matches = [ + match + for arg in iter_fx_node_inputs((source.args, source.kwargs)) + if isinstance(arg, torch.fx.Node) + if (match := self.match_feed_main_source(arg, output_meta)) is not None + ] + return self.validate_feed_main_source_match( + source, + GemmLocalReduceMatch.common_value( + matches, LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR + ), + ) + + def feed_main_plan( + self, + output: torch.fx.Node, + ) -> GemmLocalReduceMatch | None: + """Match feed-main reductions through trailing pointwise nodes.""" + normalized = self.graph.normalized_nodes.get(output) + if isinstance(normalized, NormalizedView): + return self.match_feed_main_source( + normalized.source, output.meta.get("val") + ) + if not is_shape_preserving_pointwise_node(output): + return None + matches = [ + match + for arg in iter_fx_node_inputs((output.args, output.kwargs)) + if isinstance(arg, torch.fx.Node) + if (match := self.feed_main_plan(arg)) is not None + ] + return self.validate_feed_main_source_match( + output, + GemmLocalReduceMatch.common_value( + matches, LOCAL_REDUCE_ONE_PHYSICAL_VALUE_ERROR + ), + ) + + def common_feed_main_match( + self, + candidates: tuple[Any, ...], + ) -> GemmLocalReduceMatch | None: + """Find the physical reduction value shared by feed-main consumers.""" + matches = [ + match + for candidate in candidates + if isinstance(candidate, torch.fx.Node) + if (match := self.feed_main_plan(candidate)) is not None + ] + return GemmLocalReduceMatch.common_value( + matches, LOCAL_REDUCE_FEED_MAIN_MIXED_MATCH_ERROR + ) + + def common_reduction_dependency_match( + self, outputs: Sequence[torch.fx.Node] + ) -> GemmLocalReduceMatch | None: + """Return one physical reduction transitively consumed by the outputs.""" + reachable = OrderedSet(outputs) + for output in outputs: + reachable.update(self.graph.dependencies.get(output, ())) + matches = [self.matches[node] for node in reachable if node in self.matches] + if not matches: + return None + reduction_node = matches[0].reduction_node + if reduction_node is None or any( + match.reduction_node is not reduction_node for match in matches + ): + return None + return matches[0] + + def compressed_aux_plan( + self, + output: Any, + aux: torch.fx.Node, + aux_index: int, + ) -> GemmOutputLocalReducePlan | None: + """Plan a matched local reduction returned in compressed output shape.""" + match = self.matches.get(aux) + output_meta = ( + output.meta.get("val") if isinstance(output, torch.fx.Node) else None + ) + aux_meta = aux.meta.get("val") + if match is None or aux_meta is None or output_meta is None: + return None + expected_aux_shape = local_reduce_compressed_shape( + output_meta.shape, match.geometry.group, match.geometry.axis + ) + if not statically_known_shape_equal(expected_aux_shape, aux_meta.shape): + return None + return match.to_plan( + store=GemmLocalReduceStore(aux, aux_index), feeds_main=False + ) + + def feed_main_output_plan( + self, + output: torch.fx.Node, + aux_outputs: tuple[torch.fx.Node, ...] = (), + *, + allow_dependency_match: bool = False, + ) -> GemmOutputPlan | None: + """Plan one physical reduction value consumed by the main output.""" + match = self.common_feed_main_match((output, *aux_outputs)) + if match is None and allow_dependency_match: + match = self.common_reduction_dependency_match((output, *aux_outputs)) + if match is None: + return None + return GemmOutputPlan( + output, + aux_outputs, + match.to_plan(store=None, feeds_main=True), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/gemm_epilogue_codegen.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/gemm_epilogue_codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..b2bc87b128f11426c35651445a599c211635a9b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/gemm_epilogue_codegen.py @@ -0,0 +1,141 @@ +# mypy: allow-untyped-defs +"""Shared CuTeDSL emission primitives for GEMM epilogues.""" + +from typing import Any + +import torch +from torch._inductor.codegen.cutedsl.cutedsl_op_overrides import ( + CuteDSLCSEVariable, + CuteDSLOpOverrides, +) +from torch._inductor.virtualized import V +from torch.utils._sympy.value_ranges import ValueRanges + + +def gemm_epilogue_op_scope(cute: Any) -> dict[str, Any]: + import operator + + import cutlass + from cutlass._mlir.dialects import math as mlir_math + + def sigmoid(x: Any) -> Any: + return 1.0 / (1.0 + cute.math.exp(-x)) + + return { + "cutlass": cutlass, + "operator": operator, + "mlir_math": mlir_math, + "cute": cute, + "erf": cute.math.erf, + "exp": cute.math.exp, + "gelu": lambda x: 0.5 * x * (1.0 + cute.math.erf(x * 0.7071067811865476)), + "relu": lambda x: cute.math.max(x, cute.full_like(x, 0.0)), + "sigmoid": sigmoid, + "silu": lambda x: x * sigmoid(x), + "tanh": cute.math.tanh, + } + + +class GemmEpilogueCuteDSLBody: + def __init__(self) -> None: + self.lines: list[str] = [] + + def writeline(self, line: str) -> None: + self.lines.append(line) + + +class GemmEpilogueCuteDSLCSE: + def __init__(self) -> None: + self.index = 0 + + def generate(self, body, expr, *, bounds=None, dtype=None, shape=None): + name = f"tmp{self.index}" + self.index += 1 + body.writeline(f"{name} = {expr}") + return CuteDSLCSEVariable( + name, + ValueRanges.unknown() if bounds is None else bounds, + dtype=dtype, + shape=shape, + ) + + +class GemmEpilogueCuteDSLKernel: + def __init__(self) -> None: + self.body = GemmEpilogueCuteDSLBody() + self.cse = GemmEpilogueCuteDSLCSE() + + +class GemmEpilogueCuteDSLOpOverrides(CuteDSLOpOverrides): + """Normalize ATen spellings before emitting CuTeDSL expressions.""" + + @staticmethod + def add(a: Any, b: Any, *, alpha: Any = 1) -> Any: + rhs = b if alpha == 1 else CuteDSLOpOverrides.mul(b, alpha) + return CuteDSLOpOverrides.add(a, rhs) + + @staticmethod + def sub(a: Any, b: Any, *, alpha: Any = 1) -> Any: + rhs = b if alpha == 1 else CuteDSLOpOverrides.mul(b, alpha) + return CuteDSLOpOverrides.sub(a, rhs) + + @staticmethod + def _to_copy(x: Any, *, dtype: torch.dtype, **kwargs: Any) -> Any: + unsupported_kwargs = { + key: value + for key, value in kwargs.items() + if value not in (None, False, torch.preserve_format) + } + if unsupported_kwargs: + raise NotImplementedError( + f"unsupported GEMM epilogue _to_copy kwargs: {unsupported_kwargs}" + ) + return CuteDSLOpOverrides.to_dtype(x, dtype) + + @staticmethod + def where(condition: Any, a: Any, b: Any) -> Any: + """Preserve all-scalar conditionals as scalar epilogue expressions.""" + if any( + CuteDSLOpOverrides._is_tensor_like(value) for value in (condition, a, b) + ): + return CuteDSLOpOverrides.where(condition, a, b) + result_expr = ( + f"({CuteDSLOpOverrides._as_expr(a)} if " + f"{CuteDSLOpOverrides._as_expr(condition)} else " + f"{CuteDSLOpOverrides._as_expr(b)})" + ) + cse_vars = tuple( + CuteDSLOpOverrides._get_cse_var(value) for value in (a, b, condition) + ) + if all(value is None for value in cse_vars): + return result_expr + dtype, bounds = CuteDSLOpOverrides._extract_dtype_and_bounds(a, b, condition) + result = V.kernel.cse.generate( + V.kernel.body, + result_expr, + bounds=bounds, + dtype=dtype if dtype is not None else torch.int32, + ) + result.is_scalar_expr = True + return result + + @staticmethod + def clamp(x: Any, min: Any = None, max: Any = None) -> Any: + result = x + if min is not None: + result = CuteDSLOpOverrides.maximum(result, min) + if max is not None: + result = CuteDSLOpOverrides.minimum(result, max) + return result + + @staticmethod + def clamp_min(x: Any, min: Any) -> Any: + return CuteDSLOpOverrides.maximum(x, min) + + @staticmethod + def clamp_max(x: Any, max: Any) -> Any: + return CuteDSLOpOverrides.minimum(x, max) + + @staticmethod + def convert_element_type(x: Any, dtype: torch.dtype) -> Any: + return CuteDSLOpOverrides.to_dtype(x, dtype) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/gemm_epilogue_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/gemm_epilogue_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ead123c73442e0a307be706a98810d83b61e88f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/gemm_epilogue_utils.py @@ -0,0 +1,57 @@ +# mypy: allow-untyped-defs +"""Symbolic shape helpers shared by GEMM epilogue frontends.""" + +from collections.abc import Sequence +from typing import Any + +import sympy + +import torch +from torch._inductor.virtualized import V +from torch.fx.experimental.symbolic_shapes import ( + guard_int, + has_guarding_hint, + statically_known_true as fx_statically_known_true, +) + + +def normalize_shape(shape: Any) -> Any: + """Canonicalize sequence-like shapes to tuples.""" + return tuple(shape) if isinstance(shape, (list, tuple, torch.Size)) else shape + + +def guarded_int(value: Any) -> int | None: + """Return an integer after guarding backed symbolic values.""" + if isinstance(value, torch.fx.Node): + value = value.meta.get("val") + if isinstance(value, torch.SymInt): + if not has_guarding_hint(value): + return None + # TODO: Defer speculative guards if they become a meaningful source of + # recompilation. + return guard_int(value) + return value if isinstance(value, int) else None + + +def statically_known(expr: Any) -> bool: + """Return whether a symbolic predicate is known true without adding guards.""" + if isinstance(expr, bool): + return expr + if isinstance(expr, sympy.Basic): + return V.graph.sizevars.statically_known_true(expr) + return fx_statically_known_true(expr) + + +def statically_known_equal(lhs: Any, rhs: Any) -> bool: + """Return whether symbolic shape values are known equal without adding guards.""" + return statically_known(lhs == rhs) + + +def statically_known_shape_equal( + actual_shape: Sequence[Any], expected_shape: Sequence[Any] +) -> bool: + """Compare possibly symbolic shape tuples without adding guards.""" + return len(actual_shape) == len(expected_shape) and all( + statically_known_equal(actual, expected) + for actual, expected in zip(actual_shape, expected_shape) + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/loop_ir_cutedsl_codegen.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/loop_ir_cutedsl_codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..551768aff9e64ad9008d053ce47cff5245456dbd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/loop_ir_cutedsl_codegen.py @@ -0,0 +1,111 @@ +# mypy: allow-untyped-defs +"""Lower Inductor GEMM epilogue loop IR to CuTeDSL source.""" + +from collections.abc import Sequence +from typing import Any + +import torch +from torch._inductor.codegen.cutedsl.cutedsl_op_overrides import CuteDSLCSEVariable +from torch._inductor.ir import ComputedBuffer +from torch._inductor.virtualized import V +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.value_ranges import ValueRanges + +from .gemm_epilogue_codegen import ( + GemmEpilogueCuteDSLKernel, + GemmEpilogueCuteDSLOpOverrides, +) +from .loop_ir_epilogue_lowering import GemmEpilogueIRAnalysis, GemmEpilogueIRExpression + + +class LoopIRCuteDSLCodegen: + """Lower scheduler loop-body expressions to a CuTeDSL fragment function.""" + + def __init__(self, accumulator: str, removed_buffers: OrderedSet[str]) -> None: + self.accumulator = accumulator + self.removed_buffers = removed_buffers + self.kernel = GemmEpilogueCuteDSLKernel() + self.reads: OrderedSet[str] = OrderedSet() + self.input_values: dict[str, CuteDSLCSEVariable] = {} + self.accumulator_value = CuteDSLCSEVariable( + "accum", ValueRanges.unknown(), dtype=torch.float32, shape=(1,) + ) + + def load(self, name: str, stored: Any) -> Any: + if stored is not None: + return self.lower(stored) + if name == self.accumulator: + return self.accumulator_value + self.reads.add(name) + if name not in self.input_values: + dtype = V.graph.get_dtype(name) + self.input_values[name] = CuteDSLCSEVariable( + name, ValueRanges.unknown(), dtype=dtype, shape=(1,) + ) + return self.input_values[name] + + def lower(self, value: Any) -> Any: + if not isinstance(value, GemmEpilogueIRExpression): + if isinstance(value, tuple): + return tuple(self.lower(item) for item in value) + return value + if value.op == "load": + name, _, stored = value.args + return self.load(name, stored) + if value.op == "identity": + return self.lower(value.args[0]) + if value.op in ("reduction", "to_dtype_bitcast"): + raise NotImplementedError( + f"CuTeDSL GEMM epilogue does not support {value.op}" + ) + lowered_args = tuple(self.lower(arg) for arg in value.args) + lowered_kwargs = {key: self.lower(arg) for key, arg in value.kwargs} + op = getattr(GemmEpilogueCuteDSLOpOverrides, value.op, None) + if op is None: + raise NotImplementedError( + f"CuTeDSL GEMM epilogue op is not implemented: {value.op}" + ) + return op(*lowered_args, **lowered_kwargs) + + def render( + self, buffers: Sequence[ComputedBuffer], fn_name: str + ) -> tuple[list[str], list[str], dict[str, str], str]: + analysis = GemmEpilogueIRAnalysis.from_buffers(buffers) + outputs: list[tuple[str, Any]] = [] + if self.accumulator not in self.removed_buffers: + outputs.append((self.accumulator, self.accumulator_value)) + for name, store in analysis.stores.items(): + if name not in self.removed_buffers: + outputs.append((name, self.lower(store.value))) + if not outputs: + raise NotImplementedError("CuTeDSL GEMM epilogue has no outputs") + + renames = {name: name for name in self.reads} + result_names: list[str] = [] + for index, (buffer_name, value) in enumerate(outputs): + result_name = "D" if index == len(outputs) - 1 else f"output{index}" + self.kernel.body.writeline(f"{result_name} = {value}") + renames[result_name] = buffer_name + result_names.append(result_name) + + params = ", ".join(("accum", *self.reads)) + body = "\n".join(f" {line}" for line in self.kernel.body.lines) + source = ( + f"def {fn_name}({params}):\n{body}\n return {', '.join(result_names)}" + ) + return list(self.reads), [name for name, _ in outputs], renames, source + + @classmethod + def from_buffers( + cls, + accumulator: str, + buffers: Sequence[ComputedBuffer], + removed_buffers: OrderedSet[str], + fn_name: str, + ) -> tuple[list[str], list[str], dict[str, str], str]: + codegen = cls(accumulator, removed_buffers) + with ( + V.set_kernel_handler(codegen.kernel), + V.set_ops_handler(GemmEpilogueCuteDSLOpOverrides()), + ): + return codegen.render(buffers, fn_name) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/loop_ir_epilogue_lowering.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/loop_ir_epilogue_lowering.py new file mode 100644 index 0000000000000000000000000000000000000000..4bc9a3cfbc4a775a188a2da976b801eeccadad45 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/loop_ir_epilogue_lowering.py @@ -0,0 +1,1051 @@ +# mypy: allow-untyped-defs +"""Lower GEMM epilogue loop IR to shared epilogue contracts.""" + +import dataclasses +import math +from collections.abc import Sequence +from typing import Any + +import sympy + +import torch +from torch._inductor.ir import ComputedBuffer +from torch._inductor.kernel.gemm_epilogue import GemmReductionConfig +from torch._inductor.ops_handler import DefaultHandler +from torch._inductor.utils import OrderedSet +from torch._inductor.virtualized import V + + +@dataclasses.dataclass(frozen=True) +class GemmEpilogueIRExpression: + """Operation captured from a lowered GEMM epilogue loop body. + + Attributes: + op: Virtualized Inductor operation name. + args: Captured positional arguments. + kwargs: Captured keyword arguments in deterministic key order. + """ + + op: str + args: tuple[Any, ...] + kwargs: tuple[tuple[str, Any], ...] = () + loads: frozenset[str] = frozenset() + reductions: tuple["GemmEpilogueIRReduction", ...] = () + + +@dataclasses.dataclass(frozen=True) +class GemmEpilogueIRReduction: + reduction_type: str + source: GemmEpilogueIRExpression + result: int | None = None + source_type: str | None = None + + +@dataclasses.dataclass(frozen=True) +class GemmEpilogueIRRegion: + output_name: str + reductions: tuple[GemmEpilogueIRReduction, ...] + expression: GemmEpilogueIRExpression + + @property + def algorithm(self) -> str: + reduction_types = OrderedSet( + reduction.reduction_type for reduction in self.reductions + ) + if "online_softmax_reduce" in reduction_types: + return "online_softmax" + if "welford_reduce" in reduction_types: + return "welford" + return "generic" + + +@dataclasses.dataclass(frozen=True) +class GemmEpilogueIRStore: + """Symbolic store produced by replaying a lowered epilogue loop body. + + Attributes: + index: Symbolic destination index used by the lowered store. + value: Captured expression written at that index. + """ + + index: sympy.Expr + value: GemmEpilogueIRExpression + + +@dataclasses.dataclass(frozen=True) +class GemmEpilogueIROutputRole: + """Transitive inputs that determine one captured epilogue output. + + Attributes: + transitive_inputs: All buffers loaded directly or through stored values. + reduction_inputs: Loaded buffers whose captured values contain reductions. + """ + + transitive_inputs: frozenset[str] + reduction_inputs: frozenset[str] + + +@dataclasses.dataclass(frozen=True) +class GemmEpilogueIRFinalizer: + """Normalized operation applied to a completed grouped reduction.""" + + output_name: str + source_name: str + kind: str + + +def _expression_values(value: Any): + if isinstance(value, GemmEpilogueIRExpression): + yield value + elif isinstance(value, (tuple, list)): + for item in value: + yield from _expression_values(item) + + +def _unique_reductions( + values: Sequence[GemmEpilogueIRExpression], +) -> tuple[GemmEpilogueIRReduction, ...]: + reductions = [] + seen: OrderedSet[int] = OrderedSet() + for value in values: + for reduction in value.reductions: + if id(reduction) not in seen: + seen.add(id(reduction)) + reductions.append(reduction) + return tuple(reductions) + + +class _GemmEpilogueIRHandler(DefaultHandler): + def __init__(self) -> None: + self.stores: dict[str, GemmEpilogueIRStore] = {} + + def _default( + self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> GemmEpilogueIRExpression: + values = tuple(_expression_values((*args, *tuple(kwargs.values())))) + return GemmEpilogueIRExpression( + name, + args, + tuple(sorted(kwargs.items())), + frozenset().union(*(value.loads for value in values)), + _unique_reductions(values), + ) + + def indirect_indexing(self, x, size, check=True, wrap_neg=True): + return sympy.Symbol(f"indirect_{len(self.stores)}", integer=True) + + def load(self, name: str, index: sympy.Expr) -> GemmEpilogueIRExpression: + stored = self.stores.get(name) + if stored is None: + return GemmEpilogueIRExpression( + "load", (name, index, None), loads=frozenset((name,)) + ) + return GemmEpilogueIRExpression( + "load", + (name, index, stored.value), + loads=frozenset((name,)) | stored.value.loads, + reductions=stored.value.reductions, + ) + + def reduction(self, dtype, src_dtype, reduction_type, value): + args = (dtype, src_dtype, reduction_type, value) + if reduction_type in ("online_softmax_reduce", "welford_reduce"): + count = 2 if reduction_type == "online_softmax_reduce" else 3 + return tuple( + GemmEpilogueIRExpression( + "reduction", + (*args, index), + loads=value.loads, + reductions=( + *value.reductions, + GemmEpilogueIRReduction(reduction_type, value, index), + ), + ) + for index in range(count) + ) + return GemmEpilogueIRExpression( + "reduction", + args, + loads=value.loads, + reductions=( + *value.reductions, + GemmEpilogueIRReduction(reduction_type, value), + ), + ) + + def store( + self, + name: str, + index: sympy.Expr, + value: GemmEpilogueIRExpression, + mode=None, + ) -> None: + self.stores[name] = GemmEpilogueIRStore(index, value) + + def store_reduction( + self, name: str, index: sympy.Expr, value: GemmEpilogueIRExpression + ) -> None: + self.stores[name] = GemmEpilogueIRStore(index, value) + + +def _loaded_names(expr: Any) -> frozenset[str]: + if not isinstance(expr, GemmEpilogueIRExpression): + return frozenset() + if expr.op == "load": + name, _, stored = expr.args + return frozenset((name,)) | _loaded_names(stored) + return frozenset().union(*(_loaded_names(arg) for arg in expr.args)) + + +@dataclasses.dataclass(frozen=True) +class GemmEpilogueIRAnalysis: + """Candidate-wide semantic view of existing lowered loop bodies.""" + + stores: dict[str, GemmEpilogueIRStore] + + @classmethod + def from_buffers( + cls, buffers: Sequence[ComputedBuffer] + ) -> "GemmEpilogueIRAnalysis": + handler = _GemmEpilogueIRHandler() + with V.set_ops_handler(handler): + for buffer in buffers: + buffer.get_store_function()(*buffer.data.inner_fn_args()) + return cls(handler.stores) + + @classmethod + def store_from_buffer(cls, buffer: ComputedBuffer) -> GemmEpilogueIRStore | None: + return cls.from_buffers((buffer,)).store(buffer.get_name()) + + def store(self, name: str) -> GemmEpilogueIRStore | None: + return self.stores.get(name) + + def output_role(self, name: str) -> GemmEpilogueIROutputRole | None: + store = self.store(name) + if store is None: + return None + transitive_inputs = store.value.loads or _loaded_names(store.value) + return GemmEpilogueIROutputRole( + transitive_inputs, + transitive_inputs & self.reduction_stores, + ) + + def grouped_reduction( + self, + output_name: str, + source_name: str, + group: int, + axis: int, + source_dtype: torch.dtype, + ) -> GemmReductionConfig | None: + store = self.store(output_name) + classified = ( + grouped_reduction_ir(store, source_name, group, source_dtype) + if store is not None + else None + ) + if classified is None: + return None + reduction_type, source_type = classified + return GemmReductionConfig( + output_name, group, axis, reduction_type, source_type + ) + + def reduction_region( + self, + output_name: str, + source_name: str, + group: int, + source_dtype: torch.dtype, + ) -> GemmEpilogueIRRegion | None: + store = self.store(output_name) + if store is None: + return None + reductions = store.value.reductions or _synthetic_reductions_ir( + store.value, store.index, source_name, group, source_dtype + ) + if not reductions: + return None + if any( + (reduction.source.loads or _loaded_names(reduction.source)) + != frozenset((source_name,)) + for reduction in reductions + ): + return None + return GemmEpilogueIRRegion(output_name, reductions, store.value) + + def reduction_finalizer( + self, + output_name: str, + source_name: str, + group: int | None = None, + ) -> GemmEpilogueIRFinalizer | None: + store = self.store(output_name) + if store is None: + return None + if operation_names_ir(store).issubset( + ("load", "to_dtype", "to_dtype_bitcast", "identity") + ): + kind = "identity" + elif group is not None and single_source_affine_ir(store, source_name) == ( + 1.0 / group, + 0.0, + ): + kind = "mean" + elif is_absmax_scale_finalizer_ir(store, source_name): + kind = "absmax_scale" + elif ( + store.value.loads == frozenset((source_name,)) + and not store.value.reductions + ): + kind = "generic" + else: + return None + return GemmEpilogueIRFinalizer(output_name, source_name, kind) + + @property + def reduction_stores(self) -> frozenset[str]: + return frozenset( + name + for name, store in self.stores.items() + if store.value.reductions or _contains_reduction(store.value) + ) + + +def _constant_value(expr: Any) -> Any | None: + if not isinstance(expr, GemmEpilogueIRExpression): + return None + if expr.op in ("constant", "index_expr") and expr.args: + return expr.args[0] + if expr.op in ("to_dtype", "to_dtype_bitcast") and expr.args: + return _constant_value(expr.args[0]) + return None + + +def _strip_conversions(expr: Any) -> Any: + while ( + isinstance(expr, GemmEpilogueIRExpression) + and expr.op in ("to_dtype", "to_dtype_bitcast", "identity") + and expr.args + ): + expr = expr.args[0] + return expr + + +def _walk(expr: Any): + if not isinstance(expr, GemmEpilogueIRExpression): + return + yield expr + for arg in expr.args: + yield from _walk(arg) + + +def grouped_reduction_axis_ir( + reduction: GemmEpilogueIRReduction, group: int, n: int +) -> int | None: + """Infer grouped M/N geometry from the reduction source load strides.""" + indices = [ + expr.args[1] + for expr in _walk(reduction.source) + if expr.op == "load" and len(expr.args) > 1 + ] + unique_indices = [] + for index in indices: + if not any(sympy.simplify(index - other) == 0 for other in unique_indices): + unique_indices.append(index) + if len(unique_indices) != group: + return None + + def is_progression(step: int) -> bool: + return any( + all( + any( + sympy.simplify(index - (base + offset * step)) == 0 + for index in unique_indices + ) + for offset in range(group) + ) + for base in unique_indices + ) + + axes = [axis for axis, step in ((1, 1), (0, n)) if is_progression(step)] + return axes[0] if len(axes) == 1 else None + + +def operation_names_ir(store: GemmEpilogueIRStore) -> frozenset[str]: + return frozenset(expr.op for expr in _walk(store.value)) + + +def _source_transform( + expr: Any, + source_name: str, + allowed_conversion_dtypes: frozenset[torch.dtype] | None = None, +) -> str | None: + if allowed_conversion_dtypes is None: + expr = _strip_conversions(expr) + else: + while isinstance(expr, GemmEpilogueIRExpression) and expr.args: + if expr.op == "identity": + expr = expr.args[0] + elif expr.op == "to_dtype": + if len(expr.args) < 2 or expr.args[1] not in allowed_conversion_dtypes: + return None + expr = expr.args[0] + elif expr.op == "to_dtype_bitcast": + return None + else: + break + if not isinstance(expr, GemmEpilogueIRExpression): + return None + if expr.op == "load": + return "identity" if expr.args[0] == source_name else None + if expr.op == "abs": + return ( + "abs" + if _source_transform(expr.args[0], source_name, allowed_conversion_dtypes) + == "identity" + else None + ) + if expr.op == "mul" and expr.args[0] == expr.args[1]: + return ( + "square" + if _source_transform(expr.args[0], source_name, allowed_conversion_dtypes) + == "identity" + else None + ) + if expr.op == "pow": + exponent = _constant_value(expr.args[1]) + return ( + "square" + if exponent == 2 + and _source_transform(expr.args[0], source_name, allowed_conversion_dtypes) + == "identity" + else None + ) + return None + + +def _flatten_associative(expr: Any, op: str) -> list[Any]: + stripped = _strip_conversions(expr) + if isinstance(stripped, GemmEpilogueIRExpression) and stripped.op == op: + return _flatten_associative(stripped.args[0], op) + _flatten_associative( + stripped.args[1], op + ) + return [expr] + + +def grouped_reduction_ir( + store: GemmEpilogueIRStore, + source_name: str, + group: int, + source_dtype: torch.dtype, +) -> tuple[str, str] | None: + """Classify a primitive or unrolled grouped reduction loop body.""" + allowed_conversion_dtypes = frozenset((source_dtype, torch.float32)) + candidates = [expr for expr in _walk(store.value) if expr.op == "reduction"] + matches = [] + for reduction in candidates: + reduction_type = str(reduction.args[2]) + source_type = _source_transform( + reduction.args[3], source_name, allowed_conversion_dtypes + ) + if source_type is not None: + matches.append((reduction_type, source_type)) + if candidates: + return matches[0] if len(candidates) == len(matches) == 1 else None + + root = _strip_conversions(store.value) + while isinstance(root, GemmEpilogueIRExpression) and root.op in ( + "add", + "mul", + "truediv", + ): + if root.op == "truediv" and _constant_value(root.args[1]) == group: + terms = _flatten_associative(root.args[0], "add") + transforms = [ + _source_transform(term, source_name, allowed_conversion_dtypes) + for term in terms + ] + if ( + len(terms) == group + and len(frozenset(transforms)) == 1 + and transforms[0] + ): + return "mean", transforms[0] + terms = _flatten_associative(root, root.op) + transforms = [ + _source_transform(term, source_name, allowed_conversion_dtypes) + for term in terms + ] + if len(terms) == group and len(frozenset(transforms)) == 1 and transforms[0]: + return ("sum" if root.op == "add" else "prod"), transforms[0] + break + for op, reduction_type in (("maximum", "max"), ("minimum", "min")): + terms = _flatten_associative(root, op) + transforms = [ + _source_transform(term, source_name, allowed_conversion_dtypes) + for term in terms + ] + if len(terms) == group and len(frozenset(transforms)) == 1 and transforms[0]: + return reduction_type, transforms[0] + return None + + +def _synthetic_reductions_ir( + expr: Any, + index: sympy.Expr, + source_name: str, + group: int, + source_dtype: torch.dtype, +) -> tuple[GemmEpilogueIRReduction, ...]: + if not isinstance(expr, GemmEpilogueIRExpression): + return () + classified = grouped_reduction_ir( + GemmEpilogueIRStore(index, expr), source_name, group, source_dtype + ) + if classified is not None: + reduction_type, source_type = classified + return (GemmEpilogueIRReduction(reduction_type, expr, source_type=source_type),) + reductions = [] + seen: OrderedSet[int] = OrderedSet() + for arg in expr.args: + for value in _expression_values(arg): + for reduction in _synthetic_reductions_ir( + value, index, source_name, group, source_dtype + ): + if id(reduction.source) not in seen: + seen.add(id(reduction.source)) + reductions.append(reduction) + return tuple(reductions) + + +def is_direct_bool_gt_zero_ir(store: GemmEpilogueIRStore, source_name: str) -> bool: + """Match a direct comparison of one lowered buffer load against zero.""" + expr = _strip_conversions(store.value) + if not isinstance(expr, GemmEpilogueIRExpression) or expr.op not in ("gt", "ge"): + return False + lhs, rhs = map(_strip_conversions, expr.args[:2]) + return ( + isinstance(lhs, GemmEpilogueIRExpression) + and lhs.op == "load" + and lhs.args[0] == source_name + and _constant_value(rhs) == 0 + ) + + +def is_absmax_scale_finalizer_ir(store: GemmEpilogueIRStore, source_name: str) -> bool: + """Match clamp(source, 1e-12) / 448 used by FP8 absmax scaling.""" + expr = _strip_conversions(store.value) + if not isinstance(expr, GemmEpilogueIRExpression): + return False + if expr.op == "truediv" and _constant_value(expr.args[1]) == 448.0: + clamped = expr.args[0] + elif expr.op == "mul": + lhs, rhs = expr.args[:2] + if _constant_value(lhs) == 1.0 / 448.0: + clamped = rhs + elif _constant_value(rhs) == 1.0 / 448.0: + clamped = lhs + else: + return False + else: + return False + + clamped = _strip_conversions(clamped) + if not isinstance(clamped, GemmEpilogueIRExpression): + return False + if clamped.op in ("maximum", "clamp_min"): + lhs, rhs = clamped.args[:2] + return ( + _source_transform(lhs, source_name) == "identity" + and _constant_value(rhs) == 1e-12 + ) or ( + _source_transform(rhs, source_name) == "identity" + and _constant_value(lhs) == 1e-12 + ) + if clamped.op == "clamp" and len(clamped.args) >= 2: + return ( + _source_transform(clamped.args[0], source_name) == "identity" + and _constant_value(clamped.args[1]) == 1e-12 + and (len(clamped.args) < 3 or clamped.args[2] is None) + ) + return False + + +def _contains_reduction(expr: Any) -> bool: + if not isinstance(expr, GemmEpilogueIRExpression): + return False + return expr.op == "reduction" or any(_contains_reduction(arg) for arg in expr.args) + + +def _affine_scale( + value: tuple[float, float, float], scale: float +) -> tuple[float, float, float]: + return value[0] * scale, value[1] * scale, value[2] * scale + + +def _affine_add( + lhs: tuple[float, float, float], rhs: tuple[float, float, float] +) -> tuple[float, float, float]: + return lhs[0] + rhs[0], lhs[1] + rhs[1], lhs[2] + rhs[2] + + +def _affine_coefficients( + expr: Any, source_name: str, reduction_names: frozenset[str] +) -> tuple[float, float, float] | None: + expr = _strip_conversions(expr) + if isinstance(expr, (int, float, sympy.Number)) and not isinstance(expr, bool): + return 0.0, 0.0, float(expr) + if not isinstance(expr, GemmEpilogueIRExpression): + return None + if expr.op == "load": + name, _, stored = expr.args + if name == source_name: + return 1.0, 0.0, 0.0 + if name in reduction_names or _contains_reduction(stored): + return 0.0, 1.0, 0.0 + return _affine_coefficients(stored, source_name, reduction_names) + if expr.op == "reduction": + return 0.0, 1.0, 0.0 + constant = _constant_value(expr) + if isinstance(constant, (int, float, sympy.Number)) and not isinstance( + constant, bool + ): + return 0.0, 0.0, float(constant) + if expr.op == "neg": + value = _affine_coefficients(expr.args[0], source_name, reduction_names) + return None if value is None else _affine_scale(value, -1.0) + if expr.op in ("add", "sub"): + lhs = _affine_coefficients(expr.args[0], source_name, reduction_names) + rhs = _affine_coefficients(expr.args[1], source_name, reduction_names) + if lhs is None or rhs is None: + return None + scale = 1.0 if expr.op == "add" else -1.0 + return _affine_add(lhs, _affine_scale(rhs, scale)) + if expr.op in ("mul", "truediv"): + lhs = _affine_coefficients(expr.args[0], source_name, reduction_names) + rhs = _affine_coefficients(expr.args[1], source_name, reduction_names) + if lhs is None or rhs is None: + return None + if expr.op == "truediv": + if rhs[:2] != (0.0, 0.0) or rhs[2] == 0.0: + return None + return _affine_scale(lhs, 1.0 / rhs[2]) + if lhs[:2] == (0.0, 0.0): + return _affine_scale(rhs, lhs[2]) + if rhs[:2] == (0.0, 0.0): + return _affine_scale(lhs, rhs[2]) + if expr.op == "fma": + lhs = _affine_coefficients(expr.args[0], source_name, reduction_names) + rhs = _affine_coefficients(expr.args[1], source_name, reduction_names) + addend = _affine_coefficients(expr.args[2], source_name, reduction_names) + if lhs is None or rhs is None or addend is None: + return None + if lhs[:2] == (0.0, 0.0): + product = _affine_scale(rhs, lhs[2]) + elif rhs[:2] == (0.0, 0.0): + product = _affine_scale(lhs, rhs[2]) + else: + return None + return _affine_add(product, addend) + return None + + +def centered_mean_consumer_type_ir( + store: GemmEpilogueIRStore, + source_name: str, + reduction_names: frozenset[str], + reduction_scale: float = 1.0, +) -> str | None: + """Classify an affine combination of a lowered value and grouped reduction.""" + coefficients = _affine_coefficients(store.value, source_name, reduction_names) + if coefficients is not None: + coefficients = ( + coefficients[0], + coefficients[1] * reduction_scale, + coefficients[2], + ) + if ( + coefficients is None + or coefficients[0] == 0.0 + or coefficients[1] == 0.0 + or not all(math.isfinite(value) for value in coefficients) + ): + return None + return "mean_linear:" + ":".join(format(value, ".17g") for value in coefficients) + + +def single_source_affine_ir( + store: GemmEpilogueIRStore, source_name: str +) -> tuple[float, float] | None: + """Return scale and bias for an affine expression of one lowered buffer.""" + coefficients = _affine_coefficients(store.value, source_name, frozenset()) + if coefficients is None or coefficients[1] != 0.0: + return None + return coefficients[0], coefficients[2] + + +def _affine_around(expr: Any, basis) -> tuple[float, float] | None: + expr = _strip_conversions(expr) + if basis(expr): + return 1.0, 0.0 + constant = _constant_value(expr) + if isinstance(constant, (int, float, sympy.Number)) and not isinstance( + constant, bool + ): + return 0.0, float(constant) + if not isinstance(expr, GemmEpilogueIRExpression): + return None + if expr.op == "neg": + value = _affine_around(expr.args[0], basis) + return None if value is None else (-value[0], -value[1]) + if expr.op in ("add", "sub"): + lhs = _affine_around(expr.args[0], basis) + rhs = _affine_around(expr.args[1], basis) + if lhs is None or rhs is None: + return None + sign = 1.0 if expr.op == "add" else -1.0 + return lhs[0] + sign * rhs[0], lhs[1] + sign * rhs[1] + if expr.op == "mul": + lhs = _affine_around(expr.args[0], basis) + rhs = _affine_around(expr.args[1], basis) + if lhs is None or rhs is None: + return None + if lhs[0] == 0.0: + return rhs[0] * lhs[1], rhs[1] * lhs[1] + if rhs[0] == 0.0: + return lhs[0] * rhs[1], lhs[1] * rhs[1] + return None + + +def _is_source(expr: Any, source_name: str) -> bool: + return _source_transform(expr, source_name) == "identity" + + +def _sum_terms(expr: Any, source_name: str, group: int) -> bool: + terms = _flatten_associative(expr, "add") + return len(terms) == group and all(_is_source(term, source_name) for term in terms) + + +def _group_max(expr: Any, source_name: str, group: int) -> bool: + terms = _flatten_associative(expr, "maximum") + return len(terms) == group and all(_is_source(term, source_name) for term in terms) + + +def _stable_group_max(expr: Any, source_name: str, group: int) -> bool: + """Match max(xs), including logsumexp's where(isinf(max), 0, max).""" + expr = _strip_conversions(expr) + if _group_max(expr, source_name, group): + return True + if not ( + isinstance(expr, GemmEpilogueIRExpression) + and expr.op == "where" + and len(expr.args) >= 3 + and _constant_value(expr.args[1]) == 0.0 + ): + return False + condition = _strip_conversions(expr.args[0]) + maximum = _strip_conversions(expr.args[2]) + if not ( + isinstance(condition, GemmEpilogueIRExpression) + and condition.op == "eq" + and _group_max(maximum, source_name, group) + ): + return False + for absolute, infinity in (condition.args[:2], reversed(condition.args[:2])): + absolute = _strip_conversions(absolute) + if ( + isinstance(absolute, GemmEpilogueIRExpression) + and absolute.op == "abs" + and _strip_conversions(absolute.args[0]) == maximum + and _constant_value(infinity) == math.inf + ): + return True + return False + + +def _shifted_exp(expr: Any, source_name: str) -> Any | None: + expr = _strip_conversions(expr) + if not ( + isinstance(expr, GemmEpilogueIRExpression) and expr.op == "exp" and expr.args + ): + return None + shifted = _strip_conversions(expr.args[0]) + if not ( + isinstance(shifted, GemmEpilogueIRExpression) + and shifted.op == "sub" + and _is_source(shifted.args[0], source_name) + ): + return None + return _strip_conversions(shifted.args[1]) + + +def is_softmax_ir( + store: GemmEpilogueIRStore, + source_name: str, + group: int, + reduction_names: frozenset[str] = frozenset(), +) -> bool: + """Match stable grouped softmax, either unrolled or reduction-backed.""" + expr = _strip_conversions(store.value) + if not isinstance(expr, GemmEpilogueIRExpression) or expr.op != "truediv": + return False + numerator, denominator = expr.args[:2] + maximum = _shifted_exp(numerator, source_name) + if maximum is None: + return False + denominator = _strip_conversions(denominator) + if reduction_names: + return ( + isinstance(maximum, GemmEpilogueIRExpression) + and maximum.op == "load" + and maximum.args[0] in reduction_names + and isinstance(denominator, GemmEpilogueIRExpression) + and denominator.op == "load" + and denominator.args[0] in reduction_names + and maximum.args[0] != denominator.args[0] + ) + terms = _flatten_associative(denominator, "add") + return ( + _group_max(maximum, source_name, group) + and len(terms) == group + and all(_shifted_exp(term, source_name) == maximum for term in terms) + ) + + +def is_absmax_normalize_ir( + store: GemmEpilogueIRStore, + source_name: str, + scale_names: str | frozenset[str], +) -> bool: + """Match source * reciprocal(clamp(absmax, 1e-12) / 448).""" + if isinstance(scale_names, str): + scale_names = frozenset((scale_names,)) + expr = _strip_conversions(store.value) + if not isinstance(expr, GemmEpilogueIRExpression) or expr.op != "mul": + return False + for source, reciprocal in (expr.args[:2], reversed(expr.args[:2])): + reciprocal = _strip_conversions(reciprocal) + if ( + _is_source(source, source_name) + and isinstance(reciprocal, GemmEpilogueIRExpression) + and reciprocal.op == "reciprocal" + and any( + is_absmax_scale_finalizer_ir( + GemmEpilogueIRStore(store.index, reciprocal.args[0]), scale_name + ) + for scale_name in scale_names + ) + ): + return True + return False + + +def _sum_affine_ir( + expr: Any, + source_name: str, + reduction_names: frozenset[str], + group: int, +) -> tuple[float, float] | None: + def is_sum(candidate: Any) -> bool: + candidate = _strip_conversions(candidate) + return ( + isinstance(candidate, GemmEpilogueIRExpression) + and candidate.op == "load" + and candidate.args[0] in reduction_names + ) or _sum_terms(candidate, source_name, group) + + return _affine_around(expr, is_sum) + + +def sum_normalize_consumer_type_ir( + store: GemmEpilogueIRStore, + source_name: str, + reduction_names: frozenset[str], + group: int, +) -> str | None: + """Classify normalization by a primitive or unrolled grouped sum.""" + parameters: tuple[str, float, float] | None = None + + def is_normalization(expr: Any) -> bool: + nonlocal parameters + expr = _strip_conversions(expr) + if not isinstance(expr, GemmEpilogueIRExpression): + return False + if expr.op == "truediv": + lhs, rhs = expr.args[:2] + if _is_source(lhs, source_name): + affine = _sum_affine_ir(rhs, source_name, reduction_names, group) + if affine is not None: + parameters = "forward", *affine + return True + if _is_source(rhs, source_name): + affine = _sum_affine_ir(lhs, source_name, reduction_names, group) + if affine is not None: + parameters = "reverse", *affine + return True + if expr.op == "mul": + for source, reciprocal in (expr.args[:2], reversed(expr.args[:2])): + reciprocal = _strip_conversions(reciprocal) + if ( + _is_source(source, source_name) + and isinstance(reciprocal, GemmEpilogueIRExpression) + and reciprocal.op == "reciprocal" + ): + affine = _sum_affine_ir( + reciprocal.args[0], source_name, reduction_names, group + ) + if affine is not None: + parameters = "forward", *affine + return True + return False + + affine = _affine_around(store.value, is_normalization) + if ( + affine is None + or parameters is None + or affine[0] == 0.0 + or not all(math.isfinite(value) for value in (*affine, *parameters[1:])) + ): + return None + kind = ( + "normalize_sum_affine" + if parameters[0] == "forward" + else "normalize_sum_reverse_affine" + ) + values = (*affine, *parameters[1:]) + return kind + ":" + ":".join(format(value, ".17g") for value in values) + + +def sum_multiply_consumer_type_ir( + store: GemmEpilogueIRStore, + source_name: str, + reduction_names: frozenset[str], + group: int, +) -> str | None: + expr = _strip_conversions(store.value) + if not isinstance(expr, GemmEpilogueIRExpression) or expr.op != "mul": + return None + for source, reduction in (expr.args[:2], reversed(expr.args[:2])): + if not _is_source(source, source_name): + continue + affine = _sum_affine_ir(reduction, source_name, reduction_names, group) + if affine is not None and all(math.isfinite(value) for value in affine): + return "sum_mul_affine:" + ":".join( + format(value, ".17g") for value in affine + ) + return None + + +def variance_parameters_ir( + store: GemmEpilogueIRStore, source_name: str, group: int +) -> tuple[float, float] | None: + """Match an unrolled grouped variance followed by an affine transform.""" + + def is_variance(expr: Any) -> bool: + expr = _strip_conversions(expr) + if not isinstance(expr, GemmEpilogueIRExpression) or expr.op != "truediv": + return False + if _constant_value(expr.args[1]) != group: + return False + squares = _flatten_associative(expr.args[0], "add") + if len(squares) != group: + return False + for square in squares: + square = _strip_conversions(square) + if not ( + isinstance(square, GemmEpilogueIRExpression) + and square.op == "mul" + and square.args[0] == square.args[1] + ): + return False + centered = _strip_conversions(square.args[0]) + if not ( + isinstance(centered, GemmEpilogueIRExpression) + and centered.op == "sub" + and _is_source(centered.args[0], source_name) + ): + return False + mean = _strip_conversions(centered.args[1]) + if not ( + isinstance(mean, GemmEpilogueIRExpression) + and mean.op == "truediv" + and _constant_value(mean.args[1]) == group + and _sum_terms(mean.args[0], source_name, group) + ): + return False + return True + + affine = _affine_around(store.value, is_variance) + return affine if affine is not None and affine[0] != 0.0 else None + + +def centered_mean_consumer_type_unrolled_ir( + store: GemmEpilogueIRStore, source_name: str, group: int +) -> str | None: + """Classify an affine source/mean expression after a small reduction unroll.""" + + def coefficients(expr: Any) -> tuple[float, float, float] | None: + expr = _strip_conversions(expr) + if isinstance(expr, GemmEpilogueIRExpression) and expr.op == "truediv": + if _constant_value(expr.args[1]) == group and _sum_terms( + expr.args[0], source_name, group + ): + return 0.0, 1.0, 0.0 + if _is_source(expr, source_name): + return 1.0, 0.0, 0.0 + constant = _constant_value(expr) + if isinstance(constant, (int, float, sympy.Number)) and not isinstance( + constant, bool + ): + return 0.0, 0.0, float(constant) + if not isinstance(expr, GemmEpilogueIRExpression): + return None + if expr.op in ("add", "sub"): + lhs, rhs = coefficients(expr.args[0]), coefficients(expr.args[1]) + if lhs is None or rhs is None: + return None + return _affine_add( + lhs, _affine_scale(rhs, 1.0 if expr.op == "add" else -1.0) + ) + if expr.op == "mul": + lhs, rhs = coefficients(expr.args[0]), coefficients(expr.args[1]) + if lhs is None or rhs is None: + return None + if lhs[:2] == (0.0, 0.0): + return _affine_scale(rhs, lhs[2]) + if rhs[:2] == (0.0, 0.0): + return _affine_scale(lhs, rhs[2]) + return None + + values = coefficients(store.value) + if ( + values is None + or values[0] == 0.0 + or values[1] == 0.0 + or not all(math.isfinite(value) for value in values) + ): + return None + return "mean_linear:" + ":".join(format(value, ".17g") for value in values) + + +def is_logsumexp_ir(store: GemmEpilogueIRStore, source_name: str, group: int) -> bool: + """Match max(xs) + log(sum(exp(xs - max(xs)))).""" + expr = _strip_conversions(store.value) + if not isinstance(expr, GemmEpilogueIRExpression) or expr.op != "add": + return False + for maximum, logarithm in (expr.args[:2], reversed(expr.args[:2])): + maximum = _strip_conversions(maximum) + logarithm = _strip_conversions(logarithm) + if not ( + _stable_group_max(maximum, source_name, group) + and isinstance(logarithm, GemmEpilogueIRExpression) + and logarithm.op == "log" + ): + continue + terms = _flatten_associative(logarithm.args[0], "add") + if len(terms) == group and all( + _shifted_exp(term, source_name) == maximum for term in terms + ): + return True + return False diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/mm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/mm.py new file mode 100644 index 0000000000000000000000000000000000000000..723e00d3a223f52ff7db939441acbc7a8ec456fc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/mm.py @@ -0,0 +1,1445 @@ +# mypy: allow-untyped-defs +import functools +import logging +from typing import Any + +import torch +from torch._dynamo.utils import counters +from torch._inductor.autoheuristic.autoheuristic import AutoHeuristicSelectAlgorithm +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + context_add_strides, + context_add_using_tf32, + mm_operations, +) +from torch._inductor.codegen.cpp_gemm_template import CppGemmTemplate +from torch._inductor.remote_gemm_autotune_cache import gen_best_config +from torch._inductor.virtualized import ops, V +from torch.fx.experimental.proxy_tensor import make_fx +from torch.nn.functional import ScalingType # type: ignore[attr-defined] +from torch.torch_version import TorchVersion +from torch.utils._ordered_set import OrderedSet + +from .. import config as inductor_config, distributed_autotune, lowering as L +from ..codegen.cutlass.gemm_template import CUTLASS2xGemmTemplate, CUTLASS3xGemmTemplate +from ..codegen.rocm.ck_tile_universal_gemm_template import CKTileGemmTemplate +from ..codegen.rocm.ck_universal_gemm_template import CKGemmTemplate +from ..codegen.subgraph import SubgraphChoiceCaller, SubgraphTemplate +from ..ir import Buffer, ChoiceCaller, is_triton, Layout +from ..kernel_inputs import MMKernelInputs +from ..lowering import ( + fallback_handler, + lowerings, + make_pointwise, + make_reduction, + register_lowering, + transform_args, +) +from ..select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, + KernelTemplate, + realize_inputs, + TritonTemplate, +) +from ..utils import ( + _use_cutlass_for_op, + ceildiv, + use_aten_gemm_kernels, + use_ck_gemm_template, + use_ck_tile_gemm_template, + use_cpp_gemm_template, + use_cutlass_template, + use_decompose_k_choice, + use_nv_universal_gemm_template, + use_triton_blackwell_tma_template, + use_triton_scaling_template, + use_triton_template, + use_triton_tma_template, +) +from .mm_common import ( + _is_static_problem, + _use_small_mm_pointwise, + load_kernel_template, + mm_args, + mm_grid, + persistent_mm_grid, + use_native_matmul, +) + + +try: + import triton + + triton_version = TorchVersion(triton.__version__) + has_triton = True +except ImportError: + triton_version = TorchVersion("0.0.0") + has_triton = False + +log = logging.getLogger(__name__) +aten = torch.ops.aten +prims = torch.ops.prims + +# We define each template kernel in a separate file which is the name of the input to load_kernel_template +# (e.g. triton_mm for templates/triton_mm.py.jinja). +# If you are adding a new template, please follow that pattern and add a new file with your implementation in the templates folder. +mm_template = TritonTemplate( + name="mm", + grid=mm_grid, + source=load_kernel_template("triton_mm") + if (torch.version.hip is None) or triton_version >= "3.3.0" + # FIXME: To get around rocm failures. + # The only difference between the two templates is M >= BLOCK_M and N >= BLOCK_N checking. + # See more details in https://github.com/pytorch/pytorch/pull/146293 + else load_kernel_template("triton_mm_rocm"), + cache_codegen_enabled_for_template=True, + prologue_loads_all_inputs=True, +) + +persistent_tma_mm_template = TritonTemplate( + name="mm_persistent_tma", + grid=persistent_mm_grid, + source=load_kernel_template("triton_persistent_tma_mm"), +) + +# Non-TMA Triton template for persistent MM +# used on AMD +persistent_mm_template = TritonTemplate( + name="mm_persistent", + grid=persistent_mm_grid, + source=load_kernel_template("triton_persistent_mm"), +) + + +scaled_mm_device_tma_epilogue_scaling_template = TritonTemplate( + name="scaled_mm_device_tma_epilogue_scaling", + grid=persistent_mm_grid, + source=load_kernel_template("triton_epilogue_scaled_mm"), +) + + +scaled_mm_device_tma_main_loop_scaling_template = TritonTemplate( + name="scaled_mm_device_tma_main_loop_scaling", + grid=persistent_mm_grid, + source=load_kernel_template("triton_main_loop_scaled_mm"), +) + +blackwell_ws_persistent_device_tma_mm_template = TritonTemplate( + name="blackwell_ws_persistent_device_tma", + grid=persistent_mm_grid, + source=load_kernel_template("triton_blackwell_ws_persistent_device_tma_mm"), +) + + +# prevent duplication registration of extern functions +@functools.cache +def lazy_register_extern_choice(fn): + return ExternKernelChoice(fn) + + +aten_mm = ExternKernelChoice(torch.mm, "at::mm_out", op_overload=aten.mm.out) +aten_mm_dtype = ExternKernelChoice( + torch.mm, + "at::mm_dtype_out", + name="mm_dtype", + op_overload=aten.mm.dtype_out, +) + +aten_addmm = ExternKernelChoice( + torch.addmm, "at::addmm_out", op_overload=aten.addmm.out +) + +aten__int_mm = ExternKernelChoice( + torch._int_mm, "at::_int_mm_out", op_overload=aten._int_mm.out +) + +aten__sparse_semi_structured_mm = ExternKernelChoice( + torch._sparse_semi_structured_mm, + "at::_sparse_semi_structured_mm", + has_out_variant=False, + op_overload=aten._sparse_semi_structured_mm.default, +) + +aten__fp8_mm = ExternKernelChoice( + torch._scaled_mm, "at::_scaled_mm_out", op_overload=aten._scaled_mm.out +) + + +def _is_int8_mat(mat): + return mat.get_dtype() in (torch.int8, torch.uint8) + + +def bias_addmm(inp, mat1, mat2, *, out=None, alpha=1, beta=1): + """ + Giving torch.addmm a 1D tensor calls a different (faster) cublasLt + kernel under the hood. There are a few shapes where this is slower, + but they are rare. + """ + if (inp.stride(0) == 0 and inp.size(0) != 0) or inp.size(0) == 1: + return torch.addmm(inp[0], mat1, mat2, out=out, alpha=alpha, beta=beta) + return torch.addmm(inp, mat1, mat2, out=out, alpha=alpha, beta=beta) + + +def check_supported_striding(mat_a, mat_b) -> None: + def is_row_major(stride) -> bool: + return V.graph.sizevars.statically_known_equals(stride[1], 1) + + def is_col_major(stride) -> bool: + return V.graph.sizevars.statically_known_equals(stride[0], 1) + + def has_zero_dim(size) -> bool: + return bool( + V.graph.sizevars.statically_known_equals(size[0], 0) + or V.graph.sizevars.statically_known_equals(size[1], 0) + ) + + # Check mat_a (self) stride requirements + torch._check( + is_row_major(mat_a.get_stride()) or has_zero_dim(mat_a.get_size()), + lambda: f"mat_a must be row_major, got stride {mat_a.get_stride()}", + ) + + # Check mat_b stride requirements + torch._check( + is_col_major(mat_b.get_stride()) or has_zero_dim(mat_b.get_size()), + lambda: f"mat_b must be col_major, got stride {mat_b.get_stride()}", + ) + + +aten_bias_addmm = ExternKernelChoice(bias_addmm, None) + + +def _check_addmm_input_metadata(inp, mat1, mat2) -> None: + torch._check( + inp.get_dtype() == mat1.get_dtype() and inp.get_dtype() == mat2.get_dtype(), + lambda: "input dtypes must be the same", + ) + torch._check( + inp.get_device() == mat1.get_device() and inp.get_device() == mat2.get_device(), + lambda: "all inputs must be on the same device", + ) + + +def decomposeK(a, b, k_splits): + m = a.shape[0] + n = b.shape[1] + k = a.shape[1] + + k_parts = k // k_splits + B = k_splits + a_reshaped = torch.permute(a.reshape(m, B, k_parts), (1, 0, 2)) + b_reshaped = b.reshape(B, k_parts, n) + result = torch.bmm(a_reshaped, b_reshaped, out_dtype=torch.float32) + reduced_buf = torch.sum(result, 0) + return reduced_buf.to(a.dtype) + + +class DecomposeKSugraphTemplate(SubgraphTemplate): + def __init__(self): + super().__init__( + name="decompose_k", + ) + + def generate( # type: ignore[override] + self, + input_nodes: list[Buffer], + layout: Layout, + k_split: int, + ) -> SubgraphChoiceCaller: + from torch._dispatch.python import enable_python_dispatcher + + from ..decomposition import select_decomp_table + + name = f"decompose_k_mm_{k_split}_split" + description = f"{k_split=}" + + with enable_python_dispatcher(): + decompositions = select_decomp_table() + fn = make_fx( + functools.partial(decomposeK, k_splits=k_split), + decompositions, + ) + + return super().generate( + name=name, + input_nodes=input_nodes, + layout=layout, + make_fx_graph=fn, + description=description, + ) + + +decompose_k_subgraph_template = DecomposeKSugraphTemplate() + + +class ContiguousTemplate(SubgraphTemplate): + def __init__(self, name: str, description: str, fn: Any): + self.name = name + self.description = description + self.fn = fn + super().__init__( + name=name, + ) + + def generate( # type: ignore[override] + self, + input_nodes: list[Buffer], + layout: Layout, + ) -> SubgraphChoiceCaller: + from torch._dispatch.python import enable_python_dispatcher + + from ..decomposition import select_decomp_table + + with enable_python_dispatcher(): + decompositions = select_decomp_table() + fn = make_fx( + self.fn, + decompositions, + ) + + return super().generate( + name=self.name, + input_nodes=input_nodes, + layout=layout, + make_fx_graph=fn, + description=self.description, + ) + + +def contiguous_mm(a, b): + return torch.mm(a, b.contiguous()) + + +def contiguous_addmm(inp, a, b): + return torch.addmm(inp, a, b.contiguous()) + + +mm_contiguous_subgraph_template = ContiguousTemplate( + "contiguous_mm", "contiguous mm", contiguous_mm +) +addmm_contiguous_subgraph_template = ContiguousTemplate( + "contiguous_addmm", "contiguous addmm", contiguous_addmm +) + + +@register_lowering(aten.mm, type_promotion_kind=None) +def tuned_mm(mat1, mat2, out_dtype=None, *, layout=None): + """ + Lowering for autotuning aten.mm with different backends (Aten, Triton, CUTLASS, etc.) + """ + if out_dtype is not None: + input_dtype = mat1.get_dtype() + torch._check( + mat2.get_dtype() == input_dtype, + lambda: "input dtypes must be the same", + ) + torch._check( + mat1.get_device().type in ("cuda", "xpu"), + lambda: "out_dtype is only supported for CUDA or XPU", + ) + torch._check( + out_dtype == input_dtype + or ( + out_dtype == torch.float32 + and input_dtype in (torch.float16, torch.bfloat16) + ), + lambda: "out_dtype must be the same as input dtype or fp32 for fp16/bf16 inputs", + ) + + # Lower matmul-related operations (e.g., torch.matmul / torch.bmm / torch.addmm) + # into native matmul IR using `ops.dot`. When we see a matmul pattern + # (C[y, x] = A[y, r] * B[r, x]), the core idea is to emulate a broadcasted + # multiply followed by a sum. + # + # For example, given `C = torch.matmul(A, B)`, this can be rewritten as: + # + # Prod = A.unsqueeze(-1) * B.unsqueeze(0) + # C = Prod.sum(dim=1) + # + # Instead of explicitly using `ops.mul` and `ops.reduction("sum")`, we lower + # these into `ops.dot` (pointwise) and `ops.reduction("dot")`. These IR nodes + # are semantically equivalent to the `ops.mul` + `ops.reduction("sum")` + # combination, but are lowered to `tl.dot` during the code generation phase. + if use_native_matmul(mat1, mat2): + mat1 = lowerings[aten.unsqueeze](mat1, -1) + mat2 = lowerings[aten.unsqueeze](mat2, 0) + args, kwargs = transform_args( + args=[mat1, mat2], + kwargs={}, + broadcast=True, + type_promotion_kind=None, + convert_input_to_bool=False, + ) # Handles broadcasting the arguments + + if inductor_config.triton.codegen_upcast_to_fp32 and mat1.dtype in [ + torch.float16, + torch.bfloat16, + ]: + + def _to_dtype(x): + return ops.to_dtype(x, mat1.dtype, use_compute_types=False) + + args = [make_pointwise(_to_dtype)(x) for x in args] + mul_pointwise = make_pointwise(ops.dot)(*args) + dot_reduction = make_reduction("dot")(mul_pointwise, 1) + + return dot_reduction + + # TODO(coconutruben): integrate into MMKernelInputs when all callsites use that + m, n, k, layout, mat1, mat2 = mm_args( + mat1, mat2, layout=layout, out_dtype=out_dtype + ) + + if out_dtype is None and _use_small_mm_pointwise(m, k, n, layout): + counters["inductor"]["decompose_mm_pointwise"] += 1 + mat1 = L.unsqueeze(mat1, -1) + mat2 = L.unsqueeze(mat2, 0) + return L.sum_(L.mul(mat1, mat2), axis=1) + + static_shape, is_nonzero = _is_static_problem(layout) + name = "mm" + + # Create MMKernelInputs for standard MM at the top + kernel_inputs = MMKernelInputs([mat1, mat2], out_dtype=out_dtype) + + # below is for getting an overview logging info of inductor mms + counters["aten_mm_info"][f"aten.mm_{m}_{n}_{k}"] += 1 + log.info( + "Tuned aten.mm: m=%s, n=%s, k=%s, mat1_dtype=%s, mat2_dtype=%s, output_layout=%s", + m, + n, + k, + mat1.get_dtype(), + mat2.get_dtype(), + layout, + ) + + choices: list[ChoiceCaller] = [] + static_shape, is_nonzero = _is_static_problem(layout) + + aten_handler: ExternKernelChoice = aten_mm + aten_extra_kwargs: dict[str, Any] = {} + if out_dtype is not None: + aten_handler = aten_mm_dtype + aten_extra_kwargs = {"out_dtype": out_dtype} + + templates_to_use: list[ExternKernelChoice | KernelTemplate] = [] + kwarg_overrides: dict[str, dict[str, Any]] = {} + if use_aten_gemm_kernels(): + templates_to_use.append(aten_handler) + if aten_extra_kwargs: + kwarg_overrides[aten_handler.uid] = aten_extra_kwargs + + if ( + out_dtype is None + and is_nonzero + and use_triton_template(layout, check_max_autotune=True) + ): + if use_decompose_k_choice(m, n, k): + templates_to_use.append(decompose_k_subgraph_template) + # Triton Templates typically perform very poorly for large K. + # Its highly unlikely that if we want to use decompose_k, then + # Triton will ever win. + # + # To be conservative we increase this threshold for N/M by 2. + is_exhaustive = inductor_config.max_autotune_gemm_search_space == "exhaustive" + if is_exhaustive or not use_decompose_k_choice(m, n, k, threshold_multiple=2): + templates_to_use.append(mm_template) + + if use_triton_blackwell_tma_template( + mat1, mat2, output_layout=layout, add_guards=True + ): + templates_to_use.append(blackwell_ws_persistent_device_tma_mm_template) + elif use_triton_tma_template( + mat1, mat2, output_layout=layout, add_guards=True + ): + if torch.version.hip is None: + templates_to_use.append(persistent_tma_mm_template) + else: + templates_to_use.append(persistent_mm_template) + + templates_to_use.append(mm_contiguous_subgraph_template) + + choices.extend( + V.choices.get_template_configs( + kernel_inputs, + templates_to_use, + "mm", + kwarg_overrides=kwarg_overrides, + ) + ) + + if ( + out_dtype is None + and is_nonzero + and use_cutlass_template(layout, m, n, k) + and _use_cutlass_for_op("mm") + ): + CUTLASS3xGemmTemplate.add_cutlass_gemm_choices( + choices, layout, kernel_inputs.nodes() + ) + + if out_dtype is None and is_nonzero and use_ck_gemm_template(layout, m, n, k): + CKGemmTemplate.add_ck_gemm_choices(choices, layout, kernel_inputs.nodes()) + if out_dtype is None and is_nonzero and use_ck_tile_gemm_template(layout, m, n, k): + CKTileGemmTemplate.add_choices(choices, layout, kernel_inputs.nodes()) + + if ( + out_dtype is None + and is_nonzero + and use_nv_universal_gemm_template(layout, m, n, k, mat1, mat2) + ): + from ..codegen.nv_universal_gemm import add_nv_universal_gemm_choices + + add_nv_universal_gemm_choices(choices, layout, kernel_inputs) + + if out_dtype is None and use_cpp_gemm_template(layout, mat1, mat2): + CppGemmTemplate.add_choices( + choices, + layout, + kernel_inputs.nodes(), + ) + + input_nodes = [mat1, mat2] + if ( + out_dtype is None + and is_nonzero + and use_triton_template(layout) + and torch._inductor.config.run_autoheuristic(name) + and is_triton(mat1) + ): + always_included = [] + if use_aten_gemm_kernels(): + always_included.append("extern_mm") + num_choices_before_extra_configs = len(choices) + choices.extend( + V.choices.get_template_configs( + # TODO(coconutruben): remove once we deprecate ah + # mm-extra is a hack to keep the ah functionality alive + # while we transition to the unified kwargs retrieval + kernel_inputs, + [mm_template], + "mm-ah", + ) + ) + + # using AutoHeuristic for ranking + ah_choices = mm_autoheuristic( + mat1, + mat2, + m, + n, + k, + choices, + name, + input_nodes, + mm_operations(), + None, + top_k=10, + always_included=always_included, + ) + if not torch._inductor.config.collect_autoheuristic(name): + # if we are collecting data, we do not want to modify choices + if ah_choices is not None and len(ah_choices) > 0: + # the order in which autoheuristic returns choices is not the same as + # as the order of choices, which affects things like epilogue fusion. + # once epilogue fusion benchmarks choices in sorted order, I think we can + # just use the order returned by autoheuristic + choices = [choice for choice in choices if choice in ah_choices] + else: + choices = choices[:num_choices_before_extra_configs] + + if out_dtype is None: + for k in inductor_config.external_matmul: + choices.append( + lazy_register_extern_choice(k).bind(kernel_inputs.nodes(), layout) + ) + + best_config_future = None + if out_dtype is None and torch._inductor.config.remote_gemm_autotune_cache: + # Purposely not awaiting the future here - this kicks off the best config lookup at lowering time + # The future will be awaited at scheduling time in select_algorithm.py + best_config_future = gen_best_config(mat1, mat2) + + if box := distributed_autotune.maybe_autotune_remote( + name, choices, kernel_inputs.nodes(), layout + ): + return box + + node, _ = autotune_select_algorithm( + name, + choices, + kernel_inputs.nodes(), + layout, + best_config_future=best_config_future, + ) + return node + + +@register_lowering(aten._int_mm, type_promotion_kind=None) +def tuned_int_mm(mat1, mat2, *, layout=None): + # TODO(coconutruben): integrate into MMKernelInputs when all callsites use that + m, n, k, layout, mat1, mat2 = mm_args( + mat1, mat2, layout=layout, out_dtype=torch.int32 + ) + name = "int_mm" + # below is for getting an overview logging info of inductor mms + counters["aten_mm_info"][f"aten._int_mm_{m}_{n}_{k}"] += 1 + log.info( + "Tuned aten._int_mm: m=%s, n=%s, k=%s, mat1_dtype=%s, mat2_dtype=%s, output_layout=%s", + m, + n, + k, + mat1.get_dtype(), + mat2.get_dtype(), + layout, + ) + + static_shape, is_nonzero = _is_static_problem(layout) + use_cutlass = static_shape and is_nonzero and use_cutlass_template(layout, m, n, k) + choices: list[ChoiceCaller] = [] + + # Create MMKernelInputs for Int MM + kernel_inputs = MMKernelInputs([mat1, mat2], out_dtype=torch.int32) + + # Collect all templates for unified call + templates_to_use: list[ExternKernelChoice | KernelTemplate] = [] + if use_aten_gemm_kernels(): + templates_to_use.append(aten__int_mm) + + if is_nonzero and use_triton_template( + layout, enable_int32=True, check_max_autotune=False + ): + templates_to_use.append(mm_template) + + # Single unified call for all templates + choices.extend( + V.choices.get_template_configs(kernel_inputs, templates_to_use, name) + ) + + if use_cutlass and _use_cutlass_for_op(name): + CUTLASS3xGemmTemplate.add_cutlass_gemm_choices( + choices, layout, kernel_inputs.nodes(), fuseable=True, non_fuseable=True + ) + + node, _ = autotune_select_algorithm(name, choices, kernel_inputs.nodes(), layout) + return node + + +@register_lowering(aten.addmm, type_promotion_kind=None) +def tuned_addmm(inp, mat1, mat2, *, alpha=1, beta=1, layout=None): + """ + Lowering for autotuning aten.addmm with different backends (Aten, Triton, CUTLASS, etc.) + """ + if beta == 0 and mat1.get_device().type == "cuda": + _check_addmm_input_metadata(inp, mat1, mat2) + if alpha == 0: + _, _, _, layout, mat1, mat2 = mm_args(mat1, mat2, layout=layout) + return lowerings[aten.full]( + layout.size, + 0, + dtype=layout.dtype, + device=layout.device, + ) + if layout is not None: + result = lowerings[aten.mm](mat1, mat2, layout=layout) + else: + result = lowerings[aten.mm](mat1, mat2) + if alpha != 1: + result = lowerings[aten.mul](alpha, result) + return result + + if use_native_matmul(mat1, mat2): + if beta == 0: + _check_addmm_input_metadata(inp, mat1, mat2) + arg1 = 0 + else: + arg1 = lowerings[aten.mul](beta, inp) + + if alpha == 0: + arg2 = 0 + else: + arg2 = lowerings[aten.mul](alpha, lowerings[aten.mm](mat1, mat2)) + + return lowerings[aten.add](arg1, arg2) + + # TODO(coconutruben): integrate into MMKernelInputs when all callsites use that + m, n, k, layout, mat1, mat2, inp_expanded = mm_args(mat1, mat2, inp, layout=layout) + inp = realize_inputs(inp) + static_shape, is_nonzero = _is_static_problem(layout) + name = "addmm" + + # Create MMKernelInputs for AddMM at the top + kernel_inputs = MMKernelInputs( + [inp_expanded, mat1, mat2], scalars=dict(alpha=alpha, beta=beta) + ) + kernel_inputs_aten = MMKernelInputs( + [inp, mat1, mat2], scalars=dict(alpha=alpha, beta=beta) + ) + + choices: list[ChoiceCaller] = [] + + # below is for getting an overview logging info of inductor mms + counters["aten_mm_info"][f"aten.addmm_{m}_{n}_{k}"] += 1 + log.info( + "Tuned aten.addmm: m=%s, n=%s, k=%s, mat1_dtype=%s, mat2_dtype=%s, output_layout=%s", + m, + n, + k, + mat1.get_dtype(), + mat2.get_dtype(), + layout, + ) + if (not is_nonzero) or ( + not (inductor_config.max_autotune or inductor_config.max_autotune_gemm) + ): + choices.extend( + V.choices.get_template_configs( + kernel_inputs_aten, + [aten_addmm], + name, + ) + ) + node, _ = autotune_select_algorithm( + name, choices, kernel_inputs.nodes(), layout + ) + return node + + templates_to_use: list[ExternKernelChoice | KernelTemplate] = [] + + if use_aten_gemm_kernels(): + aten_templates: list[ExternKernelChoice | KernelTemplate] = [aten_addmm] + if ( + inp.get_stride()[0] == 0 + and len(inp.get_size()) == 2 + and inductor_config.triton.autotune_cublasLt + and not V.graph.cpp_wrapper # bias_addmm only has a Python implementation + ): + aten_templates.append(aten_bias_addmm) + + # On ROCm, ATen choices use original bias input; non-ROCm keeps unified inputs. + choices.extend( + V.choices.get_template_configs(kernel_inputs_aten, aten_templates, name) + ) + + if is_nonzero and use_triton_template(layout, check_max_autotune=False): + templates_to_use.append(mm_template) + + if use_triton_blackwell_tma_template( + mat1, mat2, output_layout=layout, add_guards=True + ): + templates_to_use.append(blackwell_ws_persistent_device_tma_mm_template) + elif use_triton_tma_template(mat1, mat2, output_layout=layout, add_guards=True): + if torch.version.hip is None: + templates_to_use.append(persistent_tma_mm_template) + else: + templates_to_use.append(persistent_mm_template) + + # Manually call get_template_configs as use 1-D bias if possible + choices.extend( + V.choices.get_template_configs( + kernel_inputs_aten, [addmm_contiguous_subgraph_template], name + ) + ) + # Single unified call for all templates + choices.extend( + V.choices.get_template_configs(kernel_inputs, templates_to_use, name) + ) + + if ( + is_nonzero + and use_cutlass_template(layout, m, n, k) + and _use_cutlass_for_op(name) + ): + CUTLASS3xGemmTemplate.add_cutlass_gemm_choices( + choices, + layout, + # reorder here because CUTLASS expects (x, w, bias) but torch + # is bias, x, w + kernel_inputs.nodes(reorder=[1, 2, 0]), + alpha=alpha, + beta=beta, + input_reorder=[2, 0, 1], + ) + + if is_nonzero and use_nv_universal_gemm_template(layout, m, n, k, mat1, mat2): + from ..codegen.nv_universal_gemm import add_nv_universal_addmm_choices + + # inp is the original (un-expanded) bias, so a 1D row vector routes to + # the row-broadcast epilogue impl. + add_nv_universal_addmm_choices( + choices, layout, kernel_inputs, inp, alpha=alpha, beta=beta + ) + + if is_nonzero and use_ck_gemm_template(layout, m, n, k): + CKGemmTemplate.add_ck_gemm_choices( + choices, + layout, + # reorder here because CK expects (x, w, bias) but torch + # is bias, x, w + kernel_inputs.nodes(reorder=[1, 2, 0]), + alpha=alpha, + beta=beta, + input_reorder=[2, 0, 1], + ) + + if use_cpp_gemm_template(layout, mat1, mat2): + CppGemmTemplate.add_choices( + choices, + layout, + kernel_inputs.nodes(), + alpha=alpha, + beta=beta, + has_bias=True, + ) + + node, _ = autotune_select_algorithm(name, choices, kernel_inputs.nodes(), layout) + return node + + +@register_lowering(aten._sparse_semi_structured_mm, type_promotion_kind=None) +def tuned_sparse_semi_structured_mm( + mat1, mat1_meta, mat2, *, out_dtype=None, layout=None +): + from torch._inductor.select_algorithm import realize_inputs + + # TODO(coconturuben): support V.choices.get_mm_configs for sparse_semi_structured_mm + mat1, mat1_meta, mat2 = realize_inputs(mat1, mat1_meta, mat2) + m1, k1 = mat1.get_size() + m2, _ = mat1_meta.get_size() + k2, n = mat2.get_size() + m = V.graph.sizevars.check_equals_and_simplify(m1, m2) + k = V.graph.sizevars.check_equals_and_simplify(2 * k1, k2) + if layout is None: + from torch._inductor.ir import FixedLayout + + layout = FixedLayout( + mat2.get_device(), + out_dtype if out_dtype else mat2.get_dtype(), + [m, n], + [n, 1], + ) + else: + if out_dtype is not None: + raise AssertionError("out_dtype is ignored if layout is specified.") + + choices = ( + [ + aten__sparse_semi_structured_mm.bind( + (mat1, mat1_meta, mat2), layout, out_dtype=out_dtype + ) + ] + if use_aten_gemm_kernels() + else [] + ) + + if ( + m * n != 0 + and use_cutlass_template(layout, m, n, k) + and _use_cutlass_for_op("sparse_semi_structured_mm") + ): + CUTLASS2xGemmTemplate.add_cutlass_gemm_choices( + choices, layout, [mat1, mat2, mat1_meta], fuseable=True, non_fuseable=True + ) + + node, _ = autotune_select_algorithm( + "sparse_semi_structured_mm", choices, (mat1, mat1_meta, mat2), layout + ) + return node + + +scaling_pairs = [ + (ScalingType.TensorWise, ScalingType.TensorWise), + (ScalingType.RowWise, ScalingType.RowWise), + (ScalingType.BlockWise1x128, ScalingType.BlockWise128x128), + (ScalingType.BlockWise1x128, ScalingType.BlockWise1x128), + (ScalingType.BlockWise128x128, ScalingType.BlockWise1x128), +] + + +epilogue_scaling_types = [ScalingType.TensorWise, ScalingType.RowWise] +main_loop_scaling_types = [ScalingType.BlockWise1x128, ScalingType.BlockWise128x128] + + +def _is_tensorwise_scaling(sz: Any) -> bool: + return (len(sz) == 0) or all( + V.graph.sizevars.statically_known_equals(d, 1) for d in sz + ) + + +def _is_rowwise_scaling(sz: Any, transpose: bool) -> bool: + idx = 0 if transpose else -1 + return V.graph.sizevars.statically_known_equals(sz[idx], 1) + + +def _is_blockwise1xTILESIZE_scaling( + sz: Any, tensor_sz: Any, tile_size: int, transpose: bool +) -> bool: + lhs = 1 if transpose else 0 + rhs = 0 if transpose else 1 + return V.graph.sizevars.statically_known_equals( + sz[lhs], tensor_sz[lhs] + ) and V.graph.sizevars.statically_known_equals( + sz[rhs], ceildiv(tensor_sz[rhs], tile_size) + ) + + +def _is_blockwise128x128_scaling(sz: Any, tensor_sz: Any) -> bool: + return V.graph.sizevars.statically_known_equals( + sz[0], ceildiv(tensor_sz[0], 128) + ) and V.graph.sizevars.statically_known_equals(sz[1], ceildiv(tensor_sz[1], 128)) + + +def is_desired_scaling( + t: Any, + scale_size: torch.Tensor, + scaling_type: ScalingType, + transpose: bool = False, +) -> bool: + match scaling_type: + case ScalingType.TensorWise: + return _is_tensorwise_scaling(scale_size) + case ScalingType.RowWise: + return _is_rowwise_scaling(scale_size, transpose) + case ScalingType.BlockWise1x128: + return _is_blockwise1xTILESIZE_scaling( + scale_size, t.get_size(), 128, transpose + ) + case ScalingType.BlockWise128x128: + return _is_blockwise128x128_scaling(scale_size, t.get_size()) + case _: + raise AssertionError(f"Unsupported scaling type {scaling_type}") + + +def get_tile_size(scale_option) -> int: + match scale_option: + case ScalingType.BlockWise128x128: + return 128 + case ScalingType.BlockWise1x128: + return 128 + case _: + raise AssertionError( + f"Unsupported scaling type {scale_option} in get_tile_size" + ) + + +def get_scaling_options( + mat_a: Any, + mat_b: Any, + scale_a_size: torch.Tensor, + scale_b_size: torch.Tensor, +) -> tuple[ScalingType, ScalingType]: + for scale_option_a, scale_option_b in scaling_pairs: + if is_desired_scaling( + mat_a, scale_a_size, scale_option_a + ) and is_desired_scaling(mat_b, scale_b_size, scale_option_b, transpose=True): + return scale_option_a, scale_option_b + + raise AssertionError( + f"Inductor Triton does not support scale_a.shape = {scale_a_size}, scale_b.shape = {scale_b_size}" + ) # verify that shapes are supported by at least one existing pairing + + +# Inductor has no template or extern choice that understands swizzled scale +# layouts for _scaled_mm_v2 yet; defer those to the eager op. add_to_fallback_set +# is False because this handler is invoked manually from the lowering below, not +# registered as the op's global fallback. +scaled_mm_v2_fallback = fallback_handler( + aten._scaled_mm_v2.default, add_to_fallback_set=False +) + + +@register_lowering(aten._scaled_mm_v2.default, type_promotion_kind=None) +def tuned_scaled_mm_v2( + mat_a, + mat_b, + scale_a: list[Any], + recipe_a: list[int], + swizzle_a: list[int], + scale_b: list[Any], + recipe_b: list[int], + swizzle_b: list[int], + bias=None, + out_dtype=None, + contraction_dim=None, + use_fast_accum=False, + layout=None, +): + """ + Performs an optimized matrix multiplication where scaling factors are + applied to the inputs per the supplied recipes, and optionally swizzled. + + This is the _scaled_mm_v2 API, which takes scale recipes (ScalingType) and + swizzle patterns alongside the scale tensors, and supports multi-level + scaling via lists. + """ + + # Inductor only has Triton/extern lowerings for single-level, fp32-scaled, + # non-swizzled _scaled_mm_v2 with the "supported" recipes (TensorWise, + # RowWise, and DeepSeek BlockWise1x128/128x128). Everything else has no + # template or extern choice here, so defer to the eager _scaled_mm_v2 op: + # - swizzled scale layouts (e.g. CUDA/Blackwell MXFP8/NVFP4) + # - the blockwise MX/NVFP4 recipes BlockWise1x32/1x16 (also how XPU + # expresses MX/NVFP4, with NO_SWIZZLE) + # - multi-level scales (two-level NVFP4) + # - any non-fp32 block scale + # The eager op is called directly so it keeps its native v2 scale_b + # convention, unlike the v1 aten__fp8_mm choice used on the supported path. + def check_supported_recipe(recipe: list[int]) -> bool: + disallowed = OrderedSet([ScalingType.BlockWise1x16, ScalingType.BlockWise1x32]) + return all(ScalingType(r) not in disallowed for r in recipe) + + is_single_level_scale = len(scale_a) == 1 and len(scale_b) == 1 + supported_recipe = check_supported_recipe(recipe_a) and check_supported_recipe( + recipe_b + ) + if ( + any(s != 0 for s in swizzle_a) + or any(s != 0 for s in swizzle_b) + or not supported_recipe + or not is_single_level_scale + or scale_a[0].dtype != torch.float32 + ): + # contraction_dim is a non-optional int[] in the schema (default []); + # this lowering defaults it to None, so coerce before the eager call. + fallback_contraction_dim = [] if contraction_dim is None else contraction_dim + return scaled_mm_v2_fallback( + mat_a, + mat_b, + scale_a, + recipe_a, + swizzle_a, + scale_b, + recipe_b, + swizzle_b, + bias, + out_dtype, + fallback_contraction_dim, + use_fast_accum, + ) + # TODO(coconutruben): integrate into MMKernelInputs when all callsites use that + m, n, k, layout, mat_a, mat_b = mm_args( + mat_a, mat_b, layout=layout, out_dtype=out_dtype + ) + # below is for getting an overview logging info of inductor mms + counters["aten_mm_info"][f"aten._scaled_mm_v2.default_{m}_{n}_{k}"] += 1 + log.info( + "Tuned aten._scaled_mm_v2.default: m=%s, n=%s, k=%s, mat1_dtype=%s, mat2_dtype=%s, output_layout=%s", + m, + n, + k, + mat_a.get_dtype(), + mat_b.get_dtype(), + layout, + ) + name = "scaled_mm" + check_supported_striding(mat_a, mat_b) + + scale_a_real, scale_b_real = realize_inputs(scale_a[0], scale_b[0]) + + input_nodes: list[Any] + + if not bias: + input_nodes = [mat_a, mat_b, scale_a_real, scale_b_real] + else: + bias_real = realize_inputs(bias) + input_nodes = [mat_a, mat_b, scale_a_real, scale_b_real, bias_real] + + # Create MMKernelInputs for Scaled MM (matrices are at indices 0, 1) + kernel_inputs = MMKernelInputs( + input_nodes, mat1_idx=0, mat2_idx=1, out_dtype=out_dtype + ) + + choices: list[ChoiceCaller] = [] + + # Collect all templates for unified call + templates_to_use: list[ExternKernelChoice | KernelTemplate] = [] + kwarg_overrides = {} + + if use_aten_gemm_kernels(): + templates_to_use.append(aten__fp8_mm) + kwarg_overrides[aten__fp8_mm.uid] = dict( + out_dtype=out_dtype, use_fast_accum=use_fast_accum + ) + + _, is_nonzero = _is_static_problem(layout) + + if ( + # We don't have triton lowerings for the MX variants yet + is_single_level_scale + and supported_recipe + and scale_a[0].dtype == torch.float32 + and is_nonzero + and use_triton_template(layout, enable_float8=True, check_max_autotune=False) + ): + overriders = dict(USE_FAST_ACCUM=use_fast_accum) + + # Note: No NVFP4 support at this point - can ignore swizzling, and take only the + # first scale types passed. + scale_option_a, scale_option_b = ( + ScalingType(recipe_a[0]), + ScalingType(recipe_b[0]), + ) + + # TODO (paulzhan): There is no template that exists for bias and TMA + # Don't run tma template currently if bias exist + if ( + use_triton_tma_template(mat_a, mat_b, output_layout=layout, add_guards=True) + and not bias + ): + overriders["SCALE_RECIPE_A"] = scale_option_a.value + overriders["SCALE_RECIPE_B"] = scale_option_b.value + + if use_triton_scaling_template( + scale_option_a, scale_option_b, epilogue_scaling_types + ): + templates_to_use.append(scaled_mm_device_tma_epilogue_scaling_template) + kwarg_overrides[scaled_mm_device_tma_epilogue_scaling_template.uid] = ( + overriders + ) + elif use_triton_scaling_template( + scale_option_a, scale_option_b, main_loop_scaling_types + ): + overriders["TILE_SIZE_A"] = get_tile_size(scale_option_a) + overriders["TILE_SIZE_B"] = get_tile_size(scale_option_b) + + templates_to_use.append(scaled_mm_device_tma_main_loop_scaling_template) + kwarg_overrides[scaled_mm_device_tma_main_loop_scaling_template.uid] = ( + overriders + ) + else: + raise AssertionError( + "Inductor Triton does not support scaling options that are present " + + "in both epilogue scaling and main loop scaling" + ) + + if ( + use_triton_blackwell_tma_template( + mat_a, mat_b, output_layout=layout, add_guards=True + ) + and not bias + ): + templates_to_use.append(blackwell_ws_persistent_device_tma_mm_template) + kwarg_overrides[blackwell_ws_persistent_device_tma_mm_template.uid] = ( + overriders + ) + + if use_triton_scaling_template( + scale_option_a, scale_option_b, epilogue_scaling_types + ): + templates_to_use.append(mm_template) + kwarg_overrides[mm_template.uid] = overriders + + # Single unified call for all templates + choices.extend( + V.choices.get_template_configs( + kernel_inputs, + templates_to_use, + name, + kwarg_overrides=kwarg_overrides, + ) + ) + + # NVGEMM get_kernels() will return empty if the scaling mode/dtype is unsupported + if is_nonzero and use_nv_universal_gemm_template(layout, m, n, k, mat_a, mat_b): + from ..codegen.nv_universal_gemm import add_nv_universal_scaled_gemm_choices + + add_nv_universal_scaled_gemm_choices( + choices, + layout, + input_nodes, + kernel_inputs=kernel_inputs, + ) + + if ( + is_nonzero + and use_cutlass_template(layout, m, n, k) + and _use_cutlass_for_op(name) + ): + CUTLASS3xGemmTemplate.add_cutlass_gemm_choices( + choices, + layout, + kernel_inputs.nodes(), # type: ignore[arg-type] + use_fast_accum=use_fast_accum, # type: ignore[arg-type] + ) + + if is_nonzero and use_ck_gemm_template(layout, m, n, k): + CKGemmTemplate.add_ck_gemm_choices(choices, layout, kernel_inputs.nodes()) + + node, _ = autotune_select_algorithm(name, choices, kernel_inputs.nodes(), layout) + return node + + +@register_lowering(aten._scaled_mm.default, type_promotion_kind=None) # type: ignore[misc] +def tuned_scaled_mm( + mat_a, + mat_b, + scale_a, + scale_b, + bias=None, + scale_result=None, + out_dtype=None, + use_fast_accum=False, + layout=None, +): + """ + Performs an optimized matrix multiplication where scaling factors are applied + to the inputs and/or output. + + Args: + mat1 (Tensor): First input matrix + mat2 (Tensor): Second input matrix + scale1 (Tensor): Scale factor applied to mat1 (supports broadcasting) + scale2 (Tensor): Scale factor applied to mat2 (supports broadcasting) + bias (Tensor, optional): Optional bias tensor to add to the result + layout: Layout hint for optimization + + Returns: + Tensor: The result of the scaled matrix multiplication + """ + # TODO(coconutruben): integrate into MMKernelInputs when all callsites use that + m, n, k, layout, mat_a, mat_b = mm_args( + mat_a, mat_b, layout=layout, out_dtype=out_dtype + ) + # below is for getting an overview logging info of inductor mms + counters["aten_mm_info"][f"aten._scaled_mm.default_{m}_{n}_{k}"] += 1 + log.info( + "Tuned aten._scaled_mm.default: m=%s, n=%s, k=%s, mat1_dtype=%s, mat2_dtype=%s, output_layout=%s", + m, + n, + k, + mat_a.get_dtype(), + mat_b.get_dtype(), + layout, + ) + name = "scaled_mm" + check_supported_striding(mat_a, mat_b) + + scale_a_real, scale_b_real = realize_inputs(scale_a, scale_b) + + input_nodes: list[Any] + + if not bias: + input_nodes = [mat_a, mat_b, scale_a_real, scale_b_real] + else: + bias_real = realize_inputs(bias) + input_nodes = [mat_a, mat_b, scale_a_real, scale_b_real, bias_real] + + # Create MMKernelInputs for Scaled MM (matrices are at indices 0, 1) + kernel_inputs = MMKernelInputs( + input_nodes, mat1_idx=0, mat2_idx=1, out_dtype=out_dtype + ) + + choices: list[ChoiceCaller] = [] + + # Collect all templates for unified call + templates_to_use: list[ExternKernelChoice | KernelTemplate] = [] + kwarg_overrides = {} + + if use_aten_gemm_kernels(): + templates_to_use.append(aten__fp8_mm) + kwarg_overrides[aten__fp8_mm.uid] = dict( + out_dtype=out_dtype, use_fast_accum=use_fast_accum + ) + + _, is_nonzero = _is_static_problem(layout) + + if ( + # We don't have triton lowerings for the MX variants yet + scale_a.dtype == torch.float32 + and is_nonzero + and use_triton_template(layout, enable_float8=True, check_max_autotune=False) + ): + overriders = dict(USE_FAST_ACCUM=use_fast_accum) + + scale_a_size, scale_b_size = scale_a_real.shape, scale_b_real.shape + + scale_option_a, scale_option_b = get_scaling_options( + mat_a, mat_b, scale_a_size, scale_b_size + ) + + # TODO (paulzhan): There is no template that exists for bias and TMA + # Don't run tma template currently if bias exist + if ( + use_triton_tma_template(mat_a, mat_b, output_layout=layout, add_guards=True) + and not bias + ): + overriders["SCALE_RECIPE_A"] = scale_option_a.value + overriders["SCALE_RECIPE_B"] = scale_option_b.value + + if use_triton_scaling_template( + scale_option_a, scale_option_b, epilogue_scaling_types + ): + templates_to_use.append(scaled_mm_device_tma_epilogue_scaling_template) + kwarg_overrides[scaled_mm_device_tma_epilogue_scaling_template.uid] = ( + overriders + ) + elif use_triton_scaling_template( + scale_option_a, scale_option_b, main_loop_scaling_types + ): + overriders["TILE_SIZE_A"] = get_tile_size(scale_option_a) + overriders["TILE_SIZE_B"] = get_tile_size(scale_option_b) + + templates_to_use.append(scaled_mm_device_tma_main_loop_scaling_template) + kwarg_overrides[scaled_mm_device_tma_main_loop_scaling_template.uid] = ( + overriders + ) + else: + raise AssertionError( + "Inductor Triton does not support scaling options that are present " + + "in both epilogue scaling and main loop scaling" + ) + + if ( + use_triton_blackwell_tma_template( + mat_a, mat_b, output_layout=layout, add_guards=True + ) + and not bias + ): + templates_to_use.append(blackwell_ws_persistent_device_tma_mm_template) + kwarg_overrides[blackwell_ws_persistent_device_tma_mm_template.uid] = ( + overriders + ) + + if use_triton_scaling_template( + scale_option_a, scale_option_b, epilogue_scaling_types + ): + templates_to_use.append(mm_template) + kwarg_overrides[mm_template.uid] = overriders + + # Single unified call for all templates + choices.extend( + V.choices.get_template_configs( + kernel_inputs, + templates_to_use, + name, + kwarg_overrides=kwarg_overrides, + ) + ) + + # NVGEMM get_kernels() will return empty if the scaling mode/dtype is unsupported + if is_nonzero and use_nv_universal_gemm_template(layout, m, n, k, mat_a, mat_b): + from ..codegen.nv_universal_gemm import add_nv_universal_scaled_gemm_choices + + add_nv_universal_scaled_gemm_choices( + choices, + layout, + input_nodes, + kernel_inputs=kernel_inputs, + ) + + # Early return for MX variants + if scale_a.dtype != torch.float32: + node, _ = autotune_select_algorithm(name, choices, input_nodes, layout) + return node + + if ( + is_nonzero + and use_cutlass_template(layout, m, n, k) + and _use_cutlass_for_op(name) + ): + CUTLASS3xGemmTemplate.add_cutlass_gemm_choices( + choices, + layout, + kernel_inputs.nodes(), # type: ignore[arg-type] + use_fast_accum=use_fast_accum, # type: ignore[arg-type] + ) + + if is_nonzero and use_ck_gemm_template(layout, m, n, k): + CKGemmTemplate.add_ck_gemm_choices(choices, layout, kernel_inputs.nodes()) + + node, _ = autotune_select_algorithm(name, choices, kernel_inputs.nodes(), layout) + return node + + +@functools.cache +def _is_sm7x_or_older_gpu(index: int | None) -> bool: + props = torch.cuda.get_device_properties(index or 0) + return props.major <= 7 + + +def dims_are_int(dims): + return all(isinstance(dim, int) for dim in dims) + + +def mm_autoheuristic( + mat1, + mat2, + m, + n, + k, + choices, + name, + input_nodes, + ops, + precondition, + top_k: int | None = None, + always_included=None, +): + m, n, k = get_size_hints(mat1, mat2, m, n, k) + if not dims_are_int([m, n, k]): + return None + mat1_stride, mat2_stride = get_size_hints_strides(mat1, mat2) + + def get_context(m, k, n, mat1, mat2, mat1_stride, mat2_stride): + context = AHContext() + context.add_feature("m", m) + context.add_feature("k", k) + context.add_feature("n", n) + context.add_feature("mat1_dtype", mat1.layout.dtype, is_categorical=True) + context.add_feature("mat2_dtype", mat2.layout.dtype, is_categorical=True) + context_add_strides(context, "mat1", mat1_stride) + context_add_strides(context, "mat2", mat2_stride) + context.add_feature( + "mat1_iscontig", mat1.layout.is_contiguous(), is_categorical=True + ) + context.add_feature( + "mat2_iscontig", mat2.layout.is_contiguous(), is_categorical=True + ) + if name == "mm": + context_add_using_tf32(context, mat1.layout.dtype) + return context + + def fallback(): + return None + + context = get_context(m, k, n, mat1, mat2, mat1_stride, mat2_stride) + autoheuristic = AutoHeuristicSelectAlgorithm( + fallback=fallback, + choices=choices, + input_nodes=input_nodes, + context=context, + name=name, + augment_context=ops, + precondition=precondition, + ) + + if top_k is not None: + # TODO: is there a cleaner way to ensure aten.mm is always included? + return autoheuristic.get_top_k_choices_caller( + top_k, always_included=always_included + ) + + return autoheuristic.get_choice_caller() + + +def get_size_hints(mat1, mat2, m, n, k): + if not isinstance(m, int) or not isinstance(k, int): + (m, k) = V.graph.sizevars.optimization_hints(mat1.get_size()) + + if not isinstance(n, int) or not isinstance(k, int): + (k, n) = V.graph.sizevars.optimization_hints(mat2.get_size()) + return m, n, k + + +def get_size_hints_strides(mat1, mat2): + mat1_stride = mat1.layout.stride + mat2_stride = mat2.layout.stride + strides = [mat1_stride, mat2_stride] + strides_hints = [] + for stride in strides: + if not isinstance(stride, int): + stride = V.graph.sizevars.optimization_hints(stride) + strides_hints.append(stride) + return strides_hints[0], strides_hints[1] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/mm_common.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/mm_common.py new file mode 100644 index 0000000000000000000000000000000000000000..b5437532b6845279f83dcfacba32c397f99d3542 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/mm_common.py @@ -0,0 +1,287 @@ +# mypy: allow-untyped-defs +import logging +from collections.abc import Sequence +from functools import partial +from pathlib import Path +from typing import Any + +import torch +from torch._inductor.select_algorithm import realize_inputs, SymbolicGridFn +from torch._inductor.utils import get_current_backend, sympy_product +from torch._inductor.virtualized import V +from torch.fx.experimental.symbolic_shapes import has_free_unbacked_symbols + +from .. import config +from ..codegen.wrapper import PythonWrapperCodegen +from ..ir import _IntLike, Layout, TensorBox +from ..utils import load_template, triton_type + + +log = logging.getLogger(__name__) + + +@SymbolicGridFn +def mm_grid(m, n, meta, *, cdiv): + """ + The CUDA grid size for matmul triton templates. + """ + return (cdiv(m, meta["BLOCK_M"]) * cdiv(n, meta["BLOCK_N"]), 1, 1) + + +@SymbolicGridFn +def persistent_mm_grid(M: int, N: int, meta: dict[str, Any], *, cdiv, min): + """Defines the grid for persistent kernels.""" + return ( + min(meta["NUM_SMS"], cdiv(M, meta["BLOCK_M"]) * cdiv(N, meta["BLOCK_N"])), + 1, + 1, + ) + + +@SymbolicGridFn +def persistent_grouped_mm_grid(*args): + meta = args[-1] + return (meta["NUM_SMS"], 1, 1) + + +def acc_type(dtype): + if dtype in (torch.float16, torch.bfloat16): + return "tl.float32" + if dtype.is_floating_point and dtype.itemsize == 1: # fp8 dtypes + return "tl.float32" + return triton_type(dtype) + + +def mm_args( + mat1, + mat2, + *others, + layout=None, + out_dtype=None, + use_4x2_dim=False, + mat2_transposed=False, +): + """ + Common arg processing for mm,bmm,addmm,etc + """ + mat1, mat2 = realize_inputs(mat1, mat2) + *b1, m, k1 = mat1.get_size() + if mat2_transposed: + *b2, n, k2 = mat2.get_size() + else: + *b2, k2, n = mat2.get_size() + b = [V.graph.sizevars.check_equals_and_simplify(a, b) for a, b in zip(b1, b2)] + if use_4x2_dim: + k2 = k2 * 2 + k = V.graph.sizevars.check_equals_and_simplify(k1, k2) + if layout is None: + from torch._inductor.ir import FixedLayout + + if out_dtype is None: + out_dtype = mat1.get_dtype() + + layout = FixedLayout( + mat1.get_device(), + out_dtype, + [*b, m, n], + ) + else: + if out_dtype is not None: + raise AssertionError("out_dtype is ignored if layout is specified.") + from ..lowering import expand + + others = [realize_inputs(expand(x, layout.size)) for x in others] + + return [m, n, k, layout, mat1, mat2, *others] + + +def addmm_epilogue(dtype, alpha, beta): + def epilogue(acc, bias): + if alpha != 1: + acc = V.ops.mul(acc, V.ops.constant(alpha, dtype)) + if beta != 1: + bias = V.ops.mul(bias, V.ops.constant(beta, dtype)) + return V.ops.add(acc, bias) + + return epilogue + + +def scale_mm_epilogue(): + """ + Create an epilogue function that applies scaling to matrix multiplication result + using the given scale factors. + + Args: + dtype: The data type of the output + scale_a: Scale factor for matrix A + scale_b: Scale factor for matrix B + + Returns: + Epilogue function that takes the accumulator and applies scaling + """ + + def epilogue(acc, inv_a_scale, inv_b_scale, bias=None): + # The epilogue function receives the accumulator (result of mat1 @ mat2) + # and applies the scaling factors + # In the original scaled_mm, we use inverse scales, so we multiply by them + mul_scales = V.ops.mul(inv_a_scale, inv_b_scale) + mul_acc = V.ops.mul(acc, mul_scales) + if bias is not None: + return V.ops.add(mul_acc, bias) + else: + return mul_acc + + return epilogue + + +def use_native_matmul(mat1, mat2): + if not config.triton.native_matmul: + return False + + # If tma matmul is on, don't do native matmul + if ( + config.triton.enable_persistent_tma_matmul + and torch.utils._triton.has_triton_tma_device() + ): + raise AssertionError("native matmul doesn't support tma codegen yet") + + # Currently only enable native matmul for default indexing + # TODO : support block ptr + if config.triton.use_block_ptr: + raise AssertionError("native matmul doesn't support block_ptr codegen yet") + + # Currently only enable native matmul for triton on GPU. + device_type = mat1.get_device().type + if not ( + device_type in ("cuda", "xpu") and get_current_backend(device_type) == "triton" + ): + return False + + # Currently, tl.dot only supports following dtypes + triton_supported_dtype = [ + torch.int8, + torch.uint8, + torch.float16, + torch.bfloat16, + torch.float32, + ] + if mat1.dtype not in triton_supported_dtype: + return False + if mat2.dtype not in triton_supported_dtype: + return False + + # (..., M, K) @ (..., K, N) + m, k, n = mat1.get_size()[-2], mat1.get_size()[-1], mat2.get_size()[-1] + + # If the shape has unbacked symbols, don't do native matmul. + # This is related to the behavior of statically_known_multiple_of on unbacked symints. + # Since statically_known_multiple_of just returns False for unbacked symbols + # due to the expensive cost, codegen fails when there is a unbacked symbol. + # In particular, it fails at _split_iteration_ranges in codegen/simd.py. + # See this : https://github.com/pytorch/pytorch/pull/131649 + if any(map(has_free_unbacked_symbols, [m, k, n])): + return False + + # Consider the shape (m,k,n) > 1 + # TODO : support when size = 1 + if ( + V.graph.sizevars.statically_known_leq(m, 1) + or V.graph.sizevars.statically_known_leq(k, 1) + or V.graph.sizevars.statically_known_leq(n, 1) + ): + return False + + return True + + +def _use_small_mm_pointwise(m, k, n, layout) -> bool: + """Check if mm should be lowered to pointwise ops for small K and N. + + For very small inner dimensions (K < 5 and N < 5) with M >= 64, + cuBLAS launch overhead dominates and a fused pointwise kernel is + faster (1.2-4.8x on H200). M >= 64 excludes tiny matrices where + pointwise kernel launch overhead negates the benefit. K,N < 5 + avoids shapes where Triton codegen quality is unstable (K=5 regresses + at large M due to reduction-dimension alignment). Disabled under + max_autotune to preserve template selection. + See https://github.com/pytorch/pytorch/issues/186348 + """ + if config.max_autotune or config.max_autotune_gemm: + return False + if layout.device.type in ("cpu", "mps"): + return False + skt = V.graph.sizevars.statically_known_true + return skt(m >= 64) and skt(k < 5) and skt(n < 5) + + +def _is_static_problem(layout: Layout) -> tuple[bool, bool]: + """ + Check if input tensors and output layout have static shapes and non-zero sizes. + + Args: + layout: Output layout object with a 'size' attribute. + + Returns: + Tuple[bool, bool]: (is_static, is_nonzero) + is_static: True if all shapes are statically known + is_nonzero: True if all dimensions are non-zero + """ + static_shape = True + static_size = PythonWrapperCodegen.statically_known_list_of_ints_or_none( + layout.size + ) + if static_size is None: + nonzero = True + for s in layout.size: + sz = PythonWrapperCodegen.statically_known_int_or_none(s) + if sz is not None and sz == 0: + nonzero = False + break + return False, nonzero + numel = 1 + for dim in static_size: + numel *= dim + nonzero = numel > 0 + return static_shape, nonzero + + +def check_supported_striding(mat_a: TensorBox, mat_b: TensorBox) -> None: + def is_row_major(stride: Sequence[_IntLike]) -> bool: + return stride[-1] == 1 + + def is_col_major(stride: Sequence[_IntLike]) -> bool: + return stride[-2] == 1 + + def has_zero_dim(size: Sequence[_IntLike]) -> bool: + return bool(size[0] == 0 or size[1] == 0) + + # Check mat_a (self) stride requirements + torch._check( + is_row_major(mat_a.get_stride()) or has_zero_dim(mat_a.get_size()), + lambda: f"mat_a must be row_major, got stride {mat_a.get_stride()}", + ) + + # Check mat_b stride requirements + torch._check( + is_col_major(mat_b.get_stride()) or has_zero_dim(mat_b.get_size()), + lambda: f"mat_b must be col_major, got stride {mat_b.get_stride()}", + ) + + +def is_batch_stride_largest_or_zero(mat1, mat2, layout) -> bool: + """ + Checking if the batch stride is the largest in the stride. + """ + sizes = [mat1.get_size(), mat2.get_size(), layout.size] + strides = [mat1.get_stride(), mat2.get_stride(), layout.stride] + for size, stride in zip(sizes, strides): + if not (len(size) == len(stride) == 3): + raise AssertionError("Expect 3D tensors") + if stride[0] != 0 and stride[0] != sympy_product(size[1:]): + return False + + return True + + +_KERNEL_TEMPLATE_DIR = Path(__file__).parent / "templates" +load_kernel_template = partial(load_template, template_dir=_KERNEL_TEMPLATE_DIR) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/mm_grouped.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/mm_grouped.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd8802f5a52d68199e8c2280e7d58a496a1c4c6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/mm_grouped.py @@ -0,0 +1,581 @@ +# mypy: allow-untyped-defs +import logging +from dataclasses import asdict, dataclass +from typing import Any + +import torch +from torch._dynamo.utils import counters +from torch._inductor.codegen.cutedsl.cutedsl_template import CuteDSLTemplate +from torch._inductor.heuristics.template.cutedsl import get_groupgemm_configs +from torch._inductor.runtime.triton_compat import tl +from torch._inductor.virtualized import V +from torch.utils._triton import has_triton + +from ..ir import ChoiceCaller, Layout, TensorBox +from ..lowering import register_lowering +from ..select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, + realize_inputs, + TritonTemplate, +) +from ..utils import ( + get_gpu_shared_memory, + get_num_sms, + has_free_symbols, + use_aten_gemm_kernels, + use_blackwell_cutedsl_grouped_mm, + use_nv_universal_gemm_template, + use_triton_template, +) +from .mm_common import ( + _is_static_problem, + check_supported_striding, + load_kernel_template, + persistent_grouped_mm_grid, +) + + +log = logging.getLogger(__name__) +aten = torch.ops.aten + + +@dataclass +class Config: + kwargs: dict[str, int] + num_stages: int + num_warps: int + + +_NV_CONFIGS = [ + Config( + { + "BLOCK_M": block_size_m, + "BLOCK_N": block_size_n, + "BLOCK_K": block_size_k, + "NUM_CONSUMER_GROUPS": 1, + }, + num_stages=num_stages, + num_warps=num_warps, + ) + for block_size_m in [16, 32, 64, 128] + for block_size_n in [64, 128, 256] + for block_size_k in [64, 128, 256] + for num_stages in [3, 4] + for num_warps in [4, 8] +] + + +def grouped_mm_configs(): + return _NV_CONFIGS + + +def early_config_prune(g, m, dtsize, configs, named_args): + pruned_configs = [] + for config in configs: + kw = config.kwargs + BLOCK_M, BLOCK_N, BLOCK_K, num_stages, num_warps, num_consumer_groups = ( + kw["BLOCK_M"], + kw["BLOCK_N"], + kw["BLOCK_K"], + config.num_stages, + config.num_warps, + getattr(config, "num_consumer_groups", 0), + ) + + # 1. Prune NV configs depending on g and m. + if not has_free_symbols((g, m)): + a_is_2d, b_is_2d = named_args["A_IS_2D"], named_args["B_IS_2D"] + m_avg = m // g if a_is_2d and not b_is_2d else m + if m_avg <= 16: + if BLOCK_M > 32: + continue + elif m_avg <= 32: + if BLOCK_M > 64: + continue + elif m_avg <= 64: + if BLOCK_M <= 16: + continue + else: + if BLOCK_M <= 32: + continue + + # 2. make sure we have enough smem + max_shared_memory = get_gpu_shared_memory() + + required_shared_memory = (BLOCK_M + BLOCK_N) * BLOCK_K * num_stages * dtsize + if required_shared_memory > max_shared_memory: + continue + + use_warp_specialization = num_consumer_groups >= 1 + + # 3. make sure we can partition for ws + if use_warp_specialization: + if num_warps != 4: + continue + + # "tritongpu-warp-spec-data-partition" + m_slice = BLOCK_M // num_consumer_groups + n_slice = BLOCK_N // num_consumer_groups + if m_slice < 64 and n_slice < 256: + continue + + pruned_configs.append(config) + + return pruned_configs + + +triton_grouped_mm_template = TritonTemplate( + name="grouped_mm", + grid=persistent_grouped_mm_grid, + source=load_kernel_template("triton_mm_grouped"), +) + +triton_scaled_grouped_mm_template = TritonTemplate( + name="scaled_grouped_mm", + grid=persistent_grouped_mm_grid, + source=load_kernel_template("triton_mm_grouped"), +) + +cutedsl_grouped_mm_template = CuteDSLTemplate( + name="grouped_gemm_cutedsl", + source=load_kernel_template("cutedsl_mm_grouped"), +) + + +def has_grouped_mm_triton_support() -> bool: + if not torch.cuda.is_available(): + return False + if torch.version.hip: + # The grouped GEMM Triton template is supported on ROCm too. ATen + # remains a separate autotune choice when fallback kernels are enabled. + return True + return torch.cuda.get_device_capability() >= (9, 0) + + +def _rocm_gcn_arch() -> str: + return torch.cuda.get_device_properties( + torch.cuda.current_device() + ).gcnArchName.split(":", 1)[0] + + +def has_rocm_fp8_hardware_support() -> bool: + if not torch.version.hip: + return False + + # Keep this in sync with torch.testing._internal.common_cuda.PLATFORM_SUPPORTS_FP8; + # this is the production-side equivalent used to gate Triton FP8 lowering. + arch = _rocm_gcn_arch() + rocm_version = tuple(int(v) for v in torch.version.hip.split(".")[:2]) + if arch.startswith("gfx94"): + return True + if arch.startswith("gfx120") and rocm_version >= (6, 3): + return True + if arch.startswith("gfx95") and rocm_version >= (6, 5): + return True + return False + + +def has_scaled_grouped_mm_triton_support(mat_a: TensorBox, mat_b: TensorBox) -> bool: + if not torch.version.hip: + return True + if not has_rocm_fp8_hardware_support(): + return False + + arch = _rocm_gcn_arch() + # Match ATen's ROCm rowwise scaled grouped GEMM contract: gfx94 uses the + # FNUZ FP8 encoding, while newer FP8-capable arches use OCP FP8. + expected_dtype = ( + torch.float8_e4m3fnuz if arch.startswith("gfx94") else torch.float8_e4m3fn + ) + return mat_a.get_dtype() == expected_dtype and mat_b.get_dtype() == expected_dtype + + +def grouped_mm_args( + mat1: TensorBox, + mat2: TensorBox, + offs: TensorBox | None, + layout=None, + out_dtype=None, +): + mat1, mat2 = realize_inputs(mat1, mat2) + if offs is not None: + realize_inputs(offs) + mat1_size = mat1.get_size() + mat2_size = mat2.get_size() + + m1dim, m2dim = len(mat1_size), len(mat2_size) + + if m1dim not in (2, 3): + raise AssertionError(f"Expected 2D or 3D mat1, got {m1dim}D") + if m2dim not in (2, 3): + raise AssertionError(f"Expected 2D or 3D mat2, got {m2dim}D") + + if layout is None: + from torch._inductor.ir import FixedLayout + + if out_dtype is None: + out_dtype = mat1.get_dtype() + alignment = 16 // out_dtype.itemsize + + if m1dim == 2: + if m2dim == 2: + if offs is None: + raise AssertionError("offs must be provided for 2D x 2D grouped mm") + out_size = [offs.get_size()[0], mat1_size[0], mat2_size[1]] + else: + out_size = [mat1_size[0], mat2_size[-1]] + else: + if m2dim == 2: + out_size = [mat1_size[1], mat2_size[1]] + else: + out_size = [mat1_size[0], mat1_size[1], mat2_size[-1]] + # Match the ATen extern output layout: CUDA pads grouped GEMM outputs for + # TMA alignment, while ROCm's ATen path returns contiguous tensors. + # TODO: Revisit whether 16-byte alignment would be beneficial for gfx1250. + if torch.version.hip: + if len(out_size) == 2: + out_stride = [out_size[1], 1] + else: + out_stride = [out_size[1] * out_size[2], out_size[2], 1] + else: + size_padded = (out_size[-1] + alignment - 1) // alignment * alignment + if len(out_size) == 2: + out_stride = [size_padded, 1] + else: + out_stride = [out_size[1] * size_padded, size_padded, 1] + + layout = FixedLayout( + mat1.get_device(), + out_dtype, + out_size, + out_stride, + ) + else: + if out_dtype is not None: + raise AssertionError("out_dtype is ignored if layout is specified.") + + return (mat1_size, mat2_size, layout, mat1, mat2, offs) + + +aten__grouped_mm = ExternKernelChoice( + torch._grouped_mm, + "at::_grouped_mm", + op_overload=aten._grouped_mm.default, + has_out_variant=False, +) + + +aten__scaled_grouped_mm = ExternKernelChoice( + torch._scaled_grouped_mm, + "at::_scaled_grouped_mm", + op_overload=aten._scaled_grouped_mm.default, + has_out_variant=False, +) + + +def can_use_triton_kernel( + mat_a: TensorBox, + mat_b: TensorBox, + offs: TensorBox | None, + bias: TensorBox | None, + scale_result: TensorBox | None, +) -> bool: + if not has_grouped_mm_triton_support(): + return False + if not has_triton(): + return False + + # The _grouped_mm()/_scaled_grouped_mm() operator do not support + # bias nor scale_result yet. + if bias is not None: + return False + if scale_result is not None: + return False + + if len(mat_a.get_size()) == 2 or len(mat_b.get_size()) == 2: + return offs is not None + else: + return offs is None + + +def create_offsets(offs_box, m1_is_2d, m2_is_2d, m, n, k, alignment): + if m1_is_2d: + if m2_is_2d: + end = k + else: + end = m + else: + if m2_is_2d: + end = n + else: + return None + + end_hint = V.graph.sizevars.optimization_hint(end) + noffs_hint = V.graph.sizevars.optimization_hint(offs_box.get_size()[0]) + offs = torch.arange(1, noffs_hint + 1, dtype=torch.float32) * ( + end_hint / noffs_hint + ) + offs[:-1] = (offs[:-1] / alignment).round() * alignment + offs[-1] = end_hint + return offs.to(dtype=offs_box.get_dtype(), device=offs_box.get_device()) + + +def _tuned_grouped_mm_common( + operator_name: str, + algorithm_name: str, + extern_kernel_choice: ExternKernelChoice, + kernel_template: TritonTemplate, + mat_a: TensorBox, + mat_b: TensorBox, + scale_a: TensorBox | None = None, + scale_b: TensorBox | None = None, + offs: TensorBox | None = None, + bias: TensorBox | None = None, + scale_result: TensorBox | None = None, + out_dtype: torch.dtype | None = None, + use_fast_accum: bool | None = None, + layout: Layout | None = None, +) -> TensorBox: + if (scale_a is None) != (scale_b is None): + raise AssertionError( + "scale_a and scale_b must both be None or both be provided" + ) + if scale_result is not None and scale_a is None: + raise AssertionError("scale_result requires scale_a and scale_b") + + m1_size, m2_size, layout, mat_a, mat_b, offs = grouped_mm_args( + mat_a, mat_b, offs, layout=layout, out_dtype=out_dtype + ) + counters["aten_mm_info"][operator_name] += 1 + log_message = f"Tuned {operator_name}: mat1_shape=%s, mat2_shape=%s, mat1_dtype=%s, mat2_dtype=%s, output_layout=%s" + log.info( + log_message, + m1_size, + m2_size, + mat_a.get_dtype(), + mat_b.get_dtype(), + layout, + ) + + if scale_a is not None and scale_b is not None: + check_supported_striding(mat_a, mat_b) + + # workaround for Inductor not supporting optional tensor input arguments + input_nodes: list[Any] = [mat_a, mat_b] + if scale_a is not None: + input_nodes.append(realize_inputs(scale_a)) + if scale_b is not None: + input_nodes.append(realize_inputs(scale_b)) + if offs is not None: + input_nodes.append(realize_inputs(offs)) + + if use_fast_accum is None: + aten_choice = extern_kernel_choice.bind( + input_nodes, + layout, + out_dtype=out_dtype, + ) + else: + aten_choice = extern_kernel_choice.bind( + input_nodes, + layout, + out_dtype=out_dtype, + use_fast_accum=use_fast_accum, + ) + if use_fast_accum is None: + use_fast_accum = False + + choices: list[ChoiceCaller] = [] + if use_aten_gemm_kernels(): + choices.append(aten_choice) + + _, is_nonzero = _is_static_problem(layout) + + # Checking only for the equality of corresponding dims of + # multiplicands here, relying on meta function checks for + # everything else. + if len(m1_size) == 2: + if len(m2_size) == 2: + m, k1 = m1_size + k2, n = m2_size + + g = offs.get_size()[0] + k = V.graph.sizevars.check_equals(k1, k2) + a_is_2d, b_is_2d = True, True + else: + g1 = offs.layout.size[0] + m, k1 = m1_size + g2, k2, n = m2_size + g = V.graph.sizevars.check_equals_and_simplify(g1, g2) + k = V.graph.sizevars.check_equals(k1, k2) + a_is_2d, b_is_2d = True, False + else: + if len(m2_size) == 2: + g1 = offs.layout.size[0] + g2, m, k1 = m1_size + k2, n = m2_size + g = V.graph.sizevars.check_equals_and_simplify(g1, g2) + k = V.graph.sizevars.check_equals(k1, k2) + a_is_2d, b_is_2d = False, True + else: + g1, m, k1 = m1_size + g2, k2, n = m2_size + g = V.graph.sizevars.check_equals_and_simplify(g1, g2) + k = V.graph.sizevars.check_equals(k1, k2) + a_is_2d, b_is_2d = False, False + + scaled = scale_a is not None + + if ( + is_nonzero + and use_triton_template(layout) + and can_use_triton_kernel(mat_a, mat_b, offs, bias, scale_result) + and (not scaled or has_scaled_grouped_mm_triton_support(mat_a, mat_b)) + ): + a_is_k_major = mat_a.get_stride()[-1] == 1 + b_is_k_major = mat_b.get_stride()[-2] == 1 + + triton_has_make_tensor_descriptor = hasattr(tl, "make_tensor_descriptor") + triton_has_experimental_make_tensor_descriptor = hasattr( + tl, "_experimental_make_tensor_descriptor" + ) + use_tma_load = ( + triton_has_make_tensor_descriptor + or triton_has_experimental_make_tensor_descriptor + ) + kwargs = { + "SCALED": scaled, + "A_IS_2D": a_is_2d, + "B_IS_2D": b_is_2d, + "A_IS_K_MAJOR": a_is_k_major, + "B_IS_K_MAJOR": b_is_k_major, + "USE_FAST_ACCUM": use_fast_accum, + "NUM_SMS": get_num_sms(), + "USE_TMA_LOAD": use_tma_load, + "USE_EXPERIMENTAL_MAKE_TENSOR_DESCRIPTOR": triton_has_experimental_make_tensor_descriptor, + } + + for config in early_config_prune( + g, m, mat_a.dtype.itemsize, grouped_mm_configs(), kwargs + ): + kernel_template.maybe_append_choice( + choices, + input_nodes=input_nodes, + layout=layout, + num_stages=config.num_stages, + num_warps=config.num_warps, + **kwargs, + **config.kwargs, + ) + + if use_blackwell_cutedsl_grouped_mm( + mat_a, mat_b, layout, a_is_2d, b_is_2d, offs, bias, scale_result + ): + for config in get_groupgemm_configs(): + kwargs = dict( + ACC_DTYPE="cutlass.Float32", + ) + + cutedsl_grouped_mm_template.maybe_append_choice( + choices, + input_nodes=input_nodes, + layout=layout, + **kwargs, + **asdict(config), + ) + + if ( + is_nonzero + and a_is_2d + and not b_is_2d + and offs is not None + and use_nv_universal_gemm_template(layout, m, n, k, mat_a, mat_b, offs, g) + ): + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm import ( + add_nv_universal_grouped_gemm_choices, + ) + + add_nv_universal_grouped_gemm_choices( + choices, + layout, + input_nodes, + accumulator_type=torch.float32, + ) + + input_gen_fns = {} + if offs is not None: + input_offs_idx = 2 if scale_a is None else 4 + alignment = 16 // mat_a.dtype.itemsize + input_gen_fns[input_offs_idx] = lambda x: create_offsets( + x, a_is_2d, b_is_2d, m, n, k, alignment + ) + node, _ = autotune_select_algorithm( + algorithm_name, choices, input_nodes, layout, input_gen_fns=input_gen_fns + ) + return node + + +@register_lowering(aten._grouped_mm.default, type_promotion_kind=None) +def tuned_grouped_mm( + mat_a: TensorBox, + mat_b: TensorBox, + offs: TensorBox | None = None, + bias: TensorBox | None = None, + out_dtype: torch.dtype | None = None, + layout: Layout | None = None, +) -> TensorBox: + """Auto-tuning for _grouped_mm() operator.""" + + return _tuned_grouped_mm_common( + "aten._grouped_mm.default", + "grouped_mm", + aten__grouped_mm, + triton_grouped_mm_template, + mat_a, + mat_b, + None, + None, + offs, + bias, + None, + out_dtype, + None, + layout, + ) + + +@register_lowering(aten._scaled_grouped_mm.default, type_promotion_kind=None) +def tuned_scaled_grouped_mm( + mat_a: TensorBox, + mat_b: TensorBox, + scale_a: TensorBox, + scale_b: TensorBox, + offs: TensorBox | None = None, + bias: TensorBox | None = None, + scale_result: TensorBox | None = None, + out_dtype: torch.dtype | None = None, + use_fast_accum: bool = False, + layout: Layout | None = None, +) -> TensorBox: + """Auto-tuning for _scaled_grouped_mm() operator.""" + + # matching _scaled_grouped_mm_cuda Blas.cpp implementation + out_dtype = out_dtype or torch.bfloat16 + + return _tuned_grouped_mm_common( + "aten._scaled_grouped_mm.default", + "scaled_grouped_mm", + aten__scaled_grouped_mm, + triton_scaled_grouped_mm_template, + mat_a, + mat_b, + scale_a, + scale_b, + offs, + bias, + scale_result, + out_dtype, + use_fast_accum, + layout, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/mm_plus_mm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/mm_plus_mm.py new file mode 100644 index 0000000000000000000000000000000000000000..1c777ddc305de16f9386fb3c1fb6803f343b786c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/mm_plus_mm.py @@ -0,0 +1,179 @@ +# mypy: allow-untyped-defs + +import logging +from typing import TYPE_CHECKING + +import torch + +from .. import config as inductor_config +from ..kernel_inputs import MMKernelInputs +from ..lowering import lowerings +from ..select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, + TritonTemplate, +) +from ..utils import use_aten_gemm_kernels, use_triton_template +from ..virtualized import V +from .mm_common import mm_args, mm_grid + + +if TYPE_CHECKING: + from torch._inductor.ir import ChoiceCaller + from torch._inductor.select_algorithm import KernelTemplate + +log = logging.getLogger(__name__) + +aten = torch.ops.aten + +aten_mm_plus_mm = ExternKernelChoice( + torch.ops.inductor._mm_plus_mm, "torch::inductor::_mm_plus_mm" +) + +mm_plus_mm_template = TritonTemplate( + name="mm_plus_mm", + grid=mm_grid, + debug=False, + source=r""" +{{def_kernel("A", "B", "C", "D")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K1 = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + # K2 = {{size("C", 1)}} + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + stride_cm = {{stride("C", 0)}} + stride_ck = {{stride("C", 1)}} + stride_dk = {{stride("D", 0)}} + stride_dn = {{stride("D", 1)}} + + # based on triton.ops.matmul + pid = tl.program_id(0).to(INDEX_DTYPE) + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + tl.assume(pid_m >= 0) + tl.assume(pid_n >= 0) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + + if (((stride_am == 1 and stride_ak == M) or (stride_am == K1 and stride_ak == 1)) + and ((stride_cm == 1 and stride_ck == M) or (stride_cm == K1 and stride_ck == 1))): + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + else: + ram = rm % M + + if (((stride_bk == 1 and stride_bn == K1) or (stride_bk == N and stride_bn == 1)) + and ((stride_dk == 1 and stride_dn == K1) or (stride_dk == N and stride_dn == 1))): + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + else: + rbn = rn % N + + rk = tl.arange(0, BLOCK_K) + A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak) + B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn) + C = C + (ram[:, None] * stride_cm + rk[None, :] * stride_ck) + D = D + (rk[:, None] * stride_dk + rbn[None, :] * stride_dn) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + for k1 in range(K1, 0, -BLOCK_K): + # First matmul with A @ B + if EVEN_K: + a = tl.load(A) + b = tl.load(B) + else: + a = tl.load(A, mask=rk[None, :] < k1, other=0.) + b = tl.load(B, mask=rk[:, None] < k1, other=0.) + acc += tl.dot(a, b, allow_tf32=ALLOW_TF32) + A += BLOCK_K * stride_ak + B += BLOCK_K * stride_bk + + for k2 in range(K1, 0, -BLOCK_K): + + # Second matmul with C @ D + if EVEN_K: + c = tl.load(C) + d = tl.load(D) + else: + c = tl.load(C, mask=rk[None, :] < k2, other=0.) + d = tl.load(D, mask=rk[:, None] < k2, other=0.) + acc += tl.dot(c, d, allow_tf32=ALLOW_TF32) + C += BLOCK_K * stride_ck + D += BLOCK_K * stride_dk + + + idx_m = rm[:, None] + idx_n = rn[None, :] + mask = (idx_m < M) & (idx_n < N) + + # inductor generates a suffix + {{store_output(("idx_m", "idx_n"), "acc", "mask", val_shape=("BLOCK_M", "BLOCK_N"))}} +""", + cache_codegen_enabled_for_template=True, +) + + +def tuned_mm_plus_mm(mat1, mat2, mat3, mat4, *, layout=None): + """ + Computes mm(mat1, mat2) + mm(mat3, mat4) + """ + # TODO(coconutruben): integrate into MMKernelInputs when all callsites use that + m1, n1, k1, layout1, mat1, mat2 = mm_args(mat1, mat2, layout=layout) + m2, n2, _, layout2, mat3, mat4 = mm_args(mat3, mat4, layout=layout) + + # Optimization is optional, because we can always just not do the fusion + if ( + m1 * n1 == 0 + or m2 * n2 == 0 + or not V.graph.sizevars.statically_known_list_equals( + mat1.get_size(), mat3.get_size() + ) + or not V.graph.sizevars.statically_known_list_equals( + mat2.get_size(), mat4.get_size() + ) + or inductor_config.triton.native_matmul + ): + # TODO(jansel): support different K values when this is fixed: + # https://github.com/triton-lang/triton/issues/967 + return lowerings[aten.add]( + lowerings[aten.mm](mat1, mat2), lowerings[aten.mm](mat3, mat4) + ) + + # Create MMKernelInputs for MM Plus MM (matrices are at indices 0, 1 for first pair) + # Note: This is a special case with 4 matrices, but we use the first pair for M, N, K extraction + kernel_inputs = MMKernelInputs([mat1, mat2, mat3, mat4], mat1_idx=0, mat2_idx=1) + + if layout1 != layout2: + raise AssertionError("layout1 and layout2 must be equal") + # options to tune from + choices: list[ChoiceCaller] = [] + + # Collect all templates for unified call + templates_to_use: list[ExternKernelChoice | KernelTemplate] = [] + if use_aten_gemm_kernels(): + templates_to_use.append(aten_mm_plus_mm) + + if use_triton_template(layout1, check_max_autotune=False): + templates_to_use.append(mm_plus_mm_template) + + # Single unified call for all templates + choices.extend( + V.choices.get_template_configs(kernel_inputs, templates_to_use, "mm_plus_mm") + ) + + node, _ = autotune_select_algorithm( + "mm_plus_mm", choices, kernel_inputs.nodes(), layout1 + ) + return node diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/cutedsl_mm_grouped.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/cutedsl_mm_grouped.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..7dfe0fdab1a2f29d8362bd625a5a0f2426a1a6de --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/cutedsl_mm_grouped.py.jinja @@ -0,0 +1,498 @@ +import functools + +from torch._inductor.ir import get_stride_order +from torch._inductor.runtime.cutedsl_cache import disk_cache_get, disk_cache_set +from torch._inductor.runtime.runtime_utils import ceildiv +from cutlass.utils import TensorMapUpdateMode +{{gen_defines()}} +# ---- Import GroupedGemm implementation, copied from Cutlass during build. ---- +# Source: examples/python/CuTeDSL/cute/blackwell/kernel/grouped_gemm/grouped_gemm.py +from torch._inductor.kernel.vendored_templates.cutedsl.kernels.cutedsl_grouped_gemm import ( + GroupedGemmKernel, +) + +# Caching is split into two levels: +# +# 1. _prep_fn_cache — caches the compiled executor for +# build_group_ptrs_from_bases(). Depends only on tensor shapes, strides, +# and dtypes of A/B/C, so it can be reused across different group +# partitionings (`offs`). +# +# 2. _gemm_fn_cache — caches the compiled Grouped GEMM executor. Its key +# extends the prep key with (max_active_clusters, total_num_clusters) +# because different `offs` tensors change per-group problem sizes and +# thus total_num_clusters, which alters the grid shape and persistent +# scheduler configuration. Kernels compiled for one grid cannot be +# safely reused for another. +# +# Compile-time constexprs (TILE_M, TILE_N, CLUSTER_M/N, USE_2_CTA, etc.) +# are baked into each generated file, so they appear only in +# _KERNEL_CONFIG_KEY (used by the disk cache) and not in the per-call +# runtime keys. +# +# The @lru_cache on get_hardware_info() avoids redundant MLIR +# recompilation overhead from hw.get_max_active_clusters(), which depends +# only on GPU type. + +_prep_fn_cache = {} +_gemm_fn_cache = {} + +_KERNEL_CONFIG_KEY = ( + TILE_M, TILE_N, CLUSTER_M, CLUSTER_N, + int(USE_2_CTA), str(ACC_DTYPE), str(TENSORMAP_UPDATE_MODE), +) + + +def _to_cute_tensor(t, assumed_align=16): + return from_dlpack(t.detach(), assumed_align=assumed_align, enable_tvm_ffi=True).mark_layout_dynamic() + +_TORCH_TO_CUTLASS_DTYPE = { + torch.float16: cutlass.Float16, + torch.bfloat16: cutlass.BFloat16, + torch.float32: cutlass.Float32, + torch.float64: cutlass.Float64, + torch.int8: cutlass.Int8, + torch.int32: cutlass.Int32, + torch.int64: cutlass.Int64, +} + +def _to_fake_cute_tensor(t, assumed_align=16): + dyn_shape = tuple(map(int, t.shape)) + stride_order = tuple(get_stride_order(t.stride())) + return cute.runtime.make_fake_compact_tensor( + _TORCH_TO_CUTLASS_DTYPE[t.dtype], dyn_shape, + stride_order=stride_order, assumed_align=assumed_align, + ) + + +@functools.lru_cache +def get_hardware_info(): + hw = cutlass.utils.HardwareInfo() + sm_count = hw.get_max_active_clusters(1) + max_active_clusters = hw.get_max_active_clusters(CLUSTER_M * CLUSTER_N) + + return (sm_count, max_active_clusters) + + +def get_prep_cache_key(input_a, input_b, output): + return ( + tuple(input_a.shape), + tuple(input_a.stride()), + input_a.dtype, + tuple(input_b.shape), + tuple(input_b.stride()), + input_b.dtype, + tuple(output.shape), + tuple(output.stride()), + output.dtype, + ) + + +def get_gemm_cache_key(prep_cache_key, max_active_clusters, total_num_clusters): + return ( + prep_cache_key, + max_active_clusters, + total_num_clusters, + ) + + +def compute_total_num_clusters(problem_sizes_mnkl, cluster_tile_shape_mn): + total_num_clusters = 0 + for m, n, _, _ in problem_sizes_mnkl: + num_clusters_mn = tuple( + ceildiv(x, y) for x, y in zip((m, n), cluster_tile_shape_mn) + ) + total_num_clusters += functools.reduce(lambda x, y: x * y, num_clusters_mn) + return total_num_clusters + + +def compute_cluster_tile_shape(mma_tiler_mn, cluster_shape_mn, use_2cta_instrs): + cta_tile_shape_mn = list(mma_tiler_mn) + if use_2cta_instrs: + cta_tile_shape_mn[0] = cta_tile_shape_mn[0] // 2 + return tuple(x * y for x, y in zip(cta_tile_shape_mn, cluster_shape_mn)) + + +@cute.kernel +def build_group_ptrs_from_bases_kernel( + base_A_u64: cutlass.Int64, # device addr of input_a (bytes) + base_B_u64: cutlass.Int64, # device addr of input_b (bytes) + base_C_u64: cutlass.Int64, # device addr of Output (bytes) + offs: cute.Tensor, # [G], cutlass.Int32/64 cumulative + K: cutlass.Constexpr, + N: cutlass.Constexpr, + sizeof_element: cutlass.Int32, # bytes + # -------- STRIDES (in ELEMENTS) -------- + stride_A_m_elems: cutlass.Constexpr, # A.stride(0) + stride_A_k_elems: cutlass.Constexpr, # A.stride(1) + stride_B0_elems: cutlass.Constexpr, # B.stride(0) + stride_Bk_elems: cutlass.Constexpr, # B.stride(1) + stride_Bn_elems: cutlass.Constexpr, # B.stride(2) + stride_C_m_elems: cutlass.Constexpr, # C.stride(0) + stride_C_n_elems: cutlass.Constexpr, # C.stride(1) + # -------- OUTPUTS -------- + out_ptrs: cute.Tensor, # [G,3] cutlass.Int64: (A_ptr, B_ptr, C_ptr) + out_problem: cute.Tensor, # [G,4] cutlass.Int32: (m_g, n, k, 1) + out_strides_abc: cute.Tensor, # [G,3,2] cutlass.Int32 [[A_m,A_k],[B_n,B_k],[C_m,C_n]] +): + tidx, _, _ = cute.arch.thread_idx() + g = tidx + + m_beg_i32 = 0 + if g > 0: + m_beg_i32 = offs[g - 1] + m_end_i32 = offs[g] + m_g_i32 = m_end_i32 - m_beg_i32 + + a_byte_off = ( + cutlass.Int64(m_beg_i32) * stride_A_m_elems * cutlass.Int64(sizeof_element) + ) + c_byte_off = ( + cutlass.Int64(m_beg_i32) * stride_C_m_elems * cutlass.Int64(sizeof_element) + ) + b_byte_off = cutlass.Int64(g) * stride_B0_elems * cutlass.Int64(sizeof_element) + + # ---- pointers ---- + out_ptrs[g, 0] = base_A_u64 + a_byte_off + out_ptrs[g, 1] = base_B_u64 + b_byte_off + out_ptrs[g, 2] = base_C_u64 + c_byte_off + + # ---- (m, n, k, 1) ---- + out_problem[g, 0] = m_g_i32 + out_problem[g, 1] = N + out_problem[g, 2] = K + out_problem[g, 3] = cutlass.Int32(1) + + # ---- strides ---- + out_strides_abc[g, 0, 0] = cutlass.Int32(stride_A_m_elems) + out_strides_abc[g, 0, 1] = cutlass.Int32(stride_A_k_elems) + out_strides_abc[g, 1, 0] = cutlass.Int32(stride_Bn_elems) + out_strides_abc[g, 1, 1] = cutlass.Int32(stride_Bk_elems) + out_strides_abc[g, 2, 0] = cutlass.Int32(stride_C_m_elems) + out_strides_abc[g, 2, 1] = cutlass.Int32(stride_C_n_elems) + + +@cute.jit +def launch_build_group_ptrs_from_bases( + base_A_u64: cutlass.Int64, + base_B_u64: cutlass.Int64, + base_C_u64: cutlass.Int64, + offs: cute.Tensor, + G: cutlass.Constexpr, + K: cutlass.Constexpr, + N: cutlass.Constexpr, + sizeof_element: cutlass.Constexpr, + stride_A_m_elems: cutlass.Constexpr, + stride_A_k_elems: cutlass.Constexpr, + stride_B0_elems: cutlass.Constexpr, + stride_Bk_elems: cutlass.Constexpr, + stride_Bn_elems: cutlass.Constexpr, + stride_C_m_elems: cutlass.Constexpr, + stride_C_n_elems: cutlass.Constexpr, + out_ptrs: cute.Tensor, # [G,3] cutlass.Int64 + out_problem: cute.Tensor, # [G,4] cutlass.Int32 + out_strides_abc: cute.Tensor, # [3,2] cutlass.Int32 + stream: cuda.CUstream, +): + build_group_ptrs_from_bases_kernel( + base_A_u64, + base_B_u64, + base_C_u64, + offs, + K, + N, + sizeof_element, + stride_A_m_elems, + stride_A_k_elems, + stride_B0_elems, + stride_Bk_elems, + stride_Bn_elems, + stride_C_m_elems, + stride_C_n_elems, + out_ptrs, + out_problem, + out_strides_abc, + ).launch(grid=(1, 1, 1), block=(G, 1, 1), stream=stream) + + +{{def_kernel("input_a", "input_b", "input_a_offs")}} + stream = cuda.CUstream(stream) + + input_b = input_b.transpose(1, 2) + + sumM, K = input_a.shape + G, N, Kb = input_b.shape + + dev = input_a.device + dev_idx = dev.index if dev.index is not None else 0 + + base_A_u64 = int(input_a.data_ptr()) + base_B_u64 = int(input_b.data_ptr()) + base_C_u64 = int({{get_output()}}.data_ptr()) + + ptrs_t = torch.empty((G, 3), device=dev, dtype=torch.int64) + probs_t = torch.empty((G, 4), device=dev, dtype=torch.int32) + strides_t = torch.empty((G, 3, 2), device=dev, dtype=torch.int32) + + prep_cache_key = get_prep_cache_key(input_a, input_b, {{get_output()}}) + prep_executor = disk_cache_get(_prep_fn_cache, __file__, _KERNEL_CONFIG_KEY, prep_cache_key, dev_idx) + + if prep_executor is None: + sizeof_element = int(input_a.element_size()) + sA_m, sA_k = map(int, input_a.stride()) + sB_0, sB_n, sB_k = map(int, input_b.stride()) + sC_m, sC_n = map(int, {{get_output()}}.stride()) + + prep_executor = cute.compile( + launch_build_group_ptrs_from_bases, + base_A_u64=base_A_u64, + base_B_u64=base_B_u64, + base_C_u64=base_C_u64, + offs=_to_fake_cute_tensor(input_a_offs, assumed_align=4), + G=int(G), + K=int(K), + N=int(N), + sizeof_element=sizeof_element, + stride_A_m_elems=sA_m, + stride_A_k_elems=sA_k, + stride_B0_elems=sB_0, + stride_Bk_elems=sB_k, + stride_Bn_elems=sB_n, + stride_C_m_elems=sC_m, + stride_C_n_elems=sC_n, + out_ptrs=_to_fake_cute_tensor(ptrs_t), + out_problem=_to_fake_cute_tensor(probs_t, assumed_align=4), + out_strides_abc=_to_fake_cute_tensor(strides_t, assumed_align=4), + stream=cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + + disk_cache_set(_prep_fn_cache, __file__, _KERNEL_CONFIG_KEY, prep_cache_key, prep_executor, dev_idx) + + prep_executor( + base_A_u64, base_B_u64, base_C_u64, + input_a_offs, ptrs_t, probs_t, strides_t, + ) + + # --- Tensormap workspace per SM --- + num_tensormap_buffers, max_active_clusters = get_hardware_info() + tensormap_shape = ( + num_tensormap_buffers, + GroupedGemmKernel.num_tensormaps, + GroupedGemmKernel.bytes_per_tensormap // 8, + ) + tensormap_workspace_t = torch.empty(tensormap_shape, device=dev, dtype=torch.int64) + + # --- Total clusters --- + cluster_tile_shape_mn = compute_cluster_tile_shape( + (TILE_M, TILE_N), (CLUSTER_M, CLUSTER_N), bool(USE_2_CTA) + ) + + total_num_clusters = int(compute_total_num_clusters(probs_t, cluster_tile_shape_mn)) + + gemm_cache_key = get_gemm_cache_key( + prep_cache_key, max_active_clusters, total_num_clusters + ) + gemm_executor = disk_cache_get(_gemm_fn_cache, __file__, _KERNEL_CONFIG_KEY, gemm_cache_key, dev_idx) + + if gemm_executor is None: + grouped_gemm = GroupedGemmKernel( + acc_dtype=ACC_DTYPE, + use_2cta_instrs=USE_2_CTA, + mma_tiler_mn=(TILE_M, TILE_N), + cluster_shape_mn=(CLUSTER_M, CLUSTER_N), + tensormap_update_mode=TENSORMAP_UPDATE_MODE, + ) + + a_unsq = input_a.unsqueeze(-1) + b_unsq = input_b[0].unsqueeze(-1) + c_unsq = {{get_output()}}.unsqueeze(-1) + gemm_executor = cute.compile( + grouped_gemm, + _to_fake_cute_tensor(a_unsq), + _to_fake_cute_tensor(b_unsq), + _to_fake_cute_tensor(c_unsq), + G, + _to_fake_cute_tensor(probs_t, assumed_align=4), + _to_fake_cute_tensor(strides_t, assumed_align=4), + _to_fake_cute_tensor(ptrs_t), + total_num_clusters, + _to_fake_cute_tensor(tensormap_workspace_t), + max_active_clusters, + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + + disk_cache_set(_gemm_fn_cache, __file__, _KERNEL_CONFIG_KEY, gemm_cache_key, gemm_executor, dev_idx) + + gemm_executor( + input_a.unsqueeze(-1), + input_b[0].unsqueeze(-1), + {{get_output()}}.unsqueeze(-1), + probs_t, + strides_t, + ptrs_t, + tensormap_workspace_t, + ) + + +def {{kernel_name}}_precompile(precompile_shapes, precompile_strides, precompile_dtypes, device_index=0, device_capability=None, hw_info=None): + """Compile CuTe DSL kernels using fake tensors (no CUDA tensor allocation). + + Called by the subprocess worker to warm the disk cache. Uses fake compact + CuTe tensors for cute.compile(), avoiding torch.cuda.* calls so this can + run in forked subprocess workers where PyTorch CUDA is unavailable. + """ + import logging + _precompile_log = logging.getLogger(__name__) + + dtype_a = getattr(torch, precompile_dtypes["input_a"]) + dtype_b = getattr(torch, precompile_dtypes["input_b"]) + dtype_out = getattr(torch, precompile_dtypes["output"]) + + shape_a = tuple(precompile_shapes["input_a"]) + shape_b = tuple(precompile_shapes["input_b"]) + shape_out = tuple(precompile_shapes["output"]) + shape_offs = tuple(precompile_shapes["input_a_offs"]) + + stride_a = tuple(precompile_strides["input_a"]) + stride_b = tuple(precompile_strides["input_b"]) + stride_out = tuple(precompile_strides["output"]) + + sumM, K = shape_a + G = shape_offs[0] + N = shape_b[2] + + # _main transposes input_b: (G, K, N) -> (G, N, K) + trans_shape_b = (shape_b[0], shape_b[2], shape_b[1]) + trans_stride_b = (stride_b[0], stride_b[2], stride_b[1]) + + # Cache key must match get_prep_cache_key() which uses post-transpose tensors + prep_cache_key = ( + shape_a, stride_a, dtype_a, + trans_shape_b, trans_stride_b, dtype_b, + shape_out, stride_out, dtype_out, + ) + + # --- Build CPU proxy tensors from metadata --- + # Subprocess workers cannot allocate CUDA tensors, so we create CPU + # tensors with matching shape/stride/dtype for _to_fake_cute_tensor. + def _cpu_proxy(shape, stride, dtype): + return torch.empty_strided(shape, stride, dtype=dtype, device="cpu") + + # _main transposes then unsqueezes: a.unsqueeze(-1), b[0].unsqueeze(-1), c.unsqueeze(-1) + # Replicate those stride transformations on CPU proxies. + proxy_a = _cpu_proxy(shape_a, stride_a, dtype_a).unsqueeze(-1) + proxy_b_transposed = _cpu_proxy( + trans_shape_b, trans_stride_b, dtype_b, + ) + proxy_b_unsq = proxy_b_transposed[0].unsqueeze(-1) + proxy_out = _cpu_proxy(shape_out, stride_out, dtype_out).unsqueeze(-1) + + proxy_offs = _cpu_proxy(shape_offs, (1,), torch.int32) + proxy_ptrs = _cpu_proxy((G, 3), (3, 1), torch.int64) + proxy_probs = _cpu_proxy((G, 4), (4, 1), torch.int32) + proxy_strides = _cpu_proxy((G, 3, 2), (6, 2, 1), torch.int32) + + # --- Compile prep_executor --- + sizeof_element = torch.tensor(0, dtype=dtype_a).element_size() + sA_m, sA_k = stride_a + sB_0, sB_n, sB_k = trans_stride_b + sC_m, sC_n = stride_out + + prep_executor = cute.compile( + launch_build_group_ptrs_from_bases, + base_A_u64=0, + base_B_u64=0, + base_C_u64=0, + offs=_to_fake_cute_tensor(proxy_offs, assumed_align=4), + G=int(G), + K=int(K), + N=int(N), + sizeof_element=sizeof_element, + stride_A_m_elems=sA_m, + stride_A_k_elems=sA_k, + stride_B0_elems=sB_0, + stride_Bk_elems=sB_k, + stride_Bn_elems=sB_n, + stride_C_m_elems=sC_m, + stride_C_n_elems=sC_n, + out_ptrs=_to_fake_cute_tensor(proxy_ptrs), + out_problem=_to_fake_cute_tensor(proxy_probs, assumed_align=4), + out_strides_abc=_to_fake_cute_tensor(proxy_strides, assumed_align=4), + stream=cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + + disk_cache_set( + _prep_fn_cache, __file__, _KERNEL_CONFIG_KEY, prep_cache_key, + prep_executor, device_index, device_capability=device_capability, + ) + + # --- Compile GEMM executor --- + if hw_info is None: + _precompile_log.debug( + "hw_info not provided in precompile metadata; " + "skipping GEMM executor precompile (will compile lazily at runtime)" + ) + return + + sm_count, max_active_clusters = hw_info + tensormap_shape = ( + sm_count, + GroupedGemmKernel.num_tensormaps, + GroupedGemmKernel.bytes_per_tensormap // 8, + ) + + proxy_tensormap = _cpu_proxy(tensormap_shape, ( + tensormap_shape[1] * tensormap_shape[2], + tensormap_shape[2], + 1, + ), torch.int64) + + # Compute per-group problem sizes analytically from offsets + offs_data = [sumM * (i + 1) // G for i in range(G)] + problem_sizes = [] + for i in range(G): + m_beg = 0 if i == 0 else offs_data[i - 1] + problem_sizes.append((offs_data[i] - m_beg, N, K, 1)) + + cluster_tile_shape_mn = compute_cluster_tile_shape( + (TILE_M, TILE_N), (CLUSTER_M, CLUSTER_N), bool(USE_2_CTA), + ) + total_num_clusters = int(compute_total_num_clusters( + problem_sizes, cluster_tile_shape_mn, + )) + + gemm_cache_key = get_gemm_cache_key( + prep_cache_key, max_active_clusters, total_num_clusters, + ) + + grouped_gemm = GroupedGemmKernel( + acc_dtype=ACC_DTYPE, + use_2cta_instrs=USE_2_CTA, + mma_tiler_mn=(TILE_M, TILE_N), + cluster_shape_mn=(CLUSTER_M, CLUSTER_N), + tensormap_update_mode=TENSORMAP_UPDATE_MODE, + ) + + gemm_executor = cute.compile( + grouped_gemm, + _to_fake_cute_tensor(proxy_a), + _to_fake_cute_tensor(proxy_b_unsq), + _to_fake_cute_tensor(proxy_out), + G, + _to_fake_cute_tensor(proxy_probs, assumed_align=4), + _to_fake_cute_tensor(proxy_strides, assumed_align=4), + _to_fake_cute_tensor(proxy_ptrs), + total_num_clusters, + _to_fake_cute_tensor(proxy_tensormap), + max_active_clusters, + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + + disk_cache_set( + _gemm_fn_cache, __file__, _KERNEL_CONFIG_KEY, gemm_cache_key, + gemm_executor, device_index, device_capability=device_capability, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_blackwell_ws_persistent_device_tma_mm.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_blackwell_ws_persistent_device_tma_mm.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..a50e3660d4276e96cce6b60349073b723b731ed5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_blackwell_ws_persistent_device_tma_mm.py.jinja @@ -0,0 +1,147 @@ +{{def_kernel("A", "B")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + start_pid = tl.program_id(0) + grid_m = tl.cdiv(M, BLOCK_M) + grid_n = tl.cdiv(N, BLOCK_N) + k_tiles = tl.cdiv(K, BLOCK_K) + num_tiles = grid_m * grid_n + + # Note: We require TMA_EXPERIMENTAL_API == False, which + # we will check before invoking this template. + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + a_desc = triton.language.make_tensor_descriptor( + base=A, + shape=[M, K] if A_ROW_MAJOR else [K, M], + strides=[stride_am, 1] if A_ROW_MAJOR else [stride_ak, 1], + block_shape=[BLOCK_M, BLOCK_K] if A_ROW_MAJOR else [BLOCK_K, BLOCK_M], + ) + b_desc = triton.language.make_tensor_descriptor( + base=B, + shape=[K, N] if B_ROW_MAJOR else [N, K], + strides=[stride_bk, 1] if B_ROW_MAJOR else [stride_bn, 1], + block_shape=[BLOCK_K, BLOCK_N] if B_ROW_MAJOR else [BLOCK_N, BLOCK_K], + ) + # tile_id_c is used in the epilogue to break the dependency between + # the prologue and the epilogue + tile_id_c = start_pid - NUM_SMS + num_pid_in_group = GROUP_M * grid_n + + {%- if USE_META_WS %} + for tile_id in tl.range( + start_pid, + num_tiles, + NUM_SMS, + flatten=FLATTEN, + warp_specialize=WARP_SPECIALIZE, + data_partition_factor=DATA_PARTITION_FACTOR, + separate_epilogue_store=SEPARATE_EPILOGUE_STORE, + ): + {%- else %} + for tile_id in tl.range( + start_pid, num_tiles, NUM_SMS, flatten=FLATTEN, warp_specialize=WARP_SPECIALIZE + ): + {%- endif %} + pid_m, pid_n = _compute_pid( + tile_id, num_pid_in_group, grid_m, GROUP_M, NUM_SMS + ) + offs_am = pid_m * BLOCK_M + offs_bn = pid_n * BLOCK_N + offs_am_desc = offs_am.to(tl.int32) + offs_bn_desc = offs_bn.to(tl.int32) + + accumulator = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + for ki in range(k_tiles): + offs_k = ki * BLOCK_K + offs_k_desc = offs_k.to(tl.int32) + a = tl.load_tensor_descriptor( + a_desc, + [offs_am_desc, offs_k_desc] + if A_ROW_MAJOR + else [offs_k_desc, offs_am_desc], + ) + b = tl.load_tensor_descriptor( + b_desc, + [offs_k_desc, offs_bn_desc] + if B_ROW_MAJOR + else [offs_bn_desc, offs_k_desc], + ) + accumulator += tl.dot( + a if A_ROW_MAJOR else a.T, + b if B_ROW_MAJOR else b.T, + allow_tf32=ALLOW_TF32, + ) + + tile_id_c += NUM_SMS + pid_m, pid_n = _compute_pid( + tile_id_c, num_pid_in_group, grid_m, GROUP_M, NUM_SMS + ) + offs_cm = pid_m * BLOCK_M + offs_cn = pid_n * BLOCK_N + subtiles = _subtile_accumulator(accumulator, BLOCK_M, BLOCK_N, EPILOGUE_SUBTILE) + for i in tl.static_range(EPILOGUE_SUBTILE): + subtile = subtiles[i] + offs_cn_i = offs_cn + i * (BLOCK_N // EPILOGUE_SUBTILE) + {{store_output( + ("offs_cm", "offs_cn_i"), + "subtile", + indent_width=12, + val_shape=("BLOCK_M", "BLOCK_N // EPILOGUE_SUBTILE"), + block_indexing=True + )}} + +@triton.jit +def _compute_pid(tile_id, num_pid_in_group, grid_m, GROUP_M: tl.constexpr, NUM_SMS: tl.constexpr): + group_id = tile_id // num_pid_in_group + first_pid_m = group_id * GROUP_M + GROUP_M = min(grid_m - first_pid_m, GROUP_M) + pid_m = first_pid_m + (tile_id % GROUP_M) + pid_n = (tile_id % num_pid_in_group) // GROUP_M + return pid_m, pid_n + + +@triton.jit +def _subtile_accumulator( + acc, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + SUBTILE_FACTOR: tl.constexpr, +): + """ + Recursively split an accumulator into SUBTILE_FACTOR pieces using + reshape + permute + split operations. + + Args: + acc: The accumulator tensor of shape (BLOCK_M, BLOCK_N) + BLOCK_M: The M dimension size (constexpr) + BLOCK_N: The N dimension size (constexpr) + SUBTILE_FACTOR: Must be a power of 2. The number of pieces to split into (constexpr) + + Returns: + A tuple of SUBTILE_FACTOR tensors, each of shape (BLOCK_M, BLOCK_N // SUBTILE_FACTOR) + """ + # SUBTILE_FACTOR must be a power of 2 + tl.static_assert(SUBTILE_FACTOR > 0, "SUBTILE_FACTOR must be positive") + tl.static_assert((SUBTILE_FACTOR & (SUBTILE_FACTOR - 1)) == 0, "SUBTILE_FACTOR must be a power of 2") + + if SUBTILE_FACTOR == 1: + # Base case: no subtiling needed, return the input as a single-element tuple + return (acc,) + else: + # Recursive case: split into 2 halves, then recursively split each half + tl.static_assert(BLOCK_N % 2 == 0) + acc = tl.reshape(acc, (BLOCK_M, 2, BLOCK_N // 2)) + acc = tl.permute(acc, (0, 2, 1)) + left, right = tl.split(acc) + # Recursively split each half + left_subtiles = _subtile_accumulator(left, BLOCK_M, BLOCK_N // 2, SUBTILE_FACTOR // 2) + right_subtiles = _subtile_accumulator(right, BLOCK_M, BLOCK_N // 2, SUBTILE_FACTOR // 2) + # Concatenate the tuples + return left_subtiles + right_subtiles diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_bmm.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_bmm.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..6c0c19183969d5a406bf2a8df05fa977afb2963e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_bmm.py.jinja @@ -0,0 +1,71 @@ +{{def_kernel("A", "B")}} + M = {{size("A", -2)}} + N = {{size("B", -1)}} + K = {{size("A", -1)}} + BATCH = {{size("A", 0)}} + + stride_aq = {{stride("A", 0)}} + stride_am = {{stride("A", 1)}} + stride_ak = {{stride("A", 2)}} + + stride_bq = {{stride("B", 0)}} + stride_bk = {{stride("B", 1)}} + stride_bn = {{stride("B", 2)}} + + # based on triton.ops.matmul + pid = tl.program_id(0).to(INDEX_DTYPE) + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + tl.assume(pid_m >= 0) + tl.assume(pid_n >= 0) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M).to(INDEX_DTYPE) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N).to(INDEX_DTYPE) + if ((stride_am == 1 and stride_ak == M) or (stride_am == K and stride_ak == 1)) and (M >= BLOCK_M and K > 1): + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + else: + ram = rm % M + if ((stride_bk == 1 and stride_bn == K) or (stride_bk == N and stride_bn == 1)) and (N >= BLOCK_N and K > 1): + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + else: + rbn = rn % N + + rk = tl.arange(0, BLOCK_K).to(INDEX_DTYPE) + + # Reconstruct batch index from grid_y/grid_z split (handles batch > 65535) + idx_q = (tl.program_id(1) + tl.program_id(2) * tl.num_programs(1)).to(INDEX_DTYPE) + # Clamp to valid range for safe pointer arithmetic; out-of-bounds CTAs are + # masked off at the store below. + idx_q_clamped = tl.minimum(idx_q, BATCH - 1) + A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak + idx_q_clamped*stride_aq) + B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn + idx_q_clamped*stride_bq) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + for k in range(K, 0, -BLOCK_K): + if EVEN_K: + a = tl.load(A) + b = tl.load(B) + else: + a = tl.load(A, mask=rk[None, :] < k, other=0.) + b = tl.load(B, mask=rk[:, None] < k, other=0.) + acc += tl.dot(a, b, allow_tf32=ALLOW_TF32) + A += BLOCK_K * stride_ak + B += BLOCK_K * stride_bk + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M).to(INDEX_DTYPE) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N).to(INDEX_DTYPE) + idx_q = (tl.program_id(1) + tl.program_id(2) * tl.num_programs(1)).to(INDEX_DTYPE) + idx_m = rm[:, None] + idx_n = rn[None, :] + mask = (idx_m < M) & (idx_n < N) & (idx_q < BATCH) + + # inductor generates a suffix + {{store_output(("idx_q", "idx_m", "idx_n"), "acc", "mask", val_shape=("BLOCK_M", "BLOCK_N"))}} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_conv2d_bwd_input.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_conv2d_bwd_input.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..ad9c63ef1d2ef40c6ba6b3490af8b05b572c0f55 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_conv2d_bwd_input.py.jinja @@ -0,0 +1,110 @@ +{% macro loop_body_bwd_input_2d() -%} + + idx_k = k + tl.arange(0, BLOCK_K) + oc_k = (idx_k // (KERNEL_H * KERNEL_W)).to(tl.int32) + ij = idx_k % (KERNEL_H * KERNEL_W) + i_k = (ij // KERNEL_W).to(tl.int32) + j_k = (ij % KERNEL_W).to(tl.int32) + + n_i = n.to(tl.int32) + h_i = h.to(tl.int32) + w_i = w.to(tl.int32) + + oc_global = oc_k + group * GROUP_OUT_C + + yhn = h_i[:, None] + PADDING_H - i_k[None, :] * DILATION_H + ywn = w_i[:, None] + PADDING_W - j_k[None, :] * DILATION_W + + cand_h = (yhn >= 0) & (yhn <= (OUT_H - 1) * STRIDE_H) + cand_w = (ywn >= 0) & (ywn <= (OUT_W - 1) * STRIDE_W) + + div_ok_h = tl.where(cand_h, (yhn % STRIDE_H) == 0, False) + div_ok_w = tl.where(cand_w, (ywn % STRIDE_W) == 0, False) + + yh = tl.where(div_ok_h, yhn // STRIDE_H, 0) + yw = tl.where(div_ok_w, ywn // STRIDE_W, 0) + + dy_ptrs = dY \ + + n_i[:, None] * stride_dyn \ + + oc_global[None, :] * stride_dyc \ + + yh * stride_dyh \ + + yw * stride_dyw + + mask_dy = ( + (n_i[:, None] < BATCH) & + (oc_k[None, :] < GROUP_OUT_C) & + div_ok_h & div_ok_w & + (yh >= 0) & (yh < OUT_H) & + (yw >= 0) & (yw < OUT_W) + ) + mat_dy = tl.load(dy_ptrs, mask=mask_dy, other=0.0) + + w_ptrs = W \ + + oc_global[:, None] * stride_wc_out \ + + ic[None, :] * stride_wc_in \ + + i_k[:, None] * stride_wh \ + + j_k[:, None] * stride_ww + + mask_w = (oc_k[:, None] < GROUP_OUT_C) & (ic[None, :] < GROUP_IN_C) + mat_w = tl.load(w_ptrs, mask=mask_w, other=0.0) + + # (M,K) @ (K,N) = (M,N) + acc += tl.dot(mat_dy, mat_w, allow_tf32=ALLOW_TF32) +{%- endmacro %} + +{{def_kernel("dY", "W")}} + + BATCH = {{size("dY", 0)}} + OUT_C = {{size("dY", 1)}} + OUT_H = {{size("dY", 2)}} + OUT_W = {{size("dY", 3)}} + GROUP_IN_C = {{size("W", 1)}} + KERNEL_H = {{size("W", 2)}} + KERNEL_W = {{size("W", 3)}} + + IN_H = {{size(None, 2)}} + IN_W = {{size(None, 3)}} + + stride_dyn = {{stride("dY", 0)}} + stride_dyc = {{stride("dY", 1)}} + stride_dyh = {{stride("dY", 2)}} + stride_dyw = {{stride("dY", 3)}} + + stride_wc_out = {{stride("W", 0)}} + stride_wc_in = {{stride("W", 1)}} + stride_wh = {{stride("W", 2)}} + stride_ww = {{stride("W", 3)}} + +{% if GROUPS == 1 %} + group = 0 + GROUP_OUT_C = OUT_C +{% else %} + group = tl.program_id(2).to(INDEX_DTYPE) + GROUP_OUT_C = OUT_C // GROUPS +{% endif %} + + nhw = tl.program_id(0).to(INDEX_DTYPE) * BLOCK_M + tl.arange(0, BLOCK_M) + w = nhw % IN_W + nh = nhw // IN_W + h = nh % IN_H + n = nh // IN_H + + ic = tl.program_id(1).to(INDEX_DTYPE) * BLOCK_N + tl.arange(0, BLOCK_N) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + + K_TOTAL = GROUP_OUT_C * KERNEL_H * KERNEL_W + for k in range(0, K_TOTAL, BLOCK_K): + {{ loop_body_bwd_input_2d() }} + + mask = ( + (n[:, None] < BATCH) + & (h[:, None] < IN_H) + & (w[:, None] < IN_W) + & (ic[None, :] < GROUP_IN_C) + ) + + ic_global = ic + group * GROUP_IN_C + + {{store_output(("n[:, None]", "ic_global[None, :]", "h[:, None]", "w[:, None]"), + "acc", "mask", val_shape=("BLOCK_M", "BLOCK_N"))}} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_conv2d_bwd_weight.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_conv2d_bwd_weight.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..87df50e84bacd87d9bb5ba5bac26c8b332ab0c57 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_conv2d_bwd_weight.py.jinja @@ -0,0 +1,104 @@ +{% macro loop_body_bwd_weight_2d() -%} + + idx_k = k + tl.arange(0, BLOCK_K) + n = (idx_k // (OUT_H * OUT_W)).to(tl.int32) + rem = idx_k % (OUT_H * OUT_W) + yh = (rem // OUT_W).to(tl.int32) + yw = (rem % OUT_W).to(tl.int32) + + m = (m0 + tl.arange(0, BLOCK_M)).to(tl.int32) + ic = (m // (KERNEL_H * KERNEL_W)).to(tl.int32) + ij = m % (KERNEL_H * KERNEL_W) + i = (ij // KERNEL_W).to(tl.int32) + j = (ij % KERNEL_W).to(tl.int32) + + xh = yh[:, None] * STRIDE_H - PADDING_H + i[None, :] * DILATION_H + xw = yw[:, None] * STRIDE_W - PADDING_W + j[None, :] * DILATION_W + + x_ptrs = X_base \ + + n[:, None] * stride_xn \ + + ic[None, :] * stride_xc \ + + xh * stride_xh \ + + xw * stride_xw + + mask_x = ( + (n[:, None] < BATCH) & + (ic[None, :] < GROUP_IN_C) & + (xh >= 0) & (xh < IN_H) & + (xw >= 0) & (xw < IN_W) + ) + matrix_x = tl.load(x_ptrs, mask=mask_x, other=0.0) + matrix_x = tl.trans(matrix_x) + + dy_ptrs = dY_base \ + + n[:, None] * stride_dyn \ + + oc[None, :] * stride_dyc \ + + yh[:, None] * stride_dyh \ + + yw[:, None] * stride_dyw + + mask_dy = ( + (n[:, None] < BATCH) & + (oc[None, :] < GROUP_OUT_C) & + (yh[:, None] < OUT_H) & + (yw[:, None] < OUT_W) + ) + matrix_dy = tl.load(dy_ptrs, mask=mask_dy, other=0.0) + + acc += tl.dot(matrix_x, matrix_dy, allow_tf32=ALLOW_TF32) +{%- endmacro %} + +{{def_kernel("X", "dY")}} + + BATCH = {{size("X", 0)}} + IN_C = {{size("X", 1)}} + IN_H = {{size("X", 2)}} + IN_W = {{size("X", 3)}} + OUT_C = {{size("dY", 1)}} + OUT_H = {{size("dY", 2)}} + OUT_W = {{size("dY", 3)}} + + stride_xn = {{stride("X", 0)}} + stride_xc = {{stride("X", 1)}} + stride_xh = {{stride("X", 2)}} + stride_xw = {{stride("X", 3)}} + + stride_dyn = {{stride("dY", 0)}} + stride_dyc = {{stride("dY", 1)}} + stride_dyh = {{stride("dY", 2)}} + stride_dyw = {{stride("dY", 3)}} + + m0 = tl.program_id(0).to(INDEX_DTYPE) * BLOCK_M + oc = tl.program_id(1).to(INDEX_DTYPE) * BLOCK_N + tl.arange(0, BLOCK_N) + +{% if GROUPS == 1 %} + group = 0 + GROUP_IN_C = IN_C + GROUP_OUT_C = OUT_C +{% else %} + group = tl.program_id(2).to(INDEX_DTYPE) + GROUP_IN_C = IN_C // GROUPS + GROUP_OUT_C = OUT_C // GROUPS +{% endif %} + + X_base = X + group * GROUP_IN_C * stride_xc + dY_base = dY + group * GROUP_OUT_C * stride_dyc + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + + K_TOTAL = BATCH * OUT_H * OUT_W + for k in range(0, K_TOTAL, BLOCK_K): + {{ loop_body_bwd_weight_2d() }} + + m = m0 + tl.arange(0, BLOCK_M) + ic = m // (KERNEL_H * KERNEL_W) + ij = m % (KERNEL_H * KERNEL_W) + i = ij // KERNEL_W + j = ij % KERNEL_W + + out_ic = ic + out_oc = oc + group * GROUP_OUT_C + + mask = (out_ic[:, None] < GROUP_IN_C) & (oc[None, :] < GROUP_OUT_C) + + {{store_output(("out_oc[None, :]", "out_ic[:, None]", "i[:, None]", "j[:, None]"), + "acc", "mask", val_shape=("BLOCK_M", "BLOCK_N"))}} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_depthwise_conv.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_depthwise_conv.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..312177c49dda363c95345b128af6dbebb145ae72 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_depthwise_conv.py.jinja @@ -0,0 +1,64 @@ +{{def_kernel("X", "W")}} + # Depthwise conv1d - channels-last (NLC) layout + # Each group has exactly 1 input channel (groups == in_channels == out_channels) + # 3D tiling: BLOCK_N x BLOCK_L x BLOCK_C + # Matches the hand-written NLC kernel from depthwise_conv1d_benchmark.py + + BATCH = {{size("X", 0)}} + CHANNELS = {{size("X", 1)}} + IN_L = {{size("X", 2)}} + OUT_L = {{size(None, 2)}} + + stride_xn = {{stride("X", 0)}} + stride_xc = {{stride("X", 1)}} + stride_xl = {{stride("X", 2)}} + + stride_wc = {{stride("W", 0)}} + stride_wk = {{stride("W", 2)}} + + # Grid: (cdiv(BATCH, BLOCK_N), cdiv(OUT_L, BLOCK_L), cdiv(CHANNELS, BLOCK_C)) + pid_n = tl.program_id(0).to(INDEX_DTYPE) + pid_l = tl.program_id(1).to(INDEX_DTYPE) + pid_c = tl.program_id(2).to(INDEX_DTYPE) + + n_start = pid_n * BLOCK_N + l_start = pid_l * BLOCK_L + c_start = pid_c * BLOCK_C + + n_offs = n_start + tl.arange(0, BLOCK_N) + l_offs = l_start + tl.arange(0, BLOCK_L) + c_offs = c_start + tl.arange(0, BLOCK_C) + n_mask = n_offs < BATCH + l_mask = l_offs < OUT_L + c_mask = c_offs < CHANNELS + + n3 = n_offs[:, None, None] + nm3 = n_mask[:, None, None] + c3 = c_offs[None, None, :] + cm3 = c_mask[None, None, :] + + in_base = n3 * stride_xn + c3 * stride_xc + + acc = tl.zeros((BLOCK_N, BLOCK_L, BLOCK_C), dtype=tl.float32) + + for k in range(KERNEL_SIZE): + wk = tl.load( + W + c_offs * stride_wc + k * stride_wk, + mask=c_mask, + other=0.0, + ).to(tl.float32) + l_in = l_offs * CONV_STRIDE - PADDING + k + mask_in = (l_in >= 0) & (l_in < IN_L) + x_vals = tl.load( + X + in_base + l_in[None, :, None] * stride_xl, + mask=nm3 & mask_in[None, :, None] & cm3, + other=0.0, + ).to(tl.float32) + acc += x_vals * wk[None, None, :] + + mask = nm3 & l_mask[None, :, None] & cm3 + idx_n = n_offs[:, None, None] + idx_c = c_offs[None, None, :] + idx_l = l_offs[None, :, None] + + {{store_output(("idx_n", "idx_c", "idx_l"), "acc", "mask", val_shape=("BLOCK_N", "BLOCK_L", "BLOCK_C"))}} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_epilogue_scaled_mm.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_epilogue_scaled_mm.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..cd3a6bdd4913a222489f18b0dccfbd7f3a3ab490 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_epilogue_scaled_mm.py.jinja @@ -0,0 +1,203 @@ +{{def_kernel("A", "B", "A_inverse_scale", "B_inverse_scale")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + + if SCALE_RECIPE_A == 1: # ScalingType.RowWise + stride_a_scale_m = 1 + else: + stride_a_scale_m = 0 + + if SCALE_RECIPE_B == 1: # ScalingType.RowWise + stride_b_scale_n = 1 + else: + stride_b_scale_n = 0 + + start_pid = tl.program_id(axis=0).to(INDEX_DTYPE) + num_pid_m = tl.cdiv(M, BLOCK_M) + num_pid_n = tl.cdiv(N, BLOCK_N) + k_tiles = tl.cdiv(K, BLOCK_K) + num_tiles = num_pid_m * num_pid_n + + {%- if TMA_EXPERIMENTAL_API %} + workspace_base = ws_ptr + start_pid * 2 * TMA_SIZE + a_desc_ptr = workspace_base + b_desc_ptr = workspace_base + TMA_SIZE + + triton.language.extra.cuda.experimental_device_tensormap_create2d( + desc_ptr=a_desc_ptr, + global_address=A, + load_size=[BLOCK_M, BLOCK_K], + global_size=[M, K], + element_ty=A.dtype.element_ty, + ) + triton.language.extra.cuda.experimental_device_tensormap_create2d( + desc_ptr=b_desc_ptr, + global_address=B, + load_size=[BLOCK_N, BLOCK_K], + global_size=[N, K], + element_ty=B.dtype.element_ty, + ) + + tl.extra.cuda.experimental_tensormap_fenceproxy_acquire(a_desc_ptr) + tl.extra.cuda.experimental_tensormap_fenceproxy_acquire(b_desc_ptr) + + {%- else %} + stride_am = {{stride("A", 0)}} + stride_bn = {{stride("B", 1)}} + a_desc = triton.language.make_tensor_descriptor( + base=A, + shape=[M, K], + strides=[stride_am, 1], + block_shape=[BLOCK_M, BLOCK_K], + ) + b_desc = triton.language.make_tensor_descriptor( + base=B, + shape=[N, K], + strides=[stride_bn, 1], + block_shape=[BLOCK_N, BLOCK_K], + ) + {%- endif %} + + tiles_per_SM = num_tiles // NUM_SMS + if start_pid < num_tiles % NUM_SMS: + tiles_per_SM += 1 + + tile_id = start_pid - NUM_SMS + ki = -1 + + pid_m = 0 + pid_n = 0 + offs_am = 0 + offs_bn = 0 + + num_pid_in_group = GROUP_M * num_pid_n + accumulator = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + a_scale = load_scales(A_inverse_scale, SCALE_RECIPE_A) + b_scale = load_scales(B_inverse_scale, SCALE_RECIPE_B) + + for _ in range(0, k_tiles * tiles_per_SM): + ki = tl.where(ki == k_tiles - 1, 0, ki + 1) + if ki == 0: + tile_id += NUM_SMS + group_id = tile_id // num_pid_in_group + first_pid_m = group_id * GROUP_M + group_size_m = min(num_pid_m - first_pid_m, GROUP_M) + pid_m = first_pid_m + (tile_id % group_size_m) + pid_n = (tile_id % num_pid_in_group) // group_size_m + + offs_am = pid_m * BLOCK_M + offs_bn = pid_n * BLOCK_N + + offs_k = ki * BLOCK_K + offs_am_desc = offs_am.to(tl.int32) + offs_bn_desc = offs_bn.to(tl.int32) + offs_k_desc = offs_k.to(tl.int32) + + {%- if TMA_EXPERIMENTAL_API %} + a = tl._experimental_descriptor_load( + a_desc_ptr, + [offs_am_desc, offs_k_desc], + [BLOCK_M, BLOCK_K], + A.dtype.element_ty, + ) + b = tl._experimental_descriptor_load( + b_desc_ptr, + [offs_bn_desc, offs_k_desc], + [BLOCK_N, BLOCK_K], + B.dtype.element_ty, + ) + {%- else %} + a = tl.load_tensor_descriptor(a_desc, [offs_am_desc, offs_k_desc]) + b = tl.load_tensor_descriptor(b_desc, [offs_bn_desc, offs_k_desc]) + {%- endif %} + if USE_FAST_ACCUM: + accumulator = tl.dot(a, b.T, accumulator) + else: + accumulator += tl.dot(a, b.T) + + if ki == k_tiles - 1: + # Apply inverse scaling + offs_cm = offs_am + tl.arange(0, BLOCK_M) + offs_cn = offs_bn + tl.arange(0, BLOCK_N) + # Apply scaling + accumulator = apply_scaling( + accumulator, + a_scale, + b_scale, + SCALE_RECIPE_A, + SCALE_RECIPE_B, + offs_cm, + offs_cn, + M, + N, + stride_a_scale_m, + stride_b_scale_n, + ) + + # inductor generates a suffix + {%- if TMA_EXPERIMENTAL_API %} + idx_m = offs_cm[:, None] + idx_n = offs_cn[None, :] + mask = (idx_m < M) & (idx_n < N) + {{store_output(("idx_m", "idx_n"), "accumulator", "mask", indent_width=12, val_shape=("BLOCK_M", "BLOCK_N"))}} + {%- else %} + {{store_output( + ("offs_am", "offs_bn"), + "accumulator", + indent_width=12, + val_shape=("BLOCK_M", "BLOCK_N"), + block_indexing=True, + )}} + {%- endif %} + accumulator = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + + +@triton.jit +def load_scales(scale_ptr, SCALE_RECIPE: tl.constexpr): + if SCALE_RECIPE == 0: + return tl.load(scale_ptr) # For tensor-wise scaling, we'll load the scalar values + else: + return scale_ptr # For all other scaling recipes, we'll return the pointers + + +@triton.jit +def apply_scaling( + accumulator, + a_scale, + b_scale, + SCALE_RECIPE_A: tl.constexpr, + SCALE_RECIPE_B: tl.constexpr, + offs_cm, + offs_cn, + M, + N, + stride_a_scale_m, + stride_b_scale_n, +): + if SCALE_RECIPE_A == 1 and SCALE_RECIPE_B == 1: # (ScalingType.RowWise, ScalingType.RowWise) + # For row-wise scaling, we need to load the scales for each row/column + a_scales = tl.load( + a_scale + (offs_cm * stride_a_scale_m), + mask=offs_cm < M, + other=0.0, + ) + b_scales = tl.load( + b_scale + (offs_cn * stride_b_scale_n), + mask=offs_cn < N, + other=0.0, + ) + acc_scale = a_scales[:, None] * b_scales[None, :] + else: # (ScalingType.TensorWise, ScalingType.TensorWise) + # For per-tensor scaling, we can directly use the loaded scalar values + acc_scale = a_scale * b_scale + + return accumulator * acc_scale diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_main_loop_scaled_mm.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_main_loop_scaled_mm.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..0c2e51a1ec2f2d540e712e2119b6c1bba2a2eac5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_main_loop_scaled_mm.py.jinja @@ -0,0 +1,190 @@ +{{def_kernel("A", "B", "A_inverse_scale", "B_inverse_scale")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + + stride_am = {{stride("A", 0)}} + stride_bn = {{stride("B", 1)}} + + start_pid = tl.program_id(axis=0).to(INDEX_DTYPE) + num_pid_m = tl.cdiv(M, BLOCK_M) + num_pid_n = tl.cdiv(N, BLOCK_N) + k_tiles = tl.cdiv(K, BLOCK_K) + num_tiles = num_pid_m * num_pid_n + + a_desc = triton.language.make_tensor_descriptor( + base=A, + shape=[M, K], + strides=[stride_am, 1], + block_shape=[BLOCK_M, BLOCK_K], + ) + b_desc = triton.language.make_tensor_descriptor( + base=B, + shape=[N, K], + strides=[stride_bn, 1], + block_shape=[BLOCK_N, BLOCK_K], + ) + + + num_pid_in_group = GROUP_M * num_pid_n + + am_blocks = tl.cdiv(M, TILE_SIZE_A) + ak_blocks = tl.cdiv(K, TILE_SIZE_A) + bn_blocks = tl.cdiv(N, TILE_SIZE_B) + bk_blocks = tl.cdiv(K, TILE_SIZE_B) + + for tile_id in range(start_pid, num_tiles, NUM_SMS): + group_id = tile_id // num_pid_in_group + first_pid_m = group_id * GROUP_M + group_size_m = min(num_pid_m - first_pid_m, GROUP_M) + pid_m = first_pid_m + (tile_id % group_size_m) + pid_n = (tile_id % num_pid_in_group) // group_size_m + + offs_am = pid_m * BLOCK_M + offs_bn = pid_n * BLOCK_N + offs_am_desc = offs_am.to(tl.int32) + offs_bn_desc = offs_bn.to(tl.int32) + + accumulator = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + for ki in range(0, k_tiles): + offs_k = ki * BLOCK_K + offs_k_desc = offs_k.to(tl.int32) + + a = tl.load_tensor_descriptor(a_desc, [offs_am_desc, offs_k_desc]) + b = tl.load_tensor_descriptor(b_desc, [offs_bn_desc, offs_k_desc]) + + {%- if SCALE_RECIPE_A == 5 %} # ScalingType.Blockwise128x128 + scale_a_block = blockwise128x128_scaling( + pid_m, + A_inverse_scale, + ki, + am_blocks, + ak_blocks, + BLOCK_M, + BLOCK_K, + MIN_BLOCK_TILE_AM, + MIN_BLOCK_TILE_AK, + ) + {%- else %} # ScalingType.Blockwise1xTILESIZE + scale_a_block = blockwise1xTILESIZE_scaling( + pid_m, + A_inverse_scale, + ki, + M, + am_blocks, + ak_blocks, + BLOCK_M, + BLOCK_K, + MIN_BLOCK_TILE_AK, + TILE_SIZE_A, + ) + {%- endif %} + + {%- if SCALE_RECIPE_B == 5 %} # ScalingType.Blockwise128x128 + scale_b_block = blockwise128x128_scaling( + pid_n, + B_inverse_scale, + ki, + bn_blocks, + bk_blocks, + BLOCK_N, + BLOCK_K, + MIN_BLOCK_TILE_BN, + MIN_BLOCK_TILE_BK, + ) + {%- else %} # ScalingType.Blockwise1xTILESIZE + scale_b_block = blockwise1xTILESIZE_scaling( + pid_n, + B_inverse_scale, + ki, + N, + bn_blocks, + bk_blocks, + BLOCK_N, + BLOCK_K, + MIN_BLOCK_TILE_BK, + TILE_SIZE_B, + ) + {%- endif %} + + a_scaled = a * scale_a_block + b_scaled = b * scale_b_block + accumulator = tl.dot(a_scaled, b_scaled.T, accumulator) + + offs_cm = offs_am + tl.arange(0, BLOCK_M) + offs_cn = offs_bn + tl.arange(0, BLOCK_N) + + # inductor generates a suffix + {{store_output( + ("offs_am", "offs_bn"), + "accumulator", + indent_width=8, + val_shape=("BLOCK_M", "BLOCK_N"), + block_indexing=True, + )}} + + +@triton.jit +def blockwise1xTILESIZE_scaling( + pid, + scale, + ki, + lhs_size, + lhs_blocks, + k_blocks, + BLOCK_lhs: tl.constexpr, + BLOCK_K: tl.constexpr, + MIN_BLOCK_TILE_K: tl.constexpr, + TILE_SIZE: tl.constexpr, +): + row_offs_scale = pid * BLOCK_lhs + tl.arange(0, BLOCK_lhs) + col_offs_scale = ki * tl.cdiv(BLOCK_K, TILE_SIZE) + tl.arange(0, (BLOCK_K + TILE_SIZE - 1) // TILE_SIZE) + ptrs = scale + row_offs_scale[:, None] * k_blocks + col_offs_scale[None, :] + mask = (row_offs_scale[:, None] < lhs_size) & (col_offs_scale[None, :] < k_blocks) + scale_block = tl.load(ptrs, mask=mask, other=1.0) + + scale_expanded = scale_block[:, :, None] + scale_expanded = tl.broadcast_to( + scale_expanded, + (BLOCK_lhs, (BLOCK_K + TILE_SIZE - 1) // TILE_SIZE, MIN_BLOCK_TILE_K) + ) + scale_expanded = scale_expanded.reshape( + BLOCK_lhs, + ((BLOCK_K + TILE_SIZE - 1) // TILE_SIZE) * MIN_BLOCK_TILE_K + ) + + return scale_expanded + + +@triton.jit +def blockwise128x128_scaling( + pid, + scale, + ki, + lhs_blocks, + k_blocks, + BLOCK_lhs: tl.constexpr, + BLOCK_K: tl.constexpr, + MIN_BLOCK_TILE_lhs: tl.constexpr, + MIN_BLOCK_TILE_K: tl.constexpr, +): + row_offs_scale = pid * tl.cdiv(BLOCK_lhs, 128) + tl.arange(0, (BLOCK_lhs + 128 - 1) // 128) + col_offs_scale = ki * tl.cdiv(BLOCK_K, 128) + tl.arange(0, (BLOCK_K + 128 - 1) // 128) + ptrs = scale + row_offs_scale[:, None] * k_blocks + col_offs_scale[None, :] + mask = (row_offs_scale[:, None] < lhs_blocks) & (col_offs_scale[None, :] < k_blocks) + scale_block = tl.load(ptrs, mask=mask, other=1.0) + + scale_expanded = scale_block[:, :, None, None] + scale_expanded = tl.broadcast_to( + scale_expanded, + ((BLOCK_lhs + 128 - 1) // 128, (BLOCK_K + 128 - 1) // 128, MIN_BLOCK_TILE_lhs, MIN_BLOCK_TILE_K) + ) + scale_expanded = scale_expanded.reshape( + ((BLOCK_lhs + 128 - 1) // 128) * MIN_BLOCK_TILE_lhs, + ((BLOCK_K + 128 - 1) // 128) * MIN_BLOCK_TILE_K + ) + + return scale_expanded diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_mm.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_mm.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..fcb22c94eada124b9c88f996cf3f707ff5436fb3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_mm.py.jinja @@ -0,0 +1,72 @@ +{{def_kernel("A", "B")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + + # based on triton.ops.matmul + pid = tl.program_id(0).to(INDEX_DTYPE) + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + tl.assume(pid_m >= 0) + tl.assume(pid_n >= 0) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M).to(INDEX_DTYPE) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N).to(INDEX_DTYPE) + if ((stride_am == 1 and stride_ak == M) or (stride_am == K and stride_ak == 1)) and (M >= BLOCK_M and K > 1): + offs_a_m = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + else: + offs_a_m = rm % M + if ((stride_bk == 1 and stride_bn == K) or (stride_bk == N and stride_bn == 1)) and (N >= BLOCK_N and K > 1): + offs_b_n = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + else: + offs_b_n = rn % N + offs_k = tl.arange(0, BLOCK_K).to(INDEX_DTYPE) + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + + for k_idx in range(0, tl.cdiv(K, BLOCK_K)): + {% if not EVEN_K %} + a_mask = offs_k[None, :] < (K - k_idx * BLOCK_K) + b_mask = offs_k[:, None] < (K - k_idx * BLOCK_K) + {% endif %} + a_k_idx_vals = offs_k[None, :] + (k_idx * BLOCK_K) + b_k_idx_vals = offs_k[:, None] + (k_idx * BLOCK_K) + + idx_m = offs_a_m[:, None] + idx_n = a_k_idx_vals + {{load_input("A", "a", ("idx_m", "idx_n"), mask=None if EVEN_K else "a_mask", + indent_width=8, index_shape=("BLOCK_M", "BLOCK_K"))}} + + idx_m = b_k_idx_vals + idx_n = offs_b_n[None, :] + {{load_input("B", "b", ("idx_m", "idx_n"), mask=None if EVEN_K else "b_mask", + indent_width=8, index_shape=("BLOCK_K", "BLOCK_N"))}} + + {% if USE_FAST_ACCUM %} + acc = tl.dot(a, b, acc, allow_tf32=ALLOW_TF32, out_dtype=ACC_TYPE) + {% else %} + acc += tl.dot(a, b, allow_tf32=ALLOW_TF32, out_dtype=ACC_TYPE) + {% endif %} + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M).to(INDEX_DTYPE) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N).to(INDEX_DTYPE) + idx_m = rm[:, None] + idx_n = rn[None, :] + mask = (idx_m < M) & (idx_n < N) + + # inductor generates a suffix + {{store_output(("idx_m", "idx_n"), "acc", "mask", val_shape=("BLOCK_M", "BLOCK_N"))}} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_mm_grouped.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_mm_grouped.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..52049582bf21d2928b58d6ee9a664eae15e5e6b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_mm_grouped.py.jinja @@ -0,0 +1,379 @@ +{% macro assign_maybe_constexpr(name, value_expr) -%} + {%- set value_str = value_expr | string -%} + {%- set sentinel = "__NOT_A_NUMBER__" -%} + {%- set as_int = value_str | int(default=sentinel) -%} + {%- set as_float = value_str | float(default=sentinel) -%} + {%- set is_constexpr = (as_int != sentinel) or (as_float != sentinel) -%} + {{ name }}{{ ": tl.constexpr" if is_constexpr else "" }} = {{ value_expr }} +{%- endmacro %} + +import triton +import triton.language as tl + +@triton.jit +def do_tma_loads( + g, a_desc, b_desc, m_offset, n_offset, k_offset, + BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr, +): +{%- if A_IS_2D %} +{%- if A_IS_K_MAJOR %} + a = a_desc.load([m_offset, k_offset]) +{%- else %} + a = a_desc.load([k_offset, m_offset]) +{%- endif %} +{%- else %} +{%- if A_IS_K_MAJOR %} + a = a_desc.load([g, m_offset, k_offset]).reshape(BLOCK_M, BLOCK_K) +{%- else %} + a = a_desc.load([g, k_offset, m_offset]).reshape(BLOCK_K, BLOCK_M) +{%- endif %} +{%- endif %} +{%- if B_IS_2D %} +{%- if B_IS_K_MAJOR %} + b = b_desc.load([n_offset, k_offset]) +{%- else %} + b = b_desc.load([k_offset, n_offset]) +{%- endif %} +{%- else %} +{%- if B_IS_K_MAJOR %} + b = b_desc.load([g, n_offset, k_offset]).reshape(BLOCK_N, BLOCK_K) +{%- else %} + b = b_desc.load([g, k_offset, n_offset]).reshape(BLOCK_K, BLOCK_N) +{%- endif %} +{%- endif %} + + return (a, b) + + +@triton.jit +def do_mma(a, b, accumulator): +{%- if USE_FAST_ACCUM %} +{%- if A_IS_K_MAJOR and B_IS_K_MAJOR %} + accumulator = tl.dot(a, b.T, accumulator) +{%- elif A_IS_K_MAJOR and not B_IS_K_MAJOR %} + accumulator = tl.dot(a, b, accumulator) +{%- elif not A_IS_K_MAJOR and B_IS_K_MAJOR %} + accumulator = tl.dot(a.T, b.T, accumulator) +{%- else %} + accumulator = tl.dot(a.T, b, accumulator) +{%- endif %} +{%- else %} +{%- if A_IS_K_MAJOR and B_IS_K_MAJOR %} + accumulator += tl.dot(a, b.T) +{%- elif A_IS_K_MAJOR and not B_IS_K_MAJOR %} + accumulator += tl.dot(a, b) +{%- elif not A_IS_K_MAJOR and B_IS_K_MAJOR %} + accumulator += tl.dot(a.T, b.T) +{%- else %} + accumulator += tl.dot(a.T, b) +{%- endif %} +{%- endif %} + + return accumulator + + +{%- if SCALED %} +{%- if A_IS_2D or B_IS_2D %} +{{def_kernel("a_ptr", "b_ptr", "scale_a_ptr", "scale_b_ptr", "offsets_ptr")}} +{%- else %} +{{def_kernel("a_ptr", "b_ptr", "scale_a_ptr", "scale_b_ptr")}} +{%- endif %} +{%- else %} +{%- if A_IS_2D or B_IS_2D %} +{{def_kernel("a_ptr", "b_ptr", "offsets_ptr")}} +{%- else %} +{{def_kernel("a_ptr", "b_ptr")}} +{%- endif %} +{%- endif %} + tidx = tl.program_id(0).to(INDEX_DTYPE) + +{%- set M_IS_VARYING = A_IS_2D and not B_IS_2D %} +{%- set N_IS_VARYING = not A_IS_2D and B_IS_2D %} +{%- set K_IS_VARYING = A_IS_2D and B_IS_2D %} + +{%- if A_IS_2D %} +{%- if B_IS_2D %} + {{ assign_maybe_constexpr("G", size("offsets_ptr", 0)) }} +{%- else %} + {{ assign_maybe_constexpr("G", size("b_ptr", 0)) }} +{%- endif %} +{%- else %} +{%- if B_IS_2D %} + {{ assign_maybe_constexpr("G", size("a_ptr", 0)) }} +{%- else %} + {{ assign_maybe_constexpr("G", size("a_ptr", 0)) }} +{%- endif %} +{%- endif %} + + # the b_ptr tensor is given with its last two dims transposed, revert here + + {{ assign_maybe_constexpr("M", size("a_ptr", -2)) }} + {{ assign_maybe_constexpr("N", size("b_ptr", -1)) }} + {{ assign_maybe_constexpr("K", size("a_ptr", -1)) }} + + {{ assign_maybe_constexpr("A_STRIDE_M", stride("a_ptr", -2)) }} + {{ assign_maybe_constexpr("A_STRIDE_K", stride("a_ptr", -1)) }} +{%- if not A_IS_2D %} + {{ assign_maybe_constexpr("A_STRIDE_G", stride("a_ptr", 0)) }} +{%- if SCALED %} + {{ assign_maybe_constexpr("SCALE_A_STRIDE_G", stride("scale_a_ptr", 0)) }} +{%- endif %} +{%- endif %} + {{ assign_maybe_constexpr("B_STRIDE_N", stride("b_ptr", -1)) }} + {{ assign_maybe_constexpr("B_STRIDE_K", stride("b_ptr", -2)) }} +{%- if not B_IS_2D %} + {{ assign_maybe_constexpr("B_STRIDE_G", stride("b_ptr", 0)) }} + B_STRIDE_G = {{stride("b_ptr", 0)}} +{%- if SCALED %} + {{ assign_maybe_constexpr("SCALE_B_STRIDE_G", stride("scale_b_ptr", 0)) }} +{%- endif %} +{%- endif %} + +{%- if USE_TMA_LOAD %} +{%- if USE_EXPERIMENTAL_MAKE_TENSOR_DESCRIPTOR %} + a_desc = tl._experimental_make_tensor_descriptor( +{%- else %} + a_desc = tl.make_tensor_descriptor( +{%- endif %} + a_ptr, +{%- if A_IS_2D %} +{%- if A_IS_K_MAJOR %} + shape=[M, K], + strides=[A_STRIDE_M, A_STRIDE_K], + block_shape=[BLOCK_M, BLOCK_K], +{%- else %} + shape=[K, M], + strides=[A_STRIDE_K, A_STRIDE_M], + block_shape=[BLOCK_K, BLOCK_M], +{%- endif %} +{%- else %} +{%- if A_IS_K_MAJOR %} + shape=[G, M, K], + strides=[A_STRIDE_G, A_STRIDE_M, A_STRIDE_K], + block_shape=[1, BLOCK_M, BLOCK_K], +{%- else %} + shape=[G, K, M], + strides=[A_STRIDE_G, A_STRIDE_K, A_STRIDE_M], + block_shape=[1, BLOCK_K, BLOCK_M], +{%- endif %} +{%- endif %} + ) + +{%- if USE_EXPERIMENTAL_MAKE_TENSOR_DESCRIPTOR %} + b_desc = tl._experimental_make_tensor_descriptor( +{%- else %} + b_desc = tl.make_tensor_descriptor( +{%- endif %} + b_ptr, +{%- if B_IS_2D %} +{%- if B_IS_K_MAJOR %} + shape=[N, K], + strides=[B_STRIDE_N, B_STRIDE_K], + block_shape=[BLOCK_N, BLOCK_K], +{%- else %} + shape=[K, N], + strides=[B_STRIDE_K, B_STRIDE_N], + block_shape=[BLOCK_K, BLOCK_N], +{%- endif %} +{%- else %} +{%- if B_IS_K_MAJOR %} + shape=[G, N, K], + strides=[B_STRIDE_G, B_STRIDE_N, B_STRIDE_K], + block_shape=[1, BLOCK_N, BLOCK_K], +{%- else %} + shape=[G, K, N], + strides=[B_STRIDE_G, B_STRIDE_K, B_STRIDE_N], + block_shape=[1, BLOCK_K, BLOCK_N], +{%- endif %} +{%- endif %} + ) +{%- endif %} + +{%- if M_IS_VARYING %} + m_end_offset = 0 +{%- endif %} +{%- if N_IS_VARYING %} + n_end_offset = 0 +{%- endif %} +{%- if K_IS_VARYING %} + k_end_offset = 0 +{%- endif %} + iterated_tiles = 0 + for g in tl.range(G): +{%- if M_IS_VARYING %} + # Move across groups + m_start_offset = m_end_offset + m_end_offset = tl.load(offsets_ptr + g) + m_size = m_end_offset - m_start_offset +{%- if SCALED %} + m_scale_start_offset = m_start_offset +{%- endif %} +{%- else %} + m_start_offset = 0 + m_size = M +{%- if SCALED %} + m_scale_start_offset = g * M +{%- endif %} +{%- endif %} + +{%- if N_IS_VARYING %} + # Move across groups + n_start_offset = n_end_offset + n_end_offset = tl.load(offsets_ptr + g) + n_size = n_end_offset - n_start_offset +{%- if SCALED %} + n_scale_start_offset = n_start_offset +{%- endif %} +{%- else %} + n_start_offset = 0 + n_size = N +{%- if SCALED %} + n_scale_start_offset = g * N +{%- endif %} +{%- endif %} + + if m_size > 0 and n_size > 0: +{%- if K_IS_VARYING %} + # Move across groups + k_start_offset = k_end_offset + k_end_offset = tl.load(offsets_ptr + g) + k_size = k_end_offset - k_start_offset +{%- else %} + k_start_offset = 0 + k_size = K +{%- endif %} + + num_m_tiles = tl.cdiv(m_size, BLOCK_M) + num_n_tiles = tl.cdiv(n_size, BLOCK_N) + num_tiles = num_m_tiles * num_n_tiles + + # Move across tiles + while tidx >= iterated_tiles and tidx < iterated_tiles + num_tiles: + gidx = tidx - iterated_tiles + # Split M first and N second. + tile_m_idx = gidx % num_m_tiles + tile_n_idx = gidx // num_m_tiles + + accumulator = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + +{%- if USE_TMA_LOAD %} + m_tile_offset = tile_m_idx * BLOCK_M + n_tile_offset = tile_n_idx * BLOCK_N + m_offset = (m_start_offset + m_tile_offset).to(tl.int32) + n_offset = (n_start_offset + n_tile_offset).to(tl.int32) + + k_block_offset = 0 + for k in range(k_size // BLOCK_K): + k_offset = k_start_offset + k_block_offset + a, b = do_tma_loads( + g, a_desc, b_desc, m_offset, n_offset, k_offset, + BLOCK_M, BLOCK_N, BLOCK_K + ) + accumulator = do_mma(a, b, accumulator) + k_block_offset += BLOCK_K + + if k_size % BLOCK_K != 0: + k_offset = k_start_offset + k_block_offset + a, b = do_tma_loads( + g, a_desc, b_desc, m_offset, n_offset, k_offset, + BLOCK_M, BLOCK_N, BLOCK_K + ) +{%- if K_IS_VARYING %} + group_offs = k_block_offset + tl.arange(0, BLOCK_K) + k_mask = group_offs < k_size +{%- if A_IS_K_MAJOR %} + a = tl.where(k_mask[None, :], a, 0) +{%- else %} + a = tl.where(k_mask[:, None], a, 0) +{%- endif %} +{%- if B_IS_K_MAJOR %} + b = tl.where(k_mask[None, :], b, 0) +{%- else %} + b = tl.where(k_mask[:, None], b, 0) +{%- endif %} +{%- endif %} + accumulator = do_mma(a, b, accumulator) +{%- else %} + offs_am = tile_m_idx * BLOCK_M + tl.arange(0, BLOCK_M).to(INDEX_DTYPE) + offs_bn = tile_n_idx * BLOCK_N + tl.arange(0, BLOCK_N).to(INDEX_DTYPE) + for k_block_offset in range(0, k_size, BLOCK_K): + block_offs_k = k_block_offset + tl.arange(0, BLOCK_K).to(INDEX_DTYPE) + offs_k = block_offs_k + k_start_offset + a_ptrs = ( + a_ptr +{%- if not A_IS_2D %} + + g * A_STRIDE_G +{%- endif %} + + (m_start_offset + offs_am[:, None]) * A_STRIDE_M + + offs_k[None, :] * A_STRIDE_K + ) + b_ptrs = ( + b_ptr +{%- if not B_IS_2D %} + + g * B_STRIDE_G +{%- endif %} + + (n_start_offset + offs_bn[:, None]) * B_STRIDE_N + + offs_k[None, :] * B_STRIDE_K + ) + a_mask = (offs_am[:, None] < m_size) & (block_offs_k[None, :] < k_size) + b_mask = (offs_bn[:, None] < n_size) & (block_offs_k[None, :] < k_size) + a = tl.load(a_ptrs, mask=a_mask, other=tl.zeros((), dtype=a_ptrs.dtype.element_ty)) + b = tl.load(b_ptrs, mask=b_mask, other=tl.zeros((), dtype=b_ptrs.dtype.element_ty)) +{%- if USE_FAST_ACCUM %} + accumulator = tl.dot(a, b.T, accumulator) +{%- else %} + accumulator += tl.dot(a, b.T) +{%- endif %} + a_ptrs += BLOCK_K + b_ptrs += BLOCK_K +{%- endif %} + + offs_am = tile_m_idx * BLOCK_M + tl.arange(0, BLOCK_M).to(INDEX_DTYPE) + offs_bn = tile_n_idx * BLOCK_N + tl.arange(0, BLOCK_N).to(INDEX_DTYPE) +{%- if SCALED %} + scale_a = tl.load( + scale_a_ptr +{%- if A_IS_2D %} + + m_scale_start_offset +{%- else %} + + g * SCALE_A_STRIDE_G +{%- endif %} + + offs_am[:, None], + mask=offs_am[:, None] < m_size, + other=tl.zeros((), dtype=scale_a_ptr.dtype.element_ty), + ) + scale_b = tl.load( + scale_b_ptr +{%- if B_IS_2D %} + + n_scale_start_offset +{%- else %} + + g * SCALE_B_STRIDE_G +{%- endif %} + + offs_bn[None, :], + mask=offs_bn[None, :] < n_size, + other=tl.zeros((), dtype=scale_b_ptr.dtype.element_ty), + ) + c = accumulator.to(tl.float32) * scale_a * scale_b +{%- else %} + c = accumulator.to(tl.float32) +{%- endif %} + +{%- if M_IS_VARYING %} + idx_m = (m_start_offset + offs_am[:, None]) +{%- else %} + idx_m = offs_am[:, None] +{%- endif %} +{%- if N_IS_VARYING %} + idx_n = (n_start_offset + offs_bn[None, :]) +{%- else %} + idx_n = offs_bn[None, :] +{%- endif %} + mask = (offs_am[:, None] < m_size) & (offs_bn[None, :] < n_size) +{%- if M_IS_VARYING or N_IS_VARYING %} + {{store_output(("idx_m", "idx_n"), "c", "mask", indent_width=16, val_shape=("BLOCK_M", "BLOCK_N"))}} +{%- else %} + {{store_output(("g", "idx_m", "idx_n"), "c", "mask", indent_width=16, val_shape=("BLOCK_M", "BLOCK_N"))}} +{%- endif %} + tidx += NUM_SMS + + iterated_tiles += num_tiles diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_mm_rocm.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_mm_rocm.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..6ad00438cf66d428148a8a6c6c912aaaadde0291 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_mm_rocm.py.jinja @@ -0,0 +1,71 @@ +{{def_kernel("A", "B")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + + # based on triton.ops.matmul + pid = tl.program_id(0).to(INDEX_DTYPE) + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + tl.assume(pid_m >= 0) + tl.assume(pid_n >= 0) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M).to(INDEX_DTYPE) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N).to(INDEX_DTYPE) + if (stride_am == 1 and stride_ak == M) or (stride_am == K and stride_ak == 1): + offs_a_m = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + else: + offs_a_m = rm % M + if (stride_bk == 1 and stride_bn == K) or (stride_bk == N and stride_bn == 1): + offs_b_n = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + else: + offs_b_n = rn % N + offs_k = tl.arange(0, BLOCK_K).to(INDEX_DTYPE) + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + + for k_idx in range(0, tl.cdiv(K, BLOCK_K)): + {% if not EVEN_K %} + a_mask = offs_k[None, :] < (K - k_idx * BLOCK_K) + b_mask = offs_k[:, None] < (K - k_idx * BLOCK_K) + {% endif %} + a_k_idx_vals = offs_k[None, :] + (k_idx * BLOCK_K) + b_k_idx_vals = offs_k[:, None] + (k_idx * BLOCK_K) + + idx_m = offs_a_m[:, None] + idx_n = a_k_idx_vals + {{load_input("A", "a", ("idx_m", "idx_n"), mask=None if EVEN_K else "a_mask", + indent_width=8, index_shape=("BLOCK_M", "BLOCK_K"))}} + + idx_m = b_k_idx_vals + idx_n = offs_b_n[None, :] + {{load_input("B", "b", ("idx_m", "idx_n"), mask=None if EVEN_K else "b_mask", + indent_width=8, index_shape=("BLOCK_K", "BLOCK_N"))}} + {% if USE_FAST_ACCUM %} + acc = tl.dot(a, b, acc, allow_tf32=ALLOW_TF32, out_dtype=ACC_TYPE) + {% else %} + acc += tl.dot(a, b, allow_tf32=ALLOW_TF32, out_dtype=ACC_TYPE) + {% endif %} + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M).to(INDEX_DTYPE) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N).to(INDEX_DTYPE) + idx_m = rm[:, None] + idx_n = rn[None, :] + mask = (idx_m < M) & (idx_n < N) + + # inductor generates a suffix + {{store_output(("idx_m", "idx_n"), "acc", "mask", val_shape=("BLOCK_M", "BLOCK_N"))}} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_persistent_mm.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_persistent_mm.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..7450533be5adfa97632e4ccf3ef0ca966cbfef49 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_persistent_mm.py.jinja @@ -0,0 +1,75 @@ +{{def_kernel("A", "B")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + if M * N == 0: + # early exit due to zero-size input(s) + return + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + + # persistent kernel: each CTA processes multiple tiles + start_pid = tl.program_id(0).to(INDEX_DTYPE) + grid_m = tl.cdiv(M, BLOCK_M) + grid_n = tl.cdiv(N, BLOCK_N) + num_tiles = grid_m * grid_n + width = GROUP_M * grid_n + + for tile_id in tl.range(start_pid, num_tiles, NUM_SMS): + + # re-order program ID for better L2 performance + group_id = tile_id // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (tile_id % group_size) + pid_n = (tile_id % width) // (group_size) + tl.assume(pid_m >= 0) + tl.assume(pid_n >= 0) + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + if ((stride_am == 1 and stride_ak == M) or (stride_am == K and stride_ak == 1)) and (M >= BLOCK_M and K > 1): + offs_a_m = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + else: + offs_a_m = rm % M + if ((stride_bk == 1 and stride_bn == K) or (stride_bk == N and stride_bn == 1)) and (N >= BLOCK_N and K > 1): + offs_b_n = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + else: + offs_b_n = rn % N + offs_k = tl.arange(0, BLOCK_K) + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + + for k_idx in range(0, tl.cdiv(K, BLOCK_K)): + {% if not EVEN_K %} + a_mask = offs_k[None, :] < (K - k_idx * BLOCK_K) + b_mask = offs_k[:, None] < (K - k_idx * BLOCK_K) + {% endif %} + a_k_idx_vals = offs_k[None, :] + (k_idx * BLOCK_K) + b_k_idx_vals = offs_k[:, None] + (k_idx * BLOCK_K) + + idx_m = offs_a_m[:, None] + idx_n = a_k_idx_vals + {{load_input("A", "a", ("idx_m", "idx_n"), mask=None if EVEN_K else "a_mask", + indent_width=12, index_shape=("BLOCK_M", "BLOCK_K"))}} + + idx_m = b_k_idx_vals + idx_n = offs_b_n[None, :] + {{load_input("B", "b", ("idx_m", "idx_n"), mask=None if EVEN_K else "b_mask", + indent_width=12, index_shape=("BLOCK_K", "BLOCK_N"))}} + + {% if USE_FAST_ACCUM %} + acc = tl.dot(a, b, acc, allow_tf32=ALLOW_TF32, out_dtype=ACC_TYPE) + {% else %} + acc += tl.dot(a, b, allow_tf32=ALLOW_TF32, out_dtype=ACC_TYPE) + {% endif %} + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + idx_m = rm[:, None] + idx_n = rn[None, :] + mask = (idx_m < M) & (idx_n < N) + + # inductor generates a suffix + {{store_output(("idx_m", "idx_n"), "acc", "mask", indent_width=8, val_shape=("BLOCK_M", "BLOCK_N"))}} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_persistent_tma_mm.py.jinja b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_persistent_tma_mm.py.jinja new file mode 100644 index 0000000000000000000000000000000000000000..cb6b4a14408126350f76415ded20265ba4dc808f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/templates/triton_persistent_tma_mm.py.jinja @@ -0,0 +1,127 @@ +{{def_kernel("A", "B")}} + M = {{size("A", 0)}} + N = {{size("B", 1)}} + K = {{size("A", 1)}} + + if (M == 0) or (N == 0): + # early exit due to zero-size input(s) + return + + start_pid = tl.program_id(0).to(INDEX_DTYPE) + grid_m = tl.cdiv(M, BLOCK_M) + grid_n = tl.cdiv(N, BLOCK_N) + num_tiles = grid_m * grid_n + width = GROUP_M * grid_n + + {%- if TMA_EXPERIMENTAL_API %} + workspace_base = ws_ptr + start_pid * 2 * TMA_SIZE + a_desc_ptr = workspace_base + b_desc_ptr = workspace_base + TMA_SIZE + + triton.language.extra.cuda.experimental_device_tensormap_create2d( + desc_ptr=a_desc_ptr, + global_address=A, + load_size=[BLOCK_M, BLOCK_K] if A_ROW_MAJOR else [BLOCK_K, BLOCK_M], + global_size=[M, K] if A_ROW_MAJOR else [K, M], + element_ty=A.dtype.element_ty, + ) + triton.language.extra.cuda.experimental_device_tensormap_create2d( + desc_ptr=b_desc_ptr, + global_address=B, + load_size=[BLOCK_K, BLOCK_N] if B_ROW_MAJOR else [BLOCK_N, BLOCK_K], + global_size=[K, N] if B_ROW_MAJOR else [N, K], + element_ty=B.dtype.element_ty, + ) + + tl.extra.cuda.experimental_tensormap_fenceproxy_acquire(a_desc_ptr) + tl.extra.cuda.experimental_tensormap_fenceproxy_acquire(b_desc_ptr) + + {%- else %} + stride_am = {{stride("A", 0)}} + stride_ak = {{stride("A", 1)}} + stride_bk = {{stride("B", 0)}} + stride_bn = {{stride("B", 1)}} + + a_desc = triton.language.make_tensor_descriptor( + base=A, + shape=[M, K] if A_ROW_MAJOR else [K, M], + strides=[stride_am, 1] if A_ROW_MAJOR else [stride_ak, 1], + block_shape=[BLOCK_M, BLOCK_K] if A_ROW_MAJOR else [BLOCK_K, BLOCK_M], + ) + b_desc = triton.language.make_tensor_descriptor( + base=B, + shape=[K, N] if B_ROW_MAJOR else [N, K], + strides=[stride_bk, 1] if B_ROW_MAJOR else [stride_bn, 1], + block_shape=[BLOCK_K, BLOCK_N] if B_ROW_MAJOR else [BLOCK_N, BLOCK_K], + ) + {%- endif %} + + for tile_id in tl.range(start_pid, num_tiles, NUM_SMS): + + # re-order program ID for better L2 performance + group_id = tile_id // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (tile_id % group_size) + pid_n = (tile_id % width) // (group_size) + + rm = pid_m * BLOCK_M + rn = pid_n * BLOCK_N + rm_desc = rm.to(tl.int32) + rn_desc = rn.to(tl.int32) + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + + for rk in tl.range(0, K, BLOCK_K): + rk_desc = rk.to(tl.int32) + + {%- if TMA_EXPERIMENTAL_API %} + a = tl._experimental_descriptor_load( + a_desc_ptr, + [rm_desc, rk_desc] if A_ROW_MAJOR else [rk_desc, rm_desc], + [BLOCK_M, BLOCK_K] if A_ROW_MAJOR else [BLOCK_K, BLOCK_M], + A.dtype.element_ty, + ) + b = tl._experimental_descriptor_load( + b_desc_ptr, + [rk_desc, rn_desc] if B_ROW_MAJOR else [rn_desc, rk_desc], + [BLOCK_K, BLOCK_N] if B_ROW_MAJOR else [BLOCK_N, BLOCK_K], + B.dtype.element_ty, + ) + {%- else %} + a = tl.load_tensor_descriptor( + a_desc, + [rm_desc, rk_desc] if A_ROW_MAJOR else [rk_desc, rm_desc], + ) + b = tl.load_tensor_descriptor( + b_desc, + [rk_desc, rn_desc] if B_ROW_MAJOR else [rn_desc, rk_desc], + ) + {%- endif %} + if USE_FAST_ACCUM: + acc = tl.dot( + a if A_ROW_MAJOR else a.T, + b if B_ROW_MAJOR else b.T, + acc, + allow_tf32=ALLOW_TF32, + ) + else: + acc += tl.dot( + a if A_ROW_MAJOR else a.T, + b if B_ROW_MAJOR else b.T, + allow_tf32=ALLOW_TF32, + ) + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + rn = pid_n * BLOCK_N + + # inductor generates a suffix + {%- if TMA_EXPERIMENTAL_API %} + rcm = rm + tl.arange(0, BLOCK_M) + rcn = rn + tl.arange(0, BLOCK_N) + idx_m = rcm[:, None] + idx_n = rcn[None, :] + mask = (idx_m < M) & (idx_n < N) + {{store_output(("idx_m", "idx_n"), "acc", "mask", indent_width=8, val_shape=("BLOCK_M", "BLOCK_N"))}} + {%- else %} + {{store_output(("rm", "rn"), "acc", indent_width=8, val_shape=("BLOCK_M", "BLOCK_N"), block_indexing=True)}} + {%- endif %} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a867cba9152f60dc10a44194242298129d52343 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7dc51ed6f633ef7b4329b51d80c5dd4a1caa52c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__init__.py @@ -0,0 +1 @@ +# CuTeDSL vendored kernels and wrappers for PyTorch Inductor. diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e438a5493f6ad9685c8efdf0c5baff336230c16b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/dense_blockscaled_gemm_persistent.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/dense_blockscaled_gemm_persistent.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97746398640cfcec3b353712d8958c4726d62404 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/dense_blockscaled_gemm_persistent.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/dense_gemm_efc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/dense_gemm_efc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c44be20530cba63429070353806523a0ae99911 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/dense_gemm_efc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/reduction_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/reduction_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..571583e595ed5476e7bb83e2ab8e5fd1e8deddf1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/reduction_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/dense_blockscaled_gemm_persistent.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/dense_blockscaled_gemm_persistent.py new file mode 100644 index 0000000000000000000000000000000000000000..49e9565f8cd569e04dd43d6c5ac20b60b7401c46 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/dense_blockscaled_gemm_persistent.py @@ -0,0 +1,2729 @@ +# Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: BSD-3-Clause +# ruff: noqa: S101 + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import argparse +from typing import Tuple, Type, Union + +import cuda.bindings.driver as cuda + +import cutlass +import cutlass.cute as cute +import cutlass.pipeline as pipeline +import cutlass.torch as cutlass_torch +import cutlass.utils as utils +import cutlass.utils.blackwell_helpers as sm100_utils +import cutlass.utils.blockscaled_layout as blockscaled_utils +from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.cute.runtime import from_dlpack +from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait + +import torch +from torch._inductor.kernel.vendored_templates.cutedsl.reduction_utils import ( + get_lane_warp_layouts, + partition_for_epilogue, +) + + +""" +This example provides an experimental implementation of the SM100 batched dense blockscaled GEMM kernel, please note that the APIs and implementation details related to this kernel may change in future releases. + +A high-performance persistent batched dense blockscaled GEMM example for the NVIDIA Blackwell SM100 architecture +using CUTE DSL. +- Matrix A is MxKxL, L is batch dimension, A can be row-major("K") or column-major("M") for MXF8 input type and can only be row-major("K") for MXF4/NVF4 input type +- Matrix B is NxKxL, L is batch dimension, B can be row-major("N") or column-major("K") for MXF8 input type and can only be row-major("K") for MXF4/NVF4 input type +- Matrix C is MxNxL, L is batch dimension, C can be row-major("N") or column-major("M") +- Matrix SFA layout is filled internally according to A shape and BlockScaledBasicChunk, which has M×ceil_div(K, sf_vec_size)×L elements respectively +- Matrix SFB layout is filled internally according to B shape and BlockScaledBasicChunk, which has N×ceil_div(K, sf_vec_size)×L elements respectively + +This GEMM kernel supports the following features: + - Utilizes Tensor Memory Access (TMA) for efficient memory operations + - Utilizes Blackwell's tcgen05.mma for matrix multiply-accumulate (MMA) operations (including 2cta mma instructions) + - Implements TMA multicast with cluster to reduce L2 memory traffic + - Support persistent tile scheduling to better overlap memory load/store with mma between tiles + - Support warp specialization to avoid explicit pipelining between mainloop load and mma + +This GEMM works as follows: +1. DMA warp: Load A and B matrices from global memory (GMEM) to shared memory (SMEM) using TMA operations. +2. MMA warp: + - Load scale factor A/B from shared memory (SMEM) to tensor memory (TMEM) using tcgen05.cp instruction. + - Perform matrix multiply-accumulate (MMA) operations using tcgen05.mma instruction. +3. EPILOGUE warp: + - Load completed accumulator from tensor memory (TMEM) to registers (RMEM) using tcgen05.ld. + - Type convert C matrix to output type. + - Optionally store C matrix from registers (RMEM) to shared memory (SMEM) to global memory (GMEM) with TMA operations, + or directly store C matrix from registers (RMEM) to global memory (GMEM) without TMA operations. + - Optionally accept an elementwise lambda function epilogue_op to apply to the output tensor: + e.g., relu can set epilogue_op = lambda x: cute.where(x > 0, x, cute.full_like(x, 0)) + +SM100 tcgen05.mma.kind.block_scale instructions operate as follows: +- Read matrix A from SMEM +- Read matrix B from SMEM +- Read scalefactor A from TMEM +- Read scalefactor B from TMEM +- Write accumulator to TMEM +The accumulator in TMEM must then be loaded to registers before writing back to GMEM. + +Input arguments to this example is shown below: + +.. code-block:: bash + + python examples/blackwell/dense_blockscaled_gemm_persistent.py \ + --ab_dtype Float4E2M1FN --sf_dtype Float8E8M0FNU --sf_vec_size 16 \ + --c_dtype Float16 \ + --mma_tiler_mn 256,128 --cluster_shape_mn 2,1 \ + --mnkl 8192,8192,1024,1 + +To collect performance with NCU profiler: + +.. code-block:: bash + + ncu python examples/blackwell/dense_blockscaled_gemm_persistent.py \ + --ab_dtype Float4E2M1FN --sf_dtype Float8E8M0FNU --sf_vec_size 16 \ + --c_dtype Float16 \ + --mma_tiler_mn 256,128 --cluster_shape_mn 2,1 \ + --mnkl 8192,8192,1024,1 \ + --warmup_iterations 1 --iterations 10 --skip_ref_check + + +Constraints: +* Supported input data types: mxf8, mxf4, nvf4 + see detailed valid dtype combinations in below Sm100BlockScaledPersistentDenseGemmKernel class documentation +* A/B tensor must have the same data type, mixed data type is not supported (e.g., mxf8 x mxf4) +* Mma tiler M must be 128 or 256(use_2cta_instrs) +* Mma tiler N must be 64/128/192/256 +* Cluster shape M/N must be positive and power of 2, total cluster size <= 16 +* Cluster shape M must be multiple of 2 if Mma tiler M is 256(use_2cta_instrs) +* The contiguous dimension of A/B/C tensors must be at least 16 bytes aligned, + i.e, number of elements is a multiple of 16 and 32 for Float8 and Float4, respectively. +""" + + +class Sm100BlockScaledPersistentDenseGemmKernel: + """This class implements batched matrix multiplication (C = A x SFA x B x SFB) with support for various data types + and architectural features specific to Blackwell GPUs with persistent tile scheduling and warp specialization. + + :param sf_vec_size: Scalefactor vector size. + :type sf_vec_size: int + :param mma_tiler_mn: Shape of the Matrix Multiply-Accumulate (MMA) tile (M,N) + :type mma_tiler_mn: Tuple[int, int] + :param cluster_shape_mn: Cluster dimensions (M,N) for parallel processing + :type cluster_shape_mn: Tuple[int, int] + + :note: In current version, A and B tensor must have the same data type + - i.e., Float8E4M3FN for A and Float8E5M2 for B is not supported + + :note: Supported combinations of A/B data types, SF data typs and SF vector size: + - MXF8: A/B: Float8E5M2/Float8E4M3FN + SF: Float8E8M0FNU + sf_vec_size: 32 + - MXF4: A/B: Float4E2M1FN + SF: Float8E8M0FNU + sf_vec_size: 32 + - NVF4: A/B: Float4E2M1FN + SF: Float8E8M0FNU/Float8E4M3FN + sf_vec_size: 16 + + :note: Supported accumulator data types: + - Float32 + + :note: Supported C data types: + - Float32 + - Float16/BFloat16 + - Float8E4M3FN/Float8E5M2 + :note: Constraints: + - MMA tiler M must be 128 or 256 (use_2cta_instrs) + - MMA tiler N must be 64/128/192/256 + - Cluster shape M must be multiple of 2 if Mma tiler M is 256 + - Cluster shape M/N must be positive and power of 2, total cluster size <= 16 + - Also, Cluster shape M/N must be <= 4 for scale factor multicasts due to limited size of scale factors + + Example: + >>> # xdoctest: +SKIP(requires cutlass) + >>> gemm = Sm100BlockScaledPersistentDenseGemmKernel( + ... sf_vec_size=16, mma_tiler_mn=(256, 128), cluster_shape_mn=(2, 1) + ... ) + >>> gemm( + ... a_tensor, + ... b_tensor, + ... sfa_tensor, + ... sfb_tensor, + ... c_tensor, + ... max_active_clusters, + ... stream, + ... ) + """ + + def __init__( + self, + sf_vec_size: int, + mma_tiler_mn: Tuple[int, int], + cluster_shape_mn: Tuple[int, int], + use_prefetch: bool = False, + ): + """Initializes the configuration for a Blackwell dense GEMM kernel. + + This configuration includes several key aspects: + + 1. MMA Instruction Settings (tcgen05): + - acc_dtype: Data types for MMA accumulator, always set to Float32 + - sf_vec_size: Scalefactor A/B vector size. + - mma_tiler_mn: The (M, N) shape of the MMA instruction tiler. + + 2. Cluster Shape: + - cluster_shape_mn: The (ClusterM, ClusterN) shape of the CTA cluster. + + :param sf_vec_size: Scalefactor vector size. + :type sf_vec_size: int + :param mma_tiler_mn: Tuple (M, N) shape of the MMA instruction. + :type mma_tiler_mn: Tuple[int, int] + :param cluster_shape_mn: Tuple (ClusterM, ClusterN) shape of the cluster. + :type cluster_shape_mn: Tuple[int, int] + """ + + self.acc_dtype = cutlass.Float32 + self.sf_vec_size = sf_vec_size + self.use_2cta_instrs = mma_tiler_mn[0] == 256 + self.cluster_shape_mn = cluster_shape_mn + # K dimension is deferred in _setup_attributes + self.mma_tiler = (*mma_tiler_mn, 1) + + self.cta_group = ( + tcgen05.CtaGroup.TWO if self.use_2cta_instrs else tcgen05.CtaGroup.ONE + ) + + # TMA-prefetch tactic: prefetch A/B/SF tiles ahead in the K-loop to + # hide latency; helps small-M large-K. + self.use_prefetch = use_prefetch + + self.occupancy = 1 + # Set specialized warp ids + self.epilog_warp_id = ( + 0, + 1, + 2, + 3, + ) + self.mma_warp_id = 4 + self.tma_warp_id = 5 + self.threads_per_cta = 32 * len( + (self.mma_warp_id, self.tma_warp_id, *self.epilog_warp_id) + ) + # Set barrier id for epilogue sync and tmem ptr sync + self.epilog_sync_barrier = pipeline.NamedBarrier( + barrier_id=1, + num_threads=32 * len(self.epilog_warp_id), + ) + self.tmem_alloc_barrier = pipeline.NamedBarrier( + barrier_id=2, + num_threads=32 * len((self.mma_warp_id, *self.epilog_warp_id)), + ) + self.smem_capacity = utils.get_smem_capacity_in_bytes("sm_100") + SM100_TMEM_CAPACITY_COLUMNS = 512 + self.num_tmem_alloc_cols = SM100_TMEM_CAPACITY_COLUMNS + + def _setup_attributes(self): + """Set up configurations that are dependent on GEMM inputs + + This method configures various attributes based on the input tensor properties + (data types, leading dimensions) and kernel settings: + - Configuring tiled MMA + - Computing MMA/cluster/tile shapes + - Computing cluster layout + - Computing multicast CTAs for A/B/SFA/SFB + - Computing epilogue subtile + - Setting up A/B/SFA/SFB/C stage counts in shared memory + - Computing A/B/SFA/SFB/C shared memory layout + """ + # Compute mma instruction shapes + # (MMA_Tile_Shape_M, MMA_Tile_Shape_N, MMA_Inst_Shape_K) + self.mma_inst_shape_mn = ( + self.mma_tiler[0], + self.mma_tiler[1], + ) + # (CTA_Tile_Shape_M, Round_Up(MMA_Tile_Shape_N, 128), MMA_Inst_Shape_K) + self.mma_inst_shape_mn_sfb = ( + self.mma_inst_shape_mn[0] // (2 if self.use_2cta_instrs else 1), + cute.round_up(self.mma_inst_shape_mn[1], 128), + ) + + tiled_mma = sm100_utils.make_blockscaled_trivial_tiled_mma( + self.a_dtype, + self.a_major_mode, + self.b_major_mode, + self.sf_dtype, + self.sf_vec_size, + self.cta_group, + self.mma_inst_shape_mn, + ) + + tiled_mma_sfb = sm100_utils.make_blockscaled_trivial_tiled_mma( + self.a_dtype, + self.a_major_mode, + self.b_major_mode, + self.sf_dtype, + self.sf_vec_size, + cute.nvgpu.tcgen05.CtaGroup.ONE, + self.mma_inst_shape_mn_sfb, + ) + + # Compute mma/cluster/tile shapes + mma_inst_shape_k = cute.size(tiled_mma.shape_mnk, mode=[2]) + mma_inst_tile_k = 4 + self.mma_tiler = ( + self.mma_inst_shape_mn[0], + self.mma_inst_shape_mn[1], + mma_inst_shape_k * mma_inst_tile_k, + ) + self.mma_tiler_sfb = ( + self.mma_inst_shape_mn_sfb[0], + self.mma_inst_shape_mn_sfb[1], + mma_inst_shape_k * mma_inst_tile_k, + ) + self.cta_tile_shape_mnk = ( + self.mma_tiler[0] // cute.size(tiled_mma.thr_id.shape), + self.mma_tiler[1], + self.mma_tiler[2], + ) + self.cta_tile_shape_mnk_sfb = ( + self.mma_tiler_sfb[0] // cute.size(tiled_mma.thr_id.shape), + self.mma_tiler_sfb[1], + self.mma_tiler_sfb[2], + ) + + # Compute cluster layout + self.cluster_layout_vmnk = cute.tiled_divide( + cute.make_layout((*self.cluster_shape_mn, 1)), + (tiled_mma.thr_id.shape,), + ) + self.cluster_layout_sfb_vmnk = cute.tiled_divide( + cute.make_layout((*self.cluster_shape_mn, 1)), + (tiled_mma_sfb.thr_id.shape,), + ) + + # Compute number of multicast CTAs for A/B + self.num_mcast_ctas_a = cute.size(self.cluster_layout_vmnk.shape[2]) + self.num_mcast_ctas_b = cute.size(self.cluster_layout_vmnk.shape[1]) + self.num_mcast_ctas_sfb = cute.size(self.cluster_layout_sfb_vmnk.shape[1]) + self.is_a_mcast = self.num_mcast_ctas_a > 1 + self.is_b_mcast = self.num_mcast_ctas_b > 1 + self.is_sfb_mcast = self.num_mcast_ctas_sfb > 1 + + # Compute epilogue subtile + self.epi_tile = sm100_utils.compute_epilogue_tile_shape( + self.cta_tile_shape_mnk, + self.use_2cta_instrs, + self.c_layout, + self.c_dtype, + ) + self.epi_tile_n = cute.size(self.epi_tile[1]) + + # Setup A/B/C stage count in shared memory and ACC stage count in tensor memory + self.num_acc_stage, self.num_ab_stage, self.num_c_stage = self._compute_stages( + tiled_mma, + self.mma_tiler, + self.a_dtype, + self.b_dtype, + self.epi_tile, + self.c_dtype, + self.c_layout, + self.sf_dtype, + self.sf_vec_size, + self.smem_capacity, + self.occupancy, + ) + + # Prefetch depth = AB pipeline depth. + self.prefetch_dist = self.num_ab_stage + + # Compute A/B/SFA/SFB/C shared memory layout + self.a_smem_layout_staged = sm100_utils.make_smem_layout_a( + tiled_mma, + self.mma_tiler, + self.a_dtype, + self.num_ab_stage, + ) + self.b_smem_layout_staged = sm100_utils.make_smem_layout_b( + tiled_mma, + self.mma_tiler, + self.b_dtype, + self.num_ab_stage, + ) + self.sfa_smem_layout_staged = blockscaled_utils.make_smem_layout_sfa( + tiled_mma, + self.mma_tiler, + self.sf_vec_size, + self.num_ab_stage, + ) + self.sfb_smem_layout_staged = blockscaled_utils.make_smem_layout_sfb( + tiled_mma, + self.mma_tiler, + self.sf_vec_size, + self.num_ab_stage, + ) + self.c_smem_layout_staged = sm100_utils.make_smem_layout_epi( + self.c_dtype, + self.c_layout, + self.epi_tile, + self.num_c_stage, + ) + + # Overlap and double buffer accumulator when num_acc_stage == 1 for cta_tile_n = 256 case + self.overlapping_accum = self.num_acc_stage == 1 + + # Compute number of TMEM columns for SFA/SFB/Accumulator + sf_atom_mn = 32 + self.num_sfa_tmem_cols = ( + self.cta_tile_shape_mnk[0] // sf_atom_mn + ) * mma_inst_tile_k + self.num_sfb_tmem_cols = ( + self.cta_tile_shape_mnk_sfb[1] // sf_atom_mn + ) * mma_inst_tile_k + self.num_sf_tmem_cols = self.num_sfa_tmem_cols + self.num_sfb_tmem_cols + self.num_accumulator_tmem_cols = ( + self.cta_tile_shape_mnk[1] * self.num_acc_stage + if not self.overlapping_accum + else self.cta_tile_shape_mnk[1] * 2 - self.num_sf_tmem_cols + ) + + # Only when overlapping_accum is enabled, we need to release accumulator buffer early in epilogue + self.iter_acc_early_release_in_epilogue = ( + self.num_sf_tmem_cols // self.epi_tile_n + ) + + @cute.jit + def __call__( + self, + a_tensor: cute.Tensor, + b_tensor: cute.Tensor, + sfa_tensor: cute.Tensor, + sfb_tensor: cute.Tensor, + c_tensor: cute.Tensor, + max_active_clusters: cutlass.Constexpr, + stream: cuda.CUstream, + epilogue_op: cutlass.Constexpr = lambda x: x, + epilogue_input_dtype: cutlass.Constexpr = cutlass.Float32, + alpha_tensor: cute.Tensor = None, + epilogue_tensor0: cute.Tensor = None, + epilogue_tensor1: cute.Tensor = None, + epilogue_tensor2: cute.Tensor = None, + epilogue_tensor3: cute.Tensor = None, + epilogue_tensor_kind0: cutlass.Constexpr = 0, + epilogue_tensor_kind1: cutlass.Constexpr = 0, + epilogue_tensor_kind2: cutlass.Constexpr = 0, + epilogue_tensor_kind3: cutlass.Constexpr = 0, + epilogue_output0: cute.Tensor = None, + epilogue_output1: cute.Tensor = None, + epilogue_output2: cute.Tensor = None, + epilogue_output_count: cutlass.Constexpr = 1, + primary_epilogue_output: cutlass.Constexpr = 0, + local_reduce_tensor: cute.Tensor = None, + local_reduce_group: cutlass.Constexpr = 0, + local_reduce_axis: cutlass.Constexpr = 1, + local_reduce_type: cutlass.Constexpr = "sum", + local_reduce_source: cutlass.Constexpr = "identity", + local_reduce_feeds_main: cutlass.Constexpr = False, + ): + """Execute the GEMM operation in steps: + - Setup static attributes before smem/grid/tma computation + - Setup TMA load/store atoms and tensors + - Compute grid size with regard to hardware constraints + - Define shared storage for kernel + - Launch the kernel synchronously + + :param a_tensor: Input tensor A + :type a_tensor: cute.Tensor + :param b_tensor: Input tensor B + :type b_tensor: cute.Tensor + :param sfa_tensor: Scale factor tensor A + :type sfa_tensor: cute.Tensor + :param sfb_tensor: Scale factor tensor B + :type sfb_tensor: cute.Tensor + :param c_tensor: Output tensor C + :type c_tensor: cute.Tensor + :param max_active_clusters: Maximum number of active clusters + :type max_active_clusters: cutlass.Constexpr + :param stream: CUDA stream for asynchronous execution + :type stream: cuda.CUstream + :param epilogue_op: Optional elementwise lambda function to apply to the output tensor + :type epilogue_op: cutlass.Constexpr + :raises TypeError: If input data types are incompatible with the MMA instruction. + """ + + # Convert from torch convention to CuTe convention. + # CUTLASS API passes tensors as A:(L,M,K) B:(L,K,N) C:(L,M,N) + # but CuTe DSL kernels expect A:(M,K,L) B:(N,K,L) C:(M,N,L). + def add_batch_mode(tensor: cute.Tensor) -> cute.Tensor: + return cute.make_tensor( + tensor.iterator, + cute.prepend(tensor.layout, cute.make_layout(1), up_to_rank=3), + ) + + a_tensor = add_batch_mode(a_tensor) + b_tensor = add_batch_mode(b_tensor) + c_tensor = add_batch_mode(c_tensor) + if cutlass.const_expr(local_reduce_tensor is not None): + local_reduce_tensor = add_batch_mode(local_reduce_tensor) + + self.local_reduce_group = local_reduce_group + self.local_reduce_axis = local_reduce_axis + self.local_reduce_type = local_reduce_type + self.local_reduce_source = local_reduce_source + self.local_reduce_feeds_main = local_reduce_feeds_main + self.has_cross_warp_local_reduce = cutlass.const_expr( + local_reduce_tensor is not None + and local_reduce_axis == 0 + and local_reduce_group > 4 + ) + + a_tensor = cute.make_tensor( + a_tensor.iterator, cute.select(a_tensor.layout, [1, 2, 0]) + ) + b_tensor = cute.make_tensor( + b_tensor.iterator, cute.select(b_tensor.layout, [2, 1, 0]) + ) + c_tensor = cute.make_tensor( + c_tensor.iterator, cute.select(c_tensor.layout, [1, 2, 0]) + ) + + def epilogue_tensor_to_mnl(tensor: cute.Tensor) -> cute.Tensor: + tensor = add_batch_mode(tensor) + return cute.make_tensor( + tensor.iterator, cute.select(tensor.layout, [1, 2, 0]) + ) + + if cutlass.const_expr(epilogue_tensor0 is not None): + epilogue_tensor0 = epilogue_tensor_to_mnl(epilogue_tensor0) + if cutlass.const_expr(epilogue_tensor1 is not None): + epilogue_tensor1 = epilogue_tensor_to_mnl(epilogue_tensor1) + if cutlass.const_expr(epilogue_tensor2 is not None): + epilogue_tensor2 = epilogue_tensor_to_mnl(epilogue_tensor2) + if cutlass.const_expr(epilogue_tensor3 is not None): + epilogue_tensor3 = epilogue_tensor_to_mnl(epilogue_tensor3) + if cutlass.const_expr(epilogue_output0 is not None): + epilogue_output0 = epilogue_tensor_to_mnl(epilogue_output0) + if cutlass.const_expr(epilogue_output1 is not None): + epilogue_output1 = epilogue_tensor_to_mnl(epilogue_output1) + if cutlass.const_expr(epilogue_output2 is not None): + epilogue_output2 = epilogue_tensor_to_mnl(epilogue_output2) + + self.epilogue_output_count = epilogue_output_count + self.primary_epilogue_output = primary_epilogue_output + + # Setup static attributes before smem/grid/tma computation + self.a_dtype: Type[cutlass.Numeric] = a_tensor.element_type + self.b_dtype: Type[cutlass.Numeric] = b_tensor.element_type + self.sf_dtype: Type[cutlass.Numeric] = sfa_tensor.element_type + self.c_dtype: Type[cutlass.Numeric] = c_tensor.element_type + self.a_major_mode = utils.LayoutEnum.from_tensor(a_tensor).mma_major_mode() + self.b_major_mode = utils.LayoutEnum.from_tensor(b_tensor).mma_major_mode() + self.c_layout = utils.LayoutEnum.from_tensor(c_tensor) + + # Check if input data types are compatible with MMA instruction + if cutlass.const_expr(self.a_dtype != self.b_dtype): + raise TypeError(f"Type must match: {self.a_dtype} != {self.b_dtype}") + + # Setup attributes that dependent on gemm inputs + self._setup_attributes() + + # Setup sfa/sfb tensor by filling A/B tensor to scale factor atom layout + # ((Atom_M, Rest_M),(Atom_K, Rest_K),RestL) + sfa_layout = blockscaled_utils.tile_atom_to_shape_SF( + a_tensor.shape, self.sf_vec_size + ) + sfa_tensor = cute.make_tensor(sfa_tensor.iterator, sfa_layout) + + # ((Atom_N, Rest_N),(Atom_K, Rest_K),RestL) + sfb_layout = blockscaled_utils.tile_atom_to_shape_SF( + b_tensor.shape, self.sf_vec_size + ) + sfb_tensor = cute.make_tensor(sfb_tensor.iterator, sfb_layout) + + tiled_mma = sm100_utils.make_blockscaled_trivial_tiled_mma( + self.a_dtype, + self.a_major_mode, + self.b_major_mode, + self.sf_dtype, + self.sf_vec_size, + self.cta_group, + self.mma_inst_shape_mn, + ) + + tiled_mma_sfb = sm100_utils.make_blockscaled_trivial_tiled_mma( + self.a_dtype, + self.a_major_mode, + self.b_major_mode, + self.sf_dtype, + self.sf_vec_size, + cute.nvgpu.tcgen05.CtaGroup.ONE, + self.mma_inst_shape_mn_sfb, + ) + atom_thr_size = cute.size(tiled_mma.thr_id.shape) + + # Setup TMA load for A + a_op = sm100_utils.cluster_shape_to_tma_atom_A( + self.cluster_shape_mn, tiled_mma.thr_id + ) + a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0)) + tma_atom_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A( + a_op, + a_tensor, + a_smem_layout, + self.mma_tiler, + tiled_mma, + self.cluster_layout_vmnk.shape, + ) + + # Setup TMA load for B + b_op = sm100_utils.cluster_shape_to_tma_atom_B( + self.cluster_shape_mn, tiled_mma.thr_id + ) + b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0)) + tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B( + b_op, + b_tensor, + b_smem_layout, + self.mma_tiler, + tiled_mma, + self.cluster_layout_vmnk.shape, + ) + + # Setup TMA load for SFA + sfa_op = sm100_utils.cluster_shape_to_tma_atom_A( + self.cluster_shape_mn, tiled_mma.thr_id + ) + sfa_smem_layout = cute.slice_( + self.sfa_smem_layout_staged, (None, None, None, 0) + ) + tma_atom_sfa, tma_tensor_sfa = cute.nvgpu.make_tiled_tma_atom_A( + sfa_op, + sfa_tensor, + sfa_smem_layout, + self.mma_tiler, + tiled_mma, + self.cluster_layout_vmnk.shape, + internal_type=cutlass.Int16, + ) + + # Setup TMA load for SFB + sfb_op = sm100_utils.cluster_shape_to_tma_atom_SFB( + self.cluster_shape_mn, tiled_mma.thr_id + ) + sfb_smem_layout = cute.slice_( + self.sfb_smem_layout_staged, (None, None, None, 0) + ) + tma_atom_sfb, tma_tensor_sfb = cute.nvgpu.make_tiled_tma_atom_B( + sfb_op, + sfb_tensor, + sfb_smem_layout, + self.mma_tiler_sfb, + tiled_mma_sfb, + self.cluster_layout_sfb_vmnk.shape, + internal_type=cutlass.Int16, + ) + + if cutlass.const_expr(self.cta_tile_shape_mnk[1] == 192): + x = tma_tensor_sfb.stride[0][1] + y = cute.ceil_div(tma_tensor_sfb.shape[0][1], 4) + + new_shape = ( + (tma_tensor_sfb.shape[0][0], ((2, 2), y)), + tma_tensor_sfb.shape[1], + tma_tensor_sfb.shape[2], + ) + # Use right multiplication for ScaledBasis (3 * x instead of x * 3) + x_times_3 = 3 * x + new_stride = ( + (tma_tensor_sfb.stride[0][0], ((x, x), x_times_3)), + tma_tensor_sfb.stride[1], + tma_tensor_sfb.stride[2], + ) + tma_tensor_sfb_new_layout = cute.make_layout(new_shape, stride=new_stride) + tma_tensor_sfb = cute.make_tensor( + tma_tensor_sfb.iterator, tma_tensor_sfb_new_layout + ) + + a_copy_size = cute.size_in_bytes(self.a_dtype, a_smem_layout) + b_copy_size = cute.size_in_bytes(self.b_dtype, b_smem_layout) + sfa_copy_size = cute.size_in_bytes(self.sf_dtype, sfa_smem_layout) + sfb_copy_size = cute.size_in_bytes(self.sf_dtype, sfb_smem_layout) + self.num_tma_load_bytes = ( + a_copy_size + b_copy_size + sfa_copy_size + sfb_copy_size + ) * atom_thr_size + + # Setup TMA store for C + epi_smem_layout = cute.slice_(self.c_smem_layout_staged, (None, None, 0)) + tma_atom_c, tma_tensor_c = cpasync.make_tiled_tma_atom( + cpasync.CopyBulkTensorTileS2GOp(), + c_tensor, + epi_smem_layout, + self.epi_tile, + ) + + # Compute grid size + self.tile_sched_params, grid = self._compute_grid( + c_tensor, + self.cta_tile_shape_mnk, + self.cluster_shape_mn, + max_active_clusters, + ) + + self.buffer_align_bytes = 1024 + + # Define shared storage for kernel + @cute.struct + class SharedStorage: + ab_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage] + ab_empty_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage] + acc_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage] + acc_empty_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage] + tmem_dealloc_mbar_ptr: cutlass.Int64 + tmem_holding_buf: cutlass.Int32 + # (EPI_TILE_M, EPI_TILE_N, STAGE) + sC: cute.struct.Align[ + cute.struct.MemRange[ + self.c_dtype, + cute.cosize(self.c_smem_layout_staged.outer), + ], + self.buffer_align_bytes, + ] + # (MMA, MMA_M, MMA_K, STAGE) + sA: cute.struct.Align[ + cute.struct.MemRange[ + self.a_dtype, cute.cosize(self.a_smem_layout_staged.outer) + ], + self.buffer_align_bytes, + ] + # (MMA, MMA_N, MMA_K, STAGE) + sB: cute.struct.Align[ + cute.struct.MemRange[ + self.b_dtype, cute.cosize(self.b_smem_layout_staged.outer) + ], + self.buffer_align_bytes, + ] + # (MMA, MMA_M, MMA_K, STAGE) + sSFA: cute.struct.Align[ + cute.struct.MemRange[ + self.sf_dtype, cute.cosize(self.sfa_smem_layout_staged) + ], + self.buffer_align_bytes, + ] + # (MMA, MMA_N, MMA_K, STAGE) + sSFB: cute.struct.Align[ + cute.struct.MemRange[ + self.sf_dtype, cute.cosize(self.sfb_smem_layout_staged) + ], + self.buffer_align_bytes, + ] + sLocalReduce: cute.struct.Align[ + cute.struct.MemRange[ + cutlass.Float32, + self.cta_tile_shape_mnk[1] * 3 + if self.has_cross_warp_local_reduce + else 1, + ], + 16, + ] + + self.shared_storage = SharedStorage + + # Launch the kernel synchronously + self.kernel( + tiled_mma, + tiled_mma_sfb, + tma_atom_a, + tma_tensor_a, + tma_atom_b, + tma_tensor_b, + tma_atom_sfa, + tma_tensor_sfa, + tma_atom_sfb, + tma_tensor_sfb, + tma_atom_c, + tma_tensor_c, + self.cluster_layout_vmnk, + self.cluster_layout_sfb_vmnk, + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.sfa_smem_layout_staged, + self.sfb_smem_layout_staged, + self.c_smem_layout_staged, + self.epi_tile, + self.tile_sched_params, + epilogue_op, + epilogue_input_dtype, + alpha_tensor, + epilogue_tensor0, + epilogue_tensor1, + epilogue_tensor2, + epilogue_tensor3, + epilogue_tensor_kind0, + epilogue_tensor_kind1, + epilogue_tensor_kind2, + epilogue_tensor_kind3, + epilogue_output0, + epilogue_output1, + epilogue_output2, + local_reduce_tensor, + ).launch( + grid=grid, + block=[self.threads_per_cta, 1, 1], + cluster=(*self.cluster_shape_mn, 1), + stream=stream, + min_blocks_per_mp=1, + ) + return + + # GPU device kernel + @cute.kernel + def kernel( + self, + tiled_mma: cute.TiledMma, + tiled_mma_sfb: cute.TiledMma, + tma_atom_a: cute.CopyAtom, + mA_mkl: cute.Tensor, + tma_atom_b: cute.CopyAtom, + mB_nkl: cute.Tensor, + tma_atom_sfa: cute.CopyAtom, + mSFA_mkl: cute.Tensor, + tma_atom_sfb: cute.CopyAtom, + mSFB_nkl: cute.Tensor, + tma_atom_c: cute.CopyAtom, + mC_mnl: cute.Tensor, + cluster_layout_vmnk: cute.Layout, + cluster_layout_sfb_vmnk: cute.Layout, + a_smem_layout_staged: cute.ComposedLayout, + b_smem_layout_staged: cute.ComposedLayout, + sfa_smem_layout_staged: cute.Layout, + sfb_smem_layout_staged: cute.Layout, + c_smem_layout_staged: Union[cute.Layout, cute.ComposedLayout], + epi_tile: cute.Tile, + tile_sched_params: utils.PersistentTileSchedulerParams, + epilogue_op: cutlass.Constexpr, + epilogue_input_dtype: cutlass.Constexpr, + alpha_tensor: cute.Tensor, + epilogue_tensor0: cute.Tensor, + epilogue_tensor1: cute.Tensor, + epilogue_tensor2: cute.Tensor, + epilogue_tensor3: cute.Tensor, + epilogue_tensor_kind0: cutlass.Constexpr, + epilogue_tensor_kind1: cutlass.Constexpr, + epilogue_tensor_kind2: cutlass.Constexpr, + epilogue_tensor_kind3: cutlass.Constexpr, + epilogue_output0: cute.Tensor, + epilogue_output1: cute.Tensor, + epilogue_output2: cute.Tensor, + local_reduce_tensor: cute.Tensor, + ): + """ + GPU device kernel performing the Persistent batched GEMM computation. + """ + warp_idx = cute.arch.warp_idx() + warp_idx = cute.arch.make_warp_uniform(warp_idx) + + # + # Prefetch tma desc + # + if warp_idx == self.tma_warp_id: + cpasync.prefetch_descriptor(tma_atom_a) + cpasync.prefetch_descriptor(tma_atom_b) + cpasync.prefetch_descriptor(tma_atom_sfa) + cpasync.prefetch_descriptor(tma_atom_sfb) + cpasync.prefetch_descriptor(tma_atom_c) + + use_2cta_instrs = cute.size(tiled_mma.thr_id.shape) == 2 + + # + # Setup cta/thread coordinates + # + # Coords inside cluster + bidx, bidy, bidz = cute.arch.block_idx() + mma_tile_coord_v = bidx % cute.size(tiled_mma.thr_id.shape) + is_leader_cta = mma_tile_coord_v == 0 + cta_rank_in_cluster = cute.arch.make_warp_uniform( + cute.arch.block_idx_in_cluster() + ) + block_in_cluster_coord_vmnk = cluster_layout_vmnk.get_flat_coord( + cta_rank_in_cluster + ) + block_in_cluster_coord_sfb_vmnk = cluster_layout_sfb_vmnk.get_flat_coord( + cta_rank_in_cluster + ) + # Coord inside cta + tidx, _, _ = cute.arch.thread_idx() + + # + # Alloc and init: a+b full/empty, accumulator full/empty, tensor memory dealloc barrier + # + smem = utils.SmemAllocator() + storage = smem.allocate(self.shared_storage) + sLocalReduce = storage.sLocalReduce.get_tensor( + cute.make_layout((self.cta_tile_shape_mnk[1], 3)) + if self.has_cross_warp_local_reduce + else cute.make_layout(1) + ) + + # Initialize mainloop ab_pipeline (barrier) and states + ab_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + num_tma_producer = self.num_mcast_ctas_a + self.num_mcast_ctas_b - 1 + ab_pipeline_consumer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, num_tma_producer + ) + ab_pipeline = pipeline.PipelineTmaUmma.create( + barrier_storage=storage.ab_full_mbar_ptr.data_ptr(), + num_stages=self.num_ab_stage, + producer_group=ab_pipeline_producer_group, + consumer_group=ab_pipeline_consumer_group, + tx_count=self.num_tma_load_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + + # Initialize acc_pipeline (barrier) and states + acc_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + num_acc_consumer_threads = len(self.epilog_warp_id) * ( + 2 if use_2cta_instrs else 1 + ) + acc_pipeline_consumer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, num_acc_consumer_threads + ) + acc_pipeline = pipeline.PipelineUmmaAsync.create( + barrier_storage=storage.acc_full_mbar_ptr.data_ptr(), + num_stages=self.num_acc_stage, + producer_group=acc_pipeline_producer_group, + consumer_group=acc_pipeline_consumer_group, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + + # Tensor memory dealloc barrier init + tmem = utils.TmemAllocator( + storage.tmem_holding_buf, + barrier_for_retrieve=self.tmem_alloc_barrier, + allocator_warp_id=self.epilog_warp_id[0], + is_two_cta=use_2cta_instrs, + two_cta_tmem_dealloc_mbar_ptr=storage.tmem_dealloc_mbar_ptr, + ) + + # Cluster arrive after barrier init + pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mn, is_relaxed=True) + + # + # Setup smem tensor A/B/SFA/SFB/C + # + # (EPI_TILE_M, EPI_TILE_N, STAGE) + sC = storage.sC.get_tensor( + c_smem_layout_staged.outer, swizzle=c_smem_layout_staged.inner + ) + # (MMA, MMA_M, MMA_K, STAGE) + sA = storage.sA.get_tensor( + a_smem_layout_staged.outer, swizzle=a_smem_layout_staged.inner + ) + # (MMA, MMA_N, MMA_K, STAGE) + sB = storage.sB.get_tensor( + b_smem_layout_staged.outer, swizzle=b_smem_layout_staged.inner + ) + # (MMA, MMA_M, MMA_K, STAGE) + sSFA = storage.sSFA.get_tensor(sfa_smem_layout_staged) + # (MMA, MMA_N, MMA_K, STAGE) + sSFB = storage.sSFB.get_tensor(sfb_smem_layout_staged) + + # + # Compute multicast mask for A/B/SFA/SFB buffer full + # + a_full_mcast_mask = None + b_full_mcast_mask = None + sfa_full_mcast_mask = None + sfb_full_mcast_mask = None + if cutlass.const_expr(self.is_a_mcast or self.is_b_mcast or use_2cta_instrs): + a_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=2 + ) + b_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=1 + ) + sfa_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=2 + ) + sfb_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_sfb_vmnk, block_in_cluster_coord_sfb_vmnk, mcast_mode=1 + ) + + # + # Local_tile partition global tensors + # + # (bM, bK, RestM, RestK, RestL) + gA_mkl = cute.local_tile( + mA_mkl, cute.slice_(self.mma_tiler, (None, 0, None)), (None, None, None) + ) + # (bN, bK, RestN, RestK, RestL) + gB_nkl = cute.local_tile( + mB_nkl, cute.slice_(self.mma_tiler, (0, None, None)), (None, None, None) + ) + # (bM, bK, RestM, RestK, RestL) + gSFA_mkl = cute.local_tile( + mSFA_mkl, cute.slice_(self.mma_tiler, (None, 0, None)), (None, None, None) + ) + # (bN, bK, RestN, RestK, RestL) + gSFB_nkl = cute.local_tile( + mSFB_nkl, + cute.slice_(self.mma_tiler_sfb, (0, None, None)), + (None, None, None), + ) + # (bM, bN, RestM, RestN, RestL) + gC_mnl = cute.local_tile( + mC_mnl, cute.slice_(self.mma_tiler, (None, None, 0)), (None, None, None) + ) + k_tile_cnt = cute.size(gA_mkl, mode=[3]) + + # + # Partition global tensor for TiledMMA_A/B/C + # + thr_mma = tiled_mma.get_slice(mma_tile_coord_v) + thr_mma_sfb = tiled_mma_sfb.get_slice(mma_tile_coord_v) + # (MMA, MMA_M, MMA_K, RestM, RestK, RestL) + tCgA = thr_mma.partition_A(gA_mkl) + # (MMA, MMA_N, MMA_K, RestN, RestK, RestL) + tCgB = thr_mma.partition_B(gB_nkl) + # (MMA, MMA_M, MMA_K, RestM, RestK, RestL) + tCgSFA = thr_mma.partition_A(gSFA_mkl) + # (MMA, MMA_N, MMA_K, RestN, RestK, RestL) + tCgSFB = thr_mma_sfb.partition_B(gSFB_nkl) + # (MMA, MMA_M, MMA_N, RestM, RestN, RestL) + tCgC = thr_mma.partition_C(gC_mnl) + + # + # Partition global/shared tensor for TMA load A/B + # + # TMA load A partition_S/D + a_cta_layout = cute.make_layout( + cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape + ) + # ((atom_v, rest_v), STAGE) + # ((atom_v, rest_v), RestM, RestK, RestL) + tAsA, tAgA = cpasync.tma_partition( + tma_atom_a, + block_in_cluster_coord_vmnk[2], + a_cta_layout, + cute.group_modes(sA, 0, 3), + cute.group_modes(tCgA, 0, 3), + ) + # TMA load B partition_S/D + b_cta_layout = cute.make_layout( + cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape + ) + # ((atom_v, rest_v), STAGE) + # ((atom_v, rest_v), RestN, RestK, RestL) + tBsB, tBgB = cpasync.tma_partition( + tma_atom_b, + block_in_cluster_coord_vmnk[1], + b_cta_layout, + cute.group_modes(sB, 0, 3), + cute.group_modes(tCgB, 0, 3), + ) + + # TMA load SFA partition_S/D + sfa_cta_layout = a_cta_layout + # ((atom_v, rest_v), STAGE) + # ((atom_v, rest_v), RestM, RestK, RestL) + tAsSFA, tAgSFA = cute.nvgpu.cpasync.tma_partition( + tma_atom_sfa, + block_in_cluster_coord_vmnk[2], + sfa_cta_layout, + cute.group_modes(sSFA, 0, 3), + cute.group_modes(tCgSFA, 0, 3), + ) + tAsSFA = cute.filter_zeros(tAsSFA) + tAgSFA = cute.filter_zeros(tAgSFA) + + # TMA load SFB partition_S/D + sfb_cta_layout = cute.make_layout( + cute.slice_(cluster_layout_sfb_vmnk, (0, None, 0, 0)).shape + ) + # ((atom_v, rest_v), STAGE) + # ((atom_v, rest_v), RestN, RestK, RestL) + tBsSFB, tBgSFB = cute.nvgpu.cpasync.tma_partition( + tma_atom_sfb, + block_in_cluster_coord_sfb_vmnk[1], + sfb_cta_layout, + cute.group_modes(sSFB, 0, 3), + cute.group_modes(tCgSFB, 0, 3), + ) + tBsSFB = cute.filter_zeros(tBsSFB) + tBgSFB = cute.filter_zeros(tBgSFB) + + # + # Partition shared/tensor memory tensor for TiledMMA_A/B/C + # + # (MMA, MMA_M, MMA_K, STAGE) + tCrA = tiled_mma.make_fragment_A(sA) + # (MMA, MMA_N, MMA_K, STAGE) + tCrB = tiled_mma.make_fragment_B(sB) + # (MMA, MMA_M, MMA_N) + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + if cutlass.const_expr(self.overlapping_accum): + num_acc_stage_overlapped = 2 + tCtAcc_fake = tiled_mma.make_fragment_C( + cute.append(acc_shape, num_acc_stage_overlapped) + ) + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_fake = cute.make_tensor( + tCtAcc_fake.iterator, + cute.make_layout( + tCtAcc_fake.shape, + stride=( + tCtAcc_fake.stride[0], + tCtAcc_fake.stride[1], + tCtAcc_fake.stride[2], + (256 - self.num_sf_tmem_cols) * tCtAcc_fake.stride[0][1], + ), + ), + ) + else: + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_fake = tiled_mma.make_fragment_C( + cute.append(acc_shape, self.num_acc_stage) + ) + + # + # Cluster wait before tensor memory alloc + # + pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mn) + + # + # Specialized TMA load warp + # + if warp_idx == self.tma_warp_id: + # + # Persistent tile scheduling loop + # + tile_sched = utils.StaticPersistentTileScheduler.create( + tile_sched_params, cute.arch.block_idx(), cute.arch.grid_dim() + ) + work_tile = tile_sched.initial_work_tile_info() + + ab_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_ab_stage + ) + + while work_tile.is_valid_tile: + # Get tile coord from tile scheduler + cur_tile_coord = work_tile.tile_idx + mma_tile_coord_mnl = ( + cur_tile_coord[0] // cute.size(tiled_mma.thr_id.shape), + cur_tile_coord[1], + cur_tile_coord[2], + ) + + # + # Slice to per mma tile index + # + # ((atom_v, rest_v), RestK) + tAgA_slice = tAgA[ + (None, mma_tile_coord_mnl[0], None, mma_tile_coord_mnl[2]) + ] + # ((atom_v, rest_v), RestK) + tBgB_slice = tBgB[ + (None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2]) + ] + + # ((atom_v, rest_v), RestK) + tAgSFA_slice = tAgSFA[ + (None, mma_tile_coord_mnl[0], None, mma_tile_coord_mnl[2]) + ] + + slice_n = mma_tile_coord_mnl[1] + if cutlass.const_expr(self.cta_tile_shape_mnk[1] == 64): + slice_n = mma_tile_coord_mnl[1] // 2 + # ((atom_v, rest_v), RestK) + tBgSFB_slice = tBgSFB[(None, slice_n, None, mma_tile_coord_mnl[2])] + + # TMA-prefetch tactic: issue prefetches for the first + # prefetch_dist K-tiles to hide latency. + # Helps small-M large-K where the mainloop is load-bound. + if cutlass.const_expr(self.use_prefetch): + for pf_k_tile in cutlass.range( + 0, min(self.prefetch_dist, k_tile_cnt), unroll=1 + ): + cute.prefetch(tma_atom_a, tAgA_slice[(None, pf_k_tile)]) + cute.prefetch(tma_atom_b, tBgB_slice[(None, pf_k_tile)]) + cute.prefetch(tma_atom_sfa, tAgSFA_slice[(None, pf_k_tile)]) + cute.prefetch(tma_atom_sfb, tBgSFB_slice[(None, pf_k_tile)]) + + # Peek (try_wait) AB buffer empty for k_tile = prefetch_k_tile_cnt + ab_producer_state.reset_count() + peek_ab_empty_status = cutlass.Boolean(1) + if ab_producer_state.count < k_tile_cnt: + peek_ab_empty_status = ab_pipeline.producer_try_acquire( + ab_producer_state + ) + # + # Tma load loop + # + for k_tile in cutlass.range(0, k_tile_cnt, 1, unroll=1): + # Conditionally wait for AB buffer empty + ab_pipeline.producer_acquire( + ab_producer_state, peek_ab_empty_status + ) + + # TMA load A/B/SFA/SFB + cute.copy( + tma_atom_a, + tAgA_slice[(None, ab_producer_state.count)], + tAsA[(None, ab_producer_state.index)], + tma_bar_ptr=ab_pipeline.producer_get_barrier(ab_producer_state), + mcast_mask=a_full_mcast_mask, + ) + cute.copy( + tma_atom_b, + tBgB_slice[(None, ab_producer_state.count)], + tBsB[(None, ab_producer_state.index)], + tma_bar_ptr=ab_pipeline.producer_get_barrier(ab_producer_state), + mcast_mask=b_full_mcast_mask, + ) + cute.copy( + tma_atom_sfa, + tAgSFA_slice[(None, ab_producer_state.count)], + tAsSFA[(None, ab_producer_state.index)], + tma_bar_ptr=ab_pipeline.producer_get_barrier(ab_producer_state), + mcast_mask=sfa_full_mcast_mask, + ) + cute.copy( + tma_atom_sfb, + tBgSFB_slice[(None, ab_producer_state.count)], + tBsSFB[(None, ab_producer_state.index)], + tma_bar_ptr=ab_pipeline.producer_get_barrier(ab_producer_state), + mcast_mask=sfb_full_mcast_mask, + ) + + # Rolling prefetch: stay prefetch_dist tiles ahead each + # iteration to hide TMA latency + # through the whole K-loop. This is the piece that helps + # small-M large-K (the initial pre-loop burst alone does not). + if cutlass.const_expr(self.use_prefetch): + if k_tile < k_tile_cnt - self.prefetch_dist: + future_k_tile = ab_producer_state.count + self.prefetch_dist + cute.prefetch(tma_atom_a, tAgA_slice[(None, future_k_tile)]) + cute.prefetch(tma_atom_b, tBgB_slice[(None, future_k_tile)]) + cute.prefetch( + tma_atom_sfa, tAgSFA_slice[(None, future_k_tile)] + ) + cute.prefetch( + tma_atom_sfb, tBgSFB_slice[(None, future_k_tile)] + ) + + # Peek (try_wait) AB buffer empty for k_tile = prefetch_k_tile_cnt + k_tile + 1 + ab_producer_state.advance() + peek_ab_empty_status = cutlass.Boolean(1) + if ab_producer_state.count < k_tile_cnt: + peek_ab_empty_status = ab_pipeline.producer_try_acquire( + ab_producer_state + ) + + # + # Advance to next tile + # + tile_sched.advance_to_next_work() + work_tile = tile_sched.get_current_work() + + # + # Wait A/B buffer empty + # + ab_pipeline.producer_tail(ab_producer_state) + + # + # Specialized MMA warp + # + if warp_idx == self.mma_warp_id: + # + # Bar sync for retrieve tensor memory ptr from shared mem + # + tmem.wait_for_alloc() + + # + # Retrieving tensor memory ptr and make accumulator/SFA/SFB tensor + # + acc_tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + # Make accumulator tmem tensor + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_base = cute.make_tensor(acc_tmem_ptr, tCtAcc_fake.layout) + + # Make SFA tmem tensor + sfa_tmem_ptr = cute.recast_ptr( + acc_tmem_ptr + self.num_accumulator_tmem_cols, + dtype=self.sf_dtype, + ) + # (MMA, MMA_M, MMA_K) + tCtSFA_layout = blockscaled_utils.make_tmem_layout_sfa( + tiled_mma, + self.mma_tiler, + self.sf_vec_size, + cute.slice_(sfa_smem_layout_staged, (None, None, None, 0)), + ) + tCtSFA = cute.make_tensor(sfa_tmem_ptr, tCtSFA_layout) + + # Make SFB tmem tensor + sfb_tmem_ptr = cute.recast_ptr( + acc_tmem_ptr + self.num_accumulator_tmem_cols + self.num_sfa_tmem_cols, + dtype=self.sf_dtype, + ) + # (MMA, MMA_N, MMA_K) + tCtSFB_layout = blockscaled_utils.make_tmem_layout_sfb( + tiled_mma, + self.mma_tiler, + self.sf_vec_size, + cute.slice_(sfb_smem_layout_staged, (None, None, None, 0)), + ) + tCtSFB = cute.make_tensor(sfb_tmem_ptr, tCtSFB_layout) + # + # Partition for S2T copy of SFA/SFB + # + ( + tiled_copy_s2t_sfa, + tCsSFA_compact_s2t, + tCtSFA_compact_s2t, + ) = self.mainloop_s2t_copy_and_partition(sSFA, tCtSFA) + ( + tiled_copy_s2t_sfb, + tCsSFB_compact_s2t, + tCtSFB_compact_s2t, + ) = self.mainloop_s2t_copy_and_partition(sSFB, tCtSFB) + + # + # Persistent tile scheduling loop + # + tile_sched = utils.StaticPersistentTileScheduler.create( + tile_sched_params, cute.arch.block_idx(), cute.arch.grid_dim() + ) + work_tile = tile_sched.initial_work_tile_info() + + ab_consumer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_ab_stage + ) + acc_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_acc_stage + ) + + while work_tile.is_valid_tile: + # Get tile coord from tile scheduler + cur_tile_coord = work_tile.tile_idx + mma_tile_coord_mnl = ( + cur_tile_coord[0] // cute.size(tiled_mma.thr_id.shape), + cur_tile_coord[1], + cur_tile_coord[2], + ) + + # Get accumulator stage index + reverse_subtile = cutlass.Boolean(False) + if cutlass.const_expr(self.overlapping_accum): + acc_stage_index = acc_producer_state.phase ^ 1 + else: + acc_stage_index = acc_producer_state.index + + # Set tensor memory buffer for current tile + # (MMA, MMA_M, MMA_N) + tCtAcc = tCtAcc_base[(None, None, None, acc_stage_index)] + + # Peek (try_wait) AB buffer full for k_tile = 0 + ab_consumer_state.reset_count() + peek_ab_full_status = cutlass.Boolean(1) + if ab_consumer_state.count < k_tile_cnt and is_leader_cta: + peek_ab_full_status = ab_pipeline.consumer_try_wait( + ab_consumer_state + ) + + # + # Wait for accumulator buffer empty + # + if is_leader_cta: + acc_pipeline.producer_acquire(acc_producer_state) + + tCtSFB_mma = tCtSFB + if cutlass.const_expr(self.cta_tile_shape_mnk[1] == 192): + # If this is an ODD tile, shift the TMEM start address for cta_tile_shape_n=192 case by two words (ignores first 64 columns of SFB) + offset = ( + cutlass.Int32(2) + if mma_tile_coord_mnl[1] % 2 == 1 + else cutlass.Int32(0) + ) + shifted_ptr = cute.recast_ptr( + acc_tmem_ptr + + self.num_accumulator_tmem_cols + + self.num_sfa_tmem_cols + + offset, + dtype=self.sf_dtype, + ) + tCtSFB_mma = cute.make_tensor(shifted_ptr, tCtSFB_layout) + elif cutlass.const_expr(self.cta_tile_shape_mnk[1] == 64): + # Move in increments of 64 columns of SFB + offset = cutlass.Int32((mma_tile_coord_mnl[1] % 2) * 2) + shifted_ptr = cute.recast_ptr( + acc_tmem_ptr + + self.num_accumulator_tmem_cols + + self.num_sfa_tmem_cols + + offset, + dtype=self.sf_dtype, + ) + tCtSFB_mma = cute.make_tensor(shifted_ptr, tCtSFB_layout) + + # + # Reset the ACCUMULATE field for each tile + # + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + + # + # Mma mainloop + # + for k_tile in range(k_tile_cnt): + if is_leader_cta: + # Conditionally wait for AB buffer full + ab_pipeline.consumer_wait( + ab_consumer_state, peek_ab_full_status + ) + + # Copy SFA/SFB from smem to tmem + s2t_stage_coord = ( + None, + None, + None, + None, + ab_consumer_state.index, + ) + tCsSFA_compact_s2t_staged = tCsSFA_compact_s2t[s2t_stage_coord] + tCsSFB_compact_s2t_staged = tCsSFB_compact_s2t[s2t_stage_coord] + cute.copy( + tiled_copy_s2t_sfa, + tCsSFA_compact_s2t_staged, + tCtSFA_compact_s2t, + ) + cute.copy( + tiled_copy_s2t_sfb, + tCsSFB_compact_s2t_staged, + tCtSFB_compact_s2t, + ) + + # tCtAcc += tCrA * tCrSFA * tCrB * tCrSFB + num_kblocks = cute.size(tCrA, mode=[2]) + for kblock_idx in cutlass.range(num_kblocks, unroll_full=True): + kblock_coord = ( + None, + None, + kblock_idx, + ab_consumer_state.index, + ) + + # Set SFA/SFB tensor to tiled_mma + sf_kblock_coord = (None, None, kblock_idx) + tiled_mma.set( + tcgen05.Field.SFA, + tCtSFA[sf_kblock_coord].iterator, + ) + tiled_mma.set( + tcgen05.Field.SFB, + tCtSFB_mma[sf_kblock_coord].iterator, + ) + + cute.gemm( + tiled_mma, + tCtAcc, + tCrA[kblock_coord], + tCrB[kblock_coord], + tCtAcc, + ) + + # Enable accumulate on tCtAcc after first kblock + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + + # Async arrive AB buffer empty + ab_pipeline.consumer_release(ab_consumer_state) + + # Peek (try_wait) AB buffer full for k_tile = k_tile + 1 + ab_consumer_state.advance() + peek_ab_full_status = cutlass.Boolean(1) + if ab_consumer_state.count < k_tile_cnt: + if is_leader_cta: + peek_ab_full_status = ab_pipeline.consumer_try_wait( + ab_consumer_state + ) + + # + # Async arrive accumulator buffer full + # + if is_leader_cta: + acc_pipeline.producer_commit(acc_producer_state) + acc_producer_state.advance() + + # + # Advance to next tile + # + tile_sched.advance_to_next_work() + work_tile = tile_sched.get_current_work() + + # + # Wait for accumulator buffer empty + # + acc_pipeline.producer_tail(acc_producer_state) + # + # Specialized epilogue warps + # + if warp_idx < self.mma_warp_id: + # + # Alloc tensor memory buffer + # + tmem.allocate(self.num_tmem_alloc_cols) + + # + # Bar sync for retrieve tensor memory ptr from shared memory + # + tmem.wait_for_alloc() + + # + # Retrieving tensor memory ptr and make accumulator tensor + # + acc_tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_base = cute.make_tensor(acc_tmem_ptr, tCtAcc_fake.layout) + + # + # Partition for epilogue + # + epi_tidx = tidx + ( + tiled_copy_t2r, + tTR_tAcc_base, + tTR_rAcc, + ) = self.epilog_tmem_copy_and_partition( + epi_tidx, tCtAcc_base, tCgC, epi_tile, use_2cta_instrs + ) + + tTR_rC = cute.make_rmem_tensor(tTR_rAcc.shape, self.c_dtype) + tiled_copy_r2s, tRS_rC, tRS_sC = self.epilog_smem_copy_and_partition( + tiled_copy_t2r, tTR_rC, epi_tidx, sC + ) + ( + tma_atom_c, + bSG_sC, + bSG_gC_partitioned, + ) = self.epilog_gmem_copy_and_partition( + epi_tidx, tma_atom_c, tCgC, epi_tile, sC + ) + + # + # Persistent tile scheduling loop + # + tile_sched = utils.StaticPersistentTileScheduler.create( + tile_sched_params, cute.arch.block_idx(), cute.arch.grid_dim() + ) + work_tile = tile_sched.initial_work_tile_info() + + acc_consumer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_acc_stage + ) + + # Threads/warps participating in tma store pipeline + c_producer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, + 32 * len(self.epilog_warp_id), + ) + c_pipeline = pipeline.PipelineTmaStore.create( + num_stages=self.num_c_stage, + producer_group=c_producer_group, + ) + + while work_tile.is_valid_tile: + # Get tile coord from tile scheduler + cur_tile_coord = work_tile.tile_idx + mma_tile_coord_mnl = ( + cur_tile_coord[0] // cute.size(tiled_mma.thr_id.shape), + cur_tile_coord[1], + cur_tile_coord[2], + ) + + # + # Slice to per mma tile index + # + # ((ATOM_V, REST_V), EPI_M, EPI_N) + bSG_gC = bSG_gC_partitioned[ + ( + None, + None, + None, + *mma_tile_coord_mnl, + ) + ] + + # Get accumulator stage index + if cutlass.const_expr(self.overlapping_accum): + acc_stage_index = acc_consumer_state.phase + reverse_subtile = ( + cutlass.Boolean(True) + if acc_stage_index == 0 + else cutlass.Boolean(False) + ) + else: + acc_stage_index = acc_consumer_state.index + + # Set tensor memory buffer for current tile + # (T2R, T2R_M, T2R_N, EPI_M, EPI_M) + tTR_tAcc = tTR_tAcc_base[ + (None, None, None, None, None, acc_stage_index) + ] + + # + # Wait for accumulator buffer full + # + acc_pipeline.consumer_wait(acc_consumer_state) + + tTR_tAcc = cute.group_modes(tTR_tAcc, 3, cute.rank(tTR_tAcc)) + bSG_gC = cute.group_modes(bSG_gC, 1, cute.rank(bSG_gC)) + + # + # Store accumulator to global memory in subtiles + # + subtile_cnt = cute.size(tTR_tAcc.shape, mode=[3]) + num_prev_subtiles = tile_sched.num_tiles_executed * subtile_cnt + local_reduce_partial = None + if cutlass.const_expr( + (local_reduce_tensor is not None or self.local_reduce_feeds_main) + and self.local_reduce_axis == 1 + and self.local_reduce_group > self.epi_tile_n + ): + local_reduce_partial = cute.make_rmem_tensor( + ((1, self.epi_tile_n, 1), 1, 1), self.acc_dtype + ) + for subtile_idx in cutlass.range(subtile_cnt): + real_subtile_idx = subtile_idx + if cutlass.const_expr(self.overlapping_accum): + if reverse_subtile: + real_subtile_idx = ( + self.cta_tile_shape_mnk[1] // self.epi_tile_n + - 1 + - subtile_idx + ) + # + # Load accumulator from tensor memory buffer to register + # + tTR_tAcc_mn = tTR_tAcc[(None, None, None, real_subtile_idx)] + cute.copy(tiled_copy_t2r, tTR_tAcc_mn, tTR_rAcc) + + # + # Async arrive accumulator buffer empty earlier when overlapping_accum is enabled + # + if cutlass.const_expr(self.overlapping_accum): + if subtile_idx == self.iter_acc_early_release_in_epilogue: + # Fence for TMEM load + cute.arch.fence_view_async_tmem_load() + with cute.arch.elect_one(): + acc_pipeline.consumer_release(acc_consumer_state) + acc_consumer_state.advance() + + # + # Convert to C type + # + acc_vec = tiled_copy_r2s.retile(tTR_rAcc).load() + # Fused global scale: multiply by runtime alpha[0] (a traced + # kernel-arg scalar) when provided. Closure capture cannot + # read a runtime tensor here, so alpha must be a kernel arg. + # Apply in fp32 (acc_dtype) BEFORE the downcast to c_dtype so + # low-range outputs (fp8/fp16) don't overflow/saturate on the + # cast before alpha (typically < 1) restores range, and before + # epilogue_op so the epilogue sees the true scaled value. + # const_expr makes this a compile-time branch (skipped when + # alpha_tensor is None) rather than device control flow. + if cutlass.const_expr(alpha_tensor is not None): + acc_vec = acc_vec * alpha_tensor[0].to(self.acc_dtype) + has_epilogue_tensors = cutlass.const_expr( + epilogue_tensor0 is not None + or epilogue_tensor1 is not None + or epilogue_tensor2 is not None + or epilogue_tensor3 is not None + ) + has_epilogue_outputs = cutlass.const_expr( + self.epilogue_output_count > 1 + ) + if cutlass.const_expr( + has_epilogue_tensors + or has_epilogue_outputs + or local_reduce_tensor is not None + ): + tDcC = partition_for_epilogue( + cute.make_identity_tensor(self.cta_tile_shape_mnk[:2]), + epi_tile=epi_tile, + tiled_copy=tiled_copy_t2r, + tidx=epi_tidx, + reference_src=False, + ) + tDcC = tDcC[(None, None, None, 0, real_subtile_idx)] + coord_flt = cute.filter_zeros(tDcC) + + epilogue_values = [] + if cutlass.const_expr(has_epilogue_tensors or has_epilogue_outputs): + output_m = cute.size(mC_mnl, mode=[0]) + output_n = cute.size(mC_mnl, mode=[1]) + if cutlass.const_expr(has_epilogue_tensors): + for tensor, kind in ( + (epilogue_tensor0, epilogue_tensor_kind0), + (epilogue_tensor1, epilogue_tensor_kind1), + (epilogue_tensor2, epilogue_tensor_kind2), + (epilogue_tensor3, epilogue_tensor_kind3), + ): + if cutlass.const_expr(tensor is not None): + fragment = cute.make_rmem_tensor_like( + acc_vec, tensor.element_type + ) + for i in cutlass.range( + cute.size(fragment), unroll_full=True + ): + row_idx = coord_flt[i][0] + col_idx = coord_flt[i][1] + global_m = ( + mma_tile_coord_mnl[0] + * self.cta_tile_shape_mnk[0] + + row_idx + ) + global_n = ( + mma_tile_coord_mnl[1] + * self.cta_tile_shape_mnk[1] + + col_idx + ) + tensor_m = ( + 0 if cutlass.const_expr(kind == 2) else global_m + ) + tensor_n = ( + 0 if cutlass.const_expr(kind == 3) else global_n + ) + fragment[i] = tensor[0, 0, 0] + if global_m < output_m and global_n < output_n: + fragment[i] = tensor[ + tensor_m, + tensor_n, + mma_tile_coord_mnl[2], + ] + epilogue_values.append(fragment.load()) + if cutlass.const_expr( + local_reduce_tensor is not None or self.local_reduce_feeds_main + ): + local_reduce_vec = acc_vec.to(epilogue_input_dtype).to( + self.acc_dtype + ) + if cutlass.const_expr(self.local_reduce_source == "square"): + local_reduce_vec = local_reduce_vec * local_reduce_vec + else: + assert self.local_reduce_source == "identity" + if cutlass.const_expr(self.local_reduce_feeds_main): + group = cutlass.const_expr(self.local_reduce_group) + lane_layout_mn, _ = get_lane_warp_layouts( + tiled_copy_t2r, reference_src=False + ) + lanes_in_m = cutlass.const_expr( + cute.size(lane_layout_mn, mode=[0]) + ) + assert group <= lanes_in_m + feed_value = cute.make_rmem_tensor_like( + local_reduce_vec, self.acc_dtype + ) + feed_value.store(local_reduce_vec) + feed_flt = cute.filter_zeros(feed_value) + for i in cutlass.range(cute.size(feed_flt), unroll_full=True): + rows = group // 2 + while rows > 0: + feed_flt[i] += cute.arch.shuffle_sync_bfly( + feed_flt[i], + offset=cute.crd2idx((rows, 0), lane_layout_mn), + ) + rows //= 2 + if cutlass.const_expr(self.local_reduce_type == "mean"): + feed_flt[i] /= group + epilogue_result = ( + acc_vec.to(epilogue_input_dtype) - feed_value.load() + ) + else: + epilogue_result = epilogue_op( + acc_vec.to(epilogue_input_dtype), *tuple(epilogue_values) + ) + if cutlass.const_expr(has_epilogue_outputs): + for output_index, tensor in enumerate( + (epilogue_output0, epilogue_output1, epilogue_output2) + ): + if cutlass.const_expr(tensor is not None): + result_index = cutlass.const_expr( + output_index + if output_index < self.primary_epilogue_output + else output_index + 1 + ) + output_vec = epilogue_result[result_index].to( + tensor.element_type + ) + fragment = cute.make_rmem_tensor_like( + output_vec, tensor.element_type + ) + fragment.store(output_vec) + fragment_flt = cute.filter_zeros(fragment) + for i in cutlass.range( + cute.size(fragment_flt), unroll_full=True + ): + row_idx = coord_flt[i][0] + col_idx = coord_flt[i][1] + global_m = ( + mma_tile_coord_mnl[0] + * self.cta_tile_shape_mnk[0] + + row_idx + ) + global_n = ( + mma_tile_coord_mnl[1] + * self.cta_tile_shape_mnk[1] + + col_idx + ) + if global_m < output_m and global_n < output_n: + tensor[ + global_m, + global_n, + mma_tile_coord_mnl[2], + ] = fragment_flt[i] + acc_vec = epilogue_result[self.primary_epilogue_output].to( + self.c_dtype + ) + else: + acc_vec = epilogue_result.to(self.c_dtype) + + if cutlass.const_expr( + local_reduce_tensor is not None + and not self.local_reduce_feeds_main + ): + group = cutlass.const_expr(self.local_reduce_group) + mReduce = local_reduce_tensor[mma_tile_coord_mnl[2], None, None] + if cutlass.const_expr(self.local_reduce_axis == 1): + fragment_n = cutlass.const_expr( + cute.size(acc_vec.shape, mode=[0]) + ) + assert group > 1 and group <= self.cta_tile_shape_mnk[1] + fragment_group = cutlass.const_expr(min(group, fragment_n)) + assert group % fragment_group == 0 + assert fragment_n % fragment_group == 0 + repeats = cutlass.const_expr(fragment_n // fragment_group) + grouped = local_reduce_vec.reshape( + ((1, fragment_group, repeats), 1, 1) + ) + if cutlass.const_expr( + self.local_reduce_type in ("sum", "mean") + ): + reduce_op = cute.ReductionOp.ADD + init_val = 0.0 + elif cutlass.const_expr(self.local_reduce_type == "prod"): + reduce_op = cute.ReductionOp.MUL + init_val = 1.0 + elif cutlass.const_expr(self.local_reduce_type == "max"): + reduce_op = cute.ReductionOp.MAX + init_val = -cutlass.Float32.inf + else: + assert self.local_reduce_type == "min" + reduce_op = cute.ReductionOp.MIN + init_val = cutlass.Float32.inf + reduced = grouped.reduce( + reduce_op, + init_val=init_val, + reduction_profile=((None, 1, None), 1, 1), + ) + if cutlass.const_expr( + self.local_reduce_type == "mean" and group <= fragment_n + ): + reduced = reduced / group + reduced = reduced.reshape(((1, 1, repeats), 1, 1)) + reduced = reduced.broadcast_to(grouped.shape) + should_store = cutlass.Boolean(True) + store_offset = cutlass.Int32(0) + if cutlass.const_expr(group > fragment_n): + fragments_per_group = cutlass.const_expr( + group // fragment_n + ) + partial = local_reduce_partial.load() + if subtile_idx % fragments_per_group == 0: + partial = reduced + elif cutlass.const_expr( + self.local_reduce_type in ("sum", "mean") + ): + partial = partial + reduced + elif cutlass.const_expr( + self.local_reduce_type == "prod" + ): + partial = partial * reduced + elif cutlass.const_expr( + self.local_reduce_type == "max" + ): + partial = cute.math.max(partial, reduced) + else: + assert self.local_reduce_type == "min" + partial = cute.math.min(partial, reduced) + local_reduce_partial.store(partial) + should_store = ( + subtile_idx % fragments_per_group + == fragments_per_group - 1 + ) + if should_store: + reduced = partial + if cutlass.const_expr( + self.local_reduce_type == "mean" + ): + reduced = reduced / group + store_offset = ( + real_subtile_idx * self.epi_tile_n + ) % group + tDrReduce = cute.make_rmem_tensor( + reduced.shape, self.acc_dtype + ) + tDrReduce.store(reduced) + reduced_flt = cute.filter_zeros(tDrReduce) + groups_per_cta = cutlass.const_expr( + self.cta_tile_shape_mnk[1] // group + ) + gReduce = cute.local_tile( + mReduce, + (self.cta_tile_shape_mnk[0], groups_per_cta), + mma_tile_coord_mnl[:2], + ) + limit_m = min( + cute.size(local_reduce_tensor, mode=[1]) + - mma_tile_coord_mnl[0] * self.cta_tile_shape_mnk[0], + self.cta_tile_shape_mnk[0], + ) + limit_groups = cute.size(local_reduce_tensor, mode=[2]) + for i in cutlass.range( + cute.size(reduced_flt), unroll_full=True + ): + row_idx = coord_flt[i][0] + n_idx = coord_flt[i][1] + group_idx = n_idx // group + global_group_idx = ( + mma_tile_coord_mnl[1] * groups_per_cta + group_idx + ) + if ( + should_store + and n_idx % group == store_offset + and row_idx < limit_m + and global_group_idx < limit_groups + ): + gReduce[row_idx, group_idx] = reduced_flt[i] + else: + tDrReduce = cute.make_rmem_tensor_like( + local_reduce_vec, self.acc_dtype + ) + tDrReduce.store(local_reduce_vec) + reduced_flt = cute.filter_zeros(tDrReduce) + lane_layout_mn, warp_layout_mn = get_lane_warp_layouts( + tiled_copy_t2r, reference_src=False + ) + lanes_in_m = cutlass.const_expr( + cute.size(lane_layout_mn, mode=[0]) + ) + assert group > 1 and group <= self.cta_tile_shape_mnk[0] + reduction_group = cutlass.const_expr(min(group, lanes_in_m)) + assert group % reduction_group == 0 + assert lanes_in_m % reduction_group == 0 + for i in cutlass.range( + cute.size(reduced_flt), unroll_full=True + ): + rows = reduction_group // 2 + while rows > 0: + other = cute.arch.shuffle_sync_bfly( + reduced_flt[i], + offset=cute.crd2idx((rows, 0), lane_layout_mn), + ) + if cutlass.const_expr( + self.local_reduce_type in ("sum", "mean") + ): + reduced_flt[i] += other + elif cutlass.const_expr( + self.local_reduce_type == "prod" + ): + reduced_flt[i] *= other + elif cutlass.const_expr( + self.local_reduce_type == "max" + ): + reduced_flt[i] = cute.arch.fmax( + reduced_flt[i], other + ) + else: + assert self.local_reduce_type == "min" + reduced_flt[i] = cute.arch.fmin( + reduced_flt[i], other + ) + rows = rows // 2 + if cutlass.const_expr(self.local_reduce_type == "mean"): + reduced_flt[i] /= group + groups_per_cta = cutlass.const_expr( + self.cta_tile_shape_mnk[0] // group + ) + gReduce = cute.local_tile( + mReduce, + (groups_per_cta, self.cta_tile_shape_mnk[1]), + mma_tile_coord_mnl[:2], + ) + limit_n = min( + cute.size(local_reduce_tensor, mode=[2]) + - mma_tile_coord_mnl[1] * self.cta_tile_shape_mnk[1], + self.cta_tile_shape_mnk[1], + ) + limit_groups = cute.size(local_reduce_tensor, mode=[1]) + group_warps = cutlass.const_expr(group // lanes_in_m) + warp_m = warp_layout_mn[0] + warps_in_m = cutlass.const_expr(cute.size(warp_m)) + assert group_warps <= warps_in_m + warp_idx = cute.arch.make_warp_uniform( + epi_tidx // cute.arch.WARP_SIZE + ) + warp_m_idx = warp_layout_mn.get_hier_coord(warp_idx)[0] + if cutlass.const_expr(group > lanes_in_m): + for i in cutlass.range( + cute.size(reduced_flt), unroll_full=True + ): + row_idx = coord_flt[i][0] + n_idx = coord_flt[i][1] + group_idx = row_idx // group + group_warp_start = group_idx * group_warps + group_warp_idx = warp_m_idx - group_warp_start + if ( + row_idx % lanes_in_m == 0 + and group_warp_idx > 0 + and group_warp_idx < group_warps + ): + sLocalReduce[ + n_idx, warp_m_idx - group_idx - 1 + ] = reduced_flt[i] + self.epilog_sync_barrier.arrive_and_wait() + for i in cutlass.range( + cute.size(reduced_flt), unroll_full=True + ): + row_idx = coord_flt[i][0] + n_idx = coord_flt[i][1] + group_idx = row_idx // group + global_group_idx = ( + mma_tile_coord_mnl[0] * groups_per_cta + group_idx + ) + group_value = reduced_flt[i] + group_warp_start = group_idx * group_warps + if cutlass.const_expr(group > lanes_in_m): + if ( + row_idx % group == 0 + and warp_m_idx == group_warp_start + ): + for warp_offset in cutlass.range_constexpr( + 1, group_warps + ): + other = sLocalReduce[ + n_idx, + group_warp_start + + warp_offset + - group_idx + - 1, + ] + if cutlass.const_expr( + self.local_reduce_type + in ("sum", "mean") + ): + group_value += other + elif cutlass.const_expr( + self.local_reduce_type == "prod" + ): + group_value *= other + elif cutlass.const_expr( + self.local_reduce_type == "max" + ): + group_value = cute.arch.fmax( + group_value, other + ) + else: + assert self.local_reduce_type == "min" + group_value = cute.arch.fmin( + group_value, other + ) + if ( + row_idx % group == 0 + and n_idx < limit_n + and global_group_idx < limit_groups + ): + gReduce[group_idx, n_idx] = group_value + if cutlass.const_expr(group > lanes_in_m): + self.epilog_sync_barrier.arrive_and_wait() + tRS_rC.store(acc_vec) + + # + # Store C to shared memory + # + c_buffer = (num_prev_subtiles + real_subtile_idx) % self.num_c_stage + cute.copy( + tiled_copy_r2s, + tRS_rC, + tRS_sC[(None, None, None, c_buffer)], + ) + # Fence and barrier to make sure shared memory store is visible to TMA store + cute.arch.fence_proxy( + "async.shared", + space="cta", + ) + self.epilog_sync_barrier.arrive_and_wait() + + # + # TMA store C to global memory + # + if warp_idx == self.epilog_warp_id[0]: + cute.copy( + tma_atom_c, + bSG_sC[(None, c_buffer)], + bSG_gC[(None, real_subtile_idx)], + ) + # Fence and barrier to make sure shared memory store is visible to TMA store + c_pipeline.producer_commit() + c_pipeline.producer_acquire() + self.epilog_sync_barrier.arrive_and_wait() + + # + # Async arrive accumulator buffer empty + # + if cutlass.const_expr(not self.overlapping_accum): + with cute.arch.elect_one(): + acc_pipeline.consumer_release(acc_consumer_state) + acc_consumer_state.advance() + + # + # Advance to next tile + # + tile_sched.advance_to_next_work() + work_tile = tile_sched.get_current_work() + + # + # Dealloc the tensor memory buffer + # + tmem.relinquish_alloc_permit() + self.epilog_sync_barrier.arrive_and_wait() + tmem.free(acc_tmem_ptr) + # + # Wait for C store complete + # + c_pipeline.producer_tail() + + def mainloop_s2t_copy_and_partition( + self, + sSF: cute.Tensor, + tSF: cute.Tensor, + ) -> Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]: + """ + Make tiledCopy for smem to tmem load for scale factor tensor, then use it to partition smem memory (source) and tensor memory (destination). + + :param sSF: The scale factor tensor in smem + :type sSF: cute.Tensor + :param tSF: The scale factor tensor in tmem + :type tSF: cute.Tensor + + :return: A tuple containing (tiled_copy_s2t, tCsSF_compact_s2t, tCtSF_compact_s2t) where: + - tiled_copy_s2t: The tiled copy operation for smem to tmem load for scale factor tensor(s2t) + - tCsSF_compact_s2t: The partitioned scale factor tensor in smem + - tSF_compact_s2t: The partitioned scale factor tensor in tmem + :rtype: Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor] + """ + # (MMA, MMA_MN, MMA_K, STAGE) + tCsSF_compact = cute.filter_zeros(sSF) + # (MMA, MMA_MN, MMA_K) + tCtSF_compact = cute.filter_zeros(tSF) + + # Make S2T CopyAtom and tiledCopy + copy_atom_s2t = cute.make_copy_atom( + tcgen05.Cp4x32x128bOp(self.cta_group), + self.sf_dtype, + ) + tiled_copy_s2t = tcgen05.make_s2t_copy(copy_atom_s2t, tCtSF_compact) + thr_copy_s2t = tiled_copy_s2t.get_slice(0) + + # ((ATOM_V, REST_V), Rest_Tiler, MMA_MN, MMA_K, STAGE) + tCsSF_compact_s2t_ = thr_copy_s2t.partition_S(tCsSF_compact) + # ((ATOM_V, REST_V), Rest_Tiler, MMA_MN, MMA_K, STAGE) + tCsSF_compact_s2t = tcgen05.get_s2t_smem_desc_tensor( + tiled_copy_s2t, tCsSF_compact_s2t_ + ) + # ((ATOM_V, REST_V), Rest_Tiler, MMA_MN, MMA_K) + tCtSF_compact_s2t = thr_copy_s2t.partition_D(tCtSF_compact) + + return tiled_copy_s2t, tCsSF_compact_s2t, tCtSF_compact_s2t + + def epilog_tmem_copy_and_partition( + self, + tidx: cutlass.Int32, + tAcc: cute.Tensor, + gC_mnl: cute.Tensor, + epi_tile: cute.Tile, + use_2cta_instrs: Union[cutlass.Boolean, bool], + ) -> Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]: + """ + Make tiledCopy for tensor memory load, then use it to partition tensor memory (source) and register array (destination). + + :param tidx: The thread index in epilogue warp groups + :type tidx: cutlass.Int32 + :param tAcc: The accumulator tensor to be copied and partitioned + :type tAcc: cute.Tensor + :param gC_mnl: The global tensor C + :type gC_mnl: cute.Tensor + :param epi_tile: The epilogue tiler + :type epi_tile: cute.Tile + :param use_2cta_instrs: Whether use_2cta_instrs is enabled + :type use_2cta_instrs: bool + + :return: A tuple containing (tiled_copy_t2r, tTR_tAcc, tTR_rAcc) where: + - tiled_copy_t2r: The tiled copy operation for tmem to register copy(t2r) + - tTR_tAcc: The partitioned accumulator tensor + - tTR_rAcc: The accumulated tensor in register used to hold t2r results + :rtype: Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor] + """ + # Make tiledCopy for tensor memory load + copy_atom_t2r = sm100_utils.get_tmem_load_op( + self.cta_tile_shape_mnk, + self.c_layout, + self.c_dtype, + self.acc_dtype, + epi_tile, + use_2cta_instrs, + ) + # (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, STAGE) + tAcc_epi = cute.flat_divide( + tAcc[((None, None), 0, 0, None)], + epi_tile, + ) + # (EPI_TILE_M, EPI_TILE_N) + tiled_copy_t2r = tcgen05.make_tmem_copy( + copy_atom_t2r, tAcc_epi[(None, None, 0, 0, 0)] + ) + + thr_copy_t2r = tiled_copy_t2r.get_slice(tidx) + # (T2R, T2R_M, T2R_N, EPI_M, EPI_M, STAGE) + tTR_tAcc = thr_copy_t2r.partition_S(tAcc_epi) + + # (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, RestM, RestN, RestL) + gC_mnl_epi = cute.flat_divide( + gC_mnl[((None, None), 0, 0, None, None, None)], epi_tile + ) + # (T2R, T2R_M, T2R_N, EPI_M, EPI_N, RestM, RestN, RestL) + tTR_gC = thr_copy_t2r.partition_D(gC_mnl_epi) + # (T2R, T2R_M, T2R_N) + tTR_rAcc = cute.make_rmem_tensor( + tTR_gC[(None, None, None, 0, 0, 0, 0, 0)].shape, self.acc_dtype + ) + return tiled_copy_t2r, tTR_tAcc, tTR_rAcc + + def epilog_smem_copy_and_partition( + self, + tiled_copy_t2r: cute.TiledCopy, + tTR_rC: cute.Tensor, + tidx: cutlass.Int32, + sC: cute.Tensor, + ) -> Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]: + """ + Make tiledCopy for shared memory store, then use it to partition register array (source) and shared memory (destination). + + :param tiled_copy_t2r: The tiled copy operation for tmem to register copy(t2r) + :type tiled_copy_t2r: cute.TiledCopy + :param tTR_rC: The partitioned accumulator tensor + :type tTR_rC: cute.Tensor + :param tidx: The thread index in epilogue warp groups + :type tidx: cutlass.Int32 + :param sC: The shared memory tensor to be copied and partitioned + :type sC: cute.Tensor + :type sepi: cute.Tensor + + :return: A tuple containing (tiled_copy_r2s, tRS_rC, tRS_sC) where: + - tiled_copy_r2s: The tiled copy operation for register to smem copy(r2s) + - tRS_rC: The partitioned tensor C (register source) + - tRS_sC: The partitioned tensor C (smem destination) + :rtype: Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor] + """ + copy_atom_r2s = sm100_utils.get_smem_store_op( + self.c_layout, self.c_dtype, self.acc_dtype, tiled_copy_t2r + ) + tiled_copy_r2s = cute.make_tiled_copy_D(copy_atom_r2s, tiled_copy_t2r) + # (R2S, R2S_M, R2S_N, PIPE_D) + thr_copy_r2s = tiled_copy_r2s.get_slice(tidx) + tRS_sC = thr_copy_r2s.partition_D(sC) + # (R2S, R2S_M, R2S_N) + tRS_rC = tiled_copy_r2s.retile(tTR_rC) + return tiled_copy_r2s, tRS_rC, tRS_sC + + def epilog_gmem_copy_and_partition( + self, + tidx: cutlass.Int32, + atom: Union[cute.CopyAtom, cute.TiledCopy], + gC_mnl: cute.Tensor, + epi_tile: cute.Tile, + sC: cute.Tensor, + ) -> Tuple[cute.CopyAtom, cute.Tensor, cute.Tensor]: + """Make tiledCopy for global memory store, then use it to: + partition shared memory (source) and global memory (destination) for TMA store version. + + :param tidx: The thread index in epilogue warp groups + :type tidx: cutlass.Int32 + :param atom: The copy_atom_c to be used for TMA store version, or tiled_copy_t2r for none TMA store version + :type atom: cute.CopyAtom or cute.TiledCopy + :param gC_mnl: The global tensor C + :type gC_mnl: cute.Tensor + :param epi_tile: The epilogue tiler + :type epi_tile: cute.Tile + :param sC: The shared memory tensor to be copied and partitioned + :type sC: cute.Tensor + + :return: A tuple containing (tma_atom_c, bSG_sC, bSG_gC) where: + - tma_atom_c: The TMA copy atom + - bSG_sC: The partitioned shared memory tensor C + - bSG_gC: The partitioned global tensor C + :rtype: Tuple[cute.CopyAtom, cute.Tensor, cute.Tensor] + """ + # (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, RestM, RestN, RestL) + gC_epi = cute.flat_divide( + gC_mnl[((None, None), 0, 0, None, None, None)], epi_tile + ) + + tma_atom_c = atom + sC_for_tma_partition = cute.group_modes(sC, 0, 2) + gC_for_tma_partition = cute.group_modes(gC_epi, 0, 2) + # ((ATOM_V, REST_V), EPI_M, EPI_N) + # ((ATOM_V, REST_V), EPI_M, EPI_N, RestM, RestN, RestL) + bSG_sC, bSG_gC = cpasync.tma_partition( + tma_atom_c, + 0, + cute.make_layout(1), + sC_for_tma_partition, + gC_for_tma_partition, + ) + return tma_atom_c, bSG_sC, bSG_gC + + @staticmethod + def _compute_stages( + tiled_mma: cute.TiledMma, + mma_tiler_mnk: Tuple[int, int, int], + a_dtype: Type[cutlass.Numeric], + b_dtype: Type[cutlass.Numeric], + epi_tile: cute.Tile, + c_dtype: Type[cutlass.Numeric], + c_layout: utils.LayoutEnum, + sf_dtype: Type[cutlass.Numeric], + sf_vec_size: int, + smem_capacity: int, + occupancy: int, + ) -> Tuple[int, int, int]: + """Computes the number of stages for A/B/C operands based on heuristics. + + :param tiled_mma: The tiled MMA object defining the core computation. + :type tiled_mma: cute.TiledMma + :param mma_tiler_mnk: The shape (M, N, K) of the MMA tiler. + :type mma_tiler_mnk: tuple[int, int, int] + :param a_dtype: Data type of operand A. + :type a_dtype: type[cutlass.Numeric] + :param b_dtype: Data type of operand B. + :type b_dtype: type[cutlass.Numeric] + :param epi_tile: The epilogue tile shape. + :type epi_tile: cute.Tile + :param c_dtype: Data type of operand C (output). + :type c_dtype: type[cutlass.Numeric] + :param c_layout: Layout enum of operand C. + :type c_layout: utils.LayoutEnum + :param sf_dtype: Data type of Scale factor. + :type sf_dtype: type[cutlass.Numeric] + :param sf_vec_size: Scale factor vector size. + :type sf_vec_size: int + :param smem_capacity: Total available shared memory capacity in bytes. + :type smem_capacity: int + :param occupancy: Target number of CTAs per SM (occupancy). + :type occupancy: int + + :return: A tuple containing the computed number of stages for: + (ACC stages, A/B operand stages, C stages) + :rtype: tuple[int, int, int] + """ + # ACC stages + num_acc_stage = 1 if mma_tiler_mnk[1] == 256 else 2 + + # Default C stages + num_c_stage = 2 + + # Calculate smem layout and size for one stage of A, B, SFA, SFB and C + a_smem_layout_stage_one = sm100_utils.make_smem_layout_a( + tiled_mma, + mma_tiler_mnk, + a_dtype, + 1, # a tmp 1 stage is provided + ) + b_smem_layout_staged_one = sm100_utils.make_smem_layout_b( + tiled_mma, + mma_tiler_mnk, + b_dtype, + 1, # a tmp 1 stage is provided + ) + sfa_smem_layout_staged_one = blockscaled_utils.make_smem_layout_sfa( + tiled_mma, + mma_tiler_mnk, + sf_vec_size, + 1, # a tmp 1 stage is provided + ) + sfb_smem_layout_staged_one = blockscaled_utils.make_smem_layout_sfb( + tiled_mma, + mma_tiler_mnk, + sf_vec_size, + 1, # a tmp 1 stage is provided + ) + + c_smem_layout_staged_one = sm100_utils.make_smem_layout_epi( + c_dtype, + c_layout, + epi_tile, + 1, + ) + + ab_bytes_per_stage = ( + cute.size_in_bytes(a_dtype, a_smem_layout_stage_one) + + cute.size_in_bytes(b_dtype, b_smem_layout_staged_one) + + cute.size_in_bytes(sf_dtype, sfa_smem_layout_staged_one) + + cute.size_in_bytes(sf_dtype, sfb_smem_layout_staged_one) + ) + mbar_helpers_bytes = 1024 + c_bytes_per_stage = cute.size_in_bytes(c_dtype, c_smem_layout_staged_one) + c_bytes = c_bytes_per_stage * num_c_stage + + # Calculate A/B/SFA/SFB stages: + # Start with total smem per CTA (capacity / occupancy) + # Subtract reserved bytes and initial C stages bytes + # Divide remaining by bytes needed per A/B/SFA/SFB stage + num_ab_stage = ( + smem_capacity // occupancy - (mbar_helpers_bytes + c_bytes) + ) // ab_bytes_per_stage + + # Refine epilogue stages: + # Calculate remaining smem after allocating for A/B/SFA/SFB stages and reserved bytes + # Add remaining unused smem to epilogue + num_c_stage += ( + smem_capacity + - occupancy * ab_bytes_per_stage * num_ab_stage + - occupancy * (mbar_helpers_bytes + c_bytes) + ) // (occupancy * c_bytes_per_stage) + + return num_acc_stage, num_ab_stage, num_c_stage + + @staticmethod + def _compute_grid( + c: cute.Tensor, + cta_tile_shape_mnk: Tuple[int, int, int], + cluster_shape_mn: Tuple[int, int], + max_active_clusters: cutlass.Constexpr, + ) -> Tuple[utils.PersistentTileSchedulerParams, Tuple[int, int, int]]: + """Use persistent tile scheduler to compute the grid size for the output tensor C. + + :param c: The output tensor C + :type c: cute.Tensor + :param cta_tile_shape_mnk: The shape (M, N, K) of the CTA tile. + :type cta_tile_shape_mnk: tuple[int, int, int] + :param cluster_shape_mn: Shape of each cluster in M, N dimensions. + :type cluster_shape_mn: tuple[int, int] + :param max_active_clusters: Maximum number of active clusters. + :type max_active_clusters: cutlass.Constexpr + + :return: A tuple containing: + - tile_sched_params: Parameters for the persistent tile scheduler. + - grid: Grid shape for kernel launch. + :rtype: Tuple[utils.PersistentTileSchedulerParams, tuple[int, int, int]] + """ + c_shape = cute.slice_(cta_tile_shape_mnk, (None, None, 0)) + gc = cute.zipped_divide(c, tiler=c_shape) + num_ctas_mnl = gc[(0, (None, None, None))].shape + cluster_shape_mnl = (*cluster_shape_mn, 1) + + tile_sched_params = utils.PersistentTileSchedulerParams( + num_ctas_mnl, cluster_shape_mnl + ) + grid = utils.StaticPersistentTileScheduler.get_grid_shape( + tile_sched_params, max_active_clusters + ) + + return tile_sched_params, grid + + @staticmethod + def is_valid_dtypes_and_scale_factor_vec_size( + ab_dtype: Type[cutlass.Numeric], + sf_dtype: Type[cutlass.Numeric], + sf_vec_size: int, + c_dtype: Type[cutlass.Numeric], + ) -> bool: + """ + Check if the dtypes and sf_vec_size are valid combinations + + :param ab_dtype: The data type of the A and B operands + :type ab_dtype: Type[cutlass.Numeric] + :param sf_dtype: The data type of the scale factor + :type sf_dtype: Type[cutlass.Numeric] + :param sf_vec_size: The vector size of the scale factor + :type sf_vec_size: int + :param c_dtype: The data type of the output tensor + :type c_dtype: Type[cutlass.Numeric] + + :return: True if the dtypes and sf_vec_size are valid, False otherwise + :rtype: bool + """ + is_valid = True + + # Check valid ab_dtype + if ab_dtype not in { + cutlass.Float4E2M1FN, + cutlass.Float8E5M2, + cutlass.Float8E4M3FN, + }: + is_valid = False + + # Check valid sf_vec_size + if sf_vec_size not in {16, 32}: + is_valid = False + + # Check valid sf_dtype + if sf_dtype not in {cutlass.Float8E8M0FNU, cutlass.Float8E4M3FN}: + is_valid = False + + # Check valid sf_dtype and sf_vec_size combinations + if sf_dtype == cutlass.Float8E4M3FN and sf_vec_size == 32: + is_valid = False + if ab_dtype in {cutlass.Float8E5M2, cutlass.Float8E4M3FN} and sf_vec_size == 16: + is_valid = False + + # Check valid c_dtype + if c_dtype not in { + cutlass.Float32, + cutlass.Float16, + cutlass.BFloat16, + cutlass.Float8E5M2, + cutlass.Float8E4M3FN, + }: + is_valid = False + + return is_valid + + @staticmethod + def is_valid_layouts( + ab_dtype: Type[cutlass.Numeric], + c_dtype: Type[cutlass.Numeric], + a_major: str, + b_major: str, + c_major: str, + ) -> bool: + """ + Check if layouts and dtypes are valid combinations + + :param ab_dtype: The data type of the A and B operands + :type ab_dtype: Type[cutlass.Numeric] + :param c_dtype: The data type of the output tensor + :type c_dtype: Type[cutlass.Numeric] + :param a_major: The major dimension of the A tensor + :type a_major: str + :param b_major: The major dimension of the B tensor + :type b_major: str + :param c_major: The major dimension of the C tensor + :type c_major: str + + :return: True if the layouts are valid, False otherwise + :rtype: bool + """ + is_valid = True + + if ab_dtype is cutlass.Float4E2M1FN and not (a_major == "k" and b_major == "k"): + is_valid = False + return is_valid + + @staticmethod + def is_valid_mma_tiler_and_cluster_shape( + mma_tiler_mn: Tuple[int, int], + cluster_shape_mn: Tuple[int, int], + ) -> bool: + """ + Check if the mma tiler and cluster shape are valid + + :param mma_tiler_mn: The (M, N) shape of the MMA instruction tiler + :type mma_tiler_mn: Tuple[int, int] + :param cluster_shape_mn: The (ClusterM, ClusterN) shape of the CTA cluster + :type cluster_shape_mn: Tuple[int, int] + + :return: True if the mma tiler and cluster shape are valid, False otherwise + :rtype: bool + """ + is_valid = True + # Skip invalid mma tile shape + if mma_tiler_mn[0] not in [128, 256]: + is_valid = False + if mma_tiler_mn[1] not in [64, 128, 192, 256]: + is_valid = False + # Skip illegal cluster shape + if cluster_shape_mn[0] % (2 if mma_tiler_mn[0] == 256 else 1) != 0: + is_valid = False + # Skip invalid cluster shape + is_power_of_2 = lambda x: x > 0 and (x & (x - 1)) == 0 + if ( + cluster_shape_mn[0] * cluster_shape_mn[1] > 16 + or cluster_shape_mn[0] <= 0 + or cluster_shape_mn[1] <= 0 + # Special cluster shape check for scale factor multicasts. + # Due to limited size of scale factors, we can't multicast among more than 4 CTAs. + or cluster_shape_mn[0] > 4 + or cluster_shape_mn[1] > 4 + or not is_power_of_2(cluster_shape_mn[0]) + or not is_power_of_2(cluster_shape_mn[1]) + ): + is_valid = False + return is_valid + + @staticmethod + def is_valid_tensor_alignment( + m: int, + n: int, + k: int, + l: int, + ab_dtype: Type[cutlass.Numeric], + c_dtype: Type[cutlass.Numeric], + a_major: str, + b_major: str, + c_major: str, + ) -> bool: + """ + Check if the tensor alignment is valid + + :param m: The number of rows in the A tensor + :type m: int + :param n: The number of columns in the B tensor + :type n: int + :param k: The number of columns in the A tensor + :type k: int + :param l: The number of columns in the C tensor + :type l: int + :param ab_dtype: The data type of the A and B operands + :type ab_dtype: Type[cutlass.Numeric] + :param c_dtype: The data type of the output tensor + :type c_dtype: Type[cutlass.Numeric] + :param a_major: The major axis of the A tensor + :type a_major: str + :param b_major: The major axis of the B tensor + :type b_major: str + :param c_major: The major axis of the C tensor + :type c_major: str + + :return: True if the problem shape is valid, False otherwise + :rtype: bool + """ + is_valid = True + + def check_contigous_16B_alignment(dtype, is_mode0_major, tensor_shape): + major_mode_idx = 0 if is_mode0_major else 1 + num_major_elements = tensor_shape[major_mode_idx] + num_contiguous_elements = 16 * 8 // dtype.width + return num_major_elements % num_contiguous_elements == 0 + + if ( + not check_contigous_16B_alignment(ab_dtype, a_major == "m", (m, k, l)) + or not check_contigous_16B_alignment(ab_dtype, b_major == "n", (n, k, l)) + or not check_contigous_16B_alignment(c_dtype, c_major == "m", (m, n, l)) + ): + is_valid = False + return is_valid + + @staticmethod + def can_implement( + ab_dtype: Type[cutlass.Numeric], + sf_dtype: Type[cutlass.Numeric], + sf_vec_size: int, + c_dtype: Type[cutlass.Numeric], + mma_tiler_mn: Tuple[int, int], + cluster_shape_mn: Tuple[int, int], + m: int, + n: int, + k: int, + l: int, + a_major: str, + b_major: str, + c_major: str, + ) -> bool: + """ + Check if the gemm can be implemented + + :param ab_dtype: The data type of the A and B operands + :type ab_dtype: Type[cutlass.Numeric] + :param sf_dtype: The data type of the scale factor tensor + :type sf_dtype: Type[cutlass.Numeric] + :param sf_vec_size: The vector size + :type sf_vec_size: int + :param c_dtype: The data type of the output tensor + :type c_dtype: Type[cutlass.Numeric] + :param mma_tiler_mn: The (M, N) shape of the MMA instruction tiler + :type mma_tiler_mn: Tuple[int, int] + :param cluster_shape_mn: The (ClusterM, ClusterN) shape of the CTA cluster + :type cluster_shape_mn: Tuple[int, int] + :param m: The number of rows in the A tensor + :type m: int + :param n: The number of columns in the B tensor + :type n: int + :param k: The number of columns in the A tensor + :type k: int + :param l: The number of columns in the C tensor + :type l: int + :param a_major: The major axis of the A tensor + :type a_major: str + :param b_major: The major axis of the B tensor + :type b_major: str + :param c_major: The major axis of the C tensor + :type c_major: str + + :return: True if the gemm can be implemented, False otherwise + :rtype: bool + """ + can_implement = True + # Skip unsupported types + if not Sm100BlockScaledPersistentDenseGemmKernel.is_valid_dtypes_and_scale_factor_vec_size( + ab_dtype, sf_dtype, sf_vec_size, c_dtype + ): + can_implement = False + # Skip unsupported layouts + if not Sm100BlockScaledPersistentDenseGemmKernel.is_valid_layouts( + ab_dtype, c_dtype, a_major, b_major, c_major + ): + can_implement = False + # Skip invalid mma tile shape and cluster shape + if not Sm100BlockScaledPersistentDenseGemmKernel.is_valid_mma_tiler_and_cluster_shape( + mma_tiler_mn, cluster_shape_mn + ): + can_implement = False + # Skip illegal problem shape for load/store alignment + if not Sm100BlockScaledPersistentDenseGemmKernel.is_valid_tensor_alignment( + m, n, k, l, ab_dtype, c_dtype, a_major, b_major, c_major + ): + can_implement = False + return can_implement + + +@cute.jit +def cvt_sf_MKL_to_M32x4xrm_K4xrk_L( + sf_ref_tensor: cute.Tensor, + sf_mma_tensor: cute.Tensor, +): + """Convert scale factor tensor from MKL layout to mma specification M(32x4xrest_m)xK(4xrest_k)xL layout""" + # sf_mma_tensor has flatten shape (32, 4, rest_m, 4, rest_k, l) + # group to ((32, 4, rest_m), (4, rest_k), l) + sf_mma_tensor = cute.group_modes(sf_mma_tensor, 0, 3) + sf_mma_tensor = cute.group_modes(sf_mma_tensor, 1, 3) + for i in cutlass.range(cute.size(sf_ref_tensor)): + mkl_coord = sf_ref_tensor.layout.get_hier_coord(i) + sf_mma_tensor[mkl_coord] = sf_ref_tensor[mkl_coord] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/dense_gemm_efc.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/dense_gemm_efc.py new file mode 100644 index 0000000000000000000000000000000000000000..fbc2b243f08a4305dcb5d07a5801b77df07b19ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/dense_gemm_efc.py @@ -0,0 +1,2621 @@ +# Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: BSD-3-Clause +# ruff: noqa: S101 + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import types +import typing + +import cuda.bindings.driver as cuda # pyrefly: ignore [missing-import] + +import cutlass +import cutlass.cute as cute +import cutlass.operators.providers.cutedsl.evt.common_efc as common_efc +import cutlass.pipeline as pipeline +import cutlass.utils as utils +import cutlass.utils.blackwell_helpers as sm100_utils +from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.operators.providers.cutedsl.evt.common_efc import log + +from torch._inductor.kernel.gemm_epilogue import GemmReductionDescriptor +from torch._inductor.kernel.vendored_templates.cutedsl.reduction_utils import ( + get_lane_warp_layouts, + partition_for_epilogue, +) +from torch.utils._ordered_set import OrderedSet + + +""" +Common base infrastructure for high-performance persistent batched dense GEMM with custom epilogue fusion +for the NVIDIA Blackwell SM100 architecture using CUTE DSL and Epilogue Fusion Configuration (EFC). + +This module provides the PersistentDenseGemmEFCKernel base class that implements the core GEMM +functionality with support for custom epilogue operations. Subclasses define specific epilogue +configurations by providing an epilogue function that operates on the accumulator and supplemental +tensors. + +Key Features: + - Utilizes Tensor Memory Access (TMA) for efficient memory operations + - Utilizes Blackwell's tcgen05.mma for matrix multiply-accumulate (MMA) operations (including 2CTA MMA instructions) + - Implements TMA multicast with cluster to reduce L2 memory traffic + - Supports persistent tile scheduling to better overlap memory load/store with MMA across tiles + - Supports warp specialization to avoid explicit pipelining between mainloop load and MMA + - Uses Epilogue Fusion Configuration (EFC) to define custom epilogue operations + +GEMM Execution Flow: +1. DMA warp: Load A and B matrices from global memory (GMEM) to shared memory (SMEM) using TMA operations. +2. MMA warp: Perform matrix multiply-accumulate (MMA) operations using tcgen05.mma instruction. +3. EPILOGUE warp (customizable via EFC): + - Load completed accumulator from tensor memory (TMEM) to registers (RMEM) using tcgen05.ld. + - Load supplemental input tensors from GMEM to SMEM using TMA, then to RMEM. + - Execute custom epilogue function (defined by subclass) that: + * Accesses the accumulator via efc_config.accum() + * Reads from supplemental input tensors via tensor.load() + * Writes to supplemental output tensors via tensor.store() + * Can apply arbitrary element-wise operations, scaling, and fusion + - Store result tensors from RMEM to SMEM to GMEM with TMA operations. + +SM100 tcgen05.mma instructions operate as follows: +- Read matrix A from SMEM +- Read matrix B from SMEM +- Write accumulator to TMEM +The accumulator in TMEM must then be loaded to registers before writing back to GMEM. + +Base Tensor Dimensions: +- Matrix A is MxKxL, L is batch dimension, A can be row-major("K") or column-major("M") +- Matrix B is NxKxL, L is batch dimension, B can be row-major("N") or column-major("K") +- Supplemental tensors are MxNxL with layout matching the epilogue configuration + +Common Constraints: +* Supported input data types: fp16, bf16, tf32, int8, uint8, fp8 (e4m3fn, e5m2) +* A/B tensors must have the same data type +* MMA tiler M must be 64/128 (use_2cta_instrs=False) or 128/256 (use_2cta_instrs=True) +* MMA tiler N must be 32-256, step 32 +* Cluster shape M/N must be positive and power of 2, total cluster size <= 16 +* Cluster shape M must be multiple of 2 if use_2cta_instrs=True +* The contiguous dimension of all tensors must be at least 16 bytes aligned, + i.e., number of elements is a multiple of 4, 8, and 16 for TFloat32, + Float16/BFloat16, and Int8/Uint8/Float8, respectively. +* OOB tiles are not allowed when TMA store is disabled + +Subclass Examples: +- custom_epilogue_dense_gemm.py: Custom fused epilogue with multiple read/write tensors +- broadcast_custom_epilogue_dense_gemm.py: Broadcasting and mode remapping with transposed tensors +- activation_custom_epilogue_dense_gemm.py: Activation functions with Ada FP8 GEMM epilogue pattern +- synthetic_custom_epilogue_dense_gemm.py: Synthetic epilogue for testing with configurable tensor counts + +Writing an Epilogue Function (EFC User Guide) +============================================== + +The Epilogue Fusion Configuration (EFC) lets you define custom epilogue +operations as a plain Python function. The framework analyzes the +function signature, JIT-compiles it for the GPU kernel, and also +executes it on the CPU with PyTorch for automatic verification. + +Function Signature +------------------ + +The epilogue function must follow this contract: + + def epilogue(efc_config, , , ...): + ... + +- The first parameter **must** be named ``efc_config``. It is an + ``EFC.Configuration`` instance that provides access to the GEMM + accumulator, activation functions, and mode remapping. +- The remaining parameters are user-defined. Their names must match + the supplemental arguments passed to the GEMM ``compile()`` call. +- **Tensor** parameters correspond to ``cutlass.cute.Tensor`` values + and support ``.load()`` / ``.store()`` operations. +- **Scalar** parameters (``float``, ``int``, etc.) are used directly + in arithmetic expressions without ``.load()``. +- The function does **not** return a value. Results are written via + ``.store()`` on tensor parameters. At least one ``.store()`` call + is required for a useful computation. + +Accessing the Accumulator +~~~~~~~~~~~~~~~~~~~~~~~~~ + +``efc_config.accum()`` returns the GEMM accumulator (the result of +A * B). It can be called multiple times within the same epilogue:: + + def epilogue(efc_config, D): + D.store(efc_config.accum()) + +Loading and Storing Tensors +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tensor parameters expose two operations: + +- ``tensor.load()`` — reads the tensor value (marks it as an input). +- ``tensor.store(value)`` — writes a computed value (marks it as an output). + +A tensor can be both loaded and stored (read-modify-write). When +using multiple tensors, all ``.load()`` calls should be issued before +any ``.store()`` calls:: + + def epilogue(efc_config, C, D, alpha, beta): + D.store(efc_config.accum() * alpha + C.load() * beta) + +Activation Functions +~~~~~~~~~~~~~~~~~~~~ + +The ``efc_config`` object provides built-in activation functions: + +- ``efc_config.identity(x)`` — f(x) = x +- ``efc_config.relu(x)`` — f(x) = max(0, x) +- ``efc_config.leaky_relu(x, negative_slope=0.01)`` +- ``efc_config.tanh(x)`` +- ``efc_config.sigmoid(x)`` — f(x) = 1 / (1 + exp(-x)) +- ``efc_config.silu(x)`` — f(x) = x * sigmoid(x) (Swish) +- ``efc_config.hardswish(x)`` — f(x) = x * relu6(x + 3) / 6 +- ``efc_config.gelu(x)`` + +Example:: + + def epilogue(efc_config, C, D, alpha, beta): + D.store(efc_config.relu(efc_config.accum() * alpha + C.load() * beta)) + +Element-wise Utilities +~~~~~~~~~~~~~~~~~~~~~~ + +- ``efc_config.maximum(x, y)`` — element-wise maximum +- ``efc_config.minimum(x, y)`` — element-wise minimum + +Additionally, any method called on ``efc_config`` that is not +explicitly defined is dispatched to ``cutlass.cute.()`` on GPU +and ``torch.()`` during PyTorch verification. This gives access +to functions like ``efc_config.abs(x)``, ``efc_config.exp(x)``, +``efc_config.sqrt(x)``, ``efc_config.clamp(x, min, max)``, +``efc_config.full_like(x, value)``, etc. + +Broadcasting and Mode Remapping +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When supplemental tensors have fewer dimensions or a different mode +ordering than the output tensor, use ``tensor.remap_modes[...]`` to +broadcast or transpose them:: + + tensor.remap_modes[] + +The target shape is implicitly the output shape ``(m, n, l)`` derived +from the GEMM input matrices ``A(m, k, l)`` and ``B(n, k, l)``. + +The subscript uses Python's ``__getitem__`` syntax where each element +is either: + +- An **integer** — the index of the source mode to place at this + position. +- ``:`` — broadcast the source along this dimension (stride 0). + +The returned remapped tensor proxy supports ``.load()`` and +``.store()`` just like regular tensor parameters. + +Examples (output is (M, N, L)): + +- **Broadcast along M** — ``C`` is (N, L):: + + C.remap_modes[:, 0, 1].load() + +- **Broadcast along N** — ``X`` is (M, L):: + + X.remap_modes[0, :, 1].load() + +- **Scalar broadcast** — ``x_factor`` is a 0-d tensor:: + + x_factor.remap_modes[:, :, :].load() + +- **Transpose** — ``Y`` is (N, M, L):: + + Y.remap_modes[1, 0, 2].store(value) + +A remapped tensor can also be both loaded and stored for +read-modify-write on a transposed layout:: + + remapped_Y = Y.remap_modes[1, 0, 2] + remapped_Y.store(efc_config.accum() + remapped_Y.load()) + +Complete Examples +~~~~~~~~~~~~~~~~~ + +**Alpha-beta scaling** (simplest useful epilogue):: + + def epilogue(efc_config, C, D, alpha, beta): + D.store(efc_config.accum() * alpha + C.load() * beta) + +**Multi-tensor with activation**:: + + def epilogue(efc_config, C, D, alpha, beta, X, x_factor, Y): + Y.store(efc_config.accum()) + result = ( + efc_config.relu(efc_config.accum() * alpha + C.load() * beta) + + X.load() * x_factor + ) + D.store(result) + +**Ada FP8 GEMM pattern with dynamic activation**:: + + def epilogue(efc_config, C, Aux, alpha, beta, bias, + scale_a, scale_b, scale_c, D, leaky_relu_alpha): + aux_val = ( + (alpha * scale_a * scale_b) * efc_config.accum() + + (beta * scale_c) * C.load() + + bias + ) + Aux.store(aux_val) + D.store(efc_config.relu(aux_val)) + +**Broadcasting with mode remapping**:: + + def epilogue(efc_config, C, D, alpha, beta, X, x_factor, Y): + # Y is (N, M, L), output is (M, N, L): transpose via [1, 0, 2] + Y.remap_modes[1, 0, 2].store(efc_config.accum()) + # C is (N, L): broadcast along M via [:, 0, 1] + # X is (M, L): broadcast along N via [0, :, 1] + result = ( + efc_config.relu( + efc_config.accum() * alpha + + C.remap_modes[:, 0, 1].load() * beta + ) + + X.remap_modes[0, :, 1].load() + * x_factor.remap_modes[:, :, :].load() + ) + D.store(result) +""" + + +class PersistentDenseGemmEFCKernel: + """Base class for batched GEMM with custom epilogue fusion using EFC. + + This class provides the core infrastructure for persistent batched GEMM operations + with customizable epilogue fusion. Subclasses define specific epilogue behaviors + by providing an epilogue configuration function that describes operations on the + accumulator and supplemental tensors. + + The class handles: + - GEMM mainloop (A * B computation) + - TMA-based memory operations + - Warp specialization + - Persistent tile scheduling + - EFC (Epilogue Fusion Configuration) integration + - Tensor creation and validation + + :param acc_dtype: Data type for accumulation during computation + :type acc_dtype: type[cutlass.Numeric] + :param epi_dtype: Data type for epilogue operation + :type epi_dtype: type[cutlass.Numeric] + :param use_2cta_instrs: Whether to use CTA group 2 for advanced thread cooperation + :type use_2cta_instrs: bool + :param mma_tiler_mn: Shape of the Matrix Multiply-Accumulate (MMA) tile (M,N) + :type mma_tiler_mn: tuple[int, int] + :param cluster_shape_mn: Cluster dimensions (M,N) for parallel processing + :type cluster_shape_mn: tuple[int, int] + :param epilogue_function_configuration: Function defining the epilogue behavior via EFC + :type epilogue_function_configuration: Callable + + :note: Supported A/B data types: + - TFloat32 + - Float16/BFloat16 + - Int8/Uint8 + - Float8E4M3FN/Float8E5M2 + (A and B must have the same data type) + + :note: Supported accumulator data types: + - Float32 (for all floating point A/B data types) + - Float16 (only for fp16 and fp8 A/B data types) + - Int32 (only for uint8/int8 A/B data types) + + :note: Supported supplemental tensor data types (epilogue-dependent): + - Float32 (for float32 and int32 accumulator data types) + - Int32 (for float32 and int32 accumulator data types) + - Float16/BFloat16 (for fp16 and fp8 accumulator data types) + - Int8/Uint8 (for uint8/int8 accumulator data types) + - Float8E4M3FN/Float8E5M2 (for float32 accumulator data types) + + :note: Constraints: + - MMA tiler M must be 64/128 (use_2cta_instrs=False) or 128/256 (use_2cta_instrs=True) + - MMA tiler N must be 32-256, step 32 + - Cluster shape M must be multiple of 2 if use_2cta_instrs=True + - Cluster shape M/N must be positive and power of 2, total cluster size <= 16 + """ + + def __init__( + self, + acc_dtype: type[cutlass.Numeric], + epi_dtype: type[cutlass.Numeric], + use_2cta_instrs: bool, + mma_tiler_mn: tuple[int, int], + cluster_shape_mn: tuple[int, int], + epilogue_function_configuration: typing.Callable, + ): + """Initializes the configuration for a Blackwell dense GEMM kernel with EFC. + + This configuration includes several key aspects: + + 1. MMA Instruction Settings (tcgen05): + - acc_dtype: Data type for MMA accumulator. + - mma_tiler_mn: The (M, N) shape of the MMA instruction tiler. + - use_2cta_instrs: Boolean indicating if the tcgen05 MMA variant + with cta_group=2 should be used. + + 2. Cluster Shape: + - cluster_shape_mn: The (ClusterM, ClusterN) shape of the CTA cluster. + + 3. Epilogue Configuration: + - epilogue_function_configuration: Defines custom epilogue behavior + that operates on accumulator and supplemental tensors. + + :param acc_dtype: Data type of the accumulator. + :type acc_dtype: type[cutlass.Numeric] + :param epi_dtype: Data type of the epilogue. + :type epi_dtype: type[cutlass.Numeric] + :param use_2cta_instrs: Boolean, True to use cta_group=2 MMA variant. + :type use_2cta_instrs: bool + :param mma_tiler_mn: tuple (M, N) shape of the MMA instruction. + :type mma_tiler_mn: tuple[int, int] + :param cluster_shape_mn: tuple (ClusterM, ClusterN) shape of the cluster. + :type cluster_shape_mn: tuple[int, int] + :param epilogue_function_configuration: Function defining epilogue behavior via EFC. + :type epilogue_function_configuration: Callable + """ + self.acc_dtype: type[cutlass.Numeric] = acc_dtype + self.epi_dtype: type[cutlass.Numeric] = epi_dtype + self.use_2cta_instrs = use_2cta_instrs + self.cluster_shape_mn = cluster_shape_mn + # K dimension is deferred in _setup_attributes + self.mma_tiler_mn = mma_tiler_mn + self.mma_tiler = (*mma_tiler_mn, 1) + self.arch = "sm_100" + + self.c_dtype = self.epi_dtype + + self.cta_group = ( + tcgen05.CtaGroup.TWO if self.use_2cta_instrs else tcgen05.CtaGroup.ONE + ) + + self.occupancy = 1 + # Set specialized warp ids: + + # The warps responsible for computing the epilogue function and storing + # the results. + self.epilogue_warp_id = (0, 1, 2, 3) + # The warp responsible for computing the matrix multiplication. + self.mma_warp_id = 4 + # The warp responsible for loading the tensors A & B to feed the MMA. + self.tma_warp_id = 5 + # The warp responsible for loading the auxiliary tensors used in the epilogue. + self.epilogue_load_warp_id = 6 + self.threads_per_cta = 32 * len( + ( + self.mma_warp_id, + self.tma_warp_id, + *self.epilogue_warp_id, + self.epilogue_load_warp_id, + ) + ) + # Barrier ids for cta sync, epilogue sync and tmem ptr sync. + self.epilogue_sync_bar_id = 1 + self.tmem_alloc_sync_bar_id = 2 + self.tmem_dealloc_sync_bar_id = 3 + # Amount of available shared memory. + self.smem_capacity = utils.get_smem_capacity_in_bytes(self.arch) + + # Setup the EFC from the given function representing the epilogue + # configuration. + self.efc = common_efc.EFC(self, epilogue_function_configuration) + + def _create_tiled_mma(self): + """Make a tiled MMA atom with given data type, leading dimension, CTA + group and MMA tile shape. Use SMEM operand source for A. + """ + return utils.sm100.make_trivial_tiled_mma( + self.a_dtype, + self.b_dtype, + self.a_major_mode, + self.b_major_mode, + self.acc_dtype, + self.cta_group, + self.mma_tiler[:2], + ) + + def _setup_attributes(self): + """Set up configurations that are dependent on GEMM inputs + + This method configures various attributes based on the input tensor properties + (data types, leading dimensions) and kernel settings: + - Configuring tiled MMA + - Computing MMA/cluster/tile shapes + - Computing cluster layout + - Computing multicast CTAs for A/B + - Computing epilogue subtile + - Setting up A/B/C/D stage counts in shared memory + - Computing A/B/C/D shared memory layout + - Computing tensor memory allocation columns + """ + # Get the right tiled MMA. + self._tiled_mma = self._create_tiled_mma() + log(f"{self._tiled_mma = !s}") + + # Compute mma/cluster/tile shapes + mma_inst_shape_k = cute.size(self._tiled_mma.shape_mnk, mode=[2]) + mma_inst_tile_k = 4 + # Extend mma_tiler with k-dimension (MMA_M, MMA_N, MMA_K) + self.mma_tiler = ( + self.mma_tiler[0], + self.mma_tiler[1], + mma_inst_shape_k * mma_inst_tile_k, + ) + log(f"{self.mma_tiler = !s}") + # CTA tiler with the 2CTA instruction correction. + self.cta_tile_shape_mnk = ( + self.mma_tiler[0] // cute.size(self._tiled_mma.thr_id.shape), + self.mma_tiler[1], + self.mma_tiler[2], + ) + log(f"{self.cta_tile_shape_mnk = !s}") + # Compute cluster layout, V for the 2CTA instructions. + self.cluster_layout_vmnk = cute.tiled_divide( + cute.make_layout((*self.cluster_shape_mn, 1)), + (self._tiled_mma.thr_id.shape,), + ) + log(f"{cute.make_layout((*self.cluster_shape_mn, 1)) = !s}") + log(f"{self.cluster_layout_vmnk = !s}") + # Compute number of multicast CTAs for A/B + self.num_mcast_ctas_a = cute.size(self.cluster_layout_vmnk.shape[2]) + self.num_mcast_ctas_b = cute.size(self.cluster_layout_vmnk.shape[1]) + self.is_a_mcast = self.num_mcast_ctas_a > 1 + self.is_b_mcast = self.num_mcast_ctas_b > 1 + log(f"{self.num_mcast_ctas_a = }, {self.num_mcast_ctas_b = }") + log(f"{self.is_a_mcast = }, {self.is_b_mcast = }") + + # Compute epilogue (EPI_TILE_M, EPI_TILE_N) subtile of cta_tile_shape_mnk + # according to some heuristics. + self.epi_tile = sm100_utils.compute_epilogue_tile_shape( + self.cta_tile_shape_mnk, + self.use_2cta_instrs, + layout_d=self.d_layout, + elem_ty_d=self.d_dtype, + layout_c=self.c_layout, + elem_ty_c=self.c_dtype, + ) + self.epi_tile_m = cute.size(self.epi_tile[0]) + self.epi_tile_n = cute.size(self.epi_tile[1]) + self.has_cross_warp_local_reduce = cutlass.const_expr( + (self.has_local_reduce_tensor or self.local_reduce_feeds_main) + and ( + ( + self.local_reduce_axis == 0 + and (self.local_reduce_group > 4 or self.local_reduce_feeds_main) + ) + or ( + self.local_reduce_axis == 1 + and self.local_reduce_group > self.epi_tile_n + ) + ) + ) + self.local_reduce_smem_rows = ( + self.cta_tile_shape_mnk[1] + if self.local_reduce_axis == 0 + else self.cta_tile_shape_mnk[0] + ) + self.local_reduce_smem_cols = ( + 3 + self.cta_tile_shape_mnk[0] // self.local_reduce_group + if self.local_reduce_feeds_main and self.local_reduce_axis == 0 + else max( + 3, + self.local_reduce_group // self.epi_tile_n + if self.local_reduce_axis == 1 + else 3, + ) + ) + self.local_reduce_smem_bytes = ( + self.local_reduce_smem_rows * self.local_reduce_smem_cols * 4 + if self.has_cross_warp_local_reduce + else 0 + ) + log(f"{self.epi_tile = !s}") + + # Setup A/B/C/D pipeline stage count in shared memory and ACC stage + # count in tensor memory. + self.compute_stages() + log(f"{self.num_acc_stage = }, {self.num_ab_stage = }, {self.num_c_stage = }") + # Compute A/B shared memory layout + self.a_smem_layout_staged = sm100_utils.make_smem_layout_a( + self._tiled_mma, + self.mma_tiler, + self.a_dtype, + self.num_ab_stage, + ) + log(f"{self.a_smem_layout_staged = !s}") + self.b_smem_layout_staged = sm100_utils.make_smem_layout_b( + self._tiled_mma, + self.mma_tiler, + self.b_dtype, + self.num_ab_stage, + ) + log(f"{self.b_smem_layout_staged = !s}") + # Get the smem_layout for the tensors used in the EFC. + self.efc.jit.smem_layout() + + # Compute the number of tensor memory allocation columns + self.compute_num_tmem_alloc_cols() + + @cute.jit + def __call__( + self, + a: cute.Tensor, + b: cute.Tensor, + max_active_clusters: cutlass.Constexpr, + stream: cuda.CUstream, + local_reduce_tensor: cute.Tensor, + local_reduce_feed_tensor: cute.Tensor, + local_reduce_secondary_feed_tensor: cute.Tensor, + local_reduce_group: cutlass.Constexpr, + local_reduce_axis: cutlass.Constexpr, + local_reduce_type: cutlass.Constexpr, + local_reduce_source: cutlass.Constexpr, + local_reduce_feeds_main: cutlass.Constexpr, + local_reduce_secondary_feed_type: cutlass.Constexpr, + local_reduce_op: cutlass.Constexpr, + local_reduce_init: cutlass.Constexpr, + local_reduce_combine: cutlass.Constexpr, + local_reduce_source_op: cutlass.Constexpr, + local_reduce_finalize: cutlass.Constexpr, + *supplemental_parameters, + ): + """Execute the GEMM operation in steps: + - Setup static attributes before smem/grid/tma computation + - Setup TMA load/store atoms and tensors + - Compute grid size with regard to hardware constraints + - Define shared storage for kernel + - Launch the kernel synchronously + + :param a: Input tensor A in (L, M, K) or (M, K) layout. + :type a: cute.Tensor + :param b: Input tensor B in (L, K, N) or (K, N) layout. + :type b: cute.Tensor + :param max_active_clusters: Maximum number of active clusters. + :type max_active_clusters: cutlass.Constexpr + :param stream: CUDA stream for asynchronous execution. + :type stream: cuda.CUstream + :param supplemental_parameters: Variadic epilogue parameters (tensors and scalars). + :raises TypeError: If input data types are incompatible with the MMA instruction. + :raises AssertionError: If OOB (Out-Of-Bounds) tiles are present when TMA store is disabled. + + """ + + def add_batch_mode(tensor: cute.Tensor) -> cute.Tensor: + return cute.make_tensor( + tensor.iterator, + cute.prepend(tensor.layout, cute.make_layout(1), up_to_rank=3), + ) + + a = add_batch_mode(a) + b = add_batch_mode(b) + if cutlass.const_expr(local_reduce_tensor is not None): + local_reduce_tensor = add_batch_mode(local_reduce_tensor) + if cutlass.const_expr(local_reduce_feed_tensor is not None): + local_reduce_feed_tensor = add_batch_mode(local_reduce_feed_tensor) + local_reduce_feed_tensor = cute.make_tensor( + local_reduce_feed_tensor.iterator, + cute.select(local_reduce_feed_tensor.layout, [1, 2, 0]), + ) + if cutlass.const_expr(local_reduce_secondary_feed_tensor is not None): + local_reduce_secondary_feed_tensor = add_batch_mode( + local_reduce_secondary_feed_tensor + ) + local_reduce_secondary_feed_tensor = cute.make_tensor( + local_reduce_secondary_feed_tensor.iterator, + cute.select(local_reduce_secondary_feed_tensor.layout, [1, 2, 0]), + ) + + # Permute tensor modes from torch to cute convention + # A: (L, M, K) -> (M, K, L) + a = cute.make_tensor(a.iterator, cute.select(a.layout, [1, 2, 0])) + # B: (L, K, N) -> (N, K, L) + b = cute.make_tensor(b.iterator, cute.select(b.layout, [2, 1, 0])) + self.local_reduce_group = local_reduce_group + self.local_reduce_axis = local_reduce_axis + self.local_reduce_input_coefficient = 1.0 + self.local_reduce_result_coefficient = 0.0 + self.local_reduce_bias = 0.0 + self.local_reduce_affine_scale = 1.0 + self.local_reduce_affine_bias = 0.0 + self.local_reduce_denominator_scale = 1.0 + self.local_reduce_denominator_bias = 0.0 + self.local_reduce_secondary_scale = 1.0 + self.local_reduce_secondary_bias = 0.0 + self.local_reduce_variance_scale = 1.0 + self.local_reduce_variance_bias = 0.0 + self.local_reduce_direct_bool = False + self.local_reduce_secondary_reuses_primary = False + secondary_expression = ( + GemmReductionDescriptor.parse(local_reduce_secondary_feed_type) + if local_reduce_secondary_feed_type is not None + else None + ) + secondary_parameters = ( + () if secondary_expression is None else secondary_expression.parameters + ) + if cutlass.const_expr( + secondary_expression is not None + and secondary_expression.kind == "sum_mul_affine" + ): + secondary_scale, secondary_bias = secondary_parameters + self.local_reduce_secondary_scale = float(secondary_scale) + self.local_reduce_secondary_bias = float(secondary_bias) + elif cutlass.const_expr( + secondary_expression is not None + and secondary_expression.kind == "direct_bool_gt_zero" + ): + self.local_reduce_direct_bool = True + elif cutlass.const_expr(local_reduce_secondary_feed_type is not None): + self.local_reduce_secondary_reuses_primary = True + reduction_expression = GemmReductionDescriptor.parse(local_reduce_type) + local_reduce_type = reduction_expression.kind + if cutlass.const_expr(local_reduce_type == "mean_linear"): + input_coefficient, result_coefficient, bias = ( + reduction_expression.parameters + ) + self.local_reduce_input_coefficient = float(input_coefficient) + self.local_reduce_result_coefficient = float(result_coefficient) + self.local_reduce_bias = float(bias) + elif cutlass.const_expr(local_reduce_type == "variance_affine"): + variance_scale, variance_bias = reduction_expression.parameters + local_reduce_type = "variance" + self.local_reduce_variance_scale = float(variance_scale) + self.local_reduce_variance_bias = float(variance_bias) + elif cutlass.const_expr(local_reduce_type == "normalize_sum_affine"): + ( + affine_scale, + affine_bias, + denominator_scale, + denominator_bias, + ) = reduction_expression.parameters + local_reduce_type = "normalize_sum" + self.local_reduce_affine_scale = float(affine_scale) + self.local_reduce_affine_bias = float(affine_bias) + self.local_reduce_denominator_scale = float(denominator_scale) + self.local_reduce_denominator_bias = float(denominator_bias) + elif cutlass.const_expr(local_reduce_type == "normalize_sum_reverse_affine"): + ( + affine_scale, + affine_bias, + denominator_scale, + denominator_bias, + ) = reduction_expression.parameters + local_reduce_type = "normalize_sum_reverse" + self.local_reduce_affine_scale = float(affine_scale) + self.local_reduce_affine_bias = float(affine_bias) + self.local_reduce_denominator_scale = float(denominator_scale) + self.local_reduce_denominator_bias = float(denominator_bias) + self.local_reduce_type = local_reduce_type + self.local_reduce_source = local_reduce_source + self.local_reduce_feeds_main = local_reduce_feeds_main + self.local_reduce_op = local_reduce_op + self.local_reduce_init = local_reduce_init + self.local_reduce_combine = local_reduce_combine + self.local_reduce_source_op = local_reduce_source_op + self.local_reduce_finalize = local_reduce_finalize + self.has_local_reduce_tensor = local_reduce_tensor is not None + # Identify parameters that are remap_modes sources (broadcast tensors). + # These skip add_batch_mode + permute entirely — they are passed as-is + # to the EFC and remap_modes inside the kernel handles all the layout + # work (broadcast expansion, dimension reordering). + remap_sources = OrderedSet( + [ + attrs.mapped_source + for attrs in self.efc.parameter_attributes.values() + if attrs.mapped_source + ] + ) + + # Add batch mode and permute epilogue parameters, except for + # broadcast remap sources which are passed untouched. + param_names = self.efc.epilogue_parameter_names + supplemental_parameters = ( + # Broadcast source: pass through untouched. + t + if name in remap_sources + # Regular tensor: (L, M, N) -> rank 3 -> (M, N, L). + else cute.make_tensor( + add_batch_mode(t).iterator, + cute.select(add_batch_mode(t).layout, [1, 2, 0]), + ) + if isinstance(t, cute.Tensor) + # Scalar: pass through. + else t + for name, t in zip(param_names, supplemental_parameters) + ) + + # Process the variadic parameters. + self.efc.jit.unpack_parameters(supplemental_parameters) + + # - Matrix A is MxKxL, L is batch dimension, A can be row-major("K") or column-major("M") + # - Matrix B is NxKxL, L is batch dimension, B can be row-major("N") or column-major("K") + # - Supplemental tensors are MxNxL with layout matching the epilogue configuration + + # The output shape (m, n, l) is derived from A(m, k, l) and B(n, k, l). + self.efc.output_shape = (a.shape[0], b.shape[0], a.shape[2]) + self.efc.jit.handle_remapping() + + # Setup static attributes before smem/grid/tma computation + self.a_dtype: type[cutlass.Numeric] = a.element_type + self.b_dtype: type[cutlass.Numeric] = b.element_type + self.a_major_mode = utils.LayoutEnum.from_tensor(a).mma_major_mode() + self.b_major_mode = utils.LayoutEnum.from_tensor(b).mma_major_mode() + + # Gather all the auxiliary tensor element data types. + self.efc.jit.record_tensor_dtypes() + + # There is no D tensor to be used as a returned tensor. In the + # following, D is used more like a "store" concept. So use the + # written tensor with the biggest element_type to set up all the tiling + # heuristics and epilogue store pipeline. + self.d_name_bigger = self.efc.jit.written_tensor_name_with_bigger_element_type() + d = self.efc.jit.parameter[self.d_name_bigger] + self.d_dtype: type[cutlass.Numeric] = d.element_type + self.d_layout = utils.LayoutEnum.from_tensor(d) + log(f"d{self.d_name_bigger} = {d!s}") + + # C is the read tensor with the biggest element_type, if any, used by + # some heuristics for tiling. + self.c_dtype = typing.cast(type[cutlass.Numeric], None) + self.c_layout = None + self.c_name_bigger = self.efc.jit.read_tensor_name_with_bigger_element_type() + if cutlass.const_expr(self.c_name_bigger): + # The tensor with the biggest data type might be a broadcast vector. + c = self.efc.jit.get_remapped_tensor_or_itself(self.c_name_bigger) + log(f"{self.c_name_bigger = } -> {c = !s}") + self.c_dtype = c.element_type + # If only broadcast tensors are read, there is no leading dimension + # defined, so use the same as the output. + try: + self.c_layout = utils.LayoutEnum.from_tensor(c) + except ValueError: + self.c_layout = self.d_layout + + # Check if input data types are compatible with MMA instruction + if cutlass.const_expr(self.a_dtype != self.b_dtype): + raise TypeError(f"Types must match: {self.a_dtype} != {self.b_dtype}") + + # Setup attributes that depend on gemm inputs + self._setup_attributes() + + atom_thr_size = cute.size(self._tiled_mma.thr_id.shape) + + # Setup TMA load for A + a_op = utils.sm100.cluster_shape_to_tma_atom_A( + self.cluster_shape_mn, self._tiled_mma.thr_id + ) + log(f"{a_op = !s}") + # Get rid of the pipeline dimension. + a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0)) + log(f"{a_smem_layout = !s}") + tma_atom_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A( + a_op, + a, + a_smem_layout, + self.mma_tiler, + self._tiled_mma, + self.cluster_layout_vmnk.shape, + internal_type=( + cutlass.TFloat32 if a.element_type is cutlass.Float32 else None + ), + ) + log(f"{tma_atom_a = !s}") + log(f"{tma_tensor_a = !s}") + # Setup TMA load for B + b_op = utils.sm100.cluster_shape_to_tma_atom_B( + self.cluster_shape_mn, self._tiled_mma.thr_id + ) + log(f"{b_op = !s}") + # Get rid of the pipeline dimension. + b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0)) + log(f"{b_smem_layout = !s}") + tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B( + b_op, + b, + b_smem_layout, + self.mma_tiler, + self._tiled_mma, + self.cluster_layout_vmnk.shape, + internal_type=( + cutlass.TFloat32 if b.element_type is cutlass.Float32 else None + ), + ) + log(f"{tma_atom_b = !s}") + log(f"{tma_tensor_b = !s}") + a_copy_size = cute.size_in_bytes(self.a_dtype, a_smem_layout) + b_copy_size = cute.size_in_bytes(self.b_dtype, b_smem_layout) + self.num_tma_load_bytes = (a_copy_size + b_copy_size) * atom_thr_size + log(f"{self.num_tma_load_bytes = }") + + # Set the TMA related arguments for the tensors used in the EFC. + self.efc.jit.create_tma_arguments() + + # Compute grid size + self.tile_sched_params, grid = self._compute_grid( + d, self.cta_tile_shape_mnk, self.cluster_shape_mn, max_active_clusters + ) + + self.efc.jit.create_supplemental_arguments_for_kernel() + + # Launch the kernel synchronously + self.kernel( + self._tiled_mma, + tma_atom_a, + tma_tensor_a, + tma_atom_b, + tma_tensor_b, + self.cluster_layout_vmnk, + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.epi_tile, + self.tile_sched_params, + local_reduce_tensor, + local_reduce_feed_tensor, + local_reduce_secondary_feed_tensor, + self.efc.kernel.pack_arguments(), + ).launch( + grid=grid, + block=[self.threads_per_cta, 1, 1], + cluster=(*self.cluster_shape_mn, 1), + stream=stream, + ) + + # GPU device kernel + @cute.kernel + def kernel( + self, + tiled_mma: cute.TiledMma, + tma_atom_a: cute.CopyAtom, + mA_mkl: cute.Tensor, + tma_atom_b: cute.CopyAtom, + mB_nkl: cute.Tensor, + cluster_layout_vmnk: cute.Layout, + a_smem_layout_staged: cute.ComposedLayout, + b_smem_layout_staged: cute.ComposedLayout, + epi_tile: cute.Tile, + tile_sched_params: utils.PersistentTileSchedulerParams, + local_reduce_tensor: cute.Tensor, + local_reduce_feed_tensor: cute.Tensor, + local_reduce_secondary_feed_tensor: cute.Tensor, + supplemental_parameters: tuple, + ): + """GPU device kernel performing the Persistent batched GEMM computation.""" + # Process the variadic parameters. + self.efc.kernel.unpack_parameters(supplemental_parameters) + + warp_idx = cute.arch.warp_idx() + warp_idx = cute.arch.make_warp_uniform(warp_idx) + + # + # Prefetch TMA descriptors + # + if warp_idx == self.tma_warp_id: + cpasync.prefetch_descriptor(tma_atom_a) + cpasync.prefetch_descriptor(tma_atom_b) + # Prefetch the TMA descriptors for all the supplemental tensors. + self.efc.kernel.prefetch_tma_descriptors() + + # + # Setup cta/thread coordinates + # + # Coords inside cluster + bidx, bidy, bidz = cute.arch.block_idx() + mma_tile_coord_v = bidx % cute.size(tiled_mma.thr_id.shape) + is_leader_cta = mma_tile_coord_v == 0 + cta_rank_in_cluster = cute.arch.make_warp_uniform( + cute.arch.block_idx_in_cluster() + ) + block_in_cluster_coord_vmnk = cluster_layout_vmnk.get_flat_coord( + cta_rank_in_cluster + ) + # Coord inside cta + tidx, _, _ = cute.arch.thread_idx() + + # + # Alloc and init: a+b full/empty, accumulator full/empty, tensor memory dealloc barrier + # + self.buffer_align_bytes = 1024 + + # Define shared storage for kernel + @cute.struct + class SharedStorage: + ab_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage] + ab_empty_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage] + acc_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage] + acc_empty_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage] + # Barriers used by the supplemental load tensor pipeline. + c_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_c_stage] + c_empty_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_c_stage] + tmem_dealloc_mbar: cutlass.Int64 + tmem_holding_buf: cutlass.Int32 + # (MMA, MMA_M, MMA_K, STAGE) + sA: cute.struct.Align[ + cute.struct.MemRange[ + self.a_dtype, cute.cosize(a_smem_layout_staged.outer) + ], + self.buffer_align_bytes, + ] + # (MMA, MMA_N, MMA_K, STAGE) + sB: cute.struct.Align[ + cute.struct.MemRange[ + self.b_dtype, cute.cosize(b_smem_layout_staged.outer) + ], + self.buffer_align_bytes, + ] + sLocalReduce: cute.struct.Align[ + cute.struct.MemRange[ + cutlass.Float32, + self.local_reduce_smem_rows * self.local_reduce_smem_cols + if self.has_cross_warp_local_reduce + else 1, + ], + 16, + ] + + self.shared_storage = SharedStorage + + self.smem = utils.SmemAllocator() + storage = self.smem.allocate(self.shared_storage) + sLocalReduce = storage.sLocalReduce.get_tensor( + cute.make_layout((self.local_reduce_smem_rows, self.local_reduce_smem_cols)) + if self.has_cross_warp_local_reduce + else cute.make_layout(1) + ) + + # Allocate the shared memory for all the supplemental tensors. + self.efc.kernel.allocate_smem() + + # Initialize mainloop ab_pipeline (barrier) and states + ab_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + num_tma_producer = self.num_mcast_ctas_a + self.num_mcast_ctas_b - 1 + ab_pipeline_consumer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, num_tma_producer + ) + ab_producer, ab_consumer = pipeline.PipelineTmaUmma.create( + barrier_storage=storage.ab_full_mbar_ptr.data_ptr(), + num_stages=self.num_ab_stage, + producer_group=ab_pipeline_producer_group, + consumer_group=ab_pipeline_consumer_group, + tx_count=self.num_tma_load_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ).make_participants() + + # Initialize acc_pipeline (barrier) and states + acc_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + num_acc_consumer_threads = len(self.epilogue_warp_id) * ( + 2 if self.use_2cta_instrs else 1 + ) + acc_pipeline_consumer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, num_acc_consumer_threads + ) + acc_pipeline = pipeline.PipelineUmmaAsync.create( + barrier_storage=storage.acc_full_mbar_ptr.data_ptr(), + num_stages=self.num_acc_stage, + producer_group=acc_pipeline_producer_group, + consumer_group=acc_pipeline_consumer_group, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + + # Load pipeline, used to load all the supplemental tensors of the + # epilogue. + c_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + c_consumer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, + len(self.epilogue_warp_id), + ) + c_pipeline = pipeline.PipelineTmaAsync.create( + barrier_storage=storage.c_full_mbar_ptr.data_ptr(), + num_stages=self.num_c_stage, + producer_group=c_producer_group, + consumer_group=c_consumer_group, + # Unlock the barrier when all the tensor bytes have been loaded. + tx_count=self.efc.jit.total_tma_load_bytes, + defer_sync=True, + ) + + tmem_alloc_barrier = pipeline.NamedBarrier( + barrier_id=self.tmem_alloc_sync_bar_id, + num_threads=32 * len((self.mma_warp_id, *self.epilogue_warp_id)), + ) + # Tensor memory dealloc barrier init + tmem = utils.TmemAllocator( + storage.tmem_holding_buf.ptr, + barrier_for_retrieve=tmem_alloc_barrier, + allocator_warp_id=self.epilogue_warp_id[0], + is_two_cta=self.use_2cta_instrs, + two_cta_tmem_dealloc_mbar_ptr=storage.tmem_dealloc_mbar.ptr, + ) + + # Cluster arrive after barrier init + pipeline.pipeline_init_arrive( + cluster_shape_mn=self.cluster_shape_mn, is_relaxed=True + ) + + # + # Setup smem tensor A/B + # + # (MMA, MMA_M, MMA_K, STAGE) + sA = storage.sA.get_tensor( + a_smem_layout_staged.outer, swizzle=a_smem_layout_staged.inner + ) + # (MMA, MMA_N, MMA_K, STAGE) + sB = storage.sB.get_tensor( + b_smem_layout_staged.outer, swizzle=b_smem_layout_staged.inner + ) + + # + # Compute multicast mask for A/B buffer full + # + a_full_mcast_mask = None + b_full_mcast_mask = None + if cutlass.const_expr( + self.is_a_mcast or self.is_b_mcast or self.use_2cta_instrs + ): + a_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=2 + ) + b_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=1 + ) + + # + # Local_tile partition global tensors + # + # (bM, bK, loopM, loopK, loopL) + gA_mkl = cute.local_tile( + mA_mkl, cute.slice_(self.mma_tiler, (None, 0, None)), (None, None, None) + ) + # (bN, bK, loopN, loopK, loopL) + gB_nkl = cute.local_tile( + mB_nkl, cute.slice_(self.mma_tiler, (0, None, None)), (None, None, None) + ) + + k_tile_cnt = cute.size(gA_mkl, mode=[3]) + + # + # Partition global tensor for TiledMMA_A/B/D + # + self.thr_mma = tiled_mma.get_slice(mma_tile_coord_v) + # (MMA, MMA_M, MMA_K, loopM, loopK, loopL) + tCgA = self.thr_mma.partition_A(gA_mkl) + log(f"{tCgA = !s}") + # (MMA, MMA_N, MMA_K, loopN, loopK, loopL) + tCgB = self.thr_mma.partition_B(gB_nkl) + log(f"{tCgB = !s}") + # Create the local_tile gX_mnl for all the EFC supplemental tensors. + self.efc.kernel.partition_global_tensors_for_tiled_mma() + + # + # Partition global/shared tensor for TMA load A/B + # + # TMA load A partition_S/D + a_cta_layout = cute.make_layout( + cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape + ) + # ((atom_v, rest_v), STAGE) + # ((atom_v, rest_v), tiles_m, tiles_k, tiles_l) + tAsA, tAgA = cpasync.tma_partition( + tma_atom_a, + block_in_cluster_coord_vmnk[2], + a_cta_layout, + cute.group_modes(sA, 0, 3), + cute.group_modes(tCgA, 0, 3), + ) + # TMA load B partition_S/D + b_cta_layout = cute.make_layout( + cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape + ) + # ((atom_v, rest_v), STAGE) + # ((atom_v, rest_v), tiles_n, tiles_k, tiles_l) + tBsB, tBgB = cpasync.tma_partition( + tma_atom_b, + block_in_cluster_coord_vmnk[1], + b_cta_layout, + cute.group_modes(sB, 0, 3), + cute.group_modes(tCgB, 0, 3), + ) + + # + # Partition shared/tensor memory tensor for TiledMMA_A/B/C/D + # + # (MMA, MMA_M, MMA_K, STAGE) + tCrA = tiled_mma.make_fragment_A(sA) + log(f"{tCrA = !s}") + # (MMA, MMA_N, MMA_K, STAGE) + tCrB = tiled_mma.make_fragment_B(sB) + log(f"{tCrB = !s}") + # (MMA, MMA_M, MMA_N) + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + log(f"{acc_shape = !s}") + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_fake = tiled_mma.make_fragment_C( + cute.append(acc_shape, self.num_acc_stage) + ) + log(f"{tCtAcc_fake = !s}") + + # Named barriers + # + epilogue_sync_barrier = pipeline.NamedBarrier( + self.epilogue_sync_bar_id, 32 * len(self.epilogue_warp_id) + ) + + # + # Cluster wait before tensor memory alloc + # + pipeline.pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mn) + + # + # Specialized TMA load warp + # + + if warp_idx == self.tma_warp_id: + # + # Persistent tile scheduling loop + # + tile_sched = utils.StaticPersistentTileScheduler.create( + tile_sched_params, cute.arch.block_idx(), cute.arch.grid_dim() + ) + work_tile = tile_sched.initial_work_tile_info() + + while work_tile.is_valid_tile: + # Get tile coord from tile scheduler + cur_tile_coord = work_tile.tile_idx + mma_tile_coord_mnl = ( + cur_tile_coord[0] // cute.size(tiled_mma.thr_id.shape), + cur_tile_coord[1], + cur_tile_coord[2], + ) + + # + # Slice to per mma tile index + # + # ((atom_v, rest_v), loopK) + tAgA_slice = tAgA[ + (None, mma_tile_coord_mnl[0], None, mma_tile_coord_mnl[2]) + ] + # ((atom_v, rest_v), loopK) + tBgB_slice = tBgB[ + (None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2]) + ] + + # Peek (try_wait) AB buffer empty for k_tile = prefetch_k_tile_cnt + ab_producer.reset() + peek_ab_empty_status = ab_producer.try_acquire() + + # + # Tma load loop + # + for k_tile in cutlass.range(0, k_tile_cnt, 1, unroll=1): + # Conditionally wait for AB buffer empty + handle = ab_producer.acquire_and_advance(peek_ab_empty_status) + + # TMA load A/B + cute.copy( + tma_atom_a, + tAgA_slice[(None, handle.count)], + tAsA[(None, handle.index)], + tma_bar_ptr=handle.barrier, + mcast_mask=a_full_mcast_mask, + ) + cute.copy( + tma_atom_b, + tBgB_slice[(None, handle.count)], + tBsB[(None, handle.index)], + tma_bar_ptr=handle.barrier, + mcast_mask=b_full_mcast_mask, + ) + + # Peek (try_wait) AB buffer empty for k_tile = prefetch_k_tile_cnt + k_tile + 1 + peek_ab_empty_status = cutlass.Boolean(1) + if handle.count + 1 < k_tile_cnt: + peek_ab_empty_status = ab_producer.try_acquire() + + # + # Advance to next tile + # + tile_sched.advance_to_next_work() + work_tile = tile_sched.get_current_work() + + # + # Wait A/B buffer empty + # + ab_producer.tail() + + # + # Specialized MMA warp + # + if warp_idx == self.mma_warp_id: + # + # Bar sync to retrieve tensor memory ptr from shared mem + # + tmem.wait_for_alloc() + + # + # Retrieving tensor memory ptr and make accumulator tensor + # + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout) + + # + # Persistent tile scheduling loop + # + tile_sched = utils.StaticPersistentTileScheduler.create( + tile_sched_params, cute.arch.block_idx(), cute.arch.grid_dim() + ) + work_tile = tile_sched.initial_work_tile_info() + + acc_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_acc_stage + ) + + while work_tile.is_valid_tile: + # Get tile coord from tile scheduler + cur_tile_coord = work_tile.tile_idx + mma_tile_coord_mnl = ( + cur_tile_coord[0] // cute.size(tiled_mma.thr_id.shape), + cur_tile_coord[1], + cur_tile_coord[2], + ) + + # Set tensor memory buffer for current tile + # (MMA, MMA_M, MMA_N) + tCtAcc = tCtAcc_base[(None, None, None, acc_producer_state.index)] + + # Peek (try_wait) AB buffer full for k_tile = 0 + ab_consumer.reset() + peek_ab_full_status = cutlass.Boolean(1) + if is_leader_cta: + peek_ab_full_status = ab_consumer.try_wait() + + # + # Wait for accumulator buffer empty + # + if is_leader_cta: + acc_pipeline.producer_acquire(acc_producer_state) + + # + # Reset the ACCUMULATE field for each tile + # + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + + # + # Mma mainloop + # + for k_tile in range(k_tile_cnt): + if is_leader_cta: + # Conditionally wait for AB buffer full + handle = ab_consumer.wait_and_advance(peek_ab_full_status) + + # tCtAcc += tCrA * tCrB + tiled_mma.set(tcgen05.Field.ACCUMULATE, k_tile != 0) + tile_crd = (None, None, None, handle.index) + cute.gemm( + tiled_mma, tCtAcc, tCrA[tile_crd], tCrB[tile_crd], tCtAcc + ) + + # Async arrive AB buffer empty + handle.release() + + # Peek (try_wait) AB buffer full for k_tile = k_tile + 1 + peek_ab_full_status = cutlass.Boolean(1) + if handle.count + 1 < k_tile_cnt: + peek_ab_full_status = ab_consumer.try_wait() + + # + # Async arrive accumulator buffer full + # + if is_leader_cta: + acc_pipeline.producer_commit(acc_producer_state) + acc_producer_state.advance() + + # + # Advance to next tile + # + tile_sched.advance_to_next_work() + work_tile = tile_sched.get_current_work() + + # + # Wait for accumulator buffer empty + # + acc_pipeline.producer_tail(acc_producer_state) + # + # Specialized epilogue warps + # + if warp_idx < self.mma_warp_id: + # + # Alloc tensor memory buffer + # + tmem.allocate(self.num_tmem_alloc_cols) + + # + # Bar sync to retrieve tensor memory ptr from shared memory + # + tmem.wait_for_alloc() + + # + # Retrieving tensor memory ptr and make accumulator tensor + # + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + log(f"tmem_ptr = {tmem_ptr!s}") + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout) + log(f"tCtAcc_base = {tCtAcc_base!s}") + # + # Partition for epilogue + # + epi_tidx = tidx + tCgD = self.efc.kernel.tCgD_written[self.d_name_bigger] + log(f"tCgD (aka tCgD_written[{self.d_name_bigger}])= {tCgD!s}") + + ( + tiled_copy_t2r, # (EPI_TILE_M, EPI_TILE_N) + tTR_tAcc_base, # (T2R, T2R_M, T2R_N, EPI_M, EPI_M, STAGE) + tTR_rAcc, # (T2R, T2R_M, T2R_N) + ) = self.epilogue_tmem_copy_and_partition( + epi_tidx, tCtAcc_base, tCgD, epi_tile + ) + log(f"{tiled_copy_t2r = !s}") + log(f"{tTR_tAcc_base = !s}") + log(f"{tTR_rAcc = !s}") + # Copy and partition for the supplemental EFC tensors. + self.efc.kernel.copy_and_partition_supplemental_rmem_tensors( + tiled_copy_t2r, tTR_rAcc, epi_tidx, epi_tile + ) + + # + # Persistent tile scheduling loop + # + tile_sched = utils.StaticPersistentTileScheduler.create( + tile_sched_params, cute.arch.block_idx(), cute.arch.grid_dim() + ) + work_tile = tile_sched.initial_work_tile_info() + + acc_consumer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_acc_stage + ) + + # Store D pipeline used for all the written tensors in the epilogue. + d_producer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, + 32 * len(self.epilogue_warp_id), + ) + d_pipeline = pipeline.PipelineTmaStore.create( + num_stages=self.num_d_stage, + producer_group=d_producer_group, + ) + + c_pipeline_consumer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_c_stage + ) + + while work_tile.is_valid_tile: + # Get tile coord from tile scheduler + cur_tile_coord = work_tile.tile_idx + mma_tile_coord_mnl = ( + cur_tile_coord[0] // cute.size(tiled_mma.thr_id.shape), + cur_tile_coord[1], + cur_tile_coord[2], + ) + + # Slice the supplemental written tensors per MMA tile index. + self.efc.kernel.slice_written_tensors_per_mma_tile_index( + mma_tile_coord_mnl + ) + + # Set tensor memory buffer for current tile + # (T2R, T2R_M, T2R_N, EPI_M, EPI_M) + tTR_tAcc = tTR_tAcc_base[ + (None, None, None, None, None, acc_consumer_state.index) + ] + log(f"tTR_tAcc = {tTR_tAcc!s}") + # + # Wait for accumulator buffer full + # + acc_pipeline.consumer_wait(acc_consumer_state) + + # Group together the EPI_M, EPI_M which are starting at group 3. + # (T2R, T2R_M, T2R_N, (EPI_M, EPI_M)) + tTR_tAcc = cute.group_modes(tTR_tAcc, 3, cute.rank(tTR_tAcc)) + log(f"group_modes tTR_tAcc = {tTR_tAcc!s}") + # + # Store accumulator to global memory in subtiles + # + # Use EPI_M*EPI_M to iterate using the 1-D coordinate. + subtile_cnt = cute.size(tTR_tAcc.shape, mode=[3]) + num_prev_subtiles = tile_sched.num_tiles_executed * subtile_cnt + epi_tile_n = cutlass.const_expr(self.epi_tile_n) + local_reduce_partial: typing.Any = None + local_reduce_nan_partial: typing.Any = None + if cutlass.const_expr( + (local_reduce_tensor is not None or self.local_reduce_feeds_main) + and self.local_reduce_axis == 1 + and self.local_reduce_group > self.epi_tile_n + ): + local_reduce_partial = cute.make_rmem_tensor( + ((1, self.epi_tile_n, 1), 1, 1), self.acc_dtype + ) + if cutlass.const_expr(self.local_reduce_type in ("max", "min")): + local_reduce_nan_partial = cute.make_rmem_tensor( + ((1, self.epi_tile_n, 1), 1, 1), self.acc_dtype + ) + for subtile_idx in cutlass.range(subtile_cnt): + # + # Load accumulator from tensor memory buffer to register + # + tTR_tAcc_mn = tTR_tAcc[(None, None, None, subtile_idx)] + cute.copy(tiled_copy_t2r, tTR_tAcc_mn, tTR_rAcc) + log(f"cute.copy tiled_copy_t2r = {tiled_copy_t2r!s}") + log(f"cute.copy tTR_tAcc_mn = {tTR_tAcc_mn!s}") + log(f"cute.copy tTR_rAcc = {tTR_rAcc!s}") + + # Wait for the EFC tensor loads to complete. The wait is + # blocking even if the tx_count is 0 when there is no tensor + # to load. So, only wait if there is something to read, + # i.e. smem_read is not empty. + if cutlass.const_expr(self.efc.kernel.smem_read): + c_pipeline.consumer_wait(c_pipeline_consumer_state) + + # Load supplemental tensors from shared memory to register. + self.efc.kernel.load_tensors_from_smem_to_register( + c_pipeline_consumer_state.index + ) + + cute.arch.fence_proxy( + "async.shared", + space="cta", + ) + c_pipeline.consumer_release(c_pipeline_consumer_state) + + # Advance pipeline states + c_pipeline_consumer_state.advance() + + # + # Perform epilogue op on accumulator. + # + tiled_copy_r2s = self.efc.kernel.tiled_copy_r2s[self.d_name_bigger] + log(f"tiled_copy_r2s = {tiled_copy_r2s!s}") + # Use a SimpleNamespace to pass easily some local content as + # an extensible class compatible with CuTe DSL + # implementation. + epilogue_context = types.SimpleNamespace() + # Load the accumulator cast to the epi_dtype used to do all + # the computations in the epilogue. + # Retile the accumulator subtile to fit the destination + # subtile vector TV layout. + epilogue_context.acc_vec = ( + tiled_copy_r2s.retile(tTR_rAcc).load().to(self.epi_dtype) + ) + log(f"before .retile tTR_rAcc = {tTR_rAcc!s}") + log( + f"tiled_copy_r2s.retile(tTR_rAcc) = {tiled_copy_r2s.retile(tTR_rAcc)!s}" + ) + log( + f"tiled_copy_r2s.retile(tTR_rAcc).load() = {tiled_copy_r2s.retile(tTR_rAcc).load()!s}" + ) + log(f"epilogue_context.acc_vec = {epilogue_context.acc_vec!s}") + + if cutlass.const_expr(self.local_reduce_direct_bool): + direct_fragment = cute.make_rmem_tensor_like( + epilogue_context.acc_vec, self.acc_dtype + ) + direct_fragment.store( + epilogue_context.acc_vec.to(self.acc_dtype) + ) + direct_flt = cute.filter_zeros(direct_fragment) + direct_coordinates = partition_for_epilogue( + cute.make_identity_tensor(self.cta_tile_shape_mnk[:2]), + epi_tile=epi_tile, + tiled_copy=tiled_copy_t2r, + tidx=epi_tidx, + reference_src=False, + )[(None, None, None, 0, subtile_idx)] + direct_coord_flt = cute.filter_zeros(direct_coordinates) + output_m = cute.size(mA_mkl, mode=[0]) + output_n = cute.size(mB_nkl, mode=[0]) + for i in cutlass.range(cute.size(direct_flt), unroll_full=True): + global_m = ( + mma_tile_coord_mnl[0] * self.cta_tile_shape_mnk[0] + + direct_coord_flt[i][0] + ) + global_n = ( + mma_tile_coord_mnl[1] * self.cta_tile_shape_mnk[1] + + direct_coord_flt[i][1] + ) + if global_m < output_m and global_n < output_n: + local_reduce_secondary_feed_tensor[ + global_m, + global_n, + mma_tile_coord_mnl[2], + ] = (direct_flt[i] > 0.0).to( + local_reduce_secondary_feed_tensor.element_type + ) + + if cutlass.const_expr( + ( + local_reduce_tensor is not None + or self.local_reduce_feeds_main + ) + and self.local_reduce_axis == 0 + ): + assert self.local_reduce_type in ( + "sum", + "mean", + "mean_linear", + "prod", + "max", + "min", + "normalize_sum", + "normalize_sum_reverse", + ) + assert self.local_reduce_source in ( + "identity", + "square", + "abs", + ) + group = cutlass.const_expr(self.local_reduce_group) + acc_fragment = cute.make_rmem_tensor_like( + epilogue_context.acc_vec, self.acc_dtype + ) + acc_fragment.store(epilogue_context.acc_vec.to(self.acc_dtype)) + reduced_flt = cute.filter_zeros(acc_fragment) + coordinates = partition_for_epilogue( + cute.make_identity_tensor(self.cta_tile_shape_mnk[:2]), + epi_tile=epi_tile, + tiled_copy=tiled_copy_t2r, + tidx=epi_tidx, + reference_src=False, + ) + coordinates = coordinates[(None, None, None, 0, subtile_idx)] + coord_flt = cute.filter_zeros( + tiled_copy_r2s.retile(coordinates) + ) + lane_layout_mn, warp_layout_mn = get_lane_warp_layouts( + tiled_copy_t2r, reference_src=False + ) + lanes_in_m = cutlass.const_expr( + cute.size(lane_layout_mn, mode=[0]) + ) + assert group > 1 and group <= self.cta_tile_shape_mnk[0] + reduction_group = cutlass.const_expr(min(group, lanes_in_m)) + assert group % reduction_group == 0 + assert lanes_in_m % reduction_group == 0 + for i in cutlass.range( + cute.size(reduced_flt), unroll_full=True + ): + reduced_flt[i] = self.local_reduce_source_op(reduced_flt[i]) + rows = reduction_group // 2 + while rows > 0: + other = cute.arch.shuffle_sync_bfly( + reduced_flt[i], + offset=cute.crd2idx((rows, 0), lane_layout_mn), + ) + reduced_flt[i] = self.local_reduce_combine( + reduced_flt[i], other + ) + rows //= 2 + reduced_flt[i] = self.local_reduce_finalize( + reduced_flt[i], group + ) + groups_per_cta = cutlass.const_expr( + self.cta_tile_shape_mnk[0] // group + ) + g_reduce: typing.Any = None + if cutlass.const_expr(local_reduce_tensor is not None): + m_reduce = local_reduce_tensor[ + mma_tile_coord_mnl[2], None, None + ] + g_reduce = cute.local_tile( + m_reduce, + (groups_per_cta, self.cta_tile_shape_mnk[1]), + mma_tile_coord_mnl[:2], + ) + limit_n = ( + min( + cute.size(local_reduce_tensor, mode=[2]) + - mma_tile_coord_mnl[1] * self.cta_tile_shape_mnk[1], + self.cta_tile_shape_mnk[1], + ) + if cutlass.const_expr(local_reduce_tensor is not None) + else self.cta_tile_shape_mnk[1] + ) + limit_groups = ( + cute.size(local_reduce_tensor, mode=[1]) + if cutlass.const_expr(local_reduce_tensor is not None) + else cute.size(mA_mkl, mode=[0]) // group + ) + group_warps = cutlass.const_expr(group // lanes_in_m) + warp_m = warp_layout_mn[0] + warps_in_m = cutlass.const_expr(cute.size(warp_m)) + assert group_warps <= warps_in_m + warp_idx = cute.arch.make_warp_uniform( + epi_tidx // cute.arch.WARP_SIZE + ) + warp_m_idx = warp_layout_mn.get_hier_coord(warp_idx)[0] + feed_fragment = cute.make_rmem_tensor_like( + acc_fragment, self.acc_dtype + ) + feed_fragment.store(epilogue_context.acc_vec.to(self.acc_dtype)) + feed_flt = cute.filter_zeros(feed_fragment) + if cutlass.const_expr(group > lanes_in_m): + for i in cutlass.range( + cute.size(reduced_flt), unroll_full=True + ): + row_idx = coord_flt[i][0] + n_idx = coord_flt[i][1] + group_idx = row_idx // group + group_warp_start = group_idx * group_warps + group_warp_idx = warp_m_idx - group_warp_start + if ( + row_idx % lanes_in_m == 0 + and group_warp_idx > 0 + and group_warp_idx < group_warps + ): + sLocalReduce[n_idx, warp_m_idx - group_idx - 1] = ( + reduced_flt[i] + ) + epilogue_sync_barrier.arrive_and_wait() + for i in cutlass.range( + cute.size(reduced_flt), unroll_full=True + ): + row_idx = coord_flt[i][0] + n_idx = coord_flt[i][1] + group_idx = row_idx // group + global_group_idx = ( + mma_tile_coord_mnl[0] * groups_per_cta + group_idx + ) + group_value = reduced_flt[i] + group_warp_start = group_idx * group_warps + if cutlass.const_expr(group > lanes_in_m): + if ( + row_idx % group == 0 + and warp_m_idx == group_warp_start + ): + for warp_offset in cutlass.range_constexpr( + 1, group_warps + ): + other = sLocalReduce[ + n_idx, + group_warp_start + + warp_offset + - group_idx + - 1, + ] + group_value = self.local_reduce_combine( + group_value, other + ) + if cutlass.const_expr(self.local_reduce_feeds_main): + if row_idx % group == 0 and ( + group <= lanes_in_m + or warp_m_idx == group_warp_start + ): + feed_flt[i] = group_value + if cutlass.const_expr(local_reduce_tensor is not None): + if ( + row_idx % group == 0 + and n_idx < limit_n + and global_group_idx < limit_groups + ): + g_reduce[group_idx, n_idx] = group_value + if cutlass.const_expr(group > lanes_in_m): + epilogue_sync_barrier.arrive_and_wait() + if cutlass.const_expr(self.local_reduce_feeds_main): + primary_acc_vec = epilogue_context.acc_vec + for i in cutlass.range( + cute.size(reduced_flt), unroll_full=True + ): + row_idx = coord_flt[i][0] + n_idx = coord_flt[i][1] + group_idx = row_idx // group + group_warp_start = group_idx * group_warps + if row_idx % group == 0 and ( + group <= lanes_in_m + or warp_m_idx == group_warp_start + ): + sLocalReduce[n_idx, group_idx + 3] = feed_flt[i] + epilogue_sync_barrier.arrive_and_wait() + for i in cutlass.range( + cute.size(reduced_flt), unroll_full=True + ): + row_idx = coord_flt[i][0] + n_idx = coord_flt[i][1] + reduced_flt[i] = sLocalReduce[ + n_idx, row_idx // group + 3 + ] + epilogue_sync_barrier.arrive_and_wait() + normalized_fragment = cute.make_rmem_tensor_like( + acc_fragment, self.acc_dtype + ) + normalized_fragment.store( + epilogue_context.acc_vec.to(self.acc_dtype) + ) + normalized_flt = cute.filter_zeros(normalized_fragment) + for i in cutlass.range( + cute.size(normalized_flt), unroll_full=True + ): + if cutlass.const_expr( + self.local_reduce_type == "mean_linear" + ): + normalized_flt[i] = ( + normalized_flt[i] + * self.local_reduce_input_coefficient + + reduced_flt[i] + * self.local_reduce_result_coefficient + + self.local_reduce_bias + ) + else: + denominator = ( + reduced_flt[i] + * self.local_reduce_denominator_scale + + self.local_reduce_denominator_bias + ) + if cutlass.const_expr( + self.local_reduce_type == "normalize_sum" + ): + normalized_flt[i] /= denominator + else: + assert ( + self.local_reduce_type + == "normalize_sum_reverse" + ) + normalized_flt[i] = ( + denominator / normalized_flt[i] + ) + normalized_flt[i] = ( + normalized_flt[i] * self.local_reduce_affine_scale + + self.local_reduce_affine_bias + ) + if cutlass.const_expr(local_reduce_feed_tensor is not None): + output_m = cute.size(mA_mkl, mode=[0]) + output_n = cute.size(mB_nkl, mode=[0]) + for i in cutlass.range( + cute.size(normalized_flt), unroll_full=True + ): + global_m = ( + mma_tile_coord_mnl[0] + * self.cta_tile_shape_mnk[0] + + coord_flt[i][0] + ) + global_n = ( + mma_tile_coord_mnl[1] + * self.cta_tile_shape_mnk[1] + + coord_flt[i][1] + ) + if global_m < output_m and global_n < output_n: + local_reduce_feed_tensor[ + global_m, + global_n, + mma_tile_coord_mnl[2], + ] = normalized_flt[i].to( + local_reduce_feed_tensor.element_type + ) + if cutlass.const_expr( + local_reduce_secondary_feed_tensor is not None + ): + output_m = cute.size(mA_mkl, mode=[0]) + output_n = cute.size(mB_nkl, mode=[0]) + if cutlass.const_expr( + self.local_reduce_secondary_reuses_primary + ): + secondary_flt = normalized_flt + else: + secondary_fragment = cute.make_rmem_tensor_like( + acc_fragment, self.acc_dtype + ) + secondary_fragment.store( + primary_acc_vec.to(self.acc_dtype) + ) + secondary_flt = cute.filter_zeros( + secondary_fragment + ) + for i in cutlass.range( + cute.size(secondary_flt), unroll_full=True + ): + secondary_flt[i] *= ( + reduced_flt[i] + * self.local_reduce_secondary_scale + + self.local_reduce_secondary_bias + ) + for i in cutlass.range( + cute.size(secondary_flt), unroll_full=True + ): + global_m = ( + mma_tile_coord_mnl[0] + * self.cta_tile_shape_mnk[0] + + coord_flt[i][0] + ) + global_n = ( + mma_tile_coord_mnl[1] + * self.cta_tile_shape_mnk[1] + + coord_flt[i][1] + ) + if global_m < output_m and global_n < output_n: + local_reduce_secondary_feed_tensor[ + global_m, + global_n, + mma_tile_coord_mnl[2], + ] = secondary_flt[i].to( + local_reduce_secondary_feed_tensor.element_type + ) + if cutlass.const_expr(local_reduce_feed_tensor is not None): + epilogue_context.acc_vec = primary_acc_vec + else: + epilogue_context.acc_vec = normalized_fragment.load() + + if cutlass.const_expr( + ( + local_reduce_tensor is not None + and self.local_reduce_axis == 1 + ) + or ( + self.local_reduce_feeds_main and self.local_reduce_axis == 1 + ) + ): + assert self.local_reduce_type in ( + "sum", + "mean", + "prod", + "max", + "min", + "logsumexp", + "variance", + "normalize_sum", + "normalize_sum_reverse", + ) + assert self.local_reduce_source in ( + "identity", + "square", + "abs", + ) + group = cutlass.const_expr(self.local_reduce_group) + fragment_n = epi_tile_n + n_subtiles = cutlass.const_expr( + self.cta_tile_shape_mnk[1] // fragment_n + ) + fragments_per_group = cutlass.const_expr( + max(1, group // fragment_n) + ) + subtile_n_idx = subtile_idx % n_subtiles + assert group > 1 + acc_fragment = cute.make_rmem_tensor_like( + epilogue_context.acc_vec, self.acc_dtype + ) + acc_fragment.store(epilogue_context.acc_vec.to(self.acc_dtype)) + acc_flt = cute.filter_zeros(acc_fragment) + wide_reduced = None + wide_nan = None + if cutlass.const_expr(group > fragment_n): + local_reduce_vec = epilogue_context.acc_vec.to( + self.acc_dtype + ) + if cutlass.const_expr( + self.local_reduce_type in ("max", "min") + ): + nan_grouped = ( + (local_reduce_vec != local_reduce_vec) + .to(self.acc_dtype) + .reshape(((1, fragment_n, 1), 1, 1)) + ) + wide_nan = nan_grouped.reduce( + cute.ReductionOp.ADD, + init_val=0.0, + reduction_profile=((None, 1, None), 1, 1), + ) + wide_nan = wide_nan.reshape( + ((1, 1, 1), 1, 1) + ).broadcast_to(nan_grouped.shape) + local_reduce_vec = self.local_reduce_source_op( + local_reduce_vec + ) + fragment_width = cutlass.const_expr( + cute.size(local_reduce_vec.shape, mode=[0]) + ) + grouped = local_reduce_vec.reshape( + ((1, fragment_width, 1), 1, 1) + ) + wide_reduced = grouped.reduce( + self.local_reduce_op, + init_val=self.local_reduce_init, + reduction_profile=((None, 1, None), 1, 1), + ) + wide_reduced = wide_reduced.reshape( + ((1, 1, 1), 1, 1) + ).broadcast_to(grouped.shape) + reduced_fragment = cute.make_rmem_tensor_like( + acc_fragment, cutlass.Float32 + ) + reduced_flt = cute.filter_zeros(reduced_fragment) + wide_partial_fragment = cute.make_rmem_tensor_like( + acc_fragment, cutlass.Float32 + ) + wide_partial_flt = cute.filter_zeros(wide_partial_fragment) + for i in cutlass.range( + cute.size(wide_partial_flt), unroll_full=True + ): + wide_partial_flt[i] = self.local_reduce_init + coordinates = partition_for_epilogue( + cute.make_identity_tensor(self.cta_tile_shape_mnk[:2]), + epi_tile=epi_tile, + tiled_copy=tiled_copy_t2r, + tidx=epi_tidx, + reference_src=False, + ) + coordinates = coordinates[(None, None, None, 0, subtile_idx)] + coord_flt = cute.filter_zeros(coordinates) + acc_coord_flt = cute.filter_zeros( + tiled_copy_r2s.retile(coordinates) + ) + groups_per_cta = cutlass.const_expr( + self.cta_tile_shape_mnk[1] // group + ) + g_reduce: typing.Any = None + if cutlass.const_expr(local_reduce_tensor is not None): + m_reduce = local_reduce_tensor[ + mma_tile_coord_mnl[2], None, None + ] + g_reduce = cute.local_tile( + m_reduce, + (self.cta_tile_shape_mnk[0], groups_per_cta), + mma_tile_coord_mnl[:2], + ) + limit_m = min( + cute.size(mA_mkl, mode=[0]) + - mma_tile_coord_mnl[0] * self.cta_tile_shape_mnk[0], + self.cta_tile_shape_mnk[0], + ) + limit_groups = ( + cute.size(local_reduce_tensor, mode=[2]) + if cutlass.const_expr(local_reduce_tensor is not None) + else cute.size(mB_nkl, mode=[0]) // group + ) + for i in cutlass.range(cute.size(acc_flt), unroll_full=True): + row_idx = coord_flt[i][0] + n_idx = coord_flt[i][1] + logical_row = row_idx + group_idx = ( + subtile_n_idx // fragments_per_group + if cutlass.const_expr(group > fragment_n) + else n_idx // group + ) + global_group_idx = ( + mma_tile_coord_mnl[1] * groups_per_cta + group_idx + ) + if ( + ( + self.local_reduce_feeds_main + or n_idx + % ( + fragment_n + if cutlass.const_expr(group > fragment_n) + else group + ) + == 0 + ) + and logical_row < limit_m + and global_group_idx < limit_groups + ): + reduced = self.local_reduce_init + for j in cutlass.range( + cute.size(acc_flt), unroll_full=True + ): + if coord_flt[j][0] == row_idx and ( + cutlass.const_expr(group > fragment_n) + or coord_flt[j][1] // group == group_idx + ): + value = acc_flt[j] + value = self.local_reduce_source_op(value) + reduced = self.local_reduce_combine( + reduced, value + ) + if cutlass.const_expr( + self.local_reduce_type == "logsumexp" + and group <= fragment_n + ): + shift = reduced + if cute.math.abs(shift) == cutlass.Float32.inf: + shift = cutlass.Float32(0.0) + exp_sum = cutlass.Float32(0.0) + for j in cutlass.range( + cute.size(acc_flt), unroll_full=True + ): + if ( + coord_flt[j][0] == row_idx + and coord_flt[j][1] // group == group_idx + ): + exp_sum += cute.math.exp(acc_flt[j] - shift) + reduced = cute.math.log(exp_sum) + shift + elif cutlass.const_expr( + self.local_reduce_type == "variance" + and group <= fragment_n + ): + mean = reduced / group + reduced = cutlass.Float32(0.0) + for j in cutlass.range( + cute.size(acc_flt), unroll_full=True + ): + if ( + coord_flt[j][0] == row_idx + and coord_flt[j][1] // group == group_idx + ): + delta = acc_flt[j] - mean + reduced += delta * delta + reduced = ( + reduced + / group + * self.local_reduce_variance_scale + + self.local_reduce_variance_bias + ) + elif cutlass.const_expr(group <= fragment_n): + reduced = self.local_reduce_finalize(reduced, group) + if cutlass.const_expr(self.local_reduce_feeds_main): + reduced_flt[i] = reduced + if cutlass.const_expr(group > fragment_n): + wide_partial_flt[i] = reduced + if cutlass.const_expr(local_reduce_tensor is not None): + if cutlass.const_expr(group > fragment_n): + if n_idx % fragment_n == 0: + fragment_idx = ( + subtile_n_idx % fragments_per_group + ) + sLocalReduce[logical_row, fragment_idx] = ( + reduced + ) + elif n_idx % group == 0: + g_reduce[logical_row, group_idx] = reduced + if cutlass.const_expr( + group > fragment_n + and local_reduce_tensor is not None + and self.local_reduce_type == "sum" + ): + sum_fragment_idx = subtile_n_idx % fragments_per_group + sum_group_idx = subtile_n_idx // fragments_per_group + sum_global_group_idx = ( + mma_tile_coord_mnl[1] * groups_per_cta + sum_group_idx + ) + sum_row_idx = epi_tidx + if sum_fragment_idx == 0: + if ( + sum_row_idx < limit_m + and sum_global_group_idx < limit_groups + ): + shared_element = cute.make_tensor( + sLocalReduce.iterator + sum_row_idx, + cute.make_layout(1), + ) + shared_element[0] = cutlass.Float32(0.0) + epilogue_sync_barrier.arrive_and_wait() + for i in cutlass.range( + cute.size(acc_flt), unroll_full=True + ): + if ( + sum_row_idx < limit_m + and sum_global_group_idx < limit_groups + ): + cute.arch.atomic_add( + sLocalReduce.iterator + sum_row_idx, + acc_flt[i], + scope="cta", + ) + epilogue_sync_barrier.arrive_and_wait() + if sum_fragment_idx == fragments_per_group - 1: + if ( + sum_row_idx < limit_m + and sum_global_group_idx < limit_groups + ): + shared_element = cute.make_tensor( + sLocalReduce.iterator + sum_row_idx, + cute.make_layout(1), + ) + output_element = cute.make_tensor( + g_reduce.iterator # pyrefly: ignore[unbound-name] + + sum_row_idx * limit_groups, + cute.make_layout(1), + ) + output_element[0] = shared_element[0] + if cutlass.const_expr( + group > fragment_n and self.local_reduce_type != "sum" + ): + fragment_idx = subtile_n_idx % fragments_per_group + partial = local_reduce_partial.load() + current = wide_reduced + if fragment_idx == 0: + partial = current + else: + partial = self.local_reduce_combine(partial, current) + local_reduce_partial.store(partial) + if cutlass.const_expr( + self.local_reduce_type in ("max", "min") + ): + nan_partial = local_reduce_nan_partial.load() + if fragment_idx == 0: + nan_partial = wide_nan + else: + nan_partial += wide_nan + local_reduce_nan_partial.store(nan_partial) + if fragment_idx == fragments_per_group - 1: + final_fragment = cute.make_rmem_tensor_like( + local_reduce_partial, cutlass.Float32 + ) + final_fragment.store(partial) + final_flt = cute.filter_zeros(final_fragment) + nan_flt: typing.Any = None + if cutlass.const_expr( + self.local_reduce_type in ("max", "min") + ): + nan_fragment = cute.make_rmem_tensor_like( + local_reduce_nan_partial, cutlass.Float32 + ) + nan_fragment.store(local_reduce_nan_partial.load()) + nan_flt = cute.filter_zeros(nan_fragment) + store_coordinates = partition_for_epilogue( + cute.make_identity_tensor( + self.cta_tile_shape_mnk[:2] + ), + epi_tile=epi_tile, + tiled_copy=tiled_copy_t2r, + tidx=epi_tidx, + reference_src=False, + ) + store_coordinates = store_coordinates[ + ( + None, + None, + None, + 0, + subtile_idx - fragment_idx, + ) + ] + store_coord_flt = cute.filter_zeros(store_coordinates) + for i in cutlass.range( + cute.size(final_flt), unroll_full=True + ): + row_idx = store_coord_flt[i][0] + n_idx = store_coord_flt[i][1] + group_idx = subtile_n_idx // fragments_per_group + global_group_idx = ( + mma_tile_coord_mnl[1] * groups_per_cta + + group_idx + ) + if ( + n_idx % fragment_n == 0 + and row_idx < limit_m + and global_group_idx < limit_groups + ): + value = final_flt[i] + if cutlass.const_expr( + self.local_reduce_type in ("max", "min") + ): + if nan_flt[i] > 0.0: + value = float("nan") + value = self.local_reduce_finalize(value, group) + g_reduce[row_idx, group_idx] = value + if cutlass.const_expr(self.local_reduce_feeds_main): + primary_acc_vec = epilogue_context.acc_vec + for i in cutlass.range( + cute.size(acc_flt), unroll_full=True + ): + denominator = ( + reduced_flt[i] * self.local_reduce_denominator_scale + + self.local_reduce_denominator_bias + ) + if cutlass.const_expr( + self.local_reduce_type == "normalize_sum" + ): + value = acc_flt[i] / denominator + else: + value = denominator / acc_flt[i] + acc_flt[i] = ( + value * self.local_reduce_affine_scale + + self.local_reduce_affine_bias + ) + if cutlass.const_expr(local_reduce_feed_tensor is not None): + output_m = cute.size(mA_mkl, mode=[0]) + output_n = cute.size(mB_nkl, mode=[0]) + for i in cutlass.range( + cute.size(acc_flt), unroll_full=True + ): + global_m = ( + mma_tile_coord_mnl[0] + * self.cta_tile_shape_mnk[0] + + acc_coord_flt[i][0] + ) + global_n = ( + mma_tile_coord_mnl[1] + * self.cta_tile_shape_mnk[1] + + acc_coord_flt[i][1] + ) + if global_m < output_m and global_n < output_n: + local_reduce_feed_tensor[ + global_m, + global_n, + mma_tile_coord_mnl[2], + ] = acc_flt[i].to( + local_reduce_feed_tensor.element_type + ) + if cutlass.const_expr(local_reduce_feed_tensor is not None): + epilogue_context.acc_vec = primary_acc_vec + else: + epilogue_context.acc_vec = acc_fragment.load().to( + self.epi_dtype + ) + + # Execute the EFC epilogue. + self.efc.kernel.epilogue_computation(epilogue_context) + d_buffer = (num_prev_subtiles + subtile_idx) % self.num_d_stage + + # Store the EFC written tensors to shared memory. + self.efc.kernel.store_written_tensors_to_smem(d_buffer) + + # Fence and barrier to make sure shared memory store is visible to TMA store + cute.arch.fence_proxy( + "async.shared", + space="cta", + ) + epilogue_sync_barrier.arrive_and_wait() + + # + # TMA store D to global memory + # + if warp_idx == self.epilogue_warp_id[0]: + # Store with TMA the written EFC tensors to global memory. + self.efc.kernel.tma_store_written_tensors_to_gmem( + d_buffer, subtile_idx + ) + # Fence and barrier to make sure shared memory store is visible to TMA store + d_pipeline.producer_commit() + d_pipeline.producer_acquire() + + epilogue_sync_barrier.arrive_and_wait() + + # + # Async arrive accumulator buffer empty + # + with cute.arch.elect_one(): + acc_pipeline.consumer_release(acc_consumer_state) + acc_consumer_state.advance() + + # + # Advance to next tile + # + tile_sched.advance_to_next_work() + work_tile = tile_sched.get_current_work() + + # + # Dealloc the tensor memory buffer + # + tmem.relinquish_alloc_permit() + epilogue_sync_barrier.arrive_and_wait() + tmem.free(tmem_ptr) + # + # Wait for D store complete + # + d_pipeline.producer_tail() + + # + # Specialized epilogue load warp + # + if warp_idx == self.epilogue_load_warp_id: + # Create the tiled tensors to be loaded in the epilogue. + self.efc.kernel.create_epilogue_subtile_tensors(tidx, epi_tile) + + tile_sched = utils.StaticPersistentTileScheduler.create( + tile_sched_params, cute.arch.block_idx(), cute.arch.grid_dim() + ) + work_tile = tile_sched.initial_work_tile_info() + + c_pipeline_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_c_stage + ) + + # Setup the pipelines reading the EFC supplemental tensors. + + while work_tile.is_valid_tile: + # Get tile coord from tile scheduler + cur_tile_coord = work_tile.tile_idx + mma_tile_coord_mnl = ( + cur_tile_coord[0] // cute.size(tiled_mma.thr_id.shape), + cur_tile_coord[1], + cur_tile_coord[2], + ) + # Prepare the EFC tensors to be loaded by the subtiles. + subtile_cnt = self.efc.kernel.prepare_tensor_load_for_subtiles( + mma_tile_coord_mnl, + ) + + # Assume the pipeline can work even in the case there is no + # tensor to load and so subtile_cnt is 0. + for subtile_idx in cutlass.range(subtile_cnt): + # Load C from global memory to shared memory. + c_pipeline.producer_acquire(c_pipeline_producer_state) + + # Load the subtiles of EFC tensors. + self.efc.kernel.load_tensor_subtiles( + subtile_idx, c_pipeline, c_pipeline_producer_state + ) + + c_pipeline_producer_state.advance() + + # + # Advance to next tile + # + tile_sched.advance_to_next_work() + work_tile = tile_sched.get_current_work() + + # + # Wait for the load buffer to be empty. + # + c_pipeline.producer_tail(c_pipeline_producer_state) + + def epilogue_tmem_copy_and_partition( + self, + tidx: cutlass.Int32, + tAcc: cute.Tensor, + tCgC: cute.Tensor, + epi_tile: cute.Tile, + ) -> tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]: + """Make tiledCopy for tensor memory load, then use it to partition tensor memory (source) and register array (destination).""" + # Make tiledCopy for tensor memory load + copy_atom_t2r = sm100_utils.get_tmem_load_op( + self.cta_tile_shape_mnk, + self.d_layout, # Take this as the reference layout for the epilogue tile. + self.epi_dtype, # But we get the accumulator as epi_dtype in the epilogue. + self.acc_dtype, + epi_tile, + self.use_2cta_instrs, + ) + + # (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, STAGE) + tAcc_epi = cute.flat_divide( + tAcc[((None, None), 0, 0, None)], + epi_tile, + ) + # (EPI_TILE_M, EPI_TILE_N) + tiled_copy_t2r = tcgen05.make_tmem_copy( + copy_atom_t2r, tAcc_epi[(None, None, 0, 0, 0)] + ) + thr_copy_t2r = tiled_copy_t2r.get_slice(tidx) + # (T2R, T2R_M, T2R_N, EPI_M, EPI_M, STAGE) + tTR_tAcc = thr_copy_t2r.partition_S(tAcc_epi) + + # (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, RestM, RestN, RestL) + tCgC_epi = cute.flat_divide( + tCgC[((None, None), 0, 0, None, None, None)], epi_tile + ) + # (T2R, T2R_M, T2R_N, EPI_M, EPI_N, RestM, RestN, RestL) + tTR_gC = thr_copy_t2r.partition_D(tCgC_epi) + # (T2R, T2R_M, T2R_N) + tTR_rAcc = cute.make_rmem_tensor( + tTR_gC[(None, None, None, 0, 0, 0, 0, 0)].shape, self.acc_dtype + ) + return tiled_copy_t2r, tTR_tAcc, tTR_rAcc + + def epilogue_smem_copy_and_partition_load( + self, + tiled_copy_t2r: cute.TiledCopy, + tTR_rC: cute.Tensor, + tidx: cutlass.Int32, + sC: cute.Tensor, + ) -> tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]: + """Make tiledCopy for shared memory load, then use it to partition register array (destination) and shared memory (source). + + :param tiled_copy_t2r: The tiled copy operation for tmem to register copy(t2r) + :type tiled_copy_t2r: cute.TiledCopy + :param tTR_rC: The partitioned accumulator tensor + :type tTR_rC: cute.Tensor + :param tidx: The thread index in epilogue warp groups + :type tidx: cutlass.Int32 + :param sC: The shared memory tensor to be copied and partitioned + :type sC: cute.Tensor + + :return: A tuple containing (tiled_copy_s2r, tSR_rC, tSR_sC) where: + - tiled_copy_s2r: The tiled copy operation for smem to register copy(s2r) + - tSR_rC: The partitioned tensor C (register destination) + - tSR_sC: The partitioned tensor C (smem source) + :rtype: tuple[cute.TiledCopy, cute.Tensor, cute.Tensor] + """ + copy_atom_s2r = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), self.c_dtype) + tiled_copy_s2r = cute.make_tiled_copy_D(copy_atom_s2r, tiled_copy_t2r) + # (S2R, S2R_M, S2R_N, PIPE_C) + thr_copy_s2r = tiled_copy_s2r.get_slice(tidx) + tSR_sC = thr_copy_s2r.partition_D(sC) + # (S2R, S2R_M, S2R_N) + tSR_rC = tiled_copy_s2r.retile(tTR_rC) + return tiled_copy_s2r, tSR_rC, tSR_sC + + def epilogue_gmem_copy_and_partition( + self, + tidx: cutlass.Int32, + atom: cute.CopyAtom | cute.TiledCopy, + gC_mnl: cute.Tensor, + epi_tile: cute.Tile, + sC: cute.Tensor, + dtype: type[cutlass.Numeric], + ) -> tuple[cute.CopyAtom, cute.Tensor, cute.Tensor]: + """Make tiledCopy for global memory store, then use it to: + - partition register array (source) and global memory (destination) for non-TMA store version; + - partition shared memory (source) and global memory (destination) for TMA store version. + + :param tidx: The thread index in epilogue warp groups + :type tidx: cutlass.Int32 + :param atom: The copy_atom_c to be used for TMA store version, or tiled_copy_t2r for non-TMA store version + :type atom: cute.CopyAtom or cute.TiledCopy + :param gC_mnl: The global tensor C + :type gC_mnl: cute.Tensor + :param epi_tile: The epilogue tiler + :type epi_tile: cute.Tile + :param sC: The shared memory tensor to be copied and partitioned + :type sC: cute.Tensor + + :return: A tuple containing either: + - For TMA store: (tma_atom_c, bSG_sC, bSG_gC) where: + - tma_atom_c: The TMA copy atom + - bSG_sC: The partitioned shared memory tensor C + - bSG_gC: The partitioned global tensor C + - For non-TMA store: (simt_atom, tTR_rC, tTR_gC) where: + - simt_atom: The SIMT copy atom + - tTR_rC: The register tensor C + - tTR_gC: The partitioned global tensor C + :rtype: tuple[cute.CopyAtom, cute.Tensor, cute.Tensor] + """ + # (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, tiles_m, tiles_n, tiles_l) + gC_epi = cute.flat_divide( + gC_mnl[((None, None), 0, 0, None, None, None)], epi_tile + ) + + tma_atom_c = atom + sC_for_tma_partition = cute.group_modes(sC, 0, 2) + gC_for_tma_partition = cute.group_modes(gC_epi, 0, 2) + # ((ATOM_V, REST_V), EPI_M, EPI_N) + # ((ATOM_V, REST_V), EPI_M, EPI_N, tiles_m, tiles_n, tiles_l) + bSG_sC, bSG_gC = cpasync.tma_partition( + tma_atom_c, + 0, + cute.make_layout(1), + sC_for_tma_partition, + gC_for_tma_partition, + ) + return tma_atom_c, bSG_sC, bSG_gC + + def compute_stages(self) -> None: + """Compute and set the number of stages for A/B/C/D operands. + + Uses instance attributes to compute and assign: + `self.num_acc_stage`, `self.num_ab_stage`, `self.num_c_stage`, + and `self.num_d_stage`. + """ + # Defaults + self.num_acc_stage = 2 + # To read the tensors needed for the epilogue: + self.num_c_stage = 2 + # To write the tensors produced by the epilogue: + self.num_d_stage = 2 + + # Calculate smem layout and size for one stage of A, B, C, and D + a_smem_layout_stage_one = sm100_utils.make_smem_layout_a( + self._tiled_mma, self.mma_tiler, self.a_dtype, 1 + ) + b_smem_layout_staged_one = sm100_utils.make_smem_layout_b( + self._tiled_mma, self.mma_tiler, self.b_dtype, 1 + ) + + # Get the contribution from the tensors used in the EFC. + self.efc.jit.compute_stage() + + ab_bytes_per_stage = cute.size_in_bytes( + self.a_dtype, a_smem_layout_stage_one + ) + cute.size_in_bytes(self.b_dtype, b_smem_layout_staged_one) + mbar_helpers_bytes = 2048 + self.local_reduce_smem_bytes + # Contribution from the tensors loaded in the EFC. + c_bytes_per_stage = self.efc.jit.smem_size_in_bytes_of_read_tensors() + c_bytes = c_bytes_per_stage * self.num_c_stage + # Contribution from the tensors stored in the EFC. There is at least 1 + # written tensor, so the following is strictly positive. + d_bytes_per_stage = self.efc.jit.smem_size_in_bytes_of_written_tensors() + d_bytes = d_bytes_per_stage * self.num_d_stage + + # Calculate A/B stages + self.num_ab_stage = ( + self.smem_capacity // self.occupancy + - (mbar_helpers_bytes + c_bytes + d_bytes) + ) // ab_bytes_per_stage + log(f"{common_efc.TAB}{self.num_ab_stage = }") + + if self.num_ab_stage <= 0: + raise MemoryError("Not enough smem capacity to allocate all the tensors.") + + # Refine epilogue stages: + # Calculate remaining smem after allocating for A/B stages and reserved bytes. + # Add remaining unused smem to epilogue. + self.num_d_stage += ( + self.smem_capacity + - self.occupancy * ab_bytes_per_stage * self.num_ab_stage + - self.occupancy * (mbar_helpers_bytes + c_bytes + d_bytes) + ) // (self.occupancy * d_bytes_per_stage) + log(f"{common_efc.TAB}new {self.num_d_stage = }") + + @staticmethod + def _compute_grid( + d: cute.Tensor, + cta_tile_shape_mnk: tuple[int, int, int], + cluster_shape_mn: tuple[int, int], + max_active_clusters: cutlass.Constexpr, + ) -> tuple[utils.PersistentTileSchedulerParams, tuple[int, int, int]]: + """Use persistent tile scheduler to compute the grid size for the output tensor D. + + :param d: The output tensor D + :type d: cute.Tensor + :param cta_tile_shape_mnk: The shape (M, N, K) of the CTA tile. + :type cta_tile_shape_mnk: tuple[int, int, int] + :param cluster_shape_mn: Shape of each cluster in M, N dimensions. + :type cluster_shape_mn: tuple[int, int] + :param max_active_clusters: Maximum number of active clusters. + :type max_active_clusters: cutlass.Constexpr + + :return: A tuple containing: + - tile_sched_params: Parameters for the persistent tile scheduler. + - grid: Grid shape for kernel launch. + :rtype: tuple[utils.PersistentTileSchedulerParams, tuple[int, int, int]] + """ + log(f"compute_grid: {max_active_clusters = }") + d_shape = cute.slice_(cta_tile_shape_mnk, (None, None, 0)) + gd = cute.zipped_divide(d, tiler=d_shape) + num_ctas_mnl = gd[(0, (None, None, None))].shape + common_efc.if_debug( + lambda: cute.printf("compute_grid: num_ctas_mnl = {}", num_ctas_mnl) + ) + cluster_shape_mnl = (*cluster_shape_mn, 1) + + tile_sched_params = utils.PersistentTileSchedulerParams( + num_ctas_mnl, cluster_shape_mnl + ) + grid = utils.StaticPersistentTileScheduler.get_grid_shape( + tile_sched_params, max_active_clusters + ) + common_efc.if_debug(lambda: cute.printf("compute_grid: grid = {}", grid)) + return tile_sched_params, grid + + def compute_num_tmem_alloc_cols(self) -> None: + """Compute and set the number of tensor memory allocation columns. + + This method uses the instance attributes computed during setup to + determine the number of tensor memory allocation columns and stores + the result in `self.num_tmem_alloc_cols`. + """ + acc_shape = self._tiled_mma.partition_shape_C(self.mma_tiler[:2]) + log(f"compute_num_tmem_alloc_cols: {acc_shape = !s}") + tCtAcc_fake = self._tiled_mma.make_fragment_C( + cute.append(acc_shape, self.num_acc_stage) + ) + log(f"compute_num_tmem_alloc_cols: {tCtAcc_fake = !s}") + self.num_tmem_alloc_cols = utils.get_num_tmem_alloc_cols(tCtAcc_fake) + log(f"compute_num_tmem_alloc_cols: {self.num_tmem_alloc_cols = }") diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/kernels/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/kernels/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/kernels/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/kernels/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2582bc54f9ae94ff7a37df3a44d53080ab93b4fc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/kernels/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/kernels/__pycache__/cutedsl_grouped_gemm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/kernels/__pycache__/cutedsl_grouped_gemm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..633779876a1e4d5d321f908b18708257e5ab8f9a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/kernels/__pycache__/cutedsl_grouped_gemm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/kernels/cutedsl_grouped_gemm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/kernels/cutedsl_grouped_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c28f143f6af02ae11230fb125547121b0ce138 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/kernels/cutedsl_grouped_gemm.py @@ -0,0 +1,2387 @@ +# Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: BSD-3-Clause + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import argparse +import functools +from typing import List, Type, Union +from inspect import isclass + +import torch +import cuda.bindings.driver as cuda + +import cutlass +import cutlass.cute as cute +import cutlass.cute.testing as testing +import cutlass.utils as utils +import cutlass.pipeline as pipeline +from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait +from cutlass.cute.nvgpu import cpasync, tcgen05 +import cutlass.utils.blackwell_helpers as sm100_utils +import cutlass.torch as cutlass_torch + +""" +A grouped GEMM example for the NVIDIA Blackwell SM100 architecture using CUTE DSL + +This example demonstrates an implementation of grouped GEMM using a TMA plus Blackwell SM100 TensorCore +warp-specialized persistent kernel. +The grouped GEMM workload computes a batch of GEMM operations with distinct problem sizes. Pointers to matrices +in global memory are passed to the kernel in an array (also held in global memory). Similarly, problem shapes and +strides are also stored in arrays in GMEM. + +This differs from "Batched Array" GEMM since the size of each GEMM problem in the grouped GEMM concept may be distinct. + +To run this example: + +.. code-block:: bash + + python examples/blackwell/grouped_gemm.py \ + --ab_dtype Float16 --c_dtype Float16 --acc_dtype Float32 \ + --mma_tiler_mn 128,64 --cluster_shape_mn 1,1 \ + --problem_sizes_mnkl "(8192,1280,32,1),(16,384,1536,1),(640,1280,16,1),(640,160,16,1)" \ + --num_groups 4 --tensormap_update_mode SMEM + +The above example command makes 4 groups of different m, n, k sizes. The Blackwell tcgen05 MMA tile shape +is specified as (128, 64) and the cluster shape is (1,1). The input, mma accumulator and output data type +are set as fp16, fp32 and fp16, respectively. + +To collect performance with NCU profiler: + +.. code-block:: bash + + ncu python examples/blackwell/grouped_gemm.py \ + --ab_dtype Float16 --c_dtype Float16 --acc_dtype Float32 \ + --mma_tiler_mn 128,64 --cluster_shape_mn 1,1 \ + --problem_sizes_mnkl "(8192,1280,32,1),(16,384,1536,1),(640,1280,16,1),(640,160,16,1)" \ + --num_groups 4 --tensormap_update_mode SMEM \ + --warmup_iterations 1 --iterations 10 --skip_ref_check + +There are some constrains for this example. Besides the constrains from the Balckwell dense GEMM persistent example, +there are also the following constrains: +* Only fp16 and bf16 data types are supported as inputs. +* Output data types could be fp16, bf16 or fp32. +* The contiguous dimension of each tensor must be at least 16 bytes aligned. +* The l mode(aka, batch size) for each group must be 1. +* The majorness for A, B and C must be the same across all groups. +""" + + +class GroupedGemmKernel: + def __init__( + self, + acc_dtype: type[cutlass.Numeric], + use_2cta_instrs: bool, + mma_tiler_mn: tuple[int, int], + cluster_shape_mn: tuple[int, int], + tensormap_update_mode: utils.TensorMapUpdateMode = utils.TensorMapUpdateMode.SMEM, + ): + """Initializes the configuration for a Blackwell grouped GEMM kernel. + + Besides configurations for dense persistent GEMM, there is an extra config specific to grouped GEMM: + + Tensormap Update Mode: + - tensormap_update_mode: Specifies whether the tensormap is + updated in global memory(GMEM) or shared memory(SMEM). + The 2 modes are functionally equivalent and the difference are: + - We buffer 3 tensormaps in SMEM for A, B, and C tensors (each TMA descriptor takes 128B) when TMA updates performed on SMEM. + - Performance varies between modes depending on problem size; optimal choice differs across workloads. + + :param acc_dtype: Data type of the accumulator. + :type acc_dtype: type[cutlass.Numeric] + :param use_2cta_instrs: Boolean, True to use cta_group=2 MMA variant. + :type use_2cta_instrs: bool + :param mma_tiler_mn: tuple (M, N) shape of the MMA instruction. + :type mma_tiler_mn: tuple[int, int] + :param cluster_shape_mn: tuple (ClusterM, ClusterN) shape of the cluster. + :type cluster_shape_mn: tuple[int, int] + :param tensormap_update_mode: Mode for updating the tensormap (GMEM or SMEM), defaults to SMEM. + :type tensormap_update_mode: utils.TensorMapUpdateMode, optional + """ + self.acc_dtype: Type[cutlass.Numeric] = acc_dtype + self.use_2cta_instrs = use_2cta_instrs + self.cluster_shape_mn = cluster_shape_mn + # K dimension is deferred in _setup_attributes + self.mma_tiler = (*mma_tiler_mn, 1) + self.cta_group = ( + tcgen05.CtaGroup.TWO if use_2cta_instrs else tcgen05.CtaGroup.ONE + ) + + self.tensormap_update_mode = tensormap_update_mode + # Delegate tensormap ab initialization to MMA warp when SMEM mode is used for better latency hiding + self.delegate_tensormap_ab_init = ( + tensormap_update_mode == utils.TensorMapUpdateMode.SMEM + ) + + self.num_mcast_ctas_a = 1 + self.num_mcast_ctas_b = 1 + self.is_a_mcast = False + self.is_b_mcast = False + + self.occupancy = 1 + # Set specialized warp ids + self.epilog_warp_id = ( + 0, + 1, + 2, + 3, + ) + self.mma_warp_id = 4 + self.tma_warp_id = 5 + self.threads_per_cta = 32 * len( + (self.mma_warp_id, self.tma_warp_id, *self.epilog_warp_id) + ) + # Set barrier for epilog sync, tmem ptr sync and tensormap update sync + self.epilog_sync_barrier = pipeline.NamedBarrier( + barrier_id=1, + num_threads=32 * len(self.epilog_warp_id), + ) + self.tmem_alloc_barrier = pipeline.NamedBarrier( + barrier_id=2, + num_threads=32 * len((self.mma_warp_id, *self.epilog_warp_id)), + ) + # Barrier used by MMA/TMA warps to signal A/B tensormap initialization completion + self.tensormap_ab_init_barrier = pipeline.NamedBarrier( + barrier_id=3, + num_threads=32 * (len(self.epilog_warp_id) + 1), + ) + self.smem_capacity = utils.get_smem_capacity_in_bytes("sm_100") + self.num_tma_load_bytes = 0 + + def _setup_attributes(self): + """Set up configurations that are dependent on GEMM inputs + + Most of the implementation follows standard dense GEMM patterns, + with the key difference being additional consideration for SMEM + buffer needed for tensormap updates. + """ + # Configure tiled mma + tiled_mma = sm100_utils.make_trivial_tiled_mma( + self.a_dtype, + self.a_major_mode, + self.b_major_mode, + self.acc_dtype, + self.cta_group, + self.mma_tiler[:2], + ) + + # Compute mma/cluster/tile shapes + mma_inst_shape_k = cute.size(tiled_mma.shape_mnk, mode=[2]) + mma_inst_tile_k = 4 + self.mma_tiler = ( + self.mma_tiler[0], + self.mma_tiler[1], + mma_inst_shape_k * mma_inst_tile_k, + ) + self.cta_tile_shape_mnk = ( + self.mma_tiler[0] // cute.size(tiled_mma.thr_id.shape), + self.mma_tiler[1], + self.mma_tiler[2], + ) + self.cluster_tile_shape_mnk = tuple( + x * y for x, y in zip(self.cta_tile_shape_mnk, (*self.cluster_shape_mn, 1)) + ) + + # Compute cluster layout + self.cluster_layout_vmnk = cute.tiled_divide( + cute.make_layout((*self.cluster_shape_mn, 1)), + (tiled_mma.thr_id.shape,), + ) + + # Compute number of multicast CTAs for A/B + self.num_mcast_ctas_a = cute.size(self.cluster_layout_vmnk.shape[2]) + self.num_mcast_ctas_b = cute.size(self.cluster_layout_vmnk.shape[1]) + self.is_a_mcast = self.num_mcast_ctas_a > 1 + self.is_b_mcast = self.num_mcast_ctas_b > 1 + + # Compute epilogue subtile + self.epi_tile = utils.compute_epilogue_tile_shape( + self.cta_tile_shape_mnk, + self.use_2cta_instrs, + self.c_layout, + self.c_dtype, + ) + + # Setup A/B/C stage count in shared memory and ACC stage count in tensor memory + ( + self.num_acc_stage, + self.num_ab_stage, + self.num_epi_stage, + ) = self._compute_stages( + tiled_mma, + self.mma_tiler, + self.a_dtype, + self.b_dtype, + self.epi_tile, + self.c_dtype, + self.c_layout, + self.smem_capacity, + self.occupancy, + ) + + self.a_smem_layout_staged = sm100_utils.make_smem_layout_a( + tiled_mma, + self.mma_tiler, + self.a_dtype, + self.num_ab_stage, + ) + self.b_smem_layout_staged = sm100_utils.make_smem_layout_b( + tiled_mma, + self.mma_tiler, + self.b_dtype, + self.num_ab_stage, + ) + self.epi_smem_layout_staged = sm100_utils.make_smem_layout_epi( + self.c_dtype, + self.c_layout, + self.epi_tile, + self.num_epi_stage, + ) + + mbar_smem_bytes = self._get_mbar_smem_bytes( + num_acc_stage=self.num_acc_stage, + num_ab_stage=self.num_ab_stage, + num_epi_stage=self.num_epi_stage, + ) + tensormap_smem_bytes = self._get_tensormap_smem_bytes( + self.tensormap_update_mode + ) + if ( + mbar_smem_bytes + + tensormap_smem_bytes + + GroupedGemmKernel.tensor_memory_management_bytes + > self.reserved_smem_bytes + ): + raise ValueError( + f"smem consumption for mbar and tensormap {mbar_smem_bytes + tensormap_smem_bytes} exceeds the " + f"reserved smem bytes {self.reserved_smem_bytes}" + ) + + # Compute the number of tensor memory allocation columns + self.num_tmem_alloc_cols = self._compute_num_tmem_alloc_cols( + tiled_mma, self.mma_tiler, self.num_acc_stage + ) + + @cute.jit + def __call__( + self, + initial_a: cute.Tensor, + initial_b: cute.Tensor, + initial_c: cute.Tensor, + group_count: cutlass.Constexpr[int], + problem_shape_mnkl: cute.Tensor, + strides_abc: cute.Tensor, + tensor_address_abc: cute.Tensor, + total_num_clusters: cutlass.Constexpr[int], + tensormap_cute_tensor: cute.Tensor, + max_active_clusters: cutlass.Constexpr[int], + stream: cuda.CUstream, + ): + """Execute the GEMM operation in steps: + - Setup static attributes before smem/grid/tma computation + - Setup TMA load/store atoms and tensors + - Compute grid size with regard to hardware constraints + - Define shared storage for kernel + - Launch the kernel synchronously + + For grouped GEMM, tensor shapes, tensor strides, and tensor address are all provided + by different tensors in global memory. The "initial" tensors only carry data type and + majorness information. + + :param initial_a: Initial tensor A, used for data type and majorness information. + :type initial_a: cute.Tensor + :param initial_b: Initial tensor B, used for data type and majorness information. + :type initial_b: cute.Tensor + :param initial_c: Initial tensor C, used for data type and majorness information. + :type initial_c: cute.Tensor + :param group_count: The number of GEMM groups. + :type group_count: cutlass.Constexpr[int] + :param problem_shape_mnkl: Tensor containing the (M, N, K, L) shape for each group. + :type problem_shape_mnkl: cute.Tensor + :param strides_abc: Tensor containing the strides for A, B, and C for each group. + :type strides_abc: cute.Tensor + :param tensor_address_abc: Tensor containing the base addresses for A, B, and C for each group. + :type tensor_address_abc: cute.Tensor + :param total_num_clusters: Total number of clusters needed for all groups. + :type total_num_clusters: cutlass.Constexpr[int] + :param tensormap_cute_tensor: Tensor for storing tensormaps. + :type tensormap_cute_tensor: cute.Tensor + :param max_active_clusters: Maximum number of active clusters. + :type max_active_clusters: cutlass.Constexpr[int] + :param stream: CUDA stream for asynchronous execution. + :type stream: cuda.CUstream + :raises TypeError: If A and B data types do not match. + """ + + self.a_dtype = initial_a.element_type + self.b_dtype = initial_b.element_type + self.c_dtype = initial_c.element_type + + self.a_major_mode = utils.LayoutEnum.from_tensor(initial_a).mma_major_mode() + self.b_major_mode = utils.LayoutEnum.from_tensor(initial_b).mma_major_mode() + self.c_layout = utils.LayoutEnum.from_tensor(initial_c) + if cutlass.const_expr(self.a_dtype != self.b_dtype): + raise TypeError(f"Type mismatch: {self.a_dtype} != {self.b_dtype}") + + # Setup attributes that dependent on gemm inputs + self._setup_attributes() + + tiled_mma = sm100_utils.make_trivial_tiled_mma( + self.a_dtype, + self.a_major_mode, + self.b_major_mode, + self.acc_dtype, + self.cta_group, + self.mma_tiler[:2], + ) + atom_thr_size = cute.size(tiled_mma.thr_id.shape) + + # Setup TMA load for A + a_op = sm100_utils.cluster_shape_to_tma_atom_A( + self.cluster_shape_mn, tiled_mma.thr_id + ) + a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0)) + tma_atom_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A( + a_op, + initial_a, + a_smem_layout, + self.mma_tiler, + tiled_mma, + self.cluster_layout_vmnk.shape, + ) + + # Setup TMA load for B + b_op = sm100_utils.cluster_shape_to_tma_atom_B( + self.cluster_shape_mn, tiled_mma.thr_id + ) + b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0)) + tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B( + b_op, + initial_b, + b_smem_layout, + self.mma_tiler, + tiled_mma, + self.cluster_layout_vmnk.shape, + ) + + a_copy_size = cute.size_in_bytes(self.a_dtype, a_smem_layout) + b_copy_size = cute.size_in_bytes(self.b_dtype, b_smem_layout) + self.num_tma_load_bytes = (a_copy_size + b_copy_size) * atom_thr_size + + # Setup TMA store for C + tma_atom_c = None + tma_tensor_c = None + epi_smem_layout = cute.slice_(self.epi_smem_layout_staged, (None, None, 0)) + tma_atom_c, tma_tensor_c = cpasync.make_tiled_tma_atom( + cpasync.CopyBulkTensorTileS2GOp(), + initial_c, + epi_smem_layout, + self.epi_tile, + ) + + self.tile_sched_params, grid = self._compute_grid( + total_num_clusters, self.cluster_shape_mn, max_active_clusters + ) + + self.buffer_align_bytes = 1024 + self.size_tensormap_in_i64 = ( + 0 + if self.tensormap_update_mode == utils.TensorMapUpdateMode.GMEM + else GroupedGemmKernel.num_tensormaps + * GroupedGemmKernel.bytes_per_tensormap + // 8 + ) + + # Define shared storage for kernel + @cute.struct + class SharedStorage: + tensormap_buffer: cute.struct.MemRange[ + cutlass.Int64, self.size_tensormap_in_i64 + ] + ab_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage] + ab_empty_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage] + acc_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage] + acc_empty_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage] + tmem_dealloc_mbar: cutlass.Int64 + tmem_holding_buf: cutlass.Int32 + # (EPI_TILE_M, EPI_TILE_N, STAGE) + sC: cute.struct.Align[ + cute.struct.MemRange[ + self.c_dtype, + cute.cosize(self.epi_smem_layout_staged.outer), + ], + self.buffer_align_bytes, + ] + # (MMA, MMA_M, MMA_K, STAGE) + sA: cute.struct.Align[ + cute.struct.MemRange[ + self.a_dtype, cute.cosize(self.a_smem_layout_staged.outer) + ], + self.buffer_align_bytes, + ] + # (MMA, MMA_N, MMA_K, STAGE) + sB: cute.struct.Align[ + cute.struct.MemRange[ + self.b_dtype, cute.cosize(self.b_smem_layout_staged.outer) + ], + self.buffer_align_bytes, + ] + + self.shared_storage = SharedStorage + + # Launch the kernel synchronously + self.kernel( + tiled_mma, + tma_atom_a, + tma_tensor_a, + tma_atom_b, + tma_tensor_b, + tma_atom_c, + tma_tensor_c, + self.cluster_layout_vmnk, + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.epi_smem_layout_staged, + self.epi_tile, + self.tile_sched_params, + group_count, + problem_shape_mnkl, + strides_abc, + tensor_address_abc, + tensormap_cute_tensor, + ).launch( + grid=grid, + block=[self.threads_per_cta, 1, 1], + cluster=(*self.cluster_shape_mn, 1), + stream=stream, + min_blocks_per_mp=1, + ) + return + + # GPU device kernel + @cute.kernel + def kernel( + self, + tiled_mma: cute.TiledMma, + tma_atom_a: cute.CopyAtom, + mA_mkl: cute.Tensor, + tma_atom_b: cute.CopyAtom, + mB_nkl: cute.Tensor, + tma_atom_c: cute.CopyAtom, + mC_mnl: cute.Tensor, + cluster_layout_vmnk: cute.Layout, + a_smem_layout_staged: cute.ComposedLayout, + b_smem_layout_staged: cute.ComposedLayout, + epi_smem_layout_staged: Union[cute.Layout, cute.ComposedLayout], + epi_tile: cute.Tile, + tile_sched_params: utils.PersistentTileSchedulerParams, + group_count: cutlass.Constexpr[int], + problem_sizes_mnkl: cute.Tensor, + strides_abc: cute.Tensor, + ptrs_abc: cute.Tensor, + tensormaps: cute.Tensor, + ): + """ + GPU device kernel performing the grouped GEMM computation. + """ + warp_idx = cute.arch.warp_idx() + warp_idx = cute.arch.make_warp_uniform(warp_idx) + + # + # Prefetch tma desc + # + if warp_idx == self.tma_warp_id: + cpasync.prefetch_descriptor(tma_atom_a) + cpasync.prefetch_descriptor(tma_atom_b) + cpasync.prefetch_descriptor(tma_atom_c) + + use_2cta_instrs = cute.size(tiled_mma.thr_id.shape) == 2 + + # + # Setup cta/thread coordinates + # + # Coord inside cluster + bid = cute.arch.block_idx() + mma_tile_coord_v = bid[0] % cute.size(tiled_mma.thr_id.shape) + is_leader_cta = mma_tile_coord_v == 0 + cta_rank_in_cluster = cute.arch.make_warp_uniform( + cute.arch.block_idx_in_cluster() + ) + block_in_cluster_coord_vmnk = cluster_layout_vmnk.get_flat_coord( + cta_rank_in_cluster + ) + # Coord inside cta + tidx, _, _ = cute.arch.thread_idx() + + # + # Alloc and init: tensormap buffer, a+b full/empty, accumulator full/empty, tensor memory dealloc barrier + # + smem = utils.SmemAllocator() + storage = smem.allocate(self.shared_storage) + + tensormap_a_smem_ptr = None + tensormap_b_smem_ptr = None + tensormap_c_smem_ptr = None + if cutlass.const_expr( + self.tensormap_update_mode == utils.TensorMapUpdateMode.SMEM + ): + tensormap_smem_ptr = storage.tensormap_buffer.data_ptr() + tensormap_a_smem_ptr = tensormap_smem_ptr + tensormap_b_smem_ptr = ( + tensormap_a_smem_ptr + GroupedGemmKernel.bytes_per_tensormap // 8 + ) + tensormap_c_smem_ptr = ( + tensormap_b_smem_ptr + GroupedGemmKernel.bytes_per_tensormap // 8 + ) + + # init barrier for loading A, B with TMA + ab_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + num_tma_producer = self.num_mcast_ctas_a + self.num_mcast_ctas_b - 1 + ab_pipeline_consumer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, num_tma_producer + ) + ab_pipeline = pipeline.PipelineTmaUmma.create( + barrier_storage=storage.ab_full_mbar_ptr.data_ptr(), + num_stages=self.num_ab_stage, + producer_group=ab_pipeline_producer_group, + consumer_group=ab_pipeline_consumer_group, + tx_count=self.num_tma_load_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + # Accumulator barrier init + acc_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + num_acc_consumer_threads = len(self.epilog_warp_id) * ( + 2 if use_2cta_instrs else 1 + ) + acc_pipeline_consumer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, num_acc_consumer_threads + ) + acc_pipeline = pipeline.PipelineUmmaAsync.create( + barrier_storage=storage.acc_full_mbar_ptr.data_ptr(), + num_stages=self.num_acc_stage, + producer_group=acc_pipeline_producer_group, + consumer_group=acc_pipeline_consumer_group, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + # Tensor memory dealloc barrier init + tmem = utils.TmemAllocator( + storage.tmem_holding_buf.ptr, + barrier_for_retrieve=self.tmem_alloc_barrier, + allocator_warp_id=self.epilog_warp_id[0], + is_two_cta=use_2cta_instrs, + two_cta_tmem_dealloc_mbar_ptr=storage.tmem_dealloc_mbar.ptr, + ) + + # Cluster arrive after barrier init + pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mn, is_relaxed=True) + + # + # Setup smem tensor A/B/C + # + # (EPI_TILE_M, EPI_TILE_N, STAGE) + sC = storage.sC.get_tensor( + epi_smem_layout_staged.outer, swizzle=epi_smem_layout_staged.inner + ) + # (MMA, MMA_M, MMA_K, STAGE) + sA = storage.sA.get_tensor( + a_smem_layout_staged.outer, swizzle=a_smem_layout_staged.inner + ) + # (MMA, MMA_N, MMA_K, STAGE) + sB = storage.sB.get_tensor( + b_smem_layout_staged.outer, swizzle=b_smem_layout_staged.inner + ) + + # + # Compute multicast mask for A/B buffer full and empty + # + a_full_mcast_mask = None + b_full_mcast_mask = None + ab_empty_mcast_mask = None + if cutlass.const_expr(self.is_a_mcast or self.is_b_mcast or use_2cta_instrs): + a_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=2 + ) + b_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=1 + ) + ab_empty_mcast_mask = a_full_mcast_mask | b_full_mcast_mask + acc_full_mcast_mask = None + if cutlass.const_expr(use_2cta_instrs): + acc_full_mcast_mask = cute.make_layout_image_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mode=0 + ) + block_in_cluster_coord_vmnk_peer = ( + block_in_cluster_coord_vmnk[0] ^ 1, + *block_in_cluster_coord_vmnk[1:], + ) + a_full_mcast_mask_peer = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk_peer, mcast_mode=2 + ) + b_full_mcast_mask_peer = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk_peer, mcast_mode=1 + ) + ab_empty_mcast_mask = ( + a_full_mcast_mask_peer + | b_full_mcast_mask_peer + | cutlass.Int16( + 0 if ab_empty_mcast_mask is None else ab_empty_mcast_mask + ) + ) + + # + # Local_tile partition global tensors + # + # (bM, bK, RestM, RestK, RestL) + gA_mkl = cute.local_tile( + mA_mkl, cute.slice_(self.mma_tiler, (None, 0, None)), (None, None, None) + ) + # (bN, bK, RestN, RestK, RestL) + gB_nkl = cute.local_tile( + mB_nkl, cute.slice_(self.mma_tiler, (0, None, None)), (None, None, None) + ) + # (bM, bN, RestM, RestN, RestL) + gC_mnl = cute.local_tile( + mC_mnl, cute.slice_(self.mma_tiler, (None, None, 0)), (None, None, None) + ) + + # + # Partition global tensor for TiledMMA_A/B/C + # + thr_mma = tiled_mma.get_slice(mma_tile_coord_v) + # (MMA, MMA_M, MMA_K, RestM, RestK, RestL) + tCgA = thr_mma.partition_A(gA_mkl) + # (MMA, MMA_N, MMA_K, RestN, RestK, RestL) + tCgB = thr_mma.partition_B(gB_nkl) + # (MMA, MMA_M, MMA_N, RestM, RestN, RestL) + tCgC = thr_mma.partition_C(gC_mnl) + + # + # Partition global/shared tensor for load A, B with TMA + # + a_cta_layout = cute.make_layout( + cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape + ) + # ((atom_v, rest_v), STAGE) + # ((atom_v, rest_v), RestM, RestK, RestL) + tAsA, tAgA = cpasync.tma_partition( + tma_atom_a, + block_in_cluster_coord_vmnk[2], + a_cta_layout, + cute.group_modes(sA, 0, 3), + cute.group_modes(tCgA, 0, 3), + ) + # TMA load B partition_S/D + b_cta_layout = cute.make_layout( + cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape + ) + # ((atom_v, rest_v), STAGE) + # ((atom_v, rest_v), RestM, RestK, RestL) + tBsB, tBgB = cpasync.tma_partition( + tma_atom_b, + block_in_cluster_coord_vmnk[1], + b_cta_layout, + cute.group_modes(sB, 0, 3), + cute.group_modes(tCgB, 0, 3), + ) + + # + # Partition shared/tensor memory tensor for TiledMMA_A/B/C + # + # (MMA, MMA_M, MMA_K, STAGE) + tCrA = tiled_mma.make_fragment_A(sA) + # (MMA, MMA_N, MMA_K, STAGE) + tCrB = tiled_mma.make_fragment_B(sB) + # (MMA, MMA_M, MMA_N) + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_fake = tiled_mma.make_fragment_C( + cute.append(acc_shape, self.num_acc_stage) + ) + + # + # Cluster wait before tensor memory alloc + # + pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mn) + + # + # Get tensormap buffer address + # + grid_dim = cute.arch.grid_dim() + tensormap_workspace_idx = ( + bid[2] * grid_dim[1] * grid_dim[0] + bid[1] * grid_dim[0] + bid[0] + ) + + tensormap_manager = utils.TensorMapManager( + self.tensormap_update_mode, GroupedGemmKernel.bytes_per_tensormap + ) + tensormap_a_ptr = tensormap_manager.get_tensormap_ptr( + tensormaps[(tensormap_workspace_idx, 0, None)].iterator + ) + tensormap_b_ptr = tensormap_manager.get_tensormap_ptr( + tensormaps[(tensormap_workspace_idx, 1, None)].iterator + ) + tensormap_c_ptr = tensormap_manager.get_tensormap_ptr( + tensormaps[(tensormap_workspace_idx, 2, None)].iterator + ) + # Setup tensormap initialization pointer based on the mode + if cutlass.const_expr( + self.tensormap_update_mode == utils.TensorMapUpdateMode.SMEM + ): + tensormap_a_init_ptr = tensormap_a_smem_ptr + tensormap_b_init_ptr = tensormap_b_smem_ptr + tensormap_c_init_ptr = tensormap_c_smem_ptr + else: + tensormap_a_init_ptr = tensormap_a_ptr + tensormap_b_init_ptr = tensormap_b_ptr + tensormap_c_init_ptr = tensormap_c_ptr + + # + # Persistent tile scheduling loop + # + # When the problem shapes are on device, we launch one CTA per SM. + # The if condition later prevents the warps from extra CTAs from doing any work. + tile_sched = utils.StaticPersistentGroupTileScheduler.create( + tile_sched_params, + bid, + grid_dim, + self.cluster_tile_shape_mnk, + utils.create_initial_search_state(), + group_count, + problem_sizes_mnkl, + ) + initial_work_tile_info = tile_sched.initial_work_tile_info() + + # + # Specialized TMA load warp + # + if warp_idx == self.tma_warp_id and initial_work_tile_info.is_valid_tile: + # Initialize tensormaps for A, B + if cutlass.const_expr(self.delegate_tensormap_ab_init == False): + tensormap_manager.init_tensormap_from_atom( + tma_atom_a, tensormap_a_init_ptr, self.tma_warp_id + ) + tensormap_manager.init_tensormap_from_atom( + tma_atom_b, tensormap_b_init_ptr, self.tma_warp_id + ) + + tensormap_init_done = cutlass.Boolean(False) + # group index of last tile + last_group_idx = cutlass.Int32(-1) + + work_tile = initial_work_tile_info + ab_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_ab_stage + ) + + while work_tile.is_valid_tile: + grouped_gemm_cta_tile_info = work_tile.group_search_result + + cur_k_tile_cnt = grouped_gemm_cta_tile_info.cta_tile_count_k + is_k_tile_cnt_zero = cur_k_tile_cnt == 0 + cur_group_idx = grouped_gemm_cta_tile_info.group_idx + # Do not load any data if cur_k_tile_cnt is 0 + if not is_k_tile_cnt_zero: + is_group_changed = cur_group_idx != last_group_idx + # skip tensormap update if we're working on the same group + if is_group_changed: + real_tensor_a = self.make_tensor_for_tensormap_update( + cur_group_idx, + self.a_dtype, + ( + grouped_gemm_cta_tile_info.problem_shape_m, + grouped_gemm_cta_tile_info.problem_shape_n, + grouped_gemm_cta_tile_info.problem_shape_k, + ), + strides_abc, + ptrs_abc, + 0, # 0 for tensor A + ) + real_tensor_b = self.make_tensor_for_tensormap_update( + cur_group_idx, + self.b_dtype, + ( + grouped_gemm_cta_tile_info.problem_shape_m, + grouped_gemm_cta_tile_info.problem_shape_n, + grouped_gemm_cta_tile_info.problem_shape_k, + ), + strides_abc, + ptrs_abc, + 1, # 1 for tensor B + ) + # wait tensormap initialization complete before update + if not tensormap_init_done: + if cutlass.const_expr(self.delegate_tensormap_ab_init): + self.tensormap_ab_init_barrier.arrive_and_wait() + tensormap_manager.fence_tensormap_initialization() + tensormap_init_done = True + + tensormap_manager.update_tensormap( + (real_tensor_a, real_tensor_b), + (tma_atom_a, tma_atom_b), + (tensormap_a_ptr, tensormap_b_ptr), + self.tma_warp_id, + (tensormap_a_smem_ptr, tensormap_b_smem_ptr), + ) + + mma_tile_coord_mnl = ( + grouped_gemm_cta_tile_info.cta_tile_idx_m + // cute.size(tiled_mma.thr_id.shape), + grouped_gemm_cta_tile_info.cta_tile_idx_n, + 0, + ) + + # + # Slice to per mma tile index + # + # ((atom_v, rest_v), RestK) + tAgA_slice = tAgA[ + (None, mma_tile_coord_mnl[0], None, mma_tile_coord_mnl[2]) + ] + # ((atom_v, rest_v), RestK) + tBgB_slice = tBgB[ + (None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2]) + ] + + # Peek (try_wait) AB buffer empty for k_tile = prefetch_k_tile_cnt + ab_producer_state.reset_count() + peek_ab_empty_status = cutlass.Boolean(1) + if ab_producer_state.count < cur_k_tile_cnt: + peek_ab_empty_status = ab_pipeline.producer_try_acquire( + ab_producer_state + ) + # ensure the update to tensormap has completed before using it + if is_group_changed: + tensormap_manager.fence_tensormap_update(tensormap_a_ptr) + tensormap_manager.fence_tensormap_update(tensormap_b_ptr) + # + # Tma load loop + # + for k_tile in cutlass.range(0, cur_k_tile_cnt, 1, unroll=1): + # Wait for AB buffer empty + ab_pipeline.producer_acquire( + ab_producer_state, peek_ab_empty_status + ) + + # Load A/B with TMA + cute.copy( + tma_atom_a, + tAgA_slice[(None, ab_producer_state.count)], + tAsA[(None, ab_producer_state.index)], + tma_bar_ptr=ab_pipeline.producer_get_barrier( + ab_producer_state + ), + mcast_mask=a_full_mcast_mask, + tma_desc_ptr=tensormap_manager.get_tensormap_ptr( + tensormap_a_ptr, + cute.AddressSpace.generic, + ), + ) + cute.copy( + tma_atom_b, + tBgB_slice[(None, ab_producer_state.count)], + tBsB[(None, ab_producer_state.index)], + tma_bar_ptr=ab_pipeline.producer_get_barrier( + ab_producer_state + ), + mcast_mask=b_full_mcast_mask, + tma_desc_ptr=tensormap_manager.get_tensormap_ptr( + tensormap_b_ptr, + cute.AddressSpace.generic, + ), + ) + + # Peek (try_wait) AB buffer empty for k_tile = prefetch_k_tile_cnt + k_tile + 1 + ab_producer_state.advance() + peek_ab_empty_status = cutlass.Boolean(1) + if ab_producer_state.count < cur_k_tile_cnt: + peek_ab_empty_status = ab_pipeline.producer_try_acquire( + ab_producer_state + ) + else: + # If tensormap initialization is not done, wait for it to complete + if not tensormap_init_done: + if cutlass.const_expr(self.delegate_tensormap_ab_init): + self.tensormap_ab_init_barrier.arrive_and_wait() + tensormap_manager.fence_tensormap_initialization() + tensormap_init_done = True + # Advance to next tile + tile_sched.advance_to_next_work() + work_tile = tile_sched.get_current_work() + last_group_idx = cur_group_idx + + # + # Wait A/B buffer empty + # + ab_pipeline.producer_tail(ab_producer_state) + + # + # Specialized MMA warp + # + if warp_idx == self.mma_warp_id and initial_work_tile_info.is_valid_tile: + # Bar sync for retrieve tmem ptr from shared mem + tmem.wait_for_alloc() + + # + # Retrieving tensor memory ptr and make accumulator tensor + # + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout) + + # + # Persistent tile scheduling loop + # + work_tile = initial_work_tile_info + ab_consumer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_ab_stage + ) + acc_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_acc_stage + ) + + # tile count we have searched + while work_tile.is_valid_tile: + cur_group_idx = work_tile.group_search_result.group_idx + problem_shape_k = work_tile.group_search_result.problem_shape_k + + # MMA warp is only interested in number of tiles along K dimension + cur_k_tile_cnt = ( + problem_shape_k + self.cluster_tile_shape_mnk[2] - 1 + ) // self.cluster_tile_shape_mnk[2] + is_k_tile_cnt_zero = cur_k_tile_cnt == 0 + + # (MMA, MMA_M, MMA_N) + tCtAcc = tCtAcc_base[(None, None, None, acc_producer_state.index)] + + # Peek (try_wait) AB buffer full for k_tile = 0 + ab_consumer_state.reset_count() + peek_ab_full_status = cutlass.Boolean(1) + if is_leader_cta: + if ab_consumer_state.count < cur_k_tile_cnt: + peek_ab_full_status = ab_pipeline.consumer_try_wait( + ab_consumer_state + ) + + # + # Wait for accumulator buffer empty + # + if not is_k_tile_cnt_zero: + acc_pipeline.producer_acquire(acc_producer_state) + + # + # Reset the ACCUMULATE field for each tile + # + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + + # + # Mma mainloop + # + for k_tile in cutlass.range(0, cur_k_tile_cnt, 1, unroll=1): + # Wait for AB buffer full + ab_pipeline.consumer_wait( + ab_consumer_state, peek_ab_full_status + ) + # tCtAcc += tCrA * tCrB + num_kblocks = cute.size(tCrA, mode=[2]) + for kblock_idx in cutlass.range(num_kblocks, unroll_full=True): + kblock_coord = ( + None, + None, + kblock_idx, + ab_consumer_state.index, + ) + + cute.gemm( + tiled_mma, + tCtAcc, + tCrA[kblock_coord], + tCrB[kblock_coord], + tCtAcc, + ) + # Enable accumulate on tCtAcc after first kblock + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + + # Async arrive AB buffer empty + ab_pipeline.consumer_release(ab_consumer_state) + + # Peek (try_wait) AB buffer full for k_tile = k_tile + 1 + ab_consumer_state.advance() + peek_ab_full_status = cutlass.Boolean(1) + if ab_consumer_state.count < cur_k_tile_cnt: + peek_ab_full_status = ab_pipeline.consumer_try_wait( + ab_consumer_state + ) + + # + # Async arrive accumulator buffer full + # + if not is_k_tile_cnt_zero: + acc_pipeline.producer_commit(acc_producer_state) + acc_producer_state.advance() + + # + # Advance to next tile + # + tile_sched.advance_to_next_work() + work_tile = tile_sched.get_current_work() + # + # Wait for accumulator buffer empty + # + acc_pipeline.producer_tail(acc_producer_state) + + # + # Specialized epilogue warps + # + if warp_idx < self.mma_warp_id and initial_work_tile_info.is_valid_tile: + # initialize tensormap A, B for TMA warp + if cutlass.const_expr(self.delegate_tensormap_ab_init): + tensormap_manager.init_tensormap_from_atom( + tma_atom_a, tensormap_a_init_ptr, self.epilog_warp_id[0] + ) + tensormap_manager.init_tensormap_from_atom( + tma_atom_b, tensormap_b_init_ptr, self.epilog_warp_id[0] + ) + # signal tensormap initialization has finished + self.tensormap_ab_init_barrier.arrive_and_wait() + # initialize tensorap for C + tensormap_manager.init_tensormap_from_atom( + tma_atom_c, + tensormap_c_init_ptr, + self.epilog_warp_id[0], + ) + # Alloc tensor memory buffer + tmem.allocate(self.num_tmem_alloc_cols) + + # + # Bar sync for retrieve tensor memory ptr from shared memory + # + tmem.wait_for_alloc() + + # + # Retrieving tensor memory ptr and make accumulator tensor + # + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout) + + epi_tidx = tidx + # + # Partition for epilogue + # + ( + tiled_copy_t2r, + tTR_tAcc_base, + tTR_rAcc, + ) = self.epilog_tmem_copy_and_partition( + epi_tidx, tCtAcc_base, tCgC, epi_tile, use_2cta_instrs + ) + + tTR_rC = cute.make_rmem_tensor(tTR_rAcc.shape, self.c_dtype) + tiled_copy_r2s, tRS_rC, tRS_sC = self.epilog_smem_copy_and_partition( + tiled_copy_t2r, tTR_rC, epi_tidx, sC + ) + ( + tma_atom_c, + bSG_sC, + bSG_gC_partitioned, + ) = self.epilog_gmem_copy_and_partition(tma_atom_c, tCgC, epi_tile, sC) + + # + # Persistent tile scheduling loop + # + + work_tile = initial_work_tile_info + + # wait tensormap initialization complete before update + tensormap_manager.fence_tensormap_initialization() + acc_consumer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_acc_stage + ) + # Threads/warps participating in tma store pipeline + c_producer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, + 32 * len(self.epilog_warp_id), + ) + c_pipeline = pipeline.PipelineTmaStore.create( + num_stages=self.num_epi_stage, + producer_group=c_producer_group, + ) + # group index of last tile + last_group_idx = cutlass.Int32(-1) + while work_tile.is_valid_tile: + grouped_gemm_cta_tile_info = work_tile.group_search_result + cur_group_idx = grouped_gemm_cta_tile_info.group_idx + cur_k_tile_cnt = grouped_gemm_cta_tile_info.cta_tile_count_k + is_k_tile_cnt_zero = cur_k_tile_cnt == 0 + is_group_changed = cur_group_idx != last_group_idx + # We still need to store 0s when k_tile_cnt is 0 + if is_group_changed: + # construct tensor C based on real address, shape and stride information + real_tensor_c = self.make_tensor_for_tensormap_update( + cur_group_idx, + self.c_dtype, + ( + grouped_gemm_cta_tile_info.problem_shape_m, + grouped_gemm_cta_tile_info.problem_shape_n, + grouped_gemm_cta_tile_info.problem_shape_k, + ), + strides_abc, + ptrs_abc, + 2, # 2 for tensor C + ) + tensormap_manager.update_tensormap( + ((real_tensor_c),), + ((tma_atom_c),), + ((tensormap_c_ptr),), + self.epilog_warp_id[0], + (tensormap_c_smem_ptr,), + ) + + mma_tile_coord_mnl = ( + grouped_gemm_cta_tile_info.cta_tile_idx_m + // cute.size(tiled_mma.thr_id.shape), + grouped_gemm_cta_tile_info.cta_tile_idx_n, + 0, + ) + + # + # Slice to per mma tile index + # + # ((ATOM_V, REST_V), EPI_M, EPI_N) + bSG_gC = bSG_gC_partitioned[ + ( + None, + None, + None, + *mma_tile_coord_mnl, + ) + ] + # (T2R, T2R_M, T2R_N, EPI_M, EPI_M) + tTR_tAcc = tTR_tAcc_base[ + (None, None, None, None, None, acc_consumer_state.index) + ] + # + # Wait for accumulator buffer full + # + # Not waiting for accumulator buffer full when k_tile_cnt is 0 + if not is_k_tile_cnt_zero: + acc_pipeline.consumer_wait(acc_consumer_state) + + tTR_tAcc = cute.group_modes(tTR_tAcc, 3, cute.rank(tTR_tAcc)) + bSG_gC = cute.group_modes(bSG_gC, 1, cute.rank(bSG_gC)) + # ensure the update to tensormap has completed before using it + if is_group_changed: + if warp_idx == self.epilog_warp_id[0]: + tensormap_manager.fence_tensormap_update(tensormap_c_ptr) + # + # Store accumulator to global memory in subtiles + # + subtile_cnt = cute.size(tTR_tAcc.shape, mode=[3]) + num_prev_subtiles = tile_sched.num_tiles_executed * subtile_cnt + for subtile_idx in range(subtile_cnt): + # + # Store C to shared memory + # + epi_buffer = (num_prev_subtiles + subtile_idx) % self.num_epi_stage + # + # Load accumulator from tensor memory buffer to register + # + tTR_tAcc_mn = tTR_tAcc[(None, None, None, subtile_idx)] + if not is_k_tile_cnt_zero: + cute.copy(tiled_copy_t2r, tTR_tAcc_mn, tTR_rAcc) + + # + # Convert to output type + # + acc_vec = tiled_copy_r2s.retile(tTR_rAcc).load() + tRS_rC.store(acc_vec.to(self.c_dtype)) + else: + tRS_rC.fill(0) + cute.copy( + tiled_copy_r2s, + tRS_rC, + tRS_sC[(None, None, None, epi_buffer)], + ) + # Fence and barrier to make sure shared memory store is visible to TMA store + cute.arch.fence_proxy( + "async.shared", + space="cta", + ) + self.epilog_sync_barrier.arrive_and_wait() + # + # store C to global memory with TMA + # + if warp_idx == self.epilog_warp_id[0]: + cute.copy( + tma_atom_c, + bSG_sC[(None, epi_buffer)], + bSG_gC[(None, subtile_idx)], + tma_desc_ptr=tensormap_manager.get_tensormap_ptr( + tensormap_c_ptr, + cute.AddressSpace.generic, + ), + ) + # Fence and barrier to make sure shared memory store is visible to TMA store + c_pipeline.producer_commit() + c_pipeline.producer_acquire() + self.epilog_sync_barrier.arrive_and_wait() + # + # Async arrive accumulator buffer empty + # + if not is_k_tile_cnt_zero: + with cute.arch.elect_one(): + acc_pipeline.consumer_release(acc_consumer_state) + acc_consumer_state.advance() + + # + # Advance to next tile + # + tile_sched.advance_to_next_work() + work_tile = tile_sched.get_current_work() + last_group_idx = cur_group_idx + + # + # Dealloc the tensor memory buffer + # + tmem.relinquish_alloc_permit() + self.epilog_sync_barrier.arrive_and_wait() + tmem.free(tmem_ptr) + + # + # Wait for C store complete + # + c_pipeline.producer_tail() + + @cute.jit + def make_tensor_for_tensormap_update( + self, + group_idx: cutlass.Int32, + dtype: Type[cutlass.Numeric], + problem_shape_mnk: tuple[cutlass.Int32, cutlass.Int32, cutlass.Int32], + strides_abc: cute.Tensor, + tensor_address_abc: cute.Tensor, + tensor_index: int, + ): + """Extract stride and tensor address for a given group and construct a global tensor. + + This function is used within the kernel to dynamically create a CUTE tensor + representing A, B, or C for the current group being processed, using the + group-specific address, shape, and stride information. + + :param group_idx: The index of the current group within the grouped GEMM. + :type group_idx: cutlass.Int32 + :param dtype: The data type of the tensor elements (e.g., cutlass.Float16). + :type dtype: Type[cutlass.Numeric] + :param problem_shape_mnk: The (M, N, K) problem shape for the current group. + :type problem_shape_mnk: tuple[cutlass.Int32, cutlass.Int32, cutlass.Int32] + :param strides_abc: Tensor containing strides for A, B, C for all groups. Layout: (group_count, 3, 2). + :type strides_abc: cute.Tensor + :param tensor_address_abc: Tensor containing global memory addresses for A, B, C for all groups. Layout: (group_count, 3). + :type tensor_address_abc: cute.Tensor + :param tensor_index: Specifies which tensor to create: 0 for A, 1 for B, 2 for C. + :type tensor_index: int + :return: A CUTE tensor representing the requested global memory tensor (A, B, or C) for the specified group. + :rtype: cute.Tensor + :raises TypeError: If the provided dtype is not a subclass of cutlass.Numeric. + """ + ptr_i64 = tensor_address_abc[(group_idx, tensor_index)] + if cutlass.const_expr( + not isclass(dtype) or not issubclass(dtype, cutlass.Numeric) + ): + raise TypeError( + f"dtype must be a type of cutlass.Numeric, got {type(dtype)}" + ) + tensor_gmem_ptr = cute.make_ptr( + dtype, ptr_i64, cute.AddressSpace.gmem, assumed_align=16 + ) + + strides_tensor_gmem = strides_abc[(group_idx, tensor_index, None)] + strides_tensor_reg = cute.make_rmem_tensor( + cute.make_layout(2), + strides_abc.element_type, + ) + cute.autovec_copy(strides_tensor_gmem, strides_tensor_reg) + stride_mn = strides_tensor_reg[0] + stride_k = strides_tensor_reg[1] + c1 = cutlass.Int32(1) + c0 = cutlass.Int32(0) + + if cutlass.const_expr(tensor_index == 0): # tensor A + m = problem_shape_mnk[0] + k = problem_shape_mnk[2] + return cute.make_tensor( + tensor_gmem_ptr, + cute.make_layout((m, k, c1), stride=(stride_mn, stride_k, c0)), + ) + elif cutlass.const_expr(tensor_index == 1): # tensor B + n = problem_shape_mnk[1] + k = problem_shape_mnk[2] + return cute.make_tensor( + tensor_gmem_ptr, + cute.make_layout((n, k, c1), stride=(stride_mn, stride_k, c0)), + ) + else: # tensor C + m = problem_shape_mnk[0] + n = problem_shape_mnk[1] + return cute.make_tensor( + tensor_gmem_ptr, + cute.make_layout((m, n, c1), stride=(stride_mn, stride_k, c0)), + ) + + def epilog_tmem_copy_and_partition( + self, + tidx: cutlass.Int32, + tAcc: cute.Tensor, + gC_mnl: cute.Tensor, + epi_tile: cute.Tile, + use_2cta_instrs: Union[cutlass.Boolean, bool], + ) -> tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]: + """ + Make tiledCopy for tensor memory load, then use it to partition tensor memory (source) and register array (destination). + + :param tidx: The thread index in epilogue warp groups + :type tidx: cutlass.Int32 + :param tAcc: The accumulator tensor to be copied and partitioned + :type tAcc: cute.Tensor + :param gC_mnl: The global tensor C + :type gC_mnl: cute.Tensor + :param epi_tile: The epilogue tiler + :type epi_tile: cute.Tile + :param use_2cta_instrs: Whether use_2cta_instrs is enabled + :type use_2cta_instrs: bool + + :return: A tuple containing (tiled_copy_t2r, tTR_tAcc, tTR_rAcc) where: + - tiled_copy_t2r: The tiled copy operation for tmem to register copy(t2r) + - tTR_tAcc: The partitioned accumulator tensor + - tTR_rAcc: The accumulated tensor in register used to hold t2r results + :rtype: Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor] + """ + # Make tiledCopy for tensor memory load(t2r) + copy_atom_t2r = sm100_utils.get_tmem_load_op( + self.cta_tile_shape_mnk, + self.c_layout, + self.c_dtype, + self.acc_dtype, + epi_tile, + use_2cta_instrs, + ) + # (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, STAGE) + tAcc_epi = cute.flat_divide( + tAcc[((None, None), 0, 0, None)], + epi_tile, + ) + # (EPI_TILE_M, EPI_TILE_N) + tiled_copy_t2r = tcgen05.make_tmem_copy( + copy_atom_t2r, tAcc_epi[(None, None, 0, 0, 0)] + ) + + thr_copy_t2r = tiled_copy_t2r.get_slice(tidx) + # (T2R, T2R_M, T2R_N, EPI_M, EPI_M, STAGE) + tTR_tAcc = thr_copy_t2r.partition_S(tAcc_epi) + + # (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, RestM, RestN, RestL) + gC_mnl_epi = cute.flat_divide( + gC_mnl[((None, None), 0, 0, None, None, None)], epi_tile + ) + # (T2R, T2R_M, T2R_N, EPI_M, EPI_N, RestM, RestN, RestL) + tTR_gC = thr_copy_t2r.partition_D(gC_mnl_epi) + # (T2R, T2R_M, T2R_N) + tTR_rAcc = cute.make_rmem_tensor( + tTR_gC[(None, None, None, 0, 0, 0, 0, 0)].shape, self.acc_dtype + ) + return tiled_copy_t2r, tTR_tAcc, tTR_rAcc + + def epilog_smem_copy_and_partition( + self, + tiled_copy_t2r: cute.TiledCopy, + tTR_rC: cute.Tensor, + tidx: cutlass.Int32, + sC: cute.Tensor, + ) -> tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]: + """ + Make tiledCopy for shared memory store, then use it to partition register array (source) and shared memory (destination). + + :param tiled_copy_t2r: The tiled copy operation for tmem to register copy(t2r) + :type tiled_copy_t2r: cute.TiledCopy + :param tTR_rC: The partitioned accumulator tensor + :type tTR_rC: cute.Tensor + :param tidx: The thread index in epilogue warp groups + :type tidx: cutlass.Int32 + :param sC: The shared memory tensor to be copied and partitioned + :type sC: cute.Tensor + + :return: A tuple containing (tiled_copy_r2s, tRS_rC, tRS_sC) where: + - tiled_copy_r2s: The tiled copy operation for register to smem copy(r2s) + - tRS_rC: The partitioned tensor C (register source) + - tRS_sC: The partitioned tensor C (smem destination) + :rtype: Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor] + """ + copy_atom_r2s = sm100_utils.get_smem_store_op( + self.c_layout, self.c_dtype, self.acc_dtype, tiled_copy_t2r + ) + tiled_copy_r2s = cute.make_tiled_copy_D(copy_atom_r2s, tiled_copy_t2r) + # (R2S, R2S_M, R2S_N, PIPE_D) + thr_copy_r2s = tiled_copy_r2s.get_slice(tidx) + tRS_sC = thr_copy_r2s.partition_D(sC) + # (R2S, R2S_M, R2S_N) + tRS_rC = tiled_copy_r2s.retile(tTR_rC) + return tiled_copy_r2s, tRS_rC, tRS_sC + + def epilog_gmem_copy_and_partition( + self, + tma_atom_c: cute.CopyAtom, + gC_mnl: cute.Tensor, + epi_tile: cute.Tile, + sC: cute.Tensor, + ) -> tuple[cute.CopyAtom, cute.Tensor, cute.Tensor]: + """Make tiledCopy for global memory store, then use it to partition + shared memory (source) and global memory (destination) for TMA store version. + + :param tma_atom_c: The TMA copy atom configured for storing tensor C. + :type tma_atom_c: cute.CopyAtom + :param gC_mnl: The global memory tensor C. + :type gC_mnl: cute.Tensor + :param epi_tile: The epilogue tiler defining the granularity of the operation. + :type epi_tile: cute.Tile + :param sC: The shared memory epilogue buffer tensor. + :type sC: cute.Tensor + :return: A tuple containing: + - tma_atom_c: The input TMA copy atom (passed through). + - bSG_sC: The source shared memory tensor partitioned for the TMA operation. + - tCgC: The destination global memory tensor partitioned for the TMA operation. + :rtype: tuple[cute.CopyAtom, cute.Tensor, cute.Tensor] + """ + # (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, RestM, RestN, RestL) + gC_epi = cute.flat_divide( + gC_mnl[((None, None), 0, 0, None, None, None)], epi_tile + ) + sC_for_tma_partition = cute.group_modes(sC, 0, 2) + gC_for_tma_partition = cute.group_modes(gC_epi, 0, 2) + # ((ATOM_V, REST_V), EPI_M, EPI_N) + # ((ATOM_V, REST_V), EPI_M, EPI_N, RestM, RestN, RestL) + bSG_sC, bSG_gC = cpasync.tma_partition( + tma_atom_c, + 0, + cute.make_layout(1), + sC_for_tma_partition, + gC_for_tma_partition, + ) + return tma_atom_c, bSG_sC, bSG_gC + + @staticmethod + def _compute_stages( + tiled_mma: cute.TiledMma, + mma_tiler_mnk: tuple[int, int, int], + a_dtype: type[cutlass.Numeric], + b_dtype: type[cutlass.Numeric], + epi_tile: cute.Tile, + c_dtype: type[cutlass.Numeric], + c_layout: utils.LayoutEnum, + smem_capacity: int, + occupancy: int, + ) -> tuple[int, int, int]: + """Computes the number of stages for accumulator, A/B operands, and epilogue based on heuristics. + + :param tiled_mma: The tiled MMA object defining the core computation. + :type tiled_mma: cute.TiledMma + :param mma_tiler_mnk: The shape (M, N, K) of the MMA tiler. + :type mma_tiler_mnk: tuple[int, int, int] + :param a_dtype: Data type of operand A. + :type a_dtype: type[cutlass.Numeric] + :param b_dtype: Data type of operand B. + :type b_dtype: type[cutlass.Numeric] + :param epi_tile: The epilogue tile shape. + :type epi_tile: cute.Tile + :param c_dtype: Data type of operand C (output). + :type c_dtype: type[cutlass.Numeric] + :param c_layout: Layout enum of operand C in global memory. + :type c_layout: utils.LayoutEnum + :param smem_capacity: Total available shared memory capacity in bytes. + :type smem_capacity: int + :param occupancy: Target number of CTAs per SM (occupancy). + :type occupancy: int + + :return: A tuple containing the computed number of stages for: + (accumulator stages, A/B operand stages, epilogue stages) + :rtype: tuple[int, int, int] + """ + # Default accumulator and epilogue stages + num_acc_stage = 2 + num_epi_stage = 2 + + # Calculate smem layout and size for one stage of A, B, and Epilogue + a_smem_layout_stage_one = sm100_utils.make_smem_layout_a( + tiled_mma, + mma_tiler_mnk, + a_dtype, + 1, # stage=1 + ) + b_smem_layout_staged_one = sm100_utils.make_smem_layout_b( + tiled_mma, + mma_tiler_mnk, + b_dtype, + 1, # stage=1 + ) + epi_smem_layout_staged_one = sm100_utils.make_smem_layout_epi( + c_dtype, + c_layout, + epi_tile, + 1, # stage=1 + ) + ab_bytes_per_stage = cute.size_in_bytes( + a_dtype, a_smem_layout_stage_one + ) + cute.size_in_bytes(b_dtype, b_smem_layout_staged_one) + + epi_bytes_per_stage = cute.size_in_bytes(c_dtype, epi_smem_layout_staged_one) + epi_bytes = epi_bytes_per_stage * num_epi_stage + + # Calculate A/B stages: + # Start with total smem per CTA (capacity / occupancy) + # Subtract reserved bytes and initial epilogue bytes + # Divide remaining by bytes needed per A/B stage + num_ab_stage = ( + smem_capacity // occupancy + - GroupedGemmKernel.reserved_smem_bytes + - epi_bytes + ) // ab_bytes_per_stage + + # Refine epilogue stages: + # Calculate remaining smem after allocating for A/B stages and reserved bytes + # Add remaining unused smem to epilogue + remaining_smem = ( + smem_capacity + - occupancy * ab_bytes_per_stage * num_ab_stage + - occupancy * (GroupedGemmKernel.reserved_smem_bytes + epi_bytes) + ) + num_epi_stage += remaining_smem // (occupancy * epi_bytes_per_stage) + return num_acc_stage, num_ab_stage, num_epi_stage + + @staticmethod + def _compute_grid( + total_num_clusters: int, + cluster_shape_mn: tuple[int, int], + max_active_clusters: cutlass.Constexpr[int], + ) -> tuple[utils.PersistentTileSchedulerParams, tuple[int, int, int]]: + """Compute tile scheduler parameters and grid shape for grouped GEMM operations. + + :param total_num_clusters: Total number of clusters to process across all groups. + :type total_num_clusters: int + :param cluster_shape_mn: Shape of each cluster in M, N dimensions. + :type cluster_shape_mn: tuple[int, int] + :param max_active_clusters: Maximum number of active clusters. + :type max_active_clusters: cutlass.Constexpr[int] + + :return: A tuple containing: + - tile_sched_params: Parameters for the persistent tile scheduler. + - grid: Grid shape for kernel launch. + :rtype: tuple[utils.PersistentTileSchedulerParams, tuple[int, ...]] + """ + # Create problem shape with M, N dimensions from cluster shape + # and L dimension representing the total number of clusters. + problem_shape_ntile_mnl = ( + cluster_shape_mn[0], + cluster_shape_mn[1], + cutlass.Int32(total_num_clusters), + ) + + tile_sched_params = utils.PersistentTileSchedulerParams( + problem_shape_ntile_mnl, (*cluster_shape_mn, 1) + ) + + grid = utils.StaticPersistentGroupTileScheduler.get_grid_shape( + tile_sched_params, max_active_clusters + ) + + return tile_sched_params, grid + + @staticmethod + def _get_mbar_smem_bytes(**kwargs_stages: int) -> int: + """Calculate shared memory consumption for memory barriers based on provided stages. + + Each stage requires 2 barriers, and each barrier consumes 8 bytes of shared memory. + The total consumption is the sum across all provided stages. This function calculates the total + shared memory needed for these barriers. + + :param kwargs_stages: Variable keyword arguments where each key is a stage name + (e.g., num_acc_stage, num_ab_stage) and each value is the + number of stages of that type. + :type kwargs_stages: int + :return: Total shared memory bytes required for all memory barriers. + :rtype: int + """ + num_barriers_per_stage = 2 + num_bytes_per_barrier = 8 + mbar_smem_consumption = sum( + [ + num_barriers_per_stage * num_bytes_per_barrier * stage + for stage in kwargs_stages.values() + ] + ) + return mbar_smem_consumption + + @staticmethod + def _get_tensormap_smem_bytes( + tensormap_update_mode: utils.TensorMapUpdateMode, + ) -> int: + """Get the SMEM consumption for the tensormap buffer based on the update mode. + + :param tensormap_update_mode: Specifies whether tensormaps are updated in GMEM or SMEM. + :type tensormap_update_mode: utils.TensorMapUpdateMode + :return: The shared memory bytes required for the tensormap buffer. Returns 0 if mode is GMEM. + :rtype: int + :raises ValueError: If an invalid tensormap update mode is provided. + """ + if tensormap_update_mode == utils.TensorMapUpdateMode.GMEM: + return 0 + elif tensormap_update_mode == utils.TensorMapUpdateMode.SMEM: + return ( + GroupedGemmKernel.bytes_per_tensormap * GroupedGemmKernel.num_tensormaps + ) + else: + raise ValueError(f"Invalid tensormap update mode: {tensormap_update_mode}") + + @staticmethod + def _compute_num_tmem_alloc_cols( + tiled_mma: cute.TiledMma, + mma_tiler: tuple[int, int, int], + num_acc_stage: int, + ) -> int: + """ + Compute the number of tensor memory allocation columns. + + :param tiled_mma: The tiled MMA object defining the core computation. + :type tiled_mma: cute.TiledMma + :param mma_tiler: The shape (M, N, K) of the MMA tile. + :type mma_tiler: tuple[int, int, int] + :param acc_stage: The stage of the accumulator tensor. + :type acc_stage: int + + :return: The number of tensor memory allocation columns. + :rtype: int + """ + acc_shape = tiled_mma.partition_shape_C(mma_tiler[:2]) + tCtAcc_fake = tiled_mma.make_fragment_C(cute.append(acc_shape, num_acc_stage)) + num_tmem_alloc_cols = utils.get_num_tmem_alloc_cols(tCtAcc_fake) + + return num_tmem_alloc_cols + + # Size of smem we reserved for mbarrier, tensor memory management and tensormap update + reserved_smem_bytes = 1024 + bytes_per_tensormap = 128 + num_tensormaps = 3 + # size of smem used for tensor memory management + tensor_memory_management_bytes = 12 + + +# Create tensor and return the pointer, tensor, and stride +def create_tensor_and_stride( + l: int, + mode0: int, + mode1: int, + is_mode0_major: bool, + dtype: type[cutlass.Numeric], + is_dynamic_layout: bool = True, + torch_tensor_cpu: torch.Tensor = None, +) -> tuple[int, torch.Tensor, cute.Tensor, torch.Tensor, tuple[int, int]]: + """Create GPU tensor from either a new or existing CPU tensor. + + :param torch_tensor_cpu: Optional existing CPU tensor to reuse. If None, creates a new one. + :type torch_tensor_cpu: torch.Tensor, optional + """ + if torch_tensor_cpu is None: + # Create new CPU tensor + torch_tensor_cpu = cutlass_torch.matrix(l, mode0, mode1, is_mode0_major, dtype) + + # Create GPU tensor from CPU tensor (new or existing) + cute_tensor, torch_tensor = cutlass_torch.cute_tensor_like( + torch_tensor_cpu, dtype, is_dynamic_layout, assumed_align=16 + ) + return ( + torch_tensor.data_ptr(), + torch_tensor, + cute_tensor, + torch_tensor_cpu, + torch_tensor.stride()[:-1], + ) + + +def create_tensors_for_all_groups( + problem_sizes_mnkl: List[tuple[int, int, int, int]], + ab_dtype: Type[cutlass.Numeric], + c_dtype: Type[cutlass.Numeric], + a_major: str, + b_major: str, + c_major: str, + torch_fp32_tensors_abc: List[List[torch.Tensor]] = None, +) -> tuple[ + List[List[int]], + List[List[torch.Tensor]], + List[tuple], + List[List[tuple]], + List[List[torch.Tensor]], +]: + if torch_fp32_tensors_abc is not None and len(torch_fp32_tensors_abc) != len( + problem_sizes_mnkl + ): + raise ValueError("torch_fp32_tensors_abc must have one entry per group") + + # Initialize lists to store tensors for all groups + new_torch_fp32_tensors_abc = ( + [] if torch_fp32_tensors_abc is None else torch_fp32_tensors_abc + ) + torch_tensors_abc = [] + cute_tensors_abc = [] + strides_abc = [] + ptrs_abc = [] + + # Iterate through all groups and create tensors for each group + for group_idx, (m, n, k, l) in enumerate(problem_sizes_mnkl): + # Get existing CPU tensors if available, otherwise None + existing_cpu_a = ( + torch_fp32_tensors_abc[group_idx][0] if torch_fp32_tensors_abc else None + ) + existing_cpu_b = ( + torch_fp32_tensors_abc[group_idx][1] if torch_fp32_tensors_abc else None + ) + existing_cpu_c = ( + torch_fp32_tensors_abc[group_idx][2] if torch_fp32_tensors_abc else None + ) + + # Create tensors (reusing CPU tensors if provided) + ( + ptr_a, + torch_tensor_a, + cute_tensor_a, + tensor_fp32_a, + stride_mk_a, + ) = create_tensor_and_stride( + l, m, k, a_major == "m", ab_dtype, torch_tensor_cpu=existing_cpu_a + ) + ( + ptr_b, + torch_tensor_b, + cute_tensor_b, + tensor_fp32_b, + stride_nk_b, + ) = create_tensor_and_stride( + l, n, k, b_major == "n", ab_dtype, torch_tensor_cpu=existing_cpu_b + ) + ( + ptr_c, + torch_tensor_c, + cute_tensor_c, + tensor_fp32_c, + stride_mn_c, + ) = create_tensor_and_stride( + l, m, n, c_major == "m", c_dtype, torch_tensor_cpu=existing_cpu_c + ) + + # Only append to new_torch_fp32_tensors_abc if we created new CPU tensors + if torch_fp32_tensors_abc is None: + new_torch_fp32_tensors_abc.append( + [tensor_fp32_a, tensor_fp32_b, tensor_fp32_c] + ) + + ptrs_abc.append([ptr_a, ptr_b, ptr_c]) + torch_tensors_abc.append([torch_tensor_a, torch_tensor_b, torch_tensor_c]) + strides_abc.append([stride_mk_a, stride_nk_b, stride_mn_c]) + cute_tensors_abc.append( + ( + cute_tensor_a, + cute_tensor_b, + cute_tensor_c, + ) + ) + + return ( + ptrs_abc, + torch_tensors_abc, + cute_tensors_abc, + strides_abc, + new_torch_fp32_tensors_abc, + ) + + +def run( + num_groups: int, + problem_sizes_mnkl: tuple[int, int, int, int], + host_problem_shape_available: bool, + ab_dtype: Type[cutlass.Numeric], + c_dtype: Type[cutlass.Numeric], + acc_dtype: Type[cutlass.Numeric], + a_major: str, + b_major: str, + c_major: str, + mma_tiler_mn: tuple[int, int], + cluster_shape_mn: tuple[int, int], + use_2cta_instrs: bool, + tensormap_update_mode: utils.TensorMapUpdateMode, + tolerance: float, + warmup_iterations: int, + iterations: int, + skip_ref_check: bool, + use_cold_l2: bool = False, + **kwargs, +): + """Run grouped GEMM example with specified configurations. + + :param use_cold_l2: Whether to use circular buffer strategy to ensure cold L2 cache, defaults to False + :type use_cold_l2: bool, optional + :return: Execution time of the GEMM kernel in microseconds + :rtype: float + """ + print("Running Blackwell Grouped GEMM test with:") + print(f"{num_groups} groups") + for i, (m, n, k, l) in enumerate(problem_sizes_mnkl): + print(f"Group {i}: {m}x{n}x{k}x{l}") + print(f"AB dtype: {ab_dtype}, C dtype: {c_dtype}, Acc dtype: {acc_dtype}") + print(f"Matrix majors - A: {a_major}, B: {b_major}, C: {c_major}") + print(f"Mma Tiler (M, N): {mma_tiler_mn}, Cluster Shape (M, N): {cluster_shape_mn}") + print(f"2CTA MMA instructions: {'True' if use_2cta_instrs else 'False'}") + print(f"Tensor map update mode: {tensormap_update_mode}") + print(f"Tolerance: {tolerance}") + print(f"Warmup iterations: {warmup_iterations}") + print(f"Iterations: {iterations}") + print(f"Skip reference checking: {skip_ref_check}") + print(f"Use cold L2: {'True' if use_cold_l2 else 'False'}") + + # Skip unsupported types + if ab_dtype not in { + cutlass.Float16, + cutlass.BFloat16, + }: + raise ValueError(f"Skip unsupported ab_dtype {ab_dtype}") + if c_dtype not in {cutlass.Float16, cutlass.BFloat16, cutlass.Float32}: + raise ValueError(f"Skip unsupported c_dtype {c_dtype}") + # Skip unsupported acc dtype + if acc_dtype not in {cutlass.Float32, cutlass.Float16}: + raise ValueError(f"Skip unsupported acc_dtype {acc_dtype}") + # Skip invalid ab_dtype and acc_dtype combination + if ab_dtype == cutlass.BFloat16 and acc_dtype == cutlass.Float16: + raise ValueError("Skip invalid ab_dtype and acc_dtype combination") + # Skip invalid mma tile shape + if not ( + (not use_2cta_instrs and mma_tiler_mn[0] in [64, 128]) + or (use_2cta_instrs and mma_tiler_mn[0] in [128, 256]) + ): + raise ValueError(f"Skip invalid mma tiler M {mma_tiler_mn[0]}") + if mma_tiler_mn[1] not in range(32, 257, 32): + raise ValueError(f"Skip invalid mma tiler N {mma_tiler_mn[1]}") + # Skip illegal cluster shape + if cluster_shape_mn[0] % (2 if use_2cta_instrs else 1) != 0: + raise ValueError( + f"cluster_shape_m need align with use_2cta_instrs config {cluster_shape_mn}" + ) + # Skip invalid cluster shape + is_power_of_2 = lambda x: x > 0 and (x & (x - 1)) == 0 + if ( + cluster_shape_mn[0] * cluster_shape_mn[1] > 16 + or cluster_shape_mn[0] <= 0 + or cluster_shape_mn[1] <= 0 + or not is_power_of_2(cluster_shape_mn[0]) + or not is_power_of_2(cluster_shape_mn[1]) + ): + raise ValueError(f"Skip invalid cluster shape {cluster_shape_mn}") + + # Skip illegal problem shape for load/store alignment + def check_contigous_16B_alignment(dtype, is_mode0_major, tensor_shape): + major_mode_idx = 0 if is_mode0_major else 1 + num_major_elements = tensor_shape[major_mode_idx] + num_contiguous_elements = 16 * 8 // dtype.width + return num_major_elements % num_contiguous_elements == 0 + + if ( + not check_contigous_16B_alignment(ab_dtype, a_major == "m", (m, k, l)) + or not check_contigous_16B_alignment(ab_dtype, b_major == "n", (n, k, l)) + or not check_contigous_16B_alignment(c_dtype, c_major == "m", (m, n, l)) + ): + raise ValueError("Skip invalid problem alignment") + if not torch.cuda.is_available(): + raise RuntimeError("GPU is required to run this example!") + + # Create tensors for all groups using the new function + ( + ptrs_abc, + torch_tensors_abc, + cute_tensors_abc, + strides_abc, + torch_fp32_tensors_abc, + ) = create_tensors_for_all_groups( + problem_sizes_mnkl, + ab_dtype, + c_dtype, + a_major, + b_major, + c_major, + ) + + # Setup inital tensors for TMA of A,B and C + alignment = 16 # 16 bytes aligned + min_ab_size = alignment * 8 // ab_dtype.width + min_c_size = alignment * 8 // c_dtype.width + initial_cute_tensors_abc = [ + create_tensor_and_stride(1, min_ab_size, min_ab_size, a_major == "m", ab_dtype)[ + 2 + ], + create_tensor_and_stride(1, min_ab_size, min_ab_size, b_major == "n", ab_dtype)[ + 2 + ], + create_tensor_and_stride(1, min_c_size, min_c_size, c_major == "m", c_dtype)[2], + ] + + hardware_info = utils.HardwareInfo() + sm_count = hardware_info.get_max_active_clusters(1) + max_active_clusters = hardware_info.get_max_active_clusters( + cluster_shape_mn[0] * cluster_shape_mn[1] + ) + + # Prepare tensormap buffer for each SM + num_tensormap_buffers = sm_count + tensormap_shape = ( + num_tensormap_buffers, + GroupedGemmKernel.num_tensormaps, + GroupedGemmKernel.bytes_per_tensormap // 8, + ) + tensor_of_tensormap, tensor_of_tensormap_torch = cutlass_torch.cute_tensor_like( + torch.empty(tensormap_shape, dtype=torch.int64), + cutlass.Int64, + is_dynamic_layout=False, + ) + + grouped_gemm = GroupedGemmKernel( + acc_dtype, + use_2cta_instrs, + mma_tiler_mn, + cluster_shape_mn, + tensormap_update_mode, + ) + + # layout (num_groups, 4):(4, 1) + ( + tensor_of_dim_size_mnkl, + tensor_of_dim_size_mnkl_torch, + ) = cutlass_torch.cute_tensor_like( + torch.tensor(problem_sizes_mnkl, dtype=torch.int32), + cutlass.Int32, + is_dynamic_layout=False, + assumed_align=16, + ) + + # layout (num_groups, 3, 2):(6, 2, 1) + tensor_of_strides_abc, tensor_of_strides_abc_torch = cutlass_torch.cute_tensor_like( + torch.tensor(strides_abc, dtype=torch.int32), + cutlass.Int32, + is_dynamic_layout=False, + assumed_align=16, + ) + + # layout (num_groups,3):(3, 1) + tensor_of_ptrs_abc, tensor_of_ptrs_abc_torch = cutlass_torch.cute_tensor_like( + torch.tensor(ptrs_abc, dtype=torch.int64), + cutlass.Int64, + is_dynamic_layout=False, + assumed_align=16, + ) + + # Compute total number of cluster tiles we need to compute for given grouped GEMM problem + def compute_total_num_clusters( + problem_sizes_mnkl: List[tuple[int, int, int, int]], + cluster_tile_shape_mn: tuple[int, int], + ) -> int: + total_num_clusters = 0 + for m, n, _, _ in problem_sizes_mnkl: + num_clusters_mn = tuple( + (x + y - 1) // y for x, y in zip((m, n), cluster_tile_shape_mn) + ) + total_num_clusters += functools.reduce(lambda x, y: x * y, num_clusters_mn) + return total_num_clusters + + # Compute cluster tile shape + def compute_cluster_tile_shape( + mma_tiler_mn: tuple[int, int], + cluster_shape_mn: tuple[int, int], + use_2cta_instrs: bool, + ) -> tuple[int, int]: + cta_tile_shape_mn = list(mma_tiler_mn) + if use_2cta_instrs: + cta_tile_shape_mn[0] = cta_tile_shape_mn[0] // 2 + return tuple(x * y for x, y in zip(cta_tile_shape_mn, cluster_shape_mn)) + + cluster_tile_shape_mn = compute_cluster_tile_shape( + mma_tiler_mn, cluster_shape_mn, use_2cta_instrs + ) + + # If the host problem shape is available, we will launch the grid with only + # the necessary clusters. The function compute_total_num_clusters() does that. + # If the problem shape only exists on device, we will need to launch all active + # clusters possible on a device. + if host_problem_shape_available: + print("Problem shapes available on host and device") + total_num_clusters = compute_total_num_clusters( + problem_sizes_mnkl, cluster_tile_shape_mn + ) + else: + print("Problem shapes available only on device") + total_num_clusters = max_active_clusters + + # Initialize Stream + current_stream = cutlass_torch.default_stream() + + # try to check CUDA version to decide the opt level + try: + from cutlass import CUDA_VERSION + + opt_level = ( + 3 + if CUDA_VERSION.major < 13 + or (CUDA_VERSION.major == 13 and CUDA_VERSION.minor < 1) + else 2 + ) + except ImportError: + opt_level = 3 + # Compile grouped GEMM kernel + compiled_grouped_gemm = cute.compile( + grouped_gemm, + initial_cute_tensors_abc[0], + initial_cute_tensors_abc[1], + initial_cute_tensors_abc[2], + num_groups, + tensor_of_dim_size_mnkl, + tensor_of_strides_abc, + tensor_of_ptrs_abc, + total_num_clusters, + tensor_of_tensormap, + max_active_clusters, + current_stream, + options=f"--opt-level {opt_level}", + ) + + if not skip_ref_check: + compiled_grouped_gemm( + initial_cute_tensors_abc[0], + initial_cute_tensors_abc[1], + initial_cute_tensors_abc[2], + tensor_of_dim_size_mnkl, + tensor_of_strides_abc, + tensor_of_ptrs_abc, + tensor_of_tensormap, + current_stream, + ) + + # Compute reference result + for i, (a, b, c) in enumerate(torch_tensors_abc): + ref = torch.einsum( + "mkl,nkl->mnl", + a.cpu().to(dtype=torch.float32), + b.cpu().to(dtype=torch.float32), + ) + print(f"checking group {i}") + torch.testing.assert_close( + c.cpu(), + ref.to(cutlass_torch.dtype(c_dtype)), + atol=tolerance, + rtol=1e-05, + ) + + if iterations <= 0: + return 0 + + def generate_tensors(): + # Reuse existing CPU tensors and create new GPU tensors from them + ( + ptrs_abc_workspace, + torch_tensors_abc_workspace, + cute_tensors_abc_workspace, + strides_abc_workspace, + _, + ) = create_tensors_for_all_groups( + problem_sizes_mnkl, + ab_dtype, + c_dtype, + a_major, + b_major, + c_major, + torch_fp32_tensors_abc, + ) + + initial_cute_tensors_abc_workspace = [ + create_tensor_and_stride( + 1, min_ab_size, min_ab_size, a_major == "m", ab_dtype + )[2], + create_tensor_and_stride( + 1, min_ab_size, min_ab_size, b_major == "n", ab_dtype + )[2], + create_tensor_and_stride( + 1, min_c_size, min_c_size, c_major == "m", c_dtype + )[2], + ] + + # Create new tensors for this workspace + tensor_of_strides_abc_workspace, _ = cutlass_torch.cute_tensor_like( + torch.tensor(strides_abc_workspace, dtype=torch.int32), + cutlass.Int32, + is_dynamic_layout=False, + assumed_align=16, + ) + + tensor_of_ptrs_abc_workspace, _ = cutlass_torch.cute_tensor_like( + torch.tensor(ptrs_abc_workspace, dtype=torch.int64), + cutlass.Int64, + is_dynamic_layout=False, + assumed_align=16, + ) + + tensormap_workspace, _ = cutlass_torch.cute_tensor_like( + torch.empty(tensormap_shape, dtype=torch.int64), + cutlass.Int64, + is_dynamic_layout=False, + ) + + args = testing.JitArguments( + initial_cute_tensors_abc_workspace[0], + initial_cute_tensors_abc_workspace[1], + initial_cute_tensors_abc_workspace[2], + tensor_of_dim_size_mnkl, + tensor_of_strides_abc_workspace, + tensor_of_ptrs_abc_workspace, + tensormap_workspace, + current_stream, + ) + args.add_to_scope([torch_tensors_abc_workspace]) + return args + + workspace_count = 1 + if use_cold_l2: + one_workspace_bytes = ( + sum( + [ + sum( + [ + torch_tensor.numel() * torch_tensor.element_size() + for torch_tensor in group_tensors + ] + ) + for group_tensors in torch_tensors_abc + ] + ) + + + # Add size of strides tensor + tensor_of_strides_abc_torch.numel() + * tensor_of_strides_abc_torch.element_size() + + + # Add size of ptrs tensor + tensor_of_ptrs_abc_torch.numel() * tensor_of_ptrs_abc_torch.element_size() + + + # Add size of tensormap tensor + tensor_of_tensormap_torch.numel() * tensor_of_tensormap_torch.element_size() + ) + workspace_count = testing.get_workspace_count( + one_workspace_bytes, warmup_iterations, iterations + ) + + exec_time = testing.benchmark( + compiled_grouped_gemm, + workspace_generator=generate_tensors, + workspace_count=workspace_count, + stream=current_stream, + warmup_iterations=warmup_iterations, + iterations=iterations, + ) + + runtime_s = exec_time / 1.0e6 + fmas = 0 + for group in range(num_groups): + [M, N, K, _] = problem_sizes_mnkl[group] + fmas += M * N * K + flop = 2 * fmas + gflop = flop / 1.0e9 + gflops = gflop / runtime_s + + print("Average Runtime : ", exec_time / 1000, "ms") + print("GFLOPS : ", gflops) + + return exec_time # Return execution time in microseconds + + +if __name__ == "__main__": + + def parse_comma_separated_ints(s: str) -> tuple[int, ...]: + try: + return tuple(int(x.strip()) for x in s.split(",")) + except ValueError: + raise argparse.ArgumentTypeError( + "Invalid format. Expected comma-separated integers." + ) + + def parse_comma_separated_tuples(s: str) -> List[tuple[int, ...]]: + if s.strip().startswith("("): + # Split on ),( to separate tuples + tuples = s.strip("()").split("),(") + result = [] + tuple_len = None + + for t in tuples: + # Parse individual tuple + nums = [int(x.strip()) for x in t.split(",")] + + # Validate tuple length consistency + if tuple_len is None: + tuple_len = len(nums) + elif len(nums) != tuple_len: + raise argparse.ArgumentTypeError( + "All tuples must have the same length" + ) + + result.append(tuple(nums)) + return result + + raise argparse.ArgumentTypeError( + "Invalid format. Expected comma-separated integers or list of tuples" + ) + + parser = argparse.ArgumentParser( + description="Example of Grouped GEMM on Blackwell." + ) + parser.add_argument( + "--num_groups", + type=int, + default=3, + help="Number of groups", + ) + parser.add_argument( + "--problem_sizes_mnkl", + type=parse_comma_separated_tuples, + default=((128, 128, 128, 1), (512, 128, 128, 1), (128, 256, 128, 1)), + help="a tuple of problem sizes for each group (comma-separated tuples)", + ) + parser.add_argument( + "--host_problem_shape_available", + action="store_true", + help="Enable the compute of grid based upon host problem shape", + ) + parser.add_argument( + "--mma_tiler_mn", + type=parse_comma_separated_ints, + default=(128, 128), + help="Mma tile shape (comma-separated)", + ) + parser.add_argument( + "--cluster_shape_mn", + type=parse_comma_separated_ints, + default=(1, 1), + help="Cluster shape (comma-separated)", + ) + parser.add_argument( + "--tensormap_update_mode", + type=str, + default="SMEM", + help="Tensor map update mode", + ) + parser.add_argument("--ab_dtype", type=cutlass.dtype, default=cutlass.Float16) + parser.add_argument("--c_dtype", type=cutlass.dtype, default=cutlass.Float16) + parser.add_argument("--acc_dtype", type=cutlass.dtype, default=cutlass.Float32) + parser.add_argument( + "--use_2cta_instrs", + action="store_true", + help="Enable 2CTA MMA instructions feature", + ) + parser.add_argument("--a_major", choices=["k", "m"], type=str, default="k") + parser.add_argument("--b_major", choices=["k", "n"], type=str, default="k") + parser.add_argument("--c_major", choices=["n", "m"], type=str, default="n") + parser.add_argument( + "--tolerance", type=float, default=1e-01, help="Tolerance for validation" + ) + parser.add_argument( + "--warmup_iterations", type=int, default=0, help="Warmup iterations" + ) + parser.add_argument( + "--iterations", + type=int, + default=1, + help="Number of iterations to run the kernel", + ) + parser.add_argument( + "--skip_ref_check", action="store_true", help="Skip reference checking" + ) + parser.add_argument( + "--use_cold_l2", + action="store_true", + default=False, + help="Use circular buffer tensor sets to ensure L2 cold cache", + ) + + args = parser.parse_args() + + if ( + len(args.problem_sizes_mnkl) != 0 + and len(args.problem_sizes_mnkl) != args.num_groups + ): + parser.error("--problem_sizes_mnkl must contain exactly num_groups tuples") + + # l mode must be 1 for all groups + for _, _, _, l in args.problem_sizes_mnkl: + if l != 1: + parser.error("l must be 1 for all groups") + + if len(args.mma_tiler_mn) != 2: + parser.error("--mma_tiler_mn must contain exactly 2 values") + + if len(args.cluster_shape_mn) != 2: + parser.error("--cluster_shape_mn must contain exactly 2 values") + + if args.tensormap_update_mode not in ["GMEM", "SMEM"]: + parser.error("--tensormap_update_mode must be GMEM or SMEM") + + if args.tensormap_update_mode == "GMEM": + tensormap_update_mode = utils.TensorMapUpdateMode.GMEM + else: + tensormap_update_mode = utils.TensorMapUpdateMode.SMEM + + torch.manual_seed(2025) + + run( + args.num_groups, + args.problem_sizes_mnkl, + args.host_problem_shape_available, + args.ab_dtype, + args.c_dtype, + args.acc_dtype, + args.a_major, + args.b_major, + args.c_major, + args.mma_tiler_mn, + args.cluster_shape_mn, + args.use_2cta_instrs, + tensormap_update_mode, + args.tolerance, + args.warmup_iterations, + args.iterations, + args.skip_ref_check, + args.use_cold_l2, + ) + print("PASS") diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/reduction_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/reduction_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..854e3302442a1ad2c3964f91840818a4c1e1b311 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/reduction_utils.py @@ -0,0 +1,40 @@ +"""CuTeDSL geometry helpers shared by NVGEMM reduction kernels.""" + +__all__ = ["get_lane_warp_layouts", "partition_for_epilogue"] + + +def get_lane_warp_layouts(tiled_copy, reference_src=True): + """Derive two-dimensional lane and warp layouts for an epilogue copy.""" + import cutlass.cute as cute + + from torch._vendor.quack import layout_utils + + layout_tv = ( + tiled_copy.layout_src_tv_tiled + if reference_src + else tiled_copy.layout_dst_tv_tiled + ) + ref_layout = cute.right_inverse(layout_tv) + tile_m = cute.size(tiled_copy.tiler_mn[0]) + tile_n = cute.size(tiled_copy.tiler_mn[1]) + ref_layout_mn = cute.composition(ref_layout, cute.make_layout((tile_m, tile_n))) + + num_warps = cute.size(tiled_copy) // cute.arch.WARP_SIZE + tv_to_lane = cute.make_layout((cute.arch.WARP_SIZE, num_warps, 1), stride=(1, 0, 0)) + ref_to_lane = cute.composition(tv_to_lane, ref_layout_mn) + lane_m = cute.filter(cute.select(ref_to_lane, [0])) + lane_n = cute.filter(cute.select(ref_to_lane, [1])) + lane_layout_mn = layout_utils.concat_layout(lane_m, lane_n) + + tv_to_warp = cute.make_layout((cute.arch.WARP_SIZE, num_warps, 1), stride=(0, 1, 0)) + ref_to_warp = cute.composition(tv_to_warp, ref_layout_mn) + warp_m = cute.filter(cute.select(ref_to_warp, [0])) + warp_n = cute.filter(cute.select(ref_to_warp, [1])) + warp_layout_mn = layout_utils.concat_layout(warp_m, warp_n) + return lane_layout_mn, warp_layout_mn + + +def partition_for_epilogue(*args, **kwargs): + from torch._vendor.quack.sm90_utils import partition_for_epilogue as partition + + return partition(*args, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d56aeae8e586e2642c1cbcca62a9f5f9a3186f9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/__init__.py @@ -0,0 +1,2 @@ +# CuTeDSL Cutlass API registrations for PyTorch Inductor. +from . import dense_blockscaled_gemm_kernel diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abc1467186fbed22532de0a044373e05c44b58d3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/__pycache__/dense_blockscaled_gemm_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/__pycache__/dense_blockscaled_gemm_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dda9d69a1798f4eb7f2ef8c9df781a3b2493d0b3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/__pycache__/dense_blockscaled_gemm_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_blockscaled_gemm_kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_blockscaled_gemm_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..416252bad32695fc0d4d2e254dfcd78bf53609e9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_blockscaled_gemm_kernel.py @@ -0,0 +1,751 @@ +"""Kernel wrapper for dense_blockscaled_gemm_persistent vendored template.""" + +from __future__ import annotations + +import ast +import dataclasses +import functools +import itertools +import logging +from collections.abc import Callable, Generator # noqa: TC003 + +import cutlass.operators +from cutlass.operators import ScaleMode, ScaleSwizzleMode +from cutlass.operators.arch import TargetSm +from cutlass.operators.arguments import GemmArguments +from cutlass.operators.artifact import CompiledArtifact # noqa: TC002 +from cutlass.operators.metadata import ( + DenseTensorConstraints, + GemmOperandsMetadata, + OperatorMetadata, + ScaledOperandConstraints, + Sm100DesignMetadata, +) +from cutlass.operators.mma import BlackwellTcgen05Mma +from cutlass.operators.providers.cutedsl import integration_utils as cutedsl_utils +from cutlass.operators.providers.cutedsl.operator import CuteDslOperator +from cutlass.operators.status import Status +from cutlass.operators.utils.common import tuple_to_string +from cutlass.operators.utils.device import to_cuda_stream +from cutlass.operators.utils.tensor import strides_to_layout_string + + +log = logging.getLogger(__name__) + + +_ONES_ALPHA: dict = {} + + +@dataclasses.dataclass(frozen=True) +class _EpilogueABI: + """Runtime tensors and metadata derived from a traced epilogue signature.""" + + inputs: tuple + input_kinds: tuple[int, ...] + outputs: tuple + output_count: int + primary_output: int + + @classmethod + def from_args(cls, args, tensor_attr: str) -> _EpilogueABI: + outputs, output_count, primary_output = _epilogue_outputs(args, tensor_attr) + return cls( + _epilogue_tensors(args, tensor_attr), + _epilogue_tensor_kinds(args), + outputs, + output_count, + primary_output, + ) + + +@functools.lru_cache(maxsize=256) +def _epilogue_signature(epilogue_fn) -> tuple[tuple[str, ...], tuple[str, ...]]: + from cutlass.operators.fusion import trace_in_out + + inputs, outputs = trace_in_out(epilogue_fn) + return ( + tuple(name for name in inputs if name != "accum"), + tuple(outputs), + ) + + +def _epilogue_tensors(args, attr: str) -> tuple: + epilogue = getattr(args, "epilogue", None) + tensors = ( + () + if epilogue is None + else tuple( + getattr(_epilogue_abi_tensor(epilogue.tensors[name]), attr) + for name in _epilogue_signature(epilogue.epilogue_fn)[0] + ) + ) + if len(tensors) > 4: + raise NotImplementedError("NVGEMM scaled epilogues support up to four inputs") + return tensors + (None,) * (4 - len(tensors)) + + +def _epilogue_abi_tensor(tensor): + runtime_tensor = tensor.runtime_tensor + leading = runtime_tensor.shape[0] + if leading % 8 == 0: + return tensor + from cutlass.operators.utils.tensor import TensorWrapper + + padded_shape = (leading + 7) // 8 * 8, *runtime_tensor.shape[1:] + import torch + + padded = torch.empty( + padded_shape, + dtype=runtime_tensor.dtype, + device=runtime_tensor.device, + ) + padded[:leading].copy_(runtime_tensor) + return TensorWrapper(padded) + + +def _epilogue_tensor_kinds(args) -> tuple[int, ...]: + epilogue = getattr(args, "epilogue", None) + if epilogue is None: + return (0, 0, 0, 0) + kinds = [] + output_m, output_n = args.out.shape[-2:] + for name in _epilogue_signature(epilogue.epilogue_fn)[0]: + shape = epilogue.tensors[name].shape + if shape[-1] == 1 and (len(shape) == 1 or shape[-2] == 1): + if output_n == 1: + kinds.append(2) + elif output_m == 1: + kinds.append(3) + else: + raise NotImplementedError( + "NVGEMM scaled epilogues do not support scalar tensor inputs" + ) + elif len(shape) == 1 or shape[-2] == 1: + kinds.append(2) + elif shape[-1] == 1: + kinds.append(3) + else: + kinds.append(1) + return tuple(kinds) + (0,) * (4 - len(kinds)) + + +def _epilogue_outputs(args, attr: str) -> tuple[tuple, int, int]: + epilogue = getattr(args, "epilogue", None) + if epilogue is None: + return (None, None, None), 1, 0 + output_names = _epilogue_signature(epilogue.epilogue_fn)[1] + if not output_names or len(output_names) > 4: + raise NotImplementedError("NVGEMM scaled epilogues support 1-4 outputs") + if len(output_names) > 1 and "D" not in output_names: + raise NotImplementedError("NVGEMM scaled multi-store requires a D output") + primary_index = output_names.index("D") if "D" in output_names else 0 + tensors = tuple( + getattr(epilogue.tensors[name], attr) + for index, name in enumerate(output_names) + if index != primary_index + ) + return tensors + (None,) * (3 - len(tensors)), len(output_names), primary_index + + +def _ones_alpha(): + """Cached per-device (4,)-ones alpha TensorWrapper (identity global scale). + + The kernel always takes an alpha arg so its signature is consistent across + compile/run paths; when not fusing we pass ones (a no-op *1.0). Len is a + multiple of 4 (CuTeDSL requires the operand's last dim divisible by 4). + """ + from cutlass.operators.utils.tensor import TensorWrapper + + import torch + + dev = torch.cuda.current_device() + tw = _ONES_ALPHA.get(dev) + if tw is None: + tw = TensorWrapper(torch.ones(4, dtype=torch.float32, device=f"cuda:{dev}")) + _ONES_ALPHA[dev] = tw + return tw + + +def _epilogue_op_scope(cute): + def relu(x): + return cute.math.max(x, cute.full_like(x, 0.0)) + + def sigmoid(x): + return 1.0 / (1.0 + cute.math.exp(-x)) + + def gelu(x): + return 0.5 * x * (1.0 + cute.math.erf(x * 0.7071067811865476)) + + return { + "erf": cute.math.erf, + "exp": cute.math.exp, + "gelu": gelu, + "relu": relu, + "sigmoid": sigmoid, + "silu": lambda x: x * sigmoid(x), + "tanh": cute.math.tanh, + } + + +try: + from ..dense_blockscaled_gemm_persistent import ( # pyrefly: ignore[missing-import] + Sm100BlockScaledPersistentDenseGemmKernel as BlockScaledGemmKernelImpl, + ) +except ImportError: + BlockScaledGemmKernelImpl = None # type: ignore[misc, assignment] + + +class VendoredDenseBlockScaledGemmKernel(CuteDslOperator): + """Wrapper for vendored dense blockscaled GEMM template for SM100 GPUs.""" + + supported_args_type = GemmArguments + designed_for_min_cc = 100 + + def __init__(self, metadata: OperatorMetadata): + super().__init__(metadata) + + self.sf_vec_size = metadata.operands.A.mode[-1] + mma_tiler_mn = (metadata.design.tile_shape[0], metadata.design.tile_shape[1]) + cluster_shape_mn = ( + metadata.design.cluster_shape[0], + metadata.design.cluster_shape[1], + ) + + import os + + self.impl = BlockScaledGemmKernelImpl( # pyrefly: ignore[not-callable] + self.sf_vec_size, + mma_tiler_mn, + cluster_shape_mn, + use_prefetch=os.environ.get("TORCHINDUCTOR_NVGEMM_PREFETCH", "0") == "1", + ) + self.cluster_shape_mn = cluster_shape_mn + self.mma_tiler_mn = mma_tiler_mn + + @staticmethod + def _major_modes(args): + """Extract major modes from arguments or operand metadata.""" + import cutlass.utils as utils + from cutlass.cute.nvgpu.tcgen05 import OperandMajorMode + + if args.A.stride[-2:].index(1) == 1: + a_major_mode = (OperandMajorMode.K, "k") + else: + a_major_mode = (OperandMajorMode.MN, "m") + + if args.B.stride[-2:].index(1) == 0: + b_major_mode = (OperandMajorMode.K, "k") + else: + b_major_mode = (OperandMajorMode.MN, "n") + + if args.out.stride[-2:].index(1) == 1: + out_layout = (utils.LayoutEnum.ROW_MAJOR, "n") + else: + out_layout = (utils.LayoutEnum.COL_MAJOR, "m") + + return a_major_mode, b_major_mode, out_layout + + def _compile( + self, args: GemmArguments, target_sm: TargetSm | None = None + ) -> CompiledArtifact: + import cutlass.cute as cute + + stream = cute.runtime.make_fake_stream() + max_active_clusters = cutedsl_utils.mma.get_max_active_clusters( + self.cluster_shape_mn + ) + + # Fused global scale: alpha is ALWAYS threaded as a trailing kernel arg + # (ones when not fusing) so the kernel signature is consistent across all + # compile/run paths -- a None alpha is not reliably dropped from the + # runtime signature. args.alpha (a TensorWrapper, len multiple-of-4) is + # applied elementwise in the epilogue; closure capture cannot read a + # runtime tensor there. + alpha = getattr(args, "alpha", None) + if alpha is None: + alpha = _ones_alpha() + + def epilogue_op(v): + return v + + if getattr(args, "epilogue", None) is not None: + epilogue_op = args.epilogue.epilogue_fn + if isinstance(epilogue_op, str): + fn_name = next( + node.name + for node in ast.parse(epilogue_op).body + if isinstance(node, ast.FunctionDef) + ) + scope = _epilogue_op_scope(cute) + exec(epilogue_op, scope) + epilogue_op = scope[fn_name] + epilogue = _EpilogueABI.from_args(args, "compile_time_tensor") + local_reduce_out = getattr(args, "local_reduce_out", None) + local_reduce_feeds_main = getattr(args, "local_reduce_feeds_main", False) + if local_reduce_out is not None or local_reduce_feeds_main: + return self.cute_compile( + self.impl, + args.A.tensor, + args.B.tensor, + args.A.scale.tensor, + args.B.scale.tensor, + args.out.tensor, + max_active_clusters, + stream, + epilogue_op, + self.metadata.operands.out.dtype, + alpha, + *epilogue.inputs, + *epilogue.input_kinds, + *epilogue.outputs, + epilogue.output_count, + epilogue.primary_output, + ( + local_reduce_out.compile_time_tensor + if local_reduce_out is not None + else None + ), + args.local_reduce_group, + args.local_reduce_axis, + args.local_reduce_type, + args.local_reduce_source, + local_reduce_feeds_main, + target_sm=target_sm, + ) + return self.cute_compile( + self.impl, + args.A.tensor, + args.B.tensor, + args.A.scale.tensor, + args.B.scale.tensor, + args.out.tensor, + max_active_clusters, + stream, + epilogue_op, + self.metadata.operands.out.dtype, + alpha, + *epilogue.inputs, + *epilogue.input_kinds, + *epilogue.outputs, + epilogue.output_count, + epilogue.primary_output, + target_sm=target_sm, + ) + + def _run( + self, + args: GemmArguments, + compiled_artifact: CompiledArtifact, + stream, + workspace=None, + ) -> None: + import torch + + stream = to_cuda_stream(stream) + compiled_gemm = compiled_artifact.compiled_obj + + # TVM FFI needs a torch.cuda.Stream, not a raw int handle + if isinstance(stream, int): + stream = torch.cuda.ExternalStream(stream) + + # Runtime arg list must match _compile: alpha always trails stream. + alpha = getattr(args, "alpha", None) + if alpha is None: + alpha = _ones_alpha() + with torch.cuda.stream(stream): + epilogue = _EpilogueABI.from_args(args, "runtime_tensor") + + local_reduce_out = getattr(args, "local_reduce_out", None) + local_reduce_feeds_main = getattr(args, "local_reduce_feeds_main", False) + if local_reduce_out is not None or local_reduce_feeds_main: + self.cute_run( # pyrefly: ignore[missing-attribute] + compiled_gemm, + args.A.tensor, + args.B.tensor, + args.A.scale.tensor, + args.B.scale.tensor, + args.out.tensor, + stream, + alpha, + *epilogue.inputs, + *epilogue.outputs, + local_reduce_out.runtime_tensor + if local_reduce_out is not None + else None, + ) + return + + self.cute_run( # pyrefly: ignore[missing-attribute] + compiled_gemm, + args.A.tensor, + args.B.tensor, + args.A.scale.tensor, + args.B.scale.tensor, + args.out.tensor, + stream, + alpha, + *epilogue.inputs, + *epilogue.outputs, + None, + ) + + def _supports( + self, args: GemmArguments, target_sm: TargetSm | None = None + ) -> Status: + # Match the upstream block-scaled operator: validate scale-factor element + # counts via ScaledOperand.numel_scale for the operand's mode/swizzle, + # rather than re-inferring the layout (the old _infer_scale_swizzle_impl + # check wrongly rejected valid NVFP4 args on the transposed B operand). + from cutlass.operators.arguments import ScaledOperand + + local_reduce_out = getattr(args, "local_reduce_out", None) + if local_reduce_out is not None or getattr( + args, "local_reduce_feeds_main", False + ): + group = args.local_reduce_group + axis = args.local_reduce_axis + m, n = args.out.shape[-2:] + selected_size = n if axis == 1 else m + max_group = self.mma_tiler_mn[axis] if axis == 1 else 16 + if ( + axis not in (0, 1) + or group <= 1 + or group > max_group + or selected_size % group != 0 + ): + return Status.fail( + "Grouped reduction requires a supported M- or N-axis group " + "that divides the selected dimension." + ) + if local_reduce_out is not None: + expected_shape = (m, n // group) if axis == 1 else (m // group, n) + if local_reduce_out.shape != expected_shape: + return Status.fail( + "Grouped reduction output shape must be " + f"{expected_shape}; got {local_reduce_out.shape}." + ) + if local_reduce_out.dtype is not cutlass.Float32 or tuple( + local_reduce_out.stride + ) != (expected_shape[1], 1): + return Status.fail( + "Grouped reduction output must be contiguous Float32." + ) + + m, n = args.out.shape[-2:] + k = args.A.shape[-1] + L = args.A.shape[0] if len(args.A.shape) == 3 else 1 + + expected_sfa = ScaledOperand.numel_scale((L, m, k), args.A.mode, args.A.swizzle) + expected_sfb = ScaledOperand.numel_scale((L, n, k), args.B.mode, args.B.swizzle) + if args.A.scale.numel() != expected_sfa: + return Status.fail( + f"Scale factor A must have {expected_sfa} elements for mat shape " + f"{args.A.shape}; got {args.A.scale.numel()}." + ) + if args.B.scale.numel() != expected_sfb: + return Status.fail( + f"Scale factor B must have {expected_sfb} elements for mat shape " + f"{args.B.shape}; got {args.B.scale.numel()}." + ) + return Status.success() + + @staticmethod + def _is_valid_dtype_combo(ab_dtype, sf_dtype, sf_vec_size, out_dtype) -> bool: + """Validate dtype/scale-factor/vec-size combinations. + + Matches constraints from the upstream kernel: + MXF8: Float8E5M2/Float8E4M3FN + Float8E8M0FNU, sf_vec_size=32 + MXF4: Float4E2M1FN + Float8E8M0FNU, sf_vec_size=32 + NVF4: Float4E2M1FN + Float8E8M0FNU/Float8E4M3FN, sf_vec_size=16 + """ + import cutlass + + if ab_dtype not in { + cutlass.Float4E2M1FN, + cutlass.Float8E5M2, + cutlass.Float8E4M3FN, + }: + return False + if sf_vec_size not in {16, 32}: + return False + if sf_dtype not in {cutlass.Float8E8M0FNU, cutlass.Float8E4M3FN}: + return False + # Float8E4M3FN as SF only valid with sf_vec_size=16 (NVF4) + if sf_dtype == cutlass.Float8E4M3FN and sf_vec_size == 32: + return False + # Float8 AB types require sf_vec_size=32 (MXF8) + if ab_dtype in {cutlass.Float8E5M2, cutlass.Float8E4M3FN} and sf_vec_size == 16: + return False + if out_dtype not in { + cutlass.Float32, + cutlass.Float16, + cutlass.BFloat16, + cutlass.Float8E5M2, + cutlass.Float8E4M3FN, + }: + return False + return True + + @staticmethod + def _is_valid_layouts(ab_dtype, a_major, b_major) -> bool: + """Float4E2M1FN (MXF4/NVF4) requires row-major (K-major) A and B.""" + import cutlass + + if ab_dtype is cutlass.Float4E2M1FN and not (a_major == "k" and b_major == "k"): + return False + return True + + @staticmethod + def _valid_operands(operands: GemmOperandsMetadata, sf_vec_size: int) -> bool: + import cutlass + + if operands.A.dtype != operands.B.dtype: + return False + if operands.A.scale.dtype != operands.B.scale.dtype: + return False + if operands.accumulator_type != cutlass.Float32: + return False + + ab_dtype = operands.A.dtype + sf_dtype = operands.A.scale.dtype + out_dtype = operands.out.dtype + + if not VendoredDenseBlockScaledGemmKernel._is_valid_dtype_combo( + ab_dtype, sf_dtype, sf_vec_size, out_dtype + ): + return False + + (_, a_major), (_, b_major), _ = VendoredDenseBlockScaledGemmKernel._major_modes( + operands + ) + if not VendoredDenseBlockScaledGemmKernel._is_valid_layouts( + ab_dtype, a_major, b_major + ): + return False + + return True + + @staticmethod + def _metadata_operand_combinations() -> Generator[GemmOperandsMetadata, None, None]: + import cutlass + + ab_dtypes = [cutlass.Float8E5M2, cutlass.Float8E4M3FN, cutlass.Float4E2M1FN] + out_dtypes = [ + cutlass.Float32, + cutlass.Float16, + cutlass.BFloat16, + cutlass.Float8E4M3FN, + cutlass.Float8E5M2, + ] + sf_dtypes = [cutlass.Float8E8M0FNU, cutlass.Float8E4M3FN] + scale_modes = [ScaleMode.Blockwise1x16, ScaleMode.Blockwise1x32] + + row_major = (0, 0, 1) + col_major = (0, 1, 0) + alignment_bytes = 16 + + def major_str_a(stride): + return "k" if stride == row_major else "m" + + def major_str_b(stride): + return "n" if stride == row_major else "k" + + for ab_dtype, sf_dtype, scale_mode, out_dtype in itertools.product( + ab_dtypes, sf_dtypes, scale_modes, out_dtypes + ): + sf_vec_size = scale_mode[-1] + if not VendoredDenseBlockScaledGemmKernel._is_valid_dtype_combo( + ab_dtype, sf_dtype, sf_vec_size, out_dtype + ): + continue + + for stride_A, stride_B, stride_out in itertools.product( + [row_major, col_major], repeat=3 + ): + a_major = major_str_a(stride_A) + b_major = major_str_b(stride_B) + + if not VendoredDenseBlockScaledGemmKernel._is_valid_layouts( + ab_dtype, a_major, b_major + ): + continue + + ab_div = alignment_bytes * 8 // ab_dtype.width + out_div = alignment_bytes * 8 // out_dtype.width + sf_div = alignment_bytes * 8 // sf_dtype.width + + yield GemmOperandsMetadata( + A=ScaledOperandConstraints( + quantized=DenseTensorConstraints( + dtype=ab_dtype, + stride=stride_A, + divisibility=ab_div, + ), + scale=DenseTensorConstraints( + dtype=sf_dtype, + stride=None, + divisibility=sf_div, + ), + mode=scale_mode, + swizzle=ScaleSwizzleMode.Swizzle32x4x4, + ), + B=ScaledOperandConstraints( + quantized=DenseTensorConstraints( + dtype=ab_dtype, + stride=stride_B, + divisibility=ab_div, + ), + scale=DenseTensorConstraints( + dtype=sf_dtype, + stride=None, + divisibility=sf_div, + ), + mode=scale_mode, + swizzle=ScaleSwizzleMode.Swizzle32x4x4, + ), + out=DenseTensorConstraints( + dtype=out_dtype, + stride=stride_out, + divisibility=out_div, + ), + accumulator_type=cutlass.Float32, + ) + + @classmethod + def _valid_metadata(cls, metadata: OperatorMetadata) -> bool: + scale_vec = metadata.operands.A.mode + + if len(scale_vec) > 1: + for i in range(len(scale_vec) - 1): + if scale_vec[i] != 1: + return False + + sf_vec_size = scale_vec[-1] + if not VendoredDenseBlockScaledGemmKernel._valid_operands( + metadata.operands, sf_vec_size + ): + return False + + design = metadata.design + if not isinstance(design, Sm100DesignMetadata): + return False + + cm, cn, _ = design.cluster_shape + if cm <= 0 or cn <= 0: + return False + if cm * cn > 16: + return False + if cm & (cm - 1) != 0 or cn & (cn - 1) != 0: + return False + # SF multicast constraint: cluster dims <=4 + if cm > 4 or cn > 4: + return False + + tile_m, tile_n, _ = design.tile_shape + if tile_m not in [128, 256]: + return False + if tile_n not in [64, 128, 192, 256]: + return False + use_2cta = tile_m == 256 + if use_2cta and cm % 2 != 0: + return False + + if metadata.epilogue is not None and "EFC" not in cls.__name__: + return False + + return True + + @classmethod + def _generate_operators( + cls, + metadata_filter: Callable[[OperatorMetadata], bool], + epilogue_args=None, + target_sm: TargetSm | None = None, + args=None, + ) -> list[VendoredDenseBlockScaledGemmKernel]: + if target_sm is not None and target_sm.cc not in [100, 101, 103]: + return [] + if epilogue_args is not None: + return [] + + design_params = { + "mma_instruction_type": [BlackwellTcgen05Mma], + "use_2cta_mma": [True], + "tile_shape": [ + (M, N, 256) for M in [128, 256] for N in [64, 128, 192, 256] + ], + "cluster_shape": [(M, N, 1) for M in [1, 2, 4] for N in [1, 2, 4]], + "use_tma_store": [True], + } + + param_names = list(design_params.keys()) + param_values = [design_params[name] for name in param_names] + + operator_list = [] + + for operands in cls._metadata_operand_combinations(): + # pyrefly: ignore[no-matching-overload] + for values in itertools.product(*param_values): + design = Sm100DesignMetadata(**dict(zip(param_names, values))) + + operator_name = ( + f"inductor_vendored.{cls.__name__}_sm100_" + "{layout}_A{A}_B{B}_out{out}_SFA{SFA}_SFB{SFB}_" + "acc{acc}_scale{scale_mode}_swizzle{scale_swizzle}_" + "{num_cta}cta_cluster{cluster}_tile{tile}" + "{_tma_store}" + ).format( + layout=strides_to_layout_string( + operands.A.stride, + operands.B.stride, + operands.out.stride, + ), + A=operands.A.dtype, + B=operands.B.dtype, + out=operands.out.dtype, + SFA=operands.A.scale.dtype, + SFB=operands.B.scale.dtype, + acc=operands.accumulator_type, + scale_mode=operands.A.mode, + scale_swizzle=operands.A.swizzle, + num_cta="2" if design.use_2cta_mma else "1", + cluster=tuple_to_string(design.cluster_shape), + tile=tuple_to_string(design.tile_shape), + _tma_store="_tma_store" if design.use_tma_store else "", + ) + + metadata = OperatorMetadata( + operands=operands, + design=design, + operator_name=operator_name, + operator_class=cls, + supported_targets=TargetSm.get_supported_targets(design, operands), + epilogue=None, + ) + + if cls._valid_metadata(metadata): + if metadata_filter is None or metadata_filter(metadata): + operator_list.append(cls(metadata)) + + log.debug( + "Generated %d DenseBlockScaledGemmKernel configurations", + len(operator_list), + ) + return operator_list + + +class VendoredDenseBlockScaledGemmEFC(VendoredDenseBlockScaledGemmKernel): + """Block-scaled provider variant using the kernel's unary epilogue hook.""" + + supported_args_type = GemmArguments + designed_for_min_cc = 100 + + +# Only register if kernel implementation is available +if BlockScaledGemmKernelImpl is not None: + cutlass.operators.providers.cutedsl.CuTeDSLProvider.register( + VendoredDenseBlockScaledGemmKernel + ) + cutlass.operators.providers.cutedsl.CuTeDSLProvider.register( + VendoredDenseBlockScaledGemmEFC + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel_inputs.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..f9dbc922bf6d1bd62f90248d2cf8c510ee8bd0ee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel_inputs.py @@ -0,0 +1,354 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import Any, TYPE_CHECKING + +import torch +import torch._inductor.config +from torch._inductor import ir +from torch._inductor.virtualized import V + +from .ir import FixedLayout, FlexibleLayout, Layout + + +if TYPE_CHECKING: + from collections.abc import Sequence + + import sympy + + +class KernelInputs(ABC): + """ + Class to store and provide access to input nodes for kernels. + This class takes in a tuple of input nodes and provides methods to access + information about these nodes, such as their device type and device. + """ + + def __init__( + self, + input_nodes: list[Any], + scalars: dict[str, float | int] | None = None, + out_dtype: torch.dtype | None = None, + ): + """ + Initialize with a tuple of input nodes. + + Args: + input_nodes: A tuple of input nodes to store + out_dtype: Optional output dtype to store + """ + self._input_nodes = input_nodes + self._device_name: str | None = None + self._scalars = scalars if scalars is not None else {} + self._out_dtype = out_dtype + if len(input_nodes) <= 0: + raise AssertionError("Expected at least one input node") + + def nodes(self, reorder: Sequence[int] | None = None) -> list[Any]: + """ + Return the stored input nodes, optionally reordered. + + Args: + reorder: Optional sequence of indices to reorder the nodes. + For example, (2, 0, 1) would return nodes in that order. + + Returns: + The tuple of input nodes, optionally reordered + """ + if reorder is None: + return self._input_nodes + if len(self._input_nodes) != len(reorder): + raise AssertionError( + f"Reorder length mismatch: {len(self._input_nodes)} vs {len(reorder)}" + ) + return [self._input_nodes[i] for i in reorder] + + @property + def count(self) -> int: + """ + Get the number of input nodes. + + Returns: + The number of input nodes + """ + return len(self._input_nodes) + + @property + def device_type(self) -> str | None: + """ + Get the device type of the first node. + + Returns: + The device type (e.g., 'cuda', 'cpu') + """ + + return ir.get_device_type(self._input_nodes[0]) + + def device(self) -> torch.device: + """ + Get the device of the first node. + + Returns: + The device of the first node + """ + return self._input_nodes[0].get_device() + + def device_name(self) -> str | None: + """ + Get the device name information. + + Returns: + A tuple of (gpu_name, vendor, model) + """ + if self._device_name is None: + device = self.device() + if self.device_type == "cuda": + device_properties = torch.cuda.get_device_properties(device) + self._device_name = device_properties.gcnArchName + return self._device_name + + def shapes_symbolic(self) -> tuple[tuple[Any, ...], ...]: + """ + Get the symbolic shapes of all input nodes. + + Returns: + A tuple of shape tuples for each input node + """ + return tuple(node.get_size() for node in self._input_nodes) + + def shapes_hinted(self) -> tuple[tuple[int, ...], ...]: + """ + Get the size hints for shapes of all input nodes. + + Returns: + A tuple of shape tuples with integer hints for each input node + """ + return tuple( + V.graph.sizevars.optimization_hints(node.get_size()) + for node in self._input_nodes + ) + + def strides_symbolic(self) -> tuple[tuple[sympy.Integer, ...], ...]: + """ + Get the symbolic strides of all input nodes. + + Returns: + A tuple of stride tuples for each input node + """ + return tuple(node.get_stride() for node in self._input_nodes) + + def strides_hinted(self) -> tuple[tuple[int, ...], ...]: + """ + Get the size hints for strides of all input nodes. + + Returns: + A tuple of stride tuples with integer hints for each input node + """ + return tuple( + V.graph.sizevars.optimization_hints(node.get_stride()) + for node in self._input_nodes + ) + + def dtypes(self) -> tuple[torch.dtype, ...]: + """ + Get the dtypes of all input nodes. + + Returns: + A tuple of dtypes for each input node + """ + return tuple(node.get_dtype() for node in self._input_nodes) + + def dtype(self, idx: int = 0) -> torch.dtype: + """ + Get the dtype of a specific input node. + + Args: + idx: Index of the node to get the dtype from (default: 0) + + Returns: + The dtype of the specified input node + """ + return self._input_nodes[idx].get_dtype() + + @abstractmethod + def out_dtype(self) -> torch.dtype: + """ + Get the output dtype, whether passed in or inferred from the nodes + + Returns: + The output dtype + """ + + def get_scalar(self, name: str) -> float | int: + """ + Get the scalar value for a given name. + + Args: + name: Name of the scalar to get + + Returns: + The scalar value + """ + if name not in self._scalars: + raise AssertionError(f"Scalar {name} not found, but required") + return self._scalars[name] + + @abstractmethod + def output_layout(self, flexible: bool = True) -> Layout: + """ + Abstract method to handle output layout generation. + + Args: + out_dtype: Optional output dtype. If not provided, infer from inputs + flexible: If True, return FlexibleLayout, otherwise FixedLayout + """ + + +class MMKernelInputs(KernelInputs): + """ + Specialized KernelInputs for matrix multiplication operations. + Provides additional methods to access M, N, K dimensions. + """ + + def __init__( + self, + input_nodes: list[Any], + scalars: dict[str, float | int] | None = None, + out_dtype: torch.dtype | None = None, + mat1_idx: int = -2, + mat2_idx: int = -1, + ): + """ + Initialize with a tuple of input nodes. + + By default, we assume the last 2 input nodes are mat1 and mat2, but + the caller can adjust when necessary + """ + super().__init__(input_nodes, scalars, out_dtype) + # for mm, we need at least 2 nodes, and we need to know which nodes + # are the main matrices e.g. addmm is (bias, mat1, mat2) whereas others + # might be (mat1, mat2, scale), etc. + if len(self._input_nodes) < 2: + raise AssertionError("Expected at least 2 input nodes") + + # Adjust assertions to handle negative indices + m1_idx, m2_idx = mat1_idx, mat2_idx + if mat1_idx < 0: + m1_idx += len(input_nodes) + if mat2_idx < 0: + m2_idx += len(input_nodes) + + if not (0 <= m1_idx < len(input_nodes)): + raise AssertionError(f"Invalid mat1_idx: {mat1_idx}") + if not (0 <= m2_idx < len(input_nodes)): + raise AssertionError(f"Invalid mat2_idx: {mat2_idx}") + + self._mat1_idx = mat1_idx + self._mat2_idx = mat2_idx + + def mnk_symbolic( + self, + ) -> tuple[sympy.Integer, sympy.Integer, sympy.Integer]: + """ + Get the symbolic M, N, K dimensions for matrix multiplication. + Handles both 2D (MM) and 3D (BMM) tensors. + + M is extracted from the second-to-last dimension of the first operand (mat1). + N is extracted from the last dimension of the second operand (mat2). + K is extracted from the last dimension of the first operand (mat1). + + Returns: + A tuple of (M, N, K) dimensions + """ + mat1 = self.nodes()[self._mat1_idx] + mat2 = self.nodes()[self._mat2_idx] + + m = mat1.get_size()[-2] # M from second-to-last dimension of mat1 + k = mat1.get_size()[-1] # K from last dimension of mat1 + n = mat2.get_size()[-1] # N from last dimension of mat2 + + # Ensure K dimensions match between operands + k0 = mat2.get_size()[-2] # K from second-to-last dimension of mat2 + V.graph.sizevars.check_equals(k, k0) + return (m, n, k) + + def out_dtype(self) -> torch.dtype: + """ + Get the output dtype, whether passed in or inferred from the nodes + + Returns: + The output dtype + """ + if self._out_dtype is not None: + return self._out_dtype + return self.mat1mat2()[0].get_dtype() + + def output_layout(self, flexible: bool = True) -> Layout: + """ + Handle output layout generation for matrix multiplication. + + Args: + out_dtype: Optional output dtype. If not provided, infer from inputs + flexible: If True, return FlexibleLayout, otherwise FixedLayout + """ + mat1, mat2 = self.mat1mat2() + out_dtype = self.out_dtype() + # NOTE: taken from mm_common.mm_args + *b1, m, k1 = mat1.get_size() + *b2, k2, n = mat2.get_size() + b = [V.graph.sizevars.check_equals_and_simplify(a, b) for a, b in zip(b1, b2)] + size = [*b, m, n] + if flexible: + return FlexibleLayout(self.device(), out_dtype, size) + else: + return FixedLayout(self.device(), out_dtype, size) + + def mat1mat2(self) -> tuple[Any, Any]: + """ + Get the mat1 and mat2 nodes. + + Returns: + A tuple of (mat1, mat2) nodes + """ + nodes = self.nodes() + return nodes[self._mat1_idx], nodes[self._mat2_idx] + + def mnk_hinted(self) -> tuple[int, int, int]: + """ + Get the hinted M, N, K dimensions for matrix multiplication. + Handles both 2D (MM) and 3D (BMM) tensors. + + Uses shapes_hinted from the base class to get integer hints for dimensions. + + Returns: + A tuple of (M, N, K) dimensions as integers + """ + hinted_shapes = self.shapes_hinted() + mat1_shape = hinted_shapes[self._mat1_idx] + mat2_shape = hinted_shapes[self._mat2_idx] + + m = mat1_shape[-2] # M from second-to-last dimension of mat1 + k = mat1_shape[-1] # K from last dimension of mat1 + n = mat2_shape[-1] # N from last dimension of mat2 + + # Ensure K dimensions match between operands + k_check = mat2_shape[-2] # K from second-to-last dimension of mat2 + if k != k_check: + raise AssertionError(f"K dimensions don't match: {k} vs {k_check}") + + return (m, n, k) + + def batch_hinted(self) -> int: + """ + Get the hinted batch size for batched matrix multiplication. + Returns 1 for non-batched (2D) operations. + + Returns: + The batch size as an integer + """ + hinted_shapes = self.shapes_hinted() + mat1_shape = hinted_shapes[self._mat1_idx] + + if len(mat1_shape) >= 3: + return mat1_shape[-3] # Batch from third-to-last dimension + return 1 # Non-batched operation diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/kernel_template_choice.py b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel_template_choice.py new file mode 100644 index 0000000000000000000000000000000000000000..22f8125814e4d8ec96797bf4940d53a75f61756d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/kernel_template_choice.py @@ -0,0 +1,99 @@ +from __future__ import annotations + +from typing import Any, TYPE_CHECKING + +from .heuristics.template.params import DictKernelTemplateParams + + +if TYPE_CHECKING: + from collections.abc import Generator + + from .codegen.common import KernelTemplate + from .heuristics.template.params import KernelTemplateParams + from .ir import ChoiceCaller, Layout + from .kernel_inputs import KernelInputs + from .select_algorithm import ExternKernelChoice + + +class KernelTemplateChoice: + """ + A class that encapsulates all the components needed to create a ChoiceCaller from a template. + + This class implements lazy evaluation for the choice property - the actual ChoiceCaller + is only created when first accessed via the choice property. + """ + + def __init__( + self, + template: KernelTemplate | ExternKernelChoice, + params: KernelTemplateParams, + extra_kwargs: dict[str, Any], + layout: Layout, + inputs: KernelInputs, + ): + self.template = template + self.params = params + self.extra_kwargs = extra_kwargs + self.layout = layout + self.inputs = inputs + self.annotations: dict[str, Any] = {"ktc": self} + + @property + def choice(self) -> ChoiceCaller | None: + """ + Lazily evaluate and return the ChoiceCaller for this template choice. + + On first access, calls template.choice_or_none() with the stored parameters. + If successful, caches and returns the ChoiceCaller. If it fails, caches + and returns None. Subsequent accesses return the cached value. + + Returns: + ChoiceCaller if the template choice succeeds, None otherwise + """ + if not hasattr(self, "_choice"): + # First time accessing choice - try to generate it + kwargs = self.params.to_kwargs() + self._choice = self.template.choice_or_none( + **kwargs, + **self.extra_kwargs, + layout=self.layout, + input_nodes=self.inputs.nodes(), + ) + if self._choice is not None: + self._choice.annotations = self.annotations + return self._choice + + +def make_ktc_generator( + template: KernelTemplate | ExternKernelChoice, + cs: Generator[KernelTemplateParams, None, None], + extra_kwargs: dict[str, Any], + overrides: dict[str, Any], + layout: Layout, + inputs: KernelInputs, +) -> Generator[KernelTemplateChoice, None, None]: + """ + Create a generator of KernelTemplateChoice objects for a given template. + + Args: + template: The template object (KernelTemplate or ExternKernelChoice) + cs: Generator of KernelTemplateParams from template heuristic + overrides: Override kwargs for the template + layout: Layout value for the template + inputs: KernelInputs for the op + + Yields: + KernelTemplateChoice objects + """ + for params in cs: + # Apply overrides to params + base_kwargs = params.to_kwargs() + final_kwargs = {**base_kwargs, **overrides} + final_params = DictKernelTemplateParams(final_kwargs) + yield KernelTemplateChoice( + template=template, + params=final_params, + extra_kwargs=extra_kwargs, + layout=layout, + inputs=inputs, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/lookup_table/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/lookup_table/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ebb1d5618bfa5eb44cfa9c4bc3921e887f54374 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/lookup_table/__init__.py @@ -0,0 +1,32 @@ +""" +Template lookup table system for PyTorch Inductor. + +This package provides functionality for: +- Loading pre-configured template choices from lookup tables +- Managing template configurations and choices + +All functionality is contained within the LookupTableChoices class. +You can customize any aspect by subclassing LookupTableChoices and overriding methods. + +Usage: + # Basic usage + choices = LookupTableChoices() + V.set_choices_handler(choices) + + # Custom usage + class MyCustomChoices(LookupTableChoices): + def _get_lookup_table(self): + return my_custom_table + + def make_lookup_key(self, kernel_inputs, op_name, include_device=False): + return f"custom_{op_name}_{hash(str(kernel_inputs))}" + + V.set_choices_handler(MyCustomChoices()) +""" + +from .choices import LookupTableChoices + + +__all__ = [ + "LookupTableChoices", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/lookup_table/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/lookup_table/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d026fe560fce5776d3ce8cb790761eeb68650a3b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/lookup_table/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/lookup_table/__pycache__/choices.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/lookup_table/__pycache__/choices.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f69e056fa9c323188d10a1fb44954fc18efd6a61 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/lookup_table/__pycache__/choices.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/lookup_table/choices.py b/.venv/lib/python3.12/site-packages/torch/_inductor/lookup_table/choices.py new file mode 100644 index 0000000000000000000000000000000000000000..5cf72ea24d9a4d7b5635709c73078cdcbb600d36 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/lookup_table/choices.py @@ -0,0 +1,421 @@ +from __future__ import annotations + +import copy +import logging +from functools import lru_cache +from typing import Any, TYPE_CHECKING + +import torch +from torch._inductor import config +from torch._inductor.choices import InductorChoices +from torch._inductor.heuristics.template.params import DictKernelTemplateParams +from torch._inductor.kernel_template_choice import KernelTemplateChoice + + +log = logging.getLogger(__name__) + + +if TYPE_CHECKING: + from collections.abc import Generator + + from torch._inductor.codegen.common import KernelTemplate + from torch._inductor.kernel_inputs import KernelInputs + from torch._inductor.select_algorithm import ExternKernelChoice + + +class LookupTableChoices(InductorChoices): + """ + InductorChoices subclass that uses lookup table when available, otherwise falls back to parent. + All lookup functionality is contained within this class and can be customized by overriding methods. + """ + + def _get_lookup_table(self) -> dict[str, list[dict[str, Any]]]: + """ + Get the template lookup table from config. + Override this method to use custom lookup table sources (database, API, etc.). + """ + if not torch.cuda.is_available() or config.lookup_table.table is None: + return {} + return config.lookup_table.table + + @staticmethod + @lru_cache + def _get_device_key(device: torch.device) -> str | None: + """ + Generate a device key for lookup table indexing. + For CPU devices, returns None. + For CUDA devices, returns the props.gcnArchName string. + """ + if device.type != "cuda": + # only cuda devices are supported, this indicates that the system is not in use + # for this device + return None + + # Get CUDA device properties + props = torch.cuda.get_device_properties(device.index) + return props.gcnArchName + + @staticmethod + def _generate_kernel_inputs_key(kernel_inputs: KernelInputs) -> str: + """ + Generate a key based on input node properties and scalars. + The key includes dtype, size, and stride information for each input node, + plus scalar values as key=value pairs separated by & signs. + """ + # Get node information using existing methods + dtypes = kernel_inputs.dtypes() + shapes = kernel_inputs.shapes_hinted() + strides = kernel_inputs.strides_hinted() + + # Create tuple of (dtype, shape_list, stride_list) for each node + node_info = tuple( + (dtype, list(shape), list(stride)) + for dtype, shape, stride in zip(dtypes, shapes, strides) + ) + + # Create base key from node information + fmt_key = str(node_info) + # Add scalar information if present + if kernel_inputs._scalars: + # Sort scalars for consistent key generation and join with & + scalar_parts = [ + f"{key}={value}" + for key, value in sorted(kernel_inputs._scalars.items()) + ] + scalars_key = "&".join(scalar_parts) + fmt_key = f"{fmt_key}+{scalars_key}" + + return f"{fmt_key}" + + def make_lookup_key( + self, kernel_inputs: KernelInputs, op_name: str, include_device: bool = False + ) -> str | None: + """ + Create a flattened lookup key from kernel inputs and operation name. + Override this method to customize key generation. + + Args: + kernel_inputs: KernelInputs object containing input nodes and scalars + op_name: Operation name (e.g., "mm", "addmm") + include_device: Whether to include device key in the generated key + + Returns: + A string key combining device (optional), operation, and input information + """ + device = kernel_inputs.device() + dev_key = self._get_device_key(device) + if dev_key is None: + # The system does not run when dev_key is None, regardless of + # whether include_device is True or False + return None + if not include_device: + dev_key = None + + # Generate input key using our staticmethod + input_key = self._generate_kernel_inputs_key(kernel_inputs) + + # Create the flattened lookup key + if dev_key is not None: + key_parts = [dev_key, input_key, op_name] + else: + key_parts = [input_key, op_name] + + return "+".join(key_parts) + + def make_lookup_key_variants( + self, kernel_inputs: KernelInputs, op_name: str + ) -> tuple[str | None, str | None]: + """ + Generate both device-specific and device-agnostic lookup keys. + Override this method to customize key variant generation. + + Args: + kernel_inputs: KernelInputs object containing input nodes and scalars + op_name: Operation name (e.g., "mm", "addmm") + + Returns: + Tuple of (device_key, device_agnostic_key). Either may be None if generation fails. + """ + device_key = self.make_lookup_key(kernel_inputs, op_name, include_device=True) + device_agnostic_key = self.make_lookup_key( + kernel_inputs, op_name, include_device=False + ) + + return device_key, device_agnostic_key + + @staticmethod + def _entry_is_valid( + cfg: dict[str, Any], + template_id: str, + template_hash_map: dict[str, str | None] | None, + ) -> bool: + """ + Check if a config entry is valid based on template hash validation. + + Args: + cfg: Configuration dictionary that may contain a template_hash field + template_id: The template identifier + template_hash_map: Optional mapping from template_uid to src_hash for validation + + Returns: + True if the config is valid and should be kept, False if it should be filtered out + """ + # If hash checking is disabled or no hash map provided, keep the config + if not config.lookup_table.check_src_hash or not template_hash_map: + return True + + template_hash = template_hash_map.get(template_id) + config_hash = cfg.get("template_hash") + + # Both hashes present - validate they match + if template_hash is not None and config_hash is not None: + if config_hash != template_hash: + log.warning( + "Hash validation failed for template '%s': config_hash='%s' != template_hash='%s'. " + "Template code may have changed. Filtering out config: %s", + template_id, + config_hash, + template_hash, + {k: v for k, v in cfg.items() if k != "template_hash"}, + ) + return False + else: + log.debug( + "Hash validation passed for template '%s': hash='%s'", + template_id, + template_hash, + ) + return True + # Config has no hash - keep it + elif config_hash is None: + log.debug( + "Config for template '%s' has no hash - keeping it (template_hash='%s')", + template_id, + template_hash, + ) + return True + # Template has no hash - keep config + else: + log.debug( + "Template '%s' has no src_hash - keeping config with hash '%s'", + template_id, + config_hash, + ) + return True + + def lookup_template_configs( + self, + kernel_inputs: KernelInputs, + op_name: str, + template_uids: list[str], + template_hash_map: dict[str, str | None] | None = None, + ) -> dict[str, list[dict[str, Any]]]: + """ + Unified function to look up template configurations for multiple templates. + Override this method to customize lookup logic. + + Args: + kernel_inputs: KernelInputs object containing input nodes and scalars + op_name: Operation name (e.g., "mm", "addmm") + template_uids: List of template identifiers (e.g., ["mm", "tma", "decompose_k"]) + template_hash_map: Optional mapping from template_uid to src_hash for validation + + Returns: + {}: No lookup table in use, or no matches found for any template + {"template_uid1": [config1, config2], ...}: Matches found, filtered configurations + """ + lookup_table = self._get_lookup_table() + if not lookup_table: + log.debug("Lookup table: no table configured or CUDA unavailable") + return {} + + # Try both key variants: device-specific first, then device-agnostic + # If both exist, device-specific takes priority + device_key, device_agnostic_key = self.make_lookup_key_variants( + kernel_inputs, op_name + ) + + config_list = [] + + for key_type, key in [ + ("device-specific", device_key), + ("device-agnostic", device_agnostic_key), + ]: + if key is not None: + config_list = lookup_table.get(key, []) + if config_list: + log.debug( + "Lookup table: found %d configs using %s key '%s' for %s", + len(config_list), + key_type, + key, + op_name, + ) + break + else: + log.debug( + "Lookup table: no match for %s (tried keys: %s, %s) (table has %d keys)", + op_name, + device_key, + device_agnostic_key, + len(lookup_table), + ) + return {} + + log.debug( + "Lookup table: found %d configs for %s templates %s", + len(config_list), + op_name, + template_uids, + ) + # Group configs by template_id + configs_by_template: dict[str, list[dict[str, Any]]] = {} + for cfg in config_list: + if not isinstance(cfg, dict): + raise ValueError( + f"Config for {op_name} operation is not a dictionary: {cfg}" + ) + if "template_id" not in cfg: + raise ValueError( + f"Config for {op_name} operation missing required 'template_id' field: {cfg}" + ) + + template_id = cfg["template_id"] + if template_id in template_uids: + if template_id not in configs_by_template: + configs_by_template[template_id] = [] + configs_by_template[template_id].append(cfg) + + # Check template hashes and clean up template_id field + result = {} + for template_id, matching_configs in configs_by_template.items(): + filtered_configs = [] + for cfg in matching_configs: + # Check template hash using helper function + if not self._entry_is_valid(cfg, template_id, template_hash_map): + continue + + # Return a copy of the config, as we don't want to modify the original + cconfig = copy.deepcopy(cfg) + # Lastly, we have to throw out the template_id, as it's not a valid kwarg + # and just used to identify which template the entry belongs to + del cconfig["template_id"] + # Similarly, the template_hash is not a valid kwarg + cconfig.pop("template_hash", None) + filtered_configs.append(cconfig) + + if filtered_configs: + result[template_id] = filtered_configs + + return result + + def _finalize_template_configs( + self, + template_choices: dict[str, Generator[KernelTemplateChoice, None, None]], + kernel_inputs: KernelInputs, + templates: list[KernelTemplate | ExternKernelChoice], + op_name: str, + kwarg_overrides: dict[str, dict[str, Any]] | None = None, + ) -> list[KernelTemplateChoice]: + """Check lookup table for hits, use those if found, otherwise fall back to parent.""" + # 1. Collect template src_hashes for validation + template_uids = [template.uid for template in templates] + template_hash_map = {} + for template in templates: + src_hash = getattr(template, "src_hash", None) + template_hash_map[template.uid] = src_hash + + log.debug( + "Choices: attempting lookup for %s with %d templates", + op_name, + len(template_uids), + ) + + # 2. Single batch lookup for all templates + lookup_results = self.lookup_template_configs( + kernel_inputs, op_name, template_uids, template_hash_map + ) + + # 3. Early exit if no lookup table or no matches + if not lookup_results: # Empty dict + log.info("LookupChoices: lookup miss for %s, using fallback", op_name) + return self._fallback( + template_choices, + kernel_inputs, + templates, + op_name, + kwarg_overrides, + ) + + log.info( + "LookupChoices: lookup hit for %s - found %d/%d templates: %s", + op_name, + len(lookup_results), + len(template_uids), + list(lookup_results.keys()), + ) + + # 4. Create KTCs only for templates with lookup entries + return self._create_lookup_choices( + lookup_results, templates, kernel_inputs, op_name + ) + + def _fallback( + self, + template_choices: dict[str, Generator[KernelTemplateChoice, None, None]], + kernel_inputs: KernelInputs, + templates: list[KernelTemplate | ExternKernelChoice], + op_name: str, + kwarg_overrides: dict[str, dict[str, Any]] | None = None, + ) -> list[KernelTemplateChoice]: + """Fallback to parent if no lookup table or no matches.""" + # NOTE: this is broken out, so that subclasses are able to override this + # to handle explicitly the situations where the lookup table had a miss vs + # overriding the entire logic + return super()._finalize_template_configs( + template_choices, + kernel_inputs, + templates, + op_name, + kwarg_overrides, + ) + + def _create_lookup_choices( + self, + lookup_results: dict[str, list[dict[str, Any]]], + templates: list[KernelTemplate | ExternKernelChoice], + kernel_inputs: KernelInputs, + op_name: str, + ) -> list[KernelTemplateChoice]: + """Create KernelTemplateChoice objects from lookup results using parent's get_ktc method.""" + templates_by_uid = {template.uid: template for template in templates} + lookup_choices: list[KernelTemplateChoice] = [] + + for template_uid, configs in lookup_results.items(): + template = templates_by_uid[template_uid] + + # Use parent's get_ktc method to get a generator, then get the first base KTC + ktc_generator = self.get_ktc(kernel_inputs, template, op_name) + + try: + base_ktc = next(ktc_generator) + except StopIteration: + # No configs from heuristic, skip this template + continue + + # For each lookup config, create a KTC with the override kwargs + # Start from base params (which include derived options like OUT_DTYPE) + # and let the lookup config override them + base_kwargs = base_ktc.params.to_kwargs() + for c in configs: + merged = {**base_kwargs, **c} + lookup_ktc = KernelTemplateChoice( + template=base_ktc.template, + params=DictKernelTemplateParams(merged), + extra_kwargs=base_ktc.extra_kwargs, + layout=base_ktc.layout, + inputs=base_ktc.inputs, + ) + lookup_choices.append(lookup_ktc) + + return lookup_choices diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/loop_body.py b/.venv/lib/python3.12/site-packages/torch/_inductor/loop_body.py new file mode 100644 index 0000000000000000000000000000000000000000..1fe16358b8b7b8f775287a6cdd2d613b3086a14d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/loop_body.py @@ -0,0 +1,900 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import collections +import functools +import itertools +import re +from enum import auto, Enum +from typing import Any, NamedTuple, TYPE_CHECKING, TypeVar + +import sympy + +import torch.fx +from torch._dynamo.utils import identity +from torch.fx.proxy import Scope, TracerBase +from torch.utils._sympy.functions import Mod +from torch.utils._sympy.symbol import SymT + +from . import config, dependencies +from .codegen.common import index_prevent_reordering +from .ops_handler import DefaultHandler, OpsHandler, WrapperHandler +from .utils import ( + cache_on_self, + decompose_index, + flatten_index, + reduction_num_outputs, + sympy_index_symbol_with_prefix, + sympy_subs, +) +from .virtualized import ops, V + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + +T = TypeVar("T") + + +class InterpreterShim(torch.fx.Interpreter): + @staticmethod + @functools.cache + def _dummy_gm(): + return torch.fx.symbolic_trace(identity) + + def __init__(self, graph, submodules): + # call super() with a placeholder to avoid constructing a + # GraphModule which is very expensive (it does codegen). + super().__init__(self._dummy_gm(), garbage_collect_values=False) + self.module = self # type: ignore[assignment] + self.graph = graph + self.submodules = submodules + self.extra_traceback = False + self.fetch_attr = submodules.__getitem__ # type: ignore[method-assign] + self.current_node = None + + def run_node(self, n: torch.fx.Node) -> Any: + # pyrefly: ignore [bad-assignment] + self.current_node = n + return super().run_node(n) + + def run(self, *args, **kwargs): + with V.set_interpreter_handler(self): + return super().run(*args, **kwargs) + + +# We don't need the nn.Module and constant handling in Tracer +class LightTracer(TracerBase): + def __init__(self): + super().__init__() + self.graph = torch.fx.Graph(tracer_cls=self.__class__) # type: ignore[arg-type] + self.scope = Scope("", None) + self.module_stack = {} # type: ignore[assignment] + self.node_name_to_scope = {} + + +class MemoryEntry(NamedTuple): + index_name: str # LoopBody.indexing_exprs[index_name] + buffer_name: str | None + mode: str | None # V.ops.store(..., mode=mode) + + +class MemoryUsageType(Enum): + # These are 1:1 with the opcode generating the usage + LOAD = auto() + LOAD_SEED = auto() + STORE = auto() + STORE_REDUCTION = auto() + INDEX_EXPR = auto() + CHECK_BOUNDS = auto() + BUCKETIZE = auto() + + +class LoopBody: + """ + Captures the body of a Loops subclass into an FX graph. Persists any + indexing simplifications and makes it easier to analyze loop bodies. + """ + + indexing_exprs: dict[str, sympy.Expr] + submodules: dict[str, Any] + subblocks: dict[str, LoopBodyBlock] + indirect_vars: list[sympy.Symbol] + indirect_var_ranges: dict[sympy.Symbol, sympy.Expr] + root_block: LoopBodyBlock + memory_usage: dict[MemoryUsageType, list[MemoryEntry]] + op_counts: collections.Counter[str] + + # defined only temporarily + indexing_exprs_name: dict[sympy.Expr, str] + + @staticmethod + def _wrap_int_to_sympy_integer(expr): + # Static sizes can enter indexing expressions as Python ints. + if type(expr) is int: + return sympy.Integer(expr) + return expr + + def __init__( + self, + fn, + args, + var_ranges, + iter_vars, + reduce_vars, + allow_same_symbol_in_index=False, + ): + super().__init__() + + _flat_sizes = tuple(var_ranges.values()) + self.sizes = ( + _flat_sizes[: len(iter_vars)], + _flat_sizes[len(iter_vars) :], + ) + + self.iter_vars = iter_vars + self.reduce_vars = reduce_vars + self.var_ranges = var_ranges + + if isinstance(fn, LoopBody): + self._init_with_copy(fn, args, allow_same_symbol_in_index) + else: + self._init_with_tracing(fn, args) + + self.indexing = None + + def get_original_num_rdims(self) -> int: + if not self.has_partial_accumulate: + raise AssertionError("Expected has_partial_accumulate to be set") + node = self.root_block.graph.find_nodes( + op="call_method", target="partial_accumulate" + )[0] + meta = node.args[-1] + return meta["num_reduction_dims"] + + def extract_pw_from_reduction(self): + self.root_block = self.root_block.extract_pw_from_reduction() + self.has_partial_accumulate = True + self.iter_vars = self.iter_vars + self.reduce_vars + self.reduce_vars = [] + self.sizes = (self.sizes[0] + self.sizes[1], tuple()) + return self + + def _init_with_tracing(self, fn, args): + """Do an FX trace of an arbitrary callable to construct self""" + self.indexing_exprs = {} + self.indexing_exprs_name = {} + self.submodules = {"get_index": self.get_index} + self.subblocks = {} + self.indirect_vars = [] + self.indirect_var_ranges: dict[sympy.Symbol, sympy.Expr] = {} + self.memory_usage = {t: [] for t in MemoryUsageType} + self.op_counts = collections.Counter() + self.root_block = LoopBodyBlock(self, fn, args) # traces + self.has_partial_accumulate = bool( + self.root_block.graph.find_nodes( + op="call_method", target="partial_accumulate" + ) + ) + del self.indexing_exprs_name # not used after _init_with_tracing + + def _init_with_copy(self, other: LoopBody, args, allow_same_symbol_in_index): + """ + _init_with_tracing() is slow, so this is a fast path in the case + where we are just reordering/merging/splitting the args of an + existing LoopBody. + """ + indexing_exprs = other.indexing_from_args(args, allow_same_symbol_in_index) + self.indexing_exprs = { + name: self._wrap_int_to_sympy_integer( + V.graph.sizevars.simplify_with_ranges(expr, self.var_ranges) + ) + for name, expr in indexing_exprs.items() + } + self.subblocks = {k: v.clone(self) for k, v in other.subblocks.items()} + self.indirect_vars = other.indirect_vars + self.indirect_var_ranges = other.indirect_var_ranges + self.memory_usage = other.memory_usage + self.op_counts = other.op_counts + self.root_block = other.root_block.clone(self) + self.has_partial_accumulate = other.has_partial_accumulate + + submodules = {**other.submodules} + submodules.pop("get_index") + self.submodules = { + "get_index": self.get_index, + **{k: v.clone(self) for k, v in submodules.items()}, # type: ignore[attr-defined] + } + + def has_op(self, name: str): + return self.op_counts.get(name, 0) > 0 + + def merge_loops(self) -> LoopBody: + """ + Merge both iteration and reduction loops and return a new LoopBody. + """ + old_body = self + old_sizes = self.sizes + old_iter_vars, old_reduce_vars = old_body.vars + old_iter_sizes, old_reduce_sizes = old_sizes + + index_exprs = [*old_body.indexing_exprs.values()] + + iter_sizes, iter_reindex, _ = V.graph.sizevars._simplify_loops( + old_iter_vars, + old_iter_sizes, + index_prevent_reordering(index_exprs, old_iter_vars, old_iter_sizes), + ) + + reduce_sizes, reduce_reindex, _ = V.graph.sizevars._simplify_loops( + old_reduce_vars, + old_reduce_sizes, + index_prevent_reordering(index_exprs, old_reduce_vars, old_reduce_sizes), + ) + + if iter_sizes == old_iter_sizes and reduce_sizes == old_reduce_sizes: + return old_body + + ( + ( + iter_vars, + reduce_vars, + ), + var_ranges, + ) = dependencies.index_vars_no_squeeze(iter_sizes, reduce_sizes, prefix="p") + new_body = LoopBody( + old_body, + [iter_reindex(iter_vars), reduce_reindex(reduce_vars)], + var_ranges, + iter_vars, + reduce_vars, + allow_same_symbol_in_index=True, + ) + + return new_body + + def with_indexing_exprs(self, replacements: dict[str, sympy.Expr]) -> LoopBody: + iter_vars, reduce_vars = self.vars + new_body = LoopBody( + self, + (iter_vars, reduce_vars), + self.var_ranges, + iter_vars, + reduce_vars, + allow_same_symbol_in_index=True, + ) + new_body.indexing_exprs.update(replacements) + return new_body + + def expand_dimension_for_pointwise_node( + self, dimension: int, new_range: int + ) -> LoopBody: + """ + Expand node on `dimension` to `new_range` and rely on index modular to avoid + out-of-boundary access. + """ + + old_body = self + old_sizes = self.sizes + + iter_size, reduce_size = old_sizes + original_range = iter_size[dimension] + new_iter_size = list(iter_size) + new_iter_size[dimension] = new_range + new_sizes = (new_iter_size, reduce_size) + + (iter_vars, reduce_vars), var_ranges = dependencies.index_vars_no_squeeze( + *new_sizes, + prefix="t", # type: ignore[arg-type] + ) + + def new_body(*indices: Sequence[sympy.Expr]) -> Any: + index = [*itertools.chain.from_iterable(indices)] + if not len(index) == len(iter_size) + len(reduce_size): + raise AssertionError( + f"Expected index length {len(index)} to equal " + f"iter_size + reduce_size ({len(iter_size)} + {len(reduce_size)})" + ) + iter_idx = index[: len(iter_size)] + reduce_idx = index[len(iter_size) :] + + new_iter_idx = list(iter_idx) + new_iter_idx[dimension] = Mod(iter_idx[dimension], original_range) + + return old_body(new_iter_idx, reduce_idx) + + loop_body = LoopBody( + new_body, (iter_vars, reduce_vars), var_ranges, iter_vars, reduce_vars + ) + + # use the original symbol prefix so we can do multiple round of reordering + (iter_vars2, reduce_vars2), var_ranges2 = dependencies.index_vars_no_squeeze( + *new_sizes, + prefix="p", # type: ignore[arg-type] + ) + new_body = LoopBody( + loop_body, (iter_vars2, reduce_vars2), var_ranges2, iter_vars2, reduce_vars2 + ) + return new_body + + def reindex_iter_loops(self, new_iter_sizes: Sequence[sympy.Expr]) -> LoopBody: + """ + Reindex iteration loops into a different factorization of the same + total numel. For example, [1024, 8192] -> [65536, 128]. + + The old iteration vars are expressed as functions of the new vars via + FloorDiv and ModularIndexing on the flat index. + """ + old_body = self + old_iter_sizes = self.sizes[0] + reduce_sizes = self.sizes[1] + + new_sizes = (list(new_iter_sizes), list(reduce_sizes)) + + (iter_vars, reduce_vars), var_ranges = dependencies.index_vars_no_squeeze( + *new_sizes, + prefix="t", # type: ignore[arg-type] + ) + + def new_body(*indices: Sequence[sympy.Expr]) -> Any: + index = [*itertools.chain.from_iterable(indices)] + new_iter_idx = index[: len(new_iter_sizes)] + reduce_idx = index[len(new_iter_sizes) :] + flat = flatten_index(new_iter_idx, new_iter_sizes) + old_iter_idx = decompose_index(flat, old_iter_sizes) + return old_body(old_iter_idx, list(reduce_idx)) + + loop_body = LoopBody( + new_body, (iter_vars, reduce_vars), var_ranges, iter_vars, reduce_vars + ) + + (iter_vars2, reduce_vars2), var_ranges2 = dependencies.index_vars_no_squeeze( + *new_sizes, + prefix="p", # type: ignore[arg-type] + ) + return LoopBody( + loop_body, + (iter_vars2, reduce_vars2), + var_ranges2, + iter_vars2, + reduce_vars2, + ) + + def reorder_iter_loops(self, new_order) -> LoopBody: + """ + Reorder iteration loops and return a new LoopBody. + """ + from .ir import same_reorder + + old_body = self + old_sizes = self.sizes + if not len(old_sizes[0]) == len(new_order): + raise AssertionError( + f"Expected old_sizes[0] length {len(old_sizes[0])} to equal " + f"new_order length {len(new_order)}" + ) + reorder_fn = same_reorder(new_order) + + iter_size, reduce_size = old_sizes + new_iter_size = reorder_fn(iter_size) + + new_sizes = (new_iter_size, reduce_size) + + (iter_vars, reduce_vars), var_ranges = dependencies.index_vars_no_squeeze( + *new_sizes, + prefix="p", # type: ignore[arg-type] + ) + + inverse_order = {b: a for a, b in enumerate(new_order)} + inverse_order = [inverse_order[i] for i in range(len(new_order))] + + def new_body(*indices: Sequence[sympy.Expr]) -> Any: + index = [*itertools.chain.from_iterable(indices)] + if not len(index) == len(iter_size) + len(reduce_size): + raise AssertionError( + f"Expected index length {len(index)} to equal " + f"iter_size + reduce_size ({len(iter_size)} + {len(reduce_size)})" + ) + iter_idx = index[: len(iter_size)] + reduce_idx = index[len(iter_size) :] + iter_idx = [iter_idx[i] for i in inverse_order] + return old_body(iter_idx, reduce_idx, allow_same_symbol_in_index=True) + + return LoopBody( + new_body, + (iter_vars, reduce_vars), + var_ranges, + iter_vars, + reduce_vars, + ) + + @property + def vars(self): + if self.iter_vars is None: + raise AssertionError("iter_vars is None") + if self.reduce_vars is None: + raise AssertionError("reduce_vars is None") + return self.iter_vars, self.reduce_vars + + @cache_on_self + def get_nodes(self): + all_graphs = itertools.chain( + (self.root_block.graph,), + (block.graph for block in self.subblocks.values()), + ) + return [node for graph in all_graphs for node in graph.nodes] + + @cache_on_self + def bounds(self): + # Doing a local import to avoid dumping all the code here + from .bounds import BoundVars + + return BoundVars(self) + + def get_read_expr(self, buffer_name): + # reversed to match old behavior + for entry in reversed(self.memory_usage[MemoryUsageType.LOAD]): + if entry.buffer_name == buffer_name: + return self.indexing_exprs[entry.index_name] + raise KeyError(buffer_name) + + def get_write_expr(self, buffer_name): + for entry in itertools.chain( + self.memory_usage[MemoryUsageType.STORE], + self.memory_usage[MemoryUsageType.STORE_REDUCTION], + ): + if entry.buffer_name == buffer_name: + return self.indexing_exprs[entry.index_name] + raise KeyError(buffer_name) + + def get_read_exprs(self): + return [ + self.indexing_exprs[entry.index_name] + for entry in self.memory_usage[MemoryUsageType.LOAD] + ] + + def get_all_read_expr(self, buffer_name): + # reversed to match old behavior + out = [] + for entry in reversed(self.memory_usage[MemoryUsageType.LOAD]): + if entry.buffer_name == buffer_name: + out.append(self.indexing_exprs[entry.index_name]) + return out + + def get_write_exprs(self): + return [ + self.indexing_exprs[entry.index_name] + for entry in itertools.chain( + self.memory_usage[MemoryUsageType.STORE], + self.memory_usage[MemoryUsageType.STORE_REDUCTION], + ) + ] + + def get_all_write_expr(self, buffer_name): + out = [] + for entry in itertools.chain( + self.memory_usage[MemoryUsageType.STORE], + self.memory_usage[MemoryUsageType.STORE_REDUCTION], + ): + if entry.buffer_name == buffer_name: + out.append(self.indexing_exprs[entry.index_name]) + return out + + def debug_str(self): + lines = [f"var_ranges = {dict(self.var_ranges)}"] + lines.extend([f"{name} = {val}" for name, val in self.indexing_exprs.items()]) + lines.extend( + [ + block.debug_str(name) + for name, block in itertools.chain( + [("body", self.root_block)], self.subblocks.items() + ) + ] + ) + return "\n".join(lines) + + def is_memory_copy(self) -> bool: + """ + True if this contains only a single loads and store. + Note, this could involve a layout change. + """ + return ( + len(self.memory_usage[MemoryUsageType.LOAD]) == 1 + and len(self.memory_usage[MemoryUsageType.STORE]) == 1 + and len(self.submodules) == 1 # get_index + and self.root_block.contains_only_ops(("load", "store")) + ) + + __repr__ = debug_str + + def add_index_expr( + self, + expr: sympy.Expr, + mtype: MemoryUsageType, + buffer_name: str | None = None, + mode: str | None = None, + ): + expr = self._wrap_int_to_sympy_integer(expr) + name = self.indexing_exprs_name.get(expr) + if not name: + name = f"index{len(self.indexing_exprs)}" + self.indexing_exprs_name[expr] = name + self.indexing_exprs[name] = expr + self.memory_usage[mtype].append(MemoryEntry(name, buffer_name, mode)) + return name + + def add_submodule(self, block, prefix): + """Not actually for nn.Modules, but subblocks in generated code are mapped to FX call_module opcodes""" + if prefix[-1].isnumeric() and prefix not in self.submodules: + name = prefix + else: + name = f"{prefix}{len(self.submodules)}" + self.submodules[name] = block + return name + + def add_indirect(self, size): + var = sympy_index_symbol_with_prefix(SymT.INDIRECT, len(self.indirect_vars)) + if var in self.indirect_var_ranges: + raise AssertionError(f"Indirect var {var} already in indirect_var_ranges") + self.indirect_vars.append(var) + self.indirect_var_ranges[var] = size + return var + + def replace_indirect(self, old, new): + """Swap in a variable used in indirect indexing""" + if str(old) == str(new): + return + if self.indexing is None: + raise AssertionError("indexing must be set before replace_indirect") + # pyrefly: ignore [bad-assignment] + self.indexing = {k: sympy_subs(v, {old: new}) for k, v in self.indexing.items()} + + def get_index(self, name): + if self.indexing is None: + raise AssertionError("indexing must be set before get_index") + return self.indexing[name] + + def indexing_from_args(self, indices, allow_same_symbol_in_index=False): + index = [*itertools.chain.from_iterable(indices)] + if not len(index) == len(self.var_ranges): + raise AssertionError(f"Index length mismatch: {index} vs {self.var_ranges}") + if not allow_same_symbol_in_index and not all( + v not in self.var_ranges for v in index + ): + raise AssertionError( + f"Same symbol found in index: {self.var_ranges=}, {indices=}" + ) + + replacements = dict(zip(self.var_ranges.keys(), index)) + return { + name: sympy_subs(expr, replacements) + for name, expr in self.indexing_exprs.items() + } + + def __call__(self, *indices, allow_same_symbol_in_index=False): + self.indexing = self.indexing_from_args(indices, allow_same_symbol_in_index) + result = self.root_block() + self.indexing = None + return result + + def bind_set_indirect_shim(self, var, size, check, wrap_neg): + def set_indirect(new_var): + self.replace_indirect( + var, V.ops.indirect_indexing(new_var, size, check, wrap_neg) + ) + + set_indirect.clone = functools.partial( # type: ignore[attr-defined] + LoopBody.bind_set_indirect_shim, + var=var, + size=size, + check=check, + wrap_neg=wrap_neg, + ) + return set_indirect + + def bind_scan_shim(self, combine_fn): + def shim(dtypes, values): + return V.ops.scan(dtypes, combine_fn, values) + + shim.clone = functools.partial(LoopBody.bind_scan_shim, combine_fn=combine_fn) # type: ignore[attr-defined] + return shim + + def bind_masked_shim(self, name): + def shim(mask, other): + return V.ops.masked(mask, self.subblocks[name], other) + + shim.clone = functools.partial(LoopBody.bind_masked_shim, name=name) # type: ignore[attr-defined] + return shim + + +class LoopBodyBlock: + """ + Captures the body of a Loops subclass into an FX graph. + In normal cases there will be a 1:1 mapping between LoopBody and + LoopBodyBlock, however in the case of ops.masked() the masked out + operations will manifest as an extra LoopBodyBlock. + """ + + def __init__(self, body: LoopBody, fn: Callable[..., Any], args: list[Any]): + self.body = body + + tracer = LightTracer() + proxy_ops = tracer.create_proxy("placeholder", "ops", (), {}) + + from .index_propagation import IndexPropagation + + handler: Any = CountOps( + CaptureIndexing( + # pyrefly: ignore[bad-argument-type] + proxy_ops, + body, + tracer, + ), + body.op_counts, + ) + if config.constant_and_index_propagation: + handler = IndexPropagation( + handler, self.body.var_ranges, self.body.indirect_var_ranges + ) + + with V.set_ops_handler(handler): + # This indirection is just a cute way to get IndexPropagation to + # unwrap the return value. + ops.output(fn(*args)) + self.graph = tracer.graph + + def extract_pw_from_reduction(self): + red = None + store = None + for node in self.graph.nodes: + if node.target == "reduction": + if red: + raise AssertionError("Found multiple reduction nodes") + red = node + if node.target == "store_reduction": + if store: + raise AssertionError("Found multiple store_reduction nodes") + store = node + if not red: + raise AssertionError("No reduction node found in graph") + if not store: + raise AssertionError("No store_reduction node found in graph") + reduction_type = red.args[-2] + red_arg = red.args[-1] + buf = store.args[1] + ops = store.args[0] + + extra_meta = { + "num_reduction_dims": len(self.body.reduce_vars), + } + with self.graph.inserting_after(store): + self.graph.call_method( + "partial_accumulate", (ops, buf, reduction_type, red_arg, extra_meta) + ) + self.graph.erase_node(store) + self.graph.erase_node(red) + return self + + def __call__(self): + graph = self.graph + submodules = self.body.submodules + + return InterpreterShim(graph, submodules).run(V.get_ops_handler()) + + def debug_str(self, name="block"): + code = torch.fx.GraphModule(self.body.submodules, self.graph).code + return re.sub( + # strip `; del var0` suffixes to make output prettier + r";[^\n]*", + "", + code.strip().replace("def forward(", f"def {name}("), + ) + + def contains_only_ops(self, allowed_ops) -> bool: + return all( + node.target in allowed_ops + for node in self.graph.find_nodes(op="call_method") + ) + + def clone(self, body: LoopBody): + """Shallow copy with a new parent LoopBody""" + copy = LoopBodyBlock.__new__(LoopBodyBlock) + copy.__dict__.update({**self.__dict__, "body": body}) + return copy + + +class CountOps(DefaultHandler): + def __init__(self, inner: OpsHandler[Any], counts: collections.Counter[str]): + self._inner = inner + self._counts = counts + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + self._counts[name] += 1 + return getattr(self._inner, name)(*args, **kwargs) + + +class CaptureIndexing(WrapperHandler): + name = "CaptureIndexing" + + def __init__( + self, + inner: OpsHandler[Any], + body: LoopBody, + tracer: LightTracer, + ): + super().__init__(inner) + self.body = body + self.tracer = tracer + + def _add_index(self, expr: sympy.Expr, mtype: MemoryUsageType, **kwargs: Any): + return self.tracer.create_proxy( + "call_module", + "get_index", + (self.body.add_index_expr(expr, mtype, **kwargs),), + {}, + ) + + def _simplify(self, expr: sympy.Expr) -> sympy.Expr: + return V.graph.sizevars.simplify_with_ranges(expr, self.body.var_ranges) + + def load(self, name: str, index: sympy.Expr): + index = self._simplify(index) + index = self._add_index(index, MemoryUsageType.LOAD, buffer_name=name) + return self._inner.load(name, index) + + def load_seed(self, name: str, index: int): + if not isinstance(index, int): + raise AssertionError(f"Expected int, got {type(index)}") + self.body.add_index_expr( + sympy.Integer(index), MemoryUsageType.LOAD_SEED, buffer_name=name + ) + return self._inner.load_seed(name, index) + + def store(self, name, index, value, mode=None): + index = self._simplify(index) + index = self._add_index( + index, MemoryUsageType.STORE, buffer_name=name, mode=mode + ) + return self._inner.store(name, index, value, mode) + + def store_reduction(self, name, index, value): + index = self._simplify(index) + index = self._add_index( + index, MemoryUsageType.STORE_REDUCTION, buffer_name=name + ) + return self._inner.store_reduction(name, index, value) + + def reduction(self, dtype, src_dtype, reduction_type, value): + result = self._inner.reduction(dtype, src_dtype, reduction_type, value) + num_outputs = reduction_num_outputs(reduction_type) + if num_outputs > 1: + return tuple(result[i] for i in range(num_outputs)) + return result + + def index_expr(self, index, dtype): + index = self._simplify(index) + if isinstance(index, (int, sympy.Integer)): + return self._inner.constant(int(index), dtype) + index = self._add_index(index, MemoryUsageType.INDEX_EXPR) + return self._inner.index_expr(index, dtype) + + def value_expr(self, index, dtype): + index = self._simplify(index) + if isinstance(index, (int, sympy.Integer)): + return self._inner.constant(int(index), dtype) + index = self._add_index(index, MemoryUsageType.INDEX_EXPR) + return self._inner.value_expr(index, dtype) + + def check_bounds(self, index, size, lower, upper): + index = self._simplify(index) + index = self._add_index(index, MemoryUsageType.CHECK_BOUNDS) + size = self.body._wrap_int_to_sympy_integer(size) + size = self._add_index(size, MemoryUsageType.CHECK_BOUNDS) + return self._inner.check_bounds(index, size, lower, upper) + + def bucketize( + self, + values: T, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: T, + indexing_dtype: torch.dtype, + right: bool, + sorter: tuple[str, sympy.Expr] | None = None, + sorter_indices: T | None = None, + ) -> T: + """ + See [Note: Inductor bucketize op] + """ + boundaries = ( + boundaries[0], + self._add_index( + boundaries[1], + MemoryUsageType.BUCKETIZE, + buffer_name=boundaries[0], + ), + self._add_index( + boundaries[2], + MemoryUsageType.BUCKETIZE, + buffer_name=boundaries[0], + ), + self._add_index( + boundaries[3], + MemoryUsageType.BUCKETIZE, + buffer_name=boundaries[0], + ), + ) + if sorter is not None: + sorter = ( + sorter[0], + self._add_index( + sorter[1], MemoryUsageType.BUCKETIZE, buffer_name=sorter[0] + ), + ) + + return self._inner.bucketize( + values, + boundaries, + boundary_indices, + indexing_dtype, + right, + sorter, + sorter_indices, + ) + + def masked(self, mask_proxy, masked_body: Callable[..., Any], other_proxy): + """ + Recursively capture the masked out body in another LoopBodyBlock + """ + name = self.body.add_submodule(None, "masked_subblock") + self.body.submodules[name] = self.body.bind_masked_shim(name) + self.body.subblocks[name] = LoopBodyBlock(self.body, masked_body, []) + return self.tracer.create_proxy( + "call_module", name, (mask_proxy, other_proxy), {} + ) + + def scan( + self, + dtype_proxy, + combine_fn: Callable[[tuple[Any, ...], tuple[Any, ...]], tuple[Any, ...]], + value_proxy, + ): + shim = self.body.bind_scan_shim(combine_fn) + name = self.body.add_submodule(shim, "scan") + result = self.tracer.create_proxy( + "call_module", + name, + (dtype_proxy, value_proxy), + {}, + ) + # Proxies are iterable, but some methods expect tuples/lists + return tuple(result[i] for i in range(len(value_proxy))) + + def sort(self, dtypes, values, stable, descending): + result = self._inner.sort(dtypes, values, stable, descending) + # Proxies are iterable, but some methods expect tuples/lists + return tuple(result[i] for i in range(len(values))) + + def frexp(self, value_proxy): + result = self._inner.frexp(value_proxy) + # Proxies are iterable, but some methods expect tuples/lists + return (result[0], result[1]) + + def indirect_indexing(self, index_proxy, size, check=True, wrap_neg=True): + """ + Flow data from tensors into indexing formulas. + Introduce a call_module to update the indexing. + """ + + var = self.body.add_indirect(size) + set_indirect = self.body.bind_set_indirect_shim(var, size, check, wrap_neg) + self.tracer.create_proxy( + "call_module", + self.body.add_submodule(set_indirect, f"set_{var}"), + (index_proxy,), + {}, + ) + return var + + def output(self, *result): + self.tracer.create_proxy("output", "output", result, {}) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/lowering.py b/.venv/lib/python3.12/site-packages/torch/_inductor/lowering.py new file mode 100644 index 0000000000000000000000000000000000000000..a124b6ff8ad8ef9b671e54a321c767d4f9704e6f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/lowering.py @@ -0,0 +1,9727 @@ +from __future__ import annotations + +import contextlib +import dataclasses +import functools +import itertools +import logging +import math +import operator +import os +import sys +import warnings +from collections import defaultdict +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any, cast, Literal, TYPE_CHECKING, TypeGuard, TypeVar +from typing_extensions import ParamSpec +from unittest.mock import patch + +import sympy + +import torch +import torch.ao.quantization.fx._decomposed +import torch.fx +import torch.utils._pytree as pytree +from torch._dynamo.utils import counters +from torch._functorch._aot_autograd.descriptors import ( + SavedForBackwardsAOTOutput, + SavedForBackwardsNoVcCheckAOTOutput, +) +from torch._higher_order_ops.associative_scan import associative_scan_op +from torch._higher_order_ops.triton_kernel_wrap import triton_kernel_wrapper_mutation +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class_obj +from torch._library.utils import get_layout_constraint_tag +from torch._prims_common import ( + canonicalize_dim, + canonicalize_dims, + check, + dtype_to_type, + elementwise_dtypes, + ELEMENTWISE_TYPE_PROMOTION_KIND, + get_computation_dtype, + is_boolean_dtype, + is_float_dtype, + is_integer_dtype, + Number, +) +from torch.fx.experimental.sym_node import magic_methods, method_to_operator +from torch.fx.experimental.symbolic_shapes import ( + free_unbacked_symbols, + has_free_unbacked_symbols, + resolve_unbacked_bindings, + SymTypes, +) +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import ( + CeilDiv, + FloorDiv, + Identity, + Max, + Min, + Mod, + ModularIndexing, +) +from torch.utils._triton import has_triton_reduction_ordering + +from .._dynamo.utils import import_submodule +from . import config, inductor_prims, ir, test_operators # NOQA: F401 +from .decomposition import decompositions, get_decompositions +from .ir import ( + BaseView, + DtypeView, + ExpandView, + IndexingConstant, + IRNode, + is_triton, + MutableBox, + OnlineSoftmaxReduction, + ops_wrapper, + PermuteView, + Pointwise, + Reduction, + SqueezeView, + TensorBox, + validate_ir, + View, +) +from .utils import ( + ceildiv, + convert_symint_to_expr, + decode_device, + is_dynamic, + is_gpu, + is_nvidia_sm100_or_later, + is_pointwise_use, + is_triton_fp8_dtype_supported, + is_view, + needs_fallback_due_to_atomic_add_limitations, + pad_listlike, + register_op_dtype_propagation_rules, + register_op_requires_libdevice_fp64, + sympy_product, + use_scatter_fallback, +) +from .virtualized import ops, V + + +if TYPE_CHECKING: + from .ir import BaseConstant + from .ops_handler import ReductionType + + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +# TODO(jansel): we should implement decomps or lowerings for these +# https://github.com/pytorch/torchdynamo/issues/327 +FALLBACK_ALLOW_LIST = OrderedSet( + [ + "torchvision::roi_align", + "aten::index_add", + ] +) + +log = logging.getLogger(__name__) +lowerings: dict[Callable[..., Any] | str, Callable[..., Any]] = {} +# User-registered lowerings that take priority over built-in lowerings. +user_lowerings: dict[torch._ops.OpOverload, Callable[..., Any]] = {} +# Use maybe_layout_constraints to access this dict, we lazily register tag-based layout constraints +_maybe_layout_constraints: dict[torch._ops.OpOverload, Callable[..., Any] | None] = {} +fallbacks = OrderedSet[torch._ops.OpOverload]() +aten = torch.ops.aten +tr_c10d = torch.ops.tr_c10d +prims = torch.ops.prims +needs_realized_inputs = OrderedSet[torch._ops.OpOverload]() +foreach_ops = OrderedSet[torch._ops.OpOverload]( + [torch._higher_order_ops._foreach_map] # type: ignore[list-item] +) +# TODO(rec): torch._higher_order_ops._foreach_map is not an OpOverload +# so why is it in foreach_ops? +inplace_foreach_ops = OrderedSet[torch._ops.OpOverload]() +inplaceable_foreach_ops: dict[torch._ops.OpOverload, torch._ops.OpOverload] = {} +quantized_decomposed = torch.ops.quantized_decomposed +_SAVED_FOR_BACKWARDS_OUTPUT_DESC_TYPES = ( + SavedForBackwardsAOTOutput, + SavedForBackwardsNoVcCheckAOTOutput, +) + + +def cur_node_has_non_foreach_users() -> bool: + for node in V.graph.current_node.users: + for user in node.users: + if not (user.op == "call_function" and (user.target in foreach_ops)): + return True + + return False + + +# group by device, whether any of the inputs are dynamic +# note arg_pairs may or may not be a pair +# foreach_map for example just passes output buffers here +def group_foreach_args( + arg_pairs: Iterable[Any], +) -> defaultdict[tuple[Any, bool], list[tuple[int, Any]]]: + out = defaultdict(list) + unpack_args = False + for i, args in enumerate(arg_pairs): + if not isinstance(args, Iterable): + unpack_args = True + args = (args,) + use_foreach = ( + not is_dynamic(*args) or config.combo_kernel_foreach_dynamic_shapes + ) + device = None + for t in args: + if isinstance(t, TensorBox): + device = t.data.get_device() + break + if device is None: + raise AssertionError("foreach op should have at least one tensor arg") + if unpack_args: + (args,) = args + out[(device, use_foreach)].append((i, args)) + return out + + +def maybe_layout_constraints(fn: Callable[..., Any]) -> Callable[..., Any] | None: + """Get layout constraints. Returns None if there are no layout constraints.""" + if not isinstance(fn, torch._ops.OpOverload): + # Only OpOverloads have layout constraints. + return None + + if maybe_layout_tag := get_layout_constraint_tag(fn, with_default=False): + return tag_to_layout_constraint(maybe_layout_tag) + + if fn in _maybe_layout_constraints: + return _maybe_layout_constraints[fn] + return None + + +def tag_to_layout_constraint( + tag: torch._C.Tag, +) -> Callable[..., tuple[Any, Any]] | None: + if tag == torch._C.Tag.needs_exact_strides: + return constrain_to_fake_tensors + if tag == torch._C.Tag.needs_contiguous_strides: # type: ignore[attr-defined] + return require_contiguous_strides + if tag == torch._C.Tag.needs_fixed_stride_order: + return constrain_to_fx_strides + if tag == torch._C.Tag.flexible_layout: + return None + raise AssertionError(f"Unknown layout constraint tag: {tag}") + + +def assert_nyi(cond: bool, msg: str) -> None: + if not cond: + raise NotImplementedError(f"inductor does not support {msg}") + + +def add_needs_realized_inputs(fn): + if isinstance(fn, (list, set, tuple, OrderedSet)): # noqa: set_linter + return [add_needs_realized_inputs(x) for x in fn] + needs_realized_inputs.add(fn) + if isinstance(fn, torch._ops.OpOverloadPacket): + needs_realized_inputs.update(fn.op_overloads()) + + +def add_layout_constraint( + fn: torch._ops.OpOverloadPacket | torch._ops.OpOverload, + constraint: Callable[..., tuple[Any, Any]], +) -> None: + if isinstance(fn, torch._ops.OpOverloadPacket): + for overload in fn.op_overloads(): + _maybe_layout_constraints[overload] = constraint + else: + _maybe_layout_constraints[fn] = constraint + + +add_needs_realized_inputs( + [ + aten.as_strided, + aten.as_strided_copy, + aten.avg_pool2d, + aten.avg_pool2d_backward, + aten.bmm, + aten.convolution, + aten.convolution_backward, + aten.max_pool2d_with_indices, + aten.max_pool3d_with_indices, + aten.max_pool2d_with_indices_backward, + aten.mm, + aten.upsample_nearest2d, + aten._upsample_nearest_exact2d, + aten._int_mm, + ] +) + +# TODO(jansel): ezyang says we won't need this in the future, try removing it +# based on https://github.com/pytorch/pytorch/blob/9e3eb329df8f701/c10/core/ScalarType.h#L28 +DTYPE_ID_LOOKUP = { + 0: torch.uint8, + 1: torch.int8, + 2: torch.int16, + 3: torch.int32, + 4: torch.int64, + 5: torch.float16, + 6: torch.float32, + 7: torch.float64, + 8: torch.complex32, + 9: torch.complex64, + 10: torch.complex32, + 11: torch.bool, + 15: torch.bfloat16, + # TODO(jansel): add quantized types? + # _(c10::qint8, QInt8) /* 12 */ + # _(c10::quint8, QUInt8) /* 13 */ + # _(c10::qint32, QInt32) /* 14 */ + # _(c10::quint4x2, QUInt4x2) /* 16 */ + # _(c10::quint2x4, QUInt2x4) /* 17 */ +} + + +def decode_dtype(dtype: int | torch.dtype) -> torch.dtype: + if not isinstance(dtype, int): + return dtype + if dtype not in DTYPE_ID_LOOKUP: + raise AssertionError(f"id {dtype} missing from DTYPE_ID_LOOKUP") + + dtype = DTYPE_ID_LOOKUP[dtype] + return dtype + + +def is_integer_type(x: Any) -> TypeGuard[TensorBox | IRNode | sympy.Expr | int]: + if isinstance(x, (TensorBox, IRNode)): + return is_integer_dtype(x.get_dtype()) or is_boolean_dtype(x.get_dtype()) + elif isinstance(x, sympy.Expr): + return x.is_integer is True # type: ignore[attr-defined] + else: + return isinstance(x, int) + + +def is_boolean_type(x: Any) -> TypeGuard[TensorBox | IRNode | bool]: + if isinstance(x, (TensorBox, IRNode)): + return is_boolean_dtype(x.get_dtype()) + else: + return isinstance(x, bool) + + +def get_promoted_dtype( + *args: Any, + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND, + return_compute_dtype: bool = False, +) -> torch.dtype: + def construct_input(inp: Any) -> Any: + if isinstance(inp, (Number, sympy.Basic)): + return inp + else: + dim = len(inp.get_size()) + # construct a tmp tensor to feed into torch.result_type + return torch.zeros([1] * dim, dtype=inp.get_dtype()) + + inps = [construct_input(arg) for arg in args] + compute_dtype, result_dtype = elementwise_dtypes( + *inps, type_promotion_kind=type_promotion_kind + ) + return compute_dtype if return_compute_dtype else result_dtype + + +def get_overloads(aten_fn): + if not isinstance(aten_fn, (list, tuple)): + aten_fn = [aten_fn] + else: + aten_fn = list(aten_fn) + + for fn in list(aten_fn): + if isinstance(fn, torch._ops.OpOverloadPacket): + for other_fn in fn.op_overloads(): + if other_fn not in lowerings: + aten_fn.append(other_fn) + + return aten_fn + + +def in_namespace( + op: Any | torch._ops.OpOverloadPacket | torch._ops.OpOverload, namespace: str +) -> bool: + if isinstance(op, torch._ops.OpOverloadPacket): + return namespace in op._qualified_op_name + elif isinstance(op, torch._ops.OpOverload): + return namespace in op.name() + return False + + +def maybe_copy_cpu_scalar(x: TensorBox, device: torch.device) -> TensorBox: + """ + Copy cpu scalar if doesn't not match with given `device` + """ + if not isinstance(x.data, ir.ReinterpretView) or has_free_unbacked_symbols( + x.get_size() + ): + return x + size = V.graph.sizevars.guarding_hints_or_throw(x.get_size()) + cur_device = x.get_device() + if ( + cur_device is not None + and cur_device.type == "cpu" + and cur_device != device + and (len(size) == 0 or (len(size) == 1 and size[0] == 1)) + ): + return TensorBox(ir.StorageBox(ir.DeviceCopy.create(x, cur_device, False))) + return x + + +def transform_args( + args: list[Any], + kwargs: dict[str, Any], + broadcast: bool, + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND | None, + convert_input_to_bool: bool, +) -> tuple[list[Any], dict[str, Any]]: + """ + Transforms arguments for broadcasting and type promotion + """ + + args_indices = [i for i, x in enumerate(args) if isinstance(x, TensorBox)] + kwargs_indices = [k for k, v in kwargs.items() if isinstance(v, TensorBox)] + # check that there's something to transform + if not args_indices and not kwargs_indices: + return args, kwargs + + if type_promotion_kind or convert_input_to_bool: + if convert_input_to_bool: + dtype = torch.bool + else: + # FIXME this is a crude approximation for promoting args + promoting_args = [ + a + for a in args + if isinstance(a, (Number, sympy.Basic)) or hasattr(a, "dtype") + ] + # only consider tensor kwargs for promotion, for now + promoting_args.extend(a for a in kwargs.values() if hasattr(a, "dtype")) + dtype = get_promoted_dtype( + *promoting_args, + type_promotion_kind=type_promotion_kind, # type: ignore[arg-type] + ) + + device = ( + args[args_indices[0]] if args_indices else kwargs[kwargs_indices[0]] + ).get_device() + + for i in args_indices: + args[i] = maybe_copy_cpu_scalar(args[i], device) + + for k in kwargs_indices: + kwargs[k] = maybe_copy_cpu_scalar(kwargs[k], device) + + # sometimes args are an immutable list so we can't mutate them + def promote(arg: Any) -> Any: + if isinstance(arg, TensorBox): + return to_dtype(arg, dtype) + elif isinstance(arg, ir.Constant): + return ir.Constant(value=arg.value, dtype=dtype, device=device) + else: + return arg + + args = [promote(a) for a in args] + kwargs = {k: promote(v) for k, v in kwargs.items()} + + if broadcast: + broadcasted = broadcast_tensors( + *list( + itertools.chain( + (args[i] for i in args_indices), + (kwargs[k] for k in kwargs_indices), + ) + ) + ) + size = list(broadcasted[0].get_size()) + + for i, x in zip(args_indices, broadcasted[: len(args_indices)]): + args[i] = x + for k, x in zip(kwargs_indices, broadcasted[len(args_indices) :]): + kwargs[k] = x + + for i in range(len(args)): + if isinstance(args[i], ir.Constant): + args[i] = ExpandView.create(args[i], size) + for k in kwargs: + if isinstance(kwargs[k], ir.Constant): + kwargs[k] = ExpandView.create(kwargs[k], size) + + return args, kwargs + + +def _register_foreach_lowering( + aten_fn: torch._ops.OpOverload, decomp_fn: Callable[..., Any] +) -> Callable[..., Any]: + """ + Add a foreach lowering to lowerings dict. + + Arguments: + aten_fn: torch.ops.aten.* fn we are lowering + decomp_fn: alternate implementation on our IR + broadcast: True to apply broadcasting to tensor inputs + type_promotion_kind: kind of type promotion applied to tensor inputs, `None` means no type promotion + convert_input_to_bool: some logical ops require inputs are converted to bool + """ + + @functools.wraps(decomp_fn) + def wrapped(*args: Any, **kwargs: Any) -> Any: + out = decomp_fn(*args, **kwargs) + validate_ir(out) + return out + + aten_fns = get_overloads(aten_fn) + foreach_ops.update(aten_fns) + lowerings.update(dict.fromkeys(aten_fns, wrapped)) + return wrapped + + +def _register_lowering( + aten_fn, + decomp_fn: Callable[..., Any], + broadcast: bool, + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND | None, + convert_input_to_bool: bool, + lowering_dict: dict[Callable[..., Any] | str, Callable[..., Any]], +): + """ + Add a lowering to lowerings dict + + Arguments: + aten_fn: torch.ops.aten.* fn we are lowering + decomp_fn: alternate implementation on our IR + broadcast: True to apply broadcasting to tensor inputs + type_promotion_kind: kind of type promotion applied to tensor inputs, `None` means no type promotion + convert_input_to_bool: some logical ops require inputs are converted to bool + """ + + @functools.wraps(decomp_fn) + def wrapped(*args, **kwargs): + args: list[Any] = list(args) + kwargs: dict[str, Any] = dict(kwargs) + unpacked = False + # TODO maybe we need to use pytrees here + if len(args) == 1 and isinstance(args[0], (list, tuple)): + unpacked = True + args = list(args[0]) + + if not all( + (fn in fallbacks or in_namespace(fn, "_c10d_functional")) for fn in aten_fn + ): + # explicitly assert for "out=" ops for better error messages + if any(x == "out" for x in kwargs): + raise AssertionError("out= ops aren't yet supported") + + args, kwargs = transform_args( + args, kwargs, broadcast, type_promotion_kind, convert_input_to_bool + ) + + if unpacked: + args = [args] + + out = decomp_fn(*args, **kwargs) + validate_ir(out) + + return out + + aten_fn = get_overloads(aten_fn) + + lowering_dict.update(dict.fromkeys(aten_fn, wrapped)) + return wrapped + + +def register_lowering( + aten_fn, + broadcast=False, + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND + | None = ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + convert_input_to_bool=False, + lowering_dict=lowerings, +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + """ + Shim to support decorator syntax. + """ + return functools.partial( + _register_lowering, + aten_fn, + broadcast=broadcast, + type_promotion_kind=type_promotion_kind, + convert_input_to_bool=convert_input_to_bool, + lowering_dict=lowering_dict, + ) + + +def broadcast_symbolic_shapes(a, b): + """ + Broadcasting logic based on symbolic shapes. + + We give the shapes 0 and 1 concrete values, while all other shapes + are symbolic sympy formulas. + """ + b = tuple(b) + if not a or a == b: + return b + + output = [] + for x, y in itertools.zip_longest(reversed(a), reversed(b), fillvalue=sympy.S.One): + if V.graph.sizevars.is_size_one_or_false(y): + output.append(x) + elif V.graph.sizevars.is_size_one_or_false(x): + output.append(y) + else: + V.graph.sizevars.check_equals(x, y) + if len(sympy.expand(y).free_symbols) < len(sympy.expand(x).free_symbols): + output.append(y) # prefer shorter formula + else: + output.append(x) + return tuple(reversed(output)) + + +def promote_constants( + inputs: Sequence[_T], + override_return_dtype: torch.dtype | None = None, + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND | None = None, + round_scalar_constants: bool = False, + round_scalars_to_tensor_dtype: bool = False, +) -> Sequence[_T | BaseView | BaseConstant]: + """Convert raw Python scalars and sympy expressions in inputs to IR constants. + + When a tensor input is present, scalars become Constants of the tensor's + dtype, broadcast to its size. For bf16/fp16 tensors, the scalar value is + additionally rounded to the tensor dtype to match eager kernels that cast + scalar operands to the common dtype: always for comparison ops + (override_return_dtype == torch.bool) and for callers passing + round_scalar_constants (e.g. remainder); on CPU and MPS only for ops + passing round_scalars_to_tensor_dtype (e.g. add/sub, whose CUDA eager + kernels keep scalars at opmath precision). + """ + if not (override_return_dtype is None or type_promotion_kind is None): + raise AssertionError( + "only one of override_return_dtype or type_promotion_kind may be given" + ) + + if override_return_dtype is None and type_promotion_kind is None: + type_promotion_kind = ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + + if not any(isinstance(x, (sympy.Basic, int, float)) for x in inputs): + return inputs + if all(isinstance(x, (int, float, sympy.Basic)) for x in inputs): + dtype = override_return_dtype or get_promoted_dtype( + *inputs, + # pyrefly: ignore [bad-argument-type] + type_promotion_kind=type_promotion_kind, + ) + + def const_func(x): + if isinstance(x, sympy.Basic): + return ir.IndexingConstant( + index=x, dtype=dtype, device=decode_device(None) + ) + else: + return ir.Constant(value=x, dtype=dtype, device=decode_device(None)) + + return [const_func(x) for x in inputs] + ex = next(x for x in inputs if isinstance(x, (TensorBox, ExpandView, ir.Constant))) + tensor_dtype = ex.get_dtype() + + # Round scalars to the tensor's dtype where eager does; see docstring. + if tensor_dtype in ( + torch.bfloat16, + torch.float16, + ) and ( + override_return_dtype == torch.bool + or round_scalar_constants + or ( + round_scalars_to_tensor_dtype + and ex.get_device_or_error().type in ("cpu", "mps") + ) + ): + _round_scalar = lambda v: torch.tensor(v, dtype=tensor_dtype).item() # noqa: E731 + else: + _round_scalar = lambda v: v # noqa: E731 + + out = [] + for x in inputs: + if isinstance(x, (int, float)): + out.append( + ExpandView.create( + ir.Constant( + value=_round_scalar(x), + dtype=tensor_dtype, + device=ex.get_device_or_error(), + ), + list(ex.get_size()), + ) + ) + elif isinstance(x, sympy.Basic): + out.append( + ExpandView.create( + IndexingConstant( + index=x, dtype=tensor_dtype, device=ex.get_device_or_error() + ), + list(ex.get_size()), + ) + ) + else: + out.append(x) + + return out + + +def _add_with_alpha_fma(a, b, alpha): + """Compute a + alpha * b using FMA for CUDA floating-point precision.""" + dtype = get_promoted_dtype( + a, + b, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + ) + a_loader = a.make_loader() + b_loader = b.make_loader() + + def inner_fn(idx): + a_val = a_loader(idx) + b_val = b_loader(idx) + if isinstance(alpha, sympy.Basic): + alpha_expr = ops.index_expr(alpha, dtype) + else: + alpha_expr = ops.constant(alpha, dtype) + return ops.fma(b_val, alpha_expr, a_val) + + return Pointwise.create( + device=a.get_device(), + dtype=dtype, + inner_fn=inner_fn, + ranges=a.get_size(), + ) + + +def _has_saved_lowp_output_use(node: torch.fx.Node | None) -> bool: + if node is None: + return False + + has_non_output_user = False + for user in node.users: + if user.op != "output": + has_non_output_user = True + break + + if not has_non_output_user: + return False + + for user in node.users: + if user.op != "output": + continue + + descs = user.meta.get("desc") + if descs is None: + continue + + output_values = pytree.tree_leaves(user.args[0]) + for output_value, desc in zip(output_values, descs): + if output_value is node and isinstance( + desc, _SAVED_FOR_BACKWARDS_OUTPUT_DESC_TYPES + ): + return True + + return False + + +def make_pointwise( + fn: Callable[..., Any], + override_return_dtype: torch.dtype | None = None, + override_device: torch.device | None = None, + override_fn_when_input_bool: Callable[..., Any] | None = None, + allow_alpha: bool = False, + use_fma_for_alpha: bool = False, + triton_fallback: Callable[..., _T] | None = None, + round_scalars_to_tensor_dtype: bool = False, +) -> Callable[..., TensorBox | _T]: + """Wraps a pointwise fn and returns a function representing the pointwise in + the define-by-run IR.""" + + def inner(*inputs: Any, alpha=None) -> TensorBox | _T: # noqa: docstring_linter + if triton_fallback is not None and any( + isinstance(inp, IRNode) and is_triton(inp) for inp in inputs + ): + if allow_alpha: # not implemented + raise AssertionError("expected: not allow_alpha") + return triton_fallback(*inputs) + + # pyrefly: ignore [bad-assignment] + inputs = promote_constants( + inputs, + override_return_dtype, + round_scalars_to_tensor_dtype=round_scalars_to_tensor_dtype, + ) + if allow_alpha: + if alpha is not None and alpha != 1: + # Use FMA for add-with-alpha on Triton GPU floating-point. + # Eager CUDA/ROCm computes a + alpha * b as fma(b, alpha, a). + if use_fma_for_alpha and isinstance(inputs[0], IRNode): + inp_device = inputs[0].get_device() + if ( + inputs[0].get_dtype().is_floating_point + and inp_device is not None + and inp_device.type == "cuda" + ): + return _add_with_alpha_fma(inputs[0], inputs[1], alpha) + + # pyrefly: ignore [bad-assignment] + inputs = list(inputs) + # pyrefly: ignore [unsupported-operation] + inputs[-1] = mul(inputs[-1], alpha) + else: + if alpha is not None: + raise AssertionError("expected: alpha is None") + loaders = [x.make_loader() for x in inputs] + ranges = inputs[0].get_size() + dtype = override_return_dtype or inputs[0].get_dtype() + + for other in inputs[1:]: + if not ( + isinstance(other, ir.BaseConstant) + or len(ranges) == len(other.get_size()) + ): + raise AssertionError(f"ndim mismatch {fn} {ranges} {other.get_size()}") + + # in tracing, we will annotate pointwise nodes that correspond to the output of + # a pointwise node that would have been run in eager. intermediary pointwise nodes + # during decompositions are not annotated. + low_pr_fp = (torch.bfloat16, torch.float16) + current_node = ( + getattr(V.graph, "current_node", None) if V.graph is not None else None + ) + emulate_precision_casts = ( + current_node is not None + and current_node.meta is not None + and current_node.meta.get("low_precision_pointwise_barrier", False) + ) + truncate_saved_output = ( + config.emulate_precision_casts_on_saved_tensors + and not emulate_precision_casts + and dtype in low_pr_fp + and _has_saved_lowp_output_use(current_node) + ) + emulate_output_cast = ( + emulate_precision_casts or truncate_saved_output + ) and dtype in low_pr_fp + + def inner_fn(index): + if len(index) != len(ranges): + raise AssertionError(f"wrong ndim {index} {ranges}") + if dtype == torch.bool and override_fn_when_input_bool is not None: + return override_fn_when_input_bool(*[load(index) for load in loaders]) + else: + inputs_loaded = [] + for inp_index, load in enumerate(loaders): + out = load(index) + inp_dtype = inputs[inp_index].get_dtype() + if emulate_precision_casts and inp_dtype in low_pr_fp: + downcast = ops.to_dtype(out, inp_dtype, use_compute_types=False) + out = ops.to_dtype(downcast, inp_dtype) + inputs_loaded.append(out) + + out = fn(*inputs_loaded) + if emulate_output_cast: + # fp16/bf16 kernels are computed in fp32. Casting down to fp16/bf16 here, + # then upcasting again, to emulate casts that eager would do. + downcast = ops.to_dtype(out, dtype, use_compute_types=False) + return ops.to_dtype(downcast, dtype) + return out + + if not override_device: + device = None + for i in inputs: + # pyrefly: ignore [missing-attribute] + if is_gpu(i.get_device().type): + device = i.get_device() + break + if not device: + device = inputs[0].get_device() + + # pyrefly: ignore [unbound-name] + device = override_device or device + + return Pointwise.create( + device=device, # type: ignore[arg-type] + dtype=dtype, + inner_fn=inner_fn, + ranges=ranges, + ) + + return inner + + +foreach_node_t = TypeVar("foreach_node_t", bound=IRNode) + + +def make_foreach_pointwise( + pw_fn: Callable[..., foreach_node_t], + allow_alpha: bool = False, + scalar_kwarg: str = "alpha", +) -> Callable[..., list[foreach_node_t]]: + def inner(*inputs: list[list[TensorBox]], alpha=1, value=1) -> list[foreach_node_t]: + # For ops like addcmul/addcdiv, the scalar `value` arrives as a + # positional arg (not keyword) due to the ATen schema. Extract it + # from the end of inputs if present. + # pyrefly: ignore [bad-assignment] + inputs = list(inputs) + if ( + scalar_kwarg == "value" + and inputs + and not isinstance(inputs[-1], (list, tuple)) + ): + # pyrefly: ignore [missing-attribute] + scalar_val = inputs.pop() + elif scalar_kwarg == "value": + scalar_val = value + else: + scalar_val = alpha + + realize_outputs = ( + len(V.graph.current_node.users) == 0 + or V.graph.current_node.target in inplace_foreach_ops + or cur_node_has_non_foreach_users() + ) + + a_list_input = None + for input in inputs: + if isinstance(input, (list, tuple)): + a_list_input = input + break + if a_list_input is None: + raise AssertionError("at least one input must be a list to a foreach op") + + # broadcast scalar inputs to match length of list inputs + broadcast_inputs = [] + for input in inputs: + if not isinstance(input, (list, tuple)): + broadcast_inputs.append([input] * len(a_list_input)) + else: + # pyrefly: ignore [bad-argument-type] + broadcast_inputs.append(input) + + groups = group_foreach_args(zip(*broadcast_inputs)) + + def apply_fn(args) -> foreach_node_t: + if allow_alpha: + return pw_fn(*args, **{scalar_kwarg: scalar_val}) + else: + return pw_fn(*args) + + return foreach_group_loop(groups, len(a_list_input), apply_fn, realize_outputs) + + return inner + + +def foreach_group_loop( + groups: Mapping[tuple[Any, bool], list[tuple[int, Any]]], + num_outputs: int, + apply_fn: Callable[..., foreach_node_t], + realize_outputs: bool, +) -> list[foreach_node_t]: + """ + Common loop over grouped foreach arguments. + + Args: + groups: Result of group_foreach_args - dict mapping (device, use_foreach) to groups + num_outputs: Number of outputs to produce + apply_fn: Function to apply to each set of args, returns the output + realize_outputs: Whether to realize outputs for foreach fusion + """ + outputs: list[foreach_node_t | None] = [None] * num_outputs + for (device, use_foreach), group in groups.items(): + operation_list: list[str] = [] + for output_ind, args in group: + output = apply_fn(args) + outputs[output_ind] = output + + if ( + V.graph.has_feature(device, BackendFeature.FOREACH) + and use_foreach + and realize_outputs + ): + output.realize() + operation_list.append(output.get_operation_name()) + + if operation_list: + V.graph.register_operation_list(operation_list) + + if not all(x is not None for x in outputs): + raise AssertionError("expected: all(x is not None for x in outputs)") + + return cast(list[foreach_node_t], outputs) + + +def to_dtype( + x: TensorBox, dtype: torch.dtype, copy: bool = False, use_compute_types: bool = True +): + src_dtype = x.get_dtype() + if src_dtype == dtype: + return clone(x) if copy else x + + def _to_dtype(x): + result = ops.to_dtype( + x, + dtype, + src_dtype=src_dtype, + use_compute_types=use_compute_types, + ) + low_pr_fp = (torch.bfloat16, torch.float16) + if not use_compute_types and dtype in low_pr_fp: + # Upcast back to compute type so fused consumers see a compute-type + # value. Without this, a raw low-precision value gets a redundant + # downcast from the consumer's input emulation. + result = ops.to_dtype(result, dtype) + return result + + return make_pointwise(_to_dtype, override_return_dtype=dtype)(x) + + +_FLOAT8_E8M0FNU_TO_FLOAT_DTYPES = ( + torch.float32, + torch.float64, + torch.float16, + torch.bfloat16, +) + + +def _float8_e8m0fnu_to_dtype(x: TensorBox, dtype: torch.dtype) -> TensorBox: + x_u8 = to_dtype_bitcast(x, torch.uint8) + + def _to_float(value): + # E8M0's exponent bits map directly to FP32; only encodings 0 and 255 + # need special handling for 2^-127 and NaN, respectively. + value_i32 = ops.to_dtype(value, torch.int32) + f32_bits = ops.bitwise_left_shift(value_i32, ops.constant(23, torch.int32)) + f32_bits = ops.where( + ops.eq(value, ops.constant(0, torch.uint8)), + ops.constant(0x00400000, torch.int32), + f32_bits, + ) + f32_bits = ops.where( + ops.eq(value, ops.constant(255, torch.uint8)), + ops.constant(0x7F800001, torch.int32), + f32_bits, + ) + dequant = ops.to_dtype_bitcast(f32_bits, torch.float32, src_dtype=torch.int32) + if dtype != torch.float32: + return ops.to_dtype(dequant, dtype) + return dequant + + return make_pointwise(_to_float, override_return_dtype=dtype)(x_u8) + + +@register_lowering(torch._higher_order_ops._foreach_map, type_promotion_kind=None) +def _foreach_map(subgraph, *args, **kwargs): + """ + This lowers an invocation of foreach_map + The way this works is that an arbitrary N-arg func is provided by the user, looped over by the + polyfill with the same semantics as a foreach op (a loop applying an n-ary function to n args) + and then traced into a subgraph by dynamo. + This code allows us to inline the subgraph into the main graph lowering using the PontwiseSubgraphLowering. + The graph outputs represent the vertically fused sequence of ops, and then register_operation_list + below registers the buffers as horizontally fuseable in the scheduler. + """ + from .subgraph_lowering import PointwiseSubgraphLowering + + inputs = args + + gm = subgraph.graph_module + pw_subgraph = PointwiseSubgraphLowering(gm, root_graph_lowering=V.graph) + with V.set_graph_handler(pw_subgraph): # type: ignore[arg-type] + pw_subgraph.run(*inputs) + + sub_outputs = pw_subgraph.graph_outputs + # group outputs by device and register as foreach + if not (sub_outputs): # mypy lol + raise AssertionError("expected: sub_outputs") + groups = group_foreach_args(sub_outputs) + + outputs = [None] * len(sub_outputs) + for (device, use_foreach), group in groups.items(): + operation_list: list[str] = [] + for ( + output_ind, + output, + ) in group: + outputs[output_ind] = output + + if V.graph.has_feature(device, BackendFeature.FOREACH) and use_foreach: + output.realize() + operation_list.append(output.get_operation_name()) + + if operation_list: + V.graph.register_operation_list(operation_list) + + if not (all(x is not None for x in outputs)): + raise AssertionError("expected: all(x is not None for x in outputs)") + return outputs + + +@register_lowering(prims.convert_element_type, type_promotion_kind=None) +def _convert_element_type(x: TensorBox, dtype: torch.dtype): + if dtype.is_complex or x.get_dtype().is_complex: + if x.get_size(): + # Decompose since aa aten fallback is more friendly for c++ codegen. + # This decomposition doesn't work for empty tensor, which needs more investigation. + dst = empty_like(x, dtype=dtype) + ir.InplaceCopyFallback.create(dst, x) + return dst + else: + return fallback_handler( + prims.convert_element_type.default, add_to_fallback_set=False + )(x, dtype) + src_dtype = x.get_dtype() + if src_dtype == torch.float8_e8m0fnu and dtype in _FLOAT8_E8M0FNU_TO_FLOAT_DTYPES: + return _float8_e8m0fnu_to_dtype(x, dtype) + + low_pr_fp = (torch.bfloat16, torch.float16) + # In precision-emulation mode, explicit lowp casts must materialize the + # storage dtype. Later pointwise barriers will widen from that rounded value. + use_compute_types = not ( + config.emulate_precision_casts + and (src_dtype in low_pr_fp or dtype in low_pr_fp) + ) + return to_dtype(x, dtype, copy=True, use_compute_types=use_compute_types) + + +def to_dtype_bitcast(x: TensorBox, dtype: torch.dtype, *, copy=False): + x_dtype = x.get_dtype() + if x_dtype == dtype: + return clone(x) if copy else x + + def _get_primitive_bitwidth(dtype): + if dtype.is_floating_point: + return torch.finfo(dtype).bits + elif dtype == torch.bool: + # torch.iinfo doesn't support bool; bools are stored as uint8 (8 bits) + return 8 + else: + return torch.iinfo(dtype).bits + + src_bits = _get_primitive_bitwidth(x_dtype) + dst_bits = _get_primitive_bitwidth(dtype) + if src_bits != dst_bits: + # fallback to aten eager implementation for differing bitwidths + x_cont = ir.ExternKernel.require_contiguous_strides(x) + return fallback_handler(aten.view.dtype)(x_cont, dtype) + else: + return TensorBox(DtypeView.create(x, dtype)) + + +@register_lowering(aten.view.dtype, type_promotion_kind=None) +def _view_dtype(x: TensorBox, dtype: torch.dtype): + if dtype.is_complex or x.get_dtype().is_complex: + return TensorBox.create( + ir.ComplexView.create(torch.ops.aten.view.dtype, x, dtype) + ) + return to_dtype_bitcast(x, dtype) + + +def to_device(x: TensorBox, device: torch.device, *, copy=False, non_blocking=False): + device = decode_device(device) + if x.get_device() == device: + return clone(x) if copy else x + return TensorBox.create(ir.DeviceCopy.create(x, device, non_blocking)) + + +@register_lowering(prims.device_put, type_promotion_kind=None) +def _device_put(x: TensorBox, device: torch.device, non_blocking=False): + return to_device(x, device, copy=True, non_blocking=non_blocking) + + +def register_pointwise( + aten_fn, + name=None, + broadcast=True, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + convert_input_to_bool=False, + override_return_dtype=None, + override_fn_when_input_bool=None, + allow_alpha=False, + use_fma_for_alpha=False, + triton_fallback=None, + round_scalars_to_tensor_dtype=False, +): + """A pointwise function that maps ops.{name} to inputs""" + name = name or aten_fn.__name__ + fn = ops_wrapper(name) + + register_op_dtype_propagation_rules( + name, type_promotion_kind, override_return_dtype + ) + + if override_fn_when_input_bool is not None: + override_fn_when_input_bool = ops_wrapper(override_fn_when_input_bool) + + fn = make_pointwise( + fn, + override_return_dtype=override_return_dtype, + override_fn_when_input_bool=override_fn_when_input_bool, + allow_alpha=allow_alpha, + use_fma_for_alpha=use_fma_for_alpha, + triton_fallback=triton_fallback, + round_scalars_to_tensor_dtype=round_scalars_to_tensor_dtype, + ) + fn = register_lowering( + aten_fn, + broadcast=broadcast, + type_promotion_kind=type_promotion_kind, + convert_input_to_bool=convert_input_to_bool, + )(fn) + + if hasattr(prims, name): + register_lowering( + getattr(prims, name), + type_promotion_kind=None, + convert_input_to_bool=convert_input_to_bool, + )(fn) + return fn + + +register_op_dtype_propagation_rules( + "ldexp", + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + override_return_dtype=None, +) + + +@register_lowering(aten.ldexp, broadcast=True, type_promotion_kind=None) +def ldexp_lowering(x: TensorBox, n: TensorBox): + ldexp_fn = ops_wrapper("ldexp") + + x_dtype = x.get_dtype() + n_dtype = n.get_dtype() + + x_is_float = x_dtype.is_floating_point + n_is_int = not n_dtype.is_floating_point and n_dtype != torch.bool + + if x_is_float and n_is_int: + # Use native ldexp + def compute_ldexp(x, n): + return ldexp_fn(x, n) + + return make_pointwise(compute_ldexp)(x, n) + else: + # Fall back to decomposition: x * pow(2, n) + out_dtype = torch.float32 if is_integer_type(x) else x_dtype + + def compute_fallback(x, n): + n_out_type = ops.to_dtype(n, out_dtype) + two = ops.constant(2.0, out_dtype) + pow_result = ops.pow(two, n_out_type) + return ops.mul(x, pow_result) + + return make_pointwise( + compute_fallback, + override_return_dtype=out_dtype, + )(x, n) + + +def register_frexp(): + """A pointwise function that maps ops.frexp to inputs""" + name = "frexp" + frexp = ops_wrapper("frexp") + + def frexp0(*args, **kwargs): + return frexp(*args, **kwargs)[0] # type: ignore[index] + + def frexp1(*args, **kwargs): + return frexp(*args, **kwargs)[1] # type: ignore[index] + + pw_fns = [ + make_pointwise(frexp0), + make_pointwise(frexp1, override_return_dtype=torch.int32), + ] + + def fn(*args, **kwargs): + return pw_fns[0](*args, **kwargs), pw_fns[1](*args, **kwargs) + + fn = register_lowering( + aten.frexp, + )(fn) + + if hasattr(prims, name): + register_lowering( + getattr(prims, name), + type_promotion_kind=None, + )(fn) + return fn + + +register_frexp() + + +def register_foreach_pointwise( + aten_fn, + pointwise_lowering_fn, + allow_alpha=False, + scalar_kwarg="alpha", +): + fn = make_foreach_pointwise( + pointwise_lowering_fn, allow_alpha=allow_alpha, scalar_kwarg=scalar_kwarg + ) + fn = _register_foreach_lowering(aten_fn, fn) + return fn + + +@register_lowering(aten.where, broadcast=False, type_promotion_kind=None) +def where(cond, a, b): + def fn(*args): + return ops.where(*args) + + if isinstance(a, (float, int)): + a = constant_like(a)(b) + if isinstance(b, (float, int)): + b = constant_like(b)(a) + + args = [cond, a, b] + dtype = get_promoted_dtype( + args[1], args[2], type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + indices = [i for i, x in enumerate(args) if isinstance(x, TensorBox)] + for i, x in zip(indices, broadcast_tensors(*[args[i] for i in indices])): + args[i] = x + for i in range(len(args)): + if isinstance(args[i], ir.Constant): + args[i] = ExpandView.create(args[i], list(args[indices[0]].get_size())) + return make_pointwise(fn, override_return_dtype=dtype)( + args[0], to_dtype(args[1], dtype), to_dtype(args[2], dtype) + ) + + +@register_lowering(aten.broadcast_tensors, broadcast=False, type_promotion_kind=None) +def broadcast_tensors(*inputs): + if len(inputs) == 1: + if isinstance(inputs[0], (list, tuple)): + return broadcast_tensors(*inputs[0]) + return inputs + target: list[sympy.Expr] = functools.reduce( + broadcast_symbolic_shapes, (x.get_size() for x in inputs), () + ) + outputs = [] + for x in inputs: + if (sizes := tuple(x.get_size())) == target: + pass + + elif len(sizes) != len(target) or any( + V.graph.sizevars.is_size_one_or_false(a) + != V.graph.sizevars.is_size_one_or_false(b) + for a, b in zip(sizes, target) + ): + x = expand(x, target) + outputs.append(x) + return outputs + + +@register_lowering([aten.alias, aten.detach, aten.detach_, aten.lift, prims.view_of]) +def nop(x): + return x # AOT autograd handles this for us + + +if hasattr(aten, "lift_fresh"): + register_lowering(aten.lift_fresh)(nop) + + +@register_lowering(aten.squeeze, type_promotion_kind=None) +def squeeze(x, dim=None): + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if dim is None: + return TensorBox(SqueezeView.create(x.data)) + + dim = ( + V.graph.sizevars.guard_int(dim) + if isinstance(dim, (int, sympy.Expr)) + else tuple(V.graph.sizevars.guard_int(d) for d in dim) + ) + dim = canonicalize_dims(len(x.get_size()), dim) # type: ignore[call-overload] + dims = OrderedSet((dim,) if not isinstance(dim, tuple) else dim) + + new_shape = [] + for d, s in enumerate(x.get_size()): + if not (d in dims and V.graph.sizevars.guard_or_false(sympy.Eq(s, 1))): + new_shape.append(s) + + # squeeze does nothing if the size isn't 1 + return view(x, new_shape) if new_shape != x.get_size() else x + + +@register_lowering(aten.squeeze_copy, type_promotion_kind=None) +def squeeze_copy(x, dim=None): + return clone(squeeze(x, dim)) + + +@register_lowering([aten.squeeze_]) +def squeeze_(x, dim=None): + val = squeeze(x, dim) + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if not (isinstance(val, TensorBox)): + raise AssertionError("expected: isinstance(val, TensorBox)") + x.data = val.data + return x + + +@register_lowering(aten.isinf) +def isinf(x): + if is_integer_type(x): + return full_like(x, False, dtype=torch.bool) + fn = ops_wrapper("isinf") + return make_pointwise(fn, override_return_dtype=torch.bool)(x) + + +@register_lowering(aten.isnan) +def isnan(x): + if is_integer_type(x): + return full_like(x, False, dtype=torch.bool) + fn = ops_wrapper("isnan") + return make_pointwise(fn, override_return_dtype=torch.bool)(x) + + +@register_lowering(aten.ceil) +def ceil(x): + if is_integer_type(x): + return clone(x) + fn = ops_wrapper("ceil") + return make_pointwise(fn)(x) + + +@register_lowering(aten.floor) +def floor(x): + if is_integer_type(x): + return clone(x) + fn = ops_wrapper("floor") + return make_pointwise(fn)(x) + + +@register_lowering(aten.round.default) +def round(x): + if is_integer_type(x): + return clone(x) + else: + fn = ops_wrapper("round") + return make_pointwise(fn)(x) + + +@register_lowering(aten.trunc) +def trunc(x): + if is_integer_type(x): + return clone(x) + fn = ops_wrapper("trunc") + return make_pointwise(fn)(x) + + +@register_lowering(aten.expand, type_promotion_kind=None) +def expand(x, sizes, *, implicit=False): + # `implicit` is autograd-internal metadata (see aten::expand schema); it + # does not affect the produced tensor, so the lowering ignores it. Without + # this kwarg the lowering rejects graphs produced by dynamo autograd where + # aten.expand.default is emitted with implicit=False. + del implicit + (x,) = promote_constants([x]) + if isinstance(x, ir.BaseConstant): + return ExpandView.create(x, tuple(sizes)) + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if not (isinstance(sizes, (list, tuple))): + raise AssertionError("expected: isinstance(sizes, (list, tuple))") + if tuple(x.get_size()) == tuple(sizes): + return x + + if not free_unbacked_symbols(x.get_size()): + x_size_product = V.graph.sizevars.guarding_hint_or_throw( + sympy_product(x.get_size()) + ) + # TODO: It would be better to realize the input if any of its sizes + # are unbacked, because typically the size will be non-zero. However, + # this cannot be done directly as below as we'll choke on the size_hint + # here + if x_size_product > 0 and not free_unbacked_symbols(sizes): + # Broadcast loop reuse is not graph fanout; keep the graph-fanout + # read-count heuristic from materializing cheap expanded producers. + # In deterministic modes, preserve the old materialization boundary + # since fusing through expanded inputs can change reduction numerics. + x.mark_reuse( + V.graph.sizevars.guarding_hint_or_throw(sympy_product(sizes)) + // x_size_product, + graph_reuse=config.deterministic + or torch.are_deterministic_algorithms_enabled(), + ) + return TensorBox(ExpandView.create(x.data, tuple(sizes))) + + +@register_lowering(prims.broadcast_in_dim, type_promotion_kind=None) +def broadcast_in_dim(a, shape, broadcast_dimensions): + s = list(shape) + for broadcast_dimension in broadcast_dimensions: + s[broadcast_dimension] = -1 + + v = a + for idx, x in enumerate(s): + if x != -1: + v = unsqueeze(v, idx) + + return expand(v, shape) + + +@register_lowering(aten.expand_as, type_promotion_kind=None) +def expand_as(x, y): + return expand(x, y.get_size()) + + +@register_lowering(aten.repeat) +def repeat(x, repeats): + old_size = list(x.get_size()) + if len(repeats) > len(old_size): + old_size = [sympy.S.One] * (len(repeats) - len(old_size)) + old_size + x = view(x, list(old_size)) + if len(repeats) != len(x.get_size()): + raise AssertionError("expected: len(repeats) == len(x.get_size())") + + new_size = list(x.get_size()) + + zero_tensor = False + for i in range(len(repeats)): + if repeats[i] == 0: + zero_tensor = True + new_size[i] = new_size[i] * repeats[i] + + if zero_tensor: + return empty(new_size, dtype=x.get_dtype(), device=x.get_device()) + if all((a == 1 or b == 1) for a, b in zip(repeats, old_size)): + return clone(expand(x, new_size)) + + x_loader: Callable[[Any], Any] + + def inner_fn(index): + if len(index) != len(repeats): + raise AssertionError("expected: len(index) == len(repeats)") + index = list(index) + for i in range(len(repeats)): + if repeats[i] != 1: + if old_size[i] == 1: + index[i] = sympy.S.Zero + else: + index[i] = ModularIndexing(index[i], 1, old_size[i]) + return x_loader(index) + + # TODO Laith is there better check + if not free_unbacked_symbols(old_size) and not free_unbacked_symbols(new_size): + old_size_product = V.graph.sizevars.guarding_hint_or_throw( + sympy_product(old_size) + ) + if old_size_product > 0: + # maybe realize the input but skip for unbacked symints since it'll + # choke on the size hint. + x.mark_reuse( + V.graph.sizevars.guarding_hint_or_throw(sympy_product(new_size)) + // old_size_product + ) + + x_loader = x.make_loader() + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=inner_fn, + ranges=list(new_size), + ) + + +@register_lowering(aten._unsafe_view, type_promotion_kind=None) +@register_lowering(aten.view, type_promotion_kind=None) +@register_lowering(aten.reshape, type_promotion_kind=None) +def view(x: ir.IRNode, sizes: Sequence[sympy.Expr]) -> TensorBox: + # post-mm_args operands are raw ReinterpretView/StorageBox nodes, and taking + # .data on those would drop the view itself + data = x.data if isinstance(x, TensorBox) else x + return TensorBox(View.create(data, sizes)) + + +@register_lowering(aten.permute, type_promotion_kind=None) +def permute(x, dims): + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if not (isinstance(dims, (list, tuple))): + raise AssertionError("expected: isinstance(dims, (list, tuple))") + return TensorBox(PermuteView.create(x.data, tuple(dims))) + + +# Note: logic in this function need to be always synchronized with +# slice_forward in fake implementation. +def _register_unbacked_slice_size_bindings(dim, start, end, step, size): + """Register DynamicSliceSize for any unbacked size bindings on the current FX node. + + Unbacked symbols may have been allocated at trace time of the slice + that inductor must define so the assertion + new_unbacked_defs >= renamed_unbacked_bindings passes in run_node. + + Returns (sym_size, sym_storage) parsed from the bindings, or (None, None). + """ + from torch.fx.experimental.symbolic_shapes import ( + CallMethodKey, + resolve_unbacked_bindings, + ) + + # current_node may be None when slice_ is called from template rendering + # (e.g. cpp_template_kernel.slice_nd) rather than FX graph lowering. + current_node = V.graph.current_node + node_unbacked_bindings = resolve_unbacked_bindings( + V.graph.sizevars.shape_env, + current_node.meta.get("unbacked_bindings", {}) + if current_node is not None + else {}, + ) + sym_size, sym_storage = None, None + if node_unbacked_bindings: + if len(node_unbacked_bindings) > 2: + raise AssertionError(node_unbacked_bindings) + for sym, keypath in node_unbacked_bindings.items(): + if keypath == (CallMethodKey("size"), pytree.SequenceKey(dim)): + sym_size = sym + elif keypath == (CallMethodKey("storage_offset"),): + sym_storage = sym + if sym_size is not None: + b_size = ir.DynamicSliceSize(sym_size, start, end, step, size) + b_size.name = V.graph.register_buffer(b_size) + V.graph.register_operation(b_size) + # NOTE: storage_offset registration is not handled here — it is only + # needed in the ambiguous (unbacked start/end) path, where it is + # handled via DynamicSelectStorageOffset after this helper returns. + return sym_size, sym_storage + + +def _compute_slice_index(index, size, default=None): + if index is None: + return default + + guard = V.graph.sizevars.guard_or_false + index = sympy.expand(index) + size = sympy.expand(size) + if guard(sympy.And(sympy.Ge(index, 0), sympy.Le(index, size))): + return index + elif guard(sympy.And(sympy.Lt(index, 0), sympy.Ge(index, -size))): + return index + size + elif guard(sympy.Gt(index, size)): + return size + elif guard(sympy.Lt(index, -size)): + return 0 + elif guard(sympy.Ge(index, 0)): + # If index >= 0, the resolved index is at most min(index, size). + return Min(index, size) + elif guard(sympy.Lt(index, 0)): + # If index < 0, wrap and clamp: the resolved index is at least 0. + return Max(index + size, 0) + return None + + +def _clamp_slice_end_to_start(end, start): + if V.graph.sizevars.statically_known_geq(end, start): + return end + if V.graph.sizevars.statically_known_leq(end, start): + return start + return Max(end, start) + + +@register_lowering(aten.slice, type_promotion_kind=None) +def slice_(x, dim=0, start=0, end=sys.maxsize, step=1, clamp=True): + """ + Lowers a slice call, creating ExternKernels for the output size & storage offset symbols, + if the indices are unbacked and appropriate semantics aren't known. + If they are known (indices are static/backed/unbacked with info), a SliceView is created. + """ + + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + dim = _validate_dim(x, dim, 0) + size = x.get_size()[dim] + step = sympy.expand(step) + if not (isinstance(step, sympy.Expr) or step > 0): + raise AssertionError(step) + + # maybe apply slice optimization + try: + if ( + start == 0 + and V.graph.sizevars.statically_known_leq(size, end) + and step == 1 + ): + _, sym_storage = _register_unbacked_slice_size_bindings( + dim, start, end, step, size + ) + if sym_storage is not None: + raise AssertionError( + "Unexpected storage_offset unbacked binding for no-op slice" + ) + return x + except TypeError: + pass + + start_index, end_index = None, None + # ambiguous_slice=False means we know what semantics this slice call follows, + # and don't need to generate an extern kernel to represent the output size. + # This is assumed True for clamp=False + # (meant to follow standard indexing semantics: 0 <= index < size) + ambiguous_slice = clamp + if ambiguous_slice: + start_index = _compute_slice_index(start, size, 0) + # Special case: if end is maxsize (unbounded), use size directly + # This matches the logic in fake_impls.py + if end is not None and V.graph.sizevars.statically_known_equals( + end, sys.maxsize + ): + end_index = size + else: + end_index = _compute_slice_index(end, size, size) + if start_index is not None and end_index is not None: + start, end = start_index, end_index + ambiguous_slice = False + + if not ambiguous_slice: + _, sym_storage = _register_unbacked_slice_size_bindings( + dim, start, end, step, size + ) + if sym_storage is not None: + raise AssertionError( + "Unexpected storage_offset unbacked binding when both " + "start and end indices are resolved" + ) + + return TensorBox( + ir.SliceView.create(x.data, dim, start, end, step, clamp=clamp) + ) # go to SliceView/ReinterpretView + + # unbacked territory: unbacked start / end + if not (clamp): + raise AssertionError("expected: clamp") + if not (start_index is None or end_index is None): + raise AssertionError("expected: start_index is None or end_index is None") + sym_size, sym_storage = _register_unbacked_slice_size_bindings( + dim, start, end, step, x.get_size()[dim] + ) + if sym_size is None: + raise AssertionError("expected: sym_size is not None") + + if x.maybe_get_layout() is None: + # realize tensor before accessing layout + x.realize() + stride = x.maybe_get_stride() + + if start_index is not None: + # we shouldn't have allocated storage offset symbol if start index was determinable + if sym_storage is not None: + raise AssertionError("expected: sym_storage is None") + if stride is None: + return TensorBox( + ir.SliceView.create_with_size(x.data, dim, start_index, sym_size, step) + ) + new_storage_offset = x.get_layout().offset + start_index * stride[dim] + else: + if stride is None: + raise AssertionError("expected: stride is not None") + b_storage = ir.DynamicSelectStorageOffset( + sym_storage, + start, + x.get_layout().offset, + stride[dim], + x.get_size()[dim], + clamp=True, + ) + b_storage.name = V.graph.register_buffer(b_storage) + V.graph.register_operation(b_storage) + new_storage_offset = sym_storage + + new_sizes = list(x.get_size()) + new_strides = list(stride) + new_sizes[dim] = sym_size + new_strides[dim] *= step + return as_strided( + x, + new_sizes, + new_strides, + new_storage_offset, + storage_offset_relative_to_input_storage=False, + ) + + +@register_lowering(aten.as_strided, type_promotion_kind=None) +def as_strided( + x, + size, + stride, + storage_offset=None, + *, + storage_offset_relative_to_input_storage=True, +): + explicit_storage_offset = ( + storage_offset is not None and storage_offset_relative_to_input_storage + ) + new_device = None + new_dtype = None + if isinstance(x, TensorBox) and isinstance(x.data, ir.BaseView): + # Note: Merging views + # When we use as_strided, we can rewrite the size/stride/offset + # of the incoming buffer x. If x is a view, we would overwrite + # its metadata. Except for dtype, which we need to propagate. + + # Technically device is not needed because it is not possible + # to have a cross-device view today. + new_device = x.get_device() + new_dtype = x.dtype + if storage_offset is None and x.maybe_get_layout() is not None: + storage_offset = x.get_layout().offset + x = x.data.unwrap_view() + x.realize() + if not ir.is_storage_and_layout(x): + raise NotImplementedError(f"unrealized as_strided({x}, ...)") + storage, old_layout = ir.as_storage_and_layout(x) + storage_offset = ( + convert_symint_to_expr(storage_offset) if storage_offset is not None else 0 + ) + storage_data = storage.data if isinstance(storage, ir.StorageBox) else storage + if explicit_storage_offset and isinstance(storage_data, ir.InputBuffer): + # Runtime graph input pointers already include the input tensor's + # storage_offset(), but explicit as_strided offsets are storage-relative. + storage_offset = sympy.expand( + storage_offset + - V.graph.graph_input_storage_offsets.get(storage_data.get_name(), 0) + ) + new_layout = ir.FixedLayout( + new_device if new_device else old_layout.device, + new_dtype if new_dtype else old_layout.dtype, + [sympy.expand(s) for s in size], + [sympy.expand(s) for s in stride], + sympy.expand(storage_offset), + ) + return TensorBox(ir.ReinterpretView(data=storage, layout=new_layout)) + + +@register_lowering(aten.as_strided_, type_promotion_kind=None) +def as_strided_(x, size, stride, storage_offset=None): + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + x.data = as_strided(x, size, stride, storage_offset).data + return x + + +@register_lowering(aten.as_strided_copy, type_promotion_kind=None) +def as_strided_copy(x, size, stride, storage_offset=None): + result = as_strided(x, size, stride, storage_offset) + return clone(result) + + +def pointwise_cat(inputs, dim=0): + # (inclusive, exclusive) + inputs_ranges: list[tuple[sympy.Expr, sympy.Expr]] = [] + prev_end = 0 + for inp in inputs: + inputs_ranges.append((prev_end, prev_end + inp.get_size()[dim])) # type: ignore[arg-type] + prev_end = inputs_ranges[-1][-1] # type: ignore[assignment] + + inputs_loaders = [inp.make_loader() for inp in inputs] + + def inner_fn(idx): + idx_dim = ops.index_expr(idx[dim], torch.int64) + + masks = [] + masked_loads = [] + for i in range(len(inputs)): + start = ( + ops.constant(0, torch.int64) + if i == 0 + else ops.index_expr(inputs_ranges[i][0], torch.int64) + ) + end = ops.index_expr(inputs_ranges[i][1], torch.int64) + + start_cond = ops.ge(idx_dim, start) + end_cond = ops.lt(idx_dim, end) + if i == 0: + mask = end_cond + elif i == len(inputs) - 1: + mask = start_cond + else: + mask = ops.and_(start_cond, end_cond) + + masks.append(mask) + idx_load = list(idx) + + # if we're concatting [4], [2] + # when we index the second tensor for 5 we want to index 5 - 4 + # Use Identity to prevent expansion of index * stride to keep expression + # in same int bitwidth as shape + idx_load[dim] = Identity(idx_load[dim] - inputs_ranges[i][0]) + + masked_loads.append( + ops.masked( + mask, + lambda: inputs_loaders[i](idx_load), + 0.0, # this value should be unused + ), + ) + + next_val = masked_loads[-1] + for i in range((len(inputs)) - 2, -1, -1): + next_val = ops.where( + masks[i], + masked_loads[i], + next_val, + ) + return next_val + + new_size = list(inputs[0].get_size()) + new_size[dim] = inputs_ranges[-1][-1] + + return Pointwise.create( + device=inputs[0].get_device(), + dtype=inputs[0].get_dtype(), + inner_fn=inner_fn, + ranges=new_size, + ) + + +@register_lowering(quantized_decomposed.quantize_per_channel, type_promotion_kind=None) +def quantized_decomposed_quantize_per_channel( + input: TensorBox, + scales: TensorBox, + zero_points: TensorBox, + axis: int, + quant_min: int, + quant_max: int, + dtype: torch.dtype, +) -> TensorBox: + if len(scales.get_size()) != 1: + raise AssertionError("expect scales 1 dim") + if len(zero_points.get_size()) != 1: + raise AssertionError("expect zero_points 1 dim") + + if input.get_dtype() == torch.bfloat16: + input = to_dtype(input, torch.float32) + if input.get_dtype() != torch.float32: + raise AssertionError( + f"Expecting input to have dtype torch.float32, but got dtype: {input.get_dtype()}" + ) + if axis >= len(input.get_size()): + raise AssertionError(f"Expecting axis to be < {len(input.get_size())}") + + input_loader = input.make_loader() + scales_loader = scales.make_loader() + zero_points_loader = zero_points.make_loader() + + def inner_fn(idx): + channel_idx = (idx[axis],) + + input = input_loader(idx) + scale = scales_loader(channel_idx) + zero_point = zero_points_loader(channel_idx) + qmin, qmax = _create_constants(quant_min, quant_max, dtype=torch.float32) + + if scales.dtype != torch.float32: + scale = ops.to_dtype(scale, torch.float32) + if zero_points.dtype != torch.int32: + zero_point = ops.to_dtype(zero_point, torch.int32) + inv_scale = ops.reciprocal(scale) + val = ops.round(input * inv_scale) + zero_point + clamped = ops.maximum(qmin, ops.minimum(qmax, val)) + return ops.to_dtype(clamped, dtype) + + return Pointwise.create( + device=input.get_device(), + dtype=dtype, + inner_fn=inner_fn, + ranges=input.get_size(), + ) + + +def _assert_async(cond, msg): + cond.realize() + cond = to_dtype(cond, torch.bool) + + def inner_fn(index): + with ir.ComputedBuffer.force_realize(): + return ops.device_assert_async(cond.make_loader()(index), msg) + + assertion_op = Pointwise.create( + device=cond.get_device(), + dtype=cond.get_dtype(), + inner_fn=inner_fn, + ranges=list(cond.get_size()), + ) + assertion_op.realize() + return assertion_op + + +@register_lowering(aten._assert_async.msg) +def lower_assert_async(cond, msg): + return _assert_async(cond, msg) + + +@register_lowering(aten._functional_assert_async.msg) +def lower_assert_functional_async(cond, msg): + return _assert_async(cond, msg) + + +@register_lowering( + quantized_decomposed.dequantize_per_channel, type_promotion_kind=None +) +def quantized_decomposed_dequantize_per_channel( + input: TensorBox, + scales: TensorBox, + zero_points: TensorBox, + axis: int, + quant_min: int, + quant_max: int, + dtype: torch.dtype, + *, + out_dtype: torch.dtype | None = None, +) -> TensorBox: + if len(scales.get_size()) != 1: + raise AssertionError("expect scales 1 dim") + if len(zero_points.get_size()) != 1: + raise AssertionError("expect zero_points 1 dim") + if input.get_dtype() != dtype: + raise AssertionError( + f"Expecting input to have dtype {dtype}, but got dtype: {input.get_dtype()}" + ) + if axis >= len(input.get_size()): + raise AssertionError(f"Expecting axis to be < {len(input.get_size())}") + + if out_dtype is None: + out_dtype = torch.float32 + + input_loader = input.make_loader() + scales_loader = scales.make_loader() + zero_points_loader = zero_points.make_loader() + + def inner_fn(idx): + channel_idx = (idx[axis],) + + input = input_loader(idx) + scale = scales_loader(channel_idx) + zero_point = zero_points_loader(channel_idx) + + if scales.dtype != torch.float32: + scale = ops.to_dtype(scale, torch.float32) + if zero_points.dtype != torch.float32: + zero_point = ops.to_dtype(zero_point, torch.float32) + val = ops.sub(ops.to_dtype(input, torch.float32), zero_point) * scale + val = ops.to_dtype(val, out_dtype) + return val + + return Pointwise.create( + device=input.get_device(), + dtype=out_dtype, + inner_fn=inner_fn, + ranges=input.get_size(), + ) + + +@register_lowering( + quantized_decomposed.quantize_per_tensor.default, type_promotion_kind=None +) +def quantized_decomposed_quantize_per_tensor_default( + input: TensorBox, + scale: float, + zero_point: int, + quant_min: int, + quant_max: int, + dtype: torch.dtype, +) -> TensorBox: + if input.get_dtype() == torch.bfloat16: + input = to_dtype(input, torch.float32) + if input.get_dtype() != torch.float32: + raise AssertionError( + f"Expecting input to have dtype torch.float32, but got dtype: {input.get_dtype()}" + ) + + input_loader = input.make_loader() + + def inner_fn(idx, scale, zero_point): + input = input_loader(idx) + inv_scale, zero_point = _create_constants( + 1.0 / scale, zero_point, dtype=torch.float32 + ) + val = ops.round(input * inv_scale) + zero_point + qmin, qmax = _create_constants(quant_min, quant_max, dtype=torch.float32) + clamped = ops.minimum(ops.maximum(val, qmin), qmax) + return ops.to_dtype(clamped, dtype) + + return Pointwise.create( + device=input.get_device(), + dtype=dtype, + inner_fn=functools.partial( + inner_fn, scale=float(scale), zero_point=int(zero_point) + ), + ranges=input.get_size(), + ) + + +@register_lowering( + quantized_decomposed.dequantize_per_tensor.default, type_promotion_kind=None +) +def quantized_decomposed_dequantize_per_tensor_default( + input: TensorBox, + scale: float, + zero_point: int, + quant_min: int, + quant_max: int, + dtype: torch.dtype, + *, + out_dtype: torch.dtype | None = None, +) -> TensorBox: + if input.get_dtype() != dtype: + raise AssertionError( + f"Expecting input to have dtype {dtype}, but got dtype: {input.get_dtype()}" + ) + + if out_dtype is None: + out_dtype = torch.float32 + + input_loader = input.make_loader() + + def inner_fn(idx, scale, zero_point): + input = input_loader(idx) + scale, zero_point = _create_constants(scale, zero_point, dtype=torch.float32) + val = ops.sub(ops.to_dtype(input, torch.float32), zero_point) * scale + val = ops.to_dtype(val, out_dtype) + return val + + return Pointwise.create( + device=input.get_device(), + dtype=out_dtype, + inner_fn=functools.partial( + inner_fn, scale=float(scale), zero_point=int(zero_point) + ), + ranges=input.get_size(), + ) + + +@register_lowering( + quantized_decomposed.quantize_per_tensor.tensor, type_promotion_kind=None +) +def quantized_decomposed_quantize_per_tensor_tensor( + input: TensorBox, + scale: TensorBox, + zero_point: TensorBox, + quant_min: int, + quant_max: int, + dtype: torch.dtype, +) -> TensorBox: + if input.get_dtype() == torch.bfloat16: + input = to_dtype(input, torch.float32) + if input.get_dtype() != torch.float32: + raise AssertionError( + f"Expecting input to have dtype torch.float32, but got dtype: {input.get_dtype()}" + ) + if not ( + len(scale.get_size()) == 0 + or (len(scale.get_size()) == 1 and scale.get_size()[0] == 1) + ): + raise AssertionError("expect scale as scalar tensor") + if not ( + len(zero_point.get_size()) == 0 + or (len(zero_point.get_size()) == 1 and zero_point.get_size()[0] == 1) + ): + raise AssertionError("expect zero_point as scalar tensor") + + input_loader = input.make_loader() + scale_loader = scale.make_loader() + zero_point_loader = zero_point.make_loader() + + device = input.get_device() + + def inner_fn(idx): + input = input_loader(idx) + _scale = scale_loader((0,) if len(scale.get_size()) == 1 else ()) + _zero_point = zero_point_loader((0,) if len(scale.get_size()) == 1 else ()) + if scale.dtype != torch.float32: + _scale = ops.to_dtype(_scale, torch.float32) + if zero_point.dtype != torch.float32: + _zero_point = ops.to_dtype(_zero_point, torch.float32) + if device and device.type == "cpu": + val = ops.fma(input, ops.reciprocal(_scale), _zero_point) + return ops.round_to_int(val, dtype) + val = ops.round(input * ops.reciprocal(_scale)) + _zero_point + qmin, qmax = _create_constants(quant_min, quant_max, dtype=torch.float32) + clamped = ops.minimum(ops.maximum(val, qmin), qmax) + return ops.to_dtype(clamped, dtype) + + return Pointwise.create( + device=input.get_device(), + dtype=dtype, + inner_fn=inner_fn, + ranges=input.get_size(), + ) + + +@register_lowering( + quantized_decomposed.dequantize_per_tensor.tensor, type_promotion_kind=None +) +def quantized_decomposed_dequantize_per_tensor_tensor( + input: TensorBox, + scale: TensorBox, + zero_point: TensorBox, + quant_min: int, + quant_max: int, + dtype: torch.dtype, + *, + out_dtype: torch.dtype | None = None, +) -> TensorBox: + if not ( + len(scale.get_size()) == 0 + or (len(scale.get_size()) == 1 and scale.get_size()[0] == 1) + ): + raise AssertionError("expect scale as scalar tensor") + if not ( + len(zero_point.get_size()) == 0 + or (len(zero_point.get_size()) == 1 and zero_point.get_size()[0] == 1) + ): + raise AssertionError("expect zero_point as scalar tensor") + if input.get_dtype() != dtype: + raise AssertionError( + f"Expecting input to have dtype {dtype}, but got dtype: {input.get_dtype()}" + ) + + if out_dtype is None: + out_dtype = torch.float32 + + input_loader = input.make_loader() + scale_loader = scale.make_loader() + zero_point_loader = zero_point.make_loader() + + def inner_fn(idx): + input = input_loader(idx) + _scale = scale_loader((0,) if len(scale.get_size()) == 1 else ()) + _zero_point = zero_point_loader((0,) if len(scale.get_size()) == 1 else ()) + if scale.dtype != torch.float32: + _scale = ops.to_dtype(_scale, torch.float32) + if zero_point.dtype != torch.float32: + _zero_point = ops.to_dtype(_zero_point, torch.float32) + val = ops.sub(ops.to_dtype(input, torch.float32), _zero_point) * _scale + val = ops.to_dtype(val, out_dtype) + return val + + return Pointwise.create( + device=input.get_device(), + dtype=out_dtype, + inner_fn=inner_fn, + ranges=input.get_size(), + ) + + +def _cat_inputs_recombine_reduction(inputs: list[TensorBox], dim: int) -> str | None: + """If all cat inputs share a common upstream reduction buffer whose + only consumers feed into this cat, return its name so it can be + excluded from the can_fuse_reduction check. + + Checks common reads for an IR reduction whose numel matches the cat + output, then verifies via FX origins that all of the reduction's + consumers feed into the cat inputs.""" + if len(inputs) < 2: + return None + + common_reads = inputs[0].get_read_names() + for inp in inputs[1:]: + common_reads = common_reads & inp.get_read_names() + if not common_reads: + return None + + # Find a common read that is an IR reduction buffer whose input + # numel matches the cat output numel. + cat_out_numel = convert_symint_to_expr(V.graph.current_node.meta["val"].numel()) + reduction_name = None + reduction_buf = None + for name in common_reads: + buf = V.graph.try_get_buffer(name) + if ( + buf is not None + and isinstance(buf, ir.ComputedBuffer) + and isinstance(buf.data, ir.Reduction) + ): + reduction_numel = sympy_product(buf.data.get_size()) * sympy_product( + buf.data.get_reduction_size() + ) + if V.graph.sizevars.statically_known_equals(cat_out_numel, reduction_numel): + reduction_name = name + reduction_buf = buf + break + + if reduction_name is None: + return None + + # Verify the reduction doesn't have consumers outside this cat's + # computation. Each IR node tracks which FX nodes produced it + # (origins). Collect the FX origins of all cat inputs, then check + # that every FX user of the reduction's origins feeds into one of + # the cat inputs. + # + # We also tried checking IR-level users via V.graph.name_to_users, + # but at lowering time the cat inputs are unrealized TensorBox + # wrappers (not named buffers), so name_to_users entries can't be + # correlated back to the cat's input chain. + # + # TODO: origins is a set of FX nodes attached to IR nodes during + # lowering — using it for correctness is fragile. A proper + # buffer→FX node mapping would be better. + origins = getattr(reduction_buf, "origins", None) + if not origins: + return None + + cat_input_origins: OrderedSet[torch.fx.Node] = OrderedSet() + for inp in inputs: + inp_origins = getattr(inp, "origins", None) + if inp_origins: + cat_input_origins.update(inp_origins) + + # Check that the reduction FX node's users all feed into the cat. + # origins may include non-reduction nodes (e.g. pow that feeds into + # mean), so filter to only reduction ops via torch.Tag.reduction. + for origin in origins: + if ( + origin.op == "call_function" + and isinstance(origin.target, torch._ops.OpOverload) + and torch.Tag.reduction in origin.target.tags + and not all(u in cat_input_origins for u in origin.users) + ): + return None + + return reduction_name + + +@register_lowering(aten.cat) +def cat(inputs, dim=0): + """Lower aten.cat, choosing between pointwise_cat and ConcatKernel.""" + cpu_device = inputs[0].get_device().type == "cpu" + if cpu_device and all( + input.get_dtype() in [torch.int8, torch.uint8] for input in inputs + ): + # TODO Remove this fallback when we support vectorization + # code gen with uint8 data type directly. + for input in inputs: + input.realize() + if all(len(input.get_size()) == 4 for input in inputs): + inputs, _ = require_channels_last(aten.cat, *inputs) + return fallback_handler(aten.cat.default)(inputs, dim) + + if len(inputs) == 1: + return clone(inputs[0]) + + # ATen's cat skips 1-D empty tensors (cat_should_skip_tensor) during + # dimension validation and concatenation. Replicate that here. + def _cat_should_skip(t): + size = t.get_size() + return len(size) == 1 and V.graph.sizevars.statically_known_equals(size[0], 0) + + skip_mask = [_cat_should_skip(t) for t in inputs] + if any(skip_mask): + valid_inputs = [t for t, skip in zip(inputs, skip_mask) if not skip] + if not valid_inputs: + return clone(inputs[0]) + if len(valid_inputs) == 1: + return clone(valid_inputs[0]) + inputs = valid_inputs + + dim = _validate_dim(inputs[0], dim, 0) + dtype = get_promoted_dtype( + *inputs, type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + inputs = [to_dtype(inp, dtype) for inp in inputs] + + def unwrap_tensor(x: TensorBox | ir.StorageBox) -> ir.IRNode: + if isinstance(x, TensorBox): + if isinstance(x.data, ir.BaseView): + return x.data.unwrap_view() + else: + return x.data + + if isinstance(x, ir.StorageBox): + return x.data + + return x + + def is_reduction(t): + return isinstance(t, ir.ComputedBuffer) and isinstance(t.data, ir.Reduction) + + def can_fuse_reduction(t, exclude: OrderedSet[str] = OrderedSet()): + if isinstance(t, (TensorBox, ir.StorageBox)): + return can_fuse_reduction(unwrap_tensor(t), exclude) + return ( + is_reduction(t) + or isinstance(t, ir.Pointwise) + and any( + read not in exclude + and can_fuse_reduction(V.graph.get_buffer(read), exclude) + for read in t.get_read_names() + ) + ) + + # Pointwise cat evaluates every input's computation for each + # output element (masked), so fusing reductions in is wasteful. + # Exception: when inputs just recombine a reduction's output + # (e.g. qknorm → RoPE → cat), we do not duplicate computation + recombined = _cat_inputs_recombine_reduction(inputs, dim) + exclude: OrderedSet[str] = OrderedSet([recombined]) if recombined else OrderedSet() + fusable_reduction = any(can_fuse_reduction(t, exclude) for t in inputs) + + def should_lower_cat_input(x) -> bool: + # Unrealized inputs will not be storage and layouts, and we don't want to realize + # them in case we want to fuse + if ir.is_storage_and_layout(x): + storage, _ = ir.as_storage_and_layout(x, freeze=False) + return not ir.ConcatKernel.can_realize_into_without_copy(storage) + + if isinstance(x, (TensorBox, ir.StorageBox)): + return should_lower_cat_input(unwrap_tensor(x)) + + if isinstance(x, ir.Pointwise): + return True + + return False + + if config.force_pointwise_cat: + return pointwise_cat(inputs, dim) + + # TODO: We observed negative performance impact of pointwise_cat optimization on CPU so disabled it. + # We will revisit this later after enabling vectorization on index_expr. + if cpu_device: + return TensorBox(ir.ConcatKernel.create(inputs, dim)) + + def op_count(x): + if isinstance(x, (TensorBox, ir.StorageBox)): + return op_count(unwrap_tensor(x)) + + # this will correspond to a direct memory read + if not isinstance(x, ir.Pointwise): + return 0 + + count = x.inner_fn_opcount().num_ops + for read in x.get_read_names(): + count += op_count(V.graph.get_buffer(read)) + + return count + + # as inputs increase, possibility for register spilling also increases. + # Past a certain threshold we only fuse if the input kernels are simple. + MAX_SIMPLE_OP_COUNT = 2 + + def additional_pointwise_ops(op: torch._ops.OpOverload): + return op in (aten.cat.default, aten.constant_pad_nd.default) + + if len(inputs) <= config.max_complex_pointwise_cat_inputs or ( + (len(inputs) <= config.max_pointwise_cat_inputs) + and all(op_count(t) <= MAX_SIMPLE_OP_COUNT for t in inputs) + ): + pointwise_uses = all( + is_pointwise_use(use, additional_pointwise_ops) + for use in V.current_node.users + ) + # fuse in case we will be used in a pointwise node, and there are any inputs we + # we can prevent materialization of. + fuse_pointwise_use = ( + any(should_lower_cat_input(inp) for inp in inputs) and pointwise_uses + ) + + # horizontal fuse in case all inputs will require a copy kernel anyway. + # only horizontally fuse pointwise kernels + + # Skip pointwise_cat when any cat input has a fusible (pointwise) + # multi-consumer — ConcatKernel + NonOwningLayout avoids redundant + # reads. Also skip when input is an unrealized Pointwise with + # multiple consumers to avoid recomputation (e.g. pad-as-cat). + def any_input_has_multi_consumers() -> bool: + current_node = V.current_node + if current_node is None: + return False + fx_args = current_node.args[0] + if isinstance(fx_args, (list, tuple)): + input_nodes = fx_args + elif isinstance(fx_args, torch.fx.Node): + input_nodes = [fx_args] + else: + return False + + if any(skip_mask): + input_nodes = [n for n, skip in zip(input_nodes, skip_mask) if not skip] + + def is_unrealized_pointwise(x): + if isinstance(x, (TensorBox, ir.StorageBox)): + return is_unrealized_pointwise(unwrap_tensor(x)) + return isinstance(x, ir.Pointwise) + + for arg, ir_input in zip(input_nodes, inputs): + if not hasattr(arg, "users") or len(arg.users) <= 1: + continue + # input will be computed multiple times because other consumers + # (eg. pointwise) will also inline it. So we should realize-in-place via ConcatKernel + if any(is_pointwise_use(u) for u in arg.users if u is not current_node): + return True + # If input is an unrealized Pointwise with multiple consumers, pointwise_cat + # will inline input without realizing it to memory, causing separate + # realization cost for input. So we should realize-in-place via ConcatKernel + if is_unrealized_pointwise(ir_input): + return True + return False + + has_multi_consumers = any_input_has_multi_consumers() + + horizontal_fuse_cat = ( + all(should_lower_cat_input(inp) for inp in inputs) and not fusable_reduction + ) + + if not has_multi_consumers and (fuse_pointwise_use or horizontal_fuse_cat): + return pointwise_cat(inputs, dim) + + return TensorBox(ir.ConcatKernel.create(inputs, dim)) + + +@register_lowering(aten.diagonal, type_promotion_kind=None) +def diagonal(input, offset: int = 0, dim1: int = 0, dim2: int = 1): + original_shape = input.get_size() + num_dims = len(original_shape) + dim1 = canonicalize_dim(idx=dim1, rank=num_dims) + dim2 = canonicalize_dim(idx=dim2, rank=num_dims) + + check( + dim1 != dim2, lambda: f"diagonal dimensions cannot be identical {dim1}, {dim2}" + ) + + offset_negative = V.graph.sizevars.evaluate_expr(sympy.Lt(offset, 0)) + if offset_negative: + diag_size = V.graph.sizevars.evaluate_max( + V.graph.sizevars.evaluate_min( + original_shape[dim1] + offset, + original_shape[dim2], + ), + 0, # type: ignore[arg-type] + ) + else: + diag_size = V.graph.sizevars.evaluate_max( + V.graph.sizevars.evaluate_min( + original_shape[dim1], + original_shape[dim2] - offset, + ), + 0, # type: ignore[arg-type] + ) + + base_idx = (0, 0) + if offset_negative: + base_idx = (-offset, 0) + else: + base_idx = (0, offset) + + sizes = [s for i, s in enumerate(original_shape) if i not in (dim1, dim2)] + sizes.append(diag_size) + + def reindexer(idx): + diag_idx = idx[-1] + original_idx = [0] * len(original_shape) + cur_dim = 0 + for d in range(num_dims): + if d == dim1: + original_idx[d] = diag_idx + base_idx[0] + elif d == dim2: + original_idx[d] = diag_idx + base_idx[1] + else: + original_idx[d] = idx[cur_dim] + cur_dim += 1 + + if cur_dim != len(original_shape) - 2: + raise AssertionError("expected: cur_dim == len(original_shape) - 2") + return original_idx + + return TensorBox(ir.GenericView.create(input, sizes, reindexer)) + + +@register_lowering(aten.diagonal_copy, type_promotion_kind=None) +def diagonal_copy(input, offset: int = 0, dim1: int = 0, dim2: int = 1): + return clone(diagonal(input, offset, dim1, dim2)) + + +@register_lowering(aten.diagonal_scatter, type_promotion_kind=None) +def diagonal_scatter(input, src, offset: int = 0, dim1: int = 0, dim2: int = 1): + output = clone(input) + target = diagonal(output, offset, dim1, dim2) + mutate_to(target, src) + return output + + +@register_lowering(aten.select, type_promotion_kind=None) +def select(x, dim, idx): + idx = sympy.expand(idx) + size = sympy.expand(x.get_size()[dim]) + actual_index = None + + if V.graph.sizevars.guard_or_false(sympy.Lt(idx, 0)): + actual_index = idx + size + elif V.graph.sizevars.guard_or_false(sympy.Ge(idx, 0)): + actual_index = idx + + if actual_index is not None: + if has_free_unbacked_symbols(idx): + # Inductor could generate incorrect views for tensors with unbacked symbols here; + # Squeeze operations are translated to views, resulting in incorrect strides. + # Additionally, we want to avoid accidental unbacked unsqueeze semantics. To resolve this, + # we use as_strided instead. + # Removing this branch will cause test_unbacked_select_index_with_check to fail. + + # before accessing size, stride, and offset we need to realize. + x.realize() + new_size = x.get_size() + new_stride = x.get_stride() + new_storage_offset = x.get_layout().offset + new_stride[dim] * actual_index + + del new_size[dim] + del new_stride[dim] + return as_strided( + x, + new_size, + new_stride, + new_storage_offset, + storage_offset_relative_to_input_storage=False, + ) + else: + # no need to clamp, this function handles negative indexing itself + slice_result = slice_(x, dim, actual_index, actual_index + 1, clamp=False) + return squeeze(slice_result, dim) + + # Unbacked Semantics: + # When the index idx is unbacked (e.g., u0), we compute the index dynamically + # during the lowering of the select operation using DynamicSelectStorageOffset. + + unbacked_bindings = resolve_unbacked_bindings( + V.graph.sizevars.shape_env, V.graph.current_node.meta["unbacked_bindings"] + ) + if unbacked_bindings is None: + raise AssertionError("expected: unbacked_bindings is not None") + if len(unbacked_bindings) != 1: + raise AssertionError(unbacked_bindings) + unbacked_offset_sym, _ = next(iter(unbacked_bindings.items())) + + # before accessing size, stride, and offset we need to realize. + x.realize() + new_size = x.get_size() + new_stride = x.get_stride() + new_storage_offset = unbacked_offset_sym + buffer = ir.DynamicSelectStorageOffset( + unbacked_offset_sym, + idx, + x.get_layout().offset, + new_stride[dim], + x.get_size()[dim], + clamp=False, + ) + buffer.name = V.graph.register_buffer(buffer) + V.graph.register_operation(buffer) + + del new_size[dim] + del new_stride[dim] + return as_strided( + x, + new_size, + new_stride, + new_storage_offset, + storage_offset_relative_to_input_storage=False, + ) + + +@register_lowering(aten.split, type_promotion_kind=None) +def split(x, sizes, dim=0): + dim = _validate_dim(x, dim, 0) + sizes_ = sizes + + # If sizes is an integer (or a SymInt), we turn it into a list of sizes + # by computing what the actual size of each chunk should be. + if not isinstance(sizes, (list, tuple)): + sizevars = V.graph.sizevars + if sizevars.statically_known_lt(sizes, 0): + raise RuntimeError( + f"split expects split_size be non-negative, but got split_size={sizes}" + ) + + x_size = x.get_size()[dim] + if sizevars.statically_known_equals(x_size, 0): + return [slice_(x, dim, 0, 0, clamp=False)] + + if sizevars.statically_known_equals(sizes, 0): + raise RuntimeError( + "split_size can only be 0 if dimension size is 0, " + f"but got dimension size of {x_size}" + ) + + chunks = sizevars.guard_int(FloorDiv(x_size + sizes - 1, sizes)) + sizes_ = [sizes] * chunks + # The last chunk might have a smaller size than the rest. + sizes_[-1] = x_size - (chunks - 1) * sizes + + # From this point, we assume that the sum of the sizes of all chunks + # equals the size of the base tensor. + result = [] + start = 0 + for size in sizes_: + end = start + size + # No need for clamping here, since we compute the exact + # start and end values. + result.append(slice_(x, dim, start, end, clamp=False)) + start = end + return result + + +@register_lowering(aten.split_with_sizes, type_promotion_kind=None) +def split_with_sizes(x, sizes, dim=0): + return split(x, sizes, dim) + + +@register_lowering(aten.unbind, type_promotion_kind=None) +def unbind(x, dim=0): + dim = _validate_dim(x, dim, 0) + x_size = V.graph.sizevars.guard_int(x.get_size()[dim]) + result = [select(x, dim, i) for i in range(x_size)] + return result + + +@register_lowering(aten.unfold, type_promotion_kind=None) +def unfold(x, dimension, size, step): + sizes = x.get_size() + ndim = len(sizes) + dim = canonicalize_dim(ndim, dimension) + + if ndim == 0: + return slice_(unsqueeze(x, 0), end=size, clamp=False) + + dim_size = sizes[dim] + sizevars = V.graph.sizevars + sizevars.check_leq(size, dim_size) + sizevars.check_lt(0, step) # type: ignore[arg-type] + + new_dim_size = FloorDiv(dim_size - size, step) + 1 + if sizevars.guarding_hint_or_throw(dim_size) > 0: + x.mark_reuse( + sizevars.guarding_hint_or_throw(CeilDiv(new_dim_size * size, dim_size)) + ) + + out_size = [*sizes[:dim], new_dim_size, *sizes[dim + 1 :], size] + + def reindexer(idx): + dim_idx = idx[-1] + idx[dim] * step + return (*idx[:dim], dim_idx, *idx[dim + 1 : -1]) + + return TensorBox(ir.GenericView.create(x, out_size, reindexer)) + + +@register_lowering(aten.unsqueeze, type_promotion_kind=None) +def unsqueeze(x, dim): + dim = _validate_dim(x, dim, 1) + new_shape = list(x.get_size()) + new_shape.insert(dim, sympy.S.One) + return view(x, new_shape) + + +@register_lowering(aten.unsqueeze_, type_promotion_kind=None) +def unsqueeze_(x, dim): + val = unsqueeze(x, dim) + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if not (isinstance(val, TensorBox)): + raise AssertionError("expected: isinstance(val, TensorBox)") + x.data = val.data + return x + + +def _validate_dim(x, dim, offset=0): + dim = V.graph.sizevars.shape_env.evaluate_expr(sympy.sympify(dim)) + ndim = len(x.get_size()) + if dim < 0: + dim += ndim + offset + if not (0 <= dim < ndim + offset): + raise AssertionError("expected: 0 <= dim < ndim + offset") + return dim + + +@register_lowering(aten.glu) +def glu(x, dim=-1): + dim = _validate_dim(x, dim, 0) + # TODO: don't guard on static shape here + new_len = V.graph.sizevars.guard_int(x.get_size()[dim]) // 2 + # no need to clamp, index is int based on input size + a = slice_(x, dim, 0, new_len, clamp=False) + b = slice_(x, dim, new_len, new_len * 2, clamp=False) + return mul(a, sigmoid(b)) + + +def fallback_handler(kernel, add_to_fallback_set=True): + if add_to_fallback_set: + fallbacks.add(kernel) + + def handler(*args, **kwargs): + def wrap_tensors(x): + return x.wrap_for_lowering() if isinstance(x, ir.IRNode) else x + + return pytree.tree_map( + wrap_tensors, ir.FallbackKernel.create(kernel, *args, **kwargs) + ) + + # This lets us detect that a lowering is a fallback handler. + handler._is_fallback_handler = True # type: ignore[attr-defined] + + return handler + + +@functools.cache +def _warn_complex_not_supported(): + warnings.warn( + "Torchinductor does not support code generation for complex operators. Performance may be worse than eager." + ) + + +# There are some types (CPU) which we accept as input but not as +# output. +def unsupported_input_tensor(t: torch.Tensor, node=None): + "Do not support reading or writing to this tensor" + if t.is_complex(): + # Complex views are supported with IR ComplexView + _warn_complex_not_supported() + return True + + if t.is_meta: + return True + + if t.is_sparse: + return True + + if not is_triton_fp8_dtype_supported(t.dtype, t.device): + from .codegen.triton_utils import ( + use_uint8_triton_storage_for_cuda_float8_e4m3fn, + ) + + if not use_uint8_triton_storage_for_cuda_float8_e4m3fn( + t.dtype, device=t.device + ): + return True + + # uint8 storage reinterprets fp8 bytes: allow bitcast, views, memory + # movement, and dequant (convert out of fp8) + if not node: + return True + return not ( + isinstance(node.target, torch._ops.OpOverload) + and node.target + in ( + aten.view.dtype, + aten.cat.default, + aten.clone.default, + aten._scaled_mm.default, + aten._scaled_mm_v2.default, + prims.convert_element_type.default, + ) + or (isinstance(node.target, torch._ops.OpOverload) and is_view(node.target)) + ) + + if t.dtype == torch.float8_e8m0fnu: + if not node: + return True + + # Allow bitcasts, views, memory movement, and supported conversions, + # but not arithmetic. + # TODO: delete once triton adds native support + if not isinstance(node.target, torch._ops.OpOverload): + return True + if node.target in ( + aten.view.dtype, + aten.cat.default, + aten.clone.default, + aten._scaled_mm.default, + aten._scaled_mm_v2.default, + ) or is_view(node.target): + return False + if node.target == torch.ops.prims.convert_element_type.default: + return not ( + len(node.args) >= 2 and node.args[1] in _FLOAT8_E8M0FNU_TO_FLOAT_DTYPES + ) + return True + + return False + + +def unsupported_output_tensor(t: torch.Tensor, node=None): + "Do not support writing tensor but can read from it" + supported_complex_views = ( + aten.view.dtype, + torch.ops.prims.convert_element_type.default, + ) + if node is not None and node.target in supported_complex_views and t.is_complex(): + return False + if unsupported_input_tensor(t, node): + return True + if not is_triton_fp8_dtype_supported(t.dtype, t.device): + return True + return t.is_cpu and config.disable_cpp_codegen + + +def fallback_node_due_to_unsupported_type(node: torch.fx.Node, allow_cpu_inputs=True): + # Custom fallback lowering + if node.target is aten.view_as_complex.default: + return False + + if node.op == "placeholder": + return False + + # We should be able to remove this special case once `disable_cpp_codegen` is killed. + if node.target is aten.lift_fresh_copy.default: + return False + + def check_skip_condition(inp_out_node, is_output): + if not isinstance(inp_out_node, torch.fx.Node): + return False + + if "val" not in inp_out_node.meta: + return False + + for meta in pytree.tree_leaves(inp_out_node.meta["val"]): + if not torch._subclasses.fake_tensor.is_fake_tensor(meta): + continue + + if is_output: + if unsupported_output_tensor(meta, node): + return True + else: + if unsupported_input_tensor(meta, node): + return True + + return False + + # only skip codegen if there is a cpu output, not input + for arg in pytree.arg_tree_leaves(*node.args, **node.kwargs): + if check_skip_condition(arg, is_output=False): + return True + + return check_skip_condition(node, is_output=True) + + +def make_fallback( + op, + layout_constraint=None, + warn=True, + override_decomp=False, + get_decomp_fn=None, +): + check_decomps = get_decomp_fn() if get_decomp_fn is not None else decompositions + if op in check_decomps and not override_decomp: + raise AssertionError(f"both a fallback and a decomp for same op: {op}") + if ( + warn + and bool(os.getenv("CI")) + and get_decompositions([op]) + # if fallback_random, we allow not decomposing random + and not ( + config.fallback_random + and op in torch._decomp.decompositions_for_rng.extra_random_decomps + ) + and not override_decomp + ): + # Note: 'warn' is holdover from when this was a warning, but for ops that previously + # set warn=False we do not want a CI error. + # Ignore the 'suppress errors' configs in CI, as this particular warning happens on startup anyway and is not + # likely to be triggered preferentially on one CI config over another. + if torch._dynamo.config.suppress_errors: + torch._dynamo.config.suppress_errors = False + log.warning( + "A make_fallback error occurred in suppress_errors config," + " and suppress_errors is being disabled to surface it." + ) + raise AssertionError( + f"make_fallback({op}): a decomposition exists, we should switch to it." + " To fix this error, either add a decomposition to core_aten_decompositions (preferred)" + " or inductor_decompositions, and delete the corresponding `make_fallback` line." + " Get help from the inductor team if unsure, don't pick arbitrarily to unblock yourself.", + ) + + def register_fallback(op_overload): + add_needs_realized_inputs(op_overload) + if layout_constraint is not None: + add_layout_constraint(op_overload, layout_constraint) + return register_lowering(op_overload, type_promotion_kind=None)( + fallback_handler(op_overload) + ) + + if isinstance(op, torch._ops.OpOverloadPacket): + for op_overload in op.op_overloads(): + register_fallback(op_overload) + elif isinstance(op, (torch._ops.OpOverload, torch._ops.HigherOrderOperator)): + register_fallback(op) + else: + raise RuntimeError(f"Unsupported fallback {op} with type {type(op)}") + + +def philox_rand_offset(shape): + """ + TorchInductor offset calculation differs from PyTorch eager offset + calculation for random ops (tl.rand vs torch.rand). In future, we should + strive for same impl for tl.rand and torch.rand. + """ + numel = 1 + for s in shape: + numel = numel * s + return tensor(numel, dtype=torch.int64) + + +@register_lowering(torch.ops.rngprims.philox_rand, type_promotion_kind=None) +def philox_rand(size, seed, offset, stride, device, dtype): + # stride arg is optional and will be used in future for distributed random + # ops. Currently, its unused. + random_pos = ir.FixedLayout( + device, + dtype, + size, + ir.FlexibleLayout.contiguous_strides(size), + ).make_indexer() + seed_loader = seed.make_loader() + offset_loader = offset.make_loader() + + def inner_fn(index): + # Both seed and offset in the philox_rand op are tensors. + # torch seed and offsets are of type int64, but tl.rand accepts int32 + seed_index_expr = ops.to_dtype(seed_loader([]), torch.int32) + offset_index_expr = ops.to_dtype(offset_loader([]), torch.int32) + # Get the offset'd position + rand_index_expr = ops.add( + ops.index_expr(random_pos(index), torch.int32), offset_index_expr + ) + result = ops.rand( + seed_index_expr, + rand_index_expr, + ) + return ops.to_dtype(result, dtype) + + random_values_node = Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=list(size), + ) + + offset_node = philox_rand_offset(size) + return random_values_node, offset_node + + +@register_lowering(aten.native_dropout, type_promotion_kind=None) +def native_dropout(x, p, train): + if config.fallback_random: + return pytree.tree_map( + TensorBox.create, + ir.FallbackKernel.create(aten.native_dropout.default, x, p, train), + ) + else: + raise AssertionError("should be handled in replace_random.py") + + +@register_lowering(aten.bernoulli_, type_promotion_kind=None) +def bernoulli_(x, *args): + if not (config.fallback_random or x.get_device() == torch.device("cpu")): + raise AssertionError( + "this should be handled in decomps unless config.fallback_random or the device is CPU" + ) + x.realize() + op_overload = ( + aten.bernoulli_.float + if len(args) == 0 or isinstance(args[0], float) + else aten.bernoulli_.Tensor + ) + ir.InplaceBernoulliFallback(op_overload, x, *args) + return x + + +@register_lowering(aten.bernoulli.p, type_promotion_kind=None) +def bernoulli_p(x, *args): + if not (config.fallback_random or x.get_device() == torch.device("cpu")): + raise AssertionError( + "this should be handled in decomps unless config.fallback_random or the device is CPU" + ) + return bernoulli_(clone(x), *args) + + +# This shouldn't be called in general +@register_lowering(aten._foobar) +def _foobar(_): + raise AssertionError + + +@functools.lru_cache(1) +def _warn_triton_random(salt): + log.info("using triton random, expect difference from eager") + + +def warn_triton_random(): + # only warn once per graph + _warn_triton_random(V.graph.creation_time) + + +fallback_rand_default = fallback_handler(aten.rand.default) +fallback_rand_generator = fallback_handler(aten.rand.generator) +fallback_randn_default = fallback_handler(aten.randn.default) +fallback_randn_generator = fallback_handler(aten.randn.generator) +make_fallback(aten.randint) +make_fallback(aten.rand_like, override_decomp=True) +make_fallback(aten.randn_like, override_decomp=True) +make_fallback(aten.randint_like, override_decomp=True) +make_fallback(aten.normal, override_decomp=True) +make_fallback(aten.rrelu_with_noise_functional) + +# TODO: mlazos reevaluate if we want to codegen something different +make_fallback(torch.ops.streams.record_event.default) +make_fallback(torch.ops.streams.wait_event.default) +make_fallback(torch.ops.streams.synchronize_event.default) +make_fallback(torch.ops.streams.synchronize_device.default) +make_fallback(torch.ops.streams.synchronize_stream.default) +make_fallback(torch.ops.streams.wait_stream.default) + + +@register_lowering(aten.rand) +def rand(*args, **kwargs): + if kwargs.get("generator") is not None: + return fallback_rand_generator(*args, **kwargs) + elif config.fallback_random or kwargs.get("pin_memory"): + kwargs.pop("generator", None) + return fallback_rand_default(*args, **kwargs) + raise AssertionError("should have been handled in replace_random.py") + + +@register_lowering(aten.randn) +def randn(*args, **kwargs): + if kwargs.get("generator") is not None: + return fallback_randn_generator(*args, **kwargs) + elif config.fallback_random or kwargs.get("pin_memory"): + kwargs.pop("generator", None) + return fallback_randn_default(*args, **kwargs) + raise AssertionError("should have been handled in replace_random.py") + + +@register_lowering(inductor_prims.force_stride_order, type_promotion_kind=None) +def inductor_force_stride_order(input_tensor, stride): + stride_order = ir.get_stride_order(stride, V.graph.sizevars.shape_env) + return ir.ExternKernel.require_stride_order(input_tensor, stride_order) + + +@register_lowering(inductor_prims.seed, type_promotion_kind=None) +def inductor_seed(device: torch.device): + raise AssertionError("should be handled in fuse_seed_creation_pass()") + + +@register_lowering(inductor_prims.seeds, type_promotion_kind=None) +def inductor_seeds(count, device): + warn_triton_random() + return TensorBox.create(ir.RandomSeeds(count, decode_device(device))) + + +@register_lowering(inductor_prims.lookup_seed, type_promotion_kind=None) +def inductor_lookup_seed(seeds, index): + def inner_fn(_): + return ops.load_seed(seeds.get_name(), index) + + return Pointwise.create( + device=seeds.get_device(), + dtype=seeds.get_dtype(), + inner_fn=inner_fn, + ranges=[], + ) + + +def get_threads_per_round(device: torch.device): + if not isinstance(device, torch.device): + device = torch.device(device) + + if device.type == "cuda": + idx = device.index + if idx is None: + idx = torch.cuda.current_device() + + prop = torch.cuda.get_device_properties(idx) + threads_per_round = ( + prop.multi_processor_count * prop.max_threads_per_multi_processor + ) + else: + _CPU_GRAIN_SIZE = 32768 + threads_per_round = _CPU_GRAIN_SIZE + + return threads_per_round + + +@register_lowering(inductor_prims.random, type_promotion_kind=None) +def inductor_random( + size: list[int], + seed: TensorBox, + mode: str, + *, + offset: int = 0, + align_dtype: torch.dtype = torch.float32, +): + if config.fallback_random: + raise AssertionError("expected: not config.fallback_random") + if mode not in ("rand", "randn"): + raise AssertionError('expected: mode in ("rand", "randn")') + size = [*size] + dtype = torch.float32 + device = seed.get_device_or_error() + random_pos = ir.FixedLayout( + device, dtype, size, ir.FlexibleLayout.contiguous_strides(size), offset=offset + ).make_indexer() + seed_loader = seed.make_loader() + + if config.align_random_eager and device.type == "cuda": + threads_per_round = get_threads_per_round(device) + + def _vec_from_dtype(dt: torch.dtype) -> int: + if dt in (torch.float16, torch.bfloat16): + return 8 + return 4 + + vec = _vec_from_dtype(align_dtype) + + def inner_fn(index): + rng_seed = seed_loader([0]) + base_offset = seed_loader([1]) + return ops.rand_eager( + rng_seed, + base_offset, + threads_per_round, + ops.index_expr(random_pos(index), torch.int32), + vec=int(vec), + ) + else: + + def inner_fn(index): + return getattr(ops, mode)( + seed_loader([]), + ops.index_expr(random_pos(index), torch.int32), + ) + + result = Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=[*size], + ) + result.realize() + return result + + +make_fallback(inductor_prims.rand_eager_offset) +make_fallback(inductor_prims.rand_eager_offsets) + + +@register_lowering(inductor_prims.randint, type_promotion_kind=None) +def inductor_randint( + low: int, high: int, size: list[int], seed: TensorBox, *, offset: int = 0 +): + if config.fallback_random: + raise AssertionError("expected: not config.fallback_random") + size = [*size] + dtype = torch.int64 + device = seed.get_device_or_error() + random_pos = ir.FixedLayout( + device, dtype, size, ir.FlexibleLayout.contiguous_strides(size), offset=offset + ).make_indexer() + seed_loader = seed.make_loader() + + def inner_fn(index): + return ops.randint64( + seed_loader([]), + ops.index_expr(random_pos(index), torch.int32), + ops.value_expr(low, torch.int64), + ops.value_expr(high, torch.int64), + ) + + return Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=[*size], + ) + + +def _boundaries_helper(tb: TensorBox) -> tuple[str, sympy.Expr, sympy.Expr, sympy.Expr]: + size = tb.get_size() + stride = tb.get_stride() + return ( + tb.get_name(), + size[-1], + tb.get_layout().storage_size(), + stride[-1], + ) + + +def _realize_bucketize_lookup_tensor(tb: TensorBox) -> TensorBox: + # ops.bucketize needs a named strided tensor. realize_input() also replays + # affine views over newly-realized inputs as ReinterpretViews when possible. + return TensorBox(ir.ExternKernel.realize_input(tb)) + + +def _sorter_helper(tb: TensorBox) -> tuple[str, sympy.Expr]: + return tb.get_name(), tb.get_stride()[-1] + + +def _bucketize_indices( + tb: TensorBox, index: Sequence[sympy.Expr], index_dtype: torch.dtype +) -> Any: + strides = tb.get_stride() + flattened_index = tb.get_layout().offset + sum( + (s * i for s, i in zip(strides[:-1], index[:-1])), sympy.S.Zero + ) + if not index and isinstance(flattened_index, sympy.Integer): + return int(flattened_index) + return ops.index_expr(flattened_index, index_dtype) + + +@register_lowering(aten.searchsorted.Tensor, type_promotion_kind=None) +def searchsorted( + sorted_sequence: TensorBox, + self: TensorBox, + *, + out_int32: bool = False, + right: bool = False, + side: str | None = None, + sorter: TensorBox | None = None, +) -> TensorBox: + validate_bucketize = lambda tb: V.graph.has_feature( # noqa: E731 + tb, BackendFeature.BUCKETIZE + ) + if ( + not validate_bucketize(sorted_sequence) + or not validate_bucketize(self) + or (sorter is not None and not validate_bucketize(sorter)) + ): + return fallback_handler(aten.searchsorted.Tensor, add_to_fallback_set=False)( + sorted_sequence, + self, + out_int32=out_int32, + right=right, + side=side, + sorter=sorter, + ) + + # If side is present, override the value of right if needed. This assumes that + # validation of the two options being non-contradictory is already done by the + # searchsorted meta-function. + if side is not None and side == "right": + right = True + + index_dtype = torch.int32 if out_int32 else torch.int64 + values_loader = self.make_loader() + + # The entire sorted_sequence tensor needs to be used by ops.bucketize, so we + # need a named strided tensor for codegen below. + sorted_sequence = _realize_bucketize_lookup_tensor(sorted_sequence) + + if sorter is not None: + sorter = _realize_bucketize_lookup_tensor(sorter) + + if len(sorted_sequence.get_size()) == 1: + + def inner_fn(idx): + val = values_loader(idx) + return ops.bucketize( + val, + _boundaries_helper(sorted_sequence), + _bucketize_indices(sorted_sequence, (), index_dtype), + index_dtype, + right, + sorter=None if sorter is None else _sorter_helper(sorter), + sorter_indices=( + None + if sorter is None + else _bucketize_indices(sorter, (), index_dtype) + ), + ) + + else: + + def inner_fn(idx): + val = values_loader(idx) + + # Get index to the beginning of the sorted sequence within a flattened + # version of the array. + def get_flattened_index(tb: TensorBox): + return _bucketize_indices(tb, idx, index_dtype) + + return ops.bucketize( + val, + _boundaries_helper(sorted_sequence), + get_flattened_index(sorted_sequence), + index_dtype, + right, + sorter=None if sorter is None else _sorter_helper(sorter), + sorter_indices=None if sorter is None else get_flattened_index(sorter), + ) + + device = self.get_device() + result = Pointwise.create( + device=device, + dtype=index_dtype, + inner_fn=inner_fn, + ranges=self.shape, + ) + # see [NOTE: inductor bucketize realize] + result.realize() + + return result + + +@register_lowering( + aten.bucketize.Tensor, type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH +) +def bucketize( + input: TensorBox, + boundaries: TensorBox, + *, + out_int32: bool = False, + right: bool = False, +): + if len(boundaries.get_size()) != 1: + raise AssertionError("expected: len(boundaries.get_size()) == 1") + + if not ( + V.graph.has_feature(input, BackendFeature.BUCKETIZE) + and V.graph.has_feature(boundaries, BackendFeature.BUCKETIZE) + ): + return fallback_handler(aten.bucketize.Tensor, add_to_fallback_set=False)( + input, boundaries, out_int32=out_int32, right=right + ) + + # The entire boundaries tensor needs to be used by ops.bucketize, so we + # need a named strided tensor for codegen below. + boundaries = _realize_bucketize_lookup_tensor(boundaries) + device = input.get_device() + input_loader = input.make_loader() + + index_dtype = torch.int32 if out_int32 else torch.int64 + + def inner_fn(index): + val = input_loader(index) + indices = ops.bucketize( + val, + _boundaries_helper(boundaries), + _bucketize_indices(boundaries, (), index_dtype), + index_dtype, + right, + ) + + return indices + + result = Pointwise.create( + device=device, + dtype=index_dtype, + inner_fn=inner_fn, + ranges=input.get_size(), + ) + + # [NOTE: inductor bucketize realize] + # bucketize_binary_search is relatively expensive, so we don't want to re-compute + # it unnecessarily. If we run bucketize() and then broadcast the result, we don't + # want this to be fused into a large number of duplicate bucketize() computations + # for each of the elements in the result. + # + # If no broadcasting occurs, fusions can still occur in scheduler.py + result.realize() + + return result + + +def _is_tensor_irnode(x): + return isinstance(x, ir.IRNode) and not isinstance( + x, (ir.NonTensorObj, ir.OpaqueMultiOutput) + ) + + +def require_dense(_, *args, **kwargs): + args, kwargs = pytree.tree_map_only( + _is_tensor_irnode, ir.ExternKernel.require_stride1, (args, kwargs) + ) + return args, kwargs + + +def require_contiguous(_, *args, **kwargs): + args, kwargs = pytree.tree_map_only( + _is_tensor_irnode, + ir.ExternKernel.require_contiguous, + (args, kwargs), + ) + return args, kwargs + + +def require_contiguous_strides(_, *args, **kwargs): + # TODO: combine this with require_contiguous after + # https://github.com/pytorch/pytorch/pull/148235 lands. + args, kwargs = pytree.tree_map_only( + _is_tensor_irnode, + ir.ExternKernel.require_contiguous_strides, + (args, kwargs), + ) + return args, kwargs + + +def require_channels_last(_, *args, **kwargs): + args, kwargs = pytree.tree_map_only( + _is_tensor_irnode, + ir.ExternKernel.require_channels_last, + (args, kwargs), + ) + return args, kwargs + + +def constrain_to_fake_tensor(arg, fake_arg): + if fake_arg is None: + return arg + if isinstance(fake_arg, FakeScriptObject) or is_custom_class_obj(fake_arg): + return arg + if isinstance(arg, ir.IRNode): + return ir.ExternKernel.require_exact_strides(arg, fake_arg.stride()) + if isinstance(arg, dict): + return {key: constrain_to_fake_tensor(arg[key], fake_arg[key]) for key in arg} + elif isinstance(arg, (tuple, list)): + return type(arg)( + constrain_to_fake_tensor(a, f_a) for (a, f_a) in zip(arg, fake_arg) + ) + return arg + + +def constrain_to_fake_tensors(args, kwargs, fake_args, fake_kwargs): + args = tuple( + constrain_to_fake_tensor(arg, fake_arg) + for arg, fake_arg in zip(args, fake_args) + ) + kwargs = {k: constrain_to_fake_tensor(v, fake_kwargs[k]) for k, v in kwargs.items()} + return args, kwargs + + +def constrain_to_fx_strides(fx_node, *args, **kwargs): + def get_fake_val(fx_arg): + if isinstance(fx_arg, torch.fx.Node): + return fx_arg.meta.get("val") + return fx_arg + + def apply_constraint(arg, fx_arg): + fake_val = get_fake_val(fx_arg) + if _is_tensor_irnode(arg): + if not isinstance(fake_val, torch.Tensor): + return arg + stride_order = ir.get_stride_order( + fake_val.stride(), V.graph.sizevars.shape_env + ) + return ir.ExternKernel.require_stride_order(arg, stride_order) + if isinstance(arg, dict): + if not isinstance(fake_val, dict): + return arg + return {key: apply_constraint(arg[key], fake_val[key]) for key in arg} + if isinstance(arg, (tuple, list)): + if not isinstance(fake_val, (tuple, list)): + return arg + return type(arg)( + apply_constraint(a, fx_a) for a, fx_a in zip(arg, fake_val) + ) + return arg + + args = tuple( + apply_constraint(arg, fx_arg) for arg, fx_arg in zip(args, fx_node.args) + ) + kwargs = {k: apply_constraint(v, fx_node.kwargs[k]) for k, v in kwargs.items()} + return args, kwargs + + +def constrain_to_fx_strides_if_fallback_random(fx_node, *args, **kwargs): + if not config.fallback_random: + return args, kwargs + return constrain_to_fx_strides(fx_node, *args, **kwargs) + + +# native_dropout uses empty_like(input) internally, so bernoulli_ consumes +# RNG values in the input's stride order. Constrain input strides to match +# the FX graph (i.e. eager) so the dropout mask is identical. +add_layout_constraint( + aten.native_dropout.default, constrain_to_fx_strides_if_fallback_random +) + + +def sdpa_constraint(fx_node, *args, **kwargs): + """Apply stride constraints to SDPA inputs, ensuring dense last dimension.""" + + def apply_constraint(idx, arg, fx_arg): + if not _is_tensor_irnode(arg): + return arg + + meta_val = fx_arg.meta["val"] + meta_stride_expr = [ + s.node.expr if isinstance(s, torch.SymInt) else s for s in meta_val.stride() + ] + shape_env = V.graph.sizevars.shape_env + stride_order = ir.get_stride_order(meta_val.stride(), shape_env) + + if stride_order and stride_order[-1] != 0: + # contiguous stride order + stride_order = list(reversed(range(len(arg.get_size())))) + + if ( + fx_node.target + == aten._scaled_dot_product_efficient_attention_backward.default + and idx in (0, 5) + ): + if len(stride_order) != 4: + raise AssertionError("expected: len(stride_order) == 4") + # The 0 and 5th arguments for aten._scaled_dot_product_efficient_attention_backward.default + # are for out and gradient_out. They have to be in + # (3, 1, 2, 0) stride order. Otherwise the kernel will crash. + # Check https://github.com/pytorch/pytorch/issues/138772 + stride_order = (3, 1, 2, 0) + + # Cache keyed by (id(arg), arg_name, stride_order) to avoid + # duplicate copy_input when the same tensor feeds multiple SDPA + # positions (e.g., key=value). Including arg_name handles + # mutation: mark_buffer_mutated() renames the buffer in place, + # so a mutated tensor has the same id but a different name, + # causing a cache miss. + cache_key = None + if config.cache_sdpa_constraint: + arg_name = arg.maybe_get_name() + cache_key = ( + id(arg), + arg_name, + tuple(stride_order) if stride_order else None, + ) + if cache_key in V.graph.sdpa_constraint_cache: + return V.graph.sdpa_constraint_cache[cache_key] + + result = _apply_constraint_inner( + idx, arg, meta_val, meta_stride_expr, stride_order + ) + if cache_key is not None: + V.graph.sdpa_constraint_cache[cache_key] = result + return result + + def _apply_constraint_inner(idx, arg, meta_val, meta_stride_expr, stride_order): + if not (meta_val.is_cuda or meta_val.is_xpu): + return ir.ExternKernel.require_stride_order(arg, stride_order) + + # This is the minimum alignment required by SDPA kernels for attention_bias. + # This value can be found in pytorch/aten/src/ATen/native/transformers/attention.cpp preprocess_mask + ALIGNMENT = 8 + + # effn_attn_fwd does requires dense last dim, not just alignment + effn_attn_fwd_bias = ( + fx_node.target + == torch.ops.aten._scaled_dot_product_efficient_attention.default + and idx == 3 + ) + + if not (isinstance(arg, TensorBox)): + raise AssertionError("expected: isinstance(arg, TensorBox)") + if len(arg.get_size()) not in (3, 4): + return arg + + is_aligned_tensor = ir.is_aligned_realized_tensor(arg, ALIGNMENT) + if is_aligned_tensor: + return ir.try_match_insignificant_strides( + ir.ExternKernel.realize_input(arg), meta_stride_expr + ) + + if ( + isinstance(arg, IRNode) + and arg.maybe_get_stride() is not None + and is_aligned_tensor + ): + return ir.try_match_insignificant_strides( + ir.ExternKernel.realize_input(arg), meta_stride_expr + ) + + if effn_attn_fwd_bias: + out_size = list(arg.get_size()) + + expanded_dims = [] + # We require a dense last dimension, but the other strides + # can be expanded, which results in a smaller tensor + maybe_stride = arg.maybe_get_stride() + for i in range(len(arg.get_size()) - 1): + if V.graph.sizevars.statically_known_equals(meta_stride_expr[i], 0) or ( + maybe_stride is not None + and V.graph.sizevars.statically_known_equals(maybe_stride[i], 0) + ): + expanded_dims.append(i) + + # Now, pad strides to alignment + out_strides = [-1] * len(out_size) + out_strides[-1] = 1 + stride = 1 + for i in range(len(out_size) - 2, -1, -1): + if out_strides[i + 1] != 0: + stride = stride * out_size[i + 1] + + # the expanded dims still need to be aligned, if they are, + # we can make them expanded by setting the stride equal to 0 + if i in expanded_dims: + if V.graph.sizevars.statically_known_equals( + Mod(out_strides[i + 1], ALIGNMENT), 0 + ): + out_strides[i] = 0 + continue + + if not V.graph.sizevars.statically_known_equals( + Mod(stride, ALIGNMENT), 0 + ): + stride = ceildiv(stride, ALIGNMENT) * ALIGNMENT + + out_strides[i] = stride + + return ir.ExternKernel.require_exact_strides(arg, out_strides) + + if is_aligned_tensor: + return ir.try_match_insignificant_strides( + ir.ExternKernel.realize_input(arg), meta_stride_expr + ) + + if ( + isinstance(arg, IRNode) + and arg.maybe_get_stride() is not None + and is_aligned_tensor + ): + return ir.try_match_insignificant_strides( + ir.ExternKernel.realize_input(arg), meta_stride_expr + ) + + def is_aligned(x): + size = x.get_size() + if len(size) == 0: + return False + return V.graph.sizevars.guard_or_false( + sympy.Eq(Mod(size[-1], ALIGNMENT), 0) + ) + + if isinstance(arg.data, ir.BaseView): + if not is_aligned(arg): + if is_aligned(arg.unwrap_view()): + return ir.try_match_insignificant_strides( + ir.ExternKernel.realize_input(arg), meta_stride_expr + ) + + return ir.ExternKernel.require_stride_order(arg, stride_order) + + args = tuple( + apply_constraint(idx, arg, fx_arg) + for idx, (arg, fx_arg) in enumerate(zip(args, fx_node.args)) + ) + kwargs = {k: apply_constraint(-1, v, fx_node.kwargs[k]) for k, v in kwargs.items()} + return args, kwargs + + +# WIP +make_fallback(aten._adaptive_avg_pool3d) # @isuruf +make_fallback(aten.adaptive_max_pool3d, override_decomp=True) +make_fallback(aten._scaled_dot_product_attention_math_for_mps) # @malfet + + +# 1) Easy +make_fallback(aten.uniform, override_decomp=True) +make_fallback(aten.exponential.default, warn=False) # (fails accuracy on test_torch.py) +make_fallback(aten._pdist_forward, require_contiguous) # Has decomp. Needs benchmarks +make_fallback(aten.soft_margin_loss_backward, warn=False) # py_impl? +make_fallback(aten._fused_rms_norm, warn=False) # (MPS-only and faster than decomp) +if torch.xpu._is_compiled(): + make_fallback( + aten.embedding_dense_backward, warn=False + ) # (XPU-only and faster than decomp) + +if torch.mtia._is_compiled(): + make_fallback( + aten.native_layer_norm, warn=False + ) # (MTIA-only and faster than decomp) + +# 1.5) Easy or Impossible +make_fallback(aten._cdist_forward) # p=2 should be feasible +make_fallback(aten._cdist_backward) + +# 2) Medium +make_fallback(aten._trilinear) + + +# 3) Difficult +# Scans +# See the discussion at +# https://dev-discuss.pytorch.org/t/pytorch-sparse-gnn-compiler-rfc/1644/19 +make_fallback(aten.segment_reduce.default) +make_fallback(aten._segment_reduce_backward.default) + +# Histogram (need to implement Histogram IR) +make_fallback(aten.histc) +make_fallback(aten.histogram.bin_ct) +make_fallback(aten._histogramdd_bin_edges.default) +make_fallback(aten._histogramdd_from_bin_cts.default) + +# Need templated kernel +make_fallback(aten.addbmm) +make_fallback(aten._addmm_activation, warn=False) + +make_fallback(aten._grouped_mm, require_dense) + +# Need templated kernel. Probably impossible to write efficiently +make_fallback(aten._cudnn_rnn, require_dense) +make_fallback(aten._cudnn_rnn_backward, require_contiguous) +make_fallback(aten.miopen_rnn, require_dense) +make_fallback(aten.miopen_rnn_backward, require_contiguous) + +# Haven't checked but sound difficult / impossible +make_fallback(aten._embedding_bag, require_contiguous) +make_fallback(aten._embedding_bag_forward_only, require_contiguous) +make_fallback(aten._embedding_bag_backward) +make_fallback(aten._embedding_bag_per_sample_weights_backward) +make_fallback(aten._embedding_bag_per_sample_weights_backward) +make_fallback(aten._fused_moving_avg_obs_fq_helper) +make_fallback(aten._fused_moving_avg_obs_fq_helper_functional) + + +# 4) Backwards (try py_impl'ing them) when fwd is written as a decomp +make_fallback(aten.max_pool3d_with_indices_backward) +make_fallback(aten._adaptive_avg_pool2d_backward, require_dense) +make_fallback(aten._adaptive_avg_pool3d_backward) +make_fallback(aten.adaptive_max_pool2d_backward) +make_fallback(aten.adaptive_max_pool3d_backward) +make_fallback(aten.fractional_max_pool2d_backward) +make_fallback(aten.fractional_max_pool3d_backward) +make_fallback(aten.replication_pad1d_backward) +make_fallback(aten.replication_pad2d_backward) +make_fallback(aten.upsample_linear1d_backward) +make_fallback(aten.upsample_bicubic2d_backward, require_contiguous) +make_fallback(aten.upsample_trilinear3d_backward) +make_fallback(aten.grid_sampler_2d_backward) +make_fallback(aten._pdist_backward, require_contiguous) + + +# 5) Impossible (missing triton/CPU features) + +# Sorting / Sorting-like +make_fallback(aten.nanmedian) +make_fallback(aten.multinomial.default, warn=False) +make_fallback(aten.randperm) +# see: https://github.com/pytorch/pytorch/pull/121354 +make_fallback(aten.resize_) +make_fallback(aten.resize_as_) + +# Linalg +make_fallback(aten._linalg_det) +make_fallback(aten.linalg_householder_product) +make_fallback(aten.linalg_inv_ex) +make_fallback(aten.linalg_ldl_factor_ex) +make_fallback(aten.linalg_ldl_solve) +make_fallback(aten.linalg_lu) +make_fallback(aten.linalg_lu_factor_ex) +make_fallback(aten.linalg_lu_solve) +make_fallback(aten.linalg_matrix_exp) +make_fallback(aten.linalg_matrix_sqrth) +make_fallback(aten.linalg_polar) +make_fallback(aten.linalg_qr) +make_fallback(aten._linalg_slogdet) +make_fallback(aten._linalg_solve_ex) +make_fallback(aten.linalg_solve_triangular) +make_fallback(aten._linalg_svd) +make_fallback(aten.lu_unpack) +make_fallback(aten.ormqr) +make_fallback(aten._linalg_check_errors) +make_fallback(aten.linalg_pinv.atol_rtol_tensor) +make_fallback(aten._linalg_eigh) +make_fallback(aten.triangular_solve) +make_fallback(aten.linalg_cholesky_ex) +make_fallback(aten.cholesky_inverse) +make_fallback(aten.cholesky_solve) +make_fallback(aten.geqrf) +make_fallback(aten._fft_r2c) # needs complex as well + +# Data dependent (are these necessary?) +make_fallback(aten.nonzero.default) +# Not data-dependent, but still using fallback +make_fallback(aten.nonzero_static.default) +# Data-dependent output size; route to ATen eager kernel (CPU/CUDA/XPU all have +# native implementations) +make_fallback(aten.bincount.default, warn=False) +make_fallback(aten._unique2.default, warn=False) +make_fallback(aten.unique_dim.default, warn=False) +make_fallback(aten.unique_consecutive.default, warn=False) +make_fallback(aten.unique_dim_consecutive.default, warn=False) + +# Misc +make_fallback(aten.gcd.default, warn=False) +make_fallback(aten._thnn_fused_lstm_cell, require_dense) +make_fallback(torch._prims.rng_prims.run_and_save_rng_state) +make_fallback(torch._prims.rng_prims.run_with_rng_state) +make_fallback(torch._prims.rng_prims.graphsafe_run_with_rng_state) +make_fallback(torch._prims.rng_prims.run_dtensor_rng_op) + +# AMP / GradScaler ops: both the in-place (_amp_update_scale_) and functional +# (_amp_update_scale) variants need explicit fallbacks. Inductor uses the +# functional form when the input tensor is a computed (non-leaf) value. +make_fallback(aten._amp_update_scale_.default, warn=False) +make_fallback(aten._amp_update_scale.default, warn=False) + + +# Implemented / Half implemented +# Scans. Implemented for CUDA, missing CPU +make_fallback(aten.masked_scatter) +make_fallback(aten.masked_scatter_backward) + +# Complex number support +make_fallback(aten.view_as_complex, require_contiguous) +make_fallback(aten.angle) # needs complex + +# Needs Sparse +make_fallback(aten._sparse_coo_tensor_with_dims_and_tensors) +make_fallback(aten.to_sparse) +make_fallback(aten._to_sparse) + + +@register_lowering(aten._to_dense.default, type_promotion_kind=None) +def _to_dense(x, dtype=None, masked_grad=None): + x = ir.ExternKernel.realize_input(x) + size = x.get_size() + device = x.get_device() + if device is None: + raise AssertionError("realized _to_dense input must have a device") + output_dtype = dtype if dtype is not None else x.get_dtype() + + def unflatten_args(tensor_args, non_tensor_args): + return [tensor_args[0], *non_tensor_args], {} + + # cpp_wrapper has no direct AOTI C shim for _to_dense, so route through the + # proxy-executor fallback while still describing the single dense output. + # MultiOutput lets this single-output op force a contiguous strided output + # layout instead of inheriting anything from the opaque MKLDNN input. + packed = ir.FallbackKernel( + ir.MultiOutputLayout(device=device), + aten._to_dense.default, + [x], + [dtype, masked_grad], + unflatten_args, + ) + out = ir.MultiOutput( + ir.FixedLayout( + device, + output_dtype, + size, + ir.FlexibleLayout.contiguous_strides(size), + ), + packed, + [], + ) + packed.outputs = [out] + return TensorBox.create(out) + + +# 6) Pattern-matched +make_fallback( + aten._scaled_dot_product_efficient_attention.default, + sdpa_constraint, + warn=False, +) +make_fallback( + aten._scaled_dot_product_efficient_attention_backward.default, + sdpa_constraint, + warn=False, +) +make_fallback( + aten._scaled_dot_product_flash_attention.default, + sdpa_constraint, + warn=False, +) +make_fallback( + aten._scaled_dot_product_flash_attention.quantized, + warn=False, +) +make_fallback( + aten._scaled_dot_product_flash_attention_backward.default, + sdpa_constraint, + warn=False, +) +make_fallback( + aten._scaled_dot_product_cudnn_attention.default, + sdpa_constraint, + warn=False, +) +make_fallback( + aten._scaled_dot_product_cudnn_attention_backward.default, + sdpa_constraint, + warn=False, +) +make_fallback( + aten._scaled_dot_product_flash_attention_for_cpu.default, + sdpa_constraint, + warn=False, +) +make_fallback( + aten._scaled_dot_product_flash_attention_for_cpu_backward.default, + sdpa_constraint, + warn=False, +) +make_fallback( + aten._scaled_dot_product_fused_attention_overrideable.default, + sdpa_constraint, + warn=False, +) +make_fallback( + aten._scaled_dot_product_fused_attention_overrideable_backward.default, + sdpa_constraint, + warn=False, +) +make_fallback(aten._flash_attention_forward.default, sdpa_constraint) +make_fallback(aten._flash_attention_forward.quantized) +make_fallback(aten._flash_attention_backward.default, sdpa_constraint) +make_fallback(aten._efficient_attention_forward.default, sdpa_constraint) +make_fallback(aten._efficient_attention_backward.default, sdpa_constraint) + +# index_reduce requires fallback when use_scatter_fallback(...) returns True +make_fallback(aten.index_reduce) +make_fallback(aten.repeat_interleave.Tensor, override_decomp=True) + +make_fallback(aten._weight_norm_interface_backward.default, require_contiguous) + + +# Register with type_promotion_kind None. +# For example, fp16.copy_(fp32) should **not** promote the first input's dtype. +@register_lowering(aten.copy, type_promotion_kind=None) +def copy(self, src, non_blocking=False): + if not isinstance(src, ir.IRNode): + src = tensor(src, dtype=self.get_dtype(), device=self.get_device()) + x = src + if self.get_device() != src.get_device(): + x = to_device(x, self.get_device()) + if self.get_dtype() != src.get_dtype(): + x = to_dtype(x, self.get_dtype()) + + if self.get_size() != src.get_size(): + out = expand(x, self.get_size()) + result = clone(out) + else: + result = clone(x) + + self_layout = self.maybe_get_layout() + if self_layout is not None and self_layout.is_pinned: + _realize_as_pinned(result) + return result + + +@register_lowering(aten.clone) +def clone(x, *, memory_format=None): + # Don't materialize the layout here based on memory_format, + # as we want to give the scheduler opportunity to perform layout optimization. + # Let the downstream op handle the input stride as needed. + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=x.make_loader(), + ranges=list(x.get_size()), + ) + + +def _realize_as_pinned(result): + result.realize() + result.data.data.get_layout().is_pinned = True + + +def clone_preserve_reinterpret_view(x): + reinterpret_view_layouts = [] + if isinstance(x, TensorBox) and isinstance(x.data, ir.ReinterpretView): + x = x.data # unwrap TensorBox + # pyrefly: ignore [bad-assignment] + while isinstance(x, ir.ReinterpretView): + reinterpret_view_layouts.append(x.get_layout()) + x = x.data + x = TensorBox(x) + + x = clone(x) + + if reinterpret_view_layouts: + x = x.data # unwrap TensorBox + for layout in reinterpret_view_layouts[::-1]: + x = ir.ReinterpretView(data=x, layout=layout) + x = TensorBox(x) + + return x + + +def lift_fresh_copy(x): + result = clone(x) + input_layout = x.maybe_get_layout() + if input_layout is not None and input_layout.is_pinned: + # torch.tensor(..., pin_memory=True) constants reach Inductor as a + # pinned constant followed by lift_fresh_copy. + _realize_as_pinned(result) + return result + + +if hasattr(aten, "lift_fresh_copy"): + register_lowering(aten.lift_fresh_copy)(lift_fresh_copy) + + +@register_lowering(prims.iota) +def iota( + length, + *, + start, + step, + dtype, + device, + requires_grad, +): + def fn(index): + return ops.index_expr(step * index[0] + start, dtype=dtype) + + return Pointwise.create( + device=decode_device(device), + dtype=dtype, + inner_fn=fn, + ranges=[length], + ) + + +@register_lowering(aten.arange.start_step, type_promotion_kind=None) +def arange_start_step( + start, + end, + step=1, + *, + dtype=None, + device=None, + layout=None, + pin_memory=None, + requires_grad=False, +): + if dtype is None: + raise AssertionError("expected: dtype is not None") + length = ceildiv(end - start, step) + return iota( + length, + start=start, + step=step, + dtype=dtype, + device=device if device is not None else "cpu", + requires_grad=requires_grad, + ) + + +@register_lowering(aten.select_scatter, type_promotion_kind=None) +def select_scatter(x, src, dim: int, index: int): + src = to_dtype(src, x.get_dtype()) + x_loader = x.make_loader() + dim = _validate_dim(x, dim, 0) + if V.graph.sizevars.guard_or_false(sympy.Lt(index, 0)): + index = index + x.get_size()[dim] + elif V.graph.sizevars.guard_or_false(sympy.Ge(index, 0)): + pass + else: + # unbacked index + return fallback_handler(aten.select_scatter.default)(x, src, dim, index) + + V.graph.sizevars.check_leq(0, index) # type: ignore[arg-type] + V.graph.sizevars.check_lt(index, x.get_size()[dim]) # type: ignore[arg-type] + src = expand(unsqueeze(src, dim), x.get_size()) + src_loader = src.make_loader() + + def inner_fn(idx): + return ops.where( + ops.eq( + ops.index_expr(idx[dim], torch.int32), + ops.index_expr(index, torch.int32), + ), + src_loader(idx), + x_loader(idx), + ) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=inner_fn, + ranges=list(x.get_size()), + ) + + +@register_lowering(aten.slice_scatter, type_promotion_kind=None) +def slice_scatter(x, src, dim=0, start=None, end=None, step=1): + """Lower slice_scatter with exact source shape checks.""" + src = to_dtype(src, x.get_dtype()) + x_loader = x.make_loader() + dim = _validate_dim(x, dim, 0) + dim_size = x.get_size()[dim] + + if any(free_unbacked_symbols(x) for x in (start, end, dim_size)): + start_index = _compute_slice_index(start, dim_size, 0) + if end is not None and V.graph.sizevars.statically_known_equals( + end, sys.maxsize + ): + end_index = dim_size + else: + end_index = _compute_slice_index(end, dim_size, dim_size) + + if start_index is None or end_index is None: + return fallback_handler(aten.slice_scatter.default)( + x, src, dim, start, end, step + ) + + start = start_index + end = _clamp_slice_end_to_start(end_index, start) + else: + # pyrefly: ignore [bad-argument-type] + start, end = ir.SliceView.normalize_start_end(x, dim, start, end) + + src_size = list(x.get_size()) + src_size[dim] = FloorDiv(end - start + (step - 1), step) + if len(src.get_size()) != len(src_size): + raise AssertionError("expected src and slice to have the same rank") + for actual, expected in zip(src.get_size(), src_size): + V.graph.sizevars.check_equals(actual, expected) + src = expand(src, src_size) + src_loader = src.make_loader() + + def inner_fn(idx): + if start == 0 and end == dim_size and step == 1: + # selecting every element is the same as just src.clone() + return src_loader(idx) + + idx_dim = ops.index_expr(idx[dim], torch.int64) + src_idx = list(idx) + src_idx[dim] = FloorDiv(idx[dim] - start, step) + + mask = [] + if start != 0: + mask.append( + ops.ge( + idx_dim, + ops.index_expr(sympy.expand(start), torch.int64), + ) + ) + if end != dim_size: + mask.append( + ops.lt( + idx_dim, + ops.index_expr(sympy.expand(end), torch.int64), + ) + ) + if step != 1: + mask.append( + ops.eq( + ops.index_expr( + ModularIndexing(idx[dim] - start, 1, step), torch.int64 + ), + ops.constant(0, torch.int64), + ) + ) + if not (mask): + raise AssertionError("expected: mask") + mask = functools.reduce(ops.and_, mask) + src_val = ops.masked( + mask, + lambda: src_loader(src_idx), + 0 if is_integer_type(x) else 0.0, + ) + return ops.where( + mask, + src_val, + x_loader(idx), + ) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=inner_fn, + ranges=list(x.get_size()), + ) + + +def _unwrap(x): + if isinstance(x, (list, tuple)) and len(x) > 0: + return _unwrap(x[0]) + return x + + +@register_lowering([torch.tensor, aten.scalar_tensor, prims.scalar_tensor]) +def tensor(data, *, dtype=None, device=None, layout=None, pin_memory=False): + # Match eager/meta scalar_tensor behavior; NJT handles scalar broadcasting. + if layout == torch.jagged: + layout = torch.strided + assert_nyi(layout in (None, torch.strided), f"layout={layout}") + if isinstance(_unwrap(data), int): + dtype = dtype or torch.int64 + else: + dtype = dtype or torch.get_default_dtype() + + ranges: list[sympy.Expr] = [] + + _truncate_fp = dtype in (torch.bfloat16, torch.float16) + + if isinstance(data, sympy.Basic): + + def inner_fn(index): + result = ops.index_expr(data, dtype) + if _truncate_fp: + result = ops.to_dtype(result, dtype, use_compute_types=False) + result = ops.to_dtype(result, dtype) + return result + + elif isinstance(data, (float, int)): + if _truncate_fp and isinstance(data, float): + data = torch.tensor(data, dtype=dtype).item() + + def inner_fn(index): + return ops.constant(data, dtype) + + elif len(data) == 0 or isinstance(data[0], (float, int)) and len(data) <= 8: + # inline small tensors + ranges.append(sympy.Integer(len(data))) + + def inner_fn(index): + def binary_search(start, end): + if start >= end: + raise AssertionError("expected: start < end") + if end - start == 1: + return ops.constant(data[start], dtype) + mid = (end - start) // 2 + start + return ops.where( + ops.lt( + ops.index_expr(index[0], torch.int64), + ops.constant(mid, torch.int64), + ), + binary_search(start, mid), + binary_search(mid, end), + ) + + if len(data) == 0: + return ops.constant(0, dtype) + return binary_search(0, len(data)) + + else: + return V.graph.add_tensor_constant( + torch.tensor( + data, dtype=dtype, device=device, pin_memory=pin_memory or False + ) + ) + + result = Pointwise.create( + device=decode_device(device), + dtype=dtype, + inner_fn=inner_fn, + ranges=ranges, + ) + if pin_memory: + _realize_as_pinned(result) + return result + + +@register_lowering(torch.as_tensor) +def as_tensor(data, dtype=None, device=None): + if isinstance(data, TensorBox): + if dtype is not None: + data = to_dtype(data, dtype) + if device is not None: + data = to_device(data, device) + return data + return tensor(data, dtype=dtype, device=device) + + +@register_lowering(torch.LongTensor) +def long_tensor(data): + return tensor(data, dtype=torch.int64) + + +@register_lowering(aten._local_scalar_dense) +def _local_scalar_dense(data): + # This is interesting! Most lowerings return tensors, so you can just + # return the buffer you allocated and it will get used (or not used, if + # it's dead.) But _local_scalar_dense (aka item) returns an int, + # not a Tensor, so you would have a type mismatch if you return a buffer; + # we are obligated to return a sympy expression instead. However, + # we need to actually codegen the .item() call somehow. We do this + # by registering a faux buffer for the DynamicScalar IR node, which is + # solely responsible for generating this .item(). The buffer is + # not used for anything (notice we discard it); at codegen time, + # the "buffer" just gets assigned None. + unbacked_bindings = resolve_unbacked_bindings( + V.graph.sizevars.shape_env, V.graph.current_node.meta["unbacked_bindings"] + ) + if unbacked_bindings is None: + raise AssertionError("expected: unbacked_bindings is not None") + if len(unbacked_bindings) != 1: + raise AssertionError(unbacked_bindings) + # NB: Have to be very careful here. V.graph.current_node.meta["val"] + # seemingly also contains a symbol which you want to do binding for, + # but it actually isn't. In particular, if we have later performed + # a deferred runtime assert saying that u0 == s0, you will actually + # see s0 from expr! This is bad because we need to actually generate + # the assert that says u0 == s0, so we need to know where to get u0 + # from (this call). In particular, we must use unbacked_bindings, which + # is guaranteed to have the original, unreplaced symbol in question. + # + # NB2: Another thing we have to be very careful about are symbol bindings + # that require nontrivial refinement, e.g., when you have a binding site + # x: Sym(u0 * 4) = y.item(). Here, the code generation must do a division + # in order to appropriately bind u0. This is communicated via the keypath + # in unbacked_bindings, and we need to hold onto it in order to generate + # code appropriately for this case. + binding_sym, keypath = next(iter(unbacked_bindings.items())) + buffer = ir.DynamicScalar(binding_sym, keypath, data) + buffer.name = V.graph.register_buffer(buffer) + V.graph.register_operation(buffer) + # NB: the replaced expr is OK to use directly downstream, we want + # simplifications in this case! + val = V.graph.current_node.meta["val"] + if isinstance(val, (torch.SymInt, torch.SymFloat, torch.SymBool)): + return val.node.expr + else: + return sympy.sympify(val) + + +@register_lowering(aten._assert_scalar) +def _assert_scalar(data, msg): + # NB: These will be handled at codegen time + # Not sure if we are guaranteed to be able to serve out truth from the + # deferred_runtime_asserts, TODO: try this assert out + # See [NOTE] Codegen runtime asserts in Inductor + # assert bool(data.scalar), data + return None + + +@register_lowering(aten._assert_tensor_metadata) +def _assert_tensor_metadata( + a, size=None, stride=None, dtype=None, *, device=None, layout=None +): + return None + + +def _full(fill_value, device, dtype, size): + value = fill_value + if not isinstance(fill_value, (int, float)) and hasattr(value, "value"): + value = value.value + + if isinstance(value, (int, float)): + + def inner_fn(index): + return ops.constant(value, dtype) + + elif isinstance(value, sympy.Basic): + + def inner_fn(index): + return ops.index_expr(value, dtype) + + else: + if len(value.get_size()) != 0: + raise AssertionError("expected: len(value.get_size()) == 0") + value_loader = value.make_loader() + + def inner_fn(index): + return value_loader([]) + + return Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=list(size), + ) + + +def full_like(x, fill_value, **kwargs): + return create_tensor_like(tensor_constructor(fill_value))(x, **kwargs) + + +def tensor_constructor(fill_value): + # torch.zeros, torch.ones, etc + def inner( + *size, + dtype=None, + device=None, + layout=None, + pin_memory=False, + memory_format=None, + ): + assert_nyi(layout in (None, torch.strided), f"layout={layout}") + assert_nyi(not memory_format, "memory_format") + device = decode_device(device) + dtype = dtype or torch.get_default_dtype() + if len(size) == 1 and isinstance(size[0], (list, tuple, torch.Size)): + size = tuple(size[0]) + # See https://github.com/pytorch/pytorch/issues/118102 + # All sizes at lowering time should be sympy.Symbol, not SymInt! + for s in size: + if isinstance(s, torch.SymInt): + raise AssertionError("expected: not isinstance(s, torch.SymInt)") + size = [sympy.expand(s) for s in size] + full_pointwise = _full(fill_value, decode_device(device), dtype, size) + + if pin_memory: + _realize_as_pinned(full_pointwise) + + return full_pointwise + + return inner + + +@register_lowering([torch.empty, aten.empty]) +def empty( + *size, + dtype=None, + layout=None, + device=None, + pin_memory=None, + memory_format=None, +): + device = decode_device(device) + if len(size) == 1 and isinstance(size[0], (list, tuple, torch.Size)): + size = tuple(size[0]) + return empty_strided( + size, None, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +def create_tensor_like(creation_fn): + """ + Shim to convert X_like(...) into X(...). For example zeros_like() into zeros(). + """ + + def _constant_like( + x, *, dtype=None, device=None, layout=None, pin_memory=False, memory_format=None + ): + assert_nyi(not pin_memory, "pin_memory") + assert_nyi(layout in (None, torch.strided), f"layout={layout}") + if dtype is None: + dtype = x.get_dtype() + else: + dtype = decode_dtype(dtype) + device = device or x.get_device() + size = list(x.get_size()) + return creation_fn( + size, dtype=dtype, device=device, layout=layout, pin_memory=pin_memory + ) + + return _constant_like + + +def constant_like(fill_value): + return create_tensor_like(tensor_constructor(fill_value)) + + +empty_like = register_lowering(aten.empty_like)(create_tensor_like(empty)) +ones_like = create_tensor_like(tensor_constructor(1)) +zeros_like = create_tensor_like(tensor_constructor(0)) + + +def new_constant(fill_value): + def _new_constant( + x, size, *, dtype=None, layout=None, device=None, pin_memory=None + ): + if not (isinstance(size, (list, tuple))): + raise AssertionError("expected: isinstance(size, (list, tuple))") + assert_nyi(not pin_memory, "pin_memory") + assert_nyi(layout in (None, torch.strided), f"layout={layout}") + # pyrefly: ignore [bad-argument-type] + dtype = decode_dtype(dtype) or x.get_dtype() + device = device or x.get_device() + size = [sympy.Integer(s) for s in size] + return _full(fill_value, decode_device(device), dtype, size) + + return _new_constant + + +@register_lowering(aten.new_empty) +def new_empty(x, size, *, dtype=None, layout=None, device=None, pin_memory=None): + if dtype is None: + dtype = x.get_dtype() + if device is None: + device = x.get_device() + return empty_strided( + size, + None, + dtype=dtype, + layout=layout, + device=decode_device(device), + pin_memory=pin_memory, + ) + + +@register_lowering(aten.empty_strided) +def empty_strided( + size, stride, *, dtype=None, layout=None, device=None, pin_memory=None +): + if not (isinstance(size, (list, tuple))): + raise AssertionError("expected: isinstance(size, (list, tuple))") + if not (isinstance(stride, (list, tuple, type(None)))): + raise AssertionError("expected: isinstance(stride, (list, tuple, type(None)))") + assert_nyi(layout in (None, torch.strided), f"layout={layout}") + # pyrefly: ignore [bad-argument-type] + dtype = decode_dtype(dtype) or torch.get_default_dtype() + device = device or torch.tensor(0.0).device + device = decode_device(device) + pointwise = _full(fill_value=0, device=device, dtype=dtype, size=size) + pointwise.realize() + buffer = pointwise.data.data + # explicitly set ranges to zeros in order to make a NopKernelSchedulerNode + buffer.data = dataclasses.replace(buffer.data, ranges=[0] * len(size)) + if not (isinstance(buffer, ir.ComputedBuffer)): + raise AssertionError("expected: isinstance(buffer, ir.ComputedBuffer)") + size = [sympy.expand(s) for s in size] + stride = ( + [sympy.expand(s) for s in stride] + if stride + else ir.FlexibleLayout.contiguous_strides(size) + ) + buffer.layout = ir.FixedLayout( + device=device, + dtype=dtype, + size=size, + stride=stride, + is_pinned=pin_memory or False, + ) + return pointwise + + +@register_lowering(aten.new_empty_strided) +def new_empty_strided( + x, size, stride, *, dtype=None, layout=None, device=None, pin_memory=None +): + if dtype is None: + dtype = x.get_dtype() + if device is None: + device = x.get_device() + return empty_strided( + size, + stride, + dtype=dtype, + layout=layout, + device=decode_device(device), + pin_memory=pin_memory, + ) + + +@register_lowering(prims.copy_strided.default) +def copy_strided(x, stride): + stride = V.graph.sizevars.guarding_hints_or_throw(stride) + stride_order = sorted(range(len(stride)), key=stride.__getitem__) + return ir.ExternKernel.require_stride_order(x, stride_order) + + +@register_lowering([torch.full, aten.full]) +def full(size, fill_value, **kwargs): + if kwargs.get("dtype") is None: + raise AssertionError("dtype should be handled by decomposition") + return tensor_constructor(fill_value)(size, **kwargs) + + +@register_lowering(aten._efficientzerotensor, type_promotion_kind=None) +def _efficientzerotensor( + size, *, dtype=None, layout=None, device=None, pin_memory=False +): + assert_nyi(layout in (None, torch.strided), f"layout={layout}") + dtype = torch.get_default_dtype() if dtype is None else decode_dtype(dtype) + with torch.utils._python_dispatch._disable_current_modes(): + scalar = torch.zeros((), dtype=dtype, device=decode_device(device)) + return expand(V.graph.add_tensor_constant(scalar), size) + + +@register_lowering(aten.gather, type_promotion_kind=None) +def gather(x, dim, index, sparse_grad=False): + # sparse_grad doesn't affect forward computation, + # and backward tracing is taken care of by AOT Autograd + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if index.get_numel() == 0: + # Empty index case. Return an empty array with the same shape + return new_empty(x, index.get_size()) + + size = x.get_size() + offset = len(size) == 0 + dim = _validate_dim(x, dim, offset) + + if offset: + x = expand(x, [1]) + size = [1] + + x_loader = x.make_loader() + index_loader = index.make_loader() + + def fn(idx): + idx = list(idx) + gather_idx = ops.indirect_indexing(index_loader(idx), size[dim], wrap_neg=False) + if len(idx) == 0: + idx = [gather_idx] + else: + idx[dim] = gather_idx + return x_loader(idx) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=fn, + ranges=index.get_size(), + ) + + +@register_lowering(aten.embedding, type_promotion_kind=None) +def embedding(weight, indices, padding_idx=-1, scale_grad_by_freq=False, sparse=False): + if sparse: + return fallback_handler(aten.embedding.default)( + weight, indices, padding_idx, scale_grad_by_freq, sparse + ) + + if sparse: + raise AssertionError("expected: not sparse") + if not (isinstance(weight, TensorBox)): + raise AssertionError("expected: isinstance(weight, TensorBox)") + if not (isinstance(indices, TensorBox)): + raise AssertionError("expected: isinstance(indices, TensorBox)") + if "int" not in str(indices.get_dtype()): + raise AssertionError('expected: "int" in str(indices.get_dtype())') + + weight_loader = weight.make_loader() + indices_loader = indices.make_loader() + indices_ndim = len(indices.get_size()) + weight_size = weight.get_size() + new_size = [*indices.get_size(), *weight_size[1:]] + + def fn(idx): + if len(idx) != len(new_size): + raise AssertionError(f"{idx} != {new_size}") + var_index = indices_loader(idx[:indices_ndim]) + weight_idx = [ + ops.indirect_indexing(var_index, weight_size[0], wrap_neg=False) + ] + [*idx[indices_ndim:]] + return weight_loader(weight_idx) + + return Pointwise.create( + device=weight.get_device(), + dtype=weight.get_dtype(), + inner_fn=fn, + ranges=new_size, + ) + + +def check_and_broadcast_indices(indices, device): + if not ( + all( + i.get_dtype() in (torch.int64, torch.int32, torch.bool, torch.uint8) + for i in indices + if i is not None + ) + ): + raise AssertionError( + f"indices must be int64, byte or bool. Got {[i.get_dtype() for i in indices if i is not None]}" + ) + if any( + i.get_dtype() in (torch.bool, torch.uint8) for i in indices if i is not None + ): + raise NotImplementedError("Fallback for bool indices") + + valid_idxs = [i for i, x in enumerate(indices) if isinstance(x, TensorBox)] + if len(valid_idxs) <= 0: + raise AssertionError("requires at least 1 non-None index") + new_indices = [None] * len(indices) + for i, x in zip(valid_idxs, broadcast_tensors(*[indices[i] for i in valid_idxs])): + # Eager allows indices to be CPU tensor when running on CUDA + # FIXME: Calling to_device(x, device) should work but + # test_advancedindex_mixed_cpu_devices still fails + if x.get_device() != device: + raise NotImplementedError("Fallback when indices is on a different device") + new_indices[i] = x + return new_indices, valid_idxs + + +def index_output_size_and_inner_fn( + x_size, + indices, + tensor_indices, + tensor_size, + indices_loaders, + indexed_size, + x_loader, + check, + wrap_neg=True, +): + # Note that behavior of indexing differs when there are non consecutive + # tensors. In this case, the tensor index is pulled to the beginning. + # + # Suppose a = torch.arange(3 * 4 * 5 * 6 * 7).view(3, 4, 5, 6, 7) + # x = torch.tensor[1,2] + # Then, a[:,x,:,x,:] will have shape 2,3,5,7 as due to x,:,x then 2 will + # be pulled to the front. + non_consecutive_tensors = False + for previous, current in itertools.pairwise(tensor_indices): + if current - previous != 1: + non_consecutive_tensors = True + + output_size = [x_size[i] for i, val in enumerate(indices) if val is None] + output_size = [*output_size, *x_size[len(output_size) + len(tensor_indices) :]] + + first_tensor_index = tensor_indices[0] + if non_consecutive_tensors: + output_size = tensor_size + output_size + else: + output_size = ( + output_size[:first_tensor_index] + + tensor_size + + output_size[first_tensor_index:] + ) + + def fn(idx): + if len(idx) != len(output_size): + raise AssertionError("expected: len(idx) == len(output_size)") + if len(indices_loaders) != len(indexed_size): + raise AssertionError("expected: len(indices_loaders) == len(indexed_size)") + + rank = len(tensor_size) + new_index = [] + first_tensor_index = tensor_indices[0] + start_offset = 0 if non_consecutive_tensors else first_tensor_index + next_idx = 0 + for i in range(tensor_indices[-1] + 1): + if i == start_offset: + next_idx += rank + if indices[i] is None: + if next_idx >= len(idx): + raise AssertionError("expected: next_idx < len(idx)") + new_index.append(idx[next_idx]) + next_idx += 1 + else: + loader = indices_loaders[i] + if loader is None: + raise AssertionError("expected: loader is not None") + size = indexed_size[i] + new_index.append( + ops.indirect_indexing( + loader(idx[start_offset : start_offset + rank]), + size, + check=check, + wrap_neg=wrap_neg, + ) + ) + new_index = [ + *new_index, + *idx[next_idx:], + ] + return new_index if x_loader is None else x_loader(new_index) + + return output_size, fn + + +def index_impl(x, indices, check): + output_size, inner_fn, _ = index_impl_helper(x, indices, check) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=inner_fn, + ranges=output_size, + ) + + +def index_impl_helper(x, indices, check, wrap_neg=True): + if not (isinstance(indices, (list, tuple))): + raise AssertionError("expected: isinstance(indices, (list, tuple))") + x_loader = x.make_loader() + indices, tensor_indices = check_and_broadcast_indices(indices, x.get_device()) + if len(tensor_indices) <= 0: + raise AssertionError("Must have at least one valid idx") + + indices_loaders = [i.make_loader() if i is not None else None for i in indices] + # no guards on output size, all the guards are set in broadcast_tensors + + # We can use the first one since they are all required to be the same size + tensor_size = list(indices[tensor_indices[0]].get_size()) + + x_size = x.get_size() + + indexed_size = [x_size[i] for i in range(len(indices)) if indices[i] is not None] + if check and 0 in indexed_size and 0 not in tensor_size: + raise IndexError("index is out of bounds for dimension with size 0") + + indexed_size = [x_size[i] for i in range(len(indices))] + output_size, index_inner_fn = index_output_size_and_inner_fn( + x_size, + indices, + tensor_indices, + tensor_size, + indices_loaders, + indexed_size, + None, + check=check, + wrap_neg=wrap_neg, + ) + + def inner_fn(idx): + return x_loader(index_inner_fn(idx)) + + return output_size, inner_fn, index_inner_fn + + +@register_lowering(aten.index, type_promotion_kind=None) +def index(x, indices): + try: + return index_impl(x, indices, check=True) + except NotImplementedError: + # Fallback to ATen for boolean indexing + x.realize() + return fallback_handler(aten.index.Tensor, add_to_fallback_set=False)( + x, indices + ) + + +@register_lowering(aten._unsafe_index, type_promotion_kind=None) +def _unsafe_index(x, indices): + return index_impl(x, indices, check=False) + + +# All the indexing decompositions are written in terms of index, index_put, and index_put_ +# We cannot have this lowering as a decomposition as it introduces +# mutation in the graph, which is bad for Aot Autograd. Aot Autograd runs dead +# code elimination and common subexpression elimination optimizations, which +# assume graphs to be side-effect free. More details at +# https://github.com/pytorch/torchdynamo/issues/1235 +# and +# https://github.com/pytorch/torchdynamo/issues/1863 +@register_lowering(aten.index_put, type_promotion_kind=None) +def index_put(x, indices, values, accumulate=False): + return index_put_impl_( + clone(x), indices, values, accumulate, check=True, may_realize=False + ) + + +@register_lowering(aten._unsafe_index_put) +def _unsafe_index_put(x, indices, values, accumulate=False): + return index_put_impl_( + clone(x), indices, values, accumulate, check=False, may_realize=False + ) + + +def index_put_as_masked_fill(self, indices, value, accumulate): + if value.get_device() != self.get_device(): + value = to_device(value, self.get_device()) + if accumulate: + value = add(self, value) + return mutate_to(self, where(indices[0], value, self)) + + +def index_put_fallback(self, indices, values, accumulate): + from .utils import _fx_node_is_input_dependent_cudagraph_unsafe + + op_overload = getattr(aten.index_put_, V.graph.current_node.target._overloadname) # type: ignore[union-attr] + + # Check if any index is a boolean tensor - if so, mark as cudagraph-unsafe + # because boolean indices trigger .nonzero() during CUDA graph capture + # When graph_partition is enabled, skip - partitioning handles this + fx_node = V.graph.current_node + if ( + not config.graph_partition + and fx_node is not None + and _fx_node_is_input_dependent_cudagraph_unsafe(fx_node) + ): + msg = "index_put_ fallback with boolean indexing is not compatible with CUDA graphs" + if stack_trace := fx_node.meta.get("stack_trace", None): + msg = f"{msg} Found from : \n {stack_trace}" + V.graph.disable_cudagraphs_reason = msg + + ir.IndexPutFallback(op_overload, self, indices, values, accumulate) + return self + + +@register_lowering(aten.index_put_, type_promotion_kind=None) +def index_put_(self, indices, values, accumulate=False): + return index_put_impl_( + self, indices, values, accumulate, check=True, may_realize=True + ) + + +@register_lowering(inductor_prims._unsafe_index_put_, type_promotion_kind=None) +def _unsafe_index_put_(self, indices, values, accumulate=False): + return index_put_impl_( + self, indices, values, accumulate, check=False, may_realize=True + ) + + +def index_put_impl_(self, indices, values, accumulate, check, may_realize=False): + if may_realize: + + def indice_slice_from_randperm(indice): + # Refer to: https://github.com/pytorch/pytorch/pull/139366#discussion_r1825424660 + # For this specific pattern, indices is unique as coming from torch.randperm. + # However, as the content of the indices is unknown, we have to check this specific pattern. + if isinstance(indice, TensorBox) and isinstance(indice.data, ir.BaseView): + indice = indice.data.unwrap_view() + return ( + isinstance(indice, ir.StorageBox) + and isinstance(indice.data, ir.ExternKernel) + and getattr(indice.data, "fx_node", None) + and indice.data.fx_node.target is torch.ops.aten.randperm.default + ) + return False + + if ir.try_get_name(self) in values.get_read_names() and not all( + indice_slice_from_randperm(indice) for indice in indices + ): + # Fix issue: https://github.com/pytorch/pytorch/issues/138908 + # When self and values have memory overlapping, indices may + # contain duplicate values, potentially causing incorrect results since + # the load of `values` might contain modified value from the store of `self`. + # To address this, store values in a temporary buffer in such cases. + values.realize() + + # Dispatch to masked fill for single boolean index with single value + if ( + values.get_numel() == 1 + and len(indices) == 1 + and indices[0].get_dtype() in (torch.bool, torch.uint8) + ): + mask = indices[0] + for _ in range(len(mask.get_size()), len(self.get_size())): + mask = unsqueeze(mask, -1) + return index_put_as_masked_fill(self, [mask], values, accumulate) + + # Fallback in torch deterministic mode + if torch.are_deterministic_algorithms_enabled(): + return index_put_fallback(self, indices, values, accumulate) + + # Fallback if there is a boolean index + for index in indices: + if index is not None and index.get_dtype() in (torch.bool, torch.uint8): + return index_put_fallback(self, indices, values, accumulate) + + x_size = self.get_size() + x_ndim = len(x_size) + + device = self.get_device() + if ( + accumulate + and device is not None + and is_gpu(device.type) + and needs_fallback_due_to_atomic_add_limitations(self.get_dtype()) + ): + # self is an scalar Tensor + if x_ndim == 0: + self = view(self, [1]) + self = index_put_fallback(self, indices, values, accumulate) + if x_ndim == 0: + self = view(self, []) + return self + + values = to_dtype(values, self.get_dtype()) + + try: + indices, tensor_indices = check_and_broadcast_indices( + indices, self.get_device() + ) + except NotImplementedError: + return index_put_fallback(self, indices, values, accumulate) + + indices_loaders = [i.make_loader() if i is not None else None for i in indices] + + if not (isinstance(self, TensorBox)): + raise AssertionError("expected: isinstance(self, TensorBox)") + self.realize() + + # self is an scalar Tensor + if x_ndim == 0: + self = view(self, [1]) + + # We can use the first one since they are all required to be the same size + tensor_size = list(indices[tensor_indices[0]].get_size()) + indexed_size = [x_size[i] for i in range(len(indices))] + + expected_vals_size, inner_fn = index_output_size_and_inner_fn( + x_size, + indices, + tensor_indices, + tensor_size, + indices_loaders, + indexed_size, + None, + check=check, + ) + values = expand(values, expected_vals_size) + # all guards are set above during broadcast_tensors and expand + + device = self.get_device() + if device is None: + raise AssertionError("expected: device is not None") + scatter = ir.Scatter( + device=device, + dtype=self.get_dtype(), + inner_fn=values.make_loader(), + ranges=expected_vals_size, # iter_ranges, + output_indexer=inner_fn, + scatter_mode="atomic_add" if accumulate else None, + ) + buffer = ir.ComputedBuffer( + name=None, + layout=ir.MutationLayoutSHOULDREMOVE(self), + data=scatter, + ) + buffer.name = V.graph.register_buffer(buffer) + V.graph.register_operation(buffer) + + if x_ndim == 0: + self = view(self, []) + return self + + +fallback__unsafe_masked_index = fallback_handler( + aten._unsafe_masked_index.default, add_to_fallback_set=False +) + +fallback__unsafe_masked_index_put_accumulate = fallback_handler( + aten._unsafe_masked_index_put_accumulate.default, add_to_fallback_set=False +) + + +@register_lowering(aten._unsafe_masked_index, type_promotion_kind=None) +def _unsafe_masked_index(self, mask, indices, fill): + ranges, _, _unsafe_index_fn = index_impl_helper( + self, indices, check=False, wrap_neg=False + ) + mask_loader = mask.make_loader() + self_loader = self.make_loader() + + def inner_fn(idx): + if mask.dtype != torch.bool: + mask_val = ops.to_dtype(mask_loader(idx), torch.bool) + else: + mask_val = mask_loader(idx) + return ops.masked(mask_val, lambda: self_loader(_unsafe_index_fn(idx)), fill) + + return Pointwise.create( + device=self.get_device(), + dtype=self.get_dtype(), + inner_fn=inner_fn, + ranges=ranges, + ) + + +@register_lowering(aten._unsafe_masked_index_put_accumulate, type_promotion_kind=None) +def _unsafe_masked_index_put_accumulate(x, mask, indices, values): + masked_value = where(mask, values, 0) + shape = x.get_size() + clamped_indices = [ + clamp(indices[i], -shape[i], shape[i] - 1) if indices[i] else None + for i in range(len(indices)) + ] + # TODO: use a masked store for this. currently only triton + # supports masked stores and cpp backend does not. + return _unsafe_index_put(x, clamped_indices, masked_value, accumulate=True) + + +@make_pointwise +def clamp(a, min, max): + return ops.maximum(min, ops.minimum(max, a)) + + +@register_lowering(aten.as_strided_scatter, type_promotion_kind=None) +def as_strided_scatter(self, src, size, stride, storage_offset=None): + output = clone(self) + output_view = as_strided(output, size, stride, storage_offset) + copy_(output_view, src) + return output + + +@register_lowering(aten.scatter, type_promotion_kind=None) +def scatter(x, dim: int, index, src, **kwargs): + return scatter_(clone(x), dim, index, src, **kwargs) + + +def scatter_fallback( + op_overload: torch._ops.OpOverload, + self, + dim: int, + index, + src, + *, + reduce: str | None = None, + include_self: bool = True, +): + src_is_tensor = isinstance(src, TensorBox) + if use_scatter_fallback( + op_overload, + reduce, + self.get_dtype(), + cast(torch.dtype, src.get_dtype() if src_is_tensor else type(src)), + # pyrefly: ignore [missing-attribute] + src.get_device().type if src_is_tensor else "not impl", + src_is_tensor, + ): + ir.ScatterFallback( + op_overload, + self, + dim, + index, + src, + reduce=reduce, + include_self=include_self, + ) + return self + + return None + + +@register_lowering(aten.scatter_, type_promotion_kind=None) +def scatter_(self, dim: int, index, src, *, reduce: str | None = None): + if reduce not in (None, "add", "multiply"): + raise AssertionError('expected: reduce in (None, "add", "multiply")') + if reduce is None: + op_overload = getattr(aten.scatter_, V.graph.current_node.target._overloadname) # type: ignore[union-attr] + fallback_result = scatter_fallback( + op_overload, self, dim, index, src, reduce=reduce + ) + if fallback_result is not None: + return fallback_result + + if reduce == "add": + reduce = "sum" + elif reduce == "multiply": + reduce = "prod" + return scatter_reduce_(self, dim, index, src, reduce) + + +@register_lowering(aten.scatter_add, type_promotion_kind=None) +def scatter_add(x, dim: int, index, src): + return scatter_add_(clone(x), dim, index, src) + + +@register_lowering(aten.scatter_add_, type_promotion_kind=None) +def scatter_add_(x, dim: int, index, src): + return scatter_reduce_(x, dim, index, src, "sum") + + +@register_lowering(aten.scatter_reduce, type_promotion_kind=None) +def scatter_reduce(x, dim: int, index, src, reduction_type, **kwargs): + return scatter_reduce_(clone(x), dim, index, src, reduction_type, **kwargs) + + +@register_lowering(aten.scatter_reduce_, type_promotion_kind=None) +def scatter_reduce_(self, dim: int, index, src, reduce, *, include_self: bool = True): + if reduce not in (None, "sum", "prod", "mean", "amax", "amin"): + raise AssertionError( + 'expected: reduce in (None, "sum", "prod", "mean", "amax", "amin")' + ) + if not ( + len(aten.scatter_reduce_.overloads()) == 1 + and "two" in aten.scatter_reduce_.overloads() + ): + raise AssertionError( + "aten.scatter_reduce_.two is not the unique overload of aten.scatter_reduce_" + ) + + if isinstance(src, Number): + src = full_like(self, src) + + fallback_result = scatter_fallback( + aten.scatter_reduce_.two, + self, + dim, + index, + src, + reduce=reduce, + include_self=include_self, + ) + + if fallback_result: + return fallback_result + + if not (isinstance(self, TensorBox)): + raise AssertionError("expected: isinstance(self, TensorBox)") + + ndim = len(self.get_size()) + if ndim == 0: + self = view(self, [1]) + + if isinstance(src, TensorBox) and len(src.get_size()) == 0: + src = view(src, [1]) + + if isinstance(index, TensorBox) and len(index.get_size()) == 0: + index = view(index, [1]) + + if index.get_numel() == 0: + return self + + if "int" not in str(index.get_dtype()): + raise AssertionError('expected: "int" in str(index.get_dtype())') + + dim = _validate_dim(self, dim) + + self.realize() + index_loader = index.make_loader() + src_loader = src.make_loader() if isinstance(src, TensorBox) else None + + def output_indexer(idx): + # self is captured from the end of the function, so it may have 0 dim + shape = self.get_size() + ndim = len(shape) + indirect_idx = list(idx) + indirect_idx[dim] = ops.indirect_indexing( + index_loader(idx), 1 if ndim == 0 else shape[dim], wrap_neg=False + ) + return indirect_idx + + def fn(idx): + if src_loader: + return src_loader(idx) + else: + # src is a scalar + # pyrefly: ignore [bad-argument-type] + return ops.constant(src, self.get_dtype()) + + def backend_reduce_str(reduce): + if reduce == "sum": + return "atomic_add" + else: + # TODO: Need to support more reduction type + if reduce is not None: + raise AssertionError("expected: reduce is None") + return None + + device = self.get_device() + if device is None: + raise AssertionError("expected: device is not None") + + if not include_self: + # zero out the corresponding elements first + zero_out = ir.Scatter( + device=device, + dtype=self.get_dtype(), + inner_fn=lambda index: ops.constant(0, self.get_dtype()), + ranges=index.get_size(), + output_indexer=output_indexer, + scatter_mode=None, + ) + buffer = ir.ComputedBuffer( + name=None, + layout=ir.MutationLayoutSHOULDREMOVE(self), + data=zero_out, + ) + buffer.name = V.graph.register_buffer(buffer) + V.graph.register_operation(buffer) + + # self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0 + # self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 + # self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2 + scatter = ir.Scatter( + device=device, + dtype=self.get_dtype(), + inner_fn=fn, + ranges=index.get_size(), + output_indexer=output_indexer, + scatter_mode=backend_reduce_str(reduce), + ) + buffer = ir.ComputedBuffer( + name=None, + layout=ir.MutationLayoutSHOULDREMOVE(self), + data=scatter, + ) + buffer.name = V.graph.register_buffer(buffer) + V.graph.register_operation(buffer) + + if ndim == 0: + self = view(self, []) + return self + + +def upsample_nearestnd( + x, + output_size, + scales_x: tuple[float | None, ...], + n: int = 2, + exact: bool = False, +): + x.realize_hint() # elements are reused + x_loader = x.make_loader() + i_sizes = x.get_size()[-n:] + batch = x.get_size()[:-n] + i_sizes = [V.graph.sizevars.guard_int(i) for i in i_sizes] + + if len(scales_x) != n: + raise AssertionError("expected: len(scales_x) == n") + o_sizes = output_size + + inv_scales = [i / o for i, o in zip(i_sizes, o_sizes)] + for i, scale in enumerate(scales_x): + if scale is not None: + inv_scales[i] = 1.0 / scale + + def scale_fn(x, scale, size): + # Nearest Exact: input_index = round(scale * (output_index + 0.5) - 0.5) + # = floor(scale * (output_index + 0.5)) + # Nearest: input_index = floor(scale * output_index) + x = ops.index_expr(x, torch.float32) + if exact: + x = ops.add(x, ops.constant(0.5, torch.float32)) + x = ops.mul(x, ops.constant(scale, torch.float32)) + x = ops.to_dtype(x, torch.int32) + return ops.indirect_indexing(x, size, check=False) + + def fn(idx): + x = idx[-n:] + b = idx[:-n] + return x_loader( + [*b, *[scale_fn(i, s, size) for i, s, size in zip(x, inv_scales, i_sizes)]] + ) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=fn, + ranges=[*batch, *o_sizes], + ) + + +@register_lowering(aten.upsample_nearest1d.default) +def upsample_nearest1d(x, output_size, scales: float | None = None): + return upsample_nearestnd(x, output_size, (scales,), n=1) + + +@register_lowering(aten._upsample_nearest_exact1d.default) +def _upsample_nearest_exact1d(x, output_size, scales: float | None = None): + return upsample_nearestnd(x, output_size, (scales,), n=1, exact=True) + + +@register_lowering(aten.upsample_nearest2d.default) +def upsample_nearest2d( + x, output_size, scales_h: float | None = None, scales_w: float | None = None +): + return upsample_nearestnd(x, output_size, (scales_h, scales_w), n=2) + + +@register_lowering(aten._upsample_nearest_exact2d.default) +def _upsample_nearest_exact2d( + x, output_size, scales_h: float | None = None, scales_w: float | None = None +): + return upsample_nearestnd(x, output_size, (scales_h, scales_w), n=2, exact=True) + + +@register_lowering(aten.upsample_nearest3d.default) +def upsample_nearest3d( + x, + output_size, + scales_d: float | None = None, + scales_h: float | None = None, + scales_w: float | None = None, +): + return upsample_nearestnd(x, output_size, (scales_d, scales_h, scales_w), n=3) + + +@register_lowering(aten._upsample_nearest_exact3d.default) +def _upsample_nearest_exact3d( + x, + output_size, + scales_d: float | None = None, + scales_h: float | None = None, + scales_w: float | None = None, +): + return upsample_nearestnd( + x, output_size, (scales_d, scales_h, scales_w), n=3, exact=True + ) + + +def _create_constants(*args, dtype): + return tuple(ops.constant(a, dtype) for a in args) + + +@register_lowering(prims.rev.default) +def rev(x, dims): + # note - dims pre-canonicalized + x_loader = x.make_loader() + sizes = x.get_size() + + def loader(idx): + idx = list(idx) + if len(idx) != len(sizes): + raise AssertionError("expected: len(idx) == len(sizes)") + for dim in dims: + idx[dim] = (sizes[dim] - 1) - idx[dim] + + return x_loader(idx) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=loader, + ranges=sizes, + ) + + +def inplace_constant_pad_nd( + x: TensorBox, padding: Sequence[int], fill_value: float +) -> TensorBox | None: + """ + This optimization changes the semantics of padding from 'clone' + style to 'view' style. + + Thanks to functionalization, this change can still maintain numerical + correctness. + """ + + def _padding_can_be_fused(): + """ + Conservatively check if padding can be fused with downstream op. + 1. if the downstream op is a sum, then there is little benefit to + do inplace padding + 2. if the downstream op is a matmul, doing inplace padding can + save membw. + """ + current_node = V.graph.current_node + if current_node is None: + return True # be conservative + users = tuple(current_node.users) + if len(users) == 1 and users[0].target in ( + aten.mm.default, + aten.addmm.default, + ): + return False + + return True # be conservative + + if _padding_can_be_fused(): + return None + + # Only handle 2D case for now + if len(padding) != 4 or len(x.get_size()) != 2: + return None + + # No harm to realize since we already know that + # the op can not be fused into the single user. + # It need to be realized later anyways. + x.realize() + + # If x is a view (e.g. a SliceView), realizing it just realizing the + # underlying storage. x itself is still a view. + if ( + not isinstance(x, ir.TensorBox) + or not isinstance(x.data, ir.StorageBox) + or not ( + isinstance(x.data.data, ir.ComputedBuffer) + or ( + config.can_inplace_pad_graph_input + and isinstance(x.data.data, ir.InputBuffer) + ) + ) + or not x.data.data.name + ): + return None + x.freeze_layout() + + _, layout = ir.as_storage_and_layout(x) + strides = layout.stride + if strides[1] != 1: + return None + + if padding[0] != 0 or padding[2] != 0 or padding[3] != 0: + return None + + npad = padding[1] + if npad == 0: + return None + + stride0 = strides[0] + rowsize = layout.size[1] + + if stride0 < rowsize + npad: + return None + + bufname = x.data.data.name + padded_size = [layout.size[0], layout.size[1] + npad] + V.graph.buffer_to_padded_size[bufname] = padded_size + resized_x = as_strided( + x, + padded_size, + layout.stride, + layout.offset, + storage_offset_relative_to_input_storage=False, + ) + + sliced_x = slice_(resized_x, dim=1, start=rowsize, end=rowsize + npad, clamp=False) + fill_(sliced_x, fill_value) + + counters["inductor"]["inplace_padding"] += 1 + return resized_x + + +def _pad_as_cat( + x: TensorBox, padding: Sequence[int], fill_value: float +) -> TensorBox | None: + """Decompose right-pad into cat([x, fill], dim) and delegate to cat lowering. + + The cat lowering already has heuristics for choosing between pointwise_cat + (fusion) and ConcatKernel (memory planning / zero-copy). By routing through + cat() we reuse those heuristics rather than duplicating them here. + """ + # Bail out for symbolic padding, dynamic shapes + if not all(isinstance(p, int) for p in padding): + return None + + sizes = x.get_size() + ndim = len(sizes) + pad_pairs = list(zip(padding[::2], padding[1::2])) + + # Only support single-dimension right-pad + pad_dim = None + pad_amount = None + for i, (left, right) in enumerate(pad_pairs): + if left != 0: + return None + if right > 0: + if pad_dim is not None: + return None # multi-dim pad + pad_dim = ndim - 1 - i # padding format is reversed dim order + pad_amount = right + elif right < 0: + return None # trim, not pad + + if pad_dim is None: + return None + + # CPU cat always uses ConcatKernel (no pointwise_cat), which adds + # extra kernel launches for the fill. Skip pad-as-cat on CPU. + device = x.get_device() + if device is not None and device.type == "cpu": + return None + + # Build the fill tensor for the padding region + pad_shape = list(sizes) + pad_shape[pad_dim] = pad_amount + dtype = x.get_dtype() + fill_value_typed = dtype_to_type(dtype)(fill_value) + pad_tensor = tensor_constructor(fill_value_typed)( + pad_shape, dtype=dtype, device=device + ) + + counters["inductor"]["pad_rewritten_as_cat"] += 1 + return cat([x, pad_tensor], pad_dim) + + +@register_lowering(aten.constant_pad_nd, type_promotion_kind=None) +def constant_pad_nd(x, padding, fill_value=0): + if len(padding) % 2 != 0: + raise AssertionError("expected: (len(padding) % 2) == 0") + if all(p == 0 for p in padding): + return clone(x) + + if config.inplace_padding: + out = inplace_constant_pad_nd(x, padding, fill_value) + if out: + return out + # fall through if can not inplace the padding + + out = _pad_as_cat(x, padding, fill_value) + if out is not None: + return out + + sizes = x.get_size() + + bounds = list(reversed(list(zip(padding[::2], padding[1::2])))) + n = len(sizes) - len(bounds) + + # if padding is a complicated expression, hoist it + bounds_precomp: list[tuple[sympy.Symbol, Any]] = [] + for l, h in bounds: + bounds_precomp.append((V.graph.sizevars.lookup_precomputed_size(l), h)) # type: ignore[arg-type] + + output_size = list(sizes[:n]) + mask_sizes = [] + for (low, high), size in zip(bounds, sizes[n:]): + mask_sizes.append(size) + output_size.append(sympy.expand(size + low + high)) + if len(output_size) != len(sizes): + raise AssertionError("expected: len(output_size) == len(sizes)") + fill_value = dtype_to_type(x.get_dtype())(fill_value) + + def mask(index): + mask = [] + for idx, (low, high), length in zip(index[n:], bounds, mask_sizes): + if low != 0: + mask.append(range_mask_low(idx, 0)) + if high != 0: + mask.append(range_mask_high(idx, length)) + mask = functools.reduce(ops.and_, mask) + return ops.masked(mask, lambda: x_loader(index), fill_value) + + def offset_fn(index): + new_index = list(index[:n]) + for idx, (low, _high) in zip(index[n:], bounds_precomp): + new_index.append(idx - low) + if len(new_index) != len(index): + raise AssertionError("expected: len(new_index) == len(index)") + return mask(new_index) + + x_loader = x.make_loader() + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=offset_fn, + ranges=output_size, + ) + + +def range_mask_low(i: sympy.Expr, low: sympy.Expr | int): + return ops.ge( + ops.index_expr(i, torch.int64), + ops.index_expr(sympy.Integer(low), torch.int64), + ) + + +def range_mask_high(i: sympy.Expr, high: sympy.Expr): + return ops.lt( + ops.index_expr(i, torch.int64), + ops.index_expr(high, torch.int64), + ) + + +def range_mask(i: sympy.Expr, high: sympy.Expr, low: sympy.Expr): + return ops.and_( + range_mask_low(i, low), + range_mask_high(i, high), + ) + + +def constant_boundary_condition( + x, fill_value, padding=None, pad_fill_value=1.0, dim=None +): + h = x.get_size()[-dim:] + x_loader = x.make_loader() + # pyrefly: ignore [unsupported-operation] + padding_h = padding or [0] * dim + + def load(index): + prefix = index[:-dim] + ih = index[-dim:] + + mask = functools.reduce( + ops.and_, + # pyrefly: ignore [bad-argument-type, no-matching-overload] + [range_mask(ih[i], h[i] + padding_h[i], -padding_h[i]) for i in range(dim)], + ) + return ( + ops.masked( + mask, + lambda: constant_boundary_condition(x, pad_fill_value, dim=dim)( + [*prefix, *ih] + ), + fill_value, + ) + if padding + else ops.masked(mask, lambda: x_loader([*prefix, *ih]), fill_value) + ) + + return load + + +def pooling_size(x, i, kernel_size, stride, padding, ceil_mode, *, dilation=None): + if dilation is None: + dilation = [1] * len(padding) + + x_out = FloorDiv( + x + 2 * padding[i] - dilation[i] * (kernel_size[i] - 1) + (stride[i] - 1), + stride[i], + ) + + if ceil_mode: + x_alt = FloorDiv( + x + + 2 * padding[i] + - dilation[i] * (kernel_size[i] - 1) + + 2 * (stride[i] - 1), + stride[i], + ) + if V.graph.sizevars.guard_or_false( + sympy.Ge((x_alt - 1) * stride[i] - x - padding[i], 0) + ): + # Sliding windows must start within the input or left padding + x_alt -= 1 # type: ignore[assignment] + if V.graph.sizevars.guard_or_false(sympy.Eq(x_out, x_alt)): + # ceil mode is actually a no-op, lets guard on that + ceil_mode = False + else: + x_out = x_alt + return x_out, ceil_mode + + +def should_fallback_max_pool_with_indices(kernel_size, *, n_dim): + kernel_size = pad_listlike(kernel_size, n_dim) + window_size = functools.reduce(operator.mul, kernel_size) + return window_size > 25 + + +def max_pool_checks( + x, kernel_size, stride, padding, dilation, n_dim, *, assert_fallback=None +): + if padding == 0: + padding = [0] * n_dim + if dilation == 1: + dilation = [1] * n_dim + if not stride: + stride = kernel_size + + kernel_size = pad_listlike(kernel_size, n_dim) + stride = pad_listlike(stride, n_dim) + padding = pad_listlike(padding, n_dim) + dilation = pad_listlike(dilation, n_dim) + + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if len(kernel_size) != n_dim: + raise AssertionError("expected: len(kernel_size) == n_dim") + if len(stride) != n_dim: + raise AssertionError("expected: len(stride) == n_dim") + if len(padding) != n_dim: + raise AssertionError("expected: len(padding) == n_dim") + if len(dilation) != n_dim: + raise AssertionError("expected: len(dilation) == n_dim") + if len(x.get_size()) not in (n_dim + 1, n_dim + 2): + raise AssertionError("expected: len(x.get_size()) in (n_dim + 1, n_dim + 2)") + + use_fallback = should_fallback_max_pool_with_indices(kernel_size, n_dim=n_dim) + if assert_fallback is not None: + if use_fallback != assert_fallback: + raise AssertionError("expected: use_fallback == assert_fallback") + + return kernel_size, stride, padding, dilation, use_fallback + + +def _max_pool_with_offsets( + x, + kernel_size, + stride, + padding, + dilation, + ceil_mode, + *, + n_dim, +): + x.realize_hint() + batch = x.shape[:-n_dim] + dhw = x.shape[-n_dim:] + + dhw_out, ceil_mode = zip( + *[ + pooling_size( + dhw[d], d, kernel_size, stride, padding, ceil_mode, dilation=dilation + ) + for d in range(n_dim) + ] + ) + + dtype = x.dtype + min_value = ( + False + if dtype is torch.bool + else (float("-inf") if dtype.is_floating_point else torch.iinfo(dtype).min) + ) + + new_size = list(batch) + list(dhw_out) + if any(padding) or any(ceil_mode) or any(d > 1 for d in dilation): + x_loader = constant_boundary_condition(x, min_value, dim=n_dim) + else: + x_loader = x.make_loader() + + def fn_inner(idx, reduction_idx): + prefix = idx[:-n_dim] + bh = idx[-n_dim:] + ih = [ + (bh[i] * stride[i]) + (reduction_idx[i] * dilation[i]) - padding[i] + for i in range(n_dim) + ] + return x_loader([*prefix, *ih]) + + result = Reduction.create( + reduction_type="max", + input_node=x, + device=x.get_device(), + dst_dtype=dtype, + src_dtype=dtype, + inner_fn=fn_inner, + ranges=new_size, + reduction_ranges=kernel_size, + ) + offsets = Reduction.create( + reduction_type="argmax", + input_node=x, + device=x.get_device(), + dst_dtype=torch.int64, + src_dtype=dtype, + inner_fn=fn_inner, + ranges=new_size, + reduction_ranges=kernel_size, + ) + if isinstance(result.data.data, Reduction): # type: ignore[attr-defined, union-attr] + # Only realize if reduction isn't unrolled + result.realize() + if isinstance(offsets.data.data, Reduction): # type: ignore[attr-defined, union-attr] + # Only realize if reduction isn't unrolled + offsets.realize() + + return result, offsets + + +@register_lowering(prims._low_memory_max_pool_with_offsets, type_promotion_kind=None) +def _low_memory_max_pool_with_offsets( + x, + kernel_size, + stride, + padding, + dilation, + ceil_mode=False, +): + n_dim = len(kernel_size) + + # assert we are not on a fallback path, the inductor decomp should have guaranteed this + kernel_size, stride, padding, dilation, _ = max_pool_checks( + x, + kernel_size, + stride, + padding, + dilation, + n_dim, + assert_fallback=False, + ) + + with config.patch(unroll_reductions_threshold=25): + result, offsets = _max_pool_with_offsets( + x, + kernel_size, + stride, + padding, + dilation, + ceil_mode, + n_dim=n_dim, + ) + return result, to_dtype(offsets, torch.int8) + + +def _pool_offsets_to_indices( + offsets: TensorBox, + kernel_size: Sequence[int | torch.SymInt], + input_size: Sequence[int | torch.SymInt], + increments_to_index: Callable[ + [Sequence[int | torch.SymInt], Sequence[int | torch.SymInt]], + torch._inductor.virtualized.OpsValue, + ], +) -> TensorBox: + n_dim = len(kernel_size) + offsets_loader = offsets.make_loader() + window_size = sympy.sympify(functools.reduce(operator.mul, kernel_size)) + + def offsets_to_indices(idx): + offset = offsets_loader(idx) + offset_sympy = ops.indirect_indexing(offset, window_size) + reduction_idx = inductor_prims._flattened_index_to_nd(offset_sympy, kernel_size) + idhw = increments_to_index(idx, reduction_idx) + return ops.index_expr( + inductor_prims._flatten_index(idhw, input_size[-n_dim:]), torch.int64 + ) + + indices = Pointwise.create( + device=offsets.get_device(), + dtype=torch.int64, + inner_fn=offsets_to_indices, + ranges=offsets.get_size(), + ) + return indices + + +@register_lowering( + prims._low_memory_max_pool_offsets_to_indices, type_promotion_kind=None +) +def _low_memory_max_pool_offsets_to_indices( + offsets, kernel_size, input_size, stride, padding, dilation +): + # TODO: Generalize to other max pooling flavors + n_dim = len(kernel_size) + + def increments_to_index(idx, reduction_idx): + bh = idx[-n_dim:] + return [ + (bh[i] * stride[i]) + (reduction_idx[i] * dilation[i]) - padding[i] + for i in range(n_dim) + ] + + return _pool_offsets_to_indices( + offsets, kernel_size, input_size, increments_to_index + ) + + +def _max_pool_with_indices( + x, + kernel_size, + stride, + padding, + dilation, + ceil_mode, + n_dim, +): + kernel_size, stride, padding, dilation, _ = max_pool_checks( + x, kernel_size, stride, padding, dilation, n_dim=n_dim + ) + + out, offsets = _max_pool_with_offsets( + x, kernel_size, stride, padding, dilation, ceil_mode, n_dim=n_dim + ) + + indices = _low_memory_max_pool_offsets_to_indices( + offsets, + kernel_size, + x.shape[-n_dim:], + stride, + padding, + dilation, + ) + + return out, indices + + +# Fallback when we do not decompose to the low-memory path. +@register_lowering(aten.max_pool2d_with_indices, type_promotion_kind=None) +def max_pool2d_with_indices( + x, + kernel_size, + stride=None, + padding=0, + dilation=1, + ceil_mode=False, +): + return _max_pool_with_indices( + x, kernel_size, stride, padding, dilation, ceil_mode, n_dim=2 + ) + + +# Fallback when we do not decompose to the low-memory path. +@register_lowering(aten.max_pool3d_with_indices, type_promotion_kind=None) +def max_pool3d_with_indices( + x, + kernel_size, + stride=None, + padding=0, + dilation=1, + ceil_mode=False, +): + return _max_pool_with_indices( + x, kernel_size, stride, padding, dilation, ceil_mode, n_dim=3 + ) + + +fallback_max_pool2d_with_indices_backward = fallback_handler( + aten.max_pool2d_with_indices_backward.default, + add_to_fallback_set=False, +) + + +@register_lowering(aten.max_pool2d_with_indices_backward, type_promotion_kind=None) +def max_pool2d_with_indices_backward( + grad_output, x, kernel_size, stride, padding, dilation, ceil_mode, indices +): + if x.get_device().type == "xpu": + return fallback_max_pool2d_with_indices_backward( + grad_output, x, kernel_size, stride, padding, dilation, ceil_mode, indices + ) + + if padding == 0: + padding = [0, 0] + if dilation == 1: + dilation = [1, 1] + if not stride: + stride = kernel_size + + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if len(kernel_size) != 2: + raise AssertionError("expected: len(kernel_size) == 2") + if len(stride) != 2: + raise AssertionError("expected: len(stride) == 2") + if len(padding) != 2: + raise AssertionError("expected: len(padding) == 2") + if len(dilation) != 2: + raise AssertionError("expected: len(dilation) == 2") + if len(x.get_size()) not in (3, 4): + raise AssertionError("expected: len(x.get_size()) in (3, 4)") + + # we will read this many times, so make sure it is computed + grad_output.realize_hint() + gO_stride = grad_output.maybe_get_stride() + x_stride: Sequence[Any] | None + if isinstance(x, TensorBox) and isinstance(x.data.data, Pointwise): # type: ignore[attr-defined] + data = x.data.data # type: ignore[attr-defined] + device = data.get_device() + if device is None: + raise AssertionError("expected: device is not None") + x_buffer = ir.ComputedBuffer( + name=None, + layout=ir.FlexibleLayout( + device=device, + dtype=data.get_dtype(), + size=data.get_size(), + ), + data=data, + ) + x_buffer.decide_layout() + x_stride = x_buffer.get_stride() + else: + x_stride = x.maybe_get_stride() + + is_channels_last = (x_stride is not None and x_stride[1] == 1) or ( + gO_stride is not None and gO_stride[1] == 1 + ) + if any(d != 1 for d in dilation): + # dilation NYI + return fallback_max_pool2d_with_indices_backward( + grad_output, x, kernel_size, stride, padding, dilation, ceil_mode, indices + ) + + *_batch, _height, width = x.get_size() + *_, pooled_height, pooled_width = grad_output.get_size() + + indices_loader = indices.make_loader() + grad_loader = grad_output.make_loader() + new_size = list(x.get_size()) + + h_window_size = max( + max(FloorDiv(h, stride[0]) - max(0, FloorDiv(h - kernel_size[0], stride[0])), 1) + for h in range(kernel_size[0] * 2) + ) + w_window_size = max( + max(FloorDiv(w, stride[1]) - max(0, FloorDiv(w - kernel_size[1], stride[1])), 1) + for w in range(kernel_size[1] * 2) + ) + + window_size = h_window_size * w_window_size + + if window_size > 25: + # Kernel size too big. Results in hard-to-optimize Triton code. Use fallback. + return fallback_max_pool2d_with_indices_backward( + grad_output, x, kernel_size, stride, padding, dilation, ceil_mode, indices + ) + + indices_size = indices.get_size() + + def fn(idx): + *prefix, h, w = idx + index_test = ops.index_expr(h * width + w, torch.int32) + h = h + padding[0] + w = w + padding[1] + phstart = ops.index_expr( + FloorDiv(h - kernel_size[0] + stride[0], stride[0]), torch.int32 + ) + pwstart = ops.index_expr( + FloorDiv(w - kernel_size[1] + stride[1], stride[1]), torch.int32 + ) + phend = ops.index_expr(FloorDiv(h, stride[0]) + 1, torch.int32) + pwend = ops.index_expr(FloorDiv(w, stride[1]) + 1, torch.int32) + + phstart = ops.maximum(phstart, ops.constant(0, torch.int32)) + pwstart = ops.maximum(pwstart, ops.constant(0, torch.int32)) + phend = ops.minimum(phend, ops.index_expr(pooled_height, torch.int32)) + pwend = ops.minimum(pwend, ops.index_expr(pooled_width, torch.int32)) + + gradient = None + for ph_ in range(h_window_size): + for pw_ in range(w_window_size): + ph = ops.add(phstart, ops.constant(ph_, torch.int32)) + pw = ops.add(pwstart, ops.constant(pw_, torch.int32)) + grad_index = [ + *prefix, + ops.indirect_indexing( + ops.minimum(ph, ops.sub(phend, ops.constant(1, torch.int32))), + indices_size[-2], + check=False, + ), + ops.indirect_indexing( + ops.minimum(pw, ops.sub(pwend, ops.constant(1, torch.int32))), + indices_size[-1], + check=False, + ), + ] + + index_actual = indices_loader(grad_index) + grad_part = grad_loader(grad_index) + check = ops.eq(index_actual, index_test) + + if gradient is None: + # don't need mask for 0, 0 + gradient = ops.where( + check, grad_part, ops.constant(0.0, torch.float32) + ) + else: + mask = ops.and_( + ops.and_( + ops.lt(ph, phend), + ops.lt(pw, pwend), + ), + check, + ) + gradient = ops.where(mask, ops.add(gradient, grad_part), gradient) + if gradient is None: + raise AssertionError("expected: gradient is not None") + return gradient + + out = Pointwise.create( + device=grad_output.get_device(), + dtype=grad_output.get_dtype(), + inner_fn=fn, + ranges=new_size, + ) + if is_channels_last: + return ir.ExternKernel.require_channels_last(out) + else: + return out + + +def pad_adaptive_loader(x, pad_val=0.0): + x_loader = x.make_loader() + + def load(prefix, increments, start_indices, end_indices): + ih, iw = increments + h_start_index, w_start_index = start_indices + h_end_index, w_end_index = end_indices + + mask = ops.and_( + ops.lt( + ops.index_expr(h_start_index + ih, torch.int64), + ops.index_expr(h_end_index, torch.int64), + ), + ops.lt( + ops.index_expr(w_start_index + iw, torch.int64), + ops.index_expr(w_end_index, torch.int64), + ), + ) + + return ops.masked( + mask, + lambda: x_loader([*prefix, h_start_index + ih, w_start_index + iw]), + pad_val, + ) + + return load + + +def compute_indices_adaptive_pooling(start_index, end_index, h_in, w_in, h_out, w_out): + h_start_index = functools.partial(start_index, out_dim=h_out, inp_dim=h_in) + h_end_index = functools.partial(end_index, out_dim=h_out, inp_dim=h_in) + + w_start_index = functools.partial(start_index, out_dim=w_out, inp_dim=w_in) + w_end_index = functools.partial(end_index, out_dim=w_out, inp_dim=w_in) + + return h_start_index, h_end_index, w_start_index, w_end_index + + +def _adaptive_pooling_fn( + start_index, end_index, kernel_maxes, in_sizes, out_sizes, pooling_fn +): + h_in, w_in = in_sizes + h_out, w_out = out_sizes + + ( + h_start_index_fn, + h_end_index_fn, + w_start_index_fn, + w_end_index_fn, + ) = compute_indices_adaptive_pooling( + start_index, end_index, h_in, w_in, h_out, w_out + ) + + def fn(idx, loader): + *prefix, bh, bw = idx + + h_start_index = h_start_index_fn(bh) + h_end_index = h_end_index_fn(bh) + + w_start_index = w_start_index_fn(bw) + w_end_index = w_end_index_fn(bw) + + result = None + for ih, iw in itertools.product(range(kernel_maxes[0]), range(kernel_maxes[1])): + val = loader( + prefix, + [ih, iw], + [h_start_index, w_start_index], + [h_end_index, w_end_index], + ) + if result is None: + result = val + else: + result = pooling_fn(val, result) + return result + + return fn + + +def _adaptive_pooling_fn_with_idx( + start_index, end_index, kernel_maxes, in_sizes, out_sizes, pooling_fn +): + h_in, w_in = in_sizes + h_out, w_out = out_sizes + + ( + h_start_index_fn, + h_end_index_fn, + w_start_index_fn, + w_end_index_fn, + ) = compute_indices_adaptive_pooling( + start_index, end_index, h_in, w_in, h_out, w_out + ) + + def fn(idx, loader): + *prefix, bh, bw = idx + + h_start_index = h_start_index_fn(bh) + h_end_index = h_end_index_fn(bh) + + w_start_index = w_start_index_fn(bw) + w_end_index = w_end_index_fn(bw) + + maxval = None + maxindex = None + for ih, iw in itertools.product(range(kernel_maxes[0]), range(kernel_maxes[1])): + val = loader( + prefix, + [ih, iw], + [h_start_index, w_start_index], + [h_end_index, w_end_index], + ) + + index = ops.index_expr( + (h_start_index + ih) * w_in + w_start_index + iw, torch.int64 + ) + + if maxindex is None: + maxindex = index + else: + maxindex = ops.where(ops.gt(val, maxval), index, maxindex) + + if maxval is None: + maxval = val + else: + maxval = pooling_fn(val, maxval) + + return maxindex + + return fn + + +fallback_adaptive_avg_pool2d = fallback_handler( + aten._adaptive_avg_pool2d.default, add_to_fallback_set=False +) + + +@register_lowering(aten._adaptive_avg_pool2d) +def _adaptive_avg_pool2d(x, output_size): + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if len(output_size) != 2: + raise AssertionError("expected: len(output_size) == 2") + x.realize_hint() + + *batch, h_in, w_in = x.get_size() + + h_in = V.graph.sizevars.guard_int(h_in) + w_in = V.graph.sizevars.guard_int(w_in) + + h_out, w_out = output_size + + if h_out == 0 or w_out == 0: + o_size = [*batch, h_out, w_out] + return empty(o_size, dtype=x.get_dtype(), device=x.get_device()) + + if x.get_dtype() == torch.int64: + # not supported in eager + raise RuntimeError("'adaptive_avg_pool2d' not implemented for 'Long'") + + # no-op if the same input and output + if h_in == h_out and w_in == w_out: + return clone(x) + + if h_in % h_out == 0 and w_in % w_out == 0: + kernel_size = [FloorDiv(h_in, h_out), FloorDiv(w_in, w_out)] + return avg_pool2d(x, kernel_size) + + h_kernel_max = ceildiv((h_in + h_out - 1), h_out) + w_kernel_max = ceildiv((w_in + w_out - 1), w_out) + + new_size = list(batch) + [h_out, w_out] + dtype = x.get_dtype() + + window_size = h_kernel_max * w_kernel_max + if V.graph.sizevars.guard_or_true(sympy.Gt(window_size, 25)): + # Kernel size too big. Results in hard-to-optimize Triton code. Use fallback. + return fallback_adaptive_avg_pool2d(x, output_size) + + h_kernel_max = V.graph.sizevars.guard_int(h_kernel_max) + w_kernel_max = V.graph.sizevars.guard_int(w_kernel_max) + + def start_index(index, out_dim, inp_dim): + return FloorDiv((index * inp_dim), out_dim) + + def end_index(index, out_dim, inp_dim): + return FloorDiv((index + 1) * inp_dim + out_dim - 1, out_dim) + + fn_sum = _adaptive_pooling_fn( + start_index=start_index, + end_index=end_index, + kernel_maxes=[h_kernel_max, w_kernel_max], + in_sizes=[h_in, w_in], + out_sizes=[h_out, w_out], + pooling_fn=ops.add, + ) + + ones_loader = pad_adaptive_loader(ones_like(x)) + + def fn(idx): + return ops.truediv( + fn_sum(idx, pad_adaptive_loader(x)), fn_sum(idx, ones_loader) + ) + + rv = Pointwise.create( + device=x.get_device(), + dtype=dtype, + inner_fn=fn, + ranges=new_size, + ) + # TODO: should we force these to be realized? + return rv + + +fallback_adaptive_max_pool2d = fallback_handler( + aten.adaptive_max_pool2d.default, add_to_fallback_set=False +) + + +@register_lowering(aten.adaptive_max_pool2d) +def adaptive_max_pool2d(x, output_size): + if x.get_dtype() == torch.int64: + # not supported in eager + raise RuntimeError("adaptive_max_pool2d not implemented for Long") + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if len(output_size) != 2: + raise AssertionError("expected: len(output_size) == 2") + x.realize_hint() + + *batch, h_in, w_in = x.get_size() + + h_in = V.graph.sizevars.guard_int(h_in) + w_in = V.graph.sizevars.guard_int(w_in) + + h_out, w_out = output_size + + if h_out == 0 or w_out == 0: + o_size = [*batch, h_out, w_out] + return empty(o_size, dtype=x.get_dtype(), device=x.get_device()), empty( + o_size, dtype=torch.int64, device=x.get_device() + ) + + if h_in % h_out == 0 and w_in % w_out == 0: + # This is handled by a decomposition + raise ValueError + + h_kernel_max = ceildiv((h_in + h_out - 1), h_out) + w_kernel_max = ceildiv((w_in + w_out - 1), w_out) + + new_size = list(batch) + [h_out, w_out] + dtype = x.get_dtype() + + window_size = h_kernel_max * w_kernel_max + if window_size > 25: + # Kernel size too big. Results in hard-to-optimize Triton code. Use fallback. + return fallback_adaptive_max_pool2d(x, output_size) + + def start_index(index, out_dim, inp_dim): + return FloorDiv((index * inp_dim), out_dim) + + def end_index(index, out_dim, inp_dim): + return FloorDiv((index + 1) * inp_dim + out_dim - 1, out_dim) + + inner_func_max_val = _adaptive_pooling_fn( + start_index=start_index, + end_index=end_index, + kernel_maxes=[h_kernel_max, w_kernel_max], + in_sizes=[h_in, w_in], + out_sizes=[h_out, w_out], + pooling_fn=ops.maximum, + ) + + inner_func_max_idx = _adaptive_pooling_fn_with_idx( + start_index=start_index, + end_index=end_index, + kernel_maxes=[h_kernel_max, w_kernel_max], + in_sizes=[h_in, w_in], + out_sizes=[h_out, w_out], + pooling_fn=ops.maximum, + ) + + def inner_fn_max_val(idx): + return inner_func_max_val(idx, pad_adaptive_loader(x, float("-inf"))) + + def inner_fn_max_idx(idx): + return inner_func_max_idx(idx, pad_adaptive_loader(x, float("-inf"))) + + rv = Pointwise.create( + device=x.get_device(), + dtype=dtype, + inner_fn=inner_fn_max_val, + ranges=new_size, + ) + ri = Pointwise.create( + device=x.get_device(), + dtype=torch.int64, + inner_fn=inner_fn_max_idx, + ranges=new_size, + ) + return rv, ri + + +def _fractional_pooling_offsets(samples, in_sz, out_sz, kernel_sz, dim, ndims): + out_sz = out_sz[dim] + in_sz = in_sz[dim] + kernel_sz = kernel_sz[dim] + samples_loader = samples.make_loader() + + def load(prefix, i): + # Handle indexing for samples tensor correctly for different input dimensions + # samples tensor always has shape (N, C, 2) for fractional_max_pool2d where: + # - N=1 for 3D inputs (C,H,W), N=batch_size for 4D inputs (N,C,H,W) + # - C=num_channels + # - 2 for the two spatial dimensions (height, width) + samples_shape = samples.get_size() + + if len(samples_shape) == 3: # Expected: (N, C, 2) + if len(prefix) == 1: + # 3D input case: prefix=(channel,), samples=(1, C, 2) + # Access: samples[0, channel, dim] + sample = samples_loader([0, prefix[0], ndims - 1 - dim]) + elif len(prefix) >= 2: + # 4D+ input case: prefix=(batch, channel, ...), samples=(batch, C, 2) + # Access: samples[batch, channel, dim] + sample = samples_loader([prefix[0], prefix[1], ndims - 1 - dim]) + else: + # Edge case - shouldn't happen for valid fractional pooling + sample = samples_loader([0, 0, ndims - 1 - dim]) + else: + # Fallback for unexpected tensor shapes + sample = samples_loader([*prefix, ndims - 1 - dim]) + i_expr = ops.index_expr(i, samples.get_dtype()) + diff = ops.index_expr(in_sz - kernel_sz, torch.int64) + out_sz_expr = ops.index_expr(out_sz - 1, torch.int64) + alpha = ops.truediv( + ops.to_dtype(diff, torch.float64), ops.to_dtype(out_sz_expr, torch.float64) + ) + alpha = ops.where(ops.eq(out_sz_expr, 0), 0, alpha) + seq_i = ops.trunc((i_expr + sample) * alpha) - ops.trunc(sample * alpha) + seq_i = ops.to_dtype(seq_i, torch.int64) + mask = ops.lt(i_expr, out_sz_expr) + return ops.indirect_indexing(ops.where(mask, seq_i, diff), sympy.sympify(in_sz)) + + return load + + +@register_lowering(aten.fractional_max_pool2d) +def fractional_max_pool2d(x, kernel_size, output_size, random_samples): + return _fractional_max_pool(x, kernel_size, output_size, random_samples, n_dim=2) + + +@register_lowering(aten.fractional_max_pool3d) +def fractional_max_pool3d(x, kernel_size, output_size, random_samples): + return _fractional_max_pool(x, kernel_size, output_size, random_samples, n_dim=3) + + +def _fractional_max_pool(x, kernel_size, output_size, random_samples, n_dim): + x.realize_hint() + batch, inp_dhw = x.shape[:-n_dim], x.shape[-n_dim:] + + with config.patch(unroll_reductions_threshold=25): + dhw_index_fn = [ + _fractional_pooling_offsets( + samples=random_samples, + in_sz=inp_dhw, + out_sz=output_size, + kernel_sz=kernel_size, + ndims=n_dim, + dim=d, + ) + for d in range(n_dim) + ] + + x_loader = x.make_loader() + + def fn_inner(idx, reduction_idx): + prefix = idx[:-n_dim] + return x_loader([*prefix, *increments_to_index(idx, reduction_idx)]) + + def increments_to_index(idx, reduction_idx): + prefix = idx[:-n_dim] + bdhw = idx[-n_dim:] + return [ + dhw_index_fn[d](prefix, bdhw[d]) + reduction_idx[d] + for d in range(n_dim) + ] + + new_size = list(batch) + list(output_size) + dtype = x.get_dtype() + result = Reduction.create( + reduction_type="max", + input_node=x, + device=x.get_device(), + dst_dtype=dtype, + src_dtype=dtype, + inner_fn=fn_inner, + ranges=new_size, + reduction_ranges=kernel_size, + ) + offsets = Reduction.create( + reduction_type="argmax", + input_node=x, + device=x.get_device(), + dst_dtype=torch.int64, + src_dtype=dtype, + inner_fn=fn_inner, + ranges=new_size, + reduction_ranges=kernel_size, + ) + if not (isinstance(result, TensorBox)): + raise AssertionError(result) + if isinstance(result.data.data, Reduction): # type: ignore[attr-defined] + # Only realize if reduction isn't unrolled + result.realize() + if not (isinstance(offsets, TensorBox)): + raise AssertionError(offsets) + if isinstance(offsets.data.data, Reduction): # type: ignore[attr-defined] + # Only realize if reduction isn't unrolled + offsets.realize() + + indices = _pool_offsets_to_indices( + offsets, kernel_size, x.shape, increments_to_index + ) + return result, indices + + +@register_lowering(aten.upsample_nearest2d_backward.default) +def upsample_nearest2d_backward( + x, output_size=None, input_size=None, scales_h=None, scales_w=None +): + x.realize_hint() + + *_batch, inp_h, inp_w = x.get_size() + inp_h = V.graph.sizevars.guard_int(inp_h) + inp_w = V.graph.sizevars.guard_int(inp_w) + + # pyrefly: ignore [not-iterable] + *_batch, out_h, out_w = input_size + + if inp_h % out_h == 0 and inp_w % out_w == 0: + return avg_pool2d( + x, [FloorDiv(inp_h, out_h), FloorDiv(inp_w, out_w)], divisor_override=1 + ) + + h_kernel_max = ceildiv(inp_h, out_h) + w_kernel_max = ceildiv(inp_w, out_w) + + def start_index(index, out_dim, inp_dim): + return CeilDiv(index * inp_dim, sympy.sympify(out_dim)) + + def end_index(index, out_dim, inp_dim): + return start_index((index + 1), out_dim, inp_dim) + + fn_sum = _adaptive_pooling_fn( + start_index=start_index, + end_index=end_index, + kernel_maxes=[h_kernel_max, w_kernel_max], + in_sizes=[inp_h, inp_w], + out_sizes=[out_h, out_w], + pooling_fn=ops.add, + ) + + def fn(idx): + return fn_sum(idx, pad_adaptive_loader(x)) + + rv = Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=fn, + # pyrefly: ignore [bad-argument-type, no-matching-overload] + ranges=list(input_size), + ) + + return rv + + +@register_lowering(aten.avg_pool2d, type_promotion_kind=None) +def avg_pool2d( + x, + kernel_size, + stride=(), + padding=0, + ceil_mode=False, + count_include_pad=True, + divisor_override=None, +): + return _avg_poolnd( + x, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override, + dim=2, + ) + + +@register_lowering(aten.avg_pool3d, type_promotion_kind=None) +def avg_pool3d( + x, + kernel_size, + stride=(), + padding=0, + ceil_mode=False, + count_include_pad=True, + divisor_override=None, +): + return _avg_poolnd( + x, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override, + dim=3, + ) + + +fallbacks_avg_poolnd = [ + fallback_handler(aten.avg_pool1d.default, add_to_fallback_set=False), + fallback_handler(aten.avg_pool2d.default, add_to_fallback_set=False), + fallback_handler(aten.avg_pool3d.default, add_to_fallback_set=False), +] + + +def _avg_poolnd( + x, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override, + dim, +): + if not stride: + stride = kernel_size + if not padding: + padding = [0] * dim + kernel_size = pad_listlike(kernel_size, dim) + stride = pad_listlike(stride, dim) + padding = pad_listlike(padding, dim) + + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if len(kernel_size) != dim: + raise AssertionError("expected: len(kernel_size) == dim") + if len(stride) != dim: + raise AssertionError("expected: len(stride) == dim") + if len(padding) != dim: + raise AssertionError("expected: len(padding) == dim") + if len(x.get_size()) not in (dim + 1, dim + 2): + raise AssertionError("expected: len(x.get_size()) in (dim + 1, dim + 2)") + + x.realize_hint() + batch = x.get_size()[:-dim] + h = x.get_size()[-dim:] + + h_out, ceil_modes = zip( + *[ + pooling_size(h[i], i, kernel_size, stride, padding, ceil_mode) + for i in range(dim) + ] + ) + + if any(padding) or any(ceil_modes): + x_loader = constant_boundary_condition(x, 0.0, dim=dim) + had_padding = True + else: + x_loader = x.make_loader() + had_padding = False + + new_size = list(batch) + list(h_out) + dtype = x.get_dtype() + # compute in higher-precision until scaling + output_dtype = get_promoted_dtype( + x, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + return_compute_dtype=True, + ) + + def fn_inner(idx, reduction_idx): + prefix = idx[:-dim] + bh = idx[-dim:] + ih = reduction_idx + ih = [bh[i] * stride[i] + ih[i] - padding[i] for i in range(dim)] + return x_loader([*prefix, *ih]) + + window_size = functools.reduce(operator.mul, kernel_size) + + if window_size > 25 and any( + V.graph.sizevars.statically_known_true(sympy.Ne(k, s)) + for k, s in zip(kernel_size, stride) + ): + fallback = fallbacks_avg_poolnd[dim - 1] + return fallback( + x, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override, + ) + + # TODO: remove this when #100331 is merged. We only do this + # for window_size <=25 to avoid performance regressions compared + # to the previous algorithm which unrolled manually for <=25 + context = ( + config.patch(unroll_reductions_threshold=25) + if window_size <= 25 + else contextlib.nullcontext() + ) + + device = x.get_device() + if device is None: + raise AssertionError("expected: device is not None") + + with context: + rv = Reduction.create( + reduction_type="sum", + input_node=x, + device=device, + dst_dtype=output_dtype, + src_dtype=dtype, + inner_fn=fn_inner, + ranges=new_size, + reduction_ranges=kernel_size, + ) + if hasattr(rv.data, "data") and isinstance(rv.data.data, Reduction): + # Only realize if reduction isn't unrolled + rv.realize() + + if not had_padding or divisor_override: + divisor = divisor_override if divisor_override else window_size + result = div_prim(rv, divisor) + else: + + def fn_count(idx): + bh = idx[-dim:] + + divide_factors = [] + for i in range(dim): + hstart = bh[i] * stride[i] - padding[i] + hend = Min(hstart + kernel_size[i], h[i] + padding[i]) + if not count_include_pad: + hstart = Max(hstart, 0) + hend = Min(hend, h[i]) + factor = ops.index_expr(hend - hstart, torch.int32) + divide_factors.append(factor) + return functools.reduce(ops.mul, divide_factors) + + divide_factor = Pointwise.create( + device=x.get_device(), + dtype=dtype, + inner_fn=fn_count, + ranges=new_size, + ) + result = div_prim(rv, divide_factor) + + return to_dtype(result, dtype) + + +fallback_avg_pool2d_backward = fallback_handler( + aten.avg_pool2d_backward.default, add_to_fallback_set=False +) + + +@register_lowering(aten.avg_pool2d_backward, type_promotion_kind=None) +def avg_pool2d_backward( + grad_output, + x, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override=None, +): + if divisor_override is not None and divisor_override == 0: + raise AssertionError("divisor must be not zero") + if not stride: + stride = kernel_size + if not padding: + padding = [0, 0] + + if not (isinstance(grad_output, TensorBox)): + raise AssertionError("expected: isinstance(grad_output, TensorBox)") + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if len(kernel_size) != 2: + raise AssertionError("expected: len(kernel_size) == 2") + if len(stride) != 2: + raise AssertionError("expected: len(stride) == 2") + if len(padding) != 2: + raise AssertionError("expected: len(padding) == 2") + if len(x.get_size()) not in (3, 4): + raise AssertionError("expected: len(x.get_size()) in (3, 4)") + + grad_output.realize_hint() # we will read this many times, so make sure it is computed + + *_, height, width = x.get_size() + + _h_out, ceil_mode1 = pooling_size( + height, 0, kernel_size, stride, padding, ceil_mode + ) + _w_out, ceil_mode2 = pooling_size(width, 1, kernel_size, stride, padding, ceil_mode) + + grad_loader = grad_output.make_loader() + + had_padding = padding[0] or padding[1] or ceil_mode1 or ceil_mode2 + + *_, pooled_height, pooled_width = grad_output.get_size() + new_size = list(x.get_size()) + dtype = x.get_dtype() + + h_window_size = max( + max(FloorDiv(h, stride[0]) - max(0, FloorDiv(h - kernel_size[0], stride[0])), 1) + for h in range(kernel_size[0] * 2) + ) + w_window_size = max( + max(FloorDiv(w, stride[1]) - max(0, FloorDiv(w - kernel_size[1], stride[1])), 1) + for w in range(kernel_size[1] * 2) + ) + + window_size = h_window_size * w_window_size + if window_size > 25: + # Kernel size too big. Results in hard-to-optimize Triton code. Use fallback. + return fallback_avg_pool2d_backward( + grad_output, + x, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override, + ) + + def compute_pool_size_without_padding(ph, pw): + """ + This computes the scaling factor that we will divide an element + by when `count_include_pad=False` + """ + stride_h = ops.constant(stride[0], torch.int32) + stride_w = ops.constant(stride[1], torch.int32) + pad_h = ops.constant(padding[0], torch.int32) + pad_w = ops.constant(padding[1], torch.int32) + kernel_h = ops.constant(kernel_size[0], torch.int32) + kernel_w = ops.constant(kernel_size[1], torch.int32) + hstart = ops.sub(ops.mul(ph, stride_h), pad_h) + wstart = ops.sub(ops.mul(pw, stride_w), pad_w) + hend = ops.minimum( + ops.add(hstart, kernel_h), + ops.add(ops.index_expr(height, torch.int32), pad_h), + ) + wend = ops.minimum( + ops.add(wstart, kernel_w), + ops.add(ops.index_expr(width, torch.int32), pad_w), + ) + hstart = ops.maximum(hstart, ops.constant(0, torch.int32)) + wstart = ops.maximum(wstart, ops.constant(0, torch.int32)) + hend = ops.minimum(hend, ops.index_expr(height, torch.int32)) + wend = ops.minimum(wend, ops.index_expr(width, torch.int32)) + divide_factor = ops.mul(ops.sub(hend, hstart), ops.sub(wend, wstart)) + return divide_factor + + def fn(idx): + *prefix, h, w = idx + h = h + padding[0] + w = w + padding[1] + phstart = ops.index_expr( + FloorDiv(h - kernel_size[0] + stride[0], stride[0]), torch.int32 + ) + pwstart = ops.index_expr( + FloorDiv(w - kernel_size[1] + stride[1], stride[1]), torch.int32 + ) + phend = ops.index_expr(FloorDiv(h, stride[0]) + 1, torch.int32) + pwend = ops.index_expr(FloorDiv(w, stride[1]) + 1, torch.int32) + + phstart = ops.maximum(phstart, ops.constant(0, torch.int32)) + pwstart = ops.maximum(pwstart, ops.constant(0, torch.int32)) + phend = ops.minimum(phend, ops.index_expr(pooled_height, torch.int32)) + pwend = ops.minimum(pwend, ops.index_expr(pooled_width, torch.int32)) + + gradient = None + for ph_ in range(h_window_size): + for pw_ in range(w_window_size): + ph = ops.add(phstart, ops.constant(ph_, torch.int32)) + pw = ops.add(pwstart, ops.constant(pw_, torch.int32)) + + if divisor_override is not None: + scale = divisor_override + elif count_include_pad or not had_padding: + scale = kernel_size[0] * kernel_size[1] + else: + scale = compute_pool_size_without_padding(ph, pw) + + part = ops.truediv( + grad_loader( + [ + *prefix, + ops.indirect_indexing( + ops.minimum( + ph, ops.sub(phend, ops.constant(1, torch.int32)) + ), + pooled_height, + check=False, + ), + ops.indirect_indexing( + ops.minimum( + pw, ops.sub(pwend, ops.constant(1, torch.int32)) + ), + pooled_width, + check=False, + ), + ] + ), + scale, + ) + + mask = ops.and_( + ops.lt(ph, phend), + ops.lt(pw, pwend), + ) + if gradient is None: + gradient = ops.where(mask, part, ops.constant(0.0, torch.float32)) + else: + gradient = ops.where(mask, ops.add(gradient, part), gradient) + if gradient is None: + raise AssertionError("expected: gradient is not None") + return gradient + + rv = Pointwise.create( + device=grad_output.get_device(), + dtype=dtype, + inner_fn=fn, + ranges=new_size, + ) + return rv + + +fallback_avg_pool3d_backward = fallback_handler( + aten.avg_pool3d_backward.default, add_to_fallback_set=False +) + + +@register_lowering(aten.avg_pool3d_backward, type_promotion_kind=None) +def avg_pool3d_backward( + grad_output, + x, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override=None, +): + if divisor_override is not None and divisor_override == 0: + raise AssertionError("divisor must be not zero") + if not stride: + stride = kernel_size + if not padding: + padding = [0, 0, 0] + + if not (isinstance(grad_output, TensorBox)): + raise AssertionError("expected: isinstance(grad_output, TensorBox)") + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if len(kernel_size) != 3: + raise AssertionError("expected: len(kernel_size) == 3") + if len(stride) != 3: + raise AssertionError("expected: len(stride) == 3") + if len(padding) != 3: + raise AssertionError("expected: len(padding) == 3") + if len(x.get_size()) not in (4, 5): + raise AssertionError("expected: len(x.get_size()) in (4, 5)") + + grad_output.realize_hint() + + *_batch, depth, height, width = x.get_size() + + _d_out, ceil_mode_d = pooling_size( + depth, 0, kernel_size, stride, padding, ceil_mode + ) + _h_out, ceil_mode_h = pooling_size( + height, 1, kernel_size, stride, padding, ceil_mode + ) + _w_out, ceil_mode_w = pooling_size( + width, 2, kernel_size, stride, padding, ceil_mode + ) + + grad_loader = grad_output.make_loader() + had_padding = any(padding) or ceil_mode_d or ceil_mode_h or ceil_mode_w + + *_, pooled_depth, pooled_height, pooled_width = grad_output.get_size() + new_size = list(x.get_size()) + dtype = x.get_dtype() + + d_window_size, h_window_size, w_window_size = ( + max( + max(d // stride[i] - max(0, (d - kernel_size[i]) // stride[i]), 1) + for d in range(kernel_size[i] * 2) + ) + for i in range(3) + ) + + window_size = d_window_size * h_window_size * w_window_size + if window_size > 125: + # Kernel size too big. Results in hard-to-optimize Triton code. + return fallback_avg_pool3d_backward( + grad_output, + x, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override, + ) + + def compute_pool_size_without_padding(pd, ph, pw): + stride_d, stride_h, stride_w = (ops.constant(s, torch.int32) for s in stride) + pad_d, pad_h, pad_w = (ops.constant(p, torch.int32) for p in padding) + kernel_d, kernel_h, kernel_w = ( + ops.constant(k, torch.int32) for k in kernel_size + ) + + dstart, hstart, wstart = ( + ops.sub(ops.mul(p, s), pad) + for p, s, pad in zip( + [pd, ph, pw], [stride_d, stride_h, stride_w], [pad_d, pad_h, pad_w] + ) + ) + dend, hend, wend = ( + ops.minimum( + ops.add(start, k), ops.add(ops.index_expr(dim, torch.int32), pad) + ) + for start, k, dim, pad in zip( + [dstart, hstart, wstart], + [kernel_d, kernel_h, kernel_w], + [depth, height, width], + [pad_d, pad_h, pad_w], + ) + ) + dstart, hstart, wstart = ( + ops.maximum(start, ops.constant(0, torch.int32)) + for start in [dstart, hstart, wstart] + ) + dend, hend, wend = ( + ops.minimum(end, ops.index_expr(dim, torch.int32)) + for end, dim in zip([dend, hend, wend], [depth, height, width]) + ) + divide_factor = ops.mul( + ops.mul(ops.sub(dend, dstart), ops.sub(hend, hstart)), ops.sub(wend, wstart) + ) + return divide_factor + + def fn(idx): + *prefix, d, h, w = idx + d, h, w = (v + pad for v, pad in zip([d, h, w], padding)) + + pdstart, phstart, pwstart = ( + ops.index_expr(FloorDiv(v - k + s, s), torch.int32) + for v, k, s in zip([d, h, w], kernel_size, stride) + ) + + pdend, phend, pwend = ( + ops.index_expr(FloorDiv(v, s) + 1, torch.int32) + for v, s in zip([d, h, w], stride) + ) + + pdstart, phstart, pwstart = ( + ops.maximum(pstart, ops.constant(0, torch.int32)) + for pstart in [pdstart, phstart, pwstart] + ) + pdend, phend, pwend = ( + ops.minimum(pend, ops.index_expr(pooled_dim, torch.int32)) + for pend, pooled_dim in zip( + [pdend, phend, pwend], [pooled_depth, pooled_height, pooled_width] + ) + ) + + gradient = None + # Iterate over the 3D region to accumulate gradients + for pd_ in range(d_window_size): + for ph_ in range(h_window_size): + for pw_ in range(w_window_size): + pd, ph, pw = ( + ops.add(pstart, ops.constant(p_, torch.int32)) + for pstart, p_ in zip( + [pdstart, phstart, pwstart], [pd_, ph_, pw_] + ) + ) + + if divisor_override is not None: + scale = divisor_override + elif count_include_pad or not had_padding: + scale = kernel_size[0] * kernel_size[1] * kernel_size[2] + else: + scale = compute_pool_size_without_padding(pd, ph, pw) + + part = ops.truediv( + grad_loader( + [ + *prefix, + ops.indirect_indexing( + ops.minimum( + pd, ops.sub(pdend, ops.constant(1, torch.int32)) + ), + pooled_depth, + check=False, + ), + ops.indirect_indexing( + ops.minimum( + ph, ops.sub(phend, ops.constant(1, torch.int32)) + ), + pooled_height, + check=False, + ), + ops.indirect_indexing( + ops.minimum( + pw, ops.sub(pwend, ops.constant(1, torch.int32)) + ), + pooled_width, + check=False, + ), + ] + ), + scale, + ) + + mask = ops.and_( + ops.and_(ops.lt(pd, pdend), ops.lt(ph, phend)), + ops.lt(pw, pwend), + ) + if gradient is None: + gradient = ops.where( + mask, part, ops.constant(0.0, torch.float32) + ) + else: + gradient = ops.where(mask, ops.add(gradient, part), gradient) + if gradient is None: + raise AssertionError("expected: gradient is not None") + return gradient + + rv = Pointwise.create( + device=grad_output.get_device(), + dtype=dtype, + inner_fn=fn, + ranges=new_size, + ) + return rv + + +def _validate_reduction_axis(x, axis): + size = x.get_size() + if isinstance(axis, int): + axis = [axis] + elif not axis: + axis = range(len(size)) + if len(size) == 0: + if tuple(axis) not in [(), (0,), (-1,)]: + raise AssertionError(f"invalid axis: {axis}") + return [] + axis = list(axis) + for i in range(len(axis)): + if axis[i] < 0: + axis[i] += len(size) if len(size) else 1 + if not (0 <= axis[i] < len(size) or (len(size) == 0 and axis[i] == 0)): + raise AssertionError( + "expected: 0 <= axis[i] < len(size) or (len(size) == 0 and axis..." + ) + if len(OrderedSet(axis)) != len(axis): + raise AssertionError("reduction axis not unique") + return axis + + +def _make_reduction_inner( + x, *, axis, keepdims, dtype, override_return_dtype, reduction_type=None +): + if dtype is not None: + x = to_dtype(x, dtype) + size = x.get_size() + axis = OrderedSet[int](_validate_reduction_axis(x, axis)) + + kept_sizes = [] + kept_idx = [] + reduced_sizes = [] + reduced_idx = [] + for i in range(len(size)): + if i in axis: + reduced_idx.append(i) + reduced_sizes.append(size[i]) + else: + kept_idx.append(i) + kept_sizes.append(size[i]) + + # For argmax/argmin compute logical indices when the tensor has non-contiguous layout. + should_compute_logical_index = False + supports_logical_index_argreduce = is_triton(x) or ( + ir.get_device_type(x) == "cpu" and config.cpu_backend == "cpp" + ) + if ( + reduction_type + in ( + "argmax", + "argmin", + "argmax_value", + "argmin_value", + "argmax_with_value", + "argmin_with_value", + ) + and len(reduced_sizes) > 1 + and supports_logical_index_argreduce + ): + if isinstance(x.data, PermuteView): + should_compute_logical_index = True + elif isinstance(x.data, ir.ReinterpretView) or ( + isinstance(x.data, ir.StorageBox) and isinstance(x.data.data, ir.Buffer) + ): + layout = x.get_layout() + should_compute_logical_index = ( + layout.is_transposed() or not layout.is_contiguous() + ) + + def loader(index, reduction_index): + if len(reduction_index) != len(reduced_idx): + raise AssertionError("expected: len(reduction_index) == len(reduced_idx)") + if keepdims: + if len(index) != len(size): + raise AssertionError("expected: len(index) == len(size)") + index = [index[i] for i in kept_idx] + if len(index) != len(kept_idx): + raise AssertionError("expected: len(index) == len(kept_idx)") + new_index = [None] * (len(index) + len(reduction_index)) + for idx, var in itertools.chain( + zip(kept_idx, index), zip(reduced_idx, reduction_index) + ): + new_index[idx] = var + value = inner_loader(new_index) + + # For argmax/argmin reductions, return tuple with logical linear index if needed + if should_compute_logical_index: + rindex = [sympy.expand(i) for i in reduction_index] + + # Compute linear index in row-major order + # For reduction_ranges = [4, 6]: linear_index = r0 * 6 + r1 + linear_idx = rindex[0] + for i in range(1, len(rindex)): + linear_idx = linear_idx * reduced_sizes[i] + rindex[i] + + return (value, ops.index_expr(linear_idx, torch.int64)) + + return value + + if keepdims: + new_size = list(size) + for i in reduced_idx: + new_size[i] = sympy.S.One + else: + new_size = kept_sizes + + inner_loader = x.make_loader() + return dict( + device=x.get_device(), + dst_dtype=override_return_dtype or x.get_dtype(), + src_dtype=x.get_dtype(), + inner_fn=loader, + ranges=new_size, + reduction_ranges=reduced_sizes, + ) + + +def make_reduction( + reduction_type: ReductionType, + override_return_dtype=None, + *, + strict_sum: bool = False, +) -> Callable[..., TensorBox]: + def inner(x, axis=None, keepdims=False, *, dtype=None) -> TensorBox: + # For argmax/argmin on boolean tensors, cast to int32 first to ensure + # correct comparison. Boolean comparisons can produce incorrect indices + # on multiple backends (Triton, CPU, etc.). + # See https://github.com/pytorch/pytorch/issues/174069 + # and https://github.com/pytorch/pytorch/issues/184893 + if reduction_type in ("argmax", "argmin") and x.get_dtype() == torch.bool: + x = to_dtype(x, torch.int32) + kwargs = _make_reduction_inner( + x, + axis=axis, + keepdims=keepdims, + dtype=dtype, + override_return_dtype=override_return_dtype, + reduction_type=reduction_type, + ) + result = Reduction.create( + reduction_type=reduction_type, + input_node=x, + strict_sum=strict_sum, + **kwargs, + ) + if isinstance( + result.data.data, # type: ignore[attr-defined, attr-type, union-attr] + Reduction, + ): # Only realize if reduction isn't unrolled + result.realize() + return result + + return inner + + +def make_arg_with_value_reduction( + reduction_type: ReductionType, +) -> Callable[..., Sequence[TensorBox]]: + def inner(x, axis=None, keepdims=False) -> Sequence[TensorBox]: + kwargs = _make_reduction_inner( + x, + axis=axis, + keepdims=keepdims, + dtype=None, + override_return_dtype=x.get_dtype(), + reduction_type=reduction_type, + ) + return ir.ArgReduction.create( + reduction_type=reduction_type, input_node=x, **kwargs + ) + + return inner + + +def _make_scan_inner(x, *, axis, dtype): + if dtype is not None: + x = to_dtype(x, dtype) + axis = _validate_dim(x, axis) + + return dict( + device=x.get_device(), + dtypes=(x.get_dtype(),), + inner_fns=(x.make_loader(),), + size=x.get_size(), + axis=axis, + ) + + +@register_lowering(aten.mean) +def mean(x, axis=None, keepdim=False, *, dtype=None): + if dtype is not None: + x = to_dtype(x, dtype) + size = x.get_size() + axis = _validate_reduction_axis(x, axis) + # compute in higher-precision until end of mean lowering + output_dtype = x.get_dtype() + if output_dtype in (torch.float16, torch.bfloat16): + x = to_dtype(x, torch.float) + sum_result = sum_(x, axis, keepdim) + denom = sympy_product(size[i] for i in axis) + denom = ir.IndexingConstant(index=denom, dtype=x.get_dtype(), device=x.get_device()) + denom = ExpandView.create(denom, list(sum_result.get_size())) + return to_dtype(div(sum_result, denom), output_dtype) + + +def var_mean_sum_(x, axis, correction, keepdim, return_mean): + if correction is None: + correction = 1 + + size = x.get_size() + axis = _validate_reduction_axis(x, axis) + x_mean = mean(x, axis, keepdim=True) + if return_mean: + x_mean.realize() + + diffs = square(sub(x, x_mean)) + sum_result = sum_(diffs, axis, keepdim) + + denom = sympy_product(size[i] for i in axis) + if correction: + denom = Max(denom - correction, 0) + denom = ir.IndexingConstant(index=denom, dtype=x.get_dtype(), device=x.get_device()) + denom = ExpandView.create(denom, list(sum_result.get_size())) + x_var = div(sum_result, denom) + if not return_mean: + return (x_var,) + + x_mean = x_mean if keepdim else squeeze(x_mean, axis) + return x_var, x_mean + + +def use_two_step_variance(x, axis, keepdim, input_dtype): + # The two-step algorithm can be faster for non-split reductions because + # Welford does more work per element. Preserve the old tiny-reduction + # two-step path, keep Welford for the rest of the small reductions where + # the speedup is limited and training gradients are more sensitive to the + # different accumulation order, and keep Welford for larger or split + # reductions where avoiding another full pass over the data is profitable. + axis = _validate_reduction_axis(x, axis) + kwargs = _make_reduction_inner( + x, axis=axis, keepdims=keepdim, dtype=None, override_return_dtype=None + ) + + ranges = kwargs["ranges"] + reduction_numel = sympy_product(kwargs["reduction_ranges"]) + device = x.get_device() + check_for_split = False + min_numel = 0 + is_cuda_two_step_dtype = input_dtype in (torch.bfloat16, torch.float16) + if device and device.type == "cpu": + # 1024 is a default value to pass all the UTs about accuracy. + # A larger threshold can still get performance benefits. + threshold = config.cpp.use_two_step_variance_threshold + elif device and device.type == "cuda" and is_triton(x) and is_cuda_two_step_dtype: + min_numel = config.triton.use_two_step_variance_min_numel + threshold = config.triton.use_two_step_variance_threshold + check_for_split = True + else: + threshold = config.unroll_reductions_threshold + + if not isinstance(reduction_numel, sympy.Integer): + return False + + reduction_numel = int(reduction_numel) + if reduction_numel > threshold or sympy_product(ranges) == 1: + return False + + if min_numel and config.unroll_reductions_threshold < reduction_numel < min_numel: + return False + + if not check_for_split: + return True + + _, split = ir.Reduction.num_splits( + reduction_numel=reduction_numel, + reduction_type="sum", + **kwargs, + ) + return V.graph.sizevars.statically_known_leq(split, 1) + + +def var_mean_welford_(x, axis, *, correction, keepdim, return_mean): + if correction is None: + correction = 1 + + kwargs = _make_reduction_inner( + x, axis=axis, keepdims=keepdim, dtype=None, override_return_dtype=None + ) + loader = kwargs.pop("inner_fn") + kwargs.pop("dst_dtype") + kwargs.pop("src_dtype") + + mean, m2, _ = ir.WelfordReduction.create( + inner_fns=(loader,), + reduction_type="welford_reduce", + dtype=x.get_dtype(), + **kwargs, + ) + m2.realize() + + dtype = x.get_dtype() + size = x.get_size() + axis = _validate_reduction_axis(x, axis) + rnumel = sympy_product(size[i] for i in axis) + + def get_constant_or_index_expr(x, dtype): + if isinstance(x, sympy.Expr) and not x.is_number: + return ops.to_dtype(ops.index_expr(x, torch.int64), dtype) + return ops.constant(x, dtype) + + def scale_fn(data): + c = get_constant_or_index_expr(correction, dtype) + N = get_constant_or_index_expr(rnumel, dtype) + zero = ops.constant(0, dtype) + return data / ops.maximum(zero, N - c) + + var = make_pointwise(scale_fn)(m2) + + if return_mean: + mean.realize() + return var, mean + return (var,) + + +def var_mean_helper_(x, *, axis, correction, keepdim, return_mean): + out_dtype = x.get_dtype() + compute_dtype = get_computation_dtype(out_dtype) + x = to_dtype(x, compute_dtype, copy=False) + kwargs = dict( + x=x, + axis=axis, + correction=correction, + keepdim=keepdim, + return_mean=return_mean, + ) + output = ( + var_mean_sum_(**kwargs) + if ( + config.mtia.disable_welford_reduction + or use_two_step_variance( + x, axis=axis, keepdim=keepdim, input_dtype=out_dtype + ) + ) + else var_mean_welford_(**kwargs) + ) + output = tuple(to_dtype(x, out_dtype, copy=False) for x in output) + return output[0] if not return_mean else output + + +@register_lowering([aten.var, prims.var]) +def var_(x, axis=None, *, correction=None, keepdim=False): + return var_mean_helper_( + x, axis=axis, correction=correction, keepdim=keepdim, return_mean=False + ) + + +@register_lowering(aten.var_mean) +def var_mean(x, axis=None, *, correction=None, keepdim=False): + return var_mean_helper_( + x, axis=axis, correction=correction, keepdim=keepdim, return_mean=True + ) + + +def pow_recursive(x, y, dtype): + if y < 0: + return pow_recursive(ops.reciprocal(x), -y, dtype) + if y == 0: + return ops.constant(1, dtype) + if y == 1: + return x + + result = pow_recursive(x, y // 2, dtype) + result = ops.mul(result, result) + if (y % 2) == 1: + result = ops.mul(result, x) + return result + + +@make_pointwise +def pow_native(a, b): + return ops.pow(a, b) + + +fallback_pow_tensor_tensor = fallback_handler( + aten.pow.Tensor_Tensor, add_to_fallback_set=False +) +fallback_pow_scalar = fallback_handler(aten.pow.Scalar, add_to_fallback_set=False) +fallback_pow_tensor_scalar = fallback_handler( + aten.pow.Tensor_Scalar, add_to_fallback_set=False +) + + +@register_lowering(aten.pow, broadcast=True) +def pow(a, b): + if isinstance(b, float) and b.is_integer(): + return pow(a, int(b)) + elif isinstance(b, float) and b == 0.5: + return sqrt(a) + elif isinstance(b, int) and b == 1: + return clone(a) + + # Type promotion ensures all tensor arguments have the same type + dtype = next(x.get_dtype() for x in (a, b) if isinstance(x, ir.TensorBox)) + is_integer_pow = is_integer_dtype(dtype) + + # Optimize away small fixed powers, or for integers avoid falling back to ATen + embed_exponent = isinstance(b, int) and ( + -32 < b < 32 or (is_integer_pow and b >= 0) + ) + if embed_exponent: + loader = a.make_loader() + + def fn(idx): + return pow_recursive(loader(idx), b, a.get_dtype()) + + return Pointwise.create( + device=a.get_device(), + dtype=a.get_dtype(), + inner_fn=fn, + ranges=a.get_size(), + ) + + if isinstance(a, Number): + if a == 1: + return full_like(b, 1) + + if a == 2 and is_float_dtype(b.get_dtype()): + return exp2(b) + + if is_integer_pow: + # ops.pow doesn't work for integers + if isinstance(a, Number): + return fallback_pow_scalar(a, b) + elif isinstance(b, Number): + return fallback_pow_tensor_scalar(a, b) + else: + return fallback_pow_tensor_tensor(a, b) + + return pow_native(a, b) + + +def mutate_to(changed, val, unsafe_alias=False): + if isinstance(changed, TensorBox): + changed_data = changed.data + else: + changed_data = changed + if isinstance(val, TensorBox): + val = val.data + + if not isinstance(val, ir.StorageBox): + # introduce a copy to handle views + node = Pointwise.create( + device=changed.get_device(), + dtype=changed.get_dtype(), + inner_fn=val.make_loader(), + ranges=changed.get_size(), + ) + if not (isinstance(node, (BaseView, MutableBox))): + raise AssertionError("expected: isinstance(node, (BaseView, MutableBox))") + val = node.data + if not (isinstance(val, ir.StorageBox)): + raise AssertionError("expected: isinstance(val, ir.StorageBox)") + + if isinstance(changed_data, ir.StorageBox) and not ( + changed_data.is_input_buffer() + # In AOTI, module parameters and buffers are not lifted as graph inputs + or changed_data.is_module_buffer() + or isinstance(changed_data.data, ir.NopKernel) + ): + # Fast path, just swing the data pointer + val.realize() + changed_data.data = val.data + return changed + + ir.MutationLayoutSHOULDREMOVE.realize_into( + val, changed_data, unsafe_alias=unsafe_alias + ) + return changed + + +@register_lowering(aten.fill_) +def fill_(x, fill_value): + return mutate_to(x, full_like(x, fill_value)) + + +@register_lowering(aten.copy_, type_promotion_kind=None) +def copy_(dst, src, non_blocking=False): + if dst is src: + # dst.copy_(dst) can happen from the reinplacing pass + return dst + src = to_device(src, dst.get_device()) + src = to_dtype(src, dst.get_dtype()) + src = expand(src, dst.get_size()) + return mutate_to(dst, src) + + +@make_pointwise +def floordiv(a, b): + return ops.floordiv(a, b) + + +@make_pointwise +def truncdiv(a, b): + return ops.truncdiv(a, b) + + +@make_pointwise +def _div_rn(a, b): + return ops.div_rn(a, b) + + +def _floor_div_floating(a, b): + # Either operand may be a python scalar (e.g. torch.floor_divide(scalar, + # tensor)); constant_like needs a tensor for dtype/device/size, so seed the + # constants from whichever operand is a tensor. + ref = a if isinstance(a, (TensorBox, IRNode)) else b + nan = constant_like(float("nan"))(ref) + neg_one = constant_like(-1.0)(ref) + zero = constant_like(0.0)(ref) + + def fn(a, b, nan, neg_one, zero): + quotient = ops.div_rn(a, b) + result = ops.floor(quotient) + a_is_inf = ops.isinf(a) + a_is_finite = ops.logical_and( + ops.logical_not(a_is_inf), ops.logical_not(ops.isnan(a)) + ) + # Eager floor division uses a fmod-based implementation. For +/-inf + # divided by a nonzero divisor, fmod produces NaN. Keep divisor == 0 + # unchanged because eager returns a / b directly. + a_inf_nonzero_b = ops.logical_and(a_is_inf, ops.ne(b, zero)) + + # For finite nonzero a divided by +/-inf, floor(a / b) can produce + # signed zero. Eager applies Python-style floor-division sign correction, + # so negative zero direction results become -1. + finite_nonzero_a_inf_b = ops.logical_and( + ops.logical_and(a_is_finite, ops.ne(a, zero)), + ops.logical_and(ops.isinf(b), ops.ne(ops.lt(a, zero), ops.lt(b, zero))), + ) + result = ops.where(finite_nonzero_a_inf_b, neg_one, result) + return ops.where(a_inf_nonzero_b, nan, result) + + return make_pointwise(fn)(a, b, nan, neg_one, zero) + + +@register_lowering(aten.div, broadcast=True) +def div_mode(a, b, rounding_mode=None): + both_integer = is_integer_type(a) and is_integer_type(b) + both_boolean = is_boolean_type(a) and is_boolean_type(b) + + # floordiv and truncdiv need special handling for integer tensors on Triton, + # see the discussion at https://github.com/triton-lang/triton/issues/605 + if rounding_mode == "floor": + if both_boolean: + raise AssertionError( + "floordiv operands can not be boolean at the same time" + ) + # Use div_rn (IEEE round-to-nearest) instead of truediv here because + # Triton's default division uses an approximate reciprocal, which can + # produce a result slightly below the true quotient and cause floor() + # to round down by one. + return floordiv(a, b) if both_integer else _floor_div_floating(a, b) + if rounding_mode == "trunc": + if both_boolean: + raise AssertionError( + "truncdiv operands can not be boolean at the same time" + ) + return truncdiv(a, b) if both_integer else trunc(div(a, b)) + return div(a, b) + + +@register_lowering([aten.mul], broadcast=True) +def mul(a, b): + both_bool = is_boolean_type(a) and is_boolean_type(b) + if both_bool: + return logical_and(a, b) + else: + fn = ops_wrapper(aten.mul.__name__) + return make_pointwise(fn)(a, b) + + +def get_constant_value(x: ir.IRNode) -> ir.Constant | None: + """Try convert an arbitrary IR node into an ir.Constant value""" + + # First try unwrapping the IRNode to see if it is already an ir.Constant + # Optional step, but avoids unnecessary inner_fn evaluation. + if isinstance(x, ir.MutableBox): + return get_constant_value(x.data) + if isinstance(x, ir.BaseView): + return get_constant_value(x.unwrap_view()) + if isinstance(x, ir.Constant): + return x + + # If the unwrapped node is not an ir.Constant, try evaluating inner_fn + # to see if the returned value is from an `ops.constant` call + if not isinstance(x, ir.Loops): + return None + + handler = torch._inductor.ops_handler.ExtractConstantsHandler(x.get_device()) + with ( + V.set_ops_handler(handler), + patch.object(ir.FlexibleLayout, "allow_indexing", True), + ): + out = x.inner_fn(*x.inner_fn_args()) + + if not (isinstance(out, torch._inductor.virtualized.OpsValue)): + raise AssertionError( + "expected: isinstance(out, torch._inductor.virtualized.OpsValue)" + ) + if isinstance(out.value, ir.Constant): + return out.value + return None + + +# NOTE: prims.div maps to a / b in C, so performs truncation division on +# integer inputs and true division for floating and complex inputs. +@register_lowering([prims.div], broadcast=True) +def div_prim(a, b): + is_integral = all(is_boolean_type(x) or is_integer_type(x) for x in [a, b]) + + if is_integral: + return truncdiv(a, b) + + # Disable CPU optimization to avoid precision issues. + # see https://github.com/pytorch/pytorch/issues/157959 + if (divisor := get_constant_value(b)) is not None and a.get_device().type != "cpu": + # Replace divide by constant with multiply by reciprocal + + if divisor.value == 0: + reciprocal = math.copysign(float("inf"), divisor.value) + else: + reciprocal = 1.0 / divisor.value + return mul(a, reciprocal) + + def fn(*args): + return ops.truediv(*args) + + return make_pointwise(fn)(a, b) + + +@register_lowering( + [aten.true_divide, aten.div.Tensor], + broadcast=True, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def div(a, b): + a, b = promote_constants( + (a, b), type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT + ) + return div_prim(a, b) + + +@register_lowering([aten.fmod, prims.fmod], broadcast=True) +def fmod(a, b): + is_integral = is_boolean_type(a) or is_integer_type(a) + + if is_integral: + + def fn(a, b): + return ops.mod(a, b) + + else: + + def fn(a, b): + return ops.fmod(a, b) + + return make_pointwise(fn)(a, b) + + +def _strict_sum_layout_eligible(axis, dtype) -> bool: + current_node = V.graph.current_node + if ( + current_node is None + or config.numerics != "strict" + or current_node.target != aten.sum.dim_IntList + or dtype is not None + or axis is None + or not has_triton_reduction_ordering() + ): + return False + dims = [axis] if isinstance(axis, int) else list(axis) + if len(dims) != 1: + return False + + fx_input = current_node.args[0] + if not isinstance(fx_input, torch.fx.Node): + return False + value = fx_input.meta.get("val") + if not isinstance(value, torch.Tensor) or value.dtype not in { + torch.float16, + torch.bfloat16, + torch.float32, + torch.float64, + }: + return False + if ( + not value.is_cuda + or torch.version.hip is not None + or not is_triton(value.device) + ): + return False + + dim = dims[0] + value.ndim if dims[0] < 0 else dims[0] + if not 0 <= dim < value.ndim: + return False + sizes = [convert_symint_to_expr(size) for size in value.shape] + strides = [convert_symint_to_expr(stride) for stride in value.stride()] + sizevars = V.graph.sizevars + outer = [ + (size, stride) + for i, (size, stride) in enumerate(zip(sizes, strides)) + if i != dim and not sizevars.statically_known_equals(size, 1) + ] + collapsible = all( + sizevars.statically_known_equals(slow_stride, fast_stride * fast_size) + for (_, slow_stride), (fast_size, fast_stride) in itertools.pairwise(outer) + ) + if sizevars.statically_known_equals(sizes[dim], 1): + if not outer: + return sizevars.statically_known_equals(strides[0], 1) and all( + sizevars.statically_known_equals(stride, 0) + or sizevars.statically_known_equals(stride, 1) + for stride in strides[1:] + ) + return collapsible and sizevars.statically_known_equals(outer[-1][1], 1) + if not sizevars.statically_known_equals(strides[dim], 1): + return False + if any( + not sizevars.statically_known_true(sympy.Gt(stride, 1)) for _, stride in outer + ): + return False + return collapsible + + +@register_lowering([aten.sum, prims.sum]) +def sum_(x, axis=None, keepdims=False, *, dtype=None): + strict_sum = _strict_sum_layout_eligible(axis, dtype) + if ( + is_integer_dtype(x.get_dtype()) or is_boolean_dtype(x.get_dtype()) + ) and dtype is None: + dtype = torch.int64 + + fn = make_reduction("sum", override_return_dtype=dtype, strict_sum=strict_sum) + return fn(x, axis, keepdims, dtype=dtype) + + +fallback_cumsum = fallback_handler(aten.cumsum.default) +fallback_cumprod = fallback_handler(aten.cumprod.default) +fallback_logcumsumexp = fallback_handler(aten.logcumsumexp.default) +fallback_cummax = fallback_handler(aten.cummax.default) +fallback_cummin = fallback_handler(aten.cummin.default) + + +@register_lowering(aten.cumsum) +def cumsum(x, axis=None, dtype=None): + if ( + is_integer_dtype(x.get_dtype()) or is_boolean_dtype(x.get_dtype()) + ) and dtype is None: + dtype = torch.int64 + + if len(x.get_size()) == 0: + if axis not in [0, -1]: + raise AssertionError("expected: axis in [0, -1]") + dtype = dtype or x.get_dtype() + return to_dtype(x, dtype, copy=True) + + def combine_fn(a_tuple, b_tuple): + (a,) = a_tuple + (b,) = b_tuple + return (ops.add(a, b),) + + kwargs = _make_scan_inner(x, axis=axis, dtype=dtype) + (result,) = ir.Scan.create(**kwargs, combine_fn=combine_fn) + if result is None: + return fallback_cumsum(x, dim=axis, dtype=dtype) + return result + + +@register_lowering(aten.cumprod) +def cumprod(x, axis=None, dtype=None): + if ( + is_integer_dtype(x.get_dtype()) or is_boolean_dtype(x.get_dtype()) + ) and dtype is None: + dtype = torch.int64 + + if len(x.get_size()) == 0: + if axis not in [0, -1]: + raise AssertionError("expected: axis in [0, -1]") + dtype = dtype or x.get_dtype() + return to_dtype(x, dtype, copy=True) + + def combine_fn(a_tuple, b_tuple): + (a,) = a_tuple + (b,) = b_tuple + return (ops.mul(a, b),) + + kwargs = _make_scan_inner(x, axis=axis, dtype=dtype) + (result,) = ir.Scan.create(**kwargs, combine_fn=combine_fn) + if result is None: + return fallback_cumprod(x, dim=axis, dtype=dtype) + return result + + +@register_lowering(aten.logcumsumexp) +def logcumsumexp(x, dim): + def log_add_exp_helper(a_tuple, b_tuple): + (a,) = a_tuple + (b,) = b_tuple + min_v = ops.minimum(a, b) + max_v = ops.maximum(a, b) + mask = (min_v != max_v) | (~ops.isinf(min_v)) + return (ops.where(mask, ops.log1p(ops.exp(min_v - max_v)) + max_v, a),) + + dtype = x.get_dtype() + if len(x.get_size()) == 0: + if dim not in [0, -1]: + raise AssertionError("expected: dim in [0, -1]") + return clone(x) + + kwargs = _make_scan_inner(x, axis=dim, dtype=dtype) + (result,) = ir.Scan.create(**kwargs, combine_fn=log_add_exp_helper) + if result is None: + return fallback_logcumsumexp(x, dim=dim) + return result + + +@register_lowering(aten.cummax, type_promotion_kind=None) +def cummax(x, axis=None): + if len(x.get_size()) == 0: + if axis not in [0, -1]: + raise AssertionError("expected: axis in [0, -1]") + return clone(x), empty_like(x, dtype=torch.int64) + + dtype = x.get_dtype() + combine_fn = ir.get_reduction_combine_fn( + "argmax", dtype=dtype, arg_break_ties_left=False + ) + + kwargs = _make_scan_inner(x, axis=axis, dtype=dtype) + kwargs["dtypes"] = (dtype, torch.int64) + kwargs["inner_fns"] = ( + x.make_loader(), + lambda idx: ops.index_expr(idx[axis], torch.int64), + ) + values, indices = ir.Scan.create(**kwargs, combine_fn=combine_fn) # type: ignore[arg-type] + if values is None: + return fallback_cummax(x, dim=axis) + return values, indices + + +@register_lowering(aten.cummin, type_promotion_kind=None) +def cummin(x, axis=None): + if len(x.get_size()) == 0: + if axis not in [0, -1]: + raise AssertionError("expected: axis in [0, -1]") + return clone(x), empty_like(x, dtype=torch.int64) + + dtype = x.get_dtype() + combine_fn = ir.get_reduction_combine_fn( + "argmin", dtype=dtype, arg_break_ties_left=False + ) + + kwargs = _make_scan_inner(x, axis=axis, dtype=dtype) + kwargs["dtypes"] = (dtype, torch.int64) + kwargs["inner_fns"] = ( + x.make_loader(), + lambda idx: ops.index_expr(idx[axis], torch.int64), + ) + values, indices = ir.Scan.create(**kwargs, combine_fn=combine_fn) # type: ignore[arg-type] + if values is None: + return fallback_cummin(x, dim=axis) + return values, indices + + +@register_lowering(aten.prod) +def prod(x, axis=None, keepdims=False, *, dtype=None): + if ( + is_integer_dtype(x.get_dtype()) or is_boolean_dtype(x.get_dtype()) + ) and dtype is None: + dtype = torch.int64 + + fn = make_reduction("prod", override_return_dtype=dtype) + return fn(x, axis, keepdims, dtype=dtype) + + +def _current_node_uses_all_tuple_outputs(indices: tuple[int, ...]) -> bool: + current_node = V.graph.current_node + if current_node is None: + return True + + used_indices: OrderedSet[int] = OrderedSet() + for user in current_node.users: + if ( + user.op == "call_function" + and user.target is operator.getitem + and len(user.args) >= 2 + and isinstance(user.args[1], int) + ): + if len(user.users) > 0: + used_indices.add(user.args[1]) + else: + return True + + return all(index in used_indices for index in indices) + + +@register_lowering(aten.any) +def reduce_any(x, dim=None, keepdim=False): + x = to_dtype(x, torch.bool) + return make_reduction("any")(x, axis=dim, keepdims=keepdim) + + +@register_lowering(aten.max, type_promotion_kind=None) +def reduce_max(x, dim=None, keepdim=False): + if dim is not None: + if is_triton(x) and x.get_dtype() != torch.bool: + if _current_node_uses_all_tuple_outputs((0, 1)): + return reduce_argmax_with_value(x, axis=dim, keepdims=keepdim) + return ( + reduce_argmax_value(x, axis=dim, keepdims=keepdim), + reduce_argmax(x, axis=dim, keepdims=keepdim), + ) + return ( + reduce_amax(x, axis=dim, keepdims=keepdim), + reduce_argmax(x, axis=dim, keepdims=keepdim), + ) + + return reduce_amax(x, axis=None, keepdims=keepdim) + + +@register_lowering(aten.min, type_promotion_kind=None) +def reduce_min(x, dim=None, keepdim=False): + if dim is not None: + if is_triton(x) and x.get_dtype() != torch.bool: + if _current_node_uses_all_tuple_outputs((0, 1)): + return reduce_argmin_with_value(x, axis=dim, keepdims=keepdim) + return ( + reduce_argmin_value(x, axis=dim, keepdims=keepdim), + reduce_argmin(x, axis=dim, keepdims=keepdim), + ) + return ( + reduce_amin(x, axis=dim, keepdims=keepdim), + reduce_argmin(x, axis=dim, keepdims=keepdim), + ) + + return reduce_amin(x, axis=None, keepdims=keepdim) + + +register_lowering(prims.xor_sum)(make_reduction("xor_sum")) +reduce_amax = register_lowering(aten.amax)(make_reduction("max")) +reduce_amin = register_lowering(aten.amin)(make_reduction("min")) +reduce_argmax = register_lowering(aten.argmax)( + make_reduction("argmax", override_return_dtype=torch.int64) +) +reduce_argmin = register_lowering(aten.argmin)( + make_reduction("argmin", override_return_dtype=torch.int64) +) +reduce_argmax_value = make_reduction("argmax_value") +reduce_argmin_value = make_reduction("argmin_value") +reduce_argmax_with_value = make_arg_with_value_reduction("argmax_with_value") +reduce_argmin_with_value = make_arg_with_value_reduction("argmin_with_value") + +add = register_pointwise( + aten.add, + allow_alpha=True, + use_fma_for_alpha=True, + override_fn_when_input_bool="logical_or", + round_scalars_to_tensor_dtype=True, +) + +sort_fallback = fallback_handler(aten.sort.stable, add_to_fallback_set=False) + + +@register_lowering(aten.sort.stable, type_promotion_kind=None) +def sort_stable(x, *, stable=None, dim=-1, descending=False): + if stable is None: + stable = False + + shape = x.get_size() + device = x.get_device() + dim = canonicalize_dim(len(shape), dim) + if len(shape) == 0: + return clone(x), _full(0, device, torch.int64, shape) + + dim_size = shape[dim] if len(shape) else 1 + # Use int32 indices when decompose_sort_ops is enabled, allowing sort + # dimensions up to 2^31-1. Default int16 keeps register pressure low + # on GPU where the bitonic network holds all indices in-block. + if config.triton.decompose_sort_ops: + idx_dtype = torch.int32 + else: + idx_dtype = torch.int16 + if not V.graph.sizevars.guard_or_false( + sympy.Lt(dim_size, torch.iinfo(idx_dtype).max) + ): + return sort_fallback(x, stable=stable, dim=dim, descending=descending) + + indices = iota( + dim_size, start=0, step=1, dtype=idx_dtype, device=device, requires_grad=False + ) + view_shape = [1] * len(shape) + if len(shape): + view_shape[dim] = dim_size + indices = view(indices, view_shape) + indices = expand(indices, shape) + + values, indices = ir.Sort.create( + device=device, + dtypes=(x.dtype, indices.dtype), + inner_fns=(x.make_loader(), indices.make_loader()), + size=shape, + axis=dim, + stable=stable, + descending=descending, + ) + if values is None: + return sort_fallback(x, stable=stable, dim=dim, descending=descending) + + if indices is None: + raise AssertionError("expected: indices is not None") + return values, to_dtype(indices, torch.int64) + + +@register_lowering(aten.sort.default, type_promotion_kind=None) +def sort(x, dim=-1, descending=False): + return sort_stable(x, stable=False, dim=dim, descending=descending) + + +# Sort-based op lowerings +# When config.triton.decompose_sort_ops is enabled, decompose into sort-based +# ops so Inductor generates Triton kernels via ir.Sort. +# Otherwise, fall back to ATen eager. +topk_fallback = fallback_handler(aten.topk.default, add_to_fallback_set=False) +kthvalue_fallback = fallback_handler(aten.kthvalue.default, add_to_fallback_set=False) +median_fallback = fallback_handler(aten.median.default, add_to_fallback_set=False) +median_dim_fallback = fallback_handler(aten.median.dim, add_to_fallback_set=False) +mode_fallback = fallback_handler(aten.mode.default, add_to_fallback_set=False) + +# sort/sort.stable already have register_lowering above (sort_stable, sort). +# They use ir.Sort directly and fall back when the dimension is too large. +# When decompose_sort_ops is enabled, the size limit is lifted (int32 indices). + + +@register_lowering(aten.median.default, type_promotion_kind=None) +def median_default(self): + if not config.triton.decompose_sort_ops: + return median_fallback(self) + size = self.get_size() + numel = functools.reduce(operator.mul, size, sympy.Integer(1)) + flat = view(self, [numel]) + sorted_vals, _ = sort_stable(flat, dim=0) + k = (numel - 1) // 2 + return select(sorted_vals, 0, k) + + +@register_lowering(aten.median.dim, type_promotion_kind=None) +def median_dim(self, dim, keepdim=False): + if not config.triton.decompose_sort_ops: + return median_dim_fallback(self, dim, keepdim) + shape = self.get_size() + ndim = len(shape) + if ndim == 0: + return clone(self), _full(0, self.get_device(), torch.int64, shape) + dim = canonicalize_dim(ndim, dim) + sorted_vals, sorted_idxs = sort_stable(self, stable=True, dim=dim) + n = shape[dim] + k = (n - 1) // 2 + values = select(sorted_vals, dim, k) + indices = select(sorted_idxs, dim, k) + if keepdim: + values = unsqueeze(values, dim) + indices = unsqueeze(indices, dim) + return values, indices + + +@register_lowering(aten.mode.default, type_promotion_kind=None) +def mode_default(self, dim=-1, keepdim=False): + """Lower aten.mode via sort-based decomposition or fallback.""" + if not config.triton.decompose_sort_ops: + return mode_fallback(self, dim, keepdim) + shape = self.get_size() + ndim = len(shape) + device = self.get_device() + if ndim == 0: + return clone(self), _full(0, device, torch.int64, shape) + dim = canonicalize_dim(ndim, dim) + sorted_vals, sorted_idxs = sort_stable(self, stable=True, dim=dim) + n = shape[dim] + + # Position indices along dim: [0, 1, ..., n-1] + positions = iota( + n, start=0, step=1, dtype=torch.int64, device=device, requires_grad=False + ) + pos_view_shape = [sympy.Integer(1)] * ndim + pos_view_shape[dim] = n + positions = view(positions, pos_view_shape) + positions = expand(positions, shape) + + # Shift positions by -1, clamp to 0 for position 0 + positions_loader0 = positions.make_loader() + + def prev_pos_fn(idx): + return ops.maximum( + ops.sub(positions_loader0(idx), ops.constant(1, torch.int64)), + ops.constant(0, torch.int64), + ) + + prev_positions = Pointwise.create( + device=decode_device(device), + dtype=torch.int64, + inner_fn=prev_pos_fn, + ranges=shape, + ) + + # Gather shifted values and compare for run boundaries + shifted_vals = gather(sorted_vals, dim, prev_positions) + + sorted_loader = sorted_vals.make_loader() + shifted_loader = shifted_vals.make_loader() + positions_loader = positions.make_loader() + + # is_boundary = (sorted != shifted) | (position == 0) + def is_boundary_fn(idx): + return ops.or_( + ops.ne(sorted_loader(idx), shifted_loader(idx)), + ops.eq(positions_loader(idx), ops.constant(0, torch.int64)), + ) + + is_boundary = Pointwise.create( + device=decode_device(device), + dtype=torch.bool, + inner_fn=is_boundary_fn, + ranges=shape, + ) + + # boundary_pos = where(is_boundary, position, -1) + is_boundary_loader = is_boundary.make_loader() + positions_loader2 = positions.make_loader() + + def boundary_pos_fn(idx): + return ops.where( + is_boundary_loader(idx), + positions_loader2(idx), + ops.constant(-1, torch.int64), + ) + + boundary_pos = Pointwise.create( + device=decode_device(device), + dtype=torch.int64, + inner_fn=boundary_pos_fn, + ranges=shape, + ) + + # Propagate boundary positions forward with cummax + last_boundary, _ = cummax(boundary_pos, dim) + + # run_len = position - last_boundary + 1 + positions_loader3 = positions.make_loader() + last_boundary_loader = last_boundary.make_loader() + + def run_len_fn(idx): + return ops.add( + ops.sub(positions_loader3(idx), last_boundary_loader(idx)), + ops.constant(1, torch.int64), + ) + + run_len = Pointwise.create( + device=decode_device(device), + dtype=torch.int64, + inner_fn=run_len_fn, + ranges=shape, + ) + + # argmax returns first maximum -> end of leftmost longest run + max_pos = reduce_argmax(run_len, axis=dim, keepdims=True) + mode_vals = gather(sorted_vals, dim, max_pos) + mode_idxs = gather(sorted_idxs, dim, max_pos) + + if not keepdim: + mode_vals = squeeze(mode_vals, dim) + mode_idxs = squeeze(mode_idxs, dim) + + return mode_vals, mode_idxs + + +@register_lowering(aten.topk.default, type_promotion_kind=None) +def topk(self, k, dim=-1, largest=True, sorted=True): + if not config.triton.decompose_sort_ops: + return topk_fallback(self, k, dim, largest, sorted) + shape = self.get_size() + ndim = len(shape) + if ndim == 0: + return clone(self), _full(0, self.get_device(), torch.int64, shape) + dim = canonicalize_dim(ndim, dim) + sorted_vals, sorted_idxs = sort_stable( + self, stable=True, dim=dim, descending=largest + ) + values = slice_(sorted_vals, dim, 0, k) + indices = slice_(sorted_idxs, dim, 0, k) + return values, indices + + +@register_lowering(aten.kthvalue.default, type_promotion_kind=None) +def kthvalue(self, k, dim=-1, keepdim=False): + if not config.triton.decompose_sort_ops: + return kthvalue_fallback(self, k, dim, keepdim) + shape = self.get_size() + ndim = len(shape) + if ndim == 0: + return clone(self), _full(0, self.get_device(), torch.int64, shape) + dim = canonicalize_dim(ndim, dim) + sorted_vals, sorted_idxs = sort_stable(self, stable=True, dim=dim) + # k is 1-based + values = select(sorted_vals, dim, k - 1) + indices = select(sorted_idxs, dim, k - 1) + if keepdim: + values = unsqueeze(values, dim) + indices = unsqueeze(indices, dim) + return values, indices + + +def register_pointwise_numeric(op, name=None, triton_fallback=None): + return register_pointwise( + op, + name=name, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + triton_fallback=triton_fallback, + ) + + +def register_pointwise_numeric_ldf64(op: torch._ops.OpOverloadPacket): + register_op_requires_libdevice_fp64(op.__name__) + return register_pointwise( + op, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + + +rsqrt = register_pointwise_numeric(aten.rsqrt) +exp = register_pointwise_numeric_ldf64(aten.exp) +exp2 = register_pointwise_numeric(aten.exp2) +expm1 = register_pointwise_numeric(aten.expm1) +relu = register_pointwise(aten.relu) +sigmoid = register_pointwise_numeric_ldf64(aten.sigmoid) +sqrt = register_pointwise_numeric_ldf64(aten.sqrt) +square = register_pointwise(aten.square) +sub = register_pointwise(aten.sub, allow_alpha=True, round_scalars_to_tensor_dtype=True) + + +@register_lowering(aten.addcmul, broadcast=True) +def addcmul(self, tensor1, tensor2, *, value=1): + """ + Computes self + value * tensor1 * tensor2 using FMA for better precision. + + Matches eager CUDA kernel order: self + value * (tensor1 * tensor2) + This is computed as: fma(value, tensor1 * tensor2, self) + + Note: FMA is used for floating-point types on CUDA and ROCm (via tl.fma). For + integer types we fall back to regular arithmetic since FMA doesn't support integers. + + For floating-point types, we use mul_rn (round-to-nearest multiplication) + to force rounding of the product before the FMA. This prevents Triton's + compiler from fusing the multiplication with the FMA, matching eager's + rounding behavior. On ROCm, mul_rn falls back to regular multiplication since + libdevice.mul_rn is not available; the FMA itself (tl.fma) is still used. + """ + dtype = get_promoted_dtype( + self, + tensor1, + tensor2, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + ) + + self_loader = self.make_loader() + t1_loader = tensor1.make_loader() + t2_loader = tensor2.make_loader() + + device = self.get_device() + use_fma = ( + dtype.is_floating_point + and device is not None + and device.type in ["cuda", "xpu"] + ) + + def inner_fn(idx): + self_val = self_loader(idx) + t1_val = t1_loader(idx) + t2_val = t2_loader(idx) + + if value == 1 and use_fma: + return ops.fma(t1_val, t2_val, self_val) + + # Match eager order: self + value * (tensor1 * tensor2) + # Compute tensor1 * tensor2 first + if use_fma: + # Use mul_rn to force rounding of the product, preventing Triton + # from fusing t1*t2 with the subsequent FMA + t1_times_t2 = ops.mul_rn(t1_val, t2_val) + else: + t1_times_t2 = ops.mul(t1_val, t2_val) + + # Use index_expr for sympy expressions (e.g., from .item()), constant otherwise + if isinstance(value, sympy.Basic): + value_expr = ops.index_expr(value, dtype) + else: + value_expr = ops.constant(value, dtype) + + if use_fma: + # Use FMA for floating-point types for better precision + return ops.fma(value_expr, t1_times_t2, self_val) + else: + # Fall back to regular arithmetic for integer types + return ops.add(self_val, ops.mul(value_expr, t1_times_t2)) + + return Pointwise.create( + device=self.get_device(), + dtype=dtype, + inner_fn=inner_fn, + ranges=self.get_size(), + ) + + +@register_lowering(aten.addcdiv, broadcast=True) +def addcdiv(self, tensor1, tensor2, *, value=1): + """ + Computes self + value * (tensor1 / tensor2) using FMA for better precision. + + Matches eager CUDA kernel order: self + value * (tensor1 / tensor2) + This is computed as: fma(value, tensor1 / tensor2, self) + + For value=1: self + tensor1 / tensor2 (no FMA needed, just add the division) + For value!=1: fma(value, div_rn(tensor1, tensor2), self) + + Note: FMA is used for floating-point types on CUDA and ROCm (via tl.fma). For + integer types we fall back to regular arithmetic since FMA doesn't support integers. + + We use div_rn (round-to-nearest division) to force proper rounding, preventing + Triton from fusing operations in ways that change the rounding behavior. + div_rn emits triton.language.div_rn on both CUDA and ROCm (unlike mul_rn, which + falls back to regular multiplication on ROCm where libdevice.mul_rn is unavailable). + """ + dtype = get_promoted_dtype( + self, + tensor1, + tensor2, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + + self_loader = self.make_loader() + t1_loader = tensor1.make_loader() + t2_loader = tensor2.make_loader() + + device = self.get_device() + use_fma = ( + dtype.is_floating_point + and device is not None + and device.type in ["cuda", "xpu"] + ) + + def inner_fn(idx): + self_val = self_loader(idx) + t1_val = t1_loader(idx) + t2_val = t2_loader(idx) + + if use_fma: + t1_div_t2 = ops.div_rn(t1_val, t2_val) + else: + t1_div_t2 = ops.truediv(t1_val, t2_val) + + if value == 1: + return ops.add(self_val, t1_div_t2) + + # Use index_expr for sympy expressions (e.g., from .item()), constant otherwise + if isinstance(value, sympy.Basic): + value_expr = ops.index_expr(value, dtype) + else: + value_expr = ops.constant(value, dtype) + + if use_fma: + return ops.fma(value_expr, t1_div_t2, self_val) + else: + return ops.add(self_val, ops.mul(value_expr, t1_div_t2)) + + return Pointwise.create( + device=self.get_device(), + dtype=dtype, + inner_fn=inner_fn, + ranges=self.get_size(), + ) + + +_foreach_addcmul_scalar = register_foreach_pointwise( + aten._foreach_addcmul.Scalar, addcmul, allow_alpha=True, scalar_kwarg="value" +) +_foreach_addcdiv_scalar = register_foreach_pointwise( + aten._foreach_addcdiv.Scalar, addcdiv, allow_alpha=True, scalar_kwarg="value" +) + + +register_pointwise_numeric_ldf64(aten.cos) +register_pointwise_numeric_ldf64(aten.sin) +abs = register_pointwise(aten.abs) +bitwise_and = register_pointwise(aten.bitwise_and) +bitwise_left_shift = register_pointwise(aten.bitwise_left_shift) +bitwise_not = register_pointwise( + aten.bitwise_not, override_fn_when_input_bool="logical_not" +) +bitwise_or = register_pointwise(aten.bitwise_or) +bitwise_right_shift = register_pointwise(aten.bitwise_right_shift) +bitwise_xor = register_pointwise(aten.bitwise_xor) +register_pointwise_numeric(aten.lgamma) +erf = register_pointwise_numeric(aten.erf) +register_lowering( + aten.special_erf, type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT +)(erf) + +register_pointwise_numeric(aten.log1p) +register_pointwise_numeric(aten.tan) +register_pointwise_numeric(aten.tanh) +register_pointwise_numeric_ldf64(aten.log) +logical_and = register_pointwise( + aten.logical_and, + type_promotion_kind=None, + convert_input_to_bool=True, + override_return_dtype=torch.bool, +) +logical_not = register_pointwise( + aten.logical_not, + type_promotion_kind=None, + convert_input_to_bool=True, + override_return_dtype=torch.bool, +) +logical_or = register_pointwise( + aten.logical_or, + type_promotion_kind=None, + convert_input_to_bool=True, + override_return_dtype=torch.bool, +) +logical_xor = register_pointwise( + aten.logical_xor, + type_promotion_kind=None, + convert_input_to_bool=True, + override_return_dtype=torch.bool, +) +maximum = register_pointwise(aten.maximum) +minimum = register_pointwise(aten.minimum) +register_lowering(aten.clamp_min)(maximum) +register_lowering(aten.clamp_max)(minimum) +register_op_dtype_propagation_rules( + "fmaximum", + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + override_return_dtype=None, +) +neg = register_pointwise(aten.neg) +abs = register_pointwise(aten.abs) +reciprocal = register_pointwise_numeric(aten.reciprocal) + +register_op_dtype_propagation_rules( + "remainder", + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + override_return_dtype=None, +) + + +@register_lowering(aten.remainder, broadcast=True) +def remainder(a, b): + a, b = promote_constants((a, b), round_scalar_constants=True) + fn = ops_wrapper("remainder") + return make_pointwise(fn)(a, b) + + +sign = register_pointwise(aten.sign, override_fn_when_input_bool="identity") +register_pointwise(aten.ceil) + + +@register_lowering(aten.signbit) +def signbit(x): + if x.get_dtype() in ( + torch.bool, + torch.uint8, + torch.uint16, + torch.uint32, + torch.uint64, + ): + return full_like(x, False, dtype=torch.bool) + fn = ops_wrapper("signbit") + return make_pointwise(fn, override_return_dtype=torch.bool)(x) + + +register_lowering(aten._neg_view)(neg) + +register_pointwise(aten.le, override_return_dtype=torch.bool) +register_pointwise(aten.lt, override_return_dtype=torch.bool) +register_pointwise(aten.ge, override_return_dtype=torch.bool) +gt = register_pointwise(aten.gt, override_return_dtype=torch.bool) +register_pointwise(aten.eq, override_return_dtype=torch.bool) +register_pointwise(aten.ne, override_return_dtype=torch.bool) + +register_pointwise_numeric(aten.cosh) +register_pointwise_numeric(aten.sinh) +register_pointwise_numeric(aten.acos) +register_pointwise_numeric(aten.acosh) +register_pointwise_numeric(aten.asin) +register_pointwise_numeric(aten.asinh) +register_pointwise_numeric(aten.atan2) +register_pointwise_numeric(aten.atan) +register_pointwise_numeric(aten.atanh) +register_pointwise_numeric(aten.copysign) +register_pointwise_numeric(aten.erfc) +register_pointwise_numeric(aten.erfinv) +register_pointwise_numeric(aten.hypot) +register_pointwise_numeric(aten.log10) +register_pointwise_numeric(aten.log2) +register_pointwise_numeric(aten.nextafter) + +from .codegen.common import BackendFeature, pointwise_overrides_data + + +def _get_pointwise_overrides(ns, name): + data = pointwise_overrides_data[name] + op = getattr(ns, data.name, None) + if op is None: + return + + def make_triton_fallback(op): + if data.triton is None: + return fallback_handler(op) + + if isinstance(op, torch._ops.OpOverloadPacket): + for ol in op.op_overloads(): + yield ol, data.type_promotion_kind, make_triton_fallback(ol) + else: + yield op, data.type_promotion_kind, make_triton_fallback(op) + + +for name in pointwise_overrides_data: + for op, type_promotion_kind, triton_fallback in _get_pointwise_overrides( + aten, name + ): + register_pointwise( + op, + name=name, + type_promotion_kind=type_promotion_kind, + triton_fallback=triton_fallback, + ) + + for op, type_promotion_kind, triton_fallback in _get_pointwise_overrides( + prims, name + ): + register_pointwise( + op, + name=name, + type_promotion_kind=type_promotion_kind, + triton_fallback=triton_fallback, + ) + + +foreach_add_list = register_foreach_pointwise( + aten._foreach_add.List, add, allow_alpha=True +) +foreach_add_scalar = register_foreach_pointwise( + aten._foreach_add.Scalar, add, allow_alpha=True +) +register_foreach_pointwise(aten._foreach_add.Tensor, add, allow_alpha=True) +foreach_mul_list = register_foreach_pointwise(aten._foreach_mul.List, mul) +register_foreach_pointwise(aten._foreach_mul.Tensor, mul) +foreach_mul_scalar = register_foreach_pointwise(aten._foreach_mul.Scalar, mul) +register_foreach_pointwise(aten._foreach_sub.List, sub, allow_alpha=True) +register_foreach_pointwise(aten._foreach_sub.Scalar, sub, allow_alpha=True) +register_foreach_pointwise(aten._foreach_neg.default, neg) +register_foreach_pointwise(aten._foreach_abs.default, abs) +register_foreach_pointwise(aten._foreach_pow.Scalar, pow) +register_foreach_pointwise(aten._foreach_pow.List, pow) +register_foreach_pointwise(aten._foreach_pow.ScalarAndTensor, pow) +foreach_div_list = register_foreach_pointwise(aten._foreach_div.List, div) +register_foreach_pointwise(aten._foreach_div.Tensor, div) +foreach_div_scalar = register_foreach_pointwise(aten._foreach_div.Scalar, div) +register_foreach_pointwise(aten._foreach_sqrt, sqrt) +register_foreach_pointwise(aten._foreach_rsqrt, rsqrt) +register_foreach_pointwise(aten._foreach_maximum.List, maximum) +register_foreach_pointwise(aten._foreach_maximum.Scalar, maximum) +register_foreach_pointwise(aten._foreach_minimum.List, minimum) +register_foreach_pointwise(aten._foreach_minimum.Scalar, minimum) +register_foreach_pointwise(aten._foreach_clamp_min.List, maximum) +register_foreach_pointwise(aten._foreach_clamp_min.Scalar, maximum) +register_foreach_pointwise(aten._foreach_clamp_max.List, minimum) +register_foreach_pointwise(aten._foreach_clamp_max.Scalar, minimum) +register_foreach_pointwise(aten._foreach_reciprocal, reciprocal) +register_foreach_pointwise(aten._foreach_sign, sign) +register_foreach_pointwise(aten._foreach_clone, clone) +foreach_copy = register_foreach_pointwise(aten._foreach_copy, copy) + + +# these are only encountered as outputs of the graph +# reinplacing epilogue copies improves compile time +# by removing extra buffers sent to the scheduler. +def register_foreach_inplace(aten_op, outplace_aten_op, outplace_op): + inplaceable_foreach_ops[outplace_aten_op] = aten_op + inplace_foreach_ops.add(aten_op) + + def fn(*args, **kwargs): + results = outplace_op(*args, **kwargs) + mut_results = [] + for arg, result in zip(args[0], results): + mut_results.append(mutate_to(arg, result, unsafe_alias=True)) + + return mut_results + + _register_foreach_lowering(aten_op, fn) + + +register_foreach_inplace( + aten._foreach_add_.List, aten._foreach_add.List, foreach_add_list +) +register_foreach_inplace( + aten._foreach_add_.Scalar, aten._foreach_add.Scalar, foreach_add_scalar +) +register_foreach_inplace( + aten._foreach_mul_.List, aten._foreach_mul.List, foreach_mul_list +) +register_foreach_inplace( + aten._foreach_mul_.Scalar, aten._foreach_mul.Scalar, foreach_mul_scalar +) +register_foreach_inplace( + aten._foreach_div_.List, aten._foreach_div.List, foreach_div_list +) +register_foreach_inplace( + aten._foreach_div_.Scalar, aten._foreach_div.Scalar, foreach_div_scalar +) +register_foreach_inplace( + aten._foreach_copy_.default, aten._foreach_copy.default, foreach_copy +) +register_foreach_inplace( + aten._foreach_addcmul_.Scalar, + aten._foreach_addcmul.Scalar, + _foreach_addcmul_scalar, +) +register_foreach_inplace( + aten._foreach_addcdiv_.Scalar, + aten._foreach_addcdiv.Scalar, + _foreach_addcdiv_scalar, +) + + +def register_inplace(aten_op, outplace_op): + @register_lowering(aten_op, type_promotion_kind=None) + def fn(*args, **kwargs): + result = outplace_op(*args, **kwargs) + result = to_dtype(result, args[0].get_dtype()) + return mutate_to(args[0], result) + + return fn + + +register_inplace(aten.add_, add) +register_inplace(aten.bitwise_and_, bitwise_and) +register_inplace(aten.bitwise_left_shift_, bitwise_left_shift) +register_inplace(aten.bitwise_not_, bitwise_not) +register_inplace(aten.bitwise_or_, bitwise_or) +register_inplace(aten.bitwise_right_shift_, bitwise_right_shift) +register_inplace(aten.bitwise_xor_, bitwise_xor) +register_inplace(aten.mul_, mul) +register_inplace(aten.div_.Tensor, div) +register_inplace(aten.div_.Tensor_mode, div_mode) +register_inplace(aten.logical_and_, logical_and) +register_inplace(aten.logical_not_, logical_not) +register_inplace(aten.logical_or_, logical_or) +register_inplace(aten.logical_xor_, logical_xor) +register_inplace(aten.sub_, sub) +register_inplace(aten.relu_, relu) +register_inplace(aten.sigmoid_, sigmoid) + + +register_lowering(aten.__and__)(bitwise_and) +register_lowering(aten.__lshift__)(bitwise_left_shift) +register_lowering(aten.__or__)(bitwise_or) +register_lowering(aten.__rshift__)(bitwise_right_shift) +register_lowering(aten.__xor__)(bitwise_xor) + +register_inplace(aten.__iand__, aten.__and__) +register_inplace(aten.__ilshift__, aten.__lshift__) +register_inplace(aten.__ior__, aten.__or__) +register_inplace(aten.__irshift__, aten.__rshift__) +register_inplace(aten.__ixor__, aten.__xor__) + + +@register_lowering(aten.sym_constrain_range) +def sym_constrain_range(a, min=None, max=None): + return None + + +def _record_symbolic_input_source( + tensor: Any, + dim: int, + expr: sympy.Expr, + kind: Literal["size", "stride"], +) -> None: + if not isinstance(expr, sympy.Symbol) or not isinstance(tensor, TensorBox): + return + + if not isinstance(tensor.data, ir.StorageBox) or not isinstance( + tensor.data.data, ir.InputBuffer + ): + return + + name = tensor.get_name() + if name not in V.graph.graph_inputs: + return + + V.graph.symbolic_input_sources.setdefault(expr, (name, kind, int(dim))) + + +@register_lowering(aten.sym_size.int) +def sym_size(a, dim): + val = V.graph.current_node.meta["val"] + if isinstance(val, torch.SymInt): + expr = val.node.expr + _record_symbolic_input_source(a, dim, expr, "size") + return expr + else: + return int(val) + + +@register_lowering(aten.sym_stride.int) +def sym_stride(a, dim): + val = V.graph.current_node.meta["val"] + if isinstance(val, torch.SymInt): + expr = val.node.expr + _record_symbolic_input_source(a, dim, expr, "stride") + return expr + else: + return int(val) + + +@register_lowering(aten.sym_numel) +def sym_numel(a): + return a.get_numel() + + +def _unwrap_symbolic_magic_arg(x): + if isinstance(x, SymTypes): + return x.node.expr + if isinstance(x, (int, float, bool)): + return sympy.sympify(x) + return x + + +for method, func in magic_methods.items(): + + @register_lowering(method_to_operator(method)) + def wrapped(*args, _func=func, **kwargs): + node = V.graph.current_node + meta_val = node.meta.get("val") if node is not None else None + if isinstance(meta_val, SymTypes): + return meta_val.node.expr + if any( + isinstance(x, (SymTypes, sympy.Basic)) + for x in itertools.chain(args, kwargs.values()) + ): + return _func( + *(_unwrap_symbolic_magic_arg(x) for x in args), + **{k: _unwrap_symbolic_magic_arg(v) for k, v in kwargs.items()}, + ) + return _func(*args, **kwargs) + + +@register_lowering(torch.sym_sum) +def sym_sum(*args): + # sym_sum can be called as sym_sum([a, b]) or sym_sum(a, b). + # Normalize to a flat list before summing. + if len(args) == 1 and isinstance(args[0], (list, tuple)): + args = args[0] + return sympy.Add(*args) + + +@register_lowering(aten._foobar) +def foobar(self, *args, **kwargs): + raise NotImplementedError("Helpful for debugging") + + +@register_lowering(torch.ops._inductor_test.realize) +def _realize(x): + x.realize() + return clone(x) + + +@register_lowering(torch.ops.inductor.resize_storage_bytes_) +def resize_storage_bytes_(variable, new_size): + variable.realize() + ir.ResizeStorageBytes(variable, new_size) + return variable + + +@register_lowering(torch.ops.aten.set_.source_Tensor) +def set__source_tensor(self, source_tensor): + self.realize() + source_tensor.realize() + return TensorBox.create(ir.SetSourceTensorKernel(self, source_tensor)) + + +@register_lowering(torch.ops.aten.shallow_copy_data_.default) +def shallow_copy_data_(self, source_tensor): + self.realize() + source_tensor.realize() + return TensorBox.create(ir.ShallowCopyDataKernel(self, source_tensor)) + + +if hasattr(torch.ops.fsdp, "copy_"): + + @register_lowering(torch.ops.fsdp.copy_.default) + def fsdp_copy_(dst, src): + if dst is src: + # dst.copy_(dst) can happen from the reinplacing pass + return dst + src = to_device(src, dst.get_device()) + src = to_dtype(src, dst.get_dtype()) + src = expand(src, dst.get_size()) + return mutate_to(dst, src) + + +@register_lowering(torch.ops.aten.resize) +def resize(x, size, *, memory_format=None): + if not (isinstance(x, TensorBox)): + raise AssertionError("expected: isinstance(x, TensorBox)") + if not (isinstance(size, (list, tuple))): + raise AssertionError("expected: isinstance(size, (list, tuple))") + + if memory_format is None: + memory_format = torch.contiguous_format + if memory_format == torch.preserve_format: + raise RuntimeError(f"unsupported memory format: {memory_format}") + + if memory_format == torch.channels_last: + if len(size) != 4: + raise AssertionError("expected: len(size) == 4") + if memory_format == torch.channels_last_3d: + if len(size) != 5: + raise AssertionError("expected: len(size) == 5") + + old_numel = x.get_numel() + dtype = x.get_dtype() + device = x.get_device_or_error() + + if ( + torch.are_deterministic_algorithms_enabled() + and torch.utils.deterministic.fill_uninitialized_memory # type: ignore[attr-defined] + ): + if is_float_dtype(dtype): + uninitialized_val = float("nan") + elif is_integer_dtype(dtype): + uninitialized_val = torch.iinfo(dtype).max + else: + uninitialized_val = True + else: + # using zero as that is what empty does + uninitialized_val = 0.0 + + if V.graph.sizevars.statically_known_equals(old_numel, 0): # type: ignore[arg-type] + return full(size, uninitialized_val, dtype=dtype, device=device) + + strides = x.maybe_get_stride() + has_overlapping = strides is not None and any( + V.graph.sizevars.statically_known_equals(s, 0) for s in strides + ) + if has_overlapping: + # overlapping: provide a contiguous logical view + x_flat = view(x, [old_numel]) + else: + # non-overlapping: keep storage order + if isinstance(x.data, ir.BaseView): + x.data = x.data.unwrap_view() + x_flat = as_strided(x, [old_numel], [1]) + flat_loader = x_flat.make_loader() + out_stride = ir.FlexibleLayout.stride_ordered_for_memory_format(size, memory_format) + out_indexer = ir.FixedLayout(device, dtype, size, out_stride).make_indexer() + + def inner_fn(idx): + flat_index = out_indexer(idx) + flat_index_expr = ops.index_expr(flat_index, torch.int64) + limit = ops.index_expr(old_numel, torch.int64) + mask = ops.lt(flat_index_expr, limit) + return ops.masked(mask, lambda: flat_loader([flat_index]), uninitialized_val) + + out = Pointwise.create( + device=device, dtype=dtype, inner_fn=inner_fn, ranges=list(size) + ) + return out + + +from torch._higher_order_ops.auto_functionalize import auto_functionalized + + +make_fallback(auto_functionalized) + + +@register_lowering(triton_kernel_wrapper_mutation) +def triton_kernel_wrap_( + *, + kernel_idx, + constant_args_idx, + grid, + tma_descriptor_metadata, + kwargs, + launch_kwargs=None, +): + from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table + + constant_args = kernel_side_table.get_constant_args(constant_args_idx) + ir.UserDefinedTritonKernel( + kernel_idx=kernel_idx, + grid=grid, + tma_descriptor_metadata=tma_descriptor_metadata, + kernel_args={**kwargs, **constant_args}, + launch_kwargs=() if launch_kwargs is None else launch_kwargs, + ) + return {key: val for key, val in kwargs.items() if isinstance(val, TensorBox)} + + +@register_lowering(torch.ops.higher_order.cond, type_promotion_kind=None) +def cond( + pred, true_fn, false_fn, operands +) -> list[ir.TensorBox | ir.ShapeAsConstantBuffer]: + # TODO: when graph_partition is enabled, skip - partitioning handles control flow + # we run into memory cleanup issue + if any(isinstance(x, IRNode) and is_triton(x) for x in [pred, *operands]): + msg = "control flow operator: torch.cond." + if stack_trace := V.graph.current_node.meta.get("stack_trace", None): + msg = f"{msg} Found from : \n {stack_trace}" + V.graph.disable_cudagraphs_reason = msg + + # The branches are reordered to [false_fn, true_fn] + # because during codegen the pred is converted to an integer with True -> 1 and False -> 0. + # When iterating over the branches the false_fn is associated index 0. + result = ir.Switch.create(pred, [false_fn, true_fn], operands, is_cond=True) + return list(map(TensorBox.create, result)) # pyrefly: ignore no-matching-overload + + +@register_lowering(torch.ops.higher_order.switch, type_promotion_kind=None) +def switch(index, branches, operands) -> list[ir.TensorBox | ir.ShapeAsConstantBuffer]: + # TODO: cudagraph support for torch.switch is not yet implemented; always disable. + msg = "control flow operator: torch.switch." + if stack_trace := V.graph.current_node.meta.get("stack_trace", None): + msg = f"{msg} Found from : \n {stack_trace}" + V.graph.disable_cudagraphs_reason = msg + + result = ir.Switch.create(index, branches, operands) + return list(map(TensorBox.create, result)) # pyrefly: ignore no-matching-overload + + +@register_lowering(torch.ops.higher_order.while_loop, type_promotion_kind=None) +def while_loop(cond_fn, body_fn, carried_inputs, additional_inputs, stack_output=False): + # TODO: when graph_partition is enabled, skip - partitioning handles control flow + # we run into memory cleanup issue + if not config.graph_partition and any( + isinstance(x, IRNode) and is_triton(x) + for x in carried_inputs + additional_inputs + ): + msg = "control flow operator: torch.while_loop." + if stack_trace := V.graph.current_node.meta.get("stack_trace", None): + msg = f"{msg} Found from : \n {stack_trace}" + V.graph.disable_cudagraphs_reason = msg + + result = ir.WhileLoop.create( + cond_fn, body_fn, carried_inputs, additional_inputs, stack_output + ) + if not (isinstance(result, Sequence)): + raise AssertionError("expected: isinstance(result, Sequence)") + return list(map(ir.WhileLoop._maybe_wrap_as_tensor_box, result)) + + +register_lowering( + torch.ops.higher_order.while_loop_stack_output, type_promotion_kind=None +)(functools.partial(while_loop, stack_output=True)) + + +@register_lowering(torch.ops.higher_order.invoke_subgraph, type_promotion_kind=None) +def invoke_subgraph(subgraph_fn: ir.Subgraph, identifier: str, *operands): + result = ir.InvokeSubgraph.create(subgraph_fn, *operands) + return list(map(TensorBox.create, result)) # type: ignore[call-overload] + + +_MISSING = object() + + +def process_subgraph_nodes(graph_module: torch.fx.GraphModule, args: list[Any]): + """Process nodes from a FX graph by executing them through V.graph. + + This is a common pattern for executing a subgraph's nodes: + - Placeholder nodes are mapped to the provided args + - Output nodes return their result + - Other nodes are executed via V.graph.run_node + + """ + output = _MISSING + + for i, node in enumerate(graph_module.graph.nodes): + if node.op == "placeholder": + if node in V.graph.env: + raise AssertionError("expected: node not in V.graph.env") + V.graph.env[node] = args[i] + continue + elif node.op == "output": + output_args, kwargs = V.graph.fetch_args_kwargs_from_env(node) + output = torch.fx.Interpreter.output(V.graph, node, output_args, kwargs) + else: + if node in V.graph.env: + raise AssertionError("expected: node not in V.graph.env") + # Track current node for error diagnostics; restore after run_node to handle nested calls correctly + saved_current_node = V.graph.current_node + try: + V.graph.current_node = node + V.graph.env[node] = V.graph.run_node(node) + finally: + V.graph.current_node = saved_current_node + + if output is _MISSING: + raise RuntimeError("No output node found in graph") + + return output + + +# Import the control_deps_op HOP for lowering +from torch._inductor.fx_passes.control_dependencies import control_deps + + +@register_lowering(control_deps, type_promotion_kind=None) +def control_deps_op_lowering(additional_deps, subgraph_fn, *args): + """ + Lower control_deps_op by ensuring dependencies are realized and tracking them. + + The control_deps_op HOP makes dependencies explicit in the graph. During lowering: + 1. Realize all additional dependencies to ensure they're computed + 2. Execute the target operation normally + 3. Track the dependencies for the scheduler + """ + # Pair lowered deps with their original FX nodes so we can handle void ops + # (e.g. record_event) that lower to None but still create operations that + # subsequent control_deps nodes (e.g. wait_event) must be ordered after. + original_dep_nodes = V.graph.current_node.args[0] + if not (isinstance(original_dep_nodes, tuple)): + raise AssertionError("expected: isinstance(original_dep_nodes, tuple)") + + dep_names: list[str] = [] + for dep, orig_node in zip(additional_deps, original_dep_nodes, strict=True): + dep_ir_nodes = [ + dep_leaf + for dep_leaf in pytree.tree_leaves(dep) + if isinstance(dep_leaf, IRNode) + ] + for dep_ir_node in dep_ir_nodes: + dep_ir_node.realize() + dep_names.append(dep_ir_node.get_name()) + if isinstance(orig_node, torch.fx.Node): + found = V.graph._void_ctrl_dep_op_names.get(orig_node, []) + dep_names.extend(found) + + original_args = V.graph.current_node.args + arg_offset = 2 # first two args (additional_deps, subgraph) + if len(args) + arg_offset != len(original_args): + raise AssertionError("expected: len(args) + arg_offset == len(original_args)") + + operation_len = len(V.graph.operations) + if len(subgraph_fn.graph_module.graph.find_nodes(op="placeholder")) != len(args): + raise AssertionError( + 'expected: len(subgraph_fn.graph_module.graph.find_nodes(op="pl...' + ) + + # Process subgraph nodes using the shared helper + output = process_subgraph_nodes(subgraph_fn.graph_module, list(args)) + + if not (additional_deps): + raise AssertionError("expected: additional_deps") + + new_ops = V.graph.operations[operation_len:] + + # Store buffer names of void ops (e.g. record_event has NoneLayout) so that + # subsequent control_deps nodes (e.g. wait_event) can depend on them even + # though void ops don't produce a usable tensor value. We detect void ops + # by NoneLayout rather than checking `output is None`, because the overall + # control_deps output may be a passthrough tuple (not None) even when the + # subgraph contains a void op. + # + # Skip ops that are not themselves named buffers (op.name is None). This + # excludes multi-output kernels like UserDefinedTritonKernel, whose buffer + # identity lives on their MutationOutput children rather than the op: the + # op is registered only as an Operation, and Buffer.get_name() asserts on + # the missing self.name. Downstream ordering for those ops is already + # captured through the named MutationOutput buffers they produce. + void_names = [ + op.get_name() + for op in new_ops + if isinstance(op, ir.Buffer) + and op.name is not None + and isinstance(op.layout, ir.NoneLayout) + ] + if void_names: + V.graph._void_ctrl_dep_op_names[V.graph.current_node] = void_names + + # some operators, like wait_tensor, just return their input, + # so its more robust to add dep to the operation itself, + # otherwise you can have a cycle of + # a = coll + # b = control_deps(a, mm, ...) + # c = control_deps(b, wait, ...) + # if c == a, then you have a cycle. + subgraph_ops = V.graph.operations[operation_len:] + for op in subgraph_ops: + for dep_name in dep_names: + op_name = op.operation_name + if op_name is None: + raise AssertionError("expected: op_name is not None") + V.graph.additional_buffer_deps[op_name].add(dep_name) + + # Pass-through versioning: inputs that are also outputs get an + # OrderingOutput so future readers are ordered after all subgraph ops. + # TODO: if control_deps ever wraps ops that truly mutate a pass-through + # (not just ordering), this needs MutationOutput instead of OrderingOutput. + input_names = OrderedSet() + for a in args: + if isinstance(a, IRNode): + a.realize() + input_names.add(a.get_name()) + output_leaves = list(pytree.tree_leaves(output)) if output is not None else [] + passthrough_vals = [] + for v in output_leaves: + if isinstance(v, IRNode): + v.realize() + if v.get_name() in input_names: + passthrough_vals.append(v) + for val in passthrough_vals: + barrier = ir.OrderingBarrier(val) + barrier_op = barrier.get_operation_name() + for op in subgraph_ops: + op_name = op.operation_name + if op_name is not None: + buf_name = op.get_buffer_name() + if buf_name is not None: + V.graph.additional_buffer_deps[barrier_op].add(buf_name) + + return output + + +@register_lowering(torch._higher_order_ops.invoke_quant, type_promotion_kind=None) +def invoke_quant_tracer(subgraph_fn: ir.Subgraph, *operands, scheme=None): + output = None + quant_options = V.graph.current_node.meta.get("quant_options", None) + if quant_options is None: + raise AssertionError("expected: quant_options is not None") + + for i, node in enumerate(subgraph_fn.graph_module.graph.nodes): + if node.op == "placeholder": + V.graph.env[node] = operands[i] + continue + # todo getattr + elif node.op == "output": + args, kwargs = V.graph.fetch_args_kwargs_from_env(node) + + for v in itertools.chain(args, kwargs.values()): + v.realize() + + if quant_options.codegen_low_precision: + V.graph.low_precision_codegen_ops.add(v.get_operation_name()) + + V.graph.invoke_quant_ops.add(v.get_operation_name()) + + output = torch.fx.Interpreter.output(V.graph, node, args, kwargs) + else: + V.graph.env[node] = V.graph.run_node(node) + + return output + + +@register_lowering(associative_scan_op, type_promotion_kind=None) +def associative_scan(combine_fn: ir.Subgraph, xs, additional_inputs: tuple[Any, ...]): + from .subgraph_lowering import InputDescriptor, lower_pointwise_subgraph + + # combine_mode="pointwise" codegen requires a backend with scan support + # (e.g. Triton on CUDA/XPU). The eager wrapper no longer enforces a device + # requirement, so check every leaf here -- before lower_pointwise_subgraph + # runs -- to raise a clear device-specific error. ir.Scan.create re-checks + # the same feature on xs[0] below and otherwise fails with a generic "Unable + # to generate code" error. See https://github.com/pytorch/pytorch/issues/186594. + for x in xs: + device = x.get_device() + if not V.graph.has_feature(device, BackendFeature.SCAN): + device_str = device.type if device is not None else "unknown device" + raise RuntimeError( + "associative_scan with combine_mode='pointwise' is not supported " + f"on {device_str}. Try to use combine_mode='generic'." + ) + + num_scan_inputs = 2 * len(xs) + placeholders = [ + node for node in combine_fn.graph_module.graph.nodes if node.op == "placeholder" + ] + additional_placeholders = placeholders[num_scan_inputs:] + if len(additional_placeholders) != len(additional_inputs): + raise RuntimeError("Unable to generate code for associative_scan op") + + # Dynamic shapes can lift symbols from the scan element metadata into the + # combine graph even when the combine function does not read them. + unsupported_inputs = [] + for arg, placeholder in zip(additional_inputs, additional_placeholders): + if not isinstance(arg, (int, sympy.Basic)) or placeholder.users: + unsupported_inputs.append(arg) + if unsupported_inputs: + raise RuntimeError( + "Unable to generate code for associative_scan op, because there are " + "unsupported lifted arguments" + ) + + subgraph_inputs = [ + InputDescriptor(dtype=x.get_dtype(), device=x.get_device()) + for x in itertools.chain(xs, xs) + ] + subgraph_inputs.extend(additional_inputs) + lowered_combine_fn = lower_pointwise_subgraph(combine_fn, subgraph_inputs) + + def wrapped_combine_fn(lhs, rhs): + return lowered_combine_fn( + *pytree.tree_leaves(lhs), + *pytree.tree_leaves(rhs), + *additional_inputs, + ) + + kwargs = _make_scan_inner(xs[0], axis=0, dtype=None) + kwargs["dtypes"] = tuple(x.get_dtype() for x in xs) + kwargs["inner_fns"] = tuple(x.make_loader() for x in xs) + result = ir.Scan.create( + combine_fn=wrapped_combine_fn, + can_fallback_to_aten=False, + **kwargs, + ) + if result[0] is None: + raise RuntimeError("Unable to generate code for associative_scan op") + return result + + +@register_lowering(torch.ops.prims._sink_tokens.default) +def _sink_tokens(tokens): + return None + + +@register_lowering(torch.ops.prims._make_token.default) +def _make_token(): + return None + + +@register_lowering(torch.ops.higher_order.with_effects, type_promotion_kind=None) +def with_effects(token, op, *args, **kwargs): + """ + We lower the operator directly, and then we add StarDep dependencies to all + the newly created nodes in the graph. + """ + from torch._higher_order_ops.effects import _get_effect, _get_schema + + # Get effect type + effect_type = _get_effect(op) + if effect_type is None and op is torch.ops.higher_order.invoke_subgraph: + from torch._guards import InvokeSubgraphCache, TracingContext + + tracing_ctx = TracingContext.try_get() + if tracing_ctx: + invoke_subgraph_cache = tracing_ctx.hop_dispatch_set_cache.get_cache( + torch.ops.higher_order.invoke_subgraph + ) + if invoke_subgraph_cache: + if not (isinstance(invoke_subgraph_cache, InvokeSubgraphCache)): + raise AssertionError( + "expected: isinstance(invoke_subgraph_cache, InvokeSubgraphCache)" + ) + # args[1] is identifier + effects = invoke_subgraph_cache.get_effects(args[1]) + if effects: + if len(effects) != 1: + raise AssertionError("Multiple effects NYI") + effect_type = next(iter(effects)) + + # Track operations before + operation_len = len(V.graph.operations) + + # Lower the op + if op in lowerings: + result = lowerings[op](*args, **kwargs) + # Realize so that we can get the ops to show up in V.graph.operations + pytree.tree_map_only(TensorBox, lambda a: a.realize(), result) + else: + + def wrap_tensors(x): + return x.wrap_for_lowering() if isinstance(x, ir.IRNode) else x + + result = pytree.tree_map( + wrap_tensors, ir.FallbackKernel.create(op, *args, **kwargs) + ) + + # Get all the operations created during the lowering above, and add StarDeps + # to the previous node with the same effect + if len(V.graph.operations[operation_len:]) <= 0: + raise AssertionError( + f"No operation nodes were generated when lowering effectful operator {op}." + ) + if effect_type: + prev_effect_buffer = V.graph.effectful_ops.get(effect_type) + for new_op in V.graph.operations[operation_len:]: + # Patch has_side_effects to return True + new_op.has_side_effects = lambda: True # pyrefly: ignore[missing-attribute] + if prev_effect_buffer: + op_name = new_op.get_name() # pyrefly: ignore[missing-attribute] + V.graph.additional_star_deps[op_name].add(prev_effect_buffer.get_name()) + # Update the effectful ops chain to point to the latest operation + V.graph.effectful_ops[effect_type] = ( + new_op # pyrefly: ignore[unsupported-operation] + ) + + try: + + def convert_ir_to_value(a): + if isinstance(a, ir.TorchBindObject): + return a.get_value() + elif isinstance(a, TensorBox): + # TensorBox wraps StorageBox, which wraps the actual buffer + # We need to get the example tensor from the inner buffer + try: + storage = a.data + if hasattr(storage, "data") and hasattr( + storage.data, "get_example" + ): + return storage.data.get_example() + except (AttributeError, NotImplementedError): + pass + # Fall back to returning the TensorBox itself if get_example fails + return a + return a + + schema_args, schema_kwargs = pytree.tree_map( + convert_ir_to_value, (args, kwargs) + ) + schema = _get_schema(op, schema_args, schema_kwargs) + except RuntimeError as e: + error_msg = str(e) + log.warning( + "Failed to get schema for %s: %s. Assuming list output", op, error_msg + ) + if isinstance(result, (tuple, list)): + return (token, *result) + else: + return (token, result) + + if len(schema.returns) == 0: + return (token, result) + elif len(schema.returns) == 1: + return (token, result) + else: + return (token, *result) + + +from .comm_lowering import register_comm_lowerings, register_symm_mem_lowerings + + +register_comm_lowerings() +register_symm_mem_lowerings() + + +@register_lowering(inductor_prims.prepare_softmax_online, type_promotion_kind=None) +def prepare_softmax_online(x, dim): + """ + Lowering inductor_prims.prepare_softmax_online to compute max/sum with + online softmax reductions when profitable. + """ + kwargs = _make_reduction_inner( + x, axis=dim, keepdims=True, dtype=None, override_return_dtype=None + ) + + rnumel = V.graph.sizevars.simplify(sympy_product(kwargs["reduction_ranges"])) + + if V.graph.sizevars.statically_known_geq( + rnumel, config.unroll_reductions_threshold + ): + max_tensor, sum_tensor = OnlineSoftmaxReduction.create( + input_node=x, num_output=2, **kwargs + ) + return max_tensor, sum_tensor + else: + amax = reduce_amax(x, dim, keepdims=True) + exp = lowerings[aten.exp](sub(x, amax)) + xsum = sum_(exp, dim, keepdims=True) + return amax, xsum + + +@register_lowering(inductor_prims.cvt_e8m0_rceil, type_promotion_kind=None) +def cvt_e8m0_rceil_lowering(inp): + """ + Lowering for cvt_e8m0_rceil. Uses PTX cvt.rp.satfinite.ue8m0x2.f32 on NVIDIA SM100+. + + The PTX instruction takes 2 float32 and outputs 2 e8m0 packed in uint16. + Currently we pass 0.0 as the second input and only use the low byte result. + """ + # TODO: Optimize to process pairs (pack=2) by creating a custom Pointwise + # that loads adjacent elements, applies PTX to both, and uses a follow-up + # kernel to extract the packed uint16 results as uint8. + if not is_nvidia_sm100_or_later(): + raise NotImplementedError( + "cvt_e8m0_rceil requires NVIDIA SM100+ (Blackwell) for PTX instruction support" + ) + + dtype = inp.get_dtype() + if dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise ValueError( + f"cvt_e8m0_rceil requires float32, float16, or bfloat16 input, got {dtype}" + ) + + # Upcast bf16/fp16 to float32 for PTX instruction + if dtype != torch.float32: + inp = to_dtype(inp, torch.float32) + + fn = functools.partial( + ops.inline_asm_elementwise, + asm="cvt.rp.satfinite.ue8m0x2.f32 $0, 0.0, $1;", + constraints="=h,r", + dtype=torch.uint16, + is_pure=True, + pack=1, + ) + result = make_pointwise(fn)(inp) + return to_dtype(result, torch.uint8) + + +@register_lowering( + torch._higher_order_ops.inline_asm_elementwise, type_promotion_kind=None +) +def lower_inline_asm_elementwise( + *inputs, asm_str, constraints, dtype, is_pure=True, pack=1 +): + inputs = broadcast_tensors(*inputs) + + input_dtypes = tuple(inp.get_dtype() for inp in inputs) + loaders = [inp.make_loader() for inp in inputs] + + def inner_fn(idx): + vals = tuple(loader(idx) for loader in loaders) + result = ops.inline_asm_elementwise( + *vals, + asm=asm_str, + constraints=constraints, + dtype=dtype, + is_pure=is_pure, + pack=pack, + input_dtypes=input_dtypes, + ) + # Inductor computes in fp32 for bf16/fp16. Upcast so fused downstream + # ops (reductions, etc.) see fp32 values. The Pointwise's storage dtype + # handles the final downcast on store. + if dtype in (torch.float16, torch.bfloat16): + result = ops.to_dtype(result, torch.float32) + return result + + return ir.Pointwise.create( + device=inputs[0].get_device(), + dtype=dtype, + inner_fn=inner_fn, + ranges=list(inputs[0].get_size()), + ) + + +# populate lowerings defined in kernel/* +from . import kernel + + +import_submodule(kernel) + +from . import ( + jagged_lowerings, + mkldnn_lowerings, # noqa: F401 # registers oneDNN fusion ops on import + quantized_lowerings, +) + + +jagged_lowerings.register_jagged_ops() +quantized_lowerings.register_quantized_ops() +quantized_lowerings.register_woq_mm_ops() + + +@contextlib.contextmanager +def force_fallback(op: torch._ops.OpOverload): + """ + A context manager to force fallback an op. Used in unit test + for FallbackKernel. + """ + if not (isinstance(op, torch._ops.OpOverload)): + raise AssertionError("Only OpOverload to make the clean up easier") + old_handler = lowerings.get(op) + try: + register_lowering(op)(fallback_handler(op)) + yield + finally: + if old_handler: + lowerings[op] = old_handler + else: + lowerings.pop(op) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/memory.py b/.venv/lib/python3.12/site-packages/torch/_inductor/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..f6b6c3d19a0e34545196ec61a88f18f84e6aad19 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/memory.py @@ -0,0 +1,1214 @@ +from __future__ import annotations + +import collections +import dataclasses +import heapq +import logging +from typing import TYPE_CHECKING, TypedDict + +import torch +from torch._environment import is_fbcode +from torch._utils_internal import signpost_event +from torch.utils._ordered_set import OrderedSet + +from . import config +from .ir import MultiOutputLayout, NoneLayout +from .utils import get_dtype_size, is_nonfreeable_buffers +from .virtualized import V + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + + from .dependencies import Dep + from .scheduler import BaseSchedulerNode, SchedulerBuffer + +from .dependencies import WeakDep + + +torch_log = logging.getLogger(__name__) + + +@dataclasses.dataclass +class PeakMemoryResult: + order: list[BaseSchedulerNode] + peak_memory: int + method: str + + +@dataclasses.dataclass +class MemoryPlanningInfoForBuffer: + size_alloc: int = 0 + size_free: int = 0 + # succ_nodes used for buffer lifetime/freeing (excludes is_fake WeakDeps) + succ_nodes: OrderedSet[BaseSchedulerNode] = dataclasses.field( + default_factory=OrderedSet + ) + # succ_nodes used for node ordering (includes is_fake WeakDeps) + succ_nodes_for_ordering: OrderedSet[BaseSchedulerNode] = dataclasses.field( + default_factory=OrderedSet + ) + + def __post_init__(self) -> None: + torch._check( + len(self.succ_nodes) <= len(self.succ_nodes_for_ordering), + lambda: f"succ_nodes must be a subset of succ_nodes_for_ordering. " + f"len(succ_nodes)={len(self.succ_nodes)}, len(succ_nodes_for_ordering)={len(self.succ_nodes_for_ordering)}", + ) + + +@dataclasses.dataclass +class MemoryPlanningInfoForNode: + index: int = 0 + size: int = 0 + pred_buffers: OrderedSet[SchedulerBuffer | FreeableInputBuffer] = dataclasses.field( + default_factory=OrderedSet + ) + pred_nodes: OrderedSet[BaseSchedulerNode] = dataclasses.field( + default_factory=OrderedSet + ) + succ_nodes: OrderedSet[BaseSchedulerNode] = dataclasses.field( + default_factory=OrderedSet + ) + + +@dataclasses.dataclass +class FreeableInputBuffer: + name: str + mpi_buffer: MemoryPlanningInfoForBuffer = dataclasses.field( + default_factory=MemoryPlanningInfoForBuffer + ) + + def get_name(self) -> str: + return self.name + + def __hash__(self) -> int: + return hash(self.name) + + +def get_freeable_input_buf( + nodes: list[BaseSchedulerNode], + graph_inputs: OrderedSet[str], +) -> dict[str, FreeableInputBuffer]: + """ + Create and keep track of all input buffers that can be freed during the program + + Returns: + A dictionary containing all freeable input buffers, keyed by their names. + """ + + def _dep_size_hint(dep: Dep) -> int: + return V.graph.get_dep_size_hint(dep) + + # get freeable input buffers' successor nodes for memory lifetime (excludes is_fake WeakDeps) + # and for ordering (includes all deps) + dep_name_to_succ_nodes: dict[str, OrderedSet[BaseSchedulerNode]] = ( + collections.defaultdict(OrderedSet) + ) + dep_name_to_succ_nodes_for_ordering: dict[str, OrderedSet[BaseSchedulerNode]] = ( + collections.defaultdict(OrderedSet) + ) + dep_name_to_size: dict[str, int] = dict() + + for node in nodes: + for dep in node.read_writes.reads: + if dep.name in graph_inputs: + if not is_nonfreeable_buffers(dep): + # All deps contribute to ordering, but fake weak deps do not contribute to + # memory liveness + dep_name_to_succ_nodes_for_ordering[dep.name].add(node) + dep_name_to_size[dep.name] = _dep_size_hint(dep) + if not (isinstance(dep, WeakDep) and dep.is_fake): + dep_name_to_succ_nodes[dep.name].add(node) + + # create FreeableInputBuffer objects and add them to the returned dictionary + name_to_freeable_input_buf: dict[str, FreeableInputBuffer] = dict() + for dep_name in dep_name_to_succ_nodes_for_ordering: + name_to_freeable_input_buf[dep_name] = FreeableInputBuffer( + dep_name, + MemoryPlanningInfoForBuffer( + size_free=dep_name_to_size[dep_name], + succ_nodes=dep_name_to_succ_nodes[dep_name], + succ_nodes_for_ordering=dep_name_to_succ_nodes_for_ordering[dep_name], + ), + ) + return name_to_freeable_input_buf + + +def compute_size_for_scheduler_buffer( + name_to_buf: dict[str, SchedulerBuffer], +) -> dict[str, tuple[int, int]]: + """ + Compute the size of each scheduler buffer, including (1) memory allocated when + it is created and (2) memory deallocated when it is freed. + + We specially handle the case of MultiOutputLayout. + Consider the following case: + buf0 = some_ops_with_multi_outputs(...) + buf1 = buf0[0] # assume 10 bytes + buf2 = buf0[1] # assume 20 bytes + In such cases, + buf0: at creation, 30 bytes allocated, when deleted, 0 bytes freed + buf1: at creation, 0 bytes allocated, when deleted, 10 bytes freed + buf2: at creation, 0 bytes allocated, when deleted, 20 bytes freed + + When an operation mutates a buffer in-place, the scheduler creates a new buffer name + to track the "before" and "after" states, even though they share the same memory. + + The mutated buffer represents a rename with zero allocation and deallocation cost. + During dependency tracking, we transfer dependencies from the mutated name back to + the original buffer, ensuring the original memory is only freed when all aliases + are done. + + This handles cases where a buffer has multiple non-overlapping aliases - rather than + trying to assign free costs to individual aliases, we forward all alias dependencies + to the original buffer. + + Consider: + buf0 = op0() + buf1 = mutation_op_(buf0) + del buf0 + ... + op(buf1) + del buf1 + + The only memory events are the creation prior to op0, and the deletion following buf1. + + Returns: + A dictionary mapping a scheduler buffer to a tuple of (size_alloc, size_free). + """ + from .ir import MultiOutput + from .scheduler import OutputNode + + sched_buf_to_size: dict[str, tuple[int, int]] = dict() + + def _compute_and_update_buf_size( + sched_buf: SchedulerBuffer, user_of_MultiOutputLayout: bool = False + ) -> int: + if sched_buf.get_name() in V.graph.scheduler.mutation_real_name: + sched_buf_to_size[sched_buf.get_name()] = (0, 0) + return 0 + elif isinstance(sched_buf.node.layout, NoneLayout): + sched_buf_to_size[sched_buf.get_name()] = (0, 0) + return 0 + elif isinstance(sched_buf.node.layout, MultiOutputLayout): + size_alloc = 0 + for user in sched_buf.users: + if isinstance(user.node, OutputNode): + continue + for buf in user.node.get_outputs(): + if isinstance(buf.node, MultiOutput): + size_alloc += _compute_and_update_buf_size(buf, True) + sched_buf_to_size[sched_buf.get_name()] = ( + 0 if user_of_MultiOutputLayout else size_alloc, + 0, + ) + return size_alloc + else: + buf_size = V.graph.sizevars.optimization_hint( + sched_buf.node.get_numel(), fallback=0 + ) * get_dtype_size(sched_buf.node.get_dtype()) + sched_buf_to_size[sched_buf.get_name()] = ( + 0 if user_of_MultiOutputLayout else buf_size, + buf_size, + ) + return buf_size + + for sched_buf in name_to_buf.values(): + # skip if sched_buf is already processed as a user of another SchedulerBuffer + # whose layout is of the type MultiOutputLayout + if sched_buf.get_name() not in sched_buf_to_size: + _compute_and_update_buf_size(sched_buf) + + return sched_buf_to_size + + +def assign_memory_planning_info_for_scheduler_buffers( + nodes: list[BaseSchedulerNode], + name_to_buf: dict[str, SchedulerBuffer], +) -> None: + """ + For each SchedulerBuffer, assign its size info and successor nodes. + A buffer's successor nodes determines when a buffer can be freed. + """ + # get buffer sizes + sched_buf_to_size = compute_size_for_scheduler_buffer(name_to_buf) + + # get buffer's successor nodes for memory lifetime (excludes is_fake WeakDeps) + # and for ordering (includes all deps) + dep_name_to_succ_nodes: dict[str, OrderedSet[BaseSchedulerNode]] = ( + collections.defaultdict(OrderedSet) + ) + dep_name_to_succ_nodes_for_ordering: dict[str, OrderedSet[BaseSchedulerNode]] = ( + collections.defaultdict(OrderedSet) + ) + for node in nodes: + for dep in node.unmet_dependencies: + # All deps contribute to ordering, but fake weak deps do not contribute to + # memory liveness + dep_name_to_succ_nodes_for_ordering[dep.name].add(node) + if not (isinstance(dep, WeakDep) and dep.is_fake): + dep_name_to_succ_nodes[dep.name].add(node) + + # iterate in reverse, so dependencies are picked up transitively. + for mutating_buf_name, real_buf_name in reversed( + V.graph.scheduler.mutation_real_name.items() + ): + dep_name_to_succ_nodes[real_buf_name] |= dep_name_to_succ_nodes[ + mutating_buf_name + ] + dep_name_to_succ_nodes_for_ordering[real_buf_name] |= ( + dep_name_to_succ_nodes_for_ordering[mutating_buf_name] + ) + + # populate the MemoryPlanningInfoForBuffer attribute to each scheduler buffer + # note: there are scheduler buffers not in dep_name_to_succ_nodes (e.g., graph outputs) + for buf_name in name_to_buf: + name_to_buf[buf_name].mpi_buffer = MemoryPlanningInfoForBuffer( + size_alloc=sched_buf_to_size[buf_name][0], + size_free=sched_buf_to_size[buf_name][1], + succ_nodes=dep_name_to_succ_nodes[buf_name], + succ_nodes_for_ordering=dep_name_to_succ_nodes_for_ordering[buf_name], + ) + + +def assign_memory_planning_info_for_scheduler_nodes( + nodes: list[BaseSchedulerNode], + name_to_fused_node: dict[str, BaseSchedulerNode], + name_to_buf: dict[str, SchedulerBuffer], + name_to_freeable_input_buf: dict[str, FreeableInputBuffer], +) -> None: + """ + Assign to each scheduler node its predecessor and successor nodes. + """ + + node_to_pred_nodes: dict[BaseSchedulerNode, OrderedSet[BaseSchedulerNode]] = ( + collections.defaultdict(OrderedSet) + ) + node_to_succ_nodes: dict[BaseSchedulerNode, OrderedSet[BaseSchedulerNode]] = {} + node_to_pred_buffers: dict[ + BaseSchedulerNode, OrderedSet[SchedulerBuffer | FreeableInputBuffer] + ] = collections.defaultdict(OrderedSet) + + # collect all predecessors using existing successor mappings + for node in nodes: + succ_nodes = OrderedSet( + succ_node + for buffer in node.get_outputs() + for succ_node in buffer.mpi_buffer.succ_nodes_for_ordering + ) + node_to_succ_nodes[node] = succ_nodes + + # For each successor, add current node as its predecessor + for succ_node in succ_nodes: + node_to_pred_nodes[succ_node].add(node) + + # For each output buffer, add it as predecessor to its successor nodes + # Use succ_nodes (not succ_nodes_for_ordering) since pred_buffers is used + # for memory lifetime tracking, not ordering + for buffer in node.get_outputs(): + for succ_node in buffer.mpi_buffer.succ_nodes: + node_to_pred_buffers[succ_node].add(buffer) + + for freeable_buffer in name_to_freeable_input_buf.values(): + for succ_node in freeable_buffer.mpi_buffer.succ_nodes: + node_to_pred_buffers[succ_node].add(freeable_buffer) + + # Second pass: assign memory planning info using completed predecessor mappings + for index, node in enumerate(nodes): + size_alloc = sum(buffer.mpi_buffer.size_alloc for buffer in node.get_outputs()) + succ_nodes = node_to_succ_nodes[node] + pred_nodes = node_to_pred_nodes[node] + + # make sure we do not make node a successor or predecessor of itself + succ_nodes.discard(node) + pred_nodes.discard(node) + + node.mpi_node = MemoryPlanningInfoForNode( + index=index, + size=size_alloc, + pred_buffers=node_to_pred_buffers[node], + pred_nodes=node_to_pred_nodes[node], + succ_nodes=succ_nodes, + ) + + +# map each scheduler buffer to its size, start step, and end step +@dataclasses.dataclass +class BufferInfo: + buffer: SchedulerBuffer | FreeableInputBuffer + size_alloc: int + size_free: int + start_step: int + end_step: int + + +def compute_memory_timeline( + nodes: list[BaseSchedulerNode], + name_to_freeable_input_buf: dict[str, FreeableInputBuffer], + graph_outputs: OrderedSet[str], +) -> tuple[ + list[BufferInfo], + dict[BaseSchedulerNode, int], + dict[FreeableInputBuffer | SchedulerBuffer, BaseSchedulerNode], +]: + """ + Compute buffer allocation and deallocation sizes and map their + lifetime to the node schedule + """ + + # get the execution step of each node, this will be used to determine + # the end_step of buffers + node_to_step: dict[BaseSchedulerNode, int] = { + node: step for step, node in enumerate(nodes) + } + + # get buffers' size and liveliness information + buf_info_list: list[BufferInfo] = [] + buf_to_snode_last_use: dict[ + FreeableInputBuffer | SchedulerBuffer, BaseSchedulerNode + ] = {} + + def _get_end_step_and_snode( + buf: FreeableInputBuffer | SchedulerBuffer, + ) -> tuple[int, BaseSchedulerNode | None]: + max_step: int = -1 + max_step_snode: BaseSchedulerNode | None = None + succ_nodes = buf.mpi_buffer.succ_nodes + if succ_nodes: + for succ_node in succ_nodes: + step = node_to_step[succ_node] + if step > max_step: + max_step = step + max_step_snode = succ_node + if max_step_snode is None: + raise AssertionError("expected max_step_snode to be set") + return max_step, max_step_snode + + # 1. for freeable input buffers + for buf_name, input_buf in name_to_freeable_input_buf.items(): + end_step = -1 + if buf_name not in graph_outputs: + end_step, end_step_snode = _get_end_step_and_snode(input_buf) + if end_step_snode is None: + raise AssertionError("expected end_step_snode to be set") + buf_to_snode_last_use[input_buf] = end_step_snode + + buf_info_list.append( + BufferInfo( + input_buf, + input_buf.mpi_buffer.size_free, + input_buf.mpi_buffer.size_free, + 0, + end_step, + ) + ) + + # 2. for scheduler buffers + for step, node in enumerate(nodes): + for sched_buf in node.get_outputs(): + # note: it is possible for a non-graph-output sched_buf to have no succ_nodes and + # to be only used by its defining op (e.g., due to fusion when all consumers of + # the buffer are fused with its defining op). In such cases, end_step is step. + buf_name = sched_buf.get_name() + end_step = -1 + if buf_name not in graph_outputs: + end_step, end_step_snode = _get_end_step_and_snode(sched_buf) + if end_step == -1: + end_step = step + buf_to_snode_last_use[sched_buf] = node + else: + if end_step_snode is None: + raise AssertionError("expected end_step_snode to be set") + buf_to_snode_last_use[sched_buf] = end_step_snode + + buf_info_list.append( + BufferInfo( + sched_buf, + sched_buf.mpi_buffer.size_alloc, + sched_buf.mpi_buffer.size_free, + step, + end_step, + ) + ) + + return buf_info_list, node_to_step, buf_to_snode_last_use + + +def peak_memory_from_buf_info_list( + buf_info_list: list[BufferInfo], num_steps: int +) -> tuple[int, list[int]]: + """Compute peak and per-step live memory from buffer lifetimes. + + Skip the free for graph-output buffers (`end_step == -1`); otherwise + `delta[0] -= size_free` would cancel the alloc. + """ + delta = [0] * (num_steps + 1) + for bi in buf_info_list: + delta[bi.start_step] += bi.size_alloc + if bi.end_step != -1: + delta[bi.end_step + 1] -= bi.size_free + + max_memory = 0 + cur_memory = 0 + memories_at_nodes = [0] * (num_steps + 1) + for t in range(num_steps + 1): + cur_memory += delta[t] + memories_at_nodes[t] = cur_memory + if cur_memory > max_memory: + max_memory = cur_memory + return max_memory, memories_at_nodes + + +def live_memory_before_steps_from_buf_info_list( + buf_info_list: list[BufferInfo], num_steps: int +) -> list[int]: + """Compute live bytes before each scheduler step runs.""" + delta = [0] * (num_steps + 1) + cur_memory = 0 + for bi in buf_info_list: + if isinstance(bi.buffer, FreeableInputBuffer): + cur_memory += bi.size_alloc + else: + delta[bi.start_step + 1] += bi.size_alloc + + if bi.end_step != -1: + delta[bi.end_step + 1] -= bi.size_free + + live_before = [0] * (num_steps + 1) + live_before[0] = cur_memory + for t in range(1, num_steps + 1): + cur_memory += delta[t] + live_before[t] = cur_memory + return live_before + + +def estimate_peak_memory( + nodes: list[BaseSchedulerNode], + name_to_freeable_input_buf: dict[str, FreeableInputBuffer], + graph_outputs: OrderedSet[str], +) -> tuple[int, list[int]]: + """ + Given a list of nodes in their execution order, estimate the peak memory, by + keeping track of the liveliness of SchedulerBuffers and FreeableInputBuffers. + + Returns: + int: peak memory + List[int]: memory usage at each node (or each step). + """ + buf_info_list, _, _ = compute_memory_timeline( + nodes, name_to_freeable_input_buf, graph_outputs + ) + return peak_memory_from_buf_info_list(buf_info_list, len(nodes)) + + +def estimate_region_peak_memory( + nodes_in_window: Iterable[BaseSchedulerNode], + *, + region_start: int, + region_end: int, + step_of: Callable[[BaseSchedulerNode], int], + graph_outputs: OrderedSet[str], + cur_memory: int = 0, +) -> int: + """Peak memory inside `[region_start, region_end]` for the + hypothetical post-reorder schedule. + + Walks `nodes_in_window` (post-rewrite, in proposed order). For + each node: alloc = sum of `size_alloc` over its outputs; free = + sum of `size_free` over `pred_buffers` whose proposed last + consumer is this node. Then accumulates per step starting from + `cur_memory` (live bytes at the window boundary) and returns + the maximum live bytes. + """ + R = region_end - region_start + 1 + region = [SNodeMemory(0, 0) for _ in range(R)] + + for node in nodes_in_window: + s = step_of(node) + slot = s - region_start + if not (0 <= slot < R): + raise AssertionError(f"expected 0 <= slot < {R}, got {slot}") + + for buf in node.get_outputs(): + bi = buf.mpi_buffer + region[slot].size_alloc += bi.size_alloc + name = buf.get_name() + if name in graph_outputs: + continue + succ_steps = [step_of(n) for n in bi.succ_nodes] + if not succ_steps: + region[slot].size_free += bi.size_free + + for pb in node.mpi_node.pred_buffers: + name = pb.get_name() + if name in graph_outputs: + continue + succ_steps = [step_of(n) for n in pb.mpi_buffer.succ_nodes] + if not succ_steps: + raise AssertionError("expected non-empty succ_steps") + if max(succ_steps) == s: + region[slot].size_free += pb.mpi_buffer.size_free + + cur = cur_memory + peak = cur + for af in region: + cur += af.size_alloc + if cur > peak: + peak = cur + cur -= af.size_free + return peak + + +@dataclasses.dataclass +class SNodeMemory: + size_alloc: int + size_free: int + + +def estimate_peak_memory_allocfree( + nodes: list[BaseSchedulerNode], + name_to_freeable_input_buf: dict[str, FreeableInputBuffer], + graph_outputs: OrderedSet[str], +) -> tuple[ + int, + list[tuple[int, int]], + dict[BaseSchedulerNode, SNodeMemory], + dict[FreeableInputBuffer | SchedulerBuffer, BaseSchedulerNode], +]: + """ + Alternative version of estimate_peak_memory, that respects the fact, + that every SchedulerNode has multiple phases: + 1. alloc ( outputs ) + 2. run_kernel + 3. dealloc last_use buffers + estimate_peak_memory collapses memory into one value: size_alloc - size_free + While peak memory happens after alloc. + + Duplicating the code to not migrate all callsites at once, + In future usages of estimate_peak_memory will migrate to this version. + """ + + buf_info_list, _, buf_to_snode_last_use = compute_memory_timeline( + nodes, name_to_freeable_input_buf, graph_outputs + ) + + # incremental memory changes at each step + step_idx_allocfree = [SNodeMemory(0, 0) for _ in range(len(nodes))] + + # for each buffer, update memory when created and when freed + for buf_info in buf_info_list: + step_idx_allocfree[buf_info.start_step].size_alloc += buf_info.size_alloc + if buf_info.end_step != -1: + step_idx_allocfree[buf_info.end_step].size_free += buf_info.size_free + + snodes_allocfree = {} + for i, node in enumerate(nodes): + snodes_allocfree[node] = step_idx_allocfree[i] + + max_memory = 0 + cur_memory = 0 + snodes_curr_memory = [] + for t in range(len(nodes)): + alloc = step_idx_allocfree[t].size_alloc + free = step_idx_allocfree[t].size_free + cur_memory += alloc + post_alloc = cur_memory + max_memory = max(max_memory, cur_memory) + cur_memory -= free + post_free = cur_memory + snodes_curr_memory.append((post_alloc, post_free)) + + return ( + max_memory, + snodes_curr_memory, + snodes_allocfree, + buf_to_snode_last_use, + ) + + +def topological_sort_lpmf( + nodes: list[BaseSchedulerNode], + name_to_freeable_input_buf: dict[str, FreeableInputBuffer], + name_to_buf: dict[str, SchedulerBuffer], + graph_outputs: OrderedSet[str], +) -> list[BaseSchedulerNode]: + """ + A bfs-based greedy topological order. LPMF stands for "Least Peak Memory First". + + The idea is from this paper: + Buffer memory optimization for video codec application modeled in Simulink + https://www.cs.york.ac.uk/rts/docs/DAC-1964-2006/PAPERS/2006/DAC06/PDFFILES/P0689.PDF + + The algorithm maintains the max memory so far. + At every iteration, for each scheduleable node, it computes: + - how much memory needs to be allocated for the output buffers of this node; + - how much memory can be freed as a result of executing this node. + This gives us two values for each node: + (1) mem1: memory during the execution of the node; + (2) mem2: memory after executing the node, after some input buffers are freed. + The greedy approach select as follows: + (i) if there are nodes whose mem1 values are below the max memory so far, + then pick the node with the lowest mem2 value; + (ii) otherwise, pick the one with the lowest mem1 value. + """ + + class NodeInfo(TypedDict): + indegree: int + memory_to_free: int + + class BufferInfo(TypedDict): + outdegree: int + + node_info: dict[BaseSchedulerNode, NodeInfo] = dict() + buf_info: dict[SchedulerBuffer | FreeableInputBuffer, BufferInfo] = dict() + + # compute nodes' number of unmet dependencies (for schedulability) + # initialize the list of nodes ready to be scheduled + nodes_to_schedule: OrderedSet[BaseSchedulerNode] = OrderedSet() + for node in nodes: + node_info[node] = { + "indegree": len(node.mpi_node.pred_nodes), + "memory_to_free": 0, + } + if node_info[node]["indegree"] == 0: + nodes_to_schedule.add(node) + + # compute buffers' number of unmet successors (used to decide when to free) + for buf in list(name_to_buf.values()) + list(name_to_freeable_input_buf.values()): + buf_info[buf] = { + "outdegree": len(buf.mpi_buffer.succ_nodes) + + (1 if buf.get_name() in graph_outputs else 0) + } + + # initialize memory estimations + live_memory = sum( + input_buf.mpi_buffer.size_free + for input_buf in name_to_freeable_input_buf.values() + ) + + # this is the total output memory, which is a lower bound for peak memory + # we do not include the memory of non freeable input buffers + output_memory = 0 + for buf_name in graph_outputs: + if buf_name in name_to_buf: + output_memory += name_to_buf[buf_name].mpi_buffer.size_free + elif buf_name in name_to_freeable_input_buf: + output_memory += name_to_freeable_input_buf[buf_name].mpi_buffer.size_free + max_memory = max(live_memory, output_memory) + memory_gap = max_memory - live_memory + + # compute the amount of memory that is allocated when a node is scheduled + # and the amount of memory that can be freed when a node is scheduled + for node in nodes: + # 1. if a buffer read by this node is last used by this node + for buf in node.mpi_node.pred_buffers: + if buf_info[buf]["outdegree"] == 1: + node_info[node]["memory_to_free"] += buf.mpi_buffer.size_free + # 2. if a buffer written by this node is used internally and not used later + for buf in node.get_outputs(): + if buf_info[buf]["outdegree"] == 0: + node_info[node]["memory_to_free"] += buf.mpi_buffer.size_free + + # schedule nodes one at a time + schedule: list[BaseSchedulerNode] = [] + size_threshold = config.size_threshold_for_succ_based_strategy + num_iters: int = 0 + while num_iters < len(nodes) and nodes_to_schedule: + # select a node to schedule: + if ( + size_threshold > 0 + and min(node.mpi_node.size for node in nodes_to_schedule) > size_threshold + ): + selected_node = min( + nodes_to_schedule, + key=lambda node: min( + ( + succ_node.mpi_node.index + for succ_node in node.mpi_node.succ_nodes + ), + default=len(nodes), + ), + ) + else: + selected_node = min( + nodes_to_schedule, + key=lambda node: ( + node.mpi_node.size if node.mpi_node.size > memory_gap else 0, + node.mpi_node.size - node_info[node]["memory_to_free"], + node.mpi_node.index, + ), + ) + nodes_to_schedule.remove(selected_node) + schedule.append(selected_node) + num_iters += 1 + + # update memory usage + live_memory += selected_node.mpi_node.size + max_memory = max(max_memory, live_memory) + live_memory -= node_info[selected_node]["memory_to_free"] + memory_gap = max_memory - live_memory + + # update successor nodes and nodes_to_schedule + for succ_node in selected_node.mpi_node.succ_nodes: + if node_info[succ_node]["indegree"] <= 0: + raise AssertionError( + f"expected positive indegree, got {node_info[succ_node]['indegree']}" + ) + node_info[succ_node]["indegree"] -= 1 + if node_info[succ_node]["indegree"] == 0: + nodes_to_schedule.add(succ_node) + + # update predecessor nodes + for buf in selected_node.mpi_node.pred_buffers: + if buf_info[buf]["outdegree"] <= 0: + raise AssertionError( + f"expected positive outdegree, got {buf_info[buf]['outdegree']}" + ) + buf_info[buf]["outdegree"] -= 1 + if buf_info[buf]["outdegree"] == 1: + for succ_node in buf.mpi_buffer.succ_nodes: + node_info[succ_node]["memory_to_free"] += buf.mpi_buffer.size_free + + if num_iters > len(nodes): + raise RuntimeError("Failed to schedule, while loop ran too long for lpmf") + + return schedule + + +def topological_sort_bfs(nodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]: + """ + A BFS topological sort that selects nodes whose dependencies are executed the + earliest. This follows a FIFO idea. Specifically, at every iteration, for each node + that is schedulable, we gather the order in which its predecessor nodes are executed, + and this sorted list of execution orders of predecessor nodes defines the priority. + We select the node whose predecessors nodes are executed the earliest. The FIFO + idea aims to reduce the liveness duration of buffers created. + """ + + class NodeInfo(TypedDict): + indegree: int + order: int + + node_info: dict[BaseSchedulerNode, NodeInfo] = dict() + + @dataclasses.dataclass + class NodeWithPriority: + priority: list[int] + node: BaseSchedulerNode + + def __lt__(self, other: NodeWithPriority) -> bool: + if self.priority == other.priority: + return self.node.mpi_node.index < other.node.mpi_node.index + return self.priority < other.priority + + def _node_priority(node: BaseSchedulerNode) -> list[int]: + # priority is the order in which predecessor nodes are executed + if node_info[node]["indegree"] != 0: + raise AssertionError( + f"expected zero indegree, got {node_info[node]['indegree']}" + ) + exec_orders = sorted( + OrderedSet( + node_info[pred_node]["order"] for pred_node in node.mpi_node.pred_nodes + ) + ) + return exec_orders + + # compute nodes' number of unmet dependencies (for schedulability) + # initialize the list of nodes ready to be scheduled + nodes_to_schedule: list[NodeWithPriority] = [] + for node in nodes: + node_info[node] = {"indegree": len(node.mpi_node.pred_nodes), "order": -1} + if node_info[node]["indegree"] == 0: + heapq.heappush( + nodes_to_schedule, NodeWithPriority(_node_priority(node), node) + ) + + # schedule nodes one at a time + schedule: list[BaseSchedulerNode] = [] + num_iters: int = 0 + while num_iters < len(nodes) and nodes_to_schedule: + # select a node to schedule + selected_node = heapq.heappop(nodes_to_schedule).node + node_info[selected_node]["order"] = len(schedule) + schedule.append(selected_node) + num_iters += 1 + + # update successor nodes and nodes_to_schedule + for succ_node in selected_node.mpi_node.succ_nodes: + if node_info[succ_node]["indegree"] <= 0: + raise AssertionError( + f"expected positive indegree, got {node_info[succ_node]['indegree']}" + ) + node_info[succ_node]["indegree"] -= 1 + if node_info[succ_node]["indegree"] == 0: + heapq.heappush( + nodes_to_schedule, + NodeWithPriority(_node_priority(succ_node), succ_node), + ) + + if num_iters > len(nodes): + raise RuntimeError("Failed to schedule, while loop ran too long for bfs") + + return schedule + + +def topological_sort_dfs(nodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]: + """ + This is a DFS topological sort. The setup is similar to `topological_sort_schedule` + in scheduler.py. The difference is the order nodes are visited in the outer loop. + In `topological_sort_schedule`, nodes are visited in their original order. + In this function, nodes are visited based on their priority -- for each node, we + compute the total memory of all buffers it reads from or writes to, and we visit + the nodes in ascending order of this priority. + """ + seen: OrderedSet[BaseSchedulerNode] = OrderedSet() + name_to_node: dict[str, BaseSchedulerNode] = dict() + result: list[BaseSchedulerNode] = [] + size_with_reads: dict[BaseSchedulerNode, int] = dict() + + def visit(n: BaseSchedulerNode) -> None: + if n not in seen: + seen.add(n) + dep_nodes = [ + name_to_node[dep.name] + for dep in n.unmet_dependencies + if dep.name in name_to_node + ] + for node in sorted( + dep_nodes, key=lambda n: (size_with_reads[n], n.mpi_node.index) + ): + visit(node) + result.append(n) + + for node in nodes: + for name in node.get_buffer_names(): + name_to_node[name] = node + + for node in nodes: + size_with_reads[node] = node.mpi_node.size + sum( + pred_buf.mpi_buffer.size_free for pred_buf in node.mpi_node.pred_buffers + ) + for node in sorted(nodes, key=lambda n: (size_with_reads[n], n.mpi_node.index)): + visit(node) + + return result + + +def validate_graph_acyclic(nodes: list[BaseSchedulerNode]) -> None: + """ + Validate that the graph is acyclic by checking predecessor relationships. + + Raises: + RuntimeError: If a cycle is detected in the graph + """ + # DFS coloring scheme for cycle detection: + # WHITE (0): Node has not been visited yet + # GRAY (1): Node is currently being processed (in the recursion stack) + # BLACK (2): Node has been completely processed (finished exploring all its predecessors) + # A back edge (cycle) is detected when we encounter a GRAY node during DFS traversal + WHITE, GRAY, BLACK = 0, 1, 2 + color = dict.fromkeys(nodes, WHITE) + path: list[BaseSchedulerNode] = [] # Track current DFS path + + def dfs_visit(node: BaseSchedulerNode) -> None: + if color[node] == BLACK: + return + + if color[node] == GRAY: + path.append(node) + path_info = " -> ".join([node.get_name() for node in path]) + + raise RuntimeError( + f"Cycle detected in memory planning graph" + f"Path containing cycle (i -> j: j is a dependency of i): {path_info} " + f"This indicates invalid dependency relationships in the scheduler graph" + ) + + color[node] = GRAY + path.append(node) + + for pred_node in node.mpi_node.pred_nodes: + if pred_node == node: + raise AssertionError("expected pred_node != node (self-loop)") + dfs_visit(pred_node) + + path.pop() + color[node] = BLACK + + # Start DFS from all unvisited nodes + for node in nodes: + if color[node] == WHITE: + dfs_visit(node) + + +def validate_unique_buffer_names( + nodes: list[BaseSchedulerNode], + name_to_buf: dict[str, SchedulerBuffer], + name_to_freeable_input_buf: dict[str, FreeableInputBuffer], +) -> None: + """ + Validate that for each node's output buffer, the name_to_buf mapping is correct. + For each output buffer buf, we should have name_to_buf[buf.get_name()] == buf. + Also validate that no buffer names overlap with freeable input buffer names. + + Raises: + RuntimeError: If buffer name mapping is incorrect or names overlap + """ + for node in nodes: + for buf in node.get_outputs(): + buf_name = buf.get_name() + + # Check if buffer name exists in the mapping + if buf_name not in name_to_buf: + raise RuntimeError( + f"{buf_name} from {node.get_name()} is not found in name_to_buf mapping." + f" This indicates a missing buffer mapping." + ) + + # Check if the mapping points to the correct buffer object + if name_to_buf[buf_name] != buf: + raise RuntimeError( + f"Buffer name mapping is incorrect for '{buf_name}'." + f"Expected name_to_buf['{buf_name}'] to be {buf.debug_str()}" + f"but got {name_to_buf[buf_name].debug_str()}" + f"This indicates some buffers share the same name" + ) + + # Check if buffer name conflicts with freeable input buffer names + if buf_name in name_to_freeable_input_buf: + raise RuntimeError( + f"Buffer name conflict detected: '{buf_name}' from node {node.get_name()} " + f"is also used as a freeable input buffer name. " + ) + + +def prepare_planning_info( + nodes: list[BaseSchedulerNode], + name_to_buf: dict[str, SchedulerBuffer], + name_to_fused_node: dict[str, BaseSchedulerNode], + graph_inputs: OrderedSet[str], + graph_outputs: OrderedSet[str], +) -> tuple[int, dict[str, FreeableInputBuffer]]: + """ + Prepare planning info. As nodes are scheduled one at a time, these help + keep track of when a buffer can be freed, and when a node can be scheduled + + Returns: + int: peak memory estimation + dict[str, FreeableInputBuffer]: name to freeable input buffer + """ + name_to_freeable_input_buf = get_freeable_input_buf(nodes, graph_inputs) + assign_memory_planning_info_for_scheduler_buffers(nodes, name_to_buf) + assign_memory_planning_info_for_scheduler_nodes( + nodes, name_to_fused_node, name_to_buf, name_to_freeable_input_buf + ) + + # the default + estimated_peak_memory, _ = estimate_peak_memory( + nodes, name_to_freeable_input_buf, graph_outputs + ) + + return estimated_peak_memory, name_to_freeable_input_buf + + +def reorder_for_peak_memory( + nodes: list[BaseSchedulerNode], + name_to_buf: dict[str, SchedulerBuffer], + name_to_fused_node: dict[str, BaseSchedulerNode], + graph_inputs: OrderedSet[str], + graph_outputs: OrderedSet[str], + methods: list[Callable[..., list[BaseSchedulerNode]]] = [ # noqa: B006 + topological_sort_lpmf, + topological_sort_bfs, + topological_sort_dfs, + ], +) -> list[BaseSchedulerNode]: + """ + Try a few heuristics based topological sort algorithms, and pick the one whose + resulting topological order has the lowest peak memory estimation. + """ + + torch_log.info("Reordering for peak memory -- %d nodes", len(nodes)) + + estimated_peak_memory, name_to_freeable_input_buf = prepare_planning_info( + nodes, + name_to_buf, + name_to_fused_node, + graph_inputs, + graph_outputs, + ) + + # export graph for simulator if needed + if config.reorder_for_peak_memory_debug: + export_graph_for_simulator( + nodes, + name_to_freeable_input_buf, + name_to_fused_node, + graph_inputs, + graph_outputs, + ) + + # Validate planning info before proceeding with reordering + try: + validate_graph_acyclic(nodes) + validate_unique_buffer_names(nodes, name_to_buf, name_to_freeable_input_buf) + except RuntimeError: + torch_log.exception("Memory planning validation failed") + if not is_fbcode(): # TODO: remove after ensuring OSS side is safe + raise + + # keep track of the peak memory estimates of different methods + peak_memory_diff_methods: list[PeakMemoryResult] = [] + peak_memory_diff_methods.append( + PeakMemoryResult(nodes, estimated_peak_memory, "baseline") + ) + torch_log.info("Baseline peak memory: %d", estimated_peak_memory) + + # other methods + for method in methods: + try: + if method is topological_sort_lpmf: + order = method( + nodes, name_to_freeable_input_buf, name_to_buf, graph_outputs + ) + else: + order = method(nodes) + if len(order) != len(nodes): + raise AssertionError( + f"expected order length {len(nodes)}, got {len(order)}" + ) + peak_memory, _ = estimate_peak_memory( + order, name_to_freeable_input_buf, graph_outputs + ) + peak_memory_diff_methods.append( + PeakMemoryResult(order, peak_memory, method.__name__) + ) + torch_log.info("%s peak memory: %d", method.__name__, peak_memory) + except Exception: + torch_log.exception("Failed to reorder for %s", method.__name__) + if not is_fbcode(): # TODO: remove after ensuring OSS side is safe + raise + + signpost_event( + category="inductor", + name="memory", + parameters={ + "orm": {elem.method: elem.peak_memory for elem in peak_memory_diff_methods}, + }, + ) + + # get the optimal one + best_result = min(peak_memory_diff_methods, key=lambda x: x.peak_memory) + + return best_result.order + + +def export_graph_for_simulator( + nodes: list[BaseSchedulerNode], + name_to_freeable_input_buf: dict[str, FreeableInputBuffer], + name_to_fused_node: dict[str, BaseSchedulerNode], + graph_inputs: OrderedSet[str], + graph_outputs: OrderedSet[str], +) -> None: + """ + This is for debugging purposes. It will dump a json file that records graph information. + The graph can then be used in a simulator: https://fburl.com/code/3l3d3qi4 + """ + + class ORMBuffer(TypedDict): + name: str + size_alloc: int + size_free: int + size: int # for backward compatibility + is_input: bool + is_output: bool + deps: list[str] + unmet_deps: list[str] + + class ORMNode(TypedDict): + name: str + buffer_names: list[str] + + class ORMGraph(TypedDict): + nodes: list[ORMNode] + buffers: list[ORMBuffer] + + orm_buffers: list[ORMBuffer] = [] + orm_nodes: list[ORMNode] = [] + + # get orm buffers for freeable input buffers + for buf_name, input_buf in name_to_freeable_input_buf.items(): + orm_buf_input_buffer: ORMBuffer = { + "name": buf_name, + "size_alloc": input_buf.mpi_buffer.size_free, + "size_free": input_buf.mpi_buffer.size_free, + "size": input_buf.mpi_buffer.size_free, + "is_input": True, + "is_output": buf_name in graph_outputs, + "deps": [], + "unmet_deps": [], + } + orm_buffers.append(orm_buf_input_buffer) + + # get orm buffers for scheduler buffers + name_to_buf: dict[str, SchedulerBuffer] = { + buf.get_name(): buf for node in nodes for buf in node.get_outputs() + } # need to reassign due to probably node pruning + for buf_name, sched_buf in name_to_buf.items(): + if sched_buf.defining_op is None: + continue + deps = [ + pred_buf.get_name() + for pred_buf in name_to_fused_node[ + sched_buf.defining_op.get_name() + ].mpi_node.pred_buffers + ] + orm_buf_scheduler_buffer: ORMBuffer = { + "name": buf_name, + "size_alloc": sched_buf.mpi_buffer.size_alloc, + "size_free": sched_buf.mpi_buffer.size_free, + "size": sched_buf.mpi_buffer.size_free, + "is_input": False, + "is_output": buf_name in graph_outputs, + "deps": deps, + "unmet_deps": [ + buf_name for buf_name in deps if buf_name not in graph_inputs + ], + } + orm_buffers.append(orm_buf_scheduler_buffer) + + # get orm nodes + for node in nodes: + orm_node: ORMNode = { + "name": node.get_name(), + "buffer_names": list(node.get_buffer_names()), + } + orm_nodes.append(orm_node) + + # create the graph object + g: ORMGraph = { + "nodes": orm_nodes, + "buffers": orm_buffers, + } + + # dump the graph + import json + import os + + import torch + from functorch.compile import get_graph_being_compiled + + name = os.path.splitext(get_graph_being_compiled())[0] + "_fused" + + g_str = json.dumps(g, indent=2) + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": name, + "encoding": "string", + }, + payload_fn=lambda: g_str, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/metrics.py b/.venv/lib/python3.12/site-packages/torch/_inductor/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..956c1a66581542fa87fe40bcbb38c139ac08031a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/metrics.py @@ -0,0 +1,496 @@ +from __future__ import annotations + +import csv +import dataclasses +import inspect +import os +import re +from dataclasses import dataclass +from functools import lru_cache +from typing import TYPE_CHECKING + +from torch._inductor import config +from torch._inductor.utils import get_benchmark_name +from torch.utils._ordered_set import OrderedSet + + +# Prevent circular import +if TYPE_CHECKING: + from collections.abc import Callable + + from torch._inductor.runtime.triton_compat import Config + from torch._inductor.scheduler import BaseSchedulerNode + +# counter for tracking how many kernels have been generated +generated_kernel_count = 0 +generated_cpp_vec_kernel_count = 0 +num_bytes_accessed = 0 +nodes_num_elem: list[ + tuple[ + BaseSchedulerNode, + int, + ] +] = [] +node_runtimes: list[tuple[BaseSchedulerNode, float]] = [] + +# counters for tracking fusions +ir_nodes_pre_fusion = 0 + +# counters for tracking to_dtype inserted +cpp_to_dtype_count = 0 + + +@dataclasses.dataclass +class CppOuterLoopFusedCount: + inner_kernel_number: int + local_buffer_number: int = 0 + + +# The length counts the number of outer loop fusions. +cpp_outer_loop_fused_inner_counts: list[CppOuterLoopFusedCount] = [] + +num_comprehensive_padding = 0 +num_matches_for_scatter_upon_const_tensor = 0 + +num_loop_reordering = 0 +num_auto_chunking: int = 0 + +# counter for parallel reduction. +parallel_reduction_count = 0 + +codegen_mix_order_reduction: int = 0 +rejected_mix_order_reduction_fusion: int = 0 +codegen_nested_reduction: int = 0 + + +# reset all counters +def reset() -> None: + global generated_kernel_count + global generated_cpp_vec_kernel_count + global num_bytes_accessed, nodes_num_elem + global ir_nodes_pre_fusion + global cpp_to_dtype_count + global cpp_outer_loop_fused_inner_counts + global num_comprehensive_padding + global num_matches_for_scatter_upon_const_tensor + global num_loop_reordering + global parallel_reduction_count + global codegen_mix_order_reduction + global rejected_mix_order_reduction_fusion + global codegen_nested_reduction + global num_auto_chunking + + generated_kernel_count = 0 + generated_cpp_vec_kernel_count = 0 + num_bytes_accessed = 0 + nodes_num_elem.clear() + node_runtimes.clear() + ir_nodes_pre_fusion = 0 + cpp_to_dtype_count = 0 + cpp_outer_loop_fused_inner_counts.clear() + num_comprehensive_padding = 0 + num_matches_for_scatter_upon_const_tensor = 0 + num_loop_reordering = 0 + parallel_reduction_count = 0 + codegen_mix_order_reduction = 0 + rejected_mix_order_reduction_fusion = 0 + codegen_nested_reduction = 0 + num_auto_chunking = 0 + + +@dataclass +class CachedMetricsDeltas: + """ + The subset of metrics we want update across cache hits, e.g., the + FxGraphCache. + """ + + generated_kernel_count: int + generated_cpp_vec_kernel_count: int + ir_nodes_pre_fusion: int + cpp_to_dtype_count: int + num_bytes_accessed: int + num_matches_for_scatter_upon_const_tensor: int + + +def get_metric_fields() -> list[str]: + return [field.name for field in dataclasses.fields(CachedMetricsDeltas)] + + +class CachedMetricsHelper: + """ + A helper class to help calculate and apply counter deltas for those + metrics we want to save with cache entries (e.g., FxGraphCache) and + apply on a cache hit. + """ + + def __init__(self) -> None: + self.cached_metrics = {} + for metric in get_metric_fields(): + self.cached_metrics[metric] = globals()[metric] + + def get_deltas(self) -> CachedMetricsDeltas: + delta_metrics = {} + for metric in get_metric_fields(): + delta_metrics[metric] = globals()[metric] - self.cached_metrics[metric] + + return CachedMetricsDeltas(**delta_metrics) + + @staticmethod + def apply_deltas(delta: CachedMetricsDeltas) -> None: + for metric in get_metric_fields(): + globals()[metric] += getattr(delta, metric) + + +REGISTERED_METRIC_TABLES: dict[str, MetricTable] = {} + + +@dataclass +class MetricTable: + table_name: str + column_names: list[str] + + num_rows_added: int = 0 + + def add_row(self, row_fn: Callable[[], dict[str, str | float | None]]) -> None: + if self.table_name not in enabled_metric_tables(): + return + + row_dict = row_fn() + if len(self.column_names) != len(row_dict): + raise AssertionError(f"{len(self.column_names)} v.s. {len(row_dict)}") + if OrderedSet(self.column_names) != OrderedSet(row_dict.keys()): + raise AssertionError( + f"{OrderedSet(self.column_names)} v.s. {OrderedSet(row_dict.keys())}" + ) + + bn = get_benchmark_name() + # assert bn is not None + row = [bn] + [row_dict[column_name] for column_name in self.column_names] + if not all(isinstance(i, (str, float, type(None))) for i in row): + raise AssertionError("expected all row values to be str, float, or None") + self._write_row(row) + + def output_filename(self) -> str: + return f"metric_table_{self.table_name}.csv" + + def write_header(self) -> None: + filename = self.output_filename() + with open(filename, "w") as fd: + writer = csv.writer(fd, lineterminator="\n") + writer.writerow(["model_name"] + self.column_names) + + def _write_row(self, row: list[str | float | None]) -> None: + filename = self.output_filename() + if self.num_rows_added == 0 and not os.path.exists(filename): + self.write_header() + + self.num_rows_added += 1 + + for idx, orig_val in enumerate(row): + if isinstance(orig_val, float): + new_val = f"{orig_val:.6f}" + elif orig_val is None: + new_val = "" + else: + new_val = orig_val + row[idx] = new_val + + with open(filename, "a") as fd: + writer = csv.writer(fd, lineterminator="\n") + writer.writerow(row) + + @staticmethod + def register_table(name: str, column_names: list[str]) -> None: + table = MetricTable(name, column_names) + REGISTERED_METRIC_TABLES[name] = table + + +MetricTable.register_table( + "slow_fusion", + [ + "kernel1_path", + "kernel1_latency", + "kernel2_path", + "kernel2_latency", + "fused_kernel_path", + "fused_kernel_latency", + "slow_down_ratio", + ], +) + +# track the fusion statistics for each graph +MetricTable.register_table( + "graph_stats", + [ + "graph_id", + "num_nodes_before_fusion", + "num_nodes_after_fusion", + ], +) + +# track the perf difference between persistent reduction and non-persistent +# reductions +MetricTable.register_table( + "persistent_red_perf", + [ + "kernel0_path", + "kernel1_path", + "kernel2_path", + "kernel3_path", + "kernel0_latency", + "kernel1_latency", + "kernel2_latency", + "kernel3_latency", + "size_hints", + "reduction_hint", + ], +) + +# Log the fusion failures due to indexing mismatch +MetricTable.register_table( + "fusion_failure_due_to_indexing_mismatch", + [ + "pre_grad_graph_id", + "post_grad_graph_id", + "node1_name", + "node2_name", + "node1_debug_str", + "node2_debug_str", + "common_buffer_names", + "failure_reason", + ], +) + +# Log metadata for pointwise/reduction kernels. E.g., model name, kernel path, numel, rnumel, reduction hint +MetricTable.register_table( + "kernel_metadata", + [ + "kernel_name", + "kernel_path", + "kernel_category", # pointwise/reduction/foreach etc. + "size_hints", + "reduction_hint", + "line_of_code", + "num_load", + "num_store", + "num_for_loop", + "num_atomic_add", + "num_args", + # xyz numel can be different to size_hints since size_hints are rounded + # up to the nearest power of 2. + # Inductor kernel will burn in the xyz numel in kernel code for static + # shape kernels. + # Logging them will be helpful to find unaligned shape for reduction + "xnumel", + "ynumel", + "rnumel", + "kernel_args_num_gb", + ], +) + + +def _parse_kernel_fn_code(kernel_module_code: str) -> str: + """ + The kernel_module_code is the python module that contains kernel function code. + kernel function is the proper triton kernel function annotated with + @triton.jit + """ + from .codecache import PyCodeCache + from .wrapper_benchmark import get_triton_kernel + + mod = PyCodeCache.load(kernel_module_code) + kernel = get_triton_kernel(mod) + # kernel is a CachingAutotune; kernel.fn is the JITFunction; + # kernel.fn.fn is the function being decorate by triton.jit + return inspect.getsource(kernel.fn.fn) + + +def _parse_kernel_line_of_code(proper_kernel_fn_code: str) -> int: + """ + Return the line of code for the kernel excluding the decorators. + """ + return len(proper_kernel_fn_code.splitlines()) + + +def _parse_size_hints(kernel_module_code: str, kernel_category: str) -> str | None: + if kernel_category == "foreach": + # foreach kernel does not have size_hints + return None + m = re.search(r"size_hints=(\[[0-9, ]*\]),", kernel_module_code) + if not m: + raise AssertionError("size_hints missing!") + return m.group(1) + + +def _parse_reduction_hint(kernel_category: str, kernel_module_code: str) -> str | None: + if kernel_category not in ("reduction", "persistent_reduction"): + return None + m = re.search(r"reduction_hint=ReductionHint\.(\w*),", kernel_module_code) + if not m: + raise AssertionError("reduction_hint not found in kernel source code!") + return m.group(1) + + +def _count_pattern(proper_kernel_fn_code: str, pattern: str) -> int: + return proper_kernel_fn_code.count(pattern) + + +def _count_args(proper_kernel_fn_code: str) -> int: + def_line = proper_kernel_fn_code.splitlines()[0] + if not def_line.startswith("def "): + raise AssertionError( + f"expected def line to start with 'def ', got {def_line!r}" + ) + start_idx = def_line.index("(") + end_idx = def_line.index("):") + decl_csv = def_line[start_idx + 1 : end_idx] + comps = decl_csv.split(",") + return len(comps) + + +def _parse_proper_kernel_fn_code(kernel_fn_code: str) -> str: + """ + Skip decorators. + """ + start_pos = kernel_fn_code.index("def ") + return kernel_fn_code[start_pos:] + + +def _parse_numel(proper_kernel_fn_code: str, numel_arg_name: str) -> int | None: + m = re.search(f"{numel_arg_name} = ([\\d]+)", proper_kernel_fn_code) + if m: + return int(m.group(1)) + else: + return None + + +def _parse_kernel_args_num_gb( + kernel_fn_code: str, kernel_category: str +) -> float | None: + """ + inductor meta looks like: + inductor_meta={... 'mutated_arg_names': [], 'no_x_dim': False, 'kernel_num_gb': 2.0}, + """ + m = re.search(r".kernel_num_gb.:\s*([0-9.]+)", kernel_fn_code) + if m: + return float(m.group(1)) + else: + """ + There are a few cases that kernel_num_gdb field can be missing: + 1. the field will be missing if config.benchmark_kernel and + config.profile_bandwidth are false + 2. even if config.benchmark_kernel or config.profile_bandwidth is true. + foreach kernel does not have kernel_num_gb field in the metadata + """ + return None + + +def log_kernel_metadata( + kernel_name: str, kernel_path: str, kernel_module_code: str +) -> None: + """ + A utility to log kernel metadata. We may parse metadata from kernel source code here. + + It's fine to parse the generated kernel code here since the logging is + disabled by default. It would hurt compilation time. + """ + from .wrapper_benchmark import get_kernel_category_by_source_code + + kernel_category = get_kernel_category_by_source_code(kernel_module_code) + reduction_hint = _parse_reduction_hint(kernel_category, kernel_module_code) + size_hints = _parse_size_hints(kernel_module_code, kernel_category) + kernel_fn_code = _parse_kernel_fn_code(kernel_module_code) + + proper_kernel_fn_code = _parse_proper_kernel_fn_code(kernel_fn_code) + + # the line of code excluding the decortors + kernel_line_of_code = _parse_kernel_line_of_code(proper_kernel_fn_code) + + get_metric_table("kernel_metadata").add_row( + lambda: { + "kernel_name": kernel_name, + "kernel_path": kernel_path, + "kernel_category": kernel_category, + "size_hints": size_hints, + "reduction_hint": reduction_hint, + "line_of_code": kernel_line_of_code, + "num_load": _count_pattern(proper_kernel_fn_code, "tl.load"), + "num_store": _count_pattern(proper_kernel_fn_code, "tl.store"), + "num_for_loop": _count_pattern(proper_kernel_fn_code, "for "), + "num_atomic_add": _count_pattern(proper_kernel_fn_code, "tl.atomic_add"), + "num_args": _count_args(proper_kernel_fn_code), + "xnumel": _parse_numel(proper_kernel_fn_code, "xnumel"), + "ynumel": _parse_numel(proper_kernel_fn_code, "ynumel"), + "rnumel": _parse_numel(proper_kernel_fn_code, "rnumel"), + "kernel_args_num_gb": _parse_kernel_args_num_gb( + kernel_fn_code, kernel_category + ), + } + ) + + +def purge_old_log_files() -> None: + """ + Purge the old log file at the beginning when the benchmark script runs. + Should do it in the parent process rather than the child processes running + each individual model. + """ + for name, table in REGISTERED_METRIC_TABLES.items(): + if name in enabled_metric_tables(): + filename = table.output_filename() + if os.path.exists(filename): + os.unlink(filename) + + table.write_header() + + +def enabled_metric_tables() -> OrderedSet[str]: + return enabled_metric_tables_impl(config.enabled_metric_tables) + + +@lru_cache +def enabled_metric_tables_impl(config_str: str) -> OrderedSet[str]: + enabled: OrderedSet[str] = OrderedSet() + for name in config_str.split(","): + name = name.strip() + if not name: + continue + if name not in REGISTERED_METRIC_TABLES: + raise AssertionError(f"Metric table name {name} is not registered") + enabled.add(name) + return enabled + + +def is_metric_table_enabled(name: str) -> bool: + return name in enabled_metric_tables() + + +def get_metric_table(name: str) -> MetricTable: + if name not in REGISTERED_METRIC_TABLES: + raise AssertionError(f"Metric table {name} is not defined") + return REGISTERED_METRIC_TABLES[name] + + +MetricTable.register_table( + "kernel_autotune", + [ + "kernel_path", + "kernel_name", + "triton_config", + "latency_ms", + ], +) + + +def log_kernel_autotune_result( + kernel_path: str, kernel_name: str, config: Config, latency: float +) -> None: + get_metric_table("kernel_autotune").add_row( + lambda: { + "kernel_path": kernel_path, + "kernel_name": kernel_name, + "triton_config": str(config), + "latency_ms": latency, + } + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/mkldnn_ir.py b/.venv/lib/python3.12/site-packages/torch/_inductor/mkldnn_ir.py new file mode 100644 index 0000000000000000000000000000000000000000..d07577ba1a4e68a8778cfda9c0bd6a54a9acb59b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/mkldnn_ir.py @@ -0,0 +1,1397 @@ +# mypy: allow-untyped-defs +from collections.abc import Sequence +from typing import Any, Optional + +import sympy + +import torch +from torch._prims_common import make_channels_last_strides_for, StrideType +from torch.utils._ordered_set import OrderedSet + +from .ir import ( + ExternKernelAlloc, + FixedLayout, + FlexibleLayout, + get_device_type, + ir_node_to_tensor, + IRNode, + is_contiguous_storage_and_layout, + Layout, + may_convert_to_optional, + MultiOutput, + MultiOutputLayout, + MutationOutput, + NoneLayout, + TensorBox, +) +from .utils import convert_shape_to_inductor, pad_listlike, SUPPORTED_MKLDNN_DEVICES +from .virtualized import V + + +def _prepare_convolution_fusion_create( + cls, + x: "TensorBox", + weight: "TensorBox", + bias: "TensorBox", + padding: Sequence[int], + stride: Sequence[int], + dilation: Sequence[int], + groups: int, + transposed: bool = False, + output_padding: Sequence[int] | None = None, + quantize_args: list["TensorBox"] | None = None, + other: Optional["TensorBox"] = None, +): + """ + This function is a helper function to prepare inputs, layout and constant args + for convolution post-op fusion's create function, including deciding the output + layout (channels first or channels last), realizing inputs and make them etc. The + function only supports the CPU/XPU device since conv post-op fusion kernel is only + supported on CPU/XPU right now. + """ + + # Port from aten/src/ATen/native/ConvUtils.h: _conv_input_size + def _conv_input_size( + output_size, weight_size, padding, output_padding, stride, dilation, groups + ): + if len(output_size) != len(weight_size): + raise AssertionError("Expect input dim == weight dim") + dim = len(output_size) + if dim <= 2: + raise AssertionError("Expect input dim > 2") + + BATCH_DIM = 0 + WEIGHT_INPUT_CHANNELS_DIM = 1 + input_size = [] + input_size.append(output_size[BATCH_DIM]) + input_size.append(weight_size[WEIGHT_INPUT_CHANNELS_DIM] * groups) + for d in range(2, dim): + kernel = (weight_size[d] - 1) * dilation[d - 2] + 1 + input_size_d = ( + (output_size[d] - 1) * stride[d - 2] + - (padding[d - 2] * 2) + + kernel + + output_padding[d - 2] + ) + input_size.append(input_size_d) + return list(map(int, input_size)) + + # Port from aten/src/ATen/native/ConvUtils.h: _conv_output_size + def _conv_output_size(input_size, weight_size, padding, stride, dilation=None): + has_dilation = dilation is not None + dim = len(input_size) + output_size = [] + output_size.append(input_size[0]) + output_size.append(weight_size[0]) + for d in range(2, dim): + # pyrefly: ignore [unsupported-operation] + dilation_ = dilation[d - 2] if has_dilation else 1 + kernel = dilation_ * (weight_size[d] - 1) + 1 + output_size_d = (input_size[d] + (2 * padding[d - 2]) - kernel) // stride[ + d - 2 + ] + 1 + output_size.append(output_size_d) + return output_size + + # The size of prepacked_weight is the prepacked weight size of deconv: + # Groups > 1: [g*o, i/g, ...] + # Groups == 1: [o, i, ...] + # Returns original weight size in [i, o, ...] + def _original_deconv_weight_size( + prepacked_weight, + groups, + ): + prepacked_weight_size = prepacked_weight.size() + dim = len(prepacked_weight_size) + if dim <= 2: + raise AssertionError("Expect weight dim > 2") + if groups > 1: + weight_size = [] + weight_size.append(prepacked_weight_size[1] * groups) + weight_size.append(prepacked_weight_size[0] / groups) + weight_size.extend(prepacked_weight_size[d] for d in range(2, dim)) + else: + weight_size = prepacked_weight.transpose(0, 1).size() + return weight_size + + x.realize() + weight.realize() + if bias is not None: + bias.realize() + with V.graph.fake_mode: + # TODO cleaned up the fake_tensor trace as Linear implementation + x_fake = ir_node_to_tensor(x) + weight_fake = ir_node_to_tensor(weight) + dims = len(x_fake.size()) - 2 + if not (0 < len(padding) <= dims): + raise AssertionError(f"expected 0 < len(padding) <= {dims}") + if not (0 < len(dilation) <= dims): + raise AssertionError(f"expected 0 < len(dilation) <= {dims}") + if not (0 < len(stride) <= dims): + raise AssertionError(f"expected 0 < len(stride) <= {dims}") + padding = pad_listlike(padding, dims) + dilation = pad_listlike(dilation, dims) + stride = pad_listlike(stride, dims) + if output_padding is None: + output_padding = pad_listlike([0], dims) + else: + if not (0 < len(output_padding) <= dims): + raise AssertionError(f"expected 0 < len(output_padding) <= {dims}") + output_padding = pad_listlike(output_padding, dims) + if not isinstance(groups, (int, sympy.core.numbers.Integer)): + raise AssertionError(f"expected groups to be int, got {type(groups)}") + if transposed: + # When transposed, the size of the prepacked oneDNN weight is different + # from the PyTorch weight. We're not able to run aten conv with such + # size. We infer the output size from the input params here: + weight_size = _original_deconv_weight_size(weight_fake, groups) + input_size = x_fake.size() + output_size = _conv_input_size( + input_size, + weight_size, + padding, + output_padding, + stride, + dilation, + groups, + ) + else: + x_shape = list(x_fake.shape) + weight_shape = list(weight_fake.shape) + if len(x_shape) != len(weight_shape): + if not (len(x_shape) == 3 and len(weight_shape) == 4): + raise AssertionError( + f"expected len(x_shape) == 3 and len(weight_shape) == 4, " + f"got {len(x_shape)} and {len(weight_shape)}" + ) + weight_shape.pop(2) + output_size = _conv_output_size( + x_shape, + weight_shape, + padding, + stride, + dilation, + ) + + req_stride_order = [0] + list(reversed(range(1, len(stride) + 1))) + req_stride_order = [len(req_stride_order)] + req_stride_order + + x = cls.require_stride_order(x, req_stride_order) + + # We won't do weight prepack for Conv if dynamic_shapes or if is xpu. + # In static shape cases, since weight is prepacked, we'll always force output to be channels last in the Conv kernel. + # In dynamic shape cases, for input with channels = 1, like tensor of size (s0, 1, 28, 28) and stride (784, 784, 28, 1), + # x = cls.require_stride_order(x, req_stride_order) where req_stride_order is in the channels last order + # won't change the stride of this tensor since stride for dimensions of size 1 is ignored. While in Conv kernel, + # this tensor is considered as channels first and the output will be in contiguous format. + # To align the behavior of the Conv kernel, we set the output_stride in such case to be contiguous instead of channels last. + dynamic_shapes = not all(isinstance(i, int) for i in (output_size)) + if ( + dynamic_shapes or get_device_type(x) == "xpu" + ) and is_contiguous_storage_and_layout(x): + output_stride: StrideType = FlexibleLayout.contiguous_strides(output_size) + # Currently we don't support channel last for the situation that stride of input's batch dim is 0, + # eg. input_size = (1, 1280, 64, 64), but input_stride=(0, 1, 81920, 1280). + # So we use NCHW here instead. + # Different with cpu, cpu conv always use channels_last for convolution when weight is prepacked, + # but xpu does not do the prepack, so the problem exposed here is only for xpu. + # TODO support channels_last for such zero stride input. + elif get_device_type(x) == "xpu" and x.get_stride()[0] == 0: + output_stride = FlexibleLayout.contiguous_strides(output_size) + else: + output_stride = make_channels_last_strides_for(output_size) + + if get_device_type(x) != get_device_type(weight): + raise AssertionError( + f"expected x and weight on same device, got " + f"{get_device_type(x)} and {get_device_type(weight)}" + ) + if get_device_type(x) not in SUPPORTED_MKLDNN_DEVICES: + raise AssertionError(f"unsupported mkldnn device {get_device_type(x)}") + inputs = [x] + + if quantize_args is not None: + x_scale, x_zero_point, w_scale, w_zero_point = quantize_args + x_scale.realize() + x_zero_point.realize() + w_scale.realize() + w_zero_point.realize() + inputs = inputs + [x_scale, x_zero_point] + [weight] + [w_scale, w_zero_point] + else: + inputs += [weight] + + if other is not None: + other = cls.require_stride_order(other, req_stride_order) + if not isinstance(other, TensorBox): + raise AssertionError(f"expected other to be TensorBox, got {type(other)}") + inputs += [other] + + kernel_layout = FixedLayout( + x.get_device_or_error(), + x.get_dtype(), + convert_shape_to_inductor(output_size), + convert_shape_to_inductor(output_stride), + ) + constant_args = [padding, stride, dilation, groups] + if transposed: + constant_args.insert(1, output_padding) + + if bias is not None: + inputs.append(bias) + else: + constant_args.insert(0, bias) + return inputs, constant_args, kernel_layout, req_stride_order, other + + +def _prepare_linear_fusion_create( + cls, + x: "TensorBox", + weight: "TensorBox", + bias: "TensorBox", + quantize_args: list["TensorBox"] | None = None, + other: Optional["TensorBox"] = None, + binary_sum: bool = False, +): + """ + This function is a helper function to prepare inputs, layout and constant args + for linear post-op fusion's create function. The function only supports the CPU device + since linear post-op fusion kernel is only supported on CPU right now. + """ + x.realize() + weight.realize() + if bias is not None: + bias.realize() + + *m, _ = x.get_size() + # The weight has been transposed during the qlinear weight prepack process. + # https://github.com/pytorch/pytorch/blob/4979f9c0d72490970e2019bb1d2284f83d93f76b/ + # aten/src/ATen/native/quantized/cpu/qlinear_prepack.cpp#L291 + _, oc = weight.get_size() + output_size = list(m) + [oc] + req_stride_order = list(reversed(range(len(x.get_size())))) + + x = cls.require_stride_order(x, req_stride_order) + if get_device_type(x) != get_device_type(weight): + raise AssertionError( + f"expected x and weight on same device, got " + f"{get_device_type(x)} and {get_device_type(weight)}" + ) + if get_device_type(x) not in SUPPORTED_MKLDNN_DEVICES: + raise AssertionError(f"unsupported mkldnn device {get_device_type(x)}") + inputs = [x] + + if quantize_args is not None: + x_scale, x_zero_point, w_scale, w_zero_point = quantize_args + x_scale.realize() + x_zero_point.realize() + w_scale.realize() + w_zero_point.realize() + inputs = inputs + [x_scale, x_zero_point] + [weight] + [w_scale, w_zero_point] + else: + inputs += [weight] + + if other is not None: + if binary_sum: + other = cls.require_stride_order(other, req_stride_order) + inputs = inputs + [other] + + output_stride = FlexibleLayout.contiguous_strides(output_size) + kernel_layout = FixedLayout( + x.get_device(), + x.get_dtype(), + output_size, + output_stride, + ) + constant_args: list[Any] = [] + + if bias is not None: + inputs.append(bias) + else: + constant_args.insert(0, bias) + return inputs, constant_args, kernel_layout, req_stride_order, other + + +def _create_output_node(packed): + output_ir = MultiOutput( + packed.get_layout(), + packed, + [], + ) + packed.layout = MultiOutputLayout(device=packed.get_device()) + packed.outputs = [output_ir] + return output_ir + + +class ConvolutionUnary(ExternKernelAlloc): + def __init__( + self, + layout, + inputs, + constant_args=(), + ) -> None: + self.device_type = get_device_type(inputs[0]) + super().__init__( + layout, + inputs, + constant_args, + None, + op_overload=torch.ops.mkldnn._convolution_pointwise.default, + cpp_kernel_name=f"aoti_torch_{self.device_type}_mkldnn__convolution_pointwise", + ) + + def codegen(self, wrapper): + wrapper.include_extra_header( + f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h" + ) + super().codegen(wrapper) + + @classmethod + def create( + cls, + x: "TensorBox", + weight: "TensorBox", + bias: "TensorBox", + padding_: list[int], + stride_: list[int], + dilation_: list[int], + groups: int, + attr, + scalars: list[Any] | None, + algorithm, + ): + ( + inputs, + constant_args, + kernel_layout, + _, + _, + ) = _prepare_convolution_fusion_create( + cls, x, weight, bias, padding_, stride_, dilation_, groups + ) + constant_args = constant_args + [ + attr, + may_convert_to_optional(scalars), + algorithm, + ] + packed = ConvolutionUnary( + layout=kernel_layout, + inputs=inputs, + constant_args=constant_args, + ) + return _create_output_node(packed) + + +class ConvolutionBinary(ExternKernelAlloc): + def __init__( + self, + layout, + inputs, + constant_args=(), + cpp_constant_args=(), + ) -> None: + self.device_type = get_device_type(inputs[0]) + super().__init__( + layout, + inputs, + constant_args, + None, + op_overload=torch.ops.mkldnn._convolution_pointwise.binary, + cpp_kernel_name=f"aoti_torch_{self.device_type}_mkldnn__convolution_pointwise_binary", + ) + self.cpp_constant_args = cpp_constant_args + + def codegen(self, wrapper): + wrapper.include_extra_header( + f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h" + ) + super().codegen(wrapper) + + @classmethod + def create( + cls, + x: "TensorBox", + other: "TensorBox", + weight: "TensorBox", + bias: "TensorBox", + padding_: list[int], + stride_: list[int], + dilation_: list[int], + groups: int, + binary_attr: str, + binary_alpha: float | None, + unary_attr: str | None, + unary_scalars: list[Any] | None, + unary_algorithm: str | None, + ): + ( + inputs, + constant_args, + kernel_layout, + req_stride_order, + _, + ) = _prepare_convolution_fusion_create( + cls, x, weight, bias, padding_, stride_, dilation_, groups + ) + # pyrefly: ignore [bad-assignment] + other = cls.require_stride_order(other, req_stride_order) + inputs.insert(1, other) + constant_args = constant_args + [ + binary_attr, + binary_alpha, + unary_attr, + may_convert_to_optional(unary_scalars), + unary_algorithm, + ] + packed = ConvolutionBinary( + layout=kernel_layout, + inputs=inputs, + constant_args=constant_args, + ) + return _create_output_node(packed) + + +class ConvolutionBinaryInplace(ExternKernelAlloc): + def __init__( + self, + kernel_layout, + inputs, + constant_args=(), + ) -> None: + # Due to constraint of op.call, other (Tensor&) should be at input[0] + self.device_type = get_device_type(inputs[0]) + reordered_inputs = [inputs[1], inputs[0]] + inputs[2:] + + super().__init__( + kernel_layout, + reordered_inputs, + constant_args, + None, + op_overload=torch.ops.mkldnn._convolution_pointwise_.binary, + cpp_kernel_name=f"aoti_torch_{self.device_type}_mkldnn__convolution_pointwise_binary_", + ) + + self.mutation_outputs = [ + MutationOutput(NoneLayout(device=inputs[0].get_device()), inputs[0], self), + MutationOutput(NoneLayout(device=inputs[1].get_device()), inputs[1], self), + ] + + def codegen(self, wrapper): + wrapper.include_extra_header( + f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h" + ) + super().codegen(wrapper) + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + @classmethod + def create( + cls, + x: "TensorBox", + other: "TensorBox", + weight: "TensorBox", + bias: "TensorBox", + padding_: list[int], + stride_: list[int], + dilation_: list[int], + groups: int, + binary_attr: str, + binary_alpha: float | None, + unary_attr: str | None, + unary_scalars: list[Any] | None, + unary_algorithm: str | None, + ): + ( + inputs, + constant_args, + _, + req_stride_order, + _, + ) = _prepare_convolution_fusion_create( + cls, x, weight, bias, padding_, stride_, dilation_, groups + ) + # pyrefly: ignore [bad-assignment] + other = cls.require_stride_order(other, req_stride_order) + inputs.insert(1, other) + constant_args = constant_args + [ + binary_attr, + binary_alpha, + unary_attr, + may_convert_to_optional(unary_scalars), + unary_algorithm, + ] + packed = ConvolutionBinaryInplace( + kernel_layout=NoneLayout(device=inputs[1].get_device()), # type: ignore[arg-type] + inputs=inputs, + constant_args=constant_args, + ) + # This op mutates in place which means that the result is not the + # target but rather the input that is being mutated + # init reorders the inputs, so inputs[1] becomes packed.inputs[0] + return packed.inputs[0] + + +class ConvolutionTransposeUnary(ExternKernelAlloc): + def __init__( + self, + layout, + inputs, + constant_args=(), + ) -> None: + self.device_type = get_device_type(inputs[0]) + super().__init__( + layout, + inputs, + constant_args, + None, + op_overload=torch.ops.mkldnn._convolution_transpose_pointwise.default, + cpp_kernel_name=f"aoti_torch_{self.device_type}_mkldnn__convolution_transpose_pointwise", + ) + + def codegen(self, wrapper): + wrapper.include_extra_header( + f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h" + ) + super().codegen(wrapper) + + @classmethod + def create( + cls, + x: "TensorBox", + weight: "TensorBox", + bias: "TensorBox", + padding_: list[int], + output_padding_: list[int], + stride_: list[int], + dilation_: list[int], + groups_: int, + attr, + scalars: list[Any] | None, + algorithm, + ): + transposed = True + ( + inputs, + constant_args, + kernel_layout, + _, + _, + ) = _prepare_convolution_fusion_create( + cls, + x, + weight, + bias, + padding_, + stride_, + dilation_, + groups_, + transposed, + output_padding_, + ) + constant_args = constant_args + [ + attr, + may_convert_to_optional(scalars), + algorithm, + ] + packed = ConvolutionTransposeUnary( + layout=kernel_layout, + inputs=inputs, + constant_args=constant_args, + ) + return _create_output_node(packed) + + +class QConvPointWisePT2E(ExternKernelAlloc): + def __init__( + self, + layout, + inputs, + constant_args=(), + ) -> None: + """ + if bias is not None + - inputs = [x, w, b, weight_scale, weight_zp] + - const_args is: [stride, padding, dilation, groups, x_scale, x_zp, o_scale, o_zp, + fp32_output, unary_attr, unary_scalars, unary_algorithm] + else + - inputs = [x, w, weight_scale, weight_zp] + - const_args is: [bias, stride, padding, dilation, groups, x_scale, x_zp, o_scale, o_zp, + fp32_output, unary_attr, unary_scalars, unary_algorithm] + """ + self.device_type = get_device_type(inputs[0]) + self.has_bias = len(inputs) == 5 + super().__init__( + layout, + inputs, + constant_args, + None, + op_overload=torch.ops.onednn.qconv_pointwise.tensor, + cpp_kernel_name=f"aoti_torch_{self.device_type}__qconv_pointwise_tensor", + ) + + def codegen(self, wrapper): + wrapper.include_extra_header( + f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h" + ) + super().codegen(wrapper) + if isinstance(self.layout, Layout): + self.codegen_size_asserts(wrapper) + + @classmethod + def create( + cls, + qx: "TensorBox", + x_scale: "TensorBox", + x_zero_point: "TensorBox", + qw: "TensorBox", # qw + w_scale: "TensorBox", + w_zero_point, + bias: "TensorBox", + stride: list[int], + padding: list[int], + dilation: list[int], + groups: int, + output_scale: float, + output_zero_point: int, + output_dtype, + attr, + scalars, + algorithm, + ): + transposed = False + output_padding = None + ( + inputs, + constant_args, + kernel_layout, + _, + _, + ) = _prepare_convolution_fusion_create( + cls, + qx, + qw, + bias, + padding, + stride, + dilation, + groups, + transposed, + output_padding, + [x_scale, x_zero_point, w_scale, w_zero_point], # type: ignore[list-item] + ) + # swap padding and stride to align with functional conv arg order + if bias is None: + constant_args[1], constant_args[2] = constant_args[2], constant_args[1] + else: + constant_args[0], constant_args[1] = constant_args[1], constant_args[0] + + constant_args = constant_args + [ + output_scale, + output_zero_point, + output_dtype, + attr, + may_convert_to_optional(scalars), + algorithm, + ] + + if output_dtype is None: + raise AssertionError("expected output_dtype to be not None") + if output_dtype in [torch.float32, torch.bfloat16]: + # in _prepare_convolution_fusion_create, we use x.dtype (uint8) to create kernel_layout + # if we set output_dtype is not None, the output buf should be output_dtype instead of uint8. + kernel_layout.dtype = output_dtype + + return QConvPointWisePT2E( + layout=kernel_layout, + inputs=inputs, + constant_args=constant_args, + ) + + +class QConvPointWiseBinaryPT2E(ExternKernelAlloc): + def __init__( + self, + layout, + inputs, + constant_args=(), + ) -> None: + """ + Needs input/weight/output qparams + if bias is not None + - inputs = [x, x_scale, x_zp, w, w_scale, w_zp, accum, b] + - const_args = [stride, padding, dilation, groups, o_scale, o_zp, + output_dtype, accum_scale, accum_zp, binary_attr, alpha, unary_attr, unary_scalars, unary_algorithm] + else + - inputs = [x, x_scale, x_zp, w, w_scale, w_zp, accum] + - const_args [b, stride, padding, dilation, groups, o_scale, o_zp, + output_dtype, accum_scale, accum_zp, binary_attr, alpha, unary_attr, unary_scalars, unary_algorithm] + """ + self.device_type = get_device_type(inputs[0]) + self.has_bias = len(inputs) == 8 + self.idx_for_inplace_sum = 6 + super().__init__( + layout, + inputs, + constant_args, + None, + op_overload=torch.ops.onednn.qconv2d_pointwise.binary_tensor, + cpp_kernel_name=( + f"aoti_torch_{self.device_type}__qconv2d_pointwise_binary_tensor" + ), + ) + + def codegen(self, wrapper): + wrapper.include_extra_header( + f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h" + ) + super().codegen(wrapper) + if isinstance(self.layout, Layout): + self.codegen_size_asserts(wrapper) + + def get_mutation_names(self) -> Sequence[str]: + return [self.input_name(self.idx_for_inplace_sum)] + + def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet() + + @classmethod + def create( + cls, + qx: "TensorBox", + x_scale: "TensorBox", + x_zero_point: "TensorBox", + qw: "TensorBox", # packed_weight + w_scale, + w_zero_point, + qaccum: "TensorBox", + bias: "TensorBox", + stride: list[int], + padding: list[int], + dilation: list[int], + groups: int, + output_scale: "TensorBox", + output_zero_point: "TensorBox", + output_dtype, + accum_scale, + accum_zero_point, + binary_attr, + alpha, + unary_attr, + unary_scalars, + unary_algorithm, + ): + transposed = False + output_padding = None + ( + inputs, + constant_args, + _kernel_layout, + req_stride_order, + qaccum, + ) = _prepare_convolution_fusion_create( + cls, + qx, + qw, + bias, + padding, + stride, + dilation, + groups, + transposed, + output_padding, + [x_scale, x_zero_point, w_scale, w_zero_point], + qaccum, + ) + + # swap padding and stride to align with functional conv arg order + if bias is None: + constant_args[1], constant_args[2] = constant_args[2], constant_args[1] + else: + constant_args[0], constant_args[1] = constant_args[1], constant_args[0] + + constant_args = constant_args + [ + output_scale, + output_zero_point, + output_dtype, + accum_scale, + accum_zero_point, + binary_attr, + alpha, + unary_attr, + may_convert_to_optional(unary_scalars), + unary_algorithm, + ] + + if binary_attr != "sum": + raise AssertionError( + "For now, only post op sum is supported in QConvPointWiseBinaryPT2E." + ) + + V.graph.mark_buffer_mutated(qaccum.get_name()) + packed = QConvPointWiseBinaryPT2E( + layout=NoneLayout(device=qaccum.get_device()), + inputs=inputs, + constant_args=constant_args, + ) + + # Return accum since it has been inplace changed. + return packed.inputs[packed.idx_for_inplace_sum] + + +class MKLPackedLinear(ExternKernelAlloc): + def __init__( + self, + layout, + inputs, + constant_args=(), + ) -> None: + super().__init__( + layout, + inputs, + constant_args, + None, + op_overload=torch.ops.mkl._mkl_linear.default, + ) + + def codegen(self, wrapper): + wrapper.include_extra_header("torch/csrc/inductor/aoti_torch/c/shim_cpu.h") + super().codegen(wrapper) + + @classmethod + def create(cls, x, packed_w, orig_w, B, batch_size): + x = cls.require_stride1(cls.realize_input(x)) + orig_w = cls.require_stride1(cls.realize_input(orig_w)) + *m, _ = x.get_size() + oc, _ = orig_w.get_size() + output_size = list(m) + [oc] + output_stride = FlexibleLayout.contiguous_strides(output_size) + inputs = [x, packed_w, orig_w] + constant_args = [batch_size] + if B is not None: + inputs += [B] + else: + constant_args.insert(0, None) + + device = x.get_device() + if device is None: + raise AssertionError("expected x to have a device") + return MKLPackedLinear( + layout=FixedLayout(device, x.get_dtype(), output_size, output_stride), + inputs=inputs, + constant_args=constant_args, + ) + + +class LinearUnary(ExternKernelAlloc): + def __init__( + self, + layout, + inputs, + constant_args=(), + ) -> None: + self.device_type = get_device_type(inputs[0]) + super().__init__( + layout, + inputs, + constant_args, + None, + op_overload=torch.ops.mkldnn._linear_pointwise.default, + cpp_kernel_name=f"aoti_torch_{self.device_type}__linear_pointwise", + ) + + def codegen(self, wrapper): + wrapper.include_extra_header( + f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h" + ) + super().codegen(wrapper) + + @classmethod + def create(cls, x, w, B, attr, scalars, algorithm): + x = cls.require_contiguous(cls.realize_input(x)) + w = cls.require_contiguous(cls.realize_input(w)) + + *m, _ic = x.get_size() + oc, _ic = w.get_size() + output_size = list(m) + [oc] + inputs = [x, w] + constant_args = [attr, scalars if scalars else [-1], algorithm] + if B is not None: + B = cls.require_contiguous(cls.realize_input(B)) + inputs.append(B) + else: + constant_args.insert(0, None) + + device = x.get_device() + if device is None: + raise AssertionError("expected x to have a device") + + packed = LinearUnary( + layout=FixedLayout( + device=device, + dtype=x.get_dtype(), + size=output_size, + ), + inputs=inputs, + constant_args=constant_args, + ) + return _create_output_node(packed) + + def apply_constraint(self): + pass + + +class LinearBinary(ExternKernelAlloc): + kernel = "torch.ops.mkldnn._linear_pointwise.binary" + + def __init__( + self, + layout, + inputs, + constant_args=(), + ) -> None: + self.device_type = get_device_type(inputs[0]) + super().__init__( + layout, + inputs, + constant_args, + None, + op_overload=torch.ops.mkldnn._linear_pointwise.binary, + cpp_kernel_name=f"aoti_torch_{self.device_type}__linear_pointwise_binary", + ) + + def codegen(self, wrapper): + wrapper.include_extra_header( + f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h" + ) + super().codegen(wrapper) + + @classmethod + def create(cls, x, y, w, B, attr): + x = cls.require_contiguous(cls.realize_input(x)) + y = cls.require_contiguous(cls.realize_input(y)) + w = cls.require_contiguous(cls.realize_input(w)) + + *m, _ic = x.get_size() + oc, _ic = w.get_size() + output_size = list(m) + [oc] + inputs = [x, y, w] + constant_args = [attr] + if B is not None: + B = cls.require_contiguous(cls.realize_input(B)) + inputs.append(B) + else: + constant_args.insert(0, B) + + device = x.get_device() + if device is None: + raise AssertionError("expected x to have a device") + packed = LinearBinary( + layout=FixedLayout( + device=device, + dtype=x.get_dtype(), + size=output_size, + ), + inputs=inputs, + constant_args=constant_args, + ) + return _create_output_node(packed) + + def apply_constraint(self): + pass + + +class QLinearPointwisePT2E(ExternKernelAlloc): + def __init__( + self, + layout, + inputs, + constant_args=(), + has_bias=True, + ) -> None: + """ + if bias is not None + - inputs = [x, w, b, weight_scale, weight_zp] + - const_args is: [x_scale, x_zp, o_scale, o_zp, + fp32_output, unary_attr, unary_scalars, unary_algorithm] + else + - inputs = [x, w, weight_scale, weight_zp] + - const_args is: [bias, x_scale, x_zp, o_scale, o_zp, + fp32_output, unary_attr, unary_scalars, unary_algorithm] + """ + self.device_type = get_device_type(inputs[0]) + self.has_bias = has_bias + super().__init__( + layout, + inputs, + constant_args, + None, + op_overload=(torch.ops.onednn.qlinear_pointwise.tensor), + cpp_kernel_name=( + f"aoti_torch_{self.device_type}__qlinear_pointwise_tensor" + ), + ) + + def codegen(self, wrapper): + wrapper.include_extra_header( + f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h" + ) + super().codegen(wrapper) + + if isinstance(self.layout, Layout): + self.codegen_size_asserts(wrapper) + + @classmethod + def create( + cls, + qx: "TensorBox", + x_scale: "TensorBox", + x_zero_point: "TensorBox", + qw: "TensorBox", # packed_weight + w_scale: "TensorBox", + w_zero_point: "TensorBox", + bias: "TensorBox", + output_scale: float, + output_zero_point: int, + output_dtype, + post_op_name, + post_op_args, + post_op_algorithm, + ): + (inputs, constant_args, kernel_layout, _, _) = _prepare_linear_fusion_create( + cls, + qx, + qw, + bias, + [x_scale, x_zero_point, w_scale, w_zero_point], + ) + + constant_args = constant_args + [ + output_scale, + output_zero_point, + output_dtype, + post_op_name, + may_convert_to_optional(post_op_args), + post_op_algorithm, + ] + + if output_dtype is None: + raise AssertionError("expected output_dtype to be not None") + if output_dtype in [torch.float32, torch.bfloat16]: + # in _prepare_linear_fusion_create, we use x.dtype (uint8) to create kernel_layout + # if we set fp32_output, the output buf should be dtype float32 instead of uint8. + kernel_layout.dtype = output_dtype + + return QLinearPointwisePT2E( + layout=kernel_layout, + inputs=inputs, + constant_args=constant_args, + has_bias=(bias is not None), + ) + + +class QLinearPointwiseBinaryPT2E(ExternKernelAlloc): + def __init__( + self, + layout, + inputs, + constant_args=(), + has_bias=True, + ) -> None: + """ + if bias is not None + - inputs = [x, w, x_scale, x_zp, weight_scale, weight_zp, x2, bias] + - const_args is: [o_scale, o_zp, + fp32_output, binary_attr, alpha, unary_attr, unary_scalars, unary_algorithm] + else + - inputs = [x, w, x_scale, x_zp, weight_scale, weight_zp, x2] + - const_args is: [bias, o_scale, o_zp, + fp32_output, binary_attr, alpha, unary_attr, unary_scalars, unary_algorithm] + """ + self.device_type = get_device_type(inputs[0]) + self.has_bias = has_bias + self.idx_for_inplace_sum = 6 + super().__init__( + layout, + inputs, + constant_args, + None, + op_overload=(torch.ops.onednn.qlinear_pointwise.binary_tensor), + cpp_kernel_name=f"aoti_torch_{self.device_type}__qlinear_pointwise_binary_tensor", + ) + + def codegen(self, wrapper): + wrapper.include_extra_header( + f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h" + ) + super().codegen(wrapper) + if isinstance(self.layout, Layout): + self.codegen_size_asserts(wrapper) + + def get_mutation_names(self) -> Sequence[str]: + binary_post_op = self.constant_args[-5] + if binary_post_op == "sum": + input = self.inputs[self.idx_for_inplace_sum] + if not isinstance(input, IRNode): + raise AssertionError(f"expected input to be IRNode, got {type(input)}") + return [input.get_name()] + else: + return [] + + @classmethod + def create( + cls, + qx: "TensorBox", + x_scale: "TensorBox", + x_zero_point: "TensorBox", + qw: "TensorBox", # packed_weight + w_scale: "TensorBox", + w_zero_point: "TensorBox", + other: "TensorBox", + bias: "TensorBox", + output_scale: float, + output_zero_point: int, + output_dtype, + other_scale, + other_zp, + binary_post_op, + binary_alpha, + unary_post_op, + unary_post_op_args, + unary_post_op_algorithm, + ): + ( + inputs, + constant_args, + kernel_layout, + req_stride_order, + other, + ) = _prepare_linear_fusion_create( + cls, + qx, + qw, + bias, + [x_scale, x_zero_point, w_scale, w_zero_point], + other, + binary_post_op == "sum", + ) + + constant_args = constant_args + [ + output_scale, + output_zero_point, + output_dtype, + other_scale, + other_zp, + binary_post_op, + binary_alpha, + unary_post_op, + may_convert_to_optional(unary_post_op_args), + unary_post_op_algorithm, + ] + + if binary_post_op == "sum": + V.graph.mark_buffer_mutated(other.get_name()) + packed = QLinearPointwiseBinaryPT2E( + layout=NoneLayout(device=other.get_device()), + inputs=inputs, + constant_args=constant_args, + has_bias=(bias is not None), + ) + # Return other since it has been inplace changed. + return packed.inputs[packed.idx_for_inplace_sum] + + if output_dtype is None: + raise AssertionError("expected output_dtype to be not None") + if output_dtype in [torch.float32, torch.bfloat16]: + # in _prepare_linear_fusion_create, we use x.dtype (uint8) to create kernel_layout + # if we set fp32_output, the output buf should be dtype float32 instead of uint8. + kernel_layout.dtype = output_dtype + + return QLinearPointwiseBinaryPT2E( + layout=kernel_layout, + inputs=inputs, + constant_args=constant_args, + has_bias=(bias is not None), + ) + + +class MkldnnRnnLayer(ExternKernelAlloc): + def __init__( + self, + layout, + inputs, + constant_args=(), + ) -> None: + super().__init__( + layout, + inputs, + constant_args, + None, + op_overload=torch.ops.aten.mkldnn_rnn_layer.default, + ) + + @classmethod + def create( + cls, + x: "TensorBox", + w0: "TensorBox", + w1: "TensorBox", + w2: "TensorBox", + w3: "TensorBox", + hx: "TensorBox", + cx: "TensorBox", + reverse: bool, + batch_sizes: list[int], + mode: int, + hidden_size: int, + num_layers: int, + has_biases: bool, + bidirectional: bool, + batch_first: bool, + train: bool, + ): + # pyrefly: ignore [bad-assignment] + x = cls.require_stride1(cls.realize_input(x)) + # If batch_first, x has been permuted in lstm before entering the mkldnn_rnn_layer. + # Make sure x is contiguous in batch_first case. + x.freeze_layout() + # pyrefly: ignore [bad-assignment] + w0 = cls.require_stride1(cls.realize_input(w0)) + # pyrefly: ignore [bad-assignment] + w1 = cls.require_stride1(cls.realize_input(w1)) + # pyrefly: ignore [bad-assignment] + w2 = cls.require_stride1(cls.realize_input(w2)) + # pyrefly: ignore [bad-assignment] + w3 = cls.require_stride1(cls.realize_input(w3)) + # pyrefly: ignore [bad-assignment] + hx = cls.require_stride1(cls.realize_input(hx)) + hx.freeze_layout() + # pyrefly: ignore [bad-assignment] + cx = cls.require_stride1(cls.realize_input(cx)) + cx.freeze_layout() + + input_size = x.get_size() + if len(input_size) != 3: + raise AssertionError("Expect lstm input to be 3D") + # batch_first is handled in the lstm OP. When entering + # rnn_layer here, we'll always have batch_first = False + seq_length, mini_batch, input_size = input_size + output_shape = [seq_length, mini_batch, hidden_size] + + hy_shape = hx.get_size() + cy_shape = cx.get_size() + + inputs = [x, w0, w1, w2, w3, hx, cx] + constant_args = [ + reverse, + batch_sizes, + mode, + hidden_size, + num_layers, + has_biases, + bidirectional, + batch_first, + train, + ] + + device = x.get_device() + if device is None: + raise AssertionError("expected x to have a device") + packed = MkldnnRnnLayer( + MultiOutputLayout(device=device), + inputs=inputs, + constant_args=constant_args, + ) + + def get_strides_of_lstm_output(output_shape, batch_first): + if len(output_shape) != 3: + raise AssertionError("Expect output_shape to be 3D") + return FlexibleLayout.contiguous_strides(output_shape) + + # C shim call requires all the outputs to be passed in, and thus the last + # dummy return value is added. + output_sizes = [output_shape, hy_shape, cy_shape, [1]] + output_strides = [ + get_strides_of_lstm_output(output_shape, batch_first), + FlexibleLayout.contiguous_strides(hy_shape), + FlexibleLayout.contiguous_strides(cy_shape), + [1], + ] + output_ir = [ + MultiOutput( + FixedLayout( + x.get_device(), # type: ignore[arg-type] + x.get_dtype(), + output_size, + output_stride, + ), + packed, + [(tuple, i)], + ) + for i, (output_size, output_stride) in enumerate( + zip(output_sizes, output_strides) + ) + ] + packed.outputs = output_ir + + return output_ir + + def codegen(self, wrapper): + wrapper.include_extra_header("torch/csrc/inductor/aoti_torch/c/shim_cpu.h") + return super().codegen(wrapper) + + +# Add this IR so that we can include shim_cpu.h for cpp_wrapper +class WeightInt4PackMatmul(ExternKernelAlloc): + def __init__( + self, + layout, + inputs, + constant_args=(), + ) -> None: + """ + inputs = [x, w, qGroupSize, qScalesAndZeros] + constant_args = () + """ + if len(inputs) != 4: + raise AssertionError(f"expected 4 inputs, got {len(inputs)}") + if len(constant_args) != 0: + raise AssertionError(f"expected 0 constant_args, got {len(constant_args)}") + super().__init__( + layout, + inputs, + constant_args, + None, + op_overload=(torch.ops.quantized.int4mm_packed_weight_cpu.default), + cpp_kernel_name=("aoti_torch_cpu__weight_int4pack_mm_cpu_tensor"), + ) + + def codegen(self, wrapper): + wrapper.include_extra_header("torch/csrc/inductor/aoti_torch/c/shim_cpu.h") + super().codegen(wrapper) + + if isinstance(self.layout, Layout): + self.codegen_size_asserts(wrapper) + + @classmethod + def create( + cls, + x: "TensorBox", + w: "TensorBox", + qGroupSize: "TensorBox", + qScalesAndZeros: "TensorBox", + ): + inputs = [x, w, qGroupSize, qScalesAndZeros] + *m, _ = x.get_size() + n, _ = w.get_size() + output_size = list(m) + [n] + output_stride = FlexibleLayout.contiguous_strides(output_size) + kernel_layout = FixedLayout( + x.get_device(), # type: ignore[arg-type] + x.get_dtype(), + output_size, + output_stride, + ) + return WeightInt4PackMatmul( + layout=kernel_layout, + inputs=inputs, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/mkldnn_lowerings.py b/.venv/lib/python3.12/site-packages/torch/_inductor/mkldnn_lowerings.py new file mode 100644 index 0000000000000000000000000000000000000000..bf0a4e435173bc1d7471ba75e764f41f415aa061 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/mkldnn_lowerings.py @@ -0,0 +1,1507 @@ +# mypy: allow-untyped-defs +import functools + +import torch +import torch.utils._pytree as pytree +from torch._inductor.kernel.mm_common import mm_args + +from . import config, ir +from .codegen.cpp_gemm_template import CppGemmTemplate +from .codegen.cpp_grouped_gemm_template import CppGroupedGemmTemplate +from .codegen.cpp_utils import create_epilogue_with_attr +from .ir import TensorBox +from .lowering import ( + add, + add_needs_realized_inputs, + aten, + permute, + register_lowering, + to_dtype, + view, +) +from .select_algorithm import ( + autotune_select_algorithm, + ChoiceCaller, + ExternKernelChoice, +) +from .utils import use_aten_gemm_kernels, use_cpp_gemm_template +from .virtualized import ops, OpsValue, V + + +def create_int8_compensation( + W_tensor: torch.Tensor, + packed_weight: ir.TensorBox, + x_scale: ir.TensorBox, + x_zp: ir.TensorBox, + w_scale: ir.TensorBox, +) -> tuple[ + bool, + ir.TensorBox, + ir.TensorBox | None, +]: + x_w_scale: ir.TensorBox | None = None + use_int8_fast_compensation_path = all( + isinstance(item, ir.TensorBox) + and item.get_name() in V.graph.constants + and hasattr(item.data, "data") + and isinstance(item.data.data, ir.ConstantBuffer) + for item in [x_scale, x_zp, w_scale] + ) + if use_int8_fast_compensation_path: + x_w_scale_tensor = ( + V.graph.constants[x_scale.get_name()] + * V.graph.constants[w_scale.get_name()] + ) + x_w_scale = V.graph.add_tensor_constant( + x_w_scale_tensor, + name=packed_weight.get_name() + "_x_w_compens", + ) + weight_compens_tensor = torch.sum(W_tensor.to(torch.float), dim=0) + x_zp_tensor = V.graph.constants[x_zp.get_name()] + weight_compens_tensor = weight_compens_tensor * x_w_scale_tensor * x_zp_tensor + weight_compens = V.graph.add_tensor_constant( + weight_compens_tensor, + name=packed_weight.get_name() + "_BMatrixCompens", + ) + else: + weight_compens_tensor = torch.sum(W_tensor.to(torch.float), dim=0) + weight_compens = V.graph.add_tensor_constant( + weight_compens_tensor, + name=packed_weight.get_name() + "_BMatrixCompens", + ) + return ( # type: ignore[return-type] + use_int8_fast_compensation_path, + weight_compens, + x_w_scale, + ) + + +def codegen_int8_gemm_template_compensation( + use_int8_fast_compensation_path: bool, + input: OpsValue, + _weight_compo: OpsValue, + _x_scale: OpsValue | None, + _x_zp: OpsValue | None, + _w_scale: OpsValue | None, + _x_w_scale: OpsValue | None, +) -> OpsValue: + if use_int8_fast_compensation_path: + temp = ops.sub( + ops.mul( + input, + _x_w_scale, + ), + _weight_compo, + ) + else: + temp = ops.mul( + ops.mul( + input, + _x_scale, + ), + _w_scale, + ) + # NOTE: We will apply compensation even if the x_zp is 0 for int8 quantization. + # That's because when torch.compile is invoked for dynamic quantization, + # x might coincidentally have such values that x_zp might be zero despite + # asymmetric quantization. + # Besides, if x_zp is dummy for int8 x, or if x is statically quantized, + # we'd still perform that redundant compute to avoid making the code messy + # because we discovered that redundant computation of compensation did not + # lead to performance degradation with the input shapes tested. + temp = ops.sub( + temp, + ops.mul( + ops.mul( + ops.mul( + _x_scale, + _w_scale, + ), + _x_zp, + ), + _weight_compo, + ), + ) + return temp + + +def grouped_gemm_lowering( + x: TensorBox, + w: list[TensorBox], + b: list[TensorBox], + attr=None, + scalars=None, + algorithm=None, + layout=None, +): + x_size = x.get_size() + if len(x_size) > 2: + # GEMM template needs 2D input, normalize input shape here + x = view(x, [-1, x_size[-1]]) + num_gemm = len(w) + + if not (config.max_autotune or config.max_autotune_gemm): + raise AssertionError( + "grouped_gemm_lowering requires max_autotune or max_autotune_gemm" + ) + # pyrefly: ignore [bad-assignment] + b = [bias if bias is None else ir.ExternKernel.realize_input(bias) for bias in b] + + choices: list[ChoiceCaller] = [] + *_, layout, x, _ = mm_args(x, permute(w[0], [1, 0]), layout=layout) + + kwargs = { + "has_bias": [bias is not None for bias in b], + "trans_w": True, + "epilogue_creator": None, + "act_mapping": dict.fromkeys(range(num_gemm), x), + } + + input_nodes = [x, *w] + input_nodes.extend([bias for bias in b if bias is not None]) + + CppGroupedGemmTemplate.add_choices( + choices, + layout, + input_nodes, + **kwargs, # type: ignore[arg-type] + ) + + if len(choices) == 0: + raise AssertionError("expected at least one choice for grouped_gemm") + result, _ = autotune_select_algorithm( + "grouped_gemm", + choices, + input_nodes, + layout, + ) + template_buf = result.data.data + return_bufs = [ + ir.MultiOutput(layout, template_buf, [(list, gemm_idx)]) + for gemm_idx in range(num_gemm) + ] + # pyrefly: ignore [bad-argument-type] + template_buf.layout = ir.MultiOutputLayout(device=input_nodes[0].get_device()) + template_buf.outputs = return_bufs + return_tensors = [ + ir.TensorBox.create(return_bufs[gemm_idx]) for gemm_idx in range(num_gemm) + ] + if len(x_size) > 2: + for gemm_idx in range(num_gemm): + return_tensors[gemm_idx] = view( + return_tensors[gemm_idx], # type: ignore[arg-type] + (*x_size[:-1], return_tensors[gemm_idx].get_size()[-1]), + ) + return return_tensors + + +grouped_gemm_lowering._inductor_lowering_function = True # type: ignore[attr-defined] +grouped_gemm_lowering._inductor_lowering_output_metadata_ignores_input_storage = True # type: ignore[attr-defined] + + +def _convert_to_0d_constant( + tensor_box: ir.TensorBox, + dtype: torch.dtype, + name_suffix: str = "_0d", +) -> ir.TensorBox: + """ + Normalize a tensor with all dimensions equal to 1 to a 0D ConstantBuffer. + """ + if isinstance(tensor_box, ir.TensorBox): + data = tensor_box.data + if isinstance(data, ir.StorageBox): + data = data.data + else: + data = tensor_box + + if isinstance(data, ir.ConstantBuffer): + tensor = V.graph.constants.get(tensor_box.get_name()) + if tensor is not None: + return V.graph.add_tensor_constant( + tensor.reshape([]), name=tensor_box.get_name() + name_suffix + ) + + from torch._inductor.lowering import get_constant_value + + const_value = get_constant_value(data) + if const_value is not None: + return V.graph.add_tensor_constant( + torch.tensor(const_value.value, dtype=dtype).reshape([]) + ) + + tensor_box.realize() + + from .ir import ExternKernel, GenericView + + if isinstance(tensor_box.data, GenericView): + tensor_box = ir.TensorBox(ExternKernel.require_contiguous(tensor_box.data)) + + result = view(tensor_box, []) + return result + + +def register_onednn_fusion_ops(): + if torch._C._has_mkldnn: + from . import mkldnn_ir + + aten_mkldnn_linear_unary = ExternKernelChoice( + torch.ops.mkldnn._linear_pointwise, + "mkldnn::_linear_pointwise", + has_out_variant=False, + kernel_creator=mkldnn_ir.LinearUnary.create, + ) + aten_mkldnn_linear_binary = ExternKernelChoice( + torch.ops.mkldnn._linear_pointwise.binary, + "mkldnn::_linear_pointwise", + has_out_variant=False, + kernel_creator=mkldnn_ir.LinearBinary.create, + ) + aten_mkldnn_qlinear_unary = ExternKernelChoice( + torch.ops.onednn.qlinear_pointwise, + "onednn::qlinear_pointwise", + has_out_variant=False, + kernel_creator=mkldnn_ir.QLinearPointwisePT2E.create, + ) + aten_mkldnn_qlinear_binary = ExternKernelChoice( + torch.ops.onednn.qlinear_pointwise.binary, + "onednn::qlinear_pointwise", + has_out_variant=False, + kernel_creator=mkldnn_ir.QLinearPointwiseBinaryPT2E.create, + ) + cpu_needs_realized_inputs: list[ + torch._ops.OpOverload | torch._ops.OpOverloadPacket + ] = [ + torch.ops.mkldnn._convolution_pointwise, + torch.ops.mkldnn._convolution_pointwise_, + torch.ops.mkldnn._convolution_transpose_pointwise, + torch.ops.mkldnn._linear_pointwise, + aten.mkldnn_rnn_layer.default, + torch.ops.onednn.qconv_pointwise, + ] + + @register_lowering(torch.ops.mkldnn._convolution_pointwise) + def convolution_unary( + x: TensorBox, + weight: TensorBox, + bias: TensorBox, + padding, + stride, + dilation, + groups, + attr, + scalars, + algorithm, + ): + return TensorBox.create( + mkldnn_ir.ConvolutionUnary.create( + x, + weight, + bias, + padding, + stride, + dilation, + groups, + attr, + scalars, + algorithm, + ) + ) + + @register_lowering(torch.ops.mkldnn._convolution_pointwise.binary) + def convolution_binary( + x: TensorBox, + other: TensorBox, + weight: TensorBox, + bias: TensorBox, + padding, + stride, + dilation, + groups, + binary_attr, + binary_alpha, + unary_attr, + unary_scalars, + unary_algorithm, + ): + return TensorBox.create( + mkldnn_ir.ConvolutionBinary.create( + x, + other, + weight, + bias, + padding, + stride, + dilation, + groups, + binary_attr, + binary_alpha, + unary_attr, + unary_scalars, + unary_algorithm, + ) + ) + + @register_lowering(torch.ops.mkldnn._convolution_pointwise_.binary) + def convolution_binary_inplace( + x: TensorBox, + other: TensorBox, + weight: TensorBox, + bias: TensorBox, + padding, + stride, + dilation, + groups, + binary_attr, + binary_alpha, + unary_attr, + unary_scalars, + unary_algorithm, + ): + return TensorBox.create( + mkldnn_ir.ConvolutionBinaryInplace.create( + x, + other, + weight, + bias, + padding, + stride, + dilation, + groups, + binary_attr, + binary_alpha, + unary_attr, + unary_scalars, + unary_algorithm, + ) + ) + + @register_lowering(torch.ops.mkldnn._linear_pointwise) + def linear_unary( + x: TensorBox, + w: TensorBox, + b: TensorBox, + attr, + scalars, + algorithm, + layout=None, + ): + x_size = x.get_size() + if len(x_size) > 2: + # GEMM template needs 2D input, normalize input shape here + x = view(x, [-1, x_size[-1]]) + if b is not None: + b = ir.ExternKernel.realize_input(b) # type: ignore[assignment] + choices: list[ChoiceCaller] = [] + if config.max_autotune or config.max_autotune_gemm: + transposed_w = permute(w, [1, 0]) + *_, layout, x, transposed_w = mm_args(x, transposed_w, layout=layout) + if use_cpp_gemm_template(layout, x, transposed_w): + + def epilogue_creator(buf): + return create_epilogue_with_attr( + buf, attr, scalars=scalars, algorithm=algorithm + ) + + kwargs = { + "has_bias": b is not None, + "trans_w": True, + "epilogue_creator": ( + None if attr == "none" else epilogue_creator + ), + } + if b is not None: + kwargs["input_indices"] = [2, 0, 1] # type: ignore[assignment] + CppGemmTemplate.add_choices( + choices, + layout, + [x, w] if b is None else [x, w, b], + **kwargs, # type: ignore[arg-type] + ) + if len(choices) == 0 or use_aten_gemm_kernels(): + kwargs = dict(attr=attr, scalars=scalars, algorithm=algorithm) + if b is None: + kwargs["B"] = None + choices.append( + aten_mkldnn_linear_unary.bind( + [x, w] if b is None else [x, w, b], + layout, + **kwargs, + ) + ) + if w.get_name() not in V.graph.constants: + raise AssertionError("weight must be a graph constant") + input_gen_fns = { + 1: lambda x: V.graph.constants[x.get_name()], + } + result, _ = autotune_select_algorithm( + "linear_unary", + choices, + [x, w] if b is None else [x, w, b], + layout, + input_gen_fns=input_gen_fns, + ) + if len(x_size) > 2: + result = view(result, (*x_size[:-1], result.get_size()[-1])) + return result + + @register_lowering(torch.ops.mkldnn._linear_pointwise.binary) + def linear_binary( + x: TensorBox, y: TensorBox, w: TensorBox, b: TensorBox, attr, layout=None + ): + x_size = x.get_size() + if len(x_size) > 2: + # GEMM template needs 2D input, normalize input shape here + x = view(x, [-1, x_size[-1]]) + y_size = y.get_size() + if len(y_size) > 2: + y = view(y, [-1, y_size[-1]]) + if b is not None: + b = ir.ExternKernel.realize_input(b) # type: ignore[assignment] + choices: list[ChoiceCaller] = [] + if config.max_autotune or config.max_autotune_gemm: + transposed_w = permute(w, [1, 0]) + *_, layout, x, transposed_w, y = mm_args( + x, transposed_w, y, layout=layout + ) + if use_cpp_gemm_template(layout, x, transposed_w): + + def epilogue_creator(buf): + return create_epilogue_with_attr(buf, attr, other=y) + + kwargs = { + "has_bias": b is not None, + "trans_w": True, + "epilogue_creator": epilogue_creator, + } + + # pyrefly: ignore [bad-typed-dict-key, unsupported-operation] + kwargs["input_indices"] = [0, 2, 1] if b is None else [3, 0, 2, 1] + CppGemmTemplate.add_choices( + choices, + layout, + [x, y, w] if b is None else [x, y, w, b], + **kwargs, # type: ignore[arg-type] + ) + if len(choices) == 0 or use_aten_gemm_kernels(): + kwargs = dict(attr=attr) + if b is None: + kwargs["B"] = None + choices.append( + aten_mkldnn_linear_binary.bind( + [x, y, w] if b is None else [x, y, w, b], + layout, + **kwargs, + ) + ) + if w.get_name() not in V.graph.constants: + raise AssertionError("weight must be a graph constant") + input_gen_fns = { + 2: lambda x: V.graph.constants[x.get_name()], + } + result, _ = autotune_select_algorithm( + "linear_binary", + choices, + [x, y, w] if b is None else [x, y, w, b], + layout, + input_gen_fns=input_gen_fns, + ) + if len(x_size) > 2: + result = view(result, (*x_size[:-1], result.get_size()[-1])) + return result + + @register_lowering(torch.ops.mkldnn._convolution_transpose_pointwise) + def convolution_transpose_unary( + x: TensorBox, + weight: TensorBox, + bias: TensorBox, + padding, + output_padding, + stride, + dilation, + groups, + attr, + scalars, + algorithm, + ): + return TensorBox.create( + mkldnn_ir.ConvolutionTransposeUnary.create( + x, + weight, + bias, + padding, + output_padding, + stride, + dilation, + groups, + attr, + scalars, + algorithm, + ) + ) + + @register_lowering(aten.mkldnn_rnn_layer.default) + def mkldnn_rnn_layer( + x: TensorBox, + w0: TensorBox, + w1: TensorBox, + w2: TensorBox, + w3: TensorBox, + hx: TensorBox, + cx: TensorBox, + reverse: bool, + batch_sizes: list[int], + mode: int, + hidden_size: int, + num_layers: int, + has_biases: bool, + bidirectional: bool, + batch_first: bool, + train: bool, + ): + return pytree.tree_map( + TensorBox.create, + mkldnn_ir.MkldnnRnnLayer.create( + x, + w0, + w1, + w2, + w3, + hx, + cx, + reverse, + batch_sizes, + mode, + hidden_size, + num_layers, + has_biases, + bidirectional, + batch_first, + train, + ), + ) + + @register_lowering(torch.ops.onednn.qconv_pointwise, type_promotion_kind=None) + def qconvolution_unary( + x: TensorBox, + x_scale, + x_zp, + packed_weight: TensorBox, + w_scale: TensorBox, + w_zp, + bias: TensorBox, + stride, + padding, + dilation, + groups, + o_inv_scale, + o_zero_point, + output_dtype, + attr, + scalars, + algorithm, + ): + if not isinstance(x_scale, ir.TensorBox): + if type(x_scale) is not float: + raise AssertionError( + f"expected x_scale to be float, got {type(x_scale)}" + ) + x_scale = V.graph.add_tensor_constant( + torch.tensor(x_scale, dtype=torch.float32), name="x_scale" + ) + + if x_zp is None: + x_zp = V.graph.add_tensor_constant( + torch.tensor(0, dtype=torch.int32), name="x_zp" + ) + if not isinstance(x_zp, ir.TensorBox): + if type(x_zp) is not int: + raise AssertionError(f"expected x_zp to be int, got {type(x_zp)}") + x_zp = V.graph.add_tensor_constant( + torch.tensor(x_zp, dtype=torch.int32), name="x_zp" + ) + + if w_zp is None: + w_zp = V.graph.add_tensor_constant( + torch.tensor(0, dtype=torch.int32), name="w_zp" + ) + + return TensorBox.create( + mkldnn_ir.QConvPointWisePT2E.create( + x, + x_scale, + x_zp, + packed_weight, + w_scale, + w_zp, + bias, + stride, + padding, + dilation, + groups, + o_inv_scale, + o_zero_point, + output_dtype, + attr, + scalars, + algorithm, + ) + ) + + @register_lowering( + torch.ops.onednn.qconv2d_pointwise.binary, type_promotion_kind=None + ) + @register_lowering( + torch.ops.onednn.qconv2d_pointwise.binary_tensor, type_promotion_kind=None + ) + def qconvolution_binary( + x: TensorBox, + x_scale, + x_zp, + packed_weight: TensorBox, + w_scale: TensorBox, + w_zp, + accum: TensorBox, + bias: TensorBox, + stride, + padding, + dilation, + groups, + o_inv_scale, + o_zero_point, + output_dtype, + accum_scale, + accum_zp, + binary_attr, + alpha, + unary_attr, + unary_scalars, + unary_algorithm, + ): + if not isinstance(x_scale, ir.TensorBox): + if type(x_scale) is not float: + raise AssertionError( + f"expected x_scale to be float, got {type(x_scale)}" + ) + x_scale = V.graph.add_tensor_constant( + torch.tensor(x_scale, dtype=torch.float32), name="x_scale" + ) + + if x_zp is None: + x_zp = V.graph.add_tensor_constant( + torch.tensor(0, dtype=torch.int32), name="x_zp" + ) + if not isinstance(x_zp, ir.TensorBox): + if type(x_zp) is not int: + raise AssertionError(f"expected x_zp to be int, got {type(x_zp)}") + x_zp = V.graph.add_tensor_constant( + torch.tensor(x_zp, dtype=torch.int32), name="x_zp" + ) + + if w_zp is None: + w_zp = V.graph.add_tensor_constant( + torch.tensor(0, dtype=torch.int32), name="w_zp" + ) + + if ( + binary_attr == "sum" + and output_dtype in [torch.float32, torch.bfloat16] + and accum.get_dtype() in [torch.float32, torch.bfloat16] + and accum.get_dtype() != output_dtype + ): + # For int8-mixed-bf16 quantization and inplace add, + # there is case when accum dtype is float32 but output dtype is bfloat16. + # Since the accum will be changed in-place with post op sum, + # we will do accum dtype conversion here. + accum = to_dtype(accum, output_dtype) + return TensorBox.create( + mkldnn_ir.QConvPointWiseBinaryPT2E.create( + x, + x_scale, # type: ignore[arg-type] + x_zp, # type: ignore[arg-type] + packed_weight, + w_scale, + w_zp, + accum, + bias, + stride, + padding, + dilation, + groups, + o_inv_scale, + o_zero_point, + output_dtype, + accum_scale, + accum_zp, + binary_attr, + alpha, + unary_attr, + unary_scalars, + unary_algorithm, + ) + ) + + @register_lowering(torch.ops.onednn.qlinear_pointwise, type_promotion_kind=None) + def qlinear_unary( + x: TensorBox, + x_scale, + x_zp, + packed_weight: TensorBox, + w_scale: TensorBox, + w_zp: TensorBox, + bias: TensorBox, + o_scale, + o_zero_point, + output_dtype, + attr, + scalars, + algorithm, + layout=None, + ): + if packed_weight.get_dtype() not in [torch.int8, torch.float8_e4m3fn]: + raise AssertionError( + "Only int8 and e4m3fn weights are supported by oneDNN qlinear." + ) + x_size = x.get_size() + if len(x_size) > 2: + # GEMM template needs 2D input, normalize input shape here + x = view(x, [-1, x_size[-1]]) + if not isinstance(x_scale, ir.TensorBox): + if type(x_scale) is not float: + raise AssertionError( + f"expected x_scale to be float, got {type(x_scale)}" + ) + x_scale = V.graph.add_tensor_constant( + torch.tensor(x_scale, dtype=torch.float32), name="x_scale" + ) + else: + x_scale_size = x_scale.get_size() + if len(x_scale_size) == 0 or all(dim == 1 for dim in x_scale_size): + x_scale = _convert_to_0d_constant(x_scale, torch.float32, "_0d") + else: + x_scale.realize() + if len(x_scale.get_size()) not in [0, 1]: + raise AssertionError("x_scale must be 0D or 1D") + + if x_zp is None: + x_zp = V.graph.add_tensor_constant( + torch.tensor(0, dtype=torch.int32), name="x_zp" + ) + elif not isinstance(x_zp, ir.TensorBox): + if type(x_zp) is not int: + raise AssertionError(f"expected x_zp to be int, got {type(x_zp)}") + x_zp = V.graph.add_tensor_constant( + torch.tensor(x_zp, dtype=torch.int32), name="x_zp" + ) + else: + x_zp_size = x_zp.get_size() + if len(x_zp_size) == 0 or all(dim == 1 for dim in x_zp_size): + # If all outer dims of x_zp are 1, make it a ConstantBuffer with 0D shape + # Don't call realize() before _convert_to_0d_constant to preserve ComputedBuffer + x_zp = _convert_to_0d_constant(x_zp, torch.int32, "_0d") + else: + x_zp.realize() + + if x_zp.get_numel() != 1: + raise AssertionError("x_zp is incompatible with oneDNN qlinear") + + # When channels less than 8, w_scale/w_zp is Pointwise instead of ConstantBuffer + # Refer to + # https://github.com/pytorch/pytorch/blob/f353d17755ed23b02924c962a86ff99a3405fe10/torch/_inductor/graph.py#L570-L577 + if w_zp is None: + # If w_zp is None, then it's a dummy tensor created to denote the + # absence of a zero point, and thus w is int8 symmetrically quantized. + # Moreover, oneDNN qlinear API doesn't accept None value for zp + + w_zp = V.graph.add_tensor_constant( + torch.tensor(0, dtype=torch.int32), name="w_zp" + ) + w_scale.realize() + w_zp.realize() + if w_zp.get_dtype() != torch.int32 and isinstance( + ir.InputsKernel.unwrap_storage_for_input(w_zp), + ir.ConstantBuffer, + ): + # W_zp might be a ConstantBuffer with int64, convert it to int32 + w_zp_tensor = V.graph.constants[w_zp.get_name()].to(torch.int32) + w_zp = V.graph.add_tensor_constant( # type: ignore[assignment] + torch.tensor(w_zp_tensor, dtype=torch.int32), name=w_zp.get_name() + ) + + bias_dtype = None if bias is None else bias.get_dtype() + choices: list[ChoiceCaller] = [] + + if config.max_autotune or config.max_autotune_gemm: + *_, layout, x, packed_weight = mm_args( + x, packed_weight, layout=layout, out_dtype=output_dtype + ) + + if ( + # GEMM template currently only supports symmetrically quantized weights + isinstance( + ir.InputsKernel.unwrap_storage_for_input(w_zp), + ir.ConstantBuffer, + ) + and torch.equal( + torch.zeros_like(V.graph.constants[w_zp.get_name()]), + V.graph.constants[w_zp.get_name()], + ) + ) and use_cpp_gemm_template(layout, x, packed_weight): + W_tensor = V.graph.constants[packed_weight.get_name()].to_dense() + + ( + use_int8_fast_compensation_path, + weight_compens, + x_w_scale, + ) = create_int8_compensation( + W_tensor, + packed_weight, + x_scale, + x_zp, + w_scale, + ) + + def epilogue_creator(input_buffer): + # Epilogue to convert from s32 to f32 for u8s8f32 + if output_dtype not in [ + torch.float32, + torch.bfloat16, + torch.uint8, + torch.int8, + ]: + raise AssertionError( + f"unexpected output_dtype {output_dtype}" + ) + input_loader = input_buffer.make_loader() + weight_compens_loader = weight_compens.make_loader() + x_w_scale_loader = None + if use_int8_fast_compensation_path: + if x_w_scale is None: + raise AssertionError( + "x_w_scale must be set on the fast compensation path" + ) + x_w_scale_loader = x_w_scale.make_loader() + x_scale_loader = x_scale.make_loader() + w_scale_loader = w_scale.make_loader() + x_zp_loader = x_zp.make_loader() + nonlocal bias + bias_loader = None + if bias is not None: + bias_loader = bias.make_loader() + + def inner_fn(index): + nonlocal bias + input = input_loader(index) + # MicroKernel Output is with int32 + # cvt to FP32 before doing compensation + input = ops.to_dtype(input, torch.float32) + weight_compens_index = (index[-1],) + + _x_scale = None + _x_zp = None + _w_scale = None + if not use_int8_fast_compensation_path: + _x_scale = x_scale_loader(()) + _x_zp = x_zp_loader(()) + _w_scale = w_scale_loader(weight_compens_index) + _weight_compo = weight_compens_loader(weight_compens_index) + _x_w_scale = None + if use_int8_fast_compensation_path: + if x_w_scale_loader is None: + raise AssertionError( + "x_w_scale_loader must be set on the fast compensation path" + ) + _x_w_scale = x_w_scale_loader(weight_compens_index) + # Step 1: Compute s8s8->s32 or u8s8->s32 GEMM & then apply compensation + temp = codegen_int8_gemm_template_compensation( + use_int8_fast_compensation_path, + input, + _weight_compo, + _x_scale, + _x_zp, + _w_scale, + _x_w_scale, + ) + # Step 2: add Bias if applicable + if bias is not None: + # pyrefly: ignore [not-callable] + _bias = bias_loader(weight_compens_index) + nonlocal bias_dtype + if bias_dtype not in [torch.float32, torch.bfloat16]: + raise AssertionError( + f"unexpected bias_dtype {bias_dtype}" + ) + if bias_dtype == torch.bfloat16: + _bias = ops.to_dtype(_bias, torch.float32) + temp = ops.add(temp, _bias) + + return temp + + output_buf = ir.Pointwise( + device=input_buffer.get_device(), + dtype=torch.float32, # Hardcode to FP32 for u8s8f32 & s8s8f32 + inner_fn=inner_fn, + ranges=input_buffer.get_size(), + ) + + # Step 3: Doing the unary post op fusion + if attr != "none": + output_buf = create_epilogue_with_attr( + output_buf, attr, scalars=scalars, algorithm=algorithm + ) + + # Step 4: Cast output to Target Dtype + if output_dtype == torch.bfloat16: + output_cast_loader = output_buf.make_loader() + + def inner_fn_cast_output_to_bf16(index): + input = output_cast_loader(index) + return ops.to_dtype(input, output_dtype) + + output_buf = ir.Pointwise( + device=output_buf.get_device_or_error(), + dtype=output_dtype, + inner_fn=inner_fn_cast_output_to_bf16, + ranges=output_buf.get_size(), + ) + elif output_dtype in [torch.uint8, torch.int8]: + from .lowering import _create_constants + + requant_input_loader = output_buf.make_loader() + + def inner_fn_requant(index, scale, zero_point): + input = requant_input_loader(index) + inv_scale, zero_point = _create_constants( + 1.0 / scale, zero_point, dtype=torch.float32 + ) + val = ops.round(input * inv_scale) + zero_point + if output_dtype == torch.uint8: + qmin, qmax = _create_constants( + 0, 255, dtype=torch.float32 + ) + else: + qmin, qmax = _create_constants( + -128, 127, dtype=torch.float32 + ) + clamped = ops.minimum(ops.maximum(val, qmin), qmax) + return ops.to_dtype(clamped, output_dtype) + + output_buf = ir.Pointwise( + device=output_buf.get_device_or_error(), + dtype=output_dtype, + inner_fn=functools.partial( + inner_fn_requant, + scale=float(o_scale), + zero_point=int(o_zero_point), + ), + ranges=output_buf.get_size(), + ) + + return output_buf + + if x.get_dtype() not in [torch.uint8, torch.int8]: + raise AssertionError(f"unexpected x dtype {x.get_dtype()}") + CppGemmTemplate.add_choices( + choices, + layout, + [x, x_scale, x_zp, packed_weight, w_scale, w_zp] + if bias is None + else [x, x_scale, x_zp, packed_weight, w_scale, w_zp, bias], + has_bias=bias is not None, + epilogue_creator=epilogue_creator, + input_indices=[0, 3, 1, 2, 4, 5] + if bias is None + else [6, 0, 3, 1, 2, 4, 5], + ) + if len(choices) == 0 or use_aten_gemm_kernels(): + kwargs = dict( + output_scale=o_scale, + output_zero_point=o_zero_point, + output_dtype=output_dtype, + post_op_name=attr, + post_op_args=scalars, + post_op_algorithm=algorithm, + ) + if bias is None: + kwargs["bias"] = None + choices.append( + aten_mkldnn_qlinear_unary.bind( + (x, x_scale, x_zp, packed_weight, w_scale, w_zp) + if bias is None + else (x, x_scale, x_zp, packed_weight, w_scale, w_zp, bias), + layout, + **kwargs, + ) + ) + if packed_weight.get_name() not in V.graph.constants: + raise AssertionError("packed_weight must be a graph constant") + input_gen_fns = { + 3: lambda x: V.graph.constants[x.get_name()], # packed weight + 4: lambda x: V.graph.constants[x.get_name()], # weight scale + 5: lambda x: V.graph.constants[x.get_name()], # weight zp + 6: lambda x: V.graph.constants[x.get_name()], # bias + } + if isinstance( + ir.InputsKernel.unwrap_storage_for_input(x_scale), + ir.ConstantBuffer, + ): + # x is statically quantized + input_gen_fns[1] = lambda x: V.graph.constants[x.get_name()] + if isinstance( + ir.InputsKernel.unwrap_storage_for_input(x_zp), + ir.ConstantBuffer, + ): + input_gen_fns[2] = lambda x: V.graph.constants[x.get_name()] + + result, _ = autotune_select_algorithm( + "qlinear_unary", + choices, + [x, x_scale, x_zp, packed_weight, w_scale, w_zp] + if bias is None + else [x, x_scale, x_zp, packed_weight, w_scale, w_zp, bias], + layout, + input_gen_fns=input_gen_fns, + ) + if len(x_size) > 2: + result = view(result, (*x_size[:-1], result.get_size()[-1])) + return result + + @register_lowering( + torch.ops.onednn.qlinear_pointwise.binary, type_promotion_kind=None + ) + @register_lowering( + torch.ops.onednn.qlinear_pointwise.binary_tensor, type_promotion_kind=None + ) + def qlinear_binary( + x: TensorBox, + x_scale, + x_zp, + packed_weight: TensorBox, + w_scale: TensorBox, + w_zp: TensorBox, + x2: TensorBox, + bias: TensorBox, + o_scale, + o_zero_point, + output_dtype, + x2_scale, + x2_zp, + binary_attr, + alpha, + unary_attr, + unary_scalars, + unary_algorithm, + layout=None, + ): + x_size = x.get_size() + x2_size = x2.get_size() + if len(x_size) != len(x2_size): + raise AssertionError( + f"expected x and x2 to have equal rank, got {len(x_size)} and {len(x2_size)}" + ) + if len(x_size) > 2 and binary_attr in ["add", "sum"]: + # GEMM template needs 2D input, normalize input shape here + x = view(x, [-1, x_size[-1]]) + x2 = view(x2, [-1, x2_size[-1]]) + if not isinstance(x_scale, ir.TensorBox): + if type(x_scale) is not float: + raise AssertionError( + f"expected x_scale to be float, got {type(x_scale)}" + ) + x_scale = V.graph.add_tensor_constant( + torch.tensor(x_scale, dtype=torch.float32), name="x_scale" + ) + else: + x_scale_size = x_scale.get_size() + if len(x_scale_size) == 0 or all(dim == 1 for dim in x_scale_size): + x_scale = _convert_to_0d_constant(x_scale, torch.float32, "_0d") + else: + x_scale.realize() + if len(x_scale.get_size()) not in [0, 1]: + raise AssertionError("x_scale must be 0D or 1D") + + if x_zp is None: + x_zp = V.graph.add_tensor_constant( + torch.tensor(0, dtype=torch.int32), name="x_zp" + ) + elif not isinstance(x_zp, ir.TensorBox): + if type(x_zp) is not int: + raise AssertionError(f"expected x_zp to be int, got {type(x_zp)}") + x_zp = V.graph.add_tensor_constant( + torch.tensor(x_zp, dtype=torch.int32), name="x_zp" + ) + else: + x_zp_size = x_zp.get_size() + if len(x_zp_size) == 0 or all(dim == 1 for dim in x_zp_size): + x_zp = _convert_to_0d_constant(x_zp, torch.int32, "_0d") + else: + x_zp.realize() + + if w_zp is None: + w_zp = V.graph.add_tensor_constant( + torch.tensor(0, dtype=torch.int32), name="w_zp" + ) + + # When channels less than 8, w_scale/w_zp is Pointwise instead of ConstantBuffer + # Refer to + # https://github.com/pytorch/pytorch/blob/f353d17755ed23b02924c962a86ff99a3405fe10/torch/_inductor/graph.py#L570-L577 + w_scale.realize() + w_zp.realize() + if w_zp.get_dtype() != torch.int32 and isinstance( + ir.InputsKernel.unwrap_storage_for_input(w_zp), + ir.ConstantBuffer, + ): + w_zp_tensor = V.graph.constants[w_zp.get_name()].to(torch.int32) + w_zp = V.graph.add_tensor_constant( # type: ignore[assignment] + torch.tensor(w_zp_tensor, dtype=torch.int32), name=w_zp.get_name() + ) + if binary_attr == "sum": + if output_dtype in [ + torch.float32, + torch.bfloat16, + ] and x2.get_dtype() in [torch.float32, torch.bfloat16]: + if x2.get_dtype() != output_dtype: + # For int8-mixed-bf16 quantization and inplace add, + # there is case when accum dtype is float32 but output dtype is bfloat16. + # Since the accum will be changed in-place with post op sum, + # we will do accum dtype conversion here. + x2 = to_dtype(x2, output_dtype) + else: + if x2.get_dtype() != output_dtype: + raise AssertionError( + "dtype of accum for qlinear post op sum should be the same as output" + ) + x2_dtype = x2.get_dtype() + bias_dtype = bias.get_dtype() if bias is not None else None + choices: list[ChoiceCaller] = [] + if (config.max_autotune or config.max_autotune_gemm) and binary_attr in [ + "add", + "sum", + ]: + *_, layout, x, packed_weight, x2 = mm_args( + x, packed_weight, x2, layout=layout, out_dtype=output_dtype + ) + if ( + isinstance( + ir.InputsKernel.unwrap_storage_for_input(x_zp), + ir.ConstantBuffer, + ) + and len(x_zp.get_layout().size) == 0 # Per tensor quant of act + and isinstance( + ir.InputsKernel.unwrap_storage_for_input(w_zp), + ir.ConstantBuffer, + ) + and torch.equal( + torch.zeros_like(V.graph.constants[w_zp.get_name()]), + V.graph.constants[w_zp.get_name()], + ) # We only compensate MatrixB and assume B_zp is 0 to avoid the compensation of MatrixA + and use_cpp_gemm_template(layout, x, packed_weight) + ): + W_tensor = V.graph.constants[packed_weight.get_name()] + W_tensor = W_tensor.to_dense() + ( + use_int8_fast_compensation_path, + weight_compens, + x_w_scale, + ) = create_int8_compensation( + W_tensor, + packed_weight, + x_scale, + x_zp, + w_scale, + ) + + def epilogue_creator(input_buffer): + # Epilogue to convert from s32 to f32 for u8s8f32 + if output_dtype not in [ + torch.float32, + torch.bfloat16, + torch.uint8, + torch.int8, + ]: + raise AssertionError( + f"unexpected output_dtype {output_dtype}" + ) + + input_loader = input_buffer.make_loader() + x2_loader = x2.make_loader() + weight_compens_loader = weight_compens.make_loader() + x_w_scale_loader = None + if use_int8_fast_compensation_path: + if x_w_scale is None: + raise AssertionError( + "x_w_scale must be set on the fast compensation path" + ) + x_w_scale_loader = x_w_scale.make_loader() + x_scale_loader = x_scale.make_loader() + w_scale_loader = w_scale.make_loader() + x_zp_loader = x_zp.make_loader() + nonlocal bias + bias_loader = None + if bias is not None: + bias_loader = bias.make_loader() + + def inner_fn(index): + nonlocal bias + input = input_loader(index) + _x2 = x2_loader(index) + _x_scale = None + _x_zp = None + _w_scale = None + weight_compens_index = (index[-1],) + if not use_int8_fast_compensation_path: + _x_scale = x_scale_loader(()) + _x_zp = x_zp_loader(()) + _w_scale = w_scale_loader(weight_compens_index) + # MicroKernel Output is with int32: cvt to FP32 before doing compensation + input = ops.to_dtype(input, torch.float32) + _weight_compo = weight_compens_loader(weight_compens_index) + _x_w_scale = None + if use_int8_fast_compensation_path: + if x_w_scale_loader is None: + raise AssertionError( + "x_w_scale_loader must be set on the fast compensation path" + ) + _x_w_scale = x_w_scale_loader(weight_compens_index) + # Step 1: Doing compensation to cvt fp32 + temp = codegen_int8_gemm_template_compensation( + use_int8_fast_compensation_path, + input, + _weight_compo, + _x_scale, + _x_zp, + _w_scale, + _x_w_scale, + ) + # Step 2: add Bias if applicable + if bias is not None: + # pyrefly: ignore [not-callable] + _bias = bias_loader(weight_compens_index) + nonlocal bias_dtype + if bias_dtype not in [torch.float32, torch.bfloat16]: + raise AssertionError( + f"unexpected bias_dtype {bias_dtype}" + ) + if bias_dtype == torch.bfloat16: + _bias = ops.to_dtype(_bias, torch.float32) + temp = ops.add(temp, _bias) + + # Step 3: Binary add + nonlocal x2_dtype + if x2_dtype not in [torch.float32, torch.bfloat16]: + raise AssertionError(f"unexpected x2_dtype {x2_dtype}") + if x2_dtype == torch.bfloat16: + _x2 = ops.to_dtype(_x2, torch.float32) + temp = ops.add(temp, _x2) + + return temp + + output_buf = ir.Pointwise( + device=input_buffer.get_device(), + dtype=torch.float32, # Hardcode to FP32 for u8s8f32 + inner_fn=inner_fn, + ranges=input_buffer.get_size(), + ) + + # Step 4: Unary post op if has + if unary_attr != "none": + output_buf = create_epilogue_with_attr( + output_buf, + unary_attr, + scalars=unary_scalars, + algorithm=unary_algorithm, + ) + + # Step 5: Cast output to Target Dtype + if output_dtype == torch.bfloat16: + output_cast_loader = output_buf.make_loader() + + def inner_fn_cast_output_to_bf16(index): + input = output_cast_loader(index) + return ops.to_dtype(input, output_dtype) + + output_buf = ir.Pointwise( + device=output_buf.get_device_or_error(), + dtype=output_dtype, + inner_fn=inner_fn_cast_output_to_bf16, + ranges=output_buf.get_size(), + ) + elif output_dtype in [torch.uint8, torch.int8]: + from .lowering import _create_constants + + requant_input_loader = output_buf.make_loader() + + def inner_fn_requant(index, scale, zero_point): + input = requant_input_loader(index) + inv_scale, zero_point = _create_constants( + 1.0 / scale, zero_point, dtype=torch.float32 + ) + val = ops.round(input * inv_scale) + zero_point + if output_dtype == torch.uint8: + qmin, qmax = _create_constants( + 0, 255, dtype=torch.float32 + ) + else: + qmin, qmax = _create_constants( + -128, 127, dtype=torch.float32 + ) + clamped = ops.minimum(ops.maximum(val, qmin), qmax) + return ops.to_dtype(clamped, torch.uint8) + + output_buf = ir.Pointwise( + device=output_buf.get_device_or_error(), + dtype=torch.uint8, + inner_fn=functools.partial( + inner_fn_requant, + scale=float(o_scale), + zero_point=int(o_zero_point), + ), + ranges=output_buf.get_size(), + ) + + return output_buf + + CppGemmTemplate.add_choices( + choices, + layout, + [x, x_scale, x_zp, packed_weight, w_scale, w_zp, x2] + if bias is None + else [x, x_scale, x_zp, packed_weight, w_scale, w_zp, x2, bias], + has_bias=bias is not None, + epilogue_creator=epilogue_creator, + # Reorder bias and x2 + input_indices=[0, 3, 1, 2, 4, 5, 6] + if bias is None + else [7, 0, 3, 1, 2, 4, 5, 6], + ) + + if len(choices) == 0 or use_aten_gemm_kernels(): + kwargs = dict( + output_scale=o_scale, + output_zero_point=o_zero_point, + output_dtype=output_dtype, + other_scale=x2_scale, + other_zp=x2_zp, + binary_post_op=binary_attr, + binary_alpha=alpha, + unary_post_op=unary_attr, + unary_post_op_args=unary_scalars, + unary_post_op_algorithm=unary_algorithm, + ) + if bias is None: + kwargs["bias"] = None + choices.append( + aten_mkldnn_qlinear_binary.bind( + (x, x_scale, x_zp, packed_weight, w_scale, w_zp, x2) + if bias is None + else (x, x_scale, x_zp, packed_weight, w_scale, w_zp, x2, bias), + layout, + **kwargs, + ) + ) + if packed_weight.get_name() not in V.graph.constants: + raise AssertionError("packed_weight must be a graph constant") + input_gen_fns = { + 3: lambda x: V.graph.constants[x.get_name()], + 4: lambda x: V.graph.constants[x.get_name()], + 5: lambda x: V.graph.constants[x.get_name()], + } + if bias is not None: + input_gen_fns[7] = lambda x: V.graph.constants[x.get_name()] # For bias + result, _ = autotune_select_algorithm( + "qlinear_binary", + choices, + [x, x_scale, x_zp, packed_weight, w_scale, w_zp, x2] + if bias is None + else [x, x_scale, x_zp, packed_weight, w_scale, w_zp, x2, bias], + layout, + input_gen_fns=input_gen_fns, + ) + if ( + isinstance(result.data.data, ir.CppTemplateBuffer) + and binary_attr == "sum" + and result.data.data.layout == x2.get_layout() + ): + # In this case, since x2 is inplace updated when binary_attr is "sum" + # we update the layout of result to view of x2 + result = ir.TensorBox.create( + ir.CppTemplateBuffer( + layout=ir.NonOwningLayout( + ir.ReinterpretView(data=x2, layout=x2.get_layout()) + ), + inputs=result.data.data.inputs, # type: ignore[arg-type] + make_kernel_render=result.data.data.make_kernel_render, # type: ignore[arg-type] + template=result.data.data.template, + choice=result.data.data.choice, + ) + ) + if len(x_size) > 2 and binary_attr in ["add", "sum"]: + result = view(result, (*x_size[:-1], result.get_size()[-1])) # type: ignore[arg-type] + return result + + if torch._C.has_mkl: + aten_mkl_linear = ExternKernelChoice( + torch.ops.mkl._mkl_linear, + "mkl::_mkl_linear", + has_out_variant=False, + kernel_creator=mkldnn_ir.MKLPackedLinear.create, + ) + cpu_needs_realized_inputs.append(torch.ops.mkl._mkl_linear) + + @register_lowering(torch.ops.mkl._mkl_linear) + def mkl_packed_linear( + x: TensorBox, + packed_w: TensorBox, + orig_w: TensorBox, + b: TensorBox | None, + batch_size, + *, + layout=None, + ): + choices: list[ChoiceCaller] = [] + if config.max_autotune or config.max_autotune_gemm: + transposed_w = permute(orig_w, [1, 0]) + *_, layout, x, transposed_w = mm_args( + x, transposed_w, layout=layout + ) + if use_cpp_gemm_template(layout, x, transposed_w): + CppGemmTemplate.add_choices( + choices, + layout, + [x, packed_w, orig_w], + trans_w=True, + input_indices=[0, 2], + ) + + if len(choices) == 0 or use_aten_gemm_kernels(): + choices.append( + aten_mkl_linear.bind( + (x, packed_w, orig_w), layout, B=None, batch_size=batch_size + ) + ) + + if packed_w.get_name() not in V.graph.constants: + raise AssertionError("packed_w must be a graph constant") + if orig_w.get_name() not in V.graph.constants: + raise AssertionError("orig_w must be a graph constant") + # packed_w is a mkldnn tensor which we can't generate directly + # so we use the weights from the original tensor in autotune. + input_gen_fns = { + 1: lambda x: V.graph.constants[x.get_name()], + 2: lambda x: V.graph.constants[x.get_name()], + } + result: TensorBox # annotation on separate line since tuple unpacking doesn't support inline annotation + result, _ = autotune_select_algorithm( + "packed_linear", + choices, + [x, packed_w, orig_w], + layout, + input_gen_fns=input_gen_fns, + ) + if b is not None: + result = add(result, b) + return result + + add_needs_realized_inputs(cpu_needs_realized_inputs) + + +register_onednn_fusion_ops() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/mock_cache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/mock_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..fd15b3cfdd2fced83448ff35abb191eb79f851e7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/mock_cache.py @@ -0,0 +1,274 @@ +# mypy: ignore-errors + +from __future__ import annotations + +import contextlib +import dataclasses +import sys +import threading +from typing import Any, TYPE_CHECKING +from typing_extensions import override, Self +from unittest.mock import patch + +from torch._inductor import config +from torch._inductor.remote_cache import RemoteCacheBackend + + +if TYPE_CHECKING: + from collections.abc import Callable + from types import TracebackType + + +@dataclasses.dataclass +class Stats: + num_put: int = 0 + num_get_hit: int = 0 + num_get_miss: int = 0 + + def __iadd__(self, other: Stats) -> Self: + self.num_put += other.num_put + self.num_get_hit += other.num_get_hit + self.num_get_miss += other.num_get_miss + return self + + def reset(self) -> None: + self.num_put = 0 + self.num_get_hit = 0 + self.num_get_miss = 0 + + def __str__(self) -> str: + return "".join( + ( + f"puts: {self.num_put}, ", + f"misses: {self.num_get_miss}, ", + f"hits: {self.num_get_hit}, ", + ) + ) + + def __eq__(self, other: object) -> bool: + # Dataclass's default __eq__ checks that the types are the same so can't + # be used with _GlobalItemStats. + return ( + isinstance(other, (Stats, _GlobalItemStats)) + and self.num_put == other.num_put + and self.num_get_hit == other.num_get_hit + and self.num_get_miss == other.num_get_miss + ) + + +class _GlobalItemStats(Stats): + cache: dict[str, object] + + def __init__(self) -> None: + super().__init__() + self.cache = {} + + def reset(self) -> None: + super().reset() + self.cache = {} + + +# The cache states are thread-local so if we're running multiple tests at once +# they won't cross contaminate. However - it needs to be "global" because we +# allow code to create new cache clients which refer to the same cache (because +# it's a remote cache). + + +class _GlobalStats(threading.local): + def __init__(self) -> None: + self.autotune_local = _GlobalItemStats() + self.autotune_remote = _GlobalItemStats() + self.bundled_autotune = _GlobalItemStats() + self.fx_graph = _GlobalItemStats() + self.triton = _GlobalItemStats() + self.aot_autograd = _GlobalItemStats() + self.dynamo_pgo = _GlobalItemStats() + + def reset(self) -> None: + self.autotune_local.reset() + self.autotune_remote.reset() + self.bundled_autotune.reset() + self.fx_graph.reset() + self.triton.reset() + self.aot_autograd.reset() + self.dynamo_pgo.reset() + + def get_stat(self, name: str) -> _GlobalItemStats: + return getattr(self, name) + + def report(self): + subs = ( + ("autotune_local", self.autotune_local), + ("autotune_remote", self.autotune_remote), + ("bundled_autotune", self.bundled_autotune), + ("fx_graph", self.fx_graph), + ("triton", self.triton), + ("aot_autograd", self.aot_autograd), + ("dynamo_pgo", self.dynamo_pgo), + ) + + print("Cache Stats:", file=sys.stderr) + for name, sub in subs: + print(f" {name}: {sub}", file=sys.stderr) + + print("Cache Entries:", file=sys.stderr) + for name, sub in subs: + if sub.cache: + print(f" {name}:", file=sys.stderr) + for k, v in sorted(sub.cache.items()): + v = repr(v) + if len(v) > 100: + v = v[:100] + "..." + print(f" {k!r}: {v}", file=sys.stderr) + + +global_stats = _GlobalStats() + + +class MockBackend(RemoteCacheBackend[Any]): + def __init__(self, name: str) -> None: + self._name = name + + @staticmethod + def with_name(name: str) -> Callable[[], MockBackend]: + def wrapper() -> MockBackend: + return MockBackend(name) + + return wrapper + + @override + def _get(self, key: str) -> Any | None: + stat = global_stats.get_stat(self._name) + if key in stat.cache: + stat += Stats(num_get_hit=1) + return stat.cache.get(key) + else: + stat += Stats(num_get_miss=1) + return None + + @override + def _put(self, key: str, data: Any) -> None: + stat = global_stats.get_stat(self._name) + stat += Stats(num_put=1) + stat.cache[key] = data + + +# List of configs for each cache +_CACHE_CONFIG_EN = ( + "fx_graph_cache", + "fx_graph_remote_cache", + "autotune_local_cache", + "autotune_remote_cache", + "bundled_autotune_remote_cache", +) + + +class PatchCaches(contextlib.AbstractContextManager): + @classmethod + def setUp(cls): + # If this test is using PatchCaches then disable all the caches by + # default, letting the tests turn them on explicitly. This is because + # tests using PatchCaches will often want to check stats explicitly. + cls._savedCacheState = {} + for name in _CACHE_CONFIG_EN: + if hasattr(config, name): + cls._savedCacheState[name] = getattr(config, name) + setattr(config, name, False) + + @classmethod + def tearDown(cls): + # Restore cache defaults + for name in _CACHE_CONFIG_EN: + delattr(config, name) + if name in cls._savedCacheState: + setattr(config, name, cls._savedCacheState[name]) + + def __init__(self) -> None: + self._stack = contextlib.ExitStack() + + def __enter__(self) -> Self: + global_stats.reset() + self._stack.__enter__() + + ctx = patch( + "torch._inductor.remote_cache.LocalAutotuneCache.backend_override_cls", + MockBackend.with_name("autotune_local"), + ) + self._stack.enter_context(ctx) + + ctx = patch( + "torch._inductor.remote_cache.RemoteAutotuneCache.backend_override_cls", + MockBackend.with_name("autotune_remote"), + ) + self._stack.enter_context(ctx) + + ctx = patch( + "torch._inductor.remote_cache.RemoteBundledAutotuneCache.backend_override_cls", + MockBackend.with_name("bundled_autotune"), + ) + self._stack.enter_context(ctx) + + ctx = patch( + "torch._inductor.remote_cache.RemoteFxGraphCache.backend_override_cls", + MockBackend.with_name("fx_graph"), + ) + self._stack.enter_context(ctx) + + ctx = patch( + "torch._inductor.remote_cache.RemoteAOTAutogradCache.backend_override_cls", + MockBackend.with_name("aot_autograd"), + ) + self._stack.enter_context(ctx) + + ctx = patch( + "torch._inductor.remote_cache.RemoteDynamoPGOCache.backend_override_cls", + MockBackend.with_name("dynamo_pgo"), + ) + self._stack.enter_context(ctx) + + if config.is_fbcode(): + ctx = patch( + "torch._inductor.fb.remote_cache.FbRemoteAutotuneCache.backend_override_cls", + MockBackend.with_name("autotune_remote"), + ) + self._stack.enter_context(ctx) + + ctx = patch( + "torch._inductor.fb.remote_cache.FbRemoteBundledAutotuneCache.backend_override_cls", + MockBackend.with_name("bundled_autotune"), + ) + self._stack.enter_context(ctx) + + ctx = patch( + "torch._inductor.fb.remote_cache.FbRemoteFxGraphCache.backend_override_cls", + MockBackend.with_name("fx_graph"), + ) + self._stack.enter_context(ctx) + + ctx = patch( + "triton.fb.fb_memcache.FbMemcacheRemoteKernelCache.backend_override_cls", + MockBackend.with_name("triton"), + ) + self._stack.enter_context(ctx) + + ctx = patch( + "torch._inductor.fb.remote_cache.FbRemoteAOTAutogradCache.backend_override_cls", + MockBackend.with_name("aot_autograd"), + ) + self._stack.enter_context(ctx) + + ctx = patch( + "torch._inductor.fb.remote_cache.FbRemoteDynamoPGOCache.backend_override_cls", + MockBackend.with_name("dynamo_pgo"), + ) + self._stack.enter_context(ctx) + + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self._stack.__exit__(exc_type, exc_value, traceback) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/ops_handler.py b/.venv/lib/python3.12/site-packages/torch/_inductor/ops_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..7c6aad9417e302997075d25334ff927052c5d14b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/ops_handler.py @@ -0,0 +1,1230 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import inspect +import itertools +import re +import warnings +from io import StringIO +from typing import Any, Generic, Literal, NamedTuple, TYPE_CHECKING, TypeVar +from unittest.mock import patch + +import sympy + +import torch +import torch.utils._pytree as pytree + +from ..utils._ordered_set import OrderedSet +from .utils import IndentedBuffer, reduction_num_outputs, sympy_index_symbol, sympy_str + + +if TYPE_CHECKING: + from collections.abc import Callable + + +T = TypeVar("T") +AtomicMode = Literal[ + "atomic_add", + "atomic_max", + "atomic_min", + "atomic_and", + "atomic_or", + "atomic_xor", + "atomic_cas", + "atomic_xchg", +] +StoreMode = AtomicMode | Literal["tma"] | None +ReductionType = Literal[ + "argmax", + "argmin", + "argmax_value", + "argmin_value", + "argmax_with_value", + "argmin_with_value", + "welford_reduce", + "welford_combine", + "any", + "fmax", + "max", + "min", + "prod", + "sum", + "dot", + "xor_sum", + "online_softmax_reduce", +] + + +def _arg_str(a: object) -> str: + if isinstance(a, sympy.Expr): + return sympy_str(a) + return str(a) + + +# See OpDecompositions for superclass that desugars operations like reciprocal/square. +class OpsHandler(Generic[T]): + """ + Protocol describing the set of valid operations on ``torch._inductor.virtualized.ops``, + as well as the contract for op handlers. The type T signifies the domain + of the abstract analysis AKA what all the functions return / take as arguments + anywhere compute occurs. + + While these operators are typically dtype polymorphic (e.g., you can use mul + on both integers and floats), they do NOT do promotion and usually return the + same dtype as the input. You are expected to have handled type promotion + during ATen decompositions. Most operators correspond exactly to pointwise + operations as defined by torch, so when in doubt about semantics, check the + corresponding torch documentation. These are all scalar operations (so they + are defined to operate on a single element at a time.) + + For convenience, many operators take a src_dtype which indicates what the dtype + of the input argument is. Although in principle this can be derived by an + analysis, providing this for ops where it is useful helps avoid having to repeatedly + recompute dtype in code generation. + + Note that this often describes a class of static methods, for stateless + ops handlers. + + Handlers are often defined using metaprogramming (e.g. _initialize_pointwise_overrides), + which means you will not get type errors for those methods. We have tests in + test/inductor/test_op_completeness.py which check that all operators are implemented after + all the metaprogramming has run. + """ + + def constant(self, value: bool | float | int, dtype: torch.dtype) -> T: + """Produces a scalar constant of type dtype.""" + raise NotImplementedError + + def load_seed(self, name: str, offset: T) -> T: + """Computes inductor_prims.lookup_seed.""" + raise NotImplementedError + + def rand(self, seed: T, offset: T) -> T: + """Computes inductor_prims.random with mode="rand". offset has dtype int32.""" + raise NotImplementedError + + def rand_eager( + self, seed: T, base_offset: T, threads_per_round: T, tid: T, vec: T + ) -> T: + """Computes inductor_prims.random with mode="rand_eager". offset has dtype int32.""" + raise NotImplementedError + + def randn(self, seed: T, offset: T) -> T: + """Computes inductor_prims.random with mode="randn". offset has dtype int32.""" + raise NotImplementedError + + def randint64(self, seed: T, offset: T, low: T, high: T) -> T: + """Computes inductor_prims.randint. offset has dtype int32.""" + raise NotImplementedError + + def masked(self, mask: T, body: Callable[[], T], other: T) -> T: + """ + Computes body, but only perform loads/stores if the boolean mask + evaluates to true. For example, you would use this if you needed to + perform an indirect load that may not be valid on some elements; + without masking, invalid accesses can cause IMAs. When mask is true, + the result is the result of body; otherwise it is other. Here, `other` + needs to be a constant. + + Contrast this with ops.where, which can multiplex between two values + that have been unconditionally computed. + """ + raise NotImplementedError + + def where(self, condition: T, input: T, other: T) -> T: + """ + Computes torch.where: when condition is true, return input; otherwise return other. + """ + raise NotImplementedError + + def index_expr(self, expr: sympy.Expr, dtype: torch.dtype) -> T: + """ + Converts a sympy expression into a scalar suitable for indexing memory. + The kernel decides the actual computation dtype (typically int32) — the + ``dtype`` argument is advisory and is not honored when it would conflict + with the kernel's indexing dtype. For values that must respect the + requested dtype, use ``value_expr`` instead. + """ + raise NotImplementedError + + def value_expr(self, expr: sympy.Expr, dtype: torch.dtype) -> T: + """ + Converts a sympy expression into a scalar of type ``dtype`` that + participates in tensor value computation. Unlike ``index_expr``, the + result dtype is respected, so this is the right op when the user + explicitly requested the dtype (e.g. ``arange(dtype=torch.int64)`` + whose result is added to a tensor rather than used as an index). + """ + raise NotImplementedError + + def to_dtype( + self, + x: T, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types: bool = True, + ) -> T: + """ + Convert x to dtype. src_dtype can be optionally set to specify what the original + dtype of x was, which can improve code generation (used by torch to(dtype=dtype)). + """ + raise NotImplementedError + + def trunc_to_int(self, x: T, dtype: torch.dtype) -> T: + """ + Convert x to dtype with truncation semantics (similar to how the int + constructor works in Python). In Inductor codegen, this just decays + to trunc and then to_dtype, but this composite operation helps + roundtrips for Sympy evaluation. + + dtype is taken as an explicit parameter because the desired output + dtype is typically the index dtype, which may vary between int32 and + int64 depending on if we've shown that all the indexing operations can + be done in int32. + """ + raise NotImplementedError + + def ceil_to_int(self, x: T, dtype: torch.dtype) -> T: + """ + Convert x to dtype with ceiling semantics. See also trunc_to_int. + """ + raise NotImplementedError + + def floor_to_int(self, x: T, dtype: torch.dtype) -> T: + """ + Convert x to dtype with ceiling semantics. See also trunc_to_int. + """ + raise NotImplementedError + + def round_to_int(self, x: T, dtype: torch.dtype) -> T: + """ + Convert x to dtype with round-to-even semantics. See also trunc_to_int. + """ + raise NotImplementedError + + def to_dtype_bitcast(self, x: T, dtype: torch.dtype, src_dtype: torch.dtype) -> T: + """ + Reinterpret cast x to dtype (reinterpreting the bits in memory as another dtype.) + src_dtype must be the original type of x. + """ + raise NotImplementedError + + def identity(self, x: T) -> T: + """ + Returns x as is. This is used to trigger CSE. + """ + raise NotImplementedError + + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # These operations are only available in a "kernel" context. Check + # torch._inductor.codegen.common.CSEProxy for their typical implementation + # in op handler (routing to their respective implementations in the kernel + # handler) + # + # Importantly, inside a kernel, indexing and mask variables are available + # in scope, which are typically used by sympy.Expr indexing. + + def indirect_indexing( + self, x: T, size: sympy.Expr, check: bool = True, wrap_neg=True + ) -> sympy.Expr: + """ + Convert an integral x into a sympy.Expr that can be subsequently used in + indexing computation. 'size' represents an upper bound on what valid + indexes can be; when 'check' is True, we check that the x is in bounds. + + NB: This is typically mandatory to implement for any analysis, because you + MUST return a valid sympy.Expr of some sort (even if it's a meaningless symbol). + """ + raise NotImplementedError + + def load(self, name: str, index: sympy.Expr) -> T: + """ + Load from the memory location 'name', offset by some indexing expression 'index'. + """ + raise NotImplementedError + + def store( + self, + name: str, + index: sympy.Expr, + value: T, + mode: StoreMode = None, + ) -> None: + """ + Store 'value' to the memory location 'name' offset by 'expr'. If + specified, 'mode' can require the store to be an atomic addition. + """ + raise NotImplementedError + + # TODO: Better explain how the "collective" semantics of these ops; + # remember that the input value is a scalar, you can't reduce on it in the + # traditional sense! + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: T, + ) -> T | tuple[T, ...]: + """ + Perform a 'reduction_type' reduction on 'value' of dtype 'src_dtype', + using 'dtype' as the accumulation dtype for the reduction. The result + is an intermediate computation which should be stored to the final + location using 'ops.store_reduction'. + + Valid reduction types are . For Welford reduction types, this + function returns multiple outputs; consult reduction_num_outputs to + determine the amount in metaprogramming applications. + """ + raise NotImplementedError + + # TODO: in practice, this seems to actually return None, but not returning + # a T makes common __getattr__ idioms not type correctly. Figure out if + # this should be returning something. + def store_reduction(self, name: str, index: sympy.Expr, value: T) -> None: + """ + Store the fully accumulated result of 'reduction' to the memory + location 'name' offset by 'expr'. + """ + raise NotImplementedError + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[[tuple[T, ...], tuple[T, ...]], tuple[T, ...]], + values: tuple[T, ...], + ) -> tuple[T, ...]: + """ + Perform an associative scan on 'value'. + """ + # TODO: Improve the description with some pseudocode + raise NotImplementedError + + def sort( + self, + dtypes: tuple[torch.dtype, ...], + values: tuple[T, ...], + stable: bool, + descending: bool, + ) -> tuple[T, ...]: + """ + Sort values along the reduction dimension. + """ + raise NotImplementedError + + def bucketize( + self, + values: T, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: T, + indexing_dtype: torch.dtype, + right: bool, + sorter: tuple[str, sympy.Expr] | None = None, + sorter_indices: T | None = None, + ) -> T: + # See [Note: Inductor bucketize op] + raise NotImplementedError + + def partial_accumulate( + self, + name: str, + reduction_type: ReductionType, + value: T, + extra_meta: dict[str, Any], + ) -> None: + raise NotImplementedError + + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # The following ops have semantics that correspond exactly to the torch + # operation with the same corresponding name. + + def abs(self, x0: T) -> T: + raise NotImplementedError + + def exp(self, x0: T) -> T: + raise NotImplementedError + + def exp2(self, x0: T) -> T: + raise NotImplementedError + + def expm1(self, x0: T) -> T: + raise NotImplementedError + + def sqrt(self, x0: T) -> T: + raise NotImplementedError + + def relu(self, x0: T) -> T: + raise NotImplementedError + + def minimum(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def maximum(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def fmaximum(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def cos(self, x0: T) -> T: + raise NotImplementedError + + def sin(self, x0: T) -> T: + raise NotImplementedError + + def lgamma(self, x0: T) -> T: + raise NotImplementedError + + def erf(self, x0: T) -> T: + raise NotImplementedError + + def cosh(self, x0: T) -> T: + raise NotImplementedError + + def sinh(self, x0: T) -> T: + raise NotImplementedError + + def acos(self, x0: T) -> T: + raise NotImplementedError + + def acosh(self, x0: T) -> T: + raise NotImplementedError + + def asin(self, x0: T) -> T: + raise NotImplementedError + + def asinh(self, x0: T) -> T: + raise NotImplementedError + + def atan2(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def atan(self, x0: T) -> T: + raise NotImplementedError + + def atanh(self, x0: T) -> T: + raise NotImplementedError + + def copysign(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def erfc(self, x0: T) -> T: + raise NotImplementedError + + def erfinv(self, x0: T) -> T: + raise NotImplementedError + + def frexp(self, x0: T): + raise NotImplementedError + + def hypot(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def log10(self, x0: T) -> T: + raise NotImplementedError + + def log2(self, x0: T) -> T: + raise NotImplementedError + + def ldexp(self, x0: T, n: T) -> T: + raise NotImplementedError + + def nextafter(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def logical_and(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def logical_not(self, x0: T) -> T: + raise NotImplementedError + + def logical_or(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def logical_xor(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def bitwise_and(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def bitwise_not(self, x0: T) -> T: + raise NotImplementedError + + def bitwise_or(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def bitwise_xor(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def bitwise_left_shift(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def bitwise_right_shift(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def rsqrt(self, x0: T) -> T: + raise NotImplementedError + + def log1p(self, x0: T) -> T: + raise NotImplementedError + + def tan(self, x0: T) -> T: + raise NotImplementedError + + def tanh(self, x0: T) -> T: + raise NotImplementedError + + def sigmoid(self, x0: T) -> T: + raise NotImplementedError + + def signbit(self, x0: T) -> T: + raise NotImplementedError + + def fmod(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def log(self, x0: T) -> T: + raise NotImplementedError + + def isinf(self, x0: T) -> T: + raise NotImplementedError + + def isnan(self, x0: T) -> T: + raise NotImplementedError + + # NB: this returns a float, like the torch operation + # This rounds half to even to break ties + def round(self, x0: T) -> T: + raise NotImplementedError + + # NB: this returns a float, like the torch operation + def floor(self, x0: T) -> T: + raise NotImplementedError + + def sign(self, x0: T) -> T: + raise NotImplementedError + + # NB: this returns a float, like the torch operation + def trunc(self, x0: T) -> T: + raise NotImplementedError + + # NB: this returns a float, like the torch operation + def ceil(self, x0: T) -> T: + raise NotImplementedError + + def neg(self, x0: T) -> T: + raise NotImplementedError + + def reciprocal(self, x0: T) -> T: + raise NotImplementedError + + def eq(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def ne(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def lt(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def gt(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def le(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def ge(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def add(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def sub(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def mul(self, x0: T, x1: T) -> T: + raise NotImplementedError + + # NB: this returns a float, like the torch operation + def pow(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def and_(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def or_(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def xor(self, x0: T, x1: T) -> T: + raise NotImplementedError + + # These are metaprogrammed by MockHandler._init_cls + def lshift(self, x0: T, x1: T) -> T: + raise NotImplementedError + + def rshift(self, x0: T, x1: T) -> T: + raise NotImplementedError + + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # These are "special" operators. These only exist if the target + # language actually supports the operator. Keep this in sync with + # pointwise_overrides_data. + + def airy_ai(self, x: T) -> T: + raise NotImplementedError + + def bessel_j0(self, x: T) -> T: + raise NotImplementedError + + def bessel_j1(self, x: T) -> T: + raise NotImplementedError + + def bessel_y0(self, x: T) -> T: + raise NotImplementedError + + def bessel_y1(self, x: T) -> T: + raise NotImplementedError + + def digamma(self, x: T) -> T: + raise NotImplementedError + + def erfcx(self, x: T) -> T: + raise NotImplementedError + + def fma(self, x: T, y: T, z: T) -> T: + raise NotImplementedError + + def mul_rn(self, x: T, y: T) -> T: + """Multiplication with round-to-nearest, preventing fusion with subsequent ops.""" + raise NotImplementedError + + def igamma(self, x: T, y: T) -> T: + raise NotImplementedError + + def igammac(self, x: T, y: T) -> T: + raise NotImplementedError + + def gammainc(self, x: T, y: T) -> T: + raise NotImplementedError + + def gammaincc(self, x: T, y: T) -> T: + raise NotImplementedError + + def i0(self, x: T) -> T: + raise NotImplementedError + + def i0e(self, x: T) -> T: + raise NotImplementedError + + def i1(self, x: T) -> T: + raise NotImplementedError + + def i1e(self, x: T) -> T: + raise NotImplementedError + + def log_ndtr(self, x: T) -> T: + raise NotImplementedError + + def modified_bessel_i0(self, x: T) -> T: + raise NotImplementedError + + def modified_bessel_i1(self, x: T) -> T: + raise NotImplementedError + + def modified_bessel_k0(self, x: T) -> T: + raise NotImplementedError + + def modified_bessel_k1(self, x: T) -> T: + raise NotImplementedError + + def ndtr(self, x: T) -> T: + raise NotImplementedError + + def ndtri(self, x: T) -> T: + raise NotImplementedError + + def polygamma(self, x: T, y: T) -> T: + raise NotImplementedError + + def scaled_modified_bessel_k0(self, x: T) -> T: + raise NotImplementedError + + def scaled_modified_bessel_k1(self, x: T) -> T: + raise NotImplementedError + + def spherical_bessel_j0(self, x: T) -> T: + raise NotImplementedError + + def zeta(self, x: T, y: T) -> T: + raise NotImplementedError + + def chebyshev_polynomial_t(self, x: T, y: T) -> T: + raise NotImplementedError + + def chebyshev_polynomial_u(self, x: T, y: T) -> T: + raise NotImplementedError + + def chebyshev_polynomial_v(self, x: T, y: T) -> T: + raise NotImplementedError + + def chebyshev_polynomial_w(self, x: T, y: T) -> T: + raise NotImplementedError + + def legendre_polynomial_p(self, x: T, y: T) -> T: + raise NotImplementedError + + def shifted_chebyshev_polynomial_t(self, x: T, y: T) -> T: + raise NotImplementedError + + def shifted_chebyshev_polynomial_u(self, x: T, y: T) -> T: + raise NotImplementedError + + def shifted_chebyshev_polynomial_v(self, x: T, y: T) -> T: + raise NotImplementedError + + def shifted_chebyshev_polynomial_w(self, x: T, y: T) -> T: + raise NotImplementedError + + def hermite_polynomial_h(self, x: T, y: T) -> T: + raise NotImplementedError + + def hermite_polynomial_he(self, x: T, y: T) -> T: + raise NotImplementedError + + def laguerre_polynomial_l(self, x: T, y: T) -> T: + raise NotImplementedError + + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # These operators are a bit special, because they are conventionally + # natively supported in both Python and C, but the semantics differ so + # care must be taken + + def truncdiv(self, x0: T, x1: T) -> T: + """C-style trunc division between integers only. Computes the true + division of two numbers and rounds the result to zero. + """ + raise NotImplementedError + + def floordiv(self, x0: T, x1: T) -> T: + """Python-style floor division between integers only. Computes the + true division of two numbers and floors the result. If you want + floor division for floats, do regular truediv and floor the result. + """ + raise NotImplementedError + + def truediv(self, x0: T, x1: T) -> T: + """True division between floats. Integer inputs are NOT valid. To + do Python-style (int, int) -> float division, use int_truediv""" + raise NotImplementedError + + def div_rn(self, x0: T, x1: T) -> T: + """Division with round-to-nearest rounding mode. Used for matching + eager CUDA semantics where division uses IEEE round-to-nearest.""" + raise NotImplementedError + + def int_truediv(self, x0: T, x1: T) -> T: + """True division between integers. This is NOT the same as promoting + to float and doing integer division, there is a bespoke algorithm for + doing the division in higher precision than the above. + """ + raise NotImplementedError + + def mod(self, x0: T, x1: T) -> T: + """C-style modulus, take sign from LHS (x0).""" + raise NotImplementedError + + def remainder(self, x0: T, x1: T) -> T: + """Python-style modulus, take sign from RHS (x1).""" + raise NotImplementedError + + def square(self, x0: T) -> T: + raise NotImplementedError + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + raise NotImplementedError + + # halide-only + def halide_clamp(self, value: T, size: sympy.Expr, check: bool) -> T: + raise NotImplementedError + + # triton-only + def dot(self, x: T, y: T) -> T: + raise NotImplementedError + + # triton-only + def inline_asm_elementwise( + self, + *inputs: T, + asm: str, + constraints: str | None = None, + dtype: torch.dtype = torch.float32, + is_pure: bool = True, + pack: int = 1, + input_dtypes: tuple[torch.dtype, ...] | None = None, + ) -> T: + raise NotImplementedError + + def output(self, *args: T) -> None: + """This is a fake op used in analysis but not codegen""" + raise NotImplementedError + + def placeholder(self, index: int) -> T: + """This is a fake op used in analysis but not codegen""" + raise NotImplementedError + + def device_assert_async(self, cond: T, msg: str) -> T: + raise NotImplementedError + + +_ignore_op_re = re.compile(r"_.*|paren").fullmatch + + +def list_ops(cls: type[Any]): + return OrderedSet([x for x in dir(cls) if not _ignore_op_re(x)]) + + +OP_NAMES = list_ops(OpsHandler) + + +class DefaultHandler(OpsHandler[Any]): + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + """ + Default implementation for all ops. Override in a subclass to + provide generic op behavior. + + Args: + name: name of the op, see OpHandler.{name} + args: positional args passed to the op + kwargs: keyword args passed to the op + + Returns: + return value of the op + + """ + raise NotImplementedError + + def __getattr__(self, name: str) -> Any: + def fallback(*args: Any, **kwargs: Any) -> Any: + return self._default(name, args, kwargs) + + # would like to remove this function entirely, but it's used in MTIA backend + warnings.warn(f"undefined OpHandler.{name}, please add missing op schema") + return fallback + + @staticmethod + def _call_default(target: str): + def call_default(self, *args, **kwargs): + return self._default(target, args, kwargs) + + call_default.__name__ = target + return call_default + + @classmethod + def _init_cls(cls): + """ + Here we codegen many functions of the form: + + def add(self, a, b): + return self._default('add', (a, b), {}) + + and install them in cls. This is the same as _call_default above, + but is about 1.2x faster since CPython varargs parsing is slow. + """ + code = StringIO() + for target in OP_NAMES: + sig = inspect.signature(getattr(OpsHandler, target)) + if all( + p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + and p.default is inspect.Parameter.empty + for p in sig.parameters.values() + ): + self_arg, *args = sig.parameters.keys() + if self_arg != "self": + raise AssertionError( + f"expected first parameter 'self', got {self_arg!r}" + ) + code.write( + f""" + def {target}(self, {", ".join(args)}): + return self._default({target!r}, ({", ".join(args)}, ), {{}}) + """.strip() + ) + code.write("\n\n") + else: + # slower fallback for ops with default or variadic arguments + setattr(cls, target, cls._call_default(target)) + + ctx: dict[str, Any] = {} + exec(code.getvalue(), ctx) + for target, impl in ctx.items(): + if target in OP_NAMES: + setattr(cls, target, impl) + + +DefaultHandler._init_cls() + + +class NoopHandler(DefaultHandler): + name = "NoopHandler" + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + return None + + @staticmethod + def masked(mask, body, other) -> None: + return None + + @staticmethod + # pyrefly: ignore [bad-override] + def frexp(x) -> tuple[None, None]: + return (None, None) + + @staticmethod + def scan(dtypes, combine_fn, values) -> tuple[None, ...]: + return (None,) * len(values) + + @staticmethod + def sort(dtypes, values, stable, descending) -> tuple[None, ...]: + return (None,) * len(values) + + @staticmethod + # pyrefly: ignore [bad-override] + def indirect_indexing(index_var, size, check=True, wrap_neg=True) -> sympy.Symbol: + return sympy.S.Zero + + +class BasicMathOpsMixin: + @staticmethod + def add(a, b): + return f"{a} + {b}" + + @staticmethod + def sub(a, b): + return f"{a} - {b}" + + @staticmethod + def mul(a, b): + return f"{a} * {b}" + + @staticmethod + def floordiv(a, b): + return f"{a} // {b}" + + @staticmethod + def truediv(a, b): + return f"{a} / {b}" + + @staticmethod + def mod(a, b): + # careful, depending on target semantics varies + return f"{a} % {b}" + + @staticmethod + def pow(a, b): + return f"{a} ** {b}" + + @staticmethod + def lshift(a, b): + return f"{a} << {b}" + + @staticmethod + def rshift(a, b): + return f"{a} >> {b}" + + @staticmethod + def and_(a, b): + return f"{a} & {b}" + + @staticmethod + def or_(a, b): + return f"{a} | {b}" + + @staticmethod + def xor(a, b): + return f"{a} ^ {b}" + + @staticmethod + def eq(a, b): + return f"{a} == {b}" + + @staticmethod + def ne(a, b): + return f"{a} != {b}" + + @staticmethod + def lt(a, b): + return f"{a} < {b}" + + @staticmethod + def gt(a, b): + return f"{a} > {b}" + + @staticmethod + def le(a, b): + return f"{a} <= {b}" + + @staticmethod + def ge(a, b): + return f"{a} >= {b}" + + @staticmethod + def neg(a): + return f"-{a}" + + +class MockHandler(BasicMathOpsMixin, DefaultHandler): + name = "MockHandler" + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + fargs = [*map(_arg_str, args)] + for k, v in kwargs.items(): + fargs.append(f"{k}={_arg_str(v)}") + return f"ops.{name}({', '.join(fargs)})" + + @staticmethod + def masked(mask, body, other) -> str: + return f"ops.masked({mask}, {body()}, {other})" + + @staticmethod + # pyrefly: ignore [bad-override] + def frexp(x): + return (f"ops.frexp({x})[0]", f"ops.frexp({x})[1]") + + @staticmethod + def scan(dtypes, combine_fn, values): + return tuple( + f"ops.scan({dtypes}, {combine_fn}, {values})[{i}]" + for i in range(len(values)) + ) + + @staticmethod + def sort(dtypes, values, stable, descending): + return tuple( + f"ops.sort({dtypes}, {values}, stable={stable}, descending={descending})[{i}]" + for i in range(len(values)) + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def indirect_indexing(index_var, size, check=True, wrap_neg=True) -> sympy.Symbol: + return sympy_index_symbol(str(index_var)) + + +class KernelFormatterHandler(DefaultHandler): + def __init__(self, parent_handler: OpsHandler[Any]): + self.parent_handler = parent_handler + self._output = IndentedBuffer(1) + self.var_counter = itertools.count() + + @staticmethod + def ir_to_string(ir_fn, index, rindex=None) -> str: + from .ir import FlexibleLayout + from .virtualized import V + + args = [index, rindex] if rindex is not None else [index] + names = ["index", "rindex"] if rindex is not None else ["index"] + formatter = KernelFormatterHandler(MockHandler()) + + with formatter._output.indent(-1): + formatter._output.writeline(f"def inner_fn({', '.join(names)}):") + for name, arg in zip(names, args): + if arg: + lhs = ", ".join( + [ + str("_" if isinstance(v, (int, sympy.Integer)) else v) + for v in arg + ] + ) + formatter._output.writeline(f"{lhs} = {name}") + + with ( + V.set_ops_handler(formatter), + patch.object(FlexibleLayout, "allow_indexing", True), + ): + result = ir_fn(*args) + return formatter.getvalue(result) + + def indirect_indexing(self, *args, **kwargs) -> sympy.Symbol: + return self.parent_handler.indirect_indexing(*args, **kwargs) + + def _write(self, line): + # replace line with a new variable name + varname = f"tmp{next(self.var_counter)}" + self._output.writeline(f"{varname} = {line}") + return varname + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + return pytree.tree_map( + self._write, getattr(self.parent_handler, name)(*args, **kwargs) + ) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: str | tuple[str, ...], + ) -> str | tuple[str, ...]: + line = self.parent_handler.reduction(dtype, src_dtype, reduction_type, value) + num_values = reduction_num_outputs(reduction_type) + varnames = [f"tmp{next(self.var_counter)}" for _ in range(num_values)] + self._output.writeline(f"{','.join(varnames)} = {line}") + return tuple(varnames) if num_values > 1 else varnames[0] + + def getvalue(self, result): + self._output.writeline(f"return {result}") + return self._output.getvalue() + + +class WrapperHandler(DefaultHandler): + def __init__(self, inner: OpsHandler[Any]): + self._inner = inner + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + return getattr(self._inner, name)(*args, **kwargs) + + +class AddParenHandler(WrapperHandler): + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + val = getattr(self._inner, name)(*args, **kwargs) + if not val or isinstance(val, (sympy.Expr, tuple, list)): + return val + return f"({val})" + + +class OpCountResult(NamedTuple): + num_ops: int + used_ops: OrderedSet[str] + read_buffers: list[str] + nontrivial_read_count: int + + +class OpCounterCSE(DefaultHandler): + """Shim to count how many ops are used""" + + def __init__(self, inner: OpsHandler[Any]): + super().__init__() + self.parent_handler = inner + self.op_count = 0 + self.var_names: dict[str, str] = {} + self._used_ops: OrderedSet[str] = OrderedSet() + self._read_names: list[str] = [] + self._nontrivial_read_count = 0 + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + self._used_ops.add(name) + return pytree.tree_map( + self._update_count, getattr(self.parent_handler, name)(*args, **kwargs) + ) + + def _update_count(self, val): + varname = self.var_names.get(val) + if not varname: + varname = f"tmp{self.op_count}" + self.op_count += 1 + self.var_names[val] = varname + return varname + + def indirect_indexing(self, *args, **kwargs): + self._used_ops.add("indirect_indexing") + return self.parent_handler.indirect_indexing(*args, **kwargs) + + def load(self, name: str, index: sympy.Expr) -> str: + val = self.parent_handler.load(name, index) + if val not in self.var_names: + self._used_ops.add("load") + self._read_names.append(name) + if not isinstance(index, (sympy.Integer, int)): + self._nontrivial_read_count += 1 + return self._update_count(val) + + def load_seed(self, name: str, offset: T): + val = self.parent_handler.load_seed(name, offset) + if val not in self.var_names: + self._used_ops.add("load_seed") + self._read_names.append(name) + return self._update_count(val) + + def bucketize( + self, + values: T, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: T, + indexing_dtype: torch.dtype, + right: bool, + sorter: tuple[str, sympy.Expr] | None = None, + sorter_indices: T | None = None, + ) -> T: + """ + See [Note: Inductor bucketize op] + """ + val = self.parent_handler.bucketize( + values, + boundaries, + boundary_indices, + indexing_dtype, + right, + sorter, + sorter_indices, + ) + if val not in self.var_names: + self._used_ops.add("bucketize") + self._read_names.append(boundaries[0]) + if sorter is not None: + self._read_names.append(sorter[0]) + return self._update_count(val) + + def getvalue(self): + return OpCountResult( + self.op_count, self._used_ops, self._read_names, self._nontrivial_read_count + ) + + +class ExtractConstantsHandler(NoopHandler): + def __init__(self, device: torch.device | None): + self.device = device + + def constant(self, value: Any, dtype: torch.dtype) -> torch._inductor.ir.Constant: + from torch._inductor import ir + + return ir.Constant( + value=value, dtype=dtype, device=self.device or torch.get_default_device() + ) + + +class SimpleCSEHandler(WrapperHandler): + """Wraps the underlying handler with a CSE pass + + NOTE: Compared to codegen level CSE this is simplified as it + doesn't support stores which require load cache invalidation. + """ + + def __init__(self, inner: Any): + super().__init__(inner) + self.cse_cache: dict[str, Any | tuple[Any, ...]] = {} + self.mock = MockHandler() + + def indirect_indexing(self, *args, **kwargs) -> sympy.Expr: + return super().indirect_indexing(*args, **kwargs) # type: ignore[misc] + + def store(self, *args, **kwargs) -> None: + raise NotImplementedError("store not implemented") + + def store_reduction(self, *args, **kwargs) -> None: + raise NotImplementedError("store not implemented") + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + key = getattr(self.mock, name)(*args, **kwargs) + val = self.cse_cache.get(key) + if val is not None: + return val + + val = getattr(self._inner, name)(*args, **kwargs) + self.cse_cache[key] = val + return val + + def device_assert_async(self, *args, **kwargs) -> None: + raise NotImplementedError( + f"{type(self).__name__}: device_assert_async should be handled by CSEProxy" + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/optimize_indexing.py b/.venv/lib/python3.12/site-packages/torch/_inductor/optimize_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..3d3bf5b7d402a23cdbebc9b425c81f363f13210a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/optimize_indexing.py @@ -0,0 +1,421 @@ +import math +from dataclasses import dataclass +from typing import Any + +import sympy + +import torch +from torch.fx.node import map_arg +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.value_ranges import ValueRanges + +from .loop_body import LoopBody +from .utils import dominated_nodes + + +def val_expressable_in_32_bits(val: Any) -> bool: + if getattr(val, "is_Boolean", False): + return True + + if isinstance(val, sympy.Expr): + if not val.is_number: + raise AssertionError(f"expected a number, got {val}") + if val.is_Integer or val.is_Boolean: + val = int(val) + else: + val = float(val) + + # bound within mantissa + if isinstance(val, float): + return val <= (2**24) and val >= -(2**24) + + if isinstance(val, int): + iinfo = torch.iinfo(torch.int32) + return val <= iinfo.max and val >= iinfo.min + + raise TypeError(f"Unexpected value {val}") + + +def range_expressable_in_32_bits(range: ValueRanges[sympy.Expr]) -> bool: + return val_expressable_in_32_bits(range.lower) and val_expressable_in_32_bits( + range.upper + ) + + +def try_to_reduce_precision( + node: Any, + bounds: dict[Any, Any], + indirect_vars: list[Any], + indices: dict[Any, sympy.Expr], + replacement_vals: dict[Any, ValueRanges[sympy.Expr]], +) -> None: + # if a downstream use of a node explicitly converts to int32, or float16/float32/float64, + # then its precision is set for that chain of uses, and we don't need to consider those + # dominated values + def skip_filter(node: Any) -> bool: + return node.target == "to_dtype" and node.args[2] in ( + torch.int32, + torch.float32, + torch.float64, + ) + + # TODO - there are dominated uses whose dtype does not depend on whether + # we reduce the precision here, e.g. add(int64, int64) one of the args can be reduced to + # int32 without changing the output precision of the node. this case hasn't shown up + for dominated in dominated_nodes([node], skip_filter): + if dominated.target in ["store", "output"]: + continue + + if isinstance(dominated.target, str) and "set_indirect" in dominated.target: + idx = int(dominated.target[len("set_indirect") :]) + indirect_var = indirect_vars[idx] + + # We check that we can compute all the indices it's involved in with int32 + for index, expr in indices.items(): + if indirect_var in expr.free_symbols: + index_val = replacement_vals[index] + + if math.isinf(index_val.lower) or math.isinf(index_val.upper): + return + + # all indices are integers, so make sure that we + # use the bounds of integers instead of floats. + # TODO - not sure if we should be doing int/float casts while tracing, + # might interfere with sympy. + + index_val_int = ValueRanges[sympy.Expr]( + int(index_val.lower), int(index_val.upper) + ) + if not range_expressable_in_32_bits(index_val_int): + return + + if not range_expressable_in_32_bits(bounds[dominated]): + return + + args = list(node.args) + args[2] = torch.int32 + node.args = tuple(args) + + +def indexing_dtype_strength_reduction(loop_body: LoopBody) -> None: + """ + Performs Value Range Analysis on LoopBody's fx graph to reduce precision of + intermediaries from int64 to int32 + """ + bv = loop_body.bounds() + + int64_dtype_nodes = [ + node + for node in loop_body.get_nodes() + if ( + node.target == "to_dtype" + and node.args[2] == torch.int64 + and node not in bv.unbounded_vars + ) + ] + if not int64_dtype_nodes: + return + + bounds = bv.get_bounds() + + # TODO - if dominated node of one to_dtype is not expressible in int32, + # we should short circuit another to_dtype node if that node also dominates + for node in int64_dtype_nodes: + try_to_reduce_precision( + node, + bounds, + loop_body.indirect_vars, + loop_body.indexing_exprs, + bv.replacement_vals, + ) + + +@dataclass(frozen=True) +class _ValueUseRule: + # These fields are op arguments, so Any covers FX nodes, SymPy exprs, + # scalars, and nested tuples/lists. value_sinks seed the backward walk + # unconditionally. value_inputs propagate value demand only when the op's + # result is already value-reachable. indexing_inputs block propagation + # because they only affect addresses, bounds, masks, or other indexing-only + # state. + value_inputs: tuple[Any, ...] = () + value_sinks: tuple[Any, ...] = () + indexing_inputs: tuple[Any, ...] = () + + +def _collect_fx_nodes(arg: Any) -> OrderedSet[torch.fx.Node]: + nodes: OrderedSet[torch.fx.Node] = OrderedSet() + + def add_node(node: torch.fx.Node) -> torch.fx.Node: + nodes.add(node) + return node + + map_arg(arg, add_node) + return nodes + + +def _collect_input_nodes(node: torch.fx.Node) -> OrderedSet[torch.fx.Node]: + inputs = OrderedSet(node.all_input_nodes) + if ( + node.op == "call_method" + and node.args + and isinstance(node.args[0], torch.fx.Node) + ): + inputs.discard(node.args[0]) + return inputs + + +class _ValueUseRules: + @staticmethod + def default_rule(*args: Any, **kwargs: Any) -> _ValueUseRule | None: + return None + + def load(self, name: str, index: sympy.Expr) -> _ValueUseRule: + return _ValueUseRule(indexing_inputs=(index,)) + + def load_seed(self, name: str, offset: int) -> _ValueUseRule: + return _ValueUseRule(indexing_inputs=(offset,)) + + def store( + self, + name: str, + index: sympy.Expr, + value: Any, + mode: Any = None, + ) -> _ValueUseRule: + return _ValueUseRule( + value_sinks=(value,), + indexing_inputs=(index,), + ) + + def store_reduction( + self, name: str, index: sympy.Expr, value: Any + ) -> _ValueUseRule: + return _ValueUseRule( + value_sinks=(value,), + indexing_inputs=(index,), + ) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: str, + value: Any, + ) -> _ValueUseRule: + return _ValueUseRule(value_sinks=(value,)) + + def partial_accumulate( + self, + name: str, + reduction_type: str, + value: Any, + extra_meta: dict[str, Any], + ) -> _ValueUseRule: + return _ValueUseRule(value_sinks=(value,)) + + def sort( + self, + dtypes: tuple[torch.dtype, ...], + values: tuple[Any, ...], + stable: bool, + descending: bool, + ) -> _ValueUseRule: + return _ValueUseRule(value_sinks=(values,)) + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn_or_values: Any, + values: tuple[Any, ...] | None = None, + ) -> _ValueUseRule: + if values is None: + values = combine_fn_or_values + return _ValueUseRule(value_sinks=(values,)) + + def bucketize( + self, + values: Any, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: Any, + indexing_dtype: torch.dtype, + right: bool, + sorter: tuple[str, sympy.Expr] | None = None, + sorter_indices: Any | None = None, + ) -> _ValueUseRule: + return _ValueUseRule( + value_inputs=(values,), + indexing_inputs=(boundaries, boundary_indices, sorter, sorter_indices), + ) + + def indirect_indexing( + self, x: Any, size: sympy.Expr, check: bool = True, wrap_neg: bool = True + ) -> _ValueUseRule: + return _ValueUseRule(indexing_inputs=(x, size)) + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> _ValueUseRule: + return _ValueUseRule(indexing_inputs=(expr, size)) + + def masked(self, mask: Any, body: Any, other: Any) -> _ValueUseRule: + return _ValueUseRule(value_inputs=(other,), indexing_inputs=(mask,)) + + def masked_subblock(self, mask: Any, other: Any) -> _ValueUseRule: + return _ValueUseRule(value_inputs=(other,), indexing_inputs=(mask,)) + + def set_indirect(self, new_var: Any) -> _ValueUseRule: + return _ValueUseRule(indexing_inputs=(new_var,)) + + def device_assert_async(self, cond: Any, msg: str) -> _ValueUseRule: + return _ValueUseRule(indexing_inputs=(cond,)) + + +class _ValueUseAnalysis: + def __init__(self, loop_body: LoopBody) -> None: + self.loop_body = loop_body + self.rules = _ValueUseRules() + self.root_graph = loop_body.root_block.graph + self.subblocks = getattr(loop_body, "subblocks", {}) + self.indirect_vars = getattr(loop_body, "indirect_vars", ()) + self.graphs = [ + self.root_graph, + *(block.graph for block in self.subblocks.values()), + ] + self.install_call_module_rules() + + self.value_reachable: OrderedSet[torch.fx.Node] = OrderedSet() + self.worklist: list[tuple[torch.fx.Graph, torch.fx.Node]] = [] + self.indirect_inputs: dict[sympy.Symbol, tuple[torch.fx.Graph, Any]] = {} + + def run(self) -> bool: + if not self.has_index_expr(): + return False + + self.seed_value_reachable_nodes() + return self.propagate_value_reachability() + + def has_index_expr(self) -> bool: + return any( + graph.find_nodes(op="call_method", target="index_expr", sort=False) + for graph in self.graphs + ) + + def install_call_module_rules(self) -> None: + for graph in self.graphs: + for node in graph.find_nodes(op="call_module", sort=False): + if not isinstance(node.target, str): + continue + if node.target in self.subblocks: + setattr(self.rules, node.target, self.rules.masked_subblock) + elif node.target.startswith("scan"): + setattr(self.rules, node.target, self.rules.scan) + elif node.target.startswith("set_indirect"): + setattr(self.rules, node.target, self.rules.set_indirect) + + def seed_value_reachable_nodes(self) -> None: + self._enqueue_graph_output(self.root_graph) + for graph in self.graphs: + for node in graph.nodes: + if node.op == "output": + continue + if ( + node.op == "call_module" + and isinstance(node.target, str) + and node.target.startswith("set_indirect") + ): + idx = int(node.target[len("set_indirect") :]) + self.indirect_inputs[self.indirect_vars[idx]] = (graph, node.args) + for sink_node in self.value_sink_nodes(node): + self.worklist.append((graph, sink_node)) + + def propagate_value_reachability(self) -> bool: + changed = False + while self.worklist: + graph, node = self.worklist.pop() + if node in self.value_reachable: + continue + self.value_reachable.add(node) + + if node.target == "index_expr": + node.target = "value_expr" + changed = True + + if ( + node.op == "call_module" + and isinstance(node.target, str) + and node.target in self.subblocks + ): + self._enqueue_graph_output(self.subblocks[node.target].graph) + + if node.op == "call_module" and node.target == "get_index": + index_name = node.args[0] + if not isinstance(index_name, str): + raise AssertionError(f"expected str index name, got {index_name!r}") + expr = self.loop_body.indexing_exprs[index_name] + if isinstance(expr, sympy.Expr): + for symbol in expr.free_symbols: + indirect_input = self.indirect_inputs.get(symbol) + if indirect_input is not None: + ig, ia = indirect_input + map_arg(ia, lambda n: self.worklist.append((ig, n))) + + for input_node in self.value_input_nodes(node): + self.worklist.append((graph, input_node)) + + return changed + + def rule_for_node(self, node: torch.fx.Node) -> _ValueUseRule | None: + if node.op == "call_method" and isinstance(node.target, str): + rule_fn = getattr(self.rules, node.target, self.rules.default_rule) + return rule_fn(*node.args[1:], **node.kwargs) + if node.op == "call_module" and isinstance(node.target, str): + rule_fn = getattr(self.rules, node.target, self.rules.default_rule) + return rule_fn(*node.args, **node.kwargs) + return None + + def value_input_nodes(self, node: torch.fx.Node) -> OrderedSet[torch.fx.Node]: + rule = self.rule_for_node(node) + if rule is None: + return _collect_input_nodes(node) + return _collect_fx_nodes(rule.value_inputs) | _collect_fx_nodes( + rule.value_sinks + ) + + def value_sink_nodes(self, node: torch.fx.Node) -> OrderedSet[torch.fx.Node]: + rule = self.rule_for_node(node) + return _collect_fx_nodes(rule.value_sinks) if rule else OrderedSet() + + def _enqueue_graph_output(self, graph: torch.fx.Graph) -> None: + output_nodes = graph.find_nodes(op="output", sort=False) + if len(output_nodes) != 1: + raise AssertionError( + f"expected exactly 1 output node, got {len(output_nodes)}" + ) + map_arg(output_nodes[0].args, lambda n: self.worklist.append((graph, n))) + + +def convert_index_expr_to_value_expr(loop_body: LoopBody) -> None: + """ + Rewrite ``index_expr`` nodes that participate in value computation to + ``value_expr``, so codegen can honor the requested dtype instead of + narrowing to the kernel's indexing dtype. + + Classification: walk backward from value sinks (store value, reduction, + output). Indexing inputs to ops such as ``load``, ``store``, + ``check_bounds``, and ``set_indirect`` do not receive value demand. Any + ``index_expr`` reachable from a value sink is converted in-place to + ``value_expr``. Indirect indexing is handled by following value-reachable + ``get_index`` expressions through any referenced ``indirect*`` symbols back + to the corresponding ``set_indirect*`` input. + + Mixed-use policy: if the same ``index_expr`` feeds both an indexing use and + a value use, rewrite it in-place to ``value_expr``. This is conservative and + correct because the indexing path may compute at a wider dtype than needed, + but the value path cannot lose precision. Cloning would preserve the + narrower indexing path, but the mixed-use case is rare and the simpler + in-place rewrite avoids extra CSE/register pressure. + """ + if _ValueUseAnalysis(loop_body).run(): + LoopBody.get_nodes.clear_cache(loop_body) + LoopBody.bounds.clear_cache(loop_body) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/output_code.py b/.venv/lib/python3.12/site-packages/torch/_inductor/output_code.py new file mode 100644 index 0000000000000000000000000000000000000000..78bde32d7dc438b9b5a9b36673c2409fcb520286 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/output_code.py @@ -0,0 +1,1349 @@ +""" +This provides an abstract class which parametrizes over an "output code" concept +for Inductor. Intuitively, this represents the compiled callable which Inductor +produces which you can call to get optimized code. However, this callable +has some other capabilities: + +- It is serializable, so you can save/load this product from disk without + having to do compilation again. + +- (When using remote cache) it is addressable, so you can save just a key + which you can use to load this product from remote cache later. + +This class is abstract because we have several different implementations of +serialized format: + +- Python wrapper (the default) + +- AOTInductor (this produces ABI stable binaries which work across PyTorch + versions) + +""" + +from __future__ import annotations + +import contextlib +import dataclasses +import logging +import os +from functools import partial +from typing import Any, cast, Protocol, TYPE_CHECKING, TypeAlias + +import torch +from torch._custom_class_base import CustomClassBase +from torch._dynamo.utils import counters, get_runtime_metrics_context +from torch._guards import compile_context, CompileContext +from torch._higher_order_ops.wrap import inductor_compiled_code +from torch._inductor.cudagraph_utils import ( + BoxedDeviceIndex, + cudagraph_trees_clone_live_user_visible_outputs, + CudagraphCachedInfo, + CudagraphMetadata, + get_input_storage_mutation_info, + get_input_storage_mutation_reason, + get_partition_cudagraph_metadata, + get_placeholder_info, + log_cudagraph_skip_and_bump_counter, +) +from torch._inductor.freezing_utils import has_frozen_params, is_frozen_param +from torch._inductor.utils import ( + _unstable_customized_partition_wrapper, + align_inputs_from_check_idxs, + BoxedBool, + CUDAGraphWrapperMetadata, + GraphPartitionMap, + InputType, + is_gpu, + output_node, + set_tracing_context_output_strides, +) +from torch.fx._graph_pickler import _node_metadata_key_filter_safe, _ops_filter_safe +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import is_in_torch_dispatch_mode + +from . import config +from .runtime.autotune_cache import AutotuneCacheBundler + + +if TYPE_CHECKING: + from collections import Counter + from collections.abc import Callable, Sequence + + from torch._inductor import metrics + from torch._inductor.graph import GraphLowering + from torch._library.fake_class_registry import FakeScriptObject + from torch.export.pt2_archive._package_weights import Weights + + from .compile_fx import _CompileFxKwargs + from .triton_bundler import TritonBundle + + # Boxed calling convention: a single list of inputs in, graph outputs out. + # Inductor's compiled-graph entry points and cudagraph wrappers all take + # exactly this shape, so we name it rather than repeating Callable[..., Any]. + _BoxedCallable: TypeAlias = Callable[[Sequence[InputType]], object] + + class CompiledFnRunner(Protocol): + """Runner emitted by the Python wrapper when graph_partition is on. + + codegen writes a Runner class (see codegen/wrapper.py) whose partitions + hold the per-partition callables and whose recursively_apply_fns rewrites + each partition in place (e.g. wrapping it in a cudagraph). + """ + + partitions: list[Callable[..., Any]] + + def recursively_apply_fns(self, fns: Sequence[Callable[..., Any]]) -> None: ... + + +log = logging.getLogger(__name__) + + +@dataclasses.dataclass +class OutputCode: + # TODO: Remove underscores here + + # None if the output is not remote cacheable + _fx_graph_cache_key: str | None = dataclasses.field(default=None, init=False) + _fx_graph_cache_debug_lines: list[str] | None = dataclasses.field( + default=None, init=False + ) + + # How long it took to compile this OutputCode, end to end + _time_taken_ns: int | None = dataclasses.field(default=None, init=False) + + def __call__(self, inputs: Sequence[Any]) -> Any: + raise NotImplementedError(type(self)) + + def prepare_for_serialization(self) -> None: + raise NotImplementedError(type(self)) + + def post_compile( + self, + example_inputs: Sequence[InputType], + constants: CompiledFxGraphConstants, + graph_kwargs: _CompileFxKwargs, + ) -> None: + raise NotImplementedError(type(self)) + + # TODO: Get rid of this + def set_triton_bundle(self, triton_bundle: Any) -> None: + raise NotImplementedError(type(self)) + + +_StrideExprStr: TypeAlias = str + + +# copy_ fails when trying to write to tensors with memory overlap, +# for expanded dimensions (a dimension which used to have size 1 -> ?) +# we can select one element from that dimension and write to it +# to achieve writing to all values of that dimension of the input tensor +def get_expanded_dims(t: torch.Tensor) -> list[int]: + if not isinstance(t, torch.Tensor): + # pyrefly: ignore [bad-return] + return None + return [i for i in range(t.ndim) if t.stride(i) == 0 and t.size(i) != 1] + + +def index_expanded_dims(t: torch.Tensor, expanded_dims: list[int]) -> torch.Tensor: + for expanded_dim in expanded_dims: + t = torch.ops.aten.slice(t, expanded_dim, 0, 1) + return t + + +# Bytewise copy of src's reachable strided extent into dst, starting from each +# tensor's data_ptr. Requires matching sizes/strides/dtype. Use when dst +# self-overlaps and a regular strided copy_ would be ambiguous: the overlap +# pattern reproduces in dst because the underlying bytes are copied verbatim. +def copy_strided_storage_(dst: torch.Tensor, src: torch.Tensor) -> None: + if dst.dtype != src.dtype: + raise AssertionError(f"dtype mismatch: dst={dst.dtype} src={src.dtype}") + if tuple(dst.size()) != tuple(src.size()): + raise AssertionError( + f"size mismatch: dst={tuple(dst.size())} src={tuple(src.size())}" + ) + if tuple(dst.stride()) != tuple(src.stride()): + raise AssertionError( + f"stride mismatch: dst={tuple(dst.stride())} src={tuple(src.stride())}" + ) + if dst.numel() == 0: + return + if not (all(st >= 0 for st in src.stride())): + raise AssertionError("copy_strided_storage_ requires non-negative strides") + elem = src.element_size() + nbytes = (sum((s - 1) * st for s, st in zip(src.size(), src.stride())) + 1) * elem + src_off = src.storage_offset() * elem + dst_off = dst.storage_offset() * elem + dst.untyped_storage()[dst_off : dst_off + nbytes].copy_( + src.untyped_storage()[src_off : src_off + nbytes] + ) + + +def maybe_handle_backward_generation( + compiled_graph: CompiledFxGraph, + boxed_forward_device_index: BoxedDeviceIndex | None, +) -> None: + if compiled_graph.current_callable is None: + raise AssertionError("compiled_graph.current_callable must not be None") + is_backward = compiled_graph.fx_kwargs["is_backward"] + + # See [Backward Generation Handling] + # if cudagraph'd the forward and set the device, we need to let the cudagraph manager + # know we are running the backward even if we will not run it in cudagraphs + if is_backward and config.triton.cudagraph_trees: + if boxed_forward_device_index is None: + raise AssertionError("boxed_forward_device_index must not be None") + if boxed_forward_device_index.value is None: + raise AssertionError("boxed_forward_device_index.value must not be None") + compiled_graph_callable = compiled_graph.current_callable + + manager = torch._inductor.cudagraph_trees.get_manager( + boxed_forward_device_index.value, create_if_none_exists=False + ) + # should already exist from forward + if manager is None: + raise AssertionError("CUDAGraph manager must not be None") + + def compiled_artifact(new_inputs: Sequence[InputType]) -> object: + manager.set_to_running_backward() # type: ignore[union-attr] + return compiled_graph_callable(new_inputs) + + compiled_graph.current_callable = compiled_artifact + + +def prepare_cudagraph_post_compile( + compiled_graph: CompiledFxGraph, + example_inputs: Sequence[InputType], + boxed_forward_device_index: BoxedDeviceIndex | None, +) -> None: + if not config.triton.cudagraph_trees: + # Force specialize all inputs so that CUDA graphs will work + for t in example_inputs: + if isinstance(t, torch.SymInt): + int(t) # guard + + is_inference = compiled_graph.fx_kwargs["is_inference"] + is_backward = compiled_graph.fx_kwargs["is_backward"] + if boxed_forward_device_index is not None and not is_inference and not is_backward: + boxed_forward_device_index.set(next(iter(compiled_graph.device_idxs))) + + +def cudagraph_post_compile( + example_inputs: Sequence[InputType], + compiled_graph: CompiledFxGraph, + cudagraphs: BoxedBool, + constants: dict[str, torch.Tensor | type], + boxed_forward_device_index: BoxedDeviceIndex | None, +) -> None: + """ + Checks for any reasons not to run cudagraphs and then + runs it on compiled_graph. + Mutates the `compiled_graph.current_callable` and `cudagraphs` + """ + from torch._inductor.compiler_bisector import CompilerBisector + + if compiled_graph.current_callable is None: + raise AssertionError("compiled_graph.current_callable must not be None") + if compiled_graph.cudagraph_info is None: + raise AssertionError("compiled_graph.cudagraph_info must not be None") + cached_info = compiled_graph.cudagraph_info + cudagraph_fail_reasons = cached_info.cudagraph_fail_reasons + is_inference = compiled_graph.fx_kwargs["is_inference"] + is_backward = compiled_graph.fx_kwargs["is_backward"] + + # Check if bisector wants to disable cudagraphs for this graph + if CompilerBisector.disable_subsystem("inductor", "cudagraphs"): + BoxedBool.disable(cudagraphs) + maybe_handle_backward_generation(compiled_graph, boxed_forward_device_index) + log_cudagraph_skip_and_bump_counter("skipping cudagraphs due to bisector") + return + + if not cudagraph_fail_reasons: + fx_kwargs = compiled_graph.fx_kwargs + static_input_idxs = fx_kwargs["static_input_idxs"] + + placeholders = cached_info.placeholders + stack_traces = cached_info.stack_traces + if stack_traces is None: + raise AssertionError( + "stack_traces should not be None in cudagraph_post_compile" + ) + user_visible_output_idxs = getattr(cached_info, "user_visible_output_idxs", ()) + + prepare_cudagraph_post_compile( + compiled_graph, example_inputs, boxed_forward_device_index + ) + + current_callable = compiled_graph.current_callable + if current_callable is None: + raise AssertionError("current_callable must not be None") + # Filter to only tensor constants (exclude opaque value type classes) + tensor_constants = { + k: v for k, v in constants.items() if isinstance(v, torch.Tensor) + } + + device_index = next(iter(compiled_graph.device_idxs)) + cudagraphify_kwargs = dict( + device_index=device_index, + stack_traces=stack_traces, + is_backward=is_backward, + is_inference=is_inference, + constants=tuple(tensor_constants.values()), + placeholders=placeholders, + mutated_input_idxs=tuple(compiled_graph.mutated_input_idxs), + kernel_free_cudagraph=compiled_graph.kernel_free_cudagraph, + user_visible_output_idxs=tuple(user_visible_output_idxs), + ) + + policy = config.cudagraph_policy + if policy is not None: + compiled_graph.current_callable = policy.cudagraphify( + current_callable, + example_inputs, + static_input_idxs or (), + **cudagraphify_kwargs, + ) + else: + from .compile_fx import cudagraphify + + compiled_graph.current_callable = cudagraphify( + current_callable, + static_input_idxs=static_input_idxs or (), + **cudagraphify_kwargs, + ) + + else: + BoxedBool.disable(cudagraphs) + maybe_handle_backward_generation(compiled_graph, boxed_forward_device_index) + + if any(is_gpu(device) for device in compiled_graph.device_types): + # prefer better disable_cudagraphs_reason bc stack trace + # TODO: migrate all disable reasons to stack trace, refactor + if compiled_graph.disabled_cudagraphs_reason: + log_cudagraph_skip_and_bump_counter( + compiled_graph.disabled_cudagraphs_reason + ) + else: + log_cudagraph_skip_and_bump_counter( + f"skipping cudagraphs due to {cudagraph_fail_reasons}" + ) + + +def cudagraph_partition_post_compile( + example_inputs: Sequence[InputType], + compiled_graph: CompiledFxGraph, + cudagraphs: BoxedBool, + constants: dict[str, torch.Tensor | type], + boxed_forward_device_index: BoxedDeviceIndex | None, +) -> None: + """ + Cudagraphify each partition function, which first prepares the necessary + metadata and then applies the cudagraphify function to each partition. + + Assuming all partition functions are cudagraphified and share the same order + as `compiled_graph.partition_maps`. See [Note: Graph Partition Map for CUDAGraph]. + """ + from torch._inductor.compiler_bisector import CompilerBisector + + if CompilerBisector.disable_subsystem("inductor", "cudagraphs"): + BoxedBool.disable(cudagraphs) + maybe_handle_backward_generation(compiled_graph, boxed_forward_device_index) + log_cudagraph_skip_and_bump_counter("skipping cudagraphs due to bisector") + return + + if compiled_graph.cudagraph_info is None: + raise AssertionError("compiled_graph.cudagraph_info must not be None") + cudagraph_fail_reasons = compiled_graph.cudagraph_info.cudagraph_fail_reasons + + if ( + cudagraph_fail_reasons + or compiled_graph.partition_maps is None + or len(compiled_graph.partition_maps) == 0 + ): + # cudagraphify is not called if there are no partitions + BoxedBool.disable(cudagraphs) + maybe_handle_backward_generation(compiled_graph, boxed_forward_device_index) + return + + if compiled_graph.current_callable is None: + raise AssertionError("compiled_graph.current_callable must not be None") + if compiled_graph.recursively_apply_fns is None: + raise AssertionError("compiled_graph.recursively_apply_fns must not be None") + is_inference = compiled_graph.fx_kwargs["is_inference"] + is_backward = compiled_graph.fx_kwargs["is_backward"] + static_input_idxs = OrderedSet(compiled_graph.fx_kwargs["static_input_idxs"] or ()) + mutated_input_idxs = compiled_graph.mutated_input_idxs + device_index = next(iter(compiled_graph.device_idxs)) + + # Filter to only tensor constants (exclude opaque value type classes) + tensor_constants = { + k: v for k, v in constants.items() if isinstance(v, torch.Tensor) + } + + if compiled_graph.cudagraph_info.stack_traces is None: + raise AssertionError( + "stack_traces should not be None in cudagraph_partition_post_compile" + ) + graph_metadata = CudagraphMetadata( + compiled_graph.cudagraph_info.placeholders, + static_input_idxs, + mutated_input_idxs, + compiled_graph.cudagraph_info.stack_traces, + OrderedSet( + getattr(compiled_graph.cudagraph_info, "user_visible_output_idxs", ()) + ), + tensor_constants, + ) + + prepare_cudagraph_post_compile( + compiled_graph, example_inputs, boxed_forward_device_index + ) + + from .compile_fx import cudagraphify + + # cudagraphify each partition function, assuming every graph partition function + # is cudagraphable. Non-cudagraphable ops (e.g., cpu ops) are inlined into + # `call` function and not included in partition functions. + cudagraphify_fns = [] + for partition_map in compiled_graph.partition_maps: + partition_metadata = get_partition_cudagraph_metadata( + partition_map, + graph_metadata, + ) + + cudagraphify_fn = partial( + cudagraphify, + static_input_idxs=tuple(partition_metadata.static_input_idxs), + device_index=device_index, + stack_traces=partition_metadata.stack_traces, + is_backward=is_backward, + is_inference=is_inference, + constants=tuple(partition_metadata.constants.values()), + placeholders=partition_metadata.placeholders, + mutated_input_idxs=tuple(partition_metadata.mutated_input_idxs), + kernel_free_cudagraph=compiled_graph.kernel_free_cudagraph, + user_visible_output_idxs=tuple(partition_metadata.user_visible_output_idxs), + ) + cudagraphify_fns.append(cudagraphify_fn) + + compiled_graph.recursively_apply_fns(cudagraphify_fns) + + +def maybe_realign_inputs( + ran_cudagraphs: BoxedBool, + compiled_graph: CompiledFxGraph, + inputs_to_check: Sequence[int], + mutated_inputs_idxs: OrderedSet[int], +) -> None: + """ + Realigns input strides from inputs_to_check if + we didn't end up running cudagraphs. Mutates + `compiled_graph.current_callable` if cudagraphs + was run. Otherwise, does nothing. + + Non-mutated inputs are handled by deferred alignment copies + in the generated code. Only mutated inputs need the wrapper + for writeback. + """ + if not ran_cudagraphs: + check_idxs = inputs_to_check + if compiled_graph._defers_input_alignment: + # Non-mutated inputs are handled by deferred alignment copies + # in the generated Python code. Only mutated inputs need the wrapper + # for writeback. Backends that don't emit deferred copies (cpp_wrapper, + # FXIR) need the full wrapper. + check_idxs = [i for i in inputs_to_check if i in mutated_inputs_idxs] + if check_idxs: + if compiled_graph.current_callable is None: + raise AssertionError("compiled_graph.current_callable must not be None") + new_callable = align_inputs_from_check_idxs( + compiled_graph.current_callable, + check_idxs, + mutated_inputs_idxs, + ) + if new_callable is not compiled_graph.current_callable: + # align_inputs_from_check_idxs preserves the boxed convention but + # its wrapper is typed with a list[InputType] parameter; the field + # uses the Sequence[InputType] boxed alias, so re-tag it here. + compiled_graph.current_callable = cast("_BoxedCallable", new_callable) + + +class CompiledFxGraphConstants: + """Wrapper class that unwraps constants from a compiled fx graph. This + version of the class only supports directly grabbing the saved constants off of + a CompiledFxGraph. + + With freezing, FxGraphCache doesn't store the constants of the input + GraphModule it gets from AOTAutograd. Instead, it saves just the **names** + of those constants, and grabs the constant values directly from the graph module + passed in at runtime. + + Thing is, we don't always *have* the graph module available at runtime, hence + the existence of this class and its CompiledFxGraphConstantsWithGm counterpart. + + To support freezing, FXGraphCache gets passed a CompiledFxGraphConstantsWithGm during + post compile. Otherwise, CompiledFxGraphConstants supports the basic case of loading + the value of constants directly off of the original saved object. + """ + + def unwrap(self, g: CompiledFxGraph) -> dict[str, torch.Tensor | type]: + if g.constants is None: + raise AssertionError("g.constants must not be None") + return {**g.constants, **g.opaque_value_type_classes} + + +class CompiledFxGraphConstantsWithGm(CompiledFxGraphConstants): + """ + This version of CompiledFxGraphConstants, instead of grabbing constants + directly saved on CompiledFxGraphs, will just grab their names. Then, it takes + a second GraphModule to grab the corresponding constant values out of. + + This is necessary for supporting freezing in FxGraphCache. + """ + + def __init__(self, gm: torch.fx.GraphModule) -> None: + self.gm = gm + + def unwrap(self, g: CompiledFxGraph) -> dict[str, torch.Tensor | type]: + frozen_params = { + name: getattr(self.gm, orig_name) + for name, orig_name in g.frozen_param_names.items() + } + constants = g.constants or {} + return {**constants, **frozen_params, **g.opaque_value_type_classes} + + +@dataclasses.dataclass +class CompiledFxGraph(OutputCode): + """ + Class holding a compiled FX graph. This is the object serialized on disk + to support FxGraph caching. + """ + + current_callable: _BoxedCallable | None + recursively_apply_fns: Callable[[Sequence[Callable[..., Any]]], None] | None + compiled_fn_runner: CompiledFnRunner | None + cache_key: str + source_code: str = dataclasses.field(repr=False) # Do not display source_code + runnable_graph_str: str = dataclasses.field(repr=False) # Do not display graph + inductor_post_grad_graph_str: str = dataclasses.field( + repr=False + ) # Do not display graph + cache_linemap: list[tuple[int, str]] | None + device_types: OrderedSet[str] + device_idxs: OrderedSet[int] + mutated_inputs: OrderedSet[str] + mutated_input_idxs: OrderedSet[int] + constants: dict[str, torch.Tensor] | None + frozen_param_names: dict[str, str] + torchbind_constants: dict[str, torch._C.ScriptObject | FakeScriptObject] + opaque_value_type_classes: dict[str, type] + output_strides: list[tuple[_StrideExprStr, ...] | None] | None + disabled_cudagraphs_reason: str | None + metrics_deltas: metrics.CachedMetricsDeltas + counter_deltas: Counter[str] + # This is a string representation of an expression we serialize + # with the object so the guards can be evaluated in a different + # context in order to verify the validity of serving a cached + # fx graph. The expression must be generated by: + # ShapeEnv.produce_guards_expression() + guards_expr: str | None + extern_libs_key: str | None + inductor_provenance_mapping_str: str | None + inductor_provenance_stack_traces_str: str | None + kernel_free_cudagraph: bool + + cudagraph_info: CudagraphCachedInfo | None + partition_maps: list[GraphPartitionMap] | None + compile_region_name: str | None + fx_kwargs: _CompileFxKwargs + inputs_to_check: Sequence[int] + + _boxed_call: bool | None = None + _triton_bundle: TritonBundle | None = None + _wrap_compiled_regions: bool = False + _defers_input_alignment: bool = False + _compile_context: CompileContext | None = dataclasses.field( + default=None, init=False, repr=False, compare=False + ) + # Metadata-stripped copy of the FX graph for fake tensor propagation. + # Running this graph under FakeTensorMode re-derives output shapes + # (including aliasing) from the input shapes. + _original_gm: torch.fx.GraphModule | None = None + _serialized_original_gm: bytes | None = None + + def __init__( + self, + current_callable: _BoxedCallable | None, + graph: GraphLowering, + gm: torch.fx.GraphModule, + output_strides: list[tuple[_StrideExprStr, ...] | None], + disabled_cudagraphs_reason: str | None, + metrics_deltas: metrics.CachedMetricsDeltas, + counter_deltas: Counter[str], + cudagraphs: BoxedBool, + example_inputs: Sequence[InputType], + static_input_idxs: Sequence[int], + compile_region_name: str | None, + fx_kwargs: _CompileFxKwargs, + inputs_to_check: Sequence[int], + runnable_graph_str: str, + inductor_post_grad_graph_str: str, + compiled_fn_runner: CompiledFnRunner | None = None, + inductor_provenance_mapping_str: str | None = None, + inductor_provenance_stack_traces_str: str | None = None, + ) -> None: + self.current_callable = current_callable + self.compiled_fn_runner = compiled_fn_runner + self.recursively_apply_fns = ( + compiled_fn_runner.recursively_apply_fns + if compiled_fn_runner is not None + else None + ) + self.cache_key = graph.cache_key + if graph.cache_path: + with open(graph.cache_path) as f: + self.source_code = f.read() + self.runnable_graph_str = runnable_graph_str + self.inductor_post_grad_graph_str = inductor_post_grad_graph_str + self.inductor_provenance_mapping_str = inductor_provenance_mapping_str + self.inductor_provenance_stack_traces_str = inductor_provenance_stack_traces_str + self.cache_linemap = graph.cache_linemap + # TODO - ordered set + self.device_types = OrderedSet(graph.device_types) + self.device_idxs = OrderedSet(graph.device_idxs) + self.mutated_inputs = OrderedSet(graph.mutated_inputs) + self.mutated_input_idxs = OrderedSet(graph.mutated_input_idxs) + + # We store the constant attributes in the cache entry and re-attach them + # to the module created in PyCodeCache.load_by_key_path. In the case that + # the graph has frozen parameters, we save the mapping from the attribute + # names in the GraphLowering to the original name of the attribute in the + # GraphModule. When we create the module from the cache entry, we then + # look up the constants from the current GraphModule. This scheme allows + # us to support caching with freezing. + if not has_frozen_params(gm): + self.constants = graph.constants + self.frozen_param_names = {} + else: + self.constants = {} + self.frozen_param_names = {} + for k, v in graph.constants.items(): + if is_frozen_param(v): + self.frozen_param_names[k] = graph.allocated_constant_name[k] + else: + self.constants[k] = v + + self.torchbind_constants = graph.torchbind_constants + self.opaque_value_type_classes = graph.opaque_value_type_classes + self.output_strides = output_strides + self.disabled_cudagraphs_reason = disabled_cudagraphs_reason + self.kernel_free_cudagraph = graph.kernel_free_cudagraph + self.metrics_deltas = metrics_deltas + self.counter_deltas = counter_deltas + self.guards_expr = None + self.extern_libs_key = None + self.cudagraph_info = None + self.partition_maps = graph.partition_maps + self._defers_input_alignment = getattr(graph, "_defers_input_alignment", False) + storage_mutation_info = get_input_storage_mutation_info(gm) + self.fx_kwargs = {} + self.inputs_to_check = () + + cudagraph_info = None + if cudagraphs: + # check cudagraph disabling reasons from inductor lowering + if self.disabled_cudagraphs_reason: + if any(is_gpu(device) for device in self.device_types): + log_cudagraph_skip_and_bump_counter( + f"skipping cudagraphs due to {self.disabled_cudagraphs_reason}" + ) + else: + counters["inductor"]["cudagraph_skips"] += 1 + BoxedBool.disable(cudagraphs) + else: + if not config.triton.cudagraph_support_input_mutation: + # Skip supports for cudagraph-managed tensors + from torch._inductor.cudagraph_utils import ( + check_for_mutation_ignore_cuda_graph_managed_tensor, + ) + + has_mutation_str = ( + check_for_mutation_ignore_cuda_graph_managed_tensor( + gm, + self.mutated_inputs, + self.mutated_input_idxs, + static_input_idxs, + ) + ) + has_mutation = has_mutation_str is not None + + if has_mutation: + self.disabled_cudagraphs_reason = has_mutation_str + else: + # Check mutation later to support cudagraph-managed tensors + has_mutation = None + + storage_mutation_reason = get_input_storage_mutation_reason( + storage_mutation_info, + ) + if storage_mutation_reason is not None: + self.disabled_cudagraphs_reason = storage_mutation_reason + + cudagraph_tests = [ + (storage_mutation_reason is None, "input storage mutation"), + (not has_mutation, "mutated inputs"), + ( + not config.force_disable_cudagraph_TESTING_ONLY, + "force_disable_cudagraph_TESTING_ONLY", + ), + ( + all( + isinstance( + t, + ( + torch.Tensor, + torch.SymInt, + torch.Generator, + CustomClassBase, + ), + ) + for t in example_inputs + ), + "non-Tensor inputs", + ), + ] + output = output_node(gm) + # output args are tuple of first argument + if len(output.args) != 1: + raise AssertionError( + f"Expected output.args to have length 1, got {len(output.args)}" + ) + # Use stack traces captured on the output node before + # post-grad passes, which may strip stack_trace from + # individual arg nodes. + stack_traces = output.meta.get("output_stack_traces") or [ + (arg.stack_trace if isinstance(arg, torch.fx.node.Node) else None) + for arg in output.args[0] # type: ignore[union-attr] + ] + user_visible_output_idxs = ( + output.meta.get("user_visible_output_idxs", ()) + if cudagraph_trees_clone_live_user_visible_outputs() + else () + ) + cudagraph_fail_reasons = [s for b, s in cudagraph_tests if not b] + placeholders = tuple(get_placeholder_info(gm.graph)) + cudagraph_info = CudagraphCachedInfo( + placeholders, + stack_traces, + tuple(user_visible_output_idxs), + cudagraph_fail_reasons, + ) + + self.cudagraph_info = cudagraph_info + self.compile_region_name = compile_region_name + self.inputs_to_check = inputs_to_check + self.fx_kwargs = fx_kwargs + self._set_compile_context_for_autotune_cache() + + # aot autograd needs to know to pass in inputs as a list + self._boxed_call = True + + # Store whether to wrap compiled regions in inductor_compiled_code HOP + # This is set at compile time to avoid runtime overhead + self._wrap_compiled_regions = config.wrap_inductor_compiled_regions + + if self._wrap_compiled_regions: + # Store a metadata-stripped copy of the FX graph. Running this + # under FakeTensorMode re-derives output shapes and aliasing + # from the input fake tensors. + import copy + + gm_copy = copy.deepcopy(gm) + for node in gm_copy.graph.nodes: + node.meta.clear() + self._original_gm = gm_copy + + def __del__(self) -> None: + if self.compiled_fn_runner is not None: + # For torch._inductor.config.graph_partition = True, + # self.compiled_fn_runner.partitions hold cudagraphified functions + # which prevents deallocation. When CompiledFxGraph is deleted, + # self.compiled_fn_runner will not be called in the future so we + # should also delete these partitions. + del self.compiled_fn_runner.partitions + + def _set_compile_context_for_autotune_cache(self) -> None: + compile_context_for_autotune_cache = CompileContext.try_get() + self._compile_context = ( + compile_context_for_autotune_cache + if AutotuneCacheBundler.has_active_compile( + compile_context_for_autotune_cache + ) + else None + ) + + def __call__(self, inputs: Sequence[Any]) -> Any: + if self.current_callable is None: + raise AssertionError("self.current_callable must not be None") + + if ( + torch._inductor.debug.RECORD_GRAPH_EXECUTION + and torch._inductor.debug.GRAPH_EXECUTION_ORDER is not None + ): + graph_id = self.fx_kwargs.get("graph_id") + compile_id = ( + torch._inductor.debug.GRAPH_COMPILE_IDS.get(graph_id) + if graph_id is not None + and torch._inductor.debug.GRAPH_COMPILE_IDS is not None + else None + ) + torch._inductor.debug.GRAPH_EXECUTION_ORDER.append( + { + "compile_id": compile_id, + } + ) + compile_context_for_autotune_cache = self._compile_context + has_active_autotune_cache_bundler = AutotuneCacheBundler.has_active_compile( + compile_context_for_autotune_cache + ) + autotune_cache_context = ( + compile_context(compile_context_for_autotune_cache) + if has_active_autotune_cache_bundler + else contextlib.nullcontext() + ) + # Autotune cache writes happen during the first call. End the bundler + # while its saved compile context is restored, then clear the saved + # context after leaving the compile_context manager. + try: + with autotune_cache_context: + try: + # Checking the profiler directly is faster than nullcontext + if torch.autograd.profiler._is_profiler_enabled: + with torch._C._profiler._RecordFunctionFast( + f"## Call CompiledFxGraph {self._fx_graph_cache_key} ##", + keyword_values={"scope": "user_scope"}, + ): + return self.current_callable(inputs) + else: + return self.current_callable(inputs) + finally: + get_runtime_metrics_context().finish() + if has_active_autotune_cache_bundler: + AutotuneCacheBundler.end_compile() + finally: + if ( + has_active_autotune_cache_bundler + and not AutotuneCacheBundler.has_active_compile( + compile_context_for_autotune_cache + ) + ): + self._compile_context = None + + def post_compile( + self, + example_inputs: Sequence[InputType], + constants: CompiledFxGraphConstants, + graph_kwargs: _CompileFxKwargs, + ) -> None: + """ + Run a set of post processing steps after loading from the cache. These involve: + - Setting the tracing context output strides + - Running cudagraphs if enabled + - Realigning inputs + + This runs whether or not we have a cache hit, and always runs directly after we get a CompiledFxGraph. + The results of this function are *not* saved in the cache itself. + """ + if config.graph_partition and _unstable_customized_partition_wrapper.wrapper: + # Mechanically apply user-specified cudagraph wrappers without modification + if self.recursively_apply_fns is None: + raise AssertionError("self.recursively_apply_fns must not be None") + if self.compiled_fn_runner is None: + raise AssertionError("self.compiled_fn_runner must not be None") + num_partitions = len(self.compiled_fn_runner.partitions) + wrapper_metadatas = [ + CUDAGraphWrapperMetadata(num_partitions, i) + for i in range(num_partitions) + ] + customized_wrapper = _unstable_customized_partition_wrapper.wrapper + customized_wrappers_with_metadata = [ + lambda f, m=metadata: customized_wrapper(f, m) + for metadata in wrapper_metadatas + ] + self.recursively_apply_fns(customized_wrappers_with_metadata) + return + + set_tracing_context_output_strides(example_inputs, self) + if graph_kwargs["cudagraphs"] is None: + raise AssertionError("graph_kwargs['cudagraphs'] must not be None") + if graph_kwargs["is_backward"] is None: + raise AssertionError("graph_kwargs['is_backward'] must not be None") + is_backward = graph_kwargs["is_backward"] + cudagraphs: BoxedBool = graph_kwargs["cudagraphs"] + + # When a CUDAGraphPolicy is set and it says not to wrap this + # inner CompiledFxGraph (e.g. because wrapping happens at the + # outer level via policy.wrap_output), disable cudagraphs for + # this graph so the rest of post_compile (input realignment, + # _wrap_compiled_regions) still runs normally. + policy = config.cudagraph_policy + if policy is not None and not policy.should_wrap(self): + counters["inductor"]["cudagraph_skips"] += 1 + BoxedBool.disable(cudagraphs) + + if cudagraphs: + # It's possible that cudagraphs is enabled, but was disabled + # during a previous compilation we're loading from the cache. + # If so, we need to disable it on this new process too. + if self.disabled_cudagraphs_reason: + if any(is_gpu(device) for device in self.device_types): + log_cudagraph_skip_and_bump_counter( + f"skipping cudagraphs due to {self.disabled_cudagraphs_reason}" + ) + else: + counters["inductor"]["cudagraph_skips"] += 1 + BoxedBool.disable(cudagraphs) + else: + if is_backward: + if "boxed_forward_device_index" not in graph_kwargs: + raise AssertionError( + "Expected 'boxed_forward_device_index' in graph_kwargs" + ) + boxed_forward_device_index = graph_kwargs[ + "boxed_forward_device_index" + ] + else: + # On the forward we don't know whether or not + # boxed_forward_device_index is set yet + boxed_forward_device_index = graph_kwargs.get( + "boxed_forward_device_index", None + ) + + if config.graph_partition and policy is None: + # With graph_partition=True, we skip some cudagraph checks + # if it's supported with partition, so we use + # cudagraph_partition_post_compile. When a CUDAGraphPolicy + # is active, we use cudagraph_post_compile instead so the + # policy controls wrapping via policy.cudagraphify(). + cudagraph_partition_post_compile( + example_inputs, + self, + cudagraphs, + constants.unwrap(self), + boxed_forward_device_index, + ) + else: + cudagraph_post_compile( + example_inputs, + self, + cudagraphs, + constants.unwrap(self), + boxed_forward_device_index, + ) + inputs_to_check = self.inputs_to_check + # cudagraphs could have been disabled from the earlier conditions + # so we still need to realign inputs if that happens + maybe_realign_inputs( + cudagraphs, + self, + inputs_to_check, + self.mutated_input_idxs, + ) + + if self._original_gm is None and self._serialized_original_gm is not None: + from torch._subclasses import FakeTensorMode + from torch.fx._graph_pickler import GraphPickler + from torch.fx.experimental.symbolic_shapes import ShapeEnv + + fake_mode = FakeTensorMode( + allow_non_fake_inputs=True, + shape_env=ShapeEnv(), + ) + original_gm = cast( + torch.fx.GraphModule, + GraphPickler.loads(self._serialized_original_gm, fake_mode), + ) + original_gm.recompile() + self._original_gm = original_gm + self._serialized_original_gm = None + + # Apply inductor_compiled_code HOP wrapper if configured + # This is done in post_compile to ensure it works with cached artifacts + if self._wrap_compiled_regions and self.current_callable is not None: + from torch._higher_order_ops.wrap import InductorCompiledCallable + + original_callable = self.current_callable + + inductor_callable = InductorCompiledCallable( + original_callable, + self._original_gm, + compile_region_name=self.compile_region_name, + ) + + def wrapped_callable(inputs): + if is_in_torch_dispatch_mode(): + kwargs = ( + {"name": self.compile_region_name} + if self.compile_region_name is not None + else {} + ) + return inductor_compiled_code(inductor_callable, inputs, **kwargs) + else: + return original_callable(inputs) + + self.current_callable = wrapped_callable + + def set_triton_bundle(self, triton_bundle: Any) -> None: + self._triton_bundle = triton_bundle + + def prepare_for_serialization(self) -> None: + # We can't really serialize callables that may be C++/Triton/etc., + # so we serialize their PyCodeCache disk cache location instead. + # TODO: This could be better if we're ever able to serialize compiled + # models to disk. + self._compile_context = None + self.current_callable = None + self.recursively_apply_fns = None + self.compiled_fn_runner = None + if self._original_gm is not None: + from torch.fx._graph_pickler import GraphPickler, Options + + self._serialized_original_gm = GraphPickler.dumps( + self._original_gm, Options(ops_filter=None) + ) + self._original_gm = None + # Note: _serialized_fx_graph is already in serializable form (SerializedGraphModule) + # so it doesn't need to be cleared + + def write_to_disk(self) -> str: + from torch._dynamo.utils import counters + from torch._inductor.codecache import get_path, write_atomic + + # See _save_graph(); we don't store the callable in the cache entry so + # recreate it here from the PyCodeCache disk cache. + artifact_path = get_path(self.cache_key, "py")[2] + code = self.source_code + if not os.path.exists(artifact_path): + counters["inductor"]["fxgraph_lookup_write_file"] += 1 + write_atomic(artifact_path, code, make_dirs=True) + return artifact_path + + def after_deserialization(self, constants: CompiledFxGraphConstants) -> str: + from torch._dynamo.utils import dynamo_timed + from torch._inductor.codecache import PyCodeCache + + artifact_path = self.write_to_disk() + + try: + with dynamo_timed( + "PyCodeCache.load_by_key_path", + log_pt2_compile_event=True, + ): + code_cache = PyCodeCache.load_by_key_path( + self.cache_key, + artifact_path, + self.cache_linemap, + constants.unwrap(self), + ) + self.current_callable = code_cache.call + self.recursively_apply_fns = getattr( + code_cache, "recursively_apply_fns", None + ) + self.compiled_fn_runner = getattr(code_cache, "runner", None) + except OSError: + log.error("Failed to load artifact: %s", artifact_path) + raise + + return artifact_path + + +@dataclasses.dataclass +class CompiledAOTI(OutputCode): + """ + Class holding an AOTInductor compiled so. + """ + + filename: str | list[str | Weights] | torch.fx.GraphModule + device_type: str + current_callable: Callable[..., Any] | None = None + _cached_files: dict[str, bytes] = dataclasses.field(default_factory=dict) + + def __post_init__(self): + if not config.aot_inductor.link_libtorch: + return + + if ( + torch._inductor.cpp_builder._IS_MACOS + or torch._inductor.cpp_builder._IS_WINDOWS + ): + return + + if config.aot_inductor.cross_target_platform == "windows": + return + + if config.aot_inductor.package_cpp_only: + return + + if not config.enable_autograd_for_aot: + return + + if isinstance(self.filename, list): + current_callable = next( + fn for fn in self.filename if isinstance(fn, str) and fn.endswith(".so") + ) + else: + current_callable = self.filename + + if isinstance(current_callable, torch.fx.GraphModule): + # pyrefly: ignore [bad-assignment] + self.current_callable = current_callable + return + + if self.device_type.startswith("cuda"): + current_callable = ( + torch._C._aoti.AOTIModelContainerRunnerCuda( # type: ignore[call-arg] + current_callable, + 1, + self.device_type, + "", + True, + ).run # type: ignore[attr-defined] + ) # type: ignore[attr-defined] + elif self.device_type.startswith("xpu"): + current_callable = ( + torch._C._aoti.AOTIModelContainerRunnerXpu( # type: ignore[call-arg] + current_callable, + 1, + self.device_type, + "", + ).run # type: ignore[attr-defined] + ) # type: ignore[attr-defined] + elif self.device_type == "cpu": + current_callable = ( + torch._C._aoti.AOTIModelContainerRunnerCpu( # type: ignore[call-arg] + current_callable, 1 + ).run # type: ignore[attr-defined] + ) # type: ignore[attr-defined] + else: + raise RuntimeError(f"unsupported device type {self.device_type}") + self.current_callable = current_callable + self._boxed_call = True + for file in self._cached_files: + if not os.path.exists(file): + with open(file, "wb") as f: + f.write(self._cached_files[file]) + + def __call__(self, inputs: Sequence[Any]) -> Any: + if self.current_callable is None: + raise RuntimeError("AOTInductor compiled so is not loaded") + return self.current_callable(inputs) + + def prepare_for_serialization(self) -> None: + self.current_callable = None + self._cached_files = {} + filenames: list[str] = [] + if isinstance(self.filename, list): + filenames = self.filename # type: ignore[assignment] + elif isinstance(self.filename, str): + filenames = [self.filename] + for name in filenames: + with open(name, "rb") as f: + self._cached_files[name] = f.read() + + def __getstate__(self): + state = self.__dict__.copy() + state["current_callable"] = None + return state + + def post_compile( + self, + example_inputs: Sequence[InputType], + constants: CompiledFxGraphConstants, + graph_kwargs: _CompileFxKwargs, + ) -> None: + if self.current_callable is None: + self.__post_init__() + + def set_triton_bundle(self, triton_bundle: Any) -> None: + pass + + +@dataclasses.dataclass +class MockFXGraphCacheOutput(OutputCode): + gm: Any = None + + def __post_init__(self) -> None: + self._boxed_call = True + + def post_compile( + self, + example_inputs: Sequence[InputType], + constants: CompiledFxGraphConstants, + graph_kwargs: _CompileFxKwargs, + ) -> None: + pass + + def __call__(self, inputs: Sequence[Any]) -> Any: + return self.gm(inputs) + + def set_triton_bundle(self, triton_bundle: Any) -> None: + pass + + +@dataclasses.dataclass +class RegionalOutputCode(OutputCode): + """ + OutputCode for regional inductor compilation results. + + Regional inductor returns a torch.fx.GraphModule that contains both + compiled regions (via standalone_compile) and eager regions. This needs + special serialization using GraphPickler instead of standard pickle. + + The serialization strategy stores the GraphModule as bytes using + GraphPickler.dumps(), which handles FakeTensors, AOTCompiledArtifacts, + and other special objects that standard pickle cannot handle. + """ + + # The serialized graph module as bytes (using GraphPickler) + _serialized_graph_module: bytes | None = None + + # The actual graph module (cleared during serialization) + _graph_module: torch.nn.Module | None = None + + # Optional filter for ops during serialization + _ops_filter: Callable[[str], bool] | None = None + + def __init__( + self, + graph_module: torch.fx.GraphModule, + ops_filter: Callable[[str], bool] = _ops_filter_safe, + node_metadata_key_filter: Callable[[str], bool] | None = ( + _node_metadata_key_filter_safe + ), + ): + """ + Args: + graph_module: The torch.fx.GraphModule returned by regional_inductor + ops_filter: Optional filter function for op names during serialization. + If provided, only ops whose name passes the filter will be serialized. + """ + super().__init__() + self._graph_module = graph_module + self._serialized_graph_module = None + self._serialized_wrappers = [] + self._boxed_call = True + _, module = self._unwrap_graph_module() + self._inner_boxed_call = isinstance( + module.graph._codegen, torch.fx.graph._BoxedCodeGen + ) + self._ops_filter = ops_filter + self._node_metadata_key_filter = node_metadata_key_filter + + def __call__(self, inputs: list[Any]) -> Any: + """ + Execute the regional compiled graph. + + Args: + inputs: A mutable list of inputs. Must be a list (not an arbitrary + Sequence) because the boxed calling convention allows the callee + to mutably clear the list when inputs become dead, enabling early + memory deallocation. + """ + if self._graph_module is None: + raise RuntimeError( + "RegionalOutputCode has no graph module loaded. " + "Did you forget to call post_compile()?" + ) + + if self._inner_boxed_call: + return self._graph_module(inputs) + return self._graph_module(*inputs) + + @property + def graph(self): + _, module = self._unwrap_graph_module() + return module.graph + + def _unwrap_graph_module( + self, + ) -> tuple[list[tuple[Callable, dict[str, Any]]], torch.fx.GraphModule]: + module = self._graph_module + serialized_wrappers = [] + if isinstance(module, torch._dynamo.OptimizedModule): + dynamo_ctx = module.dynamo_ctx + if not isinstance(dynamo_ctx, torch._dynamo.eval_frame.DisableContext): + raise AssertionError(f"Expected DisableContext, got {type(dynamo_ctx)}") + serialized_wrappers.append( + ( + torch._dynamo.disable, + {"reason": dynamo_ctx.msg, "wrapping": dynamo_ctx.wrapping}, + ) + ) + module = module._orig_mod + if not isinstance(module, torch.fx.GraphModule): + raise AssertionError(f"Expected torch.fx.GraphModule, got {type(module)}") + return serialized_wrappers, module + + def post_compile( + self, + example_inputs: Sequence[InputType], + constants: CompiledFxGraphConstants, + graph_kwargs: _CompileFxKwargs, + ) -> None: + """ + Post-compile processing for regional inductor. + + This deserializes the GraphModule from bytes using GraphPickler, + extracting the fake_mode from example_inputs. + """ + if self._graph_module is not None: + return + if self._serialized_graph_module is None: + raise AssertionError("self._serialized_graph_module must not be None") + # Get fake mode from example inputs + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode(example_inputs) + if fake_mode is None: + raise RuntimeError( + "Could not detect fake mode from example inputs. " + "Regional inductor requires fake mode for deserialization." + ) + + # Deserialize the graph module + from torch.fx._graph_pickler import GraphPickler + + gm = GraphPickler.loads(self._serialized_graph_module, fake_mode) + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"Expected torch.fx.GraphModule, got {type(gm)}") + gm.recompile() + for fn, kwargs in reversed(self._serialized_wrappers): + gm = fn(gm, **kwargs) + self._graph_module = gm + + def set_triton_bundle(self, triton_bundle: Any) -> None: + """Regional inductor doesn't use triton bundles directly.""" + + def prepare_for_serialization(self) -> None: + """ + Prepare for serialization by converting the GraphModule to bytes. + + This uses GraphPickler to serialize the graph module since it contains + special objects like FakeTensors and AOTCompiledArtifacts that need + custom pickling. + """ + if self._graph_module is not None: + from torch.fx._graph_pickler import GraphPickler, Options + + self._serialized_graph_module = None + self._serialized_wrappers, graph_module = self._unwrap_graph_module() + + self._serialized_graph_module = GraphPickler.dumps( + graph_module, + options=Options( + ops_filter=self._ops_filter, + node_metadata_key_filter=self._node_metadata_key_filter, + ), + ) + # Clear the graph module to avoid pickling it with standard pickle + self._graph_module = None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/package/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/package/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..15587401b723581b57f94fdcddbcbc8255f73bfe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/package/__init__.py @@ -0,0 +1 @@ +from .package import AOTICompiledModel, load_package, package_aoti diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/package/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/package/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29c9eecc1ee350fc0f6383b95bda84632a38edc7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/package/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/package/__pycache__/build_package.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/package/__pycache__/build_package.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aebf5a35f6ceb01128f046acedaa3dcf08d8426d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/package/__pycache__/build_package.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/package/__pycache__/package.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/package/__pycache__/package.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40a3eefb33115641aea4b4fef55e482c23569fdc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/package/__pycache__/package.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/package/build_package.py b/.venv/lib/python3.12/site-packages/torch/_inductor/package/build_package.py new file mode 100644 index 0000000000000000000000000000000000000000..9205b9ced254275018472108485173eba9479f11 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/package/build_package.py @@ -0,0 +1,15 @@ +build_package_contents = """ +import os +from pathlib import Path + +from torch._inductor.package.package import compile_so + +curr_dir = Path(__file__).parent +aoti_files = [ + os.path.join(root, file) + for root, dirs, files in os.walk(curr_dir) + for file in files +] + +output_so = compile_so(curr_dir, aoti_files, curr_dir) +""" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/package/package.py b/.venv/lib/python3.12/site-packages/torch/_inductor/package/package.py new file mode 100644 index 0000000000000000000000000000000000000000..4bef5fc742b1ab471bd7f0908133494e7a212bfe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/package/package.py @@ -0,0 +1,141 @@ +import io +import json +import logging +import os +import tempfile +from typing import IO + +import torch +from torch._inductor import config +from torch._inductor.cpp_builder import BuildOptionsBase, CppBuilder +from torch.export.pt2_archive._package import ( + AOTI_FILES, + AOTICompiledModel, + load_pt2, + package_pt2, +) +from torch.types import FileLike + + +log = logging.getLogger(__name__) +AOTI_PACKAGE_DEVICE_ERROR = "Cannot load AOTInductor package for device" + + +def compile_so(aoti_dir: str, aoti_files: list[str], so_path: str) -> str: + def get_aoti_file_with_suffix(suffix: str) -> str: + for file in aoti_files: + if file.endswith(suffix): + return file + raise RuntimeError(f"Unable to find file with suffix {suffix}") + + # Compile all the files into a .so + cpp_file = os.path.join(aoti_dir, get_aoti_file_with_suffix(".cpp")) + consts_o = os.path.join(aoti_dir, get_aoti_file_with_suffix(".o")) + + file_name = os.path.splitext(cpp_file)[0] + + # Parse compile flags and build the .o file + with open(file_name + "_compile_flags.json") as f: + compile_flags = json.load(f) + + compile_options = BuildOptionsBase( + **compile_flags, use_relative_path=config.is_fbcode() + ) + object_builder = CppBuilder( + name=file_name, + sources=cpp_file, + BuildOption=compile_options, + ) + output_o = object_builder.get_target_file_path() + object_builder.build() + + # Parse linker flags and build the .so file + with open(file_name + "_linker_flags.json") as f: + linker_flags = json.load(f) + + linker_options = BuildOptionsBase( + **linker_flags, use_relative_path=config.is_fbcode() + ) + so_builder = CppBuilder( + name=os.path.split(so_path)[-1], + sources=[output_o, consts_o], + BuildOption=linker_options, + output_dir=so_path, + ) + output_so = so_builder.get_target_file_path() + so_builder.build() + + # mmapped weights + serialized_weights_filename = file_name + "_serialized_weights.bin" + if serialized_weights_filename in aoti_files: + with open(serialized_weights_filename, "rb") as f_weights: + serialized_weights = f_weights.read() + + with open(output_so, "a+b") as f_so: + so_size = f_so.tell() + # Page align the weights + f_so.write(b" " * (16384 - so_size % 16384)) + f_so.write(serialized_weights) + + return output_so + + +def package_aoti( + archive_file: FileLike, + aoti_files: AOTI_FILES, +) -> FileLike: + """ + Saves the AOTInductor generated files to the PT2Archive format. + + Args: + archive_file: The file name to save the package to. + aoti_files: This can either be a singular path to a directory containing + the AOTInductor files, or a dictionary mapping the model name to the + path to its AOTInductor generated files. + """ + + return package_pt2( + archive_file, + aoti_files=aoti_files, + ) + + +def load_package( + path: FileLike, + model_name: str = "model", + run_single_threaded: bool = False, + num_runners: int = 1, + device_index: int = -1, +) -> AOTICompiledModel: + try: + pt2_contents = load_pt2( + path, + run_single_threaded=run_single_threaded, + num_runners=num_runners, + device_index=device_index, + ) + if model_name not in pt2_contents.aoti_runners: + raise RuntimeError(f"Model {model_name} not found in package") + return pt2_contents.aoti_runners[model_name] + except RuntimeError as e: + if AOTI_PACKAGE_DEVICE_ERROR in str(e): + raise + log.warning("Loading outdated pt2 file. Please regenerate your package.") + + if isinstance(path, (io.IOBase, IO)): + with tempfile.NamedTemporaryFile(suffix=".pt2") as f: + # TODO(angelayi): We shouldn't need to do this -- miniz should + # handle reading the buffer. This is just a temporary workaround + path.seek(0) + f.write(path.read()) + log.debug("Writing buffer to tmp file located at %s.", f.name) + loader = torch._C._aoti.AOTIModelPackageLoader( + f.name, model_name, run_single_threaded, num_runners, device_index + ) + return AOTICompiledModel(loader) + + path = os.fspath(path) # AOTIModelPackageLoader expects (str, str) + loader = torch._C._aoti.AOTIModelPackageLoader( + path, model_name, run_single_threaded, num_runners, device_index + ) + return AOTICompiledModel(loader) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/pattern_matcher.py b/.venv/lib/python3.12/site-packages/torch/_inductor/pattern_matcher.py new file mode 100644 index 0000000000000000000000000000000000000000..d30320cbc4409b100e82022da659d9e363fef74b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/pattern_matcher.py @@ -0,0 +1,3087 @@ +""" +# Inductor Pattern Matcher + +The pattern matcher enables search/replace within an FX graph. + +The main entrypoint to the pattern matcher is register_replacement(). Given a +search function and a replacement function this will register a replacement with +a pass (such as torch._inductor.fx_passes.joint_graph.patterns). + +Internally the pattern matcher represents patterns as a graph (a DAG). Creating +new patterns manually as a graph is cumbersome and error-prone so the standard +way to create patterns (using register_replacement()) is to provide a search +function and a replacement function which is traced and converted into a graph. + +Because the search functions are built somewhat generic (they tend to ignore +tensor sizes, for example) register_replacement() allows you to specify an +`extra_check` function which performs additional checks to verify that the +matched pattern fully matches before returning it. + +## Precompiled Patterns + +New patterns are added using register_replacement(). Patterns added in this way +can have a compile-time overhead because they need to be traced before +use. Patterns can be precompiled and added using gen_register_replacement() +instead. To do this you call gen_register_replacement() instead of +register_replacement(). The arguments are the same except for an additional +unique name which is used as a lookup key. + +## Internals + +The match DAG is represented by a graph of `PatternExpr` nodes. Each PatternExpr +implements a `_match` method which returns either a `Match` object for a +successful match or a `FailedMatch` object for a failure to match. +""" + +from __future__ import annotations + +import contextlib +import dataclasses +import functools +import importlib +import inspect +import itertools +import logging +import math +import operator +import os +import re +import textwrap +import typing +from abc import ABC, abstractmethod +from collections import defaultdict +from collections.abc import Callable, Collection, Generator, Iterable, Mapping, Sequence +from pathlib import Path +from typing import Any, NoReturn, Protocol, TypeVar +from typing_extensions import Self, TypeIs + +import torch +import torch._guards +import torch.fx +import torch.utils._pytree as pytree +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.utils import counters +from torch._prims_common import is_integer_dtype +from torch._subclasses.fake_tensor import ( + is_fake_tensor, + maybe_get_fake_constant, + unset_fake_temporarily, +) +from torch.fx.experimental.proxy_tensor import make_fx +from torch.fx.experimental.symbolic_shapes import guard_or_false, statically_known_true +from torch.fx.graph_module import _get_attr +from torch.fx.immutable_collections import immutable_dict, immutable_list +from torch.fx.passes.graph_transform_observer import GraphTransformObserver +from torch.fx.traceback import preserve_node_meta +from torch.utils._ordered_set import OrderedSet + +from .._functorch import config as functorch_config +from .._functorch.aot_autograd import aot_function, make_boxed_func +from .._functorch.partitioners import default_partition +from .._subclasses import FakeTensor, FakeTensorMode +from ..fx import Transformer +from . import config +from .decomposition import select_decomp_table +from .lowering import fallback_node_due_to_unsupported_type + + +log = logging.getLogger(__name__) +aten = torch.ops.aten +prims = torch.ops.prims + +Constant = Any +NodeOrConstant = Constant | torch.fx.Node + +backend = os.environ.get("TORCHINDUCTOR_PATTERN_MATCH_BACKEND", "inductor") + + +_debug_nodes_cache: bool | OrderedSet[str] | None = None +_debug_nodes_env_value_cache: str | None = None + + +def _should_debug_node(node_name: str) -> bool: + def _get_debug_nodes() -> bool | OrderedSet[str]: + global _debug_nodes_cache, _debug_nodes_env_value_cache + + def parse_debug_env(env_value: str | None) -> bool | OrderedSet[str]: + if not env_value: + return False + if env_value == "all": + return True + return OrderedSet(env_value.split(",")) + + current_env = os.environ.get("TORCHINDUCTOR_PATTERN_MATCH_DEBUG") + + # Recompute only if env changed + if current_env != _debug_nodes_env_value_cache or _debug_nodes_cache is None: + _debug_nodes_cache = parse_debug_env(current_env) + _debug_nodes_env_value_cache = current_env + + return _debug_nodes_cache + + debug_nodes = _get_debug_nodes() + if isinstance(debug_nodes, bool): + return debug_nodes + return node_name in debug_nodes + + +class SearchFn(Protocol): + __name__: str + + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + + +class ReplaceFn(Protocol): + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + + +class TraceFn(Protocol): + def __call__( + self, fn: SearchFn | ReplaceFn, *args: Any, **kwargs: Any + ) -> torch.fx.GraphModule: ... + + +T = TypeVar("T") + +# What's a better name for this? +FnsType = torch.fx.node.Target | str + + +class Multiple: + def __init__(self) -> None: + # Ensure we're really a singleton. + if "MULTIPLE" in globals() and self is not MULTIPLE: + raise AssertionError("Multiple is not a singleton") + + +# Sentinel indicating multiple quantities can be matched +MULTIPLE = Multiple() + + +def _transfer_meta( + new_meta: dict[str, Any], old_node: torch.fx.Node, pass_name: str = "" +) -> None: + from torch.fx.traceback import NodeSource, NodeSourceAction + + # Transfer metadata after pattern matching occurs. + # Copies _COPY_META_FIELDS, stack_trace, and (if missing) val/tensor_meta. + if config.effective_provenance_tracking_level() == 1: + new_from_node = new_meta.get("from_node", []).copy() + new_from_node.append(NodeSource(old_node, pass_name, NodeSourceAction.REPLACE)) + new_meta.update( + (k, v) + for k, v in old_node.meta.items() + if k in torch.fx.proxy._COPY_META_FIELDS + ) + new_meta["from_node"] = new_from_node + else: + new_meta.update( + (k, v) + for k, v in old_node.meta.items() + if k in torch.fx.proxy._COPY_META_FIELDS + ) + if "stack_trace" in old_node.meta: + new_meta["stack_trace"] = old_node.meta["stack_trace"] + # Copy val/tensor_meta only when the new node doesn't already have them + # (e.g. from tracing the replacement graph). Don't overwrite if present + # since the replacement's own val is more accurate. + if "val" not in new_meta and "val" in old_node.meta: + new_meta["val"] = old_node.meta["val"] + if "tensor_meta" not in new_meta and "tensor_meta" in old_node.meta: + new_meta["tensor_meta"] = old_node.meta["tensor_meta"] + + +def _common_custom_context(nodes: Sequence[torch.fx.Node]) -> dict[str, Any]: + if not nodes: + return {} + + stream = nodes[0].meta.get("custom", {}).get("stream", 0) + mempool = nodes[0].meta.get("custom", {}).get("mempool") + mempool_device = nodes[0].meta.get("custom", {}).get("mempool_device") + if any( + ( + node.meta.get("custom", {}).get("stream", 0), + node.meta.get("custom", {}).get("mempool"), + node.meta.get("custom", {}).get("mempool_device"), + ) + != (stream, mempool, mempool_device) + for node in nodes[1:] + ): + return {} + + context: dict[str, Any] = {} + if stream != 0 or any("stream" in node.meta.get("custom", {}) for node in nodes): + context["stream"] = stream + if mempool is not None: + context["mempool"] = mempool + context["mempool_device"] = mempool_device + return context + + +def _merge_custom_context( + new_meta: dict[str, Any], custom_context: dict[str, Any] +) -> None: + # Replacement nodes inherit user stream/mempool context only at explicit + # graph transform hooks. Other transforms must preserve meta["custom"] or + # avoid moving context-tagged values across boundaries. + if not custom_context: + return + custom = new_meta.setdefault("custom", {}) + for key, value in custom_context.items(): + custom.setdefault(key, value) + + +class Match: + """ + Represents a successfully matched pattern. + + The `Match` object is returned to represent a successfully matched + pattern. Included in the Match are the pattern that was matched, the graph + nodes matched, and any args that were used during the matching. + + The args and kwargs are specific to the type of pattern that was matched and + provide hints about what was matched. + """ + + pattern: PatternExpr + args: list[Any] + kwargs: dict[str, Any] + nodes: list[torch.fx.Node] + targets: dict[_TargetExpr, torch.fx.node.Target] + ctx: MatchContext + replacement_graph: torch.fx.GraphModule | None + + def __init__( + self, + ctx: MatchContext, + pattern: PatternExpr, + args: Sequence[Any] | None = None, + kwargs: dict[str, Any] | None = None, + ) -> None: + super().__init__() + self.pattern = pattern + # The input nodes that must be passed in to the result + self.args = list(args or []) + self.kwargs = kwargs or {} + # The nodes matched in this expression + self.nodes = [] + # Mapping CallFunction to the node.target + self.targets = {} + self.ctx = ctx + self.replacement_graph = None + + @property + def graph(self) -> torch.fx.Graph: + return self.ctx.graph + + def extend(self, other: Match) -> None: + if self.kwargs: + for key in OrderedSet(self.kwargs.keys()) & OrderedSet(other.kwargs.keys()): + if self.kwargs[key] != other.kwargs[key]: + raise FailedMatch("kwarg mismatch: {}", key) + self.args.extend(other.args) + self.nodes.extend(other.nodes) + self.kwargs.update(other.kwargs) + self.targets.update(other.targets) + + def bundle(self) -> Match: + # Wrap args in an extra list + self.args = [tuple(self.args)] if self.args else [] + return self + + def __repr__(self) -> str: + return f"Match(..., {self.args}, {self.kwargs})" + + def erase_nodes(self) -> None: + graph = self.graph + for n in reversed(self.nodes): + if not n._erased and not n.users: + graph.erase_node(n) + + def output_nodes(self) -> list[torch.fx.Node | None]: + return [ + (self.ctx.pattern_to_node[p] if p is not None else None) + for p in self.ctx.outputs + ] + + def output_node(self) -> torch.fx.Node: + return next(p for p in self.output_nodes() if p) + + def replace_with_graph( + self, replacement_graph: torch.fx.Graph, args: Sequence[Any] + ) -> list[torch.fx.Node]: + return ReplacementPatternEntry.replace_with_graph( + self, self.ctx.graph, replacement_graph, args + ) + + def replace_by_example( + self, + replacement_fn: ReplaceFn, + args: Sequence[Any], + trace_fn: TraceFn | None = None, + run_functional_passes: bool = True, + ) -> list[torch.fx.Node]: + """Replace with a graph generated by tracing the replacement_fn. + + Args: + run_functional_passes (bool). If we should run passes that + assume functional IR (like DCE, remove_noop_ops), on the + replacement graph. + + """ + from torch._inductor.virtualized import NullHandler, V + + context = ( + V.fake_mode + if (not isinstance(V.fake_mode, NullHandler) or (V.fake_mode is None)) + else contextlib.nullcontext() + ) + + def should_propagate_eager_input_vals(nodes: list[torch.fx.Node]) -> bool: + if len(nodes) != 1: + return False + node = nodes[0] + if "eager_input_vals" not in node.meta: + return False + return node.target in OrderedSet( + [ + torch.ops.higher_order.auto_functionalized, + torch.ops.higher_order.auto_functionalized_v2, + ] + ) + + # pyrefly: ignore [bad-context-manager] + with context: + if trace_fn is None: + trace_fn = functools.partial( + fwd_only, run_functional_passes=run_functional_passes + ) + + if should_propagate_eager_input_vals(self.nodes): + # Our strategy is: + # 1) trace out the graph with eager_input_vals (which have accurate eager-mode metadata) + # 2) trace out the graph with vals (which have the accurate Inductor metadata) + # 3) Propagate the eager_input_vals from the first graph to the second. + # 4) Use the second graph as the replacement graph. + + # Construct a map of node -> FakeTensor val in eager_input_vals + node_to_val = {} + + fake_args, fake_kwargs = self.nodes[0].meta["eager_input_vals"] + fake_kwargs = {**fake_kwargs} + match_args, match_kwargs = tuple(self.args), self.kwargs + + def record(node: torch.fx.Node, val: Any) -> None: + if isinstance(node, torch.fx.Node): + node_to_val[node] = val + + torch.utils._pytree.tree_map( + record, (match_args, match_kwargs), (fake_args, fake_kwargs) + ) + # map args to their FakeTensor val in eager_input_vals + example_vals = torch.fx.map_arg(args, lambda arg: node_to_val[arg]) + + # first graph + graph_with_eager_vals = trace_fn(replacement_fn, example_vals) + + # second graph + example_vals = torch.fx.map_arg(args, lambda arg: arg.meta["val"]) + # pyrefly: ignore [bad-argument-type] + replacement = trace_fn(graph_with_eager_vals, example_vals) + + # propagate metadata from first graph to second + # NB: This assertion might not be true in general, but it is true for + # the auto_functionalized use cases we have + if len(graph_with_eager_vals.graph.nodes) != len( + replacement.graph.nodes + ): + raise AssertionError( + "graph node count mismatch between eager and replacement" + ) + for old_node, new_node in zip( + graph_with_eager_vals.graph.nodes, replacement.graph.nodes + ): + if "eager_input_vals" in old_node.meta: + new_node.meta["eager_input_vals"] = old_node.meta[ + "eager_input_vals" + ] + + else: + example_vals = torch.fx.map_arg( + args, + lambda arg: arg.meta["val"] + if "val" in arg.meta + else arg.meta["example_value"], + ) + fake_mode = torch._dynamo.utils.detect_fake_mode(example_vals) + if fake_mode is not None: + + def _convert_to_fake_mode(it): + if is_fake_tensor(it) and fake_mode is not None: + return fake_mode.from_tensor(it) + return it + + example_vals = torch.fx.node.map_aggregate( + example_vals, _convert_to_fake_mode + ) + replacement = trace_fn(replacement_fn, example_vals) + if len(self.nodes) == 1: + for n in replacement.graph.nodes: + _transfer_meta( + new_meta=n.meta, + old_node=self.nodes[0], + pass_name="replace_by_example", + ) + + return ReplacementPatternEntry.replace_with_graph( + self, + self.ctx.graph, + replacement, + args, + ) + + +class FailedMatch(RuntimeError): + """ + Represents a unsuccessful match. + + The `FailedMatch` object is returned to represent a failure to match a + pattern. + """ + + format_string: str + + def __init__(self, format_string: str, *args: Any, **kwargs: Any) -> None: + self.format_string = format_string + # We want to construct error messages lazily instead of eagerly, as + # constructing them eagerly can significantly worsen compile times. + if len(format_string) > 200: + raise RuntimeError( + f"Format string too long - use lazy construction of strings instead. Format string is\n {format_string}" + ) + self.args = args + self.kwargs = kwargs + + def __str__(self) -> str: + return self.format_string.format(*self.args, **self.kwargs) + + def __bool__(self) -> bool: + return False + + +MatchResult = Match | FailedMatch + + +def is_match(m: MatchResult) -> TypeIs[Match]: + """ + TypeIs cannot act on `self`. Thus this function exists to let mypy + recognize FailedMatch.__bool__ as a TypeIs. + """ + return bool(m) + + +class MatchContext: + """ + Internal state needed while running PatternExpr._match(). + """ + + outputs: list[PatternExpr | None] + pattern_to_node: dict[PatternExpr, torch.fx.Node | None] + graph: torch.fx.Graph + exclusive_node_set: list[NodeOrConstant] + + def __init__( + self, + outputs: list[PatternExpr | None], + pattern_to_node: dict[PatternExpr, torch.fx.Node] | None = None, + *, + graph: torch.fx.Graph, + ) -> None: + self.outputs = outputs + self.pattern_to_node = {} if pattern_to_node is None else dict(pattern_to_node) + self.graph = graph + self.exclusive_node_set = [] + + def match(self, pattern: PatternExpr, node: NodeOrConstant) -> MatchResult: + """wrapper to check reused nodes in patterns""" + if pattern in self.pattern_to_node: + if self.pattern_to_node[pattern] == node: + return Match(self, pattern) # already checked this node + else: + return FailedMatch("repeated pattern differs") + m = pattern._match(node, self) + if pattern in self.pattern_to_node: + raise AssertionError("pattern already present in pattern_to_node") + self.pattern_to_node[pattern] = node if m else None + return m + + def filter_multi_user_patterns(self) -> dict[PatternExpr, torch.fx.Node]: + return { + pattern: node + for pattern, node in self.pattern_to_node.items() + if pattern.has_multiple_users() and node is not None + } + + +class PatternExpr(ABC): + """ + Base class for types of patterns. + """ + + @abstractmethod + def _match(self, node: torch.fx.Node, ctx: MatchContext) -> MatchResult: ... + + def match(self, node: torch.fx.Node) -> MatchResult: + try: + return MatchContext([self], graph=node.graph).match(self, node) + except FailedMatch as e: + return e + + def has_multiple_users(self) -> bool: + return False + + def __repr__(self) -> str: + return self.__class__.__name__ + "()" + + def find_anchor_nodes( + self, ctx: MatchContext, searched: OrderedSet[torch.fx.Node] + ) -> Generator[torch.fx.Node | None, None, None]: + if self in ctx.pattern_to_node: + yield ctx.pattern_to_node[self] + + def pattern_eq(self, other: Any) -> bool: + """ + Compare two `PatternExpr`s and return true if they are the + same. Note this is NOT matching a pattern - it is comparing the pattern + structures (for debugging). + """ + return isinstance(other, self.__class__) + + +class Arg(PatternExpr): + """ + Capture an arg which will become an input to the handler. Args are + passed in depth first order. + """ + + def _match(self, node: NodeOrConstant, ctx: MatchContext) -> MatchResult: + return Match(ctx, self, args=[node]) # matches anything + + +class Ignored(PatternExpr): + """ + Match an arg, but don't pass it to handler + """ + + def _match(self, node: NodeOrConstant, ctx: MatchContext) -> MatchResult: + return Match(ctx, self) # matches anything + + def __repr__(self) -> str: + return "*" + + def pretty_print(self, pp: PatternPrettyPrinter) -> str: + return "Ignored()" + + +def _get_fake_tensor_constant(value: torch.Tensor) -> torch.Tensor | None: + if is_fake_tensor(value): + return maybe_get_fake_constant(value) + return value + + +def _tensor_values_equal(a: torch.Tensor, b: torch.Tensor) -> bool: + if torch.equal(a, b): + return True + if a.dtype.is_complex: + return _tensor_values_equal(a.real, b.real) and _tensor_values_equal( + a.imag, b.imag + ) + if a.dtype.is_floating_point: + return bool(((a == b) | (torch.isnan(a) & torch.isnan(b))).all().item()) + return False + + +def _constant_values_equal(a: Any, b: Any) -> bool: + if isinstance(a, torch.Tensor) or isinstance(b, torch.Tensor): + if not isinstance(a, torch.Tensor) or not isinstance(b, torch.Tensor): + return False + if ( + a.dtype != b.dtype + or a.shape != b.shape + or a.device != b.device + or a.layout != b.layout + or a.requires_grad != b.requires_grad + ): + return False + if a.layout == torch.strided and ( + a.stride() != b.stride() or a.storage_offset() != b.storage_offset() + ): + return False + a_constant = _get_fake_tensor_constant(a) + b_constant = _get_fake_tensor_constant(b) + if a_constant is None or b_constant is None: + return False + try: + with unset_fake_temporarily(): + return _tensor_values_equal(a_constant, b_constant) + except (RuntimeError, TypeError, ValueError): + return False + + try: + result = a == b + except (RuntimeError, TypeError, ValueError): + return False + return result if isinstance(result, bool) else False + + +def _python_constant_repr(value: Any) -> str: + if isinstance(value, float): + if math.isnan(value): + return "float('nan')" + if math.isinf(value): + return "float('inf')" if value > 0 else "-float('inf')" + if isinstance(value, complex): + return f"complex({_python_constant_repr(value.real)}, {_python_constant_repr(value.imag)})" + if isinstance(value, list): + return f"[{', '.join(map(_python_constant_repr, value))}]" + if isinstance(value, tuple): + trailing_comma = "," if len(value) == 1 else "" + return f"({', '.join(map(_python_constant_repr, value))}{trailing_comma})" + return repr(value) + + +def _tensor_constant_repr(value: torch.Tensor) -> str: + if value.layout != torch.strided: + raise NotImplementedError( + f"NYI: serializing get_attr tensor with layout {value.layout}" + ) + dtype = value.dtype + device = value.device + if is_fake_tensor(value): + constant = maybe_get_fake_constant(value) + if constant is None: + raise NotImplementedError("NYI: serializing fake get_attr tensor") + data_value = constant + else: + data_value = value + if value.requires_grad: + raise NotImplementedError("NYI: serializing tensor that requires grad") + if not value.is_contiguous() or value.storage_offset() != 0: + raise NotImplementedError("NYI: serializing non-contiguous get_attr tensor") + with unset_fake_temporarily(): + if data_value.device.type != "cpu": + cpu_value = data_value.detach().cpu() + else: + cpu_value = data_value.detach() + value_list = cpu_value.tolist() + + args = [_python_constant_repr(value_list)] + args.append(f"dtype={dtype}") + if device.type != "cpu": + args.append(f"device={str(device)!r}") + return f"torch.tensor({', '.join(args)})" + + +class GetAttr(PatternExpr): + """ + Match a get_attr node by comparing the attribute value instead of the target + name, which is local to the traced GraphModule. + """ + + def __init__(self, value: Any, users: Multiple | int = 1) -> None: + super().__init__() + self.value = value + self.users = users + + def __repr__(self) -> str: + if self.users is MULTIPLE: + comma_users = ", MULTIPLE" + elif self.users != 1: + comma_users = f", {self.users}" + else: + comma_users = "" + return f"{self.__class__.__name__}({self.value!r}{comma_users})" + + def has_multiple_users(self) -> bool: + return isinstance(self.users, Multiple) or self.users > 1 + + def _match(self, node: NodeOrConstant, ctx: MatchContext) -> MatchResult: + if not isinstance(node, torch.fx.Node) or node.op != "get_attr": + return FailedMatch("get_attr_mismatch: node={}, pattern={}", node, self) + if ( + self not in ctx.outputs + and self.users is not MULTIPLE + and len(node.users) != self.users + ): + return FailedMatch("multiple_users {}", self) + if node.graph.owning_module is None: + return FailedMatch("get_attr without owning module: {}", node) + if not isinstance(node.target, str): + return FailedMatch("get_attr target is not str: {}", node.target) + value = _get_attr(node.graph.owning_module, node.target) + if not _constant_values_equal(self.value, value): + return FailedMatch("get_attr_value: {} != {}", value, self.value) + m = Match(ctx, self) + m.nodes.append(node) + return m + + def pretty_print(self, pp: PatternPrettyPrinter) -> str: + args = [pp.pretty_print(self.value)] + if self.users is MULTIPLE: + args.append("MULTIPLE") + elif self.users != 1: + args.append(str(self.users)) + return f"{self.__class__.__name__}({', '.join(args)})" + + def pattern_eq(self, other: Any) -> bool: + other = typing.cast(Self, other) + return ( + super().pattern_eq(other) + and _constant_values_equal(self.value, other.value) + and self.users == other.users + ) + + +class KeywordArg(PatternExpr): + """ + Capture a kwarg which will become an input to the handler. + """ + + def __init__(self, name: str) -> None: + super().__init__() + self.name = name + + def __repr__(self) -> str: + return f"KeywordArg({self.name!r})" + + def _match(self, node: NodeOrConstant, ctx: MatchContext) -> MatchResult: + return Match(ctx, self, kwargs={self.name: node}) # matches anything + + def pattern_eq(self, other: Any) -> bool: + other = typing.cast(Self, other) # super makes sure this is true + return super().pattern_eq(other) and self.name == other.name + + +class ExclusiveKeywordArg(PatternExpr): + """ + Capture a kwarg which will become an input to the handler. + """ + + name: str + + def __init__(self, name: str) -> None: + super().__init__() + self.name = name + + def __repr__(self) -> str: + return f"ExclusiveKeywordArg({self.name!r})" + + def _match(self, node: NodeOrConstant, ctx: MatchContext) -> MatchResult: + if node in ctx.exclusive_node_set: + return FailedMatch("exclusive arg appears twice") + + ctx.exclusive_node_set.append(node) + return Match(ctx, self, kwargs={self.name: node}) # matches anything + + def pattern_eq(self, other: Any) -> bool: + other = typing.cast(Self, other) # super makes sure this is true + return super().pattern_eq(other) and self.name == other.name + + +class _TargetExpr(PatternExpr): + """ + Base class for filtering match by node.target + """ + + fns: list[FnsType] + fns_set: OrderedSet[FnsType] + + def __init__( + self, fns: FnsType | Sequence[FnsType], users: Multiple | int = 1 + ) -> None: + super().__init__() + fns = [fns] if callable(fns) or isinstance(fns, str) else list(fns) + for fn in fns: + if isinstance(fn, torch._ops.OpOverloadPacket): + fns.extend(fn.op_overloads()) # noqa: B909 + + self.fns = fns + self.fns_set = OrderedSet(fns) + self.users = users + + @property + @abstractmethod + def op(self) -> str: ... + + def fns_repr(self) -> str: + first_repr = self.fns[0] + if not isinstance(first_repr, str): + first_repr = first_repr.__name__ + + if len(self.fns) > 1: + return f"[{first_repr}, ...]" + elif self.fns[0] is getattr(torch, first_repr, None): + return f"torch.{first_repr}" + elif self.fns[0] is getattr(operator, first_repr, None): + return f"operator.{first_repr}" + elif isinstance(self.fns[0], torch._ops.OpOverload): + return str(self.fns[0]) + else: + return first_repr + + def __repr__(self) -> str: + if self.users is MULTIPLE: + comma_users = ", MULTIPLE" + elif self.users != 1: + comma_users = f", {self.users})" + else: + comma_users = "" + return f"{self.__class__.__name__}({self.fns_repr()}{comma_users})" + + def has_multiple_users(self) -> bool: + return isinstance(self.users, Multiple) or self.users > 1 + + def find_anchor_nodes( + self, ctx: MatchContext, searched: OrderedSet[torch.fx.Node] + ) -> Generator[torch.fx.Node | None, None, None]: + raise NotImplementedError + + def _match_fns(self, node: torch.fx.Node) -> bool: + return ( + isinstance(node, torch.fx.Node) + and node.op == self.op + and extract_target(node) in self.fns_set + ) + + def _match_users(self, node: torch.fx.Node, ctx: MatchContext) -> bool: + return ( + self in ctx.outputs + or self.users is MULTIPLE + or len(node.users) == self.users + ) + + def pattern_eq(self, other: Any) -> bool: + other = typing.cast(Self, other) # super makes sure this is true + return ( + super().pattern_eq(other) + and self.op == other.op + and self.fns == other.fns + and self.users == other.users + ) + + +_SimpleSpec = tuple[Any, ...] + + +class _TargetArgsExpr(_TargetExpr): + """ + Base class for filtering match by node.{target,args,kwargs} + """ + + def __init__( + self, + fns: torch.fx.node.Target | str | Sequence[Any], + *args: Any, + _users: int | Multiple = 1, + **kwargs: Any, + ) -> None: + super().__init__(fns, _users) + self.args = tuple(args) + self.kwargs = dict(kwargs) + if any( + isinstance(x, (dict, list, tuple)) + for x in itertools.chain(args, kwargs.values()) + ): + self.flatten = self.pytree_flatten + else: + self.flatten = self.simple_flatten + self.flat_args_kwargs = self.flatten(self.args, self.kwargs) + + @staticmethod + def simple_flatten( + args: Sequence[Any], kwargs: Mapping[Any, Any] + ) -> tuple[Sequence[Any], _SimpleSpec | pytree.TreeSpec]: + values = (*args, *kwargs.values()) + spec = (len(args), *kwargs.keys()) + return values, spec + + @staticmethod + def pytree_flatten( + args: Sequence[Any], kwargs: Mapping[Any, Any] + ) -> tuple[Sequence[Any], _SimpleSpec | pytree.TreeSpec]: + type_mapping: dict[type, type] = { + immutable_list: tuple, + list: tuple, + immutable_dict: dict, + } + + def convert_type(x: Any) -> Any: + cls = type(x) + convert_fn = type_mapping.get(cls) + if convert_fn is not None: + return pytree.tree_map( + convert_type, + convert_fn(x), + is_leaf=lambda x: type(x) in type_mapping, + ) + return x + + normalized_args_tree = pytree.tree_map( + convert_type, + (args, kwargs), + is_leaf=lambda x: type(x) in type_mapping, + ) + flat, spec = pytree.tree_flatten(normalized_args_tree) + return flat, spec + + def __repr__(self) -> str: + args = [ + self.fns_repr(), + *map(repr, self.args), + *[f"{k}={v}" for k, v in self.kwargs.items()], + ] + if self.users is MULTIPLE: + args.append("_users=MULTIPLE") + elif self.users != 1: + args.append(f"_users={self.users}") + return f"{self.__class__.__name__}({', '.join(args)})" + + def pretty_print(self, pp: PatternPrettyPrinter) -> str: + args = [ + self.fns_repr(), + *(pp.pretty_print(x) for x in self.args), + *[f"{k}={pp.pretty_print(v)}" for k, v in self.kwargs.items()], + ] + if self.users is MULTIPLE: + args.append("_users=MULTIPLE") + elif self.users != 1: + args.append(f"_users={self.users}") + + joiner_str = ", " + return f"{self.__class__.__name__}({joiner_str.join(args)})" + + def _match(self, node: torch.fx.Node, ctx: MatchContext) -> MatchResult: + if not self._match_fns(node) or len(node.args) != len(self.args): + return FailedMatch("function_mismatch: node={}, pattern={}", node, self) + + if not self._match_users(node, ctx): + return FailedMatch("multiple_users {}", self) + + _args = node.args + _kwargs = node.kwargs + if len(_kwargs) < len(self.kwargs): + from torch.fx.operator_schemas import normalize_function + + if not callable(node.target): + raise AssertionError( + f"expected callable node.target, got {node.target}" + ) + normalized_args_and_kwargs = normalize_function( + node.target, node.args, node.kwargs + ) + + if normalized_args_and_kwargs is None: + return FailedMatch("function_mismatch: node={}, pattern={}", node, self) + else: + _args, _kwargs = normalized_args_and_kwargs + if len(_args) == len(self.args) and len(_kwargs) >= len(self.kwargs): + _kwargs = {i: _kwargs[i] for i in _kwargs if i in self.kwargs} + else: + return FailedMatch( + "function_mismatch: node={}, pattern={}", node, self + ) + else: + _kwargs = {i: _kwargs[i] for i in _kwargs if i in self.kwargs} + + node_items, node_spec = self.flatten(_args, _kwargs) + self_items, self_spec = self.flat_args_kwargs + if node_spec != self_spec: + return FailedMatch("args_structure {} {}", node_spec, self_spec) + if len(node_items) != len(self_items): + raise AssertionError("node_items and self_items length mismatch") + + m = Match(ctx, self) + for pattern, child_node in zip(self_items, node_items): + if isinstance(pattern, PatternExpr): + child_match = ctx.match(pattern, child_node) + if not is_match(child_match): + return child_match + m.extend(child_match) + elif isinstance(child_node, torch.fx.Node) or child_node != pattern: + return FailedMatch( + "constant_args: {} {!r}!={pattern!r}", + node, + child_node, + pattern=pattern, + ) + m.nodes.append(node) + m.targets[self] = node.target + return m + + def find_anchor_nodes( + self, ctx: MatchContext, searched: OrderedSet[torch.fx.Node] + ) -> Generator[torch.fx.Node | None, None, None]: + """ + This is used when we are matching a pattern with multiple outputs. + There is a partial match (stored in ctx) and we want to walk + this pattern to find a connection to an already-matched node. + + Yields candidate nodes that `self._match` might like. + """ + if self in ctx.pattern_to_node: + yield ctx.pattern_to_node[self] + return + + for pattern in self.flat_args_kwargs[0]: + if isinstance(pattern, PatternExpr): + for other_node in pattern.find_anchor_nodes(ctx, searched): + if not isinstance(other_node, torch.fx.Node): + continue + for node in other_node.users: + if node not in searched: + if self._match_fns(node): + yield node + searched.add(node) + + def pattern_eq(self, other: Any) -> bool: + other = typing.cast(Self, other) # super makes sure this is true + return ( + super().pattern_eq(other) + and self.flat_args_kwargs[1] == other.flat_args_kwargs[1] + and all( + a.pattern_eq(b) if isinstance(a, PatternExpr) else a == b + for a, b in zip(self.flat_args_kwargs[0], other.flat_args_kwargs[0]) + ) + ) + + +class CallFunction(_TargetArgsExpr): + """ + Matches a call_function node in the FX graphs: `fns[i](*args, **kwargs)` + """ + + op = "call_function" + + +class CallMethod(_TargetArgsExpr): + """ + Matches a call_method node in the FX graphs: `fns[i].method(*args, **kwargs)` + """ + + op = "call_method" + + +class CallModule(_TargetArgsExpr): + """ + Matches a call_module node in the FX graphs: `module(*args, **kwargs)` + """ + + op = "call_module" + + +class _TargetExprVarArgs(_TargetExpr): + """ + Matches a call_function node with any arguments which are passed into the pattern + """ + + def _match(self, node: torch.fx.Node, ctx: MatchContext) -> MatchResult: + if not self._match_fns(node): + return FailedMatch("function_mismatch") + + if not self._match_users(node, ctx): + return FailedMatch("multiple_users") + + m = Match(ctx, self) + m.nodes.append(node) + m.targets[self] = node.target + m.args.extend(node.args) + m.kwargs.update(node.kwargs) + return m + + +class CallFunctionVarArgs(_TargetExprVarArgs): + op = "call_function" + + +class CallMethodVarArgs(_TargetExprVarArgs): + op = "call_method" + + +class CallModuleVarArgs(_TargetExprVarArgs): + op = "call_module" + + +class ListOf(PatternExpr): + """ + Matches a repeated pattern + """ + + def __init__(self, pattern: PatternExpr, partial: bool = False) -> None: + super().__init__() + if not isinstance(pattern, PatternExpr): + raise AssertionError(f"expected PatternExpr, got {type(pattern)}") + self.pattern = pattern + self.partial = partial + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.pattern})" + + def _match(self, node: list[torch.fx.Node], ctx: MatchContext) -> MatchResult: # type: ignore[override] + if not isinstance(node, (list, tuple)) or len(node) == 0: + return FailedMatch("non_list") + m = Match(ctx, self) + # Propagating patterns with multiple users will ensure we don't revisit + # the same nodes + pattern_to_node = ctx.filter_multi_user_patterns() + matched = False + for i, child_node in enumerate(node): + child_ctx = MatchContext( + ctx.outputs, pattern_to_node, graph=child_node.graph + ) + child_match = child_ctx.match(self.pattern, child_node) + pattern_to_node = child_ctx.filter_multi_user_patterns() + if not is_match(child_match): + if not self.partial: + return FailedMatch("list[{}]: {}", i, child_match) + continue + matched = True + m.extend(child_match.bundle()) + if not matched: + return FailedMatch("list: no_match") + return m.bundle() + + def pattern_eq(self, other: Any) -> bool: + other = typing.cast(Self, other) # super makes sure this is true + return ( + super().pattern_eq(other) + and self.pattern.pattern_eq(other.pattern) + and self.partial == other.partial + ) + + +class MultiOutputPattern(PatternExpr): + outputs: list[PatternExpr | None] + + def __init__(self, outputs: Sequence[PatternExpr | None]) -> None: + super().__init__() + if not isinstance(outputs[0], _TargetExpr): + raise AssertionError(f"expected _TargetExpr, got {type(outputs[0])}") + if not all(x is None or isinstance(x, PatternExpr) for x in outputs): + raise AssertionError(outputs) + self.outputs = list(outputs) + self.op = outputs[0].op + + @property + def fns(self) -> Callable[..., Any] | str | Sequence[Any]: + # This cast is checked above in __init__() + output = typing.cast(_TargetExpr, self.outputs[0]) + return output.fns + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.outputs})" + + def pretty_print(self, pp: PatternPrettyPrinter) -> str: + args = [pp.pretty_print(x) for x in self.outputs] + joiner_str = f",\n{' '}" + str_out = f"{self.__class__.__name__}([{joiner_str.join(args)}" + str_out = f"{str_out}\n])" + return str_out + + def _match(self, node: torch.fx.Node, ctx: MatchContext) -> MatchResult: + output = typing.cast(_TargetExpr, self.outputs[0]) + m = ctx.match(output, node) + if not is_match(m): + return m + + for pattern in self.outputs[1:]: + if pattern is None: + continue + child_match = self._match_from_anchors(pattern, ctx) + if not is_match(child_match): + return child_match + m.extend(child_match) + + return m + + def _match_from_anchors( + self, pattern: PatternExpr, ctx: MatchContext + ) -> MatchResult: + prior = dict(ctx.pattern_to_node) + m: MatchResult = FailedMatch("no anchor found") + for node in pattern.find_anchor_nodes(ctx, OrderedSet()): + m = ctx.match(pattern, node) + if is_match(m): + return m + # revert any partial matches + ctx.pattern_to_node = dict(prior) + return m + + def match(self, node: torch.fx.Node) -> MatchResult: + try: + return MatchContext(self.outputs, graph=node.graph).match(self, node) + except FailedMatch as e: + return e + + def pattern_eq(self, other: Any) -> bool: + other = typing.cast(Self, other) # super makes sure this is true + return ( + super().pattern_eq(other) + and len(self.outputs) == len(other.outputs) + and all( + a.pattern_eq(b) if isinstance(a, PatternExpr) else a == b + for a, b in zip(self.outputs, other.outputs) + ) + ) + + +class RepeatedExpr(PatternExpr): + """ + Checks for a repeated pattern. Useful for repeated operations after a node such as `split` or `unbind` + """ + + def __init__(self, inner_pattern: _TargetExpr) -> None: + super().__init__() + self.inner_pattern = inner_pattern + self.op = inner_pattern.op + + @property + def fns(self) -> Sequence[FnsType]: + return self.inner_pattern.fns + + def _match(self, node: torch.fx.Node, ctx: MatchContext) -> MatchResult: + m = ctx.match(self.inner_pattern, node) + if not is_match(m): + return m + ctx.pattern_to_node.pop( + self.inner_pattern, + ) + # Check all anchor nodes match the pattern + for anchor_node in self.inner_pattern.find_anchor_nodes( + ctx, OrderedSet([node]) + ): + anchor_m = MatchContext([self], graph=node.graph).match( + self.inner_pattern, anchor_node + ) + if not is_match(anchor_m): + return anchor_m + m.extend(anchor_m) + return m + + def pattern_eq(self, other: Any) -> bool: + other = typing.cast(Self, other) # super makes sure this is true + return super().pattern_eq(other) and self.inner_pattern.pattern_eq( + other.inner_pattern + ) + + +class PatternPrettyPrinter: + """ + Serializes Patterns to executable python. + XXX: currently only used and tested for fuse attention patterns. May not cover + all patterns. + """ + + def __init__(self) -> None: + self.namespace = torch.fx.graph._Namespace() + self.memoized_objs_names: dict[PatternExpr, str] = {} + self.memoized_objs_pp: dict[PatternExpr, str] = {} + + @staticmethod + @functools.cache + def run(obj: PatternExpr, output_name: str = "output") -> str: + """ + Serializes obj to python code with obj written out to `output_name` + """ + + pp = PatternPrettyPrinter() + if not hasattr(obj, "pretty_print"): + raise AssertionError("obj has no pretty_print method") + out_str = obj.pretty_print(pp=pp) + + output = [ + f"{pp.memoized_objs_names[key]} = {pp.memoized_objs_pp[key]}" + for key in pp.memoized_objs_names + ] + + output.append(f"{output_name} = {out_str}") + + return "\n".join(output) + + def pretty_print(self, obj: Any) -> str: + if isinstance(obj, _TargetArgsExpr): + if memoized_name := self.memoized_objs_names.get(obj): + return memoized_name + else: + return self.memoize(obj) + if isinstance(obj, torch.Tensor): + return _tensor_constant_repr(obj) + if hasattr(obj, "pretty_print"): + return obj.pretty_print(self) + + return repr(obj) + + def memoize(self, obj: _TargetArgsExpr) -> str: + obj_str = obj.pretty_print(self) + obj_name = obj.fns_repr() + for prefix in ("aten.", "torch.", "prims."): + obj_name = obj_name.replace(prefix, "") + + tmp_name = self.namespace.create_name(obj_name, None) + self.memoized_objs_names[obj] = tmp_name + self.memoized_objs_pp[obj] = obj_str + return tmp_name + + +class _PassDictsType(Protocol): + def __getitem__( + self, k: tuple[str, torch.fx.node.Target] + ) -> list[PatternEntry]: ... + + +@dataclasses.dataclass +class PatternEntry: + pattern: PatternExpr + extra_check: Callable[[Match], bool] + + def apply(self, match: Match, graph: torch.fx.Graph, node: torch.fx.Node) -> None: + raise NotImplementedError + + def register( + self, + pass_dicts: _PassDictsType | Sequence[_PassDictsType], + target: torch.fx.node.Target | None = None, + prepend: bool = False, + ) -> None: + if target is None: + if not hasattr(self.pattern, "fns"): + raise AssertionError("pattern has no fns attribute") + for fn in self.pattern.fns: + self.register(pass_dicts, fn, prepend=prepend) + elif isinstance(pass_dicts, (dict, PatternMatcherPass)): + if not hasattr(self.pattern, "op"): + raise AssertionError("pattern has no op attribute") + if prepend: + pass_dicts[(self.pattern.op, target)].insert(0, self) + else: + pass_dicts[(self.pattern.op, target)].append(self) + else: + pass_dicts = typing.cast(Sequence[_PassDictsType], pass_dicts) + for x in pass_dicts: + self.register(x, target, prepend=prepend) + + +@dataclasses.dataclass +class LoweringPatternEntry(PatternEntry): + handler: Callable[..., Any] + + def apply(self, match: Match, graph: torch.fx.Graph, node: torch.fx.Node) -> None: + handler = functools.wraps(self.handler)(functools.partial(self.handler, match)) + with graph.inserting_before(node): + replacement = graph.call_function(handler, tuple(match.args), match.kwargs) + _transfer_meta(replacement.meta, node) + node.replace_all_uses_with(replacement) + if match.nodes[-1] is not node: + raise AssertionError("expected match.nodes[-1] to be node") + match.erase_nodes() + + +@dataclasses.dataclass +class GraphPatternEntry(PatternEntry): + """ + A pattern that runs a function on the FX graph + """ + + handler: Callable[..., Any] + + def apply(self, match: Match, graph: torch.fx.Graph, node: torch.fx.Node) -> None: + with graph.inserting_before(node): + self.handler(match, *match.args, **match.kwargs) + + +@dataclasses.dataclass +class ReplacementPatternEntry(PatternEntry): + """ + The replacement pattern for the graph + """ + + normalize_args: Callable[..., list[Any]] + pattern_name: str | None = None # Unique identifier for per-pattern telemetry + + @staticmethod + def replace_with_graph( + match: Match, + graph: torch.fx.Graph, + replacement_graph: torch.fx.Graph | torch.fx.GraphModule, + args: Sequence[torch.fx.Node], + pass_name: str | None = None, + ) -> list[torch.fx.Node]: + """ + Inserts the replacement graph into the toplevel graph at the match + """ + + added_replacement_nodes: list[torch.fx.Node] = [] + custom_context = _common_custom_context(match.nodes) + + class Replacer(torch.fx.Interpreter): + call_method = None # type: ignore[assignment] + call_module = None # type: ignore[assignment] + get_attr = None # type: ignore[assignment] + + def run_node(self, node: torch.fx.Node) -> Any: + if node.op in ("placeholder", "output"): + return super().run_node(node) + target = node.target + args, kwargs = self.fetch_args_kwargs_from_env(node) + if node.op == "call_function": + if not callable(target): + raise AssertionError(f"expected callable target, got {target}") + result = graph.call_function(target, args, kwargs) + added_replacement_nodes.append(result) + _transfer_meta( + new_meta=result.meta, + old_node=node, + pass_name=pass_name or "", + ) + _merge_custom_context(result.meta, custom_context) + # This function copy-pastes the replacement graph into + # the graph. If the replacement graph had any eager_input_vals, + # we propagate those over (val/tensor_meta are handled by + # _transfer_meta above). + if "eager_input_vals" in node.meta: + result.meta["eager_input_vals"] = node.meta["eager_input_vals"] + return result + if node.op == "get_attr": + # If the replacement graph contains a HOP, the subgraphs of the HOP are "get_attr" nodes. + # We need to fetch the subgraph of the HOP then register the subgraph to the replaced graph's root. + from torch._higher_order_ops.utils import ( + unique_graph_name_with_root, + ) + + sub_gm = super().get_attr(target, args, kwargs) + if not isinstance(sub_gm, torch.fx.GraphModule): + raise NotImplementedError( + f"NYI: replacement_graph.{target} is not a graph module. Got {sub_gm}." + ) + if graph.owning_module is None: + raise AssertionError("graph.owning_module is None") + graph_name = None + for n, mod in graph.owning_module.named_modules(): + if sub_gm is mod: + graph_name = n + break + if graph_name is None: + if not isinstance(target, str): + raise AssertionError( + f"expected str target, got {type(target)}" + ) + _, graph_name = unique_graph_name_with_root( + # pyrefly: ignore [unbound-name] + graph.owning_module, + target, + ) + # pyrefly: ignore [unbound-name] + graph.owning_module.register_module(graph_name, sub_gm) + # pyrefly: ignore [unbound-name] + getattr_node = graph.get_attr(graph_name) + added_replacement_nodes.append(getattr_node) + return getattr_node + + raise NotImplementedError(f"unhandled {node}") + + output_nodes = match.output_nodes() + + if len(output_nodes) == 1: + last_node = output_nodes[0] + else: + if not output_nodes[0]: + raise AssertionError("output_nodes[0] is falsy") + nodes = list(output_nodes[0].graph.nodes) + indices = [ + (nodes.index(n), n) + for n in output_nodes + if isinstance(n, torch.fx.Node) + ] + last_node = min(indices, key=operator.itemgetter(0))[1] + + def percolate_tags( + node: torch.fx.Node, + tag_name: str, + tag_value: str, + input_stops: OrderedSet[torch.fx.Node], + ) -> None: + queue = [node] + visited = OrderedSet[torch.fx.Node]() + + while queue: + arg = queue.pop() + if ( + arg not in visited + and arg not in input_stops + and hasattr(arg, "meta") + ): + visited.add(arg) + arg.meta[tag_name] = tag_value + queue.extend(arg.all_input_nodes) + + with graph.inserting_before(last_node): + if not isinstance(replacement_graph, torch.fx.GraphModule): + raise AssertionError( + f"expected GraphModule, got {type(replacement_graph)}" + ) + replacement = Replacer(replacement_graph).run(*args) + if isinstance(replacement, torch.fx.Node): + replacement = [replacement] + + def maybe_getitem(node: torch.fx.Node) -> Any: + if node.op != "call_function": + return None + if node.target != operator.getitem: + return None + if len(node.args) != 2: + raise AssertionError(f"expected 2 args, got {len(node.args)}") + return node.args[1] + + def replace( + old: torch.fx.Node | None, + new: torch.fx.Node | Sequence[torch.fx.Node] | None, + ) -> None: + def filter_nodes_in_newly_added_nodes(node: torch.fx.Node) -> bool: + # Do not replace the use of a node if it is being used by + # nodes in the replaced graph + return node not in added_replacement_nodes + + if old is None: + if new is not None: + raise AssertionError("expected new to be None when old is None") + return + if not isinstance(old, torch.fx.Node): + raise AssertionError(f"expected torch.fx.Node, got {type(old)}") + if new is None: + old.replace_all_uses_with( + None, # type: ignore[arg-type] + delete_user_cb=filter_nodes_in_newly_added_nodes, + ) + if len(old.users) == 0: + graph.erase_node(old) + return + if isinstance(new, torch.fx.Node): + _transfer_meta(new.meta, old, pass_name=pass_name or "") + + # Preserve the recompute tags in the replacement graph. We + # look at the recompute tags of the original output node to + # propagate the tag from the output all the way to the input + args_set, _ = pytree.tree_flatten(args) + # args (named as args in the replace_with_graph). + # Note that this is best effort. Since patterns are from + # many to many, there is no easy way to correctly map the + # recomputable tags. It is possible in some scenarios that we + # incorrectly tag some nodes as recomputables. + for tag_name in ["recompute", "ac_graph_id", "custom"]: + if tag_name in old.meta: + percolate_tags( + new, tag_name, old.meta[tag_name], OrderedSet(args_set) + ) + + old.replace_all_uses_with( + new, delete_user_cb=filter_nodes_in_newly_added_nodes + ) + if len(old.users) == 0: + graph.erase_node(old) + return + + # `new` is not a node: it's a list of nodes. + # + # This happens when we want to replace a node that has a single + # packed return with multiple unpacked returns. We need to do + # some graph surgery here. + # + # Example: + # def original_graph(x): + # a = op(x) + # b = a[0] + # c = a[1] + # ... + # + # Assume that we want to replace op(x) with the graph + # def new_op(x): + # w = x + 1 + # z = x + 2 + # return (w, z) + # + # We need to replace `op` with the contents of `new_op`, + # and then rewrite a[0] to be w and a[1] to be z, as so: + # def new_graph(x): + # w = x + 1 + # z = x + 2 + # b = w + # c = z + # ... + old_uses = list(old.users.keys()) + for user in old_uses: + idx = maybe_getitem(user) + if idx is None: + # Output is used directly + # pyrefly: ignore [bad-argument-type] + old.replace_all_uses_with(new) + else: + replace(user, new[idx]) + graph.erase_node(old) + + if len(output_nodes) == len(replacement): + for old, new in zip(output_nodes, replacement): + replace(old, new) + else: + if len(output_nodes) != 1: + raise AssertionError( + f"expected 1 output node, got {len(output_nodes)}" + ) + replace(output_nodes[0], replacement) + + match.erase_nodes() + + # Remove dead replacement nodes so they don't inflate user counts + # in later lowering heuristics (e.g. should_realize_on_reuse). + for node in reversed(added_replacement_nodes): + if ( + not node.users + and not node.is_impure() + and not isinstance(node.target, torch._ops.HigherOrderOperator) + ): + graph.erase_node(node) + + return [node for node in added_replacement_nodes if not node._erased] + + def apply(self, match: Match, graph: torch.fx.Graph, node: torch.fx.Node) -> None: + if match.replacement_graph is None: + raise AssertionError("match.replacement_graph is None") + self.replace_with_graph( + match, + graph, + match.replacement_graph, + self.normalize_args(*match.args, **match.kwargs), + pass_name=self.pattern_name or "replace_with_graph", + ) + + +def _return_true(match: Match) -> bool: + return True + + +def log_trace_failure(search_fn: Callable[..., Any], e: RuntimeError) -> None: + log.info( + "Replacement pattern %s failed to apply due to shape mismatch: %s", + search_fn.__name__, + e, + ) + + +@dataclasses.dataclass(frozen=True) +class _TraceArgInfo: + argnames: list[str] + flat_argnames: list[str] + arg_specs: dict[str, Any] + arg_flat_names: dict[str, list[str]] + + +def _unique_argname(name: str, used_names: OrderedSet[str]) -> str: + if name not in used_names: + used_names.add(name) + return name + + i = 0 + while f"{name}_{i}" in used_names: + i += 1 + name = f"{name}_{i}" + used_names.add(name) + return name + + +def _trace_args_for_initial_trace( + argnames: Sequence[str], + example_inputs: Sequence[Any], + scalar_workaround: dict[str, float | int], +) -> list[Any]: + trace_args = [] + input_idx = 0 + for argname in argnames: + if argname in scalar_workaround: + trace_args.append(scalar_workaround[argname]) + else: + trace_args.append(example_inputs[input_idx]) + input_idx += 1 + return trace_args + + +def _trace_arg_info(argnames: Sequence[str], args: Sequence[Any]) -> _TraceArgInfo: + flat_argnames: list[str] = [] + arg_specs: dict[str, Any] = {} + arg_flat_names: dict[str, list[str]] = {} + used_names: OrderedSet[str] = OrderedSet() + + for argname, arg in zip(argnames, args): + flat_args, spec = pytree.tree_flatten(arg) + arg_specs[argname] = spec + if len(flat_args) == 0: + names: list[str] = [] + elif len(flat_args) == 1: + names = [_unique_argname(argname, used_names)] + else: + names = [ + _unique_argname(f"{argname}_{i}", used_names) + for i in range(len(flat_args)) + ] + flat_argnames.extend(names) + arg_flat_names[argname] = names + + return _TraceArgInfo( + argnames=list(argnames), + flat_argnames=flat_argnames, + arg_specs=arg_specs, + arg_flat_names=arg_flat_names, + ) + + +def _unflatten_match_kwargs( + kwargs: Mapping[str, Any], + arg_info: _TraceArgInfo, + defaults: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + kwargs = dict(kwargs) + result: dict[str, Any] = {} + + for argname in arg_info.argnames: + flat_names = arg_info.arg_flat_names[argname] + found_names = [flat_name for flat_name in flat_names if flat_name in kwargs] + if len(found_names) != len(flat_names): + if defaults is not None and argname in defaults and not found_names: + result[argname] = defaults[argname] + continue + missing_names = [ + flat_name for flat_name in flat_names if flat_name not in kwargs + ] + raise RuntimeError( + f"Not all inputs to pattern found in match.kwargs. Perhaps one " + f"of the inputs is unused? argname={argname}, " + f"flat_argnames={flat_names}, missing_argnames={missing_names}, " + f"match.kwargs={kwargs}" + ) + + flat_values = [] + for flat_name in flat_names: + flat_values.append(kwargs.pop(flat_name)) + result[argname] = pytree.tree_unflatten( + flat_values, arg_info.arg_specs[argname] + ) + + result.update(kwargs) + return result + + +def _get_match_node_value(node: torch.fx.Node) -> Any: + if "val" in node.meta: + return node.meta["val"] + return node.meta["example_value"] + + +def check_and_add_duplicate_pattern( + pattern: PatternExpr, + graph: torch.fx.Graph | None, + seen_patterns: dict[str, list[str | None]], + skip_duplicates: bool = False, +) -> bool: + """ + Check if a pattern is a duplicate. Because we ignore certain types in searching, but not + in matching, use the graph to distinguish equivalent search patterns. + + Returns True if a duplicate is found and `skip_duplicates=True` is passed in. Errors if + `skip_duplicates` is False and a duplicate is found. + """ + + pattern_repr = PatternPrettyPrinter.run(pattern) + equiv_pattern_reprs = seen_patterns.get(pattern_repr) + if not equiv_pattern_reprs: + seen_patterns[pattern_repr].append(str(graph) if graph else None) + return False + + if graph is None: + if skip_duplicates: + return True + torch._check( + False, + lambda: f"Duplicate pattern: {pattern_repr} with no graph", + ) + + new_graph_str = str(graph) + for graph_str in equiv_pattern_reprs: + if new_graph_str != graph_str: + continue + if skip_duplicates: + return True + torch._check( + False, + lambda: f"Duplicate pattern: {pattern_repr} with duplicated match graph {graph_str} ", + ) + equiv_pattern_reprs.append(new_graph_str) + return False + + +def register_replacement( + search_fn: SearchFn, + replace_fn: ReplaceFn, + example_inputs: list[Any] | tuple[Any, ...], + trace_fn: TraceFn, + pass_dicts: _PassDictsType | Sequence[_PassDictsType], + extra_check: Callable[[Match], bool] = _return_true, + scalar_workaround: dict[str, float | int] | None = None, + exclusive_arg_names: Sequence[str] = (), + search_fn_pattern: PatternExpr | None = None, + skip_duplicates: bool = False, + pattern_name: str | None = None, + get_decomp_fn: Callable[..., dict[Any, Callable[..., Any]]] = select_decomp_table, +) -> bool: + """ + Create a replacement rule based on example functions that get traced + to create patterns. This supports both training and inference when + run on a joint forward+backward graph. + + Args: + search_fn: traced to give original pattern + replace_fn: traced to give replacement graph + example_inputs: example inputs for initial trace + trace_fn: fwd_only or joint_fwd_bwd + pass_dict: dict of passes to register to + extra_check: additional check to run on match(using real shapes) + """ + argnames_static = [*inspect.signature(search_fn).parameters.keys()] + + if inspect.ismethod(search_fn): + search_fn = _wrap_bound_method(search_fn, argnames_static) + + if inspect.ismethod(replace_fn): + replace_argnames = [*inspect.signature(replace_fn).parameters.keys()] + replace_fn = _wrap_bound_method(replace_fn, replace_argnames) + + if not isinstance(example_inputs, (list, tuple)): + raise TypeError( + f"example_inputs must be a list or tuple, got {type(example_inputs)}" + ) + scalar_workaround = scalar_workaround or {} + initial_trace_args = _trace_args_for_initial_trace( + argnames_static, example_inputs, scalar_workaround + ) + initial_arg_info = _trace_arg_info(argnames_static, initial_trace_args) + requires_grad = pytree.tree_map( + lambda x: isinstance(x, torch.Tensor) and x.requires_grad, + initial_trace_args, + ) + + def check_fn(match: Match) -> bool: + """ + Often shapes get burned into the pattern, so our initial match ran with + `ignore_types=(int, ...)`. + + Recheck the match with the correct shapes. + """ + structured_match_kwargs = _unflatten_match_kwargs( + match.kwargs, initial_arg_info + ) + + args = list( + torch.fx.map_arg( + [structured_match_kwargs[name] for name in argnames_static], + _get_match_node_value, + ) + ) + + sym_args: list[torch.SymInt] = [] + fake_mode = torch._dynamo.utils.detect_fake_mode(args) + if fake_mode is None: + raise AssertionError("fake_mode is None") + with fake_mode: + invalid_args = False + requires_grad_values = iter(pytree.tree_leaves(requires_grad)) + + def refresh_arg(arg: Any) -> Any: + nonlocal invalid_args + grad = next(requires_grad_values) + if not isinstance(arg, torch.Tensor): + return arg + + if grad and is_integer_dtype(arg.dtype): + invalid_args = True + return arg + + refreshed_arg = torch.empty_strided( + arg.size(), + arg.stride(), + dtype=arg.dtype, + device=arg.device, + requires_grad=grad, + ) + for v in itertools.chain(refreshed_arg.shape, refreshed_arg.stride()): + if isinstance(v, torch.SymInt) and all( + statically_known_true(v != a) for a in sym_args + ): + sym_args.append(v) + return refreshed_arg + + args = pytree.tree_map(refresh_arg, args) + if invalid_args: + return False + + # If we were given a pre-traced pattern then use that instead of + # retracing. Note that this means the pattern has to be independent + # of its args. + specific_pattern = search_fn_pattern + specific_arg_info = _trace_arg_info(argnames_static, args) + specific_argnames = specific_arg_info.flat_argnames + + if not specific_pattern: + if sym_args: + # AOT Autograd and make fx will dedupe symbolic shape size + # accesses of sym ints that appear as inputs + # We don't want the sym_size uses to interfere with pattern matching + # so we provide them as inputs. + # Later, when we actually do the replacement, the symbolic shape + # sizes will get re-traced and added to the graph. + + def search_fn_new(*args_new: Any, **_: Any) -> Any: + return search_fn(*args_new[len(args_new) - len(args) :]) + + try: + specific_graph = trace_fn( + search_fn_new, + sym_args + args, + get_decomp_fn=get_decomp_fn, + ) + except RuntimeError as e: + log_trace_failure(search_fn, e) + return False + + # correct argnames in the graph + sym_arg_names = [] + placeholders = [ + n for n in specific_graph.graph.nodes if n.op == "placeholder" + ] + for i, placeholder in enumerate( + placeholders[: len(sym_args) + len(specific_argnames)] + ): + if i < len(sym_args): + sym_arg_names.append(placeholder.target) + continue + + with specific_graph.graph.inserting_after(placeholder): + new_node = specific_graph.graph.placeholder( + specific_argnames[i - len(sym_args)] + ) + new_node.target = new_node.name + placeholder.replace_all_uses_with(new_node) + specific_graph.graph.erase_node(placeholder) + + specific_argnames = sym_arg_names + specific_argnames + else: + try: + specific_graph = trace_fn( + search_fn, args, get_decomp_fn=get_decomp_fn + ) + except RuntimeError as e: + log_trace_failure(search_fn, e) + return False + + specific_pattern = fx_to_pattern( + specific_graph, + argnames=specific_argnames, + exclusive_arg_names=exclusive_arg_names, + scalar_workaround=scalar_workaround, + ) + + node = match.output_nodes()[0] + if node is None: + raise AssertionError("output node is None") + specific_pattern_match = specific_pattern.match(node) + + if _should_debug_node(node.name): + log.warning( + "Specific pattern match: %s%s %s %s", + node, + node.args, + specific_pattern_match, + specific_pattern, + ) + + if is_match(specific_pattern_match): + specific_pattern_match.kwargs = _unflatten_match_kwargs( + specific_pattern_match.kwargs, + specific_arg_info, + defaults=structured_match_kwargs, + ) + + if is_match(specific_pattern_match) and extra_check(specific_pattern_match): + # trace the pattern using the shapes from the user program + match.replacement_graph = trace_fn( + replace_fn, args, get_decomp_fn=get_decomp_fn + ) + match.kwargs = structured_match_kwargs + if len(match.nodes) == 1: + for n in match.replacement_graph.graph.nodes: + _transfer_meta( + new_meta=n.meta, + old_node=match.nodes[0], + pass_name="replacement", + ) + return True + return False + + def normalize_args(**kwargs: Any) -> list[Any]: + # Flat kwargs come from the initial match; structured kwargs are restored + # after check_fn accepts the match. + if not all(name in kwargs for name in argnames_static): + kwargs = _unflatten_match_kwargs(kwargs, initial_arg_info) + structured_args = [kwargs.pop(name) for name in argnames_static] + args = [] + for arg in structured_args: + args.extend(pytree.tree_leaves(arg)) + for i in range(1, len(kwargs) + 1): + if f"tangents_{i}" not in kwargs: + break + args.append(kwargs.pop(f"tangents_{i}")) + if kwargs: + raise AssertionError(f"leftover kwargs: {kwargs!r}") + return args + + if trace_fn is joint_fwd_bwd: + # If inference mode is enabled during compilation, assume that we don't + # want to match on any training graph patterns + if torch.is_inference_mode_enabled(): + return False + + # TODO: Revisit the functionalize_rng_ops for lowmem dropout + with functorch_config.patch(functionalize_rng_ops=False): + if search_fn_pattern is None: + pattern, gm = gen_pattern_and_search_gm( + search_fn, + example_inputs, + trace_fn, + scalar_workaround, + exclusive_arg_names, + get_decomp_fn=get_decomp_fn, + ) + else: + pattern = search_fn_pattern + gm = None + + for pattern_matcher_pass in ( + pass_dicts if isinstance(pass_dicts, Sequence) else [pass_dicts] + ): + if isinstance(pattern_matcher_pass, PatternMatcherPass): + if check_and_add_duplicate_pattern( + pattern, + gm.graph if gm else None, + pattern_matcher_pass.seen_patterns, + skip_duplicates=skip_duplicates, + ): + return False + + pattern = ReplacementPatternEntry( + pattern=pattern, + extra_check=check_fn, + normalize_args=normalize_args, + pattern_name=pattern_name, + ) + pattern.register(pass_dicts) + return pattern.pattern # type: ignore[return-value] + + +_serialized_patterns: OrderedSet[str] = OrderedSet() + + +def _serialize_pattern( + unique_name: str, + search_fn: SearchFn, + example_inputs: Sequence[Any], + trace_fn: TraceFn, + scalar_workaround: dict[str, float | int] | None, +) -> PatternExpr: + def get_file_template() -> str: + auto_generated_msg = textwrap.dedent( + """\ + # This is an auto-generated file. Please do not modify it by hand. + # To re-generate, run: + # cd ~/pytorch && python torchgen/fuse/gen_patterns.py + """ + ) + + file_template = textwrap.dedent( + """\ + # noqa: F401, E501 + {msg} + import torch + import torch._inductor + import operator + + aten = torch.ops.aten + prims = torch.ops.prims + + """ + ).format(msg=auto_generated_msg) + + pattern_matcher_imports = [] + for name in dir(torch._inductor.pattern_matcher): + attr = getattr(torch._inductor.pattern_matcher, name) + try: + if isinstance(attr, type) and issubclass( + attr, (PatternExpr, _TargetExpr) + ): + # pyrefly: ignore [bad-argument-type] + pattern_matcher_imports.append(name) + except TypeError: + pass + + formatted_imports = ",\n ".join(pattern_matcher_imports) + formatted_imports = f"from torch._inductor.pattern_matcher import (\n {formatted_imports},\n)\n" + return f"{file_template}{formatted_imports}" + + if not SERIALIZED_PATTERN_PATH.is_dir(): + raise RuntimeError( + f"Could not find serialized patterns directory at {SERIALIZED_PATTERN_PATH}" + ) + + pattern_name = search_fn.__name__ + + from torch._functorch import config as functorch_config + + with functorch_config.patch(functionalize_rng_ops=False): + pattern = gen_pattern(search_fn, example_inputs, trace_fn, scalar_workaround) + + serialized_pattern = PatternPrettyPrinter.run(pattern, output_name=unique_name) + if pattern_name not in _serialized_patterns: + write_mode = "w" + _serialized_patterns.add(pattern_name) + else: + write_mode = "a" + + file_template = get_file_template() + + with open(SERIALIZED_PATTERN_PATH / f"{pattern_name}.py", write_mode) as f: + if write_mode == "w": + f.write(file_template) + else: + f.write("\n\n") + f.write(serialized_pattern) + f.write("\n") + + return pattern + + +SERIALIZED_PATTERN_PATH = Path(__file__).parent / "fx_passes" / "serialized_patterns" + + +# This is the set of serialized patterns that we've registered. Used by +# test_serialized_patterns_up_to_date() to ensure the patterns are up +# to date. +@dataclasses.dataclass +class _PrecompiledPattern: + search_fn: SearchFn + example_inputs: Sequence[Any] + trace_fn: TraceFn + scalar_workaround: dict[str, float | int] | None + search_fn_pattern: PatternExpr + + +_known_precompiled_patterns: list[_PrecompiledPattern] = [] + + +def gen_register_replacement( + unique_name: str, + search_fn: SearchFn, + replace_fn: ReplaceFn, + example_inputs: Iterable[Any], + trace_fn: TraceFn, + pass_dicts: _PassDictsType | Sequence[_PassDictsType], + extra_check: Callable[[Match], bool] = _return_true, + scalar_workaround: dict[str, float | int] | None = None, + exclusive_arg_names: Sequence[str] = (), + skip_duplicates: bool = False, + get_decomp_fn: Callable[..., dict[Any, Callable[..., Any]]] = select_decomp_table, +) -> None: + # Make sure the example_inputs is materialized. + example_inputs = tuple(example_inputs) + + if "PYTORCH_GEN_PATTERNS" in os.environ: + pat = _serialize_pattern( + unique_name, search_fn, example_inputs, trace_fn, scalar_workaround + ) + else: + pattern_name = search_fn.__name__ + m = importlib.import_module( + f"torch._inductor.fx_passes.serialized_patterns.{pattern_name}" + ) + if not m or not hasattr(m, unique_name): + log.warning( + "Precompiled pattern %r not found. Run torchgen/fuse/gen_patterns.py.", + unique_name, + ) + pat = getattr(m, unique_name) + + for arg in pytree.tree_iter(example_inputs): + if isinstance(arg, FakeTensor) and maybe_get_fake_constant(arg) is not None: # noqa: ISINSTANCE_FAKE_TENSOR + # This can be a problem - small fake tensors (e.g. `tensor(2)`) will + # hold onto their original constant value - and by stashing it here + # will cause a memory leak if the constant value is on GPU. + # Since this is just an optimization we can clear it out. + # for c++ need to add a setter + arg.constant = None + + _known_precompiled_patterns.append( + _PrecompiledPattern(search_fn, example_inputs, trace_fn, scalar_workaround, pat) + ) + register_replacement( + search_fn, + replace_fn, + example_inputs, + trace_fn, + pass_dicts, + extra_check, + scalar_workaround, + exclusive_arg_names, + search_fn_pattern=pat, + skip_duplicates=skip_duplicates, + pattern_name=unique_name, + get_decomp_fn=get_decomp_fn, + ) + + +@functorch_config.patch(functionalize_rng_ops=False) # type: ignore[misc] +def gen_pattern_and_search_gm( + search_fn: SearchFn, + example_inputs: Sequence[Any], + trace_fn: TraceFn, + scalar_workaround: dict[str, float | int] | None = None, + exclusive_arg_names: Sequence[str] = (), + get_decomp_fn: Callable[..., dict[Any, Callable[..., Any]]] = select_decomp_table, +) -> tuple[PatternExpr, torch.fx.GraphModule]: + argnames = [*inspect.signature(search_fn).parameters.keys()] + + scalar_workaround = scalar_workaround or {} + flat_inputs = _trace_args_for_initial_trace( + argnames, example_inputs, scalar_workaround + ) + arg_info = _trace_arg_info(argnames, flat_inputs) + + search_gm = trace_fn(search_fn, flat_inputs, get_decomp_fn=get_decomp_fn) + return ( + fx_to_pattern( + search_gm, + ignore_types=(int, float, list, torch.device, torch.dtype), + argnames=arg_info.flat_argnames, + scalar_workaround=scalar_workaround, + exclusive_arg_names=exclusive_arg_names, + ), + search_gm, + ) + + +def gen_pattern( + search_fn: SearchFn, + example_inputs: Sequence[Any], + trace_fn: TraceFn, + scalar_workaround: dict[str, float | int] | None = None, + exclusive_arg_names: Sequence[str] = (), +) -> PatternExpr: + return gen_pattern_and_search_gm( + search_fn, example_inputs, trace_fn, scalar_workaround, exclusive_arg_names + )[0] + + +def register_lowering_pattern( + pattern: PatternExpr, + extra_check: Callable[[Match], bool] = _return_true, + *, + pass_dict: _PassDictsType, + prepend: bool = False, + output_metadata_ignores_input_storage: bool = True, + output_metadata_is_input: int | str | None = None, + output_metadata_fn: Callable[..., Any] | None = None, +) -> Callable[[Callable[..., Any]], Callable[..., Any]]: + """ + Register an aten to inductor IR replacement pattern. The decorated + function is saved and then called at lowering time allowing direct + pattern to inductor IR conversion. + """ + + def decorator(handler: Callable[..., Any]) -> Callable[..., Any]: + if not callable(handler): + raise AssertionError(f"expected callable handler, got {handler}") + LoweringPatternEntry( + pattern=pattern, extra_check=extra_check, handler=handler + ).register(pass_dict, prepend=prepend) + handler._inductor_lowering_function = True # type: ignore[attr-defined] + handler._inductor_lowering_output_metadata_ignores_input_storage = ( # type: ignore[attr-defined] + output_metadata_ignores_input_storage + ) + handler._inductor_lowering_output_metadata_is_input = ( # type: ignore[attr-defined] + output_metadata_is_input + ) + handler._inductor_lowering_output_metadata_fn = output_metadata_fn # type: ignore[attr-defined] + return handler + + return decorator + + +def register_graph_pattern( + pattern: PatternExpr, + extra_check: Callable[[Match], bool] = _return_true, + *, + pass_dict: _PassDictsType, + prepend: bool = False, +) -> Callable[[Callable[..., Any]], Callable[..., Any]]: + """ + Register a pattern that runs a function on the FX graph, allowing + custom transformation code. + """ + + def decorator(handler: Callable[..., Any]) -> Callable[..., Any]: + if not callable(handler): + raise AssertionError(f"expected callable handler, got {handler}") + GraphPatternEntry( + pattern=pattern, extra_check=extra_check, handler=handler + ).register(pass_dict, prepend=prepend) + return handler + + return decorator + + +def is_start_of_fx_graph(graph: torch.fx.Graph, node: torch.fx.Node) -> bool: + # first node in the graph + return node is next(iter(graph.nodes)) + + +# match: copy_, relu_, _set_grad_enabled, manual_seed, _enter_autocast, etc +# doesn't match: __rshift__, etc +_mutation_op_re = re.compile(r"(? bool: + if op.namespace != "inductor": + return False + + # TODO - fix schema + # Don't add any more! + return op in (torch.ops.inductor.resize_storage_bytes_.default,) + + +def is_mutation_op(node: torch.fx.Node) -> bool: + if isinstance( + node.target, torch._ops.OpOverload + ) and not fixme_incorrect_inductor_schema_op(node.target): + return node.target._schema.is_mutable + elif isinstance( + node.target, torch._higher_order_ops.auto_functionalize.AutoFunctionalized + ): + return False + if node.op == "call_function": + if not callable(node.target): + raise AssertionError(f"expected callable node.target, got {node.target}") + if _mutation_op_re.search(node.target.__name__): + return True + elif node.op == "call_method": + if not isinstance(node.target, str): + raise AssertionError(f"expected str node.target, got {type(node.target)}") + if _mutation_op_re.search(node.target): + return True + return node.kwargs.get("out") is not None + + +def same_mutation_regions(a: torch.fx.Node, b: torch.fx.Node) -> bool: + if "mutation_region_id" not in a.meta: + raise AssertionError("mutation_region_id missing from a.meta") + if "mutation_region_id" not in b.meta: + raise AssertionError("mutation_region_id missing from b.meta") + return a.meta["mutation_region_id"] == b.meta["mutation_region_id"] + + +def get_mutation_region_id(graph: torch.fx.Graph, node: torch.fx.Node) -> int: + n = node + while "mutation_region_id" not in n.meta and not is_start_of_fx_graph(graph, n): + n = n.prev + mutation_region_id = n.meta.get("mutation_region_id", 0) + while n is not node: + n = n.next + if is_mutation_op(n): + mutation_region_id += 1 + n.meta["mutation_region_id"] = mutation_region_id + return mutation_region_id + + +def should_compute_mutation_region_ids(graph: torch.fx.Graph) -> bool: + return "mutation_region_id" not in next(iter(graph.nodes)).meta + + +def compute_mutation_region_ids(graph: torch.fx.Graph) -> None: + mutation_region_id = 0 + for nd in graph.nodes: + if is_mutation_op(nd): + mutation_region_id += 1 + nd.meta["mutation_region_id"] = mutation_region_id + + +@dataclasses.dataclass(frozen=True) +class _MutationRegionRefresh: + anchor: torch.fx.Node + stop: torch.fx.Node + mutation_region_id: int + mutation_count: int + + +@dataclasses.dataclass +class _GraphMutationTracker: + created_nodes: list[torch.fx.Node] = dataclasses.field(default_factory=list) + erased_mutation_node: bool = False + + def changed_mutation_regions(self) -> bool: + return self.erased_mutation_node or _contains_mutation_op(self.created_nodes) + + +@contextlib.contextmanager +def _track_graph_mutation_ops( + graph: torch.fx.Graph, + custom_context: dict[str, Any] | None = None, +) -> Generator[_GraphMutationTracker, None, None]: + custom_context = custom_context or {} + tracker = _GraphMutationTracker() + create_node = graph.create_node + erase_node = graph.erase_node + sentinel = object() + graph_dict = graph.__dict__ + create_node_attr = graph_dict.get("create_node", sentinel) + erase_node_attr = graph_dict.get("erase_node", sentinel) + + def tracked_create_node(*args: Any, **kwargs: Any) -> torch.fx.Node: + created_node = create_node(*args, **kwargs) + _merge_custom_context(created_node.meta, custom_context) + tracker.created_nodes.append(created_node) + return created_node + + def tracked_erase_node(to_erase: torch.fx.Node) -> Any: + if not to_erase._erased and is_mutation_op(to_erase): + tracker.erased_mutation_node = True + return erase_node(to_erase) + + graph_dict["create_node"] = tracked_create_node + graph_dict["erase_node"] = tracked_erase_node + try: + yield tracker + finally: + if create_node_attr is sentinel: + del graph_dict["create_node"] + else: + graph_dict["create_node"] = create_node_attr + if erase_node_attr is sentinel: + del graph_dict["erase_node"] + else: + graph_dict["erase_node"] = erase_node_attr + + +def _count_mutation_ops_until(start: torch.fx.Node, stop: torch.fx.Node) -> int: + mutation_count = 0 + nd = start + while nd is not stop: + if nd.op == "root": + raise AssertionError(f"unexpected root node reached: {nd}") + if is_mutation_op(nd): + mutation_count += 1 + nd = nd.next + return mutation_count + + +def _contains_mutation_op(nodes: Iterable[torch.fx.Node]) -> bool: + return any(is_mutation_op(nd) for nd in nodes) + + +def _replacement_changes_mutation_regions( + entry: ReplacementPatternEntry, match: Match +) -> bool: + if match.replacement_graph is None: + raise AssertionError("match.replacement_graph must not be None") + return _contains_mutation_op(match.nodes) or _contains_mutation_op( + match.replacement_graph.graph.nodes + ) + + +def _mutation_region_refresh( + graph: torch.fx.Graph, + nodes: Sequence[torch.fx.Node], +) -> _MutationRegionRefresh: + if nodes: + first_matched_node = min(nodes) + last_matched_node = max(nodes) + anchor = first_matched_node.prev + stop = last_matched_node.next + else: + first_node = next(iter(graph.nodes)) + anchor = first_node.prev + stop = anchor + + mutation_region_id = ( + 0 if anchor.op == "root" else get_mutation_region_id(graph, anchor) + ) + return _MutationRegionRefresh( + anchor, + stop, + mutation_region_id, + _count_mutation_ops_until(anchor.next, stop), + ) + + +def _refresh_mutation_region_ids( + graph: torch.fx.Graph, + refresh: _MutationRegionRefresh, +) -> None: + if refresh.anchor._erased or refresh.stop._erased: + compute_mutation_region_ids(graph) + return + + nd = refresh.anchor.next + mutation_region_id = refresh.mutation_region_id + mutation_count = 0 + while nd is not refresh.stop: + if nd.op == "root": + compute_mutation_region_ids(graph) + return + if is_mutation_op(nd): + mutation_region_id += 1 + mutation_count += 1 + nd.meta["mutation_region_id"] = mutation_region_id + nd = nd.next + + if mutation_count == refresh.mutation_count: + return + + while nd.op != "root": + if is_mutation_op(nd): + mutation_region_id += 1 + nd.meta["mutation_region_id"] = mutation_region_id + nd = nd.next + + +def _wrap_bound_method(fn: Any, argnames: list[str]) -> Any: + """ + Wrap a bound method to remove 'self' from its signature for FX tracing. + """ + + def wrapper(*args: Any, **kwargs: Any) -> Any: + return fn(*args, **kwargs) + + params = [ + inspect.Parameter(name, inspect.Parameter.POSITIONAL_OR_KEYWORD) + for name in argnames + ] + wrapper.__signature__ = inspect.Signature(params) # type: ignore[attr-defined] + return wrapper + + +class PatternMatcherPass: + """ + Registry of patterns to match and replace in FX graphs. + """ + + def __init__( + self, + pass_name: str | None = None, + subsystem: str | None = None, + ) -> None: + super().__init__() + self.patterns: defaultdict[ + tuple[str, torch.fx.node.Target], list[PatternEntry] + ] = defaultdict(list) + self.pass_name = pass_name + self.subsystem = subsystem + + # For a particular generated pattern repr, store all of the str representations + # of the graph used to generate them. Because we ignore certain patterns + # in searching, but not in matching, use the graph to distinguish if two equivalent + # searches are actually different. + self.seen_patterns: dict[str, list[str | None]] = defaultdict(list) + + def __getitem__(self, item: tuple[str, torch.fx.node.Target]) -> list[PatternEntry]: + return self.patterns[item] + + def apply(self, gm: torch.fx.GraphModule | torch.fx.Graph) -> int: + """Apply all registered patterns to the graph, returning the number of matches.""" + if not self.patterns: + return 0 + if isinstance(gm, torch.fx.GraphModule): + graph = gm.graph + elif isinstance(gm, torch.fx.Graph): + graph = gm + gm = graph.owning_module # type: ignore[assignment] + else: + raise RuntimeError( + f"The input to PatternMatcherPass must be a GraphModule or a Graph, but got {type(gm)}" + ) + if should_compute_mutation_region_ids(graph): + compute_mutation_region_ids(graph) + get_mutation_region_id_partial = functools.partial( + get_mutation_region_id, graph + ) + count = 0 + nodes = [] + has_call_module = False + for op, target in self.patterns: + if op == "call_module": + has_call_module = True + else: + nodes.append(graph.find_nodes(op=op, target=target, sort=False)) + if has_call_module: + nodes.append(graph.find_nodes(op="call_module", sort=False)) + pass_name = self.pass_name if self.pass_name is not None else "pattern_matcher" + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"expected GraphModule, got {type(gm)}") + with GraphTransformObserver(gm, pass_name, self.subsystem): + for node in sorted(itertools.chain.from_iterable(nodes), reverse=True): + target = extract_target(node) + if node.op == "call_module": + if (node.op, target) not in self.patterns: + continue + + # conservatively not applying pattern for cpu input, + # since some of the patterns induce codegen and split nodes. + # Note: we will only skip cpu compute if disable_cpp_codegen=True + if fallback_node_due_to_unsupported_type(node, allow_cpu_inputs=False): + continue + + for entry in self.patterns[(node.op, target)]: + if node._erased: + break + m = entry.pattern.match(node) + # pattern match crosses mutation barrier - discard + if ( + is_match(m) + and len( + OrderedSet(map(get_mutation_region_id_partial, m.nodes)) + ) + != 1 + ): + continue + # pattern match crosses stream boundary - discard + if ( + is_match(m) + and len( + OrderedSet( + ( + n.meta.get("custom", {}).get("stream", 0), + n.meta.get("custom", {}).get("mempool"), + n.meta.get("custom", {}).get("mempool_device"), + ) + for n in m.nodes + ) + ) + != 1 + ): + continue + if _should_debug_node(node.name): + log.warning("%s%s %s %s", node, node.args, m, entry.pattern) + + if is_match(m) and guard_or_false(entry.extra_check(m)): + count += 1 + if isinstance(entry, ReplacementPatternEntry): + mutation_region_refresh = ( + _mutation_region_refresh(graph, m.nodes) + if _replacement_changes_mutation_regions(entry, m) + else None + ) + elif isinstance(entry, GraphPatternEntry): + mutation_region_refresh = None + else: + mutation_region_refresh = _mutation_region_refresh( + graph, m.nodes + ) + if isinstance(entry, GraphPatternEntry): + with _track_graph_mutation_ops( + graph, _common_custom_context(m.nodes) + ) as mutation_tracker: + entry.apply(m, graph, node) + if mutation_tracker.changed_mutation_regions(): + compute_mutation_region_ids(graph) + elif mutation_region_refresh is not None: + entry.apply(m, graph, node) + _refresh_mutation_region_ids(graph, mutation_region_refresh) + else: + entry.apply(m, graph, node) + counters[backend]["pattern_matcher_count"] += 1 + counters[backend]["pattern_matcher_nodes"] += len(m.nodes) + + # Track per-pattern counts when debug mode is active + if os.environ.get("TORCHINDUCTOR_PATTERN_MATCH_DEBUG"): + if getattr(entry, "pattern_name", None): + pattern_name = entry.pattern_name + else: + # Fallback: use pattern class name + operation target + pattern_class = entry.pattern.__class__.__name__ + target = str(node.target) + pattern_name = f"{pattern_class}_{target}" + + pattern_key = f"{backend}_pattern_matcher_per_pattern" + counters[pattern_key][pattern_name] += 1 + return count + + def clear(self) -> None: + self.patterns.clear() + + +def _not_implemented(*args: Any, **kwargs: Any) -> NoReturn: + raise NotImplementedError + + +def fx_to_pattern( + gm: torch.fx.GraphModule | torch.fx.Graph, + ignore_types: Sequence[type[Any]] = (), + argnames: Sequence[str] = (), + scalar_workaround: dict[str, float | int] | None = None, + exclusive_arg_names: Sequence[str] = (), +) -> PatternExpr: + """ + Convert an FX graph into a PatternExpr. This is useful for simple + patterns that can only match single functions and fixed-length lists. + """ + # scalar_workaround is a hack to capture dropout_p + # see https://github.com/pytorch/pytorch/issues/97894 + scalar_workaround = scalar_workaround or {} + inv_scalar_workaround = {v: k for k, v in scalar_workaround.items()} + if len(inv_scalar_workaround) != len(scalar_workaround): + raise AssertionError("scalar_workaround has duplicate values") + + def process_arg( + x: T, ignore_types_override: Sequence[type[Any]] | None = None + ) -> T | KeywordArg | Ignored: + current_ignore_types = ( + ignore_types_override if ignore_types_override is not None else ignore_types + ) + if isinstance(x, (float, int)) and x in inv_scalar_workaround: + return KeywordArg(inv_scalar_workaround[x]) + if type(x) in current_ignore_types: + return Ignored() + if isinstance(x, list) and all(isinstance(y, Ignored) for y in x) and x: + return Ignored() + return x + + argnum = itertools.count() + + class Converter(torch.fx.Interpreter): + # pyrefly: ignore [bad-override] + call_method = _not_implemented + # pyrefly: ignore [bad-override] + call_module = _not_implemented + + # pyrefly: ignore [bad-override] + def placeholder( + self, + target: str, # type: ignore[override] + args: Sequence[Any], + kwargs: Mapping[str, Any], + ) -> ExclusiveKeywordArg | KeywordArg: + n = next(argnum) + if n < len(argnames): + name = argnames[n] + elif argnames: + if not target.startswith("tangent"): + raise AssertionError( + f"expected target to start with 'tangent', got {target}" + ) + name = target + else: + target = re.sub(r"_\d+$", "", target) # de-mangle arg name + name = target + if name in exclusive_arg_names: + return ExclusiveKeywordArg(name) + else: + return KeywordArg(name) + + # pyrefly: ignore [bad-override] + def get_attr( + self, + target: str, # type: ignore[override] + args: Sequence[Any], + kwargs: Mapping[str, Any], + ) -> GetAttr: + if args or kwargs: + raise AssertionError(f"unexpected get_attr args: {args}, {kwargs}") + return GetAttr(_get_attr(self.module, target)) + + # pyrefly: ignore [bad-override] + def call_function( + self, + target: str, # type: ignore[override] + args: Sequence[Any], + kwargs: Mapping[str, Any], + ) -> PatternExpr: + process_arg_fn = process_arg + # Indexing is critical for matching getitem nodes, so we can't ignore int args here + if target is operator.getitem: + + def process_arg_fn_impl( + x: T, + ignore_types_override: Sequence[type[Any]] | None = tuple( + t for t in ignore_types if t is not int + ), + ) -> T | KeywordArg | Ignored: + return process_arg(x, ignore_types_override) + + process_arg_fn = process_arg_fn_impl + + args, kwargs = pytree.tree_map(process_arg_fn, (args, kwargs)) + if list in ignore_types: + # Handle a burned in tensor size which are now [Ignored(), Ignored(), ...] + args = [process_arg_fn(a) for a in args] + kwargs = {k: process_arg_fn(a) for k, a in kwargs.items()} + return CallFunction(target, *args, **kwargs) + + def run_node(self, n: torch.fx.Node) -> Any: + rv = super().run_node(n) + if n.op == "output" and isinstance(rv, tuple): + args = n.args[0] + if not isinstance(args, Collection): + raise AssertionError(f"expected Collection, got {type(args)}") + if len(rv) != len(args): + raise AssertionError("rv and args length mismatch") + for r, arg in zip(rv, args): + # pyrefly: ignore [missing-attribute] + r.users = len(arg.users) + else: + rv.users = len(n.users) + return rv + + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"expected GraphModule, got {type(gm)}") + pattern = Converter(gm).run() + if not isinstance(pattern, PatternExpr): + return MultiOutputPattern(pytree.tree_leaves(pattern)) + return pattern + + +@torch.no_grad() +def fwd_only( + fn: Callable[..., Any], + args: Sequence[Any], + *, + run_functional_passes: bool = True, + get_decomp_fn: Callable[..., Any] = select_decomp_table, +) -> torch.fx.GraphModule: + """Build a normalized inference graph, for use with fx_to_pattern""" + from torch.compiler import config as compiler_config + + # Patterns are device-agnostic templates traced with fixed example tensors; keep the + # compile-on-one-rank device handling out of pattern tracing so make_fx's single-device + # check only validates real user graphs, not these internal fixed-device templates. + # TODO - look into using aot autograd, asserting no mutating ops here + with ( + # pyrefly: ignore [missing-attribute] + compiler_config.patch(compile_on_one_rank=False), + enable_python_dispatcher(), + preserve_node_meta(), + ): + gm = make_fx(fn, get_decomp_fn(), tracing_mode="real")(*args) + + from .fx_passes.post_grad import remove_noop_ops + + if run_functional_passes: + remove_noop_ops(gm.graph) + + # NOTE: applying early_patterns to user patterns cause + # duplicate patterns being found in vllm. Check + # https://github.com/pytorch/pytorch/pull/170649#issuecomment-3693427775 + # for more details. + # from .fx_passes.joint_graph import early_patterns + # early_patterns.apply(gm.graph) + + gm.graph.eliminate_dead_code() + + gm.recompile() + return gm + + +@torch.enable_grad() +def joint_fwd_bwd( + fn: Callable[..., Any], + args: Sequence[Any], + *, + get_decomp_fn: Callable[..., Any] = select_decomp_table, +) -> torch.fx.GraphModule: + """Build a normalized training graph, for use with fx_to_pattern""" + gm: torch.fx.GraphModule | None = None + + def record_joint_graph( + joint_graph: torch.fx.GraphModule, inputs: Sequence[Any], **kwargs: Any + ) -> tuple[torch.fx.GraphModule, torch.fx.GraphModule]: + nonlocal gm + if gm: + raise AssertionError("gm already set") + gm = clone_graph(joint_graph) + return default_partition(joint_graph, inputs, **kwargs) + + from torch.compiler import config as compiler_config + + # Keep compile-on-one-rank device handling out of pattern tracing (see fwd_only). + # pyrefly: ignore [missing-attribute] + with torch._guards.tracing(None), compiler_config.patch(compile_on_one_rank=False): + aot_function( + fn, + # pyrefly: ignore[bad-argument-type] + lambda gm, example_inputs: make_boxed_func(gm), + partition_fn=record_joint_graph, + decompositions=get_decomp_fn(), + keep_inference_input_mutations=True, + enable_log=False, + )(*args) + if not gm: + raise AssertionError("gm was not set") + + from .fx_passes.post_grad import remove_noop_ops + + remove_noop_ops(gm.graph) + + from .fx_passes.joint_graph import early_patterns + + early_patterns.apply(gm.graph) + + # remove in/out specs + gm.graph._codegen = torch.fx.graph.CodeGen() + gm.graph.eliminate_dead_code() + gm.recompile() + return gm + + +def _args(n: torch.fx.Node) -> list[torch.fx.node.Argument]: + args: list[torch.fx.node.Argument] = [] + torch.fx.map_arg((n.args, n.kwargs), args.append) + return args + + +def stable_topological_sort(graph: torch.fx.Graph) -> None: + # Nodes are in exactly one of these three collections: + + # - Nodes in `pending` are waiting to be processed (in reverse order): + pending = list(reversed(graph.nodes)) + + # - Nodes in `ready` have been processed and are already in the correct + # order. + ready = OrderedSet[torch.fx.Node]() + + # - `waiting` is a mapping from a dependency to nodes which depend on that + # dependency. + waiting = defaultdict(list) + + # The cursor indicates the last processed node so we can add new nodes + # after it. + cursor = None + while pending: + node = pending.pop() + waiting_for = [x for x in _args(node) if x not in ready] + if waiting_for: + # We have unprocessed input nodes. Might as well wait for the last + # arg so an already sorted list will only recheck this node once. + waiting[waiting_for[-1]].append(node) + else: + ready.add(node) + if cursor and cursor.next is not node: + cursor.append(node) + cursor = node + # Mark the nodes that have been waiting for this node to finish as + # ready to check again. + pending.extend(reversed(waiting.pop(node, ()))) + + if not (not waiting and len(ready) == len(graph.nodes)): + raise AssertionError("topological sort did not consume all nodes") + + +def init_once_fakemode(fn: Callable[..., Any]) -> Callable[..., Any]: + """Wrapper around lazy init functions in fx_passes/""" + + _fn_params = inspect.signature(fn).parameters + + @functools.cache + @functools.wraps(fn) + def lazy_init( + input_device: Any | None = None, + get_decomp_fn: Callable[ + ..., dict[Any, Callable[..., Any]] + ] = select_decomp_table, + ) -> Any: + counters_ref = counters[backend].copy() + + kwargs: dict[str, Any] = {} + if "input_device" in _fn_params: + kwargs["input_device"] = input_device + if "get_decomp_fn" in _fn_params: + kwargs["get_decomp_fn"] = get_decomp_fn + + with torch._guards.tracing(None), unset_fake_temporarily(), FakeTensorMode(): + result = fn(**kwargs) + + # clear view matches encountered during tracing + counters[backend] = counters_ref + + return result + + return lazy_init + + +def config_flag(name: str) -> Callable[[Match], Any]: + """Function for extra_check to put pass behind a flag""" + + def flag_check(match: Match) -> Any: + return getattr(config, name) + + return flag_check + + +def clone_graph(input_graph: torch.fx.GraphModule) -> torch.fx.GraphModule: + class CopyGraph(Transformer): + def run_node(self, old_node: torch.fx.Node) -> torch.fx.Node: + new_node = super().run_node(old_node) + if isinstance(new_node, torch.fx.Proxy): + new_node.node.meta.update(old_node.meta) + new_node.node.name = self.new_graph._graph_namespace.create_name( + old_node.name, None + ) + + return new_node + + return CopyGraph(input_graph).transform() + + +# TODO: remove in follow up diff, used internally +_seen_patterns: OrderedSet[str] = OrderedSet() + + +def get_arg_value( + node: torch.fx.Node, arg_number: int, kwarg_name: str | None = None +) -> Any: + if len(node.args) > arg_number: + return node.args[arg_number] + elif kwarg_name is None: + return None + else: + return node.kwargs.get(kwarg_name) + + +def filter_nodes(nodes: Iterable[torch.fx.Node], fn: Any) -> list[torch.fx.Node]: + fns = [fn] + if isinstance(fn, torch._ops.OpOverloadPacket): + fns.extend(fn.op_overloads()) + + return [node for node in nodes if node.target in fns] + + +def extract_target(node: torch.fx.Node) -> torch.fx.node.Target: + """For call_function and call_method, we directly use the target function; + For call_module, the target is string, and we treat the module class + as a function. + """ + if node.op == "call_module": + if not isinstance(node.target, str): + raise AssertionError(f"expected str node.target, got {type(node.target)}") + if node.graph.owning_module is None: + raise AssertionError("node.graph.owning_module must not be None") + return _get_attr(node.graph.owning_module, node.target).__class__ + return node.target diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/profiler.py b/.venv/lib/python3.12/site-packages/torch/_inductor/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa06161c69db1e4d7731cd9fe1d39776a5bc4f8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/profiler.py @@ -0,0 +1,512 @@ +# mypy: allow-untyped-defs +import ast +import gzip +import json +import logging +import os +import re +import tempfile +from bisect import bisect_left +from collections import defaultdict +from typing import Any + +import torch._inductor.config as inductor_config +from torch.utils._ordered_set import OrderedSet + + +__all__ = ["inductor_trace_handler"] + +log = logging.getLogger(__name__) + +# https://github.com/pytorch/kineto/blob/a054a4be0db117c579a21747debf19c863631f26/libkineto/src/output_json.cpp#L559 +# Kernel and CUDA runtime API events are connected by ac2g; forward and backward +# ATen ops are connected by fwdbwd. +_profile_flow_types = OrderedSet(["fwdbwd", "ac2g"]) + + +class _EventItem: + def __init__(self, event): + self.e = event + self.start, self.end = self._interval_of() + + def _interval_of(self): + start = self.e["ts"] + duration = self.e.get("dur", 0) + return start, start + duration + + +def _find_events_covered_in( + events: list[dict[str, Any]], + top_level_events: list[dict[str, Any]], +): + """Find events covered in top level events. + + Returns a dict mapping top-level event uid to covered event uids. + """ + top_level_by_tid = defaultdict(list) + for event in top_level_events: + top_level_by_tid[event["tid"]].append(_EventItem(event)) + for tid in top_level_by_tid: + top_level_by_tid[tid] = sorted(top_level_by_tid[tid], key=lambda x: x.start) + starts_by_tid = { + tid: [event.start for event in event_items] + for tid, event_items in top_level_by_tid.items() + } + top_level_id_to_events = defaultdict(OrderedSet) + + for event in events: + if event.get("cat") not in { + "cuda_runtime", + "cuLaunchKernel", + "cpu_op", + "cuda_driver", + "gpu_memset", + "python_function", + }: + continue + if "CallFrom" in event.get("args", {}): + continue + tid = event.get("tid") + if tid not in top_level_by_tid: + continue + item = _EventItem(event) + event_items = top_level_by_tid[tid] + idx = bisect_left(starts_by_tid[tid], item.start) - 1 + if idx < 0 or idx >= len(event_items): + continue + top_level_item = event_items[idx] + if top_level_item.start <= item.start and item.end <= top_level_item.end: + top_level_id_to_events[top_level_item.e["uid"]].add(event["uid"]) + return top_level_id_to_events + + +class _InductorTraceProcessor: + def _assign_uniq_id_to_event(self, trace): + if trace.get("uid_assigned"): + return {event["uid"]: event for event in trace["traceEvents"]} + uid_2_events = {} + for uid, event in enumerate(trace["traceEvents"]): + event["uid"] = uid + uid_2_events[uid] = event + trace["uid_assigned"] = True + return uid_2_events + + def _build_flow_mapping(self, trace, flow_events): + """Build src/dst event mappings from profiler flow events.""" + if not flow_events: + return {}, {} + + flow_pair: dict[int, list[int | None]] = {} + prev_event = None + for event in trace["traceEvents"]: + if ( + event.get("name") not in _profile_flow_types + and event.get("cat") not in _profile_flow_types + ): + prev_event = event + continue + if event.get("ph") == "s": + if prev_event is None: + continue + pair = flow_pair.setdefault(int(event["id"]), [None, None]) + pair[0] = prev_event["uid"] + elif event.get("ph") == "f": + if prev_event is None: + continue + pair = flow_pair.setdefault(int(event["id"]), [None, None]) + pair[1] = prev_event["uid"] + prev_event = event + + src2dst = {} + dst2src = {} + for src, dst in flow_pair.values(): + if src is None or dst is None: + continue + src2dst[src] = dst + dst2src[dst] = src + return src2dst, dst2src + + def _maybe_triton_call(self, kernel_name): + return kernel_name.startswith("triton_") + + def _has_kernel_info(self, compile_info, graph_key, kernel_name): + graph_info = compile_info.get(graph_key, {}) + if kernel_name in graph_info: + return True + kernel_prefix = kernel_name + ":" + return any(name.startswith(kernel_prefix) for name in graph_info) + + def _maybe_extern_call(self, event, compile_info, fwd_key, bw_keys, need_bw): + kernel_name = event["name"] + return not self._has_kernel_info(compile_info, fwd_key, kernel_name) and ( + not need_bw + or all( + not self._has_kernel_info(compile_info, bw_key, kernel_name) + for bw_key in bw_keys + ) + ) + + def add_to_chrome_trace(self, origin_trace): + """Add Inductor kernel stack information to a Chrome trace.""" + from torch._inductor.debug import get_kernel_information_jsons + + compile_linenos = get_kernel_information_jsons() + if not compile_linenos: + return origin_trace + + trace = origin_trace + uid_2_events = self._assign_uniq_id_to_event(trace) + + real_events = [] + flow_events = [] + compiled_events = [] + extern_events = [] + for event in trace["traceEvents"]: + name = event.get("name", "") + cat = event.get("cat", "") + if name in _profile_flow_types or cat in _profile_flow_types: + flow_events.append(event) + continue + + real_events.append(event) + if cat == "cpu_op" and ( + name == "CompiledFunctionBackward" or "Torch-Compiled Region" in name + ): + compiled_events.append(event) + if ( + name + and "extern_kernels" in name + and cat + in ( + "cpu_op", + "python_function", + ) + ): + extern_events.append(event) + + compiled_events = sorted(compiled_events, key=lambda x: _EventItem(x).start) + compiled_event_items = [_EventItem(event) for event in compiled_events] + compiled_event_starts = [item.start for item in compiled_event_items] + ops_in_compile_region = _find_events_covered_in(real_events, compiled_events) + ops_in_extern_region = _find_events_covered_in(real_events, extern_events) + src2dst, dst2src = self._build_flow_mapping(trace, flow_events) + kernel_uids_by_external_id = defaultdict(list) + for event in real_events: + if event.get("cat") != "kernel": + continue + external_id = event.get("args", {}).get("External id") + if external_id is not None: + kernel_uids_by_external_id[external_id].append(event["uid"]) + + def _related_compile_region(compile_event): + src_event = uid_2_events[dst2src[compile_event["uid"]]] + src_item = _EventItem(src_event) + idx = bisect_left(compiled_event_starts, src_item.start) - 1 + # Compiled regions are expected to be nearly nested around their + # source events, so the nearest preceding region usually matches. + while idx >= 0: + region_item = compiled_event_items[idx] + if ( + src_item.start > region_item.start + and src_item.end < region_item.end + ): + return region_item.e + idx -= 1 + raise ValueError(f"Cannot find compile region for {compile_event}") + + def _parse_compile_region_key(key): + try: + parsed_key = ast.literal_eval(key) + except (SyntaxError, ValueError): + return None + if ( + not isinstance(parsed_key, tuple) + or len(parsed_key) != 2 + or not isinstance(parsed_key[0], str) + or not isinstance(parsed_key[1], bool) + ): + return None + return parsed_key + + def _backward_graph_keys(compile_info, compile_name): + bw_graph_key = str((compile_name, True)) + keys = [bw_graph_key] + if bw_graph_key in compile_info: + return keys + + prefix = compile_name + "_" + for key, info in compile_info.items(): + if not info: + continue + parsed_key = _parse_compile_region_key(key) + if parsed_key is None: + continue + graph_name, is_backward = parsed_key + if is_backward and graph_name.startswith(prefix): + keys.append(key) + return keys + + def _stack_from_kernel_info(kernel_info): + if isinstance(kernel_info, dict): + return kernel_info.get("stack_traces") + return kernel_info + + def _stack_for_kernel(compile_info, graph_key, kernel_name): + graph_info = compile_info.get(graph_key, {}) + kernel_info = graph_info.get(kernel_name) + if kernel_info is None: + kernel_prefix = kernel_name + ":" + for name, info in graph_info.items(): + if name.startswith(kernel_prefix): + kernel_info = info + break + return _stack_from_kernel_info(kernel_info) + + def _single_stack_for_graph(compile_info, graph_key): + stacks = [ + stack + for stack in ( + _stack_from_kernel_info(kernel_info) + for kernel_info in compile_info.get(graph_key, {}).values() + ) + if stack is not None + ] + if len(stacks) == 1: + return stacks[0] + return None + + def _assign_stack(event, compile_info, fwd_key, bw_keys, kernel_name): + for bw_key in bw_keys: + stack = _stack_for_kernel(compile_info, bw_key, kernel_name) + if stack is not None: + event.setdefault("args", {})["stack"] = stack + return True + stack = _stack_for_kernel(compile_info, fwd_key, kernel_name) + if stack is not None: + event.setdefault("args", {})["stack"] = stack + return True + return False + + def _assign_single_stack(event, compile_info, fwd_key, bw_keys): + for bw_key in bw_keys: + stack = _single_stack_for_graph(compile_info, bw_key) + if stack is not None: + event.setdefault("args", {})["stack"] = stack + return True + stack = _single_stack_for_graph(compile_info, fwd_key) + if stack is not None: + event.setdefault("args", {})["stack"] = stack + return True + return False + + def _kernel_events_for_op(op_id): + if op_id in src2dst: + return [uid_2_events[src2dst[op_id]]] + external_id = uid_2_events[op_id].get("args", {}).get("External id") + if external_id is None: + return [] + return [ + uid_2_events[kernel_uid] + for kernel_uid in kernel_uids_by_external_id.get(external_id, []) + ] + + def _extern_kernel_name(name): + match = re.search(r"\b(extern\w+)\s*,", name) + return match.group(1) if match else name + + for compile_func_id, scoped_ops in ops_in_compile_region.items(): + compile_event = uid_2_events[compile_func_id] + compile_name = compile_event["name"] + need_bw = "Backward" in compile_name + + if need_bw: + try: + compile_name = _related_compile_region(compile_event)["name"] + except ValueError: + continue + + fw_graph_key = str((compile_name, False)) + bw_graph_keys = _backward_graph_keys(compile_linenos, compile_name) + if fw_graph_key not in compile_linenos and all( + bw_graph_key not in compile_linenos for bw_graph_key in bw_graph_keys + ): + continue + + for op_id in scoped_ops: + kernel_events = _kernel_events_for_op(op_id) + if not kernel_events: + continue + for kernel_event in kernel_events: + assigned_stack = False + warn_if_unrecognized = False + if self._maybe_extern_call( + kernel_event, + compile_linenos, + fw_graph_key, + bw_graph_keys, + need_bw, + ): + for extern_call, related_ops in ops_in_extern_region.items(): + if op_id in related_ops: + extern_event = uid_2_events[extern_call] + assigned_stack = _assign_stack( + kernel_event, + compile_linenos, + fw_graph_key, + bw_graph_keys, + _extern_kernel_name(extern_event.get("name", "")), + ) + if assigned_stack: + break + if not assigned_stack: + assigned_stack = _assign_single_stack( + kernel_event, + compile_linenos, + fw_graph_key, + bw_graph_keys, + ) + elif not self._maybe_triton_call(kernel_event.get("name", "")): + warn_if_unrecognized = True + assigned_stack = _assign_single_stack( + kernel_event, + compile_linenos, + fw_graph_key, + bw_graph_keys, + ) + else: + assigned_stack = _assign_stack( + kernel_event, + compile_linenos, + fw_graph_key, + bw_graph_keys, + kernel_event.get("name", ""), + ) + if not assigned_stack and warn_if_unrecognized: + log.warning( + "Kernel %s cannot be recognized as a custom kernel or triton kernel. " + "Please try profile with stack=True.", + kernel_event.get("name", ""), + ) + return trace + + +def _add_inductor_provenance(path): + from torch._inductor.debug import get_kernel_information_jsons + + try: + # Kineto owns the initial serialization path. Re-read the exported + # trace here so timeline provenance stays decoupled from Kineto's + # JSON writer and remains a Python-only post-processing step. + with open(path) as f: + trace = json.load(f) + + num_events = len(trace.get("traceEvents", [])) + max_events = inductor_config.trace.provenance_tracking_max_events + if max_events > 0 and num_events > max_events: + log.warning( + "Skipping provenance tracking: trace has %d events " + "(exceeds limit of %d). Set TORCH_COMPILE_DEBUG_MAX_EVENTS=0 " + "to disable this protection or increase the limit.", + num_events, + max_events, + ) + return + + if not inductor_config.triton.unique_kernel_names: + log.warning( + "Profiling trace does not contain Triton kernel stack traces " + "because TORCHINDUCTOR_UNIQUE_KERNEL_NAMES=0." + ) + if inductor_config.cpp_wrapper: + log.warning( + "Profiling trace does not contain compiled kernel stack traces " + "because cpp_wrapper is enabled." + ) + return + try: + log.info("Add stack trace to compiled kernel.") + trace = _InductorTraceProcessor().add_to_chrome_trace(trace) + with open(path, "w") as f: + json.dump(trace, f, indent=1) + except MemoryError: + log.error( + "MemoryError during add_to_chrome_trace. " + "Try increasing TORCH_COMPILE_DEBUG_MAX_EVENTS or disable provenance tracking." + ) + raise + except Exception: + log.exception("Failed to add stack trace to compiled kernel") + finally: + get_kernel_information_jsons().clear() + + +def inductor_trace_handler( + dir_name: str, + worker_name: str | None = None, + use_gzip: bool = False, + use_python_export: bool = False, +): + """ + Outputs tracing files with Inductor provenance to dir_name. + + Provenance tracking must also be enabled with TORCH_COMPILE_DEBUG_EXTEND=1 + or trace.provenance_tracking_to_timeline=True. + """ + import socket + import time + + from torch.profiler import kineto_available + + def handler_fn(prof) -> None: + nonlocal worker_name + if not os.path.isdir(dir_name): + try: + os.makedirs(dir_name, exist_ok=True) + except Exception as e: + raise RuntimeError("Can't create directory: " + dir_name) from e + if not worker_name: + worker_name = f"{socket.gethostname()}_{os.getpid()}" + file_name = f"{worker_name}.{time.time_ns()}.pt.trace.json" + if use_gzip: + file_name = file_name + ".gz" + path = os.path.join(dir_name, file_name) + provenance_enabled = ( + kineto_available() and inductor_config.trace.provenance_tracking_to_timeline + ) + + if getattr(prof, "_use_cupti_monitor", False): + observer = getattr(prof, "_cupti_profiler_observer", None) + has_monitor_export = ( + observer is not None + and observer.available + and getattr(prof, "_monitor_window_id", None) is not None + ) + prof.export_chrome_trace( + path, + use_python_export=use_python_export, + ) + if provenance_enabled and has_monitor_export: + from torch._inductor.debug import get_kernel_information_jsons + + get_kernel_information_jsons().clear() + return + + if use_gzip: + with tempfile.NamedTemporaryFile("w+b", suffix=".json") as fp: + prof.export_chrome_trace( + fp.name, + use_python_export=use_python_export, + ) + if provenance_enabled: + _add_inductor_provenance(fp.name) + with open(fp.name, "rb") as fin, gzip.open(path, "wb") as fout: + fout.writelines(fin) + else: + prof.export_chrome_trace( + path, + use_python_export=use_python_export, + ) + if provenance_enabled: + _add_inductor_provenance(path) + + return handler_fn diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/quantized_lowerings.py b/.venv/lib/python3.12/site-packages/torch/_inductor/quantized_lowerings.py new file mode 100644 index 0000000000000000000000000000000000000000..2f34fef147495ec9e3a29d97f57ae4290aaba596 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/quantized_lowerings.py @@ -0,0 +1,185 @@ +import logging +from typing import Any + +import torch +from torch._inductor.kernel.mm_common import mm_args + +from . import config +from .codegen.cpp_gemm_template import CppGemmTemplate, CppWoqInt4GemmTemplate +from .codegen.cpp_utils import create_epilogue_with_attr +from .mkldnn_ir import WeightInt4PackMatmul +from .select_algorithm import ( + autotune_select_algorithm, + ExternKernelChoice, + realize_inputs, +) +from .utils import use_aten_gemm_kernels, use_cpp_gemm_template +from .virtualized import V + + +log = logging.getLogger(__name__) + +aten__weight_int8pack_mm = ExternKernelChoice( + torch._weight_int8pack_mm, "at::_weight_int8pack_mm", has_out_variant=False +) + +aten__weight_int4pack_mm_cpu = ExternKernelChoice( + torch.ops.quantized.int4mm_packed_weight_cpu, + "at::native::_weight_int4pack_mm_cpu_tensor", + has_out_variant=False, + kernel_creator=WeightInt4PackMatmul.create, +) + +quantized = torch.ops.quantized +_quantized = torch.ops._quantized +aten = torch.ops.aten + + +def register_quantized_ops() -> None: + from . import lowering + + lowering.add_needs_realized_inputs( + [ + quantized.max_pool2d, + _quantized.wrapped_fbgemm_pack_gemm_matrix_fp16, + _quantized.wrapped_fbgemm_linear_fp16_weight, + ] + ) + lowering.make_fallback(quantized.max_pool2d) + lowering.make_fallback(_quantized.wrapped_fbgemm_pack_gemm_matrix_fp16) + lowering.make_fallback(_quantized.wrapped_fbgemm_linear_fp16_weight) + + +def register_woq_mm_ops() -> None: + """Register weight-only quantized matmul lowerings.""" + from . import lowering + from .lowering import expand, register_lowering + + @register_lowering(aten._weight_int8pack_mm, type_promotion_kind=None) # type: ignore[misc] + def int8pack_mm( + input: torch.Tensor, + weight: torch.Tensor, + scale: torch.Tensor, + *, + layout: Any = None, + ) -> Any: + _, _, _, layout, mat1, mat2 = mm_args( + input, weight, layout=layout, mat2_transposed=True + ) + if not ( + mat1.get_dtype() in [torch.bfloat16, torch.float16, torch.float] + and mat2.get_dtype() == torch.int8 + ): + raise AssertionError( + f"expected mat1 dtype in [bfloat16, float16, float] and mat2 dtype " + f"int8, got {mat1.get_dtype()} and {mat2.get_dtype()}" + ) + aten_layout = layout + + # options to tune from + choices = ( + [aten__weight_int8pack_mm.bind((mat1, mat2, scale), aten_layout)] + if use_aten_gemm_kernels() + else [] + ) + + # scale is applied as an epilogue, and the scale tensor is expanded (with a view op) + # for broadcasting, as it's 1D. + def _mul_epilogue(buf: torch.Tensor) -> Any: + return create_epilogue_with_attr( + buf, "mul", other=realize_inputs(expand(scale, layout.size)) + ) + + if use_cpp_gemm_template(aten_layout, mat1, mat2, mat2_transposed=True): + CppGemmTemplate.add_choices( + choices, + aten_layout, + [mat1, mat2, scale], + trans_w=True, + epilogue_creator=_mul_epilogue, # type: ignore[arg-type] + ) + + node, _ = autotune_select_algorithm( + "_weight_int8pack_mm", choices, [mat1, mat2, scale], aten_layout + ) + return node + + @register_lowering(aten._weight_int4pack_mm_for_cpu, type_promotion_kind=None) # type: ignore[misc] + def int4pack_mm_cpu( + input: torch.Tensor, + weight: torch.Tensor, + qGroupSize: int, + qScaleAndZeros: torch.Tensor, + *, + layout: Any = None, + ) -> Any: + _, _, _, layout, mat1, mat2 = mm_args( + input, weight, layout=layout, use_4x2_dim=True, mat2_transposed=True + ) + if not ( + mat1.get_dtype() in [torch.bfloat16, torch.float16, torch.float] + and mat2.get_dtype() == torch.uint8 + ): + raise AssertionError( + f"expected mat1 dtype in [bfloat16, float16, float] and mat2 dtype " + f"uint8, got {mat1.get_dtype()} and {mat2.get_dtype()}" + ) + group_size = V.graph.add_tensor_constant( + torch.tensor(qGroupSize, dtype=torch.int64), name=None + ) + aten_layout = layout + + # options to tune from + choices = ( + [ + aten__weight_int4pack_mm_cpu.bind( + (mat1, mat2, group_size, qScaleAndZeros), aten_layout + ) + ] + if use_aten_gemm_kernels() + else [] + ) + if ( + (config.max_autotune or config.max_autotune_gemm) + and use_cpp_gemm_template( + aten_layout, + mat1, + mat2, + mat2_transposed=True, + is_woq_int4=True, + q_group_size=qGroupSize, + ) + and mat2.get_layout().is_contiguous() + ): + # pyrefly: ignore [bad-specialization, missing-attribute, not-a-type] + CppWoqInt4GemmTemplate[qGroupSize].add_choices( + choices, + aten_layout, + [mat1, mat2, group_size, qScaleAndZeros], + ) + + # define functions to generate example inputs for weight and group size + # otherwise, autotuner generates example inputs of all zeros for them + def get_example_weight(x: torch._inductor.ir.IRNode) -> torch.Tensor: + if not x.get_layout().is_contiguous(): + raise AssertionError("expected x to have a contiguous layout") + shape = x.get_size() + device = x.get_device() + return torch.randint(0, 255, shape, dtype=torch.uint8, device=device) + + input_gen_fns = { + 1: get_example_weight, # packed weight + 2: lambda x: V.graph.constants[x.get_name()], # group size + } + + node, _ = autotune_select_algorithm( + "_weight_int4pack_mm_for_cpu", + choices, + [mat1, mat2, group_size, qScaleAndZeros], + aten_layout, + input_gen_fns=input_gen_fns, + ) + return node + + lowering.make_fallback(aten._dyn_quant_matmul_4bit) + lowering.make_fallback(aten._dyn_quant_pack_4bit_weight) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/remote_cache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/remote_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..1709eeefdb33a0f9b5b65daf5a18dab1a1d68926 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/remote_cache.py @@ -0,0 +1,492 @@ +from __future__ import annotations + +import atexit +import collections +import dataclasses +import functools +import json +import logging +import os +import sys +import typing +from abc import abstractmethod +from typing import Any, Generic, TypeAlias, TypeVar, Union +from typing_extensions import override + +from torch._dynamo.utils import dynamo_timed +from torch._inductor import config +from torch.monitor import _WaitCounter + + +if typing.TYPE_CHECKING: + from collections.abc import Callable + + +try: + import redis +except ImportError: + redis = None # type: ignore[assignment] + + +log = logging.getLogger(__name__) + + +if config.is_fbcode(): + from rfe.scubadata.scubadata_py3 import ( # type: ignore[import-not-found] + Sample as Sample_, + ) + + Sample: TypeAlias = Sample_ +else: + Sample: TypeAlias = type[object] # type: ignore[misc,no-redef] + + +_T = TypeVar("_T") +_U = TypeVar("_U") + + +remote_fx_cache_get_timed = functools.partial( + dynamo_timed, + "FbRemoteFxGraphCache.get", + phase_name="remote_fx_graph_cache_get", + log_pt2_compile_event=False, + dynamo_compile_column_us="remote_fx_graph_cache_get_time_us", + log_waitcounter=True, +) +remote_fx_cache_put_timed = functools.partial( + dynamo_timed, + "FbRemoteFxGraphCache.put", + phase_name="remote_fx_graph_cache_put", + log_pt2_compile_event=False, + dynamo_compile_column_us="remote_fx_graph_cache_put_time_us", + log_waitcounter=True, +) + + +class RemoteCacheBackend(Generic[_T]): + """ + A backend implementation for cache storage. Most backends are remote, but + local filesystem backends use the same bytes-oriented interface. For + structured data use a RemoteCache. + """ + + def __init__(self) -> None: + self._name = f"backend:{type(self).__name__}" + + @abstractmethod + def _get(self, key: str) -> _T | None: + pass + + @abstractmethod + def _put(self, key: str, data: _T) -> None: + pass + + def get(self, key: str) -> _T | None: + try: + value = self._get(key) + cache_stats.get(self._name, value) + except Exception: + cache_stats.exception(self._name) + raise + return value + + def put(self, key: str, data: _T) -> None: + try: + self._put(key, data) + cache_stats.put(self._name) + except Exception: + cache_stats.exception(self._name) + raise + + +# Serde that encodes from _T to _U and decodes from _U to _T. +class RemoteCacheSerde(Generic[_T, _U]): + @abstractmethod + def encode(self, data: _T) -> _U: + pass + + @abstractmethod + def decode(self, data: _U) -> _T: + pass + + +JsonDataTy: TypeAlias = Union[ # noqa: UP007 + int, float, str, bool, dict[str, "JsonDataTy"], list["JsonDataTy"], None +] + + +class RemoteCacheJsonSerde(RemoteCacheSerde[JsonDataTy, bytes]): + def encode(self, data: JsonDataTy) -> bytes: + return bytes(json.dumps(data), "ascii") + + def decode(self, data: bytes) -> JsonDataTy: + return json.loads(data) + + +class RemoteCachePassthroughSerde(RemoteCacheSerde[_T, _T]): + def encode(self, data: _T) -> _T: + return data + + def decode(self, data: _T) -> _T: + return data + + +class LocalCacheBackend(RemoteCacheBackend[bytes]): + """ + A local filesystem implementation of the cache backend interface. + """ + + @override + def _get(self, key: str) -> bytes | None: + try: + with open(key, "rb") as fd: + return fd.read() + except FileNotFoundError: + return None + + @override + def _put(self, key: str, data: bytes) -> None: + os.makedirs(os.path.dirname(key), exist_ok=True) + from torch._inductor import codecache + + codecache.write_atomic(key, data) + + +# This class is the top of a RemoteCache. A RemoteCache is fundamentally made of +# three parts: +# +# 1. The controller (this class). +# 2. A serializer/deserializer (instance of RemoteCacheSerde). +# 3. A backend (instance of RemoteCacheBackend). +# +# To write (`put`), the RemoteCache takes data, uses the RemoteCacheSerde to +# convert it for the backend and passes it to the backend. +# +# Conversely when reading (`get`), the RemoteCache takes data from the backend, +# uses the RemoteCacheSerde to convert it and returns it. +# +# The RemoteCacheBackend is generic on _U - which is the type of data the +# backend can directly cache (usually `bytes`). +# +# The RemoteCacheSerde is responsible for converting between _T (the type of +# data the RemoteCache accepts in `put` and returns in `get`) and _U. +# +# When instantiating a RemoteCache you should override, not directly create a +# RemoteCache. The reason is that when logging cache use (`TORCH_LOGS=cache`) we +# use the concrete type of the RemoteCache as the reported cache. See +# RemoteFxGraphCache below as an example. +class RemoteCache(Generic[_T]): + backend_override_cls: Callable[[], RemoteCacheBackend[Any]] | None = None + + def __init__( + self, backend: RemoteCacheBackend[_U], serde: RemoteCacheSerde[_T, _U] + ) -> None: + # Support for testing to mock out the backend on a class-by-class basis. + if (override_cls := self.__class__.backend_override_cls) is not None: + self.backend = override_cls() + else: + self.backend = backend + # pyrefly: ignore [invalid-type-var] + self.serde = serde + + # See if the cache contains `key`. Returns `None` if the value is not + # present in the cache. + def get(self, key: str) -> _T | None: + with _WaitCounter("pytorch.remote_cache.get").guard(): + sample = self._create_sample() + try: + result = self._get(key, sample) + cache_stats.get(type(self).__name__, result) + except Exception as e: + cache_stats.exception(type(self).__name__) + if sample: + sample.fail_reason = str(e) + raise + finally: + self._log_sample(sample) + return result + + # Add `value` to the cache with the key `key`. Note that `None` is not a + # valid value even if _T supports it (because you can't tell the difference + # between `None` and a missing cache entry). + def put(self, key: str, value: _T) -> None: + with _WaitCounter("pytorch.remote_cache.put").guard(): + if value is None: + raise AssertionError("cannot put None into the cache") + sample = self._create_sample() + try: + self._put(key, value, sample) + cache_stats.put(type(self).__name__) + except Exception as e: + cache_stats.exception(type(self).__name__) + if sample: + sample.fail_reason = str(e) + raise + finally: + self._log_sample(sample) + + # Used to convert data from the cache into structured data. + def _decode(self, data: _U, sample: Sample | None) -> _T: # type: ignore[override] + return self.serde.decode(data) # type: ignore[arg-type] + + # Used to convert structured data into data for the cache. + def _encode(self, value: _T, sample: Sample | None) -> object: # returns _U + return self.serde.encode(value) + + # Get structured data from the cache. + # Separate from `get` so that it can be overridden. + def _get(self, key: str, sample: Sample | None) -> _T | None: + if data := self._backend_get(key): + return self._decode(data, sample) + return None + + # Get unstructured data from the cache. + # Separate from `get` so that it can be overridden. + # Returns _U - but we aren't actually generic on _U + def _backend_get(self, key: str) -> object: + return self.backend.get(key) + + # Put structured data into the cache. + # Separate from `put` so that it can be overridden. + def _put(self, key: str, value: _T, sample: Sample | None) -> None: + data = self._encode(value, sample) + self._backend_put(key, data) + + # Put unstructured data into the cache. + # Separate from `put` so that it can be overridden. + # Takes data: _U - but we aren't actually generic on _U + def _backend_put(self, key: str, data: object) -> None: + self.backend.put(key, data) + + # Create a logging Sample - used with internal loggers to monitor cache + # effectiveness. + def _create_sample(self) -> Sample | None: + return None + + # Write the logging Sample to the logger. + def _log_sample(self, sample: Sample | None) -> None: + pass + + +class RedisRemoteCacheBackend(RemoteCacheBackend[bytes]): + """ + A Redis implementation of a remote/distributed cache. + """ + + # pyrefly: ignore [missing-attribute] + _redis: redis.Redis | None = None + + def __init__(self, cache_id: str) -> None: + super().__init__() + if not redis: + raise RuntimeError("redis not available but required for remote cache") + + if "TORCHINDUCTOR_REDIS_URL" in os.environ: + self._redis = redis.Redis.from_url(os.environ["TORCHINDUCTOR_REDIS_URL"]) + else: + self._redis = redis.Redis( + host=os.environ.get("TORCHINDUCTOR_REDIS_HOST", "localhost"), + port=int(os.environ.get("TORCHINDUCTOR_REDIS_PORT", 6379)), + ) + + @override + def _get(self, key: str) -> bytes | None: + if not self._redis: + # Either redis wasn't found or we already had some trouble... + return None + + try: + # pyrefly: ignore [missing-attribute] + value = self._redis.get(key) + # pyrefly: ignore [missing-attribute] + except redis.exceptions.ConnectionError: + # Redis is lazy and doesn't actually attempt to connect until the + # first use. Mark it as unavailable now. + self._redis = None + return None + + # In theory redis.get() can return an Awaitable as well... + if not (value is None or isinstance(value, bytes)): + raise AssertionError(f"expected bytes or None, got {type(value)}") + return value + + @override + def _put(self, key: str, data: bytes) -> None: + if not self._redis: + # Either redis wasn't found or we already had some trouble... + return + + try: + # pyrefly: ignore [missing-attribute] + self._redis.set(key, data) + # pyrefly: ignore [missing-attribute] + except redis.exceptions.ConnectionError: + # Redis is lazy and doesn't actually attempt to connect until the + # first use. Mark it as unavailable now. + self._redis = None + + +class RedisRemoteCache(RemoteCache[JsonDataTy]): + def __init__(self, cache_id: str) -> None: + # Special test handling: If we're just going to override the backend + # anyway don't require redis + if self.__class__.backend_override_cls: + # This is totally bogus but it works for now... + backend = typing.cast(RemoteCacheBackend[bytes], None) + else: + backend = RedisRemoteCacheBackend(cache_id) + serde = RemoteCacheJsonSerde() + super().__init__(backend, serde) + version = 1 # consistency between various types of keys + self._key_fmt = f"pt2:{cache_id}::{{key}}:c{version}" + + def _get_key(self, key: str) -> str: + return self._key_fmt.format(key=key) + + @override + def _get(self, key: str, sample: Sample | None) -> JsonDataTy | None: + key = self._get_key(key) + return super()._get(key, sample) + + @override + def _put(self, key: str, value: JsonDataTy, sample: Sample | None) -> None: + key = self._get_key(key) + super()._put(key, value, sample) + + +class LocalCache(RemoteCache[JsonDataTy]): + def __init__(self, cache_id: str) -> None: + # Local caches use the per-operation key as the filesystem path. Accept + # cache_id so they can be constructed through create_cache like remote + # caches. + backend = LocalCacheBackend() + serde = RemoteCacheJsonSerde() + super().__init__(backend, serde) + + @override + def _get(self, key: str, sample: Sample | None) -> JsonDataTy | None: + try: + return super()._get(key, sample) + except (json.JSONDecodeError, UnicodeDecodeError) as exc: + log.warning( + "Ignoring corrupt local cache entry %s: %s: %s", + key, + type(exc).__name__, + exc, + ) + return None + + +class LocalAutotuneCache(LocalCache): + # Keep a distinct cache type for cache stats and test backend overrides. + pass + + +class RemoteAutotuneCache(RedisRemoteCache): + pass + + +class RemoteBundledAutotuneCache(RedisRemoteCache): + pass + + +class RemoteFxGraphCache(RedisRemoteCache): + pass + + +class RemoteAOTAutogradCache(RedisRemoteCache): + pass + + +class RemoteDynamoPGOCache(RedisRemoteCache): + pass + + +def create_cache( + key: str, + is_fbcode: bool = False, + fb_cache_cls: str | None = None, + oss_cache_cls: str | None = None, + *, + local_cache_cls: str | None = None, +) -> RemoteCache[JsonDataTy] | None: + try: + this_module = sys.modules[__name__] + if local_cache_cls is not None: + cache_cls = getattr(this_module, local_cache_cls) + return cache_cls(key) + elif is_fbcode: + if fb_cache_cls is None: + raise AssertionError("fb_cache_cls must not be None in fbcode") + import torch._inductor.fb.remote_cache + + cache_cls = getattr(torch._inductor.fb.remote_cache, fb_cache_cls) + return cache_cls(key) + else: + if oss_cache_cls is None: + raise AssertionError("oss_cache_cls must not be None") + cache_cls = getattr(this_module, oss_cache_cls) + return cache_cls(key) + + except Exception: + log.warning("Unable to create cache", exc_info=True) + return None + + +# Some simple stat capture +@dataclasses.dataclass +class _CacheStat: + miss: int = 0 + hit: int = 0 + put: int = 0 + exception: int = 0 + + def __str__(self) -> str: + return f"{{hit: {self.hit}, miss: {self.miss}, put: {self.put}, exception: {self.exception}}}" + + +class _CacheStats: + _stats: dict[str, _CacheStat] + + def __init__(self) -> None: + self._stats = collections.defaultdict(_CacheStat) + + def miss(self, name: str, count: int = 1) -> None: + self._stats[name].miss += count + + def hit(self, name: str, count: int = 1) -> None: + self._stats[name].hit += count + + def get(self, name: str, value: object | None) -> None: + if value is None: + self.miss(name) + else: + self.hit(name) + + def put(self, name: str, count: int = 1) -> None: + self._stats[name].put += count + + def exception(self, name: str, count: int = 1) -> None: + self._stats[name].exception += count + + +cache_stats = _CacheStats() + + +@atexit.register +def dump_cache_stats() -> None: + if not log.isEnabledFor(logging.INFO): + return + + import io + + out = io.StringIO() + + if not cache_stats._stats: + print(" None", file=out) + else: + print(file=out) + for k, v in sorted(cache_stats._stats.items()): + print(f" {k}: {v}", file=out) + + log.info("Cache Metrics:%s", out.getvalue()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/remote_gemm_autotune_cache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/remote_gemm_autotune_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..0ef026269b10c86d58f72e53e998af4ba59b13bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/remote_gemm_autotune_cache.py @@ -0,0 +1,20 @@ +import asyncio +from typing import TypeVar + +import torch._inductor.config as config +from torch._inductor import ir + + +_T = TypeVar("_T") + + +def gen_best_config(mat1: ir.StorageBox, mat2: ir.StorageBox) -> asyncio.Task[_T]: + """ + Generate the best GEMM autotune config for the given matrices. + """ + if config.is_fbcode(): + from torch._inductor.fb.remote_gemm_autotune_cache import gen_best_config + + return gen_best_config(mat1, mat2) + else: + raise NotImplementedError("Function gen_best_config is not yet implemented") diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/rocm_multiarch_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/rocm_multiarch_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8a713d4ca033d81eba5d92176a2e7ba08332b015 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/rocm_multiarch_utils.py @@ -0,0 +1,310 @@ +""" +ROCm Multi-Architecture Support Utilities +Compile LLVM IR to multi-arch bundles that HIP can load automatically. +""" + +import logging +import os +import re +import subprocess + +import torch +from torch.utils.cpp_extension import _join_rocm_home, ROCM_HOME + + +log = logging.getLogger(__name__) + + +def get_rocm_compiler() -> str: + """ + Get path to ROCm's clang compiler. + Uses PyTorch's ROCM_HOME detection. + + Returns: + Path to clang compiler + + Raises: + RuntimeError: If ROCm is not found + """ + if ROCM_HOME is None: + raise RuntimeError( + "ROCm installation not found. " + "PyTorch was not built with ROCm support or ROCM_HOME is not set." + ) + + # ROCm's clang is at /llvm/bin/clang + clang_path = _join_rocm_home("llvm", "bin", "clang") + + if not os.path.exists(clang_path): + raise RuntimeError( + f"ROCm clang not found at {clang_path}. ROCM_HOME is set to {ROCM_HOME}" + ) + + return clang_path + + +def get_rocm_bundler() -> str: + """ + Get path to clang-offload-bundler. + Uses PyTorch's ROCM_HOME detection. + + Returns: + Path to bundler + + Raises: + RuntimeError: If bundler is not found + """ + if ROCM_HOME is None: + raise RuntimeError( + "ROCm installation not found. " + "PyTorch was not built with ROCm support or ROCM_HOME is not set." + ) + + # Bundler is at /llvm/bin/clang-offload-bundler + bundler_path = _join_rocm_home("llvm", "bin", "clang-offload-bundler") + + if not os.path.exists(bundler_path): + raise RuntimeError( + f"clang-offload-bundler not found at {bundler_path}. " + f"ROCM_HOME is set to {ROCM_HOME}" + ) + + return bundler_path + + +def get_rocm_target_archs() -> list[str]: + env_archs = os.environ.get("PYTORCH_ROCM_ARCH", "").strip() + if env_archs: + archs = [arch.strip() for arch in env_archs.replace(";", ",").split(",")] + archs = [arch for arch in archs if arch] + if archs: + # Ensure current device arch is included + if torch.cuda.is_available(): + for dev_idx in range(torch.cuda.device_count()): + current_arch = torch.cuda.get_device_properties( + dev_idx + ).gcnArchName.split(":")[0] + if current_arch not in archs: + archs.append(current_arch) + return archs + + try: + from torch._inductor import config + + if hasattr(config, "rocm") and hasattr(config.rocm, "target_archs"): + archs = config.rocm.target_archs + if archs: + return archs + + except Exception: + pass + + return torch.cuda.get_arch_list() + + +def _sanitize_llvm_ir_for_rocm(llvm_ir_path: str) -> str: + """ + Sanitize LLVM IR to be compatible with ROCm's clang. + + Triton's LLVM (upstream) may emit attributes and metadata that ROCm's + older clang does not yet support. Only strips attributes confirmed to + cause parse errors — preserves all others to maintain correct codegen. + + Currently strips: + - nocreateundeforpoison: function attribute (upstream LLVM, not in ROCm) + - dwarfAddressSpace: debug metadata field (upstream LLVM, not in ROCm) + + Returns: + Path to sanitized .ll file, or original path if no changes needed. + """ + with open(llvm_ir_path) as f: + content = f.read() + + sanitized = content + sanitized = re.sub(r"\bnocreateundeforpoison\b\s*", "", sanitized) + sanitized = re.sub(r",\s*dwarfAddressSpace:\s*\d+", "", sanitized) + + if sanitized == content: + return llvm_ir_path + + sanitized_path = llvm_ir_path + ".sanitized.ll" + with open(sanitized_path, "w") as f: + f.write(sanitized) + + log.debug( + "Sanitized LLVM IR for ROCm clang compatibility: %s -> %s", + llvm_ir_path, + sanitized_path, + ) + return sanitized_path + + +def compile_llvm_ir_to_code_object( + llvm_ir_path: str, output_path: str, target_arch: str +) -> bool: + """ + Compile unbundled LLVM IR to a single-arch code object. + + Args: + llvm_ir_path: Path to .ll file + output_path: Where to write .hsaco file + target_arch: Target architecture (e.g., 'gfx90a') + + Returns: + True if successful + """ + if not os.path.exists(llvm_ir_path): + return False + + os.makedirs(os.path.dirname(output_path), exist_ok=True) + + try: + clang = get_rocm_compiler() + except RuntimeError: + return False + + # Sanitize LLVM IR to remove attributes unsupported by ROCm's clang + llvm_ir_path = _sanitize_llvm_ir_for_rocm(llvm_ir_path) + + # Using clang and not hipcc since we are not compiling source code + # Instead we use the LLVM IR (.ll) provided by triton + cmd = [ + clang, + "-target", + "amdgcn-amd-amdhsa", + f"-mcpu={target_arch}", + llvm_ir_path, + "-o", + output_path, + ] + + try: + subprocess.run(cmd, capture_output=True, text=True, check=True) + + if not os.path.exists(output_path): + return False + + return True + + except subprocess.CalledProcessError: + return False + + +def create_multiarch_bundle(code_objects: dict, output_bundle_path: str) -> bool: + """ + Bundle multiple architecture code objects into a single multi-arch bundle. + + Uses clang-offload-bundler to create a fat binary that HIP runtime can load. + The runtime automatically selects the correct architecture at load time. + + Args: + code_objects: Dict mapping architecture to code object path + output_bundle_path: Path for output bundle + + Returns: + True if successful + """ + if not code_objects: + return False + + os.makedirs(os.path.dirname(output_bundle_path), exist_ok=True) + + try: + bundler = get_rocm_bundler() + except RuntimeError: + return False + + # Build targets and inputs lists for clang-offload-bundler + targets = ["host-x86_64-unknown-linux-gnu"] + + # We include a dummy host entry to satisfy the bundler format + inputs = ["/dev/null"] + + for arch, path in sorted(code_objects.items()): + if not os.path.exists(path): + continue + # hipv4 = HIP version 4 code object format + # amdgcn-amd-amdhsa = target triple for ROCm/HSA runtime + # arch = specific GPU (gfx90a, gfx942, etc.) + targets.append(f"hipv4-amdgcn-amd-amdhsa--{arch}") + inputs.append(path) + + if len(inputs) == 1: # Only host, no device code + return False + + cmd = [ + bundler, + "--type=o", + # CRITICAL: HIP runtime expects 4096-byte alignment for loading bundles + # Without this, hipModuleLoadData gives segmentation fault + "-bundle-align=4096", # CRITICAL: Required by HIP runtime! + f"--targets={','.join(targets)}", + ] + + for input_file in inputs: + cmd.append(f"--input={input_file}") + + cmd.append(f"--output={output_bundle_path}") + + try: + subprocess.run(cmd, capture_output=True, text=True, check=True) + + if not os.path.exists(output_bundle_path): + return False + + return True + + except subprocess.CalledProcessError: + return False + + +def compile_multiarch_bundle_from_llvm_ir( + llvm_ir_path: str, output_bundle_path: str, target_archs: list[str] | None = None +) -> bool: + """ + Complete workflow: LLVM IR → multiple code objects → bundle. + + This is the main entry point for multi-arch compilation. + + Args: + llvm_ir_path: Path to .ll file + output_bundle_path: Where to write bundle + target_archs: Optional list of architectures + + Returns: + True if successful + """ + if target_archs is None: + # Get architectures from environment variable or config + target_archs = get_rocm_target_archs() + + # Step 1: Compile LLVM IR to code object for each architecture + code_objects = {} + temp_dir = os.path.dirname(output_bundle_path) + kernel_name = os.path.splitext(os.path.basename(llvm_ir_path))[0] + + for arch in target_archs: + # Create temporary single-architecture code object + # Format: kernel_name_gfx90a.co, kernel_name_gfx942.co, etc. + co_path = os.path.join(temp_dir, f"{kernel_name}_{arch}.co") + + # Compile with clang backend: LLVM IR → GPU machine code + if compile_llvm_ir_to_code_object(llvm_ir_path, co_path, arch): + code_objects[arch] = co_path + + if not code_objects: + return False + + # Step 2: Bundle all code objects together + # Uses clang-offload-bundler to create fat binary + success = create_multiarch_bundle(code_objects, output_bundle_path) + + # Step 3: Clean up temporary single-arch code objects + # The bundle contains all the code, so intermediates are no longer needed + for co_path in code_objects.values(): + try: + os.remove(co_path) + except Exception: + pass + + return success diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a7d70cea52a4668515997c661fb6a7777b0830c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/autotune_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/autotune_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef548a1d38bdf36bf81b01eebf7d11f033de70fe Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/autotune_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/benchmarking.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/benchmarking.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..023644f4470010c0b1fdb6da8086c0011ced462a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/benchmarking.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/cache_dir_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/cache_dir_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5aea95c37e64359bb48bec2f4838713707376637 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/cache_dir_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/compile_tasks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/compile_tasks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9ab0512eba4740be3abf87a63156b6c4558d350 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/compile_tasks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/coordinate_descent_tuner.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/coordinate_descent_tuner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc31862fb4a49b099ac408a2b86eebb10c7089b9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/coordinate_descent_tuner.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/cutedsl_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/cutedsl_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad1753e10de253c287aabb0b337662be3a41e9f3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/cutedsl_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/debug_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/debug_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5db17b8bdaeed4f5bb30defc53c67663659d0632 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/debug_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/halide_helpers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/halide_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a27e0d041af2348e714e8d235f075f1f374b524 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/halide_helpers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/hints.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/hints.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42c057c0fe35a73344655cb6a326b408c19df3a2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/hints.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/proton_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/proton_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..375fea941d621072491879199a581ee4dc1c29a1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/proton_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/runtime_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/runtime_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cabbe5da2a4e1006f18e797230ab02488966feb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/runtime_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/static_triton_launcher.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/static_triton_launcher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ff5ea79bcc705782ff935427369d9e8a479a876 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/static_triton_launcher.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_compat.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6762be0845224fbc665bc1b0220c6d69e67775ab Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_compat.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_helpers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28255aecef4ddcb26594dc7cec97f8add723f3aa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_helpers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_heuristics.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_heuristics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8855b2c4eaffae17eb3eed0d6053f277569df5ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_heuristics.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:106a6edcdb2db623464fbc505d02aac49a85fc1835039204650e9d38013a85d0 +size 212315 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_lazy_compile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_lazy_compile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ec6c50a4aaeef03680d866ca449a62ae15bf282 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_lazy_compile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/autotune_cache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/autotune_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..8a6a0d7a02a422d4279719e947a62c1b5b90c2f8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/autotune_cache.py @@ -0,0 +1,743 @@ +""" +PyTorch Inductor Autotuning Cache System + +This module implements a caching system for autotuning configurations in PyTorch's Inductor compiler. +It provides mechanisms to store and retrieve optimal kernel configurations both locally and remotely, +which significantly speeds up compilation by reusing previously discovered optimal parameters. + +The caching system includes: +- Local filesystem caching for individual machine reuse +- Remote caching for sharing optimizations across machines +- Bundled caching to efficiently store multiple related configurations +- Cache invalidation based on PyTorch versions and backend changes +- Serialization/deserialization support for worker processes + +Key components: +- AutotuneCache: Main class for managing cache access and storage +- AutotuneCacheBundler: Bundles multiple cache entries for efficient storage +- LocalCacheBackend: Low-level file operations for cache storage +- AutotuneCacheArtifact: Integration with PyTorch's artifact system + +This caching system is critical for performance as it eliminates the need to re-run +expensive autotuning operations when the same kernels are compiled multiple times. +""" + +from __future__ import annotations + +import dataclasses +import logging +import os +import os.path +import re +import threading +import weakref +from typing import Any +from typing_extensions import override + +import torch +from torch._guards import CompileContext +from torch._inductor.runtime.runtime_utils import cache_dir +from torch.compiler._cache import ( + CacheArtifact, + CacheArtifactFactory, + CacheArtifactRecorder, +) +from torch.utils._triton import has_triton + +from ..cache_key import AUTOTUNE_CACHE_KEY_STRATEGY +from ..remote_cache import ( + create_cache, + JsonDataTy, + LocalAutotuneCache, + LocalCacheBackend, + RemoteCache, + RemoteCacheJsonSerde, +) +from .hints import InductorMeta +from .triton_compat import Config, HAS_WARP_SPEC + + +log = logging.getLogger(__name__) + + +_InductorMetaTy = InductorMeta + + +def inductor_meta_from_config() -> _InductorMetaTy: + from torch._inductor import config + + backend_hash = None + if has_triton(): + try: + backend_hash = torch.utils._triton.triton_hash_with_backend() + except RuntimeError: + # This can get the error: + # RuntimeError: 0 active drivers ([]). There should only be one. + pass + + is_hip = None + if torch.version.hip is not None: + is_hip = True + + return { + "autotune_local_cache": config.autotune_local_cache, + "autotune_remote_cache": config.autotune_remote_cache, + "backend_hash": backend_hash, + "bundled_autotune_remote_cache": config.bundled_autotune_remote_cache, + "coordinate_descent_tuning": config.coordinate_descent_tuning, + "is_fbcode": config.is_fbcode(), + "is_hip": is_hip, + } + + +@CacheArtifactFactory.register +class AutotuneCacheArtifact(CacheArtifact): + @override + def populate_cache(self) -> None: + autotune_cache = LocalCacheBackend() + key = os.path.join(cache_dir(), self.key) + autotune_cache._put(key, self.content) + + @override + @staticmethod + def type() -> str: + return "autotune" + + @override + @staticmethod + def encode(content: JsonDataTy) -> bytes: + if isinstance(content, bytes): + raise AssertionError("content must not be bytes before encoding") + serde = RemoteCacheJsonSerde() + content_bytes = serde.encode(content) + if not isinstance(content_bytes, bytes): + raise AssertionError( + f"Expected bytes after encoding, got {type(content_bytes)}" + ) + return content_bytes + + +@dataclasses.dataclass +class AutotuneCache: + """Coordinates local and remote autotune cache lookups for one kernel.""" + + configs_hash: str + local_cache: tuple[RemoteCache[JsonDataTy], str] | None = None + remote_cache: tuple[RemoteCache[JsonDataTy], str] | None = None + artifact_recorder: CacheArtifactRecorder | None = None + + # Create a AutotuneCache. Returns None if none of the caches can be used. + @staticmethod + def create( + inductor_meta: _InductorMetaTy, filename: str, configs_hash: str + ) -> AutotuneCache | None: + cache = AutotuneCache(configs_hash) + key = AutotuneCache._prepare_key(filename) + local_cache_key = AutotuneCache._make_local_cache_key( + os.path.dirname(filename), key + ) + cache.artifact_recorder = CacheArtifactRecorder( + AutotuneCacheArtifact.type(), + AutotuneCache._artifact_key_from_local_cache_key(local_cache_key), + ) + + cache._setup_local_cache(inductor_meta, local_cache_key) + cache._setup_remote_autotune_cache(inductor_meta, key) + if cache.local_cache or cache.remote_cache: + return cache + else: + return None + + @staticmethod + def _prepare_key(filename: str) -> str: + from torch.compiler import config as cconfig + + # base of filename is already sha256 hash the source contents + key = f"{os.path.basename(filename)}:{cconfig.cache_key_tag}" + return AUTOTUNE_CACHE_KEY_STRATEGY.key(key) + + @staticmethod + def _make_local_cache_key(dirname: str, cache_key: str) -> str: + """ + [Note: torch_key in autotune cache key] + Include torch_key() in the cache key so that different versions + of torch result in cache invalidation. This is important in case + of changes to the best_config format or other code changes that + are not backward compatible w.r.t. the cache. + """ + from ..codecache import torch_key + + updated_cache_key = AUTOTUNE_CACHE_KEY_STRATEGY.key(cache_key, torch_key()) + return os.path.join(dirname, f"{updated_cache_key}.best_config") + + @staticmethod + def _artifact_key_from_local_cache_key(local_cache_key: str) -> str: + return os.path.join(*local_cache_key.split(os.sep)[-2:]) + + def _record_artifact(self, data: JsonDataTy) -> None: + # Older pickled AutotuneCache instances may not have this field. + if recorder := getattr(self, "artifact_recorder", None): + recorder.record(data) + + # Read the best config options from the most local cache and return it. + def _read(self) -> dict[str, JsonDataTy] | None: + if local_cache := self.local_cache: + cache, key = local_cache + AutotuneCacheBundler.sync() + best_config = cache.get(key) + if best_config is not None: + if not isinstance(best_config, dict): + raise AssertionError( + f"Expected dict for best_config, got {type(best_config)}" + ) + # Imagine we have a new model that reuses some existing kernels that + # have already been compiled. If we didn't put() here on cache hit, + # then the new model would only bundle newly compiled kernels, not + # existing kernels that were already compiled and cached. + AutotuneCacheBundler.put(key, best_config) + self._record_artifact(best_config) + if best_config: + return best_config + + if remote_cache := self.remote_cache: + cache, key = remote_cache + if best_config := cache.get(key): + if isinstance(best_config, dict): + self._record_artifact(best_config) + return best_config + + return None + + # Read the best config options from the most local cache and figure out + # which `configs` represents that option. + def read_best( + self, inductor_meta: _InductorMetaTy, configs: list[Config] + ) -> Config | None: + if best := self._read(): + return _load_cached_autotuning( + best, self.configs_hash, configs, inductor_meta + ) + return None + + # Set up local filesystem caching information + def _setup_local_cache( + self, inductor_meta: _InductorMetaTy, cache_key: str + ) -> None: + if not inductor_meta.get("autotune_local_cache", True): + return + + local_cache = create_cache( + "local-autotune", + local_cache_cls=LocalAutotuneCache.__name__, + ) + if local_cache is None: + return + self.local_cache = (local_cache, cache_key) + + # Set up remote caching information + def _setup_remote_autotune_cache( + self, inductor_meta: _InductorMetaTy, cache_key: str + ) -> None: + if not _should_use_remote_autotune_cache(inductor_meta): + return + + if (backend_hash := inductor_meta.get("backend_hash", None)) is None: + log.debug( + "backend_hash is not passed on the inductor_meta, unable to use autotune remote cache" + ) + return + if not isinstance(backend_hash, str): + raise AssertionError( + f"Expected str for backend_hash, got {type(backend_hash)}" + ) + + from ..codecache import torch_key + + is_fbcode = bool(inductor_meta.get("is_fbcode", False)) + + salt = "autotune-best-config-v2" + # re: torch_key - see [Note: torch_key in autotune cache key] + key = AUTOTUNE_CACHE_KEY_STRATEGY.key( + torch_key().hex(), backend_hash, self.configs_hash, salt + ) + + remote_cache = create_cache( + key, + is_fbcode, + "FbRemoteAutotuneCache", + "RemoteAutotuneCache", + ) + if not remote_cache: + return + + # Save the args passed to create_cache + # in case AutotuneCache needs to be pickled + self.remote_cache_full_key = key + self.is_fbcode = is_fbcode + self.remote_cache = (remote_cache, cache_key) + + # The AutotuneCache may be serialized/deserialized if we're using + # AsyncCompile worker processes to run triton compilation. + # This is because AutotuneCache instances are created on the worker + # process, but we need to run AutotuneCache.save on the parent process + # when actually doing autotuning. + def __getstate__(self) -> dict[str, Any]: + # The remote cache handles themselves may not be serializable + # So clear it and reconstruct it on setstate + remote_cache = getattr(self, "remote_cache", None) + return { + **self.__dict__, + # Save the cache_key portion + "remote_cache": remote_cache and remote_cache[1], + } + + def __setstate__(self, state: dict[str, Any]) -> None: + # Reconstruct the remote cache on the parent class + self.__dict__.update(state) + if self.remote_cache is not None: + if not isinstance(self.remote_cache, str): + raise AssertionError( + f"Expected str for remote_cache after deserialization, got {type(self.remote_cache)}" + ) + if not hasattr(self, "remote_cache_full_key"): + raise AssertionError( + "Missing remote_cache_full_key attribute after deserialization" + ) + if not hasattr(self, "is_fbcode"): + raise AssertionError( + "Missing is_fbcode attribute after deserialization" + ) + cache_key = self.remote_cache + remote_cache = create_cache( + self.remote_cache_full_key, + self.is_fbcode, + "FbRemoteAutotuneCache", + "RemoteAutotuneCache", + ) + if remote_cache is not None: + self.remote_cache = (remote_cache, cache_key) + else: + log.warning("Warning, failed to recreate remote cache after pickling") + self.remote_cache = None + + # Save the config in the caches + def save( + self, + config: Config, + time_taken_ns: int, + found_by_coordesc: bool = False, + triton_cache_hash: str | None = None, + ) -> None: + data: dict[str, JsonDataTy] = { + # pyrefly: ignore [missing-attribute] + **config.kwargs, + # pyrefly: ignore [missing-attribute] + "num_warps": config.num_warps, + # pyrefly: ignore [missing-attribute] + "num_stages": config.num_stages, + "configs_hash": self.configs_hash, + "found_by_coordesc": found_by_coordesc, + "time_taken_ms": time_taken_ns // 1000000, # Convert from NS to MS + "triton_cache_hash": triton_cache_hash, + } + # Save extra_options if present on the config. This allows third-party + # backends to store custom tuned options alongside the standard config. + if extra_options := getattr(config, "extra_options", None): + data["extra_options"] = extra_options + if HAS_WARP_SPEC: + data.update( + { + "num_consumer_groups": getattr(config, "num_consumer_groups", 0), + "num_buffers_warp_spec": getattr( + config, "num_buffers_warp_spec", 0 + ), + } + ) + + self._record_artifact(data) + + if local_cache := self.local_cache: + cache, key = local_cache + # pyrefly: ignore [bad-argument-type] + cache.put(key, data) + # pyrefly: ignore [bad-argument-type] + AutotuneCacheBundler.put(key, data) + + if log.isEnabledFor(logging.DEBUG): + type_str = "coordesc" if found_by_coordesc else "heuristic" + log.debug("Save %s tuning result to %s", type_str, key) + + if remote_cache := self.remote_cache: + cache, key = remote_cache + # pyrefly: ignore [bad-argument-type] + cache.put(key, data) + + +class _AutotuneCacheBundlerImpl: + """ + Caches a set of local autotune entries together in a single cache. + """ + + _key: str + _cache: RemoteCache[JsonDataTy] + + # All known entries from local autotune cache writes. + _entries: dict[str, JsonDataTy] + + def end_compile(self) -> None: + # TODO: Do we need to compute time_taken_ms and encode that somehow? + if self._entries: + self._cache.put(self._key, self._entries) + + def put(self, basename: str, data: JsonDataTy) -> None: + # Do we need to worry about duplicates? We only have a single local fs + # entry - so probably not. + self._entries[basename] = data + + def __init__(self, key: str, cache: RemoteCache[JsonDataTy]) -> None: + self._key = key + self._cache = cache + self._entries = {} + + def sync(self) -> None: + # We don't currently use this - but we could async load starting at + # `begin_compile` and wait for the load to be finished here. + pass + + @classmethod + def _should_use_bundled_autotune_remote_cache( + cls, inductor_meta: _InductorMetaTy + ) -> bool: + # The bundled autotune cache is only available if you've also got local + # caching enabled (because we feed the bundled data to the local cache). + if not inductor_meta.get("autotune_local_cache", True): + return False + + # Check if we're enabled via config + if ( + bundled_autotune_remote_cache := inductor_meta.get( + "bundled_autotune_remote_cache" + ) + ) is not None: + return bool(bundled_autotune_remote_cache) + + if not cls._get_is_fbcode(inductor_meta): + return False + if torch._utils_internal.is_fb_unit_test(): + return False + if inductor_meta.get("is_hip"): + return False + + try: + from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION + except ModuleNotFoundError: + return False + + jk = torch._utils_internal.justknobs_getval_int( + "pytorch/remote_cache:bundled_autotune_remote_cache_version" + ) + return REMOTE_CACHE_VERSION >= jk + + def _load_cache(self) -> bool: + from torch._inductor import codecache + + # The single key is defined on construction of the cache. + entries = self._cache.get(self._key) + if entries is None or not isinstance(entries, dict): + # We couldn't load the cache - so mark _entries as non-None so we + # store local cache values. + return False + + # Go through the entries we got from the cache and save them locally. + time_saved_ns = 0 + local_cache = create_cache( + "local-autotune", + local_cache_cls=LocalAutotuneCache.__name__, + ) + for basename, data in entries.items(): + # Reconstruct the final filename (see put()) + root, ext = _splitext_nodot(basename) + _, _, filename = codecache.get_path(root, ext) + if isinstance(data, dict) and (tsns := data.get("time_saved_ns")): + time_saved_ns += int(tsns) # type: ignore[arg-type] + if local_cache is not None: + local_cache.put(filename, data) + + codecache.add_ephemeral_timeout_increase_for_distributed(time_saved_ns) + + return True + + @staticmethod + def _get_is_fbcode(inductor_meta: _InductorMetaTy) -> bool: + return bool(inductor_meta.get("is_fbcode", False)) + + @staticmethod + def _get_backend_hash(inductor_meta: _InductorMetaTy) -> str: + backend_hash = inductor_meta["backend_hash"] + if not isinstance(backend_hash, str): + raise AssertionError( + f"Expected str for backend_hash, got {type(backend_hash)}" + ) + return backend_hash + + +class AutotuneCacheBundler: + """Manages one bundled autotune cache write scope for a compile context.""" + + _context_bundlers: weakref.WeakKeyDictionary[ + CompileContext, AutotuneCacheBundler + ] = weakref.WeakKeyDictionary() + _context_bundlers_lock = threading.Lock() + + def __init__(self) -> None: + self._bundler: _AutotuneCacheBundlerImpl | None = None + + @classmethod + def _get_context_bundler( + cls, + ctx: CompileContext | None = None, + *, + create: bool, + ) -> AutotuneCacheBundler | None: + if ctx is None: + return None + + with cls._context_bundlers_lock: + bundler = cls._context_bundlers.get(ctx) + if bundler is None and create: + bundler = cls() + cls._context_bundlers[ctx] = bundler + if bundler is not None and not isinstance(bundler, cls): + raise AssertionError( + f"Expected AutotuneCacheBundler or None, got {type(bundler)}" + ) + return bundler + + @classmethod + def has_active_compile(cls, compile_context: CompileContext | None) -> bool: + context_bundler = cls._get_context_bundler(compile_context, create=False) + return context_bundler is not None and context_bundler._bundler is not None + + # Call this before we start any autotune computation for an inductor python + # file. On a cache hit it copies the individual results into the local + # autotune caches. + @classmethod + def begin_compile( + cls, + inductor_meta: _InductorMetaTy, + *, + code: str | None = None, + code_hash: str | None = None, + ) -> None: + if code is not None: + if code_hash is not None: + raise AssertionError("Cannot specify both code and code_hash") + code_hash = _comment_stripped_hash(code) + if code_hash is None: + raise AssertionError("Either code or code_hash must be provided") + + if not _AutotuneCacheBundlerImpl._should_use_bundled_autotune_remote_cache( + inductor_meta + ): + return + + context_bundler = cls._get_context_bundler( + CompileContext.try_get(), create=True + ) + if context_bundler is None: + log.debug( + "Skipping bundled autotune cache because compile_context is not set" + ) + return + if context_bundler._bundler is not None: + raise AssertionError( + "begin_compile called while a bundler is already active" + ) + + cache = create_cache( + "bundled-autotune-v1", + _AutotuneCacheBundlerImpl._get_is_fbcode(inductor_meta), + "FbRemoteBundledAutotuneCache", + "RemoteBundledAutotuneCache", + ) + if not cache: + return + + # We're starting a compilation phase. We have a cache key for the code + # we're compiling. We'll get the individual autotune bundles later (via + # self.put()). For now create the AutotuneCacheBundler and try to load + # from the cache. + + salt = "bundled-autotune-best-configs-v1" + backend_hash = _AutotuneCacheBundlerImpl._get_backend_hash(inductor_meta) + # TODO: The autotune cache includes configs_hash in the key. The problem + # is that the configs_hash includes info from the individual pointwise() + # calls (size_hints, for example) which we can't know yet. I *think* + # that info is basically present in the `code_hash` (since it's a + # parameter to the pointwise decorator) - but is there other info we + # need to include from inductor_meta? + key = AUTOTUNE_CACHE_KEY_STRATEGY.key(code_hash, backend_hash, salt) + + bundler = _AutotuneCacheBundlerImpl(key, cache) + if not bundler._load_cache(): + # We couldn't load from the cache - so save the data so we can store + # the saved autotunes. + context_bundler._bundler = bundler + + # If we get a cache hit don't bother saving any of the individual + # autotune results. + + # Call this after all individual autotune results are finished for a + # inductor python file. If we gathered any individual results then we bundle + # those and put it into the cache. + @classmethod + def end_compile(cls) -> None: + if not ( + context_bundler := cls._get_context_bundler( + CompileContext.try_get(), create=False + ) + ): + return + if bundler := context_bundler._bundler: + context_bundler._bundler = None + bundler.end_compile() + + @classmethod + def sync(cls) -> None: + if not ( + context_bundler := cls._get_context_bundler( + CompileContext.try_get(), create=False + ) + ): + return + if bundler := context_bundler._bundler: + bundler.sync() + + @classmethod + def put(cls, filename: str, data: JsonDataTy) -> None: + if not ( + context_bundler := cls._get_context_bundler( + CompileContext.try_get(), create=False + ) + ): + return + if bundler := context_bundler._bundler: + # The filename comes in as something like + # "/tmp/tmp{random}/{aa}/{basename}.py" (where aa is + # basename[1:3]). Strip it down and make sure that it looks like a path + # we could reconstruct (because it's possible for the caller to + # customize the path). + basename = os.path.basename(filename) + + # TODO: check cache_dir() vs filename, then strip dirname + bundler.put(basename, data) + + +# Remove the comments from the code (which include things like run ids and file +# paths) and then hash the result. +def _comment_stripped_hash(code: str) -> str: + code = re.sub(r"#.*$", "", code, count=0, flags=re.MULTILINE) + return torch._inductor.codecache.code_hash(code) + + +def _should_use_remote_autotune_cache(inductor_meta: _InductorMetaTy) -> bool: + if (config := inductor_meta.get("autotune_remote_cache")) is not None: + return bool(config) + if not inductor_meta.get("is_fbcode"): + return False + if torch._utils_internal.is_fb_unit_test(): + return False + if inductor_meta.get("is_hip"): + return False + + try: + from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION + except ModuleNotFoundError: + return False + + return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int( + "pytorch/remote_cache:autotune_memcache_version" + ) + + +def _reconstruct_triton_config( + best_config: dict[str, Any], + extra_options: JsonDataTy | None, +) -> Config: + num_warps = best_config.pop("num_warps") + num_stages = best_config.pop("num_stages") + config_args: dict[str, Any] = { + "num_warps": num_warps, + "num_stages": num_stages, + } + if HAS_WARP_SPEC: + config_args.update( + { + "num_consumer_groups": best_config.pop("num_consumer_groups", 0), + "num_buffers_warp_spec": best_config.pop("num_buffers_warp_spec", 0), + } + ) + # pyrefly: ignore [bad-argument-count, unexpected-keyword] + triton_config = Config(best_config, **config_args) + # pyrefly: ignore [missing-attribute] + triton_config.extra_options = extra_options + return triton_config + + +def _load_cached_autotuning( + best_config: dict[str, JsonDataTy], + configs_hash: str, + configs: list[Config], + inductor_meta: _InductorMetaTy, +) -> Config | None: + if best_config is None: + return None + if best_config.pop("configs_hash", None) != configs_hash: + return None + + # Remove time taken for comparison + best_config.pop("time_taken_ms", None) + + best_config.pop("triton_cache_hash", None) + + # Extract extra_options if present. This allows third-party backends + # to restore custom tuned options from the cache. + extra_options = best_config.pop("extra_options", None) + + found_by_coordesc = inductor_meta.get( + "coordinate_descent_tuning" + ) and best_config.pop("found_by_coordesc", False) + + if not found_by_coordesc: + matching_configs = [ + cfg + for cfg in configs + # pyrefly: ignore [missing-attribute] + if all(val == best_config.get(key) for key, val in cfg.kwargs.items()) + # pyrefly: ignore [missing-attribute] + and cfg.num_warps == best_config.get("num_warps") + # pyrefly: ignore [missing-attribute] + and cfg.num_stages == best_config.get("num_stages") + ] + if len(matching_configs) == 1: + matched_config = matching_configs[0] + # pyrefly: ignore [missing-attribute] + matched_config.extra_options = extra_options + return matched_config + + # Reconstruct Config from cached data. This handles both coordesc + # configs and dynamically added configs (e.g. _dynamic_scale_rblock) + # that aren't in the original config list. + best_config.pop("found_by_coordesc", None) + triton_config = _reconstruct_triton_config(best_config, extra_options) + if found_by_coordesc: + # pyrefly: ignore [missing-attribute] + triton_config.found_by_coordesc = True + return triton_config + + +def _splitext_nodot(basename: str) -> tuple[str, str]: + root, ext = os.path.splitext(basename) + if ext: + ext = ext[1:] + return root, ext diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/benchmarking.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/benchmarking.py new file mode 100644 index 0000000000000000000000000000000000000000..679c0209f51bda4622a360c54e9c9aa29673f564 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/benchmarking.py @@ -0,0 +1,953 @@ +import contextlib +import functools +import inspect +import time +from collections.abc import Callable, Iterator +from functools import cached_property, wraps +from itertools import chain +from statistics import median +from typing import Any, Concatenate +from typing_extensions import ParamSpec, Self, TypeVar + +import torch +import torch._inductor.config as inductor_config +import torch.utils._pytree as pytree +from torch._dynamo.device_interface import get_interface_for_device +from torch._dynamo.utils import counters +from torch.utils._debug_mode import DebugMode +from torch.utils._ordered_set import OrderedSet + + +logger = torch._logging.getArtifactLogger(__name__, "benchmarking") +GPU_BENCHMARK_DEVICE_TYPES = ("cuda", "xpu", "mtia") +_CALLABLE_PROFILE_EVENT_NAME = "_CALLABLE" + + +MILLISECONDS_PER_SECOND = 1000 + +P = ParamSpec("P") +T = TypeVar("T") + + +def _get_default_gpu_device_type() -> str: + avail_gpus = [ + device_type + for device_type in GPU_BENCHMARK_DEVICE_TYPES + if getattr(torch, device_type).is_available() + ] + if len(avail_gpus) > 1: + raise AssertionError( + f"expected at most one available GPU type, got {avail_gpus}" + ) + return "cuda" if len(avail_gpus) == 0 else avail_gpus.pop() + + +def _normalize_gpu_device_type(device_type: str | torch.device | None) -> str: + if device_type is None: + return _get_default_gpu_device_type() + if isinstance(device_type, torch.device): + return device_type.type + return torch.device(device_type).type + + +_GpuBenchmarkLockContext = Callable[[], contextlib.AbstractContextManager[None]] +_gpu_benchmark_lock_context: _GpuBenchmarkLockContext | None = None + + +def set_gpu_benchmark_lock_context( + context_factory: _GpuBenchmarkLockContext | None, +) -> _GpuBenchmarkLockContext | None: + """Override the process-local GPU benchmark lock context. + + This lets benchmark harnesses provide the context used by Inductor GPU + benchmark calls. Some benchmark helpers delegate to other benchmark + methods, so harness contexts should support nested entry from the same + thread. Returning the previous context lets callers restore it in tests. + """ + global _gpu_benchmark_lock_context + previous = _gpu_benchmark_lock_context + _gpu_benchmark_lock_context = context_factory + return previous + + +@contextlib.contextmanager +def maybe_gpu_benchmark_lock() -> Iterator[None]: + """Optionally enter the registered GPU benchmark lock context.""" + context_factory = _gpu_benchmark_lock_context + if context_factory is None: + yield + return + with context_factory(): + yield + + +def gpu_benchmark_lock(fn: Callable[P, T]) -> Callable[P, T]: + @wraps(fn) + def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: + with maybe_gpu_benchmark_lock(): + return fn(*args, **kwargs) + + return wrapper + + +# Device-type → benchmarking function registry. +# Keys must match torch.device.type (e.g., "cpu", "cuda", "mps", "xpu", ...). +# Values are callables with signature: +# fn(self: Benchmarker, _callable: Callable[..., Any], *, warmup: int, rep: int, **kwargs) -> Any +_BENCHMARK_DISPATCH: dict[str, Callable[..., Any]] = {} + + +def register_benchmarker( + device_type: str, + fn: Callable[..., Any], + *, + override: bool = False, +) -> None: + """ + Register a device-type specific benchmarker. + + Args: + device_type: torch.device.type string (e.g., "cuda", "cpu", "mps", "xpu"). + fn: callable(self, _callable, *, warmup, rep, **kwargs) -> Any + override: allow overriding an existing registration. + """ + if not isinstance(device_type, str) or not device_type: + raise ValueError( + "device_type must be a non-empty string matching torch.device.type" + ) + if not callable(fn): + raise TypeError("fn must be callable") + if not override and device_type in _BENCHMARK_DISPATCH: + raise ValueError( + f"Benchmarker for device_type '{device_type}' already registered" + ) + _BENCHMARK_DISPATCH[device_type] = fn + + +def may_distort_benchmarking_result(fn: Callable[..., Any]) -> Callable[..., Any]: + from torch._inductor import config + + if config.test_configs.distort_benchmarking_result == "": + return fn + + def distort( + ms: list[float] | tuple[float, ...] | float, + ) -> list[float] | tuple[float, ...] | float: + if isinstance(ms, (list, tuple)): + return type(ms)(distort(val) for val in ms) # type: ignore[misc] + + distort_method = config.test_configs.distort_benchmarking_result + if not isinstance(ms, float): + raise AssertionError(f"Expected float, got {type(ms)}") + if distort_method == "inverse": + return 1.0 / ms if ms else 0.0 + elif distort_method == "random": + import random + + return random.random() + else: + raise RuntimeError(f"Unrecognized distort method {distort_method}") + + @functools.wraps(fn) + def wrapper( + *args: list[Any], **kwargs: dict[str, Any] + ) -> list[float] | tuple[float, ...] | float: + ms = fn(*args, **kwargs) + + return distort(ms) + + return wrapper + + +def may_ban_benchmarking() -> None: + if torch._inductor.config.deterministic: + raise RuntimeError("""In the deterministic mode of Inductor, we will avoid those + benchmarkings that would cause non-deterministic results. Only benchmarkings in the vetted + scenarios are allowed. Examples include autotuning for triton configs of pointwise kernels. + + When you see this exception, you can do one of the following two things: + 1. if the benchmarking you are doing does not introduce any non-determinism, you can just + add is_vetted_benchmarking=True to your benchmark_gpu call. That would solve the issue. + + 2. if the benchmarking you are doing indeed introduces non-determinism, you'll need to disable + such feature in deterministic mode or find an alternative implementation that is deterministic. + """) + + +def time_and_count( + fn: Callable[Concatenate[Any, P], T], +) -> Callable[Concatenate[Any, P], T]: + """ + Wraps `fn` to increment the appropriate dynamo counters. It is expected that `fn` + is a method of `Benchmarker` or one of its subclasses; typing limitations prevent + us from declaring this directly. + + NOTE: If you're tempted to add a dynamo_timed call here, this function can be + called enough that the dynamo_timed overhead is not negligible. + """ + + @wraps(fn) + def wrapper(self: Any, *args: P.args, **kwargs: P.kwargs) -> T: + fn_qual_name = f"{self.__class__.__name__}.{fn.__name__}" + counters["inductor"][f"benchmarking.{fn_qual_name}"] += 1 + return fn(self, *args, **kwargs) + + return wrapper + + +class Benchmarker: + """ + A device-agnostic benchmarking utility for measuring the runtime of + inductor generated callables. + """ + + def infer_device(self, *fn_args: Any, **fn_kwargs: Any) -> torch.device: + inferred_device: torch.device | None = None + for arg_or_kwarg in chain(fn_args, fn_kwargs.values()): + # Some callables take nested structures as arguments so use the + # flattened form to find any tensors + for arg_or_kwarg_leaf in pytree.tree_leaves(arg_or_kwarg): + if not isinstance(arg_or_kwarg_leaf, torch.Tensor): + continue + if inferred_device is None: + inferred_device = arg_or_kwarg_leaf.device + elif arg_or_kwarg_leaf.device != inferred_device: + raise ValueError( + "Can't safely infer the device type of `fn` with multiple device types in `fn_args` and `fn_kwargs`!" + ) + + if inferred_device is None: + raise ValueError( + "Can't safely infer the device type of `fn` with no device types" + " in `fn_args` or `fn_kwargs`. Use a direct benchmarking method instead e.g. " + "`Benchmarker.benchmark_cpu` or `Benchmarker.benchmark_gpu`." + ) + + return inferred_device + + @time_and_count + def benchmark( + self: Self, + fn: Callable[..., Any], + fn_args: tuple[Any, ...] | None = None, + fn_kwargs: dict[str, Any] | None = None, + device: str | torch.device | None = None, + **kwargs: Any, + ) -> float: + """Benchmark `fn(*fn_args, *fn_kwargs)` and return the runtime, in milliseconds (the + actual runtime calculation is dictated by the benchmarking implementation, but may be + one of [mean, median, minimum, etc.]). Functions as a convenience wrapper around + device-specific implementations, like `benchmark_cpu` and `benchmark_gpu`. Raises + `ValueError(...)` if we can't safely infer the device type of `fn`; for example, + if multiple device types are found in `fn_args` and `fn_kwargs`, or if no device + types are found. To bypass device inference, provide the device to the `device` + parameter. + + WARNING: if `fn` mutates `fn_args` or `fn_kwargs`, benchmarking may fail unexpectedly. + For example, if `fn` clears a mutable object, subsequent invocations of `fn` during + benchmarking will fail. In such cases, `fn` should handle cloning its arguments internally. + If device inference is required, `Benchmarker.infer_device` can be used prior to calling + this method without any arguments for `fn_args` and `fn_kwargs`. + + Arguments: + - fn: The function to benchmark. + - fn_args: The function's arguments. + - fn_kwargs: The function's kwargs. + + Keyword Arguments: + - device: Which device to use for benchmarking. If not provided the device will be attempted + to be inferred from `fn_args` and `fn_kwargs`. + - **kwargs: The benchmarking implementation's kwargs. + + Returns: + - The runtime of `fn(*fn_args, **fn_kwargs)`, in milliseconds. + """ + inferred_device: torch.device | None = None + if device is not None: + inferred_device = ( + torch.device(device) if isinstance(device, str) else device + ) + else: + if fn_args is None and fn_kwargs is None: + raise ValueError( + "`fn_args` and `fn_kwargs` cannot both be None if `device` is not provided." + ) + + fn_args = fn_args or tuple() + fn_kwargs = fn_kwargs or {} + inferred_device = self.infer_device(*fn_args, **fn_kwargs) + + if not isinstance(inferred_device, torch.device): + raise AssertionError(f"Expected torch.device, got {type(inferred_device)}") + + fn_args = fn_args or tuple() + fn_kwargs = fn_kwargs or {} + + # No need to wrap if the callable takes no arguments + if len(fn_args) == 0 and len(fn_kwargs) == 0: + # Keep a true zero-arg callable type to satisfy type checkers. + def _callable() -> Any: + return fn() + else: + _args = fn_args + _kwargs = fn_kwargs + + def _callable() -> Any: + return fn(*_args, **_kwargs) + + warmup = kwargs.pop("warmup", inductor_config.inductor_default_autotune_warmup) + rep = kwargs.pop("rep", inductor_config.inductor_default_autotune_rep) + + # Surfacing all kernels during autotuning is super noisy; filtering these out. + with DebugMode._benchmarking_inductor(): + # First, try a registered device-specific benchmarker + benchmark_fn: Callable[..., Any] | None = _BENCHMARK_DISPATCH.get( + inferred_device.type + ) + if benchmark_fn is not None: + return benchmark_fn(self, _callable, warmup=warmup, rep=rep, **kwargs) + + # Backward-compatible default: + # - CPU -> CPU benchmark path + # - else -> GPU benchmark path (legacy behavior retained for non-CPU) + if inferred_device == torch.device("cpu"): + return self.benchmark_cpu(_callable, warmup=warmup, rep=rep, **kwargs) + return self.benchmark_gpu(_callable, warmup=warmup, rep=rep, **kwargs) + + @time_and_count + def benchmark_cpu( + self: Self, _callable: Callable[[], Any], warmup: int = 20, rep: int = 100 + ) -> float: + """Benchmark the CPU callable, `_callable`, and return the median runtime, + in milliseconds. + + Arguments: + - _callable: The CPU callable to benchmark. + + Keyword Arguments: + - warmup: Optionally, the duration, in milliseconds, to run `_callable` + before benchmarking starts. + - rep: Optionally, the duration, in milliseconds, to run `_callable` + during benchmarking. + + Returns: + - The median runtime of `_callable`, in milliseconds. + """ + + def run_for(ms: int) -> list[float]: + timings = [] + run_start_t = time.perf_counter() + while True: + start_t = time.perf_counter() + _callable() + end_t = time.perf_counter() + timings.append((end_t - start_t) * MILLISECONDS_PER_SECOND) + if ((end_t - run_start_t) * MILLISECONDS_PER_SECOND) > ms: + break + return timings + + run_for(warmup) + return median(run_for(rep)) + + @time_and_count + def benchmark_gpu(self: Self, *args: Any, **kwargs: Any) -> float: + raise NotImplementedError + + @time_and_count + @gpu_benchmark_lock + def benchmark_gpu_with_cuda_graph( + self: Self, + _callable: Callable[[], Any], + grad_to_none: list[torch.Tensor] | None = None, + **kwargs: Any, + ) -> float: + """Benchmark a GPU callable using CUDA graph capture and replay. + + This captures the callable into a CUDA graph and benchmarks the graph replay, + which eliminates kernel launch overhead for fair comparison between different + implementations. + """ + # Warmup + torch.cuda.synchronize() + _callable() + torch.cuda.synchronize() + + # Side-stream warmup then capture + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + if grad_to_none is not None: + for x in grad_to_none: + x.grad = None + _callable() + stream.synchronize() + + cuda_graph = torch.cuda.CUDAGraph() + with torch.cuda.graph( + cuda_graph, stream=stream, capture_error_mode="thread_local" + ): + if grad_to_none is not None: + for x in grad_to_none: + x.grad = None + _callable() + + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + + # grad clearing is captured in the graph, don't pass it through. + return self.benchmark_gpu(cuda_graph.replay, **kwargs) + + +# Make built-in defaults explicit via the registry +def _default_cpu_bench(self, f, *, warmup, rep, **kw): + return self.benchmark_cpu(f, warmup=warmup, rep=rep, **kw) + + +def _default_cuda_bench(self, f, *, warmup, rep, **kw): + kw.setdefault("device_type", "cuda") + return self.benchmark_gpu(f, warmup=warmup, rep=rep, **kw) + + +def _default_xpu_bench(self, f, *, warmup, rep, **kw): + kw.setdefault("device_type", "xpu") + return self.benchmark_gpu(f, warmup=warmup, rep=rep, **kw) + + +register_benchmarker("cpu", _default_cpu_bench, override=True) +register_benchmarker("cuda", _default_cuda_bench, override=True) +register_benchmarker("xpu", _default_xpu_bench, override=True) + + +def _get_callable_device_kernel_time_us( + kineto_events: Any, + profiler_events: Any, + rep: int, + profiler_device_type: Any, +) -> float: + from torch.autograd import DeviceType + + benchmark_event_ids: OrderedSet[int] = OrderedSet() + + def collect_cpu_event_ids(event: Any) -> None: + if event.device_type != DeviceType.CPU: + return + + benchmark_event_ids.add(event.id) + for child in event.cpu_children: + collect_cpu_event_ids(child) + + benchmark_events = [ + event + for event in profiler_events + if event.name == _CALLABLE_PROFILE_EVENT_NAME + and event.device_type == DeviceType.CPU + ] + if len(benchmark_events) != rep: + raise RuntimeError( + f"Expected {rep} {_CALLABLE_PROFILE_EVENT_NAME} profiling events. " + f"Found {len(benchmark_events)} events." + ) + + for event in benchmark_events: + collect_cpu_event_ids(event) + + # An op may re-dispatch internally (e.g. aten::sum with no dim calls + # aten::sum with dim), producing a kineto CPU event whose corr ID the + # device kernel links to but which is absent from the profiler event tree. + # Include kineto corr IDs of all CPU events within the _CALLABLE time + # window to cover these hidden dispatches. + callable_kineto_windows: list[tuple[int, int]] = [] + for ev in kineto_events: + if ( + ev.name() == _CALLABLE_PROFILE_EVENT_NAME + and ev.device_type() == DeviceType.CPU + ): + callable_kineto_windows.append((ev.start_ns(), ev.end_ns())) + + if callable_kineto_windows: + for ev in kineto_events: + if ev.device_type() != DeviceType.CPU: + continue + ev_start = ev.start_ns() + ev_end = ev.end_ns() + for win_start, win_end in callable_kineto_windows: + if ev_start >= win_start and ev_end <= win_end: + benchmark_event_ids.add(ev.correlation_id()) + break + + device_time_us = 0.0 + for event in kineto_events: + linked_correlation_id = event.linked_correlation_id() + correlation_id = event.correlation_id() + activity_type = event.activity_type() + if ( + event.device_type() == profiler_device_type + and activity_type != "gpu_user_annotation" + and ( + linked_correlation_id in benchmark_event_ids + or ( + linked_correlation_id == 0 and correlation_id in benchmark_event_ids + ) + ) + and event.name() != "Context Sync" + ): + device_time_us += (event.end_ns() - event.start_ns()) / 1000.0 + + return device_time_us + + +class TritonBenchmarker(Benchmarker): + @cached_property + def triton_do_bench(self: Self) -> Callable[..., Any]: + """Lazily import Triton's `do_bench`.""" + try: + from triton.testing import do_bench + except ImportError as e: + raise NotImplementedError("requires Triton") from e + return do_bench + + @may_distort_benchmarking_result + @time_and_count + @gpu_benchmark_lock + # pyrefly: ignore [bad-override] + def benchmark_gpu( + self: Self, + _callable: Callable[[], Any], + is_vetted_benchmarking: bool = False, + **kwargs: Any, + ) -> float: + """Benchmark the GPU callable, `_callable`, and return the runtime, in milliseconds. + + Arguments: + - _callable: The GPU callable to benchmark. + + Keyword Arguments: + - quantiles: Optionally, a tuple of floats denoting the requested quantiles. + - return_mode: Optionally, the requested return mode. Currently, Triton's + `do_bench` supports min, max, mean, and median return modes. + - **kwargs: Additional kwargs passed to Triton's `do_bench`. + + Returns: + - The runtime of `callable`, in milliseconds. If `kwargs["quantiles"]` is specified, + this is the first requested quantile. Else, if `kwargs["return_mode"]` is specified, + this is the requested return mode. Otherwise, this is the median. + """ + if not is_vetted_benchmarking: + may_ban_benchmarking() + + do_bench_params = inspect.signature(self.triton_do_bench).parameters + for kwarg in list(kwargs.keys()): + if kwarg not in do_bench_params: + del kwargs[kwarg] + try: + if "quantiles" in kwargs: + return self.triton_do_bench(_callable, **kwargs)[0] + elif "return_mode" in kwargs: + return self.triton_do_bench(_callable, **kwargs) + return self.triton_do_bench(_callable, **kwargs, return_mode="median") + except Exception as e: + # ErrorInvalidConfiguration + # Return inf to skip this config during autotuning + error_str = str(e).lower() + if "invalid configuration" in error_str: + logger.warning( + "Skipping benchmark due to invalid configuration error: %s", + error_str, + ) + return float("inf") + raise + + +class InductorBenchmarker(TritonBenchmarker): # noqa: docstring_linter + def __init__(self: Self) -> None: + super().__init__() + self._in_cudagraph_benchmark = False + + @cached_property + def L2_cache_size(self: Self) -> int: + """Get the L2 cache size, in bytes, of the current device.""" + return self.get_device_cache_size() + + def get_device_cache_size( + self: Self, device_type: str | torch.device | None = None + ) -> int: + """Get the L2/global cache size, in bytes, of the current device.""" + if "L2_cache_size" in self.__dict__: + return self.__dict__["L2_cache_size"] + + device_type = _normalize_gpu_device_type(device_type) + device_interface = get_interface_for_device(device_type) + device = device_interface.current_device() + props = device_interface.get_device_properties(device) + for attr in ("L2_cache_size", "last_level_cache_size"): + cache_size = getattr(props, attr, None) + if cache_size: + return cache_size + return 256 * 1024 * 1024 + + def get_event_pairs( + self: Self, iters: int, device_type: str | torch.device | None = None + ) -> list[tuple[Any, Any]]: + """Get `iters` pairs of device events.""" + device_interface = get_interface_for_device( + _normalize_gpu_device_type(device_type) + ) + return [ + ( + device_interface.Event(enable_timing=True), + device_interface.Event(enable_timing=True), + ) + for _ in range(iters) + ] + + def get_event_pairs_min_timing( + self: Self, event_pairs: list[tuple[Any, Any]] + ) -> float: + """Get the minimum timing, in milliseconds, for a group of event pairs.""" + return min( + [ + start_event.elapsed_time(end_event) + for start_event, end_event in event_pairs + ] + ) + + @time_and_count + def benchmark_gpu_with_cuda_graph( + self: Self, + _callable: Callable[[], Any], + grad_to_none: list[torch.Tensor] | None = None, + **kwargs: Any, + ) -> float: + # Prevent benchmark_gpu from re-entering this method + # when autotune_cudagraph_benchmarking is enabled. + self._in_cudagraph_benchmark = True + try: + result = super().benchmark_gpu_with_cuda_graph( + _callable, grad_to_none=grad_to_none, **kwargs + ) + finally: + self._in_cudagraph_benchmark = False + return result + + @may_distort_benchmarking_result + @time_and_count + @gpu_benchmark_lock + def benchmark_gpu( # type: ignore[override] + self: Self, + _callable: Callable[[], Any], + estimation_iters: int = 5, + memory_warmup_iters: int = 100, + benchmark_iters: int = 100, + max_benchmark_duration: int = 25, + return_mode: str = "min", + grad_to_none: list[torch.Tensor] | None = None, + is_vetted_benchmarking: bool = False, + device_type: str | torch.device | None = None, + **kwargs: Any, + ) -> float | list[float]: + """Benchmark a GPU callable using a custom benchmarking implementation. + + Arguments: + - _callable: The callable to benchmark. + + Keyword Arguments: + - estimation_iters: Optionally, the number of iterations to run `_callable` + during runtime estimation. + - memory_warmup_iters: Optionally, the number of iterations to flush the L2 + cache before starting benchmarking. + - benchmark_iters: Optionally, the number of iterations to run `_callable` + during the benchmarking. + - max_benchmark_duration: Optionally, the maximum duration of the benchmarking, + in milliseconds. An estimated duration is calculated based on the values + of `memory_warmup_iters` and `benchmark_iters`, along with the estimated + runtime of `_callable` and various other factors, and we then shrink + `benchmark_iters` to fit in the allotted maximum duration. + - return_mode: Return mode for benchmark results. Options are "min" (default), + "all" (returns all measurements). + - grad_to_none: Optionally, a list of tensors whose gradients should be cleared + before each benchmark iteration. + - is_vetted_benchmarking: in deterministic mode, we only allow + benchmarking in vetted cases. + - **kwargs: Additional kwargs that may be passed to the fallback. + + Returns: + - If return_mode="min": The minimum runtime of `_callable`, in milliseconds. + - If return_mode="all": List of all runtime measurements, in milliseconds. + """ + + if not is_vetted_benchmarking: + may_ban_benchmarking() + + device_type = _normalize_gpu_device_type(device_type) + device_interface = get_interface_for_device(device_type) + + if ( + device_type == "cuda" + and inductor_config.autotune_cudagraph_benchmarking + and inductor_config.max_autotune + and not self._in_cudagraph_benchmark + ): + try: + return self.benchmark_gpu_with_cuda_graph( + _callable, + estimation_iters=estimation_iters, + memory_warmup_iters=memory_warmup_iters, + benchmark_iters=benchmark_iters, + max_benchmark_duration=max_benchmark_duration, + return_mode=return_mode, + grad_to_none=grad_to_none, + device_type=device_type, + ) + except RuntimeError: + logger.warning( + "CUDA graph capture failed during benchmarking, " + "falling back to eager benchmarking", + exc_info=True, + ) + + # we don't want any outside errors propagating into benchmarking + device_interface.synchronize() + + # warmup `_callable` (and catches any failures in the process) + _callable() + device_interface.synchronize() + + # see https://github.com/triton-lang/triton/pull/840 for why `dtype=torch.int` + buffer = torch.empty( + self.get_device_cache_size(device_type) // 4, + dtype=torch.int, + device=device_type, + ) + buffer.zero_() + + # estimate the runtime of `_callable` + event_pairs = self.get_event_pairs(estimation_iters, device_type=device_type) + for start_event, end_event in event_pairs: + # Clear gradients before timing (matches triton.testing.do_bench) + if grad_to_none is not None: + for x in grad_to_none: + x.grad = None + buffer.zero_() + start_event.record() + _callable() + end_event.record() + device_interface.synchronize() + estimated_timing = self.get_event_pairs_min_timing(event_pairs) + + # adjust `benchmark_iters` to fit in the maximum benchmarking duration + if estimated_timing > 0: + benchmark_iters = max( + min(benchmark_iters, int(max_benchmark_duration // estimated_timing)), 1 + ) + + # do the memory warmup + for _ in range(memory_warmup_iters): + buffer.zero_() + + # benchmark `_callable` + event_pairs = self.get_event_pairs(benchmark_iters, device_type=device_type) + for start_event, end_event in event_pairs: + # Clear gradients before timing (matches triton.testing.do_bench) + if grad_to_none is not None: + for x in grad_to_none: + x.grad = None + buffer.zero_() + start_event.record() + _callable() + end_event.record() + device_interface.synchronize() + + # explicitly delete the buffer, sometimes helps memory + # footprint metrics in OSS Inductor performance benchmarks + del buffer + + # Return based on the requested mode + if return_mode == "all": + # Get all timings from event pairs + all_timings = [ + start_event.elapsed_time(end_event) + for start_event, end_event in event_pairs + ] + return all_timings + elif return_mode == "min": + benchmarked_timing = self.get_event_pairs_min_timing(event_pairs) + # return the minimum of `estimated_timing` and `benchmarked_timing`, + # we just want the minimum timing overall so we might as well check both + return min(estimated_timing, benchmarked_timing) + else: + raise ValueError( + f"Unsupported return_mode: {return_mode}. Use 'min' or 'all'." + ) + + +class TorchProfilerBenchmarker(InductorBenchmarker): # noqa: docstring_linter + """Benchmarker that uses torch.profiler for GPU kernel benchmarking.""" + + @time_and_count + @gpu_benchmark_lock + def benchmark_gpu( # type: ignore[override] + self: Self, + _callable: Callable[[], Any], + warmup: int = 25, + rep: int = 100, + estimation_iters: int = 5, + memory_warmup_iters: int = 10, + max_benchmark_duration: int = 25, + return_mode: str = "mean", + grad_to_none: list[torch.Tensor] | None = None, + device_type: str | torch.device | None = None, + **kwargs: Any, + ) -> float: + """Benchmark a GPU callable using torch.profiler. + + Arguments: + - _callable: The callable to benchmark. + + Keyword Arguments: + - warmup: Ignored (kept for API compat). Warmup is handled by the + estimation phase which runs estimation_iters with cache flushing. + - rep: Optionally, the maximum number of iterations to run during benchmarking. + - estimation_iters: Optionally, the number of iterations used to estimate + the runtime of `_callable` for dynamic rep adjustment. These iterations + also serve as warmup for the callable. + - memory_warmup_iters: Optionally, the number of buffer.zero_() iterations + to run after estimation to bring the cache into a steady state before + the profiled benchmark phase. + - max_benchmark_duration: Optionally, the maximum duration of the profiled + benchmark phase, in milliseconds. The rep count is reduced if the + estimated total would exceed this budget. + - return_mode: Return mode for benchmark results. Options are "min", "mean" (default), + or "max". + - grad_to_none: Optionally, a list of tensors whose gradients should be cleared + before each benchmark iteration. + - **kwargs: Additional kwargs that may be passed to the fallback. + + Returns: + - The runtime of `_callable` in milliseconds, computed according to return_mode. + """ + device_type = _normalize_gpu_device_type(device_type) + device_interface = get_interface_for_device(device_type) + + # we don't want any outside errors propagating into benchmarking + device_interface.synchronize() + + # warmup `_callable` (and catches any failures in the process) + _callable() + device_interface.synchronize() + + # Keep Triton's 256 MB cache flush on ROCm. On other backends, reuse + # the shared L2-sized flush from InductorBenchmarker. + # see https://github.com/triton-lang/triton/pull/840 for why `dtype=torch.int` + if torch.version.hip: + buffer_size_bytes = 256 * 1024 * 1024 + else: + buffer_size_bytes = self.get_device_cache_size(device_type) + buffer = torch.empty( + buffer_size_bytes // 4, dtype=torch.int, device=device_type + ) + buffer.zero_() + + # Estimation phase with separate event pairs — also serves as warmup. + # Using per-iteration event pairs lets us take the min, matching + # InductorBenchmarker's approach for a more robust estimate. + event_pairs = self.get_event_pairs(estimation_iters, device_type=device_type) + for start_event, end_event in event_pairs: + if grad_to_none is not None: + for x in grad_to_none: + x.grad = None + buffer.zero_() + start_event.record() + _callable() + end_event.record() + device_interface.synchronize() + estimated_ms = self.get_event_pairs_min_timing(event_pairs) + if estimated_ms > 0: + rep = max(min(rep, int(max_benchmark_duration / estimated_ms)), 1) + + # Light memory warmup: flush the cache into a steady state before + # the profiled run. No callable — estimation already warmed it. + for _ in range(memory_warmup_iters): + buffer.zero_() + + # benchmark with profiler + # Use both CPU and device activities, otherwise record_function + # will not record the region. + device_type_upper = device_type.upper() + profile_activity = getattr(torch.profiler.ProfilerActivity, device_type_upper) + with torch.profiler.profile( + activities=[ + torch.profiler.ProfilerActivity.CPU, + profile_activity, + ], + record_shapes=False, + ) as prof: + for _ in range(rep): + if grad_to_none is not None: + for x in grad_to_none: + x.grad = None + buffer.zero_() + + with torch.profiler.record_function("_CALLABLE"): + _callable() + + device_interface.synchronize() + + # Extract _CALLABLE GPU time directly from raw kineto events. + # This avoids prof.key_averages() which triggers expensive lazy + # processing: _parse_kineto_results (wrapping every raw event in + # a Python FunctionEvent), _build_tree, and grouping/aggregation. + from torch.autograd import DeviceType as _DeviceType + + profiler_device_type = getattr(_DeviceType, device_type_upper) + callable_gpu_time_us = 0.0 + for kineto_event in prof.profiler.kineto_results.events(): + if ( + kineto_event.name() == _CALLABLE_PROFILE_EVENT_NAME + and kineto_event.device_type() == profiler_device_type + ): + callable_gpu_time_us += ( + kineto_event.end_ns() - kineto_event.start_ns() + ) / 1000.0 + + if callable_gpu_time_us <= 0: + callable_gpu_time_us = _get_callable_device_kernel_time_us( + prof.profiler.kineto_results.events(), + prof.events(), + rep, + profiler_device_type, + ) + + if callable_gpu_time_us <= 0: + raise AssertionError( + f"TorchProfilerBenchmarker: '_CALLABLE' {device_type_upper} event not found in " + "raw kineto results, and no correlated device events were found." + ) + + # TODO: Revisit incorporating launch overhead effects. + total_time_us = callable_gpu_time_us + avg_time_ms = (total_time_us / rep) / 1000.0 + + # explicitly delete the buffer, sometimes helps memory + # footprint metrics in OSS Inductor performance benchmarks + del buffer + + # Return based on the requested mode + # Note: For profiler-based benchmarking, we return the mean time per iteration + # min/max modes are kept for API compatibility but return the mean + if return_mode in ("min", "mean", "max"): + return avg_time_ms + else: + raise ValueError( + f"Unsupported return_mode: {return_mode}. Use 'min', 'mean', or 'max'." + ) + + +def _make_default_benchmarker() -> Benchmarker: + if inductor_config.use_torch_profiler_benchmarker: + return TorchProfilerBenchmarker() + if inductor_config.use_experimental_benchmarker: + return InductorBenchmarker() + return TritonBenchmarker() + + +benchmarker = _make_default_benchmarker() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/cache_dir_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/cache_dir_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a2e9655d8f9e4811c15b582a972f5641506cd468 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/cache_dir_utils.py @@ -0,0 +1,61 @@ +import getpass +import os +import re +import tempfile +from collections.abc import Generator +from contextlib import contextmanager + +from torch._environment import is_fbcode + + +# Factoring out to file without torch dependencies + + +def cache_dir() -> str: + cache_dir = os.environ.get("TORCHINDUCTOR_CACHE_DIR") + if cache_dir is None: + cache_dir = default_cache_dir() + cache_dir = os.path.abspath(cache_dir) + os.environ["TORCHINDUCTOR_CACHE_DIR"] = cache_dir + os.makedirs(cache_dir, exist_ok=True) + return cache_dir + + +def default_cache_dir() -> str: + try: + username = getpass.getuser() + except (KeyError, ModuleNotFoundError, OSError): + getuid = getattr(os, "getuid", None) + username = f"uid_{getuid()}" if callable(getuid) else "unknown_user" + sanitized_username = re.sub(r'[\\/:*?"<>|]', "_", username) + return os.path.join( + tempfile.gettempdir() if not is_fbcode() else "/var/tmp", + "torchinductor_" + sanitized_username, + ) + + +def triton_cache_dir(device: int) -> str: + if (directory := os.getenv("TRITON_CACHE_DIR")) is not None: + return directory + return os.path.join( + cache_dir(), + "triton", + str(device), + ) + + +@contextmanager +def temporary_cache_dir(directory: str) -> Generator[None, None, None]: + from torch._inductor.utils import clear_caches + + original = os.environ.get("TORCHINDUCTOR_CACHE_DIR") + os.environ["TORCHINDUCTOR_CACHE_DIR"] = directory + try: + clear_caches() + yield + finally: + clear_caches() + if original is None: + del os.environ["TORCHINDUCTOR_CACHE_DIR"] + else: + os.environ["TORCHINDUCTOR_CACHE_DIR"] = original diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..69c0821ec15e0106beb25f37efcdeb19f50a3a2e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__init__.py @@ -0,0 +1,32 @@ +from . import config, encoders, memoizers +from .context import IsolationSchema, SelectedCompileContext, SelectedRuntimeContext +from .exceptions import ( + CacheError, + FileLockTimeoutError, + KeyEncodingError, + LockTimeoutError, + SystemError, + UserError, + ValueDecodingError, + ValueEncodingError, +) +from .interfaces import Memoizer, PersistentMemoizer + + +__all__ = [ + "CacheError", + "FileLockTimeoutError", + "IsolationSchema", + "KeyEncodingError", + "LockTimeoutError", + "Memoizer", + "PersistentMemoizer", + "SelectedCompileContext", + "SelectedRuntimeContext", + "SystemError", + "UserError", + "ValueDecodingError", + "ValueEncodingError", + "encoders", + "memoizers", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d67f5235eead4a11160a1601ab2cc305f999c2f8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d1fefd03b051347218110bc80403b0cb163cca8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff31c20a5f148985b7c1f5c14f0db49896079d30 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/encoders.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/encoders.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..010a08e82e2f5a28bfb3fdbcdffdba310215b02b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/encoders.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/exceptions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..266ce608c6e46a4dcb4051ba4528f45ac5e12a19 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/exceptions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/implementations.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/implementations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68b4cd97b54db5ec82313182c295518eda90b3f5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/implementations.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/interfaces.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/interfaces.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53d891853fa0dca830fd39e706bf36bc3bcc5d5b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/interfaces.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/locks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/locks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2104980cf780ca920889f06338b060881422fa74 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/locks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/memoizers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/memoizers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4afa00b42eeff90adadefe04831cacc97b12b20 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/memoizers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2874517f46d2f9b4448a80cbe0586667e8a55ddd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/config.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/config.py new file mode 100644 index 0000000000000000000000000000000000000000..5655e6affe2f18d0f2f6a3848278e5f298802300 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/config.py @@ -0,0 +1,167 @@ +import os +from collections.abc import Callable +from functools import cache, partial +from typing import TypeVar + +import torch +from torch._environment import is_fbcode + + +T = TypeVar("T") + + +def _is_force_disable_caches() -> bool: + """Check if caching is force disabled via inductor config. + + This defers importing torch._inductor.config to avoid circular imports. + + Returns: + True if force_disable_caches is set in inductor config, False otherwise. + """ + from torch._inductor import config as inductor_config + + return inductor_config.force_disable_caches + + +@cache +def _env_var_val(env_var: str, default: T) -> str | T: + """Get the value of an environment variable or return the default. + + Args: + env_var: Environment variable name to check + default: Default value to return if environment variable is not set + + Returns: + The value from the environment variable as a string, or the default if not set + """ + return os.environ.get(env_var, default) + + +@cache +def _env_var_config(env_var: str, default: bool) -> bool: + env_val = _env_var_val(env_var, None) + if env_val is not None: + return env_val == "1" + return default + + +@cache +def _versioned_config( + jk_name: str, + this_version: int, + oss_default: bool, + env_var_override: str | None = None, +) -> bool: + """ + A versioned configuration utility that determines boolean settings based on: + 1. Environment variable override (highest priority) + 2. JustKnobs version comparison in fbcode environments + 3. OSS default fallback + + This function enables gradual rollouts of features in fbcode by comparing + a local version against a JustKnobs-controlled remote version, while + allowing environment variable overrides for testing and OSS defaults + for non-fbcode environments. + + Args: + jk_name: JustKnobs key name (e.g., "pytorch/inductor:feature_version") + this_version: Local version number to compare against JustKnobs version + oss_default: Default value to use in non-fbcode environments + env_var_override: Optional environment variable name that, when set, + overrides all other logic + + Returns: + bool: Configuration value determined by the priority order above + """ + if ( + env_var_override + and (env_var_value := os.environ.get(env_var_override)) is not None + ): + return env_var_value == "1" + elif is_fbcode(): + # this method returns 0 on failure, which we should check for specifically. + # in the case of JK failure, the safe bet is to simply disable the config + jk_version: int = torch._utils_internal.justknobs_getval_int(jk_name) + return (this_version >= jk_version) and (jk_version != 0) + return oss_default + + +# toggles the entire caching module, but only when calling through the +# public facing interfaces. get/insert operations become no-ops in the sense +# that get will always miss and insert will never insert; record becomes a +# no-op in the sense that the function will always be called and the cache +# will never be accessed +_CACHING_MODULE_VERSION: int = 0 +_CACHING_MODULE_VERSION_JK: str = "pytorch/inductor:caching_module_version" +_CACHING_MODULE_OSS_DEFAULT: bool = False +_CACHING_MODULE_ENV_VAR_OVERRIDE: str = "TORCHINDUCTOR_ENABLE_CACHING_MODULE" + + +def _is_caching_module_enabled_base() -> bool: + """Base check for caching module enablement via versioned config.""" + return _versioned_config( + _CACHING_MODULE_VERSION_JK, + _CACHING_MODULE_VERSION, + _CACHING_MODULE_OSS_DEFAULT, + _CACHING_MODULE_ENV_VAR_OVERRIDE, + ) + + +def IS_CACHING_MODULE_ENABLED() -> bool: + """Check if the caching module is enabled. + + Returns False if: + - The versioned config disables it + - force_disable_caches is set in inductor config + + Returns: + True if caching module is enabled, False otherwise. + """ + if not _is_caching_module_enabled_base(): + return False + if _is_force_disable_caches(): + return False + return True + + +# Controls whether the Memoizer dumps its cache to a JSON file on destruction. +# When enabled, the Memoizer will write its in-memory cache to a JSON file +# (memoizer_cache.json in the cache directory) on destruction. This dump file +# can later be used to pre-populate Memoizers via CACHE_DUMP_FILE_PATH. +# +# This is useful for: +# - Debugging and inspection of cached values +# - Creating cache snapshots that can be reused across runs +# - Pre-warming caches for subsequent executions +# +# Set via environment variable: TORCHINDUCTOR_DUMP_MEMOIZER_CACHE=1 +_DUMP_MEMOIZER_CACHE_ENV_VAR: str = "TORCHINDUCTOR_DUMP_MEMOIZER_CACHE" +_DUMP_MEMOIZER_CACHE_DEFAULT: bool = False +IS_DUMP_MEMOIZER_CACHE_ENABLED: Callable[[], bool] = partial( + _env_var_config, + _DUMP_MEMOIZER_CACHE_ENV_VAR, + _DUMP_MEMOIZER_CACHE_DEFAULT, +) + + +# Path to a cache dump file to pre-populate Memoizers on initialization. +# This should point to a JSON file produced by IS_DUMP_MEMOIZER_CACHE_ENABLED. +# +# When set, Memoizers will load cached entries from this file on initialization, +# allowing cache values to be reused across separate runs without recomputation. +# This is particularly useful for: +# - Pre-warming caches with known-good values +# - Reproducing behavior from a previous run +# - Sharing cached computations across different environments +# +# The dump file format is produced by the Memoizer's _dump_to_disk method when +# IS_DUMP_MEMOIZER_CACHE_ENABLED is set to true. +# +# Set via environment variable: TORCHINDUCTOR_CACHE_DUMP_FILE_PATH=/path/to/dump.json +_CACHE_DUMP_FILE_PATH_ENV_VAR: str = "TORCHINDUCTOR_CACHE_DUMP_FILE_PATH" +_CACHE_DUMP_FILE_PATH_DEFAULT: str | None = None +CACHE_DUMP_FILE_PATH: Callable[[], str | None] = partial( + _env_var_val, + _CACHE_DUMP_FILE_PATH_ENV_VAR, + _CACHE_DUMP_FILE_PATH_DEFAULT, +) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/context.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/context.py new file mode 100644 index 0000000000000000000000000000000000000000..deef8a97b00507056ae06cd604c2fbf4bb6c7691 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/context.py @@ -0,0 +1,310 @@ +"""Context management for PyTorch Inductor runtime caching. + +This module provides context classes for collecting configuration and environment +information used in caching decisions for PyTorch's Inductor runtime. +""" + +import json +from abc import ABC, abstractmethod +from base64 import b64encode +from collections.abc import Sequence +from functools import cache +from hashlib import sha256 +from typing_extensions import override, TypedDict + +import torch + + +class _Context(ABC): + """Abstract base class for context providers. + + Context providers collect specific configuration and environment information + that affects compilation and runtime behavior. + """ + + @staticmethod + @abstractmethod + def forms_of_context() -> Sequence[str]: + """Return a sequence of context form names provided by this context class. + + Returns: + A sequence of strings representing the available context forms. + """ + + +class _RuntimeContext(_Context): + """Context provider for runtime configuration and environment settings. + + Collects configuration settings that affect runtime behavior but not + compilation, such as Inductor configs, determinism settings, and CUDA + matmul precision configurations. + """ + + @override + @staticmethod + def forms_of_context() -> Sequence[str]: + """Return the runtime context forms provided by this class. + + Returns: + A sequence containing the available runtime context forms: + - "inductor_configs": PyTorch Inductor configuration settings + - "torch_determinism_configs": Deterministic algorithm settings + - "cuda_matmul_precision_configs": CUDA matrix multiplication precision settings + """ + return ( + "inductor_configs", + "torch_determinism_configs", + "cuda_matmul_precision_configs", + ) + + @staticmethod + def inductor_configs() -> dict[str, object]: + """Get portable Inductor configuration settings. + + Returns: + A dictionary containing Inductor configuration settings, + including private configs. + """ + from torch._inductor import config + + return config.save_config_portable(ignore_private_configs=False) + + @staticmethod + def torch_determinism_configs() -> dict[str, object]: + """Get PyTorch deterministic algorithm configuration settings. + + Returns: + A dictionary containing deterministic algorithm settings: + - Whether deterministic algorithms are enabled + - Whether deterministic algorithm warnings are enabled + - Fill uninitialized memory setting + """ + return { + "torch.are_deterministic_algorithms_enabled": torch.are_deterministic_algorithms_enabled(), + "torch.is_deterministic_algorithms_warn_only_enabled": ( + torch.is_deterministic_algorithms_warn_only_enabled() + ), + "torch.utils.deterministic.fill_uninitialized_memory": getattr( + torch.utils.deterministic, "fill_uninitialized_memory", None + ), + } + + @staticmethod + def cuda_matmul_precision_configs() -> dict[str, object]: + """Get CUDA matrix multiplication precision configuration settings. + + Returns: + A dictionary containing CUDA matmul precision settings: + - FP32 precision setting + - FP16 reduced precision reduction allowance + - BF16 reduced precision reduction allowance + """ + return { + "torch.backends.cuda.matmul.fp32_precision": torch.backends.cuda.matmul.fp32_precision, + "torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction": ( + torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction + ), + "torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction": ( + torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction + ), + } + + +class _CompileContext(_Context): + """Context provider for compilation-related configuration and environment settings. + + Collects information that affects compilation behavior, such as PyTorch and Triton + versions, runtime environment, and accelerator properties. + """ + + @override + @staticmethod + def forms_of_context() -> Sequence[str]: + """Return the compile context forms provided by this class. + + Returns: + A sequence containing the available compile context forms: + - "torch_version_hash": PyTorch version hash + - "triton_version_hash": Triton version hash (if available) + - "runtime": Runtime type (CUDA/HIP/None) + - "runtime_version": Runtime version string + - "accelerator_properties": GPU/accelerator properties + """ + return ( + "torch_version_hash", + "triton_version_hash", + "runtime", + "runtime_version", + "accelerator_properties", + ) + + @cache + @staticmethod + def torch_version_hash() -> str: + """Get base64-encoded PyTorch version hash. + + Returns: + A base64-encoded string representing the PyTorch version hash. + """ + from torch._inductor.codecache import torch_key + + return b64encode(torch_key()).decode() + + @cache + @staticmethod + def triton_version_hash() -> str | None: + """Get Triton version key if Triton is available. + + Returns: + Triton version key if Triton is available, None otherwise. + """ + from torch._inductor.runtime.triton_compat import HAS_TRITON, triton_key + + return triton_key() if HAS_TRITON else None + + @cache + @staticmethod + def runtime() -> str | None: + """Determine the runtime type based on available backends. + + Returns: + "CUDA" if CUDA is available, "HIP" if HIP is available, None otherwise. + """ + return "CUDA" if torch.version.cuda else "HIP" if torch.version.hip else None + + @cache + @staticmethod + def runtime_version() -> str | None: + """Get the version string for the detected runtime. + + Returns: + Version string for the current runtime (CUDA or HIP), or None if + no supported runtime is detected. + """ + return { + "CUDA": torch.version.cuda, + "HIP": torch.version.hip, + "None": None, + }.get(_CompileContext.runtime() or "None") + + @cache + @staticmethod + def accelerator_properties() -> str | None: + """Get string representation of CUDA device properties. + + Returns: + String representation of CUDA device properties if a runtime is + available, None otherwise. + """ + return ( + repr(torch.cuda.get_device_properties()) + if _CompileContext.runtime() and torch.cuda.is_available() + else None + ) + + +class SelectedRuntimeContext(TypedDict): + inductor_configs: bool + torch_determinism_configs: bool + cuda_matmul_precision_configs: bool + + +class SelectedCompileContext(TypedDict): + torch_version_hash: bool + triton_version_hash: bool + runtime: bool + runtime_version: bool + accelerator_properties: bool + + +class IsolationSchema(TypedDict): + """Schema for specifying which context forms to include in cache isolation. + + Attributes: + runtime_context: Either True (include all runtime context), False (exclude all), + or a SelectedRuntimeContext dict specifying which forms to include. + compile_context: Either True (include all compile context), False (exclude all), + or a SelectedCompileContext dict specifying which forms to include. + """ + + runtime_context: SelectedRuntimeContext | bool + compile_context: SelectedCompileContext | bool + + +_DEFAULT_ISOLATION_SCHEMA: IsolationSchema = IsolationSchema( + runtime_context=True, compile_context=True +) + + +def _collect_runtime_context( + selection: SelectedRuntimeContext | bool, +) -> dict[str, object] | None: + """Collect runtime context based on selection. + + Args: + selection: True to include all, False to exclude all, or a dict + specifying which forms to include. + + Returns: + Dictionary of selected context data, or None if excluded. + """ + return { + form: getattr(_RuntimeContext, form)() + for form in _RuntimeContext.forms_of_context() + if selection is True or (selection and selection.get(form, False)) + } or None + + +def _collect_compile_context( + selection: SelectedCompileContext | bool, +) -> dict[str, object] | None: + """Collect compile context based on selection. + + Args: + selection: True to include all, False to exclude all, or a dict + specifying which forms to include. + + Returns: + Dictionary of selected context data, or None if excluded. + """ + return { + form: getattr(_CompileContext, form)() + for form in _CompileContext.forms_of_context() + if selection is True or (selection and selection.get(form, False)) + } or None + + +def _isolation_context( + ischema: IsolationSchema = _DEFAULT_ISOLATION_SCHEMA, +) -> dict[str, object]: + """Generate context data based on the isolation schema. + + Args: + ischema: Schema specifying which context forms to include. + Defaults to including all runtime and compile context. + + Returns: + A dictionary containing the selected context data with keys + "runtime_context" and "compile_context", where each value is + either None (if excluded) or a dict of context form data. + """ + return { + "runtime_context": _collect_runtime_context(ischema["runtime_context"]), + "compile_context": _collect_compile_context(ischema["compile_context"]), + } + + +def _isolation_key(ischema: IsolationSchema = _DEFAULT_ISOLATION_SCHEMA) -> str: + """Generate a unique key for the given isolation schema. + + Args: + ischema: Schema specifying which context forms to include. + Defaults to including all runtime and compile context. + + Returns: + A 32-character hexadecimal string that uniquely identifies + the context specified by the isolation schema. + """ + return sha256( + json.dumps(_isolation_context(ischema), sort_keys=True).encode() + ).hexdigest()[:32] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/encoders.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/encoders.py new file mode 100644 index 0000000000000000000000000000000000000000..24a8473bdd5d86c62de08064359689f8957eb617 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/encoders.py @@ -0,0 +1,68 @@ +""" +Custom encoder functions + +This module provides reusable encoder functions that convert function parameters +into JSON-serializable dictionaries for caching purposes. +""" + +from typing_extensions import TypedDict + +import torch +from torch import Tensor +from torch._inductor.pattern_matcher import Match +from torch._inductor.runtime.caching.utils import _encode_tensor, EncodedTensor + + +class ShouldPadEncodedParams(TypedDict): + """TypedDict for encoded should_pad parameters.""" + + mat1: EncodedTensor + mat2: EncodedTensor + op: str + input: EncodedTensor | None + mat1_exclude_padding_time: bool + mat2_exclude_padding_time: bool + tf32: bool + + +def should_pad_params_encoder( + match: Match, + mat1: Tensor, + mat2: Tensor, + op: torch._ops.OpOverloadPacket, + input: Tensor | None = None, +) -> ShouldPadEncodedParams: + """Encode parameters for _should_pad into a human-readable dict. + + This encoder extracts only the information needed for caching: + - Tensor shape, stride, and dtype (not the actual data) + - Whether padding time should be excluded for mat1 and mat2 + - The operation as a string + + Args: + match: The pattern match object + mat1: First matrix tensor + mat2: Second matrix tensor + op: The operation being performed + input: Optional input tensor for addmm + + Returns: + A dict containing the encoded parameters in human-readable form + """ + # Import here to avoid circular dependency + from torch._inductor.fx_passes.pad_mm import should_exclude_padding_time + + return ShouldPadEncodedParams( + mat1=_encode_tensor(mat1), + mat2=_encode_tensor(mat2), + op=str(op), + input=_encode_tensor(input) if input is not None else None, + mat1_exclude_padding_time=should_exclude_padding_time(match, "mat1"), + mat2_exclude_padding_time=should_exclude_padding_time(match, "mat2"), + tf32=False + if mat1.dtype != torch.float32 + else bool( + torch.backends.cuda.matmul.fp32_precision == "tf32" + or torch.backends.mkldnn.fp32_precision == "tf32" + ), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/exceptions.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f860c5a2721b2e198adc1f37d185ae104e464d9b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/exceptions.py @@ -0,0 +1,96 @@ +"""Exception classes for PyTorch Inductor runtime caching. + +This module defines a hierarchy of exceptions used throughout the caching system. +All custom exceptions inherit from CacheError, with UserError serving as a base +for user-facing errors that also inherit from TypeError for compatibility. +""" + +from threading import Lock + +from filelock import BaseFileLock + + +class CacheError(Exception): + """Base class for all caching-related errors. + + This is the root exception class for all custom exceptions raised by the caching + module, providing a common interface for error handling and logging. + """ + + +class SystemError(CacheError, RuntimeError): + """Base class for system-level caching errors. + + This class represents errors that occur during cache operations, such as + storage or retrieval failures. It inherits from RuntimeError to indicate + that the error is not caused by user input. + """ + + +class LockTimeoutError(SystemError): + """Error raised when a lock operation times out. + + This exception is raised when a lock operation exceeds the specified timeout + limit, indicating that the lock could not be acquired within the allotted time. + """ + + def __init__(self, lock: Lock, timeout: float) -> None: + """Initialize the lock timeout error with detailed lock information. + + Args: + lock: The lock object that timed out. + timeout: The timeout limit that was exceeded. + """ + super().__init__(f"Failed to acquire lock {lock} within {timeout} seconds.") + + +class FileLockTimeoutError(SystemError): + """Error raised when a file lock operation times out. + + This exception is raised when a file lock operation exceeds the specified timeout + limit, indicating that the lock could not be acquired within the allotted time. + """ + + def __init__(self, flock: BaseFileLock, timeout: float) -> None: + """Initialize the file lock timeout error with detailed lock information. + + Args: + flock: The file lock object that timed out. + timeout: The timeout limit that was exceeded. + """ + super().__init__( + f"Failed to acquire file lock {flock} within {timeout} seconds." + ) + + +class UserError(CacheError, TypeError): + """Base class for user-facing cache errors that also inherit from TypeError. + + This class combines CacheError with TypeError to provide compatibility + with existing exception handling patterns while maintaining the cache + error hierarchy. All user-facing cache errors should inherit from this class. + """ + + +class KeyEncodingError(UserError): + """Base class for errors that occur during cache key encoding operations. + + Raised when cache keys cannot be properly encoded for storage or transmission. + This includes serialization, hashing, or other encoding-related failures. + """ + + +class ValueEncodingError(UserError): + """Base class for errors that occur during cache value encoding operations. + + Raised when cache values cannot be properly encoded for storage or transmission. + This includes serialization, compression, or other encoding-related failures. + """ + + +class ValueDecodingError(UserError): + """Base class for errors that occur during cache value decoding operations. + + Raised when cached values cannot be properly decoded during retrieval. + This includes deserialization, decompression, or other decoding-related failures. + """ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/implementations.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/implementations.py new file mode 100644 index 0000000000000000000000000000000000000000..9c7e7b771f71cd87e9269675a18b3d87542da9ca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/implementations.py @@ -0,0 +1,422 @@ +"""Cache implementation classes + +This module provides concrete implementations of caching backends including +in-memory, on-disk, and remote caching strategies. Each implementation follows +the abstract _CacheImpl interface and provides thread-safe operations with +appropriate locking mechanisms. +""" + +from abc import ABC, abstractmethod +from collections.abc import Generator +from contextlib import contextmanager +from dataclasses import dataclass +from hashlib import sha256 +from io import BufferedReader, BufferedWriter +from os import PathLike +from pathlib import Path +from threading import Lock +from typing import Generic, TypeVar +from typing_extensions import override + +from filelock import BaseFileLock, FileLock + +from . import locks + + +# Type variable for cache value types +_V = TypeVar("_V") + + +@dataclass +class Hit(Generic[_V]): + """Result wrapper for hits on cache get operations. + + Allows distinguishing between a cache miss and a cached None value. + + Attributes: + value: The cached value. The type depends on the cache implementation: + - InMemoryCache: object (any Python object) + - OnDiskCache: bytes + - RemoteCache: bytes + """ + + value: _V + + +class Miss: + """Sentinel class representing a cache miss. + + Used to distinguish between a cached None value and a cache miss + when None is a valid cached value. + """ + + +# Singleton instance for cache miss sentinel +miss = Miss() + + +class _CacheImpl(ABC, Generic[_V]): + """Abstract base class for cache implementations. + + This class defines the interface that all cache implementations must follow. + It provides thread-safe operations through a locking mechanism and supports + both get and insert operations. + + Type Parameters: + _V: The type of values stored in the cache. Each implementation specifies + its own value type (e.g., object for in-memory, bytes for on-disk). + """ + + def __init__(self) -> None: + """Initialize the cache implementation with a threading lock.""" + self._lock: Lock = Lock() + + @property + def lock(self) -> locks._LockProtocol: + """Get a context manager for acquiring the cache lock. + + Locking of the cache is not done by the implementation itself, but by the + interface that uses it. The interface may want to hold the lock for longer + than a single cache operation, for example when dealing with multiple + cache implementations at once, so we leave that decision up to the interface. + + Args: + timeout: Optional timeout in seconds (float) for acquiring the lock. + + Returns: + A callable that returns a context manager for the lock. + """ + + def _lock_with_timeout( + timeout: float | None = None, + ) -> locks._LockContextManager: + return locks._acquire_lock_with_timeout(self._lock, timeout) + + return _lock_with_timeout + + @abstractmethod + def get(self, key: str) -> Hit[_V] | None: + """Retrieve a value from the cache. + + Args: + key: The key to look up in the cache (must be str). + + Returns: + A Hit object on cache hit where Hit.value is the cached value, + or None on cache miss. + """ + + @abstractmethod + def insert(self, key: str, value: _V) -> bool: + """Insert a key-value pair into the cache. + + Args: + key: The key to insert (must be str). + value: The value to associate with the key. + + Returns: + True if the insertion was successful, False if not inserted. + """ + + +class _InMemoryCacheImpl(_CacheImpl[_V], Generic[_V]): + """In-memory cache implementation using a dictionary. + + This implementation stores key-value pairs in a Python dictionary, + with keys being pickled for consistent hashing. It provides fast + access but is limited by available memory and process lifetime. + + Type Parameters: + _V: The type of values stored in the cache. + """ + + def __init__(self) -> None: + """Initialize the in-memory cache with an empty dictionary.""" + super().__init__() + self._memory: dict[str, _V] = {} + + @override + def get(self, key: str) -> Hit[_V] | None: + """Retrieve a value from the in-memory cache. + + Args: + key: The key to look up (must be str). + + Returns: + A Hit object on cache hit where Hit.value is the cached value, + or None on cache miss. + """ + if key in self._memory: + return Hit(value=self._memory[key]) + return None + + @override + def insert(self, key: str, value: _V) -> bool: + """Insert a key-value pair into the in-memory cache. + + Args: + key: The key to insert (must be str). + value: The value to associate with the key. + + Returns: + True if the insertion was successful (key was new), + False if not inserted (key already existed). + """ + if key not in self._memory: + self._memory[key] = value + return True + return False + + +class _OnDiskCacheImpl(_CacheImpl[bytes]): + """On-disk cache implementation using file system storage. + + This implementation stores cached data as files on disk, with version + headers to handle cache invalidation. It uses file locking to ensure + thread safety across processes and provides persistent storage that + survives process restarts. + + The value type is 'bytes' since data must be serialized to bytes for disk storage. + + Attributes: + _version: _Version number for cache format compatibility. + _version_header_length: Length of the version header in bytes. + """ + + _version: int = 0 + _version_header_length: int = 4 + + def __init__(self, sub_dir: PathLike[str] | None = None) -> None: + """Initialize the on-disk cache with a specified subdirectory. + + Args: + sub_dir: Subdirectory name within the cache directory. + Defaults to empty string if not specified. + """ + self._cache_dir: Path = self._base_dir / (sub_dir or "") + self._flock: BaseFileLock = FileLock(str(self._cache_dir / "dir.lock")) + + @property + def _base_dir(self) -> Path: + """Get the base directory for cache storage. + + Returns: + Path to the cache directory based on the default cache dir + and the specified subdirectory. + """ + from torch._inductor.runtime.runtime_utils import default_cache_dir + + return Path(default_cache_dir(), "cache") + + def _fpath_from_key(self, key: str) -> Path: + """Generate a file path from a cache key. + + Args: + key: The cache key to convert to a file path (must be str). + + Returns: + A Path object representing the file location for this key. + """ + return self._cache_dir / key + + @classmethod + def _version_header(cls) -> bytes: + """Generate the version header bytes. + + Returns: + A byte string representing the current cache version header. + """ + return sha256(str(cls._version).encode()).digest()[: cls._version_header_length] + + def _version_header_matches(self, fp: BufferedReader) -> bool: + """Check if the file's version header matches the current version. + + Args: + fp: File pointer positioned at the start of the file. + + Returns: + True if the version header matches, False otherwise. + """ + return fp.read(self._version_header_length) == self._version_header() + + def _write_version_header(self, fp: BufferedWriter) -> None: + """Write the version header to a file. + + Args: + fp: File pointer where the version header should be written. + """ + fp.write(self._version_header()) + + @override + @property + def lock(self) -> locks._LockProtocol: + """Get a context manager for acquiring the file lock. + + Uses file locking to ensure thread safety across processes. + + Args: + timeout: Optional timeout in seconds (float) for acquiring the file lock. + + Returns: + A callable that returns a context manager for the file lock. + """ + + def _lock_with_timeout( + timeout: float | None = None, + ) -> locks._LockContextManager: + return locks._acquire_flock_with_timeout(self._flock, timeout) + + return _lock_with_timeout + + @override + def get(self, key: str) -> Hit[bytes] | None: + """Retrieve a value from the on-disk cache. + + Args: + key: The key to look up in the cache (must be str). + + Returns: + A Hit object on cache hit where Hit.value is the cached value (bytes), + or None on cache miss or version mismatch. + """ + fpath: Path = self._fpath_from_key(key) + + if not fpath.is_file(): + return None + + pickled_value: bytes | None = None + with open(fpath, "rb") as fp: + if self._version_header_matches(fp): + pickled_value = fp.read() + + if not pickled_value: + # if pickled_value is still None, even though the file exists, then + # we know that the version header did not match. in this case implementation + # is up to preference, we choose to remove entries that do not match + # the version header so that the key can be re-cached later with the correct + # version header + fpath.unlink() + return None + + return Hit(value=pickled_value) + + @override + def insert(self, key: str, value: bytes) -> bool: + """Insert a key-value pair into the on-disk cache. + + Args: + key: The key to insert (must be str). + value: The value to associate with the key (must be bytes). + + Returns: + True if successfully inserted, False if the key already exists + with a valid version. + """ + fpath: Path = self._fpath_from_key(key) + fpath.parent.mkdir(parents=True, exist_ok=True) + + r_fp, w_fp, inserted = None, None, False + try: + w_fp = open(fpath, "xb") # noqa: SIM115 + except FileExistsError: + is_stale: bool = False + with open(fpath, "rb") as r_fp: + is_stale = not self._version_header_matches(r_fp) + + if is_stale: + # same story as above, in this case the version header doesn't + # match so we choose to remove the old entry so that the new + # k/v pair can be cached + fpath.unlink() + w_fp = open(fpath, "xb") # noqa: SIM115 + else: + w_fp = None + finally: + if w_fp: + try: + self._write_version_header(w_fp) + w_fp.write(value) + inserted = True + finally: + w_fp.close() + + return inserted + + +try: + from .fb.implementations import _RemoteCacheImpl +except ModuleNotFoundError: + + class _RemoteCacheImpl(_CacheImpl[bytes]): + """Fallback remote cache implementation for non-Facebook environments. + + This is a no-op implementation that always raises NotImplementedError. + The actual remote cache implementation is provided in the `.fb` module + for Facebook-specific environments. + + The value type is 'bytes' for consistency with the FB implementation. + + Attributes: + _version: _Version number for cache format compatibility. + has_strong_consistency: Whether the remote cache provides strong + consistency guarantees. + """ + + _version: int = 0 + has_strong_consistency: bool = False + + def __init__(self) -> None: + """Initialize the fallback remote cache implementation. + + Note: We don't need to initialize any form of lock since this + implementation provides a pseudo-lock context manager. + """ + + @override + @property + def lock(self) -> locks._LockProtocol: + """Get a pseudo lock that does nothing. + + Most remote cache implementations don't have an ability to implement + any form of locking, so we provide a no-op pseudo-lock for consistency + with the interface. + + Args: + timeout: Optional timeout in seconds (float). Ignored in this + + Returns: + A callable that returns a no-op context manager. + """ + + @contextmanager + def pseudo_lock( + timeout: float | None = None, + ) -> Generator[None, None, None]: + yield + + return pseudo_lock + + @override + def get(self, key: str) -> Hit[bytes] | None: + """Raise NotImplementedError for remote cache get operations. + + Args: + key: The key to look up (must be str, ignored). + + Raises: + NotImplementedError: Always raised as this is a fallback implementation. + """ + raise NotImplementedError + + @override + def insert(self, key: str, value: bytes) -> bool: + """Raise NotImplementedError for remote cache insert operations. + + Args: + key: The key to insert (must be str, ignored). + value: The value to insert (must be bytes, ignored). + + Raises: + NotImplementedError: Always raised as this is a fallback implementation. + """ + raise NotImplementedError diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/interfaces.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/interfaces.py new file mode 100644 index 0000000000000000000000000000000000000000..aa4d872fa274c1c9f2a2489e4ab18df49a7925b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/interfaces.py @@ -0,0 +1,1281 @@ +"""Public interfaces for PyTorch Inductor runtime caching. + +This module provides high-level caching interfaces for memoization and +result caching functionality. +""" + +import atexit +import functools +import json +import logging +import pickle +import shutil +import threading +import weakref +from collections.abc import Callable +from dataclasses import dataclass, field +from hashlib import sha256 +from os import PathLike +from pathlib import Path +from typing import cast, Generic, Protocol, TypedDict +from typing_extensions import ParamSpec, TypeVar + +from filelock import FileLock + +import torch +from torch._inductor.runtime.runtime_utils import cache_dir +from torch._inductor.utils import clear_on_fresh_cache + +from . import config, implementations, locks + + +logger = torch._logging.getArtifactLogger(__name__, "caching") + +# Type variable for function parameters +_P = ParamSpec("_P") +# Type variable for function return type +_R = TypeVar("_R") +# Type variable for encoded result type +_EncodedR = TypeVar("_EncodedR") + + +class CacheDumpEntry(TypedDict): + """A single cache entry in the dump format. + + Attributes: + params: The encoded function parameters. + result: The encoded function result. + """ + + params: object + result: object + + +class CacheDump(TypedDict): + """The structure of the memoizer cache dump file. + + Cache entries are organized by sub_key in the collections field. + Memoizers without a sub_key use None as their key in collections. + + Multiple Memoizer instances with different sub_keys can coexist in the same file. + + Attributes: + collections: Dictionary mapping sub_keys (or None for root entries) + to their cache entries. + cache_size: The total number of cache entries across all collections. + """ + + collections: dict[str | None, dict[str, CacheDumpEntry]] + cache_size: int + + +@dataclass +class CacheEntry: + """A cache entry containing encoded parameters and result. + + This dataclass stores the encoded form of function parameters and + the (possibly encoded) result for human-readable cache dumps. + + Attributes: + encoded_params: The encoded function parameters used for debugging/inspection. + encoded_result: The (possibly encoded) result of the function call. + """ + + encoded_params: object + encoded_result: object + + +@dataclass +class InterimResult(Generic[_R]): + """Wrapper for an available interim result from a DeferredRecording. + + When get_interim_result() returns an InterimResult, it means the + make_interim_result callable was provided and has been invoked. + The wrapped value is the result of that invocation. + + This allows distinguishing between: + - No interim result configured: get_interim_result() returns None + - Interim result available: get_interim_result() returns InterimResult(value) + where value may itself be None if the callable returns None. + + Attributes: + value: The value returned by calling make_interim_result(). + May legitimately be None if the callable returns None. + """ + + value: _R + + +@dataclass +class DeferredRecording(Generic[_R, _EncodedR]): + """Signals that recording should happen at a later time. + + When returned from a custom_result_encoder, the memoizer will: + 1. Skip immediate caching + 2. Register a completion callback on this object + + The encoder is responsible for calling `finalize(encoded_result)` + when the actual result is ready to be cached. This is useful when + the function returns a value whose final encoded form is not yet + available (e.g., an object containing a pending computation), + allowing the expensive work to remain hidden while still enabling caching. + + This class handles the race condition where the computation might complete + before the memoizer has registered its callback. If finalize() is called + first, the result is stored and the callbacks are invoked when registered. + + Multiple callbacks can be registered - they will all be invoked when + finalize() is called (or immediately if already completed). Callbacks are + guaranteed to be invoked in registration order. + + Optionally, a `make_interim_result` callable can be provided to handle + subsequent calls while the deferred recording is pending. When a memoized + function is called again with the same parameters while a deferred recording + is still pending, the memoizer can use this callable to construct an + appropriate return value instead of re-executing the function. The callable + does not necessarily return the same object - it provides a way to derive + a suitable response based on the pending deferred recording's context. + + This class is thread-safe: concurrent calls to finalize() and + register_callback() are properly synchronized. + + WARNING: Callbacks are executed while holding the internal lock to ensure + ordering guarantees. Callbacks MUST NOT call back into this DeferredRecording + instance (e.g., calling finalize() or register_callback() from within a + callback) as this will cause a deadlock. + + Example usage in an encoder: + def my_encoder(*args, **kwargs): + def encode(result: _R) -> DeferredRecording[_R, _EncodedR]: + deferred: DeferredRecording[_R, _EncodedR] = DeferredRecording( + # Construct an appropriate return for subsequent calls while pending + make_interim_result=lambda: result + ) + + def on_complete(): + encoded_result: _EncodedR = _encode_result(result) + deferred.finalize(encoded_result) + + result.add_completion_callback(on_complete) + return deferred + + return encode + + Attributes: + _callbacks: List of callbacks to invoke when finalize() is called. + Set to None after finalize() is called to indicate completion. + _encoded_result: The encoded result passed to finalize(). + _lock: Lock for thread-safe access to mutable state. + make_interim_result: Optional callable that constructs a return value for subsequent + calls while the deferred recording is pending. If set, the memoizer + calls this instead of re-executing the function. The callable may + return the same object or construct a new appropriate response. + """ + + _callbacks: list[Callable[[_EncodedR], None]] | None = field( + default_factory=list, repr=False + ) + _encoded_result: _EncodedR | None = field(default=None, repr=False) + _lock: threading.Lock = field(default_factory=threading.Lock, repr=False) + make_interim_result: Callable[[], _R] | None = field(default=None, repr=False) + + def finalize(self, encoded_result: _EncodedR) -> None: + """Finalize the deferred recording with the encoded result. + + This method should be called by the encoder (typically via a completion + callback) when the actual result is ready to be cached. + + All registered callbacks are invoked with the encoded result in + registration order. If no callbacks are registered yet, the result is + stored and callbacks will be invoked when registered. + + This method is thread-safe. + + WARNING: Callbacks are executed while holding the internal lock. + Do not call finalize() or register_callback() from within a callback, + as this will cause a deadlock. + + Args: + encoded_result: The encoded result to cache. + """ + with self._lock: + if self._callbacks is None: + raise RuntimeError( + "finalize() called multiple times on DeferredRecording" + ) + + # Store the result and get callbacks to invoke + self._encoded_result = encoded_result + callbacks_to_invoke = self._callbacks + self._callbacks = None + + # Execute callbacks inside the lock to ensure ordering: + # - All pre-finalize callbacks execute in registration order + # - Any callback registered during/after finalize will see + # _callbacks=None and execute immediately (also under lock) + for callback in callbacks_to_invoke: + callback(encoded_result) + + def register_callback(self, callback: Callable[[_EncodedR], None]) -> None: + """Register a completion callback. + + This method is called by memoizers to register callbacks that + will insert cache entries. Multiple callbacks can be registered. + + If finalize() has already been called (e.g., the computation was fast), + the callback is invoked immediately with the stored result. + + This method is thread-safe. Callbacks are guaranteed to be invoked + in registration order. + + WARNING: Callbacks are executed while holding the internal lock. + Do not call finalize() or register_callback() from within a callback, + as this will cause a deadlock. + + Args: + callback: The function to call with the encoded result. + """ + with self._lock: + if self._callbacks is None: + # Already finalized - invoke immediately while holding lock + # to maintain ordering with respect to other callbacks + # we need to cast here, we can't assert because the encoded + # result may genuinely be None + callback(cast(_EncodedR, self._encoded_result)) + else: + self._callbacks.append(callback) + + def get_interim_result(self) -> InterimResult[_R] | None: + """Try to get an interim result for use while deferred recording is pending. + + When a memoized function is called again with the same parameters while + a deferred recording is still pending, the memoizer uses this method to + check if an interim result can be returned instead of re-executing the + function. + + This method provides thread-safe access to the make_interim_result + callable. It atomically checks if the callable was provided and invokes + it if so. + + This method is thread-safe. + + Returns: + InterimResult wrapping the value if make_interim_result was provided, + or None if no interim result is available. + + Note: + The callable is invoked each time this method is called, so if + make_interim_result returns a new object each time, callers will + receive different objects. To return the same object, the callable + should capture and return a reference to a single object. + """ + with self._lock: + if self.make_interim_result is not None: + return InterimResult(self.make_interim_result()) + return None + + +class ResultEncoderFactory(Protocol[_P, _R, _EncodedR]): + """Protocol for custom result encoder factories. + + A result encoder factory is a callable with the following signature: + factory(fn) -> params_to_encoder(*args, **kwargs) -> encoder(result) -> encoded + + The three levels are: + 1. factory(fn): Takes the underlying unwrapped function, returns a params_to_encoder + 2. params_to_encoder(*args, **kwargs): Takes the memoized function's arguments, + returns an encoder function + 3. encoder(result): Converts the result R -> _EncodedR (or DeferredRecording) + + The `fn` parameter allows the encoder to call the underlying function without + triggering memoization, which is useful when the encoder needs to re-execute + the function (e.g., to get a fresh result for DeferredRecording). + + Example: + def my_encoder_factory(fn: Callable) -> Callable: + def params_to_encoder(*args, **kwargs) -> Callable: + def encode(result: R) -> EncodedR: + return {"encoded": result} + return encode + return params_to_encoder + + @memoizer.record(custom_result_encoder=my_encoder_factory) + def compute(x: int) -> int: + return x * 2 + """ + + def __call__( + self, + fn: Callable[_P, _R], + ) -> Callable[_P, Callable[[_R], _EncodedR | DeferredRecording[_R, _EncodedR]]]: ... + + +# pyrefly: ignore [variance-mismatch] +class ResultDecoderFactory(Protocol[_P, _R, _EncodedR]): + """Protocol for custom result decoder factories. + + A result decoder factory is a callable with the following signature: + factory(fn) -> params_to_decoder(*args, **kwargs) -> decoder(encoded) -> result + + The three levels are: + 1. factory(fn): Takes the underlying unwrapped function, returns a params_to_decoder + 2. params_to_decoder(*args, **kwargs): Takes the memoized function's arguments, + returns a decoder function + 3. decoder(encoded): Converts the encoded result _EncodedR -> R + + The `fn` parameter allows the decoder to call the underlying function without + triggering memoization, which is useful for fallback paths when the cached + result cannot be fully decoded. + + Example: + def my_decoder_factory(fn: Callable) -> Callable: + def params_to_decoder(*args, **kwargs) -> Callable: + def decode(encoded_result: EncodedR) -> R: + return encoded_result["value"] + return decode + return params_to_decoder + + @memoizer.replay(custom_result_decoder=my_decoder_factory) + def compute(x: int) -> int: + return x * 2 + """ + + def __call__( + self, + fn: Callable[_P, _R], + ) -> Callable[_P, Callable[[_EncodedR], _R]]: ... + + +class _BaseMemoizer: + """Base class for memoization interfaces. + + This class provides the common memoize method that orchestrates + record and replay functionality. + """ + + @staticmethod + def _make_key( + custom_params_encoder: Callable[..., object] | None, + *args: object, + **kwargs: object, + ) -> str: + """Generate a cache key from function parameters. + + Args: + custom_params_encoder: Optional encoder to apply to function parameters. + If None, params are pickled directly. + *args: Positional arguments to encode. + **kwargs: Keyword arguments to encode. + + Returns: + A 32-character hex string suitable for use as a cache key. + """ + if custom_params_encoder is None: + # Pickle the parameters directly + pickled_params: bytes = pickle.dumps((args, kwargs)) + else: + # Encode the parameters using the custom encoder + encoded_params = custom_params_encoder(*args, **kwargs) + # Pickle the encoded output + pickled_params = pickle.dumps(encoded_params) + + # Hash the pickled bytes with SHA256 + hash_obj = sha256(pickled_params) + + # Get hex digest and truncate to 32 characters + return hash_obj.hexdigest()[:32] + + def record( + self, + custom_params_encoder: Callable[_P, object] | None = None, + custom_result_encoder: ResultEncoderFactory[_P, _R, _EncodedR] | None = None, + ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + """Record a function call result. Must be implemented by subclasses. + + This can be used standalone to cache results without necessarily + replaying them, for example for logging or analytics purposes. + + See memoize() for a description of the arguments. + """ + raise NotImplementedError + + def replay( + self, + custom_params_encoder: Callable[_P, object] | None = None, + custom_result_decoder: ResultDecoderFactory[_P, _R, _EncodedR] | None = None, + ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + """Replay a cached function result. Must be implemented by subclasses. + + This can be used standalone to use cached values that are otherwise + too hard to automatically record. + + See memoize() for a description of the arguments. + """ + raise NotImplementedError + + def memoize( + self, + custom_params_encoder: Callable[_P, object] | None = None, + custom_result_encoder: ResultEncoderFactory[_P, _R, _EncodedR] | None = None, + custom_result_decoder: ResultDecoderFactory[_P, _R, _EncodedR] | None = None, + ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + """Memoize a function with record and replay functionality. + + This is a decorator that attempts to replay cached results first. + If a cache miss occurs, it records the result by executing the wrapped function. + + Args: + custom_params_encoder: Optional encoder for function parameters. + If None, parameters are pickled directly. + custom_result_encoder: Optional encoder factory for function results. + Takes function parameters and returns an encoder + function that converts R -> _EncodedR. + custom_result_decoder: Optional decoder factory for cached results. + Takes function parameters and returns a decoder + function that converts _EncodedR -> R. + + Returns: + A decorator function that can be applied to functions. + + Example: + @memoizer.memoize( + custom_params_encoder=my_param_encoder, + custom_result_encoder=my_result_encoder_factory, + custom_result_decoder=my_result_decoder_factory, + ) + def expensive_function(x, y): + return x + y + """ + + def wrapper(fn: Callable[_P, _R]) -> Callable[_P, _R]: + """Wrap the function to enable memoization with replay and record. + + Args: + fn: The function to wrap. + + Returns: + A wrapped version of the function. + """ + # If caching is disabled, return the original function unchanged + if not config.IS_CACHING_MODULE_ENABLED(): + return fn + + # Create decorated versions using record and replay + replay_fn = self.replay( + custom_params_encoder, + custom_result_decoder, + )(fn) + record_fn = self.record( + custom_params_encoder, + custom_result_encoder, + )(fn) + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + """Attempt to replay from cache, or record on cache miss. + + Args: + *args: Positional arguments to pass to the function. + **kwargs: Keyword arguments to pass to the function. + + Returns: + The result from cache (if hit) or from executing the function (if miss). + """ + # Try to replay first + try: + return replay_fn(*args, **kwargs) + except KeyError: + # Cache miss - record the result + return record_fn(*args, **kwargs) + + return inner + + return wrapper + + +class Memoizer(_BaseMemoizer): + """In-memory memoization interface for caching function results. + + This class provides methods for recording, retrieving, and managing + cached function results in memory with custom encoding/decoding logic. + + Cache entries are stored as CacheEntry objects containing both the encoded + parameters and the encoded result. This makes debugging easier since entries + can be inspected with full context about what inputs produced each result. + + On memoizer destruction, the cache is automatically dumped to a shared JSON file + in the cache directory for debugging and inspection purposes. Multiple Memoizer + instances contribute to the same file additively. + + Note: Use this over functools.cache when you need to support parameters + that functools.cache cannot handle, or when you need custom encoding/decoding + of results. + """ + + def __init__(self, sub_key: str | None = None) -> None: + """Initialize the Memoizer instance with an in-memory cache. + + Args: + sub_key: Optional key for organizing cache entries in the JSON dump. + If provided, cache entries are stored under cache_entries[sub_key]. + If None, cache entries are merged directly into root cache_entries. + """ + self._cache: implementations._InMemoryCacheImpl[CacheEntry] = ( + implementations._InMemoryCacheImpl() + ) + # Optional sub_key for nested cache structure + self._sub_key: str | None = sub_key + # Track pending deferred recordings by cache key. + # Uses WeakValueDictionary to prevent memory leaks: if the DeferredRecording + # is no longer referenced elsewhere (e.g., the async computation was cancelled + # or failed and garbage collected), the entry is automatically removed. + self._pending_deferred: weakref.WeakValueDictionary[str, DeferredRecording] = ( + weakref.WeakValueDictionary() + ) + # Register atexit handler to dump cache on program exit + if config.IS_DUMP_MEMOIZER_CACHE_ENABLED(): + atexit.register(self._dump_to_disk) + # Pre-populate cache from dump file if configured (with sub_key now set) + self._maybe_prepopulate_from_dump() + # Register with clear_on_fresh_cache for fresh_cache() integration + clear_on_fresh_cache(self) + + def cache_clear(self) -> None: + """Clear the in-memory cache. + + This method resets the in-memory cache to empty. It is called by + the fresh_cache() context manager via clear_on_fresh_cache registration. + """ + self._cache._memory.clear() + + def _finalize_deferred_recording( + self, + cache_key: str, + encoded_params: object, + encoded_result: _EncodedR, + ) -> None: + """Finalize a deferred recording by inserting the cache entry. + + This method is called when a DeferredRecording's finalize() method is invoked. + It creates the cache entry and inserts it into the in-memory cache. + + Args: + cache_key: The cache key for the entry. + encoded_params: The encoded function parameters. + encoded_result: The final encoded result to cache. + """ + # Remove from pending tracking + self._pending_deferred.pop(cache_key, None) + # Insert into cache + cache_entry = CacheEntry( + encoded_params=encoded_params, + encoded_result=encoded_result, + ) + self._cache.insert(cache_key, cache_entry) + + @functools.cached_property + def _shared_cache_filepath(self) -> Path: + """Get the shared cache filepath for memoizer cache dumps. + + Returns: + The path to the shared memoizer cache JSON file. + """ + return Path(cache_dir()) / "memoizer_cache.json" + + @functools.cached_property + def _shared_cache_lockfile(self) -> Path: + """Get the lock file path for the shared memoizer cache. + + Returns: + The path to the lock file for the shared cache. + """ + return Path(cache_dir()) / "memoizer_cache.lock" + + def _read_dump_from_disk(self, filepath: Path | None = None) -> CacheDump | None: + """Read a cache dump from disk. + + Attempts to read and parse a cache JSON file. + + Args: + filepath: Path to the dump file to read. If None, uses the + shared cache filepath (self._shared_cache_filepath). + + Returns: + The cache dump if the file exists and is valid JSON, None otherwise. + """ + target_path = filepath if filepath is not None else self._shared_cache_filepath + try: + with open(target_path) as f: + data = json.load(f) + return data + except FileNotFoundError: + return None + except json.JSONDecodeError: + return None + + def _write_dump_to_disk(self, dump: CacheDump) -> None: + """Write the cache dump to disk. + + Writes the provided dump to the shared cache JSON file and logs the result. + + Args: + dump: The cache dump to write. + """ + try: + with open(self._shared_cache_filepath, "w") as f: + json.dump(dump, f, indent=2) + + # Log the filepath + if self._sub_key: + logger.log( + logging.INFO, + "Memoizer cache (sub_key=%s) dumped to: %s", + self._sub_key, + self._shared_cache_filepath, + ) + else: + logger.log( + logging.INFO, + "Memoizer cache dumped to: %s", + self._shared_cache_filepath, + ) + except Exception as e: + # If dumping fails, just log it and don't crash the program + logger.log( + logging.WARNING, + "Warning: Failed to dump memoizer cache: %s", + e, + ) + + def _prepare_dump(self, existing_dump: CacheDump | None) -> CacheDump: + """Prepare a cache dump from the current Memoizer state. + + Takes the existing dump (if any) and merges it with the current + in-memory cache entries. + + Args: + existing_dump: The existing dump to merge with, or None if starting fresh. + + Returns: + The prepared cache dump ready to be written to disk. + """ + # Start with existing data or empty structure + if existing_dump is not None: + dump = existing_dump + else: + dump: CacheDump = {"collections": {}, "cache_size": 0} + + # Ensure collections field exists + if "collections" not in dump: + dump["collections"] = {} + + # JSON serializes None keys as "null" string, so we need to handle both cases + # When reading from JSON, the key will be "null" (string), not None + lookup_key = "null" if self._sub_key is None else self._sub_key + + # Get existing entries for this sub_key to merge with + existing_entries = dump["collections"].get(lookup_key, {}) + + # Format cache entries as {"params": ..., "result": ...} + formatted_cache: dict[str, CacheDumpEntry] = dict(existing_entries) + for key, value in self._cache._memory.items(): + entry = value + formatted_cache[key] = CacheDumpEntry( + params=entry.encoded_params, + result=entry.encoded_result, + ) + + # Store under sub_key in collections (use lookup_key to maintain JSON compatibility) + dump["collections"][lookup_key] = formatted_cache + + # Calculate total cache size + total_size = sum(len(collection) for collection in dump["collections"].values()) + dump["cache_size"] = total_size + + return dump + + def _dump_to_disk(self) -> None: + """Dump the in-memory cache to a shared JSON file. + + This method is automatically called on program exit via atexit. + It reads any existing cache data, merges it with this instance's cache, + and writes the combined result back. Multiple Memoizer instances + contribute to the same file additively. + + If self._sub_key is set and non-empty, cache entries are stored under + cache_entries[sub_key]. Otherwise, they're merged directly into cache_entries. + + Cache entries are formatted as {"params": , "result": } + for better human readability. + + The filepath where the cache was dumped is logged. + """ + # Skip if cache is empty + if not self._cache._memory: + return + + # Ensure parent directory exists + self._shared_cache_filepath.parent.mkdir(parents=True, exist_ok=True) + + # Acquire file lock to ensure thread/process safety + flock = FileLock(str(self._shared_cache_lockfile)) + with locks._acquire_flock_with_timeout(flock): + existing_dump = self._read_dump_from_disk() + dump = self._prepare_dump(existing_dump) + self._write_dump_to_disk(dump) + + def _maybe_prepopulate_from_dump(self) -> None: + """Pre-populate cache entries from a dump file if configured. + + Checks the CACHE_DUMP_FILE_PATH config option for a path to a JSON dump file + produced by IS_DUMP_MEMOIZER_CACHE_ENABLED. If a valid path is provided and + the file exists, loads cache entries from it into the in-memory cache. + + For Memoizer instances without a sub_key, loads entries from the root cache_entries. + For Memoizer instances with a sub_key, loads entries from cache_entries[sub_key]. + + This method is called during __init__ to pre-populate the cache. + """ + dump_file_path = config.CACHE_DUMP_FILE_PATH() + + # Skip if no dump file configured + if not dump_file_path: + return + + # Read the dump file using the helper method + dump = self._read_dump_from_disk(Path(dump_file_path)) + if dump is None: + return + + # Extract entries to load from the dump + entries_to_load = self._extract_entries_from_dump(dump) + if not entries_to_load: + return + + # Populate the cache + self._populate_cache_from_entries(entries_to_load) + + # Log the result + if self._sub_key: + logger.log( + logging.INFO, + "Loaded %d cache entries from %s (sub_key=%s)", + len(entries_to_load), + dump_file_path, + self._sub_key, + ) + else: + logger.log( + logging.INFO, + "Loaded %d cache entries from %s", + len(entries_to_load), + dump_file_path, + ) + + def _extract_entries_from_dump(self, dump: CacheDump) -> dict[str, CacheDumpEntry]: + """Extract cache entries from a dump based on sub_key. + + Args: + dump: The cache dump to extract entries from. + + Returns: + Dictionary of cache entries to load. + """ + collections = dump.get("collections", {}) + # JSON serializes None keys as "null" string, so we need to handle both cases + # When reading from JSON, the key will be "null" (string), not None + lookup_key = "null" if self._sub_key is None else self._sub_key + return collections.get(lookup_key, {}) + + def _populate_cache_from_entries(self, entries: dict[str, CacheDumpEntry]) -> None: + """Populate the in-memory cache from dump entries. + + Args: + entries: Dictionary of cache entries to load. + """ + for key, entry in entries.items(): + cache_entry = CacheEntry( + encoded_params=entry["params"], + encoded_result=entry["result"], + ) + self._cache.insert(key, cache_entry) + + def record( + self, + custom_params_encoder: Callable[_P, object] | None = None, + custom_result_encoder: ResultEncoderFactory[_P, _R, _EncodedR] | None = None, + ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + """Record a function call result with custom encoding. + + This is a decorator that wraps a function to enable memoization + with custom encoding/decoding logic. + + Args: + custom_params_encoder: Optional encoder for function parameters. + If None, parameters are pickled directly. + custom_result_encoder: Optional encoder factory for function results. + First receives the underlying function, then takes + function parameters and returns an encoder function + that converts R -> _EncodedR. + + Returns: + A decorator function that can be applied to functions. + + Example: + @memoizer.record( + custom_params_encoder=my_param_encoder, + custom_result_encoder=my_result_encoder_factory, + ) + def expensive_function(x, y): + return x + y + """ + + def wrapper(fn: Callable[_P, _R]) -> Callable[_P, _R]: + """Wrap the function to enable memoization. + + Args: + fn: The function to wrap. + + Returns: + A wrapped version of the function. + """ + # If caching is disabled, return the original function unchanged + if not config.IS_CACHING_MODULE_ENABLED(): + return fn + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + """Call the original function and cache the result. + + Args: + *args: Positional arguments to pass to the function. + **kwargs: Keyword arguments to pass to the function. + + Returns: + The result of calling the original function. + """ + # Call the function to compute the result + result = fn(*args, **kwargs) + + # Generate cache key from parameters + cache_key = self._make_key(custom_params_encoder, *args, **kwargs) + + # Encode params for human-readable dump + if custom_params_encoder is not None: + encoded_params = custom_params_encoder(*args, **kwargs) + else: + encoded_params = { + "args": args, + "kwargs": kwargs, + } + + # Encode the result if encoder is provided + if custom_result_encoder is not None: + # Get the encoder function by calling the factory: + # 1. First call with fn to get params_to_encoder factory + # 2. Second call with params to get the encoder function + params_to_encoder = custom_result_encoder(fn) + encoder_fn = params_to_encoder(*args, **kwargs) + encoded_result = encoder_fn(result) + else: + encoded_result = result + + # Check for deferred recording + if isinstance(encoded_result, DeferredRecording): + # Track the pending deferred recording + self._pending_deferred[cache_key] = encoded_result + # Register the callback - handles race condition if encoded_result already completed + encoded_result.register_callback( + functools.partial( + self._finalize_deferred_recording, + cache_key, + encoded_params, + ) + ) + return result # Return without caching + + # Store CacheEntry in cache + cache_entry = CacheEntry( + encoded_params=encoded_params, + encoded_result=encoded_result, + ) + self._cache.insert(cache_key, cache_entry) + + # Return the original result (not the encoded version) + return result + + return inner + + return wrapper + + def replay( + self, + custom_params_encoder: Callable[_P, object] | None = None, + custom_result_decoder: ResultDecoderFactory[_P, _R, _EncodedR] | None = None, + ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + """Replay a cached function result without executing the function. + + This is a decorator that retrieves cached results instead of executing + the function. Raises an exception if no cached result exists. + + Args: + custom_params_encoder: Optional encoder for function parameters. + If None, parameters are pickled directly. + custom_result_decoder: Optional decoder factory for cached results. + First receives the underlying function, then takes + function parameters and returns a decoder function + that converts _EncodedR -> R. + + Returns: + A decorator function that can be applied to functions. + + Example: + @memoizer.replay( + custom_params_encoder=my_param_encoder, + custom_result_decoder=my_result_decoder_factory, + ) + def expensive_function(x, y): + return x + y + """ + + def wrapper(fn: Callable[_P, _R]) -> Callable[_P, _R]: + """Wrap the function to retrieve from cache. + + Args: + fn: The function to wrap (not actually called). + + Returns: + A wrapped version of the function. + """ + # If caching is disabled, always raise KeyError (cache miss) + if not config.IS_CACHING_MODULE_ENABLED(): + + @functools.wraps(fn) + def always_miss(*args: _P.args, **kwargs: _P.kwargs) -> _R: + raise KeyError("Caching is disabled") + + return always_miss + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + """Retrieve the cached result without calling the function. + + Args: + *args: Positional arguments to generate the cache key. + **kwargs: Keyword arguments to generate the cache key. + + Returns: + The cached result (decoded if decoder is provided). + + Raises: + KeyError: If no cached result exists for the given parameters. + """ + # Generate cache key from parameters + cache_key = self._make_key(custom_params_encoder, *args, **kwargs) + + # Check if result is cached + cached_hit = self._cache.get(cache_key) + if cached_hit is not None: + # Extract the cached value + cache_entry = cached_hit.value + + # Decode and return the cached result + if custom_result_decoder is not None: + # Get the decoder function by calling the factory: + # 1. First call with fn to get params_to_decoder factory + # 2. Second call with params to get the decoder function + params_to_decoder = custom_result_decoder(fn) + decoder_fn = params_to_decoder(*args, **kwargs) + return decoder_fn(cast(_EncodedR, cache_entry.encoded_result)) + return cast(_R, cache_entry.encoded_result) + + # Check for pending deferred recording with interim result + pending = self._pending_deferred.get(cache_key) + if pending is not None: + interim = pending.get_interim_result() + if interim is not None: + return interim.value + + raise KeyError(f"No cached result found for key: {cache_key}") + + return inner + + return wrapper + + +class PersistentMemoizer(_BaseMemoizer): + """Persistent memoization interface for caching function results to disk. + + This class provides methods for recording, retrieving, and managing + cached function results using a two-level cache strategy: + 1. In-memory cache (fast, checked first) - via Memoizer instance + 2. On-disk cache (persistent, checked on memory miss) + + Results are persisted across process restarts. + + On program exit, the in-memory cache entries are automatically dumped to + the shared JSON file. If sub_dir is non-empty, entries are stored under + a nested structure based on the sub_dir. If sub_dir is empty, entries are + merged directly into the root cache_entries. + + Note: Use this over functools.cache when you need to support parameters + that functools.cache cannot handle, custom result encoding and/or decoding, + or when you need disk caching to persist results across program boundaries. + """ + + def __init__(self, sub_dir: PathLike[str] | None = None) -> None: + """Initialize the PersistentMemoizer with two-level caching. + + Args: + sub_dir: Optional subdirectory within the cache directory for + organizing cached results. Defaults to empty string if not specified. + If non-empty, cache entries will be stored under cache_entries[sub_dir]. + If empty, cache entries are merged into root cache_entries. + """ + # Use a Memoizer instance for in-memory caching + self._memoizer: Memoizer = Memoizer(sub_key=str(sub_dir) if sub_dir else None) + # Store on-disk cache as a separate attribute + self._disk_cache: implementations._OnDiskCacheImpl = ( + implementations._OnDiskCacheImpl(sub_dir=sub_dir) + ) + # Register with clear_on_fresh_cache for fresh_cache() integration + clear_on_fresh_cache(self) + + def cache_clear(self) -> None: + """Clear the on-disk cache. + + This method removes the on-disk cache directory. The in-memory cache + is cleared automatically by the underlying Memoizer instance, which + registers itself with clear_on_fresh_cache. + + This is called by the fresh_cache() context manager via clear_on_fresh_cache + registration. + """ + # Clear on-disk cache by removing the cache directory + # Note: in-memory cache is cleared by the Memoizer's own cache_clear + if self._disk_cache._cache_dir.exists(): + shutil.rmtree(self._disk_cache._cache_dir, ignore_errors=True) + + def record( + self, + custom_params_encoder: Callable[_P, object] | None = None, + custom_result_encoder: ResultEncoderFactory[_P, _R, _EncodedR] | None = None, + ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + """Record a function call result with custom encoding to both caches. + + This is a decorator that wraps a function to enable memoization + with custom encoding/decoding logic. Results are stored in both + the in-memory cache and the on-disk cache. + + This method delegates to the underlying Memoizer for memory caching, + then adds disk persistence. For deferred recordings, it registers + an additional callback to persist to disk when the recording completes. + + Args: + custom_params_encoder: Optional encoder for function parameters. + If None, parameters are pickled directly. + custom_result_encoder: Optional encoder factory for function results. + First receives the underlying function, then takes + function parameters and returns an encoder function + that converts R -> _EncodedR. + + Returns: + A decorator function that can be applied to functions. + + Example: + @persistent_memoizer.record( + custom_params_encoder=my_param_encoder, + custom_result_encoder=my_result_encoder_factory, + ) + def expensive_function(x, y): + return x + y + """ + + def wrapper(fn: Callable[_P, _R]) -> Callable[_P, _R]: + """Wrap the function to enable memoization. + + Args: + fn: The function to wrap. + + Returns: + A wrapped version of the function. + """ + # If caching is disabled, return the original function unchanged + if not config.IS_CACHING_MODULE_ENABLED(): + return fn + + # Get the memory-cached version from the memoizer + memory_record_fn = self._memoizer.record( + custom_params_encoder, custom_result_encoder + )(fn) + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + """Call the original function and cache the result in both caches. + + Args: + *args: Positional arguments to pass to the function. + **kwargs: Keyword arguments to pass to the function. + + Returns: + The result of calling the original function. + """ + # Call the memory-cached version (which calls fn and caches in memory) + result = memory_record_fn(*args, **kwargs) + + # Also store in disk cache + cache_key = self._make_key(custom_params_encoder, *args, **kwargs) + + # Check if this was a deferred recording + pending = self._memoizer._pending_deferred.get(cache_key) + if pending is not None: + # Deferred recording - register our own callback for disk persistence + # By the time our callback runs, Memoizer's callback will have + # already inserted the cache entry, so we just read and persist it + pending.register_callback( + functools.partial(self._persist_to_disk, cache_key) + ) + return result + + # Persist the cache entry to disk + self._persist_to_disk(cache_key) + + return result + + return inner + + return wrapper + + def _persist_to_disk( + self, + cache_key: str, + _callback_result: object = None, + ) -> None: + """Persist a cache entry to disk. + + This method handles disk persistence for both immediate and deferred recordings: + - For immediate recordings: called directly after memory caching + - For deferred recordings: registered as a callback that runs after the + Memoizer's callback has inserted the entry into memory + + Args: + cache_key: The cache key for the entry. + _callback_result: Unused. When called as a callback from DeferredRecording, + this receives the encoded result, but we ignore it and + read the full CacheEntry from the Memoizer's cache instead. + """ + # Always read from memory cache - Memoizer's callback has already inserted it + cached_hit = self._memoizer._cache.get(cache_key) + if not cached_hit: + raise AssertionError("Cache entry must exist in memory cache") + cache_entry = cached_hit.value + + # Store the full CacheEntry in disk cache for easier debugging + pickled_entry: bytes = pickle.dumps(cache_entry) + self._disk_cache.insert(cache_key, pickled_entry) + + def replay( + self, + custom_params_encoder: Callable[_P, object] | None = None, + custom_result_decoder: ResultDecoderFactory[_P, _R, _EncodedR] | None = None, + ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + """Replay a cached function result without executing the function. + + This is a decorator that retrieves cached results using a two-level + cache strategy. It checks the in-memory cache first (fast), then + falls back to the on-disk cache. If found on disk, the result is + cached in memory for future access. + + Args: + custom_params_encoder: Optional encoder for function parameters. + If None, parameters are pickled directly. + custom_result_decoder: Optional decoder factory for cached results. + First receives the underlying function, then takes + function parameters and returns a decoder function + that converts _EncodedR -> R. + + Returns: + A decorator function that can be applied to functions. + + Example: + @persistent_memoizer.replay( + custom_params_encoder=my_param_encoder, + custom_result_decoder=my_result_decoder_factory, + ) + def expensive_function(x, y): + return x + y + """ + + def wrapper(fn: Callable[_P, _R]) -> Callable[_P, _R]: + """Wrap the function to retrieve from cache. + + Args: + fn: The function to wrap (not actually called). + + Returns: + A wrapped version of the function. + """ + # If caching is disabled, always raise KeyError (cache miss) + if not config.IS_CACHING_MODULE_ENABLED(): + + @functools.wraps(fn) + def always_miss(*args: _P.args, **kwargs: _P.kwargs) -> _R: + raise KeyError("Caching is disabled") + + return always_miss + + # Get the memory replay function + memory_replay_fn = self._memoizer.replay( + custom_params_encoder, custom_result_decoder + )(fn) + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + """Retrieve the cached result without calling the function. + + Checks memory cache first, then disk cache. Populates memory + cache from disk on a disk hit. + + Args: + *args: Positional arguments to generate the cache key. + **kwargs: Keyword arguments to generate the cache key. + + Returns: + The cached result (decoded if decoder is provided). + + Raises: + KeyError: If no cached result exists for the given parameters. + """ + # Try memory cache first via memoizer + try: + return memory_replay_fn(*args, **kwargs) + except KeyError: + pass # Memory miss, check disk + + # Memory miss - check disk cache + cache_key = self._make_key(custom_params_encoder, *args, **kwargs) + disk_hit = self._disk_cache.get(cache_key) + if disk_hit is not None: + # Disk cache hit - unpickle the CacheEntry + pickled_value = disk_hit.value + cache_entry = cast(CacheEntry, pickle.loads(pickled_value)) + + # Populate memory cache for future access + self._memoizer._cache.insert(cache_key, cache_entry) + + # Decode and return + if custom_result_decoder is not None: + # Get the decoder function by calling the factory: + # 1. First call with fn to get params_to_decoder factory + # 2. Second call with params to get the decoder function + params_to_decoder = custom_result_decoder(fn) + decoder_fn = params_to_decoder(*args, **kwargs) + return decoder_fn(cast(_EncodedR, cache_entry.encoded_result)) + return cast(_R, cache_entry.encoded_result) + + # Complete miss + raise KeyError(f"No cached result found for key: {cache_key}") + + return inner + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/locks.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/locks.py new file mode 100644 index 0000000000000000000000000000000000000000..6b8108de0328bf178336c6107564de888b41c3c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/locks.py @@ -0,0 +1,207 @@ +"""Lock acquisition utilities + +This module provides safe and unsafe lock acquisition functions for both threading.Lock +and FileLock objects, with configurable timeout behaviors. It supports three timeout modes: +blocking (infinite wait), non-blocking (immediate), and blocking with timeout (finite wait). + +The module offers both context manager and manual acquisition patterns: +- Safe acquisition: Uses context managers that automatically handle lock release +- Unsafe acquisition: Manual acquisition that requires explicit release by the caller +""" + +from __future__ import annotations + +from contextlib import _GeneratorContextManager, contextmanager, ExitStack +from typing import TYPE_CHECKING, TypeAlias +from typing_extensions import Protocol + +from filelock import BaseFileLock, Timeout + +from . import exceptions + + +if TYPE_CHECKING: + from collections.abc import Generator + from threading import Lock + + from .implementations import _CacheImpl + + +_LockContextManager: TypeAlias = _GeneratorContextManager[None, None, None] + + +class _LockProtocol(Protocol): # noqa: PYI046 + def __call__(self, timeout: float | None = None) -> _LockContextManager: ... + + +# Infinite timeout - blocks indefinitely until lock is acquired. +_BLOCKING: float = -1 +# No timeout - returns immediately if lock cannot be acquired. +_NON_BLOCKING: float = 0 +# Finite timeout - blocks for a specified duration before raising a timeout error. +_BLOCKING_WITH_TIMEOUT: float = 60.0 +# Default timeout for lock acquisition. +_DEFAULT_TIMEOUT: float = _BLOCKING_WITH_TIMEOUT + + +@contextmanager +def _acquire_lock_with_timeout( + lock: Lock, + timeout: float | None = None, +) -> Generator[None, None, None]: + """Context manager that safely acquires a threading.Lock with timeout and automatically releases it. + + This function provides a safe way to acquire a lock with timeout support, ensuring + the lock is always released even if an exception occurs during execution. + + Args: + lock: The threading.Lock object to acquire + timeout: Timeout in seconds. If None, uses _DEFAULT_TIMEOUT. + - Use _BLOCKING (-1.0) for infinite wait + - Use _NON_BLOCKING (0.0) for immediate return + - Use positive value for finite timeout + + Yields: + None: Yields control to the caller while holding the lock + + Raises: + LockTimeoutError: If the lock cannot be acquired within the timeout period + + Example: + with _acquire_lock_with_timeout(my_lock, timeout=30.0): + # Critical section - lock is held + perform_critical_operation() + # Lock is automatically released here + """ + _unsafe_acquire_lock_with_timeout(lock, timeout=timeout) + + try: + yield + finally: + lock.release() + + +def _unsafe_acquire_lock_with_timeout(lock: Lock, timeout: float | None = None) -> None: + """Acquire a threading.Lock with timeout without automatic release (unsafe). + + This function acquires a lock with timeout support but does NOT automatically + release it. The caller is responsible for releasing the lock explicitly. + Use this only when you need manual control over lock lifetime. + + Args: + lock: The threading.Lock object to acquire + timeout: Timeout in seconds. If None, uses _DEFAULT_TIMEOUT. + - Use _BLOCKING (-1.0) for infinite wait + - Use _NON_BLOCKING (0.0) for immediate return + - Use positive value for finite timeout + + Raises: + LockTimeoutError: If the lock cannot be acquired within the timeout period + + Warning: + This is an "unsafe" function because it does not automatically release + the lock. Always call lock.release() when done, preferably in a try/finally + block or use the safe _acquire_lock_with_timeout context manager instead. + + Example: + lock = Lock() + try: + _unsafe_acquire_lock_with_timeout(lock, timeout=30.0) + # Critical section - lock is held + perform_critical_operation() + finally: + lock.release() # Must manually release! + """ + _timeout: float = timeout if timeout is not None else _DEFAULT_TIMEOUT + if not lock.acquire(timeout=_timeout): + raise exceptions.LockTimeoutError(lock, _timeout) + + +@contextmanager +def _acquire_flock_with_timeout( + flock: BaseFileLock, + timeout: float | None = None, +) -> Generator[None, None, None]: + """Context manager that safely acquires a FileLock with timeout and automatically releases it. + + This function provides a safe way to acquire a file lock with timeout support, ensuring + the lock is always released even if an exception occurs during execution. + + Args: + flock: The FileLock object to acquire + timeout: Timeout in seconds. If None, uses _DEFAULT_TIMEOUT. + - Use _BLOCKING (-1.0) for infinite wait + - Use _NON_BLOCKING (0.0) for immediate return + - Use positive value for finite timeout + + Yields: + None: Yields control to the caller while holding the file lock + + Raises: + FileLockTimeoutError: If the file lock cannot be acquired within the timeout period + + Example: + flock = FileLock("/tmp/my_process.lock") + with _acquire_flock_with_timeout(flock, timeout=30.0): + # Critical section - file lock is held + perform_exclusive_file_operation() + # File lock is automatically released here + """ + _unsafe_acquire_flock_with_timeout(flock, timeout=timeout) + + try: + yield + finally: + flock.release() + + +def _unsafe_acquire_flock_with_timeout( + flock: BaseFileLock, + timeout: float | None, +) -> None: + """Acquire a FileLock with timeout without automatic release (unsafe). + + This function acquires a file lock with timeout support but does NOT automatically + release it. The caller is responsible for releasing the lock explicitly. + Use this only when you need manual control over lock lifetime. + + Args: + flock: The FileLock object to acquire + timeout: Timeout in seconds. If None, uses _DEFAULT_TIMEOUT. + - Use _BLOCKING (-1.0) for infinite wait + - Use _NON_BLOCKING (0.0) for immediate return + - Use positive value for finite timeout + + Raises: + FileLockTimeoutError: If the file lock cannot be acquired within the timeout period + + Warning: + This is an "unsafe" function because it does not automatically release + the lock. Always call flock.release() when done, preferably in a try/finally + block or use the safe _acquire_flock_with_timeout context manager instead. + + Example: + flock = FileLock("/tmp/my_process.lock") + try: + _unsafe_acquire_flock_with_timeout(flock, timeout=30.0) + # Critical section - file lock is held + perform_exclusive_file_operation() + finally: + flock.release() # Must manually release! + """ + _timeout: float = timeout if timeout is not None else _DEFAULT_TIMEOUT + try: + _ = flock.acquire(timeout=_timeout) + except Timeout as err: + raise exceptions.FileLockTimeoutError(flock, _timeout) from err + + +@contextmanager +def _acquire_many_impl_locks_with_timeout( + *impls: _CacheImpl, + timeout: float | None = None, +) -> Generator[None, None, None]: + with ExitStack() as stack: + for impl in impls: + stack.enter_context(impl.lock(timeout)) + yield diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/memoizers.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/memoizers.py new file mode 100644 index 0000000000000000000000000000000000000000..da0d535c7796adb1e9a81a7d52eec4194465d2a7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/memoizers.py @@ -0,0 +1,7 @@ +from pathlib import Path + +from .interfaces import PersistentMemoizer + + +# Memoizer for _should_pad in pad_mm +should_pad_memoizer = PersistentMemoizer(sub_dir=Path("should_pad")) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ffc23f21a484c24fa8f86431c7304cc42d0bb63f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/caching/utils.py @@ -0,0 +1,66 @@ +"""Utility functions + +This module provides helper functions for LRU caching decorators used +throughout the caching system. +""" + +from collections.abc import Callable +from functools import lru_cache, wraps +from typing_extensions import ParamSpec, TypedDict, TypeVar + +from torch import Tensor + + +# Type specification for function parameters +P = ParamSpec("P") +# Type variable for function return values +R = TypeVar("R") + + +def _lru_cache(fn: Callable[P, R]) -> Callable[P, R]: + """LRU cache decorator with TypeError fallback. + + Provides LRU caching with a fallback mechanism that calls the original + function if caching fails due to unhashable arguments. Uses a cache + size of 64 with typed comparison. + + Args: + fn: The function to be cached. + + Returns: + A wrapper function that attempts caching with fallback to original function. + """ + cached_fn = lru_cache(maxsize=64, typed=True)(fn) + + @wraps(fn) + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: + try: + return cached_fn(*args, **kwargs) + except TypeError: + return fn(*args, **kwargs) + + return wrapper + + +class EncodedTensor(TypedDict): + """TypedDict for encoded tensor metadata.""" + + shape: tuple[int, ...] + stride: tuple[int, ...] + dtype: str + + +def _encode_tensor(t: Tensor) -> EncodedTensor: + """Encode a tensor's metadata into a JSON-serializable dict. + + Args: + t: PyTorch tensor to encode + + Returns: + Dict containing shape, stride, and dtype information + """ + return EncodedTensor( + shape=tuple(t.shape), + stride=tuple(t.stride()), + dtype=str(t.dtype), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/compile_tasks.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/compile_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..fc99a0be7a24415e7afe8541ebf4434fbca416dd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/compile_tasks.py @@ -0,0 +1,237 @@ +from __future__ import annotations + +import functools +import linecache +import os +import sys +import time +import warnings +from pathlib import Path +from types import ModuleType +from typing import Any, TYPE_CHECKING + +from torch._utils_internal import log_triton_builds + +from ..utils import apply_subprocess_env, clear_caches + + +if TYPE_CHECKING: + from collections.abc import Callable + + from torch._inductor.runtime.triton_heuristics import CachingAutotuner + + +def _reload_python_module( + key: str, path: str, set_sys_modules: bool = True +) -> ModuleType: + with open(path) as f: + try: + code = compile(f.read(), path, "exec", dont_inherit=True) + except Exception as e: + raise RuntimeError( + f"Failed to import {path}\n{type(e).__name__}: {e}" + ) from None + mod = ModuleType(f"{__name__}.{key}") + mod.__file__ = path + mod.key = key # type: ignore[attr-defined] + exec(code, mod.__dict__, mod.__dict__) + if set_sys_modules: + sys.modules[mod.__name__] = mod + return mod + + +@functools.cache +def _set_triton_ptxas_path() -> None: + if os.environ.get("TRITON_PTXAS_PATH") is not None: + return + ptxas = Path(__file__).absolute().parents[2] / "bin" / "ptxas" + if not ptxas.exists(): + return + if ptxas.is_file() and os.access(ptxas, os.X_OK): + os.environ["TRITON_PTXAS_PATH"] = str(ptxas) + else: + warnings.warn(f"{ptxas} exists but is not an executable") + + +def _set_triton_libdevice_path() -> None: + """ + Use the CUDA toolkit's libdevice instead of Triton's bundled version. + This ensures Triton's libdevice calls match CUDA eager numerics for bitwise + precision. Gated by config.eager_numerics.use_pytorch_libdevice and by + config.emulate_precision_casts, which also requests eager-like numerics. + """ + from torch._inductor import config + + if not ( + config.eager_numerics.use_pytorch_libdevice or config.emulate_precision_casts + ): + return + + _set_triton_libdevice_path_impl() + + +def _set_triton_libdevice_path_impl() -> None: + import torch + + if torch.version.cuda is None: + return + + try: + from triton import knobs + except ImportError: + return + + env_path = os.environ.get("TRITON_LIBDEVICE_PATH") + if env_path is not None: + knobs.nvidia.libdevice_path = env_path + return + + if knobs.nvidia.libdevice_path is not None: + return + + try: + from torch.utils.cpp_extension import CUDA_HOME + + if CUDA_HOME is None: + warnings.warn( + "CUDA_HOME not set; using Triton's bundled libdevice which may " + "cause minor precision differences in pow operations. " + "To fix: set TRITON_LIBDEVICE_PATH to your CUDA toolkit's libdevice, " + "e.g., export TRITON_LIBDEVICE_PATH=/usr/local/cuda/nvvm/libdevice/libdevice.10.bc", + stacklevel=3, + ) + return + libdevice = Path(CUDA_HOME) / "nvvm" / "libdevice" / "libdevice.10.bc" + if libdevice.is_file(): + knobs.nvidia.libdevice_path = str(libdevice) + # Also set env var so subprocess compile workers inherit it + os.environ["TRITON_LIBDEVICE_PATH"] = str(libdevice) + else: + warnings.warn( + f"CUDA libdevice not found at {libdevice}; using Triton's bundled " + "libdevice which may cause minor precision differences in pow operations. " + "To fix: set TRITON_LIBDEVICE_PATH to your CUDA toolkit's libdevice, " + "e.g., export TRITON_LIBDEVICE_PATH=/usr/local/cuda/nvvm/libdevice/libdevice.10.bc", + stacklevel=3, + ) + except ImportError: + warnings.warn( + "torch.utils.cpp_extension not available; using Triton's bundled " + "libdevice which may cause minor precision differences in pow operations. " + "To fix: set TRITON_LIBDEVICE_PATH to your CUDA toolkit's libdevice, " + "e.g., export TRITON_LIBDEVICE_PATH=/usr/local/cuda/nvvm/libdevice/libdevice.10.bc", + stacklevel=3, + ) + + +_WORKER_CACHE_ENV_VARS = ("TORCHINDUCTOR_CACHE_DIR", "TRITON_CACHE_DIR") +_last_applied_cache_env: dict[str, str | None] | None = None + + +def _apply_subprocess_env_and_clear_caches(extra_env: dict[str, str | None]) -> None: + global _last_applied_cache_env + + cache_env = { + key: extra_env.get(key) for key in _WORKER_CACHE_ENV_VARS if key in extra_env + } + if cache_env and cache_env != _last_applied_cache_env: + clear_caches() + _last_applied_cache_env = cache_env.copy() + apply_subprocess_env(extra_env) + + +def _worker_compile_pycodecache_kernel( + kernel_name: str, + source_code: str, + main_suffix: str, + extra_env: dict[str, str | None], + precompile_metadata: dict[str, Any] | None = None, +) -> tuple[str, str, int]: + """ + Subprocess worker for PyCodeCache-based kernel compilation. + + Writes source to PyCodeCache, loads the module, validates the entry point, + and optionally triggers real GPU compilation (MLIR -> PTX -> CUBIN) via a + _precompile entry point. Compiled artifacts are persisted to disk cache so + the parent process can load them without recompilation. + + Used by both CuteDSL and NV Universal GEMM backends. + """ + _apply_subprocess_env_and_clear_caches(extra_env) + + start_ns = time.time_ns() + + import torch._inductor.codecache as codecache + + key, path = codecache.PyCodeCache.write(source_code) + mod = codecache.PyCodeCache.load_by_key_path(key, path) + + main_func_name = f"{kernel_name}_{main_suffix}" + if not hasattr(mod, main_func_name): + available = [name for name in dir(mod) if callable(getattr(mod, name))] + raise RuntimeError( + f"Could not find kernel function '{main_func_name}'. " + f"Available callables: {available}" + ) + + if precompile_metadata is not None: + precompile_fn_name = f"{kernel_name}_precompile" + precompile_fn = getattr(mod, precompile_fn_name, None) + if precompile_fn is not None: + precompile_fn(**precompile_metadata) + else: + import logging + + logging.getLogger(__name__).warning( + "Precompile metadata was provided but module has no %s " + "— the scheduling layer expected this template to support " + "subprocess precompilation. Kernel will compile lazily on " + "first call instead.", + precompile_fn_name, + ) + + elapsed_ns = time.time_ns() - start_ns + linecache.clearcache() + return key, path, elapsed_ns // 1000 + + +def _worker_compile_triton( + load_kernel: Callable[[], CachingAutotuner], + extra_env: dict[str, str | None], + extra_config: dict[str, Any], +) -> tuple[CachingAutotuner, int]: + _set_triton_ptxas_path() + _apply_subprocess_env_and_clear_caches(extra_env) + # Keep Triton's in-process knob in sync with the parent environment, including + # clearing stale worker state when the parent no longer has this variable. + if "TRITON_LIBDEVICE_PATH" in extra_env: + try: + from triton import knobs + + knobs.nvidia.libdevice_path = extra_env["TRITON_LIBDEVICE_PATH"] + except ImportError: + pass + from torch._inductor import config + from torch._inductor.compile_worker import watchdog + from torch._inductor.runtime import triton_helpers + + with config.patch(extra_config): + fail = None + try: + start_ns = time.time_ns() + # Generated Triton modules set up the GPU driver at import time, + # but compile workers only need to warm the compile cache. + with triton_helpers.skip_gpu_driver_setup(): + kernel = load_kernel() + watchdog.report_phase(watchdog.Phase.COMPILING) + kernel.precompile(warm_cache_only=True) + elapsed_ns = time.time_ns() - start_ns + kernel.prepare_for_pickle() + # We can release this memory in the compile subprocesses: + linecache.clearcache() + return kernel, elapsed_ns // 1000 + except Exception as e: + fail = str(e) + raise + finally: + log_triton_builds(fail=fail) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/coordinate_descent_tuner.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/coordinate_descent_tuner.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9761a3688e8b93ee99cbcf24e96b8703607b5b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/coordinate_descent_tuner.py @@ -0,0 +1,488 @@ +# mypy: allow-untyped-defs +import copy +import itertools +import logging +from collections.abc import Callable +from typing import TYPE_CHECKING + +from torch.utils._ordered_set import OrderedSet + +from ..utils import get_max_numwarps +from .hints import ( + InductorMeta, + native_matmul_block_numel, + native_matmul_persistent_rblock, + TRITON_MAX_BLOCK, + TRITON_MAX_TENSOR_NUMEL, +) +from .runtime_utils import red_text, triton_config_to_hashable + + +if TYPE_CHECKING: + from .triton_compat import triton + + +log = logging.getLogger(__name__) + + +def get_field(config, name): + if name == "num_warps": + return config.num_warps + elif name == "num_stages": + return config.num_stages + elif name == "waves_per_eu": + return config.kwargs.get(name, int(8 // config.num_warps)) + else: + return config.kwargs.get(name, None) + + +def set_field(config, name, value): + if name == "num_warps": + config.num_warps = value + elif name == "num_stages": + config.num_stages = value + else: + config.kwargs[name] = value + + +class CoordescTuner: + """ + The coordinate descent tuner. Tune one field/coordinate at a time. + + TODO will it be necessary to tune multiple fields simultaneously. + + + TODO: what if both increasing and decreasing a field can improve perf. + i.e., there are multiple local optima.. + """ + + def __init__( + self, + is_mm=False, + is_native_matmul=False, + is_mix_order_reduction=False, + name="unknown", + size_hints=None, + inductor_meta: InductorMeta | None = None, + frozen_fields=None, + ): + self.is_mm = is_mm # we will tune num_stages for mm + + # Native matmul codegen assumes ZBLOCK=1 always. + # This is because 3d tl.dot is slow and so we want to tile y and x only. + # tl.dot also does not support size smaller than 16; we put this restriction. + self.is_native_matmul = is_native_matmul + if self.is_mm and self.is_native_matmul: + raise AssertionError("is_mm and is_native_matmul are mutually exclusive") + self.is_mix_order_reduction = is_mix_order_reduction + self.cached_benchmark_results = {} + self.name = name + self.size_hints = size_hints + self.inductor_meta: InductorMeta = ( + inductor_meta if inductor_meta is not None else {} + ) + self.frozen_fields: OrderedSet[str] = ( + OrderedSet(frozen_fields) if frozen_fields is not None else OrderedSet() + ) + + def get_config_max(self, prefix: str) -> int: + max_block = TRITON_MAX_BLOCK[prefix.upper()] + size_hint = self.size_hints.get(prefix) if self.size_hints is not None else None + return min(max_block, size_hint) if size_hint is not None else max_block + + def get_warpsmax(self): + # Avoid querying device directly if device properties are populated in inductor_meta + warp_size = self.inductor_meta.get("warp_size") + max_threads_per_block = self.inductor_meta.get("max_threads_per_block") + if warp_size and max_threads_per_block: + return max_threads_per_block // warp_size + else: + return get_max_numwarps() + + def cache_benchmark_result(self, config, timing): + self.cached_benchmark_results[triton_config_to_hashable(config)] = timing + + def lookup_in_cache(self, config): + return self.cached_benchmark_results.get(triton_config_to_hashable(config)) + + def call_func(self, func, config): + found = self.lookup_in_cache(config) + if found is not None: + log.debug(" CACHED") + return found + timing = func(config) + self.cache_benchmark_result(config, timing) + return timing + + @property + def tunable_fields(self) -> list[str]: + out: list[str] = [ + "XBLOCK", + "YBLOCK", + "ZBLOCK", + # NOTE: we should not tune R0_BLOCK for persistent reduction. + # We rely on the fact that persistent reduction's triton.Config + # does not have the R0_BLOCK field to guarantee that. + "R0_BLOCK", + "R1_BLOCK", + # the following 3 are for mm + "BLOCK_M", + "BLOCK_N", + "BLOCK_K", + "num_warps", + ] + if self.is_mm: + out.append("num_stages") + if self.inductor_meta.get("is_hip") is True: + out.append("waves_per_eu") + if self.is_native_matmul: + out.append("num_stages") + out.remove("ZBLOCK") # ZBLOCK=1 always in native matmul + + if self.is_mix_order_reduction: + # unlike TritonConfig.num_stages, this one is + # put in TritonConfig.kwargs["NUM_STAGES"] and is used to + # control the stage of pipelining of tl.range. + out.append("NUM_STAGES") + + # Combo-kernel per-subkernel block fields (e.g. XBLOCK_0/1, YBLOCK_0/1) + # come from the worker-side metadata in ``inductor_meta``. Prepend + # them so coordesc iterates them alongside the base fields. Read + # live each call so any post-construction mutation of + # ``inductor_meta`` is observed. + combo_fields: list[str] = self.inductor_meta.get( + "combo_coordesc_field_order", [] + ) + out = combo_fields + out + return [f for f in out if f not in self.frozen_fields] + + def value_too_large(self, name: str, val: int) -> bool: + field_limits = self.inductor_meta.get("combo_coordesc_field_limits") + if isinstance(field_limits, dict) and name in field_limits: + return val > field_limits[name] + + block_suffix = "BLOCK" + if name.endswith(block_suffix): + prefix = name.strip(block_suffix).lower() + return val > self.get_config_max(prefix) + if name == "num_warps": + return val > self.get_warpsmax() + if name == "waves_per_eu": + return val > 8 + + return False + + def value_too_small(self, name: str, val: int) -> bool: + min_block = None + if name == "XBLOCK": + min_block = self.inductor_meta.get("min_xblock") + elif name == "R0_BLOCK": + min_block = self.inductor_meta.get("min_rblock") + if min_block is not None and val < min_block: + return True + + # In native matmul, block size should be >= 16 for tl.dot + if self.is_native_matmul: + if name in ["YBLOCK", "XBLOCK", "R0_BLOCK"]: + return val < 16 + + # Break if value becomes 0/neg + return val <= 0 + + def get_neighbour_values(self, name, orig_val, radius=None, include_self=False): + """ + Get neighbour values in 'radius' steps. The original value is not + returned as its own neighbour. + """ + if radius is None: + radius = 1 + if name == "NUM_STAGES": + # we see cases that + # NUM_STAGES=1 is better than NUM_STAGES=2 + # while NUM_STAGES=1 is worse than NUM_STAGES=3 + radius = max(radius, 2) + + if radius < 1: + raise AssertionError(f"radius must be >= 1, got {radius}") + + def update(cur_val, inc=True): + if name in ["num_stages", "NUM_STAGES"]: + if inc: + return cur_val + 1 + else: + return cur_val - 1 + else: + if inc: + return cur_val * 2 + else: + return cur_val // 2 + + out = [] + # increment loop + cur_val = orig_val + for _ in range(radius): + cur_val = update(cur_val, True) + if self.value_too_large(name, cur_val): + break + out.append(cur_val) + + # decrement loop + cur_val = orig_val + for _ in range(radius): + cur_val = update(cur_val, False) + if self.value_too_small(name, cur_val): + break + out.append(cur_val) + + if include_self: + out.append(orig_val) + return out + + @staticmethod + def has_improvement(baseline, test): + threshold = 0.001 # 0.1% + return test is not None and test < baseline * (1 - threshold) + + def is_valid_config(self, config) -> bool: + if self.is_mix_order_reduction: + # Mix order reduction has an extra constraint that + # we should not tune XBLOCK beyond RSPLIT_SIZE + xblock = config.kwargs["XBLOCK"] + split_size = config.kwargs["RSPLIT_SIZE"] + return xblock <= split_size + if self.is_native_matmul: + r0_block = None + if "R0_BLOCK" not in config.kwargs: + r0_block = self.inductor_meta.get("native_matmul_persistent_rblock") + if r0_block is None and self.size_hints is not None: + r0_block_hint = self.size_hints.get("r0_") + if r0_block_hint is not None: + r0_block = native_matmul_persistent_rblock(r0_block_hint) + if ( + native_matmul_block_numel(config.kwargs, r0_block=r0_block) + > TRITON_MAX_TENSOR_NUMEL + ): + return False + return True + + def get_all_tuning_directions( + self, + # pyrefly: ignore [missing-attribute] + config: "triton.Config", + ) -> list["triton.Config"]: # pyrefly: ignore [missing-attribute] + """Return the Cartesian product of neighbour values across every + tunable field, as a list of valid candidate configs.""" + candidate_values_list = [] + effective_fields = [] + for field in self.tunable_fields: + old_value = get_field(config, field) + if old_value is None: + continue + radius = self.inductor_meta.get("coordinate_descent_search_radius", 1) + candidate_values = self.get_neighbour_values( + field, + old_value, + radius=radius, + include_self=True, + ) + candidate_values_list.append(candidate_values) + effective_fields.append(field) + + configs = [] + for choice in itertools.product(*candidate_values_list): + if len(choice) != len(effective_fields): + raise AssertionError( + f"Expected {len(effective_fields)} values, got {len(choice)}" + ) + candidate = copy.deepcopy(config) + for new_val, field in zip(choice, effective_fields): + set_field(candidate, field, new_val) + if self.is_valid_config(candidate): + configs.append(candidate) + return configs + + def check_all_tuning_directions( + self, + # pyrefly: ignore [missing-attribute] + func: Callable[["triton.Config"], float], + best_config, + best_timing, + ): + """ + Check all directions. We only do this once the regular coordinate + descent tuning find no better choices any more. + We only have a few tunable fields, so this should be fine. + """ + improved = False + for candidate_config in self.get_all_tuning_directions(best_config): + cmp_res, candidate_timing = self.compare_config( + func, candidate_config, best_config, best_timing + ) + if cmp_res: + improved = True + best_config = candidate_config + best_timing = candidate_timing + + return improved, best_config, best_timing + + def compare_config(self, func, candidate_config, best_config, best_timing): + """ + Check if candidate_config is better than best_config. + + Return a tuple of (compare_result, candidate_timing). + compare_result is true iff candidate_config is better. + """ + log.debug("Try config %s", candidate_config) + try: + candidate_timing = self.call_func(func, candidate_config) + except Exception as e: + log.debug("Got exception %s", e) + return False, float("inf") + + if self.has_improvement(best_timing, candidate_timing): + log.debug( + "Tune from %s %f -> %s %f", + best_config, + best_timing, + candidate_config, + candidate_timing, + ) + + return True, candidate_timing + return False, candidate_timing + + def get_neighbour_configs( + self, + # pyrefly: ignore [missing-attribute] + config: "triton.Config", + field: str, + ) -> list["triton.Config"]: # pyrefly: ignore [missing-attribute] + """Return every valid neighbour of ``config`` along ``field`` + only — the per-axis counterpart of ``get_neighbour_values``. + + Precondition: ``field`` must be present on ``config``. Callers + iterating ``tunable_fields`` against arbitrary configs must + filter empty fields up front; ``autotune`` does.""" + cur_val = get_field(config, field) + if cur_val is None: + raise AssertionError(f"field {field!r} not present on config") + neighbours = [] + for next_val in self.get_neighbour_values(field, cur_val): + candidate = copy.deepcopy(config) + set_field(candidate, field, next_val) + if self.is_valid_config(candidate): + neighbours.append(candidate) + return neighbours + + def autotune( + self, + # pyrefly: ignore [missing-attribute] + func: Callable[["triton.Config"], float], + # pyrefly: ignore [missing-attribute] + baseline_config: "triton.Config", + baseline_timing: float | None = None, + ) -> "triton.Config": # pyrefly: ignore # missing-attribute + """ + Perform coordinate descent autotuning starting from a baseline configuration. + """ + if baseline_timing is None: + baseline_timing = self.call_func(func, baseline_config) + + log.debug("= Do coordinate descent tuning for %s =", self.name) + log.debug( + "%s: Baseline Config %s, baseline timing %f", + self.name, + baseline_config, + baseline_timing, + ) + improved = True + best_config = baseline_config + best_timing = baseline_timing + + while improved: + improved = False + + # Gauss-Seidel: walk one field at a time, applying any + # improvement immediately so subsequent fields see the + # updated working point. + for field in self.tunable_fields: + # Some kernels don't have R0_BLOCK / YBLOCK / ZBLOCK, + # so the field may be absent from ``best_config``. + # Filter here so ``get_neighbour_configs`` can assume + # the field is present. + if get_field(best_config, field) is None: + continue + for candidate_config in self.get_neighbour_configs(best_config, field): + cmp_res, candidate_timing = self.compare_config( + func, candidate_config, best_config, best_timing + ) + if cmp_res: + improved = True + best_config, best_timing = candidate_config, candidate_timing + + if not improved and self.inductor_meta.get( + "coordinate_descent_check_all_directions" + ): + old_best_timing = best_timing + improved, best_config, best_timing = self.check_all_tuning_directions( + func, best_config, best_timing + ) + + if improved: + msg = red_text( + "%s: Coordinate descend tuning found improvement of %.3fx by looking in all directions." + ) + log.debug( + msg, + self.name, + old_best_timing / best_timing, + ) + + log.debug( + "%s: Improve from %s %f -> %s %f, %.3fx", + self.name, + baseline_config, + baseline_timing, + best_config, + best_timing, + baseline_timing / best_timing, + ) + + return best_config + + @staticmethod + def autotune_single_field(fn, init_val, min_val=None, max_val=None): + """ + fn is a function that takes the field value and returns the benchmarking result + init_val is the starting point of autotuning. + + Should work well for parabola like curve. Here is a real example + for split-size of mix-order-reduction: https://github.com/pytorch/pytorch/pull/166461 + """ + cache = {} + + def _bench(val): + if val not in cache: + cache[val] = fn(val) + # print(f"split size {val} -> {cache[val]:.3f} ms") + return cache[val] + + if min_val is None: + min_val = 1 + if max_val is None: + max_val = 2**30 # some arbitrary large value + + best_val = init_val + improved = True + while improved: + improved = False + candlist = [best_val // 2, best_val * 2] + for cand in candlist: + cand = max(cand, min_val) + cand = min(cand, max_val) + + if _bench(cand) < _bench(best_val): + best_val = cand + improved = True + + return best_val diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/cutedsl_cache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/cutedsl_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..52d4d1ebaa3babc1646da14c3239272a534b5b80 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/cutedsl_cache.py @@ -0,0 +1,164 @@ +"""Disk cache for CuTe DSL compiled kernel artifacts. + +Persists compiled GPU binaries (CUBIN/PTX via TVM FFI) across process +boundaries so that subprocess compilation workers can produce artifacts +that the parent process loads without recompilation. + +Cache keys include the module's PyCodeCache path (content-addressed), +compile-time configuration, runtime shapes/dtypes, GPU architecture, +and CUDA toolkit version to prevent stale artifact reuse. +""" + +from __future__ import annotations + +import hashlib +import logging +import os +import pickle +import struct +from pathlib import Path +from typing import Any + + +log = logging.getLogger(__name__) + + +def _fix_elf_dup_text_flags(data: bytes) -> bytes: + """Harmonize flags on duplicate .text ELF sections. + + The CUTLASS MLIR compiler emits .o files with two .text sections: + one for code (ALLOC|EXECINSTR) and one for writable data + (WRITE|ALLOC). LLVM's MCJIT mishandles this in multi-process + workloads, causing non-deterministic SIGSEGV. Fix: set duplicate + .text sections' flags to match the first (ALLOC|EXECINSTR = 0x6). + + See https://github.com/NVIDIA/cutlass/issues/3162 + """ + if len(data) < 64 or data[4] != 2 or data[5] != 1: + return data + e_shoff = struct.unpack_from("= e_shnum: + return data + shstr_hdr = e_shoff + e_shstrndx * e_shentsize + shstr_off = struct.unpack_from(" Path: + cache_root = os.environ.get( + "TORCHINDUCTOR_CACHE_DIR", + os.path.join(os.path.expanduser("~"), ".cache", "torch_inductor"), + ) + return Path(cache_root) / "cutedsl_compile_cache" + + +def _make_disk_key( + module_path: str, + config_key: tuple[Any, ...], + runtime_key: tuple[Any, ...], + device_index: int = 0, + device_capability: tuple[int, int] | None = None, +) -> str: + import torch + + arch = device_capability + if arch is None and torch.cuda.is_available(): + arch = torch.cuda.get_device_capability(device_index) + cuda_version = getattr(torch.version, "cuda", None) + + full_key = (module_path, config_key, runtime_key, arch, cuda_version) + return hashlib.sha256(pickle.dumps(full_key)).hexdigest() + + +def disk_cache_get( + mem_cache: dict[Any, Any], + module_path: str, + config_key: tuple[Any, ...], + runtime_key: tuple[Any, ...], + device_index: int = 0, + device_capability: tuple[int, int] | None = None, +) -> Any | None: + """Look up a compiled CuTe DSL function, checking memory then disk.""" + mem_key = (runtime_key, device_index) + if mem_key in mem_cache: + return mem_cache[mem_key] + + h = _make_disk_key( + module_path, config_key, runtime_key, device_index, device_capability + ) + obj_path = _cache_dir() / f"{h}.o" + if obj_path.exists(): + try: + raw = obj_path.read_bytes() + patched = _fix_elf_dup_text_flags(raw) + if patched is not raw: + obj_path.write_bytes(patched) + + import cutlass.cute as cute + + m = cute.runtime.load_module(str(obj_path), enable_tvm_ffi=True) + fn = m.func + mem_cache[mem_key] = fn + return fn + except Exception: + log.debug("Failed to load cached artifact %s", obj_path, exc_info=True) + return None + + +def disk_cache_set( + mem_cache: dict[Any, Any], + module_path: str, + config_key: tuple[Any, ...], + runtime_key: tuple[Any, ...], + compiled_fn: Any, + device_index: int = 0, + device_capability: tuple[int, int] | None = None, +) -> None: + """Store a compiled CuTe DSL function to memory and disk.""" + mem_key = (runtime_key, device_index) + mem_cache[mem_key] = compiled_fn + + h = _make_disk_key( + module_path, config_key, runtime_key, device_index, device_capability + ) + d = _cache_dir() + d.mkdir(parents=True, exist_ok=True) + obj_path = d / f"{h}.o" + import tempfile + + tmp_path = None + try: + fd, tmp_path = tempfile.mkstemp(dir=str(d), suffix=".o.tmp") + os.close(fd) + compiled_fn.export_to_c(object_file_path=tmp_path, function_name="func") + with open(tmp_path, "rb") as f: + patched = _fix_elf_dup_text_flags(f.read()) + with open(tmp_path, "wb") as f: + f.write(patched) + os.replace(tmp_path, str(obj_path)) + except (AttributeError, RuntimeError, TypeError): + log.debug( + "export_to_c not available for %s, skipping disk persistence", + type(compiled_fn).__name__, + exc_info=True, + ) + if tmp_path is not None: + try: + os.unlink(tmp_path) + except OSError: + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/debug_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/debug_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2c85d5049fa9a40c257194479a036602103f8a87 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/debug_utils.py @@ -0,0 +1,143 @@ +import functools +import logging +import threading +import weakref + +import torch +from torch.utils._ordered_set import OrderedSet + + +log = logging.getLogger(__name__) + +local = threading.local() +local.memory_tracker = None + + +class BufferMemoryTracker: + """ + Tracks inductor runtime allocations and deallocations to compare against + expected behavior. + """ + + def __init__(self) -> None: + self.tensor_tracker: dict[str, torch.storage.UntypedStorage] = ( + weakref.WeakValueDictionary() # type: ignore[assignment] + ) + self.died_since_last_step: OrderedSet[str] = OrderedSet() + self.added_since_last_step: OrderedSet[str] = OrderedSet() + self.error = ( + torch._inductor.config.test_configs.track_memory_lifecycle == "assert" + ) + + def set_tensor(self, name: str, tensor: torch.Tensor) -> None: + storage = tensor.untyped_storage() + + self.added_since_last_step.add(name) + self.tensor_tracker[name] = storage + + def on_tensor_death() -> None: + self.died_since_last_step.add(name) + + weakref.finalize(storage, on_tensor_death) + + def advance_step(self) -> None: + self.died_since_last_step.clear() + self.added_since_last_step.clear() + + def log_or_raise(self, msg: str) -> None: + if self.error: + raise RuntimeError(msg) + else: + log.info(msg) + + def check_step_delta( + self, + expected_allocated: list[str], + expected_freed: list[str], + is_final_step: bool, + ) -> None: + """Check only the delta changes since last step""" + + # Check expected deaths - we don't currently distinguish between nodes which die in last step + # and are returned as outputs, so skip if final_step. + if not is_final_step: + missing_deaths = OrderedSet(expected_freed) - self.died_since_last_step + if missing_deaths: + self.log_or_raise( + f"Expected tensors to die but still alive: {missing_deaths}" + ) + + # Check for unexpected deaths + unexpected_deaths = self.died_since_last_step - OrderedSet(expected_freed) + if unexpected_deaths: + self.log_or_raise(f"Unexpected tensor deaths: {unexpected_deaths}") + + # Check newly alive tensors - separate messages like deaths + actual_allocated = self.added_since_last_step + expected_allocated_set = OrderedSet(expected_allocated) + + extra_alive = actual_allocated - expected_allocated_set + if extra_alive: + self.log_or_raise(f"Unexpected allocated tensors: {extra_alive}") + + missing_alive = expected_allocated_set - actual_allocated + if missing_alive: + self.log_or_raise( + f"Expected allocated tensors but missing: {missing_alive}" + ) + + # Reset for next step + self.advance_step() + + if is_final_step: + local.memory_tracker = None + + +def get_mem_tracker() -> BufferMemoryTracker: + if local.memory_tracker is None: + local.memory_tracker = BufferMemoryTracker() + return local.memory_tracker + + +def track_tensor(tensor: torch.Tensor, name: str) -> None: + get_mem_tracker().set_tensor(name, tensor) + + +def tracked_empty_strided( + size: list[int], + stride: list[int], + *, + dtype: torch.dtype, + device: torch.device, + name: str, +) -> torch.Tensor: + o = torch.empty_strided(size, stride, dtype=dtype, device=device) + track_tensor(o, name) + return o + + +def check_memory_step( + allocated: list[str], freed: list[str], is_final_step: bool = False +) -> None: + tracker = get_mem_tracker() + tracker.check_step_delta(allocated, freed, is_final_step) + + +@functools.lru_cache(None) +def register_check_mem_op() -> None: + lib = torch.library.Library("_inductor_debug", "FRAGMENT") + # Keep `lib` alive: this function is lru_cached, so it runs once, but the + # registered op must remain accessible via torch.ops for the rest of the + # process's lifetime. Letting `lib` die triggers the finalizer, which + # clears torch.ops._inductor_debug.check_memory_step. + torch.library._keep_alive.append(lib) + lib.define( + "check_memory_step(str[] allocated, str[] freed, bool is_final_step) -> ()" + ) + lib.impl("check_memory_step", check_memory_step, "BackendSelect") + from torch._higher_order_ops.effects import _EffectType, _register_effectful_op + + _register_effectful_op( + torch.ops._inductor_debug.check_memory_step.default, + _EffectType.ORDERED, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/halide_helpers.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/halide_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9fbcd14a7b9a5a132ecb2abd89f7db286af6d053 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/halide_helpers.py @@ -0,0 +1,157 @@ +# mypy: allow-untyped-defs +import math + + +try: + import halide as hl # type: ignore[import-untyped, import-not-found] +except ImportError: + hl = None + +PHILOX_N_ROUNDS_DEFAULT = 10 # Default number of rounds for philox + +if hl is not None: + PHILOX_KEY_A_U32 = hl.u32(0x9E3779B9) + PHILOX_KEY_B_U32 = hl.u32(0xBB67AE85) + PHILOX_ROUND_A_U32 = hl.u32(0xD2511F53) + PHILOX_ROUND_B_U32 = hl.u32(0xCD9E8D57) +else: + PHILOX_KEY_A_U32 = None + PHILOX_KEY_B_U32 = None + PHILOX_ROUND_A_U32 = None + PHILOX_ROUND_B_U32 = None + + +def _pair_uniform_to_normal(u1, u2): + """Box-Muller transform""" + u1 = hl.max(hl.f32(1.0e-7), u1) + th = hl.f32(math.tau) * u2 + r = hl.sqrt(hl.f32(-2.0) * hl.log(u1)) + return r * hl.cos(th), r * hl.sin(th) + + +def _uint_to_uniform_float(x): + """ + Numerically stable function to convert a random uint into a random float uniformly sampled in [0, 1). + """ + + # TODO: + # conditions can be simplified + # scale is ((2**23 - 1) / 2**23) * 2**(N_BITS - 1) + # https://github.com/triton-lang/triton/blob/e4a0d93ff1a367c7d4eeebbcd7079ed267e6b06f/python/triton/language/random.py#L116-L132. + if x.type() != hl.UInt(32) and x.type() != hl.Int(32): + raise AssertionError(f"Expected UInt(32) or Int(32), got {x.type()}") + x = hl.cast(hl.Int(32), x) + scale = hl.f64(4.6566127342e-10) + x = hl.select(x < 0, -x - 1, x) + return x * scale + + +def philox_impl(c0, c1, c2, c3, k0, k1, n_rounds): + def umulhi(a, b): + a = hl.cast(hl.UInt(64), a) + b = hl.cast(hl.UInt(64), b) + return hl.cast(hl.UInt(32), ((a * b) >> 32) & hl.u64(0xFFFFFFFF)) + + for _ in range(n_rounds): + _c0, _c2 = c0, c2 + + c0 = umulhi(PHILOX_ROUND_B_U32, _c2) ^ c1 ^ k0 + c2 = umulhi(PHILOX_ROUND_A_U32, _c0) ^ c3 ^ k1 + c1 = PHILOX_ROUND_B_U32 * _c2 + c3 = PHILOX_ROUND_A_U32 * _c0 + # raise key + k0 = k0 + PHILOX_KEY_A_U32 + k1 = k1 + PHILOX_KEY_B_U32 + + return c0, c1, c2, c3 + + +def halide_philox(seed, c0, c1, c2, c3, n_rounds): + seed = hl.cast(hl.UInt(64), seed) + + if c0.type().bits() != 32: + raise AssertionError(f"Expected 32-bit type, got {c0.type().bits()}-bit") + + seed_hi = hl.cast(hl.UInt(32), (seed >> 32) & hl.u64(0xFFFFFFFF)) + seed_lo = hl.cast(hl.UInt(32), seed & hl.u64(0xFFFFFFFF)) + + return philox_impl(c0, c1, c2, c3, seed_lo, seed_hi, n_rounds) + + +def randint4x(seed, offset, n_rounds): + offset = hl.cast(hl.UInt(32), offset) + _0 = hl.u32(0) + return halide_philox(seed, offset, _0, _0, _0, n_rounds) + + +def rand4x(seed, offset, n_rounds=PHILOX_N_ROUNDS_DEFAULT): + i1, i2, i3, i4 = randint4x(seed, offset, n_rounds) + u1 = _uint_to_uniform_float(i1) + u2 = _uint_to_uniform_float(i2) + u3 = _uint_to_uniform_float(i3) + u4 = _uint_to_uniform_float(i4) + return u1, u2, u3, u4 + + +def randint(seed, offset, n_rounds=PHILOX_N_ROUNDS_DEFAULT): + ret, _, _, _ = randint4x(seed, offset, n_rounds) + return ret + + +def rand(seed, offset, n_rounds=PHILOX_N_ROUNDS_DEFAULT): + source = randint(seed, offset, n_rounds) + return _uint_to_uniform_float(source) + + +def rand_eager_kernel(seed, offset_blocks, tid, VEC, n_rounds=PHILOX_N_ROUNDS_DEFAULT): + inv = hl.cast(hl.Float(32), 1.0 / 4294967296.0) # 2^-32 + half = hl.cast(hl.Float(32), 0.5) * inv + + tid_u64 = hl.cast(hl.UInt(64), tid) + VEC_u64 = hl.cast(hl.UInt(64), VEC) + subseq = tid_u64 // VEC_u64 + which4 = (tid_u64 % VEC_u64) // hl.cast(hl.UInt(64), 4) + lane = tid_u64 % hl.cast(hl.UInt(64), 4) + + offblk = hl.cast(hl.UInt(64), offset_blocks) + which4 + + c0 = hl.cast(hl.UInt(32), offblk & hl.cast(hl.UInt(64), 0xFFFFFFFF)) + c1 = hl.cast( + hl.UInt(32), + (offblk >> hl.cast(hl.UInt(64), 32)) & hl.cast(hl.UInt(64), 0xFFFFFFFF), + ) + c2 = hl.cast(hl.UInt(32), subseq & hl.cast(hl.UInt(64), 0xFFFFFFFF)) + c3 = hl.cast( + hl.UInt(32), + (subseq >> hl.cast(hl.UInt(64), 32)) & hl.cast(hl.UInt(64), 0xFFFFFFFF), + ) + + u0, u1, u2, u3 = halide_philox(seed, c0, c1, c2, c3, n_rounds) + + v01 = hl.select(lane == hl.cast(hl.UInt(64), 0), u0, u1) + v23 = hl.select(lane == hl.cast(hl.UInt(64), 2), u2, u3) + rand_int = hl.select( + (lane == hl.cast(hl.UInt(64), 0)) | (lane == hl.cast(hl.UInt(64), 1)), v01, v23 + ) + + return hl.cast(hl.Float(32), 1.0) - (hl.cast(hl.Float(32), rand_int) * inv + half) + + +def randn(seed, offset): + i1, i2, _, _ = randint4x(seed, offset, PHILOX_N_ROUNDS_DEFAULT) + u1 = _uint_to_uniform_float(i1) + u2 = _uint_to_uniform_float(i2) + n1, _ = _pair_uniform_to_normal(u1, u2) + return n1 + + +def randint64(seed, offset, low, high): + r0, r1, _r2, _r3 = randint4x(seed, offset, PHILOX_N_ROUNDS_DEFAULT) + r0 = hl.cast(hl.UInt(64), r0) + r1 = hl.cast(hl.UInt(64), r1) + + result = r0 | (r1 << 32) + size = high - low + result = result % hl.cast(hl.UInt(64), size) + result = hl.cast(hl.Int(64), result) + low + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/hints.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/hints.py new file mode 100644 index 0000000000000000000000000000000000000000..c05c910ec0339e34468073c458ce3d3ef17c0fce --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/hints.py @@ -0,0 +1,406 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import collections +import functools +import typing +from enum import auto, Enum + +import torch +from torch.utils._triton import has_triton_package + + +# The following maximums only apply to runtime autotuning, when using FixedTritonConfig one may see larger values +# NOTE: if these fail asserts submit a PR to increase them +TRITON_MAX_BLOCK = { + "X": 8192 if torch.version.hip else 4096, + "Y": 1024, + "Z": 1024, + "R0_": 4096 * 16, # * 16 is multi-kernel only + "R1_": 2048 * 16, # * 16 is multi-kernel only +} +TRITON_MAX_RSPLIT = 64 +TRITON_MAX_TENSOR_NUMEL = 1 << 20 +TRITON_DOT_MIN_BLOCK = 16 +TRITON_DEFAULT_BLOCK_SIZES = { + "XBLOCK": 128, + "YBLOCK": 1, + "ZBLOCK": 1, + "R0_BLOCK": 1, +} +TRITON_DEFAULT_RSPLIT = 1 +TRITON_DEFAULT_RSPLIT_SIZE = 1 + + +def native_matmul_block_numel( + kwargs: typing.Mapping[str, int], r0_block: int | None = None +) -> int: + return ( + kwargs.get("XBLOCK", 1) + * kwargs.get("YBLOCK", 1) + * kwargs.get("ZBLOCK", 1) + * (kwargs.get("R0_BLOCK", 1) if r0_block is None else r0_block) + ) + + +def native_matmul_persistent_rblock(r0_block: int) -> int: + return max(r0_block, TRITON_DOT_MIN_BLOCK) + + +class ReductionHint(Enum): + INNER = 0 + OUTER = 1 + OUTER_TINY = 2 + DEFAULT = 3 + + +class TileHint(Enum): + SQUARE = 0 + DEFAULT = 1 + + +# Define `AttrsDescriptorWrapper` function with clear conditional handling +if has_triton_package(): + import triton + import triton.backends.compiler + import triton.compiler.compiler + + if hasattr(triton.backends.compiler, "AttrsDescriptor"): + # Triton 3.2.0 - the second implementation + from triton.backends.compiler import AttrsDescriptor + + def AttrsDescriptorWrapper( + divisible_by_16=None, + equal_to_1=None, + pointer_range_32=None, + ): + # Prepare the arguments for AttrsDescriptor + kwargs = { + "tt.divisibility": divisible_by_16, + "tt.equal_to": equal_to_1, + } + + # Instantiate AttrsDescriptor with the prepared arguments + res = AttrsDescriptor.from_dict( + {"arg_properties": kwargs, "cls": AttrsDescriptor.__name__} + ) + if res.property_values["tt.divisibility"] != 16: + raise AssertionError( + f"Expected tt.divisibility == 16, got {res.property_values['tt.divisibility']}" + ) + if res.property_values["tt.equal_to"] != 1: + raise AssertionError( + f"Expected tt.equal_to == 1, got {res.property_values['tt.equal_to']}" + ) + return res + + elif hasattr(triton.compiler.compiler, "AttrsDescriptor"): + # Triton 3.0.0 - the original implementation + from triton.compiler.compiler import AttrsDescriptor + + def AttrsDescriptorWrapper( + divisible_by_16=None, + equal_to_1=None, + pointer_range_32=None, + ): + # Prepare the arguments for AttrsDescriptor + kwargs = { + "divisible_by_16": divisible_by_16, + "equal_to_1": equal_to_1, + } + + # Instantiate AttrsDescriptor with the prepared arguments + return AttrsDescriptor(**kwargs) + + else: + # Triton in 2025: + # note: there's also a range of triton commits not currently supported + # from ~Dec 9, 2024 to Jan 1 2025, in which AttrsDescriptors are still + # used, but the contents are different. + + def AttrsDescriptorWrapper( + divisible_by_16=None, + equal_to_1=None, + pointer_range_32=None, + ): + # pyrefly: ignore [not-iterable] + # Build attr dict merging divisibility and pointer_range per arg index, + # since a single arg can carry both attributes. + result = {(x,): [["tt.divisibility", 16]] for x in (divisible_by_16 or ())} + for x in pointer_range_32 or (): + key = (x,) + if key in result: + result[key].append(["tt.pointer_range", 32]) + else: + result[key] = [["tt.pointer_range", 32]] + return result + +else: + # Define a namedtuple as a fallback when AttrsDescriptor is not available + AttrsDescriptorWrapper = collections.namedtuple( # type: ignore[no-redef, name-match] + # pyrefly: ignore [invalid-argument] + "AttrsDescriptor", + ["divisible_by_16", "equal_to_1", "pointer_range_32"], + defaults=[(), (), ()], + ) + + +class HeuristicType(Enum): + PERSISTENT_REDUCTION = auto() + POINTWISE = auto() + REDUCTION = auto() + SPLIT_SCAN = auto() + TEMPLATE = auto() + USER_AUTOTUNE = auto() + FIXED = auto() + + +class AutotuneHint(Enum): + ONE_ELEMENT_PER_THREAD = 0 + + # Triton codegen tries to codegen set of AutotuneHints. + # Enum.__repr__ looks like """ + # which isn't valid python. + # Enum.__str__ will just return "AutotuneHint.ELEMENTS_PER_WARP_32". + __repr__ = Enum.__str__ + + +class DeviceProperties(typing.NamedTuple): + """Copy device properties into a data structure not requiring torch to be imported""" + + type: str # type: ignore[assignment] + index: int # type: ignore[assignment] + multi_processor_count: int + cc: int + major: int | None = None + regs_per_multiprocessor: int | None = None + max_threads_per_multi_processor: int | None = None + max_threads_per_block: int | None = None + warp_size: int | None = None + + @property + def warp_size_or_default(self) -> int: + if self.warp_size is not None: + return self.warp_size + if self.type in ("cuda", "hip"): + raise RuntimeError(f"{self.type} device properties must report warp_size") + return 32 + + @classmethod + @functools.cache + def create(cls, device) -> DeviceProperties: + import torch + from torch._dynamo.device_interface import get_interface_for_device + + device_type = device.type + + if torch.version.hip and device_type == "cuda": + device_type = "hip" + + device_interface = get_interface_for_device(device) + props = device_interface.get_device_properties(device) + try: + multi_processor_count = props.multi_processor_count + except AttributeError: + if device_type == "xpu": + multi_processor_count = props.gpu_subslice_count + elif device_type == "mtia": + multi_processor_count = 64 + else: + raise + return cls( + type=device_type, + index=device.index, + multi_processor_count=multi_processor_count, + cc=device_interface.get_compute_capability(device), + major=getattr(props, "major", None), + regs_per_multiprocessor=getattr(props, "regs_per_multiprocessor", None), + max_threads_per_multi_processor=getattr( + props, "max_threads_per_multi_processor", None + ), + max_threads_per_block=getattr(props, "max_threads_per_block", 1024), + warp_size=getattr(props, "warp_size", None), + ) + + +def get_warp_size(device) -> int: + """Return the wave/warp size in threads for the given device. + + Reads from torch.cuda.get_device_properties(device).warp_size via the cached + DeviceProperties.create(). Correct on both AMD (64 for CDNA/gfx9, 32 for + RDNA/gfx10+) and NVIDIA (always 32). Missing cuda/hip warp_size metadata is + treated as an error rather than silently falling back. + """ + return DeviceProperties.create(device).warp_size_or_default + + +class TritonMeta(typing.TypedDict, total=False): + """Metadata bag threaded from Triton codegen into the runtime launcher. + + total=False because the key set is populated incrementally across codegen + (signature/device/constants/configs first, then backend/ROCm/tlx extras) + and the whole bag is forwarded verbatim to external Triton APIs, which + tolerate and ignore keys they do not recognize. `device` is typed as the + codegen-time DeviceProperties; CachingAutotuner rewrites it to the integer + device index before reaching Triton, and the runtime read sites that expect + that int narrow it with an explicit cast. + """ + + signature: dict[str, typing.Any] + device: DeviceProperties + device_type: str + constants: dict[str, typing.Any] + configs: list[typing.Any] + native_matmul: bool + launch_cooperative_grid: bool + enable_fp_fusion: bool + launch_pdl: bool + disable_ftz: bool + matrix_instr_nonkdim: int + waves_per_eu: int + kpack: int + restore_value: tuple[str, ...] + reset_to_zero: tuple[str, ...] + backend_options: dict[str, typing.Any] + + +class InductorMeta(typing.TypedDict, total=False): + """The inductor kernel-config / heuristics metadata bag. + + Produced on the codegen side (TritonKernel.inductor_meta_common / + inductor_meta_per_kernel plus the codegen_kernel literal) and consumed by + the runtime autotuning machinery in triton_heuristics.py, + coordinate_descent_tuner.py, and autotune_cache.py. Every key is optional + (total=False): consumers read via .get(...) with defaults, and several keys + are injected only on specific paths (reductions, combo kernels, fixed grids). + Dynamically keyed nested bags (e.g. combo_grid_meta) stay typed dict[str, + Any] because their keys are computed at runtime. The codegen-side producers + still build this bag as a plain dict[str, Any], so the write side is not yet + checked against this TypedDict; typing the producers is left as a follow-up. + """ + + # Global inductor config snapshot (inductor_meta_common / inductor_meta_from_config) + backend_hash: str | None + assert_indirect_indexing: bool + autotune_local_cache: bool + autotune_pointwise: bool + autotune_remote_cache: bool | None + bundled_autotune_remote_cache: bool | None + force_disable_caches: bool + dynamic_scale_rblock: bool + incremental_autotune: bool + max_autotune: bool + max_autotune_pointwise: bool + min_split_scan_rblock: int + spill_threshold: int + store_cubin: bool + deterministic: bool + batch_invariant: bool + force_filter_reduction_configs: bool + mix_order_reduction_allow_multi_stages: bool + dynamic_disable_pipelining: bool + are_deterministic_algorithms_enabled: bool + is_hip: bool | None + is_fbcode: bool + profile_bandwidth: bool + profile_bandwidth_regex: str + profile_bandwidth_output: str + profile_bandwidth_with_do_bench_using_profiling: bool + coordinate_descent_tuning: bool + coordinate_descent_search_radius: int + coordinate_descent_check_all_directions: bool + + # Per-kernel metadata (inductor_meta_per_kernel) + no_x_dim: bool + atomic_add_found: bool + num_load: int + num_store: int + num_reduction: int + autotune_hints: typing.Any + RSPLIT_SIZE: int + has_loadstore_with_contiguous_rdim: bool + tma_min_block_sizes: dict[str, int] + uses_tma: bool + uses_device_tma: bool + host_tma_descriptor_args: dict[str, dict[str, typing.Any]] + tiling_scores: typing.Any + min_xblock: int + min_rblock: int + persistent_reduction: bool + native_matmul_persistent_rblock: int + add_persistent_rblock: bool + max_persistent_rblock: int + strict_sum_rblock: int + kernel_num_gb: float + kernel_flop: int + + # Kernel identity / launch (codegen_kernel literal) + grid_type: str + kernel_name: str + mutated_arg_names: typing.Any + optimize_mem: bool + + # Injected at runtime (CachingAutotuner, reduction heuristics, combo kernels) + warp_size: int | None + max_threads_per_block: int | None + reduction_hint: typing.Any + combo_grid_meta: dict[str, typing.Any] + combo_tuning_groups: typing.Any + combo_coordesc_field_order: list[str] + combo_coordesc_field_limits: dict[str, int] + combo_warp_stage_candidates: typing.Any + extra_launcher_args: typing.Any + fixed_grid: typing.Any + precomputed_grids: typing.Any + config_args: typing.Any + use_fast_triton_launcher: bool + + +class HalideInputSpec(typing.NamedTuple): + ctype: str + name: str + shape: list[str] | None = None + stride: list[str] | None = None + offset: str | None = None + alias_of: str | None = None + + def bindings_type(self) -> str: + if self.ctype in ("at::Half*", "at::BFloat16*"): + return "uint16_t*" # half not defined + return self.ctype + + def halide_type(self) -> str: + if self.ctype == "at::Half*": + return "halide_type_t(halide_type_float, 16)" # half not defined + if self.ctype == "at::BFloat16*": + return "halide_type_t(halide_type_bfloat, 16)" # half not defined + return f"halide_type_of<{self.ctype.replace('*', '')}>()" + + def is_scalar(self) -> bool: + return self.shape is None + + def is_buffer(self) -> bool: + return self.shape is not None + + +class HalideMeta(typing.NamedTuple): + argtypes: list[HalideInputSpec] + target: str + scheduler: str | None = None + scheduler_flags: dict[str, int | str] | None = None + cuda_device: int | None = None + + def args(self) -> list[str]: + """Command line args to pass to halide generator""" + args = [f"target={self.target}"] + if self.scheduler: + args.append(f"autoscheduler={self.scheduler}") + if self.scheduler_flags: + if not self.scheduler: + raise AssertionError("scheduler_flags requires scheduler to be set") + for k, v in self.scheduler_flags.items(): + args.append(f"autoscheduler.{k}={v}") + return args + + def is_cuda(self) -> bool: + return self.cuda_device is not None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/proton_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/proton_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c857a9529033baaf080cea2566f182a604d093 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/proton_utils.py @@ -0,0 +1,325 @@ +""" +Utilities for post-processing Triton Proton profiling trace files. + +This module provides functions to transform proton-generated Chrome trace files +for better visualization in Perfetto/Chrome tracing tools. +""" + +import gzip +import json +import os +import re +from typing import Any + +from torch.utils._ordered_set import OrderedSet + + +def _write_trace(path: str, data: dict[str, Any]) -> None: + """Write trace data to a gzipped JSON file.""" + with gzip.open(path, "wt", encoding="utf-8") as f: + json.dump(data, f) + + +def _read_trace(path: str) -> dict[str, Any]: + """Read trace data from a JSON file (gzipped or not).""" + if path.endswith(".gz"): + with gzip.open(path, "rt", encoding="utf-8") as f: + return json.load(f) + else: + with open(path) as f: + return json.load(f) + + +def _get_base_name(trace_path: str) -> str: + """Get the base name of a trace file, stripping known extensions.""" + base_name = os.path.basename(trace_path) + for ext in [".trace.json.gz", ".chrome_trace", ".json.gz", ".json"]: + if base_name.endswith(ext): + return base_name[: -len(ext)] + return os.path.splitext(base_name)[0] + + +def _group_events_by_sm(events: list[dict[str, Any]]) -> list[dict[str, Any]]: + """ + Group events so all CTAs on the same SM share one track. + + Transforms: + - pid: "Core0 CTA6" -> "Core0" + - tid: "warp0" -> "CTA6 warp0" + """ + core_cta_pattern = re.compile(r"^(.*?)\s*(Core\d+)\s+(CTA\d+)$") + + for event in events: + pid = event.get("pid", "") + tid = event.get("tid", "") + + match = core_cta_pattern.match(str(pid)) + if match: + prefix = match.group(1).strip() + core = match.group(2) + cta = match.group(3) + event["pid"] = f"{prefix} {core}" if prefix else core + event["tid"] = f"{cta} {tid}" if tid else cta + + return events + + +def _group_events_per_cta_occupancy( + events: list[dict[str, Any]], +) -> list[dict[str, Any]]: + """ + Process warp events into CTA-level events with slot assignment. + + Each CTA gets: min warp start, max warp end. + CTAs are assigned to slots per SM such that non-overlapping CTAs share slots. + """ + core_cta_pattern = re.compile(r"^(.*?)\s*(Core\d+)\s+(CTA\d+)$") + + # Group events by (prefix, SM, CTA) + cta_events: dict[tuple[str, str, str], list[dict[str, Any]]] = {} + + for event in events: + pid = event.get("pid", "") + match = core_cta_pattern.match(str(pid)) + if match: + prefix = match.group(1).strip() + core = match.group(2) + cta = match.group(3) + key = (prefix, core, cta) + if key not in cta_events: + cta_events[key] = [] + cta_events[key].append(event) + + # For each CTA, compute min start and max end + cta_intervals: dict[tuple[str, str, str], tuple[float, float]] = {} + for key, evts in cta_events.items(): + min_start = float("inf") + max_end = float("-inf") + for evt in evts: + ts = evt.get("ts", 0) + dur = evt.get("dur", 0) + min_start = min(min_start, ts) + max_end = max(max_end, ts + dur) + if min_start != float("inf"): + cta_intervals[key] = (min_start, max_end) + + # Group CTAs by (prefix, SM) and assign to slots + sm_ctas: dict[tuple[str, str], list[tuple[str, float, float]]] = {} + for (prefix, core, cta), (start, end) in cta_intervals.items(): + sm_key = (prefix, core) + if sm_key not in sm_ctas: + sm_ctas[sm_key] = [] + sm_ctas[sm_key].append((cta, start, end)) + + # Assign CTAs to slots using interval scheduling (greedy) + cta_slot_assignments: dict[tuple[str, str, str], int] = {} + for sm_key, ctas in sm_ctas.items(): + prefix, core = sm_key + sorted_ctas = sorted(ctas, key=lambda x: x[1]) + slots: list[float] = [] + for cta, start, end in sorted_ctas: + assigned_slot = None + for i, slot_end in enumerate(slots): + if start >= slot_end: + assigned_slot = i + slots[i] = end + break + if assigned_slot is None: + assigned_slot = len(slots) + slots.append(end) + cta_slot_assignments[(prefix, core, cta)] = assigned_slot + + # Build numeric ID mappings for pids and tids + # Chrome trace format requires numeric pid/tid values + pid_names: dict[str, int] = {} + tid_names: dict[tuple[int, str], int] = {} # (pid, tid_name) -> tid_num + + for key in cta_intervals: + prefix, core, cta = key + pid_name = f"{prefix} {core}" if prefix else core + if pid_name not in pid_names: + pid_names[pid_name] = len(pid_names) + + new_events: list[dict[str, Any]] = [] + + # Add process name metadata events + for pid_name, pid_num in pid_names.items(): + new_events.append( + { + "name": "process_name", + "ph": "M", + "pid": pid_num, + "args": {"name": pid_name}, + } + ) + + # Create CTA events with numeric IDs and collect tid mappings + for key, (start, end) in cta_intervals.items(): + prefix, core, cta = key + slot = cta_slot_assignments[key] + pid_name = f"{prefix} {core}" if prefix else core + tid_name = f"slot{slot}" + pid_num = pid_names[pid_name] + + if (pid_num, tid_name) not in tid_names: + tid_num = len(tid_names) + tid_names[(pid_num, tid_name)] = tid_num + # Add thread name metadata event + new_events.append( + { + "name": "thread_name", + "ph": "M", + "pid": pid_num, + "tid": tid_num, + "args": {"name": tid_name}, + } + ) + else: + tid_num = tid_names[(pid_num, tid_name)] + + new_events.append( + { + "name": cta, + "cat": "cta", + "ph": "X", + "ts": start, + "dur": end - start, + "pid": pid_num, + "tid": tid_num, + } + ) + + return new_events + + +def _apply_grouping( + events: list[dict[str, Any]], group_by_sm: bool, per_cta_occupancy: bool +) -> list[dict[str, Any]]: + """Apply grouping transformation to events.""" + if per_cta_occupancy: + return _group_events_per_cta_occupancy(events) + elif group_by_sm: + return _group_events_by_sm(events) + return events + + +def _split_events_by_invocation( + events: list[dict[str, Any]], + gap_threshold_ns: float = 1000.0, +) -> list[list[dict[str, Any]]]: + """Split events into separate invocations based on time gaps.""" + if not events: + return [] + + events_sorted = sorted(events, key=lambda e: e.get("ts", 0)) + invocations: list[list[dict[str, Any]]] = [[]] + prev_end = events_sorted[0].get("ts", 0) + + for event in events_sorted: + ts = event.get("ts", 0) + dur = event.get("dur", 0) + if ts - prev_end > gap_threshold_ns and invocations[-1]: + invocations.append([]) + invocations[-1].append(event) + prev_end = max(prev_end, ts + dur) + + return [inv for inv in invocations if inv] + + +def _normalize_timestamps( + events: list[dict[str, Any]], scale_factor: float = 1.0 +) -> list[dict[str, Any]]: + """Normalize timestamps to start at 0 and optionally scale.""" + if not events: + return events + + # Only consider duration events (ph=X) for min timestamp calculation + duration_events = [e for e in events if e.get("ph") == "X"] + if not duration_events: + return events + + min_ts = min(e.get("ts", 0) for e in duration_events) + for event in events: + if event.get("ph") == "X": + event["ts"] = (event.get("ts", 0) - min_ts) * scale_factor + if "dur" in event: + event["dur"] = event["dur"] * scale_factor + + return events + + +def process_proton_trace( + trace_path: str, + output_dir: str | None = None, + group_by_sm: bool = True, + split_invocations: bool = True, + scale_factor: float = 1.0, + gap_threshold_ns: float = 1000.0, + per_cta_occupancy: bool = True, +) -> list[str]: + """ + Process a proton trace file with various transformations. + + Always produces 1 + N files: one complete trace and N per-invocation traces. + Grouping options (group_by_sm, per_cta_occupancy) apply uniformly to all outputs. + + Args: + trace_path: Path to the input Chrome trace file + output_dir: Directory to write output files. If None, uses same directory as input. + group_by_sm: If True, group CTAs by SM into single tracks. + split_invocations: If True, also produce per-invocation trace files. + scale_factor: Factor to scale durations by (helps visibility in Perfetto). + gap_threshold_ns: Time gap (in nanoseconds) that indicates a new invocation. + per_cta_occupancy: If True, process warp tracks into CTA tracks and assign + CTAs to slots per SM such that CTAs do not overlap. + + Returns: + List of paths to the output files. + """ + if output_dir is None: + output_dir = os.path.dirname(trace_path) or "." + + os.makedirs(output_dir, exist_ok=True) + base_name = _get_base_name(trace_path) + + data = _read_trace(trace_path) + events = data.get("traceEvents", []) + + # Split into invocations first (before grouping, to avoid merging across invocations) + invocations = _split_events_by_invocation(events, gap_threshold_ns) + + # Apply grouping transformation to each invocation + invocations = [ + _apply_grouping(inv_events, group_by_sm, per_cta_occupancy) + for inv_events in invocations + ] + + output_files = [] + + # Write complete trace (dedupe metadata events) + complete_events = [] + seen_metadata: OrderedSet[tuple[str | None, int | None, int | None]] = OrderedSet() + for inv_events in invocations: + for event in inv_events: + if event.get("ph") == "M": + # Dedupe metadata events by (name, pid, tid) + key = (event.get("name"), event.get("pid"), event.get("tid")) + if key in seen_metadata: + continue + seen_metadata.add(key) + complete_events.append(event) + complete_path = os.path.join(output_dir, f"{base_name}.trace.json.gz") + _write_trace(complete_path, {"traceEvents": complete_events}) + output_files.append(complete_path) + + # Write per-invocation traces + if split_invocations: + for i, inv_events in enumerate(invocations): + inv_events = _normalize_timestamps(list(inv_events), scale_factor) + inv_path = os.path.join( + output_dir, f"{base_name}_invocation_{i}.trace.json.gz" + ) + _write_trace(inv_path, {"traceEvents": inv_events}) + output_files.append(inv_path) + + return output_files diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/runtime_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/runtime_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..64b4e6c64399661a2d748e49bb69e2ba3ae97835 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/runtime_utils.py @@ -0,0 +1,852 @@ +from __future__ import annotations + +import functools +import math +import operator +from typing import Any, TYPE_CHECKING + +import sympy + +import torch + +# NOTE: other files rely on the imports below +from torch._dynamo import callback as compilation_callback # noqa: F401 +from torch._inductor.runtime.cache_dir_utils import ( # noqa: F401 + cache_dir, + default_cache_dir, + triton_cache_dir, +) + + +if TYPE_CHECKING: + from collections.abc import Hashable + + from .triton_compat import Config + + +def conditional_product(*args: int) -> int: + return functools.reduce(operator.mul, [x for x in args if x]) + + +def ceildiv(number: int, denom: int) -> int: + return -(number // -denom) + + +def is_power_of_2(n: int) -> bool: + """Returns whether n = 2 ** m for some integer m.""" + return n > 0 and n & n - 1 == 0 + + +def next_power_of_2(n: int) -> int: + """Return the smallest power of 2 greater than or equal to n""" + if isinstance(n, sympy.Integer): + n = int(n) + if n <= 0: + return 1 + return 1 << (n - 1).bit_length() + + +def last_power_of_2(n: int) -> int: + """Return the largest power of 2 less than or equal to n""" + next_pow2 = next_power_of_2(n) + return next_pow2 // 2 if next_pow2 > n else next_pow2 + + +def get_num_bytes(*args: torch.Tensor, num_in_out_args: int = 0) -> int: + """ + Return the total number of bytes the arguments of tensor type takes. + + For in/out args, tensor sizes are counted twice: once for reading and + once for writing. + + The first num_in_out_args arguments are in out tensors. + """ + return sum( + arg.numel() * arg.element_size() * (1 + int(i < num_in_out_args)) + for i, arg in enumerate(args) + if isinstance(arg, torch.Tensor) + ) + + +def triton_config_to_hashable(cfg: Config) -> Hashable: + """ + Convert triton config to a tuple that can uniquely identify it. We can use + the return value as a dictionary key. + """ + # pyrefly: ignore [missing-attribute] + items = sorted(cfg.kwargs.items()) + # pyrefly: ignore [missing-attribute] + items.append(("num_warps", cfg.num_warps)) + # pyrefly: ignore [missing-attribute] + items.append(("num_stages", cfg.num_stages)) + return tuple(items) + + +def validate_triton_config(cfg: Config) -> None: + # [Note: Triton pre_hook in inductor] + # pre-hook is a lambda function, which we don't attempt to serialize. + # right now, if a pre-hook is attached to the config, it will not be saved; + # and then it won't be used when the config is loaded from cache. + # So we assert - if we do get a pre_hook, it might get ignored after caching. + if getattr(cfg, "pre_hook", None) is not None: + raise AssertionError("triton configs with pre_hooks not supported") + + +def assert_tensor_metadata( + tensor: torch.Tensor | None, + expected_size: tuple[Any, ...], + expected_stride: tuple[Any, ...], + expected_dtype: torch.dtype, + op_name: str | None = None, +) -> None: + if tensor is None: + return + if tensor.dtype != expected_dtype: + op_msg = f"\nError in op: {op_name}" if op_name else "" + raise RuntimeError( + f"expected dtype {expected_dtype} but got {tensor.dtype}" + + op_msg + + "\nThis error most often comes from an incorrect fake (aka meta) " + "kernel for a custom op." + "\nUse torch.library.opcheck to test your custom op." + "\nSee https://pytorch.org/docs/stable/library.html#torch.library.opcheck" + ) + torch._C._dynamo.guards.assert_size_stride( + tensor, expected_size, expected_stride, op_name + ) + + +def create_bandwidth_info_str( + ms: float, + num_gb: float, + gb_per_s: float, + prefix: str = "", + suffix: str = "", + color: bool = True, +) -> str: + info_str = f"{prefix}{ms:.3f}ms \t{num_gb:.3f} GB \t {gb_per_s:7.2f}GB/s{suffix}" + slow = ms > 0.012 and gb_per_s < 650 + return red_text(info_str) if color and slow else info_str + + +def get_max_y_grid() -> int: + return 65535 + + +try: + import colorama + + HAS_COLORAMA = True +except ModuleNotFoundError: + HAS_COLORAMA = False + colorama = None # type: ignore[assignment] + + +if HAS_COLORAMA: + + def _color_text(msg: str, color: str) -> str: + # pyrefly: ignore [missing-attribute] + return getattr(colorama.Fore, color.upper()) + msg + colorama.Fore.RESET + +else: + + def _color_text(msg: str, color: str) -> str: + return msg + + +def green_text(msg: str) -> str: + return _color_text(msg, "green") + + +def yellow_text(msg: str) -> str: + return _color_text(msg, "yellow") + + +def red_text(msg: str) -> str: + return _color_text(msg, "red") + + +def blue_text(msg: str) -> str: + return _color_text(msg, "blue") + + +def get_first_attr(obj: Any, *attrs: str) -> Any: + """ + Return the first available attribute or throw an exception if none is present. + """ + for attr in attrs: + if hasattr(obj, attr): + return getattr(obj, attr) + + raise AssertionError(f"{obj} does not has any of the attributes: {attrs}") + + +dynamo_timed = torch._dynamo.utils.dynamo_timed # type: ignore[has-type] + + +def triton_hash_to_path_key(key: str) -> str: + # In early versions of Triton, the hash is directly used in the path name. + # Later, the hash is converted to base64 before being used in the path name. + # Later, the base64 conversion was replaced to the base32 + # + # This code tries to import _base64 and falls back to _base32 if _base64 is unavailable. + # + # To handle this, try to import the to-base64-conversion function. + # If it exists, use it; otherwise, try using _base32; if both are unavailable, use the hash directly. + try: + from triton.runtime.cache import _base64 + + return _base64(key) + except Exception: + try: + from triton.runtime.cache import _base32 + + return _base32(key) + except Exception: + return key + + +def compile_mps_shader(source: str) -> Any: + """ + Compiles shader source but raise more actionable error message when needed + """ + try: + return torch.mps.compile_shader(source) + except SyntaxError as err: + raise SyntaxError(f"failed to compile {source} with {err.msg}") from err + + +def compile_mps_shaders( + kernels: list[tuple[str, str, list[str]]], +) -> dict[str, Any]: + """Compile a batch of Metal kernels into one library. + + Args: + kernels: list of (kernel_name, metal_source, headers) tuples. + headers are bare names resolved as . + + Returns: + dict mapping each kernel_name to its compiled function handle. + """ + from torch.utils._ordered_set import OrderedSet + + all_headers = sorted(OrderedSet(h for _, _, hs in kernels for h in hs)) + header_src = "\n".join(f"#include " for h in all_headers) + body_src = "\n".join(src for _, src, _ in kernels) + lib = compile_mps_shader(header_src + "\n" + body_src) + return {name: getattr(lib, name) for name, _, _ in kernels} + + +def torch_dtype_to_jax_runtime(dtype: torch.dtype) -> Any: + """ + Map PyTorch dtype to actual JAX dtype object at runtime. + + This helper is used in generated Pallas kernels at runtime to convert + PyTorch dtypes to JAX dtype objects (not string representations). + + Args: + dtype: PyTorch dtype to convert + + Returns: + JAX dtype object (e.g., jnp.float32 object itself) + """ + import jax.numpy as jnp # pyrefly: ignore [import-error, missing-import] + + dtype_map = { + torch.float32: jnp.float32, + torch.float64: jnp.float64, + torch.float16: jnp.float16, + torch.bfloat16: jnp.bfloat16, + torch.int32: jnp.int32, + torch.int64: jnp.int64, + torch.int16: jnp.int16, + torch.int8: jnp.int8, + torch.uint8: jnp.uint8, + torch.bool: jnp.bool_, + torch.complex64: jnp.complex64, + torch.complex128: jnp.complex128, + } + if dtype not in dtype_map: + raise ValueError(f"Unsupported dtype for JAX conversion: {dtype}") + return dtype_map[dtype] + + +def torch_dtype_to_jax(dtype: torch.dtype) -> str: + """ + Map PyTorch dtype to JAX dtype expression string. + + This helper is used at compile time in codegen to generate + JAX dtype expressions for Pallas kernels. + + Args: + dtype: PyTorch dtype to convert + + Returns: + JAX dtype expression as string (e.g., "jnp.float32") + """ + jax_dtype = torch_dtype_to_jax_runtime(dtype) + dtype_name = jax_dtype.__name__ + if dtype_name == "bool": + dtype_name = "bool_" + return f"jnp.{dtype_name}" + + +def pallas_gpu_pad_inputs(inputs: list[Any], alignment: int = 128) -> list[Any]: + """Flatten and pad each input JAX array to a multiple of alignment.""" + import jax.numpy as jnp # pyrefly: ignore [import-error, missing-import] + + padded = [] + for inp in inputs: + flat = inp.flatten() + orig_size = flat.size + aligned_size = ((orig_size + alignment - 1) // alignment) * alignment + if orig_size != aligned_size: + padded.append(jnp.pad(flat, (0, aligned_size - orig_size))) + else: + padded.append(flat) + return padded + + +def pallas_gpu_align_output_specs( + out_shapes: tuple[Any, ...], + out_dtypes: tuple[Any, ...], + alignment: int = 128, +) -> tuple[tuple[Any, ...], list[bool]]: + """Build aligned output ShapeDtypeStruct specs for GPU kernels. + + Returns (aligned_specs, is_scalar_output) where is_scalar_output[i] is True + when the i-th output is scalar and should not be padded/unpadded. + """ + import jax # pyrefly: ignore [import-error, missing-import] + + aligned_specs = [] + is_scalar = [] + for shape, dtype in zip(out_shapes, out_dtypes): + numel = math.prod(shape) + if numel <= 1: + aligned_specs.append(jax.ShapeDtypeStruct(shape, dtype)) + is_scalar.append(True) + else: + aligned_numel = ((numel + alignment - 1) // alignment) * alignment + aligned_specs.append(jax.ShapeDtypeStruct((aligned_numel,), dtype)) + is_scalar.append(False) + return tuple(aligned_specs), is_scalar + + +def pallas_gpu_unpad_results( + results: Any, + orig_shapes: tuple[Any, ...], + is_scalar_output: list[bool] | None = None, +) -> Any: + """Remove padding from GPU kernel results and reshape to original shapes. + + If is_scalar_output is None, all outputs are treated as non-scalar. + """ + if not isinstance(results, tuple): + results = (results,) + unpadded = [] + for i, (res, shape) in enumerate(zip(results, orig_shapes)): + if is_scalar_output is not None and is_scalar_output[i]: + unpadded.append(res) + else: + orig_numel = math.prod(shape) + unpadded.append(res[:orig_numel].reshape(shape)) + return unpadded[0] if len(unpadded) == 1 else tuple(unpadded) + + +# --------------------------------------------------------------------------- +# Pallas CPU / TPU tiling helpers +# --------------------------------------------------------------------------- +# TPU alignment: last dim must be full or a multiple of 128, +# second-to-last dim must be full or a multiple of 8. +_TPU_ALIGN_LAST = 128 +_TPU_ALIGN_SECOND_LAST = 8 + + +def _pallas_tile_size( + dim: int, alignment: int, max_tile: int = 1024, is_tpu: bool = False +) -> int: + """Pick the largest aligned tile size <= max_tile for *dim*. + + If *dim* is already <= alignment the full dimension is used (no tiling + on this axis). + """ + if dim == 0: + # Tile size >= 1 avoids division by zero in JAX's _pad_to_block_dimension + return alignment if is_tpu else 1 + + if is_tpu: + # On TPU, Mosaic requires block dimensions to perfectly align to hardware + # registers (128 for inner, 8 for outer). We MUST pad the block spec up to + # the next alignment boundary (Mosaic handles the OOB masking). + if dim <= alignment: + return alignment + t = min(max_tile, dim) + # Use ceiling division to ensure the tile covers the dimension or aligns upward + t = ((t + alignment - 1) // alignment) * alignment + return t + + if dim <= alignment: + return dim + t = min(max_tile, dim) + t = (t // alignment) * alignment + return max(alignment, t) + + +def pallas_permute(x, perm): + """Permute array x according to perm, working around Mosaic TPU bugs. + + Mosaic's jnp.permute_dims produces corrupted output for certain 3D+ + permutations at large sizes. Decomposes into: loop over smallest output + dim via unrolled Python loop + stack, with recursive sub-permutation. + At the 2D base case, uses jnp.permute_dims (which works on Mosaic). + + Callers should ensure tiles are small enough via tiling so that the + Mosaic bug doesn't trigger (threshold ~ 256K elements). + """ + import jax.numpy as jnp # pyrefly: ignore [import-error, missing-import] + + ndim = len(perm) + if ndim <= 2: + return jnp.permute_dims(x, perm) + if perm == tuple(range(ndim)): + return x # identity + + shape = x.shape + out_shape = tuple(shape[p] for p in perm) + + # Choose the output dimension with the smallest size to loop over. + loop_out_dim = min(range(ndim), key=lambda d: out_shape[d]) + loop_size = out_shape[loop_out_dim] + loop_in_dim = perm[loop_out_dim] + + # Build the sub-permutation for the remaining (ndim-1) dimensions. + remaining_in_dims = [d for d in range(ndim) if d != loop_in_dim] + remaining_out_perm_raw = [perm[d] for d in range(ndim) if d != loop_out_dim] + dim_map = {old: new for new, old in enumerate(remaining_in_dims)} + sub_perm = tuple(dim_map[d] for d in remaining_out_perm_raw) + + # Unrolled loop: extract slices with static indices, apply sub-perm, + # then stack along the loop output dimension. + slices = [] + # pyrefly: ignore [bad-argument-type] + for i in range(loop_size): + idx: list[Any] = [slice(None)] * ndim + idx[loop_in_dim] = i + slc = x[tuple(idx)] # static index, removes loop_in_dim + slc_p = pallas_permute(slc, sub_perm) + slices.append(slc_p) + + return jnp.stack(slices, axis=loop_out_dim) + + +# Maximum tile elements for permutation kernels. Mosaic's +# jnp.permute_dims produces corrupted output above ~1.5M elements for +# certain 3D+ permutations. Keep tiles well under that threshold. +_PERMUTE_MAX_TILE_ELEMS = 1 << 18 # ~256K elements + + +def pallas_compute_tiling( + ref_shape: tuple[int, ...], + transpose: bool = False, # constrain tile size for pallas_permute VMEM + skip_last_n: int = 0, + exact_only: bool = False, + is_tpu: bool = False, + permutations: list[tuple[int, ...]] | None = None, + max_grid_product: int | None = None, +) -> tuple[tuple[int, ...], tuple[int, ...], dict[int, int]]: + """Compute tile shape, grid and axis→grid-dim mapping for CPU/TPU. + + Always uses TPU-compatible alignment (last dim multiple of 128, + second-to-last multiple of 8) so that the same generated kernel works + on both CPU-interpret and real TPU. + + *transpose* constrains tile sizes to keep VMEM usage within safe + limits for pallas_permute (gather-based permutation). + + *skip_last_n* prevents tiling the last N dimensions (used when those + dims correspond to internal reduction ranges that must remain full). + + *exact_only* restricts tiling to dimensions that divide evenly by the + tile size (no remainder blocks). Required on TPU where Mosaic needs + block shapes to match the XLA memory layout. + + Returns ``(tile_shape, grid, axis_to_grid)`` where *axis_to_grid* + maps each tiled reference-shape axis index to its position in the + grid tuple. + + When no dimension benefits from tiling the grid is ``(1,)`` and the + tile covers the full tensor. + """ + nd = len(ref_shape) + if nd == 0: + return (), (1,), {} + + # Effective number of dims eligible for tiling + tileable_nd = nd - skip_last_n + + tile = list(ref_shape) + grid_parts: list[int] = [] + axis_to_grid: dict[int, int] = {} # ref axis → grid dim + + # Pick alignment based on the physical position of the axis in the + # tensor, not its position in the tileable subset. The TPU requires + # the physical last dim to be a multiple of 128 and the physical + # second-to-last dim to be a multiple of 8. + # + # When permutations are present, an output dim `ax` maps to input + # dim `perm[ax]`. If `perm[ax]` is the input's last dim, that + # output dim must also satisfy _TPU_ALIGN_LAST. Compute the + # strictest alignment across all buffers. + def _input_align(input_ax: int, input_nd: int) -> int: + return _TPU_ALIGN_LAST if input_ax == input_nd - 1 else _TPU_ALIGN_SECOND_LAST + + def _align(ax: int) -> int: + out_align = _TPU_ALIGN_LAST if ax == nd - 1 else _TPU_ALIGN_SECOND_LAST + if permutations: + for perm in permutations: + if perm is not None and len(perm) == nd: + in_ax = perm[ax] + in_align = _input_align(in_ax, len(perm)) + out_align = max(out_align, in_align) + return out_align + + def _can_tile_ax(ax: int, dim: int, t: int) -> bool: + """Check if tiling dim to t is valid.""" + if t >= dim: + # For TPU padding, we allow tiles >= dimension for the aligned axes + if _align(ax) == _TPU_ALIGN_LAST or _align(ax) == _TPU_ALIGN_SECOND_LAST: + return True + return False + if exact_only and dim % t != 0: + if _align(ax) == _TPU_ALIGN_LAST or _align(ax) == _TPU_ALIGN_SECOND_LAST: + # TPU DMA `#tpu.element_window` natively masks out-of-bounds remainder tiles + return True + return False + return True + + # Second-to-last tileable dim (added first so it becomes grid dim 0) + if tileable_nd >= 2: + ax = tileable_nd - 2 + t = _pallas_tile_size(ref_shape[ax], _align(ax), is_tpu=is_tpu) + if _can_tile_ax(ax, ref_shape[ax], t): + tile[ax] = t + axis_to_grid[ax] = len(grid_parts) + grid_parts.append((ref_shape[ax] + t - 1) // t) + + # Last tileable dim + if tileable_nd >= 1: + ax = tileable_nd - 1 + t = _pallas_tile_size(ref_shape[ax], _align(ax), is_tpu=is_tpu) + if _can_tile_ax(ax, ref_shape[ax], t): + tile[ax] = t + axis_to_grid[ax] = len(grid_parts) + grid_parts.append((ref_shape[ax] + t - 1) // t) + + # When transpose is active, tile dimensions to keep the total tile + # elements below the safe threshold for Mosaic's permute_dims. + # Mosaic pads the last dimension to _TPU_ALIGN_LAST (128 for f32), + # so when the last dim is small (e.g. 2), VMEM usage is much higher + # than the logical tile size. We compute an effective element count + # that accounts for this padding. + if transpose: + tile_elems = 1 + for t in tile: + tile_elems *= t + last_dim = tile[nd - 1] if nd > 0 else 1 + padded_last = max(last_dim, _TPU_ALIGN_LAST) + # pallas_permute decomposes ndim>2 permutations by looping over + # the smallest dim and recursing, creating (ndim-1)-D intermediates + # at each level. Mosaic pads the last physical dim of each + # intermediate to _TPU_ALIGN_LAST (128), which can cause VMEM OOM + # when a small dim (e.g. 4) ends up as the last dim. + # + # For ndim >= 3, compute effective_max from the worst-case VMEM + # of the (ndim-1)-D intermediate created by pallas_permute. + # The intermediate removes the loop dim (smallest output dim) and + # may have a small dim as its last physical dim -> padded to 128. + if nd >= 4: + # For 4D+, pallas_permute creates (nd-1)-D intermediates + # that can have small dims as their last physical dim, + # which Mosaic pads to _TPU_ALIGN_LAST (128). This can + # cause VMEM OOM. (3D pallas_permute only creates 2D + # intermediates which Mosaic handles efficiently.) + sorted_dims = sorted(tile) + # The loop dim is the smallest; intermediate has the rest. + inter_dims = sorted_dims[1:] # (nd-1) dims, sorted + smallest_inter = inter_dims[0] + # Padded intermediate: smallest remaining dim padded to 128. + padded_inter_elems = 1 + for d in inter_dims: + padded_inter_elems *= d + pad_factor = max(smallest_inter, _TPU_ALIGN_LAST) // max(smallest_inter, 1) + padded_inter_elems *= pad_factor + padded_inter_bytes = padded_inter_elems * 4 + # Conservative VMEM budget: 2MB per intermediate buffer. + # pallas_permute creates multiple live intermediates (input + # slices, sub-permutation results, stack temps). Empirically, + # 2MB per worst-case intermediate avoids OOM on TPU v4 (64MB VMEM). + vmem_per_buf = 2 * 1024 * 1024 # 2MB + if padded_inter_bytes > vmem_per_buf: + scale = vmem_per_buf / padded_inter_bytes + effective_max = max(int(tile_elems * scale), 1024) + else: + effective_max = _PERMUTE_MAX_TILE_ELEMS + else: + # For ndim <= 3: pallas_permute creates 2D intermediates + # (fine) but jnp.stack creates a 3D result with the same + # shape as the output. If the last dim is small, Mosaic + # pads it to _TPU_ALIGN_LAST (128), which can exhaust VMEM. + # Empirically: 8MB per padded buffer keeps us safe on TPU v4 + # (64MB VMEM, multiple buffers live simultaneously). + vmem_per_buf = 8 * 1024 * 1024 # 8MB + max_nonlast_product = vmem_per_buf // (padded_last * 4) + effective_max = min( + max_nonlast_product * last_dim, + _PERMUTE_MAX_TILE_ELEMS, + ) + effective_max = min(effective_max, _PERMUTE_MAX_TILE_ELEMS) + effective_max = max(effective_max, 1024) + + if tile_elems > effective_max: + # Collect tileable dims. For ndim >= 4 with VMEM-constrained + # intermediates, include ALL tileable dims (even the last) + # since we may need to shrink every dim to fit in VMEM. + # For ndim <= 3, exclude the last dim (it's often small + # and already at minimum). + if nd >= 4: + tileable_axes = [ + ax for ax in range(tileable_nd - 1, -1, -1) if ref_shape[ax] > 1 + ] + else: + tileable_axes = [ + ax for ax in range(tileable_nd - 2, -1, -1) if ref_shape[ax] > 1 + ] + # Distribute reduction proportionally across dims. + reduction = tile_elems / effective_max + n = len(tileable_axes) + per_dim = reduction ** (1.0 / max(n, 1)) + + for ax in tileable_axes: + if tile_elems <= effective_max: + break + dim = ref_shape[ax] + cur_t = tile[ax] + align = _align(ax) + # Target tile: proportional reduction, but also check + # against the remaining budget for subsequent dims. + target = int(cur_t / per_dim) + remaining_budget = effective_max * cur_t // tile_elems + target = min(target, remaining_budget) + target = (target // align) * align + target = max(target, align) + # Find largest aligned divisor of dim <= target. + best_t = cur_t + for candidate in range(target, 0, -align): + if candidate >= cur_t: + continue + if dim % candidate != 0: + continue + best_t = candidate + break + if best_t < cur_t: + if ax in axis_to_grid: + grid_parts[axis_to_grid[ax]] = dim // best_t + else: + axis_to_grid[ax] = len(grid_parts) + grid_parts.append(dim // best_t) + tile_elems = tile_elems * best_t // cur_t + tile[ax] = best_t + + grid = tuple(grid_parts) if grid_parts else (1,) + + # Enforce max_grid_product by scaling up tiles on tiled axes. + if max_grid_product is not None and grid_parts: + grid_product = 1 + for g in grid_parts: + grid_product *= g + if grid_product > max_grid_product: + # Sort tiled axes by their grid contribution (descending) + # and increase tiles to reduce the grid. + tiled_axes = sorted( + axis_to_grid.keys(), + key=lambda ax: grid_parts[axis_to_grid[ax]], + reverse=True, + ) + for ax in tiled_axes: + if grid_product <= max_grid_product: + break + gi = axis_to_grid[ax] + cur_grid = grid_parts[gi] + cur_tile = tile[ax] + dim = ref_shape[ax] + align = _align(ax) + # Target grid for this axis: proportional share of reduction + target_grid = max(1, int(cur_grid * max_grid_product / grid_product)) + target_tile = (dim + target_grid - 1) // target_grid + # Round up to alignment + target_tile = ((target_tile + align - 1) // align) * align + target_tile = min(target_tile, dim) + # Find smallest aligned value >= target_tile that divides dim + # (or just use the rounded-up value if exact_only is False) + best_tile = dim # fallback: full dim + if exact_only: + for candidate in range(target_tile, dim + 1, align): + if dim % candidate == 0: + best_tile = candidate + break + else: + best_tile = target_tile + if best_tile > cur_tile: + new_grid = (dim + best_tile - 1) // best_tile + grid_product = grid_product * new_grid // cur_grid + grid_parts[gi] = new_grid + tile[ax] = best_tile + grid = tuple(grid_parts) + + return tuple(tile), grid, axis_to_grid + + +def pallas_make_block_spec( + buf_shape: tuple[int, ...], + ref_shape: tuple[int, ...], + tile_shape: tuple[int, ...], + axis_to_grid: dict[int, int], + n_grid: int, + permutation: tuple[int, ...] | None = None, + is_output: bool = False, +) -> Any: + """Build a ``pl.BlockSpec`` for *buf_shape* given tiling of *ref_shape*. + + Lower-ndim buffers are right-aligned with the reference shape (numpy + broadcast rules). Dimensions that match a tiled reference dimension + are tiled; broadcast dimensions (size 1 or absent) are kept full. + + When *buf_nd > ref_nd* (reduction inputs), we find an alignment offset + so the ref dims map into the buffer. Extra dims are kept at full size + with index 0 in the index_map. + + When *permutation* is given (a tuple mapping ref axis -> buf axis), + the buffer dimensions are accessed in permuted order relative to the + reference shape. For example, permutation=(1, 0) swaps the last two. + + When *is_output* is True and *buf_nd < ref_nd*, left-alignment is used + as a fallback (for reduction outputs whose trailing dims were reduced). + """ + from jax.experimental import ( # pyrefly: ignore [import-error, missing-import] + pallas as pl, + ) + + buf_nd = len(buf_shape) + ref_nd = len(ref_shape) + + if buf_nd == 0: + # Scalar — untouched regardless of grid shape. + return pl.BlockSpec((1,), _make_index_map([], 1, n_grid)) + + bs = list(buf_shape) + tiled_pairs: list[tuple[int, int]] = [] + + if buf_nd > ref_nd: + # Reduction input: find alignment offset k where ref dims map into buf. + align_k = 0 + for k in range(buf_nd - ref_nd + 1): + ok = True + for i in range(ref_nd): + if ref_shape[i] == 1: + continue + if buf_shape[k + i] != ref_shape[i]: + ok = False + break + if ok: + align_k = k + break + + for ref_ax, grid_dim in axis_to_grid.items(): + buf_ax = align_k + ref_ax + if 0 <= buf_ax < buf_nd and buf_shape[buf_ax] == ref_shape[ref_ax]: + bs[buf_ax] = tile_shape[ref_ax] + tiled_pairs.append((buf_ax, grid_dim)) + + elif permutation is not None and buf_nd == ref_nd: + # Permuted buffer: map ref axes through the permutation. + for ref_ax, grid_dim in axis_to_grid.items(): + buf_ax = permutation[ref_ax] + if 0 <= buf_ax < buf_nd and buf_shape[buf_ax] == ref_shape[ref_ax]: + bs[buf_ax] = tile_shape[ref_ax] + tiled_pairs.append((buf_ax, grid_dim)) + + else: + # Standard right-alignment, with left-alignment fallback for + # reduction outputs (e.g. sum(dim=-1) on (10,10) → (10,)). + for ref_ax, grid_dim in axis_to_grid.items(): + buf_ax = ref_ax - (ref_nd - buf_nd) + if 0 <= buf_ax < buf_nd and buf_shape[buf_ax] == ref_shape[ref_ax]: + bs[buf_ax] = tile_shape[ref_ax] + tiled_pairs.append((buf_ax, grid_dim)) + elif ( + is_output + and buf_nd < ref_nd + and 0 <= ref_ax < buf_nd + and buf_shape[ref_ax] == ref_shape[ref_ax] + ): + # Left-aligned match for output: buf dim i matches ref dim i + # (reduction output whose trailing dims were reduced away) + bs[ref_ax] = tile_shape[ref_ax] + tiled_pairs.append((ref_ax, grid_dim)) + + return pl.BlockSpec( + tuple(bs), + _make_index_map(tiled_pairs, buf_nd, n_grid), + ) + + +def _make_index_map( + tiled_pairs: list[tuple[int, int]], + buf_nd: int, + n_grid: int, +) -> Any: + """Return an index_map callable for ``pl.BlockSpec``. + + *tiled_pairs* is a list of ``(buf_axis, grid_dim)`` indicating which + buffer axes receive a grid index. All other axes return 0 (full block). + + All returned values are explicitly ``jnp.int32`` so that TPU Mosaic + lowering (which rejects 64-bit types) works when ``jax_enable_x64`` is + active. The casts are created inside the function body (not captured) + to satisfy JAX's "index_map must not capture constants" rule. + """ + import jax.numpy as jnp # pyrefly: ignore [import-error, missing-import] + + # Pre-build the mapping so the returned lambda is a plain lookup. + mapping = dict(tiled_pairs) + + if n_grid == 0 or (n_grid == 1 and not mapping): + return lambda _i: tuple(jnp.int32(0) for _ in range(buf_nd)) + + def index_map(*grid_args): + return tuple( + jnp.int32(grid_args[mapping[d]]) if d in mapping else jnp.int32(0) + for d in range(buf_nd) + ) + + return index_map + + +def pallas_ensure_nonzero_rank(x: torch.Tensor) -> torch.Tensor: + if len(x.shape) == 0: + return x.reshape((1,)) + return x + + +def pallas_make_block_spec_non_tiled(shape: tuple[int, ...]) -> Any: + import jax.numpy as jnp # pyrefly: ignore [import-error, missing-import] + from jax.experimental import ( # pyrefly: ignore [import-error, missing-import] + pallas as pl, + ) + + nonzero_rank_shape = shape if len(shape) > 0 else (1,) + return pl.BlockSpec( + nonzero_rank_shape, + lambda i: [jnp.int32(i)] * len(nonzero_rank_shape), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/static_triton_launcher.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/static_triton_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..472511f625eda5dc1d4047eee379057118b5c7d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/static_triton_launcher.py @@ -0,0 +1,552 @@ +import functools +import os +from functools import cached_property +from typing import Any +from typing_extensions import Unpack + +from ..utils import is_rocm +from .triton_compat import ASTSource, CompiledKernel, knobs as triton_knobs +from .triton_helpers import get_constexprs + + +@functools.lru_cache(None) +def _tma_arg_helpers(): + """Cached (make_arg, TensorDescriptor) for host-side TMA arg expansion. + make_arg(arg, metadata) -> [CUtensorMap, *shape, *strides]; the nvidia + backend's make_tensordesc_arg ignores its third arg, so we pass None.""" + from triton.backends.nvidia.driver import make_tensordesc_arg + from triton.tools.tensor_descriptor import TensorDescriptor + + def make_arg(arg, metadata): + return make_tensordesc_arg(arg, metadata, None) + + return make_arg, TensorDescriptor + + +class StaticallyLaunchedTritonKernel: + """ + Parses the metadata of a CompiledKernel from Triton into a structure that can + launch the cuda kernel directly. Only works for triton kernels compiled to cubin. + + Doing this avoids C++ codegen and compilation during compile, since we can use a + statically compiled library to launch the kernel. To avoid mallocing for the arguments, + we have a launcher for different numbers of arguments up to a max. StaticCudaLauncher + only supports # of arguments up until 10 for now. + + Workflow: + Compile time: + 1. Compile a kernel with triton and get a CompiledKernel + 2. Instantiate kernel = StaticallyLaunchedTritonKernel(triton_kernel) + 3. Write to a cubin file: kernel.write_cubin_to_file(filepath) + 4. Call kernel.load_kernel() (CUDA should be initialized by this point) to load the cubin + Runtime: + 5. Call kernel.run(grid, stream, args) to launch the kernel + + Note that after step 3, StaticallyLaunchedTritonKernel is fully pickleable/serializable. + This allows it to be cached by FXGraphCache/TritonBundler, as well as sent from the worker + to the parent process in inductor. + + There are two main versions of triton that we wish to support: 3.3 and 3.2. Triton makes considerable changes + to how it handles constants in 3.3, so there's some special logic necessary to handle both versions. + """ + + @cached_property + def C_impl(self): + raise NotImplementedError + + def __init__(self, kernel: CompiledKernel) -> None: + # pyrefly: ignore [missing-attribute] + self.name = kernel.src.fn.__name__ + # pyrefly: ignore [missing-attribute] + self.cubin_path = kernel._cubin_path + + # Used by torch.compile to filter constants in older triton versions + # pyrefly: ignore [missing-attribute] + self.arg_names = kernel.src.fn.arg_names + + # Const exprs that are declared by the triton kernel directly + # Used to generate the kernel launcher's def args + # pyrefly: ignore [missing-attribute] + self.declared_constexprs = get_constexprs(kernel.src.fn) + + # pyrefly: ignore [missing-attribute] + self.hash = kernel.hash + + if triton_knobs is None: + # pyrefly: ignore [missing-attribute] + launch_enter = kernel.__class__.launch_enter_hook + # pyrefly: ignore [missing-attribute] + launch_exit = kernel.__class__.launch_exit_hook + else: + launch_enter = triton_knobs.runtime.launch_enter_hook + launch_exit = triton_knobs.runtime.launch_exit_hook + + def hook_is_empty(hook: Any) -> bool: + if hook is None: + return True + if ( + triton_knobs + and (HookChain := getattr(triton_knobs, "HookChain", None)) is not None + and isinstance(hook, HookChain) + ): + # Support hooks after https://github.com/triton-lang/triton/pull/7866 + return len(hook.calls) == 0 + return False + + if not hook_is_empty(launch_enter) or not hook_is_empty(launch_exit): + raise NotImplementedError( + "We don't support launch enter or launch exit hooks" + ) + # pyrefly: ignore [missing-attribute] + self.num_warps = kernel.metadata.num_warps + self.shared = ( + # pyrefly: ignore [missing-attribute] + kernel.shared if hasattr(kernel, "shared") else kernel.metadata.shared + ) + + def needs_scratch_arg(scratch_name: str, param_name: str) -> bool: + # pyrefly: ignore [missing-attribute] + if hasattr(kernel.metadata, param_name): + # pyrefly: ignore [missing-attribute] + if getattr(kernel.metadata, param_name) > 0: + raise NotImplementedError( + f"{scratch_name} scratch not yet supported" + ) + return True + return False + + # Newer triton versions pass an extra global scratch parameter to the compiled cuda kernel. + # Inductor never uses this field or enables it, but we still have to pass + # an extra None into the set of params if its enabled + self.has_global_scratch = needs_scratch_arg("Global", "global_scratch_size") + # same situation for profile scratch - triton-lang/triton#7258 + self.has_profile_scratch = needs_scratch_arg("Profile", "profile_scratch_size") + + # pyrefly: ignore [missing-attribute] + self.tensordesc_meta = getattr(kernel.metadata, "tensordesc_meta", None) + self._has_tensordesc = False + # pyrefly: ignore [missing-attribute] + self.arg_tys = self.arg_ty_from_signature(kernel.src) + self.function: int | None = None # Loaded by load_kernel(on the parent process) + self.module: int | None = None # Owns the HIP/CUDA module loaded for function + # compile-on-one-rank: a device-agnostic kernel (no baked device index) can be + # launched on more than one device within a single process. A loaded module/ + # function is bound to a single device, so when device_agnostic is set we keep + # them per device and resolve the current device at launch time. The cubin + # (device-agnostic) is retained so it can be loaded onto additional devices. + # These per-device dicts assume one thread per device for a given launcher (the + # single-process multi-device path is sequential in practice); concurrent + # first-launch on two new devices would need external locking. + self.device_agnostic: bool = False + self.functions: dict[int, int] = {} + self.modules: dict[int, int] = {} + num_ctas = 1 + if hasattr(kernel, "num_ctas"): + num_ctas = kernel.num_ctas + elif hasattr(kernel, "metadata"): + num_ctas = kernel.metadata.num_ctas + + if num_ctas != 1: + raise NotImplementedError( + "Static cuda launcher only supports num_ctas == 1" + ) + + def reload_cubin_from_raw(self, filepath: str) -> str: + """ + If the cubin file triton generated gets deleted under us, we can + reload it from the raw cubin file. + """ + if self.cubin_path is None: + if self.cubin_raw is None: + raise AssertionError("cubin_raw must be set when cubin_path is None") + os.makedirs(os.path.dirname(filepath), exist_ok=True) + with open(filepath, "wb") as f: + f.write(self.cubin_raw) + self.cubin_path = filepath # pyre-ignore + return self.cubin_path + + def _agnostic_cubin_path(self) -> str: + # The cubin bytes are device-agnostic, so the same file loads onto any device. + # Keep it available (the single-device path frees it after one load) and rewrite + # from the retained raw bytes if the file was removed under us. + if self.cubin_path is not None and os.path.exists(self.cubin_path): + return self.cubin_path + if self.cubin_raw is None or self.cubin_path is None: + raise AssertionError( + "device-agnostic kernel cannot reload its cubin for a new device" + ) + os.makedirs(os.path.dirname(self.cubin_path), exist_ok=True) + with open(self.cubin_path, "wb") as f: + f.write(self.cubin_raw) + return self.cubin_path + + def load_kernel(self, device: int) -> None: + if self.device_agnostic: + if device in self.functions: + return + (module, function, self.n_regs, self.n_spills) = self.C_impl._load_kernel( + self._agnostic_cubin_path(), self.name, self.shared, device + ) + self.modules[device] = module + self.functions[device] = function + return + + if self.function is not None: + return + + if not hasattr(self, "cubin_path"): + raise AssertionError("cubin_path attribute not set before load_kernel") + if self.cubin_path is None: + raise AssertionError("cubin_path must not be None before load_kernel") + (self.module, self.function, self.n_regs, self.n_spills) = ( + self.C_impl._load_kernel(self.cubin_path, self.name, self.shared, device) + ) + # Don't need the cubin path anymore now that we've loaded + self.cubin_path = None + self.cubin_raw = None + + def _current_device(self) -> int: + raise NotImplementedError + + def close(self) -> None: + # Clear Python-visible handles first so repeated cleanup is harmless even if + # the driver reports an error while unloading. + modules = list(self.modules.values()) + if self.module is not None: + modules.append(self.module) + self.module = None + self.function = None + self.modules = {} + self.functions = {} + for mod in modules: + self.C_impl._unload_kernel(mod) + + def __del__(self) -> None: + try: + self.close() + except Exception: + pass + + @staticmethod + @functools.lru_cache + def type_mappings() -> dict[str, str]: + return { + "i1": "i", + "i8": "b", + "i16": "h", + "i32": "i", + "i64": "l", + "u1": "I", + "u8": "B", + "u16": "H", + "u32": "I", + "u64": "K", + "fp16": "f", + "bf16": "f", + "fp32": "f", + "f32": "f", + "fp64": "d", + # TODO handle nvTmaDesc/CUtensormap + } + + def extract_type(self, ty: str) -> str: + """ + Takes a triton type from CompiledKernel.signature and + converts it into a single char encoding. _StaticCudaLauncher + will switch on this char to figure out what type the underlying + value should be passed to the triton kernel as. + """ + if ty[0] == "*": + return "O" + elif ty == "nvTmaDesc" or ty.startswith("tensordesc<"): + raise NotImplementedError("TMA descriptor kernels are not yet supported") + return StaticallyLaunchedTritonKernel.type_mappings()[ty] + + def _expand_tensordesc_type(self, ty: str) -> str: + """Expand a tensordesc signature entry into the per-arg + type chars triton lowers it to (mirrors nvidia driver expand_signature): + nvTmaDesc path -> CUtensorMap + shape(i32) + strides(i64); host-decomposed + path -> base ptr + shape/strides(i64) + 2 flags + shape(i32) + strides(i64). + + This mirrors the string parse in triton's own expand_signature: the only + thing we need is the descriptor's rank, which lives in the shape list of + the serialized "tensordesc" form. We parse that string + here rather than importing expand_signature because that helper's argument + signature differs across triton versions (a 2-arg (signature, meta) form + in the fb-triton nvidia driver vs a 3-arg (signature, meta, + descriptor_type) form as backends converge on a shared helper), so + importing it would break across triton bumps; the serialized string + format is stable. + TODO: switch to triton's expand_signature once the versions converge on a + single argument signature. + """ + import re + + # Same regex triton's expand_signature uses. We only need the rank, so + # the captured dtype group is unused (kept to match triton's pattern). + match = re.match(r"tensordesc<([^\[>]*)\[([^\]]*)\]", ty) + if match is None: + raise NotImplementedError(f"Could not parse tensordesc type: {ty}") + ndim = match.group(2).count(",") + 1 + meta = self.tensordesc_meta + idx = self._tensordesc_idx + self._tensordesc_idx += 1 + per_desc_meta = meta[idx] if meta else None + if per_desc_meta is None: + chars = ["O"] + ["l"] * (2 * ndim) + ["i", "i"] + else: + chars = ["M"] + chars += ["i"] * ndim + ["l"] * ndim + return "".join(chars) + + def arg_ty_from_signature(self, src: ASTSource) -> str: + def index_key(i: Any) -> int: + if isinstance(i, str): + # pyrefly: ignore [missing-attribute] + return src.fn.arg_names.index(i) + elif isinstance(i, tuple): + # In triton 3.3, src.fn.constants has tuples as a key + return i[0] + else: + return i + + # pyrefly: ignore [missing-attribute] + signature = {index_key(key): value for key, value in src.signature.items()} + # Triton uses these as the main way to filter out constants passed to their cubin + constants = [index_key(key) for key in getattr(src, "constants", dict())] + # This value is always a superset of kernel.fn.constexprs: kernel.fn.constexprs are + # constants declared by the triton kernel directly, whereas this list can have + # constants that are unused by the triton kernel that triton figured out during + # compilation. + self.full_constexprs = constants + # Despite requiring them to be passed in, the triton CUDA launcher + # completely ignores the constexprs passed into it when generating code. + # So we can ignore them here too + params = [] + self._tensordesc_idx = 0 + + for i in sorted(signature.keys()): + ty = signature[i] + # In newer triton versions, constants are passed in to signature with type `constexpr` + # In older triton versions, there can be constants in src.constants that are not `constexpr` in signature + # so we check both here + if ty == "constexpr" or i in constants: + pass + elif isinstance(ty, str) and ty.startswith("tensordesc<"): + self._has_tensordesc = True + params.append(self._expand_tensordesc_type(ty)) + else: + # pyrefly: ignore [bad-argument-type] + params.append(self.extract_type(ty)) + return "".join(params) + + def __getstate__(self) -> dict[str, Any]: + # Remove objects that are no longer valid for pickling + state = self.__dict__.copy() + state["function"] = None + state["module"] = None + state["functions"] = {} + state["modules"] = {} + # Cubin paths aren't consistent across processes, so we clear + # and reload them. + state["cubin_path"] = None + return state + + def _expand_tma_args(self, args: tuple[object, ...]) -> tuple[object, ...]: + """Expand host-side TMA TensorDescriptor args into the flat kernel params + (CUtensorMap + shape + strides) so they match the expanded type string.""" + make_tensordesc_arg, TensorDescriptor = _tma_arg_helpers() + + meta = self.tensordesc_meta + out: list[object] = [] + td_idx = 0 + for arg in args: + if isinstance(arg, TensorDescriptor): + per_desc_meta = meta[td_idx] if meta else None + td_idx += 1 + out.extend(make_tensordesc_arg(arg, per_desc_meta)) + else: + out.append(arg) + return tuple(out) + + def run( + self, + grid_x: int, + grid_y: int, + grid_z: int, + stream: int, + *args: Unpack[tuple[object, ...]], + ) -> None: + """Actually run the kernel at runtime. This function is the hot codepath.""" + + if self.device_agnostic: + # The loaded function is device-bound; pick (loading on demand) the one for + # the current device so a shared kernel launches on whatever device the + # caller is using. + device = self._current_device() + function = self.functions.get(device) + if function is None: + self.load_kernel(device) + function = self.functions[device] + else: + function = self.function + + # Assert load_kernel() has been called and args match + if function is None: + raise AssertionError("load_kernel() must be called before run()") + + # TODO: actually, if the args *don't* match, we probably should + # throw an exception. But if inductor is the only one calling this + # thing, it should always match. + # Get rid of constants before passing to cubin launcher + + if self._has_tensordesc: + args = self._expand_tma_args(args) + + arg_tys = self.arg_tys + + if is_rocm(): + # ROCm/HIP kernel ABI: The Triton HIP backend ALWAYS includes both + # global_scratch and profile_scratch parameters in the kernel signature, + # even when the kernel doesn't use them (i.e., when has_*_scratch is False). + # + # This differs fundamentally from CUDA, where these parameters are only + # present in the signature if the corresponding has_*_scratch flag is True. + # + # The flags indicate whether memory will be allocated/used: + # - has_global_scratch: Whether global scratch workspace is needed + # - has_profile_scratch: Whether profiling instrumentation is enabled + # + # However, regardless of flag values, we MUST always pass both parameters + # to match the HIP kernel ABI. Passing None is safe: + # + # - If scratch is not needed (has_*_scratch=False or scratch_size=0): + # The None becomes nullptr, which the kernel never dereferences + # + # - If scratch is needed (has_*_scratch=True and scratch_size>0): + # The None becomes nullptr initially, but the HIP runtime intercepts + # the kernel launch, allocates the required scratch memory based on + # kernel metadata, and replaces the nullptr with a valid pointer before + # the kernel actually executes + # + # Not passing both parameters causes segmentation faults because the kernel + # expects them at specific positions in the argument array. + arg_tys = arg_tys + "OO" + args = (*args, None, None) + + else: + for has_scratch in [self.has_global_scratch, self.has_profile_scratch]: + if has_scratch: + arg_tys = arg_tys + "O" + args = (*args, None) + # pyrefly: ignore [bad-argument-type] + if len(args) != len(arg_tys): + raise AssertionError(f"Expected {len(arg_tys)} args, got {len(args)}") + + # TODO: can handle grid functions here or in C++, so + # that we don't need the grid handler above. + self.C_impl._launch_kernel( + function, + grid_x, + grid_y, + grid_z, + self.num_warps, + self.shared, + arg_tys, + args, + stream, + ) + + +class StaticallyLaunchedCudaKernel(StaticallyLaunchedTritonKernel): + @cached_property + def C_impl(self): + from torch._C import _StaticCudaLauncher + + return _StaticCudaLauncher + + def __init__(self, kernel: CompiledKernel) -> None: + # pyrefly: ignore [missing-attribute] + if "hsaco" in kernel.asm: + # pyrefly: ignore [missing-attribute] + self.cubin_raw = kernel.asm["hsaco"] + + # pyrefly: ignore [missing-attribute] + elif "cubin" in kernel.asm: + # pyrefly: ignore [missing-attribute] + self.cubin_raw = kernel.asm["cubin"] + else: + raise RuntimeError( + "Expected either 'hsaco' (ROCm) or 'cubin' (CUDA) in kernel.asm" + ) + super().__init__(kernel) + + def _current_device(self) -> int: + import torch + + return torch.cuda.current_device() + + +class StaticallyLaunchedXpuKernel(StaticallyLaunchedTritonKernel): + @cached_property + def C_impl(self): + from torch._C import _StaticXpuLauncher + + return _StaticXpuLauncher + + def __init__(self, kernel: CompiledKernel) -> None: + # pyrefly: ignore [missing-attribute] + self.cubin_raw = kernel.asm.get("zebin", None) + super().__init__(kernel) + + def load_kernel(self, device: int) -> None: + # The XPU static launcher returns a PyCapsule for the loaded SYCL kernel, + # not a separate module/function pair like the CUDA/HIP launcher. + if self.device_agnostic: + if device in self.functions: + return + (function, self.n_regs, self.n_spills) = self.C_impl._load_kernel( + self._agnostic_cubin_path(), self.name, self.shared, device + ) + # XPU has no separate module handle (only the function capsule). + self.functions[device] = function + return + + if self.function is not None: + return + + if not hasattr(self, "cubin_path"): + raise AssertionError("expected cubin_path attribute to be set") + if self.cubin_path is None: + raise AssertionError("expected cubin_path to not be None") + (self.function, self.n_regs, self.n_spills) = self.C_impl._load_kernel( + self.cubin_path, self.name, self.shared, device + ) + self.module = None + self.cubin_path = None + self.cubin_raw = None + + def _current_device(self) -> int: + import torch + + return torch.xpu.current_device() + + def close(self) -> None: + self.module = None + # Drop the PyCapsule references so their destructors can release sycl::kernel. + self.function = None + self.functions = {} + self.modules = {} + + +def statically_launched_kernel_by_device( + kernel: CompiledKernel, device_type: str = "cuda" +) -> StaticallyLaunchedTritonKernel: + if device_type in ("cuda", "hip"): + return StaticallyLaunchedCudaKernel(kernel) + elif device_type == "xpu": + return StaticallyLaunchedXpuKernel(kernel) + else: + raise NotImplementedError( + f"Device type {device_type} is not supported for static launcher" + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/triton_compat.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/triton_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..cd3d53f139c03510f83f9d9565b26914af4684d2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/triton_compat.py @@ -0,0 +1,175 @@ +from __future__ import annotations + +import inspect +from typing import Any + +import torch + + +try: + import triton +except ImportError: + triton = None + + +if triton is not None: + import triton.language as tl + from triton import Config + from triton.compiler import CompiledKernel + from triton.runtime.autotuner import OutOfResources + from triton.runtime.jit import JITFunction, KernelInterface + + try: + from triton.runtime.autotuner import PTXASError + except ImportError: + + class PTXASError(Exception): # type: ignore[no-redef] + pass + + try: + from triton.compiler.compiler import ASTSource + except ImportError: + ASTSource = None + + try: + from triton.backends.compiler import GPUTarget + except ImportError: + + def GPUTarget( + backend: str, + arch: int | str, + warp_size: int, + ) -> Any: + if torch.version.hip: + return [backend, arch, warp_size] + return (backend, arch) + + # In the latest triton, math functions were shuffled around into different modules: + # https://github.com/triton-lang/triton/pull/3172 + try: + from triton.language.extra import libdevice + + libdevice = tl.extra.libdevice # noqa: F811 + math = tl.math + except ImportError: + if hasattr(tl.extra, "cuda") and hasattr(tl.extra.cuda, "libdevice"): + libdevice = tl.extra.cuda.libdevice + math = tl.math + elif hasattr(tl.extra, "intel") and hasattr(tl.extra.intel, "libdevice"): + libdevice = tl.extra.intel.libdevice + math = tl.math + else: + libdevice = tl.math + math = tl + + try: + from triton.language.standard import _log2 + except ImportError: + + def _log2(x: Any) -> Any: + raise NotImplementedError + + def _triton_config_has(param_name: str) -> bool: + if not hasattr(triton, "Config"): + return False + if not hasattr(triton.Config, "__init__"): + return False + return param_name in inspect.signature(triton.Config.__init__).parameters + + # Drop the legacy support of autoWS + HAS_WARP_SPEC = False + + try: + from triton import knobs + except ImportError: + knobs = None + + try: + from triton.runtime.cache import triton_key # type: ignore[attr-defined] + except ImportError: + from triton.compiler.compiler import ( + triton_key, # type: ignore[attr-defined,no-redef] + ) + + try: + from triton.runtime.errors import IntelGPUError + except ImportError: + + class IntelGPUError(Exception): # type: ignore[no-redef] + pass + + builtins_use_semantic_kwarg = ( + "_semantic" in inspect.signature(triton.language.core.view).parameters + ) + HAS_TRITON = True +else: + + def _raise_error(*args: Any, **kwargs: Any) -> Any: + raise RuntimeError("triton package is not installed") + + class OutOfResources(Exception): # type: ignore[no-redef] + pass + + class PTXASError(Exception): # type: ignore[no-redef] + pass + + class IntelGPUError(Exception): # type: ignore[no-redef] + pass + + Config = object + CompiledKernel = object + KernelInterface = object + ASTSource = None + GPUTarget = None + _log2 = _raise_error + libdevice = None + math = None + knobs = None + builtins_use_semantic_kwarg = False + + class triton: # type: ignore[no-redef] + @staticmethod + def jit(*args: Any, **kwargs: Any) -> Any: + return _raise_error + + class tl: # type: ignore[no-redef] + @staticmethod + def constexpr(val: Any) -> Any: + return val + + tensor = Any + dtype = Any + + class JITFunction: # type: ignore[no-redef] + pass + + HAS_WARP_SPEC = False + triton_key = _raise_error + HAS_TRITON = False + + +try: + autograd_profiler = torch.autograd.profiler +except AttributeError: # Compile workers only have a mock version of torch + + class autograd_profiler: # type: ignore[no-redef] + _is_profiler_enabled = False + + +__all__ = [ + "Config", + "CompiledKernel", + "OutOfResources", + "KernelInterface", + "PTXASError", + "IntelGPUError", + "ASTSource", + "GPUTarget", + "tl", + "_log2", + "libdevice", + "math", + "triton", + "knobs", + "triton_key", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/triton_helpers.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/triton_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..b8f1152b29aa9502889596c60ec4dbf6b25295c8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/triton_helpers.py @@ -0,0 +1,1059 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import math as pymath +import warnings +from collections.abc import Callable +from contextlib import contextmanager +from contextvars import ContextVar +from typing import Any, TypeVar + +from .triton_compat import ( + _log2, + builtins_use_semantic_kwarg, + JITFunction, + libdevice, + math, + tl, + triton, +) + + +_T = TypeVar("_T") +_LOG_2_E: tl.constexpr = tl.constexpr(pymath.log2(pymath.e)) +_skip_gpu_driver_setup: ContextVar[bool] = ContextVar( + "_skip_gpu_driver_setup", default=False +) + + +@contextmanager +def skip_gpu_driver_setup(): + # Scoped no-op for set_driver_to_gpu(). ContextVar keeps nested/thread-local + # uses isolated. + token = _skip_gpu_driver_setup.set(True) + try: + yield + finally: + _skip_gpu_driver_setup.reset(token) + + +def set_driver_to_cpu(): + driver = triton.runtime.driver + if backend := triton.backends.backends.get("cpu", None): + if isinstance(driver.active, backend.driver): + # Don't re-initialize backend if it is already active + return + driver.set_active(backend.driver()) + return + # This can be a hard error once triton-cpu is merged into fbcode + warnings.warn( + "Could not find an active CPU backend. Generated kernels will not be executable!" + ) + + +def _is_backend_active(name, backend): + if backend.driver.is_active(): + return True + # Triton may fail to detect the GPU in subprocess workers when using + # ctypes-based driver detection (triton-lang/triton#9578). Fall back + # to torch's own device checks which are more reliable in these environments. + if name == "nvidia": + import torch + + return torch.cuda.is_available() and torch.version.hip is None + if name == "amd": + import torch + + return torch.cuda.is_available() and torch.version.hip is not None + return False + + +def set_driver_to_gpu(): + if _skip_gpu_driver_setup.get(): + return + + driver = triton.runtime.driver + for name, backend in triton.backends.backends.items(): + if _is_backend_active(name, backend) and name != "cpu": + # After https://github.com/triton-lang/triton/commit/b844d519bc5e86edf00fe6b3c6c2d1badcd509a4, + # `driver.active` can be of `LazyProxy` type and the sign of this - `_obj` attribute. + if ( + isinstance(driver.active, backend.driver) + or hasattr(driver.active, "_obj") + and isinstance(driver.active._obj, backend.driver) + ): + # Don't re-initialize backend if it is already active + return + driver.set_active(backend.driver()) + return + raise RuntimeError("Could not find an active GPU backend") + + +def get_backend_options_for_target(target, options=None): + options = {} if options is None else dict(options) + backend = triton.compiler.compiler.make_backend(target) + return backend.parse_options(options).__dict__ + + +def get_backend_options(): + from triton.runtime import driver + + target = driver.active.get_current_target() + return get_backend_options_for_target(target) + + +def _is_concrete_backend_option_value(value: Any) -> bool: + import sympy + + import torch + + if isinstance( + value, + ( + torch.Tensor, + torch.SymInt, + torch.SymFloat, + torch.SymBool, + sympy.Expr, + ), + ): + return False + if isinstance(value, (tuple, list)): + return all(_is_concrete_backend_option_value(item) for item in value) + if isinstance(value, dict): + return all( + _is_concrete_backend_option_value(key) + and _is_concrete_backend_option_value(item) + for key, item in value.items() + ) + return True + + +def try_filter_backend_options_for_target(target, options, kernel_arg_names=()): + parsed_options = get_backend_options_for_target(target) + kernel_arg_names = tuple(kernel_arg_names) + filtered_options = { + name: value for name, value in options.items() if name in parsed_options + } + invalid_options = [ + name + for name in options + if name not in parsed_options and name not in kernel_arg_names + ] + if invalid_options: + raise RuntimeError( + "Triton launch kwargs must be kernel parameters or valid backend options: " + f"{sorted(invalid_options)!r}." + ) + dynamic_options = [ + name + for name, value in filtered_options.items() + if not _is_concrete_backend_option_value(value) + ] + if dynamic_options: + raise RuntimeError( + "Triton backend options must be concrete values: " + f"{sorted(dynamic_options)!r}." + ) + return filtered_options + + +def get_constexprs(kernel: JITFunction) -> list[int]: + return [p.num for p in kernel.params if p.is_constexpr] + + +@triton.jit +def promote_to_tensor(x): + # Addition promotes to tensor for us + return x + tl.zeros((1,), tl.int1) + + +@triton.jit +def fp8e4m3fn_to_float32(x): + x_u32 = x.to(tl.uint32) + sign = (x_u32 & 0x80) << 24 + exp = (x_u32 >> 3) & 0xF + mant = x_u32 & 0x7 + + normal_bits = sign | ((exp + 120) << 23) | (mant << 20) + normal = normal_bits.to(tl.float32, bitcast=True) + + subnormal_abs = mant.to(tl.float32) * 0.001953125 + subnormal_bits = subnormal_abs.to(tl.uint32, bitcast=True) | sign + subnormal = subnormal_bits.to(tl.float32, bitcast=True) + + nan = (sign | 0x7FF00000).to(tl.float32, bitcast=True) + result = tl.where(exp == 0, subnormal, normal) + return tl.where((exp == 0xF) & (mant == 0x7), nan, result) + + +@triton.jit +def div_floor_integer(a, b): + # NOTE: a // b is C division, but we want floor division + # Based on c10::div_floor_integer + quot = a // b + remainder = a % b + fixed = tl.where(remainder != 0, quot - 1, quot) + return tl.where((a < 0) != (b < 0), fixed, quot) + + +@triton.jit +def remainder_integer(a, b): + # NOTE: a % b matches C division, not floor division + remainder = a % b + return tl.where((remainder != 0) & ((a < 0) != (b < 0)), remainder + b, remainder) + + +@triton.jit +def pow_integer(base, exponent): + # Triton has no exact integer pow primitive; use repeated squaring for + # nonnegative integer exponents so integral scalar pow does not round + # through libdevice.pow before casting back to int. + exponent_dtype: tl.constexpr = tl.core.get_int_dtype( + exponent.dtype.primitive_bitwidth, signed=False + ) + exp = exponent.to(exponent_dtype) + result = tl.full(base.shape, 1, base.dtype) + for _ in tl.static_range(exponent_dtype.primitive_bitwidth): + result = tl.where((exp & 1) != 0, result * base, result) + exp = exp >> 1 + base = base * base + return result + + +@triton.jit +def is_floating(x): + return promote_to_tensor(x).dtype.is_floating() + + +@triton.jit +def _prod_accumulate(a, b): + return a * b + + +@triton.jit +def prod(input, axis): + return tl.reduce(input, axis, _prod_accumulate) + + +@triton.jit +def minimum(a, b): + return tl.minimum(a, b, propagate_nan=tl.PropagateNan.ALL) + + +@triton.jit +def maximum(a, b): + return tl.maximum(a, b, propagate_nan=tl.PropagateNan.ALL) + + +@triton.jit +def _minimum_reduce(a, b): + value = minimum(a, b) + if is_floating(a): + value = tl.where(a == b, b, value) + return value + + +@triton.jit +def _maximum_reduce(a, b): + value = maximum(a, b) + if is_floating(a): + value = tl.where(a == b, b, value) + return value + + +@triton.jit +def fmaximum(a, b): + return tl.maximum(a, b) + + +@triton.jit +def min2(a, dim): + return tl.reduce(a, dim, minimum) + + +@triton.jit +def max2(a, dim): + return tl.reduce(a, dim, maximum) + + +@triton.jit +def min2_strict(a, dim): + return tl.reduce(a, dim, _minimum_reduce) + + +@triton.jit +def max2_strict(a, dim): + return tl.reduce(a, dim, _maximum_reduce) + + +@triton.jit +def fmax2(a, dim): + return tl.reduce(a, dim, fmaximum) + + +@triton.jit +def minimum_with_index(a_value, a_index, b_value, b_index): + mask = a_value < b_value + equal = a_value == b_value + if is_floating(a_value): + a_isnan = a_value != a_value + b_isnan = b_value != b_value + mask |= a_isnan & (not b_isnan) + # Consider NaNs as equal + equal |= a_isnan & b_isnan + + # Prefer lowest index if values are equal + mask |= equal & (a_index < b_index) + return tl.where(mask, a_value, b_value), tl.where(mask, a_index, b_index) + + +@triton.jit +def maximum_with_index(a_value, a_index, b_value, b_index): + mask = a_value > b_value + equal = a_value == b_value + if is_floating(a_value): + a_isnan = a_value != a_value + b_isnan = b_value != b_value + mask |= a_isnan & (not b_isnan) + # Consider NaNs as equal + equal |= a_isnan & b_isnan + + # Prefer lowest index if values are equal + mask |= equal & (a_index < b_index) + return tl.where(mask, a_value, b_value), tl.where(mask, a_index, b_index) + + +@triton.jit +def min_with_index(value, index, dim): + return tl.reduce((value, index), dim, minimum_with_index) + + +@triton.jit +def max_with_index(value, index, dim): + return tl.reduce((value, index), dim, maximum_with_index) + + +@triton.jit +def exp(x, use_fast_math: tl.constexpr): + if use_fast_math: + return math.exp(x) + else: + return libdevice.exp(x) + + +@triton.jit +def online_softmax_reduce( + lhs_max, + lhs_sum, + dim, + use_fast_math: tl.constexpr, + strict_signed_zero: tl.constexpr, +): + if strict_signed_zero: + out_max = max2_strict(lhs_max, dim) + else: + out_max = max2(lhs_max, dim) + out_max_keepdim = tl.expand_dims(out_max, dim) + delta = tl.where(out_max_keepdim == float("-inf"), 0, lhs_max - out_max_keepdim) + out_sum = tl.sum(lhs_sum * exp(delta, use_fast_math), dim) + return out_max, out_sum + + +@triton.jit +def online_softmax_combine( + lhs_max, + lhs_sum, + rhs_max, + use_fast_math: tl.constexpr, + strict_signed_zero: tl.constexpr, +): + """ + When we do combine, we assume lhs is the accumulator and rhs is the next + block of data. + Then rhs_sum is always 1. With that assumption, we can save some registers + and computation. + """ + if strict_signed_zero: + out_max = _maximum_reduce(lhs_max, rhs_max) + else: + out_max = maximum(lhs_max, rhs_max) + + lhs_scale = tl.where( + out_max == float("-inf"), 1.0, exp(lhs_max - out_max, use_fast_math) + ) + rhs_scale = tl.where( + out_max == float("-inf"), 1.0, exp(rhs_max - out_max, use_fast_math) + ) + + # Should be + # out_sum = lhs_sum * lhs_scale + rhs_sum * rhs_scale + # but since rhs_sum is all 1, we can simplify it. + out_sum = lhs_sum * lhs_scale + rhs_scale + return out_max, out_sum + + +@triton.jit +def online_softmax_combine_with_sum( + lhs_max, + lhs_sum, + rhs_max, + rhs_sum, + use_fast_math: tl.constexpr, + strict_signed_zero: tl.constexpr, +): + if strict_signed_zero: + out_max = _maximum_reduce(lhs_max, rhs_max) + else: + out_max = maximum(lhs_max, rhs_max) + + lhs_scale = tl.where( + out_max == float("-inf"), 1.0, exp(lhs_max - out_max, use_fast_math) + ) + rhs_scale = tl.where( + out_max == float("-inf"), 1.0, exp(rhs_max - out_max, use_fast_math) + ) + + out_sum = lhs_sum * lhs_scale + rhs_sum * rhs_scale + return out_max, out_sum + + +@triton.jit +def welford_reduce(value, mean, m2, weight, first_iteration): + if first_iteration: + new_weight = tl.full(weight.shape, 1, weight.dtype) + new_mean = value + new_m2 = tl.zeros_like(m2) + else: + delta = value - mean + new_weight = weight + 1 + new_mean = mean + delta / new_weight + new_m2 = m2 + delta * (value - new_mean) + return new_mean, new_m2, new_weight + + +@triton.jit +def welford_combine(mean_1, m2_1, weight_1, mean_2, m2_2, weight_2): + # Guard against inf - inf = NaN when both means are infinite and equal. + # This occurs during FP16/BF16 LayerNorm when inputs overflow to inf. + delta = tl.where(mean_1 == mean_2, 0.0, mean_2 - mean_1) + new_weight = weight_1 + weight_2 + w2_over_w = tl.where(new_weight == 0.0, 0.0, weight_2 / new_weight) + return ( + mean_1 + delta * w2_over_w, + m2_1 + m2_2 + delta * delta * weight_1 * w2_over_w, + new_weight, + ) + + +@triton.jit +def welford(mean, m2, weight, dim): + return tl.reduce((mean, m2, weight), dim, welford_combine) + + +@triton.jit +def device_assert_then(cond, msg, r): + tl.device_assert(cond, msg) + return r + + +@triton.jit +def rand_eager_kernel(seed, offset_blocks, tid: tl.tensor, VEC: tl.constexpr): + inv = 1.0 / 4294967296.0 + half = inv * 0.5 + + tid_u64 = tid.to(tl.uint64) + + subseq = tid_u64 // VEC + which4 = (tid_u64 % VEC) // 4 + lane = tid_u64 % 4 + + offblk = offset_blocks.to(tl.uint64) + which4 + + u0, u1, u2, u3 = tl.philox( + seed, + (offblk & 0xFFFFFFFF).to(tl.uint32), + ((offblk >> 32) & 0xFFFFFFFF).to(tl.uint32), + (subseq & 0xFFFFFFFF).to(tl.uint32), + ((subseq >> 32) & 0xFFFFFFFF).to(tl.uint32), + ) + + v01 = tl.where(lane == 0, u0, u1) + v23 = tl.where(lane == 2, u2, u3) + rand_int = tl.where((lane == 0) | (lane == 1), v01, v23) + + return 1.0 - (rand_int.to(tl.float32) * inv + half) + + +@triton.jit +def _random_4x_to_block(r0, r1, r2, r3): + # Pack lanes by logical offset so the random stream is independent of XBLOCK. + size: tl.constexpr = r0.numel + return tl.reshape(tl.join(tl.join(r0, r2), tl.join(r1, r3)), [size * 4]) + + +@triton.jit +def rand4x(seed, offsets, BLOCK: tl.constexpr): + offsets = offsets.to(tl.uint32) + seed = tl.min(seed + offsets * 0, axis=0) + if BLOCK >= 4 and BLOCK % 4 == 0: + base = tl.min(offsets, axis=0) + reduced_offsets = base // 4 + tl.arange(0, BLOCK // 4) + r0, r1, r2, r3 = tl.rand4x(seed, reduced_offsets) + return _random_4x_to_block(r0, r1, r2, r3) + return tl.rand(seed, offsets) + + +@triton.jit +def randn4x(seed, offsets, BLOCK: tl.constexpr): + offsets = offsets.to(tl.uint32) + seed = tl.min(seed + offsets * 0, axis=0) + if BLOCK >= 4 and BLOCK % 4 == 0: + base = tl.min(offsets, axis=0) + reduced_offsets = base // 4 + tl.arange(0, BLOCK // 4) + r0, r1, r2, r3 = tl.randn4x(seed, reduced_offsets) + return _random_4x_to_block(r0, r1, r2, r3) + return tl.randn(seed, offsets) + + +@triton.jit +def randint64(seed, offset, low, high): + r0, r1, _r2, _r3 = tl.randint4x(seed, offset) + r0 = r0.to(tl.uint64) + r1 = r1.to(tl.uint64) + result = r0 | (r1 << 32) + size = high - low + result = result % size.to(tl.uint64) + result = result.to(tl.int64) + low + return result + + +@triton.jit +def _any_combine(a, b): + return a | b + + +@triton.jit +def any(a, dim): + return tl.reduce(a, dim, _any_combine) + + +@triton.jit +def bucketize_binary_search( + values: tl.tensor, + boundaries_ptr: tl.tensor, + BOUNDARIES_SIZE: int, + BOUNDARIES_UNDERLYING_NUMEL: int, + BOUNDARIES_STRIDE: int, + boundary_indices: tl.tensor, + indexing_dtype: tl.dtype, + right: "bool", # triton can't handle the unquoted bool annotation + sorter_ptr: tl.tensor, + SORTER_STRIDE: int, + sorter_indices: tl.tensor, +): + """ + See [Note: Inductor bucketize op] + + Inputs: + ------- + values: the values to bucketize. + boundaries_ptr: a pointer to the beginning of the boundaries tensor, in 1-D. + BOUNDARIES_SIZE: the length of the last dimension of the boundaries tensor (i.e. one + individual set of boundaries). + BOUNDARIES_UNDERLYING_NUMEL: the length of the boundaries tensor, in 1-D, ignoring + any striding. + BOUNDARIES_STRIDE: the stride of the last dimension of the boundaries tensor + boundary_indices: a tensor of the same size as "values"; each element is an index + into a 1-D, un-strided boundaries tensor, pointing to the first element in the set + of boundaries used for that value. + indexing_dtype: the dtype used for indexing into the boundaries tensor, and the + return dtype. + right: if true, use boundary intervals closed on the left; otherwise use intervals + closed on the right. + sorter_ptr: an optional pointer to a sorter tensor of the same shape as boundaries, + but potentially different striding. If present, this allows us to treat boundaries + as sorted even if the elements of boundaries are unsorted. + SORTER_STRIDE: must be present if sorter_ptr is non-None; the stride of the last + dimension of the sorter tensor. + sorter_indices: must be present if sorter_ptr is non-None; see "boundary_indices". + BLOCK_SHAPE: the shape of the data block being processed. + """ + + low = tl.zeros(values.shape, dtype=indexing_dtype) + high = tl.full(values.shape, BOUNDARIES_SIZE, dtype=indexing_dtype) + + full_range = BOUNDARIES_SIZE + 1 + while full_range > 1: + mid = (high + low) // 2 + mask = ( + (mid * BOUNDARIES_STRIDE + boundary_indices) < BOUNDARIES_UNDERLYING_NUMEL + ).logical_and(mid < BOUNDARIES_SIZE) + mid_indices = ( + mid + if sorter_ptr is None or SORTER_STRIDE is None + else tl.load( + sorter_ptr + sorter_indices + SORTER_STRIDE * mid, + mask=mask, + other=0, + ) + ) + + bucket_upper_bound = tl.load( + boundaries_ptr + boundary_indices + BOUNDARIES_STRIDE * mid_indices, + mask=mask, + other=0, + ) + if right: + is_above = values >= bucket_upper_bound + else: + is_above = values > bucket_upper_bound + + if is_floating(values): + is_above = is_above | (values != values) + + low = tl.where(is_above & mask, mid + 1, low) + high = tl.where(is_above, high, mid) + + full_range = (full_range + 1) // 2 + + return low + + +@triton.jit +def pack_value_flag( + value, + flag, + DTYPE_VALUE_AS_UINT: tl.constexpr, + DTYPE_PACK: tl.constexpr, +): + # Workaround for triton bug, tensor.to doesn't unwrap constexpr values + DTYPE_VALUE_AS_UINT = tl.core._unwrap_if_constexpr(DTYPE_VALUE_AS_UINT) + bitwidth = DTYPE_VALUE_AS_UINT.primitive_bitwidth + uv = value.to(DTYPE_VALUE_AS_UINT, bitcast=True).to(DTYPE_PACK) + return flag.to(DTYPE_PACK) | (uv << bitwidth) + + +@triton.jit +def unpack_value( + pack, + DTYPE_VALUE, + DTYPE_VALUE_AS_UINT, +): + # Workaround for triton bug, tensor.to doesn't unwrap constexpr values + DTYPE_VALUE = tl.core._unwrap_if_constexpr(DTYPE_VALUE) + DTYPE_VALUE_AS_UINT = tl.core._unwrap_if_constexpr(DTYPE_VALUE_AS_UINT) + bitwidth = DTYPE_VALUE_AS_UINT.primitive_bitwidth + value_uint = (pack >> bitwidth).to(DTYPE_VALUE_AS_UINT) + return value_uint.to(DTYPE_VALUE, bitcast=True) + + +@triton.jit +def unpack_flag(pack, DTYPE_FLAG): + return pack.to(DTYPE_FLAG) + + +@triton.jit +def exclusive_scan_decoupled_lookback( + scratch_base, + block_value, + index, + combine_fn, + DTYPE_VALUE_AS_UINT: tl.constexpr, + DTYPE_PACK: tl.constexpr, +): + """Compute exclusive scan of a scalar value between blocks + + Ref: https://research.nvidia.com/publication/2016-03_single-pass-parallel-prefix-scan-decoupled-look-back + + scratch_base: Pointer to scratch space in global memory + block_value: Scalar value for this block + index: Scalar index of this block relative to the current scan + combine_fn: Function ``(value, value) -> value`` which is scanned over + DTYPE_VALUE_AS_UINT: A tl.uint{n} type equal in size to ``block_value`` + DTYPE_PACK: Unsigned type twice the width of block_value + + NOTE: This function is limited to values which are 32-bits or less because + we need to pack (value, flag) into a single unsigned int. + """ + # Publish block sum so subsequent blocks don't get stuck waiting for us + DTYPE_VALUE = block_value.dtype + pack = pack_value_flag( + block_value, + tl.full(block_value.shape, 1, DTYPE_VALUE_AS_UINT), + DTYPE_VALUE_AS_UINT, + DTYPE_PACK, + ) + if index > 0: + tl.atomic_xchg(scratch_base + index, pack, sem="relaxed") + + # Calculate exclusive prefix scan + exclusive_prefix = tl.zeros([], DTYPE_VALUE) + prefix_valid = False + test_target = index - 1 + while test_target >= 0: + # tl.atomic_load + flag = tl.full([], 0, DTYPE_VALUE_AS_UINT) + while flag == 0: + pack = tl.atomic_add(scratch_base + test_target, 0, sem="relaxed") + flag = unpack_flag(pack, DTYPE_VALUE_AS_UINT) + + value = unpack_value(pack, DTYPE_VALUE, DTYPE_VALUE_AS_UINT) + if prefix_valid: + exclusive_prefix = combine_fn(value, exclusive_prefix) + else: + exclusive_prefix = value + prefix_valid = True + + if flag == 2: + test_target = -1 + else: + test_target = test_target - 1 + + # Make inclusive block sum visible to other blocks + if prefix_valid: + inclusive_prefix = combine_fn(exclusive_prefix, block_value) + else: + inclusive_prefix = block_value + pack = pack_value_flag( + inclusive_prefix, + tl.full([], 2, DTYPE_VALUE_AS_UINT), + DTYPE_VALUE_AS_UINT, + DTYPE_PACK, + ) + tl.atomic_xchg(scratch_base + index, pack, sem="relaxed") + return exclusive_prefix + + +@triton.jit +def exclusive_scan_decoupled_lookback_64(scratch_base, block_value, index, combine_fn): + """Compute exclusive scan of a scalar value between blocks + + Ref: https://research.nvidia.com/publication/2016-03_single-pass-parallel-prefix-scan-decoupled-look-back + + scratch_base: Pointer to scratch space in global memory + block_value: Scalar value for this block, must be 64-bits wide + index: Scalar index of this block relative to the current scan + combine_fn: Function ``(value, value) -> value`` which is scanned over + init: Scalar value equal to the identity of combine_fn + """ + # Publish block sum so subsequent blocks don't get stuck waiting for us + if index > 0: + block_value_u64 = block_value.to(tl.uint64, bitcast=True) + tl.store(scratch_base + 3 * index + 1, block_value_u64) + tl.debug_barrier() + flag_one = tl.full([], 1, tl.uint64) + tl.atomic_xchg(scratch_base + 3 * index + 0, flag_one, sem="release") + + # Calculate exclusive prefix scan + exclusive_prefix = tl.zeros([], block_value.dtype) + prefix_valid = False + test_target = index - 1 + while test_target >= 0: + flag = tl.full([], 0, tl.uint64) + while flag == 0: + flag = tl.atomic_add(scratch_base + 3 * test_target + 0, 0, sem="acquire") + + value_u64 = tl.load(scratch_base + 3 * test_target + flag.to(tl.int32)) + value = value_u64.to(block_value.dtype, bitcast=True) + if prefix_valid: + exclusive_prefix = combine_fn(value, exclusive_prefix) + else: + exclusive_prefix = value + prefix_valid = True + + if flag == 2: + test_target = tl.full([], -1, index.dtype) # Match the original type + else: + test_target = test_target - 1 + + # Make inclusive block sum visible to other blocks + if prefix_valid: + inclusive_prefix = combine_fn(exclusive_prefix, block_value) + else: + inclusive_prefix = block_value + inclusive_prefix_u64 = inclusive_prefix.to(tl.uint64, bitcast=True) + tl.store(scratch_base + 3 * index + 2, inclusive_prefix_u64) + tl.debug_barrier() + flag_two = tl.full([], 2, tl.uint64) + tl.atomic_xchg(scratch_base + 3 * index + 0, flag_two, sem="release") + + return exclusive_prefix + + +@triton.jit +def frexp(x): + # TODO(isuruf): use inline_asm_elementwise here + zero = x == 0 + not_finite = libdevice.isinf(x).to(tl.int1) | libdevice.isnan(x).to(tl.int1) + special = zero | not_finite + safe_x = tl.where(special, 1.0, x) + y = libdevice.ilogb(safe_x) + 1 + exponent = tl.where(special, 0, y) + mantissa = tl.where(zero, 0, tl.where(not_finite, x, libdevice.ldexp(safe_x, -y))) + return mantissa, exponent + + +@triton.jit +def _compare_and_swap_with_index( + x, + idxs, + rnumel, + flip, + i: tl.constexpr, + n_dims: tl.constexpr, + stable: tl.constexpr, + descending: tl.constexpr, +): + n_outer: tl.constexpr = x.numel >> n_dims + shape: tl.constexpr = [n_outer * 2**i, 2, 2 ** (n_dims - i - 1)] + + idtype = tl.core.get_int_dtype(bitwidth=x.dtype.primitive_bitwidth, signed=True) + + y = tl.reshape(x, shape) + iy = y.to(idtype, bitcast=True) + # slice left/right with 'stride' 2**(n_dims - i - 1) + right_mask = tl.arange(0, 2)[None, :, None].to(idtype) + left_mask = (1 - right_mask).to(idtype) + ileft = tl.broadcast_to(tl.sum(iy * left_mask, 1).to(idtype)[:, None, :], shape) + iright = tl.broadcast_to(tl.sum(iy * right_mask, 1).to(idtype)[:, None, :], shape) + ileft = tl.reshape(ileft, x.shape) + iright = tl.reshape(iright, x.shape) + left = ileft.to(x.dtype, bitcast=True) + right = iright.to(x.dtype, bitcast=True) + + # idx + y_idx = tl.reshape(idxs, shape) + left_idx = tl.broadcast_to( + tl.sum(y_idx * left_mask.to(y_idx.dtype), 1)[:, None, :], shape + ) + right_idx = tl.broadcast_to( + tl.sum(y_idx * right_mask.to(y_idx.dtype), 1)[:, None, :], shape + ) + left_idx = tl.reshape(left_idx, x.shape) + right_idx = tl.reshape(right_idx, x.shape) + + # valid + if rnumel is None: + left_valid_mask = tl.full(x.shape, True, tl.int1) + right_valid_mask = tl.full(x.shape, True, tl.int1) + else: + left_valid_mask = left_idx < rnumel + right_valid_mask = right_idx < rnumel + + # actual compare-and-swap + ix = x.to(idtype, bitcast=True) + + # sort treats nan as having the higher value. comparisons with nan always return False. + # to align with sort semantics, we need to update descending to check if right_isnan, + # and ascending to check if left_isnan. + left_isnan = left != left + right_isnan = right != right + + if descending: + cond = left < right + if is_floating(left): + if not stable: + cond = cond | right_isnan + else: + cond = cond | (right_isnan & (~left_isnan)) + + else: + cond = left > right + if is_floating(left): + if not stable: + cond = cond | left_isnan + else: + cond = cond | (left_isnan & (~right_isnan)) + + if stable: + # When stable sorting, tie break by index + eq = left == right + if is_floating(left): + eq = eq | (left_isnan & right_isnan) + cond = cond | (eq & (left_idx > right_idx)) + + cond = (right_valid_mask > left_valid_mask) | ( + (right_valid_mask == left_valid_mask) & cond + ) + cond = (cond ^ flip).to(tl.int1) + ret = ix ^ tl.where(cond, ileft ^ iright, tl.zeros_like(ix)) + new_idxs = idxs ^ tl.where(cond, left_idx ^ right_idx, tl.zeros_like(idxs)) + + return ret.to(x.dtype, bitcast=True), new_idxs + + +@triton.jit +def _bitonic_merge_with_index( + x, + idxs, + rnumel, + stage: tl.constexpr, + alternating: tl.constexpr, + n_dims: tl.constexpr, + stable: tl.constexpr, + descending: tl.constexpr, +): + n_outer: tl.constexpr = x.numel >> n_dims + tl.static_assert(stage <= n_dims) + # flip denotes whether to re-arrange sub-sequences of elements in ascending or + # descending order. + # if flip = 00000000... then all elements will be re-arranged ascendingly at this stage + # if flip = 00110011... then all the elements will be re-arranged alternatingly (with + # a stride of 2) at this stage + if alternating: + shape: tl.constexpr = [n_outer * 2 ** (n_dims - 1 - stage), 2, 2**stage] + flip = tl.reshape( + tl.broadcast_to(tl.arange(0, 2)[None, :, None], shape), x.shape + ) + else: + flip = False + # perform `stage` rounds of `compare-and-swap` + for i in tl.static_range(stage): + x, idxs = _compare_and_swap_with_index( + x, idxs, rnumel, flip, i + (n_dims - stage), n_dims, stable, descending + ) + return x, idxs + + +@triton.jit +def sort_with_index( + x, # value + idxs, # index + rnumel, # number of elements + dim: tl.constexpr = None, + stable: tl.constexpr = tl.constexpr(False), + descending: tl.constexpr = tl.constexpr(False), +): + x, idxs = tl.broadcast(x, idxs) + # handle default dimension or check that it is the most minor dim + _dim: tl.constexpr = len(x.shape) - 1 if dim is None else dim + tl.static_assert( + _dim == len(x.shape) - 1, "only minor dimension is currently supported" + ) + # iteratively run bitonic merge-sort steps + n_dims: tl.constexpr = _log2(x.shape[_dim]) + + for i in tl.static_range(1, n_dims + 1): + x, idxs = _bitonic_merge_with_index( + x, + idxs, + rnumel, + i, + alternating=i < n_dims, + n_dims=n_dims, + stable=stable, + descending=descending, + ) + return x, idxs + + +@triton.jit +def select_one(x, mask, dim, keep_dims=False): + idtype = tl.core.get_int_dtype(x.dtype.primitive_bitwidth, signed=False) + ix = x.to(idtype, bitcast=True) + iy = tl.sum(ix * mask, dim, keep_dims=keep_dims) + return iy.to(idtype).to(x.dtype, bitcast=True) + + +@triton.jit +def x_grid_barrier(sem): + """ + Wait for all other thread blocks in grid sharing same y/z program_id + to reach this barrier before returning. + + Args: + sem: an uint32 semaphores, zero or 0x80000000 initialized. Must be unique to each y/z program ID. + """ + # ensure stores before this are visible + tl.debug_barrier() + + one_i32 = 1 + one_u32 = one_i32.to(tl.uint32) # type: ignore[attr-defined] + expected = tl.num_programs(0).to(tl.uint32) + if tl.program_id(0) == 0: + nb = 0x80000000 - (expected - one_u32) + else: + nb = one_u32 + + old_arrive = tl.atomic_add(sem, nb, sem="release") + + bar_flipped = False + while not bar_flipped: + # want a `ld.acquire.gpu.u32 $0,[$1];` but Triton doesn't have it + current_arrive = tl.atomic_add(sem, 0, sem="acquire") + # current_arrive = tl.load(sem, volatile=True) + bar_flipped = ((old_arrive ^ current_arrive) & 0x80000000) != 0 + + # TODO(jansel): is this needed? + tl.debug_barrier() + + +def triton_builtin(f: Callable[..., _T]) -> Callable[..., _T]: + """ + Decorator to mark a function as a Triton built-in function. These functions + are evaluated at compile time. + + Args: + f (function): The function to be marked as a Triton built-in. + + Returns: + function: The same function, marked as a Triton built-in. + """ + if builtins_use_semantic_kwarg: + # support Triton before and after https://github.com/triton-lang/triton/pull/7054 + # and after https://github.com/triton-lang/triton/pull/7239 + def wrapper(*args, _semantic, **kwargs): + kwargs["_builder"] = _semantic + return f(*args, **kwargs) + else: + wrapper = f # type: ignore[assignment] + + wrapper.__triton_builtin__ = True # type: ignore[attr-defined] + return wrapper + + +@triton_builtin +def constexpr_next_power_of_2( + n: tl.constexpr, *, _builder: object = None +) -> tl.constexpr: + """ + A version triton.next_power_of_two that can be used within a kernel on constants. + """ + if not isinstance(n, tl.constexpr): + raise AssertionError(f"Expected tl.constexpr, got {type(n)}") + return tl.constexpr(triton.next_power_of_2(n.value)) + + +@triton_builtin +def if_mask(mask: Any, val, *, _builder: object = None) -> tl.constexpr: + """ + Work around triton compile error: `ValueError: `other` cannot be provided without `mask`` + A compile-time to check to return either `val` or `None` depending on the value of mask. + """ + if isinstance(mask, tl.constexpr) and mask.value is None: + return tl.constexpr(None) + return val + + +@triton.jit +def inline_asm_pack(x, pack: tl.constexpr): + """Ravel to 1D and pad (via join with zeros) so numel is divisible by pack.""" + result = x.ravel() + # Only pad when the block size is smaller than pack. When block >= pack + # the numel is already divisible by pack (both are powers of 2). + n_pad: tl.constexpr = _log2(pack) - _log2(result.numel) + for _ in tl.static_range(n_pad): + result = tl.reshape( + tl.join(result, tl.zeros_like(result)), (result.shape[0] * 2,) + ) + return result + + +@triton.jit +def inline_asm_unpack(x, orig, pack: tl.constexpr): + """Unpad and reshape back to orig's shape.""" + result = x + n_pad: tl.constexpr = _log2(pack) - _log2(orig.numel) + for _ in tl.static_range(n_pad): + result, _ = tl.split(tl.reshape(result, (result.shape[0] // 2, 2))) + return tl.reshape(result, orig.shape) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/triton_heuristics.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/triton_heuristics.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9773de9d561fb93899a7a2fe15a88eeb402ab6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/triton_heuristics.py @@ -0,0 +1,5447 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import builtins +import copy +import dataclasses +import enum +import functools +import hashlib +import inspect +import itertools +import logging +import math +import operator +import os +import os.path +import re +import sys +import threading +import time +from collections import namedtuple +from typing import ( + Any, + cast, + Final, + Generic, + get_args, + Literal, + TYPE_CHECKING, + TypeAlias, + TypeVar, +) + +import torch +from torch._dynamo.utils import counters, set_feature_use +from torch._inductor import metrics +from torch._inductor.config import triton as inductor_triton_config +from torch._prims_common import compute_required_storage_length +from torch.utils._debug_mode import get_active_debug_mode +from torch.utils._ordered_set import OrderedSet +from torch.utils._triton import get_triton_version, has_triton_stable_tma_api + +from ..triton_bundler import TritonBundler +from ..utils import ( + GPU_KERNEL_BIN_EXTS, + prefix_is_reduction, + tlx_only_cuda_options, + TMA_ALIGNMENT, + triton_version_uses_attrs_dict, + XPU_KERNEL_FORMAT, +) +from . import triton_helpers +from .autotune_cache import AutotuneCache +from .benchmarking import benchmarker +from .coordinate_descent_tuner import CoordescTuner +from .hints import ( + AutotuneHint, + DeviceProperties, + HeuristicType, + InductorMeta, + native_matmul_block_numel, + ReductionHint, + TileHint, + TRITON_MAX_BLOCK, + TRITON_MAX_TENSOR_NUMEL, + TritonMeta, +) +from .runtime_utils import ( + cache_dir, + ceildiv, + conditional_product, + create_bandwidth_info_str, + dynamo_timed, + get_first_attr, + get_max_y_grid, + get_num_bytes, + next_power_of_2, + triton_cache_dir, + triton_config_to_hashable, + triton_hash_to_path_key, + validate_triton_config, +) +from .static_triton_launcher import ( + statically_launched_kernel_by_device, + StaticallyLaunchedCudaKernel, + StaticallyLaunchedXpuKernel, +) +from .triton_compat import ( + ASTSource, + autograd_profiler, + CompiledKernel, + Config, + GPUTarget, + HAS_WARP_SPEC, + IntelGPUError, + KernelInterface, + knobs, + OutOfResources, + PTXASError, + triton, +) +from .triton_helpers import get_constexprs + + +class BenchmarkFailureReason(enum.Enum): + """Reasons why a triton config benchmark may return float('inf').""" + + REGISTER_SPILLING = "register_spilling" + INVALID_CONFIG = "invalid_config" + + +class InductorConfig(Config): + """Inductor-specific Triton config with additional control flags""" + + def __init__(self, *args, dynamic_scale_rblock=True, **kwargs): + super().__init__(*args, **kwargs) + self.dynamic_scale_rblock = dynamic_scale_rblock + + +class NoTritonConfigsError(RuntimeError): + pass + + +def _should_enable_triton_debug_asserts(inductor_meta: InductorMeta) -> bool: + """ + Enable Triton debug asserts whenever indirect indexing asserts are on, + except on HIP where older Triton releases lack the required support. + + Triton 3.7 is the first release that includes the upstream debug-assert + support needed by ROCm, so HIP kernels must keep this disabled below that + version to remain compatible. + """ + if not inductor_meta.get("assert_indirect_indexing", True): + return False + if not inductor_meta.get("is_hip", False): + return True + return get_triton_version() >= (3, 7) + + +if TYPE_CHECKING: + from collections.abc import Callable, Container, Hashable + + from torch._C._profiler import _RecordFunctionFast + from torch._guards import CompileId + from torch.utils._debug_mode import _TritonKernelCall + + LauncherType = Any + +_KernelType: TypeAlias = ( + CompiledKernel | StaticallyLaunchedCudaKernel | StaticallyLaunchedXpuKernel +) +_T = TypeVar( + "_T", + CompiledKernel, + StaticallyLaunchedCudaKernel, + StaticallyLaunchedXpuKernel, +) +if get_args(_KernelType) != _T.__constraints__: + raise AssertionError("_KernelType args must match _T type constraints") + +log = logging.getLogger(__name__) +autotuning_inputs_log = torch._logging.getArtifactLogger(__name__, "autotuning_inputs") + +triton_name_sub = re.compile(r"^def [^(]+\(") + + +def generate_lookup_hash_from_source_code(size_hints_str: str, source_code: str) -> str: + # Name agnostic + strip white space + fn_strip_name = re.sub(triton_name_sub, "(", source_code.strip(), count=1) + hash_str = size_hints_str + fn_strip_name + fn_hash = hashlib.sha256(hash_str.encode("utf-8")).hexdigest() + + return fn_hash + + +def lookup_autotune_config(size_hints, fn) -> Config | None: + lookup_table = torch._inductor.config.autotune_lookup_table + cached_config = None + if len(lookup_table) > 0 and "_fused_" in fn.src: + fn_hash = generate_lookup_hash_from_source_code(str(size_hints), fn.src) + if fn_hash in lookup_table: + config_dict = lookup_table[fn_hash] + block_configs = {k: v for k, v in config_dict.items() if "BLOCK" in k} + cached_config = Config( + block_configs, + num_warps=config_dict["num_warps"], + num_stages=config_dict["num_stages"], + ) + + return cached_config + + +def get_total_reduction_numel(numels: dict[str, int]) -> int: + return conditional_product( + *[numel for prefix, numel in numels.items() if prefix_is_reduction(prefix)] + ) + + +def _resolve_dims(dims, cfg_kwargs, constants): + """Resolve a list of block/shape/stride dims to concrete ints.""" + result = [] + for s in dims: + if isinstance(s, int): + result.append(s) + elif isinstance(s, str) and s in constants: + result.append(int(constants[s])) + elif isinstance(s, str) and s in cfg_kwargs: + result.append(int(cfg_kwargs[s])) + else: + log.debug("host-side TMA: unresolved descriptor dim %r; skipping", s) + return None + return result + + +@functools.lru_cache(None) +def _warn_host_tma_clone(name: str) -> None: + log.warning( + "host-side TMA: input %s is not %d-byte aligned; cloning it (an extra " + "copy per launch). Pass aligned inputs to avoid this.", + name, + TMA_ALIGNMENT, + ) + + +def _host_tma_aligned(tensor, name): + """Return a TMA_ALIGNMENT-aligned view of `tensor`, cloning (with a one-time + warning) only if its base address is not aligned. Used by the host-side TMA + launcher to build TensorDescriptors from aligned storage.""" + if tensor.data_ptr() % TMA_ALIGNMENT == 0: + return tensor + _warn_host_tma_clone(name) + return tensor.clone() + + +def autotune_hints_to_configs( + hints: OrderedSet[AutotuneHint], + size_hints, + block_size: int, + device_props: DeviceProperties, +) -> list[Config]: + """ + AutotuneHints can be attached to the metadata of triton kernels for providing + suggestions about what to try for autotuning. One reason to do this is if there are + some configs that are only useful in specific scenarios, in which case we can avoid + wasting compile time on autotuning unless we know we are in one of those scenarios. + + Based on those hints, this function will generate a list of additional autotuning + configs to try. + """ + xyz_options: tuple[tuple[int, int | None, int | None], ...] + configs: list[Config] = [] + for hint in hints: + if hint == AutotuneHint.ONE_ELEMENT_PER_THREAD: + if device_props.warp_size is None: + log.debug( + "Skipping %s autotune hint because device %s does not report warp_size", + AutotuneHint.ONE_ELEMENT_PER_THREAD, + device_props.type, + ) + continue + if len(size_hints) == 1: + xyz_options = ((block_size // 4, None, None),) + elif len(size_hints) == 2: + xyz_options = ((block_size // 4, 1, None), (1, block_size // 4, None)) + elif len(size_hints) == 3: + xyz_options = ( + (block_size // 4, 1, 1), + (1, block_size // 4, 1), + (1, 1, block_size // 4), + ) + warp_size = device_props.warp_size_or_default + configs.extend( + triton_config( + size_hints, + *xyz, + num_elements_per_warp=warp_size, + warp_size=warp_size, + ) + for xyz in xyz_options + ) + + return configs + + +def _dump_launch_params(args, kwargs, launcher, kernel_name, grid): + call_args = [] + call_kwargs = dict(kwargs) + for arg in args: + if isinstance(arg, (int, bool)): + call_args.append(str(arg)) + else: + call_args.append("T") + call_kwargs.update(launcher.config.kwargs) + call_kwargs["num_warps"] = launcher.config.num_warps + call_kwargs["num_stages"] = launcher.config.num_stages + if HAS_WARP_SPEC: + call_kwargs["num_consumer_groups"] = getattr( + launcher.config, "num_consumer_groups", 0 + ) + call_kwargs["num_buffers_warp_spec"] = getattr( + launcher.config, "num_buffers_warp_spec", 0 + ) + args_str = [*call_args] + args_str.extend(f"{k}={v}" for k, v in call_kwargs.items()) + args_str = ", ".join(args_str) + abs_path = os.path.abspath(sys.argv[0]) + with open(f"{abs_path}.launch_params", "a") as f: + f.write(f"{kernel_name} | {args_str} | {grid!r}\n") + + +def _dump_launch_tensors(args, kernel_path, kernel_hash, kernel_name): + tensor_list = [arg for arg in args if isinstance(arg, torch.Tensor)] + + run_index = 0 + + # Some kernels don't have path and hash stored + # Using only the name to differentiate between those + if not kernel_path: + kernel_hash = kernel_name + + # Saving only the last N runs of the kernels to avoid bloating the folder + if kernel_hash in inductor_triton_config.debug_dump_kernel_inputs: + run_index = inductor_triton_config.debug_dump_kernel_inputs[kernel_hash] + 1 + + if run_index >= inductor_triton_config.max_kernel_dump_occurrences: + run_index = 0 + + inductor_triton_config.debug_dump_kernel_inputs[kernel_hash] = run_index + + # Default path for kernels with no hash + if not kernel_path: + directory_path = os.path.join(cache_dir(), "unhashed_kernel_inputs") + else: + directory_path = os.path.dirname(kernel_path) + directory_path = f"{directory_path}/{kernel_name}_run_{run_index}" + os.makedirs(directory_path, exist_ok=True) + + log.info( + "Dumping %d tensor(s) for kernel %s to %s", + len(tensor_list), + kernel_name, + directory_path, + ) + + for index, tensor in enumerate(tensor_list): + torch.save(tensor, f"{directory_path}/tensor_{index}.pt") + + +def _combo_has_reduction_subkernel(inductor_meta: InductorMeta) -> bool: + combo_meta = inductor_meta.get("combo_grid_meta") + if combo_meta is None or "heuristic_0" not in combo_meta: + return False + # Stitched combos fix the reduction blocks at codegen time: no-bench uses a + # single config, compile-time autotune passes the chosen blocks via + # default_config and only autotunes launch candidates. Neither runtime-scales + # rblock, so don't add scaling candidates for them. + if "stitched_num_warps" in combo_meta or "stitched_launch_candidates" in combo_meta: + return False + return any( + combo_meta.get(f"heuristic_{i}") == "reduction" + for i in range(combo_meta["num_kernels"]) + ) + + +def _could_dynamic_scale_rblock( + *, + size_hints: list[int] | None, + heuristic_type: HeuristicType, + device_prop: DeviceProperties | None, + inductor_meta: InductorMeta, +) -> bool: + return ( + device_prop is not None + and not inductor_meta.get("deterministic", False) + and inductor_meta.get("dynamic_scale_rblock", True) + and not inductor_meta.get("persistent_reduction") + and heuristic_type == HeuristicType.REDUCTION + # Combo kernels with per-subkernel blocks set size_hints=None but + # carry per-subkernel size hints in combo_grid_meta. + and (size_hints is not None or _combo_has_reduction_subkernel(inductor_meta)) + # Disable for Intel as Triton is not ready to return n_regs for a compiled_binary. + and device_prop.type in ["cuda", "hip"] + and bool(device_prop.major) + and (device_prop.major >= 8 or torch.version.hip) + and device_prop.regs_per_multiprocessor is not None + and device_prop.warp_size is not None + ) + + +def check_autotune_cache( + configs: list[Config], + filename: str | None, + inductor_meta: InductorMeta, + dynamic_scale_rblock_eligible: bool = False, +) -> tuple[list[Config], AutotuneCache | None, dict[str, Any]]: + """ + Given a list of configs, checks autotune cache and return metadata + """ + autotune_cache = None + autotune_cache_info = {} + disabled = inductor_meta.get("force_disable_caches", False) + if ( + not disabled + and filename is not None + and ( + len(configs) > 1 + or inductor_meta.get("coordinate_descent_tuning") + or dynamic_scale_rblock_eligible + ) + and os.environ.get("TRITON_INTERPRET", "0") != "1" + ): + configs_hash = hash_configs(configs) + + from torch._inductor.compile_worker import watchdog + + watchdog.report_phase(watchdog.Phase.QUERYING_CACHE) + autotune_cache = AutotuneCache.create(inductor_meta, filename, configs_hash) + if autotune_cache: + if best_config := autotune_cache.read_best(inductor_meta, configs): + configs = [best_config] + autotune_cache_info["best_config"] = triton_config_to_hashable( + best_config + ) + autotune_cache_info["autotune_cache_state"] = "hit" + + else: + autotune_cache_info["autotune_cache_state"] = "miss" + autotune_cache_info["num_configs"] = len(configs) + if inductor_meta.get("coordinate_descent_tuning"): + autotune_cache_info["coordesc_tuning"] = True + if len(configs) == 1: + # This is the config that coordinate descent tuning started at, which + # is not the same as the final config chosen (i.e. only_config, best_config) + autotune_cache_info["coordesc_tuning_start_config"] = ( + triton_config_to_hashable(configs[0]) + ) + else: + if len(configs) == 1: + autotune_cache_info["autotune_cache_state"] = "only 1 config" + autotune_cache_info["only_config"] = triton_config_to_hashable(configs[0]) + + if disabled: + autotune_cache_info["autotune_cache_state"] = "force_disabled" + log.debug("autotune caching is disabled by config.force_disable_caches") + + return configs, autotune_cache, autotune_cache_info + + +# Sentinel returned by plugin hooks to defer to the next plugin or to the +# default behavior. Tested with ``is DEFER``. +DEFER: Final[object] = object() + + +class CachingAutotunerPlugin: + """Base class for ``CachingAutotuner`` plugins. + + Each hook returns ``DEFER`` to fall through to the next plugin / default + behavior, or any other value to short-circuit ``run()`` with that value. + """ + + def pre_compile(self, autotuner: CachingAutotuner) -> object: + """Fires at the top of ``CachingAutotuner.precompile`` (the + parent-side, non-warm-cache-only path). + + Returning ``DEFER`` lets the standard precompile flow run + (``_precompile_worker`` → ``_make_launchers`` → + ``_dynamic_scale_rblock``). Returning anything else short- + circuits ``precompile`` entirely — the plugin owns compile and + launcher creation from this point on, including any + ``TritonBundler`` interaction (the standard + ``static_triton_bundle_key`` bundling path is skipped). + """ + return DEFER + + def pre_dispatch( + self, + autotuner: CachingAutotuner, + *args: object, + stream: object, + **kwargs: object, + ) -> object: + """Fires before kernel dispatch, ahead of precompile or autotune. + + Note: ``run()``'s steady-state fast path returns ``self._cached_launcher`` + directly once it is populated (after autotune converges to one + launcher), bypassing this hook entirely on subsequent calls. + Plugins that need every-call interception cannot rely on + ``pre_dispatch`` alone. + """ + return DEFER + + def pre_autotune( + self, + autotuner: CachingAutotuner, + *args: object, + stream: object, + **kwargs: object, + ) -> object: + """Fires after precompile when more than one launcher remains, in + place of ``autotune_to_one_config()``. + + Returning non-``DEFER`` short-circuits the *entire* remainder of + ``run()`` — the plugin must perform ``_pre_launch`` / kernel + launch / ``_post_launch`` / ``TritonBundler.put_winner`` / + ``save_gpu_kernel`` and any post-autotune transforms (combo + tuning, coordinate descent) itself, and return the launch + result. Plugins that only want to influence config selection + should mutate ``autotuner.launchers`` and return ``DEFER`` + instead. + """ + return DEFER + + +def get_caching_autotuner_plugins( + autotuner: CachingAutotuner, +) -> list[CachingAutotunerPlugin]: + """Build the list of plugins active for ``autotuner``. + + Each plugin adds an entry here, gated on its own config flag, with + imports kept inside the relevant branch. + """ + plugins: list[CachingAutotunerPlugin] = [] + if autotuner.inductor_meta.get("incremental_autotune", False): + try: + from .fb.incremental import IncrementalAutotunePlugin + + plugins.append(IncrementalAutotunePlugin()) + except ImportError: + pass + return plugins + + +def _resolve_load_device(device: int | None, device_type: str) -> int | None: + # compile-on-one-rank: a None device is the rank-agnostic marker; resolve it to the + # current device at load time so a shared kernel's cubin loads on the running rank's + # GPU rather than a baked compile-time index. CPU has no device index and its + # DeviceGuard is a no-op -- resolving its None to 0 makes the guard call + # exchange_device, which CPU does not implement -- so leave CPU as-is. + if device is not None or device_type == "cpu": + return device + from torch._dynamo.device_interface import get_interface_for_device + + return get_interface_for_device(device_type.replace("hip", "cuda")).current_device() + + +class CachingAutotuner(KernelInterface): + """ + Simplified version of Triton autotuner that has no invalidation + key and caches the best config to disk to improve cold start times. + Unlike the main triton Autotuner, this version can precompile all + configs, and does not rely on the Triton JIT. + """ + + def __init__( + self, + fn, + triton_meta: TritonMeta, # passed directly to triton + configs, + save_cache_hook, + mutated_arg_names: list[str], # see [Note: clone mutated buffers] + optimize_mem, + heuristic_type, + size_hints=None, + inductor_meta: InductorMeta | None = None, # metadata not relevant to triton + custom_kernel=False, # whether the kernel is inductor-generated or custom + filename: str | None = None, + reset_to_zero_arg_names: list[str] | None = None, + autotune_cache_info: dict[str, Any] | None = None, + ): + super().__init__() + + if len(configs) == 0: + raise AssertionError("Non-empty TritonConfig list required for compiling") + # makes sure there are no pre-hooks on any of the triton configs + for cfg in configs: + validate_triton_config(cfg) + + self.fn = fn + self.device_props: DeviceProperties = triton_meta["device"] + # device may be None under compile-on-one-rank (rank-agnostic); it is resolved to + # the current device at load time (see _resolve_load_device), not baked here. + self.triton_meta: TritonMeta = cast( + TritonMeta, + { + **triton_meta, + "device": self.device_props.index, + "device_type": self.device_props.type, + }, + ) + self.inductor_meta: InductorMeta = ( + {} if inductor_meta is None else inductor_meta + ) + # Add device properties to inductor_meta for use by coordinate descent tuner + self.inductor_meta["warp_size"] = self.device_props.warp_size + self.inductor_meta["max_threads_per_block"] = ( + self.device_props.max_threads_per_block + ) + self.deterministic_mode = self.inductor_meta.get("deterministic", False) + + self.save_cache_hook = save_cache_hook + self.mutated_arg_names = mutated_arg_names + self.reset_to_zero_arg_names = ( + [] if reset_to_zero_arg_names is None else reset_to_zero_arg_names + ) + self.optimize_mem = optimize_mem + cached_config = lookup_autotune_config(size_hints, fn) + self.configs = [cached_config] if cached_config else configs + + self.heuristic_type = heuristic_type + self.custom_kernel = custom_kernel + self.cuda_kernel_saved = False + self.cpu_kernel_saved = False + self.autotune_cache_info = autotune_cache_info + if log.isEnabledFor(logging.DEBUG): + log.debug( + "CachingAutotuner gets %d configs for %s", + len(self.configs), + self.fn.__name__, + ) + for c in self.configs: + log.debug(c) + + self.compile_results: list[_KernelCompileResult] = [] + self.launchers: list[LauncherType] = [] + self.lock = threading.Lock() + self.benchmark_failure_reasons: dict[Any, BenchmarkFailureReason] = {} + if os.getenv("TRITON_CACHE_DIR") is None: + os.environ["TRITON_CACHE_DIR"] = triton_cache_dir( + cast(int, self.triton_meta.get("device", 0)) + ) + log.debug("Triton cache dir: %s", os.environ["TRITON_CACHE_DIR"]) + + self.size_hints = size_hints + self.is_mix_order_reduction = self.inductor_meta.get("RSPLIT_SIZE") is not None + self.coordesc_tuner = CoordescTuner( + is_mm=False, + is_native_matmul=triton_meta.get("native_matmul", False), + is_mix_order_reduction=self.is_mix_order_reduction, + name=self.fn.__name__, + size_hints=size_hints, + inductor_meta=self.inductor_meta, + ) + self.filename = filename + + # used for profiling + self.kernel_hash: str = "" + + # Kernels are stored in the codecache with the filename as a hash of the code. + # We rely on this to obtain the kernel hash + if self.filename is not None: + base_name = os.path.basename(self.filename) + if ".py" in base_name: + self.kernel_hash = os.path.splitext(base_name)[0] + + self.precompile_time_taken_ns = 0 + self.autotune_time_taken_ns = 0 + # Dumps the launch configs after autotuning. + self.dump_launch_params = ( + os.environ.get("TORCHINDUCTOR_DUMP_LAUNCH_PARAMS", "0") == "1" + ) + self.dump_launch_tensors = ( + os.environ.get("TORCHINDUCTOR_DUMP_LAUNCH_TENSORS", "0") == "1" + ) + self.kernels_to_dump = os.environ.get( + "TORCHINDUCTOR_KERNELS_TO_DUMP", "" + ).split(",") + + self.triton_interpret = os.environ.get("TRITON_INTERPRET", "0") == "1" + + self._debug_call: _TritonKernelCall | None = None + self._profiler_ctx: _RecordFunctionFast | None = None + + # Cached launcher for fast path — bypasses all preamble after first + # successful steady-state launch. Set to None until populated. + self._cached_launcher: LauncherType | None = None + # Pre-compute static eligibility for launcher caching. These flags + # are set once in __init__ and never change, so we avoid re-checking + # them on every kernel launch. + self._cache_eligible = ( + not self.triton_interpret + and not self.dump_launch_params + and not self.dump_launch_tensors + ) + + self._plugins = get_caching_autotuner_plugins(self) + + # Compile-time info included in runtime logginging + self.compile_id: CompileId | None = None + self.is_backward = False + + # Mode for launch grid calculation + self.grid_mode: Literal["python", "cpp"] = "python" + + @staticmethod + def _close_compiled_kernel(kernel: Any) -> None: + if kernel is None: + return + close = getattr(kernel, "close", None) + if close is not None: + close() + return + module = getattr(kernel, "module", None) + if module is not None: + # Transitional fallback for Triton versions before CompiledKernel.close(). + # Their __del__ unloads the module and clears kernel.module, so repeated + # calls from our idempotent benchmark cleanup paths are harmless. + delete = getattr(kernel, "__del__", None) + if delete is not None: + delete() + + def release_benchmark_artifacts(self) -> None: + for launcher in self.launchers: + kernel = getattr(launcher, "__self__", None) + self._close_compiled_kernel(kernel) + + for result in self.compile_results: + self._close_compiled_kernel(getattr(result, "kernel", None)) + + self.launchers = [] + self.compile_results = [] + self.benchmark_failure_reasons.clear() + self._cached_launcher = None + self._debug_call = None + + def is_statically_launchable(self): + """ + Checks if every compiled kernel is statically launchable, which + allows us to efficiently cache it in FXGraphCache + """ + if not self.compile_results: + return False + return all( + isinstance(x, StaticTritonCompileResult) for x in self.compile_results + ) + + def recheck_autotune_cache( + self, reload_kernel_from_src: Callable[[], CachingAutotuner] + ) -> None: + """ + On cache load on static autotuner, we need to recheck the autotune cache, since + a best config could have been found from a previous run + """ + if not self.is_statically_launchable(): + raise AssertionError("Expected statically launchable kernel") + + configs = [result.config for result in self.compile_results] + + (cached_configs, _, autotune_cache_info) = check_autotune_cache( + configs, + self.filename, + self.inductor_meta, + dynamic_scale_rblock_eligible=self._could_rblock_scale, + ) + self.autotune_cache_info = autotune_cache_info + # I.e. there was an autotune cache hit + if len(cached_configs) == 1: + best_config = cached_configs[0] + found_by_coordesc = getattr(best_config, "found_by_coordesc", False) + # Grab the best compiled config, if it's in the list of available ones + best_config_hash = triton_config_to_hashable(best_config) + + for compile_result in self.compile_results: + if triton_config_to_hashable(compile_result.config) == best_config_hash: + compile_result.config.found_by_coordesc = found_by_coordesc + self.compile_results = [compile_result] + return + + # The best config isn't in our compile results — it was + # found dynamically (coordesc tuning or _dynamic_scale_rblock) + # after the static autotuner was saved. Compile it now. + with dynamo_timed("CachingAutotuner.slow_precompile_config"): + if self.fn.fn is None: + self.fn = reload_kernel_from_src().fn + self.compile_results = [self._precompile_config(best_config)] + + def set_compile_info(self, compile_id: CompileId | None, is_backward: bool) -> None: + self.compile_id = compile_id + self.is_backward = is_backward + + def precompile( + self, + warm_cache_only=False, + reload_kernel: Callable[[], CachingAutotuner] | None = None, + static_triton_bundle_key: str | None = None, + ): + if warm_cache_only: + self._precompile_worker() + return + with self.lock: + # Helper function for reloading a kernel generated in a worker + # in the parent class. Normally we don't need to reload the kernel + # in the parent process, but in certain cases (coordesc tuning, dynamic_scale_rblock), + # we need to actually run compilation on the parent process + if reload_kernel is not None: + self._reload_kernel = reload_kernel + # Plugin opt-out: ``pre_compile`` returning anything other + # than ``DEFER`` means the plugin owns compile + launcher + # creation entirely. We return without running + # ``_precompile_worker`` / ``_make_launchers`` / + # ``_dynamic_scale_rblock``. + for plugin in self._plugins: + if plugin.pre_compile(self) is not DEFER: + return + self._precompile_worker() + if static_triton_bundle_key is not None and self.is_statically_launchable(): + TritonBundler.put_static_autotuner(static_triton_bundle_key, self) + self._make_launchers() + self._dynamic_scale_rblock() + + def _precompile_worker(self): + if self.compile_results: + for result in self.compile_results: + TritonBundler.put( + triton_hash_to_path_key(result.kernel.hash), # type: ignore[attr-defined] + cast(int, self.triton_meta.get("device", 0)), + ) + return + if self.launchers: + raise AssertionError("launchers already populated before precompile") + if not self.configs: + raise NoTritonConfigsError("No triton configs are available") + + compile_results = [] + exc = None + for c in self.configs: + try: + compile_results.append(self._precompile_config(c)) + except (OutOfResources, PTXASError, IntelGPUError) as e: + exc = e + if len(compile_results) == 0: + raise NoTritonConfigsError( + f"No valid triton configs. {type(exc).__name__}: {exc}" + ) + self.compile_results = compile_results + self.configs = None + + @functools.cached_property + def _could_rblock_scale(self) -> bool: + """Whether ``_dynamic_scale_rblock`` should attempt occupancy- + driven rblock halving for this autotuner. + """ + if "strict_sum_rblock" in self.inductor_meta: + # Strict numerics: don't scale/tune R0_BLOCK for reductions (it shifts the order). + return False + return _could_dynamic_scale_rblock( + size_hints=self.size_hints, + heuristic_type=self.heuristic_type, + device_prop=self.device_props, + inductor_meta=self.inductor_meta, + ) + + @functools.cached_property + def _combo_has_reduction_subkernel(self) -> bool: + """True for a combo kernel (per-subkernel blocks) with a non-persistent + reduction sub-kernel; these carry size_hints=None at the autotuner level.""" + return _combo_has_reduction_subkernel(self.inductor_meta) + + def _iter_rblock_scale_candidates(self): + """Yield new configs with halved rblock for occupancy improvement. + + Caller is responsible for gating on ``self._could_rblock_scale``. + """ + # TODO(jansel): we should find a way to move this extra compile into the worker process + # Currently it relies on _make_launchers(), which requires a cuda context, to populate nreg. + device_prop = self.device_props + if not device_prop.regs_per_multiprocessor: + raise AssertionError("device_prop.regs_per_multiprocessor is not set") + if not device_prop.max_threads_per_multi_processor: + raise AssertionError( + "device_prop.max_threads_per_multi_processor is not set" + ) + if not device_prop.multi_processor_count: + raise AssertionError("device_prop.multi_processor_count is not set") + if device_prop.warp_size is None: + raise AssertionError("device_prop.warp_size is not set") + seen_config_hashes: OrderedSet[Hashable] | None = None + warp_size = device_prop.warp_size + # Combo kernels with per-subkernel blocks pass size_hints=None and carry + # per-subkernel xnumel_i / XBLOCK_i in combo_grid_meta. Only total_block + # is derived differently; reduction-block selection and the occupancy + # logic below are shared with the single-kernel path. + combo_meta = ( + self.inductor_meta.get("combo_grid_meta") + if self.size_hints is None + else None + ) + for result in self.compile_results: + triton_config = result.config + compiled_binary = result.kernel + if combo_meta is not None: + # Combo grid sums each sub-kernel's blocks (SequentialFlatten); + # xnumel_i is None for dynamic shapes, so those dims are skipped. + total_block = 0 + for i in range(combo_meta["num_kernels"]): + xnumel = combo_meta.get(f"xnumel_{i}") + if isinstance(xnumel, int): + xblock = triton_config.kwargs.get(f"XBLOCK_{i}", 1) + total_block += (xnumel + xblock - 1) // xblock + else: + if len(self.size_hints) < 2: + raise AssertionError( + f"Expected at least 2 size_hints, got {len(self.size_hints)}" + ) + xblock = triton_config.kwargs.get("XBLOCK", 1) + total_block = (self.size_hints["x"] + xblock - 1) // xblock + # Tunable reduction blocks. Combo's per-subkernel kwargs are suffixed + # (R0_BLOCK_0, R1_BLOCK_0, R0_BLOCK_1, ...); persistent/pointwise + # sub-kernels carry no R*_BLOCK kwarg so they drop out naturally. Same + # rule for both paths. + reduction_kwargs = [ + kwarg for kwarg in triton_config.kwargs if kwarg.startswith("R") + ] + if not reduction_kwargs: + continue + rblocks = [triton_config.kwargs[kwarg] for kwarg in reduction_kwargs] + nreg = getattr(compiled_binary, "n_regs", None) + if nreg is None: + continue + + # make sure rblocks are not too small + if conditional_product(*rblocks) <= 64: + continue + + # each SM of A100 has 65536 32-bit registers. To maximize + # the theoretical occupancy, we need run 2048 threads on each + # SM. So each thread should use no more than 65536 / 2048 + # = 32 registers. In cases where occupancy matters, and each + # thread uses too many registers, reduce R0_BLOCK to reduce + # the register usage. + # For kernel https://gist.github.com/shunting314/e4cccc031fe30d378b9b23c08c238cbd + # from PLBartForCausalLM, latency improve from + # 7.795ms to 4.883ms. + # + if ( + nreg + <= device_prop.regs_per_multiprocessor + // device_prop.max_threads_per_multi_processor + ): + continue + + nreg_per_warp = nreg * warp_size + nreg_per_block = nreg_per_warp * triton_config.num_warps + + # Previously we set max_blocks_per_sm to 'max_threads_per_multi_processor / (warp_size * num_warps)' + # The formula below is a tighter upper bound since we have the assumption that + # nreg > device_prop.regs_per_multiprocessor // device_prop.max_threads_per_multi_processor + # due to the if condition above and: + # regs_per_multiprocessor / nreg_per_block + # = regs_per_multiprocessor / (nreg * warp_size * num_warps) + # < regs_per_multiprocessor / ((regs_per_multiprocessor / max_threads_per_multi_processor) * warp_size * num_warps) + # = max_threads_per_multi_processor / (warp_size * num_warps) + # Using a tighter upper bound can reveal more optimization opportunities. + max_blocks_per_sm = max( + device_prop.regs_per_multiprocessor // nreg_per_block, 1 + ) + + if total_block <= max_blocks_per_sm * device_prop.multi_processor_count: + # no need to improve occupancy + continue + + # Reduce the largest Rn_BLOCK by a factor of 2. + largest_rkwarg: str = max( + reduction_kwargs, key=triton_config.kwargs.__getitem__ + ) + new_rblock = triton_config.kwargs[largest_rkwarg] // 2 + min_rblock = self.inductor_meta.get("min_rblock") + if ( + min_rblock is not None + and largest_rkwarg.startswith("R0_BLOCK") + and new_rblock < min_rblock + ): + continue + new_config = copy.deepcopy(triton_config) + new_config.kwargs[largest_rkwarg] = new_rblock + + if seen_config_hashes is None: + seen_config_hashes = OrderedSet( + [triton_config_to_hashable(x.config) for x in self.compile_results] + ) + new_config_hash = triton_config_to_hashable(new_config) + if new_config_hash in seen_config_hashes: + continue + seen_config_hashes.add(new_config_hash) + log.debug( + "Dynamically scale down %s from TritonConfig(%s) and get a new TritonConfig(%s)", + largest_rkwarg, + triton_config, + new_config, + ) + self._ensure_kernel_loaded() + yield new_config + + # Combo kernels additionally offer an all-reduction-blocks-halved + # candidate. A combo's register count is the max across sub-kernel + # branches, so a balanced combo (sub-kernels with similar register + # use) only drops below the occupancy limit when every branch + # shrinks, not just the largest. + if combo_meta is not None and len(reduction_kwargs) > 1: + all_halved = copy.deepcopy(triton_config) + too_small = False + for kwarg in reduction_kwargs: + halved = triton_config.kwargs[kwarg] // 2 + # A block that is already 1 would halve to 0 (invalid -> Triton + # compile error). Skip the candidate rather than emit a 0 block. + if halved < 1 or ( + min_rblock is not None + and kwarg.startswith("R0_BLOCK") + and halved < min_rblock + ): + too_small = True + break + all_halved.kwargs[kwarg] = halved + if not too_small: + all_hash = triton_config_to_hashable(all_halved) + if all_hash not in seen_config_hashes: + seen_config_hashes.add(all_hash) + self._ensure_kernel_loaded() + yield all_halved + + def _dynamic_scale_rblock(self): + if ( + self.autotune_cache_info + and self.autotune_cache_info.get("autotune_cache_state") == "hit" + ): + return + if not self._could_rblock_scale: + return + for new_config in self._iter_rblock_scale_candidates(): + self.compile_results.append(self._precompile_config(new_config)) # noqa: B909 + self._make_launchers() + + def compile_by_disabling_pipelining(self, config): + self._ensure_kernel_loaded() + cfg = copy.deepcopy(config) + cfg.num_stages = 1 + if "NUM_STAGES" in cfg.kwargs: + cfg.kwargs["NUM_STAGES"] = 1 + result = self._precompile_config(cfg) + self.compile_results = [result] + return result.make_launcher() + + def _make_launcher( + self, compile_result: _KernelCompileResult + ) -> tuple[LauncherType, None] | tuple[None, Exception]: + """Create a launcher from a compile result. + + Caller must hold a DeviceGuard for the target device. + Returns (launcher, None) on success, or (None, exception) on failure. + """ + try: + return compile_result.make_launcher(), None + except ( + OutOfResources, + PTXASError, + torch.cuda.OutOfMemoryError, + IntelGPUError, + ) as e: + return None, e + + def _make_launchers(self): + if len(self.launchers) == len(self.compile_results): + return + + from torch._dynamo.device_interface import DeviceGuard + + device_interface = self.get_device_interface() + launchers = [] + exc = None + try: + load_device = _resolve_load_device( + self.triton_meta["device"], self.device_props.type + ) + # DeviceGuard ensures each launcher's binary loads onto the right device. + with DeviceGuard(device_interface, cast(int, load_device)): + for result in self.compile_results: + launcher, exc = self._make_launcher(result) + if launcher is not None: + launchers.append(launcher) + if len(launchers) == 0: + result = self.compile_results[-1] + config = result.config + if ( + isinstance(exc, (OutOfResources, torch.cuda.OutOfMemoryError)) + and ( + config.num_stages > 1 + or config.kwargs.get("NUM_STAGES", 1) > 1 + ) + and self.inductor_meta.get("dynamic_disable_pipelining", True) + ): + self.launchers = [self.compile_by_disabling_pipelining(config)] + return + raise RuntimeError( + f"No valid triton configs. {type(exc).__name__}: {exc}" + ) + self.launchers = launchers + finally: + # Drop the retained failed-config exception. Holding it keeps its traceback + # (and thus the whole benchmarking frame chain up to do_bench via f_back) + # alive; do_bench's 256MB L2-flush buffer would then leak one-per-autotuned + # kernel until cyclic GC runs -- which never happens under gc.disable(). We + # only needed exc's type/message above. + exc = None + + def _prune_compile_results_to_launcher(self, launcher: LauncherType) -> None: + if not self.compile_results: + return + + launcher_config = launcher.config # type: ignore[attr-defined] + for result in self.compile_results: + if result.config is launcher_config: + self.compile_results = [result] + return + + launcher_config_hash = triton_config_to_hashable(launcher_config) + for result in self.compile_results: + if triton_config_to_hashable(result.config) == launcher_config_hash: + self.compile_results = [result] + return + + raise AssertionError( + f"Autotuned launcher config does not match any compile result: {launcher_config}" + ) + + def _ensure_kernel_loaded(self) -> None: + """Reload the kernel in the parent process if needed. + + When this autotuner was compiled in a worker subprocess and + unpickled into the parent, ``prepare_for_pickle`` cleared + ``self.fn.fn`` so the worker's JITFunction wouldn't follow + across the pickle. Any path that needs the live function in + the parent (coordesc, dynamic_scale_rblock, kernel_autotune + metrics) must reload first via the stashed ``_reload_kernel`` + callback. No-op when the function is already present. + """ + if self.fn.fn is None: + if not hasattr(self, "_reload_kernel"): + raise AssertionError("_reload_kernel attribute not set") + if not callable(self._reload_kernel): + raise AssertionError("_reload_kernel must be callable") + self.fn = self._reload_kernel().fn + + def prepare_for_pickle(self) -> tuple[Any, ...]: + """Drop stuff from triton.JITFunction that does not pickle. + This must be called after precompile so that these things are no longer needed. + Returns a tuple of old values + """ + old_values = ( + self.fn.fn, + self.fn.__globals__, + self.fn.used_global_vals, + self.fn.repr, + self.launchers, + getattr(self.fn, "_hash_lock", None), + self.benchmark_failure_reasons, + ) + self.fn.fn = None + self.fn.__globals__ = None + self.fn.used_global_vals = None + self.fn.repr = _ConstRepr(self.fn.repr(self.fn)) + self.launchers = [] + self._cached_launcher = None + self.benchmark_failure_reasons = {} + self.fn._hash_lock = None + return old_values + + def restore_after_unpickle(self, old_values: tuple[Any, ...] | None) -> None: + self._cached_launcher = None + if old_values: + ( + self.fn.fn, + self.fn.__globals__, + self.fn.used_global_vals, + self.fn.repr, + self.launchers, + self.fn._hash_lock, + self.benchmark_failure_reasons, + ) = old_values + else: + # even if we don't need/have specific values, we do need the + # _hash_lock to be a valid RLock + self.fn._hash_lock = threading.RLock() + + def prepare_for_caching(self) -> None: + """ + Statically Launched CUDA Kernels have a raw cubin on them + that we don't need to store in the cache(since TritonBundler handles the collection for us), + this behavior is gated by keep_static_cubin_raw config. + """ + # Only cubin_raw must be retained: __getstate__ already nulls cubin_path + # on every serialize, so a cold-container load rehydrates the cubin from + # cubin_raw (reload_cubin_path calls reload_cubin_from_raw) instead of + # pointing at a missing file. + if torch._inductor.config.keep_static_cubin_raw: + return + for result in self.compile_results: + if isinstance(result, StaticTritonCompileResult): + # Don't save this in the inductor cache, as it is very large + result.kernel.cubin_raw = None + + def __getstate__(self) -> dict[str, Any]: + if self.launchers: + raise AssertionError("pickle should not be called after make_launchers()") + return { + **self.__dict__, + "lock": None, + "_plugins": [], + } + + def __setstate__(self, state: dict[str, Any]) -> None: + self.__dict__.update(state) + self.lock = threading.Lock() + self._plugins = get_caching_autotuner_plugins(self) + + def get_device_interface(self): + # this code cannot run in compile workers, because it imports from torch + from torch._dynamo.device_interface import get_interface_for_device + + return get_interface_for_device(self.device_props.type.replace("hip", "cuda")) + + def _create_compile_meta(self, cfg: Config) -> dict[str, Any]: + """ + Create compilation metadata for a given autotuner config. This involves + processing the Config kwargs so that the kwargs that are not part + of the triton signature are passed in as options to triton.compile + instead + """ + compile_meta: dict[str, Any] = cast( + dict[str, Any], copy.deepcopy(self.triton_meta) + ) + compile_meta["num_warps"] = cfg.num_warps + compile_meta["num_stages"] = cfg.num_stages + + cfg_kwargs = {**cfg.kwargs} + if self.device_props.type == "hip": + kernel_arg_names = OrderedSet(compile_meta["signature"]) + combo_meta = self.inductor_meta.get("combo_grid_meta") or {} + kernel_arg_names.update(combo_meta.get("block_arg_names", ())) + # AttrsDescriptor signatures omit constexprs, so combo block argument + # names are carried separately in combo_grid_meta. + # Any HIP config kwarg that is *not* in that set is not a kernel + # argument at all; it is a backend compile option that should be forwarded + # to triton.compile via `options`, not materialized as a constexpr. + backend_options = { + key: value + for key, value in cfg_kwargs.items() + if key not in kernel_arg_names + } + cfg_kwargs = { + key: value + for key, value in cfg_kwargs.items() + if key in kernel_arg_names + } + if backend_options: + # Stash backend-only options separately so they do not get mixed into + # `constants`, which are interpreted as signature-bound constexpr args. + compile_meta["backend_options"] = { + **compile_meta.get("backend_options", {}), + **backend_options, + } + compile_meta["constants"].update(cfg_kwargs) + + for i in get_constexprs(self.fn): + arg_name = self.fn.arg_names[i] + if arg_name not in compile_meta["constants"] and ( + arg_name == "num_warps" or arg_name == "num_stages" + ): + compile_meta["constants"][arg_name] = getattr(cfg, arg_name) + if HAS_WARP_SPEC: + compile_meta["num_consumer_groups"] = getattr(cfg, "num_consumer_groups", 0) + compile_meta["num_buffers_warp_spec"] = getattr( + cfg, "num_buffers_warp_spec", 0 + ) + + host_tma_args = self.inductor_meta.get("host_tma_descriptor_args") + if host_tma_args: + all_constants = compile_meta["constants"] + for key in list(compile_meta["signature"]): + desc_info = host_tma_args.get(key) + if desc_info is None or not isinstance(desc_info, dict): + continue + block_shape_vals = _resolve_dims( + desc_info["block_shape"], cfg_kwargs, all_constants + ) + shape_vals = _resolve_dims( + desc_info["shape"], cfg_kwargs, all_constants + ) + stride_vals = _resolve_dims( + desc_info["strides"], cfg_kwargs, all_constants + ) + if ( + block_shape_vals is None + or shape_vals is None + or stride_vals is None + or any(v <= 0 for v in block_shape_vals) + ): + continue + ty = compile_meta["signature"][key] + if isinstance(ty, str) and ty.startswith("*"): + dtype_str = ty[1:] + elif isinstance(ty, str) and ty.startswith("tensordesc<"): + dtype_str = ty.split("<")[1].split("[")[0] + else: + continue + compile_meta["signature"][key] = ( + f"tensordesc<{dtype_str}{list(block_shape_vals)}>" + ) + + compile_meta["debug"] = _should_enable_triton_debug_asserts(self.inductor_meta) + + # device type will be "hip" rather than "cuda" here + compile_meta["device_type"] = self.device_props.type + compile_meta["cc"] = self.device_props.cc + + for k in tlx_only_cuda_options(): + if v := getattr(cfg, k, None): + compile_meta[k] = v + + return compile_meta + + def _create_compile_options( + self, cfg: Config, compile_meta: dict[str, Any] + ) -> dict[str, Any]: + """ + Create options to pass to triton.compile based on the compile metadata + and the given config. + """ + options = { + "num_warps": compile_meta["num_warps"], + "num_stages": compile_meta["num_stages"], + "debug": compile_meta["debug"], + "sanitize_overflow": False, # turn off additional asserts added for overflow checks + } + if "enable_fp_fusion" in compile_meta: + options["enable_fp_fusion"] = compile_meta["enable_fp_fusion"] + if HAS_WARP_SPEC: + options.update( + { + "num_consumer_groups": compile_meta.get("num_consumer_groups", 0), + "num_buffers_warp_spec": compile_meta.get( + "num_buffers_warp_spec", 0 + ), + } + ) + if self.device_props.type == "cuda": + options.update( + { + "launch_cooperative_grid": compile_meta.get( + "launch_cooperative_grid", False + ), + "launch_pdl": compile_meta.get("launch_pdl", False), # True + } + ) + if compile_meta.get("disable_ftz", False): + options["enable_reflect_ftz"] = False + for k in tlx_only_cuda_options(): + if v := getattr(cfg, k, None): + options[k] = v + # Backend options are consumed by Triton out-of-band from the kernel + # signature. They are intentionally *not* present in `constants`. + options.update(compile_meta.get("backend_options", {})) + + if self.device_props.type == "xpu" and XPU_KERNEL_FORMAT == "zebin": + options["generate_native_code"] = True + + return options + + def _precompile_config( + self, cfg: Config, *, cc_override: str | int | None = None + ) -> _KernelCompileResult: + """Ahead of time compile a given autotuner config.""" + compile_meta = self._create_compile_meta(cfg) + if cc_override is not None: + compile_meta["cc"] = cc_override + + if self.device_props.type == "cpu": + triton_helpers.set_driver_to_cpu() + else: + triton_helpers.set_driver_to_gpu() + + if not ASTSource: + raise RuntimeError("Installed triton version too old, please upgrade") + + compile_args = ( + ASTSource( + self.fn, + compile_meta["signature"], + compile_meta["constants"], + compile_meta["configs"][0], + ), + ) + + if self.device_props.type == "mtia": + from mtia.host_runtime.torch_mtia.acc_flags import ( # type: ignore[import-not-found] + build_codename, + ) + + arch = build_codename() + else: + arch = compile_meta["cc"] + + target = GPUTarget( + compile_meta["device_type"], + arch, + self.device_props.warp_size_or_default, + ) + + options = self._create_compile_options(cfg, compile_meta) + + compile_kwargs = { + "target": target, + "options": options, + } + + try: + binary = triton.compile(*compile_args, **compile_kwargs) + except Exception: + log.exception( + "Triton compilation failed: %s\n%s\nmetadata: %s", + self.inductor_meta.get("kernel_name", "triton_"), + self.fn.src, + compile_meta, + ) + raise + + # Simulate JIT Hook call + if ( + torch._inductor.config.run_jit_post_compile_hook + and knobs + and getattr(knobs.runtime, "jit_post_compile_hook", None) + ): + try: + hook = knobs.runtime.jit_post_compile_hook + + # base args everyone should get + call_kwargs = dict( + key=getattr(self.fn, "cache_key", self.kernel_hash or str(self.fn)), + repr=getattr(self.fn, "src", None), + fn=self.fn, + compile=binary, + is_manual_warmup=False, + already_compiled=True, + ) + + # only add inductor_args if the hook takes it + sig = inspect.signature(hook) + params = sig.parameters + if "inductor_args" in params and "config_args" in self.inductor_meta: + call_kwargs["inductor_args"] = self.inductor_meta["config_args"] + + hook(**call_kwargs) + except Exception: + log.exception("jit_post_compile_hook failed") + + TritonBundler.put( + triton_hash_to_path_key(binary.hash), + cast(int, self.triton_meta.get("device", 0)), + ) + # If the binary has a cubin file to directly launch, save it on the binary + static_launcher = StaticTritonCompileResult.can_statically_launch( + binary, self.inductor_meta, self.triton_meta, self.heuristic_type + ) + + if static_launcher is not None: + result = StaticTritonCompileResult( + static_launcher, cfg, compile_meta, self.inductor_meta + ) + return result + + return TritonCompileResult(binary, cfg, compile_meta, self.inductor_meta) + + def bench(self, launcher, *args, with_profiler=False, **kwargs): + """Measure the performance of a given launcher.""" + # we don't skip configs with spilled registers when auto-tuning custom + # (user-written) Triton kernels, as (i) we don't have any knowledge or + # control over the kernel code; (ii) there is empirical evidence that + # for some (complicated) custom Triton kernels, a register-spilling + # config may yield the best latency. + if ( + not self.custom_kernel + and launcher.n_spills is not None + and launcher.n_spills + > self.inductor_meta.get("spill_threshold", 32 if torch.version.hip else 16) + ): + log.debug( + "Skip config %s because of register spilling: %d", + launcher.config, + launcher.n_spills, + ) + self.benchmark_failure_reasons[launcher] = ( + BenchmarkFailureReason.REGISTER_SPILLING + ) + return float("inf") + + device_interface = self.get_device_interface() + + cpu_copies = self.copy_args_to_cpu_if_needed(*args, **kwargs) + + def kernel_call(): + # Resolve the raw stream at call time rather than at closure-creation + # time so that CUDA graph capture on a different stream works correctly. + stream = device_interface.get_raw_stream(device_interface.current_device()) + cloned_args, cloned_kwargs = self.maybe_clone_args( + cpu_copies, *args, **kwargs + ) + kernel_name = self.inductor_meta.get("kernel_name", "triton kernel") + # reset to zero before evaluating any config + self.reset_to_zero_args(*args, **kwargs) + if autograd_profiler._is_profiler_enabled: + profiler_kwargs = self.get_profiler_kwargs(stream, launcher) + with torch._C._profiler._RecordFunctionFast( + kernel_name, + cloned_args, + profiler_kwargs, + ): + try: + launcher( + *cloned_args, + **cloned_kwargs, + stream=stream, + ) + except Exception as e: + if isinstance(e, TypeError): + self._check_launcher_call_args(launcher, cloned_args) + log.error( + "Failed during launch %s with config: %s (num_warps=%s, num_stages=%s, kwargs=%s)", + kernel_name, + launcher.config, + launcher.config.num_warps, + launcher.config.num_stages, + launcher.config.kwargs, + ) + raise + + else: + try: + launcher( + *cloned_args, + **cloned_kwargs, + stream=stream, + ) + except Exception as e: + if isinstance(e, TypeError): + self._check_launcher_call_args(launcher, cloned_args) + log.error( + "Failed during launch %s with config: %s (num_warps=%s, num_stages=%s, kwargs=%s)", + kernel_name, + launcher.config, + launcher.config.num_warps, + launcher.config.num_stages, + launcher.config.kwargs, + ) + raise + self.restore_args_from_cpu(cpu_copies) + + # only use profiler when not already in a profiler instance + if with_profiler and not autograd_profiler._is_profiler_enabled: + from torch._inductor.utils import do_bench_using_profiling + + return do_bench_using_profiling(kernel_call, warmup=10, rep=40) + + benchmark_kwargs = ( + {} + if self.device_props.type == "cpu" + else {"rep": 40, "is_vetted_benchmarking": True} + ) + result = benchmarker.benchmark( + fn=kernel_call, + device=self.device_props.type, + **benchmark_kwargs, # type: ignore[arg-type] + ) + # benchmarker.benchmark() only returns float("inf") when catching an + # "invalid configuration" exception - all other exceptions are re-raised. + # Therefore, if result is inf here, it must be due to invalid config. + if result == float("inf"): + self.benchmark_failure_reasons[launcher] = ( + BenchmarkFailureReason.INVALID_CONFIG + ) + return result + + def copy_args_to_cpu_if_needed(self, *args, **kwargs): + """ + To support benchmarking in the presence of mutated args, we need to avoid + autotuning contaminating them. We try to pass cloned args to the kernel. + If those clones would increase the peak memory usage, however, we instead + copy to cpu and restore them after each iteration. Figure out the args + to be copied and do the copying. + """ + if not self.optimize_mem: + return {} + + copies = {} + try: + if torch.accelerator.current_accelerator() is None: + # No initialized accelerator; skip memory-optimized path + return {} + budget = ( + torch.accelerator.max_memory_allocated() + - torch.accelerator.memory_allocated() + ) + except RuntimeError: + # Possibly a custom CUDA allocator, see https://github.com/pytorch/pytorch/issues/163257 + return {} + + def maybe_copy(name, arg): + if name in self.mutated_arg_names and arg.device.type in ( + "cuda", + "xpu", + ): + nonlocal budget + if not isinstance(arg, torch.Tensor): + raise AssertionError( + f"Expected torch.Tensor for mutated arg, got {type(arg)}" + ) + required_storage_length = compute_required_storage_length( + arg.size(), + arg.stride(), + 0, + ) + size = required_storage_length * arg.element_size() + if size > budget: + cpu_arg = torch.empty_strided( + (required_storage_length,), + (1,), + dtype=arg.dtype, + device="cpu", + pin_memory=True, + ) + cpu_arg.copy_( + arg.as_strided((required_storage_length,), (1,)), + non_blocking=True, + ) + copies[name] = (arg, cpu_arg) + else: + budget -= size + + for name, arg in zip(self.fn.arg_names, args): + maybe_copy(name, arg) + + for name, arg in kwargs.items(): + maybe_copy(name, arg) + + return copies + + def restore_args_from_cpu(self, cpu_copies): + for pair in cpu_copies.values(): + arg, cpu_arg = pair + required_storage_length = compute_required_storage_length( + arg.size(), + arg.stride(), + 0, + ) + arg.as_strided((required_storage_length,), (1,)).copy_( + cpu_arg, non_blocking=True + ) + + def reset_to_zero_args(self, *args, **kwargs): + if not self.reset_to_zero_arg_names: + return + for i, arg in enumerate(args): + if self.fn.arg_names[i] in self.reset_to_zero_arg_names: + if not isinstance(arg, torch.Tensor): + raise AssertionError( + "self.reset_to_zero_arg_names should only contain valid argument names" + ) + arg.zero_() + + for name, arg in kwargs.items(): + if name in self.reset_to_zero_arg_names: + if not isinstance(arg, torch.Tensor): + raise AssertionError( + "self.reset_to_zero_arg_names should only contain valid argument names" + ) + arg.zero_() + + def maybe_clone_args( + self, exclude: Container[str], *args, **kwargs + ) -> tuple[list[Any], dict[str, Any]]: + """ + Prepare new args and kwargs by cloning any in-place buffers + (that are not in the provided exclusion list), to avoid autotune + contaminating them. Avoid cloning the other buffers because it + leads to increased memory usage. + """ + from ..compile_fx import clone_preserve_strides + + def prepare_arg(name, arg): + if name in self.mutated_arg_names and name not in exclude: + if not isinstance(arg, torch.Tensor): + raise AssertionError( + f"Expected torch.Tensor for mutated arg '{name}', got {type(arg)}" + ) + return clone_preserve_strides(arg) + else: + return arg + + cloned_args = [ + prepare_arg(name, arg) + for name, arg in itertools.zip_longest(self.fn.arg_names[: len(args)], args) + ] + cloned_kwargs = {name: prepare_arg(name, arg) for name, arg in kwargs.items()} + return cloned_args, cloned_kwargs + + def clone_args(self, *args, **kwargs) -> tuple[list[Any], dict[str, Any]]: + return self.maybe_clone_args(OrderedSet(), *args, **kwargs) + + @staticmethod + def _close_static_launcher(launcher: LauncherType) -> None: + if not getattr(launcher, "_is_static", False): + return + runner = getattr(launcher, "__globals__", {}).get("runner") + kernel = getattr(runner, "__self__", None) + close = getattr(kernel, "close", None) + if close is not None: + close() + + def _release_static_launchers_except(self, keep_launcher: LauncherType) -> None: + for launcher in self.launchers: + if launcher is not keep_launcher: + self._close_static_launcher(launcher) + if not getattr(keep_launcher, "_is_static", False): + return + keep_hash = getattr(keep_launcher, "cache_hash", None) + if keep_hash is None: + return + keep_results = [ + result + for result in self.compile_results + if isinstance(result, StaticTritonCompileResult) + and triton_hash_to_path_key(result.kernel.hash) == keep_hash + ] + if len(keep_results) == 1: + for result in self.compile_results: + if result is not keep_results[0] and isinstance( + result, StaticTritonCompileResult + ): + close = getattr(result.kernel, "close", None) + if close is not None: + close() + self.compile_results = keep_results + + def _log_autotune_inputs(self, args, kwargs) -> None: + """Log input tensor shapes/dtypes and scalar values for autotuning.""" + kernel_name = self.inductor_meta.get("kernel_name", self.fn.__name__) + signature = self.triton_meta.get("signature", {}) + arg_names = list(signature.keys()) + + autotuning_inputs_log.debug("=" * 60) + autotuning_inputs_log.debug("Autotuning inputs for kernel: %s", kernel_name) + autotuning_inputs_log.debug("=" * 60) + autotuning_inputs_log.debug(" Heuristic type: %s", self.heuristic_type) + autotuning_inputs_log.debug(" Size hints: %s", self.size_hints) + autotuning_inputs_log.debug( + " Num configs to benchmark: %d", len(self.launchers) + ) + autotuning_inputs_log.debug( + " Device: %s (index=%s)", self.device_props.type, self.device_props.index + ) + autotuning_inputs_log.debug("-" * 60) + autotuning_inputs_log.debug("Arguments:") + + for i, arg in enumerate(args): + arg_name = arg_names[i] if i < len(arg_names) else f"arg_{i}" + arg_signature = signature.get(arg_name, "unknown") + if isinstance(arg, torch.Tensor): + autotuning_inputs_log.debug( + " [%d] %s (%s): Tensor(shape=%s, dtype=%s, device=%s, stride=%s, contiguous=%s)", + i, + arg_name, + arg_signature, + tuple(arg.shape), + arg.dtype, + arg.device, + arg.stride(), + arg.is_contiguous(), + ) + elif isinstance(arg, (int, float, bool)): + autotuning_inputs_log.debug( + " [%d] %s (%s): %s (type=%s)", + i, + arg_name, + arg_signature, + arg, + type(arg).__name__, + ) + else: + autotuning_inputs_log.debug( + " [%d] %s (%s): %s (type=%s)", + i, + arg_name, + arg_signature, + repr(arg)[:100], + type(arg).__name__, + ) + + if kwargs: + autotuning_inputs_log.debug("-" * 60) + autotuning_inputs_log.debug("Keyword arguments:") + for k, v in kwargs.items(): + if isinstance(v, torch.Tensor): + autotuning_inputs_log.debug( + " %s: Tensor(shape=%s, dtype=%s, device=%s)", + k, + tuple(v.shape), + v.dtype, + v.device, + ) + else: + autotuning_inputs_log.debug( + " %s: %s (type=%s)", k, v, type(v).__name__ + ) + + autotuning_inputs_log.debug("=" * 60) + + def benchmark_all_configs(self, *args, **kwargs): + with ( + dynamo_timed( + "CachingAutotuner.benchmark_all_configs", + log_pt2_compile_event=True, + metadata={"kernel_name": self.inductor_meta.get("kernel_name")}, + dynamo_compile_column_us="runtime_triton_autotune_time_us", + compile_id=self.compile_id, + is_backward=self.is_backward, + log_waitcounter=True, + waitcounter_name_override="triton_autotuner", + ), + # Temporarily disable due to spam + # compilation_callback.callback_handler.install_callbacks( + # compilation_callback.CallbackTrigger.TRITON_AUTOTUNING, + # str(self.compile_id), + # ), + ): + timings = {} + best_launcher = None + best_timing = float("inf") + for launcher in self.launchers: + timing = self.bench(launcher, *args, **kwargs) + timings[launcher] = timing + # Close losing static launchers eagerly so exhaustive autotuning + # keeps only the current winner and candidate modules loaded. + if best_launcher is None or timing < best_timing: + if best_launcher is not None: + self._close_static_launcher(best_launcher) + best_launcher = launcher + best_timing = timing + else: + self._close_static_launcher(launcher) + + for k, v in timings.items(): + self.coordesc_tuner.cache_benchmark_result(k.config, v) + + if log.isEnabledFor(logging.DEBUG): + log.debug("Benchmark all input configs for %s, get:", self.fn.__name__) + for k, v in timings.items(): + log.debug( + "%s: %f, nreg %d, nspill %d, #shared-mem %s", + k.config, + v, + k.n_regs, + k.n_spills, + k.shared, + ) + + if metrics.is_metric_table_enabled("kernel_autotune"): + self._ensure_kernel_loaded() + + kernel_path = self.fn.fn.__code__.co_filename + kernel_name = self.fn.__name__ + + for k, v in timings.items(): + metrics.log_kernel_autotune_result( + kernel_path, kernel_name, k.config, v + ) + + self.reset_to_zero_args(*args, **kwargs) + return timings + + def autotune_to_one_config(self, *args, **kwargs): + """Execute autotuning to select the optimal kernel configuration.""" + if autotuning_inputs_log.isEnabledFor(logging.DEBUG): + self._log_autotune_inputs(args, kwargs) + + start_time = time.time_ns() + timings = self.benchmark_all_configs(*args, **kwargs) + benchmark_time_taken_ns = time.time_ns() - start_time + + # Check if any configs failed (have inf timing) and log which one was selected + failed_launchers = [ + launcher for launcher, timing in timings.items() if timing == float("inf") + ] + if failed_launchers: + valid_timings = [(k, v) for k, v in timings.items() if v != float("inf")] + if valid_timings: + best_launcher, best_time = min(valid_timings, key=lambda x: x[1]) + + # Count failures by reason + spill_count = sum( + 1 + for launcher in failed_launchers + if self.benchmark_failure_reasons.get(launcher) + == BenchmarkFailureReason.REGISTER_SPILLING + ) + invalid_config_count = sum( + 1 + for launcher in failed_launchers + if self.benchmark_failure_reasons.get(launcher) + == BenchmarkFailureReason.INVALID_CONFIG + ) + + reason_parts = [] + if spill_count > 0: + reason_parts.append(f"{spill_count} register spilling") + if invalid_config_count > 0: + reason_parts.append(f"{invalid_config_count} invalid config") + reason_str = ", ".join(reason_parts) if reason_parts else "unknown" + + log.info( + "Skipped %d/%d configs for %s (%s). Selected: %s (%.4f ms)", + len(failed_launchers), + len(timings), + self.fn.__name__, + reason_str, + best_launcher.config, + best_time, + ) + + best_launcher = builtins.min(timings, key=timings.get) + self._release_static_launchers_except(best_launcher) + self.launchers = [best_launcher] + self._prune_compile_results_to_launcher(best_launcher) + self.autotune_time_taken_ns = ( + self.precompile_time_taken_ns + benchmark_time_taken_ns + ) + + # log the best config + launcher = self.launchers[0] + log.debug( + "Best config for %s: %s: %f, nreg %d, nspill %d, #shared-mem %s", + self.fn.__name__, + launcher.config, + timings[launcher], + launcher.n_regs, + launcher.n_spills, + launcher.shared, + ) + + TritonBundler.put_winner(launcher.cache_hash) + + if self.save_cache_hook: + self.save_cache_hook( + launcher.config, + self.autotune_time_taken_ns, + found_by_coordesc=self.inductor_meta.get( + "coordinate_descent_tuning", False + ), + triton_cache_hash=launcher.cache_hash, + ) + + def _combo_sequential_autotune(self, launcher, *args, **kwargs): + """ + Chain block-size decisions for combo kernels: tune one group at a time, + each step building on the previous winner. + + Phase 1: Tune block sizes with warps/stages fixed from the base config. + Phase 2: Re-tune warps/stages with finalized block sizes. + """ + combo_tuning_groups = self.inductor_meta.get("combo_tuning_groups") + if not combo_tuning_groups: + return launcher + + self._ensure_kernel_loaded() + + combo_meta = self.inductor_meta.get("combo_grid_meta") or {} + block_arg_names = OrderedSet(combo_meta.get("block_arg_names", ())) + best_config = launcher.config + current_kwargs = dict(best_config.kwargs) + base_num_warps = best_config.num_warps + base_num_stages = best_config.num_stages + + start_time = time.time_ns() + best_time = self.bench(launcher, *args, **kwargs) + counters["inductor"]["combo_autotune_bench"] += 1 + self.coordesc_tuner.cache_benchmark_result(launcher.config, best_time) + log.debug( + " Phase 1 baseline: %s warps=%d time=%f", + dict(current_kwargs), + base_num_warps, + best_time, + ) + + # Phase 1: Tune block sizes per sub-kernel (largest first). + # warps/stages stay fixed at base config values. + for gi, group in enumerate(combo_tuning_groups): + member_indices = group["member_indices"] + cfgs = group["configs"] + skip_rblock = group["skip_rblock"] + + if len(cfgs) <= 1: + log.debug(" Phase 1 group %d SK%s: 1 config, skip", gi, member_indices) + continue + + log.debug( + " Phase 1 group %d SK%s: trying %d configs, current_kwargs=%s", + gi, + member_indices, + len(cfgs), + dict(current_kwargs), + ) + for ci, cfg in enumerate(cfgs): + trial_kwargs = dict(current_kwargs) + for idx in member_indices: + _update_combo_kernel_kwargs( + trial_kwargs, cfg.kwargs, idx, skip_rblock, block_arg_names + ) + + if trial_kwargs == current_kwargs: + log.debug(" cfg[%d] skip (same as current)", ci) + continue + + trial_config = triton.Config( + trial_kwargs, + num_warps=base_num_warps, + num_stages=base_num_stages, + ) + + with self.lock: + trial_launcher = self._precompile_config( + trial_config + ).make_launcher() + trial_time = self.bench(trial_launcher, *args, **kwargs) + counters["inductor"]["combo_autotune_bench"] += 1 + self.coordesc_tuner.cache_benchmark_result(trial_config, trial_time) + + improved = trial_time < best_time + log.debug( + " cfg[%d] trial=%s time=%f%s", + ci, + dict(trial_kwargs), + trial_time, + " (BETTER)" if improved else "", + ) + if improved: + best_time = trial_time + launcher = trial_launcher + current_kwargs = trial_kwargs + + log.debug( + " Phase 1 group %d winner: current_kwargs=%s", + gi, + dict(current_kwargs), + ) + + # Phase 2: Re-tune num_warps/num_stages with finalized block sizes. + # Block sizes are now optimal — find the best warp/stage pair for them. + warp_stage_candidates = self.inductor_meta.get("combo_warp_stage_candidates") + log.debug( + " Phase 2: blocks=%s, trying %d warp/stage pairs", + dict(current_kwargs), + len(warp_stage_candidates), + ) + best_warps = launcher.config.num_warps + best_stages = launcher.config.num_stages + for num_warps, num_stages in warp_stage_candidates: + if num_warps == best_warps and num_stages == best_stages: + log.debug( + " warps=%d stages=%d skip (same as current)", + num_warps, + num_stages, + ) + continue + + trial_config = triton.Config( + dict(current_kwargs), + num_warps=num_warps, + num_stages=num_stages, + ) + with self.lock: + trial_launcher = self._precompile_config(trial_config).make_launcher() + trial_time = self.bench(trial_launcher, *args, **kwargs) + counters["inductor"]["combo_autotune_bench"] += 1 + self.coordesc_tuner.cache_benchmark_result(trial_config, trial_time) + + improved = trial_time < best_time + log.debug( + " warps=%d stages=%d time=%f%s", + num_warps, + num_stages, + trial_time, + " (BETTER)" if improved else "", + ) + if improved: + best_time = trial_time + launcher = trial_launcher + best_warps = num_warps + best_stages = num_stages + + log.debug( + "Combo sequential autotune for %s: best config %s, time %f", + self.fn.__name__, + launcher.config, + best_time, + ) + launcher.config.found_by_combo_autotune = True + self.autotune_time_taken_ns += time.time_ns() - start_time + if self.save_cache_hook: + self.save_cache_hook(launcher.config, self.autotune_time_taken_ns) + return launcher + + def save_gpu_kernel(self, stream, launcher): + """Save the selected GPU kernel binary and assembly for AOTI packaging.""" + key = self.inductor_meta.get("kernel_name", None) # unique kernel name + if key is None: + raise AssertionError("kernel_name can not be None") + binary = launcher.bin + + from torch._inductor import config as inductor_config + + target_cc = None + cuda_arch = None + if ( + self.device_props.type == "cuda" + and torch.version.hip is None + and inductor_config.aot_inductor.emit_multi_arch_kernel + ): + from torch._inductor.codegen.cuda import compile_utils as cuda_compile_utils + + cuda_arch = cuda_compile_utils._aoti_cuda_target_arch() + if inductor_config.cuda.arch is not None: + target_cc = cuda_compile_utils._cuda_arch_number(cuda_arch) + device_cc = cuda_compile_utils._cuda_arch_number( + str(self.device_props.cc) + ) + if target_cc == device_cc: + target_cc = None + + if target_cc is not None: + # Autotuning must run kernels compiled for the actual GPU, but AOTI + # needs to package PTX/cubin for the requested deployment target. + # Recompile the selected config for the target arch without loading + # or benchmarking that binary on the current device. + target_result = self._precompile_config( + launcher.config, cc_override=target_cc + ) + if isinstance(target_result, TritonCompileResult): + binary = target_result.kernel + else: + raise RuntimeError( + "AOTI CUDA target-arch packaging requires a Triton binary" + ) + + # Prefer Level 0 launch metadata schema (versioned, stable contract) + # over hasattr probing of CompiledKernel internals. + # TODO: When the AOTI C++ launch path gains cuLaunchKernelEx support for + # CTA clusters, add num_ctas/cluster_dims here from the schema. + # Currently num_ctas is already captured via config_to_dict(launcher.config) + # for scratch space scaling, but is not used in the actual kernel launch. + schema = getattr(binary, "launch_metadata_schema", None) + if schema is not None and inductor_config.use_launch_metadata_schema: + params: dict[str, Any] = { + "mangled_name": schema["entry_name"], + "num_warps": schema["num_warps"], + "shared_mem": schema["shared_mem"], + "stream": stream, + "config": config_to_dict(launcher.config), + "inductor_meta": self.inductor_meta, + "triton_meta": self.triton_meta, + "def_args": launcher.def_args, + "call_args": launcher.call_args, + "global_scratch": launcher.global_scratch, + "profile_scratch": launcher.profile_scratch, + "cuda_arch": cuda_arch, + } + else: + # Fallback: hasattr probing for older Triton versions + params: dict[str, Any] = { + "mangled_name": ( + binary.metadata.name + if hasattr(binary.metadata, "name") + else binary.metadata["name"] + ), + "num_warps": ( + binary.num_warps + if hasattr(binary, "num_warps") + else binary.metadata.num_warps + ), + "shared_mem": ( + binary.shared + if hasattr(binary, "shared") + else binary.metadata.shared + ), + "stream": stream, + "config": config_to_dict(launcher.config), + "inductor_meta": self.inductor_meta, + "triton_meta": self.triton_meta, + "def_args": launcher.def_args, + "call_args": launcher.call_args, + "global_scratch": launcher.global_scratch, + "profile_scratch": launcher.profile_scratch, + "cuda_arch": cuda_arch, + } + + from torch._inductor.codecache import CudaKernelParamCache + + bin_type = {"hip": "hsaco", "xpu": XPU_KERNEL_FORMAT}.get( + self.device_props.type, "cubin" + ) + kernel_binary = binary.asm[bin_type] + + # ROCm multi-arch: capture LLVM IR + if torch.version.hip and inductor_config.aot_inductor.emit_multi_arch_kernel: + # Multi-arch ROCm: Capture LLVM IR for cross-architecture compilation + asm_type = "ll" + + # llir is the key to obtain LLVM IR from triton + asm = binary.asm.get("llir", None) + + # CRITICAL: Multi-arch compilation cannot proceed without LLVM IR + # Fail fast with clear error message pointing to the issue + if not asm: + available_keys = list(binary.asm.keys()) + raise RuntimeError( + f"ROCm multi-arch requires LLVM IR, but none found. " + f"Available keys: {available_keys}. " + f"Triton may need to be patched to emit LLVM IR." + ) + + # Everything else: capture architecture-specific assembly + else: + asm_type = {"hip": "amdgcn", "cuda": "ptx", "xpu": "spv"}.get( + self.device_props.type + ) + asm = binary.asm.get(asm_type, None) + + CudaKernelParamCache.set(key, params, kernel_binary, bin_type, asm, asm_type) + self.cuda_kernel_saved = True + + def save_cpu_kernel(self, launcher): + """AOTI counterpart of save_gpu_kernel for CPU Triton kernels. + + Captures the kernel and launcher `.so` files into + `CpuTritonKernelCache` for `CppWrapperCpu` to dlopen at runtime. + Triton CPU backend needs to emit `run_from_nativert`. + """ + from torch._inductor.codecache import CpuTritonKernelCache + + key = self.inductor_meta.get("kernel_name") + if key is None: + raise AssertionError("kernel_name can not be None") + + compiled = launcher.bin + kernel_bytes = compiled.asm.get("so") + launcher_bytes = compiled.asm.get("launcher.so") + if kernel_bytes is None or launcher_bytes is None: + raise RuntimeError( + f"CPU AOTI requires a Triton CPU backend that emits a launcher " + f"`.so` exporting `run_from_nativert`; kernel '{key}' has " + f"compiled.asm keys {list(compiled.asm.keys())}." + ) + kernel_symbol = ( + compiled.metadata.name + if hasattr(compiled.metadata, "name") + else compiled.metadata["name"] + ) + signature = compiled.src.signature + + CpuTritonKernelCache.set( + key, + kernel_bytes=kernel_bytes, + launcher_bytes=launcher_bytes, + kernel_symbol=kernel_symbol, + signature=signature, + ) + self.cpu_kernel_saved = True + + @functools.cached_property + def _should_coordesc_tune(self) -> bool: + """Whether this autotuner is eligible for coordinate descent tuning.""" + if self.heuristic_type in ( + HeuristicType.TEMPLATE, + HeuristicType.USER_AUTOTUNE, + HeuristicType.FIXED, + ): + return False + # Deterministic mode (and strict numerics) forbid tuning RBLOCK / num_warps for + # reductions because those knobs shift numerics. + if ( + self.deterministic_mode or "strict_sum_rblock" in self.inductor_meta + ) and self.heuristic_type in ( + HeuristicType.REDUCTION, + HeuristicType.PERSISTENT_REDUCTION, + HeuristicType.SPLIT_SCAN, + ): + return False + return True + + def coordinate_descent_tuning(self, launcher, *args, **kwargs): + """ + Coordinate descent tuning can be run with or without max-autotune. + + The only difference between these two is the starting config for coordinate_descent tuning. + E.g., assuming regular autotune only get one config C1; while max-autotune get 4 configs C1, C2, C3, C4 + and max-autotune figure out C3 is the best. + + Then if coordinate descent tuning is run with max-autotune disabled, it will start from C1; + while if coordinate descent tuning is run with max-autotune enabled, it will start from C3. + """ + if not self._should_coordesc_tune: + return launcher + + with dynamo_timed( + "CachingAutotuner.coordinate_descent_tuning", + # These generate too many pt2_compile_event logs: + log_pt2_compile_event=False, + metadata={"kernel_name": self.inductor_meta.get("kernel_name")}, + dynamo_compile_column_us="runtime_triton_autotune_time_us", + compile_id=self.compile_id, + is_backward=self.is_backward, + log_waitcounter=True, + waitcounter_name_override="triton_autotuner", + ): + return self._coordinate_descent_tuning(launcher, *args, **kwargs) + + def _coordinate_descent_tuning(self, launcher, *args, **kwargs): + config2launcher = {launcher.config: launcher} + + self._ensure_kernel_loaded() + + def benchmark_one_config(config): + with self.lock: + launcher = self._precompile_config(config).make_launcher() + config2launcher[config] = launcher + + out = self.bench(launcher, *args, **kwargs) + counters["inductor"]["coordesc_tuning_bench"] += 1 + log.debug( + "COORDESC: %s: %f, nreg %d, nspill %d, #shared-mem %d", + launcher.config, + out, + launcher.n_regs, + launcher.n_spills, + launcher.shared, + ) + return out + + if ( + self.heuristic_type == HeuristicType.PERSISTENT_REDUCTION + and "R0_BLOCK" in launcher.config.kwargs + ): + raise AssertionError( + "Coordinate descent tuner relies on the assumption that persistent reduction's triton config does not have R0_BLOCK" + ) + start_time = time.time_ns() + best_config = self.coordesc_tuner.autotune( + benchmark_one_config, launcher.config, None + ) + coordesc_time_taken_ns = time.time_ns() - start_time + best_config.found_by_coordesc = True + + if self.save_cache_hook: + self.save_cache_hook( + best_config, + self.autotune_time_taken_ns + coordesc_time_taken_ns, + found_by_coordesc=True, + ) + + if best_config not in config2launcher: + # On a Coordesc cache hit, we might not have loaded the launcher + # This can happen because PyCodeCache saves CachingAutotuners in memory, + # even for separate compile IDs (which can have different inputs without changing output code) + config2launcher[best_config] = self._precompile_config( + best_config + ).make_launcher() + + winner = config2launcher[best_config] + TritonBundler.put_winner(winner.cache_hash) + + fn_hash = generate_lookup_hash_from_source_code( + str(self.size_hints), self.fn.src + ) + log.debug("Function hash %s has best config %s", fn_hash, best_config) + return winner + + def get_profiler_kwargs(self, stream, launcher): + kernel_kwargs_str = ",".join( + f"{k}={v}" for (k, v) in launcher.config.kwargs.items() + ) + + ret = { + "kernel_file": (self.filename or ""), + "kernel_hash": self.kernel_hash, + "kernel_backend": "triton", + "stream": stream, + "num_warps": launcher.config.num_warps, + "num_stages": launcher.config.num_stages, + "kernel_kwargs": kernel_kwargs_str, + } + if "kernel_name" in self.inductor_meta: + ret["kernel_name"] = self.inductor_meta["kernel_name"] + if "kernel_flop" in self.inductor_meta: + ret["kernel_flop"] = self.inductor_meta["kernel_flop"] + if "kernel_num_gb" in self.inductor_meta: + ret["kernel_num_gb"] = self.inductor_meta["kernel_num_gb"] + return ret + + def _pre_launch(self, launcher, *args, stream, **kwargs): + """Pre-launch instrumentation: param/tensor dumping and profiler context entry.""" + if self.dump_launch_params: + new_args, grid = self._interpret_args_grid(args, launcher.config) + _dump_launch_params(new_args, kwargs, launcher, self.fn.__name__, grid) + + if self.dump_launch_tensors: + if not self.kernels_to_dump or any( + kernel_name in self.fn.__name__ for kernel_name in self.kernels_to_dump + ): + _dump_launch_tensors( + args, self.filename, self.kernel_hash, self.fn.__name__ + ) + + if autograd_profiler._is_profiler_enabled: + profiler_kwargs = self.get_profiler_kwargs(stream, launcher) + profiler_ctx = torch._C._profiler._RecordFunctionFast( + self.inductor_meta.get("kernel_name", "triton kernel"), + tuple(args), + profiler_kwargs, + ) + profiler_ctx.__enter__() + # set ctx after enter succeeds + self._profiler_ctx = profiler_ctx + else: + self._profiler_ctx = None + + def _post_launch(self) -> None: + """Post-launch instrumentation: profiler context exit and debug mode finalization.""" + if (profiler_ctx := self._profiler_ctx) is not None: + self._profiler_ctx = None + profiler_ctx.__exit__(None, None, None) + if (debug_call := self._debug_call) is not None: + self._debug_call = None + debug_call.finalize(self.get_device_interface()) + + def run( + self, + *args, + stream, + benchmark_run=False, + **kwargs, + ): # type:ignore[override] + """Launch triton kernel call and return result.""" + # --- FAST PATH --- + # After the first successful launch in steady state, cache the launcher + # and skip all preamble on subsequent calls (~2µs savings). + # Conditions here deliberately differ from the cache-population block + # below: we re-check dynamic conditions (profiler, debug mode) every + # call so enabling them at runtime falls back to the slow path. + # Static conditions (interpret, dump flags, launcher count) were + # already validated when the cache was populated. + # `not kwargs` is checked here but not at population time because + # inductor steady-state never passes kwargs; if it somehow does, the + # slow path handles it correctly. + fast = self._cached_launcher + if ( + fast is not None + and not benchmark_run + and not kwargs + and not autograd_profiler._is_profiler_enabled + and not get_active_debug_mode() + ): + return fast(*args, stream=stream) + + debug_mode = get_active_debug_mode() + if debug_mode: + arg_names = list(self.triton_meta.get("signature", {}).keys()) + kernel_kwargs = dict(zip(arg_names, args)) + kernel_kwargs.update(kwargs) + self._debug_call = debug_mode.record_triton_kernel( + kernel_name=self.fn.__name__, kwargs=kernel_kwargs + ) + + if hasattr(triton, "set_allocator"): + + def alloc_fn(size: int, align: int, stream: int | None): + return torch.empty( + size, dtype=torch.int8, device=self.device_props.type + ) + + triton.set_allocator(alloc_fn) + + if self.triton_interpret: + args, grid = self._interpret_args_grid(args, self.configs[0]) + return self.fn[grid]( + *args, + **kwargs, + **self.configs[0].kwargs, + ) + + for plugin in self._plugins: + if ( + result := plugin.pre_dispatch(self, *args, stream=stream, **kwargs) + ) is not DEFER: + return result + + if len(self.launchers) != 1: + if len(self.launchers) == 0: + start_time = time.time_ns() + self.precompile() + self.precompile_time_taken_ns = time.time_ns() - start_time + if len(self.launchers) > 1: + for plugin in self._plugins: + if ( + result := plugin.pre_autotune( + self, *args, stream=stream, **kwargs + ) + ) is not DEFER: + return result + # Re-check: a plugin may have mutated launchers down to one. + if len(self.launchers) > 1: + self.autotune_to_one_config(*args, **kwargs) + + if self.inductor_meta.get("combo_tuning_groups") and not getattr( + self.launchers[0].config, "found_by_combo_autotune", False + ): + with dynamo_timed( + "CachingAutotuner.combo_sequential_autotune", + log_pt2_compile_event=False, + metadata={"kernel_name": self.inductor_meta.get("kernel_name")}, + dynamo_compile_column_us="runtime_triton_autotune_time_us", + compile_id=self.compile_id, + is_backward=self.is_backward, + log_waitcounter=True, + waitcounter_name_override="triton_autotuner", + ): + self.launchers = [ + self._combo_sequential_autotune(self.launchers[0], *args, **kwargs) + ] + + if not getattr( + self.launchers[0].config, "found_by_coordesc", False + ) and self.inductor_meta.get("coordinate_descent_tuning", False): + self.launchers = [ + self.coordinate_descent_tuning(self.launchers[0], *args, **kwargs) + ] + + (launcher,) = self.launchers + # Ensure the final launcher is marked as a winner for bundle filtering. + # For multi-config autotuning and coordesc, put_winner was already called + # (this is an idempotent set-add). For single-config kernels that skip + # autotuning entirely, this is the only call site that records the winner. + TritonBundler.put_winner(launcher.cache_hash) + if launcher.store_cubin and (not benchmark_run or not self.cuda_kernel_saved): + if self.device_props.type == "cpu": + if not self.cpu_kernel_saved: + self.save_cpu_kernel(launcher) + else: + self.save_gpu_kernel(stream, launcher) + + try: + self._pre_launch(launcher, *args, stream=stream, **kwargs) + try: + result = launcher(*args, **kwargs, stream=stream) + except Exception as e: + if isinstance(e, TypeError): + self._check_launcher_call_args(launcher, args) + raise + finally: + self._post_launch() + + # Populate fast path: cache the launcher for future calls. Static + # conditions (interpret, dump flags) are pre-computed in _cache_eligible; + # only dynamic conditions are checked here. + if ( + self._cached_launcher is None + and self._cache_eligible + and not benchmark_run + and not debug_mode + and not autograd_profiler._is_profiler_enabled + and len(self.launchers) == 1 + ): + self._cached_launcher = self._build_fast_launcher(launcher) or launcher + return result + + def _check_launcher_call_args( + self, + launcher: LauncherType, + args: tuple[Any, ...], + ) -> None: + """Raise TypeError with a helpful message when stream is passed positionally.""" + expected = getattr(launcher, "_expected_positional_count", None) + if expected is None: + return + + if len(args) > expected: + kernel_name = self.inductor_meta.get("kernel_name", "triton kernel") + raise TypeError( + f"{kernel_name}: too many positional arguments - " + f"expected {expected}, got {len(args)}. " + "'stream' must be passed as a keyword argument." + ) from None + + def _build_fast_launcher(self, launcher: LauncherType) -> LauncherType | None: + """Try to build a _FastCudaLauncher-backed version of the launcher. + + Returns a new launcher function with the runner replaced by a + _FastCudaLauncher instance (vectorcall C extension), or None if + conditions are not met. Falls back silently on expected errors, + logs a warning on unexpected ones. + """ + import types + + if not self.inductor_meta.get( + "use_fast_triton_launcher", + torch._inductor.config.use_fast_triton_launcher, + ): + return None + + # The _FastCudaLauncher vectorcall bypasses run(), so it can't do the + # variable-length TMA descriptor expansion; fall back to the regular + # (still static) launcher. + if self.inductor_meta.get("host_tma_descriptor_args"): + return None + + # _FastCudaLauncher binds CUDA/HIP function pointers; XPU static + # launchers use SYCL kernels stored in PyCapsules. + if self.device_props.type not in ("cuda", "hip"): + return None + + try: + from torch._C import _FastCudaLauncher + except ImportError: + return None + + try: + # Only works for the static triton launcher path. + if not getattr(launcher, "_is_static", False): + return None + + # Resolve the bound kernel behind the launcher function. + runner = launcher.__globals__.get("runner") + if not callable(runner): + return None + kernel = runner.__self__ + # compile-on-one-rank kernels keep their loaded handles per device, so + # kernel.function is None; the fast launcher binds a single device's + # function pointer, so fall back to the per-device static launcher. + if getattr(kernel, "device_agnostic", False): + return None + cu_function = kernel.function + num_warps = kernel.num_warps + shared = kernel.shared + arg_tys = kernel.arg_tys + if cu_function is None or num_warps is None: + return None + + n_scratch = sum( + [ + getattr(kernel, "has_global_scratch", False), + getattr(kernel, "has_profile_scratch", False), + ] + ) + if torch.version.hip: + n_scratch = max(n_scratch, 2) + + fast_runner = _FastCudaLauncher( + cu_function, num_warps, shared, arg_tys, n_scratch + ) + + new_globals = {**launcher.__globals__, "runner": fast_runner} + new_launcher = types.FunctionType( + launcher.__code__, + new_globals, + launcher.__name__, + ) + # Copy launcher attributes to the new function object. + # NOTE: If new attributes are added to launchers in the future, + # they must be added here too — otherwise the fast launcher will + # silently drop them. + for attr in ( + "config", + "n_regs", + "n_spills", + "shared", + "cache_hash", + "store_cubin", + "_is_static", + "_expected_positional_count", + ): + val = getattr(launcher, attr, None) + if val is not None: + setattr(new_launcher, attr, val) + # _FastCudaLauncher bakes kernel.function (a raw CUfunction pointer) + # into a C object and never re-reads it, and replacing the "runner" + # global drops this launcher's only reference to the owning static + # kernel. Without an explicit reference the kernel can be collected or + # closed while this launcher is still cached and callable; its + # close()/__del__ then unloads the module and leaves the baked pointer + # dangling, producing a CUDA "misaligned address" error on the next + # launch. Keep the owner alive for as long as the fast launcher is. + new_launcher._static_kernel_owner = kernel # type: ignore[attr-defined] + return new_launcher + except (AttributeError, TypeError, KeyError, ValueError): + # Expected failures - silent fallback is OK. + # ValueError is raised when nArgs > MAX_ARGS in the C extension. + return None + except Exception: + # Unexpected failures - log for debugging + log.warning("Unexpected error building fast launcher", exc_info=True) + return None + + def _interpret_args_grid( + self, args: tuple[Any, ...], cfg: Config + ) -> tuple[tuple[Any, ...], tuple[int, int, int]]: + if triton_version_uses_attrs_dict(): + + def filtered_signature() -> list[str]: + # constexprs are not passed in as args + new_signature: list[str] = [] + from triton.runtime.interpreter import InterpretedFunction + + for i, x in enumerate(self.triton_meta["signature"].keys()): + if isinstance(self.fn, InterpretedFunction): + # These are torch compiled triton kernels that definitely + # have block size configs. Dynamo does not currently + # trace user defined triton kernels when TRITON_INTERPRET=1 + if x not in cfg.kwargs: + new_signature.append(x) + elif i not in get_constexprs(self.fn): + # use constexprs rather than just configs since user + # defined triton kernels may not have any configs + new_signature.append(x) + + return new_signature + + else: + + def filtered_signature() -> list[str]: + return list(self.triton_meta["signature"].keys()) + + grid = GridExpr.from_meta( + self.inductor_meta, cfg, mode=self.grid_mode + ).eval_slow( + dict( + zip( + [ + *filtered_signature(), + *self.inductor_meta.get("extra_launcher_args", ()), + ], + args, + ) + ) + ) + if self.inductor_meta.get("extra_launcher_args"): + args = args[: -len(self.inductor_meta["extra_launcher_args"])] + return args, grid + + +class _ConstRepr: + def __init__(self, value: str): + self.value = value + + def __call__(self, _=None) -> str: + return self.value + + +class CompileResult(Generic[_T]): + """ + Base class representing compiled result. + """ + + def __init__( + self, + kernel: _T, + config: Config, + compile_meta: dict[str, Any], + inductor_meta: InductorMeta, + ): + self.kernel = kernel + self.config = config + self.compile_meta = compile_meta + self.inductor_meta = inductor_meta + + def make_launcher(self) -> LauncherType: ... + + def _host_tma_pre_runner_lines( + self, runner_args: list[str], call_args: list[str] + ) -> tuple[list[str], list[str]]: + """Build host-side TMA descriptors in the launcher and swap them in for + the raw tensor args. Shared by the dynamic and static launchers.""" + host_tma_args = self.inductor_meta.get("host_tma_descriptor_args") + pre_runner_lines: list[str] = [] + if not host_tma_args: + return pre_runner_lines, runner_args + if not has_triton_stable_tma_api(): + raise RuntimeError( + "host-side TMA requires a Triton with the stable TMA API " + "(triton.tools.tensor_descriptor.TensorDescriptor)" + ) + cfg_kwargs = self.config.kwargs + all_constants = self.compile_meta["constants"] + for inner_name, desc_info in host_tma_args.items(): + if inner_name not in call_args or not isinstance(desc_info, dict): + continue + block_shape_vals = _resolve_dims( + desc_info["block_shape"], cfg_kwargs, all_constants + ) + shape_vals = _resolve_dims(desc_info["shape"], cfg_kwargs, all_constants) + stride_vals = _resolve_dims(desc_info["strides"], cfg_kwargs, all_constants) + if block_shape_vals is None or shape_vals is None or stride_vals is None: + continue + desc_var = f"{inner_name}_host_tma_desc" + aligned_var = f"{inner_name}_aligned" + # _host_tma_aligned clones (warning once) only if misaligned. + pre_runner_lines.append( + f'{aligned_var} = _host_tma_aligned({inner_name}, "{inner_name}")' + ) + pre_runner_lines.append( + f"{desc_var} = TensorDescriptor({aligned_var}, {shape_vals}," + f" {stride_vals}, {block_shape_vals})" + ) + runner_args = [desc_var if a == inner_name else a for a in runner_args] + return pre_runner_lines, runner_args + + def _gen_launcher_code( + self, scope, def_args, runner_args, pre_runner_lines=None + ) -> LauncherType: + grid = GridExpr.from_meta(self.inductor_meta, self.config) + # grid.prefix is usually empty, grid.x_grid is something like `-(xnumel//-1024)` + lines = [ + f"def launcher({', '.join(def_args)}, stream):", + *[f" {line}" for line in grid.prefix], + f" grid_0 = {grid.x_grid}", + f" grid_1 = {grid.y_grid}", + f" grid_2 = {grid.z_grid}", + *(f" {l}" for l in (pre_runner_lines or [])), + f" runner({', '.join(runner_args)})", + ] + launcher_code = "\n".join(lines) + exec(launcher_code, scope) + launcher = scope["launcher"] + # Stash expected positional arg count at codegen time so + # _check_launcher_call_args can validate without inspect.signature(). + launcher._expected_positional_count = len(def_args) + return launcher + + def _get_arg_lists( + self, arg_names, constexprs + ) -> tuple[list[str], list[str], OrderedSet[str]]: + """ + Return a bunch of intermediate lists of args needed for generating + launcher code. + """ + compile_meta = self.compile_meta + cfg = self.config + known_constants = OrderedSet( + arg for i, arg in enumerate(arg_names) if i in constexprs + ) + + """ + https://github.com/pytorch/pytorch/issues/115344 + + self.fn.constexprs doesn't properly deal with None args, so when we filter out + an arg in UserDefinedTritonKernel.codegen, we need to filter it here as well. + We also don't want to modify self.fn. + + We know that we removed something from the signature if: + 1. It's in compile_meta["constants"] + 2. It isn't a constant we already know about + Note: The value of interest has already been added to compile_meta['constants'], + so we use self.fn.constexprs instead. + 3. It isn't in the compile_meta signature + """ + none_args = OrderedSet( + k + for k, v in compile_meta["constants"].items() + if v is None and k not in known_constants + ) + none_args = none_args.difference(OrderedSet(compile_meta["signature"].keys())) + + def _convert_constant(constant): + if isinstance(constant, str): + return "r'" + constant + "'" + else: + return repr(constant) + + if triton_version_uses_attrs_dict(): + call_args = arg_names + def_args = arg_names + implicit_constants = OrderedSet( + ( + "num_warps", + "num_stages", + ) + ).union(OrderedSet(k for k in known_constants)) + if implicit_constants := implicit_constants & OrderedSet( + compile_meta["constants"].keys() + ): + # num_warps/num_stages are special implicit args that are not in the signature + # see test_triton_kernel_special_params + def_args = [arg for arg in def_args if arg not in implicit_constants] + repl = { + k: _convert_constant(compile_meta["constants"].get(k)) + for k in implicit_constants + } + call_args = [repl.get(arg, arg) for arg in call_args] + else: + call_args = [ + arg + for i, arg in enumerate(arg_names) + if i not in constexprs and arg not in none_args + ] + cfg_dict = config_to_dict(cfg) + def_args = [ + name + for name in arg_names + if name not in cfg_dict and name not in none_args + ] + + if "extra_launcher_args" in self.inductor_meta: + def_args = [*def_args, *self.inductor_meta["extra_launcher_args"]] + + return call_args, def_args, none_args + + +_KernelCompileResult: TypeAlias = ( + CompileResult[CompiledKernel] + | CompileResult[StaticallyLaunchedCudaKernel] + | CompileResult[StaticallyLaunchedXpuKernel] +) + + +class CannotStaticallyLaunchKernel(Exception): + pass + + +class StaticTritonCompileResult(CompileResult[_T]): + """ + TritonCompileResult that uses StaticCudaLauncher, + which vastly simplifies the setup and metadata needed to be kept. + """ + + @staticmethod + def can_statically_launch( + kernel: CompiledKernel, + inductor_meta: InductorMeta, + triton_meta: TritonMeta, + heuristic_type: HeuristicType, + ) -> _KernelType | None: + if not torch._inductor.config.use_static_triton_launcher: + return None + + def check_can_launch() -> _KernelType: + if triton_meta.get("device_type") not in ("cuda", "xpu", "hip"): + raise CannotStaticallyLaunchKernel("Non-cuda/XPU/ROCm device") + + if triton_meta.get("device_type") == "xpu" and XPU_KERNEL_FORMAT == "spv": + raise CannotStaticallyLaunchKernel( + "Static XPU Triton kernel launch does not support SPIR-V kernel." + ) + + if torch._inductor.config.cpp_wrapper: + # If we're running with cpp wrapper, it doesn't + # make sense to statically compile since everything + # is codegenned anyway + raise CannotStaticallyLaunchKernel("Cpp wrapper enabled") + + if ( + heuristic_type == HeuristicType.USER_AUTOTUNE + and not torch._inductor.config.static_launch_user_defined_triton_kernels + ): + # Don't support user defined triton kernels yet + raise CannotStaticallyLaunchKernel("User defined triton kernel") + + if inductor_meta.get("store_cubin"): + # Requires storing the entire binary + raise CannotStaticallyLaunchKernel("store_cubin is enabled") + + if getattr(kernel.metadata, "launch_pdl", False) or getattr( + kernel.metadata, "launch_cooperative_grid", False + ): + raise CannotStaticallyLaunchKernel( + "static launch does not support launch attributes" + ) + + binary_ext = GPU_KERNEL_BIN_EXTS.get( + triton_meta.get("device_type"), ".cubin" + ) + cubin_location = os.path.join( + triton_cache_dir(cast(int, triton_meta.get("device", 0))), + triton_hash_to_path_key(kernel.hash), + f"{kernel.src.fn.__name__}{binary_ext}", + ) + + if not os.path.exists(cubin_location): + raise CannotStaticallyLaunchKernel( + f"Cubin path not found: {cubin_location}" + ) + + else: + kernel._cubin_path = cubin_location + + try: + static_kernel = statically_launched_kernel_by_device( + kernel, triton_meta.get("device_type") + ) + except NotImplementedError as e: + raise CannotStaticallyLaunchKernel(f"NotImplemented: {str(e)}") from e + + return static_kernel + + try: + result = check_can_launch() + return result + except CannotStaticallyLaunchKernel as e: + log.info("Bypassing StaticallyLaunchedCudaKernel due to %s", e) + if torch._inductor.config.strict_static_triton_launcher: + raise e + return None + + def reload_cubin_path(self): + """ + When loading from cache on disk, we want to reload cubin + files from their appropriate location on disc. + """ + device_type = ( + "hip" if torch.version.hip else self.compile_meta.get("device_type", "cuda") + ) + binary_ext = GPU_KERNEL_BIN_EXTS.get(device_type, "cubin") + cubin_location = os.path.join( + triton_cache_dir( + _resolve_load_device(self.compile_meta.get("device"), device_type) + ), + triton_hash_to_path_key(self.kernel.hash), + f"{self.kernel.name}{binary_ext}", + ) + if not os.path.exists(cubin_location): + if self.kernel.cubin_raw is not None: + # We saved the raw cubin, so write it to he appropriate location + self.kernel.reload_cubin_from_raw(cubin_location) + else: + raise RuntimeError( + "Cubin file saved by TritonBundler not found at %s", cubin_location + ) + self.kernel.cubin_path = cubin_location + + def make_launcher(self) -> LauncherType: + # If at least one static make_launcher call occurs, + # we're sure static cuda launcher was used for this compile + set_feature_use("static_triton_launcher", True) + # Load the binary on the parent + if not self.kernel.cubin_path: + self.reload_cubin_path() + # compile-on-one-rank: a None device in compile_meta marks a rank/device-agnostic + # kernel, so the launcher must keep its loaded handles per device. + self.kernel.device_agnostic = self.compile_meta.get("device") is None + device = _resolve_load_device( + self.compile_meta.get("device"), + self.compile_meta.get("device_type", "cuda"), + ) + self.kernel.load_kernel(device) + scope = { + "runner": self.kernel.run, + } + + # NOTE: Constexpr handling for triton and static cuda launcher + + # Triton kernels have two types of constexprs: *declared* ones, which are ones the user + # has explicitly declared as tl.constexpr, and *implied* ones, which are expressions triton + # deems constant while compiling/analyzing the code (i.e. unused parameters, for example) + + # Triton kernels handle constexprs slightly differently depending on which version of triton + # we care about (we support 3.2.0 and 3.3.0). + + # In 3.2.0, triton kernels do not require passing any declared constexprs into the kernel + # In 3.3.0, triton kernels require all declared constexprs be passed into the kernel, where + # they are subsequently ignored. + # When statically launching, since we're launching from the triton generated cubin, we actually want to + # always get rid of all const exprs, declared or implied, since the underlying cubin file has all + # of the constants stripped away anyway. + + # But CachingAutotuner.run will pass us a different number of arguments depending on + # whether or not we're in triton 3.2.0 or later, so we grab def_args with the same logic + # as the (non static) TritonCompileResult. We then generate call_args ourselves, since we + # want only a subset of the arguments passed to triton. + # Here, arg_names is exactly fn.src.arg_names and declared_constexprs is exactly fn.src.constexprs, + # which matches behavior with regular TritonCompileResult + _, def_args, none_args = self._get_arg_lists( + self.kernel.arg_names, self.kernel.declared_constexprs + ) + + call_args = [ + arg + for i, arg in enumerate(self.kernel.arg_names) + if i not in self.kernel.full_constexprs and arg not in none_args + ] + + # StaticallyLaunchedCudaKernel.run takes in order grid_0, grid_1, grid_2, stream, and call_args + runner_args = ["grid_0", "grid_1", "grid_2", "stream", *call_args] + pre_runner_lines, runner_args = self._host_tma_pre_runner_lines( + runner_args, call_args + ) + if self.inductor_meta.get("host_tma_descriptor_args"): + # _host_tma_pre_runner_lines already validated the stable TMA API. + from triton.tools.tensor_descriptor import TensorDescriptor + + scope["_host_tma_aligned"] = _host_tma_aligned + scope["TensorDescriptor"] = TensorDescriptor + launcher = self._gen_launcher_code( + scope, def_args, runner_args, pre_runner_lines=pre_runner_lines + ) + launcher.config = self.config # type: ignore[attr-defined] + launcher.n_regs = self.kernel.n_regs # type: ignore[attr-defined] + launcher.n_spills = self.kernel.n_spills # type: ignore[attr-defined] + launcher.shared = self.kernel.shared # type: ignore[attr-defined] + launcher.cache_hash = triton_hash_to_path_key(self.kernel.hash) # type: ignore[attr-defined] + launcher.store_cubin = False # type: ignore[attr-defined] + launcher._is_static = True # type: ignore[attr-defined] + return launcher + + +class TritonCompileResult(CompileResult[CompiledKernel]): + """ + Upstream Triton CompileKernel can not be pickled. This is a wrapper + to support serialization and generate the launcher function. + """ + + @staticmethod + @functools.lru_cache(32) + def _kernel_metadata_cls(fields: tuple[str, ...]) -> Any: + return namedtuple("KernelMetadata", sorted(fields)) + + @staticmethod + def _serialize_metadata(metadata): + """ + Triton uses a nested class called KernelMetadata to store metadata information. + Pickle does not work well with nested namedtuples, as the namedtuple doesn't appear + in the toplevel namespace of the module. So these serialization/deser functions + are used to convert the namedtuples to a dict and back. + + As for packed_metadata, depending on the triton backend, KernelMetadata can be + a namedtuple, or a regular tuple! So the serialization function branches on whether + the metadata to be serialized is a namedtuple or regular, serializable one. + """ + + def is_namedtuple(obj) -> bool: + return ( + isinstance(obj, tuple) + and hasattr(obj, "_asdict") + and hasattr(obj, "_fields") + ) + + if is_namedtuple(metadata): + return metadata._asdict() + else: + return metadata + + @staticmethod + def _deserialize_metadata(metadata): + if isinstance(metadata, dict): + return TritonCompileResult._kernel_metadata_cls(tuple(metadata.keys()))( + **metadata + ) + else: + return metadata + + def __getstate__(self) -> dict[str, Any]: + kernel = self.kernel + # replace the fields that don't pickle nicely + kernel_state = { + **kernel.__dict__, + # See doc about serializing metadata above + "metadata": self._serialize_metadata(kernel.metadata), + "packed_metadata": self._serialize_metadata( + getattr(kernel, "packed_metadata", None) + ), + "module": None, # regenerated by kernel._init_handles() + "function": None, # regenerated by kernel._init_handles() + "run": None, # regenerated by kernel._init_handles() + } + return {**self.__dict__, "kernel": kernel_state} # type: ignore[dict-item] + + def __setstate__(self, state: dict[str, Any]) -> None: + # src = ASTSource.__new__(ASTSource) + # src.__setstate__(state["kernel"]["src"]) + # TODO(jansel): need to fixup src.fn which is now None + kernel = CompiledKernel.__new__(CompiledKernel) + metadata = state["kernel"]["metadata"] + packed_metadata = state["kernel"]["packed_metadata"] + kernel.__dict__.update( + { + **state["kernel"], + # "src": src, + "metadata": self._deserialize_metadata(metadata), + "packed_metadata": self._deserialize_metadata(packed_metadata), + } + ) + self.__dict__.update(state) + self.kernel = kernel + + def make_launcher(self) -> LauncherType: + """ + Launching triton kernels is performance sensitive, we compile + a custom Python function get the grid() and reorder the args to + the underlying wrapper. + """ + cfg = self.config + compile_meta = self.compile_meta + binary = self.kernel + fn = binary.src.fn + binary._init_handles() + (call_args, def_args, none_args) = self._get_arg_lists( + fn.arg_names, get_constexprs(fn) + ) + binary_shared = ( + binary.shared if hasattr(binary, "shared") else binary.metadata.shared + ) + + if knobs is None: + launch_enter = binary.__class__.launch_enter_hook + launch_exit = binary.__class__.launch_exit_hook + else: + launch_enter = knobs.runtime.launch_enter_hook + launch_exit = knobs.runtime.launch_exit_hook + + import math as math_lib + + import triton as triton_lib + + import torch as torch_lib + + scope = { + "grid_meta": cfg.kwargs, + "bin": binary, + "launch_enter_hook": launch_enter, + "launch_exit_hook": launch_exit, + "metadata": ( + binary.packed_metadata + if hasattr(binary, "packed_metadata") + else binary.metadata + ), + "shared": binary_shared, + "num_warps": ( + binary.num_warps + if hasattr(binary, "num_warps") + else binary.metadata.num_warps + ), + "cta_args": ( + ( + binary.num_ctas, + *get_first_attr(binary, "cluster_dims", "clusterDims"), + ) + if hasattr(binary, "num_ctas") + else ( + (binary.metadata.num_ctas, *binary.metadata.cluster_dims) + if hasattr(binary, "metadata") + and hasattr(binary.metadata, "num_ctas") + and hasattr(binary.metadata, "cluster_dims") + else () + ) + ), + "function": get_first_attr(binary, "function", "cu_function"), + "runner": get_first_attr(binary, "run", "c_wrapper"), + "math": math_lib, + "torch": torch_lib, + "triton": triton_lib, + } + + if not hasattr(binary, "launch_metadata"): + # launch args before CompiledKernel.launch_metadata is added. + # TODO(jansel): delete this branch in mid-2025 + runner_args = [ + "grid_0", + "grid_1", + "grid_2", + "num_warps", + "*cta_args", + "shared", + "stream", + "function", + "launch_enter_hook", + "launch_exit_hook", + "metadata", + *call_args, + ] + else: # args after CompiledKernel.launch_metadata: https://github.com/triton-lang/triton/pull/3492 + # Getting the kernel launch args is extremely perf-sensitive. Evaluating + # `bin.launch_metadata` is relatively expensive, and returns None unless a + # `launch_enter_hook` is installed. So if we don't have that hook installed, + # we want to burn None in to the launch args with zero overhead. + # See https://github.com/pytorch/pytorch/issues/123597 + if launch_enter: + launch_metadata = f"bin.launch_metadata((grid_0, grid_1, grid_2), stream, {', '.join(call_args)})" + else: + launch_metadata = "None" + runner_args = [ + "grid_0", + "grid_1", + "grid_2", + "stream", + "function", + "metadata", + launch_metadata, + "launch_enter_hook", + "launch_exit_hook", + *call_args, + ] + + pre_runner_lines, runner_args = self._host_tma_pre_runner_lines( + runner_args, call_args + ) + if self.inductor_meta.get("host_tma_descriptor_args"): + # _host_tma_pre_runner_lines already validated the stable TMA API. + from triton.tools.tensor_descriptor import TensorDescriptor + + scope["_host_tma_aligned"] = _host_tma_aligned + scope["TensorDescriptor"] = TensorDescriptor + + launcher = self._gen_launcher_code( + scope, def_args, runner_args, pre_runner_lines=pre_runner_lines + ) + + launcher = scope["launcher"] + launcher.config = cfg + launcher.n_regs = getattr(binary, "n_regs", None) + launcher.n_spills = getattr(binary, "n_spills", None) + launcher.shared = binary_shared + launcher.cache_hash = triton_hash_to_path_key(binary.hash) + launcher.store_cubin = self.inductor_meta.get("store_cubin", False) + # store this global variable to avoid the high overhead of reading it when calling run + if launcher.store_cubin: + launcher.fn = fn + launcher.bin = binary + if triton_version_uses_attrs_dict(): + # arg filtering wasn't done above + cfg_dict = config_to_dict(cfg) + def_args = [x for x in def_args if x not in cfg_dict] + call_args = [ + x + for x in call_args + if compile_meta["signature"].get(x, "constexpr") != "constexpr" + and x not in none_args + ] + launcher.def_args = def_args + launcher.call_args = call_args + kernel_metadata = getattr(self.kernel, "metadata", None) + + # for the scratch arguments: None indicates that the kernel doesn't + # take any scratch argument; otherwise a number indicates the number + # of bytes of scratch that need to be provided. + + # in AMD's Triton backend, the global scratch size is never provided + # (but for AMD it's safe to pass an extra null arg, so always include it) + global_scratch: int | None = getattr( + kernel_metadata, + "global_scratch_size", + (0 if torch.version.hip else None), + ) + profile_scratch: int | None = getattr( + kernel_metadata, "profile_scratch_size", None + ) + launcher.global_scratch = global_scratch + launcher.profile_scratch = profile_scratch + return launcher + + +def _find_names(obj): + import gc + import inspect + + frame = inspect.currentframe() + while frame is not None: + # On CPython <= 3.12 this access materializes the frame's locals + # dict so gc.get_referrers below can find obj inside it. On 3.13+ + # f_locals is a fresh write-through proxy (PEP 667) and this loop + # is a no-op, so function-local names are not discoverable there. + _ = frame.f_locals + frame = frame.f_back + obj_names = [] + for referrer in gc.get_referrers(obj): + if isinstance(referrer, dict): + for k, v in referrer.items(): + if v is obj: + obj_names.append(k) + return obj_names + + +collected_calls: list[Any] = [] + + +def start_graph(): + collected_calls.clear() + + +def end_graph(output_file): + if len(collected_calls) == 0: + return + overall_time = sum(call[0] for call in collected_calls) + overall_gb = sum(call[1] for call in collected_calls) + cur_file = inspect.stack()[1].filename + summary_str = ( + f"SUMMARY ({cur_file})\n" + f"{overall_time:.2f}ms \t {overall_gb:.2f} GB\t {overall_gb / (overall_time / 1e3):.2f}GB/s" + ) + log.info( + "%s", + summary_str, + ) + if output_file is not None: + # sort perf numbers in descending order, i.e. placing the + # most runtime-heavy kernels at the top of the list + sorted_calls = sorted(collected_calls, key=lambda c: float(c[0]), reverse=True) + try: + with open(output_file, "a") as file: + log.info( + "Save profile bandwidth results to %s", + output_file, + ) + file.write("====================\n") + file.write(f"TRITON KERNELS BANDWIDTH INFO ({cur_file})\n") + for ms, num_gb, gb_per_s, kernel_name in sorted_calls: + # also display the runtime percentage for each kernel + percentage = f"{ms / overall_time * 100:.2f}%" + suffix = f" \t {percentage} \t {kernel_name}" + bw_info_str = create_bandwidth_info_str( + ms, + num_gb, + gb_per_s, + suffix=suffix, + color=False, + ) + file.write(bw_info_str + "\n") + file.write(f"{summary_str}\n\n") + except Exception: + log.warning( + "failed to write profile bandwidth result into %s", + output_file, + exc_info=True, + ) + + +class DebugAutotuner(CachingAutotuner): + def __init__( + self, + *args, + regex_filter="", + with_profiler=False, + with_bandwidth_info=True, + **kwargs, + ): + self.regex_filter = regex_filter + self.with_profiler = with_profiler + self.with_bandwidth_info = with_bandwidth_info + super().__init__(*args, **kwargs) + self.cached = None + + def run(self, *args, stream, **kwargs): + if not self.with_bandwidth_info: + super().run(*args, stream=stream, **kwargs, benchmark_run=True) + return + else: + possible_names = _find_names(self) + if possible_names: + kernel_name = f"{max(possible_names, key=len)}" + else: + # In the AOTI lazy compile path, the CachingAutotuner is not + # bound to a module-level name, so _find_names returns empty. + # Fall back to the kernel name recorded in inductor_meta. + kernel_name = self.inductor_meta.get("kernel_name") or self.fn.__name__ + if not re.match(self.regex_filter, kernel_name): + return + if len(self.launchers) != 1: + if len(self.launchers) == 0: + start_time = time.time_ns() + self.precompile() + self.precompile_time_taken_ns = time.time_ns() - start_time + if len(self.launchers) > 1: + self.autotune_to_one_config(*args, **kwargs) + (launcher,) = self.launchers + + if launcher.store_cubin: + if self.device_props.type == "cpu": + self.save_cpu_kernel(launcher) + else: + self.save_gpu_kernel(stream, launcher) + + if self.cached is None: + ms = self.bench(launcher, *args, with_profiler=self.with_profiler) + num_in_out_ptrs = len( + [ + arg_name + for arg_name in self.fn.arg_names + if arg_name.startswith("in_out_ptr") + ] + ) + num_gb = self.inductor_meta.get("kernel_num_gb", None) + if num_gb is None: + num_gb = get_num_bytes(*args, num_in_out_args=num_in_out_ptrs) / 1e9 + gb_per_s = num_gb / (ms / 1e3) + self.cached = ms, num_gb, gb_per_s, kernel_name + collected_calls.append((ms, num_gb, gb_per_s, kernel_name)) + log.info( + "%s", + create_bandwidth_info_str( + ms, num_gb, gb_per_s, suffix=f" \t {kernel_name}" + ), + ) + else: + # in AOTI, we will call the kernel and its timing info has been cached already + collected_calls.append(self.cached) + + +def hash_configs(configs: list[Config]): + """ + Hash used to check for changes in configurations + """ + hasher = hashlib.sha256() + for cfg in configs: + hasher.update( + f"{sorted(cfg.kwargs.items())} {cfg.num_warps} {cfg.num_stages}\n".encode() + ) + return hasher.hexdigest() + + +def cached_autotune( + size_hints: list[int] | None, + configs: list[Config], + triton_meta: TritonMeta, + heuristic_type, + filename=None, + inductor_meta: InductorMeta | None = None, + custom_kernel=False, + caching_autotuner_cls: type[CachingAutotuner] = CachingAutotuner, + debug_autotuner_cls: type[DebugAutotuner] = DebugAutotuner, +): + """ + A copy of triton.autotune that calls our subclass. Our subclass + has additional debugging, error handling, and on-disk caching. + """ + inductor_meta = {} if inductor_meta is None else inductor_meta + if size_hints is not None and heuristic_type in ( + HeuristicType.REDUCTION, + HeuristicType.PERSISTENT_REDUCTION, + ): + configs = _enforce_reduction_config_block_minimums( + configs, size_hints, inductor_meta + ) + configs = unique_configs(configs) + if len(configs) != 1 and not filename: + raise AssertionError("filename required when multiple configs are provided") + + device_prop = triton_meta.get("device") + if not isinstance(device_prop, DeviceProperties): + device_prop = None + dynamic_scale_rblock_eligible = _could_dynamic_scale_rblock( + size_hints=size_hints, + heuristic_type=heuristic_type, + device_prop=device_prop, + inductor_meta=inductor_meta, + ) + configs, autotune_cache, autotune_cache_info = check_autotune_cache( + configs, + filename, + inductor_meta, + dynamic_scale_rblock_eligible=dynamic_scale_rblock_eligible, + ) + mutated_arg_names = cast("list[str]", inductor_meta.pop("mutated_arg_names", ())) + optimize_mem = inductor_meta.pop("optimize_mem", True) + + if "restore_value" in triton_meta: + mutated_arg_names += triton_meta.pop("restore_value") + + reset_to_zero_arg_names: list[str] = [] + if "reset_to_zero" in triton_meta: + reset_to_zero_arg_names.extend(triton_meta.pop("reset_to_zero")) + + def decorator(fn): + # Remove XBLOCK from config if it's not a function argument. + # This way, coordinate descent tuning will not try to tune it. + # + # Context: When TritonKernel.no_x_dim is True, we hardcode XBLOCK to 1. + import inspect + + if "XBLOCK" not in inspect.signature(fn.fn).parameters: + for tconfig in configs: + if "XBLOCK" in tconfig.kwargs: + if tconfig.kwargs["XBLOCK"] != 1: + raise AssertionError( + f"Expected XBLOCK == 1 when not in fn params, got {tconfig.kwargs['XBLOCK']}" + ) + tconfig.kwargs.pop("XBLOCK") + + if inductor_meta.get("profile_bandwidth"): + return debug_autotuner_cls( + fn, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + regex_filter=inductor_meta["profile_bandwidth_regex"], + with_profiler=inductor_meta[ + "profile_bandwidth_with_do_bench_using_profiling" + ], + configs=configs, + save_cache_hook=autotune_cache and autotune_cache.save, + mutated_arg_names=mutated_arg_names, + reset_to_zero_arg_names=reset_to_zero_arg_names, + optimize_mem=optimize_mem, + heuristic_type=heuristic_type, + size_hints=size_hints, + custom_kernel=custom_kernel, + filename=filename, + with_bandwidth_info=True, + ) + return caching_autotuner_cls( + fn, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + configs=configs, + save_cache_hook=autotune_cache and autotune_cache.save, + mutated_arg_names=mutated_arg_names, + reset_to_zero_arg_names=reset_to_zero_arg_names, + optimize_mem=optimize_mem, + heuristic_type=heuristic_type, + size_hints=size_hints, + custom_kernel=custom_kernel, + filename=filename, + autotune_cache_info=autotune_cache_info, + ) + + return decorator + + +def unique_configs(configs: list[Config]): + """Remove duplicate configurations""" + seen: OrderedSet[Hashable] = OrderedSet() + pruned_configs = [] + + for cfg in configs: + key = triton_config_to_hashable(cfg) + if key not in seen: + seen.add(key) + pruned_configs.append(cfg) + return pruned_configs + + +def check_config(cfg, *, xnumel=None, ynumel=None, znumel=None): + for numel, label in zip((xnumel, ynumel, znumel), "XYZ"): + if numel is None: + continue + block = cfg[f"{label}BLOCK"] + if numel == 1: + if block != 1: + raise AssertionError( + f"TritonKernel.indexing assumes numel == 1 => BLOCK == 1" + f" but {label.lower()}numel=={numel} and {label}BLOCK={block} (cfg={cfg})." + ) + max_block = TRITON_MAX_BLOCK[label] + max_block_str = f'config.triton.max_block["{label}"]' + if max_block % block != 0: + raise AssertionError( + f"TritonKernel.indexing assumes {label}BLOCK divides {max_block_str}" + f" but {label}BLOCK={block} and {max_block_str}={max_block} (cfg={cfg})." + ) + + +def check_max_block(cfg: dict[str, int]): + """ + Check that block sizes are within the maximum allowed. + """ + for var, val in cfg.items(): + block_suffix = "BLOCK" + if block_suffix in var: + prefix = var.removesuffix(block_suffix) + max_block = TRITON_MAX_BLOCK[prefix] + if val > max_block: + raise AssertionError( + f"'{var}' too large. Maximum: {max_block}. Actual: {val}." + ) + + +def _check_native_matmul_block_numel( + kwargs: dict[str, int], r0_block: int | None = None +) -> None: + block_numel = native_matmul_block_numel(kwargs, r0_block=r0_block) + if block_numel > TRITON_MAX_TENSOR_NUMEL: + raise AssertionError( + f"Block numel {block_numel} exceeds Triton maximum " + f"{TRITON_MAX_TENSOR_NUMEL}" + ) + + +def _native_matmul_config_under_numel_limit( + cfg: Config, r0_block: int | None = None +) -> bool: + return ( + native_matmul_block_numel(cfg.kwargs, r0_block=r0_block) + <= TRITON_MAX_TENSOR_NUMEL + ) + + +def _cap_native_matmul_configs(configs: list[Config], r0_block: int) -> list[Config]: + capped_configs: list[Config] = [] + for cfg in configs: + cfg = copy.deepcopy(cfg) + while not _native_matmul_config_under_numel_limit(cfg, r0_block=r0_block): + shrinkable_fields = [ + field for field in ("XBLOCK", "YBLOCK") if cfg.kwargs.get(field, 1) > 16 + ] + if not shrinkable_fields: + break + field = max(shrinkable_fields, key=lambda field: cfg.kwargs[field]) + cfg.kwargs[field] //= 2 + + if _native_matmul_config_under_numel_limit(cfg, r0_block=r0_block): + capped_configs.append(cfg) + + return unique_configs(capped_configs) + + +def _enforce_reduction_config_block_minimums( + configs: list[Config], + size_hints: dict[str, int], + inductor_meta: InductorMeta, +) -> list[Config]: + min_xblock = inductor_meta.get("min_xblock") + min_rblock = inductor_meta.get("min_rblock") + if min_xblock is None and min_rblock is None: + return configs + + for cfg in configs: + if frozenset(("YBLOCK", "ZBLOCK", "R1_BLOCK")) & cfg.kwargs.keys(): + raise AssertionError( + f"min_xblock/min_rblock only support 2D X/R0 configs: {cfg}" + ) + has_xblock = "XBLOCK" in cfg.kwargs + has_rblock = "R0_BLOCK" in cfg.kwargs + if not (has_xblock or has_rblock): + continue + + x_floor = min_xblock if min_xblock is not None else 1 + r_floor = min_rblock if min_rblock is not None else 1 + target_tile_product = (cfg.kwargs["XBLOCK"] if has_xblock else 1) * ( + cfg.kwargs["R0_BLOCK"] if has_rblock else 1 + ) + + if has_xblock: + cfg.kwargs["XBLOCK"] = max(cfg.kwargs["XBLOCK"], x_floor) + if has_rblock: + cfg.kwargs["R0_BLOCK"] = max(cfg.kwargs["R0_BLOCK"], r_floor) + + def current_tile_product() -> int: + return (cfg.kwargs["XBLOCK"] if has_xblock else 1) * ( + cfg.kwargs["R0_BLOCK"] if has_rblock else 1 + ) + + def shrink_to_budget(name: str, floor: int) -> None: + while ( + name in cfg.kwargs + and current_tile_product() > target_tile_product + and cfg.kwargs[name] > floor + ): + cfg.kwargs[name] //= 2 + + # Preserve the autotuner's original tile-size budget where possible: + # raising one block to satisfy a floor should shrink the other block. + shrink_to_budget("R0_BLOCK", r_floor) + shrink_to_budget("XBLOCK", x_floor) + + check_max_block(cfg.kwargs) + check_config( + cfg.kwargs, + xnumel=size_hints.get("x") if "XBLOCK" in cfg.kwargs else None, + ynumel=size_hints.get("y") if "YBLOCK" in cfg.kwargs else None, + znumel=size_hints.get("z") if "ZBLOCK" in cfg.kwargs else None, + ) + + return configs + + +def _num_warps( + num_warps, + max_num_warps=8, + min_num_warps=2, + register_intensive=False, + *, + warp_size: int = 32, +): + # On wave64 AMD GPUs (CDNA / gfx9) each warp has 64 lanes, double NVIDIA + # and RDNA, so use half the number of warps to keep total thread count + # comparable. RDNA (wave32) follows the NVIDIA path. + if warp_size == 64: + max_num_warps = (max_num_warps + 1) // 2 + min_num_warps = (min_num_warps + 1) // 2 + # persistent reduction is register intensive + if register_intensive: + max_num_warps = max_num_warps // 2 + return next_power_of_2(min(max(num_warps, min_num_warps), max_num_warps)) + + +def _check_max_grid_x(size_hints, x, num_warps, *, warp_size: int = 32): + # Check if maxGridSize is exceeded - if so then must scale XBLOCK further + max_grid_x = 2147483647 + max_block_x = TRITON_MAX_BLOCK["X"] + num_blocks = (size_hints["x"] + x - 1) // x + + if torch.version.hip: + # HIP has a 2^31-1 limit on total threads (num_blocks * num_warps * warp_size) + while ( + (num_blocks * num_warps * warp_size) > max_grid_x + and x < size_hints["x"] + and x < max_block_x + ): + x *= 2 + num_blocks = num_blocks // 2 + else: + # NVIDIA has a 2^31-1 limit on number of blocks in grid (not total threads) + while num_blocks > max_grid_x and x < size_hints["x"] and x < max_block_x: + x *= 2 + num_blocks = num_blocks // 2 + + if num_blocks > max_grid_x: + raise AssertionError( + "Reduction config exceeds cudaDeviceProp maxGridSize. Please raise a pytorch issue" + ) + return x, num_blocks + + +def triton_config( + size_hints, + x, + y=None, + z=None, + num_stages=1, + num_elements_per_warp=256, + min_elem_per_thread=0, + num_warps=None, + matrix_instr=None, + waves_per_eu=None, + kpack=None, + *, + warp_size: int = 32, +) -> Config: + """ + Construct a pointwise triton config with some adjustment heuristics + based on size_hints. Size_hints is a tuple of numels in each tile + dimension and will be rounded up to the nearest power of 2. + + num_elements_per_warp is a suggestion for controlling how many warps + the triton config should contain. e.g.: if x=16, y=8, z=4 then + num_elements = 16*8*4 = 512. Then if we set num_elements_per_warp=128, + we'll launch 512 (elem) / 128 (elem/warp) = 4 warps. Note that it's + just a suggestion, and sometimes other adjustment heuristics will + override the num_elements_per_warp. + + min_elem_per_thread controls the minimum number of elements + processed by each thread. It's always enforced. + """ + # Ideally we want to read this from some device config + + maxGridSize = [2147483647, 65535, 65535] + + target = conditional_product(x, y, z) + if conditional_product(*size_hints.values()) < target: + target //= 8 + + # shrink sizes to size hints + x = min(x, size_hints["x"]) + if y: + y = min(y, size_hints["y"]) + if z: + z = min(z, size_hints["z"]) + + # if we are below original block size, scale up where we can; + # or if the calculated grid size is larger than the limit, we bump up the corresponding dimension + while x < min(size_hints["x"], TRITON_MAX_BLOCK["X"]) and ( + x * maxGridSize[0] < size_hints["x"] or conditional_product(x, y, z) < target + ): + x *= 2 + while ( + y + and y < min(size_hints["y"], TRITON_MAX_BLOCK["Y"]) + and ( + y * maxGridSize[1] < size_hints["y"] + or conditional_product(x, y, z) < target + ) + ): + y *= 2 + while ( + z + and z < min(size_hints["z"], TRITON_MAX_BLOCK["Z"]) + and ( + z * maxGridSize[2] < size_hints["z"] + or conditional_product(x, y, z) < target + ) + ): + z *= 2 + + # Calculate num_warps if they are not hard passed to config + if num_warps is None: + num_warps = _num_warps( + conditional_product(x, y, z) // num_elements_per_warp, + min_num_warps=1, + warp_size=warp_size, + ) + # we are going to arrive at 2 warps only if bs was too small due to + # numel being too small. However to workaround some ptx bugs we still + # want at least 4 warps if there's enough elements per thread + # given that this is a rare situation, don't expect this to affect perf + # in general + # see https://github.com/pytorch/pytorch/pull/97950 + if conditional_product(x, y, z) >= 128 and not torch.version.hip: + num_warps = max(num_warps, 4) + xnumel = size_hints["x"] + ynumel = size_hints.get("y") + znumel = size_hints.get("z") + + # Increase x to satisfy min_elem_per_thread requirements. + block_size = max( + conditional_product(x, y, z), + min_elem_per_thread * warp_size * num_warps, + ) + x *= math.ceil(block_size / conditional_product(x, y, z)) + + x, _num_blocks = _check_max_grid_x(size_hints, x, num_warps, warp_size=warp_size) + x = min(x, size_hints["x"]) + + cfg = {"XBLOCK": x} + if y: + cfg["YBLOCK"] = y + if z: + cfg["ZBLOCK"] = z + check_max_block(cfg) + check_config(cfg, xnumel=xnumel, ynumel=ynumel, znumel=znumel) + config = Config(cfg, num_warps=num_warps, num_stages=num_stages) + + if torch.version.hip: + if matrix_instr is not None: + config.kwargs["matrix_instr_nonkdim"] = matrix_instr + if waves_per_eu is not None: + config.kwargs["waves_per_eu"] = waves_per_eu + if kpack is not None: + config.kwargs["kpack"] = kpack + + return config + + +def _get_nd_reduction_numels(r: int, size_hints: dict[str, int]) -> dict[str, int]: + """ + Converts a linear reduction numel to ND, in row major order. + This order is often desirable as it presents opportunities to coalesce memory + accesses. + For example, if r = 64 and size_hints = [32,32], this function returns [32, 2]. + This unraveling works because both r and size_hints are powers of 2. + """ + # Shrink r to size_hints. + r = min(r, get_total_reduction_numel(size_hints)) + num_reduction_dims = len( + [prefix for prefix in size_hints if prefix_is_reduction(prefix)] + ) + + remaining = r + rnumels = {} + for idx in range(num_reduction_dims - 1, -1, -1): + prefix = f"r{idx}_" + max_size = min(size_hints[prefix], TRITON_MAX_BLOCK[prefix.upper()]) + dim = min(max_size, remaining) + if remaining % dim != 0: + raise AssertionError( + f"Expected dimension '{dim}' to divide remaining size '{remaining}'" + ) + rnumels[prefix] = dim + remaining //= dim + + # Sanity check the results. + final_numel = conditional_product(*rnumels.values()) + if r != final_numel: + raise AssertionError( + f"Expected ND reduction size ({rnumels}) to have {r} elements." + ) + if not all(rnumels[prefix] <= size_hints[prefix] for prefix in rnumels): + raise AssertionError(f"rnumels exceed size_hints. {rnumels} > {size_hints}") + + return rnumels + + +def triton_config_reduction( + size_hints, + x: int, + r: int, + num_stages=1, + num_warps=None, + register_intensive=False, + waves_per_eu=None, + dynamic_scale_rblock=True, + reduction_hint=None, + min_num_warps=None, + *, + warp_size: int = 32, +) -> Config: + """ + Construct a reduction triton config with some adjustment heuristics + based on size_hints. Size_hints is a tuple of numels in each tile + dimension and will be rounded up to the nearest power of 2. + """ + # Convert the linear reduction numel into a multi-dimensional block. + rnumels = _get_nd_reduction_numels(r, size_hints) + + # shrink sizes to size hints + x = min(x, size_hints["x"]) + target = conditional_product(x, *rnumels.values()) + if conditional_product(*size_hints.values()) < target: + target //= 8 + + def total_numel() -> int: + return conditional_product(x, *rnumels.values()) + + # if we are below original block size, scale up where we can + while x < size_hints["x"] and total_numel() < target: + x *= 2 + for prefix in sorted(rnumels): + while rnumels[prefix] < size_hints[prefix] and total_numel() < target: + rnumels[prefix] *= 2 + + if num_warps is None: + if reduction_hint == ReductionHint.INNER: + # r is contiguous, ensure at least 8 elements per thread + # xblock is usually 1-2, default to giving each thread more work + num_warps = r // 128 + else: + num_warps = total_numel() // 128 + + max_num_warps = 16 if r <= 8192 else 32 + if min_num_warps is not None: + _num_warps_func = functools.partial(_num_warps, min_num_warps=min_num_warps) + else: + _num_warps_func = _num_warps + + num_warps = _num_warps_func( + num_warps, + max_num_warps=max_num_warps, + register_intensive=register_intensive, + warp_size=warp_size, + ) + + x, _num_blocks = _check_max_grid_x(size_hints, x, num_warps, warp_size=warp_size) + + for prefix in sorted(rnumels): + while total_numel() > target: + if rnumels[prefix] == 1: + break + rnumels[prefix] //= 2 + + cfg = _get_config({"x": x, **rnumels}) + check_max_block(cfg) + check_config(cfg, xnumel=size_hints["x"]) + config = InductorConfig( + cfg, + num_warps=num_warps, + num_stages=num_stages, + dynamic_scale_rblock=dynamic_scale_rblock, + ) + + if torch.version.hip: + if waves_per_eu is not None: + config.kwargs["waves_per_eu"] = waves_per_eu + + return config + + +def _get_config(numels: dict[str, int]) -> dict[str, int]: + """ + Convert numels ("x", "r0_", etc.) to block sizes ("XBLOCK", "R0_BLOCK"), etc. + """ + + return {prefix.upper() + "BLOCK": numel for prefix, numel in numels.items()} + + +def _subkernel_fingerprint(combo_meta: dict[str, Any], i: int) -> tuple[Any, ...]: + """Per-sub-kernel heuristic inputs as a hashable tuple. Identical + fingerprints imply identical heuristic output. + + Per-kernel fields (num_load, autotune_hints, tiling_scores, etc.) live + inside combo_meta[f"inductor_meta_{i}"] (single source of truth — see + TritonKernel.inductor_meta_per_kernel). Combo-level fields (heuristic, + size_hints, tile_hint, reduction_hint) remain top-level in combo_meta. + """ + sub_meta = combo_meta.get(f"inductor_meta_{i}", {}) + tma = sub_meta.get("tma_min_block_sizes") or {} + tiling_scores = sub_meta.get("tiling_scores") or {} + return ( + combo_meta[f"heuristic_{i}"], + tuple(sorted(combo_meta[f"size_hints_{i}"].items())), + sub_meta.get("num_load"), + sub_meta.get("num_store"), + sub_meta.get("num_reduction"), + tuple(sorted(sub_meta.get("autotune_hints") or [], key=str)), + sub_meta.get("atomic_add_found"), + sub_meta.get("no_x_dim"), + combo_meta.get(f"reduction_hint_{i}"), + combo_meta.get(f"tile_hint_{i}"), + sub_meta.get("add_persistent_rblock", False), + sub_meta.get("has_loadstore_with_contiguous_rdim"), + sub_meta.get("uses_device_tma", False), + tuple(sorted(tma.items())), + tuple(sorted(tiling_scores.items())), + ) + + +def _update_combo_kernel_kwargs( + kwargs: dict[str, Any], + cfg_kwargs: dict[str, Any], + subkernel_idx: int, + skip_rblock: bool, + block_arg_names: OrderedSet[str], +) -> None: + for key, value in cfg_kwargs.items(): + if skip_rblock and key.startswith("R") and "BLOCK" in key: + continue + suffixed_key = f"{key}_{subkernel_idx}" + # Only suffix keys emitted as combo kernel block arguments. + # Everything else must stay unsuffixed so HIP-specific compile options like + # waves_per_eu continue to flow through the backend-options path above. + kwargs[suffixed_key if suffixed_key in block_arg_names else key] = value + + +def _handle_combo_kernel_per_subkernel_blocks( + size_hints: dict[str, int], + inductor_meta: InductorMeta, + triton_meta: TritonMeta, + filename: str | None = None, + reduction_hint: bool = False, + tile_hint: Any = None, + min_elem_per_thread: int = 0, +) -> list[Config] | None: + """ + Handle per-subkernel config generation for combo kernels. + + Each sub-kernel gets its own block sizes (XBLOCK_0, XBLOCK_1, etc.) generated + using the same heuristics as standalone Triton kernels. + + Returns base configs that vary (num_warps, num_stages) with all blocks at + heuristic defaults. Stores per-subkernel candidate configs in + inductor_meta["combo_tuning_groups"] for sequential chained autotuning + in CachingAutotuner._combo_sequential_autotune(). + + Returns: + List of configs if combo kernel with combo_grid_meta and per-subkernel + blocks enabled, None otherwise. + """ + combo_meta = inductor_meta.get("combo_grid_meta") + if combo_meta is None or "heuristic_0" not in combo_meta: + return None + + # CAP no-bench: combo_grid_meta carries a stitched config; skip the + # combo_tuning_groups computation and return a single stitched config. + # default_config holds BLOCK keys for the grid lambda; backend kwargs + # (HIP options like waves_per_eu) come from stitched_backend_kwargs. + stitched_warps = combo_meta.get("stitched_num_warps") + if "stitched_launch_candidates" in combo_meta or stitched_warps is not None: + # Compile-time autotune emits the distinct winner launch configs (kwargs, num_warps, + # num_stages) -> combo autotunes kernel-level knobs over them; the chosen block sizes + # are passed as args via default_config. No-bench mode has no candidates and reuses + # default_config for the explicitly recorded combo block arguments. + if "stitched_launch_candidates" in combo_meta: + launch_candidates = combo_meta["stitched_launch_candidates"] + block_config = combo_meta.get("default_config") or {} + return [ + triton.Config({**block_config, **kwargs}, num_warps=nw, num_stages=ns) + for kwargs, nw, ns in launch_candidates + ] + block_arg_names = OrderedSet(combo_meta.get("block_arg_names", ())) + block_config = { + k: v + for k, v in (combo_meta.get("default_config") or {}).items() + if k in block_arg_names + } + return [ + triton.Config( + {**block_config, **combo_meta["stitched_backend_kwargs"]}, + num_warps=stitched_warps, + num_stages=combo_meta["stitched_num_stages"], + ) + ] + + num_kernels = combo_meta["num_kernels"] + inductor_meta_clean = { + k: v for k, v in inductor_meta.items() if k != "combo_grid_meta" + } + + combined_kwargs: dict[str, int] = {} + all_num_warps: list[int] = [] + all_num_stages: list[int] = [] + unique_warp_stage_pairs: OrderedSet[tuple[int, int]] = OrderedSet() + combo_coordesc_field_limits: dict[str, int] = {} + block_arg_names = OrderedSet(combo_meta.get("block_arg_names", ())) + + # Group sub-kernels with identical config kwargs to skip redundant tuning. + group_map: dict[tuple[Any, ...], dict[str, Any]] = {} + + for i in range(num_kernels): + subkernel_heuristic = combo_meta[f"heuristic_{i}"] + size_hints_i = combo_meta[f"size_hints_{i}"] + # Per-sub-kernel inductor_meta passthrough packed by combo_grid_meta() + # via TritonKernel.inductor_meta_per_kernel(). Forward into + # inductor_meta_i so pointwise()/_reduction_configs()/_persistent_reduction_configs() + # pick configs based on the actual sub-kernel . + inductor_meta_i = cast( + "InductorMeta", + { + **inductor_meta_clean, + **combo_meta.get(f"inductor_meta_{i}", {}), + }, + ) + + if subkernel_heuristic == "pointwise": + cfgs = pointwise( + size_hints_i, + triton_meta=triton_meta, + tile_hint=( + TileHint.SQUARE + if combo_meta[f"tile_hint_{i}"] == "TileHint.SQUARE" + else TileHint.DEFAULT + ), + filename=filename, + min_elem_per_thread=min_elem_per_thread, + inductor_meta=inductor_meta_i, + return_configs=True, + ) + skip_rblock = False + elif subkernel_heuristic == "reduction": + cfgs = reduction( + size_hints_i, + reduction_hint=ReductionHint[combo_meta[f"reduction_hint_{i}"]], + triton_meta=triton_meta, + filename=filename, + inductor_meta=inductor_meta_i, + return_configs=True, + ) + skip_rblock = False + elif subkernel_heuristic == "persistent_reduction": + cfgs = persistent_reduction( + size_hints_i, + reduction_hint=ReductionHint[combo_meta[f"reduction_hint_{i}"]], + triton_meta=triton_meta, + filename=filename, + inductor_meta=inductor_meta_i, + return_configs=True, + ) + skip_rblock = True # persistent reduction embeds RBLOCK in kernel body + else: + raise ValueError(f"Unknown heuristic: {subkernel_heuristic}") + + group_coordesc_fields: OrderedSet[str] = OrderedSet() + cfg = cfgs[0] + _update_combo_kernel_kwargs( + combined_kwargs, cfg.kwargs, i, skip_rblock, block_arg_names + ) + for key in cfg.kwargs: + if skip_rblock and key.startswith("R") and "BLOCK" in key: + continue + if not key.endswith("BLOCK"): + continue + combined_key = f"{key}_{i}" + group_coordesc_fields.add(combined_key) + prefix = key.removesuffix("BLOCK").lower() + if prefix in size_hints_i: + combo_coordesc_field_limits[combined_key] = min( + TRITON_MAX_BLOCK[prefix.upper()], + size_hints_i[prefix], + ) + + all_num_warps.append(cfg.num_warps) + all_num_stages.append(cfg.num_stages) + for c in cfgs: + unique_warp_stage_pairs.add((c.num_warps, c.num_stages)) + + group_key = ( + _subkernel_fingerprint(combo_meta, i) + if combo_meta.get("autotune_grouping") + else (i,) + ) + if group_key in group_map: + group_map[group_key]["member_indices"].append(i) + else: + group_map[group_key] = { + "member_indices": [i], + "configs": cfgs, + "skip_rblock": skip_rblock, + "size_hints": size_hints_i, + "coordesc_fields": list(group_coordesc_fields), + } + + unique_warp_stage_pairs.add((max(all_num_warps), max(all_num_stages))) + + combo_tuning_groups = list(group_map.values()) + # Largest sub-kernels tuned first — they dominate runtime and get most freedom + combo_tuning_groups.sort( + key=lambda g: -functools.reduce(operator.mul, g["size_hints"].values()) + ) + inductor_meta["combo_tuning_groups"] = combo_tuning_groups + inductor_meta["combo_coordesc_field_order"] = [ + field for group in combo_tuning_groups for field in group["coordesc_fields"] + ] + inductor_meta["combo_coordesc_field_limits"] = combo_coordesc_field_limits + # Candidates for num_warps/num_stages re-tuning after block sizes are finalized + inductor_meta["combo_warp_stage_candidates"] = list(unique_warp_stage_pairs) + + # Single base config: max warps/stages, all blocks at heuristic defaults. + # Block sizes are tuned in _combo_sequential_autotune, then num_warps/num_stages + # are re-tuned at the end with finalized block sizes. + base_num_warps = max(all_num_warps) + base_num_stages = max(all_num_stages) + return [ + triton.Config( + combined_kwargs, + num_warps=base_num_warps, + num_stages=base_num_stages, + ) + ] + + +def triton_config_tiled_reduction( + size_hints, + x, + y, + r, + num_stages=1, + register_intensive=False, + waves_per_eu=None, + *, + warp_size: int = 32, +): + """ + Construct a tile reduction triton config with some adjustment + heuristics based on size_hints. Size_hints is a tuple of numels in + each tile dimension and will be rounded up to the nearest power of 2. + """ + # Convert the linear reduction numel into a multi-dimensional block. + rnumels = _get_nd_reduction_numels(r, size_hints) + + # shrink sizes to size hints + x = min(x, size_hints["x"]) + y = min(y, size_hints["y"]) + + def total_numel() -> int: + return conditional_product(x, y, *rnumels.values()) + + target = total_numel() + if conditional_product(*size_hints.values()) < target: + target //= 8 + + # if we are below original block size, scale up where we can + while x < size_hints["x"] and total_numel() < target: + x *= 2 + for prefix in sorted(rnumels): + while rnumels[prefix] < size_hints[prefix] and total_numel() < target: + rnumels[prefix] *= 2 + while y < size_hints["y"] and total_numel() < target: + y *= 2 + + cfg = _get_config({"x": x, "y": y, **rnumels}) + num_warps = _num_warps(total_numel() // 256, min_num_warps=1, warp_size=warp_size) + num_warps = _num_warps( + num_warps, + max_num_warps=16, + register_intensive=register_intensive, + warp_size=warp_size, + ) + check_config(cfg, xnumel=size_hints["x"], ynumel=size_hints["y"]) + check_max_block(cfg) + config = Config(cfg, num_warps=num_warps, num_stages=num_stages) + if torch.version.hip: + if waves_per_eu is not None: + config.kwargs["waves_per_eu"] = waves_per_eu + return config + + +def _maybe_filter_configs_for_tma_restrictions( + inductor_meta: InductorMeta, configs: list[Config] +): + tma_min_block_sizes: dict[str, int] | None + if (tma_min_block_sizes := inductor_meta.get("tma_min_block_sizes")) and configs: + # Rn blocks are not provided to the kernel for persistent reductions + if inductor_meta.get("persistent_reduction"): + tma_min_block_sizes = { + block_type: block_size + for block_type, block_size in tma_min_block_sizes.items() + if not prefix_is_reduction(block_type.lower()) + } + + if not all( + block_type in configs[0].kwargs for block_type in tma_min_block_sizes + ): + raise AssertionError( + f"Not all TMA block types found in config kwargs: " + f"missing {OrderedSet(tma_min_block_sizes) - OrderedSet(configs[0].kwargs)}" + ) + + # Add a config that is guaranteed to compile + example_config = configs[0] + config_block_sizes = {**example_config.kwargs} + for block_type, min_block_value in tma_min_block_sizes.items(): + existing = config_block_sizes.get(block_type, 1) + config_block_sizes[block_type] = max(existing, min_block_value) + new_configs = [ + Config( + config_block_sizes, + num_warps=example_config.num_warps, + num_stages=example_config.num_stages, + maxnreg=example_config.maxnreg, + pre_hook=example_config.pre_hook, + ) + ] + # Remove configs that will not compile + for c in configs: + if all( + c.kwargs.get(block_type) >= min_block_value + for block_type, min_block_value in tma_min_block_sizes.items() + ): + new_configs.append(c) + + log.debug( + "Filtering configs for TMA API restrictions. Input configs size: %d. Output configs size: %d", + len(configs), + len(new_configs), + ) + return new_configs + return configs + + +def pointwise( + size_hints, + triton_meta: TritonMeta, + tile_hint=None, + filename=None, + min_elem_per_thread=0, + inductor_meta: InductorMeta | None = None, + return_configs=False, +): + """ + Construct @triton.heuristics() based on size_hints. + """ + inductor_meta = {} if inductor_meta is None else inductor_meta + + configs = _handle_combo_kernel_per_subkernel_blocks( + size_hints, + inductor_meta, + triton_meta, + filename=filename, + tile_hint=tile_hint, + min_elem_per_thread=min_elem_per_thread, + ) + if configs is not None: + return cached_autotune( + None, + configs, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + heuristic_type=HeuristicType.POINTWISE, + filename=filename, + ) + + if inductor_meta.get("no_x_dim"): + raise AssertionError("no_x_dim should not be set for this heuristic") + + numel = functools.reduce(operator.mul, size_hints.values()) + bs = max(256, min(numel // 128, 1024)) + + hinted_configs = autotune_hints_to_configs( + inductor_meta.get("autotune_hints", OrderedSet()), + size_hints, + bs, + triton_meta["device"], + ) + + warp_size = triton_meta["device"].warp_size_or_default + triton_config_with_settings = functools.partial( + triton_config, min_elem_per_thread=min_elem_per_thread, warp_size=warp_size + ) + + from torch._inductor.heuristics.registry import get_codegen_heuristic + + pointwise_heuristic = get_codegen_heuristic("pointwise", triton_meta["device"].type) + configs = pointwise_heuristic.get_configs( + size_hints, + bs, + triton_config_with_settings, + hinted_configs, + tile_hint=tile_hint, + inductor_meta=inductor_meta, + ) + + configs = _maybe_filter_configs_for_tma_restrictions(inductor_meta, configs) + if return_configs: + return configs + + return cached_autotune( + size_hints, + configs, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + heuristic_type=HeuristicType.POINTWISE, + filename=filename, + ) + + +def make_matmul_triton_config(sizes: dict[str, int], num_warps: int, num_stages: int): + config = { + "XBLOCK": sizes.get("x"), + "YBLOCK": sizes.get("y"), + "ZBLOCK": sizes.get("z"), + "R0_BLOCK": sizes.get("r"), + } + # Remove keys with None values (i.e., missing in sizes) + config = {k: v for k, v in config.items() if v is not None} + _check_native_matmul_block_numel(config) + return Config(config, num_warps=num_warps, num_stages=num_stages) + + +def _config_helper(bmm=False, persistent=False): + # Each entry is: (sizes_dict, num_warps, num_stages) + _base_mm_configs = [ + ({"x": 32, "y": 32, "r": 16}, 2, 1), + ({"x": 32, "y": 32, "r": 128}, 4, 2), + ({"x": 32, "y": 64, "r": 32}, 8, 5), + ({"x": 64, "y": 32, "r": 32}, 8, 5), + ({"x": 64, "y": 32, "r": 128}, 4, 5), + ({"x": 64, "y": 64, "r": 16}, 4, 2), + ({"x": 64, "y": 64, "r": 32}, 4, 2), + ({"x": 64, "y": 64, "r": 64}, 8, 3), + ({"x": 64, "y": 64, "r": 128}, 4, 5), + ({"x": 64, "y": 128, "r": 32}, 4, 3), + ({"x": 64, "y": 128, "r": 32}, 8, 4), + ({"x": 64, "y": 128, "r": 64}, 4, 3), + ({"x": 64, "y": 128, "r": 128}, 4, 4), + ({"x": 128, "y": 64, "r": 32}, 4, 3), + ({"x": 128, "y": 64, "r": 32}, 8, 4), + ({"x": 128, "y": 128, "r": 32}, 8, 2), + ({"x": 128, "y": 128, "r": 32}, 4, 3), + ({"x": 128, "y": 128, "r": 64}, 4, 3), + ({"x": 128, "y": 128, "r": 64}, 8, 5), + ] + out = [] + for sizes, w, s in _base_mm_configs: + d = dict(sizes) + if persistent: + d.pop("r", None) + if bmm: + d["z"] = 1 + out.append((d, w, s)) + + # Deduplicate by converting dicts to immutable frozensets + deduped = {(frozenset(d.items()), w, s): (d, w, s) for d, w, s in out} + + return list(deduped.values()) + + +triton_native_mm_configs = _config_helper(bmm=False, persistent=False) +triton_native_persistent_mm_configs = _config_helper(bmm=False, persistent=True) +triton_native_bmm_configs = _config_helper(bmm=True, persistent=False) +triton_native_persistent_bmm_configs = _config_helper(bmm=True, persistent=True) + + +def _reduction_configs( + *, + size_hints: dict[str, int], + inductor_meta: InductorMeta, + triton_meta: TritonMeta, + num_dynamic=0, +) -> list[Config]: + from torch._inductor.heuristics.registry import get_codegen_heuristic + + reduction_heuristic = get_codegen_heuristic("reduction", triton_meta["device"].type) + configs = reduction_heuristic.get_configs( + size_hints=size_hints, + inductor_meta=inductor_meta, + triton_meta=triton_meta, + num_dynamic=num_dynamic, + ) + r0 = inductor_meta.get("strict_sum_rblock") + if r0 is not None: + configs = copy.deepcopy(configs) + for triton_config in configs: + if "R0_BLOCK" in triton_config.kwargs: + triton_config.kwargs["R0_BLOCK"] = r0 + configs = unique_configs(configs) + return configs + + +def filter_reduction_configs_for_determinism( + inductor_meta: InductorMeta, configs: list[Config] +) -> list[Config]: + """ + Filter configs for reduction so the numerics can be deterministic. + + Heuristics: + - skip reduction configs with too small RBLOCK + - skip reduction configs with XBLOCK==1 if we are confident it will not perform well + - if there is a tie, pick the config with second largest RBLOCK + - if there is still a tie, pick the config with second largest num_warps + - if there is still a tie, pick the config with second largest XBLOCK + """ + configs = unique_configs(configs) + if len(configs) == 0: + raise AssertionError("No configs remaining after deduplication") + + def _do_filter_due_to_inductor_config(): + return ( + inductor_meta.get("deterministic", False) + or inductor_meta.get("force_filter_reduction_configs", False) + ) or inductor_meta.get("are_deterministic_algorithms_enabled") + + if not _do_filter_due_to_inductor_config() or len(configs) == 1: + # no filtering happening if NOT in deterministic mode + return configs + + if log.isEnabledFor(logging.DEBUG): + log.debug("reduction configs before filtering:") + for c in configs: + log.debug("%s", c) + log.debug("") + + def _has_too_small_rblock(config): + rblock = config.kwargs.get("R0_BLOCK") + # too small RBLOCK is likely to be bad + return rblock is not None and rblock <= 4 + + def _nonpromising_xblock_1(config): + # kernel like https://gist.github.com/shunting314/0b3281c087e79bc915fe45985ff9d7d5 + # without a load/store having contiguous rdim is unlikely to perform well with XBLOCK==1 + return config.kwargs["XBLOCK"] == 1 and not inductor_meta.get( + "has_loadstore_with_contiguous_rdim", True + ) + + newconfigs = [*filter(lambda x: not _has_too_small_rblock(x), configs)] + # accept the filtering only if there are configs left + if len(newconfigs) > 0: + configs = newconfigs + + newconfigs = [*filter(lambda x: not _nonpromising_xblock_1(x), configs)] + if len(newconfigs) > 0: + configs = newconfigs + + if len(configs) == 0: + raise AssertionError("No configs remaining after filtering") + + def _r0_block(c): + return c.kwargs.get("R0_BLOCK", -1) + + def _xblock(c): + return c.kwargs.get("XBLOCK", -1) + + def _num_warps(c): + return c.num_warps + + def _pick_second_largest(accessor): + nonlocal configs + configs = sorted(configs, key=lambda x: accessor(x)) + if accessor(configs[0]) != accessor(configs[-1]): + max_val = accessor(configs[-1]) + configs = [*filter(lambda x: accessor(x) != max_val, configs)] + second_max_val = accessor(configs[-1]) + configs = [*filter(lambda x: accessor(x) == second_max_val, configs)] + return configs + + def _pick_config(): + nonlocal configs + if len(configs) == 0: + raise AssertionError("No configs available for selection") + if len(configs) == 1: + return configs[0] + + # break tie by R0_BLOCK + configs = _pick_second_largest(_r0_block) + if len(configs) == 1: + return configs[0] + + # break tie by num_warps + configs = _pick_second_largest(_num_warps) + if len(configs) == 1: + return configs[0] + + # break tie by XBLOCK + configs = _pick_second_largest(_xblock) + + # there is still a tie, pick the first one + return configs[0] + + configs = [_pick_config()] + + if log.isEnabledFor(logging.DEBUG): + log.debug("reduction configs after filtering:") + for c in configs: + log.debug("%s", c) + log.debug("") + return configs + + +def reduction( + size_hints, + reduction_hint=False, + triton_meta: TritonMeta | None = None, + filename=None, + inductor_meta: InductorMeta | None = None, + return_configs=False, +): + """args to @triton.heuristics()""" + inductor_meta = {} if inductor_meta is None else inductor_meta + inductor_meta["reduction_hint"] = reduction_hint + if inductor_meta.get("no_x_dim"): + size_hints["x"] = 1 + + if triton_meta is None: + raise AssertionError("triton_meta must not be None") + + configs = _handle_combo_kernel_per_subkernel_blocks( + size_hints, + inductor_meta, + triton_meta, + filename=filename, + reduction_hint=reduction_hint, + ) + if configs is not None: + return cached_autotune( + None, + configs, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + heuristic_type=HeuristicType.REDUCTION, + filename=filename, + ) + + if triton_meta is None: + raise AssertionError("triton_meta must not be None") + + num_dynamic = 0 + for k in triton_meta["signature"]: + if "ks" in k: + num_dynamic += 1 + + configs = _reduction_configs( + size_hints=size_hints, + inductor_meta=inductor_meta, + triton_meta=triton_meta, + num_dynamic=num_dynamic, + ) + + configs = _maybe_filter_configs_for_tma_restrictions(inductor_meta, configs) + configs = filter_reduction_configs_for_determinism(inductor_meta, configs) + strict_rblock = inductor_meta.get("strict_sum_rblock") + if strict_rblock is not None and any( + triton_config.kwargs.get("R0_BLOCK", strict_rblock) != strict_rblock + for triton_config in configs + ): + raise AssertionError("strict sum requires its planned R0_BLOCK") + + if return_configs: + return configs + + return cached_autotune( + size_hints, + configs=configs, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + heuristic_type=HeuristicType.REDUCTION, + filename=filename, + ) + + +def cooperative_reduction( + size_hints, + reduction_hint, + triton_meta: TritonMeta, + filename, + inductor_meta: InductorMeta | None = None, +): + inductor_meta = {} if inductor_meta is None else inductor_meta + inductor_meta["reduction_hint"] = reduction_hint + if inductor_meta.get("no_x_dim"): + size_hints["x"] = 1 + + from torch._inductor.heuristics.registry import get_codegen_heuristic + + reduction_heuristic = get_codegen_heuristic("reduction", triton_meta["device"].type) + configs = reduction_heuristic.get_cooperative_configs( + size_hints=size_hints, + reduction_hint=reduction_hint, + inductor_meta=inductor_meta, + triton_meta=triton_meta, + ) + # TODO(jansel): add more configs in max_autotune + + configs = _maybe_filter_configs_for_tma_restrictions(inductor_meta, configs) + configs = filter_reduction_configs_for_determinism(inductor_meta, configs) + return cached_autotune( + size_hints, + configs=configs, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + heuristic_type=HeuristicType.REDUCTION, + filename=filename, + ) + + +def _persistent_reduction_configs( + size_hints, + reduction_hint=False, + inductor_meta: InductorMeta | None = None, + triton_meta: TritonMeta | None = None, +): + from torch._inductor.heuristics.registry import get_codegen_heuristic + + reduction_heuristic = get_codegen_heuristic("reduction", triton_meta["device"].type) + return reduction_heuristic.get_persistent_configs( + size_hints=size_hints, + reduction_hint=reduction_hint, + inductor_meta=inductor_meta, + triton_meta=triton_meta, + ) + + +def persistent_reduction( + size_hints, + reduction_hint=False, + triton_meta: TritonMeta | None = None, + filename=None, + inductor_meta: InductorMeta | None = None, + return_configs=False, +): + """Generate persistent reductions + mix-order if available""" + inductor_meta = {} if inductor_meta is None else inductor_meta + inductor_meta["reduction_hint"] = reduction_hint + if inductor_meta.get("no_x_dim"): + size_hints["x"] = 1 + + if triton_meta is None: + raise AssertionError("triton_meta must not be None") + + configs = _handle_combo_kernel_per_subkernel_blocks( + size_hints, + inductor_meta, + triton_meta, + filename=filename, + reduction_hint=reduction_hint, + ) + if configs is not None: + return cached_autotune( + None, + configs, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + heuristic_type=HeuristicType.PERSISTENT_REDUCTION, + filename=filename, + ) + + configs = _persistent_reduction_configs( + size_hints, reduction_hint, inductor_meta, triton_meta + ) + + # This key is not added to the inductor meta as its clear from the heuristic + # choice that it is persistent. Add it and remove it below so that persistent + # configs can be filtered appropriately by _maybe_filter_configs_for_tma_restrictions + persistent_reduction_key = "persistent_reduction" + inductor_meta[persistent_reduction_key] = True + configs = _maybe_filter_configs_for_tma_restrictions(inductor_meta, configs) + inductor_meta.pop(persistent_reduction_key) + + if inductor_meta.get("RSPLIT_SIZE"): + from torch._inductor.heuristics.registry import get_codegen_heuristic + + reduction_heuristic = get_codegen_heuristic( + "reduction", triton_meta["device"].type + ) + configs = reduction_heuristic.apply_rsplit_size( + configs, + size_hints=size_hints, + inductor_meta=inductor_meta, + ) + + configs = filter_reduction_configs_for_determinism(inductor_meta, configs) + + if return_configs: + return configs + + return cached_autotune( + size_hints, + configs, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + filename=filename, + heuristic_type=HeuristicType.PERSISTENT_REDUCTION, + ) + + +def split_scan( + size_hints, + reduction_hint=False, + triton_meta: TritonMeta | None = None, + filename=None, + inductor_meta: InductorMeta | None = None, +): + """Heuristic for TritonSplitScanKernel""" + inductor_meta = {} if inductor_meta is None else inductor_meta + inductor_meta["reduction_hint"] = reduction_hint + if inductor_meta.get("no_x_dim"): + size_hints["x"] = 1 + + if triton_meta is None: + raise AssertionError("triton_meta must not be None") + if len(size_hints) != 2: + raise NotImplementedError(f"size_hints: {size_hints}") + + from torch._inductor.heuristics.registry import get_codegen_heuristic + + reduction_heuristic = get_codegen_heuristic("reduction", triton_meta["device"].type) + configs = reduction_heuristic.get_split_scan_configs( + size_hints=size_hints, + inductor_meta=inductor_meta, + triton_meta=triton_meta, + ) + + configs = _maybe_filter_configs_for_tma_restrictions(inductor_meta, configs) + configs = filter_reduction_configs_for_determinism(inductor_meta, configs) + return cached_autotune( + size_hints, + configs=configs, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + heuristic_type=HeuristicType.SPLIT_SCAN, + filename=filename, + ) + + +def template( + num_stages, + num_warps, + triton_meta: TritonMeta, + num_consumer_groups=0, + num_buffers_warp_spec=0, + filename=None, + inductor_meta: InductorMeta | None = None, + **kwargs, +): + """ + Compile a triton template + """ + # Prepare the base configuration + config_args = { + "num_stages": num_stages, + "num_warps": num_warps, + } + + # Conditionally add arguments based on HAS_WARP_SPEC + if HAS_WARP_SPEC: + config_args.update( + { + "num_consumer_groups": num_consumer_groups, + "num_buffers_warp_spec": num_buffers_warp_spec, + } + ) + + for k in tlx_only_cuda_options(): + if v := triton_meta.get(k, None): + config_args[k] = v + + return cached_autotune( + None, + [triton.Config({}, **config_args)], + triton_meta=triton_meta, + inductor_meta=inductor_meta, + heuristic_type=HeuristicType.TEMPLATE, + filename=filename, + ) + + +def _pop_config_kwargs(config: dict[str, Any]) -> dict[str, Any]: + """Extract triton.Config options that should become kwargs""" + popped = {} + for key in ( + "num_warps", + "num_stages", + "num_ctas", + "maxnreg", + "num_consumer_groups", + "num_buffers_warp_spec", + ): + val = config.pop(key, None) + if val is not None: + popped[key] = val + return popped + + +def config_to_dict(config: Config) -> dict[str, Any]: + config_dict = { + **config.kwargs, + "num_warps": config.num_warps, + "num_stages": config.num_stages, + } + if HAS_WARP_SPEC: + config_dict.update( + { + "num_consumer_groups": getattr(config, "num_consumer_groups", 0), + "num_buffers_warp_spec": getattr(config, "num_buffers_warp_spec", 0), + } + ) + return config_dict + + +def config_from_dict(config: dict[str, Any]) -> Config: + config = {**config} + return Config(config, **_pop_config_kwargs(config)) + + +def fixed_config( + config, filename, triton_meta: TritonMeta, inductor_meta: InductorMeta +): + """ + Used when the configuration is already decided at compile time + """ + config = {**config} + return cached_autotune( + None, + [triton.Config(config, **_pop_config_kwargs(config))], + triton_meta=triton_meta, + inductor_meta=inductor_meta, + heuristic_type=HeuristicType.FIXED, + filename=filename, + ) + + +def user_autotune( + configs, + triton_meta: TritonMeta, + filename=None, + inductor_meta: InductorMeta | None = None, + custom_kernel=False, +): + """ + Compile a user defined triton kernel + """ + if len(configs) == 0: + configs = [triton.Config({})] + else: + configs = [*map(config_from_dict, configs)] + return cached_autotune( + None, + configs, + triton_meta=triton_meta, + heuristic_type=HeuristicType.USER_AUTOTUNE, + filename=filename, + inductor_meta=inductor_meta, + custom_kernel=custom_kernel, + ) + + +def foreach( + triton_meta: TritonMeta, filename=None, inductor_meta: InductorMeta | None = None +): + """ + Compile a triton foreach kernel + """ + inductor_meta = {} if inductor_meta is None else inductor_meta + configs = [] + + # Naive autotuning path for num_warps + if not ( + inductor_meta.get("max_autotune") or inductor_meta.get("max_autotune_pointwise") + ): + configs.append(triton.Config({}, num_stages=1, num_warps=8)) + else: + for warps in [1, 2, 4, 8]: + configs.append(triton.Config({}, num_stages=1, num_warps=warps)) + + return cached_autotune( + None, + configs, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + heuristic_type=HeuristicType.TEMPLATE, + filename=filename, + ) + + +@dataclasses.dataclass +class GridExpr: + """Generate code for grid size expressions in launcher""" + + inductor_meta: InductorMeta + mode: Literal["python", "cpp"] = "python" + prefix: list[str] = dataclasses.field(default_factory=list) + x_grid: str | int = 1 + y_grid: str | int = 1 + z_grid: str | int = 1 + + def __post_init__(self) -> None: + if self.mode not in ("python", "cpp"): + raise AssertionError(f"mode must be 'python' or 'cpp', got {self.mode!r}") + + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + raise NotImplementedError + + def ceildiv(self, numel: str | int, block: int | str | None) -> str | int: + if block is None or block == 1: + return numel + if isinstance(numel, int) and isinstance(block, int): + return ceildiv(numel, block) # constant fold + # This trick only works in python, where + # negative integer division is floored + if self.mode == "python": + return f"-(({numel}) // -({block}))" + # For cpp code gen + return f"(({numel} + ({block} - 1)) / ({block}))" + + def maximum(self, seq: list[int | str]) -> int | str: + """Codegen for max function with constant folding, constants are represented as int""" + items = self._constant_fold(max, seq) + if len(items) <= 1: + return items[0] + if self.mode == "python": + return f"max({', '.join(map(str, items))})" + # Cast int constants to (long) to avoid type deduction errors with std::max + # when mixing long variables with int literals + cpp_items = [f"(long){x}" if isinstance(x, int) else str(x) for x in items] + return functools.reduce(lambda x, y: f"std::max({x}, {y})", cpp_items) + + def summation(self, seq: list[int | str]) -> int | str: + """Codegen for sum function with constant folding, constants are represented as int""" + items = self._constant_fold(sum, seq) + if len(items) <= 1: + return items[0] + return " + ".join(map(str, items)) + + def product(self, seq: list[int | str]) -> int | str: + items = self._constant_fold(math.prod, seq) + if len(items) <= 1: + return items[0] + return " * ".join(map(str, items)) + + def _constant_fold( + self, fn: Callable[[list[int]], int], seq: list[int | str] + ) -> list[int | str]: + """Constant fold through a commutative fn where ints are constants""" + items: list[int | str] = [x for x in seq if not isinstance(x, int)] + const_items = [x for x in seq if isinstance(x, int)] + if const_items: + items.append(fn(const_items)) + return items + + def assign_tmp(self, name: str, expr: str | int) -> str: + # Grid functions are one per kernel, so name collisions are fine + if self.mode == "python": + return f"{name} = {expr}" + if self.mode == "cpp": + return f"uint32_t {name} = {expr};" + raise AssertionError(f"invalid mode {self.mode}") + + @staticmethod + def from_meta( + inductor_meta: InductorMeta, + cfg: Config | dict[str, int], + mode: Literal["python", "cpp"] = "python", + ) -> GridExpr: + grid_cls = globals()[inductor_meta["grid_type"]] + if not issubclass(grid_cls, GridExpr): + raise AssertionError(f"Expected GridExpr subclass, got {grid_cls}") + grid = grid_cls(inductor_meta=inductor_meta, mode=mode) + if isinstance(cfg, Config): + cfg = config_to_dict(cfg) + grid.generate(cfg) + return grid + + def eval_slow(self, meta: dict[str, int]) -> tuple[int, int, int]: + scope = {**meta} + for line in self.prefix: + exec(line, scope) + exec(f"grid_0 = {self.x_grid}", scope) + exec(f"grid_1 = {self.y_grid}", scope) + exec(f"grid_2 = {self.z_grid}", scope) + return scope["grid_0"], scope["grid_1"], scope["grid_2"] + + def generate_lazy(self, kernel_name: str) -> None: + """ + Creates a GridExpr for lazy compile, where config values are not known + at codegen time and are instead referenced by variable names. + """ + meta: dict[str, Any] = { + "XBLOCK": f"{kernel_name}_result.xblocks[0]", + "YBLOCK": f"{kernel_name}_result.yblocks[0]", + "ZBLOCK": f"{kernel_name}_result.zblocks[0]", + "R0_BLOCK": f"{kernel_name}_result.r0blocks[0]", + "RSPLIT": f"{kernel_name}_result.rsplit", + "RSPLIT_SIZE": f"{kernel_name}_result.rsplit_size", + } + # assertions are done based on real values, so we can skip here + self.generate(meta, is_lazy=True) + + @classmethod + def from_meta_lazy( + cls, + inductor_meta: InductorMeta | None, + kernel_name: str, + ) -> GridExpr: + """Factory method for lazy compile mode.""" + if inductor_meta is None: + raise AssertionError("inductor_meta must be specified for lazy compile") + grid_type = inductor_meta.get("grid_type", None) + if grid_type is None: + raise AssertionError("grid_type must be specified for lazy compile") + grid_cls = globals()[grid_type] + if not issubclass(grid_cls, GridExpr): + raise AssertionError(f"Expected GridExpr subclass, got {grid_cls}") + grid = grid_cls(inductor_meta=inductor_meta, mode="cpp") + grid.generate_lazy(kernel_name) + return grid + + +class Grid1D(GridExpr): + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + self.x_grid = self.ceildiv("xnumel", meta.get("XBLOCK")) + + +class Grid2D(GridExpr): + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + self.x_grid = self.ceildiv("xnumel", meta.get("XBLOCK")) + self.y_grid = self.ceildiv("ynumel", meta.get("YBLOCK")) + + +class Grid3D(GridExpr): + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + self.x_grid = self.ceildiv("xnumel", meta.get("XBLOCK")) + self.y_grid = self.ceildiv("ynumel", meta.get("YBLOCK")) + self.z_grid = self.ceildiv("znumel", meta.get("ZBLOCK")) + + +class BatchMatmulGrid3D(GridExpr): + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + self.z_grid = self.ceildiv("xnumel", meta.get("XBLOCK")) + self.y_grid = self.ceildiv("ynumel", meta.get("YBLOCK")) + self.x_grid = self.ceildiv("znumel", meta.get("ZBLOCK")) + + +class Grid2DWithYZOverflow(GridExpr): + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + self.x_grid = self.ceildiv("xnumel", meta.get("XBLOCK")) + self.prefix.extend( + [ + self.assign_tmp( + "y_grid_raw_", self.ceildiv("ynumel", meta.get("YBLOCK")) + ), + self.assign_tmp( + "y_grid_div_", self.ceildiv("y_grid_raw_", get_max_y_grid()) + ), + ] + ) + ceildiv_expr = self.ceildiv("y_grid_raw_", "y_grid_div_") + if self.mode == "python": + self.y_grid = f"(0 if y_grid_div_ == 0 else {ceildiv_expr})" + else: + self.y_grid = f"(y_grid_div_ == 0 ? 0 : {ceildiv_expr})" + self.z_grid = "y_grid_div_" + + +class MixOrderReductionGrid(GridExpr): + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + split_size = meta.get("RSPLIT_SIZE") + xblock = meta.get("XBLOCK") + if not is_lazy: + if not split_size: + raise AssertionError("Missing RSPLIT_SIZE") + if not xblock: + raise AssertionError("Missing XBLOCK") + if split_size % xblock != 0: + raise AssertionError(f"{split_size=}, {xblock=}") + self.x_grid = self.ceildiv("xnumel", split_size) + + +class CooperativeReductionGrid(GridExpr): + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + self.x_grid = str(meta["RSPLIT"]) + self.y_grid = self.ceildiv("xnumel", meta.get("XBLOCK")) + + +class SplitScanGrid(GridExpr): + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + if not is_lazy: + if meta.get("XBLOCK", 1) != 1: + raise AssertionError( + f"Expected XBLOCK == 1 for SplitScanGrid, got {meta.get('XBLOCK', 1)}" + ) + self.x_grid = self.ceildiv("r0_numel", meta.get("R0_BLOCK")) + self.y_grid = "xnumel" + + +class FixedGrid(GridExpr): + @staticmethod + def setup_grid_as_args() -> dict[str, Any]: + """Inductor meta so the launcher takes three extra grid arguments""" + return { + "grid_type": FixedGrid.__name__, + "fixed_grid": ["_grid_0", "_grid_1", "_grid_2"], + "extra_launcher_args": ["_grid_0", "_grid_1", "_grid_2"], + } + + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + self.x_grid, self.y_grid, self.z_grid = self.inductor_meta["fixed_grid"] + + +class PrecomputedGrid(GridExpr): + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + for candidate in self.inductor_meta["precomputed_grids"]: + if all(meta.get(k) == v for k, v in candidate["config"].items()): + self.x_grid, self.y_grid, self.z_grid = candidate[self.mode] + return + raise AssertionError( + f"Precomputed grid not found for {meta} in {self.inductor_meta['precomputed_grids']}" + ) + + +class ComboKernelGrid(GridExpr): + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + combo_meta = self.inductor_meta["combo_grid_meta"] + if combo_meta["default_config"]: + meta = {**combo_meta["default_config"], **meta} + no_x_dims = [] + xnumels = [] + ynumels = [] + + for num in range(combo_meta["num_kernels"]): + if ( + combo_meta[f"xnumel_{num}"] is not None + and combo_meta[f"xnumel_{num}"] <= 0 + ): + raise AssertionError( + f"xnumel_{num} must be None or positive, got {combo_meta[f'xnumel_{num}']}" + ) + no_x_dims.append(combo_meta[f"no_x_dim_{num}"]) + xnumels.append(combo_meta[f"xnumel_{num}"] or f"xnumel_{num}") + if f"ynumel_{num}" in combo_meta: + ynumels.append(combo_meta[f"ynumel_{num}"] or f"ynumel_{num}") + + self.x_grid = self.combo_x_grid(xnumels, no_x_dims, meta) + if combo_meta["min_blocks"]: + self.x_grid = self.maximum([self.x_grid, combo_meta["min_blocks"]]) + if ynumels: + self.prefix.extend( + [ + self.assign_tmp( + "y_grid_raw_", + self.ceildiv(self.maximum(ynumels), meta.get("YBLOCK")), + ), + self.assign_tmp( + "y_grid_div_", self.ceildiv("y_grid_raw_", get_max_y_grid()) + ), + ] + ) + ceildiv_expr = self.ceildiv("y_grid_raw_", "y_grid_div_") + if self.mode == "python": + self.y_grid = f"(0 if y_grid_div_ == 0 else {ceildiv_expr})" + else: + self.y_grid = f"(y_grid_div_ == 0 ? 0 : {ceildiv_expr})" + self.z_grid = "y_grid_div_" + + def combo_x_grid( + self, + xnumels: list[int | str], + no_x_dims: list[bool], + meta: dict[str, int], + ) -> str | int: + raise NotImplementedError + + +class SequentialComboKernelGrid(ComboKernelGrid): + def combo_x_grid( + self, + xnumels: list[int | str], + no_x_dims: list[bool], + meta: dict[str, int], + ) -> str | int: + if len(xnumels) != len(no_x_dims): + raise AssertionError( + f"xnumels and no_x_dims length mismatch: {len(xnumels)} != {len(no_x_dims)}" + ) + return self.summation( + [ + self.ceildiv(x, 1 if no_x_dim else meta.get("XBLOCK")) + for x, no_x_dim in zip(xnumels, no_x_dims) + ] + ) + + +class SequentialFlattenComboKernelGrid(GridExpr): + """Flattened grid: (sum of x*y blocks, 1, 1) for per-subkernel with flattened dispatch.""" + + def generate_lazy(self, kernel_name: str) -> None: + combo_meta = self.inductor_meta["combo_grid_meta"] + num_kernels = combo_meta["num_kernels"] + meta: dict[str, Any] = {} + for i in range(num_kernels): + meta[f"XBLOCK_{i}"] = f"{kernel_name}_result.xblocks[{i}]" + meta[f"YBLOCK_{i}"] = f"{kernel_name}_result.yblocks[{i}]" + self.generate(meta, is_lazy=True) + + def generate(self, meta: dict[str, int], is_lazy: bool = False) -> None: + combo_meta = self.inductor_meta["combo_grid_meta"] + if combo_meta["default_config"]: + meta = {**combo_meta["default_config"], **meta} + + total_blocks_list = [] + for num in range(combo_meta["num_kernels"]): + xnumel = combo_meta[f"xnumel_{num}"] + if xnumel is not None and xnumel <= 0: + raise AssertionError( + f"xnumel_{num} must be None or positive, got {xnumel}" + ) + xnumel = xnumel or f"xnumel_{num}" + x_blocks = self.ceildiv( + xnumel, + 1 if combo_meta[f"no_x_dim_{num}"] else meta.get(f"XBLOCK_{num}"), + ) + y_blocks = ( + self.ceildiv( + combo_meta[f"ynumel_{num}"] or f"ynumel_{num}", + meta.get(f"YBLOCK_{num}"), + ) + if f"ynumel_{num}" in combo_meta + else 1 + ) + total_blocks_list.append(self.product([x_blocks, y_blocks])) + + self.x_grid = self.summation(total_blocks_list) + if combo_meta["min_blocks"]: + self.x_grid = self.maximum([self.x_grid, combo_meta["min_blocks"]]) + self.y_grid = 1 + self.z_grid = 1 + + +class RoundRobinComboKernelGrid(ComboKernelGrid): + def combo_x_grid( + self, + xnumels: list[int | str], + no_x_dims: list[bool], + meta: dict[str, int], + ) -> str: + if len(xnumels) != len(no_x_dims): + raise AssertionError( + f"xnumels and no_x_dims length mismatch: {len(xnumels)} != {len(no_x_dims)}" + ) + num_kernels = self.inductor_meta["combo_grid_meta"]["num_kernels"] + exprs = [x for x, no_x_dim in zip(xnumels, no_x_dims) if no_x_dim] + xnumels_x_dim = [x for x, no_x_dim in zip(xnumels, no_x_dims) if not no_x_dim] + if xnumels_x_dim: + exprs.append(self.ceildiv(self.maximum(xnumels_x_dim), meta.get("XBLOCK"))) + return f"({self.maximum(exprs)}) * {num_kernels}" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/triton_lazy_compile.py b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/triton_lazy_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..906889937814da007d854bb2cceda0d646282a50 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/runtime/triton_lazy_compile.py @@ -0,0 +1,278 @@ +""" +Lazy Triton kernel compilation for C++ wrapper. + +This module provides functionality to compile and autotune Triton kernels at runtime +when the C++ wrapper is used without autotune_at_compile_time. + +The workflow is: +1. At model initialization: Call start_kernel_compile() for all kernels to start + parallel compilation using multi-process async_compile +2. At kernel execution time: Call run_triton_kernel_with_autotune() which waits + for the specific kernel to be ready, then runs it with autotuning +""" + +from __future__ import annotations + +import dataclasses +import logging +import re +from typing import Any + +from .hints import ( + TRITON_DEFAULT_BLOCK_SIZES, + TRITON_DEFAULT_RSPLIT, + TRITON_DEFAULT_RSPLIT_SIZE, +) +from .triton_heuristics import CachingAutotuner + + +log = logging.getLogger(__name__) + + +@dataclasses.dataclass +class TritonKernelCompileResult: + cubin_path: str + mangled_name: str + num_warps: int + shared_mem: int + xblocks: list[int] + yblocks: list[int] + zblocks: list[int] + r0blocks: list[int] + rsplit: int + rsplit_size: int + config_index: int | None + global_scratch: int | None + profile_scratch: int | None + + +_async_compile: Any = None + + +def _get_async_compile() -> Any: + """Get or create the shared AsyncCompile instance.""" + global _async_compile + if _async_compile is None: + from torch._inductor.async_compile import AsyncCompile + + _async_compile = AsyncCompile() + return _async_compile + + +def _wrap_tma_args(args: list[Any], kernel_fn: CachingAutotuner) -> list[Any]: + """Wrap tensor args with TMA descriptors where the signature requires them.""" + signature = kernel_fn.triton_meta.get("signature", {}) + sig_items = list(signature.items()) + + # Track args index separately from sig_items index since the signature + # may include constexpr entries that are not present in args. + tma_indices = [] + arg_idx = 0 + for name, sig_type in sig_items: + if isinstance(sig_type, str) and sig_type == "constexpr": + continue + if isinstance(sig_type, str) and sig_type == "nvTmaDesc": + raise RuntimeError( + f"nvTmaDesc (experimental TMA API) is not supported in lazy compile " + f"for arg '{name}'. Use the stable tensordesc API instead." + ) + if isinstance(sig_type, str) and sig_type.startswith("tensordesc<"): + tma_indices.append((arg_idx, name, sig_type)) + arg_idx += 1 + + if not tma_indices: + return args + + from triton.tools.tensor_descriptor import TensorDescriptor + + wrapped = list(args) + for arg_idx, name, sig_type in tma_indices: + if arg_idx >= len(wrapped): + raise RuntimeError( + f"TMA arg index {arg_idx} for '{name}' exceeds arg count {len(wrapped)}" + ) + tensor = wrapped[arg_idx] + # Parse block_shape from tensordesc + match = re.match(r"tensordesc<[^[]*\[([^\]]*)\]", sig_type) + if match: + block_shape = [int(x.strip()) for x in match.group(1).split(",")] + wrapped[arg_idx] = TensorDescriptor.from_tensor(tensor, block_shape) + + return wrapped + + +def start_kernel_compile( + pending_kernels: dict[str, Any], kernel_name: str, kernel_source: str +) -> None: + """ + This function is called from C++ at model initialization time for each kernel. + It starts the compilation in a background process but does NOT wait for it. + The actual kernel execution happens later in run_triton_kernel_with_autotune(). + + The pending_kernels dict is per-module, created in C++ and passed through + to avoid global state collisions across compiled modules. + """ + if kernel_name in pending_kernels: + return + + async_compile = _get_async_compile() # noqa: F841 (used by eval below) + + # Evaluate the kernel source to get the Future or CachingAutotuner + # The kernel_source is like: async_compile.triton('name', '''...''', ...) + kernel_obj = eval(kernel_source.strip()) + + pending_kernels[kernel_name] = kernel_obj + + +def run_triton_kernel_with_autotune( + pending_kernels: dict[str, Any], + kernel_name: str, + stream: Any, + args: list[Any], +) -> TritonKernelCompileResult: + """ + Run a Triton kernel with full autotuning using actual tensor arguments. + """ + from torch._inductor.codecache import CodeCacheFuture, CudaKernelParamCache + from torch._inductor.runtime.triton_heuristics import config_to_dict + + if kernel_name not in pending_kernels: + raise RuntimeError(f"Kernel {kernel_name} not found in pending kernels.") + kernel_obj = pending_kernels[kernel_name] + + if isinstance(kernel_obj, CodeCacheFuture): + kernel_fn = kernel_obj.result() + elif isinstance(kernel_obj, CachingAutotuner): + kernel_fn = kernel_obj + else: + raise RuntimeError(f"Unexpected kernel object type: {type(kernel_obj)}") + + if not isinstance(kernel_fn, CachingAutotuner): + raise AssertionError(f"Expected CachingAutotuner, got {type(kernel_fn)}") + + inductor_meta = kernel_fn.inductor_meta + inductor_meta["store_cubin"] = True + + # For TMA kernels, wrap tensor args with TMA descriptors + args = _wrap_tma_args(args, kernel_fn) + + # Run the kernel with the provided arguments + # This will trigger autotuning if there are multiple configs + kernel_fn.run(*args, stream=stream) + if not kernel_fn.launchers: + raise RuntimeError("Kernel run did not produce any launchers") + launcher = kernel_fn.launchers[0] + + cached_params: dict[str, Any] | None = CudaKernelParamCache.get(kernel_name) + if cached_params is None: + raise RuntimeError(f"Failed to get cached params for kernel {kernel_name}") + + from torch._inductor.codecache import get_cpp_wrapper_cubin_path_name + + cubin_path_name = get_cpp_wrapper_cubin_path_name() + for key_name in (cubin_path_name, "mangled_name", "num_warps", "shared_mem"): + if key_name not in cached_params: + raise RuntimeError( + f"{key_name} not found in cached params for {kernel_name}" + ) + cubin_path = cached_params[cubin_path_name] + if not isinstance(cubin_path, str): + raise AssertionError(f"expected cubin_path to be str, got {type(cubin_path)}") + runtime_bin_path = cached_params.get("runtime_bin_path", cubin_path) + if not isinstance(runtime_bin_path, str): + raise AssertionError( + f"expected runtime_bin_path to be str, got {type(runtime_bin_path)}" + ) + mangled_name = cached_params["mangled_name"] + num_warps = cached_params["num_warps"] + shared_mem = cached_params["shared_mem"] + + config = config_to_dict(launcher.config) if launcher.config else {} + + # For combo/foreach kernels, the autotuned config may have empty kwargs + # (e.g., the foreach heuristic only tunes num_warps, not XBLOCK). + # In that case, use the default_config from combo_grid_meta + combo_grid_meta = inductor_meta.get("combo_grid_meta") if inductor_meta else None + default_config = combo_grid_meta.get("default_config") if combo_grid_meta else None + if default_config: + config = {**default_config, **config} + + # Extract per-subkernel block sizes for combo kernels, or single block sizes. + num_kernels = combo_grid_meta.get("num_kernels", 1) if combo_grid_meta else 1 + if num_kernels > 1 and "XBLOCK_0" in config: + xblocks = [ + config.get(f"XBLOCK_{i}", TRITON_DEFAULT_BLOCK_SIZES["XBLOCK"]) + for i in range(num_kernels) + ] + yblocks = [ + config.get(f"YBLOCK_{i}", TRITON_DEFAULT_BLOCK_SIZES["YBLOCK"]) + for i in range(num_kernels) + ] + zblocks = [ + config.get(f"ZBLOCK_{i}", TRITON_DEFAULT_BLOCK_SIZES["ZBLOCK"]) + for i in range(num_kernels) + ] + r0blocks = [ + config.get(f"R0_BLOCK_{i}", TRITON_DEFAULT_BLOCK_SIZES["R0_BLOCK"]) + for i in range(num_kernels) + ] + else: + xblocks = [config.get("XBLOCK", TRITON_DEFAULT_BLOCK_SIZES["XBLOCK"])] + yblocks = [config.get("YBLOCK", TRITON_DEFAULT_BLOCK_SIZES["YBLOCK"])] + zblocks = [config.get("ZBLOCK", TRITON_DEFAULT_BLOCK_SIZES["ZBLOCK"])] + r0blocks = [config.get("R0_BLOCK", TRITON_DEFAULT_BLOCK_SIZES["R0_BLOCK"])] + rsplit = config.get("RSPLIT", TRITON_DEFAULT_RSPLIT) + rsplit_size = config.get("RSPLIT_SIZE", TRITON_DEFAULT_RSPLIT_SIZE) + + config_index = None + grid_type = inductor_meta.get("grid_type") if inductor_meta else None + if grid_type == "PrecomputedGrid" and inductor_meta: + # PrecomputedGrid selects one of precomputed_grids. We use config_index + # to remember which grid is chosen. + precomputed_grids = inductor_meta.get("precomputed_grids", []) + for idx, entry in enumerate(precomputed_grids): + entry_config = entry.get("config", {}) + if all(config.get(k) == v for k, v in entry_config.items()): + config_index = idx + break + + global_scratch: int | None = cached_params.get("global_scratch") + profile_scratch: int | None = cached_params.get("profile_scratch") + + log.debug( + "Successfully autotuned Triton kernel: cubin_path=%s, " + "runtime_bin_path=%s, mangled_name=%s, " + "num_warps=%d, shared_mem=%d, xblocks=%s, yblocks=%s, zblocks=%s, r0blocks=%s, " + "rsplit=%d, rsplit_size=%d, config_index=%s, global_scratch=%s, profile_scratch=%s", + cubin_path, + runtime_bin_path, + mangled_name, + num_warps, + shared_mem, + xblocks, + yblocks, + zblocks, + r0blocks, + rsplit, + rsplit_size, + config_index, + global_scratch, + profile_scratch, + ) + + result = TritonKernelCompileResult( + cubin_path=runtime_bin_path, + mangled_name=mangled_name, + num_warps=num_warps, + shared_mem=shared_mem, + xblocks=xblocks, + yblocks=yblocks, + zblocks=zblocks, + r0blocks=r0blocks, + rsplit=rsplit, + rsplit_size=rsplit_size, + config_index=config_index, + global_scratch=global_scratch, + profile_scratch=profile_scratch, + ) + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/scheduler.py b/.venv/lib/python3.12/site-packages/torch/_inductor/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..7f4a38f974598b5cce0d442ae4a6d24dd2fd831b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/scheduler.py @@ -0,0 +1,10792 @@ +from __future__ import annotations + +import collections +import contextlib +import dataclasses +import enum +import functools +import inspect +import itertools +import logging +import math +import operator +import os +import pprint +import sys +import textwrap +import time +import traceback +import typing +from collections import Counter, defaultdict +from concurrent.futures import as_completed, Future +from typing import ( + Any, + Generic, + Literal, + NamedTuple, + overload, + TYPE_CHECKING, + TypeAlias, + TypeVar, +) +from typing_extensions import ParamSpec + +from torch.utils._ordered_set import OrderedSet + +from .ir import ComputedBuffer, Pointwise + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Iterator, Sequence + from types import ModuleType + + from torch._inductor.codegen.wrapper import EnterCudaStreamContextLine + + from .codegen.simd import MemoryCoalescing + from .codegen.wrapper import PythonWrapperCodegen + from .tiling_utils import CoalesceVarAnalysis + +import sympy + +import torch +import torch._inductor.async_compile +import torch.utils._pytree as pytree +from torch._dynamo.utils import counters, dynamo_timed +from torch._inductor.autotune_process import use_pipelined_autotuning +from torch._inductor.codecache import LambdaFuture, PyCodeCache +from torch._inductor.ir import TritonTemplateCallerBase +from torch._inductor.metrics import get_metric_table, is_metric_table_enabled +from torch._inductor.stream_utils import get_stream_name +from torch.fx.experimental.symbolic_shapes import free_symbols +from torch.utils._sympy.functions import FloorDiv +from torch.utils._sympy.symbol import free_symbol_is_type, symbol_is_type, SymT +from torch.utils._triton import has_triton + +from . import comms, config, config_comms, dependencies, ir, metrics +from .analyze_preserves_zero_mask import can_codegen_without_upcasts +from .codegen.common import BackendFeature, get_scheduling_for_device, Kernel +from .comm_analysis import ( + estimate_nccl_collective_runtime, + estimate_nccl_collective_runtime_nccl_estimator, +) +from .dependencies import Dep, MemoryDep, StarDep, WeakDep +from .exc import GPUTooOldForTriton, TritonMissing +from .fx_utils import count_flops_fx +from .ir import ( + assign_origin_node, + get_device_type, + GraphPartitionSignature, + MultiOutput, + MultiOutputLayout, + NoneLayout, +) +from .loop_body import LoopBody +from .memory import MemoryPlanningInfoForBuffer, MemoryPlanningInfoForNode +from .runtime.hints import DeviceProperties, ReductionHint +from .runtime.runtime_utils import green_text, is_power_of_2, red_text +from .sizevars import SimplifyIndexing +from .utils import ( + _unstable_customized_partition_wrapper, + cache_on_self, + cache_on_self_and_args, + cmp, + decompose_index, + device_need_guard, + get_current_backend, + get_device_tflops, + get_dtype_size, + get_gpu_dram_gbps, + get_op_names, + GraphPartitionMap, + IndentedBuffer, + is_collective, + is_cudagraph_unsafe_op, + is_gpu, + is_multi_outputs_template, + is_output_of_multi_outputs_template, + is_wait, + sympy_product, + sympy_subs, +) +from .virtualized import V + + +log = logging.getLogger(__name__) + + +def _real_dep_names(deps: OrderedSet[Dep]) -> OrderedSet[str]: + """Names of real reads/writes, excluding WeakDep (ordering-only deps that + do not actually read or write the buffer).""" + return OrderedSet(dep.name for dep in deps if not isinstance(dep, WeakDep)) + + +fusion_log = torch._logging.getArtifactLogger(__name__, "fusion") +loop_ordering_log = torch._logging.getArtifactLogger(__name__, "loop_ordering") +compute_dependencies_log = torch._logging.getArtifactLogger( + __name__, "compute_dependencies" +) +cudagraphs_log = torch._logging.getArtifactLogger(__name__, "cudagraphs") + +PartitionType: TypeAlias = list["BaseSchedulerNode"] +_T = TypeVar("_T") +_P = ParamSpec("_P") +_FLATTENED_READ_VAR = sympy.Dummy("flattened_read", integer=True, nonnegative=True) +_REINDEXING_FUSION_LAUNCH_OVERHEAD_NS = 1_000 + + +@dataclasses.dataclass +class FusionResult: + should_fuse: bool | None = None + callable_fn: Callable[[], bool] | None = None + future: LambdaFuture | None = None + + def __post_init__(self): + if not ((self.should_fuse is not None) ^ (self.callable_fn is not None)): + raise AssertionError( + "Fusion result should contain either fusion decision or callable_fn, not both" + ) + + @classmethod + def fuse(cls, should_fuse: bool): + return FusionResult(should_fuse=should_fuse) + + @classmethod + def from_callable( + cls, callable_fn: Callable[[], bool], future: LambdaFuture | None = None + ): + return FusionResult(callable_fn=callable_fn, future=future) + + +@dataclasses.dataclass +class PendingFusion: + callable_fn: Callable[[], bool] + node1: BaseSchedulerNode + node2: BaseSchedulerNode + future: LambdaFuture | None = None + + def get_fusion_nodes(self) -> tuple[BaseSchedulerNode, BaseSchedulerNode]: + return (self.node1, self.node2) + + +class _LocalEntry(NamedTuple): + """One row of the post-rewrite slice the gate builds. + + `cur` is the step the node currently wants to run at, `baseline` + is its original index (used to break ties when sorting), and + `node` is the slice member itself. + """ + + cur: int + baseline: int + node: BaseSchedulerNode + + +@dataclasses.dataclass(slots=True) +class ComboKernelMemoryContext: + """Shared state used by the memory-aware combo gate. + + Candidate windows are evaluated independently against the original + schedule. Earlier accepted combos only contribute through `running_peak`, + which caps the cumulative peak drift from the original graph. + """ + + graph_outputs: OrderedSet[str] + node_to_idx: dict[BaseSchedulerNode, int] + baseline_peak: int = 0 + # Running peak after earlier accepts. Bumped on each accept; the + # gate's threshold check still compares against `baseline_peak` + # (the original) so total drift is capped. + running_peak: int = 0 + # Live bytes before each step in the original schedule. Combo windows + # are evaluated independently, so a window's entry memory is the + # precomputed baseline live-in at `region_start`. + baseline_live_before: list[int] = dataclasses.field(default_factory=list) + + +def _is_gpu_triton_backend( + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, +) -> bool: + if not node1.is_gpu() or not node2.is_gpu(): + return False + device_type = node1.get_device().type # type: ignore[union-attr] + return ( + device_type in ("cuda", "xpu") and get_current_backend(device_type) == "triton" + ) + + +class MixOrderReduction: + """ + This class contains utility functions to decide if we should fuse reductions + reducing across different dimensions of the same input tensor. + """ + + @staticmethod + def is_split_reduction(node: BaseSchedulerNode) -> bool: + return node.is_reduction() and all( + subnode.node._split_size is not None + for subnode in node.get_nodes() + if isinstance(subnode, SchedulerNode) + and subnode.is_reduction() + and isinstance(subnode.node, ComputedBuffer) + ) + + @classmethod + def get_numel_rnumel(cls, node: BaseSchedulerNode) -> tuple[sympy.Expr, sympy.Expr]: + if cls.is_split_reduction(node): + xnumel = None + rnumel = None + for subnode in node.get_nodes(): + if not ( + isinstance(subnode, SchedulerNode) + and subnode.is_reduction() + and isinstance(subnode.node, ComputedBuffer) + ): + continue + + if subnode.node._original_ranges is None: + raise AssertionError( + "expected subnode.node._original_ranges to be set" + ) + curxnumel = V.graph.sizevars.simplify( + sympy_product(subnode.node._original_ranges) + ) + if subnode.node._original_reduction_ranges is None: + raise AssertionError( + "expected subnode.node._original_reduction_ranges to be set" + ) + currnumel = V.graph.sizevars.simplify( + sympy_product(subnode.node._original_reduction_ranges) + ) + + if xnumel is None: + xnumel = curxnumel + rnumel = currnumel + else: + if not V.graph.sizevars.statically_known_equals(xnumel, curxnumel): + raise AssertionError(f"{xnumel} v.s. {curxnumel}") + if not V.graph.sizevars.statically_known_equals(rnumel, currnumel): + raise AssertionError(f"{rnumel} v.s. {currnumel}") + + if xnumel is None: + raise AssertionError("expected xnumel to be set") + return (xnumel, rnumel) + else: + return node.group[1] # type: ignore[return-value] + + @classmethod + def has_mix_reduction_orders( + cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + g1 = cls.get_numel_rnumel(node1) + g2 = cls.get_numel_rnumel(node2) + + if len(g1) != 2 or len(g2) != 2 or g1 == g2: + return False + + return tuple(g1) == tuple(reversed(g2)) + + @classmethod + def _is_full_access(cls, buf: str, node: BaseSchedulerNode) -> bool: + """ + The access to 'buf' is not a broadcast access. + """ + found_dep = None + for dep in node.read_writes.reads: + if isinstance(dep, MemoryDep) and dep.name == buf: + found_dep = dep + break + + if not found_dep: + return False + + index = found_dep.index + var_ranges = node.read_writes.var_ranges + + if not var_ranges: + if not isinstance(node, FusedSchedulerNode): + raise AssertionError(f"{type(node)}") + var_ranges = node.snodes[0].read_writes.var_ranges + + if not var_ranges: + raise AssertionError("expected var_ranges to be non-empty") + if not (OrderedSet(var_ranges) - OrderedSet(index.free_symbols)): + return True + + # cases that happen after merging loops: + # MemoryDep('arg0_1', c0, {c0: 25165824})]) + # var_ranges={d0: 32768, d1: 768} + if V.graph.sizevars.statically_known_equals( + sympy_product(found_dep.size), sympy_product(var_ranges.values()) + ): + return True + return False + + @classmethod + def get_common_read( + cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> list[str]: + out = [] + common_reads = node1.used_buffer_names() & node2.used_buffer_names() + for buf in common_reads: + if cls._is_full_access(buf, node1) and cls._is_full_access(buf, node2): + out.append(buf) + + return out + + @classmethod + def has_common_read( + cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + return len(cls.get_common_read(node1, node2)) > 0 + + @classmethod + def get_numel(cls, node: BaseSchedulerNode) -> int: + g1 = cls.get_numel_rnumel(node) + return V.graph.sizevars.optimization_hint(g1[0] * g1[1], fallback=0) + + @classmethod + def get_fusion_score( + cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> int: + # node2 is ignored for now + return cls.get_numel(node1) + + # TODO add a cache + @classmethod + def can_fuse(cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode) -> bool: + """ + Check whether we can fuse two reductions with mix loop orders. + """ + if not config.triton.mix_order_reduction: + return False + + # TODO: Mix order reduction is not supported with cpp_wrapper yet + if V.graph.cpp_wrapper: + return False + + if not _is_gpu_triton_backend(node1, node2): + return False + if not node1.is_reduction() or not node2.is_reduction(): + return False + if node1.has_strict_sum() or node2.has_strict_sum(): + return False + + if (node1.ancestors & node2.get_operation_names()) or ( + node2.ancestors & node1.get_operation_names() + ): + # Mix-order reductions are sibling reductions, not producer-consumer. + return False + + # check for mix reduction orders + if not cls.has_mix_reduction_orders(node1, node2): + return False + + # check common buffer accesses + common_reads = MixOrderReduction.get_common_read(node1, node2) + if len(common_reads) == 0: + return False + + if cls.is_contiguous_node(node1): + contiguous_node, other_node = node1, node2 + elif cls.is_contiguous_node(node2): + contiguous_node, other_node = node2, node1 + else: + return False + + g1 = cls.get_numel_rnumel(contiguous_node) + nrow, ncol = g1 + + # in non strict mode, we will skip the non-critical checks + if not config.triton.mix_order_reduction_non_strict_mode: + # the fused version has worse perf than non-fused version for + # small workload. When a workload is small enough, data can be + # fully cached by L2 + size_thres = 5 * 2**20 + + # Call evaluate_expr rather than statically_known_geq since nrow can + # have dynamic shape in real models. + # Don't use hint directly since hint can be non-representative. + if not V.graph.sizevars.evaluate_expr( + sympy.Ge(nrow * ncol, size_thres), + size_oblivious=True, + fallback_value=False, + ): + return False + + # We require more more row than columns since + # 1, we prefer doing persistent reduction for each row + # 2, we will split the reduction across the rows + if not V.graph.sizevars.evaluate_expr( + sympy.Ge(nrow, ncol * 2), + size_oblivious=True, + fallback_value=False, + ): + return False + + # When nrow is small, ncol should also be small (due to the check + # above). Thus the entire tensor should be well cached in L2. + # Mix order reduction is less beneficial. + if not V.graph.sizevars.evaluate_expr( + sympy.Ge(nrow, 4096), + size_oblivious=True, + fallback_value=False, + ): + return False + + # Make sure a persistent reduction will be generated + if any( + subnode.node.data.reduction_hint # type: ignore[union-attr] + not in ( + ReductionHint.INNER, + ReductionHint.DEFAULT, + ) + for subnode in contiguous_node.get_nodes() + if subnode.is_reduction() + ): + return False + + # rnumel so large that we will not generated persistent reduction + # We don't see real use cases with dynamic ncol. But if we do, + # we should call evaluete_expr here which adds guards. + if not V.graph.sizevars.statically_known_leq(ncol, 1024 * 16): + return False + + if MixOrderReduction.is_split_reduction(contiguous_node): + return False + + # Other reduction types like max/min is not supported yet. + # There are no real use case as well. + out = all( + subnode.node.get_reduction_type() # type: ignore[union-attr] + in { + "sum", + "prod", + } + for subnode in other_node.get_nodes() + if subnode.is_reduction() + ) + return out + + @classmethod + def are_mix_order_reductions( + cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + return cls.can_fuse(node1, node2) + + @classmethod + def is_contiguous_node(cls, node: BaseSchedulerNode) -> bool: + if not all( + cls.is_contiguous_load(dep.name, node) for dep in node.read_writes.reads + ): + return False + return True + + @classmethod + def is_contiguous_load(cls, buf: str, parent_node: BaseSchedulerNode) -> bool: + from torch._inductor.loop_body import MemoryUsageType + + for node in parent_node.get_nodes(): + if not isinstance(node, SchedulerNode): + raise AssertionError("expected node to be a SchedulerNode") + loop_body = node._body + entries = loop_body.memory_usage[MemoryUsageType.LOAD] + index_names = [e.index_name for e in entries if e.buffer_name == buf] + + if len(index_names) == 0: + continue + + # there can be multiple index_names some times + for index_name in index_names: + index_expr = loop_body.indexing_exprs[index_name] + var_ranges = loop_body.var_ranges + + # assumes the final symbol is for reduction + var_symbols = list(var_ranges.keys()) + stride_vars = V.graph.sizevars.stride_vars( + index_expr, + var_symbols, + var_symbols, + ) + + # stride==0 means a broadcast + if not (stride_vars[-1] == 0 or stride_vars[-1] == 1): + return False + return True + + +class NestedReduction: + """ + Detects when an outer reduction and a dependent grouped reduction can be + fused into one kernel. The outer reduction reduces over a large dimension + (e.g. D) producing per-row statistics; the grouped reduction performs a + small local reduction over the same logical elements. The grouped reduction + may re-read the outer reduction's large input, consume its full-resolution + output, or both. + + This is deliberately limited to same-total-numel pairs: + both reductions must traverse the same number of logical elements. + General output-size-reducing nested reductions, including split reductions, + need different grid ownership and are rejected here. + + Example: + - layernorm + block amax: amax over groups of G after layer_norm + """ + + MAX_INNER_R_GROUP_SIZE = 512 + MAX_NON_INNER_GROUP_SIZE = 128 + + @staticmethod + def _is_dependent_reduction_pair( + outer_node: BaseSchedulerNode, grouped_node: BaseSchedulerNode + ) -> bool: + """Check that the grouped reduction is a consumer of the outer reduction.""" + return ( + outer_node.is_reduction() + and grouped_node.is_reduction() + and bool(outer_node.get_operation_names() & grouped_node.ancestors) + ) + + @staticmethod + def _is_enabled_for( + outer_node: BaseSchedulerNode, grouped_node: BaseSchedulerNode + ) -> bool: + return ( + config.triton.nested_reduction + and not V.graph.cpp_wrapper + and _is_gpu_triton_backend(outer_node, grouped_node) + and not outer_node.has_strict_sum() + and not grouped_node.has_strict_sum() + ) + + @classmethod + def is_candidate(cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode) -> bool: + """Cheap filter for dependent reductions with different reduction sizes.""" + if not cls._is_enabled_for( + node1, node2 + ) or not cls._is_dependent_reduction_pair(node1, node2): + return False + _, (_, rnumel1) = node1.group + _, (_, rnumel2) = node2.group + return not V.graph.sizevars.statically_known_equals(rnumel1, rnumel2) + + class PointwiseDomain(enum.Enum): + """ + Where a pointwise node runs in the nested pipeline. + + The local reduction stage has three meaningful domains: its reduced + output, its input before reducing the local lane, and the outer + reduction's parent tile after broadcast-back. + """ + + # Local reduction output, e.g. [B, D // G]. + REDUCED = enum.auto() + # Input domain before reducing the local group, e.g. [B, D // G, G]. + LOCAL_REDUCTION_INPUT = enum.auto() + # Outer reduction tile after broadcast-back, e.g. [B, D]. + PARENT_FULL = enum.auto() + + class GroupedAxis(enum.Enum): + R = enum.auto() + X = enum.auto() + + @dataclasses.dataclass(frozen=True) + class PointwiseDomainContext: + grouped_reduction: SchedulerNode + grouped_numel: sympy.Expr + grouped_rnumel: sympy.Expr + local_reduction_domain: tuple[sympy.Expr, ...] + parent_full_domain: tuple[sympy.Expr, ...] + + @classmethod + def _get_grouped_reduction_and_size( + cls, grouped_node: BaseSchedulerNode, grouped_rnumel: sympy.Expr + ) -> tuple[SchedulerNode, sympy.Integer] | None: + """Validate the candidate as a single simple grouped reduction.""" + if not grouped_node.is_reduction(): + return None + reductions = [sn for sn in grouped_node.get_nodes() if sn.is_reduction()] + if len(reductions) != 1: + return None + reduction = reductions[0] + if not isinstance(reduction, SchedulerNode) or not isinstance( + reduction.node, ComputedBuffer + ): + return None + iter_ranges, reduce_ranges = reduction.get_ranges() + # The original tensor may be higher-rank, but scheduler ranges are + # already collapsed into loop trees. Nested codegen maps the grouped + # reduction as either [outer_x, r_groups, G] or [x_groups, outer_r, G]. + # A singleton non-reduced tree may be squeezed out; additional trees + # need explicit axis provenance and are rejected here. + if len(iter_ranges) not in (1, 2) or len(reduce_ranges) != 1: + return None + # Single-value reductions are lowered by reshape + tl.(..., axis). + # Tuple/stateful reductions such as argmax and Welford need the normal + # reduction lowering and are rejected before nested codegen. + if reduction.node.get_reduction_type() not in { + "any", + "max", + "min", + "prod", + "sum", + "xor_sum", + }: + return None + + group_size = V.graph.sizevars.simplify(grouped_rnumel) + if not isinstance(group_size, (int, sympy.Integer)) or int(group_size) < 1: + return None + return reduction, sympy.Integer(group_size) + + @classmethod + def _pointwise_nodes_match_nested_domains( + cls, + outer_node: BaseSchedulerNode, + grouped_node: BaseSchedulerNode, + domain_context: PointwiseDomainContext, + ) -> bool: + """Classify pointwise nodes by nested stage and validate their ranges. + + Each pointwise node must run either on the grouped reduction output, + on the grouped reduction's full local-group domain, or on the outer + reduction's full parent domain, based on its producer/consumer + relationship to the grouped reduction. + """ + pointwise_domains = cls._classify_nested_pointwise_nodes( + outer_node, + grouped_node, + domain_context, + ) + if pointwise_domains is None: + return False + + return cls._pointwise_domains_are_compatible(domain_context, pointwise_domains) + + @classmethod + def _classify_nested_pointwise_nodes( + cls, + outer_node: BaseSchedulerNode, + grouped_node: BaseSchedulerNode, + domain_context: PointwiseDomainContext, + ) -> list[tuple[SchedulerNode, PointwiseDomain]] | None: + outer_pointwise_domains: list[ + tuple[SchedulerNode, NestedReduction.PointwiseDomain] + ] = [] + # Use ancestor names to find pointwise subnodes inside the outer fused + # node that consume an outer reduction result. + outer_reduction_names: OrderedSet[str] = OrderedSet() + for sn in outer_node.get_nodes(): + if sn.is_reduction(): + outer_reduction_names |= sn.get_operation_names() + + # Full-resolution consumers already fused into the outer reduction feed + # the local reduction, so they run in that input domain. + for sn in outer_node.get_nodes(): + if sn.is_reduction(): + continue + if outer_reduction_names & sn.ancestors: + if not isinstance(sn, SchedulerNode): + return None + outer_pointwise_domains.append( + (sn, cls.PointwiseDomain.LOCAL_REDUCTION_INPUT) + ) + + grouped_pointwise_domains = cls._classify_grouped_pointwise_nodes( + domain_context, + grouped_node.get_nodes(), + ) + if grouped_pointwise_domains is None: + return None + return [*outer_pointwise_domains, *grouped_pointwise_domains] + + @classmethod + def _classify_grouped_pointwise_nodes( + cls, + domain_context: PointwiseDomainContext, + nodes: Sequence[BaseSchedulerNode], + ) -> list[tuple[SchedulerNode, PointwiseDomain]] | None: + """Classify pointwise nodes relative to the grouped reduction. + + A node must be on exactly one side of the grouped reduction: either a + producer feeding its local-group body, or a consumer of its reduced + output. Its numel then determines whether it runs at reduced, + grouped-full, or parent-full resolution. + """ + grouped_reduction = domain_context.grouped_reduction + reduction_names = grouped_reduction.get_operation_names() + full_numel = V.graph.sizevars.simplify( + domain_context.grouped_numel * domain_context.grouped_rnumel + ) + pointwise_domains: list[ + tuple[SchedulerNode, NestedReduction.PointwiseDomain] + ] = [] + for sn in nodes: + if sn.is_reduction(): + continue + if not isinstance(sn, SchedulerNode): + return None + + sn_names = sn.get_operation_names() + is_producer = bool(sn_names & grouped_reduction.ancestors) + is_consumer = bool(reduction_names & sn.ancestors) + if is_producer and is_consumer: + # Supportable by splitting/modeling a multi-stage pointwise, + # but not as one nested pipeline stage today. + return None + if not is_producer and not is_consumer: + # Supportable as a sidecar, but nested codegen does not yet + # model an insertion point for unrelated pointwise nodes. + return None + + full_domain = ( + cls.PointwiseDomain.LOCAL_REDUCTION_INPUT + if is_producer + else cls.PointwiseDomain.PARENT_FULL + ) + _, (sn_numel, _) = sn.group + if V.graph.sizevars.statically_known_equals( + sn_numel, domain_context.grouped_numel + ): + domain = cls.PointwiseDomain.REDUCED + elif V.graph.sizevars.statically_known_equals(sn_numel, full_numel): + domain = full_domain + else: + return None + pointwise_domains.append((sn, domain)) + return pointwise_domains + + @classmethod + def _pointwise_domains_are_compatible( + cls, + domain_context: PointwiseDomainContext, + pointwise_domains: Sequence[tuple[SchedulerNode, PointwiseDomain]], + ) -> bool: + return all( + cls._pointwise_domain_is_compatible(sn, domain, domain_context) + for sn, domain in pointwise_domains + ) + + @classmethod + def _pointwise_domain_is_compatible( + cls, + sn: SchedulerNode, + domain: PointwiseDomain, + domain_context: PointwiseDomainContext, + ) -> bool: + from .codegen.simd import SIMDKernel + + iter_ranges, _ = domain_context.grouped_reduction.get_ranges() + _, (sn_numel, _) = sn.group + if domain is cls.PointwiseDomain.REDUCED: + expected_numel = domain_context.grouped_numel + expected_groups: Sequence[sympy.Expr] = tuple(iter_ranges) + elif domain is cls.PointwiseDomain.LOCAL_REDUCTION_INPUT: + expected_numel = V.graph.sizevars.simplify( + domain_context.grouped_numel * domain_context.grouped_rnumel + ) + expected_groups = domain_context.local_reduction_domain + else: + if domain is not cls.PointwiseDomain.PARENT_FULL: + raise AssertionError(f"expected PARENT_FULL domain, got {domain}") + expected_numel = V.graph.sizevars.simplify( + domain_context.grouped_numel * domain_context.grouped_rnumel + ) + expected_groups = domain_context.parent_full_domain + return V.graph.sizevars.statically_known_equals( + sn_numel, expected_numel + ) and SIMDKernel.is_compatible(expected_groups, sn.get_ranges()) + + @classmethod + def _min_block_unprofitable_for_kernel( + cls, + outer_node: BaseSchedulerNode, + outer_numel: sympy.Expr, + outer_rnumel: sympy.Expr, + *, + grouped_axis: GroupedAxis, + group_size: int, + ) -> bool: + from .codegen.simd import SIMDScheduling + + if not isinstance(outer_node, (SchedulerNode, FusedSchedulerNode)): + return True + coalesce_analysis = ( + outer_node.get_coalesce_analysis() + if config.triton.coalesce_tiling_analysis + else None + ) + node_schedule = list(outer_node.get_nodes()) + tiling = SIMDScheduling.select_tiling( + node_schedule, + outer_numel, + outer_rnumel, + coalesce_analysis, + ) + # TODO: fold richer profitability/coalescing policy into this guard. + # For now this is only a codegen capability check for the min block. + # The grouped reduction forces a minimum block on the split axis. Today + # that floor is only modeled for ordinary x/r0 kernels, where x is the + # outer pointwise axis and r0_ is the inner reduction axis. + if OrderedSet(tiling) != OrderedSet(("x", "r0_")): + return True + if not ( + V.graph.sizevars.statically_known_equals(tiling["x"], outer_numel) + and V.graph.sizevars.statically_known_equals(tiling["r0_"], outer_rnumel) + ): + return True + return group_size > cls._max_min_block_group_size(node_schedule, grouped_axis) + + @classmethod + def _max_min_block_group_size( + cls, + node_schedule: Sequence[BaseSchedulerNode], + grouped_axis: GroupedAxis, + ) -> int: + from .codegen.simd_kernel_features import SIMDKernelFeatures + + reduction_hints = [ + SIMDKernelFeatures.reduction_hint(sn) + for sn in node_schedule + if isinstance(sn, SchedulerNode) + and sn.is_reduction() + and isinstance(sn.node, ComputedBuffer) + ] + if ( + grouped_axis is cls.GroupedAxis.R + and reduction_hints + and all(hint is ReductionHint.INNER for hint in reduction_hints) + ): + return cls.MAX_INNER_R_GROUP_SIZE + return cls.MAX_NON_INNER_GROUP_SIZE + + @classmethod + def can_fuse(cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode) -> bool: + """Check whether a dependent cross-axis reduction pair can be fused.""" + # TODO: enable nested reduction with cpp wrapper after validating the + # additional autotuning meta (min_xblock / min_rblock). + if not cls._is_enabled_for(node1, node2): + return False + + if not cls._is_dependent_reduction_pair(node1, node2): + raise AssertionError( + "expected node1 and node2 to be a dependent reduction pair" + ) + + outer_node = node1 + grouped_node = node2 + outer_group: tuple[sympy.Expr, sympy.Expr] + grouped_group: tuple[sympy.Expr, sympy.Expr] + _, outer_group = outer_node.group # pyrefly: ignore [bad-assignment] + _, grouped_group = grouped_node.group # pyrefly: ignore [bad-assignment] + outer_numel, outer_rnumel = outer_group + grouped_numel, grouped_rnumel = grouped_group + if V.graph.sizevars.statically_known_equals(outer_rnumel, grouped_rnumel): + return False + + # The grouped candidate must be one small block-local reduction. + # We specialize the grouped reduction on that block size, so it must + # simplify to an exact static int. Multiple reductions in the grouped + # candidate (e.g. amax AND sum from the same input) are not supported. + grouped_reduction_info = cls._get_grouped_reduction_and_size( + grouped_node, grouped_rnumel + ) + if grouped_reduction_info is None: + return False + + # Total-element equality also implies divisibility of the grouped + # parent extent by group_size (grouped_total factors through + # FloorDiv(extent, group_size) * group_size). No separate Mod check + # is needed. The sizevars divisible set records Mod(s, s//G) from + # the view op, not Mod(s, G), so statically_known_equals on + # Mod(extent, group_size) would fail with dynamic shapes. + # TODO: teach sizevars to infer Mod(s, G)==0 from Mod(s, s//G)==0 + outer_total = V.graph.sizevars.simplify(outer_numel * outer_rnumel) + grouped_total = V.graph.sizevars.simplify(grouped_numel * grouped_rnumel) + if not V.graph.sizevars.statically_known_equals(outer_total, grouped_total): + return False + + grouped_reduction, group_size = grouped_reduction_info + + grouped_axis = cls.get_grouped_axis( + grouped_reduction, + outer_numel, + outer_rnumel, + group_size, + outer_node=outer_node, + ) + if grouped_axis is None: + return False + parent_grouped_axis = ( + outer_rnumel if grouped_axis is cls.GroupedAxis.R else outer_numel + ) + iter_ranges, _ = grouped_reduction.get_ranges() + if len(iter_ranges) == 2: + grouped_axis_groups = ( + iter_ranges[1] if grouped_axis is cls.GroupedAxis.R else iter_ranges[0] + ) + if not V.graph.sizevars.statically_known_equals( + FloorDiv(parent_grouped_axis, group_size), grouped_axis_groups + ): + return False + elif not V.graph.sizevars.statically_known_equals( + sympy.Mod(parent_grouped_axis, group_size), 0 + ): + return False + group_size_int = int(group_size) + if not (1 <= group_size_int and is_power_of_2(group_size_int)): + return False + if cls._min_block_unprofitable_for_kernel( + outer_node, + outer_numel, + outer_rnumel, + grouped_axis=grouped_axis, + group_size=group_size_int, + ): + return False + iter_ranges, reduce_ranges = grouped_reduction.get_ranges() + domain_context = cls.PointwiseDomainContext( + grouped_reduction=grouped_reduction, + grouped_numel=grouped_numel, + grouped_rnumel=grouped_rnumel, + local_reduction_domain=(*iter_ranges, *reduce_ranges), + parent_full_domain=(outer_numel, outer_rnumel), + ) + if not cls._pointwise_nodes_match_nested_domains( + outer_node, + grouped_node, + domain_context, + ): + return False + + return True + + @classmethod + def get_grouped_axis( + cls, + grouped_reduction: SchedulerNode, + outer_numel: sympy.Expr, + outer_rnumel: sympy.Expr, + group_size: sympy.Expr, + *, + outer_node: BaseSchedulerNode | None = None, + ) -> GroupedAxis | None: + """Return which parent axis is split by the grouped local reduction.""" + sizevars = V.graph.sizevars + iter_ranges, reduce_ranges = grouped_reduction.get_ranges() + if len(iter_ranges) != 2 or len(reduce_ranges) != 1: + if len(iter_ranges) == 1 and len(reduce_ranges) == 1: + if not sizevars.statically_known_equals(reduce_ranges[0], group_size): + return None + # [R / G] reduce G: parent X is singleton, so the local group + # splits the parent R axis. + if sizevars.statically_known_equals( + FloorDiv(outer_rnumel, group_size), iter_ranges[0] + ) and sizevars.statically_known_equals(outer_numel, 1): + return cls.GroupedAxis.R + # [R] reduce G: parent X is exactly one local group and is + # reduced away, leaving the parent R axis as the only iterator. + if sizevars.statically_known_equals( + FloorDiv(outer_numel, group_size), 1 + ) and sizevars.statically_known_equals(iter_ranges[0], outer_rnumel): + return cls.GroupedAxis.X + return None + if not sizevars.statically_known_equals(reduce_ranges[0], group_size): + return None + # 2D group-in-R form: [X, R / G] reduce G. Dynamic view guards often + # preserve the quotient dimension even when Mod(R, G) is not directly + # provable. + if sizevars.statically_known_equals( + iter_ranges[0], outer_numel + ) and sizevars.statically_known_equals( + FloorDiv(outer_rnumel, group_size), iter_ranges[1] + ): + return cls.GroupedAxis.R + # 2D group-in-X form: [X / G, R] reduce G. + if sizevars.statically_known_equals( + iter_ranges[1], outer_rnumel + ) and sizevars.statically_known_equals( + FloorDiv(outer_numel, group_size), iter_ranges[0] + ): + return cls.GroupedAxis.X + if outer_node is not None: + return cls._get_grouped_axis_from_loop_body(outer_node, grouped_reduction) + return None + + @classmethod + def _get_grouped_axis_from_loop_body( + cls, outer_node: BaseSchedulerNode, grouped_reduction: SchedulerNode + ) -> GroupedAxis | None: + """Use LoopBody iter/reduce vars to disambiguate equal-size axes.""" + from torch._inductor.loop_body import MemoryUsageType + + outer_reductions = [sn for sn in outer_node.get_nodes() if sn.is_reduction()] + if len(outer_reductions) != 1: + return None + outer_reduction = typing.cast(SchedulerNode, outer_reductions[0]) + outer_body = getattr(outer_reduction, "_body", None) + grouped_body = getattr(grouped_reduction, "_body", None) + if outer_body is None or grouped_body is None: + return None + + outer_iter_ranges, outer_reduce_ranges = outer_reduction.get_ranges() + grouped_iter_ranges, grouped_reduce_ranges = grouped_reduction.get_ranges() + if len(outer_reduce_ranges) != 1 or len(grouped_reduce_ranges) != 1: + return None + + def load_exprs_by_name(body: LoopBody) -> dict[str, list[sympy.Expr]]: + result: dict[str, list[sympy.Expr]] = defaultdict(list) + for entry in body.memory_usage.get(MemoryUsageType.LOAD, ()): + if entry.buffer_name is not None: + result[entry.buffer_name].append( + body.indexing_exprs[entry.index_name] + ) + return result + + if len(outer_body.reduce_vars) != 1 or len(grouped_body.reduce_vars) != 1: + return None + if len(outer_body.iter_vars) != len(outer_iter_ranges) or len( + grouped_body.iter_vars + ) != len(grouped_iter_ranges): + return None + + outer_reads_by_name = load_exprs_by_name(outer_body) + result: NestedReduction.GroupedAxis | None = None + grouped_reduce_var = grouped_body.reduce_vars[-1] + for name, grouped_read_exprs in load_exprs_by_name(grouped_body).items(): + outer_read_exprs = outer_reads_by_name.get(name) + if not outer_read_exprs: + continue + for grouped_read_expr in grouped_read_exprs: + grouped_coeff = grouped_read_expr.coeff(grouped_reduce_var) + if grouped_coeff == 0: + continue + for outer_read_expr in outer_read_exprs: + outer_reduce_var = outer_body.reduce_vars[-1] + outer_reduce_coeff = outer_read_expr.coeff(outer_reduce_var) + matches_reduction = grouped_coeff == outer_reduce_coeff + matches_iter = any( + grouped_coeff == outer_read_expr.coeff(var) + for var in outer_body.iter_vars + ) + if matches_reduction == matches_iter: + continue + candidate = ( + cls.GroupedAxis.R if matches_reduction else cls.GroupedAxis.X + ) + + if result is not None and result != candidate: + return None + result = candidate + return result + + +@dataclasses.dataclass +class SchedulerBuffer: + scheduler: Scheduler + node: ir.Buffer + defining_op: BaseSchedulerNode | None + users: list[NodeUser] = dataclasses.field(default_factory=list) + mpi_buffer: MemoryPlanningInfoForBuffer = dataclasses.field( + default_factory=MemoryPlanningInfoForBuffer + ) + + def defining_op_name(self) -> str: + op = self.defining_op + if op is None: + raise AssertionError("expected op to be set") + return op.get_name() + + def is_ordering_only(self) -> bool: + return self.node.ordering_only + + def __hash__(self) -> int: + return hash(self.node.name) + + def debug_str(self) -> str: + result = IndentedBuffer() + name = self.get_name() + result.writeline(f"{name}: {type(self.node).__name__}") + result.writeline(f"{name}.layout = {self.node.layout}") + if self.get_aliases(): + result.writeline(f"{name}.aliases = {pformat(self.get_aliases())}") + if self.get_mutations(): + result.writeline(f"{name}.mutations = {pformat(self.get_mutations())}") + + if len(self.users) <= 1: + result.writeline(f"{name}.users = {self.users}") + else: + result.writeline(f"{name}.users = [") + with result.indent(1): + for user in self.users: + result.writeline(f"{user},") + result.writeline("]") + return result.getrawvalue() + + def get_name(self) -> str: + return self.node.get_name() + + def allocate(self) -> None: + if self.node is None: + raise AssertionError("expected self.node to be set") + if not self.node.should_allocate(): + return + + if ( + self.node.get_inputs_that_alias_output() + or self.node.get_mutation_names() + or isinstance(self.node.get_output_spec(), ir.CommBufferLayout) + ): + V.graph.wrapper_code.codegen_allocation(self.node) + return + + # hacky check for if V.kernel is a real kernel or NullHandler + if ( + hasattr(V.kernel, "args") + and self.get_name() in V.kernel.inplace_update_buffers + ): + input_buffer: ir.DonatedBuffer | ir.Buffer + input_buffer_name = V.kernel.inplace_update_buffers[self.get_name()] + if input_buffer_name in self.scheduler.name_to_donated_buffer: + input_buffer = self.scheduler.name_to_donated_buffer[ + input_buffer_name + ].node + else: + input_buffer = self.scheduler.name_to_buf[input_buffer_name].node + V.graph.wrapper_code.codegen_inplace_reuse( + input_buffer, + self.node, + ) + else: + V.graph.wrapper_code.codegen_allocation(self.node) + + def can_free(self) -> bool: + # There's no real allocated buffer, no need to free it + if self.node is None: + raise AssertionError("expected self.node to be set") + if isinstance(self.node.layout, ir.NoneLayout) or is_multi_outputs_template( + self.node + ): + return False + for use in self.users: + if isinstance(use.node, OutputNode): + return False + return True + + def set_users(self, users: list[NodeUser]) -> None: + # deduplicate + result: dict[int, NodeUser] = {} + for use in users: + if id(use.node) in result: + result[id(use.node)] = use.merge(result[id(use.node)]) + else: + result[id(use.node)] = use + self.users = list(result.values()) + + def get_aliases(self) -> Sequence[str]: + if self.node is None: + raise AssertionError("expected self.node to be set") + return self.node.get_inputs_that_alias_output() + + def get_mutations(self) -> Sequence[str]: + if self.node is None: + raise AssertionError("expected self.node to be set") + return self.node.get_mutation_names() + + def get_device(self) -> torch.device | None: + return self.node.get_output_spec().get_device() + + +@dataclasses.dataclass +class SchedulerDonatedBuffer(SchedulerBuffer): + defining_op: BaseSchedulerNode | None = None + + +class BaseSchedulerNode: + ancestors: OrderedSet[str] + group: tuple[torch.device, tuple[tuple[sympy.Expr, ...], ...]] + last_usage: OrderedSet[str] + # .min_order and .max_order are only relevant for "grouped" nodes such as FusedSchedulerNode. + # e.g. if the FusedSchedulerNode includes nodes (op_1, op_2, op_3), and op_X is X-th node + # in `self.scheduler.nodes`, then for this FusedSchedulerNode, .min_order is 1 and .max_order is 3. + # For non-"grouped" nodes (i.e. regular SchedulerNode), + # .min_order = .max_order = X if this node is X-th node in `self.scheduler.nodes`. + min_input_distance: int + max_input_distance: int + min_order: int + max_order: int + mpi_node: MemoryPlanningInfoForNode + mutation_renames: dict[str, str] + node: ir.Operation | None = None + outputs: list[SchedulerBuffer] + outputs_by_name: dict[str, SchedulerBuffer] + override_estimated_runtime: float | None = None + read_writes: dependencies.ReadWrites + unmet_dependencies: OrderedSet[Dep] + written: bool = False + + def __init__(self, scheduler: Scheduler) -> None: + self.scheduler: Scheduler = scheduler + self.debug_device_str: Callable[[BaseSchedulerNode], list[str]] = ( + lambda *args, **kwargs: [] + ) + + def _init_from_node(self, node: ir.Operation) -> None: + self.node = node + self.ancestors = OrderedSet() + self.min_input_distance = 0 + self.max_input_distance = 0 + self.last_usage = OrderedSet[ + str + ]() # buffers that won't be used after this kernel + self.written = False + self.outputs = [ + SchedulerBuffer( + scheduler=self.scheduler, + node=output, + defining_op=self, + ) + for output in node.get_outputs() + ] + self.outputs_by_name = {buf.get_name(): buf for buf in self.outputs} + + # mutation_renames for the current node. Due to potential + # more mutations happening later, this can be different + # to Scheduler.mutation_renames. Also this dict should be small + # since only mutation information relevant to the deps for this + # node is stored here. + self.mutation_renames = {} + + def __repr__(self) -> str: + return f"{type(self).__name__}(name={self.get_name()!r})" + + def debug_str(self) -> str: + """Longer form printout for trace logs""" + name = self.get_name() + buf = IndentedBuffer() + buf.splice( + f"""\ +{name}: {type(self).__name__}({type(getattr(self, "node", None)).__name__}) +{name}.writes = {pformat(self.read_writes.writes)} +{name}.unmet_dependencies = {pformat(self.unmet_dependencies)} +{name}.met_dependencies = {pformat(self.read_writes.reads - self.unmet_dependencies)} +{name}.min_input_distance = {self.min_input_distance} +{name}.max_input_distance = {self.max_input_distance} +{name}.outputs = [ + """ + ) + with buf.indent(): + for out in self.get_outputs(): + buf.splice(out.debug_str()) + buf.writeline("]") + + try: + buf.splice(self.debug_str_extra()) + except Exception: + log.warning("Ignoring error in debug_str()", exc_info=True) + + return buf.getrawvalue().rstrip() + + def debug_str_extra(self) -> str: + return "" + + def _debug_str_for_device(self) -> list[str]: + return self.debug_device_str(self) + + def debug_str_short(self) -> str: + maybe_data = getattr(self.node, "data", None) + data_str = "" + if isinstance(maybe_data, torch._inductor.ir.Pointwise): + data_str = ", " + maybe_data.str_helper( + [maybe_data.get_size()], shorten=False, multiline=False + ) + elif isinstance(maybe_data, torch._inductor.ir.Reduction): + data_str = ", " + maybe_data.str_helper( + [maybe_data.get_reduction_size(), maybe_data.get_reduction_type()], + shorten=False, + multiline=False, + ) + return f"{self}{data_str}" + + def log_details(self) -> None: + log.info( + "%s: unmet_dependencies = %s, writes = %s", + self, + self.unmet_dependencies, + self.read_writes.writes, + ) + + def reorder_loops_by_dep_pair( + self, self_dep: MemoryDep, other_dep: MemoryDep + ) -> bool: + return False + + def update_mutated_names(self, renames: dict[str, str]) -> None: + self.mutation_renames = { + name: renames[name] + for name in (dep.name for dep in self.read_writes.reads_and_writes()) + if name in renames + } + self.set_read_writes(self.read_writes.rename(self.mutation_renames)) + + def add_fake_dep(self, dep: Dep) -> None: + self.set_read_writes(self.read_writes.with_read(dep)) + + def has_aliasing_or_mutation(self) -> bool: + return any( + buf.get_aliases() or buf.get_mutations() for buf in self.get_outputs() + ) + + def set_read_writes(self, rw: dependencies.ReadWrites) -> None: + self.read_writes = rw + self.unmet_dependencies = self.read_writes.reads + self.clear_read_writes_dependent_caches() + self.prune_deps() + + def clear_read_writes_dependent_caches(self) -> None: + self.get_coalesce_analysis.clear_cache(self) + typing.cast(Any, self.get_tiling).clear_cache(self) + + @cache_on_self + def get_coalesce_analysis(self) -> CoalesceVarAnalysis | None: + from .tiling_utils import _analyze_memory_coalescing + + if not isinstance(self, (SchedulerNode, FusedSchedulerNode)): + return None + return _analyze_memory_coalescing(self) + + @cache_on_self_and_args("BaseSchedulerNode") + def get_tiling( + self, numel: sympy.Expr, rnumel: sympy.Expr + ) -> dict[str, sympy.Expr]: + from .codegen.simd import SIMDScheduling + + return SIMDScheduling.select_tiling(self.get_nodes(), numel, rnumel) + + def set_last_usage( + self, future_used_buffers: OrderedSet[str], mutation_real_name: dict[str, str] + ) -> None: + used_buffers = self.used_or_aliased_buffer_names() + used_buffers = OrderedSet(mutation_real_name.get(k, k) for k in used_buffers) + self.last_usage = used_buffers - future_used_buffers + + def mark_run(self) -> None: + for buf in self.outputs: + buf.allocate() + + def used_buffer_names(self) -> OrderedSet[str]: + return OrderedSet( + dep.name + for dep in itertools.chain(self.read_writes.reads, self.read_writes.writes) + ) + + def used_or_aliased_buffer_names(self) -> OrderedSet[str]: + """ + Returns buffer names used by this node, including aliases. + + Note: is_fake WeakDeps are excluded since they are purely for ordering + and should not affect buffer lifetime. + """ + used_names: OrderedSet[str] = OrderedSet() + + deps = [ + dep.name + for dep in itertools.chain(self.read_writes.reads, self.read_writes.writes) + if not (isinstance(dep, WeakDep) and dep.is_fake) + ] + while len(deps) > 0: + dep = deps.pop() + used_names.add(dep) + if V.graph.name_to_buffer.get(dep): + deps.extend( + alias + for alias in V.graph.name_to_buffer[ + dep + ].get_inputs_that_alias_output() + if alias not in used_names + ) + return used_names + + def prune_deps(self) -> None: + self.unmet_dependencies = OrderedSet( + dep + for dep in self.unmet_dependencies + if dep.name not in self.scheduler.available_buffer_names + ) + + def prune_weak_deps(self) -> None: + # Prune weak dependencies on operations that have been removed + def should_prune(dep: Dep) -> bool: + if not isinstance(dep, WeakDep): + return False + if dep.name not in self.scheduler.name_to_buf: + return False + + op_name = self.scheduler.name_to_buf[dep.name].defining_op_name() + return op_name in V.graph.removed_operations + + to_remove = OrderedSet( + dep for dep in self.read_writes.reads if should_prune(dep) + ) + self.set_read_writes(self.read_writes.remove_reads(to_remove)) + + def prune_redundant_deps( + self, name_to_fused_node: dict[str, BaseSchedulerNode] + ) -> None: + _prune_redundant_deps(self, name_to_fused_node, self.scheduler.name_to_buf) + + def get_name(self) -> str: + if self.node is None: + raise AssertionError("expected self.node to be set") + return self.node.get_operation_name() + + def get_first_name(self) -> str: + return self.get_name() + + @cache_on_self + def get_operation_names(self) -> OrderedSet[str]: + return OrderedSet(node.get_name() for node in self.get_nodes()) + + @cache_on_self + def get_buffer_names(self) -> OrderedSet[str]: + return OrderedSet(out.get_name() for out in self.outputs) + + @cache_on_self + def can_codegen_in_low_precision(self) -> bool: + return all( + isinstance(n, SchedulerNode) + and can_codegen_without_upcasts(n, disallow_fp32_ops=True) + for n in self.get_nodes() + ) + + @cache_on_self + def can_codegen_without_upcasts(self) -> bool: + return all( + isinstance(n, SchedulerNode) and can_codegen_without_upcasts(n) + for n in self.get_nodes() + ) + + def get_nodes(self) -> Sequence[BaseSchedulerNode]: + return [self] + + @cache_on_self + def has_strict_sum(self) -> bool: + return any( + isinstance(node, SchedulerNode) + and isinstance(node.node, ComputedBuffer) + and isinstance(node.node.data, ir.Reduction) + and node.node.data.strict_sum_rblock is not None + for node in self.get_nodes() + ) + + def get_outputs(self) -> Sequence[SchedulerBuffer]: + return self.outputs + + def get_output(self, buf_name: str) -> SchedulerBuffer: + return self.outputs_by_name[buf_name] + + def get_device(self) -> torch.device | None: + if self.node is None: + raise AssertionError("expected self.node to be set") + return self.node.get_device() + + def is_cpu(self) -> bool: + device = self.get_device() + return device is not None and device.type == "cpu" + + def is_gpu(self) -> bool: + device = self.get_device() + return device is not None and is_gpu(device.type) + + def is_reduction(self) -> bool: + return False + + def is_native_matmul(self) -> bool: + return False + + def is_split_scan(self) -> bool: + return False + + def is_template(self) -> bool: + return False + + def is_extern(self) -> bool: + return False + + def is_foreach(self) -> bool: + return False + + def can_inplace(self, read_dep: dependencies.Dep) -> bool: + return False + + def has_side_effects(self) -> bool: + return False + + def decide_inplace_update(self) -> None: + """ + Decide if there should be inplace updates for the node + and record the decision in the active kernel. + """ + from .codegen.wrapper import can_match_buffer_size + + if not ( + isinstance(self, SchedulerNode) + and config.inplace_buffers + and V.graph.has_feature(self.get_device(), BackendFeature.INPLACE_BUFFERS) + and ( + not isinstance(V.kernel, torch._inductor.codegen.simd.SIMDKernel) + or getattr(V.kernel, "mutations", None) is not None + ) + # hacky check for if V.kernel is a real kernel or NullHandler + and hasattr(V.kernel, "args") + ): + return + + # NOTE remove V.graph.removed_operations once deps issue is fixed + inconsequential_nodes = ( + self.ancestors + | V.graph.removed_operations + | self.scheduler.completed_operations + ) + + def single_index_in_fused_node(buf_to_be_inplaced: SchedulerBuffer) -> bool: + # Inside of NodeUser, we track that the read and write are equivalent + # before deciding if the use can be inplace. + # But if that use is fused into a larger kernel, we need to check equivalence + # of other accesses in fused scheduler node as well. + fused_node = buf_to_be_inplaced.scheduler.get_fused_node(self) + buf_name = buf_to_be_inplaced.get_name() + # Dedup read/writes with equivalent indices + # TODO - would be nice if we could just cache accesses on ReadWrites, + # and enforce variant that this class & members are functional.. + deps: OrderedSet[Dep] = OrderedSet() + for user in buf_to_be_inplaced.users: + user_node = user.node + if not isinstance(user_node, BaseSchedulerNode): + continue + + if ( + user_node.get_first_name() + not in buf_to_be_inplaced.scheduler.name_to_fused_node + or buf_to_be_inplaced.scheduler.get_fused_node(user_node) + is not fused_node + ): + continue + + deps |= ( + o + for o in user_node.read_writes.reads_and_writes() + if o.name == buf_name + ) + if len(deps) > 1: + return False + + return True + + for buf in self.get_outputs(): + buf_node = buf.node + if buf_node is None: + raise AssertionError("expected buf_node to be set") + if ( + not buf_node.should_allocate() + or buf_node.get_inputs_that_alias_output() + or buf_node.get_mutation_names() + or buf.get_name() in V.graph.removed_buffers + # CommBufferLayout buffer must keep its P2P allocation. + # Do not allow in-place reuse into or from a P2P buffer. + or isinstance(buf_node.get_output_spec(), ir.CommBufferLayout) + ): + continue + + for read in self.read_writes.reads: + input_buf: SchedulerBuffer | SchedulerDonatedBuffer | None + if read.name in self.scheduler.name_to_donated_buffer: + input_buf = self.scheduler.name_to_donated_buffer[read.name] + else: + input_buf = self.scheduler.name_to_buf.get(read.name) + + if ( + input_buf + and V.graph.wrapper_code.can_reuse(input_buf, self) + and not isinstance(input_buf.defining_op, NopKernelSchedulerNode) + ): + if input_buf.users is None: + raise AssertionError("expected input_buf.users to be set") + remaining_uses = [ + x + for x in input_buf.users + if x.node.get_name() not in inconsequential_nodes + ] + has_cross_stream_hazard = self.scheduler.has_cross_stream_hazard( + read.name, self + ) + has_cross_mempool_hazard = self.scheduler.get_buf_mempool( + read.name + ) != self.scheduler.node_to_mempool.get(self) + + if ( + not has_cross_stream_hazard + and not has_cross_mempool_hazard + and len(remaining_uses) == 1 + and remaining_uses[0].can_inplace + and remaining_uses[0].node is self + and input_buf.node is not None + and not isinstance( + input_buf.node.get_output_spec(), + ( + ir.NoneLayout, + ir.MultiOutputLayout, + ir.MutationLayoutSHOULDREMOVE, + ir.CommBufferLayout, + ), + ) + and not ( + input_buf.defining_op + and isinstance( + input_buf.defining_op.node, + (ir.FallbackKernel, ir.MultiOutput), + ) + and len(input_buf.node.get_inputs_that_alias_output()) > 0 + ) + and can_match_buffer_size(input_buf.node, buf.node) + and single_index_in_fused_node(input_buf) + ): + # if there isn't a triton kernel, then we don't need to call triton-specific things. + # but TODO this might be a convenient place to signal to the Collective kernels to inplace + # (and, can we make "kernel" less generic of a name?) + V.kernel.args.make_inplace(input_buf.get_name(), buf.get_name()) + # mutations not tracked in cpp kernels + if isinstance( + V.kernel, torch._inductor.codegen.simd.SIMDKernel + ): + V.kernel.mutations.add(input_buf.get_name()) + V.kernel.mutations.add(buf.get_name()) + + V.kernel.inplace_update_buffers[buf.get_name()] = ( + input_buf.get_name() + ) + break + + def codegen_originating_info( + self, buffer: IndentedBuffer, only_once: bool = True + ) -> None: + if not config.comment_origin: + return + + if only_once and self.written: + return + if self.node is None: + raise AssertionError("expected self.node to be set") + origins = self.node.get_origins() + out_lines = [] + + for o in origins: + if o.op == "output": + # These are boring and samey + continue + + out_lines.append("") + # TODO(voz): Should the pragma be constant somewhere? + out_lines.append("#pragma CMT ORIGIN:") + op_info_str = f"#pragma CMT {o.op} {o.target}" + if "seq_nr" in o.meta: + op_info_str = op_info_str + f" seq_nr:{o.meta['seq_nr']}" + out_lines.append(op_info_str) + if "stack_trace" in o.meta: + stack_trace = f"{o.meta['stack_trace']}" + stack_trace_last_line = stack_trace.rsplit("|", maxsplit=1)[-1] + out_lines.append( + "#pragma CMT " + + stack_trace_last_line.replace("{", "{{") + .replace("}", "}}") + .replace("\n", "\\") + .replace( + "\\", "\\\\" + ) # For windows safe path, avoid for example \x, \U. + ) + out_lines.append("#pragma CMT END ORIGIN") + out_lines.append("") + + if len(out_lines) == 0: + return + + # TODO(voz): Ostensibly, we should not need this. But there are cases where C++ codegen does + # not use BracesBuffer, so we have no good indicator of a C++ buffer atm. + buffer.writelines(out_lines) + self.written = True + + @cache_on_self + def get_read_write_buffers_sizes(self) -> int: + return self.get_read_write_buffers_sizes_impl( + include_reads=True, include_writes=True + ) + + @cache_on_self + def get_read_buffer_sizes(self) -> int: + return self.get_read_write_buffers_sizes_impl( + include_reads=True, include_writes=False + ) + + @cache_on_self + def get_write_buffer_sizes(self) -> int: + return self.get_read_write_buffers_sizes_impl( + include_reads=False, include_writes=True + ) + + def get_read_write_buffers_sizes_impl( + self, include_reads: bool, include_writes: bool + ) -> int: + return sum( + self.get_read_write_buffer_accesses( + include_reads=include_reads, include_writes=include_writes + ).values(), + start=0, + ) + + def get_read_write_buffer_accesses( + self, include_reads: bool, include_writes: bool + ) -> dict[str, int]: + """ + Counting the number of bytes accessed for a kernel is + surprisingly tricky. In particular, there is a differentiation + between 'theoretical' memory accesses and practical memory + accesses. For example, a layernorm kernel may actually access an + input 3 times, but in theory, it only needs to access its input + once (and may be optimized to do so through say, persistent + reductions) + + Another example is that even though a buffer is passed in, we may + not access the entire buffer. This may occur if we are accessing + a slice of the buffer. Another tricky case is for indirect + indexing, where the amount of bytes accessed depends on the + values of the input. + + What this function aims to compute is the memory accesses for + worst-case inputs, best-case optimization. What this means is + that for each buffer we compute the amount of potential accesses in two ways and take the minimum. + + 1. Numel in ranges multiplied by number of deps the buffer has + 2. The buffer size + + Returns memory accesses per buffer. + """ + if isinstance(self, NopKernelSchedulerNode): + return {} + if isinstance(self, ExternKernelSchedulerNode) and isinstance( + self.node, MultiOutput + ): + # todo: Calculate this - it's kinda annoying. + return {} + if ( + isinstance(self, ExternKernelSchedulerNode) + and isinstance(self.node, ir.FallbackKernel) + and self.node.op_overload + is torch._prims.rng_prims.graphsafe_run_with_rng_state + ): + return {} + + def try_size_hint(s: sympy.Expr) -> int: + return V.graph.sizevars.optimization_hint(s, fallback=0) + + if isinstance(self, SchedulerNode): + node_numel = try_size_hint( + sympy_product(self.get_ranges()[0]) + * sympy_product(self.get_ranges()[1]), + ) + else: + node_numel = int(1e9) + buf_accesses = collections.defaultdict(list) + + if include_reads: + for dep in self.read_writes.reads: + buf_accesses[dep.name].append(dep) + + if include_writes: + for dep in self.read_writes.writes: + buf_accesses[dep.name].append(dep) + + reads = ( + OrderedSet(dep.name for dep in self.read_writes.reads) + if include_reads + else OrderedSet() + ) + writes = ( + OrderedSet(dep.name for dep in self.read_writes.writes) + if include_writes + else OrderedSet() + ) + + def is_materialized(buf: str, snodes: Sequence[BaseSchedulerNode]) -> bool: + users = self.scheduler.name_to_buf[buf].users + buf_uses = OrderedSet(user.node for user in users) + return len(buf_uses - OrderedSet(snodes)) > 0 + + if isinstance(self, FusedSchedulerNode): + removed_buffers = OrderedSet( + dep for dep in writes if not is_materialized(dep, self.snodes) + ) + writes = writes - removed_buffers + reads = reads - removed_buffers + + buf_byte_accesses: dict[str, int] = {} + + for buf_name in reads | writes: + buf_accessed_elems = sum(node_numel for dep in buf_accesses[buf_name]) + buf: ir.Buffer | ir.TensorBox | ir.TorchBindObject + if buf_name in V.graph.name_to_buffer: + buf = V.graph.name_to_buffer[buf_name] + elif buf_name in V.graph.graph_inputs: + buf = V.graph.graph_inputs[buf_name] + else: + continue + + def get_buf_bytes( + buf: ir.Buffer | ir.TensorBox | ir.TorchBindObject | None, + ) -> int: + if not buf: + return 0 + + if isinstance(buf, ir.TorchBindObject): + return buf.get_buf_bytes() + elif isinstance(buf.layout, MultiOutputLayout): + # Kind of a lazy way to get the MultiOutput nodes corresponding to + # a MultiOutputLayout + users = self.scheduler.name_to_buf[buf.get_name()].users + tot = 0 + for user in users: + if isinstance(user.node, OutputNode): + continue + if not isinstance(user.node, BaseSchedulerNode): + raise AssertionError( + "expected user.node to be a BaseSchedulerNode" + ) + if isinstance(user.node.node, MultiOutput): + for sched_buf in user.node.get_outputs(): + tot += get_buf_bytes(sched_buf.node) + else: + # Buf is a MultiOutputLayout but not all of its + # users are MultiOutputs... + # TODO: Figure out what's going on + return 0 + return tot + elif isinstance(buf.layout, ir.NoneLayout): + return sum( + get_buf_bytes(V.graph.get_buffer(mut_name)) + for mut_name in buf.get_mutation_names() + ) + else: + buf_elems = try_size_hint(sympy_product(buf.get_size())) + return get_dtype_size(buf.get_dtype()) * min( + buf_accessed_elems, buf_elems + ) + + buf_bytes = get_buf_bytes(buf) + if buf_name not in buf_byte_accesses: + buf_byte_accesses[buf_name] = buf_bytes + else: + buf_byte_accesses[buf_name] += buf_bytes + + return buf_byte_accesses + + @cache_on_self + def estimate_flops(self) -> int | None: + if self.node is None: + return None + fx_node = self.node.get_origin_node() + if fx_node is None: + return None + + flops = count_flops_fx(fx_node) + if flops is None: + return None + + if isinstance(flops, torch.SymInt): + flops = flops.node.expr + + resolved_flops = V.graph.sizevars.optimization_hint(flops, fallback=0) + counters["inductor"]["flop_count"] += resolved_flops + return resolved_flops + + def get_estimated_runtime(self) -> float: + if self.override_estimated_runtime is not None: + return self.override_estimated_runtime + + return self._get_estimated_runtime() + + @cache_on_self + def _get_estimated_runtime(self) -> float: + """ + Returns estimated op runtime in milliseconds (ms) + """ + buf = self.get_nodes()[0].get_outputs()[0] + layout = buf.node.get_output_spec() + if not is_gpu(get_device_type(layout)): + # default to no reordering based on runtime + return 0 + + # Collective kernels + if is_collective(self.node): + if not isinstance(self.node, ir.IRNode): + raise AssertionError("expected self.node to be an ir.IRNode") + try: + if config_comms.runtime_estimations_use_nccl_lib_estimations: + cache_key = get_estimate_runtime_cache_key_from_snode(self) + cache = get_estimate_runtime_cache() + cache_val = cache.lookup(cache_key) + if cache_val is not None: + if not isinstance(cache_val, float): + raise AssertionError("expected cache_val to be a float") + return cache_val + + ms = estimate_nccl_collective_runtime_nccl_estimator(self) + if ms is None: + # NCCL estimations fail: fallback to in-tree algorithmic estimation. + ms = estimate_nccl_collective_runtime(self.node) + + cache.set_value(cache_key, value=ms) + return ms + return estimate_nccl_collective_runtime(self.node) + except ValueError as e: + # We don't know how to estimate runtime for this collective, + # falling back to 0 + log.info(e) + return 0 + except TypeError as e: + # this happens when the collective is not of type ir._CollectiveKernel + log.info(e) + return 0 + + elif is_wait(self.node): + # ir.Wait is only used for collective ops. + # The time needed for the collective op is already estimated and considered + # when we are processing the collective op IR node, so ir.Wait takes 0 time + # since it doesn't take extra time to get the result after the collective is completed. + return 0 + + ret = maybe_estimate_runtime_benchmark(self) + if ret is not None: + return ret + + dtype = buf.node.maybe_get_dtype() + try: + gpu_memory_bandwidth = get_gpu_dram_gbps() + gpu_flops = get_device_tflops(dtype) * 10**12 + # If cudaGetDeviceProperties returns 0 for gpu_memory_bandwidth or gpu_flops + # there is a chance to continue execution successfully. Otherwise, it would fail with + # ZeroDivisionError below. + if gpu_memory_bandwidth <= 0: + raise AssertionError( + f"gpu_memory_bandwidth cannot be <= 0, but got {gpu_memory_bandwidth}" + ) + if gpu_flops <= 0: + raise AssertionError(f"gpu_flops cannot be <= 0, but got {gpu_flops}") + except Exception: + return 0 + + flops_est = self.estimate_flops() + + if flops_est == 0 or flops_est is None: + # no flops estimate, so fall back to memory estimate + ns = self.get_read_write_buffers_sizes() / gpu_memory_bandwidth + ms = ns / 1e6 + return ms + + # TODO(xmfan): find a better heuristic to model FLOPS/latency relationship + factor = 1.0 + counted_bytes = self.get_read_write_buffers_sizes() + counted_bytes = 0 if counted_bytes is None else counted_bytes + compute_time = (factor * flops_est / gpu_flops) * 1e9 + transfer_time = counted_bytes / gpu_memory_bandwidth + + # Return estimated runtime in milliseconds + ns = max(compute_time, transfer_time) + ms = ns / 1e6 + return ms + + def get_template_node(self) -> ir.TemplateBuffer | None: + return None + + def get_template_node_or_throw(self) -> ir.TemplateBuffer: + template = self.get_template_node() + if template is None: + raise AssertionError("expected template to be set") + return template + + @staticmethod + def get_prologue_template_epilogue( + nodes: list[BaseSchedulerNode], + ) -> tuple[list[BaseSchedulerNode], BaseSchedulerNode, list[BaseSchedulerNode]]: + """ + For the list of nodes, get the prologue, template, and epilogue + """ + template_index = next(i for i, n in enumerate(nodes) if n.is_template()) + + prologue = nodes[:template_index] + template_node = nodes[template_index] + epilogue = nodes[template_index + 1 :] + return prologue, template_node, epilogue + + +@functools.cache +def get_estimate_runtime_cache() -> torch._inductor.codecache.LocalCache: + return torch._inductor.codecache.LocalCache() + + +def get_estimate_runtime_cache_key_from_snode(snode: BaseSchedulerNode) -> str: + python_kernel_name = getattr(snode.node, "python_kernel_name", "") + args = snode.node.inputs # type: ignore[union-attr] + args = snode.node.fill_non_provided_args( # type: ignore[union-attr] + [*args, *snode.node.constant_args], # type: ignore[union-attr] + snode.node.kwargs, # type: ignore[union-attr] + ) + kwargs = snode.node.kwargs # type: ignore[union-attr] + flat_args, flat_args_pytree_spec = pytree.tree_flatten((args, kwargs)) + + def _is_tensor_ir(x) -> bool: # type: ignore[no-untyped-def] + return isinstance(x, ir.IRNode) and not isinstance( + x, (ir.GeneratorState, ir.OpaqueObjectState) + ) + + cache_key = str( + (python_kernel_name,) + + tuple(tuple(a.get_size()) if _is_tensor_ir(a) else None for a in flat_args) + ) + return cache_key + + +def _get_benchmarkable_extern_fn( + snode: BaseSchedulerNode, +) -> Callable[[Any], Any] | None: + if not isinstance(snode, ExternKernelSchedulerNode): + return None + if not isinstance(snode.node, ir.ExternKernel): + return None + + op_overload = snode.node.op_overload + if not isinstance(op_overload, torch._ops.OpOverload): + return None + + op = op_overload.overloadpacket + + from torch.utils.flop_counter import flop_registry + + if op not in flop_registry: + return None + + return op + + +def maybe_estimate_runtime_benchmark(snode: BaseSchedulerNode) -> float | None: + bench_fn = None + args_kwargs_fn = None + if config.runtime_estimations_mms_benchmark: + mm_fn = _get_benchmarkable_extern_fn(snode) + if mm_fn is None: + return None + bench_fn = mm_fn + + args_kwargs_fn = lambda: snode_args_kwargs(snode) # noqa: E731 + else: + return None + + cache_key = get_estimate_runtime_cache_key_from_snode(snode) + cache = get_estimate_runtime_cache() + cache_val = cache.lookup(cache_key) + if cache_val is not None: + if not isinstance(cache_val, float): + raise AssertionError("expected cache_val to be a float") + return cache_val + + from .utils import snode_args_kwargs + + args, kwargs = args_kwargs_fn() + from torch._inductor.runtime.benchmarking import benchmarker + + ms = benchmarker.benchmark( + bench_fn, + args, # pyrefly: ignore[bad-argument-type] + kwargs, + memory_warmup_iters=5, + benchmark_iters=10, + max_benchmark_duration=10, + ) # type: ignore[arg-type] + + cache.set_value(cache_key, value=ms) + return ms + + +@dataclasses.dataclass(slots=True) +class WhyNoFuse: + name1: str + name2: str + reason: str + args: tuple[Any, ...] + + def __init__(self, node1: BaseSchedulerNode, node2: BaseSchedulerNode) -> None: + self.name1 = node1.get_name() + self.name2 = node2.get_name() + + def __call__(self, reason: str, *args: Any) -> None: + self.reason = reason + self.args = args + fusion_log.debug(self) + + def __str__(self) -> str: + return f"cannot fuse {self.name1} with {self.name2}: " + ( + self.reason % self.args + ) + + +def pformat(obj: Any) -> str: + if isinstance(obj, (OrderedSet, set)): # noqa: set_linter + # pformat has trouble with sets of sympy exprs + obj = sorted(obj, key=str) + result = pprint.pformat(obj, indent=4) + if "\n" in result: + return f"\n{textwrap.indent(result, ' ' * 4)}" + return result + + +class OutputNode: + def __init__(self, dep: StarDep) -> None: + self.unmet_dependencies = OrderedSet([dep]) + + def is_reduction(self) -> bool: + return False + + def get_inputs_that_alias_output(self) -> Sequence[str]: + return () + + def get_name(self) -> str: + return "OUTPUT" + + __repr__ = get_name + + +def _prune_redundant_deps( + node: BaseSchedulerNode, + name_to_fused_node: dict[str, BaseSchedulerNode], + name_to_buf: dict[str, SchedulerBuffer], +) -> None: + """ + Prunes weakdeps intended for mutation ordering + on an upstream fused node if after fusion there is another dependency + on the fused upstream node, making the weakdep redundant + + In essence this enforces an ordering on fusions. As fusions occur, weakdeps will + be incrementally removed, enabling other fusions, ensuring they are fused in order. + """ + name_to_dep_count: Counter[str] = collections.Counter() + + for dep in node.unmet_dependencies: + if not isinstance(dep, WeakDep): + op_name = name_to_buf[dep.name].defining_op_name() + name_to_dep_count[name_to_fused_node[op_name].get_name()] += 1 + + def should_prune(dep: Dep) -> bool: + if isinstance(dep, WeakDep): + op_name = name_to_buf[dep.name].defining_op_name() + is_redundant = name_to_dep_count[ + name_to_fused_node[op_name].get_name() + ] > 0 and node.scheduler.fusable_weak_dep( + dep, name_to_fused_node[op_name], node + ) + # These can occur because fused nodes always gather deps from their snodes + # If B has a weakdep on A + # B gets fused with C, then any time BC is fused, the weakdep will reappear + is_self_dep = name_to_fused_node[op_name] == node + return is_redundant or is_self_dep + else: + return False + + deps_to_prune = OrderedSet( + dep for dep in node.unmet_dependencies if should_prune(dep) + ) + + if deps_to_prune: + node.unmet_dependencies = node.unmet_dependencies - deps_to_prune + node.set_read_writes(node.read_writes.remove_reads(deps_to_prune)) + + +class ExternKernelSchedulerNode(BaseSchedulerNode): + def __init__(self, scheduler: Scheduler, node: ir.Operation) -> None: + super().__init__(scheduler) + self._init_from_node(node) + self.set_read_writes(node.get_read_writes()) + + if isinstance(node, ir.UserDefinedTritonKernel) and node.can_fuse_epilogue(): + numel = math.prod(node.mutable_args[0].shape) + rnumel = 1 + device = node.get_device_or_error() + # pyrefly: ignore [bad-assignment] + self.group = (device, (numel, rnumel)) + + def debug_str_extra(self) -> str: + return f"{self.get_name()}.node.kernel = {getattr(self.node, 'python_kernel_name', None)}" + + def is_extern(self) -> bool: + return True + + def has_side_effects(self) -> bool: + if self.node is None: + raise AssertionError("expected self.node to be set") + return hasattr(self.node, "has_side_effects") and self.node.has_side_effects() + + def get_ranges(self) -> Sequence[Sequence[sympy.Expr]]: + if ( + isinstance(self.node, ir.UserDefinedTritonKernel) + and self.node.can_fuse_epilogue() + ): + numel = math.prod(self.node.mutable_args[0].shape) + return ([numel], []) + return ([], []) + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + if not isinstance(self.node, ir.ExternKernel): + raise AssertionError("expected self.node to be an ir.ExternKernel") + return self.node.codegen(wrapper) + + +class NopKernelSchedulerNode(BaseSchedulerNode): + def __init__(self, scheduler: Scheduler, node: ir.Operation) -> None: + super().__init__(scheduler) + self._init_from_node(node) + self.set_read_writes(node.get_read_writes()) + + +class SchedulerNode(BaseSchedulerNode): + """ + A SchedulerNode is a node for scheduling that encapsulates either + a ComputedBuffer or a TemplateBuffer. + """ + + _sizes: tuple[Sequence[sympy.Expr], ...] + _body: LoopBody + + def __init__( + self, + scheduler: Scheduler, + node: ir.ComputedBuffer | ir.TemplateBuffer, + ) -> None: + super().__init__(scheduler) + self._loop_mutation_listener: Callable[[SchedulerNode], None] | None = None + self._loop_state_gen = 0 + self._init_from_node(node) + self._compute_attrs() + + def _compute_attrs( + self, + extra_indexing_constraints: ir.ExtraIndexingConstraints | None = None, + recompute_sizes_body_func: Callable[_P, _T] | None = None, + ) -> None: + if not isinstance(self.node, (ir.ComputedBuffer, ir.TemplateBuffer)): + raise AssertionError( + "expected self.node to be a ComputedBuffer or TemplateBuffer" + ) + self._sizes, body = self.node.simplify_and_reorder( + extra_indexing_constraints=extra_indexing_constraints, + recompute_sizes_body_func=recompute_sizes_body_func, + ) + self._body = body # type: ignore[assignment] + + device = self.node.get_device_or_error() + group_fn = self.scheduler.get_backend(device).group_fn + self.group = (device, group_fn(self._sizes)) + + # Don't normalize since normalization will merge loops which + # makes it hard to decide new loop orders. + should_normalize = not config.loop_ordering_after_fusion or not is_gpu( + device.type + ) + + if isinstance(self.node, ir.TemplateBuffer): + self.set_read_writes( + self.node.extract_read_writes(normalize=should_normalize) + ) + else: + self.set_read_writes( + dependencies.extract_read_writes( + self._body, *self._sizes, normalize=should_normalize + ) + ) + + def recompute_size_and_body( + self, + extra_indexing_constraints: ir.ExtraIndexingConstraints | None = None, + recompute_sizes_body_func: Callable[..., Any] | None = None, + ) -> None: + fake_deps: OrderedSet[Dep] = OrderedSet( + dep for dep in self.read_writes.reads if isinstance(dep, (WeakDep, StarDep)) + ) + self._compute_attrs( + extra_indexing_constraints=extra_indexing_constraints, + recompute_sizes_body_func=recompute_sizes_body_func, + ) + if fake_deps or self.mutation_renames: + read_writes = self.read_writes + if fake_deps: + read_writes = read_writes.with_read(fake_deps) + self.set_read_writes(read_writes.rename(self.mutation_renames)) + + def refresh_dependencies( + self, normalize: bool, need_clear_tiling_cache: bool + ) -> None: + # Fake dependencies are added manually. They can not be analyzed from + # extract_read_writes. Find them out and apply manually. + fake_deps: OrderedSet[Dep] = OrderedSet( + dep for dep in self.read_writes.reads if isinstance(dep, (WeakDep, StarDep)) + ) + + # don't normalize since the loop order may need to be further changed + # later + self.set_read_writes( + dependencies.extract_read_writes( + self._body, *self._sizes, normalize=normalize + ) + .with_read(fake_deps) + .rename(self.mutation_renames) + ) + + self.clear_loop_body_dependent_caches(need_clear_tiling_cache) + + def clear_loop_body_dependent_caches(self, need_clear_tiling_cache: bool) -> None: + self.clear_read_writes_dependent_caches() + self.pointwise_read_writes.clear_cache(self) + + if need_clear_tiling_cache: + from .codegen.simd import SIMDScheduling + + # TODO(shunting) if this cause compilation time increase when + # enabling LOAF by default, try just clearing the specific cache + # entry by using a customized cache implementation rather than + # lru_cache. + SIMDScheduling.candidate_tilings.cache_clear() + + def snapshot_loop_state(self) -> tuple[Any, ...]: + """Snapshot mutable state modified by loop transformations + (apply_new_loop_order, apply_loop_reindexing). Must be kept + in sync with those methods and restore_loop_state.""" + return ( + self._body, + self._sizes, + self.group, + self.read_writes, + self.unmet_dependencies, + self._loop_state_gen, + ) + + def restore_loop_state(self, state: tuple[Any, ...]) -> None: + """Restore state from snapshot_loop_state.""" + ( + self._body, + self._sizes, + self.group, + self.read_writes, + self.unmet_dependencies, + self._loop_state_gen, + ) = state + self.clear_loop_body_dependent_caches(need_clear_tiling_cache=True) + + def _before_loop_state_mutation(self) -> None: + if self._loop_mutation_listener is not None: + self._loop_mutation_listener(self) + # Identifies the current loop state, so analyses derived from it can be + # cached across the O(n^2) fusion pair search. Bumped after notifying + # the listener, which snapshots the pre-mutation state: snapshot and + # restore then carry the generation, so rolling a trial reindex back + # also restores cache validity. + self._loop_state_gen += 1 + + def apply_indexing_exprs(self, replacements: dict[str, sympy.Expr]) -> None: + if self._body is None: + raise AssertionError("expected a loop body") + self._before_loop_state_mutation() + self._body = self._body.with_indexing_exprs(replacements) + self.refresh_dependencies(normalize=True, need_clear_tiling_cache=True) + + def apply_new_loop_order(self, new_order: Sequence[int]) -> None: + self._before_loop_state_mutation() + self._body = self._body.reorder_iter_loops( + new_order, + ) + self._sizes = self._body.sizes + + self.refresh_dependencies(normalize=False, need_clear_tiling_cache=True) + + def apply_loop_reindexing(self, new_iter_sizes: Sequence[sympy.Expr]) -> None: + if not isinstance(self.node, (ir.ComputedBuffer, ir.TemplateBuffer)): + raise AssertionError( + "expected self.node to be a ComputedBuffer or TemplateBuffer" + ) + + self._before_loop_state_mutation() + self._body = self._body.reindex_iter_loops(new_iter_sizes) + self._sizes = self._body.sizes + + device = self.node.get_device_or_error() + group_fn = self.scheduler.get_backend(device).group_fn + self.group = (device, group_fn(self._sizes)) + + self.refresh_dependencies(normalize=False, need_clear_tiling_cache=True) + + def swap_pw_red_dimension(self) -> None: + num_rdims = self._body.get_original_num_rdims() + num_pwdims = len(self._body.iter_vars) - num_rdims + pwdims = tuple(range(num_pwdims)) + rdims = tuple(range(num_pwdims, num_pwdims + num_rdims)) + + self.apply_new_loop_order(rdims + pwdims) + if len(self.group[1]) != 2: + raise AssertionError( + f"expected group[1] to have length 2, got {len(self.group[1])}" + ) + self.group = self.group[0], (self.group[1][1], self.group[1][0]) + + def extract_pw_from_reduction(self) -> BaseSchedulerNode: + self._body = self._body.extract_pw_from_reduction() + return self + + def cancel_reduction_split(self) -> None: + if not MixOrderReduction.is_split_reduction(self): + return + if not isinstance(self.node, ir.ComputedBuffer): + raise AssertionError("expected self.node to be an ir.ComputedBuffer") + with self.node.with_original_inner_fn(): + self._compute_attrs() + + def expand_dimension_for_pointwise_node( + self, dimension: int, new_range: int + ) -> None: + if not isinstance(self.node, (ir.ComputedBuffer, ir.TemplateBuffer)): + raise AssertionError( + "expected self.node to be a ComputedBuffer or TemplateBuffer" + ) + + self._before_loop_state_mutation() + self._body = self._body.expand_dimension_for_pointwise_node( + dimension, new_range + ) + self._sizes = self._body.sizes + + device = self.node.get_device_or_error() + group_fn = self.scheduler.get_backend(device).group_fn + self.group = (device, group_fn(self._sizes)) + + # Need normalize the prefix name to facilitate finding common dependencies + self.refresh_dependencies(normalize=True, need_clear_tiling_cache=True) + + def merge_loops(self) -> None: + self._body = self._body.merge_loops() + self._sizes = self._body.sizes + + # merge_loops is called after loop reordering. + # We still need retain fake dependencies since codegen the + # estimated amount of memory access rely on them. + # + # Merge loops does not affect the tiling decision. So we + # don't need clear the tiling cache. + self.refresh_dependencies(normalize=True, need_clear_tiling_cache=False) + + def reorder_loops_by_dep_pair( + self, self_dep: MemoryDep, other_dep: MemoryDep + ) -> bool: + new_order = None + self_sizes = self._sizes[0] + if len(self_sizes) == self_dep.num_vars == other_dep.num_vars: + new_order = self_dep.decide_loop_order_to_match(other_dep) + + if new_order: + # pyrefly: ignore [bad-assignment] + metrics.num_loop_reordering += 1 + loop_ordering_log.debug( + "Reorder loops for %s with order %s", self.get_name(), new_order + ) + self.apply_new_loop_order(new_order) + return True + else: + loop_ordering_log.debug( + "Don't reordering %s because we can not decide the suitable loop order", + self.get_name(), + ) + return False + + def debug_str_extra(self) -> str: + name = self.get_name() + lines = [ + f"{name}.group.device = {self.group[0]}", + f"{name}.group.iteration = {self.group[1]}", + f"{name}.sizes = {self._sizes}", + ] + for dep in self.read_writes.reads_and_writes(): + if not isinstance(dep, WeakDep): + buf_name = dep.name + buf = V.graph.get_buffer(buf_name) + if not isinstance(buf, ir.TorchBindObject): + lines.append(f"{buf_name}_layout = {pformat(buf.layout)}") + if isinstance(self._body, LoopBody): + lines.append(f"class {name}_loop_body:") + lines.append(textwrap.indent(self._body.debug_str(), " ")) + + if self.node is None: + raise AssertionError("expected self.node to be set") + lines.extend(self._debug_str_for_device()) + + return "\n".join(lines) + + def get_ranges(self) -> Sequence[Sequence[sympy.Expr]]: + return self._sizes + + def is_reduction(self) -> bool: + if not isinstance(self.node, (ir.ComputedBuffer, ir.TemplateBuffer)): + raise AssertionError(f"{type(self.node)=}") + + # self._body containing partial accumulate means the reduction is + # converted to a pointwise node. Need this extra check since + # we change self._body but didn't change self.node (IRNode) + # when converting a reduction to a pointwise + return bool(self.node.get_reduction_type()) and ( + self._body is None or not self._body.has_partial_accumulate + ) + + def is_native_matmul(self) -> bool: + if not isinstance(self.node, ir.ComputedBuffer): + raise AssertionError(f"{type(self.node)=}") + return self.node.get_reduction_type() == "dot" + + def is_split_scan(self) -> bool: + if not isinstance(self.node, (ir.ComputedBuffer, ir.TemplateBuffer)): + raise AssertionError(f"{type(self.node)=}") + return isinstance(self.node, ir.ComputedBuffer) and isinstance( + self.node.data, ir.SplitScan + ) + + def is_template(self) -> bool: + return isinstance(self.node, ir.TemplateBuffer) + + def get_template_node(self) -> ir.TemplateBuffer | None: + return self.node if isinstance(self.node, ir.TemplateBuffer) else None + + def run(self, *index_vars: Sequence[sympy.Expr]) -> None: + self.decide_inplace_update() + self.mark_run() + self.codegen(index_vars) + + def ranges_from_index_vars( + self, index_vars: Sequence[Sequence[sympy.Expr]] + ) -> dict[sympy.Expr, sympy.Expr]: + sizes = self._sizes + if sum(map(len, sizes)) != sum(map(len, index_vars)): + raise AssertionError("expected sum of sizes to equal sum of index_vars") + var_ranges = dict( + zip( + itertools.chain.from_iterable(index_vars), + itertools.chain.from_iterable(sizes), + ) + ) + return var_ranges + + def codegen(self, index_vars: Sequence[Sequence[sympy.Expr]]) -> None: + """ + Generate code for this node using the provided index variables. + + This method sets up the appropriate context for code generation, including + simplifying indexing expressions based on the variable ranges, and then + calls the node's body function with the index variables. + + Args: + index_vars: A sequence of sequences of sympy expressions representing + the index variables for each dimension of the computation. + """ + var_ranges = self.ranges_from_index_vars(index_vars) + try: + with ( + V.set_ops_handler(SimplifyIndexing(V.get_ops_handler(), var_ranges)), + V.kernel.set_current_node(self), + ): + self._body(*index_vars) + except Exception: + log.fatal("Error in codegen for %s", self.node) + raise + + def pointwise_or_reduction_read_writes( + self, pointwise: bool = True + ) -> dependencies.ReadWrites: + """ + Get the memory dependencies in either the pointwise or the reduction axes. + """ + keep_sizes, ignore_sizes = self._sizes if pointwise else reversed(self._sizes) + return dependencies.extract_read_writes( + self._body, keep_sizes, hidden_args=[[sympy.S.Zero] * len(ignore_sizes)] + ) + + @cache_on_self + def pointwise_read_writes(self) -> dependencies.ReadWrites: + """ + Get the memory dependencies in the non-reduction axes. + """ + return self.pointwise_or_reduction_read_writes(pointwise=True) + + @cache_on_self + def reduction_read_writes(self) -> dependencies.ReadWrites: + """ + Get the memory dependencies in the reduction axes. + """ + return self.pointwise_or_reduction_read_writes(pointwise=False) + + def can_inplace(self, read_dep: dependencies.Dep) -> bool: + if self.is_template(): + return False + if any(out.get_aliases() for out in self.get_outputs()): + return False + if len(self.read_writes.writes) == 1 and isinstance( + read_dep, dependencies.MemoryDep + ): + write_dep = next(iter(self.read_writes.writes)) + if not isinstance(write_dep, dependencies.MemoryDep): + raise AssertionError(f"{type(write_dep)=}") + return read_dep.index == write_dep.index and read_dep.size == write_dep.size + return False + + @cache_on_self + def _get_atomic_add_buffers(self) -> OrderedSet[str]: + buffers_store_as_atomic_add: OrderedSet[str] = OrderedSet() + if isinstance(self._body, LoopBody): + for node in self._body.get_nodes(): + if ( + node.op == "call_method" + and node.target == "store" + and ( + ("mode" in node.kwargs and node.kwargs["mode"] == "atomic_add") + or (len(node.args) == 5 and node.args[4] == "atomic_add") + ) + ): + buffers_store_as_atomic_add.add( + node.kwargs["name"] + if "name" in node.kwargs + else (node.args[1] if len(node.args) >= 2 else "") + ) + return buffers_store_as_atomic_add + + @cache_on_self + def has_side_effects(self) -> bool: + # self._body is None sometimes that's why this check was added + if self._body is not None and self._body.has_op("device_assert_async"): + return True + return super().has_side_effects() + + +def refresh_group_node_dependencies( + group_snode: FusedSchedulerNode | GroupedSchedulerNode, +) -> None: + snodes = group_snode.snodes + group_snode.set_read_writes( + dependencies.ReadWrites.merge_list([x.read_writes for x in snodes]) + ) + + group_snode.unmet_dependencies = ( + OrderedSet( + dep + for dep in OrderedSet.union(*[x.unmet_dependencies for x in snodes]) + if dep.name not in group_snode.get_buffer_names() + ) + - group_snode.read_writes.writes + ) + + +def init_group_node( + group_snode: FusedSchedulerNode | GroupedSchedulerNode, + scheduler: Scheduler, + snodes: list[BaseSchedulerNode], +) -> None: + if not isinstance(group_snode, (FusedSchedulerNode, GroupedSchedulerNode)): + raise AssertionError("expected FusedSchedulerNode or GroupedSchedulerNode") + group_snode.snodes = snodes + group_snode.scheduler = scheduler + group_snode.node = None + group_snode.ancestors = OrderedSet.union( + *[x.ancestors for x in snodes if x.ancestors is not None] + ) + + refresh_group_node_dependencies(group_snode) + + group_snode.min_order = min(x.min_order for x in group_snode.snodes) + group_snode.max_order = max(x.max_order for x in group_snode.snodes) + group_snode.min_input_distance = min( + x.min_input_distance for x in group_snode.snodes + ) + group_snode.max_input_distance = max( + x.max_input_distance for x in group_snode.snodes + ) + group_snode.outputs_by_name = { + buf.get_name(): buf for buf in group_snode.get_outputs() + } + + +class FusedSchedulerNode(BaseSchedulerNode): + """ + This is a "fake" scheduler node that represents a group of scheduler nodes + that are meant to be fused together. The way it does this is by maintaining + its unmet dependencies as the union of its constituent nodes. + """ + + snodes: list[BaseSchedulerNode] + + @classmethod + def fuse( + cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> FusedSchedulerNode: + if node1.scheduler is not node2.scheduler: + raise AssertionError("expected node1 and node2 to share the same scheduler") + if not isinstance(node1, (SchedulerNode, FusedSchedulerNode)): + raise AssertionError( + "expected node1 to be a SchedulerNode or FusedSchedulerNode" + ) + if node1.is_template() and isinstance(node2, ExternKernelSchedulerNode): + if not isinstance(node2.node, ir.MultiOutput): + raise AssertionError("expected node2.node to be an ir.MultiOutput") + else: + if not isinstance(node2, (SchedulerNode, FusedSchedulerNode)): + raise AssertionError( + "expected node2 to be a SchedulerNode or FusedSchedulerNode" + ) + nodes = list(itertools.chain(node1.get_nodes(), node2.get_nodes())) + return cls(node1.scheduler, nodes) + + def extract_pw_from_reduction(self) -> BaseSchedulerNode: + for subnode in self.snodes: + if not isinstance(subnode, SchedulerNode): + raise AssertionError("expected subnode to be a SchedulerNode") + if not subnode.is_reduction(): + raise AssertionError("expected subnode to be a reduction") + subnode.extract_pw_from_reduction() + return self + + def swap_pw_red_dimension(self) -> None: + for subnode in self.snodes: + if not isinstance(subnode, SchedulerNode): + raise AssertionError("expected subnode to be a SchedulerNode") + subnode.swap_pw_red_dimension() + + @cache_on_self + def estimate_flops(self) -> int | None: + # don't increment counters in fused methods so we don't double count + fps = list( + filter( + None, + ( + node.estimate_flops() + for node in self.get_nodes() + if node.is_template() or node.is_extern() + ), + ) + ) + if len(fps) == 0: + return None + ret = sum(fps) + return ret + + def reorder_loops_by_dep_pair( + self, self_dep: MemoryDep, other_dep: MemoryDep + ) -> bool: + """ + Return true if a loop reordering is performed. + """ + if self.is_template(): + # We can not really reorder loops for a triton template + return False + self_sizes = None + for snode in self.snodes: + if not isinstance(snode, SchedulerNode): + return False + if self_sizes is not None and tuple(self_sizes) != tuple(snode._sizes[0]): + loop_ordering_log.debug( + "Can not reorder fused node due to different sizes" + ) + return False + self_sizes = snode._sizes[0] + new_order = None + + if self_sizes is None: + raise AssertionError("expected self_sizes to be set") + if len(self_sizes) == self_dep.num_vars == other_dep.num_vars: + new_order = self_dep.decide_loop_order_to_match(other_dep) + + if not new_order: + loop_ordering_log.debug( + "Don't reordering fused node %s because we can not decide the suitable loop order", + self.get_name(), + ) + return False + # pyrefly: ignore [bad-assignment] + metrics.num_loop_reordering += 1 + loop_ordering_log.debug( + "Reorder loops for fused node %s with order %s", self.get_name(), new_order + ) + for snode in self.snodes: + if not isinstance(snode, SchedulerNode): + raise AssertionError("expected snode to be a SchedulerNode") + snode.apply_new_loop_order(new_order) + + refresh_group_node_dependencies(self) + return True + + def __init__(self, scheduler: Scheduler, snodes: list[BaseSchedulerNode]) -> None: + super().__init__(scheduler) + init_group_node(self, scheduler, snodes) + self.users: list[NodeUser] = [] + self.group = max(snodes, key=lambda x: int(x.is_reduction())).group + + @cache_on_self + def get_name(self) -> str: + return "_".join([x.get_name() for x in self.snodes]) + + def get_first_name(self) -> str: + return self.snodes[0].get_name() + + @cache_on_self + def get_buffer_names(self) -> OrderedSet[str]: + return OrderedSet.union(*[x.get_buffer_names() for x in self.snodes]) + + def get_outputs(self) -> list[SchedulerBuffer]: + result: list[SchedulerBuffer] = [] + for node in self.snodes: + result.extend(node.get_outputs()) + return result + + def debug_str_extra(self) -> str: + lines = [ + f"{self.get_name()}.snodes[{i}] =\n{node.debug_str()}" + for i, node in enumerate(self.snodes) + ] + node = self.snodes[0].node + if node is not None: + lines.extend(self._debug_str_for_device()) + + return textwrap.indent("\n".join(lines).rstrip(), " ") + + def debug_str_short(self) -> str: + snodes_str = [node.debug_str_short() for node in self.snodes] + return f"{self}, snodes: {snodes_str}" + + def set_last_usage( + self, future_used_buffers: OrderedSet[str], mutation_real_name: dict[str, str] + ) -> None: + # Set self.last_usage using the global information + # This will be used for inter-kernel optimisations + super().set_last_usage(future_used_buffers, mutation_real_name) + # Set self.last_usage on the snodes + # This will be used for optimisations within the kernel + future_used_buffers: OrderedSet[str] = OrderedSet() + for node in reversed(self.snodes): + node.set_last_usage(future_used_buffers, mutation_real_name) + future_used_buffers.update(node.last_usage) + + @cache_on_self + def used_buffer_names(self) -> OrderedSet[str]: + return OrderedSet.union(*[x.used_buffer_names() for x in self.snodes]) + + @cache_on_self + def used_or_aliased_buffer_names(self) -> OrderedSet[str]: + return OrderedSet.union( + *[x.used_or_aliased_buffer_names() for x in self.snodes] + ) + + def get_nodes(self) -> Sequence[BaseSchedulerNode]: + return self.snodes + + def __repr__(self) -> str: + return f"{type(self).__name__}(nodes={self.get_name()})" + + @cache_on_self + def is_reduction(self) -> bool: + return any(x.is_reduction() for x in self.snodes) + + @cache_on_self + def is_native_matmul(self) -> bool: + return any(x.is_native_matmul() for x in self.snodes) + + @cache_on_self + def is_split_scan(self) -> bool: + return any(x.is_split_scan() for x in self.snodes) + + @cache_on_self + def is_template(self) -> bool: + return any(x.is_template() for x in self.snodes) + + @cache_on_self + def get_template_node(self) -> ir.TemplateBuffer | None: + for node in self.snodes: + if node.is_template(): + return node.get_template_node() + return None + + def get_device(self) -> torch.device: + return self.group[0] + + @cache_on_self + def has_aliasing_or_mutation(self) -> bool: + return any(x.has_aliasing_or_mutation() for x in self.snodes) + + # None of these need to be implemented, as a FusedSchedulerNode is just an + # abstraction for scheduling purposes + def update_mutated_names(self, renames: dict[str, str]) -> None: + raise NotImplementedError + + def add_fake_dep(self, name: Dep) -> None: + raise NotImplementedError + + def can_inplace(self, read_dep: dependencies.Dep) -> bool: + raise NotImplementedError + + def debug_str(self) -> str: + """Longer form printout for trace logs""" + name = self.get_name() + node_typestr = ",".join(type(n).__name__ for n in self.snodes) + buf = IndentedBuffer() + buf.splice( + f"""\ +{name}: {type(self).__name__}({node_typestr}) +{name}.writes = {pformat(self.read_writes.writes)} +{name}.unmet_dependencies = {pformat(self.unmet_dependencies)} +{name}.met_dependencies = {pformat(self.read_writes.reads - self.unmet_dependencies)} +{name}.min_input_distance = {self.min_input_distance} +{name}.max_input_distance = {self.max_input_distance} +{name}.outputs = [ + """ + ) + with buf.indent(): + for out in self.get_outputs(): + buf.splice(out.debug_str()) + buf.writeline("]") + + try: + buf.splice(self.debug_str_extra()) + except Exception: + log.warning("Ignoring error in debug_str()", exc_info=True) + + return buf.getrawvalue().rstrip() + + @cache_on_self + def has_side_effects(self) -> bool: + if self.snodes is not None: + return any(node.has_side_effects() for node in self.snodes) + return super().has_side_effects() + + +class FusedMixOrderReductions(FusedSchedulerNode): + """Fused node for two reductions with different iteration orders (inner + outer).""" + + def __init__(self, node1: BaseSchedulerNode, node2: BaseSchedulerNode) -> None: + if not MixOrderReduction.is_contiguous_node(node1): + if not MixOrderReduction.is_contiguous_node(node2): + raise AssertionError("expected node2 to be a contiguous node") + node1, node2 = node2, node1 + + self.node1 = node1 + self.node2 = node2 + super().__init__( + node1.scheduler, list(node1.get_nodes()) + list(node2.get_nodes()) + ) + self.numel = MixOrderReduction.get_numel(self.node1) + + def sub_node_can_fuse( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + other_nodes: tuple[BaseSchedulerNode, ...], + ): + """ + node1 is from the current mix order reduction; node2 is another node we want to fuse in. + + other_nodes are passed in to check if fusion will introduce producer/consumer relationship + between the inner and outer reduction. If yes, we don't fuse. + """ + if isinstance(node1, FusedMixOrderReductions): + raise AssertionError("expected node1 to not be a FusedMixOrderReductions") + if isinstance(node2, FusedMixOrderReductions): + raise AssertionError("expected node2 to not be a FusedMixOrderReductions") + + # When we fuse extra nodes into a FusedMixOrderReductions node, + # we should not allow recursive mix-order reduction being + # created. + if not self.scheduler.can_fuse(node1, node2, allow_mix_order_reduction=False): + return False + + # Since node1 is from the current mix order reduction, if node1 is + # contiguous, the fused node should also be contiguous. + if MixOrderReduction.is_contiguous_node( + node1 + ) and not MixOrderReduction.is_contiguous_node(node2): + return False + + def _get_ancestors(nodes: tuple[BaseSchedulerNode, ...]) -> OrderedSet[str]: + out = OrderedSet() + return out.union(*(n.ancestors for n in nodes)) + + def _get_operation_names( + nodes: tuple[BaseSchedulerNode, ...], + ) -> OrderedSet[str]: + out = OrderedSet() + return out.union(*(n.get_operation_names() for n in nodes)) + + if other_nodes: + if (_get_ancestors((node1, node2)) & _get_operation_names(other_nodes)) or ( + _get_ancestors(other_nodes) & _get_operation_names((node1, node2)) + ): + return False + + return ( + not node2.is_reduction() + or self.scheduler.score_fusion_memory(node1, node2, count_bytes=False) + >= self.numel + ) + + def can_fuse_with(self, other: BaseSchedulerNode): + if self.has_strict_sum() or other.has_strict_sum(): + return False + # Limit tl.load() count in the fused RSPLIT loop to avoid register + # spills. See https://github.com/pytorch/pytorch/issues/179423 + max_reads = config.triton.mix_order_reduction_max_reads + if max_reads > 0: + all_reads: OrderedSet[str] = OrderedSet() + for sn in itertools.chain(self.get_nodes(), other.get_nodes()): + for dep in sn.read_writes.reads: + if isinstance(dep, MemoryDep): + all_reads.add(dep.name) + if len(all_reads) > max_reads: + # pyrefly: ignore [bad-assignment] + metrics.rejected_mix_order_reduction_fusion += 1 + return False + if not isinstance(other, FusedMixOrderReductions): + return self.sub_node_can_fuse( + self.node1, other, (self.node2,) + ) or self.sub_node_can_fuse(self.node2, other, (self.node1,)) + else: + # pass empty tuple for the second since the producer/consumer relationship has + # already been checked in the first call + return self.sub_node_can_fuse( + self.node1, other.node1, (self.node2, other.node2) + ) and self.sub_node_can_fuse(self.node2, other.node2, tuple()) + + def fuse_with(self, other: BaseSchedulerNode): + device = self.node1.get_device() + backend = self.scheduler.get_backend(device) + + if isinstance(other, FusedMixOrderReductions): + fused_node1 = backend.fuse(self.node1, other.node1) + fused_node2 = backend.fuse(self.node2, other.node2) + return FusedMixOrderReductions(fused_node1, fused_node2) + else: + if self.sub_node_can_fuse(self.node1, other, (self.node2,)): + fused_node = backend.fuse(self.node1, other) + return FusedMixOrderReductions(fused_node, self.node2) + else: + fused_node = backend.fuse(self.node2, other) + return FusedMixOrderReductions(self.node1, fused_node) + + +class FusedNestedReductions(FusedSchedulerNode): + """ + Fused node for two dependent reductions over the same logical elements. + The outer reduction owns the codegen grid; the grouped reduction is staged + inside that grid. + """ + + def __init__(self, node1: BaseSchedulerNode, node2: BaseSchedulerNode) -> None: + self.node1 = node1 + self.node2 = node2 + super().__init__( + node1.scheduler, list(node1.get_nodes()) + list(node2.get_nodes()) + ) + # Nested append fusion checks legality against node2, the grouped + # stage, while the fused node owns producers from both stages. Hide + # internal producer-consumer edges from later ancestor checks so reads + # from node1 are not mistaken for external intermediate deps. + self.ancestors -= self.get_operation_names() + grouped_node = node2 + _, (grouped_numel, grouped_rnumel) = grouped_node.group + grouped_reduction_info = NestedReduction._get_grouped_reduction_and_size( + grouped_node, grouped_rnumel + ) + if grouped_reduction_info is None: + raise AssertionError("expected grouped_reduction_info to be non-None") + grouped_reduction, exact_group_size = grouped_reduction_info + self.grouped_reduction: SchedulerNode = grouped_reduction + self.group_size: sympy.Integer = exact_group_size + _, (outer_numel, outer_rnumel) = node1.group + grouped_axis = NestedReduction.get_grouped_axis( + grouped_reduction, + outer_numel, + outer_rnumel, + exact_group_size, + outer_node=node1, + ) + if grouped_axis is None: + raise AssertionError("expected grouped_axis to be non-None") + self.grouped_axis: NestedReduction.GroupedAxis = grouped_axis + self.group_size_in_r: bool = self.grouped_axis is NestedReduction.GroupedAxis.R + iter_ranges, reduce_ranges = grouped_reduction.get_ranges() + self.domain_context: NestedReduction.PointwiseDomainContext = ( + NestedReduction.PointwiseDomainContext( + grouped_reduction=grouped_reduction, + grouped_numel=grouped_numel, + grouped_rnumel=grouped_rnumel, + local_reduction_domain=(*iter_ranges, *reduce_ranges), + parent_full_domain=(outer_numel, outer_rnumel), + ) + ) + + def can_fuse_with(self, other: BaseSchedulerNode, *, can_reorder: bool) -> bool: + """Allow downstream pointwise of the grouped reduction to fuse in. + + Consumers fused directly into the grouped reduction must run at either + reduced-output resolution or full parent-tile resolution. + """ + if other.is_reduction(): + return False + # fuse_with() appends into node2, the grouped stage. Pointwise nodes + # that do not consume that stage need a different insertion point. + if not (self.node2.get_operation_names() & other.ancestors): + return False + + pointwise_domains: ( + list[tuple[SchedulerNode, NestedReduction.PointwiseDomain]] | None + ) = NestedReduction._classify_grouped_pointwise_nodes( + self.domain_context, + other.get_nodes(), + ) + if pointwise_domains is None: + return False + if not NestedReduction._pointwise_domains_are_compatible( + self.domain_context, pointwise_domains + ): + return False + # Producers for the grouped reduction body need to be inserted before + # the reduction; this append-only path only accepts consumers. + if any( + domain is NestedReduction.PointwiseDomain.LOCAL_REDUCTION_INPUT + for _, domain in pointwise_domains + ): + return False + return self.scheduler._can_fuse_nested_reduction_append( + self.node2, + other, + pointwise_domains, + can_reorder=can_reorder, + ) + + def fuse_with(self, other: BaseSchedulerNode) -> FusedNestedReductions: + device = self.node2.get_device() + backend = self.scheduler.get_backend(device) + new_node2 = backend.fuse(self.node2, other) + return FusedNestedReductions(self.node1, new_node2) + + +class FusedExternTritonKernelSchedulerNode(FusedSchedulerNode): + def __init__( + self, + scheduler: Scheduler, + kernel_node: ExternKernelSchedulerNode, + fused_epilogue: SchedulerNode, + ) -> None: + if not isinstance(kernel_node.node, ir.UserDefinedTritonKernel): + raise AssertionError( + "expected kernel_node.node to be an ir.UserDefinedTritonKernel" + ) + snodes = typing.cast(list[BaseSchedulerNode], [kernel_node, fused_epilogue]) + super().__init__(scheduler, snodes) + self.kernel_node = kernel_node + self.fused_epilogue = fused_epilogue + self.min_order = self.kernel_node.min_order + self.outputs = fused_epilogue.outputs + + @classmethod + def epilogue_fuse( + cls, + node1: ExternKernelSchedulerNode, + node2: SchedulerNode, + ) -> FusedSchedulerNode: + if not isinstance(node1.node, ir.UserDefinedTritonKernel): + raise AssertionError( + "expected node1.node to be an ir.UserDefinedTritonKernel" + ) + scheduler = node1.scheduler + + if len(node1.node.mutation_outputs) != 1: + raise AssertionError( + f"expected one mutation output, got {len(node1.node.mutation_outputs)}" + ) + # pyrefly: ignore[bad-assignment] + mutated_name: str = node1.node.mutation_outputs[0].name + # Node1's mutated tensor becomes an intermediary tensor. + # Thus, remove node1 from the respective allocated buffer's users + # for `Scheduler.dead_node_elimination` to remove. + real_name = scheduler.mutation_real_name.get(mutated_name, mutated_name) + scheduler.name_to_buf[real_name].users.remove(NodeUser(node1)) + return cls(scheduler, node1, node2) + + def codegen(self, wrapper: PythonWrapperCodegen) -> None: + if not isinstance(self.fused_epilogue.node, ir.ComputedBuffer): + raise AssertionError( + "expected fused_epilogue.node to be an ir.ComputedBuffer" + ) + if not isinstance(self.kernel_node.node, ir.UserDefinedTritonKernel): + raise AssertionError( + "expected kernel_node.node to be an ir.UserDefinedTritonKernel" + ) + if not self.kernel_node.node.can_fuse_epilogue(): + raise AssertionError("expected kernel_node.node to allow epilogue fusion") + numel = math.prod(self.kernel_node.node.mutable_args[0].shape) + from torch._inductor.codegen.simd import SIMDScheduling + + tiling, _ = SIMDScheduling.get_tiling_and_scores([self.fused_epilogue], numel) + + from torch._inductor.codegen.simd_kernel_features import SIMDKernelFeatures + + kernel_features = SIMDKernelFeatures([self.fused_epilogue], numel) + + from torch._inductor.codegen.triton import FusedUserDefinedTritonKernel + + fused_user_kernel = FusedUserDefinedTritonKernel(tiling, kernel_features, self) + new_kernel_src = fused_user_kernel.codegen() + + return self.kernel_node.node.codegen_with_epilogue_fusion( + wrapper, (self.fused_epilogue.node, new_kernel_src) + ) + + def is_extern(self) -> bool: + return True + + def get_ranges(self) -> Sequence[Sequence[sympy.Expr]]: + return self.kernel_node.get_ranges() + + +class ForeachKernelSchedulerNode(FusedSchedulerNode): + """ + This is a schedular node that consists of a set of scheduler nodes that + has no data dependencies among them and can be executed in parallel. + """ + + def get_consumer_subnode_for( + self, producer: BaseSchedulerNode + ) -> BaseSchedulerNode | None: + for buf in producer.get_outputs(): + if buf.get_name() in self.read_to_node: + return self.read_to_node[buf.get_name()] + + return None + + def get_producer_subnode_for( + self, consumer: BaseSchedulerNode + ) -> BaseSchedulerNode | None: + producers = OrderedSet[BaseSchedulerNode]() + for rd in consumer.read_writes.reads: + if rd.name not in self.scheduler.name_to_buf: + continue + + node_name = self.scheduler.name_to_buf[rd.name].defining_op_name() + if node_name in self.name_to_node: + producers.add(self.name_to_node[node_name]) + + # Don't permit fusion if there are multiple subnodes + # that this consumer reads from + if len(producers) == 1: + return next(iter(producers)) + else: + return None + + @classmethod + def can_fuse(cls, producer: BaseSchedulerNode, consumer: BaseSchedulerNode) -> bool: + why = WhyNoFuse(producer, consumer) + if producer.is_foreach() and consumer.is_foreach(): + producer = typing.cast(ForeachKernelSchedulerNode, producer) + consumer = typing.cast(ForeachKernelSchedulerNode, consumer) + foreach_match = len(producer.snodes) == len(consumer.snodes) + if not foreach_match: + why("foreach do not have same length") + return foreach_match and all( + producer.scheduler.can_fuse(l, r) + for l, r in zip(producer.snodes, consumer.snodes) + ) + elif consumer.is_foreach(): + if producer.is_reduction(): + why( + "candidate producer is a reduction, foreach ops cannot be fused with reductions currently" + ) + return False + + consumer = typing.cast(ForeachKernelSchedulerNode, consumer) + consumer_subnode = consumer.get_consumer_subnode_for(producer) + if consumer_subnode is not None: + return consumer.scheduler.can_fuse(producer, consumer_subnode) + + why("candidate producer is not dep of any foreach consumer") + return False + + elif producer.is_foreach(): + if consumer.is_reduction(): + why( + "candidate consumer is a reduction, foreach ops cannot be fused with reductions currently" + ) + return False + + producer = typing.cast(ForeachKernelSchedulerNode, producer) + producer_subnode = producer.get_producer_subnode_for(consumer) + if producer_subnode is not None: + return producer.scheduler.can_fuse(producer_subnode, consumer) + + why("candidate consumer has no dep in any foreach producer") + return False + + raise AssertionError( + "At least one node passed to ForeachKernelSchedulerNode.can_fuse should be a foreach node" + ) + + @classmethod + def fuse( + cls, producer: BaseSchedulerNode, consumer: BaseSchedulerNode + ) -> ForeachKernelSchedulerNode: + if not (producer.is_foreach() or consumer.is_foreach()): + raise AssertionError("expected producer or consumer to be foreach") + if producer.is_foreach(): + producer = typing.cast(ForeachKernelSchedulerNode, producer) + use_custom_partition_algo = producer.use_custom_partition_algo + enable_autotune = producer.enable_autotune + else: + consumer = typing.cast(ForeachKernelSchedulerNode, consumer) + use_custom_partition_algo = consumer.use_custom_partition_algo + enable_autotune = consumer.enable_autotune + prev_node_1 = None + prev_node_2 = None + fused_nodes: list[BaseSchedulerNode] + if producer.is_foreach() and consumer.is_foreach(): + producer = typing.cast(ForeachKernelSchedulerNode, producer) + consumer = typing.cast(ForeachKernelSchedulerNode, consumer) + fused_nodes = [ + FusedSchedulerNode.fuse(l, r) + for l, r in zip(producer.snodes, consumer.snodes) + ] + elif producer.is_foreach(): + producer = typing.cast(ForeachKernelSchedulerNode, producer) + producer_subnode = producer.get_producer_subnode_for(consumer) + fused_nodes = [] + prev_node_1 = producer + prev_node_2 = None + for node in producer.snodes: + if node is producer_subnode: + new_node = FusedSchedulerNode.fuse(node, consumer) + prev_node_2 = new_node + fused_nodes.append(new_node) + else: + fused_nodes.append(node) + + elif consumer.is_foreach(): + consumer = typing.cast(ForeachKernelSchedulerNode, consumer) + consumer_subnode = consumer.get_consumer_subnode_for(producer) + fused_nodes = [] + prev_node_1 = consumer + prev_node_2 = None + + for node in consumer.snodes: + if node is consumer_subnode: + new_node = FusedSchedulerNode.fuse(producer, node) + prev_node_2 = new_node + fused_nodes.append(new_node) + else: + fused_nodes.append(node) + else: + raise AssertionError( + "At least one node passed to ForeachKernelSchedulerNode.fuse should be a foreach node" + ) + + return cls( + producer.scheduler, + fused_nodes, + use_custom_partition_algo=use_custom_partition_algo, + prev_node_1=prev_node_1, + prev_node_2=prev_node_2, + enable_autotune=enable_autotune, + ) + + def __init__( + self, + scheduler: Scheduler, + snodes: list[BaseSchedulerNode], + use_custom_partition_algo: bool, + prev_node_1: BaseSchedulerNode | None = None, + prev_node_2: BaseSchedulerNode | None = None, + enable_autotune: bool = False, + per_subkernel_blocks: bool = False, + ) -> None: + self.read_to_node = {} + self.name_to_node = {} + + if prev_node_1 is None or prev_node_2 is None: + super().__init__(scheduler, snodes) + + for node in snodes: + for read in node.read_writes.reads: + self.read_to_node[read.name] = node + + for name in node.get_operation_names(): + self.name_to_node[name] = node + else: + self.scheduler = scheduler + self.snodes = snodes + self.node = None + self.users: list[NodeUser] = [] + + self.set_read_writes( + dependencies.ReadWrites.merge_list( + [prev_node_1.read_writes, prev_node_2.read_writes] + ) + ) + + self.unmet_dependencies = ( + OrderedSet( + dep + for dep in OrderedSet.union( + prev_node_1.unmet_dependencies, prev_node_2.unmet_dependencies + ) + if dep.name not in self.get_buffer_names() + ) + - self.read_writes.writes + ) + + self.min_order = min([prev_node_1.min_order, prev_node_2.min_order]) + self.max_order = max([prev_node_1.max_order, prev_node_2.max_order]) + self.min_input_distance = min( + prev_node_1.min_input_distance, prev_node_2.min_input_distance + ) + self.max_input_distance = max( + prev_node_1.max_input_distance, prev_node_2.max_input_distance + ) + + if prev_node_1.is_foreach(): + if not isinstance(prev_node_1, ForeachKernelSchedulerNode): + raise AssertionError( + "expected prev_node_1 to be a ForeachKernelSchedulerNode" + ) + foreach_node, other_node = prev_node_1, prev_node_2 + else: + if not isinstance(prev_node_2, ForeachKernelSchedulerNode): + raise AssertionError( + "expected prev_node_2 to be a ForeachKernelSchedulerNode" + ) + foreach_node, other_node = prev_node_2, prev_node_1 + + self.ancestors = foreach_node.ancestors + self.ancestors.update(other_node.ancestors) + + self.name_to_node = foreach_node.name_to_node + for name in other_node.get_operation_names(): + self.name_to_node[name] = other_node + + self.outputs_by_name: dict[str, SchedulerBuffer] = { + k: v for snode in self.snodes for k, v in snode.outputs_by_name.items() + } + + self.use_custom_partition_algo = use_custom_partition_algo + device = snodes[0].get_device() + if not device: + raise AssertionError("expected device to be set") + self.group = (device, ((sympy.Expr("combo_kernel"),),)) + self.origins = OrderedSet[torch.fx.Node]() + self.enable_autotune = enable_autotune + self.per_subkernel_blocks = per_subkernel_blocks + + @classmethod + def combinable_nodes( + cls, nodes: list[BaseSchedulerNode] + ) -> list[BaseSchedulerNode]: + """Filter a node list down to combo-kernel candidates. + + Drops node kinds that can't or shouldn't share a combo kernel: + extern, grouped, mixed-order reduction, existing foreach, and + template nodes. + """ + extern = [x for x in nodes if isinstance(x, ExternKernelSchedulerNode)] + if extern: + log.debug( + "ComboKernels: %d external nodes are filtered %s", + len(extern), + [node.node.get_origins() for node in extern if node.node is not None], + ) + grouped = [x for x in nodes if isinstance(x, GroupedSchedulerNode)] + if grouped: + log.debug( + "ComboKernels: %d grouped nodes are filtered", + len(grouped), + ) + mix_order = [x for x in nodes if isinstance(x, FusedMixOrderReductions)] + if mix_order: + log.debug( + "ComboKernels: %d FusedMixOrderReductions nodes are filtered", + len(mix_order), + ) + nested_reductions = [x for x in nodes if isinstance(x, FusedNestedReductions)] + if nested_reductions: + log.debug( + "ComboKernels: %d FusedNestedReductions nodes are filtered", + len(nested_reductions), + ) + + filtered_nodes = [ + x + for x in nodes + if not isinstance( + x, + ( + NopKernelSchedulerNode, + ExternKernelSchedulerNode, + GroupedSchedulerNode, + FusedMixOrderReductions, + FusedNestedReductions, + ), + ) + ] + foreach_nodes = [ + x for x in filtered_nodes if isinstance(x, ForeachKernelSchedulerNode) + ] + if foreach_nodes: + log.debug("ComboKernels: %d foreach nodes are filtered", len(foreach_nodes)) + filtered_nodes = [ + x for x in filtered_nodes if not isinstance(x, ForeachKernelSchedulerNode) + ] + template_nodes = [x for x in filtered_nodes if x.is_template()] + if template_nodes: + log.debug( + "ComboKernels: %d template nodes are filtered: %s", + len(template_nodes), + template_nodes, + ) + filtered_nodes = [x for x in filtered_nodes if x not in template_nodes] + + # Keep strict sums standalone so their planned R0_BLOCK cannot change. + filtered_nodes = [node for node in filtered_nodes if not node.has_strict_sum()] + + # Filter out reduction nodes if combo_kernels_pointwise_only is enabled + if config.combo_kernels_pointwise_only: + reduction_nodes = [x for x in filtered_nodes if x.is_reduction()] + if reduction_nodes: + log.debug( + "ComboKernels: %d reduction nodes are filtered (pointwise_only mode)", + len(reduction_nodes), + ) + filtered_nodes = [x for x in filtered_nodes if not x.is_reduction()] + + # Synthetic benchmark inputs cannot preserve indirect-index constraints and may + # produce out-of-bounds indices. Keep these nodes out of benchmarked combos. + if config.benchmark_combo_kernel or ( + config.combo_kernels_autotune > 0 + and config.combo_kernel_per_subkernel_blocks + and config.combo_kernel_compile_time_autotune + ): + indirect_nodes = [ + n + for n in filtered_nodes + if any( + isinstance(dep, MemoryDep) and dep.is_indirect() + for dep in n.read_writes.reads_and_writes() + ) + ] + if indirect_nodes: + log.debug( + "ComboKernels: %d indirect-indexing nodes are filtered", + len(indirect_nodes), + ) + filtered_nodes = [n for n in filtered_nodes if n not in indirect_nodes] + + return filtered_nodes + + @staticmethod + def _default_group_nodes_for_combo_kernels( + scheduler: Scheduler, + ) -> list[list[BaseSchedulerNode]]: + """ + Returns a list of lists of nodes that are to be grouped together. + """ + sorted_nodes = scheduler._topological_sort_nodes() + grouped_nodes = [] + max_num_nodes = config.combo_kernel_max_num_nodes + + excluded_buffer_names: OrderedSet[str] = OrderedSet( + [ + buf_name + for group in sorted_nodes + for node in group + if isinstance(node, FusedMixOrderReductions) + for buf_name in node.get_buffer_names() + ] + ) + for nodes in sorted_nodes: + # Group nodes by device first to avoid mixed-device fusion + device_groups: dict[torch.device | None, list[BaseSchedulerNode]] = ( + defaultdict(list) + ) + for node in nodes: + device = node.get_device() + if device and (device.type == "mps" or device.type == "cpu"): + continue + + # exclude nodes that read from FusedMixOrderReductions output buffers' + if node.used_buffer_names() & excluded_buffer_names: + continue + device_groups[device].append(node) + + # Sub-group by stream and mempool to avoid mixing nodes across + # context boundaries. When a context is inactive every node maps to + # the default key so this is a no-op. + for device_nodes in device_groups.values(): + context_groups: dict[ + tuple[int, tuple[int, int] | None], list[BaseSchedulerNode] + ] = defaultdict(list) + for node in device_nodes: + context_groups[ + ( + scheduler.get_node_stream(node), + scheduler.node_to_mempool.get(node), + ) + ].append(node) + for context_nodes in context_groups.values(): + grouped_nodes.extend( + [ + context_nodes[i : i + max_num_nodes] + for i in range(0, len(context_nodes), max_num_nodes) + ] + ) + return grouped_nodes + + group_algorithm_for_combo_kernels: Callable[ + [Scheduler], list[list[BaseSchedulerNode]] + ] = _default_group_nodes_for_combo_kernels + + @staticmethod + def set_group_algorithm_for_combo_kernels( + custom_group_algorithm: Callable[[Scheduler], list[list[BaseSchedulerNode]]], + ) -> None: + ForeachKernelSchedulerNode.group_algorithm_for_combo_kernels = ( + custom_group_algorithm + ) + + @staticmethod + def group_nodes_for_combo_kernels( + scheduler: Scheduler, + ) -> list[list[BaseSchedulerNode]]: + return ForeachKernelSchedulerNode.group_algorithm_for_combo_kernels(scheduler) + + def mark_run(self) -> None: + raise NotImplementedError + + def codegen(self) -> None: + raise NotImplementedError + + def is_foreach(self) -> bool: + return True + + def get_subkernel_nodes(self) -> list[BaseSchedulerNode]: + """Returns a list of nodes which comprise the combo kernel. + These nodes may be vertically fused.""" + return list(self.snodes) + + def get_nodes(self) -> Sequence[BaseSchedulerNode]: + """Returns all nodes contained in this kernel, unpacking fused nodes + into their constituent scheduler nodes.""" + return list(itertools.chain.from_iterable(x.get_nodes() for x in self.snodes)) + + def get_first_name(self) -> str: + return self.snodes[0].get_first_name() + + def prune_redundant_deps( + self, name_to_fused_node: dict[str, BaseSchedulerNode] + ) -> None: + _prune_redundant_deps(self, name_to_fused_node, self.scheduler.name_to_buf) + + for node in self.snodes: + node.prune_redundant_deps(name_to_fused_node) + + +class GroupedSchedulerNode(BaseSchedulerNode): + """ + This is a "fake" scheduler node that represents a group of scheduler nodes + that are meant to be *grouped* together (it does not allow another node to be scheduled + in between its constituent nodes, nor does it allow another node to fuse into any of its constituent nodes). + The way it does this is by maintaining its unmet dependencies as the union of its constituent nodes. + Fusion will still happen among the nodes within each GroupedSchedulerNode. + At codegen time, this scheduler node will be unpacked and codegen is called on each constituent node. + """ + + snodes: list[BaseSchedulerNode] + + @classmethod + def create(cls, snodes: list[BaseSchedulerNode]) -> GroupedSchedulerNode: + scheduler = snodes[0].scheduler + if not all(node.scheduler is scheduler for node in snodes): + raise AssertionError("expected all nodes to share the same scheduler") + grouped_snode = cls(scheduler, snodes) + for snode in snodes: + scheduler.name_to_fused_node[snode.get_name()] = grouped_snode + scheduler.name_to_fused_node[grouped_snode.get_name()] = grouped_snode + return grouped_snode + + def __init__( + self, + scheduler: Scheduler, + snodes: list[BaseSchedulerNode], + temp_grouping: bool = False, + ) -> None: + super().__init__(scheduler) + init_group_node(self, scheduler, snodes) + # This flag is introduced for "temporary" grouping during some passes, + # Where nodes are grouped and moved together. + # After the pass those nodes are flattened. + # Reusing calculation of grouped unmed_dependencies etc. + # No fusion logic in this case. + self.temp_grouping = temp_grouping + + def unpack(self) -> list[BaseSchedulerNode]: + """ + Do fusion among nodes within this GroupedSchedulerNode, + and then unpack this GroupedSchedulerNode into regular nodes. + """ + if self.temp_grouping: + return self.snodes + + for snode in self.snodes: + self.scheduler.name_to_fused_node[snode.get_name()] = snode + del self.scheduler.name_to_fused_node[self.get_name()] + return self.scheduler.fuse_nodes(self.snodes) + + def add_fake_dep(self, fake_dep: Dep) -> None: + self.set_read_writes(self.read_writes.with_read(fake_dep)) + self.unmet_dependencies.add(fake_dep) + + @cache_on_self + def get_name(self) -> str: + return "_".join([x.get_name() for x in self.snodes]) + + def get_first_name(self) -> str: + return self.snodes[0].get_name() + + @cache_on_self + def get_buffer_names(self) -> OrderedSet[str]: + return OrderedSet.union(*[x.get_buffer_names() for x in self.snodes]) + + def get_outputs(self) -> list[SchedulerBuffer]: + result: list[SchedulerBuffer] = [] + for node in self.snodes: + result.extend(node.get_outputs()) + return result + + @cache_on_self + def estimate_flops(self) -> int | None: + # don't increment counters in fused methods so we don't double count + fps = list( + filter( + None, + ( + node.estimate_flops() + for node in self.get_nodes() + if node.is_template() or node.is_extern() + ), + ) + ) + if len(fps) == 0: + return None + ret = sum(fps) + return ret + + def get_nodes(self) -> Sequence[BaseSchedulerNode]: + return self.snodes + + def get_device(self) -> torch.device | None: + return self.snodes[0].get_device() if self.snodes else None + + @classmethod + def can_fuse(cls, producer: BaseSchedulerNode, consumer: BaseSchedulerNode) -> bool: + # GroupedSchedulerNode cannot be fused with another node + return False + + +def pick_loop_order( + stride_lengths: list[list[int]], + sizes: Sequence[sympy.Expr], + priority_idx: Sequence[int] = (), +) -> list[int]: + """ + A heuristic to decide loop iteration orders. This has not been well + tuned and may be something we should autotune. + """ + + @functools.cmp_to_key + def index_cmp(a: int, b: int) -> int: + if sizes[a] == 1 or sizes[b] == 1: + # 1-sizes don't matter, just move them to the end + return cmp(sizes[a] == 1, sizes[b] == 1) + + # Take abs, otherwise flipped dimensions are treated as smaller + # strides than contiguous dims + stride_len_a = [abs(sl[a]) for sl in stride_lengths] + stride_len_b = [abs(sl[b]) for sl in stride_lengths] + + # equivalent to + # np.logical_or(stride_lengths[:, b] == 0, stride_lengths[:, a] < stride_lengths[:, b]).all() + a_first = sum( + sl_b == 0 or sl_a < sl_b for sl_a, sl_b in zip(stride_len_a, stride_len_b) + ) + b_first = sum( + sl_a == 0 or sl_b < sl_a for sl_a, sl_b in zip(stride_len_a, stride_len_b) + ) + if a_first > b_first: + return -1 + if b_first > a_first: + return 1 + + # otherwise contiguous + return cmp(b, a) + + order = list(reversed(range(len(stride_lengths[0])))) + if len(priority_idx) > 0: + # if we have priority node, only use that node's order + stride_lengths = [stride_lengths[pi] for pi in priority_idx] + if config.pick_loop_orders: + order.sort(key=index_cmp) + return order + + +def _replace_operation_buffer( + orig_node: ir.MultiTemplateBuffer, new_node: ir.OperationBuffer +) -> None: + replaced_buf_name = new_node.get_name() + orig_buf_name = orig_node.get_name() + if not (isinstance(orig_buf_name, str) and isinstance(replaced_buf_name, str)): + raise AssertionError("expected orig_buf_name and replaced_buf_name to be str") + + replaced_op_name = new_node.get_operation_name() + orig_op_name = orig_node.get_operation_name() + if not (isinstance(orig_op_name, str) and isinstance(replaced_op_name, str)): + raise AssertionError("expected orig_op_name and replaced_op_name to be str") + + del V.graph.name_to_buffer[replaced_buf_name] + new_node.name = orig_buf_name + + del V.graph.name_to_op[replaced_op_name] + new_node.operation_name = orig_op_name + + orig = V.graph.buffers.index(orig_node) + V.graph.buffers.remove(new_node) + V.graph.buffers[orig] = new_node + V.graph.name_to_buffer[orig_buf_name] = new_node + + orig = V.graph.operations.index(orig_node) + V.graph.operations.remove(new_node) + V.graph.operations[orig] = new_node + V.graph.name_to_op[orig_op_name] = new_node + + +def _estimate_fused_epilogue_runtime(node1, node2, epilogue_runtime) -> float: + template_write_bytes = node1.get_write_buffer_sizes() + epilogue_read_bytes = node2.get_read_buffer_sizes() + extra_bytes = epilogue_read_bytes - template_write_bytes + # If no extra memory read by epilogue, assume epilogue is free + # if extra memory is read by epilogue, add to minimum choice + extra_bytes_ratio = extra_bytes / template_write_bytes + + # Smoothly approaches 1 as extra_bytes_ratio increases + extra_memory_ratio = extra_bytes_ratio / (1 + extra_bytes_ratio) + return extra_memory_ratio * epilogue_runtime + + +def _occupancy_before_and_after_fusion( + unfused_n_regs: int, + fused_n_regs: int, + fused_n_spills: int, + num_warps: int, + device_props: DeviceProperties, +) -> tuple[int, int]: + if fused_n_spills >= 8: + return 0, -1 + + # # Need device info to calculate occupancy + regs_per_sm = device_props.regs_per_multiprocessor + warp_size = device_props.warp_size + if regs_per_sm is None or warp_size is None: + return 1, 1 # Can't calculate, allow fusion + + if not num_warps: + raise AssertionError("expected num_warps to be truthy") + threads_per_block = num_warps * warp_size + + regs_per_block_unfused = unfused_n_regs * threads_per_block + regs_per_block_fused = fused_n_regs * threads_per_block + + blocks_unfused = regs_per_sm // regs_per_block_unfused + blocks_fused = regs_per_sm // regs_per_block_fused + + return blocks_unfused, blocks_fused + + +def _fuse_epilogue( + ms1: float, + ms2: float, + unfused_n_regs: int, + fused_n_regs: int, + fused_n_spills: int, + num_warps: int, + device_props: DeviceProperties, +) -> bool: + """ + Determine whether to fuse an epilogue into a GEMM template. + """ + MIN_ACCEPTED_OCCUPANCY = 4 + REGRESSED_OCCUPANCY_RATIO = 0.5 + + # Check occupancy impact + blocks_unfused, blocks_fused = _occupancy_before_and_after_fusion( + unfused_n_regs, fused_n_regs, fused_n_spills, num_warps, device_props + ) + + epilogue_dominated_with_sufficient_occupancy = ms2 > 2 * ms1 and blocks_fused > 1 + + # fuse if no major register spills + # Occupancy can decrease but if memory bound/epilogue dominated + # optimistically fuse + return blocks_fused != -1 and ( + blocks_fused >= MIN_ACCEPTED_OCCUPANCY + or blocks_fused / blocks_unfused > REGRESSED_OCCUPANCY_RATIO + or epilogue_dominated_with_sufficient_occupancy + ) + + +@dataclasses.dataclass +class NodeUser: + node: BaseSchedulerNode | OutputNode + can_inplace: bool = False + + # A weak user must be scheduled after a given node, but doesn't actually + # use the result + is_weak: bool = False + + def __hash__(self) -> int: + return hash((self.node.get_name(), self.can_inplace, self.is_weak)) + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, NodeUser) + and self.get_name() == other.get_name() + and self.can_inplace == other.can_inplace + and self.is_weak == other.is_weak + ) + + def get_name(self) -> str: + return self.node.get_name() + + def merge(self, other: NodeUser) -> NodeUser: + if self.node is not other.node: + raise AssertionError("expected self.node to be other.node") + return NodeUser( + self.node, + self.can_inplace and other.can_inplace, + self.is_weak and other.is_weak, + ) + + +_post_grad_graph_counter = itertools.count() + + +def get_layout_symints(node: ir.IRNode) -> OrderedSet[sympy.Symbol]: + """Get free symbols from a node's layout (size, stride, offset).""" + free_symbol_uses: OrderedSet[sympy.Symbol] = OrderedSet() + layout = node.maybe_get_layout() + if isinstance(layout, ir.Layout): + free_symbol_uses.update( + free_symbols(layout.size) + | free_symbols(layout.stride) + | free_symbols(layout.offset) + ) + if isinstance(layout, ir.MutationLayoutSHOULDREMOVE): + # symint may be used as index in layout.target + free_symbol_uses.update(get_layout_symints(layout.target)) + else: + if layout is not None: + raise AssertionError(f"Expect layout to be None but found layout={layout}") + return free_symbol_uses + + +def get_scheduler_node_symbol_uses( + node: BaseSchedulerNode, +) -> OrderedSet[sympy.Symbol]: + """ + Gets symbols used in a scheduler node, including free symbols from + the node's operations and layout symints from outputs. + """ + if isinstance(node, FusedSchedulerNode): + return OrderedSet().union( + *(get_scheduler_node_symbol_uses(snode) for snode in node.snodes) + ) + if node.node is None: + raise AssertionError("expected node.node to be set") + free_symbol_uses = node.node.get_free_symbol_uses() + free_symbol_uses.update( + *(get_layout_symints(ir_node) for ir_node in node.node.get_outputs()) + ) + return free_symbol_uses + + +def _is_epilogue_fusion_enabled(template_node: BaseSchedulerNode) -> bool: + """Check per-template flag, fall back to global config.""" + tb = template_node.get_template_node() + if tb is not None and tb.allow_epilogue_fusion is not None: + return tb.allow_epilogue_fusion + return config.epilogue_fusion + + +def _is_atomic_add_mutation_epilogue( + node: BaseSchedulerNode, *, check_config: bool = True +) -> bool: + if check_config and not config.epilogue_fusion_with_atomic_add: + return False + if not isinstance(node, SchedulerNode): + return False + if not isinstance(node.node, ir.ComputedBuffer): + return False + if not isinstance(node.node.data, ir.Scatter): + return False + if node.node.data.scatter_mode != "atomic_add": + return False + + outputs = node.get_outputs() + if len(outputs) != 1: + return False + if outputs[0].get_aliases() or len(outputs[0].get_mutations()) != 1: + return False + + writes = node.read_writes.writes + return bool(writes) and all( + isinstance(write, MemoryDep) and write.mode == "atomic_add" for write in writes + ) + + +def _can_fuse_atomic_add_template_epilogue( + template_node: BaseSchedulerNode, epilogue_node: BaseSchedulerNode +) -> bool: + template_buf = template_node.get_template_node() + return isinstance( + template_buf, ir.TritonTemplateBuffer + ) and _is_atomic_add_mutation_epilogue(epilogue_node) + + +def _is_prologue_fusion_enabled(template_node: BaseSchedulerNode) -> bool: + """Check per-template flag, fall back to global config.""" + tb = template_node.get_template_node() + if tb is not None and tb.allow_prologue_fusion is not None: + return tb.allow_prologue_fusion + return config.prologue_fusion + + +def is_epilogue_fusion(node1: BaseSchedulerNode, node2: BaseSchedulerNode): + return ( + node1.is_template() + and not node2.is_template() + and _is_epilogue_fusion_enabled(node1) + ) + + +def is_prologue_fusion(node1: BaseSchedulerNode, node2: BaseSchedulerNode): + return ( + node2.is_template() + and not node1.is_template() + and _is_prologue_fusion_enabled(node2) + ) + + +def is_template_fusion(node1: BaseSchedulerNode, node2: BaseSchedulerNode): + return is_epilogue_fusion(node1, node2) or is_prologue_fusion(node1, node2) + + +def template_fusion_pw_node(node1: BaseSchedulerNode, node2: BaseSchedulerNode): + return node2 if is_epilogue_fusion(node1, node2) else node1 + + +def _iter_loop_state_nodes( + nodes: Iterable[BaseSchedulerNode], +) -> Iterator[SchedulerNode | FusedSchedulerNode]: + for node in nodes: + if isinstance(node, FusedSchedulerNode): + yield from _iter_loop_state_nodes(node.snodes) + yield node + elif isinstance(node, SchedulerNode): + yield node + + +@dataclasses.dataclass +class _LoopStateSnapshot: + """Captured loop state for a set of scheduler nodes, restorable on rollback. + + Stores both SchedulerNode loop state (body, sizes, deps) and + FusedSchedulerNode group assignments, since the latter is reassigned + directly after child reindexing and has no mutation listener. + """ + + scheduler_node_states: dict[SchedulerNode, tuple[Any, ...]] = dataclasses.field( + default_factory=dict + ) + fused_node_groups: dict[FusedSchedulerNode, Any] = dataclasses.field( + default_factory=dict + ) + + @classmethod + def create(cls, nodes: tuple[BaseSchedulerNode, ...]) -> _LoopStateSnapshot: + """Capture scheduler-node boundaries and their mutable leaf loop state.""" + snapshot = cls() + for node in _iter_loop_state_nodes(nodes): + if isinstance(node, FusedSchedulerNode): + snapshot._snapshot_fused_node(node) + else: + snapshot._snapshot_scheduler_node(node) + return snapshot + + def _snapshot_scheduler_node(self, sn: SchedulerNode) -> None: + """Capture one leaf scheduler node before its first loop mutation.""" + if sn in self.scheduler_node_states: + raise AssertionError(f"scheduler node {sn} already snapshotted") + self.scheduler_node_states[sn] = sn.snapshot_loop_state() + + def _snapshot_fused_node(self, node: FusedSchedulerNode) -> None: + """Capture fused-node group metadata changed outside leaf listeners.""" + if node in self.fused_node_groups: + raise AssertionError(f"fused node {node} already snapshotted") + self.fused_node_groups[node] = node.group + + def restore(self) -> None: + """Restore all captured loop state and fused-node group metadata.""" + for sn, state in self.scheduler_node_states.items(): + sn.restore_loop_state(state) + for node, group in self.fused_node_groups.items(): + node.group = group + refresh_group_node_dependencies(node) + + +@dataclasses.dataclass +class _LoopMutationTracker: + """Rollback scope for speculative loop mutations during can_fuse(). + + can_fuse() may speculatively reorder or reindex loops while evaluating + whether a fusion is legal. If the final decision rejects the fusion, + this tracker restores the original loop structure so later fusion + candidates do not inherit a speculative layout chosen for a fusion + that did not happen. + + Recursive can_fuse() calls chain their listeners so each scope captures its + own decision boundary while the outer scope still sees nested mutations. + + Use finish(rollback=False) to keep mutations or finish(rollback=True) to + restore the original state. If no mutation occurred, finish() is a no-op. + """ + + nodes: tuple[BaseSchedulerNode, ...] + watched_nodes: OrderedSet[SchedulerNode] = dataclasses.field( + default_factory=OrderedSet + ) + previous_listeners: dict[SchedulerNode, Callable[[SchedulerNode], None] | None] = ( + dataclasses.field(default_factory=dict) + ) + state: _LoopStateSnapshot | None = None + + @classmethod + def create(cls, nodes: tuple[BaseSchedulerNode, ...]) -> _LoopMutationTracker: + """Create a rollback scope and watch mutable leaf scheduler nodes.""" + seen = OrderedSet(nodes) + tracker = cls(nodes=tuple(seen)) + for node in _iter_loop_state_nodes(seen): + if isinstance(node, SchedulerNode): + tracker.watch(node) + return tracker + + def watch(self, sn: SchedulerNode) -> None: + """Install this scope as the mutation listener for a leaf node.""" + if sn in self.watched_nodes: + return + self.previous_listeners[sn] = sn._loop_mutation_listener + self.watched_nodes.add(sn) + sn._loop_mutation_listener = self.track + + def track(self, sn: SchedulerNode) -> None: + """Lazily snapshot candidate roots when the first mutation occurs.""" + if sn not in self.watched_nodes: + raise AssertionError(f"scheduler node {sn} is not being watched") + if previous := self.previous_listeners[sn]: + previous(sn) + if self.state is not None: + # Keep the original pre-mutation snapshot for the whole scope. + return + + # The listener tells us a child loop mutated. Snapshot the original + # candidate roots here so we also capture fused-node group state, + # which is reassigned directly and has no listener of its own. + self.state = _LoopStateSnapshot.create(self.nodes) + + def finish(self, *, rollback: bool) -> None: + """Detach listeners and restore captured state if rolling back.""" + for sn in self.watched_nodes: + sn._loop_mutation_listener = self.previous_listeners[sn] + if not rollback or self.state is None: + return + self.state.restore() + + +# Distinguishes "not cached" from a cached None in _tiling_memory_cache. +_TILING_MEMORY_MISS = object() + + +class Scheduler: + """ + A Scheduler is a graph of BaseSchedulerNodes. It is responsible for + optimizations such as fusion, reorder, and graph partition. + """ + + def __init__(self, nodes: list[ir.Operation]) -> None: + with dynamo_timed("Scheduler.__init__"): + self._init(nodes) + + @staticmethod + def count_kernel_nodes(nodes: Sequence[BaseSchedulerNode]) -> int: + return sum(1 for node in nodes if not isinstance(node, NopKernelSchedulerNode)) + + def _init(self, nodes: list[ir.Operation]) -> None: + self._tiling_memory_cache: dict[tuple[Any, ...], Any] = {} + super().__init__() + V.graph.scheduler = self + self.backends: dict[torch.device, BaseScheduling] = {} + self.post_grad_graph_id = next(_post_grad_graph_counter) + self._graph_partition_counter = itertools.count() + self.completed_operations: OrderedSet[str] = OrderedSet() + self.available_buffer_names = OrderedSet( + [ + *V.graph.graph_inputs.keys(), + *V.graph.constants.keys(), + *V.graph.torchbind_constants.keys(), + ] + ) + self.nodes = [self.create_scheduler_node(n) for n in nodes] + self.previous_node: BaseSchedulerNode | None = None + self.current_node: BaseSchedulerNode | None = None + self.update_zero_dim_cpu_tensor() + # some new constants could have been created above + self.available_buffer_names.update(V.graph.constants.keys()) + for node in self.nodes: + node.prune_deps() + + # See [Note: Graph Partition Device Contexts] + self.default_device_context: torch.device | None = None + + self.name_to_donated_buffer: dict[str, SchedulerDonatedBuffer] = ( + self.get_donated_buffers() + ) + self.name_to_node: dict[str, BaseSchedulerNode] = { + n.get_name(): n for n in self.nodes + } + + self.name_to_buf: dict[str, SchedulerBuffer] = { + buf.get_name(): buf for node in self.nodes for buf in node.get_outputs() + } + self.name_to_fused_node: dict[str, BaseSchedulerNode] = self.name_to_node.copy() + + # mutation_real_name: Maps back to the original name for codegen + # Example: + # If you mutate buf0 inside of buf1's kernel, then: + # mutation_real_name = {"buf0" : "buf1"} + # all subsequent uses of buf0 become buf1's usage in dependency graph + self.mutation_real_name: dict[str, str] = {} + + # We handle mutation by renaming modified versions of the same + # buffer in the dependency graph to prevent cycles. + # mutation_renames: tracks the current name for a given buffer + # (changed once per mutation) + # Example: + # If you mutate buf0 inside of buf1's kernel, then: + # mutation_renames = {"buf1" : "buf0"} + # in codegen we only use buf0, never buf1 + self.mutation_renames: dict[str, str] = {} + + self.seen_template_fusions: OrderedSet[ + tuple[BaseSchedulerNode, BaseSchedulerNode] + ] = OrderedSet() + # Must run first to correctly set dependencies, before all other passes that rely on + # reading from .read_writes.reads or .unmet_dependencies + self.nodes = comms.decide_global_ordering_of_comms( + self.nodes, + self.name_to_buf, + self.name_to_fused_node, + ) + + self.compute_dependencies() + self.nodes = self.topological_sort_schedule(self.nodes) + self.dead_node_elimination() + self.name_to_fused_node = {n.get_name(): n for n in self.nodes} + self.compute_ancestors() + self.compute_input_distances() + + # pyrefly: ignore [bad-assignment] + metrics.ir_nodes_pre_fusion += len(self.nodes) + from torch._inductor.debug import log_ir_post_fusion, log_ir_pre_fusion + + log_ir_pre_fusion(self.nodes) + self.num_orig_nodes = len(self.nodes) + self.create_foreach_nodes() + self.nodes = self.topological_sort_schedule(self.nodes) + self.logged_slow_fusion = OrderedSet[tuple[str, str]]() + if config._pre_fusion_custom_pass is not None: + self.nodes = config._pre_fusion_custom_pass(self.nodes) + + # Distributed autotune can replace MultiTemplateBuffer nodes before the + # normal mempool assignment pass runs. Initialize these maps now so + # replacement can preserve any IR-level mempool metadata it sees. + self.node_to_mempool: dict[BaseSchedulerNode, tuple[int, int] | None] = {} + self.buff_to_mempool: dict[str, tuple[int, int] | None] = {} + self._mempool_nodes: bool = False + + if config.distributed_max_autotune_gemm: + from . import distributed_autotune + + distributed_autotune.schedule(self) + self.compute_ancestors() + + # Stream assignments must be populated BEFORE fusion + # to prevent fusing nodes across stream boundaries + self.node_to_stream: dict[BaseSchedulerNode, int] = {} + self.buff_to_stream: dict[str, int] = {} + self._multi_stream_nodes: bool = False + # Maps stream_idx → user_object_index for retrieving user stream objects + self.stream_idx_to_user_obj_idx: dict[int, int] = {} + self.user_obj_idx_to_stream_idx: dict[int, int] = {} + self._populate_stream_assignments() + self._populate_mempool_assignments() + + self.nodes = self.fuse_nodes(self.nodes) + if config._post_fusion_custom_pass is not None: + self.nodes = config._post_fusion_custom_pass(self.nodes) + + if any( + isinstance(node, FusedExternTritonKernelSchedulerNode) + for node in self.nodes + ): + # if a user triton kernel has been epilogue-fused, + # there is likely an opportunity to prune an NopKernel + # (which is originally used to generate the buffer which the triton kernel writes to) + self.dead_node_elimination() + + self.merge_loops() + self.finalize_multi_template_buffers() + if ( + config.max_autotune_gemm or config.max_autotune + ) and use_pipelined_autotuning(): + torch._inductor.select_algorithm.PrecompileThreadPool.shutdown_instance() + + # torch.cond and torch.switch can contain arbitrary subgraphs with collectives; + # reordering them can cause an nccl hang. + self._enforce_switch_ordering() + + # Peak memory pass and overlap pass must run last, otherwise + # other reordering passes could undo their effects. + if config.reorder_for_peak_memory: + from .memory import reorder_for_peak_memory + + self.nodes = reorder_for_peak_memory( + self.nodes, + self.name_to_buf, + self.name_to_fused_node, + OrderedSet(V.graph.graph_inputs.keys()), + OrderedSet(V.graph.get_output_names()), + ) + + if config.combo_kernels: + with dynamo_timed( + "Scheduler.create_combo_kernel_nodes", + log_pt2_compile_event=True, + log_waitcounter=True, + ): + self.create_combo_kernel_nodes(num_ck_nodes=None) + from .memory import assign_memory_planning_info_for_scheduler_buffers + + assign_memory_planning_info_for_scheduler_buffers( + self.nodes, self.name_to_buf + ) + + # reorder_for_compute_comm_overlap may do benchmarking to estimate + # op runtime. Disable it for now in deterministic mode. + if not config.deterministic and config.reorder_for_compute_comm_overlap: + if not config.reorder_for_peak_memory: + from .memory import assign_memory_planning_info_for_scheduler_buffers + + assign_memory_planning_info_for_scheduler_buffers( + self.nodes, self.name_to_buf + ) + + if config_comms.runtime_estimations_align_across_all_distributed_ranks: + has_collectives = False + for node in self.nodes: + if is_collective(node.node): + has_collectives = True + break + if has_collectives: + from .comms import ( + align_runtime_estimations_across_all_distributed_ranks, + ) + + align_runtime_estimations_across_all_distributed_ranks(self.nodes) + + # pyrefly: ignore [unbound-name] + if config_comms.reorder_sink_verbose_logging: + from torch._logging import trace_structured + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "scheduler_nodes_before_comm_overlap", + "encoding": "string", + }, + payload_fn=lambda: "\n\n".join( + [ + f"snode[{i}]" + + n.debug_str() + + f" buffer_names:{n.get_buffer_names()}" + for i, n in enumerate(self.nodes) + ] + ), + ) + self.nodes = comms.reorder_compute_and_comm_for_overlap(self.nodes) + + if config.aten_distributed_optimizations.enable_simple_overlap: + if ( + not config.reorder_for_peak_memory + and not config.reorder_for_compute_comm_overlap + ): + from .memory import assign_memory_planning_info_for_scheduler_buffers + + assign_memory_planning_info_for_scheduler_buffers( + self.nodes, self.name_to_buf + ) + with dynamo_timed( + "Scheduler.simple_overlap", + log_pt2_compile_event=True, + log_waitcounter=True, + ): + self.nodes = comms.simple_overlap(self.nodes) + + self.process_grouped_nodes() + + if ( + # pyrefly: ignore[unbound-name] + config.graph_partition + # pyrefly: ignore[unbound-name] + and config.triton.cudagraphs + # pyrefly: ignore[unbound-name] + and config.triton.reorder_for_reducing_graph_partitions + ): + self.nodes = self.maybe_reorder_for_minimizing_partition(self.nodes) + self.nodes = self.reorder_for_partition_with_simple_dependency(self.nodes) + + self.compute_last_usage() + + if torch._inductor.config.test_configs.track_memory_lifecycle: + self.insert_memory_check_nodes() + + log_ir_post_fusion(self.nodes) + # pyrefly: ignore[unbound-name] + V.debug.graph_diagram(self.nodes) + self.debug_draw_graph() + + # used during codegen: + self.buffer_names_to_free: OrderedSet[str] = OrderedSet() + + # fx graph node to the position it appears in the graph + # for debug attribution + self.origin_to_index: dict[torch.fx.Node, int] = {} + + # The only source of which stream context we are currently in during the codegen phase. + self._current_stream_ctx: EnterCudaStreamContextLine | None = None + + get_metric_table("graph_stats").add_row( + lambda: { + "graph_id": self.post_grad_graph_id, + "num_nodes_before_fusion": self.num_orig_nodes, + "num_nodes_after_fusion": len(self.nodes), + } + ) + + # Unlike V.graph.removed_buffers, the op recorded here is removed but + # we still need the buffer (generated in alternative ways) + self.removed_ops: OrderedSet[str] = OrderedSet() + + def get_donated_buffers(self) -> dict[str, SchedulerDonatedBuffer]: + name_to_donated_buf = {} + for name in V.graph.graph_inputs_original: + if isinstance(V.graph.graph_inputs_original[name], ir.DonatedBuffer): + name_to_donated_buf[name] = SchedulerDonatedBuffer( + self, + V.graph.graph_inputs_original[name], + defining_op=None, + ) + return name_to_donated_buf + + def _populate_stream_assignments(self) -> None: + """Populate node_to_stream and buff_to_stream from IR node stream_idx. + + Reads the stream_idx field set on IR nodes during lowering to determine + which stream each scheduler node should run on. This field is propagated + from 'custom.stream' FX node metadata via IRNode.current_stream_idx(). + """ + from .stream_constants import DEFAULT_STREAM_IDX + + for node in self.nodes: + stream_idx = DEFAULT_STREAM_IDX + + if node.node is not None: + user_obj_idx = node.node.get_stream_idx() + if user_obj_idx is not None: + stream_idx = self._get_or_create_stream_idx_for_user_obj( + user_obj_idx + ) + + self.node_to_stream[node] = stream_idx + + # Also populate buff_to_stream for all buffers produced by this node. + # Mutation renames are resolved at lookup time via get_buf_stream. + for buf in node.get_buffer_names(): + self.buff_to_stream[buf] = stream_idx + + # Propagate a device to device-less nodes (e.g. record_event, + # wait_event) so they naturally enter the device guard in the + # main codegen loop instead of requiring special-case handling. + if any(s != DEFAULT_STREAM_IDX for s in self.node_to_stream.values()): + device = next( + (n.get_device() for n in self.nodes if n.get_device() is not None), None + ) + if device is not None: + for node in self.nodes: + ir_node = node.node + if ( + node.get_device() is None + and isinstance(ir_node, ir.Buffer) + and isinstance(ir_node.layout, ir.NoneLayout) + ): + # pyrefly: ignore [bad-assignment] + ir_node.layout = ir.NoneLayout(device=device) + + # Check if we have any nodes on non-default streams + self._multi_stream_nodes = any( + stream_idx != DEFAULT_STREAM_IDX + for stream_idx in self.node_to_stream.values() + ) + + def _get_or_create_stream_idx_for_user_obj(self, user_obj_idx: int) -> int: + stream_idx = self.user_obj_idx_to_stream_idx.get(user_obj_idx) + if stream_idx is None: + # 0 is reserved for the default stream. + stream_idx = len(self.user_obj_idx_to_stream_idx) + 1 + self.user_obj_idx_to_stream_idx[user_obj_idx] = stream_idx + self.stream_idx_to_user_obj_idx[stream_idx] = user_obj_idx + return stream_idx + + def get_node_stream(self, node: BaseSchedulerNode) -> int: + from .stream_constants import DEFAULT_STREAM_IDX + + if node in self.node_to_stream: + return self.node_to_stream[node] + + child_streams = OrderedSet( + self.get_node_stream(child) + for child in node.get_nodes() + if child is not node + ) + if len(child_streams) == 1: + stream_idx = next(iter(child_streams)) + elif len(child_streams) > 1: + raise AssertionError( + f"Scheduler node {node.get_name()} combines multiple streams: " + f"{list(child_streams)}" + ) + elif ( + node.node is not None + and (user_obj_idx := node.node.get_stream_idx()) is not None + ): + stream_idx = self._get_or_create_stream_idx_for_user_obj(user_obj_idx) + else: + buffer_streams = OrderedSet( + self.buff_to_stream[buf_name] + for buf_name in node.get_buffer_names() + if buf_name in self.buff_to_stream + ) + if len(buffer_streams) > 1: + raise AssertionError( + f"Scheduler node {node.get_name()} has outputs on multiple " + f"streams: {list(buffer_streams)}" + ) + stream_idx = ( + next(iter(buffer_streams)) if buffer_streams else DEFAULT_STREAM_IDX + ) + + self.node_to_stream[node] = stream_idx + if stream_idx != DEFAULT_STREAM_IDX: + self._multi_stream_nodes = True + for buf_name in node.get_buffer_names(): + self.buff_to_stream.setdefault(buf_name, stream_idx) + return stream_idx + + def _has_multi_stream_nodes(self) -> bool: + """Check if any nodes are assigned to non-default streams.""" + return self._multi_stream_nodes + + def _populate_mempool_assignments(self) -> None: + """Populate node_to_mempool and buff_to_mempool from IR node metadata.""" + self.node_to_mempool.clear() + self.buff_to_mempool.clear() + for node in self.nodes: + mempool = self._get_node_mempool(node) + self.node_to_mempool[node] = mempool + + # Also populate buff_to_mempool for all buffers produced by this node. + # Mutation renames are resolved at lookup time via get_buf_mempool. + for buf in node.get_buffer_names(): + self.buff_to_mempool[buf] = mempool + + self._mempool_nodes = any( + mempool is not None for mempool in self.node_to_mempool.values() + ) + + def _has_mempool_nodes(self) -> bool: + """Check if any nodes are assigned to a user CUDA MemPool.""" + return self._mempool_nodes + + def _get_node_mempool(self, node: BaseSchedulerNode) -> tuple[int, int] | None: + """Return the CUDA MemPool assigned to a scheduler node. + + Grouped scheduler nodes such as ForeachKernelSchedulerNode have + node.node == None, so derive their context from the underlying nodes. + """ + if node.node is not None: + return node.node.get_mempool() + + mempools = OrderedSet( + self._get_node_mempool(subnode) + for subnode in node.get_nodes() + if subnode is not node + ) + if not mempools: + return None + if len(mempools) != 1: + raise AssertionError( + f"Scheduler node {node.get_name()} contains mixed CUDA MemPool " + f"contexts: {list(mempools)}" + ) + return next(iter(mempools)) + + def get_buf_stream(self, buf_name: str) -> int: + """Return the stream index for a buffer, resolving mutation renames.""" + real = self.mutation_renames.get(buf_name, buf_name) + return self.buff_to_stream.get(real, self.buff_to_stream.get(buf_name, 0)) + + def get_buf_mempool(self, buf_name: str) -> tuple[int, int] | None: + """Return the CUDA MemPool for a buffer, resolving mutation renames.""" + real = self.mutation_renames.get(buf_name, buf_name) + return self.buff_to_mempool.get(real, self.buff_to_mempool.get(buf_name, None)) + + def has_cross_stream_hazard(self, buf_name: str, node: BaseSchedulerNode) -> bool: + """True if buf_name was produced on a different stream than node. + + Resolves mutation renames so that mutated buffers inherit the + stream of their original definition. + """ + if not self._has_multi_stream_nodes(): + return False + return self.get_buf_stream(buf_name) != self.get_node_stream(node) + + @property + def current_device(self) -> torch.device | None: + return V.graph.current_device + + @current_device.setter + def current_device(self, device: torch.device | None) -> None: + V.graph.current_device = device + + def debug_draw_graph(self) -> None: + """Generate an image of the graph for debugging""" + if os.environ.get("INDUCTOR_WRITE_SCHEDULER_GRAPH", None) == "1": + from .debug import draw_buffers + + draw_buffers(self.nodes, print_graph=True) + + def debug_print_nodes(self, label: str) -> None: + if log.isEnabledFor(logging.INFO): + log.info("%s:", label) + for node in self.nodes: + node.log_details() + + def create_scheduler_node(self, node: ir.Operation) -> BaseSchedulerNode: + if node.get_origins() is None: + raise AssertionError("All nodes passed to scheduling must have an origin") + if node.is_no_op(): + return NopKernelSchedulerNode(self, node) + elif isinstance(node, (ir.ComputedBuffer, ir.TemplateBuffer)): + return SchedulerNode(self, node) + elif isinstance(node, ir.ExternKernel): + return ExternKernelSchedulerNode(self, node) + else: + raise NotImplementedError(node) + + def create_foreach_nodes(self) -> None: + removed_node_names: OrderedSet[str] = OrderedSet() + fe_nodes = [] + kept_node_names = self.name_to_fused_node.keys() + + for names in V.graph.lists.values(): + names = [ + name + for name in names + if name in kept_node_names + and not isinstance(self.name_to_node[name], NopKernelSchedulerNode) + ] + if not names: + # All nodes eliminated + continue + + removed_node_names.update(names) + snodes = [self.name_to_node[name] for name in names] + + enable_autotune = config.combo_kernels_autotune > 1 + fe_node = ForeachKernelSchedulerNode( + self, + snodes, + use_custom_partition_algo=False, + enable_autotune=enable_autotune, + ) + + fe_nodes.append(fe_node) + + for name in names: + self.name_to_fused_node[name] = fe_node + + self.nodes = [ + node for node in self.nodes if node.get_name() not in removed_node_names + ] + list(fe_nodes) + + def compute_dependencies(self) -> None: + """ + Create dependency edges between nodes, handling aliasing and + mutation properly. + """ + + class DedupList(Generic[_T]): + """ + This data structure behaves like a list except it makes sure the + elements remain unique. + Normally one could use a OrderedSet/dict for this purpose however + the list in question gets elements appended as it is being + iterated over which means that we need to keep the list + semantics. + """ + + def __init__( + self, + items: list[_T] | None = None, + membership: OrderedSet[_T] | None = None, + ) -> None: + self.items = items or [] + self.membership = membership or OrderedSet() + + def append(self, node_user: _T) -> None: + if node_user in self.membership: + return + self.items.append(node_user) + self.membership.add(node_user) + + def __add__(self, other: DedupList[_T]) -> DedupList[_T]: + new_membership = OrderedSet.union(self.membership, other.membership) + new_items = self.items + [ + x for x in other.items if x not in self.membership + ] + return DedupList(new_items, new_membership) + + # pyrefly: ignore [not-a-type] + name_to_users: defaultdict[str, DedupList[NodeUser]] = collections.defaultdict( + DedupList + ) + + # handle aliasing by using python aliasing in name_to_users + # if foo aliases bar then we will make name_to_users["foo"] point + # to the same python list as name_to_users["bar"] + for node in self.nodes: + for buf1 in node.get_outputs(): + buf1_name = buf1.get_name() + # This is for handling auto functionized ops which return None + # and mutate more than 1 inputs, we shouldn't let them all + # point to the same user list since buffers in the aliases + # list might not be alias to each other. + if ( + isinstance(buf1.node.layout, ir.NoneLayout) + and len(buf1.get_aliases()) > 1 + ): + continue + for buf2_name in buf1.get_aliases(): + if buf1_name in name_to_users and buf2_name in name_to_users: + # merge the two + list1 = name_to_users[buf1_name] + list2 = name_to_users[buf2_name] + combined = list1 + list2 + for key in name_to_users: + if ( + name_to_users[key] is list1 + or name_to_users[key] is list2 + ): + name_to_users[key] = combined + elif buf1_name in name_to_users: + name_to_users[buf2_name] = name_to_users[buf1_name] + else: + name_to_users[buf1_name] = name_to_users[buf2_name] + + # pyrefly: ignore [not-a-type] + def rename(n: str) -> str: + if n in self.mutation_renames: + return rename(self.mutation_renames[n]) + return n + + def add_user( + # pyrefly: ignore [not-a-type] + used_by_name: str, + user_node: BaseSchedulerNode | OutputNode, + can_inplace: bool = False, + is_weak: bool = False, + ) -> None: + name_to_users[rename(used_by_name)].append( + NodeUser(user_node, can_inplace, is_weak) + ) + + # pyrefly: ignore [not-a-type, unsupported-operation] + unbacked_symbol_to_origin_node: dict[sympy.Symbol, str | None] = {} + + # NB: None means that the dependency is on an input. Don't actually + # generate a dependency because if we do, Inductor will start trying + # to free the unbacked int but that's pointless + for val in V.graph.graph_inputs.values(): + if isinstance(val, sympy.Expr): + for fs in val.free_symbols: + unbacked_symbol_to_origin_node[fs] = None + elif isinstance(val, ir.TensorBox): + # We also need to add symbols from input size as well because + # AOTI doesn't lift the unbacked symints to inputs + sym_size = [s for s in val.get_size() if isinstance(s, sympy.Expr)] + for s in sym_size: + for fs in s.free_symbols: + unbacked_symbol_to_origin_node[fs] = None + + has_non_input_unbacked_defs = False + for node in self.nodes: + if node.node is None: + raise AssertionError("expected node.node to be set") + # unbacked symbols don't follow ordinary buffer dependencies, so + # we track their def/uses separately + unbacked_symbol_defs = sorted( + node.node.get_unbacked_symbol_defs(), key=lambda x: x.name + ) + for s in unbacked_symbol_defs: + if not isinstance(s, sympy.Symbol): + raise AssertionError("expected s to be a sympy.Symbol") + # Pick the first definer as canonical. There may be multiple + # because if a MultiOutputLayout buffer propagates an unbacked + # symint to multiple outputs, they will all claim to def it. + has_non_input_unbacked_defs = True + if s not in unbacked_symbol_to_origin_node: + unbacked_symbol_to_origin_node[s] = node.get_name() + + for node in self.nodes: + log.debug("scheduling %s", node.node) + + if has_non_input_unbacked_defs: + if node.node is None: + raise AssertionError("expected node.node to be set") + + unbacked_symbol_uses = sorted( + node.node.get_free_symbol_uses(unbacked_only=True), + key=lambda x: x.name, + ) + # if a kernel takes unbacked symints, register dependencies + for s in unbacked_symbol_uses: + if s not in unbacked_symbol_to_origin_node: + raise AssertionError( + f"{s} not in {unbacked_symbol_to_origin_node}" + ) + if (r := unbacked_symbol_to_origin_node[s]) is not None: + for buf in self.name_to_node[r].get_outputs(): + node.add_fake_dep(StarDep(buf.get_name())) + + if ( + len(node.read_writes.writes) == 1 + and (dep := next(iter(node.read_writes.writes))) + and isinstance(dep, MemoryDep) + ): + node_mode = dep.mode + else: + node_mode = None + + # Handle output mutations + for buf in node.get_outputs(): + # a node will mutate either 0 or 1 buffers + if len(buf.get_mutations()) > 1: + raise AssertionError( + f"expected at most one mutation, got {len(buf.get_mutations())}" + ) + for alt_name in buf.get_mutations(): + alt_name = rename(alt_name) + is_ordering_only = buf.is_ordering_only() + if is_ordering_only: + add_user(alt_name, node, is_weak=True) + node.add_fake_dep( + WeakDep(alt_name, mutating_buf=buf.get_name(), is_fake=True) + ) + continue + # this node must run after the prior writer + add_user(alt_name, node) + node.add_fake_dep(StarDep(alt_name, mode=node_mode)) + for user in name_to_users[alt_name].items: + if user.get_name() == node.get_name(): + continue + + if not isinstance(user.node, BaseSchedulerNode): + raise AssertionError( + "expected user.node to be a BaseSchedulerNode" + ) + for out_buf in user.node.get_outputs(): + other_name = out_buf.get_name() + # this node must run after all prior readers + other_name = rename(other_name) + # Check if the prior reader is a true alias (view) vs a clone. + # Views share underlying storage with the mutated buffer, so we + # need a real dependency (is_fake=False) to keep the view's + # buffer alive until after this mutation completes. Clones have + # independent storage, so we only need an ordering dependency + # (is_fake=True) that won't extend their buffer lifetime. + is_alias = alt_name in out_buf.get_aliases() + node.add_fake_dep( + WeakDep( + other_name, + mutating_buf=buf.get_name(), + is_fake=not is_alias, + ) + ) + add_user(other_name, node, is_weak=True) + + for add_dep in V.graph.additional_buffer_deps[node.get_name()]: + add_user(add_dep, node, is_weak=True) + # is_fake=True because these are control dependencies for ordering only, + # they should not extend buffer lifetimes + node.add_fake_dep(WeakDep(add_dep, node.get_name(), is_fake=True)) + + for add_dep in V.graph.additional_star_deps[node.get_name()]: + add_user(add_dep, node, is_weak=False) # Strong dependency + node.add_fake_dep(StarDep(add_dep)) + + # add normal non-mutation dependencies + for read in node.read_writes.reads: + if not isinstance(read, WeakDep): + add_user(read.name, node, node.can_inplace(read)) + + node.update_mutated_names(self.mutation_renames) + + # update our renaming scheme for the next iteration + for buf in node.get_outputs(): + for alt_name in buf.get_mutations(): + self.mutation_renames[rename(alt_name)] = buf.get_name() + self.mutation_renames[alt_name] = buf.get_name() + self.mutation_real_name[buf.get_name()] = ( + self.mutation_real_name.get(alt_name, alt_name) + ) + + # make sure outputs aren't dead-code-eliminated + for buf_name in V.graph.get_output_names(): + log.debug("scheduling output %s", buf_name) + add_user(buf_name, OutputNode(StarDep(buf_name))) + + # make sure unbacked symints aren't dead-code-eliminated + if has_non_input_unbacked_defs: + for out in V.graph.graph_outputs: + for s in out.get_free_symbol_uses(unbacked_only=True): + if s not in unbacked_symbol_to_origin_node: + raise AssertionError( + f"{s} not in {unbacked_symbol_to_origin_node.keys()}" + ) + if r := unbacked_symbol_to_origin_node[s]: + for buf_name in self.name_to_node[r].get_buffer_names(): + log.debug( + "scheduling output %s for unbacked symint %s", + buf_name, + s, + ) + add_user(buf_name, OutputNode(StarDep(buf_name))) + + # make sure input mutation isn't dead-code-eliminated + for name in self.mutation_renames: + if name in V.graph.graph_inputs: + add_user(name, OutputNode(StarDep(name))) + V.graph.mutated_inputs.add(name) + elif name in V.graph.constants: + # In AOTI, module parameters and buffers are not lifted as graph inputs + add_user(name, OutputNode(StarDep(name))) + + inp_names = { + name: index for index, name in enumerate(V.graph.graph_inputs.keys()) + } + V.graph.mutated_input_idxs = [ + inp_names[name] for name in V.graph.mutated_inputs + ] + + # copy users information onto the nodes + for node in self.nodes: + for buf in node.get_outputs(): + buf.set_users(name_to_users[buf.get_name()].items) + + for name in self.name_to_donated_buffer: + self.name_to_donated_buffer[name].set_users(name_to_users[name].items) + + # For debug logging + logbuf = IndentedBuffer() + logbuf.splice("{") + for key, value in name_to_users.items(): + with logbuf.indent(): + users = [v.get_name() for v in value.items] + logbuf.splice(f"'{key}': {users},") + logbuf.splice("}") + str = logbuf.getrawvalue().rstrip() + compute_dependencies_log.debug("BUFFER USER LIST\n") + compute_dependencies_log.debug("===== AFTER SCHEDULING =====\n%s", str) + + def insert_memory_check_nodes(self) -> None: + from .memory import ( + assign_memory_planning_info_for_scheduler_buffers, + compute_memory_timeline, + FreeableInputBuffer, + get_freeable_input_buf, + ) + + graph_inputs: OrderedSet[str] = OrderedSet(V.graph.graph_inputs.keys()) + name_to_freeable_input_buf: dict[str, FreeableInputBuffer] = ( + get_freeable_input_buf(self.nodes, graph_inputs) + ) + + if not torch._inductor.config.reorder_for_peak_memory: + assign_memory_planning_info_for_scheduler_buffers( + self.nodes, self.name_to_buf + ) + + graph_outputs: OrderedSet[str] = OrderedSet(V.graph.get_output_names()) + buf_info_list, _, _ = compute_memory_timeline( + self.nodes, + name_to_freeable_input_buf, + graph_outputs, + ) + + step_allocs_deallocs: list[tuple[list[str], list[str]]] = [ + ([], []) for _ in range(len(self.nodes)) + ] + for buf_info in buf_info_list: + # Skip zero-size buffers + if buf_info.size_alloc == 0 and buf_info.size_free == 0: + continue + + buf_name = buf_info.buffer.get_name() + + step_allocs_deallocs[buf_info.start_step][0].append(buf_name) + step_allocs_deallocs[buf_info.end_step][1].append(buf_name) + + from torch._inductor.runtime.debug_utils import register_check_mem_op + + register_check_mem_op() + + def construct_mem_check_node( + step_idx: int, is_final_step: bool + ) -> ExternKernelSchedulerNode: + expected_newly_alive = step_allocs_deallocs[step_idx][0] + expected_newly_dead = step_allocs_deallocs[step_idx][1] + + nontensor_args = [expected_newly_alive, expected_newly_dead, is_final_step] + + node = ir.MemoryCheckKernel( + layout=NoneLayout(device=torch.device("cpu")), + kernel=torch.ops._inductor_debug.check_memory_step.default, + tensor_args=[], + nontensor_args=nontensor_args, + unflatten_args=lambda tensor_args, constant_args: ( + tensor_args, + { + "alive": constant_args[0], + "dead": constant_args[1], + "is_final_step": constant_args[2], + }, + ), + ) + node.operation_name = f"mem_check_{self.nodes[step_idx].get_name()}" + return ExternKernelSchedulerNode(self, node) + + new_nodes = [] + + for i, node in enumerate(self.nodes): + new_nodes.append(node) + new_nodes.append( + construct_mem_check_node(i, is_final_step=(i == len(self.nodes) - 1)) + ) + + self.nodes = new_nodes + + def dead_node_elimination(self) -> None: + """ + Remove any nodes without users + """ + if not config.use_dce: + return + + # self.nodes is in topological order, so by iterating in reverse order + # we have visited (and potentially removed) all users before visiting a + # given node. + updated_nodes = [] + for node in reversed(self.nodes): + + def can_eliminate_user(user: NodeUser) -> bool: + return user.is_weak or user.get_name() in V.graph.removed_operations + + active_buffers = False + for buf in node.get_outputs(): + can_eliminate = all(can_eliminate_user(u) for u in buf.users) + if can_eliminate: + log.debug("removed dead buffer: %s", buf.get_name()) + V.graph.removed_buffers.add(buf.get_name()) + else: + active_buffers = True + + can_eliminate = not node.has_side_effects() and not active_buffers + + if not can_eliminate: + updated_nodes.append(node) + else: + # dead code + log.debug("removed dead operation: %s", node.get_name()) + V.graph.removed_operations.add(node.get_name()) + for read in node.read_writes.reads: + if read.name in self.name_to_buf: + users = self.name_to_buf[read.name].users + self.name_to_buf[read.name].users = [ + u for u in users if u.node.get_name() != node.get_name() + ] + self.nodes = list(reversed(updated_nodes)) + + # Prune any WeakDeps no longer needed + for node in self.nodes: + node.prune_weak_deps() + + def mode_requires_synchronization(self, mode: str | None) -> bool: + """Check if store mode requires cross-thread synchronization.""" + return mode is not None # Currently all non-None modes need sync + + def topological_sort_schedule( + self, nodes: list[BaseSchedulerNode] + ) -> list[BaseSchedulerNode]: + """ + Ensure nodes is in topologically sorted order + """ + seen = OrderedSet[BaseSchedulerNode]() + name_to_node: dict[str, BaseSchedulerNode] = dict() + result: list[BaseSchedulerNode] = [] + + def visit(n: BaseSchedulerNode) -> None: + if n not in seen: + seen.add(n) + for dep in sorted(n.unmet_dependencies, key=lambda d: d.name): + # We only care about doing toposort within `nodes` + if dep.name not in name_to_node: + continue + visit(name_to_node[dep.name]) + result.append(n) + + for node in nodes: + for name in node.get_buffer_names(): + name_to_node[name] = node + for node in nodes: + visit(node) + return result + + def _enforce_switch_ordering(self) -> None: + conditional_nodes = [n for n in self.nodes if isinstance(n.node, ir.Switch)] + for i in range(1, len(conditional_nodes)): + mutating_buf = next(iter(conditional_nodes[i].get_buffer_names())) + prev_buf = next(iter(conditional_nodes[i - 1].get_buffer_names())) + conditional_nodes[i].add_fake_dep( + WeakDep(prev_buf, mutating_buf=mutating_buf, is_fake=True) + ) + + def _get_unmet_dep_nodes(self, snode: BaseSchedulerNode) -> list[BaseSchedulerNode]: + unmet_deps: OrderedSet[str] = OrderedSet() + if isinstance( + snode, + ( + SchedulerNode, + ExternKernelSchedulerNode, + NopKernelSchedulerNode, + FusedSchedulerNode, + GroupedSchedulerNode, + ), + ): + for dep in snode.unmet_dependencies: + unmet_deps.add(dep.name) + else: + raise RuntimeError( + f"get_unmet_dep_nodes is not implemented for {type(snode)}." + ) + unmet_dep_ops = (self.name_to_buf[dep].defining_op_name() for dep in unmet_deps) + return list(OrderedSet(self.name_to_fused_node[n] for n in unmet_dep_ops)) + + def _topological_sort_nodes(self) -> list[list[BaseSchedulerNode]]: + """ + Sort nodes by their topological order, return a list of node lists. + """ + order = [] + nodes = dict.fromkeys(self.nodes, 0) + children: dict[Any, Any] = {} + for node in self.nodes: + deps = self._get_unmet_dep_nodes(node) + nodes[node] = len(deps) + for dep in deps: + c = children.get(dep, []) + c.append(node) + children[dep] = c + + zero_deg_nodes = [n for n, v in nodes.items() if v == 0] + while zero_deg_nodes: + order.append(zero_deg_nodes) + for n in zero_deg_nodes: + for user in children.get(n, []): + nodes[user] -= 1 + nodes.pop(n) + zero_deg_nodes = [n for n, v in nodes.items() if v == 0] + if nodes: + raise AssertionError("Topological sort failed!") + return order + + def compute_ancestors(self) -> None: + """ + Populate each node.ancestors + """ + # note self.nodes is topologically sorted + name_to_ancestors: dict[str, OrderedSet[str]] = {} + for node in self.nodes: + ancestors: OrderedSet[str] = OrderedSet() + for dep in node.unmet_dependencies: + dep_node_name = self.name_to_buf[dep.name].defining_op_name() + # A node can transiently depend on a buffer it also writes (a + # self-edge, e.g. from a mutating op whose read and write + # resolve to the same buffer). A node is never its own + # ancestor, so skip it rather than KeyError on itself. + if dep_node_name == node.get_name(): + continue + ancestors.add(dep_node_name) + ancestors |= name_to_ancestors[dep_node_name] + name_to_ancestors[node.get_name()] = ancestors + node.ancestors = ancestors + + for order, node in enumerate(self.nodes): + node.min_order = order + node.max_order = order + + def compute_input_distances(self) -> None: + """ + Populate each node's min/max_input_distance with the depth from graph + inputs, measured as dependency hops before fusion. Nodes whose + dependencies are all satisfied by graph inputs/constants have depth 0. + """ + name_to_min_distance: dict[str, int] = {} + name_to_max_distance: dict[str, int] = {} + for node in self.nodes: + # Skip self-edges (a node depending on a buffer it also writes); a + # node is not at any distance from itself. See compute_ancestors. + dep_ops = [ + op + for dep in node.unmet_dependencies + if (op := self.name_to_buf[dep.name].defining_op_name()) + != node.get_name() + ] + if not dep_ops: + min_dist = 0 + max_dist = 0 + else: + min_dist = min(name_to_min_distance[op] + 1 for op in dep_ops) + max_dist = max(name_to_max_distance[op] + 1 for op in dep_ops) + name_to_min_distance[node.get_name()] = min_dist + name_to_max_distance[node.get_name()] = max_dist + node.min_input_distance = min_dist + node.max_input_distance = max_dist + + def merge_loops(self) -> None: + if not config.loop_ordering_after_fusion: + return + + for node in self.nodes: + # Even for CPU, if we are using the halide backend, we still need + # the merge loops steps below + if not isinstance(node, (SchedulerNode, FusedSchedulerNode)) or ( + not node.is_gpu() and config.cpu_backend != "halide" + ): + continue + for snode in node.get_nodes(): + # merge loops for the scheduler node + if not isinstance(snode, SchedulerNode) or snode.is_template(): + continue + + snode.merge_loops() + + # Note that for CPU backend, merging loops will change + # snode.group. It's fine for Triton backend. + # But if we simplify update snode.group like this: + # group_fn = self.get_backend(snode.node.get_device()).group_fn + # snode.group = (snode.node.get_device(), group_fn(snode._sizes)) + # There is still an issue due to different snode in a + # FusedSchedulerNode having different merged loops. + # Skip CPU backend for now. + + def fuse_nodes(self, nodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]: + """ + Combine eligible nodes into FusedSchedulerNodes. + """ + with dynamo_timed( + "Scheduler.fused_nodes", log_pt2_compile_event=True, log_waitcounter=True + ): + for i in range(10): + old_len = len(nodes) + fusion_log.debug( + "===== attempting fusion (%d/10): %d nodes =====", + i + 1, + old_len, + ) + nodes = self.fuse_nodes_once(nodes, is_reorder_round=False) + new_len = len(nodes) + fusion_log.debug( + "completed fusion round (%d/10): fused %d nodes into %d nodes\n", + i + 1, + old_len, + new_len, + ) + if new_len == old_len or new_len == 1: + fusion_log.debug( + "===== fusion complete (%d iterations) =====", i + 1 + ) + break + + if ( + config.loop_ordering_after_fusion + or config.loop_index_inversion_in_fusion + ): + nodes = self.fuse_nodes_once(nodes, is_reorder_round=True) + return nodes + + def process_grouped_nodes(self) -> None: + """ + Unpack GroupedSchedulerNode into regular nodes. + """ + new_nodes: list[BaseSchedulerNode] = [] + for node in self.nodes: + new_nodes.extend( + node.unpack() if isinstance(node, GroupedSchedulerNode) else [node] + ) + self.nodes = new_nodes + + def benchmark_fused_nodes( + self, nodes: Sequence[BaseSchedulerNode] + ) -> tuple[float, str]: + """ + Benchmark fused list of nodes and return the execution time + in milliseconds on randomly generated inputs. + """ + if len(nodes) <= 0: + raise AssertionError(f"expected nodes to be non-empty, got {len(nodes)}") + device = nodes[0].get_device() + self.current_device = device + backend = self.get_backend(device) + with dynamo_timed( + "benchmark_fused_nodes", + log_pt2_compile_event=True, + dynamo_compile_column_us="compile_time_autotune_time_us", + ): + return backend.benchmark_fused_nodes(nodes) + + def generate_kernel_code_from_nodes( + self, + nodes: Sequence[BaseSchedulerNode], + benchmark_kernel: bool, + hint_override: int | None = None, + ) -> str: + """ + Generate a kernel given a list of pre-fused nodes. + """ + if len(nodes) <= 0: + raise AssertionError(f"expected nodes to be non-empty, got {len(nodes)}") + device = nodes[0].get_device() + self.current_device = device + backend = self.get_backend(device) + with dynamo_timed("generate_kernel_code_from_nodes"): + return backend.generate_kernel_code_from_nodes( + nodes, benchmark_kernel, hint_override=hint_override + ) + + def benchmark_codegened_module( + self, module: ModuleType, device: torch.device + ) -> tuple[float, str]: + """ + Benchmark a compiled module and return the execution time + in milliseconds on randomly generated inputs. + """ + self.current_device = device + backend = self.get_backend(device) + with dynamo_timed("benchmark_codegened_module"): + return backend.benchmark_codegened_module(module) + + def _has_layout_conflict_for_template( + self, multi_node: ir.MultiTemplateBuffer + ) -> bool: + """ + Check if selecting a Triton template would cause layout conflicts. + Returns True if there's a conflict and we should fall back to ATen. + """ + constraints = V.graph.buffer_layout_constraints + if not constraints: + return False + + log.debug("Node %s has constraints %s", multi_node, constraints) + for inp in multi_node.inputs: + # pyrefly: ignore [missing-attribute] + inp_name = inp.get_name() + + if not torch._inductor.select_algorithm.should_use_layout_constraints(inp): + continue + + # pyrefly: ignore [missing-attribute] + layout = inp.layout + expected_layout = constraints[inp_name] + if isinstance(layout, ir.FlexibleLayout): + # Freeze to the expected layout to avoid conflicts + # pyrefly: ignore [missing-attribute] + inp.freeze_layout_with_exact_strides(expected_layout.stride) + # pyrefly: ignore [missing-attribute] + layout = inp.layout + + if isinstance(layout, ir.FixedLayout) and expected_layout != layout: + # Layout already frozen to a different layout - conflict + log.warning( + "Layout conflict detected for %s: template expects %s but layout is frozen to %s", + inp_name, + expected_layout, + layout, + ) + return True + + return False + + def finalize_multi_template_buffers(self) -> None: + """ + Finalize a backing choice for MultiTemplateBuffers which did not already have a + choice finalized through fusion. In the case of an extern choice, this will result + in replacing the SchedulerNode. + + If a MultiTemplateBuffer did not have any fusion opportunities, finalizing a choice + will force completion of compilation and benchmarking. + """ + + for i, node in enumerate(self.nodes): + if isinstance(node, SchedulerNode) and isinstance( + node.node, ir.MultiTemplateBuffer + ): + multi_node = node.node + if ( + not config.test_configs.force_extern_kernel_in_multi_template + and not self._has_layout_conflict_for_template(multi_node) + ): + # TODO (PaulZhang12): Potentially support recompilation/benchmark for new strides + min_node_unfused, _ = multi_node.get_min_choice() + else: + extern_choices = [ + c + for c in multi_node.choices + if isinstance( + c, + torch._inductor.select_algorithm.ExternKernelCaller, + ) + ] + if not extern_choices: + raise AssertionError("No extern kernel detected for fallback") + if len(extern_choices) > 1: + timings = multi_node.choice_timings() + min_node_unfused = min(extern_choices, key=lambda c: timings[c]) + else: + min_node_unfused = extern_choices[0] + + if isinstance( + min_node_unfused, + torch._inductor.ir.TritonTemplateCallerBase, + ): + # pyrefly: ignore [unbound-name] + if config.multi_kernel_hints: + callers: dict[int | None, TritonTemplateCallerBase] = {} + callers[None] = min_node_unfused + + # pyrefly: ignore [unbound-name] + for hint in config.multi_kernel_hints: + timings = multi_node.choice_timings(hint_override=hint) + triton_timings = { + k: v + for k, v in timings.items() + if isinstance(k, TritonTemplateCallerBase) + } + choice = min(triton_timings.items(), key=lambda x: x[1])[0] + callers[hint] = choice + + node.node.finalize_as_triton_callers(callers) + else: + node.node.finalize_as_triton_caller(min_node_unfused) + continue + + with ir.IRNode.current_origins(multi_node.origins): + out_tensorbox = min_node_unfused.output_node() + out_storage = out_tensorbox.data # type: ignore[union-attr] + if not isinstance(out_storage, ir.StorageBox): + raise AssertionError("expected out_storage to be an ir.StorageBox") + out_buffer = out_storage.data + if not isinstance(out_buffer, ir.OperationBuffer): + raise AssertionError( + "expected out_buffer to be an ir.OperationBuffer" + ) + + if multi_node.origin_node: + assign_origin_node(out_tensorbox, multi_node.origin_node) + + out_buffer.layout = multi_node.layout + self._replace_node(out_buffer, multi_node, i, node) + + def _replace_node( + self, + out_buffer: ir.OperationBuffer, + multi_node: ir.MultiTemplateBuffer, + i: int, + node: SchedulerNode, + ) -> None: + _replace_operation_buffer(multi_node, out_buffer) + new_scheduler_node = self.create_scheduler_node(out_buffer) + + self.nodes[i] = new_scheduler_node + self.name_to_node[node.get_name()] = new_scheduler_node + self.name_to_fused_node[node.get_name()] = new_scheduler_node + + # We need to reflect the mutation renames that were recorded in the original node + mutation_renames = {} + for dep in itertools.chain(node.read_writes.reads, node.unmet_dependencies): + if real_name := self.mutation_real_name.get(dep.name, None): + mutation_renames[real_name] = dep.name + + def rename_deps(deps: OrderedSet[Dep]) -> OrderedSet[Dep]: + return OrderedSet(dep.rename(mutation_renames) for dep in deps) + + new_scheduler_node.unmet_dependencies = rename_deps( + new_scheduler_node.unmet_dependencies + ) + new_scheduler_node.read_writes.reads = rename_deps( + new_scheduler_node.read_writes.reads + ) + + for new_out, old_out in zip( + new_scheduler_node.get_outputs(), node.get_outputs() + ): + self.name_to_buf[old_out.get_name()] = new_out + new_out.users = old_out.users + + new_scheduler_node.min_order = node.min_order + new_scheduler_node.max_order = node.max_order + new_scheduler_node.ancestors = node.ancestors + new_scheduler_node.last_usage = node.last_usage + + mempool = self.node_to_mempool.get(node) + if node not in self.node_to_mempool: + mempool = self._get_node_mempool(node) + # If replacement happens before _populate_mempool_assignments, the + # later population pass must be able to recover the preserved context + # from the replacement IR node itself. + if new_scheduler_node.node is not None: + typing.cast(ir.IRNode, new_scheduler_node.node).mempool = mempool + self.node_to_mempool[new_scheduler_node] = mempool + for buf in new_scheduler_node.get_buffer_names(): + self.buff_to_mempool[buf] = mempool + if mempool is not None: + self._mempool_nodes = True + + def _any_atomic_add(self, node_list: Sequence[BaseSchedulerNode]) -> bool: + return any( + hasattr(n.node, "data") + and n.node is not None + and hasattr(n.node.data, "scatter_mode") + and n.node.data.scatter_mode == "atomic_add" + for n in node_list + ) + + def compile_kernel( + self, nodes: Sequence[BaseSchedulerNode], hint_override: int | None = None + ) -> tuple[LambdaFuture | None, ModuleType]: + src_code = self.generate_kernel_code_from_nodes( + nodes, benchmark_kernel=True, hint_override=hint_override + ) + mod = PyCodeCache.load(src_code) + + if not hasattr(mod, "triton_"): + return (None, mod) + + async_compile = torch._inductor.async_compile.AsyncCompile() + if not async_compile.use_process_pool(): + fut = None + else: + fut = async_compile.triton(kernel_name="triton_", source_code=src_code) + if not isinstance(fut, LambdaFuture): + raise AssertionError("expected fut to be a LambdaFuture") + + return (fut, mod) + + def speedup_by_fusion( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> FusionResult: + """ + If config.benchmark_fusion is False, always return True. + Otherwise, return True if fusion can brings speedup. + """ + + is_multi_template = any( + n.is_template() + and isinstance(n.get_template_node(), ir.MultiTemplateBuffer) + for n in (node1, node2) + ) + atomic_add_template_epilogue = isinstance( + node1.get_template_node(), ir.TritonTemplateBuffer + ) and _is_atomic_add_mutation_epilogue(node2, check_config=False) + if atomic_add_template_epilogue and not config.epilogue_fusion_with_atomic_add: + return FusionResult.fuse(False) + + if not config.benchmark_fusion and not is_multi_template: + return FusionResult.fuse(True) + + if ( + node1.is_template() + and not isinstance(node1.get_template_node(), ir.TritonTemplateBuffer) + or node1.is_foreach() + or node2.is_foreach() + ): + return FusionResult.fuse(True) + + node_list_1 = node1.get_nodes() + device = node_list_1[0].get_device() + if not device: + raise AssertionError("expected device to be set") + + # don't support benchmark fusion for CPU C++ backend right now. + if device.type == "cpu" and config.cpu_backend != "triton": + return FusionResult.fuse(True) + + node_list_2 = node2.get_nodes() + node_list_fused = list(itertools.chain(node_list_1, node_list_2)) + has_atomic_add = self._any_atomic_add(node_list_fused) + + # We can not accurately benchmark kernel using atomic_add + # due to how we generate random integer inputs. + # Skip benchmarking them by allowing fusion. The + # epilogue_fusion_with_atomic_add gate only applies to Triton template + # epilogues, so keep the existing non-template behavior here. + if has_atomic_add and not is_multi_template: + return FusionResult.fuse(True) + + from triton.compiler.errors import CompilationError + + why = WhyNoFuse(node1, node2) + + device = node_list_fused[0].get_device() + if device is None: + raise AssertionError("expected device to be set") + + def log_fusion(ms_fused: float, ms1: float, ms2: float) -> None: + if fusion_log.isEnabledFor(logging.DEBUG): + if ms_fused == 0.0: + fusion_log.debug( + "can fuse (assumed): fusing %s with %s (benchmarking skipped)", + node1.get_buffer_names(), + node2.get_buffer_names(), + ) + elif ms_fused < ms1 + ms2: + fusion_log.debug( + "can fuse (benchmark): fusing %s with %s cause %sx speedup", + node1.get_buffer_names(), + node2.get_buffer_names(), + green_text(f"{(ms1 + ms2) / ms_fused:.3f}"), + ) + else: + fusion_log.debug( + "cannot fuse (benchmark): fusing %s with %s cause %sx slowdown", + node1.get_buffer_names(), + node2.get_buffer_names(), + red_text(f"{ms_fused / (ms1 + ms2):.3f}"), + ) + + if is_multi_template and any( + n.get_template_node() is not None for n in (node1, node2) + ): + epilogue_fusion = node1.get_template_node() is not None + multi_node = ( + node1.get_template_node() + if epilogue_fusion + else node2.get_template_node() + ) + if not isinstance(multi_node, ir.MultiTemplateBuffer): + raise AssertionError( + "expected multi_node to be an ir.MultiTemplateBuffer" + ) + # Check for layout conflicts before committing to Triton template + if self._has_layout_conflict_for_template(multi_node): + return FusionResult.fuse(False) + + hint_override_best_fusion_choice: dict[int | None, ir.ChoiceCaller] = {} + if not has_atomic_add: + for hint_override in config.multi_kernel_hints: + future_choices: list[ + tuple[Any, LambdaFuture | None, ModuleType] + ] = [] + choice_timings = multi_node.choice_timings(hint_override) + for choice, _ in sorted(choice_timings.items(), key=lambda x: x[1]): + if not isinstance( + choice, + torch._inductor.select_algorithm.TritonTemplateCaller, + ): + continue + with multi_node.swap_as_triton_caller(choice): + future_choices.append( + ( + choice, + *self.compile_kernel( + node_list_fused, + hint_override=choice.hint_override, + ), + ) + ) + + min_ms_fused = float("inf") + ms_fused_choice: TritonTemplateCallerBase | None = None + new_timings = {} + for choice, future, mod_fused in future_choices: + try: + if future is not None: + future.result() + except Exception as e: + if fusion_log.isEnabledFor(logging.DEBUG): + fusion_log.debug( + "Exception in compiling %s: %s", + "prologue" if not epilogue_fusion else "epilogue", + e, + ) + continue + with multi_node.swap_as_triton_caller(choice): + ms_fused, path = self.benchmark_codegened_module( + mod_fused, device + ) + new_timings[choice] = ms_fused + if ms_fused < min_ms_fused: + min_ms_fused = ms_fused + ms_fused_choice = choice + multi_node._choice_timings[hint_override] = new_timings + if ms_fused_choice is not None: + if not isinstance(ms_fused_choice, TritonTemplateCallerBase): + raise AssertionError( + f"expected TritonTemplateCallerBase, " + f"got {type(ms_fused_choice)}" + ) + hint_override_best_fusion_choice[hint_override] = ( + ms_fused_choice + ) + + from torch._inductor.codegen.nv_universal_gemm import NVUniversalGemmCaller + + bench_epilogue = config.benchmark_epilogue_fusion + num_fusible_callers = sum( + isinstance(c, (TritonTemplateCallerBase, NVUniversalGemmCaller)) + for c in multi_node.choices + ) + # Track if the choice timings can be retrieved async after compilation + get_choice_timings_async = ( + use_pipelined_autotuning() + and not bench_epilogue + and num_fusible_callers <= config.max_epilogue_benchmarked_choices + ) + + ms1, ms2 = float("inf"), float("inf") + min_choice: ir.ChoiceCaller | None = None + if not get_choice_timings_async: + choice_timings = multi_node.choice_timings() + min_choice, ms1 = multi_node.get_min_choice() + + choice_timings_iter = sorted( + choice_timings.items(), key=operator.itemgetter(1) + ) + else: + # Use 0 for unfused time, won't be used as bench_epilogue + # is guaranteed to be False here + choice_timings_iter = [(c, 0) for c in multi_node.choices] + + from torch._inductor.codegen.simd import CantSplit + + def choice_supports_fusion(choice: ir.ChoiceCaller) -> bool: + if not isinstance( + choice, torch._inductor.select_algorithm.TritonTemplateCaller + ): + return False + # For prologue fusion we check if the underlying template of the choice + # supports all allowed prologue inputs. If not, we skip this choice in + # the fusion benchmark. + # TODO: Remove this check after all Triton templates support prologue fusion. + # Currently, persistent+TMA Triton template does not due to the TMA-based loads. + return not ( + not epilogue_fusion + and hasattr(choice, "allowed_prologue_inps") + and choice.allowed_prologue_inps != multi_node.allowed_prologue_inps + ) + + def compile_without_benchmarking( + choice: torch._inductor.select_algorithm.TritonTemplateCaller, + ) -> bool: + with multi_node.swap_as_triton_caller(choice): + try: + future, mod_fused = self.compile_kernel( + node_list_fused, hint_override=choice.hint_override + ) + if future is not None: + future.result() + else: + mod_fused.triton_.precompile() + except CantSplit: + return False + except Exception as e: + if fusion_log.isEnabledFor(logging.DEBUG): + fusion_log.debug( + "Exception in compiling %s: %s", + "prologue" if not epilogue_fusion else "epilogue", + e, + ) + return False + return True + + if has_atomic_add: + if not epilogue_fusion: + return FusionResult.fuse(False) + + for hint_override in [*config.multi_kernel_hints, None]: + choice_timings = multi_node.choice_timings(hint_override) + ms_fused_choice: TritonTemplateCallerBase | None = None + for choice, _ in sorted( + choice_timings.items(), key=operator.itemgetter(1) + ): + if not choice_supports_fusion(choice): + continue + triton_choice = typing.cast( + torch._inductor.select_algorithm.TritonTemplateCaller, + choice, + ) + if compile_without_benchmarking(triton_choice): + ms_fused_choice = triton_choice + break + if ms_fused_choice is None: + return FusionResult.fuse(False) + hint_override_best_fusion_choice[hint_override] = ms_fused_choice + + if config.multi_kernel_hints: + multi_node.finalize_as_triton_callers( + hint_override_best_fusion_choice # pyrefly: ignore [bad-argument-type] + ) + else: + best = hint_override_best_fusion_choice[None] + # pyrefly: ignore [bad-argument-type] + multi_node.finalize_as_triton_caller(best) + return FusionResult.fuse(True) + + if bench_epilogue: + ms2, path2 = ( + self.benchmark_fused_nodes(node_list_2) + if epilogue_fusion + else self.benchmark_fused_nodes(node_list_1) + ) + else: + # By default, don't do prologue fusion. Generally slower + if not epilogue_fusion: + return FusionResult.fuse(False) + + ms2 = node2._get_estimated_runtime() + ms2_fused = _estimate_fused_epilogue_runtime(node1, node2, ms2) + + future_choices: list[tuple[Any, LambdaFuture | None, ModuleType]] = [] + template_choices = 0 + for choice, unfused_time in choice_timings_iter: + is_triton = isinstance( + choice, torch._inductor.ir.TritonTemplateCallerBase + ) + is_nvgemm = isinstance(choice, NVUniversalGemmCaller) + + if not is_triton and not is_nvgemm: + continue + + # pyrefly: ignore [missing-attribute] + if is_nvgemm and not choice.supports_epilogue_fusion: + continue + + # NVGEMM doesn't support prologue fusion. Skip NVGEMM choices in + # the prologue direction (epilogue_fusion is False when node1 is + # the pointwise prologue, node2 is the template). + if is_nvgemm and not epilogue_fusion: + continue + + # For prologue fusion we check if the underlying template of the choice + # supports all allowed prologue inputs. If not, we skip this choice in + # the fusion benchmark. + # TODO: Remove this check after all Triton templates support prologue fusion. + # Currently, persistent+TMA Triton template does not due to the TMA-based loads. + if ( + is_triton + and not epilogue_fusion + and hasattr(choice, "allowed_prologue_inps") + and choice.allowed_prologue_inps != multi_node.allowed_prologue_inps + ): + continue + + if bench_epilogue and unfused_time >= ms1 + ms2: + break + + template_choices += 1 + if template_choices > config.max_epilogue_benchmarked_choices: + break + + try: + if is_triton: + # pyrefly: ignore [bad-argument-type] + with multi_node.swap_as_triton_caller(choice): + future_choices.append( + ( + choice, + *self.compile_kernel( + node_list_fused, + hint_override=getattr( + choice, "hint_override", None + ), + ), + ) + ) + elif is_nvgemm: + # pyrefly: ignore [missing-attribute] + with multi_node.swap_as_nvgemm_caller(choice): + future_choices.append( + (choice, *self.compile_kernel(node_list_fused)) + ) + except CantSplit: + continue + + if len(future_choices) == 0: + return FusionResult.fuse(False) + + def benchmark_when_ready() -> bool: + nonlocal choice_timings, future_choices, ms1, min_choice, multi_node + min_ms_fused = float("inf") + ms_fused_choice = None + new_timings = {} + + if get_choice_timings_async: + if not ( + multi_node and isinstance(multi_node, ir.MultiTemplateBuffer) + ): + raise AssertionError( + "expected multi_node to be an ir.MultiTemplateBuffer" + ) + choice_timings = multi_node.choice_timings() + min_choice, ms1 = multi_node.get_min_choice() + + # Some choices can fail to benchmark, inf timing + future_choices = [ + fut_choice + for fut_choice in future_choices + if fut_choice[0] in choice_timings + ] + + future_choices = sorted( + future_choices, + key=lambda x: choice_timings[x[0]], + ) + # Benchmark each choice after compilation completes + for choice, future, mod_fused in future_choices: + try: + if future is not None: + res = future.result() + elif not bench_epilogue: + if hasattr(mod_fused, "triton_"): + res = mod_fused.triton_ + res.precompile() + else: + res = None + else: + res = None + + # Ideally we would more narrowly catch Exceptions here but + # triton will unpredictably error with valid prologue fusions + except Exception as e: + if fusion_log.isEnabledFor(logging.DEBUG): + fusion_log.debug( + "Exception in compiling %s: %s", + "prologue" if not epilogue_fusion else "epilogue", + e, + ) + continue + + if bench_epilogue: + is_nvgemm_choice = isinstance(choice, NVUniversalGemmCaller) + swap_ctx = ( + # pyrefly: ignore [missing-attribute] + multi_node.swap_as_nvgemm_caller(choice) + if is_nvgemm_choice + # pyrefly: ignore [missing-attribute, bad-argument-type] + else multi_node.swap_as_triton_caller(choice) + ) + with swap_ctx: + ms_fused, path = self.benchmark_codegened_module( + mod_fused, + # pyrefly: ignore [bad-argument-type] + device, + ) + new_timings[choice] = ms_fused + if ms_fused < min_ms_fused: + min_ms_fused = ms_fused + ms_fused_choice = choice + else: + fusible_choice = ( + min_choice == choice + or ms2 + ms1 > choice_timings[choice] + ms2_fused + ) + + is_nvgemm_choice = isinstance(choice, NVUniversalGemmCaller) + if is_nvgemm_choice and fusible_choice: + # NVGEMM register allocations are fixed by cutlass.operators; + # Triton's n_regs/n_spills heuristic doesn't apply. + ms_fused_choice = choice + break + elif res and fusible_choice: + choice.precompile() + # pyrefly: ignore [missing-attribute] + if not (res.launchers and choice.n_regs): + raise AssertionError( + "expected res.launchers and choice.n_regs to be set" + ) + # pyrefly: ignore [bad-index] + compiled_kernel = res.launchers[0] + # pyrefly: ignore [missing-attribute] + fused_n_regs = compiled_kernel.n_regs + # pyrefly: ignore [missing-attribute] + fused_n_spills = compiled_kernel.n_spills + should_fuse_epilogue = _fuse_epilogue( + ms1, + ms2, + choice.n_regs, + fused_n_regs, + fused_n_spills, + choice.bmreq.num_warps, + DeviceProperties.create(device), + ) + if should_fuse_epilogue: + ms_fused_choice = choice + break + + if bench_epilogue: + log_fusion(min_ms_fused, ms1, ms2) + + if ( + not bench_epilogue or min_ms_fused < (ms1 + ms2) + ) and ms_fused_choice is not None: + is_nvgemm = isinstance(ms_fused_choice, NVUniversalGemmCaller) + if is_nvgemm: + # pyrefly: ignore [missing-attribute] + multi_node.finalize_as_nvgemm_caller(ms_fused_choice) + elif config.multi_kernel_hints: + hint_override_best_fusion_choice[None] = ms_fused_choice + # pyrefly: ignore [missing-attribute] + multi_node.finalize_as_triton_callers( + hint_override_best_fusion_choice + ) + else: + # pyrefly: ignore [missing-attribute] + multi_node.finalize_as_triton_caller(ms_fused_choice) + + if bench_epilogue: + # pyrefly: ignore [missing-attribute] + multi_node._choice_timings[None] = new_timings + return True + else: + return False + + # Use a non-None future when available: handing None to from_callable + # causes benchmark_when_ready to run synchronously, blocking any + # remaining Triton async-compile overlap. + deferred_future = next( + (fut for _, fut, _ in future_choices if fut is not None), None + ) + return FusionResult.from_callable(benchmark_when_ready, deferred_future) + + else: + # Start parallel compilation for all three kernels + future_and_mod_l1 = self.compile_kernel(node_list_1) + future_and_mod_l2 = self.compile_kernel(node_list_2) + future_and_mod_l1_fused = self.compile_kernel(node_list_fused) + + def benchmark_when_ready() -> bool: + from torch._inductor.runtime.triton_heuristics import ( + NoTritonConfigsError, + ) + + try: + # Wait for all compilations to complete + for fut in ( + future_and_mod_l1[0], + future_and_mod_l2[0], + future_and_mod_l1_fused[0], + ): + if fut is not None: + fut.result() + + ms1, path1 = self.benchmark_codegened_module( + future_and_mod_l1[1], + # pyrefly: ignore [bad-argument-type] + device, + ) + if math.isinf(ms1): + why("register spilling of the first kernel") + return False + + ms2, path2 = self.benchmark_codegened_module( + future_and_mod_l2[1], + # pyrefly: ignore [bad-argument-type] + device, + ) + if math.isinf(ms2): + why("register spilling of the second kernel") + return False + + ms_fused, path_fused = self.benchmark_codegened_module( + future_and_mod_l1_fused[1], + # pyrefly: ignore [bad-argument-type] + device, + ) + if math.isinf(ms_fused): + why("register spilling of the fused kernel") + return False + + log_fusion(ms_fused, ms1, ms2) + + if ( + is_metric_table_enabled("slow_fusion") + and ms_fused >= ms1 + ms2 + and (path1, path2) not in self.logged_slow_fusion + ): + self.logged_slow_fusion.add((path1, path2)) + get_metric_table("slow_fusion").add_row( + lambda: { + "kernel1_path": path1, + "kernel1_latency": ms1, + "kernel2_path": path2, + "kernel2_latency": ms2, + "fused_kernel_path": path_fused, + "fused_kernel_latency": ms_fused, + "slow_down_ratio": ms_fused / (ms1 + ms2), + } + ) + + return ms_fused < ms1 + ms2 + + except NoTritonConfigsError: + return False + + except CompilationError as e: + if "Loop-carried variable" in str(e): + return True + raise + + return FusionResult.from_callable( + callable_fn=benchmark_when_ready, future=future_and_mod_l1_fused[0] + ) + + def get_fused_node(self, node: BaseSchedulerNode) -> BaseSchedulerNode: + "Look up the node in Scheduler name_to_fused_node" + return self.name_to_fused_node[node.get_first_name()] + + def fuse_two_nodes( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + fused_nodes: OrderedSet[BaseSchedulerNode], + ) -> BaseSchedulerNode: + fusion_log.debug("fusing %s with %s", node1.get_name(), node2.get_name()) + + device = node1.get_device() + if node2.get_device() != device: + raise AssertionError( + f"expected node2 device to be {device}, got {node2.get_device()}" + ) + node3 = self.get_backend(device).fuse(node1, node2) + fused_nodes.remove(node1) + fused_nodes.remove(node2) + fused_nodes.add(node3) + self.name_to_fused_node.update({n.get_name(): node3 for n in node3.get_nodes()}) + + # Propagate stream assignment to the fused node so that subsequent + # fusion rounds still respect stream boundaries. + self.node_to_stream[node3] = self.get_node_stream(node1) + self.node_to_mempool[node3] = self.node_to_mempool.get(node1) + + return node3 + + def fuse_if_speedup( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + speedup_fn: Callable[[], bool], + fused_nodes: OrderedSet[BaseSchedulerNode], + ): + if ( + self.can_fuse(node1, node2) + and not self.will_fusion_create_cycle(node1, node2) + and speedup_fn() + ): + self.fuse_two_nodes(node1, node2, fused_nodes) + return True + + return False + + def _evaluate_pending_template_fusions( + self, + template_fusion_candidates: dict[BaseSchedulerNode, list[PendingFusion]], + fused_nodes: OrderedSet[BaseSchedulerNode], + ) -> None: + """ + Evaluate pending template fusions for a set of fusion candidate nodes. + The fusion candidate nodes are pointwise nodes as potential epilogue + or prologue fusions + """ + + while template_fusion_candidates: + template_futures: list[Future] = [] + future_to_pending_fusion: dict[ + Future, tuple[PendingFusion, BaseSchedulerNode] + ] = {} + fusions_to_remove: OrderedSet[BaseSchedulerNode] = OrderedSet() + for candidate in template_fusion_candidates: + if not ( + candidate in template_fusion_candidates + and len(template_fusion_candidates[candidate]) >= 1 + ): + raise AssertionError( + "expected candidate to have at least one template fusion candidate" + ) + pending_fusion = template_fusion_candidates[candidate].pop(0) + + if len(template_fusion_candidates[candidate]) == 0: + fusions_to_remove.add(candidate) + + node1, node2 = pending_fusion.get_fusion_nodes() + + if node2 == candidate: + if not is_epilogue_fusion(node1, node2): + raise AssertionError( + "expected node1, node2 to be an epilogue fusion" + ) + template_node = node1 + else: + if node1 != candidate: + raise AssertionError("expected node1 to equal candidate") + if not is_prologue_fusion(node1, node2): + raise AssertionError( + "expected node1, node2 to be a prologue fusion" + ) + template_node = node2 + + # template node fused with same class of pointwise (prologue/epilogue) + # move onto next candidate as not fusible + # TODO (PaulZhang12): Does not support fusions of templates with + # multiple potential epilogues + if self.get_fused_node(template_node) is not template_node: + continue + + if pending_fusion.future: + f = pending_fusion.future.future + if f is None: + raise AssertionError("expected f to be set") + template_futures.append(f) + future_to_pending_fusion[f] = (pending_fusion, candidate) + else: + # Non AsyncCompile path, perform fusion + if self.fuse_if_speedup( + node1, node2, pending_fusion.callable_fn, fused_nodes + ): + fusions_to_remove.add(candidate) + + # Evaluate fusion candidates as async_compile completes + for f in as_completed(template_futures): + pending_fusion, cand = future_to_pending_fusion[f] + if self.fuse_if_speedup( + self.get_fused_node(pending_fusion.node1), + self.get_fused_node(pending_fusion.node2), + pending_fusion.callable_fn, + fused_nodes, + ): + fusions_to_remove.add(cand) + + for f in fusions_to_remove: + template_fusion_candidates.pop(f) + + def _try_fusion_pairs( + self, + possible_fusion_pairs: list[tuple[BaseSchedulerNode, BaseSchedulerNode]], + pending_fusions: dict[BaseSchedulerNode, PendingFusion], + template_fusion_nodes: dict[BaseSchedulerNode, list[PendingFusion]], + fused_nodes: OrderedSet[BaseSchedulerNode], + is_reorder_round: bool, + ): + def resolve_pending_fusions( + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + ) -> None: + while ( + self.get_fused_node(node1) in pending_fusions + or self.get_fused_node(node2) in pending_fusions + ): + pending_fusion = pending_fusions.get( + self.get_fused_node(node1), + pending_fusions.get(self.get_fused_node(node2)), + ) + if pending_fusion is None: + raise AssertionError("expected pending_fusion to be set") + + node_key1, node_key2 = pending_fusion.get_fusion_nodes() + is_speedup = pending_fusion.callable_fn + + pending_fusions.pop(node_key1, None) + pending_fusions.pop(node_key2, None) + + if self.get_fused_node(node_key1) is not node_key1: + raise AssertionError("expected node_key1 to be its own fused node") + if self.get_fused_node(node_key2) is not node_key2: + raise AssertionError("expected node_key2 to be its own fused node") + + if not is_speedup() or self.will_fusion_create_cycle(node1, node2): + continue + + self.fuse_two_nodes(node_key1, node_key2, fused_nodes) + + for node1, node2 in possible_fusion_pairs: + # if either node is in a pending fusion, resolve it. + # since we iterate on potential fusions based on profitability + # the first potential fusion should take precedence. + resolve_pending_fusions(node1, node2) + node1 = self.get_fused_node(node1) + node2 = self.get_fused_node(node2) + + if ( + is_template_fusion(node1, node2) + and (node1, node2) in self.seen_template_fusions + ): + continue + + if self.can_fuse( + node1, node2, is_reorder_round + ) and not self.will_fusion_create_cycle(node1, node2): + fusion_res = self.speedup_by_fusion(node1, node2) + if fusion_res.callable_fn is not None: + pending_fusion = PendingFusion( + callable_fn=fusion_res.callable_fn, + node1=node1, + node2=node2, + future=fusion_res.future, + ) + + if is_template_fusion(node1, node2): + if (node1, node2) in self.seen_template_fusions: + raise AssertionError( + "expected (node1, node2) to not already be a seen template fusion" + ) + self.seen_template_fusions.add((node1, node2)) + + template_pw_node = template_fusion_pw_node(node1, node2) + if template_pw_node not in template_fusion_nodes: + template_fusion_nodes[template_pw_node] = [] + template_fusion_nodes[template_pw_node].append(pending_fusion) + else: + pending_fusions[node1] = pending_fusion + pending_fusions[node2] = pending_fusion + + continue + + if not fusion_res.should_fuse: + continue + + self.fuse_two_nodes(node1, node2, fused_nodes) + + def _finish_pending_fusions( + self, + fused_nodes: OrderedSet[BaseSchedulerNode], + pending_fusions: dict[BaseSchedulerNode, PendingFusion], + ): + seen_pair_speedup_fn: OrderedSet[Callable[[], bool]] = OrderedSet() + + # Resolve pending fusions for non templates in case of benchmark_kernel=True + for pending_fusion in pending_fusions.values(): + node_key1, node_key2 = pending_fusion.get_fusion_nodes() + is_speedup_fn = pending_fusion.callable_fn + + if is_speedup_fn in seen_pair_speedup_fn or is_template_fusion( + node_key1, node_key2 + ): + continue + + seen_pair_speedup_fn.add(is_speedup_fn) + + if self.get_fused_node(node_key1) is not node_key1: + raise AssertionError("expected node_key1 to be its own fused node") + if self.get_fused_node(node_key2) is not node_key2: + raise AssertionError("expected node_key2 to be its own fused node") + + self.fuse_if_speedup(node_key1, node_key2, is_speedup_fn, fused_nodes) + + def _handle_template_overlap( + self, + possible_fusions: list[tuple[BaseSchedulerNode, BaseSchedulerNode]], + deferred_prologue_fusions: list[tuple[BaseSchedulerNode, BaseSchedulerNode]], + ): + # Potentially a prologue fusion might have the same template as an epilogue + # the prologue fusion therefore has to be evaluated on the potential + # fused template + epilogue + epilogue_template_nodes = OrderedSet( + [n1 for n1, n2 in possible_fusions if is_epilogue_fusion(n1, n2)] + ) + new_possible_fusions = [] + for n1, n2 in possible_fusions: + if is_prologue_fusion(n1, n2) and n2 in epilogue_template_nodes: + deferred_prologue_fusions.append((n1, n2)) + else: + new_possible_fusions.append((n1, n2)) + + return new_possible_fusions + + def fuse_nodes_once( + self, + nodes: list[BaseSchedulerNode], + is_reorder_round: bool, + ) -> list[BaseSchedulerNode]: + """ + Combine eligible nodes into FusedSchedulerNodes. + + This relies on two key functions to control the logic: + - self.can_fuse(): checks if a fusion is legal + - self.score_fusion(): assigns priority to a given fusion + """ + self.prune_redundant_deps(nodes) + fused_nodes = OrderedSet(nodes) + if fusion_log.isEnabledFor(logging.DEBUG): + fusion_log.debug("fuse_nodes_once, candidates:") + for node in fused_nodes: + fusion_log.debug(" %s", node.debug_str_short()) + + # These are potential fusions which we are async compiling, + # and which we will benchmark profitability of. + # Maps node -> (is_speedup_fn, LambdaFuture, node1, node2) + # Only used in the case of benchmark_kernel=True + pending_fusions: dict[ + BaseSchedulerNode, + PendingFusion, + ] = {} + + template_fusion_nodes: dict[BaseSchedulerNode, list[PendingFusion]] = {} + deferred_prologue_fusions: list[ + tuple[BaseSchedulerNode, BaseSchedulerNode] + ] = [] + + possible_fusions = self.get_possible_fusions( + nodes, + is_reorder_round, + ) + + if config.max_autotune_gemm or config.max_autotune: + possible_fusions = self._handle_template_overlap( + possible_fusions, deferred_prologue_fusions + ) + + self._try_fusion_pairs( + possible_fusions, + pending_fusions, + template_fusion_nodes, + fused_nodes, + is_reorder_round, + ) + self._finish_pending_fusions(fused_nodes, pending_fusions) + + self._evaluate_pending_template_fusions(template_fusion_nodes, fused_nodes) + template_fusion_nodes.clear() + + if deferred_prologue_fusions: + self._try_fusion_pairs( + deferred_prologue_fusions, + pending_fusions, + template_fusion_nodes, + fused_nodes, + is_reorder_round, + ) + self._evaluate_pending_template_fusions(template_fusion_nodes, fused_nodes) + + nodes = sorted(fused_nodes, key=lambda x: x.min_order) + nodes = self.topological_sort_schedule(nodes) + return nodes + + @staticmethod + def _distance_windows( + nodes: list[BaseSchedulerNode], + node_to_idx: dict[BaseSchedulerNode, int], + max_distance: int, + ) -> Iterator[list[BaseSchedulerNode]]: + """Sort `nodes` by baseline index, then yield groups whose span + is at most `max_distance`. Start a new window whenever the next + node would push the span past the limit. Negative `max_distance` + means "no limit" — yield everything as one window. + """ + ordered = sorted(nodes, key=lambda n: node_to_idx[n]) + if max_distance < 0: + if ordered: + yield ordered + return + window: list[BaseSchedulerNode] = [] + window_min = -1 + for n in ordered: + idx = node_to_idx[n] + if window and idx - window_min > max_distance: + yield window + window = [] + if not window: + window_min = idx + window.append(n) + if window: + yield window + + def create_combo_kernel_nodes(self, num_ck_nodes: int | None = None) -> None: + """Group parallel nodes into combo kernels. + + Each parallel group is split into windows whose baseline-index + span is at most `combo_kernel_max_distance` (set the config to a + negative value to disable splitting). If a peak-memory threshold is set, + each window goes through the gate, which simulates the + post-fusion peak and accepts the combo only if the peak stays + under the threshold; rejected windows are halved and retried. + Without a threshold, every window becomes a combo directly. + """ + fused_nodes = OrderedSet(self.nodes) + count = 0 + num_nodes_orig = len(self.nodes) + log.debug("ComboKernels: Generating with num_ck_nodes = %s...", num_ck_nodes) + enable_autotune = config.combo_kernels_autotune > 0 + + abs_thr_gb = config.combo_kernel_peak_memory_increase_gb + pct_thr = config.combo_kernel_peak_memory_pct_threshold + memory_check = abs_thr_gb is not None or pct_thr is not None + max_distance = config.combo_kernel_max_distance + memory_sim_time = 0.0 + mem_ctx: ComboKernelMemoryContext | None = None + if memory_check: + mem_ctx = self._init_peak_memory_context() + node_to_idx = mem_ctx.node_to_idx + else: + node_to_idx = {n: i for i, n in enumerate(self.nodes)} + output_order = node_to_idx.copy() + + def _register_accept( + combo_node: ForeachKernelSchedulerNode, + accepted: list[BaseSchedulerNode], + num: int, + ) -> None: + nonlocal count + count += 1 + log.info( + "ComboKernels: Combining %d nodes for %d-th group", + len(accepted), + num, + ) + for node in accepted: + fused_nodes.remove(node) + fused_nodes.add(combo_node) + output_order[combo_node] = min(output_order[node] for node in accepted) + self.name_to_fused_node.update( + {n.get_name(): combo_node for n in combo_node.get_nodes()} + ) + accepted_streams = OrderedSet(self.get_node_stream(n) for n in accepted) + if len(accepted_streams) != 1: + raise AssertionError( + f"Combo kernel combines multiple streams: {list(accepted_streams)}" + ) + self.node_to_stream[combo_node] = next(iter(accepted_streams)) + accepted_mempools = OrderedSet( + self.node_to_mempool.get(n) for n in accepted + ) + if len(accepted_mempools) != 1: + raise AssertionError( + "Combo kernel combines multiple CUDA MemPool contexts: " + f"{list(accepted_mempools)}" + ) + self.node_to_mempool[combo_node] = next(iter(accepted_mempools)) + + for num, node_list in enumerate( + ForeachKernelSchedulerNode.group_nodes_for_combo_kernels(self) + ): + if num_ck_nodes is not None and count > num_ck_nodes: + break + members = ForeachKernelSchedulerNode.combinable_nodes(node_list) + if len(members) < 2: + continue + + for window in Scheduler._distance_windows( + members, node_to_idx, max_distance + ): + if num_ck_nodes is not None and count > num_ck_nodes: + break + if len(window) < 2 or not self.speedup_by_combo_kernel(window): + continue + if memory_check: + if mem_ctx is None: + raise AssertionError("expected mem_ctx to be set") + sim_start = time.perf_counter() + self._try_combo_with_halving( + window, + num, + mem_ctx, + enable_autotune=enable_autotune, + on_accept=_register_accept, + ) + memory_sim_time += time.perf_counter() - sim_start + else: + combo_node = ForeachKernelSchedulerNode( + window[0].scheduler, + window, + use_custom_partition_algo=True, + enable_autotune=enable_autotune, + per_subkernel_blocks=config.combo_kernel_per_subkernel_blocks, + ) + _register_accept(combo_node, window, num) + + self.nodes = sorted(fused_nodes, key=output_order.__getitem__) + self.nodes = self.topological_sort_schedule(self.nodes) + log.info( + "Generated ComboKernel nodes: %d ComboKernels, totally %d -> %d nodes", + count, + num_nodes_orig, + len(self.nodes), + ) + if memory_check: + log.info( + "ComboKernels memory-aware: %.3fs spent in peak simulation", + memory_sim_time, + ) + self.prune_redundant_deps(self.nodes) + + def _init_peak_memory_context(self) -> ComboKernelMemoryContext: + """Build the immutable baseline state the gate compares against: + original buffer lifetimes, original peak, and step indices. + """ + from .memory import ( + assign_memory_planning_info_for_scheduler_buffers, + assign_memory_planning_info_for_scheduler_nodes, + compute_memory_timeline, + get_freeable_input_buf, + live_memory_before_steps_from_buf_info_list, + peak_memory_from_buf_info_list, + ) + + graph_inputs = OrderedSet(V.graph.graph_inputs.keys()) + graph_outputs = OrderedSet(V.graph.get_output_names()) + + name_to_freeable = get_freeable_input_buf(self.nodes, graph_inputs) + assign_memory_planning_info_for_scheduler_buffers(self.nodes, self.name_to_buf) + assign_memory_planning_info_for_scheduler_nodes( + self.nodes, + self.name_to_fused_node, + self.name_to_buf, + name_to_freeable, + ) + buf_info_list, _, _ = compute_memory_timeline( + self.nodes, name_to_freeable, graph_outputs + ) + baseline_peak, _ = peak_memory_from_buf_info_list( + buf_info_list, len(self.nodes) + ) + baseline_live_before = live_memory_before_steps_from_buf_info_list( + buf_info_list, len(self.nodes) + ) + + return ComboKernelMemoryContext( + graph_outputs=graph_outputs, + node_to_idx={node: idx for idx, node in enumerate(self.nodes)}, + baseline_peak=baseline_peak, + running_peak=baseline_peak, + baseline_live_before=baseline_live_before, + ) + + def _try_combo_with_memory_check( + self, + group_nodes: list[BaseSchedulerNode], + mem_ctx: ComboKernelMemoryContext, + enable_autotune: bool, + ) -> tuple[ForeachKernelSchedulerNode | None, int]: + """The gate: does fusing `group_nodes` into one combo keep peak + memory under the threshold? + + Returns `(combo_node, combo_step)` if accepted, or `(None, 0)` + if rejected. The running peak lives on `mem_ctx.running_peak`. + + The pretend rewrite only changes node order inside the window + `[region_start, region_end]` (the smallest range containing all + members). Inside that window: + - the members collapse into one combo node, all at `combo_step`, + - everything else is evaluated from the original schedule. + Outside the window, nothing moves. Earlier accepts are accounted + for only by `mem_ctx.running_peak`. The threshold is checked + against `mem_ctx.baseline_peak` (the original graph peak) so total + peak drift is capped. + """ + from .memory import estimate_region_peak_memory + + combo_node = ForeachKernelSchedulerNode( + group_nodes[0].scheduler, + group_nodes, + use_custom_partition_algo=True, + enable_autotune=enable_autotune, + per_subkernel_blocks=config.combo_kernel_per_subkernel_blocks, + ) + # Wire the combo's pred_buffers from its members so the gate + # simulator can read `node.mpi_node.pred_buffers` uniformly. + combo_pred_buffers = OrderedSet() + for m in group_nodes: + combo_pred_buffers.update(m.mpi_node.pred_buffers) + combo_node.mpi_node = MemoryPlanningInfoForNode( + pred_buffers=combo_pred_buffers, + ) + + node_to_idx = mem_ctx.node_to_idx + + # Single pass over group_nodes: build the set and find the + # min/max baseline index together. + group_set: OrderedSet[BaseSchedulerNode] = OrderedSet() + region_start = sys.maxsize + region_end = -1 + for n in group_nodes: + group_set.add(n) + idx = node_to_idx[n] + if idx < region_start: + region_start = idx + if idx > region_end: + region_end = idx + + # Build the post-rewrite slice for [region_start, region_end]. + local_entries: list[_LocalEntry] = [] + inserted_combo = False + + def add_local(node: BaseSchedulerNode, cur: int, baseline: int) -> None: + local_entries.append(_LocalEntry(cur, baseline, node)) + + for i in range(region_start, region_end + 1): + n = self.nodes[i] + if n in group_set: + if not inserted_combo: + add_local(combo_node, region_start, i) + inserted_combo = True + continue + add_local(n, i, i) + + local_nodes = [ + e.node for e in sorted(local_entries, key=lambda e: (e.cur, e.baseline)) + ] + local_nodes = self.topological_sort_schedule(local_nodes) + + new_step = {n: region_start + i for i, n in enumerate(local_nodes)} + combo_step = new_step[combo_node] + for n in group_nodes: + new_step[n] = combo_step + + def step_of(node: BaseSchedulerNode) -> int: + if node in new_step: + return new_step[node] + return node_to_idx[node] + + # Combo windows are evaluated independently. The entry live set is + # therefore the original-schedule live memory before this region starts. + cur_memory = mem_ctx.baseline_live_before[region_start] + + region_peak = estimate_region_peak_memory( + local_nodes, + region_start=region_start, + region_end=region_end, + step_of=step_of, + graph_outputs=mem_ctx.graph_outputs, + cur_memory=cur_memory, + ) + + # Compare against the *original* baseline peak (not the running + # peak) to cap total drift across many accepts. + original_peak = mem_ctx.baseline_peak + new_peak = max(mem_ctx.running_peak, region_peak) + delta = new_peak - original_peak + abs_thr_gb = config.combo_kernel_peak_memory_increase_gb + pct_thr = config.combo_kernel_peak_memory_pct_threshold + limits = [float(abs_thr_gb) * (1024**3)] if abs_thr_gb is not None else [] + if pct_thr is not None: + limits.append(pct_thr * original_peak) + if not limits: + raise AssertionError("expected limits to be truthy") + accept = delta <= min(limits) + + pct = (100.0 * delta / original_peak) if original_peak > 0 else 0.0 + if not accept: + log.debug( + "ComboKernels memory-aware: rejected %d nodes " + "(peak delta %+d bytes = %.3f%%)", + len(group_nodes), + delta, + pct, + ) + return None, 0 + + log.info( + "ComboKernels memory-aware: accepted %d nodes " + "(peak delta %+d bytes = %.3f%%)", + len(group_nodes), + delta, + pct, + ) + mem_ctx.running_peak = new_peak + return combo_node, combo_step + + def _try_combo_with_halving( + self, + candidate: list[BaseSchedulerNode], + num: int, + mem_ctx: ComboKernelMemoryContext, + *, + enable_autotune: bool, + on_accept: Callable[ + [ForeachKernelSchedulerNode, list[BaseSchedulerNode], int], None + ], + ) -> None: + """Try the full candidate; on reject, halve at the + baseline-index midpoint and try each half. + """ + n2i = mem_ctx.node_to_idx + # Push late then early so early pops first. + stack: list[list[BaseSchedulerNode]] = [candidate] + while stack: + subset = stack.pop() + if len(subset) < 2 or not self.speedup_by_combo_kernel(subset): + continue + + combo_node, combo_step = Scheduler._try_combo_with_memory_check( + self, subset, mem_ctx, enable_autotune + ) + if combo_node is not None: + on_accept(combo_node, subset, num) + continue + + idxs = [n2i[n] for n in subset] + lo, hi = min(idxs), max(idxs) + if lo == hi: + continue + mid = (lo + hi) // 2 + early = [n for n in subset if n2i[n] <= mid] + late = [n for n in subset if n2i[n] > mid] + if 2 <= len(late) < len(subset): + stack.append(late) + if 2 <= len(early) < len(subset): + stack.append(early) + + def prune_redundant_deps(self, nodes: list[BaseSchedulerNode]) -> None: + for node in nodes: + node.prune_redundant_deps(self.name_to_fused_node) + + def get_possible_fusions( + self, + nodes: list[BaseSchedulerNode], + is_reorder_round: bool, + ) -> list[tuple[BaseSchedulerNode, BaseSchedulerNode]]: + """ + Helper to find all legal fusion opportunities, sorted by self.score_fusion() + """ + possible_fusions = [] + seen = OrderedSet[tuple[BaseSchedulerNode, BaseSchedulerNode]]() + + def check_all_pairs(nodes: list[BaseSchedulerNode]) -> None: + for node1_index, node1 in enumerate(nodes): + for node2 in nodes[ + node1_index + 1 : node1_index + + 1 + + config.max_fusion_buffer_group_pairwise_attempts + ]: + key = (node1, node2) + if key in seen: + continue + seen.add(key) + + if self.can_fuse(node1, node2, is_reorder_round): + possible_fusions.append(key) + elif (node2.is_template() or node2.is_foreach()) and self.can_fuse( + node2, node1, is_reorder_round + ): + # foreach fusions and epilogue fusions are order dependent + possible_fusions.append((node2, node1)) + + buffer_names_grouping = collections.defaultdict(list) + for node in nodes: + if self.unfusable_node(node): + continue + for buf in node.used_buffer_names(): + buffer_names_grouping[buf].append(node) + for node_grouping in buffer_names_grouping.values(): + check_all_pairs(node_grouping) + + if config.aggressive_fusion: + group_grouping = collections.defaultdict(list) + for node in nodes: + group = getattr(node, "group", None) + if group: + group_grouping[group].append(node) + for node_grouping in group_grouping.values(): + check_all_pairs(node_grouping) + + possible_fusions = self.get_possible_fusions_with_highest_priority( + possible_fusions + ) + possible_fusions.sort(key=self.score_fusion_key, reverse=True) + fusion_log.debug("found %d possible fusions", len(possible_fusions)) + return possible_fusions + + def will_fusion_create_cycle( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + """ + Finds whether there's a path from node1 to node2 (or vice-versa) + caused indirectly by other fusions. + """ + # since we are just returning boolean here, use slightly faster, unordered set + visited = OrderedSet[FusedSchedulerNode]() + + def found_path(node: BaseSchedulerNode) -> bool: + # only fused nodes can introduce new ancestors. + if isinstance(node, FusedSchedulerNode) and node not in visited: + visited.add(node) + if node.get_operation_names().issubset(combined_ancestors): + # All fusion outputs are in ancestors of node1 and node2, thus + # cannot introduce new path: + # + # 1. if output is neither descendant of node1 or node2, the + # output cannot introduce a path + # 2. due to [can_fuse]: if WLOG output is descendant of node1, it cannot be + # on path(node1->node2), hence it cannot be ancestor of node2 + # 3. due to [acyclic]: if WLOG output is descendant of node1, it cannot be + # ancestor of node1 + return False + else: + # continue DFS of new ancestors introduced by the fusion + return bool(combined_names & node.ancestors) or any( + found_path(self.name_to_fused_node[n]) + for n in node.ancestors - combined_ancestors + ) + return False + + # as above - use slightly faster, unordered set + combined_names = ( + node1.get_operation_names()._dict.keys() + | node2.get_operation_names()._dict.keys() + ) + combined_ancestors = ( + node1.ancestors._dict.keys() | node2.ancestors._dict.keys() + ) - combined_names + cycle = any(found_path(self.name_to_fused_node[n]) for n in combined_ancestors) + if cycle: + WhyNoFuse(node1, node2)("will create cycle") + return cycle + + def can_fusion_increase_peak_memory( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + """ + Return true if fusing the two nodes can potentially increasing peak memory. + + The implementation is more like a heuristic since we don't really know if we are at peak + or not when trying to fuse these two nodes. The order of nodes may change later which makes the + peak memory estimation hard. + + Here is how we decide the LOWER BOUND of extra memory allocation if we fuse these 2 nodes: + 1. find all buffers read by each node with a single user. These buffers are supposed to + be reused if we don't fuses these 2 nodes + 2. find the intersection of these buffers for the two node and sum the total buffer size. + If we don't fuse these two nodes, we can at lease avoid this much memory allocation. + Note that the extra memory allocation is not necessarily causing peak memory increase. + This is just a heuristic. + + We return true only if the saving for fusion can not trade off the extra memory allocation. + """ + + from .codegen.wrapper import buffer_reuse_key + + def _find_single_user_inputs( + node: BaseSchedulerNode, + ) -> list[ir.Buffer]: + output = [] + for rd in node.read_writes.reads: + buf = self.name_to_buf.get(rd.name) + if buf and len(buf.users) == 1 and buf.node.has_tensor_output(): + output.append(buf.node) + return output + + # Check inputs that can be potentially reused + lhs_dep_nodes = _find_single_user_inputs(node1) + rhs_dep_nodes = _find_single_user_inputs(node2) + + lhs_reuse_keys = OrderedSet(buffer_reuse_key(buf) for buf in lhs_dep_nodes) + rhs_reuse_keys = OrderedSet(buffer_reuse_key(buf) for buf in rhs_dep_nodes) + + common_reuse_keys = lhs_reuse_keys.intersection(rhs_reuse_keys) + + memory_overhead = 0 + for key in common_reuse_keys: + try: + memory_overhead += int(key[2]) + except ValueError: + # not an integer. Fallback is to fuse + return False + + bw_saving = self.score_fusion_memory(node1, node2) + + # The factor 32 here is quite arbitrary. + if V.graph.sizevars.statically_known_gt(memory_overhead, 32 * bw_saving): + return True + return False + + def fusion_prevent_too_many_reads_and_writes( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode, threshold: int + ) -> bool: + # After fusion, we need to calculate the unique I/O buffers + # accounting for buffers that become internal (removed through fusion) + + # Get all nodes that will be in the fused node + fused_node_names = OrderedSet( + [node.get_name() for node in node1.get_nodes()] + + [node.get_name() for node in node2.get_nodes()] + ) + + # Calculate node2 reads that can be removed through fusion, + # i.e. node2 reads that are outputs of node1 + node1_write_names = OrderedSet(dep.name for dep in node1.read_writes.writes) + node2_read_names = OrderedSet(dep.name for dep in node2.read_writes.reads) + reads_removed_through_fusion = node2_read_names & node1_write_names + + # Calculate node1 writes that can be removed through fusion, + # i.e. node1 writes that are only read by node2 + writes_removed_through_fusion: OrderedSet[str] = OrderedSet() + for write_dep in node1.read_writes.writes: + if self.can_buffer_be_removed_through_fusion( + write_dep.name, fused_node_names + ): + writes_removed_through_fusion.add(write_dep.name) + + # Get all unique reads (union of both nodes' reads) + all_read_names = OrderedSet( + dep.name for dep in node1.read_writes.reads + ) | OrderedSet(dep.name for dep in node2.read_writes.reads) + + # Get all unique writes (union of both nodes' writes) + all_write_names = OrderedSet( + dep.name for dep in node1.read_writes.writes + ) | OrderedSet(dep.name for dep in node2.read_writes.writes) + + # Remove reads that become internal + unique_reads = all_read_names - reads_removed_through_fusion + + # Remove writes that become internal + unique_writes = all_write_names - writes_removed_through_fusion + + # Get all unique buffer names (reads and writes combined, but no double counting) + unique_io_buffers = unique_reads | unique_writes + + return len(unique_io_buffers) > threshold + + def are_long_distant_nodes( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + """ + This function prevents fusion for nodes that can increase memory + footprint. This problem is more common in horizontal fusion, where nodes + that are far apart in the original order get fused, lengthening the live + intervals of tensors. This is very evident in models with activation + checkpointing, where the recomputed nodes from different checkpointed + regions get fused and significantly increase the memory footprint. + + The current attempt is a quick, possibly hacky, heuristic to prevent the + fusion of nodes that are far away in the original order. + + A better but difficult to implement heuristic would be to use live + intervals of the buffers, find region of peak pressure in the original + program and prevent fusion that crosses that peak region. We might need + special care or good approximation in this implementation, as fusion of + node changes live intervals, and re-computing live intervals and peak + memory after each fusion can introduce large compilation overhead. + """ + proximity_score = max( + abs(node1.min_order - node2.max_order), + abs(node2.min_order - node1.max_order), + ) + return proximity_score > 64 + + def decide_fusion_fail_reason( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + common_buf_names: tuple[str, ...] | OrderedSet[str], + ) -> str: + """ + Try to decide reasons why fusion fail due to no shared memory even though + there are common buffers. + """ + reasons = {} + node1_name2dep = {dep.name: dep for dep in node1.read_writes.reads_and_writes()} + node2_name2dep = {dep.name: dep for dep in node2.read_writes.reads_and_writes()} + + for buf_name in common_buf_names: + buf = V.graph.get_buffer(buf_name) + lhs_dep = node1_name2dep[buf_name] + rhs_dep = node2_name2dep[buf_name] + + if not isinstance(lhs_dep, MemoryDep) or not isinstance(rhs_dep, MemoryDep): + reasons[buf_name] = ( + f"not MemoryDep: {type(lhs_dep)} v.s. {type(rhs_dep)}" + ) + continue + + if lhs_dep.get_numel() != rhs_dep.get_numel(): + reasons[buf_name] = ( + f"different numel: {lhs_dep.get_numel()} v.s. {rhs_dep.get_numel()}" + ) + continue + + # same numel but different MemoryDep.size. Should be broadcasting + if sympy_product(lhs_dep.size) != sympy_product(rhs_dep.size): + reasons[buf_name] = "broadcast" + continue + + lhs_off = lhs_dep.get_offset() + rhs_off = rhs_dep.get_offset() + if lhs_off != rhs_off: + # One example is in transformer, we use a concatenated linear layer + # to project Q/K/V and then split the result. The 3 splits will + # point to the same buffer with different offsets. + reasons[buf_name] = f"different offset: {lhs_off} v.s. {rhs_off}" + continue + + if ( + lhs_dep.normalize_with_stride_order() + == rhs_dep.normalize_with_stride_order() + ): + reasons[buf_name] = f"Mismatch loop orders: {lhs_dep} v.s. {rhs_dep}" + continue + + # Add more rules here + layout_str = "" + if not isinstance(buf, ir.TorchBindObject): + layout_str = f"Layout: {buf.layout}" + reasons[buf_name] = ( + f"Unknown reason: {lhs_dep} v.s. {rhs_dep}. {layout_str}" + ) + + return str(reasons) + + def _can_reindex_consumer_for_index_inversion( + self, + producer_write: MemoryDep, + consumer_read: MemoryDep, + consumer_write: MemoryDep, + consumer: SchedulerNode, + read_expr: sympy.Expr, + ) -> bool: + if consumer.is_reduction() or consumer_read.size != consumer_write.size: + return False + + flat_size = sympy_product(producer_write.size) + if not V.graph.sizevars.statically_known_equals( + sympy_product(consumer_read.size), flat_size + ) or not V.graph.sizevars.statically_known_equals( + sympy_product(consumer._sizes[0]), flat_size + ): + return False + if tuple(consumer._sizes[0]) == (flat_size,): + return False + + body = consumer._body + if body is None or not consumer_write.normalize().is_contiguous(): + return False + + iter_vars = body.vars[0] + iter_sizes = body.sizes[0] + if len(iter_vars) != len(iter_sizes): + return False + + return ( + self._get_flattened_read_inverse( + read_expr, tuple(iter_vars), tuple(iter_sizes), flat_size + ) + is not None + ) + + def _get_flattened_read_inverse( + self, + read_expr: sympy.Expr, + iter_vars: tuple[sympy.Symbol, ...], + iter_sizes: tuple[sympy.Expr, ...], + flat_size: sympy.Expr, + ) -> tuple[sympy.Symbol, sympy.Expr] | None: + if V.graph.sizevars.statically_known_equals(flat_size, 0): + return None + + # A flat reindex decomposes one new loop variable into the old loop domain. + # Apply that substitution to the read without rebuilding the LoopBody. + flat_var = _FLATTENED_READ_VAR + flattened_read = sympy_subs( + read_expr, + dict(zip(iter_vars, decompose_index(flat_var, iter_sizes))), + ) + + inverse = self._get_indexing_inverse(flattened_read, flat_var, flat_size) + if inverse is None: + return None + return flat_var, inverse + + def _get_indexing_inverse( + self, + read_expr: sympy.Expr, + index_var: sympy.Symbol, + index_size: sympy.Expr, + ) -> sympy.Expr | None: + # Canonicalize the loop variable so preflight and the rebuilt LoopBody + # share one scheduler-local cache entry. + canonical_read = sympy_subs(read_expr, {index_var: _FLATTENED_READ_VAR}) + canonical_read = V.graph.sizevars.simplify_with_ranges( + sympy.expand(canonical_read), {_FLATTENED_READ_VAR: index_size} + ) + inverse = self._get_canonical_indexing_inverse(canonical_read, index_size) + if inverse is None: + return None + return sympy_subs(inverse, {_FLATTENED_READ_VAR: index_var}) + + @cache_on_self_and_args("Scheduler") + def _get_canonical_indexing_inverse( + self, read_expr: sympy.Expr, index_size: sympy.Expr + ) -> sympy.Expr | None: + from torch._inductor.invert_expr_analysis import generate_inverse_formula + + return generate_inverse_formula(read_expr, _FLATTENED_READ_VAR, index_size) + + def shared_data_after_inverting_indexing( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + ) -> int: + """ + Attempts to enable fusion between two nodes by inverting indexing patterns. + + This optimization targets cases where node1 has a contiguous write and + node2 has a contiguous write but discontiguous read. By inverting the + indexing in node2's read and write operations, we can make them compatible + with node1 for potential fusion. + + Args: + node1: First scheduler node (source) + node2: Second scheduler node (target for inversion) + + Returns: + int: Fusion score if successful, 0 if optimization not applicable + """ + + if not config.loop_index_inversion_in_fusion: + return -1 + + if any(n.is_cpu() for n in [node1, node2]): + return -1 + if not isinstance(node2, SchedulerNode): + return -1 + if not isinstance(node2.node, ir.ComputedBuffer): + return -1 + body = node2._body + if body is None: + return -1 + + # Check for shared buffers between nodes + node1_buffer_names = node1.read_writes.buffer_names() + node2_buffer_names = node2.read_writes.buffer_names() + common_buffer_names = node1_buffer_names & node2_buffer_names + + if not common_buffer_names: + return -1 + + # only invert if node1 is single unmet dep + node2_unmet_dependencies = OrderedSet( + dep.name for dep in node2.unmet_dependencies + ) + if node2_unmet_dependencies - node1_buffer_names: + return -1 + + if len(node2_unmet_dependencies) > 1: + return -1 + + # Currently only handle single read/write operations + if len(node2.read_writes.reads) != 1 or len(node2.read_writes.writes) != 1: + return -1 + + node2_read = next(iter(node2.read_writes.reads)) + node2_write = next(iter(node2.read_writes.writes)) + + if not isinstance(node2_read, MemoryDep) or not isinstance( + node2_write, MemoryDep + ): + return -1 + + matching_node1_writes = [ + dep for dep in node1.read_writes.writes if dep.name == node2_read.name + ] + if len(matching_node1_writes) != 1: + return -1 + + node1_write = matching_node1_writes[0] + + if not isinstance(node1_write, MemoryDep): + return -1 + + # Index inversion supports one read and one write expression without subblocks. + if len(body.indexing_exprs) != 2 or body.subblocks: + return -1 + node2_read_exprs = OrderedSet(body.get_read_exprs()) + if len(node2_read_exprs) != 1: + return -1 + read_expr = next(iter(node2_read_exprs)) + + # Check the flattened read before rebuilding the consumer LoopBody. + can_reindex = self._can_reindex_consumer_for_index_inversion( + node1_write, node2_read, node2_write, node2, read_expr + ) + if can_reindex: + node2.apply_loop_reindexing([sympy_product(node1_write.size)]) + # Re-enter with refreshed dependencies; inverse lookup uses the cache. + return self.shared_data_after_inverting_indexing(node1, node2) + + if not node2_write.is_contiguous(): + return -1 + + # We are checking for compatibility with the normalized node1 write + # then modifying node2 reads/writes. since the node1 write will be just used + # for compatibility, while node2 will be used in actual modification, just + # normalize node1 not node2. + node1_write = node1_write.normalize() + + if ( + node1_write.index != node2_write.index + and node1_write.size != node2_write.size + ): + return -1 + + if node2_read.size != node2_write.size or len(node2_read.var_names) != 1: + return -1 + + if not ("index0" in body.indexing_exprs and "index1" in body.indexing_exprs): + raise AssertionError("expected index0 and index1 in node2 indexing_exprs") + + # Determine which index is for reading vs writing + if read_expr == body.indexing_exprs["index0"]: + read_expr_index = "index0" + write_expr_index = "index1" + else: + if read_expr != body.indexing_exprs["index1"]: + raise AssertionError("expected read_expr to match node2 index1 expr") + read_expr_index = "index1" + write_expr_index = "index0" + + index_vars = body.vars[0] + if len(index_vars) != 1: + return -1 + + inverse_formula = self._get_indexing_inverse( + read_expr, index_vars[0], node2_read.size[0] + ) + + # formula is not invertible + if inverse_formula is None: + return -1 + + # === Apply Inversion === + + # Swap the indexing expressions using the inverse formula + node2.apply_indexing_exprs( + { + read_expr_index: body.indexing_exprs[write_expr_index], + write_expr_index: inverse_formula, + } + ) + + # Calculate fusion score + score = self.score_fusion_memory(node1, node2) + if not isinstance(score, int): + raise AssertionError("expected score to be an int") + if score == 0: + score = self._score_fusion_memory_by_fusable_read_write(node1, node2) + + fusion_log.info("Shared memory after inversion: %d", score) + return score + + def shared_data_after_reordering_loop( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> int: + """ + Right now just greedily reorder the loop of node1 to be compatible with node2, + but ideally we should have some heuristics to reorder the loop for node2 + to be compatible with node1 if that's more efficient. + + Return the amount of shared data re-computed in this method. + If no such recomputation happens, return -1 (not return 0 since 0 is a valid + amount of shared data). + + """ + + # TODO Don't do loop reordering/reindexing for CPU for now. + # Should debug more why it does not work for CPU codegen + if any(n.is_cpu() for n in [node1, node2]): + return -1 + + # in some rare case, a template can be passed in. + # Check test_interaction_with_multi_template in test_loop_ordering.py + # and https://github.com/pytorch/pytorch/issues/165579 + if node1.is_template() or node2.is_template(): + return -1 + + common_buffer_names = ( + node1.read_writes.buffer_names() & node2.read_writes.buffer_names() + ) + if not common_buffer_names: + return -1 + + if config.loop_ordering_after_fusion: + score = self._try_reorder_loops_for_candidates(node1, node2) + if score >= 0: + return score + + # No reordering candidates found (or loop ordering disabled). + # Try reindexing the pointwise to match the reduction's iteration + # domain (e.g., [1024, 8192] -> [65536, 128] for RMS norm with + # reshape), then retry loop reordering if enabled. The retry is + # needed because FusedSchedulerNodes may have more loop vars than + # the reindexed pointwise (e.g., 3 vs 2), and only the normalize() + # comparison in _try_reorder_loops_for_candidates handles that + # num_vars mismatch. + if ( + not config.loop_reindexing_after_fusion + or not self._try_reindex_pointwise_for_reduction(node1, node2) + ): + return -1 + + if config.loop_ordering_after_fusion: + score = self._try_reorder_loops_for_candidates(node1, node2) + if score >= 0: + return score + + return self.score_fusion_memory(node1, node2) + + def _try_reorder_loops_for_candidates( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + ) -> int: + """ + Find common buffers with matching normalized stride order but different + loop orders, and try to reorder loops to align them. + """ + common_buffer_names = ( + node1.read_writes.buffer_names() & node2.read_writes.buffer_names() + ) + node1_reads = {dep.name: dep for dep in node1.read_writes.reads} + node1_writes = {dep.name: dep for dep in node1.read_writes.writes} + node2_reads = {dep.name: dep for dep in node2.read_writes.reads} + node2_writes = {dep.name: dep for dep in node2.read_writes.writes} + + candidates = [] + for buffer_name in common_buffer_names: + lhs_dep = node1_writes.get(buffer_name) or node1_reads[buffer_name] + rhs_dep = node2_writes.get(buffer_name) or node2_reads[buffer_name] + + is_write_read = ( + buffer_name in node1_writes and buffer_name in node2_reads + ) or (buffer_name in node2_writes and buffer_name in node1_reads) + + if ( + lhs_dep.normalize_with_stride_order() + == rhs_dep.normalize_with_stride_order() + ): + candidates.append( + ( + is_write_read, + V.graph.sizevars.optimization_hint( + lhs_dep.get_numel(), fallback=0 + ), + lhs_dep, + rhs_dep, + ) + ) + elif is_write_read: + # A write→read dep failed normalize_with_stride_order. + # This could be a dimension order issue (reordering can + # fix it) or a factorization issue (only reindexing can). + # Distinguish by checking if the write dep's sizes are + # a subset of the read dep's — if so, reordering the + # read's loops could align them. + w = node1_writes.get(buffer_name) or node2_writes.get(buffer_name) + r = node2_reads.get(buffer_name) or node1_reads.get(buffer_name) + if isinstance(w, MemoryDep) and isinstance(r, MemoryDep): + sv = V.graph.sizevars + w_sizes = w.normalize().size + r_sizes = r.normalize().size + if not all( + any(sv.statically_known_equals(ws, rs) for rs in r_sizes) + for ws in w_sizes + ): + return -1 + + if len(candidates) == 0: + return -1 + + # Prefer write→read deps over shared reads. Among same + # priority, pick the largest buffer. + _is_wr, _numel, lhs_dep, rhs_dep = max( + candidates, key=operator.itemgetter(0, 1) + ) + + if not isinstance(lhs_dep, MemoryDep) or not isinstance(rhs_dep, MemoryDep): + return -1 + + if lhs_dep.num_vars != rhs_dep.num_vars: + # this can happen due to we don't merge loops. + # We can not do loop reordering in this case right now + # Simply returning true if the two Deps are the same after + # normalization (merging loops) + if lhs_dep.normalize() == rhs_dep.normalize(): + return self.dep_size_hint(lhs_dep) + return -1 + + reordered = False + # Only reorder loops for pointwise for now + if not node1.is_reduction(): + reordered = node1.reorder_loops_by_dep_pair(lhs_dep, rhs_dep) + elif not node2.is_reduction(): + reordered = node2.reorder_loops_by_dep_pair(rhs_dep, lhs_dep) + else: + loop_ordering_log.debug( + "Don't reorder loops since both nodes are reductions: %s v.s. %s", + node1.get_name(), + node2.get_name(), + ) + + return self.score_fusion_memory(node1, node2) if reordered else -1 + + def _selected_tiling_memory( + self, nodes: Sequence[BaseSchedulerNode] + ) -> MemoryCoalescing | None: + """Memory accessed by these nodes codegened as one kernel, or None. + + None means the coalescing cost is unknown - either the analysis does not + apply, or the tiling was forced or fell back and so was never scored. + """ + from .codegen.simd import SIMDScheduling + from .tiling_utils import analyze_memory_coalescing_for_nodes + + if ( + not nodes + or not config.triton.coalesce_tiling_analysis + or config.triton.prefer_nd_tiling + or any(node.is_foreach() for node in nodes) + ): + return None + + snodes = [subnode for node in nodes for subnode in node.get_nodes()] + if not snodes or not all(isinstance(node, SchedulerNode) for node in snodes): + return None + + if any(node.is_cpu() for node in snodes): + return None + + # The fusion search asks this for the same nodes over and over while + # pairing them up (on one model, 1160 calls over 53 distinct nodes). + # The answer is a function of the nodes' loop state, which + # _loop_state_gen identifies, so key on that. snodes are leaf + # SchedulerNodes (checked above), which the scheduler keeps for its + # lifetime, so keying on the nodes themselves retains nothing extra. + # pyrefly: ignore[missing-attribute] + cache_key = tuple((sn, sn._loop_state_gen) for sn in snodes) + cached = self._tiling_memory_cache.get(cache_key, _TILING_MEMORY_MISS) + if cached is not _TILING_MEMORY_MISS: + return cached + + analysis = analyze_memory_coalescing_for_nodes(snodes) + if analysis is None: + self._tiling_memory_cache[cache_key] = None + return None + + reduction = max(snodes, key=lambda node: int(node.is_reduction())) + _, (numel, rnumel) = reduction.group + result = SIMDScheduling.select_tiling_with_memory( + snodes, numel, rnumel, analysis + ).memory + self._tiling_memory_cache[cache_key] = result + return result + + def _reindexing_regresses_memory_coalescing( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + unfused_memory: tuple[MemoryCoalescing, ...] | None, + ) -> bool: + """Did reindexing make the fused kernel's memory access worse? + + `unfused_memory` is measured before reindexing, so this compares the two + original kernels against the single reindexed one. + """ + if unfused_memory is None: + return False + fused_memory = self._selected_tiling_memory([node1, node2]) + if fused_memory is None: + return False + + # The fused analysis omits removable intermediates, so saved + # materialization traffic offsets coalescing regressions here. + unfused_cost = sum(memory.weighted_cost() for memory in unfused_memory) + fused_cost = fused_memory.weighted_cost() + try: + dram_gbps = get_gpu_dram_gbps() + valid_dram_gbps = math.isfinite(dram_gbps) and dram_gbps > 0 + except Exception: + dram_gbps = 0 + valid_dram_gbps = False + if valid_dram_gbps: + # GB/s is numerically bytes/ns, so division converts the + # byte-equivalent costs to estimated time in nanoseconds. + unfused_time_ns = ( + unfused_cost / dram_gbps + _REINDEXING_FUSION_LAUNCH_OVERHEAD_NS + ) + fused_time_ns = fused_cost / dram_gbps + regresses = fused_time_ns > unfused_time_ns + else: + regresses = fused_cost > unfused_cost + if regresses: + loop_ordering_log.debug( + "rejecting reindex of %s and %s: unfused memory %s (cost=%d), " + "fused memory %s (cost=%d)", + node1.get_name(), + node2.get_name(), + unfused_memory, + unfused_cost, + fused_memory, + fused_cost, + ) + return True + return False + + def _try_reindex_pointwise_for_reduction( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + ) -> bool: + """ + Reindex a pointwise's iteration loops to match a reduction's + groups. After reindexing, the shared reads have identical index + expressions, enabling the codegen to CSE loads. + + Returns True if reindexing was applied. + """ + from .codegen.simd import SIMDKernel + + # Keep this consistent with shared_data_after_reordering_loop(): CPU + # reindexing is not validated yet. + if node1.is_cpu() or node2.is_cpu(): + return False + + if node1.is_foreach() or node2.is_foreach(): + return False + + if node1.is_reduction() and not node2.is_reduction(): + reduction_node, pw_node = node1, node2 + elif node2.is_reduction() and not node1.is_reduction(): + reduction_node, pw_node = node2, node1 + else: + return False + + _, groups = reduction_node.group + red_numel = typing.cast(sympy.Expr, groups[0]) + red_rnumel = typing.cast(sympy.Expr, groups[1]) + target_numel = red_numel * red_rnumel + + if not all(isinstance(sn, SchedulerNode) for sn in pw_node.get_nodes()): + return False + snodes = typing.cast(list[SchedulerNode], pw_node.get_nodes()) + + # All snodes must have the same total iteration numel matching + # the reduction's numel * rnumel so they can be reindexed identically. + if not all( + V.graph.sizevars.statically_known_equals( + sympy_product(sn._sizes[0]), target_numel + ) + for sn in snodes + ): + return False + + if not all( + SIMDKernel.is_compatible((red_numel, red_rnumel), sn.get_ranges()) + for sn in snodes + ): + return False + + # Nothing to reindex if the pointwise already uses the reduction split. + target_iter_sizes = (red_numel, red_rnumel) + if all(tuple(sn._sizes[0]) == target_iter_sizes for sn in snodes): + return False + + # Measure each node's memory access before mutating any loops, so the + # coalescing guard below can compare against the un-reindexed kernels. + unfused_memory: tuple[MemoryCoalescing, ...] | None = None + memory = tuple(self._selected_tiling_memory([node]) for node in (node1, node2)) + if all(m is not None for m in memory): + unfused_memory = typing.cast("tuple[MemoryCoalescing, ...]", memory) + + # Local rollback is still needed even with _LoopMutationTracker: this + # helper is also used by shared_data_after_reordering_loop(), where a + # failed reindex attempt returns -1 and the caller may keep evaluating + # fusion within the same can_fuse() call. + rollback_snapshot = _LoopStateSnapshot.create((pw_node,)) + + for sn in snodes: + sn.apply_loop_reindexing([red_numel, red_rnumel]) + + if isinstance(pw_node, FusedSchedulerNode): + pw_node.group = snodes[0].group + refresh_group_node_dependencies(pw_node) + + # Verify reindexing actually increases shared deps. + common_names = ( + node1.read_writes.buffer_names() & node2.read_writes.buffer_names() + ) + n1_deps = {dep.name: dep for dep in node1.read_writes.reads_and_writes()} + n2_deps = {dep.name: dep for dep in node2.read_writes.reads_and_writes()} + has_benefit = any( + self.deps_match_normalized(n1_deps[name], n2_deps[name]) + for name in common_names + ) + if not has_benefit: + rollback_snapshot.restore() + return False + + # TODO: Measure fused memory first so coalesced fusions skip per-node analysis. + # Reindexing the pointwise onto the reduction's split can make its own + # accesses uncoalesced. Undo the reindex when that costs more than the + # traffic saved by fusing. + if self._reindexing_regresses_memory_coalescing(node1, node2, unfused_memory): + rollback_snapshot.restore() + return False + + # When loop ordering is disabled, re-extract deps with + # normalize=True so variable names are canonical. This is + # safe because no further loop reordering will occur. + # Without this, reindexed deps use different var names + # (e.g. c0 vs d0) causing exact dep comparisons to fail. + if not config.loop_ordering_after_fusion: + for sn in snodes: + sn.refresh_dependencies(normalize=True, need_clear_tiling_cache=False) + if isinstance(pw_node, FusedSchedulerNode): + refresh_group_node_dependencies(pw_node) + + return True + + def unfusable_node(self, node: BaseSchedulerNode) -> bool: + """ + Is this node unfusable under any conditions. + """ + if isinstance(node, NopKernelSchedulerNode): + return not node.is_template() and not is_output_of_multi_outputs_template( + node.node + ) + if isinstance(node, ExternKernelSchedulerNode): + if isinstance(node.node, ir.UserDefinedTritonKernel): + return not node.node.can_fuse_epilogue() + return not node.is_template() and not is_output_of_multi_outputs_template( + node.node + ) + return False + + def check_prologue_fusion_heuristics_fusable( + self, + prologue_node: BaseSchedulerNode, + template_node: BaseSchedulerNode, + why: WhyNoFuse, + ) -> bool: + """ + Heuristics to avoid benchmarking predictably slow prologue fusions + """ + # user opt into more aggressive prologue fusion, don't use heuristics + if prologue_node.get_operation_names() <= V.graph.invoke_quant_ops: + return True + + read_bytes = prologue_node.get_read_buffer_sizes() + write_bytes = prologue_node.get_write_buffer_sizes() + + # Initially, only do fusions which will result in fewer memory accesses inside of the template to avoid + # potential bad cache behavior and shared memory use. + # we also want to avoid benchmarking reliably unprofitable fusions like downcasts from fp32 -> fp16 inside kernel. + # allowing gathers by allowing increasing write_bytes by small factor + # TODO - make configurable per input, for instance, bias can fuse fp32 -> fp16 profitably + + BYTES_THRESHOLD_MULTIPLIER = 1.1 + if read_bytes > (write_bytes * BYTES_THRESHOLD_MULTIPLIER): + why("prologue fusion will not increase amount of bytes read in kernel") + return False + + # we want to avoid attempting to fuse predictably unprofitable prologues + # such as increasing the unaligned reads or writes. + # TODO - would be nice to generalize this, however, we would need more explicit + # knowledge of memory access patterns in the TritonTemplate in order to know + # the stride order to check alignment. + origins = tuple( + e.target + for n in prologue_node.get_nodes() + if n.node is not None + for e in n.node.get_origins() + if e.op == "call_function" + ) + if origins == (torch.ops.aten.constant_pad_nd.default,): + why( + "prologue fusion will not increase attempt to fuse in padding bc it increases unaligned reads" + ) + return False + + def low_prec_fp(dtype: torch.dtype) -> bool: + return dtype.itemsize <= 2 and dtype.is_floating_point + + template_buf = template_node.get_template_node_or_throw() + if ( + not template_buf.is_multi_outputs_template() + and low_prec_fp(template_buf.dtype) + and not prologue_node.can_codegen_in_low_precision() + ): + why( + "prologue fusion that must be upcast to fp32 not profitable for low precision templates" + ) + return False + + return True + + def get_expand_dim_for_pointwise_nodes( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> tuple[int, SchedulerNode, sympy.Expr] | None: + """ + Fusing two small pointwise nodes significantly reduces kernel overhead + and launch overhead. However, slightly different sizes would prevent fusion. + Here, we decide if expanding sizes of one node is profitible by allowing + fusion, and returns the dimension to expand, node with smaller sizes, + and new size after expand. + """ + # only support scheduler node + if not isinstance(node1, SchedulerNode) or not isinstance(node2, SchedulerNode): + return None + + # only support computued buffer + if not ( + isinstance(node1.node, ir.ComputedBuffer) + and isinstance(node2.node, ir.ComputedBuffer) + ): + return None + + # does not support mutation yet since relying on index mod to handle + # out-of-boundary access. + if node1.has_aliasing_or_mutation() or node2.has_aliasing_or_mutation(): + return None + + # skip halide which does not support mod for index + if config.cpu_backend == "halide": + return None + + # only support pointwise nodes with the same reduction size + n1_sizes, n2_sizes = node1._sizes, node2._sizes + n1_iter_sizes, n1_reduce_sizes = n1_sizes + n2_iter_sizes, n2_reduce_sizes = n2_sizes + if ( + node1.is_reduction() + or node2.is_reduction() + or n1_reduce_sizes != n2_reduce_sizes + or len(n1_iter_sizes) != len(n2_iter_sizes) + ): + return None + + # only support nodes with 1 write for simplification + if len(node1.read_writes.writes) > 1 or len(node2.read_writes.writes) > 1: + return None + + # When memory access is small, reducing gpu kernel overhead is profitable over + # slightly larger memory access. + node1_write_memory = self.dep_size_hint(next(iter(node1.read_writes.writes))) + node2_write_memory = self.dep_size_hint(next(iter(node2.read_writes.writes))) + if ( + max(node1_write_memory, node2_write_memory) + > config.small_memory_access_threshold + ): + return None + + # does not support reinplace since `index % boundary` may lead to + # race condition + def has_reusable_buffer(node: BaseSchedulerNode) -> bool: + for read in node.read_writes.reads: + input_buf: SchedulerBuffer | SchedulerDonatedBuffer | None + if read.name in self.name_to_donated_buffer: + input_buf = self.name_to_donated_buffer[read.name] + else: + input_buf = self.name_to_buf.get(read.name) + + if ( + input_buf + and V.graph.wrapper_code.can_reuse(input_buf, node) + and not isinstance(input_buf.defining_op, NopKernelSchedulerNode) + ): + return True + return False + + if has_reusable_buffer(node1) or has_reusable_buffer(node2): + return None + + # only support nodes with 1 mismatch dimension + mismatch_dimensions = [] + for idx, (n1_size, n2_size) in enumerate(zip(n1_iter_sizes, n2_iter_sizes)): + if n1_size != n2_size: + mismatch_dimensions.append(idx) + + if len(mismatch_dimensions) != 1: + return None + + mismatch_dim = mismatch_dimensions[0] + mismatch_size1, mismatch_size2 = ( + n1_iter_sizes[mismatch_dim], + n2_iter_sizes[mismatch_dim], + ) + if V.graph.sizevars.statically_known_lt(mismatch_size1, mismatch_size2): + return mismatch_dim, node1, mismatch_size2 + elif V.graph.sizevars.statically_known_lt(mismatch_size2, mismatch_size1): + return mismatch_dim, node2, mismatch_size1 + else: + return None + + def _producer_output_names_read_by_consumer( + self, producer: BaseSchedulerNode, consumer: BaseSchedulerNode + ) -> OrderedSet[str]: + producer_buf_names = OrderedSet( + self.mutation_renames.get(name, name) + for name in producer.get_buffer_names() + ) + return OrderedSet( + name + for dep in consumer.read_writes.reads + if (name := self.mutation_renames.get(dep.name, dep.name)) + in producer_buf_names + ) + + def _nested_index_equivalent_dep_names( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + ) -> OrderedSet[str] | None: + if not NestedReduction.is_candidate(node1, node2): + return None + # These names feed both the score bridge and relaxed vertical dep + # matching. The score bridge exists only so V.choices.can_fuse does not + # reject legal equivalent-index deps before vertical legality runs, so it + # must use the same fully legal nested relation as can_fuse_vertical. + # TODO: split cheap score prefiltering from legality if this shows up in + # compile-time profiles, without letting score-only names relax legality. + if not NestedReduction.can_fuse(node1, node2): + return None + return self._producer_output_names_read_by_consumer(node1, node2) + + def _can_fuse_nested_reduction_append( + self, + grouped_node: BaseSchedulerNode, + other: BaseSchedulerNode, + pointwise_domains: Sequence[ + tuple[BaseSchedulerNode, NestedReduction.PointwiseDomain] + ], + *, + can_reorder: bool, + ) -> bool: + index_equivalent_dep_names: OrderedSet[str] = OrderedSet() + grouped_buf_names = OrderedSet( + self.mutation_renames.get(name, name) + for name in grouped_node.get_buffer_names() + ) + for sn, domain in pointwise_domains: + if domain is not NestedReduction.PointwiseDomain.PARENT_FULL: + continue + reads = ( + self.mutation_renames.get(dep.name, dep.name) + for dep in sn.read_writes.reads + ) + index_equivalent_dep_names.update( + dep_name for dep_name in reads if dep_name in grouped_buf_names + ) + # Parent-full consumers may read grouped-stage outputs through + # broadcasted parent-tile views. Relax matching only for those named + # producer outputs; all other deps use normal vertical legality. + return self._can_fuse( + grouped_node, + other, + can_reorder=can_reorder, + index_equivalent_dep_names=index_equivalent_dep_names, + ) + + def can_fuse( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + can_reorder: bool = False, + allow_mix_order_reduction: bool = True, + ) -> bool: + """Determine if node1 and node2 can be combined into a single fused node. + + Speculative loop mutations (reordering, reindexing) are automatically + rolled back if the fusion decision ultimately fails. + """ + tracker = _LoopMutationTracker.create((node1, node2)) + can_fuse = self._can_fuse_impl( + node1, + node2, + can_reorder=can_reorder, + allow_mix_order_reduction=allow_mix_order_reduction, + ) + tracker.finish(rollback=not can_fuse) + return can_fuse + + def _can_fuse_impl( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + can_reorder: bool = False, + allow_mix_order_reduction: bool = True, + ) -> bool: + """ + Determine if it is possible to combine node1 and node2 into a + single fused node. + """ + return self._can_fuse( + node1, + node2, + can_reorder=can_reorder, + allow_mix_order_reduction=allow_mix_order_reduction, + ) + + def _can_fuse( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + can_reorder: bool = False, + allow_mix_order_reduction: bool = True, + index_equivalent_dep_names: OrderedSet[str] | None = None, + ) -> bool: + if node1 is node2: + return False + if index_equivalent_dep_names is not None: + index_equivalent_dep_names = OrderedSet( + self.mutation_renames.get(name, name) + for name in index_equivalent_dep_names + ) + + # Prevent fusion across stream boundaries + if self._has_multi_stream_nodes(): + stream1 = self.get_node_stream(node1) + stream2 = self.get_node_stream(node2) + if stream1 != stream2: + return False + if self._has_mempool_nodes(): + mempool1 = self.node_to_mempool.get(node1) + mempool2 = self.node_to_mempool.get(node2) + if mempool1 != mempool2: + return False + + if isinstance(node1, FusedNestedReductions): + return node1.can_fuse_with(node2, can_reorder=can_reorder) + if isinstance(node2, FusedNestedReductions): + return False + + if isinstance(node1, FusedMixOrderReductions): + return node1.can_fuse_with(node2) + if isinstance(node2, FusedMixOrderReductions): + # We don't fuse something before a FusedMixOrderReductions + # right now + return False + + why = WhyNoFuse(node1, node2) + + if node1.is_template() and node2.has_strict_sum(): + why("template fusion does not preserve strict sum ordering") + return False + + if ( + (node1.has_strict_sum() or node2.has_strict_sum()) + and node1.is_reduction() + and node2.is_reduction() + ): + why("reduction fusion does not preserve strict sum ordering") + return False + + if node1.is_template() and self.get_backend( + node1.get_device() + ).can_fuse_multi_outputs_template(node1, node2): + return True + if node1.is_template() and self.get_backend( + node1.get_device() + ).can_fuse_reduction_epilogue(node1, node2): + return True + + if isinstance(node1, GroupedSchedulerNode) or isinstance( + node2, GroupedSchedulerNode + ): + why("grouped node must not be fused with other nodes") + return False + if isinstance(node1, NopKernelSchedulerNode) and not node1.is_template(): + why("node1 is nop") + return False + + if isinstance(node1, ExternKernelSchedulerNode): + if not isinstance(node1.node, ir.UserDefinedTritonKernel): + why("node1 is extern but not a triton kernel") + return False + + if not node1.node.can_fuse_epilogue(): + why("node1's triton kernel doesn't support epilogue fusion") + return False + + if not isinstance(node2, SchedulerNode): + why("node1 is extern but node2 is not SchedulerNode") + return False + if not isinstance(node2.node, ComputedBuffer): + why("node1 is extern but node2.node is not SchedulerNode") + return False + if not isinstance(node2.node.data, Pointwise): + why("node1 is extern but node2.node.data is not Pointwise") + return False + + if len(node1.node.mutation_outputs) != 1: + raise AssertionError( + f"expected one mutation output, got {len(node1.node.mutation_outputs)}" + ) + written_buffer_name = node1.node.mutation_outputs[0].name + + # The epilogue must be an in-place, unary pointwise operation. + # Any other tensor/s would require additional load expressions. + epilogue_reads = list(node2.read_writes.reads) + epilogue_writes = list(node2.read_writes.writes) + if ( + len(epilogue_reads) != 1 + or len(epilogue_writes) != 1 + or epilogue_reads[0].name != written_buffer_name + ): + why("epilogue is not a unary read of the output buffer") + return False + + write_dep = epilogue_writes[0] + read_dep = epilogue_reads[0] + if not isinstance(read_dep, MemoryDep): + raise AssertionError(f"expected MemoryDep, got {type(read_dep)}") + if not isinstance(write_dep, MemoryDep): + raise AssertionError(f"expected MemoryDep, got {type(write_dep)}") + if read_dep.index != write_dep.index or read_dep.size != write_dep.size: + why("epilogue's read and write indices differ") + return False + + # the epilogue depends on expressions which may not available in the user triton kernel + # (e.g. indexing exprs used not in a load) + node2_inner_fn_free_symbols = node2.node.data.inner_fn_free_symbols() + for symbol in node2_inner_fn_free_symbols: + usages = node2.node.data.collect_inner_fn_symbol_usage(symbol) + if any(usage != "load" for usage in usages): + return False + + # should be true now because we checked `can_fuse_epilogue` + if len(node1.node.mutable_args) != 1: + raise AssertionError( + f"expected one mutable arg, got {len(node1.node.mutable_args)}" + ) + + # Compare layouts, modulo dtype. We allow casting during codegen. + layout1 = node1.node.mutable_args[0].layout + layout2 = node2.node.layout + if not (isinstance(layout1, ir.Layout) and isinstance(layout2, ir.Layout)): + raise AssertionError("expected layout1 and layout2 to be ir.Layout") + if ( + layout1.size != layout2.size + or layout1.stride != layout2.stride + or layout1.device != layout2.device + ): + why("node1 and node2 uses different buf layouts") + return False + + def _is_other_node_that_references_mutation_buffer( + other_node: BaseSchedulerNode, + ): + return ( + (other_node is not node1) + and (other_node is not node2) + and written_buffer_name in other_node.used_buffer_names() + ) + + if any( + _is_other_node_that_references_mutation_buffer(node) + for node in self.nodes + ): + return False + + if ( + isinstance(node2, (ExternKernelSchedulerNode, NopKernelSchedulerNode)) + and not node2.is_template() + ): + why("node2 is extern or nop") + return False + + if node2.get_operation_names() & node1.ancestors: + why("node1 must go before node2") + return False + + if node2.is_template(): + if not _is_prologue_fusion_enabled(node2): + why("prologue fusion turned off") + return False + + if node1.is_reduction() or node1.is_template(): + why("prologue fusion only supported for pointwise nodes") + return False + + template = node2.get_template_node_or_throw() + allowed_prologue_inps = template.get_allowed_prologue_inps() + if not allowed_prologue_inps: + why("template has no allowed prologue inputs") + return False + + unsupported_prologue_args = ( + OrderedSet(inp.get_name() for inp in template.inputs) # type: ignore[union-attr] + - allowed_prologue_inps + ) + + if node1.get_buffer_names() & unsupported_prologue_args: + why("prologue fusion not implemented for kernel for these inputs") + return False + + if node1.has_aliasing_or_mutation() or ( + template.has_aliasing_or_mutation_for_prologue_fusion(node2) + ): + why("template prologue can only fuse functional pointwise nodes") + return False + + prologue_nodes = node1.get_nodes() + for node in prologue_nodes[:-1]: + node_outs = node.get_outputs() + for out in node_outs: + if not all(user.node in prologue_nodes for user in out.users): + why("template prologue can only fuse nodes with a single use") + return False + + template_snodes = ( + [node2] + if not isinstance(node2, FusedSchedulerNode) + else [n for n in node2.snodes if n.is_template()] + ) + if len(template_snodes) != 1: + raise AssertionError( + f"expected one template snode, got {len(template_snodes)}" + ) + template_snode = template_snodes[0] + + if not ( + len(prologue_nodes[-1].outputs) == 1 + and len(prologue_nodes[-1].outputs[0].users) == 1 + and prologue_nodes[-1].outputs[0].users[0].node is template_snode + ): + why( + "template prologue can only fuse nodes with a single use into template" + ) + return False + + if not self.check_prologue_fusion_heuristics_fusable(node1, node2, why): + return False + + if node1.is_template(): + atomic_add_mutation_epilogue = _can_fuse_atomic_add_template_epilogue( + node1, node2 + ) + backend = self.get_backend(node1.get_device()) + if ( + (node2.has_aliasing_or_mutation() and not atomic_add_mutation_epilogue) + or ( + node2.is_reduction() + and not backend.can_fuse_reduction_epilogue(node1, node2) + ) + or not _is_epilogue_fusion_enabled(node1) + ): + why("template epilogue not satisfied") + return False + template_buf = node1.get_template_node() + if template_buf is None: + raise AssertionError("expected template_buf to be set") + if template_buf.is_multi_outputs_template() and not isinstance( + node2.node, ir.ComputedBuffer + ): + why("multi-output template epilogue requires ComputedBuffer") + return False + + if (node1.get_buffer_names() & V.graph.no_fuse_buffer_names) or ( + node2.get_buffer_names() & V.graph.no_fuse_buffer_names + ): + why("fusion for buffer explicit disabled") + return False + device = node1.get_device() + device2 = node2.get_device() + if device != device2: + why("device mismatch (%s vs %s)", device, device2) + return False + del device2 + + if index_equivalent_dep_names is None: + index_equivalent_dep_names = self._nested_index_equivalent_dep_names( + node1, node2 + ) + shared_data_score = self._score_fusion_memory_for_can_fuse( + node1, + node2, + allow_mix_order_reduction=allow_mix_order_reduction, + index_equivalent_dep_names=index_equivalent_dep_names, + ) + + if config.expand_dimension_for_pointwise_nodes and ( + expand_analysis := self.get_expand_dim_for_pointwise_nodes(node1, node2) + ): + (expand_dim, smaller_node, expand_size) = expand_analysis + smaller_node.expand_dimension_for_pointwise_node(expand_dim, expand_size) + shared_data_score = self._score_fusion_memory_for_can_fuse( + node1, + node2, + index_equivalent_dep_names=index_equivalent_dep_names, + ) + + if ( + can_reorder + and shared_data_score < config.score_fusion_memory_threshold + and ( + config.loop_ordering_after_fusion or config.loop_reindexing_after_fusion + ) + ): + new_shared_data_score = self.shared_data_after_reordering_loop(node1, node2) + if new_shared_data_score >= 0: + shared_data_score = new_shared_data_score + + if ( + config.loop_index_inversion_in_fusion + and shared_data_score < config.score_fusion_memory_threshold + ): + new_shared_data_score = self.shared_data_after_inverting_indexing( + node1, node2 + ) + if new_shared_data_score >= 0: + shared_data_score = new_shared_data_score + + if loop_ordering_log.isEnabledFor(logging.DEBUG): + loop_ordering_log.debug( + "%s and %s has %s shared data", + node1.get_name(), + node2.get_name(), + shared_data_score, + ) + + if not V.choices.can_fuse(self, node1, node2, shared_data_score): + return False + + if node1.get_operation_names() & node2.ancestors: + # node2 depends on node1 outputs + if ( + self.can_fuse_vertical( + node1, + node2, + index_equivalent_dep_names=index_equivalent_dep_names, + ) + and V.choices.can_fuse_vertical(self, node1, node2, shared_data_score) + and self.get_backend(device).can_fuse_vertical(node1, node2) + ): + return True + + # Vertical fusion failed — the iteration domains may not + # match (e.g. pointwise reads buf[x//32] while reduction + # writes buf[x]). Try reindexing the pointwise to the + # reduction's domain and retry. + if ( + config.loop_reindexing_after_fusion + and self._try_reindex_pointwise_for_reduction(node1, node2) + ): + return ( + self.can_fuse_vertical( + node1, + node2, + index_equivalent_dep_names=index_equivalent_dep_names, + ) + and V.choices.can_fuse_vertical( + self, node1, node2, shared_data_score + ) + and self.get_backend(device).can_fuse_vertical(node1, node2) + ) + + return False + else: # nodes don't depend on each other, but may have common reads + return V.choices.can_fuse_horizontal( + self, node1, node2, shared_data_score + ) and self.get_backend(device).can_fuse_horizontal(node1, node2) + + def can_fuse_vertical( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + *, + index_equivalent_dep_names: OrderedSet[str] | None = None, + ) -> bool: + """ + Check if it is legal to fuse a consumer (node2) into a producer (node1). + + We can fuse them if all the reads of node2 either match + corresponding writes in node1, or are written by nodes that can + be scheduled before the fusion of node1 and node2. + + ``index_equivalent_dep_names`` relaxes write/read matching only for + named producer outputs; the remaining intermediate-dependency checks + still run normally. + """ + node1_buf_names = node1.get_buffer_names() + why = WhyNoFuse(node1, node2) + remaining_deps_by_name: dict[str, list[Dep]] = defaultdict(list) + + for dep in node2.unmet_dependencies: + name = self.mutation_renames.get(dep.name, dep.name) + if isinstance(dep, WeakDep) and self.fusable_weak_dep(dep, node1, node2): + continue + remaining_deps_by_name[name].append(dep) + + for cd in node1.read_writes.writes: + if not isinstance(cd, MemoryDep) and not isinstance(cd, StarDep): + continue + write_name = self.mutation_renames.get(cd.name, cd.name) + remaining = remaining_deps_by_name.get(write_name) + if remaining: + for rd in remaining: + if isinstance(cd, MemoryDep) and self.fusable_read_and_write( + rd.rename(self.mutation_renames), + cd, + allow_index_equivalence=( + index_equivalent_dep_names is not None + and write_name in index_equivalent_dep_names + ), + ): + remaining.remove(rd) # noqa: B909 + elif isinstance(cd, StarDep) and ( + self.fusable_stardep_write_and_read_on_empty_tensor( + rd, cd, node1.node + ) + ): + remaining.remove(rd) # noqa: B909 + + remaining_deps = OrderedSet( + dep.name + for dep in itertools.chain.from_iterable(remaining_deps_by_name.values()) + ) + + if remaining_deps & node1_buf_names: + # MemoryDeps didn't match and read different locations of the same buffer. + # Examples here include: + # - MemoryDep("foo", x) != MemoryDep("foo", x + 1) + # - MemoryDep("foo", x) != StarDep("foo") + why("memory deps did not match") + return False + + node1_op_names = node1.get_operation_names() + for name in remaining_deps: + op_name = self.name_to_buf[name].defining_op_name() + if node1_op_names & self.name_to_fused_node[op_name].ancestors: + why("intermediate nodes between node1 & node2") + return False + + return True + + def fusable_weak_dep( + self, weak_dep: WeakDep, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + if weak_dep.name not in node1.get_buffer_names(): + return False + + # A weak dep can be fused if and only if the fused operation acts inplace + # on the buffer being mutated. i.e. the same index is being read then mutated + mutating_writes = [ + write + for write in node2.read_writes.writes + if write.name == weak_dep.mutating_buf + ] + if len(mutating_writes) != 1: + return False + write = mutating_writes[0] + if isinstance(write, StarDep): + return False + if not isinstance(write, MemoryDep): + raise AssertionError("expected write to be a MemoryDep") + + if free_symbol_is_type(write.index, SymT.TMP): + return False + + # Non-injective scatter: range vars absent from write index mean + # multiple iterations hit the same location. Can't fuse the reader + # in or it will see partially-written state between iterations. + if not OrderedSet(write.var_names) <= write.index.free_symbols: + return False + + real_name = self.mutation_real_name[weak_dep.mutating_buf] + relevant_reading_nodes = [node1] + if isinstance(node1, ForeachKernelSchedulerNode): + relevant_reading_nodes = node1.snodes + num_concurrent_reads = 0 + for reading_node in relevant_reading_nodes: + relevant_reads = [ + read + for read in reading_node.read_writes.reads + if read.name == real_name + ] + if not relevant_reads: + continue + device = node2.get_device() + if device is not None and ( + (device.type == "cpu" and config.cpu_backend == "halide") + or (device.type == "cuda" and config.cuda_backend == "halide") + ): + # Halide autoschedules may overcompute output tiles via + # TailStrategy::ShiftInwards. That is only semantics-preserving + # if the output is not also an input read by the fused producer. + return False + num_concurrent_reads += 1 + if not all( + isinstance(read, MemoryDep) + and not free_symbol_is_type(read.index, SymT.TMP) + and read.index == write.index + and read.size == write.size + for read in relevant_reads + ): + return False + return num_concurrent_reads <= 1 + + @staticmethod + def _same_index_with_prefix_size(read: MemoryDep, write: MemoryDep) -> bool: + return ( + read.index == write.index + and len(read.size) >= len(write.size) + and read.size[: len(write.size)] == write.size + ) + + # StarDep doesn't match MemoryDep, and indirect indexing is not fusible. + def fusable_read_and_write( + self, read: Dep, write: MemoryDep, *, allow_index_equivalence: bool = False + ) -> bool: + """Return whether a producer write can satisfy a consumer read. + + The default path accepts exact matches, plus the existing + loop-ordering-normalized exact match when that config is enabled. + ``allow_index_equivalence`` only runs after those checks fail. It keeps + the producer write dense and injective, then accepts conservative + consumer-side equivalent reads such as broadcasts or normalized + loop-order changes. + """ + if isinstance(read, MemoryDep): + if ( + read.name != write.name + or free_symbol_is_type(read.index, SymT.TMP) + or free_symbol_is_type(write.index, SymT.TMP) + ): + return False + + original_read = read + original_write = write + + # Operations like index_add_, scatter_add_, etc. require global + # synchronization - all threads must complete writes before any reads. + # These cannot be safely fused into the same kernel. Atomic modes + # and TMA stores require synchronization barriers. + if self.mode_requires_synchronization(original_write.mode): + return False + + # Preserve the normal exact-dependency path before any optional + # normalization or relaxed equivalence checks. + if self._same_index_with_prefix_size(original_read, original_write): + return True + + if config.loop_ordering_after_fusion and read.num_vars != write.num_vars: + # Need merge loops if we do loop ordering after fusion since + # we have not merged the loops yet when creating the scheduler + # nodes. + read = read.normalize() + write = write.normalize() + + # Re-check after optional loop normalization. The first exact + # match preserves original deps, including gapped layouts; this + # path only covers deps that become exact after loop vars merge. + if self._same_index_with_prefix_size(read, write): + return True + + if not allow_index_equivalence: + return False + + return self._fusable_read_after_index_equivalence( + original_read, original_write + ) + elif isinstance(read, StarDep): + if ( + read.mode == write.mode + and write.mode is not None + and read.name == write.name + ): + return True + return False + + def _fusable_read_after_index_equivalence( + self, read: MemoryDep, write: MemoryDep + ) -> bool: + # Relaxed matching is only for consumer-side reshapes/broadcasts. + # If a write var is absent from the write index, the producer itself + # broadcasts multiple loop iterations to the same address. + if not OrderedSet(write.var_names) <= write.index.free_symbols: + return False + # Once read/write indices differ, require the producer to write a + # dense logical region. Otherwise gaps or aliases in the producer + # could be hidden by a consumer-side broadcast. + if not ( + write.normalize().is_contiguous() + or write.normalize_with_stride_order().is_contiguous() + ): + return False + + return self.deps_match_normalized( + read, write + ) or self._fusable_read_after_broadcast(read, write) + + @staticmethod + def _fusable_read_after_broadcast(read: MemoryDep, write: MemoryDep) -> bool: + """Match conservative broadcasted read forms. + + This handles two nested-reduction dependency shapes: + + - Pure broadcast dims absent from the read index: + + read: d1, {d0: 1024, d1: 16} + write: d0, {d0: 16} + + - Same-rank expanded dims used through a quotient: + + read: 32*d0 + FloorDiv(d1, 128), {d0: 128, d1: 4096} + write: 32*d0 + d1, {d0: 128, d1: 32} + + Producer-side broadcast and non-dense writes are rejected before this + helper, so these cases only relax consumer-side broadcasts. + """ + # Strategy 1: remove read loop vars that do not affect the address, + # then compare the normalized access against the producer write. + read_vars = tuple( + var for var in read.var_names if var in read.index.free_symbols + ) + if len(read_vars) != read.num_vars: + read_ranges = {var: read.ranges[var] for var in read_vars} + read = MemoryDep( + read.name, + read.index, + tuple(read_ranges), + tuple(read_ranges.values()), + read.mode, + ) + if read.normalize() == write.normalize(): + return True + + if read.num_vars != write.num_vars: + return False + + # Strategy 2: split a larger read axis into (write axis, tail), then + # simplify with the tail range. This only matches if the tail + # disappears from the final index. + sizevars = V.graph.sizevars + write_vars = tuple( + sympy.Symbol(f"_fusable_broadcast_{i}", integer=True, nonnegative=True) + for i in range(read.num_vars) + ) + replacements: dict[sympy.Expr, sympy.Expr] = {} + tail_ranges: dict[sympy.Symbol, sympy.Expr] = {} + for read_var, read_size, write_var, write_size in zip( + read.var_names, read.size, write_vars, write.size + ): + if sizevars.statically_known_equals(read_size, write_size): + replacements[read_var] = write_var + continue + + if not sizevars.statically_known_equals( + sympy.Mod(read_size, write_size), 0 + ): + return False + factor = sizevars.simplify(FloorDiv(read_size, write_size)) + if not sizevars.statically_known_gt(factor, 1): + return False + + tail_var = sympy.Symbol( + f"_fusable_broadcast_tail_{len(tail_ranges)}", + integer=True, + nonnegative=True, + ) + replacements[read_var] = write_var * factor + tail_var + tail_ranges[tail_var] = factor + + if not tail_ranges: + return False + + read_index = sizevars.simplify_with_ranges( + sympy_subs(read.index, replacements), + {**dict(zip(write_vars, write.size)), **tail_ranges}, + ) + write_index = sympy_subs(write.index, dict(zip(write.var_names, write_vars))) + return sizevars.statically_known_equals(read_index, write_index) + + # on tensors that are "empty" (i.e. with undefined values), + # we relax the conditions for fusion and additionally allow matching a writing StarDep with any read dep. + # This makes use of the fact that `f(UB) = UB`. + def fusable_stardep_write_and_read_on_empty_tensor( + self, read: Dep, write: StarDep, writing_node: ir.Operation | None + ) -> bool: + if not isinstance(writing_node, ir.UserDefinedTritonKernel): + return False + if not writing_node.can_fuse_epilogue(): + return False + read_name = self.mutation_renames.get(read.name, read.name) + write_name = self.mutation_renames.get(write.name, write.name) + if isinstance(write, StarDep) and read_name == write_name: + return True + return False + + @staticmethod + def deps_match_normalized(dep1: Dep, dep2: Dep) -> bool: + """Check if two deps refer to the same access pattern after normalization. + + Handles the case where FusedSchedulerNodes have more loop vars + than a single SchedulerNode (e.g., 3 vars vs 2) by falling back + to normalize() which merges loops before comparing. + """ + if not isinstance(dep1, MemoryDep) or not isinstance(dep2, MemoryDep): + return False + if dep1 == dep2: + return True + if dep1.num_vars == dep2.num_vars: + return ( + dep1.normalize_with_stride_order() == dep2.normalize_with_stride_order() + ) + return dep1.normalize() == dep2.normalize() + + def dep_size_hint(self, dep: Dep, count_bytes: bool = True) -> int: + return V.graph.get_dep_size_hint(dep, count_bytes) + + def _score_fusion_memory_by_fusable_read_write( + self, + producer: BaseSchedulerNode, + consumer: BaseSchedulerNode, + count_bytes: bool = True, + index_equivalent_dep_names: OrderedSet[str] | None = None, + ) -> int: + """Score vertical producer-output deps missed by exact dep scoring. + + Exact scoring is set-intersection based, but vertical legality can also + accept normalized equivalent read/write deps. Give those pairs a memory + score so heuristics do not discard them before legality runs. + """ + if not (producer.get_operation_names() & consumer.ancestors): + return 0 + + reads = list(consumer.read_writes.reads) + matched_reads: OrderedSet[int] = OrderedSet() + score = 0 + for write in producer.read_writes.writes: + if not isinstance(write, MemoryDep): + continue + write_name = self.mutation_renames.get(write.name, write.name) + for i, read in enumerate(reads): + if i in matched_reads: + continue + if self.fusable_read_and_write( + read.rename(self.mutation_renames), + write, + allow_index_equivalence=( + index_equivalent_dep_names is not None + and write_name in index_equivalent_dep_names + ), + ): + matched_reads.add(i) + score += max( + self.dep_size_hint(read, count_bytes), + self.dep_size_hint(write, count_bytes), + ) + break + return score + + def _score_fusion_memory_for_can_fuse( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + allow_mix_order_reduction: bool = True, + index_equivalent_dep_names: OrderedSet[str] | None = None, + ) -> int: + score = self.score_fusion_memory( + node1, + node2, + allow_mix_order_reduction=allow_mix_order_reduction, + ) + if not isinstance(score, int): + raise AssertionError(f"expected score to be int, got {type(score)}") + if score == 0 and index_equivalent_dep_names: + score = self._score_fusion_memory_by_fusable_read_write( + node1, + node2, + index_equivalent_dep_names=index_equivalent_dep_names, + ) + return score + + @overload + def score_fusion_memory( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + count_bytes: bool = ..., + return_is_mix_order_reduction: Literal[False] = ..., + allow_mix_order_reduction: bool = ..., + ) -> int: ... + + @overload + def score_fusion_memory( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + count_bytes: bool = ..., + return_is_mix_order_reduction: Literal[True] = ..., + allow_mix_order_reduction: bool = ..., + ) -> tuple[int, int, bool]: ... + + def score_fusion_memory( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + count_bytes: bool = True, + return_is_mix_order_reduction: bool = False, + allow_mix_order_reduction: bool = True, + ) -> int | tuple[int, int, bool]: + """ + The first term in our fusion score that estimates number of saved + memory operations. + + This function scores fusion candidates based on shared memory access patterns. + Higher scores indicate better fusion candidates. + + Scoring strategy: + 1. If nodes share exact memory deps (same buffer + same indexing), return + the sum of shared dep sizes (original behavior). + 2. If no dependency score remains, check for same-buffer reads with + different indexing (e.g., split operations reading different slices). + - Give bonus if nodes read from exactly the same set of buffers + - Score based on overlap ratio: common_buffer_size / total_read_size + - High overlap (>50%) suggests good cache locality benefit from fusion + """ + + def _construct_return_value( + score, buffer_overlap_score, is_mix_order_reduction + ): + if return_is_mix_order_reduction: + return (score, buffer_overlap_score, is_mix_order_reduction) + return score + buffer_overlap_score + + if allow_mix_order_reduction and MixOrderReduction.can_fuse(node1, node2): + # The fusion score for mix order reduction only count + # numel so far. It's actually fine. This makes other fusions + # sharing the same amount of numels go first; but make + # fusions only share weight/bias go later. + score = MixOrderReduction.get_fusion_score(node1, node2) + return _construct_return_value(score, 0, True) + + # For UserDefinedTritonKernel, the write deps are StarDep that won't + # match the epilogue's MemoryDep via set intersection. For templates, + # view/reshape between the template output and epilogue can produce + # different index expressions that don't match via set intersection. + # Fall back to name-based matching so that the fusion score reflects + # the actual shared buffers. + if ( + ( + isinstance(node1.node, ir.UserDefinedTritonKernel) + and node1.node.can_fuse_epilogue() + ) + or node1.is_template() + or node2.is_template() + ): + node1_deps = node1.read_writes.reads | node1.read_writes.writes + node2_deps = node2.read_writes.reads | node2.read_writes.writes + + def _match(dep1: Dep, dep2: Dep): + if dep1 == dep2: + return True + if isinstance(dep1, (StarDep, MemoryDep)) and isinstance( + dep2, (StarDep, MemoryDep) + ): + return dep1.name == dep2.name + return False + + score = 0 + for node1_dep in node1_deps: + for node2_dep in node2_deps: + if _match(node1_dep, node2_dep): + score += max( + self.dep_size_hint(node1_dep), self.dep_size_hint(node2_dep) + ) + + return _construct_return_value(score, 0, False) + + node1_deps = node1.read_writes.reads | node1.read_writes.writes + node2_deps = node2.read_writes.reads | node2.read_writes.writes + if len(node1_deps) > len(node2_deps): + node1_deps, node2_deps = node2_deps, node1_deps + + common_memory_deps = [dep for dep in node1_deps if dep in node2_deps] + score = sum(self.dep_size_hint(dep, count_bytes) for dep in common_memory_deps) + if score: + return _construct_return_value(score, 0, False) + + # This is a horizontal/common-read locality heuristic, not a + # producer-consumer dependency match. + buffer_overlap_score = 0 + if score == 0 and self._can_use_buffer_overlap_scoring(node1, node2): + buffer_overlap_score = self._score_fusion_memory_by_buffer_overlap( + node1, node2 + ) + + return _construct_return_value(score, buffer_overlap_score, False) + + def _can_use_buffer_overlap_scoring( + self, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + ) -> bool: + """ + Check if buffer overlap scoring should be used for this node pair. + + Buffer overlap scoring handles split/cat patterns where nodes read from + the same buffer at different indices. We skip it when: + - Either node is a reduction (different memory access patterns) + - Either node is a template + - Both nodes are prologue/epilogue candidates for the same template, + because horizontal fusion would prevent them from being absorbed + into the template kernel. For example, in: + q = a[:64, :]; k = a[64:, :] + return mm(q + 2, k - 2) + "q + 2" and "k - 2" both read from `a` and would get a high overlap + score, but fusing them horizontally prevents prologue fusion into mm + (resulting in 2 kernels instead of 1). + + We allow buffer overlap scoring when: + - The node outputs are not actually in the template's allowed_prologue_inps, + meaning they can't be prologue-fused anyway, so horizontal fusion doesn't + prevent any optimization opportunity. + """ + if node1.is_reduction() or node2.is_reduction(): + return False + if node1.is_template() or node2.is_template(): + return False + + if config.max_autotune or config.max_autotune_gemm: + node1_outputs = node1.get_outputs() + node2_outputs = node2.get_outputs() + + # Early return if either node has no outputs + if not node1_outputs or not node2_outputs: + return True + + node1_output_names = OrderedSet(buf.get_name() for buf in node1_outputs) + node2_output_names = OrderedSet(buf.get_name() for buf in node2_outputs) + + # Find templates that consume node1's outputs via buffer users + # and check if the outputs are actually prologue-fusable + node1_prologue_eligible_template_users: OrderedSet[BaseSchedulerNode] = ( + OrderedSet() + ) + for buf in node1_outputs: + for user in buf.users: + if ( + isinstance(user.node, BaseSchedulerNode) + and user.node.is_template() + and _is_prologue_fusion_enabled(user.node) + ): + # Check if this output is actually in the template's + # allowed_prologue_inps. If not, fusing horizontally + # won't prevent any prologue fusion opportunity. + template_node = user.node.get_template_node() + if template_node is not None and isinstance( + template_node, ir.TritonTemplateBuffer + ): + allowed_inps = template_node.get_allowed_prologue_inps() + if node1_output_names & allowed_inps: + node1_prologue_eligible_template_users.add(user.node) + else: + # Conservative: assume it could be a prologue candidate + node1_prologue_eligible_template_users.add(user.node) + + # Check if any of node1's prologue-eligible template users also consume + # node2's outputs in a prologue-eligible way + if node1_prologue_eligible_template_users: + for buf in node2_outputs: + for user in buf.users: + if ( + isinstance(user.node, BaseSchedulerNode) + and user.node.is_template() + and user.node in node1_prologue_eligible_template_users + ): + # Also verify node2's output is prologue-eligible + template_node = user.node.get_template_node() + if template_node is not None and isinstance( + template_node, ir.TritonTemplateBuffer + ): + allowed_inps = template_node.get_allowed_prologue_inps() + if node2_output_names & allowed_inps: + return False + else: + # Conservative: block fusion + return False + + for node in (node1, node2): + for dep in node.read_writes.reads: + producer = self.name_to_fused_node.get(dep.name) + if ( + producer is not None + and producer.is_template() + and _is_epilogue_fusion_enabled(producer) + ): + return False + + return True + + def _score_fusion_memory_by_buffer_overlap( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> int: + """ + Score fusion based on buffer name overlap when exact dep matching fails. + + This handles the split/cat fusion case where nodes read from the same buffer + but at different indices (e.g., different slices from a split operation). + + Scoring logic: + - If nodes read from exactly the same buffers: high bonus (encourages fusion) + - For common buffers: score based on overlap ratio + - overlap_ratio = common_buffer_size / + max(node1_total_reads, node2_total_reads) + - If overlap_ratio > threshold (e.g., 0.5): give proportional score + - If overlap_ratio < threshold: minimal/no score (not worth fusing) + + Note on dynamic shapes: + - When deps have unbacked symbols (dynamic shapes), dep_size_hint returns 0 + - In this case, we use count * 10 as a proxy for size + - This ensures fusion still works for models with dynamic batch sizes + + Note on multiple deps from same buffer: + - A node may have multiple MemoryDep entries for the same buffer name + (e.g., 4 split reads from arg0_1 at different indices) + - We sum ALL dep sizes for each buffer, not just take max + - This ensures overlap ratio is calculated correctly when nodes read + multiple slices from the same underlying buffer + """ + # Fallback size when dep_size_hint returns 0 (e.g., unbacked symbols) + FALLBACK_DEP_SIZE = 10 + + def get_dep_size(dep: Dep) -> int: + size = self.dep_size_hint(dep) + return size if size > 0 else FALLBACK_DEP_SIZE + + node1_read_names = OrderedSet(dep.name for dep in node1.read_writes.reads) + node2_read_names = OrderedSet(dep.name for dep in node2.read_writes.reads) + + # Early exit if no common buffer names + common_names = node1_read_names & node2_read_names + + if not common_names: + return 0 + + # Calculate total read sizes for each node (sum of ALL deps) + node1_total_read_size = sum( + get_dep_size(dep) for dep in node1.read_writes.reads + ) + node2_total_read_size = sum( + get_dep_size(dep) for dep in node2.read_writes.reads + ) + + max_total_read_size = max(node1_total_read_size, node2_total_read_size) + if max_total_read_size == 0: + return 0 + + # Calculate total reads from common buffers for each node + # Sum ALL deps for each common buffer name + # (handles multiple reads from same buffer) + node1_common_read_size = sum( + get_dep_size(dep) + for dep in node1.read_writes.reads + if dep.name in common_names + ) + node2_common_read_size = sum( + get_dep_size(dep) + for dep in node2.read_writes.reads + if dep.name in common_names + ) + + # Use max of the two as the common buffer size estimate + # This represents how much data is being read from shared buffers + common_read_buffer_size = max(node1_common_read_size, node2_common_read_size) + + # Calculate overlap ratio + overlap_ratio = common_read_buffer_size / max_total_read_size + # Scale score by overlap ratio and common buffer size + # Higher overlap = higher score + # Larger common buffer = higher score (more cache benefit) + return ( + common_read_buffer_size if overlap_ratio >= config.min_overlap_ratio else 0 + ) + + def get_possible_fusions_with_highest_priority( + self, possible_fusions: list[tuple[BaseSchedulerNode, BaseSchedulerNode]] + ) -> list[tuple[BaseSchedulerNode, BaseSchedulerNode]]: + # Group the possible fusions based on their priority from the backend. + # Only return the group of possible fusions with highest priority. + if len(possible_fusions) == 0: + return possible_fusions + possible_fusions_group_by_priority: dict[ + int, list[tuple[BaseSchedulerNode, BaseSchedulerNode]] + ] = {} + + for node1, node2 in possible_fusions: + if node1.get_device() != node2.get_device(): + raise AssertionError( + "expected node1 and node2 to be on the same device" + ) + device = node1.get_device() + fusion_pair_priority = int( + self.get_backend(device).get_fusion_pair_priority(node1, node2) + ) + if fusion_pair_priority not in possible_fusions_group_by_priority: + possible_fusions_group_by_priority[fusion_pair_priority] = [ + (node1, node2), + ] + else: + possible_fusions_group_by_priority[fusion_pair_priority].append( + (node1, node2) + ) + # return the possible fusions with highest priority + possible_fusions_with_highest_priority = min( + possible_fusions_group_by_priority.items(), key=operator.itemgetter(0) + )[1] + if len(possible_fusions_with_highest_priority) <= 0: + raise AssertionError( + "expected at least one possible fusion with highest priority" + ) + return possible_fusions_with_highest_priority + + def score_fusion_key( + self, nodes: tuple[BaseSchedulerNode, BaseSchedulerNode] + ) -> Any: + """ + Shim for list.sort(key=...) + """ + return V.choices.score_fusion(self, *nodes) + + def compute_last_usage(self) -> None: + """ + Populate node.last_usage recursively (also for the nodes within a FusedSchedulerNode) + """ + + future_used_buffers = OrderedSet(V.graph.get_output_names()) + + for node in reversed(self.nodes): + node.set_last_usage(future_used_buffers, self.mutation_real_name) + future_used_buffers.update(node.last_usage) + + def free_buffers(self) -> None: + """Free any buffers that are no longer needed""" + for name in sorted( + self.buffer_names_to_free + - V.graph.removed_buffers + - V.graph.wrapper_code.freed # type: ignore[has-type] + ): + if name in self.name_to_buf: + buf = self.name_to_buf[name] + if buf.can_free(): + V.graph.wrapper_code.codegen_free(buf.node) + elif name in V.graph.graph_inputs: + inp = V.graph.graph_inputs[name] + if isinstance(inp, ir.TorchBindObject): + V.graph.wrapper_code.codegen_free(inp) + elif isinstance(inp, (ir.GeneratorState, ir.OpaqueObjectState)): + continue + else: + storage = inp.data + if not ( + isinstance(storage, ir.StorageBox) and storage.is_input_buffer() + ): + raise AssertionError( + "expected storage to be an ir.StorageBox input buffer" + ) + V.graph.wrapper_code.codegen_free(storage.data) + + self.buffer_names_to_free.clear() + + def flush(self) -> None: + for backend in self.backends.values(): + backend.flush() + self.free_buffers() + + def codegen_extern_call( + self, + scheduler_node: BaseSchedulerNode, + ) -> None: + if not isinstance( + scheduler_node, + (ExternKernelSchedulerNode, FusedExternTritonKernelSchedulerNode), + ): + raise AssertionError( + "expected an ExternKernelSchedulerNode or FusedExternTritonKernelSchedulerNode" + ) + # 'decide_inplace_update' stores the inplace update decisions in + # the current kernel from where 'allocate' retrieve those decisions. + # We have to make sure there is a non-NULL kernel handler to store + # those inplace update decisions. + counters["inductor"]["extern_calls"] += 1 + with V.set_kernel_handler(Kernel(increase_kernel_count=False)): + scheduler_node.decide_inplace_update() + scheduler_node.mark_run() + scheduler_node.codegen(V.graph.wrapper_code) + self.free_buffers() + + def create_backend(self, device: torch.device) -> BaseScheduling: + if is_gpu(device.type) and device.index is None: + raise AssertionError(f"{device} should have been normalized in lowering") + V.graph.add_device_info(device) + + device_scheduling = get_scheduling_for_device(device.type) + if device_scheduling is None: + raise RuntimeError(f"Unsupported device type: {device.type}") + + if not has_triton(): + if ( + device.type == "cuda" + and (device_props := torch.cuda.get_device_properties(device)).major < 7 + ): + raise GPUTooOldForTriton(device_props, inspect.currentframe()) + elif is_gpu(device.type) and not device.type == "mps": + raise TritonMissing(inspect.currentframe()) + + return device_scheduling(self) + + def get_backend(self, device: torch.device | None) -> BaseScheduling: + if device is None: + raise AssertionError("expected device to be set") + if device not in self.backends: + self.backends[device] = self.create_backend(device) + return self.backends[device] + + def enter_context(self, node: BaseSchedulerNode) -> None: + def get_order(n: torch.fx.Node) -> int: + if n not in self.origin_to_index: + self.origin_to_index.update({n: i for i, n in enumerate(n.graph.nodes)}) + return self.origin_to_index[n] + + # Use a dict to have ordering + origins = { + (get_order(e), e): None + for n in node.get_nodes() + if n.node is not None + for e in n.node.get_origins() + } + origins = list(origins.keys()) + if origins: + _, last = max(origins, key=operator.itemgetter(0)) + V.graph.wrapper_code.enter_context(last) + + def can_buffer_be_removed_through_fusion( + self, name: str, fused_node_names: OrderedSet[str] + ) -> bool: + try: + users = self.name_to_buf[name].users + except KeyError: + return False + return ( + all(user.is_weak or user.get_name() in fused_node_names for user in users) + and name not in self.mutation_renames + and name not in self.mutation_real_name + ) + + def should_partition(self, node: BaseSchedulerNode) -> str | None: + """ + Return the reason why we should partition the inductor graph on this node, + or None if the node is cudagraphable. + """ + + # Allow users to manually specify if a node should be partitioned + # Can only do this for FallbackKernels + ir_node = node.node + if isinstance(ir_node, torch._inductor.ir.FallbackKernel) and ( + op := ir_node.op_overload + ): + op_overload_packet_name, op_overload_name = get_op_names(op) + if ( + op_overload_packet_name in config.custom_should_partition_ops + or op_overload_name in config.custom_should_partition_ops + ): + if not isinstance(op, torch._ops.OpOverload): + raise AssertionError("expected op to be a torch._ops.OpOverload") + return f"custom partition op: {op_overload_name}" + + # When not using cudagraphs, keep all kernels in the `call` function + # instead of graph partition functions, since graph partition only brings + # benefit to cudagraph + if ( + not torch._inductor.config.triton.cudagraphs + and _unstable_customized_partition_wrapper.wrapper is None + ): + return "partition includes all ops when cudagraphs is disabled" + + if isinstance(node, FusedSchedulerNode): + for snode in node.snodes: + reason = self.should_partition(snode) + if reason: + return reason + return None + + if node.node is None: + raise AssertionError("expected node.node to be set") + + if not node.is_gpu(): + return f"{node.get_device()} ops" + + if isinstance(node.node, ir.DeviceCopy): + return "DeviceCopy ops" + + if isinstance(node.node, ir.Switch): + return "Switch ops" + + if getattr(node.node, "unbacked_bindings", None): + return "unbacked binding ops" + + if is_cudagraph_unsafe_op(node.node): + return "CUDAGraph-unsafe custom ops" + + if reason := self._uses_cudagraph_unsafe_unbacked_symint(node): + return reason + + # Partition around nodes with dynamic shapes when cudagraph_skip_dynamic_graphs is enabled + if config.triton.cudagraph_skip_dynamic_graphs: + if get_scheduler_node_symbol_uses(node): + return "dynamic shape ops" + + return None + + @cache_on_self + def _get_cudagraph_unsafe_unbacked_symints(self) -> OrderedSet[sympy.Symbol]: + """ + Collect output unbacked symints from ops in config.cudagraph_unsafe_unbacked_ops. + """ + unsafe_symints: OrderedSet[sympy.Symbol] = OrderedSet() + + if not config.cudagraph_unsafe_unbacked_ops: + return unsafe_symints + + for node in self.nodes: + ir_node = node.node + if ir_node is None: + continue + + if not isinstance(ir_node, torch._inductor.ir.FallbackKernel): + continue + + op = ir_node.op_overload + if op is None: + continue + + op_overload_packet_name, op_overload_name = get_op_names(op) + if ( + op_overload_packet_name not in config.cudagraph_unsafe_unbacked_ops + and op_overload_name not in config.cudagraph_unsafe_unbacked_ops + ): + continue + + for sym in ir_node.get_unbacked_symbol_defs(): + sym = V.graph.sizevars.simplify(sym) + if symbol_is_type(sym, (SymT.UNBACKED_INT, SymT.UNBACKED_FLOAT)): + unsafe_symints.add(sym) + + return unsafe_symints + + def _uses_cudagraph_unsafe_unbacked_symint( + self, node: BaseSchedulerNode + ) -> str | None: + unsafe_symints = self._get_cudagraph_unsafe_unbacked_symints() + if not unsafe_symints: + return None + + node_symbols = get_scheduler_node_symbol_uses(node) + + for sym in node_symbols: + simplified_sym = V.graph.sizevars.simplify(sym) + for free_sym in simplified_sym.free_symbols: + if free_sym in unsafe_symints: + return f"uses cudagraph-unsafe unbacked symint: {free_sym}" + + return None + + def get_name_to_nodes( + self, + ) -> dict[str, ir.IRNode | ir.TorchBindObject | sympy.Expr]: + """ + Return a mapping from name strings to the corresponding graph inputs or + base scheduler node outputs. + """ + name_to_node: dict[str, ir.IRNode | ir.TorchBindObject | sympy.Expr] = {} + name_to_node.update(V.graph.graph_inputs) + + for node in self.nodes: + for name, scheduler_buffer in node.outputs_by_name.items(): + name_to_node[name] = scheduler_buffer.node + + return name_to_node + + def compute_graph_partition_maps( + self, + signatures: list[GraphPartitionSignature], + ) -> None: + """ + computes a mapping from partition input/output indices to graph input/output + indices for each partition. + """ + name_to_graph_input_index = { + name: idx for idx, name in enumerate(V.graph.graph_inputs) + } + name_to_graph_output_indices: dict[str, list[int]] = defaultdict(list) + for idx, name in enumerate(V.graph.get_output_names()): + name_to_graph_output_indices[name].append(idx) + + V.graph.partition_maps = [] + for partition_id, signature in enumerate(signatures): + if signature.skip_cudagraph: + # Note: [Graph Partition Map for CUDAGraph] + # number of partition map should be the same as the number of generated + # partition functions. This assumption will be used when cudagraphify + # each partition function. + continue + + input_mapping = [] + for name in signature.input_nodes: + input_mapping.append(name_to_graph_input_index.get(name)) + + output_mapping = [] + for node in signature.output_nodes: + output_mapping.append( + name_to_graph_output_indices.get(node.get_name(), []) + ) + + V.graph.partition_maps.append( + GraphPartitionMap( + partition_id, + input_mapping, + output_mapping, + signature.constant_names, + ) + ) + + def get_graph_partition_symbol_inputs( + self, + partition: PartitionType, + input_nodes: dict[str, ir.IRNode | ir.TorchBindObject | sympy.Expr], + ) -> OrderedSet[sympy.Symbol]: + """ + Returns all symbol inputs which are required to be in scope to successfully + perform codegen for this graph partition, including: + - free symbols used in partition nodes + - free symbols in partition input/node shapes, strides, and offsets. This is needed + for recording cudagraphs for tensors with dynamic shapes. + """ + + def get_input_node_symbols( + node: ir.IRNode | sympy.Expr | ir.TorchBindObject, + ) -> OrderedSet[sympy.Symbol]: + """ + Gets symbols used in input node shapes, strides, and offsets. + """ + if isinstance(node, ir.TorchBindObject): + # TorchBindObject does not involve dynamic shapes yet + return OrderedSet() + elif isinstance(node, ir.IRNode): + return get_layout_symints(node) + else: + # node cannot be sympy.Expr since node comes from read_writes and + # read_writes does not contain sympy.Expr + raise NotImplementedError(f"Unsupported input node type: {type(node)}") + + def filter_symbols( + symbols: OrderedSet[sympy.Symbol], + ) -> OrderedSet[sympy.Symbol]: + """ + Filters a set of symbols that are required for codegen. Skip symbols + that are always internal to kernels, such as SymT.TMP, SymT.INDEX, + and SymT.R0_INDEX. + """ + return OrderedSet( + s + for s in symbols + if symbol_is_type( + s, + ( + SymT.SIZE, + SymT.FLOAT, + SymT.UNBACKED_INT, + SymT.UNBACKED_FLOAT, + ), + ) + ) + + candidate_symbols: OrderedSet[sympy.Symbol] = OrderedSet().union( + *(get_scheduler_node_symbol_uses(node) for node in partition) + ) + candidate_symbols.update( + *(get_input_node_symbols(node) for node in input_nodes.values()) + ) + + candidate_symbols = filter_symbols(candidate_symbols) + + res: OrderedSet[sympy.Symbol] = OrderedSet() + for s in candidate_symbols: + symplified_s = V.graph.sizevars.simplify(s) + # use free_symbols only when s is simplified to an Integer or expr + res.update(symplified_s.free_symbols) + + return OrderedSet(sorted(res, key=operator.attrgetter("name"))) + + def get_graph_partition_signature( + self, partitions: list[PartitionType], skip_cudagraphs: list[bool] + ) -> list[GraphPartitionSignature]: + """ + Gets signature for each graph partition, including input nodes, output nodes, and + whether deallocating an input within graph partition. + """ + signatures = [] + + unmet_output_names = OrderedSet(V.graph.get_output_names()) + name_to_node = self.get_name_to_nodes() + + def is_unallocated_buffer(buf_name: str) -> bool: + """ + Checks if buf_name resolves to a NoneLayout buffer (following mutation_real_name). + Buffers with NoneLayout are not allocated so graph partition should not + take them as inputs or outputs. + """ + buf = self.name_to_buf.get(buf_name, None) + + if buf is None: + return False + + if isinstance(buf.node.layout, NoneLayout): + # If there's a mutation real name, check the underlying buffer + # This handles both MutationOutput and other mutation ops like + # IndexPutFallback that have NoneLayout but mutate real buffers + if real_name := self.mutation_real_name.get(buf_name, None): + return is_unallocated_buffer(real_name) + + return True + + return False + + for partition, skip_cudagraph in zip( + reversed(partitions), reversed(skip_cudagraphs) + ): + output_names: OrderedSet[str] = OrderedSet() + + for node in partition: + output_names.update(node.outputs_by_name.keys()) + + returned_output_names = output_names.intersection(unmet_output_names) + + # all reads/writes are partition inputs except those generated + # within the partition and tensor constants + read_writes = dependencies.ReadWrites.merge_list( + [node.read_writes for node in partition] + ) + + # WeakDep is fake dependency on unused buffer. It should not appear + # in partition_input_names for inputs that are actually read or written. + partition_input_names = ( + _real_dep_names(read_writes.reads | read_writes.writes) - output_names + ) + + partition_input_names = OrderedSet( + self.mutation_real_name.get(name, name) + for name in partition_input_names + ) + + buffer_names_to_free: OrderedSet[str] = OrderedSet() + for node in partition: + buffer_names_to_free.update(node.last_usage) + + # buffer_names_to_free may contain buffers allocated in previous + # graph partitions. These buffers should also be a partition + # input. + extra_input_names = [ + name + for name in (buffer_names_to_free - output_names) + if name in name_to_node + ] + partition_input_names.update(extra_input_names) + + input_nodes = { + name: name_to_node[name] + for name in partition_input_names + if name in name_to_node + } + input_deallocation = { + name: name in buffer_names_to_free + for name in partition_input_names + if name in name_to_node + } + + # if an input tensor is not freed in the partition function, it should + # also be returned as an output. This brings benefits to cudagraph + # since the returned output tensor is a cudagraph managed tensor with + # a static tensor address. + extra_output_names = [ + name + for name in partition_input_names + if name in name_to_node and name not in buffer_names_to_free + ] + + returned_output_names.update(extra_output_names) + + returned_output_names = OrderedSet( + self.mutation_real_name.get(name, name) + for name in returned_output_names + ) + + output_nodes = [ + name_to_node[name] + for name in returned_output_names + if not is_unallocated_buffer(name) + ] + + constant_names = [ + name for name in partition_input_names if name in V.graph.constants + ] + + symbol_inputs = self.get_graph_partition_symbol_inputs( + partition, input_nodes + ) + + partition_signature = GraphPartitionSignature( + symbol_inputs, + input_nodes, + output_nodes, + input_deallocation, + skip_cudagraph, + constant_names, + ) + + signatures.append(partition_signature) + + unmet_output_names = partition_input_names.union( + unmet_output_names - returned_output_names + ) + + return signatures[::-1] + + def clean_removed_buffer_from_partition_signatures( + self, + signature: GraphPartitionSignature, + removed_buffers: OrderedSet[str], + ) -> GraphPartitionSignature: + """ + Updates the partition signature by removing buffers specified in + removed_buffers. See [Note: Removed Graph Partition Arguments] + """ + input_nodes = { + name: buffer + for name, buffer in signature.input_nodes.items() + if name not in removed_buffers + } + input_deallocation = { + name: val + for name, val in signature.input_deallocation.items() + if name not in removed_buffers + } + output_nodes = [ + node + for node in signature.output_nodes + if node.maybe_get_name() not in removed_buffers + ] + constant_names = [ + name for name in signature.constant_names if name not in removed_buffers + ] + return GraphPartitionSignature( + signature.symbol_inputs, + input_nodes, + output_nodes, + input_deallocation, + signature.skip_cudagraph, + constant_names, + ) + + def reorder_for_minimizing_partition( + self, + nodes: list[BaseSchedulerNode], + ) -> list[BaseSchedulerNode]: + """ + Reorder nodes to minimize the number of partitions via a bfs + topological sort. This is the optimal reordering such that the + number of partitions cannot be reduced further. This may be + sub-optimal for other metrics such as peak memory. This does not + change relative orders of two cudagraphable nodes, nor the + relative order of two non_cudagraphable nodes. + """ + import heapq + + node_to_indegree: dict[BaseSchedulerNode, int] = dict() + cudagraphable_nodes: list[tuple[int, BaseSchedulerNode]] = [] + non_cudagraphable_nodes: list[tuple[int, BaseSchedulerNode]] = [] + node_to_index = {node: idx for idx, node in enumerate(nodes)} + + def insert_pending_nodes(node: BaseSchedulerNode) -> None: + node_with_index = (node_to_index[node], node) + if self.should_partition(node): + heapq.heappush(non_cudagraphable_nodes, node_with_index) + else: + heapq.heappush(cudagraphable_nodes, node_with_index) + + def update_indegree(node: BaseSchedulerNode) -> None: + for succ_node in node.mpi_node.succ_nodes: + if node_to_indegree[succ_node] <= 0: + raise AssertionError( + f"expected positive indegree, got {node_to_indegree[succ_node]}" + ) + node_to_indegree[succ_node] -= 1 + if node_to_indegree[succ_node] == 0: + insert_pending_nodes(succ_node) + + for node in nodes: + node_to_indegree[node] = len(node.mpi_node.pred_nodes) + if node_to_indegree[node] == 0: + insert_pending_nodes(node) + + schedule: list[BaseSchedulerNode] = [] + num_iters: int = 0 + while num_iters < len(nodes) and ( + non_cudagraphable_nodes or cudagraphable_nodes + ): + while non_cudagraphable_nodes: + _, node = heapq.heappop(non_cudagraphable_nodes) + schedule.append(node) + update_indegree(node) + + while cudagraphable_nodes: + _, node = heapq.heappop(cudagraphable_nodes) + schedule.append(node) + update_indegree(node) + + num_iters += 1 + + if num_iters > len(nodes): + raise RuntimeError( + """ + Failed to schedule, while loop ran too long when + reordering for minimizing the num of partitions + """ + ) + + return schedule + + def maybe_reorder_for_minimizing_partition( + self, + nodes: list[BaseSchedulerNode], + ) -> list[BaseSchedulerNode]: + """ + Reorder nodes to minimize the number of partitions if this only slightly + increase peak memory. + """ + from .memory import estimate_peak_memory, prepare_planning_info + + graph_outputs = OrderedSet(V.graph.get_output_names()) + + default_peak_memory, name_to_freeable_input_buf = prepare_planning_info( + nodes, + self.name_to_buf, + self.name_to_fused_node, + OrderedSet(V.graph.graph_inputs.keys()), + graph_outputs, + ) + + reordered_nodes = self.reorder_for_minimizing_partition(nodes) + reorder_peak_memory, _ = estimate_peak_memory( + reordered_nodes, name_to_freeable_input_buf, graph_outputs + ) + + if ( + reorder_peak_memory + < default_peak_memory * config.triton.cudagraph_partition_memory_budget + ): + return reordered_nodes + + return nodes + + def reorder_for_partition_with_simple_dependency( + self, nodes: list[BaseSchedulerNode] + ) -> list[BaseSchedulerNode]: + """ + Reorder a node if it should be partitioned and has simple dependency: + 1. move a partitioned node to the front if it has no dependency + 2. move a partitioned node to the back if it is only used by OutputNode + 3. otherwise do not reorder + """ + + front: list[BaseSchedulerNode] = [] + middle: list[BaseSchedulerNode] = [] + back: list[BaseSchedulerNode] = [] + + def only_output_user(node: BaseSchedulerNode) -> bool: + for buf in node.get_outputs(): + for use in buf.users: + if not isinstance(use.node, OutputNode): + return False + return True + + for node in nodes: + should_partition = self.should_partition(node) is not None + if should_partition and len(node.unmet_dependencies) == 0: + front.append(node) + elif should_partition and only_output_user(node): + back.append(node) + else: + middle.append(node) + + return front + middle + back + + def graph_partition( + self, + ) -> tuple[list[PartitionType], list[GraphPartitionSignature]]: + """ + Given a list of BaseSchedulerNodes, split into a list of + graph partitions and compute partition input/output signatures. + """ + partitions: list[PartitionType] = [] + skip_cudagraph = True + cur_partition: PartitionType = [] + skip_cudagraphs = [] + for node in self.nodes: + node_should_partition = self.should_partition(node) is not None + if cur_partition and skip_cudagraph != node_should_partition: + partitions.append(cur_partition) + skip_cudagraphs.append(skip_cudagraph) + cur_partition = [] + + skip_cudagraph = node_should_partition + cur_partition.append(node) + + if cur_partition: + partitions.append(cur_partition) + skip_cudagraphs.append(skip_cudagraph) + + # Apply minimum partition size threshold: if a cudagraph-eligible partition + # has fewer kernels than the threshold, mark it as non-cudagraphable + min_size = config.triton.cudagraph_min_partition_size + if min_size > 0: + for i, (partition, skip) in enumerate(zip(partitions, skip_cudagraphs)): + if not skip: + kernel_count = self.count_kernel_nodes(partition) + if kernel_count < min_size: + skip_cudagraphs[i] = True + cudagraphs_log.debug( + "Partition %d has %d kernels, below minimum size %d, skipping cudagraph", + i, + kernel_count, + min_size, + ) + + signatures = self.get_graph_partition_signature( + partitions=partitions, skip_cudagraphs=skip_cudagraphs + ) + self.compute_graph_partition_maps(signatures) + + self._log_graph_partitions(partitions, signatures) + + return partitions, signatures + + def _log_graph_partitions( + self, + partitions: list[PartitionType], + signatures: list[GraphPartitionSignature], + ) -> None: + if not cudagraphs_log.isEnabledFor(logging.DEBUG): + return + + # Don't log partition reasons for CPU-only graphs since cudagraph + # partitioning is not relevant when there are no GPU devices + has_gpu_device = any(is_gpu(device) for device in V.graph.device_types) + if not has_gpu_device: + return + + cudagraphable_count = sum(1 for s in signatures if not s.skip_cudagraph) + non_cudagraphable_count = len(signatures) - cudagraphable_count + cudagraphs_log.debug( + "Created %d graph partitions: %d cudagraphable, %d non-cudagraphable", + len(partitions), + cudagraphable_count, + non_cudagraphable_count, + ) + for i, (partition, signature) in enumerate(zip(partitions, signatures)): + cudagraphs_log.debug( + " Partition %d: %d nodes, %s, inputs=%d, outputs=%d", + i, + len(partition), + "non-cudagraphable" if signature.skip_cudagraph else "cudagraphable", + len(signature.input_nodes), + len(signature.output_nodes), + ) + if signature.skip_cudagraph: + # Log details for each non-cudagraphable node + for node in partition: + self._log_non_cudagraphable_node(node) + + def _log_non_cudagraphable_node(self, node: BaseSchedulerNode) -> None: + """Log details for a non-cudagraphable node.""" + reason = self.should_partition(node) + if not reason: + return + + node_name = node.get_name() + fx_node = node.node.get_origin_node() if node.node is not None else None + parts = [f"reason={reason}"] + ir_type = type(node.node).__name__ + parts.append(f"ir={ir_type}") + if fx_node is not None: + fx_str = f"{fx_node.target}({', '.join(str(a) for a in fx_node.args)})" + parts.append(f"fx={fx_str}") + + cudagraphs_log.debug(" %s: %s", node_name, ", ".join(parts)) + + # Log full stack trace if available + if fx_node is not None: + stack_trace = fx_node.meta.get("stack_trace", None) + if stack_trace: + for line in stack_trace.strip().split("\n"): + cudagraphs_log.debug(" %s", line) + + def codegen(self) -> None: + with dynamo_timed("Scheduler.codegen"): + return ( + self._codegen_partitions() + if torch._inductor.config.graph_partition + else self._codegen(self.nodes) + ) + + def _codegen_partition_wrapper( + self, + partition: PartitionType, + signature: GraphPartitionSignature, + ) -> None: + """Codegen a partition given its inputs/outputs""" + from .codegen.wrapper import SubgraphPythonWrapperCodegen + + parent_wrapper_code = V.graph.wrapper_code + graph_partition_id = next(self._graph_partition_counter) + graph_name = parent_wrapper_code.get_partition_name(graph_partition_id) + + with V.graph.set_current_wrapper_code(): + V.graph.init_wrapper_code( + is_subgraph=True, + subgraph_name=graph_name, + parent_wrapper_code=parent_wrapper_code, + partition_signatures=signature, + ) + # V.graph.removed_buffers is global to the wrapper. Only buffers added + # while codegening this partition should be removed from this signature. + removed_buffers_before_codegen = V.graph.removed_buffers.copy() + self._codegen(partition) + + # Note: [Removed Graph Partition Arguments] + # Graph partition relies on node.read_writes to analyze the partition + # inputs and outputs. However, during codegen, we may decide some buffers + # are internal to a kernel (e.g., triton kernel) such that these buffers + # are never actually defined. This information is collected during codegen + # and recorded in V.graph.removed_buffers. So we cleanup signature and write + # prefix (i.e., generating call function and return outputs) after we have + # codegen the partition. + if not isinstance(V.graph.wrapper_code, SubgraphPythonWrapperCodegen): + raise AssertionError( + "expected wrapper_code to be a SubgraphPythonWrapperCodegen" + ) + removed_buffers_during_codegen = ( + V.graph.removed_buffers - removed_buffers_before_codegen + ) + signature = self.clean_removed_buffer_from_partition_signatures( + signature, removed_buffers_during_codegen + ) + V.graph.wrapper_code.partition_signatures = signature + V.graph.wrapper_code.write_prefix() + + partition_code, _ = V.graph.wrapper_code.generate(V.graph.is_inference) + + V.graph.wrapper_code.define_subgraph_launcher_fn(graph_name, partition_code) + + V.graph.wrapper_code.codegen_partition_call(graph_partition_id, signature) + V.graph.wrapper_code.allocated.update( # type: ignore[has-type] + [node.get_name() for node in signature.output_nodes] + ) + + def use_default_device_context( + self, partitions: list[PartitionType], signatures: list[GraphPartitionSignature] + ) -> contextlib.AbstractContextManager[None]: + @contextlib.contextmanager + def ctx() -> Iterator[None]: + self.update_graph_partition_default_device(partitions, signatures) + if self.default_device_context and device_need_guard( + self.default_device_context.type + ): + if self.default_device_context.index is None: + raise AssertionError("device should have an index") + V.graph.wrapper_code.codegen_device_guard_enter( + self.default_device_context.index + ) + + try: + yield + finally: + if self.default_device_context and device_need_guard( + self.default_device_context.type + ): + V.graph.wrapper_code.codegen_device_guard_exit() + self.default_device_context = None + + return ctx() + + def update_graph_partition_default_device( + self, partitions: list[PartitionType], signatures: list[GraphPartitionSignature] + ) -> None: + # Note: [Graph Partition Device Contexts] + # Entering a device context takes 60 microseconds and exiting a device + # context takes 20 microseconds. If all graph partitions and + # cudagraph-unsafe ops happen on the same device, we can share the + # device context. + + if len(partitions) == 1 and not signatures[0].skip_cudagraph: + # If there is only 1 cudagraph partition, the device context + # should happen within the cudagraph partition, which + # would be removed by cudagraph. + return + + def get_cudagraph_partition_device(partition: PartitionType) -> torch.device: + partition_device = partition[0].get_device() + if partition_device is None: + raise AssertionError("expected partition_device to be set") + return partition_device + + def all_on_target_device( + partition: PartitionType, target_device: torch.device + ) -> bool: + for node in partition: + device = node.get_device() + if device != target_device: + return False + return True + + cudagraph_partition_device = None + for partition, signature in zip(partitions, signatures): + if not signature.skip_cudagraph: + cudagraph_partition_device = get_cudagraph_partition_device(partition) + break + + # all partitions skip cudagraph + if cudagraph_partition_device is None: + return + + for partition, signature in zip(partitions, signatures): + if signature.skip_cudagraph and not all_on_target_device( + partition, cudagraph_partition_device + ): + return + + self.default_device_context = cudagraph_partition_device + + def _codegen_partitions(self) -> None: + """ + Split nodes into partitions and codegen each partition into separate functions. + This allows further applying different optimizations (e.g., cudagraph) to + each function. + """ + partitions, signatures = self.graph_partition() + + if len(partitions) > 1: + counters["inductor"]["cudagraph_partitions"] += len(partitions) + + with self.use_default_device_context(partitions, signatures): + for partition, signature in zip(partitions, signatures): + if len(partition) < 1: + raise AssertionError( + f"Each partition must have at least one node but found {len(partition)}" + ) + + if signature.skip_cudagraph: + self._codegen(partition) + else: + self._codegen_partition_wrapper(partition, signature) + + num_partitions = next(self._graph_partition_counter) + V.graph.wrapper_code.set_all_partition_names(num_partitions) + + # See [Note: Graph Partition Map for CUDAGraph] + if num_partitions > 0: + if V.graph.partition_maps is None: + raise AssertionError("expected V.graph.partition_maps to be set") + if num_partitions != len(V.graph.partition_maps): + raise AssertionError( + f"Expect {num_partitions} partition maps but got {len(V.graph.partition_maps)}" + ) + + def _codegen(self, nodes: list[BaseSchedulerNode]) -> None: + if config.check_stack_no_cycles_TESTING_ONLY: + import torch._dynamo.convert_frame + + stack = traceback.extract_stack() + seen: OrderedSet[tuple[str, int | None]] = OrderedSet() + for frame in reversed(stack): + # This is where maybe_cprofile is + if ( + frame.name == "_compile_inner" + and frame.filename == torch._dynamo.convert_frame.__file__ + ): + break + key = (frame.filename, frame.lineno) + if key in seen: + raise AssertionError( + f"Duplicate stack frame {frame.filename}:{frame.lineno}; " + "did you add a decorator to one of the functions in this stack " + "trace? If so, try using a context manager instead." + ) + seen.add(key) + + self.current_device = self.default_device_context + if self.previous_node is not None: + raise AssertionError("expected previous_node to be None") + + # pyrefly: ignore [unbound-name] + if self.default_device_context and config.triton.autotune_at_compile_time: + V.graph.wrapper_code.write_get_raw_stream_header() + + # Register non-mutated inputs that need alignment checks. + # Deferred to just before the first kernel that reads each input. + V.graph.wrapper_code.register_alignment_check_inputs() + + # An input read on more than one stream needs its copy_if_misaligned + # emitted per consuming stream (not once at the first reader by line + # order, which would place the only copy inside one branch's stream and + # race the others). Reclassify those inputs here. + if self._has_multi_stream_nodes(): + pending = V.graph.wrapper_code._pending_alignment_copies + if pending: + input_streams: dict[str, OrderedSet[int]] = {} + for n in nodes: + s = self.node_to_stream.get(n, 0) + for name in _real_dep_names(n.read_writes.reads): + if name in pending: + input_streams.setdefault(name, OrderedSet()).add(s) + multi = [name for name, ss in input_streams.items() if len(ss) > 1] + if multi: + V.graph.wrapper_code.mark_multistream_alignment(multi) + + for node in nodes: + if log.isEnabledFor(logging.DEBUG): + try: + log.debug( + "Generating code for node %s with estimated runtime %f", + node.get_name(), + node.get_estimated_runtime(), + ) + except Exception: + log.debug( + "Generating code for node %s with estimated runtime 0.0", + node.get_name(), + ) + + self.enter_context(node) + + # pyrefly: ignore [unbound-name] + if config.size_asserts: + V.graph.wrapper_code.codegen_deferred_input_asserts( + dep.name for dep in node.read_writes.reads + ) + + if device := node.get_device(): + if ( + device != self.current_device + or node.is_extern() + or node.is_template() + ): + self.flush() + if device != self.current_device: + if self.current_device and device_need_guard( + self.current_device.type + ): + # Exit stream context before exiting device guard + if self.current_stream_idx is not None: + self.generate_stream_ctx_exit() + V.graph.wrapper_code.codegen_device_guard_exit() + self.current_device = device + if device_need_guard(device.type): + if device.index is None: + raise AssertionError("device should have an index") + # Compute num_streams if we have multi-stream nodes + num_streams = 1 + if self._has_multi_stream_nodes(): + # Count unique streams (excluding default stream 0) + unique_streams = OrderedSet( + self.get_node_stream(n) for n in self.nodes + ) + num_streams = ( + max(unique_streams) + 1 if unique_streams else 1 + ) + V.graph.wrapper_code.codegen_device_guard_enter( + device.index, + num_streams, + self.stream_idx_to_user_obj_idx, + ) + + node_mempool = None + mempool_ctx_entered = False + # Nop nodes allocate nothing; avoid emitting an empty use_mem_pool + # context even when their metadata has a pool. + if not isinstance(node, NopKernelSchedulerNode): + node_mempool = self.node_to_mempool.get(node) + if node_mempool is not None: + # Flush any previously queued wrapper code before entering a pool + # that only applies to the current scheduler node. If a stream + # context from the previous node is still open, close it first so + # the generated order is use_mem_pool outer, stream inner. + self.flush() + if self.current_stream_idx is not None: + self.generate_stream_ctx_exit() + V.graph.wrapper_code.codegen_cuda_mempool_enter(node_mempool) + mempool_ctx_entered = True + + # Handle stream context switching for multi-stream scheduling. + # This runs for all nodes (including device-less sync ops like + # record_event/wait_event) so they are placed inside the correct + # stream context. Only switch when inside a device guard (i.e. + # current_device is set), since stream variables are declared there. + if self._has_multi_stream_nodes() and self.current_device is not None: + self.generate_stream_ctx_switching(node) + + # Emit deferred alignment copies for inputs first used by this + # node, on this node's stream. This runs *after* mempool and + # stream context switching so the copy executes inside the same + # pool and on the same stream as the consuming kernel; inputs read + # on multiple streams get one copy per stream. + V.graph.wrapper_code.codegen_deferred_alignment_copies( + (dep.name for dep in node.read_writes.reads), + self.node_to_stream.get(node, 0), + ) + + self.current_node = node + self.buffer_names_to_free.update(node.last_usage) + + if node.is_template(): + prologue, template_node, epilogue = node.get_prologue_template_epilogue( + list(node.get_nodes()) + ) + # pyrefly: ignore [unbound-name] + self.get_backend(device).codegen_template( + template_node, epilogue, prologue + ) + elif node.is_extern(): + self.codegen_extern_call(node) + elif node.is_foreach(): + node = typing.cast(ForeachKernelSchedulerNode, node) + # pyrefly: ignore [unbound-name] + backend_ = self.get_backend(device) + from .codegen.cuda_combined_scheduling import CUDACombinedScheduling + from .codegen.simd import SIMDScheduling + from .codegen.xpu.xpu_combined_scheduling import XPUCombinedScheduling + + if isinstance( + backend_, + (SIMDScheduling, CUDACombinedScheduling, XPUCombinedScheduling), + ): + backend = backend_ + else: + raise AssertionError(f"{type(self)=}") + backend.codegen_combo_kernel(node) + elif isinstance(node, FusedNestedReductions): + # pyrefly: ignore [unbound-name] + self.get_backend(device).codegen_nested_reduction(node) + elif isinstance(node, FusedMixOrderReductions): + # pyrefly: ignore [unbound-name] + self.get_backend(device).codegen_mix_order_reduction(node) + elif isinstance(node, (FusedSchedulerNode, SchedulerNode)): + # pyrefly: ignore [unbound-name] + self.get_backend(device).codegen_node(node) + else: + if not isinstance(node, NopKernelSchedulerNode): + raise AssertionError("expected node to be a NopKernelSchedulerNode") + node.mark_run() + + # pyrefly: ignore [unbound-name] + if config.triton.debug_sync_kernel: + # pyrefly: ignore [unbound-name] + self.get_backend(device).codegen_sync() + + self.available_buffer_names.update(node.get_buffer_names()) + self.completed_operations.update(node.get_operation_names()) + + if not isinstance(node, NopKernelSchedulerNode): + device = node.get_device() + if ( + device is not None + and device.type != "meta" + and self.get_backend(device).ready_to_flush() + ): + self.flush() + + if mempool_ctx_entered: + # Ensure backends that emit wrapper code at flush time still + # allocate and launch inside the active pool and stream. + self.flush() + if self.current_stream_idx is not None: + self.generate_stream_ctx_exit() + V.graph.wrapper_code.codegen_cuda_mempool_exit() + + if all(isinstance(n, SchedulerNode) for n in node.get_nodes()): + self.previous_node = node + else: + self.previous_node = None + + if self.current_device != self.default_device_context: + # when default_device_context is not None, we are codegen + # for graph partitions and all nodes must be on + # the same default device. + if self.current_device is None: + raise AssertionError("expected current_device to be set") + if device_need_guard(self.current_device.type): + # exit the outermost CUDA device guard. this is + # important for nested indentation codegen-ing. + V.graph.wrapper_code.codegen_device_guard_exit() + + self.previous_node = None + self.flush() + + def benchmark_combo_kernel( + self, node_list: Sequence[BaseSchedulerNode], node_benchmark_results + ) -> tuple[float, float, list[str | None]]: + """ + Benchmark fused list of nodes and return the execution time + in milliseconds on randomly generated inputs. + """ + device = node_list[0].get_device() + V.graph.scheduler = self + self.current_device = device + if device is None: + raise AssertionError("expected device to be set") + backend = self.get_backend(device) + return backend.benchmark_combo_kernel(node_list, node_benchmark_results) + + def speedup_by_combo_kernel(self, nodes: list[BaseSchedulerNode]) -> bool: + """ + If config.benchmark_fusion is False, always return True. + Otherwise, return True if fusion can brings speedup. + """ + + subkernel_nodes = nodes + device = subkernel_nodes[0].get_device() + + if not all(node.get_device() == device for node in subkernel_nodes): + raise AssertionError( + "All nodes in a combo kernel group must be on the same device" + ) + + if not config.benchmark_combo_kernel: + return True + + from triton.compiler.errors import CompilationError + + ms1, path1_list = 0.0, [] + node_benchmark_results = {} + for i, snode in enumerate(subkernel_nodes): + node_list = snode.get_nodes() + # We can not accurately benchmark kernel using atomic_add + # due to how we generate random integer inputs. + if self._any_atomic_add(node_list): + fusion_log.debug( + "ComboKernel: benchmarking may not accurate due to atomic_add" + ) + + try: + ms, path = self.benchmark_fused_nodes(node_list) + node_benchmark_results[snode] = (ms, path) + if math.isinf(ms): + fusion_log.debug( + "ComboKernel benchmark: register spilling of %d-th subkernel", + i, + ) + return False + except CompilationError as e: + # workaround triton issue: https://github.com/triton-lang/triton/issues/2151 + if "Loop-carried variable" in str(e): + fusion_log.debug( + "ComboKernel benchmark: return True because of loop-carried variable" + ) + return True # allow fusion + else: + raise + ms1 += ms + path1_list.append(path) + + try: + ms2, ms2_clone, _path2_list = self.benchmark_combo_kernel( + subkernel_nodes, node_benchmark_results + ) + except CompilationError as e: + # workaround triton issue: https://github.com/triton-lang/triton/issues/2151 + if "Loop-carried variable" in str(e): + fusion_log.debug( + "ComboKernel benchmark: return True because of loop-carried variable" + ) + return True # allow fusion + else: + raise + + # small kernels are very likely to have speedup but hard to benchmark. So we skip benchmarking. + small_kernel = ms2 - ms2_clone < 0.3 or ms1 < 0.3 + if fusion_log.isEnabledFor(logging.DEBUG): + if ms1 > ms2 or small_kernel: + fusion_log.debug( + "can fuse (benchmark): fusing causes %sx speedup", + green_text(f"{ms1 / ms2:.3f}"), + ) + else: + fusion_log.debug( + "cannot fuse (benchmark): fusing causes %sx slowdown", + red_text(f"{ms1 / ms2:.3f}"), + ) + # ms1 returned by benchmark_fused_nodes discounted clone time + return ms2 - ms2_clone < ms1 or small_kernel + + def get_buffer_layout(self, buf_name: str) -> ir.Layout: + buf = self.name_to_buf[buf_name] + if buf.node is None: + raise AssertionError("expected buf.node to be set") + return buf.node.get_layout() + + def update_zero_dim_cpu_tensor(self) -> None: + for node in self.nodes: + if node.is_gpu(): + for read in node.read_writes.reads: + buffer = V.graph.name_to_buffer.get(read.name) + if ( + buffer + and get_device_type(buffer) == "cpu" + and not isinstance( + buffer.layout, (NoneLayout, MultiOutputLayout) + ) + and buffer.get_size() == [] + ): + V.graph.zero_dim_cpu_tensor_list.add(read.name) + + @property + def current_stream_idx(self) -> int | None: + """CUDA Stream index that current scheduler node assigned to.""" + if self._current_stream_ctx is not None: + return self._current_stream_ctx.stream_idx + else: + return None + + @property + def current_stream_name(self) -> str | None: + """CUDA Stream name that current scheduler node assigned to.""" + if (stream_idx := self.current_stream_idx) is not None: + return get_stream_name(stream_idx) + else: + return None + + def generate_stream_ctx_enter(self, node: BaseSchedulerNode) -> None: + """Code-gen to enter the Stream context assigned to node.""" + if isinstance(node, NopKernelSchedulerNode): + raise AssertionError("expected node to not be a NopKernelSchedulerNode") + node_stream = self.get_node_stream(node) + self._current_stream_ctx = V.graph.wrapper_code.codegen_cuda_stream_enter( + stream_idx=node_stream, + ) + + def generate_stream_ctx_exit(self) -> None: + """Code-gen to exit from the current Stream context.""" + if self._current_stream_ctx is None: + raise AssertionError("expected _current_stream_ctx to be set") + V.graph.wrapper_code.codegen_cuda_stream_exit() + self._current_stream_ctx = None + + def generate_stream_ctx_switching(self, node: BaseSchedulerNode) -> None: + """Generate stream entering and exiting to properly run node in a multi-stream scenario. + + Stream context switching is only generated if ``node``'s assigned stream is different from + the previous node's stream. NopKernelSchedulerNodes have stream=None and inherit the + enclosing stream context (or do nothing if no context is active yet). + """ + stream = ( + None + if isinstance(node, NopKernelSchedulerNode) + else self.get_node_stream(node) + ) + if self.current_stream_idx == stream: + # Covers: same stream as current (no switch needed), and both None + # (nop node before any stream context — nothing to do). + return + elif self.current_stream_idx is not None and stream is None: + # Don't generate ctx switching. Memory planning code (e.g., delete buffers) on current + # node goes to previous stream ctx. + return + elif self.current_stream_idx is None and stream is not None: + # Enter new ctx, update current stream status. + self.generate_stream_ctx_enter(node) + else: + # Switching from previous stream ctx to the new stream ctx. + self.generate_stream_ctx_exit() + self.generate_stream_ctx_enter(node) + + +class BaseScheduling: # noqa: docstring_linter + def __init__(self, scheduler: Scheduler | None): + super().__init__() + self.scheduler = scheduler + + def free_buffers_in_scheduler(self) -> None: + if self.scheduler: + self.scheduler.free_buffers() + + def get_backend_features(self, device: torch.device) -> OrderedSet[BackendFeature]: + """Return a set of .codegen.common.BackendFeature()""" + return OrderedSet() + + def can_fuse_vertical( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + """ + Check whether node1 and node2 can be vertically fused or not. + """ + raise NotImplementedError + + def can_fuse_horizontal( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + """ + Check whether node1 and node2 can be horizontally fused or not. + """ + raise NotImplementedError + + def can_fuse_reduction_epilogue( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + return False + + def can_fuse_multi_outputs_template( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + """ + A Multi-Output Template (referenced in #144012) is a template node + with MultiOutputLayout, and its output buffers are instances of MultiOutput. + In this context, we verify whether node1 represents the Multi-Output Template + and node2 corresponds to one of its outputs. If so, we further check if + backend supports this fusion. + + """ + template_buf = node1.get_template_node() + if not isinstance(template_buf, ir.TemplateBuffer): + return False + if not template_buf.is_multi_outputs_template(): + return False + + if isinstance(node2.node, ir.MultiOutput): + return ( + len(node2.node.inputs) == 1 + and isinstance(node2.node.inputs[0], ir.IRNode) + and node2.node.inputs[0].get_name() == template_buf.get_name() + ) + + return False + + def fuse( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> FusedSchedulerNode: + """ + Fuse two nodes + """ + if node1.is_foreach() or node2.is_foreach(): + return ForeachKernelSchedulerNode.fuse(node1, node2) + elif NestedReduction._is_dependent_reduction_pair( + node1, node2 + ) and NestedReduction.can_fuse(node1, node2): + return FusedNestedReductions(node1, node2) + elif MixOrderReduction.are_mix_order_reductions(node1, node2): + return FusedMixOrderReductions(node1, node2) + elif isinstance(node1, FusedNestedReductions): + return node1.fuse_with(node2) + elif isinstance(node1, FusedMixOrderReductions): + return node1.fuse_with(node2) + elif isinstance(node1, ExternKernelSchedulerNode) and isinstance( + node2, SchedulerNode + ): + if not isinstance(node1.node, ir.UserDefinedTritonKernel): + raise AssertionError( + "expected node1.node to be an ir.UserDefinedTritonKernel" + ) + return FusedExternTritonKernelSchedulerNode.epilogue_fuse(node1, node2) + else: + return FusedSchedulerNode.fuse(node1, node2) + + def group_fn( + self, sizes: Sequence[Sequence[sympy.Expr]] + ) -> tuple[tuple[sympy.Expr, ...], ...]: + """ + Process the iteration sizes in case a transformation needs to be applied. + """ + raise NotImplementedError + + def codegen_template( + self, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + prologue_nodes: Sequence[BaseSchedulerNode], + ) -> str | None: + """ + Given a template node, generate a kernel. + + This function is only available for triton now. If the third-party backend behaves as a sub-class + of TritonScheduling, it can override it or reuse it. + """ + raise NotImplementedError + + def generate_kernel_code_from_nodes( + self, + nodes: Sequence[BaseSchedulerNode], + benchmark_kernel: bool, + hint_override: int | None = None, + ) -> str: + """ + Generate a kernel given a list of pre-fused nodes. + """ + raise NotImplementedError + + def codegen_node(self, node: FusedSchedulerNode | SchedulerNode) -> None: + """ + Generate a kernel given a list of pre-fused nodes. + """ + raise NotImplementedError + + def codegen_mix_order_reduction(self, node: FusedMixOrderReductions) -> None: + raise NotImplementedError + + def codegen_nested_reduction(self, node: FusedNestedReductions) -> None: + raise NotImplementedError + + def codegen_sync(self) -> None: + """ + Generate synchronization code for the kernel. This method depends on the hardware characteristics. + """ + raise NotImplementedError + + def ready_to_flush(self) -> bool: + """ + Check whether the backend is requesting the scheduler to flush the generated kernel. + If not supported, please return False. + """ + return False + + def flush(self) -> None: + """ + Flush the generated kernel and python wrapper code to the source code file. + """ + raise NotImplementedError + + def benchmark_fused_nodes( + self, nodes: Sequence[BaseSchedulerNode] + ) -> tuple[float, str]: + """ + Benchmark fused list of nodes and return the execution time + in milliseconds on randomly generated inputs. + """ + raise NotImplementedError + + def benchmark_codegened_module(self, module: ModuleType) -> tuple[float, str]: + """ + Benchmark a compiled module and return the execution time + in milliseconds on randomly generated inputs. + """ + raise NotImplementedError + + def get_fusion_pair_priority( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> int: + """ + Return an unsigned integer which represents the priority of this fusion pair. + The smaller is with higher priority. + """ + return 0 + + def benchmark_combo_kernel( + self, node_list: Sequence[BaseSchedulerNode], node_benchmark_results + ) -> tuple[float, float, list[str | None]]: + """ + Benchmark the list of nodes to combine and return the execution time + and memory copy time in milliseconds on randomly generated inputs. + """ + raise NotImplementedError + + def codegen_comment( + self, + node_schedule: Sequence[BaseSchedulerNode], + kernel_name: str | None = None, + ) -> None: + if kernel_name: + from torch._inductor.debug import set_kernel_post_grad_provenance_tracing + + debug_handle = set_kernel_post_grad_provenance_tracing( + node_schedule, # type: ignore[arg-type] + kernel_name, + ) + V.graph.wrapper_code.write_provenance_debug_handle( + kernel_name, debug_handle + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/script.ld b/.venv/lib/python3.12/site-packages/torch/_inductor/script.ld new file mode 100644 index 0000000000000000000000000000000000000000..5a052e984fcd720526201aa93d6d13b0aba2107a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/script.ld @@ -0,0 +1,8 @@ +SECTIONS { + /* By default, in LLD 16, .lrodata is placed immediately after .rodata. + * However, .lrodata can be very large in our compiled models, which leads to + * relocation out-of-range errors for relative relocations. So we place it + * after other the sections that are referenced from .text using relative + * relocations. This is the default behavior in GNU ld. */ + .lrodata : { *(.lrodata) } + } INSERT AFTER .bss; diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/select_algorithm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/select_algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..2cf00d0320bfd940104acef53711694e125b384e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/select_algorithm.py @@ -0,0 +1,6348 @@ +# mypy: allow-untyped-defs +import contextlib +import dataclasses +import functools +import hashlib +import inspect +import itertools +import json +import logging +import math +import operator +import os +import re +import sys +import textwrap +import time +from collections import defaultdict +from collections.abc import Callable, Sequence +from concurrent.futures import as_completed, ThreadPoolExecutor +from concurrent.futures.process import BrokenProcessPool +from io import StringIO +from pathlib import Path +from types import ModuleType +from typing import Any, cast, NamedTuple, Optional, TYPE_CHECKING +from typing_extensions import Self +from unittest.mock import patch + +import sympy + +import torch +import torch._inductor.async_compile +from torch._dynamo.device_interface import get_interface_for_device +from torch._dynamo.testing import rand_strided +from torch._dynamo.utils import ( + counters, + dynamo_timed, + get_chromium_event_logger, + identity, + preserve_rng_state, +) +from torch._inductor.await_utils import await_sync +from torch._inductor.utils import clear_on_fresh_cache +from torch.utils._filelock import FileLock +from torch.utils._ordered_set import OrderedSet + +from ..utils._sympy.functions import CeilDiv, Max, Min +from . import config, ir +from .autotune_process import ( + AsyncAutotuner, + PrecompileThreadPool, + TensorMeta, + TritonBenchmarkRequest, + TritonCPUBenchmarkRequest, + TritonGPUBenchmarkRequest, + use_pipelined_autotuning, +) +from .codecache import code_hash, PersistentCache, PyCodeCache +from .codegen.common import ( + CSEVariable, + IndentedBuffer, + KernelTemplate, + OpOverrides, + WorkspaceArg, + WorkspaceZeroMode, +) +from .codegen.simd_kernel_features import SIMDKernelFeatures +from .codegen.subgraph import SubgraphChoiceCaller +from .codegen.triton import ( + texpr, + TMACompatibilityChecker, + TritonKernel, + TritonScheduling, + TritonSymbols, +) +from .codegen.triton_utils import config_of, equal_1_arg_indices, signature_to_meta +from .codegen.wrapper import pexpr +from .exc import CUDACompileError +from .fx_utils import count_flops_fx +from .ir import ChoiceCaller, PrimitiveInfoType +from .ops_handler import StoreMode +from .runtime.hints import DeviceProperties, TritonMeta +from .runtime.triton_compat import HAS_WARP_SPEC +from .runtime.triton_heuristics import FixedGrid +from .utils import ( + ceildiv, + do_bench_using_profiling, + FakeIndentedBuffer, + get_dtype_size, + is_gpu, + Placeholder, + restore_stdout_stderr, + sympy_dot, + sympy_index_symbol, + sympy_product, + tlx_only_cuda_options, + triton_type, + triton_type_to_torch, + unique, + use_aten_gemm_kernels, +) +from .virtualized import V + + +log = logging.getLogger(__name__) + +# correctness checks struggle with fp16/tf32 +VERIFY: dict[str, Any] = {} +PRINT_AUTOTUNE = True +DEBUG = False + + +if TYPE_CHECKING: + import concurrent + + from torch._inductor.autotune_process import BenchmarkRequest + from torch._inductor.codegen.simd import IterationRangesEntry, IterationRangesRoot + + from .codegen.common import CSE + + +class KernelNamespace: + pass + + +# these objects are imported from the generated wrapper code +extern_kernels = KernelNamespace() + +WORKSPACE_ARG_PLACEHOLDER = "ws_placeholder" + + +@dataclasses.dataclass +class BenchmarkTensors: + """Represents a set of inputs and outputs for autotuning with a template""" + + input_tensors: list[torch.Tensor] + output_tensor: torch.Tensor | None + + def unpack(self): + return self.input_tensors, self.output_tensor + + +@dataclasses.dataclass +class AutotuneArgs: + """During autotuning, we need to pass the same inputs to all choices. + Note: + Since we typically have a mix of external choices and triton choices, we create + two lists of inputs for the same underlying buffers: + - External inputs (for aten kernels): Include offset for sliced tensors + - Triton inputs: Use base pointer for sliced tensors, without offset + """ + + triton: BenchmarkTensors + extern: BenchmarkTensors + expected: torch.Tensor | None = None + + def get_benchmark_tensors(self, extern=False) -> BenchmarkTensors: + """Returns the inputs and output tensors for a given choice.""" + bench_tensors = self.extern if extern else self.triton + return bench_tensors + + @classmethod + def from_choice_args( + cls, + example_inputs: list[torch.Tensor], + example_inputs_extern: list[torch.Tensor], + out: torch.Tensor, + out_extern: torch.Tensor, + expected: torch.Tensor | None = None, + ) -> Self: + """Factory method to create AutotuneInputs from separate inputs/outputs""" + return cls( + triton=BenchmarkTensors(example_inputs, out), + extern=BenchmarkTensors(example_inputs_extern, out_extern), + expected=expected, + ) + + def verify(self, **kwargs): + """Verify the correctness of the benchmarking results""" + + torch.testing.assert_close(self.extern.output_tensor, self.expected, **kwargs) + + +class PartialRender: + """ + Some parts of a template need to be generated at the end, but + inserted into the template at the start. This allows doing a bunch + of replacements after the initial render. + """ + + HookFn = Callable[[], str] + + def __init__(self, code: str, replacement_hooks: dict[str, HookFn | None]) -> None: + super().__init__() + self._code: str = code + self.replacement_hooks: dict[str, PartialRender.HookFn | None] = ( + replacement_hooks + ) + + @property + def code(self) -> str: + """ + The fully rendered code. Will **error** if any hooks have yet to be + finalized. + """ + remaining_active_hooks = [ + key for key, fn in self.replacement_hooks.items() if fn is not None + ] + if len(remaining_active_hooks) != 0: + raise AssertionError( + f"The following hooks have not yet been finalized:\n {remaining_active_hooks=}" + ) + return self._code + + def _replace_placeholder(self, hook_key: str, result: str) -> str: + """Replace all occurrences of a placeholder in the code with the hook result. + + During Jinja template rendering, hooks like ``def_kernel()``, + ``load_input()``, and ``store_output()`` emit placeholder strings + (e.g. ````, ````, ````) + into the rendered code and register corresponding hook functions in + ``self.replacement_hooks``. When ``finalize_hook()`` is called for + each key, the hook function runs and this method replaces every + occurrence of the placeholder with the result. + + Three replacement modes based on how each placeholder appears in + the code: + + **Non-empty result, whole-line placeholder** — indent-propagating + substitution. + When the placeholder is the only non-whitespace content on a + line, the entire line is replaced. The placeholder line's + leading whitespace (indent) is prepended to each result line + that has no leading whitespace of its own; lines that are + already indented are kept as-is. This handles both hooks that + return results at uniform indent 0 (e.g. + ``ExternalTritonTemplateKernel``) and hooks that use the + ``strip()`` convention (first line un-indented, subsequent + lines pre-indented to the target level). + + **Non-empty result, inline placeholder** — direct substitution + (``str.replace``). + When the placeholder appears mid-line (e.g. + ``{{gen_argdefs()}},``), all occurrences on that line are + replaced with the result verbatim via ``str.replace``. + + **Empty result** — line removal. + Every line whose only non-whitespace content is the placeholder + is removed. This handles cases like: + + - ```` returning ``""`` for + ``ExternalTritonTemplateKernel`` (Helion), which emits its + own kernel definition outside the template system. + - ```` returning ``""`` when prologue fusion + replaces the explicit load with inline computation from a + fused producer. + - ```` returning ``""`` for + ``ExternalTritonTemplateKernel`` outputs that have no + matching epilogue consumer. + """ + if hook_key not in self._code: + return self._code + + # Empty result — remove every line that contains only the placeholder + if not (result and result.strip()): + lines = self._code.split("\n") + return "\n".join(line for line in lines if line.strip() != hook_key) + + # Non-empty result — line-by-line replacement + lines = self._code.split("\n") + new_lines = [] + for line in lines: + if line.strip() == hook_key: + # Whole-line placeholder: decide how to indent the result. + indent = line[: len(line) - len(line.lstrip())] + result_lines = result.strip("\n").split("\n") + non_empty = [rl for rl in result_lines if rl.strip()] + all_unindented = bool(non_empty) and all( + not rl[0].isspace() for rl in non_empty + ) + if all_unindented: + # Result is at uniform indent 0 (e.g. + # ExternalTritonTemplateKernel hooks) — apply the + # placeholder indent to every non-empty line. + indented = [ + indent + rl if rl.strip() else rl for rl in result_lines + ] + new_lines.append("\n".join(indented).rstrip()) + else: + # Result has internal indentation (e.g. hooks using the + # strip() convention, or with function + # bodies) — fall back to str.replace which prepends + # the placeholder line's whitespace to the first line + # only. + new_lines.append(line.replace(hook_key, result)) + elif hook_key in line: + # Inline placeholder: simple substitution + new_lines.append(line.replace(hook_key, result)) + else: + new_lines.append(line) + return "\n".join(new_lines) + + def finalize_hook(self, hook_key: str, strict: bool = True) -> None: + """ + Finalize a hook by name. + + :param strict: If ``True``, raise an error if the hook wasn't found. + + NOTE: Will **error** if the hook has already been finalized. + """ + if hook_key not in self.replacement_hooks: + if strict: + raise RuntimeError( + f"{hook_key} not registered in self.replacement_hooks" + ) + else: + return + + hook = self.replacement_hooks[hook_key] + if hook is None: + raise AssertionError(f"Hook key {hook_key} can only be called once") + self._code = self._replace_placeholder(hook_key, hook()) + + self.replacement_hooks[hook_key] = None + + def finalize_remaining(self) -> str: + """ + Finalize the remaining active hooks. This function can be used in cases + where the caller uses `finalize_hook` rather than `finalize_all`. + Note: `finalize_all` errors if a hook that has already been finalized + is attempted to be called again. This function only attempts to + finalize active hooks. + """ + for key, fn in self.replacement_hooks.items(): + if fn is not None: + self.finalize_hook(key) + return self.code + + def finalize_all(self) -> str: + """ + Finalize all active hooks. + + NOTE: unlike ``finalize_remaining``, this method will **error** if any + hook has already been finalized. + """ + for key in self.replacement_hooks: + self.finalize_hook(key) + return self.code + + +# This is used to store info needed for lowering each subgraph in triton +# templates + + +@dataclasses.dataclass() +class SubgraphInfo: + body: IndentedBuffer + template_mask: str | None = None + template_out_shape: str | tuple[str] | None = None + compute: IndentedBuffer = dataclasses.field(default_factory=IndentedBuffer) + indexing_code: IndentedBuffer = dataclasses.field(default_factory=IndentedBuffer) + loads: IndentedBuffer = dataclasses.field(default_factory=IndentedBuffer) + stores: IndentedBuffer = dataclasses.field(default_factory=IndentedBuffer) + ops_handler: V.WrapperHandler | None = None # type: ignore[name-defined] + cse: Optional["CSE[Any, str]"] = None + + # only copied over if not None + range_trees: list["IterationRangesRoot"] | None = None + range_tree_nodes: dict[sympy.Symbol, "IterationRangesEntry"] | None = None + numels: dict[str, sympy.Expr] | None = None + + # Mapping from original range-tree root variable names (e.g. "xindex") + # to renamed prologue variables (e.g. "_prologue_x_xindex"). Used by + # prologue hooks to apply text-level renames in a structured way. + root_var_renames: dict[str, str] = dataclasses.field(default_factory=dict) + + def __post_init__(self): + self.only_copy_if_non_none_fields = ( + "range_trees", + "range_tree_nodes", + "numels", + "cse", + ) + + def to_dict(self): + return { + field.name: getattr(self, field.name) for field in dataclasses.fields(self) + } + + +class ModificationWrapper(V.WrapperHandler): # type: ignore[name-defined] + """Handles placeholder substitutions during subgraph processing.""" + + def __init__( + self, + kernel, + subgraph_number: int, + fixed_inputs: dict[str, Any], + mask: str | None, + input_shapes: dict[str, tuple[str, ...]] | None = None, + input_dtypes: dict[str, torch.dtype | str] | None = None, + ): + super().__init__(V.ops) + self.name = f"PlaceholderSubstitution_{subgraph_number}" + self.kernel = kernel + self.fixed_inputs = fixed_inputs + self.mask = mask + self.input_shapes = input_shapes or {} + self.input_dtypes = input_dtypes or {} + extra_input_shapes = self.input_shapes.keys() - self.fixed_inputs.keys() + extra_input_dtypes = self.input_dtypes.keys() - self.fixed_inputs.keys() + if extra_input_shapes: + raise AssertionError( + f"input_shapes keys must match fixed inputs: {extra_input_shapes}" + ) + if extra_input_dtypes: + raise AssertionError( + f"input_dtypes keys must match fixed inputs: {extra_input_dtypes}" + ) + + def load(self, name: str, index: sympy.Expr): + """Handle loading from tensor or fixed input.""" + if name not in self.fixed_inputs: + index_str = self._process_indexing(index) + var = self._add_kernel_input(name) + buffer = V.graph.get_buffer(name) + var_dtype = buffer.dtype + line = f"tl.load({var} + {index_str})" + + if ( + var_dtype in (torch.float16, torch.bfloat16) + and config.triton.codegen_upcast_to_fp32 + ): + line += ".to(tl.float32)" + var_dtype = torch.float32 + + out = self.kernel.cse.generate( + self.kernel.compute, + line, + dtype=var_dtype, + shape=TritonSymbols.get_block_shape(index), + ) + return out + + shape = self.input_shapes.get(name, ()) + return self.kernel.cse.generate( + self.kernel.compute, + f"({self.fixed_inputs[name]})", + dtype=self._fixed_input_dtype(name), + shape=shape, + ) + + def _index_dtype(self) -> torch.dtype: + return torch.int64 if self.kernel.index_dtype == "tl.int64" else torch.int32 + + def _normalize_input_dtype(self, dtype: torch.dtype | str) -> torch.dtype: + if isinstance(dtype, torch.dtype): + return dtype + if dtype == "index": + return self._index_dtype() + raise AssertionError(f"Unexpected fixed input dtype: {dtype}") + + def _fixed_input_dtype(self, name: str) -> torch.dtype: + if name in self.input_dtypes: + return self._normalize_input_dtype(self.input_dtypes[name]) + + value = self.fixed_inputs[name] + if isinstance(value, CSEVariable) and value.dtype is not None: + return value.dtype + if isinstance(value, str): + cse_value = self.kernel.cse.varname_map.get(value) + if cse_value is not None and cse_value.dtype is not None: + return cse_value.dtype + if isinstance(value, bool): + return torch.bool + if isinstance(value, float): + return torch.float32 + return torch.float32 + + def indirect_indexing(self, index_var: str, size, check, wrap_neg=True): + """Convert index variable to symbolic form.""" + return sympy_index_symbol(str(index_var)) + + # pyrefly: ignore [bad-override] + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> str: + """Currently only supports stores for atomic adds coming from scatter nodes + This is used by flex_attention's backwards grad for captured buffers, see + zeros_and_scatter lowering + """ + if self.mask is None: + raise AssertionError("Mask is required for inner stores in modifications") + if mode != "atomic_add": + raise AssertionError("Only atomic_add is supported for inner stores") + + buf_name = self._add_kernel_input(name) + index_str = self._broadcast_index(index, f"{value}.shape") + return f"tl.atomic_add({buf_name} + {index_str}, {value}, {self.mask}, sem='relaxed')" + + def _add_kernel_input(self, name: str) -> str: + return self.kernel.args.input(name) + + def _process_indexing(self, index: sympy.Expr) -> str: + return self.kernel.kexpr(self.kernel.rename_indexing(index)) + + def _broadcast_index(self, index: sympy.Expr, shape: str) -> str: + index = sympy.sympify(index) + index_str = self._process_indexing(index) + index_shape = TritonSymbols.get_block_shape(index) + if ( + index_shape + and len(index_shape) == 1 + and all( + V.graph.sizevars.statically_known_equals(sympy.sympify(d), 1) + for d in index_shape + ) + ): + return f"tl.broadcast_to(tl.reshape({index_str}, []), {shape})" + if not index_shape and len(index.free_symbols) == 0: + return f"tl.full({shape}, {index_str}, INDEX_DTYPE)" + return f"tl.broadcast_to({index_str}, {shape})" + + +# Function name, followed by args and kwargs. +RecordedEventsType = list[tuple[str, list[Any], dict[str, Any]]] + + +class TritonTemplateKernel(TritonKernel): + """ + A specialized kernel class for Triton templates that handles code generation + for templated Triton kernels. + + This class extends TritonKernel to provide additional functionality for + template-based kernel generation, including support for subgraphs, workspace + arguments, and prologue/epilogue fusion. + """ + + def __init__( + self, + kernel_name, + input_nodes: tuple[ir.IRNode, ...], + output_node, + defines, + num_stages, + num_warps, + grid_fn, + meta, + call_sizes, + num_consumer_groups=0, + num_buffers_warp_spec=0, + use_jit=False, + tma_store=False, + tma_load_for_template_epilogue=False, + transpose_discontiguous_tensor_descriptors_override=None, + prefix_args=0, + suffix_args=0, + epilogue_fn=identity, + subgraphs: list[ir.ComputedBuffer] | None = None, + workspace_arg: WorkspaceArg | None = None, + prologue_loads_all_inputs=False, + hint_override: int | None = None, + triton_meta: TritonMeta | None = None, + always_freeze_layout: bool = False, + index_dtype_override: str | None = None, + ) -> None: + tma_2d = tma_store or tma_load_for_template_epilogue + if tma_store: + pass + numel = sympy_product(output_node.get_size()) + if tma_2d: + if len(output_node.get_size()) != 2: + raise AssertionError( + "TMA load/store only supported for 2D with templates" + ) + tiling = { + "x": output_node.get_size()[0], + "y": output_node.get_size()[1], + "r0_": sympy.S.One, + } + else: + tiling = { + "x": numel, + "r0_": sympy.S.One, + } + super().__init__( + tiling, + features=SIMDKernelFeatures([], numel), + hint_override=hint_override, + ) + if tma_2d: + # By default `construct_range_trees` will return the range_trees in the order + # ["z", "y", "x", "r0_", "r1_"] (see simd.py:all_prefixes) + # and this order defines what the kernel block shape will be. So if the template + # input / output has requested e.g. ["x", "y"], `construct_range_trees` will still return the + # trees in the order ["y", "x"]. This would mean that the template would need to transpose + # the loaded value. + # The below sorts the range trees according to that required by the caller + prefix_to_range_tree = {rt.prefix: rt for rt in self.range_trees} + pw_sorted_range_trees = [] + reduction_idx = None + for i, prefix in enumerate(tiling): + rt = prefix_to_range_tree[prefix] + + if rt.is_reduction: + reduction_idx = i + break + rt.index = i + rt.grid_dim = i + rt.tensor_dim = i + pw_sorted_range_trees.append(rt) + self.range_trees = pw_sorted_range_trees + self.range_trees[reduction_idx:] + + self.input_nodes = input_nodes + self.output_node = output_node + self.named_input_nodes = {} # type: ignore[var-annotated] + self.defines = defines + self.kernel_name = kernel_name + self.use_jit = use_jit + self.tma_store = tma_store + self.tma_load_for_template_epilogue = tma_load_for_template_epilogue + self.transpose_discontiguous_tensor_descriptors_override = ( + transpose_discontiguous_tensor_descriptors_override + ) + self.num_stages = num_stages + self.num_warps = num_warps + self.num_consumer_groups = num_consumer_groups + self.num_buffers_warp_spec = num_buffers_warp_spec + self.grid_fn = grid_fn + self.meta = meta + self.call_sizes = call_sizes + # for templates with fixed epilogues + self.prefix_args = prefix_args + self.suffix_args = suffix_args + # pyrefly: ignore [invalid-type-var] + self.epilogue_fn = epilogue_fn + self.render_hooks = {} # type: ignore[var-annotated] + self.triton_meta: TritonMeta | None = triton_meta + self._index_dtype_override = index_dtype_override + # For Templated Attention this can be a list of ir.Subgraph + self.subgraphs: list[ir.ComputedBuffer] | None = subgraphs + + # Some templates use extra global memory as a workspace + self.workspace_arg = workspace_arg + if workspace_arg is not None: + self.args.workspace_args.append(workspace_arg) + + # The following attributes (body, template_mask, output_val) are all + # used for triton kernel codegen. + # They are swapped onto the TritonTemplateKernel object by + # `set_subgraph_body` + self.subgraph_bodies: dict[str, SubgraphInfo] = {} + + # input buffers which we are allowed to prologue fuse into + self.prologue_supported_inputs: OrderedSet[str] = OrderedSet() + + # input buffers which we are fusing into + self.prologue_fused_inputs: OrderedSet[str] = OrderedSet() + # input buffers which we are fusing into, which preserve a zero mask + self.prologue_fused_inputs_preserve_zero: OrderedSet[str] = OrderedSet() + + # The following attributes are all used for triton kernel codegen. + # They are swapped onto the TritonTemplateKernel object by + # `set_subgraph_body` + # NB: the names here must match the fields in SubgraphInfo + self.body: IndentedBuffer = FakeIndentedBuffer() + self.compute: IndentedBuffer = FakeIndentedBuffer() + self.indexing_code: IndentedBuffer = FakeIndentedBuffer() + self.loads: IndentedBuffer = FakeIndentedBuffer() + self.stores: IndentedBuffer = FakeIndentedBuffer() + self.template_mask: str | None = None + self.template_out_shape: str | tuple[str] | None = None + self.ops_handler: V.WrapperHandler | None = None # type: ignore[name-defined] + self.root_var_renames: dict[str, str] = {} + + # When caching is enabled, the generated code is not dependent on the input nodes names, or + # symbolic sizes names. + # However, some of the variables returned by generate_and_load that are computed during the + # triton template expansions (code generation) are dependent on those. + # In order to cache the code generation and avoid redoing it for similar inputs that varies only by + # input names or symbol names, we do a record and replay method. + # During template expansions we record all function calls that change input_dependent_preserved_state + # and replay them on a cache hit to regenerate them. + self.cached_replay_events: RecordedEventsType | None = None + + # Update each time an input is marked frozen, used to replay the freezing of inputs on a cache hit. + self.frozen_layouts_cnt = 0 + + # When prologue_loads_all_inputs is true, prologue_supported_inputs is populated during def_kernel + # by adding all inputs. + self.prologue_loads_all_inputs = prologue_loads_all_inputs + + # When always_freeze_layout is True, get_stride_and_maybe_freeze_layout will + # always freeze the layout immediately, bypassing layout constraints. + # This is used by FlexAttention templates which require frozen layouts. + self.always_freeze_layout = always_freeze_layout + + # Extra functions to be exposed during partial template rendering. + self.extra_template_env_fns: list[Callable[..., Any]] = [] + + # Tracking for intermediate variables + self.tmp_var_ctr = itertools.count() + + @property + def index_dtype(self) -> str: + if self._index_dtype_override is not None: + return self._index_dtype_override + return super().index_dtype + + def _gen_tmp_var(self) -> str: + return f"_tmp_var{next(self.tmp_var_ctr)}" + + def input_dependent_preserved_state(self) -> str: + # Not adding self.args.output_buffers on purpose. But we do not need to reproduce it on a cache hit. + # (never accessed). + return repr( + [ + self.args.input_buffers, + self.args.sizevars, + self.args.workspace_args, + self.prologue_supported_inputs, + self.frozen_layouts_cnt, + ] + ) + + def record_input_dependent_tracked_event(self) -> Callable[..., Any]: + def decorator(fn) -> Callable[..., Any]: + def wrapper(*args, **kwargs) -> Any: + pre_state = self.input_dependent_preserved_state() + result = fn(*args, **kwargs) + post_state = self.input_dependent_preserved_state() + if pre_state != post_state: + if self.cached_replay_events is None: + raise AssertionError("cached_replay_events must not be None") + self.cached_replay_events.append((fn.__name__, [*args], {**kwargs})) + return result + + return wrapper + + return decorator + + def replay_cached_events(self, events: RecordedEventsType) -> None: + for f, args, kwargs in events: + getattr(self, f)(*args, **kwargs) + + @contextlib.contextmanager + def set_subgraph_body(self, body_name: str): + if not all( + hasattr(self, field.name) for field in dataclasses.fields(SubgraphInfo) + ): + raise AssertionError("missing expected SubgraphInfo fields on self") + old_state = { + key.name: getattr(self, key.name) + for key in dataclasses.fields(SubgraphInfo) + } + + if body_name not in self.subgraph_bodies: + raise AssertionError(body_name) + + subgraph = self.subgraph_bodies[body_name] + for key, value in subgraph.to_dict().items(): + if value is None and key in subgraph.only_copy_if_non_none_fields: + continue + setattr(self, key, value) + + context = ( + contextlib.nullcontext + if not self.ops_handler + # pyrefly: ignore [not-callable] + else lambda: V.set_ops_handler(self.ops_handler(V.get_ops_handler())) + ) + with context(): # type: ignore[operator] + yield + self.subgraph_bodies[body_name] = SubgraphInfo( + **{ + key.name: getattr(self, key.name) + for key in dataclasses.fields(SubgraphInfo) + } + ) + for key, value in old_state.items(): + setattr(self, key, value) + + @contextlib.contextmanager + def create_subgraph_body(self, body_name: str, clear_cse: bool = False): + if body_name in self.subgraph_bodies: + raise AssertionError(f"subgraph body {body_name} already exists") + self.subgraph_bodies[body_name] = SubgraphInfo( + IndentedBuffer(), None, None, cse=self.cse.clone() if clear_cse else None + ) + with self.set_subgraph_body(body_name): + yield + + def _make_independent_subgraph(self, subgraph_name, numel, **extra_fields): + """Create a subgraph with fresh independent range trees. + + Used by external template backends for epilogue/prologue hooks + that need their own range tree state. + """ + groups = {"x": V.graph.sizevars.simplify(numel), "r0_": sympy.S.One} + self.subgraph_bodies[subgraph_name] = SubgraphInfo( + body=IndentedBuffer(), + cse=self.cse.clone(), + range_trees=self.construct_range_trees( + pid_cache=None, + inside_reduction=False, + is_reduction=False, + numels=groups, + no_x_dim=False, + ), + range_tree_nodes={}, + numels=groups, + **extra_fields, + ) + + def _setup_contiguous_index_state( + self, + indices: list[str], + index_symbols: list[sympy.Symbol], + lengths: list[sympy.Expr], + mask: str | None, + xindex_name: str = "xindex", + ) -> sympy.Expr: + """Set up range trees, contiguous index, mask, and template indices. + + Common boilerplate shared by store_output, _setup_epilogue_hook, + and load_input. Returns the contiguous index expression. + """ + for name, range_tree_entry in zip( + indices, self.range_trees[0].construct_entries(lengths) + ): + range_tree_entry.set_name(name) + contiguous_index = sympy_dot( + ir.FlexibleLayout.contiguous_strides(lengths), index_symbols + ) + contiguous_index = self.rename_indexing(contiguous_index) + self.body.writeline(f"{xindex_name} = " + texpr(contiguous_index)) + xindex_entry = self.range_trees[0].lookup(sympy.S.One, sympy_product(lengths)) + old_symbol = xindex_entry.symbol() + xindex_entry.set_name(xindex_name) + # Re-key only range_tree_nodes: get_block_shape resolves the renamed symbol + # via this dict. Unlike the TMA re-key, var_list/var_ranges are left alone -- + # in the single-dim case old_symbol is the construct_entries-renamed name, + # not the auto symbol var_list holds, so a var_list.index() re-key would raise; + # the stale entries only cost codegen quality, not correctness. + if self.range_tree_nodes.get(old_symbol) is xindex_entry: + del self.range_tree_nodes[old_symbol] + self.range_tree_nodes[xindex_entry.symbol()] = xindex_entry + self.template_mask = mask + self.template_indices = indices + return contiguous_index + + def _make_codegen_hook( + self, subgraph_name: str, indent_width: int = 0 + ) -> Callable[[], str]: + """Create a hook closure that codegen's a subgraph body.""" + + def hook(): + with self.set_subgraph_body(subgraph_name): + self.codegen_body() + self.cse.invalidate(OrderedSet()) + result = self.body.getvalue() + if indent_width: + result = textwrap.indent( + textwrap.dedent(result), " " * indent_width + ) + return result.strip() + + return hook + + def need_numel_args(self): + return False + + def estimate_kernel_num_bytes(self): + """ + Estimate the total number of bytes this kernel takes. + For in/out nodes, sizes are counted twice: once for reading and + once for writing. + """ + ninplace_args = len(unique(self.args.inplace_buffers.values())) + num_bytes = [] + for i, inp in enumerate(itertools.chain(self.input_nodes, (self.output_node,))): + size = V.graph.sizevars.optimization_hints(inp.get_size(), fallback=0) + numel = functools.reduce(operator.mul, size, 1) + dtype_size = get_dtype_size(inp.get_dtype()) + num_bytes.append(numel * dtype_size * (1 + int(i < ninplace_args))) + return sum(num_bytes) + + def estimate_flops(self) -> int: + for node in self.input_nodes: + for fx_node in node._current_origins: + f = count_flops_fx(fx_node) + if f is not None: + if isinstance(f, torch.SymInt): + f = f.node.expr + return V.graph.sizevars.optimization_hint(f, fallback=0) + return 0 + + def jit_lines(self): + """Render decorators and metadata for the generated Triton template.""" + if self.use_jit: + return "@triton.jit" + + argdefs, _, signature, _ = self.args.python_argdefs() + triton_meta: TritonMeta = { + "signature": signature_to_meta( + signature, + size_dtype=self.index_dtype, + argdefs=argdefs, + is_template=True, + ), + "device": DeviceProperties.create(self.output_node.get_device()), + "constants": {}, + } + triton_meta["configs"] = [config_of(signature)] + for arg_num in equal_1_arg_indices(signature): # type: ignore[index] + triton_meta["constants"][signature[arg_num].name] = 1 # type: ignore[index,union-attr] + matrix_instr_nonkdim = self.meta.get("matrix_instr_nonkdim", None) + waves_per_eu = self.meta.get("waves_per_eu", None) + kpack = self.meta.get("kpack", None) + if matrix_instr_nonkdim: + triton_meta["matrix_instr_nonkdim"] = matrix_instr_nonkdim + if waves_per_eu: + triton_meta["waves_per_eu"] = waves_per_eu + if kpack: + triton_meta["kpack"] = kpack + + # tlx options carry dynamic string keys outside the TritonMeta schema. + triton_meta_extra = cast(dict[str, Any], triton_meta) + for k in tlx_only_cuda_options(): + if v := self.meta.get(k, None): + triton_meta_extra[k] = v + + if self.triton_meta is None: + self.triton_meta = triton_meta + else: + self.triton_meta.update(triton_meta) + + inductor_meta = { + "kernel_name": str(Placeholder.DESCRIPTIVE_NAME), + **self.inductor_meta_common(), + **FixedGrid.setup_grid_as_args(), + } + if config.profile_bandwidth or config.benchmark_kernel: + num_gb = self.estimate_kernel_num_bytes() / 1e9 + inductor_meta["kernel_num_gb"] = num_gb + if config.benchmark_kernel: + flops = self.estimate_flops() + inductor_meta["kernel_flop"] = flops + + inductor_meta["config_args"] = self.meta + + template_args = f""" + num_stages={self.num_stages}, + num_warps={self.num_warps}, + triton_meta={self.triton_meta!r}, + inductor_meta={inductor_meta!r}, + """ + + if HAS_WARP_SPEC: + template_args += f""" + num_consumer_groups={self.num_consumer_groups}, + num_buffers_warp_spec={self.num_buffers_warp_spec}, + """ + + # tlx options carry dynamic string keys outside the TritonMeta schema. + triton_meta_extra = cast(dict[str, Any], self.triton_meta) + for k in tlx_only_cuda_options(): + if v := self.meta.get(k, None): + template_args += f""" + {k}={v}, + """ + triton_meta_extra[k] = v + + return f""" + @triton_heuristics.template( + {template_args} + ) + @triton.jit + """ + + def gen_argdefs(self): + def hook(): + # python_argdefs() cannot be run until after the rest of the template lazily adds more args + arg_defs, *_ = self.args.python_argdefs() + return f"{', '.join(x.full_name() for x in arg_defs)}" + + return self._register_hook("", hook, allow_overwriting=True) + + def gen_defines(self): + return self.defines + + def def_kernel(self, *argnames): + """ + Hook called from template code to generate function def and + needed args. + """ + if not all(isinstance(x, str) for x in argnames): + raise AssertionError("all argnames must be str") + renames = IndentedBuffer(initial_indent=1) + + named_args = self.input_nodes[ + self.prefix_args : len(self.input_nodes) - self.suffix_args + ] + + if len(argnames) != len(named_args): + raise AssertionError( + ( + len(argnames), + len(named_args), + self.prefix_args, + len(self.input_nodes), + ) + ) + + for input_node in self.input_nodes[: self.prefix_args]: + # get args in correct order + self.args.input(input_node.get_name()) + + for name, input_node in zip(argnames, named_args): + arg_name = f"arg_{name}" + self.named_input_nodes[name] = input_node + if input_node.get_name() in V.graph.removed_buffers: + continue + if input_node.get_name() in self.prologue_fused_inputs: + continue + + self.args.input_buffers[input_node.get_name()] = arg_name + + # The args may be duplicated, so renaming must be after args are de-duplicated. + for name in argnames: + input_node = self.named_input_nodes[name] + if self.prologue_loads_all_inputs: + self.prologue_supported_inputs.add(input_node.get_name()) + if input_node.get_name() in V.graph.removed_buffers: + continue + if input_node.get_name() in self.prologue_fused_inputs: + continue + + arg_name = self.args.input_buffers[input_node.get_name()] + if input_node.get_layout().offset == 0: + renames.writeline(f"{name} = {arg_name}") + else: + offset = texpr(self.rename_indexing(input_node.get_layout().offset)) + renames.writeline(f"{name} = {arg_name} + {offset}") + + for input_node in self.input_nodes[len(self.input_nodes) - self.suffix_args :]: + # get args in correct order + if input_node.get_name() in V.graph.removed_buffers: + continue + if input_node.get_name() in self.prologue_fused_inputs: + continue + + self.args.input(input_node.get_name()) + + def hook(): + # python_argdefs() cannot be run until after the rest of the template lazily adds more args + arg_defs, *_ = self.args.python_argdefs() + code = IndentedBuffer() + code.splice(self.gen_common_triton_imports()) + code.splice(self.jit_lines()) + code.writeline( + f"def {self.kernel_name}({', '.join(x.full_name() for x in arg_defs)}):" + ) + with code.indent(): + code.splice(self.defines) + code.splice(renames.getvalue()) + self.codegen_prologue(code) + return code.getvalue() + + return self._register_hook("", hook) + + def size(self, name: str | None, index: int): + """ + Hook called from template code to get the size of an arg. + Will add needed args to pass it in if it is dynamic. + Automatically wraps with tl.full([], ..., dtype=INDEX_DTYPE) when + int64 indexing is needed to prevent overflow in size arithmetic. + """ + if not isinstance(index, int): + raise AssertionError(f"expected index to be int, got {type(index)}") + if name is None: + val = self.output_node.get_size()[index] + else: + if not isinstance(name, str): + raise AssertionError(f"expected name to be str, got {type(name)}") + val = self.named_input_nodes[name].get_size()[index] + result = texpr(self.rename_indexing(val)) + if self.index_dtype == "tl.int64": + return f"tl.full([], {result}, dtype=INDEX_DTYPE)" + return result + + def stride(self, name, index=None): + """ + Hook called from template code to get the stride of an arg. + Will add needed args to pass it in if it is dynamic. + """ + if name is None: + val = self.output_node.get_stride() + else: + if not isinstance(name, str): + raise AssertionError(f"expected name to be str, got {type(name)}") + val = self.get_stride_and_maybe_freeze_layout(self.named_input_nodes[name]) + + if isinstance(index, int): + return texpr(self.rename_indexing(val[index])) + return ", ".join([texpr(self.rename_indexing(i)) for i in val]) + + def _get_subgraph(self, subgraph_number: int): + if not isinstance(subgraph_number, int): + raise AssertionError( + f"expected subgraph_number to be int, got {type(subgraph_number)}" + ) + if not isinstance(self.subgraphs, list): + raise AssertionError( + f"expected self.subgraphs to be list, got {type(self.subgraphs)}" + ) + if subgraph_number >= len(self.subgraphs): + raise AssertionError( + f"Invalid subgraph number provided to create_modification, {subgraph_number} must be < {len(self.subgraphs)}" + ) + if self.body.getvalue() != "": + raise AssertionError("Body should be clear before adding a modification") + return self.subgraphs[subgraph_number] + + def _handle_scatter_graph(self, scatter_graph): + """Handle processing for a single scatter graph. + + Args: + scatter_graph: The scatter graph to process + """ + if not isinstance(scatter_graph, ir.ComputedBuffer): + raise AssertionError( + f"scatter_graph must be an instance of ComputeBuffer but got {type(scatter_graph)}" + ) + + def contiguous_strides(x): + # We always create a fresh contiguous grad for scattering into + return sum( + x_i * stride for x_i, stride in zip(x, scatter_graph.get_stride()) + ) + + return scatter_graph.data.store_output( # type: ignore[attr-defined] + scatter_graph.name, contiguous_strides, [] + ) + + def modification( + self, + subgraph_number: int, + output_name: str | None, + mask: str | None = None, + input_shapes: dict[str, tuple[str, ...]] | None = None, + input_dtypes: dict[str, torch.dtype | str] | None = None, + **fixed_inputs, + ) -> str: + """This creates a modification function for a subgraph. + To use this inside a template, the first argument should specify which subgraph to codegen for + + Args: + subgraph_number (int): The index of the subgraph in self.subgraphs + output_name (Optional[str]): The name of the output variable to store the result in + mask (Optional[str]): An optional mask to use for the store operation. If provided, this mask + will be applied to the store. + input_shapes (Optional[dict[str, tuple[str, ...]]]): Optional mapping of input names to their + block shapes. Used for proper shape propagation during codegen. + input_dtypes (Optional[dict[str, torch.dtype | str]]): Optional dtype + mapping. The string "index" resolves to the template index dtype. + """ + num = 0 + out = None + scatters = [] + while f"mod_{subgraph_number}_{num}" in self.subgraph_bodies: + num += 1 + with self.create_subgraph_body(f"mod_{subgraph_number}_{num}"): + subgraph = self._get_subgraph(subgraph_number) + modification_handler = ModificationWrapper( + self, + subgraph_number, + fixed_inputs, + mask, + input_shapes, + input_dtypes, + ) + with V.set_ops_handler(modification_handler): + if not isinstance(subgraph, (ir.ComputedBuffer, list)): + raise AssertionError( + f"Expected the subgraph to be a ComputedBuffer or a List[ComputedBuffer], got {type(subgraph)}" + ) + # Handle scatter stores + if isinstance(subgraph, list): + for scatter_graph in subgraph: + scatters.append(self._handle_scatter_graph(scatter_graph)) + elif isinstance(subgraph.data, ir.InputBuffer): + out = subgraph.data.make_loader()(()) + else: + out = subgraph.data.inner_fn(()) + + self.codegen_body() + if output_name is not None: + if not isinstance(output_name, str): + raise AssertionError( + f"expected output_name to be str, got {type(output_name)}" + ) + if out is None: + raise AssertionError("out must not be None") + self.body.writeline(f"{output_name} = {out.value}") + else: + if out is not None: + raise AssertionError("out must be None when output_name is None") + for scatter in scatters: + self.body.writeline(str(scatter)) + + body_val = self.body.getvalue() + self.cse.invalidate(OrderedSet()) + return body_val + + def load_input( + self, + input_name: str, + output_name: str, + indices: list[Any] | tuple[Any], + mask: str | None = None, + other: float | int | None = 0.0, + indent_width: int = 4, + index_shape: tuple[str] | None = None, + ): + """Loads an input and applies any necessary preprocessing or masking. + + Args: + input_name (str): The name of the input to load. + indices (Union[List, Tuple]): The index for each dimension of the input. + val (str): The name of the variable to store the loaded value. + mask (Optional[str]): An optional mask to use for the load operation. + other (Optional[Union[float, int]]): The value to use for masked elements. Default is 0.0. + indent_width (int): The number of spaces to use for indentation. + """ + + input_node = self.named_input_nodes[input_name] + if not self.prologue_loads_all_inputs: + self.prologue_supported_inputs.add(input_node.get_name()) + + tilings = (sympy_product(input_node.get_size()), sympy.Integer(1)) + groups = { + "x": tilings[0], + "r0_": tilings[1], + } + + range_trees = self.construct_range_trees( + pid_cache=None, + inside_reduction=False, + is_reduction=False, + numels=groups, + no_x_dim=False, + ) + load_code = None + + with self.create_subgraph_body(f""): + if not isinstance(indices, (list, tuple)): + raise AssertionError( + f"expected indices to be list or tuple, got {type(indices)}" + ) + if not isinstance(output_name, str): + raise AssertionError( + f"expected output_name to be str, got {type(output_name)}" + ) + if not isinstance(mask, (str, type(None))): + raise AssertionError( + f"expected mask to be str or None, got {type(mask)}" + ) + self.range_trees = range_trees + self.numels = {k: V.graph.sizevars.simplify(v) for k, v in groups.items()} + indices = list(map(OpOverrides.paren, indices)) + index_symbols = [sympy.Symbol(x, integer=True) for x in indices] + + lengths = [V.graph.sizevars.simplify(s) for s in input_node.get_size()] + if len(indices) != len(lengths): + raise AssertionError( + f"expected len(indices) == len(lengths), got {len(indices)} and {len(lengths)}" + ) + + # MM templates use out-of-bounds wrapping (e.g. `rm % M`) so no mask + # is needed on the load. Pass "None" when mask is unset to override + # the mask that would otherwise be inherited. + contiguous_index = self._setup_contiguous_index_state( + indices, + index_symbols, + lengths, + mask=mask if mask is not None else "None", + ) + self.template_out_shape = index_shape if index_shape else "xindex" + self.cse.invalidate(OrderedSet()) + + template_mask = self.template_mask + + class StoreOutputSubstitution(V.WrapperHandler): # type: ignore[name-defined] + name = "StoreOutputSubstitution" + + def store( + self, + name: str, + index: sympy.Expr, + value: "CSEVariable", + mode: "StoreMode" = None, + ): + V.kernel.store_buffer_names.add(name) + V.kernel.cse.store_cache[name] = value + if name in V.kernel.prologue_fused_inputs: + # We load masked out values with 0, then apply a prologue. + # The masked out values may not necessarily be 0 any more + # so we need to reapply the mask. + value_dtype = value.dtype + value_str = str(value) + if template_mask != "None" and ( + name not in V.kernel.prologue_fused_inputs_preserve_zero + or other != 0 + ): + value_str = ( + f"tl.where({template_mask}, {value_str}, {other})" + ) + + if value_dtype != V.graph.get_buffer(name).dtype: + value_str = f"{value_str}.to({triton_type(V.graph.get_buffer(name).dtype)})" + + # TODO: we should have intermediary var shapes + V.kernel.compute.writeline( + f"{output_name} = {value_str}.broadcast_to(xindex.shape)" + ) + + # pyrefly: ignore [bad-assignment] + self.ops_handler = StoreOutputSubstitution + + input_node = self.named_input_nodes[input_name] + if isinstance(input_node.layout, ir.FlexibleLayout): + # This will set a layout constraint on the template + self.get_stride_and_maybe_freeze_layout(input_node) + with patch.object(ir.FlexibleLayout, "allow_indexing", True): + output_index = input_node.make_indexer()(index_symbols) + else: + output_index = input_node.make_indexer()(index_symbols) + + # in def_kernel above we define the inputs with the storage offset adjusted + # creating the load in input_node.make_indexer() will also adjust by storage offset + # so subtract here to not double increment + if not V.graph.sizevars.statically_known_equals( + input_node.layout.offset, 0 + ): + output_index = output_index - self.rename_indexing( + input_node.get_layout().offset + ) + + output_index = self.rename_indexing(output_index) + + if output_index == contiguous_index: + output_index_str = "xindex" + else: + out_indexing = self.indexing( + output_index, + copy_shape=self.template_out_shape, + override_mask=self.template_mask, + ) + from .codegen.triton import IndexingOptions + + if not isinstance(out_indexing, IndexingOptions): + raise AssertionError( + f"expected out_indexing to be IndexingOptions, got {type(out_indexing)}" + ) + output_index_str = ( + f"({out_indexing.index_str}).broadcast_to(xindex.shape)" + ) + + # Generate load code + load_code = f"{output_name} = tl.load({input_name} + ({output_index_str})" + + if mask: + load_code += f", mask={mask}, other={other})" + else: + load_code += ")" + + hook_key = f"" + + def hook(): + with self.set_subgraph_body(hook_key): + self.cse.invalidate(OrderedSet()) + self.codegen_body() + self.cse.invalidate(OrderedSet()) + if input_node.get_name() not in self.prologue_fused_inputs: + if load_code is None: + raise AssertionError("load_code must not be None") + self.body.writeline(load_code) + + result = self.body.getvalue() + if indent_width: + result = textwrap.indent(result, " " * indent_width) + return result.strip() + + return self._register_hook(hook_key, hook) + + def _generate_index_from_tma_index( + self, + output_name: str, + offset_name: str, + tma_index: sympy.Symbol, + block_size: str, + dim: int, + num_dims: int, + block_name: str | None = None, + ) -> list[str]: + """ + Generate the logic to compute the regular tl.load index from the provided + tma index. This is used to ensure variables can support fusions. + + Args: + output_name (str): The output variable name. + offset_name (str): The name used for the intermediate offset. + tma_index (sympy.Symbol): The symbol used for the original TMA index. + block_size (str): The block size of the index. + dim (int): Which dimension to project the index in. + num_dims (int): The total number of dimensions in the output. + block_name (Optional[str]): The name of the block variable. If not passed + in then we aren't reusing standard symbol names. + + Returns: + list[str]: The lines used to generate the index. + + """ + if block_name: + # Generate the expected names for the structure: + # XBLOCK/YBLOCK and xoffset/yoffset. We append XBLOCK/YBLOCK + # to the top of the kernel so we can safely extract the tensor + # descriptor construction to the top of the kernel. + if block_name in self.prologue_cache: + if self.prologue_cache[block_name] != block_size: + raise AssertionError( + f"Constant {block_name} must be used for all stores" + ) + else: + self.prologue_cache[block_name] = block_size + self.prologue.writeline(f"{block_name}: tl.constexpr = {block_size}") + else: + block_name = block_size + line0 = f"{offset_name} = {texpr(tma_index)}" + expr = f"({offset_name} + tl.arange(0, {block_name}))" + prefix_none = "".join(["None, "] * dim) + suffix_none = ", ".join(["None"] * (num_dims - (dim + 1))) + line1 = f"{output_name} = {expr}[{prefix_none}:, {suffix_none}]" + return [line0, line1] + + def _generated_mask_for_tma( + self, + index_name: str, + shape_val: str, + output_name: str, + ) -> str: + """ + Generate the mask logic to feed to fusions for mask. The expectation + is that if we have X/Y there will be a variable named xmask and ymask. + + Args: + index_name (str): The index used in the mask. Should be one of + xindex or yindex. + shape_val (str): The expression for the upper bound shape. + output_name (str): The expression used for the output. + + Returns: + str: The mask generation line. + """ + return f"{output_name} = {index_name} < {shape_val}" + + def store_output( + self, + indices: list[Any] | tuple[Any], + val: str, + mask: str | None = None, + indent_width: int = 4, + val_shape: tuple[str] | None = None, + block_indexing: bool = False, + ): + """Stores the final output and appends any epilogue fusions if the buffer hasn't been optimized away. + + Args: + indices (Union[List, Tuple]): The index for each dimension of the output. The dot product of + these indices and output strides must match `val`. + val (str): The value to store. + mask (Optional[str]): An optional mask to use for the store operation. If provided, this mask + will be applied to the store. + indent_width (int): The number of spaces to use for indentation. This is used when the call to + store_output is indented in the kernel definition. + block_indexing (bool): Are the input indices presented as offsets for creating the block (e.g. + inputs to TMA) or are they tensors that should be passed in directly. + """ + subgraph_idx = next(self.store_output_ctr) + subgraph_name = self._get_store_output_subgraph_name(subgraph_idx) + with self.create_subgraph_body(subgraph_name, clear_cse=True): + if not isinstance(indices, (list, tuple)): + raise AssertionError( + f"expected indices to be list or tuple, got {type(indices)}" + ) + if not isinstance(val, str): + raise AssertionError(f"expected val to be str, got {type(val)}") + if not isinstance(mask, (str, type(None))): + raise AssertionError( + f"expected mask to be str or None, got {type(mask)}" + ) + if not isinstance(val_shape, (tuple, type(None))): + raise AssertionError( + f"expected val_shape to be tuple or None, got {type(val_shape)}" + ) + if not isinstance(block_indexing, bool): + raise AssertionError( + f"expected block_indexing to be bool, got {type(block_indexing)}" + ) + if self.template_mask is not None: + raise AssertionError("template_mask must be None") + indices = list(map(OpOverrides.paren, indices)) + index_symbols = [sympy.Symbol(x, integer=True) for x in indices] + lengths = [ + V.graph.sizevars.simplify(s) for s in self.output_node.get_size() + ] + if len(indices) != len(lengths): + raise AssertionError( + f"expected len(indices) == len(lengths), got {len(indices)} and {len(lengths)}" + ) + + output_layout = self.output_node.get_layout() + self.template_out = val + if block_indexing: + if not val_shape: + raise AssertionError( + "Blocking indexing requires passing in val_shape" + ) + if len(val_shape) != 2: + raise AssertionError( + "Blocking indexing only supports 2D data at this time" + ) + if mask: + raise AssertionError("Mask is not supported with blocking indexing") + intermediate_lines: list[str] = [] + epilogue_index_symbols: list[sympy.Symbol] = [] + if self.tma_store or self.tma_load_for_template_epilogue: + val_shape_copy = list(val_shape) + for i, range_tree in enumerate(self.range_trees[:-1]): + name = range_tree.name + symbol = range_tree.symbol() + epilogue_index_symbols.append(symbol) + lookup_output = range_tree.lookup(sympy.S.One, lengths[i]) + old_symbol = lookup_output.symbol() + lookup_output.set_name(name) + # Update var_list and var_range + range_tree.var_list[range_tree.var_list.index(old_symbol)] = ( + symbol + ) + range_val = range_tree.var_ranges[old_symbol] + del range_tree.var_ranges[old_symbol] + range_tree.var_ranges[symbol] = range_val + # Keep block-shape inference metadata in sync with the + # renamed epilogue range symbols used below. + if self.range_tree_nodes.get(old_symbol) is lookup_output: + del self.range_tree_nodes[old_symbol] + self.range_tree_nodes[symbol] = lookup_output + intermediate_lines.extend( + self._generate_index_from_tma_index( + name, + "xoffset" if name == "xindex" else "yoffset", + index_symbols[i], + val_shape[i], + i, + len(val_shape), + block_name=range_tree.symt.name, + ) + ) + # Generate the xmask and ymask + intermediate_lines.append( + self._generated_mask_for_tma( + name, + self.size(None, i), + "xmask" if name == "xindex" else "ymask", + ) + ) + # Update the val_shape information to use consistent naming + # after the remapping. + + val_shape_copy[i] = range_tree.symt.name + # pyrefly: ignore [bad-assignment] + val_shape = tuple(val_shape_copy) + else: + mask_vars: list[str] = [] + for i, (index, shape) in enumerate(zip(index_symbols, val_shape)): + index_name = self._gen_tmp_var() + offset_name = self._gen_tmp_var() + intermediate_lines.extend( + self._generate_index_from_tma_index( + index_name, + offset_name, + index, + shape, + i, + len(index_symbols), + ) + ) + epilogue_index_symbols.append( + sympy.Symbol(index_name, integer=True) + ) + mask_name = self._gen_tmp_var() + intermediate_lines.append( + self._generated_mask_for_tma( + index_name, + self.size(None, i), + mask_name, + ) + ) + mask_vars.append(mask_name) + final_mask_var = self._gen_tmp_var() + final_mask_rhs = " & ".join( + f"{mask_name}" for mask_name in mask_vars + ) + intermediate_lines.append(f"{final_mask_var} = {final_mask_rhs}") + self.template_mask = final_mask_var + index_symbols = epilogue_index_symbols + contiguous_index = sympy_dot(output_layout.stride, index_symbols) + if not (self.tma_store or self.tma_load_for_template_epilogue): + # Convert to just use xindex. + contiguous_index = self.rename_indexing(contiguous_index) + intermediate_lines.append(f"xindex = {texpr(contiguous_index)}") + self.range_trees[0].lookup( + sympy.S.One, sympy_product(lengths) + ).set_name("xindex") + index_symbols = epilogue_index_symbols + output_index = contiguous_index + # Write out the intermediate lines + for line in intermediate_lines: + self.body.writeline(line) + else: + if self.tma_store: + raise AssertionError("TMA store requires block indexing") + contiguous_index = self._setup_contiguous_index_state( + indices, index_symbols, lengths, mask + ) + output_index = self.output_node.get_layout().make_indexer()( + index_symbols + ) + output_index = self.rename_indexing(output_index) + if output_index == contiguous_index: + output_index = sympy.Symbol("xindex", integer=True) + + self.template_out_shape = val_shape if val_shape else val + acc_dtype = ( + triton_type_to_torch(self.meta["ACC_TYPE"]) + if "ACC_TYPE" in self.meta + else torch.float32 + ) + output_dtype = self.output_node.get_dtype() + + epilogue_args = [ + V.kernel.cse.namedvar(val, dtype=acc_dtype, shape=val_shape) + ] + epilogue_nodes_by_subgraph = getattr( + self, "_epilogue_nodes_by_subgraph", None + ) + has_epilogue_fusion = bool( + epilogue_nodes_by_subgraph[subgraph_idx] + if epilogue_nodes_by_subgraph is not None + else False + ) + for input_node in itertools.chain( + self.input_nodes[: self.prefix_args], + self.input_nodes[len(self.input_nodes) - self.suffix_args :], + ): + input_node.freeze_layout() + epilogue_arg = V.kernel.cse.generate( + self.compute, + input_node.make_loader()(index_symbols), + dtype=acc_dtype, + shape=input_node.get_size(), + ) + epilogue_args.append(epilogue_arg) + # We update frozen_layouts_cnt in order to replay this function on a cache hit. + self.frozen_layouts_cnt += 1 + + # Apply the template's manual epilogue (e.g., bias add for addmm) + epilogue_result = self.epilogue_fn(*epilogue_args) + + # When acc_dtype differs from output_dtype and there are fused + # epilogue ops, emulate unfused numerics by truncating AFTER the + # manual epilogue (so bias add happens in full precision) + if acc_dtype != output_dtype and has_epilogue_fusion: + epilogue_result = V.ops.to_dtype( + epilogue_result, + output_dtype, + src_dtype=acc_dtype, + use_compute_types=False, + ) + epilogue_result = V.ops.to_dtype( + epilogue_result, acc_dtype, src_dtype=output_dtype + ) + + V.ops.store( + self.output_node.get_name(), + output_index, + epilogue_result, + mode="tma" if self.tma_store else None, + ) + self.codegen_body() + + return self._register_hook( + subgraph_name, self._make_codegen_hook(subgraph_name, indent_width) + ) + + def _register_hook( + self, + hook_name: str, + hook_fn: PartialRender.HookFn, + *, + allow_overwriting: bool = False, + ) -> str: + """ + Register a hook function with a name. + + ``hook_name`` should match the string that will be replaced via + ``hook_fn``, and should not already be in use for a hook. + + If ``allow_overwriting`` is ``False``, will assert that there isn't + currently a registered hook of the same name before registering the new + one. + """ + + if not allow_overwriting: + if hook_name in self.render_hooks: + raise AssertionError( + f"Tried to register the hook {hook_name} multiple times. If " + "desired, pass allow_overwriting=True to _register_hook" + ) + self.render_hooks[hook_name] = hook_fn + return hook_name + + def _register_extra_template_env_fns(self, *fns: Callable[..., Any]): + """ + Register some extra functions to expose when performing the initial + template render, so that they're in scope to by used by jinja + expressions. + + These can be used to, for example, implement extra replacement hooks, + if the given function: + + * Returns the name of their hook, which should also be the string to + replace via the hook function. The convention is to use the format + . + * Assigns the corresponding entry in ``self.render_hooks`` to a hook + function. + """ + self.extra_template_env_fns.extend(fns) + + def render(self, template, kwargs, record_input_dependent_tracked_event=False): + if record_input_dependent_tracked_event: + self.cached_replay_events = [] + + template_env = { + fn.__name__: ( + self.record_input_dependent_tracked_event()(fn) + if record_input_dependent_tracked_event + else fn + ) + for fn in [ + self.def_kernel, + self.size, + self.stride, + self.store_output, + self.load_input, + self.make_load, + self.modification, + self.gen_argdefs, + self.gen_defines, + *self.extra_template_env_fns, + ] + } + return PartialRender( + template.render(**template_env, **kwargs), + self.render_hooks, + ) + + def make_load(self, name, indices, mask): + """ + Optional helper called from template code to generate the code + needed to load from a tensor. + """ + if not isinstance(indices, (list, tuple)): + raise AssertionError( + f"expected indices to be list or tuple, got {type(indices)}" + ) + if not isinstance(name, str): + raise AssertionError(f"expected name to be str, got {type(name)}") + if not isinstance(mask, str): + raise AssertionError(f"expected mask to be str, got {type(mask)}") + stride = self.get_stride_and_maybe_freeze_layout(self.named_input_nodes[name]) + indices = list(map(OpOverrides.paren, indices)) + if len(indices) != len(stride): + raise AssertionError( + f"expected len(indices) == len(stride), got {len(indices)} and {len(stride)}" + ) + index = " + ".join( + f"{texpr(self.rename_indexing(s))} * {i}" for s, i in zip(stride, indices) + ) + return f"tl.load({name} + ({index}), {mask}, other=0.0)" + + def indexing( + self, + index: sympy.Expr, + *, + dense_indexing=False, + copy_shape=None, + override_mask=None, + block_ptr=False, + tma_compatibility_checker: TMACompatibilityChecker | None = None, + mask_constant_index=False, + ): + """ + Override the default indexing to use our custom mask and force + dense indexing. + """ + return super().indexing( + index, + dense_indexing=False, + # We pass template_out as the shape to broadcast the indexing to as + # the mask might be broadcast to the output shape + copy_shape=self.template_out_shape, + override_mask=self.template_mask, + block_ptr=block_ptr, + tma_compatibility_checker=tma_compatibility_checker, + mask_constant_index=mask_constant_index, + ) + + def codegen_range_tree(self): + pass # ignore default codegen + + def additional_call_args_and_types(self): + if isinstance(self.grid_fn, SymbolicGridFn): + grid_args = self.grid_fn.sympy_call(*self.call_sizes, self.meta) + if len(grid_args) not in (0, 3): + raise AssertionError("grid_fn should return 3 values") + return (grid_args, map(type, grid_args)) + elif all(isinstance(x, (int, sympy.Integer)) for x in self.call_sizes): + grid_args = self.grid_fn(*map(int, self.call_sizes), self.meta) + if len(grid_args) not in (0, 3): + raise AssertionError("grid_fn should return 3 values") + return (grid_args, map(type, grid_args)) + return ((), ()) + + def call_kernel( + self, name: str, node: ir.IRNode | None = None, deallocate_ws: bool = True + ): + wrapper = V.graph.wrapper_code + _, call_args, _, arg_types = self.args.python_argdefs() + + additional_call_args, additional_arg_types = ( + self.additional_call_args_and_types() + ) + + if not additional_call_args: + if V.graph.cpp_wrapper: + raise AssertionError("cpp_wrapper requires SymbolicGridFn") + wrapper.add_import_once(f"import {self.grid_fn.__module__}") + meta = wrapper.add_meta_once(self.meta) + fn_name = f"{self.grid_fn.__module__}.{self.grid_fn.__name__}" + call_args.append( + f"*{fn_name}({', '.join(map(pexpr, self.call_sizes))}, {meta})" + ) + arg_types.append(None) + + call_args.extend(additional_call_args) + arg_types.extend(additional_arg_types) + + if self.workspace_arg is not None: + wrapper.generate_workspace_allocation(self.workspace_arg) + + # Use FixedGrid which properly handles grid values passed as arguments + inductor_meta = FixedGrid.setup_grid_as_args() if additional_call_args else None + wrapper.generate_kernel_call( + name, + call_args, + arg_types=arg_types, + triton_meta=self.triton_meta, + inductor_meta=inductor_meta, + triton=True, + ) + self._emit_post_kernel_code(wrapper, name) + if self.workspace_arg is not None: + wrapper.generate_workspace_deallocation(self.workspace_arg) + + def _emit_post_kernel_code(self, wrapper, kernel_name: str) -> None: + """Hook for subclasses to emit code after kernel call, before workspace dealloc.""" + pass # noqa: PIE790 + + def kernel_benchmark_extra_args(self) -> list[str]: + # Grid args are only used for benchmarking, not correctness + return [ + str(x) + for x in self.grid_fn( + *V.graph.sizevars.optimization_hints(self.call_sizes), self.meta + ) + ] + + def get_stride_and_maybe_freeze_layout(self, node) -> list[int]: + """ + Get the stride of an input node for template code generation, with deferred + layout freezing: + - If the layout is FlexibleLayout, compute speculative strides without freezing + - Record the expected layout (as FixedLayout) as a constraint for later validation + - Only freeze at finalization time after validating no conflicts exist + + Scheduler falls back to aten if layout constraint violated. If no aten, + freeze right away. + """ + + # realizing for safety + ir.ExternKernel.realize_input(node) + layout = node.data.layout + node_name = node.get_name() + + # For ReinterpretView, the view's strides are already determined by its layout. + # We skip constraint tracking because node.get_name() returns the underlying + # buffer name, not the view's identity, so constraints would be incorrectly + # associated with the underlying buffer rather than the view. + if isinstance(layout, ir.FlexibleLayout) and not isinstance( + node, ir.ReinterpretView + ): + if not use_aten_gemm_kernels() or self.always_freeze_layout: + # No ExternKernel fallback available, or always_freeze_layout is set + # (e.g., for FlexAttention templates), freeze immediately + node.data.freeze_layout() + else: + # Compute what strides WOULD be if frozen, without actually freezing + fixed_layout_copy = layout.get_fixed_layout_without_freezing() + # Save to graph-level constraints instead of per-kernel + existing = V.graph.buffer_layout_constraints.get(node_name) + if existing is not None and existing != fixed_layout_copy: + raise AssertionError( + f"Layout constraint mismatch for {node_name}: " + f"existing {existing} vs new {fixed_layout_copy}" + ) + else: + V.graph.buffer_layout_constraints[node_name] = fixed_layout_copy + + return list(fixed_layout_copy.stride) + # Already frozen or not a FlexibleLayout, just return current strides + return node.get_stride() + + def _compute_fusion_metadata( + self, scheduling, epilogue_nodes, prologue_nodes, buf_name_to_prologue_group + ): + """Prepare epilogue/prologue routing before render(). + + Default: trivial routing — all epilogues broadcast to every subgraph, + none unfused, no prologue source tracking. Override in subclasses + for per-output routing. + """ + self._epilogue_nodes_by_subgraph: defaultdict[int, list[Any]] = defaultdict( + lambda: epilogue_nodes + ) + self._unfused_epilogues: list[Any] = [] + self._prologue_sources: dict[str, frozenset[str]] = {} + + def codegen_template_body( + self, + scheduling, + template_node, + epilogue_nodes, + prologue_nodes, + buf_name_to_prologue_group, + prologue_preserves_zero_mask_fn, + render, + ) -> str: + """Generate template source code with fused prologues and epilogues. + + Returns the final source code string. + """ + self._compute_fusion_metadata( + scheduling, epilogue_nodes, prologue_nodes, buf_name_to_prologue_group + ) + with self: + partial_code = render() + + num_store_subgraphs = self.get_store_output_count() + for i in range(num_store_subgraphs): + subgraph_name = self._get_store_output_subgraph_name(i) + with self.set_subgraph_body(subgraph_name): + for node in self._epilogue_nodes_by_subgraph[i]: + node.codegen(self.split_and_set_ranges(node.get_ranges())) + self.cse.invalidate(OrderedSet()) + + self.codegen_prologues_in_subgraphs( + buf_name_to_prologue_group, prologue_preserves_zero_mask_fn + ) + + partial_code = self._finalize_partial_render(partial_code) + + # Template hooks must be finalised after kernel.remove_kernel_local_buffers + # is called (this is called when the kernel context is exited above), and when + # the kernel handler is set (as below). This is because the hooks may add + # DeferredLine type lines, which preclude lines involving buffers that have + # been removed + + # finalize must be called after adding epilogue above + with V.set_kernel_handler(self): + if isinstance(partial_code, str): + src_code = partial_code + else: + # This is used to calculate flops in TritonTemplateKernels + with ir.IRNode.current_origins(template_node.node.origins): + partial_code.finalize_hook("") + partial_code.finalize_hook("", strict=False) + + # TODO: Maybe unify CUTLASSTemplateKernel to also use PartialRender for flexible epilogue fusion. + + for input_name in self.named_input_nodes: + subgraph_name = f"" + partial_code.finalize_hook(subgraph_name, strict=False) + + num_store_subgraphs = self.get_store_output_count() + for i in range(num_store_subgraphs): + subgraph_name = self._get_store_output_subgraph_name(i) + partial_code.finalize_hook(subgraph_name) + + # Ensure all hooks are finalized before the kernel is defined. + # Note: some of these hooks may have been registered by a kernel subclass + src_code = partial_code.finalize_remaining() + + return src_code + + def codegen_prologues_in_subgraphs( + self, buf_name_to_prologue_group, prologue_preserves_zero_mask_fn + ): + """Run prologue codegen in each load-input subgraph body.""" + for input_name, buffer in self.named_input_nodes.items(): + subgraph_name = f"" + prologue_group = buf_name_to_prologue_group.get(buffer.get_name(), []) + if not prologue_group: + continue + can_codegen_without_upcast = all( + p_n.can_codegen_without_upcasts() for p_n in prologue_group + ) + with config.patch( + "triton.codegen_upcast_to_fp32", not can_codegen_without_upcast + ): + with self.set_subgraph_body(subgraph_name): + for prologue_node in prologue_group: + if ( + len(prologue_node.get_buffer_names()) == 1 + and len(prologue_group) == 1 + ): + if prologue_preserves_zero_mask_fn(prologue_node): + self.prologue_fused_inputs_preserve_zero |= ( + prologue_node.get_buffer_names() + ) + prologue_node.codegen( + self.split_and_set_ranges(prologue_node.get_ranges()) + ) + self.cse.invalidate(OrderedSet()) + + def _finalize_partial_render( + self, partial_code: str | PartialRender + ) -> str | PartialRender: + """Hook to intercept or replace the PartialRender before hook finalization. + + Called after Inductor has populated subgraph buffers (epilogue stores, + prologue loads) but before ``finalize_hook`` resolves placeholders. + Subclasses may return a replacement ``PartialRender`` — e.g. to capture + the rendered hook outputs and supply entirely new source code (as + ``ExternalTritonTemplateKernel`` does for fusion-aware autotuning). + """ + return partial_code + + +class ExternalTritonTemplateKernel(TritonTemplateKernel): + """TritonTemplateKernel variant for external template backends (e.g. Helion). + + Orchestrates prologue/epilogue fusion by running Inductor's codegen ops + (store, load, indexing) on fused scheduler nodes, capturing the generated + code into subgraph buffers. The backend's ``render()`` callable handles + hook setup and AST generation, while the standard ``codegen_template_body`` + handles hook finalization and subgraph codegen. + + Also implements ``call_kernel`` and ``emit_kernel_override`` for + post-codegen emission of the fused kernel. + + Subclasses TritonTemplateKernel for subgraph body management and + template indexing support. + """ + + def __init__(self, template_buffer: "ir.TemplateBuffer") -> None: + class _RealOutputNode: + def get_size(self) -> list: + return list(template_buffer.get_size()) + + def get_layout(self): + return template_buffer.get_layout() + + def get_name(self) -> str: + return template_buffer.get_name() + + # Pass dummy values for TritonTemplateKernel params that are only + # relevant for standalone Triton kernel codegen (grid, warps, etc.). + super().__init__( + kernel_name="", + input_nodes=(), + output_node=_RealOutputNode(), + defines={}, + num_stages=0, + num_warps=1, + grid_fn=None, + meta={}, + call_sizes=[], + hint_override=None, + ) + self._template_buffer = template_buffer + # Extra inputs needed by fused ops beyond the template's own I/O + self._extra_inputs: dict[str, str] = {} + # Prologue primary source buffers, populated by load_input + self._prologue_source_buffers: dict[str, str | None] = {} + # Simplified epilogue interface: {output_param: epilogue_idx} + self._epilogue_idx_by_param: dict[str, int] = {} + # Output params that must keep their original tl.store + self._epilogue_keep_store: OrderedSet[str] = OrderedSet() + # Store target buffers: {buf_name: param_name} + self._extra_store_targets: dict[str, str] = {} + # Prologue variable names per input param + self._prologue_vars: dict[str, dict[str, str]] = {} + # Import lines for emit_kernel_override, populated by external render + self._kernel_imports: list[str] = [] + # Call emission state, populated by _setup_fusion_hooks / external render + self._call_preamble: list[str] = [] + self._call_args: list[str] = [] + # Epilogues that could not be fused into the kernel + self._unfused_epilogues: list[Any] = [] + # Reference to the scheduler, set by _compute_fusion_metadata; + # used in call_kernel() to codegen unfused epilogue nodes + self._scheduling_ref: Any = None + + def _finalize_partial_render( + self, partial_code: str | PartialRender + ) -> str | PartialRender: + # Capture hook outputs. + hook_outputs: dict[str, str] = {} + with V.set_kernel_handler(self): + for key, hook in self.render_hooks.items(): + hook_outputs[key] = hook() + + # Delegate to template buffer. + result = self._template_buffer._finalize_codegen(hook_outputs) + if result is None: + return partial_code + + # Apply structured result to kernel state. + self._kernel_imports = result.imports + self._call_preamble = result.call_preamble + self._call_args = result.call_args + + # Freeze hooks and clear subgraph buffers. + if hook_outputs: + self.render_hooks = { + k: (lambda captured=v: captured) for k, v in hook_outputs.items() + } + for info in self.subgraph_bodies.values(): + info.loads = IndentedBuffer() + info.compute = IndentedBuffer() + info.stores = IndentedBuffer() + info.indexing_code = IndentedBuffer() + + return PartialRender(result.source, self.render_hooks) + + def get_unfused_epilogues(self) -> list[Any]: + return self._unfused_epilogues + + def _compute_fusion_metadata( + self, scheduling, epilogue_nodes, prologue_nodes, buf_name_to_prologue_group + ): + """Compute fusion metadata for external backends. + + Determines eligible epilogues/prologues, builds epilogue specs, + and computes prologue sources — all before render(). + + Hook setup (_setup_epilogue_hook / _setup_prologue_hook) cannot + happen here because it requires V.kernel context, which is only + active during codegen_template_body → render(). + """ + self._scheduling_ref = scheduling + from torch._inductor.dependencies import MemoryDep + + tb = self._template_buffer + self._eligible_epilogues = self._find_eligible_epilogues( + epilogue_nodes, tb.epilogue_fusable_outputs + ) + self._epilogue_nodes_by_subgraph = defaultdict( + list, + {i: [sn] for i, (sn, _, _, _) in enumerate(self._eligible_epilogues)}, + ) + fused_ids = OrderedSet(id(sn) for sn, _, _, _ in self._eligible_epilogues) + self._unfused_epilogues = [ + n + for n in epilogue_nodes + if id(n) not in fused_ids and not isinstance(n.node, ir.MultiOutput) + ] + self._prologue_sources = { + buf_name: frozenset( + d.name for d in pro_node.read_writes.reads if isinstance(d, MemoryDep) + ) + for buf_name, pro_nodes in buf_name_to_prologue_group.items() + for pro_node in pro_nodes + } + + # Build simplified epilogue interface: _epilogue_idx_by_param, + # _epilogue_keep_store, and _extra_store_targets. + from torch._inductor.codegen.common import RemovedArg + + scheduler = V.graph.scheduler + epilogues = self._eligible_epilogues + + # Compute fused node names for buffer removability + fused_node_names = None + if scheduler is not None: + all_store_names = OrderedSet([tb.get_name()]) + all_store_names.update(tb._multi_output_children) + all_store_names.update(st for _, _, _, st in epilogues if st) + fused_node_names = OrderedSet( + scheduler.name_to_buf[n].defining_op_name() + for n in all_store_names + if n in scheduler.name_to_buf + ) + + # Pre-register store_target buffers so we know their param names + for _, _, _, store_target in epilogues: + if ( + store_target is not None + and store_target not in self.args.output_buffers + ): + self.args.output(store_target) + + # Build per-epilogue metadata + for i, (_, output_buf, output_param, store_target) in enumerate(epilogues): + self._epilogue_idx_by_param[output_param] = i + + can_remove = ( + store_target is not None + and fused_node_names is not None + and scheduler.can_buffer_be_removed_through_fusion( + output_buf, fused_node_names + ) + ) + + store_target_param_raw = ( + self.args.output_buffers.get(store_target) + if store_target is not None + else None + ) + store_target_param = ( + None + if isinstance(store_target_param_raw, RemovedArg) + else store_target_param_raw + ) + + if store_target_param is not None: + self._extra_store_targets[store_target] = store_target_param + if can_remove: + self.removed_buffers.add(output_buf) + else: + self._epilogue_keep_store.add(output_param) + + def _setup_fusion_hooks(self): + """Set up epilogue/prologue render hooks and mark prologue buffers. + + Must be called during render() (inside V.kernel context), after + _compute_fusion_metadata has run. + """ + tb = self._template_buffer + + # Mark prologue buffers on the kernel. + for pro_buf, source_bufs in self._prologue_sources.items(): + self.store_buffer_names.add(pro_buf) + if not source_bufs: + self.removed_buffers.add(pro_buf) + + # Set up epilogue hooks. + epilogues = self._eligible_epilogues + for epilogue_idx in range(len(tb.epilogue_fusable_outputs)): + epi = epilogues[epilogue_idx] if epilogue_idx < len(epilogues) else None + self._setup_epilogue_hook( + output_buf=epi[1] if epi else None, + output_param=epi[2] if epi else None, + ) + + # Set up prologue hooks. + for param_name in tb._named_inputs: + self._setup_prologue_hook( + param_name, prologue_sources=self._prologue_sources + ) + + # Register no-op hook (standard path requires it). + self.render_hooks[""] = lambda: "" + + def _find_eligible_epilogues(self, epilogue_nodes, output_param_mapping): + """Compute fusion eligibility and register extra inputs. + + Returns list of eligible epilogue tuples: + [(snode, output_buf, output_param, store_target), ...] + """ + from torch._inductor.dependencies import MemoryDep + + # Filter eligible epilogues + epilogues = [] + for epilogue_node in epilogue_nodes: + if isinstance(epilogue_node.node, ir.MultiOutput): + continue + dep_names = OrderedSet( + d.name + for d in epilogue_node.read_writes.reads + if isinstance(d, MemoryDep) and d.name in output_param_mapping + ) + if len(dep_names) != 1: + continue + output_buf = next(iter(dep_names)) + epilogue_writes = epilogue_node.read_writes.writes + raw_st = next(iter(epilogue_writes)).name if epilogue_writes else None + epilogues.append( + ( + epilogue_node, + output_buf, + output_param_mapping[output_buf], + raw_st if raw_st != output_buf else None, + ) + ) + + # Register extra inputs needed by fused epilogues + for snode, _, _, _ in epilogues: + for dep in snode.read_writes.reads: + if isinstance(dep, MemoryDep) and dep.name not in output_param_mapping: + if dep.name not in self._extra_inputs: + param = f"_extra_input_{len(self._extra_inputs)}" + self._extra_inputs[dep.name] = param + self.args.input_buffers[dep.name] = param + + return epilogues + + def _setup_epilogue_hook(self, output_buf=None, output_param=None): + store_idx = next(self.store_output_ctr) + subgraph_name = self._get_store_output_subgraph_name(store_idx) + if output_buf is None: + self.subgraph_bodies[subgraph_name] = SubgraphInfo(body=IndentedBuffer()) + self.render_hooks[subgraph_name] = lambda: "" + return + + n_dims = len(self._template_buffer.get_size()) + indices = [f"x_epilogue{store_idx}_{d}" for d in range(n_dims)] + val = f"_kernel_val_{store_idx}" + mask = f"_tile_mask_{store_idx}" + + buf = output_buf + node = V.graph.get_buffer(buf) if buf else None + output_size = ( + list(node.get_size()) + if node is not None + else list(self.output_node.get_size()) + ) + self._make_independent_subgraph(subgraph_name, sympy_product(output_size)) + with self.set_subgraph_body(subgraph_name): + indices = list(map(OpOverrides.paren, indices)) + index_symbols = [sympy.Symbol(x, integer=True) for x in indices] + lengths = [V.graph.sizevars.simplify(s) for s in output_size] + if len(indices) != len(lengths): + raise AssertionError( + f"expected len(indices) == len(lengths), got {len(indices)} and {len(lengths)}" + ) + self.template_out = val + self._setup_contiguous_index_state( + indices, + index_symbols, + lengths, + mask, + xindex_name=f"x_epilogue{store_idx}_index", + ) + self.template_out_shape = val + + # Set up CSE state for epilogue codegen + block_shape = tuple( + f"{rt.prefix.upper()}BLOCK" + for rt in self.range_trees + if not rt.is_reduction + ) + if not block_shape: + block_shape = ("XBLOCK",) + self.cse.store_cache[buf] = self.cse.namedvar( + val, dtype=torch.float32, shape=block_shape + ) + if output_param is None: + raise AssertionError("output_param must not be None") + self.args.output_buffers[buf] = output_param + + self.render_hooks[subgraph_name] = self._make_codegen_hook(subgraph_name) + + def _setup_prologue_hook(self, input_name, prologue_sources=None): + ir_node = self._template_buffer._named_inputs.get(input_name) + if ir_node is None: + return + self.named_input_nodes[input_name] = ir_node + input_buf = ir_node.get_name() + source_bufs = ( + prologue_sources.get(input_buf) if prologue_sources is not None else None + ) + if source_bufs is None: + return + source_buffer = next(iter(source_bufs)) if source_bufs else None + self._prologue_source_buffers[input_name] = source_buffer + if source_buffer is not None: + self.args.input_buffers[source_buffer] = input_name + for src in source_bufs: + if src != source_buffer: + if src not in self._extra_inputs: + self._extra_inputs[src] = f"_extra_input_{len(self._extra_inputs)}" + self.args.input_buffers[src] = self._extra_inputs[src] + + subgraph_name = f"" + result_var = f"_prologue_{input_name}_result" + + # Compute prologue variable names once and store them. + renames = { + "xindex": f"_prologue_{input_name}_xindex", + "xmask": f"_prologue_{input_name}_xmask", + } + self._prologue_vars[input_name] = { + "xindex": renames["xindex"], + "xmask": renames["xmask"], + "result": result_var, + } + + class _CaptureStoreHandler(V.WrapperHandler): # type: ignore[name-defined] + def store(self, name, index, value, mode=None): + V.kernel.store_buffer_names.add(name) + V.kernel.cse.store_cache[name] = value + V.kernel.compute.writeline(f"{result_var} = {value}") + + self._make_independent_subgraph( + subgraph_name, + sympy_product(ir_node.get_size()), + ops_handler=_CaptureStoreHandler, + root_var_renames=renames, + ) + + def hook(_name=subgraph_name, _input=input_name, _self=self): + with _self.set_subgraph_body(_name): + _self.codegen_body() + _self.cse.invalidate(OrderedSet()) + body = _self.body.getvalue() + # Rename range-tree root variables (xindex/xmask) to avoid collisions + # across prologue subgraphs. tmp/x0 names are already unique (shared + # kernel-level counters). Read renames from the subgraph info. + subgraph = _self.subgraph_bodies[_name] + for orig, renamed in subgraph.root_var_renames.items(): + body = re.sub(rf"\b{orig}\b", renamed, body) + return body.rstrip() + + self.render_hooks[f""] = hook + + def call_kernel(self, name, node=None, deallocate_ws=True): + """Emit the kernel call, multi-output unpacking, and unfused epilogues.""" + tb = self._template_buffer + wrapper = V.graph.wrapper_code + for line in self._call_preamble: + wrapper.writeline(line) + output_name = tb.get_name() + wrapper.writeline(f"{output_name} = {name}({', '.join(self._call_args)})") + # Unpack multi-output children from the kernel result + for mo_name, mo in sorted(tb._multi_output_children.items()): + if mo_name not in self.removed_buffers: + idx_str = output_name + for _, idx in mo.indices: + idx_str = f"{idx_str}[{idx}]" + wrapper.writeline(f"{mo_name} = {idx_str}") + # Unfused epilogues are codegen'd separately after the kernel call + for epi_node in self._unfused_epilogues: + self._scheduling_ref.codegen_node(epi_node) + + def emit_kernel_override( + self, + wrapper, + src_code, + kernel_name, + node_schedule, + kernel_path, + get_kernel_metadata, + ): + origins, detailed = get_kernel_metadata(node_schedule, wrapper) + wrapper.header.writeline(f"# kernel path: {kernel_path}\n{origins}\n{detailed}") + for imp in self._kernel_imports: + wrapper.add_import_once(imp) + # Hooks may reference standard Inductor runtime modules + wrapper.add_import_once( + "from torch._inductor.runtime import triton_helpers, triton_heuristics" + ) + wrapper.add_import_once( + "from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math" + ) + wrapper.header.splice(src_code, strip=True) + wrapper.header.writeline("") + return True + + +@functools.cache +def _jinja2_env(): + try: + import jinja2 + + return jinja2.Environment( + undefined=jinja2.StrictUndefined, + ) + except ImportError: + return None + + +class GenerateAndLoadResult(NamedTuple): + """ + Return type of TritonTemplate.generate_and_load. + """ + + mod: ModuleType + extra: str + input_call_args: tuple[str, ...] + prologue_supported_inputs: OrderedSet[str] + kernel_args_sizevars_keys: tuple[sympy.Expr, ...] + kernel_options: dict[str, Any] + + +class GeneratedCodeCacheEntry(NamedTuple): + code: str + extra: str + events: list[Any] + + +def template_subgraph_index_dtype_nodes( + subgraphs: Sequence[Any] | None, +) -> tuple[ir.IRNode, ...]: + """Return graph buffers referenced by template subgraphs for index-width selection.""" + if subgraphs is None: + return () + + nodes: list[ir.IRNode] = [] + seen_names: OrderedSet[str] = OrderedSet() + pending: list[Any] = list(reversed(subgraphs)) + while pending: + subgraph = pending.pop() + if isinstance(subgraph, (list, tuple)): + pending.extend(reversed(subgraph)) + continue + if subgraph is None: + continue + for dep in subgraph.get_read_writes().reads_and_writes(): + if dep.name in seen_names: + continue + buffer = V.graph.try_get_buffer(dep.name) + if isinstance(buffer, ir.IRNode): + nodes.append(buffer) + seen_names.add(dep.name) + return tuple(nodes) + + +class GeneratedCodeCache: + """ + Cache for generated code. The cache key is a string representation of the input nodes, + number of stages, number of warps, and call sizes. The cache value is a tuple of the + generated code, extra code, and events. + """ + + def __init__(self, *args, **kwargs): + self._cache: dict[str, GeneratedCodeCacheEntry] = {} + + def cache_clear(self) -> None: + self._cache.clear() + + def __repr__(self): + return repr(self._cache) + + def make_key( + self, + input_nodes: tuple[ir.IRNode, ...], + num_stages: int, + num_warps: int, + call_sizes: Sequence[sympy.core.symbol.Symbol], + prefix_args: int, + suffix_args: int, + epilogue_fn: Callable[..., Any] | None, + epilogue_fn_hash: str | None, + tma_store: bool, + tma_load_for_template_epilogue: bool, + transpose_discontiguous_tensor_descriptors_override: bool | None, + subgraphs: list[ir.Buffer] | None, # has to be none to cache + workspace_arg: WorkspaceArg | None, # has to be none to cache + layout: ir.Layout, + num_consumer_groups: int, + num_buffers_warp_spec: int, + kwargs: dict[str, Any], + hint_override: int | None = None, + triton_meta: TritonMeta | None = None, + ) -> str | None: + def layout_key(layout: ir.Layout) -> str: + if isinstance(layout, ir.FlexibleLayout): + raise AssertionError("layout must not be a FlexibleLayout") + return repr( + [ + layout.size, + layout.stride, + layout.dtype, + layout.device, + layout.offset, + ] + ) + + def has_flexible_layout() -> bool: + if isinstance(layout, ir.FlexibleLayout): + return True + + for input_node in input_nodes: + if isinstance(input_node.get_layout(), ir.FlexibleLayout): + return True + return False + + if epilogue_fn is identity: + if epilogue_fn_hash is not None: + raise AssertionError("epilogue_fn_hash must be None") + epilogue_fn_hash = "identity" + + # we do not cache under those conditions right now. + if ( + has_flexible_layout() + or subgraphs is not None + or workspace_arg is not None + or epilogue_fn_hash is None + ): + return None + + return repr( + { + "input_nodes": [ + layout_key(input.get_layout()) for input in input_nodes + ], + "num_stages": num_stages, + "num_warps": num_warps, + "prefix_args": prefix_args, + "suffix_args": suffix_args, + "call_sizes": call_sizes, + "layout": layout_key(layout), + "num_consumer_groups": num_consumer_groups, + "num_buffers_warp_spec": num_buffers_warp_spec, + "epilogue_fn_hash": epilogue_fn_hash, + "tma_store": tma_store, + "tma_load_for_template_epilogue": tma_load_for_template_epilogue, + "transpose_discontiguous_tensor_descriptors_override": transpose_discontiguous_tensor_descriptors_override, + "kwargs": kwargs, + "hint_override": hint_override, + "triton_meta": triton_meta, + } + ) + + def get_entry(self, cache_key: str | None) -> GeneratedCodeCacheEntry | None: + if cache_key is None: + return None + + entry = self._cache.get(cache_key, None) + if entry is None: + torch._dynamo.utils.counters["inductor"]["generated_module_cache_miss"] += 1 + else: + torch._dynamo.utils.counters["inductor"]["generated_module_cache_hit"] += 1 + return entry + + def put_entry( + self, + cache_key: str | None, + code: str, + extra: str, + events: list[Any], + ) -> None: + if cache_key is None: + return + entry = GeneratedCodeCacheEntry(code, extra, events) + self._cache.update({cache_key: entry}) + + +class TritonTemplate(KernelTemplate): + """ + A Triton template is a template that can be used to generate a Triton kernel. + """ + + # Allow subclasses to override the kernel type + kernel_type: type[Any] = TritonTemplateKernel + index_counter = itertools.count() + all_templates: dict[str, "TritonTemplate"] = {} + + def __init__( + self, + name: str, + grid: Any, + source: str, + debug=False, + cache_codegen_enabled_for_template=False, + prologue_loads_all_inputs=False, + always_freeze_layout: bool = False, + ) -> None: + super().__init__(name, hash=hashlib.sha256(source.encode("utf-8")).hexdigest()) + self.grid = grid + self.template = self._template_from_string(source) + # A module that registers templates can be initialized more than once in + # a single process (e.g. a double-import path). Tolerate re-registration + # under an existing name as long as the template source matches, but + # reject a genuine name collision between different templates. + existing = self.all_templates.get(name) + if existing is not None and existing.src_hash != self.src_hash: + raise AssertionError("duplicate template name") + TritonTemplate.all_templates[name] = self + self.debug = debug + self._cache_codegen_enabled_for_template = cache_codegen_enabled_for_template + self._generated_code_cache: GeneratedCodeCache = GeneratedCodeCache() + clear_on_fresh_cache(self._generated_code_cache) + # When prologue_loads_all_inputs is true, prologue_supported_inputs is populated during def_kernel + # by adding all inputs. + self.prologue_loads_all_inputs = prologue_loads_all_inputs + # When always_freeze_layout is True, the kernel will always freeze layouts + # immediately instead of using layout constraints. This is used by + # FlexAttention templates which require frozen layouts. + self.always_freeze_layout = always_freeze_layout + + # When this flag is on, we ensure that the cached results and the generated result if cache + # was not used are the same. + test_cache = False + + @property + def uid(self) -> str: + # unique by prefixing with triton + return f"triton::{self.name}" + + def maybe_append_choice( + self, choices: list[Any], **kwargs: Any + ) -> NotImplementedError | None: + """ + Maybe generates a new ChoiceCaller and appends it into existing choices. + Returns None if success, otherwise returns the error. + + choices: A list of ChoiceCallers. + kwargs: Additional kwargs to be passed to self.generate() to generate a new ChoiceCaller. + """ + + try: + choice = self.generate(generate_with_caching=True, **kwargs) + if choice is not None: + choices.append(choice) + return None + except NotImplementedError as e: + log.info( + "Cannot Append Choice: %s. KernelTemplate type is %s", + e, + type(self), + stack_info=log.getEffectiveLevel() < logging.INFO, + ) + return e + + # NOTE: MAKE SURE THAT ANY ARGUMENT ADDED TO THIS FUNCTION IS PROPERLY HANDLED IN _generated_code_cache.make_key. + def generate_and_load( + self, + input_nodes: tuple[ir.IRNode, ...], + num_stages: int, + num_warps: int, + call_sizes: Sequence[sympy.core.symbol.Symbol], + prefix_args: int, + suffix_args: int, + epilogue_fn: Callable[..., Any] | None, + epilogue_fn_hash: str | None, + subgraphs: list[ir.Buffer] | None, + workspace_arg: WorkspaceArg | None, + num_consumer_groups: int, + num_buffers_warp_spec: int, + layout: ir.Layout, + kwargs: dict[str, Any], + generate_with_caching, + hint_override: int | None = None, + tma_store: bool = False, + tma_load_for_template_epilogue: bool = False, + transpose_discontiguous_tensor_descriptors_override: bool | None = None, + triton_meta: TritonMeta | None = None, + ) -> GenerateAndLoadResult | None: + """Generate the python code and load it into the current process""" + caching_enabled = ( + generate_with_caching + and torch._inductor.config.enable_caching_generated_triton_templates + ) + + cache_key = None + if caching_enabled: + cache_key = self._generated_code_cache.make_key( + input_nodes, + num_stages, + num_warps, + call_sizes, + prefix_args, + suffix_args, + epilogue_fn, + epilogue_fn_hash, + tma_store, + tma_load_for_template_epilogue, + transpose_discontiguous_tensor_descriptors_override, + subgraphs, + workspace_arg, + layout, + num_consumer_groups, + num_buffers_warp_spec, + kwargs, + hint_override, + triton_meta, + ) + + if not self.template: + raise AssertionError("requires jinja2") + defines = StringIO() + + for name, val in kwargs.items(): + defines.write(f"{name} : tl.constexpr = {val}\n") + + fake_out = ir.Buffer(name="buf_out", layout=layout) + kernel_name = f"triton_{self.name}" + + numel = sympy_product(layout.size) + buffers = itertools.chain( + input_nodes, + template_subgraph_index_dtype_nodes(subgraphs), + (fake_out,), + ) + + if TritonScheduling.can_use_32bit_indexing(numel, buffers): + index_dtype = "tl.int32" + else: + index_dtype = "tl.int64" + + # Add index dtype to defines so it's available in the template + defines.write(f"INDEX_DTYPE : tl.constexpr = {index_dtype}\n") + defines = defines.getvalue() + + kernel_options = { + "input_nodes": input_nodes, + "defines": defines, + "num_stages": num_stages, + "num_warps": num_warps, + "grid_fn": self.grid, + "meta": kwargs, + "call_sizes": call_sizes, + "prefix_args": prefix_args, + "suffix_args": suffix_args, + "epilogue_fn": epilogue_fn, + "subgraphs": subgraphs, + "prologue_loads_all_inputs": self.prologue_loads_all_inputs, + "always_freeze_layout": self.always_freeze_layout, + "index_dtype_override": index_dtype, + } + + if HAS_WARP_SPEC: + kernel_options.update( + { + "num_consumer_groups": num_consumer_groups, + "num_buffers_warp_spec": num_buffers_warp_spec, + } + ) + + def make_kernel(): + return self.kernel_type( + kernel_name=kernel_name, + output_node=fake_out, + workspace_arg=workspace_arg, + use_jit=False, + hint_override=hint_override, + tma_store=tma_store, + tma_load_for_template_epilogue=tma_load_for_template_epilogue, + transpose_discontiguous_tensor_descriptors_override=transpose_discontiguous_tensor_descriptors_override, + triton_meta=triton_meta, + **kernel_options, + ) + + def generate_code(kernel) -> tuple[str, str] | None: + def make_extra() -> str: + extra_parts = [ + f"{kwarg}={repr(kwargs[kwarg])}" for kwarg in sorted(kwargs.keys()) + ] + + extra_parts.extend( + [ + f"num_stages={num_stages}", + f"num_warps={num_warps}", + ] + ) + if HAS_WARP_SPEC: + extra_parts.extend( + [ + f"num_consumer_groups={num_consumer_groups}", + f"num_buffers_warp_spec={num_buffers_warp_spec}", + ] + ) + extra = "-".join(extra_parts) + "-" + return extra + + try: + template = kernel.render(self.template, kwargs, caching_enabled) + code = template.finalize_all() + except ZeroDivisionError: + # TODO(nmacchioni): fix sympy division by zero + return None + if self.debug: + print("Generated Code:\n", code) + + extra = make_extra() + return code, extra + + def maybe_test_cache(code: str, extra: str, kernel): + if self.test_cache or self.debug: + with ( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(fake_out)), + V.graph.set_current_device(layout.device), + make_kernel() as kernel_test, + ): + result2 = generate_code(kernel_test) + if result2 is None: + raise AssertionError("result2 must not be None") + code_test, extra_test = result2 + if not ( + code == code_test + and extra == extra_test + and kernel.args.input_buffers == kernel_test.args.input_buffers + and kernel.prologue_supported_inputs + == kernel_test.prologue_supported_inputs + and kernel.args.sizevars == kernel_test.args.sizevars + ): + raise AssertionError( + "Generated code cache results in wrong output" + ) + + # Generate code, extra. + code: str | None = None + extra: str | None = None + with ( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(fake_out)), + V.graph.set_current_device(layout.device), + make_kernel() as kernel, + ): + cache_entry = self._generated_code_cache.get_entry(cache_key) + cache_hit = False + + if cache_entry is not None: + code, extra, events = cache_entry + kernel.replay_cached_events(events) + cache_hit = True + + else: + result = generate_code(kernel) + if result is None: # happens at ZeroDivisionError: + return None + code, extra = result + self._generated_code_cache.put_entry( + cache_key, code, extra, kernel.cached_replay_events + ) + + if not (code is not None and extra is not None): + raise AssertionError("code and extra must not be None") + + mod = PyCodeCache.load(code, extra, set_sys_modules=False) + + input_call_args = tuple(kernel.args.input_buffers.keys()) + prologue_supported_inputs = kernel.prologue_supported_inputs.copy() + kernel_args_sizevars_keys = tuple(kernel.args.sizevars.keys()) + + if cache_hit: + maybe_test_cache(code, extra, kernel) + + return GenerateAndLoadResult( + mod, + extra, + input_call_args, + prologue_supported_inputs, + kernel_args_sizevars_keys, + kernel_options, + ) + + def generate( # type: ignore[override] + self, + input_nodes: tuple[ir.IRNode, ...], + layout: ir.Layout, + num_stages: int, + num_warps: int, + num_consumer_groups: int = 0, + num_buffers_warp_spec: int = 0, + prefix_args: int = 0, + suffix_args: int = 0, + epilogue_fn: Callable[..., Any] | None = identity, + epilogue_fn_hash: str | None = None, + subgraphs: list[ir.Buffer] | None = None, + mutated_inputs: list[ir.IRNode] | None = None, + call_sizes: Sequence[sympy.core.symbol.Symbol] | None = None, + workspace_arg: WorkspaceArg | None = None, + generate_with_caching=False, + hint_override: int | None = None, + tma_store: bool = False, + tma_load_for_template_epilogue: bool = False, + transpose_discontiguous_tensor_descriptors_override: bool | None = None, + triton_meta: TritonMeta | None = None, + **kwargs, + ): + """This function generates a TritonTemplateCaller + + Args: + input_nodes: List of input nodes + layout: Output layout + num_stages: Number of stages for triton launch + num_warps: Number of warps for triton launch + prefix_args: Number of input nodes to be passed as arguments + suffix_args: Number of input nodes to be passed as arguments + epilogue_fn: Optional epilogue function to be called on the output + subgraphs: Optional subgraphs to be passed as arguments, these will be inlined + into the triton template string + mutated_inputs: Optional list of input nodes that are mutated by the kernel, this is helpful + if you need to return multiple outputs. You can pass them as inputs and mark them as + being mutated by the kernel. + """ + # HACK: Triton currently breaks if TF32 floats are requested, but the CUDA + # capability doesn't support them. This is a bug in Triton, but for now we'll + # patch around it here. See https://github.com/triton-lang/triton/issues/3011 + # for one example issue with this problem. + if torch.cuda.is_available() and not torch.cuda.is_tf32_supported(): + kwargs["ALLOW_TF32"] = "False" + + if call_sizes is None: + call_sizes = layout.size + + result = self.generate_and_load( + input_nodes, + num_stages, + num_warps, + call_sizes, + prefix_args, + suffix_args, + epilogue_fn, + epilogue_fn_hash, + subgraphs, + workspace_arg, + num_consumer_groups, + num_buffers_warp_spec, + layout, + kwargs, + generate_with_caching and self._cache_codegen_enabled_for_template, + hint_override=hint_override, + tma_store=tma_store, + tma_load_for_template_epilogue=tma_load_for_template_epilogue, + transpose_discontiguous_tensor_descriptors_override=transpose_discontiguous_tensor_descriptors_override, + triton_meta=triton_meta, + ) + + # May happen as result of dev by 0. + if result is None: + return None + + # We expect the input_buffer order to be [*input_nodes, *captured_buffers] + expected_input_args = tuple(unique(x.get_name() for x in input_nodes)) + if result.input_call_args[: len(expected_input_args)] != expected_input_args: + raise AssertionError( + ( + result.input_call_args, + expected_input_args, + ) + ) + + # `kernel_input_nodes` are the actual inputs that will be passed to the kernel, + # so e.g. views of the same input are not included. `codegen_input_nodes` + # includes views of inputs to preserve the kernel semantics. The shape and + # strides of `codegen_input_nodes` will be used to infer read/writes in + # TemplateBuffer.extract_read_writes + kernel_input_nodes = tuple( + [V.graph.get_buffer(k) for k in result.input_call_args] + ) + # Here we have (*input_nodes, *captured_buffers) + codegen_input_nodes = ( + tuple(input_nodes) + kernel_input_nodes[len(expected_input_args) :] + ) + + extra_args = tuple( + V.graph.sizevars.optimization_hint_with_override( + sympy.expand(e), + hint_override=hint_override, + ) + for e in result.kernel_args_sizevars_keys + ) + + kernel_hash_name = f"triton_{self.name}_{next(self.index_counter)}" + + # Extract workspace metadata for async autotuning (don't create tensor here + # as it can't be pickled for subprocess communication) + workspace_size_bytes: int | None = None + workspace_zero_fill = False + workspace_args = [] + if workspace_arg is not None: + ws_count = V.graph.sizevars.optimization_hint(workspace_arg.count) + workspace_size_bytes = ws_count * get_dtype_size(workspace_arg.dtype) + workspace_zero_fill = ( + workspace_arg.zero_mode != WorkspaceZeroMode.UNINITIALIZED + ) + + workspace_args.append(WORKSPACE_ARG_PLACEHOLDER) + + options = result.kernel_options + + def make_kernel_render(out_node, hint_override: int | None = None): + if result is None: + raise AssertionError("result must not be None") + # Create a new unique name for the workspace arg buffer for each render + # to prevent buffer reuse of the same workspace arg + kernel_workspace_arg = workspace_arg + if workspace_arg is not None: + kernel_workspace_arg = WorkspaceArg( + count=workspace_arg.count, + zero_mode=workspace_arg.zero_mode, + device=workspace_arg.device, + outer_name=WorkspaceArg.unique_name(), + inner_name=workspace_arg.inner_name, + dtype=workspace_arg.dtype, + ) + kernel = self.kernel_type( + kernel_name=str(Placeholder.KERNEL_NAME), + output_node=out_node, + workspace_arg=kernel_workspace_arg, + use_jit=False, + hint_override=hint_override, + tma_store=tma_store, + tma_load_for_template_epilogue=tma_load_for_template_epilogue, + transpose_discontiguous_tensor_descriptors_override=transpose_discontiguous_tensor_descriptors_override, + triton_meta=triton_meta, + **options, + ) + render = functools.partial( + kernel.render, + self.template, + kwargs, + ) + return kernel, render + + # create the BenchmarkRequest + if result.mod.__file__ is None: + raise AssertionError("result.mod.__file__ must not be None") + + grid = self.grid( + *V.graph.sizevars.optimization_hints_with_override( + call_sizes, + hint_override=hint_override, + ), + kwargs, + ) + bmreq_cls: type[TritonBenchmarkRequest] + if layout.device.type == "cpu": + bmreq_cls = TritonCPUBenchmarkRequest + else: + bmreq_cls = TritonGPUBenchmarkRequest + bmreq = bmreq_cls( + module_path=result.mod.__file__, + module_cache_key=result.mod.key, + kernel_name=f"triton_{self.name}", + extra_args=[*extra_args, *workspace_args, *grid], + num_stages=num_stages, + num_warps=num_warps, + num_consumer_groups=num_consumer_groups, + num_buffers_warp_spec=num_buffers_warp_spec, + matrix_instr_nonkdim=kwargs.get("matrix_instr_nonkdim", 0), + waves_per_eu=kwargs.get("waves_per_eu", 0), + kpack=kwargs.get("kpack", 2), + workspace_size=workspace_size_bytes, + workspace_zero_fill=workspace_zero_fill, + input_tensor_meta=TensorMeta.from_irnodes(kernel_input_nodes), # type: ignore[arg-type] + output_tensor_meta=TensorMeta.from_irnodes(layout), + ) + + # Convolution-specific parameters to include in logging + CONV_TUNABLE_KEYS = [ + "KERNEL_H", + "KERNEL_W", + "KERNEL_D", + "STRIDE_H", + "STRIDE_W", + "STRIDE_D", + "PADDING_H", + "PADDING_W", + "PADDING_D", + "GROUPS", + "UNROLL", + ] + + return TritonTemplateCaller( + kernel_hash_name, + codegen_input_nodes, + layout, + make_kernel_render, + result.extra.strip("-").replace("-", ", "), + bmreq, + log_info={ + "tile_shape": str( + ( + kwargs.get("BLOCK_M", -1), + kwargs.get("BLOCK_K", -1), + kwargs.get("BLOCK_N", -1), + ) + ), + "num_stages": num_stages, + "num_warps": num_warps, + "GROUP_M": kwargs.get("GROUP_M", -1), + "allow_tf32": str(kwargs.get("ALLOW_TF32")), + "acc_type": str(kwargs.get("ACC_TYPE")), + "matrix_instr_nonkdim": kwargs.get("matrix_instr_nonkdim", 0), + "waves_per_eu": kwargs.get("waves_per_eu", 0), + "kpack": kwargs.get("kpack", 2), + "epilogue_subtile": kwargs.get("EPILOGUE_SUBTILE", 0), + **{ + k: kwargs[k] + for k in AlgorithmSelectorCache.FLEX_ATTENTION_TUNABLE_KEYS + if k in kwargs + }, + **{k: kwargs[k] for k in CONV_TUNABLE_KEYS if k in kwargs}, + }, + mutated_inputs=mutated_inputs, + workspace_arg=workspace_arg, + allowed_prologue_inps=result.prologue_supported_inputs, + hint_override=hint_override, + ) + + +class ExternKernelChoice: + """Represents an external kernel that can participate in autotuning. + + Each instance is registered as a singleton by name in ``_registry`` and + on the ``extern_kernels`` module so that codegen can emit a stable + reference. Use ``lookup(name)`` to retrieve an existing instance + before creating a new one to avoid duplicate registrations. + """ + + _registry: dict[str, "ExternKernelChoice"] = {} + + def __init__( + self, + kernel: Callable[..., Any], + cpp_kernel: str | None = None, + *, + name: str | None = None, + has_out_variant: bool = True, + op_overload: torch._ops.OpOverload | None = None, + use_fallback_kernel: bool = False, + kernel_creator: Callable[..., ir.ExternKernel] | None = None, + ) -> None: + super().__init__() + name = name or kernel.__name__ + if not callable(kernel): + raise AssertionError("kernel must be callable") + # A module that registers an extern kernel can be initialized more than + # once in a single process (e.g. a double-import path). Tolerate + # re-registration under an existing name as long as it wraps the same + # callable, but reject a genuine name collision between different kernels. + existing = getattr(extern_kernels, name, None) + if existing is not None and existing is not kernel: + raise AssertionError(f"duplicate extern kernel: {name}") + self.name = name + self.cpp_kernel_name = cpp_kernel + self.has_out_variant = has_out_variant + setattr(extern_kernels, name, kernel) + self.op_overload = op_overload + self.use_fallback_kernel = use_fallback_kernel + self.kernel_creator = kernel_creator + # match the API for KernelTemplate as they can be treated the same + # There is no src hash for ExternKernelChoice in the traditional sense + # so we indicate this by returning None + self.src_hash = None + # By default GraphModule is None for extern kernels if not set + self.gm = None + ExternKernelChoice._registry[name] = self + + @classmethod + def lookup(cls, name: str) -> Optional["ExternKernelChoice"]: + return cls._registry.get(name) + + def to_callable(self) -> Callable[..., Any]: + return getattr(extern_kernels, self.name) + + def call_name(self): + return f"extern_kernels.{self.name}" + + @functools.cache # noqa: B019 + def hash_key(self): + fn = self.to_callable() + parts = [ + self.name, + getattr(fn, "__name__", ""), + getattr(fn, "__module__", ""), + ] + try: + parts.append(inspect.getsource(fn)) + except Exception: + pass + return code_hash("-".join(parts)) + + def bind( + self, + input_nodes, + layout, + ordered_kwargs_for_cpp_kernel=(), + **kwargs, + ): + self.ordered_kwargs_for_cpp_kernel = ordered_kwargs_for_cpp_kernel + return ExternKernelCaller( + self, + input_nodes, + layout, + kwargs, + has_out_variant=self.has_out_variant, + ) + + @property + def uid(self) -> str: + # unique by prefixing with aten + return f"aten::{self.name}" + + def choice_or_none(self, **kwargs: Any) -> ChoiceCaller | None: + """ + Maybe generates a new ChoiceCaller and returns it, or None if generation fails. + + kwargs: Additional kwargs to be passed to generate a new ChoiceCaller. + """ + temp_choices: list[Any] = [] + result = self.maybe_append_choice(temp_choices, **kwargs) + if result is None and len(temp_choices) == 1: + return temp_choices[0] + return None + + def maybe_append_choice( + self, choices: list[Any], **kwargs: Any + ) -> NotImplementedError | None: + # convenience function to match the Template interface, so that + # templates and ExternKernelChoice can be treated the same when + # generating choice callers + if "input_nodes" not in kwargs: + raise AssertionError("input_nodes argument required") + if "layout" not in kwargs: + raise AssertionError("layout argument required") + input_nodes = kwargs.pop("input_nodes") + layout = kwargs.pop("layout") + choices.append(self.bind(input_nodes=input_nodes, layout=layout, **kwargs)) + return None + + +class TritonTemplateCaller(ir.TritonTemplateCallerBase): + """ + Represents a ChoiceCaller for a TritonTemplate + """ + + def __init__( + self, + name, + input_nodes, + layout, + make_kernel_render, + description, + bmreq, + log_info: dict[str, PrimitiveInfoType | list[PrimitiveInfoType]] | None = None, + mutated_inputs=None, + workspace_arg: WorkspaceArg | None = None, + allowed_prologue_inps: OrderedSet[str] | None = None, + hint_override: int | None = None, + ) -> None: + super().__init__(name, input_nodes, layout, description) + self.make_kernel_render = make_kernel_render + self.bmreq: TritonBenchmarkRequest = bmreq + if log_info is None: + log_info = {} + self.log_info: dict[str, Any] = log_info + self.log_info.update( + { + "backend": "Triton", + "num_stages": self.bmreq.num_stages, + "num_warps": self.bmreq.num_warps, + } + ) + self.mutated_inputs = mutated_inputs + self.workspace_arg = workspace_arg + self.allowed_prologue_inps = ( + allowed_prologue_inps if allowed_prologue_inps is not None else OrderedSet() + ) + self.hint_override = hint_override + + self.n_regs = None + + def benchmark(self, *args, out): + if self.bmreq is None: + raise AssertionError("self.bmreq must not be None") + if ( + config.profile_bandwidth_with_do_bench_using_profiling + and not self._benchmark_with_cudagraphs + ): + algo = self.bmreq.make_run_fn(*args, out=out) + return do_bench_using_profiling(algo) + self.bmreq.benchmark_with_cudagraphs = self._benchmark_with_cudagraphs + return self.bmreq.benchmark(*args, out=out) + + def precompile(self): + if self.bmreq is None: + raise AssertionError("self.bmreq must not be None") + self.bmreq.precompile() + + self.n_regs = self.bmreq.n_regs + + def __str__(self) -> str: + return f"TritonTemplateCaller({self.bmreq.module_path}, {self.description})" + + def call_name(self): + return f"template_kernels.{self.name}" + + def hash_key(self): + return "-".join( + [ + self.name.rsplit("_", 1)[0], + self.bmreq.module_cache_key, + ] + ) + + def output_node(self): + buffer = ir.TritonTemplateBuffer( + layout=self.layout, + inputs=self.input_nodes, + make_kernel_render=self.make_kernel_render, + mutated_inputs=self.mutated_inputs, + allowed_prologue_inps=self.allowed_prologue_inps, + ) + # Pass KTC annotation to the buffer for encoding + if "ktc" in self.annotations: + buffer.annotations["ktc"] = self.annotations["ktc"] + return ir.TensorBox.create(buffer) + + def info_dict(self) -> dict[str, PrimitiveInfoType | list[PrimitiveInfoType]]: + """Information returned here is logged to the autotune log file when that is enabled.""" + return self.log_info + + def get_make_kernel_render(self): + return self.make_kernel_render + + def autoheuristic_id(self): + type_name = "triton" + info = self.info_dict() + # TODO(AlnisM): Does tile_shape always exist? + tile = info["tile_shape"] + tile_vals = eval(tile) # type: ignore[arg-type] + BLOCK_M = tile_vals[0] + BLOCK_K = tile_vals[1] + BLOCK_N = tile_vals[2] + num_stages = info["num_stages"] + num_warps = info["num_warps"] + return f"type={type_name}_BLOCK-M={BLOCK_M}_BLOCK-K={BLOCK_K}_BLOCK-N={BLOCK_N}_numstages={num_stages}_numwarps={num_warps}" + + +class ExternKernelCaller(ChoiceCaller): + """ + Caller for external kernel implementations + """ + + def __init__( + self, + choice: ExternKernelChoice, + input_nodes, + layout, + kwargs=None, + *, + has_out_variant=True, + ) -> None: + super().__init__(choice.name, input_nodes, layout, description="") + self.choice = choice + self.kwargs = kwargs or {} + self.has_out_variant = has_out_variant + self.gm = choice.gm + self.bmreq: BenchmarkRequest | None = None + + from torch._inductor.autotune_process import ( + ExternKernelBenchmarkRequest, + ExternKernelCPUBenchmarkRequest, + ExternKernelGPUBenchmarkRequest, + ) + + # Determine if this is a GPU or CPU kernel + if self.layout: + device = self.layout.device + else: + device = None + for inp_node in self.input_nodes: + dev = inp_node.get_device() + if dev and dev.type != "cpu": + device = dev + break + + if not device: + device = torch.device("cpu") + + self.input_tensor_meta: list[TensorMeta] | TensorMeta + self.output_tensor_meta: list[TensorMeta] | TensorMeta + self.input_tensor_meta, self.output_tensor_meta = [], [] + if device.type == "cpu": + benchmark_cls = ExternKernelCPUBenchmarkRequest + else: + try: + self.input_tensor_meta = TensorMeta.from_irnodes(self.input_nodes) + self.output_tensor_meta = TensorMeta.from_irnodes(self.layout) + except Exception: + log.warning( + "Constructing input/output tensor meta failed for Extern Choice" + ) + + benchmark_cls = ExternKernelGPUBenchmarkRequest + + self.bmreq: ExternKernelBenchmarkRequest = benchmark_cls( + kernel_name=self.choice.name, + input_tensor_meta=self.input_tensor_meta, + output_tensor_meta=self.output_tensor_meta, + extra_args=(), + callable_path=self.choice.call_name(), + kwargs=self.kwargs, + has_out_variant=self.has_out_variant, + ) + + def __str__(self) -> str: + return f"ExternKernelCaller({self.choice.call_name()})" + + def benchmark(self, *args, out): + if self.bmreq is None: + raise AssertionError("self.bmreq must not be None") + # pyrefly: ignore[missing-attribute] + self.bmreq.benchmark_with_cudagraphs = self._benchmark_with_cudagraphs + return self.bmreq.benchmark(*args, out=out) + + def benchmark_collective(self, *args, out): + """ + Called by benchmark_collective_choice, only run once, timing handled externally with barrier sync. + """ + if out.numel() == 0: + return + + algo = self.to_callable() + if self.has_out_variant: + algo(*args, out=out) + else: + algo(*args) + + def to_callable(self): + # pyrefly: ignore [missing-attribute] + return self.bmreq.to_callable() + + def hash_key(self): + return "-".join( + [ + self.choice.name, + *[ + f"{kwarg}={repr(self.kwargs[kwarg])}" + for kwarg in sorted(self.kwargs.keys()) + ], + self.choice.hash_key(), + ] + ) + + def output_node(self): + if self.choice.use_fallback_kernel: + if self.choice.op_overload is None: + raise AssertionError( + "Please provide an op_overload to use ir.FallbackKernel" + ) + inner: ir.IRNode = ir.FallbackKernel.create( + self.choice.op_overload, *self.input_nodes, **self.kwargs + ) + elif self.choice.kernel_creator is not None: + inner = self.choice.kernel_creator(*self.input_nodes, **self.kwargs) + else: + cls = ir.ExternKernelOut if self.has_out_variant else ir.ExternKernelAlloc + inner = cls( + layout=self.layout, + inputs=self.input_nodes, + python_kernel_name=self.choice.call_name(), + cpp_kernel_name=self.choice.cpp_kernel_name, + ordered_kwargs_for_cpp_kernel=self.choice.ordered_kwargs_for_cpp_kernel, + op_overload=self.choice.op_overload, + kwargs=self.kwargs, + ) + + # Pass KTC annotation to the buffer for encoding + if "ktc" in self.annotations: + inner.annotations["ktc"] = self.annotations["ktc"] + return ir.TensorBox.create(inner) + + def info_dict(self) -> dict[str, PrimitiveInfoType | list[PrimitiveInfoType]]: + """Information returned here is logged to the autotune log file when that is enabled.""" + return { + "backend": "extern", + "kernel_call_name": self.choice.call_name(), + } + + def autoheuristic_id(self): + return f"extern_{self.choice.name}" + + +@functools.cache +def get_mm_log_filename() -> str | None: + mm_file_name = os.environ.get("TORCHINDUCTOR_MM_LOGGING_FILE", None) + if not mm_file_name: + return None + + if "json" not in mm_file_name: + mm_file_name = f"{mm_file_name}.json" + + return mm_file_name + + +@functools.cache +def get_flex_attention_log_filename() -> str | None: + flex_attention_file_name = os.environ.get( + "TORCHINDUCTOR_FLEX_ATTENTION_LOGGING_FILE", None + ) + if not flex_attention_file_name: + return None + + return str(Path(flex_attention_file_name).with_suffix(".json")) + + +@functools.cache +def get_conv_log_filename() -> str | None: + conv_file_name = os.environ.get("TORCHINDUCTOR_CONV_LOGGING_FILE", None) + if not conv_file_name: + return None + + return str(Path(conv_file_name).with_suffix(".json")) + + +def append_to_log(filename, data): + lock_file = filename.replace(".json", ".lock") + lock = FileLock(lock_file) + with lock: + try: + with open(filename) as f: + log_data = json.load(f) + except (FileNotFoundError, json.JSONDecodeError): + log_data = [] + + log_data.append(data) + + with open(filename, "w") as f: + json.dump(log_data, f, indent=4) + + +class DataProcessorChoiceCallerWrapper: + def __init__(self, wrapped, preprocessor, postprocessor) -> None: + self._wrapped = wrapped + if preprocessor is not None: + self._preprocessor = preprocessor + else: + self._preprocessor = lambda x, y: (x, y) + if postprocessor is not None: + self._postprocessor = postprocessor + else: + self._postprocessor = lambda x: x + + def __getattr__(self, name): + return getattr(self._wrapped, name) + + def benchmark(self, *args, out) -> float: + new_args, new_out = self._preprocessor(args, out) + result = self._wrapped.benchmark(*new_args, out=new_out) + new_out = self._postprocessor(new_out) + if out is not new_out: + out.copy_(new_out) + return result + + def output_node(self) -> ir.TensorBox: + result = self._wrapped.output_node() + return self._postprocessor(result) + + def __repr__(self) -> str: + return f"DataProcessorChoiceCallerWrapper({self._wrapped})" + + +class DataProcessorTemplateWrapper: + """ + A wrapper class for a kernel template. + + This class together with `DataProcessorChoiceCallerWrapper` provides a convenient way to + preprocess and postprocess data before and after using the wrapped template. A typical + usage is to reorder or filter the input nodes in order to match the expected input of other + kernel choices like a ATen kernel. A more complicated usage is to prepack the weights. + See the example from :mod:`cpp_gemm_template` for more details. + """ + + def __init__( + self, + wrapped_template_cls, + preprocessor, + postprocessor, + **kwargs, + ) -> None: + if preprocessor is not None: + self._preprocessor = preprocessor + else: + self._preprocessor = lambda x, y: (x, y) + if postprocessor is not None: + self._postprocessor = postprocessor + else: + self._postprocessor = lambda x: x + if "input_nodes" not in kwargs: + raise AssertionError("input_nodes argument required") + if "layout" not in kwargs: + raise AssertionError("layout argument required") + + kwargs["input_nodes"], kwargs["layout"] = preprocessor( + kwargs["input_nodes"], kwargs["layout"] + ) + self._wrapped = wrapped_template_cls(**kwargs) + + def __getattr__(self, name): + return getattr(self._wrapped, name) + + def maybe_append_choice(self, choices, **kwargs): + return type(self._wrapped).maybe_append_choice(self, choices, **kwargs) + + def generate(self, **kwargs): + choice_caller = self._wrapped.generate(**kwargs) + return DataProcessorChoiceCallerWrapper( + choice_caller, self._preprocessor, self._postprocessor + ) + + def __repr__(self) -> str: + return f"DataProcessorTemplateWrapper({self._wrapped})" + + +class ErrorFromChoice(RuntimeError): + def __init__(self, msg, choice: ChoiceCaller, inputs_str) -> None: + msg += f"\nFrom choice {choice}\n{inputs_str}" + super().__init__(msg) + self.choice = choice + + +class NoValidChoicesError(RuntimeError): + pass + + +@functools.cache +def get_num_workers() -> int: + if "TORCHINDUCTOR_COMPILE_THREADS" in os.environ: + return int(os.environ["TORCHINDUCTOR_COMPILE_THREADS"]) + + cpu_count = torch._utils.cpu_count() + if not cpu_count: + raise AssertionError(f"expected nonzero cpu_count, got {cpu_count}") + + # Divide the number of CPUs by the number of GPUs for distributed workloads + if ( + config.is_fbcode() + and torch.cuda.is_available() + and torch.cuda.device_count() > 0 + ): + cpu_count = cpu_count // torch.cuda.device_count() + + return cpu_count + + +def create_inputs_key(input_nodes) -> str: + return repr([AlgorithmSelectorCache.key_of(x) for x in input_nodes]) + + +def create_precompile_key( + name: str, inputs_key: str, choices: list[ChoiceCaller] +) -> str: + return ":".join( + [ + name, + inputs_key, + torch.get_float32_matmul_precision(), + ] + + [choice.kernel_hash_key() for choice in choices] + ) + + +@dataclasses.dataclass(frozen=True, slots=True) +class PrecompileFunction: + """Callable precompile wrapper that carries its cache key for scoped cleanup.""" + + fn: Callable[[], dict[ChoiceCaller, float]] + precompile_key: str | None = None + + def __call__(self) -> dict[ChoiceCaller, float]: + return self.fn() + + +def _benchmark_request_for_choice(choice: ChoiceCaller) -> Any | None: + bmreq = getattr(choice, "_bmreq", None) + if bmreq is not None: + return bmreq + try: + return vars(choice).get("bmreq") + except TypeError: + return None + + +# Args to FeedbackFunctions +# timings: mapping from choices to the benchmark time +# name: name of the op +# input_nodes: list of input ir.py Nodes +# choices: list of choices +# profiled time: Callable that returns a dict mapping from choices to the profiled time +# precompile_times: mapping from choices to their precompilation time in seconds +FeedbackFunction = Callable[ + [ + dict[ChoiceCaller, float], + str, + list[Any], + list[ChoiceCaller], + Callable[[], dict[ChoiceCaller, float]], + dict[ChoiceCaller, float], + ], + None, +] + +# Args to PreprocessingFunctions +# choices: list of ChoiceCaller objects to preprocess +# Returns: modified list of ChoiceCaller objects +PreprocessingFunction = Callable[[list[ChoiceCaller]], list[ChoiceCaller]] + + +def filter_choices_by_name_regex(choices: list[ChoiceCaller]) -> list[ChoiceCaller]: + """Filter choices based on autotune_choice_name_regex config.""" + if config.test_configs.autotune_choice_name_regex is not None: + return [ + c + for c in choices + if re.search( + config.test_configs.autotune_choice_name_regex, + c.name, + ) + ] + return choices + + +def filter_choices_by_desc_regex(choices: list[ChoiceCaller]) -> list[ChoiceCaller]: + """Filter choices based on autotune_choice_desc_regex config.""" + if config.test_configs.autotune_choice_desc_regex is not None: + return [ + c + for c in choices + if re.search( + config.test_configs.autotune_choice_desc_regex, + c.description, + ) + ] + return choices + + +def _classify_kernel_operation( + name: str, choices: list[ChoiceCaller], input_nodes +) -> str: + """ + Classify the operation type for logging and filtering purposes. + Returns one of: "mm", "conv", "flex", or "other" + + This is more robust than simple string matching as it: + 1. Checks template types from choices + 2. Uses input shape patterns + 3. Falls back to exact name matching (not substring) + """ + # First, try to classify from choice types + if choices: + for choice in choices: + if isinstance(choice, TritonTemplateCaller): + # Extract template name (e.g., "mm" from "mm_1", "convolution2d" from "convolution2d_3") + template_name = choice.name.rsplit("_", 1)[0] + + # Check known template patterns + if template_name in ( + "mm", + "bmm", + "mm_persistent_tma", + "grouped_mm", + "scaled_grouped_mm", + "mm_plus_mm", + "blackwell_ws_persistent_device_tma", + "scaled_mm_device_tma_main_loop_scaling", + ): + return "mm" + elif template_name in ("convolution2d", "convolution3d"): + return "conv" + elif template_name.startswith("flex_"): + return "flex" + + elif isinstance(choice, ExternKernelCaller): + # Check extern kernel names + choice_name = choice.name + if choice_name in ( + "mm", + "bmm", + "addmm", + "baddbmm", + "_int_mm", + "_scaled_mm", + ): + return "mm" + elif "conv" in choice_name: + return "conv" + + # Second, use input shape heuristics for additional validation + if len(input_nodes) >= 2: + try: + input_0_shape = input_nodes[0].get_size() + input_1_shape = input_nodes[1].get_size() + + # Matrix multiplication patterns + if len(input_0_shape) == 2 and len(input_1_shape) == 2: + return "mm" + elif len(input_0_shape) == 3 and len(input_1_shape) == 3: + return "mm" # bmm + + # Convolution patterns: input NCHW/NCDHW, weight OIHW/OIDHW + elif len(input_0_shape) in (4, 5) and len(input_1_shape) in (4, 5): + # Could be conv or flex_attention, prefer template name if available + if len(input_0_shape) == 4 and len(input_1_shape) == 4: + # Check if it looks like conv (channel dims match) + # Conv: input[N,C,H,W] @ weight[O,C,kH,kW] where input[1] == weight[1] + try: + if input_0_shape[1] == input_1_shape[1]: + return "conv" + except (IndexError, TypeError): + pass + + except (ValueError, IndexError, AttributeError): + pass + + # Last resort: exact name matching (not substring to avoid false positives) + name_lower = name.lower() + if name_lower in ("mm", "bmm", "addmm", "baddbmm"): + return "mm" + elif name_lower in ( + "convolution", + "convolution2d", + "convolution3d", + "conv2d", + "conv3d", + ): + return "conv" + elif name_lower.startswith("flex_"): + return "flex" + + return "other" + + +class AlgorithmSelectorCache(PersistentCache): + """ + A persistent cache for algorithm selection results used in autotuning of GEMMs + and convolutions. + + This classes includes precompilation and benchmarking of the kernels. + + The cache is keyed by input characteristics (sizes, strides, dtypes, etc.) but + doesn't depend on the output layout. + """ + + FLEX_ATTENTION_TUNABLE_KEYS = tuple( + dict.fromkeys( + [ + "num_warps", + "num_stages", + "BLOCK_M", + "BLOCK_N", + "BLOCK_M1", + "BLOCK_N1", + "BLOCK_M2", + "BLOCK_N2", + "USE_TMA", + "kpack", + "matrix_instr_nonkdim", + "waves_per_eu", + ] + ) + ) + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + + # the autotuning will get occur in the scheduler, so there is + # no guarantee that the first lowering for a given key will also be the + # first to benchmark it. share a single precompilation function for all lowerings + # of a particular key + self.precompile_cache: dict[str, PrecompileFunction] = {} + # cache for prescreening results to ensure deterministic candidate selection + self.prescreening_cache: dict[str, OrderedSet[str]] = {} + # list of callbacks that are called after benchmarking + self.feedback_saver_fns: list[FeedbackFunction] = [] + # list of callbacks that are called to preprocess choices + self.preprocessing_fns: list[PreprocessingFunction] = [] + + self._register_default_preprocessing_fns() + + # registers `self.cache_clear(...)` to be called when a fresh Inductor cache is requested + clear_on_fresh_cache(self) + + def _register_default_preprocessing_fns(self): + """Register default preprocessing functions.""" + # Note: broken out into its own function so that we can avoid clearing + # them (i.e. so we can restore them after clearing user provided ones) + self.add_preprocessing_fn(filter_choices_by_name_regex) + self.add_preprocessing_fn(filter_choices_by_desc_regex) + + def cache_clear(self) -> None: + self.precompile_cache.clear() + self.prescreening_cache.clear() + + def pick_deterministic_choice(self, choices: list[ChoiceCaller]) -> ChoiceCaller: + if len(choices) < 2: + raise AssertionError(f"expected at least 2 choices, got {len(choices)}") + externs = [ + choice for choice in choices if isinstance(choice, ExternKernelCaller) + ] + if len(externs) > 0: + return externs[0] + else: + return choices[0] + + def __call__( + self, + name, + choices: list[ChoiceCaller], + input_nodes, + layout, + # optional dict mapping arg indices to the functions + # generating a torch.Tensor for that input from the + # corresponding ir.Buffer. if passed for a given + # arg, the function will be called instead of + # generating a random torch.Tensor for benchmarking. + input_gen_fns: dict[int, Callable[[ir.Buffer], torch.Tensor]] | None = None, + precompilation_timeout_seconds: int = 60 * 60, + return_multi_template=False, + best_config_future=None, + is_collective=False, + min_speedup_threshold: float = 1.0, # Only pick non-fallback if faster by this ratio + benchmark_with_cudagraphs: bool = False, # Use CUDA graphs for ExternKernelCaller benchmarking + ): + from .codegen.cutlass.kernel import CUTLASSTemplateCaller + + # Run preprocessing functions on choices + for preprocessing_fn in self.preprocessing_fns: + choices = preprocessing_fn(choices) + + # Apply benchmark_with_cudagraphs to all choices + if benchmark_with_cudagraphs: + for choice in choices: + choice._benchmark_with_cudagraphs = True + + # Templates selected with input_gen_fns require specific input data to avoid IMA + # Passing custom input gen fns to benchmark_fusion NYI, so skip deferred template selection + # TODO(jgong5): support multi-template on CPU C++ backend + if input_gen_fns is not None or ( + layout.device.type == "cpu" and config.cpu_backend != "triton" + ): + return_multi_template = False + + # TODO - assert that we have not mutating kernels here + + if len(choices) == 0: + raise self.create_no_valid_choices(name, "No choices exist for backend.") + log.debug("Max autotune selects from %s choices.", len(choices)) + + if len(choices) == 1: + if not isinstance(choices[0], CUTLASSTemplateCaller): + # CUTLASSTemplateCaller still needs to go through the autotuning process to retrieve workspace size. + node = choices[0].output_node() + return node, choices[0] + + if config.deterministic: + choice = self.pick_deterministic_choice(choices) + node = choice.output_node() + return node, choice + + inputs_key = create_inputs_key(input_nodes) + + has_cutlass = any(isinstance(c, CUTLASSTemplateCaller) for c in choices) + if config.autotune_in_subproc or has_cutlass: + # Warmup the subprocess pool early so it's ready for benchmarking + torch._inductor.autotune_process.get_tuning_process_pool() + + precompile_fn = self.make_precompile_fn( + choices, + name, + inputs_key, + precompilation_timeout_seconds=precompilation_timeout_seconds, + ) + + if return_multi_template and (config.max_autotune or config.max_autotune_gemm): + if use_pipelined_autotuning(): + if config.benchmark_epilogue_fusion: + raise AssertionError( + "Benchmarking epilogues will cause gpu contention with pipelined autotuning" + ) + extern_kernels = [ + c for c in choices if AlgorithmSelectorCache._is_extern(c) + ] + # Make sure the autotune subprocess for benchmarking is fed as much as possible + # Extern kernels do not have to precompile, so can feed them before triton + AsyncAutotuner.start(extern_kernels, inputs_key) + triton_kernels = [ + c for c in choices if not AlgorithmSelectorCache._is_extern(c) + ] + + if triton_kernels: + precompile_instance = PrecompileThreadPool.get_instance() + precompile_future = precompile_instance.submit( + self.do_autotuning, + name, + input_nodes, + layout, + input_gen_fns, + inputs_key, + triton_kernels, + precompile_fn, + ) + else: + precompile_future = None + + def get_timings(hint_override: int | None = None): + if hint_override: + raise AssertionError( + "Hint not supported with pipelined autotuning" + ) + # Await precompilation future, thread pool + precompile_start_ts = time.time() + final_choices = choices + if precompile_future: + try: + precompile_future.result() + except NoValidChoicesError: + log.error( + "Runtime error for autotuning triton choices, defaulting to extern kernels.", + ) + final_choices = extern_kernels + precompile_elapse = time.time() - precompile_start_ts + + # Await autotuning in subproc pool + autotune_start_ts = time.time() + results = AsyncAutotuner.get_results(final_choices, inputs_key) + autotune_wait_ts = time.time() - autotune_start_ts + AlgorithmSelectorCache.log_results( + name, + input_nodes, + results, + precompile_elapse, + autotune_wait_ts, + ) + + return results + else: + + def get_timings(hint_override: int | None = None): + filtered_choices = [ + c + for c in choices + if not hasattr(c, "hint_override") + or c.hint_override == hint_override + ] + timings = self.do_autotuning( + name, + input_nodes, + layout, + input_gen_fns, + inputs_key, + filtered_choices, + precompile_fn, + hint_override=hint_override, + best_config_future=best_config_future, + ) + min_extern_choice = float("inf") + for choice, timing in timings.items(): + if isinstance(choice, ExternKernelCaller): + min_extern_choice = min(min_extern_choice, timing) + + timings = { + choice: time + for choice, time in timings.items() + if ( + time <= min_extern_choice + or not isinstance(choice, ExternKernelCaller) + ) + } + + return timings + + # We take the union of allowed prologue inputs from all choices, + # and, within benchmark fusion, don't allow prologue fusion for + # choices which don't support the whole union. + allowed_prologue_inps: OrderedSet[str] = OrderedSet() + for c in choices: + if isinstance(c, TritonTemplateCaller): + allowed_prologue_inps |= c.allowed_prologue_inps + + # No single winning choice yet; selection is deferred to benchmark fusion + return ( + torch._inductor.ir.TensorBox.create( + torch._inductor.ir.MultiTemplateBuffer( + layout, + input_nodes, + get_timings, + choices, + allowed_prologue_inps, + ) + ), + None, + ) + + timings = self.do_autotuning( + name, + input_nodes, + layout, + input_gen_fns, + inputs_key, + choices, + precompile_fn, + best_config_future=best_config_future, + is_collective=is_collective, + ) + # if timings is empty, we really have no choice but to return a semi-random + # choice. returning the first `ExternKernelCaller` is probably the safest bet + # in this case, since it will generally be the ATen kernel. if there are no + # `ExternKernelCaller`s to return, then returning the 0th kernel is our next + # best option (ideally we'd fail whenever there is no ATen kernel to fallback + # to, but that's not trivial to figure out) + if timings == {}: + for choice in choices: + if isinstance(choice, ExternKernelCaller): + node = choice.output_node() + log.debug( + "Autotuning returned empty timings, falling back to first `ExternKernelCaller`: %s", + node, + ) + return node, choice + node = choices[0].output_node() + choice = choices[0] + log.debug( + "Autotuning returned empty timings, falling back to first choice: %s", + node, + ) + return node, choice + + # if we got any timings at all, pick the best of those + best_choice = min(timings, key=timings.__getitem__) + best_time = timings[best_choice] + + # All benchmarks failed; fall back to ATen if available (#171094) + if math.isinf(best_time): + extern_choices = [c for c in choices if isinstance(c, ExternKernelCaller)] + if extern_choices: + best_choice = extern_choices[0] + log.warning( + "All autotuning benchmarks failed (timing=inf). Falling back to ExternKernelCaller: %s", + getattr(best_choice, "name", ""), + ) + else: + log.warning( + "All autotuning benchmarks failed (timing=inf) and no ExternKernelCaller fallback available. " + "Selected kernel %s may cause runtime errors.", + getattr(best_choice, "name", ""), + ) + + # Apply min_speedup_threshold: only pick non-fallback if it beats fallback by threshold + elif min_speedup_threshold > 1.0: + + def is_fallback(c: ChoiceCaller) -> bool: + return isinstance(c, ExternKernelCaller) and getattr( + c.choice, "use_fallback_kernel", False + ) + + fallback_choices = [c for c in timings if is_fallback(c)] + if fallback_choices and not is_fallback(best_choice): + fallback_time = min(timings[c] for c in fallback_choices) + speedup = fallback_time / best_time if best_time > 0 else 0 + + if speedup < min_speedup_threshold: + # Best choice doesn't beat fallback by enough, use fallback instead + log.debug( + "Best choice %s speedup %.2fx < threshold %.2fx, using fallback", + best_choice.name, + speedup, + min_speedup_threshold, + ) + best_choice = min(fallback_choices, key=lambda c: timings[c]) + + best_choice = V.choices.override_best_choice(best_choice, timings) + + # Test-only: force choosing decomposition (non-fallback) if available + if config.test_configs.force_custom_op_decomposition: + + def is_fallback(c: ChoiceCaller) -> bool: + return isinstance(c, ExternKernelCaller) and getattr( + c.choice, "use_fallback_kernel", False + ) + + non_fallback_choices = [c for c in timings if not is_fallback(c)] + if non_fallback_choices: + best_choice = min(non_fallback_choices, key=lambda c: timings[c]) + + choice = best_choice + node = choice.output_node() + + log.debug("Autotuning selected choice: %s", node) + return node, choice + + def benchmark( + self, + choices, + input_nodes, + layout, + input_gen_fns, + hint_override: int | None = None, + is_collective=False, + precompile_key: str | None = None, + ): + counters["inductor"]["select_algorithm_autotune"] += 1 + # TODO(nmacchioni): remove this layer of abstraction + # construct `benchmark_fn` which should pick between in-process and sub-process autotuning + benchmark_fn = self.make_benchmark_fn( + choices, + input_nodes, + layout, + input_gen_fns, + hint_override=hint_override, + is_collective=is_collective, + ) + # `benchmark_fn(choices)` will execute each choice, and return a dict[choice, timing] which + # maps each choice to its runtime, calculated by the specified benchmarker, in milliseconds + try: + return benchmark_fn(choices) + finally: + # Safety net for failures before individual BenchmarkRequest cleanup + # can run; request-level cleanup remains the authoritative owner cleanup. + evict_paths = OrderedSet( + [ + path + for choice in choices + for bmreq in (_benchmark_request_for_choice(choice),) + for path in (getattr(bmreq, "module_path", None),) + if path is not None + ] + ) + if evict_paths: + for path in evict_paths: + PyCodeCache.modules_no_attr.pop(path, None) + PyCodeCache.linemaps.pop(path, None) + PyCodeCache.modules[:] = [ + module + for module in PyCodeCache.modules + if getattr(module, "__file__", None) not in evict_paths + ] + + if precompile_key is not None: + self.precompile_cache.pop(precompile_key, None) + + def autotune( + self, + name, + input_nodes, + layout, + input_gen_fns, + choices, + hint_override: int | None = None, + is_collective=False, + precompile_key: str | None = None, + ): + log.debug("Starting autotuning") + + with dynamo_timed( + f"{name}_template_autotuning", + log_pt2_compile_event=True, + dynamo_compile_column_us="compile_time_autotune_time_us", + metadata=_autotune_metadata(input_nodes), + ): + benchmark_results = self.benchmark( + choices, + input_nodes, + layout, + input_gen_fns, + hint_override=hint_override, + is_collective=is_collective, + precompile_key=precompile_key, + ) + if config.max_autotune_report_choices_stats: + _log_autotune_choices_stats( + f"{name}_template_autotuning", benchmark_results + ) + return benchmark_results + + def do_autotuning( + self, + name, + input_nodes, + layout, + input_gen_fns, + inputs_key, + choices, + precompile_fn, + hint_override: int | None = None, + best_config_future=None, + is_collective=False, + ): + """Execute the autotuning process for kernel algorithm selection. + + This method orchestrates the complete autotuning pipeline including precompilation, + prescreening, benchmarking, and feedback collection to select the optimal kernel + implementation for given inputs. + + Args: + name: Name identifier for the operation being autotuned (e.g., 'mm', 'convolution'). + input_nodes: List of input IR nodes used for benchmarking. + layout: Layout information specifying device and memory format for the operation. + input_gen_fns: Optional dict mapping argument indices to functions that generate + torch.Tensor inputs from ir.Buffer for benchmarking. If provided, these are + used instead of random tensors. + inputs_key: Cache key representing the input characteristics (sizes, strides, dtypes). + choices: List of ChoiceCaller objects representing candidate kernel implementations. + precompile_fn: Callable that precompiles all kernel choices before benchmarking. + hint_override: Optional index to override which choice is selected, used for testing + or forced selection. + best_config_future: Optional future containing pre-determined best configuration to + filter choices by specific config parameters. + + Returns: + dict: Mapping from ChoiceCaller to benchmark timing in seconds. Choices with + non-finite timings (inf/nan) indicate failures. + + Raises: + NoValidChoicesError: When all choices fail to compile or benchmark, or when all + timing results are non-finite. + """ + precompile_key = getattr(precompile_fn, "precompile_key", None) + + if log.isEnabledFor(logging.DEBUG) and not use_pipelined_autotuning(): + # Log shape information for debugging timeout issues + sizevars = V.graph.sizevars + + shapes = [ + "x".join( + map( + str, + sizevars.optimization_hints_with_override( + node.get_size(), + hint_override=hint_override, + ), + ) + ) + for node in input_nodes + ] + log.debug( + "[BENCHMARK DEBUG] Starting autotuning for '%s' with shapes: %s, device: %s", + name, + shapes, + layout.device.type if layout else "unknown", + ) + + precompile_start_ts = time.time() + + if not use_pipelined_autotuning(): + with dynamo_timed( + f"{name}_template_precompiling", + log_pt2_compile_event=True, + dynamo_compile_column_us="compile_time_autotune_time_us", + ): + precompile_times = precompile_fn() + else: + precompile_times = precompile_fn() + + precompile_elapse = time.time() - precompile_start_ts + log.debug("Precompilation elapsed time: %.02fs", precompile_elapse) + # Prune anything that failed to compile + choices = [c for c in choices if not c.failed] + if len(choices) == 0: + raise self.create_no_valid_choices( + name, "All choices failed to compile for backend." + ) + + candidates = self.prescreen_choices( + choices, name, inputs_key, self.prescreening_cache + ) + prescreening_elapse: float | None = None + if candidates: + prescreening_start_ts = time.time() + timings = self.lookup( + candidates, + name, + inputs_key, + lambda choices: self.autotune( + name, + input_nodes, + layout, + input_gen_fns, + choices, + hint_override=hint_override, + ), + hint_override=hint_override, + ) + choices = self.prune_choices_postscreen( + choices, timings, name, inputs_key, self.prescreening_cache + ) + prescreening_elapse = time.time() - prescreening_start_ts + log.debug("Prescreening elapsed time: %.02fs", prescreening_elapse) + + if use_pipelined_autotuning(): + AsyncAutotuner.start(choices, inputs_key) + return + + autotune_start_ts = time.time() + + if best_config_future is not None: + best_config = await_sync(best_config_future) + + important_keys = [ + "ACC_TYPE", + "ALLOW_TF32", + "BLOCK_K", + "BLOCK_M", + "BLOCK_N", + "EVEN_K", + "GROUP_M", + "USE_FAST_ACCUM", + "num_stages", + "num_warps", + "num_consumer_groups", + "num_buffers_warp_spec", + ] + choices = [ + choice + for choice in choices + if all( + f"{k}={best_config[k]}" in choice.description + for k in important_keys + ) + for k in important_keys + ] + log.info("Filtered to %d choices based on best_config", len(choices)) + + has_autotuned: bool = False + + def track_has_autotuned(choices): + nonlocal has_autotuned + has_autotuned = True + return self.autotune( + name, + input_nodes, + layout, + input_gen_fns, + choices, + hint_override=hint_override, + is_collective=is_collective, + precompile_key=precompile_key, + ) + + timings = self.lookup( + choices, + name, + inputs_key, + track_has_autotuned, + hint_override=hint_override, + ) + + autotune_elapse = time.time() - autotune_start_ts + log.debug("Autotuning elapsed time: %.02fs", autotune_elapse) + + # For collective: if any choice returned inf (timeout or failure), fallback to default + if is_collective and timings: + has_inf = any(not math.isfinite(timing) for timing in timings.values()) + if has_inf: + log.warning( + "At least one choice failed or timed out during collective benchmarking. " + "Falling back to default implementation." + ) + return {} + + # For regular: if all choices returned inf, raise error + if timings and all(not math.isfinite(timing) for timing in timings.values()): + raise NoValidChoicesError + + if ( + has_autotuned + or log.getEffectiveLevel() == logging.DEBUG + or config.trace.log_autotuning_results + ): + self.log_results( + name, + input_nodes, + timings, + autotune_elapse, + precompile_elapse, + prescreening_elapse, + hint_override=hint_override, + is_collective=is_collective, + ) + + def profiler_bench_function(choices_override=None): + # we're not running through the normal caching autotuner method here because we want to avoid returning + # the cached value. + # Avoid benchmarking in a separate process because it's not easy to signal to the TuningProcess that we + # should use the profiler. + # If choices_override is provided, only benchmark those choices instead of all choices. + choices_to_benchmark = ( + choices_override if choices_override is not None else choices + ) + with config.patch( + profile_bandwidth_with_do_bench_using_profiling=True, + autotune_in_subproc=False, + ): + return self.benchmark( + choices_to_benchmark, input_nodes, layout, input_gen_fns + ) + + for feedback_fn in self.feedback_saver_fns: + # re-benchmarking the same choices with profiler is a bit expensive, so pass it in as a thunk. + feedback_fn( + timings, + name, + input_nodes, + choices, + profiler_bench_function, + precompile_times, + ) + + return timings + + def create_no_valid_choices(self, name: str, reason: str) -> NoValidChoicesError: + backend_config = ( + "max_autotune_gemm_backends" + if name != "convolution" + else "max_autotune_conv_backends" + ) + return NoValidChoicesError( + f"No choices to select. Provided reason: {reason} " + f"please consider adding ATEN into {backend_config} " + "config (defined in torch/_inductor/config.py) to allow at least one choice. " + ) + + def make_precompile_fn( + self, + choices, + name: str, + inputs_key: str, + precompilation_timeout_seconds: int | None = 60 * 60, + ) -> Callable[[], dict[ChoiceCaller, float]]: + """ + Returns a function that precompiles the given choices. + """ + log.debug("Starting precompilation") + + def no_op(*args, **kwargs) -> dict[ChoiceCaller, float]: + return {} + + if ( + precompilation_timeout_seconds is None + or precompilation_timeout_seconds <= 0 + ): + log.debug("Precompilation timeout is None or <= 0, returning no_op") + return no_op + + num_workers = min(get_num_workers(), len(choices)) + + if num_workers <= 0: + return no_op + + # https://github.com/python/cpython/issues/106905 + if ( + sys.version_info.major == 3 + and sys.version_info.minor == 11 + and sys.version_info.micro <= 8 + ): + return no_op + + # check local and global cache before precompiling + timings = self.lookup( + choices, + name, + inputs_key, + benchmark=None, + ) + + if timings and len(timings) == len(choices): + # compilation in precompile stage is much cheaper than that in + # autotuning stage + log.debug("Found all %d timings in cache, returning no_op", len(timings)) + return no_op + + precompile_key = create_precompile_key(name, inputs_key, choices) + if precompile_func := self.precompile_cache.get(precompile_key): + log.debug("Precompile function found in cache, returning it") + return precompile_func + + try: + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm import ( + NVUniversalGemmCaller, + ) + except ImportError: + NVUniversalGemmCaller = None # type: ignore[assignment, misc] + + log.info( + "Multithreaded precompilation for %d choices using %d worker threads", + len(choices), + num_workers, + ) + + # In rare circumstances, because python threads inherit global state, + # thread pool executor can race and leave stdout/stderr in a state + # different than the original values. we explicitly restore the state + # here to avoid this issue. + + def precompile_with_captured_stdout(choice) -> tuple[None, int]: + log.debug("Precompiling choice with captured stdout: %s", choice) + start_ns = time.time_ns() + with restore_stdout_stderr(): + choice.precompile() + elapsed_ns = time.time_ns() - start_ns + # Return tuple as triton async compile (_worker_compile_triton) + # returns tuple[CachingAutotuner, int] + return None, elapsed_ns // 1000 + + def on_complete(future): + if not future.exception(): + _, precompile_elapsed_us = future.result() + elapsed_seconds = precompile_elapsed_us / 1e6 + elapsed_times[future] = elapsed_seconds + log.debug( + "Precompilation complete for future: %s, elapsed time: %.02fs", + future, + elapsed_seconds, + ) + + if use_pipelined_autotuning(): + executor = PrecompileThreadPool.get_instance() + else: + executor = ThreadPoolExecutor(max_workers=num_workers) + + async_compile = torch._inductor.async_compile.AsyncCompile() + + futures: dict[concurrent.futures.Future[Any], ChoiceCaller] = {} + elapsed_times: dict[concurrent.futures.Future[Any], float] = {} + + # Some choices only differ in runtime arguments, so we + # skip a choice if it has the same hash as a previously seen choice + seen_choices: OrderedSet[str] = OrderedSet() + + # Count NVGEMM choices to decide whether subprocess precompile is worth + # the pool-warmup/IPC overhead. Measured break-even is ~8: below ~4 + # serial wins (~1.4s), from 8 up subprocess wins and the gap grows with + # count (e.g. 32 configs: 12.5s vs 22.0s serial). The break-even used to + # be ~20 because each worker rebuilt the ~14s kernel manifest; that + # overhead is gone now (workers reconstruct the one operator from + # metadata), so the threshold drops accordingly. + _NVGEMM_SUBPROCESS_PRECOMPILE_THRESHOLD = 8 + nvgemm_count = sum( + 1 + for c in choices + if NVUniversalGemmCaller is not None + and isinstance(c, NVUniversalGemmCaller) + ) + # Block for pool warmup when there are enough NVGEMM choices to justify + # it: the serial fallback (lazy compile at benchmark time) is ~15x + # slower, and the non-blocking use_process_pool() check can otherwise + # race the pool warmup when little other compilation precedes this point. + use_nvgemm_subprocess = ( + nvgemm_count >= _NVGEMM_SUBPROCESS_PRECOMPILE_THRESHOLD + and async_compile.wait_process_pool_ready() + ) + + for c in choices: + # Skip choices which we have already issued a precompile + if c.kernel_hash_key() in seen_choices: + log.debug("Skipping already seen choice: %s", c) + continue + else: + seen_choices.add(c.kernel_hash_key()) + + if hasattr(c, "precompile"): + triton_cuda_choice = isinstance(c, TritonTemplateCaller) and isinstance( + c.bmreq, TritonGPUBenchmarkRequest + ) + nvgemm_choice = ( + isinstance(c, NVUniversalGemmCaller) + if NVUniversalGemmCaller is not None + else False + ) + if triton_cuda_choice and async_compile.use_process_pool(): + with open(c.bmreq.module_path) as file: + source_code = file.read() + future = async_compile.triton( + kernel_name=c.bmreq.kernel_name, source_code=source_code + ).future + log.debug("Submitted triton async compile for choice: %s", c) + elif nvgemm_choice and use_nvgemm_subprocess: + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import ( + CUDAContextMetadata, + ) + + cuda_ctx = CUDAContextMetadata.from_kernel( + c.bmreq.kernel, c.bmreq.input_tensor_meta[0].device + ) + try: + future = async_compile.nvgemm_precompile( + kernel_name=c.bmreq.kernel.metadata.operator_name, + variant_name=c.bmreq.variant.name, + accumulator_type=c.bmreq.accumulator_type, + input_tensor_meta=c.bmreq.input_tensor_meta, + output_tensor_meta=c.bmreq.output_tensor_meta, + cuda_ctx=cuda_ctx, + scale_type_a=c.bmreq.scale_type_a, + scale_type_b=c.bmreq.scale_type_b, + swizzle_type_a=c.bmreq.swizzle_type_a, + swizzle_type_b=c.bmreq.swizzle_type_b, + has_bias_epilogue=c.bmreq.has_bias_epilogue, + swap_ab=c.bmreq.swap_ab, + metadata=c.bmreq.kernel.metadata, + ) + except (BrokenProcessPool, RuntimeError) as e: + # A precompile worker crashed and closed the pool. Stop + # using the subprocess pool and compile the remaining + # choices lazily in-process rather than aborting the + # whole compilation with a closed-pool error. + log.warning( + "NVGEMM subprocess precompile pool unusable (%s); " + "falling back to lazy in-process compile", + e, + ) + use_nvgemm_subprocess = False + continue + log.debug( + "Submitted nvgemm subprocess precompile for choice: %s", c + ) + elif nvgemm_choice: + # CuTeDSL compilation is not thread-safe; below the + # subprocess threshold or without the process pool, + # skip precompile and compile lazily at benchmark time. + log.debug("Skipping nvgemm precompile: %s", c) + continue + else: + future = executor.submit(precompile_with_captured_stdout, c) + log.debug("Submitted precompile for choice: %s", c) + + future.add_done_callback(on_complete) + futures[future] = c + + @functools.cache + @restore_stdout_stderr() + def wait_on_futures() -> dict[ChoiceCaller, float]: + """Wait for all precompilation futures to complete. + + Returns: + Dict mapping each choice to its precompilation time in seconds. + """ + log.debug("Waiting on futures") + counters["inductor"]["select_algorithm_precompile"] += 1 + exceptions: list[tuple[ChoiceCaller, BaseException]] = [] + try: + for future in as_completed( + futures, + timeout=precompilation_timeout_seconds, + ): + if e := future.exception(): + counters["inductor"][ + "select_algorithm_num_precompilation_exceptions" + ] += 1 + exceptions.append((futures[future], e)) + log.exception( + "Exception %s for benchmark choice %s", + e, + futures[future], + exc_info=e, + ) + futures[future].mark_failed() + else: + counters["inductor"]["select_algorithm_num_precompiles"] += 1 + log.info( + "Precompiling benchmark choice %s took %.02fs", + futures.get(future), + elapsed_times.get(future), + ) + except TimeoutError: + # Don't force the entire process to crash due to a timeout + # in compilation. Just mark those futures as failed. + completed_futures = OrderedSet([f for f in futures if f.done()]) + remaining_futures = OrderedSet(futures.keys()) - completed_futures + + log.warning( + "Precompilation timeout after %ds: %d of %d futures did not complete", + precompilation_timeout_seconds, + len(remaining_futures), + len(futures), + ) + + # Mark remaining futures as failed and log them + for future in remaining_futures: + choice = futures[future] + log.warning( + "Marking choice as failed due to timeout: %s", + choice, + ) + choice.mark_failed() + # Add timeout exception to the exceptions list + timeout_exc = TimeoutError( + f"Precompilation timed out after {precompilation_timeout_seconds}s" + ) + exceptions.append((choice, timeout_exc)) + if exceptions: + _log_autotune_exceptions(exceptions) + + if not use_pipelined_autotuning(): + # pyrefly: ignore [missing-attribute] + executor.shutdown(wait=True) + + # Build and return dict mapping choices to their precompilation times + precompile_times: dict[ChoiceCaller, float] = {} + for future, choice in futures.items(): + if future in elapsed_times: + precompile_times[choice] = elapsed_times[future] + return precompile_times + + precompile_fn = PrecompileFunction(wait_on_futures, precompile_key) + self.precompile_cache[precompile_key] = precompile_fn + + return precompile_fn + + @classmethod + def get_inputs( + cls, + choices: Sequence[ChoiceCaller], + input_nodes: list[ir.IRNode], + layout: ir.Layout, + input_gen_fns: dict[int, Callable[[ir.Buffer], torch.Tensor]] | None, + hint_override: int | None = None, + ) -> AutotuneArgs: + """ + Factory method to create AutotuneArgs from a list of ChoiceCallers. + """ + if input_gen_fns is None: + input_gen_fns = {} + + # de-duplicate args + unique_example_inputs = { + x.get_name(): input_gen_fns.get( + i, + lambda x: cls.benchmark_example_value(x, hint_override=hint_override), + # pyrefly: ignore [bad-argument-type] + )(x) + for i, x in enumerate(input_nodes) + } + + def addmm_unique_example_inputs_extern(): + additional_example_inputs = {} + for input_node, extern_node in zip(input_nodes, extern_input_nodes): + extern_name = extern_node.get_name() + if extern_name in unique_example_inputs: + continue + + # Aten addmm benchmarks the original 1D bias while Triton + # benchmarks the expanded 2D input; keep both backed by the + # same values by making all rows identical. + global_tensor = unique_example_inputs[input_node.get_name()] + if global_tensor.shape[0] == 0: + # No row to copy, and the 1D bias does not depend on M. + bias = cls.benchmark_example_value(extern_node, hint_override) + else: + global_tensor[:] = global_tensor[0:1].expand_as(global_tensor) + bias = global_tensor[0].contiguous() + additional_example_inputs[extern_name] = bias + + return { + **unique_example_inputs, + **additional_example_inputs, + } + + extern_choice = next( + (choice for choice in choices if cls._is_extern(choice)), + None, + ) + extern_input_nodes = input_nodes + unique_example_inputs_extern = unique_example_inputs + + if extern_choice is not None: + if len(extern_choice.input_nodes) != len(input_nodes): + raise AssertionError( + "extern_choice.input_nodes length must match input_nodes: " + f"{len(extern_choice.input_nodes)} != {len(input_nodes)}" + ) + extern_input_nodes = extern_choice.input_nodes + + if extern_choice.name == "addmm": + unique_example_inputs_extern = addmm_unique_example_inputs_extern() + + example_inputs = list(unique_example_inputs.values()) + example_inputs_extern = [] + for i, input_node in enumerate(extern_input_nodes): + input_tensor = unique_example_inputs_extern[input_node.get_name()] + if input_tensor.is_mkldnn: + example_inputs_extern.append(input_tensor) + else: + base = ( + input_tensor if input_tensor._base is None else input_tensor._base + ) + + if i in input_gen_fns: + # Use tensor's actual shape from input_gen_fn + sizes = tuple(input_tensor.size()) + strides = tuple(input_tensor.stride()) + storage_offset = input_tensor.storage_offset() + else: + # Use IR node's shape resolved via size hints + sizes = V.graph.sizevars.optimization_hints_with_override( + input_node.get_size(), + hint_override=hint_override, + ) + strides = V.graph.sizevars.optimization_hints_with_override( + get_strides_with_layout_constraints(input_node), + hint_override=hint_override, + ) + storage_offset = V.graph.sizevars.optimization_hint_with_override( + input_node.get_layout().offset, + hint_override=hint_override, + ) + + # Check if the required storage size exceeds the current storage + # to avoid illegal memory access + needed_size = torch._prims_common.compute_required_storage_length( + sizes, strides, cast(int, storage_offset) + ) + current_size = base.untyped_storage().size() // base.element_size() + if needed_size > current_size: + # Create a new base tensor with sufficient storage + if base.dtype == torch.float4_e2m1fn_x2: + new_base = torch.randint( + 0, + 256, + (needed_size,), + dtype=torch.uint8, + device=base.device, + ).view(torch.float4_e2m1fn_x2) + else: + new_base = torch.randn( + needed_size, + dtype=base.dtype, + device=base.device, + requires_grad=base.requires_grad, + ) + base = new_base.as_strided( + base.size(), base.stride(), base.storage_offset() + ) + + example_inputs_extern.append( + torch.as_strided(base, sizes, strides, storage_offset) + ) + out = cls.benchmark_example_value(layout, hint_override=hint_override) + + # Also check the output tensor for storage size + out_base = out if out._base is None else out._base + # Only used for benchmarking tensor setup, not correctness. + # Offset is almost always 0; use that as fallback. + out_offset = V.graph.sizevars.optimization_hint(layout.offset, fallback=0) + needed_out_size = torch._prims_common.compute_required_storage_length( + out.size(), out.stride(), out_offset + ) + # untyped_storage() counts bytes, unlike the deprecated TypedStorage.size(). + current_out_size = out_base.untyped_storage().size() // out_base.element_size() + + if needed_out_size > current_out_size: + # Create a new base tensor with sufficient storage + if out_base.dtype == torch.float4_e2m1fn_x2: + new_out_base = torch.randint( + 0, + 256, + (needed_out_size,), + dtype=torch.uint8, + device=out_base.device, + ).view(torch.float4_e2m1fn_x2) + else: + new_out_base = torch.randn( + needed_out_size, + dtype=out_base.dtype, + device=out_base.device, + requires_grad=out_base.requires_grad, + ) + out_base = new_out_base.as_strided( + out_base.size(), out_base.stride(), out_base.storage_offset() + ) + + out_extern = torch.as_strided(out_base, out.size(), out.stride(), out_offset) + expected = None + if VERIFY: + choices[0].benchmark(*example_inputs_extern, out=out_extern) + expected = out_extern.clone() + + return AutotuneArgs.from_choice_args( + example_inputs, + example_inputs_extern, + out, + out_extern, + expected, + ) + + @staticmethod + def _is_extern(choice: ChoiceCaller) -> bool: + return isinstance(choice, (ExternKernelCaller, SubgraphChoiceCaller)) + + @classmethod + def benchmark_choice( + cls, choice: ChoiceCaller, autotune_args: AutotuneArgs + ) -> float: + benchmark_tensors = autotune_args.get_benchmark_tensors(cls._is_extern(choice)) + inputs, output = benchmark_tensors.unpack() + output.zero_() + try: + result = choice.benchmark(*inputs, out=output) + device_type = next( + (tensor.device.type for tensor in inputs if is_gpu(tensor.device.type)), + "cuda", + ) + device_interface = get_interface_for_device(device_type) + if device_interface.is_available(): + device_interface.synchronize() # shake out any CUDA errors + + if VERIFY and autotune_args.expected is not None: + autotune_args.verify(**VERIFY) + return result + finally: + bmreq = _benchmark_request_for_choice(choice) + cleanup_run_fn = getattr(bmreq, "cleanup_run_fn", None) + if cleanup_run_fn is not None: + # In-process autotuning owns the loaded benchmark module, so clean it + # immediately after each choice. The outer benchmark cleanup is a fallback. + cleanup_run_fn() + + @classmethod + def _run_collective_benchmark( + cls, + choice: ChoiceCaller, + inputs: tuple, + output: torch.Tensor, + nruns: int, + process_group, + timeout, + ) -> float: + """ + Single function for benchmarking collective operations. + Used for both warmup and actual benchmarking. + + Returns total time in milliseconds, or raises TimeoutError if any collective times out. + """ + import torch.distributed as dist + + work = dist.barrier(group=process_group, async_op=True) + if not work.wait(timeout): + raise TimeoutError("Barrier timeout before benchmarking") + + torch.cuda.synchronize() + + total_time = 0.0 + + for i in range(nruns): + torch.cuda.synchronize() + + start_evt = torch.cuda.Event(enable_timing=True) + end_evt = torch.cuda.Event(enable_timing=True) + + start_evt.record() + choice.benchmark_collective(*inputs, out=output) # type: ignore[attr-defined] + end_evt.record() + end_evt.synchronize() + + total_time += start_evt.elapsed_time(end_evt) + + return total_time + + @classmethod + def benchmark_collective_choice( + cls, + choice: ChoiceCaller, + autotune_args: AutotuneArgs, + ) -> float: + """ + Benchmark a choice for collective operations with cross-rank synchronization. + This method ensures all ranks synchronize before benchmarking + to get accurate measurements for distributed collective operations. + + Timeout/Error handling: If ANY rank times out or encounters an error during + the collective operations, ALL ranks will naturally time out (since the collective + won't complete), allowing the autotuner to fall back to the default implementation. + """ + from datetime import timedelta + + import torch.distributed as dist + + timeout_seconds = config.collective_benchmark_timeout + + nruns = config.collective_benchmark_nruns + nwarmup = config.inductor_default_autotune_warmup + + # Use default process group (None = all ranks) + process_group = None + rank = dist.get_rank(process_group) + + benchmark_tensors: BenchmarkTensors = autotune_args.get_benchmark_tensors( + cls._is_extern(choice) + ) + inputs, output = benchmark_tensors.unpack() + output.zero_() + + timeout = timedelta(seconds=timeout_seconds) + + try: + # Do n warmups + cls._run_collective_benchmark( + choice, inputs, output, nwarmup, process_group, timeout + ) + + # Do n actual benchmarking runs + total_time = cls._run_collective_benchmark( + choice, inputs, output, nruns, process_group, timeout + ) + + avg_time = total_time / nruns + + # All-reduce to get avg time across ranks + time_tensor = torch.tensor( + [avg_time], dtype=torch.float32, device=f"cuda:{rank}" + ) + work = dist.all_reduce( + time_tensor, + op=dist.ReduceOp.AVG, + group=process_group, + async_op=True, + ) + if not work.wait(timeout): + raise TimeoutError( + "All-reduce timeout when collecting benchmark results" + ) + + timing = time_tensor.item() + + log.info( + "Collective benchmark for %s: %.6f ms", + choice.name, + timing, + ) + + return timing + + except Exception: + log.warning( + "Collective benchmark exception for choice %s. Skipping this choice.", + getattr(choice, "name", ""), + exc_info=True, + ) + return float("inf") + + @classmethod + def benchmark_choices( + cls, + choices: Sequence[ChoiceCaller], + autotune_args: AutotuneArgs, + is_collective: bool = False, + ) -> dict[ChoiceCaller, float]: + """ + Benchmark a list of choices and return timing dict. + """ + from torch._inductor.codegen.cutlass.kernel import CUTLASSTemplateCaller + + # Reorder only when CUTLASS is present: benchmark ATen/cuBLAS before + # CUTLASS to collect valid fallback timings before any CUTLASS kernel + # can corrupt the CUDA context (#171094) + if any(isinstance(c, CUTLASSTemplateCaller) for c in choices): + + def choice_priority(c: ChoiceCaller) -> int: + if isinstance(c, ExternKernelCaller): + return 0 # ATen/cuBLAS first + elif isinstance(c, CUTLASSTemplateCaller): + return 2 # CUTLASS last + else: + return 1 # Triton and others in the middle + + choices = sorted(choices, key=choice_priority) + + if is_collective: + import torch.distributed as dist + + if not dist.is_initialized(): + log.warning( + "Collective op detected but distributed not initialized. " + "Falling back to regular benchmarking." + ) + is_collective = False + else: + rank = dist.get_rank(None) # Use default process group + log.debug( + "Using collective benchmarking for %d choices on rank %d", + len(choices), + rank, + ) + timings = {} + for choice in choices: + try: + if is_collective: + timing = cls.benchmark_collective_choice(choice, autotune_args) + else: + timing = cls.benchmark_choice(choice, autotune_args) + except CUDACompileError: + if not isinstance(choice, CUTLASSTemplateCaller): + log.exception( + "CUDA compilation error during autotuning: \n%s. \nIgnoring this choice." + ) + timing = float("inf") + except NotImplementedError: + log.warning("Not yet implemented", exc_info=True) + timing = float("inf") + except RuntimeError as e: + msg = str(e) + if "invalid argument" in msg: + msg += "\n\nThis may mean this GPU is too small for max_autotune mode.\n\n" + elif "illegal memory access" in msg: + msg += "\n\nEither error in template or triton bug.\n" + elif "unspecified launch failure" in msg: + msg += "\n\nAn unrecoverable unspecified launch failure was caught during autotuning." + msg += "\nPlease try re-running with TORCHINDUCTOR_AUTOTUNE_IN_SUBPROC=1.\n\n" + + if isinstance(choice, CUTLASSTemplateCaller): + log.debug( + "Runtime error during autotuning: \n%s. \nIgnoring this choice.", + msg, + exc_info=True, + ) + else: + log.error( + "Runtime error during autotuning: \n%s. \nIgnoring this choice.", + msg, + ) + timing = float("inf") + except AssertionError as e: + raise AssertionError( # noqa: B904 + f"Incorrect result from choice {choice}\n\n{e}" + ) + except Exception as e: + try: + from triton.runtime.autotuner import OutOfResources + + if isinstance(e, OutOfResources): + log.warning(e) + timing = float("inf") + else: + raise e + except ImportError: + raise e from None + + timings[choice] = timing + + # If a collective choice failed or timed out, skip the rest of the choices + if is_collective and not math.isfinite(timing): + log.warning( + "Choice %s failed or timed out during collective benchmarking. " + "Stopping further benchmarking to avoid NCCL corruption.", + getattr(choice, "name", ""), + ) + timings.update({c: float("inf") for c in choices if c not in timings}) + break + + # Skip remaining CUTLASS choices after first failure (#171094) + if not math.isfinite(timing) and isinstance(choice, CUTLASSTemplateCaller): + has_valid_fallback = any( + math.isfinite(t) and not isinstance(c, CUTLASSTemplateCaller) + for c, t in timings.items() + ) + if has_valid_fallback: + log.warning( + "CUTLASS choice %s failed during benchmarking. " + "Skipping remaining CUTLASS choices to avoid CUDA context corruption.", + getattr(choice, "name", ""), + ) + for c in choices: + if c not in timings and isinstance(c, CUTLASSTemplateCaller): + timings[c] = float("inf") + break + + return timings + + @classmethod + def benchmark_in_current_process( + cls, + choices: Sequence[ChoiceCaller], + input_nodes: list[ir.IRNode], + layout: ir.Layout, + input_gen_fns: dict[int, Callable[[ir.Buffer], torch.Tensor]] | None, + hint_override: int | None = None, + is_collective=False, + ) -> dict[ChoiceCaller, float]: + inputs = cls.get_inputs( + choices, input_nodes, layout, input_gen_fns, hint_override=hint_override + ) + return cls.benchmark_choices( + choices, + inputs, + is_collective=is_collective, + ) + + @classmethod + def benchmark_in_sub_process( + cls, + choices: Sequence[ChoiceCaller], + input_nodes: list[ir.IRNode], + layout: ir.Layout, + input_gen_fns: dict[int, Callable[[ir.Buffer], torch.Tensor]] | None, + hint_override: int | None = None, + ): + from . import autotune_process + from .codegen.cutlass.kernel import CUTLASSTemplateCaller + + # ATen/Extern kernels are safe to benchmark in the current process. + extern = [c for c in choices if cls._is_extern(c)] + non_cutlass = [ + c + for c in choices + if not cls._is_extern(c) and not isinstance(c, CUTLASSTemplateCaller) + ] + cutlass = [c for c in choices if isinstance(c, CUTLASSTemplateCaller)] + + timings = cls.benchmark_in_current_process( + extern, input_nodes, layout, input_gen_fns, hint_override=hint_override + ) + # Order Triton before CUTLASS so valid Triton timings are collected + # before any CUTLASS kernel can crash the subprocess (#171094) + timings.update(autotune_process.benchmark_in_sub_process(non_cutlass + cutlass)) # type: ignore[arg-type] + return timings + + @classmethod + def make_benchmark_fn( + cls, + choices: Sequence[ChoiceCaller], + input_nodes: list[ir.IRNode], + layout: ir.Layout, + input_gen_fns: dict[int, Callable[[ir.Buffer], torch.Tensor]] | None, + hint_override: int | None = None, + is_collective=False, + ): + from .codegen.cutlass.kernel import CUTLASSTemplateCaller + + if DEBUG: + print(f"{len(choices)} tuning requests:") + + has_cutlass = any(isinstance(c, CUTLASSTemplateCaller) for c in choices) + + # Collective ops must use current process + if is_collective: + return functools.partial( + cls.benchmark_in_current_process, + input_nodes=input_nodes, + layout=layout, + input_gen_fns=input_gen_fns, + hint_override=hint_override, + is_collective=is_collective, + ) + # CUTLASS kernels can cause sticky CUDA errors that permanently corrupt + # the CUDA context, so always benchmark them in a subprocess (#171094) + elif config.autotune_in_subproc or has_cutlass: + return functools.partial( + cls.benchmark_in_sub_process, + input_nodes=input_nodes, + layout=layout, + input_gen_fns=input_gen_fns, + hint_override=hint_override, + ) + else: + return functools.partial( + cls.benchmark_in_current_process, + input_nodes=input_nodes, + layout=layout, + input_gen_fns=input_gen_fns, + hint_override=hint_override, + ) + + @staticmethod + def prescreen_choices( + choices: list[ChoiceCaller], + name: str, + inputs_key: str, + prescreen_cache: dict[str, OrderedSet[str]], + ) -> list[ChoiceCaller]: + """ + Figure out what choices need to be prescreened before autotuning with runtime + params. + + Prescreening is a process of reducing the number of autotuning for choices with + runtime params via a two stage autotuning process. First, we fix a set of runtime + params (here we use swizzle=2) and run autotuning to get a set of candidates. + Then, we run autotuning again with the candidates and the full set of runtime + params. + + Since have the concept of runtime params, we need to differentiate between + choice's hash_key and choice's kernel_hash_key. The former includes information + like runtime params, while the latter does not. prescreen_cache, if exists, stores + the set of hash_key that should win the prescreening. + + Right now, only CUTLASS choices have runtime params. + """ + # Create a cache key for prescreening results + prescreen_key = f"{name}:{inputs_key}" + + # Check if we have cached prescreening results (prescreen_winners) + if prescreen_key in prescreen_cache: + prescreen_winners = [ + choice + for choice in choices + if choice.hash_key() in prescreen_cache[prescreen_key] + ] + return prescreen_winners + + # prescreen cutlass + from .codegen.cutlass.kernel import CUTLASSTemplateCaller + + candidates = [] + if ( + config.cutlass.cutlass_prescreening + and len(config.cutlass.cutlass_max_profiling_swizzle_options) > 1 + ): + candidates.extend( + [ + c + for c in choices + if isinstance(c, CUTLASSTemplateCaller) + # hardcoded to only look at swizzle=2 + if c.info_dict().get("swizzle") == "2" + ] + ) + + # skip prescreening if the number of candidates is too small + if len(candidates) < 10: + return [] + + # Include ATen in prescreening as fallback (#171094) + extern_choices = [c for c in choices if isinstance(c, ExternKernelCaller)] + candidates = extern_choices + candidates + + return candidates # type: ignore[return-value] + + @staticmethod + def prune_choices_postscreen( + choices: list[ChoiceCaller], + candidate_timings: dict[ChoiceCaller, float], + name: str, + inputs_key: str, + prescreen_cache: dict[str, OrderedSet[str]], + ) -> list[ChoiceCaller]: + """ + Prune the choices after prescreening. + """ + from .codegen.cutlass.kernel import CUTLASSTemplateCaller + + prescreen_key = f"{name}:{inputs_key}" + + # Check if we have cached postscreen results + if prescreen_key in prescreen_cache: + # candidate_timings are from choices that have won prescreening already + winner_kernel_hashes = [ + candidate.kernel_hash_key() for candidate in candidate_timings + ] + + pruned_choices = [ + choice + for choice in choices + if not isinstance(choice, CUTLASSTemplateCaller) + or choice.kernel_hash_key() in winner_kernel_hashes + ] + return pruned_choices + + log.debug("Before pruning using prescreening timings, %d choices", len(choices)) + sorted_candidates = sorted( + candidate_timings.keys(), key=lambda choice: candidate_timings[choice] + ) + + # Print prescreening timings + if ( + candidate_timings + and PRINT_AUTOTUNE + and config.autotune_num_choices_displayed != 0 + ): + n = config.autotune_num_choices_displayed + top_k = sorted_candidates[:n] + best = top_k[0] + best_time = candidate_timings[best] + + lines = ["PRESCREENING CANDIDATE TIMINGS"] + for choice in top_k: + result = candidate_timings[choice] + if result: + lines.append( + f" {choice.name} {result:.4f} ms {best_time / result:.1%} {choice.description}" + ) + else: + lines.append( + f" {choice.name} {result:.4f} ms " + ) + + log.info("\n".join(lines)) + num_to_keep = max(int(math.sqrt(len(choices)) / 4), 8) + + # prune choices based on prescreening timings + candidates_to_prune = OrderedSet( + candidate.kernel_hash_key() for candidate in sorted_candidates[num_to_keep:] + ) + winner_hashes: OrderedSet[str] = OrderedSet() + for candidate in sorted_candidates[:num_to_keep]: + if candidate_timings[candidate] == float("inf"): + candidates_to_prune.add(candidate.kernel_hash_key()) + else: + winner_hashes.add(candidate.hash_key()) + if isinstance(candidate, CUTLASSTemplateCaller): + candidate.bmreq.ensure_dll_loaded() + + pruned_choices = [ + choice + for choice in choices + if choice.kernel_hash_key() not in candidates_to_prune # type: ignore[attr-defined] + ] + + # Cache the hash_key of winners of prescreening + prescreen_cache[prescreen_key] = winner_hashes + + log.debug( + "After pruning using prescreening timings, %d choices", len(pruned_choices) + ) + return pruned_choices + + @staticmethod + def maybe_log_mm_results( + name: str, input_nodes: list[ir.IRNode], timings: dict[ChoiceCaller, float] + ) -> None: + """Log matrix multiplication autotuning results.""" + mm_filename = get_mm_log_filename() + if not mm_filename: + return + + # Classify operation to ensure it's actually an MM operation + choices_list = list(timings.keys()) + operation_type = _classify_kernel_operation(name, choices_list, input_nodes) + if operation_type != "mm": + return + + if len(input_nodes) < 2: + return + + M, K = input_nodes[-2].get_size()[:2] + N = input_nodes[-1].get_size()[-1] + + def get_choice_info(choice): + if isinstance(choice, ExternKernelCaller): + return {"type": "cublas", "time": timings[choice]} + + if isinstance(choice, TritonTemplateCaller): + info = choice.info_dict() + tile = info["tile_shape"] + + tile_vals = eval(tile) # type: ignore[arg-type] + BLOCK_M = tile_vals[0] + BLOCK_K = tile_vals[1] + BLOCK_N = tile_vals[2] + + return { + "type": "triton", + "time": timings[choice], + "BLOCK_M": BLOCK_M, + "BLOCK_K": BLOCK_K, + "BLOCK_N": BLOCK_N, + "num_stages": info["num_stages"], + "num_warps": info["num_warps"], + "waves_per_eu": info.get("waves_per_eu", 0), + "matrix_instr_nonkdim": info.get("matrix_instr_nonkdim", 0), + "kpack": info.get("kpack", 2), + } + return None + + out_dict = { + str((M, K, N)): [get_choice_info(choice) for choice in timings], + "kernel_type": name, + } + + append_to_log(mm_filename, out_dict) + + @staticmethod + def maybe_log_conv_results( + name: str, input_nodes: list[ir.IRNode], timings: dict[ChoiceCaller, float] + ) -> None: + """Log convolution autotuning results.""" + conv_filename = get_conv_log_filename() + if not conv_filename: + return + + # Classify operation to ensure it's actually a conv operation + choices_list = list(timings.keys()) + operation_type = _classify_kernel_operation(name, choices_list, input_nodes) + if operation_type != "conv": + return + + if len(input_nodes) < 2: + return + + x_size = input_nodes[0].get_size() + w_size = input_nodes[1].get_size() + + def get_conv_choice_info(choice): + if choice not in timings: + return None + info = choice.info_dict() + + # Start with timing and backend type + result = { + "time": timings[choice], + "backend": info.get("backend", "unknown"), + } + + # Add all parameters from info_dict + for key, value in info.items(): + if key != "backend": # Already added + # Convert non-serializable types to strings + try: + import json + + json.dumps(value) # Test if serializable + result[key] = value + except (TypeError, ValueError): + result[key] = str(value) + + return result + + out_dict = { + "input_shape": str(x_size), + "weight_shape": str(w_size), + "choices": [ + get_conv_choice_info(choice) + for choice in timings + if get_conv_choice_info(choice) is not None + ], + "kernel_type": name, + } + + append_to_log(conv_filename, out_dict) + + @staticmethod + def get_flex_attention_choice_info( + choice: ChoiceCaller, timings: dict[ChoiceCaller, float] + ) -> dict[str, Any]: + if isinstance(choice, torch._inductor.select_algorithm.ExternKernelCaller): + return {"type": "extern", "time": timings[choice]} + + if not isinstance( + choice, torch._inductor.select_algorithm.TritonTemplateCaller + ): + raise AssertionError( + f"expected choice to be TritonTemplateCaller, got {type(choice)}" + ) + + info = choice.info_dict() + result = { + "type": "triton", + "time": timings[choice], + } + + for key in AlgorithmSelectorCache.FLEX_ATTENTION_TUNABLE_KEYS: + if key in info: + # pyrefly: ignore [unsupported-operation] + result[key] = info[key] + + return result + + @staticmethod + def _flex_attention_log_dim(dim: int | torch.SymInt | sympy.Expr) -> int: + if isinstance(dim, torch.SymInt): + dim = dim.node.expr + + if type(dim) is int or isinstance(dim, sympy.Integer): + return int(dim) + + if isinstance(dim, sympy.Expr): + return V.graph.sizevars.optimization_hint(dim) + + raise TypeError( + f"Unexpected flex attention log dimension type {type(dim).__name__}: {dim}" + ) + + @staticmethod + def _flex_attention_log_shape( + size: Sequence[int | torch.SymInt | sympy.Expr], + ) -> str: + dims = [AlgorithmSelectorCache._flex_attention_log_dim(dim) for dim in size] + return f"[{', '.join(map(str, dims))}]" + + @staticmethod + def maybe_log_flex_attention_results( + name: str, input_nodes: list[ir.IRNode], timings: dict[ChoiceCaller, float] + ) -> None: + """Log flex attention autotuning choices when logging is enabled.""" + flex_attention_filename = get_flex_attention_log_filename() + # Support both flex_attention and flex_decoding + if not flex_attention_filename or ( + "flex_attention" not in name and "flex_decoding" not in name + ): + return + + if len(input_nodes) < 3: + return + + query_size = input_nodes[0].get_size() + key_size = input_nodes[1].get_size() + value_size = input_nodes[2].get_size() + + # Handle both 4D (forward/backward) and 5D (decode) tensor formats + # 4D: [B, H, seq_len, head_dim] + # 5D: [B, H, 1, 1, head_dim] (decode mode has extra dimension) + if len(query_size) == 5: + # Decode mode with 5D tensors + B = query_size[0] + Hq = query_size[1] + # query_size[2] and query_size[3] are both 1 for decode + seq_len_q = query_size[2] # This will be 1 + qk_head_dim = query_size[4] # Head dim is at index 4 for 5D + Hkv = key_size[1] + seq_len_kv = key_size[2] + v_head_dim = value_size[4] if len(value_size) == 5 else value_size[3] + else: + # Forward/backward mode with 4D tensors + B = query_size[0] + Hq = query_size[1] + seq_len_q = query_size[2] + qk_head_dim = query_size[3] + Hkv = key_size[1] + seq_len_kv = key_size[2] + v_head_dim = value_size[3] + + kernel_type = ( + "backward" + if "backward" in name + else ("decode" if "decoding" in name else "forward") + ) + + # Create shape info dictionary + shape_info = { + "kernel_type": kernel_type, + "B": AlgorithmSelectorCache._flex_attention_log_dim(B), + "Hq": AlgorithmSelectorCache._flex_attention_log_dim(Hq), + "Hkv": AlgorithmSelectorCache._flex_attention_log_dim(Hkv), + "seq_len_q": AlgorithmSelectorCache._flex_attention_log_dim(seq_len_q), + "seq_len_kv": AlgorithmSelectorCache._flex_attention_log_dim(seq_len_kv), + "qk_head_dim": AlgorithmSelectorCache._flex_attention_log_dim(qk_head_dim), + "v_head_dim": AlgorithmSelectorCache._flex_attention_log_dim(v_head_dim), + } + + sorted_choices = sorted(timings, key=timings.__getitem__) + + # Include shape info in each choice + choices_with_shapes = [] + for choice in sorted_choices: + choice_info = AlgorithmSelectorCache.get_flex_attention_choice_info( + choice, timings + ) + # Merge shape info with choice info + choice_info.update(shape_info) + choices_with_shapes.append(choice_info) + + out_dict = { + "query_shape": AlgorithmSelectorCache._flex_attention_log_shape(query_size), + "key_shape": AlgorithmSelectorCache._flex_attention_log_shape(key_size), + "value_shape": AlgorithmSelectorCache._flex_attention_log_shape(value_size), + "kernel_type": kernel_type, + "choices": choices_with_shapes, + } + append_to_log(flex_attention_filename, out_dict) + + @staticmethod + def log_results( + name: str, + input_nodes: list[ir.IRNode], + timings: dict[ChoiceCaller, float], + elapse: float, + precompile_elapse: float, + prescreening_elapse: float | None = None, + hint_override: int | None = None, + is_collective: bool = False, + ): + """Log the autotuning results, currently only handles mm and flex. Log Collective op autotuning result""" + if is_collective and timings: + import torch.distributed as dist + + # Only rank 0 logs to avoid duplicate logs + rank = dist.get_rank() if dist.is_initialized() else 0 + if rank == 0: + best_choice = min(timings, key=timings.__getitem__) + log.warning("[COLLECTIVE AUTOTUNING] All timings:") + for c, t in sorted(timings.items(), key=lambda x: x[1]): + choice_name = getattr(c, "name", str(c)) + log.warning( + " - %s: %.6f ms %s", + choice_name, + t if math.isfinite(t) else float("inf"), + "← SELECTED" if c == best_choice else "", + ) + + V.debug.log_autotuning_results( + name, input_nodes, timings, elapse, precompile_elapse, prescreening_elapse + ) + if not (config.max_autotune or config.max_autotune_gemm) or not PRINT_AUTOTUNE: + return + + sizes = ", ".join( + [ + "x".join( + map( + str, + V.graph.sizevars.optimization_hints_with_override( + n.get_size(), + hint_override=hint_override, + ), + ) + ) + for n in input_nodes + ] + ) + + strides = ", ".join( + [str(get_strides_with_layout_constraints(n)) for n in input_nodes] + ) + dtypes = ", ".join([str(n.get_dtype()) for n in input_nodes]) + if config.autotune_num_choices_displayed == 0: + return + + # when autotune_num_choices_displayed is None, [:None] means all + n = config.autotune_num_choices_displayed + top_k = sorted(timings, key=timings.__getitem__)[:n] + + best = top_k[0] + + # Log autotuning results for each operation type + AlgorithmSelectorCache.maybe_log_mm_results(name, input_nodes, timings) + AlgorithmSelectorCache.maybe_log_conv_results(name, input_nodes, timings) + AlgorithmSelectorCache.maybe_log_flex_attention_results( + name, input_nodes, timings + ) + + best_time = timings[best] + sys.stderr.write(f"AUTOTUNE {name}({sizes})\n") + sys.stderr.write(f"strides: {strides}\n") + sys.stderr.write(f"dtypes: {dtypes}\n") + + for choice in top_k: + result = timings[choice] + if result: + kernel_description = choice.description + sys.stderr.write( + f" {choice.name} {result:.4f} ms {best_time / result:.1%} {kernel_description}\n" + ) + else: + sys.stderr.write( + f" {choice.name} {result:.4f} ms \n" + ) + + autotune_type_str = ( + "SubProcess" if config.autotune_in_subproc else "SingleProcess" + ) + prescreening_msg = ( + f" and {prescreening_elapse:.4f} seconds prescreening" + if prescreening_elapse is not None + else "" + ) + sys.stderr.write( + f"{autotune_type_str} AUTOTUNE benchmarking takes {elapse:.4f} seconds and {precompile_elapse:.4f}" + f" seconds precompiling for {len(timings)} choices" + + prescreening_msg + + "\n" + ) + + @staticmethod + def benchmark_example_value(node, hint_override: int | None = None): + """ + Convert an ir.Buffer into a concrete torch.Tensor we can use for + benchmarking. + """ + if isinstance(node, ir.Layout): + node = ir.Buffer(name="fake", layout=node) + # triton templates want the base tensor. + # Preserve the original dtype before unwrapping, since dtype views + # (e.g. uint8 -> float4_e2m1fn_x2) would be lost by unwrap_view. + original_dtype = node.get_dtype() + if isinstance(node, ir.BaseView): + node = node.unwrap_view() + + # Inplace padding may reinterpret a tensor to a larger tensor if the + # stride is large enough. The V.graph.get_allocation_size takes this into account. + # So we need call as_strided in the end to 'view' the tensor with the correct + # sizes/strides + result = AlgorithmSelectorCache.generate_example_value( + V.graph.sizevars.optimization_hints_with_override( + node.get_size(), + hint_override=hint_override, + ), + V.graph.sizevars.optimization_hints_with_override( + get_strides_with_layout_constraints(node), + hint_override=hint_override, + ), + node.get_device(), + node.get_dtype(), + V.graph.sizevars.optimization_hint_with_override( + node.layout.offset, + hint_override=hint_override, + ), + V.graph.sizevars.optimization_hints_with_override( + V.graph.get_allocation_size(node), + hint_override=hint_override, + ), + ) + # Restore dtype if it was lost by unwrapping a dtype view + if result.dtype != original_dtype: + result = result.view(original_dtype) + return result + + @staticmethod + def generate_example_value( + size, stride, device, dtype, extra_size, allocation_size=None + ): + # preserve rng states to avoid the rand_strided call below changes + # the rng states for the real model code. + with preserve_rng_state(): + if allocation_size is None or allocation_size == size: + return rand_strided( + size, + stride, + device=device, + dtype=dtype, + extra_size=extra_size, + ) + else: + return rand_strided( + allocation_size, + stride, + device=device, + dtype=dtype, + extra_size=extra_size, + ).as_strided(size, stride) + + @staticmethod + def key_of(node): + """ + Extract the pieces of an ir.Buffer that we should invalidate cached + autotuning results on. + """ + sizevars = V.graph.sizevars + return ( + node.get_device().type, + str(node.get_dtype()), + *sizevars.optimization_hints(node.get_size()), + *V.graph.sizevars.optimization_hints( + get_strides_with_layout_constraints(node) + ), + sizevars.optimization_hint(node.get_layout().offset), + ) + + def add_feedback_saver(self, fn: FeedbackFunction): + self.feedback_saver_fns.append(fn) + + def clear_feedback_savers(self): + self.feedback_saver_fns = [] + + def add_preprocessing_fn(self, fn: PreprocessingFunction): + self.preprocessing_fns.append(fn) + + def clear_preprocessing_fns(self, clear_defaults: bool = False): + """Clear preprocessing functions. + + Args: + clear_defaults: If True, clears all functions including defaults. + If False, clears only user-added functions and re-registers defaults. + """ + self.preprocessing_fns.clear() + if not clear_defaults: + self._register_default_preprocessing_fns() + + +_ALGORITHM_SELECTOR_CACHE: AlgorithmSelectorCache | None = None + + +def get_algorithm_selector_cache() -> AlgorithmSelectorCache: + """Get the global algorithm selector cache, creating it if it doesn't exist.""" + global _ALGORITHM_SELECTOR_CACHE + if _ALGORITHM_SELECTOR_CACHE is None: + _ALGORITHM_SELECTOR_CACHE = AlgorithmSelectorCache() + return _ALGORITHM_SELECTOR_CACHE + + +def autotune_select_algorithm(*args, **kwargs): + cache = get_algorithm_selector_cache() + + if "return_multi_template" not in kwargs: + kwargs["return_multi_template"] = ( + torch._inductor.config.benchmark_epilogue_fusion + or torch._inductor.config.pipeline_max_autotune_gemm + ) + + if "precompilation_timeout_seconds" not in kwargs: + kwargs["precompilation_timeout_seconds"] = config.precompilation_timeout_seconds + + return cache(*args, **kwargs) + + +def add_feedback_saver( + fn: FeedbackFunction, +): + cache = get_algorithm_selector_cache() + cache.add_feedback_saver(fn) + + +def clear_feedback_savers(): + """Clear all feedback saver functions.""" + cache = get_algorithm_selector_cache() + cache.clear_feedback_savers() + + +def add_preprocessing_fn( + fn: PreprocessingFunction, +): + """Add a preprocessing function to be applied to choices before autotuning. + + Preprocessing functions are called sequentially in the order they were registered, + with each function receiving the output of the previous one. They can filter, + reorder, transform, or modify the list of choices in any way. + + Args: + fn: A function that takes a list of ChoiceCaller objects and returns + a modified list of ChoiceCaller objects. + + Example: + def my_filter(choices): + # Filter out choices with certain names + return [c for c in choices if 'slow' not in c.name.lower()] + + add_preprocessing_fn(my_filter) + """ + cache = get_algorithm_selector_cache() + cache.add_preprocessing_fn(fn) + + +def clear_preprocessing_fns(clear_defaults: bool = False): + """Clear preprocessing functions at module level. + + Args: + clear_defaults: If True, clears all functions including defaults. + If False, clears only user-added functions and re-registers defaults. + """ + cache = get_algorithm_selector_cache() + cache.clear_preprocessing_fns(clear_defaults) + + +def realize_inputs(*args): + if len(args) == 1: + realized = ir.ExternKernel.realize_input(args[0]) + # Shape scalars are represented as scalar IR, e.g. ShapeAsConstantBuffer. + # Tensor layout constraints such as stride-1 only apply to tensor IR. + if not realized.has_tensor_output(): + return realized + return ir.ExternKernel.require_stride1(realized) + return [realize_inputs(x) for x in args] + + +def should_use_layout_constraints(node): + # View has its own fixed layout that is not constrained + if ( + getattr(node, "layout", None) is not None + and not isinstance(node, ir.ReinterpretView) + and not isinstance(node.get_layout(), ir.NonOwningLayout) + and node.get_name() in V.graph.buffer_layout_constraints + ): + return True + return False + + +def get_strides_with_layout_constraints(node): + if should_use_layout_constraints(node): + return V.graph.buffer_layout_constraints[node.get_name()].stride + return node.get_stride() + + +class SymbolicGridFn: + """ + Wrapper around a grid function that allows either int or sympy inputs. + + @SymbolicGridFn + def grid(x, meta, *, cdiv): + return cdiv(x, meta["BLOCK_X"]) + """ + + def __init__(self, fn: Callable[..., tuple[Any, Any, Any]]): + self.fn = fn + self.kwargs_int = {} + self.kwargs_sym = {} + params = inspect.signature(fn).parameters + for name, fn_sym, fn_int in [ + ("cdiv", CeilDiv, ceildiv), + ("min", Min, min), + ("max", Max, max), + ]: + if name in params: + self.kwargs_int[name] = fn_int + self.kwargs_sym[name] = fn_sym + + def __call__(self, *args, **kwargs) -> tuple[int, int, int]: + return self.fn(*args, **kwargs, **self.kwargs_int) + + def sympy_call(self, *args, **kwargs): + return self.fn(*args, **kwargs, **self.kwargs_sym) + + +def _autotune_metadata(input_nodes): + """Helper function to extract autotune metadata from input nodes.""" + return { + "autotune_strides": ", ".join([str(n.get_stride()) for n in input_nodes]), + "autotune_dtypes": ", ".join([str(n.get_dtype()) for n in input_nodes]), + "autotune_shape": ", ".join( + ["x".join(map(str, n.get_size())) for n in input_nodes] + ), + "autotune_offset": ", ".join([str(n.get_layout().offset) for n in input_nodes]), + # TODO(coconutruben): replace this with taking KernelInputs as the + # argument, and extracting those out there directly + "autotune_strides_hinted": ", ".join( + [ + str(V.graph.sizevars.optimization_hints(n.get_stride())) + for n in input_nodes + ] + ), + "autotune_shape_hinted": ", ".join( + [ + "x".join( + map( + str, + V.graph.sizevars.optimization_hints(n.get_size()), + ) + ) + for n in input_nodes + ] + ), + } + + +def _log_autotune_choices_stats( + event_name: str, timings: dict[ChoiceCaller, float] +) -> None: + """Helper function to extract autotune metadata from benchmark results.""" + if not timings: + return None + + metadata: dict[str, int | float | str] = { + "num_choices": len(timings), + "num_triton_choices": len( + [c for c in timings if isinstance(c, TritonTemplateCaller)] + ), + } + + sorted_choices = sorted(timings, key=timings.__getitem__) + best_choice = sorted_choices[0] + metadata["best_kernel"] = best_choice.name + if best_choice.description: + metadata["best_kernel_desc"] = best_choice.description + metadata["best_time"] = timings[best_choice] + + best_triton_pos = next( + ( + i + for i, choice in enumerate(sorted_choices) + if isinstance(choice, TritonTemplateCaller) + ), + None, + ) + if best_triton_pos is not None: + metadata["best_triton_pos"] = best_triton_pos + best_triton_kernel = sorted_choices[best_triton_pos] + if best_triton_pos != 0: + metadata["best_triton_time"] = timings[best_triton_kernel] + metadata["best_triton_kernel"] = best_triton_kernel.name + if best_triton_kernel.description: + metadata["best_triton_kernel_desc"] = best_triton_kernel.description + + payload = json.dumps(metadata) + get_chromium_event_logger().add_event_data( + event_name, autotune_choices_stats=payload + ) + sys.stderr.write(f"Autotune Choices Stats:\n{payload}\n") + + +def _log_autotune_exceptions( + exceptions: list[tuple[ChoiceCaller, BaseException]], +) -> None: + """Log autotune exceptions to chromium event logger.""" + if not exceptions: + return + + try: + pt2_compile_substack = get_chromium_event_logger().get_pt2_compile_substack() + if not pt2_compile_substack: + return + + current_event = pt2_compile_substack[-1] + if not current_event.endswith("_template_precompiling"): + return + + exception_details = [] + for choice, exc in exceptions: + try: + choice_type = ( + "triton" if isinstance(choice, TritonTemplateCaller) else "other" + ) + data = { + "choice_type": choice_type, + "choice": choice.description, + "exception_message": str(exc), + } + + exc_type_match = re.search(r"(\w+):", str(exc)) + if exc_type_match: + data["exception"] = exc_type_match.group(1) + + if "OutOfMemoryError" in str(exc): + required_match = re.search(r"Required: (\d+)", str(exc)) + if required_match: + data["required_memory"] = required_match.group(1) + + limit_match = re.search(r"Hardware limit:\s*(\d+)", str(exc)) + if limit_match: + data["hardware_limit"] = limit_match.group(1) + + exception_details.append(data) + except Exception: + # Don't let logging errors break the main flow + continue + + if exception_details: + metadata = json.dumps({"exceptions": exception_details}) + get_chromium_event_logger().try_add_event_data( + current_event, metadata=metadata + ) + except Exception: + # Silently ignore logging errors to avoid breaking autotune + pass + + +# ensure lowering is imported so that `extern_kernels.*` is populated +from . import lowering # noqa: F401 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/shape_propagation.py b/.venv/lib/python3.12/site-packages/torch/_inductor/shape_propagation.py new file mode 100644 index 0000000000000000000000000000000000000000..62d537dbeeb8a0334f4c5d6a52ce7435ae358f8b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/shape_propagation.py @@ -0,0 +1,163 @@ +import functools +from collections.abc import Callable, Sequence +from typing import Protocol + +import sympy + +import torch + +from .virtualized import OpsValue, V + + +BlockShapeType = Sequence[int | str] | None + + +class ShapeVar(Protocol): + @property + def shape(self) -> BlockShapeType: ... + + +ShapeArg = ShapeVar | torch.types.Number | str | OpsValue | torch.dtype + +# Inputs need to be cacheable (e.g., not a CSEVar) in order for the cache to be effective +# So first decompose CSEVars -> tuple before calling this + + +def get_broadcasted_shape(a: BlockShapeType, b: BlockShapeType) -> BlockShapeType: + if not isinstance(a, Sequence): + raise AssertionError(f"expected a to be a Sequence, got {type(a)}") + if not isinstance(b, Sequence): + raise AssertionError(f"expected b to be a Sequence, got {type(b)}") + return _get_broadcasted_shape(tuple(a), tuple(b)) + + +@functools.lru_cache(None) +def _get_broadcasted_shape( + a: tuple[int | str, ...], b: tuple[int | str, ...] +) -> BlockShapeType: + if len(a) > len(b): + return _get_broadcasted_shape(a, (*[1] * (len(a) - len(b)), *b)) + elif len(a) < len(b): + b, a = a, b + return _get_broadcasted_shape(a, (*[1] * (len(a) - len(b)), *b)) + else: + + def _get_broadcasted_dim(d1: int | str, d2: int | str) -> int | str: + if str(d1) == "1": + return d2 + elif str(d2) == "1": + return d1 + if str(d1) != str(d2): + raise AssertionError(f"expected str(d1) == str(d2), got {d1} != {d2}") + return d1 + + return tuple(_get_broadcasted_dim(d1, d2) for d1, d2 in zip(a, b)) + + +def broadcast_shapes_for_args(args: Sequence[ShapeArg]) -> BlockShapeType: + result_shape: BlockShapeType = None + + for arg in args: + if hasattr(arg, "shape"): + shape = arg.shape + if shape is None: + return None + elif result_shape is None: + result_shape = tuple(shape) + else: + result_shape = get_broadcasted_shape(result_shape, tuple(shape)) + elif isinstance(arg, (int, float)): + if result_shape is None: + result_shape = () + elif isinstance(arg, torch.dtype): + continue + else: + from torch._inductor.loop_body import LoopBody, LoopBodyBlock + + if isinstance(arg, (LoopBodyBlock, LoopBody, OpsValue)): + # TODO: fix me + return None + raise TypeError(f"Unknown type: {type(arg)}") + + return result_shape + + +class ShapePropagationOpsHandler: + """ + Propagate shape from args to output + """ + + @staticmethod + def constant(value: torch.types.Number, dtype: torch.dtype) -> BlockShapeType: + # TritonKernelOverrides.constant uses tl.full with shape=[1]*ndim for all types + from torch._inductor.codegen.triton import TritonKernel + + if isinstance(V.kernel, TritonKernel): + ndim = V.kernel.triton_tensor_ndim() + return tuple([1] * ndim) + else: + return () + + @staticmethod + def store_reduction(name: str, index: int, value: ShapeArg) -> None: + return None + + @staticmethod + def reduction( + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: str, + value: ShapeArg | tuple[ShapeArg, ...], + ) -> BlockShapeType | tuple[BlockShapeType, ...]: + raise NotImplementedError + + @staticmethod + def store(name: str, index: int, value: ShapeArg, mode: str | None = None) -> None: + return None + + @staticmethod + def to_dtype( + value: ShapeVar, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types: bool = True, + ) -> BlockShapeType: + return value.shape + + @staticmethod + def dot(a: sympy.Expr, b: sympy.Expr) -> BlockShapeType: + from torch._inductor.codegen.triton import TritonKernel + + if not isinstance(V.kernel, TritonKernel): + raise AssertionError("dot supports Triton only") + return ("YBLOCK", "XBLOCK") + + @staticmethod + def index_expr(expr: sympy.Expr, dtype: torch.dtype) -> BlockShapeType: + # shape is implicitly embedded in expr. + return None + + @staticmethod + def value_expr(expr: sympy.Expr, dtype: torch.dtype) -> BlockShapeType: + # shape is implicitly embedded in expr. + return None + + @staticmethod + def load_seed(name: str, offset: int) -> BlockShapeType: + return () + + @staticmethod + def indirect_indexing( + var: ShapeArg, + size: sympy.Expr | int, + check: bool = True, + wrap_neg: bool = True, + ) -> None: + return None + + def __getattr__(self, name: str) -> Callable[..., BlockShapeType]: + return lambda *args, **kwargs: broadcast_shapes_for_args(args) + + @staticmethod + def device_assert_async(cond: ShapeArg, msg: str) -> None: + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/sizevars.py b/.venv/lib/python3.12/site-packages/torch/_inductor/sizevars.py new file mode 100644 index 0000000000000000000000000000000000000000..07d2f0fee50565d3901c3caef1182d43fa8eddfe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/sizevars.py @@ -0,0 +1,1611 @@ +# mypy: allow-untyped-defs +import dataclasses +import functools +import itertools +import logging +from collections.abc import Callable, Iterable, Sequence +from typing import Any, cast + +import sympy +from sympy import Expr + +from torch import SymInt +from torch.fx.experimental._size_hinting import ( + _guarding_hint_or_throw_base, + _maybe_realize_expr, + _optimization_hint_base, +) +from torch.fx.experimental.symbolic_shapes import ( + free_symbols, + free_unbacked_symbols, + IterateExprs, + ShapeEnv, + SymNode, +) +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import ( + FloorDiv, + Max, + Min, + Mod, + ModularIndexing, + safe_gcd, + simple_floordiv_gcd, +) +from torch.utils._sympy.numbers import int_oo +from torch.utils._sympy.symbol import symbol_is_type, SymT +from torch.utils._sympy.value_ranges import IntInfinity, ValueRanges + +from . import config +from .runtime.runtime_utils import is_power_of_2 +from .utils import ( + has_free_symbols, + sympy_index_symbol, + sympy_index_symbol_with_prefix, + sympy_subs, + VarRanges, +) +from .virtualized import V + + +log = logging.getLogger(__name__) + + +Width = int | IntInfinity + + +@dataclasses.dataclass(frozen=True) +class LaneContiguity: + """How an index expression varies across lanes. + + This describes only the per-lane relationship, not full memory safety. + Callers still need to prove the relevant tensor dimension, stride, and base + alignment make a vector load valid. ``int_oo`` means the expression does not + impose a finite limit on that width. + """ + + contiguous_width: Width | None = None + uniform_width: Width | None = None + stride: int | Expr | None = None + unknown: bool = False + + @property + def uniform(self) -> bool: + return self.uniform_width is not None + + def is_contiguous_for(self, width: int) -> bool: + return _width_covers(self.contiguous_width, width) + + def is_uniform_for(self, width: int) -> bool: + return _width_covers(self.uniform_width, width) + + +def _width_covers(max_width: Width | None, width: int) -> bool: + return max_width is not None and (max_width == int_oo or max_width >= width) + + +def _min_width(lhs: Width | None, rhs: Width | None) -> Width | None: + if lhs is None or rhs is None: + return None + if lhs == int_oo: + return rhs + if rhs == int_oo: + return lhs + return min(lhs, rhs) + + +def _largest_power_of_2_factor(n: int) -> int: + return n & -n + + +# Symbols created by CppTemplateKernel.slice_nd → parse_expr_with_index_symbols +# and are internal to C++ GEMM codegen (not tracked by ShapeEnv). +_GEMM_TEMPLATE_SYMBOL_NAMES = OrderedSet( + [ + "m_start", + "m_end", + "n_start", + "n_end", + "k_start", + "k_end", + "m_size", + "n_size", + "m_offset", + "m_start_unsliced", + "m_end_unsliced", + "m_size_unsliced", + ] +) + + +# Threshold above which we skip sympy reasoning that scales poorly in the +# number of symbols. Past this point, polynomial-domain conversions inside +# sympy (e.g. gcd, Mod) dominate compile time on wide concat/sum expressions +# (see https://github.com/sympy/sympy/issues/28200). Chosen empirically from +# AOT-partitioned bwd graphs with ~60-variable shape expressions. +_MAX_SYMBOLS_FOR_EXPENSIVE_SYMPY_OPS = 20 + + +@functools.lru_cache +def stride_at(index: sympy.Expr, var: sympy.Symbol): + if not index.has(var): + # see test_torchinductor_dynamic_shapes.py::test_full_boolean_dynamic_shapes_cpu + # which has tmp0 = ops.index_expr(s0 >= 1024, torch.bool) and fails below calculation. + # in this case, there is no dependencies between index and var. + return sympy.S.Zero + replacement = {var: var + 1} + new_index = sympy_subs(index, replacement) # type: ignore[arg-type] + return sympy.simplify(new_index - index) + + +@functools.lru_cache +def simplify_index_in_vec_range(index: sympy.Expr, var: sympy.Expr, vec_length: int): + """ + Simplifies the index expression within the range of a vectorized loop. + Given a vectorized loop variable `var` in the range of a loop with `vec_length`, + this function transforms the `index` into an equivalent form. It handles + simplifications for cases where `var` can be expressed as `vec_length * a + b`, + where `b` ranges from 0 to `vec_length - 1`. The function reduces occurrences + of `FloorDiv` and `ModularIndexing` in the `index` with best-effort optimizations. + + NOTE: + The simplified index expression is intended for analysis purposes only, not + for code generation. It replaces `FloorDiv` and `ModularIndexing` with free variables + which are not dependent on the loop variable `var` in the vectorized range. Check + https://github.com/pytorch/pytorch/pull/117221#discussion_r1449746217 for more details. + + Examples: + 1. If `var` is `x3` and `vec_length` is 16, and `x3 = 16*a + b`, then + `FloorDiv(x3, div)` or `ModularIndexing(x3, div, mod)` becomes a free variable + when `div` is divisible by 16. + 2. `ModularIndexing(x3, 1, mod)` can be simplified to `x3 + c` where `c` is a free + variable when `mod` is divisible by 16. + """ + + div_freevar_id = 0 + mod_freevar_id = 0 + + def visit_indexing_div(divisor): + nonlocal div_freevar_id + result = FloorDiv(var, divisor) + if sympy.gcd(divisor, vec_length) == vec_length: + result = sympy.Symbol(f"{var}_div_c{div_freevar_id}") + div_freevar_id += 1 + return result + + def visit_modular_indexing(divisor, modulus): + nonlocal mod_freevar_id + result = ModularIndexing(var, divisor, modulus) + if sympy.gcd(divisor, vec_length) == vec_length: + result = sympy.Symbol(f"{var}_mod_c{mod_freevar_id}") + mod_freevar_id += 1 + elif divisor == 1 and sympy.gcd(modulus, vec_length) == vec_length: + result = var + sympy.Symbol(f"{var}_mod_c{mod_freevar_id}") + mod_freevar_id += 1 + return result + + original_index = index + + div = sympy.Wild("divisor", integer=True) + if index.has(FloorDiv): + index = index.replace(FloorDiv(var, div), visit_indexing_div) + + mod = sympy.Wild("modulus", integer=True) + if index.has(ModularIndexing): + index = index.replace(ModularIndexing(var, div, mod), visit_modular_indexing) + + if not index.has(sympy.Rel): + index = sympy.simplify(index) + if index != original_index: + return simplify_index_in_vec_range(index, var, vec_length) + + return index + + +@functools.lru_cache +def stride_at_vec_range( + index: sympy.Expr, var: sympy.Symbol, vec_length: int | None = None +): + if vec_length: + index = simplify_index_in_vec_range(index, var, vec_length) + return stride_at(index, var) + + +def statically_known_true( + shape_env: ShapeEnv, + expr: sympy.Basic | bool, + axioms: tuple[sympy.Expr] | None = None, + var_to_range: tuple[tuple[sympy.Symbol, ValueRanges[Any]]] | None = None, +) -> bool: + if expr in (True, False): + return bool(expr) + + # Hint fast-path: if the current concrete hints make `expr` evaluate to + # False, it cannot be universally True, so bail out without running the + # much more expensive `_maybe_evaluate_static`. (A True hint doesn't let + # us conclude universal truth, so we still fall through in that case.) + try: + hinted = expr.xreplace(shape_env.backed_var_to_val) + if hinted is sympy.S.false: + return False + except Exception: + pass + + try: + simplified = shape_env._maybe_evaluate_static( + expr, + axioms=axioms, + var_to_range=var_to_range, + ) + if simplified is not None: + return bool(simplified) + except Exception: + log.debug("Could not simplify %s", expr, exc_info=True) + + return False + + +# This class is a little awkward, because ShapeEnv is doing most of the heavy +# lifting and in some cases we should be directly passing through to ShapeEnv, +# but there is some extra inductor logic that needs to be handled here +class SizeVarAllocator: + """ + A class that manages symbolic size variables and their relationships. + + This class works with the ShapeEnv to handle symbolic shape expressions, + simplify them, and provide utilities for guarding, checking, and evaluating + symbolic expressions. It also manages precomputed replacements and stride + calculations for tensor operations. + """ + + def __init__(self, shape_env=None) -> None: + super().__init__() + # Note: this can lead to bugs. Reasoning APIs depends on existing information in + # in the shape_env. For example! var_to_ranges can't be empty! + if shape_env is None: + shape_env = ShapeEnv() + self.shape_env = shape_env + self.backed_var_to_val = self.shape_env.backed_var_to_val + self.var_to_hint_override = self.shape_env.var_to_hint_override + self.replacements: dict[sympy.Symbol, Expr] = self.shape_env.replacements + self.unbacked_replacements: dict[Expr, Expr] | None = None + # Maps of dynamic sizes that have to be precomputed on the host to the kernel args. + # The basic idea is if we have some complicated sympy expression + # f(s0), we may choose to precompute it on the host and then replace + # all occurrences of that sympy expression with ps0, so that when we + # codegen we simply reference ps0 directly without repeating + # f(s0). Unlike regular size variables, ps variables cannot be + # guarded upon; so if we are asked to guard on a Sympy expression + # which potentially could have already had a precomputed replacement + # on it, we are obligated to invert the precomputed replacements + # (inv_precomputed_replacements). + self.precomputed_replacements: dict[Expr, sympy.Symbol] = {} + self.inv_precomputed_replacements: dict[sympy.Symbol, Expr] = {} + self.stride_vars = self.make_stride_vars_cache() + self.simplify_with_ranges = self.make_simplify_with_ranges_cache() + self._simplify_loops = self.make_simplify_loops_cache() + + def simplify(self, expr: Expr): + return sympy.expand(expr).xreplace(self.replacements) + + def make_simplify_with_ranges_cache(self) -> Callable[[Expr, VarRanges], Expr]: + """ + self._simplify_with_ranges() can be expensive, cache its results + """ + cache: dict[tuple[Any, ...], Expr] = {} + replacement_count = len(self.replacements) + + def simplify_with_ranges(expr: Expr, var_ranges: VarRanges) -> Expr: + nonlocal replacement_count + if replacement_count != len(self.replacements): + # new replacements invalidates cached results + cache.clear() + replacement_count = len(self.replacements) + key = (expr, *var_ranges.items()) + result = cache.get(key) + if result is None: + result = self._simplify_with_ranges(expr, var_ranges) + cache[key] = result + if result != expr: + cache[(result, *var_ranges.items())] = result + return result + + return simplify_with_ranges + + def make_simplify_loops_cache(self): + """ + self._simplify_with_ranges() can be expensive, cache its results + """ + cache: dict[tuple[Any, ...], Any] = {} + replacement_count = len(self.replacements) + + def simplify_loops(index_vars, sizes, index_formulas): + nonlocal replacement_count + if replacement_count != len(self.replacements): + # new replacements invalidates cached results + cache.clear() + replacement_count = len(self.replacements) + key = (*index_vars, *sizes, *index_formulas) + result = cache.get(key) + if result is None: + result = self._simplify_loops_impl(index_vars, sizes, index_formulas) + cache[key] = result + return result + + return simplify_loops + + def _simplify_with_ranges(self, expr: Expr, var_ranges: VarRanges) -> Expr: + """ + Simplify indexing expression with knowledge of the ranges of + iteration variables. + """ + + expr = join_dimensions(self.simplify(expr)) + original_expr = expr + + var_to_range = dict(self.shape_env.var_to_range) + var_to_range.update( + { + k: ValueRanges( + 0, max(0, v - 1) if not has_free_symbols([v]) else IntInfinity() + ) + for k, v in var_ranges.items() + } + ) + for var in expr.free_symbols: + if var not in var_to_range: + var_to_range[var] = ValueRanges(0, IntInfinity()) + + var_to_range_tuple = cast( + tuple[tuple[sympy.Symbol, ValueRanges[sympy.Expr]]], + tuple(var_to_range.items()), + ) + + axioms = [] + for var, upper_bound in var_ranges.items(): + axioms.append(0 <= var) + axioms.append(var < upper_bound) + axioms = tuple(axioms) + self.shape_env.get_axioms() + + def statically_known(expr): + evaluated = self.shape_env._maybe_evaluate_static( + expr, + # pyrefly: ignore [bad-argument-type] + axioms=axioms, + var_to_range=var_to_range_tuple, + ) + return bool(evaluated) + + def remove_zero_terms(base, divisor): + """Symbols smaller than the divisor are zero""" + if not statically_known(base >= 0): + return base + + for v in base.free_symbols: + if v in var_ranges: + rest = sympy.Wild("_rest", exclude=[v]) + m = base.match(v + rest) + if m and v not in m[rest].free_symbols: + gcd = safe_gcd(m[rest], divisor) + if statically_known(v < gcd): + base = m[rest] + return base + + def visit_indexing_div(base, divisor): + base = remove_zero_terms(base, divisor) + if statically_known(base >= 0) and statically_known(base < divisor): + return sympy.S.Zero + # FloorDiv(ModularIndexing(b, d1, m), d2) = ModularIndexing(b, d1*d2, m//d2) + if isinstance(base, ModularIndexing) and isinstance(divisor, sympy.Integer): + b, d1, m = base.args + if m % divisor == 0: + return ModularIndexing(b, d1 * divisor, FloorDiv(m, divisor)) + return FloorDiv(base, divisor) + + def visit_modular_indexing(base, divisor, modulus): + base = remove_zero_terms(base, divisor) + + if isinstance(base, ModularIndexing): + inner_base, inner_divisor, inner_modulus = base.args + period = divisor * modulus + # Target use cases have constant indices; avoid symbolic compile-time analysis. + if all( + isinstance(value, sympy.Integer) and value > 0 + for value in (inner_modulus, divisor, modulus) + ) and self.statically_known_multiple_of(inner_modulus, period): + return ModularIndexing(inner_base, inner_divisor * divisor, modulus) + + can_remove_mod = statically_known(base >= 0) and statically_known( + base < modulus * divisor + ) + + if can_remove_mod: + return FloorDiv(base, divisor) + return ModularIndexing(base, divisor, modulus) + + if expr.has(ModularIndexing): + expr = expr.replace( + ModularIndexing( + sympy.Wild("base", integer=True), + sympy.Wild("divisor", integer=True), + sympy.Wild("modulus", integer=True), + ), + visit_modular_indexing, + ) + + if expr.has(FloorDiv): + expr = expr.replace( + FloorDiv( + sympy.Wild("base", integer=True), + sympy.Wild("divisor", integer=True), + ), + visit_indexing_div, + ) + + if expr != original_expr: + return self._simplify_with_ranges(expr, var_ranges) + return expr + + def _simplify_loops_impl( + self, index_vars: list[sympy.Symbol], sizes, index_formulas + ): + """ + Try to remove as many axis from loop iterations as possible, by: + 1) removing size==1 dimensions + 2) fuse contiguous dimensions into a single loop + If channel_last = True, we will prevent the last dim fused with other dims + """ + sizes = list(map(self.simplify, sizes)) + + strides = [ + # index_formulas may contain boolean expressions (e.g. s0 < 10), + # for which "strides" don't make sense so we ignore them here. + # NOTE: These expressions may still block merging dims in the sound + # substitution test performed in can_merge_dims. + ( + self.stride_vars(x, index_vars) + if isinstance(x, sympy.Expr) + else [0] * len(index_vars) + ) + for x in index_formulas + ] + if len(sizes) != len(strides[0]): + raise AssertionError((len(sizes), len(strides[0]))) + + for i in range(len(sizes)): + if sizes[i] == 1: + # remove dim + sizes[i] = None + + def can_merge_dims(a, b): + for k in range(len(strides)): + if self.simplify(strides[k][a] * sizes[a]) == self.simplify( + strides[k][b] + ): + # approximate test passed, try sound version + va = index_vars[a] + vb = index_vars[b] + m1 = sympy_index_symbol("_merge_tester1") + m2 = sympy_index_symbol("_merge_tester2") + # NOTE: can't sub vb=0 here in case va * vb appears in the expression, + # in which case both expr1 and expr2 would be zero! + expr1 = sympy_subs(index_formulas[k], {va: m1 * sizes[a], vb: m2}) + expr2 = sympy_subs(index_formulas[k], {va: 0, vb: (m1 + m2)}) + if self.simplify(expr1) == self.simplify(expr2): + continue + return False + return True + + changed = True + while changed: + changed = False + for i, j in itertools.product( + reversed(range(len(sizes))), reversed(range(len(sizes))) + ): + if i == j or sizes[i] is None or sizes[j] is None: + continue + if can_merge_dims(i, j): + changed = True + sizes[i] = sizes[i] * sizes[j] + sizes[j] = None + + def reindex(index): + it = list(reversed(index)) + new_index = [] + for size in sizes: + if size is None: + new_index.append(sympy.S.Zero) + else: + new_index.append(it.pop()) + if it: + raise AssertionError(f"expected all entries consumed, got {it}") + return new_index + + def prune(index): + if len(index) != len(sizes): + raise AssertionError( + f"expected len(index) == len(sizes), got {len(index)} != {len(sizes)}" + ) + return [i for i, s in zip(index, sizes) if s is not None] + + return [x for x in sizes if x is not None], reindex, prune + + # Note - [On Statically Known] + # The statically_known_* family of functions below NEVER guard, they could return True if the + # asked questions can be answered without guarding otherwise they return False. + # Those are similar to statically_known_true in symbolic_shapes.py but operate on sympy + # expressions instead of symnodes. + def statically_known_true(self, expr: sympy.Basic | bool) -> bool: + """ + Returns true if an expression is always true (symbolically or via guards), + false otherwise. Never add guards, or throw data dependent errors. + """ + return statically_known_true(self.shape_env, expr) + + def statically_known_equals(self, left: Expr | int, right: Expr | int) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left and right are equal. + """ + return self.statically_known_true(sympy.Eq(left, right)) # type: ignore[arg-type] + + def statically_known_list_equals( + self, left: Sequence[Expr], right: Sequence[Expr] + ) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left and right lists are equal. + """ + return len(left) == len(right) and all( + self.statically_known_equals(l, r) for l, r in zip(left, right) + ) + + def statically_known_leq(self, left: Expr, right: Expr | int) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left is less than or equal to right. + """ + expr = left <= right + return self.statically_known_true(expr) + + def statically_known_geq(self, left: Expr, right: Expr | int) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left is greater than or equal to right. + """ + expr = left >= right + return self.statically_known_true(expr) + + def statically_known_lt(self, left: Expr, right: Expr | int) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left is less than right. + """ + expr = left < right + return self.statically_known_true(expr) + + def statically_known_gt(self, left: Expr, right: Expr | int) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left is greater than right. + """ + expr = left > right + return self.statically_known_true(expr) + + def _is_multiple_of(self, numerator: Expr, denominator: int) -> bool: + """ + Structural divisibility check: returns True only if numerator is + provably a multiple of denominator. Recurses over sympy expression + structure before falling back to statically_known_true. + """ + # Rule 1 — concrete value + if isinstance(numerator, (int, sympy.Integer)): + return int(numerator) % denominator == 0 + + # Rule 2 — product: any factor divisible → product divisible + if isinstance(numerator, sympy.Mul): + for factor in numerator.args: + if self._is_multiple_of(factor, denominator): + return True + const = 1 + for factor in numerator.args: + if isinstance(factor, (int, sympy.Integer)): + const *= int(factor) + if const != 1 and const % denominator == 0: + return True + + # Rule 3 — sum: all terms divisible → sum divisible + if isinstance(numerator, sympy.Add): + if all(self._is_multiple_of(term, denominator) for term in numerator.args): + return True + + # Rule 4 — FloorDiv(a, b): if a is multiple of b*n + if isinstance(numerator, FloorDiv): + a, b = numerator.args + if isinstance(b, (int, sympy.Integer)): + if self._is_multiple_of(a, int(b) * denominator): + return True + + # Rule 5 — Mod(a, b): Mod(a,b) = a - b*floor(a/b), so if both a and b + # are multiples of n, then Mod(a,b) is too. + if isinstance(numerator, (Mod, sympy.Mod)): + a, b = numerator.args + if self._is_multiple_of(a, denominator) and self._is_multiple_of( + b, denominator + ): + return True + + # Rule 6 — cheap gcd check before expensive sympy fallback. + gcd = simple_floordiv_gcd(numerator, sympy.Integer(denominator)) + if isinstance(gcd, (int, sympy.Integer)) and int(gcd) % denominator == 0: + return True + + # Rule 7 — full sympy fallback (expensive on many-variable exprs). + if len(free_symbols(numerator)) > _MAX_SYMBOLS_FOR_EXPENSIVE_SYMPY_OPS: + return False + expr = sympy.Eq(Mod(numerator, denominator), 0) + return self.statically_known_true(expr) + + def statically_known_multiple_of( + self, numerator: Expr, denominator: Expr | int + ) -> bool: + """ + Return a bool indicating if it is sound to optimize for the numerator being a multiple of the denominator. + """ + # Use cheap structural equality, not statically_known_equals — + # the latter constructs sympy.Eq(wide, wide) which has measurable + # overhead (~30s on 64-variable expressions). + if numerator is denominator or numerator == denominator: + return True + + if isinstance(denominator, (int, sympy.Integer)): + return self._is_multiple_of(numerator, int(denominator)) + + if numerator == 0: + return True + + # Symbolic denominator: Mod-based reasoning can miss factorable Add + # denominators even for small expressions, so prove cancellation + # directly under the same limit used for the sympy fallback below. + if ( + len(free_symbols([numerator, denominator])) + > _MAX_SYMBOLS_FOR_EXPENSIVE_SYMPY_OPS + ): + return False + + def gcd_covers_denominator(gcd: sympy.Basic) -> bool: + return gcd != 1 and ( + gcd == denominator or self.simplify(gcd - denominator) == 0 + ) + + try: + if gcd_covers_denominator(simple_floordiv_gcd(numerator, denominator)): + return True + if gcd_covers_denominator(safe_gcd(numerator, denominator)): + return True + except sympy.PolynomialError: + pass + + expr = sympy.Eq(Mod(numerator, denominator), 0) + return self.statically_known_true(expr) # type: ignore[arg-type] + + def statically_known_power_of_2(self, expr: Expr) -> bool: + """ + Returns a bool indicating if x is known to be a power of 2. + """ + return isinstance(expr, sympy.Integer) and is_power_of_2(int(expr)) + + def analyze_lane_contiguity( + self, expr: Expr, lane_var: sympy.Symbol + ) -> LaneContiguity: + """Analyze whether `expr` is uniform or contiguous over vector lanes. + + The analysis is conservative: unknown cases must fall back to scalar or + gather-style lowering. It only describes the lane pattern of the index + expression; callers must still prove tensor stride, offset, dtype, and + alignment before emitting a vector memory load. + """ + expr = self.simplify(expr) + if lane_var not in expr.free_symbols: + return LaneContiguity(stride=0, uniform_width=int_oo) + stride = stride_at(expr, lane_var) + match expr: + case _ if self.statically_known_equals(stride, 1): + return LaneContiguity(contiguous_width=int_oo, stride=1) + case _ if self.statically_known_equals(stride, 0): + return LaneContiguity(stride=0, uniform_width=int_oo) + case sympy.Add(): + return self._analyze_lane_contiguity_add(expr.args, lane_var) + case sympy.Mul(): + return self._analyze_lane_contiguity_mul(expr.args, lane_var) + case FloorDiv(): + return self._analyze_lane_contiguity_floor_div( + expr.args[0], expr.args[1], lane_var + ) + case ModularIndexing(): + return self._analyze_lane_contiguity_modular_indexing(expr, lane_var) + case _ if isinstance(expr, (Mod, sympy.Mod)): + return self._analyze_lane_contiguity_mod( + expr.args[0], expr.args[1], lane_var + ) + case _: + return LaneContiguity(unknown=True) + + def _analyze_lane_contiguity_add( + self, args: tuple[Expr, ...], lane_var: sympy.Symbol + ) -> LaneContiguity: + """Combine additive terms when at most one term varies across lanes.""" + uniform_width: Width | None = int_oo + varying_result: LaneContiguity | None = None + for arg in args: + arg_result = self.analyze_lane_contiguity(arg, lane_var) + if arg_result.unknown: + return LaneContiguity(unknown=True) + if arg_result.uniform: + uniform_width = _min_width(uniform_width, arg_result.uniform_width) + elif varying_result is None: + varying_result = arg_result + else: + return LaneContiguity(unknown=True) + if varying_result is None: + return LaneContiguity(stride=0, uniform_width=uniform_width) + return LaneContiguity( + contiguous_width=_min_width(varying_result.contiguous_width, uniform_width), + stride=varying_result.stride, + ) + + def _analyze_lane_contiguity_mul( + self, args: tuple[Expr, ...], lane_var: sympy.Symbol + ) -> LaneContiguity: + """Propagate lane stride through lane-uniform multiplication.""" + uniform_factor: Expr = sympy.S.One + lane_factors = [] + for arg in args: + if lane_var in arg.free_symbols: + lane_factors.append(arg) + else: + uniform_factor *= arg + if len(lane_factors) != 1: + return LaneContiguity(unknown=True) + child_result = self.analyze_lane_contiguity(lane_factors[0], lane_var) + if child_result.unknown or child_result.stride is None: + return LaneContiguity(unknown=True) + stride = self.simplify(uniform_factor * child_result.stride) + if self.statically_known_equals(stride, 0): + return LaneContiguity( + stride=0, + uniform_width=child_result.uniform_width, + ) + return LaneContiguity( + contiguous_width=child_result.contiguous_width + if self.statically_known_equals(stride, 1) + else None, + stride=stride, + ) + + def _analyze_lane_contiguity_modular_indexing( + self, expr: Expr, lane_var: sympy.Symbol + ) -> LaneContiguity: + """Analyze ModularIndexing(base, divisor, modulus).""" + base, divisor, modulus = expr.args + if not isinstance(divisor, (int, sympy.Integer)): + return LaneContiguity(unknown=True) + if int(divisor) != 1: + return self._analyze_lane_contiguity_floor_div(base, divisor, lane_var) + return self._analyze_lane_contiguity_mod(base, modulus, lane_var) + + def _analyze_lane_contiguity_floor_div( + self, base: Expr, divisor: Expr, lane_var: sympy.Symbol + ) -> LaneContiguity: + """Return the largest width where ``base // divisor`` is lane-uniform.""" + if not isinstance(divisor, (int, sympy.Integer)): + return LaneContiguity(unknown=True) + divisor_int = int(divisor) + if divisor_int <= 0: + return LaneContiguity(unknown=True) + base_result = self.analyze_lane_contiguity(base, lane_var) + if not base_result.is_contiguous_for(2) or not self.statically_known_equals( + base_result.stride, 1 + ): + return LaneContiguity(unknown=True) + group_start = self.simplify(base.xreplace({lane_var: sympy.Integer(0)})) + width = _min_width( + base_result.contiguous_width, + _largest_power_of_2_factor(divisor_int), + ) + while isinstance(width, int) and width >= 2: + if self.statically_known_multiple_of(group_start, width): + return LaneContiguity(stride=0, uniform_width=width) + width //= 2 + return LaneContiguity(unknown=True) + + def _analyze_lane_contiguity_mod( + self, + base: Expr, + modulus: Expr, + lane_var: sympy.Symbol, + ) -> LaneContiguity: + """Return the largest aligned no-wrap modulo span. + + `base % modulus` is contiguous for a vector group only when both the + group start and modulus are multiples of the chosen width. For example, + lanes 0..3 under `% 4` are contiguous, but lanes 2..5 wrap to 2,3,0,1. + """ + if not isinstance(modulus, (int, sympy.Integer)): + return LaneContiguity(unknown=True) + modulus_int = int(modulus) + if modulus_int <= 0: + return LaneContiguity(unknown=True) + base_result = self.analyze_lane_contiguity(base, lane_var) + if not base_result.is_contiguous_for(2) or not self.statically_known_equals( + base_result.stride, 1 + ): + return LaneContiguity(unknown=True) + group_start = self.simplify(base.xreplace({lane_var: sympy.Integer(0)})) + width = _min_width( + base_result.contiguous_width, + _largest_power_of_2_factor(modulus_int), + ) + while isinstance(width, int) and width >= 2: + if self.statically_known_multiple_of(group_start, width): + return LaneContiguity(contiguous_width=width, stride=1) + width //= 2 + return LaneContiguity(unknown=True) + + # The expect/check functions require you to ALREADY KNOW that a particular + # condition holds. They are similar to expect_true in symbolic_shapes.py and + # torch.check but operates on sympy expressions instead of symnodes. + def expect_true(self, expr: Expr) -> bool: + """ + Use it when you already know that expr is true or should be true and want to + ensure that guards/runtime assertions are in place to ensure this in compiled + function. Unlike check, this WON'T raise an error if expr isn't actually true. + check Note [expect_true]. + """ + if not self.statically_known_true(expr): + return self.shape_env.guard_or_defer_runtime_assert( + expr, "sizevars.expect_true" + ) + return True + + def check(self, expr: Expr) -> None: + """ + Use it when you already know that expr is true or should be true and want to + ensure that guards/runtime assertions are in place to ensure this in compiled + function. Unlike expect_true, this WILL raise an error if expr isn't actually true. + check Note [expect_true]. + """ + expr = sympy_subs(expr, self.inv_precomputed_replacements) + if not self.expect_true(expr): + raise AssertionError(f"expect_true failed for {expr}") + + def check_equals(self, left: Expr, right: Expr) -> None: + """ + check(sympy.Eq(left, right)). + + """ + self.check(sympy.Eq(left, right)) + return left + + def check_equals_and_simplify(self, left: Expr, right: Expr) -> Expr: + """ + check(sympy.Eq(left, right)) and returns left after applying + inv_precomputed_replacements. + """ + self.check(sympy.Eq(left, right)) + return sympy_subs(left, self.inv_precomputed_replacements) + + def check_leq(self, left: Expr, right: Expr) -> None: + self.check(sympy.Le(left, right)) + + def check_lt(self, left: Expr, right: Expr) -> None: + self.check(sympy.Lt(left, right)) + + # Similar to the functions guard_or_false/guard_or_true in symbolic_shapes.py + # but operates on sympy expressions instead of symnodes. see Note [guard_or_]. + def guard_or_false(self, left): + import torch.fx.experimental._config as exp_config + + if exp_config.backed_size_oblivious: + static_val = self.shape_env._maybe_evaluate_static(left) + if static_val is not None: + return static_val + return False + return self.evaluate_expr(left, fallback_value=False) + + def guard_or_true(self, left): + import torch.fx.experimental._config as exp_config + + if exp_config.backed_size_oblivious: + static_val = self.shape_env._maybe_evaluate_static(left) + if static_val is not None: + return static_val + return True + return self.evaluate_expr(left, fallback_value=True) + + # The evaluate functions evaluate some symbolic sympy expression + # (NB: not necessarily an Expr) and return what the concrete result + # is, guarding on the expression being that result + + # NB: write evaluate_expr(sympy.Lt(a, b)) rather than evaluate_expr(a < b) + # as this will ensure that you actually have a sympy'ified expression, + # and will prevent you from incorrectly writing evaluate_expr(a == b) + # which does the wrong thing if a or b is a sympy expression + def evaluate_expr( + self, + left: Expr | sympy.logic.boolalg.Boolean, + size_oblivious: bool = False, + fallback_value: bool | None = None, + ) -> bool: + if not isinstance(left, (Expr, sympy.logic.boolalg.Boolean)): + raise AssertionError(type(left)) + return self.shape_env.evaluate_expr( + sympy.sympify(left), + size_oblivious=size_oblivious, + fallback_value=fallback_value, + ) + + def is_size_one_or_false(self, size: Expr) -> bool: + """Return True if size equals 1. + + Unbacked symbolic sizes return False without introducing a guard. + """ + return self.guard_or_false(sympy.Eq(size, 1)) + + def evaluate_min(self, left: Expr, right: Expr) -> Expr: + """Return the smaller of left and right, and guard on that choice.""" + if isinstance(left, Expr): + left = sympy_subs(left, self.inv_precomputed_replacements) # type: ignore[arg-type] + if isinstance(right, Expr): + right = sympy_subs(right, self.inv_precomputed_replacements) # type: ignore[arg-type] + if self.guard_or_false(sympy.Le(left, right)): + return left + if self.guard_or_false(sympy.Le(right, left)): + return right + + # GCD fallback: if gcd(a, b) == a then a divides b, implying a <= b. + # + # TODO: This is NOT always sound for unbacked symints. It can + # produce wrong results when: + # - inputs can be negative: gcd(u0, 10*u0) = u0, returns u0, + # but if u0 < 0 then u0 > 10*u0 (e.g. u0=-1: min(-1,-10) = -10) + # - a factor can be zero: gcd(u0, u0*u1) = u0, returns u0, + # but if u1=0 then u0*u1=0 < u0 (e.g. u0=5,u1=0: min(5,0) = 0) + # TODO shall we add a runtime assertion at least. + gcd = sympy.gcd(left, right) + if left == gcd: + return left + if right == gcd: + return right + + # Min/Max fallback: we can prove Min(a, b) <= c when any arg <= c, but + # sympy doesn't simplify this yet. So, evaluate it here. Same for Max. + for lhs, rhs in [(left, right), (right, left)]: + + def le_rhs(a: Expr) -> bool: + return self.guard_or_false(sympy.Le(a, rhs)) + + # Min(Min(a, b), c) ==> Min(a, b) if (a <= c) or (b <= c). + if isinstance(lhs, (sympy.Min, Min)) and any(le_rhs(a) for a in lhs.args): + return lhs + # Min(Max(a, b), c) ==> Max(a, b) if (a <= c) and (b <= c). + if isinstance(lhs, (sympy.Max, Max)) and all(le_rhs(a) for a in lhs.args): + return lhs + + raise TypeError( + f"evaluate_min({left}, {right}) with unbacked symints" + ) from None + + def evaluate_max(self, left: Expr, right: Expr) -> Expr: + """Return the larger of left and right, and guard on that choice.""" + # Always choose the opposite of eval min for consistency + # This means min(a, b) and max(a, b) produce the same guards + min_val = self.evaluate_min(left, right) + return right if min_val is left else left + + def guard_int(self, expr: Expr | int) -> int: + """ + Similar to guard_int in symbolic_shapes.py, except this function works with SymPy + expressions instead of SymNodes. It extracts the value represented by expr from shapeEnv + and specialize the compiled graph on it. Raises an error if the result cannot be + determined due to unhinted or unbacked symbols. + """ + if isinstance(expr, int): + return expr + val = self.guarding_hint_or_throw(expr) + self.check_equals(expr, sympy.Integer(val)) + return int(val) + + def guard_int_seq(self, left: Sequence[Expr | int]) -> list[int]: + """ + Apply guard_int on a sequence of inputs. + """ + return [self.guard_int(x) for x in left] + + def remove_precomputed_replacements(self, expr: Expr) -> Expr: + if any(symbol_is_type(s, SymT.PRECOMPUTED_SIZE) for s in expr.free_symbols): # type: ignore[attr-defined] + return sympy_subs(expr, self.inv_precomputed_replacements) # type: ignore[arg-type] + return expr + + def replace_backed_symbols_with_hints( + self, + expr: Expr | int, + ) -> Expr | int: + """ + Replace all backed symbols in an expression with their concrete hint values. + + This function substitutes backed symbolic variables with their known concrete + values from the shape environment, while leaving unbacked symbols (data-dependent + values) untouched. Not recommended to be used except as last resort! + was added for existing usages compatibility. + """ + if isinstance(expr, int): + return expr + # Substitute all hints into expr, but leave unbacked symints alone + expr = self.simplify(expr) + if not isinstance(expr, Expr): + if not isinstance(expr, int): + raise AssertionError(f"expected int, got {type(expr)}") + return expr + + expr = self.remove_precomputed_replacements(expr) + expr = sympy_subs(expr, self.backed_var_to_val) + if isinstance(expr, Expr): + expr = expr.expand(identity=True) + + free_symbols = expr.free_symbols + if not free_symbols: + try: + return int(expr) + except TypeError: + return expr # inf/nan/I + + return expr + + def to_symint_or_int(self, expr: Expr | int) -> SymInt | int: + """Convert a sympy expression to SymInt, or return int as is.""" + if isinstance(expr, int): + return expr + + from torch.fx.experimental.sym_node import SymNode + + expr = self.simplify(expr) + if isinstance(expr, (int, sympy.Integer)): + return int(expr) + + # Remove precomputed replacements to get canonical form + # (consistent with symbolic_hint behavior) + expr = self.remove_precomputed_replacements(expr) + + try: + hint = self.guarding_hint_or_throw(expr) + except Exception: + hint = None + node = SymNode(expr, self.shape_env, int, hint) + return SymInt(node) + + def to_symints_or_ints(self, exprs: Sequence[Expr | int]) -> list[SymInt | int]: + """Convert a sequence of sympy expressions to SymInts, or return ints as is.""" + return [self.to_symint_or_int(e) for e in exprs] + + def guarding_hint_or_throw(self, expr: Expr | int) -> int: + """ + Return a concrete integer hint for an expression that is safe to use for guarding. + + This method evaluates the expression using only backed-symbols hints. Unlike + optimization_hint(), this method does NOT use heuristics or fallback values + for unbacked symbols. + + Use this method when you need a hint value that will be used for guarding decision. + + Args: + expr: A sympy expression or integer to evaluate. + + Returns: + The concrete integer value of the expression based on backed symbol hints. + + Raises: + GuardOnDataDependentSymNode: If the expression contains unbacked symbols + (data-dependent values) that cannot be resolved to concrete values. + + See Also: + optimization_hint: For cases where fallback/heuristic values are acceptable + for unbacked symbols. + """ + if isinstance(expr, SymNode): + raise TypeError( + f"guarding_hint_or_throw expects a sympy Expr or int, not {type(expr)}. " + "Use expr.expr to extract the sympy expression from a SymNode." + ) + return _guarding_hint_or_throw_base( + self.shape_env, expr, self.inv_precomputed_replacements + ) + + def optimization_hint(self, expr: Expr | int, fallback: int | None = None) -> int: + """ + Return a concrete integer hint for an expression. + + This function should be used for non-guarding based optimizations. If you + want a hint that you can guard on, use the guarding_hint API instead. + + This function will hint unbacked symbols using user provided optimization + hints. If not provided, fallback will be used along with some heuristics + that try to maximize consistency with the shape environment. + + Special cases: + - Complex numbers (containing sympy.I): raises an error since tensor + dimensions cannot be complex. + - Infinity (int_oo, sympy.oo): returns sys.maxsize. + - NaN (sympy.nan): returns the fallback value. + """ + return _optimization_hint_base( + self.shape_env, expr, self.inv_precomputed_replacements, fallback + ) + + def optimization_hints( + self, + exprs: Iterable[Expr | int], + fallback: int | None = None, + ) -> tuple[int, ...]: + """ + Like optimization_hint but for a sequence of expressions. + Returns a tuple of concrete integer hints. + """ + # Read config at call time to respect runtime patches (e.g., in tests) + if fallback is None: + fallback = config.unbacked_symint_fallback + return tuple(self.optimization_hint(x, fallback=fallback) for x in exprs) + + def all_unbacked_explicitly_hinted(self, exprs: IterateExprs) -> bool: + """ + Return True if every unbacked symbol in *exprs* has an explicit + user-provided hint in var_to_hint_override. If there are no + unbacked symbols at all, returns True (vacuously). + *exprs* can be a single expression or any iterable accepted by + free_unbacked_symbols (list, tuple, etc.). + """ + unbacked = free_unbacked_symbols(exprs) + return unbacked.issubset(self.var_to_hint_override.keys()) + + def optimization_hint_with_override( + self, + expr: Expr | int, + hint_override: int | None, + ) -> int: + r"""Return a concrete integer hint for an expression, with optional override. + This is used in dynamic dispatch scenarios where callers may want to + provide a specific hint value rather than computing one from the expression. + The resolution order is: + 1. If ``expr`` simplifies to a static integer, return that value + (``hint_override`` is ignored for static shapes). + 2. If ``expr`` is dynamic and ``hint_override`` is not ``None``, + return ``hint_override``. + 3. Otherwise, compute a hint via :meth:`optimization_hint` + Args: + expr (Expr or int): The expression to get a hint for. + hint_override (int, optional): If provided and ``expr`` is dynamic, + this value is returned instead of computing a hint. + Returns: + int: A concrete integer hint for the expression. + """ + simplified = _maybe_realize_expr(self.simplify(expr), None) + + if simplified is not None: + return simplified + + # Dynamic shape: use hint_override if set, + # else return optimization_hint + if hint_override is not None: + return hint_override + + return self.optimization_hint(expr) + + def optimization_hints_with_override( + self, + exprs: Iterable[Expr | int], + hint_override: int | None, + ) -> tuple[int, ...]: + """ + Like optimization_hint_with_override but for a sequence of expressions. + Returns a tuple of concrete integer hints. + """ + return tuple( + self.optimization_hint_with_override(e, hint_override) for e in exprs + ) + + def guarding_hints_or_throw( + self, + exprs: Iterable[Expr | int], + ) -> tuple[int, ...]: + return tuple(self.guarding_hint_or_throw(x) for x in exprs) + + def _lru_cache(self, fn, maxsize=None): + """ + Wrapper around functools.lru_cache that clears when replacements + has been invalidated. + """ + fn_cache = functools.lru_cache(maxsize)(fn) + prior_len = len(self.replacements) + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + nonlocal prior_len + if prior_len != len(self.replacements): + prior_len = len(self.replacements) + fn_cache.cache_clear() + return fn_cache(*args, **kwargs) + + return wrapper + + def make_stride_vars_cache(self): + cache = self._lru_cache(self._stride_vars) + + def stride_vars( + index: Expr, + vars: Sequence[sympy.Symbol], + support_vars: Sequence[sympy.Symbol] | None = None, + ) -> list[Expr]: + if not support_vars: + support_vars = vars + return cache(index, tuple(vars), tuple(support_vars)) + + return stride_vars + + def _stride_vars( + self, + index: Expr, + vars: Sequence[sympy.Symbol], + support_vars: Sequence[sympy.Symbol], + ) -> list[Expr]: + """Convert an indexing expression back into strides + + NOTE: This is only valid if the index is a standard strided offset + calculation. e.g. 10 * ModularIndexing(i0 + 1, 1, 2) would give a + stride of -10 because the index wraps around after the first element + + """ + strides = [] + index = self.simplify(index) + # remove any offset + index = index - sympy_subs( + index, {v: sympy.S.Zero for v in support_vars if v != 0} + ) + for i in range(len(vars)): + # drop all the other dims + index_dim = sympy_subs( + index, + { + support_vars[j]: sympy.S.Zero + for j in range(len(support_vars)) + if vars[i] != support_vars[j] and support_vars[j] != 0 + }, + ) + v = vars[i] + if v == 0: + strides.append(sympy.S.Zero) + else: + # TODO(jansel): should we use sympy.diff here? + strides.append( + sympy_subs(index_dim, {v: sympy.S.One}) + - sympy_subs(index_dim, {v: sympy.S.Zero}) + ) + return strides + + def offset_var(self, index: Expr, vars: Sequence[sympy.Symbol]) -> Expr: + """Extract offset part of an indexing expression""" + index = self.simplify(index) + return sympy_subs(index, {v: sympy.S.Zero for v in vars if v != 0}) + + # Return stride optimizaitons hints, + # only used for optimizations. + def stride_hints( + self, + index: Expr, + vars: Sequence[sympy.Symbol], + support_vars: Sequence[sympy.Symbol] | None = None, + ) -> list[int]: + for v in index.free_symbols: + if symbol_is_type(v, SymT.INDIRECT): # type: ignore[attr-defined] + index = sympy_subs(index, {v: 0}) # type: ignore[dict-item] + result = [] + for s in self.stride_vars(index, vars, support_vars): + result.append(self.optimization_hint(s, fallback=0)) + return result + + def stride_order(self, index: Expr, vars: list[sympy.Symbol]) -> list[int]: + strides = tuple(map(abs, self.stride_hints(index, vars))) + order = list(range(len(strides))) + order.sort(key=lambda x: (strides[x] == 0, strides[x])) + return order + + def lookup_precomputed_size(self, expr: Expr) -> Expr: + if ( + isinstance(expr, (int, sympy.Symbol, sympy.Number)) + or expr.is_number + or expr.is_symbol + ): + return expr + expr = self.remove_precomputed_replacements(expr) + if expr not in self.precomputed_replacements: + sym = sympy_index_symbol_with_prefix( + SymT.PRECOMPUTED_SIZE, len(self.precomputed_replacements) + ) + self.precomputed_replacements[expr] = sym + self.inv_precomputed_replacements[sym] = expr + return self.precomputed_replacements[expr] + + def free_symbols(self) -> OrderedSet[sympy.Symbol]: + return OrderedSet(self.backed_var_to_val.keys()) - OrderedSet( + self.replacements.keys() + ) + + def combine_modular_indexing_pairs(self, index: sympy.Expr) -> sympy.Expr: + """ + A pair of special ModularIndexing can be combined. + + E.g. ModularIndexing(ModularIndexing(x, 1, a), 1, b) + We can simplify this to ModuleIndexing(x, 1, b), if + 1. x is non negative integer + 2. a and b are positive integers + 3. a is a multiple of b. + """ + + def _check_args(x, div, mod, is_first): + if not isinstance(div, sympy.Integer) or not isinstance(mod, sympy.Integer): + return False + if div != 1: + return False + if mod <= 0: + return False + + if is_first: + # first ModularIndexing should contains a nested ModularIndex + if not isinstance(x, ModularIndexing): + return False + else: + # second ModularIndexing should contains a non-negative + # symbol + if not isinstance(x, sympy.Symbol) or not self.statically_known_geq( + x, 0 + ): + return False + return True + + if isinstance(index, ModularIndexing): + x, div, mod = index.args + + if not _check_args(x, div, mod, True): + return index + + x2, div2, mod2 = x.args + + if not _check_args(x2, div2, mod2, False): + return index + + if Mod(mod2, mod) != 0: + return index + + return ModularIndexing(x2, 1, mod) + + return index + + def expand_floor_div( + self, + index: sympy.Expr, + candidate_vars: Iterable[sympy.Symbol] | None = None, + ) -> bool | tuple[sympy.Expr, sympy.Expr]: + """ + Expand the FloorDiv to the entire expression so that the expression may + be simplified. + + E.g., for a 2D contiguous tensor with shape [a, 2 * b], and index variables + x1, x2, index expression 'x1 * 2b + x2' can be easily combined. + But index expression 'x1 * b + x2 // 2' can not. + By expanding the FloorDiv to the entire expression, we get + '(x1 * 2b + x2) // 2'. This transformation allows us to merge loops + for the numerator! + + Return false if this optimization cannot be applied; + Return the new expression and the denominator otherwise. + The original expression will be equivalent to 'new_expression // denominator' + """ + candidate_vars_set = ( + OrderedSet(candidate_vars) if candidate_vars is not None else None + ) + + def parse_static_term( + term: sympy.Expr, + ) -> tuple[sympy.Expr, sympy.Symbol] | None: + if not isinstance(term, sympy.Mul): + return None + # For dynamic shape, term like '2*s1*x1' has 3 child nodes. + # Without candidate loop vars we cannot tell shape and loop + # symbols apart, so preserve the historical conservative path. + if len(term.args) != 2: + return None + factor, var = term.args + if not isinstance(factor, sympy.Integer) or not isinstance( + var, sympy.Symbol + ): + return None + return factor, var + + def parse_term(term: sympy.Expr) -> tuple[sympy.Expr, sympy.Symbol] | None: + if candidate_vars_set is None: + parsed = parse_static_term(term) + if parsed is None: + return None + factor, var = parsed + else: + if isinstance(term, sympy.Symbol): + factor = sympy.S.One + var = term + elif isinstance(term, sympy.Mul): + vars_in_term = [ + symbol + for symbol in term.free_symbols + if symbol in candidate_vars_set + ] + if len(vars_in_term) == 0: + parsed = parse_static_term(term) + if parsed is None: + return None + factor, var = parsed + elif len(vars_in_term) == 1: + var = vars_in_term[0] + factor = sympy.cancel(term / var) + if factor.has(*candidate_vars_set): + return None + if factor.is_integer is not True: + return None + else: + return None + else: + return None + + if var not in candidate_vars_set: + return None + + # It's easier to reason about the correctness of the transformation + # for non-negative integers. + if not self.statically_known_geq(var, 0): + return None + return factor, var + + if not isinstance(index, sympy.Add): + return False + terms = index.args + + if len(terms) < 2: + return False + floor_div_index = -1 + varlist = [] + factorlist = [] + for idx, term in enumerate(terms): + if parsed := parse_term(term): + factor, var = parsed + varlist.append(var) + factorlist.append(factor) + elif isinstance(term, FloorDiv): + var, factor = term.args + if not isinstance(factor, sympy.Integer) or not isinstance( + var, sympy.Symbol + ): + return False + if candidate_vars_set is not None and var not in candidate_vars_set: + return False + if not self.statically_known_geq(var, 0): + return False + if floor_div_index >= 0: + # can not handle multi FloorDiv yet + return False + + floor_div_index = idx + varlist.append(var) + # this factor is denominator + factorlist.append(factor) + else: + return False + + if floor_div_index < 0: + return False + + # Construct the new expression and remember the denominator + denominator = factorlist[floor_div_index] + new_index = sympy.S.Zero + + for var, factor, idx in zip(varlist, factorlist, itertools.count()): + if idx == floor_div_index: + new_index += var + else: + new_index += (factor * denominator) * var + + return new_index, denominator + + +def join_dimensions(expr: Expr) -> Expr: + if not isinstance(expr, sympy.Add) or not expr.has(ModularIndexing): + return expr # fast exit path + return _join_dimensions_cached(expr) + + +@functools.lru_cache(256) +def _join_dimensions_cached(expr: Expr) -> Expr: + """ + ModularIndexing(i0, 1, 32) + 32 * ModularIndexing(i0, 32, 4) + becomes + ModularIndexing(i0, 1, 128) + ModularIndexing(i0, 1, 32) + 32 * FloorDiv(i0, 32) + becomes i0 + + + This type of pattern can come from view operations + """ + if not isinstance(expr, sympy.Add): + raise AssertionError(f"expected sympy.Add, got {type(expr)}") + + scale = sympy.Wild("scale", exclude=[0], integer=True) + base = sympy.Wild("base", integer=True) + divisor = sympy.Wild("divisor", integer=True) + mod1 = sympy.Wild("modulus", integer=True) + mod2 = sympy.Wild("modulus2", integer=True) + for term1 in expr.args: + m1 = term1.match(scale * ModularIndexing(base, divisor, mod1)) + if m1: + for term2 in expr.args: + m2 = term2.match( + m1[scale] + * m1[mod1] + * ModularIndexing(m1[base], m1[divisor] * m1[mod1], mod2) + ) + if m2 and term1 != term2: + expr = join_dimensions( + expr + - term1 + - term2 + + m1[scale] + * ModularIndexing(m1[base], m1[divisor], m1[mod1] * m2[mod2]) + ) + return expr + for term1 in expr.args: + m1 = term1.match(scale * ModularIndexing(base, divisor, mod1)) + if m1: + for term2 in expr.args: + m2 = term2.match( + m1[scale] * m1[mod1] * FloorDiv(m1[base], m1[divisor] * m1[mod1]) + ) + if m2 is not None: # in case of success we get an empty dict here + expr = join_dimensions( + expr + - term1 + - term2 + + m1[scale] * FloorDiv(m1[base], m1[divisor]) + ) + return expr + return expr + + +class SimplifyIndexing(V.WrapperHandler): # type: ignore[name-defined] + """ + A wrapper around .virtualize.ops that uses var range information to + simplify ModularIndexing/FloorDiv. + """ + + def __init__(self, inner, var_ranges: VarRanges) -> None: + super().__init__(inner) + self.name = "SimplifyIndexing" + self._simplify: Callable[[Expr], Expr] = ( + lambda index: V.graph.sizevars.simplify_with_ranges(index, var_ranges) + ) + + def load(self, name: str, index: sympy.Expr): + return self._inner.load(name, self._simplify(index)) + + def store(self, name, index, value, mode=None): + return self._inner.store(name, self._simplify(index), value, mode=mode) + + def store_reduction(self, name, index, value): + return self._inner.store_reduction(name, self._simplify(index), value) + + def index_expr(self, index, dtype): + return self._inner.index_expr(self._simplify(index), dtype) + + def value_expr(self, index, dtype): + return self._inner.value_expr(self._simplify(index), dtype) + + def check_bounds(self, index, size, lower, upper): + return self._inner.check_bounds(self._simplify(index), size, lower, upper) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/standalone_compile.py b/.venv/lib/python3.12/site-packages/torch/_inductor/standalone_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..639782b9582e9b31d220f17ce272de19bb1504d0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/standalone_compile.py @@ -0,0 +1,880 @@ +from __future__ import annotations + +import contextlib +import copy +import itertools +import logging +import os +import pickle +import shutil +from abc import ABC, abstractmethod +from contextlib import AbstractContextManager, nullcontext +from typing import Any, Literal, TYPE_CHECKING + + +DynamicShapesType = Literal["from_example_inputs", "from_tracing_context", "from_graph"] + +import torch.fx +from torch._dynamo.aot_compile_types import BundledAOTAutogradSerializableCallable +from torch._dynamo.utils import dynamo_timed +from torch._inductor.cpp_builder import normalize_path_separator +from torch._inductor.cudagraph_utils import BoxedDeviceIndex +from torch._inductor.runtime.cache_dir_utils import temporary_cache_dir +from torch._inductor.utils import BoxedBool, InputType +from torch._subclasses import FakeTensorMode +from torch._subclasses.fake_tensor import maybe_get_fake_mode +from torch.fx.experimental.symbolic_shapes import ShapeEnv +from torch.fx.graph_module import _share_torchbind_and_process_group_on_deepcopy + +from . import config +from ._functionalize_collectives import ( + _functionalize_inplace_collectives, + _unbox_process_group_torchbinds, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from torch.compiler._cache import CacheInfo + from torch.fx import GraphModule + + from .output_code import OutputCode + + +log = logging.getLogger(__name__) + + +class CompiledArtifact(ABC): + """ + CompiledArtifact class represents the inductor cache artifacts that + can be invoked in order to avoid repeated compilation. + + CompiledArtifact can be obtained by calling standalone_compile(gm, example_inputs) + to create a fresh CompiledArtifact from a GraphModule and example inputs. + + Later this CompiledArtifact can be saved to disk, either as a binary or unpacked + into the provided folder via the CompiledArtifact.save function. + + CompiledArtifact.load provides a way to create a CompiledArtifact from the + binary or unpacked data. + + Finally, the CompiledArtifact can be invoked via the __call__ method + to execute the cached artifact. + """ + + def __init__( + self, + compiled_fn: Callable[..., Any], + artifacts: tuple[bytes, CacheInfo] | None, + ): + self._compiled_fn = compiled_fn + self._artifacts = artifacts + + @abstractmethod + def __call__(self, *args: Any) -> Any: ... + + @abstractmethod + def save( + self, *, path: str, format: Literal["binary", "unpacked"] = "binary" + ) -> None: ... + + @staticmethod + def load( + *, path: str, format: Literal["binary", "unpacked"] = "binary" + ) -> CompiledArtifact: + if format == "unpacked": + # If format is unpacked, it must be a CacheCompiledArtifact + return CacheCompiledArtifact.load(path=path, format=format) + + if format != "binary": + raise AssertionError(f"expected format == 'binary', got {format}") + with open(path, "rb") as file: + from torch.utils._appending_byte_serializer import BytesReader + + from .codecache import torch_key + + result_bytes = file.read() + reader = BytesReader(result_bytes) + header = reader.read_bytes() + if header == AOTCompiledArtifact.AOT_HEADER: + if reader.read_bytes() != torch_key(): + raise AssertionError("torch_key mismatch in serialized artifact") + artifact = reader.read_bytes() + if not reader.is_finished(): + raise AssertionError("expected reader to be finished") + return AOTCompiledArtifact.deserialize(artifact) + # Otherwise, it's in the CacheCompiledArtifact format + elif header == CacheCompiledArtifact.CACHE_HEADER: + if reader.read_bytes() != torch_key(): + raise AssertionError("torch_key mismatch in serialized artifact") + key = reader.read_str() + artifact_bytes = reader.read_bytes() + if not reader.is_finished(): + raise AssertionError("expected reader to be finished") + torch.compiler.load_cache_artifacts(artifact_bytes) + return CacheCompiledArtifact._load_impl(nullcontext(), key) + else: + raise RuntimeError( + "Invalid header, expected CacheCompiledArtifact or AOTCompiledArtifact, got: " + + header.decode("utf-8") + ) + + +class CacheCompiledArtifact(CompiledArtifact): + """ + CompiledArtifact that depends on torch.compiler.save_cache_artifacts + """ + + CACHE_HEADER = bytes("CacheCompiledArtifact", "utf-8") + + def __init__( + self, + compiled_fn: Callable[..., Any], + artifacts: tuple[bytes, CacheInfo] | None, + ): + self._compiled_fn = compiled_fn + self._artifacts = artifacts + + def __call__(self, *args: Any) -> Any: + return self._compiled_fn(*args) + + def is_saveable(self) -> bool: + if self._artifacts is None: + return False + _, cache_info = self._artifacts + # 0 means nothing was saved + # >1 means multiple artifacts were saved, which is concerning + # (we only expect one) + return len(cache_info.aot_autograd_artifacts) == 1 + + def _validate_and_unpack(self) -> tuple[bytes, str]: + """Validate the cached artifact, returning ``(artifact_bytes, key)``. + + Single source of the None / empty / multiple aot_autograd_artifacts checks, + shared by ``_to_binary_bytes`` and ``save``'s unpacked branch. Messages are + neutral (not tied to ``save``) because ``_to_binary_bytes`` callers obtain the + bytes without going through ``save``. + """ + if self._artifacts is None: + raise RuntimeError("CompiledArtifact has no artifact to serialize") + artifact_bytes, cache_info = self._artifacts + if len(cache_info.aot_autograd_artifacts) == 0: + raise RuntimeError( + f"CompiledArtifact has no aot_autograd artifacts to serialize. This " + f"likely means there was something that was not serializable in the graph " + f"passed to standalone_compile. This can generally be fixed by ensuring " + f"that your model only uses constructs that are serializable. {cache_info}" + ) + if len(cache_info.aot_autograd_artifacts) > 1: + raise AssertionError( + f"CompiledArtifact has more than one aot_autograd artifact but we only " + f"expected one. {cache_info}" + ) + return artifact_bytes, cache_info.aot_autograd_artifacts[0] + + def _to_binary_bytes(self) -> bytes: + """Serialize this artifact to the in-memory ``binary`` byte format. + + Produces exactly the bytes that ``save(format="binary")`` writes to disk, so + callers that only need the bytes (rather than a file on disk) can reuse this + without going through ``save``. The byte layout is the one + ``load(format="binary")`` reads back: header, ``torch_key``, the autograd-cache + ``key`` string, then the opaque ``artifact_bytes``. + """ + artifact_bytes, key = self._validate_and_unpack() + + from torch.utils._appending_byte_serializer import BytesWriter + + from .codecache import torch_key + + writer = BytesWriter() + writer.write_bytes(CacheCompiledArtifact.CACHE_HEADER) + writer.write_bytes(torch_key()) + writer.write_str(key) + writer.write_bytes(artifact_bytes) + return writer.to_bytes() + + def save( + self, *, path: str, format: Literal["binary", "unpacked"] = "binary" + ) -> None: + with dynamo_timed("CompiledArtifact.save"): + if format == "binary": + # can't assert that it is a file since it might not exist yet + if os.path.isdir(path): + raise AssertionError(f"expected path to not be a dir: {path}") + + from torch._inductor.codecache import write_atomic + + # ``_to_binary_bytes`` is the single source of the None / empty / + # multiple aot_autograd_artifacts validation, so the binary branch + # does not repeat those checks here. + write_atomic(path, self._to_binary_bytes()) + else: + if format != "unpacked": + raise AssertionError(f"expected format == 'unpacked', got {format}") + # Same None / empty / multiple validation as the binary branch, shared via + # _validate_and_unpack; the unpacked branch needs only artifact_bytes. + artifact_bytes, _key = self._validate_and_unpack() + if os.path.exists(path): + if not os.path.isdir(path): + raise AssertionError(f"expected path to be a dir: {path}") + shutil.rmtree(path, ignore_errors=True) + + from .codecache import FxGraphCache + + with temporary_cache_dir(path): + # This function unpacks the cache artifacts to disk + loaded_cache_info = torch.compiler.load_cache_artifacts( + artifact_bytes + ) + if loaded_cache_info is None: + raise AssertionError( + "expected loaded_cache_info to not be None" + ) + # Now write all the output_code artifacts to disk so that + # they can be inspected and modified + for key in loaded_cache_info.inductor_artifacts: + subdir = FxGraphCache._get_tmp_dir_for_key(key) + if not os.path.exists(subdir): + raise AssertionError(f"expected subdir to exist: {subdir}") + for path in sorted(os.listdir(subdir)): + with open(os.path.join(subdir, path), "rb") as f: + graph = pickle.load(f) + output_file = graph.write_to_disk() + log.info("Output code written to: %s", output_file) + + @staticmethod + def _load_impl( + cache_dir_ctx: AbstractContextManager[Any], key: str + ) -> CompiledArtifact: + with ( + cache_dir_ctx, + config.patch(unsafe_skip_cache_dynamic_shape_guards=True), + ): + with torch._functorch.config.patch(strict_autograd_cache=True): + from torch._functorch._aot_autograd.autograd_cache import ( + AOTAutogradCache, + ) + + result = AOTAutogradCache._lookup( + key, + local=True, + remote=False, + args=[], + cache_info={}, + aot_config=None, + ) + + if result is None: + raise AssertionError( + "expected AOTAutogradCache lookup result to not be None" + ) + (entry, _) = result + + from .compile_fx import _CompileFxKwargs + + fx_config = _CompileFxKwargs( + cudagraphs=BoxedBool(False), + boxed_forward_device_index=BoxedDeviceIndex(0), + ) + + context = torch._guards.TracingContext(FakeTensorMode(shape_env=ShapeEnv())) + with torch._guards.tracing(context): + compiled_fn = entry.wrap_post_compile( + [], entry.sanitized_aot_config, fx_config + ) + return CacheCompiledArtifact(lambda *args: compiled_fn(list(args)), None) + + @staticmethod + def _prepare_load( + *, path: str, format: Literal["binary", "unpacked"] = "binary" + ) -> tuple[str, AbstractContextManager[Any]]: + """ + Do format specific prep and loads, return a context manager and key + """ + path = normalize_path_separator(path) + with dynamo_timed("CompiledArtifact.load"): + if format == "binary": + # can't assert that it is a file since it might not exist yet + if os.path.isdir(path): + raise AssertionError(f"expected path to not be a dir: {path}") + with open(path, "rb") as file: + artifacts = file.read() + from torch.utils._appending_byte_serializer import BytesReader + + from .codecache import torch_key + + reader = BytesReader(artifacts) + if reader.read_bytes() != torch_key(): + raise AssertionError("torch_key mismatch in serialized artifact") + key = reader.read_str() + artifact_bytes = reader.read_bytes() + if not reader.is_finished(): + raise AssertionError("expected reader to be finished") + + torch.compiler.load_cache_artifacts(artifact_bytes) + return key, nullcontext() + else: + if format != "unpacked": + raise AssertionError(f"expected format == 'unpacked', got {format}") + if not os.path.isdir(path): + raise AssertionError(f"expected path to be a dir: {path}") + autograd_cache_dir = os.path.join(path, "aotautograd") + if not os.path.isdir(autograd_cache_dir): + raise AssertionError( + f"expected autograd_cache_dir to be a dir: {autograd_cache_dir}" + ) + files = list(os.listdir(autograd_cache_dir)) + if len(files) != 1: + raise AssertionError(f"expected exactly 1 file, got {len(files)}") + key = files[0] + cache_dir_ctx = temporary_cache_dir(path) + return key, cache_dir_ctx + + @staticmethod + def load( + *, path: str, format: Literal["binary", "unpacked"] = "binary" + ) -> CompiledArtifact: + key, cache_dir_ctx = CacheCompiledArtifact._prepare_load( + path=path, format=format + ) + return CacheCompiledArtifact._load_impl(cache_dir_ctx, key) + + +class AOTCompiledArtifact(CompiledArtifact): + """ + Similar to CompiledArtifact, but the object is a single, bundled precompiled function. + This object is always a serializable callable function. + + This object is essentially a wrapper for BundledAOTAutogradSerializableCallable, which + is used by torch._dynamo.aot_compile for AOT Precompilation. + """ + + AOT_HEADER = bytes("AOTCompiledArtifact", "utf-8") + + def __init__( + self, + compiled_fn: Callable[..., Any], + ): + self.inner_fn = BundledAOTAutogradSerializableCallable(compiled_fn) + self._artifacts = ( + None # We don't need artifacts, the inner object handles everything + ) + + @staticmethod + def from_bundled_callable( + bundled_fn: BundledAOTAutogradSerializableCallable, + ) -> AOTCompiledArtifact: + return AOTCompiledArtifact(bundled_fn.compiled_fn) + + def __call__(self, *args: Any) -> Any: + return self.inner_fn(*args) + + def save( + self, *, path: str, format: Literal["binary", "unpacked"] = "binary" + ) -> None: + if format == "unpacked": + raise RuntimeError( + "AOTCompiledArtifact does not support unpacked format yet" + ) + result_bytes = self.serialize() + from torch.utils._appending_byte_serializer import BytesWriter + + from .codecache import torch_key + + writer = BytesWriter() + writer.write_bytes(AOTCompiledArtifact.AOT_HEADER) + writer.write_bytes(torch_key()) + writer.write_bytes(result_bytes) + + from torch._inductor.codecache import write_atomic + + # Save a sentinel file to indicate that this is AOT + write_atomic(path, writer.to_bytes()) + + def serialize(self) -> bytes: + return BundledAOTAutogradSerializableCallable.serialize_compile_artifacts( + self.inner_fn + ) + + @staticmethod + def deserialize(result_bytes: bytes) -> AOTCompiledArtifact: + deserialized = ( + BundledAOTAutogradSerializableCallable.deserialize_compile_artifacts( + result_bytes + ) + ) + if not isinstance(deserialized, BundledAOTAutogradSerializableCallable): + raise AssertionError( + f"expected BundledAOTAutogradSerializableCallable, got {type(deserialized)}" + ) + return AOTCompiledArtifact.from_bundled_callable(deserialized) + + @staticmethod + def load( + *, path: str, format: Literal["binary", "unpacked"] = "binary" + ) -> CompiledArtifact: + if format == "unpacked": + raise RuntimeError( + "AOTCompiledArtifact does not support unpacked format yet" + ) + with open(path, "rb") as file: + from torch.utils._appending_byte_serializer import BytesReader + + from .codecache import torch_key + + result_bytes = file.read() + reader = BytesReader(result_bytes) + header = reader.read_bytes() + if header != AOTCompiledArtifact.AOT_HEADER: + raise AssertionError("expected AOTCompiledArtifact header") + if reader.read_bytes() != torch_key(): + raise AssertionError("torch_key mismatch in serialized artifact") + artifact = reader.read_bytes() + if not reader.is_finished(): + raise AssertionError("expected reader to be finished") + return AOTCompiledArtifact.deserialize(artifact) + + +def _resolve_ignore_shape_env(dynamic_shapes: DynamicShapesType): + # tells compile_fx to ignore the shape_envs on the ambient context + # and the graph_module. + return dynamic_shapes == "from_example_inputs" + + +def _resolve_fake_mode( + gm: GraphModule, + dynamic_shapes: DynamicShapesType, + fake_mode: FakeTensorMode | None = None, +) -> FakeTensorMode: + if dynamic_shapes == "from_example_inputs": + if fake_mode is not None: + if fake_mode.shape_env is None: + raise ValueError( + "standalone_compile requires `fake_mode` to have a ShapeEnv " + 'when `dynamic_shapes="from_example_inputs"`.' + ) + return fake_mode + return FakeTensorMode(shape_env=ShapeEnv()) + elif fake_mode is not None: + raise ValueError( + "standalone_compile only supports passing `fake_mode` when " + '`dynamic_shapes="from_example_inputs"`.' + ) + elif dynamic_shapes == "from_tracing_context": + # Reuse fake_mode from the TracingContext. + # NB: The TracingContext only exists if we're currently in a torch.compile backend. + context = torch._guards.TracingContext.get() + if context.fake_mode is None: + raise AssertionError("expected TracingContext.fake_mode to not be None") + return context.fake_mode + elif dynamic_shapes == "from_graph": + # Strategy: find a FakeTensor in the graph output, grab its FakeTensorMode. + # The graph passed to standalone_compile must be an Inductor-approved graph, + # which means that there is at least one Tensor output and the output node + # contains a flat list of Tensors. + last_node = next(iter(reversed(gm.graph.nodes))) + if last_node.op != "output": + raise AssertionError( + f"expected last node op == 'output', got {last_node.op}" + ) + if len(last_node.args) != 1: + raise AssertionError( + f"expected last node to have 1 arg, got {len(last_node.args)}" + ) + + # If gm came from Dynamo, then last_node.args[0] is always a list, + # even in single-Tensor returns. + # + # It's possible to get into a situation where last_node.args[0] + # is a Node (and not a list!). This happens if you call split_module + # on the graph. We allow for this case since it is common. + nodes = ( + [last_node.args[0]] + if isinstance(last_node.args[0], torch.fx.Node) + else last_node.args[0] + ) + # Find a FakeTensor to recover its FakeTensorMode. This resolver was written when + # standalone_compile was only ever fed Dynamo/AOT graphs, which return a flat list + # of real Tensor outputs and stash the fake under "example_value". precompile now + # feeds make_fx graphs too, and those break both assumptions: make_fx stashes the + # fake under "val" (not "example_value"), and the traced fn's own return value is + # kept as an output leaf -- so when fn calls .backward() (which returns None) that + # None sits in the output list as a plain non-Node entry. So skip non-Node output + # entries (the old code called .meta on the None and crashed), check both metadata + # keys, and fall back to scanning every node since a make_fx fake may live only on + # an interior node. maybe_get_fake_mode also unwraps a traceable wrapper subclass. + output_nodes = [n for n in nodes if isinstance(n, torch.fx.Node)] + for node in itertools.chain(output_nodes, gm.graph.nodes): + for key in ("example_value", "val"): + maybe_fake_mode = maybe_get_fake_mode(node.meta.get(key)) + if maybe_fake_mode is not None: + return maybe_fake_mode + + return FakeTensorMode(shape_env=ShapeEnv()) + else: + raise ValueError( + f"standalone_compile got unsupported `dynamic_shapes` value: dynamic_shapes={dynamic_shapes}." + ) + + +@contextlib.contextmanager +def _standalone_context( + gm: GraphModule, + dynamic_shapes: DynamicShapesType, + aot: bool, + fake_mode: FakeTensorMode | None = None, +): + from torch.compiler._cache import CacheArtifactManager + + resolved_fake_mode = _resolve_fake_mode(gm, dynamic_shapes, fake_mode) + tracing_context = torch._guards.TracingContext(resolved_fake_mode) + with ( + torch._guards.tracing(tracing_context), + CacheArtifactManager.with_fresh_cache(), + config.patch("triton.autotune_at_compile_time", True), + torch._functorch.config.patch( + { + "bundled_autograd_cache": aot, + # Standalone artifacts are saved immediately after compile_fx + # returns. Training graphs normally lower the backward lazily on + # first backward(), so force it while the artifact recorder is + # still active. + "force_non_lazy_backward_lowering": True, + } + ), + ): + yield + + +def standalone_compile( + gm: GraphModule, + example_inputs: Sequence[InputType], + *, + dynamic_shapes: DynamicShapesType, + options: Any, + aot: bool = False, # AOT mode, which uses BundledAOTAutogradCache + donate_graph_module: bool = False, + fake_mode: FakeTensorMode | None = None, +) -> CompiledArtifact: + """ + Implementation of torch.inductor.standalone_compile + """ + from .compile_fx import compile_fx + + ignore_shape_env = _resolve_ignore_shape_env(dynamic_shapes) + with _standalone_context(gm, dynamic_shapes, aot, fake_mode): + # compile_fx takes ownership of gm and may mutate it on cache miss. + # Deepcopy first so the rewrites below land on the owned copy rather + # than the caller's gm. The gm may carry a non-pickleable torchbind + # ProcessGroup (or, after a previous unbox, a Python + # ``dist.ProcessGroup``); smuggle it through deepcopy as a shared + # reference instead of crashing. + if not donate_graph_module: + with _share_torchbind_and_process_group_on_deepcopy(): + gm = copy.deepcopy(gm) + # ``make_fx`` traces ``dist.*`` collectives as opaque ``c10d.{op}_`` + # calls. Inductor's collective machinery only recognizes the + # ``_c10d_functional.{op}`` + ``wait_tensor`` form, so rewrite here + # before compile_fx runs. Also unbox any torchbind ProcessGroup + # attrs into Python ``dist.ProcessGroup`` so the runtime collective + # op accepts them (raw torchbind is rejected). + gm = _functionalize_inplace_collectives(gm) + gm = _unbox_process_group_torchbinds(gm) + compiled_fn = compile_fx( + gm, example_inputs, ignore_shape_env=ignore_shape_env, **options + ) + if not callable(compiled_fn): + raise AssertionError("expected compiled_fn to be callable") + if aot: + if not hasattr(compiled_fn, "serialize"): + raise RuntimeError( + "Compiled function should have serialize method when aot=True" + ) + return AOTCompiledArtifact(compiled_fn) + artifacts = torch.compiler.save_cache_artifacts() + if artifacts is None: + log.warning( + "standalone_compile artifact generation failed, cannot save. " + "Run with TORCH_LOGS=+torch._inductor.codecache to identify the problem" + ) + + return CacheCompiledArtifact(compiled_fn, artifacts) + + +class NoRunnableInductorModuleError(RuntimeError): + """Raised by ``compile_to_python`` when the graph yields no runnable Inductor + output module -- it has no compute to lower (returns inputs/constants unchanged), + so the compiled artifact carries no output-module source. Callers (e.g. + torch.compiler.precompile) convert this to a clear user-facing error suggesting an + alternative. + """ + + +def _runnable_source(compiled_graph: OutputCode) -> str: + """Return the Inductor output-module source for a compiled inner graph. + + ``compile_fx_inner`` returns a ``CompiledFxGraph`` that carries the wrapper-module + source as ``source_code``. A graph with no compute (returns inputs/constants + unchanged) short-circuits to a boxed passthrough with no such source, which we + surface as ``NoRunnableInductorModuleError``. + """ + source = getattr(compiled_graph, "source_code", None) + if not source: + raise NoRunnableInductorModuleError( + "the compiled graph produced no runnable Inductor output module: it has no " + "compute to lower (returns inputs/constants unchanged)." + ) + return source + + +def _placeholder_fake_inputs(gm: GraphModule) -> list[Any]: + """Return the fake ``val`` metadata of ``gm``'s placeholders -- the compile-time input + contract for a post-AOTAutograd graph. These fake tensors already carry the + AOTAutograd-decided static/symbolic shapes under one consistent ``FakeTensorMode``, so + lowering against them (rather than re-fakifying real ``example_inputs``) preserves + symbolic dims. A placeholder without ``val`` means ``gm`` was not traced under a + ``FakeTensorMode``, violating the post-AOTAutograd precondition.""" + fake_inputs = [] + for node in gm.graph.nodes: + if node.op != "placeholder": + continue + if "val" not in node.meta: + raise RuntimeError( + "compile_to_python placeholder has no fake ``val`` metadata; expected a " + "post-AOTAutograd graph traced under a FakeTensorMode." + ) + fake_inputs.append(node.meta["val"]) + return fake_inputs + + +def _acceleration_cache_bytes( + artifacts: tuple[bytes, CacheInfo] | None, +) -> bytes | None: + """Return the opaque cache-artifacts bundle that accelerates a later ``load_from_python``, + or ``None`` when nothing cacheable was produced (no compute) or caches are disabled. + + This is a PURE ACCELERATOR, not a serialized callable. It is the raw + ``save_cache_artifacts()`` bundle (FxGraph entry + any triton/autotune cache); + ``load_from_python`` feeds it to ``load_cache_artifacts`` so that exec'ing the emitted + ``python_code`` loads the precompiled kernels instead of JIT-compiling them. The + ``python_code`` runs correctly without it, so it carries no key/header framing -- it is + handed straight back to ``load_cache_artifacts``. + """ + if artifacts is None: + log.debug("no cache artifacts captured; no acceleration cache") + return None + artifact_bytes, _ = artifacts + return artifact_bytes + + +def load_from_python( + python_code: str, cache: bytes | None = None +) -> Callable[..., Any]: + """Load the module emitted by ``compile_to_python`` into a runnable ``call``. + + ``python_code`` is self-contained: exec'ing it defines ``call`` and JIT-compiles the + inlined kernels on first use, so it runs with ``cache=None``. When ``cache`` (the + accelerator bundle from ``compile_to_python``) is provided, it is loaded FIRST so the + kernels load their precompiled binaries instead of recompiling -- a pure speedup, never + a correctness requirement. Mirrors ``compile_to_python``: (python_code, cache) in, + runnable ``call`` out. + """ + if cache is not None: + torch.compiler.load_cache_artifacts(cache) + namespace: dict[str, Any] = {"__name__": "__compile_to_python__"} + exec(compile(python_code, "", "exec"), namespace) + call = namespace.get("call") + if not callable(call): + raise RuntimeError( + "compile_to_python module did not define a callable ``call``." + ) + return call + + +def compile_to_python( + gm: GraphModule, + example_inputs: Sequence[InputType], + *, + options: dict[str, Any] | None = None, +) -> tuple[str, bytes | None]: + """Compile ``gm`` and return ``(inner_python, cache)`` -- the INNER half of the + backend contract behind ``torch.compiler.precompile``. + + This is an INTERNAL layered-contract entry point, not an end-user API. End users + should call ``torch.compiler.precompile``; this function only emits the inductor + piece of the artifact and assumes its caller (the AOT layer) wraps it. It lives in + ``torch._inductor`` (a private, leading-underscore module), so it is exposed for + the AOT layer to import, not as a stable public surface. + + ``inner_python`` is the Inductor output module exposing ``call(args) -> outs`` + for the post-AOTAutograd inner graph (dense, functionalized). It is the inductor + piece only: it carries NO prelude/epilogue (subclass flatten/unflatten, input- + mutation copy-back, output-alias regen, grad disabling). Those belong to the AOT + layer -- a companion change in ``torch._functorch.aot_autograd`` wraps this and + composes AOTAutograd's codegen'd runtime wrappers around the result. + Callers must run ``call`` under ``torch.no_grad()`` (the kernels use out= ops). + + Caller preconditions (this layer does not re-derive them): + + - ``gm`` is a post-AOTAutograd dense, functionalized inner graph (the dense + forward/backward AOTAutograd hands to its inductor backend), NOT a raw Dynamo + or pre-dispatch graph still carrying subclasses or autograd. Crucially it must be + DECOMPOSED against the inductor decomposition table: this function drives the + inductor codegen entry point directly, and inductor lowering asserts "both a + fallback and a decomp for same op" on an undecomposed op (e.g. ``aten._softmax``). + - Placeholders carry fake ``val`` metadata (the graph was traced under a + ``FakeTensorMode``); those fake tensors are the compile-time input contract. + - ``gm`` lowers to a runnable inductor output module. A graph with no compute + raises ``NoRunnableInductorModuleError``. + + The compile lowers against the placeholders' fake ``val`` metadata, whose + static/symbolic shapes AOTAutograd already resolved, so the graph is the source of + truth for shapes -- there is no ``dynamic_shapes`` knob. ``example_inputs`` is accepted + for the backend-contract signature but is not re-fakified for the compile itself. + + ``options`` is an optional inductor config-override dict (``None`` means no + overrides), the same shape as ``torch._inductor.compile``'s ``options``. The + keys are inductor config names: they are merged into the ``config.patch`` + block this function already wraps the compile in, so they take effect as + config rather than being forwarded as ``compile_fx`` kwargs. The two + capture-critical pins below (``benchmark_harness``, ``cpp_wrapper``) always win + over a conflicting user option, since the source-capture contract depends on + them and a caller cannot be allowed to break the emitted module. + + ``inner_python`` is self-contained: exec'ing it JIT-compiles the inlined kernels on + first use, so it runs with no cache. ``cache`` is a PURE ACCELERATOR -- the opaque + ``save_cache_artifacts()`` bundle; passing it to ``load_from_python`` warms the kernel + caches so exec loads the precompiled binaries instead of recompiling. It is ``None`` + when the graph produced no cacheable module (no compute) or caches are disabled + (``force_disable_caches`` or ``fx_graph_cache=False``); ``inner_python`` still runs. + + ``inner_python`` is read off the ``CompiledFxGraph`` that ``compile_fx_inner`` + returns -- Inductor stashes the wrapper-module source on it as ``source_code`` -- so + it reflects the FINAL selected module on a cold compile, a warm cache restore, or with + caches disabled. No process-global codegen hook is involved, and the throwaway + max_autotune benchmark lowerings (which compile to their own modules during + autotuning) never become the returned graph, so nothing needs to be filtered out. + """ + if not isinstance(gm, torch.fx.GraphModule): + raise TypeError( + f"compile_to_python expects a post-AOTAutograd torch.fx.GraphModule, " + f"got {type(gm)}. This is an internal entry point wrapped by a higher AOT " + f"layer and is not meant to be called directly." + ) + # The experimental TORCHINDUCTOR_FX_COMPILE_MODE=async+/progressive+ schemes make + # compile_fx return an _AsyncOutputCode/_ProgressiveOutputCode that carries only + # _boxed_call and never surfaces the wrapper ``source_code`` this contract reads off. + # These are module-level globals resolved from the env at import time, not + # config-patchable like the pins below, so detect them up front and fail with a + # distinct error instead of the no-compute NoRunnableInductorModuleError -- the graph + # is runnable, the async scheme just did not surface its source. + from torch._inductor import compile_fx as _compile_fx + + if _compile_fx.fx_compile_async or _compile_fx.fx_compile_progressive: + raise RuntimeError( + "compile_to_python needs synchronous source capture and does not yet " + "support TORCHINDUCTOR_FX_COMPILE_MODE=async+/progressive+ (the async " + "output code does not surface the wrapper source)." + ) + # Treat ``options`` as inductor config overrides and fold them into the same + # ``config.patch`` we wrap the compile in. ``keep_static_cubin_raw`` is defaulted True + # (BEFORE user options, so a caller can still trade it off for a smaller cache): its + # default False nulls the static-launcher raw cubin and relies on the cubin FILE being + # on disk, which holds for a same-machine warm cache but NOT the cold/cross-container + # load this cache targets -- keeping it lets ``load_from_python`` rehydrate the cubin + # from the bundle so the static CUDA launcher survives a fresh-dir load instead of + # silently falling back to the slower dynamic launch. The two output pins are applied + # AFTER the user options so they override any conflicting key: benchmark_harness=False + # keeps the emitted module runnable (no get_args()/benchmark_compiled_module()/__main__), + # and cpp_wrapper=False keeps it a python wrapper (the C++ backend emits a C++ ``call`` + # we cannot inline). A caller must not be able to break either. + config_patches: dict[str, Any] = {"keep_static_cubin_raw": True} + if options is not None: + config_patches.update(options) + config_patches.update( + { + "benchmark_harness": False, + "cpp_wrapper": False, + } + ) + # ``gm`` is a POST-AOTAutograd inner graph: already functionalized and decomposed + # against the inductor decomposition table. That precondition lets us drive the + # inductor codegen entry point (``compile_fx_inner``) DIRECTLY on the dense graph + # rather than re-entering AOTAutograd via ``standalone_compile``. Re-entry would only + # re-run decomposition -- a no-op on an already-decomposed graph -- and hand back an + # AOTAutograd-level cache artifact that belongs to the layer above; driving the inner + # compile keeps this at the inductor layer and yields the accelerator cache bundle that + # ``_acceleration_cache_bytes`` returns. (If ``gm`` is NOT decomposed against the + # inductor table, inductor lowering asserts "both a fallback and a decomp for same op" + # -- the precondition is load-bearing, not defensive.) + from torch._guards import detect_fake_mode, tracing, TracingContext + from torch.compiler._cache import CacheArtifactManager + + from .compile_fx import compile_fx_inner + from .virtualized import V + + # Own a copy: the collective rewrites and inductor may mutate the graph, and ``gm`` may + # carry a non-pickleable torchbind ProcessGroup smuggled through deepcopy as a shared + # reference (mirrors ``standalone_compile``). ``make_fx`` traces ``dist.*`` collectives + # as opaque ``c10d.{op}_`` calls; rewrite them to the ``_c10d_functional.{op}`` + + # ``wait_tensor`` form inductor recognizes and unbox torchbind ProcessGroups. + with _share_torchbind_and_process_group_on_deepcopy(): + gm = copy.deepcopy(gm) + gm = _functionalize_inplace_collectives(gm) + gm = _unbox_process_group_torchbinds(gm) + + # Lower against the placeholders' fake ``val`` metadata (the compile-time input + # contract, carrying the graph's static/symbolic shapes under one FakeTensorMode) + # rather than re-fakifying ``example_inputs``, which are real and would drop symbolic + # dims. A post-AOTAutograd graph's shapes are already baked into this metadata, so + # there is no separate dynamic-shapes knob. + fake_inputs = _placeholder_fake_inputs(gm) + fake_mode = detect_fake_mode(fake_inputs) + if fake_mode is None: + raise RuntimeError( + "compile_to_python could not detect a FakeTensorMode on the graph's " + "placeholders; expected a post-AOTAutograd graph traced under one." + ) + # no_grad pins the inference path; autotune_at_compile_time keeps the emitted source + # self-contained (autotuning resolved at compile, not deferred to runtime). The fresh + # CacheArtifactManager isolates the cache bundle ``_acceleration_cache_bytes`` returns. + with ( + torch.no_grad(), + config.patch(config_patches), + config.patch("triton.autotune_at_compile_time", True), + tracing(TracingContext(fake_mode)), + V.set_fake_mode(fake_mode), + CacheArtifactManager.with_fresh_cache(), + ): + compiled_graph = compile_fx_inner( + gm, + fake_inputs, + static_input_idxs=(), + cudagraphs=BoxedBool(False), + is_inference=True, + boxed_forward_device_index=BoxedDeviceIndex(None), + ) + artifacts = torch.compiler.save_cache_artifacts() + inner_python = _runnable_source(compiled_graph) + cache = _acceleration_cache_bytes(artifacts) + return inner_python, cache + + +def autograd_cache_key( + graph, + example_inputs, + dynamic_shapes: DynamicShapesType, + aot: bool = False, # AOT mode, which uses BundledAOTAutogradCache + fake_mode: FakeTensorMode | None = None, +): + from . import compile_fx + + ignore_shape_env = _resolve_ignore_shape_env(dynamic_shapes) + with _standalone_context(graph, dynamic_shapes, aot, fake_mode): + return compile_fx.autograd_cache_key( + graph, + example_inputs, + ignore_shape_env=ignore_shape_env, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/stream_constants.py b/.venv/lib/python3.12/site-packages/torch/_inductor/stream_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..40ca19946174609025dbe350a0ff794daaea0dc4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/stream_constants.py @@ -0,0 +1,5 @@ +"""Constants for CUDA stream naming in Inductor codegen.""" + +DEFAULT_STREAM: str = "default_stream" +DEFAULT_STREAM_IDX: int = 0 +STREAM_NAME_TEMPLATE: str = "stream{stream_idx:d}" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/stream_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/stream_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b85d45d429eb45605ee366a8cecee54ce1a0ab23 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/stream_utils.py @@ -0,0 +1,120 @@ +"""Stream utilities for Inductor codegen.""" + +from __future__ import annotations + +import functools +from typing import TYPE_CHECKING + +from torch._inductor.stream_constants import ( + DEFAULT_STREAM, + DEFAULT_STREAM_IDX, + STREAM_NAME_TEMPLATE, +) + + +if TYPE_CHECKING: + import torch + + +__all__ = [ + "AOTI_SUPPORTED_STREAM_OP_NAMES", + "AOTI_UNSUPPORTED_STREAM_OP_REASONS", + "DEFAULT_STREAM", + "DEFAULT_STREAM_IDX", + "STREAM_NAME_TEMPLATE", + "get_raw_stream_name", + "get_stream_name", +] + + +AOTI_SUPPORTED_STREAM_OP_NAMES: dict[str, str] = { + "torch.ops.streams.record_event.default": "record_event", + "torch.ops.streams.wait_event.default": "wait_event", + # A targeted single-event host wait (cudaEventSynchronize); required by e.g. + # pinned non-blocking copies. Unlike synchronize_stream/device, it does not + # block the whole stream/device, so it is safe to emit inside an AOTI Run(). + "torch.ops.streams.synchronize_event.default": "synchronize_event", +} + + +AOTI_UNSUPPORTED_STREAM_OP_REASONS: dict[str, str] = { + "torch.ops.streams.synchronize_stream.default": ( + "Host-blocking sync ops are not supported inside an AOTI Run(). " + "Use record_event + wait_event for device-side ordering instead." + ), + "torch.ops.streams.synchronize_device.default": ( + "Host-blocking device synchronization is not supported inside an AOTI Run()." + ), + "torch.ops.streams.wait_stream.default": ( + "wait_stream is not supported in AOTI cpp_wrapper. Use explicit " + "record_event on the waited-on stream + wait_event on the waiting stream." + ), +} + + +@functools.lru_cache +def get_stream_name(stream_idx: int) -> str: + """Generate CUDA Stream name from stream index number. + + Args: + stream_idx: Non-negative index number. 0 refers to the default stream, others refer to side + streams. + """ + if stream_idx == 0: + return DEFAULT_STREAM + else: + return STREAM_NAME_TEMPLATE.format(stream_idx=stream_idx) + + +@functools.lru_cache +def _raw_stream_name_for_device(device_idx: int) -> str: + return f"raw_stream{device_idx}" + + +def get_raw_stream_name(device_idx: int) -> str: + """Generate variable name for a raw stream handle on the given device.""" + # Under compile-on-one-rank the wrapper must be byte-identical across ranks, so the + # stream variable name cannot carry a rank-specific device index. + from torch.fx.experimental.proxy_tensor import _coor_enabled + + if _coor_enabled(): + return "raw_stream" + return _raw_stream_name_for_device(device_idx) + + +# [device-as-parameter] Name of the function-local variable holding the runtime current +# device index under compile-on-one-rank, so generated code is byte-identical across ranks. +COOR_DEVICE_IDX_VAR = "_coor_device_idx" + + +def coor_device_str(device: torch.device | None) -> str: + """Device string to emit into generated code (benchmark and autotune harnesses). + + Under compile-on-one-rank drop the index (``cuda:0`` -> ``cuda``) so the emitted text + is rank-identical and its tensors land on the running rank's current device. + """ + from torch.fx.experimental.proxy_tensor import _coor_enabled + + if _coor_enabled() and device is not None: + return device.type + return str(device) + + +def coor_benchmark_device_idx(device_idx: int) -> tuple[str | None, int | str]: + """(preamble line, index token) for a Triton kernel's benchmark harness. + + The harness is emitted into the kernel's own source, which is what the kernel hash + covers, so under compile-on-one-rank it must resolve the device at run time rather + than bake a rank-specific index -- otherwise kernels are not rank-identical whenever + ``config.benchmark_kernel`` is on. The preamble line (when not None) must be emitted + inside the harness function before the returned token is used. + """ + from torch.fx.experimental.proxy_tensor import _coor_enabled + + if not _coor_enabled(): + return None, device_idx + + from torch._inductor.virtualized import V + + expr = V.graph.device_ops.current_device_idx_expr() + return f"{COOR_DEVICE_IDX_VAR} = {expr}", COOR_DEVICE_IDX_VAR diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/subgraph_lowering.py b/.venv/lib/python3.12/site-packages/torch/_inductor/subgraph_lowering.py new file mode 100644 index 0000000000000000000000000000000000000000..6f439918573fe23dc37a6903a00d981c1e8d8704 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/subgraph_lowering.py @@ -0,0 +1,230 @@ +"""Utilities for lowering subgraphs used by higher order operators""" + +import functools +import operator +from collections.abc import Callable, Generator +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Any, cast, TypeVar +from typing_extensions import ParamSpec + +import sympy + +import torch +from torch.utils._ordered_set import OrderedSet + +from . import ir +from .exc import SubgraphLoweringException +from .graph import GraphLowering +from .ops_handler import OpsHandler, SimpleCSEHandler +from .virtualized import ops, V, WrapperHandler + + +T = TypeVar("T") +_P = ParamSpec("_P") + +OpOverload = torch._ops.OpOverload +LoweringDict = dict[OpOverload | str, Callable[..., Any]] +TargetType = Callable[..., Any] | str + + +class PointwiseSubgraphLowering(torch.fx.Interpreter): + """ + Lowers a pointwise subgraph to a single set of buffers with a separate + lowering object. Errors if buffers are created unexpectedly + """ + + graph_outputs: list[ir.IRNode] | None + root_graph: GraphLowering + _current_op: TargetType | None + # For backwards of buffer_grads with scatters we allow mutations + allowed_mutations: OrderedSet[OpOverload] | None + additional_lowerings: LoweringDict | None + buffers: list[ir.Buffer] + mutated_buffers: OrderedSet[str] + + def __init__( + self, + gm: torch.fx.GraphModule, + root_graph_lowering: GraphLowering, + allowed_mutations: OrderedSet[OpOverload] | None = None, + additional_lowerings: LoweringDict | None = None, + ) -> None: + super().__init__(gm) + self.graph_outputs = None + self.root_graph = root_graph_lowering + self.allowed_mutations = allowed_mutations + self.additional_lowerings = additional_lowerings + self._current_op = None + + # Used to track buffers created during lowering + self.mutated_buffers = OrderedSet() + self.buffers = [] + + @contextmanager + def _op_context(self, op: TargetType) -> Generator[None, None, None]: + """Set which op is being processed in call function to know if we can mutate buffers""" + previous = self._current_op + self._current_op = op + try: + yield + finally: + self._current_op = previous + + def _approved_mutator(self) -> bool: + return ( + self.allowed_mutations is not None + and self._current_op in self.allowed_mutations + ) + + def mark_buffer_mutated(self, name: str) -> None: + if self._approved_mutator(): + self.mutated_buffers.add(name) + else: + raise SubgraphLoweringException( + f"Buffer mutation detected during lowering of {self._current_op}. " + "Buffer mutations are only allowed in approved mutation ops. " + "This is an error in the lowering of the subgraph, please file a bug report." + ) + + def register_buffer(self, buffer: ir.Buffer, *, set_name: bool = False) -> str: + if self._approved_mutator(): + name = self.root_graph.register_buffer(buffer, set_name=set_name) + return name + else: + raise SubgraphLoweringException( + "Buffers cannot be created while lowering a pointwise subgraph. " + "This could be for a good reason (e.g. you're calling an op we can't codegen as a pointwise op), " + "but it could also be a bug. Please file a bug report if you think this should be supportable." + ) + + def __getattr__(self, name: str) -> Any: + return getattr(self.root_graph, name) + + def call_function( + self, + target: TargetType, + args: Any, + kwargs: dict[str, Any], + ) -> Any: + from .lowering import lowerings + + with self._op_context(target): + if target is operator.getitem and isinstance(args[0], (list, tuple, dict)): + return super().call_function(target, args, kwargs) + + # These takes precedence over the main lowerings + if self.additional_lowerings is not None: + if target in self.additional_lowerings: + if not isinstance(target, OpOverload): + raise AssertionError( + f"expected target to be an OpOverload, got {type(target)}" + ) + return self.additional_lowerings[target](*args, **kwargs) + + if target not in lowerings: + raise SubgraphLoweringException( + f"{target} not supported in subgraph, (missing lowering)" + ) + return lowerings[target](*args, **kwargs) + + def output(self, target: str, args: tuple[Any], kwargs: dict[str, Any]) -> None: # type: ignore[override] + if len(args) != 1: + raise AssertionError(f"expected exactly one output arg, got {len(args)}") + self.graph_outputs = args[0] + + +@dataclass +class InputDescriptor: + dtype: torch.dtype + device: torch.device + + +SubgraphInput = InputDescriptor | int | sympy.Basic + + +class TracingOpsHandler(WrapperHandler): + def __init__(self, tracer: torch.fx.Tracer, num_inputs: int) -> None: + parent = tracer.create_proxy("placeholder", "ops", (), {}) + super().__init__(cast(OpsHandler[Any], parent)) + self.tracer = tracer + + self.placeholders = [ + self.tracer.create_proxy("placeholder", f"input{i}", (), {}) + for i in range(num_inputs) + ] + + def placeholder(self, idx: int) -> torch.fx.Proxy: + return self.placeholders[idx] + + def output(self, *args: tuple[object]) -> None: + self.tracer.create_node( + "output", "output", (tuple(self.tracer.create_arg(a) for a in args),), {} + ) + + +def lower_pointwise_subgraph( + subgraph: ir.Subgraph, inputs: list[SubgraphInput] +) -> Callable[_P, Any]: + # Lower subgraph to ir.Pointwise nodes + def fake_inner_fn(loop_idx: int, input_idx: int) -> ir.Expr | ir.TensorBox | None: + return ops.placeholder(input_idx) + + graph_inputs = [] + for i, desc in enumerate(inputs): + if isinstance(desc, InputDescriptor): + graph_inputs.append( + ir.Pointwise.create( + device=desc.device, + dtype=desc.dtype, + inner_fn=functools.partial(fake_inner_fn, input_idx=i), + ranges=[], + ) + ) + else: + graph_inputs.append(desc) + gm = subgraph.graph_module + pw_subgraph = PointwiseSubgraphLowering(gm, root_graph_lowering=V.graph) + with V.set_graph_handler(pw_subgraph): # type: ignore[arg-type] + pw_subgraph.run(*graph_inputs) + + # Combine multiple pointwise computations into a single graph module + # Do this by tracing through each individually and doing CSE + tracer = torch.fx.Tracer() + tracer.graph = torch.fx.Graph(tracer_cls=tracer.__class__) + trace_ops = SimpleCSEHandler(TracingOpsHandler(tracer, len(inputs))) + if pw_subgraph.graph_outputs is None: + raise AssertionError("expected pw_subgraph.graph_outputs to be set") + + with V.set_ops_handler(trace_ops): + output_irs = [] + + for out_var in pw_subgraph.graph_outputs: + if not isinstance(out_var, ir.TensorBox): + raise AssertionError(type(out_var)) + if out_var.get_size() != []: + raise AssertionError( + f"expected scalar output (empty size), got {out_var.get_size()}" + ) + if not isinstance(out_var.data, ir.StorageBox): + raise AssertionError( + f"expected out_var.data to be a StorageBox, got {type(out_var.data)}" + ) + if not isinstance(out_var.data.data, ir.Pointwise): + raise AssertionError( + f"expected out_var.data.data to be a Pointwise, got {type(out_var.data.data)}" + ) + + idx = () + ir_out = out_var.data.data.inner_fn(idx) + + output_irs.append(ir_out) + + ops.output(*output_irs) + + lowered_gm = torch.fx.GraphModule({}, tracer.graph) + + def inner_fn(*args: _P.args, **kwargs: _P.kwargs) -> Any: + return lowered_gm(V.get_ops_handler(), *args, **kwargs) + + return inner_fn diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/template_heuristics/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/template_heuristics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ff8f3d9a3b1231b09930de56e1319233acefc6e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/template_heuristics/__init__.py @@ -0,0 +1,48 @@ +# Backward-compatibility shim. +# This package has been moved to torch._inductor.heuristics.template. +# Keep every old import path working -- both +# from torch._inductor.template_heuristics import +# and +# import torch._inductor.template_heuristics. +# -- by importing the moved submodules once and aliasing them into this +# package via sys.modules so the same module objects are reused (this avoids +# duplicate imports and double registration of heuristics). +# These re-exports will be removed in a future release. +import sys + +from torch._inductor.heuristics.template import ( + aten, + base, + contiguous_mm, + cutedsl, + decompose_k, + flex_gemm, + gemm, + nv_universal_gemm, + params, + registry, + tlx, + triton, + triton_addmm, +) +from torch._inductor.heuristics.template.registry import get_template_heuristic + + +for _name in ( + "aten", + "base", + "contiguous_mm", + "cutedsl", + "decompose_k", + "flex_gemm", + "gemm", + "nv_universal_gemm", + "params", + "registry", + "tlx", + "triton", + "triton_addmm", +): + sys.modules[f"{__name__}.{_name}"] = globals()[_name] + +del sys, _name diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/template_heuristics/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/template_heuristics/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44e42d8f2700362feefc6498b16be60e86d3c6dd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/template_heuristics/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/test_case.py b/.venv/lib/python3.12/site-packages/torch/_inductor/test_case.py new file mode 100644 index 0000000000000000000000000000000000000000..9b65101b5d5c0d93d2d3dabdf8cfb11702194dc5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/test_case.py @@ -0,0 +1,50 @@ +import contextlib +import os + +from torch._dynamo.test_case import ( + run_tests as dynamo_run_tests, + TestCase as DynamoTestCase, +) +from torch._functorch import config as functorch_config +from torch._inductor import config +from torch._inductor.utils import fresh_cache + + +def run_tests(needs: str | tuple[str, ...] = ()) -> None: + dynamo_run_tests(needs) + + +class TestCase(DynamoTestCase): + """ + A base TestCase for inductor tests. Enables FX graph caching and isolates + the cache directory for each test. + """ + + def setUp(self) -> None: + super().setUp() + self._inductor_test_stack = contextlib.ExitStack() + self._inductor_test_stack.enter_context( + functorch_config.patch( + { + "enable_autograd_cache": True, + } + ) + ) + + if ( + "TORCHINDUCTOR_FX_GRAPH_CACHE" not in os.environ + and "TORCHINDUCTOR_FX_GRAPH_CACHE_DEFAULT" not in os.environ + ): + self._inductor_test_stack.enter_context( + config.patch({"fx_graph_cache": True}) + ) + + if ( + os.environ.get("INDUCTOR_TEST_DISABLE_FRESH_CACHE") != "1" + and os.environ.get("TORCH_COMPILE_DEBUG") != "1" + ): + self._inductor_test_stack.enter_context(fresh_cache()) + + def tearDown(self) -> None: + super().tearDown() + self._inductor_test_stack.close() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/test_operators.py b/.venv/lib/python3.12/site-packages/torch/_inductor/test_operators.py new file mode 100644 index 0000000000000000000000000000000000000000..bbdcf89d0ef866bec01114953bce4dfb379628e9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/test_operators.py @@ -0,0 +1,29 @@ +from typing import Any + +import torch.library +from torch import Tensor +from torch.autograd import Function + + +_test_lib_def = torch.library.Library("_inductor_test", "DEF") +_test_lib_def.define("realize(Tensor self) -> Tensor", tags=torch.Tag.pt2_compliant_tag) + +_test_lib_impl = torch.library.Library("_inductor_test", "IMPL") +for dispatch_key in ("CPU", "CUDA", "MPS", "Meta"): + _test_lib_impl.impl("realize", lambda x: x.clone(), dispatch_key) + + +class Realize(Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx: object, x: Tensor) -> Tensor: + return torch.ops._inductor_test.realize(x) + + @staticmethod + # types need to stay consistent with _SingleLevelFunction + def backward(ctx: Any, *grad_output: Any) -> Any: + return grad_output[0] + + +def realize(x: Tensor) -> Tensor: + return Realize.apply(x) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/tiling_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/tiling_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a39c256b4e720ba613af8f69bdf1eb1c695edf50 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/tiling_utils.py @@ -0,0 +1,952 @@ +import dataclasses +import itertools +from collections import Counter, defaultdict +from collections.abc import Callable, Sequence +from typing import Any, Literal, overload, TYPE_CHECKING, TypeVar, Union + +import sympy + +import torch +from torch._inductor.dependencies import index_vars_no_squeeze, ReadWrites +from torch._inductor.utils import sympy_product, sympy_subs +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import Identity +from torch.utils._sympy.solve import try_solve +from torch.utils._sympy.symbol import symbol_is_type, SymT + +from .virtualized import V + + +T = TypeVar("T") +U = TypeVar("U") + + +Split = tuple[sympy.Expr, ...] +VarsAndRanges = tuple[list[sympy.Symbol], list[sympy.Expr]] + + +loop_tiling_log = torch._logging.getArtifactLogger(__name__, "loop_tiling") +from torch.utils._sympy.functions import FloorDiv, ModularIndexing + + +if TYPE_CHECKING: + from torch._inductor.scheduler import ( + BaseSchedulerNode, + FusedSchedulerNode, + SchedulerNode, + ) + + +def solve_for_zero(expr: sympy.Expr) -> sympy.Expr | None: + """ + Given an expr with a single free symbol, solve for a constant relation that would make + this expression 0. + """ + if expr.is_constant(): + return None + elif isinstance(expr, FloorDiv): + return None + + if len(expr.free_symbols) != 1: + raise AssertionError( + f"expected exactly 1 free symbol, got {len(expr.free_symbols)}" + ) + free_symbol = next(iter(expr.free_symbols)) + if isinstance(expr, ModularIndexing): + out = try_solve(sympy.Eq(expr.args[0], expr.args[2]), free_symbol) + else: + out = try_solve(sympy.Eq(expr, 0), free_symbol) + if not out or not out[1].is_constant(): + return None + return out[1] + + +def solve_for_tiling(expr: sympy.Expr) -> sympy.Expr | None: + """ + Giving an expr with a single free symbol, try to find a tiling that would + make the expression coalesced with respect to that symbol. + + Tiling an expression `x` by `y` means that the expression will now be indexed + by both the original (x) and by (x * y). So we are looking for a + multiplicative factor that will make ((x + 1) * y) - (x * y) == 1. + + To simplify things for sympy, we'll try just x * y == 1, check x(1) and x(0). + """ + + if len(expr.free_symbols) != 1: + return None + + free_symbol = next(iter(expr.free_symbols)) + + def _solve_simple_expr(expr: sympy.Expr) -> sympy.Expr | None: + if expr.has(ModularIndexing) or expr.has(FloorDiv): + # the div approximation could not eliminate all ModularIndexing / + # FloorDiv nodes; we cannot solve this expression + return None + if len(expr.free_symbols) != 1: + return None + + out = try_solve(sympy.Eq(expr, 1), free_symbol) + if not out or not out[1].is_constant(): + return None + return out[1] + + # Sympy solving is very limited with ModularIndexing and FloorDiv, + # but good otherwise. + if not expr.has(ModularIndexing) and not expr.has(FloorDiv): + return _solve_simple_expr(expr) + + required_values = [] + eq_1_expressions = [] + + # very piecemeal solution if ModularIndexing or FloorDiv involved. + # Look for terms we'll try to make 0, and then other terms we'll try to make 1. + # Expand as needed. + for arg in sympy.Add.make_args(expr): + # Try to make mul terms 0 + if isinstance(arg, sympy.Mul): + seen = False + # TODO - only need one of these to be solvable to zero + for mul_arg in arg.args: + out = solve_for_zero(mul_arg) + if out is None: + continue + + if not out.is_constant(): + raise AssertionError(f"expected constant, got {out}") + seen = True + required_values.append(out) + + if not seen: + return None + else: + eq_1_expressions.append(arg) + + if not eq_1_expressions: + return None + + eq_1_expr = sum(eq_1_expressions) + + def indexing_div_rep( + x: sympy.Expr, + y: sympy.Expr, + z: sympy.Expr | None = None, + ) -> sympy.Expr: + return x / y + + # For the purposes of tiling/coalesced access, approximate ModularIndexing and FloorDiv + # then check later. simultaneous=False rebuilds bottom up, collapsing nested + # occurrences in one pass; the second sweep catches nodes that FloorDiv eval + # reintroduces while rebuilding. Leftovers make _solve_simple_expr bail out. + eq_1_expr_simplified = eq_1_expr + for _ in range(2): + # pyrefly: ignore [missing-attribute] + eq_1_expr_simplified = eq_1_expr_simplified.replace( + ModularIndexing, indexing_div_rep, simultaneous=False + ).replace(FloorDiv, indexing_div_rep, simultaneous=False) + + out = _solve_simple_expr(eq_1_expr_simplified) + + # since we approximated FloorDiv/ModularIndexing, double check here + if not out or sympy_subs(eq_1_expr, {free_symbol: out}) != 1: + return None + + required_values.append(out) + + if len(OrderedSet(required_values)) == 1: + return required_values[0] + + return None + + +def find_broadcast_var( + index: sympy.Expr, var_ranges: dict[sympy.Expr, int] +) -> sympy.Expr | None: + """ + Try to find the variable that this index is broadcast over. + A broadcast pattern is one where consecutive values of a variable + access the same memory location (e.g., x // 10). + """ + # Approximate analysis by evaluating at 1 and 0 + variables: dict[sympy.Symbol, int] = {} + for v in index.free_symbols: + if v in var_ranges: + variables[v] = 0 + else: + variables[v] = get_hint(v) + + zero_index = sympy_subs(index, variables) + for v in var_ranges: + if v not in index.free_symbols: + continue + + variables[v] = 1 + try: + new_val = sympy_subs(index, variables) + except ZeroDivisionError: + loop_tiling_log.info("zero division error %s %s", index, variables) + continue + # Broadcast means the value doesn't change when the variable increments + if new_val == zero_index: + return v + variables[v] = 0 + + return None + + +def find_coalesced_var( + index: sympy.Expr, var_ranges: dict[sympy.Expr, int] +) -> sympy.Expr | None: + """ + Try to find the symbol which coalesces this index + """ + top_level_terms = sympy.Add.make_args(index) + for v in var_ranges: + if v in top_level_terms: + return v + + # Approximate analysis by evaluating at 1 and 0 + variables: dict[sympy.Symbol, int] = {} + for v in index.free_symbols: + if v in var_ranges: + variables[v] = 0 + else: + variables[v] = get_hint(v) + + zero_index = sympy_subs(index, variables) + for v in var_ranges: + variables[v] = 1 + try: + new_val = sympy_subs(index, variables) + except ZeroDivisionError: + loop_tiling_log.info("zero division error %s %s", index, variables) + continue + if new_val - zero_index == 1: + variables[v] = 2 + # in some more complex expressions, 0->1 will be coalesced, + # but not 1->2 + if (sympy_subs(index, variables) - new_val) == 1: + return v + variables[v] = 0 + + return None + + +def has_indirect_access(memory_expr: sympy.Expr) -> bool: + """ + Check if this memory expression has any indirect indexing. + """ + return any(symbol_is_type(s, SymT.INDIRECT) for s in memory_expr.free_symbols) + + +@dataclasses.dataclass(frozen=True) +class FusedNormalizedReadsWrites: + """ + Normalized reads and writes for nodes in the same FusedSchedulerNode. + """ + + index_vars: OrderedSet[sympy.Symbol] + reduce_vars: OrderedSet[sympy.Symbol] + reads: dict[sympy.Expr, OrderedSet[str]] + writes: dict[sympy.Expr, OrderedSet[str]] + var_ranges: dict[sympy.Symbol, int] + + +@dataclasses.dataclass(frozen=True) +class _FusedNodeView: + nodes: Sequence["BaseSchedulerNode"] + read_writes: ReadWrites + group: Any + + def get_nodes(self) -> Sequence["BaseSchedulerNode"]: + return self.nodes + + def get_buffer_names(self) -> OrderedSet[str]: + return OrderedSet.union(*(node.get_buffer_names() for node in self.nodes)) + + def get_operation_names(self) -> OrderedSet[str]: + return OrderedSet(node.get_name() for node in self.nodes) + + +@overload +def get_pw_red_splits( + n: "SchedulerNode", + pointwise_numel: sympy.Expr, + red_numel: sympy.Expr, + none_if_not_divisible: Literal[True], +) -> tuple[VarsAndRanges, VarsAndRanges] | None: ... + + +@overload +def get_pw_red_splits( + n: "SchedulerNode", + pointwise_numel: sympy.Expr, + red_numel: sympy.Expr, + none_if_not_divisible: Literal[False] = False, +) -> tuple[VarsAndRanges, VarsAndRanges]: ... + + +def get_pw_red_splits( + n: "SchedulerNode", + pointwise_numel: sympy.Expr, + red_numel: sympy.Expr, + none_if_not_divisible: bool = False, +) -> tuple[VarsAndRanges, VarsAndRanges] | None: + # nb: use statically_known_equals here to mimic scheduler. + # TODO : store type of split/broadcast on fused node itself, + # instead of re-deriving it. + if n.is_reduction() or V.graph.sizevars.statically_known_equals( + sympy_product(n._body.sizes[0]), pointwise_numel + ): + # pyrefly: ignore [bad-return] + return ( + (n._body.iter_vars, n._body.sizes[0]), + (n._body.reduce_vars, n._body.sizes[1]), + ) # type: ignore[return-value] + + if get_hint(sympy_product(n._body.sizes[0])) != get_hint( + pointwise_numel * red_numel # type: ignore[operator] + ): + raise AssertionError( + "expected pointwise sizes to match pointwise_numel * red_numel" + ) + i = len(n._body.sizes[0]) - 1 + prod = 1 + while i >= 0: + prod *= n._body.sizes[0][i] + if prod == red_numel: + break + i -= 1 + + if i >= 0: + pw_splits = n._body.sizes[0][0:i] + iter_vars = n._body.iter_vars[0:i] + + red_splits = n._body.sizes[0][i:] + red_vars = n._body.iter_vars[i:] + return (iter_vars, pw_splits), (red_vars, red_splits) # type: ignore[return-value] + + if none_if_not_divisible: + return None + else: + # pyrefly: ignore [bad-return] + return ( + (n._body.iter_vars, n._body.sizes[0]), + (n._body.reduce_vars, n._body.sizes[1]), + ) # type: ignore[return-value] + + +class NodeSplitGetter: + """ + Finds a Pointwise, Reduction Split that compatible with all nodes in a SchedulerNode. + """ + + def __init__( + self, + node: Union["_FusedNodeView", "FusedSchedulerNode", "SchedulerNode"], + ): + self.node = node + self.pointwise_numel: sympy.Expr = node.group[1][0] + self.red_numel: sympy.Expr = node.group[1][1] + + self.pw_split_options: dict[int, OrderedSet[Split]] = defaultdict(OrderedSet) + self.red_split_options: dict[int, OrderedSet[Split]] = defaultdict(OrderedSet) + + self.reduction_split: Split = () + self.all_node_sizes: OrderedSet[tuple[Split, Split]] = OrderedSet() + + fused_group = node.group[1] + for n in reversed(node.get_nodes()): + if not isinstance(n, torch._inductor.scheduler.SchedulerNode): + continue + + # if we can't split the pw ranges into a (pw, red) split, + # don't add as a split option, but do make sure we check that this size + # is splittable + maybe_splits = get_pw_red_splits( + n, self.pointwise_numel, self.red_numel, none_if_not_divisible=True + ) + if maybe_splits is None: + self.all_node_sizes.add(n._body.sizes) + continue + + (_, n_pw_splits), (_, n_red_splits) = maybe_splits + + # fill in reduction size + n_pw_splits, n_red_splits = ( + torch._inductor.codegen.simd.SIMDKernel.prepare_split_iteration_lengths( + fused_group, (n_pw_splits, n_red_splits), self.red_numel + ) + ) + + self.pw_split_options[len(n_pw_splits)].add(tuple(n_pw_splits)) + self.red_split_options[len(n_red_splits)].add(tuple(n_red_splits)) + + if n_red_splits != (): + self.reduction_split = (sympy_product(n_red_splits),) + + n_size = (tuple(n_pw_splits), tuple(n_red_splits)) + self.all_node_sizes.add(n_size) + + self.seen_pw_splits: OrderedSet[Split] = OrderedSet() + + def get_node_splits(self) -> tuple[Split, Split]: + """ + Get a compatible pointwise, reduction split of the node + """ + + if len(self.all_node_sizes) == 1: + return next(iter(self.all_node_sizes)) + + if len(self.pw_split_options) == 0: + return ((self.pointwise_numel,), (self.red_numel,)) + + max_pw_split = max(self.pw_split_options.keys()) + max_red_split = max(self.red_split_options.keys()) + + def add_combined_split_options( + split_options: dict[int, OrderedSet[Split]], curr_length: int + ) -> None: + for split in split_options[curr_length]: + for i in range(len(split) - 1): + new_split = tuple( + split[0:i] + (sympy_product(split[i : i + 2]),) + split[i + 2 :] + ) + split_options[len(new_split)].add(new_split) + + max_total_splits = max_pw_split + max_red_split + for curr_iter, total_splits in enumerate(range(max_total_splits, 0, -1)): + for pw_split_len in range(total_splits, 0, -1): + for pw_split in self.pw_split_options[pw_split_len]: + for red_split in self.red_split_options[ + total_splits - pw_split_len + ]: + if out := self.try_split(pw_split, red_split): + return out + + add_combined_split_options(self.pw_split_options, max_pw_split - curr_iter) + add_combined_split_options( + self.red_split_options, max_red_split - curr_iter + ) + + # if for whatever reason we couldn't split above, return default split + return ((self.pointwise_numel,), (self.red_numel,)) + + def try_split(self, pw: Split, red: Split) -> tuple[Split, Split] | None: + """ + See if this split is compatible, and potentially returning a longer split + than the input. + """ + + from torch._inductor.codegen.simd import CantSplit, SIMDKernel + + if pw in self.seen_pw_splits: + return None + self.seen_pw_splits.add(pw) + + for n_pw, n_red in self.all_node_sizes: + try: + groups = pw + red + lengths = (n_pw, n_red) + splits, getters = SIMDKernel._split_iteration_ranges(groups, lengths) + except CantSplit: + return None + + if len(getters) != 2: + raise AssertionError(f"expected 2 getters, got {len(getters)}") + pw_group_splits = splits[: len(pw)] + # if we had to divide a variable into two to do this split, + # then lets try the larger, induced split. + # e.g. splitting (12, 2) into (2, 12) will split the first var into: + # (2, 6) and produce an overall split of (2, 6, 2) + flattened_pw_splits = tuple(itertools.chain.from_iterable(pw_group_splits)) + if flattened_pw_splits != pw: + if out := self.try_split(flattened_pw_splits, red): + return out + + return pw, red + + +def apply_var_mapping( + iter_vars: list[sympy.Symbol], + red_vars: list[sympy.Symbol], + norm_pw_vars: list[sympy.Symbol], + norm_red_vars: list[sympy.Symbol], + new_ranges: list[list[sympy.Expr]], + return_getters_groups: list[list[Callable[[list[sympy.Expr]], sympy.Expr]]], +) -> dict[sympy.Symbol, sympy.Expr]: + """Maps original variables to expressions using normalized variables.""" + + # the output of split_iteration_range is a new_ranges, return_getters_groups + # new_ranges is a flattened list of ranges corresponding to the new pw and red vars + # for example, taking in pw vars of range (6, 6) to normalized range [36], + # new_ranges would be [[6, 6]] + # There is a return_getter callable for each input iter_var and red_vars. + # if you flatten out all of the ranges, and create a variable for each index, + # then applying the flattening vars to the callables in return_getters_groups + # gives you the mapping from input vars -> flattened vars. + # From there, we can compute the output, normalized variables. + # For instance [6, 6] corresponding to flat vars v0, v1 will be + # v0 + 6 * v1 + + # Create flattened iteration variables + num_vars = sum(len(s) for s in new_ranges) + flat_vars = sympy.symbols(f"v_0:{num_vars}") + count = 0 + + if len(iter_vars) == 0 and len(red_vars) == 0: + return {} + + if len(new_ranges) != len(norm_pw_vars + norm_red_vars): + raise AssertionError( + f"expected len(new_ranges) == len(norm_pw_vars + norm_red_vars), " + f"got {len(new_ranges)} and {len(norm_pw_vars + norm_red_vars)}" + ) + apply_groups = [] + for group in return_getters_groups: + apply_groups.append([g(flat_vars) for g in group]) + + iter_vars_to_flat_vars = {} + for i, (group, var_group) in enumerate( + zip(apply_groups, (iter_vars, red_vars), strict=True) + ): + # if the node has sizes (p0, 1) and the fused node is (p0, r0) + # the reduction var gets filled in for split_iteration_range + if len(group) != len(var_group): + if i != 1: + raise AssertionError(f"expected i == 1, got {i}") + if len(var_group) != 0: + raise AssertionError( + f"expected empty var_group, got len {len(var_group)}" + ) + continue + + iter_vars_to_flat_vars.update({v: g for g, v in zip(group, var_group)}) + + count = 0 + flat_vars_to_new_vars = {} + for new_range, new_var in zip( + new_ranges, norm_pw_vars + norm_red_vars, strict=True + ): + range_vars = [] + for _ in range(len(new_range)): + range_vars.append(flat_vars[count]) + count += 1 + + prod = 1 + for i in range(len(new_range) - 1, -1, -1): + flat_vars_to_new_vars[range_vars[i]] = new_var * prod + prod = new_range[i] * prod + + return { + k: sympy_subs(v, flat_vars_to_new_vars) + for k, v in iter_vars_to_flat_vars.items() + } + + +def extract_normalized_read_writes( + node: Union["_FusedNodeView", "FusedSchedulerNode", "SchedulerNode"], +) -> FusedNormalizedReadsWrites | None: + """Extracts index variables, reduce variables, read/write expressions, and variable ranges from a fused node.""" + reads: dict[sympy.Expr, OrderedSet[str]] = defaultdict(OrderedSet) + writes: dict[sympy.Expr, OrderedSet[str]] = defaultdict(OrderedSet) + + all_output_names = node.get_buffer_names() + op_names = node.get_operation_names() + outputs: OrderedSet[str] = OrderedSet() + removed_buffers: OrderedSet[str] = OrderedSet() + for buf_name in all_output_names: + if V.graph.scheduler.can_buffer_be_removed_through_fusion(buf_name, op_names): + removed_buffers.add(buf_name) + else: + outputs.add(buf_name) + + inputs = OrderedSet( + dep.name for dep in node.read_writes.reads if dep.name not in removed_buffers + ) + + pointwise_numel: sympy.Expr = node.group[1][0] + red_numel: sympy.Expr = node.group[1][1] + + pw_splits, red_splits = NodeSplitGetter(node).get_node_splits() + + # lets use different prefix (`n`) to distinguish + (norm_pw_vars, norm_red_vars), ranges = index_vars_no_squeeze( + pw_splits, red_splits, prefix="n" + ) + + for n in list(node.get_nodes()): + if not isinstance(n, torch._inductor.scheduler.SchedulerNode): + continue + + body = n._body + + n_reads: dict[sympy.Expr, OrderedSet[str]] = defaultdict(OrderedSet) + n_writes: dict[sympy.Expr, OrderedSet[str]] = defaultdict(OrderedSet) + + # TODO - will the names for all the inputs/outputs accurately + # reflect mutation, or do I need to remap with mutation_real_name + for inp in inputs: + for expr in body.get_all_read_expr(inp): + n_reads[expr].add(inp) + + for out in outputs: + for expr in body.get_all_write_expr(out): + n_writes[expr].add(out) + + if not n_reads and not n_writes: + continue + + (iter_vars, n_pw_splits), (red_vars, n_red_splits) = get_pw_red_splits( + n, pointwise_numel, red_numel + ) + + groups = pw_splits + red_splits + lengths = (n_pw_splits, (n_red_splits)) + lengths = ( + torch._inductor.codegen.simd.SIMDKernel.prepare_split_iteration_lengths( + groups, lengths, red_numel + ) + ) + try: + new_ranges, return_getters_groups = ( + torch._inductor.codegen.simd.SIMDKernel._split_iteration_ranges( + groups, lengths + ) + ) + except torch._inductor.codegen.simd.CantSplit as e: + # occasionally with dynamic shapes, we will be unable to prove + # divisibility + if not (pointwise_numel.free_symbols or red_numel.free_symbols): + raise AssertionError( + "expected dynamic shapes (free symbols) when split fails" + ) from e + return None + + var_map = apply_var_mapping( + iter_vars, + red_vars, + norm_pw_vars, + norm_red_vars, + new_ranges, + return_getters_groups, + ) + + # We create Identity sympy.Functions to prevent expansion to int64, + # unwrap for tiling analysis. + def remove_identity(expr: sympy.Expr) -> sympy.Expr: + return expr.replace(Identity, lambda x: x) + + n_reads_new = { + sympy_subs(remove_identity(read), var_map): v for read, v in n_reads.items() + } + n_writes_new = { + sympy_subs(remove_identity(write), var_map): v + for write, v in n_writes.items() + } + + for expr, buf_names in n_reads_new.items(): + reads[expr] |= buf_names + + for expr, buf_names in n_writes_new.items(): + writes[expr] |= buf_names + + reads = { + V.graph.sizevars.simplify_with_ranges(r, ranges): v for r, v in reads.items() + } + writes = { + V.graph.sizevars.simplify_with_ranges(w, ranges): v for w, v in writes.items() + } + + fused_out = FusedNormalizedReadsWrites( + norm_pw_vars, # type: ignore[arg-type] + norm_red_vars, # type: ignore[arg-type] + reads, + writes, + ranges, + ) + loop_tiling_log.info("Normalized Fused reads: %s", fused_out) + return fused_out + + +def get_score( + addr: sympy.Expr, var_ranges: dict[sympy.Symbol, int], buf_names: OrderedSet[str] +) -> int: + """ + Score addr according to its approximate size. + """ + # TODO - deduplicate with candidate_tilings + var_sizes = [] + for v in addr.free_symbols: + v_size = var_ranges.get(v) + # TODO - reason about indirect vars + if not symbol_is_type(v, SymT.INDIRECT) and v_size is not None: + var_sizes.append(v_size) + from .virtualized import V + + return V.graph.sizevars.optimization_hint(sympy_product(var_sizes)) + + +def try_get_buf_size(buf_name: str) -> int | None: + buf = V.graph.try_get_buffer(buf_name) + if not buf: + return None + return V.graph.sizevars.optimization_hint(sympy_product(buf.get_size())) + + +def get_hint(v: sympy.Expr | int) -> int: + if isinstance(v, int): + return v + else: + return V.graph.sizevars.optimization_hint(v) + + +@dataclasses.dataclass(frozen=True) +class VarTiling: + """ + Tiling of a var by `tiling_factor` that yields additional coalesced mem accesses by `benefit_score` + """ + + var: sympy.Symbol + tiling_factor: int + score: int + + +@dataclasses.dataclass(frozen=True) +class CoalesceVarAnalysis: + # Var -> Memory Score - not strictly the amount of memory + # because we multiply writes x2 + # TODO: separate into dataclass that holds mem, dtype, is_write + coalesced_by_var: dict[sympy.Expr, int] + + uncoalesced_addrs: dict[sympy.Expr, int] + + norm_read_writes: FusedNormalizedReadsWrites + + suggested_split: VarTiling | None = None + + +def _analyze_memory_coalescing( + fused_node: Union["_FusedNodeView", "FusedSchedulerNode", "SchedulerNode"], +) -> CoalesceVarAnalysis | None: + """ + Implementation for BaseSchedulerNode.get_coalesce_analysis(). + Call that node method so loop-transform cache invalidation is honored. + + Find variables that coalesce the reads and writes and score the total size. + + If uncoalesced memory expressions are found, look for additionally tiling of variables + which will coalesce memory accesses. + + For instance - for the following expression: + + (32*p0) // 2048 + + Tiling p0 by 64 will make this expression coalesced. + """ + + norm_read_writes = extract_normalized_read_writes(fused_node) + + if norm_read_writes is None: + return None + + reads = norm_read_writes.reads + writes = norm_read_writes.writes + var_ranges = norm_read_writes.var_ranges + + coalesced_by_var: dict[sympy.Symbol, int] = Counter() + uncoalesced_addrs: dict[sympy.Expr, int] = Counter() + + # Only check pointwise-only kernels + index_vars = norm_read_writes.index_vars + reduce_vars = norm_read_writes.reduce_vars + innermost_var = ( + next(reversed(index_vars)) if index_vars and not reduce_vars else None + ) + + for is_read, (memory_expr, buf_names) in itertools.chain( + ((True, item) for item in reads.items()), + # pyrefly: ignore [bad-argument-type] + ((False, item) for item in writes.items()), + ): + size = get_score(memory_expr, var_ranges, buf_names) + if size == 0: + continue + + # accesses with indirect expressions are never coalesced + indirect_expr = has_indirect_access(memory_expr) + + if indirect_expr: + maybe_coalesced_var = None + else: + maybe_coalesced_var = find_coalesced_var(memory_expr, var_ranges) + # while broadcasting vars are not technically coalesced, + # accesses at least stay in cache, so they provide most of the benefit. + # treat the same for now. + if maybe_coalesced_var is None: + maybe_coalesced_var = find_broadcast_var(memory_expr, var_ranges) + + total_score = 0 + for buf_name in buf_names: + if (buf := V.graph.try_get_buffer(buf_name)) and ( + buf_size := try_get_buf_size(buf_name) + ): + # constrain by buf size since we'll read at most that many elements + # score could be more through either masking or by broadcasting (e.g. x // 16) + total_score += min(buf_size, size) * buf.dtype.itemsize + + # coalesced writes more important + total_score *= 1 if is_read else 2 + + if maybe_coalesced_var: + # Check if the coalescing is already achieved in 1D iteration. + # Skip the innermost variable: it always varies across threads, + # so its coalescing is always real. + already_coalesced_1d = False + if innermost_var is not None and maybe_coalesced_var != innermost_var: + # Evaluate stride at two points (0->1 and 1->2) to catch + # non-linear expressions that only look coalesced at the origin. + subs = dict.fromkeys(var_ranges, 0) + try: + val_0 = sympy_subs(memory_expr, subs) + subs[innermost_var] = 1 + val_1 = sympy_subs(memory_expr, subs) + stride_01 = val_1 - val_0 + if stride_01 in (0, 1): + subs[innermost_var] = 2 + val_2 = sympy_subs(memory_expr, subs) + stride_12 = val_2 - val_1 + if stride_12 in (0, 1): + already_coalesced_1d = True + except (ZeroDivisionError, TypeError): + pass + + if not already_coalesced_1d: + coalesced_by_var[maybe_coalesced_var] += total_score + else: + coalesced_by_var[innermost_var] += total_score + else: + uncoalesced_addrs[memory_expr] += total_score + + if not uncoalesced_addrs: + return CoalesceVarAnalysis( + coalesced_by_var=coalesced_by_var, + uncoalesced_addrs=uncoalesced_addrs, + norm_read_writes=norm_read_writes, + ) + + # map from var -> tiling -> total_score + tiling_scores: dict[sympy.Expr, dict[int, int]] = defaultdict(Counter) + + for uncoalesced_expr, addr_score in uncoalesced_addrs.items(): + if has_indirect_access(uncoalesced_expr): + continue + + expr_subs = dict.fromkeys(var_ranges.keys(), 0) + for v in uncoalesced_expr.free_symbols & var_ranges.keys(): + # skip non iter/reduce var variables + if v not in var_ranges: + continue + # skip small addrs + if addr_score == 0: + continue + + del expr_subs[v] + single_var_expr = sympy_subs(uncoalesced_expr, expr_subs) + expr_subs[v] = 0 + + if len(single_var_expr.free_symbols) != 1: + continue + + tiling_factor = solve_for_tiling(single_var_expr) + + if ( + tiling_factor is None + or not tiling_factor.is_constant() + or not tiling_factor.is_integer + ): + continue + + tiling_factor = int(tiling_factor) + if not V.graph.sizevars.statically_known_lt(tiling_factor, var_ranges[v]): + continue + + # TODO - if a var is in the middle, such as [n0, n1, n2] + # n1 can be split beyond range + + MIN_TILING_BLOCK = 8 + if not all( + V.graph.sizevars.statically_known_lt(MIN_TILING_BLOCK, block) + for block in (tiling_factor, var_ranges[v] // tiling_factor) + ): + continue + + tiling_scores[v][tiling_factor] += addr_score + + if len(tiling_scores) == 0: + return CoalesceVarAnalysis( + coalesced_by_var=coalesced_by_var, + uncoalesced_addrs=uncoalesced_addrs, + norm_read_writes=norm_read_writes, + ) + + best_tiling: tuple[sympy.Expr, int] | None = None + best_tiling_score = 0 + + for var, tiling_counter in tiling_scores.items(): + for tile, tile_score in tiling_counter.items(): + if tile_score > best_tiling_score: + best_tiling = (var, tile) + best_tiling_score = tile_score + + if best_tiling is None: + return CoalesceVarAnalysis( + coalesced_by_var=coalesced_by_var, + uncoalesced_addrs=uncoalesced_addrs, + norm_read_writes=norm_read_writes, + ) + + # TODO - for strictly pointwise fusions, + # we can consider just swizzling the var if the var we are going to tile + # does not coalesce a significant portion of global reads + # TODO - could also prefer index var splits to reduction, better tested + return CoalesceVarAnalysis( + coalesced_by_var=coalesced_by_var, + uncoalesced_addrs=uncoalesced_addrs, + norm_read_writes=norm_read_writes, + suggested_split=VarTiling(best_tiling[0], best_tiling[1], best_tiling_score), + ) + + +def analyze_memory_coalescing_for_nodes( + nodes: Sequence["BaseSchedulerNode"], +) -> CoalesceVarAnalysis | None: + if not nodes: + return None + + from torch._inductor import scheduler + + node_types = (scheduler.FusedSchedulerNode, scheduler.SchedulerNode) + if not all(isinstance(node, node_types) for node in nodes): + return None + + if len(nodes) == 1: + return nodes[0].get_coalesce_analysis() + + graph_scheduler = getattr(V.graph, "scheduler", None) + if graph_scheduler is not None: + fused_node = graph_scheduler.name_to_fused_node.get(nodes[0].get_first_name()) + if fused_node is not None: + fused_nodes = list(fused_node.get_nodes()) + if len(fused_nodes) == len(nodes) and all( + fused is node for fused, node in zip(fused_nodes, nodes, strict=True) + ): + return fused_node.get_coalesce_analysis() + + return _analyze_memory_coalescing( + _FusedNodeView( + nodes=nodes, + read_writes=ReadWrites.merge_list([node.read_writes for node in nodes]), + group=max(nodes, key=lambda node: int(node.is_reduction())).group, + ) + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/triton_bundler.py b/.venv/lib/python3.12/site-packages/torch/_inductor/triton_bundler.py new file mode 100644 index 0000000000000000000000000000000000000000..3a7be37a9aa4cc9d2eb60af0a14c88de5bc657e0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/triton_bundler.py @@ -0,0 +1,434 @@ +import copy +import dataclasses +import logging +import os +import shutil +import uuid +from pathlib import Path + +from torch._dynamo.utils import counters, dynamo_timed, set_feature_use +from torch._utils_internal import justknobs_check +from torch.utils._filelock import FileLock +from torch.utils._ordered_set import OrderedSet + +from .runtime.runtime_utils import triton_cache_dir +from .utils import _IS_WINDOWS, GPU_KERNEL_BIN_EXTS + + +log = logging.getLogger(__name__) + + +@dataclasses.dataclass(frozen=True) +class TritonBundleEntry: + """ + When we have compiled a triton kernel, we take note of that kernel by + its triton generated hash, its device, and where this kernel is located. + This is the minimum information we can use to later retrieve this kernel + from file system. + """ + + kernel_hash: str + device: int + directory: str + + +@dataclasses.dataclass(frozen=True) +class TritonKernelArtifact: + """ + Artifact for an individual kernel converted to bytes. + Bytes could be a cubin, json, ttir, or ttgir. + """ + + filename: str + payload: bytes = dataclasses.field(repr=False) # Do not display binary + + +@dataclasses.dataclass(frozen=True) +class StaticallyLaunchedAutotuner: + """ + Represents a statically compiled CachingAutotuner object that we can + save directly in the cache. A CachingAutotuner is made up of a list of + StaticTritonCompileResults, each of which uses the cubin from a TritonKernelArtifact. + + Statically saved here have their cubin files saved by a corresponding TritonBundleEntry. + """ + + cache_key: str + kernel_name: str + kernel: "CachingAutotuner" # type: ignore[name-defined] # noqa: F821 + + +@dataclasses.dataclass(frozen=True) +class TritonKernelArtifacts: + """ + Collection of artifacts for a particular kernel. + """ + + kernel_hash: str + device: int + artifacts: list[TritonKernelArtifact] + + +@dataclasses.dataclass(frozen=True) +class TritonBundlerMetadata: + """ + Metadata used for instrumentation + """ + + cached_kernel_names: list[str] + statically_launched_kernel_names: list[str] + + +@dataclasses.dataclass(frozen=True) +class TritonBundle: + """ + Serializable bundle to save into FXGraphCache + """ + + kernel_artifacts: list[TritonKernelArtifacts] + static_autotuners: list[StaticallyLaunchedAutotuner] + + +class TritonBundler: + """ + Lightweight Triton Kernel bundler that notes each time we compile a triton + kernel. When collect is called, converts all the previously noted kernels and + their artifacts into a structured bytes blob, and later when write is called + it writes this structured blob back to file system. + + Intended Life cycle: + - TritonBundler.begin_compile is called when we start compiling in Inductor + - TritonBundler.put is called each time a Triton Kernel is compiled + - TritonBundler.collect is called when a cache entry is being generated + - TritonBundler.end_compile is called to indicate bundling is completed, + collect will execute this function as well. + - TritonBundler.read_and_emit is called when a cache entry is read + """ + + _entries: list[TritonBundleEntry] | None = None + _static_autotuners: list[StaticallyLaunchedAutotuner] | None = None + _winners: OrderedSet[str] | None = None + + # __grp__kernel_name.json contains metadata with source code paths + # we use this as sentinel value for search and replace + _REPLACE_BYTES: bytes = b"[REPLACE]" + + @staticmethod + def is_enabled() -> bool: + from torch._inductor import config + + if config.force_disable_caches: + return False + + if (b := config.bundle_triton_into_fx_graph_cache) is not None: + return b + + if not config.is_fbcode(): + return False + + return justknobs_check( + "pytorch/remote_cache:bundle_triton_into_fx_graph_cache_v2" + ) + + @classmethod + def begin_compile(cls) -> None: + """ + Initializes the TritonBundler. + The current TritonBundler bundle is finalized by TritonBundler.collect. + """ + if not TritonBundler.is_enabled(): + return + log.debug("TritonBundler.begin_compile is called") + if cls._entries is not None: + raise AssertionError( + "TritonBundler.begin_compile called with active entries; " + "expected cls._entries to be None" + ) + cls._entries = [] + cls._static_autotuners = [] + cls._winners = OrderedSet() + + @classmethod + def end_compile(cls) -> None: + """ + Finalizes the TritonBundler. If collect is not yet called, it + discards the current bundle. + """ + log.debug("TritonBundler.end_compile is called") + cls._entries = None + cls._static_autotuners = None + cls._winners = None + + @classmethod + def put(cls, kernel_hash: str, device: int) -> None: + """ + Lazily observes that we have seen a Triton kernel compilation. Remembers + it for when collect is later called. + """ + if (entries := cls._entries) is not None: + entries.append( + TritonBundleEntry(kernel_hash, device, triton_cache_dir(device)) + ) + + @classmethod + def put_winner(cls, kernel_hash: str) -> None: + """ + Marks a kernel hash as a winning autotuning config. Only winning + kernels are included in the bundle by collect(). If no winners are + recorded (e.g. single-config kernels that skip autotuning), all + entries are bundled. + """ + if cls._winners is not None: + cls._winners.add(kernel_hash) + + @classmethod + def put_static_autotuner(cls, key: str, kernel: "CachingAutotuner") -> None: # type: ignore[name-defined] # noqa: F821 + from torch._inductor import config + + if not config.use_static_triton_launcher: + raise AssertionError("expected config.use_static_triton_launcher to be set") + if (entries := cls._static_autotuners) is not None: + # Clear a bunch of unpicklable values and make a copy to save + # for FXGraphCache + old_values = kernel.prepare_for_pickle() + new_kernel = copy.deepcopy(kernel) + new_kernel.prepare_for_caching() + new_kernel._reload_kernel = None + + entries.append( + StaticallyLaunchedAutotuner( + key, + new_kernel.inductor_meta.get("kernel_name", "unknown_kernel"), + new_kernel, + ) + ) + + # Put the values back since we need it to use now + kernel.restore_after_unpickle(old_values) + + @classmethod + def collect_static_autotuners( + cls, + ) -> tuple[list[StaticallyLaunchedAutotuner], list[str]]: + if not cls._static_autotuners: + return [], [] + else: + log.info( + "Saving %d statically launchable CachingAutotuners", + len(cls._static_autotuners), + ) + static_autotuner_names = [i.kernel_name for i in cls._static_autotuners] + counters["inductor"]["triton_bundler_save_static_autotuner"] += 1 + return cls._static_autotuners, static_autotuner_names + + @classmethod + def load_autotuners( + cls, static_autotuners: list[StaticallyLaunchedAutotuner] | None + ) -> list[str]: + """ + Load statically launchable CachingAutotuners into async_compile.CompiledTritonKernels + cache. + """ + if not static_autotuners: + return [] + + from torch._inductor.async_compile import CompiledTritonKernels + from torch._inductor.codecache import StaticAutotunerFuture + + log.info("Loading %d statically launchable autotuners", len(static_autotuners)) + kernel_names = [] + with dynamo_timed("TritonBundler.load_cached_static_autotuners"): + for result in static_autotuners: + try: + # Make sure the cubin path exists and is valid + for compile_result in result.kernel.compile_results: + compile_result.reload_cubin_path() + except RuntimeError: + log.warning( + "Failed to reload cubin file statically launchable autotuner %s", + result.kernel_name, + exc_info=True, + ) + continue + # We make a future instead of returning the kernel here so that + # kernels that are not statically launchable (i.e. cache miss) + # can launch a worker without waiting on the blocking step of + # StaticAutotunerFuture.result(). + CompiledTritonKernels._cache[result.cache_key] = StaticAutotunerFuture( + result.kernel + ) + counters["inductor"]["triton_bundler_load_static_autotuner"] += 1 + kernel_names.append(result.kernel_name) + return kernel_names + + @classmethod + def collect( + cls, + ) -> tuple[TritonBundle, TritonBundlerMetadata | None]: + """ + This is the main function called when a cache write happens. This function + converts all the previously remembered kernels into bundled format so that + it can be written into a cache entry. + This function also finalizes the current bundle. + """ + from torch._inductor import config + + if not TritonBundler.is_enabled(): + cls.end_compile() + set_feature_use("triton_bundling", False) + return TritonBundle([], []), None + set_feature_use("triton_bundling", True) + + with dynamo_timed(key="TritonBundler.collect", log_pt2_compile_event=True): + entries = cls._entries + if entries is not None: + # Only bundle winning autotuning configs. If _winners is + # non-empty, skip entries whose kernel_hash is not a winner. + # When _winners is empty (single-config kernels, or no + # autotuning ran), bundle everything. + winners = cls._winners + result: list[TritonKernelArtifacts] = [] + kernel_names: list[str] = [] + for entry in entries: + if winners and entry.kernel_hash not in winners: + log.debug("Skipping non-winning kernel %s", entry.kernel_hash) + continue + artifacts: list[TritonKernelArtifact] = [] + path = os.path.join(entry.directory, entry.kernel_hash) + if not os.path.exists(path): + continue + for filename in os.listdir(path): + filepath = os.path.join(path, filename) + try: + if not os.path.isfile(filepath): + raise AssertionError( + f"expected a regular file, got {filepath}" + ) + with open(filepath, "rb") as file: + payload = file.read() + if filepath.endswith(".json"): + # Make sure there's no sentinel value + if TritonBundler._REPLACE_BYTES in payload: + log.warning( + "Bundle contains illegal %s, payload: %s", + TritonBundler._REPLACE_BYTES, + payload, + ) + raise AssertionError( + "Bundle contains illegal bytes" + ) + # Remove the path from payload + payload = payload.replace( + str.encode(path), TritonBundler._REPLACE_BYTES + ) + artifacts.append( + TritonKernelArtifact(filename, payload) + ) + counters["inductor"]["triton_bundler_save_kernel"] += 1 + except Exception: + log.debug("failed to collect triton kernel", exc_info=True) + extension = os.path.splitext(filename)[1] + if extension in GPU_KERNEL_BIN_EXTS.values(): + # Each kernel has bunch of files like .cubin(for cuda), .zebin(for xpu), .json, .ttir + # Just append one of them without the extension + kernel_names.append(Path(filename).stem) + if artifacts: + result.append( + TritonKernelArtifacts( + entry.kernel_hash, + entry.device, + artifacts, + ) + ) + if config.use_static_triton_launcher: + static_autotuners, static_kernel_names = ( + cls.collect_static_autotuners() + ) + else: + static_autotuners = [] + static_kernel_names = [] + cls.end_compile() + return TritonBundle(result, static_autotuners), TritonBundlerMetadata( + kernel_names, static_kernel_names + ) + return TritonBundle([], []), None + + @staticmethod + def read_and_emit(bundle: TritonBundle) -> TritonBundlerMetadata | None: + """ + This is the main function called when a cache read happens. This function + converts the bundled format back into individual files and writes them + to the filesystem. + + NOTE: When we are writing to the filesystem, we assume exclusive access + to the target directory. + This means that if the target folder already exists and is non-empty, + we bail out. + Exclusive access means that no other process should be writing to + or reading from the target directory. + """ + from torch._inductor import config + + if not TritonBundler.is_enabled(): + return None + + with dynamo_timed( + key="TritonBundler.read_and_emit", log_pt2_compile_event=True + ): + kernel_names: list[str] = [] + + for artifacts in bundle.kernel_artifacts: + basedir = triton_cache_dir(artifacts.device) + directory = os.path.join(basedir, artifacts.kernel_hash) + + if os.path.exists(directory) and len(os.listdir(directory)) != 0: + # If directory already exists, we bail out and leave + # local disk to take care of caching + log.debug( + "Bailing out TritonBundler.read_and_emit, %s is non empty", + directory, + ) + continue + + Path(basedir).mkdir(parents=True, exist_ok=True) + + # Random ID to avoid any collisions + rnd_id = str(uuid.uuid4()) + tmp_dir = os.path.join(basedir, f"tmp.{rnd_id}") + os.makedirs(tmp_dir) + + for artifact in artifacts.artifacts: + filepath = os.path.join(tmp_dir, artifact.filename) + with open(filepath, "wb") as file: + payload = artifact.payload + if artifact.filename.endswith(".json"): + payload = payload.replace( + TritonBundler._REPLACE_BYTES, str.encode(directory) + ) + file.write(payload) + counters["inductor"]["triton_bundler_read_and_emit_kernel"] += 1 + extension = os.path.splitext(artifact.filename)[1] + if extension in GPU_KERNEL_BIN_EXTS.values(): + # Each kernel has bunch of files like .cubin(for cuda), zebin(for xpu), .json, .ttir + # Just append one of them without the extension + kernel_names.append(Path(artifact.filename).stem) + + if _IS_WINDOWS: + with FileLock(directory + ".lock"): + if os.path.exists(directory): + shutil.rmtree(directory) + os.replace(tmp_dir, directory) + else: + # Atomic on POSIX systems + try: + os.replace(tmp_dir, directory) + except OSError: + log.warning("Directory %s is not empty - skipping!", tmp_dir) + + if config.use_static_triton_launcher: + static_kernel_names = TritonBundler.load_autotuners( + bundle.static_autotuners + ) + else: + static_kernel_names = [] + return TritonBundlerMetadata(kernel_names, static_kernel_names) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2b85710eec6cd99e40940ee6e6cb997b4dea0fae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/utils.py @@ -0,0 +1,4947 @@ +from __future__ import annotations + +import collections +import contextlib +import dataclasses +import enum +import functools +import hashlib +import importlib +import inspect +import io +import itertools +import logging +import operator +import os +import platform +import re +import shutil +import statistics +import sys +import sysconfig +import tempfile +import time +import unittest +from collections.abc import ( + Callable, + Collection, + Generator, + Iterator, + Mapping, + MutableMapping, + MutableSet, +) +from datetime import datetime +from functools import lru_cache +from typing import ( + Any, + cast, + Concatenate, + Generic, + Literal, + Protocol, + TYPE_CHECKING, + TypeAlias, + TypeGuard, +) +from typing_extensions import dataclass_transform, ParamSpec, TypeVar +from unittest import mock + +import sympy + +import torch +import torch.utils._pytree as pytree +from torch._inductor.analysis.device_info import datasheet_tops +from torch._inductor.runtime.hints import DeviceProperties +from torch.fx.passes.regional_inductor import _needs_inductor_compile +from torch.utils._dtype_abbrs import dtype_abbrs + +# The IndentedBuffer primitive and its line-map helpers live in torch.utils so +# they can be shared across layers (dynamo guards, AOTAutograd codegen) without +# importing this heavy module. Re-exported here for existing inductor call sites. +from torch.utils._indented_buffer import ( + DeferredLineBase, + IndentedBuffer, + LineContext, # noqa: F401 + ValueWithLineMap, # noqa: F401 +) +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import tree_flatten, tree_map_only +from torch.utils._triton import has_triton_package + + +OPTIMUS_EXCLUDE_POST_GRAD = [ + "activation_quantization_aten_pass", + "inductor_autotune_lookup_table", +] + +from torch.fx.experimental._size_hinting import _sympy_subs +from torch.fx.experimental.symbolic_shapes import ( + free_symbols, + free_unbacked_symbols, + GuardOnDataDependentSymNode, + IterateExprs, + ShapeEnv, +) + + +if TYPE_CHECKING: + from collections.abc import Iterable, Sequence, ValuesView + from pathlib import Path + + from torch import SymBool, SymFloat, SymInt + from torch._prims_common import ELEMENTWISE_TYPE_PROMOTION_KIND + from torch.fx import GraphModule + from torch.fx.node import Node + from torch.nn.functional import ScalingType # type: ignore[attr-defined] + + from .codegen.common import WorkspaceArg + from .codegen.wrapper import PythonWrapperCodegen + from .dependencies import Dep + from .graph import GraphLowering + from .ir import Buffer, ExternKernel, IRNode, Layout, Operation, ReinterpretView + from .output_code import CompiledFxGraph + from .scheduler import BaseSchedulerNode, SchedulerBuffer + + +GPU_TYPES = ["cuda", "mps", "xpu", "mtia"] +T = TypeVar("T") + + +# defines here before import torch._dynamo is for avoiding circular import +# when get_gpu_type is imported from dynamo +@functools.cache +def get_gpu_type() -> str: + avail_gpus = [x for x in GPU_TYPES if getattr(torch, x).is_available()] + if not len(avail_gpus) <= 1: + raise AssertionError( + f"Expected at most 1 available GPU type, got {len(avail_gpus)}: {avail_gpus}" + ) + gpu_type = "cuda" if len(avail_gpus) == 0 else avail_gpus.pop() + return gpu_type + + +from torch._dynamo.device_interface import get_interface_for_device +from torch._dynamo.utils import detect_fake_mode +from torch.autograd import DeviceType +from torch.autograd.profiler_util import EventList +from torch.fx.passes.graph_transform_observer import GraphTransformObserver +from torch.fx.passes.shape_prop import ShapeProp +from torch.utils._sympy.functions import ( + CeilDiv, + CleanDiv, + FloorDiv, + Identity, + Max, + ModularIndexing, +) +from torch.utils._sympy.symbol import make_symbol, SymT +from torch.utils._sympy.value_ranges import bound_sympy, ValueRanges + +from . import config +from .runtime.runtime_utils import ceildiv as runtime_ceildiv + + +_IS_WINDOWS = sys.platform == "win32" + +log = logging.getLogger(__name__) + + +_DO_BENCH_PROFILE_EVENT_NAME = "inductor_do_bench_using_profiling" + + +_T = TypeVar("_T") +VarRanges = dict[sympy.Expr, sympy.Expr] +InputType = torch.Tensor | int | torch.SymInt | None + +XPU_KERNEL_FORMAT = ( + "spv" if _IS_WINDOWS else os.getenv("TORCHINDUCTOR_XPU_KERNEL_FORMAT", "zebin") +) + +GPU_KERNEL_BIN_EXTS = { + "cuda": ".cubin", + "hip": ".hsaco", + "xpu": f".{XPU_KERNEL_FORMAT}", +} + +GPU_ALIGN_BYTES = 16 +ALIGNMENT = 16 + +TMA_ALIGNMENT = 16 +TMA_DESCRIPTOR_SIZE = 128 + +# PyTorch dtypes with valid CUtensorMapDataType mappings. +# Ref: triton/backends/nvidia/include/cuda.h (CUtensorMapDataType enum) +# triton/_internal_testing.py (tma_dtypes test list) +_TMA_SUPPORTED_DTYPES: OrderedSet[torch.dtype] = OrderedSet( + [ + torch.uint8, + torch.int8, + torch.uint16, + torch.int16, + torch.uint32, + torch.int32, + torch.int64, + torch.float16, + torch.bfloat16, + torch.float32, + torch.float64, + torch.float8_e4m3fn, + torch.float8_e5m2, + torch.float8_e4m3fnuz, + torch.float8_e5m2fnuz, + ] +) + +ALIGN_BYTES = 64 +if not ((ALIGN_BYTES & (ALIGN_BYTES - 1)) == 0 and ALIGN_BYTES >= 8): + raise AssertionError("must be power of 2") + + +def _align(nbytes: int) -> int: + """Round up to the nearest multiple of ALIGN_BYTES""" + return (nbytes + ALIGN_BYTES - 1) & -ALIGN_BYTES + + +def _is_aligned(v: sympy.Expr) -> bool: + """v can be statically proven to be a multiple of ALIGN_BYTES""" + if isinstance(v, (sympy.Add, sympy.Max, Max)): + return all(map(_is_aligned, v.args)) + return isinstance(v, align) or sympy.gcd(v, ALIGN_BYTES) == ALIGN_BYTES + + +class align(sympy.Function): + """Symbolically round up to the nearest multiple of ALIGN_BYTES""" + + nargs = (1,) + is_integer = True + + @classmethod + def eval(cls, value: sympy.Expr) -> sympy.Expr | None: + if isinstance(value, (int, sympy.Integer)): + return _align(int(value)) + if _is_aligned(value): + return value + + +@dataclasses.dataclass(frozen=True) +class GraphPartitionMap: + """ + Mapping from the partition info (e.g., input/output) to the graph info + """ + + # a unique id of graph partition + id: int + + # map partition input indices to graph input indices. None indicates a + # partition input is not a graph input. + input_index_mapping: list[int | None] + # map partition output indices to graph output indices. Empty indicates a + # partition output is not a graph output. Multiple graph outputs can map to + # the same partition output when graph outputs alias the same buffer. + output_index_mapping: list[list[int]] + + # name of constants read/written by the graph partition + constant_names: list[str] + + +def fp8_bench(fn: Callable[[], Any], warmup: int = 25, rep: int = 100) -> float: + """ + Returns benchmark results by examining torch profiler events. + This could be more accurate as it doesn't count CPU side overhead. + However, this also requires manually excluding irrelevant event, e.g. + vectorized_elementwise_kernel which is used to fill L2 cache, + various CUDA events, etc, so could also be fragile. + """ + + fn() + torch.cuda.synchronize() + cache = torch.empty(int(256e6 // 4), dtype=torch.float16, device="cuda") + + # Estimate the runtime of the function + start_event = torch.cuda.Event(enable_timing=True) + end_event = torch.cuda.Event(enable_timing=True) + start_event.record() + for _ in range(5): + cache.zero_() + fn() + end_event.record() + torch.cuda.synchronize() + estimate_ms = start_event.elapsed_time(end_event) / 5 + + # compute number of warmup and repeat + n_warmup = max(1, int(warmup / estimate_ms)) + n_repeat = max(1, int(rep / estimate_ms)) + + # Warm-up + for _ in range(n_warmup): + fn() + + start_event = [torch.cuda.Event(enable_timing=True) for _ in range(n_repeat)] + end_event = [torch.cuda.Event(enable_timing=True) for _ in range(n_repeat)] + with torch.profiler.profile( + activities=[ + torch.profiler.ProfilerActivity.CUDA, + ] + ) as p: + torch.cuda.synchronize() + for i in range(n_repeat): + cache.zero_() + start_event[i].record() + with torch.cuda.nvtx.range("RunCudaModule"): + fn() + end_event[i].record() + torch.cuda.synchronize() + times = torch.tensor( + [s.elapsed_time(e) for s, e in zip(start_event, end_event)] + ) + + res = torch.mean(times).item() + log.debug("raw events") + log.debug(p.key_averages().table(sort_by="self_device_time_total", row_limit=-1)) + filtered_events = EventList( + [ + event + for event in p.events() + if ( + event.device_type == DeviceType.CUDA + and re.match(r"fused_abs_max_\d", event.name) is not None + ) + ] + ) + if filtered_events: + res -= ( + statistics.mean(event.device_time_total for event in filtered_events) + / 1000.0 + ) + + log.debug("profiling results: %s ms", res) + return res + + +def do_bench_using_profiling( + fn: Callable[[], Any], + warmup: int = 25, + rep: int = 100, + is_vetted_benchmarking: bool = False, +) -> float: + # We did't use decorator may_distort_benchmarking_result directly since that + # requires us to import torch._inductor.runtime.benchmarking into global scope. + # Importing torch._inductor.runtime.benchmarking will cause cuda initialization + # (because of calling torch.cuda.available in global scope) + # which cause failure in vllm when it create child processes. Check log: + # https://gist.github.com/shunting314/c194e147bf981e58df095c14874dd65a + # + # Another way to solve the issue is to just move do_bench_using_profiling + # to torch._inductor.runtime.benchmarking and change all the call site. + # But that's not trivial due to so many call sites in and out of pytorch. + + from torch._inductor.runtime.benchmarking import ( + gpu_benchmark_lock, + may_distort_benchmarking_result, + ) + + locked_bench = gpu_benchmark_lock(_do_bench_using_profiling) + return may_distort_benchmarking_result(locked_bench)( + fn, warmup, rep, is_vetted_benchmarking + ) + + +def _get_do_bench_profile_result( + kineto_events: Iterable[Any], + profiler_events: Iterable[Any], + n_repeat: int, + expected_device_type: DeviceType, +) -> float: + benchmark_event_ids: OrderedSet[int] = OrderedSet() + + def collect_cpu_event_ids(event: Any) -> None: + if event.device_type != DeviceType.CPU: + return + + benchmark_event_ids.add(event.id) + for child in event.cpu_children: + collect_cpu_event_ids(child) + + benchmark_events = [ + event + for event in profiler_events + if event.name == _DO_BENCH_PROFILE_EVENT_NAME + and event.device_type == DeviceType.CPU + ] + if len(benchmark_events) != n_repeat: + raise RuntimeError( + f"Expected {n_repeat} {_DO_BENCH_PROFILE_EVENT_NAME} profiling events. " + f"Found {len(benchmark_events)} events." + ) + + for event in benchmark_events: + collect_cpu_event_ids(event) + + device_time_us = 0.0 + for event in kineto_events: + linked_correlation_id = event.linked_correlation_id() + correlation_id = event.correlation_id() + activity_type = event.activity_type() + if ( + event.device_type() == expected_device_type + and activity_type != "gpu_user_annotation" + and ( + linked_correlation_id in benchmark_event_ids + or ( + linked_correlation_id == 0 and correlation_id in benchmark_event_ids + ) + ) + and event.name() != "Context Sync" + ): + device_time_us += (event.end_ns() - event.start_ns()) / 1000.0 + + if device_time_us <= 0: + raise RuntimeError( + f"Failed to capture device events for {_DO_BENCH_PROFILE_EVENT_NAME}." + ) + + return device_time_us / 1000.0 / n_repeat + + +def _do_bench_using_profiling( + fn: Callable[[], Any], + warmup: int = 25, + rep: int = 100, + is_vetted_benchmarking: bool = False, +) -> float: + """ + Returns benchmark results by examining torch profiler events. + This could be more accurate as it doesn't count CPU side overhead. + The benchmarked function is wrapped in a profiler record_function so + cache-clearing kernels can be excluded without relying on raw CUDA event + grouping or kernel names. + """ + + if not is_vetted_benchmarking: + from torch._inductor.runtime.benchmarking import may_ban_benchmarking + + may_ban_benchmarking() + + device_type = get_gpu_type() + device_type_upper = device_type.upper() + device_interface = get_interface_for_device(device_type) + fn() + device_interface.synchronize() + cache = torch.empty(int(256e6 // 4), dtype=torch.int, device=device_type) + + # Estimate the runtime of the function + start_event = device_interface.Event(enable_timing=True) + end_event = device_interface.Event(enable_timing=True) + start_event.record() + for _ in range(5): + cache.zero_() + fn() + end_event.record() + device_interface.synchronize() + estimate_ms = start_event.elapsed_time(end_event) / 5 + + # compute number of warmup and repeat + n_warmup = max(1, int(warmup / estimate_ms)) + n_repeat = max(1, int(rep / estimate_ms)) + + # Warm-up + for _ in range(n_warmup): + fn() + + device_interface.synchronize() + profile_activity = getattr(torch.profiler.ProfilerActivity, device_type_upper) + with torch.profiler.profile( + activities=[ + torch.profiler.ProfilerActivity.CPU, + profile_activity, + ] + ) as p: + # Benchmark + for _ in range(n_repeat): + # we clear the L2 cache before each run + cache.zero_() + # record time of `fn` + with torch.profiler.record_function(_DO_BENCH_PROFILE_EVENT_NAME): + fn() + # Record clocks + device_interface.synchronize() + + log.debug("raw events") + if log.isEnabledFor(logging.DEBUG): + log.debug( + p.key_averages().table(sort_by="self_device_time_total", row_limit=-1) + ) + + result = _get_do_bench_profile_result( + p.profiler.kineto_results.events(), + p.events(), + n_repeat, + getattr(DeviceType, device_type_upper), + ) + + log.debug("profiling time breakdown") + log.debug("profiling results: %s ms", result) + return result + + +@functools.cache +def has_torchvision_roi_align() -> bool: + try: + from torchvision.ops import roi_align + + torch._C._dispatch_has_kernel_for_dispatch_key("torchvision::nms", "Meta") + return roi_align is not None and hasattr( + getattr(torch.ops, "torchvision", None), "roi_align" + ) + except ImportError: + return False + except RuntimeError as e: + if "torchvision::nms does not exist" not in str(e): + raise AssertionError(f"Unexpected RuntimeError: {e}") from e + return False + + +def decode_device(device: torch.device | None | str) -> torch.device: + if device is None: + return torch.tensor(0.0).device # default device + if isinstance(device, str): + device = torch.device(device) + if device.type not in ("cpu", "meta") and device.index is None: + device_interface = get_interface_for_device(device.type) + return torch.device(device.type, index=device_interface.Worker.current_device()) + return device + + +def sympy_product(it: Iterable[sympy.Expr]) -> sympy.Expr: + return functools.reduce(operator.mul, it, sympy.S.One) + + +def sympy_dot(seq1: Sequence[sympy.Expr], seq2: Sequence[sympy.Expr]) -> sympy.Expr: + if not len(seq1) == len(seq2): + raise AssertionError( + f"Length mismatch: len(seq1)={len(seq1)}, len(seq2)={len(seq2)}" + ) + return sympy.expand(sum(a * b for a, b in zip(seq1, seq2))) + + +def flatten_index( + indices: Sequence[sympy.Expr], + sizes: Sequence[sympy.Expr], +) -> sympy.Expr: + """Row-major flatten: per-dimension indices -> flat index.""" + if len(indices) != len(sizes): + raise AssertionError( + f"indices and sizes must have equal length, got " + f"{len(indices)} and {len(sizes)}" + ) + flat = sympy.S.Zero + for index, size in zip(indices, sizes): + flat = flat * size + index + return flat + + +def decompose_index( + index: sympy.Expr, + sizes: Sequence[sympy.Expr], +) -> list[sympy.Expr]: + """Row-major decomposition: flat index -> per-dimension indices.""" + return [ + ModularIndexing(index, sympy_product(sizes[i + 1 :]), size) + for i, size in enumerate(sizes) + ] + + +def unique(it: Iterable[_T]) -> ValuesView[_T]: + return {id(x): x for x in it}.values() + + +def ceildiv(number: int | sympy.Expr, denom: int | sympy.Expr) -> int | sympy.Expr: + if isinstance(number, sympy.Expr) or isinstance(denom, sympy.Expr): + return CeilDiv(sympy.sympify(number), sympy.sympify(denom)) + # TODO: There is a bug in a call to this function, to repro: + # python benchmarks/dynamo/huggingface.py --inductor -d cuda --accuracy + # --amp --only YituTechConvBert --dynamic-shapes + if not (isinstance(number, int) and isinstance(denom, int)): + raise AssertionError(f"{number}: {type(number)}, {denom}: {type(denom)}") + return runtime_ceildiv(number, denom) + + +def _type_of(key: torch.dtype | None) -> str: + # Use the function here to get rid of dependencies on the Triton during the codegen. + # Refer to Triton implementation here: + # https://github.com/triton-lang/triton/blob/98b5945d2aef679e00ebca8e07c35c3658ec76de/python/triton/runtime/jit.py#L238 + # `None` is nullptr. Implicitly convert to *i8. + if key is None: + return "*i8" + dtype_str = str(key).split(".")[-1] + tys = { + "bool": "i1", + "float8e4nv": "fp8e4nv", + "float8e5": "fp8e5", + "float8e4b15": "fp8e4b15", + "float8e4b15x4": "fp8e4b15x4", + "float8_e4m3fn": "fp8e4nv", + "float8_e5m2": "fp8e5", + "float8_e4m3fnuz": "fp8e4b8", + "float8_e5m2fnuz": "fp8e5b16", + # TODO: remove when support is added in triton + # https://github.com/triton-lang/triton/issues/6054 + "float8_e8m0fnu": "u8", + "float4_e2m1fn_x2": "u8", + "float16": "fp16", + "bfloat16": "bf16", + "float32": "fp32", + "float64": "fp64", + "int8": "i8", + "int16": "i16", + "int32": "i32", + "int64": "i64", + "uint8": "u8", + "uint16": "u16", + "uint32": "u32", + "uint64": "u64", + } + # reinterpret can create triton type + tys.update({v: v for v in list(tys.values())}) + return key if isinstance(key, str) else f"*{tys[dtype_str]}" + + +def convert_shape_to_inductor( + lst: Iterable[int | torch.SymInt], +) -> list[sympy.Expr]: + """ + Gets the shape and stride of a tensor. For non-symbolic tensors, this is + trivial. But for symbolic tensors, we need to map from SymIntNode into + sympy.Expr. + """ + return [sympy.sympify(i) for i in lst] + + +def convert_symint_to_expr(val: int | torch.SymInt) -> int | sympy.Expr: + """ + Convert SymInt to sympy.Expr, leave int as is. + + Unlike sympy.sympify() which converts int to sympy.Integer, + this function preserves int as int and only converts SymInt to Expr. + """ + if isinstance(val, torch.SymInt): + return val.node.expr + return val + + +def convert_to_symint(i: int | sympy.Expr) -> int | torch.SymInt: + """ + Like convert_shape_to_symint, but operates on a single expression. + """ + from .virtualized import V + + return ( + i + if isinstance(i, int) + else ( + int(i) + if isinstance(i, sympy.Integer) + else V.graph.sizevars.shape_env.create_symintnode(i, hint=None) + ) + ) + + +def convert_shape_to_symint( + lst: Iterable[int | sympy.Expr], +) -> list[int | torch.SymInt]: + """ + Takes a list of shapes from Inductor and converts them into symints (or just + ints if all shapes are static). + """ + return [convert_to_symint(i) for i in lst] + + +def is_view(op: torch._ops.OpOverload) -> bool: + """ + Does this op overload have aliasing + """ + return any(a.alias_info is not None for a in op._schema.arguments) + + +def is_pointwise_use( + use: Node, + is_pointwise_fn: Callable[[torch._ops.OpOverload], bool] = lambda _: False, +) -> bool: + """ + Do all uses of this op have torch.Tag.pointwise or return True for optional `is_pointwise_fn` + + Uses in views ops will follow the views uses + """ + + if use.op != "call_function": + return False + if not ( + isinstance(use.target, torch._ops.OpOverload) or use.target is operator.getitem + ): + return False + + target = cast(torch._ops.OpOverload, use.target) + if target is operator.getitem or is_view(target): + return all(is_pointwise_use(u, is_pointwise_fn) for u in use.users) + + return torch.Tag.pointwise in target.tags or is_pointwise_fn(target) + + +def gen_gm_and_inputs( + target: Any, args: list[Any], kwargs: dict[str, Any] +) -> tuple[GraphModule, list[torch.Tensor]]: + g = torch.fx.Graph() + graph_args: list[torch.Tensor] = [] + + def add_tensor_arg(arg: torch.Tensor) -> Node: + graph_args.append(arg) + return g.placeholder(f"arg{len(graph_args)}") + + node = g.call_function( + target, *tree_map_only(torch.Tensor, add_tensor_arg, (args, kwargs)) + ) + if ( + len(target._schema.returns) == 1 + and str(target._schema.returns[0].type) == "Tensor" + ): + node = (node,) # type: ignore[assignment] + g.output(node) + + gm = torch.fx.GraphModule({}, g) + return gm, graph_args + + +def synchronize(device: str = "cuda") -> None: + if device == "cpu": + return + device_interface = get_interface_for_device(device) + if device_interface.is_available(): + device_interface.synchronize() + + +def timed( + model: Callable[..., Any], + example_inputs: Sequence[Any], + times: int = 1, + device: str = "cuda", +) -> float: + synchronize(device) + torch.manual_seed(1337) + t0 = time.perf_counter() + for _ in range(times): + result = model(*example_inputs) + synchronize(device) + t1 = time.perf_counter() + # GC the result after timing + if result is None: # type: ignore[possibly-undefined] + raise AssertionError("Expected result to be not None after timed execution") + return t1 - t0 + + +def print_performance( + model: Callable[..., Any], + example_inputs: Sequence[Any] = (), + times: int = 10, + repeat: int = 10, + baseline: float = 1.0, + device: str = "cuda", +) -> float: + timings = torch.tensor( + [timed(model, example_inputs, times, device) for _ in range(repeat)] + ) + took = torch.median(timings) / times + print(f"{took / baseline:.6f}") + return took.item() + + +def precompute_method(obj: Any, method: str) -> None: + """Replace obj.method() with a new method that returns a precomputed constant.""" + result = getattr(obj, method)() + setattr(obj, method, lambda: result) + + +def precompute_methods(obj: Any, methods: list[str]) -> None: + """Replace methods with new methods that returns a precomputed constants.""" + for method in methods: + precompute_method(obj, method) + + +def cmp(a: int, b: int) -> int: + return int(a > b) - int(a < b) + + +def pad_listlike(x: int | Sequence[int], size: int) -> Sequence[int]: + if isinstance(x, int): + return [x] * size + if len(x) == 1: + return type(x)([x[0]]) * size # type: ignore[call-arg, operator, return-value] + return x + + +# Used to ensure that iterating over a set is deterministic +def tuple_sorted(x: tuple[_T, ...]) -> list[_T]: + if len(x) == 0: + return [] + + def sort_func(elem: _T) -> str: + if isinstance(elem, str): + return elem + + from .scheduler import BaseSchedulerNode + + if not isinstance(elem, BaseSchedulerNode): + raise AssertionError(f"Expected BaseSchedulerNode, got {type(elem)}") + return elem.get_name() + + return sorted(x, key=sort_func) + + +P = ParamSpec("P") +RV = TypeVar("RV", covariant=True) +FN_TYPE = Callable[Concatenate[Any, P], RV] + + +class CachedMethod(Protocol, Generic[P, RV]): + @staticmethod + def clear_cache(cache: Any) -> None: ... + + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> RV: ... + + +# See https://github.com/python/mypy/issues/13222#issuecomment-1193073470 to understand the type signature +def cache_on_self(fn: Callable[Concatenate[Any, P], RV]) -> CachedMethod[P, RV]: + name = fn.__name__ + key = f"__{name}_cache" + + # wrapper is likely on the hot path, compile a specialized version of it + ctx = {"fn": fn} + exec( + f"""\ + def {name}_cache_on_self(self): + try: + return self.{key} + except AttributeError: + pass + rv = fn(self) + object.__setattr__(self, "{key}", rv) + return rv + """.lstrip(), + ctx, + ) + wrapper = functools.wraps(fn)(ctx[f"{name}_cache_on_self"]) + + def clear_cache(self: Any) -> None: + if hasattr(self, key): + delattr(self, key) + + wrapper.clear_cache = clear_cache # type: ignore[attr-defined] + return wrapper # type: ignore[return-value] + + +def cache_property_on_self( + fn: Callable[Concatenate[Any, P], RV], +) -> CachedMethod[P, RV]: + """ + Variant of cache_on_self for properties. The only difference is the type signature. + """ + + return cache_on_self(fn) + + +def cache_on_self_and_args( + class_name: str, +) -> Callable[[FN_TYPE[P, RV]], FN_TYPE[P, RV]]: + # include both class_name and fn_name in the key to support `super().fn(self, **args, **kwargs)` calls. + + def wrapper( + fn: FN_TYPE[P, RV], + ) -> FN_TYPE[P, RV]: + key = f"__{class_name}_{fn.__name__}_cache" + + # wrapper is likely on the hot path, compile a specialized version of it + ctx = {"fn": fn} + exec( + f"""\ + def inner(self: Any, *args: P.args, **kwargs: P.kwargs) -> RV: + args_kwargs = (args, tuple(sorted(kwargs.items()))) + + if not hasattr(self, "{key}"): + object.__setattr__(self, "{key}", {{}}) + + cache = self.{key} + + try: + return cache[args_kwargs] + except KeyError: + pass + + rv = fn(self, *args, **kwargs) + + cache[args_kwargs] = rv + return rv + """.lstrip(), + ctx, + ) + inner = functools.wraps(fn)(ctx["inner"]) + + def clear_cache(self: Any) -> None: + if hasattr(self, key): + delattr(self, key) + + inner.clear_cache = clear_cache # type: ignore[attr-defined] + return inner + + return wrapper + + +def aggregate_origins( + node_schedule: Sequence[BaseSchedulerNode] | ExternKernel, +) -> OrderedSet[Node]: + from . import ir + + if isinstance(node_schedule, list): + return functools.reduce( + operator.or_, + [ + # pyrefly: ignore [missing-attribute] + node.node.origins + for node in node_schedule + if hasattr(node, "node") and node.node + ], + OrderedSet(), + ) + elif isinstance(node_schedule, ir.ExternKernel): + return node_schedule.origins + else: + return OrderedSet() + + +def get_fused_kernel_name( + node_schedule: Sequence[BaseSchedulerNode], + descriptive_names: Literal[True, "torch", "original_aten", "inductor_node"], +) -> str: + all_origins = aggregate_origins(node_schedule) + if descriptive_names == "original_aten": + + def get_origin_meta_str(origin): + original_aten = origin.meta["original_aten"] + key = "" + if isinstance(original_aten, torch._ops.OpOverload): + key = original_aten._overloadpacket.__name__ + elif isinstance(original_aten, torch._ops.HigherOrderOperator): + key = str(original_aten.name()) + return key + + # Bases the kernel name off of the top-level aten operator (i.e. pre-decompositions) + sources = [ + get_origin_meta_str(origin) + for origin in all_origins + if origin.op == "call_function" + and "original_aten" in origin.meta + and origin.meta["original_aten"] is not None + ] + sources = sorted(OrderedSet(sources)) + elif descriptive_names == "torch": + # Bases the kernel name off of the top-level "torch" operator (i.e. post-dynamo graph) + sources = [] + for origin in all_origins: + if origin.op == "call_function": + source_fn = None + suffix = "" + if "source_fn_stack" in origin.meta: + source_fn = origin.meta["source_fn_stack"][-1] + elif "fwd_source_fn_stack" in origin.meta: + # backward nodes have "fwd_source_fn_stack" instead + source_fn = origin.meta["fwd_source_fn_stack"][-1] + suffix = "backward" + if not source_fn: + continue + if isinstance(source_fn[1], str): + sources.append(source_fn[1] + suffix) + else: + sources.append(source_fn[1].__name__ + suffix) + + sources = sorted(OrderedSet(sources)) + elif descriptive_names == "inductor_node": + sources = [ + origin.name for origin in all_origins if origin.op == "call_function" + ] + else: + raise NotImplementedError + name = "_".join(["fused"] + sources) + # On Windows the default MAX_PATH (260) limit means a long descriptive + # kernel name can push the Triton cache path past the limit, making the + # generated .ttir unopenable. Cap the name and append a hash to keep it + # both short and unique. + if is_windows() and len(name) > 50: + h = hashlib.sha256(name.encode("utf-8")).hexdigest()[:8] + name = f"{name[:41].rstrip('_')}_{h}" + return name + + +def get_kernel_metadata( + node_schedule: Sequence[BaseSchedulerNode] | ExternKernel, + wrapper: PythonWrapperCodegen, +) -> tuple[str, str]: + """ + Retrieves metadata information for a kernel. + Args: + node_schedule (Union[Sequence[BaseSchedulerNode], ExternKernel]): + Either a sequence of BaseSchedulerNode objects or an ExternKernel instance. + wrapper (PythonWrapperCodegen): + An instance of PythonWrapperCodegen, used to define the code comment format. + Returns: + tuple[str, str]: + A tuple containing two strings: + - The first string represents the kernel's metadata. + - The second string represent the kernel's detailed metadata. + """ + + all_origins = aggregate_origins(node_schedule) + inductor_nodes = [origin for origin in all_origins if origin.op == "call_function"] + + from_node_dict = collections.defaultdict(list) + original_aten_dict = collections.defaultdict(list) + + # Attempt to sort `inductor_nodes` topologically. Note that the case + # where `inductor_nodes` contains nodes from multiple graph instances + # is not supported. An example of this is conditional statements. + single_graph = None + if inductor_nodes: + unique_graphs = OrderedSet(n.graph for n in inductor_nodes) + if len(unique_graphs) == 1: + single_graph = inductor_nodes[0].graph + # create a map of idx -> node and cache it + if not hasattr(single_graph, "_inductor_kernel_metadata_node_to_idx_map"): + node_to_idx_map = {n: idx for idx, n in enumerate(single_graph.nodes)} + single_graph._inductor_kernel_metadata_node_to_idx_map = node_to_idx_map # type: ignore[attr-defined] + inductor_nodes.sort( + key=lambda n: single_graph._inductor_kernel_metadata_node_to_idx_map[n] # type: ignore[attr-defined] + ) + + for node in inductor_nodes: + if "original_aten" in node.meta and node.meta["original_aten"] is not None: + original_aten = node.meta["original_aten"] + key = None + if isinstance(original_aten, torch._ops.OpOverload): + key = str(original_aten._overloadpacket) + elif isinstance(original_aten, torch._ops.HigherOrderOperator): + key = str(original_aten.name()) + if key: + original_aten_dict[key].append(node.name) + if "from_node" in node.meta: + key = node.meta["from_node"][0].name + from_node_dict[key].append(node.name) + elif node.meta.get("partitioner_tag") == "is_backward": + # backward nodes currently don't have a "from node" + from_node_dict[node.name].append(node.name) + sort_str = "Topologically Sorted" if single_graph is not None else "Unsorted" + metadata = ( + f"{wrapper.comment} {sort_str} Source Nodes: [{', '.join(from_node_dict.keys())}], " + f"Original ATen: [{', '.join(original_aten_dict.keys())}]" + ) + + # trace back to original node here + detailed_metadata = [f"{wrapper.comment} Source node to ATen node mapping:"] + for original_node, nodes in sorted(from_node_dict.items()): + detailed_metadata.append( + f"{wrapper.comment} {original_node} => {', '.join(sorted(nodes))}" + ) + + # print the aot_autograd graph fragment + if single_graph is not None: + from . import ir + + detailed_metadata.append(f"{wrapper.comment} Graph fragment:") + all_reads: OrderedSet[str] = OrderedSet() + all_writes: list[str] = [] + if not isinstance(node_schedule, ir.ExternKernel): + from .virtualized import V + + def get_buffer_info( + buffer: ir.TensorBox | ir.Buffer | ir.TorchBindObject, rw_name: str + ) -> tuple[str, ir.Layout | None]: + if isinstance(buffer, ir.TensorBox) and isinstance( + buffer.data, ir.StorageBox + ): + origin_node = buffer.data.data.origin_node + else: + origin_node = buffer.origin_node + if origin_node is None: + # use the read/write name if no origin node is found + name = rw_name + else: + name = origin_node.name + try: + layout = buffer.get_layout() + except NotImplementedError: + layout = None + return name, layout + + def stringify_shape(shape: Iterable[int]) -> str: + return f"[{', '.join([str(x) for x in shape])}]" + + def stringfy_layout(layout: ir.Layout | None) -> str: + if layout is None: + return "" + shape_annotation = f"{stringify_shape(layout.size)}" + stride_annotation = f"{stringify_shape(layout.stride)}" + # Under compile-on-one-rank, render the bare device type so this kernel + # provenance comment is byte-identical across ranks. + from torch.fx.experimental.proxy_tensor import _coor_enabled + + device = layout.device + device_annotation = ( + device.type + if (_coor_enabled() and device is not None) + else f"{device}" + ) + + return ( + f'"{dtype_abbrs[layout.dtype]}{shape_annotation}' + f'{stride_annotation}{device_annotation}"' + ) + + for n in node_schedule: + if not hasattr(n, "read_writes") or n.read_writes is None: + continue + if hasattr(n.read_writes, "reads") and n.read_writes.reads is not None: + for r in n.read_writes.reads: + # Remove the duplicated inputs + if r.name in all_reads: + continue + all_reads.add(r.name) + buffer = V.graph.try_get_buffer(r.name) + if buffer is None: + continue + input_name, layout = get_buffer_info(buffer, r.name) + detailed_metadata.append( + f"{wrapper.comment} %{input_name} : Tensor " + f"{stringfy_layout(layout)} = PlaceHolder[target={input_name}]" + ) + + if ( + hasattr(n.read_writes, "writes") + and n.read_writes.writes is not None + ): + for w in n.read_writes.writes: + buffer = V.graph.try_get_buffer(w.name) + if buffer is None: + continue + output_name, _ = get_buffer_info(buffer, w.name) + + all_writes.append("%" + output_name) + + for node in inductor_nodes: + formatted_node = node.format_node(include_tensor_metadata=True) + if formatted_node is not None and torch.version.hip: + # AMDGCN asm strings can contain newlines, which propagate + # into format_node() output. Split so every line gets the + # comment prefix; otherwise bare newlines break the wrapper. + detailed_metadata.extend( + f"{wrapper.comment} {line}" + for line in formatted_node.splitlines() + ) + else: + detailed_metadata.append(f"{wrapper.comment} {formatted_node}") + + detailed_metadata.append(f"{wrapper.comment} return {','.join(all_writes)}") + + return metadata, "\n".join(detailed_metadata) + + +def dominated_nodes( + initial_queue: Iterable[torch.fx.Node], + skip_filter: Callable[[Any], bool] | None = None, +) -> OrderedSet[torch.fx.Node]: + """Returns the set of nodes whose values depend on those within initial_queue""" + initial_queue = list(initial_queue) + dominated_set = OrderedSet(initial_queue) + + while initial_queue: + node = initial_queue.pop() + for user in node.users: + if skip_filter and skip_filter(user): + continue + if user not in dominated_set: + dominated_set.add(user) + initial_queue.append(user) + + return dominated_set + + +def gather_origins( + args: Sequence[IRNode], kwargs: dict[str, IRNode] +) -> OrderedSet[torch.fx.Node]: + from . import ir + + def is_unrealized_node(n: IRNode) -> bool: + if isinstance(n, ir.TensorBox): + return is_unrealized_node(n.data) + if isinstance(n, ir.StorageBox): + return is_unrealized_node(n.data) + return isinstance(n, ir.IRNode) and not isinstance( + n, + ( + ir.ComputedBuffer, + ir.InputsKernel, + ir.InputBuffer, + ir.TemplateBuffer, + ), + ) + + # kwargs and args may include a container of node, for example torch.cat([t1, t2]) + # flatten them before search the unrealized nodes + kwargs_flatten, _ = tree_flatten(kwargs) + kwargs_origins = [val.origins for val in kwargs_flatten if is_unrealized_node(val)] + args_flatten, _ = tree_flatten(args) + args_origins = [val.origins for val in args_flatten if is_unrealized_node(val)] + return OrderedSet(itertools.chain(*args_origins, *kwargs_origins)) + + +def sympy_str(expr: sympy.Expr) -> str: + """ + Normal sympy str is very slow, this is a lot faster. The result are + somewhat worse, as it doesn't do as much simplification. So don't + use this for final codegen. + """ + + def is_neg_lead(expr: sympy.Expr) -> bool: + return ( + isinstance(expr, sympy.Mul) and len(expr.args) == 2 and expr.args[0] == -1 + ) + + def sympy_str_add(expr: sympy.Expr) -> str: + if isinstance(expr, sympy.Add): + # Special case 'a - b'. Note that 'a - b - c' will still appear as + # 'a + -1 * b + -1 * c'. + if len(expr.args) == 2 and is_neg_lead(expr.args[1]): + return f"{sympy_str_mul(expr.args[0])} - {sympy_str_mul(expr.args[1].args[1])}" + else: + return " + ".join(map(sympy_str_mul, expr.args)) + else: + return sympy_str_mul(expr) + + def sympy_str_mul(expr: sympy.Expr) -> str: + if isinstance(expr, sympy.Mul): + if is_neg_lead(expr): + # Special case '-a'. Note that 'a * -b' will still appear as + # '-1 * a * b'. + return f"-{sympy_str_atom(expr.args[1])}" + else: + return " * ".join(map(sympy_str_atom, expr.args)) + else: + return sympy_str_atom(expr) + + def sympy_str_atom(expr: sympy.Expr) -> str: + if isinstance(expr, sympy.Symbol): + return expr.name + elif isinstance(expr, (sympy.Add, sympy.Mul)): + return f"({sympy_str_add(expr)})" + elif isinstance(expr, (ModularIndexing, CleanDiv, FloorDiv, Identity)): + return f"{expr.func.__name__}({', '.join(map(sympy_str, expr.args))})" + else: + return str(expr) + + return sympy_str_add(expr) + + +def get_bounds_index_expr(index: sympy.Expr) -> ValueRanges[Any]: + from .virtualized import V + + # If this expression does not come from an FX node, we compute its bounds + if ( + config.compute_all_bounds + and (fx_node := getattr(V.interpreter, "current_node", None)) + and fx_node.target != "index_expr" + ): + return bound_sympy(index) + else: + return ValueRanges.unknown() + + +def prefix_is_reduction(prefix: str) -> bool: + return prefix[0] == "r" + + +def prefix_is_pointwise(prefix: str) -> bool: + return prefix[0] in ("x", "y", "z") + + +def sympy_index_symbol_with_prefix(prefix: SymT, idx: int) -> sympy.Symbol: + """ + Used to generate an integer-nonnegative symbol. + """ + # This should never be used for creating shape/stride symbols, as those + # should all be allocated before Inductor. + if prefix == SymT.SIZE: + raise AssertionError(f"prefix must not be SymT.SIZE, got {prefix}") + # NOTE: shape symbols are positive (> 0), but index variables are only + # non-negative (>= 0). + return make_symbol(prefix, idx, integer=True, nonnegative=True) + + +def generate_assert(check: bool) -> bool: + return (check or config.debug_index_asserts) and config.assert_indirect_indexing + + +def sympy_index_symbol(name: str) -> sympy.Symbol: + """ + Used to generate an integer-nonnegative symbol. + """ + # This should never be used for creating shape/stride symbols, as those + # should all be allocated before Inductor. + if name[0] == "s": + raise AssertionError(f"Symbol name must not start with 's', got {name!r}") + # NOTE: shape symbols are positive (> 0), but index variables are only + # non-negative (>= 0). + return sympy.Symbol(name, integer=True, nonnegative=True) + + +def sympy_subs(expr: sympy.Expr, replacements: dict[sympy.Expr, Any]) -> sympy.Expr: + """ + When the passed replacement symbol v is a string, it is converted to a symbol with name v that + have the same replaced expression integer and nonnegative properties. + """ + return _sympy_subs(expr, replacements) + + +def is_symbolic(a: Any) -> TypeGuard[torch.SymInt | torch.Tensor]: + return isinstance(a, torch.SymInt) or ( + isinstance(a, torch.Tensor) and a._has_symbolic_sizes_strides + ) + + +def any_is_symbolic(*args: Any) -> bool: + return any(is_symbolic(a) for a in args) + + +# Ops that are fundamentally incompatible with CUDA graph capture +# (e.g., CPU synchronization, dynamic memory allocation, etc.) +FORBIDDEN_CUDAGRAPH_OPS = frozenset( + [ + "aten._fused_moving_avg_obs_fq_helper.default", + "aten._fused_moving_avg_obs_fq_helper_functional.default", + "fbgemm.dense_to_jagged.default", + "fbgemm.jagged_to_padded_dense.default", + "run_and_save_rng_state", + "run_with_rng_state", + "aten._local_scalar_dense", + # cuSOLVER-backed linalg.eigh is not CUDA graph capturable. + "aten._linalg_eigh.default", + # Technically, it's not necessary to ban this, because an + # assert_scalar with constant arguments can be validly run + # with CUDA graphs, but the operator is also pointless with + # constant arguments, so might as well ban + "aten._assert_scalar", + ] + + ( + # rocm workaround: topk kernels fault under cudagraph trees + # on the 2nd replay of a recorded graph. + [ + "aten.topk.default", + ] + if torch.version.hip is not None + else [] + ) +) + + +def get_first_incompatible_cudagraph_node( + gm: torch.fx.GraphModule, +) -> torch.fx.Node | None: + from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols + + for node in gm.graph.nodes: + if is_cudagraph_unsafe_fx_node(node): + return node + + if (val := node.meta.get("val")) is not None and free_unbacked_symbols(val): + return node + + return None + + +def output_node(gm: torch.fx.GraphModule) -> Node: + """Get the output node from an FX graph""" + last_node = next(iter(reversed(gm.graph.nodes))) + if last_node.op != "output": + raise AssertionError( + f"Expected last node op to be 'output', got {last_node.op!r}" + ) + return last_node + + +def get_all_devices(gm: torch.fx.GraphModule) -> OrderedSet[torch.device]: + placeholder_nodes = gm.graph.find_nodes(op="placeholder") + input_devices: OrderedSet[torch.device] = OrderedSet( + node.meta["val"].device + for node in placeholder_nodes + if isinstance(node.meta.get("val"), torch.Tensor) + ) + + out_arg = output_node(gm).args[0] # type: ignore[union-attr] + out_args = out_arg if isinstance(out_arg, tuple) else (out_arg,) + out_devices: OrderedSet[torch.device] = OrderedSet( + arg.meta["val"].device + for arg in out_args + if isinstance(arg, torch.fx.Node) + and isinstance(arg.meta.get("val"), torch.Tensor) + ) + return input_devices | out_devices + + +import gc + + +def unload_xpu_triton_pyds() -> None: + # unload __triton_launcher.pyd + for module_name in list(sys.modules.keys()): + if not module_name.startswith("torch._inductor.runtime.compile_tasks."): + continue + m = sys.modules[module_name] + for attr_name in m.__dict__: + if attr_name.startswith("triton_"): + kernel = getattr(m, attr_name) + if isinstance( + kernel, torch._inductor.runtime.triton_heuristics.CachingAutotuner + ): + for result in kernel.compile_results: + if isinstance( + result, + torch._inductor.runtime.triton_heuristics.TritonCompileResult, + ): + # pyrefly: ignore [missing-attribute] + run = result.kernel.run + if hasattr(run, "mod"): + run.mod.__del__() + del sys.modules[module_name] + + # unload spirv_utils.pyd + if "triton.runtime.driver" in sys.modules: + driver_mod = sys.modules["triton.runtime.driver"] + if hasattr(driver_mod.driver.active, "utils"): + utils_cls = type(driver_mod.driver.active.utils) + if hasattr(utils_cls, "instance"): + del utils_cls.instance + elif hasattr(utils_cls, "_instance"): + utils_cls._instance = None + del driver_mod.driver.active.utils + + gc.collect() + + +_registered_caches: list[Any] = [] + + +def clear_on_fresh_cache(obj: Any) -> Any: + """ + Use this decorator to register any caches that should be cache_clear'd + with fresh_cache(). + """ + if not hasattr(obj, "cache_clear") or not callable(obj.cache_clear): + raise AttributeError(f"{obj} does not have a cache_clear method") + + _registered_caches.append(obj) + return obj + + +def clear_caches() -> None: + """ + Clear all registered caches. + """ + for obj in _registered_caches: + obj.cache_clear() + + +@contextlib.contextmanager +def _set_env(key: str, value: str) -> Iterator[None]: + """Thread-safe env var set/restore using atomic C-level lookups. + + We avoid mock.patch.dict(os.environ, ...) because it internally calls + os.environ.copy(), which iterates all env var keys then fetches values in + separate steps. That approach is not atomic and can race with background threads + (e.g. Triton async compilation) modifying the environment, causing KeyError, + so we use os.environ.get() for individual keys which is an atomic C-level lookup. + """ + old = os.environ.get(key) + try: + os.environ[key] = value + yield + finally: + if old is None: + os.environ.pop(key, None) + else: + os.environ[key] = old + + +@contextlib.contextmanager +def fresh_cache( + cache_entries: dict[str, Any] | None = None, + dir: str | None = None, + delete: bool = True, +) -> Iterator[None]: + """ + Contextmanager that provides a clean tmp cachedir for pt2 caches. + + Optionally, pass a dict as 'cache_entries' to get a list of filenames and sizes + generated with this cache instance. + """ + clear_caches() + + from torch._inductor.cpp_builder import normalize_path_separator + + inductor_cache_dir = normalize_path_separator(tempfile.mkdtemp(dir=dir)) + try: + with _set_env("TORCHINDUCTOR_CACHE_DIR", inductor_cache_dir): + log.debug("Using inductor cache dir %s", inductor_cache_dir) + triton_cache_dir = normalize_path_separator( + os.path.join(inductor_cache_dir, "triton") + ) + with _set_env("TRITON_CACHE_DIR", triton_cache_dir): + yield + if isinstance(cache_entries, dict): + if len(cache_entries) != 0: + raise AssertionError("expected empty cache_entries dict") + if os.path.exists(triton_cache_dir): + files = os.listdir(triton_cache_dir) + cache_entries.update( + { + f: os.path.getsize(os.path.join(triton_cache_dir, f)) + for f in files + if ".lock" not in f + } + ) + if delete: + if is_windows() and torch.xpu.is_available(): + unload_xpu_triton_pyds() + + shutil.rmtree( + inductor_cache_dir, + # Let's not fail if we can't clean up the temp dir. Also note that for + # Windows, we can't delete the loaded modules because the module binaries + # are open. + ignore_errors=is_windows(), + onerror=lambda func, path, exc_info: log.warning( + "Failed to remove temporary cache dir at %s", + inductor_cache_dir, + exc_info=exc_info, + ), + ) + except Exception: + log.warning("on error, temporary cache dir kept at %s", inductor_cache_dir) + raise + finally: + clear_caches() + + +# Deprecated functions -- only keeping them for BC reasons +clear_on_fresh_inductor_cache = clear_on_fresh_cache +clear_inductor_caches = clear_caches +fresh_inductor_cache = fresh_cache + + +def argsort(seq: Sequence[Any], *, reverse: bool = False) -> list[int]: + getter = seq.__getitem__ + a_r = range(len(seq)) + # preserve original order for equal strides + # e.g. if strides are [32, 8, 8, 1] + # argsort -> [3, 2, 1, 0], rather than + # [3, 1, 2, 0] + # i.e. for equal strides in ascending order (reverse=False) an + # inner dimension should come before an outer dimension, and vice versa + # for descending + sort_idx = list(sorted(a_r, key=getter, reverse=True)) # noqa: C413 + if not reverse: + return list(reversed(sort_idx)) + return sort_idx + + +def argsort_sym( + shape_env: ShapeEnv, + seq: Sequence[int | torch.SymInt | sympy.Expr], + *, + reverse: bool = False, +) -> list[int]: + """ + Return a symbolic sort order for optimization-only layout heuristics. + + Data-dependent comparisons can fall back to non-guarding optimization hints, + so callers must not use this order to make correctness decisions. + """ + + def cmp(a: tuple[int, sympy.Expr], b: tuple[int, sympy.Expr]) -> int: + a_idx, a_val = a + b_idx, b_val = b + + def evaluate( + expr: bool | torch.SymInt | sympy.Expr, + fallback: Callable[[], bool], + ) -> bool: + if isinstance(expr, bool): + return expr + try: + return shape_env.evaluate_expr(expr) + except GuardOnDataDependentSymNode: + return fallback() + + def hint_lt(lhs: sympy.Expr, rhs: sympy.Expr) -> bool: + # Stride sorting is an optimization-only ordering decision. Keep + # semantic reasoning symbolic first, then fall back to explicit + # optimization hints when unbacked comparisons are data-dependent. + return shape_env.optimization_hint(lhs) < shape_env.optimization_hint(rhs) + + if evaluate(a_val < b_val, lambda: hint_lt(a_val, b_val)): + return -1 + if evaluate(a_val > b_val, lambda: hint_lt(b_val, a_val)): + return 1 + # If strides are the same, prefer the original order. + # (this matches argsort's algorithm). + # For strides = [2048, 2048, 16, 1], this is + # [3, 2, 1, 0]. + if a_idx < b_idx: + return 1 + if a_idx > b_idx: + return -1 + return 0 + + # Strategy: convert all symints to sympy.Expr, then use a custom comparator + exprs = [ + (idx, s.node.expr if isinstance(s, torch.SymInt) else s) + for idx, s in enumerate(seq) + ] + exprs = sorted(exprs, key=functools.cmp_to_key(cmp), reverse=reverse) + result = [idx for idx, _ in exprs] + return result + + +@functools.lru_cache(8) +def get_dtype_size(dtype: torch.dtype) -> int: + # TODO: Investigate why uint64 tensor creation causes overflow error: + # Workaround for RuntimeError in memory size calculation, but underlying cause unclear + if dtype == torch.uint64: + return 8 + return torch.empty((), dtype=dtype).element_size() + + +class DualIndentedBuffer(IndentedBuffer): + """IndentedBuffer that simultaneously accumulates JIT and AOTI output. + + The base class (self._lines) holds JIT content. self.aot holds AOTI content. + By default, writeline/splice write to both. Use _jit/_aot variants for + mode-specific writes. + """ + + def __init__(self, initial_indent: int = 0) -> None: + super().__init__(initial_indent) + self.aot = IndentedBuffer(initial_indent) + + @property + def jit(self) -> IndentedBuffer: + """Read-only accessor for JIT buffer (for splicing into result). + + WARNING: Do NOT use jit for writing — writes would go to both buffers + because self.writeline is overridden. Use writeline_jit/splice_jit instead. + """ + return self # type: ignore[return-value] + + def writeline(self, line): # type: ignore[override] + IndentedBuffer.writeline(self, line) + self.aot.writeline(line) + + def writeline_jit(self, line) -> None: + IndentedBuffer.writeline(self, line) + + def writeline_aot(self, line) -> None: + self.aot.writeline(line) + + def writelines(self, lines): # type: ignore[override] + for line in lines: + self.writeline(line) + + def splice(self, other_code, strip: bool = False) -> None: # type: ignore[override] + # Splice into each buffer independently. When other_code is itself a + # DualIndentedBuffer, each side reads from the matching side. + IndentedBuffer.splice(self, other_code, strip=strip) + aot_other = ( + other_code.aot if isinstance(other_code, DualIndentedBuffer) else other_code + ) + self.aot.splice(aot_other, strip=strip) + + def splice_jit(self, other_code, strip: bool = False) -> None: + IndentedBuffer.splice(self, other_code, strip=strip) + + def splice_aot(self, other_code, strip: bool = False) -> None: + aot_other = ( + other_code.aot if isinstance(other_code, DualIndentedBuffer) else other_code + ) + self.aot.splice(aot_other, strip=strip) + + def indent(self, offset: int = 1): + @contextlib.contextmanager + def ctx(): + self._indent += offset + self.aot._indent += offset + try: + yield + finally: + self._indent -= offset + self.aot._indent -= offset + + return ctx() + + def do_indent(self, offset: int = 1) -> None: + self._indent += offset + self.aot._indent += offset + + def do_unindent(self, offset: int = 1) -> None: + self._indent -= offset + self.aot._indent -= offset + + def clear(self) -> None: + super().clear() + self.aot.clear() + + +class AotOnlyBuffer(IndentedBuffer): + """IndentedBuffer for pure-AOTI codegen. + + Mirror of the base class's pure-JIT defaults: writeline_aot/splice_aot + write to the buffer; writeline_jit/splice_jit are no-ops. Lets call + sites use writeline_jit/writeline_aot uniformly across pure-JIT, + pure-AOTI, and dual-wrapper modes. + """ + + def writeline_jit(self, line) -> None: + pass + + def writeline_aot(self, line) -> None: + self.writeline(line) + + def splice_jit(self, other_code, strip: bool = False) -> None: + pass + + def splice_aot(self, other_code, strip: bool = False) -> None: + self.splice(other_code, strip=strip) + + +def make_codegen_buffer() -> IndentedBuffer: + """Construct the IndentedBuffer subclass matching the current codegen mode. + + Dual-wrapper mode -> DualIndentedBuffer (JIT and AOTI both active). + Pure AOTI -> AotOnlyBuffer (writeline_aot writes; writeline_jit drops). + Pure JIT -> IndentedBuffer (writeline_jit writes; writeline_aot drops). + """ + from .virtualized import V + + if V.graph.is_dual_wrapper_mode: + return DualIndentedBuffer() + if V.graph.aot_mode: + return AotOnlyBuffer() + return IndentedBuffer() + + +class FakeIndentedBuffer(IndentedBuffer): + def __init__(self) -> None: + super().__init__() + + def __getattribute__(self, name: str) -> Any: + if name == "__class__": # Allow access to the class attribute + return object.__getattribute__(self, name) + raise RuntimeError( + f"Tried to call self.{name} on FakeIndentedBuffer. This buffer" + "is currently used on TritonTemplateKernel to prevent actual" + "writes to the body without explicitly specifying the body with" + "`TritonTemplateKernel.set_subgraph_body(name)`" + ) + + +@contextlib.contextmanager +def restore_stdout_stderr() -> Iterator[None]: + initial_stdout, initial_stderr = sys.stdout, sys.stderr + try: + yield + finally: + sys.stdout, sys.stderr = initial_stdout, initial_stderr + + +class DelayReplaceLine(DeferredLineBase): + """At end of codegen call `line.replace(key, value_fn())`""" + + def __init__(self, key: str, value_fn: Callable[[], str], line: str): + super().__init__(line) + self.key = key + self.value_fn = value_fn + + def __call__(self) -> str: + return self.line.replace(self.key, self.value_fn()) + + def _new_line(self, line: str) -> DelayReplaceLine: + return DelayReplaceLine(self.key, self.value_fn, line) + + +@functools.cache +def is_big_gpu(index_or_device: int | torch.device = 0) -> bool: + if isinstance(index_or_device, torch.device): + device = index_or_device + else: + device = torch.device(get_gpu_type(), index_or_device) + + prop = DeviceProperties.create(device) + + # SM logic is not relevant to ROCm gpus + # Arbitrarily skipping the older models + if torch.version.hip: + if prop.major is None: + raise AssertionError("DeviceProperties.major is None for ROCm GPU") + if prop.major < 9 or prop.major == 10: + log.warning("GPU arch does not support max_autotune_gemm mode usage") + return False + return True + + min_sms = 16 if device.type == "xpu" else 68 # 3080 + avail_sms = prop.multi_processor_count + if avail_sms < min_sms: + log.warning( + "Not enough SMs to use max_autotune_gemm mode", + extra={"min_sms": min_sms, "avail_sms": avail_sms}, + ) + return False + return True + + +@functools.lru_cache +def get_max_num_sms() -> int: + if torch.xpu.is_available(): + return torch.xpu.get_device_properties().gpu_subslice_count + return torch.cuda.get_device_properties("cuda").multi_processor_count + + +@functools.lru_cache +def using_b200() -> bool: + """Returns true if the device is a NVIDIA B200, otherwise returns false.""" + if not torch.cuda.is_available(): + return False + # compute capability 10.0 or 10.0a is NVIDIA B200 + device_properties = torch.cuda.get_device_properties(torch.cuda.current_device()) + return device_properties.major == 10 + + +def is_nvidia_sm100_or_later() -> bool: + """Return true for NVIDIA CUDA devices with compute capability SM100+.""" + return ( + torch.cuda.is_available() + and torch.version.hip is None + and torch.cuda.get_device_capability() >= (10, 0) + ) + + +def get_num_sms() -> int: + """Handle experimental carveout if set otherwise return hardware SM count""" + # TODO we need to properly guard on this global + if torch.xpu.is_available(): + return get_max_num_sms() + carveout = torch._C._get_sm_carveout_experimental() + return get_max_num_sms() - (carveout if carveout is not None else 0) + + +def get_tma_workspace_arg( + num_tma_descriptors: int, + device: torch.device, + num_programs: int | None = None, +) -> WorkspaceArg: + """Builds and returns a WorkspaceArg for the device side TMA workspace buffer.""" + from .codegen.common import WorkspaceArg, WorkspaceZeroMode + + if num_programs is None: + num_programs = get_num_sms() + zero_mode = WorkspaceZeroMode.from_bool(False) + size = num_programs * num_tma_descriptors * TMA_DESCRIPTOR_SIZE + return WorkspaceArg( + count=size, + zero_mode=zero_mode, + device=device, + outer_name=WorkspaceArg.unique_name(), + ) + + +def get_default_kpack(block_k: int = 16) -> int: + if not torch.version.hip: + return 0 + if "gfx942" in torch.cuda.get_device_properties(0).gcnArchName and block_k <= 16: + return 1 + return 2 + + +def _use_template_for_gpu( + layout: Layout, allowed_layout_dtypes: list[torch.dtype] +) -> bool: + if layout.dtype not in allowed_layout_dtypes: + log.debug( + "Not using template since dtype %s is not in allowed layout dtypes %s", + layout.dtype, + allowed_layout_dtypes, + ) + return ( + is_gpu(layout.device.type) + and layout.dtype in allowed_layout_dtypes + and is_big_gpu(layout.device) + ) + + +def _use_autotune_backend(backend: str) -> bool: + return backend.upper() in [ + x.strip() for x in config.max_autotune_gemm_backends.upper().split(",") + ] + + +def _use_conv_autotune_backend(backend: str) -> bool: + return backend.upper() in [ + x.strip() for x in config.max_autotune_conv_backends.upper().split(",") + ] + + +def _use_conv_bwd_weight_autotune_backend(backend: str) -> bool: + return backend.upper() in [ + x.strip() + for x in config.max_autotune_conv_bwd_weight_backends.upper().split(",") + ] + + +def _use_conv_bwd_input_autotune_backend(backend: str) -> bool: + return backend.upper() in [ + x.strip() + for x in config.max_autotune_conv_bwd_input_backends.upper().split(",") + ] + + +def use_triton_template( + layout: Layout, + *, + enable_int32: bool = False, + enable_float8: bool = False, + check_max_autotune: bool = True, +) -> bool: + from .codegen.common import BackendFeature, has_backend_feature + + layout_dtypes = [torch.float16, torch.bfloat16, torch.float32] + if enable_int32: + layout_dtypes = [torch.float16, torch.bfloat16, torch.float32, torch.int32] + if enable_float8: + layout_dtypes.extend([torch.float8_e4m3fn, torch.float8_e5m2]) + return ( + ( + ( + is_gpu(layout.device.type) + and _use_template_for_gpu(layout, layout_dtypes) + ) + or (layout.device.type == "cpu" and layout.dtype in layout_dtypes) + ) + # some callers handle max-autotune checking externally + and (config.max_autotune or config.max_autotune_gemm or not check_max_autotune) + and _use_autotune_backend("TRITON") + and has_backend_feature(layout.device, BackendFeature.TRITON_TEMPLATES) + ) + + +def can_use_tma( + *matrices: IRNode, output_layout: Layout | None = None, add_guards: bool = False +) -> bool: + """ + Return True iff *all* supplied tensors satisfy the CUDA TMA constraints + that Triton relies on today. + * https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TENSOR__MEMORY.html + + A tensor is accepted when: + * 1 ≤ rank ≤ 5 (cuTensorMapEncodeTiled) + * dtype in _TMA_SUPPORTED_DTYPES (CUtensorMapDataType enum) + * Base pointer 16-byte aligned + * Exactly one contiguous ("inner") dim with stride 1 + * All "outer" dims have 16-byte aligned strides + * Inner dim size × itemsize is a multiple of 16 + * For 1-byte dtypes (e.g. FP8), inner dim ≥ 32 + """ + from torch.utils._triton import has_triton_tma_device + + from .virtualized import V + + def _aligned(expr_bytes: int | sympy.Expr) -> bool: + return V.graph.sizevars.statically_known_multiple_of(expr_bytes, TMA_ALIGNMENT) + + def _is_tma_compatible_layout(layout: Layout | None) -> bool: + if layout is None: + return True + sizes = layout.size + strides = layout.stride + dtype = layout.dtype + + # Verify the output is 16-byte aligned + if not _aligned(layout.offset): + return False + + return _is_tma_compatible(sizes, strides, dtype) + + def _is_tma_compatible_matrix(m: IRNode) -> bool: + sizes = m.get_size() + strides = m.get_stride() + dtype = m.get_dtype() + + # Base pointer 16-byte aligned + if m.get_name() in V.graph.unaligned_buffers: + return False + + if (m_device := m.get_device()) is not None and m_device.type == "xpu": + return _is_tma_compatible_xpu(sizes, strides, dtype) + + return _is_tma_compatible(sizes, strides, dtype) + + def _is_tma_compatible( + sizes: Sequence[sympy.Expr], + strides: Sequence[_IntLike], + dtype: torch.dtype, + ) -> bool: + rank = len(sizes) + itemsize = dtype.itemsize + + if rank < 1 or rank > 5: + return False + + if dtype not in _TMA_SUPPORTED_DTYPES: + return False + + if add_guards: + sizes_i = V.graph.sizevars.guard_int_seq(sizes) + strides_i = V.graph.sizevars.guard_int_seq(strides) + else: + sizes_i = [ + V.graph.sizevars.replace_backed_symbols_with_hints(s) for s in sizes + ] + strides_i = [ + V.graph.sizevars.replace_backed_symbols_with_hints(st) for st in strides + ] + + # Find the single contiguous ("inner") dim + inner = [ + i + for i, st in enumerate(strides_i) + if V.graph.sizevars.statically_known_equals(st, 1) + ] + if len(inner) != 1: + return False + inner_idx = inner[0] + + # All "outer" dims must have 16-byte aligned strides + for i, st in enumerate(strides_i): + if i == inner_idx: + continue + if not _aligned(st * itemsize): + return False + + # Inner dim byte width must be a multiple of 16 B + inner_dim = sizes_i[inner_idx] + if not _aligned(inner_dim * itemsize): + return False + + # 1-byte dtypes (FP8 etc.) need inner dim ≥ 32 for tensor core alignment + if itemsize == 1 and not V.graph.sizevars.statically_known_geq(inner_dim, 32): + return False + + return True + + def _is_tma_compatible_xpu( + sizes: Sequence[sympy.Expr], + strides: Sequence[_IntLike], + dtype: torch.dtype, + ) -> bool: + # Make sure the last dimension is contiguous + last_stride = strides[-1] + last_stride_hint = V.graph.sizevars.replace_backed_symbols_with_hints( + last_stride + ) + if not V.graph.sizevars.statically_known_equals(last_stride_hint, 1): + return False + + # Triton's type of index is uint32, so all dimensions must fit in uint32 + MAX_UINT32 = 2**32 - 1 + for size in sizes: + size_hint = V.graph.sizevars.replace_backed_symbols_with_hints(size) + if V.graph.sizevars.statically_known_gt(size_hint, MAX_UINT32): + return False + + return True + + return ( + has_triton_tma_device() + and all(_is_tma_compatible_matrix(m) for m in matrices) + and _is_tma_compatible_layout(output_layout) + ) + + +def _descriptor_shape_fits_in_int32( + sizes: Sequence[sympy.Expr], add_guards: bool = False +) -> bool: + int32_max = torch.iinfo(torch.int32).max + conditions = [] + for size in sizes: + if isinstance(size, (int, sympy.Integer)): + if size > int32_max: + return False + else: + conditions.append(sympy.Le(size, int32_max)) + + if not conditions: + return True + + from .virtualized import V + + condition = conditions[0] if len(conditions) == 1 else sympy.And(*conditions) + return ( + V.graph.sizevars.guard_or_false(condition) + if add_guards + else V.graph.sizevars.statically_known_true(condition) + ) + + +def use_triton_tma_template( + *matrices: IRNode, output_layout: Layout, add_guards: bool = False +) -> bool: + if not config.triton.enable_persistent_tma_matmul: + return False + if not all(len(m.get_size()) == 2 for m in matrices): + return False + if not all( + _descriptor_shape_fits_in_int32(m.get_size(), add_guards=add_guards) + for m in matrices + ): + return False + if config.triton.enable_template_tma_store and not _descriptor_shape_fits_in_int32( + output_layout.size, add_guards=add_guards + ): + return False + # On AMD (HIP), TMA is not available but we still use non-TMA persistent + # kernels, so skip the TMA compatibility checks. + if torch.version.hip is not None: + return True + layout = output_layout if config.triton.enable_template_tma_store else None + return can_use_tma(*matrices, output_layout=layout, add_guards=add_guards) + + +def use_triton_blackwell_tma_template( + *matrices: IRNode, output_layout: Layout, add_guards: bool = False +) -> bool: + if not use_triton_tma_template( + *matrices, output_layout=output_layout, add_guards=add_guards + ): + return False + + from torch.utils._triton import has_triton_tensor_descriptor_host_tma + + from .codegen.cuda.cuda_env import is_datacenter_blackwell_arch + + # Blackwell template require the tensor descriptor API, not the experimental API. + return has_triton_tensor_descriptor_host_tma() and is_datacenter_blackwell_arch() + + +def use_triton_scaling_template( + scale_option_a: ScalingType, + scale_option_b: ScalingType, + scaling_types: list[ScalingType], +) -> bool: + return scale_option_a in scaling_types and scale_option_b in scaling_types + + +@functools.lru_cache(maxsize=1) +def ensure_cute_available() -> bool: + """Check if CuTeDSL is importable; cache the result for reuse. + + Call ensure_cute_available.cache_clear() after installing CuTeDSL + in the same interpreter to retry the import. + """ + try: + return importlib.util.find_spec("cutlass") is not None + except ImportError: + return False + + +@functools.lru_cache(maxsize=1) +def ensure_nv_universal_gemm_available() -> bool: + """Check if NVIDIA Universal GEMM (cutlass.operators) is importable; cache the result for reuse. + + Call ensure_nv_universal_gemm_available.cache_clear() after installing + cutlass.operators in the same interpreter to retry the import. + """ + try: + available = importlib.util.find_spec("cutlass.operators") is not None + except (ImportError, ValueError): + return False + if available: + _ensure_fp4_dtype_registered() + return available + + +def _ensure_fp4_dtype_registered(): + """Ensure cutlass.operators maps torch.float4_e2m1fn_x2 -> cutlass.Float4E2M1FN. + + cutlass.operators natively supports this dtype, so this is normally a no-op. + We keep the patch as a safety net (and for backward compat with generated + code that calls this) in case a future version regresses. + """ + import cutlass.operators.utils.dtype as _dtype_utils + + try: + _dtype_utils.cutlass_type_from_torch_type(torch.float4_e2m1fn_x2) + except (KeyError, AttributeError): + import cutlass + + _orig = _dtype_utils.cutlass_type_from_torch_type + + def _patched(dtype): + if dtype == torch.float4_e2m1fn_x2: + return cutlass.Float4E2M1FN + return _orig(dtype) + + _dtype_utils.cutlass_type_from_torch_type = _patched + + +@functools.lru_cache(maxsize=1) +def ensure_nvmatmul_heuristics_available() -> bool: + """Check if nvMatmulHeuristics is importable; cache the result for reuse. + + nvMatmulHeuristics provides performance model-based kernel selection + for NVIDIA GEMM operations. + + Call ensure_nvmatmul_heuristics_available.cache_clear() after installing + nvMatmulHeuristics in the same interpreter to retry the import. + """ + try: + return importlib.util.find_spec("nvMatmulHeuristics") is not None + except ImportError: + return False + + +def use_blackwell_cutedsl_grouped_mm( + mat_a: Any, + mat_b: Any, + layout: Layout, + a_is_2d: bool, + b_is_2d: bool, + offs: Any | None, + bias: Any | None, + scale_result: Any | None, +) -> bool: + """ + Returns True if we can use the blackwell kernel for grouped mm. + Required conditions: + 1. CuTeDSL backend is enabled + 2. CuTeDSL is available + 3. We are on a blackwell arch + 4. The dtype is bf16 + 5. Max autotune or max autotune gemm is enabled + 6. A, B, and the output are 16B aligned + 7. We are not using dynamic shapes + 8. A is 2d + 9. B is 3d + 10. Offsets are provided + 11. Bias and Scale are not provided + """ + if not ensure_cute_available(): + return False + + if not _use_autotune_backend("CUTEDSL"): + return False + + from .codegen.cuda.cuda_env import is_datacenter_blackwell_arch + + if not is_gpu(layout.device.type): + return False + + if not is_datacenter_blackwell_arch(): + return False + + layout_dtypes = [torch.bfloat16] + if not _use_template_for_gpu(layout, layout_dtypes): + return False + + if not (config.max_autotune or config.max_autotune_gemm): + return False + + # Checks for 16B ptr and stride alignment + if not can_use_tma(mat_a, mat_b, output_layout=layout): + return False + + if any(is_dynamic(x) for x in [mat_a, mat_b]): + return False + + if not a_is_2d or b_is_2d: + return False + + if offs is None: + return False + + if bias is not None or scale_result is not None: + return False + + return True + + +def use_cutlass_template(layout: Layout, m: int, n: int, k: int) -> bool: + from .virtualized import V + + gemm_size = V.graph.sizevars.optimization_hint(m * n * k, fallback=-1) + if gemm_size <= 0 or gemm_size < config.cutlass.cutlass_backend_min_gemm_size: + return False + from .codegen.cutlass.utils import try_import_cutlass + + # Do not use cutlass template on ROCm + if torch.version.hip: + return False + + # output dtype + # FP32 not supported: https://github.com/pytorch/pytorch/issues/145952 + layout_dtypes = [torch.float16, torch.bfloat16, torch.int32] + res = ( + _use_template_for_gpu(layout, layout_dtypes) + and (config.max_autotune or config.max_autotune_gemm) + and _use_autotune_backend("CUTLASS") + ) + + if res: + if not try_import_cutlass(): + log.warning( + "Failed to import CUTLASS lib. Please check whether " + "_inductor.config.cutlass.cutlass_dir %s is set correctly. " + "Skipping CUTLASS backend for now.", + config.cutlass.cutlass_dir, + ) + return False + return res + + +def use_nv_universal_gemm_template( + layout: Layout, + m: _IntLike, + n: _IntLike, + k: _IntLike, + mat_a: IRNode, + mat_b: IRNode, + offs: IRNode | None = None, + g: _IntLike | None = None, +) -> bool: + """ + Return True if we can use the NVIDIA Universal GEMM Template. + + Required conditions: + 1. NVGEMM backend is enabled + 2. cutlass.operators is available + 3. We are on a NVIDIA GPU + 4. Max autotune or max autotune gemm is enabled + 5. Not in AOT Inductor mode (requires runtime JIT compilation) + 6. Base pointers are 16-byte aligned + 7. Shape dimensions are not unbacked symbols + + Note: + - Shape and stride constraints are handled internally by + cutlass.operators.get_operators() which filters incompatible kernels. + - GroupedGemm currently only supports TN layout (column-major B). + Any other layout will act as a noop and fall back to ATen. + - Dynamic shapes are supported as long as they have hints + (from example inputs). + """ + from torch.fx.experimental.symbolic_shapes import has_free_unbacked_symbols + + if not ensure_cute_available(): + return False + + if not ensure_nv_universal_gemm_available(): + return False + + if not _use_autotune_backend("NVGEMM"): + return False + + from .virtualized import V + + if V.aot_compilation: + return False + + if layout.device.type != "cuda" or torch.version.hip: + return False + + if not (config.max_autotune or config.max_autotune_gemm): + return False + + # cutlass.operators can't handle unbacked symbols because it needs to evaluate + # shape constraints (e.g., stride divisibility by 8, N/K divisibility by 16). + # Unbacked symbols have no hint values, causing GuardOnDataDependentSymNode errors. + dims_to_check = [m, n, k] + if g is not None: + dims_to_check.append(g) + if any(has_free_unbacked_symbols(dim) for dim in dims_to_check): + return False + + # Base pointer must be 16-byte aligned. cutlass.operators can't check this at + # compile time because it only sees FakeTensors without real data pointers. + tensors_to_check = [mat_a, mat_b] + if offs is not None: + tensors_to_check.append(offs) + if any(t.get_name() in V.graph.unaligned_buffers for t in tensors_to_check): + return False + + return True + + +def _use_cutlass_for_op(op_name: str) -> bool: + """Check if CUTLASS should be used for the given operation.""" + enabled_ops = config.cutlass.cutlass_enabled_ops.upper() + if enabled_ops == "ALL": + return True + return op_name.upper() in [x.strip() for x in enabled_ops.split(",")] + + +_IntLike: TypeAlias = int | sympy.Expr + + +@functools.cache +def use_decompose_k_choice( + m: _IntLike, n: _IntLike, k: _IntLike, threshold_multiple: int = 1 +) -> bool: + from torch._inductor.virtualized import V + + decompose_k_threshold = config.triton.decompose_k_threshold * threshold_multiple + + return ( + V.graph.sizevars.statically_known_true( + sympy.And( + sympy.Ge(k, decompose_k_threshold * m), + sympy.Ge(k, decompose_k_threshold * n), + ) + ) + and not V.graph.aot_mode # TODO: Support AOTI for decomposeK + and not V.graph.cpp_wrapper + and config.triton.num_decompose_k_splits > 0 + ) + + +@functools.cache +def use_contiguous(m: _IntLike, n: _IntLike, k: _IntLike) -> bool: + """ + Check if we should use the contiguous subgraph transform. + This transform makes the second matrix contiguous before the matmul. + """ + contiguous_threshold = config.rocm.contiguous_threshold + + # Similar conditions to decompose_k but for contiguous transform + from torch._inductor.virtualized import V + + return ( + bool(torch.version.hip) # Only relevant on AMD + and V.graph.sizevars.statically_known_true( + sympy.And( + sympy.Ge(k, contiguous_threshold * m), + sympy.Ge(k, contiguous_threshold * n), + ) + ) + and not V.graph.aot_mode + and not V.graph.cpp_wrapper + ) + + +@functools.cache +def get_k_splits(m: _IntLike, n: _IntLike, k: _IntLike) -> list[int]: + # To limit compile time + k_splits_limit = config.triton.num_decompose_k_splits + + # Hand-tuned + default_k_splits = [16, 32, 64, 128, 256] + # If k is a sympy expression, we can't do any splitting + if isinstance(k, sympy.Expr) and not k.is_number: + return default_k_splits + elif k_splits_limit == 0: + return [] + + if (isinstance(m, sympy.Expr) and not m.is_number) or ( + isinstance(n, sympy.Expr) and not n.is_number + ): + max_k_split = 256 + else: + max_k_split = min(k // m, k // n) + + min_k_split = 2 + # Get all divisors of k, k has to be divisible by kPart + divisors = sympy.divisors(k) + + divisors = [ + divisor + for divisor in divisors + if divisor <= max_k_split and divisor >= min_k_split + ] + + pow_of_2_divisors, mul_of_32_divisors, rest_of_splits = [], [], [] + + for d in divisors: + kPart = k // d + + # Smaller than 128 might not even fit in a single tile, BLOCK_K can be 128 + if kPart < 128: + continue + + # Power of 2 divisors are best performing, conform to hardware + if (kPart & kPart - 1) == 0 and kPart >= 128: + pow_of_2_divisors.append(d) + # Else check if creates a multiple of 32 + elif kPart % 32 == 0: + mul_of_32_divisors.append(d) + # otherwise, take the smallest values + else: + rest_of_splits.append(d) + + if config.max_autotune_gemm_search_space == "EXHAUSTIVE": + return pow_of_2_divisors + mul_of_32_divisors + rest_of_splits + + best_splits = pow_of_2_divisors + mul_of_32_divisors + rest_of_splits + # Otherwise, conform results to k_splits_limit + return best_splits[:k_splits_limit] + + +@functools.cache +def _rocm_native_device_arch_name(device: str) -> str: + return torch.cuda.get_device_properties(device).gcnArchName + + +@functools.lru_cache +def using_rocm_rdna3() -> bool: + """Returns true if the device is based on RDNA3, otherwise returns false.""" + return torch.cuda.is_available() and _rocm_native_device_arch_name( + "cuda" + ).startswith("gfx11") + + +@functools.cache +def try_import_ck_lib() -> tuple[ + str | None, Callable[[], list[Any]], Callable[[], list[Any]], type[Any] +]: + try: + import ck4inductor # type: ignore[import] + from ck4inductor.universal_gemm.gen_instances import ( # type: ignore[import] + gen_ops_library, + gen_ops_preselected, + ) + from ck4inductor.universal_gemm.op import ( # type: ignore[import] + CKGemmOperation, + ) + + package_dirname = os.path.dirname(ck4inductor.__file__) + except ImportError: + + def gen_ops_library() -> list[Any]: + return [] + + def gen_ops_preselected() -> list[Any]: + return [] + + class CKGemmOperation: # type: ignore[no-redef] + pass + + package_dirname = None + return package_dirname, gen_ops_library, gen_ops_preselected, CKGemmOperation + + +def use_ck_template(layout: Layout) -> bool: + # config knobs check 1 + if not (config.max_autotune or config.max_autotune_gemm): + return False + # platform check + if not torch.version.hip: + return False + # tensors must be on GPU + if layout.device.type != "cuda": + return False + # hardware check + # if config arch list is not specified, get the native arch from the device properties + native_arch = _rocm_native_device_arch_name(layout.device) + requested_archs = {k.split(":")[0]: k for k in config.rocm.arch} or { + native_arch.split(":")[0]: native_arch + } + requested_supported_archs = [ + requested_archs[k] + for k in requested_archs.keys() & config.rocm.ck_supported_arch + ] + if not requested_supported_archs: + return False + # supported input dtypes + if layout.dtype not in [torch.float16, torch.bfloat16, torch.float32]: + return False + + ck_package_dirname, _, _, _ = try_import_ck_lib() + + if not ck_package_dirname: + log.warning("Please pip install Composable Kernel package") + return False + + config.rocm.ck_dir = ck_package_dirname + + return True + + +def use_ck_gemm_template(layout: Layout, m: int, n: int, k: int) -> bool: + from .virtualized import V + + return ( + _use_autotune_backend("CK") + and use_ck_template(layout) + and V.graph.sizevars.optimization_hint(m * n * k, fallback=-1) > 0 + ) + + +def use_ck_tile_gemm_template(layout: Layout, m: int, n: int, k: int) -> bool: + from .virtualized import V + + return ( + _use_autotune_backend("CKTILE") + and use_ck_template(layout) + and V.graph.sizevars.optimization_hint(m * n * k, fallback=-1) > 0 + ) + + +def use_ck_conv_template(layout: Layout) -> bool: + return _use_conv_autotune_backend("CK") and use_ck_template(layout) + + +def _use_template_for_cpu(layout: Layout) -> bool: + return ( + config.max_autotune or config.max_autotune_gemm + ) and layout.device.type == "cpu" + + +def use_cpp_bmm_template( + layout: Layout, mat1: ReinterpretView | Buffer, mat2: IRNode +) -> bool: + from .ir import Layout + + if not isinstance(mat1.layout, Layout): + raise AssertionError(f"Expected Layout, got {type(mat1.layout)}") + + # In certain scenarios, such as when the first stride is 0, the entire tensor may not be contiguous. + # But the 2D matrix within each batch can still be contiguous, allowing us to apply max autotune. + # So here we specifically check for contiguity within the 2D matrix of each batch. + mat1_size = mat1.layout.size + mat1_stride = mat1.layout.stride + mat1_each_batch_is_contiguous = ( + _use_template_for_cpu(layout) + and mat1.get_dtype() == torch.float32 + and (len(mat1_size) == 3) + and (len(mat1_stride) == 3) + and (mat1_stride[1] == mat1_size[2]) + and (mat1_stride[2] == 1) + ) + return use_cpp_gemm_template(layout, mat1, mat2, require_constant_mat2=False) and ( + mat1.layout.is_contiguous() or mat1_each_batch_is_contiguous + ) + + +def use_cpp_gemm_template( + layout: Layout, + mat1: IRNode, + mat2: IRNode, + mat2_transposed: bool = False, + require_constant_mat2: bool = True, + is_woq_int4: bool = False, + q_group_size: int | None = None, +) -> bool: + from . import ir + from .codegen.cpp_micro_gemm import create_micro_gemm + from .codegen.cpp_utils import get_gemm_template_output_and_compute_dtype + from .kernel.mm_common import mm_args + + if not _use_template_for_cpu(layout) or not _use_autotune_backend("CPP"): + return False + + if not config.cpp.weight_prepack: + return False + + int8_gemm = mat1.get_dtype() in [torch.uint8, torch.int8] + layout_dtypes = [torch.float32, torch.bfloat16, torch.half, torch.uint8, torch.int8] + m, n, k, layout, mat1, mat2 = mm_args( + mat1, + mat2, + out_dtype=layout.dtype if int8_gemm else None, + mat2_transposed=mat2_transposed, + use_4x2_dim=is_woq_int4, + ) + + # TODO(jgong5): support dynamic shapes for n or k + if has_free_symbols((n, k)): + return False + + if isinstance(mat2, ir.BaseView): + mat2 = mat2.unwrap_view() + + output_dtype, _ = get_gemm_template_output_and_compute_dtype(mat1.get_dtype()) + micro_gemm = create_micro_gemm( + "micro_gemm", + m, + n, + k, + input_dtype=mat1.get_dtype(), + input2_dtype=mat2.get_dtype(), + output_dtype=output_dtype, + num_threads=parallel_num_threads(), + use_ref=not is_woq_int4, + q_group_size=q_group_size, + ) + + def is_last_dim_stride1(x: IRNode) -> bool: + x.freeze_layout() + return x.get_stride()[-1] == 1 + + return ( + layout.dtype in layout_dtypes + and micro_gemm is not None + and is_last_dim_stride1(mat1) # TODO(jgong5): support transposed input + and isinstance(mat2, ir.StorageBox) + and (mat2.is_module_buffer() or not require_constant_mat2) + ) + + +def use_aten_gemm_kernels() -> bool: + return not ( + config.max_autotune or config.max_autotune_gemm + ) or _use_autotune_backend("ATEN") + + +class DebugDirManager: + counter = itertools.count(0) + prev_debug_name: str + + def __init__(self) -> None: + self.id = next(DebugDirManager.counter) + + def __enter__(self) -> None: + self.prev_debug_name = torch._dynamo.config.debug_dir_root + self.new_name = f"{self.prev_debug_name}_tmp_{self.id}" + torch._dynamo.config.debug_dir_root = self.new_name + + def __exit__(self, *args: object) -> None: + shutil.rmtree(self.new_name) + torch._dynamo.config.debug_dir_root = self.prev_debug_name + + +def run_and_get_code( + fn: Callable[P, _T], + *args: P.args, + **kwargs: P.kwargs, +) -> tuple[_T, list[str]]: + from .graph import GraphLowering + + source_codes: OrderedSet[str] = OrderedSet() + + def save_output_code(code: str) -> None: + source_codes.add(code) + + with mock.patch.object(GraphLowering, "save_output_code", save_output_code): + torch._dynamo.reset() + result = fn(*args, **kwargs) + return result, list(source_codes) + + +def run_and_get_kernels( + fn: Callable[P, _T], *args: P.args, **kwargs: P.kwargs +) -> tuple[_T, list[str]]: + remove_quote = kwargs.pop("remove_quote", False) + # pyrefly: ignore [bad-argument-type] + result, source_codes = run_and_get_code(fn, *args, **kwargs) + kernels = [] + for code in source_codes: + if config.cpp_wrapper and config.triton.autotune_at_compile_time is not True: + # With lazy Triton kernel compilation, kernel sources are embedded + # inside C++ R"TRITON(...)TRITON" raw strings. + kernels.extend(re.findall(r'R"TRITON\((.*?)\)TRITON"', code, re.DOTALL)) + else: + kernels.extend(re.findall(r"'''.*?'''", code, re.DOTALL)) + if remove_quote: + kernels = [kernel[3:-3] for kernel in kernels] + return result, kernels + + +def run_fw_bw_and_get_code(fn: Callable[..., Any]) -> tuple[Any, list[str]]: + def run_with_backward() -> Any: + result = fn() + result.sum().backward() + return result + + return run_and_get_code(run_with_backward) + + +def get_code(fn: Callable[P, _T], *args: P.args, **kwargs: P.kwargs) -> list[str]: + """Get the inductor-generated code, but skip any actual compilation or running.""" + from .graph import GraphLowering + + source_codes: list[str] = [] + + def save_output_code(code: str) -> None: + source_codes.append(code) + + def patched_compile_to_module(self: GraphLowering) -> Any: + class DummyModule: + """This is empty to replace the generated triton module""" + + def __init__(self) -> None: + pass + + def call(self, *args: Any, **kwargs: Any) -> None: + # Don't do anything when called + pass + + wrapper_code, kernel_code = ( + self.codegen_with_cpp_wrapper() if self.cpp_wrapper else self.codegen() + ) + # Skip all the actual compiling. + save_output_code(wrapper_code.value) + if kernel_code: + save_output_code(kernel_code.value) + + return DummyModule() + + with ( + mock.patch.object( + GraphLowering, "compile_to_module", patched_compile_to_module + ), + mock.patch.object(GraphLowering, "save_output_code", save_output_code), + ): + torch._dynamo.reset() + # Note the return here is None + _ = fn(*args, **kwargs) + + return source_codes + + +def get_triton_code(fn: Callable[P, _T], *args: P.args, **kwargs: P.kwargs) -> str: + # pyrefly: ignore [bad-argument-type] + source_codes = get_code(fn, *args, **kwargs) + # Can have two outputs if backwards was eagerly compiled + if not (1 <= len(source_codes) <= 2): + raise AssertionError( + f"expected one or two code outputs got {len(source_codes)}" + ) + return source_codes[0] + + +def run_and_get_triton_code( + fn: Callable[P, _T], *args: P.args, **kwargs: P.kwargs +) -> str: + # pyrefly: ignore [bad-argument-type] + _, source_codes = run_and_get_code(fn, *args, **kwargs) + # Can have two outputs if backwards was eagerly compiled + if not (1 <= len(source_codes) <= 2): + raise AssertionError( + f"expected one or two code outputs got {len(source_codes)}" + ) + return source_codes[0] + + +def run_and_get_graph_lowering( + fn: Callable[P, _T], *args: P.args, **kwargs: P.kwargs +) -> tuple[Any, list[GraphLowering]]: + from torch._inductor.graph import GraphLowering + from torch._inductor.output_code import CompiledFxGraph + + real_init = CompiledFxGraph.__init__ + graph_lowerings = [] + + def fake_init(*args: Any, **kwargs: Any) -> None: + real_init(*args, **kwargs) + graph = args[2] + if not isinstance(graph, GraphLowering): + raise AssertionError(f"Expected GraphLowering, got {type(graph)}") + graph_lowerings.append(graph) + + with mock.patch.object(CompiledFxGraph, "__init__", fake_init): + result = fn(*args, **kwargs) + + return result, graph_lowerings + + +@contextlib.contextmanager +def override_lowering( + aten_op: Callable[..., Any], override_fn: Callable[..., Any] +) -> Iterator[None]: + """ + Override the lowering of aten_op with override_fn. + The first argument of override_fn is the original lowering fn. + """ + from torch._inductor import lowering + + orig_fn = lowering.lowerings[aten_op] + try: + lowering.lowerings[aten_op] = functools.partial(override_fn, orig_fn) + yield + finally: + lowering.lowerings[aten_op] = orig_fn + + +def add_scheduler_init_hook( + pre_fn: Callable[..., Any], post_fn: Callable[..., Any] | None = None +) -> Any: + """ + Add hook functions to be called at the beginning and end of Scheduler.__init__. + Used for unit tests. + """ + from torch._inductor.scheduler import Scheduler + + orig_fn = Scheduler.__init__ + + def wrapper(scheduler: Any, nodes: Any) -> Any: + pre_fn(scheduler, nodes) + out = orig_fn(scheduler, nodes) + if post_fn: + post_fn(scheduler, nodes) + return out + + return unittest.mock.patch.object(Scheduler, "__init__", wrapper) + + +def developer_warning(msg: str) -> None: + """ + Warnings that will be actionable for PyTorch developers, but not + end users. Allows us to easily disable them in stable releases but + keep them on for nightly builds. + """ + if config.developer_warnings: + log.warning(msg) + else: + log.info(msg) + + +def get_benchmark_name() -> str | None: + """ + An experimental API used only when config.benchmark_kernel is true. + + The benchmark name is only available at codegen time. So we can not + directly call it in benchmark_all_kernels which is run after codegen. + + The function assumes the argument after --only is the benchmark name. + It works for torchbench.py/hugginface.py/timm_models.py. But for ad-hoc + scripts, this function may return None. + + There are 2 flavors of --only argument we need to handle: + 1. --only model_name + 2. --only=model_name + """ + try: + idx = sys.argv.index("--only") + if ( + idx + 1 < len(sys.argv) + and len(sys.argv[idx + 1]) > 0 + and sys.argv[idx + 1][0] != "-" + ): + return sys.argv[idx + 1] + except ValueError: + pass + + for arg in sys.argv: + if arg.startswith("--only="): + return arg[len("--only=") :] + + return None + + +def is_ones(items: Sequence[Any]) -> bool: + return all(x == 1 for x in items) + + +def is_zeros(items: Sequence[Any]) -> bool: + return all(x == 0 for x in items) + + +def is_cpu_device(inputs: Sequence[torch.Tensor]) -> bool: + return all( + item.device == torch.device("cpu") + for item in inputs + if isinstance(item, torch.Tensor) + ) + + +def get_sympy_Expr_dtype(val: sympy.Expr) -> torch.dtype: + if not isinstance(val, sympy.Expr): + raise AssertionError("only support sympy.Expr as input to get_sympy_Expr_dtype") + if val.is_integer: # type: ignore[attr-defined] + return torch.int64 + else: + return torch.float64 + + +@contextlib.contextmanager +def maybe_profile(should_profile: bool, *args: Any, **kwargs: Any) -> Iterator[Any]: + if should_profile: + with torch.profiler.profile(*args, **kwargs) as p: + yield p + else: + yield + + +def parallel_num_threads() -> int: + threads = config.cpp.threads + if threads < 1: + threads = torch.get_num_threads() + return threads + + +@functools.cache +def get_backend_num_stages() -> int: + from .runtime.triton_helpers import get_backend_options + + options = get_backend_options() + return options.get("num_stages", 2 if torch.version.hip else 3) + + +@functools.cache +def get_device_tflops(dtype: torch.dtype) -> float: + """ + We don't want to throw errors in this function. First check to see if the device is in device_info.py, + then fall back to the inaccurate triton estimation. + """ + is_tf32 = torch.backends.cuda.matmul.fp32_precision == "tf32" + if torch.xpu.is_available(): + is_tf32 = torch.backends.mkldnn.allow_tf32 + ds_tops = datasheet_tops(dtype, is_tf32=is_tf32) + if ds_tops is not None: + return ds_tops + + if not torch.cuda.is_available(): + log.warning( + "get_device_tflops: no Triton fallback available for non-CUDA devices. " + "Returning 0.0; roofline estimates will use memory bandwidth only." + ) + return 0.0 + + from triton.testing import get_max_simd_tflops, get_max_tensorcore_tflops + + SM80OrLater = torch.cuda.is_available() and torch.cuda.get_device_capability() >= ( + 8, + 0, + ) + + if dtype not in (torch.float16, torch.bfloat16, torch.float32): + raise AssertionError( + f"Expected dtype to be float16, bfloat16, or float32, got {dtype}" + ) + + if inspect.signature(get_max_simd_tflops).parameters.get("clock_rate"): + # Triton API change in https://github.com/triton-lang/triton/pull/2293 + from torch._utils_internal import max_clock_rate + + sm_clock = max_clock_rate() + if dtype in (torch.float16, torch.bfloat16) and SM80OrLater: + return get_max_tensorcore_tflops(dtype, sm_clock) + + if torch.backends.cuda.matmul.fp32_precision == "tf32": + return get_max_tensorcore_tflops(torch.float32, sm_clock) + else: + return get_max_simd_tflops(torch.float32, sm_clock) + else: + if dtype in (torch.float16, torch.bfloat16) and SM80OrLater: + return get_max_tensorcore_tflops(dtype) + + if torch.backends.cuda.matmul.fp32_precision == "tf32": + return get_max_tensorcore_tflops(torch.float32) + else: + return get_max_simd_tflops(torch.float32) + + +@functools.cache +def get_gpu_dram_gbps() -> float: + """ + We don't want to throw errors in this function. First check to see if the device is in device_info.py, + then fall back to the inaccurate triton estimation. + """ + from .analysis.device_info import datasheet_dram_bw_gbs + + ds_bw = datasheet_dram_bw_gbs() + if ds_bw is not None: + return ds_bw + + from triton.testing import get_dram_gbps + + return get_dram_gbps() + + +def get_gpu_shared_memory() -> int: + from triton.runtime import driver + + return driver.active.utils.get_device_properties(0).get("max_shared_mem", 0) + + +def get_max_numwarps() -> int: + if torch.cuda.is_available(): + device = torch.device("cuda", torch.cuda.current_device()) + props = DeviceProperties.create(device) + warp_size = props.warp_size_or_default + max_threads_per_block = props.max_threads_per_block + if max_threads_per_block is None: + raise AssertionError("expected max_threads_per_block to be set") + return max_threads_per_block // warp_size + + log.debug("CUDA is not available; defaulting max num warps to 32") + return 32 + + +def is_welford_reduction(reduction_type: str) -> bool: + return reduction_type.startswith("welford") + + +def reduction_num_outputs(reduction_type: str) -> int: + if is_welford_reduction(reduction_type): + return 3 + elif reduction_type in ( + "argmax_with_value", + "argmin_with_value", + "online_softmax_reduce", + ): + return 2 + else: + return 1 + + +def is_linux() -> bool: + return platform.system() == "Linux" + + +def is_windows() -> bool: + return sys.platform == "win32" + + +def has_free_symbols(itr: Iterable[Any]) -> bool: + return any(isinstance(x, sympy.Expr) and not x.is_number for x in itr) + + +def is_dynamic(*args: Any) -> bool: + from . import ir + + for t in args: + if isinstance( + t, (ir.TensorBox, ir.StorageBox, ir.BaseView, ir.ComputedBuffer, ir.Buffer) + ): + if has_free_symbols(t.maybe_get_size() or ()) or has_free_symbols( + t.maybe_get_stride() or () + ): + return True + elif not isinstance(t, ir.IRNode): + continue + else: + raise TypeError(f"unexpected type for is_dynamic {type(t)}") + + return False + + +# Placeholder strings used in triton codegen. +class Placeholder(enum.Enum): + # The placeholder for the actual name of a triton kernel. + # e.g. for "def triton_" it would be "triton_" + KERNEL_NAME = "KERNEL_NAME" + + # The descriptive name of the triton kernel; when unique_kernel_names = False, this + # placeholder will be replaced with a string with more information. + DESCRIPTIVE_NAME = "DESCRIPTIVE_NAME" + + +def pass_execution_and_save( + func: Callable[..., Any], gm: GraphModule, inp: Sequence[Any], msg: str +) -> None: + from .pattern_matcher import stable_topological_sort + + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + ) as f: + before_io = io.StringIO() + after_io = io.StringIO() + ShapeProp(gm=gm, fake_mode=detect_fake_mode(inp)).propagate(*inp) + print(f"Before:\n{gm.graph}", file=f) + print(gm.graph, file=before_io) + start_time = datetime.now() + with GraphTransformObserver(gm, msg): + func(gm.graph) + time_elapsed = datetime.now() - start_time + # recompile graph + stable_topological_sort(gm.graph) + gm.graph.lint() + gm.recompile() + + print(f"After:\n{gm.graph}", file=f) + print(gm.graph, file=after_io) + t = before_io.getvalue() == after_io.getvalue() + log.info( + "%s, save before/after graph to %s, graph before/after are the same = %s, time elapsed = %s", + msg, + f.name, + t, + time_elapsed, + ) + + +def is_multi_outputs_template(input_buf: Buffer | Operation | None) -> bool: + """ + Check if input buffer is a multi-outputs template buffer + """ + from . import ir + + return ( + isinstance(input_buf, ir.TemplateBuffer) + and input_buf.is_multi_outputs_template() + ) + + +def is_output_of_multi_outputs_template( + input_buf: Buffer | Operation | None, +) -> bool: + """ + Check if input buffer is a output of multi-outputs template buffer + """ + from . import ir + + return ( + isinstance(input_buf, ir.MultiOutput) + and len(input_buf.inputs) == 1 + and is_multi_outputs_template(input_buf.inputs[0]) # type: ignore[arg-type] + ) + + +def is_collective( + node: Node | Operation | None, + op: torch._ops.OperatorBase | None = None, +) -> bool: + if node is None: + return False + + from . import ir + + return ( + isinstance(node, ir._CollectiveKernel) + and not isinstance(node, ir._WaitKernel) + and (op is None or node.op_overload is op) + ) or ( + # TODO: this is a temporary solution to ensure that we can identify torchrec's + # communication ops. But in order to allow better communication and computation + # overlap, torchrec's communication ops should be not used. + type(node) is ir.FallbackKernel + and ( + # NOTE: the `hasattr()` check is to bypass errors such as the following: + # AttributeError: '_OpNamespace' 'torchrec' object has no attribute 'all_to_all_single' + ( + hasattr(torch.ops.torchrec, "all_to_all_single") + and node.op_overload == torch.ops.torchrec.all_to_all_single.default + ) + or ( + hasattr(torch.ops.torchrec, "all_gather_into_tensor") + and node.op_overload + == torch.ops.torchrec.all_gather_into_tensor.default + ) + or ( + hasattr(torch.ops.torchrec, "reduce_scatter_tensor") + and node.op_overload == torch.ops.torchrec.reduce_scatter_tensor.default + ) + ) + ) + + +def is_wait(node: IRNode | Operation | None) -> bool: + from . import ir + + return type(node) is ir._WaitKernel + + +def contains_collective( + snode: BaseSchedulerNode, + filter_fn: Callable[[BaseSchedulerNode], bool] | None = None, +) -> bool: + from torch._inductor.scheduler import GroupedSchedulerNode + + if isinstance(snode, GroupedSchedulerNode): + return any(contains_collective(x) for x in snode.snodes) + + return is_collective(snode.node) and (filter_fn is None or filter_fn(snode)) + + +def contains_wait(snode: BaseSchedulerNode) -> bool: + from torch._inductor.scheduler import GroupedSchedulerNode + + if isinstance(snode, GroupedSchedulerNode): + return any(contains_wait(x) for x in snode.snodes) + else: + return is_wait(snode.node) + + +def is_fallback_op( + node: Operation | None, + op: torch._ops.OpOverload | Collection[torch._ops.OpOverload], +) -> bool: + from . import ir + + if isinstance(op, torch._ops.OpOverload): + op = [op] + return isinstance(node, ir.FallbackKernel) and node.op_overload in op + + +def buf_name_to_fused_snode( + buf_name: str, name_to_buf: dict[str, Any], name_to_fused_node: dict[str, Any] +) -> Any: + return name_to_fused_node[name_to_buf[buf_name].defining_op.get_name()] + + +def find_recursive_deps_of_node( + snode: BaseSchedulerNode, + collected_node_set: MutableSet[BaseSchedulerNode], + name_to_buf: dict[str, SchedulerBuffer], + name_to_fused_node: dict[str, BaseSchedulerNode], + criteria_cb: Callable[[Any], bool] = lambda snode: False, +) -> None: + if criteria_cb(snode): + return + collected_node_set.add(snode) + for dep in snode.unmet_dependencies: + defining_op_for_dep = buf_name_to_fused_snode( + dep.name, name_to_buf, name_to_fused_node + ) + if defining_op_for_dep in collected_node_set: + continue + find_recursive_deps_of_node( + defining_op_for_dep, + collected_node_set, + name_to_buf, + name_to_fused_node, + criteria_cb=criteria_cb, + ) + + +def find_recursive_users_of_node( + snode: BaseSchedulerNode, + collected_node_set: MutableSet[BaseSchedulerNode], + name_to_buf: dict[str, SchedulerBuffer], + name_to_fused_node: dict[str, BaseSchedulerNode], + criteria_cb: Callable[[Any], bool] = lambda snode: False, +) -> None: + if criteria_cb(snode): + return + collected_node_set.add(snode) + for o in snode.get_outputs(): + for user in o.users: + if user.node is None: + raise AssertionError("user.node is None in collect_defined_kernels") + if user.node.get_name() == "OUTPUT": + continue + if user.node.get_name() not in name_to_fused_node: + continue + user_op = name_to_fused_node[user.node.get_name()] + if user_op in collected_node_set: + continue + find_recursive_users_of_node( + user_op, + collected_node_set, + name_to_buf, + name_to_fused_node, + criteria_cb=criteria_cb, + ) + + +def num_fw_fixed_arguments(dynamo_gm_num_inputs: int, aot_fw_gm_num_inputs: int) -> int: + "Computes the number of inputs to the aot fw graph which have fixed addresses (params and buffers)" + num_rng_seed_offset_inputs = ( + 2 if torch._functorch.config.functionalize_rng_ops else 0 + ) + # AOT won't lift any parameters if we're inlining NN Modules + # however desugaring subclasses will still add arguments + # resulted in extra fixed inputs https://github.com/pytorch/pytorch/issues/130502 + return aot_fw_gm_num_inputs - dynamo_gm_num_inputs - num_rng_seed_offset_inputs + + +def count_tangents(fx_g: torch.fx.GraphModule) -> int: + """ + Infers which inputs are static for a backwards graph + """ + + def is_saved_tensor(x: Node) -> bool: + return ( + "tangents" not in x.name + and "bwd_seed" not in x.name + and "bwd_base_offset" not in x.name + and "bwd_rng_state" not in x.name + ) + + arg_count = 0 + static_arg_idxs = [] + for n in fx_g.graph.nodes: + if n.op == "placeholder": + if is_saved_tensor(n): + static_arg_idxs.append(arg_count) + arg_count += 1 + + if static_arg_idxs != list(range(len(static_arg_idxs))): + raise AssertionError( + f"Expected static_arg_idxs to be contiguous from 0, got {static_arg_idxs}" + ) + return len(static_arg_idxs) + + +def get_static_bw_input_idxs(fx_g: torch.fx.GraphModule) -> list[int]: + """ + Returns indices of backward graph inputs that are always at fixed + addresses: primals (parameters/buffers/user inputs saved for backward). + Excludes saved activations which may not be at fixed addresses when + the forward is partitioned for CUDA graphs. + """ + static_idxs = [] + for idx, n in enumerate(fx_g.graph.nodes): + if n.op != "placeholder": + break + if n.name.startswith("primals_"): + static_idxs.append(idx) + return static_idxs + + +@dataclasses.dataclass +class BoxedBool: + value: bool + + def __bool__(self) -> bool: + return self.value + + @staticmethod + def disable(obj: Any) -> BoxedBool | bool: + if isinstance(obj, BoxedBool): + obj.value = False + return obj + return False + + +@contextlib.contextmanager +def collect_defined_kernels(kernel_list: list[str]) -> Iterator[None]: + from .codegen.wrapper import PythonWrapperCodegen + + orig_define_kernel = PythonWrapperCodegen.define_kernel + + def define_kernel( + self: PythonWrapperCodegen, + kernel_name: str, + kernel_code: str, + metadata: str | None = None, + gpu: bool = True, + cpp_definition: str | None = None, + ) -> Any: + kernel_list.append(kernel_code) + return orig_define_kernel( + self, kernel_name, kernel_code, metadata, gpu, cpp_definition + ) + + with mock.patch.object(PythonWrapperCodegen, "define_kernel", define_kernel): + yield + + +def get_cloned_parameter_buffer_name(name: str) -> str: + return name + "__original__" + + +def is_gpu(device: str | None) -> bool: + return device in GPU_TYPES + + +def is_rocm() -> bool: + """Check if we're running on ROCm/HIP platform.""" + return torch.version.hip is not None + + +@functools.lru_cache(None) +def _triton_supported_fp8_dtypes( + backend_name: str, arch: int | str, warp_size: int +) -> tuple[str, ...] | None: + if not has_triton_package(): + return None + + try: + from triton.backends.compiler import GPUTarget + from triton.compiler.compiler import make_backend + + # This is the same option Triton checks when lowering tl.float8* types. + target = GPUTarget(backend_name, arch, warp_size) + options = make_backend(target).parse_options({}) + except (AttributeError, ImportError, KeyError, TypeError): + return None + + supported_fp8_dtypes = getattr(options, "supported_fp8_dtypes", None) + if supported_fp8_dtypes is None: + return None + return tuple(supported_fp8_dtypes) + + +def is_triton_fp8_dtype_supported( + dtype: torch.dtype, + device: torch.device | str | None = None, + *, + triton_backend: str | None = None, + triton_arch: int | str | None = None, + warp_size: int | None = None, +) -> bool: + if dtype not in ( + torch.float8_e4m3fn, + torch.float8_e5m2, + torch.float8_e4m3fnuz, + torch.float8_e5m2fnuz, + ): + return True + + triton_dtype = _type_of(dtype).removeprefix("*") + + if triton_backend is None: + if device is None: + return True + device = torch.device(device) + if device.type != "cuda": + return True + if not torch.cuda.is_available(): + return True + + device_index = device.index + if device_index is None: + device_index = torch.cuda.current_device() + properties = torch.cuda.get_device_properties(device_index) + if is_rocm(): + triton_backend = "hip" + triton_arch = properties.gcnArchName.split(":")[0] + else: + triton_backend = "cuda" + triton_arch = properties.major * 10 + properties.minor + warp_size = getattr(properties, "warp_size", None) + + if triton_arch is None: + raise ValueError("triton_arch must be provided with triton_backend") + if warp_size is None: + warp_size = 64 if triton_backend == "hip" else 32 + + supported_fp8_dtypes = _triton_supported_fp8_dtypes( + triton_backend, triton_arch, warp_size + ) + if supported_fp8_dtypes is None: + return True + return triton_dtype in supported_fp8_dtypes + + +def device_need_guard(device: str) -> bool: + return device != "mps" and is_gpu(device) # TODO: MPS does not expose streams now + + +def needs_fallback_due_to_atomic_add_limitations(dtype: torch.dtype) -> bool: + if dtype == torch.bfloat16 and torch.cuda.is_available(): + return torch.cuda.get_device_capability() < (9, 0) + elif dtype == torch.bfloat16 and torch.xpu.is_available(): + return True + else: + return dtype in (torch.int64, torch.bool) + + +def use_scatter_fallback( + op_overload: torch._ops.OpOverload, + reduction_type: str | None, + self_dtype: torch.dtype, + src_dtype: torch.dtype, + src_device_type: str, + src_is_tensor: bool, +) -> bool: + if ( + op_overload.overloadpacket + in (torch.ops.aten.scatter_reduce_, torch.ops.aten.scatter_reduce) + and reduction_type is None + ): + return False + + reduce_ty = ( + "add" if op_overload.overloadpacket == torch.ops.aten.scatter_ else "sum" + ) + + return ( + reduction_type not in (None, reduce_ty) + or ( + src_is_tensor + and is_gpu(src_device_type) + and needs_fallback_due_to_atomic_add_limitations(src_dtype) + ) + or ( + op_overload.overloadpacket == torch.ops.aten.scatter_reduce_ + and reduction_type == "sum" + and src_is_tensor + and src_device_type == "cpu" + and config.cpp.fallback_scatter_reduce_sum + and (config.cpp.dynamic_threads or parallel_num_threads() != 1) + ) + or (reduction_type == reduce_ty and self_dtype in (torch.bool, torch.int64)) + or torch.are_deterministic_algorithms_enabled() + ) + + +def dump_node_schedule(node_schedule: Sequence[BaseSchedulerNode]) -> None: + """ + An API that can be used in pdb to dump a node_schedule. + Right mainly dump the read/write dependencies but can add more as needed. + """ + from torch._inductor.codegen.simd import DisableReduction, EnableReduction + from torch._inductor.scheduler import SchedulerNode + + print(f"Node schedule with {len(node_schedule)} nodes") + for idx, node in enumerate(node_schedule): + print(f" {idx:3}:") + # pyrefly: ignore [unnecessary-comparison] + if node is EnableReduction: + print("enable reduction") + # pyrefly: ignore [unnecessary-comparison] + elif node is DisableReduction: + print("disable reduction") + elif isinstance(node, SchedulerNode): + is_red = node.is_reduction() + print(f"{'red' if is_red else 'pw'} scheduler node") + if is_red: + if node.node is None: + raise AssertionError( + "SchedulerNode.node is None for reduction node" + ) + print(f"original reduction hint {node.node.data.reduction_hint}") # type: ignore[attr-defined] + print("ReadDep:") + for dep in node.read_writes.reads: + print(dep) + print("WriteDep:") + for dep in node.read_writes.writes: + print(dep) + else: + raise RuntimeError(f"Unrecognized node type: {type(node)}") + + +def tensor_is_aligned(tensor: torch.Tensor) -> bool: + # See Note: [Input Alignment handling in Inductor] + # Right now, we don't try to guard on the alignment of the storage offset. + # When this comment was written, non-symbolic storage_offsets are not guarded on + # but symbolic storage_offsets are. For consistency, we suppress guard creation + # upon performing this check: that ensures that we don't add recompiles when we + # add this logic. + from torch.fx.experimental.symbolic_shapes import statically_known_true + + return statically_known_true( + (tensor.storage_offset() * get_dtype_size(tensor.dtype)) % GPU_ALIGN_BYTES == 0 + ) + + +def should_assume_input_aligned(example_input: torch.Tensor) -> bool: + # See Note: [Input Alignment handling in Inductor] + + # right now, we only care about alignment for cuda tensors. + if not is_gpu(example_input.device.type): + return False + return config.assume_aligned_inputs or tensor_is_aligned(example_input) + + +def maybe_get_suppress_shape_guards_ctx() -> contextlib.AbstractContextManager[None]: + # Try to get TracingContext.try_get().fake_mode.shape_env.suppress_guards() + # If it's not available, return a nullcontext. + + # If we're dealing with cudagraphs, we might not have a tracing_context + tracing_context = torch._guards.TracingContext.try_get() + if not tracing_context: + return contextlib.nullcontext() + + # In standalone inductor compile mode, we might not have a shape_env attached to the fake mode + if not tracing_context.fake_mode or not tracing_context.fake_mode.shape_env: + return contextlib.nullcontext() + shape_env = tracing_context.fake_mode.shape_env + return shape_env.suppress_guards() + + +def run_and_get_cpp_code( + fn: Callable[P, _T], *args: P.args, **kwargs: P.kwargs +) -> tuple[_T, str]: + # We use the patch context manager instead of using it as a decorator. + # In this way, we can ensure that the attribute is patched and unpatched correctly + # even if this run_and_get_cpp_code function is called multiple times. + with unittest.mock.patch.object(config, "debug", True): + torch._dynamo.reset() + import io + import logging + + log_capture_string = io.StringIO() + ch = logging.StreamHandler(log_capture_string) + from torch._inductor.codecache import output_code_log + + output_code_log.addHandler(ch) + prev_level = output_code_log.level + output_code_log.setLevel(logging.DEBUG) + result = fn(*args, **kwargs) + s = log_capture_string.getvalue() + output_code_log.setLevel(prev_level) + output_code_log.removeHandler(ch) + return result, s + + +def shape_env_from_inputs(inputs: Sequence[InputType]) -> ShapeEnv | None: + fake_mode = detect_fake_mode(inputs) + + # TODO(voz): It would be nice to enable this assert, but there are lots of tests that + # pass in real inputs for now. + # if len(inputs) > 0: + # assert fake_mode is not None, breakpoint() + + if fake_mode is not None: + return fake_mode.shape_env + + # When there are no tensor inputs, get shape_env from the first SymInt. + for input in inputs: + if isinstance(input, torch.SymInt): + return input.node.shape_env + + # Check tensor sizes and strides for SymInt values + if isinstance(input, torch.Tensor): + for size in input.size(): + if isinstance(size, torch.SymInt): + return size.node.shape_env + for stride in input.stride(): + if isinstance(stride, torch.SymInt): + return stride.node.shape_env + + # TODO(voz): Should we always have one anyway? + return None + + +def align_inputs_from_check_idxs( + model: Callable[[list[InputType]], _T], + inputs_to_check: Sequence[int], + mutated_input_idxs: OrderedSet[int], +) -> Callable[[list[InputType]], _T]: + if len(inputs_to_check) == 0: + return model + + def run(new_inputs: list[InputType]) -> Any: + old_tensors, new_tensors = copy_misaligned_inputs( + new_inputs, inputs_to_check, mutated_input_idxs + ) + out = model(new_inputs) + + # If a mutated tensor was cloned to be aligned, we need to reflect back the mutation to the + # original tensor. + if len(old_tensors): + torch._foreach_copy_(old_tensors, new_tensors) + + return out + + return run + + +def clone_preserve_strides(x: torch.Tensor) -> torch.Tensor: + if 0 in x.size(): + # Short-circuits if the shape has no elements + needed_size = 0 + else: + needed_size = ( + sum((shape - 1) * stride for shape, stride in zip(x.size(), x.stride())) + 1 + ) + buffer = torch.as_strided(x, (needed_size,), (1,)).clone() + return torch.as_strided(buffer, x.size(), x.stride()) + + +def copy_misaligned_inputs( + new_inputs: list[InputType], + check_inputs_idxs: Sequence[int], + return_pair_idxs: OrderedSet[int] | None = None, +) -> tuple[list[torch.Tensor], list[torch.Tensor]]: + """ + Clones misaligned tensors which we inferred were aligned. Returns a tuple of [old_tensors], [new_tensors] for every + cloned tensor which is in `return_pair_idxs`. + """ + + old_tensors: list[torch.Tensor] = [] + new_tensors: list[torch.Tensor] = [] + + # hoist above loop because this is on the hot path + ret_pair_defined = return_pair_idxs is not None + for i in check_inputs_idxs: + _inp = new_inputs[i] + if not isinstance(_inp, torch.Tensor): + raise AssertionError(f"Expected tensors only, but got: {type(_inp)}") + if _inp.data_ptr() % ALIGNMENT: + new_inputs[i] = clone_preserve_strides(_inp) + + if ret_pair_defined and i in return_pair_idxs: # type: ignore[operator] + old_tensors.append(_inp) + new_tensors.append(new_inputs[i]) # type: ignore[arg-type] + + return old_tensors, new_tensors + + +def remove_unaligned_input_idxs( + inputs: Sequence[InputType], + static_input_idxs: Sequence[int], +) -> Sequence[int]: + """ + We require all inputs to be aligned, so introduce a copy for any + that aren't. + """ + aligned_static_input_idxs = [] + for idx in static_input_idxs: + input = inputs[idx] + if isinstance(input, torch.Tensor) and (input.data_ptr() % ALIGNMENT) == 0: + aligned_static_input_idxs.append(idx) + if len(aligned_static_input_idxs) != len(static_input_idxs): + return aligned_static_input_idxs + return static_input_idxs + + +def expr_fits_within_32bit(e: sympy.Expr) -> bool: + """Check if an expression fits within 32-bit integer range. + + NOTE: This function intentionally does not install guards. Callers are + responsible for guarding (e.g. via check_leq) when they decide to use + 32-bit indexing based on this result. + """ + from .virtualized import V + + int_max = torch.iinfo(torch.int32).max + guarding_hint_or_throw = V.graph.sizevars.guarding_hint_or_throw + has_guarding_hint = V.graph.sizevars.shape_env.has_guarding_hint + + if config.assume_32bit_indexing: + V.graph.sizevars.check_leq(e, int_max) # type: ignore[arg-type] + return True + + # Allow for unhinted e as long as we can still statically prove + # (e.g., via ValueRanges) that it is still in bounds + if V.graph.sizevars.statically_known_true(e <= int_max): + return True + + # AOTI doesn't guard on < 2**32, so checking hints isn't a viable option, + # in case the hinted value is < 2**32, but the allowed range is larger. + # However, to prevent possible perf regressions on pre-existing AOTI models + # which don't set an upper bound on the valid range, we'll skip the check. + # To recap: + # - If using AOTI: + # - If allowed range has no upper bound, then check the hint to determine + # whether this fits in int32 + # - If allowed range does have an upper bound, then obey the upper bound + # (check whether upper bound < int32_max) without checking the hint. + + if V.aot_compilation: + # check whether value has an upper bound (1e20 is > INT64_MAX, assume + # there is no upper bound if it can be larger than 1e20) + if V.graph.sizevars.statically_known_true(e < 1e20): + # if so, then assume int_max < upper bound < inf + # so this could potentially have int64 values + return False + + # Otherwise, the hint MUST exist and be in range + return has_guarding_hint(e) and guarding_hint_or_throw(e) <= int_max + + +def set_tracing_context_output_strides( + example_inputs: Sequence[Any], compiled_graph: CompiledFxGraph +) -> None: + # Return the output strides to the caller via TracingContext + context = torch._guards.TracingContext.try_get() + if context is not None and context.output_strides is not None: + if len(context.output_strides) != 0: + raise AssertionError( + f"Expected empty output_strides, got length {len(context.output_strides)}" + ) + shape_env = shape_env_from_inputs(example_inputs) + if compiled_graph.output_strides is None: + raise AssertionError("compiled_graph.output_strides is None") + for exprs in compiled_graph.output_strides: + if exprs is None: + context.output_strides.append(None) + else: + fakify_first_call = False + if ctx := torch._guards.TracingContext.try_get(): + fakify_first_call = ctx.fakify_first_call + + def map_expr(e: Any) -> float | int | SymInt | SymFloat | SymBool: + if shape_env is None: + return int(e) + if fakify_first_call: + return shape_env.deserialize_symexpr(e) + return shape_env.evaluate_symexpr(e) + + context.output_strides.append( + tuple(map_expr(e) for e in exprs) # type: ignore[misc] + ) + + +def should_use_remote_fx_graph_cache() -> bool: + if config.fx_graph_remote_cache is not None: + return config.fx_graph_remote_cache + if not config.is_fbcode(): + return False + + if torch._utils_internal.is_fb_unit_test(): + return False + + try: + from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION + except ModuleNotFoundError: + return False + + return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int( + "pytorch/remote_cache:fx_graph_memcache_version" + ) + + +def normalize_name(name: str) -> str: + return re.sub(r"[^a-zA-Z0-9_]", "_", name) + + +# correct cases where Triton types names don't match PyTorch +_triton_type_mapping = { + "tl.bool": "tl.int1", + "tl.float8_e4m3fn": "tl.float8e4nv", + "tl.float8_e5m2": "tl.float8e5", + "tl.float8_e4m3fnuz": "tl.float8e4b8", + "tl.float8_e5m2fnuz": "tl.float8e5b16", + # TODO: remove when support is added in triton + # https://github.com/triton-lang/triton/issues/6054 + "tl.float8_e8m0fnu": "tl.uint8", + "tl.float4_e2m1fn_x2": "tl.uint8", +} +_torch_triton_mapping = {v: k for k, v in _triton_type_mapping.items()} + + +_triton_type_re = re.compile(r"^.*[.]") + + +def triton_type(dtype: torch.dtype) -> str: + """Convert torch.dtype to triton type""" + triton_type_name = _triton_type_re.sub("tl.", str(dtype)) + return _triton_type_mapping.get(triton_type_name, triton_type_name) + + +def triton_type_to_torch(dtype: str) -> torch.dtype: + adjusted_type = _torch_triton_mapping.get(dtype, dtype) + type_name = adjusted_type.replace("tl.", "") + out_dtype = getattr(torch, type_name) + if not isinstance(out_dtype, torch.dtype): + raise AssertionError(f"Expected torch.dtype, got {type(out_dtype)}") + return out_dtype + + +def is_same_tensor(data: torch.Tensor, value: torch.Tensor) -> bool: + return ( + not data.is_mkldnn # type: ignore[bad-return] + and data.size() == value.size() + and data.stride() == value.stride() + and data.dtype == value.dtype + and data.device == value.device + and data.untyped_storage().data_ptr() == value.untyped_storage().data_ptr() + and data.storage_offset() == value.storage_offset() + ) + + +def is_same_mkldnn_tensor(data: torch.Tensor, value: torch.Tensor) -> bool: + return ( + data.is_mkldnn + and data.size() == value.size() + and data.dtype == value.dtype + and data.device == value.device + and torch.ops.mkldnn.data_ptr(data) == torch.ops.mkldnn.data_ptr(value) + ) + + +@functools.cache +def boolean_ops() -> tuple[str, ...]: + return ( + "isinf", + "isnan", + "logical_not", + "logical_and", + "signbit", + "and_", + "le", + "lt", + "ge", + "gt", + "eq", + "ne", + "or_", # TODO should remove this op + "xor", + ) + + +@dataclasses.dataclass +class OpDtypeRule: + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND + override_return_dtype: torch.dtype | None + + +op_dtype_propagation_rules: dict[str, OpDtypeRule] = {} + + +def register_op_dtype_propagation_rules( + name: str, + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND, + override_return_dtype: torch.dtype | None, +) -> None: + op_dtype_propagation_rules[name] = OpDtypeRule( + type_promotion_kind, override_return_dtype + ) + + +op_requires_libdevice_fp64: OrderedSet[str] = OrderedSet() + + +def register_op_requires_libdevice_fp64(name: str) -> None: + op_requires_libdevice_fp64.add(name) + + +def get_current_backend(device_type: str | None = None) -> str: + from torch._inductor.virtualized import V + + if not device_type: + device_type = V.graph.get_current_device_or_throw().type + if device_type == "cpu": + return config.cpu_backend + elif device_type == "mps": + return "mps" + elif device_type == "xpu": + return config.xpu_backend + elif device_type == "tpu": + return config.tpu_backend + else: + return config.cuda_backend + + +def device_supports_fp64(device: torch.device | None) -> bool: + """Check if the given device supports float64.""" + if device is not None and device.type == "xpu": + return torch.xpu.get_device_properties(device).has_fp64 + return True + + +def upcast_compute_type(dtype: torch.dtype) -> torch.dtype: + """Maybe upcast [b]float16 to float32""" + if ( + dtype in (torch.float16, torch.bfloat16) + and config.triton.codegen_upcast_to_fp32 + and get_current_backend() == "triton" + ): + return torch.float32 + return dtype + + +KeyType = TypeVar("KeyType") +ValType = TypeVar("ValType") + + +class ScopedDict(MutableMapping[KeyType, ValType]): + """ + A dictionary-like object that allows for scoped updates. It maintains + an original dictionary and a set of new items that can override + the original items within the scope. The original dictionary is + unmodified. + """ + + def __init__(self, original_dict: Mapping[KeyType, ValType]): + self.original_dict = original_dict + self.new_items: dict[KeyType, ValType] = {} + + def __getitem__(self, key: KeyType) -> ValType: + if key in self.new_items: + return self.new_items[key] + return self.original_dict[key] + + def __setitem__(self, key: KeyType, value: ValType) -> None: + self.new_items[key] = value + + def __contains__(self, key: object) -> bool: + return key in self.new_items or key in self.original_dict + + def get(self, key: KeyType, default: ValType | None = None) -> ValType | None: # type: ignore[override] + if key in self.new_items: + return self.new_items[key] + return self.original_dict.get(key, default) + + def __len__(self) -> int: + n = len(self.original_dict) + for k in self.new_items: + if k not in self.original_dict: + n += 1 + return n + + def __iter__(self) -> Iterator[KeyType]: + yield from self.original_dict + for k in self.new_items: + if k not in self.original_dict: + yield k + + def __bool__(self) -> bool: + return bool(self.original_dict or self.new_items) + + def __delitem__(self, key: KeyType) -> None: + raise NotImplementedError + + +@dataclass_transform(frozen_default=True) +def ir_dataclass(cls: type[Any] | None = None, /, *, frozen: bool = True) -> Any: + def wrap(cls: _T) -> _T: + return dataclasses.dataclass(cls, kw_only=True, frozen=frozen) # type: ignore[call-overload] + + if cls is None: + return wrap + return wrap(cls) + + +def get_donated_idxs() -> list[int] | None: + tracing_context = torch._guards.TracingContext.try_get() + if tracing_context is not None and tracing_context.fw_metadata: + return tracing_context.fw_metadata.bw_donated_idxs + return None + + +class TritonAttrsDescriptorVersion(enum.Enum): + V0_NO_TRITON = 0 + V1_COMPILER = 1 # triton.compiler.compiler.AttrsDescriptor + V2_BACKENDS = 2 # triton.backends.compiler.AttrsDescriptor + V3_BACKENDS_TUPLE = ( + 3 # triton.backends.compiler.AttrsDescriptor, but with tuple support + ) + V4_DICT = 4 # a raw dict + + +@functools.cache +def get_triton_attrs_descriptor_version() -> TritonAttrsDescriptorVersion: + if importlib.util.find_spec("triton") is None: + return TritonAttrsDescriptorVersion.V0_NO_TRITON + + import triton.backends.compiler + import triton.compiler.compiler + + if hasattr(triton.backends.compiler, "AttrsDescriptor"): + # Triton 3.2.0 + # AttrsDescriptor was moved from triton.compiler.compiler to triton.backends.compiler. + # AttrsDescriptor and its serialization format were also changed. + + # TODO: implement V3_BACKENDS_TUPLE + # On Dec 9, 2024, tuple support (triton #5220) was implemented and breaks handling. + # We don't have a way to detect this (and haven't implemented this version) + return TritonAttrsDescriptorVersion.V2_BACKENDS + elif hasattr(triton.compiler.compiler, "AttrsDescriptor"): + # Triton 3.0.0 + return TritonAttrsDescriptorVersion.V1_COMPILER + else: + # After Jan 1, 2025 + # AttrsDescriptor was removed and replaced with a raw dict. + return TritonAttrsDescriptorVersion.V4_DICT + + +def triton_version_uses_attrs_dict() -> bool: + return get_triton_attrs_descriptor_version() == TritonAttrsDescriptorVersion.V4_DICT + + +def get_op_names(op: torch._ops.OperatorBase) -> tuple[str, str]: + op_overload_packet_name: str = op.name() + op_overload_name = ( + f"{op_overload_packet_name}.{op._overloadname}" + if isinstance(op, torch._ops.OpOverload) + else op_overload_packet_name + ) + return op_overload_packet_name, op_overload_name + + +def _fx_node_is_input_dependent_cudagraph_unsafe(fx_node: torch.fx.Node) -> bool: + """ + Check if an FX node is cudagraph-unsafe based on its input arguments. + + Some ops are only cudagraph-unsafe depending on their inputs (e.g., index_put + with boolean indices triggers .nonzero() during capture, but integer indices + are safe). + """ + from torch.fx.operator_schemas import normalize_function + + target = fx_node.target + if not isinstance(target, torch._ops.OpOverload): + return False + + # index_put with boolean indices triggers .nonzero() during capture + if target in ( + torch.ops.aten.index_put.default, + torch.ops.aten.index_put_.default, + torch.ops.aten._unsafe_index_put.default, + ): + normalized = normalize_function( + target, fx_node.args, fx_node.kwargs, normalize_to_only_use_kwargs=True + ) + if normalized is not None: + _, kwargs = normalized + indices = kwargs["indices"] + for idx in indices: + if idx is not None and idx.meta["val"].dtype in ( + torch.bool, + torch.uint8, + ): + return True + + return False + + +def is_cudagraph_unsafe_fx_node(fx_node: torch.fx.Node) -> bool: + """ + Check if an FX node is cudagraph-unsafe. + + This includes: + - Ops in FORBIDDEN_CUDAGRAPH_OPS (CPU sync, dynamic alloc, etc.) + - Ops with the cudagraph_unsafe tag + - Input-dependent unsafe ops (e.g., index_put with boolean indices) + - Ops with sparse tensor outputs + """ + target = fx_node.target + + # Check against the forbidden ops set + if str(target) in FORBIDDEN_CUDAGRAPH_OPS: + return True + + # Check for cudagraph_unsafe tag + if ( + isinstance(target, torch._ops.OpOverload) + and torch._C.Tag.cudagraph_unsafe in target.tags # type: ignore[attr-defined] + ): + return True + + # Check for input-dependent unsafety + if _fx_node_is_input_dependent_cudagraph_unsafe(fx_node): + return True + + # Check for sparse tensor outputs + if (val := fx_node.meta.get("val")) is not None: + vals = [val] if not isinstance(val, (list, tuple)) else val + for v in vals: + if isinstance(v, torch.Tensor) and v.is_sparse: + return True + + return False + + +def is_cudagraph_unsafe_op(node: Operation) -> bool: + """ + Returns True if the node is an op that is not cudagraphable. + This includes: + - Ops in FORBIDDEN_CUDAGRAPH_OPS (CPU sync, dynamic alloc, etc.) + - Ops with the cudagraph_unsafe tag + - index_put_ with boolean indices (triggers .nonzero() during capture) + - Control flow nodes (Switch, WhileLoop) + - Ops with sparse tensor outputs + """ + from . import ir + + # Control flow nodes are cudagraph-unsafe + if isinstance(node, (ir.Switch, ir.WhileLoop)): + return True + + if not isinstance(node, (ir.FallbackKernel, ir.ExternKernel)): + return False + + fx_node = getattr(node, "fx_node", None) + if fx_node is not None and is_cudagraph_unsafe_fx_node(fx_node): + return True + + return False + + +def get_ld_library_path() -> str: + path = os.environ.get("LD_LIBRARY_PATH", "") + if config.is_fbcode(): + from libfb.py.parutil import get_runtime_path + + runtime_path = get_runtime_path() + if runtime_path: + lib_path = os.path.join(runtime_path, "runtime", "lib") + path = os.pathsep.join([lib_path, path]) if path else lib_path + + return path + + +def is_codegen_graph_partition_subgraph(wrapper: PythonWrapperCodegen) -> bool: + from torch._inductor.codegen.wrapper import SubgraphPythonWrapperCodegen + + return ( + isinstance(wrapper, SubgraphPythonWrapperCodegen) + and wrapper.partition_signatures is not None + ) + + +def is_using_cudagraph_partition() -> bool: + return ( + torch._inductor.config.triton.cudagraphs + or _unstable_customized_partition_wrapper.wrapper is not None + ) and torch._inductor.config.graph_partition + + +def dtype_from_size(size: int) -> torch.dtype: + from .virtualized import V + + if V.graph.sizevars.statically_known_lt( + size, 2**31 + ) and V.graph.sizevars.statically_known_geq(size, -(2**31)): + return torch.int32 + else: + return torch.int64 + + +SUPPORTED_MKLDNN_DEVICES = ("cpu", "xpu") + + +def is_mkldnn_bf16_supported(device_type: str) -> bool: + """ + Returns True if the device supports MKL-DNN BF16. + """ + if device_type == "cpu": + return torch.ops.mkldnn._is_mkldnn_bf16_supported() + elif "xpu" in device_type: + # match "xpu", "xpu:0", "xpu:1", etc. + return True + return False + + +def is_mkldnn_fp16_supported(device_type: str) -> bool: + """ + Returns True if the device supports MKL-DNN FP16. + """ + if device_type == "cpu": + return torch.ops.mkldnn._is_mkldnn_fp16_supported() + elif "xpu" in device_type: + # match "xpu", "xpu:0", "xpu:1", etc. + return True + return False + + +def tabulate_2d(elements: Sequence[Sequence[T]], headers: Sequence[T]) -> str: + widths = [len(str(e)) for e in headers] + for row in elements: + if len(row) != len(headers): + raise AssertionError( + f"Row length {len(row)} != header length {len(headers)}" + ) + for i, e in enumerate(row): + widths[i] = max(widths[i], len(str(e))) + lines = [] + lines.append("|".join(f" {h:{w}} " for h, w in zip(headers, widths))) + # widths whitespace horizontal separators + total_width = sum(widths) + (len(widths) * 2) + (len(widths) - 1) + lines.append("-" * total_width) + for row in elements: + lines.append("|".join(f" {e:{w}} " for e, w in zip(row, widths))) + return "\n".join(lines) + + +def zip_dicts( + dict1: Mapping[KeyType, ValType], + dict2: Mapping[KeyType, ValType], + d1_default: ValType | None = None, + d2_default: ValType | None = None, +) -> Generator[tuple[KeyType, ValType | None, ValType | None], None, None]: + """ + Zip two dictionaries together, replacing missing keys with default values. + + Args: + dict1 (dict): The first dictionary. + dict2 (dict): The second dictionary. + d1_default (Any): the default value for the first dictionary + d2_default (Any): the default value for the second dictionary + + Yields: + tuple: A tuple containing the key, the value from dict1 (or d1_default if missing), + and the value from dict2 (or d2_default if missing). + """ + # Find the union of all keys + all_keys = OrderedSet(dict1.keys()) | OrderedSet(dict2.keys()) + + # Iterate over all keys + for key in all_keys: + # Get the values from both dictionaries, or default if missing + value1 = dict1.get(key) + value2 = dict2.get(key) + + yield ( + key, + value1 if value1 is not None else d1_default, + value2 if value2 is not None else d2_default, + ) + + +def maybe_aoti_standalone_config(config_patches: dict[str, Any]) -> dict[str, Any]: + """ + Ensures the configuration is internally consistent for standalone AOTInductor. + + If `aot_inductor_mode.compile_standalone` is set to True in the provided + `config_patches` (or falls back to the global config), this function ensures + that the following configs are also enabled: + - `aot_inductor.package_cpp_only` + + Args: + config_patches (dict[str, Any]): A dictionary of user-provided config + overrides for AOTInductor compilation. + + Returns: + dict[str, Any]: The possibly-updated `config_patches` dictionary. + """ + + def patch_config( + config_patches: dict[str, Any], config_name: str, config_value: Any + ) -> None: + value = config_patches.get(config_name, getattr(config, config_name)) + if value is None: + config_patches[config_name] = config_value + elif not value and value != config_value: + raise RuntimeError( + f"Invalid config: {config_name}={config_value} when aot_inductor_mode.compile_standalone is True." + ) + + def force_patch_config( + config_patches: dict[str, Any], config_name: str, config_value: Any + ) -> None: + value = config_patches.get(config_name, getattr(config, config_name)) + if value != config_value: + log.warning( + "Overriding: %s=%s when aot_inductor_mode.compile_standalone is True.", + config_name, + config_value, + ) + config_patches[config_name] = config_value + + compile_standalone = config_patches.get( + "aot_inductor_mode.compile_standalone", + config.aot_inductor_mode.compile_standalone, + ) + # Make a copy of the config_patches to avoid modifying the original dictionary, needed for testing + config_patches = config_patches.copy() + if compile_standalone: + # Standlaone AOTInductor means only generate cpp project for building a standalone binary + patch_config(config_patches, "aot_inductor.package_cpp_only", True) + # Standlaone AOTInductor needs to embed the kernel code in the binary + patch_config(config_patches, "aot_inductor.embed_kernel_binary", True) + # Default to use multi-arch kernel codegen for non-rocm GPU + patch_config( + config_patches, "aot_inductor.emit_multi_arch_kernel", not torch.version.hip + ) + patch_config( + config_patches, "aot_inductor.model_name_for_generated_files", "aoti_model" + ) + # TODO: change these two configs to default to None and use patch_config + force_patch_config( + config_patches, + "aot_inductor.link_libtorch", + config.test_configs.use_libtorch, + ) + force_patch_config(config_patches, "aot_inductor.dynamic_linkage", False) + + cross_target_platform = config_patches.get( + "aot_inductor.cross_target_platform", + config.aot_inductor.cross_target_platform, + ) + + package_constants_in_so = config_patches.get( + "aot_inductor.package_constants_in_so", + config.aot_inductor.package_constants_in_so, + ) + + if cross_target_platform == "windows" and package_constants_in_so: + raise RuntimeError( + "config.aot_inductor.package_constants_in_so is not supported for windows cross-compilation. " + "Please use config.aot_inductor.package_constants_on_disk_format = binary_blob." + ) + + return config_patches + + +def determine_aoti_mmap_flags(consts_size: int) -> tuple[bool, bool]: + """ + Decide whether we should mmap weights, and whether to store the weights with .so. + + If force_mmap_weights or package_constants_on_disk_format == "binary_blob" configs are set, respect the config. + + Returns tuple (use_external_weights, use_mmap_weights). + """ + + if ( + config.aot_inductor.force_mmap_weights + and config.aot_inductor.package_constants_on_disk_format == "binary_blob" + ): + raise RuntimeError( + "config.aot_inductor.package_constants_on_disk_format = binary_blob and " + "config.aot_inductor.force_mmap_weights cannot both be True." + ) + + if config.aot_inductor.force_mmap_weights: + if config.aot_inductor.cross_target_platform == "windows": + raise RuntimeError( + "when cross_target_platform is windows, use_mmap_weights should not be true." + ) + use_mmap_weights = True + use_external_weights = False + return use_external_weights, use_mmap_weights + + if config.aot_inductor.package_constants_on_disk_format == "binary_blob": + use_external_weights = True + use_mmap_weights = False + return use_external_weights, use_mmap_weights + + if consts_size <= 2_000_000_000: + return False, False + + use_external_weights = False + use_mmap_weights = not config.is_fbcode() + + return use_external_weights, use_mmap_weights + + +def is_valid_aoti_model_name() -> bool: + """ + Validates if a model name is suitable for use in code generation. + + """ + from torch._inductor import config + + model_name = config.aot_inductor.model_name_for_generated_files + + if model_name is None: + return True + + if not isinstance(model_name, str): + raise ValueError("Invalid AOTI model name: Model name must be a string") + + if model_name == "": + return True + + # Can only contain alphanumeric characters and underscores + if not re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", model_name): + raise ValueError( + "Invalid AOTI model name: Model name can only contain letters, numbers, and underscores" + ) + + return True + + +def get_free_symbols(x: IterateExprs, unbacked_only: bool) -> OrderedSet[sympy.Symbol]: + if unbacked_only: + return free_unbacked_symbols(x) + else: + return free_symbols(x) + + +def python_subprocess_env() -> dict[str, str]: + """ + Get a base environment for running Python subprocesses. + """ + + torch_package_root = os.path.dirname( + os.path.dirname(os.path.abspath(torch.__file__)) + ) + env = { + # Inherit the environment of the current process. + **os.environ, + # Set the PYTHONPATH so the subprocess can find torch. + "PYTHONPATH": os.environ.get( + "TORCH_CUSTOM_PYTHONPATH", + os.pathsep.join((torch_package_root, *sys.path)), + ), + } + + # Set PYTHONHOME for internal builds, to account for builds that bundle the + # runtime. Otherwise they will use the libraries and headers from the + # platform runtime instead. + # + # This can't be done for external builds. The process can be run from a + # venv and that won't include Python headers. The process needs to be able + # to search for and find the platform runtime. + if config.is_fbcode(): + env["PYTHONHOME"] = sysconfig.get_path("data") + + return env + + +def apply_subprocess_env(extra_env: Mapping[str, str | None] | None) -> None: + """ + Apply environment updates sent from a parent process to a persistent worker. + A None value means the variable is absent in the parent and should be + removed from the worker, rather than leaving a stale value behind. + """ + if extra_env is None: + return + + for key, value in extra_env.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + + +@contextlib.contextmanager +def patch_subprocess_env( + extra_env: Mapping[str, str | None] | None, +) -> Iterator[None]: + """ + Temporarily apply parent process environment updates in a persistent worker. + """ + if extra_env is None: + yield + return + + old_env = dict(os.environ) + apply_subprocess_env(extra_env) + try: + yield + finally: + os.environ.clear() + os.environ.update(old_env) + + +@dataclasses.dataclass(frozen=True) +class CUDAGraphWrapperMetadata: + """ + Metadata for Customized CUDAGraphWrapper. + + Currently assumes there is 1 dynamo graph and will extend to + multiple graphs in the future. + """ + + # The number of partitions that are cudagraphable. + num_partitions: int + + # Index of the current partition. + partition_index: int + + +PartitionFnType = Callable[..., Any] +CUDAGraphWrapperType = Callable[ + [PartitionFnType, CUDAGraphWrapperMetadata], PartitionFnType +] + + +# only incremented by user call of mark_step_begin +class CUDAGraphWrapper: + wrapper: CUDAGraphWrapperType | None = None + + +# A customized partition wrappers from users. Interface should be: +# +# def wrapper(fn: PartitionFnType, metadata: CUDAGraphWrapperMetadata) -> PartitionFnType +# +# Inductor generates N wrapper functions for N partition functions, and mechanically wrap +# each partition fn with the generated wrapper function. Users need to handle all details +# such as static inputs, dynamic shapes, etc. +# Users could customize the wrapper based on the metadata. One example is to have special +# handle for the first and last wrapper function. +# +# Warning: This API is unstable and may change in the future. +_unstable_customized_partition_wrapper = CUDAGraphWrapper() + + +def set_customized_partition_wrappers(wrapper: CUDAGraphWrapperType) -> None: + _unstable_customized_partition_wrapper.wrapper = wrapper + + +def snode_args_kwargs(snode: BaseSchedulerNode) -> tuple[list[Any], dict[str, Any]]: + node = cast("ExternKernel", snode.node) + if isinstance(node, torch._inductor.ir.FallbackKernel): + args, kwargs = node.unflatten_args(node.inputs, node.constant_args) + else: + args = [*node.inputs, *node.constant_args] + kwargs = node.kwargs + + args = node.fill_non_provided_args(args, kwargs) + kwargs = dict(kwargs) + op_overload = getattr(node, "op_overload", None) + if isinstance(op_overload, torch._ops.OpOverload): + positional_arg_names = [ + arg.name for arg in op_overload._schema.arguments if not arg.kwarg_only + ] + for arg_name in positional_arg_names[: len(args)]: + kwargs.pop(arg_name, None) + flat_args, flat_args_pytree_spec = pytree.tree_flatten((args, kwargs)) + + def _is_tensor_ir(x) -> bool: # type: ignore[no-untyped-def] + return isinstance(x, torch._inductor.ir.IRNode) and not isinstance( + x, + (torch._inductor.ir.GeneratorState, torch._inductor.ir.OpaqueObjectState), + ) + + flat_args = [ + torch._inductor.ir.ir_node_to_tensor(a, replace_symbols_with_hints=True) + if _is_tensor_ir(a) + else a + for a in flat_args + ] + + def _tensor(size, dtype, device) -> torch.Tensor: # type: ignore[no-untyped-def] + return torch.empty(size, dtype=dtype, device=device) + + def to_real_tensor(e: Any) -> Any: + if not isinstance(e, torch.Tensor): + return e + out = _tensor(e.size(), e.dtype, e.device) + return out + + flat_args = [to_real_tensor(a) for a in flat_args] + args, kwargs = pytree.tree_unflatten(flat_args, flat_args_pytree_spec) + return args, kwargs + + +def is_nonfreeable_buffers(dep: Dep) -> bool: + from .virtualized import V + + dep_name = dep.name + # Subgraphs have a prefix for the name, cleanup the prefix + # before checking for known strings. + if V.graph.name: + dep_name = dep_name.removeprefix(V.graph.name + "_") + return dep_name.startswith( + ("primals_", "arg", "fwd_rng_state", "bwd_rng_state", "tangents") + ) + + +# Make sure to also include your jinja templates within torch_package_data in setup.py, or this function won't be able to find them +def load_template(name: str, template_dir: Path) -> str: + """Load a template file and return its content.""" + path = template_dir / f"{name}.py.jinja" + try: + with open(path, encoding="utf-8") as f: + return f.read() + except UnicodeDecodeError as e: + # Name the offending file: a bare UnicodeDecodeError hides which + # template is malformed, which is easy to misdiagnose when it surfaces + # deep inside kernel lowering. + raise ValueError(f"Template {path} is not valid UTF-8: {e}") from e + + +def should_fallback_by_default(node: torch.fx.Node) -> bool: + """Decide whether fallback for a node. This is only used in inductor lite mode.""" + target = node.target + + if not isinstance(target, (torch._ops.OpOverload, torch._ops.HigherOrderOperator)): + raise AssertionError( + f"Expected OpOverload or HigherOrderOperator, but found {type(target)}" + ) + + if not config.fallback_by_default: + return False + + # some ops need special handle due to dynamic shapes. we can avoid + # fallback if they do not impact numerics. + skip_fallback_due_to_dynamic_shape = OrderedSet( + [ + torch.ops.aten._assert_scalar.default, + torch.ops.aten.lift_fresh_copy.default, + ] + ) + + if target in skip_fallback_due_to_dynamic_shape: + return False + + # Most hops have registered lowering. We should follow the lowering and not fallback. + # However, in rare cases, hops may not register lowering, such as + # torch.ops.higher_order.triton_kernel_wrapper_functional. We should fallback for + # these hops. + fallback_hops = OrderedSet( + [torch.ops.higher_order.triton_kernel_wrapper_functional] + ) + + if isinstance(target, torch._ops.HigherOrderOperator): + return target in fallback_hops + + return not _needs_inductor_compile(node) + + +# Collective operation names for specialized benchmarking +COLLECTIVE_OPS = OrderedSet( + [ + "torch.ops._c10d_functional.all_reduce.default", + "torch.ops._c10d_functional.all_reduce_.default", + "torch.ops._c10d_functional.all_gather_into_tensor.default", + "torch.ops._c10d_functional.reduce_scatter_tensor.default", + "torch.ops._c10d_functional.all_to_all_single.default", + "torch.ops._c10d_functional_autograd.all_reduce.default", + "torch.ops._c10d_functional_autograd.all_gather_into_tensor.default", + "torch.ops._c10d_functional_autograd.reduce_scatter_tensor.default", + "torch.ops._c10d_functional_autograd.all_to_all_single.default", + "torch.ops._c10d_functional.isend.default", + "torch.ops._c10d_functional.irecv.default", + "torch.ops._c10d_functional.batch_p2p_ops.default", + ] +) + + +def is_collective_op(op_name: str) -> bool: + """Check if an operation is a collective operation.""" + return op_name in COLLECTIVE_OPS + + +@lru_cache +def tlx_only_cuda_options() -> list[str]: + try: + # Succeeds only when fbtriton (a Triton fork) is installed + from triton.language.extra.tlx.inductor.registry import tlx_only_cuda_options + + return tlx_only_cuda_options + + except ImportError: + return [] + + +def _round_up(x: int, y: int) -> int: + """Round x up to the nearest multiple of y.""" + return ((x + y - 1) // y) * y + + +def _infer_scale_swizzle_impl( + mat_size: tuple[Any, Any], + scale_size: tuple[Any, ...], + scale_numel: Any, + mat_dtype: torch.dtype, + scale_dtype: torch.dtype, + eq_fn: Callable[[Any, Any], bool], +) -> tuple[Any | None, Any | None]: + """ + Core implementation for scale/swizzle inference. + """ + from torch.nn.functional import ScalingType, SwizzleType + + # Tensor-wise: single scale for entire tensor + if eq_fn(scale_numel, 1): + return ScalingType.TensorWise, SwizzleType.NO_SWIZZLE + + # Row-wise: one scale per row or column + if len(scale_size) >= 2: + if (eq_fn(scale_size[0], mat_size[0]) and eq_fn(scale_size[1], 1)) or ( + eq_fn(scale_size[0], 1) and eq_fn(scale_size[1], mat_size[1]) + ): + return ScalingType.RowWise, SwizzleType.NO_SWIZZLE + + # Block-wise 1x128 / 128x1 (DeepGemm style) + if ( + eq_fn(scale_size[0], mat_size[0]) + and eq_fn(scale_size[1], ceildiv(mat_size[1], 128)) + ) or ( + eq_fn(scale_size[1], mat_size[1]) + and eq_fn(scale_size[0], ceildiv(mat_size[0], 128)) + ): + return ScalingType.BlockWise1x128, SwizzleType.NO_SWIZZLE + + # Block-wise 128x128 + if eq_fn(scale_size[0], ceildiv(mat_size[0], 128)) and eq_fn( + scale_size[1], ceildiv(mat_size[1], 128) + ): + return ScalingType.BlockWise128x128, SwizzleType.NO_SWIZZLE + + # Adjust for packed FP4 data (2 values per element) + K_multiplier = 2 if mat_dtype == torch.float4_e2m1fn_x2 else 1 + + # NVFP4: BlockWise1x16 with float8_e4m3fn scales + if mat_dtype == torch.float4_e2m1fn_x2 and scale_dtype == torch.float8_e4m3fn: + if torch.xpu._is_compiled(): + # XPU: no swizzle + expected_numel_a = ceildiv(mat_size[0], 16) * K_multiplier * mat_size[1] + expected_numel_b = ceildiv(K_multiplier * mat_size[1], 16) * mat_size[0] + if eq_fn(scale_numel, expected_numel_a) or eq_fn( + scale_numel, expected_numel_b + ): + return ScalingType.BlockWise1x16, SwizzleType.NO_SWIZZLE + else: + # NVIDIA: uses swizzled 32x4x4 layout + expected_numel_a = _round_up(mat_size[0], 128) * _round_up( + ceildiv(K_multiplier * mat_size[1], 16), 4 + ) + expected_numel_b = _round_up(mat_size[1], 128) * _round_up( + ceildiv(K_multiplier * mat_size[0], 16), 4 + ) + if eq_fn(scale_numel, expected_numel_a) or eq_fn( + scale_numel, expected_numel_b + ): + return ScalingType.BlockWise1x16, SwizzleType.SWIZZLE_32_4_4 + + # MXFP8: BlockWise1x32 with float8_e8m0fnu scales + if scale_dtype == torch.float8_e8m0fnu: + if not torch.version.hip and not torch.xpu._is_compiled(): + # NVIDIA: uses swizzled 32x4x4 layout + expected_numel_a = _round_up(mat_size[0], 128) * _round_up( + ceildiv(K_multiplier * mat_size[1], 32), 4 + ) + expected_numel_b = _round_up(mat_size[1], 128) * _round_up( + ceildiv(K_multiplier * mat_size[0], 32), 4 + ) + if eq_fn(scale_numel, expected_numel_a) or eq_fn( + scale_numel, expected_numel_b + ): + return ScalingType.BlockWise1x32, SwizzleType.SWIZZLE_32_4_4 + else: + # AMD/XPU: no swizzle + expected_numel_a = ceildiv(mat_size[0], 32) * K_multiplier * mat_size[1] + expected_numel_b = ceildiv(K_multiplier * mat_size[1], 32) * mat_size[0] + if eq_fn(scale_numel, expected_numel_a) or eq_fn( + scale_numel, expected_numel_b + ): + return ScalingType.BlockWise1x32, SwizzleType.NO_SWIZZLE + + return None, None + + +def infer_scale_swizzle( + mat: torch.Tensor, scale: torch.Tensor +) -> tuple[Any | None, Any | None]: + """ + Infer the scaling type and swizzle mode from matrix and scale tensor shapes/dtypes. + + This function determines how scale factors are laid out relative to the matrix: + - TensorWise: Single scale for entire tensor + - RowWise: One scale per row + - BlockWise1x128/128x128: Block-scaled with float32 scales + - BlockWise1x32: MXFP8 with float8_e8m0fnu scales (swizzled on NVIDIA) + - BlockWise1x16: NVFP4 with float8_e4m3fn scales (swizzled) + + Args: + mat: The matrix tensor (FP8 or FP4) + scale: The scale factor tensor + + Returns: + Tuple of (ScalingType, SwizzleType) or (None, None) if unrecognized + """ + return _infer_scale_swizzle_impl( + mat_size=(mat.shape[0], mat.shape[1]), + scale_size=tuple(scale.shape), + scale_numel=scale.numel(), + mat_dtype=mat.dtype, + scale_dtype=scale.dtype, + eq_fn=lambda a, b: a == b, + ) + + +def infer_scale_swizzle_ir( + mat: Buffer, + scale: Buffer, + transpose: bool = False, +) -> tuple[Any | None, Any | None]: + """ + Infer the scaling type and swizzle mode for IR nodes (used during graph lowering). + + This is the IR-compatible version of infer_scale_swizzle, using symbolic + size comparisons via V.graph.sizevars.statically_known_equals. + """ + from torch._inductor.virtualized import V + + mat_size = mat.get_size() + scale_size = scale.get_size() + + # Handle transposed matrix + if transpose: + mat_size = (mat_size[1], mat_size[0]) + + # Compute scale numel symbolically + scale_numel = functools.reduce(operator.mul, scale_size, 1) if scale_size else 1 + + def symbolic_eq(a: Any, b: Any) -> bool: + """Compare values using symbolic equality when possible.""" + return V.graph.sizevars.statically_known_equals(a, b) + + return _infer_scale_swizzle_impl( + mat_size=(mat_size[0], mat_size[1]) if len(mat_size) >= 2 else (mat_size[0], 1), + scale_size=tuple(scale_size), + scale_numel=scale_numel, + mat_dtype=mat.dtype, + scale_dtype=scale.dtype, + eq_fn=symbolic_eq, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/virtualized.py b/.venv/lib/python3.12/site-packages/torch/_inductor/virtualized.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9c19ae6c921576f688d7bd281547f0b8eca0e2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/virtualized.py @@ -0,0 +1,530 @@ +# mypy: allow-untyped-defs +""" +This file provides a number of "global" variables/handlers that are actually +thread local and dynamically scoped, with Inductor patching them to various +implementations depending on the situation. + +These handlers are interacted with in a fairly stylized way. Typically, +we will import V from this module:: + + from .virtualized import V + +Various handlers are accessible as attributes on this module; for example, +you might access ``V.graph.sizevars.optimization_hint`` to resolve a hint +associated with a symbolic expression. + +There are a few distinct usage patterns for virtualized global variables: + +1. Implicit argument passing. Examples: ``V.current_node``, ``V.aot_compilation``. + Use ``V.set_current_node`` to change what the current node is while we're + executing some region of code, so code inside that region can query ``V.current_node`` + to find out what it is. This is often more convenient than manually threading + the current node as an argument through all call stacks. + +2. Per-compilation global state. Examples: ``V.fake_mode``, ``V.graph``. For a + given ``compile_fx`` invocation, these typically don't change, but they are + associated with some internal state so they cannot just be global functions. + We install these objects at the beginning of compilation and then you can + conveniently access them without having to pass them around. + +3. Alternate define-by-run interpretations. Examples: ``V.ops``, ``V.kernel``. + A commonly used IR in Inductor is define-by-run: instead of maintaining + explicit syntax data structures, we instead represent loop bodies as + callable functions, which internally invoke operations defined on + ``V.ops``. To perform semantic analysis, print or code generate these + operations, we dynamically patch ``V.ops`` with an alternate handler with + the intended semantics and then run the callable function. For example, to + extract out a traditional (FX) graph representation of the define-by-run + IR, simply install a handler that records each ``ops`` call to a graph. + + TODO: Define a parent class / protocol that defines all of the operations + V.ops is expected to support. + +It is typically an error to access a virtualized global without having installed +an appropriate handler (you will get a NullHandler), although in some cases we +provide a default implementation. + +One last thing: although most virtualized globals are accessed via ``V``, ``ops`` is +ubiquitous enough to have its own top level variable, so you will typically see +``ops.constant(...)`` rather than ``V.ops.constant(...)``. In fact, these are not +equivalent; the former interface supports arithmetic overloads like ``x + y`` +instead of forcing ``ops.add(x, y)``, so it should be preferred. + +Some operators are seemingly unused, but they are implicitly used by ops_wrapper. +In particular, we typically have an operator for every basic pointwise PyTorch operation +supported. +""" + +from __future__ import annotations + +from contextlib import AbstractContextManager, contextmanager +from threading import local +from typing import Any, cast, Generic, TYPE_CHECKING, TypeVar + +from torch.utils._ordered_set import OrderedSet + +from .ops_handler import ( # noqa: F401 + DefaultHandler, + KernelFormatterHandler, + MockHandler, + OpsHandler, + ReductionType, + StoreMode, + WrapperHandler, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + from typing import Protocol + + import torch + from torch._inductor.choices import InductorChoices + from torch._inductor.codegen.common import CSE, CSEVariable, KernelArgs + from torch._inductor.codegen.cpp_utils import LocalBufferContext + from torch._inductor.debug import DebugContext + from torch._inductor.graph import GraphLowering + from torch._inductor.ir import ExternKernelNode + from torch._inductor.loop_body import InterpreterShim + from torch._inductor.scheduler import SchedulerNode + from torch._subclasses import FakeTensorMode + + from .distributed_autotune import _DistributedAutotuneState + from .utils import IndentedBuffer, InputType + + class KernelLike(Protocol): + """ + Structural type for ``V.kernel``. Its backing handler ranges from the + ``NullKernelHandler`` sentinel (installed while codegening the wrapper, + before any kernel exists) to a concrete ``Kernel`` subclass during + kernel codegen, so callers duck-type against this common surface rather + than a single class. The members declared explicitly below are the + common surface relied on regardless of backend; the ``__getattr__`` + fallback keeps backend-specific members (e.g. Triton/CPP tiling state) + accessible as ``Any`` without forcing every kernel class to enumerate + them here. + """ + + removed_buffers: OrderedSet[str] + inplaced_to_remove: OrderedSet[str] + index_dtype: str + cse: CSE[Any, Any] + compute: IndentedBuffer + current_node: SchedulerNode | None + args: KernelArgs + + def create_cse_var(self, *args: Any, **kwargs: Any) -> CSEVariable: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + + +threadlocal = local() + +T = TypeVar("T") + + +class NullHandler: + """ + Sentinel indicating that a global variable is unset ala None. Typically, + attempting to access the global variable before it's set is an error, but with + NullHandler it won't fail until you try to access an attribute on it. + """ + + +# If a virtualized value is set to _PoisonedVirtual then any attempt to get the +# value will result in an exception being raised. This is useful if we want to +# trap uninitialized reads of virtualized globals - for example when compiling +# in a subprocess we don't want the child reading globals that weren't copied +# from the parent. +_PoisonedVirtual = object() + + +class Virtualized(Generic[T]): + """ + Implements a global variable that redirects via thread local variable + (NB: construct this class to create the global variable; this is not + a singleton class!) + + This allows us to swap in different op implementations in codegen. + + NB: Despite the fact that we typically call these "handlers" (e.g., NullHandler is + the default value of the variable), we sometimes use these variables to + store other things, like booleans. + """ + + def __init__(self, vname: str, default: Callable[[], T] | type[NullHandler]): + self._vname = vname + self._key: str = f"__torchinductor_{vname}" + self._default = default + + def _set_handler(self, value: T) -> AbstractContextManager[None]: + prior = self._get_handler(False) + setattr(threadlocal, self._key, value) + + @contextmanager + def ctx(): + try: + yield + finally: + self._set_handler(prior) + + return ctx() + + def _get_handler(self, check_poisoned: bool = True) -> T: + try: + value = getattr(threadlocal, self._key) + if check_poisoned and value is _PoisonedVirtual: + raise RuntimeError( + f"Attempt to use poisoned virtualized value '{self._vname}'." + ) + return value + except AttributeError: + # TODO: To be honest, I feel we probably should just error in this + # case, instead of making a null handler that will probably error + # when you getattr on it + return self._default() # type: ignore[return-value] + + def __getattr__(self, name: str) -> Any: + return getattr(self._get_handler(), name) + + +class NullKernelHandler(NullHandler): + """ + We need access `V.kernel.removed_buffers` in DeferredLine class when there + is no kernel in the context. This happens when codegening the wrapper. + Initialize `removed_buffers` and `inplaced_to_remove` explicitly so we don't + need call 'getattr' with default value which is error prone to typo in + attribute name. + """ + + def __init__(self): + super().__init__() + self.removed_buffers = OrderedSet[Any]() + self.inplaced_to_remove = OrderedSet[Any]() + self.index_dtype = "tl.int64" + + def get_index_dtype_as_torch_dtype(self): + import torch + + if self.index_dtype == "tl.int64": + return torch.int64 + elif self.index_dtype == "tl.int32": + return torch.int32 + else: + raise ValueError(f"Unknown dtype: {self.index_dtype}") + + +_ops: Virtualized[OpsHandler[Any]] = Virtualized( + "ops", cast(type[OpsHandler[Any]], MockHandler) +) +_graph: Virtualized[GraphLowering] = Virtualized("graph", NullHandler) +_extern_kernel_nodes: Virtualized[list[ExternKernelNode]] = Virtualized( + "extern_kernel_nodes", NullHandler +) +_real_inputs: Virtualized[Sequence[InputType]] = Virtualized("real_inputs", NullHandler) +_fake_mode: Virtualized[FakeTensorMode] = Virtualized("fake_mode", NullHandler) +_kernel: Virtualized[KernelLike] = Virtualized("kernel", NullKernelHandler) +_debug: Virtualized[DebugContext] = Virtualized("debug", NullHandler) +_interpreter: Virtualized[InterpreterShim] = Virtualized("interpreter", NullHandler) +_aot_compilation: Virtualized[bool] = Virtualized("aot_compilation", NullHandler) +_current_node: Virtualized[torch.fx.Node] = Virtualized("current_node", NullHandler) +_local_buffer_context: Virtualized[LocalBufferContext] = Virtualized( + "local_buffer_context", NullHandler +) +_distributed_autotune_state: Virtualized[_DistributedAutotuneState] = Virtualized( + "distributed_autotune_state", NullHandler +) + + +def _active_user_lowering_ops_default() -> OrderedSet[Any]: + """Default factory for active_user_lowering_ops - returns persisted empty set.""" + rv: OrderedSet[Any] = OrderedSet() + setattr(threadlocal, _active_user_lowering_ops._key, rv) + return rv + + +_active_user_lowering_ops: Virtualized[OrderedSet[Any]] = Virtualized( + "active_user_lowering_ops", _active_user_lowering_ops_default +) + + +def _choices_default(): + """ + Lazy init the global choices handler + + We virtualize InductorChoices to allow changing inductor heuristics from out of tree. + """ + from torch._inductor import config + from torch._inductor.choices import InductorChoices + + if config.inductor_choices_class is not None: + rv = config.inductor_choices_class() + else: + rv = InductorChoices() + setattr(threadlocal, _choices._key, rv) + return rv + + +_choices: Virtualized[InductorChoices] = Virtualized("choices", _choices_default) + + +class OpsValue: + """The return type of most ops calls. + + This exists so we can overload magic methods, and write mathematical + expressions much more fluently. So instead of + + ops.add(ops.mul(ops.mul(ops.sub(ops.mul(_Ap2, x), _Ap3), x), x), _1) + + we can write + + (_Ap2 * x - _Ap3) * x * x + _1 + + """ + + value: Any + + def __init__(self, value): + self.value = value + + def __str__(self): + return str(self.value) + + def __repr__(self): + return f"OpsValue({self.value!r})" + + def __add__(self, other): + return ops.add(self, other) + + def __mul__(self, other): + return ops.mul(self, other) + + def __sub__(self, other): + return ops.sub(self, other) + + def __neg__(self): + return ops.neg(self) + + def __truediv__(self, other): + return ops.truediv(self, other) + + def __floordiv__(self, other): + return ops.floordiv(self, other) + + def __mod__(self, other): + return ops.mod(self, other) + + def __pow__(self, other): + return ops.pow(self, other) + + def __lt__(self, other): + return ops.lt(self, other) + + def __le__(self, other): + return ops.le(self, other) + + def __eq__(self, other): + return ops.eq(self, other) + + def __ne__(self, other): + return ops.ne(self, other) + + def __gt__(self, other): + return ops.gt(self, other) + + def __ge__(self, other): + return ops.ge(self, other) + + def __and__(self, other): + return ops.bitwise_and(self, other) + + def __or__(self, other): + return ops.bitwise_or(self, other) + + def __xor__(self, other): + return ops.bitwise_xor(self, other) + + def __invert__(self): + return ops.bitwise_not(self) + + def __rshfit__(self, n): + return ops.bitwise_right_shift(self, n) + + def __lshift__(self, n): + return ops.bitwise_left_shift(self, n) + + +class OpsWrapper(DefaultHandler): + """This wraps any returned IR values into an `OpsValue` instance, so that we + can overload the magic methods for writing mathematical expressions fluently. + """ + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + new_args = [OpsWrapper._unwrap(a) for a in args] + new_kwargs = {k: OpsWrapper._unwrap(v) for k, v in kwargs.items()} + return OpsWrapper._wrap(getattr(_ops, name)(*new_args, **new_kwargs)) + + @staticmethod + def _unwrap(x): + if isinstance(x, (list, tuple)): + return tuple(OpsWrapper._unwrap(v) for v in x) + if isinstance(x, OpsValue): + return x.value + return x + + @staticmethod + def _wrap(x): + if isinstance(x, (list, tuple)): + return tuple(OpsValue(v) for v in x) + return OpsValue(x) + + @staticmethod + # pyrefly: ignore [bad-override] + def indirect_indexing(index, size, check=True, wrap_neg=True): + # Returns a sympy value, not IR value + index = OpsWrapper._unwrap(index) + return _ops.indirect_indexing(index, size, check, wrap_neg) + + +ops: OpsHandler[Any] = OpsWrapper() + + +class _V: + MockHandler = MockHandler + KernelFormatterHandler = KernelFormatterHandler + WrapperHandler = WrapperHandler + + set_ops_handler: Callable[[OpsHandler[Any]], AbstractContextManager[None]] = ( + _ops._set_handler + ) + get_ops_handler: Callable[[], OpsHandler[Any]] = _ops._get_handler + set_graph_handler: Callable[[GraphLowering], AbstractContextManager[None]] = ( + _graph._set_handler + ) + set_extern_kernel_nodes: Callable[ + [list[ExternKernelNode]], AbstractContextManager[None] + ] = _extern_kernel_nodes._set_handler + set_real_inputs: Callable[[Sequence[InputType]], AbstractContextManager[None]] = ( + _real_inputs._set_handler + ) + get_real_inputs: Callable[[], Sequence[InputType]] = _real_inputs._get_handler + # Broad param: fake_mode may be installed as None (see compile_fx); the + # getter still narrows to FakeTensorMode for the common set-then-read path. + set_fake_mode: Callable[[Any], AbstractContextManager[None]] = ( + _fake_mode._set_handler + ) + get_fake_mode: Callable[[], FakeTensorMode] = _fake_mode._get_handler + set_kernel_handler: Callable[[Any], AbstractContextManager[None]] = ( + _kernel._set_handler + ) + set_debug_handler: Callable[[DebugContext], AbstractContextManager[None]] = ( + _debug._set_handler + ) + set_interpreter_handler: Callable[ + [InterpreterShim], AbstractContextManager[None] + ] = _interpreter._set_handler + set_aot_compilation: Callable[[bool], AbstractContextManager[None]] = ( + _aot_compilation._set_handler + ) + get_aot_compilation: Callable[[], bool] = _aot_compilation._get_handler + set_current_node: Callable[[torch.fx.Node], AbstractContextManager[None]] = ( + _current_node._set_handler + ) + get_current_node: Callable[[], torch.fx.Node] = _current_node._get_handler + set_local_buffer_context: Callable[ + [LocalBufferContext], AbstractContextManager[None] + ] = _local_buffer_context._set_handler + get_local_buffer_context: Callable[[], LocalBufferContext] = ( + _local_buffer_context._get_handler + ) + set_choices_handler: Callable[[InductorChoices], AbstractContextManager[None]] = ( + _choices._set_handler + ) + # Broad param: the state is reset by installing a NullHandler (see + # distributed_autotune.graph_context); the getter narrows on the read path. + set_distributed_autotune_state: Callable[[Any], AbstractContextManager[None]] = ( + _distributed_autotune_state._set_handler + ) + get_distributed_autotune_state: Callable[[], _DistributedAutotuneState] = ( + _distributed_autotune_state._get_handler + ) + set_active_user_lowering_ops: Callable[ + [OrderedSet[Any]], AbstractContextManager[None] + ] = _active_user_lowering_ops._set_handler + get_active_user_lowering_ops: Callable[[], OrderedSet[Any]] = ( + _active_user_lowering_ops._get_handler + ) + + @property + def ops(self) -> OpsHandler[Any]: + """The operator handler specific to the current codegen task""" + return _ops._get_handler() + + @property + def graph(self) -> GraphLowering: + """The graph currently being generated""" + return _graph._get_handler() + + @property + def extern_kernel_nodes(self) -> list[ExternKernelNode]: + """ + The extern_kernel_nodes needed for the entire graph, including the + subgraphs. + See `ProxyExecutor Design Note` in ir.py for more details + """ + return _extern_kernel_nodes._get_handler() + + @property + def real_inputs(self) -> Sequence[InputType]: + """non-fake example inputs""" + return _real_inputs._get_handler() + + @property + def fake_mode(self) -> FakeTensorMode: + """The graph currently being generated""" + return _fake_mode._get_handler() + + @property + def kernel(self) -> KernelLike: + """The kernel currently being generated""" + return _kernel._get_handler() + + # debug and interpreter intentionally keep an inferred (dynamic) return type. + # DebugContext dispatches via __getattr__ and InterpreterShim carries an + # Optional current_node, so pinning the concrete class here surfaces spurious + # callable/None errors at unrelated call sites. + @property + def debug(self): + return _debug._get_handler() + + @property + def interpreter(self): + return _interpreter._get_handler() + + @property + def aot_compilation(self) -> bool: + return _aot_compilation._get_handler() is True + + @property + def current_node(self) -> torch.fx.Node: + return _current_node._get_handler() + + @property + def local_buffer_context(self) -> LocalBufferContext: + return _local_buffer_context._get_handler() + + @property + def choices(self) -> InductorChoices: + return _choices._get_handler() + + @property + def distributed_autotune_state(self) -> _DistributedAutotuneState: + return _distributed_autotune_state._get_handler() + + @property + def active_user_lowering_ops(self) -> OrderedSet[Any]: + """Set of ops currently being lowered via user_lowerings (for recursion guard).""" + return _active_user_lowering_ops._get_handler() + + +V = _V() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/wrapper_benchmark.py b/.venv/lib/python3.12/site-packages/torch/_inductor/wrapper_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..1e400e19d4054f9bbbb351291b8428833f39661c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/wrapper_benchmark.py @@ -0,0 +1,525 @@ +import argparse +import datetime +import tempfile +from collections import defaultdict +from dataclasses import dataclass +from types import ModuleType +from typing import Any, Protocol + +import torch +from torch.autograd import DeviceType +from torch.utils._ordered_set import OrderedSet + +from .runtime.benchmarking import benchmarker +from .runtime.runtime_utils import create_bandwidth_info_str, get_num_bytes + + +class BenchmarkCallableType(Protocol): + def __call__(self, times: int, repeat: int) -> float: ... + + +_kernel_category_choices = [ + "foreach", + "persistent_reduction", + "pointwise", + "reduction", + "split_scan", + "template", +] + + +def get_kernel_category_by_source_code(src_code: str) -> str: + """ + Similar to get_kernel_category but use the source code. Call this API + if we have not compile the src_code to module yet. + """ + choices = [ + ch for ch in _kernel_category_choices if f"@triton_heuristics.{ch}" in src_code + ] + if len(choices) == 1: + return choices[0] + else: + return "unknown" + + +def get_kernel_category(kernel_mod: ModuleType) -> str: + """ + Given the module defining a triton kernel, return the category of the kernel. + Category can be one of: + - pointwise + - reduction + - persistent_reduction + + Currently we simply decide the category depending on what decorator is imported + by the kernel. + """ + choices = [ch for ch in _kernel_category_choices if ch in kernel_mod.__dict__] + if len(choices) == 1: + return choices[0] + else: + return "unknown" + + +def get_triton_kernel(mod: ModuleType): # type: ignore[no-untyped-def] + from torch._inductor.runtime.triton_heuristics import CachingAutotuner + + cand_list = [ + v + for k, v in mod.__dict__.items() + if k.startswith("triton_") and isinstance(v, CachingAutotuner) + ] + if len(cand_list) != 1: + raise AssertionError( + f"expected exactly one triton kernel, got {len(cand_list)}" + ) + return cand_list[0] + + +def benchmark_all_kernels( + benchmark_name: str, benchmark_all_configs: dict[Any, Any] | None +) -> None: + """ + An experimental API used only when config.benchmark_kernel is true. + + Run the kernel benchmarks for all the kernels cached in PyCodeCache. + Used in the compiled modules. + + Put this method here rather than codegen it for convenience since its implementation + does not change based on different graph modules being compiled. + """ + from torch._inductor.codecache import PyCodeCache + + nfound = 0 + for kernel_mod in PyCodeCache.modules: + kernel_key = kernel_mod.key + if not hasattr(kernel_mod, "get_args") or not hasattr(kernel_mod, "call"): + continue + + triton_kernel = get_triton_kernel(kernel_mod) + device_type = triton_kernel.device_props.type + kernel_category = get_kernel_category(kernel_mod) + args = kernel_mod.get_args() + num_in_out_ptrs = len( + [ + arg_name + for arg_name in triton_kernel.fn.arg_names + if arg_name.startswith("in_out_ptr") + ] + ) + num_gb = triton_kernel.inductor_meta.get("kernel_num_gb", None) + if num_gb is None: + num_gb = get_num_bytes(*args, num_in_out_args=num_in_out_ptrs) / 1e9 + + def get_info_str( + ms: float, + n_regs: Any | None, + n_spills: Any | None, + shared: Any | None, + prefix: str = "", + ) -> str: + if not any(x is None for x in [n_regs, n_spills, shared]): + kernel_detail_str = ( + f" {n_regs:3} regs {n_spills:3} spills {shared:8} shared mem" + ) + else: + kernel_detail_str = "" + + gb_per_s = num_gb / (ms / 1e3) + return create_bandwidth_info_str( + ms, num_gb, gb_per_s, prefix=prefix, suffix=kernel_detail_str + ) + + kernel_desc = ( + f"{benchmark_name:20} {kernel_category[:3].upper()} {kernel_key[:10]}" + ) + if benchmark_all_configs: + if not hasattr(kernel_mod, "benchmark_all_configs"): + raise AssertionError("kernel_mod is missing benchmark_all_configs") + bench_result = kernel_mod.benchmark_all_configs(args) + print(kernel_desc) + for launcher, ms in bench_result.items(): + print( + f" {get_info_str(ms, launcher.n_regs, launcher.n_spills, launcher.shared)} @ {launcher.config}" + ) + else: + ms = benchmarker.benchmark( + lambda: kernel_mod.call(args), + device=device_type, + rep=40, + ) + if len(triton_kernel.launchers) != 1: + raise AssertionError("Autotuner should have selected the best config") + launcher = triton_kernel.launchers[0] + print( + get_info_str( + ms, + launcher.n_regs, + launcher.n_spills, + launcher.shared, + prefix=f"{kernel_desc} ", + ) + ) + + nfound += 1 + if nfound == 0: + print( + "No kernel with benchmark functionality found. Make sure you run inductor with config.benchmark_kernel being True" + ) + + +@dataclass +class ProfileEvent: + category: str + key: str + self_device_time_ms: float + # the benchmark is run multiple times and we average the count across all the + # runs. It should be an integer but define a float just in case. + count: float + + +def parse_profile_event_list( + benchmark_name: str, + event_list: torch.autograd.profiler_util.EventList, + wall_time_ms: float, + nruns: int, + device_name: str, +) -> None: + """ + Parse and generate a report for an event_list. + """ + + def get_self_device_time( + ev: torch.autograd.profiler_util.EventList, + ) -> float: + """ + ev.self_device_time_total is in microsecond. Convert to millisecond. + """ + return ev.self_device_time_total / 1000 / nruns # type: ignore[attr-defined] + + all_events: dict[str, list[ProfileEvent]] = defaultdict(list) + + def add_event( + ev: torch.autograd.profiler_util.EventList, + category: str, + ) -> None: + profile_ev = ProfileEvent( + category=category, + key=ev.key, # type: ignore[attr-defined] + self_device_time_ms=get_self_device_time(ev), + count=ev.count / nruns, # type: ignore[operator] # average across all runs + ) + all_events[category].append(profile_ev) + + for ev in event_list: + if ev.is_legacy: + raise AssertionError("Don't support the legacy profiler") + if ev.device_type == DeviceType.CPU: + # ignore the event on CPU side + continue + + category = "unknown" + if ev.key.startswith("triton_"): + if ev.key.startswith("triton_poi"): + category = "triton_pointwise" + elif ev.key.startswith("triton_red"): + category = "triton_reduction" + elif ev.key.startswith("triton_per"): + category = "triton_persistent_reduction" + else: + category = "triton_unknown" + + add_event(ev, category) + + def report_category(category: str, profile_events: list[ProfileEvent]) -> float: + if not device_name: + return 0.0 + + from tabulate import tabulate + + profile_events.sort(key=lambda ev: ev.self_device_time_ms, reverse=True) + + rows = [] + total_time = 0.0 + print(f"\n == {category} category kernels == ") + for ev in profile_events: + total_time += ev.self_device_time_ms + percent = f"{ev.self_device_time_ms / wall_time_ms * 100:.2f}%" + rows.append([ev.key[:120], ev.self_device_time_ms, ev.count, percent]) + rows.append( + ["Total", total_time, "", f"{total_time / wall_time_ms * 100:.2f}%"] + ) + print( + tabulate( + rows, + headers=[ + "Kernel", + f"Self {device_name.upper()} TIME (ms)", + "Count", + "Percent", + ], + ) + ) + return total_time + + def report() -> None: + category_list = [ + "triton_pointwise", + "triton_reduction", + "triton_persistent_reduction", + "triton_unknown", + "unknown", + ] + if not OrderedSet(all_events.keys()).issubset(OrderedSet(category_list)): + raise AssertionError(f"{list(all_events.keys())}") + + per_category_wall_time = {} + total_device_ms = 0.0 + for category in category_list: + if category in all_events: + _time = report_category(category, all_events[category]) + per_category_wall_time[category] = _time + total_device_ms += _time + + device_busy_percent = f"{total_device_ms / wall_time_ms * 100:.2f}%" + if device_name: + print( + f"\nPercent of time when {device_name.upper()} is busy: {device_busy_percent}" + ) + else: + print("No device detected") + + print(f"Total wall time {wall_time_ms:.3f} ms") + + # output such a line so we can gather such line from all compiled modules from all + # benchmarks and tabulate it! + # Columns: benchmark_name, pointwise_percent, reduction_percent, persistent_reduction_percent, + # unknown_category_percent, device_busy_percent, wall_time_ms + tabulate_line = f"Output for tabulate: {benchmark_name}" + for category in category_list: + percent = ( + f"{per_category_wall_time.get(category, 0.0) / wall_time_ms * 100:.2f}%" + ) + tabulate_line += f", {percent}" + tabulate_line += f", {device_busy_percent}, {wall_time_ms:.3f}ms" + + print(tabulate_line) + + report() + + +PROFILE_DIR = tempfile.gettempdir() +PROFILE_PATH = f"{PROFILE_DIR}/compiled_module_profile.json" + + +def perf_profile( + wall_time_ms: float, + times: int, + repeat: int, + benchmark_name: str, + benchmark_compiled_module_fn: BenchmarkCallableType, +) -> None: + with torch.profiler.profile(record_shapes=True) as p: + benchmark_compiled_module_fn(times=times, repeat=repeat) + + path = PROFILE_PATH + p.export_chrome_trace(path) + print(f"Profiling result for a compiled module of benchmark {benchmark_name}:") + print(f"Chrome trace for the profile is written to {path}") + event_list = p.key_averages(group_by_input_shape=True) + print(event_list.table(sort_by="self_device_time_total", row_limit=10)) + parse_profile_event_list( + benchmark_name, event_list, wall_time_ms, times * repeat, p.use_device or "" + ) + + +def ncu_analyzer( + benchmark_name: str, + benchmark_compiled_module_fn: BenchmarkCallableType, + args: argparse.Namespace, +) -> None: + import inspect + import os + import subprocess + + kernel_regex = args.ncu_kernel_regex + metrics = args.ncu_metrics + + module_file = inspect.getfile(benchmark_compiled_module_fn) + module_dir = os.path.dirname(module_file) + module_name = os.path.splitext(os.path.basename(module_file))[0] + + ncu_dir = tempfile.gettempdir() + timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + ncu_output = os.path.join(ncu_dir, f"ncu_output_{timestamp}.ncu-rep") + python_cmd = ( + f"""import sys; sys.path.insert(0, '{module_dir}'); """ + f"""from {module_name} import benchmark_compiled_module; """ + """benchmark_compiled_module(times=1, repeat=1)""" + ) + + ncu_cmd = [ + "ncu", + "--target-processes", + "all", + "--replay-mode", + "kernel", + "--kernel-name-base", + "function", + "--print-units", + "base", + "--import-source", + "yes", + "--force-overwrite", + "--export", + ncu_output, + ] + + if kernel_regex: + ncu_cmd.extend(["--kernel-name", f"regex:{kernel_regex}"]) + + if metrics: + ncu_cmd.extend(["--metrics", metrics]) + else: + ncu_cmd.extend(["--set", "full"]) + + ncu_cmd.extend( + [ + "python", + "-c", + python_cmd, + ] + ) + + try: + subprocess.run(ncu_cmd, check=True) + print(f"\nNCU profiling results for benchmark {benchmark_name}:") + print(f"NCU report has been written to {ncu_output}") + + except subprocess.CalledProcessError as e: + print(f"NCU profiling failed with error: {e}") + return + + +def collect_memory_snapshot( + benchmark_compiled_module_fn: BenchmarkCallableType, +) -> None: + if not torch.cuda.is_available(): + raise AssertionError("CUDA is not available") + + torch.cuda.memory._record_memory_history(max_entries=100000) + benchmark_compiled_module_fn(times=10, repeat=1) # run 10 times + snapshot_path = f"{tempfile.gettempdir()}/memory_snapshot.pickle" + torch.cuda.memory._dump_snapshot(snapshot_path) + torch.cuda.memory._record_memory_history(enabled=None) + print(f"The collect memory snapshot has been written to {snapshot_path}") + + +# With AOTAutograd cache, we directly call the compiled module. So prevent +# Dynamo from reentering +@torch.compiler.disable # type: ignore[misc] +def compiled_module_main( + benchmark_name: str, benchmark_compiled_module_fn: BenchmarkCallableType +) -> None: + """ + This is the function called in __main__ block of a compiled module. + """ + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--benchmark-kernels", + "-k", + action="store_true", + help="Whether to benchmark each individual kernels", + ) + parser.add_argument( + "--benchmark-all-configs", + "-c", + action="store_true", + help="Whether to benchmark each individual config for a kernel", + ) + parser.add_argument( + "--profile", + "-p", + action="store_true", + help="Whether to profile the compiled module", + ) + parser.add_argument( + "--cuda-memory-snapshot", + action="store_true", + help=""" + Whether to collect CUDA memory snapshot. Refer to + "https://pytorch.org/blog/understanding-gpu-memory-1/ + for details about how to visualize the collected snapshot + """, + ) + parser.add_argument( + "--ncu", + action="store_true", + help="Whether to run ncu analysis", + ) + parser.add_argument( + "--ncu-kernel-regex", + type=str, + default=None, + help=( + "Filter kernels profiled by NCU using a regex (e.g., '^triton_.*'). " + "Maps to '--kernel-name regex:'. " + "If None, NCU will profile all kernels." + ), + ) + parser.add_argument( + "--ncu-metrics", + type=str, + default=None, + help=( + "Comma-separated list of NCU metrics to collect (e.g., 'dram__bytes.sum.per_second'). " + "If None, NCU will use '--set full'." + ), + ) + parser.add_argument( + "--times", + type=int, + default=10, + help="Number of times to run each benchmark iteration", + ) + parser.add_argument( + "--repeat", + type=int, + default=10, + help="Number of repetitions of each benchmark run", + ) + + args = parser.parse_args() + + if args.benchmark_kernels: + benchmark_all_kernels(benchmark_name, args.benchmark_all_configs) + else: + times = args.times + repeat = args.repeat + + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + wall_time_ms = benchmark_compiled_module_fn(times=times, repeat=repeat) * 1000 + + if torch.cuda.is_available(): + peak_mem = torch.cuda.max_memory_allocated() + print(f"Peak GPU memory usage {peak_mem / 1e6:.3f} MB") + + if torch.cuda.is_available() and args.cuda_memory_snapshot: + collect_memory_snapshot(benchmark_compiled_module_fn) + + if args.profile: + perf_profile( + wall_time_ms, + times, + repeat, + benchmark_name, + benchmark_compiled_module_fn, + ) + if args.ncu: + ncu_analyzer( + benchmark_name, + benchmark_compiled_module_fn, + args=args, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_jit_internal.py b/.venv/lib/python3.12/site-packages/torch/_jit_internal.py new file mode 100644 index 0000000000000000000000000000000000000000..ac9699fb2ca42e660d58ebc67674eae3c3a0fce5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_jit_internal.py @@ -0,0 +1,1592 @@ +# mypy: allow-untyped-defs +""" +The weak_script annotation needs to be here instead of inside torch/jit/ so it +can be used in other places in torch/ (namely torch.nn) without running into +circular dependency problems +""" + +import ast +import builtins +import collections +import contextlib +import enum +import functools +import inspect +import io +import pickle +import sys +import textwrap +import threading +import types +import typing +import warnings +import weakref +from typing import ( # noqa: UP035, F401 # (Dict, List, Tuple) imported by torch.jit.annotations + Any, + Callable, + Dict, + Final, + ForwardRef, + get_args, + get_origin, + List, + Optional, + Protocol, + Tuple, + TypeVar, + Union, +) +from typing_extensions import ParamSpec + +import torch + +# This is needed. `torch._jit_internal` is imported before `torch.distributed.__init__`. +# Explicitly ask to import `torch.distributed.__init__` first. +# Otherwise, "AttributeError: module 'torch' has no attribute 'distributed'" is raised. +import torch.distributed.rpc +import torch.package._mangling as package_mangling +from torch._awaits import _Await +from torch._C import _Await as CAwait, Future as CFuture +from torch._sources import fake_range, get_source_lines_and_file, parse_def +from torch.futures import Future + + +class HasGetattr(Protocol): + def __getattr__(self, key: str) -> Any: ... + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +BuiltinUnionType: type | tuple[type, ...] = types.UnionType + +LockType: type +try: + import _thread + + LockType = _thread.LockType +except ImportError: + import _dummy_thread # type: ignore[import-not-found] + + LockType = _dummy_thread.LockType + +# Wrapper functions that can call either of 2 functions depending on a boolean +# argument +boolean_dispatched: "weakref.WeakKeyDictionary[Callable, dict[str, Callable]]" = ( + weakref.WeakKeyDictionary() +) # noqa: T484 + + +FAKE_FILENAME_PREFIX = "__torch_jit_dataclass" + + +def is_final(ann) -> bool: + return ( + hasattr(ann, "__module__") + and ann.__module__ in {"typing", "typing_extensions"} + and (get_origin(ann) is Final or isinstance(ann, type(Final))) + ) + + +# allows BroadcastingList instance to be subscriptable +class BroadcastingListCls: + def __getitem__(self, types): + return + + +# mypy doesn't support parameters on types, so we have to explicitly type each +# list size +BroadcastingList1 = BroadcastingListCls() +for i in range(2, 7): + globals()[f"BroadcastingList{i}"] = BroadcastingList1 + + +def is_scripting() -> bool: + r""" + Function that returns True when in compilation and False otherwise. This + is useful especially with the @unused decorator to leave code in your + model that is not yet TorchScript compatible. + .. testcode:: + + import torch + + @torch.jit.unused + def unsupported_linear_op(x): + return x + + def linear(x): + if torch.jit.is_scripting(): + return torch.linear(x) + else: + return unsupported_linear_op(x) + """ + return False + + +# Retrieves a fully-qualified name (module hierarchy + classname) for a given obj. +def _qualified_name(obj, mangle_name=True) -> str: + # This special case allows us to override the qualified name on a type. + # It's currently used in conjunction with tracing, where we create a + # fake module to filter only supported attributes. However, since this + # new type is defined as a local class, we need a mechanism to override + # its qualname so it appears correctly in the TorchScript system. This, + # we set '_jit_override_qualname' with the original traced module's + # qualified name, which is picked up here + if hasattr(obj, "_jit_override_qualname"): + return obj._jit_override_qualname + # short-circuit in cases where the object already has a known qualified name + if isinstance(obj, torch._C.ScriptFunction): + return obj.qualified_name + + if getattr(obj, "__name__", None): + name = obj.__name__ + # Enum classes do not have `__name__` attr, instead they have `name`. + elif isinstance(obj, enum.Enum): + name = obj.name + else: + raise RuntimeError("Could not get name of python class object") + + if name == "": + name = "_lambda" # make name a valid identifier + + module_name = obj.__module__ + + # If the module is actually a torchbind module, then we should short circuit + if module_name == "torch._classes": + return obj.qualified_name + + # The Python docs are very clear that `__module__` can be None, but I can't + # figure out when it actually would be. + if module_name is None: + raise RuntimeError( + f"Could not get qualified name for class '{name}': " + "__module__ can't be None." + ) + + # if getattr(sys.modules[module_name], name) is not obj: + # raise RuntimeError(f"Could not get qualified name for class '{name}': " + # f"the attr {name} on module {module_name} is not the class") + + # torch.package and TorchScript have separate mangling schemes to avoid + # name collisions from multiple packages. To avoid them interfering with + # each other, normalize the package managing here. + if package_mangling.is_mangled(module_name): + module_name = module_name.replace("<", "_") + module_name = module_name.replace(">", "_") + + # The PythonExceptionValue C++ class in torch/csrc/jit/python/python_sugared_value.h + # does not need mangle the python class name. + if mangle_name: + # __main__ is a builtin module, so rewrite it to "__torch__". + if module_name == "__main__": + module_name = "__torch__" + else: + # Everything else gets a "__torch__" prefix to avoid name collisions + # with the names of user values. + module_name = "__torch__." + module_name + + if "." in name: + raise RuntimeError( + f"Could not get qualified name for class '{name}': " + f"'{name}' is not a valid identifier" + ) + + return module_name + "." + name + + +class SourceLoader: + def __init__(self): + self.content = {} + + def cache(self, fn, source): + self.content[fn] = source + + def get_source(self, fn): + return self.content.get(fn) + + +loader = SourceLoader() + + +def createResolutionCallbackFromEnv(lookup_base: HasGetattr) -> Callable[[str], Any]: + """ + Creates a resolution callback that will look up qualified names in an + environment, starting with `lookup_base` for the base of any qualified + names, then proceeding down the lookup chain with the resolved object. + + You should not use this directly, it should only be used from the other + createResolutionCallbackFrom* functions. + """ + + def lookupInModule(qualified_name: str, module: Any) -> Any: + if "." in qualified_name: + base, remaining_pieces = qualified_name.split(".", maxsplit=1) + module_value = getattr(module, base) + return lookupInModule(remaining_pieces, module_value) + else: + return getattr(module, qualified_name) + + def parseNestedExpr(expr: str, module: Any) -> tuple[Any, int]: + i = 0 + while i < len(expr) and expr[i] not in (",", "[", "]"): + i += 1 + + # Special case logic for the empty Tuple as a subscript (used + # in the type annotation `Tuple[()]`) + if expr[:i] == "()": + return (), i + + base = lookupInModule(expr[:i].strip(), module) + if base is None: + raise AssertionError(f"Unresolvable type {expr[:i]}") + if i == len(expr) or expr[i] != "[": + return base, i + + if expr[i] != "[": + raise AssertionError(f"expected '[' at position {i}, got {expr[i]!r}") + parts = [] + while expr[i] != "]": + part_len = 0 + i += 1 + part, part_len = parseNestedExpr(expr[i:], module) + parts.append(part) + i += part_len + if len(parts) > 1: + return base[tuple(parts)], i + 1 + else: + return base[parts[0]], i + 1 + + def parseExpr(expr: str, module: Any) -> Any: + try: + value, len_parsed = parseNestedExpr(expr, module) + if len_parsed != len(expr): + raise AssertionError( + "whole expression was not parsed, falling back to c++ parser" + ) + return value + except Exception: + """ + The python resolver fails in several cases in known unit tests, and is intended + to fall back gracefully to the c++ resolver in general. For example, python 2 style + annotations which are frequent in our unit tests often fail with types e.g. int not + resolvable from the calling frame. + """ + return None + + return lambda expr: parseExpr(expr, lookup_base) + + +def createResolutionCallbackFromFrame(frames_up: int = 0) -> Callable[[str], Any]: + """ + Creates a function which, given a string variable name, + returns the value of the variable in the scope of the caller of + the function which called createResolutionCallbackFromFrame (by default). + + This is used to enable access in-scope Python variables inside + TorchScript fragments. + + frames_up is number of additional frames to go up on the stack. + The default value is 0, which correspond to the frame of the caller + of createResolutionCallbackFromFrame. Also for example, if frames_up is set + to 1, then the frame of the caller's caller of createResolutionCallbackFromFrame + will be taken. + + For example, the following program prints 2:: + + def bar(): + cb = createResolutionCallbackFromFrame(1) + print(cb("foo")) + + + def baz(): + foo = 2 + bar() + + + baz() + """ + frame = inspect.currentframe() + i = 0 + while i < frames_up + 1: + if frame is None: + raise AssertionError(f"frame is None at iteration {i}") + frame = frame.f_back + i += 1 + + if frame is None: + raise AssertionError("frame is None after traversing frames_up") + f_locals = frame.f_locals + f_globals = frame.f_globals + + class env: + def __getattr__(self, key: str) -> Any: + if key in f_locals: + return f_locals[key] + elif key in f_globals: + return f_globals[key] + elif key in dir(builtins): + return getattr(builtins, key) + + return createResolutionCallbackFromEnv(env()) + + +def get_closure(fn): + """ + Get a dictionary of closed over variables from a function + """ + captures = {} + captures.update(fn.__globals__) + + for index, captured_name in enumerate(fn.__code__.co_freevars): + captures[captured_name] = fn.__closure__[index].cell_contents + + return captures + + +# [local resolution in python] +# Depending on where a variable is defined, and where it is used, we may +# or may not be able to recover its value when recursively compiling a +# script function. Remember in the general case, a module or function is +# first defined and then later scripted. This means we do not have a +# chance to capture the active frames when the function is defined. Hence any +# name resolution has to happen later on the created closure. The way +# python captures type annotations restricts what we can recover. The +# follow example illustrates the different cases: +# +# class MyGlobalClass: +# ... +# def my_local_scope(): +# @torch.jit.script +# class MyClass: +# ... +# @torch.jit.script +# class MyClassUsedAsVar: +# ... +# def eg(x: MyClass, y: MyGlobalClass): +# a_local_capture : Foo +# return MyClassUsedAsVar(x) +# +# MyGlobalClass is defined in the __globals__ dictionary of function +# 'eg', so it is always recoverable. my_local_scope introduces a new local +# variable scope in the function. Classes defined here are only visible as +# local variables. For the case of MyClassUsedAsVar, it is captured +# because it is used as a variable inside the body of the function, and we +# can resolve it using the captures returned from `get_closure`. However, +# the type annotations are not captured by the closure. In Python +# 3.0--3.9, the _value_ of MyClass and MyGlobalClass will be available as +# annotations on `eg``, but starting in Python 4.0, they will represented as +# strings and no longer present. Furthermore, since the body of `eg` does +# not reference those names, they do not appear in the list of closed over +# variables. We anticipate +# that most users will not run into this issue because their modules and +# functions will be defined at a global scope like MyGlobalClass. In cases +# where they are not, it is possible to work around issues by declaring the +# values global in the function. +# In Python 3.9 declaring class as global will make it invisible to +# `inspect.getsource`, see https://bugs.python.org/issue42666 . +# This could be worked around by manually adding it to `global()` dictionary. + + +def createResolutionCallbackFromClosure(fn) -> Callable[[str], Any]: + """ + Create a resolutionCallback by introspecting the function instead of + looking up the stack for the enclosing scope + """ + closure = get_closure(fn) + + class closure_lookup: + # This is a class since `closure` is a dict and it's easier in + # `env_helper` if everything just works with `getattr` calls + def __getattr__(self, key: str) -> Any: + if key in closure: + return closure[key] + elif hasattr(typing, key): + return getattr(typing, key) + elif hasattr(builtins, key): + return getattr(builtins, key) + return None + + return createResolutionCallbackFromEnv(closure_lookup()) + + +@functools.cache +def can_compile_class(cls) -> bool: + # If any of the functions on a type don't have a code object, this type can't + # be compiled and is probably a builtin / bound from C + if is_ignored_fn(cls): + return False + + # Ignore the following list of built-in classes. + ignored_builtin_classes = (torch.nn.Module, tuple, list, Exception) + if issubclass(cls, ignored_builtin_classes): + return False + + names = cls.__dict__ + fns = [ + getattr(cls, name) + for name in names + if inspect.isroutine(getattr(cls, name, None)) + ] + has_code = [hasattr(fn, "__code__") for fn in fns] + return all(has_code) + + +def get_callable_argument_names(fn) -> list[str]: + """ + Gets names of all POSITIONAL_OR_KEYWORD arguments for callable `fn`. + Returns an empty list when other types of arguments are present. + + This is used by `torch.jit.trace` to assign meaningful argument names to + traced functions and modules. + + Args: + fn: A callable. + Returns: + Argument names: List[str] + """ + # inspect.signature may fail, give up in that case. + try: + callable_signature = inspect.signature(fn) + except Exception: + return [] + + argument_names = [] + for name, param in callable_signature.parameters.items(): + # All four other types of arguments do not map to individual values + # with a keyword as name. + if param.kind != param.POSITIONAL_OR_KEYWORD: + continue + + argument_names.append(name) + + return argument_names + + +def get_annotation_str(annotation): + """ + Convert an AST node containing a type annotation to the string present in the source + that represents the same annotation. + """ + if isinstance(annotation, ast.Name): + return annotation.id + elif isinstance(annotation, ast.Attribute): + return ".".join([get_annotation_str(annotation.value), annotation.attr]) + elif isinstance(annotation, ast.Subscript): + # In Python3.9+ subscript indices are not wrapped in ast.Index + subscript_slice = annotation.slice + return f"{get_annotation_str(annotation.value)}[{get_annotation_str(subscript_slice)}]" + elif isinstance(annotation, ast.Tuple): + return ",".join([get_annotation_str(elt) for elt in annotation.elts]) + elif isinstance(annotation, ast.Constant): + return f"{annotation.value}" + + # If an AST node is not handled here, it's probably handled in ScriptTypeParser. + return None + + +def get_type_hint_captures(fn): + """ + Get a dictionary containing type resolution mappings necessary to resolve types + for the literal annotations on 'fn'. These are not considered to be closed-over by fn + and must be obtained separately (e.g. using this function). + + Args: + fn: A callable. + Returns: + A Dict[str, Any] containing a mapping from the literal annotations used on + fn to the Python objects they refer to. + """ + # First, try to get the source of the function. We'll need to parse it to find the actual string names + # that were used to annotate the types, since inspect.signature() will only return the class object that + # the annotation refers to, not the string name. If we can't get the source, simply return an empty dict. + # This may happen in cases where the function is synthesized dynamically at runtime. + src = loader.get_source(fn) + if src is None: + try: + src = inspect.getsource(fn) + except OSError as e: + raise OSError( + f"Failed to get source for {fn} using inspect.getsource" + ) from e + + # Gather a dictionary of parameter name -> type, skipping any parameters whose annotated + # types are strings. These are only understood by TorchScript in the context of a type annotation + # that refers to a class in its own definition, but trying to include a mapping for this in the result + # function would cause infinite recursion because the class is currently being compiled. + # In addition, there is logic in ScriptTypeParser to handle this. + signature = inspect.signature(fn) + name_to_type = { + name: parameter.annotation + for name, parameter in signature.parameters.items() + if parameter.annotation is not inspect.Parameter.empty + and not isinstance(parameter.annotation, str) + } + + # Then, get the literal type annotations from the function declaration + # by source inspection. This accounts for the case in which aliases are used + # to annotate the arguments (e.g device_t = torch.device, and then d: device_t). + # frontend.py cannot be used here because it includes _jit_internal, so use ast instead. + a = ast.parse(textwrap.dedent(src)) + if len(a.body) != 1 or not isinstance(a.body[0], ast.FunctionDef): + raise RuntimeError(f"Expected {fn} to be a function") + f = a.body[0] + + # Prepare a dictionary of source annotation -> type, which will be the final result of this function, + # by using the parsed AST (f) to reconstruct source annotations as strings for each parameter and mapping + # them to the type object corresponding to the annotation via name_to_type using the parameter name. + annotation_to_type = {} + + for arg in f.args.args: + # Get the source type annotation string for this argument if possible. + arg_annotation_str = ( + get_annotation_str(arg.annotation) if arg.annotation else None + ) + + # If the argument has no annotation or get_annotation_str cannot convert it to a string, + # arg_annotation_str will be None. Skip this arg; ScriptTypeParser will probably handle + # this in the latter case. + if arg_annotation_str is None: + continue + + # Insert {arg_annotation_str: type} into annotation_to_type if possible. One reason arg_name may not + # be present in name_to_type is that the annotation itself is a string and not a type object + # (common for self-referential annotations in classes). Once again, let ScriptTypeParser handle this. + arg_name = arg.arg + if arg_name in name_to_type: + annotation_to_type[arg_annotation_str] = name_to_type[arg_name] + + # If there is a valid return annotation, include it in annotation_to_type. As with argument annotations, + # the literal annotation has to be convertible to a string by get_annotation_str, and the actual type + # of the annotation cannot be a string. + literal_return_annotation = get_annotation_str(f.returns) + valid_literal_annotation = literal_return_annotation is not None + return_annotation = signature.return_annotation + valid_return_annotation_type = ( + return_annotation is not inspect.Parameter.empty + and not isinstance(return_annotation, str) + ) + if valid_literal_annotation and valid_return_annotation_type: + annotation_to_type[literal_return_annotation] = return_annotation + + return annotation_to_type + + +def createResolutionCallbackForClassMethods(cls: type) -> Callable[[str], Any]: + """ + This looks at all the methods defined in a class and pulls their closed-over + variables into a dictionary and uses that to resolve variables. + """ + # cls is a type here, so `ismethod` is false since the methods on the type + # aren't bound to anything, so Python treats them as regular functions + fns = [ + getattr(cls, name) + for name in cls.__dict__ + if inspect.isroutine(getattr(cls, name)) + ] + # Skip built-ins, as they do not have global scope nor type hints + # Needed to support `enum.Enum` derived classes in Python-3.11 + # That adds `_new_member_` property which is an alias to `__new__` + # Skip __annotate__ added by PEP 649 for deferred annotation evaluation + fns = [ + fn + for fn in fns + if not inspect.isbuiltin(fn) + and hasattr(fn, "__globals__") + and fn.__name__ != "__annotate__" + ] + captures = {} + + for fn in fns: + captures.update(get_closure(fn)) + captures.update(get_type_hint_captures(fn)) + + def lookup_in_class(key: str) -> Any: + if key in captures: + return captures[key] + else: + return getattr(builtins, key, None) + + return lookup_in_class + + +def boolean_dispatch( + arg_name, + arg_index, + default, + if_true, + if_false, + module_name, + func_name, +): + """ + Dispatches to either of 2 script functions based on a boolean argument. + In TorchScript, the boolean argument must be constant so that the correct + function to use can be determined at compile time. + """ + + def fn(*args, **kwargs): + dispatch_flag = default + if arg_name in kwargs: + dispatch_flag = kwargs[arg_name] + elif arg_index < len(args): + dispatch_flag = args[arg_index] + + if dispatch_flag: + return if_true(*args, **kwargs) + else: + return if_false(*args, **kwargs) + + if if_true.__doc__ is None and if_false.__doc__ is not None: + doc = if_false.__doc__ + if_true.__doc__ = doc + elif if_false.__doc__ is None and if_true.__doc__ is not None: + doc = if_true.__doc__ + if_false.__doc__ = doc + elif if_false.__doc__ is None and if_true.__doc__ is None: + # neither function has a docstring + doc = None + else: + raise RuntimeError("only one function can have a docstring") + fn.__doc__ = doc + + if module_name is not None: + fn.__module__ = module_name + if func_name is not None: + fn.__name__ = func_name + + boolean_dispatched[fn] = { + "if_true": if_true, + "if_false": if_false, + "index": arg_index, + "default": default, + "arg_name": arg_name, + } + return fn + + +class FunctionModifiers: + """ + Used to denote the behavior of a function in TorchScript. See export() and + ignore() for details. + """ + + UNUSED = "unused (ignored and replaced with raising of an exception)" + IGNORE = "ignore (leave as a call to Python, cannot be torch.jit.save'd)" + EXPORT = "export (compile this function even if nothing calls it)" + DEFAULT = "default (compile if called from an exported function / forward)" + COPY_TO_SCRIPT_WRAPPER = ( + "if this method is not scripted, copy the python method onto the scripted model" + ) + _DROP = "_drop (function is fully ignored, declaration can be unscriptable)" + + +def export(fn: Callable[_P, _R]) -> Callable[_P, _R]: + """ + This decorator indicates that a method on an ``nn.Module`` is used as an entry point into a + :class:`ScriptModule` and should be compiled. + + .. deprecated:: 2.5 + Please use :func:`torch.compile` instead. + + ``forward`` implicitly is assumed to be an entry point, so it does not need this decorator. + Functions and methods called from ``forward`` are compiled as they are seen + by the compiler, so they do not need this decorator either. + + Example (using ``@torch.jit.export`` on a method): + + .. testcode:: + + import torch + import torch.nn as nn + + class MyModule(nn.Module): + def implicitly_compiled_method(self, x): + return x + 99 + + # `forward` is implicitly decorated with `@torch.jit.export`, + # so adding it here would have no effect + def forward(self, x): + return x + 10 + + @torch.jit.export + def another_forward(self, x): + # When the compiler sees this call, it will compile + # `implicitly_compiled_method` + return self.implicitly_compiled_method(x) + + def unused_method(self, x): + return x - 20 + + # `m` will contain compiled methods: + # `forward` + # `another_forward` + # `implicitly_compiled_method` + # `unused_method` will not be compiled since it was not called from + # any compiled methods and wasn't decorated with `@torch.jit.export` + m = torch.jit.script(MyModule()) + """ + fn._torchscript_modifier = FunctionModifiers.EXPORT # type:ignore[attr-defined] + return fn + + +def unused(fn: Callable[_P, _R]) -> Callable[_P, _R]: + """ + This decorator indicates to the compiler that a function or method should + be ignored and replaced with the raising of an exception. This allows you + to leave code in your model that is not yet TorchScript compatible and still + export your model. + + Example (using ``@torch.jit.unused`` on a method):: + + import torch + import torch.nn as nn + + + class MyModule(nn.Module): + def __init__(self, use_memory_efficient): + super().__init__() + self.use_memory_efficient = use_memory_efficient + + @torch.jit.unused + def memory_efficient(self, x): + import pdb + + pdb.set_trace() + return x + 10 + + def forward(self, x): + # Use not-yet-scriptable memory efficient mode + if self.use_memory_efficient: + return self.memory_efficient(x) + else: + return x + 10 + + + m = torch.jit.script(MyModule(use_memory_efficient=False)) + m.save("m.pt") + + m = torch.jit.script(MyModule(use_memory_efficient=True)) + # exception raised + m(torch.rand(100)) + """ + if isinstance(fn, property): + prop = fn + setattr( # noqa: B010 + prop.fget, "_torchscript_modifier", FunctionModifiers.UNUSED + ) + + if prop.fset: + setattr( # noqa: B010 + prop.fset, "_torchscript_modifier", FunctionModifiers.UNUSED + ) + + return prop + + fn._torchscript_modifier = FunctionModifiers.UNUSED # type: ignore[attr-defined] + return fn + + +# No op context manager from python side +class _IgnoreContextManager(contextlib.AbstractContextManager): + def __init__(self, **kwargs): + pass + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + pass + + +def ignore(drop=False, **kwargs): + """ + This decorator indicates to the compiler that a function or method should + be ignored and left as a Python function. This allows you to leave code in + your model that is not yet TorchScript compatible. If called from TorchScript, + ignored functions will dispatch the call to the Python interpreter. Models with ignored + functions cannot be exported; use :func:`@torch.jit.unused ` instead. + + .. deprecated:: 2.5 + Please use :func:`torch.compile` instead. + + Example (using ``@torch.jit.ignore`` on a method):: + + import torch + import torch.nn as nn + + + class MyModule(nn.Module): + @torch.jit.ignore + def debugger(self, x): + import pdb + + pdb.set_trace() + + def forward(self, x): + x += 10 + # The compiler would normally try to compile `debugger`, + # but since it is `@ignore`d, it will be left as a call + # to Python + self.debugger(x) + return x + + + m = torch.jit.script(MyModule()) + + # Error! The call `debugger` cannot be saved since it calls into Python + m.save("m.pt") + + Example (using ``@torch.jit.ignore(drop=True)`` on a method): + + .. testcode:: + + import torch + import torch.nn as nn + + class MyModule(nn.Module): + @torch.jit.ignore(drop=True) + def training_method(self, x): + import pdb + pdb.set_trace() + + def forward(self, x): + if self.training: + self.training_method(x) + return x + + m = torch.jit.script(MyModule()) + + # This is OK since `training_method` is not saved, the call is replaced + # with a `raise`. + m.save("m.pt") + + .. testcleanup:: + + import os + os.remove('m.pt') + """ + + if callable(drop): + # used without any args, so drop is actually a function + # @torch.jit.ignore + # def fn(...): + fn = drop + # pyrefly: ignore [missing-attribute] + fn._torchscript_modifier = FunctionModifiers.IGNORE + return fn + + if not isinstance(drop, bool): + raise RuntimeError( + f"Argument to @torch.jit.ignore must be a bool or a function but got {drop}" + ) + + # for backwards compat + drop_on_export = kwargs.pop("drop_on_export", None) + if drop_on_export: + warnings.warn( + "ignore(drop_on_export=True) has been deprecated. TorchScript will now drop the function " + "call on compilation. Use torch.jit.unused now. {}", + stacklevel=2, + category=FutureWarning, + ) + + drop = drop_on_export + elif drop: + warnings.warn( + "ignore(True) has been deprecated. TorchScript will now drop the function " + "call on compilation. Use torch.jit.unused now. {}", + stacklevel=2, + category=FutureWarning, + ) + + def decorator(fn): + if drop: + fn._torchscript_modifier = FunctionModifiers.UNUSED + else: + fn._torchscript_modifier = FunctionModifiers.IGNORE + return fn + + return decorator + + +def _drop(fn: Callable[_P, _R]) -> Callable[_P, _R]: + fn._torchscript_modifier = FunctionModifiers._DROP # type: ignore[attr-defined] + return fn + + +def _copy_to_script_wrapper(fn: Callable[_P, _R]) -> Callable[_P, _R]: + fn._torchscript_modifier = FunctionModifiers.COPY_TO_SCRIPT_WRAPPER # type: ignore[attr-defined] + return fn + + +def module_has_exports(mod): + for name in dir(mod): + if hasattr(mod, name): + item = getattr(mod, name) + if callable(item): + if get_torchscript_modifier(item) is FunctionModifiers.EXPORT: + return True + return False + + +# WARNING: should_drop is currently being used by our JIT code coverage plug-in to mark JIT'd code as covered. If you +# rename this function, please update references in tools/coverage_plugins_package/src/coverage_plugins/jit_plugin.py to +# allow JIT'd code to still be covered. +def should_drop(fn) -> bool: + attr = get_torchscript_modifier(fn) + if attr is None: + return False + return attr is FunctionModifiers.UNUSED or attr is FunctionModifiers._DROP + + +def is_ignored_fn(fn) -> bool: + mod = get_torchscript_modifier(fn) + return ( + mod is FunctionModifiers.UNUSED + or mod is FunctionModifiers.IGNORE + or mod is FunctionModifiers._DROP + ) + + +def _is_drop_fn(fn) -> bool: + mod = get_torchscript_modifier(fn) + return mod is FunctionModifiers._DROP + + +def is_static_fn(cls, fn) -> bool: + return isinstance(inspect.getattr_static(cls, fn, default=None), staticmethod) + + +def get_static_fn(cls, fn): + return inspect.getattr_static(cls, fn).__func__ + + +def get_torchscript_modifier(fn): + if not callable(fn): + return None + if hasattr(fn, "__func__"): + fn = fn.__func__ + return getattr(fn, "_torchscript_modifier", FunctionModifiers.DEFAULT) + + +def copy_torchscript_modifier(orig, new) -> None: + attr = get_torchscript_modifier(orig) + if attr is None: + return + new._torchscript_modifier = attr + + +# overloading registration +# overloads get registered in this file, and compiled in torch/jit/__init__.py +# so that they can be imported in nn/functional.py without an import cycle + +# qualified_name => list[overload_functions] +_overloaded_fns: dict[str, list[Callable]] = {} # noqa: T484 + + +_OVERLOAD_EXAMPLE = """ +Example usage of overload function: +@torch.jit._overload +def my_function(x: type0) -> type0: # decl 1 + pass + +@torch.jit._overload +def my_function(x: type1) -> type1: # decl 2 + pass + +def my_function(x): # implementation + if isinstance(x, type0): + return x + elif isinstance(x, type1): + return x +""" + + +def get_overload_no_implementation_error_message(kind, obj): + sourcelines, file_lineno, filename = get_source_lines_and_file(obj) + return ( + f'Implementation for the {kind} "{_qualified_name(obj)}" is missing. Please make ' + f"sure a definition is provided and defined after all overload declarations.\n" + f'File "{filename}", line {file_lineno}:\n' + + "".join(sourcelines) + + "\n" + + _OVERLOAD_EXAMPLE + ) + + +def _check_overload_body(func): + try: + parsed_def = parse_def(func) + except OSError: + # Parsing the function definition can raise an OSError if source is unavailable. + # Since this is just an initial check, just raise a warning if this is the case. + warnings.warn( + f"Unable to retrieve source for @torch.jit._overload function: {func}.", + stacklevel=2, + ) + return + + body = parsed_def.ast.body[0].body + + def is_pass(x): + return isinstance(x, ast.Pass) + + def is_ellipsis(x): + return ( + isinstance(x, ast.Expr) + and isinstance(x.value, ast.Constant) + and x.value.value is Ellipsis + ) + + if len(body) != 1 or not (is_pass(body[0]) or is_ellipsis(body[0])): + msg = ( + "Only `pass` statement or `...` can be the body of overload declaration:\n" + ) + msg += "\n".join(parsed_def.source.split("\n")[:3]) + msg += " <- Expecting `pass` or `...` here!\n" + _OVERLOAD_EXAMPLE + raise RuntimeError(msg) + + +def _overload(func: Callable[_P, _R]) -> Callable[_P, _R]: + _check_overload_body(func) + qual_name = _qualified_name(func) + global _overloaded_fns + fn_overload_list = _overloaded_fns.get(qual_name) + if fn_overload_list is None: + fn_overload_list = [] + _overloaded_fns[qual_name] = fn_overload_list + fn_overload_list.append(func) + return func + + +def _get_fn_overloads(qual_name): + return _overloaded_fns.get(qual_name) + + +def _clear_fn_overloads(qual_name) -> None: + del _overloaded_fns[qual_name] + + +def get_class_name_lineno(method) -> tuple[str, int]: + current_frame = inspect.currentframe() + + # one for the get_class_name call, one for _overload_method call + for i in range(2): + if current_frame is None: + raise AssertionError(f"current_frame is None at iteration {i}") + current_frame = current_frame.f_back + + if current_frame is None: + raise AssertionError("current_frame is None after traversing frames") + class_name = current_frame.f_code.co_name + line_no = current_frame.f_code.co_firstlineno + return class_name, line_no + + +# At the point the decorator is applied to class methods the method +# has no reference to its owning class. _qualified_name would not include +# the class it is defined in, so any methods with the same name in the same file +# would have the same _qualified_name, even if they were defined in different +# classes. This problem only exists in python 2. +# We get around this problem by looking at the stack frame and identifying +# the class name, and throwing an error whenever overloads are used +# when modules of the same name are in the same file + +# qualified_name => class name => list[overload_functions] +_overloaded_methods: dict[str, dict[str, list[Callable]]] = {} # noqa: T484 + + +# (qualified_name, class name) => class_fileno +_overloaded_method_class_fileno: dict[tuple[str, str], int] = {} + + +def _overload_method(func: Callable[_P, _R]) -> Callable[_P, _R]: + try: + _check_overload_body(func) + except IndentationError: + # CPython 3.13.8 has a bug (https://github.com/python/cpython/issues/139783) + # where inspect.getsourcelines() returns truncated source when a decorator + # is followed by a comment, causing ast.parse() to fail with IndentationError. + # Fixed in 3.13.9. Swallow the error on affected versions; re-raise otherwise. + if sys.version_info[:3] == (3, 13, 8): + import warnings + + warnings.warn( + "Skipping overload body check due to a known CPython 3.13.8 bug " + "(https://github.com/python/cpython/issues/139783). " + "Consider upgrading to Python 3.13.9+.", + stacklevel=2, + ) + else: + raise + qual_name = _qualified_name(func) + global _overloaded_methods + class_name_map = _overloaded_methods.get(qual_name) + if class_name_map is None: + class_name_map = {} + _overloaded_methods[qual_name] = class_name_map + + class_name, line_no = get_class_name_lineno(func) + method_overloads = class_name_map.get(class_name) + if method_overloads is None: + method_overloads = [] + class_name_map[class_name] = method_overloads + _overloaded_method_class_fileno[(qual_name, class_name)] = line_no + else: + existing_lineno = _overloaded_method_class_fileno[(qual_name, class_name)] + if existing_lineno != line_no: + raise RuntimeError( + "Cannot currently overload the same method name in two different" + " classes with the same name in the same module" + ) + + method_overloads.append(func) + return func + + +def _get_overloaded_methods(method, mod_class): + # TODO: __name__ not set for submodules in recursive script + if not hasattr(method, "__name__"): + return None + qual_name = _qualified_name(method) + class_name_map = _overloaded_methods.get(qual_name) + if class_name_map is None: + return None + overloads = class_name_map.get(mod_class.__name__, None) + if overloads is None: + return None + + method_line_no = get_source_lines_and_file(method)[1] + mod_class_fileno = get_source_lines_and_file(mod_class)[1] + mod_end_fileno = mod_class_fileno + len(get_source_lines_and_file(mod_class)[0]) + if not (method_line_no >= mod_class_fileno and method_line_no <= mod_end_fileno): + raise AssertionError( + "Overloads are not usable when a module is redeclared within the same file: " + + str(method) + ) + return overloads + + +def is_tuple(ann) -> bool: + # Check for typing.Tuple missing args (but `tuple` is fine) + if ann is typing.Tuple: # noqa: UP006 + raise_error_container_parameter_missing("Tuple") + + # For some reason Python 3.7 violates the Type[A, B].__origin__ == Type rule + if not hasattr(ann, "__module__"): + return False + + ann_origin = get_origin(ann) + return ann.__module__ in ("builtins", "typing") and ann_origin is tuple + + +def is_list(ann) -> bool: + # Check for typing.List missing args (but `list` is fine) + if ann is typing.List: # noqa: UP006 + raise_error_container_parameter_missing("List") + + if not hasattr(ann, "__module__"): + return False + + ann_origin = get_origin(ann) + return ann.__module__ in ("builtins", "typing") and ann_origin is list + + +def is_dict(ann) -> bool: + # Check for typing.Dict missing args (but `dict` is fine) + if ann is typing.Dict: # noqa: UP006 + raise_error_container_parameter_missing("Dict") + + if not hasattr(ann, "__module__"): + return False + + ann_origin = get_origin(ann) + return ann.__module__ in ("builtins", "typing") and ann_origin is dict + + +def is_union(ann): + if ann is Union: + raise_error_container_parameter_missing("Union") + + return isinstance(ann, BuiltinUnionType) or ( + hasattr(ann, "__module__") + and ann.__module__ == "typing" + and (get_origin(ann) is Union) + ) + + +def is_optional(ann): + if ann is Optional: + raise_error_container_parameter_missing("Optional") + + def is_optional_as_optional(ann): + return ( + hasattr(ann, "__module__") + and ann.__module__ == "typing" + and (get_origin(ann) is Optional) + ) + + def is_union_as_optional(ann): + ann_args = get_args(ann) + return len(ann_args) == 2 and (None in ann_args or type(None) in ann_args) + + return is_optional_as_optional(ann) or (is_union(ann) and is_union_as_optional(ann)) + + +def is_future(ann) -> bool: + if ann is Future: + raise RuntimeError( + "Attempted to use Future without a " + "contained type. Please add a contained type, e.g. " + "Future[int]" + ) + return get_origin(ann) is Future + + +def is_await(ann) -> bool: + if ann is _Await: + return True + return get_origin(ann) is _Await + + +if torch.distributed.rpc.is_available(): + from torch._C._distributed_rpc import PyRRef + from torch.distributed.rpc import RRef + + def is_rref(ann) -> bool: + if ann is RRef: + raise RuntimeError( + "Attempted to use RRef without a " + "contained type. Please add a contained type, e.g. " + "RRef[int]" + ) + return get_origin(ann) is RRef + + def is_rref_instance(obj) -> bool: + return isinstance(obj, PyRRef) + +else: + + def is_rref_instance(obj) -> bool: + # If the RPC module doesn't exist then RRefs don't exist either. + return False + + +def _try_get_dispatched_fn(fn): + if not callable(fn): + return None + return boolean_dispatched.get(fn) + + +def _get_named_tuple_properties( + obj, + loc: torch._C._jit_tree_views.SourceRange | None = None, + rcb=None, +): + if loc is None: + loc = fake_range() + + if not issubclass(obj, tuple) or not hasattr(obj, "_fields"): + raise AssertionError( + f"expected namedtuple (tuple subclass with _fields), got {obj}" + ) + if hasattr(obj, "_field_defaults"): + defaults = [ + obj._field_defaults[field] + for field in obj._fields + if field in obj._field_defaults + ] + else: + defaults = [] + + obj_annotations = inspect.get_annotations(obj) + if len(obj_annotations) == 0 and hasattr(obj, "__base__"): + obj_annotations = inspect.get_annotations( + # pyrefly: ignore [bad-argument-type] + obj.__base__ + ) + + annotations = [] + for field in obj._fields: + if field in obj_annotations: + field_type = obj_annotations[field] + # [Note: ForwardRef annotations in NamedTuple attributes] + # NamedTuple types are slightly different from normal types. + # + # Normally, annotations are evaluated like this (during jit.script): + # 1. Load strings of python code into c++ and parse. + # 2. Get annotations as strings + # 3. Use the PythonResolver's resolution callback (rcb) to convert + # the string into a python object + # 4. We call into annotations.py:ann_to_type to convert python obj + # from step 3 into a type that torchscript understands. + # + # NamedTuples are more complicated, because it has sub-types. + # Normally, once we have the NamedTuple type object from #3, + # we can just look at the annotation literal values and use + # ann_to_type directly on them. + # + # But sometimes, users will annotate with string literals, e.g. + # x: 'int' + # This also happens with PEP563 (from __forward__ import annotations) + # + # These annotations appear in the annotation dict as ForwardRef('int'). + # + # Then, we need to convert the string into a python object. This + # requires having local context for custom objects or imported types. + # rcb() is what gives us this. So, we plumb rcb through the stack so + # it can be used in this context for the if block below. + # + # FAQ: + # - Why do we need this special handling for NamedTuple but string + # annotations work fine for normal types? Normally, we parse the + # string directly and then call rcb() directly from C++. + # - Why not use ForwardRef._evaluate? For that, we need globals() + # and locals() for the local context where the NamedTuple was defined. + # rcb is what lets us look up into these. So, basically rcb does the + # hard work for us. + if isinstance(field_type, ForwardRef) and rcb is not None: + rcb_type = rcb(field_type.__forward_arg__) + # rcb returns None if it can't find anything. + if rcb_type is None: + raise ValueError( + f"Unknown type annotation: '{field_type}' in NamedTuple {obj.__name__}." + f" Likely due to partial support for ForwardRef parameters in NamedTuples, see #95858." + f" Issue occurred at {loc.highlight()}" + ) + field_type = rcb_type + the_type = torch.jit.annotations.ann_to_type(field_type, loc, rcb) + annotations.append(the_type) + else: + annotations.append(torch._C.TensorType.getInferred()) + return type(obj).__name__, obj._fields, annotations, defaults + + +def _create_named_tuple( + t, + unqual_name: str, + field_names: list[str], + defaults: tuple[Any, ...], +): + TupleType = collections.namedtuple(unqual_name, field_names, defaults=defaults) # type: ignore[call-arg, no-redef, misc] + return TupleType(*t) + + +@contextlib.contextmanager +def _disable_emit_hooks(): + hooks = torch._C._jit_get_emit_hooks() + torch._C._jit_set_emit_hooks(None, None) + try: + yield + finally: + torch._C._jit_set_emit_hooks(hooks[0], hooks[1]) + + +def _disable_emit_hooks_decorator(_DecoratorContextManager) -> None: + def __enter__(self) -> None: + self.hooks = torch._C._jit_get_emit_hooks() + torch._C._jit_set_emit_hooks(None, None) + + def __exit__(self, *args) -> None: + torch._C._jit_set_emit_hooks(self.hooks[0], self.hooks[1]) + + +def _is_exception(obj) -> bool: + if not inspect.isclass(obj): + return False + return issubclass(obj, Exception) + + +def raise_error_container_parameter_missing(target_type) -> None: + if target_type.endswith("ict"): + raise RuntimeError( + f"Attempted to use {target_type} without " + "contained types. Please add contained type, e.g. " + f"{target_type}[int, int]" + ) + raise RuntimeError( + f"Attempted to use {target_type} without a " + "contained type. Please add a contained type, e.g. " + f"{target_type}[int]" + ) + + +_RAW_TYPE_NAME_MAPPING = { + dict: "dict", + list: "list", + tuple: "tuple", + typing.Dict: "Dict", # noqa: UP006 + typing.List: "List", # noqa: UP006 + typing.Optional: "Optional", + typing.Tuple: "Tuple", # noqa: UP006 +} + + +def check_args_exist(target_type) -> None: + if name := _RAW_TYPE_NAME_MAPPING.get(target_type): + raise_error_container_parameter_missing(name) + + +def check_empty_containers(obj) -> None: + if obj == [] or obj == {} or obj == (): + warnings.warn( + "The inner type of a container is lost when " + "calling torch.jit.isinstance in eager mode. For " + "example, List[int] would become list and " + "therefore falsely return True for List[float] or" + " List[str].", + stacklevel=2, + ) + + +# supports List/Dict/Tuple and Optional types +# TODO support future +def container_checker(obj, target_type) -> bool: + origin_type = get_origin(target_type) + check_args_exist(target_type) + if origin_type is None: + return False + elif origin_type is list or origin_type is typing.List: # noqa: UP006 + check_empty_containers(obj) + if not isinstance(obj, list): + return False + arg_type = get_args(target_type)[0] + arg_origin = get_origin(arg_type) + for el in obj: + # check if nested container, ex: List[List[str]] + if arg_origin: # processes nested container, ex: List[List[str]] + if not container_checker(el, arg_type): + return False + elif not isinstance(el, arg_type): + return False + return True + elif origin_type is typing.Dict or origin_type is dict: # noqa: UP006 + check_empty_containers(obj) + if not isinstance(obj, dict): + return False + key_type = get_args(target_type)[0] + val_type = get_args(target_type)[1] + for key, val in obj.items(): + # check if keys are of right type + if not isinstance(key, key_type): + return False + val_origin = get_origin(val_type) + if val_origin: + if not container_checker(val, val_type): + return False + elif not isinstance(val, val_type): + return False + return True + elif origin_type is typing.Tuple or origin_type is tuple: # noqa: UP006 + check_empty_containers(obj) + if not isinstance(obj, tuple): + return False + arg_types = get_args(target_type) + if len(obj) != len(arg_types): + return False + for el, el_type in zip(obj, arg_types): + el_origin = get_origin(el_type) + if el_origin: + if not container_checker(el, el_type): + return False + elif not isinstance(el, el_type): + return False + return True + elif origin_type is Union or issubclass( + origin_type, + BuiltinUnionType, + ): # also handles Optional + if obj is None: # check before recursion because None is always fine + return True + inner_types = get_args(target_type) + for t in inner_types: + t_origin = get_origin(t) + if t_origin: + return container_checker(obj, t) + elif isinstance(obj, t): + return True + return False + + +def _isinstance(obj, target_type) -> bool: + if isinstance(target_type, collections.abc.Container): + if not isinstance(target_type, tuple): + raise RuntimeError( + "The second argument to " + "`torch.jit.isinstance` must be a type " + "or a tuple of types" + ) + for t_type in target_type: + if _isinstance(obj, t_type): + return True + return False + + origin_type = get_origin(target_type) + if origin_type: + return container_checker(obj, target_type) + + # Check to handle non-typed optional origin returns as none instead + # of as optional in 3.7-3.8 + check_args_exist(target_type) + + # handle non-containers + return isinstance(obj, target_type) + + +class _TensorExtractor(pickle.Pickler): + def __init__(self, *args, tensors: list[torch.Tensor], **kwargs): + super().__init__(*args, **kwargs) + self.tensors = tensors + + def persistent_id(self, obj): + if isinstance(obj, torch.Tensor): + self.tensors.append(obj) + return "" + # Since we just want to extract tensors, we don't mind if an object is + # unpicklable if it doesn't contain tensors, as we can just ignore/skip + # it. To play it safe, we only do so for common objects that we're sure + # don't contain tensors. Feel free to add new types here. Note also that + # even if a type isn't listed here this won't block users, since they + # can just add a __getstate__ or __reduce__ method to their class. + if isinstance(obj, LockType): + return "" + # Futures and RRefs don't technically contain a value, they just offer + # the means to access a value. + if isinstance(obj, CFuture) or is_rref_instance(obj): + return "" + if isinstance(obj, CAwait): + return "" + if isinstance(obj, torch.cuda.Event): + return "" + if isinstance(obj, threading.Thread): + return "" + return None + + +def _extract_tensors(obj): + r""" + This function is exclusively called from C++. + See ``torch/csrc/jit/python/python_ivalue.h``. + + It extracts the tensors contained in the given object, through pickling. + """ + tensors: list[torch.Tensor] = [] + extractor = _TensorExtractor(io.BytesIO(), protocol=-1, tensors=tensors) + extractor.dump(obj) + return tensors + + +def _get_model_id(obj) -> str | None: + if isinstance(obj, torch.jit.ScriptModule): + return str(obj._c._type()) + elif isinstance(obj, torch.jit.ScriptFunction): + return obj.qualified_name + else: + return None + + +# In Python-3.11+ typed enums (i.e. IntEnum for example) retain number of base class methods in subclass +# that were previously dropped. To preserve the behavior, explicitly drop them there + +if sys.version_info >= (3, 11): + _drop(enum.Enum.__new__) + _drop(enum.Enum.__format__) + _drop(enum.Enum.__repr__) + _drop(enum.Enum.__str__) diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/__init__.py b/.venv/lib/python3.12/site-packages/torch/_lazy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c42f8567f7e1ae9fb7e67fcfbe23219010126a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lazy/__init__.py @@ -0,0 +1,78 @@ +import pickle +from collections.abc import Sequence +from types import ModuleType +from typing import cast, TypeVar + +import torch +import torch._C._lazy +from torch.serialization import DEFAULT_PROTOCOL +from torch.types import FileLike +from torch.utils._pytree import tree_flatten, tree_unflatten + +from .closure import add_step_closure, run_step_closures + + +_T = TypeVar("_T") + + +def mark_step(device: str = "", wait: bool = False) -> None: + """Triggers a mark step, which amounts to + - collecting a group of 'live' lazy tensors to index into the compilation cache + (lowering/compiling their IR graphs if not cached) + - kicking off execution of the compiled function + - (optionally, wait=True) waiting for cpu-side execution to complete (does not sync the accelerator) + """ + # TODO(whc) expand this to include backend hooks and align with XLA backend needs + torch._C._lazy._mark_step(device, [], wait=wait) + + run_step_closures() + + +def wait_device_ops(devices: list[str] | None = None) -> None: + """Waits for all the async operations on the given devices to complete. + Args: + devices (string..., optional): The devices whose async ops need to be waited + for. If empty, all the local devices will be waited for. + """ + if devices is None: + devices = [] + torch._C._lazy._wait_device_ops(devices=devices) + + +def sync_multi(tensors: Sequence[torch.Tensor], devices: list[str]) -> None: + """ + Sync the list of lazy tensors so there IR get lowered for the activate backend + and the compiled computation graph get cached. + """ + torch._C._lazy._sync_multi(list(tensors), devices) + + +def get_tensor_id(tensor: torch.Tensor) -> int: + """Return a unique id of the lazy tensor maintained by LTC""" + return torch._C._lazy._get_tensor_id(tensor) + + +def to_cpu(tensors: _T, devices: list[str] | None = None) -> _T: + devices = devices or ["lazy"] + + flattened, spec = tree_flatten(tensors) + sync_multi(flattened, devices) + return cast(_T, tree_unflatten([t.to("cpu") for t in flattened], spec)) + + +def save( + tensors: object, + f: FileLike, + pickle_module: ModuleType = pickle, + pickle_protocol: int = DEFAULT_PROTOCOL, + _use_new_zipfile_serialization: bool = True, + _disable_byteorder_record: bool = False, +) -> None: + torch.save( + to_cpu(tensors), + f, + pickle_module=pickle_module, + pickle_protocol=pickle_protocol, + _use_new_zipfile_serialization=_use_new_zipfile_serialization, + _disable_byteorder_record=_disable_byteorder_record, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffb7410a698a9e3b8cad6315bf7279b73e6c7bb6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/closure.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/closure.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b3079c7411cc71eabb03ab87a9a5d094547ef6f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/closure.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/computation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/computation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa3c69af9ef53820a87b02dec57a7e67692d8046 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/computation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d33fe17523b7e2cc3bb3db242681feb1218c97e5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/debug.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/debug.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9f0f33b308fb27093bbf1d8a2110a3b026dea2e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/debug.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/device_context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/device_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2083001203d47cb248fa1acbf35f697ea072d51f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/device_context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/extract_compiled_graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/extract_compiled_graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bd7c0d2a16a51182e7cf2049b401a981342bee6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/extract_compiled_graph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/ir_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/ir_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2646dfcd865cf3fa1dc738bd65afe192e07ef811 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/ir_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/metrics.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2a92eef80fb69656afd8f43df3727b103a9db6f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/metrics.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/tensor_factory_functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/tensor_factory_functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80c00111ea17a386ba508232046cbfe66a94969b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/tensor_factory_functions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/ts_backend.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/ts_backend.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6948f65cb5a654d0648e2e1c17dab691ff99ccbb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_lazy/__pycache__/ts_backend.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/closure.py b/.venv/lib/python3.12/site-packages/torch/_lazy/closure.py new file mode 100644 index 0000000000000000000000000000000000000000..c771041582d1121696ff791c9c37fc90ae761c47 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lazy/closure.py @@ -0,0 +1,158 @@ +import os +import threading +from collections.abc import Callable, Iterable +from queue import Empty as EmptyQueue, Queue +from typing import overload +from typing_extensions import TypeVarTuple, Unpack + +from torch._lazy.device_context import DeviceContext, get_device_context + + +_Ts = TypeVarTuple("_Ts") + + +class ClosureHandler: + def __init__(self) -> None: + pass + + def run(self, closure: Callable[[], object]) -> None: + """Run closure function + + Args: + closure: callable function to run + """ + closure() + + def __call__(self, closures: Iterable[Callable[[], object]]) -> None: + for closure in closures: + self.run(closure) + + +class AsyncClosureHandler(ClosureHandler): + """Handler for Asynchronous Step Closures + Args: + max_queue_size: The maximum length of the closure queue after which + the training loop will block until closures are evaluated. + By default, a reasonable limit of a maximum of 100 on the queue. + This value can be set using the `XLA_MAX_ASYNC_QUEUE` environment + variable. + """ + + def __init__(self, max_queue_size: int = 100) -> None: + super().__init__() + self._closure_queue: Queue[Callable[[], object]] = Queue( + int(os.environ.get("LTC_MAX_ASYNC_QUEUE", max_queue_size)) + ) + self._closure_exception: Queue[Exception] = Queue() + self._closure_lock = threading.Lock() + self._closure_event_loop_finished = threading.Event() + self._closure_event_loop: threading.Thread | None = None + + def start_event_loop(self) -> None: + """Start closure event loop if not started""" + if self._closure_event_loop is None: + + def event_loop() -> None: + # Run loop until closure event is set and closure queue is empty + while True: + try: + closure = self._closure_queue.get(block=True, timeout=3) + closure() + self._closure_queue.task_done() + except EmptyQueue: + with self._closure_lock: + if self._closure_queue.empty(): + self._closure_event_loop_finished.set() + return + except Exception as e: + self._closure_exception.put(e) + return + + self._closure_event_loop = threading.Thread(target=event_loop) + self._closure_event_loop.start() + + def run(self, closure: Callable[[], object]) -> None: + with self._closure_lock: + self._closure_queue.put(closure, block=True) + if ( + self._closure_event_loop is None + or not self._closure_event_loop.is_alive() + ): + try: + e = self._closure_exception.get(block=False) + raise RuntimeError( + "Cannot run asynchronous closure due to previously raised exception" + ) from e + except EmptyQueue: + self._closure_event_loop = None + self.start_event_loop() + + +@overload +def add_step_closure( + closure: Callable[[], object], + args: tuple[()] = (), + run_async: bool = False, +) -> None: ... +@overload +def add_step_closure( + closure: Callable[[Unpack[_Ts]], object], + args: tuple[Unpack[_Ts]], + run_async: bool = False, +) -> None: ... +def add_step_closure( + closure: Callable[..., object], + args: tuple[object, ...] = (), + run_async: bool = False, +) -> None: + """Adds a closure to the list of the ones to be run at the end of the step. + Many times during model training there is the need to print/report (print to + console, post to tensorboard, etc...) information which require the content of + intermediary tensors to be inspected. + Inspecting different tensors content in different points of the model code + requires many executions and typically causes performance issues. + Adding a step closure will ensure that it will be run after the barrier, when + all the live tensors will be already materialized to device data. + Live tensors which will include the ones captured by the closure arguments. + So using `add_step_closure()` will ensure a single execution will be + performed, even when multiple closures are queued, requiring multiple tensors + to be inspected. + Step closures will be run sequentially in the order they have been queued. + Note that even though using this API the execution will be optimized, it is + advised to throttle the printing/reporting events once every N steps. + Args: + closure (callable): The function to be called. + args (tuple): The arguments to be passed to the closure. + run_async: If True, run the closure asynchronously. + """ + devctx = get_device_context() + closures_type = "async_step_closures" if run_async else "step_closures" + step_closures: list[Callable[[], object]] | None = getattr( + devctx, closures_type, None + ) + if step_closures is None: + step_closures = [] + setattr(devctx, closures_type, step_closures) + step_closures.append(lambda a=args: closure(*a)) + + +def run_step_closures() -> DeviceContext: + devctx = get_device_context() + async_step_closures = getattr(devctx, "async_step_closures", None) + if async_step_closures is not None: + devctx.async_step_closures = [] # type: ignore[attr-defined] + async_closure_handler = getattr(devctx, "async_closure_handler", None) + if async_closure_handler is None: + async_closure_handler = AsyncClosureHandler() + devctx.async_closure_handler = async_closure_handler # type: ignore[attr-defined] + async_closure_handler(async_step_closures) + + step_closures = getattr(devctx, "step_closures", None) + if step_closures is not None: + devctx.step_closures = [] # type: ignore[attr-defined] + closure_handler = getattr(devctx, "closure_handler", None) + if closure_handler is None: + closure_handler = ClosureHandler() + devctx.closure_handler = closure_handler # type: ignore[attr-defined] + closure_handler(step_closures) + return devctx diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/computation.py b/.venv/lib/python3.12/site-packages/torch/_lazy/computation.py new file mode 100644 index 0000000000000000000000000000000000000000..e162b1beb8c6c6df0ffab132982f7611542fc6ea --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lazy/computation.py @@ -0,0 +1,33 @@ +from collections.abc import Sequence + +import torch +import torch._C._lazy +import torch._C._lazy_ts_backend + + +def get_tensors_ts_device_data_node( + tensors: Sequence[torch.Tensor], +) -> tuple[list[int], list[object]]: + """Return tensor ids and eager tensors for DeviceData nodes in the + IR for the passed in lazy tensors. + + TODO: This API is currently ts backend specific. We are working on + generalizing it to all backends including XLA. + """ + return torch._C._lazy_ts_backend._get_tensors_ts_device_data_node(list(tensors)) + + +def get_graph_hash(tensors: Sequence[torch.Tensor]) -> str: + """Return the graph hash for the passed in lazy tensors""" + return torch._C._lazy._get_graph_hash(list(tensors)) + + +def run_cached_graph( + hash_str: str, graph_inputs: Sequence[object] +) -> list[torch.Tensor]: + """Running the cached computation graph with the given inputs + + TODO: This API is currently ts backend specific. We are working on + generalizing it to all backends including XLA. + """ + return torch._C._lazy_ts_backend._run_cached_graph(hash_str, list(graph_inputs)) diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/config.py b/.venv/lib/python3.12/site-packages/torch/_lazy/config.py new file mode 100644 index 0000000000000000000000000000000000000000..46839094d89a04568dd602f4cdb532450f9fa130 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lazy/config.py @@ -0,0 +1,16 @@ +import torch._C._lazy + + +def get_force_fallback() -> str: + """Get the config used to force LTC fallback""" + return torch._C._lazy._get_force_fallback() + + +def set_force_fallback(configval: str) -> None: + """Set the config used to force LTC fallback""" + torch._C._lazy._set_force_fallback(configval) + + +def set_reuse_ir(val: bool) -> None: + """Set the config to reuse IR nodes for faster tracing""" + torch._C._lazy._set_reuse_ir(val) diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/debug.py b/.venv/lib/python3.12/site-packages/torch/_lazy/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..2f1a922a626ea3c8071112e1f16cdab245a31c17 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lazy/debug.py @@ -0,0 +1,24 @@ +from collections.abc import Sequence + +import torch +import torch._C._lazy + + +def render_ir_graph(tensors: Sequence[torch.Tensor]) -> str: + """Return a text dump of the LTC IR graph in dot format for the tensors. + The text can be processed by tools like dot to be rendered in pdf,png etc.""" + return torch._C._lazy._get_tensors_dot(list(tensors)) + + +def dump_ir(tensors: Sequence[torch.Tensor], ir_format: str) -> str: + """Return a dump of the tensors in the specified format. + Valid format are + - text: for LTC IR + - backend: for the active backend IR + """ + if ir_format == "text": + return torch._C._lazy._get_tensors_text(list(tensors)) + elif ir_format == "backend": + return torch._C._lazy._get_tensors_backend(list(tensors)) + else: + raise RuntimeError(f"Unrecognized IR format: {ir_format}") diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/device_context.py b/.venv/lib/python3.12/site-packages/torch/_lazy/device_context.py new file mode 100644 index 0000000000000000000000000000000000000000..a49fe1a308803e480f4c8f99232c7335310e08d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lazy/device_context.py @@ -0,0 +1,24 @@ +import threading + +import torch._C._lazy + + +class DeviceContext: + _CONTEXTS: dict[str, "DeviceContext"] = {} + _CONTEXTS_LOCK = threading.Lock() + + def __init__(self, device: str) -> None: + self.device = device + + +def get_device_context(device: str | None = None) -> DeviceContext: + if device is None: + device = torch._C._lazy._get_default_device_type() + else: + device = str(device) + with DeviceContext._CONTEXTS_LOCK: + devctx = DeviceContext._CONTEXTS.get(device, None) + if devctx is None: + devctx = DeviceContext(device) + DeviceContext._CONTEXTS[device] = devctx + return devctx diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/extract_compiled_graph.py b/.venv/lib/python3.12/site-packages/torch/_lazy/extract_compiled_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..fb721739ab2fb16b6ed17fcf12b332ad5fb0e90f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lazy/extract_compiled_graph.py @@ -0,0 +1,249 @@ +import copy +import dataclasses +import itertools +import os +from collections.abc import Iterable, Mapping, Sequence +from typing import cast, Protocol, TypeAlias, TypeVar + +import torch +import torch._lazy as lazy +import torch._lazy.metrics as metrics +from torch import fx +from torch._lazy import computation, debug as lazy_debug +from torch._lazy.tensor_factory_functions import tensor_factory_functions +from torch.fx.node import Argument + + +debug = os.environ.get("debug_extract_compiled_graph") is not None + +_T = TypeVar("_T") + +# A TorchScript graph-input IValue: concretely a const tensor, a device-data +# node, or a runtime argument, none of which share a useful static type here. +_IValue: TypeAlias = object + + +class _CompiledFn(Protocol): + def __call__(self, *args: torch.Tensor) -> Sequence[torch.Tensor]: ... + + +@dataclasses.dataclass +class GraphInputMatcher: + """ + The GraphInputMatcher class setup the graph inputs for future calls after lazy tracing. + Specifically, those graph inputs corresponding to method parameters should be replaced with the + arguments for the current call. + + tensor_id_to_arg_idx maps the tensor id to the parameter index. + graph_input_tensor_ids, graph_input_ivalues list the tensor_id and ivalue for each of the + TS/XLA graph inputs. + """ + + tensor_id_to_arg_idx: dict[int, int] + graph_input_tensor_ids: list[int] + # there are 2 categories of graph_input_tensors. + # Category 1: those whose id are not found in tensor_id_to_arg_idx. These are + # most likely const tensors and we can get its content from graph_input_tensors + # Category 2: those whose id are found in tensor_id_to_arg_idx. We should get + # the tensor from method arguments + graph_input_ivalues: list[_IValue] + + # get the real graph input tensors + def __call__(self, args: Sequence[object]) -> list[_IValue]: + real_input: list[_IValue] = [] + for tensor_id, traced_ivalue in zip( + self.graph_input_tensor_ids, self.graph_input_ivalues + ): + arg_idx = self.tensor_id_to_arg_idx.get(tensor_id, None) + if arg_idx is None: + inp = traced_ivalue + else: + inp = args[arg_idx] + real_input.append(inp) + return real_input + + +class ReturnValueHandler: + r""" + When ltc_sync_multi is called on multi tensors, the compiled graph + will contain output only for unique tensors - if a tensor appears multiple + times in the input to _ltc_sync_multi, only the first occurrence matters. + + However from python level, we still expect multi tensors returned with duplication + even if the TS graph dedup the output. e.g. for method: + + def forward(self, a): + return a, a + + the TS graph captured by LTC will return a single tensor, but Python method expects 2. + + This class dedup the lazy tensors first to get the index that will be used + to duplicate the eager tensors later. + """ + + def __init__(self, lazy_out_list: Sequence[object]) -> None: + self.index: list[list[int]] = [] + self.total_count = len(lazy_out_list) + + tensor_id_to_idx: dict[int, int] = {} + for dup_idx, lazy_tensor in enumerate(lazy_out_list): + uniq_idx = tensor_id_to_idx.get(id(lazy_tensor)) + if uniq_idx is not None: + self.index[uniq_idx].append(dup_idx) + else: + uniq_idx = len(self.index) + self.index.append([dup_idx]) + tensor_id_to_idx[id(lazy_tensor)] = uniq_idx + + def duplicate_eager_tensors(self, eager_tensor_list: Sequence[_T]) -> list[_T]: + duplicated_list: list[_T | None] = [None] * self.total_count + if len(eager_tensor_list) != len(self.index): + raise AssertionError( + f"eager_tensor_list length {len(eager_tensor_list)} != index length {len(self.index)}" + ) + + for uniq_idx, eager_tensor in enumerate(eager_tensor_list): + for dup_idx in self.index[uniq_idx]: + duplicated_list[dup_idx] = eager_tensor + # every slot is filled: self.index partitions range(total_count). + return cast(list[_T], duplicated_list) + + +def force_lazy_device(model: fx.GraphModule) -> None: + """ + Factory methods in a Fx graph may create tensors for a specific eager devices. + If we take no actions, those eager tensors will be mixed with lazy tensors and + cause crash. This method overwrite those eager device to lazy device. + """ + + def tolazydevice(dev: _T) -> _T: + if isinstance(dev, torch.device): + return cast(_T, torch.device("lazy", index=dev.index)) + return dev + + def hasDeviceArg(args: Iterable[Argument], kwargs: Mapping[str, Argument]) -> bool: + return any( + isinstance(arg, torch.device) + for arg in itertools.chain(args, kwargs.values()) + ) + + for nd in model.graph.nodes: + nd.args = tuple(tolazydevice(arg) for arg in nd.args) + nd.kwargs = {k: tolazydevice(v) for k, v in nd.kwargs.items()} + + # For torchbench like yolov3, hf_Bart, dynamo generates Fx graph that return + # eager tensors on the default device + # (check https://gist.github.com/shunting314/eabdf6c769c59bc384469717b8f9bb7f for yolove, + # and https://gist.github.com/shunting314/8d5e2d9348a3258959d3954186c48814 for hf_Bart). + # To force those tensors on the lazy device, we can not simply override + # the device argument since there is no explicit device argument. + # What we are doing here is, for the list of covered tensor factory methods + # we add a lazy device argument explicitly. + # + # TODO: This solution is not ideal since we may miss some factory methods. In future + # when we support lazy mode, this method can be replaced by that. + if nd.target in tensor_factory_functions and not hasDeviceArg( + nd.args, nd.kwargs + ): + kwargs = dict(nd.kwargs) # nd.kwargs is immutable. make a mutable copy. + kwargs["device"] = torch.device("lazy") + nd.kwargs = kwargs + + model.recompile() + + +def get_fallback_ops() -> list[str]: + fallback_ops = [] + for opname in metrics.counter_names(): + if "aten::" not in opname: + continue + val = int(metrics.counter_value(opname)) + if val > 0: + fallback_ops.append(f"{opname}={val}") + + return fallback_ops + + +def extract_compiled_graph( + model: fx.GraphModule, example_inputs: Sequence[torch.Tensor] +) -> _CompiledFn: + """ + Optimize an eager model with LTC and returns a wrapper to execute the + compiled graph directly without retracing. It depends on other mechanisms + like TorchDynamo guards to guarantee the returned wrapper is only called + when it's safe. + """ + lazy_args = [arg.to(device="lazy") for arg in example_inputs] + args_tensor_ids = [lazy.get_tensor_id(lazy_arg) for lazy_arg in lazy_args] + tensor_id_to_arg_idx = {tensor_id: i for i, tensor_id in enumerate(args_tensor_ids)} + lazy_model = copy.deepcopy(model).to(device=torch.device("lazy")) + force_lazy_device(lazy_model) + + # This line executes lazy tracing and enable us extracting compiled graph later + metrics.reset() + lazy_out = lazy_model(*lazy_args) + fallback_ops = get_fallback_ops() + metrics.reset() + + if len(fallback_ops) > 0: + raise RuntimeError( + f"Fail to extract the compiled graph because of fallback: {','.join(fallback_ops)}" + ) + + if not isinstance(lazy_out, (tuple, list)): + lazy_out = (lazy_out,) + + args_and_out = tuple(lazy_args) + tuple(lazy_out) + return_value_handler = ReturnValueHandler(args_and_out) + if debug: + print("Fx code:\n", model.code) + print("LTC IR:", lazy_debug.dump_ir(args_and_out, "text")) + + # TODO: this part is TS backend specific for now and will be generalized to + # support XLA + ( + graph_input_tensor_ids, + graph_input_ivalues, + ) = computation.get_tensors_ts_device_data_node(args_and_out) + if len(graph_input_tensor_ids) != len(graph_input_ivalues): + raise AssertionError( + f"graph_input_tensor_ids length {len(graph_input_tensor_ids)} " + f"!= graph_input_ivalues length {len(graph_input_ivalues)}" + ) + graph_input_matcher = GraphInputMatcher( + tensor_id_to_arg_idx, graph_input_tensor_ids, graph_input_ivalues + ) + + graph_hash = computation.get_graph_hash(args_and_out) + + if debug: + print("graph_hash", graph_hash) + print(f"args_tensor_ids {args_tensor_ids}") + print("tensor ids from device data:", graph_input_tensor_ids) + + # sync the list of output tensors so the computation graph for these + # tensors will be cached. Those computation graphs can be retrieved + # by graph hash later. + lazy.sync_multi(args_and_out, []) + + def optimized_mod(*args: torch.Tensor) -> Sequence[torch.Tensor]: + if len(args_and_out) == 0: + return () + graph_input = graph_input_matcher(args) + res = return_value_handler.duplicate_eager_tensors( + computation.run_cached_graph(graph_hash, graph_input) + ) + + if len(res) != len(args_and_out): + raise AssertionError( + f"result length {len(res)} != args_and_out length {len(args_and_out)}" + ) + for i, arg in enumerate(args): + # only copy those tensors that get inplace updated + if arg is not res[i]: + arg.copy_(res[i]) + + # skip the args + return res[len(args) :] + + return optimized_mod diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/ir_cache.py b/.venv/lib/python3.12/site-packages/torch/_lazy/ir_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..76781ba361ae69ddb374fad4c82fd3f695f7bc4b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lazy/ir_cache.py @@ -0,0 +1,13 @@ +import torch._C._lazy + + +def dump(dot_file_name: str) -> None: + """Dump TrieCache in the dot format""" + return torch._C._lazy._dump_ir_cache(dot_file_name) + + +def reset() -> None: + """Clear TrieCache. This is needed in testing to avoid + node reusing between different tests. + """ + return torch._C._lazy._clear_ir_cache() diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/metrics.py b/.venv/lib/python3.12/site-packages/torch/_lazy/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..ceb6f1d1eae768029a9fdb46d5d2e17e3b6c07bd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lazy/metrics.py @@ -0,0 +1,21 @@ +import torch._C._lazy + + +def reset() -> None: + """Resets all metric counters.""" + torch._C._lazy._reset_metrics() + + +def counter_names() -> list[str]: + """Retrieves all the currently active counter names.""" + return torch._C._lazy._counter_names() + + +def counter_value(name: str) -> int: + """Return the value of the counter with the specified name""" + return torch._C._lazy._counter_value(name) + + +def metrics_report() -> str: + """Return the combined (lazy core and backend) metric report""" + return torch._C._lazy._metrics_report() diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/tensor_factory_functions.py b/.venv/lib/python3.12/site-packages/torch/_lazy/tensor_factory_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..302c51306d00e6e128574f8b44d001aec1ddbea3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lazy/tensor_factory_functions.py @@ -0,0 +1,49 @@ +import torch + + +""" +tensor_factory_functions defines the list of torch functions that create tensors. +The list is grabbed by searching through native_functions.yaml by the following +regular expression: + + cat native_functions.yaml | grep 'func:' | grep -v "Tensor.*->" | grep "[-]>.*Tensor" + +It's possible that new tensor factory functions are added making this list stale. +Use at your own risk or regenerate the list. +""" +tensor_factory_functions = ( + torch._cudnn_init_dropout_state, + torch.arange, + torch.bartlett_window, + torch.blackman_window, + torch._empty_affine_quantized, + torch.empty_strided, + torch.eye, + torch.full, + torch.from_file, + torch.hann_window, + torch.hamming_window, + torch.kaiser_window, + torch.linspace, + torch.logspace, + torch.ones, + torch.scalar_tensor, + torch.rand, + torch.randint, + torch.randn, + torch.randperm, + torch.range, + torch._efficientzerotensor, + torch.zeros, + torch.tril_indices, + torch.triu_indices, + # Note: the following functions match the regular expression search above but + # they are not available in the torch module. Comment out. + # torch._sparse_coo_tensor_with_dims, + # torch.fft_fftfreq, + # torch.fft_rfftfreq, +) + ( + # torch.tensor is special since it's not in native_functions.yaml + # add it separately + torch.tensor, +) diff --git a/.venv/lib/python3.12/site-packages/torch/_lazy/ts_backend.py b/.venv/lib/python3.12/site-packages/torch/_lazy/ts_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..9051a60d7ffbc8c2dbb47b2d6922fba2821b5be2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lazy/ts_backend.py @@ -0,0 +1,6 @@ +import torch._C._lazy_ts_backend + + +def init() -> None: + """Initializes the lazy Torchscript backend""" + torch._C._lazy_ts_backend._init() diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__init__.py b/.venv/lib/python3.12/site-packages/torch/_library/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6f50d46dde0527d1e31e96d617920e26d9c69acb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/__init__.py @@ -0,0 +1,6 @@ +import torch._library.autograd +import torch._library.fake_impl +import torch._library.simple_registry +import torch._library.utils +from torch._library.fake_class_registry import register_fake_class +from torch._library.triton import capture_triton, triton_op, wrap_triton diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c1d086aedfb2955e47a379acdbdcd794cd6e3ca Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/_out_variant.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/_out_variant.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b85438cd9361d14c130540b79785b34023dd8ed8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/_out_variant.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/autograd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/autograd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a48840f7043d7c2a99c62d838a221d434e3bac5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/autograd.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/custom_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/custom_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c49bef4db51e0db433df110db926323649573b45 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/custom_ops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/effects.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/effects.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..877915a2b916a0a919201be059080add21034f19 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/effects.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/fake_class_registry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/fake_class_registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5be3c6534de3d127bcb72dea5301589f6dc7122a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/fake_class_registry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/fake_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/fake_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd5cd93e072e9974ca9d29efaabd24ab1886205a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/fake_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/fake_profile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/fake_profile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..878611ea1d8eb977b63226769ef8c55a6741eb42 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/fake_profile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/infer_schema.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/infer_schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea1c2932c816c9732db31631172c1912b1b404d0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/infer_schema.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/opaque_object.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/opaque_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59b985773d91f2a34042a322164cfe7693f2ae73 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/opaque_object.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/simple_registry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/simple_registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec13dcf39348b520703cca8508775c1a096307a9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/simple_registry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/triton.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/triton.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b7faa2ea26b68d41c41fe5f8ddc0e91e193ea1e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/triton.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae4cca0eb9bd1f88f6bf4497a0ccdbdb99927fcd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_library/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_library/_out_variant.py b/.venv/lib/python3.12/site-packages/torch/_library/_out_variant.py new file mode 100644 index 0000000000000000000000000000000000000000..9e9603a7e3c3809f104326d8b3901a8a4d137552 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/_out_variant.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +import logging + +import torch + + +log = logging.getLogger(__name__) + + +# Manual registry for ops whose out variant is not discoverable via +# to_out_variant() (e.g. flat _out naming instead of .out overload). +_manual_out_variant_registry: dict[torch._ops.OpOverload, torch._ops.OpOverload] = {} + + +def register_out_variant( + functional_op: torch._ops.OpOverload, + out_op: torch._ops.OpOverload, +) -> None: + """Register a functional op -> out variant mapping.""" + _manual_out_variant_registry[functional_op] = out_op + + +def lookup_manual_out_variant( + op: torch._ops.OpOverload, +) -> torch._ops.OpOverload | None: + """Return the manually registered out variant for op, or None.""" + return _manual_out_variant_registry.get(op) + + +def _is_functional(schema: torch._C.FunctionSchema) -> bool: + """ + A schema is functional if no argument is written to and the name doesn't + end with '_'. + """ + op_name = schema.name.split("::")[-1] + if op_name.endswith("_"): + return False + return not any(arg.is_write for arg in schema.arguments) + + +def _is_mutable_arg(arg: torch._C.Argument) -> bool: + return arg.alias_info is not None and arg.alias_info.is_write + + +def _signatures_match( + schema_a: torch._C.FunctionSchema, + schema_b: torch._C.FunctionSchema, +) -> bool: + """Compare two schemas by their non-mutable arguments (name, type, default value).""" + non_mutable_args_a = [arg for arg in schema_a.arguments if not _is_mutable_arg(arg)] + non_mutable_args_b = [arg for arg in schema_b.arguments if not _is_mutable_arg(arg)] + if len(non_mutable_args_a) != len(non_mutable_args_b): + return False + for a, b in zip(non_mutable_args_a, non_mutable_args_b): + if a.name != b.name: + return False + if str(a.type) != str(b.type): + return False + if a.default_value != b.default_value: + return False + return True + + +def _has_valid_out_variant_returns( + schema: torch._C.FunctionSchema, + mutable_args: list[torch._C.Argument], +) -> bool: + """Out variant must return either nothing or the mutable args themselves.""" + if len(schema.returns) == 0: + return True + + if len(schema.returns) != len(mutable_args): + return False + + # Each return must alias exactly one mutable arg, in order + for ret, arg in zip(schema.returns, mutable_args): + if ret.alias_info is None or arg.alias_info is None: + return False + if ret.alias_info.before_set != arg.alias_info.before_set: + return False + return True + + +def get_out_arg_names(out_op: torch._ops.OpOverload) -> list[str]: + """Get the names of out arguments for an out variant op.""" + schema = out_op._schema + return [arg.name for arg in schema.arguments if _is_mutable_arg(arg)] + + +def to_out_variant(op: torch._ops.OpOverload) -> torch._ops.OpOverload | None: + """ + Given a functional operator overload, return its corresponding out variant. + """ + schema = op._schema + + if not _is_functional(schema): + raise RuntimeError( + f"Failed to find out variant for op '{op}' as its schema is not functional. \n" + f" {schema}" + ) + + # Get the op packet to access all overloads + namespace = op.namespace + op_name = schema.name.split("::")[1] + torch_packet = getattr(getattr(torch.ops, namespace), op_name) + + # Search through all overloads for matching out variant + for candidate in torch_packet.op_overloads(): + # pyrefly: ignore [missing-attribute] + if torch.Tag.out not in candidate.tags: + continue + + candidate_schema = candidate._schema + + if not _signatures_match(schema, candidate_schema): + continue + + # We assume that all mutable args are used for out + mutable_args = [ + arg for arg in candidate_schema.arguments if _is_mutable_arg(arg) + ] + if len(mutable_args) != len(schema.returns): + continue + + if not _has_valid_out_variant_returns(candidate_schema, mutable_args): + raise RuntimeError( + f"Out variant {candidate} has invalid returns. " + f"Expected either no returns or returns that alias the mutable args, " + f"got: {candidate_schema}" + ) + + return candidate + + return None + + +def check_out_variant( + functional_op: torch._ops.OpOverload, expected_out_op: torch._ops.OpOverload +) -> None: + """ + Checks that to_out_variant returns the expected out variant for a functional op. + Raises AssertionError if the out variant is not valid. + """ + out_op = to_out_variant(functional_op) + if out_op is None: + tagged_info = _get_out_variants_info(functional_op) + raise AssertionError( + f"We did not find an out variant for {functional_op}. Some common mistakes include:\n" + " 1. The out variant is missing the torch.Tag.out tag.\n" + " 2. The out variant is not an overload of the original op (e.g., 'op.out' or 'op.overload_out') \n" + " 3. The out variant's input arguments does not match the functional op's signature (excluding the mutable args).\n" + " 4. The original operator is not functional.\n" + f"Overloads tagged with out:\n" + f"{tagged_info or ' (none)'}" + ) + if out_op != expected_out_op: + raise AssertionError( + f"to_out_variant({functional_op}) returned {out_op}, " + f"but expected {expected_out_op}. " + f"The out variant name does not match the functional op." + ) + + +def _get_out_variants_info(functional_op) -> str: + """Collect information about overloads tagged with out for debugging.""" + namespace = functional_op.namespace + op_name = functional_op._schema.name.split("::")[1] + torch_packet = getattr(getattr(torch.ops, namespace), op_name) + + overloads_info: list[str] = [] + for overload_name in torch_packet.overloads(): + candidate = getattr(torch_packet, overload_name) + # pyrefly: ignore [missing-attribute] + if torch.Tag.out in candidate.tags: + overloads_info.append(f" - {overload_name}: {candidate._schema}") + + return "\n".join(overloads_info) diff --git a/.venv/lib/python3.12/site-packages/torch/_library/autograd.py b/.venv/lib/python3.12/site-packages/torch/_library/autograd.py new file mode 100644 index 0000000000000000000000000000000000000000..8737d2d32c6dd6cc3a731b25d2613747bac1839b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/autograd.py @@ -0,0 +1,275 @@ +# mypy: allow-untyped-defs +import dataclasses +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Protocol + +from torch import _C, _ops, autograd, Tensor +from torch.utils import _pytree + +from . import utils + + +class InfoProtocol(Protocol): + _backward_fn: Callable | None + _setup_context_fn: Callable | None + + +@dataclasses.dataclass +class Info: + _backward_fn: Callable | None + _setup_context_fn: Callable | None + + +def make_autograd_impl(op: _ops.OpOverload, info: InfoProtocol) -> Callable: + name: str = f"GeneratedBackwardFor_{op._namespace}_{op._opname}_{op._overloadname}" + + schema = op._schema + is_out_op = utils.is_out(op) + has_kwarg_only_args = utils.has_kwarg_only_args(op._schema) + num_positional_args = sum(not a.kwarg_only for a in schema.arguments) + has_tensorlist_like_args = any( + utils.is_tensorlist_like_type(a.type) + for a in (*schema.arguments, *schema.returns) + ) + + @dataclass + class Metadata: + keyset: _C.DispatchKeySet + keyword_only_args: dict[str, Any] + + def redispatch_no_grad(keyset, args, kwargs): + with _C._AutoDispatchBelowAutograd(): + result = op.redispatch(keyset & _C._after_autograd_keyset, *args, **kwargs) + return result + + def forward(ctx, *args): + metadata = args[-1] + args = args[:-1] + + with _C._AutoDispatchBelowAutograd(): + keyset = metadata.keyset + kwargs = metadata.keyword_only_args + result = op.redispatch(keyset & _C._after_autograd_keyset, *args, **kwargs) + if info._setup_context_fn: + # The Dispatcher will remove args that are equal to their default + # values from (args, kwargs). We're going to add it back so that + # the user can access them. + # + # This is OK to do: The Dispatcher removed the args for serialization + # FC/BC reasons (that is, a graph will not store args that are equal + # to their default values), but that doesn't matter here. If the user + # adds a new default arg, then they must update + # their setup_context (along with the rest of their operator + # registrations) + args, kwargs = utils.fill_defaults(op._schema, args, kwargs) + + if has_kwarg_only_args: + info._setup_context_fn( + ctx=ctx, inputs=args, keyword_only_inputs=kwargs, output=result + ) + else: + info._setup_context_fn(ctx=ctx, inputs=args, output=result) + return result + + def backward(ctx, *grads): + if info._backward_fn: + try: + prev_needs_input_grad = ctx.needs_input_grad + ctx.needs_input_grad = prev_needs_input_grad[:-1] + result = info._backward_fn(ctx, *grads) + finally: + ctx.needs_input_grad = prev_needs_input_grad + num_actual_inputs = len(prev_needs_input_grad) - 1 + valid_return_counts = {num_actual_inputs, num_positional_args} + actual = len(result) if isinstance(result, tuple) else 1 + if actual not in valid_return_counts: + expected = ( + str(num_actual_inputs) + if num_actual_inputs == num_positional_args + else f"{num_actual_inputs} or {num_positional_args}" + ) + raise RuntimeError( + f"The backward formula for {op} returned an incorrect " + f"number of gradients (expected {expected}, got {actual}). " + f"Expected one gradient for each forward input, or for " + f"each positional input to the operator. Use None for " + f"inputs that do not require a gradient." + ) + if isinstance(result, tuple): + extra_grads = result[num_actual_inputs:] + if any(grad is not None for grad in extra_grads): + raise RuntimeError( + f"The backward formula for {op} returned a non-None " + f"gradient for an input that was not passed to the " + f"operator. Defaulted inputs that were not passed " + f"through autograd must return None." + ) + if has_tensorlist_like_args: + result = result[:num_actual_inputs] + return (*result, None) + return result, None + raise RuntimeError( + f"Trying to backward through {op} but no autograd " + f"formula was registered. " + f"Please use register_autograd to add one." + ) + + Generated = type( + name, + (autograd.Function,), + { + "forward": staticmethod(forward), + "backward": staticmethod(backward), + }, + ) + + if has_tensorlist_like_args: + Generated = supports_tensorlist(Generated) + + # The dispatcher passes any keyword-only-args as kwargs and the + # rest of the args (even if specified as kwargs) as args. + def autograd_impl(keyset, *args, **keyword_only_args): + if is_out_op: + if _C.is_grad_enabled() and _C._any_requires_grad( + *args, **keyword_only_args + ): + raise RuntimeError( + f"{op._opname}(): functions with out=... arguments don't " + "support automatic differentiation, but one of the arguments " + "requires grad." + ) + return redispatch_no_grad(keyset, args, keyword_only_args) + + if _C.is_grad_enabled() and _C._any_requires_grad(*args): + result = Generated.apply(*args, Metadata(keyset, keyword_only_args)) # type: ignore[attr-defined] + else: + result = redispatch_no_grad(keyset, args, keyword_only_args) + return result + + return autograd_impl + + +def supports_tensorlist(cls: Any) -> Any: + """Allows a given autograd.Function class to support List[Tensor] inputs/outputs. + + Regular autograd.Function has a constraint that it only directly supports autograd for + Tensors. Applying @supports_tensorlist enables an autograd.Function to support + autograd for List[Tensor] inputs and outputs. + """ + orig_forward = cls.forward + orig_backward = cls.backward + orig_apply = cls.apply + + @dataclass + class TensorListMetadata: + input_spec: _pytree.TreeSpec + output_spec: _pytree.TreeSpec | None = None + result_is_tuple: bool | None = None + + def new_forward(ctx, *args): + metadata = args[-1] + args = args[:-1] + if not isinstance(metadata, TensorListMetadata): + raise NotImplementedError( + "NYI: calling supports_tensorlist autograd.Function.forward directly. " + "You should probably be calling .apply instead. " + "Please file an issue if not." + ) + args = _pytree.tree_unflatten(list(args), metadata.input_spec) + result = orig_forward(ctx, *args) + metadata.result_is_tuple = isinstance(result, tuple) + if not metadata.result_is_tuple: + result = (result,) + flat_result, output_spec = _pytree.tree_flatten(result, not_list_of_tensor) + metadata.output_spec = output_spec + + if hasattr(ctx, "_pt_metadata"): + raise RuntimeError( + "Please don't set ctx._pt_metadata; PyTorch uses it to store info" + ) + ctx._pt_metadata = metadata + + return tuple(flat_result) + + def new_backward(ctx, *grads): + if not hasattr(ctx, "_pt_metadata"): + raise NotImplementedError( + "NYI: calling supports_tensorlist autograd.Function.backward directly. " + "This will automatically get called by PyTorch autograd. " + "Please file an issue if you need this." + ) + + metadata = ctx._pt_metadata + grads = _pytree.tree_unflatten(list(grads), metadata.output_spec) + + # If the user's input is ([x, y, z], w), + # then needs_input_grad is (bool, bool, bool, bool, bool). + # We need to + # 1. get rid of the additional bool (which comes from the extra + # `metadata input`) + # 2. _pytree.tree_unflatten to get the right structure. + prev_needs_input_grad = ctx.needs_input_grad + try: + ctx.needs_input_grad = _pytree.tree_unflatten( + list(ctx.needs_input_grad[:-1]), metadata.input_spec + ) + grad_inputs = orig_backward(ctx, *grads) + finally: + ctx.needs_input_grad = prev_needs_input_grad + + if not isinstance(grad_inputs, tuple): + grad_inputs = (grad_inputs,) + # Assume that any Nones in the backward are Tensors. + # If the forward has an arg that is [1, 2, 3], the backward should + # return None as the grad. + # If the forward has an arg that is [tensor, tensor], the backward + # may return [None, None], [grad, None], [None, grad], or [grad, grad]. + flat_grad_inputs, grad_inputs_spec = _pytree.tree_flatten( + grad_inputs, not_list_of_optional_tensor + ) + if grad_inputs_spec != metadata.input_spec: + raise RuntimeError( + f"Expected the return from backward to be of the same structure " + f"as the inputs. Got: {grad_inputs_spec} (return from backward), " + f"{metadata.input_spec} (inputs)" + ) + return tuple(flat_grad_inputs + [None]) + + def new_apply(*args): + flat_args, input_spec = _pytree.tree_flatten(args, is_leaf=not_list_of_tensor) + metadata = TensorListMetadata(input_spec) + result = orig_apply(*flat_args, metadata) # type: ignore[misc] + if metadata.output_spec is None: + raise AssertionError("metadata.output_spec must not be None") + result = _pytree.tree_unflatten(list(result), metadata.output_spec) + if not metadata.result_is_tuple: + if not isinstance(result, tuple): + raise AssertionError(f"result must be tuple, got {type(result)}") + if len(result) != 1: + raise AssertionError( + f"result tuple must have length 1, got {len(result)}" + ) + return result[0] + return result + + cls.forward = new_forward + cls.backward = new_backward + cls.apply = new_apply + return cls + + +def not_list_of_tensor(tree): + if isinstance(tree, tuple): + return False + if isinstance(tree, list): + return any(not isinstance(l, Tensor) for l in tree) + return True + + +def not_list_of_optional_tensor(tree): + if isinstance(tree, tuple): + return False + if isinstance(tree, list): + return any(l is not None and not isinstance(l, Tensor) for l in tree) + return True diff --git a/.venv/lib/python3.12/site-packages/torch/_library/custom_ops.py b/.venv/lib/python3.12/site-packages/torch/_library/custom_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..ad341975fcc0001816c2ea193ac8049e04320421 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/custom_ops.py @@ -0,0 +1,1123 @@ +# mypy: allow-untyped-defs +import collections +import inspect +import logging +import warnings +import weakref +from collections.abc import Callable, Iterable, Sequence +from contextlib import contextmanager +from typing import Any, overload, TypeAlias, Union + +import torch +from torch import _C, _ops, Tensor +from torch.types import _dtype +from torch.utils._exposed_in import exposed_in + +from . import autograd, utils +from .effects import EffectType + + +device_types_t: TypeAlias = str | Sequence[str] | None # noqa: PYI042 +tags_t: TypeAlias = _C.Tag | Sequence[_C.Tag] | None # noqa: PYI042 +log = logging.getLogger(__name__) + + +def _normalize_tags(tags: tags_t) -> tuple[_C.Tag, ...]: + if tags is None: + return () + if isinstance(tags, _C.Tag): + tags = (tags,) + return tuple(dict.fromkeys(tags)) + + +def _with_pt2_compliant_tag(tags: Sequence[_C.Tag]) -> list[_C.Tag]: + return [ + _C.Tag.pt2_compliant_tag, + *(tag for tag in tags if tag != _C.Tag.pt2_compliant_tag), + ] + + +@overload +def custom_op( + name: str, + fn: None = None, + /, + *, + mutates_args: str | Iterable[str], + device_types: device_types_t = None, + schema: str | None = None, + tags: tags_t = None, +) -> Callable[[Callable[..., object]], "CustomOpDef"]: ... + + +@overload +def custom_op( + name: str, + fn: Callable[..., object], + /, + *, + mutates_args: str | Iterable[str], + device_types: device_types_t = None, + schema: str | None = None, + tags: tags_t = None, +) -> "CustomOpDef": ... + + +@exposed_in("torch.library") +def custom_op( + name: str, + fn: Callable | None = None, + /, + *, + mutates_args: str | Iterable[str], + device_types: device_types_t = None, + schema: str | None = None, + tags: tags_t = None, +) -> Union[Callable[[Callable[..., object]], "CustomOpDef"], "CustomOpDef"]: + """Wraps a function into custom operator. + + Reasons why you may want to create a custom op include: + - Wrapping a third-party library or custom kernel to work with PyTorch + subsystems like Autograd. + - Preventing torch.compile/export/FX tracing from peeking inside your function. + + This API is used as a decorator around a function (please see examples). + The provided function must have type hints; these are needed to interface + with PyTorch's various subsystems. + + Args: + name (str): A name for the custom op that looks like "{namespace}::{name}", + e.g. "mylib::my_linear". The name is used as the op's stable identifier + in PyTorch subsystems (e.g. torch.export, FX graphs). + To avoid name collisions, please use your project name as the namespace; + e.g. all custom ops in pytorch/fbgemm use "fbgemm" as the namespace. + mutates_args (Iterable[str] or "unknown"): The names of args that the function mutates. + This MUST be accurate, otherwise, the behavior is undefined. If "unknown", + it pessimistically assumes that all inputs to the operator are being mutated. + device_types (str | None | Sequence[str]): The device type(s) the function + is valid for. If no device type is provided, then the function + is used as the default implementation for all device types. + Examples: "cpu", "cuda". + When registering a device-specific implementation for an operator that accepts no Tensors, + we require the operator to have a "device: torch.device argument". + schema (str | None): A schema string for the operator. If None + (recommended) we'll infer a schema for the operator from its type + annotations. We recommend letting us infer a schema unless you + have a specific reason not to. + Example: "(Tensor x, int y) -> (Tensor, Tensor)". + tags (Tag | Sequence[Tag] | None): one or more tags to apply to the + operator. Use ``torch.Tag.inplace`` for operators that mutate their + first Tensor argument and return it. Use ``torch.Tag.out`` for + operators that mutate keyword-only output tensors and return them. + Like PyTorch's built-in ``out=`` operators, ``torch.Tag.out`` + custom ops do not support autograd. + + The following types are supported for the wrapped function's input parameters: + + - Scalars: ``int``, ``float``, ``bool``, ``str``, ``torch.types.Number`` + - Tensors: ``torch.Tensor`` + - Enums/devices: ``torch.dtype``, ``torch.device`` + - Flat list of the same type: ``list[torch.Tensor]``, + ``list[int]``, ``list[float]``, ``list[bool]``, + ``list[torch.types.Number]`` + - Optionals: ``Optional`` of any of the above scalar/tensor types + - Types registered via :func:`torch.library.register_custom_class` + + The following types are supported for the return value: + + ``torch.Tensor``, ``list[torch.Tensor]``, ``int``, ``float``, + ``bool``, ``torch.types.Number``. + + .. note:: + We recommend not passing in a ``schema`` arg and instead letting us infer + it from the type annotations. It is error-prone to write your own schema. + You may wish to provide your own schema if our interpretation of + the type annotation is not what you want. + For more info on how to write a schema string, see + `here `_ + + Examples:: + >>> import torch + >>> from torch import Tensor + >>> from torch.library import custom_op + >>> import numpy as np + >>> + >>> @custom_op("mylib::numpy_sin", mutates_args=()) + >>> def numpy_sin(x: Tensor) -> Tensor: + >>> x_np = x.cpu().numpy() + >>> y_np = np.sin(x_np) + >>> return torch.from_numpy(y_np).to(device=x.device) + >>> + >>> x = torch.randn(3) + >>> y = numpy_sin(x) + >>> assert torch.allclose(y, x.sin()) + >>> + >>> # Example of a custom op that only works for one device type. + >>> @custom_op("mylib::numpy_sin_cpu", mutates_args=(), device_types="cpu") + >>> def numpy_sin_cpu(x: Tensor) -> Tensor: + >>> x_np = x.numpy() + >>> y_np = np.sin(x_np) + >>> return torch.from_numpy(y_np) + >>> + >>> x = torch.randn(3) + >>> y = numpy_sin_cpu(x) + >>> assert torch.allclose(y, x.sin()) + >>> + >>> # Example of a custom op that mutates an input + >>> @custom_op("mylib::numpy_sin_inplace", mutates_args={"x"}, device_types="cpu") + >>> def numpy_sin_inplace(x: Tensor) -> None: + >>> x_np = x.numpy() + >>> np.sin(x_np, out=x_np) + >>> + >>> x = torch.randn(3) + >>> expected = x.sin() + >>> numpy_sin_inplace(x) + >>> assert torch.allclose(x, expected) + >>> + >>> # Example of a custom op with inplace semantics + >>> @custom_op( + >>> "mylib::numpy_sin_", + >>> mutates_args={"x"}, + >>> device_types="cpu", + >>> tags=torch.Tag.inplace, + >>> ) + >>> def numpy_sin_(x: Tensor) -> Tensor: + >>> x_np = x.numpy() + >>> np.sin(x_np, out=x_np) + >>> return x + >>> + >>> x = torch.randn(3) + >>> expected = x.sin() + >>> result = numpy_sin_(x) + >>> assert result is x + >>> assert torch.allclose(x, expected) + >>> + >>> # Example of a custom op with out= semantics + >>> @custom_op( + >>> "mylib::numpy_sin_out", + >>> mutates_args={"out"}, + >>> device_types="cpu", + >>> tags=torch.Tag.out, + >>> ) + >>> def numpy_sin_out(x: Tensor, *, out: Tensor) -> Tensor: + >>> x_np = x.numpy() + >>> out_np = out.numpy() + >>> np.sin(x_np, out=out_np) + >>> return out + >>> + >>> x = torch.randn(3) + >>> out = torch.empty_like(x) + >>> result = numpy_sin_out(x, out=out) + >>> assert result is out + >>> assert torch.allclose(out, x.sin()) + >>> + >>> # Example of a factory function + >>> @torch.library.custom_op("mylib::bar", mutates_args={}, device_types="cpu") + >>> def bar(device: torch.device) -> Tensor: + >>> return torch.ones(3) + >>> + >>> bar("cpu") + >>> + >>> # Example of a custom op with list inputs + >>> @custom_op("mylib::weighted_sum", mutates_args=()) + >>> def weighted_sum( + >>> tensors: list[Tensor], + >>> weights: list[float], + >>> ) -> Tensor: + >>> return sum(t * w for t, w in zip(tensors, weights)) + >>> + >>> x = torch.randn(3) + >>> y = torch.randn(3) + >>> out = weighted_sum([x, y], [0.3, 0.7]) + + """ + + def inner(fn: Callable[..., object]) -> CustomOpDef: + import torch + + normalized_tags = _normalize_tags(tags) + if schema is None: + schema_str = torch.library.infer_schema( + fn, + mutates_args=mutates_args, + tags=normalized_tags, + ) + else: + schema_str = schema + + namespace, opname = name.split("::") + result = CustomOpDef(namespace, opname, schema_str, fn, normalized_tags) + if schema is not None: + # Check that schema's alias annotations match those of `mutates_args`. + expected = set() + for arg in result._opoverload._schema.arguments: + if arg.alias_info is not None and arg.alias_info.is_write: + expected.add(arg.name) + if expected != set(mutates_args): + raise ValueError( + f"Attempted to create a custom op with `mutates_args={mutates_args}` " + f"and `schema={schema}. The schema suggests that the op mutates {expected}" + f"which is different from what was provided to us in `mutates_args`. " + f"Please make these consistent." + ) + result.register_kernel(device_types)(fn) + result._opoverload._enable_pyobj_dispatch(True) + return result + + if fn is None: + return inner + return inner(fn) + + +class CustomOpDef: + """CustomOpDef is a wrapper around a function that turns it into a custom op. + + It has various methods for registering additional behavior for this + custom op. + + You should not instantiate CustomOpDef directly; instead, use the + :func:`torch.library.custom_op` API. + """ + + def __init__( + self, + namespace: str, + name: str, + schema: str, + fn: Callable, + tags: tags_t = None, + ) -> None: + # Fields used to interface with the PyTorch dispatcher + self._namespace = namespace + self._name = name + self._schema = schema + self._tags = _normalize_tags(tags) + + self._init_fn = fn + + self._backend_fns: dict[str | None, Callable] = {} + self._abstract_fn: Callable | None = None + self._setup_context_fn: Callable | None = None + self._backward_fn: Callable | None = None + self._torch_dispatch_fns: dict[type, Callable] = {} + self._vmap_fn: Callable | None = None + self._autocast_dtype: dict[str, _dtype | None] = {} + self._is_inplace = False + self._is_out = False + self._out_kwarg_names: tuple[str, ...] = () + + self._lib = get_library_allowing_overwrite(self._namespace, self._name) + self._register_to_dispatcher(self._tags) + self._disabled_kernel: set = set() + self._used_triton_kernels: list[Any] = list() + OPDEFS[self._qualname] = self + + @property + def _qualname(self) -> str: + return f"{self._namespace}::{self._name}" + + def __repr__(self) -> str: + return f"" + + @contextmanager + def set_kernel_enabled(self, device_type: str, enabled: bool = True): + """ + Disable or re-enable an already registered kernel for this custom operator. + + If the kernel is already disabled/enabled, this is a no-op. + + Note: + If a kernel is first disabled and then registered, it is disabled until enabled again. + + Args: + device_type (str): The device type to disable/enable the kernel for. + disable (bool): Whether to disable or enable the kernel. + + Example: + >>> inp = torch.randn(1) + >>> + >>> # define custom op `f`. + >>> @custom_op("mylib::f", mutates_args=()) + >>> def f(x: Tensor) -> Tensor: + >>> return torch.zeros(1) + >>> + >>> print(f(inp)) # tensor([0.]), default kernel + >>> + >>> @f.register_kernel("cpu") + >>> def _(x): + >>> return torch.ones(1) + >>> + >>> print(f(inp)) # tensor([1.]), CPU kernel + >>> + >>> # temporarily disable the CPU kernel + >>> with f.set_kernel_enabled("cpu", enabled = False): + >>> print(f(inp)) # tensor([0.]) with CPU kernel disabled + + """ + action = "enable" if enabled else "disable" + originally_disabled = device_type in self._disabled_kernel + if device_type not in self._backend_fns: + log.warning( + "Attempted to %s kernel for %s but no kernel was registered for this device type.", + action, + device_type, + ) + + if not enabled: + if originally_disabled: + log.warning( + "Attempted to disable kernel for %s but it was already disabled.", + device_type, + ) + else: + self._disabled_kernel.add(device_type) + else: # enable the kernel + if not originally_disabled: + log.warning( + "Attempted to enable kernel for %s but it was already enabled.", + device_type, + ) + else: + self._disabled_kernel.remove(device_type) + + try: + yield + finally: + # restore original state + if originally_disabled: + self._disabled_kernel.add(device_type) + else: + self._disabled_kernel.discard(device_type) + + def register_kernel( + self, device_types: device_types_t, fn: Callable | None = None, / + ) -> Callable: + """Register an implementation for a device type for this operator. + + Some valid device_types are: "cpu", "cuda", "xla", "mps", "ipu", "xpu". + This API may be used as a decorator. + + Args: + fn (Callable): The function to register as the implementation for + the given device types. + device_types (str | Sequence[str]): The device device_types to register an impl to. + + Examples:: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> import torch + >>> from torch import Tensor + >>> from torch.library import custom_op + >>> import numpy as np + >>> + >>> # Create a custom op that works on cpu + >>> @custom_op("mylib::numpy_sin", mutates_args=(), device_types="cpu") + >>> def numpy_sin(x: Tensor) -> Tensor: + >>> x_np = x.numpy() + >>> y_np = np.sin(x_np) + >>> return torch.from_numpy(y_np) + >>> + >>> # Add implementations for the cuda device + >>> @numpy_sin.register_kernel("cuda") + >>> def _(x): + >>> x_np = x.cpu().numpy() + >>> y_np = np.sin(x_np) + >>> return torch.from_numpy(y_np).to(device=x.device) + >>> + >>> x_cpu = torch.randn(3) + >>> x_cuda = x_cpu.cuda() + >>> assert torch.allclose(numpy_sin(x_cpu), x_cpu.sin()) + >>> assert torch.allclose(numpy_sin(x_cuda), x_cuda.sin()) + + """ + + def inner(fn): + if device_types is None or isinstance(device_types, str): + dtypes: list[str | None] = [device_types] + else: + dtypes = list(device_types) + for device_type in dtypes: + if device_type not in self._backend_fns: + + def backend_impl(*args, **kwargs): + result = self._backend_fns[device_type](*args, **kwargs) + + def get_module(): + fn = self._backend_fns[device_type] + return inspect.getmodule(fn) + + schema = self._opoverload._schema + if self._is_inplace: + if result is not args[0]: + raise RuntimeError( + f"{self._name} (with implementation in {get_module()}): " + "An operator tagged with torch.Tag.inplace must " + "return its first argument." + ) + elif self._is_out: + out_kwarg_names = self._out_kwarg_names + if len(out_kwarg_names) == 1: + returns_out_args = result is kwargs[out_kwarg_names[0]] + else: + returns_out_args = ( + isinstance(result, tuple) + and len(result) == len(out_kwarg_names) + and all( + result[i] is kwargs[name] + for i, name in enumerate(out_kwarg_names) + ) + ) + if not returns_out_args: + raise RuntimeError( + f"{self._name} (with implementation in {get_module()}): " + "An operator tagged with torch.Tag.out must " + "return its mutable keyword-only arguments." + ) + elif not schema._is_view_op(): + utils._c_check_aliasing_constraint( + self._name, + args, + kwargs, + result, + get_module, + ) + return result + + if device_type is None: + self._lib.impl( + self._name, backend_impl, "CompositeExplicitAutograd" + ) + else: + self._lib.impl( + self._name, + backend_impl, + _C._dispatch_key_for_device(device_type), + ) + + # Wrap function to choose between the default implementation or the device-specific + # implementation depending on if the kernel is disabled. + @torch._disable_dynamo + def wrapped_fn(*args, **kwargs): + if device_type in self._disabled_kernel: + return self._init_fn(*args, **kwargs) + else: + return fn(*args, **kwargs) + + self._backend_fns[device_type] = wrapped_fn + return fn + + if device_types is not None and not utils.has_tensor_arg( + self._opoverload._schema + ): + device_arg_index = utils.get_device_arg_index(self._opoverload._schema) + if device_arg_index is None: + raise ValueError( + "Functions without tensor inputs are required to have a `device: torch.device` argument" + ) + self._register_backend_select_dispatcher(device_arg_index) + + # See NOTE: [Supporting decorator and non-decorator usage] + if fn is None: + return inner + return inner(fn) + + def register_fake(self, fn: Callable, /) -> Callable: + r"""Register a FakeTensor implementation for this custom op. + + This is necessary to get the operator to work efficiently with torch.compile. + + The Fake impl (sometimes also known as a meta kernel or abstract impl) + specifies the behavior of this operator on Tensors that carry no data. + Given some input Tensors with certain properties + (sizes/strides/storage_offset/device), it specifies what the properties of + the output Tensors are. + + Please see :func:`torch.library.register_fake` for more details. + + Args: + fn (Callable): The function to register as the FakeTensor + implementation. + + Examples: + >>> import torch + >>> import numpy as np + >>> from torch import Tensor + >>> + >>> # Example 1: an operator without data-dependent output shape + >>> @torch.library.custom_op("mylib::linear", mutates_args=()) + >>> def linear(x: Tensor, weight: Tensor, bias: Tensor) -> Tensor: + >>> return (x @ weight.t()) + bias + >>> + >>> @linear.register_fake + >>> def _(x, weight, bias): + >>> assert x.dim() == 2 + >>> assert weight.dim() == 2 + >>> assert bias.dim() == 1 + >>> assert x.shape[1] == weight.shape[1] + >>> assert weight.shape[0] == bias.shape[0] + >>> assert x.device == weight.device + >>> return x.new_empty(x.size(0), weight.size(0)) + >>> + >>> x = torch.randn(2, 2) + >>> weight = torch.randn(2, 2) + >>> bias = torch.randn(2) + >>> # xdoctest: +SKIP("Requires Python <= 3.11") + >>> out = torch.compile(linear, fullgraph=True)(x, weight, bias) + >>> # xdoctest: +SKIP("Requires Python <= 3.11") + >>> assert torch.allclose(out, torch.nn.functional.linear(x, weight, bias)) + >>> + >>> # Example 2: an operator with data-dependent output shape + >>> @torch.library.custom_op("mylib::nonzero", mutates_args=()) + >>> def nonzero(x: Tensor) -> Tensor: + >>> x_np = x.cpu().numpy() + >>> res = np.stack(np.nonzero(x_np), axis=1) + >>> return torch.tensor(res, device=x.device) + >>> + >>> @nonzero.register_fake + >>> def _(x): + >>> # Number of nonzero-elements is data-dependent. + >>> # Since we cannot peek at the data in an abstract impl, + >>> # we use the ctx object to construct a new symint that + >>> # represents the data-dependent size. + >>> ctx = torch.library.get_ctx() + >>> nnz = ctx.new_dynamic_size() + >>> shape = [nnz, x.dim()] + >>> result = x.new_empty(shape, dtype=torch.int64) + >>> return result + >>> + >>> x = torch.tensor([0, 1, 2, 0, 0, 1]) + >>> # xdoctest: +SKIP("Requires Python <= 3.11") + >>> out = torch.compile(nonzero, fullgraph=True)(x) + >>> # xdoctest: +SKIP("Requires Python <= 3.11") + >>> assert torch.allclose(out, x.nonzero()) + + """ + if self._is_inplace or self._is_out: + tag = "torch.Tag.inplace" if self._is_inplace else "torch.Tag.out" + warnings.warn( + f"The fake registration for {self} is unnecessary. Custom ops " + f"tagged with {tag} already get an autogenerated fake kernel. " + "The provided fake impl will be used instead.", + stacklevel=2, + ) + self._abstract_fn = fn + return fn + + def register_effect(self, effect: EffectType | None) -> None: + self._lib._register_effectful_op(self._qualname, effect) + + def register_torch_dispatch( + self, torch_dispatch_class: Any, fn: Callable | None = None, / + ) -> Callable: + r"""Registers a torch_dispatch rule for the given operator and ``torch_dispatch_class``. + + This allows for open registration to specify the behavior between the operator + and the ``torch_dispatch_class`` without needing to modify the ``torch_dispatch_class`` + or the operator directly. + + Please see :func:`torch.library.register_torch_dispatch` for examples and more details. + """ + + def register(fn): + if torch_dispatch_class not in self._torch_dispatch_fns: + + def inner(*args, **kwargs): + return self._torch_dispatch_fns[torch_dispatch_class]( + *args, **kwargs + ) + + self._lib._register_torch_dispatch_rule( + self._name, torch_dispatch_class, inner + ) + self._torch_dispatch_fns[torch_dispatch_class] = fn + return fn + + if fn is None: + return register + else: + return register(fn) + + def register_autograd( + self, + backward: Callable, + /, + *, + setup_context: Callable | None = None, + ) -> None: + r"""Register a backward formula for this custom op. + + In order for an operator to work with autograd, you need to register + a backward formula: + 1. You must tell us how to compute gradients during the backward pass + by providing us a "backward" function. + 2. If you need any values from the forward to compute gradients, you can + use `setup_context` to save values for backward. + + ``backward_fn`` runs during the backward pass. It accepts ``(ctx, *grads)``: + - ``grads`` is one or more gradients. The number of gradients matches + the number of outputs of the operator. + The ``ctx`` object is `the same ctx object `_ used by + :class:`torch.autograd.Function`. The semantics of ``backward_fn`` are the + same as :meth:`torch.autograd.Function.backward`. + + ``setup_context(ctx, inputs, output)`` runs during the forward pass. + Please save quantities needed for backward onto the ``ctx`` object via + either :meth:`torch.autograd.function.FunctionCtx.save_for_backward` + or assigning them as attributes of ``ctx``. If your custom op has + kwarg-only arguments, we expect the signature of ``setup_context`` + to be ``setup_context(ctx, inputs, keyword_only_inputs, output)``. + + Both ``setup_context_fn`` and ``backward_fn`` must be traceable. That is, + they may not directly access :meth:`torch.Tensor.data_ptr` and they must + not depend on or mutate global state. If you need a non-traceable backward, + you can make it a separate custom_op that you call inside ``backward_fn``. + + If you need different autograd behavior on different devices, then we + recommend creating two different custom operators, one for each device + that needs different behavior, and switching between them at runtime. + + Examples: + >>> import torch + >>> import numpy as np + >>> from torch import Tensor + >>> + >>> @torch.library.custom_op("mylib::numpy_sin", mutates_args=()) + >>> def numpy_sin(x: Tensor) -> Tensor: + >>> x_np = x.cpu().numpy() + >>> y_np = np.sin(x_np) + >>> return torch.from_numpy(y_np).to(device=x.device) + >>> + >>> def setup_context(ctx, inputs, output) -> Tensor: + >>> x, = inputs + >>> ctx.save_for_backward(x) + >>> + >>> def backward(ctx, grad): + >>> x, = ctx.saved_tensors + >>> return grad * x.cos() + >>> + >>> numpy_sin.register_autograd(backward, setup_context=setup_context) + >>> + >>> x = torch.randn(3, requires_grad=True) + >>> y = numpy_sin(x) + >>> (grad_x,) = torch.autograd.grad(y, x, torch.ones_like(y)) + >>> assert torch.allclose(grad_x, x.cos()) + >>> + >>> # Example with a keyword-only arg + >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=()) + >>> def numpy_mul(x: Tensor, *, val: float) -> Tensor: + >>> x_np = x.cpu().numpy() + >>> y_np = x_np * val + >>> return torch.from_numpy(y_np).to(device=x.device) + >>> + >>> def setup_context(ctx, inputs, keyword_only_inputs, output) -> Tensor: + >>> ctx.val = keyword_only_inputs["val"] + >>> + >>> def backward(ctx, grad): + >>> return grad * ctx.val + >>> + >>> numpy_mul.register_autograd(backward, setup_context=setup_context) + >>> + >>> x = torch.randn(3, requires_grad=True) + >>> y = numpy_mul(x, val=3.14) + >>> (grad_x,) = torch.autograd.grad(y, x, torch.ones_like(y)) + >>> assert torch.allclose(grad_x, torch.full_like(x, 3.14)) + + """ + schema = self._opoverload._schema + if utils.is_out(self._opoverload): + raise RuntimeError( + f"Cannot register autograd formula for operator tagged with " + f"torch.Tag.out: {self}. Out variants do not support autograd." + ) + if not utils.is_functional_schema(schema, allow_valid_view=True): + raise RuntimeError( + f"Cannot register autograd formula for non-functional operator " + f"{self} with schema {schema}. Please create " + f"a functional operator and register an autograd formula for that." + ) + + self._backward_fn = backward + self._setup_context_fn = setup_context + + def _register_to_dispatcher(self, tags: Sequence[_C.Tag]) -> None: + schema_str = self._name + self._schema + cpp_schema = _C.parse_schema(schema_str) + self._validate_schema(cpp_schema, schema_str) + self._define_dispatcher_op(schema_str, tags) + self._is_inplace = utils.is_inplace(self._opoverload) + self._is_out = utils.is_out(self._opoverload) + if self._is_out: + _, out_kwarg_names = utils.mutated_args_kwargs(self._opoverload._schema) + self._out_kwarg_names = tuple(out_kwarg_names) + self._register_fake_dispatcher_impl() + self._register_autograd_dispatcher_impl() + self._register_adinplaceorview_dispatcher_impl() + + def _validate_schema(self, schema: _C.FunctionSchema, schema_str: str) -> None: + if utils.has_kwarg_only_tensors(schema) and torch.Tag.out not in self._tags: + # If you want to support this, the progression is: + # - supporting kwarg-only Tensors that are non-differentiable + # - supporting kwarg-only Tensors (regardless of differentiability) + raise NotImplementedError( + f"custom_op with kwarg-only Tensor args. Please make your " + f"tensors not kwarg-only. Got: {schema_str}" + ) + + def _define_dispatcher_op(self, schema_str: str, tags: Sequence[_C.Tag]) -> None: + self._lib.define( + schema_str, + tags=_with_pt2_compliant_tag(tags), + ) + self._opoverload = utils.lookup_op(self._qualname) + + def _register_fake_dispatcher_impl(self) -> None: + def fake_impl(*args, **kwargs): + if self._abstract_fn is None: + if utils.can_generate_trivial_fake_impl(self._opoverload): + return utils.generate_trivial_fake_impl( + self._opoverload, *args, **kwargs + ) + raise RuntimeError( + f"There was no fake impl registered for {self}. " + f"This is necessary for torch.compile/export/fx tracing to work. " + f"Please use `{self._init_fn.__name__}.register_fake` to add an " + f"fake impl." + ) + return self._abstract_fn(*args, **kwargs) + + self._lib._register_fake(self._name, fake_impl, _stacklevel=5) + + def _register_autograd_dispatcher_impl(self) -> None: + autograd_impl = autograd.make_autograd_impl(self._opoverload, self) + self._lib.impl(self._name, autograd_impl, "Autograd", with_keyset=True) + + def _register_adinplaceorview_dispatcher_impl(self) -> None: + schema = self._opoverload._schema + if not (schema._is_view_op() or schema.is_mutable): + return + + self._lib.m.register_ad_inplace_or_view_fallback(self._name) # type: ignore[union-attr] + + if schema.is_mutable: + self._register_mutation_version_bump(schema) + + def _register_mutation_version_bump(self, schema: _C.FunctionSchema) -> None: + mutated_idxs, mutated_keys = utils.mutated_args_kwargs(schema) + + is_view = schema._is_view_op() + if is_view: + original_kernel = torch._C._dispatch_get_computed_kernel_for_dispatch_key( + f"{self._lib.ns}::{self._name}", "ADInplaceOrView" + ) + else: + op = self._opoverload + after_ADInplaceOrView_keyset = _C._after_ADInplaceOrView_keyset + + def adinplaceorview_impl(keyset, *args, **kwargs): + # The dispatcher normalizes non-keyword-only arguments into args. + # Avoid filling defaults for every schema argument on this hot path. + for idx in mutated_idxs: + if idx < len(args): + increment_version(args[idx]) + for key in mutated_keys: + if key in kwargs: + increment_version(kwargs[key]) + if is_view: + # View ops need the C++ fallback for aliasing tracking + return original_kernel.call_boxed(keyset, *args, **kwargs) + # Non-view mutable ops: increment_version is sufficient, + # redispatch directly past ADInplaceOrView to the backend. + return op.redispatch(keyset & after_ADInplaceOrView_keyset, *args, **kwargs) + + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message="Warning only once for all operators", + category=UserWarning, + ) + self._lib.impl( + self._name, + adinplaceorview_impl, + "ADInplaceOrView", + with_keyset=True, + ) + + def _register_backend_select_dispatcher(self, device_arg_index: int): + """ + Switch on the device argument to select the correct backend to dispatch to. + """ + + def backend_select(keyset, *args, **kwargs): + device = args[device_arg_index].type + if device not in self._backend_fns: + raise RuntimeError( + f"{self._name} does not have a kernel registered for {device}. " + "Please use register_kernel to do so." + ) + # pyrefly: ignore [bad-argument-type] + dispatch_key = _C._dispatch_key_for_device(device) + dispatch_key = getattr(_C.DispatchKey, dispatch_key) + return self._opoverload.redispatch( + _C.DispatchKeySet(dispatch_key), *args, **kwargs + ) + + self._lib.impl(self._name, backend_select, "BackendSelect", with_keyset=True) + + def __call__(self, *args, **kwargs): + return self._opoverload(*args, **kwargs) + + def register_vmap( + self, + func: Callable | None = None, + ): + r"""Register a vmap implementation to support :func:`torch.vmap` for this custom op. + + This API may be used as a decorator. + + In order for an operator to work with :func:`torch.vmap`, you may need to register a + vmap implementation in the following signature: + + ``vmap_func(info, in_dims: Tuple[Optional[int]], *args, **kwargs)``, + + where ``*args`` and ``**kwargs`` are the arguments and kwargs for ``op``. + + It specifies how do we compute the batched version of ``op`` given inputs with an additional + dimension (specified by ``in_dims``). + + For each arg in ``args``, ``in_dims`` has a corresponding ``Optional[int]``. It is ``None`` + if the arg is not a Tensor or if the arg is not being vmapped over, otherwise, it is an integer + specifying what dimension of the Tensor is being vmapped over. + + ``info`` is a collection of additional metadata that may be helpful: + ``info.batch_size`` specifies the size of the dimension being vmapped over, while + ``info.randomness`` is the ``randomness`` option that was passed to :func:`torch.vmap`. + + The return of the function ``func`` is a tuple of ``(output, out_dims)``. Similar to ``in_dims``, + ``out_dims`` should be of the same structure as ``output`` and contain one ``out_dim`` + per output that specifies if the output has the vmapped dimension and what index it is in. + + Examples: + >>> import torch + >>> import numpy as np + >>> from torch import Tensor + >>> from typing import Tuple + >>> + >>> def to_numpy(tensor): + >>> return tensor.cpu().numpy() + >>> + >>> lib = torch.library.Library("mylib", "FRAGMENT") + >>> @torch.library.custom_op("mylib::numpy_cube", mutates_args=()) + >>> def numpy_cube(x: Tensor) -> Tuple[Tensor, Tensor]: + >>> x_np = to_numpy(x) + >>> dx = torch.tensor(3 * x_np ** 2, device=x.device) + >>> return torch.tensor(x_np ** 3, device=x.device), dx + >>> + >>> def numpy_cube_vmap(info, in_dims, x): + >>> result = numpy_cube(x) + >>> return result, (in_dims[0], in_dims[0]) + >>> + >>> numpy_cube.register_vmap(numpy_cube_vmap) + >>> + >>> x = torch.randn(3) + >>> torch.vmap(numpy_cube)(x) + >>> + >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=()) + >>> def numpy_mul(x: Tensor, y: Tensor) -> Tensor: + >>> return torch.tensor(to_numpy(x) * to_numpy(y), device=x.device) + >>> + >>> @numpy_mul.register_vmap + >>> def numpy_mul_vmap(info, in_dims, x, y): + >>> x_bdim, y_bdim = in_dims + >>> x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1) + >>> y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1) + >>> result = x * y + >>> result = result.movedim(-1, 0) + >>> return result, 0 + >>> + >>> + >>> x = torch.randn(3) + >>> y = torch.randn(3) + >>> torch.vmap(numpy_mul)(x, y) + """ + from torch._functorch.autograd_function import custom_function_call_vmap_helper + from torch._functorch.pyfunctorch import retrieve_current_functorch_interpreter + + def register(func): + need_register = self._vmap_fn is None + self._vmap_fn = func + + if need_register: + + def wrapped_func(keyset, *args, **kwargs): + interpreter = retrieve_current_functorch_interpreter() + return custom_function_call_vmap_helper( + # pyrefly: ignore[bad-argument-type] + interpreter, + # pyrefly: ignore[bad-argument-type] + self._vmap_fn, + self._opoverload, + *args, + **kwargs, + ) + + self._lib.impl( + self._name, wrapped_func, "FuncTorchBatched", with_keyset=True + ) + + if func is None: + return register + else: + return register(func) + + def register_autocast( + self, + device_type: str, + cast_inputs: _dtype, + ): + r"""Register an autocast dispatch rule for this custom op. + + Valid ``device_type`` values include any device type that supports autocast. + See :func:`torch.amp.is_autocast_available` for details. + + Args: + op (str | OpOverload): The operator to register an autocast dispatch rule to. + device_type(str): Device type to use. 'cuda', 'cpu', 'xpu', or any other device type that supports autocast. + The type is the same as the `type` attribute of a :class:`torch.device`. + Thus, you may obtain the device type of a tensor using `Tensor.device.type`. + cast_inputs (:class:`torch.dtype`): When custom op runs in an autocast-enabled region, + casts incoming floating-point Tensors to the target dtype (non-floating-point Tensors + are not affected), then executes custom op with autocast disabled. + lib (Optional[Library]): If provided, the lifetime of this registration + + Examples:: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> import torch + >>> from torch import Tensor + >>> from torch.library import custom_op + >>> + >>> # Create a custom op that works on cuda + >>> @torch.library.custom_op("mylib::my_sin", mutates_args=()) + >>> def my_sin(x: Tensor) -> Tensor: + >>> return torch.sin(x) + >>> + >>> # Register autocast dispatch rule for the cuda device + >>> torch.library.register_autocast("mylib::my_sin", "cuda", torch.float16) + >>> + >>> x = torch.randn(3, dtype=torch.float32, device="cuda") + >>> with torch.autocast("cuda", dtype=torch.float16): + >>> y = torch.ops.mylib.my_sin(x) + >>> assert y.dtype == torch.float16 + + """ + if not isinstance(device_type, str): + raise ValueError( + f"Expected `device_type` of type `str`, got: `{type(device_type)}`" + ) + if not torch._C._is_autocast_available(device_type): + raise ValueError(f"Device type '{device_type}' does not support autocast.") + + need_register = self._autocast_dtype.get(device_type) is None + if need_register: + self._autocast_dtype[device_type] = cast_inputs + autocast_key = "Autocast" + torch._C._dispatch_key_for_device(device_type) + autocast_dispatch_key = getattr(torch._C.DispatchKey, autocast_key) + + def kernel(_, *args, **kwargs): + if len(kwargs) != 0: + raise AssertionError( + f"Custom ops do not support kwargs yet, got {list(kwargs.keys())}" + ) + with torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(autocast_dispatch_key) + ): + return self._opoverload(*_cast(args, device_type, cast_inputs)) + + if need_register: + self._lib.impl(self._name, kernel, autocast_key, with_keyset=True) + + return kernel + + +# TODO: Merge this function with torch.amp.autocast_mode._cast, and refactor it +# into a utility function once custom ops support arbitrary input types. +def _cast(value, device_type: str, dtype: _dtype): + if isinstance(value, torch.Tensor): + is_eligible = ( + value.is_floating_point() + and value.device.type == device_type + and (value.dtype is not torch.float64) + ) + return value.to(dtype) if is_eligible else value + elif isinstance(value, (str, bytes)): + return value + elif isinstance(value, collections.abc.Iterable): + iterable = (_cast(v, device_type, dtype) for v in value) + if isinstance(value, (list, tuple)): + return type(value)(iterable) + else: + return iterable + else: + return value + + +def increment_version(val: Any) -> None: + if isinstance(val, Tensor): + torch.autograd.graph.increment_version(val) + elif isinstance(val, (tuple, list)): + for v in val: + if isinstance(v, Tensor): + torch.autograd.graph.increment_version(v) + + +# NOTE: [Supporting decorator and non-decorator usage] +# +# Some APIs may be both used as a decorator and not as a decorator. +# For example: +# +# >>> def fn(x): +# >>> return x.sin() +# >>> +# >>> # Usage 1: not as a decorator +# >>> numpy_sin.register_kernel("cuda", fn) +# >>> +# >>> # Usage 2: as a decorator +# >>> @numpy_sin.register_kernel("cuda") +# >>> def fn2(x): +# >>> return x.sin +# +# The way we support this is that `register_kernel` accepts an optional `fn`. +# If `fn` is provided (Usage 1), then we know that the user is using it not +# as a decorator. +# If `fn` is not provided (Usage 2), then `register_kernel` needs to return a +# decorator. + + +OPDEF_TO_LIB: dict[str, "torch.library.Library"] = {} +OPDEFS: weakref.WeakValueDictionary = weakref.WeakValueDictionary() + + +def get_library_allowing_overwrite( + namespace: str, name: str +) -> "torch.library.Library": + qualname = f"{namespace}::{name}" + + if qualname in OPDEF_TO_LIB: + OPDEF_TO_LIB[qualname]._destroy() + del OPDEF_TO_LIB[qualname] + + lib = torch.library.Library(namespace, "FRAGMENT") + OPDEF_TO_LIB[qualname] = lib + return lib + + +def _maybe_get_opdef( + op: CustomOpDef | _ops.OpOverload | str, +) -> CustomOpDef | None: + if isinstance(op, CustomOpDef): + return op + if isinstance(op, _ops.OpOverload): + op = op._name + if not isinstance(op, str): + raise AssertionError(f"op must be str, got {type(op)}") + if op in OPDEFS: + return OPDEFS[op] + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_library/effects.py b/.venv/lib/python3.12/site-packages/torch/_library/effects.py new file mode 100644 index 0000000000000000000000000000000000000000..2e9a8fe4109a22dfac9abb971dbe8c486fbcd0b0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/effects.py @@ -0,0 +1,84 @@ +from enum import Enum + +import torch + + +class EffectType(Enum): + ORDERED = "Ordered" + + +from torch._library.utils import RegistrationHandle + + +# These classes do not have side effects as they just store quantization +# params, so we don't need to mark them as ordered +skip_classes = ( + "__torch__.torch.classes.quantized.Conv2dPackedParamsBase", + "__torch__.torch.classes.quantized.Conv3dPackedParamsBase", + "__torch__.torch.classes.quantized.EmbeddingPackedParamsBase", + "__torch__.torch.classes.quantized.LinearPackedParamsBase", + "__torch__.torch.classes.xnnpack.Conv2dOpContext", + "__torch__.torch.classes.xnnpack.LinearOpContext", + "__torch__.torch.classes.xnnpack.TransposeConv2dOpContext", +) + + +class EffectHolder: + """A holder where one can register an effect impl to.""" + + def __init__(self, qualname: str): + self.qualname: str = qualname + self._set_default_effect() + + def _set_default_effect(self) -> None: + self._effect: EffectType | None = None + + # If the op contains a ScriptObject input, we want to mark it as having effects + namespace, opname = torch._library.utils.parse_namespace(self.qualname) + split = opname.split(".") + if len(split) > 1: + if len(split) != 2: + raise AssertionError( + f"Tried to split {opname} based on '.' but found more than 1 '.'" + ) + opname, overload = split + else: + overload = "" + + if namespace == "higher_order": + return + + opname = f"{namespace}::{opname}" + if torch._C._get_operation_overload(opname, overload) is not None: + # Since we call this when destroying the library, sometimes the + # schema will be gone already at that time. + schema = torch._C._get_schema(opname, overload) + for arg in schema.arguments: + if isinstance(arg.type, torch.ClassType): + type_str = arg.type.str() # pyrefly: ignore[missing-attribute] + if type_str in skip_classes: + continue + self._effect = EffectType.ORDERED + return + + @property + def effect(self) -> EffectType | None: + return self._effect + + @effect.setter + def effect(self, _): + raise RuntimeError("Unable to directly set kernel.") + + def register(self, effect: EffectType | None) -> RegistrationHandle: + """Register an effect + + Returns a RegistrationHandle that one can use to de-register this + effect. + """ + self._effect = effect + + def deregister_effect(): + self._set_default_effect() + + handle = RegistrationHandle(deregister_effect) + return handle diff --git a/.venv/lib/python3.12/site-packages/torch/_library/fake_class_registry.py b/.venv/lib/python3.12/site-packages/torch/_library/fake_class_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..a22ed9e00518b067dc1c047082c99170998854bc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/fake_class_registry.py @@ -0,0 +1,510 @@ +# mypy: allow-untyped-defs +import copy +import logging +from typing import Any, Protocol + +import torch +from torch._library.utils import parse_namespace +from torch.utils._python_dispatch import _disable_current_modes + + +log = logging.getLogger(__name__) + + +class FakeScriptObject: + def __init__( + self, wrapped_obj: Any, script_class_name: str, x: torch.ScriptObject | None + ): + # Use object.__setattr__ to bypass our custom __setattr__ during initialization + object.__setattr__(self, "wrapped_obj", wrapped_obj) + object.__setattr__(self, "script_class_name", script_class_name) + + from torch._library.opaque_object import is_custom_class + + # We don't want to deepcopy when tracing with opaque objects because + # if a mutation happens intentionally (Ex. caching in device mesh) + # then we want it to be recorded on the real object + real_obj = x + if not is_custom_class(type(x)): + try: + with _disable_current_modes(): + real_obj = copy.deepcopy(x) + except (RuntimeError, TypeError) as e: + log.warning( + "Unable to deepcopy the custom object %s due to %s. " + "Defaulting to the user given object. This might be " + "dangerous as side effects may be directly applied " + "to the object.", + script_class_name, + e, + ) + + object.__setattr__(self, "real_obj", real_obj) + + def __getattribute__(self, name): + try: + return super().__getattribute__(name) + except AttributeError as e: + raise AttributeError( + f"Tried to call __getattr__ with attr '{name}' on a FakeScriptObject, " + "implying that you are calling this inside of a fake kernel. " + "The fake kernel should not depend on the contents of the " + "OpaqueObject at all, so we're erroring out. If this attr is " + "a method or constant attribute, you can allow this member access by " + "registering it via `register_custom_class(members=...)`." + ) from e + + def __setattr__(self, name, value): + raise AttributeError( + f"Tried to call __setattr__ with attr '{name}' on a FakeScriptObject, " + "implying that you are calling this inside of a fake kernel. " + "The fake kernel should not depend on the contents of the " + "OpaqueObject at all, so we're erroring out. If you need this" + "functionality, consider creating a custom TorchBind Object instead" + "(but note that this is more difficult)." + ) + + def __getitem__(self, key): + # This is needed for DeviceMesh support + return self.real_obj[key] + + def __eq__(self, other): + if self is other: + return True + # Get real_obj without triggering custom __getattribute__ + self_real = object.__getattribute__(self, "real_obj") + if isinstance(other, FakeScriptObject): + other_real = object.__getattribute__(other, "real_obj") + # For reference types, identity check first + if self_real is other_real: + return True + # Fall back to equality check + return self_real == other_real + # Compare with the real object directly + return self_real == other + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + # Use real_obj's hash if available, otherwise use object id + real_obj = object.__getattribute__(self, "real_obj") + try: + return hash(real_obj) + except TypeError: + # Object is not hashable, use identity-based hash + return id(real_obj) + + def __deepcopy__(self, memo: dict[int, Any]) -> "FakeScriptObject": + if id(self) in memo: + return memo[id(self)] + new_obj = FakeScriptObject.__new__(FakeScriptObject) + memo[id(self)] = new_obj + object.__setattr__( + new_obj, "wrapped_obj", copy.deepcopy(self.wrapped_obj, memo) + ) + object.__setattr__(new_obj, "script_class_name", self.script_class_name) + # Disable dispatch modes during deepcopy of real_obj and attribute + # access to prevent tensor operations (e.g. storage cloning, property + # access on DeviceMesh) from going through proxy tracing or + # functionalization. + with _disable_current_modes(): + new_real_obj = copy.deepcopy(self.real_obj, memo) + object.__setattr__(new_obj, "real_obj", new_real_obj) + for name, value in self.__dict__.items(): + if name not in ("wrapped_obj", "script_class_name", "real_obj"): + if isinstance(value, FakeScriptMethod): + object.__setattr__( + new_obj, + name, + FakeScriptMethod(new_obj, value.method_name, value.schema), + ) + else: + if hasattr(new_real_obj, name): + object.__setattr__( + new_obj, name, getattr(new_real_obj, name) + ) + else: + object.__setattr__(new_obj, name, value) + return new_obj + + +def maybe_unwrap_fake_script_object(obj: Any) -> Any: + """If obj is a FakeScriptObject, return the underlying real object.""" + if isinstance(obj, FakeScriptObject): + return obj.real_obj + return obj + + +class FakeScriptMethod: + def __init__( + self, + self_fake_obj: FakeScriptObject, + method_name: str, + schema: torch.FunctionSchema | None, + ): + self.self_fake_obj = self_fake_obj + self.method_name = method_name + self.schema = schema + + def __call__(self, *args, **kwargs): + from torch._higher_order_ops.torchbind import call_torchbind + + return call_torchbind(self.self_fake_obj, self.method_name, *args, **kwargs) + + +class HasStaticMethodFromReal(Protocol): + @classmethod + def from_real(cls, real_obj: torch.ScriptObject): + pass + + +class FakeClassRegistry: + def __init__(self) -> None: + self._registered_class: dict[str, Any] = {} + + def has_impl(self, full_qualname: str) -> bool: + return full_qualname in self._registered_class + + def get_impl(self, full_qualname: str) -> Any: + self._check_registered(full_qualname) + return self._registered_class[full_qualname] + + def register(self, full_qualname: str, fake_class=None) -> None: + if self.has_impl(full_qualname): + log.warning( + "%s is already registered. Previous fake class is overridden with %s.", + full_qualname, + fake_class, + ) + self._registered_class[full_qualname] = fake_class + + def deregister(self, full_qualname: str) -> Any: + if not self.has_impl(full_qualname): + log.warning( + "Cannot deregister %s. Please use register_fake_class to register it first." + " Or do you dereigster it twice?", + full_qualname, + ) + else: + return self._registered_class.pop(full_qualname) + + def clear(self) -> None: + self._registered_class.clear() + + def _check_registered(self, full_qualname: str) -> None: + if full_qualname not in self._registered_class: + raise RuntimeError( + f"{full_qualname} is not registered. Please use register_fake_class to register it first." + ) + + +global_fake_class_registry = FakeClassRegistry() + + +# TODO: add this check at compile time for __obj_flatten__. +def _check_valid_flat_script_obj(flat_x): + if not isinstance(flat_x, tuple): + raise RuntimeError("Expect flat x to be a tuple.") + + for tp in flat_x: + if not isinstance(tp, tuple): + raise RuntimeError("Expect flat x to be a tuple of tuples.") + + if not len(tp) == 2 or not isinstance(tp[0], str): + raise RuntimeError( + "Expect element of flat x to be a tuple of two elements with first element being a string" + ) + + +def tracing_with_real(x: torch.ScriptObject) -> bool: + if not hasattr(x, "tracing_mode"): + return False + + if x.tracing_mode() not in ["real", "fake"]: + raise AssertionError( + f"tracing_mode can be either real or fake but got {x.tracing_mode()}" + ) + return x.tracing_mode() == "real" + + +def maybe_to_fake_obj( + fake_mode, + x: Any, +) -> FakeScriptObject | torch.ScriptObject: + import torch.utils._pytree as pytree + + # When tracing with real mode, people should implement meta kernels that can + # handle the case of real script object + fake tensor inputs. + if tracing_with_real(x): + return x + + from torch._library.opaque_object import ( + FakeOpaqueObject, + get_opaque_obj_info, + get_opaque_type_name, + is_custom_class, + OpaqueTypeStr, + ) + + x_type = type(x) + if is_custom_class(x_type): + type_name = OpaqueTypeStr if x is None else get_opaque_type_name(x_type) + fake_x_wrapped = FakeScriptObject(FakeOpaqueObject(), type_name, x) + + # Set specified members onto the fake object + opaque_info = get_opaque_obj_info(x_type) + if opaque_info is None: + raise AssertionError(f"opaque_info for type {x_type} must not be None") + for attr_name in opaque_info.members: + with _disable_current_modes(): + if not hasattr(x, attr_name): + raise TypeError( + f"Opaque object of type '{type_name}' was specified to have member " + f"'{attr_name}', but this doesn't actually exist in the object." + ) + object.__setattr__(fake_x_wrapped, attr_name, getattr(x, attr_name)) + + return fake_x_wrapped + else: + # x.__obj_flatten__() could be calling some tensor operations inside but we don't + # want to call these ops in surrounding dispatch modes when executing it. + # Otherwise, for example, the fake tensor modes will error out when the tensors inside + # script object execute some operations like clone if allow_non_fake_input flag is set. + with _disable_current_modes(): + flat_x = x.__obj_flatten__() # type: ignore[attr-defined] + + _check_valid_flat_script_obj(flat_x) + + with fake_mode: + from torch._higher_order_ops.utils import _tensor_storage + + storage_map = { + _tensor_storage(inp): i + for i, inp in enumerate(flat_x) + if isinstance(inp, torch.Tensor) + } + alias_map = { + i: storage_map[_tensor_storage(inp)] + for i, inp in enumerate(flat_x) + if isinstance(inp, torch.Tensor) + and storage_map[_tensor_storage(inp)] != i + } + if len(alias_map) > 0: + log.warning( + "Detected script object %s has aliasing relationship among its tensors. " + "Flattened obj: %s. Aliasing tensor indices: %s. " + "This is not supported and may cause unexpected behavior.", + x, + flat_x, + alias_map, + ) + + # This breaks the aliasing relationship among the tensors inside the torchbind object + # This is bad but since we don't need to preserve the aliasing relationship anyway and + # we state clearly that aliasing relationship is not preserved in the doc so this might be OK. + fake_flattened = pytree.tree_map_only( + torch.Tensor, + lambda t: torch.empty_strided( + t.size(), + t.stride(), + device=t.device, + dtype=t.dtype, + requires_grad=t.requires_grad, + layout=t.layout, + ), + flat_x, + ) + + fake_x = _find_fake_class_for_script_object(x).__obj_unflatten__(fake_flattened) + + fake_x_wrapped = FakeScriptObject(fake_x, x._type().qualified_name(), x) # type: ignore[attr-defined] + + for name in x._method_names(): # type: ignore[attr-defined] + attr = getattr(fake_x, name, None) + if attr is not None: + if not callable(attr): + raise RuntimeError(f"Expect {name} to be a callable but got {attr}.") + + real_attr = getattr(x, name) # type: ignore[attr-defined] + + # real attr sometimes is not torch.ScriptMethod thus doesn't have schema e.g. __init___ or __eq__ + method_schema: torch.FunctionSchema | None = None + if isinstance(real_attr, torch.ScriptMethod): + method_schema = real_attr.schema # type: ignore[attr-defined] + + # Bypasses our custom setattr function + object.__setattr__( + fake_x_wrapped, + name, + FakeScriptMethod(fake_x_wrapped, name, method_schema), + ) + else: + override_skip_list = {"__obj_flatten__", "__getstate__", "__setstate__"} + if name not in override_skip_list: + log.warning("fake object of %s doesn't implement method %s.", x, name) + return fake_x_wrapped + + +def register_fake_class(qualname, fake_class: HasStaticMethodFromReal | None = None): + r"""Register a fake implementation for this class. + + It's in the same spirit of registering a fake implementation for + an operator but with the difference that it + associates a fake class with the original torch bind class (registered + with torch::class_). In this way, torch.compile can handle them properly + in components such as Dynamo and AOTAutograd. + + This API may be used as a decorator (see example). For the fake class, users + are required to provide a from_real classmethod that takes a real object and + returns an instance of the fake class. All tensors in the fake object should also + be properly fakified with to_fake_tensor() in from_real. + + + Examples: + # For a custom class Foo defined in test_custom_class_registration.cpp: + + TORCH_LIBRARY(_TorchScriptTesting, m) { + m.class_("_TensorQueue") + .def(torch::init()) + .def("push", &TensorQueue::push) + .def("pop", &TensorQueue::pop) + .def("top", &TensorQueue::top) + .def("size", &TensorQueue::size) + .def("clone_queue", &TensorQueue::clone_queue) + .def("__obj_flatten__", &TensorQueue::__obj_flatten__) + .def_pickle( + // __getstate__ + [](const c10::intrusive_ptr& self) + -> c10::Dict { + return self->serialize(); + }, + // __setstate__ + [](c10::Dict data) + -> c10::intrusive_ptr { + return c10::make_intrusive(std::move(data)); + }); + }; + # We could register a fake class FakeTensorQueue in Python as follows: + import torch + + @torch._library.register_fake_class("_TorchScriptTesting::_TensorQueue") + class FakeTensorQueue: + def __init__(self, queue): + self.queue = queue + + @classmethod + def __obj_unflatten__(cls, flattened_ctx): + return cls(**dict(ctx)) + + def push(self, x): + self.queue.append(x) + + def pop(self): + return self.queue.pop(0) + + def size(self): + return len(self.queue) + + In this example, the original TensorQueue need to add a __obj_flatten__ method + to the class TensorQueue and the flattened result is passed into FakeTensorQueue's + __obj_unflatten__ as inputs to create a fake class. This protocol allows pytorch to look + at the contents of the script object and properly handle them in the subsystems + like dynamo, aot_autograd or more. + """ + + def inner(fake_class: HasStaticMethodFromReal): + ns, name = parse_namespace(qualname) + + # This also checks whether the referred torch::class_ exists. + torch._C._get_custom_class_python_wrapper(ns, name) + + from_method = getattr(fake_class, _CONVERT_FROM_REAL_NAME, None) + if not from_method: + raise RuntimeError( + f"{fake_class} doesn't define a classmethod {_CONVERT_FROM_REAL_NAME}." + ) + + if not isinstance(fake_class.__dict__[_CONVERT_FROM_REAL_NAME], classmethod): + raise RuntimeError( + f"{_CONVERT_FROM_REAL_NAME} method is not a classmethod." + ) + + global_fake_class_registry.register(_full_qual_class_name(qualname), fake_class) + return fake_class + + if fake_class is None: + return inner + return inner(fake_class) + + +def deregister_fake_class(qualname): + return global_fake_class_registry.deregister(_full_qual_class_name(qualname)) + + +def has_fake_class(full_qualname) -> bool: + return global_fake_class_registry.has_impl(full_qualname) + + +def find_fake_class(full_qualname) -> Any | None: + if not has_fake_class(full_qualname): + return None + return global_fake_class_registry.get_impl(full_qualname) + + +def _full_qual_class_name(qualname: str) -> str: + ns, name = parse_namespace(qualname) + return "__torch__.torch.classes." + ns + "." + name + + +def _is_script_object(obj: Any) -> bool: + return isinstance( + obj, torch.ScriptObject + ) and obj._type().qualified_name().startswith( # type: ignore[attr-defined] + "__torch__.torch.classes" + ) + + +# Return the namespace and class name from fully qualified name. +def _ns_and_class_name(full_qualname: str) -> tuple[str, str]: + splits = full_qualname.split(".") + if len(splits) != 5: + raise AssertionError(f"Could not split {full_qualname=}, expected 5 parts") + _torch, _torch_ns, _classes, ns, class_name = splits + return ns, class_name + + +def _find_fake_class_for_script_object(x: torch.ScriptObject) -> Any: + full_qualname = x._type().qualified_name() # type: ignore[attr-defined] + ns, class_name = _ns_and_class_name(full_qualname) + fake_class = find_fake_class(full_qualname) + if fake_class is None: + raise RuntimeError( + f" ScriptObject's {full_qualname} haven't registered a fake class." + f" Please use register_fake_class({ns}::{class_name}) to annotate a fake class for the script obj." + f" Specifically, create a python class that implements a fake version for all the methods" + f" that're used in the program and put annotated class in the program e.g. after loading the library." + f" The fake methods can be written in the same way as a meta kernel for an operator but need to additionally" + f" simulate the object's states. Be sure to add a {_CONVERT_FROM_REAL_NAME} classmethod" + f" to enable creating a fake obj from a real one." + ) + return fake_class + + +_CONVERT_FROM_REAL_NAME = "__obj_unflatten__" + + +def _fake_obj_from_real(fake_mode, x) -> Any: + fake_class = _find_fake_class_for_script_object(x) + + from_real_method = getattr(fake_class, _CONVERT_FROM_REAL_NAME, None) + if not from_real_method: + raise RuntimeError( + f"{fake_class} must define a classmethod {_CONVERT_FROM_REAL_NAME}" + f" that converts the real object to the fake object." + ) + + # from_real defined by user need the ctx to fakify the tensor states. + ctx = torch._library.fake_impl.FakeImplCtx(fake_mode, None) + with torch._library.fake_impl.set_ctx_getter(lambda: ctx): + return fake_class.from_real(x) diff --git a/.venv/lib/python3.12/site-packages/torch/_library/fake_impl.py b/.venv/lib/python3.12/site-packages/torch/_library/fake_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..79105d1b493eb0f54b52f4290d6291306396504b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/fake_impl.py @@ -0,0 +1,241 @@ +# mypy: allow-untyped-defs +import contextlib +import functools +import logging +from collections.abc import Callable +from typing_extensions import deprecated + +import torch +from torch._library.utils import Kernel, RegistrationHandle + + +log = logging.getLogger(__name__) + + +class FakeImplHolder: + """A holder where one can register a fake impl to.""" + + def __init__(self, qualname: str): + self.qualname: str = qualname + # kernels stores all registered fake kernels, ordered by registration + # time ascendingly (newer registration after older registration). If an + # operator library gets loaded that overrides an existing fake kernel, + # both kernels will be in the list, but the newest one will be the one + # that is run. If the library is unloaded, we will remove the kernel + # from this list. + self.kernels: list[Kernel] = [] + + @property + def kernel(self): + if len(self.kernels) == 0: + return None + return self.kernels[-1] + + @kernel.setter + def kernel(self, value): + raise RuntimeError("Unable to directly set kernel.") + + def register( + self, func: Callable, source: str, lib, *, allow_override=True + ) -> RegistrationHandle: + """Register a fake impl. + + Returns a RegistrationHandle that one can use to de-register this + fake impl. + """ + + if not allow_override: + if self.kernel is not None: + raise RuntimeError( + f"register_fake(...): the operator {self.qualname} " + f"already has a fake impl registered at " + f"{self.kernel.source}." + ) + if torch._C._dispatch_has_kernel_for_dispatch_key(self.qualname, "Meta"): + raise RuntimeError( + f"register_fake(...): the operator {self.qualname} " + f"already has a DispatchKey::Meta implementation via a " + f"pre-existing torch.library or TORCH_LIBRARY registration. " + f"Please either remove that registration or don't call " + f"register_fake." + ) + + if torch._C._dispatch_has_kernel_for_dispatch_key( + self.qualname, "CompositeImplicitAutograd" + ): + raise RuntimeError( + f"register_fake(...): the operator {self.qualname} " + f"already has an implementation for this device type via a " + f"pre-existing registration to " + f"DispatchKey::CompositeImplicitAutograd." + f"CompositeImplicitAutograd operators do not need a fake " + f"impl; " + f"instead, the operator will decompose into its constituents " + f"and those " + f"can have fake impls defined on them." + ) + + # Store the kernel in this holder + kernel = Kernel(func, source) + self.kernels.append(kernel) + + def deregister_fake_kernel(): + self.kernels.remove(kernel) + + meta_kernel = construct_meta_kernel(self.qualname, self) + try: + lib.impl(self.qualname, meta_kernel, "Meta", allow_override=allow_override) + except Exception: + log.info( + "Failed to register fake_impl '%s':", + self.qualname, + ) + self.kernels.remove(kernel) + raise + + handle = RegistrationHandle(deregister_fake_kernel) + return handle + + +def construct_meta_kernel(qualname: str, fake_impl_holder: FakeImplHolder) -> Callable: + if fake_impl_holder.kernel is None: + raise AssertionError("fake_impl_holder.kernel must not be None") + + @functools.wraps(fake_impl_holder.kernel.func) + def meta_kernel(*args, **kwargs): + if fake_impl_holder.kernel is None: + raise AssertionError("fake_impl_holder.kernel must not be None") + source = fake_impl_holder.kernel.source + + def error_on_ctx(): + raise RuntimeError( + f"{qualname} ({source}): You're trying to run this operator " + f"with meta Tensors (as opposed to FakeTensors), but this " + f"operator may return an output Tensor with data-dependent shape. Meta " + f"Tensors don't support operators with outputs that have data-dependent shapes " + f"but FakeTensors do. " + f"If your operator does not return an output with data-dependent shape, " + f"make sure the FakeTensor and/or meta kernel does not call " + f"torch.library.get_ctx(). Otherwise, please use FakeTensors." + ) + + with set_ctx_getter(error_on_ctx): + return fake_impl_holder.kernel(*args, **kwargs) + + return meta_kernel + + +def get_none(): + return None + + +global_ctx_getter: Callable = get_none + + +@contextlib.contextmanager +def set_ctx_getter(ctx_getter): + global global_ctx_getter + prev = global_ctx_getter + try: + global_ctx_getter = ctx_getter + yield + finally: + global_ctx_getter = prev + + +class FakeImplCtx: + """ + Context object for writing fake implementations for custom operators. + """ + + def __init__(self, _fake_mode, _op): + self._fake_mode = _fake_mode + self._shape_env = _fake_mode.shape_env + self._op = _op + + @deprecated( + "`create_unbacked_symint` is deprecated, please use `new_dynamic_size` instead", + category=FutureWarning, + ) + def create_unbacked_symint(self, *, min=2, max=None) -> torch.SymInt: + return self.new_dynamic_size(min=min, max=max) + + def new_dynamic_size(self, *, min=0, max=None) -> torch.SymInt: + """Constructs a new symint (symbolic int) representing a data-dependent value. + + This is useful for writing the fake implementation (which is necessary + for torch.compile) for a CustomOp where an output Tensor has a size + that depends on the data of the input Tensors. + + Args: + min (int): A statically known inclusive lower bound for this symint. Default: 0 + max (Optional[int]): A statically known inclusive upper bound for this + symint. Default: None + + .. warning: + + It is important that the ``min`` and ``max`` (if not None) values are set + correctly, otherwise, there will be undefined behavior under + torch.compile. The default value of ``min`` is 2 due to torch.compile + specializing on 0/1 sizes. + + You must also verify that your implementation on concrete Tensors + (e.g. CPU/CUDA) only returns Tensors where the size that corresponds + to the symint also has respects these constraint. + The easiest way to do this is to add an assertion in the CPU/CUDA/etc + implementation that the size follows these bounds. + + Example:: + + >>> # An operator with data-dependent output shape + >>> lib = torch.library.Library("mymodule", "FRAGMENT") + >>> lib.define("mymodule::custom_nonzero(Tensor x) -> Tensor") + >>> + >>> @torch.library.register_fake("mymodule::custom_nonzero") + >>> def _(x): + >>> # Number of nonzero-elements is data-dependent. + >>> # Since we cannot peek at the data in a fake impl, + >>> # we use the ctx object to construct a new symint that + >>> # represents the data-dependent size. + >>> ctx = torch.library.get_ctx() + >>> nnz = ctx.new_dynamic_size() + >>> shape = [nnz, x.dim()] + >>> result = x.new_empty(shape, dtype=torch.int64) + >>> return result + >>> + >>> @torch.library.impl(lib, "custom_nonzero", "CPU") + >>> def _(x): + >>> x_np = x.numpy() + >>> res = np.stack(np.nonzero(x_np), axis=1) + >>> return torch.tensor(res, device=x.device) + + """ + if ( + self._shape_env is None + or not self._shape_env.allow_dynamic_output_shape_ops + ): + raise torch._subclasses.fake_tensor.DynamicOutputShapeException(self._op) + + if isinstance(min, torch.SymInt) or isinstance(max, torch.SymInt): + raise ValueError( + f"ctx.new_dynamic_size(min={min}, max={max}): expected " + f"min and max to be statically known ints but got SymInt. " + f"This is not supported." + ) + + if min < 0: + raise ValueError( + f"ctx.new_dynamic_size(min={min}, ...): expected min to be " + f"greater than or equal to 0: this API can only create " + f"non-negative sizes." + ) + + return allocate_size(self._shape_env, min, max) + + +def allocate_size(shape_env, min_val=0, max_val=None): + result = shape_env.create_unbacked_symint() + torch.fx.experimental.symbolic_shapes._constrain_range_for_size( + result, min=min_val, max=max_val + ) + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_library/fake_profile.py b/.venv/lib/python3.12/site-packages/torch/_library/fake_profile.py new file mode 100644 index 0000000000000000000000000000000000000000..82056b4197fc33234635c84bee426de3ce7b9c3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/fake_profile.py @@ -0,0 +1,327 @@ +import contextlib +import io +import logging +import os +from collections.abc import Callable, Generator +from dataclasses import dataclass +from typing import Any, Optional + +import torch +from torch._library.custom_ops import _maybe_get_opdef +from torch.types import FileLike + + +log = logging.getLogger(__name__) + + +class MissingOpProfile(RuntimeError): + """ + This is raised when we don't have an operator profile available for the + given inputs. + """ + + +@dataclass(frozen=True) +class TensorMetadata: + rank: int + dtype: torch.dtype + device: torch.device + layout: torch.layout + + @staticmethod + def maybe_from_tensor(t: Any) -> Optional["TensorMetadata"]: + if not isinstance(t, torch.Tensor): + return None + return TensorMetadata(t.dim(), t.dtype, t.device, t.layout) + + +@dataclass(frozen=True) +class OpProfile: + args_profile: tuple[TensorMetadata | None] + out_profile: TensorMetadata | tuple[TensorMetadata] + + +def _generate_fake_kernel(op_name: str, op_profile: set[OpProfile]) -> Callable: + def _match_args(args_profile: tuple[TensorMetadata | None], args: Any) -> bool: + return all( + TensorMetadata.maybe_from_tensor(arg) == args_profile[i] + for i, arg in enumerate(args) + ) + + def _generate_res( + out_profile: TensorMetadata | tuple[TensorMetadata], + ) -> torch.Tensor | list[torch.Tensor]: + ctx = torch.library.get_ctx() + + def _generate_tensor_out(t: TensorMetadata) -> torch.Tensor: + fake_shape = [ctx.new_dynamic_size() for _ in range(t.rank)] + fake_strides = [-1] * t.rank + expected = 1 + fake_stride = expected + # pyrefly: ignore [bad-assignment] + for i in range(t.rank): + fake_strides[i] = fake_stride # type: ignore[assignment] + fake_stride = fake_stride * fake_shape[i] # type: ignore[assignment] + + return torch.empty_strided( + fake_shape, + fake_strides, + device=t.device, + dtype=t.dtype, + layout=t.layout, + ) + + if isinstance(out_profile, TensorMetadata): + return _generate_tensor_out(out_profile) + else: + return [_generate_tensor_out(t) for t in out_profile] + + def _fake_kernel(*args, **kwargs): # type: ignore[no-untyped-def] + for profile in op_profile: + if _match_args(profile.args_profile, (*args, *kwargs.values())): + return _generate_res(profile.out_profile) + + raise MissingOpProfile( + f"No fake kernel was found for {op_name}, and although we have " + "previously registered some profiles to generate a fake kernel, " + f"no profiles match the given inputs: {args, kwargs}." + ) + + return _fake_kernel + + +@contextlib.contextmanager +def unsafe_generate_fake_kernels(op_profiles: dict[str, set[OpProfile]]) -> Generator: + """ + Registers a fake kernel based on the given operator profiles. This fake + kernel registration will override any existing fake kernel registrations. + + The input is a dictionary mapping operator names to a set of operator + profiles, which we will use to generate fake kernels. The operator profiles + are a record of the input and output tensor metadata. Based on this + information we will match a given input to the recorded profile, and return + an output with the same metadata as in the recorded profile. If a profile + doesn't exist then an exception will be thrown. + + The fake kernel generation is considered unsafe because it relies on the + rigid, pre-defined operator profiles that do not account for potential + variations in output behavior. Specifically, the generated kernels assume a + fixed relationship between input and output ranks. However, in reality, it's + possible that data-dependent operations may produce outputs of different + ranks even when given inputs of the same rank. The generated fake kernels + are inflexible and unable to accommodate these nuances, making them + potentially unsafe. + + Args: + op_profiles (dict[str, set[OpProfile]]): A dictionary mapping operator + name to a set of operator profiles from which we will generate fake + kernels. + + Examples: + + >>> # Example: Registering an op-profile from draft-export + >>> import torch + >>> from torch.export._draft_export import draft_export + >>> + >>> @torch.library.custom_op("mylib::foo", mutates_args=()) + >>> def foo(x: Tensor, y: Tensor) -> Tensor: + >>> return x + y + >>> + >>> class M(torch.nn.Module): + >>> def forward(self, a, b): + >>> res = torch.ops.mylib.foo(a, b) # no fake impl + >>> return res + >>> + >>> ep = draft_export(M(), (torch.ones(3, 4), torch.ones(3, 4)) + >>> + >>> with torch._library.fake_profile.unsafe_generate_fake_kernels(ep._report.op_profiles): + >>> decomp = ep.run_decompositions() + + """ + + libs: list[torch.library.Library] = [] + # Stores old fake impls from custom ops declared through @custom_op + old_fake_impls: dict[str, Callable] = {} + for op_name, profiles in op_profiles.items(): + log.warning( + "Registering fake profile for %s. This will override any existing " + "fake kernel registration.", + op_name, + ) + + op_name_split = op_name.split(".") + namespace, op_name_str = op_name_split[0], op_name_split[1] + op_str = f"{namespace}::{op_name_str}" + + fake_kernel = _generate_fake_kernel(op_str, profiles) + + if opdef := _maybe_get_opdef(op_str): + # If the op is a CustomOpDef, save the existing abstract_fn so that + # we can restore it after this contextmanager + if opdef._abstract_fn is not None: + old_fake_impls[op_str] = opdef._abstract_fn + opdef.register_fake(fake_kernel) + + else: + # Create a new library so that we can register a new fake impl. + # These libraries will then be destroyed after the contextmanager, + # which will automatically restore the previously registered fake + # impls. + newlib = torch.library.Library(namespace, "FRAGMENT") + torch.library.register_fake( + op_str, fake_kernel, lib=newlib, allow_override=True + ) + libs.append(newlib) + + try: + yield libs + finally: + # Destroying the libraries will automatically restore the previously + # registered fake impls + for lib in libs: + lib._destroy() + + # Restore abstract_fns for CustomOpDefs + for op_str, old_fake in old_fake_impls.items(): + opdef = _maybe_get_opdef(op_str) + if opdef is None: + raise AssertionError(f"opdef for {op_str} must not be None") + opdef.register_fake(old_fake) + + +def get_torch_version() -> str: + version = torch.__version__.split(".") + return f"{int(version[0])}.{int(version[1])}" + + +def generate_yaml_from_profiles(op_profiles: dict[str, set[OpProfile]]) -> str: + """ + Generates a yaml string from the given operator profiles which can be saved + to a file. The yaml string can be loaded back into an operator profile + structure using `read_profiles_from_yaml`. + """ + + import yaml + + from torch._export.serde.serialize import ( + _TORCH_TO_SERIALIZE_DTYPE, + _TORCH_TO_SERIALIZE_LAYOUT, + ) + + def serialize_tensor_metadata(t: TensorMetadata) -> dict: + return { + "rank": t.rank, + "dtype": _TORCH_TO_SERIALIZE_DTYPE[t.dtype].value, + "device": str(t.device), + "layout": _TORCH_TO_SERIALIZE_LAYOUT[t.layout].value, + } + + def serialize_op_profile(op: OpProfile) -> dict: + return { + "args_profile": [ + serialize_tensor_metadata(arg) + for arg in op.args_profile + if arg is not None + ], + "out_profile": ( + serialize_tensor_metadata(op.out_profile) + if isinstance(op.out_profile, TensorMetadata) + else [serialize_tensor_metadata(out) for out in op.out_profile] + ), + } + + serialized_data = { + operator: [serialize_op_profile(profile) for profile in profiles] + for operator, profiles in op_profiles.items() + } + return yaml.dump( + {"torch_version": get_torch_version(), "operators": serialized_data}, + sort_keys=False, + ) + + +def save_op_profiles(op_profiles: dict[str, set[OpProfile]], f: FileLike) -> None: + """ + Serializes the given operator profiles into a yaml format and saves it to + the given file. The operator profile can be loaded back using `load_op_profiles`. + """ + yaml_str = generate_yaml_from_profiles(op_profiles) + + if isinstance(f, (str, os.PathLike)): + f = os.fspath(f) + + with open(f, "w") as file: + file.write(yaml_str) + + elif isinstance(f, io.BytesIO): + f.write(yaml_str.encode("utf-8")) + + else: + raise ValueError(f"Invalid type of file {f}") + + +def read_profiles_from_yaml(yaml_str: str) -> dict[str, set[OpProfile]]: + """ + Reads the yaml saved by `save_op_profiles` and returns the operator profiles. + """ + + import yaml + + from torch._export.serde.serialize import ( + _SERIALIZE_TO_TORCH_DTYPE, + _SERIALIZE_TO_TORCH_LAYOUT, + ) + + def deserialize_tensor_metadata(data: dict) -> TensorMetadata: + return TensorMetadata( + rank=data["rank"], + dtype=_SERIALIZE_TO_TORCH_DTYPE[data["dtype"]], + device=torch.device(data["device"]), + layout=_SERIALIZE_TO_TORCH_LAYOUT[data["layout"]], + ) + + def deserialize_op_profile(data: dict) -> OpProfile: + args_profile = tuple( + deserialize_tensor_metadata(arg) for arg in data["args_profile"] + ) + out_profile_data = data["out_profile"] + out_profile: tuple[TensorMetadata] | TensorMetadata = ( + tuple(deserialize_tensor_metadata(out) for out in out_profile_data) # type: ignore[assignment] + if isinstance(out_profile_data, list) + else deserialize_tensor_metadata(out_profile_data) + ) + return OpProfile(args_profile=args_profile, out_profile=out_profile) # type: ignore[arg-type] + + loaded_data = yaml.safe_load(yaml_str) + loaded_torch_version = loaded_data["torch_version"] + + if loaded_torch_version != get_torch_version(): + raise RuntimeError( + "Unable to load outdated profile. It was saved with torch version: " + f"{loaded_torch_version} but the current torch version is: {get_torch_version()}" + ) + + operators_data = loaded_data["operators"] + return { + operator: {deserialize_op_profile(profile) for profile in profiles} + for operator, profiles in operators_data.items() + } + + +def load_op_profiles(f: FileLike) -> dict[str, set[OpProfile]]: + """ + Loads the saved operator profiles from `save_op_profiles`. + """ + if isinstance(f, (str, os.PathLike)): + f = os.fspath(f) + + with open(f) as file: + yaml_str = file.read() + + elif isinstance(f, io.BytesIO): + yaml_str = f.read().decode("utf-8") + + else: + raise ValueError(f"Invalid type of file {f}") + + return read_profiles_from_yaml(yaml_str) diff --git a/.venv/lib/python3.12/site-packages/torch/_library/infer_schema.py b/.venv/lib/python3.12/site-packages/torch/_library/infer_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..29110e7d5726e1a2b8e70ef082741de2a60eaa7e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/infer_schema.py @@ -0,0 +1,471 @@ +# mypy: allow-untyped-defs +import collections +import inspect +import typing +from types import GenericAlias + +import torch +from torch import device, dtype, Tensor, types +from torch.utils._exposed_in import exposed_in + +from .opaque_object import ( + _resolve_opaque_type_info, + is_custom_class, + is_opaque_symbolic_type, +) + + +# This is used as a negative test for +# test_custom_ops.py::TestTypeConversion::test_type_eval. +_TestTensor = torch.Tensor + + +@exposed_in("torch.library") +def infer_schema( + prototype_function: typing.Callable, + /, + *, + mutates_args, + op_name: str | None = None, + tags: torch.Tag | typing.Sequence[torch.Tag] | None = (), +) -> str: + r"""Parses the schema of a given function with type hints. The schema is inferred from the + function's type hints, and can be used to define a new operator. + + We make the following assumptions: + + * None of the outputs alias any of the inputs or each other. + * | String type annotations "device, dtype, Tensor, types" without library specification are + | assumed to be torch.*. Similarly, string type annotations "Optional, List, Sequence, Union" + | without library specification are assumed to be typing.*. + * | Only the args listed in ``mutates_args`` are being mutated. If ``mutates_args`` is "unknown", + | it assumes that all inputs to the operator are being mutates. + + Callers (e.g. the custom ops API) are responsible for checking these assumptions. + + Args: + prototype_function: The function from which to infer a schema for from its type annotations. + op_name (Optional[str]): The name of the operator in the schema. If ``name`` is None, then the + name is not included in the inferred schema. Note that the input schema to + ``torch.library.Library.define`` requires an operator name. + mutates_args ("unknown" | Iterable[str]): The arguments that are mutated in the function. + tags (Tag | Sequence[Tag] | None): one or more tags to apply to the + inferred schema. Use ``torch.Tag.inplace`` or ``torch.Tag.out`` to + infer the conventional aliasing for those operator kinds. + + Returns: + The inferred schema. + + Example: + >>> def foo_impl(x: torch.Tensor) -> torch.Tensor: + >>> return x.sin() + >>> + >>> infer_schema(foo_impl, op_name="foo", mutates_args={}) + foo(Tensor x) -> Tensor + >>> + >>> infer_schema(foo_impl, mutates_args={}) + (Tensor x) -> Tensor + """ + UNKNOWN_MUTATES = "unknown" + pf_globals = prototype_function.__globals__ + pf_locals = None + # TODO: Once our minimum version is py3.10+ pass `eval_str=True` to + # inspect.signature() and we no longer need to deal with stringified + # annotations below. + sig = inspect.signature(prototype_function) + if tags is None: + tags = () + elif isinstance(tags, torch.Tag): + tags = (tags,) + is_inplace = torch.Tag.inplace in tags + is_out = torch.Tag.out in tags + if is_inplace and is_out: + raise AssertionError( + "torch.Tag.inplace and torch.Tag.out are mutually exclusive" + ) + if type(mutates_args) is not str: + mutates_args = tuple(mutates_args) + + def error_fn(what): + raise ValueError(f"infer_schema(func): {what} Got func with signature {sig})") + + def convert_type_string(annotation_type: str): + try: + return eval(annotation_type, pf_globals, pf_locals) + except NameError as e: + error_fn( + f"Unsupported type annotation {annotation_type}. It is not a type. " + f"({e}). " + f"If you are using 'from __future__ import annotations', note that " + f"annotations are evaluated lazily as strings; make sure all types " + f"referenced in annotations are importable at module scope, not only " + f"inside a local function." + ) + except Exception as e: + error_fn( + f"Unsupported type annotation {annotation_type}. It is not a type. " + f"({type(e).__name__}: {e})" + ) + + def unstringify_types( + tys: tuple[type[object] | str, ...], + ) -> tuple[tuple[typing.Any, ...], bool]: + res = [] + changed = False + for ty in tys: + ty, ty_changed = unstringify_type(ty) + res.append(ty) + changed |= ty_changed + if changed: + return tuple(res), True + else: + return tys, False # type: ignore[return-value] + + def unstringify_type(ty: type[object] | str) -> tuple[typing.Any, bool]: + # Dig through a generic type and if it contains a stringified type + # convert that to a real type. The second return value indicates if the + # type contained a string or not. + if isinstance(ty, str): + return convert_type_string(ty), True + elif origin := typing.get_origin(ty): + args, args_changed = unstringify_types(typing.get_args(ty)) + if args_changed: + return GenericAlias(origin, args), True + + return ty, False + + params = [] + seen_args = set() + saw_kwarg_only_arg = False + first_positional_arg_name = None + first_positional_arg_schema_type = None + first_positional_arg_alias = None + out_arg_aliases = [] + out_arg_names = [] + for idx, (name, param) in enumerate(sig.parameters.items()): + if not supported_param(param): + error_fn("We do not support positional-only args, varargs, or varkwargs.") + + if param.kind == inspect.Parameter.KEYWORD_ONLY: + # The first time we see a kwarg-only arg, add "*" to the schema. + if not saw_kwarg_only_arg: + params.append("*") + saw_kwarg_only_arg = True + + if param.annotation is inspect.Parameter.empty: + error_fn(f"Parameter {name} must have a type annotation.") + + # The annotation might be converted to a string by annotation, + # we convert it to the actual type. + annotation_type, _ = unstringify_type(param.annotation) + + schema_type = None + if annotation_type not in SUPPORTED_PARAM_TYPES: + if is_custom_class(annotation_type): + schema_type = _resolve_opaque_type_info(annotation_type).class_name # type: ignore[union-attr] + elif annotation_type == torch._C.ScriptObject: + error_fn( + f"Parameter {name}'s type cannot be inferred from the schema " + "as it is a ScriptObject. Please manually specify the schema " + "using the `schema=` kwarg with the actual type of the ScriptObject." + ) + elif ( + hasattr(annotation_type, "__origin__") + and annotation_type.__origin__ is tuple + ): + list_type = tuple_to_list(annotation_type) + example_type_str = "\n\n" + # Only suggest the list type if this type is supported. + if list_type in SUPPORTED_PARAM_TYPES: + example_type_str = f"For example, {list_type}.\n\n" + error_fn( + f"Parameter {name} has unsupported type {param.annotation}. " + f"We do not support Tuple inputs in schema. As a workaround, please try to use List instead. " + f"{example_type_str}" + f"The valid types are: {SUPPORTED_PARAM_TYPES.keys()}." + ) + else: + error_fn( + f"Parameter {name} has unsupported type {param.annotation}. " + f"The valid types are: {SUPPORTED_PARAM_TYPES.keys()}." + ) + else: + schema_type = SUPPORTED_PARAM_TYPES[annotation_type] + + if schema_type is None: + raise AssertionError(f"schema_type is None for param {name}") + + if ( + param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + and first_positional_arg_name is None + ): + first_positional_arg_name = name + first_positional_arg_schema_type = schema_type + first_positional_arg_alias = f"a{idx}" + + is_mutated = False + if type(mutates_args) is str: + if mutates_args != UNKNOWN_MUTATES: + raise ValueError( + "mutates_args must either be a sequence of the names of " + "the arguments that are mutated or the string 'unknown'. " + ) + if schema_type.startswith("Tensor"): + is_mutated = True + schema_type = f"Tensor(a{idx}!){schema_type[len('Tensor') :]}" + elif name in mutates_args: + is_mutated = True + if not schema_type.startswith("Tensor"): + error_fn( + f"Parameter {name} is in mutable_args but only Tensors or collections of Tensors can be mutated" + ) + schema_type = f"Tensor(a{idx}!){schema_type[len('Tensor') :]}" + if is_out and is_mutated: + if param.kind != inspect.Parameter.KEYWORD_ONLY: + error_fn("torch.Tag.out requires mutable arguments to be keyword-only.") + if schema_type != f"Tensor(a{idx}!)": + error_fn( + "torch.Tag.out only supports mutable keyword-only Tensor arguments." + ) + out_arg_aliases.append(f"a{idx}") + out_arg_names.append(name) + seen_args.add(name) + if param.default is inspect.Parameter.empty: + # pyrefly: ignore [bad-argument-type] + params.append(f"{schema_type} {name}") + else: + default_repr = None + if param.default is None or isinstance(param.default, (int, float, bool)): + default_repr = str(param.default) + elif isinstance(param.default, (str, torch.device)): + default_repr = f'"{param.default}"' + elif isinstance(param.default, torch.dtype): + dtype_repr = str(param.default) + torch_dot = "torch." + if not dtype_repr.startswith(torch_dot): + raise AssertionError( + f"dtype repr {dtype_repr!r} must start with 'torch.'" + ) + default_repr = dtype_repr[len(torch_dot) :] + else: + error_fn( + f"Parameter {name} has an unsupported default value type {type(param.default)}. " + f"Please file an issue on GitHub so we can prioritize this." + ) + # pyrefly: ignore [bad-argument-type] + params.append(f"{schema_type} {name}={default_repr}") + if mutates_args != UNKNOWN_MUTATES: + mutates_args_not_seen = set(mutates_args) - seen_args + if len(mutates_args_not_seen) > 0: + error_fn( + f"{mutates_args_not_seen} in mutates_args were not found in " + f"the custom op's signature. " + f"mutates_args should contain the names of all args that the " + f"custom op mutates, or just the string 'unknown' if you don't know." + ) + if is_inplace: + if first_positional_arg_name is None: + error_fn("torch.Tag.inplace requires a positional Tensor argument.") + if first_positional_arg_schema_type != "Tensor": + error_fn( + "torch.Tag.inplace requires the first positional argument to be a Tensor." + ) + if type(mutates_args) is str or set(mutates_args) != { + first_positional_arg_name + }: + error_fn( + "torch.Tag.inplace requires mutates_args to contain exactly " + f"the first positional argument, got {mutates_args}." + ) + if is_out and len(out_arg_aliases) == 0: + error_fn( + "torch.Tag.out requires at least one mutable keyword-only Tensor argument." + ) + return_annotation, _ = unstringify_type(sig.return_annotation) + if is_out: + ret = _infer_out_return_schema( + return_annotation, out_arg_aliases, out_arg_names, error_fn + ) + else: + ret = parse_return(return_annotation, error_fn) + if is_inplace: + if ret != "Tensor": + error_fn( + "torch.Tag.inplace requires the return annotation to be torch.Tensor." + ) + ret = f"Tensor({first_positional_arg_alias}!)" + if op_name is not None: + return f"{op_name}({', '.join(params)}) -> {ret}" + return f"({', '.join(params)}) -> {ret}" + + +def derived_types( + base_type: type | typing._SpecialForm, + cpp_type: str, + list_base: bool, + optional_base_list: bool, + optional_list_base: bool, +): + result: list[tuple[type | typing._SpecialForm | GenericAlias, str]] = [ + (base_type, cpp_type), + # pyrefly: ignore [not-a-type] + (typing.Optional[base_type], f"{cpp_type}?"), # noqa: UP045 + ] + + def derived_seq_types(typ: type | typing._SpecialForm): + return ( + typing.Sequence[typ], # type: ignore[valid-type] + typing.List[typ], # type: ignore[valid-type] # noqa: UP006 + GenericAlias(collections.abc.Sequence, (typ,)), + GenericAlias(list, (typ,)), + ) + + if list_base: + result.extend( + (seq_typ, f"{cpp_type}[]") for seq_typ in derived_seq_types(base_type) + ) + if optional_base_list: + result.extend( + (seq_typ, f"{cpp_type}?[]") + # pyrefly: ignore [not-a-type] + for seq_typ in derived_seq_types(typing.Optional[base_type]) # noqa: UP045 + ) + if optional_list_base: + result.extend( + (typing.Optional[seq_typ], f"{cpp_type}[]?") # noqa: UP045 + for seq_typ in derived_seq_types(base_type) + ) + return result + + +def get_supported_param_types(): + data: list[tuple[type | typing._SpecialForm, str, bool, bool, bool]] = [ + # (python type, schema type, type[] variant, type?[] variant, type[]? variant + (Tensor, "Tensor", True, True, False), + (int, "SymInt", True, False, True), + (float, "float", True, False, True), + (bool, "bool", True, False, True), + (str, "str", False, False, False), + (types.Number, "Scalar", True, False, False), + (dtype, "ScalarType", False, False, False), + (device, "Device", False, False, False), + ] + + if torch.distributed.is_available(): + from torch.distributed.distributed_c10d import GroupName + + data.append((typing.cast(type, GroupName), "str", False, False, False)) + + result = [] + for line in data: + result.extend(derived_types(*line)) + return dict(result) + + +SUPPORTED_RETURN_TYPES = { + Tensor: "Tensor", + typing.List[Tensor]: "Tensor[]", # noqa: UP006 + list[Tensor]: "Tensor[]", + int: "SymInt", + float: "float", + bool: "bool", + types.Number: "Scalar", +} + + +def parse_return(annotation, error_fn): + if annotation is None: + return "()" + + if annotation is inspect.Parameter.empty: + error_fn("No return type annotation was provided. Please add one.") + + origin = typing.get_origin(annotation) + if origin is not tuple: + if annotation not in SUPPORTED_RETURN_TYPES: + if is_opaque_symbolic_type(annotation): + return _resolve_opaque_type_info(annotation).class_name # type: ignore[union-attr] + error_fn( + f"Return has unsupported type {annotation}. " + f"The valid types are: {SUPPORTED_RETURN_TYPES}." + ) + + return SUPPORTED_RETURN_TYPES[annotation] + + args = typing.get_args(annotation) + for arg in args: + if arg not in SUPPORTED_RETURN_TYPES and not is_opaque_symbolic_type(arg): + error_fn( + f"Return has unsupported type {annotation}. " + f"The valid types are: {SUPPORTED_RETURN_TYPES}." + ) + + def _return_type_str(arg): + if ty := SUPPORTED_RETURN_TYPES.get(arg): + return ty + return _resolve_opaque_type_info(arg).class_name # type: ignore[union-attr] + + output_ty = ", ".join(_return_type_str(arg) for arg in args) + + # use (()) to represent tuple with single element + if len(args) == 1: + output_ty = "(" + output_ty + ")" + return "(" + output_ty + ")" + + +def _infer_out_return_schema( + return_annotation, + out_arg_aliases, + out_arg_names, + error_fn, +): + if len(out_arg_aliases) == 1: + return_annotation_matches_out_args = return_annotation is Tensor + else: + return_annotation_matches_out_args = typing.get_origin( + return_annotation + ) is tuple and typing.get_args(return_annotation) == (Tensor,) * len( + out_arg_aliases + ) + + if not return_annotation_matches_out_args: + error_fn( + "torch.Tag.out requires the return annotation to match the " + f"mutable keyword-only Tensor arguments {tuple(out_arg_names)}." + ) + + aliased_returns = [f"Tensor({out_arg_alias}!)" for out_arg_alias in out_arg_aliases] + if len(aliased_returns) == 1: + return aliased_returns[0] + return f"({', '.join(aliased_returns)})" + + +SUPPORTED_PARAM_TYPES = get_supported_param_types() + + +def supported_param(param: inspect.Parameter) -> bool: + return param.kind in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.KEYWORD_ONLY, + ) + + +def tuple_to_list(tuple_type: type[tuple]) -> type[list]: + """ + Convert `tuple_type` into a list type with the same type arguments. Assumes that `tuple_type` is typing.Tuple type. + """ + type_args = typing.get_args(tuple_type) + if ( + tuple_type is typing.Tuple # noqa: UP006 + or tuple_type is tuple + or not type_args + ): + # Handle the case of an empty tuple type + return list + elif len(type_args) == 1: + # General case: create a List with the same type arguments + return list[type_args[0]] # type: ignore[valid-type] + elif len(type_args) == 2 and type_args[1] is Ellipsis: + return list[type_args[0]] # type: ignore[valid-type] + else: + return list[typing.Union[tuple(type_args)]] # type: ignore[misc, return-value] # noqa: UP007 diff --git a/.venv/lib/python3.12/site-packages/torch/_library/opaque_object.py b/.venv/lib/python3.12/site-packages/torch/_library/opaque_object.py new file mode 100644 index 0000000000000000000000000000000000000000..c6bc3930d70e2b20e2f26e9ac133dad17e200ee8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/opaque_object.py @@ -0,0 +1,480 @@ +""" +Note [Opaque Objects] + +Opaque objects are the way we allow custom operators to accept a user-defined +"black box" object as an input. + +There are two kinds of opaque types: CONSTANT type and SYMBOLIC type. +The distinction determines how torch.compile handles the object. + +SYMBOLIC TYPES (default): + +Symbolic-typed opaque objects represent mutable stateful objects and are +treated as black boxes. In torch.compile, since torch.compile cannot optimize +the anything (including tensors) within the object, the object must be an +input to the graph. + +You can register a custom class as being a symbolic-typed opaque object class +through `register_custom_class(MyClass, typ="symbolic")`. + +CONSTANT TYPES: + +Constant-typed opaque objects represent constant values. +In torch.compile, the graph specializes on the object like how other constants +are. Therefore there are a couple of methods on the class that must be +implemented before registering it as a constant-typed opaque object class: + - __eq__: torch.compile will create guards based on the equality of this + object, meaning that a recompilation will happen if __eq__ returns False. + - __hash__: This must be implemented for Fake Tensor caching + - __fx_repr__: This must be implemented to provide an evaluable representation + for FX graph codegen. It should return a tuple of (repr_string, dict[str, type]) + where repr_string can reconstruct the object and the dict maps names used in + repr_string to their corresponding types. + +You can register a custom class as being a constant-typed opaque object class +through `register_custom_class(MyClass, typ="constant")`. +""" + +import logging +from collections.abc import Callable +from dataclasses import dataclass +from enum import Enum +from typing import Any, Literal, NewType, TYPE_CHECKING, TypeAlias +from typing_extensions import TypeIs +from weakref import WeakKeyDictionary + +import torch +from torch._custom_class_base import CustomClassBase, CustomClassBaseMeta + + +if TYPE_CHECKING: + from torch.fx import Proxy + from torch.fx.experimental.proxy_tensor import PythonKeyTracer + +from .fake_class_registry import register_fake_class + + +log = logging.getLogger(__name__) + + +class MemberType(Enum): + """ + Defines how a member (attribute/property/method) of an opaque object is handled + during torch.compile tracing. + """ + + # Reads/calls the member at trace time with the real object and bakes the result as a constant + USE_REAL = "use_real" + # Inlines/traces the member + INLINED = "inlined" + + +@register_fake_class("aten::OpaqueObject") +class FakeOpaqueObject: + def __init__(self) -> None: + pass + + @classmethod + def __obj_unflatten__(cls, flattened_ctx: dict[str, Any]) -> None: + raise RuntimeError( + "FakeOpaqueObject should not be created through __obj_unflatten__ " + "and should be special handled. Please file an issue to Github." + ) + + +OpaqueTypeStr = "__torch__.torch.classes.aten.OpaqueObject" + +OpaqueType = NewType("OpaqueType", torch._C.ScriptObject) + +# Type for reconstruct_fn: called by PythonKeyTracer.create_arg when make_fx +# encounters an untracked opaque reference (e.g. a backward closure capture). +# Should derive the object from existing graph inputs or return None to fall +# back to get_attr. Args: (obj, get_tracked_proxy, tracer). +ReconstructFn: TypeAlias = Callable[ + [CustomClassBase, Callable[[CustomClassBase], "Proxy | None"], "PythonKeyTracer"], + "Proxy | None", +] + + +@dataclass +class _OpaqueTypeInfo: + class_name: str + opaque_typ: Literal["symbolic", "constant"] + guard_fn: Callable[ + [Any], list[Any] + ] # Callable that takes the object and returns list of values to guard on + members: dict[str, MemberType] # Maps member name to how it should be handled + hoist: bool + reconstruct_fn: ReconstructFn | None + + +# Mapping of type -> (string name, symbolic/constant type) +_OPAQUE_TYPES: WeakKeyDictionary[Any, _OpaqueTypeInfo] = WeakKeyDictionary() +# Mapping of class_name -> (type, symbolic/constant type) +_OPAQUE_TYPES_BY_NAME: dict[str, _OpaqueTypeInfo] = {} + + +def _resolve_opaque_type_info(cls: Any) -> _OpaqueTypeInfo | None: + if cls in _OPAQUE_TYPES: + return _OPAQUE_TYPES[cls] + if not isinstance(cls, type): + return None + + # Allow subclasses too + for parent in cls.__mro__[1:]: + if parent in _OPAQUE_TYPES: + return _OPAQUE_TYPES[parent] + return None + + +def get_opaque_type_name(cls: Any) -> str: + """ + Gets the registered opaque type name for a given class. + + Args: + cls (type): The class to get the type name for. + + Returns: + str: The registered type name for the class. + + Raises: + ValueError: If the class is not registered as an opaque type. + """ + info = _resolve_opaque_type_info(cls) + if info is None: + raise ValueError( + f"Class {cls} is not registered as an opaque type. " + f"Call register_custom_class({cls.__name__}) first." + ) + return info.class_name + + +def register_custom_class( + cls: Any, + *, + typ: str, + hoist=False, + guard_fn: Any = None, + members: dict[str, MemberType] | None = None, + reconstruct_fn: ReconstructFn | None = None, +) -> None: + """ + Registers the given type as an opaque type which allows this to be consumed + by a custom operator. + + The type name will be automatically generated from the class's fully + qualified name (ex. my_module.MyClass). + + Args: + cls (type): The class to register as an opaque type. + typ (str): Either "symbolic" or "constant". See Note [Opaque Objects] for + more details. + hoist (bool): Only applies to constant types. A hoist=True constant type + object is lifted as an input to the torch.compile'd graph, instead + of being a constant baked into the graph. This is useful to + improve compilation times in hierarchical compilation + (e.g., change your custom ops to use hoisted strings to avoid + baking the string into the Dynamo/AOTAutograd/FX graphs). + This flag does nothing for symbolic types. + guard_fn (callable | None): A function that takes an instance of the opaque + object and returns a list of values to guard on. These values will be compared + for equality on each function call, triggering recompilation if they change. + Only applicable for symbolic types. + Example: lambda obj: [obj.x, obj.y] + members (dict[str, MemberType] | None): Dictionary mapping member names + (attributes, properties, or methods) to their MemberType, which controls + how they are handled during torch.compile tracing: + - MemberType.USE_REAL: Evaluates with the real object at compile time and + bakes the result as a constant + - MemberType.INLINED: Inlines the method call into the trace + """ + import torch.utils._pytree as pytree + + # Prevent registration of built-in types (int, str, list, dict, etc.) and torch.Tensor + if cls.__module__ == "builtins" or cls is torch.Tensor: + raise ValueError( + f"Unable to register built-in type {cls} as an opaque type. " + "Please wrap it in a custom class and register the custom class as opaque." + ) + + if cls in pytree.SUPPORTED_NODES: + raise ValueError( + f"{cls} cannot be registered as an opaque object as it has been " + "registered as a pytree. Opaque objects must be pytree leaves." + ) + + if typ == "reference": + log.warning("typ='reference' is deprecated, use typ='symbolic' instead") + typ = "symbolic" + + if typ == "value": + log.warning("typ='value' is deprecated, use typ='constant' instead") + typ = "constant" + + # Constant types store the real object directly during tracing (no + # FakeScriptObject wrapper), so they don't need CustomClassBaseMeta. + if typ != "constant" and not isinstance(cls, CustomClassBaseMeta): + raise TypeError( + f"Custom class {cls} must subclass torch._custom_class_base.CustomClassBase " + "or 'metaclass=torch._custom_class_base.CustomClassBaseMeta'. " + "This is required so that FakeScriptObject can be registered " + "as a virtual subclass, allowing isinstance() checks to work " + "during torch.compile tracing. " + ) + + if typ not in ["symbolic", "constant"]: + raise AssertionError( + f"Custom class type must be either 'symbolic' or 'constant', got {typ!r}" + ) + + if typ == "constant": + # Enums use identity-based equality (singletons), which is fine for guarding. + if not issubclass(cls, Enum) and cls.__eq__ is object.__eq__: # type: ignore[comparison-overlap] + raise TypeError( + f"Value-type opaque object of type {cls} is " + "expected to have a non-default `__eq__` " + "implementation as we will use this in torch.compile " + "to guard on the equality of objects." + ) + + # Class with a custom `__eq__` without `__hash__` won't inherit the default + # `__hash__` from object; see https://stackoverflow.com/a/1608907. + if cls.__hash__ is None: # type: ignore[comparison-overlap] + raise TypeError( + f"Value-type opaque object of type {cls} is " + "expected to have a non-default `__hash__` " + "implementation as we will use this in torch.compile " + "for FakeTensor caching." + ) + + # Enums are special-cased in get_opaque_obj_repr. + if not issubclass(cls, Enum) and not hasattr(cls, "__fx_repr__"): + raise TypeError( + f"Value-type opaque object of type {cls} is " + "expected to have a `__fx_repr__` method " + "implementation as we will use this to reconstruct " + "the object in the FX codegen. __fx_repr__ should return " + "a tuple of (repr_string, dict[str, type])." + ) + + if guard_fn is not None: + raise TypeError( + "No need to specify `guard_fn` for " + f"value-type opaque class {cls} as it will be guarded based " + "on `__eq__`." + ) + + # Generate a fully qualified name by combining module and qualname + name = f"{cls.__module__}.{cls.__qualname__}" + + type_info = _OpaqueTypeInfo( + name, typ, guard_fn, members or {}, hoist, reconstruct_fn + ) + _OPAQUE_TYPES[cls] = type_info + _OPAQUE_TYPES_BY_NAME[name] = type_info + + torch._C._register_opaque_type(name) + + +def register_opaque_type( + cls: Any, + *, + typ: str, + hoist=False, + guard_fn: Any = None, + members: dict[str, MemberType] | None = None, + reconstruct_fn: ReconstructFn | None = None, +) -> None: + log.warning("register_opaque_type is deprecated, use register_custom_class instead") + register_custom_class( + cls, + typ=typ, + hoist=hoist, + guard_fn=guard_fn, + members=members, + reconstruct_fn=reconstruct_fn, + ) + + +# Enums are always opaque constant types. +register_custom_class(Enum, typ="constant") + + +def is_custom_class_obj(value: object) -> TypeIs[OpaqueType]: + if is_custom_class(type(value)): + return True + from torch._library.fake_class_registry import FakeScriptObject + + if isinstance(value, FakeScriptObject): + return is_custom_class(type(value.real_obj)) + return False + + +def is_opaque_value(value: object) -> TypeIs[OpaqueType]: + log.warning("is_opaque_value is deprecated, use is_custom_class_obj instead") + return is_custom_class_obj(value) + + +def should_hoist(cls: Any) -> bool: + info = _resolve_opaque_type_info(cls) + if info is None: + return False + return info.hoist + + +def get_reconstruct_fn(cls: type[CustomClassBase]) -> ReconstructFn | None: + info = _resolve_opaque_type_info(cls) + if info is None: + return None + return info.reconstruct_fn + + +def has_members(cls: Any) -> bool: + info = _resolve_opaque_type_info(cls) + if info is None: + return False + return len(info.members) > 0 + + +def is_custom_class(cls: type[Any] | str) -> bool: + """ + Checks if the given type is a registered custom class. + Also returns True for subclasses of registered custom classes. + """ + if isinstance(cls, str): + return torch._C._is_opaque_type_registered(cls) + + if not isinstance(cls, type): + log.warning("Passed invalid type `%s` to is_custom_class, returning False", cls) + return False + + info = _resolve_opaque_type_info(cls) + if info is None: + return False + + return torch._C._is_opaque_type_registered(info.class_name) + + +def is_opaque_type(cls: type[Any] | str) -> bool: + log.warning("is_opaque_type is deprecated, use is_custom_class instead") + return is_custom_class(cls) + + +def is_opaque_constant_type(cls: type[Any] | str) -> bool: + """ + Checks if the given type is an opaque **constant** type. + See Note [Opaque Objects] for more information. + """ + if not is_custom_class(cls): + return False + + if isinstance(cls, str): + return _OPAQUE_TYPES_BY_NAME[cls].opaque_typ == "constant" + + info = _resolve_opaque_type_info(cls) + if info is None: + return False + return info.opaque_typ == "constant" + + +def is_opaque_value_type(cls: type[Any] | str) -> bool: + log.warning( + "is_opaque_value_type is deprecated, use is_opaque_constant_type instead" + ) + return is_opaque_constant_type(cls) + + +def is_opaque_symbolic_type(cls: Any) -> bool: + """ + Checks if the given type is an opaque **symbolic** type. + See Note [Opaque Objects] for more information. + """ + if not is_custom_class(cls): + return False + + if isinstance(cls, str): + return _OPAQUE_TYPES_BY_NAME[cls].opaque_typ == "symbolic" + + info = _resolve_opaque_type_info(cls) + if info is None: + return False + return info.opaque_typ == "symbolic" + + +def is_opaque_reference_type(cls: Any) -> bool: + log.warning( + "is_opaque_reference_type is deprecated, use is_opaque_symbolic_type instead" + ) + return is_opaque_symbolic_type(cls) + + +def get_opaque_obj_repr(obj: Any) -> tuple[str, dict[str, type]]: + """ + Get the FX-evaluable repr for an opaque object and collect required globals. + + Objects must implement __fx_repr__() which should return: + (repr_string, dict_mapping_name_to_type) + + where repr_string is an evaluable string representation and + dict_mapping_name_to_type maps the names used in repr_string to their types. + + For example, if repr_string is "Foo(bar=Bar(1))", the dict should be: + {"Foo": Foo, "Bar": Bar} + """ + + # Enums are special cased + if isinstance(obj, Enum): + cls = type(obj) + return f"{cls.__name__}.{obj.name}", {cls.__name__: cls} + + if not hasattr(obj, "__fx_repr__"): + raise TypeError( + f"Value-type opaque object of type {obj} is " + "expected to have a `__fx_repr__` method " + "implementation as we will use this to reconstruct " + "the object in the FX codegen. __fx_repr__ should return " + "a tuple of (repr_string, dict[str, type])." + ) + + repr_str, globals_dict = obj.__fx_repr__() + + if not isinstance(repr_str, str): + raise TypeError( + f"__fx_repr__ for {type(obj).__name__} must return a string as the " + f"first element, got {type(repr_str).__name__}" + ) + + if not isinstance(globals_dict, dict): + raise TypeError( + f"__fx_repr__ for {type(obj).__name__} must return a dict as the " + f"second element, got {type(globals_dict).__name__}" + ) + + return repr_str, globals_dict + + +def get_opaque_obj_info(cls: Any) -> _OpaqueTypeInfo | None: + if not is_custom_class(cls): + return None + + if isinstance(cls, str): + return _OPAQUE_TYPES_BY_NAME[cls] + + return _resolve_opaque_type_info(cls) + + +def get_member_type(cls: Any, member_name: str) -> MemberType | None: + """ + Get the MemberType for a specific member of an opaque object class. + + Args: + cls: The opaque object class (or its string name) + member_name: The name of the member to query + + Returns: + MemberType if the member is registered, None otherwise + """ + info = get_opaque_obj_info(cls) + if info is None: + return None + return info.members.get(member_name) diff --git a/.venv/lib/python3.12/site-packages/torch/_library/simple_registry.py b/.venv/lib/python3.12/site-packages/torch/_library/simple_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..2f6950e982bedcf7fa7eb89f2f50784b3e23fd8a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/simple_registry.py @@ -0,0 +1,147 @@ +from collections.abc import Callable +from typing import Any + +from torch.utils._ordered_set import OrderedSet + +from .effects import EffectHolder +from .fake_impl import FakeImplHolder +from .utils import RegistrationHandle + + +__all__ = [ + "SimpleLibraryRegistry", + "SimpleOperatorEntry", + "singleton", + "SymmMemArgsHolder", +] + + +class SimpleLibraryRegistry: + """Registry for the "simple" torch.library APIs + + The "simple" torch.library APIs are a higher-level API on top of the + raw PyTorch DispatchKey registration APIs that includes: + - fake impl + + Registrations for these APIs do not go into the PyTorch dispatcher's + table because they may not directly involve a DispatchKey. For example, + the fake impl is a Python function that gets invoked by FakeTensor. + Instead, we manage them here. + + SimpleLibraryRegistry is a mapping from a fully qualified operator name + (including the overload) to SimpleOperatorEntry. + """ + + def __init__(self) -> None: + self._data: dict[str, SimpleOperatorEntry] = {} + + def find(self, qualname: str) -> "SimpleOperatorEntry": + res = self._data.get(qualname, None) + if res is None: + self._data[qualname] = res = SimpleOperatorEntry(qualname) + return res + + def get(self, qualname: str) -> "SimpleOperatorEntry | None": + return self._data.get(qualname, None) + + +singleton: SimpleLibraryRegistry = SimpleLibraryRegistry() + + +class SimpleOperatorEntry: + """This is 1:1 to an operator overload. + + The fields of SimpleOperatorEntry are Holders where kernels can be + registered to. + """ + + def __init__(self, qualname: str) -> None: + self.qualname: str = qualname + self.fake_impl: FakeImplHolder = FakeImplHolder(qualname) + self.torch_dispatch_rules: GenericTorchDispatchRuleHolder = ( + GenericTorchDispatchRuleHolder(qualname) + ) + + self.effect: EffectHolder = EffectHolder(qualname) + self.symm_mem_args: SymmMemArgsHolder = SymmMemArgsHolder(qualname) + + # For compatibility reasons. We can delete this soon. + @property + def abstract_impl(self) -> FakeImplHolder: + return self.fake_impl + + +class GenericTorchDispatchRuleHolder: + def __init__(self, qualname: str) -> None: + self._data: dict[type, Callable[..., Any]] = {} + self.qualname: str = qualname + + def register( + self, torch_dispatch_class: type, func: Callable[..., Any] + ) -> RegistrationHandle: + if self.find(torch_dispatch_class): + raise RuntimeError( + f"{torch_dispatch_class} already has a `__torch_dispatch__` rule registered for {self.qualname}" + ) + self._data[torch_dispatch_class] = func + + def deregister() -> None: + del self._data[torch_dispatch_class] + + return RegistrationHandle(deregister) + + def find(self, torch_dispatch_class: type) -> Callable[..., Any] | None: + return self._data.get(torch_dispatch_class, None) + + +class SymmMemArgsHolder: + """Tracks which arguments of an operator require symmetric memory allocation. + + Used by Inductor during lowering to automatically realize tensors as + symmetric memory buffers. + """ + + def __init__(self, qualname: str) -> None: + self._symm_mem_args: OrderedSet[str] | None = None + self.qualname: str = qualname + + def register(self, arg_names: list[str]) -> RegistrationHandle: + if not arg_names: + raise ValueError( + f"Cannot register empty arg_names list for {self.qualname}" + ) + + if self._symm_mem_args is not None: + import logging + + log = logging.getLogger(__name__) + log.warning( + "Overwriting symm_mem arg registration for %s. Old: %s, New: %s", + self.qualname, + self._symm_mem_args, + arg_names, + ) + + self._symm_mem_args = OrderedSet(arg_names) + + def deregister() -> None: + self._symm_mem_args = None + + return RegistrationHandle(deregister) + + def get(self) -> OrderedSet[str] | None: + return self._symm_mem_args + + def is_registered(self) -> bool: + return self._symm_mem_args is not None + + def is_symm_mem_arg(self, arg_name: str) -> bool: + return self._symm_mem_args is not None and arg_name in self._symm_mem_args + + +def find_torch_dispatch_rule( + op: Any, torch_dispatch_class: type +) -> Callable[..., Any] | None: + return singleton.find(op.__qualname__).torch_dispatch_rules.find( + torch_dispatch_class + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_library/triton.py b/.venv/lib/python3.12/site-packages/torch/_library/triton.py new file mode 100644 index 0000000000000000000000000000000000000000..41c91509ada978a68925d4f7cc2c8b3ec507e377 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/triton.py @@ -0,0 +1,623 @@ +import ast +import contextlib +import inspect +import logging +import threading +from collections.abc import Callable, Generator, Iterable +from typing import Any + +from torch.utils._exposed_in import exposed_in + +from .custom_ops import custom_op, CustomOpDef +from .infer_schema import infer_schema + + +logger = logging.getLogger(__name__) + +triton_ops_to_kernels: dict[str, list[object]] = {} + + +def get_triton_kernels_for_op(name: str) -> list[object]: + return triton_ops_to_kernels.get(name, []) + + +def get_inner_triton_kernels(fn: Callable[..., Any]) -> list[object]: + """ + Inspect the source of an arbitrary callable passed to torch._library.triton_op, + and grab all of the triton kernels that are wrapped inside of it. + + This function traces local variable assignments to handle patterns like: + kernel_fn = _my_kernel # global JITFunction + wrapped = some_wrapper(kernel_fn) + capture_triton(wrapped)[grid](...) + + It also recursively analyzes called functions to find triton kernels hidden + behind helper function calls. + + That said, it is best effort. There are cases (e.g., recursion > MAX_RECURSION_DEPTH) + that are not accounted for, so keep that in mind. + """ + + # prevent infinite recursion + MAX_RECURSION_DEPTH = 5 + + def find_triton_kernels( + fn: Callable[..., Any], + visited_fns: set[int] | None = None, + depth: int = 0, + ) -> list[object]: + try: + from triton.runtime.autotuner import Autotuner + from triton.runtime.jit import JITFunction + except ImportError: + logger.warning("Triton not available, find_triton_kernels = []") + return [] + + # unwrap decorated fn's (e.g., @lru_cache) to get the original + fn = inspect.unwrap(fn) + + # init visited set and check for cycles/depth limit + if visited_fns is None: + visited_fns = set() + + fn_id = id(fn) + if fn_id in visited_fns: + return [] + if depth > MAX_RECURSION_DEPTH: + logger.debug( + "reached max recursion depth (%s) in find_triton_kernels", + MAX_RECURSION_DEPTH, + ) + return [] + + visited_fns.add(fn_id) + + try: + source = inspect.getsource(fn) + except (OSError, TypeError): + return [] # Source code not available + + from torch._inductor.utils import IndentedBuffer + + buffer = IndentedBuffer() + buffer.splice(source, strip=True) + tree = ast.parse(buffer.getrawvalue()) + + # Visitor to collect function calls, assignments, and triton kernels + class Visitor(ast.NodeVisitor): + def __init__(self) -> None: + self.triton_kernels: list[Any] = [] + # track local variable assignments: var_name -> list of RHS expressions + self.assignments: dict[str, list[ast.expr]] = {} + # track function calls + self.called_functions: list[str] = [] + # track return statement expressions + self.return_exprs: list[ast.expr] = [] + + def visit_Assign(self, node: ast.Assign) -> None: + for target in node.targets: + if isinstance(target, ast.Name): + self.assignments.setdefault(target.id, []).append(node.value) + self.generic_visit(node) + + def visit_Return(self, node: ast.Return) -> None: + if node.value is not None: + self.return_exprs.append(node.value) + self.generic_visit(node) + + def visit_Call(self, node: ast.Call) -> None: + triton_func_names = ("capture_triton", "wrap_triton") + if isinstance(node.func, ast.Attribute): + attr = node.func + if isinstance(attr.value, ast.Attribute): + if ( + isinstance(attr.value.value, ast.Name) + and attr.value.value.id == "torch" + and attr.value.attr == "_library" + and attr.attr in triton_func_names + ): + if node.args and isinstance(node.args[0], ast.Name): + self.triton_kernels.append(node.args[0].id) + elif ( + isinstance(attr.value.value, ast.Attribute) + and isinstance(attr.value.value.value, ast.Name) + and attr.value.value.value.id == "torch" + and attr.value.value.attr == "ops" + ): + self.called_functions.append( + f"{attr.value.attr}::{attr.attr}" + ) + # Catch capture_triton, wrap_triton that's been + # imported directly + elif isinstance(node.func, ast.Name): + if node.func.id in triton_func_names: + if node.args and isinstance(node.args[0], ast.Name): + self.triton_kernels.append(node.args[0].id) + else: + # track regular function calls for recursive analysis + self.called_functions.append(node.func.id) + + self.generic_visit(node) + + collector = Visitor() + collector.visit(tree) + + def extract_names_from_expr(expr: ast.expr) -> list[str]: + """Extract all Name references from an AST expression.""" + names: list[str] = [] + + class NameExtractor(ast.NodeVisitor): + def visit_Name(self, node: ast.Name) -> None: + names.append(node.id) + + def visit_Call(self, node: ast.Call) -> None: + # for function calls, visit the function and all args + self.generic_visit(node) + + NameExtractor().visit(expr) + return names + + def resolve_to_kernel(obj: object) -> object | None: + """Check if obj is a triton kernel or wrapper and return the kernel.""" + if isinstance(obj, (JITFunction, Autotuner)): + return obj + # handle wrappers that have a .fn attribute pointing to JITFunction + if callable(obj) and hasattr(obj, "fn"): + inner = obj.fn + if isinstance(inner, JITFunction): + return inner + return None + + def build_namespace(func_obj: object) -> dict[str, Any]: + """Build a combined namespace from a function's globals and closures.""" + # unwrap decorated fns (e.g., @lru_cache) + if callable(func_obj): + try: + func_obj = inspect.unwrap(func_obj) + except ValueError: + pass + if not callable(func_obj) or not hasattr(func_obj, "__code__"): + return {} + func_closure_vars = inspect.getclosurevars(func_obj) + namespace: dict[str, Any] = {} + namespace.update(func_closure_vars.builtins) + namespace.update(func_closure_vars.globals) + namespace.update(func_closure_vars.nonlocals) + if hasattr(func_obj, "__globals__"): + namespace.update(func_obj.__globals__) + return namespace + + all_names = build_namespace(fn) + + def resolve_names_to_kernels( + names: list[str], + namespace: dict[str, Any], + assignments: dict[str, list[ast.expr]] | None = None, + visited: set[str] | None = None, + ) -> list[object]: + """ + Resolve a list of names to triton kernels using the given namespace. + """ + if visited is None: + visited = set() + + results: list[object] = [] + for name in names: + if name in visited: + continue + visited.add(name) + + if name in namespace: + obj = namespace[name] + kernel = resolve_to_kernel(obj) + if kernel is not None: + results.append(kernel) + continue + # recurse into callable objects (factory fn's), + # unwrapping decorators if applicable + if callable(obj): + try: + unwrapped = inspect.unwrap(obj) + except ValueError: + unwrapped = obj + if hasattr(unwrapped, "__code__"): + nested = find_triton_kernels( + unwrapped, visited_fns, depth + 1 + ) + if nested: + results.extend(nested) + continue + logger.debug("failed to resolve %s to a triton kernel", name) + elif assignments is not None and name in assignments: + # trace through local assignments + for rhs_expr in assignments[name]: + referenced = extract_names_from_expr(rhs_expr) + traced = resolve_names_to_kernels( + referenced, namespace, assignments, visited + ) + results.extend(traced) + else: + logger.debug("%s not found in namespace or assignments", name) + + return results + + # resolve kernel names, tracing through local variables if needed + resolved: list[object] = [] + seen_ids: set[int] = set() + + names_to_resolve: list[str] = list(collector.triton_kernels) + for expr in collector.return_exprs: + names_to_resolve.extend(extract_names_from_expr(expr)) + + for name in names_to_resolve: + traced_objects = resolve_names_to_kernels( + [name], all_names, collector.assignments + ) + for obj in traced_objects: + obj_id = id(obj) + if obj_id not in seen_ids: + seen_ids.add(obj_id) + resolved.append(obj) + + for func_name in collector.called_functions: + func_obj = all_names.get(func_name) + + if func_obj is None: + from torch._library.custom_ops import OPDEFS + + if func_name in OPDEFS: + func_obj = OPDEFS[func_name]._abstract_fn + + # skip if not a callable or if it's a triton kernel itself + if func_obj is None or not callable(func_obj): + continue + + # skip built-in functions and C extensions (they can't contain triton kernels) + if not hasattr(func_obj, "__code__"): + continue + + try: + nested_kernels = find_triton_kernels(func_obj, visited_fns, depth + 1) + for kernel in nested_kernels: + kernel_id = id(kernel) + if kernel_id not in seen_ids: + seen_ids.add(kernel_id) + resolved.append(kernel) + except Exception: + logger.debug( + "failed to analyze called function %s", func_name, exc_info=True + ) + + return resolved + + return find_triton_kernels(fn) + + +@exposed_in("torch.library") +def triton_op( + name: str, + fn: Callable | None = None, + /, + *, + mutates_args: str | Iterable[str], + schema: str | None = None, +) -> Callable: + """Create a custom operator whose implementation is backed by 1+ triton kernels. + + This is a more structured way of using triton kernels with PyTorch. + Prefer using triton kernels with no ``torch.library`` custom operator wrappers + (like :func:`torch.library.custom_op`, :func:`torch.library.triton_op`) because + that is simpler; + only use :func:`torch.library.custom_op`/:func:`torch.library.triton_op` if you + want to create an operator that behaves like PyTorch built-in operators. + For example, you may use a ``torch.library`` wrapper API to define the + behavior of the triton kernel when passed a tensor subclass or under + a TorchDispatchMode. + + Use :func:`torch.library.triton_op` instead of :func:`torch.library.custom_op` + when the implementation + consists of 1+ triton kernels. :func:`torch.library.custom_op` treats + custom operators as opaque (:func:`torch.compile` and + :func:`torch.export.export` will never trace into them), but ``triton_op`` + makes the implementation visible to these subsystems, allowing them + to optimize the triton kernel(s). + + Note that ``fn`` must only consist of calls to PyTorch-understood + operators and triton kernels. Any triton kernels called inside ``fn`` + must be wrapped in a call to :func:`torch.library.wrap_triton`. + + Args: + name (str): A name for the custom op that looks like "{namespace}::{name}", + e.g. "mylib::my_linear". The name is used as the op's stable identifier + in PyTorch subsystems (e.g. torch.export, FX graphs). + To avoid name collisions, please use your project name as the namespace; + e.g. all custom ops in pytorch/fbgemm use "fbgemm" as the namespace. + mutates_args (Iterable[str] or "unknown"): The names of args that the function mutates. + This MUST be accurate, otherwise, the behavior is undefined. If "unknown", + it pessimistically assumes that all inputs to the operator are being mutated. + schema (str | None): A schema string for the operator. If None + (recommended) we'll infer a schema for the operator from its type + annotations. We recommend letting us infer a schema unless you + have a specific reason not to. + Example: "(Tensor x, int y) -> (Tensor, Tensor)". + + Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> import torch + >>> from torch.library import triton_op, wrap_triton + >>> + >>> import triton + >>> from triton import language as tl + >>> + >>> @triton.jit + >>> def add_kernel( + >>> in_ptr0, + >>> in_ptr1, + >>> out_ptr, + >>> n_elements, + >>> BLOCK_SIZE: "tl.constexpr", + >>> ): + >>> pid = tl.program_id(axis=0) + >>> block_start = pid * BLOCK_SIZE + >>> offsets = block_start + tl.arange(0, BLOCK_SIZE) + >>> mask = offsets < n_elements + >>> x = tl.load(in_ptr0 + offsets, mask=mask) + >>> y = tl.load(in_ptr1 + offsets, mask=mask) + >>> output = x + y + >>> tl.store(out_ptr + offsets, output, mask=mask) + >>> + >>> @triton_op("mylib::add", mutates_args={}) + >>> def add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + >>> output = torch.empty_like(x) + >>> n_elements = output.numel() + >>> + >>> def grid(meta): + >>> return (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) + >>> + >>> # NB: we need to wrap the triton kernel in a call to wrap_triton + >>> wrap_triton(add_kernel)[grid](x, y, output, n_elements, 16) + >>> return output + >>> + >>> @torch.compile + >>> def f(x, y): + >>> return add(x, y) + >>> + >>> x = torch.randn(3, device="cuda") + >>> y = torch.randn(3, device="cuda") + >>> + >>> z = f(x, y) + >>> assert torch.allclose(z, x + y) + + """ + + def dec(fn: Callable[..., object]) -> CustomOpDef: + def backend_fn(*args, **kwargs): # type: ignore[no-untyped-def] + # Optimization: we're passing regular Tensors into the triton kernel, so + # no need to go through HOP dispatch + with set_wrap_triton_enabled(False): + return fn(*args, **kwargs) + + result = custom_op( + name, + backend_fn, + mutates_args=mutates_args, + schema=( + schema + if schema is not None + else infer_schema(fn, mutates_args=mutates_args) + ), + ) + from .._subclasses.functional_tensor import FunctionalTensorMode + + # We require that the user pass us a function that is make_fx traceable, + # so we can just register it as the Fake/meta kernel. + result.register_fake(fn) + + # We decompose the operator when FunctionalTensorMode is active. + # The goal is to decompose the operator in AOTDispatcher. + # - With torch.compile, this means that the backend (usually Inductor) + # can see a call to the triton kernel(s) and so it can directly optimize + # them by inlining them into the lowering process. + def functional_decomp( # type: ignore[no-untyped-def] + mode, op, types, args, kwargs + ): + # NOTE [Export custom triton op] + # For torch.export (strict and non-strict), we don't do functional decomposition. + # Instead, we preserve the custom triton ops as custom ops. This is because we want + # the exported program to be high-level and serializable. If we decompose + # the custom op to a functional hop and make it a node in exported program, + # we need to figure out ways of serializing the hop and its arguments, which can be triton.jited + # functions and triton dtypes. This is undesirable because: + # - it can be tedious to maintain a layer that serializes the jited function (e.g. with a string) and dtypes. + # - exported program will contain the implementation detail (e.g. triton source code) for a specific + # backend (GPU), which is probably at a wrong level of abstraction. + # - changes to triton or the serialization logic for triton arguments can be BC breaking + # + # In the short term, we expect users to have a separate aot_compile stage that compiles the exported program + # into a Cubin file on the same machine that users call export, which does autotuning and removes triton + # dependency and serve the model with Cubin. This guarantees that triton changes won't break BC. + # In the long term, we may export multiple cubins for the triton op directly + from torch.export._trace import custom_triton_ops_decomposition_disabled + + if custom_triton_ops_decomposition_disabled(): + return mode.__torch_dispatch__(op, types, args, kwargs) + else: + # TODO: https://github.com/pytorch/pytorch/issues/160333 + # We should deduplicate the unrecognized_types logic. + import torch._subclasses + + unrecognized_types = [ + t + for t in types + if not issubclass(t, torch._subclasses.FakeTensor) + and t + not in [ + torch.Tensor, + torch._subclasses.functional_tensor.FunctionalTensor, + ] + ] + + if unrecognized_types: + return NotImplemented + with mode: + return fn(*args, **kwargs) + + triton_kernels = get_inner_triton_kernels(fn) + triton_ops_to_kernels[name] = triton_kernels + result.register_torch_dispatch(FunctionalTensorMode, functional_decomp) + return result + + if fn is None: + return dec + else: + return dec(fn) + + +wrap_triton_enabled = threading.local() +wrap_triton_enabled_default = True + + +@contextlib.contextmanager +def set_wrap_triton_enabled(enabled: bool) -> Generator[None, None, None]: + """If triton kernels annotated with @wrap_triton should dispatch via HOP + or go straight to the triton kernel execution. + + We have this switch because eager-mode performance of HOP dispatch is slow + enough to matter (~1ms) and we know that wrap_triton isn't necessary in + some situations (eager-mode with regular Tensors) + """ + try: + prev = is_wrap_triton_enabled() + wrap_triton_enabled.value = enabled + yield + finally: + wrap_triton_enabled.value = prev + + +def is_wrap_triton_enabled() -> bool: + return getattr(wrap_triton_enabled, "value", wrap_triton_enabled_default) + + +def _is_interpreted_triton_kernel(triton_kernel: Callable) -> bool: + try: + from triton.runtime.interpreter import InterpretedFunction + except ImportError: + return False + + return isinstance(triton_kernel, InterpretedFunction) + + +def _has_interpreted_triton_autotuner(triton_kernel: Callable) -> bool: + try: + from triton.runtime.autotuner import Autotuner, Heuristics + from triton.runtime.interpreter import InterpretedFunction + except ImportError: + return False + + seen: set[int] = set() + kernel: Any = triton_kernel + while isinstance(kernel, (Autotuner, Heuristics)): + kernel_id = id(kernel) + if kernel_id in seen: + return False + seen.add(kernel_id) + kernel = kernel.fn + return isinstance(kernel, InterpretedFunction) + + +def capture_triton(triton_kernel: Callable, /) -> Any: + """This API has been renamed to wrap_triton""" + return wrap_triton(triton_kernel) + + +@exposed_in("torch.library") +def wrap_triton(triton_kernel: Callable, /) -> Any: + """Allows capture of a triton kernel into a graph via make_fx or + non-strict ``torch.export``. + + These technologies perform Dispatcher-based tracing (via + ``__torch_dispatch__``) and cannot see calls to raw triton kernels. + The ``wrap_triton`` API wraps a triton kernel into a callable that + can actually be traced into a graph. + + Please use this API together with :func:`torch.library.triton_op`. + + Examples: + + >>> # xdoctest: +SKIP + >>> import torch + >>> import triton + >>> from triton import language as tl + >>> from torch.fx.experimental.proxy_tensor import make_fx + >>> from torch.library import wrap_triton + >>> + >>> @triton.jit + >>> def add_kernel( + >>> in_ptr0, + >>> in_ptr1, + >>> out_ptr, + >>> n_elements, + >>> BLOCK_SIZE: "tl.constexpr", + >>> ): + >>> pid = tl.program_id(axis=0) + >>> block_start = pid * BLOCK_SIZE + >>> offsets = block_start + tl.arange(0, BLOCK_SIZE) + >>> mask = offsets < n_elements + >>> x = tl.load(in_ptr0 + offsets, mask=mask) + >>> y = tl.load(in_ptr1 + offsets, mask=mask) + >>> output = x + y + >>> tl.store(out_ptr + offsets, output, mask=mask) + >>> + >>> def add(x, y): + >>> output = torch.empty_like(x) + >>> n_elements = output.numel() + >>> + >>> def grid_fn(meta): + >>> return (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) + >>> + >>> wrap_triton(add_kernel)[grid_fn](x, y, output, n_elements, 16) + >>> return output + >>> + >>> x = torch.randn(3, device="cuda") + >>> y = torch.randn(3, device="cuda") + >>> gm = make_fx(add)(x, y) + >>> print(gm.code) + >>> # def forward(self, x_1, y_1): + >>> # empty_like = torch.ops.aten.empty_like.default(x_1, pin_memory = False) + >>> # triton_kernel_wrapper_mutation_proxy = triton_kernel_wrapper_mutation( + >>> # kernel_idx = 0, constant_args_idx = 0, + >>> # grid = [(1, 1, 1)], kwargs = { + >>> # 'in_ptr0': x_1, 'in_ptr1': y_1, 'out_ptr': empty_like, + >>> # 'n_elements': 3, 'BLOCK_SIZE': 16 + >>> # }) + >>> # return empty_like + + """ + from triton.runtime.autotuner import Autotuner + from triton.runtime.jit import JITFunction + + from torch._higher_order_ops.triton_kernel_wrap import TraceableTritonKernelWrapper + + if isinstance(triton_kernel, JITFunction): + if not is_wrap_triton_enabled(): + return triton_kernel + return TraceableTritonKernelWrapper(triton_kernel, None, None) + + if isinstance(triton_kernel, Autotuner): + # TRITON_INTERPRET=1 can make @triton.autotune wrap an + # InterpretedFunction. It is eager-launchable but lacks the JIT + # metadata the traceable wrapper needs. + if _has_interpreted_triton_autotuner(triton_kernel): + return triton_kernel + if not is_wrap_triton_enabled(): + return triton_kernel + return TraceableTritonKernelWrapper(triton_kernel, None, None) + + # TRITON_INTERPRET=1 makes @triton.jit return InterpretedFunction. + if _is_interpreted_triton_kernel(triton_kernel): + return triton_kernel + + raise RuntimeError( + "wrap_triton only works on functions annotated with triton.jit or triton.autotune" + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_library/utils.py b/.venv/lib/python3.12/site-packages/torch/_library/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1b8591606c90f22b6650f4bbaf26c92d5abc922a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_library/utils.py @@ -0,0 +1,708 @@ +# mypy: allow-untyped-defs +import dataclasses +import inspect +import sys +from collections.abc import Callable, Iterable, Iterator +from typing import Any, Literal, overload + +import torch +import torch.utils._pytree as pytree +import torchgen +from torch import _C, _utils_internal +from torch._ops import OpOverload + + +@dataclasses.dataclass +class Kernel: + """Models a (function, source location)""" + + func: Callable + source: str + + def __call__(self, *args, **kwargs): + return self.func(*args, **kwargs) + + +class RegistrationHandle: + """Does something when someone calls .destroy() on it""" + + def __init__(self, on_destroy: Callable): + self._on_destroy = on_destroy + + def destroy(self) -> None: + self._on_destroy() + + +def get_source(stacklevel: int) -> str: + """Get a string that represents the caller. + + Example: "/path/to/foo.py:42" + + Use stacklevel=1 to get the caller's source + Use stacklevel=2 to get the caller's caller's source + etc. + """ + frame = inspect.getframeinfo(sys._getframe(stacklevel)) + source = f"{frame.filename}:{frame.lineno}" + return source + + +def parse_namespace(qualname: str) -> tuple[str, str]: + splits = qualname.split("::") + if len(splits) != 2: + raise ValueError( + f"Expected `qualname` to be of the form " + f'"namespace::name", but got {qualname}. ' + f"The qualname passed to the torch.library APIs must consist " + f"of a namespace and a name, e.g. aten::sin" + ) + return splits[0], splits[1] + + +def lookup_op(qualname: str) -> OpOverload: + namespace, name = parse_namespace(qualname) + if "." in name: + name, overload = name.split(".") + else: + overload = "default" + ns = getattr(torch.ops, namespace) + packet = getattr(ns, name) + return getattr(packet, overload) + + +def is_builtin(op: OpOverload) -> bool: + if not isinstance(op, OpOverload): + raise AssertionError(f"op must be OpOverload, got {type(op)}") + return op.namespace in {"aten", "prim", "prims"} + + +def is_out(op: OpOverload) -> bool: + """Returns True if the operator has "out" semantics: its mutable arguments + are write-only output buffers that are not read from.""" + return torch.Tag.out in op.tags + + +def is_inplace(op: OpOverload) -> bool: + """Returns True if the operator has inplace semantics: it mutates its first + positional argument and returns it.""" + return torch.Tag.inplace in op.tags + + +def is_functional_schema(schema: Any, *, allow_valid_view: bool = False) -> bool: + """Check if the schema is functional. + + An operator is functional if: + - it does not mutate any of its inputs + - If no view are allowed + - it does not return a view on any of its inputs + - If valid views are allowed + - it is not a view or a view with a single input Tensor and single output Tensor + - it has at least one return + """ + + def is_functional(schema): + if schema.is_mutable: + return False + rets = schema.returns + is_non_mutating_view = len(rets) > 0 and any( + r.alias_info is not None and not r.alias_info.is_write for r in rets + ) + num_tensor_inputs = 0 + num_tensor_outputs = 0 + + if isinstance(schema, torch.FunctionSchema): + for arg in schema.arguments: + if isinstance(arg.type, torch.TensorType): + num_tensor_inputs += 1 + + for ret in schema.returns: + if isinstance(ret.type, torch.TensorType): + num_tensor_outputs += 1 + + elif isinstance(schema, torchgen.model.FunctionSchema): + for argument in schema.arguments.flat_non_out: + if argument.type.is_tensor_like(): + num_tensor_inputs += 1 + + for ret_arg in schema.returns: + if ret_arg.type.is_tensor_like(): + num_tensor_outputs += 1 + + if is_non_mutating_view: + return allow_valid_view and ( + num_tensor_inputs == 1 and num_tensor_outputs == 1 + ) + if not schema.returns: + return False + return True + + if isinstance(schema, torch._C.FunctionSchema): + return is_functional(schema) + + # Lazy import because not all PyTorch builds have torchgen + from torchgen.model import FunctionSchema + + if isinstance(schema, str): + schema = FunctionSchema.parse(schema) + if not isinstance(schema, FunctionSchema): + raise AssertionError(f"schema must be FunctionSchema, got {type(schema)}") + return is_functional(schema) + + +# should be torch._C.JitType but that annotation is busted +def is_tensorlist_like_type(typ: Any) -> bool: + return ( + typ == _C.ListType(_C.TensorType.get()) + or typ == _C.ListType(_C.OptionalType(_C.TensorType.get())) + or typ == _C.OptionalType(_C.ListType(_C.TensorType.get())) + or typ == _C.OptionalType(_C.ListType(_C.OptionalType(_C.TensorType.get()))) + ) + + +# should be torch._C.JitType but that annotation is busted +def is_tensor_like_type(typ: Any) -> bool: + return typ == _C.TensorType.get() or typ == _C.OptionalType(_C.TensorType.get()) + + +def mutates_and_returns_first_arg(op: OpOverload): + """Check if an op is an inplace aten op, i.e. it mutates and returns the first arg. + + TODO: torchgen/model.py's FunctionSchema.parse is the source of truth for this, + but not all PyTorch builds have torchgen (due to the yaml dependency being weird). + Figure this out. + + Example: add_(Tensor(a!) x, Tensor y) -> Tensor(a) + """ + if op.namespace != "aten": + return False + schema = op._schema + if len(schema.returns) != 1: + return False + if schema.returns[0].alias_info is None: + return False + alias_set = schema.returns[0].alias_info.after_set + if len(alias_set) != 1: + return False + loc = next(iter(alias_set)) + if len(schema.arguments) < 1: + return False + first_arg = schema.arguments[0] + if first_arg.alias_info is None: + return False + if not first_arg.alias_info.is_write: + return False + alias_set = first_arg.alias_info.after_set + if len(alias_set) != 1: + return False + if loc != next(iter(alias_set)): + return False + for arg in schema.arguments[1:]: + if arg.alias_info is not None: + return False + return True + + +def fill_defaults(schema, args, kwargs): + new_args = [] + new_kwargs = {} + for i in range(len(schema.arguments)): + info = schema.arguments[i] + if info.kwarg_only: + if info.name in kwargs: + new_kwargs[info.name] = kwargs[info.name] + else: + new_kwargs[info.name] = info.default_value + else: + if i < len(args): + new_args.append(args[i]) + else: + new_args.append(info.default_value) + return tuple(new_args), new_kwargs + + +def zip_schema( + schema: _C.FunctionSchema, args: tuple[Any, ...], kwargs: dict[str, Any] +) -> Iterable[tuple[_C.Argument, Any]]: + """zips schema.arguments and (args, kwargs) together. + + Assumes that (args, kwargs) were the inputs to some torch._ops.OpOverload: + that is, (args, kwargs) must be bindable to the schema (args, kwargs). + """ + if len(schema.arguments) < len(args) + len(kwargs): + raise AssertionError( + f"schema has {len(schema.arguments)} arguments but got {len(args)} args and {len(kwargs)} kwargs" + ) + for i in range(len(schema.arguments)): + info = schema.arguments[i] + if info.kwarg_only: + if info.name in kwargs: + yield info, kwargs[info.name] + continue + if i >= len(args): + if not info.kwarg_only and info.name in kwargs: + yield info, kwargs[info.name] + # args that are equal to their default values are not populated + # if they are followed by args that are equal to their defaults. + # Skip these. + continue + yield info, args[i] + return + + +def hop_schema_from_fx_node(node): + from torchgen.gen_schema_utils import FunctionSchemaGen + + hop = node.target + if not isinstance(hop, torch._ops.HigherOrderOperator): + raise RuntimeError("fx_node's target must be a hop.") + + def _collect_example_val(node): + meta_val = node.meta.get("val", None) + if meta_val is None: + if node.op != "get_attr": + raise AssertionError( + f"node.op must be 'get_attr' when val is None, got {node.op!r}" + ) + meta_val = getattr(node.graph.owning_module, node.target) + return meta_val + + example_inputs = [] + for arg in node.args: + if isinstance(arg, (torch.fx.Node, torch.fx.node.Node)): + example_inputs.append(_collect_example_val(arg)) + elif isinstance( + arg, (torch.fx.immutable_collections.immutable_list, list, tuple) + ): + example_inputs.append([_collect_example_val(x) for x in arg]) + else: + raise RuntimeError(f"Unsupported arg type {type(arg)}") + + # Bound the arguments to make sure number of inputs are correct + bound_args: inspect.BoundArguments = inspect.signature(hop.__call__).bind( + *example_inputs + ) + + # We treat example_output as a single value in return. This is to differentiate 1. return a single val + # vs 2. return a tuple with one element. + example_output = _collect_example_val(node) + return FunctionSchemaGen.from_example( + hop._name, tuple(bound_args.arguments.items()), (list(example_output),) + ) + + +def can_generate_trivial_fake_impl(op: OpOverload) -> bool: + if not isinstance(op, OpOverload): + raise AssertionError(f"op must be OpOverload, got {type(op)}") + if is_builtin(op): + # We control the built-ins. These may (in rare cases) + # do input metadata mutation (which we have banned on custom ops) + return False + schema = op._schema + if is_out(op): + # Tag.out ops have a trivial fake impl: return the out= args in order. + return True + if is_inplace(op): + # Tag.inplace ops have a trivial fake impl: return the mutated first arg. + return True + # It's suspicious if the op is not mutable but returns nothing, so we return False out of an abundance of caution + if not schema.is_mutable: + return False + if len(schema.returns) > 0: + return False + # If the op returns nothing, then it has a trivial fake impl. + return True + + +def generate_trivial_fake_impl(op: OpOverload, *args, **kwargs): + """Generate the result of a trivial fake impl for the given op. + + For ops with no returns: returns None. + For Tag.out ops: returns the out= kwargs in declaration order. + For Tag.inplace ops: returns the first positional arg. + """ + if is_out(op): + schema = op._schema + _, out_kwarg_names = mutated_args_kwargs(schema) + out_args = tuple(kwargs[name] for name in out_kwarg_names) + if len(out_args) == 1: + return out_args[0] + return out_args + if is_inplace(op): + return args[0] + return None + + +def requires_set_python_module() -> bool: + """If an op was defined in C++ and extended from Python using the + torch.library APIs, returns if we require that there have been a + m.set_python_module("mylib.ops") call from C++ that associates + the C++ op with a python module. + """ + return getattr(_utils_internal, "REQUIRES_SET_PYTHON_MODULE", True) + + +def handle_dispatch_mode(curr_mode, op_overload, *args, **kwargs): + if not isinstance(curr_mode, torch.utils._python_dispatch.TorchDispatchMode): + raise AssertionError( + f"curr_mode must be TorchDispatchMode, got {type(curr_mode)}" + ) + args_flattened, _ = torch.utils._pytree.tree_flatten((args, kwargs.values())) + # TODO: need to double check the semantics of the "types" argument to torch_dispatch. + # It's generated in PyInterpreter.cpp, but seems to be generated in two places, + # where in one case we only include tensors with the python key, and in another + # we include **all** tensors. + overload_types = [ + type(a) + for a in args_flattened + if isinstance(a, torch.Tensor) + and torch._C._dispatch_keys(a).has(torch._C.DispatchKey.Python) + ] + # TODO: check that I got these args correct (in C++, we pass in "0000"??) + + return curr_mode.__torch_dispatch__(op_overload, overload_types, args, kwargs) + + +def has_kwarg_only_args(schema: _C.FunctionSchema): + return any(a.kwarg_only for a in schema.arguments) + + +def has_kwarg_only_tensors(schema: _C.FunctionSchema): + for a in schema.arguments: + if not (is_tensor_like_type(a.type) or is_tensorlist_like_type(a.type)): + continue + if not a.kwarg_only: + continue + return True + return False + + +def has_tensor_arg(schema: _C.FunctionSchema) -> bool: + """ + Given a schema, returns True if the schema has a Tensor arg. + A Tensor arg is any arg with a type annotation that might involve Tensor. + """ + return any( + (is_tensor_like_type(a.type) or is_tensorlist_like_type(a.type)) + for a in schema.arguments + ) + + +def get_device_arg_index(schema: _C.FunctionSchema) -> int | None: + """ + Given a schema, returns the id of the `device: torch.device` argument. + If it does not exist, returns None. + """ + for index, arg in enumerate(schema.arguments): + if arg.type is _C.DeviceObjType.get() and arg.name == "device": + return index + return None + + +def iter_tensors( + args: tuple[Any], kwargs: dict[str, Any], allowed_nesting: int = 1 +) -> Iterator[torch.Tensor]: + def check(arg): + if isinstance(arg, torch.Tensor): + yield arg + elif allowed_nesting > 0 and isinstance(arg, (tuple, list)): + yield from iter_tensors(tuple(arg), {}, allowed_nesting - 1) + + for arg in args: + yield from check(arg) + for kwarg in kwargs.values(): + yield from check(kwarg) + + +def check_aliasing_constraint(name, prev, result, get_module=lambda: "???"): + """ + custom operators' outputs must not alias any inputs or other outputs. + """ + storages = {t.untyped_storage()._cdata for t in prev if isinstance(t, torch.Tensor)} + tuple_result = result + if not isinstance(result, tuple): + tuple_result = (result,) + for tensor in iter_tensors(tuple_result, {}): + key = tensor.untyped_storage()._cdata + if tensor.untyped_storage()._cdata in storages: + raise RuntimeError( + f"{name} (with implementation in {get_module()}): " + f"The output of this custom operator (1) must not " + f"also be an input to this custom operator and " + f"(2) may not alias any inputs to this custom operator " + f"or other returns. " + f"The most common way to trigger this error is if " + f"we have y = custom_op(x) and y and x are the same Tensor. " + f"Please instead return a clone of the offending output " + f"tensor(s) (e.g. return x.clone()) or refactor the custom " + f"operator to not return y." + ) + storages.add(key) + + +def _c_check_aliasing_constraint(name, args, kwargs, result, get_module=lambda: "???"): + """ + custom operators' outputs must not have any aliases + This version uses C++ implementation for perf. + Only List container is supported. + Tensors in Lists with not only Tensors are checked. + """ + tuple_result = result + if not isinstance(result, tuple): + tuple_result = (result,) + if _C._any_output_is_alias_to_input_or_output(args, kwargs, tuple_result): + raise RuntimeError( + f"{name} (with implementation in {get_module()}): " + f"The output of this custom operator (1) must not " + f"also be an input to this custom operator and " + f"(2) may not alias any inputs to this custom operator " + f"or other returns. " + f"The most common way to trigger this error is if " + f"we have y = custom_op(x) and y and x are the same Tensor. " + f"Please instead return a clone of the offending output " + f"tensor(s) (e.g. return x.clone()) or refactor the custom " + f"operator to not return y." + ) + + +class MutationChecker: + """ + Check if an operator mutated its arguments. + Usage: + + checker = MutationChecker(op, flat_args, args_spec) + op(*args, **kwargs) + checker.check() + """ + + def __init__(self, op, flat_args, args_spec): + self.op = op + self.args_spec = args_spec + self.flat_args = flat_args + self.real_pre_hashes = [ + hash_tensor(a) if isinstance(a, torch.Tensor) else None for a in flat_args + ] + + def check(self): + real_post_hashes = [ + hash_tensor(a) if isinstance(a, torch.Tensor) else None + for a in self.flat_args + ] + was_mutated = [ + not torch.equal(pre, post) + and not (pre.isnan().all() and post.isnan().all()) + if isinstance(pre, torch.Tensor) and isinstance(post, torch.Tensor) + else None + for pre, post in zip(self.real_pre_hashes, real_post_hashes) + ] + was_mutated_args, was_mutated_kwargs = pytree.tree_unflatten( + was_mutated, self.args_spec + ) + for info, was_mutated in zip_schema( + self.op._schema, was_mutated_args, was_mutated_kwargs + ): + + def check_one(info, was_mutated): + if info.is_write == was_mutated: + return + raise RuntimeError( + f"{self.op._name}: for argument '{info.name}': the operator's schema " + f"{self.op._schema} specified that " + f"the operator {'mutates' if info.is_write else 'does not mutate'} " + f"the argument, but this seems to be empirically wrong. " + f"Please make the schema and operator behavior consistent. " + f"You can specify that an operator mutates a Tensor by " + f"e.g. changing its schema type from 'Tensor name' to 'Tensor(a!) name'" + f"(use different identifiers (a, b, c, ...) for different Tensors)" + ) + + if is_tensor_like_type(info.type): + check_one(info, was_mutated) + elif is_tensorlist_like_type(info.type): + was_any_mutated = False if was_mutated is None else any(was_mutated) + check_one(info, was_any_mutated) + + +def hash_tensor(t: torch.Tensor) -> torch.Tensor: + """Some inexpensive hash. Used as a quick and dirty indicator for tensor mutation""" + return t.detach().float().mean() + + +def has_fake_kernel(op: torch._ops.OpOverload) -> bool: + """If an operator (that stays alive until FakeTensorMode) has a Fake kernel. + Don't use this if the operator decomposes before FakeTensorMode. + """ + if can_generate_trivial_fake_impl(op): + return True + name = op._name + if torch._C._dispatch_has_kernel_for_dispatch_key( + name, "CompositeImplicitAutograd" + ): + return True + opdef = torch._library.custom_ops._maybe_get_opdef(name) + if opdef is None: + # the non-torch.library.custom_op path + if torch._C._dispatch_has_kernel_for_dispatch_key( + name, "CompositeExplicitAutograd" + ): + return True + entry = torch._library.simple_registry.singleton.find(name) + if entry.fake_impl.kernel is not None: + return True + if torch._C._dispatch_has_kernel_for_dispatch_key(name, "Meta"): + return True + else: + # the torch.library.custom_op path + if opdef._abstract_fn is not None: + return True + return False + + +def mutated_args_kwargs(schema: _C.FunctionSchema) -> tuple[list[int], list[str]]: + idxs = [] + keys = [] + for i, info in enumerate(schema.arguments): + if info.alias_info is not None and info.alias_info.is_write: + if info.kwarg_only: + keys.append(info.name) + else: + idxs.append(i) + return idxs, keys + + +tags_by_priority = [ + _C.Tag.needs_exact_strides, + _C.Tag.needs_contiguous_strides, + _C.Tag.needs_fixed_stride_order, + _C.Tag.flexible_layout, +] + + +# Case 1: with_default=True (or omitted). Return type is guaranteed to be a Tag. +@overload +def get_layout_constraint_tag( + fn: Any, *, with_default: Literal[True] = True +) -> _C.Tag: ... + + +# Case 2: with_default=False. Return type can be a Tag or None. +@overload +def get_layout_constraint_tag( + fn: Any, *, with_default: Literal[False] +) -> _C.Tag | None: ... + + +def get_layout_constraint_tag(fn, *, with_default=True): + for tag in tags_by_priority: + if tag in fn.tags: + return tag + if with_default: + if is_builtin(fn): + return _C.Tag.flexible_layout + import torch._functorch + from torch._functorch import config + + return getattr(torch._C.Tag, config.custom_op_default_layout_constraint) + return None + + +# List of random functions that should be treated as impure +_RANDOM_FUNCTIONS = { + torch.rand, + torch.randn, + torch.randint, + torch.randperm, + torch.rand_like, + torch.randn_like, + torch.randint_like, + torch.normal, + torch.poisson, + torch.bernoulli, + torch.multinomial, +} + + +def is_impure( + op: Callable, + *, + args: tuple[Any, ...] | None = None, + kwargs: dict[str, Any] | None = None, + impure_random: bool = True, +) -> bool: + """ + An operator is impure if it: + - Mutates its inputs (has a mutable schema) + - Has nondeterministic/random behavior that mutates RNG state + - Is explicitly marked as effectful via torch.library._register_effectful_op + + Args: + op: The operator to check (function, OpOverload, HigherOrderOperator, etc.) + args: Optional arguments that would be passed to the callable + kwargs: Optional keyword arguments that would be passed to the callable + impure_random: Whether to treat random operations as impure (default: True) + + Returns: + bool: True if the callable has side effects, False otherwise + """ + # Import here to avoid circular dependencies + from torch._higher_order_ops.effects import _get_effect + from torch.fx.node import _side_effectful_functions + + if isinstance(op, torch._ops.OpOverloadPacket): + if op in _side_effectful_functions: + return True + default = getattr(op, "default", None) + if default is not None: + return is_impure( + default, args=args, kwargs=kwargs, impure_random=impure_random + ) + + if isinstance(op, torch._ops.OpOverload): + schema = getattr(op, "_schema", None) + if schema is not None and schema.is_mutable: + return True + + if op in _side_effectful_functions: + return True + + if _get_effect(op) is not None: + return True + + if isinstance(op, torch._ops.HigherOrderOperator): + if op in ( + torch.ops.higher_order.auto_functionalized, + torch.ops.higher_order.auto_functionalized_v2, + ): + # Check if the auto-functionalized operator (the first argument) is + # side-effectful + if args and len(args) > 0: + return args[0] in _side_effectful_functions + + if _get_effect(op) is not None: + return True + + if op in _side_effectful_functions: + return True + + return False + + # Impure since it mutates RNG state + if impure_random and getattr(op, "_nondeterministic_seeded", False): + return True + + # Handle Python random functions that don't have _nondeterministic_seeded + # but still affect global RNG state (issue #151524) + # These should be impure regardless of impure_random setting to maintain + # consistency between eager and compiled execution + # All random operations are impure to ensure consistent behavior + # between eager and compiled execution, regardless of generator usage + if op in _RANDOM_FUNCTIONS: + return True + + schema = getattr(op, "_schema", None) + if schema is not None and schema.is_mutable: + return True + + if op in _side_effectful_functions: + return True + + return False diff --git a/.venv/lib/python3.12/site-packages/torch/_linalg_utils.py b/.venv/lib/python3.12/site-packages/torch/_linalg_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ba8f4db04b88580ed3c53fba5d74b4d75324e222 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_linalg_utils.py @@ -0,0 +1,183 @@ +"""Various linear algebra utility methods for internal use.""" + +import torch +from torch import Tensor + + +def is_sparse(A: Tensor) -> bool: + """Check if tensor A is a sparse COO tensor. + + All other sparse storage formats (CSR, CSC, etc...) will return False. + """ + if isinstance(A, torch.Tensor): + return A.layout == torch.sparse_coo + + error_str = "expected Tensor" + if not torch.jit.is_scripting(): + error_str += f" but got {type(A)}" + raise TypeError(error_str) + + +def get_floating_dtype(A: Tensor) -> torch.dtype: + """Return the floating point dtype of tensor A. + + Integer types map to float32. + """ + dtype = A.dtype + if dtype in (torch.float16, torch.float32, torch.float64): + return dtype + return torch.float32 + + +def matmul(A: Tensor | None, B: Tensor) -> Tensor: + """Multiply two matrices. + + If A is None, return B. A can be sparse or dense. B is always + dense. + """ + if A is None: + return B + if is_sparse(A): + return torch.sparse.mm(A, B) + return torch.matmul(A, B) + + +def bform(X: Tensor, A: Tensor | None, Y: Tensor) -> Tensor: + """Return bilinear form of matrices: :math:`X^T A Y`.""" + return matmul(X.mT, matmul(A, Y)) + + +def qform(A: Tensor | None, S: Tensor) -> Tensor: + """Return quadratic form :math:`S^T A S`.""" + return bform(S, A, S) + + +def basis(A: Tensor) -> Tensor: + """Return orthogonal basis of A columns.""" + return torch.linalg.qr(A).Q + + +def symeig(A: Tensor, largest: bool | None = False) -> tuple[Tensor, Tensor]: + """Return eigenpairs of A with specified ordering.""" + if largest is None: + largest = False + E, Z = torch.linalg.eigh(A, UPLO="U") + # assuming that E is ordered + if largest: + E = torch.flip(E, dims=(-1,)) + Z = torch.flip(Z, dims=(-1,)) + return E, Z + + +# These functions were deprecated and removed +# This nice error message can be removed in version 1.13+ +def cholesky(input: Tensor, upper: bool = False, *, out=None) -> Tensor: + raise RuntimeError( + "This function was deprecated since version 1.9 and is now removed. " + "`torch.cholesky` is deprecated in favor of `torch.linalg.cholesky`.\n" + "L = torch.cholesky(A) should be replaced with:\n" + "L = torch.linalg.cholesky(A)\n" + "U = torch.cholesky(A, upper=True) should be replaced with:\n" + "U = torch.linalg.cholesky(A).mH" + ) + + +def matrix_rank(input, tol=None, symmetric=False, *, out=None) -> Tensor: + raise RuntimeError( + "This function was deprecated since version 1.9 and is now removed.\n" + "Please use the `torch.linalg.matrix_rank` function instead. " + "The parameter 'symmetric' was renamed in `torch.linalg.matrix_rank()` to 'hermitian'." + ) + + +def solve(input: Tensor, A: Tensor, *, out=None) -> tuple[Tensor, Tensor]: + raise RuntimeError( + "This function was deprecated since version 1.9 and is now removed. " + "`torch.solve` is deprecated in favor of `torch.linalg.solve`. " + "`torch.linalg.solve` has its arguments reversed and does not return the LU factorization.\n\n" + "To get the LU factorization see `torch.lu`, which can be used with `torch.lu_solve` or `torch.lu_unpack`.\n" + "X = torch.solve(B, A).solution " + "should be replaced with:\n" + "X = torch.linalg.solve(A, B)" + ) + + +def lstsq(input: Tensor, A: Tensor, *, out=None) -> tuple[Tensor, Tensor]: + raise RuntimeError( + "This function was deprecated since version 1.9 and is now removed. " + "`torch.lstsq` is deprecated in favor of `torch.linalg.lstsq`.\n" + "`torch.linalg.lstsq` has reversed arguments and does not return the QR decomposition in " + "the returned tuple (although it returns other information about the problem).\n\n" + "To get the QR decomposition consider using `torch.linalg.qr`.\n\n" + "The returned solution in `torch.lstsq` stored the residuals of the solution in the " + "last m - n columns of the returned value whenever m > n. In torch.linalg.lstsq, " + "the residuals are in the field 'residuals' of the returned named tuple.\n\n" + "The unpacking of the solution, as in\n" + "X, _ = torch.lstsq(B, A).solution[:A.size(1)]\n" + "should be replaced with:\n" + "X = torch.linalg.lstsq(A, B).solution" + ) + + +def _symeig( + input, + eigenvectors=False, + upper=True, + *, + out=None, +) -> tuple[Tensor, Tensor]: + raise RuntimeError( + "This function was deprecated since version 1.9 and is now removed. " + "The default behavior has changed from using the upper triangular portion of the matrix by default " + "to using the lower triangular portion.\n\n" + "L, _ = torch.symeig(A, upper=upper) " + "should be replaced with:\n" + "L = torch.linalg.eigvalsh(A, UPLO='U' if upper else 'L')\n\n" + "and\n\n" + "L, V = torch.symeig(A, eigenvectors=True) " + "should be replaced with:\n" + "L, V = torch.linalg.eigh(A, UPLO='U' if upper else 'L')" + ) + + +def eig( + self: Tensor, + eigenvectors: bool = False, + *, + e=None, + v=None, +) -> tuple[Tensor, Tensor]: + raise RuntimeError( + "This function was deprecated since version 1.9 and is now removed. " + "`torch.linalg.eig` returns complex tensors of dtype `cfloat` or `cdouble` rather than real tensors " + "mimicking complex tensors.\n\n" + "L, _ = torch.eig(A) " + "should be replaced with:\n" + "L_complex = torch.linalg.eigvals(A)\n\n" + "and\n\n" + "L, V = torch.eig(A, eigenvectors=True) " + "should be replaced with:\n" + "L_complex, V_complex = torch.linalg.eig(A)" + ) + + +def qr( + input: Tensor, + some: bool = True, + *, + out=None, +) -> tuple[Tensor, Tensor]: + reduced = "reduced" if some else "complete" + raise RuntimeError( + "This function was deprecated since version 1.9 and is now removed. " + "`torch.qr` is deprecated in favor of `torch.linalg.qr` and the boolean parameter " + "`some` has been replaced with a string parameter `mode`.\n\n" + "Q, R = torch.qr(A) " + "should be replaced with:\n" + "Q, R = torch.linalg.qr(A, mode='reduced')\n\n" + "and\n\n" + "Q, R = torch.qr(A, some=False) " + "should be replaced with:\n" + "Q, R = torch.linalg.qr(A, mode='complete')\n\n" + f"Since `some` was set to {some}, use mode='{reduced}'." + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_lobpcg.py b/.venv/lib/python3.12/site-packages/torch/_lobpcg.py new file mode 100644 index 0000000000000000000000000000000000000000..864b91b5e0bb48503244c9155c42a37e46547d1d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lobpcg.py @@ -0,0 +1,1178 @@ +# mypy: allow-untyped-defs +"""Locally Optimal Block Preconditioned Conjugate Gradient methods.""" +# Author: Pearu Peterson +# Created: February 2020 + +import torch +from torch import _linalg_utils as _utils, Tensor +from torch.overrides import handle_torch_function, has_torch_function + + +__all__ = ["lobpcg"] + + +def _symeig_backward_complete_eigenspace(D_grad, U_grad, A, D, U): + # compute F, such that F_ij = (d_j - d_i)^{-1} for i != j, F_ii = 0 + F = D.unsqueeze(-2) - D.unsqueeze(-1) + F.diagonal(dim1=-2, dim2=-1).fill_(float("inf")) + F.pow_(-1) + + # A.grad = U (D.grad + (U^T U.grad * F)) U^T + Ut = U.mT.contiguous() + res = torch.matmul( + U, torch.matmul(torch.diag_embed(D_grad) + torch.matmul(Ut, U_grad) * F, Ut) + ) + + return res + + +def _polynomial_coefficients_given_roots(roots): + """ + Given the `roots` of a polynomial, find the polynomial's coefficients. + + If roots = (r_1, ..., r_n), then the method returns + coefficients (a_0, a_1, ..., a_n (== 1)) so that + p(x) = (x - r_1) * ... * (x - r_n) + = x^n + a_{n-1} * x^{n-1} + ... a_1 * x_1 + a_0 + + Note: for better performance requires writing a low-level kernel + """ + poly_order = roots.shape[-1] + poly_coeffs_shape = list(roots.shape) + # we assume p(x) = x^n + a_{n-1} * x^{n-1} + ... + a_1 * x + a_0, + # so poly_coeffs = {a_0, ..., a_n, a_{n+1}(== 1)}, + # but we insert one extra coefficient to enable better vectorization below + poly_coeffs_shape[-1] += 2 + poly_coeffs = roots.new_zeros(poly_coeffs_shape) + poly_coeffs[..., 0] = 1 + poly_coeffs[..., -1] = 1 + + # perform the Horner's rule + for i in range(1, poly_order + 1): + # note that it is computationally hard to compute backward for this method, + # because then given the coefficients it would require finding the roots and/or + # calculating the sensitivity based on the Vieta's theorem. + # So the code below tries to circumvent the explicit root finding by series + # of operations on memory copies imitating the Horner's method. + # The memory copies are required to construct nodes in the computational graph + # by exploiting the explicit (not in-place, separate node for each step) + # recursion of the Horner's method. + # Needs more memory, O(... * k^2), but with only O(... * k^2) complexity. + poly_coeffs_new = poly_coeffs.clone() if roots.requires_grad else poly_coeffs + out = poly_coeffs_new.narrow(-1, poly_order - i, i + 1) + out -= roots.narrow(-1, i - 1, 1) * poly_coeffs.narrow( + -1, poly_order - i + 1, i + 1 + ) + poly_coeffs = poly_coeffs_new + + return poly_coeffs.narrow(-1, 1, poly_order + 1) + + +def _polynomial_value(poly, x, zero_power, transition): + """ + A generic method for computing poly(x) using the Horner's rule. + + Args: + poly (Tensor): the (possibly batched) 1D Tensor representing + polynomial coefficients such that + poly[..., i] = (a_{i_0}, ..., a{i_n} (==1)), and + poly(x) = poly[..., 0] * zero_power + ... + poly[..., n] * x^n + + x (Tensor): the value (possible batched) to evaluate the polynomial `poly` at. + + zero_power (Tensor): the representation of `x^0`. It is application-specific. + + transition (Callable): the function that accepts some intermediate result `int_val`, + the `x` and a specific polynomial coefficient + `poly[..., k]` for some iteration `k`. + It basically performs one iteration of the Horner's rule + defined as `x * int_val + poly[..., k] * zero_power`. + Note that `zero_power` is not a parameter, + because the step `+ poly[..., k] * zero_power` depends on `x`, + whether it is a vector, a matrix, or something else, so this + functionality is delegated to the user. + """ + + res = zero_power.clone() + for k in range(poly.size(-1) - 2, -1, -1): + res = transition(res, x, poly[..., k]) + return res + + +def _matrix_polynomial_value(poly, x, zero_power=None): + """ + Evaluates `poly(x)` for the (batched) matrix input `x`. + Check out `_polynomial_value` function for more details. + """ + + # matrix-aware Horner's rule iteration + def transition(curr_poly_val, x, poly_coeff): + res = x.matmul(curr_poly_val) + res.diagonal(dim1=-2, dim2=-1).add_(poly_coeff.unsqueeze(-1)) + return res + + if zero_power is None: + zero_power = torch.eye( + x.size(-1), x.size(-1), dtype=x.dtype, device=x.device + ).view(*([1] * len(list(x.shape[:-2]))), x.size(-1), x.size(-1)) + + return _polynomial_value(poly, x, zero_power, transition) + + +def _vector_polynomial_value(poly, x, zero_power=None): + """ + Evaluates `poly(x)` for the (batched) vector input `x`. + Check out `_polynomial_value` function for more details. + """ + + # vector-aware Horner's rule iteration + def transition(curr_poly_val, x, poly_coeff): + res = torch.addcmul(poly_coeff.unsqueeze(-1), x, curr_poly_val) + return res + + if zero_power is None: + zero_power = x.new_ones(1).expand(x.shape) + + return _polynomial_value(poly, x, zero_power, transition) + + +def _symeig_backward_partial_eigenspace(D_grad, U_grad, A, D, U, largest): + # compute a projection operator onto an orthogonal subspace spanned by the + # columns of U defined as (I - UU^T) + Ut = U.mT.contiguous() + proj_U_ortho = -U.matmul(Ut) + proj_U_ortho.diagonal(dim1=-2, dim2=-1).add_(1) + + # compute U_ortho, a basis for the orthogonal complement to the span(U), + # by projecting a random [..., m, m - k] matrix onto the subspace spanned + # by the columns of U. + # + # fix generator for determinism + gen = torch.Generator(A.device) + + # orthogonal complement to the span(U) + U_ortho = proj_U_ortho.matmul( + torch.randn( + (*A.shape[:-1], A.size(-1) - D.size(-1)), + dtype=A.dtype, + device=A.device, + generator=gen, + ) + ) + U_ortho_t = U_ortho.mT.contiguous() + + # compute the coefficients of the characteristic polynomial of the tensor D. + # Note that D is diagonal, so the diagonal elements are exactly the roots + # of the characteristic polynomial. + chr_poly_D = _polynomial_coefficients_given_roots(D) + + # the code below finds the explicit solution to the Sylvester equation + # U_ortho^T A U_ortho dX - dX D = -U_ortho^T A U + # and incorporates it into the whole gradient stored in the `res` variable. + # + # Equivalent to the following naive implementation: + # res = A.new_zeros(A.shape) + # p_res = A.new_zeros(*A.shape[:-1], D.size(-1)) + # for k in range(1, chr_poly_D.size(-1)): + # p_res.zero_() + # for i in range(0, k): + # p_res += (A.matrix_power(k - 1 - i) @ U_grad) * D.pow(i).unsqueeze(-2) + # res -= chr_poly_D[k] * (U_ortho @ poly_D_at_A.inverse() @ U_ortho_t @ p_res @ U.t()) + # + # Note that dX is a differential, so the gradient contribution comes from the backward sensitivity + # Tr(f(U_grad, D_grad, A, U, D)^T dX) = Tr(g(U_grad, A, U, D)^T dA) for some functions f and g, + # and we need to compute g(U_grad, A, U, D) + # + # The naive implementation is based on the paper + # Hu, Qingxi, and Daizhan Cheng. + # "The polynomial solution to the Sylvester matrix equation." + # Applied mathematics letters 19.9 (2006): 859-864. + # + # We can modify the computation of `p_res` from above in a more efficient way + # p_res = U_grad * (chr_poly_D[1] * D.pow(0) + ... + chr_poly_D[k] * D.pow(k)).unsqueeze(-2) + # + A U_grad * (chr_poly_D[2] * D.pow(0) + ... + chr_poly_D[k] * D.pow(k - 1)).unsqueeze(-2) + # + ... + # + A.matrix_power(k - 1) U_grad * chr_poly_D[k] + # Note that this saves us from redundant matrix products with A (elimination of matrix_power) + U_grad_projected = U_grad + series_acc = U_grad_projected.new_zeros(U_grad_projected.shape) + for k in range(1, chr_poly_D.size(-1)): + poly_D = _vector_polynomial_value(chr_poly_D[..., k:], D) + series_acc += U_grad_projected * poly_D.unsqueeze(-2) + U_grad_projected = A.matmul(U_grad_projected) + + # compute chr_poly_D(A) which essentially is: + # + # chr_poly_D_at_A = A.new_zeros(A.shape) + # for k in range(chr_poly_D.size(-1)): + # chr_poly_D_at_A += chr_poly_D[k] * A.matrix_power(k) + # + # Note, however, for better performance we use the Horner's rule + chr_poly_D_at_A = _matrix_polynomial_value(chr_poly_D, A) + + # compute the action of `chr_poly_D_at_A` restricted to U_ortho_t + chr_poly_D_at_A_to_U_ortho = torch.matmul( + U_ortho_t, torch.matmul(chr_poly_D_at_A, U_ortho) + ) + # we need to invert 'chr_poly_D_at_A_to_U_ortho`, for that we compute its + # Cholesky decomposition and then use `torch.cholesky_solve` for better stability. + # Cholesky decomposition requires the input to be positive-definite. + # Note that `chr_poly_D_at_A_to_U_ortho` is positive-definite if + # 1. `largest` == False, or + # 2. `largest` == True and `k` is even + # under the assumption that `A` has distinct eigenvalues. + # + # check if `chr_poly_D_at_A_to_U_ortho` is positive-definite or negative-definite + chr_poly_D_at_A_to_U_ortho_sign = -1 if (largest and (k % 2 == 1)) else +1 + chr_poly_D_at_A_to_U_ortho_L = torch.linalg.cholesky( + chr_poly_D_at_A_to_U_ortho_sign * chr_poly_D_at_A_to_U_ortho + ) + + # compute the gradient part in span(U) + res = _symeig_backward_complete_eigenspace(D_grad, U_grad, A, D, U) + + # incorporate the Sylvester equation solution into the full gradient + # it resides in span(U_ortho) + res -= U_ortho.matmul( + chr_poly_D_at_A_to_U_ortho_sign + * torch.cholesky_solve( + U_ortho_t.matmul(series_acc), chr_poly_D_at_A_to_U_ortho_L + ) + ).matmul(Ut) + + return res + + +def _symeig_backward(D_grad, U_grad, A, D, U, largest): + # if `U` is square, then the columns of `U` is a complete eigenspace + if U.size(-1) == U.size(-2): + return _symeig_backward_complete_eigenspace(D_grad, U_grad, A, D, U) + else: + return _symeig_backward_partial_eigenspace(D_grad, U_grad, A, D, U, largest) + + +class LOBPCGAutogradFunction(torch.autograd.Function): + @staticmethod + def forward( # type: ignore[override] + ctx, + A: Tensor, + k: int | None = None, + B: Tensor | None = None, + X: Tensor | None = None, + n: int | None = None, + iK: Tensor | None = None, + niter: int | None = None, + tol: float | None = None, + largest: bool | None = None, + method: str | None = None, + tracker: None = None, + ortho_iparams: dict[str, int] | None = None, + ortho_fparams: dict[str, float] | None = None, + ortho_bparams: dict[str, bool] | None = None, + ) -> tuple[Tensor, Tensor]: + # makes sure that input is contiguous for efficiency. + # Note: autograd does not support dense gradients for sparse input yet. + A = A.contiguous() if (not A.is_sparse) else A + if B is not None: + B = B.contiguous() if (not B.is_sparse) else B + + D, U = _lobpcg( + A, + k, + B, + X, + n, + iK, + niter, + tol, + largest, + method, + tracker, + ortho_iparams, + ortho_fparams, + ortho_bparams, + ) + + ctx.save_for_backward(A, B, D, U) + ctx.largest = largest + + return D, U + + @staticmethod + def backward(ctx, D_grad, U_grad): # pyrefly: ignore # bad-override + A_grad = B_grad = None + grads = [None] * 14 + + A, B, D, U = ctx.saved_tensors + largest = ctx.largest + + # lobpcg.backward has some limitations. Checks for unsupported input + if A.is_sparse or (B is not None and B.is_sparse and ctx.needs_input_grad[2]): + raise ValueError( + "lobpcg.backward does not support sparse input yet. " + "Note that lobpcg.forward does though." + ) + if ( + A.dtype in (torch.complex64, torch.complex128) + or B is not None + and B.dtype in (torch.complex64, torch.complex128) + ): + raise ValueError( + "lobpcg.backward does not support complex input yet. " + "Note that lobpcg.forward does though." + ) + if B is not None: + raise ValueError( + "lobpcg.backward does not support backward with B != I yet." + ) + + if largest is None: + largest = True + + # symeig backward + if B is None: + A_grad = _symeig_backward(D_grad, U_grad, A, D, U, largest) + + # A has index 0 + grads[0] = A_grad + # B has index 2 + grads[2] = B_grad + return tuple(grads) + + +def lobpcg( + A: Tensor, + k: int | None = None, + B: Tensor | None = None, + X: Tensor | None = None, + n: int | None = None, + iK: Tensor | None = None, + niter: int | None = None, + tol: float | None = None, + largest: bool | None = None, + method: str | None = None, + tracker: None = None, + ortho_iparams: dict[str, int] | None = None, + ortho_fparams: dict[str, float] | None = None, + ortho_bparams: dict[str, bool] | None = None, +) -> tuple[Tensor, Tensor]: + """Find the k largest (or smallest) eigenvalues and the corresponding + eigenvectors of a symmetric positive definite generalized + eigenvalue problem using matrix-free LOBPCG methods. + + This function is a front-end to the following LOBPCG algorithms + selectable via `method` argument: + + `method="basic"` - the LOBPCG method introduced by Andrew + Knyazev, see [Knyazev2001]. A less robust method, may fail when + Cholesky is applied to singular input. + + `method="ortho"` - the LOBPCG method with orthogonal basis + selection [StathopoulosEtal2002]. A robust method. + + Supported inputs are dense, sparse, and batches of dense matrices. + + .. note:: In general, the basic method spends least time per + iteration. However, the robust methods converge much faster and + are more stable. So, the usage of the basic method is generally + not recommended but there exist cases where the usage of the + basic method may be preferred. + + .. warning:: The backward method does not support sparse and complex inputs. + It works only when `B` is not provided (i.e. `B == None`). + We are actively working on extensions, and the details of + the algorithms are going to be published promptly. + + .. warning:: While it is assumed that `A` is symmetric, `A.grad` is not. + To make sure that `A.grad` is symmetric, so that `A - t * A.grad` is symmetric + in first-order optimization routines, prior to running `lobpcg` + we do the following symmetrization map: `A -> (A + A.t()) / 2`. + The map is performed only when the `A` requires gradients. + + .. warning:: LOBPCG algorithm is not applicable when the number of `A`'s rows + is smaller than 3x the number of requested eigenpairs `n`. + + Args: + + A (Tensor): the input tensor of size :math:`(*, m, m)` + + k (integer, optional): the number of requested + eigenpairs. Default is the number of :math:`X` + columns (when specified) or `1`. + + B (Tensor, optional): the input tensor of size :math:`(*, m, + m)`. When not specified, `B` is interpreted as + identity matrix. + + X (tensor, optional): the input tensor of size :math:`(*, m, n)` + where `k <= n <= m`. When specified, it is used as + initial approximation of eigenvectors. X must be a + dense tensor. + + n (integer, optional): if :math:`X` is not specified then `n` + specifies the size of the generated random + approximation of eigenvectors. Default value for `n` + is `k`. If :math:`X` is specified, any provided value of `n` is + ignored and `n` is automatically set to the number of + columns in :math:`X`. + + iK (tensor, optional): the input tensor of size :math:`(*, m, + m)`. When specified, it will be used as preconditioner. + + niter (int, optional): maximum number of iterations. When + reached, the iteration process is hard-stopped and + the current approximation of eigenpairs is returned. + For infinite iteration but until convergence criteria + is met, use `-1`. + + tol (float, optional): residual tolerance for stopping + criterion. Default is `feps ** 0.5` where `feps` is + smallest non-zero floating-point number of the given + input tensor `A` data type. + + largest (bool, optional): when True, solve the eigenproblem for + the largest eigenvalues. Otherwise, solve the + eigenproblem for smallest eigenvalues. Default is + `True`. + + method (str, optional): select LOBPCG method. See the + description of the function above. Default is + "ortho". + + tracker (callable, optional) : a function for tracing the + iteration process. When specified, it is called at + each iteration step with LOBPCG instance as an + argument. The LOBPCG instance holds the full state of + the iteration process in the following attributes: + + `iparams`, `fparams`, `bparams` - dictionaries of + integer, float, and boolean valued input + parameters, respectively + + `ivars`, `fvars`, `bvars`, `tvars` - dictionaries + of integer, float, boolean, and Tensor valued + iteration variables, respectively. + + `A`, `B`, `iK` - input Tensor arguments. + + `E`, `X`, `S`, `R` - iteration Tensor variables. + + For instance: + + `ivars["istep"]` - the current iteration step + `X` - the current approximation of eigenvectors + `E` - the current approximation of eigenvalues + `R` - the current residual + `ivars["converged_count"]` - the current number of converged eigenpairs + `tvars["rerr"]` - the current state of convergence criteria + + Note that when `tracker` stores Tensor objects from + the LOBPCG instance, it must make copies of these. + + If `tracker` sets `bvars["force_stop"] = True`, the + iteration process will be hard-stopped. + + ortho_iparams, ortho_fparams, ortho_bparams (dict, optional): + various parameters to LOBPCG algorithm when using + `method="ortho"`. + + Returns: + + E (Tensor): tensor of eigenvalues of size :math:`(*, k)` + + X (Tensor): tensor of eigenvectors of size :math:`(*, m, k)` + + References: + + [Knyazev2001] Andrew V. Knyazev. (2001) Toward the Optimal + Preconditioned Eigensolver: Locally Optimal Block Preconditioned + Conjugate Gradient Method. SIAM J. Sci. Comput., 23(2), + 517-541. (25 pages) + https://epubs.siam.org/doi/abs/10.1137/S1064827500366124 + + [StathopoulosEtal2002] Andreas Stathopoulos and Kesheng + Wu. (2002) A Block Orthogonalization Procedure with Constant + Synchronization Requirements. SIAM J. Sci. Comput., 23(6), + 2165-2182. (18 pages) + https://epubs.siam.org/doi/10.1137/S1064827500370883 + + [DuerschEtal2018] Jed A. Duersch, Meiyue Shao, Chao Yang, Ming + Gu. (2018) A Robust and Efficient Implementation of LOBPCG. + SIAM J. Sci. Comput., 40(5), C655-C676. (22 pages) + https://arxiv.org/abs/1704.07458 + + """ + + if not torch.jit.is_scripting(): + tensor_ops = (A, B, X, iK) + if not set(map(type, tensor_ops)).issubset( + (torch.Tensor, type(None)) + ) and has_torch_function(tensor_ops): + return handle_torch_function( + lobpcg, + tensor_ops, + A, + k=k, + B=B, + X=X, + n=n, + iK=iK, + niter=niter, + tol=tol, + largest=largest, + method=method, + tracker=tracker, + ortho_iparams=ortho_iparams, + ortho_fparams=ortho_fparams, + ortho_bparams=ortho_bparams, + ) + + if not torch._jit_internal.is_scripting(): + if A.requires_grad or (B is not None and B.requires_grad): + # While it is expected that `A` is symmetric, + # the `A_grad` might be not. Therefore we perform the trick below, + # so that `A_grad` becomes symmetric. + # The symmetrization is important for first-order optimization methods, + # so that (A - alpha * A_grad) is still a symmetric matrix. + # Same holds for `B`. + A_sym = (A + A.mT) / 2 + B_sym = (B + B.mT) / 2 if (B is not None) else None + + return LOBPCGAutogradFunction.apply( + A_sym, + k, + B_sym, + X, + n, + iK, + niter, + tol, + largest, + method, + tracker, + ortho_iparams, + ortho_fparams, + ortho_bparams, + ) + else: + if A.requires_grad or (B is not None and B.requires_grad): + raise RuntimeError( + "Script and require grads is not supported atm. " + "If you just want to do the forward, use .detach() " + "on A and B before calling into lobpcg" + ) + + return _lobpcg( + A, + k, + B, + X, + n, + iK, + niter, + tol, + largest, + method, + tracker, + ortho_iparams, + ortho_fparams, + ortho_bparams, + ) + + +def _lobpcg( + A: Tensor, + k: int | None = None, + B: Tensor | None = None, + X: Tensor | None = None, + n: int | None = None, + iK: Tensor | None = None, + niter: int | None = None, + tol: float | None = None, + largest: bool | None = None, + method: str | None = None, + tracker: None = None, + ortho_iparams: dict[str, int] | None = None, + ortho_fparams: dict[str, float] | None = None, + ortho_bparams: dict[str, bool] | None = None, +) -> tuple[Tensor, Tensor]: + # A must be square: + if A.shape[-2] != A.shape[-1]: + raise AssertionError(f"A must be square, got shape {A.shape}") + if B is not None: + # A and B must have the same shapes: + if A.shape != B.shape: + raise AssertionError( + f"A and B must have same shape, got {A.shape} vs {B.shape}" + ) + + dtype = _utils.get_floating_dtype(A) + device = A.device + if tol is None: + feps = {torch.float32: 1.2e-07, torch.float64: 2.23e-16}[dtype] + tol = feps**0.5 + + m = A.shape[-1] + k = (1 if X is None else X.shape[-1]) if k is None else k + n = (k if n is None else n) if X is None else X.shape[-1] + + if m < 3 * n: + raise ValueError( + f"LOBPCG algorithm is not applicable when the number of A rows (={m})" + f" is smaller than 3 x the number of requested eigenpairs (={n})" + ) + + method = "ortho" if method is None else method + + iparams = { + "m": m, + "n": n, + "k": k, + "niter": 1000 if niter is None else niter, + } + + fparams = { + "tol": tol, + } + + bparams = {"largest": True if largest is None else largest} + + if method == "ortho": + if ortho_iparams is not None: + iparams.update(ortho_iparams) + if ortho_fparams is not None: + fparams.update(ortho_fparams) + if ortho_bparams is not None: + bparams.update(ortho_bparams) + iparams["ortho_i_max"] = iparams.get("ortho_i_max", 3) + iparams["ortho_j_max"] = iparams.get("ortho_j_max", 3) + fparams["ortho_tol"] = fparams.get("ortho_tol", tol) + fparams["ortho_tol_drop"] = fparams.get("ortho_tol_drop", tol) + fparams["ortho_tol_replace"] = fparams.get("ortho_tol_replace", tol) + bparams["ortho_use_drop"] = bparams.get("ortho_use_drop", False) + + if not torch.jit.is_scripting(): + LOBPCG.call_tracker = LOBPCG_call_tracker # type: ignore[method-assign] + + if len(A.shape) > 2: + N = int(torch.prod(torch.tensor(A.shape[:-2]))) + bA = A.reshape((N,) + A.shape[-2:]) + bB = B.reshape((N,) + A.shape[-2:]) if B is not None else None + bX = X.reshape((N,) + X.shape[-2:]) if X is not None else None + bE = torch.empty((N, k), dtype=dtype, device=device) + bXret = torch.empty((N, m, k), dtype=dtype, device=device) + + for i in range(N): + A_ = bA[i] + B_ = bB[i] if bB is not None else None + X_ = ( + torch.randn((m, n), dtype=dtype, device=device) if bX is None else bX[i] + ) + if not (len(X_.shape) == 2 and X_.shape == (m, n)): + raise AssertionError( + f"X_ shape mismatch: got {X_.shape}, expected {(m, n)}" + ) + iparams["batch_index"] = i + worker = LOBPCG(A_, B_, X_, iK, iparams, fparams, bparams, method, tracker) + worker.run() + bE[i] = worker.E[:k] + bXret[i] = worker.X[:, :k] + + if not torch.jit.is_scripting(): + LOBPCG.call_tracker = LOBPCG_call_tracker_orig # type: ignore[method-assign] + + return bE.reshape(A.shape[:-2] + (k,)), bXret.reshape(A.shape[:-2] + (m, k)) + + X = torch.randn((m, n), dtype=dtype, device=device) if X is None else X + if not (len(X.shape) == 2 and X.shape == (m, n)): + raise AssertionError(f"X shape mismatch: got {X.shape}, expected {(m, n)}") + + worker = LOBPCG(A, B, X, iK, iparams, fparams, bparams, method, tracker) + + worker.run() + + if not torch.jit.is_scripting(): + LOBPCG.call_tracker = LOBPCG_call_tracker_orig # type: ignore[method-assign] + + return worker.E[:k], worker.X[:, :k] + + +class LOBPCG: + """Worker class of LOBPCG methods.""" + + def __init__( + self, + A: Tensor | None, + B: Tensor | None, + X: Tensor, + iK: Tensor | None, + iparams: dict[str, int], + fparams: dict[str, float], + bparams: dict[str, bool], + method: str, + tracker: None, + ) -> None: + # constant parameters + self.A = A + self.B = B + self.iK = iK + self.iparams = iparams + self.fparams = fparams + self.bparams = bparams + self.method = method + self.tracker = tracker + m = iparams["m"] + n = iparams["n"] + + # variable parameters + self.X = X + self.E = torch.zeros((n,), dtype=X.dtype, device=X.device) + self.R = torch.zeros((m, n), dtype=X.dtype, device=X.device) + self.S = torch.zeros((m, 3 * n), dtype=X.dtype, device=X.device) + self.tvars: dict[str, Tensor] = {} + self.ivars: dict[str, int] = {"istep": 0} + self.fvars: dict[str, float] = {"_": 0.0} + self.bvars: dict[str, bool] = {"_": False} + + def __str__(self): + lines = ["LOBPCG:"] + lines += [f" iparams={self.iparams}"] + lines += [f" fparams={self.fparams}"] + lines += [f" bparams={self.bparams}"] + lines += [f" ivars={self.ivars}"] + lines += [f" fvars={self.fvars}"] + lines += [f" bvars={self.bvars}"] + lines += [f" tvars={self.tvars}"] + lines += [f" A={self.A}"] + lines += [f" B={self.B}"] + lines += [f" iK={self.iK}"] + lines += [f" X={self.X}"] + lines += [f" E={self.E}"] + r = "" + for line in lines: + r += line + "\n" + return r + + def update(self): + """Set and update iteration variables.""" + if self.ivars["istep"] == 0: + X_norm = float(torch.linalg.vector_norm(self.X)) + iX_norm = X_norm**-1 + A_norm = ( + float(torch.linalg.vector_norm(_utils.matmul(self.A, self.X))) * iX_norm + ) + B_norm = ( + float(torch.linalg.vector_norm(_utils.matmul(self.B, self.X))) * iX_norm + ) + self.fvars["X_norm"] = X_norm + self.fvars["A_norm"] = A_norm + self.fvars["B_norm"] = B_norm + self.ivars["iterations_left"] = self.iparams["niter"] + self.ivars["converged_count"] = 0 + self.ivars["converged_end"] = 0 + + if self.method == "ortho": + self._update_ortho() + else: + self._update_basic() + + self.ivars["iterations_left"] = self.ivars["iterations_left"] - 1 + self.ivars["istep"] = self.ivars["istep"] + 1 + + def update_residual(self): + """Update residual R from A, B, X, E.""" + mm = _utils.matmul + self.R = mm(self.A, self.X) - mm(self.B, self.X) * self.E + + def update_converged_count(self): + """Determine the number of converged eigenpairs using backward stable + convergence criterion, see discussion in Sec 4.3 of [DuerschEtal2018]. + + Users may redefine this method for custom convergence criteria. + """ + # (...) -> int + prev_count = self.ivars["converged_count"] + tol = self.fparams["tol"] + A_norm = self.fvars["A_norm"] + B_norm = self.fvars["B_norm"] + E, X, R = self.E, self.X, self.R + rerr = torch.linalg.vector_norm(R, ord=2, dim=(0,)) / ( + torch.linalg.vector_norm(X, ord=2, dim=(0,)) + * (A_norm + torch.abs(E[: X.shape[-1]]) * B_norm) + ) + converged = rerr < tol + count = 0 + for b in converged: + if not b: + # ignore convergence of following pairs to ensure + # strict ordering of eigenpairs + break + count += 1 + if count < prev_count: + raise AssertionError( + f"the number of converged eigenpairs (was {prev_count}, got {count}) cannot decrease" + ) + self.ivars["converged_count"] = count + self.tvars["rerr"] = rerr + return count + + def stop_iteration(self): + """Return True to stop iterations. + + Note that tracker (if defined) can force-stop iterations by + setting ``worker.bvars['force_stop'] = True``. + """ + return ( + self.bvars.get("force_stop", False) + or self.ivars["iterations_left"] == 0 + or self.ivars["converged_count"] >= self.iparams["k"] + ) + + def run(self): + """Run LOBPCG iterations. + + Use this method as a template for implementing LOBPCG + iteration scheme with custom tracker that is compatible with + TorchScript. + """ + self.update() + + if not torch.jit.is_scripting() and self.tracker is not None: + self.call_tracker() + + while not self.stop_iteration(): + self.update() + + if not torch.jit.is_scripting() and self.tracker is not None: + self.call_tracker() + + @torch.jit.unused + def call_tracker(self): + """Interface for tracking iteration process in Python mode. + + Tracking the iteration process is disabled in TorchScript + mode. In fact, one should specify tracker=None when JIT + compiling functions using lobpcg. + """ + # do nothing when in TorchScript mode + + # Internal methods + + def _update_basic(self): + """ + Update or initialize iteration variables when `method == "basic"`. + """ + mm = torch.matmul + ns = self.ivars["converged_end"] + nc = self.ivars["converged_count"] + n = self.iparams["n"] + largest = self.bparams["largest"] + + if self.ivars["istep"] == 0: + Ri = self._get_rayleigh_ritz_transform(self.X) + M = _utils.qform(_utils.qform(self.A, self.X), Ri) + E, Z = _utils.symeig(M, largest) + self.X[:] = mm(self.X, mm(Ri, Z)) + self.E[:] = E + np = 0 + self.update_residual() + nc = self.update_converged_count() + self.S[..., :n] = self.X + + W = _utils.matmul(self.iK, self.R) + self.ivars["converged_end"] = ns = n + np + W.shape[-1] + self.S[:, n + np : ns] = W + else: + S_ = self.S[:, nc:ns] + Ri = self._get_rayleigh_ritz_transform(S_) + M = _utils.qform(_utils.qform(self.A, S_), Ri) + E_, Z = _utils.symeig(M, largest) + self.X[:, nc:] = mm(S_, mm(Ri, Z[:, : n - nc])) + self.E[nc:] = E_[: n - nc] + P = mm(S_, mm(Ri, Z[:, n : 2 * n - nc])) + np = P.shape[-1] + + self.update_residual() + nc = self.update_converged_count() + self.S[..., :n] = self.X + self.S[:, n : n + np] = P + W = _utils.matmul(self.iK, self.R[:, nc:]) + + self.ivars["converged_end"] = ns = n + np + W.shape[-1] + self.S[:, n + np : ns] = W + + def _update_ortho(self): + """ + Update or initialize iteration variables when `method == "ortho"`. + """ + mm = torch.matmul + ns = self.ivars["converged_end"] + nc = self.ivars["converged_count"] + n = self.iparams["n"] + largest = self.bparams["largest"] + + if self.ivars["istep"] == 0: + Ri = self._get_rayleigh_ritz_transform(self.X) + M = _utils.qform(_utils.qform(self.A, self.X), Ri) + _E, Z = _utils.symeig(M, largest) + self.X = mm(self.X, mm(Ri, Z)) + self.update_residual() + np = 0 + nc = self.update_converged_count() + self.S[:, :n] = self.X + W = self._get_ortho(self.R, self.X) + ns = self.ivars["converged_end"] = n + np + W.shape[-1] + self.S[:, n + np : ns] = W + + else: + S_ = self.S[:, nc:ns] + # Rayleigh-Ritz procedure + E_, Z = _utils.symeig(_utils.qform(self.A, S_), largest) + + # Update E, X, P + self.X[:, nc:] = mm(S_, Z[:, : n - nc]) + self.E[nc:] = E_[: n - nc] + P = mm(S_, mm(Z[:, n - nc :], _utils.basis(Z[: n - nc, n - nc :].mT))) + np = P.shape[-1] + + # check convergence + self.update_residual() + nc = self.update_converged_count() + + # update S + self.S[:, :n] = self.X + self.S[:, n : n + np] = P + W = self._get_ortho(self.R[:, nc:], self.S[:, : n + np]) + ns = self.ivars["converged_end"] = n + np + W.shape[-1] + self.S[:, n + np : ns] = W + + def _get_rayleigh_ritz_transform(self, S): + """Return a transformation matrix that is used in Rayleigh-Ritz + procedure for reducing a general eigenvalue problem :math:`(S^TAS) + C = (S^TBS) C E` to a standard eigenvalue problem :math: `(Ri^T + S^TAS Ri) Z = Z E` where `C = Ri Z`. + + .. note:: In the original Rayleigh-Ritz procedure in + [DuerschEtal2018], the problem is formulated as follows:: + + SAS = S^T A S + SBS = S^T B S + D = () ** -1/2 + R^T R = Cholesky(D SBS D) + Ri = D R^-1 + solve symeig problem Ri^T SAS Ri Z = Theta Z + C = Ri Z + + To reduce the number of matrix products (denoted by empty + space between matrices), here we introduce element-wise + products (denoted by symbol `*`) so that the Rayleigh-Ritz + procedure becomes:: + + SAS = S^T A S + SBS = S^T B S + d = () ** -1/2 # this is 1-d column vector + dd = d d^T # this is 2-d matrix + R^T R = Cholesky(dd * SBS) + Ri = R^-1 * d # broadcasting + solve symeig problem Ri^T SAS Ri Z = Theta Z + C = Ri Z + + where `dd` is 2-d matrix that replaces matrix products `D M + D` with one element-wise product `M * dd`; and `d` replaces + matrix product `D M` with element-wise product `M * + d`. Also, creating the diagonal matrix `D` is avoided. + + Args: + S (Tensor): the matrix basis for the search subspace, size is + :math:`(m, n)`. + + Returns: + Ri (tensor): upper-triangular transformation matrix of size + :math:`(n, n)`. + + """ + B = self.B + SBS = _utils.qform(B, S) + d_row = SBS.diagonal(0, -2, -1) ** -0.5 + d_col = d_row.reshape(d_row.shape[0], 1) + # TODO use torch.linalg.cholesky_solve once it is implemented + R = torch.linalg.cholesky((SBS * d_row) * d_col, upper=True) + return torch.linalg.solve_triangular( + R, d_row.diag_embed(), upper=True, left=False + ) + + def _get_svqb(self, U: Tensor, drop: bool, tau: float) -> Tensor: + """Return B-orthonormal U. + + .. note:: When `drop` is `False` then `svqb` is based on the + Algorithm 4 from [DuerschPhD2015] that is a slight + modification of the corresponding algorithm + introduced in [StathopoulosWu2002]. + + Args: + + U (Tensor) : initial approximation, size is (m, n) + drop (bool) : when True, drop columns that + contribution to the `span([U])` is small. + tau (float) : positive tolerance + + Returns: + + U (Tensor) : B-orthonormal columns (:math:`U^T B U = I`), size + is (m, n1), where `n1 = n` if `drop` is `False, + otherwise `n1 <= n`. + + """ + if torch.numel(U) == 0: + return U + UBU = _utils.qform(self.B, U) + d = UBU.diagonal(0, -2, -1) + + # Detect and drop exact zero columns from U. While the test + # `abs(d) == 0` is unlikely to be True for random data, it is + # possible to construct input data to lobpcg where it will be + # True leading to a failure (notice the `d ** -0.5` operation + # in the original algorithm). To prevent the failure, we drop + # the exact zero columns here and then continue with the + # original algorithm below. + nz = torch.where(abs(d) != 0.0) + if len(nz) != 1: + raise AssertionError(f"expected nz to have length 1, got {nz}") + if len(nz[0]) < len(d): + U = U[:, nz[0]] + if torch.numel(U) == 0: + return U + UBU = _utils.qform(self.B, U) + d = UBU.diagonal(0, -2, -1) + nz = torch.where(abs(d) != 0.0) + if len(nz[0]) != len(d): + raise AssertionError( + f"expected nz[0] length {len(d)}, got {len(nz[0])}" + ) + + # The original algorithm 4 from [DuerschPhD2015]. + d_col = (d**-0.5).reshape(d.shape[0], 1) + DUBUD = (UBU * d_col) * d_col.mT + E, Z = _utils.symeig(DUBUD) + t = tau * abs(E).max() + if drop: + keep = torch.where(E > t) + if len(keep) != 1: + raise AssertionError(f"expected keep to have length 1, got {keep}") + E = E[keep[0]] + Z = Z[:, keep[0]] + d_col = d_col[keep[0]] + else: + E[(torch.where(E < t))[0]] = t + + return torch.matmul( + U * d_col.mT, + Z * E**-0.5, + ) + + def _get_ortho(self, U, V): + """Return B-orthonormal U with columns are B-orthogonal to V. + + .. note:: When `bparams["ortho_use_drop"] == False` then + `_get_ortho` is based on the Algorithm 3 from + [DuerschPhD2015] that is a slight modification of + the corresponding algorithm introduced in + [StathopoulosWu2002]. Otherwise, the method + implements Algorithm 6 from [DuerschPhD2015] + + .. note:: If all U columns are B-collinear to V then the + returned tensor U will be empty. + + Args: + + U (Tensor) : initial approximation, size is (m, n) + V (Tensor) : B-orthogonal external basis, size is (m, k) + + Returns: + + U (Tensor) : B-orthonormal columns (:math:`U^T B U = I`) + such that :math:`V^T B U=0`, size is (m, n1), + where `n1 = n` if `drop` is `False, otherwise + `n1 <= n`. + """ + mm = torch.matmul + mm_B = _utils.matmul + m = self.iparams["m"] + tau_ortho = self.fparams["ortho_tol"] + tau_drop = self.fparams["ortho_tol_drop"] + tau_replace = self.fparams["ortho_tol_replace"] + i_max = self.iparams["ortho_i_max"] + j_max = self.iparams["ortho_j_max"] + # when use_drop==True, enable dropping U columns that have + # small contribution to the `span([U, V])`. + use_drop = self.bparams["ortho_use_drop"] + + # clean up variables from the previous call + for vkey in list(self.fvars.keys()): + if vkey.startswith("ortho_") and vkey.endswith("_rerr"): + self.fvars.pop(vkey) + self.ivars.pop("ortho_i", 0) + self.ivars.pop("ortho_j", 0) + + BV_norm = torch.linalg.vector_norm(mm_B(self.B, V)) + BU = mm_B(self.B, U) + VBU = mm(V.mT, BU) + i = j = 0 + for i in range(i_max): + U = U - mm(V, VBU) + drop = False + tau_svqb = tau_drop + for j in range(j_max): + if use_drop: + U = self._get_svqb(U, drop, tau_svqb) + drop = True + tau_svqb = tau_replace + else: + U = self._get_svqb(U, False, tau_replace) + if torch.numel(U) == 0: + # all initial U columns are B-collinear to V + self.ivars["ortho_i"] = i + self.ivars["ortho_j"] = j + return U + BU = mm_B(self.B, U) + UBU = mm(U.mT, BU) + U_norm = torch.linalg.vector_norm(U) + BU_norm = torch.linalg.vector_norm(BU) + R = UBU - torch.eye(UBU.shape[-1], device=UBU.device, dtype=UBU.dtype) + R_norm = torch.linalg.vector_norm(R) + # https://github.com/pytorch/pytorch/issues/33810 workaround: + rerr = float(R_norm) * float(BU_norm * U_norm) ** -1 + vkey = f"ortho_UBUmI_rerr[{i}, {j}]" + self.fvars[vkey] = rerr + if rerr < tau_ortho: + break + VBU = mm(V.mT, BU) + VBU_norm = torch.linalg.vector_norm(VBU) + U_norm = torch.linalg.vector_norm(U) + rerr = float(VBU_norm) * float(BV_norm * U_norm) ** -1 + vkey = f"ortho_VBU_rerr[{i}]" + self.fvars[vkey] = rerr + if rerr < tau_ortho: + break + if m < U.shape[-1] + V.shape[-1]: + # TorchScript needs the class var to be assigned to a local to + # do optional type refinement + B = self.B + if B is None: + raise AssertionError("B must not be None") + raise ValueError( + "Overdetermined shape of U:" + f" #B-cols(={B.shape[-1]}) >= #U-cols(={U.shape[-1]}) + #V-cols(={V.shape[-1]}) must hold" + ) + self.ivars["ortho_i"] = i + self.ivars["ortho_j"] = j + return U + + +# Calling tracker is separated from LOBPCG definitions because +# TorchScript does not support user-defined callback arguments: +LOBPCG_call_tracker_orig = LOBPCG.call_tracker + + +def LOBPCG_call_tracker(self): + self.tracker(self) diff --git a/.venv/lib/python3.12/site-packages/torch/_logging/__init__.py b/.venv/lib/python3.12/site-packages/torch/_logging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d0fdebb23bde98f0a04b1f4b902c06984a443ec8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_logging/__init__.py @@ -0,0 +1,20 @@ +# Top level logging module for torch logging +# Design doc: https://docs.google.com/document/d/1ZRfTWKa8eaPq1AxaiHrq4ASTPouzzlPiuquSBEJYwS8/edit# +# Simple setup for onboarding (see above doc for more detail): +# 1. register any top-level log qualified name for your module in torch._logging._registrations (see there for examples) +# 2. register any artifacts ( below) in torch._logging._registrations +# a. call getArtifactLogger(__name__, ) at your logging site instead of the standard logger to log your artifact +import torch._logging._registrations + +from ._internal import ( + _init_logs, + DEFAULT_LOGGING, + dtrace_structured, + get_structured_logging_overhead, + getArtifactLogger, + hide_warnings, + LazyString, + set_logs, + trace_structured, + warning_once, +) diff --git a/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3dee37ccc7819f0b165f28a5d77337c81d6224bf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/_internal.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/_internal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30c5fcf3ab682da271d74571ec21dcaa01b534e5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/_internal.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/_registrations.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/_registrations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba1c40b412c6c725bd3fc55ba25a666efa10a36f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/_registrations.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/scribe.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/scribe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d28ebd67bcae507dc9f67013ba5993024aee689 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/scribe.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/structured.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/structured.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b9a091da8b6b85c3f0d5338b26e0158312620a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_logging/__pycache__/structured.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_logging/_internal.py b/.venv/lib/python3.12/site-packages/torch/_logging/_internal.py new file mode 100644 index 0000000000000000000000000000000000000000..631d8751e883ef8a3963d883260fe797534dc29b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_logging/_internal.py @@ -0,0 +1,1640 @@ +# mypy: allow-untyped-defs +import contextlib +import errno +import functools +import hashlib +import importlib.util +import itertools +import json +import logging +import os +import os.path +import pathlib +import pkgutil +import re +import sys +import tempfile +import time +import warnings +from collections import defaultdict +from collections.abc import Callable, Sequence +from dataclasses import dataclass, field +from typing import Any, Generic, Optional +from typing_extensions import ParamSpec +from weakref import WeakSet + +import torch._logging.structured +from torch._guards import CompileId +from torch._utils_internal import log_trace_structured_event +from torch.utils._traceback import CapturedTraceback + + +_P = ParamSpec("_P") + +log = logging.getLogger(__name__) + +# This is a synthetic logger which doesn't correspond to an actual logger, +# but handles all of our "tracing" logging, which is structured and doesn't go +# to stderr but always goes to a dedicated log file. We don't put these +# loggers in the classic module hierarchy, because we don't want a suppression +# of logs to also cause a trace to get suppressed (traces typically are not +# collected, unless we are in prod, in which case they always are collected.) +# +# TODO: Maybe we should allow for some sub-hierarchy so you can control which +# traces you want to collect, for performance reasons. +# +# See https://docs.google.com/document/d/1CX_hJ0PNy9f3R1y8TJrfkSeLkvGjjjLU84BSXgS2AZ8/edit +trace_log = logging.getLogger("torch.__trace") + +DEFAULT_LOG_LEVEL = logging.WARNING +LOG_ENV_VAR = "TORCH_LOGS" +LOG_OUT_ENV_VAR = "TORCH_LOGS_OUT" +LOG_FORMAT_ENV_VAR = "TORCH_LOGS_FORMAT" +LOG_TRACE_ID_FILTER = "TORCH_LOGS_TRACE_ID_FILTER" +TRACE_ENV_VAR = "TORCH_TRACE" +DTRACE_ENV_VAR = "TORCH_DTRACE" + +LOG_TRACE_HANDLER: Optional["LazyTraceHandler"] = None + +GET_DTRACE_STRUCTURED = False + +LOG_PREFIX = "dedicated_log_torch_trace_" + + +@dataclass +class LogRegistry: + # shorthand name to log qualified name + # Note: this only contains loggers registered + # from register_log + # e.g. "dynamo" -> "torch._dynamo" + log_alias_to_log_qnames: dict[str, list[str]] = field(default_factory=dict) + + # artifact logger qualified names, + # this is populated lazily, as calls to getArtifactLogger + # currently formatted as .__ + # e.g. "torch._dynamo.convert_frame.__guards" + artifact_log_qnames: set[str] = field(default_factory=set) + + # child logs of registered logs if specified via open + # registration by the user (ie placing "torch._dynamo.output_graph" in the env var) + # these need to be tracked so their levels can be reset properly + # e.g. "torch._dynamo.output_graph" + child_log_qnames: set[str] = field(default_factory=set) + + # artifact names, populated by register_artifact + # e.g. "guards" + artifact_names: set[str] = field(default_factory=set) + + # Artifacts that should be visible by default in the error message + visible_artifacts: set[str] = field(default_factory=set) + + # A short description of each artifact + artifact_descriptions: dict[str, str] = field(default_factory=dict) + + # artifacts which are not displayed unless explicitly named in the + # settings. Ex. output_code is NOT displayed even if the inductor + # log level is set to DEBUG. It must be explicitly named in the settings + off_by_default_artifact_names: set[str] = field(default_factory=set) + + # logging format string for artifacts + artifact_log_formatters: dict[str, logging.Formatter] = field(default_factory=dict) + + def is_artifact(self, name): + return name in self.artifact_names + + def is_log(self, alias): + return alias in self.log_alias_to_log_qnames + + # register a log with an alias + def register_log(self, alias, log_qnames: str | list[str]) -> None: + if isinstance(log_qnames, str): + log_qnames = [log_qnames] + self.log_alias_to_log_qnames[alias] = log_qnames + + # register an artifact name + def register_artifact_name( + self, name, description, visible, off_by_default, log_format + ) -> None: + self.artifact_names.add(name) + if visible: + self.visible_artifacts.add(name) + self.artifact_descriptions[name] = description + + # if off by default, don't enable it + # when log_name's log_level is set to DEBUG + if off_by_default: + self.off_by_default_artifact_names.add(name) + + if log_format is not None: + self.artifact_log_formatters[name] = logging.Formatter(log_format) + + # register the qualified name of an artifact log + # this is needed to know which logs need to be reset + # whenever the log_state is changed + def register_artifact_log(self, artifact_log_qname) -> None: + self.artifact_log_qnames.add(artifact_log_qname) + + def register_child_log(self, log_qname) -> None: + self.child_log_qnames.add(log_qname) + + # flattens all the qnames together (TODO: consider memoizing?) + def get_log_qnames(self) -> set[str]: + return set(itertools.chain.from_iterable(self.log_alias_to_log_qnames.values())) + + def get_artifact_log_qnames(self): + return set(self.artifact_log_qnames) + + def get_child_log_qnames(self): + return set(self.child_log_qnames) + + def is_off_by_default(self, artifact_qname): + return artifact_qname in self.off_by_default_artifact_names + + +@dataclass +class LogState: + # qualified log names -> currently set log level + log_qname_to_level: dict[str, str] = field(default_factory=dict) + + # the set of currently enabled artifacts + artifact_names: set[str] = field(default_factory=set) + + def enable_artifact(self, artifact_name) -> None: + self.artifact_names.add(artifact_name) + + def is_artifact_enabled(self, name): + return name in self.artifact_names + + def enable_log(self, log_qnames, log_level) -> None: + if isinstance(log_qnames, str): + log_qnames = [log_qnames] + for log_qname in log_qnames: + self.log_qname_to_level[log_qname] = log_level + + def get_log_level_pairs(self): + """Returns all qualified module names for which the user requested + explicit logging settings. + + .. warning: + + This function used to return all loggers, regardless of whether + or not the user specified them or not; it now only returns logs + which were explicitly mentioned by the user (and torch, which + always is implicitly requested when we initialize our logging + subsystem.) + """ + return self.log_qname_to_level.items() + + def clear(self) -> None: + self.log_qname_to_level.clear() + self.artifact_names.clear() + + +log_registry = LogRegistry() +log_state = LogState() + +# sample usage: torch._logging.set_logs(**torch._logging.DEFAULT_LOGGING) +DEFAULT_LOGGING = { + "dynamo": logging.INFO, + "aot": logging.INFO, + "inductor": logging.INFO, + "fsdp": logging.INFO, + "ddp_graphs": True, + "graph_breaks": True, + "side_effects": True, + "guards": True, + "recompiles": True, + "dynamic": logging.INFO, +} + + +def set_logs( + *, + all: int | None = None, + dynamo: int | None = None, + aot: int | None = None, + autograd: int | None = None, + dynamic: int | None = None, + inductor: int | None = None, + distributed: int | None = None, + c10d: int | None = None, + ddp: int | None = None, + fsdp: int | None = None, + dtensor: int | None = None, + onnx: int | None = None, + bytecode: bool = False, + aot_graphs: bool = False, + aot_joint_graph: bool = False, + ddp_graphs: bool = False, + graph: bool = False, + graph_code: bool = False, + graph_code_verbose: bool = False, + graph_breaks: bool = False, + side_effects: bool = False, + graph_sizes: bool = False, + guards: bool = False, + recompiles: bool = False, + recompiles_verbose: bool = False, + trace_source: bool = False, + trace_call: bool = False, + trace_bytecode: bool = False, + output_code: bool = False, + kernel_code: bool = False, + schedule: bool = False, + perf_hints: bool = False, + pre_grad_graphs: bool = False, + post_grad_graphs: bool = False, + ir_pre_fusion: bool = False, + ir_post_fusion: bool = False, + onnx_diagnostics: bool = False, + fusion: bool = False, + overlap: bool = False, + export: int | None = None, + modules: dict[str, int | bool] | None = None, + cudagraphs: bool = False, + sym_node: bool = False, + compiled_autograd: bool = False, + compiled_autograd_verbose: bool = False, + cudagraph_static_inputs: bool = False, + benchmarking: bool = False, + autotuning: bool = False, + autotuning_inputs: bool = False, + incremental: bool = False, + graph_region_expansion: bool = False, + inductor_metrics: bool = False, + hierarchical_compile: bool = False, + compute_dependencies: bool = False, + caching: bool = False, + partitioned_scatter: bool = False, +) -> None: + """ + Sets the log level for individual components and toggles individual log + artifact types. + + .. warning:: This feature is a prototype and may have compatibility + breaking changes in the future. + + .. note:: The ``TORCH_LOGS`` environment variable has complete precedence + over this function, so if it was set, this function does nothing. + + A component is a set of related features in PyTorch. All of the log + messages emitted from a given component have their own log levels. If the + log level of a particular message has priority greater than or equal to its + component's log level setting, it is emitted. Otherwise, it is suppressed. + This allows you to, for instance, silence large groups of log messages that + are not relevant to you and increase verbosity of logs for components that + are relevant. The expected log level values, ordered from highest to lowest + priority, are: + + * ``logging.CRITICAL`` + * ``logging.ERROR`` + * ``logging.WARNING`` + * ``logging.INFO`` + * ``logging.DEBUG`` + * ``logging.NOTSET`` + + See documentation for the Python ``logging`` module for more information on + log levels: ``_ + + An artifact is a particular type of log message. Each artifact is assigned + to a parent component. A component can emit many different kinds of + artifacts. In general, an artifact is emitted if either its corresponding + setting in the argument list below is turned on or if its parent component + is set to a log level less than or equal to the log level of the artifact. + + Keyword args: + all (:class:`Optional[int]`): + The default log level for all components. Default: ``logging.WARN`` + + dynamo (:class:`Optional[int]`): + The log level for the TorchDynamo component. Default: ``logging.WARN`` + + aot (:class:`Optional[int]`): + The log level for the AOTAutograd component. Default: ``logging.WARN`` + + autograd (:class:`Optional[int]`): + The log level for autograd. Default: ``logging.WARN`` + + inductor (:class:`Optional[int]`): + The log level for the TorchInductor component. Default: ``logging.WARN`` + + dynamic (:class:`Optional[int]`): + The log level for dynamic shapes. Default: ``logging.WARN`` + + distributed (:class:`Optional[int]`): + Whether to log c10d communication operations and other debug info from PyTorch Distributed components. + Default: ``logging.WARN`` + + c10d (:class:`Optional[int]`): + Whether to log c10d communication operations related debug info in PyTorch Distributed components. + Default: ``logging.WARN`` + + ddp (:class:`Optional[int]`): + Whether to log debug info related to ``DistributedDataParallel``(DDP) from PyTorch Distributed components. + Default: ``logging.WARN`` + + fsdp (:class:`Optional[int]`): + Whether to log debug info related to ``FullyShardedDataParallel``(FSDP) in PyTorch Distributed components. + Default: ``logging.WARN`` + + dtensor (:class:`Optional[int]`): + Whether to log debug info related to ``DTensor``(DTensor) in PyTorch Distributed components. + Default: ``logging.WARN`` + + onnx (:class:`Optional[int]`): + The log level for the ONNX exporter component. Default: ``logging.WARN`` + + bytecode (:class:`bool`): + Whether to emit the original and generated bytecode from TorchDynamo. + Default: ``False`` + + aot_graphs (:class:`bool`): + Whether to emit the graphs generated by AOTAutograd. Default: ``False`` + + aot_joint_graph (:class:`bool`): + Whether to emit the joint forward-backward graph generated by AOTAutograd. Default: ``False`` + + ddp_graphs (:class:`bool`): + Whether to emit graphs generated by DDPOptimizer. Default: ``False`` + + graph (:class:`bool`): + Whether to emit the graph captured by TorchDynamo in tabular format. + Default: ``False`` + + graph_code (:class:`bool`): + Whether to emit the python source of the graph captured by TorchDynamo. + Default: ``False`` + + graph_code_verbose (:class:`bool`): + Whether to emit verbose/intermediate FX pass logs for graph code. Default: ``False`` + + graph_breaks (:class:`bool`): + Whether to emit the graph breaks encountered by TorchDynamo. + Default: ``False`` + + side_effects (:class:`bool`): + Whether to emit side effects (mutations, hooks, etc.) that TorchDynamo + codegenerates in the output graph. Default: ``False`` + + graph_sizes (:class:`bool`): + Whether to emit tensor sizes of the graph captured by TorchDynamo. + Default: ``False`` + + guards (:class:`bool`): + Whether to emit the guards generated by TorchDynamo for each compiled + function. Default: ``False`` + + recompiles (:class:`bool`): + Whether to emit a guard failure reason and message every time + TorchDynamo recompiles a function. Default: ``False`` + + recompiles_verbose (:class:`bool`): + Whether to emit all guard failure reasons when TorchDynamo recompiles + a function, even those that are not actually run. Default: ``False`` + + trace_source (:class:`bool`): + Whether to emit when TorchDynamo begins tracing a new line. Default: ``False`` + + trace_call (:class:`bool`): + Whether to emit detailed line location when TorchDynamo creates an FX node + corresponding to function call. Python 3.11+ only. Default: ``False`` + + trace_bytecode (:class:`bool`): + Whether to emit bytecode instructions and traced stack state as TorchDynamo + traces bytecode. Default: ``False`` + + output_code (:class:`bool`): + Whether to emit the TorchInductor output code on a per-graph basis. Default: ``False`` + + kernel_code (:class:`bool`): + Whether to emit the TorchInductor output code on a per-kernel basis. Default: ``False`` + + schedule (:class:`bool`): + Whether to emit the TorchInductor schedule. Default: ``False`` + + perf_hints (:class:`bool`): + Whether to emit the TorchInductor perf hints. Default: ``False`` + + pre_grad_graphs (:class:`bool`): + Whether to emit the graphs before inductor grad passes. Default: ``False`` + + post_grad_graphs (:class:`bool`): + Whether to emit the graphs generated by after post grad passes. Default: ``False`` + + ir_pre_fusion (:class:`bool`): + Whether to emit the graphs before inductor fusion passes. Default: ``False`` + + ir_post_fusion (:class:`bool`): + Whether to emit the graphs after inductor fusion passes. Default: ``False`` + + onnx_diagnostics (:class:`bool`): + Whether to emit the ONNX exporter diagnostics in logging. Default: ``False`` + + fusion (:class:`bool`): + Whether to emit detailed Inductor fusion decisions. Default: ``False`` + + overlap (:class:`bool`): + Whether to emit detailed Inductor compute/comm overlap decisions. Default: ``False`` + + sym_node (:class:`bool`): + Whether to emit debug info for various SymNode operations. Default: ``False`` + + export (:class:`Optional[int]`): + The log level for export. Default: ``logging.WARN`` + + benchmarking (:class:`bool`): + Whether to emit detailed Inductor benchmarking information. Default: ``False`` + + modules (dict): + This argument provides an alternate way to specify the above log + component and artifact settings, in the format of a keyword args + dictionary given as a single argument. There are two cases + where this is useful (1) if a new log component or artifact has + been registered but a keyword argument for it has not been added + to this function and (2) if the log level for an unregistered module + needs to be set. This can be done by providing the fully-qualified module + name as the key, with the log level as the value. Default: ``None`` + + cudagraph_static_inputs (:class:`bool`): + Whether to emit debug info for cudagraph static input detection. Default: ``False`` + + autotuning (:class:`bool`): + Autotuning choice logs, such as kernel source, perf, and tuning parameters. Default: ``False`` + + autotuning_inputs (:class:`bool`): + Per-kernel input tensor shapes/dtypes/strides logged during autotuning. Default: ``False`` + + incremental (:class:`bool`): + Incremental autotuning logs. Default: ``False`` + + graph_region_expansion (:class:`bool`): + Whether to emit the detailed steps of the duplicate graph region tracker expansion algorithm. Default: ``False`` + + inductor_metrics (:class:`bool`): + Whether to estimate the runtimes of the nodes in a graph and log them to the metrics table. Default: ``False`` + + hierarchical_compile (:class:`bool`): + Whether to emit debug info for hierarchical compilation. Default: ``False`` + + caching (:class:`bool`): + Whether to emit detailed Inductor caching information. Default: ``False`` + + Example:: + + >>> # xdoctest: +SKIP + >>> import logging + + # The following changes the "dynamo" component to emit DEBUG-level + # logs, and to emit "graph_code" artifacts. + + >>> torch._logging.set_logs(dynamo=logging.DEBUG, graph_code=True) + + # The following enables the logs for a different module + + >>> torch._logging.set_logs(modules={"unregistered.module.name": logging.DEBUG}) + """ + # ignore if env var is set + if LOG_ENV_VAR in os.environ: + log.warning( + "Using TORCH_LOGS environment variable for log settings, ignoring call to set_logs" + ) + return + + log_state.clear() + + modules = modules or {} + + def _set_logs(**kwargs) -> None: + for alias, val in itertools.chain(kwargs.items(), modules.items()): # type: ignore[union-attr] + if val is None: + continue + + if log_registry.is_artifact(alias): + if not isinstance(val, bool): + raise ValueError( + f"Expected bool to enable artifact {alias}, received {val}" + ) + + if val: + log_state.enable_artifact(alias) + elif log_registry.is_log(alias) or alias in log_registry.child_log_qnames: + if val not in logging._levelToName: + raise ValueError( + f"Unrecognized log level for log {alias}: {val}, valid level values " + f"are: {','.join([str(k) for k in logging._levelToName])}" + ) + + log_state.enable_log( + log_registry.log_alias_to_log_qnames.get(alias, alias), val + ) + elif _is_valid_module(alias): + found_modules = _get_module_and_submodules(alias) or (alias,) + for module_name in found_modules: + if not _has_registered_parent(module_name): + log_registry.register_log(module_name, module_name) + else: + log_registry.register_child_log(module_name) + log_state.enable_log( + log_registry.log_alias_to_log_qnames.get( + module_name, module_name + ), + val, + ) + else: + raise ValueError( + f"Unrecognized log or artifact name passed to set_logs: {alias}" + ) + + _init_logs() + + _set_logs( + torch=all, + dynamo=dynamo, + aot=aot, + autograd=autograd, + inductor=inductor, + dynamic=dynamic, + bytecode=bytecode, + aot_graphs=aot_graphs, + aot_joint_graph=aot_joint_graph, + ddp_graphs=ddp_graphs, + distributed=distributed, + c10d=c10d, + ddp=ddp, + fsdp=fsdp, + dtensor=dtensor, + graph=graph, + graph_code=graph_code, + graph_code_verbose=graph_code_verbose, + graph_breaks=graph_breaks, + side_effects=side_effects, + graph_sizes=graph_sizes, + guards=guards, + recompiles=recompiles, + recompiles_verbose=recompiles_verbose, + trace_source=trace_source, + trace_call=trace_call, + trace_bytecode=trace_bytecode, + output_code=output_code, + kernel_code=kernel_code, + schedule=schedule, + perf_hints=perf_hints, + pre_grad_graphs=pre_grad_graphs, + post_grad_graphs=post_grad_graphs, + ir_pre_fusion=ir_pre_fusion, + ir_post_fusion=ir_post_fusion, + onnx=onnx, + onnx_diagnostics=onnx_diagnostics, + fusion=fusion, + overlap=overlap, + sym_node=sym_node, + export=export, + cudagraphs=cudagraphs, + compiled_autograd=compiled_autograd, + compiled_autograd_verbose=compiled_autograd_verbose, + cudagraph_static_inputs=cudagraph_static_inputs, + benchmarking=benchmarking, + autotuning=autotuning, + autotuning_inputs=autotuning_inputs, + incremental=incremental, + graph_region_expansion=graph_region_expansion, + inductor_metrics=inductor_metrics, + hierarchical_compile=hierarchical_compile, + compute_dependencies=compute_dependencies, + caching=caching, + partitioned_scatter=partitioned_scatter, + ) + + +def get_loggers() -> list[logging.Logger]: + """ + Returns: a list of all registered loggers + """ + return [logging.getLogger(qname) for qname in log_registry.get_log_qnames()] + + +def register_log(setting_name, log_name) -> None: + """ + Enables a log to be controlled by the env var and user API with the setting_name + Args: + setting_name: the shorthand name used in the env var and user API + log_name: the log name that the setting_name is associated with + """ + log_registry.register_log(setting_name, log_name) + + +def register_artifact( + setting_name, description, visible=False, off_by_default=False, log_format=None +) -> None: + """ + Enables an artifact to be controlled by the env var and user API with name + Args: + setting_name: the shorthand name used in the env var and user API + description: A description of what this outputs + visible: Whether it gets suggested to users by default + off_by_default: whether this artifact should be logged when the ancestor loggers + are enabled at level DEBUG + """ + log_registry.register_artifact_name( + setting_name, description, visible, off_by_default, log_format + ) + + +def getArtifactLogger(module_qname, artifact_name) -> logging.Logger: + if artifact_name not in log_registry.artifact_names: + raise ValueError( + f"Artifact name: {repr(artifact_name)} not registered," + f"please call register_artifact({repr(artifact_name)}) in torch._logging.registrations." + ) + qname = module_qname + f".__{artifact_name}" + log = logging.getLogger(qname) + log.artifact_name = artifact_name # type: ignore[attr-defined] + log_registry.register_artifact_log(qname) + configure_artifact_log(log) + return log + + +INCR_VERBOSITY_CHAR = "+" +DECR_VERBOSITY_CHAR = "-" +VERBOSITY_REGEX = ( + "(" + + "|".join([re.escape(INCR_VERBOSITY_CHAR), re.escape(DECR_VERBOSITY_CHAR)]) + + "?)" +) + + +def configure_artifact_log(log) -> None: + # If the artifact is off by default, then it should only be logged when explicitly + # enabled; set propagate to False so that this artifact is not propagated + # to its ancestor logger + if log_registry.is_off_by_default(log.artifact_name): + log.propagate = False + + # enable artifact logging when explicitly enabled + if log_state.is_artifact_enabled(log.artifact_name): + log.setLevel(logging.DEBUG) + log.propagate = True + + +# match a comma separated list of loggable names (whitespace allowed after commas) +def _gen_settings_regex(): + return re.compile(r"((\+|-)?[\w\.]+,\s*)*(\+|-)?[\w\.]+?") + + +def _validate_settings(settings): + return re.fullmatch(_gen_settings_regex(), settings) is not None + + +def help_message(verbose=False): + def pad_to(s, length=30): + if len(s) > length: + raise AssertionError(f"string length {len(s)} exceeds max {length}") + return s + " " * (length - len(s)) + + if verbose: + printed_artifacts = log_registry.artifact_names + else: + printed_artifacts = log_registry.visible_artifacts + if verbose: + heading = "All registered names" + else: + heading = "Visible registered names (use TORCH_LOGS='+help' for full list)" + lines = ( + ["all"] + + sorted(log_registry.log_alias_to_log_qnames.keys()) + + sorted( + [ + f"{pad_to(name)}\t{log_registry.artifact_descriptions[name]}" + for name in printed_artifacts + ] + ) + ) + setting_info = " " + "\n ".join(lines) + examples = """ +Examples: + TORCH_LOGS="+dynamo,aot" will set the log level of TorchDynamo to + logging.DEBUG and AOT to logging.INFO + + TORCH_LOGS="-dynamo,+inductor" will set the log level of TorchDynamo to + logging.ERROR and TorchInductor to logging.DEBUG + + TORCH_LOGS="aot_graphs" will enable the aot_graphs artifact + + TORCH_LOGS="+dynamo,schedule" will enable set the log level of TorchDynamo + to logging.DEBUG and enable the schedule artifact + + TORCH_LOGS="+some.random.module,schedule" will set the log level of + some.random.module to logging.DEBUG and enable the schedule artifact + + TORCH_LOGS="+torch._functorch._aot_autograd" will set the log level of + torch._functorch._aot_autograd and all its submodules to logging.DEBUG + (directory-based logging) + + TORCH_LOGS_FORMAT="%(levelname)s: %(message)s" or any provided format + string will set the output format + Valid keys are "levelname", "message", "pathname", "levelno", "lineno", + "filename" and "name". + + TORCH_LOGS_OUT=/tmp/output.txt will output the logs to /tmp/output.txt as + well. This is useful when the output is long. +""" + msg = f""" +TORCH_LOGS Info +{examples} + +{heading} +{setting_info} +""" + return msg + + +def _invalid_settings_err_msg(settings, verbose=False): + valid_settings = ( + ["all"] + + list(log_registry.log_alias_to_log_qnames.keys()) + + list(log_registry.artifact_names) + ) + valid_settings = ", ".join(sorted(valid_settings)) + msg = f""" +Invalid log settings: {settings}, must be a comma separated list of fully +qualified module names, registered log names or registered artifact names. +For more info on various settings, try TORCH_LOGS="help" +Valid settings: +{valid_settings} +""" + return msg + + +def process_env_var_string_for_windows(env_var_str: str) -> str: + """ + When we setup logging config as guide: https://docs.pytorch.org/docs/stable/logging.html + Such as: + TORCH_LOGS="+schedule,+inductor,+output_code" + + On Linux, it shows as: + declare -x SSH_TTY="/dev/pts/0" + declare -x TERM="xterm" + declare -x TORCH_LOGS="+schedule,+inductor,+output_code" + declare -x USER="xu" + + On Windows, it shows as: + TORCHINDUCTOR_WINDOWS_TESTS=1 + TORCH_LOGS="+schedule,+inductor,+output_code" + UCRTVersion=10.0.22000.0 + + For Linux, it shows quotes by default, And Windows is not shows quotes. + Besides that, Windows would auto assemble quotes when env var processing. + On Linux, we will get variable: "+schedule,+inductor,+output_code" + On Windows, we will get variable: '"+schedule,+inductor,+output_code"' + + So, we need remove the outer quotes for Windows. + """ + _IS_WINDOWS = sys.platform == "win32" + + def remove_outer_quotes(s: str) -> str: + if len(s) >= 2 and ( + (s[0] == '"' and s[-1] == '"') or (s[0] == "'" and s[-1] == "'") + ): + return s[1:-1] + return s + + if _IS_WINDOWS: + env_var_str = remove_outer_quotes(env_var_str) + + return env_var_str + + +@functools.lru_cache +def _parse_log_settings(settings): + settings = process_env_var_string_for_windows(settings) + + if settings == "": + return {} + + if settings == "help": + raise ValueError(help_message(verbose=False)) + elif settings == "+help": + raise ValueError(help_message(verbose=True)) + if not _validate_settings(settings): + raise ValueError(_invalid_settings_err_msg(settings)) + + settings = re.sub(r"\s+", "", settings) + log_names = settings.split(",") + + def get_name_level_pair(name): + clean_name = name.replace(INCR_VERBOSITY_CHAR, "") + clean_name = clean_name.replace(DECR_VERBOSITY_CHAR, "") + + if name[0] == INCR_VERBOSITY_CHAR: + level = logging.DEBUG + elif name[0] == DECR_VERBOSITY_CHAR: + level = logging.ERROR + else: + level = logging.INFO + + return clean_name, level + + log_state = LogState() + + for name in log_names: + name, level = get_name_level_pair(name) + + if name == "all": + name = "torch" + + if log_registry.is_log(name): + if level is None: + raise AssertionError("level must not be None for log name") + log_qnames = log_registry.log_alias_to_log_qnames[name] + log_state.enable_log(log_qnames, level) + elif log_registry.is_artifact(name): + log_state.enable_artifact(name) + elif _is_valid_module(name): + # Get the module and all its submodules if it's a package + found_modules = _get_module_and_submodules(name) or (name,) + for module_name in found_modules: + if not _has_registered_parent(module_name): + log_registry.register_log(module_name, module_name) + else: + log_registry.register_child_log(module_name) + log_state.enable_log(module_name, level) + else: + raise ValueError(_invalid_settings_err_msg(settings)) + + return log_state + + +def _is_valid_module(qname): + spec = importlib.util.find_spec(qname) + return spec is not None + + +def _get_module_and_submodules(qname: str) -> Sequence[str] | None: + """ + Get a module and all its submodules (recursively). + + If qname is a package, this returns a list of all modules and submodules. + If qname is a simple module, this returns a list containing just that module. + + Args: + qname: The fully qualified module name + + Returns: + A list of fully qualified module names, or None if the module doesn't exist + """ + spec = importlib.util.find_spec(qname) + if spec is None: + return None + + modules = [qname] + + if spec.submodule_search_locations is not None: + package = importlib.import_module(qname) + if hasattr(package, "__path__"): + for importer, modname, ispkg in pkgutil.walk_packages( + path=package.__path__, + prefix=qname + ".", + onerror=lambda x: None, + ): + modules.append(modname) + + return modules + + +def _update_log_state_from_env() -> None: + global log_state + log_setting = os.environ.get(LOG_ENV_VAR, None) + if log_setting is not None: + log_state = _parse_log_settings(log_setting) + + +def _has_registered_parent(log_qname) -> bool: + cur_log = logging.getLogger(log_qname) + + registered_log_qnames = log_registry.get_log_qnames() + + while cur_log.parent: + if cur_log.name in registered_log_qnames: + return True + cur_log = cur_log.parent + + return False + + +@functools.lru_cache +def _make_module_path_relative(abs_path: str, sys_path: tuple[str, ...]) -> str: + """ + The string manipulation here is fairly expensive and we expect very high + cache hit rates. Because `sys.path` changes very infrequently it's most + performant to convert it into a tuple of strings and use that for the cache + key because python has dedicated fast paths for list to tuple conversion + and tuple hashing. (Empirically, a single top-level cache is about 2x faster + than trying to cache individual parts.) + """ + + abs_path_resolved = pathlib.Path(abs_path).resolve() + + for path in sys_path: + try: + rel_path = abs_path_resolved.relative_to(path) + except ValueError: + continue + else: + return str(rel_path) + + return str(abs_path_resolved) + + +def make_module_path_relative(abs_path: str) -> str: + """ + Given an absolute filepath corresponding to a Python module which was + loaded via normal import mechanisms using sys.path, convert it into + a relative path relative to one of the Python search paths. + """ + return _make_module_path_relative(abs_path, tuple(sys.path)) + + +# apply custom formats to artifacts when necessary +class TorchLogsFormatter(logging.Formatter): + def __init__( + self, *, trace: bool = False, trace_id_filter: set[str] | None = None + ) -> None: + super().__init__() + self._is_trace = trace + self._trace_id_filter = trace_id_filter + + def format(self, record): + artifact_name = getattr(logging.getLogger(record.name), "artifact_name", None) + if artifact_name is not None: + artifact_formatter = log_registry.artifact_log_formatters.get( + artifact_name, None + ) + if artifact_formatter is not None: + return artifact_formatter.format(record) + + record.message = record.getMessage() + record.asctime = self.formatTime(record, "%m%d %H:%M:%S") + + # exception handling - copied from logging.Formatter.format + s = record.message + if record.exc_info: + from torch._dynamo import config + + should_format_exc = config.verbose or artifact_name != "graph_breaks" + # Cache the traceback text to avoid converting it multiple times + # (it's constant anyway) + if should_format_exc: + if not record.exc_text: + record.exc_text = self.formatException(record.exc_info) + if record.exc_text: + if s[-1:] != "\n": + s = s + "\n" + s = s + record.exc_text + if record.stack_info: + if s[-1:] != "\n": + s = s + "\n" + s = s + self.formatStack(record.stack_info) + + record.rankprefix = "" + if not self._is_trace and dist.is_available() and dist.is_initialized(): + record.rankprefix = f"[rank{dist.get_rank()}]:" + + record.traceid = "" + if ( + not self._is_trace + and (trace_id := torch._guards.CompileContext.current_trace_id()) + is not None + ): + record.traceid = f" [{trace_id}]" + + glog_level_to_abbr = { + "DEBUG": "V", # V is for VERBOSE in glog + "INFO": "I", + "WARNING": "W", + "ERROR": "E", + "CRITICAL": "C", + } + + shortlevel = glog_level_to_abbr.get(record.levelname, record.levelname) + + record.artifactprefix = "" + if artifact_name is not None: + record.artifactprefix = f" [__{artifact_name}]" + + filepath = make_module_path_relative(record.pathname) + + if ( + self._trace_id_filter + and record.traceid.strip() not in self._trace_id_filter + ): + return "" + + prefix = ( + f"{record.rankprefix}{shortlevel}{record.asctime}.{int(record.msecs * 1000):06d} {record.process} " + f"{filepath}:" + f"{record.lineno}]{record.traceid}{record.artifactprefix}" + ) + if self._is_trace: + if s != "": + raise AssertionError(f"expected empty string for trace, got {s!r}") + r = f"{prefix} {json.dumps(record.metadata, default=repr)}" + if record.payload is not None: + r += "".join(f"\n\t{l}" for l in record.payload.split("\n")) + return r + else: + lines = s.split("\n") + return "\n".join(f"{prefix} {l}" for l in lines) + + +def _default_formatter(): + fmt = os.environ.get(LOG_FORMAT_ENV_VAR, None) + trace_id_filter = { + item.strip() + for item in os.environ.get(LOG_TRACE_ID_FILTER, "").split(",") + if item.strip() + } + if fmt is None: + return TorchLogsFormatter(trace_id_filter=trace_id_filter) + else: + if fmt in ("short", "basic"): + fmt = logging.BASIC_FORMAT + return logging.Formatter(fmt) + + +DEFAULT_FORMATTER = _default_formatter() + + +class _StderrHandler(logging.Handler): + """ + A logging handler that follows the current sys.stderr. + + Test capture tools can replace and later close sys.stderr before Python + atexit handlers run. Some PT2 logs intentionally emit from atexit, so the + console handler must not retain a stale captured stream. + """ + + terminator = "\n" + + @property + def stream(self) -> Any: + return sys.stderr + + def flush(self) -> None: + self.acquire() + try: + stream = self.stream + if stream and hasattr(stream, "flush"): + stream.flush() + finally: + self.release() + + def emit(self, record: logging.LogRecord) -> None: + try: + msg = self.format(record) + stream = self.stream + stream.write(msg + self.terminator) + self.flush() + except RecursionError: + raise + except Exception: + self.handleError(record) + + +def _setup_handlers(create_handler_fn, log) -> None: + debug_handler = _track_handler(create_handler_fn()) + debug_handler.setFormatter(DEFAULT_FORMATTER) + debug_handler.setLevel(logging.DEBUG) + log.addHandler(debug_handler) + + +handlers = WeakSet() # type: ignore[var-annotated] +_TORCH_HANDLER_MARKER = "_torch_logging_internal_handler" + + +# mark handlers that we've created +# so we don't modify user handlers +def _track_handler(handler): + setattr(handler, _TORCH_HANDLER_MARKER, True) + handlers.add(handler) + return handler + + +def _is_torch_handler(handler): + return handler in handlers or getattr(handler, _TORCH_HANDLER_MARKER, False) + + +# clears all torch handlers on specified loggers +def _clear_handlers(log, *, close: bool = True) -> None: + to_remove = [handler for handler in log.handlers if _is_torch_handler(handler)] + for handler in to_remove: + log.removeHandler(handler) + if close: + handler.close() + + +def _reset_logs() -> None: + # reset all registered logs + for log_qname in log_registry.get_log_qnames(): + log = logging.getLogger(log_qname) + log.setLevel(logging.WARNING) + log.propagate = False + _clear_handlers(log) + + # reset all artifact and child logs + for artifact_log_qname in itertools.chain( + log_registry.get_artifact_log_qnames(), log_registry.get_child_log_qnames() + ): + log = logging.getLogger(artifact_log_qname) + log.setLevel(logging.NOTSET) + log.propagate = True + + trace_log.propagate = False + # LOG_TRACE_HANDLER is a reusable singleton. Keep its stream lifecycle + # unchanged when _init_logs temporarily removes it from trace_log. + _clear_handlers(trace_log, close=False) + + +def _get_log_state(): + return log_state + + +def _set_log_state(state) -> None: + global log_state + log_state = state + + +def _init_logs(log_file_name=None) -> None: + global GET_DTRACE_STRUCTURED + + _reset_logs() + _update_log_state_from_env() + + out = os.environ.get(LOG_OUT_ENV_VAR, None) + if out is not None: + log_file_name = out + + # First, reset all known (registered) loggers to NOTSET, so that they + # respect their parent log level + for log_qname in log_registry.get_log_qnames(): + # But not the top level torch level: this defaults to WARNING so + # that our log messages don't leak to the lower levels + if log_qname == "torch": + continue + log = logging.getLogger(log_qname) + log.setLevel(logging.NOTSET) + + # Now, for all loggers which the user requested to have non-standard + # logging behavior, modify their log levels + for log_qname, level in log_state.get_log_level_pairs(): + log = logging.getLogger(log_qname) + log.setLevel(level) + + # Finally, setup handlers for all registered loggers + for log_qname in log_registry.get_log_qnames(): + log = logging.getLogger(log_qname) + _setup_handlers( + _StderrHandler, + log, + ) + + if log_file_name is not None: + _setup_handlers( + lambda: logging.FileHandler(log_file_name), + log, + ) + + # configure artifact loggers, note: this must happen last + # since the levels of ancestor loggers are taken into account + for artifact_log_qname in log_registry.get_artifact_log_qnames(): + log = logging.getLogger(artifact_log_qname) + configure_artifact_log(log) + + # Setup handler for the special trace_log, with different default + # configuration + trace_dir_name = os.environ.get(TRACE_ENV_VAR, None) + + # If TORCH_COMPILE_DEBUG=1 is set but no TORCH_TRACE, automatically use + # the torch_compile_debug directory for trace logs (to simplify tlparse usage) + if trace_dir_name is None and os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1": + import torch._dynamo.config as dynamo_config + + trace_dir_name = os.path.join(dynamo_config.debug_dir_root, "tlparse") + + if dtrace_dir_name := os.environ.get(DTRACE_ENV_VAR, None): + GET_DTRACE_STRUCTURED = True + trace_dir_name = dtrace_dir_name + + # This handler may remove itself if trace_dir_name is None and we are not + # actually in an FB environment. This allows us to defer actually + # initializing it until we actually need to log anything. This is + # important because JK initializes a C++ singleton, which will pork our + # process if we subsequently fork. + global LOG_TRACE_HANDLER + if LOG_TRACE_HANDLER is None: + LOG_TRACE_HANDLER = LazyTraceHandler(trace_dir_name) + # This log is ALWAYS at debug level. We will additionally test if there + # are any handlers before deciding to actually call logging on this. Do + # not manually call + trace_log.setLevel(logging.DEBUG) + # Override isEnabledFor so that logging.disable() cannot suppress trace + # events. When TORCH_TRACE is set we always want output regardless of + # the global disable threshold. + trace_log.isEnabledFor = lambda level: level >= trace_log.level + trace_log_handler = _track_handler(LOG_TRACE_HANDLER) + trace_log_handler.setFormatter(TorchLogsFormatter(trace=True)) + trace_log.addHandler(trace_log_handler) + + +class LazyTraceHandler(logging.StreamHandler): + """Like FileHandler, but the file is allocated lazily only upon the first log message""" + + def __init__(self, root_dir: str | None) -> None: + # This is implemented in the same way that delay is implemented on + # FileHandler + self.root_dir = root_dir + logging.Handler.__init__(self) + self.stream = None + self._pid: int | None = None + self._stream_path: str | None = None + self._builtin_open = open + self._pending_log_version = False + + def _close_stream(self, *, flush: bool = True) -> None: + if self.stream: + stream = self.stream + try: + if flush: + self.flush() + finally: + self.stream = None + self._pid = None + self._stream_path = None + self._pending_log_version = False + if flush and hasattr(stream, "close"): + stream.close() + elif not flush: + # stream.close() flushes Python buffers. In a post-fork + # child, close only the inherited fd so parent buffers are + # discarded instead of written to the parent's trace file. + os.close(stream.fileno()) + try: + stream.close() + except OSError as exc: + if exc.errno != errno.EBADF: + raise + + # cloned from FileHandler in cpython + def close(self) -> None: + self.acquire() + try: + try: + self._close_stream(flush=self._pid is None or self._pid == os.getpid()) + finally: + # Issue #19523: call unconditionally to + # prevent a handler leak when delay is set + # Also see Issue #42378: we also rely on + # self._closed being set to True there + logging.StreamHandler.close(self) + finally: + self.release() + + def emit(self, record) -> None: + current_pid = os.getpid() + if self.stream is not None and self._pid != current_pid: + self._close_stream(flush=False) + + if self.stream is None: + if self.root_dir is None: + TRACE_LOG_DIR = "/logs" + + import torch.version as torch_version + + if ( + hasattr(torch_version, "git_version") + and os.getenv("MAST_HPC_JOB_NAME") is None + ): + log.info( + "LazyTraceHandler: disabled because not fbcode or conda on mast" + ) + elif not torch._utils_internal.justknobs_check("pytorch/trace:enable"): + log.info( + "LazyTraceHandler: disabled because justknobs_check('pytorch/trace:enable') returned False" + ) + elif not os.path.exists(TRACE_LOG_DIR): + log.info( + "LazyTraceHandler: disabled because %s does not exist", + TRACE_LOG_DIR, + ) + elif not os.access(TRACE_LOG_DIR, os.W_OK): + log.info( + "LazyTraceHandler: disabled because %s is not writeable", + TRACE_LOG_DIR, + ) + else: + self.root_dir = TRACE_LOG_DIR + + if self.root_dir is not None: + os.makedirs(self.root_dir, exist_ok=True) + ranksuffix = "" + if dist.is_available() and dist.is_initialized(): + ranksuffix = f"rank_{dist.get_rank()}_" + fd, path = tempfile.mkstemp( + suffix=".log", + prefix=LOG_PREFIX + ranksuffix, + dir=self.root_dir, + ) + self.stream = os.fdopen(fd, mode="w+") + self._pid = current_pid + self._stream_path = path + log.info("LazyTraceHandler: logging to %s", self._stream_path) + # Log tlparse path via inductor logger so it shows when + # TORCH_LOGS="inductor" is enabled + inductor_log = logging.getLogger("torch._inductor") + inductor_log.info("tlparse raw data: %s", self._stream_path) + self._pending_log_version = True + else: + # We go poof, remove and no-op + trace_log.removeHandler(self) + return + if self.stream: + super().emit(record) + if self._pending_log_version: + self._pending_log_version = False + _log_torch_version() + + +def _log_torch_version() -> None: + import torch + from torch._environment import is_fbcode + from torch._utils_internal import get_torch_source_version + + version_info: dict[str, object] = { + "pytorch_version": torch.__version__, + "commit": get_torch_source_version(), + "oss": not is_fbcode(), + } + + trace_structured( + "artifact", + metadata_fn=lambda: {"name": "torch_version", "encoding": "json"}, + payload_fn=lambda: version_info, + suppress_context=True, + expect_trace_id=False, + ) + + +@functools.cache +def warning_once(logger_obj, *args, **kwargs) -> None: + """ + This function is similar to `logger.warning()`, but will emit the warning with the same message only once + Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache. + The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to + another type of cache that includes the caller frame information in the hashing function. + """ + logger_obj.warning(*args, **kwargs) + + +def safe_grad_filter(message, category, filename, lineno, file=None, line=None) -> bool: + return "The .grad attribute of a Tensor" not in str(message) + + +def user_warning_filter( + message, category, filename, lineno, file=None, line=None +) -> bool: + return category is not UserWarning + + +@contextlib.contextmanager +def hide_warnings(filter_fn=lambda *args, **kwargs: True): + """ + A context manager that temporarily suppresses warnings, + using public API: https://docs.python.org/3/library/warnings.html#warnings.showwarning. + + Useful to hide warnings without mutating warnings module state, see: + https://github.com/pytorch/pytorch/issues/128427#issuecomment-2161496162. + + NOTE: Warnings issued under this context will still be cached in the __warningregistry__ + and count towards the once/default rule. So you should NEVER use this on a user-land function. + + Filter must implement the showwarning API: + def filter_fn(message, category, filename, lineno, file=None, line=None) -> bool: + return True # show this warning entry + """ + prior = warnings.showwarning + + def _showwarning(*args, **kwargs): + if filter_fn(*args, **kwargs): + prior(*args, **kwargs) + + try: + warnings.showwarning = _showwarning + yield + finally: + warnings.showwarning = prior + + +class LazyString(Generic[_P]): + def __init__( + self, func: Callable[_P, str], *args: _P.args, **kwargs: _P.kwargs + ) -> None: + self.func = func + self.args = args + self.kwargs = kwargs + + def __str__(self) -> str: + return self.func(*self.args, **self.kwargs) + + +# Logs the time it takes to do structured logging by frame/compile id +# key is always {frame_id}_{frame_compile_id} +structured_logging_overhead: dict[str, float] = defaultdict(float) + + +def add_structured_logging_overhead(time_spent: float) -> None: + global structured_logging_overhead + key = None + if (trace_id := torch._guards.CompileContext.current_trace_id()) is not None: + frame_id = trace_id.compile_id.frame_id + frame_compile_id = trace_id.compile_id.frame_compile_id + # Why not trace_id.attempt, like structured logging? + # We aggregate across all attempts because + # a compilation metric is logged per successful attempt + key = f"{frame_id}_{frame_compile_id}" + # TODO: deal with structured logging that occurs outside of specific compile ids + # It's hard to figure out where we would log that if we want it in compilation metrics + # itself. + if key is not None: + key = str(key) + structured_logging_overhead[key] += time_spent + + +def get_structured_logging_overhead() -> float | None: + key = None + if (trace_id := torch._guards.CompileContext.current_trace_id()) is not None: + frame_id = trace_id.compile_id.frame_id + frame_compile_id = trace_id.compile_id.frame_compile_id + key = f"{frame_id}_{frame_compile_id}" + if key is not None: + return structured_logging_overhead.get(key) + else: + return None + + +def trace_structured_artifact( + name: str, # this will go in metadata + encoding: str, + payload_fn: Callable[[], str | object | None] = lambda: None, + compile_id: CompileId | None = None, +) -> None: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": name, + "encoding": encoding, + }, + payload_fn=payload_fn, + compile_id=compile_id, + ) + + +def trace_structured( + name: str, + # NB: metadata expected to be dict so adding more info is forward compatible + # Tuple[str, int] is a special case for string interning + metadata_fn: Callable[[], dict[str, Any] | tuple[str, int]] = dict, + *, + payload_fn: Callable[[], str | object | None] = lambda: None, + suppress_context: bool = False, + expect_trace_id: bool = True, # Whether or not we expect to have a current trace id + record_logging_overhead: bool = True, # Whether or not to record the time spent on structured logging + compile_id: CompileId | None = None, # Optional if unavailable in the trace +) -> None: + """ + metadata is an arbitrary JSON compatible struct, but it's expected to not be + too long (e.g., less than 1MB) + + payload is an arbitrary string, which can be arbitrarily long (but expected to have + newlines so no lines are too long) + """ + reserved_names = [ + "rank", + "compiled_autograd_id", + "frame_id", + "frame_compile_id", + "attempt", + "severity", + "timestamp", + "pathname", + "thread", + "subgraph_name", + ] + if name in reserved_names: + raise AssertionError(f"name {name!r} is reserved and cannot be used") + if not callable(metadata_fn): + raise AssertionError( + f"metadata_fn should be callable, but got {type(metadata_fn)}" + ) + if not callable(payload_fn): + raise AssertionError( + f"payload_fn should be callable, but got {type(payload_fn)}" + ) + # trace_log never propagates and is ALWAYS DEBUG, so also check that there + # are handlers instead of checking the log level + if trace_log.handlers: + start_time = time.time_ns() + record: dict[str, object] = {} + record[name] = metadata_fn() + if not suppress_context: + # TODO: Actually, the rank probably should just be emitted once at + # the top, and not repeatedly spammed in all the logs, since it + # never changes and we assume no interleaving + if dist.is_available() and dist.is_initialized(): + record["rank"] = dist.get_rank() + + trace_id = torch._guards.CompileContext.current_trace_id() + if expect_trace_id and trace_id is None and compile_id is None: + # Record the stack of the log call to better diagnose why we + # don't have a frame id for it + record["stack"] = torch._logging.structured.from_traceback( + CapturedTraceback.extract(skip=1).summary() + ) + else: + cid = trace_id.compile_id if trace_id else compile_id + if cid is not None: + if cid.compiled_autograd_id is not None: + record["compiled_autograd_id"] = cid.compiled_autograd_id + if cid.frame_id is not None: + record["frame_id"] = cid.frame_id + if cid.frame_compile_id is not None: + record["frame_compile_id"] = cid.frame_compile_id + if trace_id: + record["attempt"] = trace_id.attempt + + from torch.fx.traceback import _get_regional_inductor_subgraph_name + + subgraph_name = _get_regional_inductor_subgraph_name() + if subgraph_name is not None: + record["subgraph_name"] = subgraph_name + + payload = payload_fn() + if payload is not None: + if not isinstance(payload, str): + if isinstance(payload, list): + # special case to look better + payload = "[\n" + ",\n".join(json.dumps(i) for i in payload) + "\n]" + else: + + def json_default(obj): + # Sets aren't json serializable + if isinstance(obj, set): + return list(obj) + raise TypeError( + f"Object of type {type(obj)} is not JSON serializable" + ) + + # force newlines so we are unlikely to overflow line limit + payload = json.dumps(payload, default=json_default, indent=0) + h = hashlib.md5(usedforsecurity=False) + h.update(payload.encode("utf-8")) + record["has_payload"] = h.hexdigest() + trace_log.debug( + "", extra={"metadata": record, "payload": payload}, stacklevel=2 + ) + log_trace_structured_event(name, record) + + if record_logging_overhead: + # Convert to seconds from nanoseconds, add it to the frame compile total + structured_logging_overhead_s = (time.time_ns() - start_time) / 1e9 + add_structured_logging_overhead(structured_logging_overhead_s) + + +def dtrace_structured( + name: str, + # NB: metadata expected to be dict so adding more info is forward compatible + # Tuple[str, int] is a special case for string interning + metadata_fn: Callable[[], dict[str, Any] | tuple[str, int]] = dict, + *, + payload_fn: Callable[[], str | object | None] = lambda: None, + suppress_context: bool = False, + expect_trace_id: bool = False, # Whether or not we expect to have a current trace id + record_logging_overhead: bool = True, # Whether or not to record the time spent on structured logging +) -> None: + """ + For logging more detailed information used for debugging. This may result in + the program becoming slow. + """ + if GET_DTRACE_STRUCTURED: + trace_structured( + name, + metadata_fn, + payload_fn=payload_fn, + suppress_context=suppress_context, + expect_trace_id=expect_trace_id, + record_logging_overhead=record_logging_overhead, + ) + + +import torch._guards +import torch._utils_internal +import torch.distributed as dist +import torch.fx.traceback diff --git a/.venv/lib/python3.12/site-packages/torch/_logging/_registrations.py b/.venv/lib/python3.12/site-packages/torch/_logging/_registrations.py new file mode 100644 index 0000000000000000000000000000000000000000..ccb8dbd9cb91ac9102bab11588dc54b1b28b55d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_logging/_registrations.py @@ -0,0 +1,302 @@ +from ._internal import register_artifact, register_log + + +DYNAMIC = [ + "torch.fx.experimental.symbolic_shapes", + "torch.fx.experimental.sym_node", + "torch.fx.experimental.recording", +] +DISTRIBUTED = [ + "torch.distributed", + "torch._dynamo.backends.distributed", + "torch.nn.parallel.distributed", +] + +register_log( + "async_compile", + [ + "torch._inductor.async_compile", + "torch._inductor.compile_worker.tracked_process_pool", + ], +) +register_log( + "cache", ("torch._inductor.remote_cache", "torch._inductor.fb.remote_cache") +) +register_log("dynamo", ["torch._dynamo", *DYNAMIC]) +register_log("fake_tensor", ["torch._subclasses.fake_tensor"]) +register_log("aot", ["torch._functorch.aot_autograd", "torch._functorch._aot_autograd"]) +register_log("autograd", "torch.autograd") +register_log("inductor", ["torch._inductor", "torch._inductor.cudagraph_trees"]) +register_log("flex_gemm", "torch._inductor.kernel.flex_gemm.debug") + +register_artifact( + "cudagraphs", + "Logs information from wrapping inductor generated code with cudagraphs.", +) + +register_log("dynamic", DYNAMIC) +register_log("torch", "torch") +register_log("distributed", DISTRIBUTED) +register_log( + "c10d", ["torch.distributed.distributed_c10d", "torch.distributed.rendezvous"] +) +register_log( + "ddp", ["torch.nn.parallel.distributed", "torch._dynamo.backends.distributed"] +) +register_log("pp", ["torch.distributed.pipelining"]) +register_log("fsdp", ["torch.distributed.fsdp", "torch.distributed._composable.fsdp"]) +register_log("dtensor", ["torch.distributed._tensor", "torch.distributed.tensor"]) +register_log("onnx", "torch.onnx") +register_log("native_dsl", "torch._native") +register_artifact( + "native_dsl_compile", + "Emits a log line and a tlparse record per torch._native DSL compile-cache call " + "(compiles and cache hits). Off by default: this fires on every op call.", + off_by_default=True, +) +register_log( + "export", + [ + "torch._dynamo", + "torch.export", + "torch.export.dynamic_shapes", + *DYNAMIC, + "torch._export.converter", + "torch._export.non_strict_utils", + "torch._export.serde.serialize", + "torch.fx.experimental.proxy_tensor", + ], +) + +register_artifact( + "guards", + "This prints the guards for every compiled Dynamo frame. It does not tell you where the guards come from.", + visible=True, +) +register_artifact("verbose_guards", "", off_by_default=True) +register_artifact( + "bytecode", + "Prints the original and modified bytecode from Dynamo. Mostly useful if you're debugging our bytecode generation in Dynamo.", + off_by_default=True, +) +register_artifact( + "graph", + "Prints the dynamo traced graph (prior to AOTDispatch) in a table. If you prefer python code use `graph_code` instead. ", +) +register_artifact("graph_code", "Like `graph`, but gives you the Python code instead.") +register_artifact( + "graph_code_verbose", + "Verbose FX pass logs, e.g. from tensorify_python_scalars and runtime_assert.", +) +register_artifact( + "graph_sizes", "Prints the sizes of all FX nodes in the dynamo graph." +) +register_artifact( + "trace_source", + "As we execute bytecode, prints the file name / line number we are processing and the actual source code. Useful with `bytecode`", +) +register_artifact( + "trace_call", + "Like trace_source, but it will give you the per-expression blow-by-blow if your Python is recent enough.", +) +register_artifact( + "trace_bytecode", + "As we trace bytecode, prints the instruction and the current stack.", +) +register_artifact( + "aot_graphs", + "Prints the FX forward and backward graph generated by AOTDispatch, after partitioning. Useful to understand what's being given to Inductor", + visible=True, +) +register_artifact( + "aot_joint_graph", + "Print FX joint graph from AOTAutograd, prior to partitioning. Useful for debugging partitioning", +) +register_artifact( + "aot_graphs_effects", + "Prints the FX forward and backward graph generated by AOTDispatch, useful for debugging effects processing.", + visible=True, +) +register_artifact( + "pre_grad_graphs", + "Prints the FX graph before inductor pre grad passes. Useful to understand what's being given to Inductor before grad passes", +) +register_artifact( + "post_grad_graphs", + "Prints the FX graph generated by post grad passes. Useful to understand what's being given to Inductor after post grad passes", +) +register_artifact( + "ir_pre_fusion", + "Prints the IR before inductor fusion passes.", + off_by_default=True, +) +register_artifact( + "ir_post_fusion", + "Prints the IR after inductor fusion passes.", + off_by_default=True, +) +register_artifact( + "compiled_autograd", + "Prints various logs in compiled_autograd, including but not limited to the graphs. Useful for debugging compiled_autograd.", + visible=True, +) +register_artifact( + "compiled_autograd_verbose", + "Will affect performance. Prints compiled_autograd logs with C++ info e.g. autograd node -> fx node mapping", + off_by_default=True, +) +register_artifact( + "ddp_graphs", + "Only relevant for compiling DDP. DDP splits into multiple graphs to trigger comms early. This will print each individual graph here.", +) +register_artifact( + "recompiles", + "Prints the reason why we recompiled a graph. Very, very useful.", + visible=True, +) +register_artifact( + "recompiles_verbose", + "Prints all guard checks that fail during a recompilation. " + "At runtime, Dynamo will stop at the first failed check for each failing guard. " + "So not all logged failing checks are actually ran by Dynamo.", + visible=True, + off_by_default=True, +) +register_artifact( + "graph_breaks", + "Prints whenever Dynamo decides that it needs to graph break (i.e. create a new graph). Useful for debugging why torch.compile has poor performance", + visible=True, +) +register_artifact( + "side_effects", + "Prints all side effects that Dynamo codegenerates, including mutations to variables, attributes, cells, and globals. Useful for debugging side effect handling", + visible=True, +) +register_artifact( + "not_implemented", + "Prints log messages whenever we return NotImplemented in a multi-dispatch, letting you trace through each object we attempted to dispatch to", +) +register_artifact( + "output_code", + "Prints the code that Inductor generates (either Triton or C++)", + off_by_default=True, + visible=True, +) +register_artifact( + "kernel_code", + "Prints the code that Inductor generates (on a per-kernel basis)", + off_by_default=True, + visible=True, +) +register_artifact( + "schedule", + "Inductor scheduler information. Useful if working on Inductor fusion algo", + off_by_default=True, +) +register_artifact("perf_hints", "", off_by_default=True) +register_artifact("onnx_diagnostics", "", off_by_default=True) +register_artifact("compute_dependencies", "", off_by_default=True) +register_artifact( + "fusion", + "Detailed Inductor fusion decisions. More detailed than 'schedule'", + off_by_default=True, +) +register_artifact( + "loop_ordering", + "Logs related to loop ordering", + off_by_default=True, +) +register_artifact( + "loop_tiling", + "Logs related to loop ordering", + off_by_default=True, +) + +register_artifact( + "auto_chunker", + "Logs related to the auto chunker", + off_by_default=True, +) + +register_artifact( + "overlap", + "Detailed Inductor compute/comm overlap decisions", + off_by_default=True, +) +register_artifact( + "overlap_scheduling", + "Detailed Inductor overlap scheduling pass information", + off_by_default=True, +) +register_artifact( + "partitioned_scatter", + "Inductor partitioned scatter pass decisions and memory accounting", + off_by_default=True, +) +register_artifact( + "sym_node", + "Logs extra info for various SymNode operations", + off_by_default=True, +) +register_artifact( + "trace_shape_events", + "Logs traces for every ShapeEnv operation that we record for replay", + off_by_default=True, +) +register_artifact( + "cudagraph_static_inputs", + "Logs static inputs handling in dynamo, AOT, and cudagraphs", + off_by_default=True, +) +register_artifact( + "benchmarking", + "Detailed Inductor benchmarking information.", + off_by_default=True, +) +register_artifact( + "incremental", + "Incremental autotuning logs.", + off_by_default=True, +) +register_artifact( + "node_runtime_estimation", + "Node runtime estimation for compile-time optimization decisions.", + off_by_default=True, +) +register_artifact( + "autotuning", + "Autotuning choice logs, such as kernel source, perf, and tuning parameters.", + off_by_default=True, +) +register_artifact( + "autotuning_inputs", + "Per-kernel input tensor shapes/dtypes/strides logged during autotuning.", + off_by_default=True, +) +register_artifact( + "graph_region_expansion", + "Logs detailed steps of the duplicate graph region tracker expansion algorithm", + off_by_default=True, +) + +register_artifact( + "inductor_metrics", + "Logs Inductor metrics, such as num_bytes, nodes_num_elem, node_runtimes", + off_by_default=True, +) +register_artifact( + "hierarchical_compile", + "Logs debug info for hierarchical compilation", + off_by_default=True, +) +register_artifact( + "annotation", + "Logs detailed steps of the creating annotation on graph nodes", + off_by_default=True, +) +register_artifact("custom_format_test_artifact", "Testing only", log_format="") +register_artifact( + "caching", + "Detailed Inductor caching information.", + off_by_default=True, +) diff --git a/.venv/lib/python3.12/site-packages/torch/_logging/scribe.py b/.venv/lib/python3.12/site-packages/torch/_logging/scribe.py new file mode 100644 index 0000000000000000000000000000000000000000..b928b0f922b6bf2e112983e079bdde8559540fc1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_logging/scribe.py @@ -0,0 +1,63 @@ +from collections.abc import Callable +from typing import TypeAlias + + +try: + from fbscribelogger import ( # type: ignore[import-untyped, import-not-found] + make_scribe_logger, + ) +except ImportError: + TAtom: TypeAlias = int | float | bool | str + TField: TypeAlias = TAtom | list[TAtom] + TLazyField: TypeAlias = TField | Callable[[], TField] + + def make_scribe_logger(name: str, thrift_src: str) -> Callable[..., None]: + def inner(**kwargs: TLazyField) -> None: + pass + + return inner + + +open_source_signpost = make_scribe_logger( + "TorchOpenSourceSignpost", + """ +struct TorchOpenSourceSignpostLogEntry { + + # The commit SHA that triggered the workflow, e.g., 02a6b1d30f338206a71d0b75bfa09d85fac0028a. Derived from GITHUB_SHA. + 4: optional string commit_sha; + + # Commit date (not author date) of the commit in commit_sha as timestamp, e.g., 1724208105. Increasing if merge bot is used, though not monotonic; duplicates occur when stack is landed. + 5: optional i64 commit_date; + + # The fully-formed ref of the branch or tag that triggered the workflow run, e.g., refs/pull/133891/merge or refs/heads/main. Derived from GITHUB_REF. + 6: optional string github_ref; + + # Indicates if branch protections or rulesets are configured for the ref that triggered the workflow run. Derived from GITHUB_REF_PROTECTED. + 7: optional bool github_ref_protected; + + # A unique number for each attempt of a particular workflow run in a repository, e.g., 1. Derived from GITHUB_RUN_ATTEMPT. + 8: optional string github_run_attempt; + + # A unique number for each workflow run within a repository, e.g., 19471190684. Derived from GITHUB_RUN_ID. + 9: optional string github_run_id; + + # A unique number for each run of a particular workflow in a repository, e.g., 238742. Derived from GITHUB_RUN_NUMBER. + 10: optional string github_run_number_str; + + # The name of the current job. Derived from JOB_NAME, e.g., linux-jammy-py3.8-gcc11 / test (default, 3, 4, linux.2xlarge). + 11: optional string job_name; + + # The GitHub user who triggered the job. Derived from GITHUB_TRIGGERING_ACTOR. + 12: optional string github_triggering_actor; + 13: optional string name; # Event name + 14: optional string parameters; # Parameters (JSON data) + 16: optional string subsystem; # Subsystem the event is associated with + + # The unit timestamp in second for the Scuba Time Column override + 17: optional i64 time; + + # The weight of the record according to current sampling rate + 18: optional i64 weight; +} +""", +) diff --git a/.venv/lib/python3.12/site-packages/torch/_logging/structured.py b/.venv/lib/python3.12/site-packages/torch/_logging/structured.py new file mode 100644 index 0000000000000000000000000000000000000000..c31c83ab787bfa85483768db65597e75c22205fc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_logging/structured.py @@ -0,0 +1,109 @@ +""" +Utilities for converting data types into structured JSON for dumping. +""" + +import inspect +import os +import traceback +from collections.abc import Sequence +from typing import Any + +import torch._logging._internal + + +INTERN_TABLE: dict[str, int] = {} + + +DUMPED_FILES: set[str] = set() + + +def intern_string(s: str | None) -> int: + if s is None: + return -1 + + r = INTERN_TABLE.get(s) + if r is None: + r = len(INTERN_TABLE) + INTERN_TABLE[s] = r + torch._logging._internal.trace_structured( + "str", lambda: (s, r), suppress_context=True + ) + return r + + +def dump_file(filename: str) -> None: + if "eval_with_key" not in filename: + return + if filename in DUMPED_FILES: + return + DUMPED_FILES.add(filename) + from torch.fx.graph_module import _loader + + torch._logging._internal.trace_structured( + "dump_file", + metadata_fn=lambda: { + "name": filename, + }, + payload_fn=lambda: _loader.get_source(filename), + ) + + +def from_traceback(tb: Sequence[traceback.FrameSummary]) -> list[dict[str, Any]]: + # dict naming convention here coincides with + # python/combined_traceback.cpp + r = [ + { + "line": frame.lineno, + "name": frame.name, + "filename": intern_string(frame.filename), + "loc": frame.line, + } + for frame in tb + ] + return r + + +def get_user_stack(num_frames: int) -> list[dict[str, Any]]: + from torch._guards import TracingContext + from torch.utils._traceback import CapturedTraceback + + user_tb = TracingContext.extract_stack() + if user_tb: + return from_traceback(user_tb[-1 * num_frames :]) + + tb = CapturedTraceback.extract().summary() + + # Filter out frames that are within the torch/ codebase + torch_filepath = os.path.dirname(inspect.getfile(torch)) + os.path.sep + for i, frame in enumerate(reversed(tb)): + if torch_filepath not in frame.filename: + # Only display `num_frames` frames in the traceback + filtered_tb = tb[len(tb) - i - num_frames : len(tb) - i] + return from_traceback(filtered_tb) + + return from_traceback(tb[-1 * num_frames :]) + + +def get_framework_stack( + num_frames: int = 25, cpp: bool = False +) -> list[dict[str, Any]]: + """ + Returns the traceback for the user stack and the framework stack + """ + from torch.fx.experimental.symbolic_shapes import uninteresting_files + from torch.utils._traceback import CapturedTraceback + + tb = CapturedTraceback.extract(cpp=cpp).summary() + tb = [ + frame + for frame in tb + if ( + ( + frame.filename.endswith(".py") + and frame.filename not in uninteresting_files() + ) + or ("at::" in frame.name or "torch::" in frame.name) + ) + ] + + return from_traceback(tb[-1 * num_frames :]) diff --git a/.venv/lib/python3.12/site-packages/torch/_lowrank.py b/.venv/lib/python3.12/site-packages/torch/_lowrank.py new file mode 100644 index 0000000000000000000000000000000000000000..25089d66d35eaf2fbe186499dde6f3ea51795562 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_lowrank.py @@ -0,0 +1,293 @@ +"""Implement various linear algebra algorithms for low rank matrices.""" + +__all__ = ["svd_lowrank", "pca_lowrank"] + + +import torch +from torch import _linalg_utils as _utils, Tensor +from torch.overrides import handle_torch_function, has_torch_function + + +def get_approximate_basis( + A: Tensor, + q: int, + niter: int | None = 2, + M: Tensor | None = None, +) -> Tensor: + """Return tensor :math:`Q` with :math:`q` orthonormal columns such + that :math:`Q Q^H A` approximates :math:`A`. If :math:`M` is + specified, then :math:`Q` is such that :math:`Q Q^H (A - M)` + approximates :math:`A - M`. without instantiating any tensors + of the size of :math:`A` or :math:`M`. + + .. note:: The implementation is based on the Algorithm 4.4 from + Halko et al., 2009. + + .. note:: For an adequate approximation of a k-rank matrix + :math:`A`, where k is not known in advance but could be + estimated, the number of :math:`Q` columns, q, can be + chosen according to the following criteria: in general, + :math:`k <= q <= min(2*k, m, n)`. For large low-rank + matrices, take :math:`q = k + 5..10`. If k is + relatively small compared to :math:`min(m, n)`, choosing + :math:`q = k + 0..2` may be sufficient. + + .. note:: To obtain repeatable results, reset the seed for the + pseudorandom number generator + + Args:: + A (Tensor): the input tensor of size :math:`(*, m, n)` + + q (int): the dimension of subspace spanned by :math:`Q` + columns. + + niter (int, optional): the number of subspace iterations to + conduct; ``niter`` must be a + nonnegative integer. In most cases, the + default value 2 is more than enough. + + M (Tensor, optional): the input tensor's mean of size + :math:`(*, m, n)`. + + References:: + - Nathan Halko, Per-Gunnar Martinsson, and Joel Tropp, Finding + structure with randomness: probabilistic algorithms for + constructing approximate matrix decompositions, + arXiv:0909.4061 [math.NA; math.PR], 2009 (available at + `arXiv `_). + """ + + niter = 2 if niter is None else niter + dtype = _utils.get_floating_dtype(A) if not A.is_complex() else A.dtype + matmul = _utils.matmul + + R = torch.randn(A.shape[-1], q, dtype=dtype, device=A.device) + + # The following code could be made faster using torch.geqrf + torch.ormqr + # but geqrf is not differentiable + + X = matmul(A, R) + if M is not None: + X = X - matmul(M, R) + Q = torch.linalg.qr(X).Q + for _ in range(niter): + X = matmul(A.mH, Q) + if M is not None: + X = X - matmul(M.mH, Q) + Q = torch.linalg.qr(X).Q + X = matmul(A, Q) + if M is not None: + X = X - matmul(M, Q) + Q = torch.linalg.qr(X).Q + return Q + + +def svd_lowrank( + A: Tensor, + q: int | None = 6, + niter: int | None = 2, + M: Tensor | None = None, +) -> tuple[Tensor, Tensor, Tensor]: + r"""Return the singular value decomposition ``(U, S, V)`` of a matrix, + batches of matrices, or a sparse matrix :math:`A` such that + :math:`A \approx U \operatorname{diag}(S) V^{\text{H}}`. In case :math:`M` is given, then + SVD is computed for the matrix :math:`A - M`. + + .. note:: The implementation is based on the Algorithm 5.1 from + Halko et al., 2009. + + .. note:: For an adequate approximation of a k-rank matrix + :math:`A`, where k is not known in advance but could be + estimated, the number of :math:`Q` columns, q, can be + chosen according to the following criteria: in general, + :math:`k <= q <= min(2*k, m, n)`. For large low-rank + matrices, take :math:`q = k + 5..10`. If k is + relatively small compared to :math:`min(m, n)`, choosing + :math:`q = k + 0..2` may be sufficient. + + .. note:: This is a randomized method. To obtain repeatable results, + set the seed for the pseudorandom number generator + + .. note:: In general, use the full-rank SVD implementation + :func:`torch.linalg.svd` for dense matrices due to its 10x + higher performance characteristics. The low-rank SVD + will be useful for huge sparse matrices that + :func:`torch.linalg.svd` cannot handle. + + Args:: + A (Tensor): the input tensor of size :math:`(*, m, n)` + + q (int, optional): a slightly overestimated rank of A. + + niter (int, optional): the number of subspace iterations to + conduct; niter must be a nonnegative + integer, and defaults to 2 + + M (Tensor, optional): the input tensor's mean of size + :math:`(*, m, n)`, which will be broadcasted + to the size of A in this function. + + References:: + - Nathan Halko, Per-Gunnar Martinsson, and Joel Tropp, Finding + structure with randomness: probabilistic algorithms for + constructing approximate matrix decompositions, + arXiv:0909.4061 [math.NA; math.PR], 2009 (available at + `arXiv `_). + + """ + if not torch.jit.is_scripting(): + tensor_ops = (A, M) + if not set(map(type, tensor_ops)).issubset( + (torch.Tensor, type(None)) + ) and has_torch_function(tensor_ops): + return handle_torch_function( + svd_lowrank, tensor_ops, A, q=q, niter=niter, M=M + ) + return _svd_lowrank(A, q=q, niter=niter, M=M) + + +def _svd_lowrank( + A: Tensor, + q: int | None = 6, + niter: int | None = 2, + M: Tensor | None = None, +) -> tuple[Tensor, Tensor, Tensor]: + # Algorithm 5.1 in Halko et al., 2009 + + q = 6 if q is None else q + m, n = A.shape[-2:] + matmul = _utils.matmul + if M is not None: + M = M.broadcast_to(A.size()) + + # Assume that A is tall + if m < n: + A = A.mH + if M is not None: + M = M.mH + + Q = get_approximate_basis(A, q, niter=niter, M=M) + B = matmul(Q.mH, A) + if M is not None: + B = B - matmul(Q.mH, M) + U, S, Vh = torch.linalg.svd(B, full_matrices=False) + V = Vh.mH + U = Q.matmul(U) + + if m < n: + U, V = V, U + + return U, S, V + + +def pca_lowrank( + A: Tensor, + q: int | None = None, + center: bool = True, + niter: int = 2, +) -> tuple[Tensor, Tensor, Tensor]: + r"""Performs linear Principal Component Analysis (PCA) on a low-rank + matrix, batches of such matrices, or sparse matrix. + + This function returns a namedtuple ``(U, S, V)`` which is the + nearly optimal approximation of a singular value decomposition of + a centered matrix :math:`A` such that :math:`A \approx U \operatorname{diag}(S) V^{\text{H}}` + + .. note:: The relation of ``(U, S, V)`` to PCA is as follows: + + - :math:`A` is a data matrix with ``m`` samples and + ``n`` features + + - the :math:`V` columns represent the principal directions + + - :math:`S ** 2 / (m - 1)` contains the eigenvalues of + :math:`A^T A / (m - 1)` which is the covariance of + ``A`` when ``center=True`` is provided. + + - ``matmul(A, V[:, :k])`` projects data to the first k + principal components + + .. note:: Different from the standard SVD, the size of returned + matrices depend on the specified rank and q + values as follows: + + - :math:`U` is m x q matrix + + - :math:`S` is q-vector + + - :math:`V` is n x q matrix + + .. note:: To obtain repeatable results, reset the seed for the + pseudorandom number generator + + Args: + + A (Tensor): the input tensor of size :math:`(*, m, n)` + + q (int, optional): a slightly overestimated rank of + :math:`A`. By default, ``q = min(6, m, + n)``. + + center (bool, optional): if True, center the input tensor, + otherwise, assume that the input is + centered. + + niter (int, optional): the number of subspace iterations to + conduct; niter must be a nonnegative + integer, and defaults to 2. + + References:: + + - Nathan Halko, Per-Gunnar Martinsson, and Joel Tropp, Finding + structure with randomness: probabilistic algorithms for + constructing approximate matrix decompositions, + arXiv:0909.4061 [math.NA; math.PR], 2009 (available at + `arXiv `_). + + """ + + if not torch.jit.is_scripting(): + if type(A) is not torch.Tensor and has_torch_function((A,)): + return handle_torch_function( + pca_lowrank, (A,), A, q=q, center=center, niter=niter + ) + + (m, n) = A.shape[-2:] + + if q is None: + q = min(6, m, n) + elif not (q >= 0 and q <= min(m, n)): + raise ValueError( + f"q(={q}) must be non-negative integer and not greater than min(m, n)={min(m, n)}" + ) + if not (niter >= 0): + raise ValueError(f"niter(={niter}) must be non-negative integer") + + dtype = _utils.get_floating_dtype(A) + + if not center: + return _svd_lowrank(A, q, niter=niter, M=None) + + if _utils.is_sparse(A): + if len(A.shape) != 2: + raise ValueError("pca_lowrank input is expected to be 2-dimensional tensor") + c = torch.sparse.sum(A, dim=(-2,)) / m + # reshape c + column_indices = c.indices()[0] + indices = torch.zeros( + 2, + len(column_indices), + dtype=column_indices.dtype, + device=column_indices.device, + ) + indices[0] = column_indices + C_t = torch.sparse_coo_tensor( + indices, c.values(), (n, 1), dtype=dtype, device=A.device + ) + + ones_m1_t = torch.ones(A.shape[:-2] + (1, m), dtype=dtype, device=A.device) + M = torch.sparse.mm(C_t, ones_m1_t).mT + return _svd_lowrank(A, q, niter=niter, M=M) + else: + C = A.mean(dim=(-2,), keepdim=True) + return _svd_lowrank(A - C, q, niter=niter, M=None) diff --git a/.venv/lib/python3.12/site-packages/torch/_meta_registrations.py b/.venv/lib/python3.12/site-packages/torch/_meta_registrations.py new file mode 100644 index 0000000000000000000000000000000000000000..d05b10533384185eea675d4ea9a604ea6284b08b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_meta_registrations.py @@ -0,0 +1,9176 @@ +# mypy: allow-untyped-defs +import math +from collections.abc import Callable, Sequence +from enum import Enum +from functools import wraps +from typing import TypeVar +from typing_extensions import ParamSpec + +import torch +import torch._prims_common as utils +from torch import SymBool, SymFloat, Tensor +from torch._decomp import ( + _add_op_to_registry, + _convert_out_params, + global_decomposition_table, + meta_table, +) +from torch._ops import OpOverload +from torch._prims import _prim_elementwise_meta, ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND +from torch._prims_common import ( + BoolLike, + corresponding_complex_dtype, + corresponding_real_dtype, + elementwise_dtypes, + ELEMENTWISE_TYPE_PROMOTION_KIND, + FloatLike, + IntLike, + make_channels_last_strides_for, + make_contiguous_strides_for, + Number, + NumberType, + suggest_memory_format, + sym_min, + TensorLike, +) +from torch._prims_common.wrappers import ( + _maybe_convert_to_dtype, + _maybe_resize_out, + _resize_output_check, + _safe_copy_out, + out_wrapper, +) +from torch._refs import _broadcast_shapes, _maybe_broadcast +from torch.fx.experimental import _config as exp_config +from torch.utils import _pytree as pytree + + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +aten = torch.ops.aten + +_meta_lib_dont_use_me_use_register_meta = torch.library.Library("aten", "IMPL", "Meta") +MODE_SUM, MODE_MEAN, MODE_MAX = range(3) + + +def ceil_div(a, b): + return (a + b - 1) // b + + +def round_up(x, y): + """Rounds up x to nearest multiple of y""" + return ((x + y - 1) // y) * y + + +def register_meta(op) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + def wrapper(fn): + fn = _convert_out_params(fn) + + def register(op): + _add_op_to_registry(meta_table, op, fn) + + pytree.tree_map_(register, op) + return fn + + return wrapper + + +def elementwise_meta( + *args, + type_promotion: ELEMENTWISE_TYPE_PROMOTION_KIND, +): + # Perform type promotion, as this is expected from prim_metafunction + _, result_dtype = utils.elementwise_dtypes( + *args, + type_promotion_kind=type_promotion, + ) + args = [_maybe_convert_to_dtype(x, result_dtype) for x in args] + + # Broadcast + args = _maybe_broadcast(*args) + + # Perform prim checks + return _prim_elementwise_meta( + *args, type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT + ) + + +def toRealValueType(dtype): + from_complex = { + torch.complex32: torch.half, + torch.cfloat: torch.float, + torch.cdouble: torch.double, + } + return from_complex.get(dtype, dtype) + + +def check_inplace_broadcast(self_shape, *args_shape): + broadcasted_shape = tuple(_broadcast_shapes(self_shape, *args_shape)) + torch._check( + broadcasted_shape == self_shape, + lambda: f"output with shape {self_shape} doesn't match the broadcast shape {broadcasted_shape}", + ) + + +@register_meta([aten.linspace, aten.logspace]) +@out_wrapper() +def meta_linspace_logspace( + start, + end, + steps, + base=None, + dtype=None, + device=None, + layout=torch.strided, + pin_memory=False, + requires_grad=False, +): + if isinstance(start, torch.Tensor): + torch._check( + start.dim() == 0, + lambda: "linspace only supports 0-dimensional start and end tensors", + ) + if isinstance(end, torch.Tensor): + torch._check( + end.dim() == 0, + lambda: "linspace only supports 0-dimensional start and end tensors", + ) + + if any(isinstance(arg, complex) for arg in (start, end, steps)): + default_complex_dtype = utils.corresponding_complex_dtype( + torch.get_default_dtype() + ) + if dtype is None: + dtype = default_complex_dtype + else: + torch._check( + utils.is_complex_dtype(dtype), + lambda: f"linspace(): inferred dtype {default_complex_dtype} can't be safely cast to passed dtype {dtype}", + ) + else: + dtype = dtype or torch.get_default_dtype() + if not isinstance(dtype, torch.dtype): + raise AssertionError(f"dtype must be torch.dtype, got {type(dtype)}") + + # steps does not participate in the computation of the dtype + torch._check_type( + isinstance(steps, IntLike), + lambda: f"received an invalid combination of arguments - got \ +({type(start).__name__}, {type(end).__name__}, {type(steps).__name__})", + ) + if not isinstance(steps, IntLike): + raise AssertionError(f"steps must be IntLike, got {type(steps)}") + torch._check(steps >= 0, lambda: "number of steps must be non-negative") + + return torch.empty( + (steps,), # type: ignore[arg-type] + dtype=dtype, + layout=layout, + device="meta", + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@register_meta([aten.take.default, aten.take.out]) +@out_wrapper() +def meta_take(self, index): + # Type and device checks + torch._check( + index.dtype == torch.long, + lambda: f"take(): Expected a long tensor for index, but got {index.dtype}", + ) + # Index checks + torch._check_index( + not (self.numel() == 0 and index.numel() != 0), + lambda: "take(): tried to take from an empty tensor", + ) + return self.new_empty(index.shape) + + +@register_meta([aten._standard_gamma.default, aten._standard_gamma.out]) +@out_wrapper() +def meta__standard_gamma(self, generator=None): + return torch.empty_like(self) + + +@register_meta( + [ + aten._transformer_encoder_layer_fwd.default, + aten._transformer_encoder_layer_fwd.out, + ] +) +@out_wrapper() +def meta__transformer_encoder_layer_fwd( + src: Tensor, + embed_dim: int, + num_heads: int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + use_gelu: bool, + norm_first: bool, + eps: float, + norm_weight_1: Tensor, + norm_bias_1: Tensor, + norm_weight_2: Tensor, + norm_bias_2: Tensor, + ffn_weight_1: Tensor, + ffn_bias_1: Tensor, + ffn_weight_2: Tensor, + ffn_bias_2: Tensor, + mask: torch.Tensor | None = None, + mask_type: int | None = None, +) -> Tensor: + if src.is_nested: + raise NotImplementedError( + "_transformer_encoder_layer_fwd fake implementation does not support nested tensors" + ) + from torch.fx.experimental.symbolic_shapes import guard_or_false + + # Unbacked-safe: known-empty takes the empty path; if the size is symbolic + # and can't be decided, assume non-empty (the common case) instead of DDE-ing. + if guard_or_false(src.numel() == 0): + return src.clone() + return torch.empty_like(src) + + +@register_meta([aten.linalg_cross.default, aten.linalg_cross.out]) +@out_wrapper() +def linalg_cross(self, other, *, dim=-1): + x_d = self.ndim + y_d = other.ndim + torch._check( + x_d == y_d, + lambda: "linalg.cross: inputs must have the same number of dimensions.", + ) + torch._check( + self.size(dim) == 3 and other.size(dim) == 3, + lambda: ( + f"linalg.cross: inputs dimension {dim} must have length 3. " + f"Got {self.size(dim)} and {other.size(dim)}" + ), + ) + out_shape = _broadcast_shapes(self.shape, other.shape) + return self.new_empty(out_shape) + + +@register_meta(aten.linalg_matrix_exp) +@out_wrapper() +def linalg_matrix_exp(self): + squareCheckInputs(self, "linalg.matrix_exp") + checkFloatingOrComplex(self, "linalg.matrix_exp") + return torch.empty_like(self, memory_format=torch.contiguous_format) + + +@register_meta(aten.linalg_matrix_sqrth) +@out_wrapper() +def linalg_matrix_sqrth(self): + squareCheckInputs(self, "linalg.matrix_sqrth") + checkFloatingOrComplex( + self, "linalg.matrix_sqrth", allow_low_precision_dtypes=False + ) + return torch.empty_like(self, memory_format=torch.contiguous_format) + + +@register_meta( + [aten.cummax.default, aten.cummax.out, aten.cummin.default, aten.cummin.out] +) +@out_wrapper("values", "indices") +def cummaxmin(self, dim): + values = torch.empty(self.shape, device=self.device, dtype=self.dtype) + indices = torch.empty(self.shape, device=self.device, dtype=torch.int64) + if self.numel() != 0 and self.ndim != 0: + # Checks that dim is within bounds + maybe_wrap_dim(dim, self.ndim) + return values, indices + + +@register_meta([aten.logcumsumexp.default, aten.logcumsumexp.out]) +@out_wrapper() +def logcumsumexp(self, dim): + # Checks that dim is within bounds + maybe_wrap_dim(dim, self.ndim) + return torch.empty_like(self, memory_format=torch.contiguous_format) + + +# Stride-related code from _exec_fft in aten/src/ATen/native/mkl/SpectralOps.cpp +# and aten/src/ATen/cuda/SpectralOps.cpp +# +# Although the actual FFT launch is different, all the permuting code appears +# to be the same +def _exec_fft(out, self, out_sizes, dim, *, forward): + ndim = self.ndim + signal_ndim = len(dim) + batch_dims = ndim - signal_ndim + + # Permute dimensions so batch dimensions come first, and in stride order + dim_permute = list(range(ndim)) + + is_transformed_dim = [False for _ in range(ndim)] + for d in dim: + is_transformed_dim[d] = True + + # std::partition + std::copy(dim.begin(), dim.end(), batch_end) + left = [d for d in dim_permute if not is_transformed_dim[d]] + dim_permute = left + list(dim) + batch_end = len(left) + + self_strides = self.stride() + tmp = dim_permute[:batch_end] + tmp.sort(key=lambda x: self_strides[x], reverse=True) + dim_permute = tmp + dim_permute[batch_end:] + input = self.permute(dim_permute) + + # Collapse batch dimensions into a single dimension + batched_sizes = [-1] + list(input.shape[batch_dims:]) + input = input.reshape(batched_sizes) + + batch_size = input.size(0) + batched_sizes[0] = batch_size + batched_out_sizes = list(batched_sizes) + for i in range(len(dim)): + batched_out_sizes[i + 1] = out_sizes[dim[i]] + out.resize_(batched_out_sizes, memory_format=torch.contiguous_format) + + # Inplace reshaping to original batch shape and inverting the dimension permutation + out_strides = [0 for _ in range(ndim)] + batch_numel = 1 + i = batch_dims - 1 + while i >= 0: + out_strides[dim_permute[i]] = batch_numel * out.stride(0) + batch_numel *= out_sizes[dim_permute[i]] + i -= 1 + for i in range(batch_dims, ndim): + out_strides[dim_permute[i]] = out.stride(1 + (i - batch_dims)) + out.as_strided_(out_sizes, out_strides, out.storage_offset()) + + return out + + +def _sort_dims(self: Tensor, dim: list[int], exclude_last: bool = False): + sorted_dims = list(dim) + self_strides = self.stride() + end = len(sorted_dims) - int(exclude_last) + sorted_dims[:end] = sorted( + sorted_dims[:end], key=lambda i: self_strides[i], reverse=True + ) + return sorted_dims + + +# See _fft_c2c_cufft in aten/src/ATen/native/cuda/SpectralOps.cpp +# and _fft_c2c_mkl in aten/src/ATen/native/mkl/SpectralOps.cpp +@register_meta([aten._fft_c2c.default, aten._fft_c2c.out]) +@out_wrapper() +def meta_fft_c2c(self, dim, normalization, forward): + torch._check(self.dtype.is_complex) + if not dim: + return self.clone() + + if device_hint(self) == "cpu" and not torch.backends.mkl.is_available(): + return self.new_empty(self.size()) + + out_sizes = self.size() + output = self.new_empty(out_sizes) + if device_hint(self) != "cuda": + sorted_dims = _sort_dims(self, dim) + return _exec_fft(output, self, out_sizes, sorted_dims, forward=forward) + + # Match _fft_c2c_cufft, which re-sorts the remaining dimensions after each + # staged transform because _exec_fft restrides the output in place. + sorted_dims = list(dim) + working_tensor = self + while True: + strides = working_tensor.stride() + sorted_dims.sort(key=lambda i: strides[i], reverse=True) + max_dims = min(cufft_max_ndim, len(sorted_dims)) + last_dims = sorted_dims[len(sorted_dims) - max_dims :] + + _exec_fft(output, working_tensor, out_sizes, last_dims, forward=forward) + sorted_dims = sorted_dims[: len(sorted_dims) - max_dims] + + if not sorted_dims: + return output + + if working_tensor is self: + working_tensor = output + output = self.new_empty(out_sizes) + else: + output, working_tensor = working_tensor, output + + +cufft_max_ndim = 3 + + +def use_optimized_cufft_path(dim: list[int]): + if len(dim) > cufft_max_ndim or (len(dim) >= 2 and dim[0] == 0 and dim[1] == 1): + return False + else: + return True + + +@register_meta([aten._fft_r2c.default, aten._fft_r2c.out]) +@out_wrapper() +def meta_fft_r2c(self, dim, normalization, onesided): + torch._check(self.dtype.is_floating_point) + input_sizes = list(self.size()) + out_sizes = list(input_sizes) + last_dim = dim[-1] + last_dim_halfsize = input_sizes[last_dim] // 2 + 1 + onesided_sizes = list(input_sizes) + onesided_sizes[last_dim] = last_dim_halfsize + + if onesided: + out_sizes[last_dim] = last_dim_halfsize + + # Determine output dtype based on input dtype and device + # bfloat16 FFT always produces complex64 output (not bcomplex32): + # - On CUDA: cuFFT CUDA_C_16BF is upcast to ComplexFloat (see SpectralOps.cpp line 376-379) + # - On ROCm/XPU: bfloat16 is promoted to float32 before FFT, yielding complex64 + # See promote_type_fft() and _fft_r2c_cufft() in aten/src/ATen/native/SpectralOps.cpp + output_dtype = self.dtype + if output_dtype == torch.bfloat16 and (device_hint(self) in ("cuda", "xpu")): + output_dtype = torch.float32 + + if device_hint(self) == "cuda" or device_hint(self) == "xpu": + # _fft_r2c_cufft in aten/src/ATen/native/cuda/SpectralOps.cpp + # _fft_r2c_xpu in torch-xpu-ops/src/ATen/native/xpu/SpectralOps.cpp + output = self.new_empty( + out_sizes, dtype=utils.corresponding_complex_dtype(output_dtype) + ) + + working_tensor = self + if device_hint(self) == "cuda" and use_optimized_cufft_path(dim): + _exec_fft(output, working_tensor, out_sizes, dim, forward=True) + else: + # First do the R2C transform on the last dimension + target_sizes = out_sizes if len(dim) == 1 else onesided_sizes + _exec_fft(output, working_tensor, target_sizes, [last_dim], forward=True) + if len(dim) > 1: + working_tensor = self.new_empty( + out_sizes, dtype=utils.corresponding_complex_dtype(output_dtype) + ) + + # Then any remaining C2C transforms + sorted_dims = dim[:-1] + while sorted_dims: + output, working_tensor = working_tensor, output + strides = working_tensor.stride() + sorted_dims.sort( + key=lambda i: strides[i], reverse=True + ) # NB reverse! Not sure if this is og bug + max_dims = min(cufft_max_ndim, len(sorted_dims)) + last_dims = sorted_dims[len(sorted_dims) - max_dims :] + _exec_fft( + output, working_tensor, onesided_sizes, last_dims, forward=True + ) + sorted_dims = sorted_dims[: len(sorted_dims) - max_dims] + + if not onesided: + if output.size(last_dim) != out_sizes[last_dim]: + working_tensor.resize_(out_sizes, memory_format=torch.contiguous_format) + output = working_tensor + + return output + + elif torch.backends.mkl.is_available(): + # _fft_r2c_mkl in aten/src/ATen/native/mkl/SpectralOps.cpp + sorted_dims = _sort_dims(self, dim, exclude_last=True) + output = self.new_empty( + out_sizes, dtype=utils.corresponding_complex_dtype(output_dtype) + ) + return _exec_fft(output, self, out_sizes, sorted_dims, forward=True) + + else: + return self.new_empty( + out_sizes, dtype=utils.corresponding_complex_dtype(output_dtype) + ) + + +@register_meta(aten.randperm.generator_out) +def meta_randperm(n, *, generator=None, out): + return _maybe_resize_out(out, torch.Size([n])) + + +@register_meta(aten.randperm.default) +def meta_randperm_default( + n, + *, + dtype=torch.long, + layout=None, + device=None, + pin_memory=None, +): + return torch.empty( + n, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta([aten.randint.default, aten.randint.out]) +@out_wrapper() +def meta_randint( + high, + size, + *, + dtype=torch.long, + layout=None, + device=None, + pin_memory=None, +): + low = 0 + torch._check( + high > low, + lambda: f"random_ expects 'from' to be less than 'to', but got from={low} >= to={high}", + ) + return torch.empty( + size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta([aten.randint.low, aten.randint.low_out]) +@out_wrapper() +def meta_randint_low( + low, + high, + size, + *, + dtype=torch.long, + layout=None, + device=None, + pin_memory=None, +): + torch._check( + high > low, + lambda: f"random_ expects 'from' to be less than 'to', but got from={low} >= to={high}", + ) + return torch.empty( + size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta([aten.rand.default, aten.rand.out]) +@out_wrapper() +def meta_rand_default(size, *, dtype=None, layout=None, device=None, pin_memory=None): + return torch.empty( + size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta(aten._philox_key_split.default) +def meta_philox_key_split(key, num_splits): + torch._check( + key.dim() >= 1 and key.shape[-1] == 2, + lambda: f"_philox_key_split: key must have shape (*batch, 2), got shape {key.shape}", + ) + torch._check( + key.dtype == torch.uint64, + lambda: f"_philox_key_split: key must have dtype uint64, got {key.dtype}", + ) + torch._check( + num_splits > 0, + lambda: f"_philox_key_split: num_splits must be positive, got {num_splits}", + ) + batch_sizes = key.shape[:-1] + return key.new_empty((num_splits, *batch_sizes, 2)) + + +@register_meta(aten._philox_key_fold_in.default) +def meta_philox_key_fold_in(key, data): + torch._check( + key.dim() >= 1 and key.shape[-1] == 2, + lambda: f"_philox_key_fold_in: key must have shape (*batch, 2), got shape {key.shape}", + ) + torch._check( + key.dtype == torch.uint64, + lambda: f"_philox_key_fold_in: key must have dtype uint64, got {key.dtype}", + ) + return torch.empty_like(key) + + +@register_meta(aten._philox_key_fold_in.Tensor) +def meta_philox_key_fold_in_tensor(key, data): + torch._check( + key.dim() >= 1 and key.shape[-1] == 2, + lambda: f"_philox_key_fold_in: key must have shape (*batch, 2), got shape {key.shape}", + ) + torch._check( + key.dtype == torch.uint64, + lambda: f"_philox_key_fold_in: key must have dtype uint64, got {key.dtype}", + ) + torch._check( + data.dtype == torch.uint64, + lambda: f"_philox_key_fold_in: data must have dtype uint64, got {data.dtype}", + ) + torch._check( + data.numel() == 1, + lambda: f"_philox_key_fold_in: data must be a single value, got {data.numel()} elements", + ) + return torch.empty_like(key) + + +def _check_philox_distribution_args(op_name, self, key): + torch._check( + self.dtype.is_floating_point, + lambda: f"{op_name}: self must be a floating point tensor, got {self.dtype}", + ) + torch._check( + key.dtype == torch.uint64, + lambda: f"{op_name}: key must have dtype uint64, got {key.dtype}", + ) + torch._check( + self.device == key.device, + lambda: ( + f"{op_name}: self and key must be on the same device, " + f"got {self.device} and {key.device}" + ), + ) + torch._check( + key.dim() >= 1 and key.shape[-1] == 2, + lambda: ( + f"{op_name}: key must have shape (2,) or (*batch, 2), got shape {key.shape}" + ), + ) + if key.dim() > 1: + torch._check( + key.dim() == self.dim() + 1, + lambda: ( + f"{op_name}: batched key must have ndim == output ndim + 1, " + f"got key shape {key.shape} with output shape {self.shape}" + ), + ) + key_batch = key.shape[: self.dim()] + torch._check( + all(ks == 1 or ks == ss for ks, ss in zip(key_batch, self.shape)), + lambda: ( + f"{op_name}: key batch shape {list(key_batch)} " + f"is not broadcastable with output shape {self.shape}" + ), + ) + + +@register_meta(aten._philox_normal_.default) +def meta_philox_normal_(self, key, mean=0.0, std=1.0): + _check_philox_distribution_args("_philox_normal_", self, key) + return self + + +@register_meta(aten._philox_uniform_.default) +def meta_philox_uniform_(self, key, low=0.0, high=1.0): + _check_philox_distribution_args("_philox_uniform_", self, key) + return self + + +@register_meta([aten._fft_c2r.default, aten._fft_c2r.out]) +@out_wrapper() +def meta_fft_c2r(self: Tensor, dim: list[int], normalization: int, lastdim: int): + # _fft_c2r_mkl + torch._check(self.dtype.is_complex) + + if device_hint(self) == "cuda": + out_sizes = list(self.size()) + out_sizes[dim[-1]] = lastdim + + output = self.new_empty(out_sizes, dtype=toRealValueType(self.dtype)) + + if use_optimized_cufft_path(dim): + return _exec_fft( + output, + self.clone(memory_format=torch.contiguous_format), + out_sizes, + dim, + forward=False, + ) + else: + # First complete any C2C transforms + if len(dim) > 1: + temp = meta_fft_c2c(self, dim[:-1], 0, forward=False) + else: + temp = self.clone(memory_format=torch.contiguous_format) + return _exec_fft(output, temp, out_sizes, [dim[-1]], forward=False) + + elif torch.backends.mkl.is_available(): + # _fft_c2r_mkl in aten/src/ATen/native/mkl/SpectralOps.cpp + input = self + if len(dim) > 1: + c2c_dims = dim[:-1] + input = meta_fft_c2c(self, c2c_dims, normalization, forward=False) + dim = dim[-1:] + + out_sizes = list(input.size()) + out_sizes[dim[-1]] = lastdim + out = self.new_empty(out_sizes, dtype=toRealValueType(self.dtype)) + return _exec_fft(out, input, out_sizes, dim, forward=False) + + else: + out_sizes = list(self.size()) + out_sizes[dim[-1]] = lastdim + return self.new_empty(out_sizes, dtype=toRealValueType(self.dtype)) + + +@register_meta(aten.copy_.default) +def meta_copy_(self, src, non_blocking=False): + # This code simulates the original decomp from inductor, + # which runs most of the meta checks that we care about. + # In theory, we should make this more robust by carefully + # auditing our C++ copy_() kernel and copying the checks here. + from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols + + # TODO: Ideally, we'd insert a deferred runtime assert here, but if we are + # calling an actual copy_, you'll get that automatically + # https://github.com/pytorch/pytorch/issues/122477 + if ( + not free_unbacked_symbols(self) and torch._debug_has_internal_overlap(self) == 1 + ): # 1 == MemOverlap::Yes + raise RuntimeError( + "more than one element of the written-to tensor refers to a single memory location" + ) + + if isinstance(src, Tensor): + intermediate = src.to(self, non_blocking) + # Validate broadcast compatibility. We call the _refs expand + # directly rather than aten.expand_copy.default because the + # aten dispatch path hits C++ that cannot handle unbacked + # symints. The refs version performs the same checks using + # sym_or(x == 1, requested_length == x) which gracefully + # handles unbacked symints. + torch._refs.expand(intermediate, self.size()) + return self + + +def inferUnsqueezeGeometry(tensor, dim): + result_sizes = list(tensor.size()) + result_strides = list(tensor.stride()) + # pyrefly: ignore [unsupported-operation] + new_stride = 1 if dim >= tensor.dim() else result_sizes[dim] * result_strides[dim] + # pyrefly: ignore [bad-argument-type] + result_sizes.insert(dim, 1) + # pyrefly: ignore [bad-argument-type] + result_strides.insert(dim, new_stride) + return result_sizes, result_strides + + +@register_meta(aten.unsqueeze_.default) +def meta_unsqueeze_(self, dim): + dim = maybe_wrap_dim(dim, self.dim() + 1) + g_sizes, g_strides = inferUnsqueezeGeometry(self, dim) + self.as_strided_(g_sizes, g_strides) + return self + + +@register_meta(aten._sparse_semi_structured_linear) +def meta_sparse_structured_linear( + input: Tensor, + weight: Tensor, + _meta: Tensor, + bias: Tensor | None = None, + _activation_opt: str | None = None, + out_dtype: torch.dtype | None = None, +): + output_sizes = list(input.shape) + if bias is not None: + if weight.size(0) != bias.size(0): + raise AssertionError( + f"output size mismatch: weight.size(0)={weight.size(0)} != bias.size(0)={bias.size(0)}" + ) + if weight.size(1) != input.size(-1) / 2: + raise AssertionError( + f"weight.size(1)={weight.size(1)} != input.size(-1)/2={input.size(-1) / 2}" + ) + output_sizes[-1] = weight.size(0) + + # see: https://github.com/pytorch/pytorch/pull/114477#issuecomment-1830121375 + # We assume that we have already squashed the inputs into a 2-D tensor + # Then, as the output is transposed, we need to propagate the transposed + # stride information to the output tensor + if len(input.shape) != 2: + raise AssertionError( + f"we can only handle the squashed input case, got {len(input.shape)}D input" + ) + transposed_strides = (1, input.size(0)) + + if out_dtype is not None: + if not (input.dtype == torch.int8 and out_dtype == torch.int32): + raise AssertionError( + f"out_dtype is only supported for i8i8->i32 linear operator, got input.dtype={input.dtype}, out_dtype={out_dtype}" + ) + output = input.new_empty_strided( + output_sizes, + transposed_strides, + dtype=input.dtype if out_dtype is None else out_dtype, + ) + + return output + + +@register_meta(aten._sparse_semi_structured_mm) +def meta_sparse_structured_mm( + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + out_dtype: torch.dtype | None = None, +): + if len(mat1.shape) != 2: + raise AssertionError(f"mat1 must be 2D, got {len(mat1.shape)}D") + if len(mat1_meta.shape) != 2: + raise AssertionError(f"mat1_meta must be 2D, got {len(mat1_meta.shape)}D") + if len(mat2.shape) != 2: + raise AssertionError(f"mat2 must be 2D, got {len(mat2.shape)}D") + if mat1.size(1) != mat2.size(0) / 2: + raise AssertionError( + f"mat1.size(1)={mat1.size(1)} != mat2.size(0)/2={mat2.size(0) / 2}" + ) + output_sizes = [mat1.size(0), mat2.size(1)] + + if out_dtype is not None: + if not (mat2.dtype == torch.int8 and out_dtype == torch.int32): + raise AssertionError( + f"out_dtype is only supported for i8i8->i32 linear operator, got mat2.dtype={mat2.dtype}, out_dtype={out_dtype}" + ) + output = mat2.new_empty( + output_sizes, + dtype=mat2.dtype if out_dtype is None else out_dtype, + ) + + return output + + +@register_meta(aten._sparse_semi_structured_addmm) +def meta_sparse_structured_addmm( + input: Tensor, + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + *, + alpha=1, + beta=1, + out_dtype: torch.dtype | None = None, +): + if len(input.shape) != 1: + raise AssertionError( + f"only input broadcasted to columns of mat1 * mat2 product is supported, got {len(input.shape)}D input" + ) + if len(mat1.shape) != 2: + raise AssertionError(f"mat1 must be 2D, got {len(mat1.shape)}D") + if len(mat1_meta.shape) != 2: + raise AssertionError(f"mat1_meta must be 2D, got {len(mat1_meta.shape)}D") + if len(mat2.shape) != 2: + raise AssertionError(f"mat2 must be 2D, got {len(mat2.shape)}D") + if input.size(0) != mat1.size(0): + raise AssertionError( + f"only input broadcasted to columns of mat1 * mat2 product is supported, " + f"input.size(0)={input.size(0)} != mat1.size(0)={mat1.size(0)}" + ) + if mat1.size(1) != mat2.size(0) / 2: + raise AssertionError( + f"mat1.size(1)={mat1.size(1)} != mat2.size(0)/2={mat2.size(0) / 2}" + ) + output_sizes = [mat1.size(0), mat2.size(1)] + + if out_dtype is not None: + if not (mat2.dtype == torch.int8 and out_dtype == torch.int32): + raise AssertionError( + f"out_dtype is only supported for i8i8->i32 linear operator, got mat2.dtype={mat2.dtype}, out_dtype={out_dtype}" + ) + output = mat2.new_empty( + output_sizes, + dtype=mat2.dtype if out_dtype is None else out_dtype, + ) + + return output + + +@register_meta(aten._cslt_sparse_mm) +def meta__cslt_sparse_mm( + compressed_A: torch.Tensor, + dense_B: torch.Tensor, + bias: Tensor | None = None, + alpha: Tensor | None = None, + out_dtype: torch.dtype | None = None, + transpose_result: bool = False, + alg_id: int = 0, + split_k: int = 1, + split_k_mode: int = -1, +): + if dense_B.dtype not in { + torch.float32, + torch.float16, + torch.bfloat16, + torch.int8, + torch.float8_e4m3fn, + }: + raise AssertionError( + f"_cslt_sparse_mm only supports fp16, bf16, int8, and fp8e4m3, got {dense_B.dtype}" + ) + if compressed_A.dtype != dense_B.dtype: + raise AssertionError( + f"inputs must have the same dtype, got {compressed_A.dtype} and {dense_B.dtype}" + ) + if len(dense_B.shape) != 2: + raise AssertionError( + f"_cslt_sparse_mm only supports 2d inputs, got {len(dense_B.shape)}D" + ) + + is_8bit_input_type = compressed_A.dtype in [torch.int8, torch.float8_e4m3fn] + + n = dense_B.size(1) + m = compressed_A.size(0) + if bias is not None: + if m != bias.size(0): + raise AssertionError( + f"bias size mismatch: m={m} != bias.size(0)={bias.size(0)}" + ) + + if out_dtype is not None: + if not ( + is_8bit_input_type + and out_dtype + in { + torch.float16, + torch.bfloat16, + torch.float32, + torch.int32, + torch.float8_e4m3fn, + } + ): + raise AssertionError( + f"out_dtype is not supported for {compressed_A.dtype} x {dense_B.dtype} -> {out_dtype} matmul!" + ) + output_shape = (n, m) if transpose_result else (m, n) + return dense_B.new_empty(output_shape, dtype=out_dtype) + + +@register_meta(aten.index_reduce.default) +def meta_index_reduce( + self: Tensor, + dim: int, + index: Tensor, + source: torch.Tensor, + reduce: str, + *, + include_self: bool = True, +) -> Tensor: + return torch.empty_like(self, memory_format=torch.contiguous_format) + + +@register_meta(aten.index_reduce_.default) +def meta_index_reduce_( + self: Tensor, + dim: int, + index: Tensor, + source: torch.Tensor, + reduce: str, + *, + include_self: bool = True, +) -> Tensor: + return self + + +# Implementations below are taken from https://github.com/albanD/subclass_zoo/blob/main/python_meta_tensor.py +@out_wrapper() +@register_meta(aten.index_select.default) +def meta_index_select(self, dim, index): + result_size = list(self.size()) + if self.dim() > 0: + result_size[dim] = index.numel() + return self.new_empty(result_size) + + +@register_meta(aten.segment_reduce.default) +def meta_segment_reduce( + data: Tensor, + reduce: str, + *, + lengths: Tensor | None = None, + indices: Tensor | None = None, + offsets: Tensor | None = None, + axis: int = 0, + unsafe: bool = False, + initial=None, +) -> Tensor: + if indices is not None: + raise NotImplementedError( + "segment_reduce(): indices based reduction is not supported yet." + ) + + def segment_reduce_output(segment_count): + output_shape = list(data.shape) + output_shape[axis] = segment_count + return torch.empty( + output_shape, + dtype=data.dtype, + device="meta", + memory_format=torch.contiguous_format, + ) + + if lengths is not None: + return segment_reduce_output(lengths.shape[axis]) + # FIXME should probably check that lengths and offset aren't both set, but + # the ATen implementation neglects this too + if offsets is not None: + return segment_reduce_output(offsets.shape[axis] - 1) + raise RuntimeError("segment_reduce(): Either lengths or offsets must be defined.") + + +@register_meta([aten.max.default, aten.max.unary_out]) +@out_wrapper() +def meta_max(self): + return self.new_empty(()) + + +@register_meta(aten.max.dim) +def meta_max_dim(self, dim, keepdim=False): + dim = utils.reduction_dims(self.shape, (dim,)) + output_shape = _compute_reduction_shape(self, dim, keepdim) + return ( + self.new_empty(output_shape), + self.new_empty(output_shape, dtype=torch.long), + ) + + +@register_meta([aten.min.default, aten.min.unary_out]) +@out_wrapper() +def meta_min(self): + return self.new_empty(()) + + +@register_meta(aten.min.dim) +def meta_min_dim(self, dim, keepdim=False): + dim = utils.reduction_dims(self.shape, (dim,)) + output_shape = _compute_reduction_shape(self, dim, keepdim) + return ( + self.new_empty(output_shape), + self.new_empty(output_shape, dtype=torch.long), + ) + + +@register_meta(aten.angle.default) +def meta_angle(self): + if self.is_complex(): + result_dtype = corresponding_real_dtype(self.dtype) + else: + _, result_dtype = elementwise_dtypes( + self, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + return torch.empty_like(self, dtype=result_dtype) + + +@register_meta(aten.angle.out) +def meta_angle_out(self, out): + torch._resize_output_(out, self.size(), self.device) + return out.copy_(torch.angle(self)) + + +@register_meta(aten._assert_async.default) +def assert_async(val): + return + + +@register_meta(aten._assert_async.msg) +def assert_async_meta(val, assert_msg): + return + + +@register_meta(aten._print.default) +def print_meta(s): + return + + +@register_meta(aten._make_dep_token.default) +def make_dep_token( + *, + dtype=None, + layout=None, + device=None, + pin_memory=None, + memory_format=None, +): + return torch.empty((), device="meta") + + +@register_meta(aten.sym_constrain_range.default) +def sym_constrain_range(size, min=None, max=None): + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import constrain_range + + if isinstance(size, (SymFloat, SymBool)): + raise ValueError("Constraining SymFloat or Symbool is nyi") + constrain_range(size, min=min, max=max) + + +@register_meta(aten._functional_sym_constrain_range.default) +def functional_sym_constrain_range(size, min=None, max=None, dep_token=None): + aten.sym_constrain_range(size, min=min, max=max) + return dep_token + + +@register_meta(aten.sym_constrain_range_for_size.default) +def sym_constrain_range_for_size(size, min=None, max=None): + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size + + if min is None and max is None: + torch._check(size >= 0) + return + + if isinstance(size, (SymFloat, SymBool)): + raise ValueError("Constraining SymFloat or Symbool is nyi") + if type(size) is int: + if min is not None: + torch._check(size >= min) + if max is not None: + torch._check(size <= max) + return + _constrain_range_for_size(size, min=min, max=max) + + +@register_meta(aten._functional_sym_constrain_range_for_size.default) +def functional_sym_constrain_range_for_size(size, min, max, dep_token): + aten.sym_constrain_range_for_size(size, min=min, max=max) + return dep_token + + +@register_meta(aten._functional_assert_async.msg) +def functional_assert_async_meta(val, assert_msg, dep_token): + return dep_token + + +# From aten/src/ATen/native/LinearAlgebraUtils.h +def squareCheckInputs(self: Tensor, f_name: str): + if self.dim() < 2: + raise AssertionError( + f"{f_name}: The input tensor must have at least 2 dimensions, got {self.dim()}" + ) + # Use torch._check to defer validation to runtime for unbacked symbolic dimensions. + torch._check( + self.size(-1) == self.size(-2), + lambda: f"{f_name}: A must be batches of square matrices, " + f"but they are {self.size(-2)} by {self.size(-1)} matrices", + ) + + +# Validates input shapes and devices +# for linear solve methods (solve, cholesky_solve, lu_solve, triangular_solve) +# From aten/src/ATen/native/LinearAlgebraUtils.h +def linearSolveCheckInputs(self: Tensor, A: Tensor, name: str): + torch._check( + self.device == A.device, + lambda: ( + f"Expected b and A to be on the same device, but found b on " + f"{self.device} and A on {A.device} instead." + ), + ) + + torch._check( + self.dtype == A.dtype, + lambda: ( + f"Expected b and A to have the same dtype, but found b of type " + f"{self.dtype} and A of type {A.dtype} instead." + ), + ) + + torch._check( + A.size(-1) == A.size(-2), + lambda: ( + f"A must be batches of square matrices, " + f"but they are {A.size(-2)} by {A.size(-1)} matrices" + ), + ) + + torch._check( + A.size(-1) == self.size(-2), + lambda: ( + f"Incompatible matrix sizes for {name}: each A " + f"matrix is {A.size(-1)} by {A.size(-1)}" + f" but each b matrix is {self.size(-2)} by {self.size(-1)}" + ), + ) + + +# From aten/src/ATen/native/LinearAlgebraUtils.h +def checkFloatingOrComplex( + t: Tensor, + f_name: str, + allow_low_precision_dtypes: bool = True, +): + dtype = t.dtype + torch._check( + t.is_floating_point() or t.is_complex(), + lambda: f"{f_name}: Expected a floating point or complex tensor as input. Got {dtype}", + ) + if not allow_low_precision_dtypes: + torch._check( + dtype in (torch.float, torch.double, torch.cfloat, torch.cdouble), + lambda: f"{f_name}: Low precision dtypes not supported. Got {dtype}", + ) + + +# From aten/src/ATen/native/LinearAlgebraUtils.h +def checkIsMatrix(A: Tensor, f_name: str, arg_name: str = "A"): + torch._check( + A.dim() >= 2, + lambda: f"{f_name}: The input tensor {arg_name} must have at least 2 dimensions.", + ) + + +def checkInputsSolver(A: Tensor, B: Tensor, left: bool, f_name: str): + squareCheckInputs(A, f_name) + checkIsMatrix(B, f_name) + torch._check( + A.size(-2) == B.size(-2) if left else A.size(-1) == B.size(-1), + lambda: ( + f"{f_name}: Incompatible shapes of A and B for the equation " + f"{'AX = B' if left else 'XA = B'}" + f" ({A.size(-2)}x{A.size(-1)} and {B.size(-2)}x{B.size(-1)})" + ), + ) + + +def checkSameDevice( + fn_name: str, + result: Tensor, + input: Tensor, + result_name: str = "result", +): + torch._check( + result.device == input.device, + lambda: ( + f"{fn_name}: Expected {result_name} and input tensors to be on the same device, but got " + f"{result_name} on {result.device} and input on {input.device}" + ), + ) + + +def checkUplo(UPLO: str): + UPLO_uppercase = UPLO.upper() + torch._check( + len(UPLO) == 1 and (UPLO_uppercase == "U" or UPLO_uppercase == "L"), + lambda: f"Expected UPLO argument to be 'L' or 'U', but got {UPLO}", + ) + + +@register_meta([aten._linalg_eigh.default, aten._linalg_eigh.eigenvalues]) +@out_wrapper("eigenvalues", "eigenvectors") +def meta__linalg_eigh(A: Tensor, UPLO: str = "L", compute_v: bool = True): + squareCheckInputs(A, "linalg.eigh") + checkUplo(UPLO) + + shape = list(A.shape) + if compute_v: + vecs = A.new_empty(shape) + vecs.as_strided_(shape, make_contiguous_strides_for(shape, row_major=False)) + else: + vecs = A.new_empty([0]) + + shape.pop() + vals = A.new_empty(shape, dtype=toRealValueType(A.dtype)) + + return vals, vecs + + +@register_meta([aten._linalg_eigvals.default, aten.linalg_eigvals.out]) +@out_wrapper() +def meta__linalg_eigvals(input: Tensor) -> Tensor: + squareCheckInputs(input, "linalg.eigvals") + complex_dtype = ( + input.dtype + if utils.is_complex_dtype(input.dtype) + else utils.corresponding_complex_dtype(input.dtype) + ) + return input.new_empty(input.shape[:-1], dtype=complex_dtype) + + +@register_meta([aten.linalg_eig]) +@out_wrapper("eigenvalues", "eigenvectors") +def meta_linalg_eig(input: Tensor): + squareCheckInputs(input, "linalg.eig") + complex_dtype = ( + input.dtype + if utils.is_complex_dtype(input.dtype) + else utils.corresponding_complex_dtype(input.dtype) + ) + values = input.new_empty(input.shape[:-1], dtype=complex_dtype) + vectors = input.new_empty(input.shape, dtype=complex_dtype) + # On CPU, linalg_eig_out_info produces column-major (Fortran) layout via + # resize_ + transpose_(-2, -1). On CUDA, vectors_tmp_needed is always true + # so the result goes through resize_output, yielding row-major (C) layout. + is_cuda = device_hint(input) == "cuda" + vectors.as_strided_( + input.shape, make_contiguous_strides_for(input.shape, row_major=is_cuda) + ) + return values, vectors + + +def cloneBatchedColumnMajor(src: Tensor) -> Tensor: + return src.mT.clone(memory_format=torch.contiguous_format).transpose(-2, -1) + + +@register_meta(aten._cholesky_solve_helper) +@out_wrapper() +def _cholesky_solve_helper(self: Tensor, A: Tensor, upper: bool) -> Tensor: + return cloneBatchedColumnMajor(self) + + +@register_meta(aten.cholesky_solve) +@out_wrapper() +def cholesky_solve(self: Tensor, A: Tensor, upper: bool = False) -> Tensor: + torch._check( + self.ndim >= 2, + lambda: f"b should have at least 2 dimensions, but has {self.ndim} dimensions instead", + ) + torch._check( + A.ndim >= 2, + lambda: f"u should have at least 2 dimensions, but has {A.ndim} dimensions instead", + ) + self_broadcasted, A_broadcasted = _linalg_broadcast_batch_dims_name( + self, A, "cholesky_solve" + ) + return _cholesky_solve_helper(self_broadcasted, A_broadcasted, upper) + + +@register_meta(aten.cholesky_inverse) +@out_wrapper() +def cholesky_inverse(self: Tensor, upper: bool = False) -> Tensor: + squareCheckInputs(self, "cholesky_inverse") + return cloneBatchedColumnMajor(self) + + +# From aten/src/ATen/native/BatchLinearAlgebra.cpp +@register_meta(aten.linalg_cholesky_ex.default) +def linalg_cholesky_ex(A: Tensor, upper: bool = False, check_errors: bool = False): + squareCheckInputs(A, "linalg.cholesky") + checkFloatingOrComplex(A, "linalg.cholesky") + + A_shape = A.shape + ndim = len(A_shape) + + # L + L_strides = make_contiguous_strides_for(A_shape, False) + L = A.new_empty(A_shape) + L.as_strided_(A_shape, L_strides) + + # infos + infos = A.new_empty(A_shape[0 : ndim - 2], dtype=torch.int32) + return L, infos + + +@register_meta( + [aten.linalg_householder_product.default, aten.linalg_householder_product.out] +) +@out_wrapper() +def linalg_householder_product(input: Tensor, tau: Tensor) -> Tensor: + torch._check( + input.ndim >= 2, + lambda: "torch.linalg.householder_product: input must have at least 2 dimensions.", + ) + torch._check( + input.size(-2) >= input.size(-1), + lambda: "torch.linalg.householder_product: input.shape[-2] must be greater than or equal to input.shape[-1]", + ) + torch._check( + input.size(-1) >= tau.size(-1), + lambda: "torch.linalg.householder_product: input.shape[-1] must be greater than or equal to tau.shape[-1]", + ) + + torch._check( + input.ndim - tau.ndim == 1, + lambda: ( + f"torch.linalg.householder_product: Expected tau to have one dimension less than input, " + f"but got tau.ndim equal to {tau.ndim} and input.ndim is equal to {input.ndim}" + ), + ) + if input.ndim > 2: + expected_batch_tau_shape = input.shape[:-2] + actual_batch_tau_shape = tau.shape[:-1] + torch._check( + actual_batch_tau_shape == expected_batch_tau_shape, + lambda: ( + f"torch.linalg.householder_product: Expected batch dimensions of tau to be " + f"equal to input.shape[:-2], but got {actual_batch_tau_shape}" + ), + ) + + torch._check( + tau.dtype == input.dtype, + lambda: ( + f"torch.linalg.householder_product: tau dtype {tau.dtype}" + f" does not match input dtype {input.dtype}" + ), + ) + checkSameDevice("torch.linalg.householder_product", tau, input, "tau") + + return torch.empty_strided( + size=input.shape, + stride=make_contiguous_strides_for(input.shape, row_major=False), + dtype=input.dtype, + device=input.device, + ) + + +# From aten/src/ATen/native/BatchLinearAlgebra.cpp +@register_meta(aten.linalg_inv_ex.default) +def linalg_inv_ex_meta(A: Tensor, check_errors: bool = False): + squareCheckInputs(A, "linalg.inv_ex") + checkFloatingOrComplex(A, "linalg.inv_ex", allow_low_precision_dtypes=False) + + L = A.new_empty(A.shape) + L.as_strided_(A.shape, make_contiguous_strides_for(A.shape, row_major=False)) + + infos = A.new_empty(A.shape[:-2], dtype=torch.int32) + return L, infos + + +@register_meta([aten.linalg_ldl_factor_ex.default, aten.linalg_ldl_factor_ex.out]) +@out_wrapper("LD", "pivots", "info") +def linalg_ldl_factor_ex_meta( + self: Tensor, + *, + hermitian: bool = False, + check_errors: bool = False, +) -> tuple[Tensor, Tensor, Tensor]: + squareCheckInputs(self, "torch.linalg.ldl_factor_ex") + checkFloatingOrComplex(self, "torch.linalg.ldl_factor_ex") + LD = torch.empty_strided( + size=self.shape, + stride=make_contiguous_strides_for(self.shape, row_major=False), + dtype=self.dtype, + device=self.device, + ) + pivots = self.new_empty(self.shape[:-1], dtype=torch.int) + info = self.new_empty(self.shape[:-2], dtype=torch.int) + return LD, pivots, info + + +@register_meta([aten.linalg_ldl_solve.default, aten.linalg_ldl_solve.out]) +@out_wrapper() +def linalg_ldl_solve_meta( + LD: Tensor, + pivots: Tensor, + B: Tensor, + *, + hermitian: bool = False, +) -> Tensor: + squareCheckInputs(LD, "torch.linalg.ldl_solve") + checkFloatingOrComplex(LD, "torch.linalg.ldl_solve") + linearSolveCheckInputs(B, LD, "torch.linalg.ldl_solve") + torch._check( + B.ndim >= 2, + lambda: ( + f"torch.linalg.ldl_solve: Expected B to have at least 2 dimensions, " + f"but it has {B.ndim} dimensions instead" + ), + ) + expected_pivots_shape = LD.shape[:-1] + torch._check( + expected_pivots_shape == pivots.shape, + lambda: ( + f"torch.linalg.ldl_solve: Expected LD.shape[:-1] and pivots.shape to be the same, " + f"but got pivots with shape {pivots.shape} instead" + ), + ) + torch._check( + utils.is_integer_dtype(pivots.dtype), + lambda: f"torch.linalg.ldl_solve: Expected pivots to be integers. Got {pivots.dtype}", + ) + torch._check( + LD.dtype == B.dtype, + lambda: f"torch.linalg.ldl_solve: LD dtype {LD.dtype} does not match b dtype {B.dtype}", + ) + B_broadcast_size, _ = _linalg_broadcast_batch_dims(B, LD) + return torch.empty_strided( + size=B_broadcast_size, + stride=make_contiguous_strides_for(B_broadcast_size, row_major=False), + dtype=B.dtype, + device=B.device, + ) + + +@register_meta([aten.linalg_lu.default, aten.linalg_lu.out]) +@out_wrapper("P", "L", "U") +def linalg_lu_meta(A: Tensor, *, pivot: bool = True) -> tuple[Tensor, Tensor, Tensor]: + torch._check( + A.ndim >= 2, + lambda: f"linalg.lu: Expected tensor with 2 or more dimensions. Got size: {A.shape} instead", + ) + + sizes = list(A.shape) + m = sizes[-2] + n = sizes[-1] + # Use sym_min to handle unbacked symbolic dimensions + k = sym_min(m, n) + + sizes[-1] = m + if pivot: + P = A.new_empty(sizes) + else: + P = A.new_empty([0]) + + sizes[-1] = k # type: ignore[call-overload] + L = A.new_empty(sizes) + + sizes[-2] = k # type: ignore[call-overload] + sizes[-1] = n + U = A.new_empty(sizes) + return P, L, U + + +@register_meta([aten.linalg_lu_factor_ex.default, aten.linalg_lu_factor_ex.out]) +@out_wrapper("LU", "pivots", "info") +def linalg_lu_factor_ex_meta( + A: Tensor, + *, + pivot: bool = True, + check_errors: bool = False, +) -> tuple[Tensor, Tensor, Tensor]: + torch._check( + A.ndim >= 2, + lambda: f"torch.lu_factor: Expected tensor with 2 or more dimensions. Got size: {A.shape} instead", + ) + + sizes = list(A.shape) + m = sizes[-2] + n = sizes[-1] + + LU = torch.empty_strided( + size=sizes, + stride=make_contiguous_strides_for(sizes, row_major=False), + dtype=A.dtype, + device=A.device, + ) + + # Sets sizes to the size of pivots + sizes.pop() + # Use sym_min to handle unbacked symbolic dimensions + sizes[-1] = sym_min(m, n) # type: ignore[call-overload] + pivots = A.new_empty(sizes, dtype=torch.int) + + # Sets sizes to the size of info + sizes.pop() + info = A.new_empty(sizes, dtype=torch.int) + + return LU, pivots, info + + +@register_meta([aten.linalg_lu_solve.default, aten.linalg_lu_solve.out]) +@out_wrapper() +def linalg_lu_solve_meta( + LU: Tensor, + pivots: Tensor, + B: Tensor, + *, + left: bool = True, + adjoint: bool = False, +) -> Tensor: + # dtype + checkFloatingOrComplex(LU, "torch.linalg.lu_solve") + torch._check( + LU.dtype == B.dtype, + lambda: ( + f"linalg.lu_solve: Expected LU and B to have the same dtype, " + f"but found LU of type {LU.dtype} and B of type {B.dtype} instead" + ), + ) + torch._check( + pivots.dtype == torch.int, + lambda: "linalg.lu_solve: pivots should be a Tensor of scalar type torch.int32", + ) + + # matrix shapes + squareCheckInputs(LU, "torch.linalg.lu_solve") + checkInputsSolver(LU, B, left, "linalg.lu_solve") + torch._check( + LU.size(-1) == pivots.size(-1), + lambda: "linalg.lu_solve: Number of pivots per batch should be same as the dimension of the matrix", + ) + + # batches + torch._check( + LU.shape[:-1] == pivots.shape, + lambda: ( + f"linalg.lu_solve: Expected LU.shape[:-1] and pivots.shape to be the same, " + f"but got pivots with shape {pivots.shape} instead" + ), + ) + + B_broadcast_size, _ = _linalg_broadcast_batch_dims(B, LU) + + result = torch.empty_strided( + size=B_broadcast_size, + stride=make_contiguous_strides_for(B_broadcast_size, row_major=not left), + dtype=B.dtype, + device=B.device, + ) + + if result.numel() != 0 and not left: + if result.is_complex(): + result = result.conj() + + return result + + +@register_meta(aten.lu_unpack) +@out_wrapper("P", "L", "U") +def lu_unpack_meta( + LU: Tensor, + pivots: Tensor, + unpack_data: bool = True, + unpack_pivots: bool = True, +) -> tuple[Tensor, Tensor, Tensor]: + torch._check( + LU.ndim >= 2, + lambda: f"torch.lu_unpack: Expected tensor with 2 or more dimensions. Got size: {LU.shape} instead", + ) + if unpack_pivots: + torch._check( + pivots.dtype == torch.int32, + lambda: ( + "torch.lu_unpack: LU_pivots is expected to be a contiguous tensor of torch.int32 dtype.\n" + "Note: this function is intended to be used with the output produced by torch.linalg.lu_factor" + ), + ) + sizes = list(LU.shape) + m = sizes[-2] + n = sizes[-1] + k = sym_min(m, n) + sizes[-1] = m + if unpack_pivots: + P = LU.new_empty(sizes) + else: + P = LU.new_empty([0]) + if unpack_data: + sizes[-1] = k # type: ignore[call-overload] + L = LU.new_empty(sizes) + sizes[-2] = k # type: ignore[call-overload] + sizes[-1] = n + U = LU.new_empty(sizes) + else: + L = LU.new_empty([0]) + U = LU.new_empty([0]) + return P, L, U + + +# parse the "mode" param in linalg_qr: return a tuple of bools (compute_q, reduced) +def _parse_qr_mode(mode: str) -> tuple[bool, bool]: + if mode == "reduced": + compute_q = True + reduced = True + elif mode == "complete": + compute_q = True + reduced = False + elif mode == "r": + compute_q = False + reduced = True # this is actually irrelevant in this mode + else: + torch._check( + False, + lambda: ( + f"qr received unrecognized mode '{mode}' " + f"but expected one of 'reduced' (default), 'r', or 'complete'" + ), + ) + return compute_q, reduced # type: ignore[possibly-undefined] + + +@register_meta([aten.linalg_qr.default, aten.linalg_qr.out]) +@out_wrapper("Q", "R") +def linalg_qr_meta(A: Tensor, mode: str = "reduced") -> tuple[Tensor, Tensor]: + checkIsMatrix(A, "linalg.qr") + checkFloatingOrComplex(A, "linalg.qr") + + compute_q, reduced_mode = _parse_qr_mode(mode) + + m = A.shape[-2] + n = A.shape[-1] + k = sym_min(m, n) + + if compute_q: + Q_shape = list(A.shape) + Q_shape[-1] = k if reduced_mode else m # type: ignore[call-overload] + Q = A.new_empty(Q_shape) + Q.as_strided_(Q_shape, make_contiguous_strides_for(Q_shape, row_major=False)) + else: + Q = A.new_empty([0]) + + # For readability + R_shape = list(A.shape) + R_shape[-2] = k if reduced_mode or not compute_q else m # type: ignore[call-overload] + R = A.new_empty(R_shape) + R.as_strided_(R_shape, make_contiguous_strides_for(R_shape, row_major=False)) + return Q, R + + +@register_meta([aten.linalg_polar.default, aten.linalg_polar.out]) +@out_wrapper("U", "H") +def linalg_polar_meta(A: Tensor) -> tuple[Tensor, Tensor]: + checkIsMatrix(A, "linalg.polar") + checkFloatingOrComplex(A, "linalg.polar") + + m = A.shape[-2] + n = A.shape[-1] + # Symbolic-safe comparison so a dynamic row dimension is not specialized. + torch._check( + m >= n, + lambda: f"linalg.polar: input must have at least as many rows as " + f"columns, but got {m} by {n} matrices", + ) + + # U matches A's shape; H is (n, n). Both row-major contiguous, matching the + # SVD-based C++ kernel and the CUDA override. + U_shape = list(A.shape) + U = A.new_empty(U_shape) + U.as_strided_(U_shape, make_contiguous_strides_for(U_shape)) + + H_shape = list(A.shape) + H_shape[-2] = n + H = A.new_empty(H_shape) + H.as_strided_(H_shape, make_contiguous_strides_for(H_shape)) + return U, H + + +@register_meta([aten._linalg_slogdet.default, aten._linalg_slogdet.sign]) +@out_wrapper("sign", "logabsdet", "LU", "pivots") +def _linalg_slogdet(A: Tensor) -> tuple[Tensor, Tensor, Tensor, Tensor]: + squareCheckInputs(A, "linalg.slogdet") + checkFloatingOrComplex(A, "linalg.slogdet", False) + shape = A.shape + sign = A.new_empty(shape[:-2]) + logabsdet = A.new_empty(shape[:-2], dtype=toRealValueType(A.dtype)) + LU = torch.empty_strided( + size=shape, + stride=make_contiguous_strides_for(shape, False), + dtype=A.dtype, + device=A.device, + ) + pivots = A.new_empty(shape[:-1], dtype=torch.int32) + return sign, logabsdet, LU, pivots + + +# From aten/src/ATen/native/BatchLinearAlgebra.cpp +# NOTE: matching defaults in aten/src/ATen/native/native_functions.yaml +@register_meta(aten._linalg_svd.default) +def _linalg_svd_meta( + A: Tensor, + full_matrices: bool = False, + compute_uv: bool = True, + driver: str | None = None, +): + checkIsMatrix(A, "linalg.svd") + checkFloatingOrComplex(A, "linalg.svd") + + batch_dims = list(A.shape[:-2]) + m = A.shape[-2] + n = A.shape[-1] + k = torch.sym_min(m, n) + + if compute_uv: + U_shape = batch_dims + [m, m if full_matrices else k] + U = A.new_empty(U_shape) + U.as_strided_(U_shape, make_contiguous_strides_for(U_shape, row_major=False)) # type: ignore[arg-type] + + V_shape = batch_dims + [n if full_matrices else k, n] + V = A.new_empty(V_shape) + # NB: This checks for CUDA since there is no way to check for cuSolver. + # Also, this might not work correctly on CPU when fake_device is not + # available as device_hint just defaults to CUDA in that case. See + # _linalg_svd meta in core. + is_cuda = device_hint(A) == "cuda" + V.as_strided_(V_shape, make_contiguous_strides_for(V_shape, row_major=is_cuda)) # type: ignore[arg-type] + else: + # doesn't matter + U = A.new_empty([0]) + V = A.new_empty([0]) + + # S is always real, even when A is complex. + S = A.new_empty(batch_dims + [k], dtype=toRealValueType(A.dtype)) + return U, S, V + + +def _linalg_broadcast_batch_dims( + arg1: Tensor, + arg2: Tensor, +) -> tuple[list[int], list[int]]: + # broadcast the batch dimensions of arg1 and arg2. + arg1_batch_sizes = arg1.shape[:-2] + arg2_batch_sizes = arg2.shape[:-2] + expand_batch_portion = _broadcast_shapes(arg1_batch_sizes, arg2_batch_sizes) + + arg1_expand_size = list(expand_batch_portion) + arg1_expand_size += [arg1.size(-2), arg1.size(-1)] + + arg2_expand_size = list(expand_batch_portion) + arg2_expand_size += [arg2.size(-2), arg2.size(-1)] + return arg1_expand_size, arg2_expand_size + + +def _linalg_broadcast_batch_dims_name( + arg1: Tensor, + arg2: Tensor, + name: str | None, +) -> tuple[Tensor, Tensor]: + # If there's no name we assume we don't want to check the errors + if name: + linearSolveCheckInputs(arg1, arg2, name) + + arg1_expand_size, arg2_expand_size = _linalg_broadcast_batch_dims(arg1, arg2) + + arg1_broadcasted = ( + arg1 if arg1_expand_size == arg1.shape else arg1.expand(arg1_expand_size) + ) + arg2_broadcasted = ( + arg2 if arg2_expand_size == arg2.shape else arg2.expand(arg2_expand_size) + ) + return arg1_broadcasted, arg2_broadcasted + + +def linalg_solve_is_vector_rhs(input: Tensor, other: Tensor) -> bool: + expected_batched_rhs_shape = input.shape[:-1] + vector_case = other.ndim == 1 or ( + input.ndim - 1 == other.ndim and other.shape == expected_batched_rhs_shape + ) + return vector_case + + +@register_meta(aten._linalg_solve_ex) +def _linalg_solve_ex( + A: Tensor, + B: Tensor, + *, + left: bool = True, + check_errors: bool = False, + result: Tensor | None = None, + LU: Tensor | None = None, + pivots: Tensor | None = None, + info: Tensor | None = None, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: + checkFloatingOrComplex(A, "linalg.solve") + torch._check( + A.dtype == B.dtype, + lambda: ( + f"linalg.solve: Expected A and B to have the same dtype, but found A of type " + f"{A.dtype} and B of type {B.dtype} instead" + ), + ) + vector_case = linalg_solve_is_vector_rhs(A, B) + B_ = B.unsqueeze(-1) if vector_case else B + checkInputsSolver(A, B_, left, "linalg.solve") + B_broad_shape, _ = _linalg_broadcast_batch_dims(B_, A) + torch._check( + left or not vector_case, + lambda: ( + "linalg.solve: Vector broadcasting of the left hand side is not supported for left=False. " + "In this case linalg.solve is equivalent to B / A.squeeze(-1)" + ), + ) + result_shape = B_broad_shape[:-1] if vector_case else B_broad_shape + result_ = torch.empty_strided( + size=result_shape, + stride=make_contiguous_strides_for(result_shape, not left), + dtype=B.dtype, + device=B.device, + ) + shape = A.shape + LU_ = torch.empty_strided( + size=shape, + stride=make_contiguous_strides_for(shape, False), + dtype=A.dtype, + device=A.device, + ) + pivots_ = A.new_empty(shape[:-1], dtype=torch.int32) + info_ = A.new_empty(shape[:-2], dtype=torch.int32) + out = (result, LU, pivots, info) + res = (result_, LU_, pivots_, info_) + if all(x is not None for x in out): + for r, o in zip(res, out): + # resize and copy operations are done in-place + _maybe_resize_out(o, r.shape) # type: ignore[arg-type] + # strides are not copied in out_wrapper + o.as_strided_(r.shape, r.stride()) # type: ignore[union-attr] + _safe_copy_out(copy_from=r, copy_to=o, exact_dtype=False) # type: ignore[arg-type] + return res + + +@register_meta([aten.linalg_solve_triangular.default, aten.linalg_solve_triangular.out]) +def linalg_solve_triangular_meta( + A: Tensor, + B: Tensor, + *, + upper: bool, + left: bool = True, + unitriangular: bool = False, + out: Tensor | None = None, +) -> Tensor: + if out is None: + out = A.new_empty([0]) + if not isinstance(out, TensorLike): + raise AssertionError(f"out must be TensorLike, got {type(out)}") + checkInputsSolver(A, B, left, "linalg.solve_triangular") + B_, A_ = _linalg_broadcast_batch_dims_name(B, A, None) + avoid_copy_A = A_.transpose(-2, -1).is_contiguous() and A_.is_conj() + if avoid_copy_A: + out = _maybe_resize_out(out, B_.shape) + else: + # reimplementation of resize_output with result F-contig + if _resize_output_check(out, B_.shape): + out.resize_(B_.transpose(-2, -1).shape) + out.transpose_(-2, -1) + return out # type: ignore[return-value] + + +@register_meta(aten.triangular_solve) +@out_wrapper("X", "M", exact_dtype=True) +def triangular_solve_meta( + self: Tensor, + A: Tensor, + upper: bool = True, + transpose: bool = False, + unitriangular: bool = False, +) -> tuple[Tensor, Tensor]: + torch._check( + self.ndim >= 2, + lambda: ( + f"torch.triangular_solve: Expected b to have at least 2 dimensions, " + f"but it has {self.ndim} dimensions instead" + ), + ) + torch._check( + A.ndim >= 2, + lambda: ( + f"torch.triangular_solve: Expected A to have at least 2 dimensions, " + f"but it has {A.ndim} dimensions instead" + ), + ) + + linearSolveCheckInputs(self, A, "triangular_solve") + + if A.layout == torch.strided: + self_broadcast_size, A_broadcast_size = _linalg_broadcast_batch_dims(self, A) + solution = torch.empty_strided( + size=self_broadcast_size, + stride=make_contiguous_strides_for(self_broadcast_size, row_major=False), + dtype=self.dtype, + device=self.device, + ) + cloned_coefficient = torch.empty_strided( + size=A_broadcast_size, + stride=make_contiguous_strides_for(A_broadcast_size, row_major=False), + dtype=A.dtype, + device=A.device, + ) + elif A.layout == torch.sparse_csr or A.layout == torch.sparse_bsr: + solution = torch.empty_like(self) + cloned_coefficient = self.new_empty([0]) + else: + torch._check(False, lambda: "triangular_solve: Got an unexpected layout.") + return solution, cloned_coefficient # type: ignore[possibly-undefined] + + +# From aten/src/ATen/native/LinearAlgebra.cpp +@register_meta(aten._linalg_det.default) +def _linalg_det_meta(A): + squareCheckInputs(A, "linalg.det") + checkFloatingOrComplex(A, "linalg.det") + + det = A.new_empty(A.shape[:-2]) + + LU = A.new_empty(A.shape) + LU.as_strided_(A.shape, make_contiguous_strides_for(A.shape, row_major=False)) + + pivots = A.new_empty(A.shape[:-1], dtype=torch.int32) + return det, LU, pivots + + +@register_meta(aten.ormqr) +@out_wrapper() +def ormqr( + input: Tensor, + tau: Tensor, + other: Tensor, + left: bool = True, + transpose: bool = False, +) -> Tensor: + torch._check( + input.ndim >= 2, lambda: "torch.ormqr: input must have at least 2 dimensions." + ) + torch._check( + other.ndim >= 2, lambda: "torch.ormqr: other must have at least 2 dimensions." + ) + + left_size_condition = -2 if left else -1 + torch._check( + other.shape[left_size_condition] >= tau.shape[-1], + lambda: f"torch.ormqr: other.shape[{left_size_condition}] must be greater than or equal to tau.shape[-1]", + ) + torch._check( + other.shape[left_size_condition] == input.shape[-2], + lambda: f"torch.ormqr: other.shape[{left_size_condition}] must be equal to input.shape[-2]", + ) + + torch._check( + tau.shape[-1] <= input.shape[-1], + lambda: "torch.ormqr: tau.shape[-1] must be less than or equal to input.shape[-1]", + ) + + torch._check( + input.ndim - tau.ndim == 1, + lambda: ( + f"torch.ormqr: Expected tau to have one dimension less than input, " + f"but got tau.ndim equal to {tau.ndim} and input.ndim is equal to {input.ndim}" + ), + ) + torch._check( + input.ndim == other.ndim, + lambda: ( + f"torch.ormqr: Expected other to have the same number of dimensions as input, " + f"but got other.ndim equal to {other.ndim} and input.ndim is equal to {input.ndim}" + ), + ) + + if input.ndim > 2: + expected_batch_shape = input.shape[:-2] + actual_batch_tau_shape = tau.shape[:-1] + torch._check( + actual_batch_tau_shape == expected_batch_shape, + lambda: ( + f"torch.ormqr: Expected batch dimensions of tau to be " + f"equal to input.shape[:-2], but got {actual_batch_tau_shape}" + ), + ) + + actual_batch_other_shape = other.shape[:-2] + torch._check( + actual_batch_other_shape == expected_batch_shape, + lambda: ( + f"torch.ormqr: Expected batch dimensions of other to be " + f"equal to input.shape[:-2], but got {actual_batch_other_shape}" + ), + ) + + torch._check( + tau.dtype == input.dtype, + lambda: ( + f"torch.ormqr: Expected input and tau to have the same dtype, " + f"but input has dtype {input.dtype} and tau has dtype {tau.dtype}" + ), + ) + torch._check( + other.dtype == input.dtype, + lambda: ( + f"torch.ormqr: Expected input and other to have the same dtype, " + f"but input has dtype {input.dtype} and other has dtype {other.dtype}" + ), + ) + + checkSameDevice("torch.ormqr", tau, input, "tau") + checkSameDevice("torch.ormqr", other, input, "other") + + return torch.empty_strided( + size=other.shape, + stride=make_contiguous_strides_for(other.shape, row_major=False), + dtype=other.dtype, + device=other.device, + ) + + +def _padding_check_valid_input(input, padding, *, dim): + torch._check( + len(padding) == 2 * dim, + lambda: f"padding size is expected to be {2 * dim}, but got: {len(padding)}", + ) + + input_dim = input.ndim + + is_batch_mode = input_dim == (dim + 2) + + valid_batch_mode = is_batch_mode + valid_non_batch_mode = not is_batch_mode + + from torch.fx.experimental.symbolic_shapes import sym_and, sym_or + + if is_batch_mode: + # allow batch size of 0-dim. + for d in range(1, input_dim): + valid_batch_mode = sym_and(valid_batch_mode, input.size(d) != 0) + else: + for d in range(input_dim): + valid_non_batch_mode = sym_and(valid_non_batch_mode, input.size(d) != 0) + + # allow empty batch size but not other dimensions. + torch._check( + sym_or(valid_batch_mode, valid_non_batch_mode), + lambda: ( + f"Expected {dim + 1}D or {dim + 2}D (batch mode) tensor with possibly 0 batch size " + f"and other non-zero dimensions for input, but got: {input.shape}" + ), + ) + + +def _pad1d_common(input, padding, *, is_reflection): + from torch.fx.experimental.symbolic_shapes import sym_and + + dim_plane = 0 + dim_w = 1 + nbatch = 1 + + if input.ndim == 3: + nbatch = input.size(0) + dim_w += 1 + dim_plane += 1 + + _padding_check_valid_input(input, padding, dim=1) + + pad_l, pad_r = padding + + nplane = input.size(dim_plane) + input_w = input.size(dim_w) + output_w = input_w + pad_l + pad_r + + if is_reflection: + torch._check( + sym_and(pad_l < input_w, pad_r < input_w), + lambda: ( + f"Argument #4: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}" + ), + ) + + torch._check( + output_w >= 1, + lambda: f"input (W: {input_w}) is too small. Calculated output W: {output_w}", + ) + + if input.ndim == 2: + return input.new_empty((nplane, output_w)) + else: + return input.new_empty((nbatch, nplane, output_w)) + + +@register_meta(aten.reflection_pad1d) +@out_wrapper() +def meta_reflection_pad1d(input, padding): + return _pad1d_common(input, padding, is_reflection=True) + + +@register_meta(aten.replication_pad1d) +@out_wrapper() +def meta_replication_pad1d(input, padding): + torch._check( + input.dtype != torch.bool, + lambda: f""""replication_pad1d" not implemented for '{input.dtype.__str__()}'""", + ) + return _pad1d_common(input, padding, is_reflection=False) + + +def _pad1d_backward_common(grad_output, input, padding, *, is_reflection): + from torch.fx.experimental.symbolic_shapes import sym_and + + dim_w = 1 + if not is_reflection: + torch._check(len(padding) == 2, lambda: "padding size is expected to be 2") + + if input.ndim == 3: + dim_w += 1 + + pad_l, pad_r = padding + + input_w = input.size(dim_w) + output_w = input_w + pad_l + pad_r + + if is_reflection: + torch._check( + sym_and(pad_l < input_w, pad_r < input_w), + lambda: ( + f"Argument #4: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}" + ), + ) + + torch._check( + output_w == grad_output.size(dim_w), + lambda: f"grad_output width unexpected. Expected: {output_w}, Got: {grad_output.size(dim_w)}", + ) + + return input.new_empty(input.shape) + + +@register_meta(aten.reflection_pad1d_backward) +@out_wrapper("grad_input") +def meta_reflection_pad1d_backward(grad_output, input, padding): + return _pad1d_backward_common(grad_output, input, padding, is_reflection=True) + + +@register_meta(aten.replication_pad1d_backward) +@out_wrapper("grad_input") +def meta_replication_pad1d_backward(grad_output, input, padding): + return _pad1d_backward_common(grad_output, input, padding, is_reflection=False) + + +def _pad2d_common(input, padding, *, is_reflection): + from torch.fx.experimental.symbolic_shapes import sym_and + + dim_w = 2 + dim_h = 1 + dim_slices = 0 + nbatch = 1 + + _padding_check_valid_input(input, padding, dim=2) + + ndim = input.ndim + if ndim == 4: + nbatch = input.size(0) + dim_w += 1 + dim_h += 1 + dim_slices += 1 + + pad_l, pad_r, pad_t, pad_b = padding + + nplane = input.size(dim_slices) + input_h = input.size(dim_h) + input_w = input.size(dim_w) + output_h = input_h + pad_t + pad_b + output_w = input_w + pad_l + pad_r + + if is_reflection: + torch._check( + sym_and(pad_l < input_w, pad_r < input_w), + lambda: ( + f"Argument #4: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}" + ), + ) + torch._check( + sym_and(pad_t < input_h, pad_b < input_h), + lambda: ( + f"Argument #6: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_t}, {pad_b}) at dimension {dim_h} of input {input.shape}" + ), + ) + + torch._check( + sym_and(output_w >= 1, output_h >= 1), + lambda: ( + f"Calculated output H: {output_h} W: {output_w} must be >= 1 " + f"in every dimension (input H: {input_h}, W: {input_w})" + ), + ) + + if input.ndim == 3: + return input.new_empty((nplane, output_h, output_w)) + else: + output = input.new_empty((nbatch, nplane, output_h, output_w)) + # CPU kernels preserve channels_last via suggest_memory_format(), + # but CUDA kernels always produce contiguous output. + if ( + device_hint(input) != "cuda" + and utils.suggest_memory_format(input) == torch.channels_last + ): + output = output.to(memory_format=torch.channels_last) + return output + + +@register_meta(aten.reflection_pad2d) +@out_wrapper() +def meta_reflection_pad2d(input, padding): + return _pad2d_common(input, padding, is_reflection=True) + + +@register_meta(aten.replication_pad2d) +@out_wrapper() +def meta_replication_pad2d(input, padding): + torch._check( + input.dtype != torch.bool, + lambda: f""""replication_pad2d" not implemented for '{input.dtype.__str__()}'""", + ) + return _pad2d_common(input, padding, is_reflection=False) + + +@register_meta( + aten._weight_norm_interface_backward.default, +) +def meta_weight_norm_backward(grad_w, saved_v, saved_g, saved_norms, dim): + grad_v = torch.empty_like(saved_v) + grad_g = torch.empty_like(saved_g) + return grad_v, grad_g + + +@register_meta( + [ + aten.reflection_pad2d_backward.default, + aten.reflection_pad2d_backward.grad_input, + aten.replication_pad2d_backward.default, + aten.replication_pad2d_backward.grad_input, + ] +) +@out_wrapper("grad_input") +def meta_pad2d_backward(grad_output, self, padding): + dim_w = 2 + dim_h = 1 + dim_plane = 0 + + self_shape = self.shape + if self.dim() == 4: + dim_w += 1 + dim_h += 1 + dim_plane += 1 + + pad_l, pad_r, pad_t, pad_b = padding + + input_h = self_shape[dim_h] + input_w = self_shape[dim_w] + output_h = input_h + pad_t + pad_b + output_w = input_w + pad_l + pad_r + + torch._check( + output_w == grad_output.size(dim_w), + lambda: f"grad_output width unexpected. Expected: {output_w}, Got: {grad_output.size(dim_w)}", + ) + torch._check( + output_h == grad_output.size(dim_h), + lambda: f"grad_output height unexpected. Expected: {output_h}, Got: {grad_output.size(dim_h)}", + ) + return self.new_empty(self.shape) + + +def _pad3d_common(input, padding, *, is_reflection): + from torch.fx.experimental.symbolic_shapes import sym_and + + dim_w = 3 + dim_h = 2 + dim_d = 1 + dim_plane = 0 + + _padding_check_valid_input(input, padding, dim=3) + + batch_mode = input.ndim == 5 + if batch_mode: + nbatch = input.size(0) + dim_w += 1 + dim_h += 1 + dim_d += 1 + dim_plane += 1 + + pad_l, pad_r, pad_t, pad_b, pad_f, pad_bk = padding + + nplane = input.size(dim_plane) + input_d = input.size(dim_d) + input_h = input.size(dim_h) + input_w = input.size(dim_w) + output_d = input_d + pad_f + pad_bk + output_h = input_h + pad_t + pad_b + output_w = input_w + pad_l + pad_r + + if is_reflection: + torch._check( + sym_and(pad_l < input_w, pad_r < input_w), + lambda: ( + f"Argument #4: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}" + ), + ) + torch._check( + sym_and(pad_t < input_h, pad_b < input_h), + lambda: ( + f"Argument #6: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_t}, {pad_b}) at dimension {dim_h} of input {input.shape}" + ), + ) + torch._check( + sym_and(pad_f < input_d, pad_bk < input_d), + lambda: ( + f"Argument #8: Padding size should be less than the corresponding input dimension, " + f"but got: padding ({pad_f}, {pad_bk}) at dimension {dim_d} of input {input.shape}" + ), + ) + + torch._check( + sym_and(output_w >= 1, output_h >= 1, output_d >= 1), + lambda: ( + f"Calculated output D: {output_d} H: {output_h} W: {output_w} must be >= 1 " + f"in every dimension (input D: {input_d}, H: {input_h}, W: {input_w})" + ), + ) + + if batch_mode: + return input.new_empty((nbatch, nplane, output_d, output_h, output_w)) # type: ignore[possibly-undefined] + else: + return input.new_empty((nplane, output_d, output_h, output_w)) + + +@register_meta(aten.reflection_pad3d) +@out_wrapper() +def meta_reflection_pad3d(input, padding): + return _pad3d_common(input, padding, is_reflection=True) + + +@register_meta(aten.replication_pad3d) +@out_wrapper() +def meta_replication_pad3d(input, padding): + torch._check( + input.dtype != torch.bool, + lambda: f""""replication_pad3d" not implemented for '{input.dtype.__str__()}'""", + ) + return _pad3d_common(input, padding, is_reflection=False) + + +@register_meta( + [ + aten.reflection_pad3d_backward.default, + aten.reflection_pad3d_backward.grad_input, + aten.replication_pad3d_backward.default, + aten.replication_pad3d_backward.grad_input, + ] +) +@out_wrapper("grad_input") +def meta_pad3d_backward(grad_output, input, padding): + torch._check(len(padding) == 6, lambda: "padding size is expected to be 6") + if input.ndim <= 3: + raise AssertionError(f"input.ndim must be > 3, got {input.ndim}") + if grad_output.ndim != input.ndim: + raise AssertionError( + f"grad_output.ndim must equal input.ndim, got {grad_output.ndim} != {input.ndim}" + ) + + dim_w = 3 + dim_h = 2 + dim_d = 1 + + if input.ndim == 5: + dim_w += 1 + dim_h += 1 + dim_d += 1 + + pad_l, pad_r, pad_t, pad_b, pad_f, pad_bk = padding + + input_d = input.size(dim_d) + input_h = input.size(dim_h) + input_w = input.size(dim_w) + output_d = input_d + pad_f + pad_bk + output_h = input_h + pad_t + pad_b + output_w = input_w + pad_l + pad_r + + torch._check( + output_w == grad_output.size(dim_w), + lambda: f"grad_output width unexpected. Expected: {output_w}, Got: {grad_output.size(dim_w)}", + ) + torch._check( + output_h == grad_output.size(dim_h), + lambda: f"grad_output height unexpected. Expected: {output_h}, Got: {grad_output.size(dim_h)}", + ) + torch._check( + output_d == grad_output.size(dim_d), + lambda: f"grad_output depth unexpected. Expected: {output_d}, Got: {grad_output.size(dim_d)}", + ) + + return input.new_empty(input.shape) + + +@register_meta(aten._pdist_forward) +@out_wrapper() +def meta__pdist_forward(self: Tensor, p: float = 2) -> Tensor: + torch._check( + self.is_contiguous(), lambda: "_pdist_forward requires contiguous input" + ) + n = self.size(0) + return self.new_empty((n * (n - 1) // 2,)).to( + memory_format=torch.legacy_contiguous_format + ) # type: ignore[call-overload] + + +@register_meta(aten._pdist_backward) +@out_wrapper() +def meta__pdist_backward( + grad_output: Tensor, self: Tensor, p: float, pdist: Tensor +) -> Tensor: + torch._check( + self.is_contiguous(), lambda: "_pdist_backward requires self to be contiguous" + ) + torch._check( + pdist.is_contiguous(), lambda: "_pdist_backward requires pdist to be contiguous" + ) + return torch.empty_like(self, memory_format=torch.legacy_contiguous_format) + + +@register_meta([aten.baddbmm.default, aten.baddbmm.out]) +@out_wrapper(exact_dtype=True) +def meta_baddbmm(self, batch1, batch2, *, beta=1, alpha=1): + from torch.fx.experimental.symbolic_shapes import guard_or_true, sym_eq + + dim1 = batch1.size(0) + dim2 = batch1.size(1) + dim3 = batch2.size(2) + if guard_or_true(torch.sym_not(sym_eq(self.shape, (dim1, dim2, dim3)))): + self = self.expand((dim1, dim2, dim3)) + torch._check(batch1.dim() == 3, lambda: "batch1 must be a 3D tensor") + torch._check(batch2.dim() == 3, lambda: "batch2 must be a 3D tensor") + if not exp_config.skip_dtype_check_in_meta_registrations: + torch._check( + self.dtype == batch1.dtype == batch2.dtype, + lambda: f"Input dtypes must be the same, got: input: {self.dtype}, batch1: {batch1.dtype}, batch2: {batch2.dtype}", + ) + batch1_sizes = batch1.shape + batch2_sizes = batch2.shape + bs = batch1_sizes[0] + contraction_size = batch1_sizes[2] + torch._check( + batch2_sizes[0] == bs and batch2_sizes[1] == contraction_size, + lambda: ( + f"Expected size for first two dimensions of batch2 tensor to be: " + f"[{bs}, {contraction_size}] but got: [{batch2_sizes[0]}, {batch2_sizes[1]}]." + ), + ) + return self.new_empty(self.size()) + + +@register_meta([aten.bernoulli.default, aten.bernoulli.out]) +@out_wrapper() +def meta_bernoulli(self, *, generator=None): + # https://github.com/pytorch/pytorch/issues/88612 + return torch.empty_like(self, memory_format=torch.contiguous_format) + + +@register_meta(aten.bernoulli_.float) +def meta_bernoulli_(self, p=0.5, generator=None): + return self + + +@register_meta(aten.bernoulli.p) +def meta_bernoulli_p(self, p=0.5, generator=None): + # https://github.com/pytorch/pytorch/issues/88612 + return torch.empty_like(self, memory_format=torch.contiguous_format) + + +@register_meta([aten.poisson.default, aten.poisson.out]) +@out_wrapper() +def meta_poisson(self, generator=None): + return torch.empty_like(self) + + +@register_meta(aten._fused_moving_avg_obs_fq_helper.default) +def meta__fused_moving_avg_obs_fq_helper( + self, + observer_on, + fake_quant_on, + running_min, + running_max, + scale, + zero_point, + averaging_const, + quant_min, + quant_max, + ch_axis, + per_row_fake_quant=False, + symmetric_quant=False, +): + torch._check( + ch_axis < self.dim(), + lambda: "Error in fused_moving_avg_obs_fake_quant_cpu: ch_axis must be < self.dim()", + ) + mask = torch.empty_like(self, dtype=torch.bool) + return (torch.empty_like(self), mask) + + +@register_meta(aten.mm) +@out_wrapper(exact_dtype=True) +def meta_mm(a, b, out_dtype: torch.dtype | None = None): + torch._check(a.dim() == 2, lambda: "a must be 2D") + torch._check(b.dim() == 2, lambda: "b must be 2D") + N, M1 = a.shape + M2, P = b.shape + torch._check( + M1 == M2, + lambda: f"a and b must have same reduction dim, but got [{N}, {M1}] X [{M2}, {P}].", + ) + if out_dtype is not None: + # The out_dtype restriction below is a property of the in-tree CUDA/XPU + # backends (see aten/src/ATen/native/cuda/Blas.cpp and + # aten/src/ATen/native/mkldnn/xpu/Blas.cpp). Out-of-tree backends (e.g. + # accelerators registered via PrivateUse1) may support arbitrary + # out_dtype combinations, so only enforce it for the backends that have + # the restriction. + if device_hint(a) in ("cuda", "xpu"): + torch._check( + out_dtype == a.dtype + or ( + out_dtype == torch.float32 + and a.dtype in (torch.float16, torch.bfloat16) + ), + lambda: "out_dtype must be the same as input dtype or fp32 for fp16/bf16 inputs", + ) + result_dtype = a.dtype if out_dtype is None else out_dtype + return a.new_empty((N, P), dtype=result_dtype) + + +def _compute_reduction_shape(self, dims, keepdim): + if keepdim: + return tuple(self.shape[i] if i not in dims else 1 for i in range(self.ndim)) + + return utils.compute_reduction_output_shape(self.shape, dims) + + +# FakeTensors (meta tensors with a device) will report device as meta +# when running meta kernels. Here, access the "fake device" of FakeTensor if it +# exists so meta kernels which have diverge per device will be more +# accurate when run with FakeTensors +def device_hint(tensor) -> "str": + fake_device = torch._subclasses.fake_tensor.maybe_get_fake_device(tensor) + if fake_device is not None: + return fake_device.type + elif ( + hasattr(tensor, "device") + and hasattr(tensor.device, "type") + and tensor.device.type != "meta" + ): + return tensor.device.type + else: + return "cuda" # default to cuda + + +def calc_conv_nd_return_shape( + input_tensor: torch.Tensor, + weight: torch.Tensor, + stride: list[int] | int, + padding: list[int] | int, + dilation: list[int] | int, + is_transposed: bool, + groups: int, + output_padding: list[int] | int | None = None, +): + def _formula(ln: int, p: int, d: int, k: int, s: int) -> int: + """ + Formula to apply to calculate the length of some dimension of the output + + See: https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html + + Args: + ln: length of the dimension + p: padding in that dim + d: dilation in that dim + k: kernel size in that dim + s: stride in that dim + Returns: + The output length + """ + return (ln + 2 * p - d * (k - 1) - 1) // s + 1 + + def _formula_transposed(ln: int, p: int, d: int, k: int, s: int, op: int) -> int: + """ + Formula to apply to calculate the length of some dimension of the output + if transposed convolution is used. + See: https://pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d.html + + Args: + ln: length of the dimension + p: padding in that dim + d: dilation in that dim + k: kernel size in that dim + s: stride in that dim + op: output padding in that dim + + Returns: + The output length + """ + return (ln - 1) * s - 2 * p + d * (k - 1) + op + 1 + + kernel_size = weight.shape[2:] + dims = input_tensor.shape[2:] + if is_transposed: + out_channels = groups * weight.shape[1] + else: + out_channels = weight.shape[0] + torch._check( + weight.shape[1] * groups == input_tensor.shape[1], + lambda: "Invalid channel dimensions", + ) + + ret_shape = [input_tensor.shape[0], out_channels] + if isinstance(stride, IntLike): + # pyrefly: ignore [bad-assignment] + stride = [stride] * len(dims) + elif len(stride) == 1: + stride = [stride[0]] * len(dims) + + if isinstance(padding, IntLike): + # pyrefly: ignore [bad-assignment] + padding = [padding] * len(dims) + elif len(padding) == 1: + padding = [padding[0]] * len(dims) + + if isinstance(dilation, IntLike): + # pyrefly: ignore [bad-assignment] + dilation = [dilation] * len(dims) + elif len(dilation) == 1: + dilation = [dilation[0]] * len(dims) + + output_padding_list: list[int] | None = None + if output_padding: + if isinstance(output_padding, IntLike): + # pyrefly: ignore [bad-assignment] + output_padding_list = [output_padding] * len(dims) + elif len(output_padding) == 1: + output_padding_list = [output_padding[0]] * len(dims) + else: + output_padding_list = output_padding + + # Validate kernel size fits within padded input (mirrors C++ check_shape_forward + # in aten/src/ATen/native/Convolution.cpp). + if not is_transposed: + from torch.fx.experimental.symbolic_shapes import sym_and + + # pyrefly: ignore [bad-index, index-error] + padded_input = [dims[i] + 2 * padding[i] for i in range(len(dims))] + effective_kernel = [ + # pyrefly: ignore [bad-index, index-error] + dilation[i] * (kernel_size[i] - 1) + 1 + for i in range(len(dims)) + ] + torch._check( + sym_and( + *[p >= k for p, k in zip(padded_input, effective_kernel, strict=True)] + ), + lambda: ( + f"Calculated padded input size per channel: " + f"({' x '.join(str(x) for x in padded_input)}). " + f"Kernel size: ({' x '.join(str(x) for x in effective_kernel)}). " + f"Kernel size can't be greater than actual input size" + ), + ) + + for i in range(len(dims)): + # If output_padding is present, we are dealing with a transposed convolution + if output_padding_list: + ret_shape.append( + _formula_transposed( + dims[i], + # pyrefly: ignore [bad-index] + padding[i], + # pyrefly: ignore [bad-index, index-error] + # pyrefly: ignore [bad-index, index-error] + dilation[i], + kernel_size[i], + # pyrefly: ignore [bad-index, index-error] + stride[i], + output_padding_list[i], + ) + ) + else: + ret_shape.append( + # pyrefly: ignore [bad-index, index-error] + _formula(dims[i], padding[i], dilation[i], kernel_size[i], stride[i]) + ) + # NOTE: Backend behavior for zero-sized spatial dimensions is inconsistent. + # CUDA (cuDNN) and HIP handle zero-sized conv_transpose outputs by short-circuiting, + # but other backends fail: CPU rejects it and MPS asserts "Placeholder tensor is empty". + from torch._subclasses.fake_tensor import maybe_get_fake_device + from torch.fx.experimental.symbolic_shapes import sym_and, sym_or + + fake_device = maybe_get_fake_device(input_tensor) + device = fake_device if fake_device is not None else input_tensor.device + + # ROCm reports device.type as "cuda"; keep the existing NVIDIA CUDA behavior + # unchanged and only apply the new check to HIP. + is_cudnn = device.type == "cuda" and torch.version.hip is None + is_hip = device.type == "cuda" and torch.version.hip is not None + if is_hip: + torch._check( + sym_and(*[x >= 0 for x in ret_shape[2:]]), + lambda: f"Given input size per channel: {list(dims)}. " + f"Calculated output size per channel: {ret_shape[2:]}. " + f"Output size is too small", + ) + elif not is_cudnn: + torch._check( + sym_or(*[x > 0 for x in ret_shape[2:]]), + lambda: f"Given input size per channel: {list(dims)}. " + f"Calculated output size per channel: {ret_shape[2:]}. " + f"Output size is too small", + ) + + return ret_shape + + +def is_channels_last(ten): + return torch._prims_common.suggest_memory_format(ten) == torch.channels_last + + +@register_meta(aten.miopen_batch_norm.default) +def meta_miopen_batch_norm( + input_tensor: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor | None, + running_mean: torch.Tensor | None, + running_var: torch.Tensor | None, + training: bool, + exponential_average_factor: float, + epsilon: float, +): + # If tensor is provided for running_mean and running_var then use this. If these are not + # provided then we return the shape of weight tensor. Similar to how this is handled in the decomposition + save_mean_shape = running_mean.shape if running_mean is not None else weight.shape + save_var_shape = running_var.shape if running_var is not None else weight.shape + + # Pick the output memory format the same way eager does (suggest_memory_format), + # but in a DDE-safe way for unbacked symbolic strides: if we can't decide whether + # the input is channels_last contiguous, fall back to plain contiguous. + fmt = suggest_memory_format(input_tensor) + + # Mirror eager's TORCH_CHECK so the compiled graph fails fast at runtime + # instead of silently producing an output with the wrong strides. + torch._check( + torch.ops.aten.sym_is_contiguous.default(input_tensor, memory_format=fmt), + lambda: f"miopen_batch_norm: input must be contiguous in {fmt}", + ) + + out = torch.empty_like(input_tensor, memory_format=fmt) + + if training: + save_mean = weight.new_empty(save_mean_shape) + save_var = weight.new_empty(save_var_shape) + else: + save_mean = weight.new_empty((0,)) + save_var = weight.new_empty((0,)) + + return out, save_mean, save_var + + +@register_meta(aten.convolution.default) +def meta_conv( + input_tensor: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor | None, + stride: list[int], + padding: list[int], + dilation: list[int], + is_transposed: bool, + output_padding: list[int], + groups: int, +): + shape_out = calc_conv_nd_return_shape( + input_tensor, + weight, + stride, + padding, + dilation, + is_transposed, + groups, + output_padding if is_transposed else None, + ) + + from torch.fx.experimental.symbolic_shapes import guard_or_false + + input_channels_dim = 1 + output_channels_dim = 1 + if guard_or_false(input_tensor.size(input_channels_dim) == 0): + shape_out[output_channels_dim] = 0 + + # Memory format is left as contiguous: meta tensors have no device info, + # so _select_conv_backend returns Overrideable and the correct format + # cannot be determined here. The FakeTensor path (torch.compile, export) + # intercepts via a register_op_impl in fake_impls.py before reaching this + # kernel and uses FakeTensor.fake_device for an accurate answer. + out = input_tensor.new_empty(shape_out) + return out + + +@register_meta(aten._convolution.default) +def meta__conv( + input_tensor: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor | None, + stride: list[int], + padding: list[int], + dilation: list[int], + transposed: bool, + output_padding: list[int], + groups: int, + benchmark: bool, + deterministic: bool, + cudnn_enabled: bool, + allow_tf32: bool = True, +): + return meta_conv( + input_tensor, + weight, + bias, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + ) + + +if torch._C._has_mkldnn: + _meta_lib_dont_use_me_use_register_meta_for_mkldnn = torch.library.Library( + "mkldnn", "IMPL", "Meta" + ) + + @register_meta(torch.ops.mkldnn._convolution_pointwise.default) + def meta_mkldnn_convolution_default( + input_tensor, + weight, + bias, + padding, + stride, + dilation, + groups, + attr, + scalars, + algorithm, + ): + shape_out = calc_conv_nd_return_shape( + input_tensor, weight, stride, padding, dilation, False, groups, [] + ) + out = input_tensor.new_empty(shape_out) + out_memory_format = torch.channels_last + if input_tensor.dim() == 5: + out_memory_format = torch.channels_last_3d + out = out.to(memory_format=out_memory_format) # type: ignore[call-overload] + return out + + @register_meta(torch.ops.mkldnn._linear_pointwise.default) + def meta_linear_pointwise_default( + input_tensor, weight, bias, attr, scalars, algorithm + ): + return input_tensor.new_empty((*input_tensor.shape[:-1], weight.shape[0])) + + if torch._C.has_mkl: + _meta_lib_dont_use_me_use_register_meta_for_mkl = torch.library.Library( + "mkl", "IMPL", "Meta" + ) + + @register_meta(torch.ops.mkl._mkl_linear) + def meta_mkl_linear(input_tensor, packed_weight, orig_weight, bias, batch_size): + return input_tensor.new_empty( + (*input_tensor.shape[:-1], orig_weight.shape[0]) + ) + + _meta_lib_dont_use_me_use_register_meta_for_onednn = torch.library.Library( + "onednn", "IMPL", "Meta" + ) + + @register_meta(torch.ops.onednn.qconv2d_pointwise.default) + @register_meta(torch.ops.onednn.qconv_pointwise.default) + @register_meta(torch.ops.onednn.qconv_pointwise.tensor) + def meta_qconv_pointwise( + x, + x_scale, + x_zp, + w, # prepacked_weight + w_scale, + w_zp, + bias, + stride, + padding, + dilation, + groups, + output_scale, + output_zero_point, + output_dtype, + attr, + scalars, + algorithm, + ): + shape_out = calc_conv_nd_return_shape( + x, + w, + stride, + padding, + dilation, + False, + groups, + None, + ) + if output_dtype is None: + output_dtype = x.dtype + if output_dtype not in [ + torch.float32, + torch.bfloat16, + torch.uint8, + torch.int8, + torch.float8_e4m3fn, + ]: + raise AssertionError( + f"output_dtype must be one of float32, bfloat16, uint8, int8, float8_e4m3fn, got {output_dtype}" + ) + out = x.new_empty(shape_out, dtype=output_dtype) + if len(shape_out) not in [3, 4, 5]: + raise AssertionError( + f"Expect output to be 3d/4d/5d for conv1d/2d/3d, got {len(shape_out)}d" + ) + format = { + 3: torch.contiguous_format, + 4: torch.channels_last, + 5: torch.channels_last_3d, + }[len(shape_out)] + out = out.to(memory_format=format) + return out + + @register_meta(torch.ops.onednn.qconv2d_pointwise.binary) + @register_meta(torch.ops.onednn.qconv2d_pointwise.binary_tensor) + def meta_qconv2d_pointwise_binary( + x, + x_scale, + x_zp, + w, + w_scale, + w_zp, + accum, + bias, + stride, + padding, + dilation, + groups, + output_scale, + output_zero_point, + output_dtype, + accum_scale, + accum_zero_point, + binary_op_name, + alpha, + unary_op_name, + unary_op_args, + unary_op_algorithm, + ): + if binary_op_name != "sum": + raise AssertionError( + f"binary_op_name must be 'sum', got '{binary_op_name}'" + ) + return accum + + @register_meta(torch.ops.onednn.qlinear_pointwise.default) + @register_meta(torch.ops.onednn.qlinear_pointwise.tensor) + def meta_qlinear_pointwise( + x, + x_scale, + x_zp, + w, + w_scale, + w_zp, + bias, + output_scale, + output_zero_point, + output_dtype, + post_op_name, + post_op_args, + post_op_algorithm, + ): + output_shape = list(x.shape) + # The weight has been transposed during the qlinear weight prepack process. + output_shape[-1] = w.shape[1] + if output_dtype not in [ + torch.float32, + torch.bfloat16, + torch.int8, + torch.uint8, + torch.float8_e4m3fn, + ]: + raise AssertionError( + f"output_dtype must be one of float32, bfloat16, int8, uint8, float8_e4m3fn, got {output_dtype}" + ) + out = x.new_empty(output_shape, dtype=output_dtype) + return out + + @register_meta(torch.ops.onednn.qlinear_pointwise.binary) + @register_meta(torch.ops.onednn.qlinear_pointwise.binary_tensor) + def meta_qlinear_pointwise_binary( + x, + x_scale, + x_zp, + w, + w_scale, + w_zp, + x_2, + bias, + output_scale, + output_zero_point, + output_dtype, + x2_scale, + x2_zp, + binary_op_name, + alpha, + unary_op_name, + unary_op_args, + unary_op_algorithm, + ): + if binary_op_name == "sum": + return x_2 + output_shape = list(x.shape) + # The weight has been transposed during the qlinear weight prepack process. + output_shape[-1] = w.shape[1] + if output_dtype not in [ + torch.float32, + torch.bfloat16, + torch.uint8, + torch.int8, + torch.float8_e4m3fn, + ]: + raise AssertionError( + f"output_dtype must be one of float32, bfloat16, uint8, int8, float8_e4m3fn, got {output_dtype}" + ) + out = x.new_empty(output_shape, dtype=output_dtype) + return out + + @register_meta(torch.ops.onednn.linear_dynamic_fp16.default) + @register_meta(torch.ops.onednn.linear_relu_dynamic_fp16.default) + def meta_linear_dynamic_fp16( + x, + w, + bias, + ): + output_shape = list(x.shape) + # The weight has been transposed during the qlinear weight prepack process. + output_shape[-1] = w.shape[1] + out = x.new_empty(output_shape) + return out + + @register_meta(torch.ops.onednn.qlinear_prepack.default) + def meta_qlinear_prepack(weight, x_shape): + # Mirror the real C++ kernel pack_weight_to_onednn_tensor in + # aten/src/ATen/native/quantized/cpu/qlinear_prepack.cpp + torch._check( + weight.dim() == 2, + lambda: f"qlinear_prepack expects a 2D weight, got {weight.dim()}D", + ) + torch._check( + weight.dtype in (torch.int8, torch.float8_e4m3fn), + lambda: ( + "qlinear_prepack expects int8 or float8_e4m3fn weight, " + f"got {weight.dtype}" + ), + ) + N, K = weight.shape + torch._check( + x_shape is None or x_shape[-1] == K, + lambda: ( + f"qlinear_prepack: x_shape[-1] ({x_shape[-1]}) must match " + f"weight in_features ({K})" + ), + ) + return weight.new_empty((K, N)) + + _meta_lib_dont_use_me_use_register_meta_for_quantized = torch.library.Library( + "quantized", "IMPL", "Meta" + ) + + @register_meta(torch.ops.quantized.max_pool2d) + def meta_quantized_max_pool2d( + input, + kernel_size, + stride=(), + padding=(0,), + dilation=(1,), + ceil_mode=False, + ): + ( + nInputPlane, + outputHeight, + outputWidth, + ) = max_pool2d_checks_and_compute_shape( + input, kernel_size, stride, padding, dilation, ceil_mode + ) + nbatch = input.size(-4) if input.dim() == 4 else 1 + memory_format = torch.channels_last + if input.dim() == 3: + size = [nInputPlane, outputHeight, outputWidth] + else: + size = [nbatch, nInputPlane, outputHeight, outputWidth] + return torch.empty( + size, + dtype=input.dtype, + device=input.device, + memory_format=memory_format, + ) + + @register_meta(torch.ops.quantized.int4mm_packed_weight_cpu) + def meta_int4mm_packed_weight_cpu(x, w, q_group_size, q_scale_and_zeros): + torch._check(x.dim() == 2, lambda: f"x must be a 2D tensor, got {x.dim()}D") + torch._check(w.dim() == 2, lambda: f"w must be a 2D tensor, got {w.dim()}D") + torch._check( + x.dtype in [torch.float32, torch.float16, torch.bfloat16], + lambda: f"expected x to be f32/f16/bf16, got {x.dtype}", + ) + torch._check( + w.dtype == torch.uint8, lambda: f"expected w to be uint8, got {w.dtype}" + ) + torch._check( + q_group_size.dtype == torch.int64, + lambda: f"q_group_size must be int64, got {q_group_size.dtype}", + ) + torch._check( + q_scale_and_zeros.dtype == x.dtype, + lambda: f"q_scale_and_zeros must have the same dtype as x, got {q_scale_and_zeros.dtype}", + ) + return x.new_empty(x.size(0), w.size(0), dtype=x.dtype) + + +# from check_dim_size() in aten/src/ATen/TensorUtils.cpp. +def check_dim_size(tensor, dim, dim_size, size): + torch._check( + tensor.dim() == dim and tensor.shape[dim_size] == size, + lambda: f"Expected a tensor of dimension {dim} and tensor.size[{dim_size}] == {size}, " + + f"but got : dimension {tensor.dim()} and tensor.size[{dim_size}] = {tensor.shape[dim_size]}", + ) + + +@register_meta(aten.quantize_per_tensor) +def meta_quantize_per_tensor( + input: torch.Tensor, scale: float, zero_point: int, dtype: torch.dtype +) -> torch.Tensor: + return torch.empty_like(input) + + +@register_meta(aten.avg_pool2d.default) +def meta_avg_pool2d( + input, + kernel_size, + stride=(), + padding=(0,), + ceil_mode=False, + count_include_pad=True, + divisor_override=None, +): + def unpack(name, val): + torch._check( + len(val) in [1, 2], + lambda: f"avg_pool2d: {name} must either be a single int, or a tuple of two ints", + ) + H = val[0] + W = H if len(val) == 1 else val[1] + return H, W + + kH, kW = unpack("kernel_size", kernel_size) + torch._check( + len(stride) in [0, 1, 2], + lambda: "avg_pool2d: stride must either be omitted, a single int, or a tuple of two ints", + ) + torch._check( + input.dtype not in [torch.uint8, torch.uint16, torch.uint32, torch.uint64], + lambda: f""""avg_pool2d" not implemented for '{input.dtype.__str__()}'""", + ) + if len(stride) == 0: + dH, dW = kH, kW + elif len(stride) == 1: + dH, dW = stride[0], stride[0] + else: + dH, dW = unpack("stride", stride) + + padH, padW = unpack("padding", padding) + + torch._check( + divisor_override is None or divisor_override != 0, + lambda: "divisor must be not zero", + ) + + nbatch = input.size(-4) if input.dim() == 4 else 1 + nInputPlane = input.size(-3) + inputHeight = input.size(-2) + inputWidth = input.size(-1) + + outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, 1, ceil_mode) + outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, 1, ceil_mode) + + memory_format = utils.suggest_memory_format(input) + pool2d_shape_check( + input, + kH, + kW, + dH, + dW, + padH, + padW, + 1, + 1, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + memory_format, + ) + + if input.dim() == 3: + size = [nInputPlane, outputHeight, outputWidth] + else: + size = [nbatch, nInputPlane, outputHeight, outputWidth] + return torch.empty( + size, + dtype=input.dtype, + device=input.device, + memory_format=memory_format, + ) + + +# from avg_pool2d_backward_shape_check() in aten/src/ATen/native/Pool.h. +def avg_pool2d_backward_shape_check( + input, + gradOutput, + nbatch, + kH, + kW, + dH, + dW, + padH, + padW, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + mem_format, +): + pool2d_shape_check( + input, + kH, + kW, + dH, + dW, + padH, + padW, + 1, + 1, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + mem_format, + ) + + ndim = input.dim() + nOutputPlane = nInputPlane + + check_dim_size(gradOutput, ndim, ndim - 3, nOutputPlane) + check_dim_size(gradOutput, ndim, ndim - 2, outputHeight) + check_dim_size(gradOutput, ndim, ndim - 1, outputWidth) + + +# Don't override the C++ registration. +@register_meta(aten.avg_pool2d_backward.default) +def meta_avg_pool2d_backward( + gradOutput_, + input, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override, +): + # From aten/src/ATen/native/AveragePool2d.cpp structured kernel meta func. + torch._check( + len(kernel_size) == 1 or len(kernel_size) == 2, + lambda: "avg_pool2d: kernel_size must either be a single int, or a tuple of two ints", + ) + kH = kernel_size[0] + kW = kH if len(kernel_size) == 1 else kernel_size[1] + torch._check( + len(stride) == 0 or len(stride) == 1 or len(stride) == 2, + lambda: "avg_pool2d: stride must either be omitted, a single int, or a tuple of two ints", + ) + dH = kH if len(stride) == 0 else stride[0] + dW = kW if len(stride) == 0 else dH if len(stride) == 1 else stride[1] + torch._check( + len(padding) == 1 or len(padding) == 2, + lambda: "avg_pool2d: padding must either be a single int, or a tuple of two ints", + ) + padH = padding[0] + padW = padH if len(padding) == 1 else padding[1] + + torch._check( + divisor_override is None or divisor_override != 0, + lambda: "divisor must be not zero", + ) + + input_size = input.shape + nbatch = input_size[-4] if input.dim() == 4 else 1 + nInputPlane = input_size[-3] + inputHeight = input_size[-2] + inputWidth = input_size[-1] + + outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, 1, ceil_mode) + outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, 1, ceil_mode) + + mem_format = utils.suggest_memory_format(input) + + avg_pool2d_backward_shape_check( + input, + gradOutput_, + nbatch, + kH, + kW, + dH, + dW, + padH, + padW, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + mem_format, + ) + + return torch.empty( + input_size, + dtype=input.dtype, + device=input.device, + memory_format=mem_format, + ) + + +@register_meta(aten.avg_pool3d) +@out_wrapper() +def meta_avg_pool3d( + input, + kernel_size, + stride=(), + padding=(0,), + ceil_mode=False, + count_include_pad=True, + divisor_override=None, +): + torch._check( + len(kernel_size) in (1, 3), + lambda: "avg_pool3d: kernel_size must be a single int, or a tuple of three ints", + ) + kT = kernel_size[0] + kH = kT if len(kernel_size) == 1 else kernel_size[1] + kW = kT if len(kernel_size) == 1 else kernel_size[2] + + torch._check( + not stride or len(stride) in (1, 3), + lambda: "avg_pool3d: stride must be omitted, a single int, or a tuple of three ints", + ) + torch._check( + input.dtype not in [torch.uint8, torch.uint16, torch.uint32, torch.uint64], + lambda: f""""avg_pool3d" not implemented for '{input.dtype.__str__()}'""", + ) + dT = kT if not stride else stride[0] + dH = kH if not stride else (dT if len(stride) == 1 else stride[1]) + dW = kW if not stride else (dT if len(stride) == 1 else stride[2]) + + torch._check( + len(padding) in (1, 3), + lambda: "avg_pool3d: padding must be a single int, or a tuple of three ints", + ) + padT = padding[0] + padH = padT if len(padding) == 1 else padding[1] + padW = padT if len(padding) == 1 else padding[2] + + torch._check( + input.ndim in (4, 5), + lambda: "non-empty 4D or 5D (batch mode) tensor expected for input", + ) + + torch._check( + divisor_override is None or divisor_override != 0, + lambda: "divisor must be not zero", + ) + + nbatch = input.size(0) + nslices = input.size(-4) + itime = input.size(-3) + iheight = input.size(-2) + iwidth = input.size(-1) + + otime = pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode) + oheight = pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode) + owidth = pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode) + + pool3d_shape_check( + input, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + padT, + padH, + padW, + 1, + 1, + 1, + itime, + iheight, + iwidth, + otime, + oheight, + owidth, + "avg_pool3d()", + check_input_size=True, + ) + + if input.ndim == 4: + return input.new_empty((nslices, otime, oheight, owidth)) + else: + return input.new_empty((nbatch, nslices, otime, oheight, owidth)) + + +@register_meta(aten.avg_pool3d_backward) +@out_wrapper("grad_input") +def meta_avg_pool3d_backward( + grad_output, + input, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override, +): + torch._check( + len(kernel_size) in (1, 3), + lambda: "avg_pool3d: kernel_size must be a single int, or a tuple of three ints", + ) + kT = kernel_size[0] + kH = kT if len(kernel_size) == 1 else kernel_size[1] + kW = kT if len(kernel_size) == 1 else kernel_size[2] + + torch._check( + not stride or len(stride) in (1, 3), + lambda: "avg_pool3d: stride must be omitted, a single int, or a tuple of three ints", + ) + dT = kT if not stride else stride[0] + dH = kH if not stride else (dT if len(stride) == 1 else stride[1]) + dW = kW if not stride else (dT if len(stride) == 1 else stride[2]) + + torch._check( + len(padding) in (1, 3), + lambda: "avg_pool3d: padding must be a single int, or a tuple of three ints", + ) + padT = padding[0] + padH = padT if len(padding) == 1 else padding[1] + padW = padT if len(padding) == 1 else padding[2] + + torch._check( + input.ndim in (4, 5), + lambda: "non-empty 4D or 5D (batch mode) tensor expected for input", + ) + + torch._check( + divisor_override is None or divisor_override != 0, + lambda: "divisor must be not zero", + ) + + nslices = input.size(-4) + itime = input.size(-3) + iheight = input.size(-2) + iwidth = input.size(-1) + + otime_for_shape_check = pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode) + oheight_for_shape_check = pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode) + owidth_for_shape_check = pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode) + + avg_pool3d_backward_shape_check( + input, + grad_output, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + padT, + padH, + padW, + itime, + iheight, + iwidth, + otime_for_shape_check, + oheight_for_shape_check, + owidth_for_shape_check, + "avg_pool3d_backward()", + ) + + return input.new_empty(input.shape) + + +@register_meta(aten._adaptive_avg_pool2d.default) +def meta_adaptive_avg_pool2d(self, output_size): + torch._check( + self.ndim == 3 or self.ndim == 4, + lambda: f"Expected 3D or 4D tensor, but got {self.shape}", + ) + output_shape = self.shape[:-2] + tuple(output_size) + memory_format = utils.suggest_memory_format(self) + # need to set memory_format to preserve the memory format of the input + # channel last input should have channel last output + return torch.empty( + output_shape, + dtype=self.dtype, + device=self.device, + memory_format=memory_format, + ) + + +@register_meta(aten._adaptive_avg_pool3d.default) +def meta_adaptive_avg_pool3d(self, output_size): + torch._check( + self.ndim == 4 or self.ndim == 5, + lambda: f"Expected 4D or 5D tensor, but got {self.shape}", + ) + return self.new_empty(self.shape[:-3] + tuple(output_size)) + + +@register_meta(aten._adaptive_avg_pool2d_backward.default) +def meta__adaptive_avg_pool2d_backward(grad_out, self): + ndim = grad_out.ndim + for i in range(1, ndim): + torch._check( + grad_out.size(i) > 0, + lambda: f"adaptive_avg_pool2d_backward(): Expected grad_output to have non-zero \ + size for non-batch dimensions, {grad_out.shape} with dimension {i} being empty", + ) + torch._check( + ndim == 3 or ndim == 4, + lambda: f"adaptive_avg_pool2d_backward(): Expected 3D or 4D tensor, but got {self.shape}", + ) + torch._check( + self.dtype == grad_out.dtype, + lambda: f"expected dtype {self.dtype} for `grad_output` but got dtype {grad_out.dtype}", + ) + memory_format = torch.contiguous_format + if is_channels_last(self): + memory_format = torch.channels_last + return self.new_empty(self.shape).to(memory_format=memory_format) + + +@register_meta(aten._adaptive_avg_pool3d_backward) +@out_wrapper("grad_input") +def meta__adaptive_avg_pool3d_backward(grad_output, self): + _adaptive_pool_empty_output_check(grad_output, "adaptive_avg_pool3d_backward") + return torch.empty_like(self, memory_format=torch.legacy_contiguous_format) + + +def _adaptive_pool_empty_output_check(grad_output: Tensor, arg_name: str): + ndim = grad_output.ndim + for i in range(1, ndim): + torch._check( + grad_output.size(i) > 0, + lambda: ( + f"{arg_name}(): Expected grad_output to have non-zero size for non-batch dimensions, " + f"but grad_output has sizes {grad_output.shape} with dimension {i} being empty" + ), + ) + + +@register_meta(aten.adaptive_max_pool2d) +@out_wrapper("out", "indices") +def meta_adaptive_max_pool2d(input, output_size): + ndim = input.ndim + torch._check( + ndim in (3, 4), + lambda: f"adaptive_max_pool2d(): Expected 3D or 4D tensor, but got: {input.shape}", + ) + for i in range(1, ndim): + torch._check( + input.size(i) > 0, + lambda: ( + f"adaptive_max_pool2d(): Expected input to have non-zero size for non-batch dimensions, " + f"but input has sizes {input.shape} with dimension {i} being empty" + ), + ) + + torch._check( + len(output_size) == 2, + lambda: "adaptive_max_pool2d(): internal error: output_size.size() must be 2", + ) + + dimH = 1 + sizeB = 1 + sizeD = 0 + + if input.ndim == 4: + sizeB = input.size(0) + dimH += 1 + + sizeD = input.size(dimH - 1) + osizeH, osizeW = output_size + + if input.ndim == 3: + out_shape = (sizeD, osizeH, osizeW) + out = input.new_empty(out_shape) + indices = input.new_empty(out_shape, dtype=torch.int64) + return out, indices + else: + out_shape = (sizeB, sizeD, osizeH, osizeW) # type: ignore[assignment] + memory_format = utils.suggest_memory_format(input) + out = input.new_empty(out_shape).to(memory_format=memory_format) + indices = input.new_empty(out_shape, dtype=torch.int64).to( + memory_format=memory_format + ) + return out, indices + + +@register_meta(aten.adaptive_max_pool2d_backward) +@out_wrapper("grad_input") +def meta_adaptive_max_pool2d_backward(grad_output, input, indices): + ndim = grad_output.ndim + torch._check( + ndim in (3, 4), + lambda: f"adaptive_max_pooling2d_backward(): Expected 3D or 4D grad_output, but got: {grad_output.shape}", + ) + + _adaptive_pool_empty_output_check(grad_output, "adaptive_max_pool2d_backward") + + torch._check( + input.dtype == grad_output.dtype, + lambda: f"expected dtype {input.dtype} for `grad_output` but got dtype {grad_output.dtype}", + ) + + memory_format = utils.suggest_memory_format(input) + return input.new_empty(input.shape).to(memory_format=memory_format) + + +@register_meta(aten.adaptive_max_pool3d) +@out_wrapper("out", "indices") +def meta_adaptive_max_pool3d(input, output_size): + ndim = input.ndim + torch._check( + ndim in (4, 5), + lambda: f"adaptive_max_pool3d(): Expected 4D or 5D tensor, but got: {input.shape}", + ) + for i in range(1, ndim): + torch._check( + input.size(i) > 0, + lambda: ( + f"adaptive_max_pool3d(): Expected input to have non-zero size for non-batch dimensions, " + f"but input has sizes {input.shape} with dimension {i} being empty" + ), + ) + + torch._check( + len(output_size) == 3, + lambda: "adaptive_max_pool3d(): internal error: output_size.size() must be 3", + ) + + dimD = 0 + sizeB = 1 + sizeD = 0 + + if ndim == 5: + sizeB = input.size(0) + dimD += 1 + + sizeD = input.size(dimD) + osizeT, osizeH, osizeW = output_size + + if ndim == 4: + out_shape = (sizeD, osizeT, osizeH, osizeW) + else: + out_shape = (sizeB, sizeD, osizeT, osizeH, osizeW) # type: ignore[assignment] + + out = input.new_empty(out_shape) + indices = input.new_empty(out_shape, dtype=torch.int64) + + return out, indices + + +@register_meta(aten.adaptive_max_pool3d_backward) +@out_wrapper("grad_input") +def meta_adaptive_max_pool3d_backward(grad_output, input, indices): + _adaptive_pool_empty_output_check(grad_output, "adaptive_max_pool3d_backward") + return input.new_empty(input.shape) + + +@register_meta(aten.repeat_interleave.Tensor) +def meta_repeat_interleave_Tensor(repeats, output_size=None): + if output_size is None: + raise RuntimeError("cannot repeat_interleave a meta tensor without output_size") + return repeats.new_empty(output_size) + + +@register_meta([aten.complex.default, aten.complex.out]) +@out_wrapper() +def meta_complex(real, imag): + if not real.dtype.is_floating_point: + raise AssertionError(f"real must be floating point, got {real.dtype}") + if not imag.dtype.is_floating_point: + raise AssertionError(f"imag must be floating point, got {imag.dtype}") + result = elementwise_meta( + real.to(corresponding_complex_dtype(real.dtype)), + imag.to(corresponding_complex_dtype(imag.dtype)), + type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + ) + return result + + +@register_meta([aten.nonzero_static.default, aten.nonzero_static.out]) +@out_wrapper() +def nonzero_static(self, *, size, fill_value: int = -1): + # The impl of nonzero_static on xpu and mps differs from cuda but aligned with cpu + if device_hint(self) in ("cpu", "mps", "xpu"): + return self.new_empty((size, self.dim()), dtype=torch.long) + else: + return torch.empty_strided( + (size, self.dim()), + (1, size), + dtype=torch.long, + device=self.device, + ) + + +@register_meta([torch.ops.aten.nonzero.default, torch.ops.aten.nonzero.out]) +@out_wrapper() +def nonzero(self): + torch._check_not_implemented( + exp_config.meta_nonzero_assume_all_nonzero, + lambda: "The register_meta function for torch.nonzero() raises unimplemented by default, " + "as a correct data-independent implementation does not exist. This implementation " + "returns a fake value, assuming all elements of the tensor are non-zero. " + "To enable this registration, please set " + "'torch.fx.experimental._config.meta_nonzero_assume_all_nonzero' to True.", + ) + return torch.empty_strided( + (self.numel(), self.dim()), + (1, self.numel()), + dtype=torch.long, + device=self.device, + ) + + +@register_meta([aten.index.Tensor, aten._unsafe_index.Tensor]) +def meta_index_Tensor(self, indices): + torch._check(bool(indices), lambda: "at least one index must be provided") + # aten::index is the internal advanced indexing implementation + # checkIndexTensorTypes and expandTensors + result: list[Tensor | None] = [] + for i, index in enumerate(indices): + if index is not None: + torch._check( + index.dtype in [torch.long, torch.int, torch.int8, torch.bool], + lambda: "tensors used as indices must be long, int, byte or bool tensors", + ) + if index.dtype in [torch.int8, torch.bool]: + nonzero = index.nonzero() + k = len(result) + torch._check_index( + k + index.ndim <= self.ndim, + lambda: f"too many indices for tensor of dimension {self.ndim}", + ) + for j in range(index.ndim): + torch._check_index( + index.shape[j] == self.shape[k + j], + lambda: f"The shape of the mask {index.shape} at index {i} " + f"does not match the shape of the indexed tensor {self.shape} at index {k + j}", + ) + result.append(nonzero.select(1, j)) + else: + result.append(index) + else: + result.append(index) + indices = result + torch._check( + len(indices) <= self.ndim, + lambda: f"too many indices for tensor of dimension {self.ndim} (got {len(indices)})", + ) + # expand_outplace + import torch._refs as refs # avoid import cycle in mypy + + indices = list(refs._maybe_broadcast(*indices)) + # add missing null tensors + while len(indices) < self.ndim: + indices.append(None) + + # hasContiguousSubspace + # true if all non-null tensors are adjacent + # See: + # https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing + # https://stackoverflow.com/questions/53841497/why-does-numpy-mixed-basic-advanced-indexing-depend-on-slice-adjacency + state = 0 + has_contiguous_subspace = False + for index in indices: + if state == 0: + if index is not None: + state = 1 + elif state == 1: + if index is None: + state = 2 + else: + if index is not None: + break + else: + has_contiguous_subspace = True + + # transposeToFront + # This is the logic that causes the newly inserted dimensions to show up + # at the beginning of the tensor, if they're not contiguous + if not has_contiguous_subspace: + dims = [] + transposed_indices = [] + for i, index in enumerate(indices): + if index is not None: + dims.append(i) + transposed_indices.append(index) + for i, index in enumerate(indices): + if index is None: + dims.append(i) + transposed_indices.append(index) + self = self.permute(dims) + indices = transposed_indices + + # AdvancedIndex::AdvancedIndex + # Now we can assume the indices have contiguous subspace + # This is simplified from AdvancedIndex which goes to more effort + # to put the input and indices in a form so that TensorIterator can + # take them. If we write a ref for this, probably that logic should + # get implemented + before_shape: list[int] = [] + after_shape: list[int] = [] + replacement_shape: list[int] = [] + for dim, index in enumerate(indices): + if index is None: + if replacement_shape: + after_shape.append(self.shape[dim]) + else: + before_shape.append(self.shape[dim]) + else: + replacement_shape = list(index.shape) + + def _restride_src(self): + """ + This follows restride_src in TensorAdvancedIndexing.cpp + """ + shape = before_shape + replacement_shape + after_shape + strides = list(self.stride()) + # pyrefly: ignore [unsupported-operation] + strides[len(before_shape) : len(self.shape) - len(after_shape)] = [0] * len( + replacement_shape + ) + return self.as_strided(shape, strides) + + out = self.new_empty(before_shape + replacement_shape + after_shape) + + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(self.numel() == 0): + # No need to worry about the output strides if self is empty. + return out + + # Try to follow eager to decide the output stride based on self. + # Note that perm here is the reverse of the 'perm_' decided by + # TensorIteratorBase::reorder_dimensions + restrided_self = _restride_src(self) + perm, _ = utils.compute_elementwise_output_logical_to_physical_perm(restrided_self) + + # Follow TensorIteratorBase::allocate_or_resize_outputs + if list(perm) != list(range(len(perm))): + perm_shape = utils.apply_perm(out.shape, perm) + new_stride = utils.make_contiguous_strides_for(perm_shape) + new_stride = utils.apply_perm(new_stride, utils.invert_perm(perm)) + out = out.as_strided(out.size(), new_stride) + return out + + +@register_meta([aten.convolution_backward.default]) +def meta_convolution_backward( + grad_output_, + input_, + weight_, + bias_sizes_opt, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + output_mask, +): + # High level logic taken from slow_conv3d_backward_cpu which should + # be representative of all convolution_backward impls + backend_grad_input = None + backend_grad_weight = None + backend_grad_bias = None + + # All GPU backends compute output memory format via + # determine_backend_memory_format(input, weight, backend) — which calls + # cudnn_conv_suggest_memory_format(input, weight), mps_conv_use_channels_last(input, weight), + # etc. The format depends only on input and weight, NOT on grad_output. + # Both grad_input and grad_weight use this same backend_memory_format. + # See: https://github.com/pytorch/pytorch/issues/171622 + def _conv_memory_format(t1, t2): + fmt1 = suggest_memory_format(t1) + fmt2 = suggest_memory_format(t2) + if fmt1 == torch.channels_last or fmt2 == torch.channels_last: + return torch.channels_last + if fmt1 == torch.channels_last_3d or fmt2 == torch.channels_last_3d: + return torch.channels_last_3d + return torch.contiguous_format + + memory_format = _conv_memory_format(input_, weight_) + if output_mask[0]: + backend_grad_input = grad_output_.new_empty(input_.size()).to( + memory_format=memory_format + ) + if output_mask[1]: + backend_grad_weight = grad_output_.new_empty(weight_.size()).to( + memory_format=memory_format + ) + if output_mask[2]: + backend_grad_bias = grad_output_.new_empty(bias_sizes_opt) + + return (backend_grad_input, backend_grad_weight, backend_grad_bias) + + +@register_meta([aten.addbmm.default, aten.addbmm.out]) +@out_wrapper(exact_dtype=True) +def meta_addbmm(self, batch1, batch2, *, beta=1, alpha=1): + dim1 = batch1.size(1) + dim2 = batch2.size(2) + self = self.expand((dim1, dim2)) + torch._check(batch1.dim() == 3, lambda: "batch1 must be a 3D tensor") + torch._check(batch2.dim() == 3, lambda: "batch2 must be a 3D tensor") + torch._check( + batch1.size(0) == batch2.size(0), + lambda: f"batch1 and batch2 must have same number of batches, got {batch1.size(0)} and {batch2.size(0)}", + ) + torch._check( + batch1.size(2) == batch2.size(1), + lambda: ( + f"Incompatible matrix sizes for bmm ({batch1.size(1)}x{batch1.size(2)} " + f"and {batch2.size(1)}x{batch2.size(2)})" + ), + ) + torch._check( + self.size(0) == dim1 and self.size(1) == dim2, + lambda: "self tensor does not match matmul output shape", + ) + return self.new_empty(self.size()) + + +@register_meta([aten.randint_like.Tensor]) +def meta_randint_like(self, high, **kwargs): + return aten.empty_like.default( + self, + dtype=kwargs.get("dtype"), + layout=kwargs.get("layout"), + device=kwargs.get("device"), + pin_memory=kwargs.get("pin_memory"), + memory_format=kwargs.get("memory_format"), + ) + + +@register_meta([aten._fused_adam_.default, aten._fused_adamw_.default]) +def meta__fused_adam_( + self, + grads, + exp_avgs, + exp_avg_sqs, + max_exp_avg_sqs, + state_steps, + *, + lr, + beta1, + beta2, + weight_decay, + eps, + amsgrad, + maximize, + grad_scale=None, + found_inf=None, +): + for l in [self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps]: + torch._check( + isinstance(l, list), + lambda: f"exponent must be a tensor list but got {type(l)}", + ) + + +@register_meta([aten._fused_adam.default]) +def meta__fused_adam( + self, + grads, + exp_avgs, + exp_avg_sqs, + max_exp_avg_sqs, + state_steps, + *, + lr, + beta1, + beta2, + weight_decay, + eps, + amsgrad, + maximize, + grad_scale=None, + found_inf=None, +): + for l in [self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps]: + torch._check( + isinstance(l, list), + lambda: f"exponent must be a tensor list but got {type(l)}", + ) + + def empty_like_list(tensor_list): + return [torch.empty_like(t) for t in tensor_list] + + return ( + empty_like_list(self), + empty_like_list(grads), + empty_like_list(exp_avgs), + empty_like_list(exp_avg_sqs), + empty_like_list(max_exp_avg_sqs), + ) + + +@register_meta([aten._int_mm]) +@out_wrapper() +def meta__int_mm(a, b): + torch._check(a.dim() == 2, lambda: "a must be a 2D tensor") + torch._check(b.dim() == 2, lambda: "b must be a 2D tensor") + torch._check( + a.dtype in [torch.int8, torch.uint8], + lambda: f"expected self to be int8 or uint8, got {a.dtype}", + ) + torch._check( + b.dtype is torch.int8, + lambda: f"expected mat2 to be int8, got {b.dtype}", + ) + torch._check( + a.size(1) == b.size(0), + lambda: ( + f"Incompatible matrix sizes for _int_mm ({a.size(0)}x{a.size(1)} " + f"and {b.size(0)}x{b.size(1)})" + ), + ) + return a.new_empty((a.size(0), b.size(1)), dtype=torch.int32) + + +@register_meta([aten._convert_weight_to_int4pack]) +def meta__convert_weight_to_int4pack(w, inner_k_tiles): + torch._check(w.dim() == 2, lambda: "w must be a 2D tensor") + torch._check( + w.dtype is torch.uint8, + lambda: f"expected w to be uint8, got {w.dtype}", + ) + n = w.size(0) + k = w.size(1) * 2 # w is [n][k / 2] uint8 + return w.new_empty( + ( + n // 8, + k // (inner_k_tiles * 16), + 32, + inner_k_tiles // 2, + ), + dtype=torch.int32, + ) + + +@register_meta([aten._convert_weight_to_int4pack_for_cpu]) +def meta__convert_weight_to_int4pack_for_cpu(w, inner_k_tiles): + torch._check(w.dim() == 2, lambda: "w must be a 2D tensor") + torch._check( + w.dtype is torch.int32, + lambda: f"expected w to be int32, got {w.dtype}", + ) + n = w.size(0) + k = w.size(1) # w is [n][k] int32 + return w.new_empty( + (n, k // 2), + dtype=torch.uint8, + ) + + +@register_meta([aten._weight_int4pack_mm]) +def meta__weight_int4pack_mm(x, w, q_group_size, q_scale_and_zeros): + torch._check(x.dim() == 2, lambda: "x must be a 2D tensor") + expected_dim = 2 if w.fake_device.type == "xpu" else 4 + torch._check(w.dim() == expected_dim, lambda: f"w must be a {expected_dim}D tensor") + torch._check( + x.dtype in [torch.float32, torch.float16, torch.bfloat16], + lambda: f"expected x to be f32/f16/bf16, got {x.dtype}", + ) + torch._check( + w.dtype is torch.int32, + lambda: f"expected w to be int32, got {w.dtype}", + ) + dim_n = w.size(0) if w.fake_device.type == "xpu" else w.size(0) * 8 + return x.new_empty(x.size(0), dim_n, dtype=x.dtype) + + +@register_meta([aten._weight_int4pack_mm_for_cpu]) +def meta__weight_int4pack_mm_for_cpu(x, w, q_group_size, q_scale_and_zeros): + torch._check(x.dim() == 2, lambda: "x must be a 2D tensor") + torch._check(w.dim() == 2, lambda: "w must be a 2D tensor") + torch._check( + x.dtype in [torch.float32, torch.float16, torch.bfloat16], + lambda: f"expected x to be f32/f16/bf16, got {x.dtype}", + ) + torch._check( + w.dtype is torch.uint8, + lambda: f"expected w to be uint8, got {w.dtype}", + ) + return x.new_empty(x.size(0), w.size(0), dtype=x.dtype) + + +@register_meta([aten._weight_int4pack_mm_with_scales_and_zeros]) +def _weight_int4pack_mm_with_scales_and_zeros(x, w, q_group_size, qScale, qZeros): + torch._check(x.dim() == 2, lambda: "x must be a 2D tensor") + torch._check(w.dim() == 2, lambda: "w must be a 2D tensor") + torch._check( + x.dtype in [torch.float32, torch.float16, torch.bfloat16], + lambda: f"expected x to be f32/f16/bf16, got {x.dtype}", + ) + torch._check( + w.dtype is torch.int32, + lambda: f"expected w to be int32, got {w.dtype}", + ) + return x.new_empty(x.size(0), w.size(0), dtype=x.dtype) + + +def kai_roundup(a: int, b: int) -> int: + return ((a + b - 1) // b) * b + + +def get_kai_packed_weight_size(n_bits, N, K, groupsize): + if n_bits == 4: + # Works for both fp32 and bf16 Kernels + if groupsize == K: # channelwise + # dotprod params only [1x8x32_neon_dotprod] + kai_nr = 8 + kai_kr = 16 + kai_sr = 2 + kai_num_bytes_sum_rhs = 4 # sizeof(int32_t) + kai_num_bytes_multiplier_rhs = 4 # sizeof(float) + kai_num_bytes_bias = 4 # sizeof(float) + + def kai_k_roundedup(k, kr, sr): + # Since we pack a float and int32 value at the end of the row, + # we must make sure that k is a multiple of 4 for alignment + kr_sr_roundedup4 = kai_roundup(kr * sr, 4) + return kai_roundup(k, kr_sr_roundedup4) + + def kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0( + k, nr, kr, sr + ): + k_internal = kai_k_roundedup(k, kr, sr) + + if (k_internal % 2) != 0: + raise AssertionError(f"k_internal must be even, got {k_internal}") + + return nr * ( + (k_internal // 2) + + kai_num_bytes_multiplier_rhs + + kai_num_bytes_sum_rhs + + kai_num_bytes_bias + ) + + def kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0( + n, k, nr, kr, sr + ): + num_rows = kai_roundup(n, nr) // nr + + return ( + num_rows + * kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0( + k, nr, kr, sr + ) + ) + + return kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0( + N, K, kai_nr, kai_kr, kai_sr + ) + elif groupsize % 32 == 0 and K % groupsize == 0: # groupwise + kai_nr = 8 + kai_kr = 16 + kai_sr = 2 + kai_num_bytes_sum_rhs = 4 + kai_num_bytes_bias = 4 + kai_nr_multiple_of = 4 + kai_bl_multiple_of = 32 + + def kai_get_rhs_packed_size_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0( + n, k, nr, kr, sr, bl + ): + if (bl % kr) != 0: + raise AssertionError(f"bl ({bl}) must be divisible by kr ({kr})") + if (nr % kai_nr_multiple_of) != 0: + raise AssertionError( + f"nr ({nr}) must be divisible by kai_nr_multiple_of ({kai_nr_multiple_of})" + ) + if (bl % kai_bl_multiple_of) != 0: + raise AssertionError( + f"bl ({bl}) must be divisible by kai_bl_multiple_of ({kai_bl_multiple_of})" + ) + + num_rows = kai_roundup(n, nr) // nr + + return ( + num_rows + * kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0( + k, nr, kr, sr, bl + ) + ) + + def kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0( + k, nr, kr, sr, bl + ): + if (bl % kr) != 0: + raise AssertionError(f"bl ({bl}) must be divisible by kr ({kr})") + if (nr % kai_nr_multiple_of) != 0: + raise AssertionError( + f"nr ({nr}) must be divisible by kai_nr_multiple_of ({kai_nr_multiple_of})" + ) + if (bl % kai_bl_multiple_of) != 0: + raise AssertionError( + f"bl ({bl}) must be divisible by kai_bl_multiple_of ({kai_bl_multiple_of})" + ) + + # kr and sr are unused in the calculation + num_bytes_multiplier_rhs = kai_get_bf16_datatype_size_in_bytes() + num_blocks_per_row = kai_num_blocks_per_row(k, bl) + num_bytes_per_block = kai_num_bytes_per_block( + bl, num_bytes_multiplier_rhs + ) + + return nr * ( + (num_bytes_per_block * num_blocks_per_row) + + kai_num_bytes_sum_rhs + + kai_num_bytes_bias + ) + + # This function returns size of these datatypes stored as enum. We modify it to just return bf16 datatype + # https://gitlab.arm.com/kleidi/kleidiai/-/blob/main/kai/kai_common.h?ref_type=heads#L55 + def kai_get_bf16_datatype_size_in_bytes(): + return 2 # 2 bytes + + def kai_num_blocks_per_row(k, bl): + if (bl % kai_bl_multiple_of) != 0: + raise AssertionError( + f"bl ({bl}) must be divisible by kai_bl_multiple_of ({kai_bl_multiple_of})" + ) + return kai_roundup(k, bl) // bl + + def kai_num_bytes_per_block(bl, num_bytes_multiplier_rhs): + if (bl % kai_bl_multiple_of) != 0: + raise AssertionError( + f"bl ({bl}) must be divisible by kai_bl_multiple_of ({kai_bl_multiple_of})" + ) + return (bl // 2) + num_bytes_multiplier_rhs + + return kai_get_rhs_packed_size_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0( + N, K, kai_nr, kai_kr, kai_sr, groupsize + ) + + +@register_meta([aten._dyn_quant_pack_4bit_weight]) +def meta__dyn_quant_pack_4bit_weight( + weights, scales_zeros, bias: Tensor | None, block_size, in_features, out_features +): + torch._check( + weights.dtype is torch.uint8, + lambda: f"expected w to be uint8, got {weights.dtype}", + ) + if torch.backends.kleidiai.is_available() and ( + (block_size == in_features and scales_zeros.dtype == torch.float) + or ( + block_size < in_features + and block_size % 32 == 0 + and in_features % block_size == 0 + and scales_zeros.dtype == torch.bfloat16 + ) + ): + packed_weight_size = get_kai_packed_weight_size( + 4, out_features, in_features, block_size + ) + return weights.new_empty(int(packed_weight_size), dtype=torch.uint8) + packed_weight_size = weights.numel() + scales_zeros.numel() + if bias is not None: + packed_weight_size += bias.numel() + return weights.new_empty(packed_weight_size, dtype=torch.float) + + +@register_meta([aten._dyn_quant_matmul_4bit]) +def meta__dyn_quant_matmul_4bit( + inp, + packed_weights, + block_size, + in_features, + out_features, +): + torch._check(inp.dim() == 2, lambda: "input must be a 2D tensor") + torch._check( + (inp.dtype == torch.float32) + or (inp.dtype == torch.bfloat16 and block_size == in_features), + lambda: ( + f"expected input to be f32 or bf16 (bf16 requires block_size == in_features), " + f"got {inp.dtype} with block_size={block_size} and in_features={in_features}" + ), + ) + M = inp.size(0) + return inp.new_empty(M, out_features, dtype=inp.dtype) + + +@register_meta([aten._weight_int8pack_mm]) +def meta__weight_int8pack_mm(x, w, q_scales): + torch._check(x.dim() == 2, lambda: "x must be a 2D tensor") + torch._check( + x.dtype in [torch.float32, torch.float16, torch.bfloat16], + lambda: f"expected x to be f32/f16/bf16, got {x.dtype}", + ) + torch._check(w.dim() == 2, lambda: "w must be a 2D tensor") + torch._check( + w.dtype is torch.int8, + lambda: f"expected w to be int8, got {w.dtype}", + ) + torch._check( + w.size(1) == x.size(1), + lambda: f"expected w.size(1) ({w.size(1)}) == x.size(1) ({x.size(1)})", + ) + torch._check( + q_scales.dim() == 1 and q_scales.size(0) == w.size(0), + lambda: f"expected q_scales to be 1D with size {w.size(0)}, got shape {q_scales.shape}", + ) + return x.new_empty(x.size(0), w.size(0), dtype=x.dtype) + + +@register_meta(aten._cdist_forward.default) +def meta_cdist_forward(x1, x2, p, compute_mode): + torch._check( + x1.dim() >= 2, + lambda: f"cdist only supports at least 2D tensors, X1 got: {x1.dim()}D", + ) + torch._check( + x2.dim() >= 2, + lambda: f"cdist only supports at least 2D tensors, X2 got: {x2.dim()}D", + ) + torch._check( + x1.size(-1) == x2.size(-1), + lambda: f"X1 and X2 must have the same number of columns. X1: {x1.size(-1)} X2: {x2.size(-1)}", + ) + torch._check( + utils.is_float_dtype(x1.dtype), + lambda: f"cdist only supports floating-point dtypes, X1 got: {x1.dtype}", + ) + torch._check( + utils.is_float_dtype(x2.dtype), + lambda: f"cdist only supports floating-point dtypes, X2 got: {x2.dtype}", + ) + torch._check(p >= 0, lambda: "cdist only supports non-negative p values") + torch._check( + compute_mode in (None, 0, 1, 2), + lambda: f"possible modes: None, 0, 1, 2, but was: {compute_mode}", + ) + r1 = x1.size(-2) + r2 = x2.size(-2) + batch_tensor1 = x1.shape[:-2] + batch_tensor2 = x2.shape[:-2] + output_shape = list(torch.broadcast_shapes(batch_tensor1, batch_tensor2)) + output_shape.extend([r1, r2]) + return x1.new_empty(output_shape) + + +@register_meta(aten._cdist_backward) +@out_wrapper() +def meta_cdist_backward(grad_output, x1, x2, p, cdist): + c1 = x1.shape[-1] + r1 = x1.shape[-2] + r2 = x2.shape[-2] + batch_tensor1 = x1.shape[:-2] + batch_tensor2 = x2.shape[:-2] + expand_batch_portion = list(torch.broadcast_shapes(batch_tensor1, batch_tensor2)) + tensor1_expand_size = expand_batch_portion.copy() + tensor1_expand_size.extend([r1, c1]) + batch_product = math.prod(expand_batch_portion) + if r1 == 0 or r2 == 0 or c1 == 0 or batch_product == 0: + return torch.zeros_like(x1) + if tensor1_expand_size != list(x1.shape): + x1 = x1.expand(tensor1_expand_size) + return torch.empty_like(x1, memory_format=torch.contiguous_format) + + +# NB: This meta function accepts non-meta arguments! When this behavior +# was originally introduced this was accidental, but it is now load bearing +# as people are using this so that they can conveniently test code involving +# embeddings (feeding CPU tensor inputs with meta device EmbeddingBag module) +@register_meta(aten._embedding_bag.default) +def meta_embedding_bag( + weight, + indices, + offsets, + scale_grad_by_freq=False, + mode=0, + sparse=False, + per_sample_weights=None, + include_last_offset=False, + padding_idx=-1, +): + torch._check( + indices.dtype in (torch.long, torch.int), + lambda: f"expected indices to be long or int, got {indices.dtype}", + ) + torch._check( + offsets.dtype in (torch.long, torch.int), + lambda: f"expected offsets to be long or int, got {offsets.dtype}", + ) + torch._check( + utils.is_float_dtype(weight.dtype), + lambda: f"expected weight to be floating point type, got {weight.dtype}", + ) + + num_bags = offsets.size(0) + if include_last_offset: + torch._check( + num_bags >= 1, + lambda: "include_last_offset: numBags should be at least 1", + ) + num_bags -= 1 + + output = weight.new_empty(num_bags, weight.size(1)) + + if per_sample_weights is not None: + torch._check( + mode == MODE_SUM, + lambda: "embedding_bag: per_sample_weights only supported with mode='sum'", + ) + torch._check( + per_sample_weights.ndim == 1, + lambda: f"expected per_sample_weights to be 1D tensor, got {per_sample_weights.ndim}D", + ) + torch._check( + per_sample_weights.numel() == indices.numel(), + lambda: ( + f"expected per_sample_weights.numel() ({per_sample_weights.numel()} " + f"to be the same as indices.numel() ({indices.numel()})" + ), + ) + + def is_fast_path_index_select_scale(src, scale, output, padding_idx): + return ( + is_fast_path_index_select(src, output, padding_idx) and scale.stride(0) == 1 + ) + + def is_fast_path_index_select(src, output, padding_idx): + return ( + (src.dtype == torch.float or src.dtype == torch.half) + and src.stride(1) == 1 + and output.stride(1) == 1 + and padding_idx < 0 + ) + + def is_fast_path(src, scale, output, padding_idx): + if scale is not None: + return is_fast_path_index_select_scale(src, scale, output, padding_idx) + else: + return is_fast_path_index_select(src, output, padding_idx) + + if device_hint(offsets) != "cpu": + offset2bag = indices.new_empty(indices.size(0)) + bag_size = indices.new_empty(offsets.size()) + if mode == MODE_MAX: + max_indices = indices.new_empty(num_bags, weight.size(1)) + else: + max_indices = indices.new_empty(0) + else: + fast_path_sum = is_fast_path(weight, per_sample_weights, output, padding_idx) + if mode in (MODE_MEAN, MODE_MAX) or not fast_path_sum: + offset2bag = offsets.new_empty(indices.size(0)) + else: + offset2bag = offsets.new_empty(0) + bag_size = offsets.new_empty(num_bags) + # This part of the logic comes from make_max_indices_out in EmbeddingBag.cpp + numBags = offsets.shape[0] + if mode == MODE_MAX: + if include_last_offset: + torch._check( + numBags >= 1, + lambda: "include_last_offset: numBags should be at least 1", + ) + numBags -= 1 + max_indices = offsets.new_empty(numBags, weight.shape[1]) + else: + max_indices = offsets.new_empty(bag_size.size()) + return output, offset2bag, bag_size, max_indices + + +@register_meta(aten._embedding_bag_forward_only.default) +def meta_embedding_bag_forward_only(weight, indices, offsets, *args): + output, offset2bag, bag_size, max_indices = meta_embedding_bag( + weight, indices, offsets, *args + ) + if device_hint(offsets) == "cpu": + bag_size = offsets.new_empty(offsets.size()) + return output, offset2bag, bag_size, max_indices + + +def _get_reduction_dtype(input, dtype, promote_int_to_long=True): + # if specified, dtype takes precedence + if dtype: + return dtype + + if input.dtype.is_floating_point or input.dtype.is_complex: + return input.dtype + elif promote_int_to_long: + return torch.long + + return input.dtype + + +@register_meta([aten.nansum.default, aten.nansum.out]) +@out_wrapper() +def meta_nansum(input, dims=None, keepdim=False, *, dtype=None): + output_dtype = _get_reduction_dtype(input, dtype, promote_int_to_long=True) + # reduces over all dimensions if dims=() is passed + if dims == () or dims == []: + dims = None + dims = utils.reduction_dims(input.shape, dims) + output_shape = _compute_reduction_shape(input, dims, keepdim) + return input.new_empty(output_shape, dtype=output_dtype) + + +@register_meta([aten.median.default, aten.nanmedian.default]) +def meta_median(input): + output_shape = utils.compute_reduction_output_shape( + input.shape, tuple(range(input.dim())) + ) + return input.new_empty(output_shape) + + +@register_meta( + [ + aten.median.dim, + aten.median.dim_values, + aten.nanmedian.dim, + aten.nanmedian.dim_values, + aten.mode.default, + aten.mode.values, + ] +) +@out_wrapper("values", "indices") +def meta_median_mode_dim(input, dim=-1, keepdim=False): + if device_hint(input) == "cuda": + utils.alert_not_deterministic("median CUDA with indices output") + dim = utils.reduction_dims(input.shape, (dim,)) + output_shape = _compute_reduction_shape(input, dim, keepdim) + return ( + input.new_empty(output_shape), + input.new_empty(output_shape, dtype=torch.long), + ) + + +@register_meta(aten.logical_not_.default) +def meta_logical_not_(self): + return self + + +@register_meta(aten.repeat.default) +def meta_repeat(self, repeats): + torch._check( + len(repeats) >= self.dim(), + lambda: "Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor", + ) + for i, rep in enumerate(repeats): + torch._check( + rep >= 0, + lambda: f"Repeats cannot be negative, found {rep} at index {i}", + ) + # Add new leading dimensions to the tensor if the + # number of target dimensions is larger than the + # number of source dimensions. + num_new_dimensions = len(repeats) - self.dim() + padded_size = (1,) * num_new_dimensions + tuple(self.shape) + target_size = [padded_size[i] * repeats[i] for i in range(len(repeats))] + return self.new_empty(target_size) + + +@register_meta(aten.zero_.default) +def meta_zero_(self): + return self + + +@register_meta( + [ + aten.mul_.Scalar, + aten.mul_.Tensor, + aten.logical_and_.default, + aten.logical_or_.default, + aten.logical_xor_.default, + ], +) +def meta_binop_inplace(self, other): + if isinstance(other, torch.Tensor): + check_inplace_broadcast(self.shape, other.shape) + return self + + +@register_meta([aten.div_.Scalar, aten.div_.Tensor]) +def meta_div_inplace(self, other): + _, result_dtype = elementwise_dtypes( + self, + other, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + torch._check( + utils.can_safe_cast_to(cast_from=result_dtype, cast_to=self.dtype), + lambda: ( + f"result type {result_dtype} can't be cast to the desired " + f"output type {self.dtype}" + ), + ) + + if isinstance(other, torch.Tensor): + check_inplace_broadcast(self.shape, other.shape) + return self + + +@register_meta( + [ + aten.add_.Scalar, + aten.sub_.Scalar, + aten.add_.Tensor, + aten.sub_.Tensor, + ], +) +def meta_binop_inplace_alpha(self, other, alpha=1): + """ + Some checks for inplace ops. + Checks for promotion rules for some dtypes. + int.add/sub_(float) and bool.add/sub_(others) are rejected. + Promoting in these in-place operations would require reallocating + and copying over elements, hence not allowed. + Checks for alpha param. + """ + + def is_integeric(arg): + if isinstance(arg, TensorLike): + return utils.is_integer_dtype(arg.dtype) + else: + return isinstance(arg, IntLike) + + def is_floatic(arg): + if isinstance(arg, TensorLike): + return utils.is_float_dtype(arg.dtype) + else: + return isinstance(arg, FloatLike) + + def is_booleanic(arg): + if isinstance(arg, TensorLike): + return utils.is_boolean_dtype(arg.dtype) + else: + return isinstance(arg, BoolLike) + + # Do not allow int+float->int in-place + if is_integeric(self) and is_floatic(other): + raise RuntimeError( + "Promotion of int.add/sub_(float) in in-place ops are not possible due to element size change." + ) + + # Do not allow bool+other->bool in-place + if is_booleanic(self) and not is_booleanic(other): + raise RuntimeError( + "Promotion of bool.add/sub_(others) in in-place ops are not possible due to element size change." + ) + + if isinstance(other, torch.Tensor): + check_inplace_broadcast(self.shape, other.shape) + return self + + +@register_meta( + [ + aten.add.Scalar, + aten.sub.Scalar, + ], +) +def meta_binop_alpha(self, other, alpha=1): + return elementwise_meta( + self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +@register_meta([aten.round.default, aten.round.decimals]) +def meta_round(self, **kwargs): + return elementwise_meta( + self, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +def shift_dtype_check(fn_name, self, val): + torch._check( + utils.is_integer_dtype(self.dtype), + lambda: f"{fn_name}: Expected input tensor to have an integral dtype. Got {self.dtype}", + ) + if isinstance(val, torch.Tensor): + torch._check( + utils.is_integer_dtype(val.dtype), + lambda: f"{fn_name}: Expected shift value to have an integral dtype. Got {val.dtype}", + ) + else: + torch._check( + isinstance(val, IntLike), + lambda: f"{fn_name}: Expected shift value to be an int. Got {val}", + ) + + +@register_meta([aten.__rshift__.Tensor, aten.__rshift__.Scalar]) +def meta_rshifts(self, other): + shift_dtype_check("rshift", self, other) + return elementwise_meta( + self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +@register_meta([aten.__lshift__.Tensor, aten.__lshift__.Scalar]) +def meta_lshifts(self, other): + shift_dtype_check("lshift", self, other) + return elementwise_meta( + self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +@register_meta(aten.zero.default) +def meta_zero(self): + return torch.empty_like(self) + + +@register_meta([aten.fill_.Tensor, aten.fill_.Scalar]) +def meta_fill_(self, val): + if isinstance(val, torch.Tensor): + torch._check( + val.dim() == 0, + lambda: f"fill_ only supports 0-dimension value tensor but got tensor with {val.dim()} dimensions.", + ) + return self + + +@register_meta([aten.fill.Tensor, aten.fill.Scalar]) +def meta_fill(self, val): + if isinstance(val, torch.Tensor): + torch._check( + val.dim() == 0, + lambda: f"fill_ only supports 0-dimension value tensor but got tensor with {val.dim()} dimensions.", + ) + return torch.empty_like(self) + + +@register_meta(aten.relu_.default) +def meta_relu_(self): + return self + + +@register_meta(aten._add_relu.Tensor) +@out_wrapper() +def meta__add_relu(self, other, alpha=1) -> Tensor: + return elementwise_meta( + self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +@register_meta([aten.rrelu_with_noise]) +@out_wrapper() +def meta_rrelu_with_noise( + self, noise, lower=0.125, upper=0.3333333333333333, training=False, generator=None +): + return torch.empty_like(self) + + +@register_meta([aten.rrelu_with_noise_functional]) +def meta_rrelu_with_noise_functional( + self, noise, lower=0.125, upper=0.3333333333333333, training=False, generator=None +): + return torch.empty_like(self), torch.empty_like(noise) + + +@register_meta([aten.rrelu_with_noise_]) +def meta_rrelu_with_noise_( + self, lower=0.125, upper=0.3333333333333333, training=False, generator=None +): + return self + + +@register_meta([aten.index_put.default, aten._unsafe_index_put.default]) +def meta_index_put(self, indices, values, accumulate=False): + return torch.empty_like(self) + + +@register_meta(aten.masked_fill_.Scalar) +def meta_masked_fill_(self, mask, value): + check_inplace_broadcast(self.shape, mask.shape) + return self + + +@register_meta(aten._masked_scale.default) +def meta__masked_scale(self, mask, scale): + masked_scale = self.new_empty(self.size()).to( + memory_format=utils.suggest_memory_format(self) + ) + return masked_scale + + +@register_meta(aten.masked_scatter_) +def meta_masked_scatter_(self, mask, source): + torch._check( + mask.dtype in (torch.bool, torch.uint8), lambda: "Mask must be bool or uint8" + ) + torch._check( + self.dtype == source.dtype, + lambda: "masked_scatter: expected self and source to have same " + f"dtypes but got {self.dtype} and {source.dtype}", + ) + return self + + +@register_meta(aten.masked_scatter) +@out_wrapper() +def meta_masked_scatter(self, mask, source): + self, mask = _maybe_broadcast(self, mask) + output = torch.empty_like(self, memory_format=torch.contiguous_format) + return meta_masked_scatter_(output, mask, source) + + +@register_meta(aten.masked_scatter_backward) +def meta_masked_scatter_backward(self, mask, sizes): + return self.new_empty(sizes) + + +@register_meta(aten.index_put_.default) +def meta_index_put_(self, indices, values, accumulate=False): + return self + + +def common_meta_baddbmm_bmm(batch1, batch2, is_bmm, self_baddbmm=None, out_dtype=None): + from torch.fx.experimental.symbolic_shapes import sym_and, sym_eq + + torch._check(batch1.dim() == 3, lambda: "batch1 must be a 3D tensor") + torch._check(batch2.dim() == 3, lambda: "batch2 must be a 3D tensor") + torch._check( + batch1.dtype == batch2.dtype, + lambda: f"expected scalar type {batch1.dtype} but found {batch2.dtype}", + ) + + batch1_sizes = batch1.size() + batch2_sizes = batch2.size() + + bs = batch1_sizes[0] + contraction_size = batch1_sizes[2] + res_rows = batch1_sizes[1] + res_cols = batch2_sizes[2] + output_size = (bs, res_rows, res_cols) + + torch._check( + sym_and(sym_eq(batch2_sizes[0], bs), sym_eq(batch2_sizes[1], contraction_size)), + lambda: f"Expected size for first two dimensions of batch2 tensor to be: [{bs}" + f", {contraction_size}] but got: [{batch2_sizes[0]}, {batch2_sizes[1]}].", + ) + if out_dtype: + # The out_dtype restriction below is a property of the in-tree CUDA/XPU + # backends (see aten/src/ATen/native/cuda/Blas.cpp and + # aten/src/ATen/native/mkldnn/xpu/Blas.cpp). Out-of-tree backends (e.g. + # accelerators registered via PrivateUse1) may support arbitrary + # out_dtype combinations, so only enforce it for the backends that have + # the restriction. + if device_hint(batch1) in ("cuda", "xpu"): + supported_out_dtype = ( + batch1.dtype == torch.float16 or batch1.dtype == torch.bfloat16 + ) and out_dtype == torch.float32 + torch._check( + out_dtype == batch1.dtype or supported_out_dtype, + lambda: "out_dtype only supported for torch.float32 output with float16/bfloat16 inputs or same as input dtypes", + ) + output = batch2.new_empty(output_size).to(out_dtype) + else: + # TODO: handle out + output = batch2.new_empty(output_size) + + if not is_bmm and self_baddbmm is not None: + torch._check(self_baddbmm.dim() == 3, lambda: "self must be a 3D tensor") + torch._check( + sym_eq(self_baddbmm.size(), output_size), + lambda: f"Expected an input tensor shape with shape {output_size} but got shape: {self_baddbmm.size()}", + ) + + return output + + +@register_meta([aten.bmm.default, aten.bmm.out]) +@out_wrapper(exact_dtype=True) +def meta_bmm(self, mat2): + return common_meta_baddbmm_bmm(self, mat2, True) + + +@register_meta([aten.bmm.dtype, aten.bmm.dtype_out]) +@out_wrapper(exact_dtype=True) +def meta_bmm_dtype(self, mat2, out_dtype): + return common_meta_baddbmm_bmm(self, mat2, True, out_dtype=out_dtype) + + +def div_rtn(x, y): + # Python // already floors toward negative infinity, so the + # remainder-sign adjustment from the original C++ port is unnecessary. + return x // y + + +def pooling_output_shape_pad_lr( + inputSize, + kernelSize, + pad_l, + pad_r, + stride, + dilation, + ceil_mode, +): + outputSize = ( + div_rtn( + inputSize + + pad_l + + pad_r + - dilation * (kernelSize - 1) + - 1 + + (stride - 1 if ceil_mode else 0), + stride, + ) + + 1 + ) + if ceil_mode: + if (outputSize - 1) * stride >= inputSize + pad_l: + outputSize -= 1 + return outputSize + + +def pooling_output_shape(inputSize, kernelSize, pad, stride, dilation, ceil_mode): + torch._check(stride != 0, lambda: "stride should not be zero") + torch._check(pad >= 0, lambda: f"pad must be non-negative, but got pad: {pad}") + torch._check( + pad <= ((kernelSize - 1) * dilation + 1) // 2, + lambda: ( + f"pad should be at most half of effective kernel size, but got pad={pad}, " + f"kernel_size={kernelSize} and dilation={dilation}" + ), + ) + return pooling_output_shape_pad_lr( + inputSize, kernelSize, pad, pad, stride, dilation, ceil_mode + ) + + +def pool2d_shape_check( + input, + kH, + kW, + dH, + dW, + padH, + padW, + dilationH, + dilationW, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + memory_format, +): + from torch.fx.experimental.symbolic_shapes import sym_and, sym_or + + ndim = input.dim() + nOutputPlane = nInputPlane + + torch._check( + kW > 0 and kH > 0, + lambda: f"kernel size should be greater than zero, but got kH: {kH}, kW: {kW}", + ) + torch._check( + dW > 0 and dH > 0, + lambda: f"stride should be greater than zero, but got dH: {dH}, dW: {dW}", + ) + torch._check( + dilationH > 0 and dilationW > 0, + lambda: f"dilation should be greater than zero, but got dilationH: {dilationH}, dilationW: {dilationW}", + ) + + valid_dims = sym_and(input.size(1) != 0, input.size(2) != 0) + + if memory_format == torch.channels_last: + torch._check( + ndim == 4 and sym_and(valid_dims, input.size(3) != 0), + lambda: "Expected 4D (batch mode) tensor expected for input with channels_last layout" + f" with optional 0 dim batch size for input, but got: {input.size()}", + ) + else: + torch._check( + sym_or( + ndim == 3 and sym_and(input.size(0) != 0, valid_dims), + ndim == 4 and sym_and(valid_dims, input.size(3) != 0), + ), + lambda: f"Expected 3D or 4D (batch mode) tensor with optional 0 dim batch size for input, but got: {input.size()}", + ) + + torch._check( + sym_and(kW // 2 >= padW, kH // 2 >= padH), + lambda: "pad should be smaller than or equal to half of kernel size, but got " + f"padW = {padW}, padH = {padH}, kW = {kW}, kH = {kH}", + ) + + torch._check( + sym_and(outputWidth >= 1, outputHeight >= 1), + lambda: f"Given input size: ({nInputPlane}x{inputHeight}x{inputWidth}). " + f"Calculated output size: ({nOutputPlane}x{outputHeight}x{outputWidth}). " + "Output size is too small", + ) + + +def pool3d_shape_check( + input: Tensor, + nslices: int, + kT: int, + kH: int, + kW: int, + dT: int, + dH: int, + dW: int, + pT: int, + pH: int, + pW: int, + dilationT: int, + dilationH: int, + dilationW: int, + itime: int, + iheight: int, + iwidth: int, + otime: int, + oheight: int, + owidth: int, + fn_name: str, + check_input_size: bool = False, +): + ndim = input.ndim + + torch._check( + kT > 0 and kW > 0 and kH > 0, + lambda: ( + f"kernel size should be greater than zero, but got " + f"kT: {kT}, kH: {kH}, kW: {kW}" + ), + ) + torch._check( + dT > 0 and dW > 0 and dH > 0, + lambda: ( + f"stride should be greater than zero, but got dT: {dT}, dH: {dH}, dW: {dW}" + ), + ) + torch._check( + dilationT > 0 and dilationW > 0 and dilationH > 0, + lambda: ( + f"dilation should be greater than zero, but got " + f"dilationT: {dilationT}, dilationH: {dilationH}, dilationW: {dilationW}" + ), + ) + + torch._check( + ndim in (4, 5), + lambda: f"{fn_name}: Expected 4D or 5D tensor for input, but got: {input.shape}", + ) + + for i in range(ndim): + if ndim == 5 and i == 0: + # size of batch-dim can be 0. + continue + torch._check( + input.size(i) > 0, + lambda: ( + f"{fn_name}: Expected input's non-batch dimensions to have positive length," + f" but input has a shape of {input.shape}" + f" and non-batch dimension {input.size(i)} has length zero!" + ), + ) + + from torch.fx.experimental.symbolic_shapes import sym_and + + if check_input_size: # AveragePool3d + torch._check( + sym_and(itime >= kT, iheight >= kH, iwidth >= kW), + lambda: ( + f"input image (T: {itime} H: {iheight} W: {iwidth}) smaller than " + f"kernel size (kT: {kT} kH: {kH} kW: {kW})" + ), + ) + + torch._check( + sym_and(kT / 2 >= pT, kW / 2 >= pW, kH / 2 >= pH), + lambda: ( + f"pad should be smaller than or equal to half of kernel size, but got " + f"kT: {kT} kW: {kW} kH: {kH} padT: {pT} padW: {pW} padH: {pH}" + ), + ) + + torch._check( + sym_and(otime >= 1, owidth >= 1, oheight >= 1), + lambda: ( + f"Given input size: ({nslices}x{itime}x{iheight}x{iwidth}). " + f"Calculated output size: ({nslices}x{otime}x{oheight}x{owidth}). " + f"Output size is too small" + ), + ) + + +def max_pool3d_backward_shape_check( + input, + grad_output, + indices, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + pT, + pH, + pW, + dilationT, + dilationH, + dilationW, + itime, + iheight, + iwidth, + otime, + oheight, + owidth, + fn_name, +): + ndim = input.ndim + + pool3d_shape_check( + input, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + pT, + pH, + pW, + dilationT, + dilationH, + dilationW, + itime, + iheight, + iwidth, + otime, + oheight, + owidth, + fn_name, + ) + + check_dim_size(grad_output, ndim, ndim - 4, nslices) + check_dim_size(grad_output, ndim, ndim - 3, otime) + check_dim_size(grad_output, ndim, ndim - 2, oheight) + check_dim_size(grad_output, ndim, ndim - 1, owidth) + + check_dim_size(indices, ndim, ndim - 4, nslices) + check_dim_size(indices, ndim, ndim - 3, otime) + check_dim_size(indices, ndim, ndim - 2, oheight) + check_dim_size(indices, ndim, ndim - 1, owidth) + + +def avg_pool3d_backward_shape_check( + input: Tensor, + grad_output: Tensor, + nslices: int, + kT: int, + kH: int, + kW: int, + dT: int, + dH: int, + dW: int, + pT: int, + pH: int, + pW: int, + itime: int, + iheight: int, + iwidth: int, + otime: int, + oheight: int, + owidth: int, + fn_name: str, +): + ndim = input.ndim + + pool3d_shape_check( + input, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + pT, + pH, + pW, + 1, + 1, + 1, + itime, + iheight, + iwidth, + otime, + oheight, + owidth, + fn_name, + True, + ) + + check_dim_size(grad_output, ndim, ndim - 4, nslices) + check_dim_size(grad_output, ndim, ndim - 3, otime) + check_dim_size(grad_output, ndim, ndim - 2, oheight) + check_dim_size(grad_output, ndim, ndim - 1, owidth) + + +def max_pool2d_checks_and_compute_shape( + input, + kernel_size, + stride, + padding, + dilation, + ceil_mode, +): + # Reference: aten/src/ATen/native/DilatedMaxPool2d.cpp + def unpack(name, val): + torch._check( + len(val) in [1, 2], + lambda: f"max_pool2d: {name} must either be a single int, or a tuple of two ints", + ) + H = val[0] + W = H if len(val) == 1 else val[1] + return H, W + + kH, kW = unpack("kernel_size", kernel_size) + + torch._check( + len(stride) in [0, 1, 2], + lambda: "max_pool2d: stride must either be omitted, a single int, or a tuple of two ints", + ) + if len(stride) == 0: + dH, dW = kH, kW + else: + dH, dW = unpack("stride", stride) + + padH, padW = unpack("padding", padding) + dilationH, dilationW = unpack("dilation", dilation) + nInputPlane = input.size(-3) + inputHeight = input.size(-2) + inputWidth = input.size(-1) + + memory_format = utils.suggest_memory_format(input) + if memory_format == torch.channels_last: + torch._check( + input.dim() == 4, + lambda: "non-empty 4D (batch mode) tensor expected for input with channels_last layout", + ) + elif memory_format == torch.contiguous_format: + torch._check( + input.dim() in [3, 4], + lambda: "non-empty 3D or 4D (batch mode) tensor expected for input", + ) + else: + torch._check( + False, + lambda: "Unsupported memory format. Supports only ChannelsLast, Contiguous", + ) + + outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, dilationH, ceil_mode) + outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, dilationW, ceil_mode) + + pool2d_shape_check( + input, + kH, + kW, + dH, + dW, + padH, + padW, + dilationH, + dilationW, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + memory_format, + ) + + return nInputPlane, outputHeight, outputWidth + + +@register_meta(aten.max_pool2d_with_indices_backward) +@out_wrapper("grad_input") +def meta_max_pool2d_with_indices_backward( + grad_output, + self, + kernel_size, + stride, + padding, + dilation, + ceil_mode, + indices, +): + ( + nInputPlane, + outputHeight, + outputWidth, + ) = max_pool2d_checks_and_compute_shape( + self, kernel_size, stride, padding, dilation, ceil_mode + ) + + torch._check( + self.dtype == grad_output.dtype, + lambda: f"Expected dtype {self.dtype} for `gradOutput` but got dtype {grad_output.dtype}", + ) + + nOutputPlane = nInputPlane + ndim = self.ndim + + def _check_dim_size(t): + check_dim_size(t, ndim, ndim - 3, nOutputPlane) + check_dim_size(t, ndim, ndim - 2, outputHeight) + check_dim_size(t, ndim, ndim - 1, outputWidth) + + _check_dim_size(grad_output) + _check_dim_size(indices) + + memory_format = utils.suggest_memory_format(self) + return torch.empty( + self.shape, + dtype=self.dtype, + device=self.device, + memory_format=memory_format, + ) + + +@register_meta(aten.max_pool2d_with_indices.default) +def meta_max_pool2d_with_indices( + input, + kernel_size, + stride=(), + padding=(0,), + dilation=(1,), + ceil_mode=False, +): + ( + nInputPlane, + outputHeight, + outputWidth, + ) = max_pool2d_checks_and_compute_shape( + input, kernel_size, stride, padding, dilation, ceil_mode + ) + + nbatch = input.size(-4) if input.dim() == 4 else 1 + memory_format = utils.suggest_memory_format(input) + if input.dim() == 3: + size = [nInputPlane, outputHeight, outputWidth] + else: + size = [nbatch, nInputPlane, outputHeight, outputWidth] + return ( + torch.empty( + size, + dtype=input.dtype, + device=input.device, + memory_format=memory_format, + ), + torch.empty( + size, + dtype=torch.int64, + device=input.device, + memory_format=memory_format, + ), + ) + + +@register_meta(aten.fractional_max_pool2d.default) +def meta_fractional_max_pool2d(self, kernel_size, output_size, random_samples): + torch._check( + self.ndim in (3, 4), + lambda: f"fractional_max_pool2d: Expected 3D or 4D tensor, but got: {self.ndim}", + ) + ndim = self.ndim + + for d in range(ndim - 3, ndim): + torch._check( + self.size(d) > 0, + lambda: f"fractional_max_pool2d: Expected input to have non-zero " + f" size for non-batch dimensions, but got {self.size()} with dimension {d} empty", + ) + + # the check and message are out of sync, but this matches the structured meta + torch._check( + len(kernel_size) == 2, + lambda: "fractional_max_pool2d: kernel_size must" + "either be a single int or tuple of Ints", + ) + torch._check( + len(output_size) == 2, + lambda: "fractional_max_pool2d: output_size must " + "either be a single int or tuple of Ints", + ) + + input_channels = self.size(-3) + input_height = self.size(-2) + input_width = self.size(-1) + if ndim == 4: + input_batch = self.size(0) + else: + input_batch = 1 + + torch._check( + self.dtype == random_samples.dtype, + lambda: "Expect _random_samples to have the same dtype as input", + ) + torch._check( + random_samples.ndim == 3, + lambda: f"Expect _random samples to have 3 dimensions got, {random_samples.ndim}", + ) + + n = random_samples.size(0) + c = random_samples.size(1) + d = random_samples.size(2) + torch._check( + n >= input_batch, + lambda: "Expect _random_samples.size(0) no less than input batch size.", + ) + torch._check( + c == input_channels, + lambda: "Expect _random_samples.size(1) equals to input channel size.", + ) + torch._check(d == 2, lambda: f"Expect _random_samples.size(2) equals to 2 got {d}.") + + torch._check( + output_size[0] + kernel_size[0] - 1 <= input_height, + lambda: f"fractional_max_pool2d: kernel height {kernel_size[0]} is too large relative to input height {input_height}", + ) + torch._check( + output_size[1] + kernel_size[1] - 1 <= input_width, + lambda: f"fractional_max_pool2d: kernel width {kernel_size[1]} is too large relative to input width {input_width}", + ) + + if self.dim() == 4: + size = [input_batch, input_channels, output_size[0], output_size[1]] + else: + size = [input_channels, output_size[0], output_size[1]] + + return ( + torch.empty( + size, + dtype=self.dtype, + device=self.device, + ), + torch.empty( + size, + dtype=torch.int64, + device=self.device, + ), + ) + + +@register_meta(aten.max_pool3d_with_indices) +@out_wrapper("out", "indices") +def meta_max_pool3d_with_indices( + input, + kernel_size, + stride=(), + padding=(0,), + dilation=(1,), + ceil_mode=False, +): + torch._check( + len(kernel_size) in (1, 3), + lambda: "max_pool3d: kernel_size must either be a single int, or a tuple of three ints", + ) + kT = kernel_size[0] + kH = kT if len(kernel_size) == 1 else kernel_size[1] + kW = kT if len(kernel_size) == 1 else kernel_size[2] + + torch._check( + not stride or len(stride) in (1, 3), + lambda: "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints", + ) + dT = kT if not stride else stride[0] + dH = kH if not stride else (dT if len(stride) == 1 else stride[1]) + dW = kW if not stride else (dT if len(stride) == 1 else stride[2]) + + torch._check( + len(padding) in (1, 3), + lambda: "max_pool3d: padding must either be a single int, or a tuple of three ints", + ) + pT = padding[0] + pH = pT if len(padding) == 1 else padding[1] + pW = pT if len(padding) == 1 else padding[2] + + torch._check( + len(dilation) in (1, 3), + lambda: "max_pool3d: dilation must be either a single int, or a tuple of three ints", + ) + dilationT = dilation[0] + dilationH = dilationT if len(dilation) == 1 else dilation[1] + dilationW = dilationT if len(dilation) == 1 else dilation[2] + + torch._check( + input.ndim in (4, 5), + lambda: "non-empty 4D or 5D (batch mode) tensor expected for input", + ) + + nbatch = input.size(-5) if input.ndim == 5 else 1 + nslices = input.size(-4) + itime = input.size(-3) + iheight = input.size(-2) + iwidth = input.size(-1) + + otime = pooling_output_shape(itime, kT, pT, dT, dilationT, ceil_mode) + oheight = pooling_output_shape(iheight, kH, pH, dH, dilationH, ceil_mode) + owidth = pooling_output_shape(iwidth, kW, pW, dW, dilationW, ceil_mode) + + pool3d_shape_check( + input, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + pT, + pH, + pW, + dilationT, + dilationH, + dilationW, + itime, + iheight, + iwidth, + otime, + oheight, + owidth, + "max_pool3d_with_indices()", + ) + + # channels_last_3d only applies to 5D tensors (C++ enforces this) + channels_last = ( + input.ndim == 5 and utils.suggest_memory_format(input) == torch.channels_last_3d + ) + if input.ndim == 4: + out_shape = (nslices, otime, oheight, owidth) + else: + out_shape = (nbatch, nslices, otime, oheight, owidth) # type: ignore[assignment] + + out = input.new_empty(out_shape) + indices = input.new_empty(out_shape, dtype=torch.int64) + + if channels_last: + out = out.to(memory_format=torch.channels_last_3d) + indices = indices.to(memory_format=torch.channels_last_3d) + + return out, indices + + +@register_meta(aten.max_pool3d_with_indices_backward) +@out_wrapper("grad_input") +def meta_max_pool3d_with_indices_backward( + grad_output, + input, + kernel_size, + stride, + padding, + dilation, + ceil_mode, + indices, +): + torch._check( + len(kernel_size) in (1, 3), + lambda: "max_pool3d: kernel_size must either be a single int, or a tuple of three ints", + ) + kT = kernel_size[0] + kH = kT if len(kernel_size) == 1 else kernel_size[1] + kW = kT if len(kernel_size) == 1 else kernel_size[2] + + torch._check( + not stride or len(stride) in (1, 3), + lambda: "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints", + ) + dT = kT if not stride else stride[0] + dH = kH if not stride else (dT if len(stride) == 1 else stride[1]) + dW = kW if not stride else (dT if len(stride) == 1 else stride[2]) + + torch._check( + len(padding) in (1, 3), + lambda: "max_pool3d: padding must either be a single int, or a tuple of three ints", + ) + pT = padding[0] + pH = pT if len(padding) == 1 else padding[1] + pW = pT if len(padding) == 1 else padding[2] + + torch._check( + len(dilation) in (1, 3), + lambda: "max_pool3d: dilation must be either a single int, or a tuple of three ints", + ) + dilationT = dilation[0] + dilationH = dilationT if len(dilation) == 1 else dilation[1] + dilationW = dilationT if len(dilation) == 1 else dilation[2] + + torch._check( + input.ndim in (4, 5), + lambda: "non-empty 4D or 5D (batch mode) tensor expected for input", + ) + + nslices = input.size(-4) + itime = input.size(-3) + iheight = input.size(-2) + iwidth = input.size(-1) + + otime = grad_output.size(-3) + oheight = grad_output.size(-2) + owidth = grad_output.size(-1) + + max_pool3d_backward_shape_check( + input, + grad_output, + indices, + nslices, + kT, + kH, + kW, + dT, + dH, + dW, + pT, + pH, + pW, + dilationT, + dilationH, + dilationW, + itime, + iheight, + iwidth, + otime, + oheight, + owidth, + "max_pool3d_with_indices_backward()", + ) + + # channels_last_3d only applies to 5D tensors (C++ enforces this) + channels_last = ( + input.ndim == 5 and utils.suggest_memory_format(input) == torch.channels_last_3d + ) + + grad_input = input.new_empty(input.shape) + + if channels_last: + grad_input = grad_input.to(memory_format=torch.channels_last_3d) + + return grad_input + + +def check_grid_sampler_common(input: Tensor, grid: Tensor): + torch._check( + input.device == grid.device, + lambda: ( + f"grid_sampler(): expected input and grid to be on same device, but input " + f"is on {input.device} and grid is on {grid.device}" + ), + ) + torch._check( + input.layout == torch.strided and grid.layout == torch.strided, + lambda: ( + f"grid_sampler(): expected input and grid to have torch.strided layout, but " + f"input has {input.layout} and grid has {grid.layout}" + ), + ) + torch._check( + input.shape[0] == grid.shape[0], + lambda: ( + f"grid_sampler(): expected grid and input to have same batch size, but got " + f"input with sizes {input.shape} and grid with sizes {grid.shape}" + ), + ) + torch._check( + grid.shape[-1] == input.ndim - 2, + lambda: ( + f"grid_sampler(): expected grid to have size {input.ndim - 2} in last " + f"dimension, but got grid with sizes {grid.shape}" + ), + ) + + for i in range(2, input.ndim): + torch._check( + input.shape[i] > 0, + lambda: ( + f"grid_sampler(): expected input to have non-empty spatial dimensions, " + f"but input has sizes {input.shape} with dimension {i} being empty" + ), + ) + + +class GridSamplerInterpolation(Enum): + BILINEAR = 0 + NEAREST = 1 + BICUBIC = 2 + + +def check_grid_sampler_2d(input: Tensor, grid: Tensor): + torch._check( + input.ndim == 4 and input.ndim == grid.ndim, + lambda: ( + f"grid_sampler(): expected 4D input and grid with same number of " + f"dimensions, but got input with sizes {input.shape}" + f" and grid with sizes {grid.shape}" + ), + ) + + +def check_grid_sampler_3d(input: Tensor, grid: Tensor, interpolation_mode: int): + torch._check( + input.ndim == 5 and input.ndim == grid.ndim, + lambda: ( + f"grid_sampler(): expected 5D input and grid with same number of " + f"dimensions, but got input with sizes {input.shape}" + f" and grid with sizes {grid.shape}" + ), + ) + torch._check( + not ( + input.ndim == 5 + and interpolation_mode == GridSamplerInterpolation.BICUBIC.value + ), + lambda: "grid_sampler(): bicubic interpolation only supports 4D input", + ) + + +# torch._grid_sampler_2d_cpu_fallback is CompositeExplicitAutograd, so without a +# meta kernel the real CPU kernel runs under FakeTensorMode and fails on +# unallocated data ("the tensor has a non-zero number of elements, but its data is +# not allocated yet"), making the op uncapturable. These mirror both the checks the +# C++ impls run (they call check_grid_sampler_common/_2d themselves, since they can +# be called instead of grid_sampler) and the shapes they allocate -- +# aten/src/ATen/native/GridSampler.cpp. +@register_meta(aten._grid_sampler_2d_cpu_fallback) +@out_wrapper() +def _grid_sampler_2d_cpu_fallback_meta( + input, + grid, + interpolation_mode, + padding_mode, + align_corners, +): + check_grid_sampler_common(input, grid) + check_grid_sampler_2d(input, grid) + N = input.shape[0] + C = input.shape[1] + out_H = grid.shape[1] + out_W = grid.shape[2] + return input.new_empty((N, C, out_H, out_W)) + + +@register_meta(aten._grid_sampler_2d_cpu_fallback_backward) +def _grid_sampler_2d_cpu_fallback_backward_meta( + grad_output, + input, + grid, + interpolation_mode, + padding_mode, + align_corners, +): + check_grid_sampler_common(input, grid) + check_grid_sampler_2d(input, grid) + grad_input = torch.zeros_like(input, memory_format=torch.contiguous_format) + grad_grid = torch.empty_like(grid, memory_format=torch.contiguous_format) + return (grad_input, grad_grid) + + +@register_meta(aten.grid_sampler_2d_backward.default) +def grid_sampler_2d_backward_meta( + grad_output, + input, + grid, + interpolation_mode, + padding_mode, + align_corners, + output_mask, +): + input_requires_grad = output_mask[0] + if input_requires_grad: + grad_input = torch.zeros_like(input, memory_format=torch.contiguous_format) + else: + grad_input = None + grad_grid = torch.empty_like(grid, memory_format=torch.contiguous_format) + return (grad_input, grad_grid) + + +@register_meta(aten.grid_sampler_3d) +@out_wrapper() +def grid_sampler_3d( + input, + grid, + interpolation_mode, + padding_mode, + align_corners, +): + check_grid_sampler_common(input, grid) + check_grid_sampler_3d(input, grid, interpolation_mode) + N = input.shape[0] + C = input.shape[1] + out_D = grid.shape[1] + out_H = grid.shape[2] + out_W = grid.shape[3] + return input.new_empty((N, C, out_D, out_H, out_W)) + + +@register_meta(aten.grid_sampler_3d_backward) +@out_wrapper("grad_input", "grad_grid") +def grid_sampler_3d_backward( + grad_output, + input, + grid, + interpolation_mode, + padding_mode, + align_corners, + output_mask, +): + check_grid_sampler_common(input, grid) + check_grid_sampler_3d(input, grid, interpolation_mode) + input_requires_grad = output_mask[0] + if input_requires_grad: + grad_input = torch.zeros_like( + input, memory_format=torch.legacy_contiguous_format + ) + else: + grad_input = None + grad_grid = torch.empty_like(grid, memory_format=torch.legacy_contiguous_format) + return grad_input, grad_grid + + +@register_meta([aten.full.default]) +def full(size, fill_value, *args, **kwargs): + dtype = kwargs.get("dtype") + if not dtype: + dtype = utils.get_dtype(fill_value) + kwargs["dtype"] = dtype + + return torch.empty(size, *args, **kwargs) + + +# zeros_like is special cased to work for sparse +@register_meta(aten.zeros_like.default) +def zeros_like( + self, + dtype=None, + layout=None, + device=None, + pin_memory=None, + memory_format=None, +): + if layout == torch.sparse_coo: + torch._check( + memory_format is None, + lambda: "memory format option is only supported by strided tensors", + ) + + res = torch.empty( + 0, + dtype=self.dtype if dtype is None else dtype, + layout=layout, + device=self.device if device is None else device, + pin_memory=pin_memory, + ) + + if self.is_sparse: + res.sparse_resize_and_clear_( + self.size(), self.sparse_dim(), self.dense_dim() + ) + else: + res.sparse_resize_and_clear_(self.size(), self.dim(), 0) + + res._coalesced_(True) + return res + res = aten.empty_like.default( + self, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + memory_format=memory_format, + ) + # device can be not "meta" + res.fill_(0) + return res + + +@register_meta([aten.ones.default, aten.ones.out]) +@out_wrapper() +def meta_ones( + size, + *, + dtype=None, + layout=None, + device=None, + pin_memory=None, + requires_grad=False, +): + if dtype is None: + dtype = torch.get_default_dtype() + if device is None: + device = torch.get_default_device() + if layout is None: + layout = torch.strided + return torch.empty( + size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta([aten.zeros.default, aten.zeros.out]) +@out_wrapper() +def meta_zeros( + size, + *, + dtype=None, + layout=None, + device=None, + pin_memory=None, + requires_grad=False, +): + if dtype is None: + dtype = torch.get_default_dtype() + if device is None: + device = torch.get_default_device() + if layout is None: + layout = torch.strided + return torch.empty( + size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta(aten.select_scatter.default) +def meta_select_scatter(self, src, dim, index): + return _scatter_meta_output(self) + + +@register_meta(aten.slice_scatter.default) +def meta_slice_scatter(self, src, dim=0, start=None, end=None, step=1): + return _scatter_meta_output(self) + + +@register_meta(aten.diagonal_scatter.default) +def meta_diagonal_scatter(self, src, offset=0, dim1=0, dim2=1): + return _scatter_meta_output(self) + + +def _scatter_meta_output(self): + from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols + + # Match clone_preserve_strides() in aten/native/TensorShape.cpp: overlapping + # bases cannot preserve their logical strides because the scatter writes would + # alias, so eager falls back to clone(). + if not free_unbacked_symbols(self) and torch._debug_has_internal_overlap(self) == 1: + return self.clone() + return utils.clone_preserve_strides(self) + + +# TODO: Deduplicate this with canonicalize_dim +def maybe_wrap_dim(dim: int, dim_post_expr: int, wrap_scalar: bool = True): + if dim_post_expr <= 0: + if not wrap_scalar: + raise AssertionError( + f"dim_post_expr={dim_post_expr} <= 0 but wrap_scalar is False" + ) + dim_post_expr = 1 + min = -dim_post_expr + max = dim_post_expr - 1 + if dim < min or dim > max: + raise IndexError( + f"Dimension out of range (expected to be in range of [{min}, {max}], but got {dim})" + ) + if dim < 0: + dim += dim_post_expr + return dim + + +def ensure_nonempty_size(t, dim): + return 1 if t.dim() == 0 else t.shape[dim] + + +# From aten/src/ATen/native/ScatterGatherChecks.h +def gather_shape_check(self, dim, index): + self_dims = max(self.dim(), 1) + index_dims = max(index.dim(), 1) + torch._check( + self_dims == index_dims, + lambda: "Index tensor must have the same number of dimensions as input tensor", + ) + for i in range(self_dims): + if i != dim: + torch._check( + ensure_nonempty_size(index, i) <= ensure_nonempty_size(self, i), + lambda: f"Size does not match at dimension {i} expected index {index.shape}" + + f" to be no larger than self {self.shape} apart from dimension {dim}", + ) + + +@register_meta(aten.gather.default) +def meta_gather(self, dim, index, sparse_grad=False): + from torch.fx.experimental.symbolic_shapes import guard_or_false + + wrapped_dim = maybe_wrap_dim(dim, self.dim()) + is_index_empty = guard_or_false(index.numel() == 0) + if not is_index_empty: + torch._check( + index.dtype == torch.long or index.dtype == torch.int, + lambda: f"gather(): Expected dtype int32/int64 for index, but got {index.dtype}", + ) + gather_shape_check(self, wrapped_dim, index) + return self.new_empty(index.shape) + + +# From aten/src/ATen/native/TensorAdvancedIndexing.cpp +def get_operator_enum(reduce_, use_new_options=False): + if use_new_options: + if reduce_ == "sum": + return "REDUCE_ADD" + elif reduce_ == "prod": + return "REDUCE_MULTIPLY" + elif reduce_ == "mean": + return "REDUCE_MEAN" + elif reduce_ == "amax": + return "REDUCE_MAXIMUM" + elif reduce_ == "amin": + return "REDUCE_MINIMUM" + torch._check( + False, + lambda: "reduce argument must be either sum, prod, mean, amax or amin.", + ) + return + else: + if reduce_ == "add": + return "REDUCE_ADD" + elif reduce_ == "multiply": + return "REDUCE_MULTIPLY" + torch._check(False, lambda: "reduce argument must be either add or multiply.") + return + + +# From aten/src/ATen/native/ScatterGatherChecks.h +def scatter_gather_dtype_check(method_name, self, index, src_opt=None): + from torch.fx.experimental.symbolic_shapes import guard_or_true + + if guard_or_true(index.numel() != 0): + torch._check( + index.dtype == torch.long or index.dtype == torch.int, + lambda: f"{method_name}(): Expected dtype int32/int64 for index", + ) + + if src_opt is not None: + torch._check( + self.dtype == src_opt.dtype, + lambda: f"{method_name}(): Expected self.dtype to be equal to src.dtype", + ) + + +def ensure_nonempty_dim(dim): + return max(dim, 1) + + +# From aten/src/ATen/native/ScatterGatherChecks.h +def scatter_shape_check(self, dim, index, src_opt=None): + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(index.numel() == 0): + return + torch._check( + ensure_nonempty_dim(self.dim()) == ensure_nonempty_dim(index.dim()), + lambda: "Index tensor must have the same number of dimensions as self tensor", + ) + + self_dims = ensure_nonempty_dim(self.dim()) + + # Check: index.size(d) <= self.size(d) for all d != dim + # Use torch._check to defer validation to runtime for unbacked symbols. + for d in range(self_dims): + if d == dim: + continue + index_d_size = ensure_nonempty_size(index, d) + self_d_size = ensure_nonempty_size(self, d) + torch._check( + index_d_size <= self_d_size, + lambda: f"Expected index {index.shape} to be no larger than self {self.shape}" + + f" apart from dimension {dim}", + ) + + # Check: index.size(d) <= src.size(d) for all d if src is Tensor + if src_opt is not None: + torch._check( + ensure_nonempty_dim(self.dim()) == ensure_nonempty_dim(src_opt.dim()), + lambda: "Index tensor must have the same number of dimensions as src tensor", + ) + for d in range(self_dims): + index_d_size = ensure_nonempty_size(index, d) + src_d_size = ensure_nonempty_size(src_opt, d) + torch._check( + index_d_size <= src_d_size, + lambda: f"Expected index {index.shape} to be no larger than src {src_opt.shape}", + ) + + +# From aten/src/ATen/native/TensorAdvancedIndexing.cpp +def scatter_meta_impl(self, dim, index, src=None, reduce_=None, use_new_options=False): + wrapped_dim = maybe_wrap_dim(dim, self.dim()) + scatter_gather_dtype_check("scatter", self, index, src) + scatter_shape_check(self, wrapped_dim, index, src) + if reduce_ is not None: + # Check if we have a valid reduce operator. + get_operator_enum(reduce_, use_new_options) + + +@register_meta(aten.scatter_add.default) +def meta_scatter_add(self, dim, index, src): + scatter_meta_impl(self, dim, index, src, "add") + return self.new_empty(self.shape) + + +@register_meta(aten.scatter_add_) +def meta_scatter_add_(self, dim, index, src): + scatter_meta_impl(self, dim, index, src, "add") + return self + + +@register_meta( + [ + aten.scatter.src, + aten.scatter.value, + aten.scatter.reduce, + aten.scatter.value_reduce, + ] +) +@out_wrapper() +def meta_scatter(self, dim, index, src_or_value, reduce=None): + src = src_or_value if isinstance(src_or_value, torch.Tensor) else None + scatter_meta_impl(self, dim, index, src, reduce) + return self.new_empty(self.shape) + + +@register_meta( + [ + aten.scatter_.src, + aten.scatter_.value, + aten.scatter_.reduce, + aten.scatter_.value_reduce, + ] +) +def meta_scatter_(self, dim, index, src_or_value, reduce=None): + src = src_or_value if isinstance(src_or_value, torch.Tensor) else None + scatter_meta_impl(self, dim, index, src, reduce) + return self + + +@register_meta([aten._scaled_dot_product_flash_attention.default]) +def meta__scaled_dot_product_flash_attention( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: float = 0.0, + is_causal: bool = False, + return_debug_mask: bool = False, + scale: float | None = None, +): + batch_size = query.size(0) + num_heads = query.size(1) + max_seqlen_batch_q = query.size(2) + head_dim = query.size(3) + max_seqlen_batch_k = key.size(2) + + attention = torch.empty_like(query) + logsumexp = torch.empty( + (batch_size, num_heads, max_seqlen_batch_q), + dtype=torch.float, + device=query.device, + ) + + if return_debug_mask: + blocksize_c = 128 if head_dim > 64 else 256 + max_seqlen_k = math.ceil(max_seqlen_batch_q / blocksize_c) + if max_seqlen_batch_k <= 128: + max_seqlen_k = 128 + elif max_seqlen_batch_k <= 256: + max_seqlen_k = 256 + debug_mask = torch.empty( + (batch_size, num_heads, max_seqlen_batch_q, max_seqlen_k), + dtype=query.dtype, + device=query.device, + ) + else: + debug_mask = torch.empty(0, dtype=query.dtype, device=query.device) + + # Note [Seed and Offset]: device for seed and offset below depends on whether we are + # capturing or not, but at the time of tracing we don't know if we + # are going to use cudagraphs or not, so we return meta tensors here + # it's possible we'll need to have some special handling in inductor for sdpa + # See [Note] BC breaking change to flash seed/offset + if torch.version.hip and torch.cuda.is_available() or device_hint(query) == "xpu": + # Maintain old path on AMD + seed = torch.empty((), dtype=torch.long, device="meta") + offset = torch.empty((), dtype=torch.long, device="meta") + else: + seed = torch.empty((2), dtype=torch.uint64, device="meta") + offset = torch.empty((), dtype=torch.uint64, device="meta") + + return ( + attention, + logsumexp, + None, + None, + max_seqlen_batch_q, + max_seqlen_batch_k, + seed, + offset, + debug_mask, + ) + + +@register_meta([aten._scaled_dot_product_flash_attention.quantized]) +def meta__scaled_dot_product_flash_attention_quantized( + query: Tensor, + key: Tensor, + value: Tensor, + q_descale: Tensor | None, + k_descale: Tensor | None, + v_descale: Tensor | None, + dropout_p: float = 0.0, + is_causal: bool = False, + return_debug_mask: bool = False, + scale: float | None = None, +): + if query.dtype == torch.float8_e4m3fn: + query = query.to(torch.bfloat16) + + return meta__scaled_dot_product_flash_attention( + query, + key, + value, + dropout_p, + is_causal, + return_debug_mask, + scale, + ) + + +def alloc_with_matching_layout( + query: Tensor, + res_shape: tuple[int, ...], +): + if tuple(query.shape) == res_shape: + res = torch.empty_like(query) + else: + dim_order = sorted( + [0, 1, 2, 3], key=lambda idx: query.stride()[idx], reverse=True + ) + strides = [0] * len(dim_order) + stride = 1 + for idx in reversed(dim_order): + strides[idx] = stride + stride *= res_shape[idx] + res = torch.empty_strided( + res_shape, strides, dtype=query.dtype, device=query.device + ) + + return res + + +@register_meta([aten._scaled_dot_product_cudnn_attention]) +def meta__scaled_dot_product_cudnn_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + compute_log_sumexp: bool, + dropout_p: float = 0.0, + is_causal: bool = False, + return_debug_mask: bool = False, + scale: float | None = None, +): + B = query.size(0) + H = query.size(1) + S_Q = query.size(2) + S_KV = key.size(2) + D_V = value.size(-1) + + res_shape = (B, H, S_Q, D_V) + res = alloc_with_matching_layout(query, res_shape) + + logsum_exp = torch.empty( + (B, H, S_Q, 1), + dtype=torch.float, + device=query.device, + ) + + # See Note [Seed and Offset] + seed = torch.empty((), dtype=torch.long, device="meta") + offset = torch.empty((), dtype=torch.long, device="meta") + + return ( + res, + logsum_exp, + None, + None, + S_Q, + S_KV, + seed, + offset, + None, + ) + + +@register_meta([aten._scaled_dot_product_fused_attention_overrideable]) +def meta__scaled_dot_product_fused_attention_overrideable( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None = None, + dropout_p: float = 0.0, + is_causal: bool = False, + return_debug_mask: bool = False, + scale: float | None = None, +): + # Explicitly handle 3D (H, S, D) and 4D (B, H, S, D) inputs, + # matching the C++ runtime in aten_mtia_ops.cpp. + B, H_Q, S_Q = 0, 0, 0 + if query.dim() == 4: + B, H_Q, S_Q, _ = query.size() + elif query.dim() == 3: + H_Q, S_Q, _ = query.size() + B = 1 + else: + raise RuntimeError("query must be 3D or 4D") + S_KV = key.size(-2) + D_V = value.size(-1) + + # Preserve input dimensionality for the output shape + out_shape = list(query.shape) + out_shape[-1] = D_V + res = alloc_with_matching_layout(query, tuple(out_shape)) + + logsum_exp = torch.empty( + (B, H_Q, S_Q), + dtype=torch.float, + device=query.device, + ) + + # See Note [Seed and Offset] + seed = torch.empty((), dtype=torch.long, device="meta") + offset = torch.empty((), dtype=torch.long, device="meta") + + return ( + res, + logsum_exp, + None, + None, + S_Q, + S_KV, + seed, + offset, + None, + ) + + +@register_meta(aten._scaled_dot_product_fused_attention_overrideable_backward) +def meta__scaled_dot_product_fused_attention_overrideable_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor, + grad_input_mask: list[bool], + out: Tensor, + logsumexp: Tensor, + cum_seq_q: Tensor, + cum_seq_k: Tensor, + max_q: int, + max_k: int, + dropout_p: float, + is_causal: bool, + philox_seed: Tensor, + philox_offset: Tensor, + *, + scale: float | None = None, +): + grad_q = torch.empty_like(query) + grad_k = torch.empty_like(key) + grad_v = torch.empty_like(value) + grad_attn_bias = torch.empty_like(attn_bias) if attn_bias is not None else None + return grad_q, grad_k, grad_v, grad_attn_bias + + +@register_meta( + [ + aten._scaled_dot_product_flash_attention_backward, + ] +) +def meta__scaled_dot_product_flash_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + out: Tensor, + logsumexp: Tensor, + cum_seq_q: Tensor, + cum_seq_k: Tensor, + max_q: int, + max_k: int, + dropout_p: float, + is_causal: bool, + philox_seed: Tensor, + philox_offset: Tensor, + scale: float | None = None, +): + grad_q = torch.empty_like(query) + grad_k = torch.empty_like(key) + grad_v = torch.empty_like(value) + return grad_q, grad_k, grad_v + + +@register_meta( + [ + aten._scaled_dot_product_flash_attention_for_cpu, + ] +) +def meta__scaled_dot_product_flash_attention_for_cpu( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: float = 0.0, + is_causal: bool = False, + attn_mask: Tensor | None = None, + scale: float | None = None, +): + batch_size = query.size(0) + num_heads = query.size(1) + max_seqlen_batch_q = query.size(2) + + attention = torch.empty_like(query) + logsumexp = torch.empty( + ( + batch_size, + max_seqlen_batch_q, + num_heads, + ), + dtype=utils.get_computation_dtype(query.dtype), + device=query.device, + ).transpose(1, 2) + return ( + attention, + logsumexp, + ) + + +@register_meta( + [ + aten._scaled_dot_product_flash_attention_for_cpu_backward, + ] +) +def meta__scaled_dot_product_flash_attention_for_cpu_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + out: Tensor, + logsumexp: Tensor, + dropout_p: float, + is_causal: bool, + attn_mask: Tensor | None = None, + scale: float | None = None, +): + # cpus's grad layout is different from cuda's, + # i.e. (batch_size, seq_len, num_heads, head_dim) + grad_q = torch.empty_permuted( + query.size(), + (0, 2, 1, 3), + dtype=query.dtype, + device=query.device, + ) + grad_k = torch.empty_permuted( + key.size(), + (0, 2, 1, 3), + dtype=key.dtype, + device=key.device, + ) + grad_v = torch.empty_permuted( + value.size(), + (0, 2, 1, 3), + dtype=value.dtype, + device=value.device, + ) + + return grad_q, grad_k, grad_v + + +@register_meta([aten._scaled_dot_product_attention_math_for_mps]) +def meta__scaled_dot_product_attention_math_for_mps( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: float = 0.0, + is_causal: bool = False, + dropout_mask: Tensor | None = None, + scale: float | None = None, + enable_gqa: bool = False, +) -> tuple[Tensor, Tensor]: + def ensure_4d(x): + if x.dim() == 3: + return x.unsqueeze(0), True + elif x.dim() > 4: + batch_size = 1 + for i in range(x.dim() - 3): + batch_size *= x.shape[i] + return x.view(batch_size, x.size(-3), x.size(-2), x.size(-1)), True + else: + return x, False + + q_, unsqueezed = ensure_4d(query) + k_, _ = ensure_4d(key) + v_, _ = ensure_4d(value) + + batch_size, num_head, q_size, _ = q_.shape + _, _, max_seq_length, value_head_size = v_.shape + + def sdpa_general_mps(): + out = q_.new_empty((batch_size, num_head, q_size, value_head_size)) + attn = q_.new_empty((batch_size, num_head, q_size, max_seq_length)) + if unsqueezed: + if query.dim() == 3: + out = out.squeeze(0) + attn = attn.squeeze(0) + else: + out_shape = list(query.shape[:-3]) + list(out.shape[1:4]) + attn_shape = list(query.shape[:-3]) + list(attn.shape[1:4]) + out = out.view(out_shape) + attn = attn.view(attn_shape) + return out, attn + + # sdpa_vector_2pass_mps and sdpa_vector_fast_mps are intentionally left out. + # See https://github.com/pytorch/pytorch/issues/177603 for additional context. + return sdpa_general_mps() + + +@register_meta([aten._scaled_dot_product_efficient_attention]) +def meta__scaled_dot_product_efficient_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + compute_log_sumexp: bool, + dropout_p=0.0, + is_causal: bool = False, + scale: float | None = None, +): + query = query.transpose(1, 2) + key = key.transpose(1, 2) + value = value.transpose(1, 2) + + B = query.size(0) + M = query.size(1) + num_heads = query.size(-2) + Kv = value.size(-1) + + res = torch.empty(B, M, num_heads, Kv, dtype=query.dtype, device=query.device) + + if torch.version.hip and torch.cuda.is_available(): + """Please see: https://github.com/pytorch/pytorch/issues/146848 + logsumexp last dim should be seq length + """ + logsumexp_dim = M if compute_log_sumexp else 0 + else: + logsumexp_dim = math.ceil(M / 32) * 32 if compute_log_sumexp else 0 + + logsum_exp = torch.empty( + (B, num_heads, logsumexp_dim), + dtype=torch.float, + device=query.device, + ) + + res = res.transpose(1, 2) + + # See Note [Seed and Offset]: + seed = torch.empty((), dtype=torch.long, device="meta") + offset = torch.empty((), dtype=torch.long, device="meta") + + return res, logsum_exp, seed, offset + + +@register_meta( + [ + aten._scaled_dot_product_efficient_attention_backward, + ] +) +def meta__scaled_dot_product_efficient_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + out: Tensor, + logsumexp: Tensor, + philox_seed: Tensor, + philox_offset: Tensor, + dropout_p: float, + grad_input_mask: list[bool], + is_causal: bool = False, + scale: float | None = None, +): + batch_size = query.size(0) + num_heads_q = query.size(1) + num_heads_k = key.size(1) + num_heads_v = value.size(1) + max_q = query.size(2) + head_dim = query.size(3) + head_dim_v = value.size(3) + + max_k = key.size(2) + + grad_q = torch.empty_permuted( + (batch_size, num_heads_q, max_q, head_dim), + (0, 2, 1, 3), + dtype=query.dtype, + device=query.device, + ) + grad_k = torch.empty_permuted( + (batch_size, num_heads_k, max_k, head_dim), + (0, 2, 1, 3), + dtype=key.dtype, + device=key.device, + ) + grad_v = torch.empty_permuted( + (batch_size, num_heads_v, max_k, head_dim_v), + (0, 2, 1, 3), + dtype=value.dtype, + device=value.device, + ) + grad_bias = None + if attn_bias is not None and grad_input_mask[3]: + lastDim = attn_bias.size(-1) + lastDimAligned = lastDim if lastDim % 16 == 0 else lastDim + 16 - lastDim % 16 + new_sizes = list(attn_bias.size()) + new_sizes[-1] = lastDimAligned + grad_bias = torch.empty( + new_sizes, dtype=attn_bias.dtype, device=attn_bias.device + ) + grad_bias = grad_bias[..., :lastDim] + + return grad_q, grad_k, grad_v, grad_bias + + +@register_meta( + [ + aten._scaled_dot_product_cudnn_attention_backward, + ] +) +def meta__scaled_dot_product_cudnn_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + out: Tensor, + logsumexp: Tensor, + philox_seed: Tensor, + philox_offset: Tensor, + attn_bias: Tensor, + cum_seq_q: Tensor, + cum_seq_k: Tensor, + max_q: int, + max_k: int, + dropout_p: float, + is_causal: bool, + scale: float | None = None, +): + grad_q = torch.empty_like(query) + grad_k = torch.empty_like(key) + grad_v = torch.empty_like(value) + return grad_q, grad_k, grad_v + + +@register_meta( + [ + aten._flash_attention_forward.default, + ] +) +def meta__flash_attention_forward( + query: Tensor, + key: Tensor, + value: Tensor, + cum_seq_q: Tensor | None, + cum_seq_k: Tensor | None, + max_q: int, + max_k: int, + dropout_p: float, + is_causal: bool, + return_debug_mask: bool, + scale: float | None = None, + window_size_left: int | None = None, + window_size_right: int | None = None, + seqused_k: Tensor | None = None, + alibi_slopes: Tensor | None = None, + block_table: Tensor | None = None, + num_splits: int | None = None, +): + # NB: there are two underlying paths: + # 1. normal dense path; expect 4D inputs of shape (batch_size, seqlen, num_heads, head_dim) + # 2. varseqlen path; expect 3D inputs of shape (total, num_heads, head_dim) where total + # includes all batch item sequences. cum_seq_q / cum_seq_k contain offsets into total + batch_size = query.size(0) if cum_seq_q is None else cum_seq_q.numel() - 1 + max_seqlen_batch_q = query.size(1) if cum_seq_q is None else max_q + max_seqlen_batch_k = key.size(1) if cum_seq_k is None else max_k + num_heads = query.size(-2) + head_dim = query.size(-1) + + # Cuda Path + attention = torch.empty_like(query) + if cum_seq_q is None: + logsumexp = torch.empty( + (batch_size, num_heads, max_seqlen_batch_q), + dtype=torch.float, + device=query.device, + ) + else: + total_q = query.size(0) + logsumexp = torch.empty( + (num_heads, total_q), dtype=torch.float, device=query.device + ) + + if return_debug_mask: + blocksize_c = 128 if head_dim > 64 else 256 + max_seqlen_k = math.ceil(max_seqlen_batch_q / blocksize_c) + if max_seqlen_batch_k <= 128: + max_seqlen_k = 128 + elif max_seqlen_batch_k <= 256: + max_seqlen_k = 256 + debug_mask = torch.empty( + (batch_size, num_heads, max_seqlen_batch_q, max_seqlen_k), + dtype=query.dtype, + device=query.device, + ) + else: + debug_mask = torch.empty(0, dtype=query.dtype, device=query.device) + + # See Note [Seed and Offset] + # See [Note] BC breaking change to flash seed/offset + seed, offset = None, None + if torch.version.hip and torch.cuda.is_available(): + # Maintain old path on AMD + seed = torch.empty((), dtype=torch.long, device="meta") + offset = torch.empty((), dtype=torch.long, device="meta") + else: + seed = torch.empty((2), dtype=torch.uint64, device="meta") + offset = torch.empty((), dtype=torch.uint64, device="meta") + return ( + attention, + logsumexp, + seed, + offset, + debug_mask, + ) + + +@register_meta([aten._flash_attention_forward_no_dropout_inplace.default]) +def meta__flash_attention_forward_no_dropout_inplace( + out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + cum_seq_q: Tensor | None, + cum_seq_k: Tensor | None, + max_q: int, + max_k: int, + dropout_p: float, + is_causal: bool, + return_debug_mask: bool, + scale: float | None = None, + window_size_left: int | None = None, + window_size_right: int | None = None, + seqused_k: Tensor | None = None, + alibi_slopes: Tensor | None = None, + block_table: Tensor | None = None, + num_splits: int | None = None, +): + _, logsumexp, _, _, _ = meta__flash_attention_forward( + query, + key, + value, + cum_seq_q, + cum_seq_k, + max_q, + max_k, + dropout_p, + is_causal, + return_debug_mask, + scale, + window_size_left, + window_size_right, + seqused_k, + alibi_slopes, + block_table, + ) + return logsumexp + + +@register_meta([aten._flash_attention_forward.quantized]) +def meta__flash_attention_forward_quantized( + query: Tensor, + key: Tensor, + value: Tensor, + cum_seq_q: Tensor | None, + cum_seq_k: Tensor | None, + max_q: int, + max_k: int, + dropout_p: float, + is_causal: bool, + return_debug_mask: bool, + q_descale: Tensor | None, + k_descale: Tensor | None, + v_descale: Tensor | None, + scale: float | None = None, + window_size_left: int | None = None, + window_size_right: int | None = None, + seqused_k: Tensor | None = None, + alibi_slopes: Tensor | None = None, +): + if query.dtype == torch.float8_e4m3fn: + query = query.to(torch.bfloat16) + + return meta__flash_attention_forward( + query, + key, + value, + cum_seq_q, + cum_seq_k, + max_q, + max_k, + dropout_p, + is_causal, + return_debug_mask, + scale, + window_size_left, + window_size_right, + seqused_k, + alibi_slopes, + ) + + +@register_meta( + [ + aten._flash_attention_backward, + ] +) +def meta__flash_attention_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + out: Tensor, + logsumexp: Tensor, + cum_seq_q: Tensor, + cum_seq_k: Tensor, + max_q: int, + max_k: int, + dropout_p: float, + is_causal: bool, + philox_seed: Tensor, + philox_offset: Tensor, + scale: float | None = None, + window_size_left: int | None = None, + window_size_right: int | None = None, +): + grad_query = torch.empty_like(query) + grad_key = torch.empty_like(key) + grad_value = torch.empty_like(value) + + return grad_query, grad_key, grad_value + + +@register_meta( + [ + aten._efficient_attention_forward, + ] +) +def meta__efficient_attention_forward( + query: Tensor, + key: Tensor, + value: Tensor, + bias: Tensor | None, + cu_seqlens_q: Tensor | None, + cu_seqlens_k: Tensor | None, + max_seqlen_q: int | None, + max_seqlen_k: int | None, + dropout_p: float, + custom_mask_type: int, + compute_log_sumexp: bool = False, + scale: float | None = None, + causal_diagonal: Tensor | None = None, + seqlen_k: Tensor | None = None, + window_size: int | None = None, +): + B = query.size(0) + M = query.size(1) + N = key.size(1) + num_heads = query.size(-2) + Kv = value.size(-1) + + res = torch.empty(B, M, num_heads, Kv, dtype=query.dtype, device=query.device) + + logsumexp_batch_dim = cu_seqlens_q.size(0) - 1 if (cu_seqlens_q is not None) else B + actual_max_seqlen_q = M + if cu_seqlens_q is not None: + if max_seqlen_q is None: + raise AssertionError( + "max_seqlen_q must not be None when cu_seqlens_q is provided" + ) + actual_max_seqlen_q = max_seqlen_q + actual_max_seqlen_k = max_seqlen_k if max_seqlen_k is not None else N + + if torch.version.hip is not None: + # ROCm efficient-attention backends return compact LSE. CUDA's + # memory-efficient attention kernel pads LSE to its kernel alignment. + logsumexp_dim = actual_max_seqlen_q if compute_log_sumexp else 0 + else: + logsumexp_dim = ( + math.ceil(actual_max_seqlen_q / 32) * 32 if compute_log_sumexp else 0 + ) + + logsum_exp = torch.empty( + (logsumexp_batch_dim, num_heads, logsumexp_dim), + dtype=torch.float, + device=query.device, + ) + + # See Note [Seed and Offset]: + seed = torch.empty((), dtype=torch.long, device="meta") + offset = torch.empty((), dtype=torch.long, device="meta") + + return res, logsum_exp, seed, offset, actual_max_seqlen_q, actual_max_seqlen_k + + +@register_meta( + [ + aten._efficient_attention_backward, + ] +) +def meta__efficient_attention_backward( + grad_out: Tensor, + query: Tensor, + key: Tensor, + value: Tensor, + bias: Tensor | None, + cu_seqlens_q: Tensor | None, + cu_seqlens_k: Tensor | None, + max_seqlen_q: torch.SymInt, + max_seqlen_k: torch.SymInt, + logsumexp: Tensor, + dropout_p: float, + philox_seed: Tensor, + philox_offset: Tensor, + custom_mask_type: int, + bias_requires_grad: bool, + scale: float | None = None, + num_splits_key: int | None = None, + shared_storage_dqdkdv: bool = False, +): + if shared_storage_dqdkdv: + torch._check( + query.shape[1] == key.shape[1], + lambda: "seqlen must match for `shared_storage_dqdkdv", + ) + torch._check( + query.shape[3] == key.shape[3], + lambda: "embedding dim must match for `shared_storage_dqdkdv", + ) + torch._check( + query.shape[2] == key.shape[2], + lambda: "num heads must match for `shared_storage_dqdkdv", + ) + chunk = torch.empty( + (*query.shape[0:-2], 3, query.shape[-2], query.shape[-1]), + dtype=query.dtype, + device=query.device, + ) + grad_query = chunk.select(-3, 0) + grad_key = chunk.select(-3, 1) + grad_value = chunk.select(-3, 2) + else: + grad_query = torch.empty_like(query) + grad_key = torch.empty_like(key) + grad_value = torch.empty_like(value) + + if bias is not None: + lastDim = bias.size(-1) + lastDimAligned = lastDim if lastDim % 16 == 0 else lastDim + 16 - lastDim % 16 + new_sizes = list(bias.size()) + new_sizes[-1] = lastDimAligned + grad_bias = torch.empty(new_sizes, dtype=bias.dtype, device=bias.device) + grad_bias = grad_bias[..., :lastDim] + else: + grad_bias = torch.empty((), device=query.device) + + return grad_query, grad_key, grad_value, grad_bias + + +def _check_scaled_mm_sizes( + self: torch.Tensor, + mat2: torch.Tensor, + scale_a: torch.Tensor, + scale_b: torch.Tensor, + bias: torch.Tensor | None = None, + scale_result: torch.Tensor | None = None, + out_dtype: torch.dtype | None = None, + use_fast_accum: bool = False, +): + def is_fp8_or_fp4_type(dtype): + return dtype in ( + torch.float8_e4m3fn, + torch.float8_e5m2, + torch.float8_e4m3fnuz, + torch.float8_e5m2fnuz, + torch.float4_e2m1fn_x2, + ) + + torch._check( + self.dim() == 2 and mat2.dim() == 2, + lambda: f"Inputs must be 2D but got self.dim()={self.dim()} and mat2.dim()={mat2.dim()}", + ) + torch._check( + is_fp8_or_fp4_type(self.dtype) and is_fp8_or_fp4_type(mat2.dtype), + lambda: f"Expected both inputs to be fp8 or fp4 types but got self.dtype={self.dtype} and mat2.dtype={mat2.dtype}", + ) + + if ( + device_hint(self) == "cuda" + or device_hint(self) == "xpu" + or device_hint(self) == "cpu" + ): + + def is_row_major(stride): + return stride[0] > stride[1] and stride[1] == 1 + + def is_col_major(stride): + return stride[0] == 1 and stride[1] > 1 + + def has_zero_dim(tensor_2d): + return tensor_2d.size(0) == 0 or tensor_2d.size(1) == 0 + + if device_hint(self) != "cpu": + torch._check( + is_row_major(self.stride()) or has_zero_dim(self), + lambda: f"self must be row_major, got stride {self.stride()}", + ) + torch._check( + is_col_major(mat2.stride()) or has_zero_dim(mat2), + lambda: f"mat2 must be col_major, got stride {mat2.stride()}", + ) + torch._check( + self.size(1) % 16 == 0, + lambda: f"Expected self.size(1) to be divisible by 16, but got self.size(1)={self.size(1)}", + ) + torch._check( + mat2.size(0) % 16 == 0 and mat2.size(1) % 16 == 0, + lambda: f"Expected both dimensions of mat2 to be divisible by 16 but got {mat2.shape}", + ) + + # determine scaling type and check input dimensions (refer to Blas.cpp op) + + m, _k = self.shape + n = mat2.size(1) + + is_blockwise_scaling = ( + ( + scale_a.dtype == torch.float8_e8m0fnu + and scale_b.dtype == torch.float8_e8m0fnu + ) + or ( + scale_a.dtype == torch.float8_e4m3fn + and scale_b.dtype == torch.float8_e4m3fn + ) + ) # note: this applies to blockwise scaling for non-FP8 types (FP8 accepts FP32 scales) + + if scale_a.numel() == 1 and scale_b.numel() == 1: + # tensorwise scaling + torch._check( + scale_a.dtype == torch.float32 and scale_b.dtype == torch.float32, + lambda: "For tensorwise scaling, both scale_a and scale_b must be float (fp32) tensors.", + ) + elif is_blockwise_scaling: + # blockwise scaling + + if scale_a.dtype == torch.float8_e4m3fn: + # NVIDIA's nvfp4 recipe: + # * block size is 16 elements packed (32 unpacked) + # * _k needs to be translated to the unpacked version + block_size_k = 16 + _k = _k * 2 + else: + block_size_k = 32 + if self.dtype == torch.float4_e2m1fn_x2: + _k = _k * 2 + + block_size_mn = 128 + + num_k_blocks = ceil_div(_k, block_size_k) + + if device_hint(self) == "xpu": + # XPU (oneDNN) uses unswizzled, unpadded blockwise scale shapes, + # unlike the L4-padded SWIZZLE_32_4_4 layout CUDA expects. + expected_a_size = num_k_blocks * m + expected_b_size = num_k_blocks * n + else: + padded_num_k_blocks = ceil_div(num_k_blocks, 4) * 4 + + expected_a_size = ( + block_size_mn * ceil_div(m, block_size_mn) * padded_num_k_blocks + ) + expected_b_size = ( + block_size_mn * ceil_div(n, block_size_mn) * padded_num_k_blocks + ) + + if ( + scale_a.numel() == expected_a_size + and scale_b.numel() == expected_b_size + ): + if device_hint(self) == "xpu": + torch._check( + scale_a.is_contiguous() or scale_a.t().is_contiguous(), + lambda: "scale_a must be contiguous or column-major contiguous", + ) + torch._check( + scale_b.is_contiguous() or scale_b.t().is_contiguous(), + lambda: "scale_b must be contiguous or column-major contiguous", + ) + else: + torch._check( + scale_a.is_contiguous(), + lambda: "scale_a must be contiguous", + ) + torch._check( + scale_b.is_contiguous(), + lambda: "scale_b must be contiguous", + ) + else: + torch._check( + False, + lambda: ( + "Invalid blockwise scaling configuration. " + f"For blockwise scaling, scale_a should have {expected_a_size} elements, got {scale_a.numel()}, " + f"scale_b should have {expected_b_size} elements, got {scale_b.numel()}." + ), + ) + else: + torch._check( + scale_a.dtype == torch.float32 and scale_b.dtype == torch.float32, + lambda: "For rowwise scaling, both scale_a and scale_b must be float (fp32) tensors.", + ) + # for rowwise scaling, enforce 2D input tensors + torch._check( + scale_a.dim() == 2 and scale_b.dim() == 2, + lambda: f"For non-tensorwise scaling, scale tensors must be 2D, but got {scale_a.dim()=} and {scale_b.dim()=}", + ) + + if ( + scale_a.size(0) == m + and scale_a.size(1) == 1 + and scale_b.size(0) == 1 + and scale_b.size(1) == n + ): + # rowwise scaling + torch._check( + scale_a.is_contiguous() and scale_b.is_contiguous(), + lambda: "Both scale_a and scale_b must be contiguous for rowwise scaling.", + ) + elif ( + scale_a.size(0) == m + and scale_a.size(1) == scale_b.size(0) == ceil_div(_k, 128) + and scale_b.size(1) == ceil_div(n, 128) + ): + # (BlockWise1x128, BlockWise128x128) + pass # do nothing, but do not error + elif ( + scale_a.size(0) == m + and scale_a.size(1) == scale_b.size(0) == ceil_div(_k, 128) + and scale_b.size(1) == n + ): + # (BlockWise1x128, BlockWise1x128) + pass # do nothing, but do not error + elif ( + scale_a.size(0) == ceil_div(m, 128) + and scale_a.size(1) == scale_b.size(0) == ceil_div(_k, 128) + and scale_b.size(1) == n + ): + # (BlockWise128x128, BlockWise1x128) + pass # do nothing, but do not error + else: + # does not match any valid scaling type + torch._check( + False, + lambda: ( + "Invalid scaling configuration. " + "For tensorwise scaling, both scales should be scalar. " + f"For rowwise scaling, scale_a should be ({m}, 1), scale_b should be (1, {n}). " + f"For (BlockWise1x128, BlockWise128x128), scale_a should be ({m}, {ceil_div(_k, 128)}), " + + f"scale_b should be ({ceil_div(_k, 128)}, {ceil_div(n, 128)}). " + f"For (BlockWise1x128, BlockWise1x128), scale_a should be ({m}, {ceil_div(_k, 128)}), " + + f"scale_b should be ({ceil_div(_k, 128)}, {n}). " + f"For (BlockWise128x128, BlockWise1x128), scale_a should be ({ceil_div(m, 128)}, {ceil_div(_k, 128)}), " + + f"scale_b should be ({ceil_div(_k, 128)}, {n}). " + f"Got scale_a.size()=({scale_a.size(0)}, {scale_a.size(1)}) " + f"and scale_b.size()=({scale_b.size(0)}, {scale_b.size(1)})" + ), + ) + + _out_dtype = out_dtype if out_dtype is not None else self.dtype + return torch.empty(self.size(0), mat2.size(1), dtype=_out_dtype, device=self.device) + + +@register_meta([aten._scaled_mm.default]) +def meta_scaled_mm( + self: torch.Tensor, + mat2: torch.Tensor, + scale_a: torch.Tensor, + scale_b: torch.Tensor, + bias: torch.Tensor | None = None, + scale_result: torch.Tensor | None = None, + out_dtype: torch.dtype | None = None, + use_fast_accum: bool = False, +): + return _check_scaled_mm_sizes( + self, mat2, scale_a, scale_b, bias, scale_result, out_dtype, use_fast_accum + ) + + +@register_meta([aten._scaled_mm_v2.default]) +def meta_scaled_mm_v2( + self: torch.Tensor, + mat2: torch.Tensor, + scale_a: list[torch.Tensor], + scale_recipe_a: list[int], + swizzle_a: list[int], + scale_b: list[torch.Tensor], + scale_recipe_b: list[int], + swizzle_b: list[int], + bias: torch.Tensor | None = None, + out_dtype: torch.dtype | None = None, + contraction_dim: list[int] | None = None, + use_fast_accum: bool = False, +): + # Shape inference only; per-recipe scale validation lives in the C++ + # TORCH_META_FUNC (validate_scaled_mm_v2_inputs) and runs in eager. This + # Python meta exists because the structured C++ meta sizes its output via + # IntArrayRef, which specializes symbolic dims under fake-tensor tracing + # (breaking mark_dynamic and unbacked symints). Same pattern as meta_mm. + torch._check( + self.dim() == 2 and mat2.dim() == 2, + lambda: f"Inputs must be 2D but got self.dim()={self.dim()} and mat2.dim()={mat2.dim()}", + ) + if contraction_dim: + torch._check( + self.size(contraction_dim[0]) == mat2.size(contraction_dim[1]), + lambda: ( + f"mat_a and mat_b shapes cannot be multiplied ({self.shape} and {mat2.shape}) " + f"with contraction dims mat_a: {contraction_dim[0]}, mat_b: {contraction_dim[1]}" + ), + ) + else: + torch._check( + self.size(1) == mat2.size(0), + lambda: f"mat_a and mat_b shapes cannot be multiplied ({self.shape} and {mat2.shape})", + ) + torch._check( + bias is None or bias.numel() == mat2.size(1), + lambda: f"Bias must be size {mat2.size(1)} but got {bias.numel()}", # type: ignore[union-attr] + ) + + _out_dtype = out_dtype if out_dtype is not None else self.dtype + return torch.empty(self.size(0), mat2.size(1), dtype=_out_dtype, device=self.device) + + +@register_meta([aten.scatter_reduce.two, aten.scatter_reduce.two_out]) +@out_wrapper() +def meta_scatter_reduce_two(self, dim, index, src, reduce, include_self=True): + scatter_meta_impl(self, dim, index, src, reduce, use_new_options=True) + return self.new_empty(self.shape) + + +@register_meta(aten.scatter_reduce_.two) +def meta_scatter_reduce__two(self, dim, index, src, reduce, include_self=True): + scatter_meta_impl(self, dim, index, src, reduce, use_new_options=True) + return self + + +@register_meta([aten.multinomial.default, aten.multinomial.out]) +@out_wrapper() +def meta_multinomial(input, num_samples, replacement=False, *, generator=None): + torch._check( + 0 < input.dim() <= 2, + lambda: f"The probability distributions dimensions must be 1 or 2, but got {input.dim()}", + ) + if input.dim() == 1: + return torch.empty(num_samples, dtype=torch.long, device=input.device) + return torch.empty( + input.size(0), num_samples, dtype=torch.long, device=input.device + ) + + +def multiply_integers(vs): + r = 1 + for v in vs: + r *= v + return r + + +def upsample_common_check(input_size, output_size, num_spatial_dims): + torch._check( + len(output_size) == num_spatial_dims, + lambda: f"It is expected output_size equals to {num_spatial_dims}, but got size {len(output_size)}", + ) + expected_input_dims = num_spatial_dims + 2 # N, C, ... + torch._check( + len(input_size) == expected_input_dims, + lambda: f"It is expected input_size equals to {expected_input_dims}, but got size {len(input_size)}", + ) + + torch._check( + all(s > 0 for s in input_size[2:]) and all(s > 0 for s in output_size), + lambda: f"Input and output sizes should be greater than 0, but got " + f"input size {input_size} and output size {output_size}", + ) + + nbatch, channels = input_size[:2] + return (nbatch, channels, *output_size) + + +@register_meta( + [aten.upsample_nearest1d.default, aten._upsample_nearest_exact1d.default] +) +def upsample_nearest1d(input, output_size, scales=None): + torch._check( + input.numel() != 0 or multiply_integers(input.size()[1:]), + lambda: f"Non-empty 3D data tensor expected but got a tensor with sizes {input.size()}", + ) + full_output_size = upsample_common_check( + input.size(), output_size, num_spatial_dims=1 + ) + return input.new_empty(full_output_size).to( + memory_format=utils.suggest_memory_format(input) + ) + + +@register_meta( + [aten.upsample_nearest2d.default, aten._upsample_nearest_exact2d.default] +) +def upsample_nearest2d(input, output_size, scales_h=None, scales_w=None): + torch._check( + input.numel() != 0 or multiply_integers(input.size()[1:]), + lambda: f"Non-empty 4D data tensor expected but got a tensor with sizes {input.size()}", + ) + full_output_size = upsample_common_check( + input.size(), output_size, num_spatial_dims=2 + ) + output = input.new_empty(full_output_size) + + # convert output to correct memory format, if necessary + memory_format = utils.suggest_memory_format(input) + + # following "heuristic: only use channels_last path when it's faster than the contiguous path" + _, n_channels, _, _ = input.shape + if input.device.type == "cuda" and n_channels < 4: + memory_format = torch.contiguous_format + + output = output.contiguous(memory_format=memory_format) + + return output + + +@register_meta( + [ + aten.upsample_nearest2d_backward.default, + aten._upsample_nearest_exact2d_backward.default, + ] +) +def upsample_nearest2d_backward( + grad_output: Tensor, + output_size: Sequence[int | torch.SymInt], + input_size: Sequence[int | torch.SymInt], + scales_h: float | None = None, + scales_w: float | None = None, +): + full_output_size = upsample_common_check( + input_size, output_size, num_spatial_dims=2 + ) + torch._check( + grad_output.ndim == 4, + lambda: f"Expected grad_output to be a tensor of dimension 4 but got: dimension {grad_output.ndim}", + ) + for i in range(4): + torch._check( + grad_output.size(i) == full_output_size[i], + lambda: ( + f"Expected grad_output to have the same shape as output;" + f" output.size({i}) = {full_output_size[i]}" + f" but got grad_output.size({i}) = {grad_output.size(i)}" + ), + ) + + return grad_output.new_empty(input_size).to( + memory_format=utils.suggest_memory_format(grad_output) + ) # type: ignore[call-overload] + + +@register_meta( + [aten.upsample_nearest3d.default, aten._upsample_nearest_exact3d.default] +) +def upsample_nearest3d(input, output_size, scales_d=None, scales_h=None, scales_w=None): + torch._check( + input.numel() != 0 or multiply_integers(input.size()[1:]), + lambda: f"Non-empty 5D data tensor expected but got a tensor with sizes {input.size()}", + ) + full_output_size = upsample_common_check( + input.size(), output_size, num_spatial_dims=3 + ) + return input.new_empty(full_output_size).to( + memory_format=utils.suggest_memory_format(input) + ) + + +@register_meta( + [ + aten.sort.default, + aten.sort.stable, + aten.sort.values, + aten.sort.values_stable, + ] +) +def meta_sort(self, stable=None, dim=-1, descending=False, values=None, indices=None): + v, i = torch.empty_like(self), torch.empty_like(self, dtype=torch.int64) + if values is not None and indices is not None: + if not isinstance(values, TensorLike): + raise AssertionError(f"values must be TensorLike, got {type(values)}") + if not isinstance(indices, TensorLike): + raise AssertionError(f"indices must be TensorLike, got {type(indices)}") + # Makes sure values and indices have the same strides. For cases where + # these have different shapes, like (5, 10, 5) and (0) in msort. + out_shape = v.shape + out_stride = v.stride() + values = _maybe_resize_out(values, out_shape) + indices = _maybe_resize_out(indices, out_shape) + values.as_strided_(out_shape, out_stride) + indices.as_strided_(out_shape, out_stride) + _safe_copy_out(copy_from=v, copy_to=values) # type: ignore[arg-type] + _safe_copy_out(copy_from=i, copy_to=indices) # type: ignore[arg-type] + return values, indices + return v, i + + +def rnn_cell_checkSizes( + input_gates, + hidden_gates, + input_bias, + hidden_bias, + factor, + prev_hidden, +): + torch._check(input_gates.ndim == 2, lambda: f"{input_gates.ndim} != 2") + torch._check( + input_gates.shape == hidden_gates.shape, + lambda: f"{input_gates.shape} != {hidden_gates.shape}", + ) + gates_size = input_gates.size(1) + if input_bias is not None: + torch._check(input_bias.ndim == 1, lambda: f"{input_bias.ndim} != 1") + torch._check( + input_bias.numel() == gates_size, + lambda: f"{input_bias.numel()} != {gates_size}", + ) + torch._check( + input_bias.shape == hidden_bias.shape, + lambda: f"{input_bias.shape} != {hidden_bias.shape}", + ) + torch._check(prev_hidden.ndim == 2, lambda: f"{prev_hidden.ndim} != 2") + expected_prev_hidden_numel = input_gates.size(0) * gates_size // factor + torch._check( + prev_hidden.numel() == expected_prev_hidden_numel, + lambda: f"{prev_hidden.numel()} != {input_gates.size(0)} * {gates_size} // {factor} (aka {expected_prev_hidden_numel})", + ) + torch._check( + all( + x.device == input_gates.device + for x in [hidden_gates, input_bias, hidden_bias, prev_hidden] + ), + lambda: "expected all inputs to be same device", + ) + + +@register_meta(aten._thnn_fused_lstm_cell.default) +def _thnn_fused_lstm_cell_meta( + input_gates, + hidden_gates, + cx, + input_bias=None, + hidden_bias=None, +): + rnn_cell_checkSizes(input_gates, hidden_gates, input_bias, hidden_bias, 4, cx) + workspace = torch.empty_like(input_gates, memory_format=torch.contiguous_format) + hy = torch.empty_like(cx, memory_format=torch.contiguous_format) + cy = torch.empty_like(cx, memory_format=torch.contiguous_format) + return (hy, cy, workspace) + + +@register_meta(aten._cudnn_rnn.default) +def _cudnn_rnn( + input, + weight, + weight_stride0, + weight_buf, + hx, + cx, + mode, + hidden_size, + proj_size, + num_layers, + batch_first, + dropout, + train, + bidirectional, + batch_sizes, + dropout_state, +): + is_input_packed = len(batch_sizes) != 0 + if is_input_packed: + seq_length = len(batch_sizes) + mini_batch = batch_sizes[0] + batch_sizes_sum = input.shape[0] + else: + seq_length = input.shape[1] if batch_first else input.shape[0] + mini_batch = input.shape[0] if batch_first else input.shape[1] + batch_sizes_sum = -1 + + num_directions = 2 if bidirectional else 1 + out_size = proj_size if proj_size != 0 else hidden_size + if is_input_packed: + out_shape = [batch_sizes_sum, out_size * num_directions] + else: + out_shape = ( + [mini_batch, seq_length, out_size * num_directions] + if batch_first + else [seq_length, mini_batch, out_size * num_directions] + ) + output = input.new_empty(out_shape) + + cell_shape = [num_layers * num_directions, mini_batch, hidden_size] + if cx is None: + cy = torch.empty(0, device=input.device) + else: + cy = cx.new_empty(cell_shape) + + hy = hx.new_empty([num_layers * num_directions, mini_batch, out_size]) + + # TODO: Query cudnnGetRNNTrainingReserveSize (expose to python) + reserve_shape = 0 if train else 0 + reserve = input.new_empty(reserve_shape, dtype=torch.uint8) + + return output, hy, cy, reserve, weight_buf + + +@register_meta(aten.miopen_rnn.default) +def miopen_rnn( + input, + weight, + weight_stride0, + # weight_buf, + hx, + cx, + mode, + hidden_size, + # proj_size, + num_layers, + batch_first, + dropout, + train, + bidirectional, + batch_sizes, + dropout_state, +): + total_weight_elems = 0 + for w in weight: + if w.numel() > 0: + total_weight_elems += w.numel() + + weight_buf = input.new_empty((total_weight_elems,)) + return _cudnn_rnn( + input, + weight, + weight_stride0, + weight_buf, + hx, + cx, + mode, + hidden_size, + 0, + num_layers, + batch_first, + dropout, + train, + bidirectional, + batch_sizes, + dropout_state, + ) + + +@register_meta(aten.mkldnn_rnn_layer.default) +def mkldnn_rnn_layer( + input, + w0, + w1, + w2, + w3, + hx_, + cx_, + reverse, + batch_sizes, + mode, + hidden_size, + num_layers, + has_biases, + bidirectional, + batch_first, + train, +): + seq_length = input.shape[1] if batch_first else input.shape[0] + mini_batch = input.shape[0] if batch_first else input.shape[1] + output_chanels = hidden_size + out_shape = ( + [mini_batch, seq_length, output_chanels] + if batch_first + else [seq_length, mini_batch, output_chanels] + ) + output = input.new_empty(out_shape) + if hx_ is None: + hy = torch.empty(0, device=input.device) + else: + hy = hx_.new_empty(hx_.shape) + if cx_ is None: + cy = torch.empty(0, device=input.device) + else: + cy = cx_.new_empty(cx_.shape) + workspace = torch.empty(0, device=input.device, dtype=torch.uint8) + return output, hy, cy, workspace + + +def zero_numel_check_dims(self, dim, fn_name): + if self.ndim == 0: + torch._check_index( + dim == 0 or dim == -1, + lambda: f"{fn_name}: Expected reduction dim -1 or 0 for scalar but got {dim}", + ) + else: + torch._check_index( + self.size(dim) != 0, + lambda: f"{fn_name}: Expected reduction dim {dim} to have non-zero size.", + ) + + +# From aten/src/ATen/native/ReduceOps.cpp +def check_argmax_argmin(name, self, dim): + if dim is not None: + dim = maybe_wrap_dim(dim, self.dim()) + zero_numel_check_dims(self, dim, name) + else: + torch._check( + self.numel() != 0, + lambda: f"{name}: Expected reduction dim to be specified for input.numel() == 0.", + ) + + +@register_meta([aten.argmax.default, aten.argmin.default]) +def argmax_argmin_meta(self, dim=None, keepdim=False): + check_argmax_argmin("argmax", self, dim) + dims = utils.reduction_dims(self.shape, (dim,) if dim is not None else None) + shape = _compute_reduction_shape(self, dims, keepdim) + return self.new_empty(shape, dtype=torch.int64) + + +@register_meta(aten.scalar_tensor.default) +def scalar_tensor(s, dtype=None, layout=None, device=None, pin_memory=None): + # NB: It's always wrong to try to create a scalar tensor with the jagged layout. + # Rather than fix this everywhere, just use the strided layout and let NJT handle + # scalar tensor broadcasting. + if layout == torch.jagged: + layout = torch.strided + return torch.empty( + (), dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_meta(aten.topk.default) +def topk_meta(self, k, dim=-1, largest=True, sorted=True): + # From aten/src/ATen/native/Sorting.cpp + dim = maybe_wrap_dim(dim, self.dim(), wrap_scalar=True) + sliceSize = 1 if self.dim() == 0 else self.size(dim) + torch._check(k >= 0) + torch._check(k <= sliceSize, lambda: "k not in range for dimension") + + topKSize = list(self.shape) + if len(topKSize) > 0: + topKSize[dim] = k + return self.new_empty(topKSize), self.new_empty(topKSize, dtype=torch.int64) + + +@register_meta(aten._segment_reduce_backward) +@out_wrapper() +def meta__segment_reduce_backward( + grad, output, data, reduce, lengths=None, offsets=None, axis=0, initial=None +): + if lengths is None and offsets is None: + raise AssertionError( + "segment_reduce(): Either lengths or offsets must be defined" + ) + data_contig = data.contiguous() + grad_contig = grad.contiguous() + return torch.empty_like( + data_contig, + dtype=grad_contig.dtype, + device=grad_contig.device, + layout=grad_contig.layout, + ) + + +@register_meta([aten.kthvalue.default, aten.kthvalue.values]) +@out_wrapper("values", "indices") +def kthvalue_meta(self, k, dim=-1, keepdim=False): + from torch.fx.experimental.symbolic_shapes import sym_and + + dim = maybe_wrap_dim(dim, self.dim(), wrap_scalar=True) + dimSize = self.size(dim) if self.dim() > 0 else 1 + torch._check( + sym_and(k >= 1, k <= dimSize), + lambda: f"kthvalue(): selected number k out of range for dimension {dim}", + ) + + shape = list(self.shape[:dim] + self.shape[dim + 1 :]) + if keepdim and self.dim() > 0: + shape.insert(dim, 1) + return self.new_empty(shape), self.new_empty(shape, dtype=torch.int64) + + +legacy_contiguous_memory_format = torch.contiguous_format + + +# From aten/src/ATen/native/cuda/RNN.cu +def checkLSTMBackwardSizes(grad_hy, grad_cy, cx, cy, workspace): + defined_grad = grad_hy if grad_hy is not None else grad_cy + torch._check(defined_grad.dim() == 2, lambda: "") + exp_size = defined_grad.size() + if grad_hy is not None: + torch._check(grad_hy.size() == exp_size, lambda: "") + if grad_cy is not None: + torch._check(grad_cy.size() == exp_size, lambda: "") + torch._check(cx.size() == exp_size, lambda: "") + torch._check(cy.size() == exp_size, lambda: "") + torch._check(workspace.dim() == 2, lambda: "") + torch._check(workspace.numel() == exp_size[0] * exp_size[1] * 4, lambda: "") + + +# From aten/src/ATen/native/cuda/RNN.cu +@register_meta(aten._thnn_fused_lstm_cell_backward_impl.default) +def _thnn_fused_lstm_cell_backward_impl(grad_hy, grad_cy, cx, cy, workspace, has_bias): + if grad_hy is None and grad_cy is None: + return None, None, None + checkLSTMBackwardSizes(grad_hy, grad_cy, cx, cy, workspace) + grad_gates = torch.empty_like( + workspace, memory_format=legacy_contiguous_memory_format + ) + grad_cx = torch.empty_like(cx, memory_format=legacy_contiguous_memory_format) + grad_bias = grad_gates.sum(0, keepdim=False) if has_bias else None + return grad_gates, grad_cx, grad_bias + + +# From aten/src/ATen/native/mps/operations/Linear.mm +@register_meta(aten.linear_backward.default) +def linear_backward(input_, grad_output_, weight_, output_mask): + grad_input = None + grad_weight = None + grad_bias = None + if output_mask[0]: + grad_input = grad_output_.new_empty(input_.size()) + if output_mask[1] or output_mask[2]: + grad_weight = grad_output_.new_empty((grad_output_.size(-1), input_.size(-1))) + grad_bias = grad_output_.new_empty(grad_output_.size(-1)) + return (grad_input, grad_weight, grad_bias) + + +@register_meta(aten.pixel_shuffle.default) +def meta_pixel_shuffle(self, upscale_factor): + torch._check( + len(self.shape) > 2, + lambda: f"Invalid input shape for pixel_shuffle: {self.shape}", + ) + torch._check( + self.shape[-3] % (upscale_factor * upscale_factor) == 0, + lambda: f"Invalid input shape for pixel_shuffle: {self.shape} with upscale_factor = {upscale_factor}", + ) + + def pick_memory_format(): + # DDE-safe variant of the original eager-style picker. + # Eager dispatch for pixel_shuffle (native_functions.yaml:4720): + # CPU -> pixel_shuffle_cpu: at::empty({0}, self.options()).resize_( + # out_sizes, self.suggest_memory_format()) -> preserves NHWC/NDHWC + # MPS -> pixel_shuffle_mps: at::empty(out_shape, self.options()) + # self.options() does NOT carry a memory_format, so this is + # always plain contiguous regardless of input layout. + # else -> math_pixel_shuffle: clone(MemoryFormat::Contiguous) -> contiguous + # So only CPU preserves channels_last; everything else is contiguous. + fmt = suggest_memory_format(self) + if ( + fmt is torch.channels_last or fmt is torch.channels_last_3d + ) and device_hint(self) == "cpu": + return fmt + return torch.contiguous_format + + C = self.shape[-3] // (upscale_factor * upscale_factor) + Hr = self.shape[-2] * upscale_factor + Wr = self.shape[-1] * upscale_factor + out_shape = (*self.shape[:-3], C, Hr, Wr) + + # Build the output tensor with the right strides directly. We avoid + # `new_empty(...).to(memory_format=...)` because `Tensor.to(memory_format=...)` + # internally calls the eager `is_contiguous(memory_format=...)` predicate to + # decide whether to no-op, and that predicate can DDE on unbacked sizes. + fmt = pick_memory_format() + if fmt is torch.channels_last or fmt is torch.channels_last_3d: + out_strides = make_channels_last_strides_for(out_shape) + else: + out_strides = make_contiguous_strides_for(out_shape) + return torch.empty_strided( + out_shape, out_strides, dtype=self.dtype, device=self.device + ) + + +@register_meta(aten.mkldnn_rnn_layer_backward.default) +def mkldnn_rnn_layer_backward( + input, + weight0, + weight1, + weight2, + weight3, + hx_, + cx_tmp, + output, + hy_, + cy_, + grad_output_r_opt, + grad_hy_r_opt, + grad_cy_r_opt, + reverse, + mode, + hidden_size, + num_layers, + has_biases, + train, + bidirectional, + batch_sizes, + batch_first, + workspace, +): + diff_x = input.new_empty(input.shape, dtype=torch.float) + diff_hx = hx_.new_empty(hx_.shape, dtype=torch.float) + diff_cx = cx_tmp.new_empty(cx_tmp.shape, dtype=torch.float) + diff_w1 = weight0.new_empty(weight0.shape, dtype=torch.float) + diff_w2 = weight1.new_empty(weight1.shape, dtype=torch.float) + # C++ computes bias = _shuffle_bias(weight2, weight3, mode) before + # creating diff_b. num_bias_gates: LSTM=4, GRU=4, RNN_RELU/TANH=1. + # GRU _shuffle_bias produces [4*hidden] from two [3*hidden] inputs. + # LSTM: bias_ih + bias_hh preserves [4*hidden]. + # RNN: bias_ih + bias_hh preserves [hidden]. + _GRU_MODE = 3 + if mode == _GRU_MODE: + bias_size = 4 * hidden_size + else: + bias_size = weight2.shape[0] + diff_b = weight2.new_empty([bias_size], dtype=torch.float) + return diff_x, diff_w1, diff_w2, diff_b, diff_b, diff_hx, diff_cx + + +@register_meta([aten.bucketize.Tensor, aten.bucketize.Tensor_out]) +@out_wrapper() +def meta_bucketize(self, boundaries, *, out_int32=False, right=False): + return torch.empty_like( + self, + dtype=torch.int32 if out_int32 else torch.int64, + memory_format=torch.contiguous_format, + ) + + +@register_meta([aten.bucketize.Scalar, aten.bucketize.Scalar_out]) +def meta_bucketize_scalar( + self: NumberType, + boundaries: Tensor, + *, + out_int32: bool = False, + right: bool = False, +): + return boundaries.new_empty( + (), + dtype=torch.int32 if out_int32 else torch.int64, + ) + + +@register_meta([aten.histc]) +@out_wrapper() +def meta_histc(input, bins=100, min=0, max=0): + fn_name = "histc()" + if device_hint(input) == "cpu": + torch._check( + input.is_floating_point(), + lambda: f"\"histogram_cpu\" not implemented for '{input.dtype}'", + ) + if device_hint(input) == "cuda" and input.is_floating_point(): + utils.alert_not_deterministic("_histc_cuda with floating point input") + torch._check( + isinstance(bins, IntLike), + lambda: f"{fn_name}: argument 'bins' must be int, not {type(bins)}", + ) + torch._check(bins > 0, lambda: f"{fn_name}: bins must be > 0, but got {bins}") + torch._check( + isinstance(min, Number), + lambda: f"{fn_name}: argument 'min' must be Number, not {type(min)}", + ) + torch._check( + isinstance(max, Number), + lambda: f"{fn_name}: argument 'max' must be Number, not {type(max)}", + ) + torch._check(max >= min, lambda: f"{fn_name}: max must be larger than min") + return torch.empty(bins, device=input.device, dtype=input.dtype) + + +@register_meta( + [ + aten._upsample_bilinear2d_aa.default, + aten._upsample_bicubic2d_aa.default, + aten._upsample_lanczos2d_aa.default, + ] +) +def meta_upsample_bimode2d_aa( + input, + output_size, + align_corners, + scales_h=None, + scales_w=None, +): + full_output_size = upsample_common_check( + input.size(), output_size, num_spatial_dims=2 + ) + torch._check( + input.numel() != 0 or all(size > 0 for size in input.size()[1:]), + lambda: f"Non-empty 4D data tensor expected but got a tensor with sizes {input.size()}", + ) + return input.new_empty(full_output_size).to( + memory_format=utils.suggest_memory_format(input) + ) + + +@register_meta( + [ + aten._upsample_bilinear2d_aa_backward.default, + aten._upsample_lanczos2d_aa_backward.default, + ] +) +def meta_upsample_bimode2d_aa_backward( + grad_output, + output_size, + input_size, + align_corners, + scales_h=None, + scales_w=None, +): + full_output_size = upsample_common_check( + input_size, output_size, num_spatial_dims=2 + ) + torch._check( + grad_output.ndim == 4, + lambda: f"Expected grad_output to be a tensor of dimension 4 but got: dimension {grad_output.ndim}", + ) + for i in range(4): + torch._check( + grad_output.shape[i] == full_output_size[i], + lambda: f""" +Expected grad_output to have the same shape as output; output.size({i}) = {full_output_size[i]} +but got grad_output_size({i}) = {grad_output.size(i)}""", + ) + return grad_output.new_empty(input_size).to( + memory_format=utils.suggest_memory_format(grad_output) + ) + + +# From aten/src/ATen/native/cuda/AmpKernels.cu +@register_meta(aten._amp_foreach_non_finite_check_and_unscale_.default) +def _amp_foreach_non_finite_check_and_unscale_(self, found_inf, inv_scale): + torch._check( + found_inf.numel() == 1, lambda: "found_inf must be a 1-element tensor." + ) + torch._check( + inv_scale.numel() == 1, lambda: "inv_scale must be a 1-element tensor." + ) + torch._check( + found_inf.dtype.is_floating_point, + lambda: "found_inf must be a float tensor.", + ) + torch._check( + inv_scale.dtype.is_floating_point, + lambda: "inv_scale must be a float tensor.", + ) + + +# From aten/src/ATen/native/UnaryOps.cpp +@register_meta([aten.nan_to_num.default, aten.nan_to_num.out]) +@out_wrapper() +def nan_to_num(self, nan=None, posinf=None, neginf=None): + return torch.empty_like(self) + + +@register_meta(torch.ops.aten.transpose_) +def transpose_(self, dim0, dim1): + if self.layout in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + }: + raise AssertionError( + f"torch.transpose_: in-place transposition is not supported for {self.layout} layout" + ) + + ndims = self.ndim + + dim0 = maybe_wrap_dim(dim0, ndims) + dim1 = maybe_wrap_dim(dim1, ndims) + + if dim0 == dim1: + return self + + size = list(self.size()) + stride = list(self.stride()) + + stride[dim0], stride[dim1] = stride[dim1], stride[dim0] + size[dim0], size[dim1] = size[dim1], size[dim0] + + self.as_strided_(size, stride) + return self + + +@register_meta(torch.ops.aten.t_) +def t_(self): + ndims = self.ndim + + if self.is_sparse: + sparse_dim = self.sparse_dim() + dense_dim = self.dense_dim() + if not (sparse_dim <= 2 and dense_dim == 0): + raise AssertionError( + f"t_ expects a tensor with <= 2 sparse and 0 dense dimensions, " + f"but got {sparse_dim} sparse and {dense_dim} dense dimensions" + ) + else: + if self.dim() > 2: + raise AssertionError( + f"t_ expects a tensor with <= 2 dimensions, but self is {ndims}D" + ) + + return transpose_(self, 0, 0 if ndims < 2 else 1) + + +@register_meta(aten.searchsorted) +@out_wrapper() +def meta_searchsorted( + sorted_sequence, + self, + *, + out_int32=False, + right=False, + side=None, + sorter=None, +): + # If the sorted_sequence is not one-dimensional, its shape must match that of values + # in all but the last dimension. + torch._check( + len(sorted_sequence.shape) <= 1 + or sorted_sequence.shape[:-1] == self.shape[:-1], + lambda: ( + "torch.searchsorted(): boundaries tensor should be 1 dimension or the " + "first N-1 dimensions of boundaries tensor and input value tensor must " + f"match, but we got boundaries tensor {list(sorted_sequence.shape)} and " + f"input value tensor {list(self.shape)}" + ), + ) + + # If a sorter array is provided, its dimensions must exactly match sorted_sequence. + torch._check( + sorter is None or sorted_sequence.shape == sorter.shape, + lambda: ( + "torch.searchsorted(): boundary and sorter must have the same size, but " + f"got boundary tensor {list(sorted_sequence.shape)} and got sorter tensor " + f"{list(sorter.shape) if sorter is not None else []}" + ), + ) + + # Per the docs, if side == "left" and right is True, we error. + torch._check( + side != "left" or not right, + lambda: "torch.searchsorted(): side and right can't be set to opposites, got side of " + "left while right was True", + ) + + dtype = torch.int32 if out_int32 else torch.int64 + if isinstance(self, torch.Tensor): + return torch.empty_like( + self, dtype=dtype, memory_format=torch.contiguous_format + ) + else: # Scalar + return torch.empty((), dtype=dtype, device=sorted_sequence.device) + + +def _check_for_unsupported_isin_dtype(dtype): + torch._check( + dtype not in (torch.bool, torch.complex128, torch.complex64), + lambda: f"Unsupported input type encountered for isin(): {dtype}", + ) + + +@register_meta(aten.embedding_dense_backward) +def meta_embedding_dense_backward( + grad_output, + indices, + num_weights, + padding_idx, + scale_grad_by_freq, +): + grad_weight = grad_output.new_empty((num_weights, grad_output.size(-1))) + return grad_weight + + +@register_meta(aten._embedding_bag_backward) +def meta_embedding_bag_backward( + grad, + indices, + offsets, + offset2bag, + bag_size, + maximum_indices, + num_weights, + scale_grad_by_freq, + mode, + sparse, + per_sample_weights, + padding_idx=-1, +): + if sparse: + return aten._embedding_bag_sparse_backward( + grad, + indices, + offsets, + offset2bag, + bag_size, + num_weights, + scale_grad_by_freq, + mode, + per_sample_weights, + padding_idx, + ) + else: + return meta_embedding_bag_dense_backward( + grad, + indices, + offset2bag, + bag_size, + maximum_indices, + num_weights, + scale_grad_by_freq, + mode, + per_sample_weights, + padding_idx, + ) + + +@register_meta(aten._embedding_bag_dense_backward) +def meta_embedding_bag_dense_backward( + grad, + indices, + offset2bag, + bag_size, + maximum_indices, + num_weights, + scale_grad_by_freq, + mode, + per_sample_weights, + padding_idx=-1, +): + torch._check( + grad.dtype in [torch.float16, torch.bfloat16, torch.float32, torch.float64], + lambda: f"Unsupported input type encountered: {grad.dtype}", + ) + if mode == MODE_MAX: + torch._check(maximum_indices is not None) + index_grad_weight = grad.new_empty((num_weights, grad.size(1))) + return index_grad_weight + + +@register_meta(aten._embedding_bag_per_sample_weights_backward) +def meta_embedding_bag_per_sample_weights_backward( + grad, + weight, + indices, + offsets, + offset2bag, + mode, + padding_idx=-1, +): + embedding_features = grad.size(1) + torch._check( + mode == MODE_SUM, + lambda: "embedding_bag_backward: per_sample_weights only supported for mode='sum'", + ) + torch._check(grad.dim() == 2) + torch._check(indices.dim() == 1) + num_samples = indices.size(0) + torch._check(weight.dim() == 2) + torch._check(weight.size(1) == embedding_features) + output = grad.new_empty((num_samples,)) + return output + + +@register_meta(aten.isin) +@out_wrapper() +def meta_isin(elements, test_elements, *, assume_unique=False, invert=False): + torch._check( + isinstance(elements, Tensor) or isinstance(test_elements, Tensor), + lambda: "At least one of elements and test_elements must be a Tensor.", + ) + if not isinstance(elements, Tensor): + elements = torch.tensor(elements, device=test_elements.device) + + if not isinstance(test_elements, Tensor): + test_elements = torch.tensor(test_elements, device=elements.device) + + _check_for_unsupported_isin_dtype(elements.dtype) + _check_for_unsupported_isin_dtype(test_elements.dtype) + return torch.empty_like(elements, dtype=torch.bool) + + +@register_meta(aten.polygamma) +@out_wrapper() +def meta_polygamma(n: int, self: Tensor) -> Tensor: + torch._check(n >= 0, lambda: "polygamma(n, x) does not support negative n.") + _, result_dtype = elementwise_dtypes( + self, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + return torch.empty_like(self, dtype=result_dtype) + + +@register_meta(aten._local_scalar_dense) +def meta_local_scalar_dense(self: Tensor): + raise RuntimeError("Tensor.item() cannot be called on meta tensors") + + +@register_meta(aten.silu) +@out_wrapper(exact_dtype=True) +def silu(self: Tensor) -> Tensor: + return torch.empty_like(self) + + +@register_meta(aten.sigmoid) +@out_wrapper() +def sigmoid(self: Tensor) -> Tensor: + _, result_dtype = elementwise_dtypes( + self, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + return torch.empty_like(self, dtype=result_dtype) + + +def _create_grouped_mm_output_tensor(mat1, mat2, offs, out_dtype): + mat1_is_2d = mat1.dim() == 2 + mat2_is_2d = mat2.dim() == 2 + + if mat1_is_2d: + if mat2_is_2d: + out_size = [offs.size(0), mat1.size(0), mat2.size(1)] + else: + torch._check( + offs.size(0) == mat2.size(0), lambda: "matrix batch sizes have to match" + ) + out_size = [mat1.size(0), mat2.size(-1)] + else: + if mat2_is_2d: + torch._check( + offs.size(0) == mat1.size(0), lambda: "matrix batch sizes have to match" + ) + out_size = [mat1.size(1), mat2.size(1)] + else: + # regular bmm + torch._check( + mat1.size(0) == mat2.size(0), lambda: "batched dimension has to match" + ) + out_size = [mat1.size(0), mat1.size(1), mat2.size(-1)] + + out_dtype = out_dtype or mat1.dtype + + if torch.version.cuda: + alignment = 16 // out_dtype.itemsize + size_padded = (out_size[-1] + alignment - 1) // alignment * alignment + if mat1_is_2d == mat2_is_2d: + out_stride = [out_size[1] * size_padded, size_padded, 1] + else: + out_stride = [size_padded, 1] + out = torch.empty_strided( + out_size, out_stride, dtype=out_dtype, device=mat1.device + ) + else: + out = torch.empty(out_size, dtype=out_dtype, device=mat1.device) + return out + + +def _meta_grouped_mm_common( + mat_a: Tensor, + mat_b: Tensor, + scale_a: torch.Tensor | None, + scale_b: torch.Tensor | None, + offs: Tensor | None = None, + bias: Tensor | None = None, + scale_result: torch.Tensor | None = None, + out_dtype: torch.dtype | None = None, + use_fast_accum: bool = False, +): + torch._check( + (scale_a is None) == (scale_b is None), + lambda: "Either both scale factors are given, or none", + ) + scaled = scale_a is not None and scale_b is not None + + # Implementing all the checks from + # _grouped_mm_cuda()/_scaled_grouped_mm_cuda() code in + # aten/src/ATen/native/cuda/Blas.cpp. + + if scaled: + fp8_dtype = torch.float8_e4m3fn + if ( + torch.version.hip + and torch.cuda.is_available() + and "gfx94" in torch.cuda.get_device_properties(0).gcnArchName + ): + fp8_dtype = torch.float8_e4m3fnuz + torch._check( + mat_a.dtype == fp8_dtype and mat_b.dtype == fp8_dtype, + lambda: f"Expected inputs of E4M3 FP8 type but got mat_a.dtype={mat_a.dtype} and mat_b.dtype={mat_b.dtype}.", + ) + elif mat_a.dtype == torch.bfloat16: + torch._check( + mat_b.dtype == mat_a.dtype, + lambda: f"Expected mat_b dtype to match mat_a dtype, got mat_a.dtype={mat_a.dtype} and mat_b.dtype={mat_b.dtype}.", + ) + elif mat_a.dtype == torch.float16: + torch._check( + mat_b.dtype == mat_a.dtype, + lambda: f"Expected mat_b dtype to match mat_a dtype, got mat_a.dtype={mat_a.dtype} and mat_b.dtype={mat_b.dtype}.", + ) + else: + torch._check( + False, + lambda: f"Expected mat_a to be BFloat16 or supported Float16 matrix, got {mat_a.dtype}.", + ) + + torch._check( + mat_a.dim() in [2, 3] and mat_b.dim() in [2, 3], + lambda: f"Multiplicands must be 2D or 3D but got mat_a.dim()={mat_a.dim()} and mat_b.dim()={mat_b.dim()}", + ) + + mat_a_is_2d = mat_a.dim() == 2 + mat_b_is_2d = mat_b.dim() == 2 + + if not mat_a_is_2d or not mat_b_is_2d: + torch._check( + mat_a.size(-1) == mat_b.size(-2), + lambda: "contraction dimension of mat_a and mat_b must match", + ) + + if scaled: + + def is_row_major(mat): + mat_stride = mat.stride() + return mat_stride[-2] > 1 and mat_stride[-1] == 1 + + def is_col_major(mat): + mat_stride = mat.stride() + return mat_stride[-2] == 1 and mat_stride[-1] > 1 + + torch._check( + is_row_major(mat_a), + lambda: f"Expected mat_a tensor to be row major in the last two dimensions, got strides {mat_a.stride()[-2:]}", + ) + torch._check( + is_col_major(mat_b), + lambda: f"Expected mat_b tensor to be column major in the last two dimensions, got strides {mat_b.stride()[-2:]}", + ) + + def check_valid_strides(mat_name, mat): + end_dim = mat.dim() - 1 + alignment = 16 // mat.element_size() + mat_stride = mat.stride() + if mat_stride[end_dim - 1] == 1 and mat_stride[end_dim] >= max( + 1, mat.shape[end_dim - 1] + ): + torch._check( + mat_stride[end_dim] % alignment == 0, + lambda: f"Expected {mat_name} stride along {end_dim} dim to be multiple of 16 bytes, got {mat_stride[end_dim]}.", + ) + elif mat_stride[end_dim] == 1 and mat_stride[end_dim - 1] >= max( + 1, mat.shape[end_dim] + ): + torch._check( + mat_stride[end_dim - 1] % alignment == 0, + lambda: f"Expected {mat_name} stride along {end_dim - 1} dim to be multiple of 16 bytes, got {mat_stride[end_dim - 1]}.", + ) + else: + torch._check( + False, + lambda: f"Invalid strides/sizes, got {mat_stride} for strides and {mat.shape} for sizes.", + ) + + check_valid_strides("mat_a", mat_a) + check_valid_strides("mat_b", mat_b) + + if scale_a is not None and scale_b is not None: + torch._check( + (scale_a.dtype == torch.float32 and scale_b.dtype == torch.float32) + or ( + scale_a.dtype == torch.float8_e8m0fnu + and scale_b.dtype == torch.float8_e8m0fnu + ), + lambda: f"For FP8 scales must both be float32, or for MXFP8 both scales must be float8_e8m0fnu. Got scale_a.dtype={scale_a.dtype} and scale_b.dtype={scale_b.dtype}.", + ) + is_mxfp8 = ( + scale_a.dtype == torch.float8_e8m0fnu + and scale_b.dtype == torch.float8_e8m0fnu + ) + + def check_scale(scale_name, scale, mat, scaled_dim, scale_multiplier=1): + if mat.dim() == 2: + torch._check( + scale.is_contiguous(), + lambda: f"Expected {scale_name} to be contiguous.", + ) + # For MXFP8, 2d tensors have variable size groups represented as subtensors, + # that are converted to blocked padded format individually. At compile time we don't know + # the group sizes yet, so we don't know the expect size of the blocked format scale. + # This limits what we can check here. + if is_mxfp8: + torch._check( + scale.dim() == mat.dim(), + lambda: f"For MXFP8, scale must have same number of dimensions as target tensor, but {scale_name} has mat.ndim={mat.ndim} and scale.ndim={scale.ndim}", + ) + else: + torch._check( + scale.dim() == 1, + lambda: f"Expected {scale_name} to be 1D tensor, but got {scale.dim()}D tensor.", + ) + torch._check( + scale.shape[0] == mat.shape[scaled_dim] * scale_multiplier, + lambda: f"Expected {scale_name} to have {mat.shape[scaled_dim] * scale_multiplier} elements, got {scale.shape[0]} elements.", + ) + else: + torch._check( + scale.stride(-1) == 1, + lambda: f"Expected {scale_name} to be contiguous in the last dimension.", + ) + torch._check( + scale.shape[0] == mat.shape[0], + lambda: f"Expected {scale_name} batch dimension to be {mat.shape[0]}, got {scale.shape[0]}.", + ) + # For MXFP8, 3d tensors have static 'groups' (stack of 2d tensors) so we can know the expected blocked + # scale sizes at compile time. + if is_mxfp8: + torch._check( + scale.ndim == mat.ndim - 1, + lambda: f"For MXFP8, 3d tensor should have 2d scales, but {scale_name} has mat.ndim={mat.ndim} and scale.ndim={scale.ndim}", + ) + # TODO: This logic only holds for RHS tensor in 2d-3d case. + # We'll need to update it to handle LHS 3d tensor in 3d-2d and 3d-3d cases. + G, K, N = mat.shape + block_size = 32 + blocked_K = round_up(K / block_size, 4) + blocked_N = round_up(N, 128) + torch._check( + scale.shape[0] == G and scale.shape[1] == blocked_K * blocked_N, + lambda: f"For MXFP8, expected mat.shape={mat.shape} to have scale shape of ({G},{blocked_K * blocked_N}), but got {scale.shape}", + ) + else: + torch._check( + scale.dim() == 2, + lambda: f"Expected {scale_name} to be 2D tensor, but got {scale.dim()}D tensor.", + ) + torch._check( + scale.shape[1] == mat.shape[1 + scaled_dim], + lambda: f"Expected {scale_name} non-batch dimension to be {mat.shape[1 + scaled_dim]}, got {scale.shape[1]}.", + ) + + scale_multiplier = ( + offs.shape[0] if offs is not None and mat_a_is_2d and mat_b_is_2d else 1 + ) + check_scale("scale_a", scale_a, mat_a, 0, scale_multiplier) + check_scale("scale_b", scale_b, mat_b, 1, scale_multiplier) + + torch._check( + scale_result is None, + lambda: "Scale result tensor provided, but it is not supported yet.", + ) + + if mat_a_is_2d or mat_b_is_2d: + torch._check( + offs is not None, + lambda: f"Offsets tensor not provided, but is needed for {mat_a.dim()}D/{mat_b.dim()}D multiplicand layouts.", + ) + if offs is not None: # to silence Mypy + torch._check( + offs.dim() == 1, + lambda: f"Offsets tensor must be 1D, but got offs.dim()={offs.dim()}.", + ) + torch._check( + offs.dtype == torch.int32, + lambda: f"Offsets tensor must be integer (int32) tensor, but got {offs.dtype}.", + ) + torch._check( + offs.stride() == (1,), + lambda: f"Offsets tensor must have stride (1,), but got {offs.stride()}.", + ) + else: + torch._check( + offs is None, + lambda: "Offsets tensor provided, but is not needed for 3D/3D multiplicand layouts.", + ) + + if mat_a.dtype == torch.float16: + torch._check( + _grouped_mm_fp16_cublaslt_supported(mat_a, mat_b, offs), + lambda: "Float16 grouped_mm requires cuBLASLt grouped GEMM support.", + ) + + torch._check( + bias is None, + lambda: "Bias tensor provided, but it is not supported yet.", + ) + + if scaled: + torch._check( + out_dtype is None or out_dtype == torch.bfloat16, + lambda: "If output dtype provided, it must be torch.bfloat16.", + ) + else: + out_dtype = out_dtype or mat_a.dtype + torch._check( + out_dtype == mat_a.dtype, + lambda: "Grouped gemm output dtype must match `mat_a` dtype.", + ) + + return _create_grouped_mm_output_tensor(mat_a, mat_b, offs, out_dtype) + + +def _grouped_mm_fp16_cublaslt_supported( + mat_a: Tensor, mat_b: Tensor, offs: Tensor | None +) -> bool: + if device_hint(mat_a) != "cuda" or device_hint(mat_b) != "cuda": + return False + if not torch.cuda.is_available(): + return False + mat_a_is_2d = mat_a.dim() == 2 + mat_b_is_2d = mat_b.dim() == 2 + batch_count = ( + offs.size(0) + if offs is not None and (mat_a_is_2d or mat_b_is_2d) + else mat_a.size(0) + ) + if batch_count < 1 or batch_count > 1024: + return False + device_capability = torch.cuda.get_device_capability() + cuda_version: tuple[int, int] = (0, 0) + if torch.version.cuda: + parts = torch.version.cuda.split(".") + cuda_version = (int(parts[0]), int(parts[1])) + return cuda_version >= (13, 3) and ( + device_capability[0] >= 9 and device_capability[0] <= 11 + ) + + +@register_meta(aten._grouped_mm) +@out_wrapper() +def meta_grouped_mm( + mat_a: Tensor, + mat_b: Tensor, + offs: Tensor | None = None, + bias: Tensor | None = None, + out_dtype: torch.dtype | None = None, +) -> Tensor: + return _meta_grouped_mm_common( + mat_a, + mat_b, + scale_a=None, + scale_b=None, + offs=offs, + bias=bias, + scale_result=None, + out_dtype=out_dtype, + ) + + +@register_meta([aten._scaled_grouped_mm]) +def meta_scaled_grouped_mm( + mat_a: torch.Tensor, + mat_b: torch.Tensor, + scale_a: torch.Tensor, + scale_b: torch.Tensor, + offs: torch.Tensor | None = None, + bias: torch.Tensor | None = None, + scale_result: torch.Tensor | None = None, + out_dtype: torch.dtype | None = None, + use_fast_accum: bool = False, +): + # matching _scaled_grouped_mm_cuda Blas.cpp implementation + out_dtype = out_dtype or torch.bfloat16 + + return _meta_grouped_mm_common( + mat_a, + mat_b, + scale_a=scale_a, + scale_b=scale_b, + offs=offs, + bias=bias, + scale_result=scale_result, + out_dtype=out_dtype, + use_fast_accum=use_fast_accum, + ) + + +@register_meta([aten._scaled_grouped_mm_v2.default]) +def meta_scaled_grouped_mm_v2( + mat_a: torch.Tensor, + mat_b: torch.Tensor, + scale_a: list[torch.Tensor], + scale_recipe_a: list[int], + swizzle_a: list[int], + scale_b: list[torch.Tensor], + scale_recipe_b: list[int], + swizzle_b: list[int], + offs: torch.Tensor | None = None, + bias: torch.Tensor | None = None, + out_dtype: torch.dtype | None = None, + contraction_dim: list[int] | None = None, + use_fast_accum: bool = False, +): + """Shape inference only, since the structured C++ meta doesn't support + dynamic shapes. Input validation lives there; same pattern as meta_mm. + """ + _out_dtype = out_dtype or torch.bfloat16 + return _create_grouped_mm_output_tensor(mat_a, mat_b, offs, _out_dtype) + + +@register_meta(aten._foreach_norm.Scalar) +def meta_foreach_norm(tensors, ord=2, dtype=None): + if float(ord) == float("inf"): + for t in tensors: + torch._check( + t.numel() > 0, + lambda: "_foreach_norm cannot compute infinity norm on empty tensor", + ) + results = [] + for t in tensors: + out_dtype = dtype if dtype is not None else t.dtype + if out_dtype.is_complex: + out_dtype = corresponding_real_dtype(out_dtype) + results.append(t.new_empty((), dtype=out_dtype)) + return results + + +@register_meta(aten._softmax) +@out_wrapper() +def softmax(x: Tensor, dim: int, half_to_float: bool) -> Tensor: + if half_to_float: + if x.dtype not in [torch.half, torch.bfloat16]: + raise AssertionError( + f"half_to_float is True but x.dtype is {x.dtype}, expected half or bfloat16" + ) + + computation_dtype, result_dtype = utils.elementwise_dtypes( + x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + result_dtype = result_dtype if not half_to_float else computation_dtype + res = torch.empty_like(x, dtype=result_dtype, memory_format=torch.contiguous_format) + return res + + +@register_meta(aten.constant_pad_nd) +@out_wrapper() +def _constant_pad_nd_meta(input, pad, value=0): + # same checks as decomposition in torch/_refs/__init__.py:constant_pad_nd() + torch._check( + len(pad) % 2 == 0, + lambda: f"Length of pad must be even but instead it equals {len(pad)}", + ) + + input_sizes = input.shape + l_inp = len(input_sizes) + l_pad = len(pad) // 2 + l_diff = l_inp - l_pad + + torch._check( + l_inp >= l_pad, + lambda: "Length of pad should be no more than twice the number of " + f"dimensions of the input. Pad length is {len(pad)} while the input has " + f"{l_inp} dimensions.", + ) + + if all(isinstance(p, utils.IntWithoutSymInt) and p <= 0 for p in pad): + c_input = input + for i in range(l_diff, l_inp): + pad_idx = 2 * (l_inp - i - 1) + if pad[pad_idx] < 0: + c_input = c_input.narrow( + i, -pad[pad_idx], c_input.shape[i] + pad[pad_idx] + ) + + if pad[pad_idx + 1] < 0: + c_input = c_input.narrow(i, 0, c_input.shape[i] + pad[pad_idx + 1]) + + return c_input.clone() + + new_shape = list(input_sizes[:l_diff]) + for i in range(l_pad): + pad_idx = len(pad) - ((i + 1) * 2) + new_dim = input_sizes[l_diff + i] + pad[pad_idx] + pad[pad_idx + 1] + torch._check( + new_dim >= 0, + lambda: f"The input size {input_sizes[l_diff + i]}, plus negative padding " + f"{pad[pad_idx]} and {pad[pad_idx + 1]} resulted in a negative output size, " + f"which is invalid. Check dimension {l_diff + i} of your input.", + ) + new_shape.append(new_dim) + + return torch.empty( + new_shape, + dtype=input.dtype, + device=input.device, + requires_grad=input.requires_grad, + memory_format=suggest_memory_format(input), + ) + + +@register_meta(aten.embedding) +@out_wrapper() +def embedding( + weight: Tensor, + indices: Tensor, + padding_idx: int = -1, + scale_grad_by_freq: bool = False, + sparse: bool = False, +) -> Tensor: + if weight.dim() != 2: + raise AssertionError(f"'weight' must be 2-D, got {weight.dim()}-D") + torch._check( + indices.dtype in (torch.long, torch.int32), + lambda: ( + "Expected tensor for argument #1 'indices' to have one of the following " + f"scalar types: Long, Int; but got {indices.dtype} instead" + ), + ) + weight_shape = weight.shape + indices_shape = indices.shape + + if indices.ndim == 0: + out_shape: tuple[int, ...] = (weight_shape[1],) + elif indices.ndim == 1: + out_shape = (indices_shape[0], weight_shape[1]) + else: + out_shape = (*indices_shape, weight_shape[1]) + + out_dtype = weight.dtype + return weight.new_empty(out_shape, dtype=out_dtype) + + +@register_meta(aten._jagged_to_padded_dense_forward.default) +def meta__jagged_to_padded_dense_forward( + values: Tensor, + offsets: list[Tensor], + max_lengths: list[int], + padding_value: float = 0.0, +): + # only one jagged dim is supported for now + if len(offsets) != 1: + raise AssertionError( + f"Only one jagged dim is supported, got {len(offsets)} offsets" + ) + if len(max_lengths) != 1: + raise AssertionError( + f"Only one jagged dim is supported, got {len(max_lengths)} max_lengths" + ) + + B = offsets[0].shape[0] - 1 + S = max_lengths[0] + output_shape = (B, S, *values.shape[1:]) + return values.new_empty(output_shape) + + +def _create_unary_float_meta_func(func): + @register_meta(func) + @out_wrapper() + def _f(x): + return elementwise_meta( + x, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT + ) + + return _f + + +# Implementation follows cuda implementation native_multi_head_attention_cuda +@register_meta(aten._native_multi_head_attention.default) +def native_multi_head_attention_fake( + query, + key, + value, + embed_dim, + num_head, + qkv_weight, + qkv_bias, + proj_weight, + proj_bias, + mask=None, + need_weights=True, + average_attn_weights=True, + mask_type=None, +): + if query.is_nested or key.is_nested or value.is_nested: + raise NotImplementedError( + "_native_multi_head_attention fake implementation does not support nested tensors" + ) + + from torch.fx.experimental.symbolic_shapes import guard_or_false + + # Unbacked-safe: known-empty takes the empty path; if the size is symbolic + # and can't be decided, assume non-empty (the common case) instead of DDE-ing. + if guard_or_false(query.numel() == 0): + return (query.new_empty(query.shape), query.new_empty(0)) + + B = query.size(0) # B: batch size + T = query.size(1) # T: target sequence length + + # In native_multi_head_attention_cuda, + # we have proj = transform0213_gemm_nt_bias(attn_ctx, proj_weight, proj_bias, query) + # , which does attn_ctx @ proj_weight.T + proj_bias + # so the last dim of output shape is proj_weight.size(0) + output_dim = proj_weight.size(0) + output = query.new_empty(B, T, output_dim) + + if need_weights: + if average_attn_weights: + # When averaging attention weights, shape is [B, T, T] (averaged over heads) + # T = query seq len, S = key/value seq len + attn_weights = query.new_empty(B, T, T) + else: + # When not averaging, shape is [B, num_head, T, T] + # T = query seq len, S = key/value seq len + attn_weights = query.new_empty(B, num_head, T, T) + else: + attn_weights = query.new_empty(0) + + return (output, attn_weights) + + +def _create_binary_float_meta_func(func): + @register_meta(func) + @out_wrapper() + def _f(x, y): + return elementwise_meta( + x, y, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT + ) + + return _f + + +_create_unary_float_meta_func(aten.special_airy_ai) +_create_unary_float_meta_func(aten.special_bessel_y0) +_create_unary_float_meta_func(aten.special_bessel_y1) +_create_unary_float_meta_func(aten.special_modified_bessel_i0) +_create_unary_float_meta_func(aten.special_modified_bessel_i1) +_create_unary_float_meta_func(aten.special_modified_bessel_k0) +_create_unary_float_meta_func(aten.special_modified_bessel_k1) +_create_unary_float_meta_func(aten.special_scaled_modified_bessel_k0) +_create_unary_float_meta_func(aten.special_scaled_modified_bessel_k1) + + +_create_binary_float_meta_func(aten.special_chebyshev_polynomial_t) +_create_binary_float_meta_func(aten.special_chebyshev_polynomial_u) +_create_binary_float_meta_func(aten.special_chebyshev_polynomial_v) +_create_binary_float_meta_func(aten.special_chebyshev_polynomial_w) +_create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_t) +_create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_u) +_create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_v) +_create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_w) +_create_binary_float_meta_func(aten.special_hermite_polynomial_h) +_create_binary_float_meta_func(aten.special_hermite_polynomial_he) +_create_binary_float_meta_func(aten.special_laguerre_polynomial_l) +_create_binary_float_meta_func(aten.special_legendre_polynomial_p) + + +def _register_inplace_meta(fn): + @wraps(fn) + def _fn(self, *args, **kwargs): + out = fn(self, *args, **kwargs) + check_inplace_broadcast(self.shape, out.shape) + return self + + inplace_name = f"{fn.__name__}_" + _fn.__name__ = inplace_name + _fn = register_meta(getattr(aten, inplace_name))(_fn) # type: ignore[assignment] + + return _fn + + +@register_meta(aten.lerp) +@out_wrapper() +def lerp(start, end, weight): + torch._check( + start.dtype == end.dtype, + lambda: f"expected dtype {start.dtype} for `end`, but got dtype {end.dtype}", + ) + args = [start, end] + if isinstance(weight, TensorLike): + if weight.ndim != 0: + torch._check( + start.dtype == weight.dtype, + lambda: f"expected dtype {start.dtype} for `weight`, but got dtype {weight.dtype}", + ) + args.append(weight) + return elementwise_meta( + *args, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +@register_meta(aten.addcmul) +@out_wrapper() +def addcmul(input, tensor1, tensor2, *, value=1): + return elementwise_meta( + input, tensor1, tensor2, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +@register_meta(aten.addcdiv) +@out_wrapper() +def addcdiv(input, tensor1, tensor2, *, value=1): + torch._check( + not ( + utils.is_integer_dtype(tensor1.dtype) + and utils.is_integer_dtype(tensor2.dtype) + ), + lambda: ( + "Integer division with addcdiv is no longer supported, and in a future ", + "release addcdiv will perform a true division of tensor1 and tensor2. ", + "The historic addcdiv behavior can be implemented as ", + "(input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) ", + "for integer inputs and as ", + "(input + value * tensor1 / tensor2) for float inputs. ", + "The future addcdiv behavior is just the latter implementation: ", + "(input + value * tensor1 / tensor2), for all dtypes.", + ), + ) + return elementwise_meta( + input, tensor1, tensor2, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + +lerp_ = _register_inplace_meta(aten.lerp) +addcmul_ = _register_inplace_meta(aten.addcmul) +addcdiv_ = _register_inplace_meta(aten.addcdiv) + + +# We must also trigger meta registrations from PrimTorch ref +# decompositions +import torch._refs +import torch._refs.nn.functional +import torch._refs.special + + +def activate_meta(): + activate_meta_table = {} + + # For a given op, we pick the most specific decomp function from + # global_decomp_table in the precedence order of meta > post_autograd > pre_autograd + for typ in ["meta", "post_autograd", "pre_autograd"]: + registry = global_decomposition_table[typ] + + for opo in registry: + if opo not in activate_meta_table: + activate_meta_table[opo] = registry[opo] + + for op_overload, fn in activate_meta_table.items(): + # Don't register meta for HigherOrderOp's decomp. + # We can reconsider this in the future, but in general, + # the way you do a meta for a HigherOrderOp is different from + # OpOverload. + if isinstance(op_overload, torch._ops.HigherOrderOperator): + continue + if not isinstance(op_overload, OpOverload): + raise AssertionError( + f"op_overload must be OpOverload, got {type(op_overload)}" + ) + + op_overload.py_impl(torch._C.DispatchKey.Meta)(fn) + + if torch._C._dispatch_has_kernel_for_dispatch_key( + op_overload.name(), "CompositeImplicitAutograd" + ): + # Internally, we shouldn't be registering meta kernels for any operators that + # have CompositeImplicitAutograd kernels. + # Instead, we should be letting those decompositions run, and writing meta kernels + # only for the base operators. + if op_overload in global_decomposition_table["meta"]: + raise RuntimeError( + f"{op_overload} is a CompositeImplicitAutograd op, we shouldn't " + "register meta function for it. Instead, we should let the decomposition run and write " + "meta kernels for the base operators." + ) + elif op_overload.is_view: + # Attempting to register a python meta kernel for a view operator. + # We shouldn't do this, because the output will report as not having aliased storages. + # All view ops have meta kernels in C++ today, so we should use those instead. + pass + elif ( + op_overload.name() + in { + "aten::empty_strided", # causing infinite recursion, test_meta.py + "aten::clone", # causing infinite recursion + "aten::_to_copy", # causing infinite recursion, test_serialization.py -k test_tensor_subclass_getstate_overwrite + "aten::copy_", # Exception not raised, test_torch.py -k test_storage_meta_errors_cpu_int64 + "aten::constant_pad_nd", # requires_grad mismatch, test_ops.py -k test_fake_crossref_backward_amp_istft_cuda_float32 + "aten::rot90", # requires_grad mismatch! test_ops.py -k test_fake_crossref_backward_amp_rot90_cuda_float32 + "aten::as_strided_scatter", # requires_grad mismatch, test_ops.py -k test_fake_crossref_backward_no_amp_as_strided_scatter_cuda_float32 + "aten::stack", # use the symint-aware C++ meta kernel (stack_meta) + } + ): + pass + else: + if "mkldnn::" in op_overload.name(): + _meta_lib_dont_use_me_use_register_meta_for_mkldnn.impl(op_overload, fn) + elif "mkl::" in op_overload.name(): + _meta_lib_dont_use_me_use_register_meta_for_mkl.impl(op_overload, fn) + elif "onednn::" in op_overload.name(): + _meta_lib_dont_use_me_use_register_meta_for_onednn.impl(op_overload, fn) + elif "quantized::" in op_overload.name(): + _meta_lib_dont_use_me_use_register_meta_for_quantized.impl( + op_overload, fn + ) + else: + _meta_lib_dont_use_me_use_register_meta.impl(op_overload, fn) + + +activate_meta() diff --git a/.venv/lib/python3.12/site-packages/torch/_native/__init__.py b/.venv/lib/python3.12/site-packages/torch/_native/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ead2e25bf8b9928465316459574fc2e113988add --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/__init__.py @@ -0,0 +1,59 @@ +import os +import warnings +from functools import cache +from typing import cast + +# This handles collecting registration of all native ops +# Also need to import DSL utils to make sure DSL registration is ok +from . import cutedsl_utils, dsl_registry, helion_utils, ops, registry, triton_utils + + +@cache +def get_user_ordering_fn() -> registry.UserOrderingFn | None: + """ + Get a user-supplied graph-ordering function if specified. + + Pass in a `package.submodule.fn` string to the env variable + `TORCH_PYTHON_NATIVE_USER_GRAPH_ORDER_FN` that implements the + calling API described in `torch/_native/README.md`. This function + must be part of an importable path. + + Return either the imported function or `None` + """ + env_var = os.getenv("TORCH_PYTHON_NATIVE_USER_GRAPH_ORDER_FN") + + if not env_var: + return None + + try: + import importlib + + # Split into "package.submodule.fn_name + module_name, fn_name = env_var.rsplit(".", 1) + + module = importlib.import_module(module_name) + fn = getattr(module, fn_name) + + if not callable(fn): + raise TypeError(f"{env_var} does not describe a callable function") + + # Cast needed: getattr returns object, but we've verified fn is callable with correct signature + return cast(registry.UserOrderingFn, fn) + except Exception as e: + raise ValueError( + f"Could not resolve {env_var} into an importable & callable function" + ) from e + + +user_order_fn = get_user_ordering_fn() +if user_order_fn: + registry.reorder_graphs_from_user_function(user_order_fn) + + +with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message="Warning only once for all operators, other operators may also be overridden\\.", + category=UserWarning, + ) + registry._register_all_overrides() diff --git a/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..870062da680f7dd3f018877e9bf1e1a5153ef172 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/common_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/common_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9e9d424d13dd378e5d3b1ffaf6daf5f11675073 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/common_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/cutedsl_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/cutedsl_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2847a730e259af83356e4070620702f8a88f058 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/cutedsl_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/dsl_registry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/dsl_registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3cce518fb54660546e7546e5c854fe5d4381a3d2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/dsl_registry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/helion_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/helion_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66a27387bc9ca10d888a8272a8d78c8fe8f5ab43 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/helion_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/instrumentation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/instrumentation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..872fd7d4e44a46367e226010c84c1811b85fde94 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/instrumentation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/nvmath_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/nvmath_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8231cfac60b63e21224a7da8268e7e563bd5e902 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/nvmath_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/registry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b9a401a3688e3db7a5c9e087d18b175e0488702 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/registry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/triton_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/triton_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d600e428daffcb86176a801f5b5c4b03b33a167a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/__pycache__/triton_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/common_utils.py b/.venv/lib/python3.12/site-packages/torch/_native/common_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7568fffdedb746d41fede98bca95ff3fbf5b93f7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/common_utils.py @@ -0,0 +1,69 @@ +import importlib +import importlib.metadata +import os +from functools import cache + +from torch._vendor.packaging import version as _packaging_version + + +@cache +def check_native_jit_disabled() -> bool: + """ + Single point to check if native DSL ops are disabled globally, + checked via: + TORCH_DISABLE_NATIVE_JIT=1 + """ + return int(os.getenv("TORCH_DISABLE_NATIVE_JIT", 0)) == 1 + + +def _unavailable_reason(deps: list[tuple[str, str]]) -> None | str: + """ + Check availability of required packages - cuteDSL & deps, + informing user what (if anything) is missing + + NOTE: Doesn't actually import anything. + """ + for package_name, module_name in deps: + # find_spec raises ModuleNotFoundError for dotted names (e.g. + # "nvmath.bindings") when the parent package is absent. + try: + found = importlib.util.find_spec(module_name) is not None + except (ModuleNotFoundError, ValueError): + found = False + if not found: + return ( + f"missing optional dependency `{package_name}` " + f"(importlib.util.find_spec({package_name}) failed)" + ) + return None + + +def _available_version(package: str) -> _packaging_version.Version | None: + """ + Get the installed version of a package as (major, minor, patch). + + Handles pre-release suffixes like "0.7.0rc1" or "3.1.0.post1" by + stripping non-numeric tails from each component. Returns None on + parse failure. + """ + try: + version = importlib.metadata.version(package) + except importlib.metadata.PackageNotFoundError: + return None + + try: + v = _packaging_version.parse(version) + except _packaging_version.InvalidVersion: + return None + + return v + + +@cache +def check_native_version_skip() -> bool: + """ + Single point to check if native DSL version gating should be skipped, + checked via: + TORCH_NATIVE_SKIP_VERSION_CHECK=1 + """ + return int(os.getenv("TORCH_NATIVE_SKIP_VERSION_CHECK", 0)) == 1 diff --git a/.venv/lib/python3.12/site-packages/torch/_native/cutedsl_utils.py b/.venv/lib/python3.12/site-packages/torch/_native/cutedsl_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5ac4b98b71049196968d47b04c6c776e01238f88 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/cutedsl_utils.py @@ -0,0 +1,148 @@ +import functools +import logging +import sys +from typing import cast + +from torch._vendor.packaging.version import Version + +from ..backends import cuda as _cuda +from .common_utils import ( + _available_version, + _unavailable_reason, + check_native_jit_disabled, + check_native_version_skip, +) +from .dsl_registry import dsl_registry, DSLModuleProtocol +from .registry import ( + _OpCondFn, + _OpImplFn, + deregister_op_overrides as _deregister_op_overrides_impl, + register_op_override as _register_op_override_impl, +) + + +log = logging.getLogger(__name__) + + +_CUTEDSL_DSL_NAME = "cutedsl" +_CUTEDSL_REQUIRED_VERSIONS: set[Version] = { + # Current version - Note Version.from_part(release=(4.4.1)) is better + # but > v26 of packaging. + Version(f"{4}.{4}.{1}"), + Version(f"{4}.{4}.{2}"), + Version(f"{4}.{5}.{2}"), +} + + +@functools.cache +def _check_runtime_available() -> tuple[bool, Version | None]: + """ + Check if cutedsl (and deps) are available. + + NOTE: Doesn't import at this point + """ + # Skip all checks if running on CPU-only binary + if not _cuda.is_built(): + return (False, None) + + # CuTeDSL kernels require genuine NVIDIA GPUs; on ROCm/HIP builds the + # CUDA compatibility layer reports is_built()=True but cuInit() will fail + # because no NVIDIA driver is present. + import torch + + if torch.version.hip is not None: + return (False, None) + + deps = [ + ("nvidia_cutlass_dsl", "cutlass"), + ("apache_tvm_ffi", "tvm_ffi"), + ] + reason = _unavailable_reason(deps) + if reason is None: + available = True + version = _available_version("nvidia_cutlass_dsl") + else: + # info, not warning: missing optional deps is the common case on stock + # builds and we don't want to spam stderr on `import torch`. Surface + # it via TORCH_LOGS=+native_dsl when diagnosing why an override is + # silent. + log.info( + "CuTeDSL operators require optional Python packages " + "`nvidia-cutlass-dsl` and `apache-tvm-ffi`; " + "%s", + reason, + ) + available = False + version = None + return available, version + + +def runtime_available() -> bool: + available, _ = _check_runtime_available() + return available + + +def runtime_version() -> None | Version: + _, version = _check_runtime_available() + return version + + +@functools.cache +def _version_is_ok() -> bool: + _, version = _check_runtime_available() + if check_native_version_skip() or (version in _CUTEDSL_REQUIRED_VERSIONS): + return True + + log.info( + "cutedsl version %s is not known-good (ok: %s); " + "set TORCH_NATIVE_SKIP_VERSION_CHECK=1 to override", + version, + _CUTEDSL_REQUIRED_VERSIONS, + ) + return False + + +def deregister_op_overrides() -> None: + """ + Deregister all ops through cuteDSL + """ + _deregister_op_overrides_impl(disable_dsl_names=_CUTEDSL_DSL_NAME) + + +def register_op_override( + lib_symbol: str, + op_symbol: str, + dispatch_key: str, + cond: _OpCondFn | None, + impl: _OpImplFn, + *, + allow_multiple_override: bool = False, + unconditional_override: bool = False, +) -> None: + """ + See torch/_native/registry.py for the underlying implementation + and arguments. This is a thin, DSL-checking wrapper over + _register_op_override_impl + """ + available, version = _check_runtime_available() + if (not available) or check_native_jit_disabled(): + return + + if not _version_is_ok(): + return + + _register_op_override_impl( + _CUTEDSL_DSL_NAME, + lib_symbol, + op_symbol, + dispatch_key, + cond, + impl, + allow_multiple_override=allow_multiple_override, + unconditional_override=unconditional_override, + ) + + +# Register this DSL module with the registry +# Note: Import-time registration ensures DSL is available when module is loaded +dsl_registry.register_dsl("cutedsl", cast(DSLModuleProtocol, sys.modules[__name__])) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/dsl_registry.py b/.venv/lib/python3.12/site-packages/torch/_native/dsl_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..2e7b324800ac9461b4e045c497344db13d91927e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/dsl_registry.py @@ -0,0 +1,154 @@ +# Owner(s): ["module: dsl-native-ops"] + +import functools +import logging +from typing import Protocol + +from torch._vendor.packaging.version import Version + +from .registry import _OpCondFn, _OpImplFn + + +log = logging.getLogger(__name__) + + +class DSLModuleProtocol(Protocol): + """Complete interface for DSL utility modules""" + + def runtime_available(self) -> bool: ... + def runtime_version(self) -> Version | None: ... + + def deregister_op_overrides(self) -> None: ... + + def register_op_override( + self, + lib_symbol: str, + op_symbol: str, + dispatch_key: str, + cond: _OpCondFn | None, + impl: _OpImplFn, + *, + allow_multiple_override: bool = False, + unconditional_override: bool = False, + ) -> None: ... + + +class DSLRegistry: + """Registry for DSL modules - calls their existing API functions dynamically""" + + def __init__(self): + self._dsl_modules: dict[str, DSLModuleProtocol] = {} + + def _validate_dsl_name(self, name: str) -> None: + """Validate DSL name at runtime""" + if not isinstance(name, str): + raise TypeError(f"DSL name must be string, got {type(name).__name__}") + + if not name.strip(): + raise ValueError("DSL name cannot be empty or whitespace") + + def register_dsl(self, name: str, dsl_module: DSLModuleProtocol) -> None: + """Register a DSL module with required interface""" + # Runtime validation for name and module interface + self._validate_dsl_name(name) + + # Validate that module implements the protocol + required_methods = [ + "runtime_available", + "runtime_version", + "register_op_override", + "deregister_op_overrides", + ] + missing_methods = [ + method for method in required_methods if not hasattr(dsl_module, method) + ] + if missing_methods: + raise TypeError( + f"DSL module '{name}' missing required methods: {missing_methods}" + ) + + # Handle duplicate registration case + if name in self._dsl_modules: + existing_module = self._dsl_modules[name] + if existing_module is dsl_module: + # Same module re-registering - this is OK (import-time registration) + log.debug( + "DSL '%s' re-registered with same module", + name, + ) + return + else: + # Different module object but same name - warn and allow (for testing) + # This can happen when tests import modules directly + log.warning( + "DSL '%s' re-registered with different module object (possibly from test imports)", + name, + ) + # Continue to allow the registration + + # No cast needed - already properly typed + self._dsl_modules[name] = dsl_module + + # Clear caches to prevent stale results after registration + self.is_dsl_available.cache_clear() + self.get_dsl_version.cache_clear() + self.list_available_dsls.cache_clear() + self.list_all_dsls.cache_clear() + + log.info("Successfully registered DSL: %s", name) + + @functools.cache # noqa: B019 + def is_dsl_available(self, dsl_name: str) -> bool: + """Check if DSL is available by calling its runtime_available()""" + dsl_module = self._dsl_modules.get(dsl_name) + if dsl_module is None: + return False + try: + return dsl_module.runtime_available() + except ImportError: + log.debug("DSL %s import error", dsl_name, exc_info=True) + return False + except Exception: + log.exception("Error checking availability for DSL %s", dsl_name) + return False + + @functools.cache # noqa: B019 + def get_dsl_version(self, dsl_name: str) -> Version | None: + """Get DSL version by calling its runtime_version()""" + dsl_module = self._dsl_modules.get(dsl_name) + if dsl_module is None: + return None + try: + return dsl_module.runtime_version() + except Exception: + log.debug("Error getting version for DSL %s", dsl_name, exc_info=True) + return None + + @functools.cache # noqa: B019 + def list_available_dsls(self) -> tuple[str, ...]: + """Get names of currently available DSLs""" + available = [] + for name in self._dsl_modules: + if self.is_dsl_available(name): # Use cached method + available.append(name) + return tuple(available) + + @functools.cache # noqa: B019 + def list_all_dsls(self) -> tuple[str, ...]: + """Get all registered DSL names (available or not)""" + return tuple(self._dsl_modules.keys()) + + def get_dsl_module(self, name: str) -> DSLModuleProtocol | None: + """Get a registered DSL module by name. + + Args: + name: Name of the DSL to retrieve. + + Returns: + The DSL module if registered, None otherwise. + """ + return self._dsl_modules.get(name) + + +# Global registry instance +dsl_registry = DSLRegistry() diff --git a/.venv/lib/python3.12/site-packages/torch/_native/helion_utils.py b/.venv/lib/python3.12/site-packages/torch/_native/helion_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dd54f0c193b8a20dc716f31994851a37fc42f290 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/helion_utils.py @@ -0,0 +1,138 @@ +import functools +import logging +import sys +from typing import cast + +from torch._vendor.packaging.version import Version + +from ..backends import cuda as _cuda +from .common_utils import ( + _available_version, + _unavailable_reason, + check_native_jit_disabled, + check_native_version_skip, +) +from .dsl_registry import dsl_registry, DSLModuleProtocol +from .registry import ( + _OpCondFn, + _OpImplFn, + deregister_op_overrides as _deregister_op_overrides_impl, + register_op_override as _register_op_override_impl, +) + + +log = logging.getLogger(__name__) + + +_HELION_DSL_NAME = "helion" +# Minimum supported Helion: the latest release verified with the native DSL +# kernels (older releases carry the same APIs but are untested). +_HELION_MINIMUM_VERSION = Version("1.2.0") +# HELION_BACKEND name -> (pip package, import module); extend to add more, +# e.g. "cute": ("nvidia-cutlass-dsl", "cutlass"). +_HELION_BACKENDS: dict[str, tuple[str, str]] = {"triton": ("triton", "triton")} +_DEFAULT_HELION_BACKEND = "triton" + + +def _chosen_backend() -> str: + """Selected Helion lowering backend (HELION_BACKEND env, default triton).""" + import os + + return os.getenv("HELION_BACKEND", _DEFAULT_HELION_BACKEND) + + +@functools.cache +def _check_runtime_available() -> tuple[bool, Version | None]: + if not _cuda.is_built(): + return (False, None) + + import torch + + if torch.version.hip is not None: + return (False, None) + + backend = _chosen_backend() + dep = _HELION_BACKENDS.get(backend) + if dep is None: + log.info( + "Helion native DSL ops support backends %s; HELION_BACKEND=%s", + tuple(_HELION_BACKENDS), + backend, + ) + return (False, None) + + reason = _unavailable_reason([("helion", "helion"), dep]) + if reason is not None: + log.info( + "Helion native DSL ops require optional packages `helion` and `%s`; %s", + dep[0], + reason, + ) + return (False, None) + return (True, _available_version("helion")) + + +def runtime_available() -> bool: + # Package presence only, like triton/cutedsl; version gated in register_op_override. + available, _ = _check_runtime_available() + return available + + +def runtime_version() -> Version | None: + _, version = _check_runtime_available() + return version + + +@functools.cache +def _version_is_sufficient() -> bool: + _, version = _check_runtime_available() + if version is not None and ( + version >= _HELION_MINIMUM_VERSION or check_native_version_skip() + ): + return True + + log.info( + "helion version %s is not sufficient (>= %s); " + "set TORCH_NATIVE_SKIP_VERSION_CHECK=1 to override", + version, + _HELION_MINIMUM_VERSION, + ) + return False + + +def deregister_op_overrides() -> None: + _deregister_op_overrides_impl(disable_dsl_names=_HELION_DSL_NAME) + + +def register_op_override( + lib_symbol: str, + op_symbol: str, + dispatch_key: str, + cond: _OpCondFn | None, + impl: _OpImplFn, + *, + allow_multiple_override: bool = False, + unconditional_override: bool = False, +) -> None: + available, _ = _check_runtime_available() + if (not available) or check_native_jit_disabled(): + return + + if not _version_is_sufficient(): + return + + _register_op_override_impl( + _HELION_DSL_NAME, + lib_symbol, + op_symbol, + dispatch_key, + cond, + impl, + allow_multiple_override=allow_multiple_override, + unconditional_override=unconditional_override, + ) + + +dsl_registry.register_dsl( + _HELION_DSL_NAME, cast(DSLModuleProtocol, sys.modules[__name__]) +) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/instrumentation.py b/.venv/lib/python3.12/site-packages/torch/_native/instrumentation.py new file mode 100644 index 0000000000000000000000000000000000000000..ccdb5bd2d58882d05956064daad27865c5422e58 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/instrumentation.py @@ -0,0 +1,537 @@ +"""Structured compile/cache instrumentation for ``torch._native`` ops. + +Native DSL ops compile device kernels lazily on first call. Those compiles +are the dominant first-call latency, and a silent cache miss is a common +"why is this slow again?" question. This module surfaces both, with no +runtime cost unless ``TORCH_LOGS=+native_dsl_compile`` is set. That artifact +is off by default to avoid log spew: these wrappers sit on the compile +*cache*, so they run on every op call, cache hits included. + +Two sinks, both gated on that artifact and fed by a single +:class:`CompileEvent`: + +* The ``native_dsl_compile`` artifact logger: a one-line human-readable + summary per compile -- outcome, wall time, and running hit/miss totals. +* ``trace_structured`` artifacts (tlparse): a JSON record per compile, for + production jobs where only the structured trace is retrievable. + +The DSLs compile through different machinery, so each has an entry point. +All reduce to the same shared core (:func:`_make_wrapper`): snapshot the +cache, time the call, snapshot again, and flag ``compiled`` when the miss +counter advanced. They differ only in how a snapshot is sampled: + +* :func:`instrument_cutedsl_compile` -- for CuTeDSL, stacked *above* the + vendored ``quack`` ``@jit_cache`` decorator. It reads the cache wrapper's + ``cache_info()`` and times the wrapped ``cute.compile`` call:: + + @instrument_cutedsl_compile("aten::topk") + @jit_cache + def _compile_topk_radix(N, K, deterministic): ... + + A ``cache_info().misses`` delta means the cache ran a real + ``cute.compile``, so the measured wall time *is* the compile time; + otherwise the key was served from the in-memory or on-disk ``.o`` cache. + +* :func:`instrument_triton_kernel` -- for Triton ``@triton.jit`` kernels, + which compile *and* launch in one ``kernel[grid](...)`` call and keep + their own per-kernel cache (``JITFunction.device_caches``). Stacked above + ``@triton.jit``, it wraps the kernel in a transparent proxy that watches + *that one kernel's* variant count; a launch that grows it means a fresh + compile. Scoping to the single kernel gives clean per-kernel attribution -- + two kernels in one module never collide. Because compile and launch are + fused, ``wall_ms`` on a miss is compile + host-launch latency (compile + dominates); on a hit it is just host-launch latency. + +* :func:`instrument_helion_kernel` -- for regular and AOT Helion kernels. It + tracks compiled configurations across the kernel's bound specialization + cache; a growing count means the call compiled a new configuration. + +The DSLs only expose miss-side signal directly (CuTeDSL's vendored cache +reports aggregate counters; Triton's cache only grows), so finer reasons +(disk-hit vs lock-timeout, Triton's on-disk cache) are not distinguished +here -- the boolean ``compiled`` flag plus wall time covers the common case. + +Neither entry point touches the underlying DSL/vendored code, and neither +hijacks Triton's process-global ``knobs.runtime`` hooks (those would also +capture Inductor's unrelated Triton compiles). +""" + +from __future__ import annotations + +import functools +import time +from dataclasses import asdict, dataclass +from typing import Any, TYPE_CHECKING, TypeVar + +import torch._logging + + +if TYPE_CHECKING: + from collections.abc import Callable + + +__all__ = [ + "CompileEvent", + "InstrumentedHelionKernel", + "InstrumentedTritonKernel", + "instrument_cutedsl_compile", + "instrument_helion_kernel", + "instrument_triton_kernel", + "instrumented_cutedsl_cache", + "instrumented_helion_kernel", + "instrumented_triton_cache", +] + +# tlparse artifact name, and the TORCH_LOGS switch gating both sinks. The +# "artifact" envelope (see trace_structured_artifact) is the well-supported +# transport; the name lets tlparse group these events. +_ARTIFACT_NAME = "native_dsl_compile" + +log = torch._logging.getArtifactLogger(__name__, _ARTIFACT_NAME) + +R = TypeVar("R") + + +@dataclass(frozen=True) +class CompileEvent: + """One compile-function invocation, as recorded to logs and tlparse. + + ``compiled`` is the ground truth (did the cache run a real compile); + ``outcome`` is its human-readable form. ``hits`` / ``misses`` are the + cache's running totals *after* this call, useful for spotting churn + (e.g. misses climbing across calls of the same shape => keys not + stable, or the persistent cache is disabled). + """ + + op: str + dsl: str + outcome: str + compiled: bool + wall_ms: float + key: str + hits: int + misses: int + + def as_dict(self) -> dict[str, Any]: + return asdict(self) + + +def _listening() -> bool: + """True if the ``native_dsl_compile`` artifact is enabled. + + Lets the wrapper skip all instrumentation work (cache sampling, timing, + key formatting, event construction) on the hot path when nothing is + listening -- important because the CuTeDSL wrapper sits on the compile + *cache* and so runs on every op call, cache hits included. + + Both sinks share this one gate; tlparse emission cannot be left to + ``trace_structured``'s internal ``trace_log.handlers`` check, which is + true in any job collecting a structured trace. + + ``log_state`` is read off the module because ``TORCH_LOGS`` parsing + rebinds it. + """ + from torch._logging import _internal + + return _internal.log_state.is_artifact_enabled(_ARTIFACT_NAME) + + +def _emit(event: CompileEvent) -> None: + """Fan the event out to the artifact logger and tlparse.""" + log.info( + "%s [%s] %s in %.1fms (key=%s, cache hits=%d misses=%d)", + event.op, + event.dsl, + event.outcome, + event.wall_ms, + event.key, + event.hits, + event.misses, + ) + + # Local import keeps `import torch._native` from pulling torch._logging's + # heavier transitive imports at registration time. + from torch._logging._internal import trace_structured + + # Same "artifact" envelope as Dynamo's trace_structured_artifact(); we call + # trace_structured directly only to pass expect_trace_id=False, since that + # helper would capture an expensive stack on every eager event (no live + # CompileContext). trace_structured still reads the live trace id, so a + # native op compiling inside torch.compile is auto-tagged with the ambient + # frame ids and nests under that compile in tlparse. + trace_structured( + "artifact", + metadata_fn=lambda: {"name": _ARTIFACT_NAME, "encoding": "json"}, + expect_trace_id=False, + payload_fn=lambda: _json_payload(event), + ) + + +def _json_payload(event: CompileEvent) -> str: + import json + + return json.dumps(event.as_dict(), sort_keys=True) + + +def _format_key(args: tuple, kwargs: dict, key_fn: Callable | None) -> str: + if key_fn is not None: + try: + return key_fn(*args, **kwargs) + except Exception: + pass + parts = [repr(a) for a in args] + parts += [f"{k}={v!r}" for k, v in sorted(kwargs.items())] + return "(" + ", ".join(parts) + ")" + + +def _make_wrapper( + fn: Callable[..., R], + op: str, + dsl: str, + key_fn: Callable[..., str] | None, + sample: Callable[[], tuple[int | None, int | None]], +) -> Callable[..., R]: + """Shared instrumentation core for both DSL entry points. + + ``sample()`` returns a ``(hits, misses)`` snapshot of the relevant cache; + a ``misses`` increase across the call means a real compile fired. Timing, + error handling, classification, and emission are identical across DSLs -- + only ``sample`` (and the reported ``dsl``) differ. + """ + + @functools.wraps(fn) + def wrapper(*args: Any, **kwargs: Any) -> R: + # Fast path: do nothing extra unless a sink is listening. This runs on + # every call to the wrapped fn (for CuTeDSL, every op invocation), so + # the no-listener cost must stay at one predicate check. + if not _listening(): + return fn(*args, **kwargs) + + _, misses_before = sample() + start = time.perf_counter() + try: + result = fn(*args, **kwargs) + outcome_is_error = False + except Exception: + outcome_is_error = True + raise + finally: + wall_ms = (time.perf_counter() - start) * 1e3 + hits_after, misses_after = sample() + compiled = ( + not outcome_is_error + and misses_before is not None + and misses_after is not None + and misses_after > misses_before + ) + if outcome_is_error: + outcome = "error" + else: + outcome = "compiled" if compiled else "cache_hit" + _emit( + CompileEvent( + op=op, + dsl=dsl, + outcome=outcome, + compiled=compiled, + wall_ms=wall_ms, + key=_format_key(args, kwargs, key_fn), + hits=hits_after or 0, + misses=misses_after or 0, + ) + ) + return result + + return wrapper + + +def _cache_info_sampler(fn: Any) -> Callable[[], tuple[int | None, int | None]]: + """Sampler reading ``(hits, misses)`` from a ``jit_cache`` wrapper. + + Defensive: the wrapped callable may not be ``jit_cache``-decorated (e.g. + a plain function in tests). Then we report ``(None, None)`` and the core + still times the call, just without compile/hit classification. + """ + + def sample() -> tuple[int | None, int | None]: + info = getattr(fn, "cache_info", None) + if info is None: + return None, None + try: + ci = info() + return ci.hits, ci.misses + except Exception: + return None, None + + return sample + + +def instrument_cutedsl_compile( + op: str, + *, + key_fn: Callable[..., str] | None = None, +) -> Callable[[Callable[..., R]], Callable[..., R]]: + """Instrument a CuTeDSL (``@jit_cache``-decorated) compile function. + + Args: + op: Operator symbol being compiled for, e.g. ``"aten::topk"``. + key_fn: Optional callable with the wrapped function's signature + returning a short string describing the compile key for logs. + Defaults to a repr of the args/kwargs. + + Returns a decorator. The decorated function behaves identically to the + original (same return value, same caching); it only adds a log line and + a tlparse artifact per call. Errors raised by the wrapped compile are + timed, reported with ``outcome="error"``, and re-raised unchanged. + """ + + def decorator(fn: Callable[..., R]) -> Callable[..., R]: + wrapper = _make_wrapper(fn, op, "cutedsl", key_fn, _cache_info_sampler(fn)) + # Forward jit_cache's bespoke attributes (functools.wraps doesn't copy + # them) so the instrumented function stays a drop-in for callers that + # introspect the cache. + for attr in ("cache", "cache_clear", "cache_info"): + if hasattr(fn, attr): + setattr(wrapper, attr, getattr(fn, attr)) + return wrapper + + return decorator + + +def _triton_cache_size(kernel: Any) -> int | None: + """Compiled-variant count across one JITFunction's per-device caches. + + Triton stores one entry per specialized variant in + ``JITFunction.device_caches[device]``, a ``(kernel_cache, ...)`` tuple + whose first element is the dict of compiled kernels. The count grows by + one each time a new (signature, constexpr, options) variant compiles, so + a delta across a launch tells us whether *this* kernel compiled. Returns + None if the object doesn't expose ``device_caches`` (a future Triton that + renames this, or a non-kernel in tests). + """ + caches = getattr(kernel, "device_caches", None) + if caches is None: + return None + try: + return sum(len(per_device[0]) for per_device in caches.values()) + except Exception: + return None + + +class InstrumentedTritonKernel: + """Transparent proxy over a single ``@triton.jit`` kernel. + + Watches only this kernel's ``device_caches``, so a launch that grows the + variant count is unambiguously *this* kernel compiling -- two kernels in + one module never collide. All attribute access except the ``kernel[grid]`` + launch path is delegated to the wrapped kernel, so the proxy is a drop-in + for the original ``JITFunction`` for attribute/method use (``.warmup``, + ``.cache_key``). + + Composition with ``torch.library.wrap_triton``: that API does a strict + ``isinstance(JITFunction)`` check and would reject this proxy, but it + targets a different path (export/tracing, where the compile does not run + through our eager launch). When a native op needs ``wrap_triton``, pass the + raw kernel via :attr:`jit_kernel`: ``wrap_triton(my_kernel.jit_kernel)``. + """ + + def __init__( + self, + kernel: Any, + op: str, + key_fn: Callable[..., str] | None, + ) -> None: + self._kernel = kernel + self._op = op + self._key_fn = key_fn + + @property + def jit_kernel(self) -> Any: + """The wrapped raw ``JITFunction`` (e.g. for ``wrap_triton``).""" + return self._kernel + + def _sample(self) -> tuple[int | None, int | None]: + # Triton has no hit counter; this kernel's variant count stands in for + # `misses`, so a delta across the launch means a fresh compile. + return None, _triton_cache_size(self._kernel) + + def __getitem__(self, grid: Any) -> Callable[..., Any]: + # kernel[grid](*args) is the launch path -- wrap the bound launcher in + # the shared core so the compile that may fire inside it is recorded. + launcher = self._kernel[grid] + return _make_wrapper(launcher, self._op, "triton", self._key_fn, self._sample) + + def __getattr__(self, name: str) -> Any: + # Delegate everything else (warmup, cache_key, wrap_triton hooks, ...) + # to the real kernel. Only triggered for names not set on the proxy. + return getattr(self._kernel, name) + + +def instrument_triton_kernel( + op: str, + *, + key_fn: Callable[..., str] | None = None, +) -> Callable[[Any], InstrumentedTritonKernel]: + """Instrument a single ``@triton.jit`` kernel, stacked above the jit:: + + @instrument_triton_kernel("aten::bmm") + @triton.jit + def _bmm_kernel(...): ... + + Unlike CuTeDSL, a Triton kernel compiles lazily *inside* its + ``kernel[grid](...)`` launch and caches variants on the kernel object. So + rather than wrap a separate compile fn, wrap the kernel itself: the proxy + watches that one kernel's variant count and records a compile when the + launch grows it. Because compile and launch are fused, ``wall_ms`` on a + miss is compile + host-launch latency (compile dominates); on a hit it is + just host-launch latency. + + Args: + op: Operator symbol being compiled for, e.g. ``"aten::bmm"``. + key_fn: Optional callable with the kernel's launch-arg signature + returning a short string for logs (the constexprs it sees, e.g. + ``BLOCK``, are the actual compile key). Defaults to a repr. + """ + + def decorator(kernel: Any) -> InstrumentedTritonKernel: + return InstrumentedTritonKernel(kernel, op, key_fn) + + return decorator + + +def _helion_cache_size(kernel: Any) -> int | None: + """Compiled-config count across a Helion Kernel's bound specializations. + + Helion stores compiled configs in ``Kernel._bound_kernels[*]._compile_cache``; + the total grows by one each time a new configuration compiles, so a delta + across a call tells us whether *this* kernel compiled. Returns None if the + object doesn't expose these private attributes (a future Helion that renames + them, or a non-kernel in tests). + """ + bound_kernels = getattr(kernel, "_bound_kernels", None) + if bound_kernels is None: + return None + try: + return sum( + len(getattr(bound, "_compile_cache", ())) + for bound in bound_kernels.values() + ) + except Exception: + return None + + +class InstrumentedHelionKernel: + """Transparent proxy over a Helion ``Kernel`` compile cache.""" + + def __init__( + self, + kernel: Any, + op: str, + key_fn: Callable[..., str] | None, + ) -> None: + self._kernel = kernel + self._wrapped = _make_wrapper(kernel, op, "helion", key_fn, self._sample) + + @property + def helion_kernel(self) -> Any: + return self._kernel + + def _sample(self) -> tuple[int | None, int | None]: + return None, _helion_cache_size(self._kernel) + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self._wrapped(*args, **kwargs) + + def __getattr__(self, name: str) -> Any: + return getattr(self._kernel, name) + + +def instrument_helion_kernel( + op: str, + *, + key_fn: Callable[..., str] | None = None, +) -> Callable[[Any], InstrumentedHelionKernel]: + """Instrument a Helion ``Kernel`` without importing Helion eagerly.""" + + def decorator(kernel: Any) -> InstrumentedHelionKernel: + return InstrumentedHelionKernel(kernel, op, key_fn) + + return decorator + + +# --------------------------------------------------------------------------- +# Combined decorators: the recommended one-decorator surface for native ops. +# They apply the DSL's own cache/jit *and* the instrumentation, so the op +# author writes a single decorator on a bare function and can't get the +# stacking order wrong. The lower-level instrument_* helpers above remain for +# custom composition. +# --------------------------------------------------------------------------- + + +def instrumented_cutedsl_cache( + op: str, + *, + key_fn: Callable[..., str] | None = None, +) -> Callable[[Callable[..., R]], Callable[..., R]]: + """Cache + instrument a CuTeDSL compile function in one decorator:: + + @instrumented_cutedsl_cache("aten::topk") + def _compile_topk_radix(N, K, deterministic): + return cute.compile(...) + + Equivalent to ``instrument_cutedsl_compile(op) `` stacked above the + vendored ``@jit_cache``. ``jit_cache`` is imported lazily so plain + ``import torch._native`` doesn't pull in the CuTeDSL runtime. + """ + # Lazy import: quack.cache pulls in cutlass, absent on CPU-only builds. + from torch._vendor.quack.cache import jit_cache + + def decorator(fn: Callable[..., R]) -> Callable[..., R]: + return instrument_cutedsl_compile(op, key_fn=key_fn)(jit_cache(fn)) + + return decorator + + +def instrumented_triton_cache( + op: str, + *, + key_fn: Callable[..., str] | None = None, +) -> Callable[[Callable[..., R]], InstrumentedTritonKernel]: + """JIT + instrument a Triton kernel in one decorator:: + + @instrumented_triton_cache("aten::bmm") + def _bmm_kernel(...): # bare kernel body, no @triton.jit + ... + + Equivalent to ``instrument_triton_kernel(op)`` stacked above + ``@triton.jit``. ``triton`` is imported lazily so plain + ``import torch._native`` doesn't pull in the Triton runtime. + """ + # Lazy import: keep Triton out of `import torch._native`. + import triton + + def decorator(fn: Callable[..., R]) -> InstrumentedTritonKernel: + return instrument_triton_kernel(op, key_fn=key_fn)(triton.jit(fn)) + + return decorator + + +def instrumented_helion_kernel( + op: str, + *, + aot: bool = False, + key_fn: Callable[..., str] | None = None, + **settings: object, +) -> Callable[[Callable[..., R]], InstrumentedHelionKernel]: + """Create and instrument a regular or AOT Helion kernel.""" + import helion # pyrefly: ignore[missing-import] + import helion.experimental # pyrefly: ignore[missing-import] + + kernel_decorator = helion.experimental.aot_kernel if aot else helion.kernel + + def decorator(fn: Callable[..., R]) -> InstrumentedHelionKernel: + return instrument_helion_kernel(op, key_fn=key_fn)( + kernel_decorator(**settings)(fn) + ) + + return decorator diff --git a/.venv/lib/python3.12/site-packages/torch/_native/nvmath_utils.py b/.venv/lib/python3.12/site-packages/torch/_native/nvmath_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..064d4e3a0b7ef96390c3cdfb6f2fd0b6762dfa51 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/nvmath_utils.py @@ -0,0 +1,68 @@ +"""Shared helpers for native ops backed by nvmath-python / cuSOLVER. + +Centralizes nvmath availability checks, cuSOLVER version gating, and cuSOLVER +handle management so multiple native ops (e.g. linalg.polar, and upcoming +matmul-family ops) don't each reimplement them. + +All functions here are import-light at module load (nvmath is only imported +inside the function bodies, lazily, on first use) so importing this module does +not pull in the nvmath/cuda runtime or initialize CUDA. +""" + +import torch + +from .common_utils import _unavailable_reason + + +# (package_name, importable_module) pairs probed without importing. +_NVMATH_DEPS = [ + ("nvmath-python", "nvmath.bindings"), +] + + +def nvmath_unavailable_reason() -> str | None: + """Return a human-readable reason nvmath is unavailable, or None if present. + + Does not import nvmath (uses importlib.util.find_spec under the hood). + """ + return _unavailable_reason(_NVMATH_DEPS) + + +def cusolver_version() -> int | None: + """cuSOLVER runtime version as major*1000 + minor*100 + patch, or None. + + Queries cusolverGetVersion through nvmath, against the exact cuSOLVER + library nvmath dlopens (which is whatever the loader resolves -- the system + CUDA install or the nvidia-cu* wheels a torch build depends on). The encoded + value does not include the build number, so it can gate out runtimes that + lack a symbol entirely but cannot distinguish patch builds. + """ + try: + from nvmath.bindings import cusolver # pyrefly: ignore[missing-import] + + return cusolver.get_version() + except Exception: + return None + + +# One cuSOLVER handle per device, reused for the process lifetime. Handles are +# bound to the CUDA device that is current when cusolverDnCreate runs, so the +# handle must be created -- and later used -- with its device active. +# +# NOTE: this creates a dedicated handle rather than reusing aten's cuSOLVER +# handle. A future improvement is to reuse the handle PyTorch already maintains +# (see at::cuda::getCurrentCUDASolverDnHandle) to avoid the extra context. +_handles: dict[torch.device, int] = {} + + +def get_cusolver_handle(device: torch.device) -> int: + """Return a cached cuSOLVER Dn handle bound to ``device``.""" + from nvmath.bindings import cusolverDn as cs # pyrefly: ignore[missing-import] + + handle = _handles.get(device) + if handle is None: + # Create under the target device so the handle is bound to it. + with torch.cuda.device(device): + handle = cs.create() + _handles[device] = handle + return handle diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/__init__.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..47e2652b52b151b0d13211f0803bea7a861c5f5e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/__init__.py @@ -0,0 +1 @@ +from . import bmm_outer_product, foreach_mm, norm, polar, scatter_add, sum, topk diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95f29a038351ab78fdfbe8f544f1a36605710611 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/__init__.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0b84de34061559cf33fe8322a6d23d7adcdf2221 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/__init__.py @@ -0,0 +1,4 @@ +from .triton_impl import register_to_dispatch + + +register_to_dispatch() diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..827e48642d8a5a25ba1c76a2b9646931b8e7c5a4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/__pycache__/triton_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/__pycache__/triton_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcd9cc15c75aa7c56e0f5a37cfb6bc76aaf7040e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/__pycache__/triton_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/__pycache__/triton_kernels.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/__pycache__/triton_kernels.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dda2732c1f53b77e74732909a5270928f968cb6d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/__pycache__/triton_kernels.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/triton_impl.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/triton_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..cb86365a823f21bd48ef304998de01997788f746 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/triton_impl.py @@ -0,0 +1,63 @@ +import torch + +from ... import triton_utils as tu + + +def _is_outer_product(a: torch.Tensor, b: torch.Tensor) -> bool: + return ( + a.ndim == 3 + and b.ndim == 3 + and a.shape[2] == 1 + and b.shape[1] == 1 + and a.numel() > 0 + and b.numel() > 0 + and not a.is_complex() + ) + + +def _bmm_outer_product_impl( + a: torch.Tensor, + b: torch.Tensor, + *args, + **kwargs, +) -> torch.Tensor: + from .triton_kernels import bmm_outer_product + + with torch.accelerator.device_index(a.get_device()): + return bmm_outer_product(a, b) + + +def _is_acc_tensor(t: torch.Tensor) -> bool: + acc = torch.accelerator.current_accelerator() + return acc is not None and acc.type == t.device.type + + +def _bmm_outer_product_cond( + a: torch.Tensor, + b: torch.Tensor, + *args, + **kwargs, +) -> bool: + # a and b are read-only here: the kernel wraps them in ConstTensorWrapper and + # reads through const_data_ptr(), so copy-on-write inputs are not + # materialized and need not be excluded. + if _is_acc_tensor(a) and a.device == b.device and _is_outer_product(a, b): + return True + return False + + +def _register_for_dispatch_key(dispatch_key: str) -> None: + tu.register_op_override( + "aten", + "bmm", + dispatch_key, + cond=_bmm_outer_product_cond, + impl=_bmm_outer_product_impl, + allow_multiple_override=True, + ) + + +def register_to_dispatch() -> None: + _register_for_dispatch_key("CUDA") + if torch.xpu._is_compiled(): + _register_for_dispatch_key("XPU") diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/triton_kernels.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/triton_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..fbe236d1617b368a59e435cad151ca1da5ce42a1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/bmm_outer_product/triton_kernels.py @@ -0,0 +1,104 @@ +import triton +import triton.language as tl + +import torch +from torch._native.instrumentation import instrumented_triton_cache + +from ...triton import ConstTensorWrapper + + +def _bmm_log_key(a, b, out, B, M, N, *strides, BLOCK_M, BLOCK_N) -> str: + # Receives the kernel's launch args; BLOCK_M/BLOCK_N are the constexprs + # that (with shapes/dtype) form the Triton compile key. + return f"bmm_outer B={B} M={M} N={N} {a.dtype} BLOCK_M={BLOCK_M} BLOCK_N={BLOCK_N}" + + +@instrumented_triton_cache("aten::bmm", key_fn=_bmm_log_key) +def _bmm_outer_product_kernel( + A_ptr, + B_ptr, + OUT_ptr, + B_dim, + M, + N, + stride_ab, + stride_am, + stride_bb, + stride_bn, + stride_ob, + stride_om, + stride_on, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, +): + pid = tl.program_id(0) + + grid_m = tl.cdiv(M, BLOCK_M) + grid_n = tl.cdiv(N, BLOCK_N) + tiles_per_batch = grid_m * grid_n + + pid_b = pid // tiles_per_batch + pid_mn = pid % tiles_per_batch + pid_m = pid_mn // grid_n + pid_n = pid_mn % grid_n + + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + + mask_m = rm < M + mask_n = rn < N + + a = tl.load(A_ptr + pid_b * stride_ab + rm * stride_am, mask=mask_m, other=0.0) + b = tl.load(B_ptr + pid_b * stride_bb + rn * stride_bn, mask=mask_n, other=0.0) + + out = a[:, None] * b[None, :] + + mask = mask_m[:, None] & mask_n[None, :] # pyrefly: ignore[bad-index] + tl.store( + OUT_ptr + pid_b * stride_ob + rm[:, None] * stride_om + rn[None, :] * stride_on, + out, + mask=mask, + ) + + +def _pick_block_sizes(m: int, n: int) -> tuple[int, int]: + """I swept over some shapes and in the future we should figure out @autotune story""" + if m <= 32: + block_m = triton.next_power_of_2(m) + elif m <= 96: + block_m = 32 + elif m <= 192: + block_m = 64 + else: + block_m = 128 + return block_m, min(triton.next_power_of_2(n), 128) + + +def bmm_outer_product(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + B, M, _ = a.shape + N = b.shape[2] + + out = torch.empty(B, M, N, dtype=a.dtype, device=a.device) + + BLOCK_M, BLOCK_N = _pick_block_sizes(M, N) + + # a and b are read-only inputs; wrap them so a copy-on-write tensor is read + # through const_data_ptr() and not materialized. out is written directly. + _bmm_outer_product_kernel[(B * triton.cdiv(M, BLOCK_M) * triton.cdiv(N, BLOCK_N),)]( + ConstTensorWrapper(a), + ConstTensorWrapper(b), + out, + B, + M, + N, + a.stride(0), + a.stride(1), + b.stride(0), + b.stride(2), + out.stride(0), + out.stride(1), + out.stride(2), + BLOCK_M=BLOCK_M, + BLOCK_N=BLOCK_N, + ) + return out diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/__init__.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a93cdfbea37eefb1dac5b1f5bca43dffc405a0b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/__init__.py @@ -0,0 +1,4 @@ +from .impl import register_to_dispatch + + +register_to_dispatch() diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f73b42f85a5b400e20f8f64928aac7eceaef23b7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/__pycache__/impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/__pycache__/impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6db6afacb375773f0331ef70cef12300a32d130e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/__pycache__/impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/__pycache__/nvmath_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/__pycache__/nvmath_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c29d7309eeb90822af5cb21d123be44b4b42c52 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/__pycache__/nvmath_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/impl.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/impl.py new file mode 100644 index 0000000000000000000000000000000000000000..35cf0f238b1caacb1d2efc38454f88f88389a38f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/impl.py @@ -0,0 +1,273 @@ +""" +Python override for aten::_foreach_mm. Supports bf16 and fp32. + +Dispatch prerequisites: + CUDA SM90+, not HIP + equal-length lists with >= 2 tensors + same CUDA device, same bf16/fp32 dtype + 2D dense/non-overlapping tensors + same row/column-major orientation across groups + matching K, K,N > 0, K,N 16-byte aligned + +Dispatch: + nvmath cublasLt grouped GEMM: + - bf16 + - nvmath installed + |-- YES --> nvmath cublasLt grouped GEMM (uniform and mixed shapes, any G) + | + torch._grouped_mm with offs: + - non-nvmath path + - max(M,N,K) < 2048 + - uniform K,N + - G < 1024 + |-- YES --> torch.cat + torch._grouped_mm with offs (uniform or variable-M) + | + fallback loop: + - non-nvmath path + - max(M,N,K) < 2048 + |-- YES --> fallback loop: torch.mm per input pair + | + |-- else -> native _foreach_mm fallback (loop of at::mm) + +Notes: +- cublasLt grouped GEMM is bf16-only (fp32 returns CUBLAS_STATUS_NOT_SUPPORTED). +- At dim >= 2048 each mm saturates the GPU; native fallback is equivalent. +""" + +import warnings +from functools import cache +from typing import Literal + +import torch + +from ... import registry +from ...common_utils import _unavailable_reason + + +_nvmath_warned = False + +_NVMATH_DEPS = [ + ("nvmath-python", "nvmath.bindings"), +] + +# cublasLtGroupedMatrixLayoutCreate, used by the nvmath grouped GEMM path, was +# introduced in cuBLAS 13.2.0 (CUDA 13.1) and is experimental as of that release. +# cublasLtGetVersion() encodes the version as 10000*major + 100*minor + patch. +# This is the cuBLAS library version, not the CUDA toolkit version. +_MIN_CUBLASLT_GROUPED_GEMM_VERSION = 130200 + + +# Cached: availability is a process-global property of the loaded cuBLASLt. +@cache +def _check_nvmath_cublaslt() -> bool: + if _unavailable_reason(_NVMATH_DEPS) is not None: + return False + try: + from nvmath.bindings import cublasLt # pyrefly: ignore[missing-import] + + return cublasLt.get_version() >= _MIN_CUBLASLT_GROUPED_GEMM_VERSION + except Exception: + return False + + +def _k_n_16_byte_aligned(a: torch.Tensor, b: torch.Tensor, elem_size: int) -> bool: + return (a.size(1) * elem_size) % 16 == 0 and (b.size(1) * elem_size) % 16 == 0 + + +def _foreach_mm_cond( + self: list[torch.Tensor], + mat2: list[torch.Tensor], +) -> bool: + if len(self) < 2 or len(self) != len(mat2): + return False + + first_a = self[0] + first_b = mat2[0] + + if not first_a.is_cuda or not first_b.is_cuda: + return False + if torch.version.hip: + return False + if first_a.dtype != first_b.dtype: + return False + if first_a.dtype not in {torch.bfloat16, torch.float32}: + return False + props = torch.cuda.get_device_properties(first_a.device) + if props.major < 9: + return False + + first_a_rm = first_a.stride(-1) == 1 + first_b_rm = first_b.stride(-1) == 1 + + elem_size = first_a.element_size() + nvmath_ok = first_a.dtype == torch.bfloat16 and _check_nvmath_cublaslt() + max_dim = 0 + + for i in range(len(self)): + a, b = self[i], mat2[i] + if a.dim() != 2 or b.dim() != 2: + return False + if a.size(1) != b.size(0): + return False + # K or N == 0 not supported by cutlass_grouped_mm + if a.size(1) == 0 or b.size(1) == 0: + return False + if not torch.ops.aten.is_non_overlapping_and_dense.default(a): + return False + if not torch.ops.aten.is_non_overlapping_and_dense.default(b): + return False + if not a.is_cuda or not b.is_cuda: + return False + if a.device != first_a.device or b.device != first_a.device: + return False + if a.dtype != first_a.dtype or b.dtype != first_a.dtype: + return False + K_i, N_i = a.size(1), b.size(1) + aligned = _k_n_16_byte_aligned(a, b, elem_size) + if nvmath_ok and not aligned: + nvmath_ok = False + if not nvmath_ok and not aligned: + return False + max_dim = max(max_dim, a.size(0), K_i, N_i) + if i > 0: + if (a.stride(-1) == 1) != first_a_rm or (b.stride(-1) == 1) != first_b_rm: + return False + + if not nvmath_ok and max_dim >= 2048: + return False + + return True + + +def _foreach_mm_impl_stack( + self: list[torch.Tensor], + mat2: list[torch.Tensor], +) -> list[torch.Tensor]: + # Router guarantees uniform K,N and group count < _CUTLASS_GROUPED_MM_GROUP_LIMIT. + # _grouped_mm with offs handles uniform and variable-M shapes in one kernel. + M_sizes = [a.size(0) for a in self] + A_cat = torch.cat(self, dim=0) # (sum_M, K) + B_3d = torch.stack(mat2) # (G, K, N) + offs = torch.tensor(M_sizes, dtype=torch.int32, device=self[0].device).cumsum( + 0, dtype=torch.int32 + ) + out_cat = torch._grouped_mm(A_cat, B_3d, offs=offs) # (sum_M, N) + return list(out_cat.split(M_sizes, dim=0)) + + +_ForeachMMCublasLt = None + + +def _get_nvmath_cls(): + global _ForeachMMCublasLt + if _ForeachMMCublasLt is None: + from torch._native.ops.foreach_mm.nvmath_impl import ForeachMMCublasLt + + _ForeachMMCublasLt = ForeachMMCublasLt + return _ForeachMMCublasLt + + +_nvmath_cache: dict[tuple, object] = {} + + +def _foreach_mm_impl_nvmath( + self: list[torch.Tensor], + mat2: list[torch.Tensor], +) -> list[torch.Tensor]: + G = len(self) + first_a = self[0] + a_row_major = first_a.stride(-1) == 1 + b_row_major = mat2[0].stride(-1) == 1 + shapes = tuple((a.size(0), b.size(1), a.size(1)) for a, b in zip(self, mat2)) + key = (shapes, a_row_major, b_row_major, first_a.device) + if key not in _nvmath_cache: + _nvmath_cache[key] = _get_nvmath_cls()( + shapes, G, a_row_major=a_row_major, b_row_major=b_row_major + ) + return _nvmath_cache[key](self, mat2) # pyrefly: ignore[not-callable] + + +# torch._grouped_mm's bf16 kernel requires group_count < 1024; nvmath has no cap. +_CUTLASS_GROUPED_MM_GROUP_LIMIT = 1024 + +_Route = Literal["nvmath_cublaslt_grouped_mm", "cutlass_grouped_mm", "mm_loop"] + + +def _can_use_nvmath_cublaslt_grouped_mm( + self: list[torch.Tensor], + mat2: list[torch.Tensor], +) -> bool: + # Metadata check only (bf16 + 16-byte-aligned N,K); does not check nvmath is installed + # (_check_nvmath_cublaslt). dtype on [0]; _foreach_mm_cond ensures uniform. + if self[0].dtype != torch.bfloat16 or mat2[0].dtype != torch.bfloat16: + return False + elem_size = self[0].element_size() + return all(_k_n_16_byte_aligned(a, b, elem_size) for a, b in zip(self, mat2)) + + +def _can_use_cutlass_grouped_mm( + self: list[torch.Tensor], + mat2: list[torch.Tensor], +) -> bool: + # torch._grouped_mm needs uniform K,N; its bf16 kernel needs < cap groups + if len(self) >= _CUTLASS_GROUPED_MM_GROUP_LIMIT: + return False + K, N = self[0].size(1), mat2[0].size(1) + return all(a.size(1) == K for a in self) and all( + b.size(0) == K and b.size(1) == N for b in mat2 + ) + + +def _foreach_mm_route(self: list[torch.Tensor], mat2: list[torch.Tensor]) -> _Route: + """Choose a backend route; assumes _foreach_mm_cond already validated inputs.""" + if _check_nvmath_cublaslt() and _can_use_nvmath_cublaslt_grouped_mm(self, mat2): + return "nvmath_cublaslt_grouped_mm" + if _can_use_cutlass_grouped_mm(self, mat2): + return "cutlass_grouped_mm" + return "mm_loop" + + +def _warn_nvmath_unavailable_once() -> None: + global _nvmath_warned + if _nvmath_warned: + return + _nvmath_warned = True + reason = ( + _unavailable_reason(_NVMATH_DEPS) + or "cuBLASLt lacks cublasLtGroupedMatrixLayoutCreate" + ) + warnings.warn( + f"_foreach_mm: nvmath cublasLt grouped GEMM unavailable ({reason}), " + f"using slower fallback.", + stacklevel=3, + ) + + +def _foreach_mm_impl( + self: list[torch.Tensor], + mat2: list[torch.Tensor], +) -> list[torch.Tensor]: + route = _foreach_mm_route(self, mat2) + if route == "nvmath_cublaslt_grouped_mm": + return _foreach_mm_impl_nvmath(self, mat2) + # warn once when nvmath-eligible inputs fall back only because nvmath is absent. + if ( + not _nvmath_warned + and _can_use_nvmath_cublaslt_grouped_mm(self, mat2) + and not _check_nvmath_cublaslt() + ): + _warn_nvmath_unavailable_once() + if route == "cutlass_grouped_mm": + return _foreach_mm_impl_stack(self, mat2) + return [torch.mm(a, b) for a, b in zip(self, mat2)] # mm_loop + + +def register_to_dispatch() -> None: + registry.register_op_override( + "native", + "aten", + "_foreach_mm", + "CUDA", + cond=_foreach_mm_cond, + impl=_foreach_mm_impl, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/nvmath_impl.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/nvmath_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..bff339eb1616f67f57d3b5184148e3507b130a6c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/foreach_mm/nvmath_impl.py @@ -0,0 +1,267 @@ +"""Cached cublasLt grouped GEMM via nvmath bindings.""" + +import ctypes + +from cuda.bindings.runtime import cudaDataType # pyrefly: ignore[missing-import] + +from nvmath.bindings import cublasLt # pyrefly: ignore[missing-import] +from nvmath.bindings.cublas import ( # pyrefly: ignore[missing-import] + ComputeType, + Operation, +) + +import torch + + +_cublaslt_workspaces: dict[tuple, torch.Tensor] = {} + + +def _get_cublaslt_workspace(device="cuda"): + ws_size = torch.backends.cuda.cublaslt_workspace_size() + key = (torch.device(device), ws_size) + if key not in _cublaslt_workspaces: + _cublaslt_workspaces[key] = torch.empty( + ws_size, dtype=torch.uint8, device=device + ) + return _cublaslt_workspaces[key], ws_size + + +def _set_attr(setter, handle, attr, val, ctype): + buf = (ctype * 1)(val) + setter(handle, attr, ctypes.addressof(buf), ctypes.sizeof(buf)) + + +class ForeachMMCublasLt: + """Cached cublasLt grouped GEMM. Supports uniform or mixed shapes per group.""" + + def __init__( + self, + shapes, + G, + a_row_major=True, + b_row_major=True, + dtype=torch.bfloat16, + device="cuda", + ): + """ + Args: + shapes: tuple of (M, N, K) triples, one per group + G: number of groups (must equal len(shapes)) + """ + if dtype != torch.bfloat16: + raise ValueError(f"ForeachMMCublasLt only supports bf16, got {dtype}") + + self.G = G + self._dtype = dtype + elem_size = dtype.itemsize + alignment = 16 // elem_size + + # cuBLAS col-major: C^T = mat2^T * self^T + # cuBLAS-A = mat2, cuBLAS-B = self + opa = Operation.N if b_row_major else Operation.T + opb = Operation.N if a_row_major else Operation.T + + # Per-group dimensions + Ms, Ns, Ks = zip(*shapes) + ldas = [n if b_row_major else k for n, k in zip(Ns, Ks)] + ldbs = [k if a_row_major else m for m, k in zip(Ms, Ks)] + N_paddeds = [(n + alignment - 1) // alignment * alignment for n in Ns] + + for vals in (Ms, Ns, Ks, ldas, ldbs, N_paddeds): + for v in vals: + if v > 2**31 - 1: + raise ValueError( + f"ForeachMMCublasLt: dimension {v} exceeds int32 range" + ) + + # Per-group output layout: allocate one contiguous buffer with + # max(M) x max(N_padded) per group, then narrow each slice to actual (M, N) + self._out_Ns = Ns + self._out_Ms = Ms + self._out_N_paddeds = N_paddeds + self._max_M = max(Ms) + self._max_N_padded = max(N_paddeds) + self._out_stride_bytes = self._max_M * self._max_N_padded * elem_size + self._uniform = len(set(Ms)) == 1 and len(set(Ns)) == 1 + # ldd must match the physical stride in the contiguous output buffer + N_paddeds = [self._max_N_padded] * G + + # Device-side dim arrays (6 x G) + # cublas_m=N, cublas_n=M, cublas_k=K + cublas_ms = list(Ns) + cublas_ns = list(Ms) + cublas_ks = list(Ks) + dims = torch.tensor( + [cublas_ms, cublas_ns, cublas_ks, ldas, ldbs, N_paddeds], + dtype=torch.int32, + device=device, + ) + d_m, d_n, d_k, d_lda, d_ldb, d_ldd = [dims[i] for i in range(6)] + + # Pinned host + device buffers for pointer arrays [Aptr|Bptr|Dptr] + self._pinned = torch.empty(3 * G, dtype=torch.int64, pin_memory=True) + self._pinned_raw = ctypes.cast( + self._pinned.data_ptr(), ctypes.POINTER(ctypes.c_int64) + ) + self._dev_ptrs = torch.empty(3 * G, dtype=torch.int64, device=device) + + # alpha=1.0, beta=0.0 as device float32 + scalars = torch.tensor([1.0, 0.0], dtype=torch.float32, device=device) + self._alpha_ptr = scalars.data_ptr() + self._beta_ptr = scalars.data_ptr() + 4 + self._scalars = scalars # prevent GC + + self._workspace, self._ws_bytes = _get_cublaslt_workspace(device) + self._ws_ptr = self._workspace.data_ptr() + self._dims = dims # prevent GC + + # cublasLt matmul descriptor + # Reuse PyTorch's cuBLAS handle (cublasHandle_t is valid as cublasLtHandle_t) + handle = torch.cuda.current_blas_handle() + self._handle = handle + desc = cublasLt.matmul_desc_create( + ComputeType.COMPUTE_32F, cudaDataType.CUDA_R_32F + ) + + def _set_desc(attr, val): + _set_attr( + cublasLt.matmul_desc_set_attribute, desc, attr, val, ctypes.c_int32 + ) + + _set_desc(cublasLt.MatmulDescAttribute.TRANSA, opa) + _set_desc(cublasLt.MatmulDescAttribute.TRANSB, opb) + _set_desc( + cublasLt.MatmulDescAttribute.POINTER_MODE, cublasLt.PointerMode.DEVICE + ) + self._desc = desc + + # Grouped matrix layouts: A=mat2, B=self, D=output (C reuses D since beta=0) + # Layout rows/cols are the physical dimensions seen by cuBLAS (before op) + cdt = cudaDataType.CUDA_R_16BF + _gl = cublasLt.grouped_matrix_layout_create + a_rows = d_m if opa == Operation.N else d_k + a_cols = d_k if opa == Operation.N else d_m + b_rows = d_k if opb == Operation.N else d_n + b_cols = d_n if opb == Operation.N else d_k + self._Ad = _gl(cdt, G, a_rows.data_ptr(), a_cols.data_ptr(), d_lda.data_ptr()) + self._Bd = _gl(cdt, G, b_rows.data_ptr(), b_cols.data_ptr(), d_ldb.data_ptr()) + self._Dd = _gl(cdt, G, d_m.data_ptr(), d_n.data_ptr(), d_ldd.data_ptr()) + + # Heuristic search (run once, algo reused for all calls) + pref = cublasLt.matmul_preference_create() + Attr = cublasLt.MatmulPreferenceAttribute + _set_attr( + cublasLt.matmul_preference_set_attribute, + pref, + Attr.MAX_WORKSPACE_BYTES, + self._ws_bytes, + ctypes.c_uint64, + ) + avg_N = sum(Ns) // G + avg_M = sum(Ms) // G + avg_K = sum(Ks) // G + for attr, val in [ + (Attr.GROUPED_DESC_D_AVERAGE_ROWS, avg_N), + (Attr.GROUPED_DESC_D_AVERAGE_COLS, avg_M), + (Attr.GROUPED_AVERAGE_REDUCTION_DIM, avg_K), + ]: + _set_attr( + cublasLt.matmul_preference_set_attribute, + pref, + attr, + val, + ctypes.c_int64, + ) + + # cublasLtMatmulHeuristicResult_t is 96 bytes; algo field is at offset 0 + heur_buf = (ctypes.c_byte * 96)() + ret = (ctypes.c_int32 * 1)(0) + cublasLt.matmul_algo_get_heuristic( + handle, + desc, + self._Ad, + self._Bd, + self._Dd, + self._Dd, + pref, + 1, + ctypes.addressof(heur_buf), + ctypes.addressof(ret), + ) + if ret[0] == 0: + raise RuntimeError("cublasLt grouped GEMM: no algorithm found") + cublasLt.matmul_preference_destroy(pref) + + self._algo_ptr = ctypes.addressof(heur_buf) + self._heur_buf = heur_buf # prevent GC + + # Cached pointer offsets into _dev_ptrs + base = self._dev_ptrs.data_ptr() + ptr_size = torch.int64.itemsize + self._dev_Aptr = base + self._dev_Bptr = base + G * ptr_size + self._dev_Dptr = base + 2 * G * ptr_size + + def __call__(self, self_list, mat2_list): + G = self.G + max_M = self._max_M + max_Np = self._max_N_padded + + # Single contiguous allocation, sliced per group + out_buf = torch.empty( + G, max_M, max_Np, dtype=self._dtype, device=self._dev_ptrs.device + ) + + # Fill pinned host buffer with device pointers, async copy to GPU + h = self._pinned_raw + out_base = out_buf.data_ptr() + out_stride = self._out_stride_bytes + for i in range(G): + h[i] = mat2_list[i].data_ptr() + h[G + i] = self_list[i].data_ptr() + h[2 * G + i] = out_base + i * out_stride + self._dev_ptrs.copy_(self._pinned, non_blocking=True) + + cublasLt.matmul( + self._handle, + self._desc, + self._alpha_ptr, + self._dev_Aptr, + self._Ad, + self._dev_Bptr, + self._Bd, + self._beta_ptr, + self._dev_Dptr, + self._Dd, # C (unused, beta=0) + self._dev_Dptr, + self._Dd, # D (output) + self._algo_ptr, + self._ws_ptr, + self._ws_bytes, + torch.cuda.current_stream().cuda_stream, + ) + + # unbind is a single C++ call creating all G views at once. + # Narrow only when output shape differs from the buffer slot size. + results = out_buf.unbind(0) + if self._uniform: + M, N = self._out_Ms[0], self._out_Ns[0] + if M != self._max_M or N != self._max_N_padded: + return [r[:M, :N] for r in results] + return list(results) + return [r[: self._out_Ms[i], : self._out_Ns[i]] for i, r in enumerate(results)] + + def __del__(self): + for attr in ("_Dd", "_Bd", "_Ad"): + d = getattr(self, attr, None) + if d is not None: + try: + cublasLt.matrix_layout_destroy(d) + except Exception: + pass + desc = getattr(self, "_desc", None) + if desc is not None: + try: + cublasLt.matmul_desc_destroy(desc) + except Exception: + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/__init__.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d657468a7780761a7c2fd7c729a3c8f05ad1483b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/__init__.py @@ -0,0 +1,4 @@ +from .rmsnorm_impl import register_rmsnorm_overrides + + +register_rmsnorm_overrides() diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8b4b46493d655fcde425e99dc926a294d18869b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/__pycache__/norms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/__pycache__/norms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93fe4f77fcc40085b81be851193d116a2b84fe7e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/__pycache__/norms.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/__pycache__/rmsnorm_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/__pycache__/rmsnorm_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71e61110989544ef686163e1e3f9a8d0ca618d56 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/__pycache__/rmsnorm_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/norms.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/norms.py new file mode 100644 index 0000000000000000000000000000000000000000..331d076f5b275c8a47db18f02c411c076868d18c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/norms.py @@ -0,0 +1,227 @@ +"""Adaptor for quack's 2-D RMSNorm kernel interface to match ATen op signatures. + +These functions handle tensor reshaping, memory allocation, and call quack's +compiled kernels directly (bypassing the ``@torch.library.custom_op`` wrapper +to avoid dispatcher overhead). +""" + +from __future__ import annotations + +import functools +import math + +import torch +from torch._native.instrumentation import instrument_cutedsl_compile + + +# quack's rmsnorm compile fns are vendored, so we can't decorate them in +# place. Wrap them once at the call site instead -- they're @jit_cache so +# the instrumentation reads their cache_info(). Memoized so the wrapper (and +# its forwarded cache_info) is stable across calls. N is positional arg 6 in +# the fwd compile signature and arg 0 in the bwd one. +@functools.cache +def _instrumented_rmsnorm_fwd(): + from torch._vendor.quack.rmsnorm import _compile_rmsnorm_fwd + + return instrument_cutedsl_compile( + "aten::_fused_rms_norm", key_fn=lambda *a, **k: f"fwd N={a[6]}" + )(_compile_rmsnorm_fwd) + + +@functools.cache +def _instrumented_rmsnorm_bwd(): + from torch._vendor.quack.rmsnorm import _compile_rmsnorm_bwd + + return instrument_cutedsl_compile( + "aten::_fused_rms_norm_backward", + key_fn=lambda *a, **k: f"bwd N={a[0]}", + )(_compile_rmsnorm_bwd) + + +# quack imports `cutlass`, which is only installed on CUDA-enabled x86 Linux +# builds. Keep the import lazy so `torch._native.ops.norm.norms` stays +# importable on CPU-only builds (test_public_bindings / +# test_circular_dependencies walk every module under `torch.`). +def _torch2cute(t: torch.Tensor | None): # type: ignore[no-untyped-def] + from torch._vendor.quack import cute_dsl_utils as _cute_dsl_utils + + if t is None: + return None + return _cute_dsl_utils.torch2cute_dtype_map[t.dtype] + + +def _required_align_bytes(t: torch.Tensor, N: int) -> int: + # quack compiles the kernel assuming the input base pointer is aligned to + # the vectorized cp.async width: gcd(N, 128 // dtype_bits) elements. A + # contiguous tensor with a non-zero storage offset (e.g. buf[1:].view(M, N)) + # has fine strides but a misaligned base, which trips CuTe's runtime + # alignment check ("Misaligned Tensor data on argument #0"). + itemsize = t.element_size() + return math.gcd(N, 128 // (itemsize * 8)) * itemsize + + +def _const_data_ptr(t: torch.Tensor) -> int: + with torch._C.DisableTorchFunctionSubclass(): + return t.const_data_ptr() # type: ignore[attr-defined] + + +def _read_only(t: torch.Tensor | None): # type: ignore[no-untyped-def] + if t is None: + return None + from cutlass.cute.runtime import from_dlpack + + from torch.utils.dlpack import ReadOnlyTensorWrapper + + with torch._C.DisableTorchFunctionSubclass(): + t = ReadOnlyTensorWrapper(t) + return from_dlpack(t, enable_tvm_ffi=True) + + +def _reshape_2d(t: torch.Tensor, M: int, N: int) -> torch.Tensor: + align = _required_align_bytes(t, N) + if t.ndim == 2 and t.shape[0] == M and t.shape[1] == N and t.is_contiguous(): + # .contiguous() is a no-op on an already-contiguous tensor and would + # preserve a misaligned base; clone to force a fresh (aligned) buffer. + return t if _const_data_ptr(t) % align == 0 else t.clone() + out = t.reshape(M, N).contiguous() + # reshape can return a view that keeps the original (misaligned) storage + # offset, and .contiguous() then leaves it untouched. + return out if _const_data_ptr(out) % align == 0 else out.clone() + + +def _aligned_weight(w: torch.Tensor, N: int) -> torch.Tensor: + # Same trap as _reshape_2d: reshape(N).contiguous() is a no-op for a + # contiguous-but-offset weight, leaving a misaligned base. Weight is only + # N elements, so always clone rather than perf-gating like the input. + w = w.reshape(N).contiguous() + if _const_data_ptr(w) % _required_align_bytes(w, N) != 0: + w = w.clone() + return w + + +def _flatten_rstd(t: torch.Tensor, M: int) -> torch.Tensor: + if t.ndim == 1 and t.shape[0] == M: + return t + if t.is_contiguous() and t.numel() == M: + return t.detach().view(M) + return t.reshape(M).contiguous() + + +def quack_rmsnorm_fwd( + input: torch.Tensor, + weight: torch.Tensor | None, + normalized_shape: list[int], + eps: float, +) -> tuple[torch.Tensor, torch.Tensor]: + input_shape = input.shape + N = math.prod(normalized_shape) + M = input.numel() // N + # quack's kernel requires a contiguous 2-D input with trailing stride 1; + # a plain `.reshape(M, N)` can return a non-contiguous view. + x = _reshape_2d(input, M, N) + + out = torch.empty_like(x) + rstd = torch.empty(M, device=x.device, dtype=torch.float32) + + if weight is not None: + weight = _aligned_weight(weight, N) + + dtype = _torch2cute(x) + out_dtype = _torch2cute(out) + weight_dtype = _torch2cute(weight) + + kernel = _instrumented_rmsnorm_fwd()( + dtype, + out_dtype, + None, + weight_dtype, + None, + None, + N, + True, + False, + False, + per_head=False, + ) + # compile order: (x, weight, bias, res, out, res_out, rstd, mean, eps) + kernel(_read_only(x), _read_only(weight), None, None, out, None, rstd, None, eps) + + out = out.reshape(input_shape) + stat_shape = list(input_shape[: -len(normalized_shape)]) + [1] * len( + normalized_shape + ) + rstd = rstd.view(stat_shape) + return out, rstd + + +def quack_rmsnorm_bwd( + grad_out: torch.Tensor, + input: torch.Tensor, + rstd: torch.Tensor, + weight: torch.Tensor | None, + normalized_shape: list[int], + dw_mask: bool = True, +) -> tuple[torch.Tensor, torch.Tensor | None]: + N = math.prod(normalized_shape) + M = input.numel() // N + x = _reshape_2d(input, M, N) + dout = _reshape_2d(grad_out, M, N) + rstd_flat = _flatten_rstd(rstd, M) + + dx = torch.empty_like(x) + from torch._vendor.quack.rmsnorm_config import get_sm_count + + sm_count = get_sm_count(N, x.device) + + # quack's kernel requires a contiguous 1-D weight with matching dtype. + if weight is not None: + weight = _aligned_weight(weight, N) + + # quack treats `weight_dtype` (whether weight is present in the kernel) + # and `has_dw_partial` (whether to accumulate dw) as independent flags. + # dx's formula depends on weight, so we always hand weight to the kernel + # when the user supplied one; dw_mask only gates the dw_partial buffer. + dw_partial: torch.Tensor | None = None + if weight is not None and dw_mask: + dw_partial = torch.empty(sm_count, N, device=x.device, dtype=torch.float32) + + dtype = _torch2cute(x) + dout_dtype = _torch2cute(dout) + dx_dtype = _torch2cute(dx) + weight_dtype = _torch2cute(weight) + + kernel = _instrumented_rmsnorm_bwd()( + N, + dtype, + dout_dtype, + dx_dtype, + weight_dtype, + False, + None, + None, + dw_partial is not None, + per_head=False, + ) + # compile order: (x, weight, dout, dres_out, rstd, dx, dw_partial, dres, db_partial, sm_count) + kernel( + _read_only(x), + _read_only(weight), + _read_only(dout), + None, + _read_only(rstd_flat), + dx, + dw_partial, + None, + None, + sm_count, + ) + + dx = dx.reshape(input.shape) + # `dw_partial is not None` implies `weight is not None` (invariant from + # allocation above), but pyrefly can't see the dependency. + if dw_partial is not None: + weight_dtype_for_sum = weight.dtype # pyrefly: ignore[missing-attribute] + dw = dw_partial.sum(dim=0).reshape(normalized_shape).to(weight_dtype_for_sum) + else: + dw = None + return dx, dw diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/rmsnorm_impl.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/rmsnorm_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..6f67d110d17340b18114f198965ed052af6f050b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/norm/rmsnorm_impl.py @@ -0,0 +1,254 @@ +"""Quack-backed RMSNorm overrides for aten fused RMSNorm operators. + +Uses the vendored quack subset at ``torch._vendor.quack``. +""" +# mypy: allow-untyped-defs + +from __future__ import annotations + +import math + +import torch + +from ... import cutedsl_utils as cu +from .norms import _const_data_ptr, _required_align_bytes + + +def _is_supported(input: torch.Tensor) -> bool: + if input.device.type != "cuda": + return False + if torch.version.hip is not None: + return False + if input.dtype not in (torch.float16, torch.bfloat16, torch.float32): + return False + major, _ = torch.cuda.get_device_capability(input.device) + return major in (9, 10) + + +# quack splits each row across a CTA cluster (at most 16 on SM90/SM100, the +# only archs _is_supported accepts) and stages the per-CTA row tile in shared +# memory. Rows whose tile exceeds the smem budget even at the max cluster size +# cannot launch, and far beyond that (e.g. N=2^28) the CuTe DSL compiler hangs +# or crashes before any smem check could fire (gh-186800). Bound N here so +# such rows fall back to aten. The reserve covers the reduction buffer, +# mbarriers, and smem alignment (mirrors quack's _BWD_SMEM_RESERVED_BYTES). +_SMEM_RESERVED_BYTES = 4 * 1024 +_MAX_CLUSTER_N = 16 +# The kernel rounds the per-CTA tile up to vecsize * threads_per_row elements +# (reduction_base._get_tiled_copy). Both are powers of 2 with vecsize <= 8 and +# threads_per_row <= 256, so rounding up to 2048 never under-estimates. +_TILE_ROUND_ELEMS = 2048 +# RmsNormBwdConfig.smem_stages default; both analytical heuristics use it. +_BWD_SMEM_STAGES = 2 + + +def _smem_budget_bytes(device: torch.device) -> int: + props = torch.cuda.get_device_properties(device) + smem = getattr( + props, "shared_memory_per_block_optin", props.shared_memory_per_block + ) + return smem - _SMEM_RESERVED_BYTES + + +def _row_tile_elems(n: int) -> int: + per_cta = -(-n // _MAX_CLUSTER_N) + return -(-per_cta // _TILE_ROUND_ELEMS) * _TILE_ROUND_ELEMS + + +def _fwd_fits_smem(input: torch.Tensor, n: int) -> bool: + # Fwd smem holds one row tile of x (rmsnorm.py sX). + return _row_tile_elems(n) * input.element_size() <= _smem_budget_bytes(input.device) + + +def _bwd_fits_smem(input: torch.Tensor, grad_out: torch.Tensor, n: int) -> bool: + # Quack's RMSNormBackward.__init__ raises for N > 128K with fp32 x; fall + # back instead of surfacing its ValueError. + if input.element_size() >= 4 and n > 128 * 1024: + return False + # Bwd smem holds smem_stages buffers of both x and dout (rmsnorm.py + # sX/sdO). + tile_bytes = ( + _row_tile_elems(n) + * _BWD_SMEM_STAGES + * (input.element_size() + grad_out.element_size()) + ) + return tile_bytes <= _smem_budget_bytes(input.device) + + +# A contiguous input with a misaligned base pointer must be cloned before the +# kernel can run (see norms._reshape_2d). The clone's extra read+write only +# pays off once quack's bandwidth advantage over aten can absorb it: measured +# on B200 (fwd, bf16/fp32), clone+quack wins 1.8-2.9x at 2^24 elements and +# loses below 2^23. Misaligned inputs smaller than this fall back to aten. +# The threshold is a perf heuristic, not a correctness bound; it has not been +# measured on H100 (SM90), where the crossover may differ. Make it per-arch +# if H100 measurements show a meaningfully different break-even. +_MISALIGNED_MIN_NUMEL = 1 << 24 + + +def _misaligned_clone_unprofitable(t: torch.Tensor, n: int) -> bool: + # Only contiguous tensors hit the clone path in norms._reshape_2d; + # non-contiguous ones pay the reshape+contiguous materialization either + # way, which always lands on an aligned fresh buffer. + if not t.is_contiguous(): + return False + if _const_data_ptr(t) % _required_align_bytes(t, n) == 0: + return False + return t.numel() < _MISALIGNED_MIN_NUMEL + + +def _n_yields_valid_cp_size(n: int, dtype: torch.dtype) -> bool: + # quack picks vecsize = gcd(N, 128 // dtype_bits) and lowers each thread's + # gmem->smem copy to cp.async, whose PTX cp_size only accepts 32, 64, or + # 128 bits. Narrow dtypes with an unfriendly N (e.g. odd N for bf16/fp16) + # produce a 16-bit vector copy that fails CuTe IR verification at compile + # time; fall through to aten in that case. + dtype_bits = torch.finfo(dtype).bits + vecsize = math.gcd(n, 128 // dtype_bits) + return vecsize * dtype_bits in (32, 64, 128) + + +def _shape_is_valid( + input: torch.Tensor, + normalized_shape: list[int], + weight: torch.Tensor | None, +) -> bool: + # Mirror aten's _check_layer_norm_inputs: on any mismatch the aten path + # raises, so we fall through and let it produce the proper error rather + # than silently running the override on ill-shaped inputs. + n = len(normalized_shape) + if n < 1 or input.ndim < n: + return False + if list(input.shape[-n:]) != list(normalized_shape): + return False + if weight is not None and list(weight.shape) != list(normalized_shape): + return False + return True + + +def _fused_rms_norm_cond( + input: torch.Tensor, + normalized_shape: list[int], + weight: torch.Tensor | None, + eps: float | None, +) -> bool: + if not _is_supported(input): + return False + if not _shape_is_valid(input, normalized_shape, weight): + return False + # Weight must match input dtype and device for quack's kernel; mismatches + # are legal under aten (it casts), so fall through. + if weight is not None and ( + weight.dtype != input.dtype or weight.device != input.device + ): + return False + # Empty inputs crash quack with cudaErrorInvalidConfiguration -- the bad + # launch config poisons the CUDA context for subsequent calls. Quack's own + # rmsnorm_bwd guards against this with `if x.numel() > 0` (rmsnorm.py:1111) + # but the fwd path doesn't. + if input.numel() == 0: + return False + if not _n_yields_valid_cp_size(math.prod(normalized_shape), input.dtype): + return False + if not _fwd_fits_smem(input, math.prod(normalized_shape)): + return False + if _misaligned_clone_unprofitable(input, math.prod(normalized_shape)): + return False + # Non-contiguous weight would require a reshape+copy that we haven't + # measured; fall through to aten until we do. + if weight is not None and not weight.is_contiguous(): + return False + return True + + +def _fused_rms_norm_impl( + input: torch.Tensor, + normalized_shape: list[int], + weight: torch.Tensor | None, + eps: float | None, +) -> tuple[torch.Tensor, torch.Tensor]: + if eps is None: + # Match aten/src/ATen/native/cuda/layer_norm_kernel.cu:1841-1847: + # aten picks eps from the *accumulator* dtype, which is float32 for + # fp16/bf16/fp32 inputs (the only dtypes our cond accepts). + eps = torch.finfo(torch.float32).eps + + from .norms import quack_rmsnorm_fwd + + return quack_rmsnorm_fwd(input, weight, normalized_shape, eps) + + +def _fused_rms_norm_backward_cond( + grad_out: torch.Tensor, + input: torch.Tensor, + normalized_shape: list[int], + rstd: torch.Tensor, + weight: torch.Tensor | None, + output_mask: list[bool], +) -> bool: + if not _is_supported(input): + return False + if not _shape_is_valid(input, normalized_shape, weight): + return False + if weight is not None and ( + weight.dtype != input.dtype or weight.device != input.device + ): + return False + if input.numel() == 0: + return False + if not _n_yields_valid_cp_size(math.prod(normalized_shape), input.dtype): + return False + if not _bwd_fits_smem(input, grad_out, math.prod(normalized_shape)): + return False + n = math.prod(normalized_shape) + if _misaligned_clone_unprofitable(input, n) or _misaligned_clone_unprofitable( + grad_out, n + ): + return False + if weight is not None and not weight.is_contiguous(): + return False + return True + + +def _fused_rms_norm_backward_impl( + grad_out: torch.Tensor, + input: torch.Tensor, + normalized_shape: list[int], + rstd: torch.Tensor, + weight: torch.Tensor | None, + output_mask: list[bool], +) -> tuple[torch.Tensor | None, torch.Tensor | None]: + from .norms import quack_rmsnorm_bwd + + grad_input, grad_weight = quack_rmsnorm_bwd( + grad_out, + input, + rstd, + weight, + normalized_shape, + dw_mask=output_mask[1], + ) + + if not output_mask[0]: + grad_input = None + return grad_input, grad_weight + + +def register_rmsnorm_overrides() -> None: + # Don't gate on torch.cuda.is_available() here: it calls cuInit and + # poisons fork (vLLM EngineCore relies on fork). cu.register_op_override + # already short-circuits on _cuda.is_built() via _check_runtime_available. + cu.register_op_override( + "aten", + "_fused_rms_norm", + "CUDA", + cond=_fused_rms_norm_cond, + impl=_fused_rms_norm_impl, + ) + cu.register_op_override( + "aten", + "_fused_rms_norm_backward", + "CUDA", + cond=_fused_rms_norm_backward_cond, + impl=_fused_rms_norm_backward_impl, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/__init__.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a93cdfbea37eefb1dac5b1f5bca43dffc405a0b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/__init__.py @@ -0,0 +1,4 @@ +from .impl import register_to_dispatch + + +register_to_dispatch() diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48f904236437f1c984c2095f27df19ae9e40e949 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/__pycache__/impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/__pycache__/impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..770c309c45372356c845f6ea54d4269a75cd844c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/__pycache__/impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/__pycache__/nvmath_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/__pycache__/nvmath_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57b85db11e82fb4aa72033e5cf4277f1ba84a4ae Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/__pycache__/nvmath_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/impl.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/impl.py new file mode 100644 index 0000000000000000000000000000000000000000..e367af383ff71cd5af73c567ff109080ac050c39 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/impl.py @@ -0,0 +1,160 @@ +""" +Python override for aten::linalg_polar (polar decomposition A = U @ H). + +This override is a CUDA-only accelerator: when nvmath-python is available and +the cuSOLVER runtime exposes Xpolar, it computes the decomposition with the +QR-based Dynamically Weighted Halley (QDWH) algorithm. For every other case -- +CPU, ROCm, complex inputs, missing/old nvmath, or unsupported shapes -- the +cond returns False and the router falls through to the structured aten kernel, +which computes the same decomposition via the SVD. That fallthrough is a +correct, fully-functional kernel (it also backs compile/export), so this +override never needs to provide its own CPU/SVD path. + +Both the functional (linalg_polar) and out= (linalg_polar.out) overloads are +overridden so the two call forms use the same algorithm. Only single 2-D +matrices are accelerated: cuSOLVER Xpolar has no batched API, so a batched +input would require a Python loop that is slower than the batched SVD kernel; +batched inputs therefore fall through to aten. +""" + +import torch + +from ... import nvmath_utils, registry + + +# Dtypes for which the cuSOLVER Xpolar (QDWH) fast path is attempted. Xpolar +# supports only real single/double; complex falls through to the aten SVD +# kernel. This is the single source of truth for the override's dtype gating. +_XPOLAR_DTYPES = (torch.float32, torch.float64) + +# Minimum cuSOLVER runtime version exposing cusolverDnXpolar (CUDA 13.2 ships +# cuSOLVER 12.2). The cuSOLVER nvmath loads is whatever the loader resolves +# (system CUDA, or the nvidia-cu* wheels a torch build pulls in), which is not +# guaranteed to be >= 12.2 just because nvmath is installed -- so we gate on the +# reported version and fall through to the SVD kernel when it is too old. +_MIN_CUSOLVER_VERSION = 12200 + +# cuSOLVER Xpolar availability. Checked lazily on first use; flipped to False +# permanently if a call ever hits a hard failure (e.g. runtime lacks the symbol). +_nvmath_available: "bool | None" = None + + +def _check_nvmath() -> bool: + global _nvmath_available + if _nvmath_available is None: + # The cuSOLVER Xpolar path is NVIDIA-only; never attempt it on ROCm + # (torch.version.hip is set for HIP builds, where tensors still report + # device.type == "cuda"). ROCm falls through to the aten SVD kernel. + version = ( + None if torch.version.hip is not None else nvmath_utils.cusolver_version() + ) + _nvmath_available = ( + torch.version.hip is None + and nvmath_utils.nvmath_unavailable_reason() is None + and version is not None + and version >= _MIN_CUSOLVER_VERSION + ) + return _nvmath_available + + +def _out_matches(A: torch.Tensor, U: torch.Tensor, H: torch.Tensor) -> bool: + # The override writes results into U/H with copy_, which neither enforces the + # output dtype nor resizes like the structured out= machinery does. Only fire + # when the provided outputs already satisfy that contract (correct dtype, + # device, and the meta-declared contiguous shapes); otherwise decline so the + # call falls through to the aten .out kernel, which validates and resizes. + m, n = A.shape + return ( + U.dtype == A.dtype + and H.dtype == A.dtype + and U.device == A.device + and H.device == A.device + and tuple(U.shape) == (m, n) + and tuple(H.shape) == (n, n) + and U.is_contiguous() + and H.is_contiguous() + ) + + +def _polar_cond_cuda(A: torch.Tensor, *args, **kwargs) -> bool: + # Only fire when we can actually accelerate: a single non-empty real 2-D + # matrix with m >= n, and a usable cuSOLVER Xpolar runtime. Batched inputs + # (dim > 2) are declined -- Xpolar has no batched API, so looping in Python + # is slower than the batched SVD kernel. Everything else (CPU, complex, + # batched, unsupported runtime) falls through to the structured aten kernel. + if A.dtype not in _XPOLAR_DTYPES: + return False + if A.dim() != 2 or A.size(0) < A.size(1) or A.size(1) == 0: + return False + if not _check_nvmath(): + return False + # For the out= overload, only accelerate when the outputs already match the + # structured contract; otherwise fall through to aten for validation/resize. + U, H = kwargs.get("U"), kwargs.get("H") + if U is not None or H is not None: + if U is None or H is None or not _out_matches(A, U, H): + return False + return True + + +def _run_xpolar(A: torch.Tensor) -> "tuple[torch.Tensor, torch.Tensor] | None": + # Returns (U, H) from cuSOLVER Xpolar, or None on a hard failure (after + # permanently disabling the fast path). + global _nvmath_available + from .nvmath_impl import polar_xpolar + + try: + U, H, _ = polar_xpolar(A) + return U, H + except Exception: + # Hard failure (missing symbol, bad runtime). Disable the fast path so + # subsequent calls (and the fall-throughs below) go straight to aten. + _nvmath_available = False + return None + + +def _polar_impl_cuda(A: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + result = _run_xpolar(A) + if result is None: + return torch.ops.aten.linalg_polar.default(A) + # Match the meta function's contiguous output layout. + U, H = result + return U.contiguous(), H.contiguous() + + +def _polar_out_impl_cuda( + A: torch.Tensor, *, U: torch.Tensor, H: torch.Tensor +) -> tuple[torch.Tensor, torch.Tensor]: + result = _run_xpolar(A) + if result is None: + return torch.ops.aten.linalg_polar.out(A, U=U, H=H) + U_qdwh, H_qdwh = result + U.copy_(U_qdwh) + H.copy_(H_qdwh) + return U, H + + +def register_to_dispatch() -> None: + # This is a CUDA-only accelerator. Registering a CUDA override captures the + # existing aten CUDA kernel as the fallback, which only exists in a CUDA + # build -- on CPU/XPU/ROCm-only builds there is no aten::linalg_polar.out + # CUDA kernel and registration would raise at import time. Gate on the + # fork-safe build-time check (NOT is_available(), which would init CUDA). + if not torch.backends.cuda.is_built(): + return + registry.register_op_override( + "native", + "aten", + "linalg_polar", + "CUDA", + cond=_polar_cond_cuda, + impl=_polar_impl_cuda, + ) + registry.register_op_override( + "native", + "aten", + "linalg_polar.out", + "CUDA", + cond=_polar_cond_cuda, + impl=_polar_out_impl_cuda, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/nvmath_impl.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/nvmath_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..7a7f90c7f48af4fa3fee8649f240c6c444a28e99 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/polar/nvmath_impl.py @@ -0,0 +1,164 @@ +"""cuSOLVER Xpolar (QDWH) polar decomposition via nvmath bindings.""" + +import ctypes + +import torch + +from ... import nvmath_utils + + +# cuBLAS fill mode passed to Xpolar. The general polar decomposition reads the +# entire input A (it is not assumed symmetric), so FULL is required -- LOWER is +# rejected and UPPER silently reads only a triangle, yielding wrong factors. +_CUBLAS_FILL_MODE_FULL = 2 + + +def _cuda_dtype(dtype: torch.dtype): + # cuSOLVER Xpolar supports only real single/double precision. Complex inputs + # are routed to the SVD path by the caller and never reach here. + from cuda.bindings.runtime import cudaDataType # pyrefly: ignore[missing-import] + + return { + torch.float32: cudaDataType.CUDA_R_32F, + torch.float64: cudaDataType.CUDA_R_64F, + }[dtype] + + +def _empty_colmajor(m: int, n: int, A: torch.Tensor) -> torch.Tensor: + # Column-major (m, n) buffer for cuSOLVER (leading dimension m). The view + # owns its storage and presents logical shape (m, n) so values read back + # directly without a transpose. + return A.new_empty((n, m)).mT + + +def _polar_2d( + A: torch.Tensor, *, return_residual: bool = False +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]: + from nvmath.bindings import cusolverDn as cs # pyrefly: ignore[missing-import] + + m, n = A.shape + dtype = A.dtype + device = A.device + + # cuSOLVER handles are device-bound; run everything (handle lookup, workspace + # allocation, and the xpolar call) with A's device current so a non-default + # device (e.g. cuda:1) doesn't trigger an illegal memory access. + with torch.cuda.device(device): + handle = nvmath_utils.get_cusolver_handle(device) + params = cs.create_params() + return _polar_2d_impl(A, m, n, dtype, device, handle, params, return_residual) + + +def _polar_2d_impl(A, m, n, dtype, device, handle, params, return_residual): + from nvmath.bindings import cusolverDn as cs # pyrefly: ignore[missing-import] + + try: + cs.set_stream(handle, torch.cuda.current_stream(device).cuda_stream) + + # cuSOLVER is column-major and overwrites the input (m x n, ld=m) with U. + # Use column-major buffers so the input is untouched and both factors + # read back with the correct (non-transposed/non-conjugated) values. + U_col = _empty_colmajor(m, n, A) + U_col.copy_(A) + H_col = _empty_colmajor(n, n, A) + + # Real single/double: input, output, and compute share one data type. + cdt = _cuda_dtype(dtype) + dtype_a = dtype_h = compute_type = cdt + + ws_dev, ws_host = cs.xpolar_buffer_size( + handle, + params, + _CUBLAS_FILL_MODE_FULL, + m, + n, + dtype_a, + U_col.data_ptr(), + m, + dtype_h, + H_col.data_ptr(), + n, + compute_type, + ) + + # Allocate exactly the queried sizes. When a size is 0, cuSOLVER does + # not dereference the corresponding pointer (an empty CUDA tensor's + # data_ptr is null, which is the expected "no workspace" convention). + buf_dev = torch.empty(ws_dev, dtype=torch.uint8, device=device) + buf_host = bytearray(ws_host) + host_ptr = (ctypes.c_char * ws_host).from_buffer(buf_host) + + # Xpolar reports convergence diagnostics into device scalars: three + # double* (res_nrm, A_nrmF, rcond) and one int* (info). Pack all four + # into a single byte buffer (8-byte aligned slots) so a single kernel + # zero-initializes them. + # + # IMPORTANT: these MUST be zero-initialized. cuSOLVER 12.2.0.1's Xpolar + # reads res_nrm/A_nrmF/rcond as accumulators during the QDWH iteration + # (not write-only outputs); passing uninitialized memory (e.g. a block + # the caching allocator just recycled from prior GPU work) makes the + # iteration diverge and silently return a wrong factorization with + # info=0. Zeroing them makes the result deterministic and correct. + diag = torch.zeros(28, dtype=torch.uint8, device=device) + diag_ptr = diag.data_ptr() + d_res_nrm = diag_ptr # double + d_a_nrm_f = diag_ptr + 8 # double, == ||A||_F + d_rcond = diag_ptr + 16 # double + d_info = diag_ptr + 24 # int32 + + cs.xpolar( + handle, + params, + _CUBLAS_FILL_MODE_FULL, + m, + n, + dtype_a, + U_col.data_ptr(), + m, + dtype_h, + H_col.data_ptr(), + n, + compute_type, + buf_dev.data_ptr(), + ws_dev, + ctypes.addressof(host_ptr), + ws_host, + d_res_nrm, + d_a_nrm_f, + d_rcond, + d_info, + ) + + # H is symmetric/Hermitian up to round-off; symmetrize to make it exact. + H = 0.5 * (H_col + H_col.mH) + + # Optionally expose the relative residual ||A - U*H||_F / ||A||_F that + # Xpolar reports, as a device scalar. We never sync on it ourselves; + # callers who want it can copy it to host (taking the sync hit) for + # debugging or to validate convergence. + residual = None + if return_residual: + diag_f64 = diag[:24].view(torch.float64) + a_nrm = diag_f64[1] + residual = diag_f64[0] / a_nrm.clamp_min(torch.finfo(torch.float64).tiny) + return U_col, H, residual + finally: + cs.destroy_params(params) + + +def polar_xpolar( + A: torch.Tensor, *, return_residual: bool = False +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]: + """Polar decomposition A = U @ H of a single 2-D matrix via cuSOLVER Xpolar. + + Fully asynchronous: issues work on the current CUDA stream and never + synchronizes. When ``return_residual`` is True, also returns the relative + residual ``||A - U*H||_F / ||A||_F`` as a device scalar for callers that + want to validate convergence. + + cuSOLVER Xpolar has no batched API, so only 2-D inputs are supported; the + dispatch override declines batched inputs (they take the batched SVD + kernel instead of a slower per-matrix loop). + """ + torch._check(A.dim() == 2, lambda: "polar_xpolar expects a 2-D matrix") + return _polar_2d(A, return_residual=return_residual) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__init__.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ead1298174416c7e2df6e01d18aec9861859421c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__init__.py @@ -0,0 +1,4 @@ +from .cutedsl_impl import register_to_dispatch + + +register_to_dispatch() diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9b7471ed4fa0c0376307ae66114cd75771a0247 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/_ptx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/_ptx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49be533e9ffc3c431132b31458e470e5c0a88b0e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/_ptx.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/cutedsl_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/cutedsl_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26bc4376248e5d82a39272fefb43fb58ab6602f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/cutedsl_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/tma_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/tma_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27056f7e31b0e0799468d2bdcc7ab1ef326db6d9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/tma_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/vec_scatter_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/vec_scatter_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad8fb1eeaa32351ed73a9b94549a76fac7521dd7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/__pycache__/vec_scatter_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/_ptx.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/_ptx.py new file mode 100644 index 0000000000000000000000000000000000000000..7cb17fe5d4e338043ea7a95ce08a15543c4cd2a6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/_ptx.py @@ -0,0 +1,94 @@ +"""Inline-PTX helpers shared across the TMA and vec-scatter kernels. + +Each helper wraps ``llvm.inline_asm`` with the options we always use +(AT&T dialect, side-effecting) and normalizes argument types (cute's +``Numeric`` wrappers get converted to ``ir.Value`` automatically). This +keeps the kernel files focused on algorithm instead of MLIR plumbing. +""" + +from cutlass._mlir.dialects import llvm +from cutlass.cutlass_dsl import dsl_user_op, T + + +def as_ir(v, *, loc=None, ip=None): + """Normalize ``v`` to ``ir.Value``: cute Numeric wrappers (Int32, + Float16, etc.) get unwrapped via ``.ir_value()``; other values pass + through unchanged (they're already ir.Values).""" + if hasattr(v, "ir_value"): + return v.ir_value(loc=loc, ip=ip) + return v + + +def _inline_asm(result_type, operands, asm, constraint, *, loc=None, ip=None): + """``llvm.inline_asm`` with the flags we always use.""" + return llvm.inline_asm( + result_type, + operands, + asm, + constraint, + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def cvta_smem(ptr, *, loc=None, ip=None): + """Shared-memory ptr -> its ``.shared::cta`` state-space u64 address.""" + raw = ptr.toint(loc=loc, ip=ip).ir_value() + # cvta is pure, not side-effecting; use inline_asm directly. + return llvm.inline_asm( + T.i64(), + [raw], + "cvta.to.shared::cta.u64 $0, $1;", + "=l,l", + has_side_effects=False, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +def make_bulk_reduce_add(ptx_suffix: str): + """Emit ``cp.reduce.async.bulk.global.shared::cta.bulk_group.add.``. + Suffix selects the dtype: ``f32`` / ``noftz.f16`` / ``noftz.bf16``.""" + + @dsl_user_op + def _op(gmem_addr_u64, smem_u64, size_bytes, *, loc=None, ip=None): + _inline_asm( + None, + [ + as_ir(gmem_addr_u64, loc=loc, ip=ip), + as_ir(smem_u64, loc=loc, ip=ip), + as_ir(size_bytes, loc=loc, ip=ip), + ], + f"cp.reduce.async.bulk.global.shared::cta.bulk_group.add.{ptx_suffix}" + " [$0], [$1], $2;", + "l,l,r", + loc=loc, + ip=ip, + ) + + return _op + + +def make_packed_half_atomic_add(ptx_suffix: str): + """Emit ``red.global.add.noftz.`` with a single ``i32`` packed + register holding two halves. Used by the vec-scatter kernel for + ``f16x2`` / ``bf16x2`` paired atomics.""" + + @dsl_user_op + def _op(gmem_ptr_i64, packed_i32, *, loc=None, ip=None): + _inline_asm( + None, + [as_ir(gmem_ptr_i64, loc=loc, ip=ip), as_ir(packed_i32, loc=loc, ip=ip)], + f"red.global.add.noftz.{ptx_suffix} [$0], $1;", + "l,r", + loc=loc, + ip=ip, + ) + + return _op diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/cutedsl_impl.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/cutedsl_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..2c89e2e10149f44a43a4173bbe8bd887162b2266 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/cutedsl_impl.py @@ -0,0 +1,454 @@ +"""CuTeDSL override registrations for ``aten::scatter_add``. + +Two kernels for the fast-path layout (self/src 2D-shaped after +coalescing, with self contiguous on the slice axis and src either +contiguous or row-strided), tried in order: + +1. **TMA** (``tma_kernel.py``, sm_90+): uses ``cp.reduce.async.bulk`` to + offload the whole reduction to the TMA unit, 3-7x faster than aten on + high-contention embedding-bag-grad-style workloads. +2. **vec-scatter** (``vec_scatter_kernel.py``, any SM): warp-per-row + scheduling with ``atomicAdd`` (scalar fp32, paired x2 halves). Covers + pre-sm_90, and sm_90+ shapes where the TMA alignment constraint isn't + met. + +Eligibility mirrors aten's ``fast_scatter_add_kernel_eligible`` +(IndexKernelUtils.h): we restride ``self`` so its scatter-axis stride +is 0 and shape matches ``index``, then build a ``TensorIterator`` on +``(self_restrided, src_restrided, index)``. TensorIterator's coalescing +and stride-magnitude reordering produces a 2D iterator iff the layout +is kernel-friendly; we then pattern-match the resulting iter strides +to confirm slice/index-axis assignment. This delegates the layout +analysis to ``TensorIterator`` rather than reimplementing it. + +Anything else (non-2D-coalescing layout, dtype mismatch, deterministic +mode) falls through to aten. Aten is competitive or better on those +shapes, so we intentionally don't override them. + +In-place (``scatter_add_``) is registered explicitly; PyTorch's +structured-delegate from ``scatter_add_`` to ``scatter_add.out`` happens +below the dispatcher, so overriding the ``.out`` variant alone doesn't +intercept the in-place method. +""" + +import functools + +import torch +from torch._tensor_iterator import TensorIterator + +from ... import cutedsl_utils as cu +from ...registry import _OpCondFn, _OpImplFn + + +_SUPPORTED_DTYPES = {torch.float16, torch.bfloat16, torch.float32} + +# 16B alignment for `src.data_ptr()` and `src.stride(0) * elem`: required +# for the LDG.128 / tile-mode TMA load of `src` and the row-start 16B +# boundary that LDG.128 reads from. Applies to both paths. +_SRC_ALIGN_BYTES = 16 +# Path-specific destination alignment. TMA: cp.reduce.async.bulk gmem +# operand needs 16B base + stride. vec-scatter: scalar fp32 atomicAdd / +# f16x2 / bf16x2 paired atomics need natural alignment of the 4B atomic +# operand on both base and per-row stride. +_TMA_DST_ALIGN_BYTES = 16 +_VEC_DST_ALIGN_BYTES = 4 + + +@functools.cache +def _is_rocm() -> bool: + # These kernels are built on the CUTLASS Python DSL (CuteDSL), which is + # NVIDIA-only and performs a hard CUDA-driver dependency check at compile + # time. On a ROCm/HIP build ``tensor.is_cuda`` is still True, so without + # this guard the cond approves and ``cute.compile`` fails with + # CudaDriverDependencyError. Decline so scatter_add falls back to aten. + return torch.version.hip is not None + + +@functools.cache +def _has_sm90_plus() -> bool: + if not torch.cuda.is_available(): + return False + major, _ = torch.cuda.get_device_capability(0) + return major >= 9 + + +def _deterministic() -> bool: + # Our kernels use non-deterministic atomicAdd. Under + # torch.use_deterministic_algorithms(True), aten's scatter_add falls + # into _scatter_via_index_put instead; we must decline to preserve + # that behavior. + return torch.are_deterministic_algorithms_enabled() + + +def _any_cow(*tensors: torch.Tensor) -> bool: + return any( + torch._C._is_cow_tensor(t) # pyrefly: ignore[missing-attribute] + for t in tensors + ) + + +def _base_cond_ok(*tensors: torch.Tensor) -> bool: + """Pre-checks shared by every path: env sanity, all CUDA, non-COW.""" + if _is_rocm(): + return False + if _deterministic(): + return False + if not all(t.is_cuda for t in tensors): + return False + if _any_cow(*tensors): + return False + return True + + +# --------------------------------------------------------------------------- +# TI-driven layout analysis. +# +# Mirrors aten's pattern in ScatterGatherKernel.cu / IndexKernelUtils.h: +# restride ``self`` so its scatter-axis stride is 0 and its shape matches +# ``index``, then build a TensorIterator on the three. TensorIterator does +# the broadcast / coalesce / dim reorder; we then pattern-match the post- +# build iter strides to recognize the kernel's expected layout. +# --------------------------------------------------------------------------- + + +def _normalize_dim(dim: int, ndim: int) -> int: + return dim + ndim if dim < 0 else dim + + +def _scatter_add_eligibility( + self: torch.Tensor, d: int, index: torch.Tensor, src: torch.Tensor +) -> TensorIterator | None: + """Return the analysis TensorIterator if (self, d, index, src) fits the + kernel's expected layout, else ``None``. ``d`` is the already-normalized + scatter axis. + + Mirrors aten's ``fast_scatter_add_kernel_eligible`` (IndexKernelUtils.h): + restride ``self`` so its scatter-axis stride is 0 (shape = ``index.shape``), + let TensorIterator coalesce + reorder, then check that the result is + a 2D iter where dim 0 is the contiguous slice axis and dim 1 is the + scatter (index) axis. + """ + if self.dtype not in _SUPPORTED_DTYPES or self.dtype != src.dtype: + return None + if index.dtype not in (torch.int32, torch.int64): + return None + if self.ndim != src.ndim or self.ndim != index.ndim or self.ndim == 0: + return None + if not 0 <= d < self.ndim: + return None + + self_strides = list(self.stride()) + self_strides[d] = 0 # aten's restride_dim trick + try: + self_r = self.as_strided(index.shape, self_strides) + src_r = src.as_strided(index.shape, src.stride()) + it = TensorIterator( + outputs=[self_r], + const_inputs=[src_r, index], + check_mem_overlap=False, + check_all_same_dtype=False, + resize_outputs=False, + ) + except RuntimeError: + return None + + if it.ndim != 2: + return None + elem = self.element_size() + idx_elem = index.element_size() + s_self, s_src, s_idx = it.strides(0), it.strides(1), it.strides(2) + if ( + s_idx[0] == 0 + and s_idx[1] == idx_elem + and s_self[0] == elem + and s_src[0] == elem + and s_self[1] == 0 + ): + return it + return None + + +def _alignment_contract_ok( + dst: torch.Tensor, src: torch.Tensor, dim: int, *, dst_ptr_align: int +) -> bool: + """Alignment of effective ptrs and outer row strides. + + The src side is always read via 16B-wide vector ops (LDG.128 / + tile-mode TMA load), so its data_ptr and per-row stride must be + 16B-aligned. The dst side's requirement is path-specific: + + - TMA: ``cp.reduce.async.bulk`` writes the gmem operand via a TMA + descriptor that requires 16B alignment of both base and stride. + - vec-scatter: writes via scalar fp32 atomicAdd / f16x2 / bf16x2 + paired atomics, which need natural alignment of the 4B atomic + operand on both base address and per-row stride. + + The "row stride" is the stride along ``dim`` -- the kernel uses it to + step between rows of the (M, N) views ``_prepare_kernel_inputs`` builds. + When this returns False the cond rejects and the call falls through + to aten, which has its own predicate and safe fallback to + ``vectorized_scatter_add_kernel_launch`` / ``indexFunc{Small,Large}Index``. + """ + if src.data_ptr() % _SRC_ALIGN_BYTES: + return False + if dst.data_ptr() % dst_ptr_align: + return False + elem = dst.element_size() + if (src.stride(dim) * elem) % _SRC_ALIGN_BYTES: + return False + if (dst.stride(dim) * elem) % dst_ptr_align: + return False + return True + + +# --------------------------------------------------------------------------- +# Per-kernel eligibility. ``it.shape[0]`` is the slice extent (N elements) +# after coalescing; that's what the alignment / divisibility checks key on. +# --------------------------------------------------------------------------- + + +def _is_tma_supported( + self: torch.Tensor, dim: int, index: torch.Tensor, src: torch.Tensor +) -> bool: + if not _has_sm90_plus(): + return False + d = _normalize_dim(dim, self.ndim) + it = _scatter_add_eligibility(self, d, index, src) + if it is None: + return False + if not _alignment_contract_ok(self, src, d, dst_ptr_align=_TMA_DST_ALIGN_BYTES): + return False + # TMA chunk_bytes = min(row_bytes, 512); row_bytes must evenly divide + # by chunk_bytes and chunk_bytes must be 16-byte aligned. + from .tma_kernel import row_shape_supported + + return row_shape_supported(self.dtype, it.shape[0]) + + +def _is_vec_scatter_supported( + self: torch.Tensor, dim: int, index: torch.Tensor, src: torch.Tensor +) -> bool: + # ``red.global.add.noftz.bf16x2`` requires sm_90+. fp16x2 (sm_70+) and + # scalar fp32 atomicAdd (sm_60+) work everywhere we care about. + if self.dtype is torch.bfloat16 and not _has_sm90_plus(): + return False + d = _normalize_dim(dim, self.ndim) + it = _scatter_add_eligibility(self, d, index, src) + if it is None: + return False + if not _alignment_contract_ok(self, src, d, dst_ptr_align=_VEC_DST_ALIGN_BYTES): + return False + # Each lane owns vec_elems consecutive elements; loop is either + # fully in-bounds or fully skipped per lane. Only requirement is + # N % vec_elems == 0 (fp32: %4, halves: %8). + from .vec_scatter_kernel import vec_elems_for + + return it.shape[0] % vec_elems_for(self.dtype) == 0 + + +# --------------------------------------------------------------------------- +# Kernel-input prep. After eligibility the kernel host functions take 2D +# (M, N) tensors and a 1D index. We synthesize those views from the user's +# original operands using the TI-approved geometry. +# --------------------------------------------------------------------------- + + +def _prepare_kernel_inputs( + self: torch.Tensor, + d: int, + index: torch.Tensor, + src: torch.Tensor, + it: TensorIterator, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Build (self_2d, index_1d, src_2d) for the kernel host functions. + + Caller has verified eligibility via ``_scatter_add_eligibility``. + ``d`` is the already-normalized scatter axis. ``it.shape[0]`` is the + coalesced slice extent (product of every non-scatter dim of ``self``). + The 2D views preserve the user's original stride along ``d`` (used by + the kernel for the row stride). + """ + N, M_src = it.shape[0], it.shape[1] + M_self = self.shape[d] + self_2d = self.as_strided((M_self, N), (self.stride(d), 1)) + src_2d = src.as_strided((M_src, N), (src.stride(d), 1)) + # Eligibility verified the iter has post-coalesce strides + # ``s_idx = (0, idx_elem)`` on ``index``; that means ``index`` carries + # M_src consecutive elements at offset 0 with element stride 1, padded + # by stride-0 broadcast axes. A single ``as_strided`` collapses that + # to the 1D view the kernels expect. + index_1d = index.as_strided((M_src,), (1,)) + if index_1d.dtype != torch.int64: + index_1d = index_1d.to(torch.int64) + return self_2d, index_1d, src_2d + + +# --------------------------------------------------------------------------- +# Cond / impl factories. ``_make_cond`` wraps a support check in the shared +# dispatch boilerplate; ``_make_impls`` produces the (functional, .out, +# in-place) triple for a given kernel. +# --------------------------------------------------------------------------- + + +def _make_cond( + support_check, + *, + out_dst_ptr_align: int | None = None, +) -> _OpCondFn: + """Build a cond function that runs ``support_check`` behind the shared + boilerplate (cutedsl availability, non-deterministic mode, CUDA + tensors, non-COW, dtype/shape match on ``out`` when present). + + ``out_dst_ptr_align`` is None for the functional / inplace variants. + For the ``.out`` variant it is the path-specific destination + alignment (TMA: 16, vec-scatter: 4) used to alignment-check ``out``, + which the ``.out`` impl runs the kernel on instead of ``self``. + + ``support_check`` is ``_is_tma_supported`` or ``_is_vec_scatter_supported`` + -- both take ``(self, dim, index, src)`` and rebuild the analysis iter + internally. + """ + if out_dst_ptr_align is not None: + + def _cond(self, dim, index, src, *, out): + if not _base_cond_ok(self, index, src, out): + return False + if out.dtype != self.dtype or out.shape != self.shape: + return False + if out.ndim == 0: + return False + # ``out`` is the destination of a functional .out call; it + # plays the role of self in the iter analysis. + if not support_check(out, dim, index, src): + return False + # The .out impl runs the kernel on ``out``, not ``self`` (see + # _make_impls.out_impl). support_check above validates ``out``'s + # layout via TI strides, but we still need to alignment-check it + # explicitly here in case ``out`` is a distinct buffer with + # different alignment from ``self``. + d = _normalize_dim(dim, out.ndim) + return _alignment_contract_ok(out, src, d, dst_ptr_align=out_dst_ptr_align) + + return _cond + + def _cond(self, dim, index, src, *args, **kwargs): + if not _base_cond_ok(self, index, src): + return False + return support_check(self, dim, index, src) + + return _cond + + +def _copy_if_distinct(out: torch.Tensor, self: torch.Tensor) -> None: + """Seed ``out`` with ``self``'s values when they're separate buffers. + Cond guarantees shape match, so no resize is needed.""" + if out.data_ptr() != self.data_ptr(): + out.copy_(self) + + +def _make_impls(kernel_getter): + """Build (functional, out, in-place) impl callables. + + ``kernel_getter`` lazily imports the ``*_scatter_add_into`` kernel + host function (we defer to keep the DSL runtime out of registration). + Cond has already verified eligibility; we rebuild the iter inside the + impl to recover the post-coalesce geometry that ``_prepare_kernel_inputs`` + needs. The build is pure C++ and cheap. + """ + + def _run(dst: torch.Tensor, dim: int, index, src) -> torch.Tensor: + d = _normalize_dim(dim, dst.ndim) + it = _scatter_add_eligibility(dst, d, index, src) + if it is None: + raise RuntimeError( + "scatter_add cutedsl: cond approved but iter rebuild failed" + ) + # Mirrors aten's `if (iter.numel() == 0) return;` in + # ScatterGatherKernel.cu -- the eligibility check is purely + # layout-shaped, so empty inputs satisfy it but have no work. + if it.numel == 0: + return dst + dst_2d, index_1d, src_2d = _prepare_kernel_inputs(dst, d, index, src, it) + kernel_getter()(dst_2d, index_1d, src_2d) + return dst + + def impl(self, dim, index, src, *args, **kwargs): + return _run(self.clone(), dim, index, src) + + def out_impl(self, dim, index, src, *, out): + _copy_if_distinct(out, self) + return _run(out, dim, index, src) + + def inplace_impl(self, dim, index, src, *args, **kwargs): + return _run(self, dim, index, src) + + return impl, out_impl, inplace_impl + + +def _tma_kernel(): + from .tma_kernel import tma_scatter_add_into + + return tma_scatter_add_into + + +def _vs_kernel(): + from .vec_scatter_kernel import vec_scatter_add_into + + return vec_scatter_add_into + + +_tma_impl, _tma_out_impl, _tma_inplace_impl = _make_impls(_tma_kernel) +_vs_impl, _vs_out_impl, _vs_inplace_impl = _make_impls(_vs_kernel) + +_tma_cond = _make_cond(_is_tma_supported) +_tma_out_cond = _make_cond(_is_tma_supported, out_dst_ptr_align=_TMA_DST_ALIGN_BYTES) +_vs_cond = _make_cond(_is_vec_scatter_supported) +_vs_out_cond = _make_cond( + _is_vec_scatter_supported, out_dst_ptr_align=_VEC_DST_ALIGN_BYTES +) + + +# --------------------------------------------------------------------------- +# Registration +# --------------------------------------------------------------------------- + + +# Dispatch priority is first-registered-wins. TMA's cond is strictly +# narrower than vec-scatter's (TMA only fires on sm_90+ with stricter D +# alignment), so TMA goes first. +_PATHS = ( + # (cond, impl, out_cond, out_impl, inplace_impl) + (_tma_cond, _tma_impl, _tma_out_cond, _tma_out_impl, _tma_inplace_impl), + (_vs_cond, _vs_impl, _vs_out_cond, _vs_out_impl, _vs_inplace_impl), +) + + +def _register_path( + dispatch_key: str, + cond: _OpCondFn, + impl: _OpImplFn, + out_cond: _OpCondFn, + out_impl: _OpImplFn, + inplace_impl: _OpImplFn, +) -> None: + # scatter_add_ has its own dispatcher entry separate from scatter_add + # and scatter_add.out; it's structured-delegated to .out below the + # dispatcher layer, so overriding .out alone doesn't catch it. + for op_symbol, cond_fn, impl_fn in ( + ("scatter_add", cond, impl), + ("scatter_add.out", out_cond, out_impl), + ("scatter_add_", cond, inplace_impl), + ): + cu.register_op_override( + "aten", + op_symbol, + dispatch_key, + cond=cond_fn, + impl=impl_fn, + allow_multiple_override=True, + ) + + +def register_to_dispatch() -> None: + for path in _PATHS: + _register_path("CUDA", *path) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/tma_kernel.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/tma_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..9fa7d6c074d0b41628a96fd56fcfb348eae80d97 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/tma_kernel.py @@ -0,0 +1,461 @@ +"""TMA-based scatter_add for the ``index.unsqueeze(-1).expand(-1, N)`` pattern. + +Port of the CUDA C++ kernel from https://github.com/pytorch/pytorch/pull/182675 +to CuTeDSL. Each CTA (one warp) handles one source row (within an assigned +chunk-index range): a tile-mode TMA bulk load (``cute.copy`` with +``CopyBulkTensorTileG2SOp`` via ``make_tiled_tma_atom``) stages +``src[i, d_start:d_end]`` into smem, then +``cp.reduce.async.bulk.global.shared::cta.bulk_group.add`` deposits the +reduction into ``out[index[i], d_start:d_end]``. + +Using the tile-mode TMA with a descriptor over the full ``(M_src, N)`` +source tensor lets TMA clamp out-of-range column reads to zero, so the +final partial chunk (when ``N`` isn't a multiple of ``chunk_elems``) is +handled natively -- we just reduce only the valid byte count on the +store side. That widens coverage to any ``row_bytes`` that's 16-byte +aligned (the ``cp.reduce.async.bulk`` gmem operand requirement). + +Synchronization between the load and the reduce uses +``cutlass.pipeline.PipelineTmaAsync`` with ``num_stages=2``: producer +``acquire``/``commit`` guards the TMA issue, consumer ``wait``/``release`` +guards the reduce. Producer and consumer cooperative groups are both +``Agent.Thread, size=1`` -- the single driver thread inside the warp +does both roles. ``PipelineState.advance()`` handles the stage index + +phase bit. + +The pipeline is software-pipelined across the flat sequence of +``(entry, chunk)`` pairs: each loop iteration issues the TMA load for +the current pair and consumes the previous one, keeping one TMA load +in flight alongside an in-progress bulk-reduce. An epilogue drains +the final outstanding load. + +Chunks along D at a compile-time ``chunk_elems``: small rows travel as +a single chunk, large rows chunk at 512 B. The TMA descriptor OOB-clamp +handles rows whose length isn't a multiple of ``chunk_elems``. + +Grid layout is 2D to maintain SM utilization for shapes with small N +and large D: ``(grid_x, grid_y)``, where ``grid_y`` partitions the +chunk-index axis. When N is large the host sets ``grid_y = 1`` so the +inner chunk loop recovers the classic schedule. When N is tiny (say +100 rows, D=640K), ``grid_y`` grows so the grid still fills the +machine. + +Restrictions (enforced by the host cond in ``cutedsl_impl.py``): + - sm_90+ (cp.reduce.async.bulk availability) + - dim == 0, rank >= 2, self/src inner-contiguous + - index is the expanded-1D pattern (same shape as src, stride 0 on every + axis except 0) + - dtype in {fp32, fp16, bf16} + - ``row_bytes % 16 == 0`` (for both the TMA load operand and the + cp.reduce.async.bulk gmem operand) +""" + +import cuda.bindings.driver as cuda # pyrefly: ignore[missing-import] +import cutlass +import cutlass.cute as cute +import cutlass.cute.nvgpu.cpasync as cpasync +import cutlass.cute.testing as cute_testing +import cutlass.pipeline as pipeline +from cutlass import BFloat16, Float16, Float32, Int32, Int64 + +import torch +from torch._native.instrumentation import instrumented_cutedsl_cache + +from ._ptx import cvta_smem, make_bulk_reduce_add + + +_MAX_CHUNK_BYTES = 512 +_THREADS_PER_CTA = 32 # one warp per CTA +# cp.async.bulk requires 128B-aligned smem destinations. +_SMEM_ALIGN_BYTES = 128 + + +def _round_up(x: int, m: int) -> int: + return (x + m - 1) // m * m + + +_TORCH_TO_CUTE = { + torch.float32: Float32, + torch.float16: Float16, + torch.bfloat16: BFloat16, +} + + +_bulk_reduce_add_f32 = make_bulk_reduce_add("f32") +_bulk_reduce_add_f16 = make_bulk_reduce_add("noftz.f16") +_bulk_reduce_add_bf16 = make_bulk_reduce_add("noftz.bf16") + + +def _reduce_op_for(dtype): + if dtype is Float32: + return _bulk_reduce_add_f32 + if dtype is Float16: + return _bulk_reduce_add_f16 + if dtype is BFloat16: + return _bulk_reduce_add_bf16 + raise ValueError(f"unsupported dtype: {dtype}") + + +def _make_kernel(dtype, elem_bytes: int, chunk_elems: int, reduce_op): + """Build a dtype-specialized kernel closure. dtype/elem_bytes + /chunk_elems are Python-time constants that the preprocessor folds + at cute.compile time; ``N`` and ``num_chunks`` are runtime args so + one compile serves every row length. + + ``chunk_elems`` is baked in at compile time (it is the static TMA + box dim). The TMA descriptor built in ``_launch`` (via + ``make_tiled_tma_atom`` on the source tensor) enables + OOB-clamp-to-zero for reads past column ``N``; the reduce side then + writes only the actual valid byte count, so partial final chunks -- + and rows shorter than a full box -- are handled natively. + + One CTA = one warp. The single driver thread (tidx == 0) serves as + both producer (issues the TMA load) and consumer (issues the + bulk-reduce). Both CooperativeGroups are ``Agent.Thread, size=1`` + so the mbarrier arrive counts match the single-threaded flow. + + The reduce side always uses the runtime ``out_row_stride`` arg so + outer-strided outputs (e.g. slices) work; the contiguous case just + passes ``out.stride(0) == N`` in as that value. + """ + + chunk_bytes = chunk_elems * elem_bytes + + # 2-stage pipeline buffer is laid out column-major; stage i starts + # at offset i * stage_stride_elems * elem_bytes, so the stride must + # round chunk_bytes up to a multiple of _SMEM_ALIGN_BYTES. Otherwise + # stage 1 is misaligned and the kernel faults the first time a CTA + # writes it. Bites both chunk_bytes < 128 (small D) and chunk_bytes + # not a multiple of 128 (e.g. fp32 N=36 -> 144 B). + stage_stride_elems = _round_up(chunk_elems, _SMEM_ALIGN_BYTES // elem_bytes) + + @cute.kernel + def _kernel( + tma_atom: cute.CopyAtom, + tma_tensor_src: cute.Tensor, # TMA-view of mSrc + mIndex: cute.Tensor, + mOut: cute.Tensor, + N: Int32, + num_chunks: Int32, + chunks_per_cta: Int32, + out_row_stride: Int64, + ): + tidx, _, _ = cute.arch.thread_idx() + bidx, bidy, _ = cute.arch.block_idx() + gdim_x, _, _ = cute.arch.grid_dim() + + # num_entries (M_src) comes from mIndex's shape; mIndex is 1D + # of length M_src after host-side flattening. + num_entries = mIndex.shape[0] + + # Chunk-index range assigned to this CTA. bidy partitions the + # chunk axis into disjoint slices of chunks_per_cta; when + # chunks_per_cta == num_chunks, grid_y == 1 and every CTA sees + # the whole D. + chunk_start = bidy * chunks_per_cta + chunk_end = chunk_start + chunks_per_cta + if chunk_end > num_chunks: + chunk_end = num_chunks + + out_rs = out_row_stride + + smem = cutlass.utils.SmemAllocator() + sBuf = smem.allocate_tensor( + dtype, + cute.make_layout((chunk_elems, 2), stride=(1, stage_stride_elems)), + _SMEM_ALIGN_BYTES, + ) + mbar_storage = smem.allocate_array(cutlass.Uint64, num_elems=2 * 2) + + pipe = pipeline.PipelineTmaAsync.create( + num_stages=2, + producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, size=1), + consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, size=1), + tx_count=chunk_bytes, + barrier_storage=mbar_storage, + tidx=tidx, + ) + + # Tile the source (M, N) by (1, chunk_elems) to get + # (1, chunk_elems, M, num_chunks); tma_partition collapses and + # returns tma_gmem[None, row_idx, chunk_idx] and tma_smem[None, + # stage]. + tiled_gmem = cute.local_tile(tma_tensor_src, (1, chunk_elems), (None, None)) + tma_smem, tma_gmem = cpasync.tma_partition( + tma_atom, + Int32(0), + cute.make_layout(1), + cute.group_modes(sBuf, 0, 1), + cute.group_modes(tiled_gmem, 0, 2), + ) + + producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, 2 + ) + consumer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, 2 + ) + + # Software-pipelined schedule: at each iteration, issue the TMA + # load for the current (entry, chunk) pair, then consume the + # previous pair (bulk-reduce). With num_stages=2 this keeps one + # TMA load in flight while a bulk-reduce is running. Final + # iteration's load is drained in an epilogue after the main loop. + # pair_count is a runtime Int32 so the ``pair_count > 0`` branch + # stays in the compiled IR (a Python bool would be baked in at + # trace time). + pair_count = Int32(0) + prev_chunk_idx = Int32(0) + prev_r = Int64(0) + + base = bidx + while base < num_entries: + entry_id = base + + chunk_idx = chunk_start + while chunk_idx < chunk_end: + if tidx == Int32(0): + r = Int64(mIndex[entry_id]) + # Bounds check: index values must be valid output + # rows. Compiling with ``--enable-assertions`` turns + # this into a device-side trap; otherwise it folds + # away. Driver thread only -- no need to replicate + # the check across all 32 lanes. + cute_testing.assert_(r >= Int64(0)) + cute_testing.assert_(r < Int64(mOut.shape[0])) + + pipe.producer_acquire(producer_state) + cute.copy( + tma_atom, + tma_gmem[None, entry_id, chunk_idx], + tma_smem[None, producer_state.index], + tma_bar_ptr=pipe.producer_get_barrier(producer_state), + ) + pipe.producer_commit(producer_state) + producer_state.advance() + + if pair_count > Int32(0): + pipe.consumer_wait(consumer_state) + cbuf_ptr = sBuf[None, consumer_state.index].iterator + + # Partial-chunk handling: actual valid element + # count is min(chunk_elems, N - off). TMA + # OOB-clamped the tail to 0 in smem, we reduce + # only the valid bytes. + off = prev_chunk_idx * Int32(chunk_elems) + cur_elems = N - off + if cur_elems > Int32(chunk_elems): + cur_elems = Int32(chunk_elems) + cur_bytes = cur_elems * Int32(elem_bytes) + + dst_off = prev_r * out_rs + Int64(off) + gmem_dst_u64 = Int64((mOut.iterator + dst_off).toint()) + reduce_op(gmem_dst_u64, cvta_smem(cbuf_ptr), cur_bytes) + cute.arch.cp_async_bulk_commit_group() + cute.arch.cp_async_bulk_wait_group(0, read=False) + pipe.consumer_release(consumer_state) + consumer_state.advance() + + prev_chunk_idx = chunk_idx + prev_r = r + pair_count = pair_count + Int32(1) + + chunk_idx = chunk_idx + Int32(1) + + base = base + gdim_x + + # Epilogue: drain the last outstanding TMA load. + if tidx == Int32(0): + if pair_count > Int32(0): + pipe.consumer_wait(consumer_state) + cbuf_ptr = sBuf[None, consumer_state.index].iterator + + off = prev_chunk_idx * Int32(chunk_elems) + cur_elems = N - off + if cur_elems > Int32(chunk_elems): + cur_elems = Int32(chunk_elems) + cur_bytes = cur_elems * Int32(elem_bytes) + + dst_off = prev_r * out_rs + Int64(off) + gmem_dst_u64 = Int64((mOut.iterator + dst_off).toint()) + reduce_op(gmem_dst_u64, cvta_smem(cbuf_ptr), cur_bytes) + cute.arch.cp_async_bulk_commit_group() + cute.arch.cp_async_bulk_wait_group(0, read=False) + pipe.consumer_release(consumer_state) + + @cute.jit + def _launch( + mSrc: cute.Tensor, + mIndex: cute.Tensor, + mOut: cute.Tensor, + stream: cuda.CUstream, + N: Int32, + num_chunks: Int32, + chunks_per_cta: Int32, + grid_x: Int32, + grid_y: Int32, + out_row_stride: Int64, + ): + # Build the tile-mode TMA descriptor over the (M_src, N) source. + # Both global dims are dynamic; the ``(1, chunk_elems)`` box is + # static. TMA clamps OOB column reads to 0, so rows shorter than + # a full box and rows with ``N % chunk_elems != 0`` are handled + # natively on the load. + tma_atom, tma_tensor_src = cpasync.make_tiled_tma_atom( + cpasync.CopyBulkTensorTileG2SOp(), + mSrc, + cute.make_layout((1, chunk_elems)), + (1, chunk_elems), + ) + _kernel( + tma_atom, + tma_tensor_src, + mIndex, + mOut, + N, + num_chunks, + chunks_per_cta, + out_row_stride, + ).launch( + grid=[grid_x, grid_y, 1], + block=[_THREADS_PER_CTA, 1, 1], + stream=stream, + ) + + return _launch + + +def _chunk_elems_for(torch_dtype: torch.dtype) -> int: + """Compile-time ``chunk_elems`` (the static TMA box dim): always + ``_MAX_CHUNK_BYTES // elem_bytes``. Since ``N`` is now a runtime arg + the box can't shrink to fit small rows -- instead a short row loads + one box and the TMA descriptor OOB-clamps the tail to 0, and the + reduce writes only ``min(chunk_elems, N)`` valid elements. 512 B is + a multiple of 16 for every supported dtype, so the box always meets + the reduce's 16-byte alignment.""" + return _MAX_CHUNK_BYTES // torch_dtype.itemsize + + +@instrumented_cutedsl_cache( + "aten::scatter_add", + key_fn=lambda torch_dtype: f"tma {torch_dtype}", +) +def _compile_tma_scatter(torch_dtype: torch.dtype): + # N and num_chunks are runtime args, so one compile per dtype serves + # every row length. chunk_elems (the static TMA box) depends only on + # the dtype's element size. + dtype = _TORCH_TO_CUTE[torch_dtype] + elem_bytes = dtype.width // 8 + chunk_elems = _chunk_elems_for(torch_dtype) + reduce_op = _reduce_op_for(dtype) + launcher = _make_kernel(dtype, elem_bytes, chunk_elems, reduce_op) + + mSrc_fake = cute.runtime.make_fake_tensor( + dtype, (cute.sym_int(), cute.sym_int()), stride=(cute.sym_int64(), 1) + ) + # Index is guaranteed contiguous by _flatten_for_expanded_1d; fix + # stride=1 so `mIndex[i]` doesn't emit a runtime stride multiply. + mIndex_fake = cute.runtime.make_fake_tensor(Int64, (cute.sym_int(),), stride=(1,)) + mOut_fake = cute.runtime.make_fake_tensor( + dtype, (cute.sym_int(), cute.sym_int()), stride=(cute.sym_int64(), 1) + ) + return cute.compile( + launcher, + mSrc_fake, + mIndex_fake, + mOut_fake, + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + Int32(0), # N + Int32(0), # num_chunks + Int32(0), # chunks_per_cta + Int32(0), # grid_x + Int32(0), # grid_y + Int64(0), # out_row_stride + # ``--enable-assertions`` keeps the ``cute_testing.assert_`` + # bounds checks on ``r`` live in production. Cost is roughly + # +1-10% (geomean +7.7%) on most shapes; the safety net is + # worth it because an OOB ``r`` would otherwise silently + # corrupt unrelated gmem via ``cp.reduce.async.bulk``. + options="--enable-tvm-ffi --enable-assertions", + ) + + +def min_d_divisor_for(dtype: torch.dtype) -> int: + """Smallest value D must be divisible by so ``cp.reduce.async.bulk`` + gmem operands stay 16-byte aligned: ``D * sizeof(dtype) % 16 == 0``, + i.e. ``D % (16 / sizeof(dtype)) == 0``. fp32: %4, bf16/fp16: %8. + Supported dtypes' itemsize divides 16, so plain // suffices. + """ + return 16 // dtype.itemsize + + +def row_shape_supported(dtype: torch.dtype, N: int) -> bool: + """Host-side check: can the TMA kernel handle an N-element row? + + Only requirement is that ``row_bytes = N * elem_size`` is a multiple + of 16, which is the PTX operand alignment for both the tile-mode + TMA load (per-row stride must be 16-aligned) and + ``cp.reduce.async.bulk`` (gmem address + byte count must be + 16-aligned). Rows that aren't multiples of ``chunk_elems`` are + handled via the TMA descriptor's OOB-clamp-to-zero behavior. + """ + return (N * dtype.itemsize) % 16 == 0 + + +def _plan_grid(M: int, D: int, chunk_elems: int, sm: int) -> tuple[int, int, int]: + """Pick ``(grid_x, grid_y, chunks_per_cta)``. + + Strategy: keep the classic 1D schedule (grid_y=1, whole chunk range + per CTA with internal double-buffering) whenever the row-axis alone + saturates the GPU. When M is too small for that, split the + chunk-axis across grid_y so every SM gets work. + """ + n_chunks = (D + chunk_elems - 1) // chunk_elems + # 1 warp per CTA: need many more CTAs than an 8-warp layout to keep + # occupancy up. sm*32 target with a sm*64 clamp works well across + # uniform / high_cont / few_idx on B200. + row_ctas = M + target_ctas = sm * 32 + if row_ctas >= target_ctas: + grid_x = min(row_ctas, sm * 64) + return grid_x, 1, n_chunks + # Split the chunk axis until we hit the target. + want_y = max(1, target_ctas // max(row_ctas, 1)) + grid_y = min(n_chunks, want_y) + chunks_per_cta = (n_chunks + grid_y - 1) // grid_y + # Recompute grid_y now that each y-slot holds chunks_per_cta chunks. + grid_y = (n_chunks + chunks_per_cta - 1) // chunks_per_cta + grid_x = row_ctas + return grid_x, grid_y, chunks_per_cta + + +def tma_scatter_add_into( + out: torch.Tensor, + index_1d: torch.Tensor, + src: torch.Tensor, +) -> None: + """In-place: ``out[index_1d[i], :] += src[i, :]`` for every i. + + ``out`` / ``src`` are 2D with inner-dim stride 1 (outer row stride + can differ from N, e.g. a slice of a wider buffer). ``index_1d`` is + 1D int64 of length M_src. ``row_bytes = N * elem_size`` must be a + multiple of 16; the host cond enforces this. + """ + M, N = src.shape + chunk_elems = _chunk_elems_for(src.dtype) + compiled = _compile_tma_scatter(src.dtype) + sm = torch.cuda.get_device_properties(out.device).multi_processor_count + + grid_x, grid_y, chunks_per_cta = _plan_grid(M, N, chunk_elems, sm) + num_chunks = (N + chunk_elems - 1) // chunk_elems + compiled( + src, + index_1d, + out, + N, + num_chunks, + chunks_per_cta, + grid_x, + grid_y, + out.stride(0), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/vec_scatter_kernel.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/vec_scatter_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..37a50c7ed28ccd9e982fdc621f86f4220303e86d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/scatter_add/vec_scatter_kernel.py @@ -0,0 +1,258 @@ +"""Vectorized scatter_add with per-element atomics (pre-sm_90 fallback). + +Same input restriction as the TMA path (expanded-1D index, dim=0, 2D +contiguous tensors), but works everywhere scalar atomicAdd does. Matches +the fallback path in https://github.com/pytorch/pytorch/pull/182675. + +Algorithm: warp-per-source-row. Each warp reads ``idx[entry]`` once, then +the 32 lanes chunk through N with vectorized gather (4 fp32 or 8 halves +per lane per step) and issue atomics into ``out[ind, :]``: + +- fp32: per-element ``atomicAdd``. +- fp16/bf16: paired x2 atomics + (``red.global.add.noftz.{f16x2,bf16x2}``), one instruction per pair. + Matches the instruction count aten gets from ``atomicAdd(__half2*, ...)``. +""" + +import cuda.bindings.driver as cuda # pyrefly: ignore[missing-import] +import cutlass +import cutlass.cute as cute +import cutlass.cute.testing as cute_testing +from cutlass import BFloat16, const_expr, Float16, Float32, Int32, Int64 +from cutlass._mlir import ir +from cutlass._mlir.dialects import llvm, vector as mlir_vector +from cutlass.cutlass_dsl import dsl_user_op, T + +import torch +from torch._native.instrumentation import instrumented_cutedsl_cache + +from ._ptx import make_packed_half_atomic_add + + +_WARPS_PER_BLOCK = 8 +_THREADS_PER_BLOCK = 32 * _WARPS_PER_BLOCK +_VEC_BYTES = 16 # 16-byte vector gather = LDG.128 + +_TORCH_TO_CUTE = { + torch.float32: Float32, + torch.float16: Float16, + torch.bfloat16: BFloat16, +} + + +def _pack_half2_as_i32(val_a, val_b, elem_mlir_type, *, loc=None, ip=None): + """Build a <2 x elem> vector from two scalar halves and bitcast to i32. + Matches the layout PTX red.global.add.noftz.{f16x2,bf16x2} expects.""" + vec_type = ir.VectorType.get([2], elem_mlir_type, loc=loc) + vec = mlir_vector.from_elements( + vec_type, + [val_a.ir_value(loc=loc, ip=ip), val_b.ir_value(loc=loc, ip=ip)], + loc=loc, + ip=ip, + ) + return llvm.bitcast(T.i32(), vec, loc=loc, ip=ip) + + +_packed_atomic_add_f16x2 = make_packed_half_atomic_add("f16x2") +_packed_atomic_add_bf16x2 = make_packed_half_atomic_add("bf16x2") + + +@dsl_user_op +def _atomic_add_f16x2(ptr, val_a: Float16, val_b: Float16, *, loc=None, ip=None): + """Packed x2 f16 atomic add. Equivalent to atomicAdd(__half2*, ...).""" + gmem_ptr_i64 = ptr.toint(loc=loc, ip=ip).ir_value() + packed = _pack_half2_as_i32(val_a, val_b, Float16.mlir_type, loc=loc, ip=ip) + _packed_atomic_add_f16x2(gmem_ptr_i64, packed, loc=loc, ip=ip) + + +@dsl_user_op +def _atomic_add_bf16x2(ptr, val_a: BFloat16, val_b: BFloat16, *, loc=None, ip=None): + """Packed x2 bf16 atomic add (sm_90+).""" + gmem_ptr_i64 = ptr.toint(loc=loc, ip=ip).ir_value() + packed = _pack_half2_as_i32(val_a, val_b, BFloat16.mlir_type, loc=loc, ip=ip) + _packed_atomic_add_bf16x2(gmem_ptr_i64, packed, loc=loc, ip=ip) + + +def _make_kernel(dtype, elem_bytes: int, vec_elems: int, contig: bool): + """Build a dtype-specialized vectorized scatter-add kernel. + + Each warp handles one source row. 32 lanes chunk through N, each lane + issuing a single vectorized LDG.128 (via ``cute.autovec_copy``) for + ``vec_elems`` consecutive elements and atomic-adding them into + ``out[ind, :]``. + + fp16/bf16 use paired x2 atomics (``red.global.add.noftz.{f16x2,bf16x2}``) + to match the instruction count aten gets with ``atomicAdd(__half2*, ...)``. + fp32 uses scalar ``atomicAdd``. + """ + is_half = dtype is Float16 or dtype is BFloat16 + + @cute.kernel + def _kernel( + mSrc: cute.Tensor, + mIndex: cute.Tensor, + mOut: cute.Tensor, + num_entries: Int32, + D: Int32, + src_row_stride: Int64, + out_row_stride: Int64, + ): + tidx, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + gdim, _, _ = cute.arch.grid_dim() + + warp_in_block = tidx // Int32(32) + lane = tidx % Int32(32) + + # Contiguous fast path: row stride is D at compile time. + if const_expr(contig): + src_row_stride = Int64(D) + out_row_stride = Int64(D) + + entries_per_block = Int32(_WARPS_PER_BLOCK) + base = bidx * entries_per_block + while base < num_entries: + entry_id = base + warp_in_block + if entry_id < num_entries: + r = Int64(mIndex[entry_id]) + # Bounds check: out-of-range ``r`` would make the + # atomicAdd below corrupt unrelated memory. Compiling + # with ``--enable-assertions`` turns this into a + # device-side trap; otherwise it folds away. + cute_testing.assert_(r >= Int64(0)) + cute_testing.assert_(r < Int64(mOut.shape[0])) + + lane_offset = lane * Int32(vec_elems) + stride_elems = Int32(32 * vec_elems) + + off = lane_offset + while off < D: + src_off = Int64(entry_id) * src_row_stride + Int64(off) + dst_off = r * out_row_stride + Int64(off) + + # Vectorized gmem -> register load. ``autovec_copy`` + # picks the widest safe instruction given the static + # shape (vec_elems x elem_bytes == 16 bytes, so this + # becomes a single LDG.128). + gsrc = cute.make_tensor( + mSrc.iterator + src_off, + cute.make_layout(vec_elems), + ) + rvals = cute.make_rmem_tensor(vec_elems, dtype) + cute.autovec_copy(gsrc, rvals) + + if const_expr(is_half): + # Paired atomics: one x2 atomic per 2 elements. + # vec_elems is even for halves (8 at 16 bytes), + # so vec_elems // 2 is exact. + for p in cutlass.range_constexpr(vec_elems // 2): + v0 = 2 * p + dst_ptr = mOut.iterator + (dst_off + Int64(v0)) + if const_expr(dtype is Float16): + _atomic_add_f16x2(dst_ptr, rvals[v0], rvals[v0 + 1]) + else: + _atomic_add_bf16x2(dst_ptr, rvals[v0], rvals[v0 + 1]) + else: + for v in cutlass.range_constexpr(vec_elems): + dst_ptr_v = mOut.iterator + (dst_off + Int64(v)) + cute.arch.atomic_add(dst_ptr_v, rvals[v]) + + off = off + stride_elems + + base = base + gdim * entries_per_block + + @cute.jit + def _launch( + mSrc: cute.Tensor, + mIndex: cute.Tensor, + mOut: cute.Tensor, + stream: cuda.CUstream, + num_entries: Int32, + D: Int32, + grid_x: Int32, + src_row_stride: Int64, + out_row_stride: Int64, + ): + _kernel( + mSrc, + mIndex, + mOut, + num_entries, + D, + src_row_stride, + out_row_stride, + ).launch( + grid=[grid_x, 1, 1], + block=[_THREADS_PER_BLOCK, 1, 1], + stream=stream, + ) + + return _launch + + +@instrumented_cutedsl_cache( + "aten::scatter_add", + key_fn=lambda torch_dtype, contig: f"vec {torch_dtype} contig={contig}", +) +def _compile_vec_scatter(torch_dtype: torch.dtype, contig: bool): + # N is a runtime arg (``D``), never a compile-time constant here: the + # kernel loops ``while off < D`` and loads fixed ``vec_elems`` chunks off + # a raw iterator, so the inner dim can stay symbolic. One compile per + # (dtype, contig) serves every N. + dtype = _TORCH_TO_CUTE[torch_dtype] + elem_bytes = dtype.width // 8 + vec_elems = _VEC_BYTES // elem_bytes + launcher = _make_kernel(dtype, elem_bytes, vec_elems, contig) + + mSrc_fake = cute.runtime.make_fake_tensor( + dtype, (cute.sym_int(), cute.sym_int()), stride=(cute.sym_int64(), 1) + ) + # Index is contiguous (see _flatten_for_expanded_1d); fix stride=1 + # so `mIndex[i]` doesn't emit a runtime stride multiply. + mIndex_fake = cute.runtime.make_fake_tensor(Int64, (cute.sym_int(),), stride=(1,)) + mOut_fake = cute.runtime.make_fake_tensor( + dtype, (cute.sym_int(), cute.sym_int()), stride=(cute.sym_int64(), 1) + ) + return cute.compile( + launcher, + mSrc_fake, + mIndex_fake, + mOut_fake, + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + Int32(0), + Int32(0), + Int32(0), + Int64(0), + Int64(0), + # ``--enable-assertions`` keeps the ``cute_testing.assert_`` + # bounds checks on ``r`` live in production. Cost is roughly + # +1-10% (geomean +7.7%) on most shapes; the safety net is + # worth it because an OOB ``r`` would otherwise silently + # corrupt unrelated gmem via the per-element ``atomicAdd``. + options="--enable-tvm-ffi --enable-assertions", + ) + + +def vec_elems_for(dtype: torch.dtype) -> int: + """Elements per lane per step (16-byte vector gather).""" + return _VEC_BYTES // dtype.itemsize + + +def vec_scatter_add_into( + out: torch.Tensor, + index_1d: torch.Tensor, + src: torch.Tensor, +) -> None: + """In-place: ``out[index_1d[i], :] += src[i, :]`` for every i. + + ``out`` / ``src`` are 2D with inner-dim stride 1; outer row stride + can differ from N. Requires N divisible by ``vec_elems_for(src.dtype)`` + (the cond enforces this). When N < 32 * vec_elems the loop has fewer + active lanes per warp; lanes whose starting offset is >= N skip. + """ + M, N = src.shape + contig = src.stride(0) == N and out.stride(0) == N + compiled = _compile_vec_scatter(src.dtype, contig) + sm = torch.cuda.get_device_properties(out.device).multi_processor_count + grid = min((M + _WARPS_PER_BLOCK - 1) // _WARPS_PER_BLOCK, sm * 8) + compiled(src, index_1d, out, M, N, grid, src.stride(0), out.stride(0)) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__init__.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ead1298174416c7e2df6e01d18aec9861859421c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__init__.py @@ -0,0 +1,4 @@ +from .cutedsl_impl import register_to_dispatch + + +register_to_dispatch() diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc1cd7b71ff5566165fb476c461f18e200df0a26 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__pycache__/cutedsl_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__pycache__/cutedsl_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1af5130c539072f615790c9343a903c20f21d9c8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__pycache__/cutedsl_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__pycache__/inner_tree_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__pycache__/inner_tree_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c757e507924878726ea50720201c0c5fcc87cd6c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__pycache__/inner_tree_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__pycache__/inner_tree_plan.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__pycache__/inner_tree_plan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ea0b478e53923de218cae1296b59c81aac61283 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/__pycache__/inner_tree_plan.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/cutedsl_impl.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/cutedsl_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..7fc9ae7aa273e344467c6cb18bef0fb60c506a4e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/cutedsl_impl.py @@ -0,0 +1,255 @@ +"""CuTeDSL override registrations for ``aten::sum`` (inner-tree reduction). + +CuTeDSL port of the Triton-style inner-tree reduction sum kernel that +otherwise lives in ``aten/src/ATen/native/cuda/ReduceSumProdKernel.cu`` +(``try_inner_tree_reduction`` + the inner-tree kernels). This override +runs only when ``PYTORCH_SUM_INNER_TREE`` is set to a truthy value, which +is the feature-rollout gate for this operator -- it is *not* gated by the +global ``TORCH_DISABLE_NATIVE_JIT`` kill switch alone (that is handled by +``cutedsl_utils`` at registration time). + +We register two ATen dispatcher entries on ``CUDA``: + +* ``sum.dim_IntList`` -- functional/method ``x.sum(dim=...)``. +* ``sum.IntList_out`` -- the structured ``.out`` target. + +``sum.dim_IntList`` is ``structured_delegate: sum.IntList_out``, so its +delegation to the ``.out`` kernel happens *below* the dispatcher; overriding +``.out`` alone would not intercept ``x.sum(dim=1)``. Both are separate +dispatcher entries and are registered explicitly (the same reason +``scatter_add_`` is registered separately from ``scatter_add.out``). + +Eligibility mirrors ``try_inner_tree_reduction`` (ReduceSumProdKernel.cu): +build the reduction ``TensorIterator`` over ``(out, self)`` and accept only +the coalesced geometry the kernels know how to run -- a single contiguous +reduced (fastest) dimension whose non-reduced dims collapse to at most one +outer-strided dimension. Anything else (multi-dim reduction, non-contiguous +reduced dim, dtype-casting sum, integer/complex dtypes, non-collapsing outer +layout) falls through to aten. + +Dispatch note: this CuTeDSL override is the only inner-tree path -- the ATen +CUDA backend has no inner-tree kernel of its own. When this predicate accepts, +the CuTeDSL kernel runs; when it rejects (or ``PYTORCH_SUM_INNER_TREE`` is +unset), the call falls through to the unchanged ATen reduction. +""" + +from __future__ import annotations + +import os + +import torch +from torch._subclasses.fake_tensor import is_fake_tensor +from torch._tensor_iterator import reduce_op, TensorIterator + +from ... import cutedsl_utils as cu + + +# Reduction input dtypes the kernel handles. fp32/fp64 are the bitwise- +# validated set (the inner-tree bitwise tests upcast fp16/bf16/fp8 data to +# fp32 before summing, and fp64 sums in fp64). fp16/bf16 native reductions +# (acc in fp32) are functionally supported but not part of the bitwise +# contract. +_SUPPORTED_DTYPES = frozenset( + {torch.float16, torch.bfloat16, torch.float32, torch.float64} +) + +# The kernel indexes rows/elements and sizes the launch grid with Int32. Decline +# reductions whose sizes would overflow that so we fall through to ATen rather +# than silently wrap (mirrors the magnitude guard from the CUDA review). +_INT32_MAX = 2**31 - 1 + + +def _int32_indexing_safe(self: torch.Tensor, d: int) -> bool: + """Decline giant reductions so the kernel's Int32 row/element indexing and + launch grid never wrap. The two-kernel grid is ``m * num_batches``; + ``num_batches`` is bounded above by ``ceil(n / (32 * vec_size))`` (the + smallest possible per-batch width), so this bound covers every path.""" + n = self.shape[d] + if n == 0: + return True + m = self.numel() // n + vec_size = max(1, 16 // self.element_size()) + num_batches_ub = -(-n // (32 * vec_size)) + return n <= _INT32_MAX and m <= _INT32_MAX and m * num_batches_ub <= _INT32_MAX + + +def _inner_tree_enabled() -> bool: + # The CUDA gate is `use_inner_tree_reduction()`; the CuTeDSL predicate + # requires the explicit feature flag (an empty/"0" value is off). + return os.getenv("PYTORCH_SUM_INNER_TREE", "") not in ("", "0") + + +def _normalize_dim(dim: int, ndim: int) -> int: + return dim + ndim if dim < 0 else dim + + +def _single_dim(dim, ndim: int) -> int | None: + """Return the one normalized reduced dim, or ``None`` if this is not a + single-dim reduction (matches ``num_reduce_dims == 1``).""" + if dim is None: + return None + if isinstance(dim, int): + dims = [dim] + else: + dims = list(dim) + if len(dims) != 1: + return None + return _normalize_dim(dims[0], ndim) + + +def _keepdim_out_shape(self: torch.Tensor, d: int) -> list[int]: + shape = list(self.shape) + shape[d] = 1 + return shape + + +def _out_keepdim_view( + self: torch.Tensor, d: int, keepdim: bool, out: torch.Tensor +) -> torch.Tensor | None: + """Return a keepdim-shaped ``(.., 1, ..)`` view of ``out`` so the kernel + writes ``out``'s storage directly. ``unsqueeze`` is always a view (unlike + ``reshape``, which may copy a non-contiguous ``out``). Returns ``None`` if + ``out`` is not the expected reduced shape.""" + expected = _keepdim_out_shape(self, d) + try: + out_kd = out if keepdim else out.unsqueeze(d) + except IndexError: + return None + return out_kd if list(out_kd.shape) == expected else None + + +def _eligibility( + self: torch.Tensor, d: int, out: torch.Tensor +) -> TensorIterator | None: + """Return the reduction ``TensorIterator`` if ``(self, d, out)`` fits the + kernel's expected geometry, else ``None``. ``d`` is already normalized + and ``out`` is a keepdim-shaped output (broadcast-aligned with ``self``). + + Mirrors ``try_inner_tree_reduction``: build the reduction iterator, then + require a single coalesced reduced (fastest) dimension with element + stride 1 on the input, and at most one non-reduced (outer) dimension so + the operands canonicalize to a single ``(M, N)`` view. + """ + try: + it = reduce_op(out, self) + except RuntimeError: + return None + + if it.numel == 0: + return None + if it.ndim == 0 or it.ndim > 2: + return None + + input_index = it.ntensors - 1 # operands are (out, self); input is last + es_in = it.element_strides(input_index) + # Input must be contiguous on the reduced (fastest, dim-0) axis. + if es_in[0] != 1: + return None + # Reduction must be on the fastest dim: either the whole tensor is the + # reduction (ndim == 1) or the reduced-dim stride is the smallest. + if it.ndim == 2 and not (es_in[0] < es_in[1]): + return None + return it + + +def _geometry(self: torch.Tensor, out: torch.Tensor, it: TensorIterator): + """Recover ``(M, N, in_row_stride, out_row_stride)`` (element units) from + the coalesced reduction iterator. ``M`` output rows, each a contiguous + ``N``-element reduction; ``in_row_stride`` / ``out_row_stride`` step + between rows of the canonical ``(M, N)`` / ``(M,)`` views.""" + m = out.numel() + n = self.numel() // m if m else 0 + if it.ndim == 2: + in_row_stride = it.element_strides(it.ntensors - 1)[1] + out_row_stride = it.element_strides(0)[1] + else: + in_row_stride = n + out_row_stride = 1 + return m, n, in_row_stride, out_row_stride + + +def _base_cond_ok(self: torch.Tensor, dim, dtype) -> int | None: + """Shared front gate. Returns the normalized reduced dim if the call is a + candidate, else ``None``.""" + if not _inner_tree_enabled(): + return None + if not self.is_cuda or is_fake_tensor(self): + return None + # dtype-casting sum (an explicit out/result dtype) is out of scope. + if dtype is not None: + return None + if self.dtype not in _SUPPORTED_DTYPES: + return None + d = _single_dim(dim, self.ndim) + if d is None or not (0 <= d < self.ndim): + return None + if not _int32_indexing_safe(self, d): + return None + return d + + +def _cond(self, dim, keepdim=False, *, dtype=None) -> bool: + d = _base_cond_ok(self, dim, dtype) + if d is None: + return False + out = torch.empty(_keepdim_out_shape(self, d), dtype=self.dtype, device=self.device) + return _eligibility(self, d, out) is not None + + +def _out_cond(self, dim, keepdim=False, *, dtype=None, out) -> bool: + d = _base_cond_ok(self, dim, dtype) + if d is None: + return False + if out.dtype != self.dtype or not out.is_cuda or is_fake_tensor(out): + return False + # The kernel writes ``out`` directly via a keepdim-aligned view; ``out`` + # must already have the reduced shape. Reject mis-shaped ``out`` and let + # aten produce the proper error. + out_kd = _out_keepdim_view(self, d, keepdim, out) + if out_kd is None: + return False + return _eligibility(self, d, out_kd) is not None + + +def _kernel(): + from .inner_tree_kernel import inner_tree_sum_into + + return inner_tree_sum_into + + +def _run(self: torch.Tensor, d: int, out_kd: torch.Tensor) -> None: + """Run the kernel writing the reduction of ``self`` along ``d`` into the + keepdim-shaped ``out_kd``. Caller has validated eligibility.""" + it = _eligibility(self, d, out_kd) + if it is None: + raise RuntimeError("sum cutedsl: cond approved but iter rebuild failed") + m, n, in_rs, out_rs = _geometry(self, out_kd, it) + if m == 0 or n == 0: + return + in_2d = self.as_strided((m, n), (in_rs, 1)) + out_1d = out_kd.as_strided((m,), (out_rs,)) + _kernel()(out_1d, in_2d) + + +def _impl(self, dim, keepdim=False, *, dtype=None): + d = _normalize_dim(dim[0] if not isinstance(dim, int) else dim, self.ndim) + out_kd = torch.empty( + _keepdim_out_shape(self, d), dtype=self.dtype, device=self.device + ) + _run(self, d, out_kd) + return out_kd if keepdim else out_kd.squeeze(d) + + +def _out_impl(self, dim, keepdim=False, *, dtype=None, out): + d = _normalize_dim(dim[0] if not isinstance(dim, int) else dim, self.ndim) + out_kd = _out_keepdim_view(self, d, keepdim, out) + assert out_kd is not None # noqa: S101 # _out_cond guarantees non-None + _run(self, d, out_kd) + return out + + +def register_to_dispatch() -> None: + cu.register_op_override("aten", "sum.dim_IntList", "CUDA", cond=_cond, impl=_impl) + cu.register_op_override( + "aten", "sum.IntList_out", "CUDA", cond=_out_cond, impl=_out_impl + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/inner_tree_kernel.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/inner_tree_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..476b9bae356484cd0171c60ac4527cfae8800e0a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/inner_tree_kernel.py @@ -0,0 +1,637 @@ +"""CuTeDSL inner-tree sum reduction kernels. + +Bitwise port of the inner-tree reduction kernels in +``aten/src/ATen/native/cuda/ReduceSumProdKernel.cu`` (with helpers from +``ReduceInnerTree.cuh`` / ``WarpReduce.cuh``). Each output element is the +sum of ``N`` contiguous input elements; ``N`` is baked in at ``cute.compile`` +time so the per-row vector tree, streaming tree, and launch planning all +unroll at trace time and the accumulation order matches the CUDA kernel +exactly. + +Three execution shapes, selected on the host exactly as +``try_inner_tree_reduction`` does: + +* Multirow (``inner_tree_reduction_multirow_kernel``): one thread per row, + used when ``N <= vec_size * kMultiRowMaxLoads``. +* Looped (``inner_tree_reduction_looped_kernel``): warps cooperate per row, + batches accumulated inside the kernel; used when ``num_batches <= 3``. +* Two-kernel (``inner_tree_reduction_kernel`` + + ``inner_tree_accumulate_multirow_kernel``): a partials kernel followed by a + linear per-row accumulate; used otherwise. + +Bitwise-critical ordering reproduced here: + +* ``vec_size = 16 / itemsize`` grouping; the in-vec tree order + (``inner_tree_reduce``) for vec_size >= 4, else linear. Zero-padded tails + are bitwise identical between tree and linear (``x + 0 == x``), so a single + uniform choice covers both the full and tail cases. +* Warp butterfly with ASCENDING shuffle-XOR offsets ``1,2,4,...`` (matches + ``WarpReduceDirection::ASCENDING``); we hand-roll it because + ``cute.arch.warp_reduction`` uses descending offsets, which is a different + (and thus bitwise-different) order. +* Streaming inner-tree carry across loads (``streaming_inner_tree_step``, + merge count = trailing-zero bits of ``load + 1``). +* Accumulation dtype: fp32 for fp16/bf16/fp32, fp64 for fp64 -- matches + ``reduce_dispatch`` so rounding is identical. The inner-tree bitwise tests + only exercise fp32 and fp64 (they upcast narrower data first); fp16/bf16 + native reductions are functionally supported but not bitwise-validated. + +Because ``N`` is compile-time, a warp/batch that owns fewer than the unrolled +number of loads contributes zeros for the extra loads; zeros are additive +identities, so this reproduces the ragged CUDA loop bit-for-bit. +""" + +from __future__ import annotations + +import cuda.bindings.driver as cuda # pyrefly: ignore[missing-import] # noqa: TC002 + +import cutlass +import cutlass.cute as cute + +# fp64 is part of the bitwise contract; import Float64 directly so an +# unsupported runtime surfaces a clear error rather than silently dropping it. +from cutlass import BFloat16, const_expr, Float16, Float32, Float64, Int32 + +import torch +from torch._native.instrumentation import instrumented_cutedsl_cache + +from .inner_tree_plan import ( + _ceil_div, + _K_MULTIROW_MAX_LOADS, + _K_TWO_KERNEL_THRESHOLD, + _next_power_of_2, + _WARP_SIZE, + compute_inner_tree_params, + InnerTreeParams, + vec_size as _vec_size, +) + + +_MULTIROW_THREADS = 128 +_MULTIROW_MAX_DEPTH = 6 # kMaxDepth in the multirow kernel +_ACCUM_THREADS = 128 # kAccumulateThreads + +_TORCH_TO_CUTE = { + torch.float16: Float16, + torch.bfloat16: BFloat16, + torch.float32: Float32, + torch.float64: Float64, +} + + +def _acc_for(in_dt): + return Float64 if in_dt is Float64 else Float32 + + +# Torch accumulator dtype for the two-kernel partials buffer (fp32 for +# fp16/bf16/fp32, fp64 for fp64) -- keeps cross-batch accumulation in the +# accumulator dtype, matching ATen. +_ACC_TORCH_DTYPE = { + torch.float16: torch.float32, + torch.bfloat16: torch.float32, + torch.float32: torch.float32, + torch.float64: torch.float64, +} + + +# --------------------------------------------------------------------------- +# Trace-time reduction helpers. These run during ``cute.compile`` tracing and +# emit the exact add DAG; ``vals`` / ``tree`` are Python lists of cute +# ``Numeric`` register values. +# --------------------------------------------------------------------------- + + +def _linear_reduce(vals): + acc = vals[0] + for i in range(1, len(vals)): + acc = acc + vals[i] + return acc + + +def _inner_tree_reduce(vals): + v = list(vals) + n = len(v) + stride = 1 + while stride < n: + i = 0 + while i + stride < n: + v[i] = v[i] + v[i + stride] + i += stride * 2 + stride *= 2 + return v[0] + + +def _reduce_vec(vals, vec_size: int): + return _inner_tree_reduce(vals) if vec_size >= 4 else _linear_reduce(vals) + + +def _streaming_push(tree, val, load: int, max_depth: int) -> None: + """Port of ``streaming_inner_tree_step``: merge count is the number of + trailing zero bits of ``load + 1`` (``__ffs(load + 1) - 1``), capped at + ``max_depth``. ``carry = tree_accs[--top] + carry`` keeps the existing + accumulator on the left.""" + trailing_zeros = ((load + 1) & -(load + 1)).bit_length() - 1 + carry = val + for _ in range(min(trailing_zeros, max_depth)): + carry = tree.pop() + carry + tree.append(carry) + + +def _warp_butterfly(val): + """Ascending-offset shuffle-XOR butterfly add reduce (matches the CUDA + ``warp_reduce`` ASCENDING direction).""" + offset = 1 + while offset < _WARP_SIZE: + val = val + cute.arch.shuffle_sync_bfly( + val, offset=offset, mask_and_clamp=_WARP_SIZE - 1 + ) + offset <<= 1 + return val + + +def _load_vec_static(mIn, row, base: int, N: int, vec_size: int, acc, zero): + """Load + reduce one vector group with compile-time ``base`` (multirow).""" + vals = [] + for i in range(vec_size): + off = base + i + vals.append(acc(mIn[row, off]) if off < N else zero) + return _reduce_vec(vals, vec_size) + + +@cute.jit +def _load_vec_dyn( + mIn, + row, + base, + N: cutlass.Constexpr, + vec_size: cutlass.Constexpr, + acc: cutlass.Constexpr, + zero, +): + """Load + reduce one vector group with a runtime ``base`` (warp paths). + + ``@cute.jit`` so the per-element bounds check is lowered by the DSL + instead of evaluated as a Python bool at trace time (the kernel body's + AST transform does not reach into plain helpers). Each element is guarded + against the row width so out-of-row reads never happen and tail elements + contribute zero. + """ + vals = [] + for i in cutlass.range_constexpr(vec_size): + off = base + Int32(i) + v = zero + if off < Int32(N): + v = acc(mIn[row, off]) + vals.append(v) + return _reduce_vec(vals, vec_size) + + +# --------------------------------------------------------------------------- +# Kernel builders. Each returns a ``@cute.jit`` launcher specialized on the +# compile-time parameters. +# --------------------------------------------------------------------------- + + +def _make_multirow(in_dt, acc, out_dt, N: int, vec_size: int): + num_loads = _next_power_of_2(_ceil_div(N, vec_size)) + + @cute.kernel + def _kernel(mIn: cute.Tensor, mOut: cute.Tensor, num_outputs: Int32): + tx, _, _ = cute.arch.thread_idx() + bx, _, _ = cute.arch.block_idx() + row = bx * Int32(_MULTIROW_THREADS) + tx + if row < num_outputs: + zero = acc(0.0) + tree = [] + for load in cutlass.range_constexpr(num_loads): + val = _load_vec_static( + mIn, row, load * vec_size, N, vec_size, acc, zero + ) + _streaming_push(tree, val, load, _MULTIROW_MAX_DEPTH) + mOut[row] = out_dt(tree[0]) + + @cute.jit + def _launch( + mIn: cute.Tensor, + mOut: cute.Tensor, + stream: cuda.CUstream, + num_outputs: Int32, + grid: Int32, + ): + _kernel(mIn, mOut, num_outputs).launch( + grid=[grid, 1, 1], block=[_MULTIROW_THREADS, 1, 1], stream=stream + ) + + return _launch + + +def _make_looped(in_dt, acc, out_dt, N: int, vec_size: int, p: InnerTreeParams): + wpr = p.num_warps # warps_per_reduction == num_warps in launch_looped + rows_per_block = p.rows_per_block + total_warps = wpr * rows_per_block + wle = _WARP_SIZE * vec_size + + # Per-batch geometry is fully compile-time (num_batches <= 3, fixed N). + batches = [] + for b in range(p.num_batches): + batch_offset = b * p.batch_total_elements + remaining = min(p.batch_total_elements, N - batch_offset) + lpw = _ceil_div(remaining, wpr * wle) + if lpw > 1: + lpw = _next_power_of_2(lpw) + batches.append((batch_offset, remaining, lpw, lpw * wle)) + + @cute.kernel + def _kernel(mIn: cute.Tensor, mOut: cute.Tensor, num_outputs: Int32): + tx, ty, _ = cute.arch.thread_idx() + bx, _, _ = cute.arch.block_idx() + lane = tx + global_warp_id = ty + row_in_block = global_warp_id // Int32(wpr) + warp_id = global_warp_id % Int32(wpr) + row = bx * Int32(rows_per_block) + row_in_block + row_active = row < num_outputs + + warp_writes = None # bound for type checker; used only when wpr > 1 + if const_expr(wpr > 1): + smem = cutlass.utils.SmemAllocator() + warp_writes = smem.allocate_tensor( + acc, cute.make_layout(total_warps), byte_alignment=8 + ) + + zero = acc(0.0) + final_sum = zero + for b in cutlass.range_constexpr(p.num_batches): + batch_offset, remaining_c, lpw, warp_chunk = batches[b] + rem = Int32(0) + if row_active: + rem = Int32(remaining_c) + warp_off = warp_id * Int32(warp_chunk) + if warp_off > rem: + warp_off = rem + warp_start = Int32(batch_offset) + warp_off + this_warp_elements = Int32(warp_chunk) + tail = rem - warp_off + if this_warp_elements > tail: + this_warp_elements = tail + this_batch_loads = (this_warp_elements + Int32(wle - 1)) // Int32(wle) + + tree = [] + for load in cutlass.range_constexpr(lpw): + base = warp_start + Int32(load * wle) + lane * Int32(vec_size) + v = zero + if Int32(load) < this_batch_loads: + v = _warp_butterfly( + _load_vec_dyn(mIn, row, base, N, vec_size, acc, zero) + ) + _streaming_push(tree, v, load, p.depth) + warp_acc = tree[0] + + if const_expr(wpr > 1): + assert warp_writes is not None # noqa: S101 + if lane == Int32(0): + warp_writes[row_in_block * Int32(wpr) + warp_id] = warp_acc + cute.arch.barrier() + merged = zero + if lane < Int32(wpr): + merged = warp_writes[row_in_block * Int32(wpr) + lane] + warp_acc = _warp_butterfly(merged) + if const_expr(b + 1 < p.num_batches): + cute.arch.barrier() + + final_sum = final_sum + warp_acc + + if row_active: + if lane == Int32(0): + if warp_id == Int32(0): + mOut[row] = out_dt(final_sum) + + @cute.jit + def _launch( + mIn: cute.Tensor, + mOut: cute.Tensor, + stream: cuda.CUstream, + num_outputs: Int32, + grid: Int32, + ): + _kernel(mIn, mOut, num_outputs).launch( + grid=[grid, 1, 1], block=[_WARP_SIZE, total_warps, 1], stream=stream + ) + + return _launch + + +def _make_two_partial(in_dt, acc, out_dt, N: int, vec_size: int, p: InnerTreeParams): + wpr = p.num_warps + num_batches = p.num_batches + wle = _WARP_SIZE * vec_size + eff = p.effective_loads + + # Only two distinct per-batch widths: full batches and the (shorter) last + # batch. Precompute both; the kernel selects on ``batch_idx`` at runtime. + full_remaining = p.batch_total_elements + last_remaining = N - (num_batches - 1) * p.batch_total_elements + warp_chunk_full = eff * wle + + def _lpw(remaining: int) -> int: + lpw = _ceil_div(remaining, wpr * wle) + return _next_power_of_2(lpw) if lpw > 1 else lpw + + warp_chunk_last = _lpw(last_remaining) * wle + + @cute.kernel + def _kernel(mIn: cute.Tensor, mPartials: cute.Tensor): + # Grid is exactly num_outputs * num_batches, so no row bounds check. + tx, ty, _ = cute.arch.thread_idx() + bx, _, _ = cute.arch.block_idx() + lane = tx + warp_id = ty + row = bx // Int32(num_batches) + batch_idx = bx % Int32(num_batches) + + remaining = Int32(full_remaining) + warp_chunk = Int32(warp_chunk_full) + if batch_idx == Int32(num_batches - 1): + remaining = Int32(last_remaining) + warp_chunk = Int32(warp_chunk_last) + batch_offset = batch_idx * Int32(p.batch_total_elements) + + warp_writes = None # bound for type checker; used only when wpr > 1 + if const_expr(wpr > 1): + smem = cutlass.utils.SmemAllocator() + warp_writes = smem.allocate_tensor( + acc, cute.make_layout(wpr), byte_alignment=8 + ) + + warp_off = warp_id * warp_chunk + if warp_off > remaining: + warp_off = remaining + warp_start = batch_offset + warp_off + this_warp_elements = warp_chunk + tail = remaining - warp_off + if this_warp_elements > tail: + this_warp_elements = tail + this_batch_loads = (this_warp_elements + Int32(wle - 1)) // Int32(wle) + + zero = acc(0.0) + tree = [] + for load in cutlass.range_constexpr(eff): + base = warp_start + Int32(load * wle) + lane * Int32(vec_size) + v = zero + if Int32(load) < this_batch_loads: + v = _warp_butterfly( + _load_vec_dyn(mIn, row, base, N, vec_size, acc, zero) + ) + _streaming_push(tree, v, load, p.depth) + warp_acc = tree[0] + + if const_expr(wpr > 1): + assert warp_writes is not None # noqa: S101 + if lane == Int32(0): + warp_writes[warp_id] = warp_acc + cute.arch.barrier() + merged = zero + if lane < Int32(wpr): + merged = warp_writes[lane] + warp_acc = _warp_butterfly(merged) + + if lane == Int32(0): + if warp_id == Int32(0): + # Store partials in the accumulator dtype so the cross-batch + # sum stays in fp32 for fp16/bf16 (matches ATen's + # accumulate-in-fp32-round-once); downcast happens only in the + # accumulate kernel's final write. + mPartials[row * Int32(num_batches) + batch_idx] = acc(warp_acc) + + @cute.jit + def _launch( + mIn: cute.Tensor, + mPartials: cute.Tensor, + stream: cuda.CUstream, + grid: Int32, + ): + _kernel(mIn, mPartials).launch( + grid=[grid, 1, 1], block=[_WARP_SIZE, wpr, 1], stream=stream + ) + + return _launch + + +def _make_two_accum(acc, out_dt, num_batches: int): + @cute.kernel + def _kernel(mPartials: cute.Tensor, mOut: cute.Tensor, num_outputs: Int32): + tx, _, _ = cute.arch.thread_idx() + bx, _, _ = cute.arch.block_idx() + row = bx * Int32(_ACCUM_THREADS) + tx + if row < num_outputs: + base = row * Int32(num_batches) + # Partials are in the accumulator dtype; accumulate in that dtype + # and downcast to the output dtype only on the final store. + s = mPartials[base] + # Runtime loop, NOT range_constexpr: num_batches grows with N + # (thousands for very large reductions), so unrolling would make + # cute.compile blow up. Linear accumulation order matches the CUDA + # kernel regardless of unroll. + for b in cutlass.range(1, num_batches): + s = s + mPartials[base + b] + mOut[row] = out_dt(s) + + @cute.jit + def _launch( + mPartials: cute.Tensor, + mOut: cute.Tensor, + stream: cuda.CUstream, + num_outputs: Int32, + grid: Int32, + ): + _kernel(mPartials, mOut, num_outputs).launch( + grid=[grid, 1, 1], block=[_ACCUM_THREADS, 1, 1], stream=stream + ) + + return _launch + + +# --------------------------------------------------------------------------- +# Compile cache + host dispatch. +# --------------------------------------------------------------------------- + + +def _fake_2d(dt, N: int): + return cute.runtime.make_fake_tensor( + dt, (cute.sym_int(), N), stride=(cute.sym_int64(), 1) + ) + + +def _fake_1d(dt): + return cute.runtime.make_fake_tensor( + dt, (cute.sym_int(),), stride=(cute.sym_int64(),) + ) + + +def _fake_1d_contig(dt): + return cute.runtime.make_fake_tensor(dt, (cute.sym_int(),), stride=(1,)) + + +@instrumented_cutedsl_cache( + "aten::sum", + key_fn=lambda torch_dtype, N: f"multirow {torch_dtype} N={N}", +) +def _compile_multirow(torch_dtype: torch.dtype, N: int): + in_dt = _TORCH_TO_CUTE[torch_dtype] + acc = _acc_for(in_dt) + launcher = _make_multirow(in_dt, acc, in_dt, N, _vec_size(torch_dtype.itemsize)) + return cute.compile( + launcher, + _fake_2d(in_dt, N), + _fake_1d(in_dt), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + Int32(0), + Int32(0), + options="--enable-tvm-ffi", + ) + + +@instrumented_cutedsl_cache( + "aten::sum", + key_fn=lambda torch_dtype, N, num_warps, _bte, num_batches, *_rest: ( + f"looped {torch_dtype} N={N} warps={num_warps} batches={num_batches}" + ), +) +def _compile_looped( + torch_dtype: torch.dtype, + N: int, + num_warps: int, + batch_total_elements: int, + num_batches: int, + depth: int, + rows_per_block: int, + effective_loads: int, +): + in_dt = _TORCH_TO_CUTE[torch_dtype] + acc = _acc_for(in_dt) + p = InnerTreeParams( + num_warps, + batch_total_elements, + num_batches, + depth, + rows_per_block, + effective_loads, + ) + launcher = _make_looped(in_dt, acc, in_dt, N, _vec_size(torch_dtype.itemsize), p) + return cute.compile( + launcher, + _fake_2d(in_dt, N), + _fake_1d(in_dt), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + Int32(0), + Int32(0), + options="--enable-tvm-ffi", + ) + + +@instrumented_cutedsl_cache( + "aten::sum", + key_fn=lambda torch_dtype, N, num_warps, _bte, num_batches, *_rest: ( + f"two_partial {torch_dtype} N={N} warps={num_warps} batches={num_batches}" + ), +) +def _compile_two_partial( + torch_dtype: torch.dtype, + N: int, + num_warps: int, + batch_total_elements: int, + num_batches: int, + depth: int, + effective_loads: int, +): + in_dt = _TORCH_TO_CUTE[torch_dtype] + acc = _acc_for(in_dt) + p = InnerTreeParams( + num_warps, + batch_total_elements, + num_batches, + depth, + 1, + effective_loads, + ) + launcher = _make_two_partial(in_dt, acc, acc, N, _vec_size(torch_dtype.itemsize), p) + return cute.compile( + launcher, + _fake_2d(in_dt, N), + _fake_1d_contig(acc), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + Int32(0), + options="--enable-tvm-ffi", + ) + + +@instrumented_cutedsl_cache( + "aten::sum", + key_fn=lambda torch_dtype, num_batches: ( + f"two_accum {torch_dtype} batches={num_batches}" + ), +) +def _compile_two_accum(torch_dtype: torch.dtype, num_batches: int): + out_dt = _TORCH_TO_CUTE[torch_dtype] + acc = _acc_for(out_dt) + launcher = _make_two_accum(acc, out_dt, num_batches) + return cute.compile( + launcher, + _fake_1d_contig(acc), + _fake_1d(out_dt), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + Int32(0), + Int32(0), + options="--enable-tvm-ffi", + ) + + +def inner_tree_sum_into(out: torch.Tensor, src: torch.Tensor) -> None: + """Compute ``out[r] = sum(src[r, :])`` for every row ``r``. + + ``src`` is a 2D ``(M, N)`` view with inner-dim stride 1 (outer row stride + may differ from N); ``out`` is a 1D ``(M,)`` view (its stride may differ + from 1). Both carry their strides into the kernel via the cute tensor, so + strided outer inputs and strided outputs are handled directly. + """ + m, n = src.shape + dtype = src.dtype + vec_size = _vec_size(dtype.itemsize) + + if n <= vec_size * _K_MULTIROW_MAX_LOADS: + compiled = _compile_multirow(dtype, n) + grid = _ceil_div(m, _MULTIROW_THREADS) + compiled(src, out, m, grid) + return + + p = compute_inner_tree_params(n, m, vec_size) + if p.num_batches <= _K_TWO_KERNEL_THRESHOLD: + compiled = _compile_looped( + dtype, + n, + p.num_warps, + p.batch_total_elements, + p.num_batches, + p.depth, + p.rows_per_block, + p.effective_loads, + ) + grid = _ceil_div(m, p.rows_per_block) + compiled(src, out, m, grid) + return + + partials = torch.empty( + m * p.num_batches, dtype=_ACC_TORCH_DTYPE[dtype], device=src.device + ) + c1 = _compile_two_partial( + dtype, + n, + p.num_warps, + p.batch_total_elements, + p.num_batches, + p.depth, + p.effective_loads, + ) + c1(src, partials, m * p.num_batches) + c2 = _compile_two_accum(dtype, p.num_batches) + c2(partials, out, m, _ceil_div(m, _ACCUM_THREADS)) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/inner_tree_plan.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/inner_tree_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..bc1ab203b3871ad0e4bd32c926acce633f7c84b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/sum/inner_tree_plan.py @@ -0,0 +1,106 @@ +from typing import NamedTuple + + +_WARP_SIZE = 32 +# Persistent/loop batch-size boundary (kInnerTreeThreshold). +_K_INNER_TREE_THRESHOLD = 8192 +# Tiny-N multirow boundary (kMultiRowMaxLoads). +_K_MULTIROW_MAX_LOADS = 8 +# Looped-vs-split boundary on num_batches (kTwoKernelThreshold). +_K_TWO_KERNEL_THRESHOLD = 3 +_K_TARGET_WARPS_PER_BLOCK = 8 # kTargetWarpsPerBlock + + +def _previous_power_of_2(n: int) -> int: + power = 1 + while power * 2 <= n: + power <<= 1 + return power + + +def _next_power_of_2(n: int) -> int: + power = 1 + while power < n: + power <<= 1 + return power + + +def _ceil_div(a: int, b: int) -> int: + return -(-a // b) + + +def vec_size(itemsize: int) -> int: + """16-byte vectorized loads: fp32->4, fp64->2, fp16/bf16->8.""" + return max(1, 16 // max(1, itemsize)) + + +class InnerTreeParams(NamedTuple): + num_warps: int + batch_total_elements: int # Inductor R0_BLOCK (the per-batch tile). + # Inductor split count: ceil(N / batch_total_elements). + num_batches: int + depth: int + rows_per_block: int + effective_loads: int + + +def compute_inner_tree_params( + inputs_per_output: int, num_outputs: int, vec_size: int +) -> InnerTreeParams: + """Plan the inner-tree reduction for one row of inputs. + + ``vec_size`` is ``vec_size(itemsize)``. The result is the tiling used by + the eager kernel. Inductor consumes ``batch_total_elements`` (R0_BLOCK) + and ``num_batches`` (split count). + """ + wle = _WARP_SIZE * vec_size + threshold = _K_INNER_TREE_THRESHOLD + n = inputs_per_output + + if n > threshold: + num_batches_est = _ceil_div(n, threshold) + if num_batches_est <= _K_TWO_KERNEL_THRESHOLD: + total_ideal_warps = 0 + for b in range(num_batches_est): + batch_start = b * threshold + batch_elements = min(threshold, n - batch_start) + total_ideal_warps += min(16, max(1, batch_elements // wle)) + num_warps = max(1, total_ideal_warps // num_batches_est) + else: + num_warps = min(16, max(1, threshold // wle)) + else: + num_warps = min(16, max(1, n // wle)) + num_warps = _previous_power_of_2(num_warps) + + loads_per_warp = _ceil_div(n, num_warps * wle) + if loads_per_warp > 1: + loads_per_warp = _next_power_of_2(loads_per_warp) + + max_loads_per_batch = max(1, threshold // (wle * num_warps)) + max_loads_per_batch = _previous_power_of_2(max_loads_per_batch) + effective_loads = min(loads_per_warp, max_loads_per_batch) + + batch_total_elements = effective_loads * wle * num_warps + num_batches = _ceil_div(n, batch_total_elements) + + if num_warps < _K_TARGET_WARPS_PER_BLOCK and num_batches <= _K_TWO_KERNEL_THRESHOLD: + rows_per_block = min(num_outputs, _K_TARGET_WARPS_PER_BLOCK // num_warps) + else: + rows_per_block = 1 + + depth = 0 + nn = effective_loads + 1 + while nn > 1: + depth += 1 + nn >>= 1 + if depth < 1: + depth = 1 + + return InnerTreeParams( + num_warps, + batch_total_elements, + num_batches, + depth, + rows_per_block, + effective_loads, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__init__.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5353b2840ab927034c6aada6623941f7ad2568e2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__init__.py @@ -0,0 +1,4 @@ +from .cutedsl_impl import register_to_dispatch as _register_cutedsl + + +_register_cutedsl() diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25ebb73a643a08173723cd08bc00dab5e1768836 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/_common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/_common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..217e81dec489677eb48f4de83eb92264aa78a8b6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/_common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/cutedsl_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/cutedsl_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e07e098d83cdab32360abe7ead00521c8cd36e0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/cutedsl_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/cutedsl_kernels.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/cutedsl_kernels.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75d6c03c035c198e6fa392c0d0001d62194cfbb2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/__pycache__/cutedsl_kernels.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/_common.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..d54ce205a86c3aa234cc9dc962eca21f78aeb555 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/_common.py @@ -0,0 +1,71 @@ +"""Shared eligibility checks and reshape helpers for topk overrides. + +Both the CuTeDSL and Triton paths operate on a 2D ``(M, N)`` fp32 row-major +view of ``self`` where ``dim`` points at the last axis. This module hosts the +checks the conds share (contiguity, dim normalisation, COW) and the reshape +helpers the impls share. +""" + +import math + +import torch + + +def any_cow(*tensors: torch.Tensor) -> bool: + return any( + torch._C._is_cow_tensor(t) # pyrefly: ignore[missing-attribute] + for t in tensors + ) + + +def normalise_dim(self: torch.Tensor, dim: int) -> int: + """Translate a possibly-negative dim into its non-negative form. + + Returns ``-1`` if the dim is out of range (cond callers should reject + in that case). + """ + if self.ndim == 0: + return -1 + if dim < -self.ndim or dim >= self.ndim: + return -1 + return dim % self.ndim + + +def last_dim_row_major_ok(self: torch.Tensor, dim: int) -> bool: + """True iff reducing over ``dim`` is equivalent to reducing over the last + axis of a 2D ``(prod(leading dims), N)`` row-major view. + + Requires ``dim`` to be the last axis and ``self`` to be contiguous in the + standard row-major sense; together they ensure the flatten-to-2D view we + pass to the kernel is a view (not a copy) and has stride-1 on N. + """ + norm = normalise_dim(self, dim) + if norm != self.ndim - 1: + return False + return self.is_contiguous() + + +def flatten_last_dim(self: torch.Tensor) -> torch.Tensor: + """View nD self as 2D ``(M, N)`` with ``N = self.shape[-1]``. + + Caller must have verified ``last_dim_row_major_ok`` so this is a view. + """ + if self.ndim == 2: + return self + if self.ndim == 1: + return self.view(1, self.shape[0]) + N = self.shape[-1] + M = math.prod(self.shape[:-1]) + return self.view(M, N) + + +def unflatten_last_dim( + flat_values: torch.Tensor, flat_indices: torch.Tensor, self: torch.Tensor, k: int +) -> tuple[torch.Tensor, torch.Tensor]: + """Reshape the 2D ``(M, K)`` kernel outputs back into ``self``'s shape.""" + if self.ndim == 2: + return flat_values, flat_indices + if self.ndim == 1: + return flat_values.view(k), flat_indices.view(k) + out_shape = self.shape[:-1] + (k,) + return flat_values.view(out_shape), flat_indices.view(out_shape) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/cutedsl_impl.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/cutedsl_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..2b374598a7a04cb8afc97ba598372d8425c6fd00 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/cutedsl_impl.py @@ -0,0 +1,230 @@ +"""CuTeDSL override registrations for ``aten::topk``. + +Two kernels, picked by (K, N) - see ``cutedsl_kernels.py``: + + * Register-resident (small K, small N): K in {16, 32}, N a power of 2 + in a per-K range (see ``_REGISTER_N_RANGE``). Each warp sorts one + row entirely in registers and writes only K outputs to gmem. + Bit-exact to aten on values; indices on ties land in + ``(value desc, idx asc)`` order which doesn't match aten's small-K + CUDA kernel - same gather invariant though. + + * Fused radix-select (larger K): K in {64, 128, 256, 512, 1024}. + Four radix byte passes over smem histograms, then a cooperative + bitonic sort of the K survivors. Two phase-2/phase-3 specialisations: + - Deterministic (under ``torch.use_deterministic_algorithms``): + block-wide prefix-sum gather + lex ``(ord, -idx)`` sort. + Bit-exact match to aten on values and indices. + - Non-deterministic: smem atomic-counter gather + ord-only sort. + Faster (~5-10%); indices may differ across runs on threshold ties. + +Common eligibility (see ``_cond``): + - fp32 input, CUDA, not COW + - ``largest=True``, ``sorted=True`` + - reducing over the last axis, ``self`` contiguous (2D flatten is a view) + - row count at least one full wave of SMs (perf gate) + +Per-kernel additional eligibility: + - register: K in {16, 32}, N pow2 in supported range above + - radix: K in {64, 128, 256, 512, 1024}, ``N >= MIN_N_MULT[k] * k``, + ``N % 4 == 0`` (128-bit vector loads) + +Anything else falls through to aten. +""" + +import functools +import math + +import torch + +from ... import cutedsl_utils as cu +from ._common import ( + any_cow, + flatten_last_dim, + last_dim_row_major_ok, + unflatten_last_dim, +) + + +_RADIX_KS: frozenset[int] = frozenset({64, 128, 256, 512, 1024}) +_REGISTER_KS: frozenset[int] = frozenset({16, 32}) +_SUPPORTED_KS: frozenset[int] = _RADIX_KS | _REGISTER_KS + +# Per-K minimum N for the radix kernel below which aten wins on B200. +# At low N the radix sweep (4 passes + gather) has too many passes over +# too little data to beat aten's launch-bound multi-pass kernel. +# K=512 needs ~8*K, K=1024 needs ~32*K because their smem footprint +# drops occupancy. +_RADIX_MIN_N_MULTIPLIER: dict[int, int] = { + 64: 2, + 128: 2, + 256: 2, + 512: 8, + 1024: 32, +} + +# Register kernel per-K (min, max) N range, both bounds powers of 2. +# Below the min, VEC = N/32 is too small (most lanes idle, bitonic +# overhead dominates) and aten wins at large M. Above the max, radix +# (K=32) or aten (K=16 N>2048) takes over. +# Tuned on B200: K=16 wins down to N=64 across all M; K=32 only beats +# both aten and radix at exactly N=256. +_REGISTER_N_RANGE: dict[int, tuple[int, int]] = { + 16: (64, 2048), + 32: (256, 256), +} + + +def _is_pow2(x: int) -> bool: + return x > 0 and (x & (x - 1)) == 0 + + +def _kernel_for(k: int, n: int) -> str | None: + """Pick the kernel for (K, N): "register", "radix", or None (aten).""" + if k in _REGISTER_KS: + n_min, n_max = _REGISTER_N_RANGE[k] + if _is_pow2(n) and n_min <= n <= n_max: + return "register" + if k in _RADIX_KS: + if n >= _RADIX_MIN_N_MULTIPLIER[k] * k and (n % 4) == 0: + return "radix" + return None + + +@functools.cache +def _min_rows_for_full_wave(device_idx: int) -> int: + """Row threshold below which the one-CTA-per-row kernel underutilises + the GPU. A full wave is SM-count CTAs; below that, aten's multi-CTA + kernel gets more parallelism out of the same rows and wins.""" + return torch.cuda.get_device_properties(device_idx).multi_processor_count + + +def _eligible( + self: torch.Tensor, k: int, dim: int, largest: bool, sorted_: bool +) -> bool: + if not self.is_cuda or self.dtype != torch.float32: + return False + if any_cow(self): + return False + if not largest or not sorted_: + return False + if not last_dim_row_major_ok(self, dim): + return False + N = self.shape[-1] if self.ndim >= 1 else 0 + if _kernel_for(k, N) is None: + return False + # Performance gate: reject shapes where aten is faster. One CTA per + # row (radix) or one warp per row (register) - either way row_count + # below SM_count leaves the GPU underutilised. + M = math.prod(self.shape[:-1]) if self.ndim >= 1 else 0 + if M < _min_rows_for_full_wave(self.device.index or 0): + return False + return True + + +def _cond( + self: torch.Tensor, + k: int, + dim: int = -1, + largest: bool = True, + sorted: bool = True, + *args, + **kwargs, +) -> bool: + return _eligible(self, int(k), int(dim), bool(largest), bool(sorted)) + + +def _out_cond( + self: torch.Tensor, + k: int, + dim: int = -1, + largest: bool = True, + sorted: bool = True, + *, + values: torch.Tensor, + indices: torch.Tensor, +) -> bool: + if not _cond(self, k, dim, largest, sorted): + return False + if any_cow(values, indices): + return False + expected_shape = self.shape[:-1] + (k,) + if values.dtype != torch.float32 or values.shape != expected_shape: + return False + if indices.dtype != torch.int64 or indices.shape != expected_shape: + return False + return True + + +def _run(self: torch.Tensor, k: int) -> tuple[torch.Tensor, torch.Tensor]: + from .cutedsl_kernels import topk_radix, topk_register + + self_2d = flatten_last_dim(self) + N = self_2d.shape[-1] + kernel = _kernel_for(k, N) + + def _launch() -> tuple[torch.Tensor, torch.Tensor]: + if kernel == "register": + return topk_register(self_2d, k) + # Pick the deterministic kernel under torch.use_deterministic_algorithms + # (kept off by default for perf; the non-det kernel still produces + # correct top-K values but indices may differ on ties). + deterministic = torch.are_deterministic_algorithms_enabled() + return topk_radix(self_2d, k, deterministic=deterministic) + + # The Python-native dispatch path does not get an automatic CUDA device + # guard before launching the kernel (unlike the generated C++ ATen path), + # so the CuTeDSL kernel runs on the current device's stream. Guard the + # launch when the input is not already on the current device, while leaving + # the common already-current path direct to avoid the context-manager + # overhead. See #187983 for the same fix on the bmm override. + device = self.get_device() + if device == torch.cuda.current_device(): + values_2d, indices_2d = _launch() + else: + with torch.cuda.device(device): + values_2d, indices_2d = _launch() + return unflatten_last_dim(values_2d, indices_2d, self, k) + + +def _impl( + self: torch.Tensor, + k: int, + dim: int = -1, + largest: bool = True, + sorted: bool = True, + *args, + **kwargs, +) -> tuple[torch.Tensor, torch.Tensor]: + return _run(self, int(k)) + + +def _out_impl( + self: torch.Tensor, + k: int, + dim: int = -1, + largest: bool = True, + sorted: bool = True, + *, + values: torch.Tensor, + indices: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + v, i = _run(self, int(k)) + values.copy_(v) + indices.copy_(i) + return values, indices + + +def register_to_dispatch() -> None: + for op_symbol, cond, impl in ( + ("topk", _cond, _impl), + ("topk.values", _out_cond, _out_impl), + ): + cu.register_op_override( + "aten", + op_symbol, + "CUDA", + cond=cond, + impl=impl, + allow_multiple_override=True, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/cutedsl_kernels.py b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/cutedsl_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..6c85283d8822435b1c96979dde0f0bf7cc1a67ba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/ops/topk/cutedsl_kernels.py @@ -0,0 +1,874 @@ +"""CuTeDSL fp32 top-K kernels. + +Two kernels live here, picked by K and N in ``cutedsl_impl.py``: + +``topk_radix`` - fused radix-select for K in {64,128,256,512,1024}. +Layout per CTA (one row): + * Phase 1 - four radix byte passes (MSB to LSB) build shared-memory + histograms via smem atomic-add; thread 0 scans descending to locate + the bin that contains the k-th-largest ordinal. + * Phase 2 - gather elements at-or-above the radix threshold. Two + specialisations selected by the ``deterministic`` constexpr: + - True: per-step block-wide exclusive prefix sums hand each + thread an exact write slot, eq-tied elements stage in a side + buffer; first ``remaining_k`` of them are appended in input + order. Stable across runs. + - False: smem atomic counters claim slots on the fly. Cheaper + but indices on threshold ties depend on atomic resolution + order. + * Phase 3 - cooperative bitonic sort descending. Block size is + ``max(K, 256)``; K threads own one element each, the rest sit the + sort out but still reach every barrier. Comparator is lex + ``(ord, -idx)`` (deterministic) or ord-only (non-deterministic). + * Phase 4 - write (values, indices) to global memory. + +``topk_register`` - register-resident top-K for K in {16, 32} with +N a power of 2 in [K, 2048]. Each warp owns one row; ``ROWS_PER_CTA`` +warps share a CTA. Per-thread VEC = N/32 elements held in registers, +encoded as Int64 ``(ord << 32) | ~idx`` keys so a descending sort gives +``(value desc, idx asc)`` matching aten. Local bitonic sort, then a +warp-cooperative bitonic-topk merge across butterfly partners. No smem, +no global staging - only the final K writes hit gmem. Bit-exact to aten. + +Both kernels do one launch; only loads/stores of the input and final +outputs hit global memory. +""" + +import math + +import cuda.bindings.driver as cuda # pyrefly: ignore[missing-import] + +import cutlass +import cutlass.cute as cute +from cutlass import const_expr, Float32, Int32, Int64 +from cutlass._mlir.dialects import llvm +from cutlass.cutlass_dsl import dsl_user_op, T + +import torch +from torch._native.instrumentation import instrumented_cutedsl_cache + + +_NEG_INF_BITS: int = 0xFF800000 +_N_HIST_BINS: int = 256 + + +def _num_threads_for_k(k: int) -> int: + """Pick block size for a given K. + + Bitonic sort in phase 3 assigns one element per thread, so we need + at least K threads. Using ``max(K, _N_HIST_BINS)`` keeps the phase-1 + histogram-zero loop one-shot for small K while letting K grow up to + the CUDA 1024-thread cap. + """ + return max(k, _N_HIST_BINS) + + +@dsl_user_op +def _elem_ptr(x: cute.Tensor, coord, *, loc=None, ip=None) -> cute.Pointer: + return x.iterator + cute.crd2idx(coord, x.layout, loc=loc, ip=ip) + + +@dsl_user_op +def _bitcast_f32_to_i32(val, *, loc=None, ip=None) -> Int32: + return Int32(llvm.bitcast(T.i32(), Float32(val).ir_value())) + + +@dsl_user_op +def _bitcast_i32_to_f32(val, *, loc=None, ip=None) -> Float32: + return Float32(llvm.bitcast(T.f32(), Int32(val).ir_value())) + + +@cute.jit +def _f32_to_radix_ord(val: Float32) -> Int32: + """Map fp32 to a monotone Int32 ordinal whose unsigned MSB->LSB byte + order matches descending fp32 order. Negatives invert all bits; + non-negatives keep their bits. With the byte-0 xor of 0x80 (applied + at the histogram-bin level), this gives a total order suitable for + MSB-first radix select. + + NaN of either sign maps to 0x7FFFFFFF (the largest ordinal under the + byte-0 xor), matching aten's TopKTypeConfig behaviour: NaN + sorts at the very top of largest-first topk regardless of sign. + """ + bits = _bitcast_f32_to_i32(val) + ord_ = bits ^ ((bits >> Int32(31)) & Int32(0x7FFFFFFF)) + # NaN detection: bits with all-ones exponent and non-zero mantissa. + # Equivalent to ``val != val``, but the DSL doesn't expose that + # comparator; the bit test is exact for IEEE-754 fp32. + is_nan = (bits & Int32(0x7FFFFFFF)) > Int32(0x7F800000) + return Int32(0x7FFFFFFF) if is_nan else ord_ + + +def _smem_scalar(smem: cutlass.utils.SmemAllocator, dtype) -> cute.Tensor: + """Allocate a single-element smem tensor (scalar bookkeeping slot).""" + return smem.allocate_tensor(dtype, cute.make_layout((1,)), byte_alignment=4) + + +@cute.jit +def _load_vec_f32(ptr: cute.Pointer, vec_elems: cutlass.Constexpr) -> cute.Tensor: + """Vectorized gmem -> rmem load of ``vec_elems`` contiguous fp32. + + Cute picks the widest safe instruction (e.g. LDG.128 for a 4-wide + fp32 tile) from the static shape. + """ + gsrc = cute.make_tensor(ptr, cute.make_layout(vec_elems)) + rvals = cute.make_rmem_tensor(vec_elems, Float32) + cute.autovec_copy(gsrc, rvals) + return rvals + + +@cute.jit +def _warp_inclusive_prefix(val: Int32, lane: Int32) -> Int32: + """Inclusive Hillis-Steele prefix sum across a single warp.""" + for i in cutlass.range_constexpr(int(math.log2(cute.arch.WARP_SIZE))): + offset = 1 << i + # mask_and_clamp=0 so lanes < offset get 0 (no contribution). + partial = cute.arch.shuffle_sync_up(val, offset=offset, mask_and_clamp=0) + if lane >= Int32(offset): + val = val + partial + return val + + +@cute.jit +def _block_excl_prefix_i32( + val: Int32, + scratch: cute.Tensor, + lane: Int32, + warp: Int32, + num_warps: cutlass.Constexpr, +) -> tuple[Int32, Int32]: + """Block-wide exclusive prefix sum over per-thread ``val``. + + Returns ``(excl_pfx, total)``: ``excl_pfx`` is this thread's + exclusive prefix; ``total`` is the sum across all threads in the + block. ``scratch`` must have at least ``num_warps + 1`` Int32 slots + and is clobbered. + + Implementation: warp-level Hillis-Steele scan, then warp 0 scans + the per-warp totals to produce per-warp offsets, then add. + """ + WARP_SIZE = const_expr(cute.arch.WARP_SIZE) + # Step 1: per-warp inclusive scan. + incl = _warp_inclusive_prefix(val, lane) + excl_intra = incl - val + # Step 2: last lane in each warp publishes warp's inclusive total. + if lane == Int32(WARP_SIZE - 1): + scratch[warp] = incl + cute.arch.barrier() + # Step 3: warp 0 prefix-sums the per-warp totals. + if warp == Int32(0): + warp_val = Int32(0) + if lane < Int32(num_warps): + warp_val = scratch[lane] + warp_incl = _warp_inclusive_prefix(warp_val, lane) + warp_excl = warp_incl - warp_val + if lane < Int32(num_warps): + scratch[lane] = warp_excl + # Stash the block total in a slot beyond the per-warp set so + # other warps can read it without a second reduction. + if lane == Int32(num_warps - 1): + scratch[num_warps] = warp_incl + cute.arch.barrier() + excl_pfx = scratch[warp] + excl_intra + total = scratch[num_warps] + cute.arch.barrier() # let everyone consume scratch before next call + return excl_pfx, total + + +class _RadixSelectTopK: + """One-CTA-per-row fused radix-select + bitonic sort. + + ``N``, ``K`` and ``deterministic`` are specialised at compile time: + the JIT cache keys on ``(N, K, deterministic)`` so a row-length or + determinism-mode change forces a recompile. + + When ``deterministic`` is True, phase 2 uses block-wide prefix-sum + scans for input-stable gather and phase 3's bitonic comparator uses + a lex ``(ord, -idx)`` key. Output matches aten bit-exactly. + + When ``deterministic`` is False, phase 2 uses smem atomic counters + for the gather and phase 3 sorts by ord-only. Faster (no extra smem + bookkeeping, no per-step block barrier on the gather), but ties at + the threshold radix bin are resolved non-deterministically and + indices may differ across runs. + """ + + VEC: int = 4 + + def __init__(self, N: int, K: int, deterministic: bool = True): + self.N = N + self.K = K + self.deterministic = deterministic + self.NUM_THREADS = _num_threads_for_k(K) + self.NUM_STAGES = int(math.log2(K)) + TILE = self.NUM_THREADS * self.VEC + self.VEC_ITERS = N // TILE + self.VEC_TAIL_START = self.VEC_ITERS * TILE + self.SCALAR_TAIL_ITERS = ( + N - self.VEC_TAIL_START + self.NUM_THREADS - 1 + ) // self.NUM_THREADS + + @cute.jit + def __call__( + self, + mX: cute.Tensor, + mValues: cute.Tensor, + mIndices: cute.Tensor, + stream: cuda.CUstream, + ): + M = mX.shape[0] + self.kernel(mX, mValues, mIndices).launch( + grid=[M, 1, 1], + block=[self.NUM_THREADS, 1, 1], + stream=stream, + ) + + @cute.kernel + def kernel(self, mX: cute.Tensor, mValues: cute.Tensor, mIndices: cute.Tensor): + tidx, _, _ = cute.arch.thread_idx() + row, _, _ = cute.arch.block_idx() + + N = const_expr(self.N) + K = const_expr(self.K) + NT = const_expr(self.NUM_THREADS) + VEC = const_expr(self.VEC) + VEC_ITERS = const_expr(self.VEC_ITERS) + VEC_TAIL_START = const_expr(self.VEC_TAIL_START) + SCALAR_TAIL_ITERS = const_expr(self.SCALAR_TAIL_ITERS) + N_HIST_BINS = const_expr(_N_HIST_BINS) + + smem = cutlass.utils.SmemAllocator() + s_hist = smem.allocate_tensor( + Int32, cute.make_layout((256,)), byte_alignment=16 + ) + s_prefix = _smem_scalar(smem, Int32) + s_mask = _smem_scalar(smem, Int32) + s_rem_k = _smem_scalar(smem, Int32) + # Phase-2 bookkeeping. Non-deterministic gather uses two + # atomic-add counters; deterministic gather carries running + # totals in registers. + s_write_ctr = _smem_scalar(smem, Int32) + s_eq_ctr = _smem_scalar(smem, Int32) + s_vals = smem.allocate_tensor( + Float32, cute.make_layout((K,)), byte_alignment=16 + ) + s_ords = smem.allocate_tensor(Int32, cute.make_layout((K,)), byte_alignment=16) + s_idxs = smem.allocate_tensor(Int32, cute.make_layout((K,)), byte_alignment=16) + # Side buffer for equal-threshold elements (deterministic gather only). + # Always allocated to keep the smem layout straightforward; + # measurements show no occupancy benefit from making it conditional. + s_eq_vals = smem.allocate_tensor( + Float32, cute.make_layout((K,)), byte_alignment=16 + ) + s_eq_idxs = smem.allocate_tensor( + Int32, cute.make_layout((K,)), byte_alignment=16 + ) + + if tidx == 0: + s_prefix[0] = Int32(0) + s_mask[0] = Int32(0) + s_rem_k[0] = Int32(K) + cute.arch.barrier() + + # Phase 1: four radix byte passes, MSB to LSB. + for byte_pos in cutlass.range_constexpr(4): + shift = (3 - byte_pos) * 8 + xor_val = 128 if byte_pos == 0 else 0 + + # Zero the 256-bin histogram. When NT > 256 (e.g. K=1024) only + # the first 256 threads participate; the histogram is always + # exactly 256 bins regardless of K. + if tidx < N_HIST_BINS: + s_hist[tidx] = Int32(0) + cute.arch.barrier() + + prefix = s_prefix[0] + decided_mask = s_mask[0] + + if byte_pos == 0: + # First pass: decided_mask==0, every element participates. + for step in cutlass.range(VEC_ITERS): + base = step * NT * VEC + tidx * VEC + rvals = _load_vec_f32(_elem_ptr(mX, (row, base)), VEC) + for vi in cutlass.range_constexpr(self.VEC): + ords = _f32_to_radix_ord(rvals[vi]) + byte_val = ((ords >> Int32(shift)) & Int32(255)) ^ Int32( + xor_val + ) + cute.arch.atomic_add(_elem_ptr(s_hist, byte_val), Int32(1)) + for step in cutlass.range(SCALAR_TAIL_ITERS): + idx = VEC_TAIL_START + step * NT + tidx + if idx < N: + ords = _f32_to_radix_ord(mX[row, idx]) + byte_val = ((ords >> Int32(shift)) & Int32(255)) ^ Int32( + xor_val + ) + cute.arch.atomic_add(_elem_ptr(s_hist, byte_val), Int32(1)) + else: + for step in cutlass.range(VEC_ITERS): + base = step * NT * VEC + tidx * VEC + rvals = _load_vec_f32(_elem_ptr(mX, (row, base)), VEC) + for vi in cutlass.range_constexpr(self.VEC): + ords = _f32_to_radix_ord(rvals[vi]) + if (ords & decided_mask) == prefix: + byte_val = ((ords >> Int32(shift)) & Int32(255)) ^ Int32( + xor_val + ) + cute.arch.atomic_add(_elem_ptr(s_hist, byte_val), Int32(1)) + for step in cutlass.range(SCALAR_TAIL_ITERS): + idx = VEC_TAIL_START + step * NT + tidx + if idx < N: + ords = _f32_to_radix_ord(mX[row, idx]) + if (ords & decided_mask) == prefix: + byte_val = ((ords >> Int32(shift)) & Int32(255)) ^ Int32( + xor_val + ) + cute.arch.atomic_add(_elem_ptr(s_hist, byte_val), Int32(1)) + cute.arch.barrier() + + # Thread 0 picks the bin that contains the k-th-largest. + if tidx == 0: + remaining_k = s_rem_k[0] + acc = Int32(0) + found = Int32(0) + sel_bin = Int32(0) + elems_above = Int32(0) + + for b in cutlass.range(256): + bin_idx = Int32(255) - b + count = s_hist[bin_idx] + if found == Int32(0): + if acc + count >= remaining_k: + sel_bin = bin_idx + elems_above = acc + found = Int32(1) + acc = acc + count + + actual_byte = sel_bin ^ Int32(xor_val) + s_prefix[0] = prefix | (actual_byte << Int32(shift)) + s_mask[0] = decided_mask | (Int32(255) << Int32(shift)) + s_rem_k[0] = remaining_k - elems_above + + cute.arch.barrier() + + # Phase 2: gather elements at-or-above the radix threshold. + # Two implementations selected at compile time: + # * Deterministic: per-step block-wide exclusive prefix sums + # give each thread an exact write slot; eq-threshold ties + # stage in a side buffer and the first ``remaining_k`` get + # appended in input-index order. + # * Non-deterministic: smem atomic counters claim slots on + # the fly. Faster but tied elements at the threshold bin + # are picked in atomic-resolution order. + threshold = s_prefix[0] + remaining_k = s_rem_k[0] + + if tidx == 0: + s_write_ctr[0] = Int32(0) + s_eq_ctr[0] = Int32(0) + if tidx < K: + s_vals[tidx] = _bitcast_i32_to_f32(Int32(_NEG_INF_BITS)) + s_idxs[tidx] = Int32(0) + cute.arch.barrier() + + if const_expr(self.deterministic): + WARP_SIZE = const_expr(cute.arch.WARP_SIZE) + NUM_WARPS = const_expr(NT // WARP_SIZE) + lane_idx = tidx % Int32(WARP_SIZE) + warp_idx = tidx // Int32(WARP_SIZE) + + # --- Vec + scalar tail (deterministic) --- + # Pack (n_above, n_eq) into a single Int32 as (high16, low16) so + # we can run one block-wide prefix sum per step instead of two. + # Per-step bounds: above+eq counts <= VEC*NT = 4*1024 = 4096, + # comfortably below 2^16; the sums share no bits so the low-half + # never carries into the high half. + # + # Carry the running bases in registers (every thread has + # ``packed_step_total`` from the scan) instead of going through + # smem each step. + above_base = Int32(0) + eq_base = Int32(0) + for step in cutlass.range(VEC_ITERS): + base = step * NT * VEC + tidx * VEC + rvals = _load_vec_f32(_elem_ptr(mX, (row, base)), VEC) + + # Hoist per-element classification into per-lane registers + # so the count pass and write pass don't redo the radix-ord + # transform and threshold compare. + # Class encoding: 2 = above, 1 = eq, 0 = below. + cls_reg = cute.make_rmem_tensor(VEC, Int32) + packed_local = Int32(0) + for vi in cutlass.range_constexpr(self.VEC): + o = _f32_to_radix_ord(rvals[vi]) + if o > threshold: + cls_reg[vi] = Int32(2) + packed_local = packed_local + Int32(1 << 16) + elif o == threshold: + cls_reg[vi] = Int32(1) + packed_local = packed_local + Int32(1) + else: + cls_reg[vi] = Int32(0) + + # Block-wide exclusive prefix sum. ``s_hist`` is reused as + # scratch for the warp-total scan (Phase 1 is done with it). + packed_pfx, packed_step_total = _block_excl_prefix_i32( + packed_local, s_hist, lane_idx, warp_idx, NUM_WARPS + ) + above_pfx = packed_pfx >> Int32(16) + eq_pfx = packed_pfx & Int32(0xFFFF) + + # Per-thread write offsets within this step. + my_above = above_base + above_pfx + my_eq = eq_base + eq_pfx + for vi in cutlass.range_constexpr(self.VEC): + val_f32 = rvals[vi] + cls = cls_reg[vi] + idx = base + Int32(vi) + if cls == Int32(2): + if my_above < Int32(K): + s_vals[my_above] = val_f32 + s_idxs[my_above] = Int32(idx) + my_above = my_above + Int32(1) + elif cls == Int32(1): + if my_eq < remaining_k: + s_eq_vals[my_eq] = val_f32 + s_eq_idxs[my_eq] = Int32(idx) + my_eq = my_eq + Int32(1) + + # Advance running bases. Cap eq at remaining_k - we never + # need more. All threads update in registers; no smem. + above_base = above_base + (packed_step_total >> Int32(16)) + eq_base = min( + remaining_k, eq_base + (packed_step_total & Int32(0xFFFF)) + ) + + # --- Scalar tail --- + for step in cutlass.range(SCALAR_TAIL_ITERS): + idx = VEC_TAIL_START + step * NT + tidx + valid = idx < N + packed_local = Int32(0) + if valid: + ords = _f32_to_radix_ord(mX[row, idx]) + if ords > threshold: + packed_local = Int32(1 << 16) + elif ords == threshold: + packed_local = Int32(1) + + packed_pfx, packed_step_total = _block_excl_prefix_i32( + packed_local, s_hist, lane_idx, warp_idx, NUM_WARPS + ) + above_pfx = packed_pfx >> Int32(16) + eq_pfx = packed_pfx & Int32(0xFFFF) + + my_above = above_base + above_pfx + my_eq = eq_base + eq_pfx + if valid: + val_f32 = mX[row, idx] + ords = _f32_to_radix_ord(val_f32) + if ords > threshold: + if my_above < Int32(K): + s_vals[my_above] = val_f32 + s_idxs[my_above] = Int32(idx) + elif ords == threshold: + if my_eq < remaining_k: + s_eq_vals[my_eq] = val_f32 + s_eq_idxs[my_eq] = Int32(idx) + + above_base = above_base + (packed_step_total >> Int32(16)) + eq_base = min( + remaining_k, eq_base + (packed_step_total & Int32(0xFFFF)) + ) + + # The eq-merge below has each thread read s_eq_vals[tidx - n_above], + # i.e. a slot written by some other thread during the gather above. + # The last barrier inside _block_excl_prefix_i32 fires *before* the + # final per-step writes to s_eq_vals, so cross-thread visibility of + # those writes isn't guaranteed without a fresh barrier here. + cute.arch.barrier() + + # Append eq-bucket survivors after the above-bucket ones to + # fill ``s_vals`` / ``s_idxs`` to exactly K entries. + n_above = above_base + if tidx < K: + offset_into_eq = Int32(tidx) - n_above + if offset_into_eq >= Int32(0) and offset_into_eq < remaining_k: + s_vals[tidx] = s_eq_vals[offset_into_eq] + s_idxs[tidx] = s_eq_idxs[offset_into_eq] + cute.arch.barrier() + else: + # Non-deterministic atomic-counter gather. + for step in cutlass.range(VEC_ITERS): + base = step * NT * VEC + tidx * VEC + rvals = _load_vec_f32(_elem_ptr(mX, (row, base)), VEC) + for vi in cutlass.range_constexpr(self.VEC): + val_f32 = rvals[vi] + idx = base + Int32(vi) + ords = _f32_to_radix_ord(val_f32) + if ords > threshold: + pos = cute.arch.atomic_add(_elem_ptr(s_write_ctr, 0), Int32(1)) + if pos < Int32(K): + s_vals[pos] = val_f32 + s_idxs[pos] = Int32(idx) + elif ords == threshold: + eq_pos = cute.arch.atomic_add(_elem_ptr(s_eq_ctr, 0), Int32(1)) + if eq_pos < remaining_k: + pos = cute.arch.atomic_add( + _elem_ptr(s_write_ctr, 0), Int32(1) + ) + if pos < Int32(K): + s_vals[pos] = val_f32 + s_idxs[pos] = Int32(idx) + for step in cutlass.range(SCALAR_TAIL_ITERS): + idx = VEC_TAIL_START + step * NT + tidx + if idx < N: + val_f32 = mX[row, idx] + ords = _f32_to_radix_ord(val_f32) + if ords > threshold: + pos = cute.arch.atomic_add(_elem_ptr(s_write_ctr, 0), Int32(1)) + if pos < Int32(K): + s_vals[pos] = val_f32 + s_idxs[pos] = Int32(idx) + elif ords == threshold: + eq_pos = cute.arch.atomic_add(_elem_ptr(s_eq_ctr, 0), Int32(1)) + if eq_pos < remaining_k: + pos = cute.arch.atomic_add( + _elem_ptr(s_write_ctr, 0), Int32(1) + ) + if pos < Int32(K): + s_vals[pos] = val_f32 + s_idxs[pos] = Int32(idx) + cute.arch.barrier() + + # Phase 3: cooperative bitonic sort (descending) on a composite + # ``(ord, ~idx)`` Int64 key so equal-value entries break ties by + # input index, matching aten's stable ordering. + # K lanes own one element each; lanes >= K clamp their smem + # index to a dummy slot so they can participate in barriers + # without OOB reads/writes. The writes from those lanes are + # discarded via the `tidx < K` guard on the store. + sort_tidx = tidx if tidx < Int32(K) else Int32(0) + if tidx < K: + s_ords[tidx] = _f32_to_radix_ord(s_vals[sort_tidx]) + cute.arch.barrier() + + for stage in cutlass.range_constexpr(self.NUM_STAGES): + for sub_rev in cutlass.range_constexpr(stage + 1): + sub = stage - sub_rev + step_size = 1 << sub + + # Snapshot both participants before the barrier; after the + # barrier the other thread may have overwritten its slot, + # so we must read our own ord now. Inactive lanes clamp + # their partner index to 0 (a safe in-bounds read) - their + # resulting comparisons are discarded by the store guard. + partner = (tidx ^ Int32(step_size)) if tidx < Int32(K) else Int32(0) + my_o = s_ords[sort_tidx] + my_i = s_idxs[sort_tidx] + p_o = s_ords[partner] + p_v = s_vals[partner] + p_i = s_idxs[partner] + cute.arch.barrier() + + # Comparator. Deterministic mode uses a lex + # ``(ord, -idx)`` tie-break so equal-ord entries land in + # ascending-idx order (matching aten). Non-deterministic + # mode skips the tiebreak (cheaper compare-exchange). + if const_expr(self.deterministic): + self_lt_partner = (my_o < p_o) or (my_o == p_o and my_i > p_i) + self_gt_partner = (my_o > p_o) or (my_o == p_o and my_i < p_i) + else: + self_lt_partner = my_o < p_o + self_gt_partner = my_o > p_o + block_dir = (tidx >> Int32(stage + 1)) & Int32(1) + if tidx < K: + if tidx < partner: + if block_dir == Int32(0): + if self_lt_partner: + s_ords[tidx] = p_o + s_vals[tidx] = p_v + s_idxs[tidx] = p_i + else: + if self_gt_partner: + s_ords[tidx] = p_o + s_vals[tidx] = p_v + s_idxs[tidx] = p_i + else: + if block_dir == Int32(0): + if self_gt_partner: + s_ords[tidx] = p_o + s_vals[tidx] = p_v + s_idxs[tidx] = p_i + else: + if self_lt_partner: + s_ords[tidx] = p_o + s_vals[tidx] = p_v + s_idxs[tidx] = p_i + cute.arch.barrier() + + # Phase 4: results to gmem. + if tidx < K: + mValues[row, tidx] = s_vals[tidx] + mIndices[row, tidx] = s_idxs[tidx] + + +def _make_fake_tensor(dtype, shape, divisibility=1): + stride = tuple( + cute.sym_int64(divisibility=divisibility) if i != len(shape) - 1 else 1 + for i in range(len(shape)) + ) + return cute.runtime.make_fake_tensor( + dtype, + shape, + stride=stride, + assumed_align=divisibility * dtype.width // 8, + ) + + +@instrumented_cutedsl_cache( + "aten::topk", + key_fn=lambda N, K, deterministic: f"radix N={N} K={K} det={deterministic}", +) +def _compile_topk_radix(N: int, K: int, deterministic: bool): + batch_sym = cute.sym_int() + div_n = math.gcd(4, N) + div_k = math.gcd(4, K) + x_fake = _make_fake_tensor(Float32, (batch_sym, N), div_n) + v_fake = _make_fake_tensor(Float32, (batch_sym, K), div_k) + i_fake = _make_fake_tensor(Int32, (batch_sym, K), div_k) + return cute.compile( + _RadixSelectTopK(N, K, deterministic=deterministic), + x_fake, + v_fake, + i_fake, + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + + +def topk_radix( + x: torch.Tensor, k: int, *, deterministic: bool = True +) -> tuple[torch.Tensor, torch.Tensor]: + """Fused radix-select top-K for fp32 2D contiguous ``x``. + + Returns ``(values[M, K]: fp32, indices[M, K]: int64)`` with K sorted + descending per row. Caller must ensure ``k`` is in the supported set + (see ``cutedsl_impl.py``) and ``N % 4 == 0``. + + ``deterministic`` controls the gather + sort tie-breaking strategy: + True (default) uses prefix-sum gather + lex comparator and matches + aten bit-exactly; False uses smem atomic gather + ord-only sort and + is faster but indices may differ on ties. + """ + M, N = x.shape + out_v = torch.empty(M, k, dtype=torch.float32, device=x.device) + # Kernel writes int32 indices; widen before returning to match aten. + out_i_i32 = torch.empty(M, k, dtype=torch.int32, device=x.device) + _compile_topk_radix(N, k, deterministic)(x, out_v, out_i_i32) + return out_v, out_i_i32.to(torch.int64) + + +# --------------------------------------------------------------------------- +# Register-resident top-K (small K, small N). +# --------------------------------------------------------------------------- + + +@cute.jit +def _make_key(val: Float32, idx: Int32) -> Int64: + """Compose the descending-sort key: ``(ord_u32 << 32) | (~idx_u32)``. + + Sorting this Int64 descending gives ``(value desc, idx asc)`` - + exactly aten's tie-break order. Real fp32 inputs (no NaN) keep keys + away from INT64_MIN, leaving that bit pattern free as a sentinel. + """ + ord32 = _f32_to_radix_ord(val) + ord64 = Int64(ord32) & Int64(0xFFFFFFFF) + inv_idx64 = Int64(~idx) & Int64(0xFFFFFFFF) + return (ord64 << Int64(32)) | inv_idx64 + + +@cute.jit +def _decode_key(key: Int64) -> tuple[Float32, Int32]: + ord32 = Int32(key >> Int64(32)) + inv_idx = Int32(key & Int64(0xFFFFFFFF)) + val_bits = ord32 ^ ((ord32 >> Int32(31)) & Int32(0x7FFFFFFF)) + return Float32(llvm.bitcast(T.f32(), val_bits.ir_value())), ~inv_idx + + +@cute.jit +def _cas_desc(arr: cute.Tensor, i: cutlass.Constexpr, j: cutlass.Constexpr) -> None: + a = arr[i] + b = arr[j] + if a < b: + arr[i] = b + arr[j] = a + + +@cute.jit +def _bitonic_sort_desc(arr: cute.Tensor, n: cutlass.Constexpr) -> None: + if const_expr(n > 1): + num_stages = int(math.log2(n)) + for s in cutlass.range_constexpr(num_stages): + for sub_rev in cutlass.range_constexpr(s + 1): + step = 1 << (s - sub_rev) + for i in cutlass.range_constexpr(n): + j = i ^ step + if j > i: + block_dir = (i >> (s + 1)) & 1 + if block_dir == 0: + _cas_desc(arr, i, j) + else: + a = arr[i] + b = arr[j] + if a > b: + arr[i] = b + arr[j] = a + + +@cute.jit +def _bitonic_merge_desc(arr: cute.Tensor, n: cutlass.Constexpr) -> None: + """Merge a bitonic sequence of length n into descending sorted.""" + if const_expr(n > 1): + num_levels = int(math.log2(n)) + for level in cutlass.range_constexpr(num_levels): + length = n >> level + step = length // 2 + for i in cutlass.range_constexpr(n // length): + start_i = i * length + for j in cutlass.range_constexpr(step): + _cas_desc(arr, start_i + j, start_i + j + step) + + +@cute.jit +def _topk_merge_desc(a: cute.Tensor, b: cute.Tensor, K: cutlass.Constexpr) -> None: + """Top-K of two K-sorted-descending sequences, in place into ``a``. + + ``a[i] <- max(a[i], b[K-1-i])`` yields a bitonic sequence in ``a``; + one bitonic merge of length K finishes it. + """ + for i in cutlass.range_constexpr(K): + x = a[i] + y = b[K - 1 - i] + if y > x: + a[i] = y + _bitonic_merge_desc(a, K) + + +class _RegisterTopK: + """Register-resident top-K. Each warp owns one row; ``ROWS_PER_CTA`` + warps per CTA. K in {16, 32}, N a power of 2 in [K, 2048]. + """ + + def __init__(self, N: int, K: int, rows_per_cta: int = 4): + self.N = N + self.K = K + self.VEC = N // 32 + self.ROWS_PER_CTA = rows_per_cta + self.NUM_THREADS = 32 * rows_per_cta + + @cute.jit + def __call__( + self, + mX: cute.Tensor, + mValues: cute.Tensor, + mIndices: cute.Tensor, + stream: cuda.CUstream, + ): + M = mX.shape[0] + ROWS = const_expr(self.ROWS_PER_CTA) + num_blocks = (M + ROWS - 1) // ROWS + self.kernel(mX, mValues, mIndices).launch( + grid=[num_blocks, 1, 1], + block=[self.NUM_THREADS, 1, 1], + stream=stream, + ) + + @cute.kernel + def kernel(self, mX: cute.Tensor, mValues: cute.Tensor, mIndices: cute.Tensor): + tidx, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + + K = const_expr(self.K) + VEC = const_expr(self.VEC) + ROWS = const_expr(self.ROWS_PER_CTA) + WARP_SIZE = const_expr(cute.arch.WARP_SIZE) + + warp_idx = tidx // Int32(WARP_SIZE) + lane_idx = tidx % Int32(WARP_SIZE) + row = Int32(bidx) * Int32(ROWS) + warp_idx + + M = mX.shape[0] + # CuTeDSL can't early-return on a dynamic predicate. Clamp the row + # for loads to keep them in-bounds, and gate the writes only. + row_safe = row if row < M else Int32(0) + in_bounds = row < M + + # Per-thread Int64 keys covering this row's VEC-sized stripe. + keys = cute.make_rmem_tensor(VEC, Int64) + for i in cutlass.range_constexpr(VEC): + col = lane_idx * Int32(VEC) + Int32(i) + keys[i] = _make_key(mX[row_safe, col], col) + + _bitonic_sort_desc(keys, VEC) + + # Build per-thread top-K. If VEC < K, pad with INT64_MIN so the + # sentinel sorts strictly below any real key; if VEC >= K take the + # leading K (already sorted). + topk = cute.make_rmem_tensor(K, Int64) + if const_expr(VEC >= K): + for i in cutlass.range_constexpr(K): + topk[i] = keys[i] + else: + SENTINEL = const_expr(-(1 << 63)) + for i in cutlass.range_constexpr(VEC): + topk[i] = keys[i] + for i in cutlass.range_constexpr(K - VEC): + topk[VEC + i] = Int64(SENTINEL) + _bitonic_sort_desc(topk, K) + + # Warp-cooperative top-K merge via butterfly shuffles. + log2_warp = const_expr(int(math.log2(WARP_SIZE))) + for s in cutlass.range_constexpr(log2_warp): + other = cute.make_rmem_tensor(K, Int64) + for i in cutlass.range_constexpr(K): + other[i] = cute.arch.shuffle_sync_bfly(topk[i], offset=Int32(1 << s)) + _topk_merge_desc(topk, other, K) + + # Lane 0 of each warp now holds the row's top-K descending. + if lane_idx == Int32(0) and in_bounds: + for i in cutlass.range_constexpr(K): + v, idx = _decode_key(topk[i]) + mValues[row, i] = v + mIndices[row, i] = idx + + +@instrumented_cutedsl_cache("aten::topk", key_fn=lambda N, K: f"register N={N} K={K}") +def _compile_topk_register(N: int, K: int): + batch_sym = cute.sym_int() + div_n = math.gcd(4, N) + div_k = math.gcd(4, K) + x_fake = _make_fake_tensor(Float32, (batch_sym, N), div_n) + v_fake = _make_fake_tensor(Float32, (batch_sym, K), div_k) + i_fake = _make_fake_tensor(Int32, (batch_sym, K), div_k) + return cute.compile( + _RegisterTopK(N, K), + x_fake, + v_fake, + i_fake, + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + + +def topk_register(x: torch.Tensor, k: int) -> tuple[torch.Tensor, torch.Tensor]: + """Register-resident top-K for fp32 2D contiguous ``x``. + + Returns ``(values[M, K]: fp32, indices[M, K]: int64)``, descending, + bit-exact to aten on both values and indices. Caller must ensure + ``k`` in {16, 32} and ``N`` is a power of 2 in [k, 2048]. + """ + M, N = x.shape + out_v = torch.empty(M, k, dtype=torch.float32, device=x.device) + out_i_i32 = torch.empty(M, k, dtype=torch.int32, device=x.device) + _compile_topk_register(N, k)(x, out_v, out_i_i32) + return out_v, out_i_i32.to(torch.int64) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/registry.py b/.venv/lib/python3.12/site-packages/torch/_native/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..4bf94fadd2ac7b1be3e5e2ae5d49b27fdda29d87 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/registry.py @@ -0,0 +1,1147 @@ +import logging +from collections.abc import Callable, Iterable +from dataclasses import dataclass, field +from typing import ParamSpec, TypeVar + +import torch.library + + +__all__ = [ + "UserOrderingFn", + "register_op_override", + "reorder_graphs_from_user_function", + "reenable_op_overrides", + "deregister_op_overrides", + "get_dsl_operations", + "native_decomp_table", +] + +log = logging.getLogger(__name__) + +P = ParamSpec("P") +R = TypeVar("R") + +_OpCondFn = Callable[P, bool] +_OpImplFn = Callable[P, R] + + +@dataclass +class _OverrideNode: + """Track function override data.""" + + dsl_name: str + op_symbol: str + dispatch_key: str + cond_fn: _OpCondFn + impl_fn: _OpImplFn + # Identifier of the opaque `_native::` op that carries this + # override's impl. Assigned once at registration time and never reused -- + # reorder / deregister / reenable do not change it, so the cached + # `_defined_native_ops` entry remains valid. + node_id: str + unconditional_override: bool = False + active: bool = True + + +UserOrderingFn = Callable[[str, str, list[_OverrideNode]], list[_OverrideNode]] + + +@dataclass +class _FilterState: + """Manages filtering state for override nodes.""" + + _dsl_names: set[str] = field(default_factory=set) + _op_symbols: set[str] = field(default_factory=set) + _dispatch_keys: set[str] = field(default_factory=set) + + def check_enabled(self, node: _OverrideNode) -> bool: + """ + Check if a node is enabled based on current filter state. + + Args: + node: The override node to check + + Returns: + bool: True if the node should be enabled, False if filtered out + """ + if node.dsl_name in self._dsl_names: + return False + + if node.op_symbol in self._op_symbols: + return False + + if node.dispatch_key in self._dispatch_keys: + return False + + return True + + def update( + self, + dsl_names: str | Iterable[str] | None, + op_symbols: str | Iterable[str] | None, + dispatch_keys: str | Iterable[str] | None, + remove_keys: bool = False, + ) -> None: + """ + Update filter sets as (current | new) or (current ~ new). + + Args: + dsl_names: DSL names to add/remove from filter + op_symbols: Operation symbols to add/remove from filter + dispatch_keys: Dispatch keys to add/remove from filter + remove_keys: If True, remove keys from filter; if False, add them + + Note: + Uses set.discard as it doesn't raise an exception if the element + wasn't in the set to begin with. + """ + if remove_keys: + self._dsl_names -= set(_resolve_iterable(dsl_names)) + self._op_symbols -= set(_resolve_iterable(op_symbols)) + self._dispatch_keys -= set(_resolve_iterable(dispatch_keys)) + else: + self._dsl_names |= set(_resolve_iterable(dsl_names)) + self._op_symbols |= set(_resolve_iterable(op_symbols)) + self._dispatch_keys |= set(_resolve_iterable(dispatch_keys)) + + def build_disable_key_set(self) -> set[tuple[str, str]]: + """ + Build a set of dictionary keys based on the current filter state. + + Returns: + set[tuple[str, str]]: Set of (op_symbol, dispatch_key) tuples + """ + return _build_key_set( + self._dsl_names, + self._op_symbols, + self._dispatch_keys, + ) + + def __str__(self) -> str: + """Return string representation of filter state.""" + s = "" + s += "Filter State:\n" + s += " === DSL: ===\n" + for i, dsl in enumerate(self._dsl_names): + s += f" {i}: {dsl}\n" + s += " === OP SYMBOL: ===\n" + for i, op in enumerate(self._op_symbols): + s += f" {i}: {op}\n" + s += " === DISPATCH KEYS: ===\n" + for i, key in enumerate(self._dispatch_keys): + s += f" {i}: {key}\n" + + return s + + +# Store the global override filtering state +_filter_state: _FilterState = _FilterState() + +# Store torch.library.Library instances +_libs: dict[tuple[str, str], torch.library.Library] = {} + +# Decomposition-style routers for the compile / export path, keyed by aten +# OpOverload. Built in `_register_overrides_from_graph` alongside the eager +# `Library.impl` routers. +# +# This dict is *not* written into any global compile/export decomp table (in +# particular, not into torch._inductor.decomposition.decompositions). Users +# opt into the overrides explicitly by passing `native_decomp_table()` to +# `ExportedProgram.run_decompositions(...)`, or by threading it through +# Dynamo/Inductor config for `torch.compile`. Reasons: +# +# 1. torch._inductor.decomposition.decompositions is an Inductor internal +# with no stability guarantee; writing to it couples us to Inductor's +# refactors. +# 2. Global writes would affect *every* consumer of that table (tests, +# third-party backends, etc.), with no scoping. +# 3. Import-time writes would force `import torch._native` to also pull in +# inductor → dynamo → triton, breaking +# `test_no_dsl_imports_after_import_torch`. +# +# Keeping the table registry-local means `import torch._native` stays cheap +# and consumers control exactly when and where overrides take effect. +_native_decomp_overrides: dict[object, Callable] = {} + + +def _has_cow_tensor(*args, **kwargs) -> bool: + def is_cow_tensor(arg) -> bool: + if isinstance(arg, torch.Tensor): + return torch._C._is_cow_tensor(arg) # pyrefly: ignore[missing-attribute] + if isinstance(arg, (list, tuple)): + return any(is_cow_tensor(item) for item in arg) + if isinstance(arg, dict): + return any(is_cow_tensor(item) for item in arg.values()) + return False + + return any(is_cow_tensor(arg) for arg in args) or any( + is_cow_tensor(arg) for arg in kwargs.values() + ) + + +# store graph structures +_GraphsType = dict[tuple[str, str], list[_OverrideNode]] +_graphs: _GraphsType = {} + +_MappingType = dict[str, list[tuple[str, str]]] + +# map a {dsl, op, dispatch_key} to keys to all graphs that contain it +_dsl_name_to_lib_graph: _MappingType = {} +_dispatch_key_to_lib_graph: _MappingType = {} +_op_symbol_to_lib_graph: _MappingType = {} + +# Monotonic counter used to mint stable, unique `_native::` op names. +# Must never decrease across the process, since `_defined_native_ops` +# pins a fake kernel for each minted id. +_node_id_counter: int = 0 + +# Dispatch keys where installing an override would break the registry's +# assumptions. The eager router is wired at a backend key so aten's +# higher-priority Autograd/Autocast kernels handle those layers, and the +# fake kernel for `_native::` redispatches to the aten op's meta -- if +# the override lived at Meta or CompositeImplicitAutograd, that +# redispatch would loop back into the router. +_DISALLOWED_DISPATCH_KEYS: frozenset[str] = frozenset( + {"Meta", "CompositeImplicitAutograd", "CompositeExplicitAutograd"} +) + + +def _build_key_set( + dsl_names: str | Iterable[str] | None, + op_symbols: str | Iterable[str] | None, + dispatch_keys: str | Iterable[str] | None, +) -> set[tuple[str, str]]: + """ + Build a set of dictionary keys based on filter criteria. + + Args: + dsl_names: DSL names to include in key set + op_symbols: Operation symbols to include in key set + dispatch_keys: Dispatch keys to include in key set + + Returns: + set[tuple[str, str]]: Set of (op_symbol, dispatch_key) tuples + """ + key_set: set[tuple[str, str]] = set() + + def _append_to_set( + entries: str | Iterable[str] | None, graph_lib_dict: _MappingType + ) -> None: + """Helper to add matching keys from graph_lib_dict to key_set.""" + resolved_entries = _resolve_iterable(entries) + + for entry in resolved_entries: + if entry in graph_lib_dict: + for key in graph_lib_dict[entry]: + key_set.add(key) + + _append_to_set(dsl_names, _dsl_name_to_lib_graph) + _append_to_set(op_symbols, _op_symbol_to_lib_graph) + _append_to_set(dispatch_keys, _dispatch_key_to_lib_graph) + + return key_set + + +def _print_override_graphs(*, print_inactive: bool = False) -> None: + """ + Print all override graphs for debugging purposes. + + Args: + print_inactive: Whether to print inactive nodes + """ + for (op, key), node_list in _graphs.items(): + print(f"{op=}, {key=}") + + for i, node in enumerate(node_list): + if node.active or print_inactive: + s: str = f" {i}: {node.dsl_name=}, {node.unconditional_override=}" + if print_inactive: + s += f" {node.active=}" + + print(s) + + +# One DEF/FRAGMENT library per namespace -- only one is allowed per process. +_def_libs: dict[str, torch.library.Library] = {} +# Ops that have already been `define`d on the _native namespace. +_defined_native_ops: set[str] = set() +# IMPL libraries on the aten namespace, keyed by (op_symbol, dispatch_key). +# One library per op/key pair so we can call `_destroy()` on it to tear down +# just that one override without affecting other ops at the same dispatch +# key. Torch's Library has no per-kernel removal API -- `_destroy` on the +# library is the only teardown mechanism. +_aten_override_libs: dict[tuple[str, str], torch.library.Library] = {} + + +def _get_def_library(namespace: str) -> torch.library.Library: + if namespace not in _def_libs: + _def_libs[namespace] = torch.library.Library(namespace, "FRAGMENT") + return _def_libs[namespace] + + +def _get_or_create_library(dispatch_key: str) -> torch.library.Library: + """ + Get or create the _native IMPL library for a given dispatch key. + + One library per dispatch key is shared across all overridden ops. + """ + global _libs + + key = ("_native", dispatch_key) + if key not in _libs: + _libs[key] = torch.library.Library("_native", "IMPL", dispatch_key) + + return _libs[key] + + +def _install_aten_override(op_symbol: str, dispatch_key: str, kernel: Callable) -> None: + """ + Install (or replace) an aten kernel at (op_symbol, dispatch_key). + + Creates a fresh Library per (op, key) so we can tear down just this + one override via `_destroy_aten_override` without affecting any other + override at the same dispatch key. + """ + key = (op_symbol, dispatch_key) + # Destroy any existing library so its kernel is fully removed before + # we install the new one. `_destroy` calls into the dispatcher to + # unregister all kernels on the library. + existing = _aten_override_libs.pop(key, None) + if existing is not None: + existing._destroy() + + lib = torch.library.Library("aten", "IMPL", dispatch_key) + lib.impl(op_symbol, kernel, dispatch_key, with_keyset=True) + _aten_override_libs[key] = lib + + +def _destroy_aten_override(op_symbol: str, dispatch_key: str) -> None: + """Tear down the aten override at (op_symbol, dispatch_key), if any.""" + lib = _aten_override_libs.pop((op_symbol, dispatch_key), None) + if lib is not None: + lib._destroy() + + +def _resolve_aten_overload(op_symbol: str) -> "torch._ops.OpOverload | None": + """ + Resolve `op_symbol` to a concrete OpOverload on `torch.ops.aten`. + + Accepts bare names ("bmm" → aten.bmm.default) and overload-qualified + names ("add_.Tensor" → aten.add_.Tensor). Returns None if the op is not + registered (e.g. a test-only op_symbol that never hit the C++ dispatcher). + """ + name, _, overload_name = op_symbol.partition(".") + overload_name = overload_name or "default" + try: + packet = getattr(torch.ops.aten, name) + return getattr(packet, overload_name) + except AttributeError: + return None + + +def _aten_schema_tail(op_symbol: str) -> str: + """Return the schema of at:: with the `aten::` prefix stripped. + + Accepts bare names ("bmm" → aten.bmm.default) and overload-qualified + names ("add_.Tensor" → aten.add_.Tensor). + """ + overload = _resolve_aten_overload(op_symbol) + if overload is None: + raise AttributeError(f"aten op not found for op_symbol={op_symbol!r}") + s = str(overload._schema) + # "aten::bmm(Tensor self, Tensor mat2) -> Tensor" -> "(Tensor self, Tensor mat2) -> Tensor" + _, rest = s.split("::", 1) + _, args = rest.split("(", 1) + return f"({args}" + + +def _define_native_op_once(name: str, op_symbol: str) -> None: + # Invariant: callers must only install the eager router at a real backend + # dispatch key (CPU, CUDA, XPU, ...). The fake kernel below redispatches + # to the aten op, and if the router were installed at Meta / + # CompositeImplicitAutograd that redispatch would re-enter the router. + # `register_op_override` enforces this via `_DISALLOWED_DISPATCH_KEYS`. + if name in _defined_native_ops: + return + _get_def_library("_native").define(f"{name}{_aten_schema_tail(op_symbol)}") + # Fake/meta kernel: required so export / dynamo / AOTAutograd can shape-infer + # through the opaque _native op. Reusing the aten op's meta is safe because + # the schema (and therefore shape rules) is cloned from it. + aten_overload = _resolve_aten_overload(op_symbol) + torch.library.register_fake(f"_native::{name}")( + lambda *args, _aten_overload=aten_overload, **kwargs: _aten_overload( + *args, **kwargs + ) + ) + # No autograd or autocast kernels are registered on _native::. Because + # the router is registered at the backend dispatch key (e.g. CUDA), aten's + # own higher-priority kernels on aten:: handle both: + # - Autograd: AutogradCUDA sees aten:: in the autograd graph and + # uses aten's built-in derivative formula. + # - Autocast: AutocastCUDA casts inputs to the autocast dtype before + # redispatching down to our CUDA-level router. + _defined_native_ops.add(name) + + +def _register_node_impl( + lib: torch.library.Library, node: _OverrideNode, dispatch_key: str +) -> None: + """ + Register a single node implementation with the library. + + Args: + lib: The torch.library.Library instance + node: The override node to register + dispatch_key: The dispatch key for registration + """ + if not node.node_id: + raise ValueError( + f"_OverrideNode must have a non-empty node_id before registration " + f"(dsl_name={node.dsl_name!r}, op_symbol={node.op_symbol!r})" + ) + _define_native_op_once(node.node_id, node.op_symbol) + lib.impl( + node.node_id, + node.impl_fn, + dispatch_key, + with_keyset=False, + allow_override=True, + ) + + +def _resolve_iterable(iterable: str | Iterable[str] | None) -> Iterable[str]: + """ + Resolve various input types to a consistent iterable of strings. + + Args: + iterable: String, iterable of strings, or None + + Returns: + Iterable[str]: Consistent iterable output + """ + if iterable is None: + return [] + + if not isinstance(iterable, Iterable) or isinstance(iterable, str): + return (iterable,) + + return iterable + + +def reenable_op_overrides( + *, + enable_dsl_names: str | list[str] | None = None, + enable_op_symbols: str | list[str] | None = None, + enable_dispatch_keys: str | list[str] | None = None, +) -> None: + """ + Re-enable overrides by removing them from filter state and reregistering. + + Args: + enable_dsl_names: DSL names to re-enable + enable_op_symbols: Operation symbols to re-enable + enable_dispatch_keys: Dispatch keys to re-enable + + Note: + This function uses reverse filter state management (removing from + filters to enable). + """ + log.info( + "Re-registering ops by dsl: %s, op_symbol: %s, dispatch_key: %s", + enable_dsl_names, + enable_op_symbols, + enable_dispatch_keys, + ) + + # Update the filters - note `remove_keys=True` because + # we are removing keys from the filters (vs. adding them) + _filter_state.update( + enable_dsl_names, + enable_op_symbols, + enable_dispatch_keys, + remove_keys=True, + ) + + # Get the set of keys that need to be reprocessed + key_set: set[tuple[str, str]] = _build_key_set( + enable_dsl_names, + enable_op_symbols, + enable_dispatch_keys, + ) + + # Process each affected graph with updated filter state + for key in key_set: + op_symbol, dispatch_key = key + + if key in _graphs: + # Note: We don't need to cleanup and recreate the library here + # since we're just updating the registration with new filter state + _register_overrides_from_graph( + op_symbol, dispatch_key, _graphs[key], filter_state=_filter_state + ) + + +def deregister_op_overrides( + *, + disable_dsl_names: str | list[str] | None = None, + disable_op_symbols: str | list[str] | None = None, + disable_dispatch_keys: str | list[str] | None = None, +) -> None: + """ + De-register overrides by updating filter state and reregistering graphs. + + Args: + disable_dsl_names: DSL names to disable + disable_op_symbols: Operation symbols to disable + disable_dispatch_keys: Dispatch keys to disable + + Note: + This function uses filter state management to selectively disable + operations. + """ + log.info( + "De-registering ops by dsl: %s, op_symbol: %s, dispatch_key: %s", + disable_dsl_names, + disable_op_symbols, + disable_dispatch_keys, + ) + + # Update filter state to disable specified entries + _filter_state.update(disable_dsl_names, disable_op_symbols, disable_dispatch_keys) + + # Get the set of keys that need to be reprocessed + key_set: set[tuple[str, str]] = _filter_state.build_disable_key_set() + + # Process each affected graph with filter state + for key in key_set: + op_symbol, dispatch_key = key + + if key in _graphs: + _cleanup_and_reregister_graph( + op_symbol, + dispatch_key, + _graphs[key], + filter_state=_filter_state, + ) + + +def get_dsl_operations(dsl_name: str) -> list[str]: + """Get list of operations registered by a specific DSL. + + Args: + dsl_name: Name of the DSL to query. + + Returns: + Sorted list of operation names registered by the DSL. + """ + operations = set() + for (op_symbol, _), nodes in _graphs.items(): + for node in nodes: + if node.dsl_name == dsl_name: + operations.add(op_symbol) + break + return sorted(operations) + + +def _update_registration_maps( + dsl_name: str, + op_symbol: str, + dispatch_key: str, + key: tuple[str, str], +) -> None: + """ + Update the registration mapping dictionaries. + + Args: + dsl_name: The DSL name + op_symbol: The operation symbol + dispatch_key: The dispatch key + key: The dictionary key tuple + """ + global _dsl_name_to_lib_graph + global _op_symbol_to_lib_graph + global _dispatch_key_to_lib_graph + + def _get_new_entry_or_append( + registration: dict[str, list[tuple[str, str]]], + symbol: str, + key: tuple[str, str], + ) -> None: + """Helper to add key to registration list or create new entry.""" + entry_list = registration.get(symbol) + + if entry_list is None: + entry_list = [key] + registration[symbol] = entry_list + else: + entry_list.append(key) + + _get_new_entry_or_append(_dsl_name_to_lib_graph, dsl_name, key) + _get_new_entry_or_append(_op_symbol_to_lib_graph, op_symbol, key) + _get_new_entry_or_append(_dispatch_key_to_lib_graph, dispatch_key, key) + + +def _always_true(*args: object, **kwargs: object) -> bool: + return True + + +def register_op_override( + backend: str, + lib_symbol: str, + op_symbol: str, + dispatch_key: str, + cond: _OpCondFn | None, + impl: _OpImplFn, + *, + allow_multiple_override: bool = False, + unconditional_override: bool = False, +) -> None: + """ + Register a passed override function to the dispatcher. + + Actually a graph-building operation; real registration happens later. + + Args: + backend: The backend name (DSL name) + lib_symbol: Library you're overriding symbols in (must be "aten") + op_symbol: Name of the operation you're overriding + dispatch_key: Dispatch key to override + cond: Predicate choosing whether `impl` applies to a given call. May + be None if `unconditional_override=True`. + impl: Implementation function for the override + allow_multiple_override: Allow overriding an existing override + unconditional_override: Implementation doesn't have a fallback and + doesn't require torch.DispatchKeySet as the first argument. When + True, a trivially-True predicate is supplied for the router if + `cond` is None. + + Raises: + ValueError: If lib_symbol is not "aten", if dispatch_key is in + _DISALLOWED_DISPATCH_KEYS (Meta / CompositeImplicitAutograd / + CompositeExplicitAutograd), or if cond is None without + unconditional_override=True. + """ + if lib_symbol != "aten": + raise ValueError(f'Unsupported lib_symbol (must be "aten", got: "{lib_symbol}"') + + if dispatch_key in _DISALLOWED_DISPATCH_KEYS: + raise ValueError( + f"dispatch_key={dispatch_key!r} is not supported. Overrides must be " + f"installed at a backend key (e.g. CPU, CUDA, XPU); the router's fake " + f"kernel redispatches to aten and would recurse otherwise." + ) + + if cond is None: + if not unconditional_override: + raise ValueError("cond must be provided unless unconditional_override=True") + cond = _always_true + + key = (op_symbol, dispatch_key) + + global _graphs, _node_id_counter + op_graph = _graphs.get(key, []) + + # Mint a stable id for the opaque `_native::` op. `_sanitized` + # strips dots from overload-qualified names so the result is a valid op + # name. The monotonic counter guarantees uniqueness even if the same + # (op_symbol, dsl_name) is registered, deregistered, and re-registered. + _sanitized = op_symbol.replace(".", "_") + node_id = f"{_sanitized}_{backend}_{_node_id_counter}" + _node_id_counter += 1 + + op_graph.append( + _OverrideNode( + dsl_name=backend, + op_symbol=op_symbol, + dispatch_key=dispatch_key, + cond_fn=cond, + impl_fn=impl, + unconditional_override=unconditional_override, + node_id=node_id, + ) + ) + _graphs[key] = op_graph + # Build additional maps helpful for de-registration + _update_registration_maps(backend, op_symbol, dispatch_key, key=key) + + +def _should_reregister_graph( + original_graph: list[_OverrideNode], + new_graph: list[_OverrideNode], + *, + force_reregister: bool = False, +) -> bool: + """ + Determine if a graph needs reregistration based on changes. + + Args: + original_graph: The original graph before modification + new_graph: The graph after modification + force_reregister: If True, always reregister regardless of changes + + Returns: + bool: True if reregistration is needed + """ + if force_reregister: + return True + + # Check if the graph structure has changed + return original_graph != new_graph + + +def _cleanup_and_reregister_graph( + op_symbol: str, + dispatch_key: str, + graph: list[_OverrideNode], + *, + filter_state: _FilterState | None = None, +) -> None: + """ + Reregister a graph's routes from scratch. + + Used by reorder / deregister / reenable. Libraries are intentionally + long-lived singletons; we rebuild the per-op router closure here. + + Args: + op_symbol: The operation symbol + dispatch_key: The dispatch key + graph: The graph to register + filter_state: Optional filter state for conditional registration + """ + _register_overrides_from_graph( + op_symbol, + dispatch_key, + graph, + filter_state=filter_state, + ) + + +def _apply_graph_transformation( + transformation_fn: UserOrderingFn, + *, + keys_to_process: set[tuple[str, str]] | None = None, + reregister_overrides: bool = False, + filter_state: _FilterState | None = None, +) -> None: + """ + Apply a transformation function to graphs and optionally reregister. + + This is the core pattern used by reorder_graphs_from_user_function and + can be reused for other graph transformation operations. + + Args: + transformation_fn: Function to transform each graph + keys_to_process: Keys to process, or None for all graphs + reregister_overrides: Whether to reregister changed graphs + filter_state: Optional filter state for conditional registration + + Note: + If transformation_fn raises an exception for a specific graph, that graph + will be skipped and processing will continue with remaining graphs. + """ + global _graphs + + # Determine which graphs to process + target_keys = ( + keys_to_process if keys_to_process is not None else set(_graphs.keys()) + ) + + # Process each graph + for op_symbol, dispatch_key in list(target_keys): + if (op_symbol, dispatch_key) not in _graphs: + continue # Skip if graph doesn't exist + + original_graph = list(_graphs[(op_symbol, dispatch_key)]) + + # Apply the transformation with error handling + try: + new_graph = transformation_fn(op_symbol, dispatch_key, original_graph) + except (TypeError, ValueError, AttributeError, RuntimeError): + log.warning( + "Graph transformation failed for %s/%s. Preserving original graph.", + op_symbol, + dispatch_key, + exc_info=True, + ) + continue + except Exception: + log.exception( + "Unexpected error in graph transformation for %s/%s. Preserving original graph.", + op_symbol, + dispatch_key, + ) + continue + + # Validate that the transformation returned a valid result + if not isinstance(new_graph, list): + log.warning( + "Graph transformation returned invalid type %s for %s/%s. Expected list. Preserving original graph.", + type(new_graph).__name__, + op_symbol, + dispatch_key, + ) + continue + + # Update the graph + _graphs[(op_symbol, dispatch_key)] = new_graph + + # Reregister if needed + if reregister_overrides and _should_reregister_graph( + original_graph, new_graph, force_reregister=False + ): + _cleanup_and_reregister_graph( + op_symbol, + dispatch_key, + new_graph, + filter_state=filter_state, + ) + + +def native_decomp_table( + overrides_only: bool = False, +) -> dict[object, Callable]: + """ + Return a decomposition table suitable for passing to + ``ExportedProgram.run_decompositions`` or to Inductor / Dynamo as a + decomposition set for ``torch.compile``. + + This is the canonical way to apply native overrides outside of eager. + Callers opt in explicitly -- the registry does **not** install into any + global compile/export decomp table on its own. This preserves three + properties: + + * ``import torch._native`` doesn't transitively import inductor / + dynamo / triton. + * No other consumer (ONNX, tests, third-party backends) accidentally + picks up our overrides. + * Scoping is up to the caller: pass the table only where routing is + desired. + + By default, the returned table contains + ``torch.export.default_decompositions()`` with native-registered + overrides layered on top -- matching typical "run the usual + decompositions, plus my overrides" intent. The override entries win + over any same-op default, because they're merged last. + + Example: + + ep = torch.export.export(model, args) + ep = ep.run_decompositions( + torch._native.registry.native_decomp_table() + ) + + Args: + overrides_only: If True, return only the native-registered overrides + and no default aten decompositions. Useful for inspection / + debugging, or when composing tables manually. + + Returns: + A dict mapping ``OpOverload`` to decomposition callable. + """ + if overrides_only: + table: dict[object, Callable] = {} + else: + # Local import: keeps `import torch._native` from pulling in + # torch.export (and its transitive imports) at module load time. + from torch.export import default_decompositions + + table = dict(default_decompositions()) + # Merge overrides last so they win on conflicts. + table.update(_native_decomp_overrides) + return table + + +def _register_overrides_from_graph( + op_symbol: str, + dispatch_key: str, + graph: list[_OverrideNode], + *, + filter_state: _FilterState | None = None, +) -> None: + """ + Register all overrides in a single graph. + + Args: + op_symbol: The operation symbol + dispatch_key: The dispatch key + graph: List of override nodes to register + filter_state: Optional filter state for conditional registration + """ + lib = _get_or_create_library(dispatch_key) + + cond_impl: list[tuple[_OpCondFn, str]] = [] + + # node.node_id is minted once at `register_op_override` time and is + # stable across reorder / deregister / reenable -- never regenerate it + # here, since `_defined_native_ops` pins a fake kernel against each id. + for node in graph: + enable = True + if filter_state: + enable = filter_state.check_enabled(node) + + if enable: + _register_node_impl(lib, node, dispatch_key) + cond_impl.append((node.cond_fn, node.node_id)) + node.active = True + else: + node.active = False + + overload = _resolve_aten_overload(op_symbol) + + # Tear down any existing aten override so either (a) the op cleanly + # reverts to native aten (empty cond_impl), or (b) the subsequent + # `get_kernel` call returns the native kernel rather than a stale + # previously-installed router. + _destroy_aten_override(op_symbol, dispatch_key) + + # If no active conds remain for this (op, key), leave the native op + # behavior intact and drop any decomp table entry. + if not cond_impl: + if overload is not None: + _native_decomp_overrides.pop(overload, None) + return + + # Capture the prior kernel at this (op, dispatch_key) *before* we install + # our override. The fallback path calls it via `call_boxed`, which + # re-enters the dispatcher with the original kernel handle -- bypassing + # our just-registered router and avoiding the recursion that would + # otherwise appear in aten's backward formulas (e.g. bmm's backward + # calls bmm, which would route back to us). + fallback_kernel = torch.library.get_kernel(f"aten::{op_symbol}", dispatch_key) + + # Build the router closures. Both share a first-match-wins loop over + # `cond_impl`; they differ only in + # (a) whether cond exceptions fail loudly or silently, and + # (b) what to do when no cond matches. + # + # Eager routers run on real tensors where cond exceptions indicate a + # genuine bug; missing a match falls back to the captured native kernel. + # + # Compile/export routers run under FakeTensor where some predicates are + # undefined (e.g. _is_cow_tensor), so we swallow cond exceptions and + # treat them as non-matches. On no-match we return NotImplemented so + # Inductor reuses the default lowering rather than recursing. + _NO_MATCH = object() # sentinel; impl return values of None would be valid outputs + + def _dispatch(args, kwargs, swallow_cond_exceptions: bool): + for cond, impl_name in cond_impl: + try: + matched = cond(*args, **kwargs) + except Exception: + if not swallow_cond_exceptions: + raise + continue + if matched: + return getattr(torch.ops._native, impl_name)(*args, **kwargs) + return _NO_MATCH + + def eager_router( + keyset, *args, _fallback=fallback_kernel, _aten_overload=overload, **kwargs + ): + # This branch is only safe while Dynamo is actively tracing this Python + # router. The broader compile-session flag can be true when this router + # executes eagerly; redispatching to aten there would re-enter us. + # + # COW state is guarded by Dynamo's _is_cow_tensor handler but is not + # modeled in the compiled graph. If a COW input reaches this router, + # keep the existing eager path so COW-preserving fallback semantics are + # maintained instead of compiling through aten and materializing it. + if ( + torch.compiler.is_dynamo_compiling() + and _aten_overload is not None + and not _has_cow_tensor(*args, **kwargs) + ): + return _aten_overload(*args, **kwargs) + + result = _dispatch(args, kwargs, swallow_cond_exceptions=False) + if result is _NO_MATCH: + return _fallback.call_boxed(keyset, *args, **kwargs) + return result + + def compile_router(*args, **kwargs): + result = _dispatch(args, kwargs, swallow_cond_exceptions=True) + if result is _NO_MATCH: + return NotImplemented + return result + + # Eager path: install a fresh aten override for this (op, key). + _install_aten_override(op_symbol, dispatch_key, eager_router) + + # Compile / export path: record the router in our own decomp table. + # Callers opt in via `native_decomp_table()` -- we deliberately do NOT + # write into torch._inductor.decomposition.decompositions (see the + # comment on `_native_decomp_overrides` for why). + if overload is not None: + _native_decomp_overrides[overload] = compile_router + + +def _register_all_overrides() -> None: + """ + Perform all registration calls from previously-built override graphs. + """ + for key, graph in _graphs.items(): + op_symbol, dispatch_key = key + + _register_overrides_from_graph( + op_symbol, + dispatch_key, + graph, + ) + + +def reorder_graphs_from_user_function( + fn: UserOrderingFn, + *, + reregister_overrides: bool = False, +) -> None: + """ + Reorder override graphs using a user-provided ordering function. + + Args: + fn: User-provided function that takes (op_symbol, dispatch_key, graph) + and returns a reordered graph + reregister_overrides: Whether to reregister graphs that have changed + + Note: + This function uses the common graph transformation pattern and can serve + as an example for other graph manipulation operations. + """ + _apply_graph_transformation( + transformation_fn=fn, + reregister_overrides=reregister_overrides, + ) + + +def _apply_graph_filter( + filter_fn: Callable[[str, str, _OverrideNode], bool], + *, + reregister_overrides: bool = False, +) -> None: + """ + Apply a filter function to remove nodes from graphs. + + This is a convenience function that uses the graph transformation pattern + to filter out unwanted nodes. + + Args: + filter_fn: Function that takes (op_symbol, dispatch_key, node) and + returns True to keep the node, False to remove it + reregister_overrides: Whether to reregister modified graphs + + Example: + # Remove all nodes with "deprecated" in the DSL name + _apply_graph_filter( + lambda op, dk, node: "deprecated" not in node.dsl_name, + reregister_overrides=True + ) + + Note: + If filter_fn raises an exception for a specific graph, the original + graph will be preserved and processing will continue. + """ + + def filtering_transformation( + op_symbol: str, dispatch_key: str, graph: list[_OverrideNode] + ) -> list[_OverrideNode]: + """Apply filter_fn to graph with error handling.""" + try: + return [node for node in graph if filter_fn(op_symbol, dispatch_key, node)] + except (TypeError, ValueError, AttributeError, RuntimeError): + log.warning( + "Graph transformation failed for %s/%s. Preserving original graph.", + op_symbol, + dispatch_key, + exc_info=True, + ) + return graph + except Exception: + log.exception( + "Unexpected error in graph transformation for %s/%s. Preserving original graph.", + op_symbol, + dispatch_key, + ) + return graph + + _apply_graph_transformation( + transformation_fn=filtering_transformation, + reregister_overrides=reregister_overrides, + ) + + +def _apply_selective_reordering( + condition_fn: Callable[[str, str], bool], + ordering_fn: UserOrderingFn, + *, + reregister_overrides: bool = False, +) -> None: + """ + Apply reordering only to graphs that match a condition. + + This allows for more targeted reordering operations. + + Args: + condition_fn: Function that takes (op_symbol, dispatch_key) and + returns True if the graph should be reordered + ordering_fn: Ordering function to apply to matching graphs + reregister_overrides: Whether to reregister modified graphs + + Example: + # Only reorder CUDA operations + _apply_selective_reordering( + condition_fn=lambda op, dk: dk == "CUDA", + ordering_fn=lambda op, dk, g: sorted(g, key=lambda n: n.dsl_name), + reregister_overrides=True + ) + + Note: + If condition_fn or ordering_fn raises an exception for a specific graph, + the original graph will be preserved and processing will continue. + """ + + def conditional_transformation( + op_symbol: str, dispatch_key: str, graph: list[_OverrideNode] + ) -> list[_OverrideNode]: + """Apply ordering_fn conditionally based on condition_fn result.""" + try: + should_reorder = condition_fn(op_symbol, dispatch_key) + except (TypeError, ValueError, AttributeError, RuntimeError): + log.warning( + "Graph transformation failed for %s/%s. Preserving original graph.", + op_symbol, + dispatch_key, + exc_info=True, + ) + return graph + except Exception: + log.exception( + "Unexpected error in graph transformation for %s/%s. Preserving original graph.", + op_symbol, + dispatch_key, + ) + return graph + + if should_reorder: + try: + return ordering_fn(op_symbol, dispatch_key, graph) + except (TypeError, ValueError, AttributeError, RuntimeError): + log.warning( + "Graph transformation failed for %s/%s. Preserving original graph.", + op_symbol, + dispatch_key, + exc_info=True, + ) + return graph + except Exception: + log.exception( + "Unexpected error in graph transformation for %s/%s. Preserving original graph.", + op_symbol, + dispatch_key, + ) + return graph + + return graph # Return unchanged if condition doesn't match + + _apply_graph_transformation( + transformation_fn=conditional_transformation, + reregister_overrides=reregister_overrides, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_native/triton/__init__.py b/.venv/lib/python3.12/site-packages/torch/_native/triton/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3b89db6b46272b05e608c7c9c9c5749825b6fb6f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/triton/__init__.py @@ -0,0 +1,4 @@ +from .const_tensor_wrapper import ConstTensorWrapper + + +__all__ = ["ConstTensorWrapper"] diff --git a/.venv/lib/python3.12/site-packages/torch/_native/triton/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/triton/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f8d6660e8e2a4d704d923f18c2aaa48f4dff0cc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/triton/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/triton/__pycache__/const_tensor_wrapper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_native/triton/__pycache__/const_tensor_wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b29e8376d216ec54f04476d6971b93f0c867ded5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_native/triton/__pycache__/const_tensor_wrapper.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_native/triton/const_tensor_wrapper.py b/.venv/lib/python3.12/site-packages/torch/_native/triton/const_tensor_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..12326018de03f74567b552ae2bbde1218d9882d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/triton/const_tensor_wrapper.py @@ -0,0 +1,62 @@ +import torch + + +class ConstTensorWrapper: + """Read-only, zero-copy view of a tensor for Triton kernel arguments. + + Triton extracts a kernel pointer argument by duck typing: any object with a + ``data_ptr()`` method and a ``dtype`` is treated as a pointer (see Triton's + ``jit.py``). ``ConstTensorWrapper`` overrides ``data_ptr()`` to return + ``const_data_ptr()``, so passing a copy-on-write tensor to an argument the + kernel only reads does not materialize it. The remaining attributes Triton + inspects during specialization and launch are forwarded to the wrapped + tensor. + + Only wrap arguments the kernel treats as read-only (loads, never stores). + Triton does not enforce this; wrapping a written argument is a bug. + + Accessors run under DisableTorchFunctionSubclass so the wrapper never + re-enters __torch_function__: const_data_ptr() and friends are dispatched + methods, and re-entering while an override is mid-redispatch trips the + "cannot skip two levels of __torch_function__" guard. + """ + + def __init__(self, tensor: torch.Tensor) -> None: + self._tensor = tensor + + def data_ptr(self) -> int: + with torch._C.DisableTorchFunctionSubclass(): + # const_data_ptr() exists at runtime but is absent from the stubs. + return self._tensor.const_data_ptr() # type: ignore[attr-defined] + + @property + def dtype(self) -> torch.dtype: + return self._tensor.dtype + + @property + def device(self) -> torch.device: + return self._tensor.device + + @property + def shape(self) -> torch.Size: + return self._tensor.shape + + @property + def ndim(self) -> int: + return self._tensor.ndim + + def dim(self) -> int: + with torch._C.DisableTorchFunctionSubclass(): + return self._tensor.dim() + + def size(self, dim: int | None = None) -> torch.Size | int: + with torch._C.DisableTorchFunctionSubclass(): + return self._tensor.size() if dim is None else self._tensor.size(dim) + + def stride(self, dim: int | None = None) -> tuple[int, ...] | int: + with torch._C.DisableTorchFunctionSubclass(): + return self._tensor.stride() if dim is None else self._tensor.stride(dim) + + def element_size(self) -> int: + with torch._C.DisableTorchFunctionSubclass(): + return self._tensor.element_size() diff --git a/.venv/lib/python3.12/site-packages/torch/_native/triton_utils.py b/.venv/lib/python3.12/site-packages/torch/_native/triton_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..40f83935091f3c47517531db8154d559bc58ce49 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_native/triton_utils.py @@ -0,0 +1,137 @@ +import functools +import logging +import sys +from typing import cast + +from torch._vendor.packaging.version import Version + +from ..backends import cuda as _cuda +from .common_utils import ( + _available_version, + _unavailable_reason, + check_native_jit_disabled, + check_native_version_skip, +) +from .dsl_registry import dsl_registry, DSLModuleProtocol +from .registry import ( + _OpCondFn, + _OpImplFn, + deregister_op_overrides as _deregister_op_overrides_impl, + register_op_override as _register_op_override_impl, +) + + +log = logging.getLogger(__name__) + + +_TRITON_DSL_NAME = "triton" +_TRITON_REQUIRED_VERSION_MAJOR = 3 +_TRITON_MINIMUM_VERSION_MINOR = 6 + + +@functools.cache +def _check_runtime_available() -> tuple[bool, Version | None]: + """ + Check if triton is available + + NOTE: must not import at this point + """ + # Skip all checks if running on CPU-only binary + if not _cuda.is_built(): + return (False, None) + + deps = [ + ("triton", "triton"), + ] + reason = _unavailable_reason(deps) + if reason is None: + available = True + version = _available_version("triton") + else: + # info, not warning: see cutedsl_utils._check_runtime_available for + # rationale (missing optional deps is the common case; surface via + # TORCH_LOGS=+native_dsl when needed). + log.info("triton native DSL ops require: `triton` %s", reason) + available = False + version = None + return available, version + + +def runtime_available() -> bool: + available, _ = _check_runtime_available() + return available + + +def runtime_version() -> None | Version: + _, version = _check_runtime_available() + return version + + +@functools.cache +def _version_is_sufficient() -> bool: + _, version = _check_runtime_available() + + if version is None: + return False + + # Either exact version, or same major + major_ok = version.major == _TRITON_REQUIRED_VERSION_MAJOR + minor_ok = version.minor >= _TRITON_MINIMUM_VERSION_MINOR + + if (major_ok and minor_ok) or check_native_version_skip(): + return True + + log.info( + "triton version %s is not sufficient (>= (%s.%s.*)); " + "set TORCH_NATIVE_SKIP_VERSION_CHECK=1 to override", + version, + _TRITON_REQUIRED_VERSION_MAJOR, + _TRITON_MINIMUM_VERSION_MINOR, + ) + return False + + +def deregister_op_overrides() -> None: + """ + Deregister all ops through triton + """ + _deregister_op_overrides_impl(disable_dsl_names=_TRITON_DSL_NAME) + + +def register_op_override( + lib_symbol: str, + op_symbol: str, + dispatch_key: str, + cond: _OpCondFn | None, + impl: _OpImplFn, + *, + allow_multiple_override: bool = False, + unconditional_override: bool = False, +) -> None: + """ + See torch/_native/registry.py for the underlying implementation + and arguments. This is a thin, DSL-checking wrapper over + _register_op_override_impl + """ + available, version = _check_runtime_available() + if (not available) or check_native_jit_disabled(): + return + + if not _version_is_sufficient(): + return + + _register_op_override_impl( + _TRITON_DSL_NAME, + lib_symbol, + op_symbol, + dispatch_key, + cond, + impl, + allow_multiple_override=allow_multiple_override, + unconditional_override=unconditional_override, + ) + + +# Register this DSL module with the registry +# Note: Import-time registration ensures DSL is available when module is loaded +dsl_registry.register_dsl("triton", cast(DSLModuleProtocol, sys.modules[__name__])) diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__init__.py b/.venv/lib/python3.12/site-packages/torch/_numpy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ff60965d6067e1a8281b665f361adaab221cd4f7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/__init__.py @@ -0,0 +1,34 @@ +# mypy: ignore-errors + +from . import fft, linalg, random +from ._dtypes import * # noqa: F403 +from ._funcs import * # noqa: F403 +from ._getlimits import finfo, iinfo +from ._ndarray import ( + array, + asarray, + ascontiguousarray, + can_cast, + from_dlpack, + ndarray, + newaxis, + result_type, +) +from ._ufuncs import * # noqa: F403 +from ._util import AxisError, UFuncTypeError + + +from math import pi, e # usort: skip + + +all = all # noqa: PLW0127 +alltrue = all + +any = any # noqa: PLW0127 +sometrue = any + +inf = float("inf") +nan = float("nan") + +False_ = False +True_ = True diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d12db6be7ff69e5d9be891b0dc4a9c7f557271d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_binary_ufuncs_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_binary_ufuncs_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..448c9b6c0efcda71e8c234d8a6899a54163e99ea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_binary_ufuncs_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_casting_dicts.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_casting_dicts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ac921c712fa8aed6e73396dd716b8c067563624 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_casting_dicts.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_dtypes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_dtypes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df14d9b412312b176ab97d9f51f91f5862ccffad Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_dtypes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_dtypes_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_dtypes_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6914a7353a39cb682a8f06e443d792ecbac1b279 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_dtypes_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_funcs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_funcs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b922540af0bd6a6dbe2a6f0fcb75020dc208e38 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_funcs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_funcs_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_funcs_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..293c6229e43165120cdfa973b2c226d6f092514b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_funcs_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_getlimits.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_getlimits.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f51746687b7a5f24cacd067dedd4cc0cf224f6ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_getlimits.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_ndarray.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_ndarray.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e12fa75cd53dd58cd3d19515414c26fd7b916cc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_ndarray.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_normalizations.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_normalizations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b7049e3e80b894af3d0ed7aa113e78ad2023d27 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_normalizations.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_reductions_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_reductions_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9913581d06f573734e3f7dbdc516d891c75c1ae1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_reductions_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_ufuncs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_ufuncs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b346c99af8dd69e06512fd1641430fcd1bc802f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_ufuncs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_unary_ufuncs_impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_unary_ufuncs_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ab2bab0048868a05fe30d3dd87cdc038cd4ece0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_unary_ufuncs_impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8f1901ccfa1634d4cc65ca3316ef8b55b52a7e6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/_util.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/fft.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/fft.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33ea019512521a29b57dda2ce557215f93d2e97c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/fft.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/linalg.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/linalg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77f4f98e85b706b1eaffba96bcaa84997a590254 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/linalg.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/random.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/random.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2abf2cc096b41fae91af86bf91b05e462d91d98d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/__pycache__/random.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_binary_ufuncs_impl.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_binary_ufuncs_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..68183fa7d6e965dc59cbb3fd0418d6455d693074 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_binary_ufuncs_impl.py @@ -0,0 +1,85 @@ +# mypy: ignore-errors + +"""Export torch work functions for binary ufuncs, rename/tweak to match numpy. +This listing is further exported to public symbols in the `torch._numpy/_ufuncs.py` module. +""" + +import torch +from torch import ( # noqa: F401 + add, + arctan2, + bitwise_and, + bitwise_left_shift as left_shift, + bitwise_or, + bitwise_right_shift as right_shift, + bitwise_xor, + copysign, + divide, + eq as equal, + float_power, + floor_divide, + fmax, + fmin, + fmod, + gcd, + greater, + greater_equal, + heaviside, + hypot, + lcm, + ldexp, + less, + less_equal, + logaddexp, + logaddexp2, + logical_and, + logical_or, + logical_xor, + maximum, + minimum, + multiply, + nextafter, + not_equal, + pow as power, + remainder, + remainder as mod, + subtract, + true_divide, +) + +from . import _dtypes_impl, _util + + +# work around torch limitations w.r.t. numpy +def matmul(x, y): + # work around: + # - RuntimeError: expected scalar type Int but found Double + # - RuntimeError: "addmm_impl_cpu_" not implemented for 'Bool' + # - RuntimeError: "addmm_impl_cpu_" not implemented for 'Half' + dtype = _dtypes_impl.result_type_impl(x, y) + is_bool = dtype == torch.bool + is_half = (x.dtype == torch.float16 or y.dtype == torch.float16) and ( + x.is_cpu or y.is_cpu + ) + + work_dtype = dtype + if is_bool: + work_dtype = torch.uint8 + if is_half: + work_dtype = torch.float32 + + x = _util.cast_if_needed(x, work_dtype) + y = _util.cast_if_needed(y, work_dtype) + + result = torch.matmul(x, y) + + if work_dtype != dtype: + result = result.to(dtype) + + return result + + +# a stub implementation of divmod, should be improved after +# https://github.com/pytorch/pytorch/issues/90820 is fixed in pytorch +def divmod(x, y): + return x // y, x % y diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_casting_dicts.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_casting_dicts.py new file mode 100644 index 0000000000000000000000000000000000000000..3c859b855dd5d806b4e9e08bb61ada58f4c14c90 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_casting_dicts.py @@ -0,0 +1,1368 @@ +# mypy: ignore-errors + +import torch + + +# These two dicts are autogenerated with autogen/gen_dtypes.py, +# using numpy version 1.24.3. + +_can_cast_dict = { + "no": { + torch.float16: { + torch.float16: True, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.float32: { + torch.float16: False, + torch.float32: True, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.float64: { + torch.float16: False, + torch.float32: False, + torch.float64: True, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.complex64: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: True, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.complex128: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.uint8: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: True, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.uint16: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: True, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.uint32: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: True, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.uint64: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: True, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.int8: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: True, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.int16: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: True, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.int32: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: True, + torch.int64: False, + torch.bool: False, + }, + torch.int64: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: True, + torch.bool: False, + }, + torch.bool: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: True, + }, + }, + "equiv": { + torch.float16: { + torch.float16: True, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.float32: { + torch.float16: False, + torch.float32: True, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.float64: { + torch.float16: False, + torch.float32: False, + torch.float64: True, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.complex64: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: True, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.complex128: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.uint8: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: True, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.uint16: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: True, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.uint32: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: True, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.uint64: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: True, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.int8: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: True, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.int16: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: True, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.int32: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: True, + torch.int64: False, + torch.bool: False, + }, + torch.int64: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: True, + torch.bool: False, + }, + torch.bool: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: False, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: True, + }, + }, + "safe": { + torch.float16: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.float32: { + torch.float16: False, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.float64: { + torch.float16: False, + torch.float32: False, + torch.float64: True, + torch.complex64: False, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.complex64: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.complex128: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: False, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.uint8: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: False, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.uint16: { + torch.float16: False, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: False, + torch.int16: False, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.uint32: { + torch.float16: False, + torch.float32: False, + torch.float64: True, + torch.complex64: False, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: True, + torch.uint64: True, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: True, + torch.bool: False, + }, + torch.uint64: { + torch.float16: False, + torch.float32: False, + torch.float64: True, + torch.complex64: False, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: True, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.int8: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.int16: { + torch.float16: False, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.int32: { + torch.float16: False, + torch.float32: False, + torch.float64: True, + torch.complex64: False, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.int64: { + torch.float16: False, + torch.float32: False, + torch.float64: True, + torch.complex64: False, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: True, + torch.bool: False, + }, + torch.bool: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + }, + "same_kind": { + torch.float16: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.float32: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.float64: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.complex64: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.complex128: { + torch.float16: False, + torch.float32: False, + torch.float64: False, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: False, + torch.int16: False, + torch.int32: False, + torch.int64: False, + torch.bool: False, + }, + torch.uint8: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.uint16: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.uint32: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.uint64: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.int8: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.int16: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.int32: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.int64: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: False, + torch.uint16: False, + torch.uint32: False, + torch.uint64: False, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: False, + }, + torch.bool: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + }, + "unsafe": { + torch.float16: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.float32: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.float64: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.complex64: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.complex128: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.uint8: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.uint16: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.uint32: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.uint64: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.int8: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.int16: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.int32: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.int64: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + torch.bool: { + torch.float16: True, + torch.float32: True, + torch.float64: True, + torch.complex64: True, + torch.complex128: True, + torch.uint8: True, + torch.uint16: True, + torch.uint32: True, + torch.uint64: True, + torch.int8: True, + torch.int16: True, + torch.int32: True, + torch.int64: True, + torch.bool: True, + }, + }, +} + + +_result_type_dict = { + torch.float16: { + torch.float16: torch.float16, + torch.float32: torch.float32, + torch.float64: torch.float64, + torch.complex64: torch.complex64, + torch.complex128: torch.complex128, + torch.uint8: torch.float16, + torch.uint16: torch.float32, + torch.uint32: torch.float64, + torch.uint64: torch.float64, + torch.int8: torch.float16, + torch.int16: torch.float32, + torch.int32: torch.float64, + torch.int64: torch.float64, + torch.bool: torch.float16, + }, + torch.float32: { + torch.float16: torch.float32, + torch.float32: torch.float32, + torch.float64: torch.float64, + torch.complex64: torch.complex64, + torch.complex128: torch.complex128, + torch.uint8: torch.float32, + torch.uint16: torch.float32, + torch.uint32: torch.float64, + torch.uint64: torch.float64, + torch.int8: torch.float32, + torch.int16: torch.float32, + torch.int32: torch.float64, + torch.int64: torch.float64, + torch.bool: torch.float32, + }, + torch.float64: { + torch.float16: torch.float64, + torch.float32: torch.float64, + torch.float64: torch.float64, + torch.complex64: torch.complex128, + torch.complex128: torch.complex128, + torch.uint8: torch.float64, + torch.uint16: torch.float64, + torch.uint32: torch.float64, + torch.uint64: torch.float64, + torch.int8: torch.float64, + torch.int16: torch.float64, + torch.int32: torch.float64, + torch.int64: torch.float64, + torch.bool: torch.float64, + }, + torch.complex64: { + torch.float16: torch.complex64, + torch.float32: torch.complex64, + torch.float64: torch.complex128, + torch.complex64: torch.complex64, + torch.complex128: torch.complex128, + torch.uint8: torch.complex64, + torch.uint16: torch.complex64, + torch.uint32: torch.complex128, + torch.uint64: torch.complex128, + torch.int8: torch.complex64, + torch.int16: torch.complex64, + torch.int32: torch.complex128, + torch.int64: torch.complex128, + torch.bool: torch.complex64, + }, + torch.complex128: { + torch.float16: torch.complex128, + torch.float32: torch.complex128, + torch.float64: torch.complex128, + torch.complex64: torch.complex128, + torch.complex128: torch.complex128, + torch.uint8: torch.complex128, + torch.uint16: torch.complex128, + torch.uint32: torch.complex128, + torch.uint64: torch.complex128, + torch.int8: torch.complex128, + torch.int16: torch.complex128, + torch.int32: torch.complex128, + torch.int64: torch.complex128, + torch.bool: torch.complex128, + }, + torch.uint8: { + torch.float16: torch.float16, + torch.float32: torch.float32, + torch.float64: torch.float64, + torch.complex64: torch.complex64, + torch.complex128: torch.complex128, + torch.uint8: torch.uint8, + torch.uint16: torch.uint16, + torch.uint32: torch.uint32, + torch.uint64: torch.uint64, + torch.int8: torch.int16, + torch.int16: torch.int16, + torch.int32: torch.int32, + torch.int64: torch.int64, + torch.bool: torch.uint8, + }, + torch.uint16: { + torch.float16: torch.float32, + torch.float32: torch.float32, + torch.float64: torch.float64, + torch.complex64: torch.complex64, + torch.complex128: torch.complex128, + torch.uint8: torch.uint16, + torch.uint16: torch.uint16, + torch.uint32: torch.uint32, + torch.uint64: torch.uint64, + torch.int8: torch.int32, + torch.int16: torch.int32, + torch.int32: torch.int32, + torch.int64: torch.int64, + torch.bool: torch.uint16, + }, + torch.uint32: { + torch.float16: torch.float64, + torch.float32: torch.float64, + torch.float64: torch.float64, + torch.complex64: torch.complex128, + torch.complex128: torch.complex128, + torch.uint8: torch.uint32, + torch.uint16: torch.uint32, + torch.uint32: torch.uint32, + torch.uint64: torch.uint64, + torch.int8: torch.int64, + torch.int16: torch.int64, + torch.int32: torch.int64, + torch.int64: torch.int64, + torch.bool: torch.uint32, + }, + torch.uint64: { + torch.float16: torch.float64, + torch.float32: torch.float64, + torch.float64: torch.float64, + torch.complex64: torch.complex128, + torch.complex128: torch.complex128, + torch.uint8: torch.uint64, + torch.uint16: torch.uint64, + torch.uint32: torch.uint64, + torch.uint64: torch.uint64, + torch.int8: torch.float64, + torch.int16: torch.float64, + torch.int32: torch.float64, + torch.int64: torch.float64, + torch.bool: torch.uint64, + }, + torch.int8: { + torch.float16: torch.float16, + torch.float32: torch.float32, + torch.float64: torch.float64, + torch.complex64: torch.complex64, + torch.complex128: torch.complex128, + torch.uint8: torch.int16, + torch.uint16: torch.int32, + torch.uint32: torch.int64, + torch.uint64: torch.float64, + torch.int8: torch.int8, + torch.int16: torch.int16, + torch.int32: torch.int32, + torch.int64: torch.int64, + torch.bool: torch.int8, + }, + torch.int16: { + torch.float16: torch.float32, + torch.float32: torch.float32, + torch.float64: torch.float64, + torch.complex64: torch.complex64, + torch.complex128: torch.complex128, + torch.uint8: torch.int16, + torch.uint16: torch.int32, + torch.uint32: torch.int64, + torch.uint64: torch.float64, + torch.int8: torch.int16, + torch.int16: torch.int16, + torch.int32: torch.int32, + torch.int64: torch.int64, + torch.bool: torch.int16, + }, + torch.int32: { + torch.float16: torch.float64, + torch.float32: torch.float64, + torch.float64: torch.float64, + torch.complex64: torch.complex128, + torch.complex128: torch.complex128, + torch.uint8: torch.int32, + torch.uint16: torch.int32, + torch.uint32: torch.int64, + torch.uint64: torch.float64, + torch.int8: torch.int32, + torch.int16: torch.int32, + torch.int32: torch.int32, + torch.int64: torch.int64, + torch.bool: torch.int32, + }, + torch.int64: { + torch.float16: torch.float64, + torch.float32: torch.float64, + torch.float64: torch.float64, + torch.complex64: torch.complex128, + torch.complex128: torch.complex128, + torch.uint8: torch.int64, + torch.uint16: torch.int64, + torch.uint32: torch.int64, + torch.uint64: torch.float64, + torch.int8: torch.int64, + torch.int16: torch.int64, + torch.int32: torch.int64, + torch.int64: torch.int64, + torch.bool: torch.int64, + }, + torch.bool: { + torch.float16: torch.float16, + torch.float32: torch.float32, + torch.float64: torch.float64, + torch.complex64: torch.complex64, + torch.complex128: torch.complex128, + torch.uint8: torch.uint8, + torch.uint16: torch.uint16, + torch.uint32: torch.uint32, + torch.uint64: torch.uint64, + torch.int8: torch.int8, + torch.int16: torch.int16, + torch.int32: torch.int32, + torch.int64: torch.int64, + torch.bool: torch.bool, + }, +} diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_dtypes.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..8438f32a2ad3ef680af8b8c11cc9cb42ddba3a29 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_dtypes.py @@ -0,0 +1,470 @@ +"""Define analogs of numpy dtypes supported by pytorch. +Define the scalar types and supported dtypes and numpy <--> torch dtype mappings. +""" + +from __future__ import annotations + +import builtins +from typing import TYPE_CHECKING, TypeGuard, TypeVar + +import torch + +from . import _dtypes_impl + + +if TYPE_CHECKING: + from collections.abc import Callable + + from ._ndarray import ndarray + + +_T = TypeVar("_T") + + +# ### Scalar types ### + + +class generic: + name = "generic" + # Concrete scalar types below set these; declared here so the dtype machinery + # can read them off any scalar type. + typecode: str + torch_dtype: torch.dtype + + def __new__(cls, value: object) -> ndarray: + # NumPy scalars are modelled as 0-D arrays + # so a call to np.float32(4) produces a 0-D array. + + from ._ndarray import asarray, ndarray + + if isinstance(value, str) and value in ["inf", "nan"]: + value = {"inf": torch.inf, "nan": torch.nan}[value] + + if isinstance(value, ndarray): + return value.astype(cls) + else: + return asarray(value, dtype=cls) + + +################## +# abstract types # +################## + + +class number(generic): + name = "number" + + +class integer(number): + name = "integer" + + +class inexact(number): + name = "inexact" + + +class signedinteger(integer): + name = "signedinteger" + + +class unsignedinteger(integer): + name = "unsignedinteger" + + +class floating(inexact): + name = "floating" + + +class complexfloating(inexact): + name = "complexfloating" + + +_abstract_dtypes = [ + "generic", + "number", + "integer", + "signedinteger", + "unsignedinteger", + "inexact", + "floating", + "complexfloating", +] + +# ##### concrete types + +# signed integers + + +class int8(signedinteger): + name = "int8" + typecode = "b" + torch_dtype = torch.int8 + + +class int16(signedinteger): + name = "int16" + typecode = "h" + torch_dtype = torch.int16 + + +class int32(signedinteger): + name = "int32" + typecode = "i" + torch_dtype = torch.int32 + + +class int64(signedinteger): + name = "int64" + typecode = "l" + torch_dtype = torch.int64 + + +# unsigned integers + + +class uint8(unsignedinteger): + name = "uint8" + typecode = "B" + torch_dtype = torch.uint8 + + +class uint16(unsignedinteger): + name = "uint16" + typecode = "H" + torch_dtype = torch.uint16 + + +class uint32(signedinteger): + name = "uint32" + typecode = "I" + torch_dtype = torch.uint32 + + +class uint64(signedinteger): + name = "uint64" + typecode = "L" + torch_dtype = torch.uint64 + + +# floating point + + +class float16(floating): + name = "float16" + typecode = "e" + torch_dtype = torch.float16 + + +class float32(floating): + name = "float32" + typecode = "f" + torch_dtype = torch.float32 + + +class float64(floating): + name = "float64" + typecode = "d" + torch_dtype = torch.float64 + + +class complex64(complexfloating): + name = "complex64" + typecode = "F" + torch_dtype = torch.complex64 + + +class complex128(complexfloating): + name = "complex128" + typecode = "D" + torch_dtype = torch.complex128 + + +class bool_(generic): + name = "bool_" + typecode = "?" + torch_dtype = torch.bool + + +# name aliases +_name_aliases = { + "intp": int64, + "int_": int64, + "intc": int32, + "byte": int8, + "short": int16, + "longlong": int64, # XXX: is this correct? + "ulonglong": uint64, + "ubyte": uint8, + "half": float16, + "single": float32, + "double": float64, + "float_": float64, + "csingle": complex64, + "singlecomplex": complex64, + "cdouble": complex128, + "cfloat": complex128, + "complex_": complex128, +} +# We register float_ = float32 and so on +for name, obj in _name_aliases.items(): + vars()[name] = obj + + +# Replicate this NumPy-defined way of grouping scalar types, +# cf tests/core/test_scalar_methods.py +sctypes = { + "int": [int8, int16, int32, int64], + "uint": [uint8, uint16, uint32, uint64], + "float": [float16, float32, float64], + "complex": [complex64, complex128], + "others": [bool_], +} + + +# Support mappings/functions + +_names = {st.name: st for cat in sctypes for st in sctypes[cat]} +_typecodes = {st.typecode: st for cat in sctypes for st in sctypes[cat]} +_torch_dtypes = {st.torch_dtype: st for cat in sctypes for st in sctypes[cat]} + + +_aliases = { + "u1": uint8, + "i1": int8, + "i2": int16, + "i4": int32, + "i8": int64, + "b": int8, # XXX: srsly? + "f2": float16, + "f4": float32, + "f8": float64, + "c8": complex64, + "c16": complex128, + # numpy-specific trailing underscore + "bool_": bool_, +} + + +_python_types = { + int: int64, + float: float64, + complex: complex128, + builtins.bool: bool_, + # also allow stringified names of python types + int.__name__: int64, + float.__name__: float64, + complex.__name__: complex128, + builtins.bool.__name__: bool_, +} + + +def sctype_from_string(s: object) -> type[generic]: + """Normalize a string value: a type 'name' or a typecode or a width alias.""" + if s in _names: + return _names[s] + if s in _name_aliases: + return _name_aliases[s] + if s in _typecodes: + return _typecodes[s] + if s in _aliases: + return _aliases[s] + if s in _python_types: + return _python_types[s] + raise TypeError(f"data type {s!r} not understood") + + +def sctype_from_torch_dtype(torch_dtype: torch.dtype) -> type[generic]: + return _torch_dtypes[torch_dtype] + + +# ### DTypes. ### + + +def dtype(arg: object) -> DType: + if arg is None: + arg = _dtypes_impl.default_dtypes().float_dtype + return DType(arg) + + +class DType: + _scalar_type: type[generic] + + def __init__(self, arg: object) -> None: + # a pytorch object? + if isinstance(arg, torch.dtype): + sctype = _torch_dtypes[arg] + elif isinstance(arg, torch.Tensor): + sctype = _torch_dtypes[arg.dtype] + # a scalar type? + elif issubclass_(arg, generic): + sctype = arg + # a dtype already? + elif isinstance(arg, DType): + sctype = arg._scalar_type + # a has a right attribute? + elif hasattr(arg, "dtype"): + sctype = arg.dtype._scalar_type + else: + sctype = sctype_from_string(arg) + self._scalar_type = sctype + + @property + def name(self) -> str: + return self._scalar_type.name + + @property + def type(self) -> type[generic]: + return self._scalar_type + + @property + def kind(self) -> str: + # https://numpy.org/doc/stable/reference/generated/numpy.dtype.kind.html + return _torch_dtypes[self.torch_dtype].name[0] + + @property + def typecode(self) -> str: + return self._scalar_type.typecode + + def __eq__(self, other: object) -> bool: + if isinstance(other, DType): + return self._scalar_type == other._scalar_type + try: + other_instance = DType(other) + except TypeError: + return False + return self._scalar_type == other_instance._scalar_type + + @property + def torch_dtype(self) -> torch.dtype: + return self._scalar_type.torch_dtype + + def __hash__(self) -> int: + return hash(self._scalar_type.name) + + def __repr__(self) -> str: + return f'dtype("{self.name}")' + + __str__ = __repr__ + + @property + def itemsize(self) -> int: + elem = self.type(1) + return elem.tensor.element_size() + + def __getstate__(self) -> builtins.type[generic]: + return self._scalar_type + + def __setstate__(self, value: builtins.type[generic]) -> None: + self._scalar_type = value + + +typecodes = { + "All": "efdFDBbhil?", + "AllFloat": "efdFD", + "AllInteger": "Bbhil", + "Integer": "bhil", + "UnsignedInteger": "B", + "Float": "efd", + "Complex": "FD", +} + + +# ### Defaults and dtype discovery + + +def set_default_dtype( + fp_dtype: object = "numpy", int_dtype: object = "numpy" +) -> Callable[[], _dtypes_impl.DefaultDTypes]: + """Set the (global) defaults for fp, complex, and int dtypes. + + The complex dtype is inferred from the float (fp) dtype. It has + a width at least twice the width of the float dtype, + i.e., it's complex128 for float64 and complex64 for float32. + + Parameters + ---------- + fp_dtype + Allowed values are "numpy", "pytorch" or dtype_like things which + can be converted into a DType instance. + Default is "numpy" (i.e. float64). + int_dtype + Allowed values are "numpy", "pytorch" or dtype_like things which + can be converted into a DType instance. + Default is "numpy" (i.e. int64). + + Returns + ------- + The old default dtype state: a namedtuple with attributes ``float_dtype``, + ``complex_dtypes`` and ``int_dtype``. These attributes store *pytorch* + dtypes. + + Notes + ------------ + This function has a side effect: it sets the global state with the provided dtypes. + + The complex dtype has bit width of at least twice the width of the float + dtype, i.e. it's complex128 for float64 and complex64 for float32. + + """ + if fp_dtype not in ["numpy", "pytorch"]: + fp_dtype = dtype(fp_dtype).torch_dtype + if int_dtype not in ["numpy", "pytorch"]: + int_dtype = dtype(int_dtype).torch_dtype + + if fp_dtype == "numpy": + float_dtype = torch.float64 + elif fp_dtype == "pytorch": + float_dtype = torch.float32 + else: + float_dtype = fp_dtype + + complex_dtype = { + torch.float64: torch.complex128, + torch.float32: torch.complex64, + torch.float16: torch.complex64, + }[float_dtype] + + if int_dtype in ["numpy", "pytorch"]: + int_dtype = torch.int64 + + new_defaults = _dtypes_impl.DefaultDTypes( + float_dtype=float_dtype, complex_dtype=complex_dtype, int_dtype=int_dtype + ) + + # set the new global state and return the old state + old_defaults = _dtypes_impl.default_dtypes + # pyrefly: ignore[bad-assignment] # TODO + _dtypes_impl._default_dtypes = new_defaults + return old_defaults + + +def issubclass_(arg: object, klass: type[_T]) -> TypeGuard[type[_T]]: + # issubclass() raises TypeError if arg is not a class; guard explicitly so a + # non-class arg returns False (and narrows arg to type[_T] on success). + return isinstance(arg, type) and issubclass(arg, klass) + + +def issubdtype(arg1: object, arg2: object) -> bool: + # cf https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numerictypes.py#L356-L420 + + # We also accept strings even if NumPy doesn't as dtypes are serialized as their + # string representation in dynamo's graph + def str_to_abstract(t: object) -> object: + if isinstance(t, str) and t in _abstract_dtypes: + return globals()[t] + return t + + arg1 = str_to_abstract(arg1) + arg2 = str_to_abstract(arg2) + + if not issubclass_(arg1, generic): + arg1 = dtype(arg1).type + if not issubclass_(arg2, generic): + arg2 = dtype(arg2).type + return issubclass(arg1, arg2) + + +__all__ = ["dtype", "DType", "typecodes", "issubdtype", "set_default_dtype", "sctypes"] +__all__ += list(_names.keys()) +__all__ += list(_name_aliases.keys()) +__all__ += _abstract_dtypes # noqa: PLE0605 diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_dtypes_impl.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_dtypes_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..5c552cc75d9e716200604d15874b6d037e751f6c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_dtypes_impl.py @@ -0,0 +1,230 @@ +# mypy: ignore-errors + +"""Dtypes/scalar type implementations with torch dtypes. + +Here `dtype` is always a torch.dtype, this module knows nothing about +scalar types, wrapper dtypes or anything like that. PyTorch only. +""" + +from collections import namedtuple + +import torch + + +# defaults : mimic NumPy, allow user control +DefaultDTypes = namedtuple( + "DefaultDTypes", ["float_dtype", "complex_dtype", "int_dtype"] +) + +# a global state +# We set it the first time we call default_dtypes() to avoid importing +# torch._dynamo.config and create a circular reference +_default_dtypes = None + + +def default_dtypes(): + global _default_dtypes + if _default_dtypes is None: + import torch._dynamo.config as config + + _default_dtypes = DefaultDTypes( + float_dtype=getattr(torch, config.numpy_default_float), + complex_dtype=getattr(torch, config.numpy_default_complex), + int_dtype=getattr(torch, config.numpy_default_int), + ) + if not isinstance(_default_dtypes.float_dtype, torch.dtype): + raise AssertionError( + f"float_dtype must be a torch.dtype, got {type(_default_dtypes.float_dtype)}" + ) + if not isinstance(_default_dtypes.complex_dtype, torch.dtype): + raise AssertionError( + f"complex_dtype must be a torch.dtype, got {type(_default_dtypes.complex_dtype)}" + ) + if not isinstance(_default_dtypes.int_dtype, torch.dtype): + raise AssertionError( + f"int_dtype must be a torch.dtype, got {type(_default_dtypes.int_dtype)}" + ) + return _default_dtypes + + +def get_default_dtype_for(dtype): + """Default scalar type given sctype category.""" + if dtype == torch.bool: + return dtype + if dtype.is_complex: + return default_dtypes().complex_dtype + if dtype.is_floating_point: + return default_dtypes().float_dtype + # else, it must be (some) integer + return default_dtypes().int_dtype + + +from . import _casting_dicts as _cd + + +def can_cast_impl(from_torch_dtype, to_torch_dtype, casting): + return _cd._can_cast_dict[casting][from_torch_dtype][to_torch_dtype] + + +def result_type_impl(*tensors): + # NB: torch dtypes here + dtyp = tensors[0].dtype + if len(tensors) == 1: + return dtyp + + for curr in tensors[1:]: + dtyp = _cd._result_type_dict[dtyp][curr.dtype] + + return dtyp + + +def python_type_for_torch(dtyp): + """Get a python scalar type a torch dtype""" + if dtyp.is_floating_point: + typ = float + elif dtyp.is_complex: + typ = complex + elif dtyp == torch.bool: + typ = bool + else: + typ = int + return typ + + +# ### NEP 50 helpers ### + +_SCALAR_TYPES = (int, bool, float, complex) + +_SCALAR_AND_SYMBOLIC_TYPES = ( + *_SCALAR_TYPES, + torch.SymInt, + torch.SymFloat, + torch.SymBool, +) + +_NEP50_FUNCS_TENSOR_ONLY = ( + "minimum", + "maximum", + "logaddexp", + "logaddexp2", + "lcm", + "gcd", + "hypot", + "heaviside", + "fmod", + "fmin", + "fmax", + "copysign", + "arctan2", +) + + +def is_scalar(x): + return isinstance(x, _SCALAR_TYPES) + + +def is_scalar_or_symbolic(x): + return isinstance(x, _SCALAR_AND_SYMBOLIC_TYPES) + + +def _dtype_for_scalar(py_type): + return { + bool: torch.bool, + torch.SymBool: torch.bool, + int: torch.int64, + torch.SymInt: torch.int64, + float: torch.float64, + torch.SymFloat: torch.float64, + complex: torch.complex128, + }[py_type] + + +def _dtype_for_scalar_or_tensor(x): + return x.dtype if isinstance(x, torch.Tensor) else _dtype_for_scalar(type(x)) + + +def is_float_or_fp_tensor(x): + return _dtype_for_scalar_or_tensor(x).is_floating_point + + +def is_complex_or_complex_tensor(x): + return _dtype_for_scalar_or_tensor(x).is_complex + + +def _category(dtype): + return { + torch.bool: 0, + torch.SymBool: 0, + # int + torch.uint8: 1, + torch.int8: 1, + torch.int16: 1, + torch.int32: 1, + torch.int64: 1, + torch.SymInt: 1, + # float + torch.float16: 2, + torch.float32: 2, + torch.float64: 2, + torch.SymFloat: 2, + # complex + torch.complex64: 3, + torch.complex128: 3, + }[dtype] + + +def nep50_to_tensors(x1, x2, handle_weaks, function_name): + """If either of inputs is a python scalar, type-promote with NEP 50.""" + + def to_tensor(scalar, dtype=None): + if dtype is None: + dtype = _dtype_for_scalar(type(scalar)) + dtype = get_default_dtype_for(dtype) + return torch.as_tensor(scalar, dtype=dtype) + + x1_is_weak = not isinstance(x1, torch.Tensor) + x2_is_weak = not isinstance(x2, torch.Tensor) + if not handle_weaks or (x1_is_weak and x2_is_weak): + x1 = to_tensor(x1) if x1_is_weak else x1 + x2 = to_tensor(x2) if x2_is_weak else x2 + return x1, x2 + + # scalar tensor: NEP 50 + if x1_is_weak == x2_is_weak: + raise AssertionError( + f"Expected exactly one weak type, got x1_is_weak={x1_is_weak}, x2_is_weak={x2_is_weak}" + ) + + weak, not_weak = (x1, x2) if x1_is_weak else (x2, x1) + + # find the dtype for the weak's type + weak_dtype = _dtype_for_scalar(type(weak)) + + cat_weak = _category(weak_dtype) + cat_not_weak = _category(not_weak.dtype) + + dt = not_weak.dtype if cat_weak <= cat_not_weak else None + + # special-case complex + float32 + if weak_dtype.is_complex and not_weak.dtype == torch.float32: + dt = torch.complex64 + + # detect overflows: in PyTorch, uint8(-1) wraps around to 255, + # while NEP50 mandates an exception. + # + # Note that we only check if each element of the binop overflows, + # not the result. Consider, e.g. `uint8(100) + 200`. Operands are OK + # in uint8, but the result overflows and wrap around 255. + # Numpy emits a RuntimeWarning, PyTorch does not, and we do not either. + if cat_weak == 1 and cat_not_weak == 1: + # integers + iinfo = torch.iinfo(not_weak.dtype) + if not (iinfo.min <= weak <= iinfo.max): + raise OverflowError( + f"Python integer {weak} out of bounds for {not_weak.dtype}" + ) + if weak_dtype != dt or function_name in _NEP50_FUNCS_TENSOR_ONLY: + # finally, can make `weak` into a 0D tensor, if both parameters are required to be tensor. + weak = to_tensor(weak, dt) + + return (weak, not_weak) if x1_is_weak else (not_weak, weak) diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_funcs.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_funcs.py new file mode 100644 index 0000000000000000000000000000000000000000..c0341c4588ed5359ff68a90c8c53e667eedeb12d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_funcs.py @@ -0,0 +1,76 @@ +# mypy: ignore-errors + +import inspect +import itertools + +from . import _funcs_impl, _reductions_impl +from ._normalizations import normalizer + + +# _funcs_impl.py contains functions which mimic NumPy's eponymous equivalents, +# and consume/return PyTorch tensors/dtypes. +# They are also type annotated. +# Pull these functions from _funcs_impl and decorate them with @normalizer, which +# - Converts any input `np.ndarray`, `torch._numpy.ndarray`, list of lists, Python scalars, etc into a `torch.Tensor`. +# - Maps NumPy dtypes to PyTorch dtypes +# - If the input to the `axis` kwarg is an ndarray, it maps it into a tuple +# - Implements the semantics for the `out=` arg +# - Wraps back the outputs into `torch._numpy.ndarrays` + + +def _public_functions(mod): + def is_public_function(f): + return inspect.isfunction(f) and not f.__name__.startswith("_") + + return inspect.getmembers(mod, is_public_function) + + +# We fill in __all__ in the loop below +__all__ = [] + +# decorate implementer functions with argument normalizers and export to the top namespace +for name, func in itertools.chain( + _public_functions(_funcs_impl), _public_functions(_reductions_impl) +): + if name in ["percentile", "quantile", "median"]: + decorated = normalizer(func, promote_scalar_result=True) + elif name == "einsum": + # normalized manually + decorated = func + else: + decorated = normalizer(func) + + decorated.__qualname__ = name + decorated.__name__ = name + vars()[name] = decorated + __all__.append(name) + + +""" +Vendored objects from numpy.lib.index_tricks +""" + + +class IndexExpression: + """ + Written by Konrad Hinsen + last revision: 1999-7-23 + + Cosmetic changes by T. Oliphant 2001 + """ + + def __init__(self, maketuple): + self.maketuple = maketuple + + def __getitem__(self, item): + if self.maketuple and not isinstance(item, tuple): + return (item,) + else: + return item + + +index_exp = IndexExpression(maketuple=True) +s_ = IndexExpression(maketuple=False) + + +__all__ += ["index_exp", "s_"] diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_funcs_impl.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_funcs_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..269c8a34c28f0bea69321549257bf8f2d1635d91 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_funcs_impl.py @@ -0,0 +1,2064 @@ +# mypy: ignore-errors + +"""A thin pytorch / numpy compat layer. + +Things imported from here have numpy-compatible signatures but operate on +pytorch tensors. +""" + +# Contents of this module ends up in the main namespace via _funcs.py +# where type annotations are used in conjunction with the @normalizer decorator. +from __future__ import annotations + +import builtins +import itertools +import operator +from typing import TYPE_CHECKING + +import torch + +from . import _dtypes_impl, _util + + +if TYPE_CHECKING: + from collections.abc import Sequence + + from ._normalizations import ( + ArrayLike, + ArrayLikeOrScalar, + CastingModes, + DTypeLike, + NDArray, + NotImplementedType, + OutArray, + ) + + +def copy( + a: ArrayLike, order: NotImplementedType = "K", subok: NotImplementedType = False +): + return a.clone() + + +def copyto( + dst: NDArray, + src: ArrayLike, + casting: CastingModes | None = "same_kind", + where: NotImplementedType = None, +): + (src,) = _util.typecast_tensors((src,), dst.dtype, casting=casting) + dst.copy_(src) + + +def atleast_1d(*arys: ArrayLike): + res = torch.atleast_1d(*arys) + if isinstance(res, tuple): + return list(res) + else: + return res + + +def atleast_2d(*arys: ArrayLike): + res = torch.atleast_2d(*arys) + if isinstance(res, tuple): + return list(res) + else: + return res + + +def atleast_3d(*arys: ArrayLike): + res = torch.atleast_3d(*arys) + if isinstance(res, tuple): + return list(res) + else: + return res + + +def _concat_check(tup, dtype, out): + if tup == (): + raise ValueError("need at least one array to concatenate") + + """Check inputs in concatenate et al.""" + if out is not None and dtype is not None: + # mimic numpy + raise TypeError( + "concatenate() only takes `out` or `dtype` as an " + "argument, but both were provided." + ) + + +def _concat_cast_helper(tensors, out=None, dtype=None, casting="same_kind"): + """Figure out dtypes, cast if necessary.""" + + if out is not None or dtype is not None: + # figure out the type of the inputs and outputs + out_dtype = out.dtype.torch_dtype if dtype is None else dtype + else: + out_dtype = _dtypes_impl.result_type_impl(*tensors) + + # cast input arrays if necessary; do not broadcast them against `out` + tensors = _util.typecast_tensors(tensors, out_dtype, casting) + + return tensors + + +def _concatenate( + tensors, axis=0, out=None, dtype=None, casting: CastingModes | None = "same_kind" +): + # pure torch implementation, used below and in cov/corrcoef below + tensors, axis = _util.axis_none_flatten(*tensors, axis=axis) + tensors = _concat_cast_helper(tensors, out, dtype, casting) + return torch.cat(tensors, axis) + + +def concatenate( + ar_tuple: Sequence[ArrayLike], + axis=0, + out: OutArray | None = None, + dtype: DTypeLike | None = None, + casting: CastingModes | None = "same_kind", +): + _concat_check(ar_tuple, dtype, out=out) + result = _concatenate(ar_tuple, axis=axis, out=out, dtype=dtype, casting=casting) + return result + + +def vstack( + tup: Sequence[ArrayLike], + *, + dtype: DTypeLike | None = None, + casting: CastingModes | None = "same_kind", +): + _concat_check(tup, dtype, out=None) + tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting) + return torch.vstack(tensors) + + +row_stack = vstack + + +def hstack( + tup: Sequence[ArrayLike], + *, + dtype: DTypeLike | None = None, + casting: CastingModes | None = "same_kind", +): + _concat_check(tup, dtype, out=None) + tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting) + return torch.hstack(tensors) + + +def dstack( + tup: Sequence[ArrayLike], + *, + dtype: DTypeLike | None = None, + casting: CastingModes | None = "same_kind", +): + # XXX: in numpy 1.24 dstack does not have dtype and casting keywords + # but {h,v}stack do. Hence add them here for consistency. + _concat_check(tup, dtype, out=None) + tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting) + return torch.dstack(tensors) + + +def column_stack( + tup: Sequence[ArrayLike], + *, + dtype: DTypeLike | None = None, + casting: CastingModes | None = "same_kind", +): + # XXX: in numpy 1.24 column_stack does not have dtype and casting keywords + # but row_stack does. (because row_stack is an alias for vstack, really). + # Hence add these keywords here for consistency. + _concat_check(tup, dtype, out=None) + tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting) + return torch.column_stack(tensors) + + +def stack( + arrays: Sequence[ArrayLike], + axis=0, + out: OutArray | None = None, + *, + dtype: DTypeLike | None = None, + casting: CastingModes | None = "same_kind", +): + _concat_check(arrays, dtype, out=out) + + tensors = _concat_cast_helper(arrays, dtype=dtype, casting=casting) + result_ndim = tensors[0].ndim + 1 + axis = _util.normalize_axis_index(axis, result_ndim) + return torch.stack(tensors, axis=axis) + + +def append(arr: ArrayLike, values: ArrayLike, axis=None): + if axis is None: + if arr.ndim != 1: + arr = arr.flatten() + values = values.flatten() + axis = arr.ndim - 1 + return _concatenate((arr, values), axis=axis) + + +# ### split ### + + +def _split_helper(tensor, indices_or_sections, axis, strict=False): + if isinstance(indices_or_sections, int): + return _split_helper_int(tensor, indices_or_sections, axis, strict) + elif isinstance(indices_or_sections, (list, tuple)): + # NB: drop split=..., it only applies to split_helper_int + return _split_helper_list(tensor, list(indices_or_sections), axis) + else: + raise TypeError(f"split_helper: {type(indices_or_sections)}") + + +def _split_helper_int(tensor, indices_or_sections, axis, strict=False): + if not isinstance(indices_or_sections, int): + raise NotImplementedError("split: indices_or_sections") + + axis = _util.normalize_axis_index(axis, tensor.ndim) + + # numpy: l%n chunks of size (l//n + 1), the rest are sized l//n + l, n = tensor.shape[axis], indices_or_sections + + if n <= 0: + raise ValueError + + if l % n == 0: + num, sz = n, l // n + lst = [sz] * num + else: + if strict: + raise ValueError("array split does not result in an equal division") + + num, sz = l % n, l // n + 1 + lst = [sz] * num + + lst += [sz - 1] * (n - num) + + return torch.split(tensor, lst, axis) + + +def _split_helper_list(tensor, indices_or_sections, axis): + if not isinstance(indices_or_sections, list): + raise NotImplementedError("split: indices_or_sections: list") + # numpy expects indices, while torch expects lengths of sections + # also, numpy appends zero-size arrays for indices above the shape[axis] + lst = [x for x in indices_or_sections if x <= tensor.shape[axis]] + num_extra = len(indices_or_sections) - len(lst) + + lst.append(tensor.shape[axis]) + lst = [ + lst[0], + ] + [a - b for a, b in zip(lst[1:], lst[:-1])] + lst += [0] * num_extra + + return torch.split(tensor, lst, axis) + + +def array_split(ary: ArrayLike, indices_or_sections, axis=0): + return _split_helper(ary, indices_or_sections, axis) + + +def split(ary: ArrayLike, indices_or_sections, axis=0): + return _split_helper(ary, indices_or_sections, axis, strict=True) + + +def hsplit(ary: ArrayLike, indices_or_sections): + if ary.ndim == 0: + raise ValueError("hsplit only works on arrays of 1 or more dimensions") + axis = 1 if ary.ndim > 1 else 0 + return _split_helper(ary, indices_or_sections, axis, strict=True) + + +def vsplit(ary: ArrayLike, indices_or_sections): + if ary.ndim < 2: + raise ValueError("vsplit only works on arrays of 2 or more dimensions") + return _split_helper(ary, indices_or_sections, 0, strict=True) + + +def dsplit(ary: ArrayLike, indices_or_sections): + if ary.ndim < 3: + raise ValueError("dsplit only works on arrays of 3 or more dimensions") + return _split_helper(ary, indices_or_sections, 2, strict=True) + + +def kron(a: ArrayLike, b: ArrayLike): + return torch.kron(a, b) + + +def vander(x: ArrayLike, N=None, increasing=False): + return torch.vander(x, N, increasing) + + +# ### linspace, geomspace, logspace and arange ### + + +def linspace( + start: ArrayLike, + stop: ArrayLike, + num=50, + endpoint=True, + retstep=False, + dtype: DTypeLike | None = None, + axis=0, +): + if axis != 0 or retstep or not endpoint: + raise NotImplementedError + if dtype is None: + dtype = _dtypes_impl.default_dtypes().float_dtype + # XXX: raises TypeError if start or stop are not scalars + return torch.linspace(start, stop, num, dtype=dtype) + + +def geomspace( + start: ArrayLike, + stop: ArrayLike, + num=50, + endpoint=True, + dtype: DTypeLike | None = None, + axis=0, +): + if axis != 0 or not endpoint: + raise NotImplementedError + base = torch.pow(stop / start, 1.0 / (num - 1)) + logbase = torch.log(base) + return torch.logspace( + torch.log(start) / logbase, + torch.log(stop) / logbase, + num, + base=base, + ) + + +def logspace( + start, + stop, + num=50, + endpoint=True, + base=10.0, + dtype: DTypeLike | None = None, + axis=0, +): + if axis != 0 or not endpoint: + raise NotImplementedError + return torch.logspace(start, stop, num, base=base, dtype=dtype) + + +def arange( + start: ArrayLikeOrScalar | None = None, + stop: ArrayLikeOrScalar | None = None, + step: ArrayLikeOrScalar | None = 1, + dtype: DTypeLike | None = None, + *, + like: NotImplementedType = None, +): + if step == 0: + raise ZeroDivisionError + if stop is None and start is None: + raise TypeError + if stop is None: + # XXX: this breaks if start is passed as a kwarg: + # arange(start=4) should raise (no stop) but doesn't + start, stop = 0, start + if start is None: + start = 0 + + # the dtype of the result + if dtype is None: + dtype = ( + _dtypes_impl.default_dtypes().float_dtype + if any(_dtypes_impl.is_float_or_fp_tensor(x) for x in (start, stop, step)) + else _dtypes_impl.default_dtypes().int_dtype + ) + work_dtype = torch.float64 if dtype.is_complex else dtype + + # RuntimeError: "lt_cpu" not implemented for 'ComplexFloat'. Fall back to eager. + if any(_dtypes_impl.is_complex_or_complex_tensor(x) for x in (start, stop, step)): + raise NotImplementedError + + if (step > 0 and start > stop) or (step < 0 and start < stop): + # empty range + return torch.empty(0, dtype=dtype) + + result = torch.arange(start, stop, step, dtype=work_dtype) + result = _util.cast_if_needed(result, dtype) + return result + + +# ### zeros/ones/empty/full ### + + +def empty( + shape, + dtype: DTypeLike | None = None, + order: NotImplementedType = "C", + *, + like: NotImplementedType = None, +): + if dtype is None: + dtype = _dtypes_impl.default_dtypes().float_dtype + return torch.empty(shape, dtype=dtype) + + +# NB: *_like functions deliberately deviate from numpy: it has subok=True +# as the default; we set subok=False and raise on anything else. + + +def empty_like( + prototype: ArrayLike, + dtype: DTypeLike | None = None, + order: NotImplementedType = "K", + subok: NotImplementedType = False, + shape=None, +): + result = torch.empty_like(prototype, dtype=dtype) + if shape is not None: + result = result.reshape(shape) + return result + + +def full( + shape, + fill_value: ArrayLike, + dtype: DTypeLike | None = None, + order: NotImplementedType = "C", + *, + like: NotImplementedType = None, +): + if isinstance(shape, int): + shape = (shape,) + if dtype is None: + dtype = fill_value.dtype + if not isinstance(shape, (tuple, list)): + shape = (shape,) + return torch.full(shape, fill_value, dtype=dtype) + + +def full_like( + a: ArrayLike, + fill_value, + dtype: DTypeLike | None = None, + order: NotImplementedType = "K", + subok: NotImplementedType = False, + shape=None, +): + # XXX: fill_value broadcasts + result = torch.full_like(a, fill_value, dtype=dtype) + if shape is not None: + result = result.reshape(shape) + return result + + +def ones( + shape, + dtype: DTypeLike | None = None, + order: NotImplementedType = "C", + *, + like: NotImplementedType = None, +): + if dtype is None: + dtype = _dtypes_impl.default_dtypes().float_dtype + return torch.ones(shape, dtype=dtype) + + +def ones_like( + a: ArrayLike, + dtype: DTypeLike | None = None, + order: NotImplementedType = "K", + subok: NotImplementedType = False, + shape=None, +): + result = torch.ones_like(a, dtype=dtype) + if shape is not None: + result = result.reshape(shape) + return result + + +def zeros( + shape, + dtype: DTypeLike | None = None, + order: NotImplementedType = "C", + *, + like: NotImplementedType = None, +): + if dtype is None: + dtype = _dtypes_impl.default_dtypes().float_dtype + return torch.zeros(shape, dtype=dtype) + + +def zeros_like( + a: ArrayLike, + dtype: DTypeLike | None = None, + order: NotImplementedType = "K", + subok: NotImplementedType = False, + shape=None, +): + result = torch.zeros_like(a, dtype=dtype) + if shape is not None: + result = result.reshape(shape) + return result + + +# ### cov & corrcoef ### + + +def _xy_helper_corrcoef(x_tensor, y_tensor=None, rowvar=True): + """Prepare inputs for cov and corrcoef.""" + + # https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/function_base.py#L2636 + if y_tensor is not None: + # make sure x and y are at least 2D + ndim_extra = 2 - x_tensor.ndim + if ndim_extra > 0: + x_tensor = x_tensor.view((1,) * ndim_extra + x_tensor.shape) + if not rowvar and x_tensor.shape[0] != 1: + x_tensor = x_tensor.mT + x_tensor = x_tensor.clone() + + ndim_extra = 2 - y_tensor.ndim + if ndim_extra > 0: + y_tensor = y_tensor.view((1,) * ndim_extra + y_tensor.shape) + if not rowvar and y_tensor.shape[0] != 1: + y_tensor = y_tensor.mT + y_tensor = y_tensor.clone() + + x_tensor = _concatenate((x_tensor, y_tensor), axis=0) + + return x_tensor + + +def corrcoef( + x: ArrayLike, + y: ArrayLike | None = None, + rowvar=True, + bias=None, + ddof=None, + *, + dtype: DTypeLike | None = None, +): + if bias is not None or ddof is not None: + # deprecated in NumPy + raise NotImplementedError + xy_tensor = _xy_helper_corrcoef(x, y, rowvar) + + is_half = (xy_tensor.dtype == torch.float16) and xy_tensor.is_cpu + if is_half: + # work around torch's "addmm_impl_cpu_" not implemented for 'Half'" + dtype = torch.float32 + + xy_tensor = _util.cast_if_needed(xy_tensor, dtype) + result = torch.corrcoef(xy_tensor) + + if is_half: + result = result.to(torch.float16) + + return result + + +def cov( + m: ArrayLike, + y: ArrayLike | None = None, + rowvar=True, + bias=False, + ddof=None, + fweights: ArrayLike | None = None, + aweights: ArrayLike | None = None, + *, + dtype: DTypeLike | None = None, +): + m = _xy_helper_corrcoef(m, y, rowvar) + + if ddof is None: + ddof = 1 if bias == 0 else 0 + + is_half = (m.dtype == torch.float16) and m.is_cpu + if is_half: + # work around torch's "addmm_impl_cpu_" not implemented for 'Half'" + dtype = torch.float32 + + m = _util.cast_if_needed(m, dtype) + result = torch.cov(m, correction=ddof, aweights=aweights, fweights=fweights) + + if is_half: + result = result.to(torch.float16) + + return result + + +def _conv_corr_impl(a, v, mode): + dt = _dtypes_impl.result_type_impl(a, v) + a = _util.cast_if_needed(a, dt) + v = _util.cast_if_needed(v, dt) + + padding = v.shape[0] - 1 if mode == "full" else mode + + if padding == "same" and v.shape[0] % 2 == 0: + # UserWarning: Using padding='same' with even kernel lengths and odd + # dilation may require a zero-padded copy of the input be created + # (Triggered internally at pytorch/aten/src/ATen/native/Convolution.cpp:1010.) + raise NotImplementedError("mode='same' and even-length weights") + + # NumPy only accepts 1D arrays; PyTorch requires 2D inputs and 3D weights + aa = a[None, :] + vv = v[None, None, :] + + result = torch.nn.functional.conv1d(aa, vv, padding=padding) + + # torch returns a 2D result, numpy returns a 1D array + return result[0, :] + + +def convolve(a: ArrayLike, v: ArrayLike, mode="full"): + # NumPy: if v is longer than a, the arrays are swapped before computation + if a.shape[0] < v.shape[0]: + a, v = v, a + + # flip the weights since numpy does and torch does not + v = torch.flip(v, (0,)) + + return _conv_corr_impl(a, v, mode) + + +def correlate(a: ArrayLike, v: ArrayLike, mode="valid"): + v = torch.conj_physical(v) + return _conv_corr_impl(a, v, mode) + + +# ### logic & element selection ### + + +def bincount(x: ArrayLike, /, weights: ArrayLike | None = None, minlength=0): + if x.numel() == 0: + # edge case allowed by numpy + x = x.new_empty(0, dtype=int) + + int_dtype = _dtypes_impl.default_dtypes().int_dtype + (x,) = _util.typecast_tensors((x,), int_dtype, casting="safe") + + return torch.bincount(x, weights, minlength) + + +def where( + condition: ArrayLike, + x: ArrayLikeOrScalar | None = None, + y: ArrayLikeOrScalar | None = None, + /, +): + if (x is None) != (y is None): + raise ValueError("either both or neither of x and y should be given") + + if condition.dtype != torch.bool: + condition = condition.to(torch.bool) + + if x is None and y is None: + result = torch.where(condition) + else: + result = torch.where(condition, x, y) + return result + + +# ###### module-level queries of object properties + + +def ndim(a: ArrayLike): + return a.ndim + + +def shape(a: ArrayLike): + return tuple(a.shape) + + +def size(a: ArrayLike, axis=None): + if axis is None: + return a.numel() + else: + return a.shape[axis] + + +# ###### shape manipulations and indexing + + +def expand_dims(a: ArrayLike, axis): + shape = _util.expand_shape(a.shape, axis) + return a.view(shape) # never copies + + +def flip(m: ArrayLike, axis=None): + # XXX: semantic difference: np.flip returns a view, torch.flip copies + if axis is None: + axis = tuple(range(m.ndim)) + else: + axis = _util.normalize_axis_tuple(axis, m.ndim) + return torch.flip(m, axis) + + +def flipud(m: ArrayLike): + return torch.flipud(m) + + +def fliplr(m: ArrayLike): + return torch.fliplr(m) + + +def rot90(m: ArrayLike, k=1, axes=(0, 1)): + axes = _util.normalize_axis_tuple(axes, m.ndim) + return torch.rot90(m, k, axes) + + +# ### broadcasting and indices ### + + +def broadcast_to(array: ArrayLike, shape, subok: NotImplementedType = False): + return torch.broadcast_to(array, size=shape) + + +# This is a function from tuples to tuples, so we just reuse it. However, +# dynamo expects its __module__ to be torch._numpy +def broadcast_shapes(*args): + return torch.broadcast_shapes(*args) + + +def broadcast_arrays(*args: ArrayLike, subok: NotImplementedType = False): + return torch.broadcast_tensors(*args) + + +def meshgrid(*xi: ArrayLike, copy=True, sparse=False, indexing="xy"): + ndim = len(xi) + + if indexing not in ["xy", "ij"]: + raise ValueError("Valid values for `indexing` are 'xy' and 'ij'.") + + s0 = (1,) * ndim + output = [x.reshape(s0[:i] + (-1,) + s0[i + 1 :]) for i, x in enumerate(xi)] + + if indexing == "xy" and ndim > 1: + # switch first and second axis + output[0] = output[0].reshape((1, -1) + s0[2:]) + output[1] = output[1].reshape((-1, 1) + s0[2:]) + + if not sparse: + # Return the full N-D matrix (not only the 1-D vector) + output = torch.broadcast_tensors(*output) + + if copy: + output = [x.clone() for x in output] + + return list(output) # match numpy, return a list + + +def indices(dimensions, dtype: DTypeLike | None = int, sparse=False): + # https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numeric.py#L1691-L1791 + dimensions = tuple(dimensions) + N = len(dimensions) + shape = (1,) * N + if sparse: + res = () + else: + res = torch.empty((N,) + dimensions, dtype=dtype) + for i, dim in enumerate(dimensions): + idx = torch.arange(dim, dtype=dtype).reshape( + shape[:i] + (dim,) + shape[i + 1 :] + ) + if sparse: + res = res + (idx,) + else: + res[i] = idx + return res + + +# ### tri*-something ### + + +def tril(m: ArrayLike, k=0): + return torch.tril(m, k) + + +def triu(m: ArrayLike, k=0): + return torch.triu(m, k) + + +def tril_indices(n, k=0, m=None): + if m is None: + m = n + return torch.tril_indices(n, m, offset=k) + + +def triu_indices(n, k=0, m=None): + if m is None: + m = n + return torch.triu_indices(n, m, offset=k) + + +def tril_indices_from(arr: ArrayLike, k=0): + if arr.ndim != 2: + raise ValueError("input array must be 2-d") + # Return a tensor rather than a tuple to avoid a graphbreak + return torch.tril_indices(arr.shape[0], arr.shape[1], offset=k) + + +def triu_indices_from(arr: ArrayLike, k=0): + if arr.ndim != 2: + raise ValueError("input array must be 2-d") + # Return a tensor rather than a tuple to avoid a graphbreak + return torch.triu_indices(arr.shape[0], arr.shape[1], offset=k) + + +def tri( + N, + M=None, + k=0, + dtype: DTypeLike | None = None, + *, + like: NotImplementedType = None, +): + if M is None: + M = N + tensor = torch.ones((N, M), dtype=dtype) + return torch.tril(tensor, diagonal=k) + + +# ### equality, equivalence, allclose ### + + +def isclose(a: ArrayLike, b: ArrayLike, rtol=1.0e-5, atol=1.0e-8, equal_nan=False): + dtype = _dtypes_impl.result_type_impl(a, b) + a = _util.cast_if_needed(a, dtype) + b = _util.cast_if_needed(b, dtype) + return torch.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan) + + +def allclose(a: ArrayLike, b: ArrayLike, rtol=1e-05, atol=1e-08, equal_nan=False): + dtype = _dtypes_impl.result_type_impl(a, b) + a = _util.cast_if_needed(a, dtype) + b = _util.cast_if_needed(b, dtype) + return torch.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan) + + +def _tensor_equal(a1, a2, equal_nan=False): + # Implementation of array_equal/array_equiv. + if a1.shape != a2.shape: + return False + cond = a1 == a2 + if equal_nan: + cond = cond | (torch.isnan(a1) & torch.isnan(a2)) + return cond.all().item() + + +def array_equal(a1: ArrayLike, a2: ArrayLike, equal_nan=False): + return _tensor_equal(a1, a2, equal_nan=equal_nan) + + +def array_equiv(a1: ArrayLike, a2: ArrayLike): + # *almost* the same as array_equal: _equiv tries to broadcast, _equal does not + try: + a1_t, a2_t = torch.broadcast_tensors(a1, a2) + except RuntimeError: + # failed to broadcast => not equivalent + return False + return _tensor_equal(a1_t, a2_t) + + +def nan_to_num( + x: ArrayLike, copy: NotImplementedType = True, nan=0.0, posinf=None, neginf=None +): + # work around RuntimeError: "nan_to_num" not implemented for 'ComplexDouble' + if x.is_complex(): + re = torch.nan_to_num(x.real, nan=nan, posinf=posinf, neginf=neginf) + im = torch.nan_to_num(x.imag, nan=nan, posinf=posinf, neginf=neginf) + return re + 1j * im + else: + return torch.nan_to_num(x, nan=nan, posinf=posinf, neginf=neginf) + + +# ### put/take_along_axis ### + + +def take( + a: ArrayLike, + indices: ArrayLike, + axis=None, + out: OutArray | None = None, + mode: NotImplementedType = "raise", +): + (a,), axis = _util.axis_none_flatten(a, axis=axis) + axis = _util.normalize_axis_index(axis, a.ndim) + idx = (slice(None),) * axis + (indices, ...) + result = a[idx] + return result + + +def take_along_axis(arr: ArrayLike, indices: ArrayLike, axis): + (arr,), axis = _util.axis_none_flatten(arr, axis=axis) + axis = _util.normalize_axis_index(axis, arr.ndim) + return torch.take_along_dim(arr, indices, axis) + + +def put( + a: NDArray, + indices: ArrayLike, + values: ArrayLike, + mode: NotImplementedType = "raise", +): + v = values.type(a.dtype) + # If indices is larger than v, expand v to at least the size of indices. Any + # unnecessary trailing elements are then trimmed. + if indices.numel() > v.numel(): + ratio = (indices.numel() + v.numel() - 1) // v.numel() + v = v.unsqueeze(0).expand((ratio,) + v.shape) + # Trim unnecessary elements, regardless if v was expanded or not. Note + # np.put() trims v to match indices by default too. + if indices.numel() < v.numel(): + v = v.flatten() + v = v[: indices.numel()] + a.put_(indices, v) + return None + + +def put_along_axis(arr: ArrayLike, indices: ArrayLike, values: ArrayLike, axis): + (arr,), axis = _util.axis_none_flatten(arr, axis=axis) + axis = _util.normalize_axis_index(axis, arr.ndim) + + indices, values = torch.broadcast_tensors(indices, values) + values = _util.cast_if_needed(values, arr.dtype) + result = torch.scatter(arr, axis, indices, values) + arr.copy_(result.reshape(arr.shape)) + return None + + +def choose( + a: ArrayLike, + choices: Sequence[ArrayLike], + out: OutArray | None = None, + mode: NotImplementedType = "raise", +): + # First, broadcast elements of `choices` + choices = torch.stack(torch.broadcast_tensors(*choices)) + + # Use an analog of `gather(choices, 0, a)` which broadcasts `choices` vs `a`: + # (taken from https://github.com/pytorch/pytorch/issues/9407#issuecomment-1427907939) + idx_list = [ + torch.arange(dim).view((1,) * i + (dim,) + (1,) * (choices.ndim - i - 1)) + for i, dim in enumerate(choices.shape) + ] + + idx_list[0] = a + return choices[tuple(idx_list)].squeeze(0) + + +# ### unique et al. ### + + +def unique( + ar: ArrayLike, + return_index: NotImplementedType = False, + return_inverse=False, + return_counts=False, + axis=None, + *, + equal_nan: NotImplementedType = True, +): + (ar,), axis = _util.axis_none_flatten(ar, axis=axis) + axis = _util.normalize_axis_index(axis, ar.ndim) + + result = torch.unique( + ar, return_inverse=return_inverse, return_counts=return_counts, dim=axis + ) + + return result + + +def nonzero(a: ArrayLike): + return torch.nonzero(a, as_tuple=True) + + +def argwhere(a: ArrayLike): + return torch.argwhere(a) + + +def flatnonzero(a: ArrayLike): + return torch.flatten(a).nonzero(as_tuple=True)[0] + + +def clip( + a: ArrayLike, + min: ArrayLike | None = None, + max: ArrayLike | None = None, + out: OutArray | None = None, +): + return torch.clamp(a, min, max) + + +def repeat(a: ArrayLike, repeats: ArrayLikeOrScalar, axis=None): + return torch.repeat_interleave(a, repeats, axis) + + +def tile(A: ArrayLike, reps): + if isinstance(reps, int): + reps = (reps,) + return torch.tile(A, reps) + + +def resize(a: ArrayLike, new_shape=None): + # implementation vendored from + # https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/fromnumeric.py#L1420-L1497 + if new_shape is None: + return a + + if isinstance(new_shape, int): + new_shape = (new_shape,) + + a = a.flatten() + + new_size = 1 + for dim_length in new_shape: + new_size *= dim_length + if dim_length < 0: + raise ValueError("all elements of `new_shape` must be non-negative") + + if a.numel() == 0 or new_size == 0: + # First case must zero fill. The second would have repeats == 0. + return torch.zeros(new_shape, dtype=a.dtype) + + repeats = -(-new_size // a.numel()) # ceil division + a = concatenate((a,) * repeats)[:new_size] + + return reshape(a, new_shape) + + +# ### diag et al. ### + + +def diagonal(a: ArrayLike, offset=0, axis1=0, axis2=1): + axis1 = _util.normalize_axis_index(axis1, a.ndim) + axis2 = _util.normalize_axis_index(axis2, a.ndim) + return torch.diagonal(a, offset, axis1, axis2) + + +def trace( + a: ArrayLike, + offset=0, + axis1=0, + axis2=1, + dtype: DTypeLike | None = None, + out: OutArray | None = None, +): + result = torch.diagonal(a, offset, dim1=axis1, dim2=axis2).sum(-1, dtype=dtype) + return result + + +def eye( + N, + M=None, + k=0, + dtype: DTypeLike | None = None, + order: NotImplementedType = "C", + *, + like: NotImplementedType = None, +): + if dtype is None: + dtype = _dtypes_impl.default_dtypes().float_dtype + if M is None: + M = N + z = torch.zeros(N, M, dtype=dtype) + z.diagonal(k).fill_(1) + return z + + +def identity(n, dtype: DTypeLike | None = None, *, like: NotImplementedType = None): + return torch.eye(n, dtype=dtype) + + +def diag(v: ArrayLike, k=0): + return torch.diag(v, k) + + +def diagflat(v: ArrayLike, k=0): + return torch.diagflat(v, k) + + +def diag_indices(n, ndim=2): + idx = torch.arange(n) + return (idx,) * ndim + + +def diag_indices_from(arr: ArrayLike): + if not arr.ndim >= 2: + raise ValueError("input array must be at least 2-d") + # For more than d=2, the strided formula is only valid for arrays with + # all dimensions equal, so we check first. + s = arr.shape + if s[1:] != s[:-1]: + raise ValueError("All dimensions of input must be of equal length") + return diag_indices(s[0], arr.ndim) + + +def fill_diagonal(a: ArrayLike, val: ArrayLike, wrap=False): + if a.ndim < 2: + raise ValueError("array must be at least 2-d") + if val.numel() == 0 and not wrap: + a.fill_diagonal_(val) + return a + + if val.ndim == 0: + val = val.unsqueeze(0) + + # torch.Tensor.fill_diagonal_ only accepts scalars + # If the size of val is too large, then val is trimmed + if a.ndim == 2: + tall = a.shape[0] > a.shape[1] + # wrap does nothing for wide matrices... + if not wrap or not tall: + # Never wraps + diag = a.diagonal() + diag.copy_(val[: diag.numel()]) + else: + # wraps and tall... leaving one empty line between diagonals?! + max_, min_ = a.shape + idx = torch.arange(max_ - max_ // (min_ + 1)) + mod = idx % min_ + div = idx // min_ + a[(div * (min_ + 1) + mod, mod)] = val[: idx.numel()] + else: + idx = diag_indices_from(a) + # a.shape = (n, n, ..., n) + a[idx] = val[: a.shape[0]] + + return a + + +def vdot(a: ArrayLike, b: ArrayLike, /): + # 1. torch only accepts 1D arrays, numpy flattens + # 2. torch requires matching dtype, while numpy casts (?) + t_a, t_b = torch.atleast_1d(a, b) + if t_a.ndim > 1: + t_a = t_a.flatten() + if t_b.ndim > 1: + t_b = t_b.flatten() + + dtype = _dtypes_impl.result_type_impl(t_a, t_b) + is_half = dtype == torch.float16 and (t_a.is_cpu or t_b.is_cpu) + is_bool = dtype == torch.bool + + # work around torch's "dot" not implemented for 'Half', 'Bool' + if is_half: + dtype = torch.float32 + elif is_bool: + dtype = torch.uint8 + + t_a = _util.cast_if_needed(t_a, dtype) + t_b = _util.cast_if_needed(t_b, dtype) + + result = torch.vdot(t_a, t_b) + + if is_half: + result = result.to(torch.float16) + elif is_bool: + result = result.to(torch.bool) + + return result + + +def tensordot(a: ArrayLike, b: ArrayLike, axes=2): + if isinstance(axes, (list, tuple)): + axes = [[ax] if isinstance(ax, int) else ax for ax in axes] + + target_dtype = _dtypes_impl.result_type_impl(a, b) + a = _util.cast_if_needed(a, target_dtype) + b = _util.cast_if_needed(b, target_dtype) + + return torch.tensordot(a, b, dims=axes) + + +def dot(a: ArrayLike, b: ArrayLike, out: OutArray | None = None): + dtype = _dtypes_impl.result_type_impl(a, b) + is_bool = dtype == torch.bool + if is_bool: + dtype = torch.uint8 + + a = _util.cast_if_needed(a, dtype) + b = _util.cast_if_needed(b, dtype) + + if a.ndim == 0 or b.ndim == 0: + result = a * b + else: + result = torch.matmul(a, b) + + if is_bool: + result = result.to(torch.bool) + + return result + + +def inner(a: ArrayLike, b: ArrayLike, /): + dtype = _dtypes_impl.result_type_impl(a, b) + is_half = dtype == torch.float16 and (a.is_cpu or b.is_cpu) + is_bool = dtype == torch.bool + + if is_half: + # work around torch's "addmm_impl_cpu_" not implemented for 'Half'" + dtype = torch.float32 + elif is_bool: + dtype = torch.uint8 + + a = _util.cast_if_needed(a, dtype) + b = _util.cast_if_needed(b, dtype) + + result = torch.inner(a, b) + + if is_half: + result = result.to(torch.float16) + elif is_bool: + result = result.to(torch.bool) + return result + + +def outer(a: ArrayLike, b: ArrayLike, out: OutArray | None = None): + return torch.outer(a, b) + + +def cross(a: ArrayLike, b: ArrayLike, axisa=-1, axisb=-1, axisc=-1, axis=None): + # implementation vendored from + # https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numeric.py#L1486-L1685 + if axis is not None: + axisa, axisb, axisc = (axis,) * 3 + + # Check axisa and axisb are within bounds + axisa = _util.normalize_axis_index(axisa, a.ndim) + axisb = _util.normalize_axis_index(axisb, b.ndim) + + # Move working axis to the end of the shape + a = torch.moveaxis(a, axisa, -1) + b = torch.moveaxis(b, axisb, -1) + msg = "incompatible dimensions for cross product\n(dimension must be 2 or 3)" + if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3): + raise ValueError(msg) + + # Create the output array + shape = broadcast_shapes(a[..., 0].shape, b[..., 0].shape) + if a.shape[-1] == 3 or b.shape[-1] == 3: + shape += (3,) + # Check axisc is within bounds + axisc = _util.normalize_axis_index(axisc, len(shape)) + dtype = _dtypes_impl.result_type_impl(a, b) + cp = torch.empty(shape, dtype=dtype) + + # recast arrays as dtype + a = _util.cast_if_needed(a, dtype) + b = _util.cast_if_needed(b, dtype) + + # create local aliases for readability + a0 = a[..., 0] + a1 = a[..., 1] + if a.shape[-1] == 3: + a2 = a[..., 2] + b0 = b[..., 0] + b1 = b[..., 1] + if b.shape[-1] == 3: + b2 = b[..., 2] + if cp.ndim != 0 and cp.shape[-1] == 3: + cp0 = cp[..., 0] + cp1 = cp[..., 1] + cp2 = cp[..., 2] + + if a.shape[-1] == 2: + if b.shape[-1] == 2: + # a0 * b1 - a1 * b0 + cp[...] = a0 * b1 - a1 * b0 + return cp + else: + if b.shape[-1] != 3: + raise AssertionError(f"b.shape[-1] must be 3, got {b.shape[-1]}") + # cp0 = a1 * b2 - 0 (a2 = 0) + # cp1 = 0 - a0 * b2 (a2 = 0) + # cp2 = a0 * b1 - a1 * b0 + cp0[...] = a1 * b2 + cp1[...] = -a0 * b2 + cp2[...] = a0 * b1 - a1 * b0 + else: + if a.shape[-1] != 3: + raise AssertionError(f"a.shape[-1] must be 3, got {a.shape[-1]}") + if b.shape[-1] == 3: + cp0[...] = a1 * b2 - a2 * b1 + cp1[...] = a2 * b0 - a0 * b2 + cp2[...] = a0 * b1 - a1 * b0 + else: + if b.shape[-1] != 2: + raise AssertionError(f"b.shape[-1] must be 2, got {b.shape[-1]}") + cp0[...] = -a2 * b1 + cp1[...] = a2 * b0 + cp2[...] = a0 * b1 - a1 * b0 + + return torch.moveaxis(cp, -1, axisc) + + +def einsum(*operands, out=None, dtype=None, order="K", casting="safe", optimize=False): + # Have to manually normalize *operands and **kwargs, following the NumPy signature + # We have a local import to avoid polluting the global space, as it will be then + # exported in funcs.py + from ._ndarray import ndarray + from ._normalizations import ( + maybe_copy_to, + normalize_array_like, + normalize_casting, + normalize_dtype, + wrap_tensors, + ) + + dtype = normalize_dtype(dtype) + casting = normalize_casting(casting) + if out is not None and not isinstance(out, ndarray): + raise TypeError("'out' must be an array") + if order != "K": + raise NotImplementedError("'order' parameter is not supported.") + + # parse arrays and normalize them + sublist_format = not isinstance(operands[0], str) + if sublist_format: + # op, str, op, str ... [sublistout] format: normalize every other argument + + # - if sublistout is not given, the length of operands is even, and we pick + # odd-numbered elements, which are arrays. + # - if sublistout is given, the length of operands is odd, we peel off + # the last one, and pick odd-numbered elements, which are arrays. + # Without [:-1], we would have picked sublistout, too. + array_operands = operands[:-1][::2] + else: + # ("ij->", arrays) format + subscripts, array_operands = operands[0], operands[1:] + + tensors = [normalize_array_like(op) for op in array_operands] + target_dtype = _dtypes_impl.result_type_impl(*tensors) if dtype is None else dtype + + # work around 'bmm' not implemented for 'Half' etc + is_half = target_dtype == torch.float16 and all(t.is_cpu for t in tensors) + if is_half: + target_dtype = torch.float32 + + is_short_int = target_dtype in [torch.uint8, torch.int8, torch.int16, torch.int32] + if is_short_int: + target_dtype = torch.int64 + + tensors = _util.typecast_tensors(tensors, target_dtype, casting) + + from torch.backends import opt_einsum + + try: + # set the global state to handle the optimize=... argument, restore on exit + if opt_einsum.is_available(): + old_strategy = torch.backends.opt_einsum.strategy + old_enabled = torch.backends.opt_einsum.enabled + + # torch.einsum calls opt_einsum.contract_path, which runs into + # https://github.com/dgasmith/opt_einsum/issues/219 + # for strategy={True, False} + if optimize is True: + optimize = "auto" + elif optimize is False: + torch.backends.opt_einsum.enabled = False + + torch.backends.opt_einsum.strategy = optimize + + if sublist_format: + # recombine operands + sublists = operands[1::2] + has_sublistout = len(operands) % 2 == 1 + if has_sublistout: + sublistout = operands[-1] + operands = list(itertools.chain.from_iterable(zip(tensors, sublists))) + if has_sublistout: + operands.append(sublistout) + + result = torch.einsum(*operands) + else: + result = torch.einsum(subscripts, *tensors) + + finally: + if opt_einsum.is_available(): + torch.backends.opt_einsum.strategy = old_strategy + torch.backends.opt_einsum.enabled = old_enabled + + result = maybe_copy_to(out, result) + return wrap_tensors(result) + + +# ### sort and partition ### + + +def _sort_helper(tensor, axis, kind, order): + if tensor.dtype.is_complex: + raise NotImplementedError(f"sorting {tensor.dtype} is not supported") + (tensor,), axis = _util.axis_none_flatten(tensor, axis=axis) + axis = _util.normalize_axis_index(axis, tensor.ndim) + + stable = kind == "stable" + + return tensor, axis, stable + + +def sort(a: ArrayLike, axis=-1, kind=None, order: NotImplementedType = None): + # `order` keyword arg is only relevant for structured dtypes; so not supported here. + a, axis, stable = _sort_helper(a, axis, kind, order) + result = torch.sort(a, dim=axis, stable=stable) + return result.values + + +def argsort(a: ArrayLike, axis=-1, kind=None, order: NotImplementedType = None): + a, axis, stable = _sort_helper(a, axis, kind, order) + return torch.argsort(a, dim=axis, stable=stable) + + +def searchsorted( + a: ArrayLike, v: ArrayLike, side="left", sorter: ArrayLike | None = None +): + if a.dtype.is_complex: + raise NotImplementedError(f"searchsorted with dtype={a.dtype}") + + return torch.searchsorted(a, v, side=side, sorter=sorter) + + +# ### swap/move/roll axis ### + + +def moveaxis(a: ArrayLike, source, destination): + source = _util.normalize_axis_tuple(source, a.ndim, "source") + destination = _util.normalize_axis_tuple(destination, a.ndim, "destination") + return torch.moveaxis(a, source, destination) + + +def swapaxes(a: ArrayLike, axis1, axis2): + axis1 = _util.normalize_axis_index(axis1, a.ndim) + axis2 = _util.normalize_axis_index(axis2, a.ndim) + return torch.swapaxes(a, axis1, axis2) + + +def rollaxis(a: ArrayLike, axis, start=0): + # Straight vendor from: + # https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numeric.py#L1259 + # + # Also note this function in NumPy is mostly retained for backwards compat + # (https://stackoverflow.com/questions/29891583/reason-why-numpy-rollaxis-is-so-confusing) + # so let's not touch it unless hard pressed. + n = a.ndim + axis = _util.normalize_axis_index(axis, n) + if start < 0: + start += n + msg = "'%s' arg requires %d <= %s < %d, but %d was passed in" + if not (0 <= start < n + 1): + raise _util.AxisError(msg % ("start", -n, "start", n + 1, start)) + if axis < start: + # it's been removed + start -= 1 + if axis == start: + # numpy returns a view, here we try returning the tensor itself + # return tensor[...] + return a + axes = list(range(n)) + axes.remove(axis) + axes.insert(start, axis) + return a.view(axes) + + +def roll(a: ArrayLike, shift, axis=None): + if axis is not None: + axis = _util.normalize_axis_tuple(axis, a.ndim, allow_duplicate=True) + if not isinstance(shift, tuple): + shift = (shift,) * len(axis) + return torch.roll(a, shift, axis) + + +# ### shape manipulations ### + + +def squeeze(a: ArrayLike, axis=None): + if axis == (): + result = a + elif axis is None: + result = a.squeeze() + else: + if isinstance(axis, tuple): + result = a + for ax in axis: + result = a.squeeze(ax) + else: + result = a.squeeze(axis) + return result + + +def reshape(a: ArrayLike, newshape, order: NotImplementedType = "C"): + # if sh = (1, 2, 3), numpy allows both .reshape(sh) and .reshape(*sh) + newshape = newshape[0] if len(newshape) == 1 else newshape + return a.reshape(newshape) + + +# NB: cannot use torch.reshape(a, newshape) above, because of +# (Pdb) torch.reshape(torch.as_tensor([1]), 1) +# *** TypeError: reshape(): argument 'shape' (position 2) must be tuple of SymInts, not int + + +def transpose(a: ArrayLike, axes=None): + # numpy allows both .transpose(sh) and .transpose(*sh) + # also older code uses axes being a list + if axes in [(), None, (None,)]: + axes = tuple(reversed(range(a.ndim))) + elif len(axes) == 1: + axes = axes[0] + return a.permute(axes) + + +def ravel(a: ArrayLike, order: NotImplementedType = "C"): + return torch.flatten(a) + + +def diff( + a: ArrayLike, + n=1, + axis=-1, + prepend: ArrayLike | None = None, + append: ArrayLike | None = None, +): + axis = _util.normalize_axis_index(axis, a.ndim) + + if n < 0: + raise ValueError(f"order must be non-negative but got {n}") + + if n == 0: + # match numpy and return the input immediately + return a + + if prepend is not None: + shape = list(a.shape) + shape[axis] = prepend.shape[axis] if prepend.ndim > 0 else 1 + prepend = torch.broadcast_to(prepend, shape) + + if append is not None: + shape = list(a.shape) + shape[axis] = append.shape[axis] if append.ndim > 0 else 1 + append = torch.broadcast_to(append, shape) + + return torch.diff(a, n, axis=axis, prepend=prepend, append=append) + + +# ### math functions ### + + +def angle(z: ArrayLike, deg=False): + result = torch.angle(z) + if deg: + result = result * (180 / torch.pi) + return result + + +def sinc(x: ArrayLike): + return torch.sinc(x) + + +# NB: have to normalize *varargs manually +def gradient(f: ArrayLike, *varargs, axis=None, edge_order=1): + N = f.ndim # number of dimensions + + varargs = _util.ndarrays_to_tensors(varargs) + + if axis is None: + axes = tuple(range(N)) + else: + axes = _util.normalize_axis_tuple(axis, N) + + len_axes = len(axes) + n = len(varargs) + if n == 0: + # no spacing argument - use 1 in all axes + dx = [1.0] * len_axes + elif n == 1 and (_dtypes_impl.is_scalar(varargs[0]) or varargs[0].ndim == 0): + # single scalar or 0D tensor for all axes (np.ndim(varargs[0]) == 0) + dx = varargs * len_axes + elif n == len_axes: + # scalar or 1d array for each axis + dx = list(varargs) + for i, distances in enumerate(dx): + distances = torch.as_tensor(distances) + if distances.ndim == 0: + continue + elif distances.ndim != 1: + raise ValueError("distances must be either scalars or 1d") + if len(distances) != f.shape[axes[i]]: + raise ValueError( + "when 1d, distances must match " + "the length of the corresponding dimension" + ) + if not (distances.dtype.is_floating_point or distances.dtype.is_complex): + distances = distances.double() + + diffx = torch.diff(distances) + # if distances are constant reduce to the scalar case + # since it brings a consistent speedup + if (diffx == diffx[0]).all(): + diffx = diffx[0] + dx[i] = diffx + else: + raise TypeError("invalid number of arguments") + + if edge_order > 2: + raise ValueError("'edge_order' greater than 2 not supported") + + # use central differences on interior and one-sided differences on the + # endpoints. This preserves second order-accuracy over the full domain. + + outvals = [] + + # create slice objects --- initially all are [:, :, ..., :] + slice1 = [slice(None)] * N + slice2 = [slice(None)] * N + slice3 = [slice(None)] * N + slice4 = [slice(None)] * N + + otype = f.dtype + if _dtypes_impl.python_type_for_torch(otype) in (int, bool): + # Convert to floating point. + # First check if f is a numpy integer type; if so, convert f to float64 + # to avoid modular arithmetic when computing the changes in f. + f = f.double() + otype = torch.float64 + + for axis, ax_dx in zip(axes, dx): + if f.shape[axis] < edge_order + 1: + raise ValueError( + "Shape of array too small to calculate a numerical gradient, " + "at least (edge_order + 1) elements are required." + ) + # result allocation + out = torch.empty_like(f, dtype=otype) + + # spacing for the current axis (NB: np.ndim(ax_dx) == 0) + uniform_spacing = _dtypes_impl.is_scalar(ax_dx) or ax_dx.ndim == 0 + + # Numerical differentiation: 2nd order interior + slice1[axis] = slice(1, -1) + slice2[axis] = slice(None, -2) + slice3[axis] = slice(1, -1) + slice4[axis] = slice(2, None) + + if uniform_spacing: + out[tuple(slice1)] = (f[tuple(slice4)] - f[tuple(slice2)]) / (2.0 * ax_dx) + else: + dx1 = ax_dx[0:-1] + dx2 = ax_dx[1:] + a = -(dx2) / (dx1 * (dx1 + dx2)) + b = (dx2 - dx1) / (dx1 * dx2) + c = dx1 / (dx2 * (dx1 + dx2)) + # fix the shape for broadcasting + shape = [1] * N + shape[axis] = -1 + a = a.reshape(shape) + b = b.reshape(shape) + c = c.reshape(shape) + # 1D equivalent -- out[1:-1] = a * f[:-2] + b * f[1:-1] + c * f[2:] + out[tuple(slice1)] = ( + a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)] + ) + + # Numerical differentiation: 1st order edges + if edge_order == 1: + slice1[axis] = 0 + slice2[axis] = 1 + slice3[axis] = 0 + dx_0 = ax_dx if uniform_spacing else ax_dx[0] + # 1D equivalent -- out[0] = (f[1] - f[0]) / (x[1] - x[0]) + out[tuple(slice1)] = (f[tuple(slice2)] - f[tuple(slice3)]) / dx_0 + + slice1[axis] = -1 + slice2[axis] = -1 + slice3[axis] = -2 + dx_n = ax_dx if uniform_spacing else ax_dx[-1] + # 1D equivalent -- out[-1] = (f[-1] - f[-2]) / (x[-1] - x[-2]) + out[tuple(slice1)] = (f[tuple(slice2)] - f[tuple(slice3)]) / dx_n + + # Numerical differentiation: 2nd order edges + else: + slice1[axis] = 0 + slice2[axis] = 0 + slice3[axis] = 1 + slice4[axis] = 2 + if uniform_spacing: + a = -1.5 / ax_dx + b = 2.0 / ax_dx + c = -0.5 / ax_dx + else: + dx1 = ax_dx[0] + dx2 = ax_dx[1] + a = -(2.0 * dx1 + dx2) / (dx1 * (dx1 + dx2)) + b = (dx1 + dx2) / (dx1 * dx2) + c = -dx1 / (dx2 * (dx1 + dx2)) + # 1D equivalent -- out[0] = a * f[0] + b * f[1] + c * f[2] + out[tuple(slice1)] = ( + a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)] + ) + + slice1[axis] = -1 + slice2[axis] = -3 + slice3[axis] = -2 + slice4[axis] = -1 + if uniform_spacing: + a = 0.5 / ax_dx + b = -2.0 / ax_dx + c = 1.5 / ax_dx + else: + dx1 = ax_dx[-2] + dx2 = ax_dx[-1] + a = (dx2) / (dx1 * (dx1 + dx2)) + b = -(dx2 + dx1) / (dx1 * dx2) + c = (2.0 * dx2 + dx1) / (dx2 * (dx1 + dx2)) + # 1D equivalent -- out[-1] = a * f[-3] + b * f[-2] + c * f[-1] + out[tuple(slice1)] = ( + a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)] + ) + + outvals.append(out) + + # reset the slice object in this dimension to ":" + slice1[axis] = slice(None) + slice2[axis] = slice(None) + slice3[axis] = slice(None) + slice4[axis] = slice(None) + + if len_axes == 1: + return outvals[0] + else: + return outvals + + +# ### Type/shape etc queries ### + + +def round(a: ArrayLike, decimals=0, out: OutArray | None = None): + if a.is_floating_point(): + result = torch.round(a, decimals=decimals) + elif a.is_complex(): + # RuntimeError: "round_cpu" not implemented for 'ComplexFloat' + result = torch.complex( + torch.round(a.real, decimals=decimals), + torch.round(a.imag, decimals=decimals), + ) + else: + # RuntimeError: "round_cpu" not implemented for 'int' + result = a + return result + + +around = round +round_ = round + + +def real_if_close(a: ArrayLike, tol=100): + if not torch.is_complex(a): + return a + if tol > 1: + # Undocumented in numpy: if tol < 1, it's an absolute tolerance! + # Otherwise, tol > 1 is relative tolerance, in units of the dtype epsilon + # https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/type_check.py#L577 + tol = tol * torch.finfo(a.dtype).eps + + mask = torch.abs(a.imag) < tol + return a.real if mask.all() else a + + +def real(a: ArrayLike): + return torch.real(a) + + +def imag(a: ArrayLike): + if a.is_complex(): + return a.imag + return torch.zeros_like(a) + + +def iscomplex(x: ArrayLike): + if torch.is_complex(x): + return x.imag != 0 + return torch.zeros_like(x, dtype=torch.bool) + + +def isreal(x: ArrayLike): + if torch.is_complex(x): + return x.imag == 0 + return torch.ones_like(x, dtype=torch.bool) + + +def iscomplexobj(x: ArrayLike): + return torch.is_complex(x) + + +def isrealobj(x: ArrayLike): + return not torch.is_complex(x) + + +def isneginf(x: ArrayLike, out: OutArray | None = None): + return torch.isneginf(x) + + +def isposinf(x: ArrayLike, out: OutArray | None = None): + return torch.isposinf(x) + + +def i0(x: ArrayLike): + return torch.special.i0(x) + + +def isscalar(a): + # We need to use normalize_array_like, but we don't want to export it in funcs.py + from ._normalizations import normalize_array_like + + try: + t = normalize_array_like(a) + return t.numel() == 1 + except Exception: + return False + + +# ### Filter windows ### + + +def hamming(M): + dtype = _dtypes_impl.default_dtypes().float_dtype + return torch.hamming_window(M, periodic=False, dtype=dtype) + + +def hanning(M): + dtype = _dtypes_impl.default_dtypes().float_dtype + return torch.hann_window(M, periodic=False, dtype=dtype) + + +def kaiser(M, beta): + dtype = _dtypes_impl.default_dtypes().float_dtype + return torch.kaiser_window(M, beta=beta, periodic=False, dtype=dtype) + + +def blackman(M): + dtype = _dtypes_impl.default_dtypes().float_dtype + return torch.blackman_window(M, periodic=False, dtype=dtype) + + +def bartlett(M): + dtype = _dtypes_impl.default_dtypes().float_dtype + return torch.bartlett_window(M, periodic=False, dtype=dtype) + + +# ### Dtype routines ### + +# vendored from https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/type_check.py#L666 + + +array_type = [ + [torch.float16, torch.float32, torch.float64], + [None, torch.complex64, torch.complex128], +] +array_precision = { + torch.float16: 0, + torch.float32: 1, + torch.float64: 2, + torch.complex64: 1, + torch.complex128: 2, +} + + +def common_type(*tensors: ArrayLike): + is_complex = False + precision = 0 + for a in tensors: + t = a.dtype + if iscomplexobj(a): + is_complex = True + if not (t.is_floating_point or t.is_complex): + p = 2 # array_precision[_nx.double] + else: + p = array_precision.get(t) + if p is None: + raise TypeError("can't get common type for non-numeric array") + precision = builtins.max(precision, p) + if is_complex: + return array_type[1][precision] + else: + return array_type[0][precision] + + +# ### histograms ### + + +def histogram( + a: ArrayLike, + bins: ArrayLike = 10, + range=None, + normed=None, + weights: ArrayLike | None = None, + density=None, +): + if normed is not None: + raise ValueError("normed argument is deprecated, use density= instead") + + if weights is not None and weights.dtype.is_complex: + raise NotImplementedError("complex weights histogram.") + + is_a_int = not (a.dtype.is_floating_point or a.dtype.is_complex) + is_w_int = weights is None or not weights.dtype.is_floating_point + if is_a_int: + a = a.double() + + if weights is not None: + weights = _util.cast_if_needed(weights, a.dtype) + + if isinstance(bins, torch.Tensor): + if bins.ndim == 0: + # bins was a single int + bins = operator.index(bins) + else: + bins = _util.cast_if_needed(bins, a.dtype) + + if range is None: + h, b = torch.histogram(a, bins, weight=weights, density=bool(density)) + else: + h, b = torch.histogram( + a, bins, range=range, weight=weights, density=bool(density) + ) + + if not density and is_w_int: + h = h.long() + if is_a_int: + b = b.long() + + return h, b + + +def histogram2d( + x, + y, + bins=10, + range: ArrayLike | None = None, + normed=None, + weights: ArrayLike | None = None, + density=None, +): + # vendored from https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/twodim_base.py#L655-L821 + if len(x) != len(y): + raise ValueError("x and y must have the same length.") + + try: + N = len(bins) + except TypeError: + N = 1 + + if N != 1 and N != 2: + bins = [bins, bins] + + h, e = histogramdd((x, y), bins, range, normed, weights, density) + + return h, e[0], e[1] + + +def histogramdd( + sample, + bins=10, + range: ArrayLike | None = None, + normed=None, + weights: ArrayLike | None = None, + density=None, +): + # have to normalize manually because `sample` interpretation differs + # for a list of lists and a 2D array + if normed is not None: + raise ValueError("normed argument is deprecated, use density= instead") + + from ._normalizations import normalize_array_like, normalize_seq_array_like + + if isinstance(sample, (list, tuple)): + sample = normalize_array_like(sample).T + else: + sample = normalize_array_like(sample) + + sample = torch.atleast_2d(sample) + + if not (sample.dtype.is_floating_point or sample.dtype.is_complex): + sample = sample.double() + + # bins is either an int, or a sequence of ints or a sequence of arrays + bins_is_array = not ( + isinstance(bins, int) or builtins.all(isinstance(b, int) for b in bins) + ) + if bins_is_array: + bins = normalize_seq_array_like(bins) + bins_dtypes = [b.dtype for b in bins] + bins = [_util.cast_if_needed(b, sample.dtype) for b in bins] + + if range is not None: + range = range.flatten().tolist() + + if weights is not None: + # range=... is required : interleave min and max values per dimension + mm = sample.aminmax(dim=0) + range = torch.cat(mm).reshape(2, -1).T.flatten() + range = tuple(range.tolist()) + weights = _util.cast_if_needed(weights, sample.dtype) + w_kwd = {"weight": weights} + else: + w_kwd = {} + + h, b = torch.histogramdd(sample, bins, range, density=bool(density), **w_kwd) + + if bins_is_array: + b = [_util.cast_if_needed(bb, dtyp) for bb, dtyp in zip(b, bins_dtypes)] + + return h, b + + +# ### odds and ends + + +def min_scalar_type(a: ArrayLike, /): + # https://github.com/numpy/numpy/blob/maintenance/1.24.x/numpy/core/src/multiarray/convert_datatype.c#L1288 + + from ._dtypes import DType + + if a.numel() > 1: + # numpy docs: "For non-scalar array a, returns the vector's dtype unmodified." + return DType(a.dtype) + + if a.dtype == torch.bool: + dtype = torch.bool + + elif a.dtype.is_complex: + fi = torch.finfo(torch.float32) + fits_in_single = a.dtype == torch.complex64 or ( + fi.min <= a.real <= fi.max and fi.min <= a.imag <= fi.max + ) + dtype = torch.complex64 if fits_in_single else torch.complex128 + + elif a.dtype.is_floating_point: + for dt in [torch.float16, torch.float32, torch.float64]: + fi = torch.finfo(dt) + if fi.min <= a <= fi.max: + dtype = dt + break + else: + # must be integer + for dt in [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]: + # Prefer unsigned int where possible, as numpy does. + ii = torch.iinfo(dt) + if ii.min <= a <= ii.max: + dtype = dt + break + + return DType(dtype) + + +def pad(array: ArrayLike, pad_width: ArrayLike, mode="constant", **kwargs): + if mode != "constant": + raise NotImplementedError + value = kwargs.get("constant_values", 0) + # `value` must be a python scalar for torch.nn.functional.pad + typ = _dtypes_impl.python_type_for_torch(array.dtype) + value = typ(value) + + pad_width = torch.broadcast_to(pad_width, (array.ndim, 2)) + pad_width = torch.flip(pad_width, (0,)).flatten() + + return torch.nn.functional.pad(array, tuple(pad_width), value=value) diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_getlimits.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_getlimits.py new file mode 100644 index 0000000000000000000000000000000000000000..b0c46094e8782f8309ba6cfa15cb59f93cf667a0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_getlimits.py @@ -0,0 +1,15 @@ +# mypy: ignore-errors + +import torch + +from . import _dtypes + + +def finfo(dtyp): + torch_dtype = _dtypes.dtype(dtyp).torch_dtype + return torch.finfo(torch_dtype) + + +def iinfo(dtyp): + torch_dtype = _dtypes.dtype(dtyp).torch_dtype + return torch.iinfo(torch_dtype) diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_ndarray.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_ndarray.py new file mode 100644 index 0000000000000000000000000000000000000000..e55c119373c869a5a99e51ad1521d0487ebf3ecb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_ndarray.py @@ -0,0 +1,733 @@ +# mypy: ignore-errors + +from __future__ import annotations + +import builtins +import math +import operator +from collections.abc import Sequence + +import torch + +from . import _dtypes, _dtypes_impl, _funcs, _ufuncs, _util +from ._normalizations import ( + ArrayLike, + normalize_array_like, + normalizer, + NotImplementedType, +) + + +newaxis = None + +FLAGS = [ + "C_CONTIGUOUS", + "F_CONTIGUOUS", + "OWNDATA", + "WRITEABLE", + "ALIGNED", + "WRITEBACKIFCOPY", + "FNC", + "FORC", + "BEHAVED", + "CARRAY", + "FARRAY", +] + +SHORTHAND_TO_FLAGS = { + "C": "C_CONTIGUOUS", + "F": "F_CONTIGUOUS", + "O": "OWNDATA", + "W": "WRITEABLE", + "A": "ALIGNED", + "X": "WRITEBACKIFCOPY", + "B": "BEHAVED", + "CA": "CARRAY", + "FA": "FARRAY", +} + + +class Flags: + def __init__(self, flag_to_value: dict): + invalid_keys = [k for k in flag_to_value if k not in FLAGS] + if invalid_keys: + raise AssertionError(f"Invalid flag keys: {invalid_keys}") + self._flag_to_value = flag_to_value + + def __getattr__(self, attr: str): + if attr.islower() and attr.upper() in FLAGS: + return self[attr.upper()] + else: + raise AttributeError(f"No flag attribute '{attr}'") + + def __getitem__(self, key): + if key in SHORTHAND_TO_FLAGS: + key = SHORTHAND_TO_FLAGS[key] + if key in FLAGS: + try: + return self._flag_to_value[key] + except KeyError as e: + raise NotImplementedError(f"{key=}") from e + else: + raise KeyError(f"No flag key '{key}'") + + def __setattr__(self, attr, value): + if attr.islower() and attr.upper() in FLAGS: + self[attr.upper()] = value + else: + super().__setattr__(attr, value) + + def __setitem__(self, key, value): + if key in FLAGS or key in SHORTHAND_TO_FLAGS: + raise NotImplementedError("Modifying flags is not implemented") + else: + raise KeyError(f"No flag key '{key}'") + + +def create_method(fn, name=None): + name = name or fn.__name__ + + def f(*args, **kwargs): + return fn(*args, **kwargs) + + f.__name__ = name + f.__qualname__ = f"ndarray.{name}" + return f + + +# Map ndarray.name_method -> np.name_func +# If name_func == None, it means that name_method == name_func +methods = { + "clip": None, + "nonzero": None, + "repeat": None, + "round": None, + "squeeze": None, + "swapaxes": None, + "ravel": None, + # linalg + "diagonal": None, + "dot": None, + "trace": None, + # sorting + "argsort": None, + "searchsorted": None, + # reductions + "argmax": None, + "argmin": None, + "any": None, + "all": None, + "max": None, + "min": None, + "ptp": None, + "sum": None, + "prod": None, + "mean": None, + "var": None, + "std": None, + # scans + "cumsum": None, + "cumprod": None, + # advanced indexing + "take": None, + "choose": None, +} + +dunder = { + "abs": "absolute", + "invert": None, + "pos": "positive", + "neg": "negative", + "gt": "greater", + "lt": "less", + "ge": "greater_equal", + "le": "less_equal", +} + +# dunder methods with right-looking and in-place variants +ri_dunder = { + "add": None, + "sub": "subtract", + "mul": "multiply", + "truediv": "divide", + "floordiv": "floor_divide", + "pow": "power", + "mod": "remainder", + "and": "bitwise_and", + "or": "bitwise_or", + "xor": "bitwise_xor", + "lshift": "left_shift", + "rshift": "right_shift", + "matmul": None, +} + + +def _upcast_int_indices(index): + if isinstance(index, torch.Tensor): + if index.dtype in (torch.int8, torch.int16, torch.int32, torch.uint8): + return index.to(torch.int64) + elif isinstance(index, tuple): + return tuple(_upcast_int_indices(i) for i in index) + return index + + +def _has_advanced_indexing(index): + """Check if there's any advanced indexing""" + return any( + isinstance(idx, (Sequence, bool)) + or (isinstance(idx, torch.Tensor) and (idx.dtype == torch.bool or idx.ndim > 0)) + for idx in index + ) + + +def _numpy_compatible_indexing(index): + """Convert scalar indices to lists when advanced indexing is present for NumPy compatibility.""" + if not isinstance(index, tuple): + index = (index,) + + # Check if there's any advanced indexing (sequences, booleans, or tensors) + has_advanced = _has_advanced_indexing(index) + + if not has_advanced: + return index + + # Convert integer scalar indices to single-element lists when advanced indexing is present + # Note: Do NOT convert boolean scalars (True/False) as they have special meaning in NumPy + converted = [] + for idx in index: + if isinstance(idx, int) and not isinstance(idx, bool): + # Integer scalars should be converted to lists + converted.append([idx]) + elif ( + isinstance(idx, torch.Tensor) + and idx.ndim == 0 + and not torch.is_floating_point(idx) + and idx.dtype != torch.bool + ): + # Zero-dimensional tensors holding integers should be treated the same as integer scalars + converted.append([idx]) + else: + # Everything else (booleans, lists, slices, etc.) stays as is + converted.append(idx) + + return tuple(converted) + + +def _get_bool_depth(s): + """Returns the depth of a boolean sequence/tensor""" + if isinstance(s, bool): + return True, 0 + if isinstance(s, torch.Tensor) and s.dtype == torch.bool: + return True, s.ndim + if not (isinstance(s, Sequence) and s and s[0] != s): + return False, 0 + is_bool, depth = _get_bool_depth(s[0]) + return is_bool, depth + 1 + + +def _numpy_empty_ellipsis_patch(index, tensor_ndim): + """ + Patch for NumPy-compatible ellipsis behavior when ellipsis doesn't match any dimensions. + + In NumPy, when an ellipsis (...) doesn't actually match any dimensions of the input array, + it still acts as a separator between advanced indices. PyTorch doesn't have this behavior. + + This function detects when we have: + 1. Advanced indexing on both sides of an ellipsis + 2. The ellipsis doesn't actually match any dimensions + """ + if not isinstance(index, tuple): + index = (index,) + + # Find ellipsis position + ellipsis_pos = None + for i, idx in enumerate(index): + if idx is Ellipsis: + ellipsis_pos = i + break + + # If no ellipsis, no patch needed + if ellipsis_pos is None: + return index, lambda x: x, lambda x: x + + # Count non-ellipsis dimensions consumed by the index + consumed_dims = 0 + for idx in index: + is_bool, depth = _get_bool_depth(idx) + if is_bool: + consumed_dims += depth + elif idx is Ellipsis or idx is None: + continue + else: + consumed_dims += 1 + + # Calculate how many dimensions the ellipsis should match + ellipsis_dims = tensor_ndim - consumed_dims + + # Check if ellipsis doesn't match any dimensions + if ellipsis_dims == 0: + # Check if we have advanced indexing on both sides of ellipsis + left_advanced = _has_advanced_indexing(index[:ellipsis_pos]) + right_advanced = _has_advanced_indexing(index[ellipsis_pos + 1 :]) + + if left_advanced and right_advanced: + # This is the case where NumPy and PyTorch differ + # We need to ensure the advanced indices are treated as separated + new_index = index[:ellipsis_pos] + (None,) + index[ellipsis_pos + 1 :] + end_ndims = 1 + sum( + 1 for idx in index[ellipsis_pos + 1 :] if isinstance(idx, slice) + ) + + def squeeze_fn(x): + return x.squeeze(-end_ndims) + + def unsqueeze_fn(x): + if isinstance(x, torch.Tensor) and x.ndim >= end_ndims: + return x.unsqueeze(-end_ndims) + return x + + return new_index, squeeze_fn, unsqueeze_fn + + return index, lambda x: x, lambda x: x + + +# Used to indicate that a parameter is unspecified (as opposed to explicitly +# `None`) +class _Unspecified: + pass + + +_Unspecified.unspecified = _Unspecified() + +############################################################### +# ndarray class # +############################################################### + + +class ndarray: + def __init__(self, t=None): + if t is None: + self.tensor = torch.Tensor() + elif isinstance(t, torch.Tensor): + self.tensor = t + else: + raise ValueError( + "ndarray constructor is not recommended; prefer" + "either array(...) or zeros/empty(...)" + ) + + # Register NumPy functions as methods + for method, name in methods.items(): + fn = getattr(_funcs, name or method) + vars()[method] = create_method(fn, method) + + # Regular methods but coming from ufuncs + conj = create_method(_ufuncs.conjugate, "conj") + conjugate = create_method(_ufuncs.conjugate) + + for method, name in dunder.items(): + fn = getattr(_ufuncs, name or method) + method = f"__{method}__" + vars()[method] = create_method(fn, method) + + for method, name in ri_dunder.items(): + fn = getattr(_ufuncs, name or method) + plain = f"__{method}__" + vars()[plain] = create_method(fn, plain) + rvar = f"__r{method}__" + vars()[rvar] = create_method(lambda self, other, fn=fn: fn(other, self), rvar) + ivar = f"__i{method}__" + vars()[ivar] = create_method( + lambda self, other, fn=fn: fn(self, other, out=self), ivar + ) + + # There's no __idivmod__ + __divmod__ = create_method(_ufuncs.divmod, "__divmod__") + __rdivmod__ = create_method( + lambda self, other: _ufuncs.divmod(other, self), "__rdivmod__" + ) + + # prevent loop variables leaking into the ndarray class namespace + del ivar, rvar, name, plain, fn, method + + @property + def shape(self): + return tuple(self.tensor.shape) + + @property + def size(self): + return self.tensor.numel() + + @property + def ndim(self): + return self.tensor.ndim + + @property + def dtype(self): + return _dtypes.dtype(self.tensor.dtype) + + @property + def strides(self): + elsize = self.tensor.element_size() + return tuple(stride * elsize for stride in self.tensor.stride()) + + @property + def itemsize(self): + return self.tensor.element_size() + + @property + def flags(self): + # Note contiguous in torch is assumed C-style + return Flags( + { + "C_CONTIGUOUS": self.tensor.is_contiguous(), + "F_CONTIGUOUS": self.T.tensor.is_contiguous(), + "OWNDATA": self.tensor._base is None, + "WRITEABLE": True, # pytorch does not have readonly tensors + } + ) + + @property + def data(self): + return self.tensor.data_ptr() + + @property + def nbytes(self): + return self.tensor.storage().nbytes() + + @property + def T(self): + return self.transpose() + + @property + def real(self): + return _funcs.real(self) + + @real.setter + def real(self, value): + self.tensor.real = asarray(value).tensor + + @property + def imag(self): + return _funcs.imag(self) + + @imag.setter + def imag(self, value): + self.tensor.imag = asarray(value).tensor + + @property + def flat(self): + return self.ravel() + + # ctors + def astype(self, dtype, order="K", casting="unsafe", subok=True, copy=True): + if order != "K": + raise NotImplementedError(f"astype(..., order={order} is not implemented.") + if casting != "unsafe": + raise NotImplementedError( + f"astype(..., casting={casting} is not implemented." + ) + if not subok: + raise NotImplementedError(f"astype(..., subok={subok} is not implemented.") + if not copy: + raise NotImplementedError(f"astype(..., copy={copy} is not implemented.") + torch_dtype = _dtypes.dtype(dtype).torch_dtype + t = self.tensor.to(torch_dtype) + return ndarray(t) + + @normalizer + def copy(self: ArrayLike, order: NotImplementedType = "C"): + return self.clone() + + @normalizer + def flatten(self: ArrayLike, order: NotImplementedType = "C"): + return torch.flatten(self) + + def resize(self, *new_shape, refcheck=False): + # NB: differs from np.resize: fills with zeros instead of making repeated copies of input. + if refcheck: + raise NotImplementedError( + f"resize(..., refcheck={refcheck} is not implemented." + ) + if new_shape in [(), (None,)]: + return + + # support both x.resize((2, 2)) and x.resize(2, 2) + if len(new_shape) == 1: + new_shape = new_shape[0] + if isinstance(new_shape, int): + new_shape = (new_shape,) + + if builtins.any(x < 0 for x in new_shape): + raise ValueError("all elements of `new_shape` must be non-negative") + + new_numel, old_numel = math.prod(new_shape), self.tensor.numel() + + self.tensor.resize_(new_shape) + + if new_numel >= old_numel: + # zero-fill new elements + if not self.tensor.is_contiguous(): + raise AssertionError("tensor must be contiguous for resize with growth") + b = self.tensor.flatten() # does not copy + b[old_numel:].zero_() + + def view(self, dtype=_Unspecified.unspecified, type=_Unspecified.unspecified): + if dtype is _Unspecified.unspecified: + dtype = self.dtype + if type is not _Unspecified.unspecified: + raise NotImplementedError(f"view(..., type={type} is not implemented.") + torch_dtype = _dtypes.dtype(dtype).torch_dtype + tview = self.tensor.view(torch_dtype) + return ndarray(tview) + + @normalizer + def fill(self, value: ArrayLike): + # Both Pytorch and NumPy accept 0D arrays/tensors and scalars, and + # error out on D > 0 arrays + self.tensor.fill_(value) + + def tolist(self): + return self.tensor.tolist() + + def __iter__(self): + return (ndarray(x) for x in self.tensor.__iter__()) + + def __str__(self): + return ( + str(self.tensor) + .replace("tensor", "torch.ndarray") + .replace("dtype=torch.", "dtype=") + ) + + __repr__ = create_method(__str__) + + def __eq__(self, other): + try: + return _ufuncs.equal(self, other) + except (RuntimeError, TypeError): + # Failed to convert other to array: definitely not equal. + falsy = torch.full(self.shape, fill_value=False, dtype=bool) + return asarray(falsy) + + def __ne__(self, other): + return ~(self == other) + + def __index__(self): + try: + return operator.index(self.tensor.item()) + except Exception as exc: + raise TypeError( + "only integer scalar arrays can be converted to a scalar index" + ) from exc + + def __bool__(self): + return bool(self.tensor) + + def __int__(self): + return int(self.tensor) + + def __float__(self): + return float(self.tensor) + + def __complex__(self): + return complex(self.tensor) + + def is_integer(self): + try: + v = self.tensor.item() + result = int(v) == v + except Exception: + result = False + return result + + def __len__(self): + return self.tensor.shape[0] + + def __contains__(self, x): + return self.tensor.__contains__(x) + + def transpose(self, *axes): + # np.transpose(arr, axis=None) but arr.transpose(*axes) + return _funcs.transpose(self, axes) + + def reshape(self, *shape, order="C"): + # arr.reshape(shape) and arr.reshape(*shape) + return _funcs.reshape(self, shape, order=order) + + def sort(self, axis=-1, kind=None, order=None): + # ndarray.sort works in-place + _funcs.copyto(self, _funcs.sort(self, axis, kind, order)) + + def item(self, *args): + # Mimic NumPy's implementation with three special cases (no arguments, + # a flat index and a multi-index): + # https://github.com/numpy/numpy/blob/main/numpy/_core/src/multiarray/methods.c#L702 + if args == (): + return self.tensor.item() + elif len(args) == 1: + # int argument + return self.ravel()[args[0]] + else: + return self.__getitem__(args) + + def __getitem__(self, index): + tensor = self.tensor + + def neg_step(i, s): + if not (isinstance(s, slice) and s.step is not None and s.step < 0): + return s + + nonlocal tensor + tensor = torch.flip(tensor, (i,)) + + # Account for the fact that a slice includes the start but not the end + if not (isinstance(s.start, int) or s.start is None): + raise AssertionError( + f"slice start must be int or None, got {type(s.start).__name__}" + ) + if not (isinstance(s.stop, int) or s.stop is None): + raise AssertionError( + f"slice stop must be int or None, got {type(s.stop).__name__}" + ) + start = s.stop + 1 if s.stop else None + stop = s.start + 1 if s.start else None + + return slice(start, stop, -s.step) + + if isinstance(index, Sequence): + index = type(index)(neg_step(i, s) for i, s in enumerate(index)) + else: + index = neg_step(0, index) + index = _util.ndarrays_to_tensors(index) + index = _upcast_int_indices(index) + # Apply NumPy-compatible indexing conversion + index = _numpy_compatible_indexing(index) + # Apply NumPy-compatible empty ellipsis behavior + index, maybe_squeeze, _ = _numpy_empty_ellipsis_patch(index, tensor.ndim) + return maybe_squeeze(ndarray(tensor.__getitem__(index))) + + def __setitem__(self, index, value): + index = _util.ndarrays_to_tensors(index) + index = _upcast_int_indices(index) + # Apply NumPy-compatible indexing conversion + index = _numpy_compatible_indexing(index) + # Apply NumPy-compatible empty ellipsis behavior + index, _, maybe_unsqueeze = _numpy_empty_ellipsis_patch(index, self.tensor.ndim) + + if not _dtypes_impl.is_scalar(value): + value = normalize_array_like(value) + value = _util.cast_if_needed(value, self.tensor.dtype) + + return self.tensor.__setitem__(index, maybe_unsqueeze(value)) + + take = _funcs.take + put = _funcs.put + + def __dlpack__(self, *, stream=None): + return self.tensor.__dlpack__(stream=stream) + + def __dlpack_device__(self): + return self.tensor.__dlpack_device__() + + +def _tolist(obj): + """Recursively convert tensors into lists.""" + a1 = [] + for elem in obj: + if isinstance(elem, (list, tuple)): + elem = _tolist(elem) + if isinstance(elem, ndarray): + a1.append(elem.tensor.tolist()) + else: + a1.append(elem) + return a1 + + +# This is the ideally the only place which talks to ndarray directly. +# The rest goes through asarray (preferred) or array. + + +def array(obj, dtype=None, *, copy=True, order="K", subok=False, ndmin=0, like=None): + if subok is not False: + raise NotImplementedError("'subok' parameter is not supported.") + if like is not None: + raise NotImplementedError("'like' parameter is not supported.") + if order != "K": + raise NotImplementedError + + # a happy path + if ( + isinstance(obj, ndarray) + and copy is False + and dtype is None + and ndmin <= obj.ndim + ): + return obj + + if isinstance(obj, (list, tuple)): + # FIXME and they have the same dtype, device, etc + if obj and all(isinstance(x, torch.Tensor) for x in obj): + # list of arrays: *under torch.Dynamo* these are FakeTensors + obj = torch.stack(obj) + else: + # XXX: remove tolist + # lists of ndarrays: [1, [2, 3], ndarray(4)] convert to lists of lists + obj = _tolist(obj) + + # is obj an ndarray already? + if isinstance(obj, ndarray): + obj = obj.tensor + + # is a specific dtype requested? + torch_dtype = None + if dtype is not None: + torch_dtype = _dtypes.dtype(dtype).torch_dtype + + tensor = _util._coerce_to_tensor(obj, torch_dtype, copy, ndmin) + return ndarray(tensor) + + +def asarray(a, dtype=None, order="K", *, like=None): + return array(a, dtype=dtype, order=order, like=like, copy=False, ndmin=0) + + +def ascontiguousarray(a, dtype=None, *, like=None): + arr = asarray(a, dtype=dtype, like=like) + if not arr.tensor.is_contiguous(): + arr.tensor = arr.tensor.contiguous() + return arr + + +def from_dlpack(x, /): + t = torch.from_dlpack(x) + return ndarray(t) + + +def _extract_dtype(entry): + try: + dty = _dtypes.dtype(entry) + except Exception: + dty = asarray(entry).dtype + return dty + + +def can_cast(from_, to, casting="safe"): + from_ = _extract_dtype(from_) + to_ = _extract_dtype(to) + + return _dtypes_impl.can_cast_impl(from_.torch_dtype, to_.torch_dtype, casting) + + +def result_type(*arrays_and_dtypes): + tensors = [] + for entry in arrays_and_dtypes: + try: + t = asarray(entry).tensor + except (RuntimeError, ValueError, TypeError): + dty = _dtypes.dtype(entry) + t = torch.empty(1, dtype=dty.torch_dtype) + tensors.append(t) + + torch_dtype = _dtypes_impl.result_type_impl(*tensors) + return _dtypes.dtype(torch_dtype) diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_normalizations.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_normalizations.py new file mode 100644 index 0000000000000000000000000000000000000000..090e72febad0bf336f521ef0369069f19c07757a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_normalizations.py @@ -0,0 +1,349 @@ +""" "Normalize" arguments: convert array_likes to tensors, dtypes to torch dtypes and so on.""" + +from __future__ import annotations + +import functools +import inspect +import operator +import typing +from typing import TYPE_CHECKING + +import torch + +from . import _dtypes, _dtypes_impl, _util + + +if TYPE_CHECKING: + from collections.abc import Callable + + from ._ndarray import ndarray + + +# These names are used both as static type annotations and as runtime markers: +# the `normalizer` decorator dispatches on the *string* form of each parameter's +# annotation (e.g. "ArrayLike", "OutArray | None"). Because `from __future__ +# import annotations` is active everywhere these are used, the annotations are +# never evaluated, so the static type below is what each parameter resolves to +# *after* normalization runs (e.g. an ArrayLike argument is a torch.Tensor by the +# time the implementer body sees it). +ArrayLike: typing.TypeAlias = torch.Tensor +Scalar = int | float | complex | bool +ArrayLikeOrScalar = ArrayLike | Scalar + +# DTypeLike normalizes to a torch.dtype (or None when no dtype is given). +DTypeLike: typing.TypeAlias = "torch.dtype | None" +# AxisLike is an axis specification: a single axis, a tuple of axes, or None. +AxisLike: typing.TypeAlias = "int | tuple[int, ...] | None" +# NDArray normalizes to the wrapped tensor. +NDArray: typing.TypeAlias = torch.Tensor +# CastingModes is one of the numpy casting strings. +CastingModes: typing.TypeAlias = str +# KeepDims is the keepdims flag; handled entirely by the normalizer. +KeepDims: typing.TypeAlias = bool + +# OutArray is to annotate the out= array argument. +# +# This one is special is several respects: +# First, It needs to be an NDArray, and we need to preserve the `result is out` +# semantics. Therefore, we cannot just extract the Tensor from the out array. +# So we never pass the out array to implementer functions and handle it in the +# `normalizer` below. +# Second, the out= argument can be either keyword or positional argument, and +# as a positional arg, it can be anywhere in the signature. +# To handle all this, we define a special `OutArray` annotation and dispatch on it. +# +OutArray: typing.TypeAlias = "ndarray" + +# NotImplementedType marks unsupported parameters; the normalizer raises unless +# the argument equals the (always None) default, so the value is never used. +NotImplementedType: typing.TypeAlias = None + + +def normalize_array_like( + x: object, + parm: inspect.Parameter | None = None, # codespell:ignore +) -> torch.Tensor: + from ._ndarray import asarray + + return asarray(x).tensor + + +def normalize_array_like_or_scalar( + x: object, + parm: inspect.Parameter | None = None, # codespell:ignore +) -> torch.Tensor | Scalar: + if _dtypes_impl.is_scalar_or_symbolic(x): + return x # pyrefly: ignore[bad-return] + return normalize_array_like(x, parm) # codespell:ignore + + +def normalize_optional_array_like_or_scalar( + x: object, + parm: inspect.Parameter | None = None, # codespell:ignore +) -> torch.Tensor | Scalar | None: + if x is None: + return None + return normalize_array_like_or_scalar(x, parm) # codespell:ignore + + +def normalize_optional_array_like( + x: object, + parm: inspect.Parameter | None = None, # codespell:ignore +) -> torch.Tensor | None: + # This explicit normalizer is needed because otherwise normalize_array_like + # does not run for a parameter annotated as Optional[ArrayLike] + return None if x is None else normalize_array_like(x, parm) # codespell:ignore + + +def normalize_seq_array_like( + x: typing.Iterable[object], + parm: inspect.Parameter | None = None, # codespell:ignore +) -> tuple[torch.Tensor, ...]: + return tuple(normalize_array_like(value) for value in x) + + +def normalize_dtype( + dtype: object, + parm: inspect.Parameter | None = None, # codespell:ignore +) -> torch.dtype | None: + # cf _decorators.dtype_to_torch + torch_dtype = None + if dtype is not None: + torch_dtype = _dtypes.dtype(dtype).torch_dtype + return torch_dtype + + +def normalize_not_implemented( + arg: object, + parm: inspect.Parameter, # codespell:ignore +) -> None: + if arg != parm.default: # codespell:ignore + raise NotImplementedError( + f"'{parm.name}' parameter is not supported." # codespell:ignore + ) + + +def normalize_axis_like( + arg: AxisLike | ndarray, + parm: inspect.Parameter | None = None, # codespell:ignore +) -> AxisLike: + from ._ndarray import ndarray + + if isinstance(arg, ndarray): + return operator.index(arg) + return arg + + +def normalize_ndarray( + arg: object, + parm: inspect.Parameter | None = None, # codespell:ignore +) -> torch.Tensor | None: + # check the arg is an ndarray, extract its tensor attribute + if arg is None: + return arg + + from ._ndarray import ndarray + + if not isinstance(arg, ndarray): + name = parm.name if parm is not None else "argument" # codespell:ignore + raise TypeError(f"'{name}' must be an array") + return arg.tensor + + +def normalize_outarray( + arg: object, + parm: inspect.Parameter | None = None, # codespell:ignore +) -> ndarray | None: + # almost normalize_ndarray, only return the array, not its tensor + if arg is None: + return arg + from ._ndarray import ndarray + + # Dynamo can pass torch tensors as out arguments, + # wrap it in an ndarray before processing + if isinstance(arg, torch.Tensor): + arg = ndarray(arg) + + if not isinstance(arg, ndarray): + name = parm.name if parm is not None else "argument" # codespell:ignore + raise TypeError(f"'{name}' must be an array") + return arg + + +def normalize_casting( + arg: object, + parm: inspect.Parameter | None = None, # codespell:ignore +) -> CastingModes: + valid = ("no", "equiv", "safe", "same_kind", "unsafe") + if not isinstance(arg, str) or arg not in valid: + raise ValueError( + f"casting must be one of 'no', 'equiv', 'safe', 'same_kind', or 'unsafe' (got '{arg}')" + ) + return arg + + +# The registered normalizers have intentionally heterogeneous signatures +# (e.g. normalize_seq_array_like takes an iterable), so the common callable +# type erases the parameter list. +normalizers: dict[str, Callable[..., object]] = { + "ArrayLike": normalize_array_like, + "ArrayLikeOrScalar": normalize_array_like_or_scalar, + "Optional[ArrayLike]": normalize_optional_array_like, + "ArrayLike | None": normalize_optional_array_like, + "Sequence[ArrayLike]": normalize_seq_array_like, + "Optional[ArrayLikeOrScalar]": normalize_optional_array_like_or_scalar, + "ArrayLikeOrScalar | None": normalize_optional_array_like_or_scalar, + "Optional[NDArray]": normalize_ndarray, + "NDArray | None": normalize_ndarray, + "Optional[OutArray]": normalize_outarray, + "OutArray | None": normalize_outarray, + "NDArray": normalize_ndarray, + "Optional[DTypeLike]": normalize_dtype, + "DTypeLike | None": normalize_dtype, + "AxisLike": normalize_axis_like, + "NotImplementedType": normalize_not_implemented, + "Optional[CastingModes]": normalize_casting, + "CastingModes | None": normalize_casting, +} + + +def maybe_normalize(arg: object, parm: inspect.Parameter) -> object: # codespell:ignore + """Normalize arg if a normalizer is registered.""" + normalizer = normalizers.get(parm.annotation) # codespell:ignore + return normalizer(arg, parm) if normalizer else arg # codespell:ignore + + +# ### Return value helpers ### + + +def maybe_copy_to( + out: ndarray | None, result: object, promote_scalar_result: bool = False +) -> object: + # NB: here out is either an ndarray or None + if out is None: + return result + elif isinstance(result, torch.Tensor): + if result.shape != out.shape: + can_fit = result.numel() == 1 and out.ndim == 0 + if promote_scalar_result and can_fit: + result = result.squeeze() + else: + raise ValueError( + f"Bad size of the out array: out.shape = {out.shape}" + f" while result.shape = {result.shape}." + ) + out.tensor.copy_(result) + return out + elif isinstance(result, (tuple, list)): + return type(result)( + maybe_copy_to(o, r, promote_scalar_result) for o, r in zip(out, result) + ) + else: + raise AssertionError # We should never hit this path + + +def wrap_tensors(result: object) -> object: + from ._ndarray import ndarray + + if isinstance(result, torch.Tensor): + return ndarray(result) + elif isinstance(result, (tuple, list)): + result = type(result)(wrap_tensors(x) for x in result) + return result + + +def array_or_scalar( + values: torch.Tensor, + py_type: type[int | float | complex | bool] = float, + return_scalar: bool = False, +) -> int | float | complex | bool | ndarray: + if return_scalar: + return py_type(values.item()) + else: + from ._ndarray import ndarray + + return ndarray(values) + + +# ### The main decorator to normalize arguments / postprocess the output ### + +_P = typing.ParamSpec("_P") +_R = typing.TypeVar("_R") + + +@typing.overload +def normalizer(_func: Callable[_P, _R]) -> Callable[_P, _R]: ... + + +@typing.overload +def normalizer( + _func: None = None, *, promote_scalar_result: bool = False +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... + + +def normalizer( + _func: Callable[_P, _R] | None = None, *, promote_scalar_result: bool = False +) -> Callable[_P, _R] | Callable[[Callable[_P, _R]], Callable[_P, _R]]: + def normalizer_inner(func: Callable[_P, _R]) -> Callable[_P, _R]: + @functools.wraps(func) + def wrapped(*args: _P.args, **kwds: _P.kwargs) -> _R: + sig = inspect.signature(func) + params = sig.parameters + first_param = next(iter(params.values())) + + # NumPy's API does not have positional args before variadic positional args + norm_args: tuple[object, ...] + if first_param.kind == inspect.Parameter.VAR_POSITIONAL: + norm_args = tuple(maybe_normalize(arg, first_param) for arg in args) + else: + # NB: extra unknown arguments: pass through, will raise in func(*args) below + norm_args = ( + tuple( + maybe_normalize(arg, parm) # codespell:ignore + for arg, parm in zip(args, params.values()) # codespell:ignore + ) + + args[len(params.values()) :] + ) + + norm_kwds = { + name: maybe_normalize(arg, params[name]) if name in params else arg + for name, arg in kwds.items() + } + + # The normalizer rebuilds args/kwds, so they are no longer the + # ParamSpec-tracked *args/**kwargs; the call is correct at runtime. + # pyrefly: ignore[invalid-param-spec] + result: object = func(*norm_args, **norm_kwds) + + # keepdims + bound_args = None + if "keepdims" in params and params["keepdims"].annotation == "KeepDims": + # keepdims can be in any position so we need sig.bind + bound_args = sig.bind(*norm_args, **norm_kwds).arguments + if bound_args.get("keepdims", False): + # In this case the first arg is the initial tensor and + # the second arg is (optionally) the axis + tensor = norm_args[0] + axis = bound_args.get("axis") + if not isinstance(tensor, torch.Tensor): + raise AssertionError("keepdims requires a tensor first arg") + # pyrefly: ignore[bad-argument-type] + result = _util.apply_keepdims(result, axis, tensor.ndim) + + # out + if "out" in params: + # out can be in any position so we need sig.bind + if bound_args is None: + bound_args = sig.bind(*norm_args, **norm_kwds).arguments + out = bound_args.get("out") + result = maybe_copy_to(out, result, promote_scalar_result) + result = wrap_tensors(result) + + return result # pyrefly: ignore[bad-return] + + return wrapped + + if _func is None: + return normalizer_inner + else: + return normalizer_inner(_func) diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_reductions_impl.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_reductions_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..0c418463f8254aec2ca38b30122f5fb4c6e7af57 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_reductions_impl.py @@ -0,0 +1,480 @@ +"""Implementation of reduction operations, to be wrapped into arrays, dtypes etc +in the 'public' layer. + +Anything here only deals with torch objects, e.g. "dtype" is a torch.dtype instance etc +""" + +from __future__ import annotations + +import functools +from typing import Concatenate, ParamSpec, TYPE_CHECKING, TypeVar + +import torch + +from . import _dtypes_impl, _util + + +if TYPE_CHECKING: + from collections.abc import Callable + + from ._normalizations import ( + ArrayLike, + AxisLike, + DTypeLike, + KeepDims, + NotImplementedType, + OutArray, + ) + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +def _deco_axis_expand( + func: Callable[Concatenate[torch.Tensor, AxisLike, _P], _R], +) -> Callable[Concatenate[torch.Tensor, AxisLike, _P], _R]: + """ + Generically handle axis arguments in reductions. + axis is *always* the 2nd arg in the function so no need to have a look at its signature + """ + + @functools.wraps(func) + def wrapped( + a: torch.Tensor, axis: AxisLike = None, *args: _P.args, **kwds: _P.kwargs + ) -> _R: + if axis is not None: + axis = _util.normalize_axis_tuple(axis, a.ndim) + + if axis == (): + # So we insert a length-one axis and run the reduction along it. + # We cannot return a.clone() as this would sidestep the checks inside the function + newshape = _util.expand_shape(a.shape, axis=0) + a = a.reshape(newshape) + axis = (0,) + + return func(a, axis, *args, **kwds) + + return wrapped + + +def _atleast_float(dtype: torch.dtype | None, other_dtype: torch.dtype) -> torch.dtype: + """Return a dtype that is real or complex floating-point. + + For inputs that are boolean or integer dtypes, this returns the default + float dtype; inputs that are complex get converted to the default complex + dtype; real floating-point dtypes (`float*`) get passed through unchanged + """ + if dtype is None: + dtype = other_dtype + if not (dtype.is_floating_point or dtype.is_complex): + return _dtypes_impl.default_dtypes().float_dtype + return dtype + + +@_deco_axis_expand +def count_nonzero( + a: ArrayLike, axis: AxisLike = None, *, keepdims: KeepDims = False +) -> torch.Tensor: + return a.count_nonzero(axis) + + +@_deco_axis_expand +def argmax( + a: ArrayLike, + axis: AxisLike = None, + out: OutArray | None = None, + *, + keepdims: KeepDims = False, +) -> torch.Tensor: + if a.is_complex(): + raise NotImplementedError(f"argmax with dtype={a.dtype}.") + + axis = _util.allow_only_single_axis(axis) + + if a.dtype == torch.bool: + # RuntimeError: "argmax_cpu" not implemented for 'Bool' + a = a.to(torch.uint8) + + return torch.argmax(a, axis) + + +@_deco_axis_expand +def argmin( + a: ArrayLike, + axis: AxisLike = None, + out: OutArray | None = None, + *, + keepdims: KeepDims = False, +) -> torch.Tensor: + if a.is_complex(): + raise NotImplementedError(f"argmin with dtype={a.dtype}.") + + axis = _util.allow_only_single_axis(axis) + + if a.dtype == torch.bool: + # RuntimeError: "argmin_cpu" not implemented for 'Bool' + a = a.to(torch.uint8) + + return torch.argmin(a, axis) + + +@_deco_axis_expand +def any( + a: ArrayLike, + axis: AxisLike = None, + out: OutArray | None = None, + keepdims: KeepDims = False, + *, + where: NotImplementedType = None, +) -> torch.Tensor: + axis = _util.allow_only_single_axis(axis) + return torch.any(a) if axis is None else torch.any(a, dim=axis) + + +@_deco_axis_expand +def all( + a: ArrayLike, + axis: AxisLike = None, + out: OutArray | None = None, + keepdims: KeepDims = False, + *, + where: NotImplementedType = None, +) -> torch.Tensor: + axis = _util.allow_only_single_axis(axis) + return torch.all(a) if axis is None else torch.all(a, dim=axis) + + +@_deco_axis_expand +def amax( + a: ArrayLike, + axis: AxisLike = None, + out: OutArray | None = None, + keepdims: KeepDims = False, + initial: NotImplementedType = None, + where: NotImplementedType = None, +) -> torch.Tensor: + if a.is_complex(): + raise NotImplementedError(f"amax with dtype={a.dtype}") + + return a.amax() if axis is None else a.amax(axis) + + +max = amax + + +@_deco_axis_expand +def amin( + a: ArrayLike, + axis: AxisLike = None, + out: OutArray | None = None, + keepdims: KeepDims = False, + initial: NotImplementedType = None, + where: NotImplementedType = None, +) -> torch.Tensor: + if a.is_complex(): + raise NotImplementedError(f"amin with dtype={a.dtype}") + + return a.amin() if axis is None else a.amin(axis) + + +min = amin + + +@_deco_axis_expand +def ptp( + a: ArrayLike, + axis: AxisLike = None, + out: OutArray | None = None, + keepdims: KeepDims = False, +) -> torch.Tensor: + amax = a.amax() if axis is None else a.amax(axis) + amin = a.amin() if axis is None else a.amin(axis) + return amax - amin + + +@_deco_axis_expand +def sum( + a: ArrayLike, + axis: AxisLike = None, + dtype: DTypeLike | None = None, + out: OutArray | None = None, + keepdims: KeepDims = False, + initial: NotImplementedType = None, + where: NotImplementedType = None, +) -> torch.Tensor: + if dtype is not None and not isinstance(dtype, torch.dtype): + raise AssertionError( + f"dtype must be None or a torch.dtype, got {type(dtype).__name__}" + ) + + if dtype == torch.bool: + dtype = _dtypes_impl.default_dtypes().int_dtype + + if axis is None: + return a.sum(dtype=dtype) + return a.sum(dim=axis, dtype=dtype) + + +@_deco_axis_expand +def prod( + a: ArrayLike, + axis: AxisLike = None, + dtype: DTypeLike | None = None, + out: OutArray | None = None, + keepdims: KeepDims = False, + initial: NotImplementedType = None, + where: NotImplementedType = None, +) -> torch.Tensor: + axis = _util.allow_only_single_axis(axis) + + if dtype == torch.bool: + dtype = _dtypes_impl.default_dtypes().int_dtype + + if axis is None: + return a.prod(dtype=dtype) + return a.prod(dim=axis, dtype=dtype) + + +product = prod + + +@_deco_axis_expand +def mean( + a: ArrayLike, + axis: AxisLike = None, + dtype: DTypeLike | None = None, + out: OutArray | None = None, + keepdims: KeepDims = False, + *, + where: NotImplementedType = None, +) -> torch.Tensor: + dtype = _atleast_float(dtype, a.dtype) + + if axis is None: + return a.mean(dtype=dtype) + return a.mean(dim=axis, dtype=dtype) + + +@_deco_axis_expand +def std( + a: ArrayLike, + axis: AxisLike = None, + dtype: DTypeLike | None = None, + out: OutArray | None = None, + ddof: float = 0, + keepdims: KeepDims = False, + *, + where: NotImplementedType = None, +) -> torch.Tensor: + in_dtype = dtype + dtype = _atleast_float(dtype, a.dtype) + tensor = _util.cast_if_needed(a, dtype) + result = tensor.std(dim=axis, correction=ddof) + return _util.cast_if_needed(result, in_dtype) + + +@_deco_axis_expand +def var( + a: ArrayLike, + axis: AxisLike = None, + dtype: DTypeLike | None = None, + out: OutArray | None = None, + ddof: float = 0, + keepdims: KeepDims = False, + *, + where: NotImplementedType = None, +) -> torch.Tensor: + in_dtype = dtype + dtype = _atleast_float(dtype, a.dtype) + tensor = _util.cast_if_needed(a, dtype) + result = tensor.var(dim=axis, correction=ddof) + return _util.cast_if_needed(result, in_dtype) + + +# cumsum / cumprod are almost reductions: +# 1. no keepdims +# 2. axis=None flattens + + +def cumsum( + a: ArrayLike, + axis: AxisLike = None, + dtype: DTypeLike | None = None, + out: OutArray | None = None, +) -> torch.Tensor: + if dtype == torch.bool: + dtype = _dtypes_impl.default_dtypes().int_dtype + if dtype is None: + dtype = a.dtype + + # pyrefly: ignore[bad-argument-type] + (a,), axis = _util.axis_none_flatten(a, axis=axis) + axis = _util.normalize_axis_index(axis, a.ndim) + + # torch accepts the numpy-compat `axis=` alias, but its stub only lists `dim`. + # pyrefly: ignore[missing-argument, unexpected-keyword] + return a.cumsum(axis=axis, dtype=dtype) + + +def cumprod( + a: ArrayLike, + axis: AxisLike = None, + dtype: DTypeLike | None = None, + out: OutArray | None = None, +) -> torch.Tensor: + if dtype == torch.bool: + dtype = _dtypes_impl.default_dtypes().int_dtype + if dtype is None: + dtype = a.dtype + + # pyrefly: ignore[bad-argument-type] + (a,), axis = _util.axis_none_flatten(a, axis=axis) + axis = _util.normalize_axis_index(axis, a.ndim) + + # torch accepts the numpy-compat `axis=` alias, but its stub only lists `dim`. + # pyrefly: ignore[missing-argument, unexpected-keyword] + return a.cumprod(axis=axis, dtype=dtype) + + +cumproduct = cumprod + + +def average( + a: ArrayLike, + axis: int | None = None, + weights: ArrayLike | None = None, + returned: bool = False, + *, + keepdims: bool = False, +) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: + if weights is None: + result = mean(a, axis) + wsum = torch.as_tensor(a.numel() / result.numel(), dtype=result.dtype) + else: + if not a.dtype.is_floating_point: + a = a.double() + + # axis & weights + if a.shape != weights.shape: + if axis is None: + raise TypeError( + "Axis must be specified when shapes of a and weights differ." + ) + if weights.ndim != 1: + raise TypeError( + "1D weights expected when shapes of a and weights differ." + ) + if weights.shape[0] != a.shape[axis]: + raise ValueError( + "Length of weights not compatible with specified axis." + ) + + # setup weight to broadcast along axis + weights = torch.broadcast_to(weights, (a.ndim - 1) * (1,) + weights.shape) + weights = weights.swapaxes(-1, axis) + + # do the work + result_dtype = _dtypes_impl.result_type_impl(a, weights) + numerator = sum(a * weights, axis, dtype=result_dtype) + wsum = sum(weights, axis, dtype=result_dtype) + result = numerator / wsum + + # We process keepdims manually because the decorator does not deal with variadic returns + if keepdims: + result = _util.apply_keepdims(result, axis, a.ndim) + + if returned: + if wsum.shape != result.shape: + wsum = torch.broadcast_to(wsum, result.shape).clone() + return result, wsum + else: + return result + + +# Not using deco_axis_expand as it assumes that axis is the second arg +def quantile( + a: ArrayLike, + q: ArrayLike, + axis: AxisLike = None, + out: OutArray | None = None, + overwrite_input: bool = False, + method: str = "linear", + keepdims: KeepDims = False, + *, + interpolation: NotImplementedType = None, +) -> torch.Tensor: + if overwrite_input: + # raise NotImplementedError("overwrite_input in quantile not implemented.") + # NumPy documents that `overwrite_input` MAY modify inputs: + # https://numpy.org/doc/stable/reference/generated/numpy.percentile.html#numpy-percentile + # Here we choose to work out-of-place because why not. + pass + + if not a.dtype.is_floating_point: + dtype = _dtypes_impl.default_dtypes().float_dtype + a = a.to(dtype) + + # edge case: torch.quantile only supports float32 and float64 + if a.dtype == torch.float16: + a = a.to(torch.float32) + + if axis is None: + a = a.flatten() + q = q.flatten() + axis = (0,) + else: + axis = _util.normalize_axis_tuple(axis, a.ndim) + + # FIXME(Mario) Doesn't np.quantile accept a tuple? + # torch.quantile does accept a number. If we don't want to implement the tuple behaviour + # (it's deffo low prio) change `normalize_axis_tuple` into a normalize_axis index above. + axis = _util.allow_only_single_axis(axis) + + q = _util.cast_if_needed(q, a.dtype) + + return torch.quantile(a, q, axis, interpolation=method) + + +def percentile( + a: ArrayLike, + q: ArrayLike, + axis: AxisLike = None, + out: OutArray | None = None, + overwrite_input: bool = False, + method: str = "linear", + keepdims: KeepDims = False, + *, + interpolation: NotImplementedType = None, +) -> torch.Tensor: + # np.percentile(float_tensor, 30) : q.dtype is int64 => q / 100.0 is float32 + if _dtypes_impl.python_type_for_torch(q.dtype) is int: + q = q.to(_dtypes_impl.default_dtypes().float_dtype) + qq = q / 100.0 + + return quantile( + a, + qq, + axis=axis, + overwrite_input=overwrite_input, + method=method, + keepdims=keepdims, + interpolation=interpolation, + ) + + +def median( + a: ArrayLike, + axis: int | None = None, + out: OutArray | None = None, + overwrite_input: bool = False, + keepdims: KeepDims = False, +) -> torch.Tensor: + return quantile( + a, + torch.as_tensor(0.5), + axis=axis, + overwrite_input=overwrite_input, + out=out, + keepdims=keepdims, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_ufuncs.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_ufuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..56d93936b441c6133e16a68c95b6c1cce62e3bc8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_ufuncs.py @@ -0,0 +1,332 @@ +# mypy: ignore-errors + +from __future__ import annotations + +import torch + +from . import _binary_ufuncs_impl, _dtypes_impl, _unary_ufuncs_impl, _util +from ._normalizations import ( + ArrayLike, + ArrayLikeOrScalar, + CastingModes, + DTypeLike, + normalizer, + NotImplementedType, + OutArray, +) + + +def _ufunc_postprocess(result, out, casting): + if out is not None: + result = _util.typecast_tensor(result, out.dtype.torch_dtype, casting) + result = torch.broadcast_to(result, out.shape) + return result + + +# ############# Binary ufuncs ###################### + +_binary = [ + name + for name in dir(_binary_ufuncs_impl) + if not name.startswith("_") and name not in ["torch", "matmul", "divmod", "ldexp"] +] + + +NEP50_FUNCS = ( + "add", + "subtract", + "multiply", + "floor_divide", + "true_divide", + "divide", + "remainder", + "bitwise_and", + "bitwise_or", + "bitwise_xor", + "bitwise_left_shift", + "bitwise_right_shift", + "hypot", + "arctan2", + "logaddexp", + "logaddexp2", + "heaviside", + "copysign", + "fmax", + "minimum", + "fmin", + "maximum", + "fmod", + "gcd", + "lcm", + "pow", +) + + +def deco_binary_ufunc(torch_func): + """Common infra for binary ufuncs. + + Normalize arguments, sort out type casting, broadcasting and delegate to + the pytorch functions for the actual work. + """ + + @normalizer + def wrapped( + x1: ArrayLikeOrScalar, + x2: ArrayLikeOrScalar, + /, + out: OutArray | None = None, + *, + where: NotImplementedType = True, + casting: CastingModes | None = "same_kind", + order: NotImplementedType = "K", + dtype: DTypeLike | None = None, + subok: NotImplementedType = False, + signature: NotImplementedType = None, + extobj: NotImplementedType = None, + ): + if dtype is not None: + + def cast(x, dtype): + if isinstance(x, torch.Tensor): + return _util.typecast_tensor(x, dtype, casting) + else: + return torch.as_tensor(x, dtype=dtype) + + x1 = cast(x1, dtype) + x2 = cast(x2, dtype) + elif isinstance(x1, torch.Tensor) and isinstance(x2, torch.Tensor): + dtype = _dtypes_impl.result_type_impl(x1, x2) + x1, x2 = _util.typecast_tensors((x1, x2), dtype, casting) + else: + x1, x2 = _dtypes_impl.nep50_to_tensors( + x1, x2, torch_func.__name__ in NEP50_FUNCS, torch_func.__name__ + ) + + result = torch_func(x1, x2) + + return _ufunc_postprocess(result, out, casting) + + wrapped.__qualname__ = torch_func.__name__ + wrapped.__name__ = torch_func.__name__ + + return wrapped + + +# matmul's signature is _slightly_ different from other ufuncs: +# - no where=... +# - additional axis=..., axes=... +# - no NEP50 scalars in or out +@normalizer +def matmul( + x1: ArrayLike, + x2: ArrayLike, + /, + out: OutArray | None = None, + *, + casting: CastingModes | None = "same_kind", + order: NotImplementedType = "K", + dtype: DTypeLike | None = None, + subok: NotImplementedType = False, + signature: NotImplementedType = None, + extobj: NotImplementedType = None, + axes: NotImplementedType = None, + axis: NotImplementedType = None, +): + if dtype is None: + dtype = _dtypes_impl.result_type_impl(x1, x2) + x1, x2 = _util.typecast_tensors((x1, x2), dtype, casting) + + result = _binary_ufuncs_impl.matmul(x1, x2) + + result = _ufunc_postprocess(result, out, casting) + return result + + +# ldexp casting is special : the dtype of the result == dtype of the 1st arg +@normalizer +def ldexp( + x1: ArrayLikeOrScalar, + x2: ArrayLikeOrScalar, + /, + out: OutArray | None = None, + *, + where: NotImplementedType = True, + casting: CastingModes | None = "same_kind", + order: NotImplementedType = "K", + dtype: DTypeLike | None = None, + subok: NotImplementedType = False, + signature: NotImplementedType = None, + extobj: NotImplementedType = None, +): + if dtype is not None: + if isinstance(x1, torch.Tensor): + x1 = _util.typecast_tensor(x1, dtype, casting) + else: + x1 = torch.as_tensor(x1, dtype=dtype) + else: + if not isinstance(x1, torch.Tensor): + x1 = torch.as_tensor(x1) + x1 = _util.cast_int_to_float(x1) + + x2 = torch.as_tensor(x2) + # the second arg must be integer + if _dtypes_impl._category(x2.dtype) != 1: + raise ValueError("ldexp 2nd arg must be integer") + + result = _binary_ufuncs_impl.ldexp(x1, x2) + + if x1.dtype == torch.float16: + # torch.ldexp(f16, int) -> f32, undo it + result = result.to(torch.float16) + + return _ufunc_postprocess(result, out, casting) + + +# nin=2, nout=2 +@normalizer +def divmod( + x1: ArrayLike, + x2: ArrayLike, + out1: OutArray | None = None, + out2: OutArray | None = None, + /, + out: tuple[OutArray | None, OutArray | None] = (None, None), + *, + where: NotImplementedType = True, + casting: CastingModes | None = "same_kind", + order: NotImplementedType = "K", + dtype: DTypeLike | None = None, + subok: NotImplementedType = False, + signature: NotImplementedType = None, + extobj: NotImplementedType = None, +): + # make sure we either have no out arrays at all, or there is either + # out1, out2, or out=tuple, but not both + num_outs = sum(x is not None for x in [out1, out2]) + if num_outs == 1: + raise ValueError("both out1 and out2 need to be provided") + elif num_outs == 2: + o1, o2 = out + if o1 is not None or o2 is not None: + raise TypeError( + "cannot specify 'out' as both a positional and keyword argument" + ) + else: + out1, out2 = out + + if dtype is None: + dtype = _dtypes_impl.result_type_impl(x1, x2) + x1, x2 = _util.typecast_tensors((x1, x2), dtype, casting) + + quot, rem = _binary_ufuncs_impl.divmod(x1, x2) + + quot = _ufunc_postprocess(quot, out1, casting) + rem = _ufunc_postprocess(rem, out2, casting) + return quot, rem + + +# +# Attach ufuncs to this module, for a further export to the public namespace in __init__.py +# +for name in _binary: + ufunc = getattr(_binary_ufuncs_impl, name) + vars()[name] = deco_binary_ufunc(ufunc) + + +def modf(x, /, *args, **kwds): + quot, rem = divmod(x, 1, *args, **kwds) + return rem, quot + + +_binary = _binary + ["divmod", "modf", "matmul", "ldexp"] + + +# ############# Unary ufuncs ###################### + + +_unary = [ + name + for name in dir(_unary_ufuncs_impl) + if not name.startswith("_") and name != "torch" +] + + +# these are ufunc(int) -> float +_fp_unary = [ + "arccos", + "arccosh", + "arcsin", + "arcsinh", + "arctan", + "arctanh", + "cbrt", + "cos", + "cosh", + "deg2rad", + "degrees", + "exp", + "exp2", + "expm1", + "log", + "log10", + "log1p", + "log2", + "rad2deg", + "radians", + "reciprocal", + "sin", + "sinh", + "sqrt", + "square", + "tan", + "tanh", + "trunc", +] + + +def deco_unary_ufunc(torch_func): + """Common infra for unary ufuncs. + + Normalize arguments, sort out type casting, broadcasting and delegate to + the pytorch functions for the actual work. + """ + + @normalizer + def wrapped( + x: ArrayLike, + /, + out: OutArray | None = None, + *, + where=True, + casting: CastingModes | None = "same_kind", + order="K", + dtype: DTypeLike | None = None, + subok: NotImplementedType = False, + signature=None, + extobj=None, + ): + if dtype is not None: + x = _util.typecast_tensor(x, dtype, casting) + + if torch_func.__name__ in _fp_unary: + x = _util.cast_int_to_float(x) + + result = torch_func(x) + result = _ufunc_postprocess(result, out, casting) + return result + + wrapped.__qualname__ = torch_func.__name__ + wrapped.__name__ = torch_func.__name__ + + return wrapped + + +# +# Attach ufuncs to this module, for a further export to the public namespace in __init__.py +# +for name in _unary: + ufunc = getattr(_unary_ufuncs_impl, name) + vars()[name] = deco_unary_ufunc(ufunc) + + +__all__ = _binary + _unary # noqa: PLE0605 diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_unary_ufuncs_impl.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_unary_ufuncs_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..9b7fe08ab4b8cf6b2e892b8956fff00d93c08d11 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_unary_ufuncs_impl.py @@ -0,0 +1,72 @@ +# mypy: ignore-errors + +"""Export torch work functions for unary ufuncs, rename/tweak to match numpy. +This listing is further exported to public symbols in the `_numpy/_ufuncs.py` module. +""" + +import torch +from torch import ( # noqa: F401 + absolute as fabs, + arccos, + arccosh, + arcsin, + arcsinh, + arctan, + arctanh, + bitwise_not, + bitwise_not as invert, + ceil, + conj_physical as conjugate, + cos, + cosh, + deg2rad, + deg2rad as radians, + exp, + exp2, + expm1, + floor, + isfinite, + isinf, + isnan, + log, + log10, + log1p, + log2, + logical_not, + negative, + rad2deg, + rad2deg as degrees, + reciprocal, + round as fix, + round as rint, + sign, + signbit, + sin, + sinh, + sqrt, + square, + tan, + tanh, + trunc, +) + + +# special cases: torch does not export these names +def cbrt(x): + return torch.pow(x, 1 / 3) + + +def positive(x): + return +x + + +def absolute(x): + # work around torch.absolute not impl for bools + if x.dtype == torch.bool: + return x + return torch.absolute(x) + + +# TODO set __name__ and __qualname__ +abs = absolute +conj = conjugate diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/_util.py b/.venv/lib/python3.12/site-packages/torch/_numpy/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..0286d59c26c1343961f432dde9cb97d7fdcdcd10 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/_util.py @@ -0,0 +1,297 @@ +"""Assorted utilities, which do not need anything other than torch and stdlib.""" + +import operator +from collections.abc import Iterable, Sequence, Sized +from typing import TypeGuard + +import torch + +from . import _dtypes_impl + + +# https://github.com/numpy/numpy/blob/v1.23.0/numpy/distutils/misc_util.py#L497-L504 +def is_sequence(seq: object) -> TypeGuard[Sized]: + if isinstance(seq, str): + return False + if not isinstance(seq, Sized): + return False + try: + len(seq) + except Exception: + return False + return True + + +class AxisError(ValueError, IndexError): + pass + + +class UFuncTypeError(TypeError, RuntimeError): + pass + + +def cast_if_needed(tensor: torch.Tensor, dtype: torch.dtype | None) -> torch.Tensor: + # NB: no casting if dtype=None + if dtype is not None and tensor.dtype != dtype: + tensor = tensor.to(dtype) + return tensor + + +def cast_int_to_float(x: torch.Tensor) -> torch.Tensor: + # cast integers and bools to the default float dtype + if _dtypes_impl._category(x.dtype) < 2: + x = x.to(_dtypes_impl.default_dtypes().float_dtype) + return x + + +# a replica of the version in ./numpy/numpy/core/src/multiarray/common.h +def normalize_axis_index(ax: int, ndim: int, argname: str | None = None) -> int: + if not (-ndim <= ax < ndim): + raise AxisError(f"axis {ax} is out of bounds for array of dimension {ndim}") + if ax < 0: + ax += ndim + return ax + + +# from https://github.com/numpy/numpy/blob/main/numpy/core/numeric.py#L1378 +def normalize_axis_tuple( + axis: int | Iterable[int], + ndim: int, + argname: str | None = None, + allow_duplicate: bool = False, +) -> tuple[int, ...]: + """ + Normalizes an axis argument into a tuple of non-negative integer axes. + + This handles shorthands such as ``1`` and converts them to ``(1,)``, + as well as performing the handling of negative indices covered by + `normalize_axis_index`. + + By default, this forbids axes from being specified multiple times. + Used internally by multi-axis-checking logic. + + Parameters + ---------- + axis : int, iterable of int + The un-normalized index or indices of the axis. + ndim : int + The number of dimensions of the array that `axis` should be normalized + against. + argname : str, optional + A prefix to put before the error message, typically the name of the + argument. + allow_duplicate : bool, optional + If False, the default, disallow an axis from being specified twice. + + Returns + ------- + normalized_axes : tuple of int + The normalized axis index, such that `0 <= normalized_axis < ndim` + """ + # Optimization to speed-up the most common cases. + axes: Iterable[int] + if isinstance(axis, (tuple, list)): + axes = axis + else: + # operator.index handles the scalar shorthand (int and __index__-like + # objects); a TypeError means axis is already an iterable of ints. + try: + axes = [operator.index(axis)] # pyrefly: ignore[bad-argument-type] + except TypeError: + axes = axis # pyrefly: ignore[bad-assignment] + # Going via an iterator directly is slower than via list comprehension. + result = tuple(normalize_axis_index(ax, ndim, argname) for ax in axes) + if not allow_duplicate and len(set(map(int, result))) != len(result): + if argname: + raise ValueError(f"repeated axis in `{argname}` argument") + else: + raise ValueError("repeated axis") + return result + + +def allow_only_single_axis(axis: int | tuple[int, ...] | None) -> int | None: + if axis is None: + return axis + if isinstance(axis, int): + return axis + if len(axis) != 1: + raise NotImplementedError("does not handle tuple axis") + return axis[0] + + +def expand_shape( + arr_shape: Sequence[int], axis: int | tuple[int, ...] | list[int] +) -> list[int]: + # taken from numpy 1.23.x, expand_dims function + axis_seq = axis if isinstance(axis, (list, tuple)) else (axis,) + out_ndim = len(axis_seq) + len(arr_shape) + normalized = normalize_axis_tuple(axis_seq, out_ndim) + shape_it = iter(arr_shape) + shape = [1 if ax in normalized else next(shape_it) for ax in range(out_ndim)] + return shape + + +def apply_keepdims( + tensor: torch.Tensor, axis: int | tuple[int, ...] | None, ndim: int +) -> torch.Tensor: + if axis is None: + # tensor was a scalar + shape = (1,) * ndim + tensor = tensor.expand(shape).contiguous() + else: + shape = expand_shape(tensor.shape, axis) + tensor = tensor.reshape(shape) + return tensor + + +def axis_none_flatten( + *tensors: torch.Tensor, axis: int | None = None +) -> tuple[tuple[torch.Tensor, ...], int]: + """Flatten the arrays if axis is None.""" + if axis is None: + tensors = tuple(ar.flatten() for ar in tensors) + return tensors, 0 + else: + return tensors, axis + + +def typecast_tensor( + t: torch.Tensor, target_dtype: torch.dtype, casting: str +) -> torch.Tensor: + """Dtype-cast tensor to target_dtype. + + Parameters + ---------- + t : torch.Tensor + The tensor to cast + target_dtype : torch dtype object + The array dtype to cast all tensors to + casting : str + The casting mode, see `np.can_cast` + + Returns + ------- + `torch.Tensor` of the `target_dtype` dtype + + Raises + ------ + ValueError + if the argument cannot be cast according to the `casting` rule + + """ + can_cast = _dtypes_impl.can_cast_impl + + if not can_cast(t.dtype, target_dtype, casting=casting): + raise TypeError( + f"Cannot cast array data from {t.dtype} to" + f" {target_dtype} according to the rule '{casting}'" + ) + return cast_if_needed(t, target_dtype) + + +def typecast_tensors( + tensors: Sequence[torch.Tensor], target_dtype: torch.dtype, casting: str +) -> tuple[torch.Tensor, ...]: + return tuple(typecast_tensor(t, target_dtype, casting) for t in tensors) + + +def _try_convert_to_tensor(obj: object) -> torch.Tensor: + try: + tensor = torch.as_tensor(obj) + except Exception as e: + mesg = f"failed to convert {obj} to ndarray. \nInternal error is: {str(e)}." + raise NotImplementedError(mesg) # noqa: B904 + return tensor + + +def _coerce_to_tensor( + obj: object, + dtype: torch.dtype | None = None, + copy: bool = False, + ndmin: int = 0, +) -> torch.Tensor: + """The core logic of the array(...) function. + + Parameters + ---------- + obj : tensor_like + The thing to coerce + dtype : torch.dtype object or None + Coerce to this torch dtype + copy : bool + Copy or not + ndmin : int + The results as least this many dimensions + is_weak : bool + Whether obj is a weakly typed python scalar. + + Returns + ------- + tensor : torch.Tensor + a tensor object with requested dtype, ndim and copy semantics. + + Notes + ----- + This is almost a "tensor_like" coercive function. Does not handle wrapper + ndarrays (those should be handled in the ndarray-aware layer prior to + invoking this function). + """ + if isinstance(obj, torch.Tensor): + tensor = obj + else: + # tensor.dtype is the pytorch default, typically float32. If obj's elements + # are not exactly representable in float32, we've lost precision: + # >>> torch.as_tensor(1e12).item() - 1e12 + # -4096.0 + default_dtype = torch.get_default_dtype() + torch.set_default_dtype(_dtypes_impl.get_default_dtype_for(torch.float32)) + try: + tensor = _try_convert_to_tensor(obj) + finally: + torch.set_default_dtype(default_dtype) + + # type cast if requested + tensor = cast_if_needed(tensor, dtype) + + # adjust ndim if needed + ndim_extra = ndmin - tensor.ndim + if ndim_extra > 0: + tensor = tensor.view((1,) * ndim_extra + tensor.shape) + + # special handling for np._CopyMode + try: + copy = bool(copy) + except ValueError: + # TODO handle _CopyMode.IF_NEEDED correctly + copy = False + # copy if requested + if copy: + tensor = tensor.clone() + + return tensor + + +def ndarrays_to_tensors(*inputs: object) -> object: + """Convert all ndarrays from `inputs` to tensors. (other things are intact)""" + from ._ndarray import ndarray + + if len(inputs) == 0: + return ValueError() + elif len(inputs) == 1: + input_ = inputs[0] + if isinstance(input_, ndarray): + return input_.tensor + elif isinstance(input_, tuple): + result = [] + for sub_input in input_: + sub_result = ndarrays_to_tensors(sub_input) + result.append(sub_result) + return tuple(result) + else: + return input_ + else: + if not isinstance(inputs, tuple): + raise AssertionError( + f"Expected inputs to be a tuple, got {type(inputs).__name__}" + ) + return ndarrays_to_tensors(inputs) diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/fft.py b/.venv/lib/python3.12/site-packages/torch/_numpy/fft.py new file mode 100644 index 0000000000000000000000000000000000000000..6a0a0bf77c8a6fb82f7be038a051b660d49f27cc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/fft.py @@ -0,0 +1,191 @@ +from __future__ import annotations + +import functools +from typing import Concatenate, ParamSpec, TYPE_CHECKING, TypeVar + +import torch + +from . import _dtypes_impl, _util +from ._normalizations import ArrayLike, normalizer + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +def upcast( + func: Callable[Concatenate[torch.Tensor, _P], _R], +) -> Callable[Concatenate[torch.Tensor, _P], _R]: + """NumPy fft casts inputs to 64 bit and *returns 64-bit results*.""" + + @functools.wraps(func) + def wrapped(tensor: torch.Tensor, *args: _P.args, **kwds: _P.kwargs) -> _R: + target_dtype = ( + _dtypes_impl.default_dtypes().complex_dtype + if tensor.is_complex() + else _dtypes_impl.default_dtypes().float_dtype + ) + tensor = _util.cast_if_needed(tensor, target_dtype) + return func(tensor, *args, **kwds) + + return wrapped + + +@normalizer +@upcast +def fft( + a: ArrayLike, n: int | None = None, axis: int = -1, norm: str | None = None +) -> torch.Tensor: + return torch.fft.fft(a, n, dim=axis, norm=norm) + + +@normalizer +@upcast +def ifft( + a: ArrayLike, n: int | None = None, axis: int = -1, norm: str | None = None +) -> torch.Tensor: + return torch.fft.ifft(a, n, dim=axis, norm=norm) + + +@normalizer +@upcast +def rfft( + a: ArrayLike, n: int | None = None, axis: int = -1, norm: str | None = None +) -> torch.Tensor: + return torch.fft.rfft(a, n, dim=axis, norm=norm) + + +@normalizer +@upcast +def irfft( + a: ArrayLike, n: int | None = None, axis: int = -1, norm: str | None = None +) -> torch.Tensor: + return torch.fft.irfft(a, n, dim=axis, norm=norm) + + +@normalizer +@upcast +def fftn( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = None, + norm: str | None = None, +) -> torch.Tensor: + return torch.fft.fftn(a, s, dim=axes, norm=norm) + + +@normalizer +@upcast +def ifftn( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = None, + norm: str | None = None, +) -> torch.Tensor: + return torch.fft.ifftn(a, s, dim=axes, norm=norm) + + +@normalizer +@upcast +def rfftn( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = None, + norm: str | None = None, +) -> torch.Tensor: + return torch.fft.rfftn(a, s, dim=axes, norm=norm) + + +@normalizer +@upcast +def irfftn( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] | None = None, + norm: str | None = None, +) -> torch.Tensor: + return torch.fft.irfftn(a, s, dim=axes, norm=norm) + + +@normalizer +@upcast +def fft2( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] = (-2, -1), + norm: str | None = None, +) -> torch.Tensor: + return torch.fft.fft2(a, s, dim=axes, norm=norm) + + +@normalizer +@upcast +def ifft2( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] = (-2, -1), + norm: str | None = None, +) -> torch.Tensor: + return torch.fft.ifft2(a, s, dim=axes, norm=norm) + + +@normalizer +@upcast +def rfft2( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] = (-2, -1), + norm: str | None = None, +) -> torch.Tensor: + return torch.fft.rfft2(a, s, dim=axes, norm=norm) + + +@normalizer +@upcast +def irfft2( + a: ArrayLike, + s: Sequence[int] | None = None, + axes: Sequence[int] = (-2, -1), + norm: str | None = None, +) -> torch.Tensor: + return torch.fft.irfft2(a, s, dim=axes, norm=norm) + + +@normalizer +@upcast +def hfft( + a: ArrayLike, n: int | None = None, axis: int = -1, norm: str | None = None +) -> torch.Tensor: + return torch.fft.hfft(a, n, dim=axis, norm=norm) + + +@normalizer +@upcast +def ihfft( + a: ArrayLike, n: int | None = None, axis: int = -1, norm: str | None = None +) -> torch.Tensor: + return torch.fft.ihfft(a, n, dim=axis, norm=norm) + + +@normalizer +def fftfreq(n: int, d: float = 1.0) -> torch.Tensor: + return torch.fft.fftfreq(n, d) + + +@normalizer +def rfftfreq(n: int, d: float = 1.0) -> torch.Tensor: + return torch.fft.rfftfreq(n, d) + + +@normalizer +def fftshift(x: ArrayLike, axes: int | Sequence[int] | None = None) -> torch.Tensor: + return torch.fft.fftshift(x, axes) + + +@normalizer +def ifftshift(x: ArrayLike, axes: int | Sequence[int] | None = None) -> torch.Tensor: + return torch.fft.ifftshift(x, axes) diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/linalg.py b/.venv/lib/python3.12/site-packages/torch/_numpy/linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..13de71351038b48cab8d402cb424d280c27afa65 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/linalg.py @@ -0,0 +1,267 @@ +from __future__ import annotations + +import functools +import math +from typing import ParamSpec, TYPE_CHECKING, TypeVar + +import torch + +from . import _dtypes_impl, _util +from ._normalizations import ArrayLike, KeepDims, normalizer, OutArray + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +class LinAlgError(Exception): + pass + + +def _atleast_float_1(a: torch.Tensor) -> torch.Tensor: + if not (a.dtype.is_floating_point or a.dtype.is_complex): + a = a.to(_dtypes_impl.default_dtypes().float_dtype) + return a + + +def _atleast_float_2( + a: torch.Tensor, b: torch.Tensor +) -> tuple[torch.Tensor, torch.Tensor]: + dtyp = _dtypes_impl.result_type_impl(a, b) + if not (dtyp.is_floating_point or dtyp.is_complex): + dtyp = _dtypes_impl.default_dtypes().float_dtype + + a = _util.cast_if_needed(a, dtyp) + b = _util.cast_if_needed(b, dtyp) + return a, b + + +def linalg_errors(func: Callable[_P, _R]) -> Callable[_P, _R]: + @functools.wraps(func) + def wrapped(*args: _P.args, **kwds: _P.kwargs) -> _R: + try: + return func(*args, **kwds) + except torch._C._LinAlgError as e: # pyrefly: ignore[missing-attribute] # TODO + raise LinAlgError(*e.args) # noqa: B904 + + return wrapped + + +# ### Matrix and vector products ### + + +@normalizer +@linalg_errors +def matrix_power(a: ArrayLike, n: int) -> torch.Tensor: + a = _atleast_float_1(a) + return torch.linalg.matrix_power(a, n) + + +@normalizer +@linalg_errors +def multi_dot( + inputs: Sequence[ArrayLike], *, out: OutArray | None = None +) -> torch.Tensor: + return torch.linalg.multi_dot(inputs) + + +# ### Solving equations and inverting matrices ### + + +@normalizer +@linalg_errors +def solve(a: ArrayLike, b: ArrayLike) -> torch.Tensor: + a, b = _atleast_float_2(a, b) + return torch.linalg.solve(a, b) + + +@normalizer +@linalg_errors +def lstsq( + a: ArrayLike, b: ArrayLike, rcond: float | None = None +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + a, b = _atleast_float_2(a, b) + # NumPy is using gelsd: https://github.com/numpy/numpy/blob/v1.24.0/numpy/linalg/umath_linalg.cpp#L3991 + # on CUDA, only `gels` is available though, so use it instead + driver = "gels" if a.is_cuda or b.is_cuda else "gelsd" + return torch.linalg.lstsq(a, b, rcond=rcond, driver=driver) + + +@normalizer +@linalg_errors +def inv(a: ArrayLike) -> torch.Tensor: + a = _atleast_float_1(a) + result = torch.linalg.inv(a) + return result + + +@normalizer +@linalg_errors +def pinv(a: ArrayLike, rcond: float = 1e-15, hermitian: bool = False) -> torch.Tensor: + a = _atleast_float_1(a) + return torch.linalg.pinv(a, rtol=rcond, hermitian=hermitian) + + +@normalizer +@linalg_errors +def tensorsolve( + a: ArrayLike, b: ArrayLike, axes: Sequence[int] | None = None +) -> torch.Tensor: + a, b = _atleast_float_2(a, b) + return torch.linalg.tensorsolve(a, b, dims=axes) + + +@normalizer +@linalg_errors +def tensorinv(a: ArrayLike, ind: int = 2) -> torch.Tensor: + a = _atleast_float_1(a) + return torch.linalg.tensorinv(a, ind=ind) + + +# ### Norms and other numbers ### + + +@normalizer +@linalg_errors +def det(a: ArrayLike) -> torch.Tensor: + a = _atleast_float_1(a) + return torch.linalg.det(a) + + +@normalizer +@linalg_errors +def slogdet(a: ArrayLike) -> tuple[torch.Tensor, torch.Tensor]: + a = _atleast_float_1(a) + return torch.linalg.slogdet(a) + + +@normalizer +@linalg_errors +def cond(x: ArrayLike, p: int | str | None = None) -> torch.Tensor: + x = _atleast_float_1(x) + + # check if empty + # cf: https://github.com/numpy/numpy/blob/v1.24.0/numpy/linalg/linalg.py#L1744 + if x.numel() == 0 and math.prod(x.shape[-2:]) == 0: + raise LinAlgError("cond is not defined on empty arrays") + + result = torch.linalg.cond(x, p=p) + + # Convert nans to infs (numpy does it in a data-dependent way, depending on + # whether the input array has nans or not) + # XXX: NumPy does this: https://github.com/numpy/numpy/blob/v1.24.0/numpy/linalg/linalg.py#L1744 + return torch.where(torch.isnan(result), float("inf"), result) + + +@normalizer +@linalg_errors +def matrix_rank( + a: ArrayLike, tol: float | None = None, hermitian: bool = False +) -> torch.Tensor | int: + a = _atleast_float_1(a) + + if a.ndim < 2: + return int((a != 0).any()) + + if tol is None: + # follow https://github.com/numpy/numpy/blob/v1.24.0/numpy/linalg/linalg.py#L1885 + atol = 0 + rtol = max(a.shape[-2:]) * torch.finfo(a.dtype).eps + else: + atol, rtol = tol, 0 + return torch.linalg.matrix_rank(a, atol=atol, rtol=rtol, hermitian=hermitian) + + +@normalizer +@linalg_errors +def norm( + x: ArrayLike, + ord: int | float | str | None = None, + axis: int | tuple[int, ...] | None = None, + keepdims: KeepDims = False, +) -> torch.Tensor: + x = _atleast_float_1(x) + return torch.linalg.norm(x, ord=ord, dim=axis) + + +# ### Decompositions ### + + +@normalizer +@linalg_errors +def cholesky(a: ArrayLike) -> torch.Tensor: + a = _atleast_float_1(a) + return torch.linalg.cholesky(a) + + +@normalizer +@linalg_errors +def qr( + a: ArrayLike, mode: str = "reduced" +) -> tuple[torch.Tensor, torch.Tensor] | torch.Tensor: + a = _atleast_float_1(a) + result = torch.linalg.qr(a, mode=mode) + if mode == "r": + # match NumPy + return result.R + return result + + +@normalizer +@linalg_errors +def svd( + a: ArrayLike, + full_matrices: bool = True, + compute_uv: bool = True, + hermitian: bool = False, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor] | torch.Tensor: + a = _atleast_float_1(a) + if not compute_uv: + return torch.linalg.svdvals(a) + + # NB: ignore the hermitian= argument (no pytorch equivalent) + result = torch.linalg.svd(a, full_matrices=full_matrices) + return result + + +# ### Eigenvalues and eigenvectors ### + + +@normalizer +@linalg_errors +def eig(a: ArrayLike) -> tuple[torch.Tensor, torch.Tensor]: + a = _atleast_float_1(a) + w, vt = torch.linalg.eig(a) + + if not a.is_complex() and w.is_complex() and (w.imag == 0).all(): + w = w.real + vt = vt.real + return w, vt + + +@normalizer +@linalg_errors +def eigh(a: ArrayLike, UPLO: str = "L") -> tuple[torch.Tensor, torch.Tensor]: + a = _atleast_float_1(a) + return torch.linalg.eigh(a, UPLO=UPLO) + + +@normalizer +@linalg_errors +def eigvals(a: ArrayLike) -> torch.Tensor: + a = _atleast_float_1(a) + result = torch.linalg.eigvals(a) + if not a.is_complex() and result.is_complex() and (result.imag == 0).all(): + result = result.real + return result + + +@normalizer +@linalg_errors +def eigvalsh(a: ArrayLike, UPLO: str = "L") -> torch.Tensor: + a = _atleast_float_1(a) + return torch.linalg.eigvalsh(a, UPLO=UPLO) diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/random.py b/.venv/lib/python3.12/site-packages/torch/_numpy/random.py new file mode 100644 index 0000000000000000000000000000000000000000..9e42cc51f45915b709a64f75289048e211557326 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/random.py @@ -0,0 +1,191 @@ +# mypy: ignore-errors + +"""Wrapper to mimic (parts of) np.random API surface. + +NumPy has strict guarantees on reproducibility etc; here we don't give any. + +Q: default dtype is float64 in numpy + +""" + +from __future__ import annotations + +import functools +from math import sqrt + +import torch + +from . import _dtypes_impl, _util +from ._normalizations import array_or_scalar, ArrayLike, normalizer + + +__all__ = [ + "seed", + "random_sample", + "sample", + "random", + "rand", + "randn", + "normal", + "choice", + "randint", + "shuffle", + "uniform", +] + + +def use_numpy_random(): + # local import to avoid ref cycles + import torch._dynamo.config as config + + return config.use_numpy_random_stream + + +def deco_stream(func): + @functools.wraps(func) + def inner(*args, **kwds): + if not use_numpy_random(): + return func(*args, **kwds) + else: + import numpy + + from ._ndarray import ndarray + + f = getattr(numpy.random, func.__name__) + + # numpy funcs accept numpy ndarrays, unwrap + args = tuple( + arg.tensor.numpy() if isinstance(arg, ndarray) else arg for arg in args + ) + kwds = { + key: val.tensor.numpy() if isinstance(val, ndarray) else val + for key, val in kwds.items() + } + + value = f(*args, **kwds) + + # `value` can be either numpy.ndarray or python scalar (or None) + if isinstance(value, numpy.ndarray): + value = ndarray(torch.as_tensor(value)) + + return value + + return inner + + +@deco_stream +def seed(seed=None): + if seed is not None: + torch.random.manual_seed(seed) + + +@deco_stream +def random_sample(size=None): + if size is None: + size = () + dtype = _dtypes_impl.default_dtypes().float_dtype + values = torch.empty(size, dtype=dtype).uniform_() + return array_or_scalar(values, return_scalar=size == ()) + + +def rand(*size): + if size == (): + size = None + return random_sample(size) + + +sample = random_sample +random = random_sample + + +@deco_stream +def uniform(low=0.0, high=1.0, size=None): + if size is None: + size = () + dtype = _dtypes_impl.default_dtypes().float_dtype + values = torch.empty(size, dtype=dtype).uniform_(low, high) + return array_or_scalar(values, return_scalar=size == ()) + + +@deco_stream +def randn(*size): + dtype = _dtypes_impl.default_dtypes().float_dtype + values = torch.randn(size, dtype=dtype) + return array_or_scalar(values, return_scalar=size == ()) + + +@deco_stream +def normal(loc=0.0, scale=1.0, size=None): + if size is None: + size = () + dtype = _dtypes_impl.default_dtypes().float_dtype + values = torch.empty(size, dtype=dtype).normal_(loc, scale) + return array_or_scalar(values, return_scalar=size == ()) + + +@deco_stream +def shuffle(x): + # no @normalizer because we do not cast e.g. lists to tensors + from ._ndarray import ndarray + + if isinstance(x, torch.Tensor): + tensor = x + elif isinstance(x, ndarray): + tensor = x.tensor + else: + raise NotImplementedError("We do not random.shuffle lists in-place") + + perm = torch.randperm(tensor.shape[0]) + xp = tensor[perm] + tensor.copy_(xp) + + +@deco_stream +def randint(low, high=None, size=None): + if size is None: + size = () + if not isinstance(size, (tuple, list)): + size = (size,) + if high is None: + low, high = 0, low + values = torch.randint(low, high, size=size) + return array_or_scalar(values, int, return_scalar=size == ()) + + +@deco_stream +@normalizer +def choice(a: ArrayLike, size=None, replace=True, p: ArrayLike | None = None): + # https://stackoverflow.com/questions/59461811/random-choice-with-pytorch + if a.numel() == 1: + a = torch.arange(a) + + # TODO: check a.dtype is integer -- cf np.random.choice(3.4) which raises + + # number of draws + if size is None: + num_el = 1 + elif _util.is_sequence(size): + num_el = 1 + for el in size: + num_el *= el + else: + num_el = size + + # prepare the probabilities + if p is None: + p = torch.ones_like(a) / a.shape[0] + + # cf https://github.com/numpy/numpy/blob/main/numpy/random/mtrand.pyx#L973 + atol = sqrt(torch.finfo(p.dtype).eps) + if abs(p.sum() - 1.0) > atol: + raise ValueError("probabilities do not sum to 1.") + + # actually sample + indices = torch.multinomial(p, num_el, replacement=replace) + + if _util.is_sequence(size): + indices = indices.reshape(size) + + samples = a[indices] + + return samples diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/testing/__init__.py b/.venv/lib/python3.12/site-packages/torch/_numpy/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..05e73b12e29f8e6608647a3f16fabab39fbfb582 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/testing/__init__.py @@ -0,0 +1,20 @@ +# mypy: ignore-errors + +from .utils import ( + _gen_alignment_data, + assert_, + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, + assert_array_less, + assert_equal, + assert_raises_regex, + assert_warns, + HAS_REFCOUNT, + IS_WASM, + suppress_warnings, +) + + +# from .testing import assert_allclose # FIXME diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/testing/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/testing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09a454e2e41af22167d8e325ebba0c84bae22f51 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/testing/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/testing/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_numpy/testing/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..689835775329f97434efa3689defadf67cf9cf72 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_numpy/testing/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_numpy/testing/utils.py b/.venv/lib/python3.12/site-packages/torch/_numpy/testing/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3531904fc1ca872044d4a358e9d278ceec1dac37 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_numpy/testing/utils.py @@ -0,0 +1,2453 @@ +# mypy: ignore-errors + +""" +Utility function to facilitate testing. + +""" + +import contextlib +import gc +import operator +import os +import platform +import pprint +import re +import shutil +import sys +import warnings +from functools import wraps +from io import StringIO +from tempfile import mkdtemp, mkstemp +from warnings import WarningMessage + +import torch._numpy as np +from torch._numpy import arange, asarray as asanyarray, empty, float32, intp, ndarray + + +__all__ = [ + "assert_equal", + "assert_almost_equal", + "assert_approx_equal", + "assert_array_equal", + "assert_array_less", + "assert_string_equal", + "assert_", + "assert_array_almost_equal", + "build_err_msg", + "decorate_methods", + "print_assert_equal", + "verbose", + "assert_", + "assert_array_almost_equal_nulp", + "assert_raises_regex", + "assert_array_max_ulp", + "assert_warns", + "assert_no_warnings", + "assert_allclose", + "IgnoreException", + "clear_and_catch_warnings", + "temppath", + "tempdir", + "IS_PYPY", + "HAS_REFCOUNT", + "IS_WASM", + "suppress_warnings", + "assert_array_compare", + "assert_no_gc_cycles", + "break_cycles", + "IS_PYSTON", +] + + +verbose = 0 + +IS_WASM = platform.machine() in ["wasm32", "wasm64"] +IS_PYPY = sys.implementation.name == "pypy" +IS_PYSTON = hasattr(sys, "pyston_version_info") +HAS_REFCOUNT = getattr(sys, "getrefcount", None) is not None and not IS_PYSTON + + +def assert_(val, msg=""): + """ + Assert that works in release mode. + Accepts callable msg to allow deferring evaluation until failure. + + The Python built-in ``assert`` does not work when executing code in + optimized mode (the ``-O`` flag) - no byte-code is generated for it. + + For documentation on usage, refer to the Python documentation. + + """ + __tracebackhide__ = True # Hide traceback for py.test + if not val: + try: + smsg = msg() + except TypeError: + smsg = msg + raise AssertionError(smsg) + + +def gisnan(x): + return np.isnan(x) + + +def gisfinite(x): + return np.isfinite(x) + + +def gisinf(x): + return np.isinf(x) + + +def build_err_msg( + arrays, + err_msg, + header="Items are not equal:", + verbose=True, + names=("ACTUAL", "DESIRED"), + precision=8, +): + msg = ["\n" + header] + if err_msg: + if err_msg.find("\n") == -1 and len(err_msg) < 79 - len(header): + msg = [msg[0] + " " + err_msg] + else: + msg.append(err_msg) + if verbose: + for i, a in enumerate(arrays): + if isinstance(a, ndarray): + # precision argument is only needed if the objects are ndarrays + # r_func = partial(array_repr, precision=precision) + r_func = ndarray.__repr__ + else: + r_func = repr + + try: + r = r_func(a) + except Exception as exc: + r = f"[repr failed for <{type(a).__name__}>: {exc}]" + if r.count("\n") > 3: + r = "\n".join(r.splitlines()[:3]) + r += "..." + msg.append(f" {names[i]}: {r}") + return "\n".join(msg) + + +def assert_equal(actual, desired, err_msg="", verbose=True): + """ + Raises an AssertionError if two objects are not equal. + + Given two objects (scalars, lists, tuples, dictionaries or numpy arrays), + check that all elements of these objects are equal. An exception is raised + at the first conflicting values. + + When one of `actual` and `desired` is a scalar and the other is array_like, + the function checks that each element of the array_like object is equal to + the scalar. + + This function handles NaN comparisons as if NaN was a "normal" number. + That is, AssertionError is not raised if both objects have NaNs in the same + positions. This is in contrast to the IEEE standard on NaNs, which says + that NaN compared to anything must return False. + + Parameters + ---------- + actual : array_like + The object to check. + desired : array_like + The expected object. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired are not equal. + + Examples + -------- + >>> np.testing.assert_equal([4, 5], [4, 6]) + Traceback (most recent call last): + ... + AssertionError: + Items are not equal: + item=1 + ACTUAL: 5 + DESIRED: 6 + + The following comparison does not raise an exception. There are NaNs + in the inputs, but they are in the same positions. + + >>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan]) + + """ + __tracebackhide__ = True # Hide traceback for py.test + + num_nones = sum([actual is None, desired is None]) + if num_nones == 1: + raise AssertionError(f"Not equal: {actual} != {desired}") + elif num_nones == 2: + return True + # else, carry on + + if isinstance(actual, np.DType) or isinstance(desired, np.DType): + result = actual == desired + if not result: + raise AssertionError(f"Not equal: {actual} != {desired}") + else: + return True + + if isinstance(desired, str) and isinstance(actual, str): + if actual != desired: + raise AssertionError(f"Strings not equal: {actual!r} != {desired!r}") + return + + if isinstance(desired, dict): + if not isinstance(actual, dict): + raise AssertionError(repr(type(actual))) + assert_equal(len(actual), len(desired), err_msg, verbose) + for k in desired: + if k not in actual: + raise AssertionError(repr(k)) + assert_equal(actual[k], desired[k], f"key={k!r}\n{err_msg}", verbose) + return + if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)): + assert_equal(len(actual), len(desired), err_msg, verbose) + for k in range(len(desired)): + assert_equal(actual[k], desired[k], f"item={k!r}\n{err_msg}", verbose) + return + + from torch._numpy import imag, iscomplexobj, isscalar, ndarray, real, signbit + + if isinstance(actual, ndarray) or isinstance(desired, ndarray): + return assert_array_equal(actual, desired, err_msg, verbose) + msg = build_err_msg([actual, desired], err_msg, verbose=verbose) + + # Handle complex numbers: separate into real/imag to handle + # nan/inf/negative zero correctly + # XXX: catch ValueError for subclasses of ndarray where iscomplex fail + try: + usecomplex = iscomplexobj(actual) or iscomplexobj(desired) + except (ValueError, TypeError): + usecomplex = False + + if usecomplex: + if iscomplexobj(actual): + actualr = real(actual) + actuali = imag(actual) + else: + actualr = actual + actuali = 0 + if iscomplexobj(desired): + desiredr = real(desired) + desiredi = imag(desired) + else: + desiredr = desired + desiredi = 0 + try: + assert_equal(actualr, desiredr) + assert_equal(actuali, desiredi) + except AssertionError: + raise AssertionError(msg) # noqa: B904 + + # isscalar test to check cases such as [np.nan] != np.nan + if isscalar(desired) != isscalar(actual): + raise AssertionError(msg) + + # Inf/nan/negative zero handling + try: + isdesnan = gisnan(desired) + isactnan = gisnan(actual) + if isdesnan and isactnan: + return # both nan, so equal + + if desired == 0 and actual == 0: + if not signbit(desired) == signbit(actual): + raise AssertionError(msg) + + except (TypeError, ValueError, NotImplementedError): + pass + + try: + # Explicitly use __eq__ for comparison, gh-2552 + if not (desired == actual): + raise AssertionError(msg) + + except (DeprecationWarning, FutureWarning) as e: + # this handles the case when the two types are not even comparable + if "elementwise == comparison" in e.args[0]: + raise AssertionError(msg) # noqa: B904 + else: + raise + + +def print_assert_equal(test_string, actual, desired): + """ + Test if two objects are equal, and print an error message if test fails. + + The test is performed with ``actual == desired``. + + Parameters + ---------- + test_string : str + The message supplied to AssertionError. + actual : object + The object to test for equality against `desired`. + desired : object + The expected result. + + Examples + -------- + >>> np.testing.print_assert_equal( + ... "Test XYZ of func xyz", [0, 1], [0, 1] + ... ) # doctest: +SKIP + >>> np.testing.print_assert_equal( + ... "Test XYZ of func xyz", [0, 1], [0, 2] + ... ) # doctest: +SKIP + Traceback (most recent call last): + ... + AssertionError: Test XYZ of func xyz failed + ACTUAL: + [0, 1] + DESIRED: + [0, 2] + + """ + __tracebackhide__ = True # Hide traceback for py.test + import pprint + + if actual != desired: + msg = StringIO() + msg.write(test_string) + msg.write(" failed\nACTUAL: \n") + pprint.pprint(actual, msg) + msg.write("DESIRED: \n") + pprint.pprint(desired, msg) + raise AssertionError(msg.getvalue()) + + +def assert_almost_equal(actual, desired, decimal=7, err_msg="", verbose=True): + """ + Raises an AssertionError if two items are not equal up to desired + precision. + + .. note:: It is recommended to use one of `assert_allclose`, + `assert_array_almost_equal_nulp` or `assert_array_max_ulp` + instead of this function for more consistent floating point + comparisons. + + The test verifies that the elements of `actual` and `desired` satisfy. + + ``abs(desired-actual) < float64(1.5 * 10**(-decimal))`` + + That is a looser test than originally documented, but agrees with what the + actual implementation in `assert_array_almost_equal` did up to rounding + vagaries. An exception is raised at conflicting values. For ndarrays this + delegates to assert_array_almost_equal + + Parameters + ---------- + actual : array_like + The object to check. + desired : array_like + The expected object. + decimal : int, optional + Desired precision, default is 7. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired are not equal up to specified precision. + + See Also + -------- + assert_allclose: Compare two array_like objects for equality with desired + relative and/or absolute precision. + assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal + + Examples + -------- + >>> from torch._numpy.testing import assert_almost_equal + >>> assert_almost_equal(2.3333333333333, 2.33333334) + >>> assert_almost_equal(2.3333333333333, 2.33333334, decimal=10) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not almost equal to 10 decimals + ACTUAL: 2.3333333333333 + DESIRED: 2.33333334 + + >>> assert_almost_equal( + ... np.array([1.0, 2.3333333333333]), np.array([1.0, 2.33333334]), decimal=9 + ... ) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not almost equal to 9 decimals + + Mismatched elements: 1 / 2 (50%) + Max absolute difference: 6.666699636781459e-09 + Max relative difference: 2.8571569790287484e-09 + x: torch.ndarray([1.0000, 2.3333], dtype=float64) + y: torch.ndarray([1.0000, 2.3333], dtype=float64) + + """ + __tracebackhide__ = True # Hide traceback for py.test + from torch._numpy import imag, iscomplexobj, ndarray, real + + # Handle complex numbers: separate into real/imag to handle + # nan/inf/negative zero correctly + # XXX: catch ValueError for subclasses of ndarray where iscomplex fail + try: + usecomplex = iscomplexobj(actual) or iscomplexobj(desired) + except ValueError: + usecomplex = False + + def _build_err_msg(): + header = f"Arrays are not almost equal to {decimal:d} decimals" + return build_err_msg([actual, desired], err_msg, verbose=verbose, header=header) + + if usecomplex: + if iscomplexobj(actual): + actualr = real(actual) + actuali = imag(actual) + else: + actualr = actual + actuali = 0 + if iscomplexobj(desired): + desiredr = real(desired) + desiredi = imag(desired) + else: + desiredr = desired + desiredi = 0 + try: + assert_almost_equal(actualr, desiredr, decimal=decimal) + assert_almost_equal(actuali, desiredi, decimal=decimal) + except AssertionError: + raise AssertionError(_build_err_msg()) # noqa: B904 + + if isinstance(actual, (ndarray, tuple, list)) or isinstance( + desired, (ndarray, tuple, list) + ): + return assert_array_almost_equal(actual, desired, decimal, err_msg) + try: + # If one of desired/actual is not finite, handle it specially here: + # check that both are nan if any is a nan, and test for equality + # otherwise + if not (gisfinite(desired) and gisfinite(actual)): + if gisnan(desired) or gisnan(actual): + if not (gisnan(desired) and gisnan(actual)): + raise AssertionError(_build_err_msg()) + else: + if not desired == actual: + raise AssertionError(_build_err_msg()) + return + except (NotImplementedError, TypeError): + pass + if abs(desired - actual) >= np.float64(1.5 * 10.0 ** (-decimal)): + raise AssertionError(_build_err_msg()) + + +def assert_approx_equal(actual, desired, significant=7, err_msg="", verbose=True): + """ + Raises an AssertionError if two items are not equal up to significant + digits. + + .. note:: It is recommended to use one of `assert_allclose`, + `assert_array_almost_equal_nulp` or `assert_array_max_ulp` + instead of this function for more consistent floating point + comparisons. + + Given two numbers, check that they are approximately equal. + Approximately equal is defined as the number of significant digits + that agree. + + Parameters + ---------- + actual : scalar + The object to check. + desired : scalar + The expected object. + significant : int, optional + Desired precision, default is 7. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired are not equal up to specified precision. + + See Also + -------- + assert_allclose: Compare two array_like objects for equality with desired + relative and/or absolute precision. + assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal + + Examples + -------- + >>> np.testing.assert_approx_equal( + ... 0.12345677777777e-20, 0.1234567e-20 + ... ) # doctest: +SKIP + >>> np.testing.assert_approx_equal( + ... 0.12345670e-20, + ... 0.12345671e-20, # doctest: +SKIP + ... significant=8, + ... ) + >>> np.testing.assert_approx_equal( + ... 0.12345670e-20, + ... 0.12345672e-20, # doctest: +SKIP + ... significant=8, + ... ) + Traceback (most recent call last): + ... + AssertionError: + Items are not equal to 8 significant digits: + ACTUAL: 1.234567e-21 + DESIRED: 1.2345672e-21 + + the evaluated condition that raises the exception is + + >>> abs(0.12345670e-20 / 1e-21 - 0.12345672e-20 / 1e-21) >= 10 ** -(8 - 1) + True + + """ + __tracebackhide__ = True # Hide traceback for py.test + import numpy as np + + (actual, desired) = map(float, (actual, desired)) + if desired == actual: + return + # Normalized the numbers to be in range (-10.0,10.0) + # scale = float(pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual)))))) + scale = 0.5 * (np.abs(desired) + np.abs(actual)) + scale = np.power(10, np.floor(np.log10(scale))) + try: + sc_desired = desired / scale + except ZeroDivisionError: + sc_desired = 0.0 + try: + sc_actual = actual / scale + except ZeroDivisionError: + sc_actual = 0.0 + msg = build_err_msg( + [actual, desired], + err_msg, + header=f"Items are not equal to {significant:d} significant digits:", + verbose=verbose, + ) + try: + # If one of desired/actual is not finite, handle it specially here: + # check that both are nan if any is a nan, and test for equality + # otherwise + if not (gisfinite(desired) and gisfinite(actual)): + if gisnan(desired) or gisnan(actual): + if not (gisnan(desired) and gisnan(actual)): + raise AssertionError(msg) + else: + if not desired == actual: + raise AssertionError(msg) + return + except (TypeError, NotImplementedError): + pass + if np.abs(sc_desired - sc_actual) >= np.power(10.0, -(significant - 1)): + raise AssertionError(msg) + + +def assert_array_compare( + comparison, + x, + y, + err_msg="", + verbose=True, + header="", + precision=6, + equal_nan=True, + equal_inf=True, + *, + strict=False, +): + __tracebackhide__ = True # Hide traceback for py.test + from torch._numpy import all, array, asarray, bool_, inf, isnan, max + + x = asarray(x) + y = asarray(y) + + def array2string(a): + return str(a) + + # original array for output formatting + ox, oy = x, y + + def func_assert_same_pos(x, y, func=isnan, hasval="nan"): + """Handling nan/inf. + + Combine results of running func on x and y, checking that they are True + at the same locations. + + """ + __tracebackhide__ = True # Hide traceback for py.test + x_id = func(x) + y_id = func(y) + # We include work-arounds here to handle three types of slightly + # pathological ndarray subclasses: + # (1) all() on `masked` array scalars can return masked arrays, so we + # use != True + # (2) __eq__ on some ndarray subclasses returns Python booleans + # instead of element-wise comparisons, so we cast to bool_() and + # use isinstance(..., bool) checks + # (3) subclasses with bare-bones __array_function__ implementations may + # not implement np.all(), so favor using the .all() method + # We are not committed to supporting such subclasses, but it's nice to + # support them if possible. + if (x_id == y_id).all().item() is not True: + msg = build_err_msg( + [x, y], + err_msg + f"\nx and y {hasval} location mismatch:", + verbose=verbose, + header=header, + names=("x", "y"), + precision=precision, + ) + raise AssertionError(msg) + # If there is a scalar, then here we know the array has the same + # flag as it everywhere, so we should return the scalar flag. + if isinstance(x_id, bool) or x_id.ndim == 0: + return bool_(x_id) + elif isinstance(y_id, bool) or y_id.ndim == 0: + return bool_(y_id) + else: + return y_id + + try: + if strict: + cond = x.shape == y.shape and x.dtype == y.dtype + else: + cond = (x.shape == () or y.shape == ()) or x.shape == y.shape + if not cond: + if x.shape != y.shape: + reason = f"\n(shapes {x.shape}, {y.shape} mismatch)" + else: + reason = f"\n(dtypes {x.dtype}, {y.dtype} mismatch)" + msg = build_err_msg( + [x, y], + err_msg + reason, + verbose=verbose, + header=header, + names=("x", "y"), + precision=precision, + ) + raise AssertionError(msg) + + flagged = bool_(False) + + if equal_nan: + flagged = func_assert_same_pos(x, y, func=isnan, hasval="nan") + + if equal_inf: + flagged |= func_assert_same_pos( + x, y, func=lambda xy: xy == +inf, hasval="+inf" + ) + flagged |= func_assert_same_pos( + x, y, func=lambda xy: xy == -inf, hasval="-inf" + ) + + if flagged.ndim > 0: + x, y = x[~flagged], y[~flagged] + # Only do the comparison if actual values are left + if x.size == 0: + return + elif flagged: + # no sense doing comparison if everything is flagged. + return + + val = comparison(x, y) + + if isinstance(val, bool): + cond = val + reduced = array([val]) + else: + reduced = val.ravel() + cond = reduced.all() + + # The below comparison is a hack to ensure that fully masked + # results, for which val.ravel().all() returns np.ma.masked, + # do not trigger a failure (np.ma.masked != True evaluates as + # np.ma.masked, which is falsy). + if not cond: + n_mismatch = reduced.size - int(reduced.sum(dtype=intp)) + n_elements = flagged.size if flagged.ndim != 0 else reduced.size + percent_mismatch = 100 * n_mismatch / n_elements + remarks = [ + f"Mismatched elements: {n_mismatch} / {n_elements} ({percent_mismatch:.3g}%)" + ] + + # with errstate(all='ignore'): + # ignore errors for non-numeric types + with contextlib.suppress(TypeError, RuntimeError): + error = abs(x - y) + if np.issubdtype(x.dtype, np.unsignedinteger): + error2 = abs(y - x) + np.minimum(error, error2, out=error) + max_abs_error = max(error) + remarks.append( + "Max absolute difference: " + array2string(max_abs_error.item()) + ) + + # note: this definition of relative error matches that one + # used by assert_allclose (found in np.isclose) + # Filter values where the divisor would be zero + nonzero = bool_(y != 0) + if all(~nonzero): + max_rel_error = array(inf) + else: + max_rel_error = max(error[nonzero] / abs(y[nonzero])) + remarks.append( + "Max relative difference: " + array2string(max_rel_error.item()) + ) + + err_msg += "\n" + "\n".join(remarks) + msg = build_err_msg( + [ox, oy], + err_msg, + verbose=verbose, + header=header, + names=("x", "y"), + precision=precision, + ) + raise AssertionError(msg) + except ValueError: + import traceback + + efmt = traceback.format_exc() + header = f"error during assertion:\n\n{efmt}\n\n{header}" + + msg = build_err_msg( + [x, y], + err_msg, + verbose=verbose, + header=header, + names=("x", "y"), + precision=precision, + ) + raise ValueError(msg) # noqa: B904 + + +def assert_array_equal(x, y, err_msg="", verbose=True, *, strict=False): + """ + Raises an AssertionError if two array_like objects are not equal. + + Given two array_like objects, check that the shape is equal and all + elements of these objects are equal (but see the Notes for the special + handling of a scalar). An exception is raised at shape mismatch or + conflicting values. In contrast to the standard usage in numpy, NaNs + are compared like numbers, no assertion is raised if both objects have + NaNs in the same positions. + + The usual caution for verifying equality with floating point numbers is + advised. + + Parameters + ---------- + x : array_like + The actual object to check. + y : array_like + The desired, expected object. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + strict : bool, optional + If True, raise an AssertionError when either the shape or the data + type of the array_like objects does not match. The special + handling for scalars mentioned in the Notes section is disabled. + + Raises + ------ + AssertionError + If actual and desired objects are not equal. + + See Also + -------- + assert_allclose: Compare two array_like objects for equality with desired + relative and/or absolute precision. + assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal + + Notes + ----- + When one of `x` and `y` is a scalar and the other is array_like, the + function checks that each element of the array_like object is equal to + the scalar. This behaviour can be disabled with the `strict` parameter. + + Examples + -------- + The first assert does not raise an exception: + + >>> np.testing.assert_array_equal( + ... [1.0, 2.33333, np.nan], [np.exp(0), 2.33333, np.nan] + ... ) + + Use `assert_allclose` or one of the nulp (number of floating point values) + functions for these cases instead: + + >>> np.testing.assert_allclose( + ... [1.0, np.pi, np.nan], [1, np.sqrt(np.pi) ** 2, np.nan], rtol=1e-10, atol=0 + ... ) + + As mentioned in the Notes section, `assert_array_equal` has special + handling for scalars. Here the test checks that each value in `x` is 3: + + >>> x = np.full((2, 5), fill_value=3) + >>> np.testing.assert_array_equal(x, 3) + + Use `strict` to raise an AssertionError when comparing a scalar with an + array: + + >>> np.testing.assert_array_equal(x, 3, strict=True) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not equal + + (shapes (2, 5), () mismatch) + x: torch.ndarray([[3, 3, 3, 3, 3], + [3, 3, 3, 3, 3]]) + y: torch.ndarray(3) + + The `strict` parameter also ensures that the array data types match: + + >>> x = np.array([2, 2, 2]) + >>> y = np.array([2.0, 2.0, 2.0], dtype=np.float32) + >>> np.testing.assert_array_equal(x, y, strict=True) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not equal + + (dtypes dtype("int64"), dtype("float32") mismatch) + x: torch.ndarray([2, 2, 2]) + y: torch.ndarray([2., 2., 2.]) + """ + __tracebackhide__ = True # Hide traceback for py.test + assert_array_compare( + operator.__eq__, + x, + y, + err_msg=err_msg, + verbose=verbose, + header="Arrays are not equal", + strict=strict, + ) + + +def assert_array_almost_equal(x, y, decimal=6, err_msg="", verbose=True): + """ + Raises an AssertionError if two objects are not equal up to desired + precision. + + .. note:: It is recommended to use one of `assert_allclose`, + `assert_array_almost_equal_nulp` or `assert_array_max_ulp` + instead of this function for more consistent floating point + comparisons. + + The test verifies identical shapes and that the elements of ``actual`` and + ``desired`` satisfy. + + ``abs(desired-actual) < 1.5 * 10**(-decimal)`` + + That is a looser test than originally documented, but agrees with what the + actual implementation did up to rounding vagaries. An exception is raised + at shape mismatch or conflicting values. In contrast to the standard usage + in numpy, NaNs are compared like numbers, no assertion is raised if both + objects have NaNs in the same positions. + + Parameters + ---------- + x : array_like + The actual object to check. + y : array_like + The desired, expected object. + decimal : int, optional + Desired precision, default is 6. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired are not equal up to specified precision. + + See Also + -------- + assert_allclose: Compare two array_like objects for equality with desired + relative and/or absolute precision. + assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal + + Examples + -------- + the first assert does not raise an exception + + >>> np.testing.assert_array_almost_equal([1.0, 2.333, np.nan], [1.0, 2.333, np.nan]) + + >>> np.testing.assert_array_almost_equal( + ... [1.0, 2.33333, np.nan], [1.0, 2.33339, np.nan], decimal=5 + ... ) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not almost equal to 5 decimals + + Mismatched elements: 1 / 3 (33.3%) + Max absolute difference: 5.999999999994898e-05 + Max relative difference: 2.5713661239633743e-05 + x: torch.ndarray([1.0000, 2.3333, nan], dtype=float64) + y: torch.ndarray([1.0000, 2.3334, nan], dtype=float64) + + >>> np.testing.assert_array_almost_equal( + ... [1.0, 2.33333, np.nan], [1.0, 2.33333, 5], decimal=5 + ... ) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not almost equal to 5 decimals + + x and y nan location mismatch: + x: torch.ndarray([1.0000, 2.3333, nan], dtype=float64) + y: torch.ndarray([1.0000, 2.3333, 5.0000], dtype=float64) + + """ + __tracebackhide__ = True # Hide traceback for py.test + from torch._numpy import any as npany, float_, issubdtype, number, result_type + + def compare(x, y): + try: + if npany(gisinf(x)) or npany(gisinf(y)): + xinfid = gisinf(x) + yinfid = gisinf(y) + if not (xinfid == yinfid).all(): + return False + # if one item, x and y is +- inf + if x.size == y.size == 1: + return x == y + x = x[~xinfid] + y = y[~yinfid] + except (TypeError, NotImplementedError): + pass + + # make sure y is an inexact type to avoid abs(MIN_INT); will cause + # casting of x later. + dtype = result_type(y, 1.0) + y = asanyarray(y, dtype) + z = abs(x - y) + + if not issubdtype(z.dtype, number): + z = z.astype(float_) # handle object arrays + + return z < 1.5 * 10.0 ** (-decimal) + + assert_array_compare( + compare, + x, + y, + err_msg=err_msg, + verbose=verbose, + header=f"Arrays are not almost equal to {decimal:d} decimals", + precision=decimal, + ) + + +def assert_array_less(x, y, err_msg="", verbose=True): + """ + Raises an AssertionError if two array_like objects are not ordered by less + than. + + Given two array_like objects, check that the shape is equal and all + elements of the first object are strictly smaller than those of the + second object. An exception is raised at shape mismatch or incorrectly + ordered values. Shape mismatch does not raise if an object has zero + dimension. In contrast to the standard usage in numpy, NaNs are + compared, no assertion is raised if both objects have NaNs in the same + positions. + + + + Parameters + ---------- + x : array_like + The smaller object to check. + y : array_like + The larger object to compare. + err_msg : string + The error message to be printed in case of failure. + verbose : bool + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired objects are not equal. + + See Also + -------- + assert_array_equal: tests objects for equality + assert_array_almost_equal: test objects for equality up to precision + + + + Examples + -------- + >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan]) + >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan]) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not less-ordered + + Mismatched elements: 1 / 3 (33.3%) + Max absolute difference: 1.0 + Max relative difference: 0.5 + x: torch.ndarray([1., 1., nan], dtype=float64) + y: torch.ndarray([1., 2., nan], dtype=float64) + + >>> np.testing.assert_array_less([1.0, 4.0], 3) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not less-ordered + + Mismatched elements: 1 / 2 (50%) + Max absolute difference: 2.0 + Max relative difference: 0.6666666666666666 + x: torch.ndarray([1., 4.], dtype=float64) + y: torch.ndarray(3) + + >>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4]) + Traceback (most recent call last): + ... + AssertionError: + Arrays are not less-ordered + + (shapes (3,), (1,) mismatch) + x: torch.ndarray([1., 2., 3.], dtype=float64) + y: torch.ndarray([4]) + + """ + __tracebackhide__ = True # Hide traceback for py.test + assert_array_compare( + operator.__lt__, + x, + y, + err_msg=err_msg, + verbose=verbose, + header="Arrays are not less-ordered", + equal_inf=False, + ) + + +def assert_string_equal(actual, desired): + """ + Test if two strings are equal. + + If the given strings are equal, `assert_string_equal` does nothing. + If they are not equal, an AssertionError is raised, and the diff + between the strings is shown. + + Parameters + ---------- + actual : str + The string to test for equality against the expected string. + desired : str + The expected string. + + Examples + -------- + >>> np.testing.assert_string_equal("abc", "abc") # doctest: +SKIP + >>> np.testing.assert_string_equal("abc", "abcd") # doctest: +SKIP + Traceback (most recent call last): + File "", line 1, in + ... + AssertionError: Differences in strings: + - abc+ abcd? + + + """ + # delay import of difflib to reduce startup time + __tracebackhide__ = True # Hide traceback for py.test + import difflib + + if not isinstance(actual, str): + raise AssertionError(repr(type(actual))) + if not isinstance(desired, str): + raise AssertionError(repr(type(desired))) + if desired == actual: + return + + diff = list( + difflib.Differ().compare(actual.splitlines(True), desired.splitlines(True)) + ) + diff_list = [] + while diff: + d1 = diff.pop(0) + if d1.startswith(" "): + continue + if d1.startswith("- "): + l = [d1] + d2 = diff.pop(0) + if d2.startswith("? "): + l.append(d2) + d2 = diff.pop(0) + if not d2.startswith("+ "): + raise AssertionError(repr(d2)) + l.append(d2) + if diff: + d3 = diff.pop(0) + if d3.startswith("? "): + l.append(d3) + else: + diff.insert(0, d3) + if d2[2:] == d1[2:]: + continue + diff_list.extend(l) + continue + raise AssertionError(repr(d1)) + if not diff_list: + return + msg = f"Differences in strings:\n{''.join(diff_list).rstrip()}" + if actual != desired: + raise AssertionError(msg) + + +import unittest + + +class _Dummy(unittest.TestCase): + def nop(self): + pass + + +_d = _Dummy("nop") + + +def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs): + """ + assert_raises_regex(exception_class, expected_regexp, callable, *args, + **kwargs) + assert_raises_regex(exception_class, expected_regexp) + + Fail unless an exception of class exception_class and with message that + matches expected_regexp is thrown by callable when invoked with arguments + args and keyword arguments kwargs. + + Alternatively, can be used as a context manager like `assert_raises`. + + Notes + ----- + .. versionadded:: 1.9.0 + + """ + __tracebackhide__ = True # Hide traceback for py.test + return _d.assertRaisesRegex(exception_class, expected_regexp, *args, **kwargs) + + +def decorate_methods(cls, decorator, testmatch=None): + """ + Apply a decorator to all methods in a class matching a regular expression. + + The given decorator is applied to all public methods of `cls` that are + matched by the regular expression `testmatch` + (``testmatch.search(methodname)``). Methods that are private, i.e. start + with an underscore, are ignored. + + Parameters + ---------- + cls : class + Class whose methods to decorate. + decorator : function + Decorator to apply to methods + testmatch : compiled regexp or str, optional + The regular expression. Default value is None, in which case the + nose default (``re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)``) + is used. + If `testmatch` is a string, it is compiled to a regular expression + first. + + """ + if testmatch is None: + testmatch = re.compile(rf"(?:^|[\\b_\\.{os.sep}-])[Tt]est") + else: + testmatch = re.compile(testmatch) + cls_attr = cls.__dict__ + + # delayed import to reduce startup time + from inspect import isfunction + + methods = [_m for _m in cls_attr.values() if isfunction(_m)] + for function in methods: + try: + if hasattr(function, "compat_func_name"): + funcname = function.compat_func_name + else: + funcname = function.__name__ + except AttributeError: + # not a function + continue + if testmatch.search(funcname) and not funcname.startswith("_"): + setattr(cls, funcname, decorator(function)) + return + + +def _assert_valid_refcount(op): + """ + Check that ufuncs don't mishandle refcount of object `1`. + Used in a few regression tests. + """ + if not HAS_REFCOUNT: + return True + + import gc + + import numpy as np + + b = np.arange(100 * 100).reshape(100, 100) + c = b + i = 1 + + gc.disable() + try: + rc = sys.getrefcount(i) + for _ in range(15): + d = op(b, c) + assert_(sys.getrefcount(i) >= rc) + finally: + gc.enable() + del d # for pyflakes + + +def assert_allclose( + actual, + desired, + rtol=1e-7, + atol=0, + equal_nan=True, + err_msg="", + verbose=True, + check_dtype=False, +): + """ + Raises an AssertionError if two objects are not equal up to desired + tolerance. + + Given two array_like objects, check that their shapes and all elements + are equal (but see the Notes for the special handling of a scalar). An + exception is raised if the shapes mismatch or any values conflict. In + contrast to the standard usage in numpy, NaNs are compared like numbers, + no assertion is raised if both objects have NaNs in the same positions. + + The test is equivalent to ``allclose(actual, desired, rtol, atol)`` (note + that ``allclose`` has different default values). It compares the difference + between `actual` and `desired` to ``atol + rtol * abs(desired)``. + + .. versionadded:: 1.5.0 + + Parameters + ---------- + actual : array_like + Array obtained. + desired : array_like + Array desired. + rtol : float, optional + Relative tolerance. + atol : float, optional + Absolute tolerance. + equal_nan : bool, optional. + If True, NaNs will compare equal. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired are not equal up to specified precision. + + See Also + -------- + assert_array_almost_equal_nulp, assert_array_max_ulp + + Notes + ----- + When one of `actual` and `desired` is a scalar and the other is + array_like, the function checks that each element of the array_like + object is equal to the scalar. + + Examples + -------- + >>> x = [1e-5, 1e-3, 1e-1] + >>> y = np.arccos(np.cos(x)) + >>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0) + + """ + __tracebackhide__ = True # Hide traceback for py.test + + def compare(x, y): + return np.isclose(x, y, rtol=rtol, atol=atol, equal_nan=equal_nan) + + actual, desired = asanyarray(actual), asanyarray(desired) + header = f"Not equal to tolerance rtol={rtol:g}, atol={atol:g}" + + if check_dtype: + if actual.dtype != desired.dtype: + raise AssertionError(f"dtype mismatch: {actual.dtype} != {desired.dtype}") + + assert_array_compare( + compare, + actual, + desired, + err_msg=str(err_msg), + verbose=verbose, + header=header, + equal_nan=equal_nan, + ) + + +def assert_array_almost_equal_nulp(x, y, nulp=1): + """ + Compare two arrays relatively to their spacing. + + This is a relatively robust method to compare two arrays whose amplitude + is variable. + + Parameters + ---------- + x, y : array_like + Input arrays. + nulp : int, optional + The maximum number of unit in the last place for tolerance (see Notes). + Default is 1. + + Returns + ------- + None + + Raises + ------ + AssertionError + If the spacing between `x` and `y` for one or more elements is larger + than `nulp`. + + See Also + -------- + assert_array_max_ulp : Check that all items of arrays differ in at most + N Units in the Last Place. + spacing : Return the distance between x and the nearest adjacent number. + + Notes + ----- + An assertion is raised if the following condition is not met:: + + abs(x - y) <= nulp * spacing(maximum(abs(x), abs(y))) + + Examples + -------- + >>> x = np.array([1.0, 1e-10, 1e-20]) + >>> eps = np.finfo(x.dtype).eps + >>> np.testing.assert_array_almost_equal_nulp(x, x * eps / 2 + x) # doctest: +SKIP + + >>> np.testing.assert_array_almost_equal_nulp(x, x * eps + x) # doctest: +SKIP + Traceback (most recent call last): + ... + AssertionError: X and Y are not equal to 1 ULP (max is 2) + + """ + __tracebackhide__ = True # Hide traceback for py.test + import numpy as np + + ax = np.abs(x) + ay = np.abs(y) + ref = nulp * np.spacing(np.where(ax > ay, ax, ay)) + if not np.all(np.abs(x - y) <= ref): + if np.iscomplexobj(x) or np.iscomplexobj(y): + msg = f"X and Y are not equal to {nulp:d} ULP" + else: + max_nulp = np.max(nulp_diff(x, y)) + msg = f"X and Y are not equal to {nulp:d} ULP (max is {max_nulp:g})" + raise AssertionError(msg) + + +def assert_array_max_ulp(a, b, maxulp=1, dtype=None): + """ + Check that all items of arrays differ in at most N Units in the Last Place. + + Parameters + ---------- + a, b : array_like + Input arrays to be compared. + maxulp : int, optional + The maximum number of units in the last place that elements of `a` and + `b` can differ. Default is 1. + dtype : dtype, optional + Data-type to convert `a` and `b` to if given. Default is None. + + Returns + ------- + ret : ndarray + Array containing number of representable floating point numbers between + items in `a` and `b`. + + Raises + ------ + AssertionError + If one or more elements differ by more than `maxulp`. + + Notes + ----- + For computing the ULP difference, this API does not differentiate between + various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000 + is zero). + + See Also + -------- + assert_array_almost_equal_nulp : Compare two arrays relatively to their + spacing. + + Examples + -------- + >>> a = np.linspace(0.0, 1.0, 100) + >>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a))) # doctest: +SKIP + + """ + __tracebackhide__ = True # Hide traceback for py.test + import numpy as np + + ret = nulp_diff(a, b, dtype) + if not np.all(ret <= maxulp): + raise AssertionError( + f"Arrays are not almost equal up to {maxulp:g} " + f"ULP (max difference is {np.max(ret):g} ULP)" + ) + return ret + + +def nulp_diff(x, y, dtype=None): + """For each item in x and y, return the number of representable floating + points between them. + + Parameters + ---------- + x : array_like + first input array + y : array_like + second input array + dtype : dtype, optional + Data-type to convert `x` and `y` to if given. Default is None. + + Returns + ------- + nulp : array_like + number of representable floating point numbers between each item in x + and y. + + Notes + ----- + For computing the ULP difference, this API does not differentiate between + various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000 + is zero). + + Examples + -------- + # By definition, epsilon is the smallest number such as 1 + eps != 1, so + # there should be exactly one ULP between 1 and 1 + eps + >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps) # doctest: +SKIP + 1.0 + """ + import numpy as np + + if dtype: + x = np.asarray(x, dtype=dtype) + y = np.asarray(y, dtype=dtype) + else: + x = np.asarray(x) + y = np.asarray(y) + + t = np.common_type(x, y) + if np.iscomplexobj(x) or np.iscomplexobj(y): + raise NotImplementedError("_nulp not implemented for complex array") + + x = np.array([x], dtype=t) + y = np.array([y], dtype=t) + + x[np.isnan(x)] = np.nan + y[np.isnan(y)] = np.nan + + if not x.shape == y.shape: + raise ValueError(f"x and y do not have the same shape: {x.shape} - {y.shape}") + + def _diff(rx, ry, vdt): + diff = np.asarray(rx - ry, dtype=vdt) + return np.abs(diff) + + rx = integer_repr(x) + ry = integer_repr(y) + return _diff(rx, ry, t) + + +def _integer_repr(x, vdt, comp): + # Reinterpret binary representation of the float as sign-magnitude: + # take into account two's-complement representation + # See also + # https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ + rx = x.view(vdt) + if rx.size != 1: + rx[rx < 0] = comp - rx[rx < 0] + else: + if rx < 0: + rx = comp - rx + + return rx + + +def integer_repr(x): + """Return the signed-magnitude interpretation of the binary representation + of x.""" + import numpy as np + + if x.dtype == np.float16: + return _integer_repr(x, np.int16, np.int16(-(2**15))) + elif x.dtype == np.float32: + return _integer_repr(x, np.int32, np.int32(-(2**31))) + elif x.dtype == np.float64: + return _integer_repr(x, np.int64, np.int64(-(2**63))) + else: + raise ValueError(f"Unsupported dtype {x.dtype}") + + +@contextlib.contextmanager +def _assert_warns_context(warning_class, name=None): + __tracebackhide__ = True # Hide traceback for py.test + with suppress_warnings() as sup: + l = sup.record(warning_class) + yield + if not len(l) > 0: + name_str = f" when calling {name}" if name is not None else "" + raise AssertionError("No warning raised" + name_str) + + +def assert_warns(warning_class, *args, **kwargs): + """ + Fail unless the given callable throws the specified warning. + + A warning of class warning_class should be thrown by the callable when + invoked with arguments args and keyword arguments kwargs. + If a different type of warning is thrown, it will not be caught. + + If called with all arguments other than the warning class omitted, may be + used as a context manager: + + with assert_warns(SomeWarning): + do_something() + + The ability to be used as a context manager is new in NumPy v1.11.0. + + .. versionadded:: 1.4.0 + + Parameters + ---------- + warning_class : class + The class defining the warning that `func` is expected to throw. + func : callable, optional + Callable to test + *args : Arguments + Arguments for `func`. + **kwargs : Kwargs + Keyword arguments for `func`. + + Returns + ------- + The value returned by `func`. + + Examples + -------- + >>> import warnings + >>> def deprecated_func(num): + ... warnings.warn("Please upgrade", DeprecationWarning) + ... return num * num + >>> with np.testing.assert_warns(DeprecationWarning): + ... assert deprecated_func(4) == 16 + >>> # or passing a func + >>> ret = np.testing.assert_warns(DeprecationWarning, deprecated_func, 4) + >>> assert ret == 16 + """ + if not args: + return _assert_warns_context(warning_class) + + func = args[0] + args = args[1:] + with _assert_warns_context(warning_class, name=func.__name__): + return func(*args, **kwargs) + + +@contextlib.contextmanager +def _assert_no_warnings_context(name=None): + __tracebackhide__ = True # Hide traceback for py.test + with warnings.catch_warnings(record=True) as l: + warnings.simplefilter("always") + yield + if len(l) > 0: + name_str = f" when calling {name}" if name is not None else "" + raise AssertionError(f"Got warnings{name_str}: {l}") + + +def assert_no_warnings(*args, **kwargs): + """ + Fail if the given callable produces any warnings. + + If called with all arguments omitted, may be used as a context manager: + + with assert_no_warnings(): + do_something() + + The ability to be used as a context manager is new in NumPy v1.11.0. + + .. versionadded:: 1.7.0 + + Parameters + ---------- + func : callable + The callable to test. + \\*args : Arguments + Arguments passed to `func`. + \\*\\*kwargs : Kwargs + Keyword arguments passed to `func`. + + Returns + ------- + The value returned by `func`. + + """ + if not args: + return _assert_no_warnings_context() + + func = args[0] + args = args[1:] + with _assert_no_warnings_context(name=func.__name__): + return func(*args, **kwargs) + + +def _gen_alignment_data(dtype=float32, type="binary", max_size=24): + """ + generator producing data with different alignment and offsets + to test simd vectorization + + Parameters + ---------- + dtype : dtype + data type to produce + type : string + 'unary': create data for unary operations, creates one input + and output array + 'binary': create data for binary operations, creates two input + and output array + max_size : integer + maximum size of data to produce + + Returns + ------- + if type is 'unary' yields one output, one input array and a message + containing information on the data + if type is 'binary' yields one output array, two input array and a message + containing information on the data + + """ + ufmt = "unary offset=(%d, %d), size=%d, dtype=%r, %s" + bfmt = "binary offset=(%d, %d, %d), size=%d, dtype=%r, %s" + for o in range(3): + for s in range(o + 2, max(o + 3, max_size)): + if type == "unary": + + def inp(): + return arange(s, dtype=dtype)[o:] + + out = empty((s,), dtype=dtype)[o:] + yield out, inp(), ufmt % (o, o, s, dtype, "out of place") + d = inp() + yield d, d, ufmt % (o, o, s, dtype, "in place") + yield ( + out[1:], + inp()[:-1], + ufmt + % ( + o + 1, + o, + s - 1, + dtype, + "out of place", + ), + ) + yield ( + out[:-1], + inp()[1:], + ufmt + % ( + o, + o + 1, + s - 1, + dtype, + "out of place", + ), + ) + yield inp()[:-1], inp()[1:], ufmt % (o, o + 1, s - 1, dtype, "aliased") + yield inp()[1:], inp()[:-1], ufmt % (o + 1, o, s - 1, dtype, "aliased") + if type == "binary": + + def inp1(): + return arange(s, dtype=dtype)[o:] + + inp2 = inp1 + out = empty((s,), dtype=dtype)[o:] + yield out, inp1(), inp2(), bfmt % (o, o, o, s, dtype, "out of place") + d = inp1() + yield d, d, inp2(), bfmt % (o, o, o, s, dtype, "in place1") + d = inp2() + yield d, inp1(), d, bfmt % (o, o, o, s, dtype, "in place2") + yield ( + out[1:], + inp1()[:-1], + inp2()[:-1], + bfmt + % ( + o + 1, + o, + o, + s - 1, + dtype, + "out of place", + ), + ) + yield ( + out[:-1], + inp1()[1:], + inp2()[:-1], + bfmt + % ( + o, + o + 1, + o, + s - 1, + dtype, + "out of place", + ), + ) + yield ( + out[:-1], + inp1()[:-1], + inp2()[1:], + bfmt + % ( + o, + o, + o + 1, + s - 1, + dtype, + "out of place", + ), + ) + yield ( + inp1()[1:], + inp1()[:-1], + inp2()[:-1], + bfmt + % ( + o + 1, + o, + o, + s - 1, + dtype, + "aliased", + ), + ) + yield ( + inp1()[:-1], + inp1()[1:], + inp2()[:-1], + bfmt + % ( + o, + o + 1, + o, + s - 1, + dtype, + "aliased", + ), + ) + yield ( + inp1()[:-1], + inp1()[:-1], + inp2()[1:], + bfmt + % ( + o, + o, + o + 1, + s - 1, + dtype, + "aliased", + ), + ) + + +class IgnoreException(Exception): + "Ignoring this exception due to disabled feature" + + +@contextlib.contextmanager +def tempdir(*args, **kwargs): + """Context manager to provide a temporary test folder. + + All arguments are passed as this to the underlying tempfile.mkdtemp + function. + + """ + tmpdir = mkdtemp(*args, **kwargs) + try: + yield tmpdir + finally: + shutil.rmtree(tmpdir) + + +@contextlib.contextmanager +def temppath(*args, **kwargs): + """Context manager for temporary files. + + Context manager that returns the path to a closed temporary file. Its + parameters are the same as for tempfile.mkstemp and are passed directly + to that function. The underlying file is removed when the context is + exited, so it should be closed at that time. + + Windows does not allow a temporary file to be opened if it is already + open, so the underlying file must be closed after opening before it + can be opened again. + + """ + fd, path = mkstemp(*args, **kwargs) + os.close(fd) + try: + yield path + finally: + os.remove(path) + + +class clear_and_catch_warnings(warnings.catch_warnings): + """Context manager that resets warning registry for catching warnings + + Warnings can be slippery, because, whenever a warning is triggered, Python + adds a ``__warningregistry__`` member to the *calling* module. This makes + it impossible to retrigger the warning in this module, whatever you put in + the warnings filters. This context manager accepts a sequence of `modules` + as a keyword argument to its constructor and: + + * stores and removes any ``__warningregistry__`` entries in given `modules` + on entry; + * resets ``__warningregistry__`` to its previous state on exit. + + This makes it possible to trigger any warning afresh inside the context + manager without disturbing the state of warnings outside. + + For compatibility with Python 3.0, please consider all arguments to be + keyword-only. + + Parameters + ---------- + record : bool, optional + Specifies whether warnings should be captured by a custom + implementation of ``warnings.showwarning()`` and be appended to a list + returned by the context manager. Otherwise None is returned by the + context manager. The objects appended to the list are arguments whose + attributes mirror the arguments to ``showwarning()``. + modules : sequence, optional + Sequence of modules for which to reset warnings registry on entry and + restore on exit. To work correctly, all 'ignore' filters should + filter by one of these modules. + + Examples + -------- + >>> import warnings + >>> with np.testing.clear_and_catch_warnings( # doctest: +SKIP + ... modules=[np.core.fromnumeric] + ... ): + ... warnings.simplefilter("always") + ... warnings.filterwarnings("ignore", module="np.core.fromnumeric") + ... # do something that raises a warning but ignore those in + ... # np.core.fromnumeric + """ + + class_modules = () + + def __init__(self, record=False, modules=()): + self.modules = set(modules).union(self.class_modules) + self._warnreg_copies = {} + super().__init__(record=record) + + def __enter__(self): + for mod in self.modules: + if hasattr(mod, "__warningregistry__"): + mod_reg = mod.__warningregistry__ + self._warnreg_copies[mod] = mod_reg.copy() + mod_reg.clear() + return super().__enter__() + + def __exit__(self, *exc_info): + super().__exit__(*exc_info) + for mod in self.modules: + if hasattr(mod, "__warningregistry__"): + mod.__warningregistry__.clear() + if mod in self._warnreg_copies: + mod.__warningregistry__.update(self._warnreg_copies[mod]) + + +class suppress_warnings: + """ + Context manager and decorator doing much the same as + ``warnings.catch_warnings``. + + However, it also provides a filter mechanism to work around + https://bugs.python.org/issue4180. + + This bug causes Python before 3.4 to not reliably show warnings again + after they have been ignored once (even within catch_warnings). It + means that no "ignore" filter can be used easily, since following + tests might need to see the warning. Additionally it allows easier + specificity for testing warnings and can be nested. + + Parameters + ---------- + forwarding_rule : str, optional + One of "always", "once", "module", or "location". Analogous to + the usual warnings module filter mode, it is useful to reduce + noise mostly on the outmost level. Unsuppressed and unrecorded + warnings will be forwarded based on this rule. Defaults to "always". + "location" is equivalent to the warnings "default", match by exact + location the warning originated from. + + Notes + ----- + Filters added inside the context manager will be discarded again + when leaving it. Upon entering all filters defined outside a + context will be applied automatically. + + When a recording filter is added, matching warnings are stored in the + ``log`` attribute as well as in the list returned by ``record``. + + If filters are added and the ``module`` keyword is given, the + warning registry of this module will additionally be cleared when + applying it, entering the context, or exiting it. This could cause + warnings to appear a second time after leaving the context if they + were configured to be printed once (default) and were already + printed before the context was entered. + + Nesting this context manager will work as expected when the + forwarding rule is "always" (default). Unfiltered and unrecorded + warnings will be passed out and be matched by the outer level. + On the outmost level they will be printed (or caught by another + warnings context). The forwarding rule argument can modify this + behaviour. + + Like ``catch_warnings`` this context manager is not threadsafe. + + Examples + -------- + + With a context manager:: + + with np.testing.suppress_warnings() as sup: + sup.filter(DeprecationWarning, "Some text") + sup.filter(module=np.ma.core) + log = sup.record(FutureWarning, "Does this occur?") + command_giving_warnings() + # The FutureWarning was given once, the filtered warnings were + # ignored. All other warnings abide outside settings (may be + # printed/error) + assert_(len(log) == 1) + assert_(len(sup.log) == 1) # also stored in log attribute + + Or as a decorator:: + + sup = np.testing.suppress_warnings() + sup.filter(module=np.ma.core) # module must match exactly + + + @sup + def some_function(): + # do something which causes a warning in np.ma.core + pass + """ + + def __init__(self, forwarding_rule="always"): + self._entered = False + + # Suppressions are either instance or defined inside one with block: + self._suppressions = [] + + if forwarding_rule not in {"always", "module", "once", "location"}: + raise ValueError("unsupported forwarding rule.") + self._forwarding_rule = forwarding_rule + + def _clear_registries(self): + if hasattr(warnings, "_filters_mutated"): + # clearing the registry should not be necessary on new pythons, + # instead the filters should be mutated. + warnings._filters_mutated() + return + # Simply clear the registry, this should normally be harmless, + # note that on new pythons it would be invalidated anyway. + for module in self._tmp_modules: + if hasattr(module, "__warningregistry__"): + module.__warningregistry__.clear() + + def _filter(self, category=Warning, message="", module=None, record=False): + if record: + record = [] # The log where to store warnings + else: + record = None + if self._entered: + if module is None: + warnings.filterwarnings("always", category=category, message=message) + else: + module_regex = module.__name__.replace(".", r"\.") + "$" + warnings.filterwarnings( + "always", category=category, message=message, module=module_regex + ) + self._tmp_modules.add(module) + self._clear_registries() + + self._tmp_suppressions.append( + (category, message, re.compile(message, re.IGNORECASE), module, record) + ) + else: + self._suppressions.append( + (category, message, re.compile(message, re.IGNORECASE), module, record) + ) + + return record + + def filter(self, category=Warning, message="", module=None): + """ + Add a new suppressing filter or apply it if the state is entered. + + Parameters + ---------- + category : class, optional + Warning class to filter + message : string, optional + Regular expression matching the warning message. + module : module, optional + Module to filter for. Note that the module (and its file) + must match exactly and cannot be a submodule. This may make + it unreliable for external modules. + + Notes + ----- + When added within a context, filters are only added inside + the context and will be forgotten when the context is exited. + """ + self._filter(category=category, message=message, module=module, record=False) + + def record(self, category=Warning, message="", module=None): + """ + Append a new recording filter or apply it if the state is entered. + + All warnings matching will be appended to the ``log`` attribute. + + Parameters + ---------- + category : class, optional + Warning class to filter + message : string, optional + Regular expression matching the warning message. + module : module, optional + Module to filter for. Note that the module (and its file) + must match exactly and cannot be a submodule. This may make + it unreliable for external modules. + + Returns + ------- + log : list + A list which will be filled with all matched warnings. + + Notes + ----- + When added within a context, filters are only added inside + the context and will be forgotten when the context is exited. + """ + return self._filter( + category=category, message=message, module=module, record=True + ) + + def __enter__(self): + if self._entered: + raise RuntimeError("cannot enter suppress_warnings twice.") + + self._orig_show = warnings.showwarning + self._filters = warnings.filters + warnings.filters = self._filters[:] + + self._entered = True + self._tmp_suppressions = [] + self._tmp_modules = set() + self._forwarded = set() + + self.log = [] # reset global log (no need to keep same list) + + for cat, mess, _, mod, log in self._suppressions: + if log is not None: + del log[:] # clear the log + if mod is None: + warnings.filterwarnings("always", category=cat, message=mess) + else: + module_regex = mod.__name__.replace(".", r"\.") + "$" + warnings.filterwarnings( + "always", category=cat, message=mess, module=module_regex + ) + self._tmp_modules.add(mod) + warnings.showwarning = self._showwarning + self._clear_registries() + + return self + + def __exit__(self, *exc_info): + warnings.showwarning = self._orig_show + warnings.filters = self._filters + self._clear_registries() + self._entered = False + del self._orig_show + del self._filters + + def _showwarning( + self, message, category, filename, lineno, *args, use_warnmsg=None, **kwargs + ): + for cat, _, pattern, mod, rec in (self._suppressions + self._tmp_suppressions)[ + ::-1 + ]: + if issubclass(category, cat) and pattern.match(message.args[0]) is not None: + if mod is None: + # Message and category match, either recorded or ignored + if rec is not None: + msg = WarningMessage( + message, category, filename, lineno, **kwargs + ) + self.log.append(msg) + rec.append(msg) + return + # Use startswith, because warnings strips the c or o from + # .pyc/.pyo files. + elif mod.__file__.startswith(filename): + # The message and module (filename) match + if rec is not None: + msg = WarningMessage( + message, category, filename, lineno, **kwargs + ) + self.log.append(msg) + rec.append(msg) + return + + # There is no filter in place, so pass to the outside handler + # unless we should only pass it once + if self._forwarding_rule == "always": + if use_warnmsg is None: + self._orig_show(message, category, filename, lineno, *args, **kwargs) + else: + self._orig_showmsg(use_warnmsg) + return + + if self._forwarding_rule == "once": + signature = (message.args, category) + elif self._forwarding_rule == "module": + signature = (message.args, category, filename) + elif self._forwarding_rule == "location": + signature = (message.args, category, filename, lineno) + + if signature in self._forwarded: + return + self._forwarded.add(signature) + if use_warnmsg is None: + self._orig_show(message, category, filename, lineno, *args, **kwargs) + else: + self._orig_showmsg(use_warnmsg) + + def __call__(self, func): + """ + Function decorator to apply certain suppressions to a whole + function. + """ + + @wraps(func) + def new_func(*args, **kwargs): + with self: + return func(*args, **kwargs) + + return new_func + + +@contextlib.contextmanager +def _assert_no_gc_cycles_context(name=None): + __tracebackhide__ = True # Hide traceback for py.test + + # not meaningful to test if there is no refcounting + if not HAS_REFCOUNT: + yield + return + + assert_(gc.isenabled()) + gc.disable() + gc_debug = gc.get_debug() + try: + for _ in range(100): + if gc.collect() == 0: + break + else: + raise RuntimeError( + "Unable to fully collect garbage - perhaps a __del__ method " + "is creating more reference cycles?" + ) + + gc.set_debug(gc.DEBUG_SAVEALL) + yield + # gc.collect returns the number of unreachable objects in cycles that + # were found -- we are checking that no cycles were created in the context + n_objects_in_cycles = gc.collect() + objects_in_cycles = gc.garbage[:] + finally: + del gc.garbage[:] + gc.set_debug(gc_debug) + gc.enable() + + if n_objects_in_cycles: + name_str = f" when calling {name}" if name is not None else "" + raise AssertionError( + "Reference cycles were found{}: {} objects were collected, " + "of which {} are shown below:{}".format( + name_str, + n_objects_in_cycles, + len(objects_in_cycles), + "".join( + "\n {} object with id={}:\n {}".format( + type(o).__name__, + id(o), + pprint.pformat(o).replace("\n", "\n "), + ) + for o in objects_in_cycles + ), + ) + ) + + +def assert_no_gc_cycles(*args, **kwargs): + """ + Fail if the given callable produces any reference cycles. + + If called with all arguments omitted, may be used as a context manager: + + with assert_no_gc_cycles(): + do_something() + + .. versionadded:: 1.15.0 + + Parameters + ---------- + func : callable + The callable to test. + \\*args : Arguments + Arguments passed to `func`. + \\*\\*kwargs : Kwargs + Keyword arguments passed to `func`. + + Returns + ------- + Nothing. The result is deliberately discarded to ensure that all cycles + are found. + + """ + if not args: + return _assert_no_gc_cycles_context() + + func = args[0] + args = args[1:] + with _assert_no_gc_cycles_context(name=func.__name__): + func(*args, **kwargs) + + +def break_cycles(): + """ + Break reference cycles by calling gc.collect + Objects can call other objects' methods (for instance, another object's + __del__) inside their own __del__. On PyPy, the interpreter only runs + between calls to gc.collect, so multiple calls are needed to completely + release all cycles. + """ + + gc.collect() + if IS_PYPY: + # a few more, just to make sure all the finalizers are called + gc.collect() + gc.collect() + gc.collect() + gc.collect() + + +def requires_memory(free_bytes): + """Decorator to skip a test if not enough memory is available""" + import pytest + + def decorator(func): + @wraps(func) + def wrapper(*a, **kw): + msg = check_free_memory(free_bytes) + if msg is not None: + pytest.skip(msg) + + try: + return func(*a, **kw) + except MemoryError: + # Probably ran out of memory regardless: don't regard as failure + pytest.xfail("MemoryError raised") + + return wrapper + + return decorator + + +def check_free_memory(free_bytes): + """ + Check whether `free_bytes` amount of memory is currently free. + Returns: None if enough memory available, otherwise error message + """ + env_var = "NPY_AVAILABLE_MEM" + env_value = os.environ.get(env_var) + if env_value is not None: + try: + mem_free = _parse_size(env_value) + except ValueError as exc: + raise ValueError( # noqa: B904 + f"Invalid environment variable {env_var}: {exc}" + ) + + msg = ( + f"{free_bytes / 1e9} GB memory required, but environment variable " + f"NPY_AVAILABLE_MEM={env_value} set" + ) + else: + mem_free = _get_mem_available() + + if mem_free is None: + msg = ( + "Could not determine available memory; set NPY_AVAILABLE_MEM " + "environment variable (e.g. NPY_AVAILABLE_MEM=16GB) to run " + "the test." + ) + mem_free = -1 + else: + msg = f"{free_bytes / 1e9} GB memory required, but {mem_free / 1e9} GB available" + + return msg if mem_free < free_bytes else None + + +def _parse_size(size_str): + """Convert memory size strings ('12 GB' etc.) to float""" + suffixes = { + "": 1, + "b": 1, + "k": 1000, + "m": 1000**2, + "g": 1000**3, + "t": 1000**4, + "kb": 1000, + "mb": 1000**2, + "gb": 1000**3, + "tb": 1000**4, + "kib": 1024, + "mib": 1024**2, + "gib": 1024**3, + "tib": 1024**4, + } + + size_re = re.compile( + r"^\s*(\d+|\d+\.\d+)\s*({})\s*$".format("|".join(suffixes.keys())), + re.IGNORECASE, + ) + + m = size_re.match(size_str.lower()) + if not m or m.group(2) not in suffixes: + raise ValueError(f"value {size_str!r} not a valid size") + return int(float(m.group(1)) * suffixes[m.group(2)]) + + +def _get_mem_available(): + """Return available memory in bytes, or None if unknown.""" + try: + import psutil + + return psutil.virtual_memory().available + except (ImportError, AttributeError): + pass + + if sys.platform.startswith("linux"): + info = {} + with open("/proc/meminfo") as f: + for line in f: + p = line.split() + info[p[0].strip(":").lower()] = int(p[1]) * 1024 + + if "memavailable" in info: + # Linux >= 3.14 + return info["memavailable"] + else: + return info["memfree"] + info["cached"] + + return None + + +def _no_tracing(func): + """ + Decorator to temporarily turn off tracing for the duration of a test. + Needed in tests that check refcounting, otherwise the tracing itself + influences the refcounts + """ + if not hasattr(sys, "gettrace"): + return func + else: + + @wraps(func) + def wrapper(*args, **kwargs): + original_trace = sys.gettrace() + try: + sys.settrace(None) + return func(*args, **kwargs) + finally: + sys.settrace(original_trace) + + return wrapper + + +def _get_glibc_version(): + try: + ver = os.confstr("CS_GNU_LIBC_VERSION").rsplit(" ")[1] + except Exception: + ver = "0.0" + + return ver + + +_glibcver = _get_glibc_version() + + +def _glibc_older_than(x): + return _glibcver != "0.0" and _glibcver < x diff --git a/.venv/lib/python3.12/site-packages/torch/_opaque_base.py b/.venv/lib/python3.12/site-packages/torch/_opaque_base.py new file mode 100644 index 0000000000000000000000000000000000000000..9751634df5eaf836fb1f8769875006936d3e9ae3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_opaque_base.py @@ -0,0 +1,11 @@ +import logging + + +log = logging.getLogger(__name__) + +log.warning("torch._opaque_base is deprecated, use torch._custom_class_base instead") + +from torch._custom_class_base import ( # noqa: F401 + CustomClassBase as OpaqueBase, + CustomClassBaseMeta as OpaqueBaseMeta, +) diff --git a/.venv/lib/python3.12/site-packages/torch/_ops.py b/.venv/lib/python3.12/site-packages/torch/_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..481846f08673facc383ec003294d8cfc40c428c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_ops.py @@ -0,0 +1,1594 @@ +# mypy: allow-untyped-defs +import abc +import contextlib +import ctypes +import importlib +import inspect +import sys +import types +from collections.abc import Callable, Iterator +from dataclasses import dataclass +from functools import cached_property +from typing import Any, ClassVar, Concatenate, final, Generic, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar + +import torch +import torch.utils._pytree as pytree +from torch import _utils_internal +from torch._C import ( + _dispatch_is_included_in_alias as is_included_in_alias, + DispatchKey, + DispatchKeySet, +) +from torch._functorch.pyfunctorch import dispatch_functorch, TransformType +from torch.utils._python_dispatch import TorchDispatchMode + + +try: + from types import NotImplementedType # Python 3.10+ +except ImportError: # pragma: no cover + NotImplementedType = type(NotImplemented) # type: ignore[misc] + + +if TYPE_CHECKING: + from torch._subclasses.functional_tensor import BaseFunctionalizeAPI + + +_T = TypeVar("_T", default=Any) +_P = ParamSpec("_P", default=...) + + +# Query `hasattr` only once. +_SET_GLOBAL_FLAGS = hasattr(sys, "getdlopenflags") and hasattr(sys, "setdlopenflags") + + +@contextlib.contextmanager +def dl_open_guard(): + """ + Context manager to set the RTLD_GLOBAL dynamic linker flag while we open a + shared library to load custom operators. + """ + if not _SET_GLOBAL_FLAGS: + yield + return + old_flags = sys.getdlopenflags() + sys.setdlopenflags(old_flags | ctypes.RTLD_GLOBAL) + try: + yield + finally: + sys.setdlopenflags(old_flags) + + +class OperatorBase: + """ + Base class for OpOverload (which represents C++ ATen operators) and HigherOrderOperator + (which represents Python-only operators that are unrepresentable in TorchScript). + """ + + def __init__(self): + # The dispatch cache precomputes a mapping of dispatch key that the + # dispatcher wants to dispatch to, to an actual implementation of the + # dispatch key. Confusingly, the actual implementation could *also* be a + # dispatch key, but in this case, this refers to the C++ kernel that + # was registered to some dispatch key. Aliases are permitted in the + # latter but not the former; for example, you might lookup the + # entry for AutogradCPU, and this maps you to the Autograd key for + # the generic autograd kernel that works for all devices. Since this + # is the Python dispatcher, you can also put an arbitrary Python + # callable to call instead. This handler gets precisely the + # args/kwargs that the operator was __call__'ed with. + # NB: This name is hard-coded in torch/csrc/autograd/python_variable.cpp + # for use with OpOverload; cache lookup is done entirely from C++ + # for speed. + # TODO: The cache is NOT currently used by HigherOrderOperator, but it should! + self._dispatch_cache: dict[DispatchKey, DispatchKey | Callable[..., Any]] = {} + + # This table allows you to override the behavior of a particular + # dispatch key to call a custom Python function, rather than the + # ordinary C++ configured behavior. This is the raison d'etre of # codespell:ignore + # Python dispatcher: to let you program the dispatcher from Python + # in case you need something unusual, and don't want to clobber + # the existing registrations using the Python operator registration + # API. + self.py_kernels: dict[DispatchKey, Callable[..., Any]] = {} + + # This table allows you to override the behavior of a particular + # operator for a particular TorchDispatchMode. In practice, + # we are using this mostly for ProxyTensorMode. Modes can be + # thought of as an open world extension of dispatch keys, so it + # makes sense that you should be able to register them, the same + # way you can register dispatch keys. + self.python_key_table: dict[ + type[TorchDispatchMode | torch.Tensor], Callable[..., Any] + ] = {} + + # This table allows you to override the behavior of functorch + # transformations. NB: this currently only does something for + # HigherOrderOperator + self.functorch_table = {} + + def __call__(self, *args, **kwargs): + raise NotImplementedError + + def has_kernel_for_dispatch_key(self, k): + return k in self.py_kernels + + def has_kernel_for_any_dispatch_key(self, ks): + for k in self.py_kernels: + if not torch._C._dispatch_is_alias_key(k) and ks.has(k): + return True + return False + + def py_impl( + self, + k: type[TorchDispatchMode] | type[torch.Tensor] | TransformType | DispatchKey, + ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + def inner(fn: Callable[_P, _T]) -> Callable[_P, _T]: + if inspect.isclass(k) and ( + issubclass(k, TorchDispatchMode) or issubclass(k, torch.Tensor) + ): + if k in self.python_key_table: + raise AssertionError(f"{k} already registered in python_key_table") + # TODO(voz): Should we replace setting DispatchKey.Python entirely with setting mode keys? + self.python_key_table[k] = fn + self._dispatch_cache.clear() + return fn + + if isinstance(k, TransformType): + if k in self.functorch_table: + raise AssertionError(f"{k} already registered in functorch_table") + self.functorch_table[k] = fn + return fn + + if not isinstance(k, DispatchKey): + raise AssertionError(f"expected DispatchKey, got {type(k)}") + if k == DispatchKey.Python: + raise AssertionError( + "Please register a mode for the DispatchKey.Python key instead." + ) + + if k in self.py_kernels: + raise RuntimeError( + f"Trying to override a python impl for {k} on operator {self.name()}" + ) + self.py_kernels[k] = fn + self._dispatch_cache.clear() + return fn + + return inner + + # Registers an implementation to all **3** variants of functionalization that we have: + # - DispatchKey.Functionalize + # - functorch.TransformType.Functionalize + # - FunctionalTensorMode + # Example: + # @py_functionalize_impl + # def functionalize_rule(ctx, inner_f, *args): + # args_unwrapped = ctx.unwrap_tensors(args) + # with ctx.redispatch_to_next(): + # out = ctx.functionalize(inner_f)(*args_unwrapped) + # return ctx.wrap_tensors(out) + def py_functionalize_impl( + self, fn: Callable[Concatenate["BaseFunctionalizeAPI", _P], _T] + ) -> Callable[Concatenate["BaseFunctionalizeAPI", _P], _T]: + from torch._subclasses.functional_tensor import ( + CppFunctionalizeAPI, + FunctionalTensorMode, + FunctorchFunctionalizeAPI, + PythonFunctionalizeAPI, + ) + + # Construct our three flavors of functionalization, + # each of which have slightly different wrap/unwrap/redispatch policies + def functionalize_dk_fn(*args: _P.args, **kwargs: _P.kwargs) -> _T: + return fn(CppFunctionalizeAPI(), *args, **kwargs) + + def functionalize_dispatch_mode_fn( + mode: FunctionalTensorMode | None, *args: _P.args, **kwargs: _P.kwargs + ) -> _T | NotImplementedType: + from torch._higher_order_ops.utils import has_user_subclass + from torch._subclasses import FakeTensor + from torch._subclasses.functional_tensor import FunctionalTensor + + if has_user_subclass( + (args, kwargs), + allowed_subclasses=(FakeTensor, FunctionalTensor), + ): + return NotImplemented + return fn(PythonFunctionalizeAPI(mode), *args, **kwargs) + + def functionalize_functorch_fn( + interpreter, *args: _P.args, **kwargs: _P.kwargs + ) -> _T: + return fn(FunctorchFunctionalizeAPI(interpreter), *args, **kwargs) + + self.py_impl(DispatchKey.Functionalize)(functionalize_dk_fn) + self.py_impl(FunctionalTensorMode)(functionalize_dispatch_mode_fn) + self.py_impl(TransformType.Functionalize)(functionalize_functorch_fn) + + return fn + + def name(self): + raise NotImplementedError + + +# Equivalent to computeDispatchTableEntryWithDebug +def resolve_key(op: OperatorBase, k: DispatchKey): # type: ignore[valid-type] + # 1. (Direct) operator registration + if op.has_kernel_for_dispatch_key(k): + return k + # 2.1 Use CompositeExplicitAutogradNonFunctional kernel if available + cand = DispatchKey.CompositeExplicitAutogradNonFunctional + if ( + k == DispatchKey.Undefined or is_included_in_alias(k, cand) + ) and op.has_kernel_for_dispatch_key(cand): + return cand + # 2.2 Use CompositeExplicitAutograd kernel if available + cand = DispatchKey.CompositeExplicitAutograd + if ( + k == DispatchKey.Undefined or is_included_in_alias(k, cand) + ) and op.has_kernel_for_dispatch_key(cand): + return cand + has_backend_kernel = op.has_kernel_for_any_dispatch_key( + torch._C._dispatch_get_backend_keyset_from_autograd(k) + ) or op.has_kernel_for_dispatch_key(DispatchKey.CompositeExplicitAutograd) + # 2.3. Use CompositeImplicitAutograd kernel if available + cand = DispatchKey.CompositeImplicitAutogradNestedTensor + if ( + (k != DispatchKey.Undefined and is_included_in_alias(k, cand)) + and op.has_kernel_for_dispatch_key(cand) + and not has_backend_kernel + ): + return cand + cand = DispatchKey.CompositeImplicitAutograd + if ( + k == DispatchKey.Undefined or is_included_in_alias(k, cand) + ) and op.has_kernel_for_dispatch_key(cand): + if k == DispatchKey.AutogradOther and op.has_kernel_for_any_dispatch_key( + torch._C._dispatch_autogradother_backends + ): + raise RuntimeError("ambiguous autogradother kernel") + elif not has_backend_kernel: + return cand + # 2.4. For autograd backend keys, use kernel from DispatchKey::Autograd if available + cand = DispatchKey.Autograd + if is_included_in_alias(k, cand) and op.has_kernel_for_dispatch_key(cand): + return cand + # 2.5 Use kernel from DispatchKey::FuncTorchBatchedDecomposition if available + cand = DispatchKey.FuncTorchBatchedDecomposition + if is_included_in_alias(k, cand) and op.has_kernel_for_dispatch_key(cand): + return cand + # Backend fallback + if torch._C._dispatch_has_backend_fallback(k): + # The dispatch key itself will implicitly route to backend fallback. + # This is probably not great for the pure Python implementation. + return k + raise NotImplementedError(f"could not find kernel for {op} at dispatch key {k}") + + +_higher_order_ops: dict[str, "HigherOrderOperator"] = {} + +_HIGHER_ORDER_OP_DEFAULT_FALLTHROUGH_DISPATCH_KEYS = [ + DispatchKey.PythonDispatcher, # type: ignore[attr-defined] + DispatchKey.PythonTLSSnapshot, # type: ignore[attr-defined] + DispatchKey.ADInplaceOrView, + DispatchKey.BackendSelect, + DispatchKey.AutocastCPU, # type: ignore[attr-defined] + DispatchKey.AutocastCUDA, # type: ignore[attr-defined] + DispatchKey.AutocastXPU, # type: ignore[attr-defined] +] + + +class HigherOrderOperator(OperatorBase, abc.ABC): + # The HigherOrderOperator will appear as torch.ops.higher_order.{name} + # + # If you're creating a new HigherOrderOperator, please do not change the + # default. Adding operators to the global torch.ops namespace is a bad + # practice due to name collisions. + def __init__( + self, name, *, cacheable=False, supports_training_input_mutation=False + ): + super().__init__() + if type(self) is HigherOrderOperator: + raise RuntimeError( + "Direct instantiation of HigherOrderOperator is not allowed. Please subclass it." + ) + self._name = name + + # Make _OPNamespace not scream, this whole name based association needs a good hard look + self.__name__ = name + _higher_order_ops[name] = self + self._ns = "higher_order" + self.__module__ = "torch.ops.higher_order" + self._cacheable = cacheable + # When True, allows mutating inputs that don't require grad during + # training. Mutations must be handled by auto_functionalize before + # reaching autograd. + self._supports_training_input_mutation = supports_training_input_mutation + + self.non_fallthrough_keys = torch._C._dispatch_keyset_full() + + for dispatch_key in _HIGHER_ORDER_OP_DEFAULT_FALLTHROUGH_DISPATCH_KEYS: + self.fallthrough(dispatch_key) + + # [NOTE] We have to register pre-dispatch key implementation + # because sometimes HOP use aot-dispatch tracing to detect certain + # mutations. This is problematic when we are functionalizing HOP + # during pre-dispatch because when the inner tracer starts, it will see + # that PreDispatch key is still active. In that case, we just redispatch + # it to next key. This is only safe to do when PreDispatch key stack has no + # active modes. + + def py_impl( + self, + k: type[TorchDispatchMode] | type[torch.Tensor] | TransformType | DispatchKey, + ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + if isinstance(k, DispatchKey) and not self.non_fallthrough_keys.has(k): + self.non_fallthrough_keys = self.non_fallthrough_keys.add(k) + return super().py_impl(k) + + def py_autograd_impl( + self, + fn: Callable[_P, _T], + ) -> Callable[_P, _T]: + def maybe_run_autograd(*args: _P.args, **kwargs: _P.kwargs) -> _T: + if not torch.is_grad_enabled() or pytree.tree_all_only( + torch.Tensor, + lambda t: not t.requires_grad, # type: ignore[union-attr] + (*args, kwargs), + ): + with torch._C._AutoDispatchBelowAutograd(): + return self(*args, **kwargs) + + from torch._higher_order_ops.utils import _has_gen_schema + + if not self._supports_training_input_mutation and _has_gen_schema(self): + schema = self.gen_schema(*args, **kwargs) + if any(arg.is_write for arg in schema.arguments): + raise RuntimeError( + f"The {self.name()} HigherOrderOperator does not currently support training " + "with in-place input or buffer mutations " + "If you require this feature, please submit an issue to PyTorch. " + "Alternatively, consider creating your own custom autograd.Function. " + ) + + return fn(*args, **kwargs) + + self.py_impl(DispatchKey.Autograd)(maybe_run_autograd) + + return fn + + @property + def namespace(self): + return self._ns + + @final + def cacheable(self) -> bool: + from torch._functorch.autograd_function import AutogradFunctionApply + + return ( + self._cacheable + or f"{self.__module__}.{self.__name__}" + in torch._inductor.config.unsafe_marked_cacheable_functions + or ( + isinstance(self, AutogradFunctionApply) + and torch._functorch.config.autograd_cache_allow_custom_autograd_functions + ) + ) + + def fallthrough(self, dispatch_key): + self.non_fallthrough_keys = self.non_fallthrough_keys.remove(dispatch_key) + + def _get_overloaded_args( + self, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> tuple[torch.Tensor, ...]: + # Default HOP behavior matches handle_torch_function_no_python_arg_parser + # in torch/csrc/utils/python_arg_parser.cpp. + overloaded_args: list[torch.Tensor] = [] + + def has_python_key(tensor): + return torch._C._dispatch_keys(tensor).has("Python") + + def check_overloaded(arg): + if isinstance(arg, torch.Tensor) and has_python_key(arg): + overloaded_args.append(arg) + + for arg in (*args, *kwargs.values()): + check_overloaded(arg) + if isinstance(arg, (list, tuple)): + for a in arg: + check_overloaded(a) + + return tuple(overloaded_args) + + # Use positional-only argument to avoid naming collide with custom ops arguments + # that are named "self". + def dispatch(self, /, dispatch_key, *args, **kwargs): + from torch.utils._python_dispatch import _get_current_dispatch_mode + + if dispatch_key in self._dispatch_cache: + kernel = self._dispatch_cache[dispatch_key] + if isinstance(kernel, DispatchKey): + raise AssertionError(f"unexpected DispatchKey in cache: {kernel}") + return kernel(*args, **kwargs) + + if dispatch_key == DispatchKey.FuncTorchDynamicLayerFrontMode: + return dispatch_functorch(self, args, kwargs) + + if dispatch_key == DispatchKey.Python: + overloaded_args = self._get_overloaded_args(args, kwargs) + + # Step 1: dispatch on any user TorchDispatchModes + from torch.utils._python_dispatch import _pop_mode_temporarily + + curr_mode = _get_current_dispatch_mode() + if curr_mode is not None: + if type(curr_mode) in self.python_key_table: + handler = self.python_key_table[type(curr_mode)] + with _pop_mode_temporarily() as mode: + # "natural" calling convention: (mode, *args, **kwargs) + # TODO(rzou): we should support torch_dispatch calling convention too. + result = handler(mode, *args, **kwargs) + else: + if curr_mode.supports_higher_order_operators: + with _pop_mode_temporarily() as mode: + return curr_mode.__torch_dispatch__(self, [], args, kwargs) + else: + raise NotImplementedError( + f"There was no rule registered for HigherOrderOperator {self._name} and mode {curr_mode}." + f"Hint: set {curr_mode}'s supports_higher_order_operators to True." + f" This causes all higher order operators to pass through {curr_mode}'s __torch_dispatch__," + f" so handle them accordingly by" + f" adding support for HigerOrderOperators (in this case, {self._name}) in" + f" {curr_mode}.__torch_dispatch__ or" + f" returning NotImplemented when not supported." + ) + if result is not NotImplemented: + return result + + # Step 2: dispatch on any subclasses + for arg in overloaded_args: + subclass_type = type(arg) + if ( + subclass_type.__torch_dispatch__ + is torch._C._disabled_torch_dispatch_impl + ): + continue + + # In some case, people are using FakeTensor without a FakeTensorMode. + # For example, some sparse arch model has a mix of FakeTensor and real + # tensor for weights during lowering, and ppl tends to run eager evaluation + # on the model without setting up the FakeTensorMode. + # In this case, we pull FakeTensorMode impl. + if subclass_type is torch._subclasses.fake_tensor.FakeTensor: + subclass_type = torch._subclasses.fake_tensor.FakeTensorMode # type: ignore[assignment] + handler = self.python_key_table[subclass_type] + result = handler(arg.fake_mode, *args, **kwargs) # type: ignore[attr-defined] + return result + + if subclass_type in self.python_key_table: + handler = self.python_key_table[subclass_type] + # "natural" calling convention: (*args, **kwargs) + # TODO(rzou): we should support torch_dispatch calling convention too. + result = handler(*args, **kwargs) + else: + raise NotImplementedError( + f"There was no rule registered for HOP {self._name} and subclass {subclass_type}. " + f"We recommend filing an issue." + ) + if result is not NotImplemented: + return result + + # All handlers returned NotImplemented + raise TypeError( + f"HigherOrderOperator '{self._name}' is not supported for the given input types. " + f"This typically happens when using custom tensor types or dispatch modes that don't " + f"have implementations for this operation.\n\n" + f"Current mode: {curr_mode}\n" + f"Input types: {[type(a).__name__ for a in overloaded_args]}\n\n" + f"To fix this, can add support for '{self._name}' in {curr_mode}'s __torch_dispatch__\n" + ) + + functionality_key = torch._C._to_functionality_key(dispatch_key) # type: ignore[attr-defined] + if functionality_key == DispatchKey.PreDispatch: + from torch.utils._python_dispatch import _pop_mode_temporarily + + # The check for Python in the exclude set is so we properly respect `with no_dispatch()` + # calls inside of a mode. + if ( + _len_torch_dispatch_stack_pre_dispatch() > 0 + ) and not torch._C._dispatch_tls_is_dispatch_key_excluded( + DispatchKey.Python + ): + curr_mode = _get_current_dispatch_mode_pre_dispatch() + if curr_mode is None: + raise AssertionError( + "Illegal invocation of dispatch on DispatchKey.PreDispatch without a mode." + ) + if type(curr_mode) not in self.python_key_table: + raise AssertionError( + f"Current active mode {curr_mode} not registered" + ) + handler = self.python_key_table[type(curr_mode)] + with _pop_mode_temporarily(functionality_key) as mode: + return handler(mode, *args, **kwargs) + + final_key = resolve_key(self, dispatch_key) + + # This can current fail due to backend fallbacks. You just have to + # register them by hand for HigherOrderOperator. + if final_key not in self.py_kernels: + raise NotImplementedError( + f"could not find kernel for HigherOrderOperator {self._name} " + f"at dispatch key {final_key} (resolved from {dispatch_key})" + ) + + # [NOTE] We shouldn't cache PreDispatch kernel here because depending + # on what modes are active, predispatch behaviour is different. + # Also we do same thing for normal ops: + # See Note [Not Caching Per-Dispatch-Key Mode Handlers] + if dispatch_key != DispatchKey.PreDispatch: + self._dispatch_cache[dispatch_key] = self.py_kernels[final_key] + kernel = self.py_kernels[final_key] + # It's illegal to register DispatchKey to py_kernels, since there's no + # C++ kernel to call into + if isinstance(kernel, DispatchKey): + raise AssertionError(f"unexpected DispatchKey in py_kernels: {kernel}") + return kernel(*args, **kwargs) + + @abc.abstractmethod + def __call__(self, /, *args, **kwargs): + flat_args = _to_flat_tuple(args, kwargs) + if torch.overrides.has_torch_function(flat_args): + return torch.overrides.handle_torch_function( + self, flat_args, *args, **kwargs + ) + del flat_args + + dispatch_key_set = _compute_keyset(args, kwargs, self.non_fallthrough_keys) + return self.dispatch(dispatch_key_set.highestPriorityTypeId(), *args, **kwargs) + + # NOTE [HigherOrderOperator Schema] + # Each invocation of a HigherOrderOperator (hop) should have its own schema because + # the subgraphs and the arguments can be different even for the same hop. + # + # Each hop should implement its own gen_schema method, which should + # take the same input as the __call__ method and returns a FunctionSchema. + # The schema provides a unified way to check if the hop mutates its inputs, + # which can be useful in implementing optimizations. + # + # If the hop doesn't implement the gen_schema method, + # we expect it to be functional. It should not mutate its inputs and there + # are no input, output aliasing via views or direct referencing. + def gen_schema(self, *args, **kwargs): + raise NotImplementedError( + f"HigherOrderOperator {self._name} does not implement a gen_schema. " + f"This is OK as long as the hop is functional. " + f"e.g. it should not mutate its inputs and there are no input, output aliasing " + f"via views or direct referencing." + ) + + def __str__(self): + return f"{self.name()}" + + def name(self): + return self._name + + # it's a no-op since HigherOrderOperator is immutable and must be unique for a given op. + def __deepcopy__(self, memo=None): + return self + + +def _to_flat_tuple(args, kwargs): + return pytree.arg_tree_leaves(*args, **kwargs) + + +def _compute_keyset(args, kwargs, non_fallthrough_keys): + tensors = _get_tensors(args, kwargs) + return key_extractor(tensors, non_fallthrough_keys) + + +def _get_tensors(args, kwargs): + flat_all = _to_flat_tuple(args, kwargs) + tensor_args = [t for t in flat_all if isinstance(t, torch.Tensor)] + return tuple(tensor_args) + + +# Note - this should maintain identical impl to the C++ dispatcher key extraction logic +# at ATen/core/dispatch/DispatchKeyExtractor.h +def key_extractor(tensors, key_mask): + key_set = torch._C._dispatch_tls_local_include_set() + for tensor in tensors: + key_set = key_set | torch._C._dispatch_keys(tensor) + key_set = key_set - torch._C._dispatch_tls_local_exclude_set() + key_set = key_set & key_mask + return key_set + + +# Mode stack for PreDispatchKey +# it should always have three keys with +# priority given to FunctionalTensorMode and +# then ProxyTorchDispatchMode. It means that +# slot 0 belongs to ProxyTorchDispatchMode and +# slot 1 belongs to FunctionalTensorMode. +# +# SchemaCheckMode is separate from the other 2, +# and is only valid when the stack is empty. +# SchemaCheckMode is for testing purposes, and +# is meant to run in eager mode on concrete inputs, +# checking for incorrect schemas in regards to +# aliasing or mutating ops. +class _ModeStackStateForPreDispatch: + def __init__(self): + self.__infra_modes = [None, None] + self._schema_check_mode = None + + def set(self, index, mode): + if index >= len(self.__infra_modes): + raise AssertionError( + f"index {index} out of bounds for infra_modes length {len(self.__infra_modes)}" + ) + self.__infra_modes[index] = mode + + def get(self, index): + if index >= len(self.__infra_modes): + raise AssertionError( + f"index {index} out of bounds for infra_modes length {len(self.__infra_modes)}" + ) + return self.__infra_modes[index] + + def count(self): + return len([i for i in self.__infra_modes if i is not None]) + int( + self._schema_check_mode is not None + ) + + +_mode_stack_state_for_pre_dispatch = _ModeStackStateForPreDispatch() + + +def unset_mode_pre_dispatch(mode_key, schema_check=False): + current_mode_stack_pre_dispatch = mode_stack_state_for_pre_dispatch() + valid_keys = ( + torch._C._TorchDispatchModeKey.PROXY, + torch._C._TorchDispatchModeKey.FUNCTIONAL, + ) + if mode_key is not None and mode_key not in valid_keys: + raise AssertionError( + f"mode_key must be None or one of {valid_keys}, got {mode_key}" + ) + if schema_check: + if mode_key is not None: + raise AssertionError("mode_key must be None when schema_check is True") + + def _unset_mode(): + # NOTE: Using `is` rather than `==` to work around slow enum comparison in + # pybind11. + if mode_key is torch._C._TorchDispatchModeKey.PROXY: + current_mode = current_mode_stack_pre_dispatch.get(0) + mode_stack_state_for_pre_dispatch().set(0, None) + return current_mode + elif mode_key is torch._C._TorchDispatchModeKey.FUNCTIONAL: + current_mode = current_mode_stack_pre_dispatch.get(1) + mode_stack_state_for_pre_dispatch().set(1, None) + return current_mode + else: + current_mode = mode_stack_state_for_pre_dispatch()._schema_check_mode + mode_stack_state_for_pre_dispatch()._schema_check_mode = None + return current_mode + + current_mode = _unset_mode() + + new_pre_dispatch_len = _len_torch_dispatch_stack_pre_dispatch() + # When we are unsetting a mode, we need to check if there is + # active mode left on the PreDispatch key. If there is nothing + # active, we need to remove PreDispatch key from local dispatch include + # set. + if new_pre_dispatch_len == 0: + torch._C._dispatch_tls_set_dispatch_key_included(DispatchKey.PreDispatch, False) + + return current_mode + + +def _set_mode_pre_dispatch(mode): + from torch._subclasses.functional_tensor import FunctionalTensorMode + from torch._subclasses.schema_check_mode import SchemaCheckMode + from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode + + if not isinstance( + mode, + ( + FunctionalTensorMode, + ProxyTorchDispatchMode, + SchemaCheckMode, + ), + ): + raise AssertionError( + f"mode must be FunctionalTensorMode, ProxyTorchDispatchMode, or SchemaCheckMode, got {type(mode)}" + ) + + previous_mode_stack_len = _len_torch_dispatch_stack_pre_dispatch() + if isinstance(mode, SchemaCheckMode): + current_mode = mode_stack_state_for_pre_dispatch()._schema_check_mode + if previous_mode_stack_len > 0: + raise AssertionError( + "SchemaCheckMode for pre-dispatch must be used exclusively, found other modes on the stack" + ) + mode_stack_state_for_pre_dispatch()._schema_check_mode = mode + elif isinstance(mode, FunctionalTensorMode): + current_mode = mode_stack_state_for_pre_dispatch().get(1) + if current_mode is not None: + raise AssertionError( + f"FunctionalTensorMode slot already occupied by {current_mode}" + ) + mode_stack_state_for_pre_dispatch().set(1, mode) + else: + current_mode = mode_stack_state_for_pre_dispatch().get(0) + if current_mode is not None: + raise AssertionError( + f"ProxyTorchDispatchMode slot already occupied by {current_mode}" + ) + mode_stack_state_for_pre_dispatch().set(0, mode) + + # When we are setting a mode, we need to check if there is + # active mode left on the PreDispatch key. If there was nothing + # active before setting this mode, it means that PreDispatch key + # was turned off. So we need to turn it on again. + if previous_mode_stack_len == 0: + torch._C._dispatch_tls_set_dispatch_key_included(DispatchKey.PreDispatch, True) + + +def _pop_mode_from_pre_dispatch(): + mode_stack = mode_stack_state_for_pre_dispatch() + pre_dispatch_len = _len_torch_dispatch_stack_pre_dispatch() + + if pre_dispatch_len == 0: + raise AssertionError("Trying to pop empty mode stack") + + if mode_stack._schema_check_mode is not None: + return unset_mode_pre_dispatch(None, schema_check=True) + if mode_stack.get(1) is not None: + return unset_mode_pre_dispatch(torch._C._TorchDispatchModeKey.FUNCTIONAL) + if mode_stack.get(0) is not None: + return unset_mode_pre_dispatch(torch._C._TorchDispatchModeKey.PROXY) + + +def _len_torch_dispatch_stack_pre_dispatch(): + return mode_stack_state_for_pre_dispatch().count() + + +def _get_dispatch_mode_pre_dispatch(mode_key): + # NOTE: Using `is` rather than `==` to work around slow enum comparison in pybind11. + if mode_key is torch._C._TorchDispatchModeKey.PROXY: + return mode_stack_state_for_pre_dispatch().get(0) + else: + if mode_key is not torch._C._TorchDispatchModeKey.FUNCTIONAL: + raise AssertionError( + f"mode_key must be PROXY or FUNCTIONAL, got {mode_key}" + ) + return mode_stack_state_for_pre_dispatch().get(1) + + +def _get_current_dispatch_mode_pre_dispatch(): + if mode_stack_state_for_pre_dispatch()._schema_check_mode is not None: + return mode_stack_state_for_pre_dispatch()._schema_check_mode + else: + stack_len = mode_stack_state_for_pre_dispatch().count() + if stack_len == 2: + return mode_stack_state_for_pre_dispatch().get(1) + if stack_len == 1: + return ( + mode_stack_state_for_pre_dispatch().get(1) + if mode_stack_state_for_pre_dispatch().get(1) is not None + else mode_stack_state_for_pre_dispatch().get(0) + ) + return None + + +def mode_stack_state_for_pre_dispatch(): + global _mode_stack_state_for_pre_dispatch + return _mode_stack_state_for_pre_dispatch + + +cached_ops: set["OpOverload"] = set() + + +def add_cached_op(op_overload): + global cached_ops + cached_ops.add(op_overload) + + +def reset_cached_ops(): + global cached_ops + cached_ops.clear() + + +def get_cached_ops(): + global cached_ops + return cached_ops + + +@dataclass +class _PyObjectDispatcher(Generic[_P, _T]): + # [NOTE: PyObject Dispatcher aka pyobj_dispatcher] + # + # Custom operators whose kernels are implemented in Python currently need + # to make 1+ roundtrips into the C++ PyTorch dispatcher. These roundtrips + # are expensive; the main expensive thing is converting a PyObject + # to an IValue requires copying the at::Tensor, incurring at::Tensor + # and PyObject (at::Tensor owns a PyObject) refcount bumps. + # + # Instead, we introduce a new type of dispatching, "PyObject Dispatching". + # When dispatching an operator, we avoid converting PyObject into IValues, + # instead doing the dispatch key computation in a reimplementation in the + # Python-C API. This dispatch is implemented faithfully compared to the + # C++ dispatcher and shares helper functions. + # + # After we have computed a DispatchKey to dispatch on, we query the C++ + # Dispatcher for the kernel to be dispatched on. If the kernel is a Python + # kernel, then we directly pass the PyObject args to the Python kernel. + # if the kernel is a C++ kernel, then we perform a C++ Dispatcher redispatch + # (which ends up doing the expensive at::Tensor copies). + dispatch: Callable[_P, _T] + redispatch: Callable[Concatenate[DispatchKeySet, _P], _T] + + +# Each OpOverload object contains pointer to a specific operator overload, a pointer to the parent `OpOverloadPacket` object. +# You can obtain an OpOverload object through attribute query on OpOverloadPacket. +class OpOverload(OperatorBase, Generic[_P, _T]): + def __init__( + self, + overloadpacket: "OpOverloadPacket", + op: Callable[_P, _T], + op_dk: Callable[Concatenate[DispatchKey, _P], _T], + schema: torch._C.FunctionSchema, + tags: list[Any], + ) -> None: + super().__init__() + self._op = op + # _op may be swapped to the PyObject dispatch callable. Keep the C++ + # dispatcher handle separately for code that must bypass that fast path. + self._cpp_dispatch_handle = op + self._op_dk = op_dk + self._schema = schema + self._pyobj_dispatcher: _PyObjectDispatcher[_P, _T] | None = None + self._overloadpacket = overloadpacket + self._tags = tags + self._overloadname = ( + "default" if schema.overload_name == "" else schema.overload_name + ) + if tags: + self._nondeterministic_seeded = torch.Tag.nondeterministic_seeded in tags + self._name = self._schema.name + if schema.overload_name: + self._name += "." + schema.overload_name + self.__name__ = f"{self._schema.name.split('::')[1]}.{self._overloadname}" + self.__module__ = overloadpacket.__module__ + op.__module__ = overloadpacket.__module__ + self.__qualname__ = self._name + self.__annotations__ = {} + + # If the OpOverload was constructed from a Library.def in Python. + self._defined_in_python = self.__qualname__ in torch.library._defs + + # Logic replicated from aten/src/ATen/native/MathBitsFallback.h + is_write = None + for a in self._schema.arguments: # pyrefly: ignore # bad-assignment + if a.alias_info is None: + continue + if is_write is None: + is_write = a.alias_info.is_write + else: + # We will conservatively call mixed mutable/non-mutable + # aliased inputs as NOT a view + is_write = a.alias_info.is_write or is_write + self.is_view = is_write is not None and not is_write + + @cached_property + def _namespace(self) -> str: + return self._schema.name.split("::", maxsplit=1)[0] + + @cached_property + def _opname(self) -> str: + return self._schema.name.split("::", maxsplit=1)[1] + + @cached_property + def _handle(self) -> torch._C._DispatchOperatorHandle: + # Handle to the C++ dispatcher operator entry, used for boxed dispatch. + return torch._C._dispatch_find_schema_or_throw( + self._schema.name, self._schema.overload_name + ) + + # it's a no-op since OpOverload object is immutable and must be unique for a given op overload. + def __deepcopy__(self, memo=None): + return self + + def __repr__(self): + return f"" + + # Use positional-only argument to avoid naming collision with aten ops arguments + # that are named "self". This way, all the aten ops can be called by kwargs. + def __call__(self, /, *args: _P.args, **kwargs: _P.kwargs) -> _T: + if ( + self._pyobj_dispatcher is not None + and torch._C._peek_should_skip_torch_function() + ): + return self._cpp_dispatch_handle(*args, **kwargs) + return self._op(*args, **kwargs) + + # Use positional-only argument to avoid naming collision with aten ops arguments + # that are named "self". This way, all the aten ops can be called by kwargs. + def redispatch( + self, /, keyset: torch._C.DispatchKeySet, *args: _P.args, **kwargs: _P.kwargs + ) -> _T: + pyobj_dispatcher = self._pyobj_dispatcher + if pyobj_dispatcher is not None: + return pyobj_dispatcher.redispatch(keyset, *args, **kwargs) + return self._handle.redispatch_boxed(keyset, *args, **kwargs) # type: ignore[return-value] + + def __hash__(self): + return hash(self._cpp_dispatch_handle) + + # `my_namespace.my_op_name.overload_name` + def __str__(self): + return "{}.{}.{}".format(*self._schema.name.split("::"), self._overloadname) + + def has_kernel_for_dispatch_key(self, k: DispatchKey) -> bool: + return super().has_kernel_for_dispatch_key( + k + ) or torch._C._dispatch_has_kernel_for_dispatch_key(self.name(), k) + + def has_kernel_for_any_dispatch_key(self, ks: torch._C.DispatchKeySet) -> bool: + return torch._C._dispatch_has_kernel_for_any_dispatch_key( + self.name(), ks + ) or super().has_kernel_for_any_dispatch_key(ks) + + @property + def namespace(self) -> str: + return self._namespace + + def _can_decompose(self) -> bool: + dk = DispatchKey.CompositeImplicitAutograd + return dk in self.py_kernels or torch._C._dispatch_has_kernel_for_dispatch_key( + self.name(), dk + ) + + def decompose(self, *args: _P.args, **kwargs: _P.kwargs) -> _T: + dk = DispatchKey.CompositeImplicitAutograd + if dk in self.py_kernels: + # NB: This branch is not too necessary anymore, because we can + # apply Python CompositeImplicitAutograd *before* tracing + # using Python dispatcher (also taking advantage of the autograd + # formula). But it's included for completeness + return self.py_kernels[dk](*args, **kwargs) + elif torch._C._dispatch_has_kernel_for_dispatch_key(self.name(), dk): + return self._op_dk(dk, *args, **kwargs) + else: + return NotImplemented # pyrefly: ignore [bad-return] + + # Remove a dispatch key from the dispatch cache. This will force it to get + # recomputed the next time. Does nothing + # WARNING: if you register a dispatch key to py_kernels of an OpOverload, + # calling _del_dispatch on that key is NOT sufficient to apply your change, + # because a single registration may affect MULTIPLE dispatch keys (e.g., + # registering Autograd affects AutogradCPU). del_dispatch is to be used + # only if you are specifically modifying how get_dispatch handles a + # particular input 'key'. + def _uncache_dispatch(self, key: DispatchKey) -> None: + self._dispatch_cache.pop(key, None) + + def _is_pyobj_dispatcher_enabled(self) -> bool: + return self._pyobj_dispatcher is not None + + def _can_enable_pyobj_dispatch(self) -> bool: + # TODO(#187974): Support non-Tensor returns by normalizing Python kernel + # returns against the operator schema in the PyObject fast path. + return all( + isinstance(ret.type, torch.TensorType) for ret in self._schema.returns + ) + + def _enable_pyobj_dispatch(self, enabled: bool = True) -> None: + if self._is_pyobj_dispatcher_enabled() == enabled: + return + if not enabled: + self._pyobj_dispatcher = None + self._op = self._cpp_dispatch_handle + return + if not self._can_enable_pyobj_dispatch(): + return + dispatch, redispatch = torch._C._dispatch_make_pyobj_dispatch_fns( + self._handle, + self._cpp_dispatch_handle, + self._handle.redispatch_boxed, + ) + self._pyobj_dispatcher = _PyObjectDispatcher(dispatch, redispatch) + self._op = dispatch + + # This implements the pre-computation logic for the Python dispatcher. + def _get_dispatch(self, key: DispatchKey) -> DispatchKey | Callable[_P, _T]: + # This is only called upon a cache miss + if key in self._dispatch_cache: + raise AssertionError(f"{self} {key} already in dispatch cache") + + if key == DispatchKey.Python: + if not isinstance(self, TorchBindOpOverload) and not self.python_key_table: + self._dispatch_cache[key] = key + add_cached_op(self) + return key + + def handler(*args: _P.args, **kwargs: _P.kwargs) -> _T: + from torch.utils._python_dispatch import _get_current_dispatch_mode + + # TODO: We also need to handle tensor subclasses here + # TODO(voz): We should walk all the nodes here / turn it into a list, topmode is ok for now. + curr_mode = type(_get_current_dispatch_mode()) + if curr_mode is None: + raise AssertionError( + "Illegal invocation of dispatch on DispatchKey.Python without a mode." + ) + + if curr_mode not in self.python_key_table: + if isinstance(self, TorchBindOpOverload): + with ( + torch.utils._python_dispatch._pop_mode_temporarily() as mode + ): + return torch._library.utils.handle_dispatch_mode( + mode, self, *args, **kwargs + ) + else: + return self._op_dk(key, *args, **kwargs) + + with torch.utils._python_dispatch._pop_mode_temporarily() as mode: + return self.python_key_table[curr_mode](mode, *args, **kwargs) # type: ignore[index] + + self._dispatch_cache[key] = handler + add_cached_op(self) + return handler + + functionality_key = torch._C._to_functionality_key(key) # type: ignore[attr-defined] + if functionality_key == DispatchKey.PreDispatch: + curr_stack_len = _len_torch_dispatch_stack_pre_dispatch() + # The check for Python in the exclude set is so we properly respect `with no_dispatch()` + # calls inside of a mode. + if ( + curr_stack_len > 0 + and not torch._C._dispatch_tls_is_dispatch_key_excluded( + DispatchKey.Python + ) + ): + + def handler(*args: _P.args, **kwargs: _P.kwargs) -> _T: + @contextlib.contextmanager + def _temporarily_pop_modes_from_pre_dispatch(): + top_mode = _pop_mode_from_pre_dispatch() + try: + yield top_mode + finally: + _set_mode_pre_dispatch(top_mode) + + with _temporarily_pop_modes_from_pre_dispatch() as curr_mode: + return torch._library.utils.handle_dispatch_mode( + curr_mode, self, *args, **kwargs + ) + + # Note [Not Caching Per-Dispatch-Key Mode Handlers] + # Note that we're not caching this handler. There isn't really a point, since the slow bit + # is the handler itself (in python). + # Also, not caching means that we don't have to reset the cache when any existing + # modes go out of scope (which in of itself takes time to loop through all operators). + return handler + + final_key = resolve_key(self, key) + + # See Note [Not Caching Per-Dispatch-Key Mode Handlers] + cache_result = key != DispatchKey.PreDispatch + + # TODO: We could potentially have lots of debugging wrappers against + # dispatch keys; design some general registration mechanism instead of + # having if statement for each of them + if key == DispatchKey.Functionalize: + import torch._dispatch.python as pydispatch + + if pydispatch.CROSSREF_FUNCTIONALIZE: + handler = pydispatch.make_crossref_functionalize(self, final_key) # type: ignore[assignment] + if cache_result: + self._dispatch_cache[key] = handler + add_cached_op(self) + return handler + + r = self.py_kernels.get(final_key, final_key) + if cache_result: + self._dispatch_cache[key] = r + add_cached_op(self) + return r + + def name(self): + return self._name + + @property + def overloadpacket(self): + return self._overloadpacket + + @property + def op(self): + return self._op + + @property + def tags(self): + return self._tags + + # TODO: add more methods to expose information about input and output arguments + + +# TorchBindOpOverload are those custom ops which have at least one overload's +# schema consists of torch.ScriptObject (i.e. custom class) input. +# TorchBindOpOverload will skip C++ dispatcher and purely dispatched in python +# when its inputs contain FakeScriptObject in a similar way as higher order ops. +class TorchBindOpOverload(OpOverload[_P, _T]): + def _fallthrough_keys(self) -> list[DispatchKey]: + # TODO: we should be calling the fallback for these, but a fallthrough is almost close + # enough to the fallback in most cases that we care about. + _DEFAULT_FALLTHROUGH_KEYS = [ + DispatchKey.Autograd, + DispatchKey.AutogradCPU, + DispatchKey.AutogradCUDA, + DispatchKey.ADInplaceOrView, + DispatchKey.BackendSelect, + DispatchKey.PythonTLSSnapshot, + DispatchKey.PythonDispatcher, + DispatchKey.Functionalize, + ] + + def _may_use_fallthrough_instead_of_fallback(key: DispatchKey): + if torch._C._dispatch_has_kernel_for_dispatch_key(self.name(), key): + return torch._C._dispatch_kernel_for_dispatch_key_is_fallthrough( + self.name(), key + ) + + return ( + key not in self.py_kernels + or self.py_kernels[key] is torch.library.fallthrough_kernel + ) + + return [ + key + for key in _DEFAULT_FALLTHROUGH_KEYS + if _may_use_fallthrough_instead_of_fallback(key) + ] + + # Use positional-only argument to avoid naming collision with aten ops arguments + # that are named "self". This way, all the aten ops can be called by kwargs. + def __call__(self, /, *args: _P.args, **kwargs: _P.kwargs) -> _T: + if _must_dispatch_in_python(args, kwargs): + # When any inputs are FakeScriptObject, we need to + # skip c++ dispatcher and dispatch in python through _get_dispatch of python_dispatcher + # because C++ dispatcher will check the schema and cannot recognize FakeScriptObject. + return self._dispatch_in_python(self._fallthrough_keys(), *args, **kwargs) + return self._op(*args, **kwargs) + + def _dispatch_in_python( + self, fallthrough_keys: list[DispatchKey], *args: _P.args, **kwargs: _P.kwargs + ) -> _T: + non_fallthrough_keys = torch._C._dispatch_keyset_full() + for key in fallthrough_keys: + non_fallthrough_keys = non_fallthrough_keys.remove(key) + + dispatch_key_set = _compute_keyset(args, kwargs, non_fallthrough_keys) + dispatch_key = dispatch_key_set.highestPriorityTypeId() + + handler = ( + self._get_dispatch(dispatch_key) + if dispatch_key not in self._dispatch_cache + else self._dispatch_cache[dispatch_key] + ) + + if isinstance(handler, DispatchKey): + # fallthrough keys can be registered at runtime via torch.library.impl + # so need to add it to fallthrough_keys and re-dispatch. + if torch._C._dispatch_kernel_for_dispatch_key_is_fallthrough( + self.name(), dispatch_key + ): + return self._dispatch_in_python( + fallthrough_keys + [dispatch_key], + *args, + **kwargs, + ) + + raise RuntimeError( + f"Torchbind op {self} received a FakeScriptObject input when dispatching {handler}." + f" but no python implementation is found." + f" Please file an issue on this when you encounter this error." + f" This error can happen when you export or compile the model." + f" It can still happen even if a C++ implementation for {dispatch_key}. " + f" has been registered. That's because FakeScriptObject purely lives in python and cannot work " + f" with a C++ implementation." + ) + + if not isinstance(handler, Callable): # type: ignore[arg-type] + raise AssertionError(f"handler must be callable, got {type(handler)}") + return handler(*args, **kwargs) + + +def _contains_fake_script_object(obj) -> bool: + """Check if obj is or contains a FakeScriptObject. + This is load-bearing for TorchBindOpOverloads so we avoid pytree + since it's much slower. + """ + if isinstance(obj, torch._library.fake_class_registry.FakeScriptObject): + return True + elif isinstance(obj, (list, tuple)): + return any(_contains_fake_script_object(item) for item in obj) + elif isinstance(obj, dict): + return any(_contains_fake_script_object(v) for v in obj.values()) + return False + + +def _must_dispatch_in_python(args, kwargs) -> bool: + return any(_contains_fake_script_object(arg) for arg in args) or ( + bool(kwargs) and any(_contains_fake_script_object(v) for v in kwargs.values()) + ) + + +def _has_script_object_arg(schema: torch.FunctionSchema) -> bool: + return any(isinstance(arg.type, torch.ClassType) for arg in schema.arguments) + + +# OpOverloadPacket class contains pointer to a base unresolved operator that doesn't correspond to a specific operator +# You can obtain an OpOverload object through attribute query. +class OpOverloadPacket(Generic[_P, _T]): + __file__: ClassVar[str] = "torch.ops" + + def __init__( + self, + qualified_op_name: str, + op_name: str, + op: Callable[_P, _T], + overload_names: list[str], + ) -> None: + # These attributes are accessible on the object through the properties + # defined below but are immutable + self._qualified_op_name = qualified_op_name + self.__name__ = op_name + self._op = op + self._overload_names = overload_names + self._dir: list[str] = [] + self._has_torchbind_op_overload = any( + _has_script_object_arg(schema) for schema in self._schemas.values() + ) + + # it's a no-op since OpOverloadPacket object is immutable and must be unique for a given op. + def __deepcopy__(self, memo=None): + return self + + def __repr__(self): + return "".format( + *self._qualified_op_name.split("::") + ) + + def __hash__(self): + return hash(self._op) + + def __str__(self): + return "{}.{}".format(*self._qualified_op_name.split("::")) + + @property + def op(self): + return self._op + + @property + def _schemas(self): + return { + overload_name: torch._C._get_schema(self._qualified_op_name, overload_name) + for overload_name in self._overload_names + } + + def __getattr__(self, key: str) -> OpOverload[_P, _T]: + # ensure that query for dunder attributes that does not exist on + # opoverloadpacket but instead exists on the self._op object does not unnecessarily call + # `_get_operation_overload` (which is an expensive operation). + # This is done to prevent any potential slowdown. This list can be extended + # if there exists other attributes like `__name__` that only exist on self._op and not on the + # opoverloadpacket. + # This is ok since we are guaranteed that an overload name for an aten op can't start with '__' + try: + if key.startswith("__"): + return getattr(self._op, key) + except AttributeError: + # for consistency because it seems weird to + # throw an attribute error with a message containing + # an object name different from the one the attribute + # query was performed on. + raise AttributeError( + f"'{str(self)}' can't have an overload name beginning with '__' and the " + f"underlying op {str(self._op)} has no attribute {key} either." + ) from None + + try: + # This is ok since we are guaranteed that an overload name for an aten op can't be 'default' + use_key = "" if key == "default" else key + # TODO: disallow access to overloads registered by JIT + op_dk_tags = torch._C._get_operation_overload( + self._qualified_op_name, use_key + ) + if op_dk_tags is None: + raise AttributeError( + f"The underlying op of '{str(self)}' has no overload name '{key}'" + ) + + op_, op_dk_, tags = op_dk_tags + schema = torch._C._get_schema(self._qualified_op_name, use_key) + overload: OpOverload[_P, _T] = ( + OpOverload(self, op_, op_dk_, schema, tags) + if not _has_script_object_arg(schema) + else TorchBindOpOverload(self, op_, op_dk_, schema, tags) + ) + # cache the overload object + setattr(self, key, overload) + self._dir.append(key) + return overload + except RuntimeError: + raise AttributeError( + f"The underlying op of '{str(self)}' has no overload name '{key}'" + ) from None + + def __iter__(self) -> Iterator[str]: + return iter(self._dir) + + # Use positional-only argument to avoid naming collision with aten ops arguments + # that are named "self". This way, all the aten ops can be called by kwargs. + def __call__(self, /, *args: _P.args, **kwargs: _P.kwargs) -> _T: + # overloading __call__ to ensure torch.ops.foo.bar() + # is still callable from JIT + # We save the function ptr as the `op` attribute on + # OpOverloadPacket to access it here. + + # Directly calling OverloadPacket goes into C++, which will check + # the schema and cause an error for torchbind op when inputs consist of FakeScriptObject so we + # intercept it here and call TorchBindOpverload instead. + if self._has_torchbind_op_overload and _must_dispatch_in_python(args, kwargs): + # pyrefly: ignore [bad-argument-type] + return _call_overload_packet_from_python(self, *args, **kwargs) + return self._op(*args, **kwargs) + + # TODO: use this to make a __dir__ + def overloads(self): + return [n if n else "default" for n in self._overload_names] + + def op_overloads(self): + return [getattr(self, n) for n in self.overloads()] + + +# Note - this mirrors the logic of the cpp_function defined in jit/python/init.cpp +# _jit_get_operations, which calls _get_operation_for_overload_or_packet. +def _call_overload_packet_from_python( + op: OpOverloadPacket[_P, _T], *args: _P.args, **kwargs: _P.kwargs +) -> _T: + # Reuse the torch function handling logic in cpp + torch_function_called, ret = torch._C._maybe_call_torch_function_for_op_packet( + op, *args, **kwargs + ) + + if torch_function_called: + return ret + + # The following mirrors getOpWithStack. + # In cpp, we do a schema matching for the arguments, and call ToIValue + # to check whether the arguments are valid. But need to do similar things here + # and check the schema whether the FakeScriptObject is the corresponding fake class + # of the actual class used in schema. + exceptions = {} + found_op = None + for overload_name in op.overloads(): + op_overload = getattr(op, overload_name) + try: + _ = torch._C._check_schema_allow_fake_script_object( + op_overload._schema, *args, **kwargs + ) + found_op = op_overload + break + except RuntimeError as e: + exceptions[overload_name] = e + + if found_op: + return found_op(*args, **kwargs) + + err_msg = ( + f"Fail to match any TorchBindOverload of {op} with following exceptions:\n" + ) + for key, msg in exceptions.items(): + err_msg += f"Overload name {key}:\n {msg}\n" + raise RuntimeError(err_msg) + + +# Resolution of torch.fn is different from torch.ops.aten.fn +# torch.fn uses the Python argparser, matches with the +# appropriate schema, and calls into the unboxed version of the method +# torch.ops.aten.fn resolution is done via the mechanism defined in JIT. +# JIT creates a stack of all the overloads and then tries to match the +# correct one at runtime and always calls into the boxed version of the method +# Autograd codegen creates VariableType, TracerType, +# inplace or view type and python bindings. +# Aten codegen generates tensor methods for the tensor class. + +# _OpNamespace is a subclass of ModuleType because the torch script +# allows attribute lookups on modules only. Since we want torch.ops.foo.bar() +# to work from script, we need to ensure ops and foo are modules + + +class _OpNamespace(types.ModuleType): + """ + An op namespace to dynamically bind Operators into Python. + + Say a user has created a custom Operator called "my_namespace::my_op". To + call this op, the user will write torch.ops.my_namespace.my_op(...). + At startup, this operation will not yet be bound into Python. Instead, the + following sequence of magic tricks will occur: + 1. `torch.ops.my_namespace` will invoke the `__getattr__` magic method + on the `torch.ops` object, which will create a new `_OpNamespace` + object called `my_namespace` and set it as an attribute on the `ops` + object. + 2. `torch.ops.my_namespace.my_op` will then invoke `__getattr__` on + the `my_namespace` object, which will retrieve the operation via + `torch.get_operation`, a function bound from C++, and then in a similar + fashion bind this new object onto the `my_namespace` object. + 3. `torch.ops.my_namespace.my_op(...)` then calls this new operation + and subsequent accesses will incur no further lookup (the namespace and + operation will already exist). + """ + + __file__ = "torch.ops" + + def __init__(self, name: str) -> None: + super().__init__("torch.ops." + name) + self.name = name + self._dir: list[str] = [] + + def __iter__(self) -> Iterator[str]: + return iter(self._dir) + + def __getattr__(self, op_name: str) -> OpOverloadPacket: + if op_name in ("__origin__", "__self__"): + raise AttributeError( + f"Invalid attribute '{op_name}' for '_OpNamespace' '{self.name}'" + ) + + # Get the op `my_namespace::my_op` if available. This will also check + # for overloads and raise an exception if there are more than one. + namespace_name = self.name + qualified_op_name = f"{namespace_name}::{op_name}" + module_name = self.__module__ + "." + namespace_name + + try: + op, overload_names = _get_packet(qualified_op_name, module_name) + if op is None: + raise AttributeError( + f"'_OpNamespace' '{self.name}' object has no attribute '{op_name}'" + ) + except RuntimeError as e: + # Turn this into AttributeError so getattr(obj, key, default) + # works (this is called by TorchScript with __origin__) + raise AttributeError( + f"'_OpNamespace' '{self.name}' object has no attribute '{op_name}'" + ) from e + + op.__module__ = module_name + opoverloadpacket = OpOverloadPacket( + qualified_op_name, op_name, op, overload_names + ) + opoverloadpacket.__module__ = self.__module__ + "." + namespace_name + # cache the opoverloadpacket to ensure that each op corresponds to + # a unique OpOverloadPacket object + setattr(self, op_name, opoverloadpacket) + self._dir.append(op_name) + return opoverloadpacket + + +def _get_packet(qualname, op_module): + op, overload_names = torch._C._jit_get_operation(qualname) + if op is not None: + # let the script frontend know that op is identical to the builtin op + # with qualified_op_name + torch.jit._builtins._register_builtin(op, qualname) + op.__module__ = op_module + return op, overload_names + + +def _refresh_packet(packet): + op, overload_names = _get_packet(packet._qualified_op_name, packet._op.__module__) + if op is None: + raise AssertionError(f"failed to get packet for {packet._qualified_op_name}") + packet._op = op + packet._overload_names = overload_names + + +class _HigherOrderNamespace(types.ModuleType): + __file__ = "torch.ops" + + def __init__(self) -> None: + super().__init__("torch.ops.higher_order") + self._dir: list[str] = [] + + def __iter__(self) -> Iterator[str]: + return iter(self._dir) + + def __getattr__(self, name: str) -> HigherOrderOperator: + # Following _OpNamespace.__getattr__, we cache the op on this object. + op = _higher_order_ops.get(name) + if op is None: + raise AttributeError( + f"'_HigherOrderNamespace' 'torch.ops.higher_order' object has no attribute '{name}'" + ) + setattr(self, name, op) + self._dir.append(name) + return op + + +class _Ops(types.ModuleType): + __file__ = "_ops.py" + + def __init__(self): + super().__init__("torch.ops") + self.loaded_libraries = set() + self.higher_order = _HigherOrderNamespace() + self._dir = [] + + def __getattr__(self, name: str) -> _OpNamespace: + # Here we are creating `torch.ops.my_namespace` + namespace = _OpNamespace(name) + setattr(self, name, namespace) + self._dir.append(name) + return namespace + + def __iter__(self) -> Iterator[str]: + return iter(self._dir) + + def import_module(self, module): + """ + Imports a Python module that has torch.library registrations. + + Generally, to extend PyTorch with custom operators, a user will + create a Python module whose import triggers registration of + the custom operators via a torch.ops.load_library call or a call + to one or more torch.library.* APIs. + + It is unexpected for Python modules to have side effects, so some + linters and formatters will complain. Use this API to import Python + modules that contain these torch.library side effects. + + Args: + module (str): The name of the Python module to import + + """ + importlib.import_module(module) + + def load_library(self, path): + """ + Loads a shared library from the given path into the current process. + + The library being loaded may run global initialization code to register + custom operators with the PyTorch JIT runtime. This allows dynamically + loading custom operators. For this, you should compile your operator + and the static registration code into a shared library object, and then + call ``torch.ops.load_library('path/to/libcustom.so')`` to load the + shared object. + + After the library is loaded, it is added to the + ``torch.ops.loaded_libraries`` attribute, a set that may be inspected + for the paths of all libraries loaded using this function. + + Args: + path (str): A path to a shared library to load. + """ + path = _utils_internal.resolve_library_path(path) + with dl_open_guard(): + # Import the shared library into the process, thus running its + # static (global) initialization code in order to register custom + # operators with the JIT. + try: + ctypes.CDLL(path) + except Exception as e: + raise OSError(f"Could not load this library: {path}") from e + self.loaded_libraries.add(path) + + +# The ops "namespace" +ops: _Ops = _Ops() diff --git a/.venv/lib/python3.12/site-packages/torch/_precompile.py b/.venv/lib/python3.12/site-packages/torch/_precompile.py new file mode 100644 index 0000000000000000000000000000000000000000..6b10cbaddac42e4840d8b1396269e7447d75482c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_precompile.py @@ -0,0 +1,1874 @@ +"""Ahead-of-time precompilation (``make_fx`` tracer by default; Dynamo planned). + + python_code, cache = torch.compiler.precompile(fn, model, *example_inputs) + f_c = torch.compiler.precompile.load(python_code, cache) + out = f_c(model, *example_inputs) # pass the model again at runtime + +precompile captures your computation with ``make_fx`` -- a NON-STRICT trace of the ATen +ops that run when ``fn`` executes once on the example inputs. It does not analyze your +Python, so it comes with an explicit contract (the programming model): stay inside it +and the artifact faithfully reproduces ``fn``; step outside it and you get an artifact +that computes the wrong thing. + +``precompile`` returns a self-contained, executable ``python_code`` string plus a +companion integrity-tagged ``cache``. With ``backend="inductor"`` (the default) the +captured graph is lowered through the AOT backend contract +(``torch._functorch.aot_autograd.compile_to_python``, AOTAutograd + Inductor); +``python_code`` JIT-compiles kernels on first call and the cache primes them so a warm +reload skips JIT. With ``backend="eager"`` ``python_code`` inlines the captured graph and +runs on its own. Reload with ``torch.compiler.precompile.load(python_code, cache)``. + +The full contract, the calling convention, and the cache / code_hash design all live in +Note [precompile programming model] below; every public entry point and guard references +it. +""" + +# Note [precompile programming model] +# +# ``fn`` is the WHOLE computation, e.g. ``lambda model, x: model(x)`` for inference +# or ``lambda model, x, t: loss_fn(model(x), t).backward()`` for a training step. +# Among the positional args, the nn.Module arguments have their parameters and +# buffers lifted to explicit graph inputs (via functional reparametrization), so +# nothing live is baked in; the remaining args are the runtime inputs. The artifact +# embeds NO weights -- you pass the model again at runtime. +# +# Because make_fx is a non-strict trace, precompile offers a contract, not a +# guarantee against misuse. The caller MUST uphold the invariants below. The ones +# that are cheaply knowable from the captured graph are ENFORCED (a violation +# raises PrecompileError); the rest are the caller's responsibility and, if broken, +# produce a SILENTLY INCORRECT artifact -- the ordinary consequence of tracing. +# +# 1. Everything live is an input. Every tensor the computation reads must be passed to +# fn as an explicit tensor argument -- EXCEPT tensors held inside an nn.Module +# argument, which precompile handles for you. For an nn.Module argument you do NOT +# enumerate its tensors yourself: precompile lifts every registered parameter and +# buffer (recursively, including submodules, tied weights collapsed by identity) to +# explicit graph inputs for you via functional reparametrization, and re-derives the +# same list from the runtime model you pass to load(). Passing the module is enough -- +# that is the whole point of accepting modules as arguments. What is NOT lifted is +# anything not reachable +# through that protocol: tensors closed over by ``fn`` (globals, captured locals) +# and plain (non-registered) module attributes -- a bare ``self.weight = t`` rather +# than a registered parameter/buffer. Those are not inputs; a vanilla make_fx trace +# would bake them in as get_attr constants. Fix by registering them on the module +# (register_parameter / register_buffer) or passing them as explicit tensor args. +# ENFORCED: _check_no_constant_tensors rejects any baked tensor constant. +# +# 2. The runtime model must match the traced model structurally. At load time you +# pass the model again; precompile re-derives the parameter/buffer list from the +# runtime model in the SAME order (parameters then buffers, interned by tensor +# identity so tied weights collapse to a single input). The runtime model must +# have the same named_parameters()/named_buffers() ordering and count and the +# same weight tying as the example model. Same architecture with different +# weights is the intended use (swap in a checkpoint); a structurally different +# model is undefined. requires_grad is ALSO part of the structural contract: which +# params get a scattered grad is fixed at capture time from the example model's +# requires_grad (invariant 5), so flipping a param's requires_grad at runtime does +# not change what the artifact computes. ENFORCED: the driver compares the runtime +# model's full param/buffer NAME list (order and identity, tied weights collapsed) +# against the traced list, AND each runtime param/buffer's SHAPE, DTYPE, AND DEVICE +# against the baked example values, so a reordered or otherwise structurally-different +# model -- even one with the same count and names but a differently shaped, typed, or +# placed weight (e.g. a Linear(4,4) swapped for a Linear(4,8), or a CPU weight where a +# CUDA one was traced) -- is rejected (it cannot silently scatter grads onto the wrong +# slot, fail deep in a kernel, or compute the wrong thing). Different WEIGHT VALUES with +# the same shapes/dtypes/devices are the intended use -- WITH ONE INDUCTOR-BACKEND +# CAVEAT: the inductor backend ALSO specializes each param/buffer's LAYOUT (memory +# format), since it bakes assert_size_stride on every weight the graph reads. So a +# same-shape/same-dtype checkpoint whose weight has a DIFFERENT layout (e.g. a +# non-contiguous view, or a channels_last weight where the example was contiguous) is +# REJECTED at runtime by the inductor backend (invariant 6). Match the example weight's +# layout (.contiguous() to match a contiguous example), or use backend='eager' for +# layout-flexible weights. +# +# 3. Control flow (and, by default, shapes) is specialized to the example. A non-strict +# trace follows the single path taken for the example inputs: Python ``if``/``for`` +# over tensor values, ``.item()``, and shape-dependent branching are resolved at +# trace time and baked. Shapes are static BY DEFAULT (capture uses make_fx in its +# "real" mode, so each size is baked as a constant). You can opt specific user-input +# dims into being dynamic by marking them with +# ``torch._dynamo.decorators.mark_unbacked`` before calling: those dims are +# captured as UNBACKED symints (symbolic capture), which CANNOT be guarded on -- so +# the artifact is valid for any runtime size of those dims, and a graph that needs to +# guard on / specialize a marked dim fails LOUDLY at capture (PrecompileError) instead +# of baking a silently-wrong result. +# +# 4. Boundary effects. Input mutation (including module buffers -- e.g. BatchNorm +# running stats in training mode), tensor-subclass wrap/unwrap (e.g. DTensor), +# outputs that alias inputs, and functionalized RNG are SUPPORTED: the inductor +# backend lowers through torch._functorch.aot_autograd.compile_to_python, which +# composes AOTAutograd's own codegen'd prelude/epilogue into the artifact (the +# effect is reflected onto the runtime model / inputs). Effectful ops are not +# supported yet and raise at capture time (_assert_supported) with a concrete +# reason; this is an implementation gap, not a fundamental limit. Every other +# runtime wrapper that can appear in a composable (cacheable) forward graph is +# codegen'd as source and composed in; the one non-codegen'd wrapper +# (FakifiedOutWrapper) only activates under fakify_first_call, which makes the graph +# non-cacheable, so such a graph is rejected before composition ever runs. +# Distributed capture: a ``compile_on_one_rank`` flag (trace on a single rank and +# broadcast the artifact to the rest, so every rank need not re-capture) is +# anticipated and scheduled for a follow-up later in this stack. +# +# 5. Backward is part of the computation. Yes: if you trace ``forward -> loss -> +# backward``, running the artifact re-runs that whole computation and puts the +# resulting parameter gradients onto the runtime model. Concretely: the parameter +# gradients are harvested inside the (functional) graph as extra outputs, and the +# driver scatters them back onto the runtime model's ``parameters()`` ``.grad`` +# fields -- ACCUMULATING (``p.grad += g``), not overwriting, exactly like eager +# ``.backward()``, so a ``zero_grad()`` / ``optimizer.step()`` loop works unchanged +# (skip the zero and grads pile up, by design). WHICH params get a grad is fixed at +# TRACE time, not runtime: only params that actually received a gradient during the +# traced backward are harvested (recorded by index in GRAD_PARAM_INDICES); a frozen +# (``requires_grad=False``) or non-contributing param keeps ``.grad = None``, exactly +# as eager leaves it -- precompile does NOT zero-fill such params, and flipping a +# param's requires_grad at runtime does not change what gets scattered (invariant 2). +# Buffers are never harvested (a requires_grad buffer that got a grad is rejected at +# capture). The artifact therefore returns ``fn``'s own result (``None`` for a bare +# ``.backward()`` step), not the grads. The grad scatter is the ONLY mutation +# precompile performs, and it happens in Python outside the graph, so the graph stays +# functional. precompile does not own optimizer state; bring your own optimizer and +# zero grads as usual. +# +# 6. Shapes are static by default (dynamic dims are opt-in via mark_unbacked, invariant +# 3), each input's dtype/device is baked, and the inductor backend also specializes +# on input layout. Each dense user-input leaf's dtype and device are recorded at +# capture and checked at runtime (both backends): a dtype- or device-mismatched input +# is rejected with a PrecompileError rather than crashing deep in a kernel or reading +# a wrong value. The graph is specialized to the example input shapes (invariant 3); +# tensor-subclass outputs in particular are rebuilt with constant outer sizes/strides, +# so a different runtime shape is undefined. The inductor backend ADDITIONALLY bakes +# each read input's stride / memory format (it emits assert_size_stride) -- and this +# applies to model PARAMETERS/BUFFERS too, not only user inputs, since they are graph +# inputs the kernels read. So a same-shape runtime input OR a same-shape/same-dtype +# checkpoint WEIGHT with a DIFFERENT layout (e.g. a contiguous tensor when the example +# was transposed or channels_last, or a non-contiguous view of a weight) is rejected +# with a clear PrecompileError; match the example layout or use backend='eager'. +# This guard is deliberately CONSERVATIVE: a layout-agnostic kernel (e.g. matmul) may +# well have computed the right answer on the new layout, but precompile cannot +# recompile to specialize it the way torch.compile does, so it rejects to stay safe +# rather than risk a silently-wrong result from a layout-sensitive kernel. Pass inputs +# in the example's layout (``.contiguous()`` to match a contiguous example), or use the +# layout-flexible eager backend. ENFORCED for read inputs (a layout mismatch raises +# rather than crashing in assert_size_stride or reading wrong strides). +# +# 7. Both python_code and the cache are trusted, EXECUTABLE input to load(). The cache +# outer envelope is a plain {"artifact": bytes, ...} dict (read with +# weights_only=True) carrying a format/version + backend tag AND a code_hash +# (sha256 of the python_code it accelerates) that load() verifies (raising +# PrecompileError on mismatch). load() feeds those bytes to +# torch.compiler.load_cache_artifacts to PRIME the inductor kernel caches, then always +# EXECs python_code -- with the caches primed the kernels load from the precompiled +# binaries instead of JIT-compiling. Both the cache priming (it unpickles) and the exec run +# code you supplied; treat both python_code and the cache like code you are about to +# run. The code_hash binds the cache to its python_code: +# load() rejects a (code, cache) pair from different precompile() calls (same +# backend) rather than silently running the cache's graph under foreign metadata. +# +# self-contained: ``python_code`` runs on its own -- it inlines the composed graph +# module (inductor: kernels JIT-compiled on first call, plus AOTAutograd's codegen'd +# prelude/epilogue) or the captured graph (eager), plus all calling-convention +# metadata. It NEVER reads the cache, and it is the SINGLE SOURCE OF TRUTH for the +# calling convention. The ``cache`` holds ONLY the compiled INDUCTOR artifact and is +# purely an ACCELERATION consumed only by load(): load AST-scrapes the module-level +# calling convention out of python_code, primes the inductor kernel caches from the bundle +# (torch.compiler.load_cache_artifacts), then execs python_code -- so its kernels load +# from the precompiled binaries instead of JIT. With the cache you skip JIT; with only +# python_code you JIT -- same results either way. The +# eager backend has no kernels to accelerate, so the eager cache carries no compiled +# artifact (artifact=None) but is still a full integrity-tagged envelope, and load() +# always runs the graph inlined in python_code. The metadata +# lives in one place (python_code); the envelope carries a code_hash (sha256 of +# python_code) alongside the format/version + backend tag, so load() rejects a +# (python_code, cache) pair that did not come from the same precompile() call. +# +# backend: "inductor" (default) lowers the captured graph through +# torch._functorch.aot_autograd.compile_to_python (AOTAutograd + Inductor, emitting a +# self-contained module). "eager" skips lowering and runs the captured +# ATen graph as-is (analogous to torch.compile(backend="eager")), for inspecting or +# debugging exactly what was traced. The contract above is identical for both +# backends with ONE exception (invariant 6): the inductor backend additionally +# specializes on each input's stride / memory format, while the eager backend is +# layout-flexible. Otherwise the same graph is captured; only its realization differs. +# Two mechanical consequences: the eager backend runs the graph directly on the +# (subclass-level) inputs, so it does not exercise the dense subclass +# flatten/unflatten path that the inductor backend's calling convention requires; +# and because there are no kernels, the eager cache carries no compiled artifact +# (artifact=None) but is still a full integrity-tagged envelope (python_code is the +# whole runnable artifact). +# +# tracer: the capture front-end, orthogonal to backend. "make_fx" (default) is a +# non-strict trace and is the only tracer implemented today -- everything above (the +# invariants, the contract) describes its behavior. "dynamo" is planned (a Dynamo-based +# front-end that analyzes Python rather than specializing to one traced path) and +# currently raises NotImplementedError. + +from __future__ import annotations + +import hashlib +import io +import logging +from types import MappingProxyType +from typing import Any, cast, NewType, TYPE_CHECKING + +import torch +import torch.utils._pytree as pytree +from torch import Tensor +from torch.fx.experimental.proxy_tensor import make_fx +from torch.nn.utils import stateless +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + +log = logging.getLogger(__name__) + + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping + + from torch._subclasses.fake_tensor import FakeTensorMode + + +# ``precompile`` and ``PrecompileError`` are exposed under the compiler namespace as +# ``torch.compiler.precompile`` / ``torch.compiler.precompile.PrecompileError`` +# (re-exported from torch/compiler/__init__.py and registered in +# ``torch.compiler.__all__``); they are deliberately kept out of this private module's +# ``__all__`` so test_public_bindings sees a consistent single public location. +__all__: list[str] = [] + + +# Integrity tag baked into the cache envelope and verified by load() (with the +# code_hash) to reject a foreign / mismatched cache; see Note [precompile programming +# model], invariant 7. +_CACHE_FORMAT = "torch.compiler.precompile" +_CACHE_VERSION = 1 + + +# Index into the caller's positional nn.Module arguments (0-based over the modules, +# not over all args), used to qualify tied-across-modules param/buffer names as m.. +_ModuleIndex = NewType("_ModuleIndex", int) + + +# Decoded mark_unbacked spec for one dim: (shape_id, min, max, hint_override). shape_id is +# an opaque hashable grouping label (dims sharing it collapse to one unbacked symbol); the +# other three are optional integer sizes and are None wherever the decorator left them unset. +_MarkSpec = tuple[object, int | None, int | None, int | None] +# Per-user-input-leaf runtime bounds harvested from the marks: {dim: (min, max)} (either +# may be None), or None when the leaf has no bounded marked dim. +_LeafBounds = dict[int, tuple[int | None, int | None]] | None + + +# Reused read-only empty mapping for the mark_unbacked getattr fallbacks (Note [precompile +# reads private dynamo mark attributes]), so the common unmarked leaf reads its (absent) +# _dynamo_* dicts without allocating a throwaway {} per call. +# The value type is Any because these back three DISTINCT private dynamo dicts (dim -> +# shape_id label / (min, max) tuple / hint int); one shared empty default cannot name all +# three, and the private _dynamo_* attrs are untyped (Note above), so Any is the isolated +# boundary here. +_NO_MARKS: Mapping[int, Any] = MappingProxyType({}) + + +class PrecompileError(RuntimeError): + """The error type raised by ``torch.compiler.precompile`` and its artifacts. + + Raised when capture, lowering, ``load``, or a runtime call violates the precompile + contract -- e.g. a tensor baked as a constant (invariant 1), an unsupported / + effectful op, a non-tensor output the inductor backend cannot lower, or a runtime + input whose shape or memory format differs from the example (invariants 3 and 6). + See Note [precompile programming model] in this module for the full contract. + """ + + +def _dense_shape(t: object) -> tuple[int, ...] | None: + """Return the shape of a plain dense tensor, else ``None`` (non-tensor / subclass). + + Tensor subclasses (e.g. DTensor) go through AOTAutograd's flatten path, so their + outer shape is not the dense shape the inductor artifact bakes; record ``None`` and + skip them in the shape check. + """ + if isinstance(t, torch.Tensor) and not is_traceable_wrapper_subclass(t): + return tuple(t.shape) + return None + + +def _dense_dtype(t: object) -> str | None: + """Return the dtype of a plain dense tensor as a string, else ``None``. + + Recorded as a string (e.g. ``"torch.float32"``) so it serializes into the artifact + metadata as a literal and compares cleanly against ``str(t.dtype)`` at runtime; + mirrors the _dense_shape convention (None for non-tensor / subclass leaves). The + graph is specialized to the example dtype (invariant 6). + """ + if isinstance(t, torch.Tensor) and not is_traceable_wrapper_subclass(t): + return str(t.dtype) + return None + + +def _dense_device(t: object) -> str | None: + """Return the device (as a string) of a plain dense tensor, else ``None``. + + Recorded as a string so it serializes into the artifact metadata as a literal and + compares cleanly at runtime; mirrors _dense_shape (None for non-tensor / subclass + leaves). The graph is specialized to the example device (invariant 6). + """ + if isinstance(t, torch.Tensor) and not is_traceable_wrapper_subclass(t): + return str(t.device) + return None + + +def _resolved_get_attrs( + gm: torch.fx.GraphModule, +) -> list[tuple[str, object]]: + """Return ``(target, attr)`` for every ``get_attr`` node, resolving dotted + qualnames the same way for both capture guards below (missing attr -> None).""" + resolved = [] + for node in gm.graph.find_nodes(op="get_attr"): + attr: object = gm + for part in node.target.split("."): + attr = getattr(attr, part, None) + resolved.append((node.target, attr)) + return resolved + + +# Note [precompile reads private dynamo mark attributes] +# +# The functions below read PRIVATE per-tensor attributes that +# torch._dynamo.decorators.mark_unbacked stamps onto a tensor: it consumes +# _dynamo_unbacked_indices / _dynamo_strict_unbacked_indices / _dynamo_shape_ids / +# _dynamo_unbacked_bounds / _dynamo_hint_overrides, and rejects _dynamo_dynamic_indices +# / _specialize_on (marks it cannot honor). This is a deliberate coupling to a private +# dynamo contract -- mark_unbacked is the documented entry point, and precompile reads +# what it leaves behind rather than exposing its own dynamic-shape kwarg. A stable +# dynamo-owned accessor is the eventual home; until then these names are load-bearing. +def _has_unbacked_marks(args: tuple[object, ...]) -> bool: + """True if any tensor reachable in ``args`` carries a mark_unbacked dim (backed or + strict).""" + return any( + isinstance(t, torch.Tensor) + and ( + getattr(t, "_dynamo_unbacked_indices", None) + or getattr(t, "_dynamo_strict_unbacked_indices", None) + ) + for t in pytree.tree_leaves(args) + ) + + +def _reject_unsupported_marks(user_flat: list[object]) -> None: + """Reject mark options precompile cannot honor, loudly (invariant 3). + + precompile only honors mark_unbacked (backed unbacked dims) and mark_unbacked's + strict variant. Backed dynamic marks (mark_dynamic -> _dynamo_dynamic_indices) and + per-dim specialization (_specialize_on) have no analogue in the static/unbacked + capture path -- silently dropping them would bake a wrong artifact, so reject rather + than ignore. (mark_unbacked's hint_override is NOT rejected: it is a perf-only + autotuning size hint, never a guard, so the single artifact is valid regardless; it + is threaded into the capture ShapeEnv in _fakeify_with_unbacked.) A mark_unbacked dim + on a tensor SUBCLASS (e.g. DTensor) is rejected: the dynamic capture cannot preserve + the subclass through the refake, so it too would bake a wrong artifact. + """ + for t in user_flat: + if not isinstance(t, torch.Tensor): + continue + # mark_unbacked on a tensor subclass (e.g. DTensor) stamps its marks on the OUTER + # subclass as well as the inner tensor, so precompile's dynamic path picks it up -- + # but _fakeify_with_unbacked refakes a marked leaf via torch.empty, which yields a + # plain dense tensor and DROPS the subclass, so the trace would run on the wrong + # type. Reject loudly here rather than silently capturing a subclass-stripped tensor + # (mirrors the decorator itself, which raises for every non-DTensor subclass). + if is_traceable_wrapper_subclass(t) and ( + getattr(t, "_dynamo_unbacked_indices", None) + or getattr(t, "_dynamo_strict_unbacked_indices", None) + ): + raise PrecompileError( + "precompile: an input is a tensor subclass (e.g. DTensor) with a " + "mark_unbacked dynamic dim, which precompile cannot honor: the dynamic " + "capture cannot preserve the subclass. Mark a dense input instead, or " + "capture that dim static (do not mark_unbacked it)." + ) + if getattr(t, "_dynamo_dynamic_indices", None): + raise PrecompileError( + "precompile: an input has a mark_dynamic (backed dynamic) dim, which " + "precompile cannot honor; it supports only mark_unbacked dynamic dims. " + "Use torch._dynamo.decorators.mark_unbacked, or leave the dim static." + ) + specialize_on = getattr(t, "_specialize_on", None) + if specialize_on and any(v for v in specialize_on.values()): + raise PrecompileError( + "precompile: an input has a mark_unbacked specialize_on list, which " + "precompile cannot honor (it produces a single artifact, not per-value " + "specializations). Remove specialize_on." + ) + + +def _read_unbacked_marks(user_flat: list[object]) -> list[dict[int, _MarkSpec]]: + """Read ``torch._dynamo.decorators.mark_unbacked`` marks off the user-input tensors. + + Dynamic shapes are opt-in via that decorator (the caller marks dims before calling + precompile), NOT via a precompile kwarg -- so the precompile signature stays simple. + Returns a per-leaf list aligned to ``user_flat``; each entry maps a marked dim to + ``(shape_id, min, max, hint_override)`` (None when unset), empty when the leaf has no + marks. Dims sharing a ``shape_id`` get the SAME unbacked symbol (so they are equal by + construction); ``min``/``max`` become runtime range asserts; ``hint_override`` is a + perf-only autotuning size hint applied to the symbol in _fakeify_with_unbacked. + """ + marks: list[dict[int, _MarkSpec]] = [] + for t in user_flat: + if not isinstance(t, torch.Tensor): + marks.append({}) + continue + # Union the non-strict and strict unbacked index sets. mark_unbacked(strict=True) + # records ONLY _dynamo_strict_unbacked_indices; precompile already enforces + # strict's error-on-specialize semantics via the GuardOnDataDependentSymNode -> + # PrecompileError path, so both are honored identically here. NOTE: the decorator's + # strict branch returns early, so a strict dim carries no shape_id/min/max/ + # hint_override (those are dropped at mark time) -- combine strict with shape_id/ + # min/max only if that limitation is acceptable; use non-strict to get them. + idx = set(getattr(t, "_dynamo_unbacked_indices", None) or ()) + idx |= set(getattr(t, "_dynamo_strict_unbacked_indices", None) or ()) + if not idx: + marks.append({}) + continue + shape_ids = getattr(t, "_dynamo_shape_ids", _NO_MARKS) or _NO_MARKS + bounds = getattr(t, "_dynamo_unbacked_bounds", _NO_MARKS) or _NO_MARKS + hints = getattr(t, "_dynamo_hint_overrides", _NO_MARKS) or _NO_MARKS + marks.append( + { + d: (shape_ids.get(d), *bounds.get(d, (None, None)), hints.get(d)) + for d in idx + } + ) + return marks + + +def _read_input_bounds(marks: list[dict[int, _MarkSpec]]) -> list[_LeafBounds]: + """Build the per-leaf runtime min/max bounds from the already-read mark_unbacked + marks, aligned to ``user_flat`` (so ``marks`` is the output of _read_unbacked_marks). + + mark_unbacked promises (in its own docstring) a runtime check that the dim is >= min + and <= max; those bounds are applied as capture-time torch._check constraints in + _fakeify_with_unbacked, but unbacked symints cannot be guarded on, so they never + become a runtime guard on their own. We record them here so the driver enforces them. + Each entry is None when the leaf has no bounded marked dim, else a dict mapping a + marked dim index to ``(lo, hi)`` (either may be None); mirrors USER_INPUT_DTYPES. + """ + bounds: list[_LeafBounds] = [] + for per in marks: + per_leaf: dict[int, tuple[int | None, int | None]] = {} + for d, (_shape_id, lo, hi, _hint) in per.items(): + if lo is not None or hi is not None: + per_leaf[d] = (lo, hi) + bounds.append(per_leaf or None) + return bounds + + +def _detect_memory_format(t: torch.Tensor) -> torch.memory_format: + """Return the example leaf's memory format so a refaked marked input preserves it. + + A mark_unbacked dim refakes the leaf via torch.empty; defaulting to contiguous would + bake a contiguous assert_size_stride and reject a channels_last / transposed input + even at its own layout. Probe the recognized formats and raise on an exotic / + ambiguous layout we cannot capture rather than silently forcing contiguous. + """ + if t.is_contiguous(memory_format=torch.contiguous_format): + return torch.contiguous_format + if t.is_contiguous(memory_format=torch.channels_last): + return torch.channels_last + if t.is_contiguous(memory_format=torch.channels_last_3d): + return torch.channels_last_3d + raise PrecompileError( + "precompile: a mark_unbacked input has a memory format that is neither " + "contiguous, channels_last, nor channels_last_3d (e.g. a transposed or " + "otherwise non-standard layout); the dynamic-shape capture cannot preserve it. " + "Pass the input in one of those layouts (.contiguous() to make it contiguous), " + "or capture the dim static (do not mark_unbacked it)." + ) + + +def _fakeify_with_unbacked( + pb_flat: list[Tensor], user_flat: list[object], marks: list[dict[int, _MarkSpec]] +) -> tuple[list[object], FakeTensorMode]: + """Fakeify the flat capture inputs for an unbacked dynamic-shape capture. + + Params/buffers and unmarked dims become static fakes; each mark_unbacked dim becomes + an UNBACKED SymInt (unguardable, so the artifact is valid for any runtime size and a + graph that needs to guard on it fails at capture). Dims sharing a ``shape_id`` reuse + one symbol; ``min``/``max`` add runtime asserts. Returns ``(flat_fake, fake_mode)``; + the fake_mode (ShapeEnv) is threaded to the lowering via from_tracing_context. + """ + from torch._subclasses.fake_tensor import FakeTensorMode + from torch.fx.experimental.symbolic_shapes import ShapeEnv + + shape_env = ShapeEnv() + fake_mode = FakeTensorMode(shape_env=shape_env, allow_non_fake_inputs=True) + # shape_id -> unbacked symint (a dynamic SymInt); untyped so grouped dims share one symbol. + shared: dict[object, Any] = {} + with fake_mode: + fake_pb = [fake_mode.from_tensor(t, static_shapes=True) for t in pb_flat] + fake_user: list[object] = [] + for leaf, per in zip(user_flat, marks): + if not isinstance(leaf, torch.Tensor): + fake_user.append(leaf) + elif not per: + fake_user.append(fake_mode.from_tensor(leaf, static_shapes=True)) + else: + sizes: list[Any] = [] # mix of static ints and unbacked SymInts + for i, s in enumerate(leaf.shape): + if i not in per: + sizes.append(int(s)) + continue + shape_id, lo, hi, hint = per[i] + if shape_id is not None and shape_id in shared: + u = shared[shape_id] + # Reusing the shared symbol still applies THIS occurrence's + # bounds: distinct dims grouped by shape_id may each carry their + # own (min, max), and dropping them would lose a runtime assert. + if lo is not None: + torch._check(u >= lo) + if hi is not None: + torch._check(u <= hi) + sizes.append(u) + continue + u = shape_env.create_unbacked_symint() + torch._check(u >= 0) + if lo is not None: + torch._check(u >= lo) + if hi is not None: + torch._check(u <= hi) + # hint_override is a perf-only autotuning size hint (not a guard): + # thread it onto the fresh symbol so inductor autotuning sees it. For a + # shared shape_id the group's one symbol keeps the first hint set here. + if hint is not None: + shape_env._set_unbacked_var_to_hint_override(u, hint) + if shape_id is not None: + shared[shape_id] = u + sizes.append(u) + memory_format = _detect_memory_format(leaf) + f = torch.empty( + sizes, + dtype=leaf.dtype, + device=leaf.device, + memory_format=memory_format, + ) + f.requires_grad_(leaf.requires_grad) + fake_user.append(f) + return [*fake_pb, *fake_user], fake_mode + + +def _check_no_constant_tensors(gm: torch.fx.GraphModule) -> None: + """Enforce invariant 1 of Note [precompile programming model]: everything live + is an input. + + Every legitimate tensor in a non-strict capture is a placeholder (a lifted + parameter/buffer or user input) or the result of a ``call_function`` node. + A ``get_attr`` pointing at a tensor therefore means some tensor was closed + over (a global, captured local, or non-registered module attribute) and would + be baked into the graph as a constant, which we forbid. + """ + offending = [ + (target, tuple(attr.shape), str(attr.dtype)) + for target, attr in _resolved_get_attrs(gm) + if isinstance(attr, torch.Tensor) + ] + if offending: + raise PrecompileError( + "precompile traced a tensor that is neither a graph input " + "(module parameter/buffer or user input) nor an intermediate. Such " + "tensors would be hard-coded into the graph. This fires for a tensor " + "closed over by fn (a global or captured local) or a plain " + "(non-registered) module attribute, and also for a tensor literal " + "constructed inside fn (e.g. torch.tensor([...])). Offending constants " + f"(target, shape, dtype): {offending}. Fix by passing the tensor as an " + "explicit argument; for module state register it as a parameter/buffer, " + "and for a literal hoist it out of fn and pass it as an argument." + ) + + +def _assert_no_control_flow_subgraphs(gm: torch.fx.GraphModule) -> None: + """Reject captured control-flow HOP subgraphs (e.g. from ``torch.cond``). + + They appear as ``get_attr`` nodes pointing at nested ``GraphModule`` submodules. + The eager backend inlines ``gm.code`` and cannot reach such submodules (they are + not on the standalone ``_GraphSelf`` holder), and the standalone composition does + not inline them either, so the artifact would crash at runtime. Fail at capture + with a concrete reason instead, like ``_assert_supported``. + """ + offending = [ + target + for target, attr in _resolved_get_attrs(gm) + if isinstance(attr, torch.fx.GraphModule) + ] + if offending: + raise PrecompileError( + "precompile cannot lower a captured control-flow subgraph (e.g. from " + f"torch.cond / torch.while_loop); not supported yet. Offending get_attr " + f"targets: {offending}." + ) + + +def _intern_param_buffers( + mods: list[torch.nn.Module], +) -> tuple[ + list[Tensor], list[str], list[str], list[tuple[_ModuleIndex, str, int]], int +]: + """Lift each module's parameters then buffers to a flat list, interning by + tensor identity so a tied weight becomes a single entry (one optimizer step, + accumulated gradient -- not one per name). + + Returns ``(pb_flat, param_names, buffer_names, alias_entries, num_params)``, + where ``alias_entries`` maps each ``(module_index, name)`` to its index in + ``pb_flat`` (used to reparametrize during capture). This same params-then- + buffers, intern-by-identity order is reproduced at runtime against the + user-supplied modules, so the dense list lines up with the compiled graph. + + INVARIANT: the all-modules' params then all-modules' buffers, dedup-by-id ordering + here is load-bearing and is reproduced VERBATIM by + ``torch._precompile_driver._extract_param_buffers`` (emitted into the inlined/eager + load paths). The cached load path uses this function directly, so both must stay + in sync; ``test_cached_and_inlined_paths_agree`` cross-checks them. + """ + if len(mods) > 1: + + def _name(mi: _ModuleIndex, n: str) -> str: + return f"m{mi}.{n}" + else: + + def _name(mi: _ModuleIndex, n: str) -> str: + return n + + unique: list[Tensor] = [] + id_to_uidx: dict[int, int] = {} + alias_entries: list[tuple[_ModuleIndex, str, int]] = [] + + def _intern(mi: _ModuleIndex, n: str, t: Tensor, names_out: list[str]) -> None: + uidx = id_to_uidx.get(id(t)) + if uidx is None: + uidx = len(unique) + id_to_uidx[id(t)] = uidx + unique.append(t) + names_out.append(_name(mi, n)) + alias_entries.append((mi, n, uidx)) + + param_names: list[str] = [] + for mi, m in enumerate(mods): + for n, p in m.named_parameters(remove_duplicate=False): + _intern(_ModuleIndex(mi), n, p, param_names) + num_params = len(unique) + buffer_names: list[str] = [] + for mi, m in enumerate(mods): + for n, b in m.named_buffers(remove_duplicate=False): + _intern(_ModuleIndex(mi), n, b, buffer_names) + return unique, param_names, buffer_names, alias_entries, num_params + + +def _capture( + fn: Callable[..., object], + args: tuple[object, ...], + decompositions: dict | None = None, +) -> _Capture: + """Trace the computation ``fn(*args)`` to an ATen graph. + + See Note [precompile programming model] for the contract. ``fn`` is the whole + computation, e.g. ``lambda model, x: model(x)`` or a training step + ``lambda model, x, t: loss_fn(model(x), t).backward()``. Among ``args``, the + ``nn.Module`` arguments have their parameters/buffers lifted to explicit graph + inputs (via reparametrization, so nothing is baked -- invariant 1); the + remaining arguments are the runtime inputs. Whatever ``fn`` returns becomes the + graph's result outputs, and if ``fn`` ran a backward, the resulting parameter + gradients (read off ``param.grad``) are harvested as additional, trailing graph + outputs. They are kept separate from the result so the driver can scatter them + onto the runtime model's ``.grad`` fields rather than return them (invariant 5). + + This is a NON-STRICT trace (invariant 3): make_fx records only the ATen ops + that run for THIS example. Python-level control flow over tensor values, data- + dependent branches, and shapes are specialized to ``args`` and baked. The + interning/order established here for params then buffers is the calling + convention the runtime model must reproduce (invariant 2). + """ + import contextlib + + args = tuple(args) + module_positions = [i for i, a in enumerate(args) if isinstance(a, torch.nn.Module)] + module_pos_set = set(module_positions) + mods = [a for a in args if isinstance(a, torch.nn.Module)] + user_inputs = tuple(a for i, a in enumerate(args) if i not in module_pos_set) + + # Lift the example modules' params/buffers for tracing only. Their VALUES are + # never stored in the cache -- the user passes the model(s) again at runtime + # (mirroring fn's signature), and the same interning is reproduced there. + pb_flat, param_names, buffer_names, alias_entries, num_params = ( + _intern_param_buffers(mods) + ) + num_pb = len(pb_flat) + # Record each interned param's / buffer's example SHAPE, DTYPE, and DEVICE (aligned to + # param_names / buffer_names) so the structural check (invariant 2) compares not just + # names but also each runtime tensor's shape, dtype, and device. The graph is specialized + # to the example param/buffer shapes (and can bake a device literal via a factory op), so + # a same-named runtime tensor with a different shape / dtype / device would otherwise + # silently compute the wrong thing (eager has no assert_size_stride backstop). + param_shapes = [tuple(t.shape) for t in pb_flat[:num_params]] + buffer_shapes = [tuple(t.shape) for t in pb_flat[num_params:]] + param_dtypes = [str(t.dtype) for t in pb_flat[:num_params]] + buffer_dtypes = [str(t.dtype) for t in pb_flat[num_params:]] + param_devices = [str(t.device) for t in pb_flat[:num_params]] + buffer_devices = [str(t.device) for t in pb_flat[num_params:]] + + user_flat, in_spec = pytree.tree_flatten(user_inputs) + # Reject mark options precompile cannot honor (mark_dynamic, specialize_on) loudly + # here, before tracing, rather than silently dropping them. (hint_override is honored, + # not rejected -- it is a perf-only autotuning hint threaded onto the capture symbol.) + _reject_unsupported_marks(user_flat) + flat_args = [*pb_flat, *user_flat] + # The REAL example tensors (params/buffers and user inputs). flat_args is reassigned + # to FAKE tensors in the unbacked path below, but the saved-grad snapshot/clear/restore + # block must protect the real example model's .grad fields (those are what the user + # owns and what a backward in fn populates), not the throwaway fakes. list() snapshots + # the real tensors here, so the later flat_args rebind does not affect real_flat. + real_flat = list(flat_args) + # Record the example user inputs' dense shapes/dtypes/devices so the drivers can + # reject a shape (invariant 3) or dtype/device (invariant 6) mismatch up front; see + # the inlined driver checks (torch._precompile_driver). Stride is NOT recorded -- + # memory-format mismatches are enforced by inductor's own (pinned-on) + # assert_size_stride. Subclasses -> None. + # Widened element type (a marked-dynamic dim becomes None within the tuple in the + # unbacked path below); _dense_shape's static tuples conform to it. + user_input_shapes: list[tuple[int | None, ...] | None] = [ + _dense_shape(t) for t in user_flat + ] + user_input_dtypes = [_dense_dtype(t) for t in user_flat] + user_input_devices = [_dense_device(t) for t in user_flat] + + # Dynamic shapes (opt-in, UNBACKED only): dims the caller tagged with + # torch._dynamo.decorators.mark_unbacked are refakeified as unbacked symints, then + # traced symbolically with the fake_mode's ShapeEnv threaded to the lowering. Unbacked + # dims cannot be guarded on, so the artifact is valid across runtime sizes; a graph + # that would need to guard on a marked dim fails loudly at capture + # (GuardOnDataDependentSymNode) rather than baking it. Reading the marks here (instead + # of a precompile kwarg) keeps the precompile signature simple. + marks = _read_unbacked_marks(user_flat) + # Record each marked dim's declared min/max so the driver enforces them at runtime; + # the capture-time torch._check on an unbacked symint never becomes a runtime guard, + # so without this the documented mark_unbacked min/max check would be a silent no-op. + user_input_bounds = _read_input_bounds(marks) + # Snapshot and clear the REAL example tensors' .grad BEFORE fakeifying and tracing. + # A backward in fn accumulates (``p.grad = p.grad + new``), so a live pre-existing + # grad would be read into the graph and baked by make_fx as a get_attr constant -- + # tripping the invariant-1 guard with a misleading "tensor closed over by fn" error on + # the common warmup-step-then-precompile flow. The clear MUST precede + # _fakeify_with_unbacked: fake_mode.from_tensor copies .grad onto the fakes we trace + # on, so clearing the reals first keeps the fakes grad-free too. Restored in finally; + # precompile does not mutate the user's example .grad (params/buffers AND user inputs). + # Snapshot the ORIGINAL .grad object (no clone) and restore that SAME object below, so + # grad IDENTITY is preserved -- a caller holding a prior p.grad reference, or optimizer + # state keyed on grad identity, is not invalidated. The unbacked path traces on fakes, + # so the reals' .grad is untouched there; the STATIC path (fake_mode is None) traces on + # the real interned params, so a backward in fn DOES write .grad in place -- but onto a + # fresh grad object, since .grad was snapshotted and cleared to None just above. The + # finally-restore below puts the snapshotted object back, so both grad identity and + # value are preserved regardless of which path ran. + saved_grads = [a.grad if isinstance(a, torch.Tensor) else None for a in real_flat] + for a in real_flat: + if isinstance(a, torch.Tensor): + a.grad = None + fake_mode = None + if any(marks): + flat_args, fake_mode = _fakeify_with_unbacked(pb_flat, user_flat, marks) + user_input_shapes = [ + None + if base is None + else tuple(None if i in per else s for i, s in enumerate(base)) + for base, per in zip(user_input_shapes, marks) + ] + + # flat_fn (traced by make_fx) writes these back so _capture can thread the output + # structure and the harvested-grad param indices into the _Capture result. + captured_out_spec: pytree.TreeSpec | None = None + captured_grad_param_indices: list[int] = [] + + def flat_fn(flat: list[object]) -> list[object]: + nonlocal captured_out_spec, captured_grad_param_indices + # The pb region is entirely interned params/buffers (Tensors); the user region + # (flat[num_pb:]) is arbitrary pytree leaves. + pb = cast("list[Tensor]", flat[:num_pb]) + runtime_inputs = pytree.tree_unflatten(flat[num_pb:], in_spec) + with contextlib.ExitStack() as stack: + for mi, m in enumerate(mods): + reparam = {n: pb[uidx] for emi, n, uidx in alias_entries if emi == mi} + stack.enter_context( + stateless._reparametrize_module(m, reparam, tie_weights=True) + ) + # Reconstruct fn's full positional args: reparametrized modules at + # their original positions, runtime inputs at theirs. + full: list[object] = [] + ui = 0 + for i in range(len(args)): + if i in module_pos_set: + full.append(args[i]) + else: + full.append(runtime_inputs[ui]) + ui += 1 + result = fn(*full) + # Harvest parameter gradients produced by any backward in fn. + param_proxies = pb[:num_params] + harvested = [p.grad for p in param_proxies] + # Buffers are not harvested (only params get scattered grads). A registered + # buffer with requires_grad=True that received a gradient would be silently + # dropped, so reject it -- a cheaply-knowable invariant-5 violation. + if any(getattr(b, "grad", None) is not None for b in pb[num_params:]): + raise PrecompileError( + "precompile: a registered buffer received a gradient (it has " + "requires_grad=True), but precompile only harvests gradients for " + "parameters. Register it as an nn.Parameter instead." + ) + # User-input leaves are not harvested either (only params get scattered + # grads), so a requires_grad user input that received a gradient during the + # traced backward would be silently dropped. Reject it, mirroring the buffer + # case -- another cheaply-knowable invariant-5 violation. + if any(getattr(t, "grad", None) is not None for t in flat[num_pb:]): + raise PrecompileError( + "precompile: a user input received a gradient; precompile only " + "harvests gradients for parameters, so an input gradient would be " + "silently dropped. Pass the tensor as a module parameter if its " + "gradient is needed." + ) + + # The result (fn's own return) and the harvested grads are kept as separate + # output regions: the driver returns the result and scatters the grads onto + # the runtime model's .grad fields. We emit a grad output ONLY for params that + # actually received a gradient -- mirroring eager .backward(), which leaves + # .grad = None for frozen / non-contributing params -- and record which unique + # param index each emitted grad belongs to, so the driver scatters onto exactly + # those params. grad_flat is empty when fn ran no backward. + result_flat, result_spec = pytree.tree_flatten(result) + grad_flat = [] + grad_param_indices = [] + for i, g in enumerate(harvested): + if g is not None: + grad_flat.append(g) + grad_param_indices.append(i) + captured_out_spec = result_spec + captured_grad_param_indices = grad_param_indices + return [*result_flat, *grad_flat] + + # Trace with grad enabled so any backward in ``fn`` is built as graph ops; the + # forward graph is the same as under no_grad. Restore in finally so a make_fx + # failure (e.g. fn raising after running a backward) does not leave the user's + # example model with clobbered .grad fields. + from torch.fx.experimental.symbolic_shapes import GuardOnDataDependentSymNode + + tracing_mode = "symbolic" if fake_mode is not None else "real" + capture_cm = fake_mode if fake_mode is not None else contextlib.nullcontext() + try: + with torch.enable_grad(), capture_cm: + try: + gm = make_fx( + flat_fn, + decomposition_table=decompositions, + tracing_mode=tracing_mode, + )(flat_args) + except GuardOnDataDependentSymNode as e: + # A mark_unbacked dim was captured as an unbacked symint (no hint), but + # the computation needs to guard on / specialize its size (e.g. a + # shape-dependent branch or a reshape that pins it). Unbacked dims cannot + # be guarded, so rather than bake a silently-wrong artifact, fail here. + raise PrecompileError( + "precompile: fn needs to guard on a dim marked with mark_unbacked " + "(it branches on or specializes that size), which is not allowed for " + "an unbacked dynamic dim. Do not mark that dim (capture it static), " + "or restructure fn to avoid the size-dependent operation. Underlying: " + f"{str(e).splitlines()[0]}" + ) from e + finally: + for a, g in zip(real_flat, saved_grads): + if isinstance(a, torch.Tensor): + a.grad = g + _check_no_constant_tensors(gm) + _assert_no_control_flow_subgraphs(gm) + _assert_supported(gm) + + # flat_fn always runs during the make_fx trace above, so captured_out_spec is set. + return _Capture( + gm=gm, + flat_args=flat_args, + module_positions=module_positions, + num_positional_args=len(args), + param_names=param_names, + buffer_names=buffer_names, + param_shapes=param_shapes, + buffer_shapes=buffer_shapes, + param_dtypes=param_dtypes, + buffer_dtypes=buffer_dtypes, + param_devices=param_devices, + buffer_devices=buffer_devices, + in_spec=in_spec, + out_spec=cast("pytree.TreeSpec", captured_out_spec), + grad_param_indices=captured_grad_param_indices, + user_input_shapes=user_input_shapes, + user_input_dtypes=user_input_dtypes, + user_input_devices=user_input_devices, + user_input_bounds=user_input_bounds, + fake_mode=fake_mode, + ) + + +class _Capture: + def __init__( + self, + gm: torch.fx.GraphModule, + flat_args: list[object], + module_positions: list[int], + num_positional_args: int, + param_names: list[str], + buffer_names: list[str], + param_shapes: list[tuple[int, ...]], + buffer_shapes: list[tuple[int, ...]], + param_dtypes: list[str], + buffer_dtypes: list[str], + param_devices: list[str], + buffer_devices: list[str], + in_spec: pytree.TreeSpec, + out_spec: pytree.TreeSpec, + grad_param_indices: list[int], + user_input_shapes: list[tuple[int | None, ...] | None], + user_input_dtypes: list[str | None], + user_input_devices: list[str | None], + user_input_bounds: list[_LeafBounds], + fake_mode: FakeTensorMode | None = None, + ) -> None: + self.gm = gm + self.flat_args = flat_args + self.module_positions = module_positions + self.num_positional_args = num_positional_args + self.param_names = param_names + self.buffer_names = buffer_names + self.param_shapes = param_shapes + self.buffer_shapes = buffer_shapes + self.param_dtypes = param_dtypes + self.buffer_dtypes = buffer_dtypes + self.param_devices = param_devices + self.buffer_devices = buffer_devices + self.in_spec = in_spec + self.out_spec = out_spec + self.grad_param_indices = grad_param_indices + self.user_input_shapes = user_input_shapes + self.user_input_dtypes = user_input_dtypes + self.user_input_devices = user_input_devices + self.user_input_bounds = user_input_bounds + # The fake_mode (with ShapeEnv) used for a dynamic-shape capture, threaded to the + # lowering (dynamic_shapes="from_tracing_context"); None for a static capture. + self.fake_mode = fake_mode + + +_GENERATED_HEADER = """\ +# Generated by torch.compiler.precompile -- do not edit. +# +# This is a SELF-CONTAINED, EXECUTABLE artifact: it runs on its own, needing no +# companion cache. You provide the model(s) at runtime, exactly as the original fn +# took them, e.g.: +# +# ns = {} +# exec(open("this_file.py").read(), ns) +# out = ns["forward"](model, my_input) # same args as the traced fn +# +# The runtime model must be STRUCTURALLY IDENTICAL to the one precompile traced +# (same parameter/buffer names, order, and weight tying); only the weight VALUES +# may differ (swap in a checkpoint). This artifact was produced by a non-strict +# make_fx trace, so control flow and shapes are specialized to the example inputs, +# and (inductor backend) each input's stride / memory format is baked too: pass +# runtime inputs in the example's layout (.contiguous() to match a contiguous +# example). See Note [precompile programming model] in torch/_precompile.py. +# +# It contains, in order: +# 1. The composed graph module from aot_autograd.compile_to_python: the inlined +# Inductor kernels (JIT-compiled from the embedded source on first use -- no +# external cache required) plus AOTAutograd's own codegen'd prelude/epilogue +# (tensor-subclass wrap/unwrap, input-mutation reflection, output aliasing), +# exposing ``call(flat_inputs) -> outputs``. +# 2. Calling-convention metadata. +# 3. A small driver that extracts each runtime module's params/buffers (in the +# same order as capture), passes them with the runtime inputs to ``call``, and +# scatters any harvested gradients onto the model's .grad fields. No model +# weights are embedded (you bring the model). +# +# The companion ``cache`` returned by precompile is purely an ACCELERATION used by +# torch.compiler.precompile.load: it primes the inductor kernel caches so exec'ing this +# file loads its kernels from the precompiled binaries (no JIT). This file does not read +# it; running this file alone just JITs. +""" + + +def _build_metadata_section(compiled: PrecompiledModule) -> list[str]: + if compiled._out_spec is None or compiled._in_spec is None: + raise PrecompileError("internal: cannot build metadata before _compile()") + # OUT_SPEC is load-bearing: the driver rebuilds fn's output via tree_unflatten, so + # unlike IN_SPEC it cannot degrade to None. If fn's output structure is not + # JSON-serializable (an unregistered namedtuple, or a registered pytree node with a + # non-JSON-dumpable context), fail with a clear PrecompileError rather than leaking + # a raw pytree NotImplementedError/TypeError. + try: + out_spec_str = pytree.treespec_dumps(compiled._out_spec) + except (NotImplementedError, TypeError) as e: + raise PrecompileError( + "precompile cannot serialize the output structure of fn (its pytree " + "TreeSpec is not JSON-serializable). This fires when fn returns an " + "unregistered collections.namedtuple, or a registered pytree node with a " + "non-JSON-dumpable context. Register the namedtuple via " + "torch.utils._pytree._register_namedtuple(...) (or supply a JSON-dumpable " + "to_dumpable_context), or return a plain tuple/list/dict of tensors." + ) from e + # IN_SPEC drives the runtime input-structure check, but is best-effort: some specs + # are not JSON-serializable -- an unregistered namedtuple raises NotImplementedError, + # and a registered pytree node whose context is not JSON-dumpable (no + # to_dumpable_context serializer, or one yielding non-JSON output) raises TypeError. + # Such inputs still compile -- emit IN_SPEC = None and the driver skips the + # structure check rather than regressing. + try: + in_spec_str: str | None = pytree.treespec_dumps(compiled._in_spec) + except (NotImplementedError, TypeError): + in_spec_str = None + parts = [ + "# " + "=" * 70, + "# 2. Calling-convention metadata", + "# " + "=" * 70, + "import torch as _torch", + "import torch.utils._pytree as _pytree", + "", + # python_code is the single source of truth for the calling convention; the + # cache holds ONLY the compiled/captured artifact. load() reads these + # constants back out of python_code (see _parse_artifact_metadata). + f"BACKEND = {compiled._backend!r}", + f"MODULE_POSITIONS = {compiled._module_positions!r}", + # Number of positional args the traced fn took (modules + runtime inputs); the + # driver checks the runtime call passes the same count up front, so a wrong + # arity raises a clear PrecompileError instead of a raw IndexError. + f"NUM_POSITIONAL_ARGS = {compiled._num_positional_args}", + f"PARAM_NAMES = {compiled._param_names!r}", + f"BUFFER_NAMES = {compiled._buffer_names!r}", + # Per interned param / buffer example shape / dtype / device (aligned to + # PARAM_NAMES / BUFFER_NAMES); the driver checks each runtime param/buffer against + # these for the structural contract (invariant 2). + f"PARAM_SHAPES = {compiled._param_shapes!r}", + f"BUFFER_SHAPES = {compiled._buffer_shapes!r}", + f"PARAM_DTYPES = {compiled._param_dtypes!r}", + f"BUFFER_DTYPES = {compiled._buffer_dtypes!r}", + f"PARAM_DEVICES = {compiled._param_devices!r}", + f"BUFFER_DEVICES = {compiled._buffer_devices!r}", + # Which unique-param index each trailing grad output belongs to (see invariant 5); + # the driver scatters grad k onto params[GRAD_PARAM_INDICES[k]]. + f"GRAD_PARAM_INDICES = {compiled._grad_param_indices!r}", + # The pytree structure of the runtime inputs, or None if not serializable (the + # driver validates against it when present, else skips the structure check). + f"IN_SPEC = {in_spec_str!r}", + f"OUT_SPEC = {out_spec_str!r}", + # Per user-input-leaf example shape / dtype / device (None for a non-tensor / + # subclass leaf); the drivers reject a runtime mismatch (invariants 3 and 6). + # Memory-format mismatches are caught by the inductor artifact's own + # assert_size_stride (pinned on at capture). + f"USER_INPUT_SHAPES = {compiled._user_input_shapes!r}", + f"USER_INPUT_DTYPES = {compiled._user_input_dtypes!r}", + f"USER_INPUT_DEVICES = {compiled._user_input_devices!r}", + # Per user-input-leaf mark_unbacked min/max bounds: None for a leaf with no bounded + # marked dim, else {dim: (lo, hi)} (either may be None). The drivers reject a + # runtime size outside the declared range (invariant 3); see the inlined drivers. + f"USER_INPUT_BOUNDS = {compiled._user_input_bounds!r}", + "", + ] + return parts + + +def _parse_artifact_metadata(python_code: str) -> dict[str, object]: + """Read the calling-convention constants back out of ``python_code`` WITHOUT + executing it (exec'ing the inlined Inductor output would JIT the kernels, the + very work the cache exists to skip). + + python_code is the single source of truth: ``_build_metadata_section`` emits the + constants below as top-level literal assignments, so an AST walk + literal_eval + recovers them safely. The cache then only needs to carry the compiled artifact. + """ + import ast + + wanted = { + "BACKEND", + "MODULE_POSITIONS", + "NUM_POSITIONAL_ARGS", + "PARAM_NAMES", + "BUFFER_NAMES", + "PARAM_SHAPES", + "BUFFER_SHAPES", + "PARAM_DTYPES", + "BUFFER_DTYPES", + "PARAM_DEVICES", + "BUFFER_DEVICES", + "GRAD_PARAM_INDICES", + "IN_SPEC", + "OUT_SPEC", + "USER_INPUT_SHAPES", + "USER_INPUT_DTYPES", + "USER_INPUT_DEVICES", + "USER_INPUT_BOUNDS", + } + found: dict[str, object] = {} + try: + tree = ast.parse(python_code) + except SyntaxError as e: + raise PrecompileError( + "python_code is not valid Python; it does not look like a " + "torch.compiler.precompile artifact." + ) from e + for node in tree.body: + if not isinstance(node, ast.Assign) or len(node.targets) != 1: + continue + target = node.targets[0] + if not isinstance(target, ast.Name): + continue + if target.id in wanted: + found[target.id] = ast.literal_eval(node.value) + else: + # Not a metadata name we consume (the driver section emits only + # function defs today, but a future artifact revision could add a + # driver-internal top-level assignment). Skipped by design, but log + # it at debug so a malformed / renamed artifact is diagnosable + # rather than silently dropped. + log.debug( + "precompile: ignoring unrecognized top-level assignment %r while " + "parsing artifact calling-convention metadata", + target.id, + ) + missing = wanted - found.keys() + if missing: + raise PrecompileError( + f"python_code is missing calling-convention metadata {sorted(missing)}; " + "it does not look like a torch.compiler.precompile artifact." + ) + return found + + +def _build_python_source( + compiled: PrecompiledModule, + graph_python: str, +) -> str: + parts = [_GENERATED_HEADER, ""] + parts.append("# " + "=" * 70) + parts.append("# 1. Compiled graph (AOTAutograd + Inductor): exposes ``call``") + parts.append("# " + "=" * 70) + # The composed graph module from aot_autograd.compile_to_python: the inlined + # Inductor kernels plus AOTAutograd's codegen'd prelude/epilogue, exposing + # ``call(flat_inputs) -> outputs`` (subclass + mutation handled inside). + parts.append(graph_python) + parts.append("") + parts.extend(_build_metadata_section(compiled)) + parts.append("# " + "=" * 70) + parts.append( + "# 3. Driver: module params/buffers + grad scatter + calling convention" + ) + parts.append("# " + "=" * 70) + parts.append(_emit_driver_source("_inductor_forward")) + return "\n".join(parts) + + +_EAGER_GENERATED_HEADER = """\ +# Generated by torch.compiler.precompile (backend="eager") -- do not edit. +# +# Self-contained, executable artifact: the captured ATen graph is inlined below (both +# the human-readable rendering and the executable code) and runs on its own. Provide +# the model(s) at runtime, exactly as the original fn took them: +# +# ns = {} +# exec(open("this_file.py").read(), ns) +# out = ns["forward"](model, my_input) # same args as the traced fn +# +# The runtime model must be structurally identical to the traced one (only weight +# VALUES may differ), and control flow / shapes are specialized to the example inputs. +# See Note [precompile programming model] in torch/_precompile.py for the full contract. +""" + + +def _build_eager_python_source(compiled: PrecompiledModule) -> str: + gm = compiled._gm + # gm.code defines ``def forward(self, flat)`` that references fx_pytree / pytree + # and self._in_spec / self._out_spec. Rename it so it does not collide with the + # driver's public ``forward``, and supply the specs via a tiny holder object so + # the inlined graph runs standalone. + in_spec = gm._in_spec if gm is not None else None + out_spec = gm._out_spec if gm is not None else None + if gm is None or in_spec is None or out_spec is None: + raise PrecompileError("internal: eager graph missing before _compile()") + graph_src = gm.code.replace("def forward(", "def _graph_forward(", 1) + in_spec_str = pytree.treespec_dumps(in_spec) + out_spec_str = pytree.treespec_dumps(out_spec) + parts = [_EAGER_GENERATED_HEADER, ""] + parts.append("# " + "=" * 70) + parts.append("# 1. Captured ATen graph (eager backend) -- executable and readable") + parts.append("# " + "=" * 70) + # gm.code relies on fx's custom builtins (torch, device, inf, nan, NoneType, + # fx_pytree, pytree) being in scope -- fx injects them when a real GraphModule + # runs. Reproduce the FULL set (not just torch/pytree) so a graph that bakes a + # device / inf / nan constant (e.g. BatchNorm, masked_fill to -inf) runs + # standalone instead of raising NameError. Sourced from fx so it stays correct. + from torch.fx.graph import _custom_builtins + + for _cb in _custom_builtins.values(): + parts.append(_cb.import_str) + parts.append(graph_src) + parts.append("") + parts.append("class _GraphSelf:") + parts.append(f" _in_spec = pytree.treespec_loads({in_spec_str!r})") + parts.append(f" _out_spec = pytree.treespec_loads({out_spec_str!r})") + parts.append("") + parts.append("") + parts.append("def call(args):") + parts.append(" out = _graph_forward(_GraphSelf(), list(args))") + parts.append(" return list(out) if isinstance(out, (list, tuple)) else [out]") + parts.append("") + parts.extend(_build_metadata_section(compiled)) + parts.append("# " + "=" * 70) + parts.append("# 3. Driver: run the inlined captured graph eagerly") + parts.append("# " + "=" * 70) + parts.append(_emit_driver_source("_eager_forward")) + return "\n".join(parts) + + +_DRIVER_MAIN = """\ +if __name__ == "__main__": + print("forward() is ready; call it with the model(s) and inputs the traced") + print("fn took, e.g. forward(model, x).") +""" + + +def _emit_driver_source(forward_fn_name: str) -> str: + """Emit the runtime driver as text for inlining into python_code. + + The driver lives as real, type-checked code in torch._precompile_driver; here we read + it back with inspect.getsource (LAZILY -- only on this emit path; load() never runs + it, so a stripped-source environment only affects capture, not reload) and rename the + selected forward variant to the public ``forward``. Emitting the TEXT (rather than + importing the module from the artifact) keeps python_code self-contained and + version-frozen (Note [precompile programming model], invariant 7).""" + import inspect + + from torch import _precompile_driver as driver + + forward_fn = getattr(driver, forward_fn_name) + blocks = [ + inspect.getsource(driver._extract_param_buffers), + inspect.getsource(driver._fail), + inspect.getsource(driver._check_structure), + inspect.getsource(forward_fn).replace( + f"def {forward_fn_name}(", "def forward(", 1 + ), + ] + body = "\n\n".join(block.rstrip() for block in blocks) + return "\n" + body + "\n\n\n" + _DRIVER_MAIN + + +def _assert_supported(gm: torch.fx.GraphModule) -> None: + """Enforce invariant 4 of Note [precompile programming model]: reject boundary + effects the AOT backend's standalone composition does not handle. Detected + directly from the captured graph -- no AOTAutograd coupling. + + Input mutation (incl. module buffers, e.g. BatchNorm running stats), tensor- + subclass wrap/unwrap, output aliasing, and functionalized RNG are SUPPORTED: + AOTAutograd's codegen'd prelude/epilogue is composed into the artifact (see + torch._functorch.aot_autograd.compile_to_python), so they are not rejected here. + + Effectful ops are not supported yet (an implementation gap, not a fundamental + limit), so raise here with a concrete reason rather than let the failure surface + deep in the cache layer. See _unsupported for the mechanical cause. + """ + from torch._higher_order_ops.effects import _get_effect + + for node in gm.graph.nodes: + # Only ATen ops can be in the effect registry; skip plain call_functions + # like operator.getitem (which _get_effect rejects). + if node.op == "call_function" and isinstance( + node.target, torch._ops.OpOverload + ): + if _get_effect(node.target) is not None: + raise _unsupported(f"effectful op {node.target}") + + +def _unsupported(reason: str) -> PrecompileError: + return PrecompileError( + f"precompile cannot compile this computation: {reason}. The graph contains an " + "effectful op, which is not supported yet: its with_effects HOP is " + "non-cacheable, so the compiled artifact cannot be saved and lowered to " + "standalone source." + ) + + +class PrecompiledModule: + """Internal holder for a precompiled computation / a loaded runnable.""" + + def __init__( + self, + fn: Callable[..., object], + *, + backend: str = "inductor", + tracer: str = "make_fx", + decompositions: dict | None = None, + ) -> None: + # ``fn`` is the whole computation: an nn.Module, or a callable that closes + # over the module(s) it uses (e.g. ``lambda x: model(x)``, or a training + # step that computes a loss and torch.autograd.grad). + self._fn = fn + self._backend = backend + self._tracer = tracer + self._decompositions = decompositions + self._artifact: object = None + self._module_positions: list[int] = [] + self._num_positional_args: int = 0 + # Interned param / buffer names and their example shape, dtype, and device + # (aligned lists); the driver checks each runtime param/buffer against these for + # the structural contract (invariant 2). Populated by _compile(). + self._param_names: list[str] = [] + self._buffer_names: list[str] = [] + self._param_shapes: list[tuple[int, ...]] = [] + self._buffer_shapes: list[tuple[int, ...]] = [] + self._param_dtypes: list[str] = [] + self._buffer_dtypes: list[str] = [] + self._param_devices: list[str] = [] + self._buffer_devices: list[str] = [] + self._in_spec: pytree.TreeSpec | None = None + self._out_spec: pytree.TreeSpec | None = None + self._gm: torch.fx.GraphModule | None = None + # Inductor backend: the composed self-contained graph module (from + # aot_autograd.compile_to_python, exposing ``call(flat_inputs)``) and the + # opaque artifact-cache bytes (None if uncacheable), populated by _compile(). + self._graph_python: str = "" + self._artifact_bytes: bytes | None = None + # Which unique-param index each emitted (trailing) grad output belongs to; its + # length is the number of grad outputs. Lets the driver scatter grads onto + # exactly the params that received one, leaving frozen / non-contributing + # params' .grad as None. + self._grad_param_indices: list[int] = [] + # Per user-input-leaf example shape, dtype, and device (None for a subclass / + # non-tensor leaf; a marked-dynamic dim is None within the shape tuple); the drivers + # reject a runtime mismatch (invariants 3 and 6). Stride / memory format is enforced + # by the inductor artifact's own assert_size_stride, not recorded here. Populated by + # _compile(). + self._user_input_shapes: list[tuple[int | None, ...] | None] = [] + self._user_input_dtypes: list[str | None] = [] + self._user_input_devices: list[str | None] = [] + # Per user-input-leaf mark_unbacked min/max bounds (None for a leaf with no + # bounded marked dim, else {dim: (lo, hi)}). The drivers reject a runtime size + # outside the declared range (invariant 3). Populated by _compile(). + self._user_input_bounds: list[Any] = [] + # Set only on the load() path, where we wrap a reconstructed callable. + self._loaded_forward: Callable[..., object] | None = None + + @classmethod + def _from_loaded( + cls, + forward: Callable[..., object], + *, + backend: str, + ) -> PrecompiledModule: + """Build a runnable from load()'s reconstructed forward. + + load() does not re-run capture/_compile, so reuse ``__init__`` for all the + defaults (the single definition of this object's state) and override only the + reconstructed forward. All the calling-convention metadata lives in the inlined + driver (``forward``) itself, so the __init__ fields (``_fn``, ``_gm``, + ``_module_positions``, ``_out_spec``, ...) stay at their defaults; inspect the + artifact via python_code. + """ + obj = cls(None, backend=backend) # type: ignore[arg-type] + obj._loaded_forward = forward + return obj + + def _compile(self, args: tuple[object, ...]) -> None: + # make_fx is the only implemented tracer; "dynamo" is a planned alternative + # capture front-end. Reject it here (the single capture-dispatch point) before + # running fn, so the failure is clear rather than a wrong default. + if self._tracer != "make_fx": + raise NotImplementedError( + f"precompile tracer={self._tracer!r} is not implemented yet; use " + "tracer='make_fx' (the default)." + ) + if self._backend == "eager" and _has_unbacked_marks(args): + raise NotImplementedError( + "precompile: mark_unbacked (dynamic shapes) is only supported with " + "backend='inductor'; eager + unbacked is not supported." + ) + capture = _capture(self._fn, args, self._decompositions) + self._module_positions = capture.module_positions + self._num_positional_args = capture.num_positional_args + self._param_names = capture.param_names + self._buffer_names = capture.buffer_names + self._param_shapes = capture.param_shapes + self._buffer_shapes = capture.buffer_shapes + self._param_dtypes = capture.param_dtypes + self._buffer_dtypes = capture.buffer_dtypes + self._param_devices = capture.param_devices + self._buffer_devices = capture.buffer_devices + self._user_input_shapes = capture.user_input_shapes + self._user_input_dtypes = capture.user_input_dtypes + self._user_input_devices = capture.user_input_devices + self._user_input_bounds = capture.user_input_bounds + self._in_spec = capture.in_spec + self._out_spec = capture.out_spec + self._grad_param_indices = capture.grad_param_indices + self._gm = capture.gm + + if self._backend == "eager": + # No Inductor lowering: the captured ATen graph IS the artifact. It is + # run directly on the (subclass-level) inputs, so there is no inductor + # ``call`` to inline and no dense flatten/unflatten -- the graph runs + # exactly as captured (see Note [precompile programming model]). + return + + # Lower through the AOT backend contract: it returns a self-contained module + # exposing ``call(flat_inputs) -> outputs`` (with AOTAutograd's own codegen'd + # prelude/epilogue -- subclass wrap/unwrap, input-mutation reflection, output + # aliasing -- composed in, not reimplemented here) plus an opaque cache (the + # save_cache_artifacts bundle that primes the inductor cache on load, or None + # for uncacheable graphs). + import torch._inductor.config as _ind_config + from torch._functorch import aot_autograd + from torch._inductor.exc import InductorError + from torch._inductor.standalone_compile import NoRunnableInductorModuleError + + # Pin size_asserts ON so the artifact ALWAYS bakes assert_size_stride for the + # inputs the graph reads -- this enforces the input memory-format contract + # (invariant 6) at runtime regardless of the user's ambient size_asserts config + # (off would otherwise elide the asserts and silently read wrong strides). The + # guard is conservative (see the inlined driver checks): an input the graph never + # reads gets no assert and stays layout-flexible, but a read input is asserted on + # the example layout even for layout-agnostic ops (matmul/addmm), since precompile + # cannot recompile to specialize a new layout the way torch.compile would. A + # dynamic (unbacked) capture additionally pins scalar_asserts so the make_fx + # ShapeEnv's runtime range asserts survive into the artifact. + # + # These are inductor config keys, so they ride in as ``options`` (aot_autograd. + # compile_to_python merges them into the inductor config.patch it wraps the + # compile in) rather than being patched around the call. The AOT layer detects + # dynamic (symbolic) shapes off the captured graph and threads the make_fx + # ShapeEnv through automatically, so there is no dynamic_shapes knob to pass and + # no manual TracingContext to install: a static capture specializes to the + # example shapes, an unbacked capture keeps the symbols. + options: dict[str, Any] = {"size_asserts": True} + if capture.fake_mode is not None and hasattr(_ind_config, "scalar_asserts"): + options["scalar_asserts"] = True + try: + self._graph_python, self._artifact_bytes = aot_autograd.compile_to_python( + capture.gm, capture.flat_args, options=options + ) + except NoRunnableInductorModuleError as e: + # Inductor emits no runnable module for a graph with no compute to lower -- + # one that returns inputs or Python constants unchanged (e.g. ``lambda x: x``, + # ``x.detach()``, ``return 7``, or a bare ``return None``). The eager backend + # (above) handles these; surface a clear PrecompileError instead of the raw + # lowering error. + raise PrecompileError( + "the inductor backend cannot lower a graph with no compute -- the traced " + "fn returns its inputs or Python constants unchanged, producing no " + "Inductor kernel. Return a computed tensor, or use backend='eager'." + ) from e + except InductorError as e: + # Inductor codegen asserts on certain non-tensor Python values in the output + # structure ("Unexpected output types: []" -- also complex, + # str, ...); int/bool/None outputs lower fine, and the eager backend handles + # them too. Surface a clear PrecompileError instead of the raw assertion. + if "Unexpected output types" in str(e): + raise PrecompileError( + "the inductor backend cannot lower a graph whose output mixes a " + "non-tensor Python value (e.g. float / complex / str) with computed " + "tensors (int / bool / None outputs are fine). Return only tensors, " + "or use backend='eager'." + ) from e + raise + + def __call__(self, *args: object) -> object: + # A PrecompiledModule is runnable only after load(); precompile() itself + # returns (python_code, cache) rather than a runnable. + if self._loaded_forward is None: + raise PrecompileError( + "this object is not runnable; build one with " + "torch.compiler.precompile.load(python_code, cache)." + ) + return self._loaded_forward(*args) + + def to_python_code(self) -> str: + """Return the self-contained, executable Python artifact as a string. + + It runs on its own, needing no cache (Note [precompile programming model], + "self-contained"). For the inductor backend it embeds the composed graph + module from aot_autograd.compile_to_python (kernels JIT-compile on first + call; AOTAutograd's prelude/epilogue inlined), the calling-convention + metadata, and a ``forward()`` that takes the same args the traced fn took + (the model(s) plus runtime inputs). For the eager backend it embeds the + captured ATen graph (both readable and executable) plus a driver that runs it + eagerly. No weights are embedded. + """ + if self._loaded_forward is not None: + raise PrecompileError( + "this object was produced by torch.compiler.precompile.load(); the " + "python_code you passed in is the source artifact (load() does not " + "re-capture, so there is no python_code to re-emit from this object)." + ) + if self._backend == "eager": + if self._gm is None: + raise PrecompileError("internal: not compiled; call _compile() first") + return _build_eager_python_source(self) + if not self._graph_python: + raise PrecompileError("internal: not compiled; call _compile() first") + return _build_python_source(self, self._graph_python) + + def to_cache_bytes(self, python_code: str | None = None) -> bytes: + """Return the binary cache as bytes -- an ACCELERATION, not required to run. + + ``python_code`` is the single source of truth for the calling convention, so the + cache holds only the compiled artifact plus the integrity tag and code_hash. For + the inductor backend that artifact is the ``save_cache_artifacts`` bundle (load + primes the kernel caches with it, so a warm reload skips JIT); for the eager + backend it is None. See Note [precompile programming model], invariant 7. + + ``python_code`` defaults to what ``to_python_code()`` would emit; ``__call__`` + threads in the exact string it already built so code_hash matches the bytes + returned to the user and the metadata is not rebuilt. + """ + # _artifact_bytes is the inductor cache bundle (None if uncacheable, and always + # None for eager); the envelope is a plain str/int/bytes dict (weights_only-safe) + # carrying the tag + code_hash that binds it to python_code (invariant 7). + if self._loaded_forward is not None: + raise PrecompileError( + "this object was produced by torch.compiler.precompile.load(); the cache " + "you passed in is the source artifact (load() does not re-capture, so " + "there is no cache to re-emit from this object)." + ) + if python_code is None: + python_code = self.to_python_code() + code_hash = hashlib.sha256(python_code.encode()).hexdigest() + buf = io.BytesIO() + torch.save( + { + "format": _CACHE_FORMAT, + "version": _CACHE_VERSION, + "backend": self._backend, + "code_hash": code_hash, + "artifact": self._artifact_bytes, + }, + buf, + ) + return buf.getvalue() + + +def _make_inlined_forward(python_code: str) -> Callable[..., object]: + """Fallback: execute the self-contained python string (JITs kernels). + + ``python_code`` needs no cache -- the kernels (inductor) or graph (eager) are + inlined, so we just exec it and hand back its ``forward``. The returned + ``forward`` takes the same args the traced fn took (model(s) plus runtime + inputs).""" + # python_code is untrusted EXECUTABLE input -- exec'ing it runs whatever it contains + # (JIT-compiling inlined kernels or running the inlined graph). Warn per load (not + # warning_once) before the exec so the inlined fallback is never silent about it. + log.warning( + "torch.compiler.precompile.load is about to EXEC python_code, which is untrusted " + "executable input (it runs inlined kernels / graph code). Only exec python_code " + "you produced or otherwise trust (Note [precompile programming model], " + "invariant 7)." + ) + module_ns: dict[str, object] = {"__name__": "_precompiled_artifact"} + exec(compile(python_code, "", "exec"), module_ns) + return cast("Callable[..., object]", module_ns["forward"]) + + +class _PrecompileApi: + """Callable namespace implementing ``torch.compiler.precompile`` and ``.load``. + + A single instance is exposed as ``torch.compiler.precompile``; calling it precompiles a + computation and ``torch.compiler.precompile.load`` reloads the resulting artifacts. It + is a class (rather than a function with attached attributes) so the call, the + loader, and the error type are explicit members. + + The contract for both ``__call__`` and ``load`` is Note [precompile programming + model] in this module. + """ + + # Reported so test_public_bindings / introspection see this as ``torch.compiler``. + __module__ = "torch.compiler" + + # The error type raised by precompile, reachable as + # ``torch.compiler.precompile.PrecompileError``. + PrecompileError = PrecompileError + + def __reduce__(self) -> str: + # torch.compiler.precompile is a process-wide singleton; pickle/deepcopy must + # round-trip to the SAME object (the instance carries no per-call state) rather + # than fail to pickle a bound-method-bearing instance. Returning the qualified + # name resolves back to this singleton on unpickle. + return "precompile" + + def __repr__(self) -> str: + return "torch.compiler.precompile" + + def __call__( + self, + fn: Callable[..., object], + *example_inputs: object, + backend: str = "inductor", + tracer: str = "make_fx", + decompositions: dict | None = None, + ) -> tuple[str, bytes]: + """Ahead-of-time precompile ``fn`` against ``example_inputs``. + + .. note:: + + ``torch.compiler.precompile`` is NOT + ``torch._dynamo.config.caching_precompile`` (a ``torch.compile`` + guard-serialization caching mode); it captures ``fn`` ahead of time and + lowers it to a self-contained Python source artifact. + + With the default ``make_fx`` tracer this is a non-strict trace with an explicit + contract; read Note [precompile programming model] before using it. The artifact + faithfully reproduces ``fn`` only for callers that uphold that contract. + + THREADING: the inductor lowering step drives process-global compiler state + and is serialized by an internal lock, so concurrent ``backend="inductor"`` + calls lower one at a time. The make_fx capture phase and the ``backend="eager"`` + path are NOT serialized. + + ``backend`` selects how the captured graph is realized: + + - ``"inductor"`` (default): lower the graph through + ``torch._functorch.aot_autograd.compile_to_python`` (the full AOTAutograd + + Inductor pipeline, composed into one self-contained module). ``python_code`` + is the inlined Inductor output with AOTAutograd's prelude/epilogue; the cache + holds the save_cache_artifacts bundle that primes the inductor cache on load. + - ``"eager"``: do NOT lower -- keep the captured ATen graph and run it as-is + (analogous to ``torch.compile(backend="eager")``). ``python_code`` inlines + the readable captured graph (both the inspectable rendering and the + executable artifact); the eager cache carries no compiled artifact + (artifact=None) but is still a full integrity-tagged envelope -- with no + kernels there is nothing to accelerate, so ``load`` runs the inlined graph. + Useful for + inspecting/debugging exactly what was traced without an Inductor dependency. + + ``tracer`` selects the capture front-end: + + - ``"make_fx"`` (default): a NON-STRICT make_fx trace -- it records the ATen ops + that actually run when ``fn`` executes once on the example inputs and does not + analyze your Python, so control flow and shapes are specialized to the example + (the source of the programming-model contract). The only tracer implemented + today. + - ``"dynamo"``: planned (a Dynamo-based front-end that analyzes the Python); + raises ``NotImplementedError`` for now. + + ``decompositions`` is an optional decomposition table (a dict mapping each + ``OpOverload`` to a decomposition function) forwarded to ``make_fx`` as its + ``decomposition_table`` during capture, so you can control how ATen ops are + broken down in the captured graph. Defaults to ``None`` (make_fx's default). + + Dynamic shapes are opt-in via ``torch._dynamo.decorators.mark_unbacked`` + (inductor backend only), NOT a precompile kwarg: mark dims on the inputs before + calling, e.g. ``mark_unbacked(x, 0); precompile(fn, model, x)`` frees ``x``'s + batch dim. Marked dims are captured as UNBACKED symints, which cannot be guarded + on, so one artifact serves any runtime size of them (invariant 3); a graph that + needs to guard on / specialize a marked dim fails at capture with a + ``PrecompileError``. Dims sharing a ``shape_id`` reuse one symbol (equal by + construction); ``min``/``max`` become runtime asserts. Other dims stay static. + Dims that MUST be equal at runtime (e.g. two inputs combined by a broadcast that + requires equal sizes, ``model(a) + model(b)``) MUST be given a SHARED ``shape_id`` + so a mismatch is rejected; marking two such dims INDEPENDENTLY currently bakes a + SILENT equal-size assumption and a runtime mismatch does NOT raise the loud failure + eager gives (invariant 3). This is a harvesting gap, not an inherent limit of the + standalone artifact: the capture ShapeEnv DOES record the equality (as a deferred + runtime assert, e.g. ``Eq(u0, u1)``), but precompile does not yet harvest/enforce + those relational asserts in the driver -- only the decorator's declared min/max feed + the runtime bound checks. A shared ``shape_id`` is the way to get the check today. + + Returns ``(python_code, cache)`` -- a self-contained, executable Python + source string (the single source of truth for the calling convention) and a + binary cache holding ONLY the backend artifact (NO metadata, NO weights). + Reload a runnable with ``torch.compiler.precompile.load(python_code, cache)``. + + ``fn`` is the whole computation, e.g.:: + + python_code, cache = torch.compiler.precompile( + lambda model, x: model(x), model, x + ) + + + def train_step(model, x, t): + loss_fn(model(x), t).backward() # or return autograd.grad(...) + + + python_code, cache = torch.compiler.precompile(train_step, model, x, t) + + Among ``example_inputs``, the ``nn.Module`` arguments have their params/buffers + lifted to graph inputs (no weights are baked into the artifact -- invariant 1); + the rest are the runtime inputs. The reloaded callable is invoked with the SAME + argument structure -- pass the model(s) again at runtime, e.g. + ``f_c(model, x)``, and that runtime model must match the example model's + parameter/buffer structure (invariant 2). Arguments are matched POSITIONALLY: + pass the model(s) and inputs positionally both here and at load time; keyword- + argument calling conventions are not supported (a fn that relies on them would + surface as a raw arity error). If ``fn`` ran a backward, the + resulting parameter gradients are scattered (accumulated) onto that runtime + model's ``parameters()`` ``.grad`` fields, exactly like eager ``.backward()``, + so a ``zero_grad()`` / ``optimizer.step()`` loop works unchanged; the artifact + returns ``fn``'s own result (``None`` for a bare ``.backward()`` step), not the + grads (invariant 5). + + Input mutation (incl. module buffers, e.g. BatchNorm running stats in + training mode), tensor subclasses (e.g. DTensor), and outputs aliasing inputs + are supported -- AOTAutograd's prelude/epilogue is composed into the artifact + (invariant 4), as is functionalized RNG. Caller responsibilities NOT checked + here (see the Note): the runtime model must be structurally identical to the + example, and control flow / shapes are specialized to ``example_inputs`` + (invariants 2 and 3). Violations that ARE checked raise ``PrecompileError``: a + tensor baked + as a constant (invariant 1), effectful ops (invariant 4), and -- for the + inductor backend -- a runtime input whose stride / memory format differs from + the example's (invariant 6). + """ + torch._C._log_api_usage_once("torch.compiler.precompile") + if backend not in ("inductor", "eager"): + raise ValueError( + f"precompile backend must be 'inductor' or 'eager', got {backend!r}." + ) + if tracer not in ("make_fx", "dynamo"): + raise ValueError( + f"precompile tracer must be 'make_fx' or 'dynamo', got {tracer!r}." + ) + compiled = PrecompiledModule( + fn, backend=backend, tracer=tracer, decompositions=decompositions + ) + compiled._compile(example_inputs) + # Build the (expensive) python_code ONCE and thread it into to_cache_bytes so + # the full metadata + embedded kernel source is not rebuilt, and so code_hash is + # sha256 over exactly the bytes returned to the caller (a matched pair loads). + python_code = compiled.to_python_code() + return python_code, compiled.to_cache_bytes(python_code) + + def load(self, python_code: str, cache: bytes) -> Callable[..., object]: + """Reconstruct a runnable from ``(python_code, cache)`` from precompile. + + The driver runs from ``python_code`` -- the single source of truth for the whole + calling convention. ``load`` reads the cache's ``BACKEND`` (to check the pairing) + and, for the inductor backend, primes the inductor kernel caches from its + ``save_cache_artifacts`` bundle (via ``torch.compiler.load_cache_artifacts``) so a + warm reload loads precompiled kernels instead of JIT-compiling; then it exec's + ``python_code``. With no usable cache it degrades to JIT'ing from ``python_code``. + + Call the result with the SAME argument structure ``fn`` took -- the + model(s) in their original positions plus the runtime inputs. Per invariant + 2 of Note [precompile programming model], the runtime model must match the + example model's parameter/buffer structure; precompile re-derives the + param/buffer list from it (same interning/order as capture). + + Raises ``PrecompileError`` if ``python_code`` is malformed or is not a + ``torch.compiler.precompile`` artifact (it fails to parse, or is missing the + calling-convention metadata), if the cache's ``backend`` tag does not match + ``python_code``, or if the cache's ``code_hash`` does not match + ``sha256(python_code)`` -- i.e. the cache and python_code came from different + ``precompile()`` calls. A cache whose ``format``/``version`` does not match (a + foreign or different-build envelope) is NOT fatal: the cache is acceleration + only, so ``load`` degrades to JIT'ing from ``python_code`` rather than crashing. + """ + # Unpickling the cache references classes in AOTAutograd's runtime; import + # dynamo first so that import completes in a non-circular order (otherwise + # a cold load can hit a runtime_wrappers <-> _dynamo circular import). + import torch._dynamo + + # The whole calling convention (MODULE_POSITIONS, OUT_SPEC, USER_INPUT_*, PARAM_*, + # BUFFER_*, IN_SPEC, ...) is consumed by the driver INLINED in python_code + # (emitted from torch._precompile_driver), so the loaded object needs none of it. + # _parse_artifact_metadata still runs to validate python_code is a precompile + # artifact and to read BACKEND for the cache-pairing check below. + meta = _parse_artifact_metadata(python_code) + backend = cast(str, meta["BACKEND"]) + + # weights_only=True is safe (plain str/int/bytes dict). The inner artifact bytes + # are the inductor save_cache_artifacts bundle, used below to prime the kernel + # caches. The cache is acceleration only, so an unreadable envelope or a FORMAT / + # VERSION mismatch degrades to JIT'ing from python_code rather than crashing. A + # BACKEND or CODE_HASH mismatch is different -- it signals a wrong (python_code, + # cache) pairing -- so it hard-fails rather than running under foreign metadata. + artifact = None + try: + blob = torch.load(io.BytesIO(cache), weights_only=True) + if blob.get("format") != _CACHE_FORMAT or blob.get("version") != ( + _CACHE_VERSION + ): + log.warning( + "torch.compiler.precompile.load got a cache with format=%r " + "version=%r, expected %r / %r; it is likely from a different torch " + "build. Falling back to JIT from python_code.", + blob.get("format"), + blob.get("version"), + _CACHE_FORMAT, + _CACHE_VERSION, + ) + blob = None + if blob is not None: + if blob.get("backend") != backend: + raise PrecompileError( + f"cache backend {blob.get('backend')!r} does not match the " + f"python_code backend {backend!r}; the cache and python_code " + "came from different precompile() calls." + ) + # Reject a cache whose code_hash does not match this python_code (a + # mismatched pairing); see Note [precompile programming model], invariant 7. + expected_code_hash = hashlib.sha256(python_code.encode()).hexdigest() + if blob.get("code_hash") != expected_code_hash: + raise PrecompileError( + "cache does not match python_code (its code_hash " + f"{blob.get('code_hash')!r} != sha256(python_code) " + f"{expected_code_hash!r}); the cache and python_code came from " + "different precompile() calls. Pair each cache with the " + "python_code from the same precompile() call." + ) + artifact = blob.get("artifact") + except PrecompileError: + raise + except Exception as e: + log.warning( + "torch.compiler.precompile.load could not read the cache envelope (%s: %s); the " + "cache is likely corrupt or from a different torch build. Falling back " + "to JIT from python_code.", + type(e).__name__, + e, + ) + if artifact is not None: + # Prime the inductor kernel caches from the bundle so the exec of python_code + # below loads the precompiled kernels (Triton binaries / autotune results) + # instead of recompiling them. The composed python_code runs its inlined + # kernels directly (no compile_fx re-entry, so no FxGraphCache lookup); the + # acceleration is the warm kernel cache. This is a pure acceleration: a stale / + # cross-torch-version / corrupt bundle that fails to load just leaves the caches + # cold, and python_code JITs -- same result, no crash. + try: + torch.compiler.load_cache_artifacts(artifact) + except Exception as e: + log.warning( + "torch.compiler.precompile.load could not prime the cache from the " + "artifact bundle (%s: %s); it is likely stale or from a different " + "torch build. Falling back to JIT from python_code.", + type(e).__name__, + e, + ) + # Run the driver inlined in python_code. It carries the full calling convention and + # runtime safety checks (subclass wrap/unwrap, param/buffer lifting, grad harvest, + # input/model validation) and JITs the kernels -- which hit the primed cache when + # the bundle above loaded, so the "cache" path is exec-with-warm-kernels rather than + # a separate runtime. + forward = _make_inlined_forward(python_code) + + return PrecompiledModule._from_loaded(forward, backend=backend) + + +precompile = _PrecompileApi() +# ``torch.compiler.precompile`` is a callable instance, not a function, so give it the +# name/doc introspection (Sphinx autosummary, help(), IDEs) expects to find on a +# public callable; the rich usage docs live on ``__call__``. +precompile.__name__ = "precompile" # type: ignore[attr-defined] +precompile.__qualname__ = "precompile" # type: ignore[attr-defined] +precompile.__doc__ = _PrecompileApi.__call__.__doc__ + +# Both are public under torch.compiler.precompile, so report their module/qualname there +# (mirroring the singleton fixup above) -- otherwise Sphinx autoexception/autofunction +# would anchor them under this private module. load is a bound method; patch the +# underlying function so introspection on precompile.load reports torch.compiler too. +PrecompileError.__module__ = "torch.compiler" +PrecompileError.__qualname__ = "precompile.PrecompileError" +_PrecompileApi.load.__module__ = "torch.compiler" +_PrecompileApi.load.__qualname__ = "precompile.load" diff --git a/.venv/lib/python3.12/site-packages/torch/_precompile_driver.py b/.venv/lib/python3.12/site-packages/torch/_precompile_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..109658a619385852892d3a52412f4c9781f64958 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_precompile_driver.py @@ -0,0 +1,368 @@ +"""Runtime driver for torch.compiler.precompile artifacts, authored as real code. + +Nothing here is imported or run by torch at runtime, and the generated artifacts never +import this module. Instead torch._precompile emits these function bodies VERBATIM (via +inspect.getsource, on the to_python_code / emit path only) into the self-contained +python_code string, after the calling-convention metadata and the compiled/captured +graph. Authoring the driver as real code -- instead of a hand-written string literal -- +lets pyrefly / ruff / IDEs type-check and navigate the load-bearing driver logic that +would otherwise be invisible inside a string (and drops the wall of ``# noqa: F821``). + +Keeping python_code self-contained and version-frozen (its behavior is hashed via +code_hash, invariant 7) still holds: the artifact carries the driver TEXT, it does not +import it, so there is no torch-version skew. The emit path runs getsource in-process +where torch source is present; load() never touches this module. + +The names the emitted bodies read from the artifact's own namespace -- the metadata +constants, the ``_torch`` / ``_pytree`` import aliases, and the graph's ``call`` -- are +declared under TYPE_CHECKING below so the bodies type-check here; at emit time they +resolve against the metadata + graph sections that precede the driver in python_code. + +INVARIANT: ``_extract_param_buffers`` reproduces +``torch._precompile._intern_param_buffers``'s params-then-buffers, intern-by-identity +ordering VERBATIM; the two must stay in sync (see Note [precompile programming model]). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch as _torch +import torch.utils._pytree as _pytree + + +if TYPE_CHECKING: + # Calling-convention metadata the emitted driver reads from the artifact namespace, + # where torch._precompile._build_metadata_section emits each as a literal assignment + # ahead of the driver. Bound here with placeholder values (not bare annotations) so + # static tools treat them as real names in the bodies below; this block is not emitted. + MODULE_POSITIONS: list[int] = [] + NUM_POSITIONAL_ARGS: int = 0 + PARAM_NAMES: list[str] = [] + BUFFER_NAMES: list[str] = [] + PARAM_SHAPES: list[tuple[int, ...]] = [] + BUFFER_SHAPES: list[tuple[int, ...]] = [] + PARAM_DTYPES: list[str] = [] + BUFFER_DTYPES: list[str] = [] + PARAM_DEVICES: list[str] = [] + BUFFER_DEVICES: list[str] = [] + GRAD_PARAM_INDICES: list[int] = [] + IN_SPEC: str | None = None + OUT_SPEC: str = "" + USER_INPUT_SHAPES: list[tuple[int | None, ...] | None] = [] + USER_INPUT_DTYPES: list[str | None] = [] + USER_INPUT_DEVICES: list[str | None] = [] + USER_INPUT_BOUNDS: list[dict[int, tuple[int | None, int | None]] | None] = [] + + # The compiled/captured graph's entry point, emitted before the driver. + def call(flat_inputs: list[object]) -> list[object]: ... + + +def _extract_param_buffers(mods): + """Lift the runtime modules' params then buffers, interning by identity, in the + same order as capture, so the list lines up with the compiled/captured graph. Returns + (pb, names) where names mirrors PARAM_NAMES + BUFFER_NAMES. This ordering AND the + naming must match torch._precompile._intern_param_buffers verbatim (its INVARIANT).""" + multi = len(mods) > 1 + seen = set() + pb = [] + names = [] + + def intern(mi, n, t): + if id(t) not in seen: + seen.add(id(t)) + pb.append(t) + names.append(f"m{mi}.{n}" if multi else n) + + for mi, m in enumerate(mods): + for n, p in m.named_parameters(remove_duplicate=False): + intern(mi, n, p) + for mi, m in enumerate(mods): + for n, b in m.named_buffers(remove_duplicate=False): + intern(mi, n, b) + return pb, names + + +def _fail(msg): + # Imported lazily (only when a guard fails) so a normal run does not couple the + # standalone artifact to torch._precompile's import surface. + from torch._precompile import PrecompileError as _PrecompileError + + raise _PrecompileError(msg) + + +def _check_structure(pb, names): + # Verify the runtime model's extracted param/buffer NAMES match the baked + # PARAM_NAMES + BUFFER_NAMES (count AND order/identity), so a reordered or + # structurally-drifted same-count model is caught precisely (invariant 2) rather + # than scattering grads onto the wrong slot. Then check each tensor's SHAPE, DTYPE and + # DEVICE against the baked example: the graph is specialized to the example shapes and + # can bake a device literal, so a same-named but differently shaped/typed/placed + # runtime tensor would silently miscompute or fail deep in a kernel. + expected = list(PARAM_NAMES) + list(BUFFER_NAMES) + if names != expected: + _fail( + f"precompile: the runtime model's param/buffer names {names!r} do not match " + f"the traced model's {expected!r}; the runtime model must be structurally " + f"identical to the traced model (invariant 2)." + ) + expected_shapes = list(PARAM_SHAPES) + list(BUFFER_SHAPES) + expected_dtypes = list(PARAM_DTYPES) + list(BUFFER_DTYPES) + expected_devices = list(PARAM_DEVICES) + list(BUFFER_DEVICES) + for _nm, _t, _shp, _dt, _dev in zip( + names, pb, expected_shapes, expected_dtypes, expected_devices + ): + if tuple(_t.shape) != tuple(_shp): + _fail( + f"precompile: the runtime param/buffer {_nm!r} has shape " + f"{tuple(_t.shape)} but the traced model's was {tuple(_shp)}; the runtime " + f"model must be structurally identical to the traced model (invariant 2)." + ) + if str(_t.dtype) != _dt: + _fail( + f"precompile: the runtime param/buffer {_nm!r} has dtype {_t.dtype} but " + f"the traced model's was {_dt}; the runtime model must be structurally " + f"identical to the traced model (invariant 2)." + ) + if str(_t.device) != _dev: + _fail( + f"precompile: the runtime param/buffer {_nm!r} is on device {_t.device} " + f"but the traced model's was {_dev}; the runtime model must be " + f"structurally identical to the traced model (invariant 2)." + ) + + +def _eager_forward(*args): + """Run the captured ATen graph eagerly. Pass the same args the traced fn took -- + the module(s) in the same positions plus the runtime inputs. The module(s) must + be structurally identical to the ones precompile traced (same param/buffer order + and tying); only the weight values may differ. + + The eager backend runs the graph as captured: inputs (including tensor + subclasses) are passed through unchanged (no dense flatten/unflatten), and the + graph's flat outputs are reassembled into fn's output structure. If fn ran a + backward, the trailing grad outputs (one per GRAD_PARAM_INDICES entry) are + parameter grads, scattered (accumulated) onto the params that received one like + eager .backward() -- frozen / non-contributing params keep .grad = None.""" + if len(args) != NUM_POSITIONAL_ARGS: + _fail( + f"precompile: expected {NUM_POSITIONAL_ARGS} positional args (the same as " + f"the traced fn), got {len(args)} (invariant 2)." + ) + mods = [] + for _i in MODULE_POSITIONS: + if not isinstance(args[_i], _torch.nn.Module): + _fail( + f"precompile: argument at position {_i} must be the nn.Module the traced " + f"fn took (invariant 2), got {type(args[_i]).__name__}." + ) + mods.append(args[_i]) + user_inputs = [a for i, a in enumerate(args) if i not in set(MODULE_POSITIONS)] + user_flat, _runtime_in_spec = _pytree.tree_flatten(tuple(user_inputs)) + if IN_SPEC is not None and _runtime_in_spec != _pytree.treespec_loads(IN_SPEC): + _fail( + "precompile: runtime inputs have a different structure than the traced " + "example inputs (invariant 3); they must match in nesting and count." + ) + # Reject a SHAPE / DTYPE / DEVICE mismatch (invariants 3 and 6) up front. Mirrors the + # inductor driver checks (keep the two drivers in sync). The eager backend has no + # assert_size_stride, so only these are checked (layout-flexible). The eager backend + # rejects mark_unbacked up front, so every dim here is static and USER_INPUT_BOUNDS is + # always all-None; there is no bounds branch (it would be dead code). USER_INPUT_BOUNDS + # is still emitted in the metadata for the inductor driver, so it is not consumed here. + if len(user_flat) != len(USER_INPUT_SHAPES): + _fail( + "precompile: runtime inputs flattened to a different number of leaves than " + "the traced example (invariant 3); they must match the traced structure." + ) + for _t, _shp, _dt, _dev in zip( + user_flat, USER_INPUT_SHAPES, USER_INPUT_DTYPES, USER_INPUT_DEVICES + ): + if _shp is None or not isinstance(_t, _torch.Tensor): + continue + _act = tuple(_t.shape) + if len(_act) != len(_shp) or any(a != e for a, e in zip(_act, _shp)): + _fail( + f"precompile: a runtime input has shape {_act} but the artifact was " + f"traced with shape {tuple(_shp)}; the graph is specialized to the static " + f"dims (invariant 3). Retrace for this shape, or use backend='eager'." + ) + if _dt is not None and str(_t.dtype) != _dt: + _fail( + f"precompile: a runtime input has dtype {_t.dtype} but the artifact was " + f"traced with dtype {_dt}; the graph is specialized to the example dtype " + f"(invariant 6). Cast the input to the traced dtype, or retrace." + ) + if _dev is not None and str(_t.device) != _dev: + _fail( + f"precompile: a runtime input is on device {_t.device} but the artifact " + f"was traced on device {_dev}; the graph is specialized to the example " + f"device (invariant 6). Move the input to the traced device, or retrace." + ) + pb, _names = _extract_param_buffers(mods) + _check_structure(pb, _names) + with _torch.no_grad(): + out = list(call([*pb, *user_flat])) + if GRAD_PARAM_INDICES: + n = len(GRAD_PARAM_INDICES) + grads = out[len(out) - n :] + out = out[: len(out) - n] + for idx, g in zip(GRAD_PARAM_INDICES, grads): + p = pb[idx] + if p.grad is None: + p.grad = g + else: + p.grad.add_(g) + return _pytree.tree_unflatten(out, _pytree.treespec_loads(OUT_SPEC)) + + +def _inductor_forward(*args): + """Run the compiled computation. Pass the same args the traced fn took -- the + module(s) in the same positions plus the runtime inputs. The module(s) must be + structurally identical to the ones precompile traced (same param/buffer order + and tying); only the weight values may differ. + + Module params/buffers are extracted (no weights are baked into the artifact) and, + together with the runtime inputs, passed to the composed ``call`` -- which is the + AOTAutograd+Inductor graph with its own prelude/epilogue, so it handles tensor- + subclass wrap/unwrap and input mutation (e.g. BatchNorm running stats) internally + and disables grad itself. If fn ran a backward, the trailing grad outputs (one per + GRAD_PARAM_INDICES entry) are parameter grads: they are scattered (accumulated) + onto the params that received one, mirroring eager .backward() (frozen / + non-contributing params keep .grad = None), and the artifact returns fn's own + result. Nothing here reads an external cache: the kernels JIT-compile from the + inlined source on first call. A runtime input whose shape, dtype, or device differs + from the traced example is rejected up front (invariants 3 and 6), and a differing + stride / memory format is rejected via the inlined assert_size_stride (invariant 6); + use backend="eager" for layout-flexible execution.""" + if len(args) != NUM_POSITIONAL_ARGS: + _fail( + f"precompile: expected {NUM_POSITIONAL_ARGS} positional args (the same as " + f"the traced fn), got {len(args)} (invariant 2)." + ) + mods = [] + for _i in MODULE_POSITIONS: + if not isinstance(args[_i], _torch.nn.Module): + _fail( + f"precompile: argument at position {_i} must be the nn.Module the traced " + f"fn took (invariant 2), got {type(args[_i]).__name__}." + ) + mods.append(args[_i]) + user_inputs = [a for i, a in enumerate(args) if i not in set(MODULE_POSITIONS)] + user_flat, _runtime_in_spec = _pytree.tree_flatten(tuple(user_inputs)) + if IN_SPEC is not None and _runtime_in_spec != _pytree.treespec_loads(IN_SPEC): + _fail( + "precompile: runtime inputs have a different structure than the traced " + "example inputs (invariant 3); they must match in nesting and count." + ) + # Reject a SHAPE / DTYPE / DEVICE / BOUNDS mismatch (invariants 3 and 6) up front. + # Mirrors the eager driver checks (keep the two drivers in sync). Stride/memory-format + # is enforced by the inlined assert_size_stride (pinned at capture). + if len(user_flat) != len(USER_INPUT_SHAPES): + _fail( + "precompile: runtime inputs flattened to a different number of leaves than " + "the traced example (invariant 3); they must match the traced structure." + ) + for _t, _shp, _dt, _dev, _bnd in zip( + user_flat, + USER_INPUT_SHAPES, + USER_INPUT_DTYPES, + USER_INPUT_DEVICES, + USER_INPUT_BOUNDS, + ): + if _shp is None or not isinstance(_t, _torch.Tensor): + continue + # A dim recorded as None was captured dynamic (unbacked); any size is valid. + _act = tuple(_t.shape) + if len(_act) != len(_shp) or any( + e is not None and a != e for a, e in zip(_act, _shp) + ): + _fail( + f"precompile: a runtime input has shape {_act} but the artifact was " + f"traced with shape {tuple(_shp)} (None = a dynamic dim, any size); the " + f"graph is specialized to the static dims (invariant 3). Retrace, mark " + f"the dim dynamic via mark_unbacked, or use backend='eager'." + ) + if _dt is not None and str(_t.dtype) != _dt: + _fail( + f"precompile: a runtime input has dtype {_t.dtype} but the artifact was " + f"traced with dtype {_dt}; the graph is specialized to the example dtype " + f"(invariant 6). Cast the input to the traced dtype, or retrace." + ) + if _dev is not None and str(_t.device) != _dev: + _fail( + f"precompile: a runtime input is on device {str(_t.device)!r} but the " + f"artifact was traced on device {_dev!r}; the graph is specialized to the " + f"example device (invariant 6). Move the input to the traced device, or " + f"retrace." + ) + if _bnd is not None: + for _d, (_lo, _hi) in _bnd.items(): + _sz = _t.shape[_d] + if _lo is not None and _sz < _lo: + _fail( + f"precompile: runtime input dim {_d} has size {_sz} but " + f"mark_unbacked declared min={_lo} (invariant 3)." + ) + if _hi is not None and _sz > _hi: + _fail( + f"precompile: runtime input dim {_d} has size {_sz} but " + f"mark_unbacked declared max={_hi} (invariant 3)." + ) + pb, _names = _extract_param_buffers(mods) + _check_structure(pb, _names) + try: + out = list(call([*pb, *user_flat])) + except AssertionError as _e: + # Only relabel inductor's own assert_size_stride failure (a stride/memory-format + # mismatch, or a size mismatch on an unbacked dim the static check above cannot + # pre-validate; invariants 3 and 6). assert_size_stride raises one of two messages + # -- "expected size A==B, stride C==D at dim=N" or "wrong number of dimensions" -- + # so match those. Any OTHER AssertionError (a user torch._assert, an internal + # inductor invariant) is re-raised unchanged so its real message is not mislabeled. + _m = str(_e) + if not ( + ("expected size" in _m and "stride" in _m) + or "wrong number of dimensions" in _m + ): + raise + # When the artifact has dynamic (None) user-input dims, an "expected size" + # assert_size_stride failure on a dynamic dim most likely means two inputs that + # share a mark_unbacked shape_id (bound to ONE symbol, hence equal by + # construction) were called with mismatched sizes. Call that out so the message + # is not misleadingly only about memory format. + _has_dynamic = any( + _s is not None and any(_d is None for _d in _s) for _s in USER_INPUT_SHAPES + ) + _shape_id_note = "" + if _has_dynamic and "expected size" in _m: + _shape_id_note = ( + " If two inputs share a mark_unbacked shape_id, their marked dims are " + "bound to one symbol and so MUST have equal sizes at runtime; this can " + "also be a shape_id equality violation." + ) + _fail( + f"precompile: a runtime tensor's shape or memory format differs from the " + f"traced example; the inductor backend specializes on input shape and memory " + f"format (invariants 3 and 6). The mismatch can be a user INPUT or a model " + f"PARAMETER/BUFFER whose layout (memory format) differs from the example " + f"weight, since the inductor backend also bakes each param/buffer's layout. " + f"Pass the model/inputs in the example's shape and layout (.contiguous() to " + f"match a contiguous example, or match the example weight's layout), or use " + f"backend='eager'.{_shape_id_note} Underlying: {_e}" + ) + # Unreachable: _fail always raises. The bare re-raise keeps `out` provably bound + # for static tools (which do not model _fail as NoReturn) and re-raises the + # original assert if _fail were ever changed to return. + raise + if GRAD_PARAM_INDICES: + n = len(GRAD_PARAM_INDICES) + grads = out[len(out) - n :] + out = out[: len(out) - n] + for idx, g in zip(GRAD_PARAM_INDICES, grads): + p = pb[idx] + if p.grad is None: + p.grad = g + else: + p.grad.add_(g) + return _pytree.tree_unflatten(out, _pytree.treespec_loads(OUT_SPEC)) diff --git a/.venv/lib/python3.12/site-packages/torch/_prims/__init__.py b/.venv/lib/python3.12/site-packages/torch/_prims/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef2e61bce1fce8546c32b2d44349a86be2538b97 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_prims/__init__.py @@ -0,0 +1,3064 @@ +# mypy: allow-untyped-defs +import operator +from collections.abc import Callable, Sequence +from enum import Enum +from functools import partial, reduce +from typing import Optional, Union + +import torch +import torch._prims_common as utils +import torch.library +from torch import sym_float, Tensor +from torch._C import _get_default_device +from torch._higher_order_ops.effects import new_token_tensor +from torch._library.utils import is_functional_schema +from torch._prims.debug_prims import register_debug_prims +from torch._prims.rng_prims import register_rng_prims +from torch._prims_common import ( + Dim, + DimsSequenceType, + DimsType, + IntLike, + Number, + NumberType, + RETURN_TYPE, + ShapeType, + StrideType, + TensorLike, + TensorLikeType, + type_to_dtype, +) +from torch._prims_common.wrappers import backwards_not_supported +from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode +from torch.overrides import handle_torch_function, has_torch_function +from torch.utils._pytree import tree_flatten, tree_map, tree_unflatten + + +prim = torch.library.Library("prims", "DEF") +prim_impl = torch.library.Library("prims", "IMPL", "CompositeExplicitAutograd") +prim_backend_select_impl = torch.library.Library("prims", "IMPL", "BackendSelect") +prim_autograd_impl = torch.library.Library("prims", "IMPL", "Autograd") +prim_meta_impl = torch.library.Library("prims", "IMPL", "Meta") + +# Experimental module containing prototype "primitive" operations. + +__all__ = [ + # + # Common datastructures and helpers + # + "RETURN_TYPE", + # + # Elementwise unary prims + # + "abs", + "acos", + "acosh", + "asin", + "asinh", + "atan", + "atanh", + "cos", + "cosh", + "bessel_i0", + "bessel_i0e", + "bessel_i1", + "bessel_i1e", + "bessel_j0", + "bessel_j1", + "bitwise_not", + "cbrt", + "ceil", + "conj_physical", + "digamma", + "erf", + "erf_inv", + "erfc", + "erfcx", + "exp", + "expm1", + "exp2", + "fill", + "floor", + "imag", + "isfinite", + "lgamma", + "log", + "log1p", + "log2", + "log10", + "ndtri", + "neg", + "real", + "reciprocal", + "round", + "sign", + "signbit", + "sin", + "sinh", + "spherical_bessel_j0", + "sqrt", + "tan", + "tanh", + "trunc", + # + # Elementwise binary prims + # + "add", + "atan2", + "bitwise_and", + "bitwise_or", + "bitwise_xor", + # 'complex', # needs custom meta + "div", + "eq", + "fmax", + "fmin", + "fmod", + "frexp", + "gcd", + "ge", + "gt", + "hypot", + "igamma", + "igammac", + "le", + "lt", + "maximum", + "minimum", + "mul", + "ne", + "nextafter", + "pow", + "remainder", + "rsqrt", + "shift_left", + "shift_right_arithmetic", + "shift_right_logical", # not implemented + "sub", + "zeta", + # + # View prims + # + "as_strided", + "broadcast_in_dim", + "collapse_view", + "conj", + "expand_dims", + # pyrefly: ignore [bad-dunder-all] + "slice", + "split_dim", + "squeeze", + "transpose", + "view_of", + "view_element_type", + # + # Functionalized view mutations + # + "as_strided_scatter", + # + # Shape prims + # + "collapse", + "cat", + "reshape", + "rev", + # + # Conditional prims + # + "where", + # + # Data conversion and movement prims + # + "clone", + "convert_element_type", + "device_put", + "item", + "maximum_value", + "minimum_value", + "copy_strided", + # + # Inplace prims + # + "copy_to", + "resize", + # "_set", # Commented out, see note below + # + # Reduction prims + # + "amax", + "amin", + "prod", + "sum", + "xor_sum", + "var", + # + # Tensor Creation Prims + # + "empty_strided", + "empty_permuted", + "scalar_tensor", + "iota", + # + # Linear algebra (linalg) Prims + # + "svd", + # + # Randomness Prims + # + "normal", + "_uniform_helper", + # + # FFT prims + # + "fft_r2c", + "fft_c2c", + "fft_c2r", + # + # prims for making/sinking tokens + # + "_make_token", + "_sink_tokens", +] + + +def TensorMeta( + tensorlike: NumberType | torch.Tensor | None = None, + *, + shape: ShapeType | None = None, + strides: StrideType | None = None, + dtype: torch.dtype | None = None, + device: torch.device | str | None = None, +): + if isinstance(tensorlike, Number): + if shape and not isinstance(shape, Sequence): + raise AssertionError( + f"shape must be None or a Sequence for Number input, got {type(shape)}" + ) + if strides and not isinstance(strides, Sequence): + raise AssertionError( + f"strides must be None or a Sequence for Number input, got {type(strides)}" + ) + inferred_shape: tuple[int, ...] = () + inferred_strides: tuple[int, ...] = () + inferred_dtype = type_to_dtype(type(tensorlike)) + inferred_device = torch.device("cpu") + # TODO: This looks wrong, a number that is wrapped into a tensor + # needs to behave differently than a scalar tensor for type + # promotion purposes + elif tensorlike is not None: + if not isinstance(tensorlike, torch.Tensor): + raise AssertionError( + f"tensorlike must be torch.Tensor, got {type(tensorlike)}" + ) # mypy + inferred_shape = tuple(tensorlike.shape) + inferred_strides = tuple(tensorlike.stride()) + inferred_dtype = tensorlike.dtype + inferred_device = tensorlike.device + else: + # If no tensorlike "example" is given then all metadata + # must be provided explicitly + if shape is None: + raise AssertionError("shape must be provided when tensorlike is None") + if strides is None: + raise AssertionError("strides must be provided when tensorlike is None") + if dtype is None: + raise AssertionError("dtype must be provided when tensorlike is None") + if device is None: + raise AssertionError("device must be provided when tensorlike is None") + + shape = inferred_shape if shape is None else tuple(shape) # type: ignore[possibly-undefined] + strides = inferred_strides if strides is None else tuple(strides) # type: ignore[possibly-undefined] + dtype = inferred_dtype if dtype is None else dtype # type: ignore[possibly-undefined] + device = inferred_device if device is None else device # type: ignore[possibly-undefined] + + if isinstance(device, str): + device = torch.device(device) + + return torch.empty_strided(shape, strides, dtype=dtype, device=device) + + +def _make_prim( + *, + schema: str, + return_type: RETURN_TYPE | tuple[RETURN_TYPE, ...], + meta: Callable, + impl_aten: Callable, + doc: str, + tags: Sequence[torch.Tag] | None = None, + use_old_custom_ops_api: bool = False, + register_conj_neg_fallthrough: bool = False, +): + """ + Creates a primitive operation. + + """ + + def _prim_impl(*args, **kwargs): + # always run the meta function because aten implementation will + # typically accept more inputs (e.g., it will do promotion and + # broadcasting) which we want to reject + meta(*args, **kwargs) + return impl_aten(*args, **kwargs) + + # Right now prims don't support autograd (we can and should add an + # argument that provides an implementation for backward here.) Because we + # don't have derivative formulas, we must setup a custom autograd function + # that raises an error if backwards is invoked + def _autograd_impl(*args, **kwargs): + return backwards_not_supported(_prim)(*args, **kwargs) + + def _backend_select_impl(*args, **kwargs): + if kwargs.get("device") and kwargs["device"].type == "meta": + return meta(*args, **kwargs) + if any(isinstance(x, torch.device) and x.type == "meta" for x in args): + return meta(*args, **kwargs) + else: + return _prim_impl(*args, **kwargs) + + name = schema.split("(", maxsplit=1)[0] + schema = schema[len(name) :] + + # register non-functional ops with old custom ops API + cpp_schema = torch._C.parse_schema(name + schema) + if use_old_custom_ops_api or not is_functional_schema(cpp_schema): + prim.define(name + schema, tags=torch.Tag.pt2_compliant_tag) + prim_impl.impl(name, _prim_impl) + prim_autograd_impl.impl(name, _autograd_impl) + prim_meta_impl.impl(name, meta) + else: + mutates_args = [ + arg.name + for arg in cpp_schema.arguments + if arg.alias_info is not None and arg.alias_info.is_write + ] + prim_def = torch.library.custom_op( + "prims::" + name, + _prim_impl, + mutates_args=tuple(mutates_args), + schema=schema, + ) + prim_def.register_fake(meta) + + # all view ops get conj/neg fallthroughs + if return_type == RETURN_TYPE.VIEW or register_conj_neg_fallthrough: + prim_def._lib.impl(name, torch.library.fallthrough_kernel, "Conjugate") + prim_def._lib.impl(name, torch.library.fallthrough_kernel, "Negative") + + _prim_packet = getattr(torch._ops.ops.prims, name) + _prim = _prim_packet.default + if tags: + _prim._tags = tags + elif aten_packet := getattr(torch.ops.aten, name, None): + overload_tags = [overload.tags for overload in aten_packet.op_overloads()] + tags_intersection = set(overload_tags[0]) + tags_intersection.intersection_update(*overload_tags[1:]) + + # don't inadvertently add to prim ops + tags_intersection.discard(torch.Tag.core) + # causes errors with python ref executor tests, none of the + # data dependent pytorch ops actually decompose to prims + tags_intersection.discard(torch.Tag.data_dependent_output) + + # iter over first tags for determinism + _prim._tags = tuple(t for t in overload_tags[0] if t in tags_intersection) + + from torch._subclasses.fake_tensor import contains_tensor_types + + if ( + not any(contains_tensor_types(a.type) for a in _prim._schema.arguments) + or str( + _prim + # See https://github.com/pytorch/pytorch/issues/103532 + ) + == "prims.device_put.default" + ): + prim_backend_select_impl.impl(name, _backend_select_impl) + + for p in (_prim_packet, _prim): + p.__doc__ = doc + p.return_type = return_type # type: ignore[attr-defined] + + p.schema = schema + p.prim_impl = _prim_impl + p.prim_meta_impl = meta + p.impl_aten = impl_aten + + torch._C._fake_dispatch_register_prim_meta( + _prim._schema.name, _prim._schema.overload_name + ) + + return _prim + + +class ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND(Enum): + DEFAULT = (0,) + INT_TO_FLOAT = (2,) + ALWAYS_BOOL = (3,) + COMPLEX_TO_FLOAT = (4,) + + +# TODO: implement dtype validation here, too, or on the corresponding refs +def _prim_elementwise_meta( + *args, + type_promotion: ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND, + args_with_fixed_dtypes: tuple[TensorLikeType, ...] | None = None, +) -> FakeTensor: + """ + Meta function for elementwise operations that produce outputs in the same dtype + as their inputs. + + Stride logic is currently incorrect. + """ + + if len(args) == 0: + raise AssertionError("elementwise operation requires at least one argument") + + utils.check_same_dtype(*args) + + args_ = list(args) + if args_with_fixed_dtypes is not None: + args_ = list(args_with_fixed_dtypes) + args_ + + utils.check_same_device(*args_, allow_cpu_scalar_tensors=True) + utils.check_same_shape(*args_, allow_cpu_scalar_tensors=True) + + l2p_perm, _ = utils.compute_elementwise_output_logical_to_physical_perm(*args_) + shape = utils.extract_shape(*args_, allow_cpu_scalar_tensors=True) + + # Acquires the dtype + dtype = None + scalar_type = None + for arg in args: + if isinstance(arg, TensorLike): + if not utils.is_cpu_scalar_tensor(arg): + dtype = arg.dtype + break + else: + dtype = arg.dtype + elif isinstance(arg, Number): + scalar_type = type(arg) + + if dtype is None and scalar_type is not None: + dtype = utils.type_to_dtype(scalar_type) + + # Acquires the device (if it exists) or number + device = None + number = None + # pyrefly: ignore [bad-assignment] + for arg in args_: + if isinstance(arg, TensorLike): + if utils.is_cpu_scalar_tensor(arg): + if device is None: + device = arg.device + # keep going, in case there is a cuda tensor later + else: + device = arg.device + break + + elif isinstance(arg, Number): + if number is None: + number = arg + + # NOTE: type promotion behavior here is mostly hidden from tests because + # references will typically handle the type promotion properly even if this doesn't + # (but getting it wrong will cause too many casts to be inserted in traces!) + if device is not None: + if dtype is None: + raise AssertionError("dtype must not be None when device is not None") + if type_promotion == ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.ALWAYS_BOOL: + dtype = torch.bool + elif type_promotion == ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.INT_TO_FLOAT: + if utils.is_integer_dtype(dtype) or utils.is_boolean_dtype(dtype): + dtype = torch.get_default_dtype() + elif type_promotion == ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT: + if utils.is_complex_dtype(dtype): + dtype = utils.corresponding_real_dtype(dtype) + + if shape is None: + raise AssertionError("shape must not be None when device is not None") + return torch.empty_permuted(shape, l2p_perm, device=device, dtype=dtype) # type: ignore[return-value] + + # Number case + # TODO: fix number type promotion (bool, complex->float) + + # For now for symint/float, just implementing the common / simple cases of (int,float,symint,symfloat) + seen_float = False + if isinstance(number, (torch.SymInt, torch.SymFloat)): + for a in args: + if not isinstance(a, (int, float, torch.SymInt, torch.SymFloat)): + raise AssertionError( + f"Expected int, float, SymInt, or SymFloat, got {type(a)}" + ) + seen_float = seen_float or isinstance(a, (float, torch.SymFloat)) + if seen_float: + number = sym_float(number) + + return TensorMeta(number) # type: ignore[arg-type] + + +def _complex_only_elementwise_meta(*args, **kwargs): + torch._check( + utils.is_complex_dtype(args[0].dtype), lambda: "Only complex dtype is supported" + ) + return _prim_elementwise_meta(*args, **kwargs) + + +def _make_elementwise_unary_prim( + name: str, *, type_promotion: ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND, **kwargs +): + """ + Creates an elementwise unary prim. + """ + + return _make_prim( + schema=f"{name}(Tensor self) -> Tensor", + meta=partial(_prim_elementwise_meta, type_promotion=type_promotion), + return_type=RETURN_TYPE.NEW, + **kwargs, + ) + + +def _make_elementwise_binary_prim( + name: str, *, type_promotion: ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND, **kwargs +): + """ + Creates an elementwise binary prim. + """ + + return _make_prim( + schema=f"{name}(Tensor self, Tensor other) -> Tensor", + meta=partial(_prim_elementwise_meta, type_promotion=type_promotion), + return_type=RETURN_TYPE.NEW, + **kwargs, + ) + + +def _not_impl(*args, **kwargs): + raise NotImplementedError + + +# +# Elementwise unary operations +# + + +abs = _make_elementwise_unary_prim( + "abs", + impl_aten=torch.abs, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT, +) + +acos = _make_elementwise_unary_prim( + "acos", + impl_aten=torch.acos, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +acosh = _make_elementwise_unary_prim( + "acosh", + impl_aten=torch.acosh, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +asin = _make_elementwise_unary_prim( + "asin", + impl_aten=torch.asin, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +asinh = _make_elementwise_unary_prim( + "asinh", + impl_aten=torch.asinh, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +atan = _make_elementwise_unary_prim( + "atan", + impl_aten=torch.atan, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +atanh = _make_elementwise_unary_prim( + "atanh", + impl_aten=torch.atanh, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +cos = _make_elementwise_unary_prim( + "cos", + impl_aten=torch.cos, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +cosh = _make_elementwise_unary_prim( + "cosh", + impl_aten=torch.cosh, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +bessel_j0 = _make_elementwise_unary_prim( + "bessel_j0", + impl_aten=torch.special.bessel_j0, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +bessel_j1 = _make_elementwise_unary_prim( + "bessel_j1", + impl_aten=torch.special.bessel_j1, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +bessel_i0 = _make_elementwise_unary_prim( + "bessel_i0", + impl_aten=torch.i0, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +bessel_i0e = _make_elementwise_unary_prim( + "bessel_i0e", + impl_aten=torch.special.i0e, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +bessel_i1 = _make_elementwise_unary_prim( + "bessel_i1", + impl_aten=torch.special.i1, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +bessel_i1e = _make_elementwise_unary_prim( + "bessel_i1e", + impl_aten=torch.special.i1e, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +bitwise_not = _make_elementwise_unary_prim( + "bitwise_not", + impl_aten=torch.bitwise_not, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + + +def _cbrt_aten(a: torch.Tensor) -> Tensor: + torch._check( + not a.is_complex(), + lambda: "cbrt: Complex inputs not supported. Consider calling torch.pow(a, 1.0/3.0)", + ) + # Returns the real cubic root of the number. + # Note that if a < 0, pow(a, (1. / 3.)) returns the complex number + # exp(1/3 * log(a)) = exp(1/3 * (log(abs(a)) + pi*i)) = cbrt(abs(a)) * e^{pi/3*i} + # which is a complex number. + # For more info see the section Note in + # https://en.cppreference.com/w/cpp/numeric/math/cbrt + return torch.copysign(torch.pow(a.abs(), 1 / 3), a) + + +cbrt = _make_elementwise_unary_prim( + "cbrt", + impl_aten=_cbrt_aten, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +ceil = _make_elementwise_unary_prim( + "ceil", + impl_aten=torch.ceil, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + + +def _conj_physical_meta(input: TensorLikeType) -> TensorLikeType: + if not input.dtype.is_complex: + raise RuntimeError("prims.conj_physical is only defined for complex dtypes") + + strides = utils.compute_elementwise_output_strides(input) + return TensorMeta(input, strides=strides) + + +conj_physical = _make_prim( + schema="conj_physical(Tensor self) -> Tensor", + meta=_conj_physical_meta, + impl_aten=torch._conj_physical, + doc="Returns the physical conjugation of a complex tensor", + return_type=RETURN_TYPE.NEW, +) + + +def _clone_meta( + input: TensorLikeType, *, memory_format: torch.memory_format = torch.preserve_format +) -> TensorLikeType: + if memory_format != torch.preserve_format: + return torch.empty( + input.shape, + dtype=input.dtype, + layout=input.layout, + device=input.device, + memory_format=memory_format, + ) + else: + # Match eager behavior by preserving strides for non_overlapping_and_dense tensors + # If not, eager clone creates contiguous strides + computed_stride = utils.compute_elementwise_output_strides(input) + return torch.empty_strided( + input.shape, + computed_stride, + dtype=input.dtype, + layout=input.layout, + device=input.device, + ) + + +clone = _make_prim( + schema="clone(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor", + meta=_clone_meta, + impl_aten=torch.clone, + doc="Returns the copy of a tensor", + return_type=RETURN_TYPE.NEW, + register_conj_neg_fallthrough=True, +) + +digamma = _make_elementwise_unary_prim( + "digamma", + impl_aten=torch.digamma, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +erf = _make_elementwise_unary_prim( + "erf", + impl_aten=torch.erf, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +erf_inv = _make_elementwise_unary_prim( + "erf_inv", + impl_aten=torch.special.erfinv, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +erfc = _make_elementwise_unary_prim( + "erfc", + impl_aten=torch.special.erfc, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +erfcx = _make_elementwise_unary_prim( + "erfcx", + impl_aten=torch.special.erfcx, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +exp = _make_elementwise_unary_prim( + "exp", + impl_aten=torch.exp, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +expm1 = _make_elementwise_unary_prim( + "expm1", + impl_aten=torch.special.expm1, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +exp2 = _make_elementwise_unary_prim( + "exp2", + impl_aten=torch.special.exp2, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + + +def _fill_meta(a: TensorLikeType, value: NumberType) -> TensorLikeType: + return _prim_elementwise_meta( + a, type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT + ) + + +# NOTE: fill uses _make_prim directly because it has a value parameter +fill = _make_prim( + schema="fill(Tensor self, Scalar value) -> Tensor", + return_type=RETURN_TYPE.NEW, + meta=_fill_meta, + impl_aten=torch.fill, + doc="", +) + +floor = _make_elementwise_unary_prim( + "floor", + impl_aten=torch.floor, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +imag = _make_prim( + schema="imag(Tensor(a) self) -> Tensor(a)", + meta=partial( + _complex_only_elementwise_meta, + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT, + ), + return_type=RETURN_TYPE.VIEW, + impl_aten=torch.imag, + doc="", +) + +isfinite = _make_elementwise_unary_prim( + "isfinite", + impl_aten=torch.isfinite, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) + +lgamma = _make_elementwise_unary_prim( + "lgamma", + impl_aten=torch.lgamma, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +log = _make_elementwise_unary_prim( + "log", + impl_aten=torch.log, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +log1p = _make_elementwise_unary_prim( + "log1p", + impl_aten=torch.log1p, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +log2 = _make_elementwise_unary_prim( + "log2", + impl_aten=torch.log2, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +log10 = _make_elementwise_unary_prim( + "log10", + impl_aten=torch.log10, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +real = _make_prim( + schema="real(Tensor(a) self) -> Tensor(a)", + meta=partial( + _complex_only_elementwise_meta, + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT, + ), + return_type=RETURN_TYPE.VIEW, + impl_aten=torch.real, + doc="", +) + +reciprocal = _make_elementwise_unary_prim( + "reciprocal", + impl_aten=torch.reciprocal, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +ndtri = _make_elementwise_unary_prim( + "ndtri", + impl_aten=torch.special.ndtri, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +neg = _make_elementwise_unary_prim( + "neg", + impl_aten=torch.neg, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +round = _make_elementwise_unary_prim( + "round", + impl_aten=torch.round, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +rsqrt = _make_elementwise_unary_prim( + "rsqrt", + impl_aten=torch.rsqrt, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +sign = _make_elementwise_unary_prim( + "sign", + impl_aten=torch.sign, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +signbit = _make_elementwise_unary_prim( + "signbit", + impl_aten=torch.signbit, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +sin = _make_elementwise_unary_prim( + "sin", + impl_aten=torch.sin, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +sinh = _make_elementwise_unary_prim( + "sinh", + impl_aten=torch.sinh, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +spherical_bessel_j0 = _make_elementwise_unary_prim( + "spherical_bessel_j0", + impl_aten=torch.special.spherical_bessel_j0, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +sqrt = _make_elementwise_unary_prim( + "sqrt", + impl_aten=torch.sqrt, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +tan = _make_elementwise_unary_prim( + "tan", + impl_aten=torch.tan, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +tanh = _make_elementwise_unary_prim( + "tanh", + impl_aten=torch.tanh, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +trunc = _make_elementwise_unary_prim( + "trunc", + impl_aten=torch.trunc, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +# +# Elementwise binary operations +# + +add = _make_elementwise_binary_prim( + name="add", + impl_aten=torch.add, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +atan2 = _make_elementwise_binary_prim( + name="atan2", + impl_aten=torch.atan2, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +bitwise_and = _make_elementwise_binary_prim( + "bitwise_and", + impl_aten=torch.bitwise_and, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +bitwise_or = _make_elementwise_binary_prim( + "bitwise_or", + impl_aten=torch.bitwise_or, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +bitwise_xor = _make_elementwise_binary_prim( + "bitwise_xor", + impl_aten=torch.bitwise_xor, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +# TODO: complex needs a special meta to account for its float -> complex behavior +# complex = _make_elementwise_binary_prim( +# impl_aten=torch.complex, +# doc="", +# ) + + +# div prim performs truncation division on integer inputs +# and true division for floating and complex inputs +def _div_aten(a, b): + is_integral = isinstance(a, (bool, int, torch.SymInt)) or ( + isinstance(a, torch.Tensor) and utils.is_integer_dtype(a.dtype) + ) + + if is_integral: + return torch.div(a, b, rounding_mode="trunc") + else: + return torch.true_divide(a, b) + + +div = _make_elementwise_binary_prim( + "div", + impl_aten=_div_aten, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +eq = _make_elementwise_binary_prim( + "eq", + impl_aten=torch.eq, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) + +fmax = _make_elementwise_binary_prim( + "fmax", + impl_aten=torch.fmax, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +fmin = _make_elementwise_binary_prim( + "fmin", + impl_aten=torch.fmin, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +fmod = _make_elementwise_binary_prim( + "fmod", + impl_aten=torch.fmod, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + + +gcd = _make_elementwise_binary_prim( + "gcd", + impl_aten=torch.gcd, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + + +ge = _make_elementwise_binary_prim( + "ge", + impl_aten=torch.ge, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) + +gt = _make_elementwise_binary_prim( + "gt", + impl_aten=torch.gt, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) + +hypot = _make_elementwise_binary_prim( + "hypot", + impl_aten=torch.hypot, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +igamma = _make_elementwise_binary_prim( + "igamma", + impl_aten=torch.special.gammainc, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +igammac = _make_elementwise_binary_prim( + "igammac", + impl_aten=torch.special.gammaincc, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +le = _make_elementwise_binary_prim( + "le", + impl_aten=torch.le, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) + +lt = _make_elementwise_binary_prim( + "lt", + impl_aten=torch.lt, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) + + +# Note: the following impls are because torch.maximum and torch.minimum do not support scalar inputs +def _maximum_aten( + a: TensorLikeType | NumberType, b: TensorLikeType | NumberType +) -> TensorLikeType: + if isinstance(a, TensorLike) and isinstance(b, Number): + b = scalar_tensor(b, dtype=a.dtype, device=a.device) + elif isinstance(b, TensorLike) and isinstance(a, Number): + a = scalar_tensor(a, dtype=b.dtype, device=b.device) + + return torch.maximum(a, b) # type: ignore[arg-type] + + +maximum = _make_elementwise_binary_prim( + "maximum", + impl_aten=_maximum_aten, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + + +def _minimum_aten( + a: TensorLikeType | NumberType, b: TensorLikeType | NumberType +) -> TensorLikeType: + if isinstance(a, TensorLike) and isinstance(b, Number): + b = scalar_tensor(b, dtype=a.dtype, device=a.device) + elif isinstance(b, TensorLike) and isinstance(a, Number): + a = scalar_tensor(a, dtype=b.dtype, device=b.device) + + return torch.minimum(a, b) # type: ignore[arg-type] + + +minimum = _make_elementwise_binary_prim( + "minimum", + impl_aten=_minimum_aten, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +mul = _make_elementwise_binary_prim( + "mul", + impl_aten=torch.mul, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +ne = _make_elementwise_binary_prim( + "ne", + impl_aten=torch.ne, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) + +nextafter = _make_elementwise_binary_prim( + "nextafter", + impl_aten=torch.nextafter, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +pow = _make_elementwise_binary_prim( + "pow", + impl_aten=torch.pow, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +remainder = _make_elementwise_binary_prim( + "remainder", + impl_aten=torch.remainder, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + + +shift_left = _make_elementwise_binary_prim( + "shift_left", + impl_aten=torch.bitwise_left_shift, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +shift_right_arithmetic = _make_elementwise_binary_prim( + "shift_right_arithmetic", + impl_aten=torch.bitwise_right_shift, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +shift_right_logical = _not_impl + +sub = _make_elementwise_binary_prim( + "sub", + impl_aten=torch.sub, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + +zeta = _make_elementwise_binary_prim( + "zeta", + impl_aten=torch.special.zeta, + doc="", + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, +) + + +# +# View operations +def _as_strided_meta( + a: TensorLikeType, size: ShapeType, stride: StrideType, storage_offset: int +) -> TensorLikeType: + if len(size) != len(stride): + raise AssertionError(f"len(size)={len(size)} != len(stride)={len(stride)}") + if storage_offset < 0: + raise AssertionError(f"storage_offset must be >= 0, got {storage_offset}") + utils.validate_strides(stride) + utils.validate_shape(size) + + if reduce(operator.mul, size) == 0: + # NOTE: This special case is to avoid having to acquire the storage below + # as_strided to shapes with no elements are trivially valid, so it's OK + pass + elif isinstance(a, torch.Tensor): + utils.check_in_bounds_for_storage( + a._typed_storage(), size, stride, storage_offset + ) + + return torch.as_strided(a, size, stride, storage_offset) + + +def _as_strided_aten( + a: Tensor, size: ShapeType, stride: StrideType, storage_offset: int +) -> Tensor: + return torch.as_strided(a, size, stride, storage_offset) + + +_as_strided_doc = """ + Creates a view of the tensor with the given shape (size), strides (stride) and + storage offset (storage_offset). +""" + +as_strided = _make_prim( + schema="as_strided(Tensor(a!) a, SymInt[] size, SymInt[] stride, SymInt storage_offset) -> Tensor(a!)", + meta=_as_strided_meta, + impl_aten=_as_strided_aten, + return_type=RETURN_TYPE.VIEW, + doc=_as_strided_doc, +) + + +def _broadcast_in_dim_meta( + a: TensorLikeType, shape: ShapeType, broadcast_dimensions: Sequence[int] +): + from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + guard_or_true, + sym_or, + ) + + # Type checks + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") # mypy + if not isinstance(shape, Sequence): + raise AssertionError(f"shape must be a Sequence, got {type(shape)}") + if not isinstance(broadcast_dimensions, Sequence): + raise AssertionError( + f"broadcast_dimensions must be a Sequence, got {type(broadcast_dimensions)}" + ) + + # every dimension must be accounted for + if a.ndim != len(broadcast_dimensions): + raise AssertionError( + f"a.ndim ({a.ndim}) != len(broadcast_dimensions) ({len(broadcast_dimensions)})" + ) + + # broadcast shape must have weakly more dimensions + if len(shape) < a.ndim: + raise AssertionError(f"len(shape) ({len(shape)}) must be >= a.ndim ({a.ndim})") + + # broadcast_dimensions must be an ascending sequence + # (no relative reordering of dims) of integers and + # each dimension must be within the new shape + def _greater_than_reduce(acc, x): + if not isinstance(x, Dim): + raise AssertionError( + f"broadcast_dimensions element must be Dim, got {type(x)}" + ) + if x <= acc: + raise AssertionError( + f"broadcast_dimensions must be strictly ascending: {x} <= {acc}" + ) + if x >= len(shape): + raise AssertionError( + f"broadcast_dimension {x} out of bounds for shape of length {len(shape)}" + ) + + return x + + reduce(_greater_than_reduce, broadcast_dimensions, -1) + + # shape must be broadcastable to + for idx, new_idx in enumerate(broadcast_dimensions): + torch._check( + sym_or(a.shape[idx] == 1, shape[new_idx] == a.shape[idx]), + lambda: f"{a.shape[idx]} must be broadcastable to {shape[new_idx]}", + ) + + new_strides = [] + original_idx = 0 + for idx in range(len(shape)): + if idx in broadcast_dimensions: + # Assigns a stride of zero to dimensions + # which were actually broadcast + if guard_or_false(a.shape[original_idx] == 1): + if guard_or_false(a.shape[original_idx] == shape[idx]): + new_strides.append(a.stride()[original_idx]) + else: + new_strides.append(0) + else: + torch._check( + a.shape[original_idx] == shape[idx], + lambda: f"non-broadcasting semantics require {a.shape[original_idx]} == {shape[idx]}", + ) + new_strides.append(a.stride()[original_idx]) + original_idx = original_idx + 1 + else: + if guard_or_true(shape[idx] != 1): + # consistent with previous use of guard_size_oblivious + new_strides.append(0) + elif original_idx == a.ndim: + new_strides.append(1) + else: + new_strides.append(a.stride()[original_idx] * a.size()[original_idx]) + + return a.as_strided(shape, new_strides, a.storage_offset()) + + +def _broadcast_in_dim_aten(a, shape, broadcast_dimensions): + s = list(shape) + for broadcast_dimension in broadcast_dimensions: + s[broadcast_dimension] = -1 + + v = a + for idx, x in enumerate(s): + if x != -1: + v = v.unsqueeze(idx) + + return v.expand(shape) + + +_broadcast_in_dim_doc = """ + Creates a view of a with the specified shape. + + Allows adding dimensions of any length and broadcasting + dimensions of length one in a to any length. + + The location of the broadcast dimensions must be specified + using the broadcast_dimensions argument. Changing the + relative order of dimensions is not supported. + """ + +broadcast_in_dim = _make_prim( + schema="broadcast_in_dim(Tensor(a) a, SymInt[] shape, int[] broadcast_dimensions) -> Tensor(a)", + meta=_broadcast_in_dim_meta, + impl_aten=_broadcast_in_dim_aten, + return_type=RETURN_TYPE.VIEW, + doc=_broadcast_in_dim_doc, +) + + +def _validate_collapse_args(a: Tensor, start: int, end: int) -> None: + # Special-case for zero dimensional tensors + ndim = max(1, a.dim()) + utils.validate_idx(ndim, start) + utils.validate_idx(ndim, end) + + # Verifies end is strictly greater than start + # (Collapse requires a non-empty interval) + torch._check_value( + end >= start, + lambda: f"Attempting to collapse but end, {end}, is less than start, {start}!", + ) + + +def _collapsed_shape(shape: ShapeType, start: int, end: int) -> tuple[int, ...]: + """ + Returns the shape of a with dims in [start, end) merged into a single dimension. + """ + # Special-case for zero dimensional tensors + shape = (1,) if len(shape) == 0 else tuple(shape) + + dim_length = 1 + for s in shape[start : end + 1]: + dim_length = dim_length * s + + return shape[0:start] + (dim_length,) + shape[end + 1 :] + + +# If the collapse is invalid or cannot be determined (because of unbacked data) +# then `must_be_valid` determines the behavior: +# None: return None, None. +# str: Do a torch._check() to ensure the collapse is valid and if it isn't +# then fail with the provided string. +def _collapse_view_helper( + a: TensorLikeType, start: int, end: int, must_be_valid: str | None +) -> tuple[ShapeType | None, StrideType | None]: + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") # mypy + + from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + guard_or_true, + sym_and, + sym_or, + ) + + _validate_collapse_args(a, start, end) + + # Special-case for zero dimensional tensors + if a.ndim == 0: + shape = (1,) + strides = (1,) + else: + shape = a.shape # type: ignore[assignment] + strides = a.stride() # type: ignore[assignment] + + if a.ndim == 0 or (end == start): + return shape, strides + + valid_op = True + if guard_or_false(a.numel() != 0): + for idx in range(end - 1, start - 1, -1): + valid_op = sym_and( + valid_op, + sym_or( + shape[idx] == 1, + shape[idx + 1] == 1, + strides[idx] == strides[idx + 1] * shape[idx + 1], + ), + ) # type: ignore[assignment] + + # early exit if we already know its invalid. + if guard_or_false(valid_op is False): + break + + # for unbacked this becomes a runtime assertion. + valid_op = sym_or(valid_op, a.numel() == 0) + + if must_be_valid: + torch._check(valid_op, lambda: must_be_valid) + else: + if not guard_or_false(valid_op): + return None, None + + # compute stride + stride = strides[end] + for idx in range(end - 1, start - 1, -1): + if shape[idx] != 1: + # TODO with unbacked we should really exclude when shape[idx] == 1 + # something like + # min(stride[end], torch.ite(shape[x]!=1,stride[idx], inf), ...) + stride = min(stride, strides[idx]) + + # compute length + length = shape[end] + if guard_or_true(length != 0): + for idx in range(end - 1, start - 1, -1): + if guard_or_false(shape[idx] == 0): + length = 0 + stride = 0 + break + length = length * shape[idx] + else: + stride = 0 + + new_shape = shape[:start] + (length,) + shape[end + 1 :] + new_strides = strides[:start] + (stride,) + strides[end + 1 :] + + # NOTE: when the input has no elements it's restrided as if it were contiguous + # except for unbacked. + if guard_or_false(a.numel() == 0): + new_strides = utils.make_contiguous_strides_for(new_shape) + + return new_shape, new_strides + + +def _collapse_view_meta(a: TensorLikeType, start: int, end: int) -> TensorLikeType: + new_shape, new_strides = _collapse_view_helper( + a, start, end, "Attempting to view a collapsed tensor, but no such view exists!" + ) + if new_strides is None: + raise AssertionError( + "new_strides should not be None after _collapse_view_helper" + ) + if new_shape is None: + raise AssertionError("new_shape should not be None after _collapse_view_helper") + return a.as_strided(new_shape, new_strides, a.storage_offset()) + + +def _collapse_view_aten(a: Tensor, start: int, end: int) -> Tensor: + new_shape = _collapsed_shape(a.shape, start, end) + return a.view(new_shape) + + +_collapse_view_doc = """ + Creates a view of a with the dimensions between + start (inclusive) and end (exclusive) merged into a + single dimension. + + If it's not possible to take such a view then an error + is thrown. See collapse instead. + + The dimensions can be merged if and only if + they are all "nested" with each other. That is, they all + have the property that + + stride[i] = stride[i+1] * shape[i+1] + + for all i in [start, end - 1). + """ + +collapse_view = _make_prim( + schema="collapse_view(Tensor(a) a, int start, int end) -> Tensor(a)", + meta=_collapse_view_meta, + impl_aten=_collapse_view_aten, + return_type=RETURN_TYPE.VIEW, + doc=_collapse_view_doc, +) + + +def _conj_meta(a: TensorLikeType) -> TensorLikeType: + if not a.dtype.is_complex: + raise RuntimeError("Expected complex dtype in prims.conj") + out = a.as_strided(a.shape, a.stride(), a.storage_offset()) + torch._C._set_conj(out, not a.is_conj()) + return out + + +_conj_doc = """ +Returns a conjugated view of the original tensor +""" + +conj = _make_prim( + schema="conj(Tensor(a) a) -> Tensor(a)", + meta=_conj_meta, + impl_aten=torch.conj, + return_type=RETURN_TYPE.VIEW, + doc=_conj_doc, +) + + +def expand_dims( + a: TensorLikeType, dimensions: DimsSequenceType, ndim=None +) -> TensorLikeType: + """ + Creates a view of a with a.ndim + len(dimensions) dimensions, with new + dimensions of length one at the dimensions specified by dimensions. + """ + if ndim is not None: + # TODO: this is only here to support the unsqueeze ref + dims = sorted(utils.canonicalize_dims(ndim, dimensions)) # type: ignore[arg-type] + else: + dims = sorted(utils.canonicalize_dims(a.ndim, dimensions)) # type: ignore[arg-type] + if len(set(dims)) != len(dims): + msg = f"Received duplicate dimensions to expand in {str(dimensions)}" + raise ValueError(msg) + + new_shape = list(a.shape) + for idx in dims: + new_shape.insert(idx, 1) + + broadcast_dimensions = [ + idx for idx in range(len(new_shape)) if idx not in dimensions + ] + return broadcast_in_dim(a, new_shape, broadcast_dimensions) + + +def _split_dim_meta(a: TensorLikeType, dim: int, outer_length: int) -> TensorLikeType: + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") # mypy + utils.validate_idx(a.ndim, dim) + utils.validate_dim_length(outer_length) + + # Verifies the dim can be split with the specified lhs_length + inner_length = a.shape[dim] // outer_length + + if (a.shape[dim] % outer_length) != 0: + msg = ( + f"Attempting to split dimension of length {a.shape[dim]}, " + f"but outer length of {outer_length} divides it with a remainder!" + ) + raise ValueError(msg) + + new_shape: list[int] = [] + new_strides: list[int] = [] + for idx in range(a.ndim): + if idx == dim: + new_shape.extend((outer_length, inner_length)) + new_strides.extend((a.stride()[idx] * inner_length, a.stride()[idx])) + else: + new_shape.append(a.shape[idx]) + new_strides.append(a.stride()[idx]) + + return a.as_strided(new_shape, new_strides, a.storage_offset()) + + +def _split_dim_aten(a: Tensor, dim: int, outer_length: int) -> Tensor: + inner_length = a.shape[dim] // outer_length + new_shape = a.shape[0:dim] + (outer_length, inner_length) + a.shape[dim + 1 :] + + return a.view(new_shape) + + +_split_dim_doc = """ + Creates a view of a with the given dimension (of length l) split + into two dimensions, with the outer of the two having + length outer_length and the inner of the two having computed + length inner_length such outer_length * inner_length = l. + """ + +# TODO: consider renaming split_dim_view +split_dim = _make_prim( + schema="split_dim(Tensor(a) a, int dim, SymInt outer_length) -> Tensor(a)", + meta=_split_dim_meta, + impl_aten=_split_dim_aten, + return_type=RETURN_TYPE.VIEW, + doc=_split_dim_doc, +) + + +# Note: allows dimensions to be specified redundantly +def _squeeze_meta(a: TensorLikeType, dimensions: Sequence) -> TensorLikeType: + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") # mypy + + for idx in dimensions: + utils.validate_idx(a.ndim, idx) + if a.shape[idx] != 1: + raise AssertionError( + f"Cannot squeeze dimension {idx} with size {a.shape[idx]} (must be 1)" + ) + + new_shape = [] + new_strides = [] + for idx in range(len(a.shape)): + if idx in dimensions: + continue + + new_shape.append(a.shape[idx]) + new_strides.append(a.stride()[idx]) + + return a.as_strided(new_shape, new_strides, a.storage_offset()) + + +_squeeze_doc = """ + Creates a view of the tensor with the specified dimensions removed. + + The removed dimensions must each have length one. + """ + +squeeze = _make_prim( + schema="squeeze(Tensor(a) a, int[] dimensions) -> Tensor(a)", + meta=_squeeze_meta, + impl_aten=torch.squeeze, + return_type=RETURN_TYPE.VIEW, + doc=_squeeze_doc, +) + + +def _transpose_meta(a: TensorLikeType, permutation: DimsSequenceType) -> TensorLikeType: + if a.ndim != len(permutation): + msg = f"Attempting to permute a tensor of rank {a.ndim}, but received a permutation of length {len(permutation)}!" + raise ValueError(msg) + + if not utils.is_valid_permutation(a.ndim, permutation): + msg = f"Received an invalid permutation, {permutation}!" + raise ValueError(msg) + + new_shape = [0] * a.ndim + new_strides = [0] * a.ndim + for idx, dim in enumerate(permutation): + new_shape[idx] = a.shape[dim] + new_strides[idx] = a.stride()[dim] + + return a.as_strided(tuple(new_shape), tuple(new_strides), a.storage_offset()) + + +def _transpose_aten(a: Tensor, permutation: DimsSequenceType) -> Tensor: + return torch.permute(a, permutation) + + +_transpose_doc = """ + Creates a view of the tensor with its dimensions permuted. + + The length of the permutation must be the rank of the tensor, + and each element of the permutation specifies the new order + for the corresponding dimension. + """ + +transpose = _make_prim( + schema="transpose(Tensor(a) a, int[] permutation) -> Tensor(a)", + meta=_transpose_meta, + impl_aten=_transpose_aten, + return_type=RETURN_TYPE.VIEW, + doc=_transpose_doc, +) + + +def _view_of_meta(a: TensorLikeType) -> TensorLikeType: + return a.as_strided(a.shape, a.stride(), a.storage_offset()) + + +def _view_of_aten(a: Tensor) -> Tensor: + return a.view(a.shape) + + +_view_of_doc = """ + Creates a view of the tensor. + """ + +view_of = _make_prim( + schema="view_of(Tensor(a) a) -> Tensor(a)", + meta=_view_of_meta, + impl_aten=_view_of_aten, + return_type=RETURN_TYPE.VIEW, + doc=_view_of_doc, +) + + +def _view_element_type_meta(a: TensorLikeType, dtype: torch.dtype) -> TensorLikeType: + return a.view(dtype) + + +def _view_element_type_aten(a: Tensor, dtype: torch.dtype) -> Tensor: + return a.view(dtype) + + +_view_element_type_doc = """ + Creates a view of the tensor with a different dtype. + """ + +view_element_type = _make_prim( + schema="view_of_dtype(Tensor(a) a, ScalarType dtype) -> Tensor(a)", + meta=_view_element_type_meta, + impl_aten=_view_element_type_aten, + return_type=RETURN_TYPE.VIEW, + doc=_view_element_type_doc, +) + +# +# Functionalized view mutations +# + + +def _as_strided_scatter_meta( + input: TensorLikeType, + src: TensorLikeType, + size: ShapeType, + stride: StrideType, + storage_offset: int, +) -> TensorLikeType: + utils.validate_shape(size) + utils.validate_strides(stride) + + required_size = utils.compute_required_storage_length(size, stride, storage_offset) + torch._check( + input.numel() >= required_size, + lambda: ( + f"as_strided_scatter: sizes {size}, strides {stride}, storage offset {storage_offset} " + f" and itemsize {input.element_size()} requiring a storage size of " + f"{required_size * input.element_size()} are out of bounds " + f"for storage of size {input.numel() * input.element_size()}" + ), + ) + torch._check( + utils.is_same_shape(src.shape, size), + lambda: f"expected src to have a size equal to the slice of self. src size = {src.shape}, slice size = {size}", + ) + + return utils.clone_preserve_strides(input) + + +_as_strided_scatter_doc = """ + Creates a new tensor equivalent to ``out = input.clone()`` after mutation by + ``out.as_strided(size, stride, storage_offset).copy_(src)``. +""" + +as_strided_scatter = _make_prim( + schema="as_strided_scatter(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt storage_offset) -> Tensor", + meta=_as_strided_scatter_meta, + impl_aten=torch.as_strided_scatter, + return_type=RETURN_TYPE.NEW, + doc=_as_strided_scatter_doc, +) + + +# +# Shape operations +# + + +def _collapse_meta(a: Tensor, start: int, end: int) -> Tensor: + # Special-case for zero dimensional tensors + _validate_collapse_args(a, start, end) + new_shape = _collapsed_shape(a.shape, start, end) + return a.new_empty(new_shape) + + +def _collapse_aten(a: Tensor, start: int, end: int) -> Tensor: + new_shape = _collapsed_shape(a.shape, start, end) + out = a.new_empty(new_shape) + with torch.no_grad(): + out.view_as(a).copy_(a) + return out + + +_collapse_doc = """ +Collapse a span of neighboring dimensions into one. + +See collapse_view for the corresponding view operation. +""" +collapse = _make_prim( + schema="collapse(Tensor a, int start, int end) -> Tensor", + meta=_collapse_meta, + impl_aten=_collapse_aten, + return_type=RETURN_TYPE.NEW, + doc=_collapse_doc, +) + + +# TODO: review stride logic +# NB: unlike torch.cat, this is more strict about empty tensors and dim is +# never negative +def _cat_meta(tensors: Sequence[TensorLikeType], dim: int) -> TensorLikeType: + # Verifies same shape (except in the concat dimension) + if dim < 0: + raise AssertionError(f"dim must be non-negative, got {dim}") + shape = tensors[0].shape + sym_sum_args = [] + for tensor_idx, tensor in enumerate(tensors): + if len(shape) != len(tensor.shape): + raise AssertionError( + f"All tensors must have the same number of dimensions. " + f"Expected {len(shape)} but tensor {tensor_idx} has {len(tensor.shape)}" + ) + for idx, (common_length, length) in enumerate(zip(shape, tensor.shape)): + if idx == dim: + sym_sum_args.append(length) + else: + torch._check( + length == common_length, + lambda: f"Sizes of tensors must match except in dimension {dim}. " + f"Expected {common_length} in dimension {idx} but got {length} for tensor number " + f"{tensor_idx} in the list", + ) + + new_shape = list(tensors[0].shape).copy() + new_shape[dim] = torch.sym_sum(sym_sum_args) # type: ignore[call-overload] + return TensorMeta( + tensors[0], + shape=new_shape, + strides=utils.make_contiguous_strides_for(new_shape), + ) + + +def _cat_aten(tensors: tuple[Tensor, ...] | list[Tensor], dim: int) -> Tensor: + return torch.cat(tensors, dim) + + +_cat_doc = """ + Concatenates tensors along the specified dimension. + + The tensors' shapes must have the same rank and same length for other dimensions. + """ + +cat = _make_prim( + schema="cat(Tensor[] tensors, int dim) -> Tensor", + meta=_cat_meta, + impl_aten=_cat_aten, + return_type=RETURN_TYPE.NEW, + doc=_cat_doc, +) + + +def _reshape_meta(a: TensorLikeType, shape: ShapeType): + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") # mypy + utils.validate_shape(shape) + + # Validates the tensor and the requested shape have the + # same number of elements + numel = reduce(operator.mul, shape) + if numel != a.numel(): + msg = f"Attempting to reshape a tensor with {a.numel()} elements to a shape with {numel} elements!" + raise ValueError(msg) + + return TensorMeta(a, shape=shape, strides=utils.make_contiguous_strides_for(shape)) + + +def _reshape_aten(a: Tensor, shape: ShapeType) -> Tensor: + return a.reshape(shape).clone(memory_format=torch.contiguous_format) + + +_reshape_doc = """ + Creates a contiguous tensor with the specified shape + containing a copy of the data in a. + """ +reshape = _make_prim( + schema="reshape(Tensor a, SymInt[] shape) -> Tensor", + meta=_reshape_meta, + impl_aten=_reshape_aten, + return_type=RETURN_TYPE.NEW, + doc=_reshape_doc, +) + + +def _rev_meta(a: TensorLikeType, dims: DimsSequenceType) -> TensorLikeType: + utils.validate_dimension_indices(a.ndim, dims) + return torch.empty_like(a, memory_format=torch.preserve_format) + + +_rev_doc = """ + Reverses the order of elements along the given dimensions. + """ + +rev = _make_prim( + schema="rev(Tensor a, int[] dims) -> Tensor", + meta=_rev_meta, + impl_aten=torch.flip, + return_type=RETURN_TYPE.NEW, + doc=_rev_doc, +) + +# +# Conditional prims +# + + +def _where_meta( + pred: TensorLikeType, a: TensorLikeType, b: TensorLikeType +) -> TensorLikeType: + return _prim_elementwise_meta( + a, + b, + type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT, + args_with_fixed_dtypes=(pred,), + ) + + +_where_doc = """ + Selects elements from a and b according to pred. + + Where pred is true the result contains the element from a, and + where pred is false the result contains the element from b. + """ + +where = _make_prim( + schema="where(Tensor pred, Tensor a, Tensor b) -> Tensor", + meta=_where_meta, + impl_aten=torch.where, + return_type=RETURN_TYPE.NEW, + doc=_where_doc, +) + + +# +# Type conversions +# +def _convert_element_type_meta(a: TensorLikeType, dtype: torch.dtype) -> TensorLikeType: + # Type checks + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") # mypy + if not isinstance(dtype, torch.dtype): + raise AssertionError(f"dtype must be torch.dtype, got {type(dtype)}") + + # dtype conversion preserves dense strides + if torch._prims_common.is_non_overlapping_and_dense_or_false(a): + strides = a.stride() + else: + strides = utils.compute_elementwise_output_strides(a) + + return TensorMeta(a, strides=strides, dtype=dtype) + + +def _convert_element_type_aten(a: Tensor, dtype: torch.dtype) -> Tensor: + # Propagates requires grad when possible + if not utils.is_grad_dtype(dtype): + requires_grad = False + else: + # TODO: update meta objects so this can be acquired directly + try: + requires_grad = a.requires_grad + except Exception: + requires_grad = False + + result = torch.empty_like( + a, device=a.device, dtype=dtype, requires_grad=requires_grad + ) + with torch.no_grad(): + return copy_to(result, a) + + +_convert_element_type_doc = """ + Creates a copy of a tensor with the given dtype. + """ + +convert_element_type = _make_prim( + schema="convert_element_type(Tensor a, ScalarType dtype) -> Tensor", + meta=_convert_element_type_meta, + impl_aten=_convert_element_type_aten, + return_type=RETURN_TYPE.NEW, + doc=_convert_element_type_doc, + tags=(torch.Tag.pointwise,), +) + + +def _device_put_meta( + a: TensorLikeType, device: str | torch.device, non_blocking=False +) -> TensorLikeType: + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") # mypy + if not isinstance(device, (str, torch.device)): + raise AssertionError(f"device must be str or torch.device, got {type(device)}") + if not isinstance(non_blocking, bool): + raise AssertionError(f"non_blocking must be bool, got {type(non_blocking)}") + + return TensorMeta(a, device=utils.canonicalize_device(device)) + + +def _device_put_aten( + a: Tensor, device: str | torch.device, non_blocking=False +) -> Tensor: + return a.to(device, non_blocking=non_blocking) + + +_device_put_doc = """ + Creates a copy of a tensor on the given device. + """ + +device_put = _make_prim( + schema="device_put(Tensor a, Device device, bool non_blocking=False) -> Tensor", + meta=_device_put_meta, + impl_aten=_device_put_aten, + return_type=RETURN_TYPE.NEW, + doc=_device_put_doc, +) + + +# NOTE: need to model meta scalars +# See https://github.com/pytorch/pytorch/issues/78070 +def _item_meta(a: TensorLikeType) -> FakeTensor: + number_type = utils.dtype_to_type(a.dtype) + return TensorMeta(number_type(-1)) + + +_item_doc = """ + Converts a tensor with one element to a Python number. +""" + + +# We can't call into python dispatcher for item again +# because the current prim decomp calls into python dispatcher +# again. https://github.com/pytorch/pytorch/issues/136050 +def _item_aten_no_python_dispatcher(*args, **kwargs): + with torch._dispatch.python.no_python_dispatcher(): + return torch.Tensor.item(*args, **kwargs) + + +# TODO: create a new return type for scalars? +# FIXME: currently returns integers for boolean tensors +# https://github.com/pytorch/pytorch/issues/78071 +item = _make_prim( + schema="item(Tensor a) -> Scalar", + meta=_item_meta, + impl_aten=_item_aten_no_python_dispatcher, + return_type=RETURN_TYPE.NEW, + doc=_item_doc, +) + + +# NOTE: need to model meta scalars +# See https://github.com/pytorch/pytorch/issues/78070 +def _maximum_value_meta(dtype: torch.dtype) -> FakeTensor: + number_type = utils.dtype_to_type(dtype) + return TensorMeta(number_type(-1)) + + +def _maximum_value_aten(dtype: torch.dtype): + if dtype == torch.bool: + return True + elif dtype.is_complex or dtype.is_floating_point: + return torch.finfo(dtype).max + else: + return torch.iinfo(dtype).max + + +_maximum_value_doc = """ + Return the maximum finite value for a dtype. +""" + +# TODO: create a new return type for scalars? +# FIXME: currently returns integers for boolean tensors +# https://github.com/pytorch/pytorch/issues/78071 +maximum_value = _make_prim( + schema="maximum_value(ScalarType dtype) -> Scalar", + meta=_maximum_value_meta, + impl_aten=_maximum_value_aten, + return_type=RETURN_TYPE.NEW, + doc=_maximum_value_doc, +) + + +# NOTE: need to model meta scalars +# See https://github.com/pytorch/pytorch/issues/78070 +def _minimum_value_meta(dtype: torch.dtype) -> FakeTensor: + number_type = utils.dtype_to_type(dtype) + return TensorMeta(number_type(-1)) + + +def _minimum_value_aten(dtype: torch.dtype): + if dtype == torch.bool: + return False + elif dtype.is_complex or dtype.is_floating_point: + return torch.finfo(dtype).min + else: + return torch.iinfo(dtype).min + + +_minimum_value_doc = """ + Return the minimum finite value for a dtype. +""" + +# TODO: create a new return type for scalars? +# FIXME: currently returns integers for boolean tensors +# https://github.com/pytorch/pytorch/issues/78071 +minimum_value = _make_prim( + schema="minimum_value(ScalarType dtype) -> Scalar", + meta=_minimum_value_meta, + impl_aten=_minimum_value_aten, + return_type=RETURN_TYPE.NEW, + doc=_minimum_value_doc, +) + +# +# Inplace operators +# + + +def _copy_to_meta(a: TensorLikeType, b: TensorLikeType): + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") # mypy + if not isinstance(b, TensorLike): + raise AssertionError(f"b must be TensorLike, got {type(b)}") # mypy + + # Validates the cast is safe + # TODO: move this as an option on the reference + # a_typ = utils.dtype_to_type(a.dtype) + # b_typ = utils.dtype_to_type(b.dtype) + # if a_typ is not utils.get_higher_type(a_typ, b_typ): + # raise RuntimeError(str(b.dtype), " can't be cast safely to ", str(a.dtype), "!") + + # Validates the tensors have the same number of elements + if a.numel() != b.numel(): + msg = f"Attempting to copy {b.numel()} elements to a tensor with {a.numel()} elements!" + raise RuntimeError(msg) + + return a + + +def _copy_to_aten(a: Tensor, b: Tensor) -> Tensor: + return a.copy_(b) + + +_copy_to_doc = """ + Copies the data in b to a and returns the modified a. + """ + +# TODO: Remove safe casting and implement on reference instead +copy_to = _make_prim( + schema="copy_to(Tensor(a!) a, Tensor b) -> Tensor(a!)", + meta=_copy_to_meta, + impl_aten=_copy_to_aten, + return_type=RETURN_TYPE.INPLACE, + doc=_copy_to_doc, + register_conj_neg_fallthrough=True, +) + + +def _copy_strided_meta(a: TensorLikeType, stride: ShapeType): + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") # mypy + return torch.empty_strided( + a.shape, + stride, + dtype=a.dtype, + layout=a.layout, + device=a.device, + requires_grad=a.requires_grad, + ) + + +def _copy_strided_aten(a: Tensor, stride: ShapeType) -> Tensor: + out = torch.empty_strided( + a.size(), + stride=stride, + dtype=a.dtype, + layout=a.layout, + device=a.device, + requires_grad=a.requires_grad, + ) + out.copy_(a) + return out + + +_copy_strided_doc = """ + Copies the data in a to a new tensor, the new tensor has same shape with a size, but has different stride. + """ + + +copy_strided = _make_prim( + schema="copy_strided(Tensor a, SymInt[] stride) -> Tensor", + meta=_copy_strided_meta, + impl_aten=_copy_strided_aten, + return_type=RETURN_TYPE.NEW, + doc=_copy_strided_doc, +) + + +def _resize_meta(a: TensorLikeType, shape: ShapeType): + return a.resize_(shape) + + +def _resize_aten(a: Tensor, shape: ShapeType) -> Tensor: + return a.resize_(shape) + + +_resize_doc = """ + Gives a tensor with no elements a new shape, returning the modified tensor. + + The tensor's strides are contiguous and its values are uninitialized. + """ + +# TODO: review support arbitrary resizes +resize = _make_prim( + schema="resize(Tensor(a!) a, SymInt[] shape) -> Tensor(a!)", + meta=_resize_meta, + impl_aten=_resize_aten, + return_type=RETURN_TYPE.INPLACE, + doc=_resize_doc, +) + + +def _reduction_meta(inp, dims, *, output_dtype=None): + """ + Meta function for single output reduction operations + Stride logic is incorrect + """ + if not isinstance(inp, TensorLike): + raise AssertionError(f"inp must be TensorLike, got {type(inp)}") # mypy + if output_dtype is None: + output_dtype = inp.dtype + output_shape = utils.compute_reduction_output_shape(inp.shape, dims) + return TensorMeta( + shape=output_shape, + strides=utils.make_contiguous_strides_for(output_shape), + dtype=output_dtype, + device=inp.device, + ) + + +def _var_reduction_meta(inp, dims, correction): + if utils.is_complex_dtype(inp.dtype): + output_dtype = utils.corresponding_real_dtype(inp.dtype) + else: + output_dtype = inp.dtype + return _reduction_meta(inp, dims, output_dtype=output_dtype) + + +_sum_doc = """ + Computes the sum of elements in the input tensor over the list of dimensions + specified in the dim argument + """ +_xor_sum_doc = """ + Computes the xor sum of elements in the input tensor over the list of dimensions + specified in the dim argument + """ +_prod_doc = """ + Computes the product of elements in the input tensor over the list of dimensions + specified in the dim argument + """ +_amax_doc = """ + Computes the maximum value of elements in the input tensor over the list of dimensions + specified in the dim argument + """ +_amin_doc = """ + Computes the minimum value of elements in the input tensor over the list of dimensions + specified in the dim argument + """ +_var_doc = """ + Computes the biased variance of x over the list of dimensions specified in the dim argument + """ + + +def _make_reduction_prim(name: str, impl_aten, doc): + """Creates a reduction prim.""" + return _make_prim( + schema=f"{name}(Tensor inp, int[]? dims, *, ScalarType? output_dtype=None) -> Tensor", + meta=_reduction_meta, + impl_aten=impl_aten, + return_type=RETURN_TYPE.NEW, + doc=doc, + ) + + +def _make_var_reduction_prim(name: str, impl_aten, doc): + """Creates a reduction prim.""" + return _make_prim( + schema=f"{name}(Tensor inp, int[]? dims, float? correction=1, *, ScalarType? output_dtype=None) -> Tensor", + meta=_var_reduction_meta, + impl_aten=impl_aten, + return_type=RETURN_TYPE.NEW, + doc=doc, + ) + + +sum = _make_reduction_prim( + name="sum", + impl_aten=torch.sum, + doc=_sum_doc, +) + + +def _xor_sum_aten( + inp: TensorLikeType, + dims: DimsSequenceType | None, + *, + dtype: torch.dtype | None = None, +) -> Tensor: + raise NotImplementedError("xor_sum only implemented with inductor") + + +xor_sum = _make_reduction_prim( + name="xor_sum", + impl_aten=_xor_sum_aten, + doc=_xor_sum_doc, +) + + +def _prod_aten( + inp: TensorLikeType, + dims: DimsSequenceType | None, + *, + dtype: torch.dtype | None = None, +) -> Tensor: + if dims is not None: + if len(dims) == 0: + return inp.clone() + for d in sorted(dims, reverse=True): + if d < 0: + raise AssertionError(f"dimension must be non-negative, got {d}") + inp = torch.prod(inp, d, dtype=dtype) + return inp + else: + return torch.prod(inp, dtype=dtype) + + +prod = _make_reduction_prim( + name="prod", + impl_aten=_prod_aten, + doc=_prod_doc, +) + + +# torch.var, but correction is not kwarg-only +def torch_var(input, dim=None, correction=1, **kwargs): + return torch.var(input, dim=dim, correction=correction, **kwargs) + + +var = _make_var_reduction_prim( + name="var", + impl_aten=torch_var, + doc=_var_doc, +) + +amax = _make_reduction_prim( + name="amax", + impl_aten=torch.amax, + doc=_amax_doc, +) + +amin = _make_reduction_prim( + name="amin", + impl_aten=torch.amin, + doc=_amin_doc, +) + + +_iota_doc = """ + Constructs a 1-D tensor t where ``t[i] == start + i * step``. +""" + + +# TODO: layout, pin_memory, memory_format +# TODO: model requires_grad on TensorMeta +def _iota_meta( + length: int, + *, + start: int, + step: int, + dtype: torch.dtype, + device: torch.device, + requires_grad: bool, +) -> TensorLikeType: + torch._check( + utils.is_integer_dtype(dtype), + lambda: "prims.iota only supports integer dtypes", + ) + torch._check(step != 0, lambda: "step must be nonzero") + return torch.empty( + length, + dtype=dtype, + device=device, + requires_grad=requires_grad, + ) + + +def _iota_aten( + length: int, + *, + start: int, + step: int, + dtype: torch.dtype, + device: torch.device, + requires_grad: bool, +) -> TensorLikeType: + end = start + length * step + return torch.arange( + start, end, step, dtype=dtype, device=device, requires_grad=requires_grad + ) + + +iota = _make_prim( + schema="iota(SymInt length, *, SymInt start, SymInt step, ScalarType dtype, Device device, bool requires_grad) -> Tensor", + return_type=RETURN_TYPE.NEW, + meta=_iota_meta, + impl_aten=_iota_aten, + doc=_iota_doc, +) + + +# TODO: layout, pin_memory, memory_format +# TODO: model requires_grad on TensorMeta +def _empty_meta( + shape: ShapeType, *, dtype: torch.dtype, device: torch.device, requires_grad: bool +) -> TensorLikeType: + strides = utils.make_contiguous_strides_for(shape) + return TensorMeta(shape=shape, strides=strides, dtype=dtype, device=device) + + +def _empty_aten( + shape: ShapeType, *, dtype: torch.dtype, device: torch.device, requires_grad: bool +) -> Tensor: + return torch.empty(shape, dtype=dtype, device=device, requires_grad=requires_grad) + + +_empty_doc = """ + Creates a tensor with uninitialized values and the specified shape, dtype, and device. +""" + +empty = _make_prim( + schema="empty(SymInt[] shape, *, ScalarType dtype, Device device, bool requires_grad) -> Tensor", + meta=_empty_meta, + impl_aten=_empty_aten, + return_type=RETURN_TYPE.NEW, + doc=_empty_doc, +) + + +def _empty_strided_meta( + shape: ShapeType, + strides: StrideType, + *, + dtype: torch.dtype, + device: torch.device, + requires_grad: bool, +) -> TensorLikeType: + return TensorMeta(shape=shape, strides=strides, dtype=dtype, device=device) + + +_empty_strided_doc = """ + Creates a tensor with uninitialized values. +""" + +# TODO: add layout, pin_memory +empty_strided = _make_prim( + schema="empty_strided(SymInt[] shape, SymInt[] strides, *, ScalarType dtype, Device device, bool requires_grad) -> Tensor", + return_type=RETURN_TYPE.NEW, + meta=_empty_strided_meta, + impl_aten=torch.empty_strided, + doc=_empty_strided_doc, +) + + +def _empty_permuted_meta( + shape: ShapeType, + physical_layout: DimsSequenceType, + *, + dtype: torch.dtype, + device: torch.device, + requires_grad: bool, +) -> TensorLikeType: + p_strides = utils.make_contiguous_strides_for([shape[l] for l in physical_layout]) + dim = len(shape) + torch._check( + len(physical_layout) == dim, + lambda: ( + "Number of dimensions in the tensor input does not match the " + f"length of the physical layout; i.e. len(size) = {dim} " + f"is not equal to len(physical_layout) = {len(physical_layout)}" + ), + ) + strides = [0] * len(shape) + seen_dims = set() + for p, l in enumerate(physical_layout): + torch._check( + 0 <= l < dim, + lambda: ( + f"Dimension out of range (expected to be between 0 and {dim - 1}, but got " + f"{l} at index {p}). NB: negative dims " + "not currently supported; file an issue if you want it." + ), + ) + torch._check(l not in seen_dims, lambda: "Duplicate dim not allowed") + strides[l] = p_strides[p] + seen_dims.add(l) + return TensorMeta( + shape=shape, + strides=strides, + dtype=dtype, + device=device, + ) + + +_empty_permuted_doc = """ + Creates a tensor with uninitialized values according to some physical layout, + that is guaranteed to be non-overlapping and dense. +""" + +# TODO: add layout, pin_memory +empty_permuted = _make_prim( + schema="empty_permuted(SymInt[] shape, int[] physical_layout, *, ScalarType dtype, Device device, bool requires_grad) -> Tensor", + return_type=RETURN_TYPE.NEW, + meta=_empty_permuted_meta, + impl_aten=torch.empty_permuted, + doc=_empty_permuted_doc, +) + + +def _full_meta( + shape: ShapeType, + fill_value: NumberType, + *, + dtype: torch.dtype, + device: torch.device, + requires_grad: bool, +) -> TensorLikeType: + strides = utils.make_contiguous_strides_for(shape) + return TensorMeta(shape=shape, strides=strides, dtype=dtype, device=device) + + +def _full_aten( + shape: ShapeType, + fill_value: NumberType, + *, + dtype: torch.dtype, + device: torch.device, + requires_grad: bool, +) -> Tensor: + # Note that Mypy thinks torch.full can't accept a complex fill_value + return torch.full( + shape, + fill_value, + dtype=dtype, + device=device, + requires_grad=requires_grad, # type: ignore[arg-type] + ) + + +_full_doc = """ + Creates a tensor filled with the given fill value, and with the specified shape, dtype, and device. +""" + +# TODO: add layout +full = _make_prim( + schema="full(SymInt[] shape, Scalar fill_value, *, ScalarType dtype, Device device, bool requires_grad) -> Tensor", + meta=_full_meta, + impl_aten=_full_aten, + return_type=RETURN_TYPE.NEW, + doc=_full_doc, +) + + +def _full_like_meta( + a: TensorLikeType, + fill_value: NumberType, + *, + dtype: torch.dtype, + device: torch.device, + requires_grad: bool, +) -> TensorLikeType: + strides = utils.compute_elementwise_output_strides(a) + if a.numel() == 0: + strides = a.stride() + + return TensorMeta(a, strides=strides, dtype=dtype, device=device) + + +def _full_like_aten( + a: Tensor, + fill_value: NumberType, + *, + dtype: torch.dtype, + device: torch.device, + requires_grad: bool, +) -> Tensor: + # Note that Mypy thinks torch.full can't accept a complex fill_value + return torch.full_like( + a, + fill_value, + dtype=dtype, + device=device, + requires_grad=requires_grad, # type: ignore[arg-type] + ) + + +_full_like_doc = """ + Creates a tensor filled with the given fill value, and the same shape, dtype, and device as the + given tensor by default. The dtype and device settings can be overridden + by specifying them explicitly. +""" + +full_like = _make_prim( + schema="full_like(Tensor a, Scalar fill_value, *, ScalarType dtype, Device device, bool requires_grad) -> Tensor", + meta=_full_like_meta, + impl_aten=_full_like_aten, + return_type=RETURN_TYPE.NEW, + doc=_full_like_doc, +) + + +def _scalar_tensor_meta( + scalar: NumberType, + *, + dtype: torch.dtype, + device: torch.device, +) -> TensorLikeType: + shape: ShapeType = [] + strides = utils.make_contiguous_strides_for(shape) + return TensorMeta(scalar, shape=shape, strides=strides, dtype=dtype, device=device) + + +def _scalar_tensor_aten( + scalar: NumberType, + *, + dtype: torch.dtype, + device: torch.device, +) -> Tensor: + if isinstance(scalar, complex) and ( + dtype is None or not utils.is_complex_dtype(dtype) + ): + raise TypeError("Complex scalar requires complex tensor dtype.") + # Note that Mypy thinks torch.scalar can't accept a complex scalar + return torch.scalar_tensor(scalar, dtype=dtype, device=device) # type: ignore[arg-type] + + +_scalar_tensor_doc = """ + Wraps a Number into a Tensor with the specified dtype and device. +""" + +# TODO: add layout and pin_memory support +scalar_tensor = _make_prim( + schema="scalar_tensor(Scalar s, *, ScalarType? dtype=None, Device? device=None) -> Tensor", + meta=_scalar_tensor_meta, + impl_aten=_scalar_tensor_aten, + return_type=RETURN_TYPE.NEW, + doc=_scalar_tensor_doc, +) + + +# +# Linear algebra (linalg) prims +# + + +def _svd_meta( + A: TensorLikeType, *, full_matrices: bool +) -> tuple[TensorLikeType, TensorLikeType, TensorLikeType]: + utils.check_is_matrix(A, "linalg.svd") + utils.check_fp_or_complex(A.dtype, "linalg.svd", allow_low_precision_dtypes=False) + + A_shape = A.shape + batch = A_shape[:-2] + m, n = A_shape[-2:] + k = min(m, n) + + shape_U = batch + (m, m if full_matrices else k) + strides_U = utils.make_contiguous_strides_for(shape_U, row_major=False) + U = TensorMeta(shape=shape_U, strides=strides_U, dtype=A.dtype, device=A.device) + + shape_S = batch + (k,) + strides_S = utils.make_contiguous_strides_for(shape_S) + S = TensorMeta( + shape=shape_S, + strides=strides_S, + dtype=utils.corresponding_real_dtype(A.dtype) if A.is_complex() else A.dtype, + device=A.device, + ) + + shape_Vh = batch + (n if full_matrices else k, n) + # The CPU backend returns V, but the cuSolver backend returns V^H + # TODO The MAGMA backend returns V, so this is wrong if used with the MAGMA backend + is_cuda = A.device.type == "cuda" + strides_Vh = utils.make_contiguous_strides_for(shape_Vh, row_major=is_cuda) + Vh = TensorMeta(shape=shape_Vh, strides=strides_Vh, dtype=A.dtype, device=A.device) + # Also makes sure this is CUDA or HIP: + # https://pytorch.org/docs/stable/notes/hip.html#checking-for-hip + if A.numel() != 0 and Vh.is_complex() and torch.cuda.is_available(): + Vh = Vh.conj() + return U, S, Vh + + +def _svd_aten( + A: TensorLikeType, *, full_matrices: bool +) -> tuple[Tensor, Tensor, Tensor]: + return torch.linalg.svd(A, full_matrices=full_matrices) + + +_svd_doc = """ + Returns the SVD of a matrix or batch of matrices. + + The `full_matrices` flag controls whether the full or reduced SVD decomposition is returned. +""" + +svd = _make_prim( + schema="svd(Tensor A, *, bool full_matrices) -> (Tensor U, Tensor S, Tensor Vh)", + meta=_svd_meta, + impl_aten=_svd_aten, + return_type=(RETURN_TYPE.NEW, RETURN_TYPE.NEW, RETURN_TYPE.NEW), + doc=_svd_doc, +) + + +# +# Randomness Prims +# + + +def _normal_meta( + shape: ShapeType, + *, + mean: float | complex, + std: float, + dtype: torch.dtype, + device: torch.device, + requires_grad: bool, + generator: torch.Generator | None = None, +) -> TensorLikeType: + torch._check( + std >= 0.0, + lambda: f"expected non-negative standard deviation, but got std={std}", + ) + + torch._check( + utils.is_float_dtype(dtype) or utils.is_complex_dtype(dtype), + lambda: f"expected a floating-point or complex dtype, but got dtype={dtype}", + ) + + strides = utils.make_contiguous_strides_for(shape) + return TensorMeta(shape=shape, strides=strides, dtype=dtype, device=device) + + +def _normal_aten( + shape: ShapeType, + *, + mean: float | complex, + std: float, + dtype: torch.dtype, + device: torch.device, + requires_grad: bool, + generator: torch.Generator | None = None, +) -> Tensor: + a = torch.empty(shape, dtype=dtype, device=device, requires_grad=requires_grad) + with torch.no_grad(): + # NOTE: normal_ is incorrectly annotated to expect mean to be a float + a.normal_(mean, std, generator=generator) # type: ignore[arg-type] + return a + + +_normal_doc = """ + Constructs a tensor filled with values drawn from a normal distribution with the specified mean + and standard deviation. + + Only supports floating-point types. +""" + +normal = _make_prim( + schema=( + "normal(SymInt[] shape, *, Scalar mean, Scalar std, ScalarType dtype, Device device, bool requires_grad, Generator? generator=None) -> Tensor" + ), + return_type=RETURN_TYPE.NEW, + meta=_normal_meta, + impl_aten=_normal_aten, + doc=_normal_doc, +) + + +def _uniform_meta( + shape: ShapeType, + *, + low: float, + high: float, + dtype: torch.dtype, + device: torch.device, + stride: ShapeType, + generator: torch.Generator | None = None, +) -> TensorLikeType: + return TensorMeta(shape=shape, strides=stride, dtype=dtype, device=device) + + +def _uniform_aten( + shape: ShapeType, + *, + low: float, + high: float, + dtype: torch.dtype, + device: torch.device, + stride: ShapeType, + generator: torch.Generator | None = None, +) -> Tensor: + a = torch.empty_strided(shape, stride=stride, dtype=dtype, device=device) + a.uniform_(low, high, generator=generator) + return a + + +_uniform_doc = """ + Constructs a tensor filled with values drawn uniformly from low to high. +""" + +# TODO: we should more seriously review randomness modeling and prims +_uniform_helper = _make_prim( + schema=( + "uniform(SymInt[] shape, *, Scalar low, Scalar high, ScalarType dtype, " + "Device device, SymInt[] stride, Generator? generator=None) -> Tensor" + ), + return_type=RETURN_TYPE.NEW, + meta=_uniform_meta, + impl_aten=_uniform_aten, + doc=_uniform_doc, +) + +# +# FFT prims +# + + +def _fft_r2c_meta( + input: TensorLike, + *, + dim: DimsSequenceType, + onesided: bool, +) -> TensorLikeType: + dim = utils.canonicalize_dims(input.ndim, dim) + utils.validate_no_repeating_dims(dim) + + shape = list(input.shape) + if onesided: + last_dim = dim[-1] + shape[last_dim] = shape[last_dim] // 2 + 1 + + dtype = utils.corresponding_complex_dtype(input.dtype) + strides = utils.make_contiguous_strides_for(shape) + return TensorMeta(shape=shape, strides=strides, dtype=dtype, device=input.device) + + +def _fft_r2c_aten( + input: TensorLike, + *, + dim: DimsSequenceType, + onesided: bool, +) -> TensorLikeType: + normalization = 0 # No normalization + return torch._fft_r2c(input, dim, normalization, onesided) + + +_fft_r2c_doc = """ + Performs a real to complex Fast Fourier Transform +""" + + +fft_r2c = _make_prim( + schema="fft_r2c(Tensor self, *, int[] dim, bool onesided) -> Tensor", + meta=_fft_r2c_meta, + impl_aten=_fft_r2c_aten, + return_type=RETURN_TYPE.NEW, + doc=_fft_r2c_doc, +) + + +def _fft_c2c_meta( + input: TensorLike, + *, + dim: DimsSequenceType, + forward: bool, +) -> TensorLikeType: + dim = utils.canonicalize_dims(input.ndim, dim) + utils.validate_no_repeating_dims(dim) + + shape = input.shape + strides = utils.make_contiguous_strides_for(shape) + return TensorMeta( + shape=shape, strides=strides, dtype=input.dtype, device=input.device + ) + + +def _fft_c2c_aten( + input: TensorLike, + *, + dim: DimsSequenceType, + forward: bool, +) -> TensorLikeType: + normalization = 0 # No normalization + return torch._fft_c2c(input, dim, normalization, forward) + + +_fft_c2c_doc = """ + Performs either a Fast Fourier Transform, or its inverse +""" + + +fft_c2c = _make_prim( + schema="fft_c2c(Tensor self, *, int[] dim, bool forward) -> Tensor", + meta=_fft_c2c_meta, + impl_aten=_fft_c2c_aten, + return_type=RETURN_TYPE.NEW, + doc=_fft_c2c_doc, +) + + +def _fft_c2r_meta( + input: TensorLike, + *, + dim: DimsSequenceType, + last_dim_size: int, +) -> TensorLikeType: + dim = utils.canonicalize_dims(input.ndim, dim) + utils.validate_no_repeating_dims(dim) + + shape = list(input.shape) + shape[dim[-1]] = last_dim_size + dtype = utils.corresponding_real_dtype(input.dtype) + strides = utils.make_contiguous_strides_for(shape) + return TensorMeta(shape=shape, strides=strides, dtype=dtype, device=input.device) + + +def _fft_c2r_aten( + input: TensorLike, + *, + dim: DimsSequenceType, + last_dim_size: int, +) -> TensorLikeType: + normalization = 0 # No normalization + return torch._fft_c2r(input, dim, normalization, last_dim_size) + + +_fft_c2r_doc = """ + Performs a complex to real Inverse Fast Fourier Transform +""" + + +fft_c2r = _make_prim( + schema="fft_c2r(Tensor self, *, int[] dim, SymInt last_dim_size) -> Tensor", + meta=_fft_c2r_meta, + impl_aten=_fft_c2r_aten, + return_type=RETURN_TYPE.NEW, + doc=_fft_c2r_doc, +) + + +def _frexp_meta(self: TensorLikeType) -> tuple[TensorLikeType, TensorLikeType]: + torch._check( + self.dtype.is_floating_point, + lambda: "torch.frexp() only supports floating-point dtypes", + ) + return torch.empty_like(self), torch.empty_like(self, dtype=torch.int32) + + +frexp = _make_prim( + schema="frexp(Tensor self) -> (Tensor mantissa, Tensor exponent)", + meta=_frexp_meta, + return_type=(RETURN_TYPE.NEW, RETURN_TYPE.NEW), + impl_aten=torch.frexp, + doc="", +) + + +def _make_token_aten() -> TensorLikeType: + return new_token_tensor() + + +_make_token = _make_prim( + schema="_make_token() -> Tensor", + meta=_make_token_aten, + return_type=RETURN_TYPE.NEW, + impl_aten=_make_token_aten, + doc="Creates a token used for keeping track of side effects.", +) + + +def _sink_tokens_aten(tokens) -> None: + pass + + +_sink_tokens = _make_prim( + schema="_sink_tokens(Tensor[] tokens) -> ()", + meta=_sink_tokens_aten, + return_type=RETURN_TYPE.NONE, + impl_aten=_sink_tokens_aten, + doc="Sink all of the tokens which were previously used for keeping track of side effects.", +) + +torch.fx.node.has_side_effect(_sink_tokens) + + +register_rng_prims() +register_debug_prims() diff --git a/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff403d024b254e0f3f11ba32f2720224e9ac3a81 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8f0849195d66f24748563ad49d90847bf2457d0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/debug_prims.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/debug_prims.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2400b825d4384c75af596bc3bbd9ae0b6ef1f7d1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/debug_prims.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/executor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/executor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b31cc67ab77196e24c6b9f53b4148090c26bedd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/executor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/rng_prims.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/rng_prims.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28bd7cfd6a926e93fe8bce7d75faeb3d23cccaec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_prims/__pycache__/rng_prims.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_prims/context.py b/.venv/lib/python3.12/site-packages/torch/_prims/context.py new file mode 100644 index 0000000000000000000000000000000000000000..e41e3e904d85740fb6068977bd290505c0bf2d79 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_prims/context.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +import functools +from contextlib import nullcontext +from typing import Any, TYPE_CHECKING, TypeVar +from typing_extensions import ParamSpec + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + +import torch +import torch._decomp +import torch._prims +import torch._refs +import torch._refs.nn +import torch._refs.nn.functional +import torch._refs.special +import torch.overrides +from torch._prims_common import torch_function_passthrough + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +@functools.cache +def torch_to_refs_map() -> dict[Any, Any]: + """ + Mapping of torch API functions to torch._refs functions. + E.g. torch_to_refs_map()[torch.add] == torch._refs.add + """ + modules = [ + (torch, torch._refs), + (torch.nn, torch._refs.nn), + (torch.nn.functional, torch._refs.nn.functional), + (torch.special, torch._refs.special), + (torch.fft, torch._refs.fft), + (torch.linalg, torch._refs.linalg), + ] + r: dict[Any, Any] = { + torch.Tensor.__invert__: torch._refs.bitwise_not, + torch.Tensor.__xor__: torch._refs.bitwise_xor, + torch.Tensor.__and__: torch._refs.bitwise_and, + torch.Tensor.__or__: torch._refs.bitwise_or, + torch.Tensor.__eq__: torch._refs.eq, + torch.Tensor.__rsub__: torch._refs.rsub, + torch.Tensor.__rtruediv__: torch._refs.rtruediv, + torch.Tensor.__floordiv__: torch._refs.floor_divide, + torch.Tensor.__rfloordiv__: torch._refs.rfloordiv, + torch.Tensor.__pow__: torch._refs.pow, + torch.Tensor.__rpow__: torch._refs.rpow, + torch.Tensor.new_empty: torch._refs.new_empty, + torch.Tensor.new_full: torch._refs.new_full, + torch.Tensor.new_zeros: torch._refs.new_zeros, + torch.Tensor.new_ones: torch._refs.new_ones, + torch.Tensor.fill_: torch._refs.fill_, + torch.Tensor.zero_: torch._refs.zero_, + torch.Tensor.to: torch._refs.to, + torch.Tensor.sum_to_size: torch._refs.sum_to_size, + # TODO: Should these methods be mapped some other way? + torch.Tensor.copy_: torch._prims.copy_to, + torch.Tensor.resize: torch._prims.resize, + } + for mod_torch, mod_refs in modules: + for s in mod_refs.__all__: # type: ignore[attr-defined] + r[mod_torch.__dict__.get(s)] = mod_refs.__dict__.get(s) + + # Support remapping torch.Tensor.foo to _refs.foo + for s in dir(torch.Tensor): + if s in torch._refs.__all__: + r[getattr(torch.Tensor, s)] = torch._refs.__dict__.get(s) + + # Support conversions + for s in torch._refs._conversions.__all__: + tensor_attr = getattr(torch.Tensor, s, None) or getattr(torch, s) + r[tensor_attr] = torch._refs._conversions.__dict__.get(s) + + return r + + +@functools.cache +def all_prims() -> set[Any]: + """ + Set of all prim functions, e.g., torch._prims.add in all_prims() + """ + return {torch._prims.__dict__.get(s) for s in torch._prims.__all__} + + +class TorchRefsMode(torch.overrides.TorchFunctionMode): + """ + Switches the interpretation of torch.* functions and Tensor methods to + use PrimTorch refs in torch._refs. (Direct calls to _refs are unaffected.) + + >>> # xdoctest: +SKIP + >>> with TorchRefsMode(): + ... torch.add(x, y) # calls torch._refs.add(x, y) + + By default, this context manager will fall back on the torch.* if the + ref does not exist; set strict=True to error if this occurs. + If the ref exists we still would like to fall back on the torch.* sometimes, + this behavior can be customized by passing a function to should_fallback_fn. + """ + + def __init__( + self, + strict: bool = False, + should_fallback_fn: Callable[..., bool] = lambda *_: False, + prims_mode_cls: type = nullcontext, + ) -> None: + self.strict = strict + self.should_fallback_fn = should_fallback_fn + self.prims_mode_cls = prims_mode_cls + + def __torch_function__( + self, + orig_func: Callable[_P, _R], + types: Sequence[type], + args: Sequence[Any] = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + if kwargs is None: + kwargs = {} + # For primitive operations, run them as is without interception + # Unless we are in prims_mode, in which case we want to use nvprims + if orig_func in torch_function_passthrough or orig_func in all_prims(): + with self.prims_mode_cls(): + # pyrefly: ignore [invalid-param-spec] + return orig_func(*args, **kwargs) + mapping = torch_to_refs_map() + func = mapping.get(orig_func, None) + + # For torch.ops.aten.*, use registered decompositions from torch._decomp + # torch._decomp.decomposition_table provides a mapping from + # torch.ops.aten.* to torch._refs or torch._decomp.decompositions + # implementations. + # There're other ways to implement this functionality, + # see https://github.com/pytorch/pytorch/pull/82657#discussion_r939776417 + if func is None and isinstance(orig_func, torch._ops.OpOverload): + func = torch._decomp.decomposition_table.get(orig_func, None) + elif func is None and isinstance(orig_func, torch._ops.OpOverloadPacket): + default = getattr(orig_func, "default", None) + if default is None and orig_func._dir: + default = getattr(orig_func, orig_func._dir[0], None) + if default is not None: + func = torch._decomp.decomposition_table.get(default, None) + + if func is not None: + # If the ref exists query whether we should use it or not + if self.should_fallback_fn(self, orig_func, func, args, kwargs): + # pyrefly: ignore [invalid-param-spec] + return orig_func(*args, **kwargs) + # torch calls inside func should be interpreted as refs calls + with self: + return func(*args, **kwargs) + if self.strict: + raise RuntimeError( + f"no _refs support for {torch.overrides.resolve_name(orig_func)}" + ) + # pyrefly: ignore [invalid-param-spec] + return orig_func(*args, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_prims/debug_prims.py b/.venv/lib/python3.12/site-packages/torch/_prims/debug_prims.py new file mode 100644 index 0000000000000000000000000000000000000000..d8c1fb8a732eea2355ed8c829ef9927dd6160a9f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_prims/debug_prims.py @@ -0,0 +1,63 @@ +import contextlib +from collections.abc import Generator, Sequence + +import torch +from torch.utils._content_store import ContentStoreReader + + +LOAD_TENSOR_READER: ContentStoreReader | None = None + + +@contextlib.contextmanager +def load_tensor_reader(loc: str) -> Generator[None, None, None]: + global LOAD_TENSOR_READER + if LOAD_TENSOR_READER is not None: + raise AssertionError("LOAD_TENSOR_READER is already set") + # load_tensor is an "op", and we will play merry hell on + # Inductor's memory planning if we return a tensor that + # aliases another tensor that we previously returned from + # an operator. So unlike standard ContentStoreReader use, + # we disable the cache so that you always get fresh storages + # (no aliasing for you!) + LOAD_TENSOR_READER = ContentStoreReader(loc, cache=False) + try: + yield + finally: + LOAD_TENSOR_READER = None + + +def register_debug_prims() -> None: + torch.library.define( + "debugprims::load_tensor", + "(str name, int[] size, int[] stride, *, ScalarType dtype, Device device) -> Tensor", + ) + + @torch.library.impl("debugprims::load_tensor", "BackendSelect") + def load_tensor_factory( + name: str, + size: Sequence[int], + stride: Sequence[int], + dtype: torch.dtype, + device: torch.device, + ) -> torch.Tensor: + if LOAD_TENSOR_READER is None: + from torch._dynamo.testing import rand_strided + + return rand_strided(size, stride, dtype, device) + else: + from torch._dynamo.utils import clone_input + + # device argument here takes care of coercion + r = LOAD_TENSOR_READER.read_tensor(name, device=device) + if list(r.size()) != size: + raise AssertionError(f"{r.size()} != {size}") + if list(r.stride()) != stride: + raise AssertionError(f"{r.stride()} != {stride}") + if r.device != device: + raise AssertionError(f"{r.device} != {device}") + + # Unlike the other properties, we will do coercions for dtype + # mismatch + if r.dtype != dtype: + r = clone_input(r, dtype=dtype) # type: ignore[no-untyped-call] + return r diff --git a/.venv/lib/python3.12/site-packages/torch/_prims/executor.py b/.venv/lib/python3.12/site-packages/torch/_prims/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..be3245b8403593cacaf7e7ad8124dd20e5e2be5f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_prims/executor.py @@ -0,0 +1,68 @@ +from collections.abc import Callable +from typing import Any, TypeVar +from typing_extensions import ParamSpec, TypeVarTuple, Unpack + +from torch._prims.context import TorchRefsMode +from torch.fx import GraphModule +from torch.fx.experimental.proxy_tensor import make_fx, wrapper_and_args_for_make_fx + + +T = TypeVar("T") +P = ParamSpec("P") +Ts = TypeVarTuple("Ts") + + +def execute( + gm: GraphModule, + *args: Unpack[Ts], + executor: str = "aten", + executor_parameters: dict | None = None, +) -> Any: + """ + Prototype ATen executor. + + Just executes the context's graph. + """ + + if executor == "aten": + return gm.forward(*args) + + msg = f"Received unexpected value for 'executor': {executor}. Allowed values are: aten." + raise ValueError(msg) + + +def make_traced(fn: Callable[P, T]) -> Callable[P, T]: + """ + Returns a function that, when called, will + trace its torch operations to prims and then + execute those prims on the requested trace executor + (possibly lowering them to that trace executor first). + + Only supports the torch operations defined in _torch_to_reference_map + in context.py and operations with positional args. All args must + be tensors. + In the near future all these restrictions will be lifted. + + Example usage: + + def foo(a, b): + return torch.add(a, b) + + traced_foo = make_traced(foo) + + a = torch.randn((1, 2, 3, 4, 5), device='cuda') + b = torch.randn((1, 2, 3, 4, 5), device='cuda') + result = traced_foo(a, b, executor='aten') + """ + + def _traced(*args: P.args, **kwargs: P.kwargs) -> T: + executor = str(kwargs.pop("executor", "aten")) + + # TODO: caching + wrapped, all_args = wrapper_and_args_for_make_fx(fn, args, kwargs) + + with TorchRefsMode(): + gm = make_fx(wrapped)(all_args) + return execute(gm, all_args, executor=executor) + + return _traced # type: ignore[return-value] diff --git a/.venv/lib/python3.12/site-packages/torch/_prims/rng_prims.py b/.venv/lib/python3.12/site-packages/torch/_prims/rng_prims.py new file mode 100644 index 0000000000000000000000000000000000000000..ed779db9b71d3af468b5f8934e31f73e3771bf29 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_prims/rng_prims.py @@ -0,0 +1,541 @@ +# mypy: allow-untyped-defs +from typing import cast + +import torch +import torch.utils._pytree as pytree +from torch import _prims +from torch._C import DispatchKey +from torch._higher_order_ops.utils import autograd_not_implemented, register_fake +from torch._ops import HigherOrderOperator +from torch._prims_common import CUDARngStateHelper, make_contiguous_strides_for +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.types import _device, _dtype + + +def throw_on_non_cuda(device): + raise RuntimeError( + f"You are trying to functionalize a {device.type} RNG operator but {device.type} does not " + f"use Philox/counter-based RNG. Therefore, functionalizing a {device.type} RNG operator is " + "not supported. We are discussing the possibility of a Philox-based RNG implementation for CPU." + ) + + +def register_rng_prim(name, schema, impl_aten, impl_meta, doc, tags=None): + rngprim_def = torch.library.custom_op( + "rngprims::" + name, impl_aten, mutates_args=(), schema=schema + ) + + rngprim_def.register_fake(impl_meta) + + prim_packet = getattr(torch._ops.ops.rngprims, name) + prim = prim_packet.default + if tags: + prim._tags = tags + + for p in (prim_packet, prim): + p.__doc__ = doc + p.return_type = torch._prims_common.RETURN_TYPE.NEW # type: ignore[attr-defined] + + p.schema = name + schema + p.impl_aten = impl_aten + p.prim_meta_impl = impl_meta + + +# Philox rand offsets could be shared in future with other philox ops, so +# keeping these functions in global scope. +def philox_rand_offset_meta( + shape: torch.Size, +): + return _prims.TensorLike(torch.tensor(0, dtype=torch.int64)) + + +def philox_rand_offset( + shape: torch.Size, +): + # For impl, look at the function calc_execution_policy in the file + # aten/src/ATen/native/cuda/DistributionTemplates.h. The impl was copied at + # commit hash 72aa0667bd16707d50eb8fa337092a1f5d11dfb6 + numel_scalar = 1 + for dim_size in shape: + numel_scalar *= dim_size + numel = torch.scalar_tensor(numel_scalar, dtype=torch.int64) + + block_size = 256 + unroll = 4 + curand4_engine_calls = 4 + device_property = torch.cuda.get_device_properties(torch.cuda.current_device()) + blocks_per_sm = device_property.max_threads_per_multi_processor // block_size + num = cast(int, numel) + grid_size = (num + block_size - 1) // block_size + grid_size = min(grid_size, device_property.multi_processor_count * blocks_per_sm) + return ((num - 1) // (block_size * grid_size * unroll) + 1) * curand4_engine_calls + + +def register_philox_rand(): + name = "philox_rand" + schema = "(SymInt[] size, Tensor seed, Tensor offset, int[]? stride, Device? device=None, ScalarType? dtype=None) -> (Tensor, Tensor)" + + def _philox_rand_meta( + shape: torch.Size, + seed: torch.Tensor, + offset: torch.Tensor, + stride: tuple[int, ...] | None, + device: _device, + dtype: _dtype, + ): + # stride arg will be useful for distributed usecase. Currently, it's unused. + if stride is not None: + raise AssertionError(f"stride must be None, got {stride}") + stride = make_contiguous_strides_for(shape) + random_values = _prims.TensorMeta( + shape=shape, strides=stride, dtype=dtype, device=device + ) + offset = philox_rand_offset_meta(shape) + return (random_values, offset) + + def _philox_rand( + shape: torch.Size, + seed: torch.Tensor, + offset: torch.Tensor, + stride: tuple[int, ...] | None, + device: _device, + dtype: _dtype, + ): + # stride arg will be useful for distributed usecase. Currently, it's unused. + if stride is not None: + raise AssertionError(f"stride must be None, got {stride}") + if device.type == "cpu": + devices = [] + else: + devices = [device] + + if device.type != "cuda": + raise throw_on_non_cuda(device) + + with torch.random.fork_rng(devices): + CUDARngStateHelper.set_torch_state_tensor(seed, offset) + random_values = torch.rand(shape, device=device, dtype=dtype) + + return random_values, philox_rand_offset(shape) + + register_rng_prim( + name=name, + schema=schema, + impl_aten=_philox_rand, + impl_meta=_philox_rand_meta, + doc="Philox based stateless rand operator", + tags=(torch.Tag.nondeterministic_seeded,), + ) + + +def get_device(args, kwargs): + if kwargs.get("device"): + device = kwargs.get("device") + if isinstance(device, str): + device = torch.device(device) + return device.type + + for arg in args: + if isinstance(arg, torch.Tensor): + return arg.device.type + if isinstance(arg, torch.device): + return arg.type + return None + + +def register_run_and_save_rng_state_op(): + class RunAndSaveRngState(HigherOrderOperator): + def __init__(self): + super().__init__("run_and_save_rng_state", cacheable=True) + + def __call__(self, op, *args, **kwargs): + # pyrefly: ignore [missing-attribute] + return super().__call__(op, *args, **kwargs) + + run_and_save_rng_state = RunAndSaveRngState() + + run_and_save_rng_state.py_impl(DispatchKey.Autograd)( + autograd_not_implemented(run_and_save_rng_state, deferred_error=True) + ) + + @run_and_save_rng_state.py_impl(DispatchKey.CUDA) + def impl_cuda(op, *args, **kwargs): + return torch.cuda.get_rng_state(), op(*args, **kwargs) + + @run_and_save_rng_state.py_impl(DispatchKey.CPU) + def impl_cpu(op, *args, **kwargs): + return torch.get_rng_state(), op(*args, **kwargs) + + @run_and_save_rng_state.py_impl(DispatchKey.HPU) + def impl_hpu(op, *args, **kwargs): + if hasattr(torch, "hpu"): + return torch.hpu.get_rng_state(), op(*args, **kwargs) + raise RuntimeError("functionalize a hpu RNG operator is not supported.") + + @run_and_save_rng_state.py_impl(DispatchKey.XPU) + def impl_xpu(op, *args, **kwargs): + return torch.xpu.get_rng_state(), op(*args, **kwargs) + + @run_and_save_rng_state.py_impl(DispatchKey.BackendSelect) + def impl_backend_select(op, *args, **kwargs): + impl_map = { + "cuda": impl_cuda, + "cpu": impl_cpu, + "hpu": impl_hpu, + "xpu": impl_xpu, + } + device = get_device(args, kwargs) + if device not in impl_map: + raise AssertionError(f"Backend not supported for {device}") + impl = impl_map[device] + return impl(op, *args, **kwargs) + + @register_fake(run_and_save_rng_state, skip_cache=True) + def impl_fake_tensor_mode(op, *args, **kwargs): + # Check device to call the right impl + return impl_backend_select(op, *args, **kwargs) + + @run_and_save_rng_state.py_impl(ProxyTorchDispatchMode) + def impl_proxy_dispatch_mode(mode, op, *args, **kwargs): + out = impl_backend_select(op, *args, **kwargs) + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, (op, *args)) + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) + out_proxy = mode.tracer.create_proxy( + "call_function", run_and_save_rng_state, proxy_args, proxy_kwargs + ) + return track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + + return run_and_save_rng_state + + +def register_run_with_rng_state_op(): + class RunWithRngState(HigherOrderOperator): + def __init__(self): + super().__init__("run_with_rng_state", cacheable=True) + + def __call__(self, rng_state, op, *args, **kwargs): + # pyrefly: ignore [missing-attribute] + return super().__call__(rng_state, op, *args, **kwargs) + + run_with_rng_state = RunWithRngState() + + run_with_rng_state.py_impl(DispatchKey.Autograd)( + autograd_not_implemented(run_with_rng_state, deferred_error=True) + ) + + @run_with_rng_state.py_impl(DispatchKey.CUDA) + def impl_cuda(rng_state, op, *args, **kwargs): + current_state = torch.cuda.get_rng_state() + torch.cuda.set_rng_state(rng_state.cpu()) + out = op(*args, **kwargs) + torch.cuda.set_rng_state(current_state) + return out + + @run_with_rng_state.py_impl(DispatchKey.CPU) + def impl_cpu(rng_state, op, *args, **kwargs): + current_state = torch.get_rng_state() + torch.set_rng_state(rng_state) + out = op(*args, **kwargs) + torch.set_rng_state(current_state) + return out + + @run_with_rng_state.py_impl(DispatchKey.HPU) + def impl_hpu(rng_state, op, *args, **kwargs): + if hasattr(torch, "hpu"): + current_state = torch.hpu.get_rng_state() + torch.hpu.set_rng_state(rng_state) + out = op(*args, **kwargs) + torch.hpu.set_rng_state(current_state) + return out + raise RuntimeError("functionalize a hpu RNG operator is not supported.") + + @run_with_rng_state.py_impl(DispatchKey.XPU) + def impl_xpu(rng_state, op, *args, **kwargs): + current_state = torch.xpu.get_rng_state() + torch.xpu.set_rng_state(rng_state) + out = op(*args, **kwargs) + torch.xpu.set_rng_state(current_state) + return out + + @run_with_rng_state.py_impl(ProxyTorchDispatchMode) + def impl_proxy_dispatch_mode(mode, rng_state, op, *args, **kwargs): + # TODO: you don't need to do this, the dispatch here already disabled + # it + with disable_proxy_modes_tracing(): + out = run_with_rng_state(rng_state, op, *args, **kwargs) + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, (rng_state, op, *args)) + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) + out_proxy = mode.tracer.create_proxy( + "call_function", run_with_rng_state, proxy_args, proxy_kwargs + ) + return track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + + @run_with_rng_state.py_impl(DispatchKey.BackendSelect) + def impl_backend_select(rng_state, op, *args, **kwargs): + impl_map = { + "cuda": impl_cuda, + "cpu": impl_cpu, + "hpu": impl_hpu, + "xpu": impl_xpu, + } + device = get_device(args, kwargs) + if device not in impl_map: + raise AssertionError(f"Backend not supported for {device}") + impl = impl_map[device] + return impl(rng_state, op, *args, **kwargs) + + @register_fake(run_with_rng_state, skip_cache=True) + def impl_fake_tensor_mode(rng_state, op, *args, **kwargs): + # Skip setting the set_rng_state as it does not work well with fake tensors. + # And it does not matter for the fake tensor mode. + return op(*args, **kwargs) + + @run_with_rng_state.py_functionalize_impl + def impl_functional(ctx, rng_state, op, *args, **kwargs): + unwrapped_rng_state = ctx.unwrap_tensors(rng_state) + unwrapped_args = ctx.unwrap_tensors(args) + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) + + with ctx.redispatch_to_next(): + out = run_with_rng_state( + unwrapped_rng_state, op, *unwrapped_args, **unwrapped_kwargs + ) + return ctx.wrap_tensors(out) + + return run_with_rng_state + + +run_and_save_rng_state = register_run_and_save_rng_state_op() +run_with_rng_state = register_run_with_rng_state_op() + + +def _impl_graphsafe_rng(op, *args, rng_state=None, **kwargs): + # pyrefly: ignore [missing-attribute] + device_idx = rng_state.device.index + device_type = rng_state.device.type # pyrefly: ignore [missing-attribute] + device_mod = getattr(torch, device_type, None) + if device_mod is None or not hasattr(device_mod, "default_generators"): + raise AssertionError( + f"GraphSafe RNG operations not supported for device '{device_type}' " + f"(no torch.{device_type}.default_generators)" + ) + generator = device_mod.default_generators[device_idx] + current_state = generator.graphsafe_get_state() + + generator.graphsafe_set_state(rng_state) + out = op(*args, **kwargs) + generator.graphsafe_set_state(current_state) + return out + + +def register_graphsafe_run_with_rng_state_op(): + class GraphSafeRunWithRngState(HigherOrderOperator): + def __init__(self): + super().__init__("graphsafe_run_with_rng_state", cacheable=True) + + def __call__(self, op, *args, rng_state=None, **kwargs): + # pyrefly: ignore [missing-attribute] + return super().__call__(op, *args, rng_state=rng_state, **kwargs) + + graphsafe_run_with_rng_state = GraphSafeRunWithRngState() + + graphsafe_run_with_rng_state.py_impl(DispatchKey.Autograd)( + autograd_not_implemented(graphsafe_run_with_rng_state, deferred_error=True) + ) + + @graphsafe_run_with_rng_state.py_impl(DispatchKey.BackendSelect) + def impl_backend_select(op, *args, rng_state=None, **kwargs): + from torch._functorch._aot_autograd.utils import supports_graphsafe_rng + + device = get_device(args, kwargs) + if device is None or not supports_graphsafe_rng(torch.device(device)): + raise AssertionError( + f"GraphSafe RNG operations not supported for device '{device}'. " + f"Call register_graphsafe_rng_device_type('{device}') to register." + ) + return _impl_graphsafe_rng(op, *args, rng_state=rng_state, **kwargs) + + @register_fake(graphsafe_run_with_rng_state, skip_cache=True) + def impl_fake_tensor_mode(op, *args, rng_state=None, **kwargs): + return op(*args, **kwargs) + + @graphsafe_run_with_rng_state.py_impl(ProxyTorchDispatchMode) + def impl_proxy_dispatch_mode(mode, op, *args, rng_state=None, **kwargs): + with disable_proxy_modes_tracing(): + out = graphsafe_run_with_rng_state(op, *args, rng_state=rng_state, **kwargs) + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, (op, *args)) + proxy_kwargs = pytree.tree_map( + mode.tracer.unwrap_proxy, {"rng_state": rng_state, **kwargs} + ) + out_proxy = mode.tracer.create_proxy( + "call_function", graphsafe_run_with_rng_state, proxy_args, proxy_kwargs + ) + return track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + + @graphsafe_run_with_rng_state.py_functionalize_impl + def impl_functional(ctx, op, *args, rng_state=None, **kwargs): + unwrapped_rng_state = ( + ctx.unwrap_tensors(rng_state) if rng_state is not None else None + ) + unwrapped_args = ctx.unwrap_tensors(args) + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) + + with ctx.redispatch_to_next(): + out = graphsafe_run_with_rng_state( + op, *unwrapped_args, rng_state=unwrapped_rng_state, **unwrapped_kwargs + ) + return ctx.wrap_tensors(out) + + return graphsafe_run_with_rng_state + + +graphsafe_run_with_rng_state = register_graphsafe_run_with_rng_state_op() + +_registered_graphsafe_dispatch_keys: set["DispatchKey"] = set() + + +def register_graphsafe_rng_dispatch(dispatch_key: "DispatchKey") -> None: + """Register graphsafe_run_with_rng_state py_impl for a dispatch key.""" + if dispatch_key in _registered_graphsafe_dispatch_keys: + return + _registered_graphsafe_dispatch_keys.add(dispatch_key) + graphsafe_run_with_rng_state.py_impl(dispatch_key)(_impl_graphsafe_rng) + + +# Register CUDA as a graphsafe RNG device by default +register_graphsafe_rng_dispatch(DispatchKey.CUDA) + + +# Late-bind CustomClassBaseMeta as Generator's metaclass. This is done here +# rather than in THPGenerator_init (C++) to avoid making torch._C depend +# on torch._custom_class_base at init time. +from torch._custom_class_base import CustomClassBaseMeta + + +torch._C._set_generator_metaclass(CustomClassBaseMeta) + +torch._library.opaque_object.register_custom_class( + torch._C.Generator, + typ="symbolic", + guard_fn=lambda gen: [gen.device], + members={ + "device": torch._library.opaque_object.MemberType.USE_REAL, + "__eq__": torch._library.opaque_object.MemberType.USE_REAL, + "__ne__": torch._library.opaque_object.MemberType.USE_REAL, + }, +) + + +def register_run_dtensor_rng_op(): + """ + Register a higher-order operator for DTensor distributed random operations. + Takes pre-computed integer offsets (start_offset_incr, end_offset_incr), an op, + and args. Internally adjusts the RNG state using the offsets before/after + running the op. + + The offsets are computed at trace time from the DTensorSpec, so the compiled graph + contains only plain integers — no DTensorSpec or DeviceMesh objects. + """ + + class RunDTensorRngOp(HigherOrderOperator): + def __init__(self): + # Not cacheable: the compiled wrapper bakes in the current device + # (torch.cuda.set_device(N)) and the rank-dependent start/end offset + # ints; sharing the cached graph across ranks routes every rank's + # set_rng_state to one rank's device and offsets, leaving the other + # ranks' generators unchanged (#185520). + super().__init__("run_dtensor_rng_op", cacheable=False) + + def __call__(self, start_offset_incr, end_offset_incr, op, *args, **kwargs): + # pyrefly: ignore [missing-attribute] + return super().__call__( + start_offset_incr, end_offset_incr, op, *args, **kwargs + ) + + run_dtensor_rng_op = RunDTensorRngOp() + + run_dtensor_rng_op.py_impl(DispatchKey.Autograd)( + autograd_not_implemented(run_dtensor_rng_op, deferred_error=True) + ) + + @run_dtensor_rng_op.py_impl(DispatchKey.CUDA) + def impl_cuda(start_offset_incr, end_offset_incr, op, *args, **kwargs): + from torch.distributed.tensor._random import _PhiloxState + + state = _PhiloxState(torch.cuda.get_rng_state()) + old_offset = state.offset.clone() + state.offset = old_offset + start_offset_incr + + device = ( + args[0].device + if args and hasattr(args[0], "device") + else torch.device(f"cuda:{torch.cuda.current_device()}") + ) + with torch.random.fork_rng(devices=[device], device_type="cuda"): + torch.cuda.set_rng_state(state.state) + try: + out = op(*args, **kwargs) + finally: + state.offset = old_offset + end_offset_incr + + torch.cuda.set_rng_state(state.state) + return out + + @run_dtensor_rng_op.py_impl(DispatchKey.BackendSelect) + def impl_backend_select(start_offset_incr, end_offset_incr, op, *args, **kwargs): + device = get_device(args, kwargs) + if device != "cuda": + raise RuntimeError( + f"run_dtensor_rng_op only supports CUDA device, got {device}. " + f"This operator is designed for distributed random operations on CUDA." + ) + return impl_cuda(start_offset_incr, end_offset_incr, op, *args, **kwargs) + + @register_fake(run_dtensor_rng_op, skip_cache=True) + def impl_fake_tensor_mode(start_offset_incr, end_offset_incr, op, *args, **kwargs): + return op(*args, **kwargs) + + @run_dtensor_rng_op.py_impl(ProxyTorchDispatchMode) + def impl_proxy_dispatch_mode( + mode, start_offset_incr, end_offset_incr, op, *args, **kwargs + ): + with disable_proxy_modes_tracing(): + out = run_dtensor_rng_op( + start_offset_incr, end_offset_incr, op, *args, **kwargs + ) + proxy_args = pytree.tree_map( + mode.tracer.unwrap_proxy, (start_offset_incr, end_offset_incr, op, *args) + ) + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) + out_proxy = mode.tracer.create_proxy( + "call_function", run_dtensor_rng_op, proxy_args, proxy_kwargs + ) + return track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + + @run_dtensor_rng_op.py_functionalize_impl + def impl_functional(ctx, start_offset_incr, end_offset_incr, op, *args, **kwargs): + unwrapped_args = ctx.unwrap_tensors(args) + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) + + with ctx.redispatch_to_next(): + out = run_dtensor_rng_op( + start_offset_incr, + end_offset_incr, + op, + *unwrapped_args, + **unwrapped_kwargs, + ) + return ctx.wrap_tensors(out) + + return run_dtensor_rng_op + + +run_dtensor_rng_op = register_run_dtensor_rng_op() + + +def register_rng_prims(): + register_philox_rand() diff --git a/.venv/lib/python3.12/site-packages/torch/_prims_common/__init__.py b/.venv/lib/python3.12/site-packages/torch/_prims_common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9d0505b816e05aa962dce467d77d70c23cdf4aa1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_prims_common/__init__.py @@ -0,0 +1,2249 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import operator +import typing +import warnings +from collections.abc import Callable, Sequence +from contextlib import AbstractContextManager, nullcontext +from enum import Enum +from functools import reduce +from typing import ( + Any, + cast, + NamedTuple, + Optional, + overload, + TYPE_CHECKING, + TypeAlias, + TypeGuard, + TypeVar, + Union, +) +from typing_extensions import deprecated + +import torch +from torch import sym_float, sym_int, sym_max, sym_min + + +if TYPE_CHECKING: + # Import the following modules during type checking to enable code intelligence features, + # such as auto-completion in tools like pylance, even when these modules are not explicitly + # imported in user code. + + import sympy + + from torch.types import BoolLikeType + + class _WorksWithInt(typing.Protocol): + def __add__(self, other: Any) -> typing.Self: ... + + def __radd__(self, other: Any) -> typing.Self: ... + + def __mul__(self, other: Any) -> typing.Self: ... + + def __rmul__(self, other: Any) -> typing.Self: ... + + _IntLikeT = TypeVar("_IntLikeT", bound=_WorksWithInt) + + +ShapeType: TypeAlias = torch.Size | list[int] | tuple[int, ...] +StrideType: TypeAlias = list[int] | tuple[int, ...] +DimsType: TypeAlias = int | list[int] | tuple[int, ...] +DimsSequenceType: TypeAlias = list[int] | tuple[int, ...] +# TODO: Type[torch.SymInt], Type[torch.SymFloat] +NumberTypeType: TypeAlias = type[bool] | type[int] | type[float] | type[complex] +# TODO: This needs a lot more type annotations +# NumberType = Union[bool, int, float, complex, torch.SymInt, torch.SymFloat] +NumberType: TypeAlias = bool | int | float | complex +RealNumberType: TypeAlias = bool | int | float + +Number = (bool, int, float, complex, torch.SymInt, torch.SymFloat, torch.SymBool) +# I don't call it Integral because numbers.Integral includes bool, but IntLike +# does not +Dim = int +IntLike = (int, torch.SymInt) +FloatLike = (float, torch.SymFloat) +BoolLike = (bool, torch.SymBool) +IntWithoutSymInt = int +FloatWithoutSymFloat = float +DeviceLikeType: TypeAlias = str | torch.device | int +Tensor = torch.Tensor + + +torch_function_passthrough = { + torch.device, + torch.sym_not, + torch.sym_float, + torch.sym_int, + torch.sym_max, + torch.sym_min, + torch._sym_sqrt, # type: ignore[attr-defined] + torch.sym_ite, + torch.Tensor.dim, + torch.Tensor.ndim.__get__, # type: ignore[attr-defined] + torch.Tensor.numel, + torch.Tensor.size, + torch.Tensor.storage_offset, + torch.Tensor.stride, + torch.Tensor.dtype.__get__, # type: ignore[attr-defined] + torch.Tensor.is_sparse.__get__, # type: ignore[attr-defined] + torch.Tensor.shape.__get__, # type: ignore[attr-defined] + torch.Tensor.device.__get__, # type: ignore[attr-defined] + torch.Tensor.requires_grad.__get__, # type: ignore[attr-defined] + torch.Tensor.layout.__get__, # type: ignore[attr-defined] + torch.Tensor.is_contiguous, + # For TorchRefsMode only + torch.Tensor.__format__, + torch.Tensor.__repr__, + torch.Tensor.requires_grad.__get__, # type: ignore[attr-defined] + torch.Tensor.__getitem__, +} + + +TensorLikeType = torch.Tensor +TensorLike = torch.Tensor +TensorSequenceType: TypeAlias = list[TensorLikeType] | tuple[TensorLikeType, ...] +TensorOrNumberLikeType: TypeAlias = TensorLikeType | NumberType + +CustomOutParamAnnotation = "__custom_out_param__" + + +def same_shape(a: ShapeType, b: ShapeType, *, allow_rhs_unbacked=False) -> bool: + from torch.fx.experimental.symbolic_shapes import guard_or_true + + if len(a) != len(b): + return False + + for x, y in zip(a, b): + if allow_rhs_unbacked: + if isinstance(y, torch.SymInt): + continue + + # if we do not know, then they are not the same. + if guard_or_true(x != y): + return False + + return True + + +def _maybe_get_pytype(t): + if t is torch.SymFloat: + return float + elif t is torch.SymInt: + return int + elif t is torch.SymBool: + return bool + else: + return t + + +# TODO: look at using torch.testing.assert_close instead with an option +# to just compare metadata +def compare_tensor_meta( + a: TensorLikeType, + b: TensorLikeType, + check_sizes=True, + check_strides=False, + *, + allow_rhs_unbacked=False, + check_conj=True, +): + """ + Checks that two tensor likes have the same shape, + dtype and device. + + In the future this will validate additional metadata, like + strides. + """ + from torch._subclasses.fake_tensor import MetadataMismatchError + + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") + if not isinstance(b, TensorLike): + raise AssertionError(f"b must be TensorLike, got {type(b)}") + + if check_sizes and not same_shape( + a.shape, b.shape, allow_rhs_unbacked=allow_rhs_unbacked + ): + msg = f"Shapes {a.shape} and {b.shape} are not equal!" + raise MetadataMismatchError(msg) + + if a.dtype != b.dtype: + msg = f"Dtypes {a.dtype} and {b.dtype} are not equal!" + raise MetadataMismatchError(msg) + + if a.device != b.device: + # Handles special cuda:0 vs cuda case + # TODO: we should review why this happens and see about fixing it + if (str(a.device) == "cuda:0" or str(a.device) == "cuda") and ( + str(b.device) == "cuda:0" or str(b.device) == "cuda" + ): + pass + else: + msg = f"Devices {a.device} and {b.device} are not equal!" + raise MetadataMismatchError(msg) + + # Stride checking is currently disabled, see https://github.com/pytorch/pytorch/issues/78050 + if check_strides: + same_strides, idx = check_significant_strides( + a, b, only_cuda=False, allow_rhs_unbacked=allow_rhs_unbacked + ) + if not same_strides: + msg = f"Stride mismatch! Strides are {a.stride()} and {b.stride()} (mismatched at {idx})!" + raise MetadataMismatchError(msg) + + if a.storage_offset() != b.storage_offset(): + msg = f"Storage offset mismatch! Storage offsets are {a.storage_offset()} and {b.storage_offset()}!" + raise MetadataMismatchError(msg) + + if check_conj: + if a.is_conj() != b.is_conj(): + raise MetadataMismatchError( + f"Conj mismatch! is_conj is set to {a.is_conj()} and {b.is_conj()}" + ) + + if a.is_neg() != b.is_neg(): + raise MetadataMismatchError( + f"Neg mismatch! is_neg is set to {a.is_neg()} and {b.is_neg()}" + ) + + +def _check_strides_helper( + a: TensorLikeType, + b: TensorLikeType, + *, + only_cuda=True, + significant_only=True, + allow_rhs_unbacked=False, +) -> tuple[bool, int | None]: + from torch.fx.experimental.symbolic_shapes import guard_or_false + + # NOTE: only on CUDA because CPU elementwise strides are incorrect in PyTorch + # See https://github.com/pytorch/pytorch/issues/77553 + # Only compares strides that are "meaningful" -- strides for dimensions with length > 1 + # and for tensors with more than one element. Use guard_or_false on the + # numel gate so unbacked shapes don't trigger a data-dependent guard. + if ( + not only_cuda or a.device.type == "cuda" or b.device.type == "cuda" + ) and guard_or_false(a.numel() > 0): + for idx in range(a.ndim): + check = not significant_only or a.shape[idx] > 1 + # TODO: Check the symbols are consistent with each other + if isinstance(b.stride()[idx], torch.SymInt): + continue + if a.stride()[idx] != b.stride()[idx] and check: + return False, idx + + return True, None + + +def check_significant_strides( + a: TensorLikeType, b: TensorLikeType, *, only_cuda=True, allow_rhs_unbacked=False +) -> tuple[bool, int | None]: + return _check_strides_helper( + a, + b, + only_cuda=only_cuda, + significant_only=True, + allow_rhs_unbacked=allow_rhs_unbacked, + ) + + +def check_all_strides( + a: TensorLikeType, b: TensorLikeType, *, only_cuda=True +) -> tuple[bool, int | None]: + return _check_strides_helper(a, b, only_cuda=only_cuda, significant_only=False) + + +def check_contiguous_sizes_strides(sizes, strides, false_if_dde=False): + """ + Performs an equality check between actual stride & expected stride (based on composed sizes), + handling contiguous stride representations: + e.g. torch.empty(u0, u1, u2).contiguous().stride() -> (Max(1, u1) * Max(1, u2), Max(1, u2), 1) + and we'd like to treat this equal to (u1 * u2, u2, 1) for comparison purposes. + """ + + from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + guard_or_true, + is_nested_int, + ) + + def eval_eager(x): + return bool(x) + + maybe_guard_or_false = guard_or_false if false_if_dde else eval_eager + maybe_guard_or_true = guard_or_true if false_if_dde else eval_eager + + expected_stride = 1 + expected_stride_max = 1 + + # pyrefly: ignore [bad-assignment] + for x, y in reversed(tuple(zip(sizes, strides))): + # Skips checking strides when a dimension has length 1. + if maybe_guard_or_false(x == 1): + continue + + if maybe_guard_or_true(y != expected_stride) and maybe_guard_or_true( + y != expected_stride_max + ): + return False + + # We symbolically check both paths to maximize the cases where this function + # returns true. This is because make_contiguous_strides_for adds the max + # symbolically, and in some other situations the max might not be there. + # And we want to ensure we return true in both cases. + expected_stride_max *= x if is_nested_int(x) else sym_max(x, 1) # type:ignore[assignment] + + expected_stride *= x + + return True + + +# This function is equivalent to compute_contiguous() from TensorImpl.cpp +def is_contiguous(a: TensorLikeType, false_if_dde=False) -> bool: + """ + Tests whether a tensor is contiguous or not. + + Tensors are contiguous when they have no elements, + one element, or when they have "nested" strides. + """ + from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + guard_size_oblivious, + ) + + def eval_eager(x): + return bool(x) + + maybe_guard_or_false = guard_or_false if false_if_dde else eval_eager + + if maybe_guard_or_false(a.numel() < 2): + return True + + return check_contiguous_sizes_strides( + a.shape, a.stride(), false_if_dde=false_if_dde + ) + + +# This function is equivalent to compute_channels_last_contiguous_2d() in TensorImpl.cpp +def is_channels_last_contiguous_2d(a: Tensor, false_if_dde=False) -> bool: + # NHWC or not channels last 2D contiguous + if a.ndim != 4: + return False + + from torch.fx.experimental.symbolic_shapes import guard_or_false, guard_or_true + + def eval_eager(x): + return bool(x) + + maybe_guard_or_false = guard_or_false if false_if_dde else eval_eager + maybe_guard_or_true = guard_or_true if false_if_dde else eval_eager + + expected_stride = 1 + for idx in (1, 3, 2, 0): + length = a.shape[idx] + if maybe_guard_or_false(length == 1): + continue + + stride = a.stride()[idx] + if maybe_guard_or_true(stride != expected_stride): + return False + + expected_stride *= length + + return True + + +def is_channels_last_contiguous_3d(a: Tensor, false_if_dde=False) -> bool: + # NDHWC or not channels last 3D contiguous + if a.ndim != 5: + return False + + from torch.fx.experimental.symbolic_shapes import guard_or_false, guard_or_true + + def eval_eager(x): + return bool(x) + + maybe_guard_or_false = guard_or_false if false_if_dde else eval_eager + maybe_guard_or_true = guard_or_true if false_if_dde else eval_eager + + expected_stride = 1 + for idx in (1, 4, 3, 2, 0): + length = a.shape[idx] + if maybe_guard_or_false(length == 1): + continue + + stride = a.stride()[idx] + if maybe_guard_or_true(stride != expected_stride): + return False + + expected_stride *= length + + return True + + +_memory_formats = { + torch.contiguous_format, + torch.preserve_format, + torch.channels_last, + torch.channels_last_3d, +} + + +def validate_memory_format(memory_format: torch.memory_format): + torch._check( + memory_format in _memory_formats, + lambda: f"Received unknown memory format {memory_format}!", + ) + + +def is_contiguous_for_memory_format( # type: ignore[return] + a: Tensor, + *, + memory_format: torch.memory_format, + false_if_dde=False, + # pyrefly: ignore [bad-return] +) -> bool: + validate_memory_format(memory_format) + + if memory_format == torch.contiguous_format: + return is_contiguous(a, false_if_dde) + if memory_format == torch.channels_last: + return is_channels_last_contiguous_2d(a, false_if_dde) + if memory_format == torch.channels_last_3d: + return is_channels_last_contiguous_3d(a, false_if_dde) + + torch._check( + False, + lambda: f"is_contiguous received unsupported memory format {memory_format}", + ) + + +def is_contiguous_or_false(a: TensorLikeType) -> bool: + return is_contiguous(a, false_if_dde=True) + + +# similar to is_channels_last_contiguous_2d but return false on data dependency. +def is_channels_last_contiguous_or_false_2d(a: Tensor) -> bool: + return is_channels_last_contiguous_2d(a, false_if_dde=True) + + +# similar to is_channels_last_contiguous_3d but return false on data dependency. +def is_channels_last_contiguous_or_false_3d(a: Tensor) -> bool: + return is_channels_last_contiguous_3d(a, false_if_dde=True) + + +# similar to is_contiguous_for_memory_format but return false on data dependency. +def is_contiguous_for_memory_format_or_false( # type: ignore[return] + a: Tensor, *, memory_format: torch.memory_format +) -> bool: + return is_contiguous_for_memory_format( + a, memory_format=memory_format, false_if_dde=True + ) + + +# NOTE: that tensors with no elements and channels last is ??? +def is_channels_last_contiguous(a: Tensor) -> bool: + """ + True when a tensor is channels-last contiguous. + + This requires that: + + - the tensor is conceptually either 4 (NHWC) or 5 (NDHWC) dimensions + - if we name the tensor's dimensions NCHW or NCDHW, then the strides are such that the + stride of the 'C' dimension (Cs) is 1 and the strides corresponding to + each dimension (Xs) can be ordered Cs <= Ws <= Hs <= (Ds) <= Ns and are + "nested" -- so Ws = Cs * Cl, where Cl is the length of the 'C' dimension, + for example. + """ + return is_channels_last_contiguous_2d(a) or is_channels_last_contiguous_3d(a) + + +# similar to is_channels_last_contiguous but return false on data dependency. +def is_channels_last_contiguous_or_false(a: Tensor) -> bool: + return is_channels_last_contiguous_or_false_2d( + a + ) or is_channels_last_contiguous_or_false_3d(a) + + +# Defined at module scope so the class is built once, not rebuilt on every call. +class K(NamedTuple): + size: int + stride: int + + def __lt__(self, other): + from torch.fx.experimental.symbolic_shapes import guard_or_false, guard_or_true + + # for backed symbols, this is practically a < operation + # for unbacked, we return True if < is statically known, + # then try to answer this symbolically, with stride ordering semantics + # (e.g. u0 < u0 is False, u0 < u1 is False with no axioms, u0 < 2 * u0 is True) + return ( + guard_or_false( + self.stride < other.stride + ) # checks statically known inequality + or ( + ( + guard_or_false(self.stride == 0) + or guard_or_false(other.stride % self.stride == 0) + ) + and guard_or_true(self.stride != other.stride) + ) # checks symbolic inequality (e.g. u0 < 2048 * u0) + ) + + +def _is_non_overlapping_and_dense_or_false(sizes, strides) -> bool: + """ + Helper function for is_non_overlapping_and_dense. + For unbacked sizes & strides, returns True only if symbolically non-overlapping & dense, + and False otherwise. + + e.g. sizes: [u0, u1], strides: [u2, u3] + this may be non-overlapping & dense at runtime, for values {u0: 4, u1: 4, u2: 4, u3: 1}, + but isn't true for all values. + """ + from torch.fx.experimental.symbolic_shapes import guard_or_false + from torch.utils._sympy.functions import Max + + # Short-circuits for 0/1-element tensors + if guard_or_false(prod(sizes) < 2): # type: ignore[operator] + return True + + # Short-circuits for tensors of rank one, which are + # non-overlapping and "dense" if their stride is one + if len(sizes) == 1: + return guard_or_false(strides[0] == 1) + + # Checks that there exists a permutation of the strides s.t. the tensor would be contiguous + # Sorts (length, stride) pairs by stride + # + # This sort is done in a size-oblivious way, which helps if we do a + # comparison like 2048*u0 > u0; we just want this to return True + # (and not worry about what if u0 is zero). + lengths_and_strides = sorted(map(K, sizes, strides)) + + # verify actual strides match the expected (composed sizes) + sizes = [x.size for x in lengths_and_strides][::-1] + strides = [x.stride for x in lengths_and_strides][::-1] + return check_contiguous_sizes_strides(sizes, strides, false_if_dde=True) + + +def is_non_overlapping_and_dense_or_false(a: Tensor) -> bool: + """ + True when a tensor is non-overlapping and dense. + + A tensor is non-overlapping and dense when there exists a permutation of + its dimensions that is contiguous. + """ + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if a.is_sparse: + return False + + return _is_non_overlapping_and_dense_or_false(a.shape, a.stride()) + + +# NOTE: Based on the implementation in TensorIterator.cpp, but note that +# the note [Computing output strides] is incorrect, because it +# says that strides will be preserved even if they are not +# "non overlapping and dense", but this is incorrect. The +# output of elementwise operations are always given +# non overlapping and dense strides. +# This is also INCORRECT because it does not model TensorIterator's +# short-circuit, which can cause different strides. +def compute_elementwise_output_logical_to_physical_perm( + *tensors, _skip_checks=False, ambiguity_check=False +) -> tuple[list[int], bool]: + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if not _skip_checks and len(tensors) == 0: + msg = "Can't compute elementwise output strides for zero tensors!" + raise ValueError(msg) + + if not _skip_checks: + check_same_shape(*tensors, allow_cpu_scalar_tensors=True) + + # Filters the tensors to actual tensors + if not _skip_checks: + tensors = tuple( + a + for a in tensors + if isinstance(a, TensorLike) and not is_cpu_scalar_tensor(a) + ) + + # Short-circuits for CPU scalar case + if len(tensors) == 0: + return [], False + + # Short-circuits for shapes with zero or one dimensions + # TODO: are these necessary? + ndim = tensors[0].ndim + if ndim == 0: + return [], False + if ndim == 1: + return [0], False + + # Short-circuits if contiguous or channels last, following the fake fast path. + # This reduces the number of guards we end up making + is_contiguous = True + is_channels_last = True + for t in tensors: + is_contiguous = is_contiguous and is_contiguous_for_memory_format_or_false( + t, memory_format=torch.contiguous_format + ) + is_channels_last = ( + is_channels_last + and is_contiguous_for_memory_format_or_false( + t, memory_format=torch.channels_last + ) + ) + + if is_contiguous and not is_channels_last: + return list(range(ndim)), False + + if is_channels_last and not is_contiguous: + return [0, *list(range(2, ndim)), 1], False + + shape = tensors[0].shape + + def should_swap(idx_a, idx_b): + def ge(a, b): + """ + Returns true if a is symbolically greater than or equal to b, assuming a >= 0, b >= 0. + """ + if guard_or_false(b == 0): + return True + elif guard_or_false(a == 0): + return False + return guard_or_false(a >= b) or guard_or_false(a % b == 0) + + for tensor in tensors: + stride_a = tensor.stride()[idx_a] + stride_b = tensor.stride()[idx_b] + + if guard_or_false(stride_a == 0) or guard_or_false(stride_b == 0): + continue + + if guard_or_false(stride_a == stride_b): + if ge(shape[idx_b], shape[idx_a]): + continue + return 1 + + if ge(stride_b, stride_a): + return -1 + + if ge(stride_a, stride_b): + return 1 + + # Note: this case is hit if all strides are zero, + # or all strides are equal and all dimensions have the same length + return 0 + + # The "sort" order for the permutation is back-to-front, but + # the natural order for permutations is front-to-back. Do the + # sorting back-to-front and then reverse it on output. + # + # also, note this returns the logical to physical shape permutation + perm = list(reversed(range(ndim))) + + # insertion sort with support for ambiguous comparisons + for i in range(1, ndim): + dim1 = i + for dim0 in reversed(range(i)): + comparison = should_swap(perm[dim0], perm[dim1]) + if comparison > 0: + perm[dim0], perm[dim1] = perm[dim1], perm[dim0] + dim1 = dim0 + elif comparison < 0: + break + + # verify we've imposed ordering if ambiguity_check=True + raise_ambiguous = False + if ambiguity_check: + for i, j in zip(range(ndim - 1), range(1, ndim)): + order = should_swap(perm[i], perm[j]) + if order != -1: + raise_ambiguous = True + break + + return list(reversed(perm)), raise_ambiguous + + +def compute_elementwise_output_strides(*tensors) -> tuple[int, ...]: + """ + Computes the output strides for elementwise operations. + """ + if len(tensors) == 0: + msg = "Can't compute elementwise output strides for zero tensors!" + raise ValueError(msg) + + check_same_shape(*tensors, allow_cpu_scalar_tensors=True) + + # Filters the tensors to actual tensors + tensors = tuple( + a for a in tensors if isinstance(a, TensorLike) and not is_cpu_scalar_tensor(a) + ) + + # Short-circuits for CPU scalar case + if len(tensors) == 0: + return () + + ndim = tensors[0].ndim + shape = tensors[0].shape + + if ndim == 0: + return () + if ndim == 1: + return (1,) + + if len(tensors) == 1: + if torch._prims_common.is_non_overlapping_and_dense_or_false(tensors[0]): + return tensors[0].stride() + else: + empty_like_tensor = torch.empty_like(tensors[0]) + return empty_like_tensor.stride() + + logical_to_physical_perm, _ = compute_elementwise_output_logical_to_physical_perm( + *tensors, _skip_checks=True + ) + permuted_shape = apply_perm(shape, logical_to_physical_perm) # to physical + + new_strides = make_contiguous_strides_for(permuted_shape) + permuted_strides = apply_perm( + new_strides, invert_perm(logical_to_physical_perm) + ) # to logical + + return tuple(permuted_strides) + + +# Identity permutation is [0, 1, 2] +def apply_perm(inp, perm): + ndim = len(inp) + permuted_inp = [-1] * ndim + for idx, x in enumerate(perm): + permuted_inp[idx] = inp[x] + return permuted_inp + + +def invert_perm(perm): + ndim = len(perm) + new_perm = [-1] * ndim + for idx, x in enumerate(perm): + new_perm[x] = idx + return new_perm + + +# +# Common helper functions +# + + +def validate_dim_length(length: int): + """ + Validates that an object represents a valid + dimension length. + """ + + if isinstance(length, (int, torch.SymInt)): + torch._check(length >= 0) + else: + # sometimes called with sympy expression by inductor + if length < 0: + raise AssertionError(f"length must be non-negative, got {length}") + + +def validate_shape(shape: ShapeType): + """ + Validates that a sequence represents a valid shape. + """ + + if not isinstance(shape, Sequence): + raise AssertionError(f"shape must be a Sequence, got {type(shape)}") + for l in shape: + validate_dim_length(l) + + +def validate_strides(strides: StrideType): + """ + Verifies the object specifies valid strides. + """ + + if not isinstance(strides, Sequence): + raise AssertionError(f"strides must be a Sequence, got {type(strides)}") + for stride in strides: + if stride < 0: + raise AssertionError(f"stride must be non-negative, got {stride}") + + +def validate_idx(rank: int, idx: int): + """ + Validates that idx is a valid index for the given shape. + Assumes the index is already canonicalized. + """ + + if not isinstance(idx, Dim): + raise AssertionError(f"idx must be Dim, got {type(idx)}") + if not isinstance(rank, Dim): + raise AssertionError(f"rank must be Dim, got {type(rank)}") + + if not (idx >= 0 and idx < rank or idx == 0): + raise AssertionError(f"idx {idx} is out of bounds for rank {rank}") + + +def validate_dimension_indices(rank: int, indices: DimsSequenceType): + for idx in indices: + validate_idx(rank, idx) + + +def validate_exclusive_idx(rank: int, ex_idx: int): + """ + Validates that ex_idx is a valid exclusive index + for the given shape. + """ + + if not isinstance(ex_idx, Dim): + raise AssertionError(f"ex_idx must be Dim, got {type(ex_idx)}") + if not isinstance(rank, Dim): + raise AssertionError(f"rank must be Dim, got {type(rank)}") + if not (ex_idx > 0 and ex_idx <= rank): + raise AssertionError( + f"ex_idx {ex_idx} is out of bounds for rank {rank} (must be in (0, rank])" + ) + + +# "Wraps" a dim (up to one time) for the given rank, allowing dims to be +# specified using negative indices. If `wrap_scalar` is true then scalar +# tensors of rank 0 will allow dimensions in the range [-1, 0]. Otherwise, +# idx should be in the range [-rank, rank-1]. +def canonicalize_dim(rank: int, idx: int, wrap_scalar: bool = True) -> int: + if rank < 0: + msg = f"Rank cannot be negative but got {rank}" + raise IndexError(msg) + + if rank == 0: + if not wrap_scalar: + msg = f"Dimension specified as {idx} but tensor has no dimensions" + raise IndexError(msg) + rank = 1 + + if idx >= 0 and idx < rank: + return idx + + if idx < 0: + _idx = idx + rank + else: + _idx = idx + + if _idx < 0 or _idx >= rank: + # Same error message as in aten/src/ATen/WrapDimUtils.h:49 + msg = f"Dimension out of range (expected to be in range of [{-rank}, {rank - 1}], but got {idx})" + raise IndexError(msg) + + return _idx + + +# Takes a dimension or sequence of dimensions and "wraps" them, +# mapping negative offsets to positive ones +@overload +def canonicalize_dims( + rank: int, + indices: Sequence[int], + wrap_scalar: bool = True, + # pyrefly: ignore [bad-return] +) -> tuple[int, ...]: + pass + + +@overload +# pyrefly: ignore [bad-return] +def canonicalize_dims(rank: int, indices: int, wrap_scalar: bool = True) -> int: + pass + + +def canonicalize_dims(rank, indices, wrap_scalar=True): + if isinstance(indices, Dim): + return canonicalize_dim(rank, indices, wrap_scalar) + + return tuple(canonicalize_dim(rank, x, wrap_scalar) for x in indices) + + +def is_valid_permutation(rank: int, perm: DimsSequenceType) -> bool: + """ + Validates that perm is a permutation of length rank. + """ + + return isinstance(perm, Sequence) and sorted(perm) == list(range(rank)) + + +def is_same_shape(a: Sequence, b: Sequence) -> BoolLikeType: + """ + Compares two shapes a and b, returning True if they are the same + (their ranks and corresponding lengths match) and False otherwise. + + Uses sym_eq for shape comparison so the result is safe to pass to + torch._check on tensors with unbacked SymInt dimensions; for backed + or concrete shapes the behaviour is unchanged. + """ + from torch.fx.experimental.symbolic_shapes import sym_eq + + return sym_eq(tuple(a), tuple(b)) + + +def is_cpu_scalar_tensor(a: object) -> TypeGuard[TensorLike]: + return isinstance(a, TensorLike) and a.ndim == 0 and a.device.type == "cpu" + + +def check_same_device(*args, allow_cpu_scalar_tensors): + """ + Checks that all Tensors in args have the same device. + + Raises a RuntimeError when: + - args contains an object whose type is not Tensor or Number + - two Tensor objects in args have different devices, unless one is a CPU scalar tensor and allow_cpu_scalar_tensors is True + """ + # Short-circuits if all (one or fewer) arguments are trivially on the same device + if len(args) <= 1: + return + + # Note: cannot initialize device to the first arg's device (it may not have one) + device = None + # pyrefly: ignore [bad-assignment] + for arg in args: + if isinstance(arg, Number): + continue + elif isinstance(arg, TensorLike): + if allow_cpu_scalar_tensors and is_cpu_scalar_tensor(arg): + continue + + if device is None: + device = arg.device + + if device != arg.device: + msg = ( + "Tensor on device " + + str(arg.device) + + " is not on the expected device " + + str(device) + + "!" + ) + raise RuntimeError(msg) + else: + msg = ( + "Unexpected type when checking for same device, " + str(type(arg)) + "!" + ) + raise RuntimeError(msg) + + +def canonicalize_device(device: DeviceLikeType) -> torch.device: + if isinstance(device, torch.device): + return device + + if not isinstance(device, str): + raise AssertionError(f"device must be torch.device or str, got {type(device)}") + return torch.device(device) + + +# Asserts if any of the following are true: +# - a non-scalar or non-Tensor is given +# - the shape of any tensors is distinct +def check_same_shape(*args, allow_cpu_scalar_tensors: bool): + """ + Checks that all Tensors in args have the same shape. + + Raises a RuntimeError when: + - args contains an object whose type is not Tensor or Number + - two Tensor objects in args have different devices + """ + shape = None + + # pyrefly: ignore [bad-assignment] + for arg in args: + if isinstance(arg, Number): + continue + elif isinstance(arg, TensorLike): + if allow_cpu_scalar_tensors and is_cpu_scalar_tensor(arg): + continue + + if shape is None: + shape = arg.shape + + if not is_same_shape(shape, arg.shape): + msg = f"Shape {arg.shape} is not the expected shape {shape}!" + raise RuntimeError(msg) + else: + msg = ( + "Unexpected type when checking for same shape, " + str(type(arg)) + "!" + ) + raise RuntimeError(msg) + + +# Acquires a common shape, if it exists, from one or more tensor arguments, +# filtering number arguments +def extract_shape(*args, allow_cpu_scalar_tensors: bool) -> ShapeType | None: + shape = None + scalar_shape = None + + # pyrefly: ignore [bad-assignment] + for arg in args: + if isinstance(arg, Number): + continue + elif isinstance(arg, TensorLike): + if allow_cpu_scalar_tensors and is_cpu_scalar_tensor(arg): + scalar_shape = arg.shape + continue + + if shape is None: + shape = arg.shape + + if not is_same_shape(shape, arg.shape): + return None + else: + return None + + return shape if shape is not None else scalar_shape + + +# Extracts dimensions that might be passed either as a list/tuple or as varargs. +# A typical case is Tensor.permute . +def extract_dims_from_varargs( + dims: DimsSequenceType | tuple[DimsSequenceType, ...], +) -> DimsSequenceType: + if dims and isinstance(dims[0], Sequence): + if len(dims) != 1: + raise AssertionError( + f"Expected exactly 1 element in dims when first element is a Sequence, got {len(dims)}" + ) + dims = cast(tuple[DimsSequenceType], dims) + return dims[0] + else: + return cast(DimsSequenceType, dims) + + +def extract_shape_from_varargs( + shape: ShapeType | tuple[ShapeType], + validate=True, +) -> tuple[int, ...]: + """ + Returns a shape from varargs. + + In PyTorch, operations that accept shapes often accept them as varargs, like + foo(*shape). However a user can pass the shape as a sequence of integers, + like this: + + foo(1, 2, 3) + + or as a sequence of integers + + foo((1, 2, 3)) + + In the first case shape will be a tuple of integers, and in the second case it's a tuple + containing a tuple of integers. This validates those inputs and canonicalizes them + to a tuple of integers. + """ + + # Handles tuple unwrapping + if len(shape) == 1 and isinstance(shape[0], Sequence): + # pyrefly: ignore [bad-assignment] + shape = shape[0] + + if validate: + validate_shape(shape) # type: ignore[arg-type] + return shape # type: ignore[return-value] + + +def infer_size_shapes(a: ShapeType, b: ShapeType) -> tuple[int, ...]: + ndim = max(len(a), len(b)) + expandedSizes = [0] * ndim + + for i in range(ndim - 1, -1, -1): + offset = ndim - 1 - i + dimA = len(a) - 1 - offset + dimB = len(b) - 1 - offset + sizeA = a[dimA] if dimA >= 0 else 1 + sizeB = b[dimB] if dimB >= 0 else 1 + + torch._check( + (sizeA == sizeB) or (sizeA == 1) or (sizeB == 1), + lambda: ( + f"The size of tensor a ({sizeA}) must match the size of " + f"tensor b ({sizeB}) at non-jagged dimension {i}" + ), + ) + + # 1s map to the other size (even 0) + expandedSizes[i] = sizeB if sizeA == 1 else sizeA + + return tuple(expandedSizes) + + +def infer_size(shape: ShapeType, numel: int) -> tuple[int, ...]: + """ + Infers the size of a dim with size -1, if it exists. + Also checks that new shape is compatible with the number of elements. + """ + from torch.fx.experimental.symbolic_shapes import guard_or_false + + dim = None + newsize = 1 + for i, d in enumerate(shape): + if guard_or_false(d == -1): + torch._check(dim is None, lambda: "only one dimension can be inferred") + dim = i + else: + torch._check( + d >= 0, + lambda: ( + f"invalid shape dimension {d}. If this was symbolic, it was assumed to not be -1." + "If this was meant to be inferred, please explicitly pass in -1." + ), + ) + newsize *= d + if dim is None: + torch._check( + numel == newsize, + lambda: f"shape '{list(shape)}' is invalid for input of size {numel}", + ) + else: + torch._check( + newsize != 0, + lambda: ( + f"cannot reshape tensor of 0 elements into shape {list(shape)} because the " + f"unspecified dimension size -1 can be any value and is ambiguous" + if guard_or_false(numel == 0) + else f"shape '{list(shape)}' is invalid for input of size {numel}" + ), + ) + torch._check( + numel % newsize == 0, + lambda: f"shape '{list(shape)}' is invalid for input of size {numel}", + ) + # Convert to list to produce a compatible error message with core + # PyTorch, which prints sequences in square brackets. + shape = list(shape) + shape[dim] = numel // newsize + torch._check(shape[dim] >= 0) + return tuple(shape) + + +_integer_dtypes = ( + torch.uint8, + torch.uint16, + torch.uint32, + torch.uint64, + torch.int8, + torch.int16, + torch.int32, + torch.int64, +) +_low_precision_dtypes = ( + torch.float16, + torch.bfloat16, + torch.complex32, + torch.bcomplex32, +) +_complex_dtypes = (torch.complex32, torch.bcomplex32, torch.complex64, torch.complex128) + + +def is_boolean_dtype(dtype: torch.dtype) -> bool: + if not isinstance(dtype, torch.dtype): + raise AssertionError(f"Expected torch.dtype, got {type(dtype)}") + return dtype is torch.bool + + +def is_integer_dtype(dtype: torch.dtype) -> bool: + if not isinstance(dtype, torch.dtype): + raise AssertionError(f"Expected torch.dtype, got {type(dtype)}") + return dtype in _integer_dtypes + + +def is_low_precision_dtype(dtype: torch.dtype) -> bool: + if not isinstance(dtype, torch.dtype): + raise AssertionError(f"Expected torch.dtype, got {type(dtype)}") + return dtype in _low_precision_dtypes + + +def is_float_dtype(dtype: torch.dtype) -> bool: + if not isinstance(dtype, torch.dtype): + raise AssertionError(f"Expected torch.dtype, got {type(dtype)}") + return dtype.is_floating_point + + +def is_complex_dtype(dtype: torch.dtype) -> bool: + if not isinstance(dtype, torch.dtype): + raise AssertionError(f"Expected torch.dtype, got {type(dtype)}") + return dtype in _complex_dtypes + + +def is_grad_dtype(dtype: torch.dtype) -> bool: + """ + Checks if the dtype can require a gradient. + """ + return dtype.is_floating_point or is_complex_dtype(dtype) + + +_complex_to_real_dtype_map = { + torch.complex128: torch.float64, + torch.complex64: torch.float32, + torch.complex32: torch.float16, + torch.bcomplex32: torch.bfloat16, +} + +_real_to_complex_dtype_map = { + torch.float16: torch.complex32, + torch.bfloat16: torch.bcomplex32, + torch.float32: torch.complex64, + torch.float64: torch.complex128, +} + + +def corresponding_real_dtype(dtype: torch.dtype) -> torch.dtype: + return _complex_to_real_dtype_map[dtype] + + +def corresponding_complex_dtype(dtype: torch.dtype) -> torch.dtype: + return _real_to_complex_dtype_map[dtype] + + +def dtype_to_type(dtype: torch.dtype) -> type: + """ + Computes the corresponding Python type (AKA "type kind") for the + given dtype. + """ + if not isinstance(dtype, torch.dtype): + raise AssertionError(f"Expected torch.dtype, got {type(dtype)}") + + if dtype is torch.bool: + return bool + if dtype in _integer_dtypes: + return int + if dtype.is_floating_point: + return float + if dtype in _complex_dtypes: + return complex + + raise ValueError("Invalid dtype!") + + +def dtype_to_type_ctor(dtype: torch.dtype) -> Callable[[NumberType], NumberType]: + """ + Computes the corresponding Python type constructor for the + given dtype. + """ + if not isinstance(dtype, torch.dtype): + raise AssertionError(f"Expected torch.dtype, got {type(dtype)}") + + if dtype is torch.bool: + return lambda x: bool(x) + if dtype in _integer_dtypes: + return sym_int + if dtype.is_floating_point: + # pyrefly: ignore [bad-return] + return sym_float + if dtype in _complex_dtypes: + # TODO: type error here is real, replace with sym_complex + return lambda x: complex(x) # type: ignore[arg-type] + + raise ValueError("Invalid dtype!") + + +def type_to_dtype(typ: type) -> torch.dtype: + """ + Computes the corresponding dtype for a Number type. + """ + + if not isinstance(typ, type): + raise AssertionError(f"Expected type, got {type(typ)}") + + if typ in (bool, torch.SymBool): + return torch.bool + if typ in (int, torch.SymInt): + return torch.long + if typ in (float, torch.SymFloat): + return torch.get_default_dtype() + # TODO: sym_complex_float? + if typ is complex: + return corresponding_complex_dtype(torch.get_default_dtype()) + + raise ValueError(f"Invalid type {typ}!") + + +def get_dtype(x: torch.Tensor | NumberType): + if isinstance(x, torch.Tensor): + return x.dtype + else: + return type_to_dtype(type(x)) + + +_ordered_types = (bool, int, float, complex) + + +def check_fp_or_complex( + dtype: torch.dtype, fn_name: str, allow_low_precision_dtypes: bool = True +): + """ + Checks whether the input is floating point or complex. + If allow_low_precision_dtypes is True, it allows having float16, bfloat16, and [b]complex32 + """ + torch._check( + is_float_dtype(dtype) or is_complex_dtype(dtype), + lambda: f"{fn_name}: Expected a floating point or complex tensor as input. Got {dtype}", + ) + torch._check( + allow_low_precision_dtypes or not is_low_precision_dtype(dtype), + lambda: f"{fn_name}: Half precision dtypes not supported. Got {dtype}", + ) + + +def check_is_matrix(A: TensorLikeType, f_name: str, arg_name: str = "A"): + torch._check( + len(A.shape) >= 2, + lambda: f"{f_name}: The input tensor {arg_name} must have at least 2 dimensions.", + ) + + +def get_higher_type(a: type, b: type) -> type: + """ + Returns the higher of the two given Number types. + + The types are ordered bool -> int -> float -> complex. + """ + a, b = _maybe_get_pytype(a), _maybe_get_pytype(b) + # Type checking + if a not in _ordered_types or b not in _ordered_types: + raise RuntimeError(f"Expected builtin numeric types, found {a}, {b}") + + if a is b: + return a + + for typ in _ordered_types: + if a is typ: + return b + if b is typ: + return a + + raise ValueError("Unknown Python scalar type!") + + +# Returns the higher of two torch datatypes a and b or, if the two +# are not ordered relative to each other, the next +# higher datatype +def get_higher_dtype( + a: torch.dtype | TensorLikeType | NumberType | None, + b: torch.dtype | TensorLikeType | NumberType | None, +) -> torch.dtype | None: + """ + Computes the "lowest" datatype that is weakly + "higher" than both a and b. + """ + + # Type checking + if a is not None and not isinstance(a, (torch.dtype, TensorLike, Number)): + raise AssertionError( + f"a must be None, torch.dtype, TensorLike, or Number, got {type(a)}" + ) + if b is not None and not isinstance(b, (torch.dtype, TensorLike, Number)): + raise AssertionError( + f"b must be None, torch.dtype, TensorLike, or Number, got {type(b)}" + ) + + def _extract_dtype( + x: torch.dtype | TensorLikeType | NumberType | None, + ) -> torch.dtype | None: + if x is None: + return None + if isinstance(x, torch.dtype): + return x + if isinstance(x, TensorLike): + return x.dtype + if isinstance(x, Number): + return type_to_dtype(type(x)) + + raise RuntimeError("Unexpected type given to _extract_dtype!") + + a, b = _extract_dtype(a), _extract_dtype(b) + + if a is b: + return a + + if a is None: + return b + + if b is None: + return a + + ordered_datatypes = ( + (torch.bool,), + (torch.uint8, torch.int8), + (torch.int16,), + (torch.int32,), + (torch.int64,), + (torch.float16, torch.bfloat16), + (torch.float32,), + (torch.float64,), + (torch.complex32, torch.bcomplex32), + (torch.complex64,), + (torch.complex128,), + ) + + for idx, dtypes in enumerate(ordered_datatypes): + if a in dtypes and b in dtypes: + return ordered_datatypes[idx + 1][0] + if a in dtypes: + return b + if b in dtypes: + return a + + raise RuntimeError("Unexpected termination!") + + +def check_pin_memory(pin_memory: bool): + torch._check_not_implemented( + not pin_memory, lambda: "PrimTorch does not support pinned memory" + ) + + +def check_layout(layout: torch.layout): + torch._check_not_implemented( + layout == torch.strided, lambda: f"PrimTorch doesn't support layout={layout}" + ) + + +# TODO: maybe unify with can_cast_to? +def is_weakly_lesser_type(a: type, b: type) -> bool: + """ + Compares two types, a and b, returning True if a is weakly "less" than b. + + The comparison is determined by the following type ordering: bool, int, float, complex. + """ + + a, b = _maybe_get_pytype(a), _maybe_get_pytype(b) + + if a not in _ordered_types or b not in _ordered_types: + raise RuntimeError(f"Expected builtin numeric types, found {a}, {b}") + + for typ in _ordered_types: + if a == typ: + return True + if b == typ: + return False + + raise RuntimeError("Unexpected termination!") + + +def can_safe_cast_to(*, cast_to: torch.dtype, cast_from: torch.dtype) -> bool: + for fn in (is_complex_dtype, is_float_dtype, is_integer_dtype, is_boolean_dtype): + if fn(cast_to): + return True + if fn(cast_from): + return False + + raise ValueError(f"Received unknown dtypes {cast_to}, {cast_from}!") + + +def check_same_dtype(*args): + """ + Checks that all Tensors in args have the same device and that all Numbers have the + same corresponding Python type. + + Raises a RuntimeError when: + - args contains an object whose type is not Tensor or Number + - two Tensors objects in args have different dtypes + - two Number objects in args have different types + - there are Tensors and Numbers in args, and one of those Tensors corresponding + Python types is different from the type of one of those Numbers + """ + full_dtype = None + scalar_type = None + + # pyrefly: ignore [bad-assignment] + for arg in args: + if isinstance(arg, Number): + # Scalar type checking is disabled (and may be removed in the future) + continue + # if scalar_type is None: + # scalar_type = type(arg) + + # if scalar_type is not type(arg): + # msg = ( + # "Scalar of type " + # + str(type(arg)) + # + " is not the expected type of " + # + str(scalar_type) + # + "!" + # ) + # raise RuntimeError(msg) + elif isinstance(arg, TensorLike): + if full_dtype is None: + full_dtype = arg.dtype + if scalar_type is None: + scalar_type = dtype_to_type(arg.dtype) + + if full_dtype is not arg.dtype: + msg = ( + "Tensor with dtype " + + str(arg.dtype) + + " is not the expected dtype of " + + str(full_dtype) + + "!" + ) + raise RuntimeError(msg) + + arg_type = dtype_to_type(arg.dtype) + if arg_type is not scalar_type: + msg = ( + "Tensor with corresponding Python type " + + str(arg_type) + + " is not the expected type of " + + str(scalar_type) + + "!" + ) + raise RuntimeError(msg) + else: + msg = ( + "Unexpected type when checking for same dtype, " + str(type(arg)) + "!" + ) + raise RuntimeError(msg) + + +# Maps datatypes to their computation types for elementwise operations +_computation_dtype_map = { + torch.bfloat16: torch.float32, + torch.float16: torch.float32, + torch.complex32: torch.complex64, + torch.bcomplex32: torch.complex64, +} + + +def get_computation_dtype(dtype: torch.dtype) -> torch.dtype: + return _computation_dtype_map.get(dtype, dtype) + + +_cpu_acc_type_map = { + torch.bfloat16: torch.float64, + torch.float16: torch.float64, + torch.float32: torch.float64, + torch.complex32: torch.complex128, + torch.complex64: torch.complex128, +} + + +def get_acc_type(dtype: torch.dtype, device: torch.device) -> torch.dtype: + # Equivalent to at::toAccumulateType, prefer computation_dtype where possible + if device.type == "cpu": + return _cpu_acc_type_map.get(dtype, dtype) + else: + return get_computation_dtype(dtype) + + +class ELEMENTWISE_TYPE_PROMOTION_KIND(Enum): + DEFAULT = (0,) + NO_OPMATH = (1,) + INT_TO_FLOAT = (2,) + ALWAYS_BOOL = (3,) + COMPLEX_TO_FLOAT = (4,) + BOOL_TO_LONG = (5,) + + +class REDUCTION_OUTPUT_TYPE_KIND(Enum): + SAME = (0,) + COMPLEX_TO_FLOAT = (1,) # for complex types outputs corresponding real type + KEEP_PROMOTED_TYPE = (2,) # keep output in opmath type, needed for mean + ALWAYS_BOOL = (3,) + + +# Describes the return type of the primitive: +# +# - NEW, a new tensor is created +# - VIEW, a view of an input tensor is returned +# - INPLACE, one or more input tensors is modified +# +# these descriptors are mutually exclusive and exhaustive. +class RETURN_TYPE(Enum): + NEW = (0,) + VIEW = (1,) + INPLACE = (2,) + NONE = (3,) + + +# TODO: when NumberType contains the sym types, can simplify this +def number_type( + x: NumberType | torch.SymInt | torch.SymFloat | torch.SymBool, +) -> type: + if isinstance(x, torch.SymInt): + return int + elif isinstance(x, torch.SymFloat): + return float + elif isinstance(x, torch.SymBool): + return bool + else: + return type(x) + + +def expr_type(x: sympy.Basic) -> type: + import sympy + + if x.kind is sympy.core.kind.BooleanKind: + return bool + elif x.is_integer: # type: ignore[attr-defined] + return int + else: + # NB: Not strictly correct, but we don't support SymPy complex or bool. + return float + + +# TODO: document type promotion kinds +def elementwise_dtypes( + *_args, + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND, +) -> tuple[torch.dtype, torch.dtype]: + """ + Computes the computation and result dtypes for elementwise type promotion + on the given arguments and with the given elementwise type promotion kind. + + Note that not all inputs to an elementwise operation necessarily participate in type promotion. + For example, the "alpha" parameter of torch.add does not participate in type promotion, + although it may be cast to the Python type corresponding to the computation dtype that + the type promotion algorithm determines. + + Default elementwise type promotion, which all other type promotion kinds tweak (see below), + first decides which of four ordered types to use: + + bool -> integer -> floating point -> complex + + The selected type is the "lowest" type in the above list such that all number arguments + have a weakly "lower" type and all tensor arguments have a weakly lower corresponding + type for their dtype. + + Once the type is determined, the particular result dtype is found. The dtypes are + partially ordered as follows: + + bool -> uint8, int8 -> int16 -> int32 -> int64 -> + float16, bfloat16 -> float32 -> float64 -> complex32, bcomplex32 -> complex64 -> complex128 + + The result dtype is selected by: + - if no tensor's dtype has the same corresponding type as the one selected, + then the result dtype is the (default) dtype corresponding to the selected type + (for example, 1.5 + an integer tensor has a result dtype of the default floating point dtype) + - if the result type is complex then the dtype is: + - the default complex dtype if there are no floating point or complex tensors + - if there are floating point or complex tensors with one or more dimensions, then + the complex dtype corresponding to the highest corresponding complex dtype among those tensors + (for example, double + cfloat -> cdouble) + - if there are only floating point or complex tensors with zero dimensions, then + the complex dtype corresponding to the highest corresponding complex dtype among those tensors + - if the first two cases do not apply, the result dtype is the highest dtype among + all tensors with one or more dimensions of the output type, and if there are no such + tensors then it's the highest dtype among all tensors with zero dimensions of the output type + (for example, long + half -> half, even if the half tensor has zero dimensions) + + The "corresponding complex dtypes" are: + float16 -> complex32 + bfloat16 -> bcomplex32 + float32 -> complex64 + float64 -> complex128 + complex32 -> complex32 + complex64 -> complex64 + complex128 -> complex128 + + The DEFAULT type promotion kind computes per above, and then uses the result dtype to pick a computation + dtype by mapping low precision floating point and complex dtypes as follows: + + float16 -> float32 + bfloat16 -> bcomplex32 + complex32 -> complex64 + + This is referred to as "op math", and the NO_OPMATH type promotion kind disables this mapping, making the + computation dtype the same as the result dtype when it's selected. NO_OPMATH is appropriate for kernels + which perform no mathematical operations on their tensors (see below for examples). + + The INT_TO_FLOAT type promotion kind maps boolean and integer result dtypes to the default floating point dtype, + and computation dtypes to the appropriate op math dtype. + + The COMPLEX_TO_FLOAT type promotion kind maps complex result dtypes to the corresponding float dtype, following this + mapping: + + complex32 -> float16 + complex64 -> float32 + complex128 -> float64 + + Note that COMPLEX_TO_FLOAT derives the computation dtype as the DEFAULT setting does. + + The BOOL_TO_LONG type promotion kind maps boolean computation and result dtypes to long. + + The ALWAYS_BOOL type promotion kind always sets the result dtype to bool. + + Example operators for each type promotion option: + DEFAULT : add + NO_OPMATH : where, nextafter, cat + INT_TO_FLOAT : sin + COMPLEX_TO_FLOAT : abs + BOOL_TO_LONG : pow + ALWAYS_BOOL : eq + + """ + + args = tuple(x for x in _args if x is not None) + + highest_type: type = bool + + # Import sympy locally, as importing it eagerly at a module level is too slow + # See https://dev-discuss.pytorch.org/t/delving-into-what-happens-when-you-import-torch/1589 + import sympy + + for x in args: + if not isinstance(x, (Number, TensorLike, sympy.Basic)): + msg = f"Unexpected type {str(type(x))} when computing elementwise type promotion!" + raise ValueError(msg) + + if isinstance(x, Number): + highest_type = get_higher_type(highest_type, number_type(x)) + elif isinstance(x, sympy.Basic): + highest_type = get_higher_type(highest_type, expr_type(x)) + else: + # x is a TensorLike + highest_type = get_higher_type(highest_type, dtype_to_type(x.dtype)) + + result_dtype = None + + def _find_highest_dtype_filtered( + args, filter, *, float_as_complex=False + ) -> torch.dtype | None: + zero_dim_tensor_dtype = None + one_plus_dim_tensor_dtype = None + for x in args: + if isinstance(x, TensorLike) and filter(x.dtype): + _dtype = x.dtype + if float_as_complex and is_float_dtype(_dtype): + _dtype = corresponding_complex_dtype(_dtype) + if x.ndim == 0: + zero_dim_tensor_dtype = get_higher_dtype( + zero_dim_tensor_dtype, _dtype + ) + else: + # x.ndim > 0 + one_plus_dim_tensor_dtype = get_higher_dtype( + one_plus_dim_tensor_dtype, _dtype + ) + + # Prefers dtype of tensors with one or more dimensions + if one_plus_dim_tensor_dtype is not None: + return one_plus_dim_tensor_dtype + + return zero_dim_tensor_dtype + + if highest_type is float: + result_dtype = _find_highest_dtype_filtered(args, is_float_dtype) + result_dtype = ( + torch.get_default_dtype() if result_dtype is None else result_dtype + ) + elif highest_type is complex: + result_dtype = _find_highest_dtype_filtered( + args, + lambda x: is_float_dtype(x) or is_complex_dtype(x), + float_as_complex=True, + ) + if result_dtype is None: + result_dtype = corresponding_complex_dtype(torch.get_default_dtype()) + elif highest_type is int: + result_dtype = _find_highest_dtype_filtered(args, is_integer_dtype) + result_dtype = torch.long if result_dtype is None else result_dtype + else: + # highest_type is bool + result_dtype = torch.bool + + if type_promotion_kind is ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT: + return get_computation_dtype(result_dtype), result_dtype + elif type_promotion_kind is ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH: + return result_dtype, result_dtype + elif type_promotion_kind is ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT: + if is_integer_dtype(result_dtype) or is_boolean_dtype(result_dtype): + result_dtype = torch.get_default_dtype() + return get_computation_dtype(result_dtype), result_dtype + elif type_promotion_kind is ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT: + # NOTE: computation can still occur in a complex dtype + computation_dtype = get_computation_dtype(result_dtype) + if is_complex_dtype(result_dtype): + result_dtype = corresponding_real_dtype(result_dtype) + return computation_dtype, result_dtype + elif type_promotion_kind is ELEMENTWISE_TYPE_PROMOTION_KIND.BOOL_TO_LONG: + if is_boolean_dtype(result_dtype): + return torch.long, torch.long + return get_computation_dtype(result_dtype), result_dtype + elif type_promotion_kind is ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL: + return get_computation_dtype(result_dtype), torch.bool + else: + raise ValueError(f"Unknown type promotion kind {str(type_promotion_kind)}") + + +def reduction_dtypes( + arg, + output_dtype_kind: REDUCTION_OUTPUT_TYPE_KIND, + dtype: torch.dtype | None = None, +) -> tuple[torch.dtype, torch.dtype | None]: + # even though some reductions, like amin or amax, don't strictly require type promotion, + # all the math ops (including comparisons) are still defined only for a computation type, + # so promotion will still happen. We are doing it explicitly here + inp_dtype = dtype if dtype is not None else arg.dtype + computation_dtype = get_computation_dtype(inp_dtype) + if ( + output_dtype_kind == REDUCTION_OUTPUT_TYPE_KIND.SAME + or output_dtype_kind == REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT + ): + result_dtype = dtype if dtype else arg.dtype + if ( + output_dtype_kind == REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT + and is_complex_dtype(result_dtype) + ): + result_dtype = corresponding_real_dtype(result_dtype) + elif output_dtype_kind == REDUCTION_OUTPUT_TYPE_KIND.KEEP_PROMOTED_TYPE: + result_dtype = None + else: # ALWAYS_BOOL + result_dtype = torch.bool + return computation_dtype, result_dtype + + +# This function's logic is borrowed from the following functions defined in C++: +# batched_matrix_contiguous_strides and contiguous_strides +def make_contiguous_strides_for( + shape: ShapeType, row_major: bool = True +) -> tuple[_IntLikeT | int, ...]: + """ + Returns the strides of a contiguous tensor if row_major + If row_major=True, it returns the strides of a contiguous batch of Fortran-contiguous matrices + This is often used when calling external libraries like BLAS/LAPACK/cuSolver... + """ + # contiguous_strides from c10/util/strides.h + validate_shape(shape) + if not shape: + return () + + from torch.fx.experimental.symbolic_shapes import is_nested_int + + multiplier: _IntLikeT | int = 1 + strides = [] + for l in reversed(shape): + strides.append(multiplier) + multiplier *= l if is_nested_int(l) else sym_max(l, 1) # type:ignore[assignment] + + result = tuple(reversed(strides)) + + # batched_matrix_contiguous_strides from aten/src/ATen/native/LinearAlgebraUtils.h + if row_major: + return result + else: + if len(shape) < 2: + return result + # Use sym_max to handle unbacked symbolic dimensions + return result[:-2] + (1, sym_max(shape[-2], 1)) # type: ignore[return-value] + + +def make_channels_last_1d_strides_for( + shape: Sequence[_IntLikeT], +) -> tuple[_IntLikeT | int, ...]: + torch._check( + len(shape) == 3, + lambda: "Only tensors of rank 3 can use the channels_last_1d memory format", + ) + + multiplier: _IntLikeT | int = 1 + strides: list[_IntLikeT | int] = [0] * 3 + for idx in (1, -1, 0): + # NOTE: intentional divergence from make_contiguous_strides_for + # This is consistent with eager + strides[idx] = multiplier + multiplier *= shape[idx] + + return tuple(strides) + + +def make_channels_last_2d_strides_for( + shape: Sequence[_IntLikeT], +) -> tuple[_IntLikeT | int, ...]: + # TODO: maybe inform the user of channels_last_3d if rank of the tensor is 5? + torch._check( + len(shape) == 4, + lambda: "Only tensors of rank 4 can use the channels_last memory format", + ) + + multiplier: _IntLikeT | int = 1 + strides: list[_IntLikeT | int] = [0] * 4 + for idx in (1, -1, -2, 0): + # NOTE: intentional divergence from make_contiguous_strides_for + # This is consistent with eager + strides[idx] = multiplier + multiplier *= shape[idx] + + return tuple(strides) + + +def make_channels_last_3d_strides_for( + shape: Sequence[_IntLikeT], +) -> tuple[_IntLikeT | int, ...]: + torch._check( + len(shape) == 5, + lambda: "Only tensors of rank 5 can use the channels_last_3d memory format", + ) + + multiplier: _IntLikeT | int = 1 + strides: list[_IntLikeT | int] = [0] * 5 + for idx in (1, -1, -2, -3, 0): + # NOTE: intentional divergence from make_contiguous_strides_for + # This is consistent with eager + strides[idx] = multiplier + multiplier *= shape[idx] + + return tuple(strides) + + +def make_channels_last_strides_for( + shape: Sequence[_IntLikeT], +) -> tuple[_IntLikeT | int, ...]: + ndim = len(shape) if isinstance(shape, Sequence) else 1 + if ndim == 3: + return make_channels_last_1d_strides_for(shape) + elif ndim == 4: + return make_channels_last_2d_strides_for(shape) + elif ndim == 5: + return make_channels_last_3d_strides_for(shape) + else: + raise RuntimeError( + f"no channels last format strides exist in {ndim} dimensions" + ) + + +def compute_reduction_output_shape( + shape: ShapeType, dimensions: Sequence +) -> tuple[int, ...]: + for idx in dimensions: + validate_idx(len(shape), idx) + + new_shape = [] + for idx in range(len(shape)): + if idx in dimensions: + continue + + new_shape.append(shape[idx]) + + return tuple(new_shape) + + +def validate_no_repeating_dims(dims: Sequence): + if len(dims) != len(set(dims)): + raise RuntimeError("duplicate value in the list of dims") + + +def reduction_dims(shape: ShapeType, dims: Sequence | None) -> tuple[int, ...]: + if dims is None: + return tuple(range(len(shape))) + dims = tuple(canonicalize_dim(len(shape), idx) for idx in dims) + validate_no_repeating_dims(dims) + return dims + + +def set_correction( + unbiased: bool | None = None, + correction: NumberType | None = None, +) -> float: + if correction is not None and unbiased is not None: + raise RuntimeError("cannot specify both correction and unbiased arguments") + elif correction is None and unbiased is None: + correction = 1.0 + elif correction is None and unbiased is not None: + correction = 0.0 if unbiased is False else 1.0 + # NB: we don't actually support symint here, but it's harmless to accept + if not isinstance(correction, (IntLike, FloatLike)): + raise ValueError("correction argument should be integer or float") + # pyrefly: ignore [bad-return] + return sym_float(correction) + + +def compute_required_storage_length( + shape: ShapeType, strides: StrideType, storage_offset: int +) -> int: + """Computes the minimum storage size to hold the given tensor geometry. + + Example + ======= + + This is the size of a newly allocated tensor's storage, in units of elements + + >>> t = torch.empty((10, 20)) + >>> compute_required_storage_length(t.shape, t.stride(), t.storage_offset()) + 200 + + >>> # xdoctest: +SKIP(failing) + >>> t2 = torch.empty_strided((1, 2, 3), (5, 7, 11)) + >>> size = compute_required_storage_length( + ... t2.shape, t2.stride(), t2.storage_offset() + ... ) + >>> size == t.storage().size() + True + + A valid tensor may have a larger storage size, but never smaller + + >>> slice = torch.empty(100)[20:40] + >>> slice.storage().size() + 100 + + >>> compute_required_storage_length( + ... slice.shape, slice.stride(), slice.storage_offset() + ... ) + 40 + + """ + from torch.fx.experimental.symbolic_shapes import guard_or_false + + # Short-circuits if the shape has no elements + # Note: we are unsafely assuming tensor is not empty here, without + # runtime assertions. + if guard_or_false(reduce(operator.mul, shape, 1) == 0): + return 0 + + max_offset = sum((x - 1) * y for x, y in zip(shape, strides)) + # +1 to account for the first element which offsets are taken from + return 1 + storage_offset + max_offset + + +def check_in_bounds_for_storage( + a: torch.TypedStorage, shape: ShapeType, strides: StrideType, storage_offset: int +): + """ + Determines if the given shape, strides, and offset are valid for the given storage. + """ + + required_length = compute_required_storage_length(shape, strides, storage_offset) + if a.size() < required_length: + msg = ( + f"Can't view a storage of size {a.size()} with an offset of {storage_offset}, " + f"shape of {str(shape)}, and strides of {str(strides)}, " + f"which requires a storage of size {required_length}" + ) + raise ValueError(msg) + + +# NOTE: This function should ideally be removed, but some Meta internal models +# packaged with `torch.package` are using it, so it will have to be removed +# at some point in the future when those models no longer use this function. +@deprecated( + "`torch._prims_common.check` is deprecated and will be removed in the future. " + "Please use `torch._check*` functions instead.", + category=FutureWarning, +) +def check( + b: bool, s: Callable[[], str], exc_type: type[Exception] = RuntimeError +) -> None: + """ + Helper function for raising an error_type (default: RuntimeError) if a boolean condition fails. + Error message is a callable producing a string (to avoid wasting time + string formatting in non-error case, and also to make it easier for torchdynamo + to trace.) + + .. note:: This function is planned for removal in the future. Please use + `torch._check*` functions instead. + """ + torch._check_with(exc_type, b, s) + + +# This combines is_channels_last_strides_2d and is_channels_last_strides_3d in +# c10/core/MemoryFormat.h into one function +# May return False when input sizes are data-dependent and the property is not +# determined. +def are_strides_like_channels_last_or_false( + shape: Sequence[int], strides: Sequence[int] +) -> bool: + from torch.fx.experimental.symbolic_shapes import ( + guard_or_true, + statically_known_true, + ) + + ndim = len(shape) + + if ndim == 4: + # Check for channels_last_2d + dim_order = [1, 3, 2, 0] + elif ndim == 5: + # Check for channels_last_3d + dim_order = [1, 4, 3, 2, 0] + else: + return False + + if guard_or_true(strides[1] == 0): + return False + + min = 0 + for d in dim_order: + if guard_or_true(shape[d] == 0): + return False + if guard_or_true(strides[d] < min): + return False + if d == 0 and min == strides[1]: + return False + min = strides[d] + # Only multiply by shape[d] when size >= 1, matching C++ logic + # shape[d]!=0 hence we know its >=1 here + min *= shape[d] + return True + + +def suggest_memory_format(x: TensorLikeType) -> torch.memory_format: + """DDE-safe Python equivalent of ``Tensor.suggest_memory_format()``. + + Returns ``torch.channels_last`` for 4D tensors with NHWC-pattern strides, + ``torch.channels_last_3d`` for 5D NDHWC, otherwise ``torch.contiguous_format``. + Uses ``are_strides_like_channels_last_or_false`` internally — when + contiguity can't be statically decided (e.g., unbacked symbolic strides), + falls back to ``contiguous_format`` instead of raising a data-dependent + error. Mirrors eager ``Tensor.suggest_memory_format()`` (with the default + ``channels_last_strides_exact_match=false``) for inputs eager would also + classify the same way. + """ + if x.layout != torch.strided: + return torch.contiguous_format + + if are_strides_like_channels_last_or_false(x.shape, x.stride()): + return torch.channels_last if x.ndim == 4 else torch.channels_last_3d + + return torch.contiguous_format + + +def prod(xs: Sequence[NumberType]) -> NumberType: + """Product of elements in input sequence. Returns 1 for empty sequence""" + return reduce(operator.mul, xs, 1) + + +def is_expandable_to(shape: ShapeType, desired: ShapeType) -> bool: + """Checks if a shape can be expanded to another shape. + This is equivalent to checking if the two shapes are broadcastable. + """ + # This is a Python implementation of + # aten/src/ATen/ExpandUtils.h:is_expandable_to + if len(shape) > len(desired): + return False + for i in range(len(shape)): + if shape[-i - 1] != desired[-i - 1] and shape[-i - 1] != 1: + return False + return True + + +def mask_tensor(mask: TensorLikeType, t: TensorLikeType): + """ + Similar to torch.where(mask, t, 0) but if t is boolean, + result is also boolean and not promoted to int. + """ + # torch.where(mask, t, False) is equivalent + # but feels hacky and might break in the future + if t.dtype is torch.bool: + return mask.logical_and(t) + else: + return torch.where(mask, t, 0) + + +def get_aten_op(fn: Callable, name: str): + """ + Given the __module__ of reference and its name, it returns + (our best guess of) the ATen name of the associated operation + + Note: In ATen, the __name__ of a function within a module often + starts by the module name. E.g. linalg_eigh, or special_zeta + """ + module = fn.__module__ + prefix = "torch._refs" + if not module.startswith(prefix): + raise AssertionError(f"module must start with {prefix}, got {module}") + module = module[len(prefix) :] + # We want to go from .special / .nn.functional + # to special and special_ / nn_functional_ + if module: + module = module[1:] + module = module.replace(".", "_") + module = module + "_" + return getattr(torch._ops.ops.aten, f"{module}{name}") + + +def dtype_or_default(dtype: torch.dtype | None) -> torch.dtype: + return dtype if dtype is not None else torch.get_default_dtype() + + +def device_or_default(device: DeviceLikeType | None) -> DeviceLikeType: + return device if device is not None else torch.device("cpu") + + +def layout_or_default(layout: torch.layout | None) -> torch.layout: + return layout if layout is not None else torch.strided + + +def clone_preserve_strides(x): + needed_size = compute_required_storage_length( + x.size(), x.stride(), x.storage_offset() + ) + # Our eager implementations for *_scatter ops are all primitives w.r.t autograd, + # so these as_strided() calls are not seen by autograd. + # We need to mimic this behavior in our ref/prim implementations. + # TODO: a better way to handle this would be with a new op, "_unsafe_as_strided" + # We should revisit this when we add a compositional as_strided op, + # and also as part of https://github.com/pytorch/pytorch/issues/90507 + try: + old = torch._C._dispatch_tls_is_dispatch_key_excluded( + torch._C.DispatchKey.ADInplaceOrView + ) + torch._C._dispatch_tls_set_dispatch_key_excluded( + torch._C.DispatchKey.ADInplaceOrView, True + ) + buffer = torch.as_strided(x, (needed_size,), (1,), 0).clone() + return torch.as_strided(buffer, x.size(), x.stride(), x.storage_offset()) + finally: + torch._C._dispatch_tls_set_dispatch_key_excluded( + torch._C.DispatchKey.ADInplaceOrView, old + ) + + +def alert_not_deterministic(caller: str): + if torch.are_deterministic_algorithms_enabled(): + if torch.is_deterministic_algorithms_warn_only_enabled(): + warnings.warn( + f"{caller} does not have a deterministic implementation, but you set " + f"'torch.use_deterministic_algorithms(True, warn_only=True)'. " + f"You can file an issue at https://github.com/pytorch/pytorch/issues " + f"to help us prioritize adding deterministic support for this operation.", + stacklevel=2, + ) + else: + torch._check( + False, + lambda: ( + f"{caller} does not have a deterministic implementation, but you set " + f"'torch.use_deterministic_algorithms(True)'. You can turn off " + f"determinism just for this operation, or you can use the " + f"'warn_only=True' option, if that's acceptable for your application. " + f"You can also file an issue at https://github.com/pytorch/pytorch/issues " + f"to help us prioritize adding deterministic support for this operation." + ), + ) + + +class CUDARngStateHelper: + @staticmethod + def get_torch_state_as_tuple( + fake_mode: AbstractContextManager[Any] = nullcontext(), + ): + if not torch.cuda.is_available(): + raise RuntimeError("CUDA not available") + + with fake_mode: + seed = torch.tensor(torch.cuda.initial_seed()) + offset = torch.tensor(torch.cuda._get_rng_state_offset()) + return seed, offset + + @staticmethod + def set_torch_state_tensor(seed, offset): + # Rng state is [64-bit seed, 64-bit offset] + seed_portion = seed.reshape([1]).view(torch.uint8) + offset_portion = offset.reshape([1]).view(torch.uint8) + new_state = torch.cat([seed_portion, offset_portion]) + torch.cuda.set_rng_state(new_state) + + @staticmethod + def set_new_offset(relative_offset): + torch.cuda._set_rng_state_offset(relative_offset.item()) diff --git a/.venv/lib/python3.12/site-packages/torch/_prims_common/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_prims_common/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50019575e32f89ff7206876cbc0886cf09e56091 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_prims_common/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_prims_common/__pycache__/wrappers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_prims_common/__pycache__/wrappers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fdacb3af73139548aea33d2e8d68503b4718cb3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_prims_common/__pycache__/wrappers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_prims_common/wrappers.py b/.venv/lib/python3.12/site-packages/torch/_prims_common/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..1eeb62a325a6701539ed7754f3009c3cfdf0dae3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_prims_common/wrappers.py @@ -0,0 +1,508 @@ +# mypy: allow-untyped-defs +import inspect +import types +import typing +import warnings +from collections.abc import Callable, Sequence +from functools import wraps +from types import GenericAlias +from typing import NamedTuple, overload, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch._prims_common as utils +from torch._prims_common import ( + CustomOutParamAnnotation, + ELEMENTWISE_TYPE_PROMOTION_KIND, + Number, + NumberType, + ShapeType, + TensorLike, + TensorLikeType, +) +from torch.utils import _pytree as pytree +from torch.utils._inspect import _fast_bind +from torch.utils._pytree import tree_flatten, tree_unflatten + + +_T = TypeVar("_T") +_P = ParamSpec("_P") + + +@overload +# pyrefly: ignore [bad-return] +def _maybe_convert_to_dtype(a: TensorLikeType, dtype: torch.dtype) -> TensorLikeType: + pass + + +@overload +# pyrefly: ignore [bad-return] +def _maybe_convert_to_dtype(a: NumberType, dtype: torch.dtype) -> NumberType: + pass + + +@overload +# pyrefly: ignore [bad-return] +def _maybe_convert_to_dtype(a: Sequence, dtype: torch.dtype) -> Sequence: + pass + + +@overload +def _maybe_convert_to_dtype(a: None, dtype: torch.dtype) -> None: + pass + + +# TODO: implement ref.cast with an option to enforce safe casting +def _maybe_convert_to_dtype(a, dtype): + if isinstance(a, TensorLike): + if a.dtype != dtype: + return a.to(dtype) + return a + if isinstance(a, Number): + return utils.dtype_to_type_ctor(dtype)(a) # type: ignore[arg-type] + if isinstance(a, Sequence): + return tuple(_maybe_convert_to_dtype(x, dtype) for x in a) + # Passthrough None because some functions wrapped with type promotion + # wrapper might have optional args + if a is None: + return None + + raise ValueError( + f"Received unsupported type {type(a)}. Expected TensorLike, Number, or Sequence." + ) + + +def _maybe_convert_to_type(a: NumberType, typ: type) -> NumberType: + if not isinstance(a, Number): + msg = f"Found unknown type {type(a)} when trying to convert scalars!" + raise ValueError(msg) + if not utils.is_weakly_lesser_type(type(a), typ): + msg = f"Scalar {a} of type {type(a)} cannot be safely cast to type {typ}!" + raise ValueError(msg) + + return typ(a) + + +def _annotation_has_type(*, typ, annotation): + args = typing.get_args(annotation) + if args: + return any(_annotation_has_type(typ=typ, annotation=a) for a in args) + return typ is annotation + + +class elementwise_type_promotion_wrapper: + """ + Adds elementwise type promotion to a Python reference implementation. + + Takes two kwargs, type_promoting_args and type_promotion_kind. + + type_promoting_args must be a string Sequence specifying the argument names of all + arguments that participate in type promotion (and should be type promoted). If the + arg specifies a Sequence-type then every element of the Sequence will participate in + type promotion. + + type_promotion_kind must be one of the kinds specified by ELEMENTWISE_TYPE_PROMOTION_KIND. + See its documentation for details. + + The return_dtype will be coerced to the wrapped function's dtype arg if it is available and + not None. + + Other type promotion behavior, like validating the Python type of scalar arguments, must + be handled separately. + """ + + def __init__( + self, + *, + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND, + type_promoting_args: Sequence[str] | None = None, + ): + self.type_promoting_arg_names = type_promoting_args + self.type_promotion_kind = type_promotion_kind + + def __call__(self, fn: Callable) -> Callable: + sig = inspect.signature(fn) + + # TorchDynamo tracing of inspect causes fake tensor dynamo_wrapped tests to fail + # PYTORCH_TEST_WITH_DYNAMO=1 python test/test_fake_tensor.py FakeTensorTest.test_basic + @torch._disable_dynamo + @wraps(fn) + def _fn(*args, **kwargs): + bound = _fast_bind(sig, *args, **kwargs) + type_promoting_args = tuple( + bound.arguments[x] + for x in self.type_promoting_arg_names # type: ignore[union-attr] + if x in bound.arguments + ) + + flattened_type_promoting_args = pytree.arg_tree_leaves(*type_promoting_args) + compute_dtype, result_dtype = utils.elementwise_dtypes( + *flattened_type_promoting_args, + type_promotion_kind=self.type_promotion_kind, + ) + + promoted_args = { + x: _maybe_convert_to_dtype(bound.arguments[x], compute_dtype) + for x in self.type_promoting_arg_names # type: ignore[union-attr] + if x in bound.arguments + } + bound.arguments.update(promoted_args) + + result = fn(**bound.arguments) + + # Override the return_dtype if a dtype arg is present and not None + if "dtype" in bound.arguments: + maybe_dtype = bound.arguments["dtype"] + if maybe_dtype: # dtype cannot be None + result_dtype = maybe_dtype + + if isinstance(result, TensorLike): + return _maybe_convert_to_dtype(result, result_dtype) + if isinstance(result, Sequence): + return tuple(_maybe_convert_to_dtype(x, result_dtype) for x in result) + raise AssertionError(f"Unhandled result type: {type(result)}") + + _fn.__signature__ = sig # type: ignore[attr-defined] + return _fn + + +# Returns True if resize is necessary +def _resize_output_check(out: TensorLikeType, shape: ShapeType): + # If the shapes are correct there's nothing to do + if utils.same_shape(out.shape, shape): + return False + if out.numel() != 0: + msg = ( + f"An output with one or more elements was resized since it had shape {str(out.shape)} " + "which does not match the required output shape {str(shape)}. " + "This behavior is deprecated, and in a future PyTorch release outputs will not " + "be resized unless they have zero elements. " + "You can explicitly reuse an out tensor t by resizing it, inplace, to zero elements with t.resize_(0)." + ) + warnings.warn(msg, stacklevel=2) + return True + + +# TODO: handle tuples of tensors +def _maybe_resize_out( + out: TensorLikeType, + shape: ShapeType, + memory_format: torch.memory_format | None = None, +): + if _resize_output_check(out, shape): + return out.resize_(shape, memory_format=memory_format) + else: + return out + + +def is_cpu_scalar(x: TensorLikeType) -> bool: + return x.dim() == 0 and x.device.type == "cpu" + + +def check_copy_devices(*, copy_from: TensorLikeType, copy_to: TensorLikeType) -> None: + if copy_from.device != copy_to.device: + msg = ( + f"Attempting to copy from device {copy_from.device} " + f"to device {copy_to.device}, but cross-device copies are not allowed!" + ) + raise RuntimeError(msg) + + +def _safe_copy_out( + *, copy_from: TensorLikeType, copy_to: TensorLikeType, exact_dtype: bool = False +): + # Checks same device + if not is_cpu_scalar(copy_from): + check_copy_devices(copy_from=copy_from, copy_to=copy_to) + + # Checks safe cast + if exact_dtype: + torch._check( + copy_from.dtype == copy_to.dtype, + lambda: f"Expected out tensor to have dtype {copy_from.dtype} " + f"but got {copy_to.dtype} instead", + ) + else: + torch._check( + utils.can_safe_cast_to(cast_from=copy_from.dtype, cast_to=copy_to.dtype), + lambda: f"Attempting to cast from {copy_from.dtype} to out tensor with dtype {copy_to.dtype}, " + "but this can't be cast because it is not safe!", + ) + + return copy_to.copy_(copy_from) + + +def out_wrapper( + *out_names: str, + exact_dtype: bool = False, + pass_is_out: bool = False, + preserve_memory_format: bool = False, +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + # The wrapped function needs to convert the output parameters to ensure + # compatibility between the Python API (which always uses "out" as the + # parameter name and may be a tuple) and the Aten API (which may have + # multiple output parameters and use different parameter names such as + # "grad_input", "indices" or "values".) + + default_out_names = ("out",) + if len(out_names) == 0: + # Use default in out name + out_names = default_out_names + + is_tensor = len(out_names) == 1 + + def maybe_compute_memory_format(t): + return utils.suggest_memory_format(t) if preserve_memory_format else None + + def _out_wrapper(fn: Callable[_P, _T]) -> Callable[_P, _T]: + """ + Adds the out parameter to a Python reference. + """ + out_type = ( + TensorLikeType + if is_tensor + else GenericAlias( + tuple, tuple(TensorLikeType for _ in range(len(out_names))) + ) + ) + # For backward compatibility - should be able to remove once PEP585 + # conversion is complete. + bc_out_type = ( + TensorLikeType + if is_tensor + else types.GenericAlias( + tuple, tuple(TensorLikeType for _ in range(len(out_names))) + ) + ) + return_type = ( + TensorLikeType + if is_tensor + else NamedTuple( + f"return_types_{fn.__name__}", + # pyrefly: ignore [bad-argument-count] + [(o, TensorLikeType) for o in out_names], + ) + ) + + sig = inspect.signature(fn) + factory_kwargs = ("device", "dtype") + is_factory_fn = all(p in sig.parameters for p in factory_kwargs) + + @wraps(fn) + def _fn(*args: _P.args, **kwargs: _P.kwargs): + out = kwargs.pop("out", None) + if is_factory_fn and out is not None: + for k in factory_kwargs: + out_attr = getattr(out, k) + if k not in kwargs: + kwargs[k] = out_attr + + def maybe_check_copy_devices(out): + if isinstance(out, TensorLike) and isinstance(args[0], TensorLike): + check_copy_devices(copy_from=args[0], copy_to=out) + + if isinstance(out, (tuple, list)): + for o in out: + maybe_check_copy_devices(o) + else: + maybe_check_copy_devices(out) + + if pass_is_out: + result = fn(*args, is_out=(out is not None), **kwargs) # type: ignore[arg-type] + else: + result = fn(*args, **kwargs) + if result is NotImplemented: + return NotImplemented + if not ( + (isinstance(result, TensorLike) and is_tensor) + or ( + isinstance(result, tuple) # type: ignore[arg-type] + and len(result) == len(out_names) # type: ignore[arg-type] + ) + or ( + fn.__name__ == "unbind" and isinstance(result, (list, tuple)) # type: ignore[arg-type] + ) + ): + raise AssertionError( + f"Unexpected result type: {type(result)}, is_tensor={is_tensor}, " + f"out_names={out_names}" + ) + # unbind_copy is a special case: see https://github.com/pytorch/pytorch/issues/130829 + if out is not None: + # Naively you might expect this assert to be true, but + # it's not: + # + # assert type(out) is type(result) + # + # The reason is that functions under this wrapper can + # get registered to the Meta dispatch key, and that + # means they can be executed in a context where tensor + # subclasses are disabled (with no_dispatch), which is a + # handy way for an is-a tensor subclass (e.g., + # FakeTensor) to have the normal meta backend create a + # meta tensor, to be wrapped once it gets returned. + # In this situation, you will get a FakeTensor as + # the output tensor, but not the result--which will + # be a normal meta tensor, but this is perfectly + # harmless. + if is_tensor and fn.__name__ != "unbind": + if not isinstance(out, TensorLike): + raise AssertionError( + f"out must be TensorLike, got {type(out)}" + ) # mypy + # These two operations are done in-place + _maybe_resize_out( + out, + result.shape, # type: ignore[union-attr] + maybe_compute_memory_format(result), + ) + _safe_copy_out( + copy_from=result, # type: ignore[arg-type] + copy_to=out, + exact_dtype=exact_dtype, + ) + else: + if fn.__name__ != "unbind": + if not isinstance(out, tuple): + raise AssertionError(f"out must be tuple, got {type(out)}") # type: ignore[arg-type] # mypy + else: + if not isinstance(out, (list, tuple)): + raise AssertionError( + f"out must be list or tuple, got {type(out)}" + ) # type: ignore[arg-type] # mypy + torch._check_type( + len(out) == len(result), # type: ignore[arg-type] + lambda: f"expected tuple of {len(result)} elements but got {len(out)}", # type: ignore[arg-type] + ) + for r, o in zip(result, out): # type: ignore[arg-type] + # These two operations are done in-place + _maybe_resize_out(o, r.shape, maybe_compute_memory_format(r)) + _safe_copy_out(copy_from=r, copy_to=o, exact_dtype=exact_dtype) # type: ignore[arg-type] + else: + out = result + # mypy does not see through the definition of out_type given that it's in a different scope + return out if is_tensor else return_type(*out) # type: ignore[operator] + + out_param = inspect.Parameter( + "out", + kind=inspect.Parameter.KEYWORD_ONLY, + default=None, + annotation=out_type, + ) + # Mark that the function now returns a tuple + if not ( + isinstance(sig.return_annotation, (str, TypeVar)) + or sig.return_annotation in (sig.empty, out_type, bc_out_type) + ): + raise AssertionError( + f"Unexpected return annotation: {sig.return_annotation}, " + f"expected str, TypeVar, empty, {out_type}, or {bc_out_type}" + ) + params = *sig.parameters.values(), out_param + + # If there's a Parameter.VAR_KEYWORD parameter (like **kwds), it must appear + # after the out= parameter, which is Parameter.KEYWORD_ONLY. Sorting by + # Parameter.kind guarantees that all the parameters are in legal order. + params = sorted(params, key=lambda p: p.kind) + + _fn.__signature__ = inspect.Signature( # type: ignore[attr-defined] + parameters=params, + return_annotation=return_type, # type: ignore[arg-type] + ) + + _fn.__annotations__ = dict(getattr(fn, "__annotations__", {})) + _fn.__annotations__["out"] = out_type + _fn.__annotations__["return"] = return_type + + # In the special case of having a single tensor out parameter with a + # name other than out, add a special annotation to name the parameter + if is_tensor and out_names != default_out_names: + _fn.__annotations__[CustomOutParamAnnotation] = out_names[0] + + # Add an indicator attribute that can be used in special cases + # where having a function wrapped by `out_wrapper` is not desirable e.g. + # jit + _fn._torch_decompositions_out_wrapper = ( # type: ignore[attr-defined] + f"This function is wrapped by {out_wrapper.__module__}.out_wrapper" + ) + + return _fn + + return _out_wrapper + + +def _maybe_remove_out_wrapper(fn: Callable): + return inspect.unwrap( + fn, + stop=lambda f: not hasattr(f, "_torch_decompositions_out_wrapper"), + ) + + +def backwards_not_supported(prim): + def redispatch_prim(args, kwargs): + with torch._C._AutoDispatchBelowAutograd(): + return prim(*args, **kwargs) + + class BackwardsNotSupported(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx, args_spec, *flat_args): + args, kwargs = tree_unflatten(flat_args, args_spec) # type: ignore[arg-type] + return redispatch_prim(args, kwargs) + + @staticmethod + def backward(ctx, *args): + raise RuntimeError("backwards not supported on prim") + + @wraps(prim) + def _autograd_impl(*args, **kwargs): + flat_args, args_spec = tree_flatten((args, kwargs)) + if torch.is_grad_enabled() and any( + a.requires_grad for a in flat_args if isinstance(a, torch.Tensor) + ): + # TODO: There is a subtle bug here: prims like copy_to + # return their input argument after mutating it; and custom + # autograd function will incorrectly turn the result into + # a view which will fail test_python_ref_executor tests. + # At the moment, we sidestep this by observing that the + # unit tests don't ever try to run the executor with + # autograd, so we don't exercise the buggy case, but if + # you ever want to feed autograd through this, be aware + # of it! We need a way of properly implementing autograd + # for mutating operations in Python to do this. + return BackwardsNotSupported.apply(args_spec, *flat_args) + else: + return redispatch_prim(args, kwargs) + + return _autograd_impl + + +# TODO: when tracing this will add torch tensors and not TensorMeta objects +# to the trace -- we should fix this by adding a tracing context and NumberMeta classes +# TODO: this wrapper is currently untested +def elementwise_unary_scalar_wrapper( + fn: Callable[_P, _T], +) -> Callable[_P, _T | NumberType]: + """ + Allows unary operators that accept tensors to work with Python numbers. + """ + sig = inspect.signature(fn) + + @wraps(fn) + def _fn(*args, **kwargs): + if len(args) > 0 and isinstance(args[0], Number): + dtype = utils.type_to_dtype(type(args[0])) + args_ = list(args) + args_[0] = torch.tensor(args[0], dtype=dtype) + # pyrefly: ignore [invalid-param-spec] + result = fn(*args_, **kwargs) + if not isinstance(result, torch.Tensor): + raise AssertionError(f"Expected torch.Tensor, got {type(result)}") + return result.item() + + # pyrefly: ignore [invalid-param-spec] + return fn(*args, **kwargs) + + _fn.__signature__ = sig # type: ignore[attr-defined] + # pyrefly: ignore [bad-return] + return _fn diff --git a/.venv/lib/python3.12/site-packages/torch/_python_dispatcher.py b/.venv/lib/python3.12/site-packages/torch/_python_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..ceff54d5c36678afd30bda162360d3e69bac6850 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_python_dispatcher.py @@ -0,0 +1,182 @@ +# mypy: allow-untyped-defs +import re + +import torch._C as C + + +""" +PythonDispatcher class is a thin python-binding to C++ dispatcher and it +is designed to show how dispatcher precompute works. In particular, +it shows for a certain op `foo`, what the computed dispatch table looks +like after user register their kernels to certain dispatch keys. + +In the real C++ dispatcher we support many dispatch keys for different +functionalities. For simplicity PythonDispatcher only supports dispatch +keys for a single example of each use case. These use cases are listed below: + +- CPU/AutogradCPU: represents in-tree backends which we usually have dedicated inference & + autograd kernel in pytorch core library. + E.g. CPU, CUDA +- FPGA/AutogradOther: represents in-tree backends which we usually have backend specific + inference kernels, but they share the same autograd kernel specified in AutogradOther. + E.g. FPGA, SparseCsrCPU +- XLA/AutogradXLA: represents out-of-tree backends which we don't have either inference or autograd + kernel defined in pytorch core library. Backend owner is responsible for registering both + inference & autograd kernels in their extensions(e.g. torch-xla) for the operators they support. + E.g. XLA, XPU, MPS +- CompositeExplicitAutograd: alias key mapped to inference kernels of all backends like CPU, CUDA, XLA etc. + Kernels registered to this key MUST work for inference for all backends. +- Autograd: alias key mapped to autograd of all backends like AutogradCPU, AutogradXLA, AutogradOther. + Kernels registered to this key MUST work for autograd for all backends. +- CompositeImplicitAutograd: alias key CompositeImplicitAutograd = CompositeExplicitAutograd + Autograd + Kernels registered to this key MUST work for both inference + autograd for all backends. + +Note we only allow registrations to alias keys inside pytorch core library. E.g +you shouldn't register a CompositeImplicitAutograd or CompositeExplicitAutograd +kernel from torch-xla extension, instead you should upstream the kernel into +pytorch/pytorch repo so that it's available for all backends and continuously +tested even without the extension. + +Usage: + dispatcher = PythonDispatcher() + dispatcher.register(["CPU", "XLA", "CompositeImplicitAutograd"]) + print(dispatcher.dispatchTable()) # This tells you exactly which kernel is used for certain backend. + # For more debugging information + # print(dispatcher.keys()) + # print(dispatcher.registrations()) + # print(dispatcher.rawRegistrations()) + # print(dispatcher.rawDispatchTable()) +PythonDispatcher calls C++ dispatcher under the hood to precompute dispatch table. +This file only provides the simplified API for developers, relevant test code is located in +test/test_dispatch.py +""" + + +class PythonDispatcher: + namespace = "__test__" + name = "foo" + # fmt: off + runtime_keys = [ + "CPU", "AutogradCPU", + "FPGA", "AutogradOther", + "XLA", "AutogradXLA", + "Lazy", "AutogradLazy", + ] + # fmt: on + alias_keys = [ + "CompositeExplicitAutograd", + "Autograd", + "CompositeImplicitAutograd", + ] + supported_keys = runtime_keys + alias_keys + + def __init__(self) -> None: + C._dispatch_check_invariants(self.name) # type: ignore[attr-defined] + self.ref = C._dispatch_library("FRAGMENT", self.namespace, "") + self.ref.def_("foo(Tensor x) -> Tensor") + + """ + Returns a list of dispatch keys supported by PythonDispatcher. + You can register kernels to these keys. + """ + + def keys(self): + return self.supported_keys + + """ + Register kernels to the target dispatchKeys. + dispatchKeys(list[str]): a list of dispatch keys that you want to register + your own kernel. Note that you don't need to write the kernel yourself in + this PythonDispatcher.E.g. for CPU key, a kernel(e.g fn_CPU for CPU) is + automatically generated and registered. + """ + + def register(self, dispatchKeys): + # Overridden is not supported and triggers a warning in C++ dispatcher. + if len(set(dispatchKeys)) != len(dispatchKeys): + raise RuntimeError( + f"Overridden is not allowed but found duplicates in {dispatchKeys}." + ) + # We currently forbid this in codegen instead of C++ dispatcher. + if ( + "CompositeImplicitAutograd" in dispatchKeys + and "CompositeExplicitAutograd" in dispatchKeys + ): + raise RuntimeError( + "Registration to both CompositeImplicitAutograd and CompositeExplicitAutograd is not allowed." + ) + for key in dispatchKeys: + if key not in self.supported_keys: + raise RuntimeError( + f"{key} is not supported, please select a dispatch key in {self.supported_keys}." + ) + self.ref.impl_t_t("foo", dispatch=key, debug="fn_" + key) + + """ + Helper function to format (key, kernel). + """ + + def _format_line(self, key, kernel): + return f"{key:<15} {kernel}\n" + + """ + Helper function to print a table header. + """ + + def _format_header(self, header): + s = f""" +{header} +""" + s += self._format_line("key", "kernel") + s += "---------------------------\n" + return s + + """ + Returns raw output of all registration info for debugging only. + Use registrations() for a simplified version. + """ + + def rawRegistrations(self): + return C._dispatch_dump(f"{self.namespace}::{self.name}") # type: ignore[attr-defined] + + """ + Returns raw output of computed dispatch table for debugging only. + Use dispatchTable() for a simplified version. + """ + + def rawDispatchTable(self): + return C._dispatch_dump_table(f"{self.namespace}::{self.name}") # type: ignore[attr-defined] + + """ + Returns a table(str) including all the registrations from users. + Note this includes registrations to both runtime keys and alias keys. + """ + + def registrations(self): + output = self._format_header("Registered Kernels") + state = self.rawRegistrations() + state_entries = state.split("\n") + for line in state_entries: + first = line.split(":")[0] + if any(first.startswith(k) for k in self.supported_keys): + kernel = line.split("::")[0].split(" ")[1] + output += self._format_line(first, kernel) + return output + + """ + Returns the computed dispatch table(str). Note this only include + runtime keys, registrations to alias keys have been decoded to their + mapped runtime keys. + """ + + def dispatchTable(self): + output = self._format_header("Computed Dispatch Table") + table = self.rawDispatchTable() + table_entries = table.split("\n") + regex = re.compile(r"registered at .*FallbackKernel\.cpp.*(\[)") + for line in table_entries: + k = line.split(":")[0] + if k in self.runtime_keys: + entry = regex.sub("[", line) + output += self._format_line(k, entry.split(": ")[1]) + return output diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/__init__.py b/.venv/lib/python3.12/site-packages/torch/_refs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..076e190137827560f9425eea06691cbd40d3803d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_refs/__init__.py @@ -0,0 +1,7204 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import builtins +import collections +import inspect +import itertools +import math +import operator +import warnings +from collections.abc import Callable, Iterable, Sequence +from enum import Enum +from functools import partial, reduce, singledispatch, wraps +from typing import Any, cast, Optional, overload, Union + +import torch +import torch._prims as prims +import torch._prims_common as utils +import torch.utils._pytree as pytree +from torch import sym_float, sym_int, sym_max, sym_min +from torch._prims_common import ( + BoolLike, + DeviceLikeType, + Dim, + DimsSequenceType, + DimsType, + dtype_to_type, + ELEMENTWISE_TYPE_PROMOTION_KIND, + FloatLike, + FloatWithoutSymFloat, + IntLike, + is_contiguous_for_memory_format_or_false, + is_contiguous_or_false, + is_weakly_lesser_type, + Number, + NumberType, + RealNumberType, + REDUCTION_OUTPUT_TYPE_KIND, + ShapeType, + StrideType, + TensorLike, + TensorLikeType, + TensorOrNumberLikeType, + TensorSequenceType, +) +from torch._prims_common.wrappers import ( + _maybe_convert_to_dtype, + _maybe_resize_out, + _safe_copy_out, + elementwise_type_promotion_wrapper, + elementwise_unary_scalar_wrapper, + out_wrapper, +) +from torch.testing._internal.common_dtype import highest_precision_float + + +# Experimental module containing prototype Python references for existing +# PyTorch operations. + +__all__ = [ + # + # Elementwise Unary References + # + "abs", + "acos", + "acosh", + "asinh", + "asin", + "atan", + "atanh", + "bitwise_not", + # "cbrt", # No corresponding torch operation + "ceil", + "conj_physical", + "cos", + "cosh", + "count_nonzero", + "deg2rad", + "digamma", + "erf", + "erfinv", + "erfc", + "exp", + "expm1", + "exponential", + "exp2", + "fill", + "fill_", + "floor", + "frac", + "geometric", + "index_add", + "index_copy", + "index_copy_", + "index_select", + "index_fill", + "index_fill_", + "isfinite", + "isinf", + "isposinf", + "isneginf", + "isnan", + "isreal", + "i0", + "lerp", + "lgamma", + "log", + "log1p", + "log2", + "log10", + "log_normal", + "log_softmax", + "mvlgamma", + "norm", + "normal", + "nan_to_num", + "neg", + "positive", + "rad2deg", + "reciprocal", + "round", # TODO: model kwargs + "sigmoid", + "sgn", + "sign", + "signbit", + "sin", + "sinc", + "sinh", + "softmax", + "sqrt", + "square", + "tan", + "tanh", + "trace", + "trunc", + # + # Elementwise Binary References + # + "add", + "atan2", + "bitwise_and", + "bitwise_left_shift", + "bitwise_or", + "bitwise_right_shift", + "bitwise_xor", + "clamp_min", + "clamp_max", + "copysign", + "div", + "eq", + "float_power", + "floor_divide", + "fmax", + "fmin", + "fmod", + "gcd", + "ge", + "gt", + "heaviside", + "hypot", + "igamma", + "igammac", + "imag", + "isclose", + "lcm", + # 'ldexp', + "le", + "logaddexp", + "logaddexp2", + "logical_and", + "logical_not", + "logical_or", + "logical_xor", + "logsumexp", + "lt", + # 'max', # implement with reductions + "maximum", + # 'min', # implement with reductions + "minimum", + "mul", + "ne", + "nextafter", + # 'polar', # abs, cos, sin + "pow", + "real", + "rpow", + "remainder", + "rsub", + "rtruediv", + "rfloordiv", + "sub", + "true_divide", + "trunc_divide", + "xlogy", + # + # Elementwise Ternary References + # + "addcdiv", + "addcmul", + "clamp", + # + # Conditional references + # + "masked_fill", + "masked_fill_", + "where", + # + # Data conversion and movement references + # + "clone", + "copy_to", # TODO: add OpInfo (or implement .to) + "item", + "to", + # + # Reduction ops + # + "all", + "amax", + "amin", + "any", + "cumsum", + "cumprod", + "mean", + "dot", + "vdot", + "std", + "std_mean", + "sum", + "sum_to_size", + "prod", + "var", + "var_mean", + # + # Linear algebra ops + # + "addr", + # + # View & Shape Ops + # + "alias", + "alias_copy", + "atleast_1d", + "atleast_2d", + "atleast_3d", + "as_strided", + "as_strided_copy", + "as_strided_scatter", + "block_diag", + "broadcast_shapes", + "broadcast_tensors", + "broadcast_to", + "cat", + "chunk", + "column_stack", + "conj", + "constant_pad_nd", + "contiguous", + "diag_embed", + "diag", + "diagonal", + "diagonal_copy", + "diagonal_scatter", + "dsplit", + "dstack", + "expand", + "expand_as", + "expand_copy", + "flatten", + "flip", + "fliplr", + "flipud", + "hsplit", + "hstack", + "meshgrid", + "movedim", + "narrow", + "narrow_copy", + "native_group_norm", + "native_layer_norm", + "permute", + "permute_copy", + "ravel", + "repeat", + "reshape", + "reshape_as", + "roll", + "rot90", + "rsqrt", + "split_with_sizes", + "stack", + "swap_axes", # alias for transpose + "squeeze", + "squeeze_copy", + "t", + "t_copy", + "T", + "take_along_dim", + "tensor_split", + "transpose", + "transpose_copy", + "unbind_copy", + "unfold", + "unfold_copy", + "unsqueeze", + "unsqueeze_copy", + "view", + "view_as", + "view_copy", + "vsplit", + "vstack", + "view_as_complex", + "unflatten", + "unbind", + "triu", + "tril", + "triu_indices", + "tril_indices", + # + # Tensor Creation + # + "arange", + "cauchy", + "empty", + "empty_like", + "empty_permuted", + "empty_strided", + "eye", + "full", + "full_like", + "linspace", + "logspace", + "new_empty", + "new_empty_strided", + "new_full", + "new_ones", + "new_zeros", + "ones", + "ones_like", + "randn", + "scalar_tensor", + "zero", + "zeros", + "zeros_like", + # + # Test-related functions + # + "allclose", + "equal", + # + # Statistical operations + # + "bucketize", + # + # Misc + # + "is_complex", + "renorm", + "stft", + "istft", +] + +Tensor = torch.Tensor +DispatchKey = torch._C.DispatchKey # type: ignore[attr-defined] +aten = torch._ops.ops.aten + +# Note that the docstrings for the public methods from this file are in +# torch/_torch_docs.py + + +def is_noncontiguous_supported(device): + return device is None or device.type != "hpu" + + +def handle_noncontiguous_outputs(input_tlist, output): + device = None + from torch._subclasses.fake_tensor import ( + FakeTensor, + is_fake_tensor, + maybe_get_fake_device, + ) + + for t in input_tlist: + if is_fake_tensor(t): + device = maybe_get_fake_device(t) + break + + if not is_noncontiguous_supported(device): + output = output.contiguous() + + return output + + +def _broadcast_shapes(*_shapes): + from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + guarding_hint_or_throw, + has_guarding_hint, + is_nested_int, + ) + + backed_so = torch.fx.experimental._config.backed_size_oblivious + + shapes = tuple( + (x,) if isinstance(x, IntLike) else x + for x in filter(lambda x: x is not None, _shapes) + ) + + # Short-circuits on no input + if len(shapes) == 0: + return None + + for shape in shapes: + if not isinstance(shape, Sequence): + raise RuntimeError( + f"Input shapes should be of type ints, a tuple of ints, or a list of ints, got {shape}" + ) + + # Computes common shape + common_shape: list[int | torch.SymInt] = [ + 1, + ] * reduce(max, (len(shape) for shape in shapes)) + for arg_idx, shape in enumerate(shapes): + for idx in range(-1, -1 - len(shape), -1): + # NB: handle nested ints specially to avoid invalid guarding on Ne(j0, 1). + if is_nested_int(shape[idx]): + # Broadcasting is allowed for (j0, 1) or (j0, j0); + # not (j0, j1), (j0, 5), etc. + if is_nested_int(common_shape[idx]) and guard_or_false( + shape[idx] == common_shape[idx] + ): + continue + else: + # When backed size oblivious is used, we specialize for broadcasting + # if it's the only way to compile the example input. + # i.e: s0:1, s1:1 ==> + # assert s0==s1, no specialization on ==1 or !=1. + # The non-broadcast path is picked + # s0:1, s1:4 ==> + # specialize(s0) to be 1. + # s0:4, s1:1 ==> + # specialize(s1) to be 1. + if ( + backed_so + and has_guarding_hint(shape[idx]) + and has_guarding_hint(common_shape[idx]) + ): + a = guarding_hint_or_throw(shape[idx]) + b = guarding_hint_or_throw(common_shape[idx]) + if a == 1 and b != 1: + torch._check(shape[idx] == 1) + if b == 1 and a != 1: + torch._check(common_shape[idx] == 1) + if guard_or_false(shape[idx] == common_shape[idx]): + continue + + if guard_or_false(common_shape[idx] == 1): + if shape[idx] < 0: + raise ValueError( + "Attempting to broadcast a dimension with negative length!" + ) + common_shape[idx] = shape[idx] + + if not is_nested_int(shape[idx]) and guard_or_false(shape[idx] == 1): + # broadcast case . + continue + else: + # If broadcasting is undecided we pick non-broadcast path and add runtime assertion. + torch._check( + common_shape[idx] == shape[idx], + lambda: f"Attempting to broadcast a dimension of length {shape[idx]} at {idx}! " + f"Mismatching argument at index {arg_idx} had {shape}; but expected shape " + f"should be broadcastable to {common_shape}", + ) + + return common_shape + + +def _maybe_broadcast(*args, preserve_cpu_scalar_tensors=True): + # Computes common shape + common_shape = _broadcast_shapes( + *(t.shape if isinstance(t, TensorLike) else None for t in args) + ) + + def should_expand(a: ShapeType, b: ShapeType) -> bool: + from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + sym_and, + sym_or, + ) + + if len(a) != len(b): + return True + + for x, y in zip(a, b): + if guard_or_false(x != y): + # We know they are not the same. + return True + + # They are the same or we do not know if they are the same or not. + # 1==1 no-broadcast + # u0==1 and 1==u0 cases. We broadcast! + if guard_or_false(sym_and(x == 1, y == 1)): + pass + elif guard_or_false(sym_or(x == 1, y == 1)): + # assume broadcasting. + return True + + # u0==u1 assume the same, no broadcasting! + torch._check( + x == y, + lambda: "sizes assumed to be the same due to unbacked broadcasting semantics", + ) + + return False + + def __maybe_broadcast(x, shape): + if x is None: + return None + elif isinstance(x, Number): + return x + elif isinstance(x, TensorLike): + if preserve_cpu_scalar_tensors and utils.is_cpu_scalar_tensor(x): + return x + + if should_expand(x.shape, common_shape): + return x.expand(common_shape) + + return x + else: + raise RuntimeError( + "Unexpected type when broadcasting: " + str(type(x)) + "!" + ) + + return tuple(__maybe_broadcast(x, common_shape) for x in args) + + +# Utilities should come BEFORE this import +from torch._decomp import register_decomposition + + +# +# Elementwise unary references +# + +infer_aten_op = object() + + +# TODO: add type promotion support +def _make_elementwise_unary_reference( + type_promotion_kind, + *, + aten_op=infer_aten_op, + extra_meta=None, + exact_dtype=False, +) -> Callable: + def inner(prim: Callable): + nonlocal aten_op + + @wraps(prim) + @out_wrapper(exact_dtype=exact_dtype) + @elementwise_unary_scalar_wrapper + @elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=type_promotion_kind, + ) + def _ref(a: TensorLikeType) -> TensorLikeType: + if extra_meta is not None: + extra_meta(a) + + output = prim(a) + return handle_noncontiguous_outputs([a], output) + + if aten_op is infer_aten_op: + aten_op = utils.get_aten_op(prim, prim.__name__) + if aten_op is not None: + register_decomposition(aten_op)(_ref) + + return _ref + + return inner + + +def _make_alias(fn, name): + """ + This function defines an alias of another function and sets its __name__ argument. + It also sets its __module__ argument to the module of the caller. + Note that when naively doing `alias = fn`, we have that `alias.__name__ == "fn"`, and + `alias.__module__ == fn.__module__`. + """ + + def _fn(*args, **kwargs): + return fn(*args, **kwargs) + + _fn.__name__ = name + _fn.__module__ = inspect.currentframe().f_back.f_globals["__name__"] # type: ignore[union-attr] + return _fn + + +def _make_inplace(fn): + """ + Given a function with out variant (i.e. using `out_wrapper()), it returns its in-place variant + See https://github.com/pytorch/pytorch/wiki/Developer-FAQ#how-do-in-place-operations-work-in-pytorch + """ + + # nb. We use the name of the first argument used in the unary references + @wraps(fn) + def _fn(a, *args, **kwargs): + # In-place ops never resize `a`, but out_wrapper would resize `out=a` + # if the broadcasted result shape were larger. Reject the mismatch up + # front with the same error eager (TensorIterator) raises. Otherwise + # fake/meta tensors silently change shape here, which corrupts shape + # metadata recorded before the op (e.g. dynamo's tracked fakes). + shapes = [ + t.shape + for t in itertools.chain(args, kwargs.values()) + if isinstance(t, TensorLike) + ] + if shapes: + broadcasted_shape = tuple(_broadcast_shapes(a.shape, *shapes)) + torch._check( + broadcasted_shape == a.shape, + lambda: f"output with shape {a.shape} doesn't match the broadcast shape {broadcasted_shape}", + ) + return fn(a, *args, out=a, **kwargs) + + inplace_name = f"{fn.__name__}_" + _fn.__name__ = inplace_name + _fn = register_decomposition(getattr(aten, inplace_name))(_fn) # type: ignore[assignment] + + # We access the __all__ attribute of the module where fn is defined + # There may be a cleaner way of doing this... + from inspect import getmodule + + _all = getmodule(fn).__all__ # type: ignore[union-attr] + if inplace_name not in _all: + _all.append(inplace_name) + return _fn + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT, + exact_dtype=True, +) +def abs(a): + return prims.abs(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def acos(a): + return prims.acos(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def acosh(a): + return prims.acosh(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def asin(a): + return prims.asin(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def asinh(a): + return prims.asinh(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def atan(a): + return prims.atan(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def atanh(a): + return prims.atanh(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT) +def bitwise_not(a): + return prims.bitwise_not(a) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + exact_dtype=True, +) +def ceil(a): + return prims.ceil(a) + + +@register_decomposition(aten.is_complex) +def is_complex(input: TensorLikeType): + return utils.is_complex_dtype(input.dtype) + + +@register_decomposition(aten.conj_physical) +@out_wrapper() +def conj_physical(input: TensorLikeType): + if not utils.is_complex_dtype(input.dtype): + return input + return prims.conj_physical(input) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def cos(a): + return prims.cos(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def cosh(a): + return prims.cosh(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def digamma(a): + return prims.digamma(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def erf(a): + return prims.erf(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def erfinv(a): + return prims.erf_inv(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def erfc(a): + return prims.erfc(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def exp(a): + return prims.exp(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def expm1(a): + return prims.expm1(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def exp2(a): + return prims.exp2(a) + + +# Fill has its own implementation because it has a value parameter +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH, +) +def fill(a: TensorLikeType, value: NumberType) -> TensorLikeType: + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") + if not isinstance(value, Number): + raise AssertionError(f"value must be Number, got {type(value)}") + + python_type = utils.dtype_to_type(a.dtype) + if not utils.is_weakly_lesser_type(type(value), python_type): + msg = f"value argument of type {type(value)} cannot be safely cast to type {python_type}!" + raise ValueError(msg) + + return prims.fill(a, value) + + +def fill_(a: TensorLikeType, value: NumberType) -> TensorLikeType: + r = prims.fill(a, value) + prims.copy_to(a, r) + return a + + +@register_decomposition(aten.zero) +@out_wrapper() +def zero(input: TensorLikeType) -> TensorLikeType: + return torch.zeros_like(input) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + exact_dtype=True, +) +def floor(a): + return prims.floor(a) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + exact_dtype=True, +) +def frac(x: TensorLikeType) -> TensorLikeType: + return torch.sub(x, torch.trunc(x)) + + +# imag does not use _make_elementwise_unary_reference because it does not support out +def imag(a: TensorLikeType) -> TensorLikeType: + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") + torch._check( + utils.is_complex_dtype(a.dtype), lambda: "imag only supports complex tensors." + ) + return prims.imag(a) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + aten_op=None, # CompositeImplicitAutograd +) +def isfinite(a: TensorLikeType) -> TensorLikeType: + if utils.is_float_dtype(a.dtype) or utils.is_complex_dtype(a.dtype): + return prims.isfinite(a) + + return ones_like(a, dtype=torch.bool) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL) +def isinf(a: TensorLikeType) -> TensorLikeType: + if utils.is_complex_dtype(a.dtype): + return torch.logical_or(isinf(torch.real(a)), isinf(torch.imag(a))) + if utils.is_float_dtype(a.dtype): + return torch.abs(a) == float("inf") + return torch.zeros_like(a, dtype=torch.bool) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + exact_dtype=True, +) +def isposinf(a: TensorLikeType) -> TensorLikeType: + torch._check( + not utils.is_complex_dtype(a.dtype), + lambda: f"Complex dtype is not supported for isposinf, got dtype {a.dtype}", + ) + if utils.is_float_dtype(a.dtype): + return a == float("inf") + return torch.zeros_like(a, dtype=torch.bool) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + exact_dtype=True, +) +def isneginf(a: TensorLikeType) -> TensorLikeType: + torch._check( + not utils.is_complex_dtype(a.dtype), + lambda: f"Complex dtype is not supported for isneginf, got dtype {a.dtype}", + ) + if utils.is_float_dtype(a.dtype): + return a == float("-inf") + return torch.zeros_like(a, dtype=torch.bool) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL) +def isnan(a: TensorLikeType) -> TensorLikeType: + return prims.ne(a, a) + + +# alias +mvlgamma = _make_alias(torch.special.multigammaln, "mvlgamma") # type: ignore[has-type] + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + aten_op=None, # CompositeImplicitAutograd +) +def isreal(a: TensorLikeType) -> TensorLikeType: + if utils.is_complex_dtype(a.dtype): + return torch.imag(a) == 0 + return torch.ones_like(a, dtype=torch.bool) + + +# TODO: if this is special maybe it should be defined there and imported here? +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, aten_op=aten.i0 +) +def i0(a): + return prims.bessel_i0(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def lgamma(a): + return prims.lgamma(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def log(a): + return prims.log(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def log1p(a): + return prims.log1p(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def log2(a): + return prims.log2(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def log10(a): + return prims.log10(a) + + +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +def log_softmax( + a: TensorLikeType, + dim: int, + dtype: torch.dtype | None = None, +) -> TensorLikeType: + result_dtype = dtype or a.dtype + computation_dtype = utils.get_computation_dtype(result_dtype) + a_ = _maybe_convert_to_dtype(a, computation_dtype) + return _maybe_convert_to_dtype(a_ - logsumexp(a_, dim, keepdim=True), result_dtype) # type: ignore[return-value] + + +@register_decomposition(aten.logsumexp) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def logsumexp( + self: TensorLikeType, dim: DimsType, keepdim: bool = False +) -> TensorLikeType: + if not isinstance(dim, Iterable): + dim = (dim,) + if self.numel() == 0: + return torch.sum(torch.exp(self), dim, keepdim).log() + + maxes = torch.amax(torch.real(self), dim, keepdim=True) + maxes = torch.masked_fill(maxes, maxes.abs() == float("inf"), 0) + + maxes_squeezed = maxes if keepdim else torch.squeeze(maxes, dim) + + result = torch.sum(torch.exp(self - maxes), dim, keepdim) + return result.log().add(maxes_squeezed) + + +@register_decomposition(aten.nan_to_num) +@out_wrapper() +def nan_to_num( + a: TensorLikeType, + nan: NumberType | None = 0.0, + posinf: NumberType | None = None, + neginf: NumberType | None = None, +) -> TensorLikeType: + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") + + if utils.is_boolean_dtype(a.dtype) or utils.is_integer_dtype(a.dtype): + return a.clone() + + if nan is None: + nan = 0.0 + + if posinf is None: + posinf = torch.finfo(a.dtype).max + + if neginf is None: + neginf = torch.finfo(a.dtype).min + + result = torch.where(torch.isnan(a), nan, a) # type: ignore[call-overload] + result = torch.where(torch.isneginf(a), neginf, result) # type: ignore[call-overload] + result = torch.where(torch.isposinf(a), posinf, result) # type: ignore[call-overload] + return result + + +def _neg_meta(a: TensorLikeType): + torch._check_not_implemented( + a.dtype is not torch.bool, + lambda: ( + "Negation, the `-` operator, on a bool tensor is not supported. " + "If you are trying to invert a mask, use the `~` or `logical_not()` " + "operator instead." + ), + ) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, extra_meta=_neg_meta +) +def neg(a): + return prims.neg(a) + + +# positive does not use _make_elementwise_unary_reference because it does not support out +# CompositeImplicitAutograd - don't register decomp +def positive(a: TensorLikeType) -> TensorLikeType: + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") + if a.dtype is torch.bool: + msg = "positive does not support bool tensors." + raise NotImplementedError(msg) + return a + + +# real does not use _make_elementwise_unary_reference because it does not support out +def real(a: TensorLikeType) -> TensorLikeType: + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") + if utils.is_complex_dtype(a.dtype): + return prims.real(a) + return a + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def reciprocal(a): + return prims.reciprocal(a) + + +@register_decomposition(aten.round) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def round(a: TensorLikeType, *, decimals: int = 0) -> TensorLikeType: + if decimals == 0: + return prims.round(a) + else: + ten_pow = 10**decimals + ten_neg_pow = 10 ** (-decimals) + return prims.mul(prims.round(prims.mul(a, ten_pow)), ten_neg_pow) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def rsqrt(a): + return prims.rsqrt(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def sigmoid(a: TensorLikeType) -> TensorLikeType: + return true_divide(1, add(1, exp(neg(a)))) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + exact_dtype=True, +) +def sgn(a): + if utils.is_complex_dtype(a.dtype): + a_abs = a.abs() + return torch.where(a_abs == 0, 0, a / a_abs) + else: + return a.sign() + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + exact_dtype=True, +) +def sign(a): + return prims.sign(a) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + exact_dtype=True, +) +def signbit(a): + return prims.signbit(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def sin(a): + return prims.sin(a) + + +# Autograd note: This will give the right first derivative at zero (by chance), +# but not the right second derivative +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def sinc(a): + a = math.pi * a + return torch.where(a == 0, 1, torch.sin(a) / a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def sinh(a): + return prims.sinh(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def sqrt(a): + return prims.sqrt(a) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.BOOL_TO_LONG, + aten_op=None, # CompositeImplicitAutograd, +) +def square(a: TensorLikeType) -> TensorLikeType: + return mul(a, a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def tan(a): + return prims.tan(a) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def tanh(a): + return prims.tanh(a) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + exact_dtype=True, +) +def trunc(a): + return prims.trunc(a) + + +# TODO: register this as a real ref/decomposition once TorchInductor supports complex! +def view_as_complex(self: TensorLikeType) -> TensorLikeType: + input_dtype = self.dtype + torch._check( + utils.is_float_dtype(input_dtype), + lambda: f"view_as_complex is only supported for floating point" + f"tensors, but got a tensor of scalar type: {input_dtype}", + ) + sizes = self.size() + torch._check( + len(sizes) != 0, + lambda: "Input tensor must have one or more dimensions", + ) + torch._check( + sizes[-1] == 2, + lambda: "Tensor must have a last dimension of size 2", + ) + + old_strides = self.stride() + torch._check( + old_strides[-1] == 1, + lambda: "Tensor must have a last dimension with stride 1", + ) + dims = old_strides[:-1] + torch._check( + builtins.all(stride % 2 == 0 for stride in dims), + lambda: "Tensor must have a stride divisible by 2 for all but last dimension", + ) + torch._check( + self.storage_offset() % 2 == 0, + lambda: "Tensor must have a storage_offset divisible by 2", + ) + return prims.view_element_type( + self, utils.corresponding_complex_dtype(input_dtype) + ).squeeze(-1) + + +def _make_elementwise_binary_reference( + type_promotion_kind, + aten_op=infer_aten_op, + name=None, + has_out=True, + supports_lhs_python_scalar=True, + supports_rhs_python_scalar=True, + supports_two_python_scalars=False, + should_register_decomposition=True, +) -> Callable: + def inner(prim: Callable): + nonlocal aten_op, name + if name is None: + name = prim.__name__ + + @wraps(prim) + @elementwise_type_promotion_wrapper( + type_promoting_args=("a", "b"), + type_promotion_kind=type_promotion_kind, + ) + def _ref( + a: Tensor | NumberType, + b: Tensor | NumberType, + ) -> Tensor: + torch._check_value( + supports_lhs_python_scalar or not isinstance(a, Number), + lambda: f"{name}: Received a lhs Python scalar to an elementwise binary " + "operation that does not accept lhs scalars!", + ) + torch._check_value( + supports_rhs_python_scalar or not isinstance(b, Number), + lambda: f"{name}: Received a rhs Python scalar to an elementwise binary " + "operation that does not accept rhs scalars!", + ) + torch._check_value( + supports_two_python_scalars + or not (isinstance(a, Number) and isinstance(b, Number)), + lambda: f"{name}: Receive two Number inputs to an elementwise binary operation!", + ) + a, b = _maybe_broadcast(a, b) + output = prim(a, b) + return handle_noncontiguous_outputs([a, b], output) + + if has_out: + _ref = out_wrapper()(_ref) # type: ignore[assignment] + + _ref.__name__ = name + if aten_op is infer_aten_op: + aten_op = utils.get_aten_op(prim, name) + if aten_op is not None and should_register_decomposition: + register_decomposition(aten_op)(_ref) + + return _ref + + return inner + + +def _binary_op_dtype( + a: TensorLikeType | NumberType, b: TensorLikeType | NumberType +) -> torch.dtype: + if isinstance(a, TensorLike): + return a.dtype + if isinstance(b, TensorLike): + return b.dtype + return utils.type_to_dtype(type(a)) + + +# Add has its own implementation because it has an alpha argument +@register_decomposition(aten.add) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a", "b"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def add( + a: TensorLikeType | NumberType, + b: TensorLikeType | NumberType, + *, + alpha: NumberType | None = None, +): + """ + Reference implementation of torch.add + """ + + a, b = _maybe_broadcast(a, b) + + if alpha is not None: + dtype = _binary_op_dtype(a, b) + python_type = utils.dtype_to_type(dtype) + if python_type is not bool and not utils.is_weakly_lesser_type( + type(alpha), python_type + ): + msg = f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!" + raise ValueError(msg) + if isinstance(b, TensorLike): + b = prims.mul(b, alpha) + else: + b = b * alpha + + output = prims.add(a, b) + return handle_noncontiguous_outputs([a, b], output) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def atan2(a, b): + return prims.atan2(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def bitwise_and(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.bitwise_and(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def bitwise_left_shift(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.shift_left(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def bitwise_or(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.bitwise_or(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def bitwise_right_shift(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.shift_right_arithmetic(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def bitwise_xor(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.bitwise_xor(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + supports_lhs_python_scalar=False, +) +def copysign(a: TensorLikeType | NumberType, b: TensorLikeType | NumberType): + if isinstance(b, Number) and isinstance(a, Tensor): + # pyrefly: ignore [bad-argument-type] + b = scalar_tensor(b, dtype=a.dtype, device=a.device) + elif isinstance(a, Tensor) and isinstance(b, Tensor) and a.device != b.device: + msg = f"Expected divisor (b) to be on the same device ({a.device}) as dividend (a), but it is found on {b.device}!" + raise RuntimeError(msg) + # pyrefly: ignore [bad-argument-type] + return where(signbit(b), neg(abs(a)), abs(a)) + + +# complex = _make_elementwise_binary_reference(prims.complex, type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT) + + +@register_decomposition(aten.div) +@out_wrapper() +def div( + a: TensorLikeType | NumberType, + b: TensorLikeType | NumberType, + *, + rounding_mode: str | None = None, +): + """ + Reference implementation of torch.div + """ + if rounding_mode is None: + return true_divide(a, b) + elif rounding_mode == "trunc": + return trunc_divide(a, b) + elif rounding_mode == "floor": + return floor_divide(a, b) + else: + msg = f"div expected rounding_mode to be one of None, 'trunc', or 'floor' but found {rounding_mode}." + raise ValueError(msg) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + supports_lhs_python_scalar=False, +) +def eq(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.eq(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.BOOL_TO_LONG, +) +def pow( + a: TensorLikeType | NumberType, + b: TensorLikeType | NumberType, +) -> TensorLikeType: + from torch.fx.experimental.symbolic_shapes import statically_known_true + + if not (isinstance(a, TensorLikeType) or isinstance(b, TensorLikeType)): + raise AssertionError("at least one of a or b must be TensorLikeType") + + if isinstance(b, Number): + if statically_known_true(b == 1.0): + return a.clone() # type: ignore[return-value,union-attr] + elif statically_known_true(b == 2.0): + return a * a # type: ignore[return-value] + elif statically_known_true(b == 0.5): + return torch.sqrt(a) # type: ignore[arg-type] + elif isinstance(a, Number): + if statically_known_true(a == 1.0): + return torch.fill(b, True) + if statically_known_true(a == 2.0) and ( + utils.is_float_dtype(b.dtype) or utils.is_complex_dtype(b.dtype) + ): + return torch.exp2(b) + + return prims.pow(a, b) + + +# Float power has its own implementation because it has unique type promotion. +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +def float_power( + a: TensorLikeType | NumberType, + b: TensorLikeType | NumberType, +) -> Tensor: + if isinstance(a, Number) and isinstance(b, Number): + raise ValueError( + "Receive two Number inputs to an elementwise binary operation!" + ) + + # Handles type promotion + dtype = utils.get_higher_dtype(a, b) + if dtype is None: + raise AssertionError("dtype should not be None after get_higher_dtype") + if utils.is_complex_dtype(dtype): + dtype = torch.complex128 + else: + dtype = torch.float64 + + # Float power has the following contiguous cast behavior to be + # consistent with its C++ impl + + a = _maybe_convert_to_dtype(a, dtype) + + b = _maybe_convert_to_dtype(b, dtype) + + a, b = _maybe_broadcast(a, b) + + return pow(a, b) + + +# >>> a = torch.tensor(-0.2500, dtype=torch.float64) +# tensor(-0.250000000000000, dtype=torch.float64) +# +# >>> b = torch.tensor(-0.0010, dtype=torch.float64) +# tensor(-0.001000000000000, dtype=torch.float64) +# +# Note: In this case, casting float to double will expand the float mantissa with zeros, +# while creating a double generates a distinct mantissa. +# >>> torch.tensor(-0.001).to(dtype=torch.float64) +# tensor(-0.001000000047497, dtype=torch.float64) +# +# Floor Division +# The difference is caused because torch.remainder(a, b) = -0.001. +# +# >>> torch.floor(torch.true_divide(a, b)) +# tensor(250., dtype=torch.float64) +# +# >>> torch.div(a, b, rounding_mode='floor') +# tensor(249., dtype=torch.float64) +# +# Definition: a // b = (a - remainder(a, b)) / b +# >>> torch.true_divide(torch.sub(a, torch.remainder(a, b)), b) +# tensor(249., dtype=torch.float64) +# +# For reference, see CPython's implementation: +# https://github.com/python/cpython/blob/ace008c531dd685a30c1dd68f9b5ba35f20171cf/Objects/floatobject.c#L636 + + +@_make_elementwise_binary_reference( + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_two_python_scalars=True, + should_register_decomposition=False, +) +def floor_divide(a: TensorLikeType | NumberType, b: TensorLikeType | NumberType): + # Wrap scalars because some references only accept tensor arguments. + if isinstance(a, Number) and isinstance(b, Number): + # pyrefly: ignore [bad-argument-type] + a = scalar_tensor(a) + # pyrefly: ignore [bad-argument-type] + b = scalar_tensor(b) + elif isinstance(b, Number) and isinstance(a, Tensor): + # pyrefly: ignore [bad-argument-type] + b = scalar_tensor(b, dtype=a.dtype, device=a.device) + elif isinstance(a, Number) and isinstance(b, Tensor): + # pyrefly: ignore [bad-argument-type] + a = scalar_tensor(a, dtype=b.dtype, device=b.device) + elif isinstance(a, Tensor) and isinstance(b, Tensor) and a.device != b.device: + if a.device == torch.device("cpu"): + msg = f"Expected divisor (b) to be on the same device ({a.device}) as dividend (a), but it is found on {b.device}!" + raise RuntimeError(msg) + else: + b = prims.device_put(b, device=a.device) + + if not (isinstance(a, Tensor) and isinstance(b, Tensor)): + raise AssertionError("a and b must both be Tensors at this point") + dtype = a.dtype + if utils.is_float_dtype(dtype): + return _floor_divide_float(a, b) + elif utils.is_integer_dtype(dtype): + return _floor_divide_integer(a, b) + else: + torch._check(False, lambda: f"{dtype} not supported for floor_divide") + + +def _floor_divide_integer(a: Tensor, b: Tensor) -> Tensor: + a, b = _maybe_broadcast(a, b) + + if not a.dtype.is_signed: + return prims.div(a, b) + + # Convert truncation to flooring: + offset = (torch.signbit(a) != torch.signbit(b)).logical_and(torch.fmod(a, b) != 0) + return prims.div(a, b) - _maybe_convert_to_dtype(offset, a.dtype) + + +def _floor_divide_float(a: Tensor, b: Tensor) -> Tensor: + mod = fmod(a, b) + div = true_divide(sub(a, mod), b) + + # Ensure that the remainder has the same sign as denominator + different_signed_inputs = bitwise_xor(lt(a, 0), lt(b, 0)) + non_zero_remainder = ne(mod, 0) + mask = bitwise_and(non_zero_remainder, different_signed_inputs) + div = where(mask, sub(div, 1), div) + + # Map quotient to nearest integer value + floor_div = floor(div) + mask = gt(sub(div, floor_div), 0.5) + floor_div = where(mask, add(floor_div, 1), floor_div) + + basic_div = true_divide(a, b) + zero_tensor = scalar_tensor(0, dtype=basic_div.dtype, device=basic_div.device) + + # If quotient is zero, copy signbit from true_divide quotient + floor_div = where(ne(div, 0), floor_div, copysign(zero_tensor, basic_div)) + + # If denominator is zero, then follow true_divide behavior + return where(ne(b, 0), floor_div, basic_div) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def fmax(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.fmax(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def fmin(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.fmin(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=True, +) +def fmod(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.fmod(a, b) + + +@register_decomposition(aten.frexp) +@out_wrapper("mantissa", "exponent") +def frexp(self: TensorLikeType) -> tuple[TensorLikeType, TensorLikeType]: + return torch.return_types.frexp(prims.frexp(self)) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def gcd(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.gcd(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + supports_lhs_python_scalar=False, +) +def ge(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.ge(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + supports_lhs_python_scalar=False, +) +def gt(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.gt(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def heaviside(input: TensorLikeType, values: TensorLikeType) -> TensorLikeType: + input_eq_zero = torch.eq(input, 0) + input_lt_zero = torch.logical_or(torch.lt(input, 0), torch.isnan(input)) + zeros_and_ones = torch.where(input_lt_zero, 0, 1) + output = torch.where(input_eq_zero, values, zeros_and_ones) + return output + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def hypot(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.hypot(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def igamma(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.igamma(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def igammac(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.igammac(a, b) + + +def _check_close_args( + name: str, + a: TensorLikeType, + b: TensorLikeType, + rtol: float, + atol: float, +) -> None: + torch._check_value( + a.dtype == b.dtype, + lambda: f"{name}: Attempting to compare tensors of different dtypes {a.dtype} and {b.dtype}!", + ) + torch._check( + rtol >= 0, + lambda: f"{name}: rtol must be greater than or equal to zero, but got {rtol}!", + ) + torch._check( + atol >= 0, + lambda: f"{name}: atol must be greater than or equal to zero, but got {atol}!", + ) + + +# CompositeImplicitAutograd - don't register decomp +def isclose( + a: TensorLikeType, + b: TensorLikeType, + rtol: float = 1e-05, + atol: float = 1e-08, + equal_nan: bool = False, +) -> TensorLikeType: + _check_close_args(name="torch.isclose", a=a, b=b, rtol=rtol, atol=atol) + + close = eq(a, b) + if equal_nan and (utils.is_float_dtype(a.dtype) or utils.is_complex_dtype(a.dtype)): + close = logical_or(close, logical_and(isnan(a), isnan(b))) + + # Note: In case of zero tolerances the closeness inequality degenerates to an equality check. + # In this case, the short-circuit prevents false positives as detailed in the paragraph below. + if atol == 0 and rtol == 0: + return close + + # Note [closeness error computation] + # atol and rtol are provided as doubles, so the computation + # rtol * other will produce a float or complex tensor. + # When the difference (self - other) is compared to it then the + # tensor representing the difference will also be cast to float or complex. + # However, since (self - other) in uint8 is very likely to produce a + # negative value, this moves the cast forward so the difference is + # always computed in a float or complex type. + # If the values of the integer tensors cannot be exactly represented + # by the default scalar type then this may cause an incorrect result. + if not utils.is_float_dtype(a.dtype) and not utils.is_complex_dtype(a.dtype): + a = prims.convert_element_type(a, torch.get_default_dtype()) + b = prims.convert_element_type(b, torch.get_default_dtype()) + + allowed_error = add(atol, abs(mul(b, rtol))) + actual_error = abs(sub(a, b)) + + # Computes finite closeness + result = logical_or( + close, logical_and(isfinite(actual_error), le(actual_error, allowed_error)) + ) + + return result + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def lcm(a: TensorLikeType, b: TensorLikeType): + dtype = a.dtype + # promoting to int32 to maintain 100% consistency with C++ and to + # prevent overflow in case of int8 and int16 + promote_to_int = dtype in (torch.int8, torch.int16) + if promote_to_int: + a = prims.convert_element_type(a, torch.int32) + b = prims.convert_element_type(b, torch.int32) + + g = torch.gcd(a, b) + # Avoid division by zero in case gcd(0, 0) == 0 + g = torch.where(g == 0, 1, g) + res = torch.abs(prims.div(a, g) * b) + return res if not promote_to_int else prims.convert_element_type(res, dtype) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + supports_lhs_python_scalar=False, +) +def le(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.le(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def logaddexp(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + # Nb. this implementation does not distribute the gradients evenly when a == b + mask = torch.real(a) >= torch.real(b) + max_ = torch.where(mask, a, b) + min_ = torch.where(mask, b, a) + inf_mask = torch.logical_and( + torch.logical_not(torch.isfinite(torch.real(a))), torch.real(a) == torch.real(b) + ) + if utils.is_complex_dtype(a.dtype) or utils.is_complex_dtype(b.dtype): + # are you wondering what this bunch of codes are for? edge cases! + neg_min_mask = torch.real(min_) < 0 + inf_vals = torch.where( + neg_min_mask, min_, torch.log(torch.exp(min_) + torch.exp(max_)) + ) + non_nan_vals = torch.where( + inf_mask, inf_vals, max_ + torch.log1p(torch.exp(min_ - max_)) + ) + # the type for full_like does not include tensor yet + nan_mask = torch.isnan(min_) + return torch.where(nan_mask, complex(float("nan"), float("nan")), non_nan_vals) # type: ignore[call-overload] + else: + return torch.where(inf_mask, a, max_ + torch.log1p(torch.exp(min_ - max_))) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def logaddexp2(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + torch._check( + not (utils.is_complex_dtype(a.dtype) or utils.is_complex_dtype(b.dtype)), + lambda: "logaddexp2 doesn't support complex dtypes", + ) + # Nb. this implementation does not distribute the gradients evenly when a == b + mask = a >= b + max_ = torch.where(mask, a, b) + min_ = torch.where(mask, b, a) + inf_mask = torch.logical_and(torch.isinf(a), a == b) + inv_log_2 = 1.0 / math.log(2) + result = max_ + torch.log1p(torch.exp2(min_ - max_)) * inv_log_2 + return torch.where(inf_mask, a, result) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) +def logical_and(a: TensorLikeType, b: TensorLikeType): + if not utils.is_boolean_dtype(a.dtype): + a = a != 0 + if not utils.is_boolean_dtype(b.dtype): + b = b != 0 + return a & b + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL) +def logical_not(a: TensorLikeType): + if not utils.is_boolean_dtype(a.dtype): + return a == 0 + return ~a + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) +def logical_or(a: TensorLikeType, b: TensorLikeType): + if not utils.is_boolean_dtype(a.dtype): + a = a != 0 + if not utils.is_boolean_dtype(b.dtype): + b = b != 0 + return bitwise_or(a, b) + + +# TODO: skip unnecessary conversion of long to float +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, +) +def logical_xor(a: TensorLikeType, b: TensorLikeType): + if not utils.is_boolean_dtype(a.dtype): + a = a != 0 + if not utils.is_boolean_dtype(b.dtype): + b = b != 0 + return a ^ b + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + supports_lhs_python_scalar=False, +) +def lt(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.lt(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def maximum(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.maximum(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def minimum(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.minimum(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + supports_two_python_scalars=True, +) +def mul(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.mul(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL, + supports_lhs_python_scalar=False, +) +def ne(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.ne(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH, + supports_lhs_python_scalar=False, + supports_rhs_python_scalar=False, +) +def nextafter(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.nextafter(a, b) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def remainder(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.remainder(a, b) + + +# reverse sub +@register_decomposition(aten.rsub) +@out_wrapper() +def rsub( + a: TensorLikeType | NumberType, + b: TensorLikeType | NumberType, + alpha: NumberType = 1, +): + if isinstance(a, Number): + msg = "Received a Number for the first argument, but expected a Tensor" + raise ValueError(msg) + + return torch.sub(b, a, alpha=alpha) + + +# TODO: consider refactoring this with add impl +# sub has its own implementation because it has an alpha argument +@register_decomposition(aten.sub) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a", "b"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def sub( + a: TensorLikeType | NumberType, + b: TensorLikeType | NumberType, + *, + alpha: NumberType = 1, +): + """ + Reference implementation of torch.sub + """ + + a, b = _maybe_broadcast(a, b) + + if isinstance(a, TensorLike) and isinstance(b, TensorLike): + torch._check_not_implemented( + not utils.is_boolean_dtype(a.dtype) and not utils.is_boolean_dtype(b.dtype), + lambda: ( + "Subtraction, the `-` operator, with two bool tensors is not supported. " + "Use the `^` or `logical_xor()` operator instead." + ), + ) + + if alpha != 1: + dtype = _binary_op_dtype(a, b) + python_type = utils.dtype_to_type(dtype) + if not utils.is_weakly_lesser_type(type(alpha), python_type): + msg = f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!" + raise ValueError(msg) + if isinstance(b, torch.Tensor): + b = prims.mul(b, alpha) + else: + # Carefully not to use prims.mul if b is a scalar / symint. + # prims.mul always returns a tensor, + # which will mess with type promotion. + b = b * alpha + + output = prims.sub(a, b) + return handle_noncontiguous_outputs([a, b], output) + + +@_make_elementwise_binary_reference( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + name="true_divide", + aten_op=None, # CompositeImplicitAutograd + supports_two_python_scalars=True, +) +def true_divide(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.div(a, b) + + +@register_decomposition(aten.xlogy) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a", "b"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def xlogy(a: TensorLikeType | NumberType, b: TensorLikeType | NumberType): + torch._check( + isinstance(a, TensorLike) or isinstance(b, TensorLike), + lambda: 'Expected either argument a or b to be a Tensor"', + ) + + # Operations like eq and log do not handle scalar values, so we convert them to scalar_tensors. + if isinstance(b, TensorLike) and isinstance(a, Number): + # pyrefly: ignore [bad-argument-type] + a = scalar_tensor(a, dtype=b.dtype, device=b.device) + elif isinstance(a, TensorLike) and isinstance(b, Number): + # pyrefly: ignore [bad-argument-type] + b = scalar_tensor(b, dtype=a.dtype, device=a.device) + + # mypy: expected "Tensor" + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") + if not isinstance(b, TensorLike): + raise AssertionError(f"b must be TensorLike, got {type(b)}") + rhs = torch.where(torch.eq(a, 0), 0, torch.mul(a, torch.log(b))) + return torch.where(torch.isnan(b), float("nan"), rhs) + + +@_make_elementwise_binary_reference( + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + aten_op=None, # CompositeImplicitAutograd + supports_two_python_scalars=True, +) +def trunc_divide(a: TensorLikeType | NumberType, b: TensorLikeType | NumberType): + dtype = utils.get_dtype(a) + if utils.is_integer_dtype(dtype): + return prims.div(a, b) + + return trunc(prims.div(a, b)) + + +# +# Elementwise Ternary References +# + + +@register_decomposition(aten.addcdiv) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self", "tensor1", "tensor2"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def addcdiv( + self: TensorLikeType, + tensor1: TensorLikeType, + tensor2: TensorLikeType, + *, + value: NumberType = 1, +) -> TensorLikeType: + """ + Reference implementation of torch.addcdiv + """ + if value is not None: + dtype = self.dtype # no scalars allowed, see add + python_type = utils.dtype_to_type(dtype) + torch._check_value( + utils.is_weakly_lesser_type(type(value), python_type), + lambda: f"value argument of type {type(value)} cannot be safely cast to type {python_type}!", + ) + + return self + value * tensor1 / tensor2 + + +@register_decomposition(aten.addcmul) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self", "tensor1", "tensor2"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def addcmul( + self: TensorLikeType, + tensor1: TensorLikeType, + tensor2: TensorLikeType, + *, + value: NumberType = 1, +) -> TensorLikeType: + """ + Reference implementation of torch.addcmul + """ + if value is not None: + dtype = self.dtype # no scalars allowed, see add + python_type = utils.dtype_to_type(dtype) + torch._check_value( + utils.is_weakly_lesser_type(type(value), python_type), + lambda: f"value argument of type {type(value)} cannot be safely cast to type {python_type}!", + ) + + return self + value * tensor1 * tensor2 + + +@register_decomposition(aten.clamp) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a", "min", "max"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def clamp( + a: TensorLikeType, + min: TensorOrNumberLikeType | None = None, + max: TensorOrNumberLikeType | None = None, +) -> TensorLikeType: + # NOTE: grad behavior with implementation `where` is not consistent on `nan` + if min is None and max is None: + msg = "clamp called but both min and max are none!" + raise ValueError(msg) + + if min is not None: + a_isnan = torch.isnan(a) + condition = torch.bitwise_or(torch.ge(a, min), a_isnan) # type: ignore[arg-type] + # we should also propagate `nan` coming from boundaries. However, that's + # not necessary since `ge` would already `False` when either operands has + # a `nan`. So this line below is redundant + # `condition = bitwise_and(condition, bitwise_not(isnan(min)))` + a = torch.where(condition, a, min) # type: ignore[arg-type] + if max is not None: + a_isnan = torch.isnan(a) + # same as above, no need to adjust `nan` from `max` + condition = torch.bitwise_or(torch.le(a, max), a_isnan) # type: ignore[arg-type] + a = torch.where(condition, a, max) # type: ignore[arg-type] + + return a + + +@register_decomposition(aten.clamp_min) +@out_wrapper() +def clamp_min( + self: TensorLikeType, + min: TensorOrNumberLikeType | None = None, +) -> TensorLikeType: + return torch.clamp(self, min=min) # type: ignore[arg-type] + + +@register_decomposition(aten.clamp_max) +@out_wrapper() +def clamp_max( + self: TensorLikeType, + max: TensorOrNumberLikeType | None = None, +) -> TensorLikeType: + return torch.clamp(self, max=max) # type: ignore[arg-type] + + +# +# Conditional references +# + + +# https://pytorch.org/docs/stable/generated/torch.where.html +@register_decomposition(aten.where.default) +def _where_default(pred: Tensor) -> tuple[Tensor, ...]: + return torch.nonzero(pred, as_tuple=True) + + +@register_decomposition(aten.where.self) +@register_decomposition(aten.where.ScalarSelf) +@register_decomposition(aten.where.ScalarOther) +@register_decomposition(aten.where.Scalar) +@register_decomposition(aten.where.self_out) +@out_wrapper(exact_dtype=True) +@elementwise_type_promotion_wrapper( + type_promoting_args=("a", "b"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH, +) +def where( + pred: Tensor, + a: TensorOrNumberLikeType | None = None, + b: TensorOrNumberLikeType | None = None, +): + """ """ + + if a is None or b is None: + raise NotImplementedError + + utils.check_same_device(pred, a, b, allow_cpu_scalar_tensors=True) + torch._check( + pred.dtype is torch.bool, + lambda: f"expected predicate to be bool, got {pred.dtype}", + ) + + pred, a, b = _maybe_broadcast(pred, a, b) + return prims.where(pred, a, b) + + +# +# Data Movement References +# +@register_decomposition(aten.clone) +@out_wrapper() +def clone( + a: TensorLikeType, *, memory_format: torch.memory_format = torch.preserve_format +) -> TensorLikeType: + result = prims.clone(a, memory_format=memory_format) + return result + + +def copy_to(a: Tensor, b: Tensor, *, allow_cross_device=True): + if not allow_cross_device and a.device != b.device: + msg = f"Attempting to copy from device {b.device} to device {a.device}, but cross-device copies are not allowed!" + raise RuntimeError(msg) + + return prims.copy_to(a, b) + + +@register_decomposition(aten.item) +def item(a: TensorLikeType) -> NumberType: + if a.numel() != 1: + msg = f"Can't convert a tensor with {a.numel()} elements to a number!" + raise ValueError(msg) + + # NOTE: explicit conversion is necessary for bool! + # See https://github.com/pytorch/pytorch/issues/78071 + number_type = utils.dtype_to_type(a.dtype) + return number_type(prims.item(a)) + + +# fast path when `to` returns an alias to input. This mimics the same function in aten +def _to_will_alias( + a: TensorLikeType, + device: DeviceLikeType | None = None, + dtype: torch.dtype | None = None, + copy: bool | None = None, + layout: torch.layout | None = None, + memory_format: torch.memory_format | None = None, + pin_memory: bool | None = False, + non_blocking: bool = False, # not using non_blocking +) -> bool: + return ( + not copy + and (device is None or a.device == device) + and (dtype is None or a.dtype == dtype) + and (layout is None or a.layout == layout) + # is_pinned issue #84925 + # and (pin_memory is None or pin_memory == a.is_pinned()) + and ( + memory_format is None + or memory_format == torch.preserve_format + or utils.is_contiguous_for_memory_format(a, memory_format=memory_format) + ) + ) + + +@singledispatch +def _to_dispatch(*args, **kwargs): + raise NotImplementedError + + +@_to_dispatch.register +def _to_device( + device: torch.device, + dtype: torch.dtype, + non_blocking: bool = False, + copy: bool = False, + memory_format: torch.memory_format | None = None, +) -> dict[str, Any]: + kwargs = { + "device": device, + "dtype": dtype, + "non_blocking": non_blocking, + "copy": copy, + "memory_format": memory_format, + } + return kwargs + + +@_to_dispatch.register +def _to_device_str( + device: str, + dtype: torch.dtype, + non_blocking: bool = False, + copy: bool = False, + memory_format: torch.memory_format | None = None, +) -> dict[str, Any]: + kwargs = { + "device": torch.device(device), + "dtype": dtype, + "non_blocking": non_blocking, + "copy": copy, + "memory_format": memory_format, + } + return kwargs + + +@_to_dispatch.register +def _to_dtype( + dtype: torch.dtype, + non_blocking: bool = False, + copy: bool = False, + memory_format: torch.memory_format | None = None, +) -> dict[str, Any]: + kwargs = { + "dtype": dtype, + "non_blocking": non_blocking, + "copy": copy, + "memory_format": memory_format, + } + return kwargs + + +@_to_dispatch.register +def _to_other( + other: Tensor, + non_blocking: bool = False, + copy: bool = False, + memory_format: torch.memory_format | None = None, +) -> dict[str, Any]: + device = other.device + dtype = other.dtype + layout = other.layout + # is_pinned issue #84925 + # pin_memory = other.is_pinned() + kwargs = { + "device": device, + "dtype": dtype, + "layout": layout, + "non_blocking": non_blocking, + "copy": copy, + "memory_format": memory_format, + } + return kwargs + + +# remove to_kwargs that is already present in `a` +def _canonicalize_to_arguments(a: Tensor, to_kwargs: dict): + options_to_check = ["dtype", "device", "layout", "memory_format"] + # "device" option could be passed a str instead torch.device + if "device" in to_kwargs and isinstance(to_kwargs["device"], str): + to_kwargs["device"] = torch.device(to_kwargs["device"]) + + for kw in options_to_check: + if kw in to_kwargs: + if ( + (kw == "memory_format" and to_kwargs[kw] is torch.preserve_format) + or ( + kw == "device" + and to_kwargs[kw].type == a.device.type + and ( + not to_kwargs[kw].index or to_kwargs[kw].index == a.device.index + ) + ) + or ( + getattr(a, kw, None) == to_kwargs[kw] + ) # this also handles {"memory_format": None} + ): + to_kwargs.pop(kw) + + +def to(a: TensorLikeType, *args, **kwargs) -> TensorLikeType: + # handled dispatch via positional arguments + if len(args) != 0: + kwargs = _to_dispatch(*args, **kwargs) + + # TODO: is_pinned is not currently supported in refs or fake_tensor + # https://github.com/pytorch/pytorch/issues/84925 + if "pin_memory" in kwargs: + raise AssertionError("pin_memory is not supported in refs") + _canonicalize_to_arguments(a, kwargs) + + if _to_will_alias(a, **kwargs): + return a + + copy = kwargs.pop("copy") if "copy" in kwargs else False + non_blocking = kwargs.pop("non_blocking") if "non_blocking" in kwargs else False + + # short-circuit to `prims.convert_element_type` when `to` is just a dtype change + if ( + (copy or (kwargs.get("dtype", a.dtype) != a.dtype)) + and (not non_blocking) + and ("memory_format" not in kwargs) + and ("device" not in kwargs) + and ("layout" not in kwargs) + # is_pinned issue #84925 + # and ("pin_memory" not in kwargs) + ): + return prims.convert_element_type(a, kwargs.get("dtype", a.dtype)) + + result = torch.empty_like(a, **kwargs) + # TODO: non_blocking should be handled by `copy_to` + copy_to(result, a) + return result + + +# +# Reduction references +# + + +def _reduction( + a: TensorLikeType, + prim: Callable, + *, + has_identity: bool = True, + accepts_dim_tuple: bool = True, # to handle min/argmin that accept single dim only + dims: DimsType | None = None, + keepdims: bool = False, + dtype: torch.dtype | None = None, # should be specified for ops that support it + out: Tensor | None = None, + output_dtype_kind: REDUCTION_OUTPUT_TYPE_KIND, +) -> TensorLikeType: # it is usually SAME, but I want + # ref writers to actually think about what to put here + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") + if a.ndim > 64: + raise RuntimeError( + f"Received a tensor with {a.ndim} dimensions, but only tensors with up to 64 dims are supported!" + ) + + if out is not None: + if not isinstance(out, TensorLike): + raise AssertionError(f"out must be TensorLike, got {type(out)}") + if dtype is not None: + # TODO - this is true for eager mode currently, but it's wrong behavior for complex norms + if dtype != out.dtype: + raise RuntimeError( + "dtype argument and out dtype must match in reduction" + ) + if not accepts_dim_tuple: + if not (dims is None or isinstance(dims, Dim)): + raise AssertionError(f"dims must be None or Dim, got {type(dims)}") + if isinstance(dims, Dim): + dims = (dims,) # type: ignore[assignment] + dims = utils.reduction_dims(a.shape, dims) + if not has_identity: + from torch.fx.experimental.symbolic_shapes import sym_and + + valid_shape = a.ndim == 0 or sym_and(*(a.shape[i] > 0 for i in dims)) + torch._check( + valid_shape, + lambda: "reducing over zero-size dimension for reduction operation without identity", + ) + + computation_dtype, result_dtype = utils.reduction_dtypes( + a, output_dtype_kind, dtype + ) + a = _maybe_convert_to_dtype(a, computation_dtype) # type: ignore[method-assign] + result = prim(a, dims) + if keepdims: + output_shape = [a.shape[i] if i not in dims else 1 for i in range(a.ndim)] + broadcast_dims = [i for i in range(a.ndim) if i not in dims] + result = prims.broadcast_in_dim(result, output_shape, broadcast_dims) + + if out is not None: + if result_dtype is None: + raise AssertionError("result_dtype should not be None when out is provided") + if dtype is not None and result_dtype != out.dtype: + raise RuntimeError( + "Expected the dtype of reduction result and out to match" + ) + out = _maybe_resize_out(out, result.shape) + return _safe_copy_out(copy_from=result, copy_to=out) # type: ignore[arg-type] + + if result.dtype != result_dtype and result_dtype is not None: + result = prims.convert_element_type(result, result_dtype) + + return result + + +def _make_copy_from_view(fn, return_none_on_out_variant=False): + """ + Given a view function (e.g. torch.diagonal) generates its copy variant (e.g. torch.diagonal_copy) + """ + aten_fn = getattr(aten, fn.__name__) + annotations = getattr(fn, "__annotations__", {}) + # view ops should not change dtypes, this ensures that the decomp path has + # the same error checks as eager. + fn = out_wrapper(exact_dtype=True)(aten_fn) + + @wraps(fn) + def _fn(*args, out=None, **kwargs): + result = fn(*args, out=out, **kwargs) + if return_none_on_out_variant and out is not None: + return None + if out is not None: + return result + + return pytree.tree_map( + lambda x: x.clone(memory_format=torch.contiguous_format), + result, + ) + + copy_name = f"{fn.__name__}_copy" + _fn.__name__ = copy_name + _fn.__annotations__.update(annotations) + register_decomposition(getattr(aten, copy_name))(_fn) + return _fn + + +@register_decomposition(aten.all) +@out_wrapper() +def all( + a: TensorLikeType, + dim: DimsType | None = None, + keepdim: bool = False, +) -> TensorLikeType: + result = torch.logical_not(torch.any(torch.logical_not(a), dim, keepdim=keepdim)) + + if a.dtype == torch.uint8: + result = result.to(dtype=torch.uint8) + + return result + + +@register_decomposition(aten.any) +@out_wrapper() +def any( + a: TensorLikeType, + dim: DimsType | None = None, + keepdim: bool = False, +) -> TensorLikeType: + a_ = _maybe_convert_to_dtype(a, torch.bool) + if isinstance(dim, (list, tuple)) and len(dim) == 0: + result = a_.clone() + else: + result = a_.sum(dim=dim, keepdim=keepdim).ne(False) + + # Preserves uint8 -- probably a legacy mask thing + if a.dtype is torch.uint8: + return prims.convert_element_type(result, torch.uint8) + + return result + + +@register_decomposition([aten.sum.dim_IntList, aten.sum.IntList_out]) +def sum( + a: TensorLikeType, + dim: int | None | list[int] = None, + keepdim: bool = False, + *, + dtype: torch.dtype | None = None, + out: Tensor | None = None, +) -> TensorLikeType: + if dtype is None: + if out is not None: + dtype = out.dtype + elif utils.is_boolean_dtype(a.dtype) or utils.is_integer_dtype(a.dtype): + dtype = torch.int64 + else: + dtype = a.dtype + # reduces over all dimensions if dim=() is passed + if dim == () or dim == []: + dim = None + return _reduction( + a, + prims.sum, + dims=dim, + keepdims=keepdim, + dtype=dtype, + out=out, + output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.SAME, + ) + + +def sum_to_size( + a: Tensor, + *shape, +) -> Tensor: + shape = utils.extract_shape_from_varargs(shape, validate=False) + torch._check( + utils.is_expandable_to(shape, a.shape), + lambda: f'sum_to_size: size "{shape}" is not expandable to size "{a.shape}"', + ) + # In ATen scalar tensors are sent through sum and the result is returned as + # type promoted + if utils.is_same_shape(shape, a.shape) and len(shape) > 0: + return prims.view_of(a) + leading_dims = a.ndim - len(shape) + reduce_dims = tuple(range(leading_dims)) + tuple( + i + for i in range(leading_dims, len(shape)) + if shape[i - leading_dims] == 1 and a.shape[i] != 1 + ) + return torch.sum(a, dim=reduce_dims, keepdim=True, dtype=None) + + +@register_decomposition(aten.prod) +def prod( + a: TensorLikeType, + dim: int | None | list[int] = None, + keepdim: bool = False, + *, + dtype=None, + out: Tensor | None = None, +) -> TensorLikeType: + if dtype is None: + if out is not None: + dtype = out.dtype + elif utils.is_boolean_dtype(a.dtype) or utils.is_integer_dtype(a.dtype): + dtype = torch.int64 + else: + dtype = a.dtype + # reduces over all dimensions if dim=() is passed + if dim == () or dim == []: + dim = None + return _reduction( + a, + prims.prod, + dims=dim, + keepdims=keepdim, + dtype=dtype, + out=out, + output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.SAME, + ) + + +@register_decomposition(aten.amin) +def amin( + a: TensorLikeType, + dim: DimsType | None = None, + keepdim: bool = False, + *, + out: Tensor | None = None, +) -> TensorLikeType: + # reduces over all dimensions if dim=() is passed + if dim == () or dim == []: + dim = None + + return _reduction( + a, + prims.amin, + dims=dim, + keepdims=keepdim, + dtype=None, + out=out, + has_identity=False, + output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.SAME, + ) + + +@register_decomposition(aten.amax) +def amax( + a: TensorLikeType, + dim: DimsType | None = None, + keepdim: bool = False, + *, + out: Tensor | None = None, +) -> TensorLikeType: + # reduces over all dimensions if dim=() is passed + if dim == () or dim == []: + dim = None + + return _reduction( + a, + prims.amax, + dims=dim, + keepdims=keepdim, + dtype=None, + out=out, + has_identity=False, + output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.SAME, + ) + + +def _dim_var_dispatch(dim=None, unbiased=None): + # There's the following overload of torch.var: + # var(Tensor self, bool unbiased=True) -> (Tensor, Tensor) + # We need to explicitly convert bool dims to unbiased arg + if unbiased is None and isinstance(dim, bool): + unbiased = dim + dim = None + return dim, unbiased + + +@register_decomposition(aten.var) +@out_wrapper() +def var( + a: TensorLikeType, + dim: DimsType | None = None, + unbiased: bool | None = None, + keepdim: bool = False, + *, + correction: NumberType | None = None, +) -> TensorLikeType: + dim, unbiased = _dim_var_dispatch(dim, unbiased) + correction = utils.set_correction(unbiased, correction) + # reduces over all dimensions if dim=() is passed + if dim == () or dim == []: + dim = None + + result = _reduction( + a, + partial(prims.var, correction=correction), + dims=dim, + keepdims=keepdim, + dtype=None, + out=None, + has_identity=True, + output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT, + ) + return result + + +@register_decomposition(aten.std) +@out_wrapper() +def std( + a: TensorLikeType, + dim: int | None | list[int] = None, + unbiased: bool | None = None, + keepdim: bool = False, + *, + correction: NumberType | None = None, +) -> TensorLikeType: + dim, unbiased = _dim_var_dispatch(dim, unbiased) + correction = utils.set_correction(unbiased, correction) + + opmath_dtype, dtype = utils.reduction_dtypes( + a, REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT + ) + a = _maybe_convert_to_dtype(a, opmath_dtype) + a_var = torch.var(a, dim, correction=correction, keepdim=keepdim) + a_std = torch.sqrt(a_var) + if dtype is None: + raise AssertionError("dtype should not be None after reduction_dtypes") + return _maybe_convert_to_dtype(a_std, dtype) + + +@register_decomposition(aten.mean) +def mean( + a: TensorLikeType, + dim: DimsType | None = None, + keepdim: bool = False, + *, + dtype=None, + out=None, +) -> TensorLikeType: + # reduces over all dimensions if dim=() is passed + if dim == () or dim == []: + dim = None + orig_dtype = dtype + if dtype is None: + dtype = a.dtype + result = _reduction( + a, + prims.sum, + dims=dim, + keepdims=keepdim, + dtype=dtype, + out=None, + output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.KEEP_PROMOTED_TYPE, + ) + torch._check( + utils.is_float_dtype(dtype) or utils.is_complex_dtype(dtype), + lambda: ( + f"mean(): could not infer output dtype. " + f"{'Input' if orig_dtype is None else 'Optional'} dtype must be either " + f"a floating point or complex dtype. Got: {dtype}" + ), + ) + if isinstance(dim, Dim): + dim = (dim,) # type: ignore[assignment] + dims = utils.reduction_dims(a.shape, dim) # type: ignore[arg-type] + nelem = 1 if a.ndim == 0 else reduce(operator.mul, (a.shape[i] for i in dims), 1) + result = true_divide(result, nelem) + result_dtype = a.dtype if dtype is None else dtype + result = _maybe_convert_to_dtype(result, result_dtype) # type: ignore[method-assign] + if out is not None: + if not isinstance(out, TensorLike): + raise AssertionError(f"out must be TensorLike, got {type(out)}") + out = _maybe_resize_out(out, result.shape) + return _safe_copy_out(copy_from=result, copy_to=out) # type: ignore[arg-type] + return result + + +@register_decomposition(aten.std_mean) +@out_wrapper("out0", "out1") +def std_mean( + a: TensorLikeType, + dim: DimsType | None = None, + *, + unbiased: bool | None = None, + keepdim: bool = False, + correction: NumberType | None = None, +): + dim, unbiased = _dim_var_dispatch(dim, unbiased) + correction = utils.set_correction(unbiased, correction) + opmath_dtype, dtype = utils.reduction_dtypes( + a, REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT + ) + original_dtype = a.dtype + a = _maybe_convert_to_dtype(a, opmath_dtype) + a_var, a_mean = torch.var_mean(a, dim, correction=correction, keepdim=keepdim) + a_std = torch.sqrt(a_var) + if dtype is None: + raise AssertionError("dtype should not be None after reduction_dtypes") + return ( + _maybe_convert_to_dtype(a_std, dtype), + _maybe_convert_to_dtype(a_mean, original_dtype), + ) + + +@register_decomposition(aten.var_mean) +@out_wrapper("out0", "out1") +def var_mean( + a: TensorLikeType, + dim: DimsType | None = None, + unbiased: bool | None = None, + keepdim: bool = False, + *, + correction: NumberType | None = None, +): + dim, unbiased = _dim_var_dispatch(dim, unbiased) + v = var(a, dim, unbiased, keepdim, correction=correction) + m = mean(a, dim, keepdim) + return v, m + + +@register_decomposition(aten.addr) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self", "vec1", "vec2"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def addr( + self: TensorLikeType, + vec1: TensorLikeType, + vec2: TensorLikeType, + *, + beta: NumberType = 1, + alpha: NumberType = 1, +) -> TensorLikeType: + torch._check( + vec1.ndim == 1, + lambda: f"addr: Expected 1-D argument vec1, but got {vec1.ndim}-D", + ) + torch._check( + vec2.ndim == 1, + lambda: f"addr: Expected 1-D argument vec2, but got {vec2.ndim}-D", + ) + for arg, arg_name in ((alpha, "alpha"), (beta, "beta")): + if isinstance(arg, bool): + torch._check( + utils.is_boolean_dtype(self.dtype) + and utils.is_boolean_dtype(vec1.dtype) + and utils.is_boolean_dtype(vec2.dtype), + lambda: f"Boolean {arg_name} only supported for Boolean results.", + ) + self = self.expand(vec1.shape[0], vec2.shape[0]) + if utils.is_boolean_dtype(self.dtype): + # Integers are accepted for booleans + torch._check( + is_weakly_lesser_type(type(beta), int), + lambda: f"expected bool/int beta but got {type(beta)}", + ) + torch._check( + is_weakly_lesser_type(type(alpha), int), + lambda: f"expected bool/int alpha but got {type(alpha)}", + ) + if not beta: + return torch.outer(vec1, vec2) if alpha else torch.full_like(self, False) + else: + return torch.logical_or( + self, + torch.outer(vec1, vec2) if alpha else torch.full_like(self, False), + ) + else: + torch._check( + is_weakly_lesser_type(type(beta), dtype_to_type(self.dtype)), + lambda: f"cannot safely convert {type(beta)} to {self.dtype}", + ) + torch._check( + is_weakly_lesser_type(type(alpha), dtype_to_type(self.dtype)), + lambda: f"cannot safely convert {type(alpha)} to {self.dtype}", + ) + if beta == 0: + # This means NaNs from self are dropped if beta is zero + return alpha * torch.outer(vec1, vec2) + else: + return beta * self + alpha * torch.outer(vec1, vec2) + + +# CompositeImplicitAutograd - don't register decomp +def atleast_1d( + arg: TensorLikeType | Sequence[TensorLikeType], *args: TensorLikeType +) -> TensorLikeType | tuple[TensorLikeType, ...]: + """Reference implementation of :func:`torch.atleast_1d`.""" + if not args and isinstance(arg, collections.abc.Sequence): + args_ = arg + else: + if isinstance(arg, collections.abc.Sequence): + raise AssertionError("arg should not be a Sequence when args is provided") + args_ = (arg,) + args + res = tuple(a if a.ndim >= 1 else unsqueeze(a, 0) for a in args_) + return res if len(res) > 1 else res[0] + + +# Helper function with assert to avoid MyPy error +# of incompatible type passed to unsqueeze +def _unsqueeze_atleast( + at_least_fn: Callable, dim: int, arg: TensorLikeType +) -> TensorLikeType: + arg_ = at_least_fn(arg) + if not isinstance(arg_, TensorLike): + raise AssertionError(f"at_least_fn must return TensorLike, got {type(arg_)}") + return unsqueeze(arg_, dim) + + +# CompositeImplicitAutograd - don't register decomp +def atleast_2d( + arg: TensorLikeType | Sequence[TensorLikeType], *args: TensorLikeType +) -> TensorLikeType | tuple[TensorLikeType, ...]: + """Reference implementation of :func:`torch.atleast_2d`.""" + if not args and isinstance(arg, collections.abc.Sequence): + args_ = arg + else: + if isinstance(arg, collections.abc.Sequence): + raise AssertionError("arg should not be a Sequence when args is provided") + args_ = (arg,) + args + unsqueeze_atleast_1d = partial(_unsqueeze_atleast, atleast_1d, 0) + res = tuple(a if a.ndim >= 2 else unsqueeze_atleast_1d(a) for a in args_) + return res if len(res) > 1 else res[0] + + +# CompositeImplicitAutograd - don't register decomp +def atleast_3d( + arg: TensorLikeType | Sequence[TensorLikeType], *args: TensorLikeType +) -> TensorLikeType | tuple[TensorLikeType, ...]: + """Reference implementation of :func:`torch.atleast_3d`.""" + if not args and isinstance(arg, collections.abc.Sequence): + args_ = arg + else: + if isinstance(arg, collections.abc.Sequence): + raise AssertionError("arg should not be a Sequence when args is provided") + args_ = (arg,) + args + unsqueeze_atleast_2d = partial(_unsqueeze_atleast, atleast_2d, -1) + res = tuple(a if a.ndim >= 3 else unsqueeze_atleast_2d(a) for a in args_) + return res if len(res) > 1 else res[0] + + +def as_strided( + a: TensorLikeType, + size: ShapeType, + stride: StrideType, + storage_offset: int | None = None, +) -> TensorLikeType: + storage_offset_int = ( + storage_offset if storage_offset is not None else a.storage_offset() + ) + return prims.as_strided(a, size, stride, storage_offset_int) + + +@register_decomposition(aten.as_strided_scatter) +@out_wrapper() +def as_strided_scatter( + input: TensorLikeType, + src: TensorLikeType, + size: ShapeType, + stride: StrideType, + storage_offset: int | None = None, +) -> TensorLikeType: + storage_offset_int = 0 if storage_offset is None else storage_offset + return prims.as_strided_scatter(input, src, size, stride, storage_offset_int) + + +def broadcast_shapes(*shapes) -> ShapeType: + return torch.Size(_broadcast_shapes(*shapes)) + + +@aten.broadcast_tensors.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.broadcast_tensors.default.py_impl(DispatchKey.Meta) +def broadcast_tensors(*tensors) -> list[TensorLikeType]: + if len(tensors) == 1 and not isinstance(tensors[0], Tensor): + tensors = tensors[0] + return list(_maybe_broadcast(*tensors, preserve_cpu_scalar_tensors=False)) + + +# CompositeImplicitAutograd - don't register decomp +def broadcast_to(a: TensorLikeType, size: ShapeType) -> TensorLikeType: + start = len(size) - len(a.shape) + dims = tuple(range(start, len(a.shape) + start)) + return prims.broadcast_in_dim(a, size, dims) + + +@register_decomposition(aten.cat) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("tensors",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH, +) +def cat(tensors: TensorSequenceType, dim: int = 0) -> TensorLikeType: + def cat_compute_output_memory_format(inputs): + format = None + for t in inputs: + f = utils.suggest_memory_format(t) + if f == torch.contiguous_format: + return f + if format is not None and format != f: + return torch.contiguous_format + format = f + if format is None: + raise AssertionError("format should not be None if len(inputs) > 0") + return format + + if len(tensors) == 0: + msg = "cat expects at least one tensor, but received zero!" + raise ValueError(msg) + + for tensor in tensors: + if not isinstance(tensor, TensorLike): + raise AssertionError(f"tensor must be TensorLike, got {type(tensor)}") + + utils.check_same_device(*tensors, allow_cpu_scalar_tensors=False) + + from torch.fx.experimental.symbolic_shapes import guard_or_false + + # This is a bit tricky. Naively, you would expect to just pick one + # arbitrary tensor and check that all tensors match this tensor. However, + # there is legacy behavior which says that if you have a 1-D empty tensor + # (0,), this is permissible. So you can't assume that all the tensors + # have same dimensionality, and you can't assume that the first tensor is + # the correct stencil. + # + # We'll implement this in a few passes. First, we will try to infer the + # ndim of the cat output. If this ndim != 1, then we know that all ndim = + # 1 inputs must be empty, or are errors. If this ndim == 1, then life + # is easy (the legacy special case coincides with regular handling). + # + # NB: The regular implementation of cat just filters out empty inputs, + # but we do it slightly different here for better handling for unbacked + # SymInts + + example = None + # pyrefly: ignore [bad-assignment] + for i, t in enumerate(tensors): + if example is None: + if t.ndim != 1: + example = t + else: + if t.ndim != 1: + torch._check( + t.ndim == example.ndim, + lambda: "Number of dimensions of tensors must match. " + f"Expected {example.ndim}-D tensors, but got {t.ndim}-D for " + f"tensor number {i} in the list", + ) + + if example is None: + # example is None if everything is 1-D. If so, just arbitrarily pick + # the first one + example = tensors[0] + + shape = example.shape + filtered = [] + for tensor_idx, tensor in enumerate(tensors): + if len(shape) != len(tensor.shape): + if tensor.ndim != 1: + raise AssertionError( + f"tensor.ndim should be 1 at this point, got {tensor.ndim}" + ) + # Don't suggest the legacy behavior in the error message + torch._check( + # NB: it is not enough to simply assert that tensor.shape[0] == 0; + # this MUST be true even under guard size oblivious. + # Effectively, we must actually know that the shape is zero, + # passing an unbacked SymInt which we will defer a runtime + # assert on won't cut it. This is a policy decision (size + # oblivious semantics say that u0 tensors never are inferred + # to be zero size, even if they must be that for the cat to go + # through), and is load bearing for our Inductor lowerings + # (which assume that size oblivious tests are OK to determine + # if a shape is permissibly zero.) + guard_or_false(tensor.shape[0] == 0), + lambda: f"Number of dimensions of tensors must match. " + f"Expected {example.ndim}-D tensors, but got 1-D for " + f"tensor number {tensor_idx} in the list", + ) + else: + # Remove inputs that are 1-D, zero size + if tensor.ndim == 1 and guard_or_false(tensor.shape[0] == 0): + continue + # Don't bother checking size match, prims.cat will handle it + filtered.append(tensor) + + memory_format = cat_compute_output_memory_format(tensors) + + if len(filtered) == 0: + t = tensors[0] + + # TODO: fix this to work with meta tensors + try: + # BUG? This looks like it wants to call builtins.any() but is + # actually calling .any() (in this file). Changing to builtins.any() + # causes tests to fail: + # PYTORCH_OPINFO_SAMPLE_INPUT_INDEX=4 python test/test_ops.py -k \ + # TestFakeTensorCUDA.test_fake_crossref_backward_amp_cat_cuda_float32 + requires_grad = bool(any(x.requires_grad for x in tensors)) # type: ignore[arg-type] + except Exception: + requires_grad = False # type: ignore[assignment] + + return empty( + (0,), + dtype=t.dtype, + device=t.device, + requires_grad=requires_grad, + memory_format=memory_format, + ) + + dim = utils.canonicalize_dim(filtered[0].ndim, dim) + utils.validate_idx(filtered[0].ndim, dim) + + return prims.cat(filtered, dim).clone(memory_format=memory_format) + + +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +def column_stack(tensors: TensorSequenceType) -> TensorLikeType: + aligned_tensors = tuple( + x if x.ndim > 1 else x.reshape((x.numel(), 1)) for x in tensors + ) + return cat(aligned_tensors, 1) + + +def conj(input: TensorLikeType) -> TensorLikeType: + if not utils.is_complex_dtype(input.dtype): + return input + if input.is_sparse: + return torch.conj_physical(input) + return prims.conj(input) + + +# This replicates at::constant_pad_nd, defined in ATen/native/PadNd.cpp +@register_decomposition(aten.constant_pad_nd) +@out_wrapper() +def constant_pad_nd( + input: TensorLikeType, pad: list[int], value: NumberType = 0 +) -> TensorLikeType: + torch._check( + len(pad) % 2 == 0, + lambda: f"Length of pad must be even but instead it equals {len(pad)}", + ) + + input_sizes = input.shape + l_inp = len(input_sizes) + + l_pad = len(pad) // 2 + l_diff = l_inp - l_pad + + torch._check( + l_inp >= l_pad, + lambda: "Length of pad should be no more than twice the number of " + f"dimensions of the input. Pad length is {len(pad)} while the input has " + f"{l_inp} dimensions.", + ) + + c_input = input + for i in range(l_diff, l_inp): + pad_idx = 2 * (l_inp - i - 1) + if pad[pad_idx] < 0: + c_input = c_input.narrow(i, -pad[pad_idx], c_input.shape[i] + pad[pad_idx]) + + if pad[pad_idx + 1] < 0: + c_input = c_input.narrow(i, 0, c_input.shape[i] + pad[pad_idx + 1]) + + # If all the pads are negative we can return the result. + # Avoid early exiting if all pads = 0 to prevent specialization on export. + # During export, raw if statements are specialized on the input, meaning + # that we lose a branch depending on the example input used to export. + # Here, this is either the case where all pads = 0, or the case where at + # least one pad > 0 and the rest are >= 0. + # Avoiding the early exit when all pads = 0 ensures we can export + # constant_pad_nd for cases when all pads >= 0. + # Note: if any pads are negative, this code specializes due to the if statements above. + if builtins.all(p < 0 for p in pad): + return c_input.clone() + + for i in range(l_pad): + pad_idx = len(pad) - ((i + 1) * 2) + new_dim = input_sizes[l_diff + i] + pad[pad_idx] + pad[pad_idx + 1] + torch._check( + new_dim >= 0, + lambda: f"The input size {input_sizes[l_diff + i]}, plus negative padding " + f"{pad[pad_idx]} and {pad[pad_idx + 1]} resulted in a negative output size, " + f"which is invalid. Check dimension {l_diff + i} of your input.", + ) + + if value == 0 and input.dtype == torch.bool: + value = False + + result = c_input + for i in range(l_diff, l_inp): + pad_idx = 2 * (l_inp - i - 1) + left = max(pad[pad_idx], 0) + right = max(pad[pad_idx + 1], 0) + if left == 0 and right == 0: + continue + parts = [] + if left > 0: + left_shape = list(result.shape) + left_shape[i] = left + # torch.full isn't typed to allow complex values + parts.append( + torch.full(left_shape, value, dtype=input.dtype, device=input.device) # type: ignore[arg-type] + ) + parts.append(result) + if right > 0: + right_shape = list(result.shape) + right_shape[i] = right + # torch.full isn't typed to allow complex values + parts.append( + torch.full(right_shape, value, dtype=input.dtype, device=input.device) # type: ignore[arg-type] + ) + result = torch.cat(parts, dim=i) + + if result is c_input: + result = result.clone() + + return result.contiguous(memory_format=utils.suggest_memory_format(input)) + + +def contiguous( + a: Tensor, *, memory_format: torch.memory_format = torch.contiguous_format +) -> Tensor: + torch._check( + memory_format != torch.preserve_format, + lambda: "preserve memory format is unsupported by the contiguous operator", + ) + + # TODO: make logic consistent with aten contiguous + if is_contiguous_for_memory_format_or_false(a, memory_format=memory_format): + return a + + return torch.clone(a, memory_format=memory_format) + + +@out_wrapper() +def dstack(tensors: TensorSequenceType) -> TensorLikeType: + torch._check(len(tensors) > 0, lambda: "dstack expects a non-empty TensorList") + aligned_tensors = atleast_3d(*tensors) + return cat(aligned_tensors, 2) + + +@register_decomposition(aten.expand) +def expand(a: Tensor, *shape, implicit: bool = False) -> Tensor: + from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + guarding_hint_or_throw, + has_guarding_hint, + sym_or, + ) + + backed_so = torch.fx.experimental._config.backed_size_oblivious + + # NOTE: cannot use utils.extract_shape_from_varargs here + # because that also validates the shape, but the shape + # given to expand may be "invalid" + if len(shape) == 1 and isinstance(shape[0], Sequence): + shape = tuple(shape[0]) + + torch._check( + len(shape) >= len(a.shape), + lambda: "expand: the requested shape has too few dimensions!", + ) + + offset = len(shape) - len(a.shape) + shape_ = list(shape) + for idx, x in enumerate(a.shape): + offset_idx = idx + offset + requested_length = shape[offset_idx] + + # expand(in -> out) has 3 different semantics: + # 1) out == -1 -> size = in, stride unchanged + # 2) in == 1 -> size = out, stride = 0 + # 3) in == out -> size = in, stride unchanged + # + # the code below is written for unbacked semantics s.t. we assume unbacked symbols don't + # represent -1 unless explicitly specified, and the user is opting for case 2) or 3). + # the sym_or allows either case, but in the decomposition's current state, broadcast_in_dim() + # will either assume case 3) (via validate_shape() marking the expanded shape size-like), or will + # raise a data-dependent error trying to figure out if the stride is 0, requiring the user to manually + # select between the semantics of cases 2) and 3). + if guard_or_false(requested_length == -1): + shape_[offset_idx] = x + else: + # When backed size oblivious is used, we specialize for broadcasting + # if it's the only way to compile the example input. + # i.e: x:1, requested_length:1 ==> + # assert x==requested_length, no specialization on ==1 or !=1. + # The non-broadcast path is picked + # x:1, requested_length:4 ==> + # specialize(x) to be 1. + if ( + backed_so + and has_guarding_hint(x) + and has_guarding_hint(requested_length) + ): + x_hint = guarding_hint_or_throw(x) + requested_hint = guarding_hint_or_throw(requested_length) + if x_hint == 1 and requested_hint != 1: + torch._check(x == 1) + + torch._check( + sym_or(x == 1, requested_length == x), + lambda: f"expand: attempting to expand a dimension of length {x} -> {requested_length}!", + ) + torch._check(requested_length >= 0) + shape_[offset_idx] = requested_length + + # At this point shape must be valid + utils.validate_shape(shape_) + + return prims.broadcast_in_dim( + a, shape_, tuple(range(offset, len(a.shape) + offset)) + ) + + +# CompositeImplicitAutograd - don't register decomp +def expand_as(a: Tensor, b: Tensor) -> Tensor: + return a.expand(b.shape) + + +def chunk(a: TensorLikeType, chunks: int, dim: int = 0) -> tuple[TensorLikeType, ...]: + if chunks <= 0: + msg = f"Expected at least one chunk, but got {chunks}!" + raise ValueError(msg) + + dim = utils.canonicalize_dim(a.ndim, dim) + length = a.shape[dim] + chunk_size = math.ceil(length / chunks) + full_chunks = math.floor(length / chunk_size) + tail_chunk_size = length % chunk_size + + result = [narrow(a, dim, i * chunk_size, chunk_size) for i in range(full_chunks)] + + if tail_chunk_size != 0: + result.append(narrow(a, dim, full_chunks * chunk_size, tail_chunk_size)) + + return tuple(result) + + +# Note: flatten, unlike other shape operators, returns the input tensor on a no-op (unless +# a 0D tensor is flattened, in which case it's returned in 1D) +# CompositeImplicitAutograd - don't register decomp +def flatten(a: TensorLikeType, start_dim: int = 0, end_dim: int = -1) -> TensorLikeType: + start_dim = utils.canonicalize_dim(a.ndim, start_dim) + end_dim = utils.canonicalize_dim(a.ndim, end_dim) + + # Short-circuits on no-op + if start_dim == end_dim and a.ndim != 0: + return a + + # Tries to take a view + # TODO: we could look at directing collapse_view to skip its meta function here (unsafe_collapse_view) + # Unbacked semantics: if validity of in-place flattening is undecided we copy. + new_shape, _new_strides = prims._collapse_view_helper( + a, start_dim, end_dim, must_be_valid=None + ) + if new_shape is not None: + return prims.collapse_view(a, start_dim, end_dim) + + # Makes a copy if it can't make a view + return prims.collapse(a, start_dim, end_dim) + + +@register_decomposition(aten.flip) +@out_wrapper() +def flip(a: TensorLikeType, dims: DimsSequenceType) -> TensorLikeType: + if not isinstance(dims, tuple) and not isinstance(dims, list): + raise ValueError("dims has to be a sequence of ints") + dims = utils.canonicalize_dims(a.ndim, dims) # type: ignore[assignment] + utils.validate_no_repeating_dims(dims) + if a.ndim == 0: + return torch.clone(a) + return prims.rev(a, dims) + + +# CompositeImplicitAutograd - don't register decomp +def fliplr(a: TensorLikeType) -> TensorLikeType: + if a.ndim < 2: + raise RuntimeError("Input must be >= 2-d.") + + return flip(a, (1,)) + + +# CompositeImplicitAutograd - don't register decomp +def flipud(a: TensorLikeType) -> TensorLikeType: + if a.ndim < 1: + raise RuntimeError("Input must be >= 1-d.") + + return flip(a, (0,)) + + +# CompositeImplicitAutograd - don't register decomp +def narrow( + a: TensorLikeType, dim: int, start: int | TensorLikeType, length: int +) -> TensorLikeType: + # Supports Tensor overload that was added for XLA: + # https://github.com/pytorch/pytorch/issues/31558 + if isinstance(start, TensorLike): + torch._check( + start.dim() == 0 and utils.is_integer_dtype(start.dtype), + lambda: "start must be an 0-dim integral Tensor.", + ) + start = start.item() # type: ignore[assignment] + start = cast(int, start) + torch._check(a.dim() > 0, lambda: "narrow() cannot be applied to a 0-dim tensor.") + torch._check(length >= 0, lambda: "narrow(): length must be non-negative.") + dim = utils.canonicalize_dim(a.ndim, dim) + dim_length = a.size(dim) + torch._check_with( + IndexError, + -dim_length <= start and start <= dim_length, + lambda: f"start out of range (expected to be in range of [{-dim_length}, {dim_length}], but got {start})", + ) + if start < 0: + start = start + dim_length + torch._check( + start <= dim_length - length, + lambda: f"start ({start}) + length ({length}) exceeds dimension size ({dim_length}).", + ) + new_shape = list(a.shape) + new_shape[dim] = length + return a.as_strided( + new_shape, a.stride(), a.storage_offset() + a.stride(dim) * start + ) + + +def _normalize( + a: Tensor, norm_dims: DimsType, eps: float +) -> tuple[Tensor, Tensor, Tensor]: + """Computes mean and 1/std of a tensor along norm_dims. + + Used as a helper function for normalization layers. + + Args: + a (Tensor): input tensor + norm_dims (DimsType): dimensions to normalize over + eps (float): epsilon for numerical stability + + Returns: + out (Tensor): normalized tensor. + mean (Tensor): mean of the tensor along norm_dims. + rstd (Tensor): 1/std of the tensor along norm_dims. + """ + + norm_dims = utils.canonicalize_dims(a.ndim, norm_dims) + computation_dtype = utils.get_computation_dtype(a.dtype) + a_acc = _maybe_convert_to_dtype(a, computation_dtype) + if not isinstance(a_acc, TensorLike): + raise AssertionError(f"a_acc must be TensorLike, got {type(a_acc)}") + biased_var, mean = torch.var_mean( + a_acc, dim=norm_dims, unbiased=False, keepdim=True + ) + rstd = torch.rsqrt(biased_var + eps) + out = (a_acc - mean) * rstd + return out, mean, rstd + + +# add all specified dimensions +def _unsqueeze_multiple(x: TensorLikeType, dimensions: list[int]) -> TensorLikeType: + for dim in sorted(dimensions): + x = torch.unsqueeze(x, dim) + return x + + +@register_decomposition(aten.native_group_norm.default) +def native_group_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + batch_size: int, + num_channels: int, + flattened_inner_size: int, + num_groups: int, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + torch._check( + num_channels > 0, + lambda: f"Expected number of channels to be greater than 0, got {num_channels}", + ) + torch._check( + flattened_inner_size > 0, + lambda: f"Expected HxW to be greater than 0, got {flattened_inner_size}", + ) + torch._check( + num_groups > 0, + lambda: f"Expected num groups to be greater than 0, got {num_groups}", + ) + torch._check( + num_channels % num_groups == 0, + lambda: ( + "Expected number of channels in input to be divisible by num_groups, " + f"but got input of shape {input.shape} and num_groups={num_groups}" + ), + ) + torch._check( + weight is None or (weight.ndim == 1 and weight.numel() == num_channels), + lambda: ( + "Expected weight to be a vector of size equal to the number of " + f"channels in input, but got weight of shape {weight.shape} " # pyrefly: ignore[missing-attribute] + f"and input of shape {input.shape}" + ), + ) + torch._check( + bias is None or (bias.ndim == 1 and bias.numel() == num_channels), + lambda: ( + "Expected bias to be a vector of size equal to the number of " + f"channels in input, but got bias of shape {bias.shape} " # pyrefly: ignore[missing-attribute] + f"and input of shape {input.shape}" + ), + ) + # This check isn't in the C++ operator, but is necessary for how we apply weight and + # bias below. + torch._check( + input.ndim >= 2, + lambda: f"Expected at least 2 dimensions for input tensor but received {input.ndim}", + ) + + # Match contiguous behavior of eager implementation. Only necessary for ref tests. + mem_fmt = ( + torch.contiguous_format + if input.device.type not in ("cpu", torch._C._get_privateuse1_backend_name()) + else utils.suggest_memory_format(input) + ) + input = input.contiguous(memory_format=mem_fmt) + weight = weight.contiguous() if weight is not None else None + bias = bias.contiguous() if bias is not None else None + + computation_dtype = utils.get_computation_dtype(input.dtype) + input_acc = _maybe_convert_to_dtype(input, computation_dtype) + # num_channels / num_groups and flattened inner dimension are the reduction axes + reduction_dims = [2, 3] + input_reshaped = torch.reshape( + input_acc, + [batch_size, num_groups, num_channels // num_groups, flattened_inner_size], + ) + reduction_dims = utils.canonicalize_dims(input_reshaped.ndim, reduction_dims) + biased_var, mean = torch.var_mean( + input_reshaped, dim=reduction_dims, unbiased=False, keepdim=True + ) + rstd = torch.rsqrt(biased_var + eps) + if input.device.type == "cpu" and weight is not None: + weight_reshaped = torch.reshape( + weight, [1, num_groups, num_channels // num_groups, 1] + ) + w = rstd * weight_reshaped + b = -mean * w + if bias is not None: + bias_reshaped = torch.reshape( + bias, [1, num_groups, num_channels // num_groups, 1] + ) + b = b + bias_reshaped + w = w.contiguous().as_strided([batch_size, num_channels], [num_channels, 1]) + b = b.contiguous().as_strided([batch_size, num_channels], [num_channels, 1]) + broadcast_dims = list(range(2, input.ndim)) + unsqueeze_w = _unsqueeze_multiple(w, broadcast_dims) + unsqueeze_b = _unsqueeze_multiple(b, broadcast_dims) + out = input_acc * unsqueeze_w + unsqueeze_b + else: + out = (input_reshaped - mean) * rstd + out = out.view(input.shape) + broadcast_dims = [0] + list(range(2, input.ndim)) + if weight is not None: + unsqueeze_weight = _unsqueeze_multiple(weight, broadcast_dims) + out = out * unsqueeze_weight + if bias is not None: + unsqueeze_bias = _unsqueeze_multiple(bias, broadcast_dims) + out = out + unsqueeze_bias + + out = _maybe_convert_to_dtype(out, input.dtype) # type: ignore[assignment] + mean = _maybe_convert_to_dtype(mean, input.dtype) # type: ignore[assignment] + rstd = _maybe_convert_to_dtype(rstd, input.dtype) # type: ignore[assignment] + + # remove broadcast dimensions from mean and rstd + mean = torch.squeeze(mean, reduction_dims) + rstd = torch.squeeze(rstd, reduction_dims) + return (out, mean, rstd) + + +_SCALAR_TYPE_NAME_OVERRIDES = { + "uint8": "Byte", + "int8": "Char", + "int16": "Short", + "int32": "Int", + "int64": "Long", + "float16": "Half", + "float32": "Float", + "float64": "Double", + "complex32": "ComplexHalf", + "complex64": "ComplexFloat", + "complex128": "ComplexDouble", + "bool": "Bool", + "qint8": "QInt8", + "quint8": "QUInt8", + "qint32": "QInt32", + "bfloat16": "BFloat16", + "quint4x2": "QUInt4x2", + "quint2x4": "QUInt2x4", + "bcomplex32": "BComplex32", +} + + +def _scalar_type_name(dtype: torch.dtype) -> str: + dtype_name = str(dtype).removeprefix("torch.") + if dtype_name in _SCALAR_TYPE_NAME_OVERRIDES: + return _SCALAR_TYPE_NAME_OVERRIDES[dtype_name] + if dtype_name.startswith("uint"): + return "UInt" + dtype_name.removeprefix("uint") + return dtype_name[:1].upper() + dtype_name[1:] + + +def _check_native_layer_norm_cuda_param_dtype( + input: Tensor, + normalized_ndim: int, + weight: Tensor | None, + bias: Tensor | None, +) -> None: + if input.device.type != "cuda": + return + + mismatched_dtype = None + if weight is not None and weight.dtype != input.dtype: + mismatched_dtype = weight.dtype + elif bias is not None and bias.dtype != input.dtype: + mismatched_dtype = bias.dtype + + if mismatched_dtype is None: + return + + axis = input.ndim - normalized_ndim + num_rows = math.prod(input.shape[:axis]) + expected_dtype = _scalar_type_name(input.dtype) + found_dtype = _scalar_type_name(mismatched_dtype) + torch._check( + num_rows == 0, + lambda: f"expected scalar type {expected_dtype} but found {found_dtype}", + ) + + +@register_decomposition(aten.native_layer_norm) +@out_wrapper("out0", "out1", "out2") +def native_layer_norm( + input: Tensor, + normalized_shape: ShapeType, + weight: Tensor | None, + bias: Tensor | None, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + from torch.fx.experimental.symbolic_shapes import sym_eq + + normalized_ndim = len(normalized_shape) + torch._check( + normalized_ndim >= 1, + lambda: "Expected normalized_shape to be at least 1-dimensional, i.e., " + + "containing at least one element, but got normalized_shape = " + + str(normalized_shape), + ) + # torch.Size([1, 2, 3]) == [1, 2, 3] evaluates to False + # while torch.Size([1, 2, 3]) == (1, 2, 3) is True + # therefore we use tuple(normalized_shape) + torch._check( + # pyrefly: ignore [bad-argument-type] + weight is None or sym_eq(weight.shape, tuple(normalized_shape)), + lambda: "Expected weight to be of same shape as normalized_shape, but got " + + "weight of shape " + + str(weight.shape) # type: ignore[union-attr] + + " and normalized_shape = " + + str(normalized_shape), + ) + torch._check( + # pyrefly: ignore [bad-argument-type] + bias is None or sym_eq(bias.shape, tuple(normalized_shape)), + lambda: "Expected bias to be of same shape as normalized_shape, but got " + + "bias of shape " + + str(bias.shape) # type: ignore[union-attr] + + " and normalized_shape = " + + str(normalized_shape), + ) + torch._check( + input.ndim >= normalized_ndim + and sym_eq( + input.shape[(input.ndim - normalized_ndim) :], + tuple(normalized_shape), + ), + lambda: "Given normalized_shape=" + + str(normalized_shape) + + ", expected input with shape " + + str(normalized_shape) + + ", but got input of size " + + str(input.shape), + ) + torch._check( + not input.is_complex(), + lambda: "native_layer_norm does not support complex inputs", + ) + _check_native_layer_norm_cuda_param_dtype(input, normalized_ndim, weight, bias) + + input = contiguous(input) + if weight is not None: + weight = contiguous(weight) + if bias is not None: + bias = contiguous(bias) + + axis = input.ndim - normalized_ndim + reduction_dims = list(range(axis, input.ndim)) + out, mean, rstd = _normalize(input, reduction_dims, eps) + + if weight is None and bias is not None: + out = out + bias + elif weight is not None and bias is None: + out = out * weight + elif weight is not None and bias is not None: + out = out * weight + bias + + out = _maybe_convert_to_dtype(out, input.dtype) # type: ignore[assignment] + if input.device.type in ["cpu", "mtia"]: + mean = _maybe_convert_to_dtype(mean, input.dtype) # type: ignore[assignment] + rstd = _maybe_convert_to_dtype(rstd, input.dtype) # type: ignore[assignment] + return (out, mean, rstd) + + +@torch._subclasses.fake_impls.register_op_impl(aten.native_layer_norm.default) +def native_layer_norm_fake(fake_mode, func, *args, **kwargs): + return native_layer_norm(*args) + + +# TODO: Adding this as a meta function causes functorch tests to fail when compiled with debug mode. +# test/test_eager_transforms.py::TestFunctionalizeCPU::test_functionalize_fx_transpose_simple_cpu +@register_decomposition(aten.permute) +def permute(a: TensorLikeType, *dims) -> TensorLikeType: + _permutation = utils.canonicalize_dims( + a.ndim, utils.extract_dims_from_varargs(dims) + ) + return prims.transpose(a, _permutation) + + +@register_decomposition(aten.renorm) +@out_wrapper() +def renorm( + input: TensorLikeType, p: RealNumberType, dim: int, maxnorm: RealNumberType +) -> TensorLikeType: + torch._check(not isinstance(p, complex), lambda: "renorm: p must be real-valued") + torch._check(p > 0, lambda: "renorm: non-positive norm not supported") + torch._check( + not isinstance(maxnorm, complex), lambda: "renorm: maxnorm must be real-valued" + ) + torch._check( + maxnorm >= 0, lambda: f"renorm: expected maxnorm to be >= 0 but got {maxnorm}" + ) + ndim = input.ndim + torch._check( + ndim > 1, + lambda: f"renorm: input needs at least 2 dimensions, got {ndim} dimensions", + ) + + dim = utils.canonicalize_dim(ndim, dim) + reduce_dims = list(range(ndim)) + del reduce_dims[dim] + + # For half and bfloat16, calculate norm in float precision then cast + # normalization factor to half + acc_type = utils.get_computation_dtype(input.dtype) + if acc_type != input.dtype: + norm = torch.linalg.vector_norm( + input, p, reduce_dims, keepdim=True, dtype=acc_type + ) + else: + norm = torch.linalg.vector_norm(input, p, reduce_dims, keepdim=True) + + eps = 1e-7 + norm_factor = torch.where(norm > maxnorm, maxnorm / (norm + eps), 1.0) + if acc_type != input.dtype: + norm_factor = prims.convert_element_type(norm_factor, input.dtype) + return (input * norm_factor).contiguous() + + +# CompositeImplicitAutograd - don't register decomp +@aten.stft.center.py_impl(DispatchKey.CompositeImplicitAutograd) +def stft( + input: Tensor, + n_fft: int, + hop_length: int | None = None, + win_length: int | None = None, + window: Tensor | None = None, + center: bool = True, + pad_mode: str = "reflect", + normalized: bool = False, + onesided: bool | None = None, + return_complex: bool | None = None, + align_to_window: bool | None = None, +) -> Tensor: + torch._check( + window is None or window.device == input.device, + lambda: ( + f"stft input and window must be on the same device but got self on {input.device}" + + f" and window on {window.device}" # type: ignore[union-attr] + ), + ) + torch._check( + not center or align_to_window is None, + lambda: "stft only supports align_to_window for center = False.", + ) + + hop_length_ = hop_length if hop_length is not None else n_fft // 4 + win_length_ = win_length if win_length is not None else n_fft + + if return_complex is None: + return_complex_ = input.is_complex() or ( + window is not None and utils.is_complex_dtype(window.dtype) + ) + torch._check( + return_complex_, + lambda: ( + "stft requires the return_complex parameter be given for real inputs, " + + "and will further require that return_complex=True in a future PyTorch release." + ), + ) + else: + return_complex_ = return_complex + + torch._check_not_implemented( + utils.is_float_dtype(input.dtype) or utils.is_complex_dtype(input.dtype), + lambda: "stft expected a tensor of floating point or complex values", + ) + torch._check(1 <= input.ndim <= 2, lambda: "stft expected a 1D or 2D tensor") + + original_ndim = input.ndim + if original_ndim == 1: + input = input.unsqueeze(0) + + if center: + extra_dims = 3 - input.ndim + pad_amount = n_fft // 2 + extended_shape = [*itertools.repeat(1, extra_dims), *input.shape] + input = aten.pad(input.view(extended_shape), [pad_amount, pad_amount], pad_mode) + input = input.view(input.size()[extra_dims:]) + + length = input.size(1) + torch._check( + 0 < n_fft <= length, + lambda: f"stft expected 0 < n_fft <= {length}, but got n_fft={n_fft}", + ) + torch._check( + hop_length_ > 0, + lambda: f"stft expected hop_length > 0 but got hop_length={hop_length_}", + ) + torch._check( + 0 < win_length_ <= n_fft, + lambda: f"stft expected 0 < win_length <= n_fft but got win_length={win_length_}", + ) + torch._check( + window is None or window.shape == (win_length_,), + lambda: ( + f"expected a 1D window tensor of size equal to win_length={win_length_}, " + + f"but got window with size {window.shape}" # type: ignore[union-attr] + ), + ) + + if win_length_ < n_fft: + if window is None: + window = torch.ones(win_length_, dtype=input.dtype, device=input.device) + left = (n_fft - win_length_) // 2 + window = aten.constant_pad_nd(window, [left, n_fft - win_length_ - left]) + + if not center and align_to_window: + input_pad_amount = (n_fft - win_length_) // 2 + input = aten.pad(input, [input_pad_amount, input_pad_amount], pad_mode) + + input = input.unfold(dimension=-1, size=n_fft, step=hop_length_) + + if window is not None: + input = input * window + + complex_fft = utils.is_complex_dtype(input.dtype) + onesided = onesided if onesided is not None else not complex_fft + norm = "ortho" if normalized else None + if onesided: + torch._check( + not complex_fft, + lambda: "Cannot have onesided output if window or input is complex", + ) + out = torch.fft.rfft(input, dim=-1, norm=norm) + else: + out = torch.fft.fft(input, dim=-1, norm=norm) + + out.transpose_(1, 2) + + if original_ndim == 1: + out = out.squeeze_(0) + + return out if return_complex_ else torch.view_as_real(out) + + +# CompositeImplicitAutograd - don't register decomp +@aten.istft.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def istft( + input: Tensor, + n_fft: int, + hop_length: int | None = None, + win_length: int | None = None, + window: Tensor | None = None, + center: bool = True, + normalized: bool = False, + onesided: bool | None = None, + length: int | None = None, + return_complex=False, +) -> Tensor: + torch._check( + window is None or window.device == input.device, + lambda: ( + f"istft input and window must be on the same device but got self on {input.device}" + + f" and window on {window.device}" # type: ignore[union-attr] + ), + ) + + hop_length_ = hop_length if hop_length is not None else n_fft // 4 + win_length_ = win_length if win_length is not None else n_fft + + torch._check_type( + utils.is_complex_dtype(input.dtype), + lambda: ( + "istft requires a complex-valued input tensor matching the " + "output from stft with return_complex=True." + ), + ) + n_frames = input.size(-1) + fft_size = input.size(-2) + + expected_output_signal_len = n_fft + hop_length_ * (n_frames - 1) + torch._check(input.numel() > 0, lambda: "istft input tensor cannot be empty") + torch._check( + 2 <= input.ndim <= 3, + lambda: f"istft expected a tensor with 2 or 3 dimensions, but got {input.ndim}", + ) + onesided_ = onesided if onesided is not None else fft_size != n_fft + + if onesided_: + torch._check( + n_fft // 2 + 1 == fft_size, + lambda: ( + "istft expected the frequency dimension (3rd to the last) of the input tensor " + + f"to match n_fft / 2 + 1 when onesided=True, but got {fft_size}" + ), + ) + else: + torch._check( + n_fft == fft_size, + lambda: ( + "istft expected the frequency dimension (3rd to the last) of the input tensor " + + f"to match n_fft when onesided=False, but got {fft_size}", + ), + ) + + torch._check( + 0 < hop_length_ <= win_length_, + lambda: "istft expected 0 < hop_length <= win_length", + ) + torch._check( + 0 < win_length_ <= n_fft, lambda: "istft expected 0 < win_length <= n_fft" + ) + torch._check( + window is None or window.shape == (win_length_,), + lambda: "Invalid window shape. window has to be 1D and length of `win_length`", + ) + + if window is None: + real_dtype = utils.corresponding_real_dtype(input.dtype) + window_ = torch.ones(win_length_, dtype=real_dtype, device=input.device) + else: + window_ = window + + if win_length_ != n_fft: + left = (n_fft - win_length_) // 2 + window_ = aten.constant_pad_nd(window_, (left, n_fft - win_length_ - left), 0) + + original_ndim = input.ndim + if input.ndim == 2: + input = input.unsqueeze(0) + + input = input.transpose(1, 2) + norm = "ortho" if normalized else None + if return_complex: + torch._check( + not onesided_, + lambda: "cannot have onesided output if window or input is complex", + ) + input = torch.fft.ifft(input, dim=-1, norm=norm) + else: + torch._check( + window is None or not utils.is_complex_dtype(window.dtype), + lambda: "Complex windows are incompatible with return_complex=False", + ) + if not onesided_: + input = input.narrow(dim=-1, start=0, length=n_fft // 2 + 1) + input = torch.fft.irfft(input, dim=-1, norm=norm) + + if input.size(2) != n_fft: + raise AssertionError( + f"Expected input.size(2) == n_fft, got {input.size(2)} != {n_fft}" + ) + + y_tmp = input * window_.view([1, 1, n_fft]) + y = aten.unfold_backward( + y_tmp, + input_sizes=(y_tmp.size(0), expected_output_signal_len), + dim=1, + size=n_fft, + step=hop_length_, + ) + window_envelop = aten.unfold_backward( + window_.pow(2).expand((1, n_frames, n_fft)), + input_sizes=(y_tmp.size(0), expected_output_signal_len), + dim=1, + size=n_fft, + step=hop_length_, + ) + + if expected_output_signal_len != y.size(1): + raise AssertionError( + f"expected_output_signal_len ({expected_output_signal_len}) != y.size(1) ({y.size(1)})" + ) + if expected_output_signal_len != window_envelop.size(1): + raise AssertionError( + f"expected_output_signal_len ({expected_output_signal_len}) != window_envelop.size(1) ({window_envelop.size(1)})" + ) + + start = n_fft // 2 if center else 0 + if length is not None: + end = start + length + elif center: + end = expected_output_signal_len - n_fft // 2 + else: + end = expected_output_signal_len + + # Clamp end to the valid signal range before slicing so that downstream + # meta / fake-tensor execution never sees an out-of-bounds access. + # The eager C++ path relies on slice's implicit clamping, but the + # compile path may convert slice to narrow which does not clamp. + # Use sym_min (not the builtin min) so the clamp stays symbolic under + # dynamic shapes: builtin min would evaluate ``end < expected_output_signal_len`` + # to a concrete bool, installing a guard for backed symints (forcing a + # recompile when the relationship flips) or raising + # GuardOnDataDependentSymNode for unbacked symints. + clamped_end = sym_min(end, expected_output_signal_len) + + y = aten.slice.Tensor(y, 1, start, clamped_end, 1) + window_envelop = aten.slice.Tensor(window_envelop, 1, start, clamped_end, 1) + + y = y / window_envelop + if original_ndim == 2: + y = y.squeeze(0) + + # Pad the tail symbolically so dynamic shapes don't force a guard on the + # ``end`` vs ``expected_output_signal_len`` relationship. sym_max keeps the + # pad >= 0, so a zero pad is a no-op when the signal already covers the + # requested length. The warning needs a concrete decision, so it is gated on + # statically_known_true: it fires for the common concrete-int case but + # installs no guard when the relationship isn't statically known. + from torch.fx.experimental.symbolic_shapes import statically_known_true + + if statically_known_true(end > expected_output_signal_len): + warnings.warn( + "The length of signal is shorter than the length parameter. Result is being " + + "padded with zeros in the tail. Please check your center and hop_length settings", + stacklevel=2, + ) + # Only emit the pad when the signal may be shorter than the requested + # length. Skipping it in the statically-known no-pad case avoids turning the + # view returned by eager (e.g. the squeeze) into a copy, which keeps + # _refs.istft view-consistent with the aten op. When the relationship is not + # statically known (dynamic shapes), pad symbolically with sym_max so a zero + # pad is a no-op and no specializing guard is installed. + if not statically_known_true(end <= expected_output_signal_len): + pad = sym_max(end - expected_output_signal_len, 0) + y = aten.constant_pad_nd(y, (0, pad), 0) + return y + + +# Get the new shape and stride after applying unfold to an input tensor +def _get_unfold_shape_stride( + a_shape: ShapeType, a_stride: StrideType, dimension: int, size: int, step: int +): + a_ndim = len(a_shape) + dim = utils.canonicalize_dim(a_ndim, dimension, wrap_scalar=True) + max_size = 1 if a_ndim == 0 else a_shape[dim] + last_stride = 1 if a_ndim == 0 else a_stride[dim] + + torch._check( + size <= max_size, + lambda: f"Maximum size for tensor at dimension {dim} is {max_size} but size is {size}", + ) + + torch._check( + step > 0, + lambda: f"Step is {step} but must be > 0", + ) + + shape = list(a_shape) + strides = list(a_stride) + shape.append(size) + strides.append(last_stride) + if dim < a_ndim: + shape[dim] = (shape[dim] - size) // step + 1 + strides[dim] *= step + return shape, strides + + +@register_decomposition(aten.repeat) +@out_wrapper() +def repeat(a: Tensor, *repeat_shape) -> Tensor: + repeat_shape = utils.extract_shape_from_varargs(repeat_shape, validate=False) + torch._check( + len(repeat_shape) >= len(a.shape), + lambda: "repeat: Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor", + ) + + if len(repeat_shape) == 0: + return torch.clone(a) + + num_new_dimensions = len(repeat_shape) - a.ndim + padded_shape = [1] * num_new_dimensions + for dim_size in a.shape: + padded_shape.append(dim_size) + + target_shape = tuple( + padded_size * repeat_size + for padded_size, repeat_size in zip(padded_shape, repeat_shape) + ) + + # return an empty tensor if one of the repeat_shape dimensions is zero + if 0 in repeat_shape: + return torch.empty( + target_shape, + dtype=a.dtype, + device=a.device, + requires_grad=a.requires_grad, + memory_format=utils.suggest_memory_format(a), + ) + + urtensor_shape = target_shape + urtensor_stride = utils.make_contiguous_strides_for(target_shape) + for dim, dim_size in enumerate(padded_shape): + # repeat each dimension by using unfold_copy operation + urtensor_shape, urtensor_stride = _get_unfold_shape_stride( + urtensor_shape, urtensor_stride, dim, dim_size, max(dim_size, 1) + ) + + # derive permute order by sorting urtensor strides + enumerated_stride = list(enumerate(urtensor_stride)) + enumerated_stride.sort(key=operator.itemgetter(1), reverse=True) + permute_order, _sorted_stride = zip(*enumerated_stride) + + # add new and expand dimensions according to urtensor + repeat_xtensor = a.expand(urtensor_shape) + + # clone tensor to concretize expanded dimensions + cloned_result = torch.clone(repeat_xtensor) + + # transpose axis so strides are in sorted order + permuted_result = cloned_result.permute(permute_order) + + # reshape to get contiguous tensor with correct target shape + return permuted_result.reshape(target_shape) + + +def _reshape_view_helper_core_alg( + a: TensorLikeType, shape, allow_copy: bool +) -> TensorLikeType: + # NOTE [Reshape Algorithm] + # This algorithm works by attempting to greedily construct the desired dimensions in + # the output shape, left to right. It does this by, conceptually, accumulating + # dimensions of the original tensor, also left to right, until the dimension + # can be constructed using prims.split_dim. + # The algorithm also has special handling for tail squeezes/unsqueezes, like + # if a reshape from (5, 5) to (5, 5, 1) or vice versa. + # + # This algorithm does not flatten the original tensor and then split dims as appropriate + # because that would create copies more often than this algorithm. flatten is the only + # operation below which can create a view or a copy, and while it prefers creating + # views it may sometimes create a copy if the tensor's strides do not permit a view. + # As a result, this algorithm tries to minimize flattening. + # + # Note that a better version of this algorithm may exist. Regions which could be + # flattened without creating a copy can be identified in advance, and that might + # allow fewer flatten calls or faster short-circuiting to make a copy. + idx = 0 + a_ = a + for length in shape: + # Handles tail unsqueezes + if idx >= a_.ndim: + if length != 1: + raise AssertionError( + f"Cannot unsqueeze dimension with length {length}, expected 1" + ) + last_dim = a_.ndim - 1 + # NOTE: using split_dim instead of unsqueeze may seem silly here, + # but it's necessary to get the strides correct + a_ = prims.split_dim(a_, last_dim, a_.shape[last_dim]) + idx = idx + 1 + continue + + # Skips dimensions that are already the correct length + if length == a_.shape[idx]: + idx = idx + 1 + continue + + accum = a_.shape[idx] + end = idx + while accum % length != 0: + end += 1 + accum *= a_.shape[end] + if end != idx: + # NOTE: in this case multiple dimensions must be flatten to create the desired dimension + # This flattening is why reshape sometimes creates a copy -- because flattening + # may return a view of a copy + + # Checks if collapse can be a view and short-circuits to copying reshape if it can't + new_shape, _new_strides = prims._collapse_view_helper( + a_, idx, end, must_be_valid=None + ) + if new_shape is None: + if allow_copy: + return prims.reshape(a, shape) + + msg = f"Cannot view a tensor with shape {a.shape} and strides {a.stride()} as a tensor with shape {shape}!" + raise ValueError(msg) + + a_ = flatten(a_, idx, end) + + # Splits the (possibly flattened) dimension to create the desired dim length. + # guard_or_true is safe due to the tail unsqueeze routine. + if accum != length: + a_ = prims.split_dim(a_, idx, length) + + idx = idx + 1 + + # Squeezes tail + while idx < a_.ndim: + torch._check( + a_.shape[idx] == 1, + lambda: f"a.size({idx}) expected to be 1 but got {a_.shape[idx]}", + ) + a_ = squeeze(a_, idx) + + if a_ is a: + return prims.view_of(a) + else: + return a_ + + +def _reshape_view_helper(a: TensorLikeType, *shape, allow_copy: bool) -> TensorLikeType: + # Creates a valid shape + shape = utils.extract_shape_from_varargs(shape, validate=False) + # Reshape may be given a shape with a -1 length + # This indicates that the dimension's length should be inferred + shape = utils.infer_size(shape, a.numel()) + + # Special-cases tensors with no elements + if a.numel() == 0: + return as_strided(a, shape, utils.make_contiguous_strides_for(shape)) + + # Special-cases reshaping zero dim tensors + if a.ndim == 0: + _a = a + for length in shape: + if length != 1: + raise AssertionError( + f"Cannot reshape 0-dim tensor: shape dimension must be 1, got {length}" + ) + _a = unsqueeze(_a, -1) + if _a is a: + return prims.view_of(a) + else: + return _a + + # Special-cases reshaping to zero dim tensors + if len(shape) == 0: + _a = a + for length in a.shape: + if length != 1: + raise AssertionError( + f"Cannot reshape to 0-dim tensor: shape dimension must be 1, got {length}" + ) + _a = squeeze(_a, -1) + if _a is a: + return prims.view_of(a) + else: + return _a + + if is_contiguous_or_false(a): + # Special-cases for nd_to_1d + if len(shape) == 1 and a.ndim > 1: + return torch.as_strided(a, [a.numel()], [1]) + # Special-cases for 1d_to_2d + if len(shape) == 2 and a.ndim == 1: + dim0 = shape[0] + dim1 = shape[1] + return torch.as_strided(a, [dim0, dim1], [dim1, 1]) + + shape_numel = reduce(operator.mul, shape, 1) + torch._check( + a.numel() == shape_numel, + lambda: f"Could not reshape a tensor with shape {a.shape} as a tensor with shape {shape}!", + ) + + # Handles general case: a 1+D tensor reshaped into a distinct 1+D shape + return _reshape_view_helper_core_alg(a, shape, allow_copy) + + +# CompositeImplicitAutograd - don't register decomp +# NOTE: shape is a vararg because Tensor.reshape can be called with as +# Tensor.reshape(a, b, c) or Tensor.reshape((a, b, c)) Function call +# torch.reshape doesn't support unpacked shapes +def reshape(a: TensorLikeType, *shape: ShapeType) -> TensorLikeType: + return _reshape_view_helper(a, *shape, allow_copy=True) + + +# CompositeImplicitAutograd - don't register decomp +def reshape_as(self: TensorLikeType, other: TensorLikeType) -> TensorLikeType: + return self.reshape(other.size()) + + +@register_decomposition(aten.roll) +@out_wrapper() +def roll(a: TensorLikeType, shifts: DimsType, dims: DimsType = ()) -> TensorLikeType: + """Reference implementation of :func:`torch.roll`.""" + + dims = utils.canonicalize_dims(a.ndim, dims) + # ATen specifies int[1] type for shifts and dims which expands integers to tuples of length 1 + if not isinstance(shifts, Iterable): + shifts = (shifts,) + if not isinstance(dims, Iterable): + dims = (dims,) + + # Avoid modulo by zero + if a.numel() == 0: + # Keeping this as ref for now as FakeTensor runs into some issues with complex tensors + return a.clone() + + # pyrefly: ignore [bad-argument-type] + if a.dim() == 0 and len(dims) > 0: + raise IndexError( + # pyrefly: ignore [bad-index, index-error] + f"Dimension specified as {dims[0]} but tensor has no dimensions" + ) + + # pyrefly: ignore [bad-argument-type] + len_shifts = len(shifts) + # pyrefly: ignore [bad-argument-type] + len_dims = len(dims) + if len_shifts != 1 or len_dims != 1: + if len_shifts == 0: + raise RuntimeError("`shifts` required") + # Takes care of the case when dims is not specified (default) + # By default, the tensor is flattened before shifting, after which the original shape is restored + if len_dims == 0 and len_shifts == 1: + return torch.roll(torch.flatten(a), shifts, 0).view(a.shape) + if len_shifts != len_dims: + raise RuntimeError( + f"shifts and dimensions must align. shifts: {len_shifts}, dims: {len_dims}" + ) + if len_dims <= 1: + raise AssertionError(f"Expected len_dims > 1, got {len_dims}") + # pyrefly: ignore [bad-index] + tail_shifts = shifts[1:] + # pyrefly: ignore [bad-index, index-error] + tail_dims = dims[1:] + # pyrefly: ignore [bad-index, index-error] + # pyrefly: ignore [bad-index, index-error] + first_dim_rolled = torch.roll(a, (shifts[0],), dims[0]) + return torch.roll(first_dim_rolled, tail_shifts, tail_dims) + + # This path is taken when only one dimension is rolled + # For example to get `first_dim_rolled` above + # pyrefly: ignore [bad-index, index-error] + dim = dims[0] + size = a.shape[dim] + # pyrefly: ignore [bad-index, index-error] + start = (size - shifts[0]) % size + idx = torch.arange(size, device=a.device) + return a.index_select(dim, torch.fmod(start + idx, size)) + + +@register_decomposition(aten.rot90) +@out_wrapper() +def rot90( + a: TensorLikeType, k: int = 1, dims: DimsSequenceType = (0, 1) +) -> TensorLikeType: + """Reference implementation of :func:`torch.rot90`.""" + if len(dims) != 2: + raise RuntimeError( + f"expected total rotation dims == 2, but got dims = {len(dims)}" + ) + if a.ndim < 2: + raise RuntimeError(f"expected total dims >= 2, but got total dims = {a.ndim}") + + # Do this after the initial checks to be compatible with the behavior in + # core. + dims = utils.canonicalize_dims(a.ndim, dims) + + if dims[0] == dims[1]: + raise RuntimeError( + f"expected rotation dims to be different, but got dim0 = {dims[0]} and dim1 = {dims[1]}" + ) + k = k % 4 # Rotation direction is from the second towards the first axis for k < 0 + if k == 1: + return torch.transpose(torch.flip(a, (dims[1],)), dims[0], dims[1]) + elif k == 2: + return torch.flip(a, dims) + elif k == 3: + return torch.transpose(torch.flip(a, (dims[0],)), dims[0], dims[1]) + else: + return a.clone(memory_format=torch.contiguous_format) + + +def _check_stack_inputs(tensors: TensorSequenceType) -> None: + from torch.fx.experimental.symbolic_shapes import sym_eq + + entry_shape = tensors[0].shape + for i in range(1, len(tensors)): + torch._check( + sym_eq(tensors[i].shape, entry_shape), + lambda: f"stack expects each tensor to be equal size, but got {entry_shape} at entry 0 ", + ) + + +@register_decomposition(aten.stack) +@out_wrapper() +def stack(tensors: TensorSequenceType, dim: int = 0) -> TensorLikeType: + if len(tensors) == 0: + raise AssertionError("stack expects a non-empty TensorList") + wrapped_dim = utils.canonicalize_dim(tensors[0].ndim + 1, dim) + # Refs need sparse support to check other condition + if wrapped_dim < tensors[0].ndim: # and not tensors[0].is_sparse: + _check_stack_inputs(tensors) + result_sizes = list(tensors[0].shape) + result_sizes.insert(wrapped_dim, len(tensors)) + out = torch.cat(tensors, wrapped_dim) + return out.view(result_sizes) + + # If dim == tensors[0].ndim, view cannot efficiently handle it + return torch.cat([t.unsqueeze(wrapped_dim) for t in tensors], dim) + + +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +def softmax( + a: TensorLikeType, + dim: int, + dtype: torch.dtype | None = None, +) -> TensorLikeType: + result_dtype = dtype or a.dtype + computation_dtype = utils.get_computation_dtype(result_dtype) + a_ = _maybe_convert_to_dtype(a, computation_dtype) + if a.numel() == 0: + a_exp = exp(a_) + else: + a_max = amax(a_, dim, keepdim=True) + a_exp = exp(a_ - a_max) + return _maybe_convert_to_dtype( + # pyrefly: ignore [no-matching-overload] + true_divide(a_exp, sum(a_exp, dim, keepdim=True)), + result_dtype, + ) # type: ignore[return-value] + + +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +def hstack(tensors: TensorSequenceType) -> TensorLikeType: + torch._check(len(tensors) > 0, lambda: "hstack expects a non-empty TensorList") + aligned_tensors = atleast_1d(*tensors) + if aligned_tensors[0].ndim == 1: + return cat(aligned_tensors, 0) + return cat(aligned_tensors, 1) + + +# CompositeImplicitAutograd - don't register decomp +@out_wrapper() +def vstack(tensors: TensorSequenceType) -> TensorLikeType: + torch._check(len(tensors) > 0, lambda: "vstack expects a non-empty TensorList") + aligned_tensors = atleast_2d(*tensors) + return cat(aligned_tensors, 0) + + +# CompositeImplicitAutograd - don't register decomp +def unflatten(a: TensorLikeType, dim: int, sizes: ShapeType) -> TensorLikeType: + dim = utils.canonicalize_dim(a.ndim, dim) + torch._check(len(sizes) != 0, lambda: "unflatten: sizes must be non-empty") + return a.view(tuple(a.shape[:dim]) + tuple(sizes) + tuple(a.shape[dim + 1 :])) + + +@register_decomposition(aten.unbind) +def unbind(t: TensorLikeType, dim: int = 0) -> TensorSequenceType: + dim = utils.canonicalize_dim(t.ndim, dim) + torch._check_index( + len(t.shape) > 0, + lambda: "Dimension specified as 0 but tensor has no dimensions", + ) + + # Note: t.shape[dim] can't be dynamic or unbacked, even if we use guard_or_false here we will fail + # later in the split since t.shape[dim] control the number of output tensors. + if t.shape[dim] == 0: + return () + else: + return tuple( + torch.squeeze(s, dim) for s in torch.tensor_split(t, t.shape[dim], dim) + ) + + +@out_wrapper() +def index_copy(x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike): + return x.clone(memory_format=torch.contiguous_format).index_copy_( + dim, index, tensor + ) + + +def index_copy_(x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike): + dim = utils.canonicalize_dims(x.ndim, dim) + torch._check( + index.ndim <= 1, + lambda: f"Index should have dimension 1 or 0 (got {index.ndim})", + ) + # Treat scalars as elements of \R^1 + y = x.unsqueeze(0) if x.ndim == 0 else x + idx = (slice(None),) * dim + (index,) + y[idx] = tensor + return x + + +@register_decomposition(aten.index_fill) +@out_wrapper() +def index_fill( + x: TensorLike, dim: int, index: TensorLike, value: NumberType | TensorLike +): + return _index_fill(x, dim, index, value, inplace=False) + + +@register_decomposition(aten.index_fill_) +def index_fill_( + x: TensorLike, dim: int, index: TensorLike, value: NumberType | TensorLike +): + return _index_fill(x, dim, index, value, inplace=True) + + +def _index_fill( + x: TensorLike, + dim: int, + index: TensorLike, + value: NumberType | TensorLike, + *, + inplace: bool, +): + torch._check( + index.ndim <= 1, + lambda: f"Index should have dimension 1 or 0 (got {index.ndim})", + ) + if isinstance(value, TensorLike): + torch._check( + value.ndim == 0, + lambda: "Only supports 0-dimensional value tensor. " # type: ignore[union-attr] + f"Got a tensor with {value.ndim} dimensions.", + ) # type: ignore[arg-type] + else: + value = torch.scalar_tensor( + value, + dtype=x.dtype, + layout=x.layout, + device=x.device, # type: ignore[arg-type] + ) + + # index_copy has some unnecessary preconditions when x is a scalar. We do this to work through them + zero_dim = x.ndim == 0 + y = x.unsqueeze(0) if zero_dim else x + # index_copy does not broadcast on value so we have to do it manually + shape = list(y.shape) + shape[dim] = index.numel() + value = value.expand(shape) + index_copy = Tensor.index_copy_ if inplace else torch.index_copy + out = index_copy(y, dim, index, value) # type: ignore[operator] + if inplace: + return x + else: + if zero_dim: + # The clone is necessary so that it returns a fresh tensor rather than a view + out = out.squeeze(0).clone() + # index_fill preserves the strides for non-overlapping-and-dense inputs + # (matching clone(Preserve) behavior). index_copy always returns contiguous tensors. + if out.stride() != x.stride() and utils.is_non_overlapping_and_dense_or_false( + x + ): + out = prims.copy_strided(out, x.stride()) + return out + + +@out_wrapper() +def index_add( + x: TensorLike, + dim: int, + index: TensorLike, + tensor: TensorLike, + *, + alpha: NumberType = 1, +): + # index_add always returns a new contiguous tensor + return x.clone(memory_format=torch.contiguous_format).index_add_( + dim, + index, + tensor, + alpha=alpha, # type: ignore[arg-type] + ) + + +@register_decomposition(aten.index_select) +@out_wrapper() +def index_select(x: TensorLike, dim: int, index: TensorLike): + dim = utils.canonicalize_dims(x.ndim, dim) + torch._check( + index.ndim <= 1, + lambda: f"Index should have dimension 1 or 0 (got {index.ndim})", + ) + if index.ndim == 0: + index = index.unsqueeze(0) + if x.ndim == 0: + # Treat scalars as elements of \R^1 + # We cannot use x[idx] here as it accesses item() (??), hence this awkward construction + return torch.empty_like(x).index_copy(0, index, x.expand_as(index)) + + idx = (slice(None),) * dim + (index,) + return x[idx].contiguous(memory_format=utils.suggest_memory_format(x)) + + +@register_decomposition(aten.squeeze.dims) +def squeeze(a: TensorLikeType, dim: DimsType | None = None) -> TensorLikeType: + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if dim is None: + dims = tuple(idx for idx, size in enumerate(a.shape) if size == 1) + return prims.squeeze(a, dims) if dims else prims.view_of(a) + + ndim = a.ndim + + dim = utils.canonicalize_dims(ndim, dim) + dims = (dim,) if isinstance(dim, Dim) else dim + # Short-circuits if the tensor has no dimensions + if ndim == 0: + if not (len(dims) == 0 or dims == (0,)): + raise AssertionError( + f"Expected dims to be empty or (0,) for 0-dim tensor, got {dims}" + ) + return prims.view_of(a) + + # Note: squeeze does not modify tensors when the given dim is not a dimension of length 1 + # would it be better if we just not allow 1 for unbacked at runtime? + dims = tuple(d for d in dims if guard_or_false(a.shape[d] == 1)) + if len(dims) == 0: + return prims.view_of(a) + if len(dims) == 1: + return prims.squeeze(a, dims) + dims_list = list(dims) + dims_list = sorted(dims_list, reverse=True) + for i in dims_list: + a = squeeze(a, i) + return a + + +@register_decomposition(aten.split_with_sizes) +def split_with_sizes( + self: Tensor, split_sizes: list[int], dim: int = 0 +) -> list[Tensor]: + # NB: Perform the check_is_size tests first so that the + # sum test does not try to do a replacement + for i in range(len(split_sizes)): + torch._check( + split_sizes[i] >= 0, + lambda: "split_with_sizes expects split_sizes have only non-negative entries", + ) + torch._check_with( + ValueError, + builtins.sum(split_sizes) == self.shape[dim], + lambda: f"Split sizes add up to {builtins.sum(split_sizes)} but got the tensor's size of {self.shape[dim]}", + ) + + splits = [] + offset = self.storage_offset() + + for split_size in split_sizes: + new_shape = list(self.shape) + new_shape[dim] = split_size + # We reimplement narrow here to avoid a lot of checks in the + # decomposition of narrow which calls slice_in_dim and slice + splits.append(self.as_strided(new_shape, self.stride(), offset)) + offset = offset + self.stride()[dim] * split_size + return splits + + +# Note: does not work with TensorMetas because of data-dependent control-flow +# CompositeImplicitAutograd - don't register decomp +def tensor_split( + a: TensorLikeType, + indices_or_sections: Tensor | DimsType, + dim: int = 0, +) -> tuple[TensorLikeType, ...]: + _dim = utils.canonicalize_dim(a.ndim, dim) + if a.ndim == 0: + msg = "tensor_split: received a rank zero tensor, but expected a tensor of rank one or greater!" + raise ValueError(msg) + + # If indices_or_sections is a tensor, it must be a CPU Long tensor + if isinstance(indices_or_sections, TensorLike): + if indices_or_sections.device.type != "cpu": + msg = ( + f"tensor_split: if indices_or_sections is a tensor it must be on the CPU, " + f"but received one on {indices_or_sections.device}" + ) + raise ValueError(msg) + if indices_or_sections.dtype != torch.long: + msg = ( + "tensor_split: if indices_or_sections is a tensor it must have long dtype, " + f" but received one with dtype {indices_or_sections.dtype}" + ) + raise ValueError(msg) + + # Case 0 -- indices_or_sections is an integer or a scalar tensor n and a is split along dim into n parts of equal-ish length + if isinstance(indices_or_sections, IntLike) or ( + isinstance(indices_or_sections, TensorLike) and indices_or_sections.ndim == 0 + ): + sections: int = ( + indices_or_sections # type: ignore[assignment] + if isinstance(indices_or_sections, Number) + else indices_or_sections.item() + ) + + if sections <= 0: + msg = f"tensor_split: number of sections must be greater than 0, but was {sections}" + raise ValueError(msg) + + dim_size = a.shape[_dim] + min_split_size = math.floor(dim_size / sections) + num_splits_one_extra = dim_size % sections + + split_sizes = [] + for split_idx in range(sections): + split_size = ( + min_split_size + 1 + if (split_idx < num_splits_one_extra) + else min_split_size + ) + split_sizes.append(split_size) + + return tuple(aten.split_with_sizes(a, split_sizes, dim=_dim)) + # Case 1 -- indices_or_sections is a sequence of integers or a 1D tensor describing the splits + else: + indices = indices_or_sections + if isinstance(indices_or_sections, TensorLike): + if indices_or_sections.ndim != 1: + msg = ( + "tensor_split: non-scalar indices_or_sections tensors must have only one dimension, " + f"but received a tensor with {indices_or_sections.ndim} dimensions" + ) + raise ValueError(msg) + + indices = indices_or_sections.tolist() + + indices = [0] + list(indices) + [a.shape[_dim]] + split_sizes = [indices[i + 1] - indices[i] for i in range(len(indices) - 1)] + return tuple(aten.split_with_sizes(a, split_sizes, dim=_dim)) + + +# CompositeImplicitAutograd - don't register decomp +def hsplit( + a: TensorLikeType, indices_or_sections: DimsType +) -> tuple[TensorLikeType, ...]: + torch._check( + a.ndim >= 1, + lambda: ( + "torch.hsplit requires a tensor with at least 1 dimension, but got a tensor with " + + str(a.ndim) + + " dimensions!" + ), + ) + dim = 0 if a.ndim == 1 else 1 + if isinstance(indices_or_sections, IntLike): + split_size = indices_or_sections + torch._check( + # pyrefly: ignore [unsupported-operation] + (split_size != 0 and a.shape[dim] % split_size == 0), + lambda: ( + "torch.hsplit attempted to split along dimension " + + str(dim) + + ", but the size of the dimension " + + str(a.shape[dim]) + + " is not divisible by the split_size " + + str(split_size) + + "!" + ), + ) + + return tensor_split(a, split_size, dim) + + torch._check_type( + isinstance(indices_or_sections, (list, tuple)), + lambda: ( + "hsplit(): received an invalid combination of arguments. " + "Expected indices_or_sections to be of type int, list of ints or tuple of ints " + f"but got type {type(indices_or_sections)}" + ), + ) + + split_sizes = indices_or_sections + return tensor_split(a, split_sizes, dim) + + +# CompositeImplicitAutograd - don't register decomp +def vsplit( + a: TensorLikeType, indices_or_sections: DimsType +) -> tuple[TensorLikeType, ...]: + torch._check( + a.ndim >= 2, + lambda: ( + "torch.vsplit requires a tensor with at least 2 dimension, but got a tensor with " + + str(a.ndim) + + " dimensions!" + ), + ) + if isinstance(indices_or_sections, IntLike): + split_size = indices_or_sections + torch._check( + # pyrefly: ignore [unsupported-operation] + (split_size != 0 and a.shape[0] % split_size == 0), + lambda: ( + f"torch.vsplit attempted to split along dimension 0" + f", but the size of the dimension " + f"{a.shape[0]}" + f" is not divisible by the split_size " + f"{split_size}" + f"!" + ), + ) + + return tensor_split(a, split_size, 0) + + torch._check_type( + isinstance(indices_or_sections, (list, tuple)), + lambda: ( + "vsplit(): received an invalid combination of arguments. " + "Expected indices_or_sections to be of type int, list of ints or tuple of ints " + f"but got type {type(indices_or_sections)}" + ), + ) + + split_sizes = indices_or_sections + return tensor_split(a, split_sizes, 0) + + +@register_decomposition(aten.diag.out) +@out_wrapper() +def diag( + self: TensorLikeType, + offset: int = 0, +) -> TensorLikeType: + ndim = self.dim() + torch._check( + ndim in (1, 2), lambda: f"diag(): Supports 1D or 2D tensors. Got {ndim}D" + ) + if ndim == 1: + return torch.diag_embed(self, offset) + else: + return torch.diagonal_copy(self, offset) + + +@register_decomposition(aten.diagonal_scatter) +@out_wrapper() +def diagonal_scatter( + input: TensorLikeType, + src: TensorLikeType, + offset: int = 0, + dim1: int = 0, + dim2: int = 1, +) -> TensorLikeType: + from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_or + + # Mirror at::native::clone_preserve_strides: when the input has internal + # memory overlap (e.g. an expand from a scalar with stride 0), we cannot + # preserve its strides because copy_to() below would write through aliased + # storage and corrupt non-diagonal positions. This arises in the backward + # of diagonal_scatter(x, src).sum(), where grad_output is expanded. Fall + # back to a plain clone, which materializes a contiguous buffer. + if builtins.any( + guard_or_false(sz > 1) and guard_or_false(s == 0) + for sz, s in zip(input.size(), input.stride()) + ): + out = input.clone() + else: + out = utils.clone_preserve_strides(input) + diag = out.diagonal(offset, dim1, dim2) + # Use sym_or + guard_or_false to handle unbacked symbolic dimensions. + torch._check( + diag.ndim == src.ndim + and not guard_or_false( + sym_or(*(d1 != d2 for d1, d2 in zip(diag.shape, src.shape))) + ), + lambda: "expected src to have a size equal to the diagonal of the input." + f"Got {src.shape} for a diagonal of shape {diag.shape}", + ) + copy_to(diag, src) + return out + + +@register_decomposition(aten.diagonal) +def diagonal( + self: TensorLikeType, + offset: int = 0, + dim1: int = 0, + dim2: int = 1, +) -> TensorLikeType: + """ + Reference implementation of torch.diagonal + """ + num_dims = self.dim() + dim1 = utils.canonicalize_dim(idx=dim1, rank=num_dims) + dim2 = utils.canonicalize_dim(idx=dim2, rank=num_dims) + + torch._check( + dim1 != dim2, lambda: f"diagonal dimensions cannot be identical {dim1}, {dim2}" + ) + + storage_offset = self.storage_offset() + + # Use sym_min/sym_max to handle unbacked symbolic dimensions. + if offset >= 0: + diag_size = sym_max(sym_min(self.size()[dim1], self.size()[dim2] - offset), 0) + storage_offset += offset * self.stride()[dim2] + else: + diag_size = sym_max(sym_min(self.size()[dim1] + offset, self.size()[dim2]), 0) + storage_offset -= offset * self.stride()[dim1] + + sizes = [s for i, s in enumerate(self.size()) if i not in (dim1, dim2)] + sizes.append(diag_size) # type: ignore[arg-type] + + strides = [s for i, s in enumerate(self.stride()) if i not in (dim1, dim2)] + strides.append(self.stride()[dim1] + self.stride()[dim2]) + + result = self.as_strided(size=sizes, stride=strides, storage_offset=storage_offset) + + return result + + +@register_decomposition(aten.diag_embed) +@out_wrapper() +def diag_embed( + t: TensorLikeType, + offset: int = 0, + dim1: int = -2, + dim2: int = -1, +) -> TensorLikeType: + """ + Reference implementation of torch.diag_embed + """ + # convert from negative dims + rank = t.ndim + 1 + dim1 = utils.canonicalize_dim(rank=rank, idx=dim1) + dim2 = utils.canonicalize_dim(rank=rank, idx=dim2) + + # as per the docs, exchanging dims is equivalent to changing the sign of + # offset + if dim1 > dim2: + dim1, dim2 = dim2, dim1 + offset = -offset + + torch._check( + dim1 != dim2, lambda: f"diagonal dimensions cannot be identical {dim1}, {dim2}" + ) + + # as per the docs, the size of last dim is placed at dim1 and dim2 + last_dim = t.size(-1) + + if offset != 0: + # add padding to match the new size + t_shape = list(t.shape) + t_shape[-1] = builtins.abs(offset) + z = torch.zeros(t_shape, dtype=t.dtype, device=t.device, requires_grad=False) + pair = (z, t) if offset > 0 else (t, z) + t = torch.cat(pair, dim=-1) + # make sure the diagonal always has the same size + last_dim += builtins.abs(offset) + + # preserve original data, but place 1 at dim1 and move last dim to dim2 + t = t.unsqueeze(dim1).movedim(-1, dim2) + + # generate ranges shifting indices based on offset + a_range = torch.arange(last_dim, device=t.device, dtype=torch.int64) + b_range = torch.arange( + offset, last_dim + offset, device=t.device, dtype=torch.int64 + ) + + # broadcast + cond = a_range == b_range.unsqueeze(-1) + cond_shape = [last_dim if i in (dim1, dim2) else 1 for i in range(len(t.shape))] + cond = cond.reshape(cond_shape) + + # aten.diag_embed always returns a new contiguous tensor + # contiguous() is needed to correctly model the output stride + return utils.mask_tensor(cond, t).contiguous() + + +@register_decomposition(aten.block_diag) +@out_wrapper() +def _block_diag_iterable(tensors: list[TensorLikeType]) -> TensorLikeType: + """ + Reference implementation of torch.block_diag + """ + tensors_2d = [ + tensor.view(1, -1) if tensor.dim() <= 1 else tensor for tensor in tensors + ] + + ncols = builtins.sum(tensor.shape[1] for tensor in tensors_2d) + device = tensors_2d[0].device + + result = [] + + col_start = 0 + for i, tensor in enumerate(tensors_2d): + torch._check( + tensor.dim() == 2, + lambda: "Input tensors must have 2 or fewer dimensions. " + f"Input {i} has {tensor.dim()} dimensions", + ) + torch._check( + tensor.device == device, + lambda: "Input tensors must all be on the same device. " + f"Input 0 is on device {device} and input {i} is on device {tensor.device}.", + ) + row, col = tensor.shape + left = torch.zeros((row, col_start), device=device, dtype=tensor.dtype) + right = torch.zeros( + (row, ncols - col_start - col), device=device, dtype=tensor.dtype + ) + result += [torch.cat((left, tensor, right), dim=1)] + col_start += col + + return torch.cat(result, dim=0) + + +def block_diag(*tensors: list[TensorLikeType]) -> TensorLikeType: + """ + This is used as an input to PythonRefInfo. `torch.block_diag` + expects arguments splatted, but `aten.block_diag` expects only + one argument that is a list of Tensors. + """ + return _block_diag_iterable(tensors) # type: ignore[arg-type] + + +# CompositeImplicitAutograd - don't register decomp +def dsplit(a: TensorLikeType, sections: DimsType) -> TensorSequenceType: + if a.ndim < 3: + raise RuntimeError( + f"torch.dsplit requires a tensor with at least 3 dimension, but got a tensor with {a.ndim} dimensions!" + ) + # pyrefly: ignore [unsupported-operation] + if isinstance(sections, IntLike) and (sections == 0 or a.shape[2] % sections != 0): + raise RuntimeError( + "torch.dsplit attempted to split along dimension 2, " + + f"but the size of the dimension {a.shape[2]} is not divisible by the split_size {sections}!" + ) + return tensor_split(a, sections, 2) + + +@register_decomposition(aten.t.default) +def t(a: TensorLikeType): + # TODO: Add sparse support + # if a.is_sparse: + # sparse_dim = a.sparse_dim() + # dense_dim = a.dense_dim() + # if not (sparse_dim <= 2 and dense_dim == 0): + # raise RuntimeError( + # f"t() expects a tensor with <= 2 sparse and 0 dense dimensions, but got {sparse_dim} sparse and" + # f"{dense_dim} dense dimensions" + # ) + if a.ndim > 2: + raise RuntimeError( + f"t() expects a tensor with <= 2 dimensions, but self is {a.ndim}D" + ) + return torch.transpose(a, 0, 0 if a.ndim < 2 else 1) + + +# CompositeImplicitAutograd - don't register decomp +def T(a: TensorLikeType) -> TensorLikeType: + # n != 2 && n != 0 is deprecated in regular PyTorch. + torch._check( + a.ndim in (0, 2), + lambda: ( + "The use of `x.T` on tensors of dimension other than 0 or 2 " + "to reverse their shape is not supported." + ), + ) + return a.t() + + +@register_decomposition(aten.alias) +def alias(a: TensorLikeType) -> TensorLikeType: + return prims.view_of(a) + + +@register_decomposition(aten.transpose) +def transpose(a: TensorLikeType, dim0: int, dim1: int) -> TensorLikeType: + _dim0, _dim1 = utils.canonicalize_dims(a.ndim, (dim0, dim1)) # type: ignore[misc] + + if a.ndim <= 1 or dim0 == dim1: + return aten.alias.default(a) + + _permutation = list(range(a.ndim)) + _permutation[_dim0] = _dim1 + _permutation[_dim1] = _dim0 + return torch.permute(a, _permutation) + + +# Aliases for transpose +swap_axes = transpose + + +@register_decomposition(aten.unfold) +def unfold( + self: TensorLikeType, dimension: int, size: int, step: int +) -> TensorLikeType: + shape, strides = _get_unfold_shape_stride( + self.shape, self.stride(), dimension, size, step + ) + return self.as_strided(shape, strides) + + +@register_decomposition(aten.unfold_copy) +@out_wrapper() +def unfold_copy(self: TensorLikeType, dimension: int, size: int, step: int): + return self.unfold(dimension, size, step).clone( + memory_format=torch.contiguous_format + ) + + +def _cumsumprod_common( + func, + init, + a: TensorLikeType, + dim: int, + *, + dtype: torch.dtype | None = None, + out: Tensor | None = None, +) -> TensorLikeType: + # We implement all the kwargs of a reduction. ATen just handles dtype + # nb. This decomposition may not be as efficient as a backend-specific implementation + ndim = a.ndim + dim = utils.canonicalize_dim(ndim, dim) + if ndim == 0: + return func(a.unsqueeze(0), dim=0, dtype=dtype, out=out) + a = a.unsqueeze(dim + 1) + rg = torch.arange(a.shape[dim], device=a.device) + mask = rg.unsqueeze(1) <= rg + for _ in range(ndim - dim - 1): + mask = mask.unsqueeze(-1) + masked_a = torch.where(mask, a, init) + return func(masked_a, dim=dim, dtype=dtype, out=out) + + +@register_decomposition(aten.cumsum) +def cumsum( + a: TensorLikeType, + dim: int, + *, + dtype: torch.dtype | None = None, + out: Tensor | None = None, +) -> TensorLikeType: + return _cumsumprod_common(func=sum, init=0, a=a, dim=dim, dtype=dtype, out=out) + + +@register_decomposition(aten.cumprod) +def cumprod( + a: TensorLikeType, + dim: int, + *, + dtype: torch.dtype | None = None, + out: Tensor | None = None, +) -> TensorLikeType: + return _cumsumprod_common(func=prod, init=1, a=a, dim=dim, dtype=dtype, out=out) + + +# Note: although squeeze is documented as having the out= kwarg it doesn't +@register_decomposition(aten.unsqueeze) +def unsqueeze(a: TensorLikeType, dim: int) -> TensorLikeType: + # Note that unsqueeze canonicalizes with rank + 1 because it allows + # a new innermost dimension to be specified + ndim = a.ndim + 1 + dim = utils.canonicalize_dim(ndim, dim) + return prims.expand_dims(a, (dim,), ndim=ndim) + + +# NOTE: shape is a vararg because Tensor.reshape can be called with as +# Tensor.view(a, b, c) or Tensor.view((a, b, c)) Function call torch.view +# doesn't support unpacked shapes +# TODO: Turn this into a decomposition (currently fails on reshape meta tests) +@register_decomposition(aten.view.default) +def view(a: TensorLikeType, *shape: ShapeType | tuple[ShapeType]) -> TensorLikeType: + from torch._subclasses.fake_impls import ( + _view_has_unbacked_input, + _view_unbacked_meta, + ) + + # Cast to satisfy the type checker since the varargs annotation creates + # tuple[ShapeType | tuple[ShapeType], ...] but the function expects + # Union[ShapeType, tuple[ShapeType]]. + shape_tuple = utils.extract_shape_from_varargs( + cast(ShapeType | tuple[ShapeType], shape), validate=False + ) + if torch.fx.experimental._config.backed_size_oblivious or _view_has_unbacked_input( + a, + shape_tuple, + ): + return _view_unbacked_meta(a, shape_tuple) + return _reshape_view_helper(a, *shape, allow_copy=False) + + +# CompositeImplicitAutograd - don't register decomp +def view_as(self: TensorLikeType, other: TensorLikeType) -> TensorLikeType: + return self.view(other.size()) + + +# CompositeImplicitAutograd - don't register decomp +def ravel(a: TensorLikeType) -> TensorLikeType: + return reshape(a, (-1,)) + + +# CompositeImplicitAutograd - don't register decomp +# missing ref impl. for aten.gather +@out_wrapper() +def take_along_dim( + a: torch.Tensor, indices: torch.Tensor, dim: int | None = None +) -> torch.Tensor: + torch._check( + a.ndim == indices.ndim, + lambda: ( + "torch.take_along_dim(): input and indices should have the same " + f"number of dimensions, but got {a.ndim} dimensions for input, and " + f"{indices.ndim} dimensions for indices" + ), + ) + + torch._check( + utils.is_integer_dtype(indices.dtype), + lambda: ( + "torch.take_along_dim(): dtype of indices should be int but got " + f"{indices.dtype} instead" + ), + ) + + if dim is None: + return torch.gather(a.view(-1), 0, indices.view(-1)) + else: + self_sizes = list(a.shape) + self_sizes[dim] = indices.size(dim) + broadcast_shape = utils.infer_size_shapes(self_sizes, indices.size()) + indices_broadcast = broadcast_to(indices, broadcast_shape) + + indices_sizes = list(indices.shape) + indices_sizes[dim] = a.size(dim) + broadcast_shape = utils.infer_size_shapes(indices_sizes, a.size()) + self_broadcast = broadcast_to(a, broadcast_shape) + + # wrap negative indices + dim_size = self_broadcast.size(dim) + indices_broadcast = indices_broadcast % dim_size + + return torch.gather(self_broadcast, dim, indices_broadcast) + + +@out_wrapper() +def empty( + *shape, + dtype: torch.dtype | None = None, + layout: torch.layout = torch.strided, + device: DeviceLikeType | None = None, + requires_grad: bool = False, + pin_memory: bool = False, + memory_format: torch.memory_format = torch.contiguous_format, +) -> TensorLikeType: + torch._check( + memory_format != torch.preserve_format, + lambda: "torch.empty: the Preserve memory format is not supported", + ) + + shape = utils.extract_shape_from_varargs(shape) + + if memory_format == torch.contiguous_format: + strides = utils.make_contiguous_strides_for(shape) + elif memory_format == torch.channels_last_3d: + # pyrefly: ignore [bad-specialization] + strides = utils.make_channels_last_3d_strides_for(shape) + else: # memory_format == torch.channels_last + torch._check( + memory_format == torch.channels_last, + lambda: f"torch.empty: received an unknown memory format {memory_format}!", + ) + # pyrefly: ignore [bad-specialization] + strides = utils.make_channels_last_2d_strides_for(shape) + + return torch.empty_strided( + shape, + strides, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@out_wrapper() +def empty_permuted( + shape, + physical_layout, + dtype: torch.dtype | None = None, + layout: torch.layout = torch.strided, + device: DeviceLikeType | None = None, + requires_grad: bool = False, + pin_memory: bool = False, +) -> TensorLikeType: + return prims.empty_permuted( + shape, + physical_layout, + dtype=dtype, + device=device, + requires_grad=requires_grad, + ) + + +@register_decomposition(aten.new_empty) +@out_wrapper() +def new_empty( + a: TensorLikeType, + size: ShapeType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: bool = False, +) -> TensorLikeType: + dtype = a.dtype if dtype is None else dtype + layout = a.layout if layout is None else layout + device = a.device if device is None else device + + return torch.empty( + size, + dtype=dtype, + device=device, + pin_memory=pin_memory, + layout=layout, + ) + + +@register_decomposition(aten.new_empty_strided) +@out_wrapper() +def new_empty_strided( + a: TensorLikeType, + size: ShapeType, + stride: StrideType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: bool = False, +) -> TensorLikeType: + """ + Reference implementation of torch.Tensor.new_empty_strided + """ + + dtype = a.dtype if dtype is None else dtype + layout = a.layout if layout is None else layout + device = a.device if device is None else device + + return torch.empty_strided( + size, + stride, + dtype=dtype, + device=device, + pin_memory=pin_memory, + layout=layout, + ) + + +@register_decomposition(aten.zeros.default) +@out_wrapper() +def zeros( + *size, + dtype: torch.dtype | None = None, + layout: torch.layout = torch.strided, + device: DeviceLikeType | None = None, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + size = utils.extract_shape_from_varargs(size) + + if dtype is None: + dtype = torch.get_default_dtype() + + return torch.full( + size, + False if dtype == torch.bool else 0, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@register_decomposition(aten.new_zeros) +@out_wrapper() +def new_zeros( + a: TensorLikeType, + size: ShapeType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + dtype = a.dtype if dtype is None else dtype + layout = a.layout if layout is None else layout + device = a.device if device is None else device + + return torch.full( + size, + False if (dtype or a.dtype) == torch.bool else 0, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@register_decomposition(aten.ones.default) +@out_wrapper() +def ones( + *size, + dtype: torch.dtype | None = None, + layout: torch.layout = torch.strided, + device: DeviceLikeType | None = None, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + size = utils.extract_shape_from_varargs(size) + + if dtype is None: + dtype = torch.get_default_dtype() + + return torch.full( + size, + True if dtype == torch.bool else 1, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@register_decomposition(aten.new_ones) +@out_wrapper() +def new_ones( + a: TensorLikeType, + size: ShapeType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + dtype = a.dtype if dtype is None else dtype + layout = a.layout if layout is None else layout + device = a.device if device is None else device + + return torch.full( + size, + True if (dtype or a.dtype) == torch.bool else 1, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@register_decomposition(aten.new_full) +@out_wrapper() +def new_full( + a: TensorLikeType, + size: ShapeType, + fill_value: NumberType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: bool = False, +) -> TensorLikeType: + dtype = a.dtype if dtype is None else dtype + layout = a.layout if layout is None else layout + device = a.device if device is None else device + + return torch.full( + size, + fill_value, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + ) + + +@aten.empty.out.py_impl(DispatchKey.CompositeImplicitAutograd) +def empty_out( + size: ShapeType, + out: TensorLikeType, + memory_format: torch.memory_format | None = None, +) -> TensorLikeType: + _maybe_resize_out(out, size, memory_format) + return out + + +@register_decomposition(aten.empty_like) +@out_wrapper() +def empty_like( + a: TensorLikeType, + *, + dtype: torch.dtype | None = None, + device: DeviceLikeType | None = None, + layout: torch.layout | None = None, + pin_memory: bool = False, + requires_grad: bool = False, + memory_format: torch.memory_format = torch.preserve_format, +) -> TensorLikeType: + dtype = a.dtype if dtype is None else dtype + layout = a.layout if layout is None else layout + device = a.device if device is None else device + + if memory_format != torch.preserve_format: + return torch.empty( + a.shape, + dtype=dtype, + layout=layout, + device=device, + requires_grad=requires_grad, + pin_memory=pin_memory, + memory_format=memory_format, + ) + + # memory_format == torch.preserve_format + logical_to_physical_perm, _ = ( + utils.compute_elementwise_output_logical_to_physical_perm(a) + ) + # identity perm is [2, 1, 0] + return torch.empty_permuted( + a.shape, + logical_to_physical_perm, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + + +@register_decomposition([aten.arange.start_step, aten.arange.start_out]) +@out_wrapper() +def arange( + start: NumberType = 0, + end: NumberType | None = None, + step: NumberType = 1, + *, + dtype: torch.dtype | None = None, + layout: torch.layout = torch.strided, + device: DeviceLikeType | None = None, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + utils.check_layout(layout) + utils.check_pin_memory(pin_memory) + device = torch.device(utils.device_or_default(device)) + + if isinstance(start, complex): + raise AssertionError("arange does not support complex start") + if isinstance(end, complex): + raise AssertionError("arange does not support complex end") + if isinstance(step, complex): + raise AssertionError("arange does not support complex step") + + # Case: torch.arange(5) + if end is None: + end = start + start = 0 + torch._check(step != 0, lambda: "step must be nonzero") + if step > 0: + torch._check( + end >= start, + lambda: "upper bound and lower bound inconsistent with step sign", + ) + elif step < 0: + torch._check( + end <= start, + lambda: "upper bound and lower bound inconsistent with step sign", + ) + + def is_finite(x): + return not isinstance(x, FloatWithoutSymFloat) or math.isfinite(x) + + torch._check( + is_finite(start) and is_finite(end), + lambda: f"unsupported range: {start} -> {end}", + ) + torch._check( + is_finite(step), + lambda: f"step must be finite but got {step}", + ) + + args = (start, end, step) + integer_args = builtins.all(isinstance(arg, IntLike) for arg in args) + + if dtype is None: + dtype = torch.int64 if integer_args else torch.get_default_dtype() + + is_integer = utils.is_integer_dtype(dtype) + if is_integer or integer_args: + xstart = sym_int(start) + xend = sym_int(end) + xstep = sym_int(step) + + if integer_args: + torch._check_value(xstep != 0, lambda: "step must be nonzero") # type: ignore[possibly-undefined] + # Uses floordiv to avoid ceil in inductor. + sgn = bool(xstep > 0) - bool(xstep < 0) # type: ignore[possibly-undefined] + length = (xend - xstart + xstep - sgn) // xstep # type: ignore[possibly-undefined] + else: + length = math.ceil((end - start) / step) + + if is_integer and integer_args: + return prims.iota( + length, + start=xstart, # type: ignore[possibly-undefined] + step=xstep, # type: ignore[possibly-undefined] + dtype=dtype, + device=device, + requires_grad=requires_grad, + ) + + if is_integer and not integer_args: + index = prims.iota( + length, + start=0, + step=1, + dtype=dtype, + device=device, + requires_grad=requires_grad, + ) + return xstart + xstep * index # type: ignore[possibly-undefined] + + index = prims.iota( + length, + start=0, + step=1, + dtype=torch.int64, + device=device, + requires_grad=False, + ) + + computation_dtype = ( + torch.long if integer_args else utils.get_acc_type(dtype, device) + ) + index = _maybe_convert_to_dtype(index, computation_dtype) + result = start + step * index + result = _maybe_convert_to_dtype(result, dtype) + + if requires_grad: + result.requires_grad_(True) + return result + + +@register_decomposition(aten.lerp) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("start", "end", "weight"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def lerp(start: Tensor, end: Tensor, weight: Tensor | NumberType): + inputs = [start, end] + if isinstance(weight, Number): + weight = start.new_full((), weight) # type: ignore[arg-type] + else: + inputs.append(weight) + if not isinstance(weight, Tensor): + raise AssertionError(f"weight must be Tensor at this point, got {type(weight)}") + # We implement it this way for numerical stability. We assume (in the stability optimisation) + # that 0 <= weight <= 1. We take the abs to deal with complex numbers + # We want to perform operations near zero, which is where floating points are most precise + # thus, we perform the following optimisation: + # If weight.abs() >= 0.5: + # return (1 - weight) * (start - end) + end + mask = weight.abs() >= 0.5 + coeff = torch.where(mask, weight - 1, weight) + base = torch.where(mask, end, start) + output = coeff * (end - start) + base + # make sure the decomposition output's stride is same as non-decomposition path. + stride = utils.compute_elementwise_output_strides(*_maybe_broadcast(*inputs)) + if output.stride() != stride: + output = prims.copy_strided(output, stride) + + return handle_noncontiguous_outputs(inputs, output) + + +@register_decomposition(aten.linspace) +@out_wrapper() +def linspace( + start: NumberType | TensorLikeType, + end: NumberType | TensorLikeType, + steps: NumberType, + *, + dtype: torch.dtype | None = None, + device: DeviceLikeType | None = None, + layout: torch.layout = torch.strided, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + if isinstance(start, TensorLikeType): + torch._check( + start.dim() == 0, + lambda: "linspace only supports 0-dimensional start and end tensors", + ) + start = _maybe_convert_to_dtype(start, highest_precision_float(device)) + if isinstance(end, TensorLikeType): + torch._check( + end.dim() == 0, + lambda: "linspace only supports 0-dimensional start and end tensors", + ) + end = _maybe_convert_to_dtype(end, highest_precision_float(device)) + + if builtins.any(isinstance(arg, complex) for arg in (start, end, steps)): + default_complex_dtype = utils.corresponding_complex_dtype( + torch.get_default_dtype() + ) + if dtype is None: + dtype = default_complex_dtype + else: + torch._check( + utils.is_complex_dtype(dtype), + lambda: f"linspace(): inferred dtype {default_complex_dtype} can't be safely cast to passed dtype {dtype}", + ) + else: + dtype = dtype or torch.get_default_dtype() + if not isinstance(dtype, torch.dtype): + raise AssertionError(f"dtype must be torch.dtype, got {type(dtype)}") + + # steps does not participate in the computation of the dtype + torch._check_type( + isinstance(steps, IntLike), + lambda: f"received an invalid combination of arguments - got \ +({type(start).__name__}, {type(end).__name__}, {type(steps).__name__})", + ) + if not isinstance(steps, IntLike): + raise AssertionError(f"steps must be IntLike, got {type(steps)}") # for mypy + torch._check(steps >= 0, lambda: "number of steps must be non-negative") + + factory_kwargs = { + "layout": layout, + "device": device, + "pin_memory": pin_memory, + "requires_grad": requires_grad, + } + if steps == 0: + return torch.full((0,), 0, dtype=dtype, **factory_kwargs) # type: ignore[arg-type] + if steps == 1: + if isinstance(start, TensorLikeType): + empty_tensor = torch.empty((steps,), dtype=dtype, **factory_kwargs) # type: ignore[arg-type] + return torch.ops.aten.copy.default(empty_tensor, start) + else: + return torch.full((steps,), start, dtype=dtype, **factory_kwargs) # type: ignore[arg-type] + + # Perform in arange in int because some backends like ATen or Triton do not support all the dtypes + rg = torch.arange(0, steps, **factory_kwargs) # type: ignore[arg-type] + + # Small types need to be computed in higher precision as this is, at heart, an associative scan + dtype_red = ( + torch.int64 + if (utils.is_boolean_dtype(dtype) or utils.is_integer_dtype(dtype)) + else dtype + ) + computation_dtype, _ = utils.reduction_dtypes( + rg, REDUCTION_OUTPUT_TYPE_KIND.SAME, dtype_red + ) + cast_rg = partial(_maybe_convert_to_dtype, dtype=computation_dtype) + + # We implement torch.lerp without performing rg / (steps - 1) explicitly + # With this we get out[0] == start, out[-1] == end + step = (end - start) / (steps - 1) + # pyrefly: ignore [no-matching-overload] + out = torch.where( + rg < steps / 2, + start + step * cast_rg(rg), # type: ignore[arg-type,operator] + end - step * cast_rg((steps - 1) - rg), # type: ignore[arg-type,operator] + ) + return _maybe_convert_to_dtype(out, dtype) # type: ignore[return-value] + + +@register_decomposition(aten.logspace) +@out_wrapper() +def logspace( + start: NumberType | TensorLikeType, + end: NumberType | TensorLikeType, + steps: NumberType, + base: NumberType = 10, + *, + dtype: torch.dtype | None = None, + device: DeviceLikeType | None = None, + layout: torch.layout = torch.strided, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + if dtype is None: + dtype = torch.get_default_dtype() + + # NB: NumPy doesn't have this cast + if prims.utils.is_integer_dtype(dtype): + if isinstance(start, FloatLike): + start = sym_int(start) + elif isinstance(start, TensorLikeType): + torch._check( + start.dim() == 0, + lambda: "logspace only supports 0-dimensional start and end tensors", + ) + start = _maybe_convert_to_dtype(start, dtype) + if isinstance(end, FloatLike): + end = sym_int(end) + elif isinstance(end, TensorLikeType): + torch._check( + end.dim() == 0, + lambda: "logspace only supports 0-dimensional start and end tensors", + ) + end = _maybe_convert_to_dtype(end, dtype) + + if builtins.any(isinstance(arg, complex) for arg in (start, end, steps)): + default_complex_dtype = utils.corresponding_complex_dtype( + torch.get_default_dtype() + ) + dtype = default_complex_dtype + _dtype = None # torch.linspace will update the correct dtype + else: + _dtype = torch.float64 + + if isinstance(base, complex): + raise AssertionError(f"base must not be complex, got {type(base)}") # for mypy + if base < 0: + raise NotImplementedError + ret = torch.linspace( # type: ignore[misc] + start, # type: ignore[arg-type] + end, # type: ignore[arg-type] + steps, # type: ignore[arg-type] + dtype=_dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + return _maybe_convert_to_dtype(torch.pow(base, ret), dtype) # type: ignore[arg-type,return-value] + + +@overload +# pyrefly: ignore [inconsistent-overload] +def meshgrid(tensors: Sequence[TensorLikeType], indexing: str): + pass + + +@overload +def meshgrid(*tensors: TensorLikeType, indexing: str): + pass + + +@register_decomposition(aten.meshgrid) # type: ignore[misc] +def meshgrid( + *tensors: TensorLikeType | list[TensorLikeType] | tuple[TensorLikeType], + indexing: str, +) -> list[TensorLikeType]: + # This ref simultaneously handles two overloads (see stubs above) + # The `indexing` argument is currently optional for torch.meshgrid, but we + # plan to make the argument required: https://github.com/pytorch/pytorch/issues/50276 + if isinstance(tensors[0], (list, tuple)): + if len(tensors) != 1: + raise AssertionError( + f"Expected exactly 1 tensor list/tuple, got {len(tensors)}" + ) + tensors = tuple(tensors[0]) + + torch._check( + builtins.all(isinstance(a, TensorLike) for a in tensors), + lambda: "meshgrid expects its inputs to be tensors", + ) + + torch._check(len(tensors) > 0, lambda: "meshgrid expects a non-empty TensorList") + + for i in range(len(tensors) - 1): + torch._check( + tensors[i].dtype == tensors[i + 1].dtype, # type: ignore[union-attr] + lambda: "meshgrid expects all tensors to have the same dtype", + ) + torch._check( + tensors[i].device == tensors[i + 1].device, # type: ignore[union-attr] + lambda: "meshgrid expects all tensors to have the same device", + ) + + swap_first_and_second_tensors = False + if indexing == "xy": + swap_first_and_second_tensors = len(tensors) >= 2 + if swap_first_and_second_tensors: + tensors = (tensors[1], tensors[0], *tensors[2:]) + else: + torch._check( + indexing == "ij", + lambda: ( + 'torch.meshgrid: indexing must be one of "xy" or "ij", ' + f"but received: {indexing}" + ), + ) + + result_shape: list[int] = [] + for t in tensors: + if not isinstance(t, TensorLike): + raise AssertionError(f"expected TensorLike, got {type(t)}") # mypy + torch._check( + t.ndim == 0 or t.ndim == 1, + lambda: f"torch.meshgrid: Expected 0D or 1D tensor in the tensor list but got: {t}", + ) + result_shape.append(t.numel()) + + grids: list[TensorLikeType] = [] + for i, t in enumerate(tensors): + if not isinstance(t, TensorLike): + raise AssertionError(f"expected TensorLike, got {type(t)}") # mypy + if t.ndim == 0: + t = t.view((1,)) + grids.append(prims.broadcast_in_dim(t, result_shape, (i,))) + + if swap_first_and_second_tensors: + # Swap outputs if we originally swapped at the beginning + grids[0], grids[1] = grids[1], grids[0] + + return grids + + +# CompositeImplicitAutograd - don't register decomp +def movedim( + input: TensorLikeType, + source: int | DimsSequenceType, + destination: int | DimsSequenceType, +) -> TensorLikeType: + """ + Reference implementation of torch.movedim + """ + if type(source) is int: + source = (source,) + if type(destination) is int: + destination = (destination,) + + # Converts to list to produce a compatible error message with core PyTorch, + # which prints sequences in square brackets. + torch._check( + len(source) == len(destination), # type: ignore[arg-type] + lambda: ( + "movedim: Invalid source or destination dims: source " # type: ignore[arg-type] + f"({list(source)} dims) should contain the same number " # type: ignore[arg-type] + f"of dims as destination ({list(destination)} dims)" # type: ignore[arg-type] + ), + ) + + rank = input.ndim + ss = tuple(utils.canonicalize_dims(rank=rank, indices=source)) # type: ignore[arg-type] + ds = tuple(utils.canonicalize_dims(rank=rank, indices=destination)) # type: ignore[arg-type] + + sss = set(ss) + dss = set(ds) + + # See above on why this converts to list in error messages. + torch._check( + len(ss) == len(sss), + lambda: f"movedim: repeated dim in `source` ({list(source)})", # type: ignore[arg-type] + ) + torch._check( + len(ds) == len(dss), + lambda: f"movedim: repeated dim in `destination` ({list(destination)})", # type: ignore[arg-type] + ) + + m = dict(zip(ds, ss)) + dims = [] + si = 0 # source index + for di in range(rank): + # check if the destination index is in the mapping + s = m.get(di) + if s is not None: + # insert source index if found + dims.append(s) + else: + # insert source index sequentially, skipping indices from the mapping + while si in sss: + si += 1 + dims.append(si) + si += 1 + + result = torch.permute(input, tuple(dims)) + + return result + + +# NOTE: for convenience, shape can be a tuple of ints or a tuple containing a tuple of ints +@register_decomposition(aten.empty_strided) +@out_wrapper() +def empty_strided( + shape: ShapeType | tuple[ShapeType], + strides: StrideType, + *, + dtype: torch.dtype | None = None, + device: DeviceLikeType | None = None, + layout: torch.layout = torch.strided, + requires_grad: bool = False, + pin_memory: bool = False, +) -> TensorLikeType: + # Layout == strided, pin_memory is False + utils.check_layout(layout) + utils.check_pin_memory(pin_memory) + + shape = utils.extract_shape_from_varargs(shape) + dtype = torch.get_default_dtype() if dtype is None else dtype + device = torch.device("cpu") if device is None else device + + return prims.empty_strided( + shape, + strides, + dtype=dtype, + device=device, + requires_grad=requires_grad, + ) + + +def _strength_reduce_integer(val: int) -> torch.dtype: + for possible_dtype in (torch.uint8, torch.uint16, torch.int32): + if val <= torch.iinfo(possible_dtype).max: + return possible_dtype + return torch.int64 + + +@register_decomposition(aten.eye) +@out_wrapper() +def eye( + n: int, + m: int | None = None, + *, + dtype: torch.dtype | None = None, + layout: torch.layout = torch.strided, + device: DeviceLikeType | None = None, + pin_memory: bool = False, + requires_grad: bool = False, # TODO: unused +) -> TensorLikeType: + """ + Reference implementation of torch.eye + """ + if m is None: + m = n + + torch._check(n >= 0, lambda: f"n must be greater or equal to 0, got {n}") + torch._check(m >= 0, lambda: f"m must be greater or equal to 0, got {m}") + + range_dtype = torch.int64 + if isinstance(n, utils.IntWithoutSymInt) and isinstance(m, utils.IntWithoutSymInt): + range_dtype = _strength_reduce_integer(max(n, m)) + range_n = torch.arange(n, dtype=range_dtype, device=device, requires_grad=False) + range_m = torch.arange(m, dtype=range_dtype, device=device, requires_grad=False) + + cond = range_n.unsqueeze(-1) == range_m + if layout in (torch.strided, None) and not pin_memory: + return cond.to(dtype or torch.get_default_dtype()) + else: + one = torch.ones( + (1,), + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=False, + ) + return torch.where(cond, one, 0) + # TODO: Use requires_grad. All refs taking the requires_grad kwarg must + # return a leaf tensor. + # result.requires_grad_(requires_grad) + + +@register_decomposition([aten.full.default, aten.full.out]) +@out_wrapper() +def full( + shape: ShapeType, + fill_value: NumberType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout = torch.strided, + device: DeviceLikeType | None = None, + pin_memory: bool = False, + requires_grad: bool = False, +) -> TensorLikeType: + utils.check_layout(layout) + utils.check_pin_memory(pin_memory) + + dtype = dtype if dtype is not None else utils.type_to_dtype(type(fill_value)) + device = device if device is not None else torch.device("cpu") + + e = empty( + shape, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + ) + return torch.fill(e, fill_value) # type: ignore[arg-type] + + +def full_like( + a: TensorLikeType, + fill_value: NumberType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: bool = False, + requires_grad: bool = False, + memory_format: torch.memory_format = torch.preserve_format, +) -> TensorLikeType: + e = torch.empty_like( + a, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + memory_format=memory_format, + ) + return fill(e, fill_value) + + +@register_decomposition(aten.zeros_like) +@out_wrapper() +def zeros_like( + a: TensorLikeType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: bool = False, + requires_grad: bool = False, + memory_format: torch.memory_format = torch.preserve_format, +) -> TensorLikeType: + return torch.full_like( + a, + False if (dtype or a.dtype) == torch.bool else 0, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + memory_format=memory_format, + ) + + +@register_decomposition(aten.ones_like) +@out_wrapper() +def ones_like( + a: TensorLikeType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: bool = False, + requires_grad: bool = False, + memory_format: torch.memory_format = torch.preserve_format, +) -> TensorLikeType: + return torch.full_like( + a, + True if (dtype or a.dtype) == torch.bool else 1, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + requires_grad=requires_grad, + memory_format=memory_format, + ) + + +@register_decomposition(aten.randn.default) +@out_wrapper() +def randn( + *shape, + dtype: torch.dtype | None = None, + device: DeviceLikeType | None = None, + layout: torch.layout | None = None, + requires_grad: bool = False, + pin_memory: bool = False, +) -> TensorLikeType: + utils.check_pin_memory(pin_memory) + + shape_ = utils.extract_shape_from_varargs(shape) + + dtype = utils.dtype_or_default(dtype) + device = utils.device_or_default(device) + + return prims.normal( + shape_, + mean=0.0, + std=1.0, + dtype=dtype, + device=device, + requires_grad=requires_grad, + ) + + +def scalar_tensor( + a: NumberType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout = torch.strided, + device: DeviceLikeType | None = None, + pin_memory: bool = False, +) -> TensorLikeType: + utils.check_layout(layout) + utils.check_pin_memory(pin_memory) + dtype = dtype if dtype is not None else utils.type_to_dtype(type(a)) + device = device if device is not None else torch.device("cpu") + return prims.scalar_tensor(a, dtype=dtype, device=device) + + +# +# Randomness References +# + + +def _uniform_helper( + shape: ShapeType, + low: bool | int | float = 0.0, + high: bool | int | float = 1.0, + *, + stride: ShapeType, + dtype: torch.dtype, + device: DeviceLikeType, +) -> TensorLikeType: + utils.validate_shape(shape) + + if not isinstance(low, Number): + raise AssertionError(f"low must be Number, got {type(low)}") + if not isinstance(high, Number): + raise AssertionError(f"high must be Number, got {type(high)}") + # pyrefly: ignore [bad-assignment] + low = sym_float(low) + # pyrefly: ignore [bad-assignment] + high = sym_float(high) + + if not isinstance(dtype, torch.dtype): + raise AssertionError(f"dtype must be torch.dtype, got {type(dtype)}") + device = utils.canonicalize_device(device) + + return prims._uniform_helper( + shape, low=low, high=high, dtype=dtype, device=device, stride=stride + ) + + +@register_decomposition(aten.masked_fill) +@out_wrapper() +def masked_fill(a: TensorLikeType, mask: TensorLikeType, value: TensorOrNumberLikeType): + python_type = utils.dtype_to_type(a.dtype) + if isinstance(value, Number): + value_type = type(value) + else: + # NOTE: Could not use value = item(value) as it resulted in + # RuntimeError: Cannot cast FakeTensor(cpu) to number + value_ndim = value.ndim + torch._check( + value_ndim == 0, + lambda: f"only supports a 0-dimensional value tensor, but got tensor with {value_ndim} dimension", + ) + # `masked_fill` allows cpu scalar to be moved to cuda, xpu and hpu but not otherwise. + is_cpu_scalar = ( + a.device.type + in ["cuda", "xpu", "mps", torch._C._get_privateuse1_backend_name(), "hpu"] + and value.device.type == "cpu" + ) + torch._check( + is_cpu_scalar or value.device == a.device, + lambda: "Expected `value` to be on same device as `a`", + ) + value_type = utils.dtype_to_type(value.dtype) + + if value_type is complex: + # only downcasting from complex to lower type is not allowed. + # We allow casting `value` to lower type for other case + # Eg. float -> int. + # Ref: https://github.com/pytorch/pytorch/issues/79195 + torch._check( + utils.is_weakly_lesser_type(value_type, python_type), + lambda: f"could not convert to type {python_type} without overflow", + ) + + # Since `where` allows type-promotion, + # cast value to correct type before passing to `where` + + value = _maybe_convert_to_dtype(value, a.dtype) + r = torch.where(mask, value, a) # type: ignore[arg-type] + + # aten.mask_fill always return a new contiguous tensor + # contiguous() is needed to correctly model the output stride + return r.contiguous() + + +@register_decomposition(aten.masked_fill_) +def masked_fill_( + a: TensorLikeType, mask: TensorLikeType, value: TensorOrNumberLikeType +) -> TensorLikeType: + b = torch.masked_fill(a, mask, value) # type: ignore[arg-type] + a.copy_(b) + return a + + +# CompositeImplicitAutograd - don't register decomp +def allclose( + a: TensorLikeType, + b: TensorLikeType, + rtol: float = 1e-05, + atol: float = 1e-08, + equal_nan: bool = False, +) -> bool: + """ + Reference implementation of torch.allclose + """ + _check_close_args(name="torch.allclose", a=a, b=b, rtol=rtol, atol=atol) + + return bool( + torch.all(torch.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)).item() + ) + + +def equal(a: TensorLikeType, b: TensorLikeType) -> bool: + utils.check_same_device(a, b, allow_cpu_scalar_tensors=False) + utils.check_same_dtype(a, b) + + # Shape check + if a.ndim != b.ndim: + return False + + for x, y in zip(a.shape, b.shape): + if x != y: + return False + + # Short-circuits if there are no elements to validate + if a.numel() == 0: + return True + + return item(all(eq(a, b))) # type: ignore[return-value] + + +@register_decomposition(aten.norm) +@out_wrapper(exact_dtype=True) +def norm( + input: TensorLikeType, + p: float | str | None = "fro", + dim: DimsType | None = None, + keepdim: bool = False, + *, + dtype: torch.dtype | None = None, +) -> TensorLikeType: + # In these cases we compute the "Frobenius norm" + if ( + p == "fro" and (dim is None or isinstance(dim, Dim) or len(dim) <= 2) + ) or p is None: + p = 2 + if isinstance(dim, Dim): + dim = [dim] + if isinstance(p, str): + # Here we either call the nuclear norm, or we call matrix_norm with some arguments + # that will throw an error + if dim is None: + dim = tuple(range(input.ndim)) + return torch.linalg.matrix_norm(input, p, dim, keepdim, dtype=dtype) + else: + return torch.linalg.vector_norm(input, p, dim, keepdim, dtype=dtype) + + +@register_decomposition(aten.trace) +@out_wrapper() +def trace(self: TensorLikeType) -> TensorLikeType: + torch._check( + self.ndim == 2, + lambda: f"expected a matrix, but got tensor with dim {self.ndim}", + ) + return torch.sum(torch.diag(self, 0)) + + +def _make_r_binary_op(base_op): + def rop( + a: TensorLikeType | NumberType, + b: TensorLikeType | NumberType, + ) -> TensorLikeType: + return base_op(b, a) + + return rop + + +rtruediv = _make_r_binary_op(true_divide) +rfloordiv = _make_r_binary_op(floor_divide) +rpow = _make_r_binary_op(pow) + + +@register_decomposition(aten.triu) +@out_wrapper() +def triu(a: TensorLikeType, diagonal: int = 0) -> TensorLikeType: + torch._check( + a.ndim >= 2, lambda: "triu: input tensor must have at least 2 dimensions" + ) + h, w = a.shape[-2:] + mask = ( + torch.arange(w, device=a.device).unsqueeze(-2) + - torch.arange(h, device=a.device).unsqueeze(-1) + ) >= diagonal + + # aten.triu always returns a new contiguous tensor + # contiguous() is needed to correctly model the output stride + return utils.mask_tensor(mask, a).contiguous() + + +@register_decomposition(aten.tril) +@out_wrapper() +def tril(a: TensorLikeType, diagonal: int = 0) -> TensorLikeType: + torch._check( + a.ndim >= 2, lambda: "tril: input tensor must have at least 2 dimensions" + ) + h, w = a.shape[-2:] + mask = ( + torch.arange(w, device=a.device).unsqueeze(-2) + - torch.arange(h, device=a.device).unsqueeze(-1) + ) <= diagonal + + # aten.tril always returns a new contiguous tensor + # contiguous() is needed to correctly model the output stride + return utils.mask_tensor(mask, a).contiguous() + + +# This is based on get_tril_size in aten/src/ATen/native/TensorFactories.h +# The components of the matrix that belong to the lower triangle with offset +# form a pentagon that can be broken down into a top trapezoid and a bottom +# rectangle. For the implementation of tril_indices, we need the sizes of +# both of these, as well as the length of the top side of the trapezoid. +def _get_tril_sizes(row: int, col: int, offset: int) -> tuple[int, int, int]: + if row == 0 or col == 0: + return 0, 0, 0 + + m_first_row = min(col, 1 + offset) if offset > 0 else int(row + offset > 0) + m_last_row = max(0, min(col, row + offset)) + n_row_all = max(0, min(row, row + offset)) + n_row_trapezoid = m_last_row - m_first_row + 1 + + # Number of elements in top trapezoid + trapezoid_size = (m_first_row + m_last_row) * n_row_trapezoid // 2 + # Number of elements in bottom rectangle + diff_row = n_row_all - n_row_trapezoid + rectangle_size = max(0, diff_row * col) + + return trapezoid_size, rectangle_size, m_first_row + + +def _trilu_checks( + name: str, + row: int, + col: int, + dtype: torch.dtype, + layout: torch.layout, + pin_memory: bool, +): + torch._check(row >= 0, lambda: f"row must be non-negative, got {row}") + torch._check(col >= 0, lambda: f"col must be non-negative, got {col}") + torch._check( + dtype in (torch.int32, torch.int64), + lambda: f"\"{name}\" not implemented for '{dtype}'", + ) + + +# This is based on tril_indices_cuda in aten/src/ATen/native/cuda/TensorFactories.cu +@register_decomposition(aten.tril_indices) +@out_wrapper() +def tril_indices( + row: int, + col: int, + offset: int = 0, + *, + dtype: torch.dtype = torch.long, + layout: torch.layout = torch.strided, + device: DeviceLikeType = "cpu", + pin_memory: bool = False, +) -> TensorLikeType: + _trilu_checks("tril_indices", row, col, dtype, layout, pin_memory) + + trapezoid_size, rectangle_size, m_first_row = _get_tril_sizes(row, col, offset) + row_offset = max(0, -offset) + + arange_kw = partial( + torch.arange, layout=layout, device=device, pin_memory=pin_memory + ) + + # first we do the indices for top trapezoid + xs1 = arange_kw(0, trapezoid_size, dtype=torch.float64) + b = m_first_row - 0.5 + row_inds1 = torch.floor(-b + torch.sqrt(b * b + 2 * xs1)) + col_inds1 = torch.floor(xs1 - (2 * m_first_row - 1 + row_inds1) * row_inds1 * 0.5) + row_inds1 = _maybe_convert_to_dtype(row_inds1 + row_offset, dtype) + col_inds1 = _maybe_convert_to_dtype(col_inds1, dtype) + + # then bottom rectangle + xs2 = arange_kw(0, rectangle_size, dtype=dtype) + row_inds2 = xs2 // col + (col - m_first_row + 1 + row_offset) + col_inds2 = xs2 % col + + return torch.stack( + (torch.cat((row_inds1, row_inds2)), torch.cat((col_inds1, col_inds2))) + ) + + +# Similar to _get_tril_sizes above, but here there is a top trapezoid and +# a bottom rectangle instead. Note that you can't reduce this to +# _get_tril_sizes(col, row, -offset) because that would correspond to +# decomposing into a left trapezoid and right rectangle. +def _get_triu_sizes(row: int, col: int, offset: int) -> tuple[int, int, int]: + if row == 0 or col == 0: + return 0, 0, 0 + + m_first_row = max(0, col - offset) if offset > 0 else col + + # Number of elements in top rectangle + rectangle_size = max(0, min(row, -offset) * col) + + # Number of elements in bottom trapezoid + trapezoid_size_tril, rectangle_size_tril, _ = _get_tril_sizes(row, col, offset - 1) + triu_size = row * col - (trapezoid_size_tril + rectangle_size_tril) + trapezoid_size = triu_size - rectangle_size + + return trapezoid_size, rectangle_size, m_first_row + + +@register_decomposition(aten.triu_indices) +@out_wrapper() +def triu_indices( + row: int, + col: int, + offset: int = 0, + *, + dtype: torch.dtype = torch.long, + layout: torch.layout = torch.strided, + device: DeviceLikeType = "cpu", + pin_memory: bool = False, +) -> TensorLikeType: + _trilu_checks("triu_indices", row, col, dtype, layout, pin_memory) + + trapezoid_size, rectangle_size, m_first_row = _get_triu_sizes(row, col, offset) + col_offset = max(0, offset) + + arange_kw = partial( + torch.arange, layout=layout, device=device, pin_memory=pin_memory + ) + + # indices for top rectangle + xs2 = arange_kw(0, rectangle_size, dtype=dtype) + row_inds2 = xs2 // col + col_inds2 = xs2 % col + + # bottom trapezoid + xs1 = arange_kw(0, trapezoid_size, dtype=torch.float64) + b = -0.5 - m_first_row + row_inds1 = torch.floor(-b - torch.sqrt(b * b - 2 * xs1)) + col_inds1 = torch.floor(xs1 - ((2 * m_first_row - 1 - row_inds1) * row_inds1) * 0.5) + row_inds1 = _maybe_convert_to_dtype(row_inds1, dtype) + col_inds1 = _maybe_convert_to_dtype(col_inds1, dtype) + + if col: + row_inds1 = row_inds1 + (rectangle_size // col) + col_inds1 = col_inds1 + col_offset + + return torch.stack( + (torch.cat((row_inds2, row_inds1)), torch.cat((col_inds2, col_inds1))) + ) + + +@register_decomposition(aten.bucketize) +@out_wrapper(exact_dtype=True) +def bucketize( + a: TensorOrNumberLikeType, + boundaries: TensorLikeType, + *, + out_int32: bool = False, + right: bool = False, +): + torch._check( + boundaries.dim() == 1, + lambda: f"boundaries tensor must be 1 dimension but got dim({boundaries.dim()})", + ) + + a = a if isinstance(a, torch.Tensor) else torch.tensor(a) + out_dtype = torch.int32 if out_int32 else torch.int64 + n_boundaries = boundaries.shape[-1] + if n_boundaries == 0: + return torch.zeros_like(a) + # We are trying to find the bucket (defined by pairs of consecutive elements of `boundaries`) + # each element of `a` belongs to. We use binary search to achieve logarithmic complexity, + # but each step of the search is done "in parallel" over all elements of `a` + # can't use int32 as indexes, so we have to do all computations with int64 and convert at the end + start = torch.zeros(a.shape, device=a.device, dtype=torch.int64) + end = start + n_boundaries + # Max depth of the binary search + # Since we can't break out of the loop at different points for different elements of a, + # we just do the max amount of iterations that binary search requires and add condition + # tensor (cond_update below) to stop updating once the search terminates + + # For first iteration through loop we can skip some checks, we have separate implementation + mid = start + (end - start) // 2 + mid_val = boundaries[mid] + if right: + cond_mid = mid_val > a + else: + cond_mid = mid_val >= a + start = torch.where(cond_mid, start, mid + 1) + + if n_boundaries > 1: + cond_update = torch.ones_like(a, dtype=torch.bool) + niters = int(math.log2(n_boundaries)) + for _ in range(niters): + end = torch.where(cond_mid & cond_update, mid, end) + cond_update = start < end + # start might end up pointing to 1 past the end, we guard against that + mid = torch.where(cond_update, start + (end - start) // 2, 0) + mid_val = boundaries[mid] + # If right is true, the buckets are closed on the *left* + # (i.e., we are doing the equivalent of std::upper_bound in C++) + # Otherwise they are closed on the right (std::lower_bound) + if right: + cond_mid = mid_val > a + else: + cond_mid = mid_val >= a + start = torch.where((~cond_mid) & cond_update, mid + 1, start) + + return start.to(dtype=out_dtype) + + +@register_decomposition(aten.cauchy) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def cauchy(self, median=0, sigma=1, generator=None): + if generator is not None: + raise AssertionError("generator is not supported in refs") + torch._check( + not utils.is_complex_dtype(self.dtype) + and not utils.is_integer_dtype(self.dtype) + and not utils.is_boolean_dtype(self.dtype), + lambda: f"Cauchy distribution is a continuous probability distribution. \ + dtype must be a floating point but you specified {self.dtype}", + ) + torch._check( + sigma > 0.0, + lambda: f"cauchy_ expects sigma > 0.0, but found sigma={sigma}", + ) + return median + sigma * torch.tan(math.pi * (torch.rand_like(self) - 0.5)) + + +@register_decomposition(aten.exponential) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def exponential(self, rate=1, generator=None): + if generator is not None: + raise AssertionError("generator is not supported in refs") + torch._check( + not utils.is_complex_dtype(self.dtype) + and not utils.is_integer_dtype(self.dtype) + and not utils.is_boolean_dtype(self.dtype), + lambda: f"Exponential distribution is a continuous probability distribution. \ + dtype must be a floating point but you specified {self.dtype}", + ) + torch._check( + rate > 0.0, + lambda: f"exponential_ expects lambda > 0.0, but found lambda={rate}", + ) + + uniform_val = torch.rand_like(self) + + # copying numerics of transformation::exponential see comment: + # curand_uniform has (0,1] bounds. log(1) is 0 and exponential excludes 0. + # we need log to be not 0, and not underflow when converted to half + # fast __logf approximation can underflow, so set log to -epsilon/2 for 1 or close to 1 args + epsilon = torch.finfo(uniform_val.dtype).eps / 2 + condition = uniform_val >= 1.0 - epsilon + log_uniform = torch.where(condition, -epsilon, torch.log(uniform_val)) + + return -1 / rate * log_uniform + + +@register_decomposition(aten.geometric) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def geometric(self, p, generator=None): + if generator is not None: + raise AssertionError("generator is not supported in refs") + # TODO: fix inductor rand_like for integer, bool dtypes + torch._check( + not utils.is_complex_dtype(self.dtype) + and not utils.is_boolean_dtype(self.dtype), + lambda: f"geometric not implemented for {self.dtype}", + ) + torch._check( + 0 < p and p < 1, + lambda: f"geometric_ expects p to be in (0, 1), but got p={p}", + ) + return torch.floor(torch.log1p(-torch.rand_like(self)) / math.log1p(-p)) + 1 + + +@register_decomposition(aten.log_normal) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def log_normal(self, mean=1, std=2, generator=None): + if generator is not None: + raise AssertionError("generator is not supported in refs") + torch._check( + not utils.is_complex_dtype(self.dtype) + and not utils.is_integer_dtype(self.dtype) + and not utils.is_boolean_dtype(self.dtype), + lambda: f"log_normal not implemented for {self.dtype}", + ) + torch._check( + 0 < std, + lambda: f"log_normal_ expects std > 0.0, but found std={std}", + ) + return torch.exp(std * torch.randn_like(self) + mean) + + +# NOTE: the device and dtype will be ignored when shape is None +@register_decomposition(aten.normal) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=( + "mean", + "std", + ), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def normal( + mean=0, + std=1, + size=None, + *, + generator=None, + dtype=None, + layout=None, + device=None, + pin_memory=None, +): + if layout is not None and layout != torch.strided: + raise AssertionError(f"layout must be None or torch.strided, got {layout}") + + if not isinstance(std, TensorLike): + torch._check( + std >= 0, lambda: f"normal expects std >= 0.0, but found std {std}" + ) + + if size is None: + tensors = tuple(t for t in (mean, std) if isinstance(t, TensorLike)) + torch._check( + len(tensors) > 0, + lambda: "normal expects that either mean or std is a tensor, or size is defined", + ) + torch._check( + layout is None and pin_memory is None, + lambda: "Cannot pass layout, or pin_memory without size", + ) + + size = _broadcast_shapes(*(t.shape for t in tensors)) + dtype = tensors[0].dtype + device = tensors[0].device + else: + torch._check( + not isinstance(mean, TensorLike) and not isinstance(std, TensorLike), + lambda: "normal expects mean and std to be scalars when size is defined", + ) + dtype = torch.get_default_dtype() if dtype is None else dtype + device = torch.device("cpu") if device is None else device + + normal_samples = prims.normal( + size, + mean=0.0, + std=1.0, + dtype=dtype, + device=device, + requires_grad=False, + generator=generator, + ) + return std * normal_samples + mean + + +@register_decomposition(aten.normal_) +def normal_(self, mean=0, std=1, *, generator=None): + return normal(mean, std, self.shape, out=self, generator=generator) + + +@register_decomposition(aten.normal_functional) +def normal_functional(self, mean=0, std=1, *, generator=None): + res = normal( + mean, + std, + self.shape, + dtype=self.dtype, + device=self.device, + generator=generator, + ) + if self.stride() == res.stride(): + return res + new_stride = utils.compute_elementwise_output_strides(self) + return res.as_strided(self.shape, new_stride) + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def rad2deg(self: TensorLikeType): + torch._check( + not utils.is_complex_dtype(self.dtype), + lambda: "rad2deg is not supported for complex tensors.", + ) + M_180_PI = 57.295779513082320876798154814105170332405472466564 + return self * M_180_PI + + +@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT) +def deg2rad(self: TensorLikeType): + torch._check( + not utils.is_complex_dtype(self.dtype), + lambda: "deg2rad is not supported for complex tensors.", + ) + M_PI_180 = 0.017453292519943295769236907684886127134428718885417 + return self * M_PI_180 + + +@register_decomposition(aten.count_nonzero) +@out_wrapper() +def count_nonzero(self, dim: DimsType | None = None): + return (self != 0).sum(dim) + + +def _dot_check(self, other): + torch._check( + self.dim() == 1 and other.dim() == 1, + lambda: f"1D tensors expected, but got {self.dim()}D and {other.dim()}D tensors", + ) + + torch._check( + self.dtype == other.dtype, + lambda: "dot : expected both vectors to have same dtype, but found " + f"{self.dtype} and {other.dtype}", + ) + + def numel_error(): + return ( + f"inconsistent tensor size, expected tensor [{self.numel()}] and src [{other.numel()}] to have the" + f"same number of elements, but got {self.numel()} and {other.numel()} elements respectively" + ) + + torch._check(self.numel() == other.numel(), numel_error) + + +def _dot_check_wrapper(fn): + @wraps(fn) + def wrapper(self, other): + _dot_check(self, other) + return fn(self, other) + + return wrapper + + +@register_decomposition(aten.dot) +@out_wrapper(exact_dtype=True) +@_dot_check_wrapper +@elementwise_type_promotion_wrapper( + type_promoting_args=("self", "other"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def dot(self, other): + if self.is_complex(): + if self.is_conj(): + if other.is_conj(): + return torch.dot(self.conj(), other.conj()).conj() + else: + return torch.vdot(self.conj(), other) + elif other.is_conj(): + return torch.vdot(other.conj(), self) + + return (self * other).sum() + + +@register_decomposition(aten.vdot) +@out_wrapper(exact_dtype=True) +@_dot_check_wrapper +@elementwise_type_promotion_wrapper( + type_promoting_args=("self", "other"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def vdot(self, other): + if not self.is_complex(): + return torch.dot(self, other) + + if self.is_conj(): + if other.is_conj(): + return torch.vdot(other.conj(), self.conj()) + else: + return torch.dot(self.conj(), other) + elif other.is_conj(): + return torch.dot(self, other.conj()).conj() + + # The decomposition fails if you do self.conj()... not sure why + return (self.conj_physical() * other).sum() + + +@register_decomposition(aten.select_scatter) +@out_wrapper() +def select_scatter(x: TensorLikeType, src: TensorLikeType, dim: int, index: int): + dim = utils.canonicalize_dim(x.ndim, dim) + mask_shape = [1] * x.ndim + mask_shape[dim] = -1 + if index < 0: + index = index + x.shape[dim] + mask = torch.arange(x.shape[dim], device=x.device).view(mask_shape) == index + src = torch.unsqueeze(src, dim).expand(x.shape) + return torch.where(mask, src, x) + + +# inplace +abs_ = _make_inplace(abs) +acos_ = _make_inplace(acos) +acosh_ = _make_inplace(acosh) +add_ = _make_inplace(add) +addcmul_ = _make_inplace(addcmul) +addcdiv_ = _make_inplace(addcdiv) +asin_ = _make_inplace(asin) +asinh_ = _make_inplace(asinh) +atan_ = _make_inplace(atan) +atanh_ = _make_inplace(atanh) +atan2_ = _make_inplace(atan2) +bitwise_and_ = _make_inplace(bitwise_and) +bitwise_left_shift_ = _make_inplace(bitwise_left_shift) +bitwise_not_ = _make_inplace(bitwise_not) +bitwise_or_ = _make_inplace(bitwise_or) +bitwise_right_shift_ = _make_inplace(bitwise_right_shift) +bitwise_xor_ = _make_inplace(bitwise_xor) +ceil_ = _make_inplace(ceil) +clamp_ = _make_inplace(clamp) +clamp_min_ = _make_inplace(clamp_min) +clamp_max_ = _make_inplace(clamp_max) +conj_physical_ = _make_inplace(conj_physical) +copysign_ = _make_inplace(copysign) +cos_ = _make_inplace(cos) +cosh_ = _make_inplace(cosh) +cumsum_ = _make_inplace(cumsum) +cumprod_ = _make_inplace(cumprod) +deg2rad_ = _make_inplace(deg2rad) +digamma_ = _make_inplace(digamma) +div_ = _make_inplace(div) +eq_ = _make_inplace(eq) +erf_ = _make_inplace(erf) +erfc_ = _make_inplace(erfc) +erfinv_ = _make_inplace(erfinv) +exp_ = _make_inplace(exp) +exp2_ = _make_inplace(exp2) +expm1_ = _make_inplace(expm1) +float_power_ = _make_inplace(float_power) +floor_ = _make_inplace(floor) +floor_divide_ = _make_inplace(floor_divide) +fmod_ = _make_inplace(fmod) +frac_ = _make_inplace(frac) +gcd_ = _make_inplace(gcd) +ge_ = _make_inplace(ge) +gt_ = _make_inplace(gt) +heaviside_ = _make_inplace(heaviside) +hypot_ = _make_inplace(hypot) +igamma_ = _make_inplace(igamma) +igammac_ = _make_inplace(igammac) +i0_ = _make_inplace(i0) +lcm_ = _make_inplace(lcm) +le_ = _make_inplace(le) +lerp_ = _make_inplace(lerp) +lgamma_ = _make_inplace(lgamma) +log10_ = _make_inplace(log10) +log1p_ = _make_inplace(log1p) +log2_ = _make_inplace(log2) +log_ = _make_inplace(log) +logical_and_ = _make_inplace(logical_and) +logical_not_ = _make_inplace(logical_not) +logical_or_ = _make_inplace(logical_or) +logical_xor_ = _make_inplace(logical_xor) +lt_ = _make_inplace(lt) +mul_ = _make_inplace(mul) +mvlgamma_ = _make_inplace(mvlgamma) +nan_to_num_ = _make_inplace(nan_to_num) +ne_ = _make_inplace(ne) +neg_ = _make_inplace(neg) +nextafter_ = _make_inplace(nextafter) +pow_ = _make_inplace(pow) +rad2deg_ = _make_inplace(rad2deg) +reciprocal_ = _make_inplace(reciprocal) +remainder_ = _make_inplace(remainder) +rsqrt_ = _make_inplace(rsqrt) +sgn_ = _make_inplace(sgn) +sigmoid_ = _make_inplace(sigmoid) +sign_ = _make_inplace(sign) +sin_ = _make_inplace(sin) +sinc_ = _make_inplace(sinc) +sinh_ = _make_inplace(sinh) +sqrt_ = _make_inplace(sqrt) +square_ = _make_inplace(square) +sub_ = _make_inplace(sub) +tan_ = _make_inplace(tan) +tanh_ = _make_inplace(tanh) +tril_ = _make_inplace(tril) +triu_ = _make_inplace(triu) +true_divide_ = _make_inplace(true_divide) +trunc_ = _make_inplace(trunc) +xlogy_ = _make_inplace(xlogy) +cauchy_ = _make_inplace(cauchy) +exponential_ = _make_inplace(exponential) +geometric_ = _make_inplace(geometric) +log_normal_ = _make_inplace(log_normal) +zero_ = _make_inplace(zero) + +alias_copy = _make_copy_from_view(aten.alias) +as_strided_copy = _make_copy_from_view(aten.as_strided) +diagonal_copy = _make_copy_from_view(aten.diagonal) +expand_copy = _make_copy_from_view(aten.expand) +# TODO: This must return a sparse tensor if the input is sparse, but refs have +# no sparse support. See narrow_copy_sparse in core. +narrow_copy = _make_copy_from_view(aten.narrow) +squeeze_copy = _make_copy_from_view(aten.squeeze) +permute_copy = _make_copy_from_view(aten.permute) +t_copy = _make_copy_from_view(aten.t) +transpose_copy = _make_copy_from_view(aten.transpose) +unbind_copy = _make_copy_from_view(aten.unbind, return_none_on_out_variant=True) +unsqueeze_copy = _make_copy_from_view(aten.unsqueeze) +view_copy = _make_copy_from_view(aten.view) + + +# xref: isStorage in torch/csrc/DynamicTypes.cpp +def _isStorage(obj): + return isinstance(obj, (torch.TypedStorage, torch.UntypedStorage)) + + +# xref: compute_sizes in torch/csrc/utils/tensor_new.cpp +def _compute_sizes(seq, scalar_type): + MAX_DIMS = 128 + is_storage = _isStorage(seq) + sizes = [] + # TODO: this is inaccurate, we actually test PySequence_Check + while isinstance(seq, (list, tuple)): + length = len(seq) + if is_storage: + length //= scalar_type.itemsize + sizes.append(length) + if len(sizes) > MAX_DIMS: + raise ValueError(f"too many dimensions '{type(seq).__name__}'") + if length == 0: + break + try: + handle = seq[0] + except Exception: + raise ValueError( # noqa: B904 + f"could not determine the shape of object type '{type(seq).__name__}'" + ) + seq = handle + + return sizes + + +# xref: infer_scalar_type in torch/csrc/utils/tensor_new.cpp +def _infer_scalar_type(obj): + if isinstance(obj, FloatLike): + return torch.get_default_dtype() + if isinstance(obj, IntLike) and not isinstance(obj, bool): # careful! + return torch.int64 + if isinstance(obj, BoolLike): + return torch.bool + if isinstance(obj, complex): + default_dtype = torch.get_default_dtype() + if default_dtype is torch.float: + return torch.cfloat + elif default_dtype is torch.double: + return torch.cdouble + elif default_dtype is torch.half: + return torch.chalf + else: + raise RuntimeError("invalid default scalar type for complex") + if isinstance(obj, torch.Tensor): + return obj.dtype + if isinstance(obj, str): + raise TypeError(f"new(): invalid data type '{type(obj).__name__}'") + # TODO: this is inaccurate, we actually test PySequence_Check + if isinstance(obj, (list, tuple)): + scalarType = None + length = len(obj) + # match NumPy semantics, except use default tensor type instead of + # double. + if length == 0: + return torch.get_default_dtype() + + for i in range(length): + cur_item = obj[i] + # TODO: test this + """ + if cur_item is obj: + raise TypeError("new(): self-referential lists are incompatible") + """ + item_scalarType = _infer_scalar_type(cur_item) # recurse! + if scalarType is not None: + scalarType = torch.promote_types(scalarType, item_scalarType) + else: + scalarType = item_scalarType + if scalarType is torch.cdouble: + # this won't change (unless we hit undefined, but that will + # fail later) + return scalarType + return scalarType + raise RuntimeError(f"Could not infer dtype of {type(obj).__name__}") + + +# Analogous to recursive_store +# xref: recursive_store in torch/csrc/utils/tensor_new.cpp +def _recursive_build( + scalarType: torch.dtype, obj: TensorOrNumberLikeType | TensorSequenceType +): + if isinstance(obj, Tensor) and obj.numel() == 1: + return obj.detach().to(dtype=scalarType, device="cpu", copy=True).view(()) + elif isinstance(obj, Tensor): + # It is invalid to call ".tensor([...])" with a non-scalar tensor in eager mode + # >>> torch.tensor([torch.randn(2)]) + # ValueError: only one element tensors can be converted to Python scalars + # + # But it is possible with a NumPy array + # >>> torch.tensor([np.random.uniform(size=(2,))]).shape + # torch.Size([1, 2]) + return obj.detach().to(dtype=scalarType, device="cpu", copy=True) + elif isinstance(obj, Number): + # pyrefly: ignore [bad-argument-type] + return torch.scalar_tensor(obj, dtype=scalarType) + + # seq can be a list of tensors + seq = obj + return ( + torch.empty(0) + if not seq + else torch.stack([_recursive_build(scalarType, item) for item in seq]) + ) + + +# xref: internal_new_from_data in torch/csrc/utils/tensor_new.cpp +def _internal_new_from_data( + options, + scalar_type, + device_opt, + data, + copy_variables, + copy_numpy, + type_inference, + pin_memory=False, +): + if isinstance(data, torch.Tensor): + torch._check( + not pin_memory, lambda: "Can't pin tensor constructed from a variable" + ) + var = data + if copy_variables: + var = var.detach() + inferred_scalar_type = var.dtype if type_inference else scalar_type + device = device_opt if device_opt is not None else var.device + return var.to( + device=device, + dtype=inferred_scalar_type, + non_blocking=False, + copy=copy_variables, + ) + + # TODO + if hasattr(data, "__cuda_array_interface__"): + return NotImplemented + + # TODO: test for numpy input with PyArray_Check + + device = device_opt if device_opt is not None else options["device"] + inferred_scalar_type = _infer_scalar_type(data) if type_inference else scalar_type + + # NB: Don't need to avoid tracing, as we aren't going to do any manual + # pointer filling tricks + if _isStorage(data): + return NotImplemented + else: + if torch.device(device).type == "meta": + return NotImplemented + + # In the C implementation, we would directly start poking the memory + # of a freshly allocated CPU tensor. Here, we're going to do an + # alternate, heinously slow implementation: turn each individual + # scalar into a tensor, and then repeatedly cat them together + tensor = _recursive_build(inferred_scalar_type, data) + + tensor = tensor.to(device, inferred_scalar_type, non_blocking=False, copy=False) + if pin_memory and torch.device(device).type == "cpu": + pinned_tensor = torch.empty_strided( + tensor.shape, + tensor.stride(), + dtype=tensor.dtype, + device=tensor.device, + pin_memory=True, + ) + pinned_tensor.copy_(tensor) + tensor = pinned_tensor + + # NB: lift_fresh is not needed, because we built the tensor from scalars + # guaranteeing a fresh tensor in this case + return tensor + + +# xref: tensor_ctor in torch/csrc/utils/tensor_new.cpp +def tensor(data, *, dtype=None, device=None, pin_memory=False, requires_grad=False): + # TODO (or not): support names kwarg + if isinstance(data, torch.Tensor): + warnings.warn( + "To copy construct from a tensor, it is recommended to use sourceTensor.detach().clone() " + "or sourceTensor.detach().clone().requires_grad_(True), rather than torch.tensor(sourceTensor)", + UserWarning, + stacklevel=2, + ) + type_inference = dtype is None + new_tensor = _internal_new_from_data( + # device="cpu" because that's what you get with torch.tensor(2) no + # device by default + {"device": "cpu"}, # TODO: use torch.get_default_tensor_type + dtype if dtype is not None else torch.get_default_dtype(), + device, + data, + copy_variables=True, + copy_numpy=True, + type_inference=type_inference, + pin_memory=pin_memory, + ) + new_tensor.detach_() + if requires_grad: + new_tensor.requires_grad_(requires_grad) + return new_tensor + + +# Views +# We can't model these as above, as the pattern of doing `op(a, out=a)` does not work for a view function +# given that it does not reshape the input (it just copies the result into it) + +# squeeze_ = _make_inplace(squeeze) +# t_ = _make_inplace(t) +# transpose_ = _make_inplace(transpose) +# unsqueeze_ = _make_inplace(unsqueeze) + + +import torch._refs._conversions +import torch._refs.fft +import torch._refs.linalg +import torch._refs.nn.functional +import torch._refs.special diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92f0a28a172b5fbfe33af3b256f0f92e9a0dad8a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/__init__.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f05f7ed160f08c287e35a2e8c8fe24961c96d0486ba01a6a201a79bdc6794560 +size 291303 diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/_conversions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/_conversions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21ebcb68563cb0d988288e057c1663aab1863312 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/_conversions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/fft.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/fft.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58175ef309fb3b1f849ace823d1a6eef5e496a21 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/fft.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/_conversions.py b/.venv/lib/python3.12/site-packages/torch/_refs/_conversions.py new file mode 100644 index 0000000000000000000000000000000000000000..8092469741981efce3c53f424e3b2fb83a38e8eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_refs/_conversions.py @@ -0,0 +1,119 @@ +# mypy: allow-untyped-defs +import torch +import torch._prims_common as utils + +# Utilities should come BEFORE this import +from torch._decomp import register_decomposition +from torch._prims_common import TensorLikeType +from torch._prims_common.wrappers import out_wrapper +from torch._refs import _broadcast_shapes + + +# Data conversion references. +# +# Note: this module breaks the usual _refs to torch naming scheme where +# _refs.foo.bar is a ref for torch.foo.bar. The following definitions are not +# part of _refs/__init__.py to avoid name clashes with Python builtin types +# (like int). + +__all__ = [ + # dtypes + "bfloat16", + "bool", + "byte", + "cdouble", + "cfloat", + "chalf", + "char", + "double", + "float", + "half", + "int", + "long", + "short", + # misc + "complex", + "polar", +] + + +def _make_conversion_method(name: str, dtype: torch.dtype): + def fn( + self: TensorLikeType, memory_format: torch.memory_format = torch.preserve_format + ) -> TensorLikeType: + return self.to(dtype, memory_format=memory_format) # type: ignore[call-overload] + + fn.__name__ = name + return fn + + +bfloat16 = _make_conversion_method("bfloat16", torch.bfloat16) + +bool = _make_conversion_method("bool", torch.bool) + +byte = _make_conversion_method("byte", torch.uint8) + +cdouble = _make_conversion_method("cdouble", torch.cdouble) + +cfloat = _make_conversion_method("cfloat", torch.cfloat) + +chalf = _make_conversion_method("chalf", torch.complex32) + +char = _make_conversion_method("char", torch.int8) + +double = _make_conversion_method("double", torch.double) + +float = _make_conversion_method("float", torch.float) + +half = _make_conversion_method("half", torch.half) + +int = _make_conversion_method("int", torch.int) + +long = _make_conversion_method("long", torch.long) + +short = _make_conversion_method("short", torch.short) + + +@register_decomposition(torch._ops.ops.aten.complex) +# Note: complex has type promotion tests disabled due to different semantics. +# exact_dtype is for compat with complex_check_dtype from core. +@out_wrapper(exact_dtype=True) +def complex(real: TensorLikeType, imag: TensorLikeType) -> TensorLikeType: + allowed_dtypes = (torch.float32, torch.float64, torch.float16) + torch._check( + real.dtype in allowed_dtypes and imag.dtype in allowed_dtypes, + lambda: ( + f"Expected both inputs to be Half, Float or Double tensors but got " + f"{real.dtype} and {imag.dtype}" + ), + ) + torch._check( + real.dtype == imag.dtype, + lambda: ( + f"Expected object of scalar type {real.dtype} but got " + f"scalar type {imag.dtype} for second argument" + ), + ) + result_dtype = utils.corresponding_complex_dtype(real.dtype) # type: ignore[arg-type] + common_shape = _broadcast_shapes(real.shape, imag.shape) + result = real.new_empty( + common_shape, + dtype=result_dtype, + layout=real.layout, + device=real.device, + # pin_memory=real.is_pinned(), # NYI + ) + result.real = real + result.imag = imag + return result + + +@register_decomposition(torch._ops.ops.aten.polar) +# Note: polar has type promotion tests disabled due to different semantics. +# exact_dtype is for compat with complex_check_dtype from core. +@out_wrapper(exact_dtype=True) +def polar(abs: TensorLikeType, angle: TensorLikeType) -> TensorLikeType: + result = torch.complex(abs, angle) + result.real = abs * torch.cos(angle) + result.imag = abs * torch.sin(angle) + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/fft.py b/.venv/lib/python3.12/site-packages/torch/_refs/fft.py new file mode 100644 index 0000000000000000000000000000000000000000..16565ad3b5bdaa91fdba1b5bd33ade60f4e6a3d2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_refs/fft.py @@ -0,0 +1,608 @@ +import math +from collections.abc import Iterable, Sequence +from typing import Literal, NamedTuple + +import torch +import torch._prims as prims +import torch._prims_common as utils +from torch._decomp import register_decomposition +from torch._prims_common import DimsType, ShapeType, TensorLikeType +from torch._prims_common.wrappers import _maybe_convert_to_dtype, out_wrapper + + +__all__ = [ + # Transforms + "fft", + "fft2", + "fftn", + "hfft", + "hfft2", + "hfftn", + "rfft", + "rfft2", + "rfftn", + "ifft", + "ifft2", + "ifftn", + "ihfft", + "ihfft2", + "ihfftn", + "irfft", + "irfft2", + "irfftn", + # Helpers + "fftshift", + "ifftshift", +] + +NormType = None | Literal["forward", "backward", "ortho"] +_NORM_VALUES = {None, "forward", "backward", "ortho"} +aten = torch._ops.ops.aten + + +def _apply_norm( + x: TensorLikeType, norm: NormType, signal_numel: int, forward: bool +) -> TensorLikeType: + """Apply normalization to the un-normalized FFT result""" + torch._check(norm in _NORM_VALUES, lambda: f"Invalid normalization mode: {norm}") + + if norm == "ortho": + return x * (1 / math.sqrt(signal_numel)) + + normalize = (not forward and (norm is None or norm == "backward")) or ( + forward and norm == "forward" + ) + return x * (1 / signal_numel) if normalize else x + + +def _promote_type_fft( + dtype: torch.dtype, require_complex: bool, device: torch.device +) -> torch.dtype: + """Helper to promote a dtype to one supported by the FFT primitives""" + if dtype.is_complex: + return dtype + + # Promote integral to default float type + if not dtype.is_floating_point: + dtype = torch.get_default_dtype() + + allowed_types = [torch.float32, torch.float64] + maybe_support_half = device.type in ["cuda", "meta", "xpu"] + + if maybe_support_half: + allowed_types.append(torch.float16) + # bfloat16 is supported for FFT on CUDA/XPU devices, but there is no + # corresponding "complex bfloat16" dtype (corresponding_complex_dtype + # maps it to complex64). Promote bfloat16 -> float32 here so that: + # * the decomposition output dtype (complex64) matches aten, and + # * a real dtype conversion happens, so the result never aliases the + # input. Otherwise, for size-1 inputs the prim would return a view + # while aten returns a fresh tensor, breaking view-consistency + # (test_python_ref__refs_fft_*_cuda_bfloat16). + if dtype == torch.bfloat16: + dtype = torch.float32 + torch._check_not_implemented( + dtype in allowed_types, lambda: f"Unsupported dtype {dtype}" + ) + + if require_complex: + dtype = utils.corresponding_complex_dtype(dtype) + + return dtype + + +def _maybe_promote_tensor_fft( + t: TensorLikeType, require_complex: bool = False +) -> TensorLikeType: + """Helper to promote a tensor to a dtype supported by the FFT primitives""" + cur_type = t.dtype + new_type = _promote_type_fft(cur_type, require_complex, t.device) + return _maybe_convert_to_dtype(t, new_type) # type: ignore[return-value] + + +def _resize_fft_input( + x: TensorLikeType, dims: tuple[int, ...], sizes: tuple[int, ...] +) -> TensorLikeType: + """ + Fixes the shape of x such that x.size(dims[i]) == sizes[i], + either by zero-padding, or by slicing x starting from 0. + """ + if len(dims) != len(sizes): + raise AssertionError( + f"dims and sizes must have the same length, got {len(dims)} and {len(sizes)}" + ) + must_copy = False + x_sizes = x.shape + pad_amount = [0] * len(x_sizes) * 2 + for i in range(len(dims)): + if sizes[i] == -1: + continue + + if x_sizes[dims[i]] < sizes[i]: + must_copy = True + pad_idx = len(pad_amount) - 2 * dims[i] - 1 + + pad_amount[pad_idx] = sizes[i] - x_sizes[dims[i]] + + if x_sizes[dims[i]] > sizes[i]: + x = x.narrow(dims[i], 0, sizes[i]) + + return torch.constant_pad_nd(x, pad_amount) if must_copy else x + + +def _fft_c2r( + func_name: str, + input: TensorLikeType, + n: int | None, + dim: int, + norm: NormType, + forward: bool, +) -> TensorLikeType: + """Common code for performing any complex to real FFT (irfft or hfft)""" + input = _maybe_promote_tensor_fft(input, require_complex=True) + dims = (utils.canonicalize_dim(input.ndim, dim, wrap_scalar=False),) + last_dim_size = n if n is not None else 2 * (input.shape[dim] - 1) + torch._check( + last_dim_size >= 1, + lambda: f"Invalid number of data points ({last_dim_size}) specified", + ) + + if n is not None: + input = _resize_fft_input(input, dims=dims, sizes=(last_dim_size // 2 + 1,)) + + if forward: + input = torch.conj(input) + + output = prims.fft_c2r(input, dim=dims, last_dim_size=last_dim_size) + return _apply_norm(output, norm=norm, signal_numel=last_dim_size, forward=forward) + + +def _fft_r2c( + func_name: str, + input: TensorLikeType, + n: int | None, + dim: int, + norm: NormType, + forward: bool, + onesided: bool, +) -> TensorLikeType: + """Common code for performing any real to complex FFT (rfft or ihfft)""" + torch._check_type( + not input.dtype.is_complex, + lambda: f"{func_name} expects a floating point input tensor, but got {input.dtype}", + ) + input = _maybe_promote_tensor_fft(input) + dims = (utils.canonicalize_dim(input.ndim, dim, wrap_scalar=False),) + dim_size = n if n is not None else input.shape[dim] + torch._check( + dim_size >= 1, lambda: f"Invalid number of data points ({dim_size}) specified" + ) + + if n is not None: + input = _resize_fft_input(input, dims, (n,)) + + ret = prims.fft_r2c(input, dim=dims, onesided=onesided) + ret = _apply_norm(ret, norm, dim_size, forward) + return ret if forward else torch.conj(ret) + + +def _fft_c2c( + func_name: str, + input: TensorLikeType, + n: int | None, + dim: int, + norm: NormType, + forward: bool, +) -> TensorLikeType: + """Common code for performing any complex to complex FFT (fft or ifft)""" + torch._check( + input.dtype.is_complex, + lambda: f"{func_name} expects a complex input tensor, but got {input.dtype}", + ) + dims = (utils.canonicalize_dim(input.ndim, dim, wrap_scalar=False),) + dim_size = n if n is not None else input.shape[dim] + torch._check( + dim_size >= 1, lambda: f"Invalid number of data points ({dim_size}) specified" + ) + + if n is not None: + input = _resize_fft_input(input, dims, (n,)) + + ret = prims.fft_c2c(input, dim=dims, forward=forward) + return _apply_norm(ret, norm, dim_size, forward) + + +@register_decomposition(aten.fft_fft) +@out_wrapper() +def fft( + input: TensorLikeType, + n: int | None = None, + dim: int = -1, + norm: NormType = None, +) -> TensorLikeType: + if input.dtype.is_complex: + return _fft_c2c("fft", input, n, dim, norm, forward=True) + else: + return _fft_r2c("fft", input, n, dim, norm, forward=True, onesided=False) + + +@register_decomposition(aten.fft_ifft) +@out_wrapper() +def ifft( + input: TensorLikeType, + n: int | None = None, + dim: int = -1, + norm: NormType = None, +) -> TensorLikeType: + if input.dtype.is_complex: + return _fft_c2c("ifft", input, n, dim, norm, forward=False) + else: + return _fft_r2c("ifft", input, n, dim, norm, forward=False, onesided=False) + + +@register_decomposition(aten.fft_rfft) +@out_wrapper() +def rfft( + input: TensorLikeType, + n: int | None = None, + dim: int = -1, + norm: NormType = None, +) -> TensorLikeType: + return _fft_r2c("rfft", input, n, dim, norm, forward=True, onesided=True) + + +@register_decomposition(aten.fft_irfft) +@out_wrapper() +def irfft( + input: TensorLikeType, + n: int | None = None, + dim: int = -1, + norm: NormType = None, +) -> TensorLikeType: + return _fft_c2r("irfft", input, n, dim, norm, forward=False) + + +@register_decomposition(aten.fft_hfft) +@out_wrapper() +def hfft( + input: TensorLikeType, + n: int | None = None, + dim: int = -1, + norm: NormType = None, +) -> TensorLikeType: + return _fft_c2r("hfft", input, n, dim, norm, forward=True) + + +@register_decomposition(aten.fft_ihfft) +@out_wrapper() +def ihfft( + input: TensorLikeType, + n: int | None = None, + dim: int = -1, + norm: NormType = None, +) -> TensorLikeType: + return _fft_r2c("ihfft", input, n, dim, norm, forward=False, onesided=True) + + +class _ShapeAndDims(NamedTuple): + shape: tuple[int, ...] + dims: tuple[int, ...] + + +def _canonicalize_fft_shape_and_dim_args( + input: TensorLikeType, shape: ShapeType | None, dim: DimsType | None +) -> _ShapeAndDims: + """Convert the shape and dim arguments into a canonical form where neither are optional""" + input_dim = input.ndim + input_sizes = input.shape + + if dim is not None: + if not isinstance(dim, Sequence): + dim = (dim,) + ret_dims = utils.canonicalize_dims(input_dim, dim, wrap_scalar=False) + + # Check dims are unique + torch._check( + len(set(ret_dims)) == len(ret_dims), lambda: "FFT dims must be unique" + ) + + if shape is not None: + if not isinstance(shape, Sequence): + shape = (shape,) + + # Has shape, might have dim + torch._check( + dim is None or len(dim) == len(shape), + lambda: "When given, dim and shape arguments must have the same length", + ) + transform_ndim = len(shape) + + torch._check( + transform_ndim <= input_dim, + lambda: f"Got shape with {transform_ndim} values but input tensor " + f"only has {input_dim} dimensions.", + ) + + # If shape is given, dims defaults to the last len(shape) dimensions + if dim is None: + ret_dims = tuple(range(input_dim - transform_ndim, input_dim)) + + # Translate any -1 values in shape to the default length + ret_shape = tuple( + s if s != -1 else input_sizes[d] + for (s, d) in zip(shape, ret_dims) # type: ignore[possibly-undefined] + ) + elif dim is None: + # No shape, no dim + ret_dims = tuple(range(input_dim)) + ret_shape = tuple(input_sizes) + else: + # No shape, has dim + ret_shape = tuple(input_sizes[d] for d in ret_dims) # type: ignore[possibly-undefined] + + for n in ret_shape: + torch._check(n > 0, lambda: f"Invalid number of data points ({n}) specified") + + return _ShapeAndDims(shape=ret_shape, dims=ret_dims) # type: ignore[possibly-undefined] + + +def _prod(xs: Iterable[int]) -> int: + """Compute product of a list""" + prod = 1 + for x in xs: + prod *= x + return prod + + +def _fftn_c2c( + function_name: str, + input: TensorLikeType, + shape: tuple[int, ...], + dim: tuple[int, ...], + norm: NormType, + forward: bool, +) -> TensorLikeType: + """Common code for n-dimensional complex to complex FFTs (fftn or ifftn)""" + torch._check( + input.dtype.is_complex, + lambda: f"{function_name} expects a complex input tensor, " + f"but got {input.dtype}", + ) + x = _resize_fft_input(input, dim, shape) + output = prims.fft_c2c(x, dim=dim, forward=forward) + return _apply_norm(output, norm=norm, signal_numel=_prod(shape), forward=forward) + + +@register_decomposition(aten.fft_fftn) +@out_wrapper() +def fftn( + input: TensorLikeType, + s: ShapeType | None = None, + dim: DimsType | None = None, + norm: NormType = None, +) -> TensorLikeType: + (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim) + x = _maybe_promote_tensor_fft(input, require_complex=True) + return _fftn_c2c("fftn", x, shape, dim, norm, forward=True) + + +@register_decomposition(aten.fft_ifftn) +@out_wrapper() +def ifftn( + input: TensorLikeType, + s: ShapeType | None = None, + dim: DimsType | None = None, + norm: NormType = None, +) -> TensorLikeType: + (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim) + x = _maybe_promote_tensor_fft(input, require_complex=True) + return _fftn_c2c("ifftn", x, shape, dim, norm, forward=False) + + +@register_decomposition(aten.fft_rfftn) +@out_wrapper() +def rfftn( + input: TensorLikeType, + s: ShapeType | None = None, + dim: DimsType | None = None, + norm: NormType = None, +) -> TensorLikeType: + torch._check_type( + not input.dtype.is_complex, + lambda: f"rfftn expects a real-valued input tensor, but got {input.dtype}", + ) + shape, dim = _canonicalize_fft_shape_and_dim_args(input, s, dim) + input = _maybe_promote_tensor_fft(input, require_complex=False) + input = _resize_fft_input(input, dim, shape) + out = prims.fft_r2c(input, dim=dim, onesided=True) + return _apply_norm(out, norm=norm, signal_numel=_prod(shape), forward=True) + + +@register_decomposition(aten.fft_ihfftn) +@out_wrapper() +def ihfftn( + input: TensorLikeType, + s: ShapeType | None = None, + dim: DimsType | None = None, + norm: NormType = None, +) -> TensorLikeType: + torch._check_type( + not input.dtype.is_complex, + lambda: f"ihfftn expects a real-valued input tensor, but got {input.dtype}", + ) + shape, dim = _canonicalize_fft_shape_and_dim_args(input, s, dim) + torch._check(len(shape) > 0, lambda: "ihfftn must transform at least one axis") + input = _maybe_promote_tensor_fft(input, require_complex=False) + input = _resize_fft_input(input, dim, shape) + + tmp = prims.fft_r2c(input, dim=dim[-1:], onesided=True) + + if len(dim) == 1: + tmp = _apply_norm(tmp, norm=norm, signal_numel=shape[0], forward=False) + return prims.conj(tmp) + + tmp = prims.conj_physical(tmp) + tmp = prims.fft_c2c(tmp, dim=dim[:-1], forward=False) + return _apply_norm(tmp, norm=norm, signal_numel=_prod(shape), forward=False) + + +class _CanonicalizeC2rReturn(NamedTuple): + shape: tuple[int, ...] + dim: tuple[int, ...] + last_dim_size: int + + +def _canonicalize_fft_c2r_shape_and_dim_args( + fname: str, + input: TensorLikeType, + s: ShapeType | None, + dim: DimsType | None, +) -> _CanonicalizeC2rReturn: + """Canonicalize shape and dim arguments for n-dimensional c2r transforms, + as well as calculating the last_dim_size which is shape[dim[-1]] for the output""" + (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim) + torch._check(len(shape) > 0, lambda: f"{fname} must transform at least one axis") + + if s is None or s[-1] == -1: + last_dim_size = 2 * (input.shape[dim[-1]] - 1) + else: + last_dim_size = shape[-1] + + torch._check( + last_dim_size >= 1, + lambda: f"Invalid number of data points ({last_dim_size}) specified", + ) + + shape_list = list(shape) + shape_list[-1] = last_dim_size // 2 + 1 + return _CanonicalizeC2rReturn( + shape=tuple(shape_list), dim=dim, last_dim_size=last_dim_size + ) + + +@register_decomposition(aten.fft_irfftn) +@out_wrapper() +def irfftn( + input: TensorLikeType, + s: ShapeType | None = None, + dim: DimsType | None = None, + norm: NormType = None, +) -> TensorLikeType: + shape, dim, last_dim_size = _canonicalize_fft_c2r_shape_and_dim_args( + "irfftn", input, s, dim + ) + input = _maybe_promote_tensor_fft(input, require_complex=True) + input = _resize_fft_input(input, dim, shape) + out = prims.fft_c2r(input, dim=dim, last_dim_size=last_dim_size) + return _apply_norm(out, norm, _prod(out.shape[d] for d in dim), forward=False) + + +@register_decomposition(aten.fft_hfftn) +@out_wrapper() +def hfftn( + input: TensorLikeType, + s: ShapeType | None = None, + dim: DimsType | None = None, + norm: NormType = None, +) -> TensorLikeType: + shape, dim, last_dim_size = _canonicalize_fft_c2r_shape_and_dim_args( + "hfftn", input, s, dim + ) + input = _maybe_promote_tensor_fft(input, require_complex=True) + input = _resize_fft_input(input, dim, shape) + + tmp = prims.fft_c2c(input, dim=dim[:-1], forward=True) if len(dim) > 1 else input + tmp = _apply_norm(tmp, norm, _prod(shape[:-1]), forward=True) + tmp = prims.conj_physical(tmp) + out = prims.fft_c2r(tmp, dim=dim[-1:], last_dim_size=last_dim_size) + return _apply_norm(out, norm, last_dim_size, forward=True) + + +@register_decomposition(aten.fft_fft2) +@out_wrapper() +def fft2( + input: TensorLikeType, + s: ShapeType | None = None, + dim: DimsType | None = (-2, -1), + norm: NormType = None, +) -> TensorLikeType: + return torch.fft.fftn(input, s=s, dim=dim, norm=norm) + + +@register_decomposition(aten.fft_ifft2) +@out_wrapper() +def ifft2( + input: TensorLikeType, + s: ShapeType | None = None, + dim: DimsType | None = (-2, -1), + norm: NormType = None, +) -> TensorLikeType: + return torch.fft.ifftn(input, s=s, dim=dim, norm=norm) + + +@register_decomposition(aten.fft_rfft2) +@out_wrapper() +def rfft2( + input: TensorLikeType, + s: ShapeType | None = None, + dim: DimsType | None = (-2, -1), + norm: NormType = None, +) -> TensorLikeType: + return torch.fft.rfftn(input, s=s, dim=dim, norm=norm) + + +@register_decomposition(aten.fft_irfft2) +@out_wrapper() +def irfft2( + input: TensorLikeType, + s: ShapeType | None = None, + dim: DimsType | None = (-2, -1), + norm: NormType = None, +) -> TensorLikeType: + return torch.fft.irfftn(input, s=s, dim=dim, norm=norm) + + +@register_decomposition(aten.fft_hfft2) +@out_wrapper() +def hfft2( + input: TensorLikeType, + s: ShapeType | None = None, + dim: DimsType | None = (-2, -1), + norm: NormType = None, +) -> TensorLikeType: + return torch.fft.hfftn(input, s=s, dim=dim, norm=norm) + + +@register_decomposition(aten.fft_ihfft2) +@out_wrapper() +def ihfft2( + input: TensorLikeType, + s: ShapeType | None = None, + dim: DimsType | None = (-2, -1), + norm: NormType = None, +) -> TensorLikeType: + return torch.fft.ihfftn(input, s=s, dim=dim, norm=norm) + + +def _default_alldims(dim: DimsType | None, x: TensorLikeType) -> list[int]: + """Convert Optional[DimsType] to a simple list, defaulting to all dimensions""" + if dim is None: + return list(range(x.ndim)) + elif not isinstance(dim, Sequence): + return [dim] + else: + return list(dim) + + +@register_decomposition(aten.fft_fftshift) +def fftshift(input: TensorLikeType, dim: DimsType | None = None) -> TensorLikeType: + dims = _default_alldims(dim, input) + shift = [input.shape[d] // 2 for d in dims] + return torch.roll(input, shift, dims) + + +@register_decomposition(aten.fft_ifftshift) +def ifftshift(input: TensorLikeType, dim: DimsType | None = None) -> TensorLikeType: + dims = _default_alldims(dim, input) + shift = [(input.shape[d] + 1) // 2 for d in dims] + return torch.roll(input, shift, dims) diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/linalg/__init__.py b/.venv/lib/python3.12/site-packages/torch/_refs/linalg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..acfe332cea5e702d3d1c2b613901d1162be2e698 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_refs/linalg/__init__.py @@ -0,0 +1,365 @@ +# mypy: allow-untyped-defs +import math +from functools import partial +from typing import Optional, Union + +import torch +import torch._prims as prims +import torch._prims_common as utils +import torch._refs as refs +import torch._refs.linalg as linalg +from torch import Tensor +from torch._prims_common import ( + check_fp_or_complex, + check_is_matrix, + Dim, + DimsType, + ELEMENTWISE_TYPE_PROMOTION_KIND, + IntLike, + TensorLikeType, +) +from torch._prims_common.wrappers import ( + _maybe_convert_to_dtype, + elementwise_type_promotion_wrapper, + out_wrapper, +) + + +__all__ = [ + "diagonal", + "matrix_norm", + "norm", + "svd", + "svdvals", + "vector_norm", + "vecdot", + "cross", +] + + +def _check_norm_dtype(dtype: torch.dtype | None, x_dtype: torch.dtype, fn_name: str): + """ + Checks related to the dtype kwarg in `linalg.*norm` functions + """ + if dtype is not None: + torch._check( + utils.is_float_dtype(dtype) or utils.is_complex_dtype(dtype), + lambda: f"{fn_name}: dtype should be floating point or complex. Got {dtype}", + ) + torch._check( + utils.is_complex_dtype(dtype) == utils.is_complex_dtype(x_dtype), + lambda: "{fn_name}: dtype should be {d} for {d} inputs. Got {dtype}".format( + fn_name=fn_name, + d="complex" if utils.is_complex_dtype(x_dtype) else "real", + dtype=dtype, + ), + ) + torch._check( + utils.get_higher_dtype(dtype, x_dtype) == dtype, + lambda: f"{fn_name}: the dtype of the input ({x_dtype}) should be convertible " + f"without narrowing to the specified dtype ({dtype})", + ) + + +import operator + +# Utilities should come BEFORE this import +from torch._decomp import register_decomposition +from torch._decomp.decompositions import pw_cast_for_opmath + + +@register_decomposition(torch._ops.ops.aten.linalg_cross) +@out_wrapper() +@pw_cast_for_opmath +def cross(a: Tensor, b: Tensor, dim: int = -1): + torch._check( + a.ndim == b.ndim, + lambda: "linalg.cross: inputs must have the same number of dimensions.", + ) + torch._check( + a.size(dim) == 3 and b.size(dim) == 3, + lambda: f"linalg.cross: inputs dim {dim} must have length 3, got {a.size(dim)} and {b.size(dim)}", + ) + a, b = torch.broadcast_tensors(a, b) + dim = utils.canonicalize_dim(a.ndim, dim) + idx = torch.arange(3, device=a.device) + return a.index_select(dim, (idx + 1) % 3) * b.index_select( + dim, (idx + 2) % 3 + ) - a.index_select(dim, (idx + 2) % 3) * b.index_select(dim, (idx + 1) % 3) + + +def diagonal( + input: TensorLikeType, + *, + offset: int = 0, + dim1: int = -2, + dim2: int = -1, +) -> TensorLikeType: + return torch.diagonal(input, offset=offset, dim1=dim1, dim2=dim2) + + +def _check_vector_norm_args( + x: TensorLikeType, ord: float | int = 2, dim: DimsType | None = None +): + from torch.fx.experimental.symbolic_shapes import sym_or + + if not (ord < 0.0 or ord == float("inf")): + return + + torch._check( + sym_or( + x.numel() != 0, + not isinstance(dim, IntLike) and dim is not None and len(dim) != 0, + ), + lambda: f"linalg.vector_norm cannot compute the {ord} norm on an empty tensor " + "because the operation does not have an identity", + ) + + shape = x.shape + if dim is not None and not isinstance(dim, IntLike): + for d in dim: + torch._check( + sym_or(x.numel() != 0, d < len(shape) and d >= 0 and shape[d] != 0), + lambda: f"linalg.vector_norm cannot compute the {ord} norm on the " + f"dimension {d} because this dimension is empty and the " + "operation does not have an identity", + ) + + +@register_decomposition(torch._ops.ops.aten.linalg_vector_norm) +@out_wrapper(exact_dtype=True) +def vector_norm( + x: TensorLikeType, + ord: float | int = 2, + dim: DimsType | None = None, + keepdim: bool = False, + *, + dtype: torch.dtype | None = None, +) -> Tensor: + from torch.fx.experimental.symbolic_shapes import guard_or_false + + check_fp_or_complex(x.dtype, "linalg.vector_norm") + + if isinstance(dim, Dim): + dim = [dim] # type: ignore[assignment] + + _check_vector_norm_args(x, ord, dim) + + _check_norm_dtype(dtype, x.dtype, "linalg.vector_norm") + + computation_dtype, result_dtype = utils.reduction_dtypes( + x, utils.REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT, dtype + ) + + to_result_dtype = partial(_maybe_convert_to_dtype, dtype=result_dtype) + + # Implementation + if ord == 0.0: + return torch.sum(torch.ne(x, 0.0), dim=dim, keepdim=keepdim, dtype=result_dtype) + elif ord == float("inf"): + return to_result_dtype(torch.amax(torch.abs(x), dim=dim, keepdim=keepdim)) # type: ignore[return-value,arg-type] + elif ord == float("-inf"): + return to_result_dtype(torch.amin(torch.abs(x), dim=dim, keepdim=keepdim)) # type: ignore[return-value,arg-type] + else: + # From here on the computation dtype is important as the reduction is non-trivial + x = _maybe_convert_to_dtype(x, computation_dtype) # type: ignore[assignment] + is_ord_even = ord % 2 == 0 if isinstance(ord, IntLike) else ord % 2.0 == 0.0 + if dim is not None and not isinstance(dim, IntLike) and len(dim) == 0: + dim = None + elif dim is not None: + dim = utils.canonicalize_dims(x.ndim, dim) + + reduce_sum = partial(torch.sum, dim=dim, keepdim=keepdim) + + if (dim is None and guard_or_false(x.numel() == 1)) or ( + dim is not None + and (x.ndim > 0 and all(guard_or_false(x.shape[d] == 1) for d in dim)) + ): + if x.ndim > 64: + raise RuntimeError( + f"Received a tensor with {x.ndim} dimensions, but only tensors with up to 64 dims are supported!" + ) + x = torch.abs(x) + if keepdim or x.ndim == 0: + return to_result_dtype(x).contiguous() + elif dim is None: + return to_result_dtype(x).flatten()[0] + else: + new_shape = [s for d, s in enumerate(x.shape) if d not in dim] + return to_result_dtype(x.view(new_shape)).contiguous() + + if not (is_ord_even and utils.is_float_dtype(x.dtype)): + x = torch.abs(x) + return to_result_dtype(torch.pow(reduce_sum(torch.pow(x, ord)), 1.0 / ord)) # type: ignore[return-value] + + +def _backshift_permutation(dim0, dim1, ndim): + # Auxiliary function for matrix_norm + # Computes the permutation that moves the two given dimensions to the back + ret = [i for i in range(ndim) if i != dim0 and i != dim1] + ret.extend((dim0, dim1)) + return ret + + +def _inverse_permutation(perm): + # Given a permutation, returns its inverse. It's equivalent to argsort on an array + return [i for i, j in sorted(enumerate(perm), key=operator.itemgetter(1))] + + +# CompositeImplicitAutograd +@out_wrapper(exact_dtype=True) +def matrix_norm( + A: TensorLikeType, + ord: float | str = "fro", + dim: DimsType = (-2, -1), + keepdim: bool = False, + *, + dtype: torch.dtype | None = None, +) -> TensorLikeType: + # shape + check_is_matrix(A, "linalg.matrix_norm") + # dim + + dim = utils.canonicalize_dims(A.ndim, dim) + if isinstance(dim, Dim): + dim = (dim,) # type: ignore[assignment] + torch._check( + len(dim) == 2, lambda: f"linalg.matrix_norm: dim must be a 2-tuple. Got {dim}" + ) + torch._check( + # pyrefly: ignore [bad-index] + dim[0] != dim[1], + # pyrefly: ignore [bad-index, index-error] + # pyrefly: ignore [bad-index, index-error] + lambda: f"linalg.matrix_norm: dims must be different. Got ({dim[0]}, {dim[1]})", + ) + # dtype arg + _check_norm_dtype(dtype, A.dtype, "linalg.matrix_norm") + + if isinstance(ord, str): + # ord + torch._check( + ord in ("fro", "nuc"), + lambda: f"linalg.matrix_norm: Order {ord} not supported.", + ) + # dtype + check_fp_or_complex( + A.dtype, "linalg.matrix_norm", allow_low_precision_dtypes=ord != "nuc" + ) + + if ord == "fro": + return vector_norm(A, 2, dim, keepdim, dtype=dtype) + else: # ord == "nuc" + if dtype is not None: + A = _maybe_convert_to_dtype(A, dtype) # type: ignore[assignment] + # pyrefly: ignore [bad-index, index-error] + perm = _backshift_permutation(dim[0], dim[1], A.ndim) + result = torch.sum(svdvals(prims.transpose(A, perm)), -1, keepdim) + if keepdim: + inv_perm = _inverse_permutation(perm) + result = prims.transpose(torch.unsqueeze(result, -1), inv_perm) + return result + else: + # ord + abs_ord = abs(ord) + torch._check( + abs_ord in (2, 1, float("inf")), + lambda: f"linalg.matrix_norm: Order {ord} not supported.", + ) + # dtype + check_fp_or_complex( + A.dtype, "linalg.matrix_norm", allow_low_precision_dtypes=ord != 2 + ) + + max_min = partial(torch.amax if ord > 0.0 else torch.amin, keepdim=keepdim) + + def _max_min_wrapper(A, dim): + # pyrefly: ignore [unsupported-operation] + if A.size(dim) == 0 and ord > 0.0: + new_size = list(A.size()) + if keepdim: + new_size[dim] = 1 + else: + del new_size[dim] + return torch.zeros(new_size, dtype=A.dtype, device=A.device) + else: + return max_min(A, dim) + + if abs_ord == 2.0: + if dtype is not None: + A = _maybe_convert_to_dtype(A, dtype) # type: ignore[assignment] + # pyrefly: ignore [bad-index, index-error] + perm = _backshift_permutation(dim[0], dim[1], A.ndim) + result = _max_min_wrapper(svdvals(prims.transpose(A, perm)), dim=-1) + if keepdim: + inv_perm = _inverse_permutation(perm) + result = prims.transpose(torch.unsqueeze(result, -1), inv_perm) + return result + else: # 1, -1, inf, -inf + # pyrefly: ignore [bad-unpacking] + dim0, dim1 = dim + if abs_ord == float("inf"): + dim0, dim1 = dim1, dim0 + if not keepdim and (dim0 < dim1): + dim1 -= 1 + return _max_min_wrapper( + vector_norm(A, 1.0, dim=dim0, keepdim=keepdim, dtype=dtype), dim1 + ) + + +# CompositeImplicitAutograd +@out_wrapper(exact_dtype=True) +def norm( + A: TensorLikeType, + ord: float | str | None = None, + dim: DimsType | None = None, + keepdim: bool = False, + *, + dtype: torch.dtype | None = None, +) -> TensorLikeType: + if dim is not None: + if isinstance(dim, Dim): + dim = (dim,) # type: ignore[assignment] + torch._check( + len(dim) in (1, 2), + lambda: f"linalg.norm: If dim is specified, it must be of length 1 or 2. Got {dim}", + ) + elif ord is not None: + torch._check( + A.ndim in (1, 2), + lambda: f"linalg.norm: If dim is not specified but ord is, the input must be 1D or 2D. Got {A.ndim}D", + ) + + if ord is not None and ( + (dim is not None and len(dim) == 2) or (dim is None and A.ndim == 2) + ): + if dim is None: + dim = (0, 1) + return matrix_norm(A, ord, dim, keepdim, dtype=dtype) + else: + if ord is None: + ord = 2.0 + return vector_norm(A, ord, dim, keepdim, dtype=dtype) # type: ignore[arg-type] + + +# CompositeImplicitAutograd +@out_wrapper("U", "S", "Vh", exact_dtype=True) +def svd(A: TensorLikeType, full_matrices: bool = True) -> tuple[Tensor, Tensor, Tensor]: + return prims.svd(A, full_matrices=full_matrices) + + +# CompositeImplicitAutograd +@out_wrapper(exact_dtype=True) +def svdvals(A: TensorLikeType) -> Tensor: + return svd(A, full_matrices=False)[1] + + +# CompositeImplicitAutograd +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("x", "y"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def vecdot(x: Tensor, y: Tensor, dim: int = -1) -> Tensor: + check_fp_or_complex(x.dtype, "linalg.vecdot") + return (x.conj() * y).sum(dim=dim) diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/linalg/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_refs/linalg/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c8c4e49b079193f12ca9c66bbe4cbf3312451e1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_refs/linalg/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/nn/__init__.py b/.venv/lib/python3.12/site-packages/torch/_refs/nn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9c2ef67bd9d44a21f9d3673ba631c0840740ced --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_refs/nn/__init__.py @@ -0,0 +1 @@ +__all__: list[str] = [] diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/nn/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_refs/nn/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d702a819b675cf9fd183e5c57a274d3dc165ac74 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_refs/nn/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/nn/functional/__init__.py b/.venv/lib/python3.12/site-packages/torch/_refs/nn/functional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b0ecb11f36b595637f8858f3cfe6d7a4ea390d2c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_refs/nn/functional/__init__.py @@ -0,0 +1,1348 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import math +from collections.abc import Callable +from functools import wraps +from typing import Concatenate, Optional, TypeVar, Union +from typing_extensions import ParamSpec + +import torch +import torch._prims as prims +import torch._prims_common as utils +import torch._refs as refs +from torch._decomp import register_decomposition +from torch._prims_common import ( + ELEMENTWISE_TYPE_PROMOTION_KIND, + NumberType, + ShapeType, + TensorLike, + TensorLikeType, +) +from torch._prims_common.wrappers import ( + elementwise_type_promotion_wrapper, + elementwise_unary_scalar_wrapper, + out_wrapper, +) +from torch._refs import _make_inplace + + +__all__ = [ + "alpha_dropout", + "celu", + "celu_", + "channel_shuffle", + "dropout", + "elu", + "elu_", + "gelu", + "glu", + "group_norm", + "hardshrink", + "hardtanh", + "hinge_embedding_loss", + "huber_loss", + "l1_loss", + "layer_norm", + "leaky_relu", + "log_softmax", + "margin_ranking_loss", + "mish", + "mish_", + "mse_loss", + "nll_loss", + "pairwise_distance", + "pdist", + "poisson_nll_loss", + "prelu", + "relu", + "relu6", + "selu", + "selu_", + "smooth_l1_loss", + "softmax", + "softmin", + "softplus", + "softshrink", + "tanhshrink", + "threshold", + "threshold_", + "triplet_margin_loss", +] + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +Tensor = torch.Tensor +aten = torch._ops.ops.aten +DispatchKey = torch._C.DispatchKey # type: ignore[attr-defined] + + +def _dropout_helper( + self: TensorLikeType, + val: float, +) -> TensorLikeType: + """ + Helper function for all dropout-type operators. During training, + some of the elements of the input tensor are randomly masked. + + Returns the masked tensor of the boolean values. + + """ + + return ( + refs._uniform_helper( + self.shape, + low=0.0, + high=1.0, + dtype=torch.float32, + device=self.device, + stride=self.stride(), + ) + < val + ) + + +@register_decomposition(aten.alpha_dropout) +def alpha_dropout( + self: TensorLikeType, p: float = 0.5, training: bool = False, inplace: bool = False +) -> TensorLikeType: + if inplace: + raise NotImplementedError + + if not training: + return self + + torch._check( + p <= 1 and p >= 0, + lambda: f"dropout probability has to be between 0 and 1, but got, {p}", + ) + + if p == 1: + return torch.zeros_like(self) + + if p == 0: + return self + + dropout_mask = _dropout_helper(self, 1 - p) + + # From paper: Self-Normalizing Neural Networks (https://arxiv.org/pdf/1706.02515.pdf) + # alpha = - SELU.alpha * SELU.scale, here + # SELU.alpha = 1.6732632423543772848170429916717 and + # SELU.scale = 1.0507009873554804934193349852946 + alpha = -1.7580993408473766 + + a = 1.0 / math.sqrt((alpha * alpha * p + 1) * (1 - p)) + b = torch.logical_not(dropout_mask) + b = b * (alpha * a) + alpha * a * p + dropout_mask = a * dropout_mask + + return self * dropout_mask + b + + +def _inplace_wrapper(fn: Callable[_P, _T]) -> Callable[_P, _T]: + """ + Given a nn.functional non-linearity, implements its `inplace: bool` argument + """ + + # nb. We use the name of the first argument used in the unary references + @wraps(fn) + def _fn(*args: _P.args, **kwargs: _P.kwargs) -> _T: + a = args[0] + if "inplace" not in kwargs: + kwargs["inplace"] = False + + if kwargs["inplace"]: + torch._check( + "out" not in kwargs, + lambda: "Cannot set inplace=True and pass out= at the same time", + ) + kwargs["inplace"] = False + kwargs["out"] = a + return fn(*args, **kwargs) + else: + return fn(*args, **kwargs) + + return _fn + + +# celu is implemented specially because it has an alpha argument +# celu is very similar to elu +@register_decomposition(aten.celu) +@_inplace_wrapper +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def celu( + a: TensorLikeType, alpha: NumberType | None = None, inplace: bool = False +) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.celu + """ + + if inplace: + raise NotImplementedError + + rhs: TensorLikeType + if alpha is not None: + torch._check( + alpha != 0, + lambda: "ZeroDivisionError: alpha cannot be 0 for CELU", + ) + python_type = utils.dtype_to_type(a.dtype) + if not utils.is_weakly_lesser_type(type(alpha), python_type): + msg = f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!" + raise ValueError(msg) + torch._check( + alpha != 0, + lambda: "ZeroDivisionError: alpha cannot be 0 for CELU", + ) + rhs = alpha * torch.expm1(torch.true_divide(a, alpha)) # type: ignore[arg-type] + else: + rhs = torch.expm1(a) + + return torch.where(a > 0, a, rhs) + + +@_inplace_wrapper +@out_wrapper() +def dropout( + a: TensorLikeType, p: float = 0.5, training: bool = True, inplace: bool = False +) -> TensorLikeType: + if inplace: + raise NotImplementedError + + if not training: + return a + + torch._check( + p <= 1 and p >= 0, + lambda: f"dropout probability has to be between 0 and 1, but got, {p}", + ) + + if p == 1: + return torch.zeros_like(a) + + if p == 0: + return a + + scale = 1 / (1 - p) + dropout_mask = _dropout_helper(a, 1 - p) + + return a * dropout_mask * scale + + +@register_decomposition(aten.elu) +@_inplace_wrapper +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def elu( + a: TensorLikeType, + alpha: NumberType = 1.0, + scale: NumberType = 1.0, + input_scale: NumberType = 1.0, + inplace: bool = False, +) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.elu + """ + if inplace: + raise NotImplementedError + + # nb. This should be factored out into a can_cast aux function + python_type = utils.dtype_to_type(a.dtype) + torch._check( + utils.is_weakly_lesser_type(type(input_scale), python_type), + lambda: f"input_scale argument of type {type(input_scale)} cannot be safely cast to type {python_type}!", + ) + torch._check( + utils.is_weakly_lesser_type(type(scale), python_type), + lambda: f"scale argument of type {type(scale)} cannot be safely cast to type {python_type}!", + ) + torch._check( + utils.is_weakly_lesser_type(type(alpha), python_type), + lambda: f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!", + ) + + return torch.where(a > 0, scale * a, (alpha * scale) * torch.expm1(a * input_scale)) + + +@register_decomposition(aten.relu) +@_inplace_wrapper +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def relu(a: TensorLikeType, inplace: bool = False) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.relu + """ + + if inplace: + raise NotImplementedError + + return torch.where(torch.le(a, 0), 0, a) + + +@_inplace_wrapper +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def hardsigmoid(a: TensorLikeType, inplace: bool = False) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.hardsigmoid + """ + return torch.clamp(a / 6 + 0.5, 0, 1) + + +@register_decomposition(aten.channel_shuffle) +@out_wrapper() +def channel_shuffle(input: TensorLikeType, groups: int) -> TensorLikeType: + """ + Reference implementation of :func:`torch.nn.functional.channel_shuffle`. + """ + from torch._meta_registrations import device_hint + + torch._check( + input.dim() > 2, + lambda: f"channel_shuffle expects input with > 2 dims, but got input with sizes {list(input.size())}", + ) + c = input.shape[1] + torch._check( + groups > 0, + lambda: f"Number of groups to divide channels in must be positive. Value of groups:{groups}", + ) + torch._check( + (c % groups) == 0, + lambda: f"Number of channels must be divisible by groups. Got {c} channels and {groups} groups.", + ) + n = input.shape[0] + cg = c // groups + dhw = input.shape[2:] + + if input.numel() == 0 or ( + device_hint(input) == "cuda" and (groups == 1 or groups == c) + ): + return input.view(input.shape) + + return ( + input.reshape(n, groups, cg, *dhw) + .transpose(1, 2) + .reshape(input.shape) + .contiguous() + ) + + +def group_norm( + input: Tensor, + num_groups: int, + weight: Tensor | None = None, + bias: Tensor | None = None, + eps: float = 1e-5, +) -> Tensor: + """ + Reference implementation of :func:`torch.nn.functional.group_norm`. + """ + torch._check( + input.ndim >= 2, + lambda: f"Expected at least 2 dimensions for input tensor but received {input.ndim}", + ) + + batch_size = input.shape[0] + num_channels = input.shape[1] + torch._check( + num_channels % num_groups == 0, + lambda: "Expected number of channels in input to be divisible by num_groups, " + + f"but got input of shape {input.shape} and num_groups = {num_groups}", + ) + + # input shape is (N, C, *), so we flatten all inner dimensions except (N, C) + flattened_inner_size = 1 + for dim_length in input.shape[2:]: + flattened_inner_size *= dim_length + + return torch.native_group_norm( + input, + weight, + bias, + batch_size, + num_channels, + flattened_inner_size, + num_groups, + eps, + )[0] + + +def layer_norm( + input: Tensor, + normalized_shape: ShapeType, + weight: Tensor | None = None, + bias: Tensor | None = None, + eps: float = 1e-5, +) -> Tensor: + """ + Reference implementation of :func:`torch.nn.functional.layer_norm`. + """ + return torch.native_layer_norm(input, normalized_shape, weight, bias, eps)[0] + + +@register_decomposition(aten.leaky_relu) +@_inplace_wrapper +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def leaky_relu( + a: TensorLikeType, negative_slope: float = 0.01, inplace: bool = False +) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.leaky_relu + """ + + if inplace: + raise NotImplementedError + + python_type = utils.dtype_to_type(a.dtype) + if not utils.is_weakly_lesser_type(type(negative_slope), python_type): + msg = f"negative_slope argument of type {type(negative_slope)} cannot be safely cast to type {python_type}!" + raise ValueError(msg) + return torch.where(torch.gt(a, 0), a, torch.mul(a, negative_slope)) + + +@register_decomposition(aten.mish) +@_inplace_wrapper +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def mish(a: TensorLikeType, inplace: bool = False) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.mish + """ + + if inplace: + raise NotImplementedError + return a * torch.tanh(torch.nn.functional.softplus(a)) + + +@register_decomposition(aten.selu) +@_inplace_wrapper +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def selu(a: TensorLikeType, inplace: bool = False) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.selu + """ + if inplace: + raise NotImplementedError + + alpha = 1.6732632423543772848170429916717 + scale = 1.0507009873554804934193349852946 + + rhs = alpha * torch.expm1(a) + + return scale * torch.where(a > 0, a, rhs) + + +# Forwarding alias: the functional variant doesn't support the out kwarg +# CompositeImplicitAutograd - don't register decomp +def softmax( + a: TensorLikeType, + dim: int | None = None, + _stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True) + dtype: torch.dtype | None = None, +) -> TensorLikeType: + # The error is for compat with regular PyTorch, which has this behavior + # deprecated. For PrimTorch, it's fine to drop support for deprecated + # behavior because it requires explicit opt in. This error is to inform + # users how to update their calls. + torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X") + return torch.softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload] + + +# CompositeImplicitAutograd - don't register decomp +def softmin( + a: TensorLikeType, + dim: int | None = None, + _stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True) + dtype: torch.dtype | None = None, +) -> TensorLikeType: + # The error is for compat with regular PyTorch, which has this behavior + # deprecated. For PrimTorch, it's fine to drop support for deprecated + # behavior because it requires explicit opt in. This error is to inform + # users how to update their calls. + torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X") + return torch.softmax(a=-a, dim=dim, dtype=dtype) # type: ignore[call-overload] + + +# softplus is implemented specially because it has beta and threshold arguments +@register_decomposition(aten.softplus) +@_inplace_wrapper +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def softplus( + a: TensorLikeType, + beta: NumberType | None = None, + threshold: NumberType = 20, + inplace: bool = False, +) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.softplus + """ + + if inplace: + raise NotImplementedError + + rhs: TensorLikeType + if beta is not None: + python_type = utils.dtype_to_type(a.dtype) + if not utils.is_weakly_lesser_type(type(beta), python_type): + msg = f"beta argument of type {type(beta)} cannot be safely cast to type {python_type}!" + raise ValueError(msg) + scaled_input = a * beta + rhs = torch.true_divide(torch.log1p(torch.exp(scaled_input)), beta) # type: ignore[arg-type] + + else: + scaled_input = a + rhs = torch.log1p(torch.exp(scaled_input)) + + return torch.where(scaled_input > threshold, a, rhs) + + +@aten.hardshrink.default.py_impl(DispatchKey.Autograd) +@register_decomposition(aten.hardshrink) +@out_wrapper() +def hardshrink(a: TensorLikeType, lambd: float = 0.5): + # Formula for reference, + # hardshrink(x) = x if x > lambd + # = x if x < -lambd + # = 0 otherwise + return torch.where(torch.abs(a) <= lambd, 0, a) + + +@aten.softshrink.default.py_impl(DispatchKey.Autograd) +@register_decomposition(aten.softshrink) +@out_wrapper() +def softshrink(a: TensorLikeType, lambd: float = 0.5): + # Formula for reference, + # softshrink(x) = x - lambd if x > lambd + # = x + lambd if x < -lambd + # = 0 otherwise + torch._check( + 0 <= lambd <= torch.finfo(a.dtype).max, + lambda: f"lambda must be in range [0, {torch.finfo(a.dtype).max}] for input dtype {a.dtype}, but found {lambd}", + ) + if a.dtype in (torch.bfloat16, torch.float16): + lambd = torch.scalar_tensor(lambd, dtype=a.dtype, device=a.device) # type: ignore[arg-type] + # We implement this in one torch.where to generate better code in the backward + # see https://github.com/pytorch/pytorch/pull/107052#discussion_r1293748211 + # We multiply by 0 for dealing with nans + return torch.where(torch.abs(a) > lambd, a - torch.sign(a) * lambd, a * 0) + + +# Losses +def _reduction_int_to_str(reduction: int) -> str: + from torch._decomp.decompositions import Reduction + + if reduction == Reduction.NONE.value: + return "none" + elif reduction == Reduction.MEAN.value: + return "mean" + elif reduction == Reduction.SUM.value: + return "sum" + else: + raise ValueError(f"{reduction} is not a valid value for reduction") + + +def _apply_loss_reduction(loss: TensorLikeType, reduction: str) -> TensorLikeType: + if reduction == "sum": + return torch.sum(loss) + elif reduction == "mean": + return torch.mean(loss) + else: # reduction == "none" + return loss + + +def _check_reduction_value(reduction: str): + if reduction not in ("mean", "sum", "none"): + raise ValueError(f"{reduction} is not a valid value for reduction") + + +# This helper function maps deprecated arguments, "size_average" and "reduce" +# to their corresponding "reduction" string argument +def _get_string_reduction_arg(*, size_average: bool | None, reduce: bool | None) -> str: + if size_average is None: + size_average = True + if reduce is None: + reduce = True + if size_average and reduce: + ret = "mean" + elif reduce: + ret = "sum" + else: + ret = "none" + return ret + + +# CompositeImplicitAutograd - don't register decomp +@elementwise_type_promotion_wrapper( + type_promoting_args=("input", "target"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT, +) +def l1_loss( + input: TensorLikeType, + target: TensorLikeType, + size_average: bool | None = None, + reduce: bool | None = None, + reduction: str = "mean", +) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.l1_loss + """ + if size_average is not None or reduce is not None: + # TODO: Raise exception instead of converting value. This is only for + # primTorch since it can drop support for deprecated arguments. + # msg = "size_average and reduce args are deprecated, please use reduction argument." + reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce) + _check_reduction_value(reduction) + loss = torch.abs(input - target) + return _apply_loss_reduction(loss, reduction) + + +@elementwise_type_promotion_wrapper( + type_promoting_args=("input", "target"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT, +) +def smooth_l1_loss( + input: TensorLikeType, + target: TensorLikeType, + size_average: bool | None = None, + reduce: bool | None = None, + reduction: str = "mean", + beta: float = 1.0, +) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.smooth_l1_loss + """ + if size_average is not None or reduce is not None: + # TODO: Raise exception instead of converting value. This is only for + # primTorch since it can drop support for deprecated arguments. + # msg = "size_average and reduce args are deprecated, please use reduction argument." + reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce) + _check_reduction_value(reduction) + + if beta == 0.0: + return torch.nn.functional.l1_loss( + input, target, size_average=size_average, reduce=reduce, reduction=reduction + ) + else: + loss = torch.abs(input - target) + + loss = torch.where(loss < beta, 0.5 * loss**2 / beta, loss - 0.5 * beta) + return _apply_loss_reduction(loss, reduction) + + +# Forwarding alias: the functional variant doesn't support the out kwarg +# CompositeImplicitAutograd - don't register decomp +def log_softmax( + a: TensorLikeType, + dim: int | None = None, + _stacklevel: int = 3, # for compat when using TorchRefsMode(strict=True) + dtype: torch.dtype | None = None, +) -> TensorLikeType: + # The error is for compat with regular PyTorch, which has this behavior + # deprecated. For PrimTorch, it's fine to drop support for deprecated + # behavior because it requires explicit opt in. This error is to inform + # users how to update their calls. + torch._check(dim is not None, lambda: "implicit dim not supported, use dim=X") + return torch.log_softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload] + + +@register_decomposition(aten.margin_ranking_loss) +def margin_ranking_loss( + input1: TensorLikeType, + input2: TensorLikeType, + target: TensorLikeType, + margin: float = 0.0, + reduction: str = "mean", +) -> TensorLikeType: + # loss_without_reduction = max(0, -target * (input1 - input2) + margin) + if input1.ndim != input2.ndim or input1.ndim != target.ndim: + raise RuntimeError( + "margin_ranking_loss : All input tensors should have same dimension but got sizes: " + f"input1: {input1.shape}, input2: {input2.shape}, target: {target.shape} " + ) + _check_reduction_value(reduction) + loss = torch.clamp_min(-target * (input1 - input2) + margin, 0) + return _apply_loss_reduction(loss, reduction) + + +@elementwise_type_promotion_wrapper( + type_promoting_args=("input", "target"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT, +) +def mse_loss( + input: TensorLikeType, + target: TensorLikeType, + size_average: bool | None = None, + reduce: bool | None = None, + reduction: str = "mean", +) -> TensorLikeType: + if size_average is not None or reduce is not None: + # TODO: Raise exception instead of converting value. This is only for + # primTorch since it can drop support for deprecated arguments. + # msg = "size_average and reduce args are deprecated, please use reduction argument." + reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce) + _check_reduction_value(reduction) + loss = torch.pow(input - target, 2) + return _apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.hinge_embedding_loss) +def hinge_embedding_loss( + input: TensorLikeType, + target: TensorLikeType, + margin: float = 1.0, + reduction: str = "mean", +) -> TensorLikeType: + # loss_without_reduction = input if y == 1 + # = max(0, margin - input) if y == -1 + _check_reduction_value(reduction) + margin_clamp = torch.clamp_min(margin - input, 0) + output_margin = torch.where(target != 1, margin_clamp, 0) + output_self = torch.where(target != -1, input, 0) + loss = output_margin + output_self + return _apply_loss_reduction(loss, reduction) + + +def _nll_loss_nd( + input: TensorLikeType, + target: TensorLikeType, + weight: TensorLikeType | None, + reduction: str, + ignore_index: int, +) -> TensorLikeType: + torch._check( + input.ndim > 0 and input.ndim <= 3, + lambda: f"Expected input dimension to be either [1, 2, 3] but received {input.ndim}.", + ) + + torch._check( + (input.ndim == 1) or (input.shape[0] == target.shape[0]), + lambda: f"Expected input batch size {input.shape[0]} to match target batch size {target.shape[0]}.", + ) + + _check_reduction_value(reduction) + + flat_target = torch.flatten(target) + ignore_classes_mask = torch.eq(flat_target, ignore_index) + + # TODO: Enable data-dependent checks with debug mode + # TODO: This check does not work with FakeTensor inputs; See Issue #85834 + # Explicit cast for class_check to bool; See Issue #78071 + """ + from torch._subclasses.fake_tensor import FakeTensor, is_fake_tensor + num_classes = input.shape[1] if input.ndim > 1 else input.shape[0] + valid_classes_mask = torch.logical_and( + (flat_target >= 0), (flat_target < num_classes) + ) + class_check = torch.all(torch.logical_or(ignore_classes_mask, valid_classes_mask)) + torch._check( + is_fake_tensor(target) or bool(class_check.item()), + lambda: "A target class is out-of-bounds and not the ignore index.", + ) + """ + + ignore_class_weight = torch.scalar_tensor(0, dtype=input.dtype, device=input.device) + class_weight = ( + torch.scalar_tensor(1, dtype=input.dtype, device=input.device) + if weight is None + else weight[flat_target] + ) + current_weight = torch.where( + ignore_classes_mask, + ignore_class_weight, + class_weight, + ) + + if input.ndim == 1: + # implicit batch size = 1 + # input (1 batch size, C classes) + loss = -input[target] * current_weight + elif input.ndim == 2: + # input (N batch size, C classes) + batch_size = input.shape[0] + loss = -input[torch.arange(batch_size), target] * current_weight + else: + # 3D case (N batch size, C classes, K dimensions) + # input (N batch size, C classes, K) + batch_size = input.shape[0] + extent = input.shape[2] + numel = batch_size * extent + indices = torch.arange(numel) + bdx = indices // extent + kdx = indices % extent + loss = -input[bdx, flat_target, kdx] * current_weight + loss = torch.reshape(loss, target.shape) + + if reduction == "none": + return loss + elif reduction == "sum": + return torch.sum(loss) + else: + # calculate weighted mean of the loss function + return torch.sum(loss) / torch.sum(current_weight) + + +@register_decomposition(aten.nll_loss) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("input",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def nll_loss( + input: TensorLikeType, + target: TensorLikeType, + weight: TensorLikeType | None = None, + size_average: bool | None = None, + ignore_index: int = -100, + reduce: bool | None = None, + reduction: str = "mean", +) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.nll_loss + """ + torch._check( + input.ndim > 0, + lambda: f"Expected input tensor to have 1 or more dimensions (got {input.ndim})", + ) + + # TODO: raise exception instead of converting value + # msg = "size_average and reduce args are deprecated, please use reduction argument." + # Convert these options for consistency with the eager mode + if size_average is not None or reduce is not None: + reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce) + + # The expected behavior when the target and input have zero elements: + # reduction = 'none' --- tensor([]) + # reduction = 'sum' --- tensor(0.) + # reduction = 'mean' --- tensor(nan) + # Mean reduction on empty tensors produces NaN. See the discussion in + # https://github.com/pytorch/pytorch/pull/64572#issuecomment-926504162 + if input.numel() == 0 and target.numel() == 0: + if reduction == "none": + return torch.zeros_like(target) + elif reduction == "sum": + return torch.empty_like(target) + else: + return torch.full_like(target, float("nan")) + + # The _nll_loss_nd helper function handles the most common cases. + # ndim == 1 (Single Example) + # => Batch Size: 1, Input: (C), Target: () + # ndim == 2 (k = 1) + # => Batch Size: N, Input: (N, C), Target: (N) + # ndim == 3 (k > 1) + # => Batch Size: N, Input: (N, C, K), Target: (N, K) + if input.ndim <= 3: + return _nll_loss_nd(input, target, weight, reduction, ignore_index) + + # For ndim > 3, we reshape the input and target to 3-D case. + # Input (N batch-size, C classes, k-dimensions) + # Target (N batch-size, k-dimensions) + torch._check( + input.ndim > 0 and target.ndim > 0 and target.shape[1:] == input.shape[2:], + lambda: ( + "Expected input and target to both have ndim > 0 and " + "target.shape[1:] == input.shape[2:], but got " + f"target.shape {target.shape} and input.shape {input.shape}" + ), + ) + + batch_size = input.shape[0] + num_classes = input.shape[1] + out_size = [batch_size] + list(target.shape[1:]) + + input = torch.reshape(input, [batch_size, num_classes, -1]) + target = torch.reshape(target, [batch_size, -1]) + if reduction != "none": + return _nll_loss_nd(input, target, weight, reduction, ignore_index) + else: + result = _nll_loss_nd(input, target, weight, reduction, ignore_index) + # reshape flattened inner-dim to original k-dimensions + return torch.reshape(result, out_size) + + +# TODO: This ref supports int reduction and out kwarg to be compatible with ATen: +# https://github.com/pytorch/pytorch/issues/83931 +# TODO: Could be rewritten to support complex: +# https://github.com/pytorch/pytorch/pull/85041 +@register_decomposition(aten.huber_loss) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("input", "target"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def huber_loss( + input: TensorLikeType, + target: TensorLikeType, + reduction: str | int = "mean", + delta: float = 1.0, +) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.huber_loss + """ + if type(reduction) is int: + reduction = _reduction_int_to_str(reduction) + _check_reduction_value(reduction) # type: ignore[arg-type] + torch._check( + delta > 0, + lambda: "huber_loss does not support non-positive values for delta.", + ) + z = (input - target).abs() + loss = torch.where(z < delta, 0.5 * z * z, delta * (z - 0.5 * delta)) + return _apply_loss_reduction(loss, reduction) # type: ignore[arg-type] + + +# tanhshrink does not use _make_elementwise_unary_reference because it does not support out +@elementwise_unary_scalar_wrapper +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def tanhshrink(a: TensorLikeType) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.tanhshrink + """ + if not isinstance(a, TensorLike): + raise RuntimeError( + "Expected a tensor input for an elementwise unary operation!" + ) + return a - torch.tanh(a) + + +@register_decomposition(aten.threshold) +@_inplace_wrapper +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def threshold( + a: TensorLikeType, + threshold: NumberType, + value: bool | int | float, + inplace: bool = False, +) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.threshold + """ + + if inplace: + raise NotImplementedError + + return torch.where(a <= threshold, value, a) + + +# CompositeImplicitAutograd - don't register decomp +# No elementwise type promotion - core op doesn't explicitly type promote +def triplet_margin_loss( + anchor: TensorLikeType, + positive: TensorLikeType, + negative: TensorLikeType, + margin: float = 1.0, + p: float = 2, + eps: float = 1e-6, + swap: bool = False, + size_average: bool | None = None, + reduce: bool | None = None, + reduction: str = "mean", +) -> TensorLikeType: + if size_average is not None or reduce is not None: + # TODO: Raise exception instead of converting value. This is only for + # primTorch since it can drop support for deprecated arguments. + # msg = "size_average and reduce args are deprecated, please use reduction argument." + reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce) + + if margin <= 0: + raise ValueError(f"margin must be greater than 0, got {margin}") + + # torch.nn.functional.triplet_margin_with_distance_loss has no ref defined + # since it's a pure Python implementation. Use this helper instead. + return _triplet_margin_with_distance_loss( + anchor=anchor, + positive=positive, + negative=negative, + distance_function=lambda x, y: torch.pairwise_distance(x, y, p, eps), + margin=margin, + swap=swap, + reduction=reduction, + ) + + +# Pure Python impl - don't register decomp and don't add a ref. Defined as a +# helper here since triplet_margin_loss can be nicely implemented with it. +def _triplet_margin_with_distance_loss( + anchor: TensorLikeType, + positive: TensorLikeType, + negative: TensorLikeType, + *, + distance_function: Callable[[TensorLikeType, TensorLikeType], TensorLikeType] + | None = None, + margin: float = 1.0, + swap: bool = False, + reduction: str = "mean", +) -> TensorLikeType: + _check_reduction_value(reduction) + + a_dim = anchor.ndim + p_dim = positive.ndim + n_dim = negative.ndim + torch._check( + a_dim == p_dim and p_dim == n_dim, + lambda: ( + f"The anchor, positive, and negative tensors are expected to have " + f"the same number of dimensions, but got: anchor {a_dim}D, " + f"positive {p_dim}D, and negative {n_dim}D inputs" + ), + ) + + if distance_function is None: + distance_function = torch.pairwise_distance + + dist_pos = distance_function(anchor, positive) + dist_neg = distance_function(anchor, negative) + # The distance swap is described in the paper "Learning shallow + # convolutional feature descriptors with triplet losses" by V. Balntas, E. + # Riba et al. If True, and if the positive example is closer to the + # negative example than the anchor is, swaps the positive example and the + # anchor in the loss computation. + if swap: + dist_swap = distance_function(positive, negative) + dist_neg = torch.minimum(dist_neg, dist_swap) + loss = torch.clamp_min(margin + dist_pos - dist_neg, 0) + return _apply_loss_reduction(loss, reduction) + + +def _hardtanh( + a: TensorLikeType, + min_val: NumberType = -1, + max_val: NumberType = 1, + inplace: bool = False, + *, + check_bounds: bool, +) -> TensorLikeType: + if inplace: + raise NotImplementedError + if utils.is_boolean_dtype(a.dtype): + raise NotImplementedError("Bool inputs not supported for hardtanh") + + # preserve legacy behavior of boundaries not causing type promotion + if utils.is_integer_dtype(a.dtype): + min_val = int(min_val) # type: ignore[arg-type] + max_val = int(max_val) # type: ignore[arg-type] + if not (a.dtype != torch.uint8 or (min_val >= 0 and max_val >= 0)): + raise RuntimeError( + "Cannot do hardtanh on an unsigned type with negative limits" + ) + + if check_bounds and min_val > max_val: # type: ignore[operator] + raise ValueError("min_val cannot be greater than max_val") + + return torch.clamp(a, min_val, max_val) # type: ignore[arg-type] + + +@register_decomposition([aten.hardtanh.default, aten.hardtanh.out]) +@_inplace_wrapper +@out_wrapper() +@elementwise_unary_scalar_wrapper +@elementwise_type_promotion_wrapper( + type_promoting_args=("a"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def _aten_hardtanh( + a: TensorLikeType, + min_val: NumberType = -1, + max_val: NumberType = 1, + inplace: bool = False, +) -> TensorLikeType: + return _hardtanh( + a, min_val=min_val, max_val=max_val, inplace=inplace, check_bounds=False + ) + + +@_inplace_wrapper +@out_wrapper() +@elementwise_unary_scalar_wrapper +@elementwise_type_promotion_wrapper( + type_promoting_args=("a"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def hardtanh( + a: TensorLikeType, + min_val: NumberType = -1, + max_val: NumberType = 1, + inplace: bool = False, +) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.hardtanh + """ + return _hardtanh( + a, min_val=min_val, max_val=max_val, inplace=inplace, check_bounds=True + ) + + +@register_decomposition(aten.gelu) +@out_wrapper() +@elementwise_unary_scalar_wrapper +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def gelu(a: TensorLikeType, approximate: str = "none") -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.gelu + """ + if not isinstance(a, TensorLike): + raise RuntimeError( + "Expected a tensor input for an elementwise unary operation!" + ) + M_SQRT2 = 1.41421356237309504880 + M_SQRT1_2 = 0.70710678118654752440 + M_2_SQRTPI = 1.12837916709551257390 + if approximate == "tanh": + kBeta = M_SQRT2 * M_2_SQRTPI * 0.5 + kKappa = 0.044715 + a_cube = a * a * a + inner = kBeta * (a + kKappa * a_cube) + return 0.5 * a * (1 + torch.tanh(inner)) + elif approximate == "none": + kAlpha = M_SQRT1_2 + return a * 0.5 * (1 + torch.erf(a * kAlpha)) + else: + raise RuntimeError("approximate argument must be either none or tanh.") + + +# CompositeImplicitAutograd - don't register decomp +@elementwise_type_promotion_wrapper( + type_promoting_args=("input", "target"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def poisson_nll_loss( + input: TensorLikeType, + target: TensorLikeType, + log_input: bool = True, + full: bool = False, + size_average: bool | None = None, + eps: float = 1e-8, + reduce: bool | None = None, + reduction: str = "mean", +) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.poisson_nll_loss + """ + if size_average is not None or reduce is not None: + # TODO: Raise exception instead of converting value. This is only for + # primTorch since it can drop support for deprecated arguments. + # msg = "size_average and reduce args are deprecated, please use reduction argument." + reduction = _get_string_reduction_arg(size_average=size_average, reduce=reduce) + _check_reduction_value(reduction) + if log_input: + loss = torch.exp(input) - target * input + else: + loss = input - target * torch.log(input + eps) + + if full: + stirling_term = ( + target * torch.log(target) - target + 0.5 * torch.log(2 * torch.pi * target) + ) + # avoid inplace add + loss = loss + stirling_term.masked_fill(target <= 1, 0) + return _apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.prelu) +@elementwise_type_promotion_wrapper( + type_promoting_args=("a", "weight"), + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def prelu(a: TensorLikeType, weight: TensorLikeType) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.prelu + """ + torch._check( + isinstance(a, TensorLike), + lambda: f"prelu: Expected `a` to be tensor, but got: {type(a)}", + ) + torch._check( + isinstance(weight, TensorLike), + lambda: f"prelu: Expected `weight` to be tensor, but got: {type(weight)}", + ) + + if weight.numel() != 1: + torch._check(a.ndim > 0, lambda: "Not allow zero-dim input tensor.") + channel_size = a.shape[1] if a.ndim >= 2 else 1 + torch._check( + weight.numel() == channel_size, + lambda: f"Mismatch of parameter numbers and input channel size. Found parameter numbers =" + f" {weight.numel()} and channel size = {channel_size}.", + ) + + torch._check( + weight.ndim == 0 or weight.ndim == 1, + lambda: f"prelu: Expected `weight` to be a scalar or 1D tensor, but got: " + f"ndim = {weight.ndim}", + ) + if a.ndim == 0: + weight = weight[0] if weight.ndim == 1 else weight + else: + weight = prims.broadcast_in_dim( + weight, a.shape, () if weight.ndim == 0 else (0 if a.ndim == 1 else 1,) + ) + + return torch.where(a > 0, a, a * weight) + + +@register_decomposition(aten.relu6) +@_inplace_wrapper +@out_wrapper() +def relu6(a: TensorLikeType, inplace: bool = False) -> TensorLikeType: + """ + Reference implementation of torch.nn.functional.relu6 + """ + if inplace: + raise NotImplementedError + + # See https://github.com/pytorch/pytorch/pull/81142#discussion_r918220126 + # It may be better to use clamp here, but we use hardtanh to replicate + # the behavior of the existing implementation + return torch.nn.functional.hardtanh(a, 0, 6) + + +@register_decomposition(aten.glu) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def glu(a: TensorLikeType, dim: int = -1) -> TensorLikeType: + dim = utils.canonicalize_dims(a.ndim, dim) + torch._check( + a.shape[dim] % 2 == 0, + lambda: f"Halving dimension must be even, but dimension {dim} is size {a.shape[dim]}", + ) + b, c = torch.tensor_split(a, 2, dim) + + return b * torch.sigmoid(c) + + +@register_decomposition(aten.pairwise_distance) +@out_wrapper() +def pairwise_distance( + x1: TensorLikeType, + x2: TensorLikeType, + p: NumberType = 2.0, + eps: NumberType = 1e-6, + keepdim=False, +) -> TensorLikeType: + return torch.linalg.vector_norm(x1 - x2 + eps, ord=p, dim=-1, keepdim=keepdim) + + +@register_decomposition(aten.pdist) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def pdist(a: TensorLikeType, p: float = 2) -> TensorLikeType: + torch._check(a.ndim == 2, lambda: f"pdist only supports 2D tensors, got: {a.ndim}D") + torch._check(p >= 0, lambda: "pdist only supports non-negative p values") + # For p == 2 we can use an efficient implementation, but other values of p + # require creating a much bigger tensor for an intermediate step + if p == 2: + aTa = torch.mm(a, a.T) + aTa_diag = torch.diag(aTa) + t = torch.sqrt(torch.clamp(aTa_diag + aTa_diag.unsqueeze(-1) - 2 * aTa, min=0)) + else: + t = torch.linalg.vector_norm(a.unsqueeze(1) - a, ord=p, dim=2) + i = torch.triu_indices(t.shape[0], t.shape[1], offset=1, device=a.device) + return t.flatten().index_select(0, i[0] * t.shape[0] + i[1]) + + +@register_decomposition(aten.pixel_shuffle) +@out_wrapper() +def pixel_shuffle(self: Tensor, upscale_factor: int): + torch._check( + self.dim() >= 3, + lambda: f"pixel_shuffle expects input to have at least 3 dimensions, but got input with {self.dim} dimension(s)", + ) + batch = self.shape[:-3] + C_out = self.shape[-3] // upscale_factor**2 + HW_out = (self.shape[-2] * upscale_factor, self.shape[-1] * upscale_factor) + n = len(batch) + B_dims = range(n) + C_dim, r1_dim, r2_dim, H_dim, W_dim = range(n, n + 5) + return ( + self.view( + *batch, + C_out, + upscale_factor, + upscale_factor, + self.shape[-2], + self.shape[-1], + ) + .permute(*B_dims, C_dim, H_dim, r1_dim, W_dim, r2_dim) + .reshape(*batch, C_out, *HW_out) + .clone(memory_format=utils.suggest_memory_format(self)) + ) + + +@register_decomposition(aten.pixel_unshuffle) +@out_wrapper() +def pixel_unshuffle(self: Tensor, downscale_factor: int): + torch._check( + self.dim() >= 3, + lambda: f"pixel_unshuffle expects input to have at least 3 dimensions, but got input with {self.dim} dimension(s)", + ) + batch = self.shape[:-3] + C_out = self.shape[-3] * downscale_factor**2 + HW_out = (self.shape[-2] // downscale_factor, self.shape[-1] // downscale_factor) + n = len(batch) + B_dims = range(n) + C_dim, H_dim, r1_dim, W_dim, r2_dim = range(n, n + 5) + return ( + self.view( + *batch, + self.shape[-3], + HW_out[0], + downscale_factor, + HW_out[1], + downscale_factor, + ) + .permute(*B_dims, C_dim, r1_dim, r2_dim, H_dim, W_dim) + .reshape(*batch, C_out, *HW_out) + .clone(memory_format=utils.suggest_memory_format(self)) + ) + + +# Needed as aten.{celu_,elu_...} exist (even if they don't have the in-place kwarg) +celu_ = _make_inplace(celu) +elu_ = _make_inplace(elu) +mish_ = _make_inplace(mish) +selu_ = _make_inplace(selu) +threshold_ = _make_inplace(threshold) diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/nn/functional/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_refs/nn/functional/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b4de0efcd44a05e600fda3a82efc7d945a6e0b2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_refs/nn/functional/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/special/__init__.py b/.venv/lib/python3.12/site-packages/torch/_refs/special/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b2ae9da46b09a8bde9f8e7418ba69cb7423cd481 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_refs/special/__init__.py @@ -0,0 +1,240 @@ +# mypy: allow-untyped-defs +import math +from typing import Optional, Union + +import torch +import torch._prims as prims +import torch._prims_common as utils +import torch._refs as refs +from torch import Tensor +from torch._decomp import register_decomposition +from torch._prims_common import ( + ELEMENTWISE_TYPE_PROMOTION_KIND, + Number, + NumberType, + TensorLike, + TensorLikeType, +) +from torch._prims_common.wrappers import elementwise_type_promotion_wrapper, out_wrapper +from torch._refs import ( + _make_alias, + _make_elementwise_binary_reference, + _make_elementwise_unary_reference, +) + + +__all__ = [ + "bessel_j0", + "bessel_j1", + "entr", + "erfcx", + "expit", + "i0e", + "i1", + "i1e", + "log_ndtr", + "logit", + "log_softmax", + "multigammaln", + "ndtr", + "ndtri", + "softmax", + "spherical_bessel_j0", + "xlog1py", + "zeta", +] +aten = torch._ops.ops.aten + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def bessel_j0(a: TensorLikeType) -> TensorLikeType: + return prims.bessel_j0(a) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def bessel_j1(a: TensorLikeType) -> TensorLikeType: + return prims.bessel_j1(a) + + +@register_decomposition(aten.special_entr) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def entr(a: TensorLikeType) -> TensorLikeType: + return torch.where( + torch.isnan(a), + a, + torch.where(a > 0, -a * torch.log(a), torch.where(a == 0, 0, -torch.inf)), + ) + + +@register_decomposition(aten.special_erfcx) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def erfcx(a: TensorLikeType) -> TensorLikeType: + return prims.erfcx(a) + + +# alias for sigmoid +expit = _make_alias(torch.sigmoid, "expit") + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def i0e(a: TensorLikeType) -> TensorLikeType: + return prims.bessel_i0e(a) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def i1(a: TensorLikeType) -> TensorLikeType: + return prims.bessel_i1(a) + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def i1e(a: TensorLikeType) -> TensorLikeType: + return prims.bessel_i1e(a) + + +@register_decomposition(aten.special_log_ndtr) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def log_ndtr(a: TensorLikeType) -> TensorLikeType: + # Note: M_SQRT1_2 is the value of 1 / sqrt(2) + M_SQRT1_2 = 0.707106781186547524400844362104849039 + t = a * M_SQRT1_2 + return torch.where( + a < 1.0, + torch.log(torch.special.erfcx(-t) / 2) - t * t, + torch.log1p(-torch.erfc(t) / 2), + ) + + +@register_decomposition(aten.logit) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("self",), + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def logit(self: TensorLikeType, eps: float | None = None) -> TensorLikeType: + if eps is None: + eps = -1.0 + lo = eps + hi = 1 - eps + self = torch.where(self < lo, lo, torch.where(self > hi, hi, self)) + return torch.log(torch.true_divide(self, torch.sub(1, self))) + + +@register_decomposition(aten.special_xlog1py) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a", "b"), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def xlog1py(a: TensorLikeType | NumberType, b: TensorLikeType | NumberType): + torch._check( + isinstance(a, TensorLike) or isinstance(b, TensorLike), + lambda: 'Expected either argument a or b to be a Tensor"', + ) + + # Operations like eq and log do not handle scalar values, so we convert them to scalar_tensors. + if isinstance(a, TensorLike) and isinstance(b, Number): + # pyrefly: ignore [bad-argument-type] + b = refs.scalar_tensor(b, dtype=a.dtype, device=a.device) + elif isinstance(b, TensorLike) and isinstance(a, Number): + # pyrefly: ignore [bad-argument-type] + a = refs.scalar_tensor(a, dtype=b.dtype, device=b.device) + + # mypy: expected "Tensor" + if not isinstance(a, TensorLike): + raise AssertionError(f"a must be TensorLike, got {type(a)}") + if not isinstance(b, TensorLike): + raise AssertionError(f"b must be TensorLike, got {type(b)}") + rhs = torch.where(torch.eq(a, 0), 0, torch.mul(a, torch.log1p(b))) + return torch.where(torch.isnan(b), float("nan"), rhs) + + +@register_decomposition(aten.mvlgamma) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def multigammaln(a: TensorLikeType, p: int) -> TensorLikeType: + c = 0.25 * p * (p - 1) * math.log(math.pi) + b = 0.5 * torch.arange(start=(1 - p), end=1, step=1, dtype=a.dtype, device=a.device) + return torch.sum(torch.lgamma(a.unsqueeze(-1) + b), dim=-1) + c + + +@register_decomposition(aten.special_ndtr) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def ndtr(a: TensorLikeType) -> TensorLikeType: + # Note: M_SQRT1_2 is the value of 1 / sqrt(2) + M_SQRT1_2 = 0.707106781186547524400844362104849039 + a_sqrt_2 = a * M_SQRT1_2 + return (1 + torch.erf(a_sqrt_2)) * 0.5 + + +@register_decomposition(aten.special_ndtri) +@out_wrapper() +@elementwise_type_promotion_wrapper( + type_promoting_args=("a",), + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def ndtri(a: TensorLikeType) -> TensorLikeType: + return prims.ndtri(a) + + +# Forwarding alias: the special variant doesn't support the out kwarg +# CompositeImplicitAutograd - don't register decomp +def log_softmax( + a: TensorLikeType, + dim: int, + dtype: torch.dtype | None = None, +) -> TensorLikeType: + return torch.log_softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload] + + +# Forwarding alias: the special variant doesn't support the out kwarg +# CompositeImplicitAutograd - don't register decomp +def softmax( + a: TensorLikeType, + dim: int, + dtype: torch.dtype | None = None, +) -> TensorLikeType: + return torch.softmax(a=a, dim=dim, dtype=dtype) # type: ignore[call-overload] + + +@_make_elementwise_unary_reference( + ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def spherical_bessel_j0(a: TensorLikeType) -> TensorLikeType: + return prims.spherical_bessel_j0(a) + + +# TODO: add docstring +@_make_elementwise_binary_reference( + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def zeta(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType: + return prims.zeta(a, b) diff --git a/.venv/lib/python3.12/site-packages/torch/_refs/special/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_refs/special/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78e419323b69e4c9a4a2a56ee0ef114a3bfb87cb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_refs/special/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_size_docs.py b/.venv/lib/python3.12/site-packages/torch/_size_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..e30240a1e6f6748d34c673489f225a51c6fe8b9d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_size_docs.py @@ -0,0 +1,39 @@ +"""Adds docstrings to torch.Size functions""" + +import torch._C +from torch._C import _add_docstr as add_docstr + + +def add_docstr_all(method: str, docstr: str) -> None: + add_docstr(getattr(torch._C.Size, method), docstr) + + +add_docstr_all( + "numel", + """ +numel() -> int + +Returns the number of elements a :class:`torch.Tensor` with the given size would contain. + +More formally, for a tensor ``x = tensor.ones(10, 10)`` with size ``s = torch.Size([10, 10])``, +``x.numel() == x.size().numel() == s.numel() == 100`` holds true. + +Example:: + + >>> x=torch.ones(10, 10) + >>> s=x.size() + >>> s + torch.Size([10, 10]) + >>> s.numel() + 100 + >>> x.numel() == s.numel() + True + + +.. warning:: + + This function does not return the number of dimensions described by :class:`torch.Size`, but instead the number + of elements a :class:`torch.Tensor` with that size would contain. + +""", +) diff --git a/.venv/lib/python3.12/site-packages/torch/_sources.py b/.venv/lib/python3.12/site-packages/torch/_sources.py new file mode 100644 index 0000000000000000000000000000000000000000..d7a1b2c2e5bb8492f1ff04000fdf0b1f5ef5d3b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_sources.py @@ -0,0 +1,138 @@ +# mypy: allow-untyped-defs +import ast +import functools +import inspect +from textwrap import dedent +from typing import Any, NamedTuple + +from torch._C import ErrorReport +from torch._C._jit_tree_views import SourceRangeFactory + + +def get_source_lines_and_file( + obj: Any, + error_msg: str | None = None, +) -> tuple[list[str], int, str | None]: + """ + Wrapper around inspect.getsourcelines and inspect.getsourcefile. + + Returns: (sourcelines, file_lineno, filename) + """ + filename = None # in case getsourcefile throws + try: + filename = inspect.getsourcefile(obj) + sourcelines, file_lineno = inspect.getsourcelines(obj) + except OSError as e: + msg = ( + f"Can't get source for {obj}. TorchScript requires source access in " + "order to carry out compilation, make sure original .py files are " + "available." + ) + if error_msg: + msg += "\n" + error_msg + raise OSError(msg) from e + + return sourcelines, file_lineno, filename + + +def normalize_source_lines(sourcelines: list[str]) -> list[str]: + """ + This helper function accepts a list of source lines. It finds the + indentation level of the function definition (`def`), then it indents + all lines in the function body to a point at or greater than that + level. This allows for comments and continued string literals that + are at a lower indentation than the rest of the code. + Args: + sourcelines: function source code, separated into lines by + the '\n' character + Returns: + A list of source lines that have been correctly aligned + """ + + def remove_prefix(text, prefix): + return text[text.startswith(prefix) and len(prefix) :] + + # Find the line and line number containing the function definition + idx = None + for i, l in enumerate(sourcelines): + if l.lstrip().startswith("def"): + idx = i + break + + # This will happen when the function is a lambda- we won't find "def" anywhere in the source + # lines in that case. Currently trying to JIT compile a lambda will throw an error up in + # `parse_def()`, but we might want to handle this case in the future. + if idx is None: + return sourcelines + + # Get a string representing the amount of leading whitespace + fn_def = sourcelines[idx] + whitespace = fn_def.split("def")[0] + + # Add this leading whitespace to all lines before and after the `def` + aligned_prefix = [ + whitespace + remove_prefix(s, whitespace) for s in sourcelines[:idx] + ] + aligned_suffix = [ + whitespace + remove_prefix(s, whitespace) for s in sourcelines[idx + 1 :] + ] + + # Put it together again + aligned_prefix.append(fn_def) + return aligned_prefix + aligned_suffix + + +# Thin wrapper around SourceRangeFactory to store extra metadata +# about the function-to-be-compiled. +class SourceContext(SourceRangeFactory): + def __init__( + self, + source, + filename, + file_lineno, + leading_whitespace_len, + uses_true_division=True, + funcname=None, + ): + super().__init__(source, filename, file_lineno, leading_whitespace_len) + self.uses_true_division = uses_true_division + self.filename = filename + self.funcname = funcname + + +@functools.cache +def make_source_context(*args): + return SourceContext(*args) + + +def fake_range(): + return SourceContext("", None, 0, 0).make_raw_range(0, 1) + + +class ParsedDef(NamedTuple): + ast: ast.Module + ctx: SourceContext + source: str + filename: str | None + file_lineno: int + + +def parse_def(fn): + sourcelines, file_lineno, filename = get_source_lines_and_file( + fn, ErrorReport.call_stack() + ) + sourcelines = normalize_source_lines(sourcelines) + source = "".join(sourcelines) + dedent_src = dedent(source) + py_ast = ast.parse(dedent_src) + if len(py_ast.body) != 1 or not isinstance(py_ast.body[0], ast.FunctionDef): + raise RuntimeError( + f"Expected a single top-level function: {filename}:{file_lineno}" + ) + leading_whitespace_len = len(source.split("\n", 1)[0]) - len( + dedent_src.split("\n", 1)[0] + ) + ctx = make_source_context( + source, filename, file_lineno, leading_whitespace_len, True, fn.__name__ + ) + return ParsedDef(py_ast, ctx, source, filename, file_lineno) diff --git a/.venv/lib/python3.12/site-packages/torch/_storage_docs.py b/.venv/lib/python3.12/site-packages/torch/_storage_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..f0d16bc4250ffb2a383af727c974e9f910a5b2a5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_storage_docs.py @@ -0,0 +1,42 @@ +# mypy: allow-untyped-defs +"""Adds docstrings to Storage functions""" + +import torch._C +from torch._C import _add_docstr as add_docstr + + +storage_classes = ["StorageBase"] + + +def add_docstr_all(method, docstr): + for cls_name in storage_classes: + cls = getattr(torch._C, cls_name) + try: + add_docstr(getattr(cls, method), docstr) + except AttributeError: + pass + + +add_docstr_all( + "from_file", + """ +from_file(filename, shared=False, nbytes=0) -> Storage + +Creates a CPU storage backed by a memory-mapped file. + +If ``shared`` is ``True``, then memory is shared between all processes. +All changes are written to the file. If ``shared`` is ``False``, then the changes on +the storage do not affect the file. + +``nbytes`` is the number of bytes of storage. If ``shared`` is ``False``, +then the file must contain at least ``nbytes`` bytes. If ``shared`` is +``True`` the file will be created if needed. (Note that for ``UntypedStorage`` +this argument differs from that of ``TypedStorage.from_file``) + +Args: + filename (str): file name to map + shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the + underlying `mmap(2) call `_) + nbytes (int): number of bytes of storage +""", +) diff --git a/.venv/lib/python3.12/site-packages/torch/_streambase.py b/.venv/lib/python3.12/site-packages/torch/_streambase.py new file mode 100644 index 0000000000000000000000000000000000000000..9d71120c959b14b09309738c84d788d60e7db326 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_streambase.py @@ -0,0 +1,20 @@ +from typing_extensions import deprecated + +import torch + + +# Preserved only for BC reasons +@deprecated( + "`torch._streambase._StreamBase` is deprecated. Please use `torch.Stream` instead.", + category=FutureWarning, +) +class _StreamBase(torch.Stream): + pass + + +@deprecated( + "`torch._streambase._EventBase` is deprecated. Please use `torch.Event` instead.", + category=FutureWarning, +) +class _EventBase(torch.Event): + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_strobelight/__init__.py b/.venv/lib/python3.12/site-packages/torch/_strobelight/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_strobelight/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_strobelight/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f4a2f4fc7fb1ff5449d6def4b993818d2774781 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_strobelight/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_strobelight/__pycache__/cli_function_profiler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_strobelight/__pycache__/cli_function_profiler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8ca51be8526fb0b6f257336e60681833176808d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_strobelight/__pycache__/cli_function_profiler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_strobelight/__pycache__/compile_time_profiler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_strobelight/__pycache__/compile_time_profiler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73ccd99a181f3a0e8b7a3811da49a14f81933f20 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_strobelight/__pycache__/compile_time_profiler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_strobelight/cli_function_profiler.py b/.venv/lib/python3.12/site-packages/torch/_strobelight/cli_function_profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..859848311711057915fc2f7ca67a4a79730b9f89 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_strobelight/cli_function_profiler.py @@ -0,0 +1,322 @@ +# mypy: disallow-untyped-defs + +import functools +import logging +import os +import re +import subprocess +import time +from collections.abc import Callable, Sequence +from threading import Lock +from timeit import default_timer as timer +from typing import Any, TypeVar +from typing_extensions import ParamSpec + + +logger = logging.getLogger("strobelight_function_profiler") + +console_handler = logging.StreamHandler() +formatter = logging.Formatter( + "%(name)s, line %(lineno)d, %(asctime)s, %(levelname)s: %(message)s" +) +console_handler.setFormatter(formatter) + +logger.addHandler(console_handler) +logger.setLevel(logging.INFO) +logger.propagate = False + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +class StrobelightCLIProfilerError(Exception): + """ + Raised when an error happens during strobelight profiling + """ + + +def _pid_namespace_link(pid: int | None = None) -> str: + """Returns the link to the process's namespace, example: pid:[4026531836]""" + PID_NAMESPACE_PATH = "/proc/{}/ns/pid" + pid = pid or os.getpid() + return os.readlink(PID_NAMESPACE_PATH.format(pid)) + + +def _pid_namespace(pid: int | None = None) -> int: + """Returns the process's namespace id""" + pid = pid or os.getpid() + link = _pid_namespace_link(pid) + return int(link[link.find("[") + 1 : -1]) + + +def _command_to_string(command: Sequence[str]) -> str: + return " ".join(command) + + +class StrobelightCLIFunctionProfiler: + """ + Note: this is a Meta only tool. + + StrobelightCLIFunctionProfiler can be used to profile a python function and + generate a strobelight link with the results. It works on meta servers but + does not require an fbcode target. + When stop_at_error is false(default), error during profiling does not prevent + the work function from running. + + Check function_profiler_example.py for an example. + """ + + # This lock is used to make sure only one thread is running the profiler at any point. + _lock = Lock() + + def __init__( + self, + *, + stop_at_error: bool = False, + max_profile_duration_sec: int = 60 * 10, + sample_each: float = 1e7, # sample each sample_each cycles. + run_user_name: str = "pytorch-strobelight-ondemand", + timeout_wait_for_running_sec: int = 60, + timeout_wait_for_finished_sec: int = 60, + recorded_env_variables: list[str] | None = None, + sample_tags: list[str] | None = None, + stack_max_len: int = 127, + async_stack_max_len: int = 127, + ): + self.stop_at_error = stop_at_error + self.max_profile_duration_sec = max_profile_duration_sec + self.sample_each = sample_each + self.run_user_name = run_user_name + self.timeout_wait_for_running_sec = timeout_wait_for_running_sec + self.timeout_wait_for_finished_sec = timeout_wait_for_finished_sec + # Results of the most recent run. + # Tracks the strobelight run id of the most recent run + self.current_run_id: int | None = None + self.profile_result: list[str] | None = None + self.sample_tags = sample_tags + + def _run_async(self) -> None: + processId = os.getpid() + namespace = _pid_namespace(processId) + command = [ + "strobeclient", + "run", + "--profiler", + "pyperf", + "--event", + "cycles", + "--async", + "--sample-interval", + f"{int(self.sample_each)}", + "--duration-ms", + f"{int(self.max_profile_duration_sec * 1000)}", + "--pid", + f"{namespace}:{processId}", + ] + + if self.sample_tags: + command.append("--sample-tags") + command.append(",".join(self.sample_tags)) + + logger.debug("running command: %s", _command_to_string(command)) + result = subprocess.run(command, capture_output=True) + output = result.stderr.decode("utf-8") + logger.debug("output:\n{%s}", output) + + if result.returncode != 0: + raise StrobelightCLIProfilerError( + f"failed to start strobelight profiling, error in run_async:{output}" + ) + + if match := re.search(r"INFO Run Id: (-?\d+)", output): + self.current_run_id = int(match.group(1)) + return + + raise StrobelightCLIProfilerError( + f"failed to start strobelight profiling, unexpected result {output}" + ) + + def _wait_for_running(self, counter: int = 0) -> None: + if counter > 20: + raise StrobelightCLIProfilerError( + "wait_for_running called more than 20 times" + ) + + command = ["strobeclient", "getRunStatus", "--run-id", f"{self.current_run_id}"] + logger.debug("running command: %s", _command_to_string(command)) + result = subprocess.run(command, capture_output=True) + output = result.stderr.decode("utf-8") + logger.debug("output:\n{%s}", output) + + if result.returncode != 0: + raise StrobelightCLIProfilerError( + f"failed to start strobelight profiling, error in wait_for_running:{output}" + ) + + if match := re.search("Profile run status: (.*)", output): + current_status = match.group(1) + if current_status == "RUNNING": + return + elif current_status == "PREPARING": + time.sleep(10) + self._wait_for_running(counter + 1) + return + else: + raise StrobelightCLIProfilerError(f"unexpected {current_status} phase") + + raise StrobelightCLIProfilerError(f"unexpected output\n: {output} ") + + def _stop_run(self) -> None: + command = ["strobeclient", "stopRun", "--run-id", str(self.current_run_id)] + logger.debug("running command: %s", _command_to_string(command)) + result = subprocess.run(command, capture_output=True) + output = result.stderr.decode("utf-8") + logger.debug("output:\n{%s}", output) + + if result.returncode != 0: + raise StrobelightCLIProfilerError( + f"failed to stop strobelight profiling, return code is not 0 :{output}" + ) + + if match := re.search("INFO ::1:(.*)", output): + current_status = match.group(1) + if current_status.__contains__("Success!"): + return + else: + raise StrobelightCLIProfilerError( + f"failed to stop strobelight profiling, got {current_status} result" + ) + + raise StrobelightCLIProfilerError(f"unexpected output\n: {output} ") + + def _get_results(self) -> None: + command = ["strobeclient", "getRunStatus", "--run-id", str(self.current_run_id)] + logger.debug("running command: %s", _command_to_string(command)) + result = subprocess.run(command, capture_output=True) + output = result.stderr.decode("utf-8") + logger.debug("output:\n{%s}", output) + + if result.returncode != 0: + raise StrobelightCLIProfilerError( + f"failed to extract profiling results, return code is not 0 : {output}" + ) + + if match := re.search("INFO ::1:(.*)", output): + current_status = match.group(1) + if current_status.__contains__("Profile run status: PROCESSING"): + time.sleep(10) + self._get_results() + return + elif not current_status.__contains__("Profile run finished with SUCCESS"): + raise StrobelightCLIProfilerError( + f"failed to extract profiling results, unexpected response {output}" + ) + + self.profile_result = [] + for item in re.findall( + r"(Total samples(.*)|GraphProfiler(.*)|Icicle view \(python stack\)(.*))", + output, + ): + self.profile_result += item[0] + logger.info(item[0]) + + def _stop_strobelight_no_throw( + self, + collect_results: bool, + ) -> None: + try: + # call stop run + self._stop_run() + logger.info("strobelight profiling stopped") + + logger.debug("collection stopped") + + if not collect_results: + return + + self._get_results() + except Exception: + logger.warning("error during stop_strobelight", exc_info=True) + + # Return true if strobelight started and is running. Never throw. + def _start_strobelight(self) -> bool: + strobelight_started = False + try: + self._run_async() + strobelight_started = True + logger.info("strobelight run id is: %s", self.current_run_id) + self._wait_for_running() + logger.info("strobelight profiling running") + return True + + except Exception: + logger.warning("error during start_strobelight:", exc_info=True) + if strobelight_started: + self._stop_strobelight_no_throw(collect_results=False) + return False + + def profile( + self, work_function: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs + ) -> _R | None: + self.current_run_id = None + self.profile_result = None + + if locked := StrobelightCLIFunctionProfiler._lock.acquire(False): + if not locked: + if self.stop_at_error: + raise StrobelightCLIProfilerError("concurrent runs not supported") + + logger.warning("concurrent runs not supported") + return work_function(*args, **kwargs) + + started = self._start_strobelight() + if not started: + if self.stop_at_error: + StrobelightCLIFunctionProfiler._lock.release() + raise StrobelightCLIProfilerError( + "failed to start strobelight profiling" + ) + result = work_function(*args, **kwargs) + StrobelightCLIFunctionProfiler._lock.release() + return result + + try: + logger.debug("collection started") + start = timer() + result = work_function(*args, **kwargs) + end = timer() + total_time = end - start # Time in seconds, e.g. 5.38091952400282 + logger.info("work function took %s seconds", total_time) + self._stop_strobelight_no_throw(collect_results=True) + StrobelightCLIFunctionProfiler._lock.release() + return result + except Exception as error: + logger.warning("work function throw exception", exc_info=True) + self._stop_strobelight_no_throw(collect_results=False) + StrobelightCLIFunctionProfiler._lock.release() + raise error + return None + + +# A function decorator that wraps profile, if no profiler is provided one with +# default args is created. A function can be annotated as: +# @strobelight() +# @strobelight(profiler = StrobelightFunctionProfiler(stop_at_error=True,..)) +# @strobelight(stop_at_error=True,...) +def strobelight( + profiler: StrobelightCLIFunctionProfiler | None = None, **kwargs: Any +) -> Callable[[Callable[_P, _R]], Callable[_P, _R | None]]: + if not profiler: + profiler = StrobelightCLIFunctionProfiler(**kwargs) + + def strobelight_inner( + work_function: Callable[_P, _R], + ) -> Callable[_P, _R | None]: + @functools.wraps(work_function) + def wrapper_function(*args: _P.args, **kwargs: _P.kwargs) -> _R | None: + # pyrefly: ignore [bad-argument-type] + return profiler.profile(work_function, *args, **kwargs) + + return wrapper_function + + return strobelight_inner diff --git a/.venv/lib/python3.12/site-packages/torch/_strobelight/compile_time_profiler.py b/.venv/lib/python3.12/site-packages/torch/_strobelight/compile_time_profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..a990e49f233226a4ea2ae5a4d53d7d33dba9e980 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_strobelight/compile_time_profiler.py @@ -0,0 +1,224 @@ +# mypy: disallow-untyped-defs + +import json +import logging +import os +import re +import subprocess +from datetime import datetime +from socket import gethostname +from typing import Any + +from torch._strobelight.cli_function_profiler import StrobelightCLIFunctionProfiler + + +logger = logging.getLogger("strobelight_compile_time_profiler") + +console_handler = logging.StreamHandler() +formatter = logging.Formatter( + "%(name)s, line %(lineno)d, %(asctime)s, %(levelname)s: %(message)s" +) +console_handler.setFormatter(formatter) + +logger.addHandler(console_handler) +logger.setLevel(logging.INFO) +logger.propagate = False + + +def get_fburl(url: str) -> str: + short_url = url + # Attempt to shorten the URL + try: + result = subprocess.run( + ["fburl", url], capture_output=True, stdin=subprocess.DEVNULL + ) + if result.returncode == 0: + short_url = result.stdout.decode("utf-8") + except Exception as e: + logger.warning("URL shortening failed: %s, using long URL", repr(e)) + return short_url + + +def get_strobelight_url(identifier: str) -> str: + scuba_json = { + "aggregateList": [], + "aggregation_field": "async_stack_complete", + "b_constraints": [[]], + "c_constraints": [[]], + "cols": ["namespace_id", "namespace_process_id"], + "compare": "none", + "constraints": [ + [{"column": "sample_tags", "op": "all", "value": [f'["{identifier}"]']}] + ], + "derivedCols": [], + "end": "now", + "enumCols": [], + "filterMode": "DEFAULT", + "hideEmptyColumns": "false", + "ignoreGroupByInComparison": "false", + "is_timeseries": "false", + "mappedCols": [], + "metric": "count", + "modifiers": [], + "order": "weight", + "order_desc": "true", + "param_dimensions": [ + {"dim": "py_async_stack", "op": "edge", "param": "0", "anchor": "0"} + ], + "purposes": [], + "return_remainder": "false", + "samplingRatio": "1", + "should_pivot": "false", + "start": "-30 days", + "timezone": "America/Los_Angeles", + "top": 10000, + } + scuba_url_prefix = "https://www.internalfb.com/intern/scuba/query/?dataset=pyperf_experimental/on_demand&drillstate=" + scuba_url_suff = "&view=GraphProfilerView&&normalized=1726332703&pool=uber" + long_url = scuba_url_prefix + json.dumps(scuba_json) + scuba_url_suff + return get_fburl(long_url) + + +class StrobelightCompileTimeProfiler: + success_profile_count: int = 0 + failed_profile_count: int = 0 + ignored_profile_runs: int = 0 + inside_profile_compile_time: bool = False + enabled: bool = False + + # A regex that can be used to filter out what frames to profile. ex: "1/.*" + frame_id_filter: str | None = os.environ.get("COMPILE_STROBELIGHT_FRAME_FILTER") + + # A unique identifier that is used as the run_user_name in the strobelight profile to + # associate all compile time profiles together. + identifier: str | None = None + + current_phase: str | None = None + + profiler: Any | None = None + + max_stack_length: int = int( + os.environ.get("COMPILE_STROBELIGHT_MAX_STACK_LENGTH", 500) + ) + max_profile_time: int = int( + os.environ.get("COMPILE_STROBELIGHT_MAX_PROFILE_TIME", 60 * 30) + ) + # Collect sample each x cycles. + sample_each: int = int( + float(os.environ.get("COMPILE_STROBELIGHT_SAMPLE_RATE", 1e7)) + ) + + @classmethod + def get_frame(cls) -> str: + from torch._guards import CompileContext + + return (str)(CompileContext.current_trace_id()) + + @classmethod + def enable(cls, profiler_class: Any = StrobelightCLIFunctionProfiler) -> None: + if cls.enabled: + logger.info("compile time strobelight profiling already enabled") + return + + logger.info("compile time strobelight profiling enabled") + + if profiler_class is StrobelightCLIFunctionProfiler: + import shutil + + if not shutil.which("strobeclient"): + logger.info( + "strobeclient not found, can't enable compile time strobelight profiling, seems" + "like you are not on a FB machine." + ) + return + + cls.enabled = True + cls._cls_init() + # profiler_class should have public API similar to that of StrobelightCLIFunctionProfiler. + # we have pass different functionProfilerClass for meta-internal fbcode targets. + # NB: the actual implementation in Meta is at + # fbcode/caffe2/fb/strobelight/function_profiler.py + cls.profiler = profiler_class( + sample_each=cls.sample_each, + max_profile_duration_sec=cls.max_profile_time, + stack_max_len=cls.max_stack_length, + async_stack_max_len=cls.max_stack_length, + run_user_name="pt2-profiler/" + + os.environ.get("USER", os.environ.get("USERNAME", "")), + sample_tags={cls.identifier}, + ) + + @classmethod + def _cls_init(cls) -> None: + cls.identifier = "{date}{pid}{hostname}".format( + date=datetime.now().strftime("%Y-%m-%d-%H:%M:%S"), + pid=os.getpid(), + hostname=gethostname(), + ) + + logger.info("Unique sample tag for this run is: %s", cls.identifier) + logger.info( + "URL to access the strobelight profile at the end of the run: %s", + get_strobelight_url(cls.identifier), + ) + + @classmethod + def _log_stats(cls) -> None: + logger.info( + "%s strobelight success runs out of %s non-recursive compilation events.", + cls.success_profile_count, + cls.success_profile_count + cls.failed_profile_count, + ) + + # TODO use threadlevel meta data to tags to record phases. + @classmethod + def profile_compile_time( + cls, func: Any, phase_name: str, *args: Any, **kwargs: Any + ) -> Any: + def skip() -> Any: + return func(*args, **kwargs) + + if not cls.enabled: + return skip() + + if cls.profiler is None: + logger.error("profiler is not set") + return + + frame_id = cls.get_frame() + + if cls.inside_profile_compile_time: + cls.ignored_profile_runs += 1 + logger.info( + "profile_compile_time is requested for phase: %s, frame %s, while already in running phase: %s," + "frame %s, recursive call ignored", + phase_name, + frame_id, + cls.current_phase, + frame_id, + ) + return skip() + + if cls.frame_id_filter is not None: + should_run = re.match(cls.frame_id_filter, frame_id) is not None + if not should_run: + logger.info( + "profiling frame %s is skipped due to frame_id_filter %s", + frame_id, + cls.frame_id_filter, + ) + return skip() + + cls.inside_profile_compile_time = True + cls.current_phase = phase_name + logger.info("profiling frame %s", frame_id) + work_result = cls.profiler.profile(func, *args, **kwargs) + + if cls.profiler.profile_result is not None: + cls.success_profile_count += 1 + else: + cls.failed_profile_count += 1 + + cls._log_stats() + cls.inside_profile_compile_time = False + return work_result diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/__init__.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc42f39cbddaf5bdc919cef88d5f049fdba2634 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/__init__.py @@ -0,0 +1,17 @@ +import torch +from torch._subclasses.fake_tensor import ( + DynamicOutputShapeException, + FakeTensor, + FakeTensorMode, + UnsupportedFakeTensorException, +) +from torch._subclasses.fake_utils import CrossRefFakeMode + + +__all__ = [ + "FakeTensor", + "FakeTensorMode", + "UnsupportedFakeTensorException", + "DynamicOutputShapeException", + "CrossRefFakeMode", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddfd16f49d5ea15c9ceb622784aedd2c510dad15 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/_fake_tensor_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/_fake_tensor_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a972cea388a084dcfb5cbedafa52a3ea0ecca4f5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/_fake_tensor_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_impls.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_impls.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aca62a9c65e58ed2873be77e3fe5635e1a7d82a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_impls.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3bf0965c0a98bb24aecb508da9793a4f3b77fc8e38453c0f38c3efb481749da3 +size 106244 diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..177b775139d99fc67257229917e09884ece36794 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff47e45b1901049a4ec8e953084452992b662b022e0e5555b1b64aaeb7b1be41 +size 147288 diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34fd62a593a0ce963cbf9a773bb9e9ce7aa73e31 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/functional_tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/functional_tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3ce1c680ca5cf99601f556ee89c79f0fc4e5322 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/functional_tensor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/meta_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/meta_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66ec3fe8ad32c35841e803adcb91691b99ac8850 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/meta_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/schema_check_mode.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/schema_check_mode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..454ec9ab8b736e4028cf9fa080ec64de52661e72 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/schema_check_mode.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/_fake_tensor_utils.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/_fake_tensor_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..240b3cf9958f9304368a5b90b9b1bb3400250da7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/_fake_tensor_utils.py @@ -0,0 +1,275 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import torch +from torch import SymInt +from torch.fx.experimental.sym_node import SymNode +from torch.types import py_sym_types, PySymType + + +if TYPE_CHECKING: + import sympy + + from torch.fx.experimental.symbolic_shapes import ShapeEnv + + from .fake_tensor import _DispatchCacheKey, _MetadataIntLike + + +@dataclass(frozen=True, slots=True) +class _DeconstructedSymNode: + """ + Represents a SymNode without the associated ShapeEnv + """ + + # n.b. keep the same protocol as SymNode + _expr: sympy.Expr + pytype: type + _hint: int | float | bool | None + constant: int | float | bool | None + fx_node: torch.fx.Node + + @staticmethod + def from_node(node: SymNode) -> _DeconstructedSymNode: + return _DeconstructedSymNode( + node._expr, + node.pytype, + # pyrefly: ignore[bad-argument-type] + node._hint, + node.constant, + # pyrefly: ignore[bad-argument-type] + node.fx_node, + ) + + def extract(self, shape_env: ShapeEnv) -> SymNode: + return SymNode( + self._expr, shape_env, self.pytype, self._hint, self.constant, self.fx_node + ) + + def __str__(self) -> str: + return str(self._expr) + + def __repr__(self) -> str: + return f"_DeconstructedSymNode{{{self._expr!r}, {self.pytype!r}, {self._hint!r}, {self.constant!r}, {self.fx_node!r}}}" + + def __eq__(self, other: object) -> bool: + raise NotImplementedError + + def __hash__(self) -> int: + raise NotImplementedError + + # _value_eq to match SymNode + def _value_eq(self, other: object) -> bool: + if isinstance(other, (SymNode, _DeconstructedSymNode)): + return ( + self._expr == other._expr + and self.pytype == other.pytype + and self._hint == other._hint + and self.constant == other.constant + and self.fx_node == other.fx_node + ) + else: + return False + + # _value_hash to match SymNode + def _value_hash(self) -> int: + return hash((self._expr, self.pytype, self._hint, self.constant, self.fx_node)) + + +@dataclass(frozen=True, slots=True) +class _DeconstructedSymType: + """ + Represents a SymInt, SymFloat, SymBool without the associated ShapeEnv + """ + + ty: type[PySymType] + node: _DeconstructedSymNode + + @staticmethod + def from_sym_type(value: PySymType) -> _DeconstructedSymType: + # pyrefly: ignore [bad-argument-type] + return _DeconstructedSymType(type(value), value.node) + + def extract(self, shape_env: ShapeEnv) -> PySymType: + return self.ty(self.node.extract(shape_env)) + + def __str__(self) -> str: + return f"{self.ty}({self.node})" + + def __repr__(self) -> str: + return f"_DeconstructedSymType({self.ty}, {self.node!r})" + + def __eq__(self, other: object) -> bool: + return NotImplemented + + def __hash__(self) -> int: + return NotImplemented + + +@dataclass(frozen=True, slots=True) +class _InputBackref: + value: int + + +@dataclass(slots=True) +class _PySymInputStub: + """ + Represents a SymInt in the cached key. Needed because SymInt doesn't + support __eq__ or __hash__ directly. + """ + + # value can be: + # PySymType: This is the 'normal' SymInt value, wrapped so we can use + # hash/eq as value hash/eq (normally SymInt does object + # hash/eq). + # _DeconstructedSymType: This is used when storing the _PySymInputStub in + # the cache to avoid cyclic ShapeEnv references. + # _InputBackref: This is a back-reference to a previous _PySymInputStub in + # the key. + value: PySymType | _DeconstructedSymType | _InputBackref + + def __init__( + self, value: PySymType | _DeconstructedSymType | _InputBackref + ) -> None: + # For inputs (values in the `key`) we need to keep the PySymType intact + # - this way if we need to reuse it as an output we can properly copy + # the original value. + self.value = value + + def strip_shape_env(self) -> None: + if isinstance(self.value, py_sym_types): + self.value = _DeconstructedSymType.from_sym_type(self.value) + + def extract(self, shape_env: ShapeEnv) -> PySymType: + if isinstance(self.value, _DeconstructedSymType): + return self.value.extract(shape_env) + else: + # We should never see an _InputBackref here - anyone extracting a + # value should be pulling from the original entry (the one this + # backref points at). + if isinstance(self.value, _InputBackref): + raise AssertionError( + "Cannot extract value from _InputBackref - use the original entry" + ) + return self.value + + def __str__(self) -> str: + return str(self.value) + + def __repr__(self) -> str: + return f"_PySymInputStub({self.value!r})" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _PySymInputStub): + return False + elif isinstance(self.value, _InputBackref) or isinstance( + other.value, _InputBackref + ): + return self.value == other.value # type: ignore[bad-return] + else: + # pyrefly: ignore [bad-argument-type] + return self.value.node._value_eq(other.value.node) + + def __hash__(self) -> int: + if isinstance(self.value, _InputBackref): + return hash(self.value) + else: + return self.value.node._value_hash() + + +@dataclass(slots=True) +class _SymIntOutputStub: + """ + Represents a SymInt in the cached output. + """ + + # This is either an `int` which represents the index in the key to copy the + # SymNode from or it's the deconstructed SymNode itself. + value: int | _DeconstructedSymNode + + def __init__(self, value: SymInt, key_path: int | None) -> None: + if key_path is None: + self.value = _DeconstructedSymNode.from_node(value.node) + else: + self.value = key_path + + def extract(self, key: _DispatchCacheKey, shape_env: ShapeEnv) -> SymInt: + if isinstance(self.value, _DeconstructedSymNode): + return SymInt(self.value.extract(shape_env)) + else: + src = key.key[self.value] + if not isinstance(src, _PySymInputStub) or not isinstance( + src.value, SymInt + ): + raise AssertionError( + f"Expected _PySymInputStub with SymInt value, got {type(src)} " + f"with {type(src.value) if isinstance(src, _PySymInputStub) else 'N/A'}" + ) + return src.value + + def __repr__(self) -> str: + return f"_SymIntOutputStub({self.value!r})" + + def __eq__(self, other: object) -> bool: + raise NotImplementedError + + def __hash__(self) -> int: + raise NotImplementedError + + +@dataclass(slots=True) +class _CacheKeyState: + """ + State used while building our cache key. + """ + + # We track the SymNodes so when we get the output we can see if it exactly + # matches one of the inputs so we can uncache it properly. + sym_node_lookup: dict[int, int] # id(SymNode) -> index + + # This is a list of all seen input sympy.Symbols. We use it when building + # the cache entry to see if the output value has any symbols that we didn't + # see on input. See _has_unrepresented_symbols(). + known_symbols: set[sympy.Symbol] + + # There are cases where we're asked to perform an op when we have no + # ShapeEnv on the FakeTensorMode - but for SymNodes we MUST have a + # ShapeEnv. So as we scan if we see a SymNode (with a ShapeEnv) we record it + # here. + shape_env: ShapeEnv | None + + def __init__(self, shape_env: ShapeEnv | None = None) -> None: + self.sym_node_lookup = {} + self.known_symbols = set() + self.shape_env = shape_env + + def cache_on_shape_env(self) -> bool: + """ + Returns true if the CacheKey needs to be cached on the ShapeEnv + rather than the global cache. + + If our inputs contain a SymNode then we can't cache this operation on + the global cache because the cached output will implicitly depend on + guard values which might not be true on some other ShapeEnv. So unless + we're also going to cache the guards we need to cache this operation on + the ShapeEnv instead of globally. + """ + return bool(self.sym_node_lookup) + + def convert_sym_int(self, result: list[object], arg: SymInt) -> None: + node_id = id(arg.node) + if node_id in self.sym_node_lookup: + result.append(_InputBackref(self.sym_node_lookup[node_id])) + else: + self.sym_node_lookup[node_id] = len(result) + self.known_symbols.update(arg.node.expr.free_symbols) + if self.shape_env is None: + self.shape_env = arg.node.shape_env + result.append(_PySymInputStub(arg)) + + def convert_output(self, arg: _MetadataIntLike) -> _MetadataIntLike: + if isinstance(arg, SymInt): + return _SymIntOutputStub(arg, self.sym_node_lookup.get(id(arg.node), None)) + else: + return arg diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/__init__.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ec81cde7e03aee9e1d140464532876d70fe1cf48 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/__init__.py @@ -0,0 +1,9 @@ +from ._core import ComplexTensor +from ._ops import ComplexTensorMode, is_complex_tensor, WrapComplexMode + + +__all__ = ["ComplexTensor", "ComplexTensorMode", "is_complex_tensor", "WrapComplexMode"] + +ComplexTensor.__module__ = __name__ +ComplexTensorMode.__module__ = __name__ +is_complex_tensor.__module__ = __name__ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9ea7e1ff68f593565552f095f2b7c69ca0a63a8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/__pycache__/_core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/__pycache__/_core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d5e080106bdeddcfc916ee378ae2bcdea7f88cd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/__pycache__/_core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_core.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_core.py new file mode 100644 index 0000000000000000000000000000000000000000..dfcabefd4687c939446b892919ea355dc24a57ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_core.py @@ -0,0 +1,176 @@ +from __future__ import annotations + +from typing import Any, TYPE_CHECKING +from typing_extensions import Self + +import torch +from torch import Tensor +from torch.autograd import Function + + +if TYPE_CHECKING: + from torch._ops import OpOverload + from torch._prims_common import DeviceLikeType + from torch.autograd.function import FunctionCtx + + +class ComplexTensor(Tensor): + """A class that decomposes all ops on complex Tensors into their real and imaginary parts.""" + + _re: Tensor + _im: Tensor + + def __new__( + cls, + real: Tensor, + imag: Tensor, + /, + ) -> Self: + """Initialize a ComplexTensor from its real and imaginary parts.""" + from ._ops.common import REAL_TO_COMPLEX + + # TODO (hameerabbasi): `torch.compile` sometimes fails here without making these + # contiguous. Why? + real = real.contiguous() + imag = imag.contiguous() + + # TODO (hameerabbasi): + # What should we do with dtype? + # We could convert to the complex type (float32 -> complex64), but we + # can't use that model for say `bfloat16` which does not have a + # corresponding complex dtype. + # If we want to support this complex rep using any float type (see + # https://github.com/pytorch/pytorch/issues/95100) + # We either need to: + # 1) add the complex types for say `complexbf32`, knowing they can't really be used anywhere + # else. + # 2) We use the real float dtype here, and it is up to the user to know + # that dtype=float here really means complex<2xSize> with dtype + # matching that of re/im parts alone + # I'm going with 1 for now, so that I can make gradcheck and some complex + # ops work properly, but might want to discuss this in the RFP. + dtype = REAL_TO_COMPLEX.get(real.dtype) + if dtype is None: + raise TypeError( + "Unsupported dtype for constituent tensors. Supported dtypes are: " + f"{set(REAL_TO_COMPLEX.keys())!r}." + ) + storage_offset = real.storage_offset() + strides = real.stride() + layout = real.layout + pin_memory = real.is_pinned() + + if real.shape != imag.shape: + raise AssertionError(f"Expected imag shape {real.shape}, got {imag.shape}") + if real.device != imag.device: + raise AssertionError( + f"Expected imag device {real.device}, got {imag.device}" + ) + if real.dtype != imag.dtype: + raise AssertionError(f"Expected imag dtype {real.dtype}, got {imag.dtype}") + if real.is_pinned() != imag.is_pinned(): + raise AssertionError( + f"Expected imag pinning {real.is_pinned()}, got {imag.is_pinned()}" + ) + + res = Tensor._make_wrapper_subclass( # type: ignore[attr-defined] + cls, + real.shape, + device=real.device, + dtype=dtype, + storage_offset=storage_offset, + strides=strides, + pin_memory=pin_memory, + layout=layout, + requires_grad=False, + ) + res._re = real.detach() + res._im = imag.detach() + + return res + + def __init__(self, *a: Any, **kw: Any) -> None: + super().__init__() + + @property + def re(self) -> Tensor: + return self._re + + @property + def im(self) -> Tensor: + return self._im + + @property + def real(self) -> Tensor: # type: ignore[bad-override] + return self.re + + @real.setter + def real(self, value: Tensor) -> None: + self.re[...] = value + + @property + def imag(self) -> Tensor: # type: ignore[bad-override] + return self.im + + @imag.setter + def imag(self, value: Tensor) -> None: + self.im[...] = value + + @classmethod + def __torch_dispatch__( # type: ignore[bad-override] + cls, + func: OpOverload, + types: tuple[type, ...], + # pyrefly: ignore [implicit-any] + args: tuple = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + from ._ops.common import lookup_complex + + kwargs = {} if kwargs is None else kwargs + + impl = lookup_complex(func, *args, **kwargs) + if impl is None: + return NotImplemented + + return impl(*args, **kwargs) + + @staticmethod + def from_interleaved(t: Tensor) -> ComplexTensor: + re = torch.real(t) + im = torch.imag(t) if t.dtype.is_complex else torch.zeros_like(t) + return Complex.apply(re, im) + + def as_interleaved(self) -> Tensor: + return torch.complex(self.re, self.im) + + @staticmethod + def __tensor_unflatten__( + inner_tensors: dict[str, Tensor], + meta: Any, + outer_size: tuple[int, ...], + outer_stride: tuple[int, ...], + ) -> ComplexTensor: + re, im = inner_tensors["_re"], inner_tensors["_im"] + return ComplexTensor(re, im) + + def __tensor_flatten__(self) -> tuple[list[str], Any]: + return ["_re", "_im"], None + + def __repr__(self, *, tensor_contents: object | None = None) -> str: + return f"ComplexTensor({self._re!r}, {self._im!r})" + + def is_pinned(self, device: DeviceLikeType | None = None) -> bool: + return self._re.is_pinned(device) + + +class Complex(Function): + @staticmethod + def forward( # type: ignore[bad-override] + ctx: FunctionCtx, real: Tensor, imag: Tensor + ) -> ComplexTensor: + return ComplexTensor(real, imag) + + @staticmethod + def backward(ctx: FunctionCtx, grad_output: ComplexTensor) -> tuple[Tensor, Tensor]: # type: ignore[bad-override] + return grad_output.real, grad_output.imag diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__init__.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e9f6f0d87aab073365b993f7bfac9dd2050431c1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__init__.py @@ -0,0 +1,5 @@ +from . import aten, prims +from .common import ComplexTensorMode, is_complex_tensor, WrapComplexMode + + +__all__ = ["ComplexTensorMode", "is_complex_tensor", "aten", "prims", "WrapComplexMode"] diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee5876033dbc9ffb449e5136cc13934670636184 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__pycache__/aten.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__pycache__/aten.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a0ac1099301c5fd1aa4ad6c3a798591af69590d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__pycache__/aten.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__pycache__/common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c5f93b9a7f57b83c52d42819dc13e4efde064fc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__pycache__/common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__pycache__/prims.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__pycache__/prims.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3efc34e00f9d7fd88ff99c9a4f2d16dbeb56df42 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/__pycache__/prims.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/aten.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/aten.py new file mode 100644 index 0000000000000000000000000000000000000000..ca290d5f9560718d83fe5f4d7eea3218dbdab65c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/aten.py @@ -0,0 +1,1108 @@ +from __future__ import annotations + +import warnings +from typing import Any, TYPE_CHECKING + +import torch + +from .._core import ComplexTensor +from .common import ( + _get_func_name, + COMPLEX_TO_REAL, + complex_to_real_dtype, + is_complex, + OpType, + promote_tensors, + register_binary_nonlinear, + register_complex, + register_error, + register_force_test, + register_simple, + split_complex_arg, + split_complex_tensor, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + +aten = torch.ops.aten + + +def register_binary_linear(op: OpType) -> Callable[..., Any]: + def impl_with_alpha( + lhs: ComplexTensor, + rhs: ComplexTensor, + *args: Any, + alpha: int | float | complex, + **kwargs: Any, + ) -> ComplexTensor: + return op(lhs, aten.mul(rhs, alpha, *args, **kwargs), *args, **kwargs) + + def impl( + lhs: ComplexTensor, rhs: ComplexTensor, *args: Any, **kwargs: Any + ) -> ComplexTensor: + alpha = kwargs.pop("alpha", None) + if alpha is not None: + return impl_with_alpha(lhs, rhs, *args, alpha=alpha, **kwargs) + a_r, a_i = split_complex_arg(lhs) + b_r, b_i = split_complex_arg(rhs) + out_dt, (a_r, a_i, b_r, b_i) = promote_tensors(a_r, a_i, b_r, b_i) + u = op(a_r, b_r, *args, **kwargs) + v = op(a_i, b_i, *args, **kwargs) + return ComplexTensor(u.to(out_dt), v.to(out_dt)) + + return register_complex(op, impl) + + +def register_binary_linear_inplace( + op: OpType, out_of_place_impl: Callable[..., Any] +) -> Callable[..., Any]: + def impl( + lhs: ComplexTensor, rhs: ComplexTensor, *args: Any, **kwargs: Any + ) -> ComplexTensor: + result = out_of_place_impl(lhs, rhs, *args, **kwargs) + lhs.copy_(result) + return lhs + + return register_complex(op, impl) + + +@register_complex(aten.real) +def real_impl(self: ComplexTensor) -> torch.Tensor: + return self.re + + +@register_complex(aten.imag) +def imag_impl(self: ComplexTensor) -> torch.Tensor: + return self.im + + +@register_complex(aten.is_pinned) +def is_pinned_impl(self: ComplexTensor, device: torch.device | None = None) -> bool: + return self.is_pinned(device) + + +SIMPLE_OPS_LIST = [ + aten.slice, + aten.flatten, + aten.view, + aten.diagonal, + aten.expand, + aten.unsqueeze, + aten.unsqueeze_, + aten.mean, + aten.sum, + aten.clone, + aten.flip, + aten.permute, + aten.repeat, + aten.index_select, + aten.split, + aten.split_with_sizes, + aten.cumsum, + aten.detach, + aten.select, + aten.squeeze, + aten.zero_, + aten.transpose, + aten.t, + aten.gather, + aten.neg, +] + +for simple_op in SIMPLE_OPS_LIST: + globals()[_get_func_name(simple_op)] = register_simple(simple_op) + +# TODO (hameerabbasi): Not being tested +SIMPLE_FORCE_TESTED_OPS = [ + aten.col2im, + aten.alias, + aten.lift_fresh, + aten._unsafe_view, + aten.index, + aten.avg_pool2d, + aten.avg_pool3d, + aten.avg_pool2d_backward, + aten.avg_pool3d_backward, + aten.masked_scatter_backward, + aten.select_backward, + aten.slice_backward, + aten.embedding, +] + +for simple_op in SIMPLE_FORCE_TESTED_OPS: + globals()[_get_func_name(simple_op)] = register_force_test( + simple_op, register_simple(simple_op) + ) + +del simple_op + +# some binary ops which we can stamp out +mul_impl = register_binary_nonlinear(aten.mul) +mul__impl = register_binary_linear_inplace(aten.mul_, mul_impl) +mm_impl = register_binary_nonlinear(aten.mm) +dot_impl = register_binary_nonlinear(aten.dot) +bmm_impl = register_binary_nonlinear(aten.bmm) + +# TODO (hameerabbasi): Not being tested +convolution_impl = register_force_test( + aten.convolution, register_binary_nonlinear(aten.convolution) +) + +slice_scatter_impl = register_force_test( + aten.slice_scatter, register_binary_linear(aten.slice_scatter) +) +select_scatter_impl = register_force_test( + aten.select_scatter, register_binary_linear(aten.select_scatter) +) + +add_impl = register_binary_linear(aten.add) +add__impl = register_binary_linear_inplace(aten.add_, add_impl) +sub_impl = register_binary_linear(aten.sub) +sub__impl = register_binary_linear_inplace(aten.sub_, sub_impl) +copy_impl = register_binary_linear(aten.copy) +diagonal_scatter_impl = register_binary_linear(aten.diagonal_scatter) +fill_impl = register_binary_linear(aten.fill) +fill__impl = register_binary_linear_inplace(aten.fill_, fill_impl) + + +@register_complex(aten.rsub) +def rsub_impl( + lhs: ComplexTensor, rhs: ComplexTensor, alpha: int | float | complex | None = None +) -> ComplexTensor: + if alpha is None: + return torch.sub(rhs, lhs) # type: ignore[bad-return] + return torch.sub(rhs, lhs, alpha=alpha) # type: ignore[bad-return] + + +@register_complex(aten.div) +@register_complex(aten.true_divide) +def div_impl( + lhs: ComplexTensor, rhs: ComplexTensor, *, rounding_mode: str | None = None +) -> ComplexTensor: + if rounding_mode is not None: + raise NotImplementedError( + "`rounding_mode` other than `None` not implemented for`ComplexTensor`." + ) + a_r, a_i = split_complex_arg(lhs) + if not is_complex(rhs): + return ComplexTensor(a_r / rhs, a_i / rhs) + b_r, b_i = split_complex_arg(rhs) + out_dt, (a_r, a_i, b_r, b_i) = promote_tensors(a_r, a_i, b_r, b_i) + num_r = a_r * b_r + a_i * b_i + num_i = a_i * b_r - a_r * b_i + den = b_r * b_r + b_i * b_i + return ComplexTensor( + (num_r / den).to(out_dt), + (num_i / den).to(out_dt), + ) + + +@register_complex(aten.reciprocal) +def reciprocal_impl(self: ComplexTensor) -> ComplexTensor: + self_r, self_i = split_complex_tensor(self) + out_dt, (self_r, self_i) = promote_tensors(self_r, self_i) + den = self_r * self_r + self_i * self_i + return ComplexTensor( + aten.div(self_r, den).to(out_dt), + aten.div(-self_i, den).to(out_dt), + ) + + +# reductions +@register_complex(aten.prod) +def prod_impl(self: ComplexTensor, *args: Any, **kwargs: Any) -> ComplexTensor: + out_dt, (self,) = promote_tensors(self) + dtype = kwargs.pop("dtype", out_dt) + kwargs["dtype"] = complex_to_real_dtype(self.dtype) + + prod_r = torch.prod(torch.abs(self), *args, **kwargs) + sum_phi = torch.sum(torch.angle(self), *args, **kwargs) + u = prod_r * torch.cos(sum_phi) + v = prod_r * torch.sin(sum_phi) + return ComplexTensor(u, v).to(dtype) # type: ignore[bad-return] + + +@register_complex(aten.complex) +def complex_impl(re: torch.Tensor, im: torch.Tensor) -> ComplexTensor: + return ComplexTensor(re, im) + + +@register_complex(aten.pow) +def pow_impl(self: ComplexTensor, exponent: ComplexTensor) -> ComplexTensor: + out_dt, (self, exponent) = promote_tensors(self, exponent) + return torch.exp(exponent * torch.log(self)).to(out_dt) # type: ignore[bad-return] + + +@register_complex(aten.cumprod) +def cumprod_impl(self: ComplexTensor, *args: Any, **kwargs: Any) -> ComplexTensor: + dtype = kwargs.pop("dtype", self.dtype) + kwargs["dtype"] = complex_to_real_dtype(dtype) + + prod_r = torch.cumprod(torch.abs(self), *args, **kwargs) + sum_phi = torch.cumsum(torch.angle(self), *args, **kwargs) + u = prod_r * torch.cos(sum_phi) + v = prod_r * torch.sin(sum_phi) + return ComplexTensor(u, v) + + +# unary funcs, +# most of these are simple or require some kind of identity +@register_complex(aten.abs) +def abs_impl(self: ComplexTensor) -> torch.Tensor: + x, y = split_complex_tensor(self) + out_dt, (x, y) = promote_tensors(x, y) + result = torch.hypot(x, y) + return result.to(out_dt) + + +@register_complex(aten.angle) +def angle_impl(self: ComplexTensor) -> torch.Tensor: + x, y = split_complex_tensor(self) + return torch.atan2(y, x) + + +@register_complex(aten.acos) +def acos_impl(self: ComplexTensor) -> ComplexTensor: + _, y = split_complex_tensor(self) + acosh_z = torch.acosh(self) + if not isinstance(acosh_z, ComplexTensor): + raise AssertionError(f"acosh_z must be a ComplexTensor, got {type(acosh_z)}") + acosh_z_re, acosh_z_im = split_complex_tensor(acosh_z) + sign_im = 2 * torch.signbit(y) - 1 + return ComplexTensor(torch.abs(acosh_z_im), sign_im * torch.abs(acosh_z_re)) + + +@register_complex(aten.asin) +def asin_impl(self: ComplexTensor) -> ComplexTensor: + x, y = split_complex_tensor(self) + asinh_iz = torch.asinh(ComplexTensor(-y, x)) + if not isinstance(asinh_iz, ComplexTensor): + raise AssertionError(f"asinh_iz must be a ComplexTensor, got {type(asinh_iz)}") + asinh_iz_re, asinh_iz_im = split_complex_tensor(asinh_iz) + return ComplexTensor(asinh_iz_im, -asinh_iz_re) + + +@register_complex(aten.atan) +def atan_impl(self: ComplexTensor) -> ComplexTensor: + x, y = split_complex_tensor(self) + tanh_iz = torch.atanh(ComplexTensor(-y, x)) + if not isinstance(tanh_iz, ComplexTensor): + raise AssertionError(f"tanh_iz must be a ComplexTensor, got {type(tanh_iz)}") + tanh_iz_re, tanh_iz_im = split_complex_tensor(tanh_iz) + return ComplexTensor(tanh_iz_im, -tanh_iz_re) + + +@register_complex(aten.asinh) +def asinh_impl(self: ComplexTensor) -> ComplexTensor: + out_dt, (self,) = promote_tensors(self) + return torch.log(self + torch.sqrt(self * self + 1)).to(out_dt) # type: ignore[bad-return] + + +@register_complex(aten.acosh) +def acosh_impl(self: ComplexTensor) -> ComplexTensor: + out_dt, (self,) = promote_tensors(self) + return torch.log(self + torch.sqrt(self * self - 1)).to(out_dt) # type: ignore[bad-return] + + +@register_complex(aten.atanh) +def atanh_impl(self: ComplexTensor) -> ComplexTensor: + x, y = split_complex_tensor(self) + out_dt, (x, y) = promote_tensors(x, y) + + ret = 0.5 * ( + torch.log(ComplexTensor(1 + x, y)) - torch.log(ComplexTensor(1 - x, -y)) + ) + if not isinstance(ret, ComplexTensor): + raise AssertionError(f"ret must be a ComplexTensor, got {type(ret)}") + ret_re, ret_im = split_complex_tensor(ret) + + return ComplexTensor(ret_re.to(out_dt), ret_im.to(out_dt)) + + +@register_complex(aten.cos) +def cos_impl(self: ComplexTensor) -> ComplexTensor: + x, y = split_complex_tensor(self) + return torch.cosh(ComplexTensor(-y, x)) # type: ignore[bad-return] + + +@register_complex(aten.cosh) +def cosh_impl(self: ComplexTensor) -> ComplexTensor: + x, y = split_complex_tensor(self) + out_dt, (x, y) = promote_tensors(x, y) + u = torch.cosh(x) * torch.cos(y) + v = torch.sinh(x) * torch.sin(y) + return ComplexTensor(u.to(out_dt), v.to(out_dt)) + + +@register_complex(aten.sin) +def sin_impl(self: ComplexTensor) -> ComplexTensor: + x, y = split_complex_tensor(self) + sinh_iz = torch.sinh(ComplexTensor(-y, x)) + if not isinstance(sinh_iz, ComplexTensor): + raise AssertionError(f"sinh_iz must be a ComplexTensor, got {type(sinh_iz)}") + sinh_iz_re, sinh_iz_im = split_complex_tensor(sinh_iz) + return ComplexTensor(sinh_iz_im, -sinh_iz_re) + + +@register_complex(aten.sinh) +def sinh_impl(self: ComplexTensor) -> ComplexTensor: + x, y = split_complex_tensor(self) + out_dt, (x, y) = promote_tensors(x, y) + u = torch.sinh(x) * torch.cos(y) + v = torch.cosh(x) * torch.sin(y) + return ComplexTensor(u.to(out_dt), v.to(out_dt)) + + +@register_complex(aten.tan) +def tan_impl(self: ComplexTensor) -> ComplexTensor: + x, y = split_complex_tensor(self) + tanh_iz = torch.tanh(ComplexTensor(-y, x)) + if not isinstance(tanh_iz, ComplexTensor): + raise AssertionError(f"tanh_iz must be a ComplexTensor, got {type(tanh_iz)}") + tanh_iz_re, tanh_iz_im = split_complex_tensor(tanh_iz) + return ComplexTensor(tanh_iz_im, -tanh_iz_re) + + +@register_complex(aten.tanh) +def tanh_impl(self: ComplexTensor) -> ComplexTensor: + x, y = split_complex_tensor(self) + out_dt, (x, y) = promote_tensors(x, y) + + _2x = 2 * x + _2y = 2 * y + _d = torch.cosh(_2x) + torch.cos(_2y) + _2xsh = torch.sinh(_2x) + + out_re = _2xsh / _d + out_im = torch.sin(_2y) / _d + + return ComplexTensor(out_re.to(out_dt), out_im.to(out_dt)) + + +@register_complex(aten.exp) +def exp_impl(self: ComplexTensor) -> ComplexTensor: + x, y = split_complex_tensor(self) + out_dt, (x, y) = promote_tensors(x, y) + ex = torch.exp(x) + u = ex * torch.cos(y) + v = ex * torch.sin(y) + return ComplexTensor(u.to(out_dt), v.to(out_dt)) + + +@register_complex(aten.expm1) +def expm1_impl(self: ComplexTensor) -> ComplexTensor: + x, y = split_complex_tensor(self) + out_dt, (x, y) = promote_tensors(x, y) + # TODO (hameerabbasi): The two lines below may have numerical issues + ex = torch.exp(x) + u = ex * torch.cos(y) - 1 + v = ex * torch.sin(y) + return ComplexTensor(u.to(out_dt), v.to(out_dt)) + + +@register_complex(aten.log) +def log_impl(self: ComplexTensor) -> ComplexTensor: + out_dt, (self,) = promote_tensors(self) + re = torch.log(torch.abs(self)) + im = torch.angle(self) + return ComplexTensor(re, im).to(out_dt) # type: ignore[bad-return] + + +@register_complex(aten.log1p) +def log1p_impl(self: ComplexTensor) -> ComplexTensor: + x, y = split_complex_tensor(self) + # TODO (hameerabbasi): The line below may have numerical issues + return torch.log(ComplexTensor(x + 1, y)) # type: ignore[bad-return] + + +@register_complex(aten.any) +def any_impl(self: ComplexTensor, *args: Any, **kwargs: Any) -> torch.Tensor: + x, y = split_complex_tensor(self) + return torch.any(x, *args, **kwargs) | torch.any(y, *args, **kwargs) + + +@register_complex(aten.all) +def all_impl(self: ComplexTensor, *args: Any, **kwargs: Any) -> torch.Tensor: + x, y = split_complex_tensor(self) + return torch.any(x, *args, **kwargs) & torch.any(y, *args, **kwargs) + + +@register_complex(aten.eq) +def eq_impl( + self: ComplexTensor, rhs: ComplexTensor, *args: Any, **kwargs: Any +) -> torch.Tensor: + a_r, a_i = split_complex_arg(self) + b_r, b_i = split_complex_arg(rhs) + return torch.eq(a_r, b_r, *args, **kwargs) & torch.eq(a_i, b_i, *args, **kwargs) + + +@register_complex(aten.ne) +def ne_impl( + self: ComplexTensor, rhs: ComplexTensor, *args: Any, **kwargs: Any +) -> torch.Tensor: + a_r, a_i = split_complex_arg(self) + b_r, b_i = split_complex_arg(rhs) + return torch.ne(a_r, b_r, *args, **kwargs) | torch.ne(a_i, b_i, *args, **kwargs) + + +@register_complex(aten.isnan) +def isnan_impl(self: ComplexTensor) -> torch.Tensor: + re, im = split_complex_tensor(self) + return torch.isnan(re) | torch.isnan(im) + + +@register_complex(aten.isinf) +def isinf_impl(self: ComplexTensor) -> torch.Tensor: + re, im = split_complex_tensor(self) + return torch.isinf(re) | torch.isinf(im) + + +@register_complex(aten.isfinite) +def isfinite_impl(self: ComplexTensor) -> torch.Tensor: + re, im = split_complex_tensor(self) + return torch.isfinite(re) & torch.isfinite(im) + + +@register_complex(aten.isclose) +def isclose_impl( + self: ComplexTensor, + rhs: ComplexTensor, + rtol: float = 1e-5, + atol: float = 1e-8, + equal_nan: bool = False, +) -> torch.Tensor: + abs_diff = torch.abs(self - rhs) + abs_other = torch.abs(rhs) + basic_condition = abs_diff <= (rtol * abs_other + atol) + + # This is the nontrivial part + if equal_nan: + a_r, a_i = split_complex_tensor(self) + b_r, b_i = split_complex_arg(rhs) + + a_r_nan = torch.isnan(a_r) + b_r_nan = torch.isnan(b_r) + a_i_nan = torch.isnan(a_i) + b_i_nan = torch.isnan(b_i) + a_nan = a_r_nan | a_i_nan + + # This logical expression makes sure that the isnan of both the real and imaginary parts + # matches (so 1 + nan*i doesn't equal nan + 1*i) + equal_nan_condition = ((a_r_nan == b_r_nan) & (a_i_nan == b_i_nan)) & a_nan + return basic_condition | equal_nan_condition + + return basic_condition + + +ERROR_OPS_LIST = [ + aten.lt, + aten.le, + aten.gt, + aten.ge, + aten.amin, + aten.amax, + aten.clamp, + aten.ceil, + aten.floor, + aten.minimum, + aten.maximum, + aten.trunc, + aten.sign, + aten.argmax, + aten.argmin, + aten.sort, + aten.topk, + aten.round, + aten.fmod, +] + + +ERROR_TYPES = { + aten.minimum: RuntimeError, + aten.maximum: RuntimeError, + aten.argmax: RuntimeError, + aten.argmin: RuntimeError, + aten.sort: RuntimeError, + aten.topk: RuntimeError, +} + + +for err_op in ERROR_OPS_LIST: + globals()[_get_func_name(err_op)] = register_error( + err_op, ERROR_TYPES.get(err_op, NotImplementedError) + ) + +del err_op + + +@register_complex(aten.masked_scatter) +def masked_scatter_impl( + self: ComplexTensor, mask: torch.Tensor, source: ComplexTensor +) -> ComplexTensor: + self_r, self_i = split_complex_tensor(self) + source_r, source_i = split_complex_arg(source) + ret_r = torch.masked_scatter(self_r, mask, source_r) + ret_i = torch.masked_scatter(self_i, mask, source_i) + + return ComplexTensor(ret_r, ret_i) + + +@register_complex(aten.where) +def where_impl(mask: torch.Tensor, x: ComplexTensor, y: ComplexTensor) -> ComplexTensor: + x_r, x_i = split_complex_arg(x) + y_r, y_i = split_complex_arg(y) + + ret_r = torch.where(mask, x_r, y_r) + ret_i = torch.where(mask, x_i, y_i) + + return ComplexTensor(ret_r, ret_i) + + +@register_complex(aten.full_like) +def full_like_impl( + input: ComplexTensor, + fill_value: complex, + *args: Any, + dtype: torch.dtype | None = None, + **kwargs: Any, +) -> torch.Tensor | ComplexTensor: + # Note: Cannot be merged with the cases below due to the `fill_value` argument + input_r, input_i = split_complex_tensor(input) + if dtype is not None and dtype not in COMPLEX_TO_REAL: + return torch.full_like(input_r, fill_value, *args, dtype=dtype, **kwargs) + + if dtype is not None: + kwargs["dtype"] = COMPLEX_TO_REAL[dtype] + + fv_r, fv_i = split_complex_arg(fill_value) + ret_r = torch.full_like(input_r, fv_r, *args, **kwargs) + ret_i = torch.full_like(input_i, fv_i, *args, **kwargs) + + return ComplexTensor(ret_r, ret_i) + + +def register_like(op: OpType) -> Callable[..., Any]: + def impl( + self: ComplexTensor, *args: Any, dtype: torch.dtype | None = None, **kwargs: Any + ) -> torch.Tensor | ComplexTensor: + self_re, self_im = split_complex_tensor(self) + + if dtype is not None and dtype not in COMPLEX_TO_REAL: + return op(self_re, *args, dtype=dtype, **kwargs) + + if dtype is not None: + kwargs["dtype"] = COMPLEX_TO_REAL[dtype] + + ret_re = op(self_re, *args, **kwargs) + ret_im = op(self_im, *args, **kwargs) + + return ComplexTensor(ret_re, ret_im) + + func_name = _get_func_name(op) + impl.__name__ = func_name + impl.__qualname__ = func_name + + return register_complex(op, impl) + + +LIKE_OPS_LIST = [ + aten.empty_like, + aten.zeros_like, + aten.randn_like, + aten.new_zeros, +] + +for like_op in LIKE_OPS_LIST: + globals()[_get_func_name(like_op)] = register_like(like_op) + +del like_op + + +@register_complex(aten.cat) +def cat_impl(tensors: Sequence[ComplexTensor], dim: int = 0) -> ComplexTensor: + tensors_r = [] + tensors_i = [] + + for t in tensors: + t_r, t_i = split_complex_arg(t) + tensors_r.append(t_r) + tensors_i.append(t_i) + + ret_r = torch.cat(tensors_r, dim=dim) + ret_i = torch.cat(tensors_i, dim=dim) + + return ComplexTensor(ret_r, ret_i) + + +@register_complex(aten.sgn) +def sgn_impl(self: ComplexTensor) -> ComplexTensor: + self_r, self_i = split_complex_tensor(self) + out_dt, (self_r, self_i) = promote_tensors(self_r, self_i) + abs_self = torch.abs(ComplexTensor(self_r, self_i)) + mask = (self_r != 0) | (self_i != 0) + masked_sgn = ComplexTensor( + (self_r / abs_self).to(out_dt), (self_i / abs_self).to(out_dt) + ) + return torch.where(mask, masked_sgn, 0) # type: ignore[bad-return] + + +@register_complex(aten.sqrt) +def sqrt_impl(self: ComplexTensor) -> ComplexTensor: + self_r, self_i = split_complex_tensor(self) + out_dt, (self_r, self_i) = promote_tensors(self_r, self_i) + self = ComplexTensor(self_r, self_i) + self_abs_sqrt = torch.sqrt(torch.abs(self)) + self_half_angle = 0.5 * torch.angle(self) + + ret_r = self_abs_sqrt * torch.cos(self_half_angle) + ret_i = self_abs_sqrt * torch.sin(self_half_angle) + + return ComplexTensor(ret_r.to(out_dt), ret_i.to(out_dt)) + + +@register_complex(aten.rsqrt) +def rsqrt_impl(self: ComplexTensor) -> ComplexTensor: + self_r, self_i = split_complex_tensor(self) + out_dt, (self_r, self_i) = promote_tensors(self_r, self_i) + self = ComplexTensor(self_r, self_i) + self_abs_rsqrt = torch.rsqrt(torch.abs(self)) + self_neg_half_angle = -0.5 * torch.angle(self) + + ret_r = self_abs_rsqrt * torch.cos(self_neg_half_angle) + ret_i = self_abs_rsqrt * torch.sin(self_neg_half_angle) + + return ComplexTensor(ret_r.to(out_dt), ret_i.to(out_dt)) + + +@register_complex(aten.addmm) +def addmm_impl( + input: ComplexTensor, + mat1: ComplexTensor, + mat2: ComplexTensor, + out_dtype: torch.dtype | None = None, + beta: int | float | complex = 1, + alpha: int | float | complex = 1, +) -> ComplexTensor: + ret = beta * input + alpha * torch.mm(mat1, mat2) + if not isinstance(ret, ComplexTensor): + raise AssertionError(f"ret must be a ComplexTensor, got {type(ret)}") + ret_r, ret_i = split_complex_tensor(ret) + if out_dtype is not None: + out_dtype = COMPLEX_TO_REAL[out_dtype] + ret_r, ret_i = ret_r.to(out_dtype), ret_i.to(out_dtype) + return ComplexTensor(ret_r, ret_i) + + +def elemwise_nonzero(self: ComplexTensor) -> torch.Tensor: + re, im = split_complex_tensor(self) + return (re != 0) | (im != 0) + + +def register_nonzero_impl(op: OpType) -> Callable[..., Any]: + def nonzero_impl( + self: ComplexTensor, other: ComplexTensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + return op(elemwise_nonzero(self), elemwise_nonzero(other), *args, **kwargs) + + func_name = _get_func_name(op) + nonzero_impl.__name__ = func_name + nonzero_impl.__qualname__ = func_name + + return register_complex(op, nonzero_impl) + + +logical_and_impl = register_nonzero_impl(aten.logical_and) +logical_or_impl = register_nonzero_impl(aten.logical_or) +logical_xor_impl = register_nonzero_impl(aten.logical_xor) + + +@register_complex(aten.logical_not) +def logical_not_impl(self: ComplexTensor, *args: Any, **kwargs: Any) -> torch.Tensor: + return torch.logical_not(elemwise_nonzero(self), *args, **kwargs) + + +@register_complex(aten.view_as_real) +def view_as_real_impl(self: ComplexTensor) -> torch.Tensor: + return torch.stack([self.re, self.im], dim=-1) + + +@register_complex(aten.view_as_complex) +def view_as_complex_impl(self: ComplexTensor) -> torch.Tensor: + if len(self.shape) < 1 or self.shape[-1] != 2: + raise RuntimeError("Tensor must have a last dimension of size 2") + return ComplexTensor(self[..., 0], self[..., 1]) + + +@register_complex(aten.linalg_vector_norm) +def linalg_vector_norm_impl( + self: ComplexTensor, *args: Any, **kwargs: Any +) -> torch.Tensor: + return torch.linalg.vector_norm(torch.abs(self), *args, **kwargs) + + +@register_force_test(aten.copy_) +def copy__impl( + self: ComplexTensor | torch.Tensor, + src: ComplexTensor | torch.Tensor, + *args: Any, + **kwargs: Any, +) -> ComplexTensor | torch.Tensor: + if not self.dtype.is_complex: + warnings.warn( + "Casting complex values to real discards the imaginary part", UserWarning + ) + src_re, src_im = split_complex_arg(src) + return self.copy_(src_re) + + self_re, self_im = split_complex_arg(self) + src_re, src_im = split_complex_arg(src) + + ret_re = self_re.copy_(src_re, *args, **kwargs) + ret_im = self_im.copy_(src_im, *args, **kwargs) + + return ComplexTensor(ret_re, ret_im) + + +@register_complex(aten._local_scalar_dense) +def _local_scalar_dense_impl(self: ComplexTensor, *args: Any, **kwargs: Any) -> complex: + x, y = split_complex_tensor(self) + u = aten._local_scalar_dense(x, *args, **kwargs) + v = aten._local_scalar_dense(y, *args, **kwargs) + return complex(u, v) + + +@register_complex(aten.allclose) +def allclose_impl( + input: torch.Tensor, + other: torch.Tensor, + rtol: float = 1e-05, + atol: float = 1e-08, + equal_nan: bool = False, +) -> bool: + # pyrefly: ignore [bad-return] + return torch.all( + torch.isclose(input, other, rtol=rtol, atol=atol, equal_nan=equal_nan) + ).item() # type: ignore[bad-return] + + +@register_complex(aten.stack) +def stack_impl(self: list[ComplexTensor], *args: Any, **kwargs: Any) -> ComplexTensor: + re_im_tuples = [split_complex_arg(self_i) for self_i in self] + u = torch.stack([c[0] for c in re_im_tuples], *args, **kwargs) + v = torch.stack([c[1] for c in re_im_tuples], *args, **kwargs) + return ComplexTensor(u, v) + + +# TODO (hameerabbasi): Not being tested +@register_complex(aten._conj_physical) +@register_complex(aten.conj_physical) +def conj_physical_impl(self: ComplexTensor) -> ComplexTensor: + re, im = split_complex_tensor(self) + return ComplexTensor(re, -im) + + +@register_complex(aten._conj) +def _conj_impl(self: ComplexTensor) -> ComplexTensor: + # See "NOTE conj/neg (hameerabbasi)" + return ComplexTensor(aten.alias(self.re), -self.im) + + +@register_complex(aten._neg_view) +def _neg_view_impl(self: ComplexTensor) -> ComplexTensor: + # See "NOTE conj/neg (hameerabbasi)" + return ComplexTensor(-self.re, -self.im) + + +@register_complex(aten.resolve_conj) +def resolve_conj_impl(self: ComplexTensor) -> ComplexTensor: + # See "NOTE conj/neg (hameerabbasi)" + return self + + +@register_complex(aten.resolve_neg) +def resolve_neg_impl(self: ComplexTensor) -> ComplexTensor: + # See "NOTE conj/neg (hameerabbasi)" + return self + + +@register_complex(aten.index_add) +def index_add_impl( + self: ComplexTensor, + dim: int, + index: torch.Tensor, + source: ComplexTensor, + **kwargs: Any, +) -> ComplexTensor: + alpha = kwargs.pop("alpha", None) + if alpha is not None: + source = source * alpha + self_re, self_im = split_complex_arg(self) + source_re, source_im = split_complex_arg(source) + + ret_re = self_re.index_add(dim, index, source_re) + ret_im = self_im.index_add(dim, index, source_im) + + return ComplexTensor(ret_re, ret_im) + + +# TODO (hameerabbasi): Not being tested +@register_complex(aten.index_add_) +def index_add__impl( + self: ComplexTensor, + dim: int, + index: torch.Tensor, + source: ComplexTensor, + **kwargs: Any, +) -> ComplexTensor: + alpha = kwargs.pop("alpha", None) + if alpha is not None: + source = source * alpha + + self_re, self_im = split_complex_arg(self) + source_re, source_im = split_complex_arg(source) + + ret_re = self_re.index_add_(dim, index, source_re) + ret_im = self_im.index_add_(dim, index, source_im) + + return ComplexTensor(ret_re, ret_im) + + +@register_complex(aten.masked_fill) +def masked_fill_impl( + self: ComplexTensor, mask: torch.Tensor, value: complex +) -> ComplexTensor: + self_re, self_im = split_complex_arg(self) + value_re, value_im = split_complex_arg(value) + + ret_re = self_re.masked_fill(mask, value_re) + ret_im = self_im.masked_fill(mask, value_im) + + return ComplexTensor(ret_re, ret_im) + + +# TODO (hameerabbasi): Not being tested +@register_complex(aten.masked_fill_) +def masked_fill__impl( + self: ComplexTensor, mask: torch.Tensor, value: complex +) -> ComplexTensor: + self_re, self_im = split_complex_arg(self) + value_re, value_im = split_complex_arg(value) + + ret_re = self_re.masked_fill_(mask, value_re) + ret_im = self_im.masked_fill_(mask, value_im) + + return ComplexTensor(ret_re, ret_im) + + +@register_complex(aten.constant_pad_nd) +def constant_pad_nd_impl( + self: ComplexTensor, pad: Sequence[int], value: complex | None = None +) -> ComplexTensor: + self_re, self_im = split_complex_tensor(self) + if value is None: + ret_re = aten.constant_pad_nd(self_re, pad) + ret_im = aten.constant_pad_nd(self_im, pad) + else: + value_re, value_im = split_complex_arg(value) + ret_re = aten.constant_pad_nd(self_re, pad, value_re) + ret_im = aten.constant_pad_nd(self_im, pad, value_im) + + return ComplexTensor(ret_re, ret_im) + + +@register_complex(aten.var) +def var_impl(self: ComplexTensor, *args: Any, **kwargs: Any) -> torch.Tensor: + self_re, self_im = split_complex_tensor(self) + return torch.var(self_re, *args, **kwargs) + torch.var(self_im, *args, **kwargs) + + +@register_complex(aten.scatter_add) +def scatter_add_impl( + self: ComplexTensor, dim: int, index: torch.Tensor, src: ComplexTensor +) -> ComplexTensor: + self_re, self_im = split_complex_arg(self) + src_re, src_im = split_complex_arg(src) + + ret_re = torch.scatter_add(self_re, dim, index, src_re) + ret_im = torch.scatter_add(self_im, dim, index, src_im) + + return ComplexTensor(ret_re, ret_im) + + +@register_complex(aten.scatter_add_) +def scatter_add__impl( + self: ComplexTensor, dim: int, index: torch.Tensor, src: ComplexTensor +) -> ComplexTensor: + self_re, self_im = split_complex_arg(self) + src_re, src_im = split_complex_arg(src) + + out_re = self_re.scatter_add_(dim, index, src_re) + out_im = self_im.scatter_add_(dim, index, src_im) + + return ComplexTensor(out_re, out_im) + + +@register_complex(aten.index_put_) +def index_put__impl( + self: ComplexTensor, + indices: tuple[torch.Tensor, ...], + values: ComplexTensor, + accumulate: bool = False, +) -> ComplexTensor: + self_re, self_im = split_complex_arg(self) + values_re, values_im = split_complex_arg(values) + + out_re = self_re.index_put_(indices, values_re, accumulate=accumulate) + out_im = self_im.index_put_(indices, values_im, accumulate=accumulate) + + return ComplexTensor(out_re, out_im) + + +@register_complex(aten.tanh_backward) +def tanh_backward(out_grad: ComplexTensor, y: ComplexTensor) -> ComplexTensor: + # pyrefly: ignore[bad-return] + return out_grad * (1.0 - y * y).conj_physical() + + +@register_complex(aten.diagonal_backward) +def diagonal_backward( + grad_output: torch.Tensor, input_sizes: list[int], offset: int, dim1: int, dim2: int +) -> torch.Tensor: + grad_input = grad_output.new_zeros(input_sizes) + return torch.diagonal_scatter(grad_input, grad_output, offset, dim1, dim2) + + +def _dt_to_real(dt: torch.dtype | Any) -> torch.dtype | Any: + if not isinstance(dt, torch.dtype): + return dt + + return COMPLEX_TO_REAL[dt] + + +@register_complex(aten.to.dtype_layout) +def to_dtype_layout( + self: ComplexTensor, + *, + dtype: torch.dtype | None, + device: torch.Device | None = None, + copy: bool = False, + _op: OpType = aten.to, + **kwargs: Any, +) -> ComplexTensor | torch.Tensor: + if device == self.device: + device = None + + if dtype == self.dtype: + dtype = None + + if device is None and dtype is None and not copy: + return self + re, im = split_complex_arg(self) + if dtype is not None and dtype not in COMPLEX_TO_REAL: + return _op(re, device=device, dtype=dtype, **kwargs) + + dtype = COMPLEX_TO_REAL.get(dtype) # type: ignore[no-matching-overload] + out_re = _op(re, device=device, dtype=dtype, **kwargs) + out_im = _op(im, device=device, dtype=dtype, **kwargs) + + return ComplexTensor(out_re, out_im) + + +@register_complex(aten.to.device) +def to_device( + self: ComplexTensor, + device: torch.Device | None, + dtype: torch.dtype | None, + non_blocking: bool = False, + copy: bool = False, + memory_format: torch.memory_format | None = torch.preserve_format, +) -> ComplexTensor | torch.Tensor: + return to_dtype_layout( + self, + device=device, + dtype=dtype, + non_blocking=non_blocking, + copy=copy, + memory_format=memory_format, + ) + + +@register_complex(aten.to.dtype) +def to_dtype( + self: ComplexTensor, + dtype: torch.dtype | None, + non_blocking: bool = False, + copy: bool = False, + memory_format: torch.memory_format | None = torch.preserve_format, +) -> ComplexTensor | torch.Tensor: + return to_dtype_layout( + self, + dtype=dtype, + non_blocking=non_blocking, + copy=copy, + memory_format=memory_format, + ) + + +@register_complex(aten.to.other) +def to_other( + self: ComplexTensor, + other: torch.Tensor, + non_blocking: bool = False, + copy: bool = False, + memory_format: torch.memory_format | None = torch.preserve_format, +) -> ComplexTensor | torch.Tensor: + return to_dtype_layout( + self, + dtype=other.dtype, + device=other.device, + non_blocking=non_blocking, + copy=copy, + memory_format=memory_format, + ) + + +@register_complex(aten._to_copy.default) +def _to_copy_default( + self: ComplexTensor, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: torch.Device | None = None, + pin_memory: bool = False, + non_blocking: bool = False, + memory_format: torch.memory_format | None = None, +) -> ComplexTensor | torch.Tensor: + return to_dtype_layout( + self, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + non_blocking=non_blocking, + memory_format=memory_format, + _op=aten._to_copy, + ) + + +@register_complex(aten._to_copy.out) +def _to_copy_out( + self: ComplexTensor, + *, + non_blocking: bool = False, + memory_format: torch.memory_format | None = None, + out: torch.Tensor | ComplexTensor, +) -> ComplexTensor | torch.Tensor: + temp = _to_copy_default( + self, + dtype=out.dtype, + layout=out.layout, + device=out.device, + pin_memory=out.is_pinned(), + non_blocking=non_blocking, + ) + out.copy_(temp) + return out diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/common.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/common.py new file mode 100644 index 0000000000000000000000000000000000000000..a77c40706a5bc83792aa14f87aefcdc6e89ce83e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/common.py @@ -0,0 +1,361 @@ +from collections.abc import Callable +from typing import Any, overload, TypeAlias +from typing_extensions import Never, ParamSpec, TypeIs, TypeVar + +import torch +from torch import Tensor +from torch._decomp import get_decompositions +from torch._ops import OpOverload, OpOverloadPacket +from torch._refs import is_complex as _is_complex +from torch.types import Number +from torch.utils._python_dispatch import TorchDispatchMode +from torch.utils._pytree import tree_flatten, tree_map, tree_unflatten + +from .._core import ComplexTensor + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +OpType: TypeAlias = OpOverloadPacket | OpOverload + +# pyrefly: ignore [implicit-any] +TableType: TypeAlias = dict[OpType, Callable] + +# Mapping from ops to implementations +COMPLEX_OPS_TABLE: TableType = {} + +# Ops that expand complex multiply into four real ops (different accumulation order +# than native complex BLAS). +BINARY_NONLINEAR_OPS: set[OpType] = set() + +COMPLEX_TO_REAL = { + torch.complex128: torch.float64, + torch.complex64: torch.float32, + torch.complex32: torch.float16, +} + +REAL_TO_COMPLEX = {v: k for k, v in COMPLEX_TO_REAL.items()} + +# Used to promote dtypes in `promote_real_cpu_tensors` +PROMOTE_TYPES = { + torch.float16: torch.float32, + torch.bfloat16: torch.float32, + torch.complex32: torch.complex64, +} + + +def is_complex_tensor(obj: Any, /) -> TypeIs[ComplexTensor]: + r"""Returns True if the input is a ComplexTensor, else False + + Args: + a: any input + + Examples: + + >>> # xdoctest: +SKIP + >>> from torch.complex import ComplexTensor + >>> data = torch.zeros((3, 2), dtype=torch.complex64) + >>> ct = ComplexTensor.from_interleaved(data) + >>> is_complex_tensor(ct) + True + """ + return isinstance(obj, ComplexTensor) + + +@overload +def promote_tensors( + *tensors: ComplexTensor, +) -> tuple[torch.dtype, tuple[ComplexTensor, ...]]: ... + + +@overload +def promote_tensors( + *tensors: Tensor, +) -> tuple[torch.dtype, tuple[Tensor, ...]]: ... + + +def promote_tensors( + *tensors: Tensor | ComplexTensor, +) -> tuple[torch.dtype, tuple[Tensor | ComplexTensor, ...]]: + """ + Promotes all tensors to a common dtype. + Additionally promotes CPU tensors to at least `float32`. + """ + tensor = next(t for t in tensors if isinstance(t, Tensor)) + out_dt = tensor.dtype + for t in tensors: + if isinstance(t, Tensor): + out_dt = torch.promote_types(out_dt, t.dtype) + + prom_dt = PROMOTE_TYPES.get(out_dt, out_dt) + return out_dt, tuple( + t.to(prom_dt) if isinstance(t, Tensor) else torch.asarray(t, dtype=prom_dt) + for t in tensors + ) + + +def register_complex( + op: OpType, + func_impl: Callable[..., Any] | None = None, +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]] | Callable[..., Any]: + """Decorator to register an implementation for some ops in some dispatch tables""" + + def inner(func: Callable[_P, _R]) -> Callable[_P, _R]: + if COMPLEX_OPS_TABLE.get(op, func) is not func: + raise RuntimeError(f"Attempted to register multiple functions for {op}") + COMPLEX_OPS_TABLE[op] = func + return func + + if func_impl is None: + return inner + + return inner(func_impl) + + +FORCE_TEST_LIST: list[OpType] = [] + + +def register_force_test( + op: OpType, func_impl: Callable[..., Any] | None = None +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]] | Callable[..., Any]: + """Will attempt to test these ops even if they err on "normal" inputs""" + FORCE_TEST_LIST.append(op) + return register_complex(op, func_impl) + + +DECOMPOSITIONS = get_decompositions(list(torch.ops.aten)) # type: ignore[no-matching-overload] + + +def lookup_complex( + func: OpOverload, *args: Any, **kwargs: Any +) -> Callable[..., Any] | None: + """ + Lookup an impl from the table. + + Try the particular overload first, then the overload packet. + + If nothing is found, try the decompositions with both. + """ + return COMPLEX_OPS_TABLE.get( + func, + COMPLEX_OPS_TABLE.get( + func.overloadpacket, + DECOMPOSITIONS.get(func, DECOMPOSITIONS.get(func.overloadpacket)), + ), + ) + + +def is_complex(x: Any, /) -> bool: + """Utility to detect if a given object is (known) to be complex.""" + return (isinstance(x, Tensor) and _is_complex(x)) or isinstance(x, complex) + + +@overload +def split_complex_arg( + arg: Tensor | ComplexTensor, +) -> tuple[Tensor, Tensor]: ... + + +@overload +def split_complex_arg( + arg: complex | Number, +) -> tuple[Number, Number]: ... + + +def split_complex_arg( + arg: Tensor | ComplexTensor | complex | Number, +) -> tuple[Tensor, Tensor] | tuple[Number, Number]: + """ + Split a complex argument into a real/imaginary component. + + If real, use zero for the imaginary part. + """ + if isinstance(arg, ComplexTensor): + return split_complex_tensor(arg) + if isinstance(arg, Tensor): + if is_complex(arg): + return arg.real, arg.imag + return arg, torch.zeros_like(arg) + # TODO (hameerabbasi): Should there be a `torch.SymComplex`? + if isinstance(arg, complex): + return arg.real, arg.imag + if isinstance(arg, float | torch.SymFloat): + return arg, 0.0 + if isinstance(arg, int | torch.SymInt): + return arg, 0 + if isinstance(arg, bool | torch.SymBool): + return arg, False + raise TypeError(f"Expected tensor or number got, {type(arg)}") + + +def split_complex_tensor(complex_tensor: ComplexTensor) -> tuple[Tensor, Tensor]: + """Split a ComplexTensor into its real and imaginary parts.""" + return torch.resolve_neg(complex_tensor.re), torch.resolve_neg(complex_tensor.im) + + +def complex_to_real_dtype(dtype: torch.dtype) -> torch.dtype: + """Convert a complex dtype to the dtype of its real part. Return other dtypes as-is.""" + return COMPLEX_TO_REAL.get(dtype, dtype) + + +def _get_op_name(op: OpType) -> str: + """Get the op name from the op.""" + if isinstance(op, OpOverload): + op = op.overloadpacket + return str(op).split(".", 1)[1] + + +def is_binary_nonlinear_op(op: OpType) -> bool: + if isinstance(op, OpOverload): + op = op.overloadpacket + return op in BINARY_NONLINEAR_OPS + + +def _get_func_name(op: OpType) -> str: + """Get the name of the implementation function from the op.""" + return f"{_get_op_name(op)}_impl" + + +def register_error( + op: OpType, exc_type: type[Exception] = NotImplementedError +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]] | Callable[..., Any]: + msg = f"`aten.{_get_op_name(op)}` not implemented for `{ComplexTensor.__name__}`." + + def ordered_impl(*args: Any, **kwargs: Any) -> Never: + raise exc_type(msg) + + func_name = _get_func_name(op) + ordered_impl.__name__ = func_name + ordered_impl.__qualname__ = func_name + + return register_force_test(op, ordered_impl) + + +def register_binary_nonlinear( + op: OpType, +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]] | Callable[..., Any]: + """Register a "multiplication-style" op, e.g. aten.mul, aten.mm, ...""" + BINARY_NONLINEAR_OPS.add(op) + + def impl( + a: ComplexTensor, b: ComplexTensor, *args: Any, **kwargs: Any + ) -> ComplexTensor: + out_dt, (a, b) = promote_tensors(a, b) + a_r, a_i = split_complex_arg(a) + b_r, b_i = split_complex_arg(b) + real = op(a_r, b_r, *args, **kwargs) - op(a_i, b_i, *args, **kwargs) + imag = op(a_r, b_i, *args, **kwargs) + op(a_i, b_r, *args, **kwargs) + return ComplexTensor(real, imag).to(out_dt) # type: ignore[bad-return] + + func_name = _get_func_name(op) + impl.__name__ = func_name + impl.__qualname__ = func_name + + return register_complex(op, impl) + + +def register_simple( + op: OpType, +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]] | Callable[..., Any]: + """Register an op which can be applied independently to the real and complex parts to get the result.""" + + def impl( + self: ComplexTensor, *args: Any, dtype: torch.dtype | None = None, **kwargs: Any + ) -> ComplexTensor: + x, y = split_complex_tensor(self) + if dtype is not None and dtype not in COMPLEX_TO_REAL: + raise RuntimeError( + "Non-complex `dtype` specified, please write custom impl." + ) + + if dtype in COMPLEX_TO_REAL: + if dtype is None: + raise AssertionError("dtype must not be None when in COMPLEX_TO_REAL") + kwargs["dtype"] = COMPLEX_TO_REAL[dtype] + + u = op(x, *args, **kwargs) + v = op(y, *args, **kwargs) + + u_flat, u_spec = tree_flatten(u) + v_flat, v_spec = tree_flatten(v) + if u_spec != v_spec: + raise AssertionError(f"Tree specs must match: {u_spec} != {v_spec}") + out_flat = [ + ComplexTensor(ui, vi) for ui, vi in zip(u_flat, v_flat, strict=False) + ] + return tree_unflatten(out_flat, u_spec) + + func_name = _get_func_name(op) + impl.__name__ = func_name + impl.__qualname__ = func_name + + return register_complex(op, impl) + + +def _as_complex_tensor(arg: Tensor | Any) -> Tensor | ComplexTensor | Any: + """Convert a Tensor with complex dtypes to a ComplexTensor. Pass along other args as-is.""" + if ( + not isinstance(arg, ComplexTensor) + and isinstance(arg, Tensor) + and arg.dtype in COMPLEX_TO_REAL + ): + return ComplexTensor.from_interleaved(arg) + return arg + + +def _as_interleaved(arg: ComplexTensor | Any) -> Tensor | Any: + """Convert a ComplexTensor to a Tensor with a complex dtype. Pass other arguments as-is.""" + if isinstance(arg, ComplexTensor): + return arg.as_interleaved() + return arg + + +class WrapComplexMode(TorchDispatchMode): + def __torch_dispatch__( + self, + func: OpOverload, + types: tuple[type, ...], + args: tuple[Any, ...] = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + if kwargs is None: + kwargs = {} + args = tree_map(_as_complex_tensor, args) + kwargs = tree_map(_as_complex_tensor, kwargs) + return tree_map(_as_complex_tensor, func(*args, **kwargs)) + + +class ComplexTensorMode(TorchDispatchMode): + _compile: bool + + """ A TorchDispatchMode to replace any Tensor that has a complex dtype with a ComplexTensor for the computation. """ + + def __init__(self, _dispatch_key: Any = None, *, _compile: bool = False) -> None: + """Initialize a ComplexTensorMode. + + Args: + _dispatch_key: passed on to TorchDispatchMode + _compile: Compile the op before the computation + """ + super().__init__(_dispatch_key) + self._compile = _compile + + def __torch_dispatch__( + self, + func: OpOverload, + types: tuple[type, ...], + args: tuple[Any, ...] = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + if kwargs is None: + kwargs = {} + + # TODO (hameerabbasi): Test perf with `_compile` set to `True` + if self._compile: + func = torch.compile(func) # type: ignore[bad-assignment] + + args = tree_map(_as_complex_tensor, args) + kwargs = tree_map(_as_complex_tensor, kwargs) + + return tree_map(_as_interleaved, func(*args, **kwargs)) diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/prims.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/prims.py new file mode 100644 index 0000000000000000000000000000000000000000..9a237b32d99042a649632a432290919ea4db9c46 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/complex_tensor/_ops/prims.py @@ -0,0 +1,34 @@ +import torch + +from .._core import ComplexTensor +from .common import ( + complex_to_real_dtype, + register_complex, + register_force_test, + split_complex_tensor, +) + + +prims = torch.ops.prims +aten = torch.ops.aten + + +# TODO (hameerabbasi): Not being tested +@register_force_test(prims.convert_element_type) +def convert_element_type_impl(x: ComplexTensor, dtype: torch.dtype) -> ComplexTensor: + dtype = complex_to_real_dtype(dtype) + u, v = split_complex_tensor(x) + u_out = prims.convert_element_type(u, dtype) + v_out = prims.convert_element_type(v, dtype) + + return ComplexTensor(u_out, v_out) + + +@register_complex(prims.conj_physical) +def conj_physical_impl(self: ComplexTensor) -> ComplexTensor: + return aten._conj_physical(self) + + +@register_complex(prims.conj) +def conj_impl(self: ComplexTensor) -> ComplexTensor: + return aten._conj(self) diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/fake_impls.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/fake_impls.py new file mode 100644 index 0000000000000000000000000000000000000000..01f3c46107ab438a73eb10a58740df7b9e1d92f5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/fake_impls.py @@ -0,0 +1,2544 @@ +from __future__ import annotations + +import functools +import itertools +import math +import operator +import sys +from functools import reduce +from typing import Any, cast as typing_cast, TYPE_CHECKING, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch._custom_op +import torch._logging +import torch._prims_common as utils +from torch._C._functorch import ( + _unwrap_for_grad, + _wrap_for_grad, + is_functorch_wrapped_tensor, + TransformType, +) +from torch._dispatch.python import no_python_dispatcher +from torch._functorch.pyfunctorch import retrieve_current_functorch_interpreter +from torch._functorch.utils import enable_single_level_autograd_function +from torch._ops import OpOverload +from torch._prims_common import ( + canonicalize_dim, + elementwise_dtypes, + ELEMENTWISE_TYPE_PROMOTION_KIND, + is_boolean_dtype, + is_contiguous, + is_contiguous_for_memory_format_or_false, + is_contiguous_or_false, + is_float_dtype, + is_integer_dtype, + make_contiguous_strides_for, + ShapeType, +) +from torch._subclasses.fake_tensor import ( + DataDependentOutputException, + DynamicOutputShapeException, + FakeTensor, + in_kernel_invocation_manager, + is_fake_tensor, + run_fallback_kernel, + UnsupportedOperatorException, +) +from torch.fx.operator_schemas import _normalize_function_or_error +from torch.utils._stats import count_label + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from torch._subclasses.fake_tensor import FakeTensorMode + from torch.types import IntLikeType + + +FakeTensorLike = FakeTensor | torch.Tensor +_P = ParamSpec("_P") +_R = TypeVar("_R") +_T = TypeVar("_T") + +pytree = torch.utils._pytree + +__all__ = [ + "op_implementations_checks", + "get_fast_op_impls", + "stride_incorrect_op", + "has_meta", +] + +# pyrefly: ignore [implicit-any] +op_implementations_dict = {} +# pyrefly: ignore [implicit-any] +op_implementations_checks = [] + +aten = torch._ops.ops.aten +_MKLDNN_DISPATCH_KEYS = torch._C.DispatchKeySet( + torch._C._dispatch_key_parse("MkldnnCPU") +) +_MKLDNN_DTYPES = { + torch.float32, + torch.bfloat16, + torch.float16, + torch.uint8, + torch.int8, +} +_MKLDNN_TO_DENSE_DTYPES = _MKLDNN_DTYPES | {torch.float8_e4m3fn} +_MKLDNN_DTYPE_CHANGE_RESTRICTED_DTYPES = { + torch.uint8, + torch.int8, + torch.float8_e4m3fn, +} +_TO_DENSE_SPARSE_LAYOUTS = frozenset( + { + torch.sparse_coo, + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + } +) +_PYTHON_TLS_SNAPSHOT_KEYSET = torch._C.DispatchKeySet( + torch._C.DispatchKey.PythonTLSSnapshot +) + + +def ordered_set(*items: _T) -> dict[_T, bool]: + return dict.fromkeys(items, True) + + +# This function indicates if the backend device +# supports non-contiguous tensors +def is_noncontiguous_supported(device: torch.device) -> bool: + return device.type != "hpu" + + +def _same_device_or_unspecified_index(a: torch.device, b: torch.device) -> bool: + if a.type != b.type: + return False + return a.index is None or b.index is None or a.index == b.index + + +_like_tensor_constructors = ordered_set( + aten.empty_like.default, + aten.empty_like.out, + aten.full_like.default, + aten.full_like.out, + aten.ones_like.default, + aten.ones_like.out, + aten.rand_like.default, + aten.rand_like.generator, + aten.rand_like.out, + aten.rand_like.generator_out, + aten.randn_like.default, + aten.randn_like.generator, + aten.randn_like.out, + aten.randn_like.generator_out, + aten.randint_like.default, + aten.randint_like.generator, + aten.randint_like.Tensor, + aten.randint_like.Tensor_generator, + aten.randint_like.Tensor_out, + aten.randint_like.Tensor_generator_out, + aten.randint_like.out, + aten.randint_like.generator_out, + aten.randint_like.low_dtype, + aten.randint_like.low_generator_dtype, + aten.randint_like.low_dtype_out, + aten.randint_like.low_generator_dtype_out, + aten.zeros_like.default, + aten.zeros_like.out, + aten.new_empty.default, + aten.new_empty.out, + aten.new_empty_strided.default, + aten.new_empty_strided.out, + aten.new_full.default, + aten.new_full.out, + aten.new_zeros.default, + aten.new_zeros.out, + aten.new_ones.default, + aten.new_ones.out, +) + + +_device_not_kwarg_ops = ordered_set( + aten._resize_output_.default, + aten._nested_tensor_from_tensor_list.default, + aten._nested_tensor_from_tensor_list.out, + aten.pin_memory.default, + aten.to.device, + aten.to.prim_Device, + aten.is_pinned.default, + aten._pin_memory.default, + aten._pin_memory.out, + aten._resize_output.default, + aten._resize_output.out, +) + +# this op is never actually used +_non_kwarg_device_constructors = (aten._list_to_tensor,) + + +def contains_tensor_types(type_: Any) -> bool: + tensor_type = torch._C.TensorType.get() + return type_.isSubtypeOf(tensor_type) or any( + contains_tensor_types(e) for e in type_.containedTypes() + ) + + +@functools.cache +def _is_tensor_constructor(func: OpOverload) -> bool: + if not isinstance(func, OpOverload): + raise AssertionError(f"func must be an OpOverload, got {type(func)}") + schema = func._schema + if any(contains_tensor_types(arg.type) for arg in schema.arguments): + return False + # TODO: no real reason to restrict multiple outputs + return ( + len(schema.returns) == 1 and schema.returns[0].type is torch._C.TensorType.get() + ) + + +@functools.cache +def _has_device_arg(func: OpOverload) -> bool: + device_type = torch._C.DeviceObjType.get() + optional_device_type = torch._C.OptionalType(device_type) + return any( + arg.name == "device" + and ( + arg.type.isSubtypeOf(device_type) + or arg.type.isSubtypeOf(optional_device_type) + ) + for arg in func._schema.arguments + ) + + +def register_op_impl( + run_impl_check: Callable[[OpOverload], bool] + | OpOverload + | list[OpOverload] + | tuple[OpOverload, ...], +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + def impl_decorator(op_impl: Callable[_P, _R]) -> Callable[_P, _R]: + if isinstance(run_impl_check, OpOverload): + if run_impl_check in op_implementations_dict: + raise AssertionError(f"duplicate registration: {run_impl_check}") + op_implementations_dict[run_impl_check] = op_impl + schema = run_impl_check._schema + torch._C._fake_dispatch_register_op_impl(schema.name, schema.overload_name) + elif isinstance(run_impl_check, (list, tuple)): + for op in run_impl_check: + register_op_impl(op)(op_impl) + else: + if not callable(run_impl_check): + raise AssertionError( + f"run_impl_check must be callable, got {type(run_impl_check)}" + ) + op_implementations_checks.append((run_impl_check, op_impl)) + + return op_impl + + return impl_decorator + + +def _is_op_registered_to_fake_rule(op: OpOverload) -> bool: + return op in op_implementations_dict + + +def _deregister_op_impl(op: OpOverload) -> None: + if op in op_implementations_dict: + op_implementations_dict.pop(op, None) + torch._C._fake_dispatch_deregister_op_impl( + op._schema.name, op._schema.overload_name + ) + for check, impl in op_implementations_checks: + if check is op: + op_implementations_checks.remove((check, impl)) + break + + +@register_op_impl(op_implementations_dict.__contains__) +def dispatch_to_op_implementations_dict( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> Any: + return op_implementations_dict[func](fake_mode, func, *args, **kwargs) + + +@register_op_impl(_is_tensor_constructor) +@register_op_impl([*_like_tensor_constructors]) +def constructors( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> FakeTensor: + if func in _non_kwarg_device_constructors: + raise AssertionError( + f"func must not be in _non_kwarg_device_constructors, got {func}" + ) + _, new_kwargs = _normalize_function_or_error( + func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True + ) + + if func in _like_tensor_constructors: + default_device = new_kwargs["input"].device + # TODO: file issue + args = (new_kwargs.pop("input"),) + else: + # cpu is default device if none is specified + default_device = torch.device("cpu") + args = () + has_device_arg = _has_device_arg(func) + out_device = new_kwargs.pop("device", None) if has_device_arg else None + out_device = out_device if out_device is not None else default_device + if has_device_arg: + new_kwargs["device"] = torch.device("meta") + # _like constructors have fake tensor inputs (maybe this causes the non-like + # to fail? hmmm) + with in_kernel_invocation_manager(fake_mode): + r = func(*args, **new_kwargs) + if r.device.type == "meta": + return fake_mode.fake_tensor_converter.from_meta_and_device( + fake_mode, r, out_device + ) + return fake_mode.fake_tensor_converter.from_real_tensor(fake_mode, r) + + +@register_op_impl(aten.is_pinned.default) +def non_kwarg_is_pinned( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> bool: + _, new_kwargs = _normalize_function_or_error( + func, args, kwargs, normalize_to_only_use_kwargs=True + ) + inp = new_kwargs.pop("input") + # we'll ignore device argument because it is deprecated and not + # actually used by is_pinned. + with in_kernel_invocation_manager(fake_mode): + r = func(inp) + return r + + +# Legacy profiler ops return Tensors but don't follow tensor constructor patterns +# They take string arguments and should not have device/dtype parameters added +@register_op_impl(torch.ops.profiler._record_function_enter.default) +def _record_function_enter( + fake_mode: FakeTensorMode, func: OpOverload, name: str, args: object | None = None +) -> FakeTensor: + # Call the real implementation to get a real handle tensor + with in_kernel_invocation_manager(fake_mode): + real_handle = func(name, args) + # Create a meta tensor with the same properties as the real handle + meta_handle = torch.empty_like(real_handle, device="meta") + # Wrap it as a FakeTensor + return FakeTensor(fake_mode, meta_handle, torch.device("cpu")) + + +@register_op_impl(torch.ops.profiler._record_function_exit.default) +def _record_function_exit( + fake_mode: FakeTensorMode, func: OpOverload, handle: Any +) -> None: + # Exit doesn't return anything and doesn't need to do anything for fake tensors + # Just return None (the actual return type is void) + pass + + +@register_op_impl(torch.ops.profiler._record_function_enter_new.default) +def _record_function_enter_new( + fake_mode: FakeTensorMode, func: OpOverload, name: str, args: object | None = None +) -> Any: + # Call the real implementation - returns a custom class, not a tensor + # Just pass through without wrapping + with in_kernel_invocation_manager(fake_mode): + return func(name, args) + + +@register_op_impl(aten.to.prim_Device) +@register_op_impl(aten.to.device) +def non_kwarg_to( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> FakeTensor: + _, new_kwargs = _normalize_function_or_error( + func, args, kwargs, normalize_to_only_use_kwargs=True + ) + input_device = new_kwargs["device"] + out_device = input_device if input_device else new_kwargs["input"].device + new_kwargs["device"] = torch.device("meta") + inp = new_kwargs.pop("input") + with in_kernel_invocation_manager(fake_mode): + r = func(inp, **new_kwargs) + # TODO: I think this does the wrong thing if r is inp + return fake_mode.fake_tensor_converter.from_meta_and_device( + fake_mode, r, out_device + ) + + +def stride_incorrect_op(op: OpOverload) -> bool: + return False + + +# These operators have meta implementations with incorrect strides +@register_op_impl(stride_incorrect_op) +def workaround_stride_incorrect_op( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> FakeTensor: + # This is a workaround for meta implementations with incorrect strides + + def is_symbolic(x: object) -> bool: + if is_fake_tensor(x): + return x._has_symbolic_sizes_strides + if isinstance(x, (torch.SymInt, torch.SymFloat, torch.SymBool)): + return True + return False + + # For static shapes, we can fall back to eager for the real strides + if fake_mode.allow_fallback_kernels: + require_dynamic = any( + is_symbolic(x) for x in itertools.chain(args, kwargs.values()) + ) + if not require_dynamic: + flat_args, args_spec = pytree.tree_flatten((args, kwargs)) + return run_fallback_kernel( + fake_mode, + func, + flat_args, + args_spec, + # TODO: refactor to lambda so we don't instantiate extra errors before + # calling + RuntimeError("Cannot run fallback kernel for stride_incorrect_op"), + ) + + raise UnsupportedOperatorException(func) + + +# Don't default to default device handling, +# since the device of `the_template` is ignored +@register_op_impl(aten.resize_as_.default) +def resize_as_( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> FakeTensor: + with in_kernel_invocation_manager(fake_mode): + return func(*args, **kwargs) + + +@register_op_impl(aten._sparse_coo_tensor_with_dims_and_tensors.default) +def _sparse_coo_tensor_with_dims_and_tensors( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> FakeTensor: + return constructors(fake_mode, func, *args, **kwargs) + + +def _spdiags_static_offsets(offsets: FakeTensorLike) -> list[int] | None: + constant = getattr(offsets, "constant", None) + if constant is None: + constant = getattr(offsets, "real_tensor", None) + if is_fake_tensor(constant): + return None + if constant is None or constant.device.type != "cpu": + return None + return [int(offset) for offset in constant.reshape(-1).tolist()] + + +def _spdiags_nnz(offsets: list[int], rows: int, cols: int, diag_cols: int) -> int: + nnz = 0 + pos_offset_limit = min(cols, diag_cols) + for offset in offsets: + if offset <= 0: + nnz_per_diag = min(offset + rows, diag_cols) + else: + nnz_per_diag = pos_offset_limit - offset + torch._check( + nnz_per_diag >= 0, + lambda: f"Trying to create tensor with negative dimension {nnz_per_diag}", + ) + nnz += nnz_per_diag + return nnz + + +def _spdiags_max_nnz_per_diag(rows: int, cols: int, diag_cols: int) -> int: + non_positive_offset_max = min(rows, diag_cols) + positive_offset_max = max(min(cols, diag_cols) - 1, 0) + return max(non_positive_offset_max, positive_offset_max, 0) + + +def _spdiags_dynamic_size( + fake_mode: FakeTensorMode, + func: OpOverload, + *, + max_size: int | None, +) -> torch.SymInt: + if ( + fake_mode.shape_env is None + or not fake_mode.shape_env.allow_dynamic_output_shape_ops + ): + raise DynamicOutputShapeException(func) + + nnz = fake_mode.shape_env.create_unbacked_symint() + + from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size + + _constrain_range_for_size(nnz, min=0, max=max_size) + return nnz + + +def _spdiags_is_static_int(value: object) -> bool: + return isinstance(value, int) and not isinstance(value, bool) + + +@register_op_impl(aten._spdiags.default) +def _spdiags( + fake_mode: FakeTensorMode, + func: OpOverload, + diagonals: FakeTensorLike, + offsets: FakeTensorLike, + shape: Sequence[int], + layout: torch.layout | None = None, +) -> FakeTensor: + diagonals_dim = diagonals.dim() + torch._check(diagonals_dim in (1, 2), lambda: "Diagonals must be vector or matrix") + torch._check(len(shape) == 2, lambda: "Output shape must be 2d") + + offsets_dim = offsets.dim() + torch._check(offsets_dim in (0, 1), lambda: "Offsets must be scalar or vector") + + n_diags = 1 if diagonals_dim == 1 else diagonals.size(0) + n_offsets = 1 if offsets_dim == 0 else offsets.size(0) + torch._check( + n_diags == n_offsets, + lambda: f"Number of diagonals ({n_diags}) does not match the number of offsets ({n_offsets})", + ) + + if layout is not None: + torch._check( + layout in (torch.sparse_coo, torch.sparse_csc, torch.sparse_csr), + lambda: f"Only output layouts (Sparse, SparseCsc, SparseCsr) are supported, got {layout}", + ) + torch._check( + offsets.dtype == torch.long, + lambda: f"Offset Tensor must have dtype Long but got {offsets.dtype}", + ) + torch._check( + diagonals.device.type == "cpu" and offsets.device.type == "cpu", + lambda: "_spdiags is only implemented for CPU tensors", + ) + + rows, cols = shape + diag_cols = diagonals.size(0) if diagonals_dim == 1 else diagonals.size(1) + static_sizes = all( + _spdiags_is_static_int(value) for value in (rows, cols, diag_cols, n_offsets) + ) + + static_offsets = _spdiags_static_offsets(offsets) + if static_offsets is not None: + torch._check( + len(static_offsets) == len(set(static_offsets)), + lambda: "Offset tensor contains duplicate values", + ) + + out_layout = layout if layout is not None else torch.sparse_coo + if static_sizes and (rows == 0 or cols == 0): + nnz = 0 + elif static_offsets is not None and static_sizes: + nnz = _spdiags_nnz(static_offsets, rows, cols, diag_cols) # type: ignore[arg-type] + elif static_sizes and n_offsets == 0: + nnz = 0 + else: + max_nnz = ( + n_offsets * _spdiags_max_nnz_per_diag(rows, cols, diag_cols) + if static_sizes + else None + ) + nnz = _spdiags_dynamic_size(fake_mode, func, max_size=max_nnz) # type: ignore[arg-type] + + with in_kernel_invocation_manager(fake_mode): + values = torch.empty((nnz,), dtype=diagonals.dtype, device="meta") + with torch.sparse.check_sparse_tensor_invariants(False): + if out_layout == torch.sparse_coo: + indices = torch.empty((2, nnz), dtype=torch.long, device="meta") + is_coalesced = nnz <= 1 if isinstance(nnz, int) else False + out = torch.ops.aten._sparse_coo_tensor_unsafe.default( + indices, + values, + shape, + device=torch.device("meta"), + is_coalesced=is_coalesced, + ) + elif out_layout == torch.sparse_csr: + crow_indices = torch.empty((rows + 1,), dtype=torch.long, device="meta") + col_indices = torch.empty((nnz,), dtype=torch.long, device="meta") + out = torch.ops.aten._sparse_compressed_tensor_unsafe.default( + crow_indices, + col_indices, + values, + shape, + layout=out_layout, + device=torch.device("meta"), + ) + else: + ccol_indices = torch.empty((cols + 1,), dtype=torch.long, device="meta") + row_indices = torch.empty((nnz,), dtype=torch.long, device="meta") + out = torch.ops.aten._sparse_compressed_tensor_unsafe.default( + ccol_indices, + row_indices, + values, + shape, + layout=out_layout, + device=torch.device("meta"), + ) + + return fake_mode.fake_tensor_converter.from_meta_and_device( + fake_mode, out, diagonals.device + ) + + +@register_op_impl(aten._to_dense.default) +def _to_dense( + fake_mode: FakeTensorMode, + func: OpOverload, + self: FakeTensor, + dtype: torch.dtype | None = None, + masked_grad: bool | None = None, +) -> FakeTensor: + maybe_mkldnn_out = maybe_to_dense_mkldnn(fake_mode, self, dtype, masked_grad) + if maybe_mkldnn_out is not NotImplemented: + return typing_cast(FakeTensor, maybe_mkldnn_out) + + if self.layout is torch.sparse_coo: + if dtype is not None: + raise RuntimeError("dtype argument is not supported by sparse_to_dense") + with in_kernel_invocation_manager(fake_mode): + out = torch.empty( + tuple(self.shape), + dtype=self.dtype, + device="meta", + ) + return FakeTensor(fake_mode, out, self.fake_device) + + with in_kernel_invocation_manager(fake_mode): + out = func(self, dtype=dtype, masked_grad=masked_grad) + return fake_mode.fake_tensor_converter.from_meta_and_device( + fake_mode, out, self.fake_device + ) + + +# index.Tensor data-dependent in only some conditions +@register_op_impl( + lambda func: torch.Tag.dynamic_output_shape in func.tags + and func + not in [aten.index.Tensor, aten.nonzero.default, aten.repeat_interleave.Tensor] +) +def dyn_shape( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> None: + raise DynamicOutputShapeException(func) + + +def _unique( + fake_mode: FakeTensorMode, + func: OpOverload, + arg: FakeTensor, + dim: int | None, + sorted: bool = True, + return_inverse: bool = False, + return_counts: bool = False, + *, + unique_consecutive: bool = False, +) -> tuple[FakeTensor, FakeTensor, FakeTensor]: + if ( + fake_mode.shape_env is None + or not fake_mode.shape_env.allow_dynamic_output_shape_ops + ): + # Without symints/symfloats, cannot handle this + raise DynamicOutputShapeException(func) + + nnz = arg.unique_consecutive_memo if unique_consecutive else arg.unique_memo + + # Do not use a memo for unique_dim + if dim is not None or nnz is None: + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import ( + _constrain_range_for_size, + has_free_symbols, + ) + + if not has_free_symbols(arg.numel()) and arg.numel() == 0: + # If numel is zero, then the output size must be zero. + # In this case, we must not allocate an unbacked SymInt, + # because if we do, it will immediately get refined to + # zero, but this will be inconsistent with size oblivious + # tests (which will continue to claim that the unbacked + # symint cannot equal zero). We could also unconditionally + # allocate an unbacked SymInt and not refine its range, + # but this seems more precise. + nnz = 0 + else: + nnz = fake_mode.shape_env.create_unbacked_symint() + + maxval = sys.maxsize - 1 + + numel = arg.numel() if dim is None else arg.size(dim) + if not has_free_symbols(numel): + maxval = int(numel) + + _constrain_range_for_size(nnz, max=maxval) + + if dim is None: + if unique_consecutive: + arg.unique_consecutive_memo = nnz # pyrefly: ignore[bad-assignment] + else: + arg.unique_memo = nnz # pyrefly: ignore[bad-assignment] + + if dim is None: + # pyrefly: ignore[no-matching-overload] + ret = [arg.new_empty((nnz,))] + else: + # pyrefly: ignore[no-matching-overload] + ret = [arg.new_empty(*arg.shape[:dim], nnz, *arg.shape[dim + 1 :])] + + return_if_dim_and_cpu = dim is not None and arg.fake_device == torch.device("cpu") + if return_inverse or return_if_dim_and_cpu: + inverse = arg.new_empty( + arg.shape if dim is None else (arg.shape[dim],), dtype=torch.int64 + ) + else: + inverse = arg.new_empty(0, dtype=torch.int64) + ret.append(inverse) + + if return_counts or return_if_dim_and_cpu: + counts = arg.new_empty( + ret[0].shape if dim is None else (ret[0].shape[dim],), dtype=torch.int64 + ) + else: + counts = arg.new_empty(0, dtype=torch.int64) + ret.append(counts) + + return tuple(ret) + + +@register_op_impl(aten._unique2.default) +def unique2( + fake_mode: FakeTensorMode, + func: OpOverload, + arg: FakeTensor, + sorted: bool = True, + return_inverse: bool = False, + return_counts: bool = False, +) -> tuple[FakeTensor, FakeTensor, FakeTensor]: + return _unique(fake_mode, func, arg, None, sorted, return_inverse, return_counts) + + +@register_op_impl(aten._unique.default) +def unique( + fake_mode: FakeTensorMode, + func: OpOverload, + arg: FakeTensor, + sorted: bool = True, + return_inverse: bool = False, +) -> tuple[FakeTensor, FakeTensor]: + uniques, inverse, _counts = _unique( + fake_mode, func, arg, None, sorted, return_inverse, False + ) + return uniques, inverse + + +@register_op_impl(aten.select.int) +def meta_select( + fake_mode: FakeTensorMode, + func: OpOverload, + self: FakeTensor, + dim: int, + index: IntLikeType, +) -> FakeTensor: + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if self.is_sparse: + return NotImplemented + + ndim = self.dim() + torch._check_index( + ndim != 0, + lambda: "select() cannot be applied to a 0-dim tensor.", + ) + + dim = dim if dim >= 0 else dim + ndim + size = self.size(dim) + + if guard_or_false(index >= size) or guard_or_false(index < -size): + torch._check_index( + False, + lambda: f"select(): index {index} out of range for tensor of size " + f"{list(self.size())} at dimension {dim}", + ) + + new_size = list(self.size()) + new_stride = list(self.stride()) + + new_storage_offset = None + if guard_or_false(index >= 0): + new_storage_offset = self.storage_offset() + index * new_stride[dim] + elif guard_or_false(index < 0): + new_storage_offset = self.storage_offset() + (index + size) * new_stride[dim] + + if new_storage_offset is None: + if fake_mode.shape_env is None or ( + not fake_mode.shape_env.allow_scalar_outputs + and not fake_mode.allow_scalar_outputs + ): + raise DataDependentOutputException(func) + + # index is data-dependent, we do not know which index we are accessing it could be index or index+size! + # we assign a new data-dependent symbol for the storage offset. + new_storage_offset = fake_mode.shape_env.create_unbacked_symint() + + del new_size[dim] + del new_stride[dim] + if new_storage_offset is None: + raise AssertionError("new_storage_offset must not be None") + # pyrefly: ignore[bad-return] + return self.as_strided(new_size, new_stride, new_storage_offset) + + +@register_op_impl(aten.unique_dim.default) +def unique_dim( + fake_mode: FakeTensorMode, + func: OpOverload, + arg: FakeTensor, + dim: int, + sorted: bool = True, + return_inverse: bool = False, + return_counts: bool = False, +) -> tuple[FakeTensor, FakeTensor, FakeTensor]: + return _unique( + fake_mode, + func, + arg, + # normalize dim to be non-negative + dim if dim >= 0 else dim % max(arg.ndim, 1), + sorted, + return_inverse, + return_counts, + ) + + +@register_op_impl(aten.unique_consecutive.default) +def unique_consecutive( + fake_mode: FakeTensorMode, + func: OpOverload, + arg: FakeTensor, + return_inverse: bool = False, + return_counts: bool = False, + dim: int | None = None, +) -> tuple[FakeTensor, FakeTensor, FakeTensor]: + return _unique( + fake_mode, + func, + arg, + dim, + False, + return_inverse, + return_counts, + unique_consecutive=True, + ) + + +# This function is python match of computeStride_impl in TensorUtils.cpp +def _compute_stride( + old_shape: Sequence[IntLikeType], + old_stride: Sequence[IntLikeType], + new_shape: Sequence[IntLikeType], + size_oblivious: bool = False, +) -> list[IntLikeType] | None: + from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + guard_or_true, + sym_eq, + ) + + def maybe_guard_or_false(x: Any) -> Any: + if size_oblivious: + return guard_or_false(x) + + return x + + def maybe_guard_or_true(x: Any) -> Any: + if size_oblivious: + return guard_or_true(x) + + return x + + if len(old_shape) == 0: + return [1] * len(new_shape) + + numel = reduce(operator.mul, old_shape, 1) + zero_numel = maybe_guard_or_false(numel == 0) + if zero_numel and maybe_guard_or_false(sym_eq(old_shape, new_shape)): + return list(old_stride) + + new_stride: list[IntLikeType] = [0] * len(new_shape) + + if zero_numel: + for view_d in range(len(new_shape) - 1, -1, -1): + if view_d == len(new_shape) - 1: + new_stride[view_d] = 1 + else: + new_stride[view_d] = ( + max(new_shape[view_d + 1], 1) * new_stride[view_d + 1] + ) + return new_stride + + view_d = len(new_shape) - 1 + # Annotate type here to support type checking + chunk_base_stride: IntLikeType = old_stride[-1] + tensor_numel: IntLikeType = 1 + view_numel: IntLikeType = 1 + + for tensor_d in range(len(old_shape) - 1, -1, -1): + tensor_numel *= old_shape[tensor_d] + + if tensor_d == 0 or ( + maybe_guard_or_true(old_shape[tensor_d - 1] != 1) + and maybe_guard_or_true( + old_stride[tensor_d - 1] != tensor_numel * chunk_base_stride + ) + ): + while view_d >= 0 and ( + maybe_guard_or_true(view_numel < tensor_numel) + or maybe_guard_or_false(new_shape[view_d] == 1) + ): + new_stride[view_d] = view_numel * chunk_base_stride + view_numel *= new_shape[view_d] + view_d -= 1 + + if maybe_guard_or_true(view_numel != tensor_numel): + return None + + if tensor_d > 0: + chunk_base_stride = old_stride[tensor_d - 1] + tensor_numel = 1 + view_numel = 1 + if view_d != -1: + return None + return new_stride + + +def _optimization_hint_or_none(value: Any) -> int | None: + if type(value) is int: + return value + if isinstance(value, torch.SymInt): + from torch.fx.experimental.symbolic_shapes import optimization_hint + + return optimization_hint(value, fallback=None) + return None + + +def _hinted_eq(lhs: Any, rhs: Any) -> bool: + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(lhs == rhs): + return True + + lhs_hint = _optimization_hint_or_none(lhs) + rhs_hint = _optimization_hint_or_none(rhs) + if lhs_hint is None or rhs_hint is None or lhs_hint != rhs_hint: + return False + + # Hints are not shape semantics. They only show that the equality is true + # for the traced example, so record the symbolic equality required for the + # view rather than specializing either side to a concrete value. + torch._check(lhs == rhs) + return True + + +def _is_contiguous_with_hinted_checks(a: torch.Tensor) -> bool: + from torch.fx.experimental.symbolic_shapes import guard_or_false, is_nested_int + + if guard_or_false(a.numel() < 2): + return True + + numel_hint = _optimization_hint_or_none(a.numel()) + if numel_hint is None: + return False + if numel_hint < 2: + torch._check(a.numel() < 2) + return True + + expected_stride = 1 + expected_stride_max = 1 + for size, stride in reversed(tuple(zip(a.shape, a.stride()))): + if guard_or_false(size == 1): + continue + + size_hint = _optimization_hint_or_none(size) + if size_hint == 1: + torch._check(size == 1) + continue + + if not _hinted_eq(stride, expected_stride) and not _hinted_eq( + stride, expected_stride_max + ): + return False + + expected_stride_max *= size if is_nested_int(size) else torch.sym_max(size, 1) + expected_stride *= size + + return True + + +def _view_has_unbacked_input( + a: torch.Tensor, shape: ShapeType | tuple[ShapeType] +) -> bool: + from torch.fx.experimental.symbolic_shapes import has_guarding_hint + + shape = utils.extract_shape_from_varargs(shape, validate=False) + + return ( + any(not has_guarding_hint(s) for s in a.size()) + or any(not has_guarding_hint(s) for s in a.stride()) + or any(not has_guarding_hint(s) for s in shape) + ) + + +def try_duck_specialization_first(a: torch.Tensor, shape) -> bool: + """ + Collect candidate (x, y) pairs whose runtime hints match (so they + *could* be equal), then test whether substituting them into the + view's numel equation makes the equation symbolically zero. + Only commit the equalities (adds the real Eq guards via bool(x == y) + which triggers set_replacement) if the substitution actually solves + the view validity check. + + This avoids polluting the shape env with spurious guards from probing. + + Returns True if at least one equality was committed. + + Conservative: only considers SymInts that appear as a top-level dim of + the input or target (skipping the -1 marker), and skips already-equal + pairs, and skips unbacked symbols. + """ + import operator + from functools import reduce + + from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols + + def _atomic_syms(dims) -> list[torch.SymInt]: + """Keep only SymInts whose expr is a single bare *backed* symbol.""" + out: list[torch.SymInt] = [] + for s in dims: + if not isinstance(s, torch.SymInt): + continue + expr = s.node.expr + free = expr.free_symbols + if len(free) != 1 or expr not in free: + continue + if free_unbacked_symbols(expr): + continue + out.append(s) + return out + + import sympy + + a_syms = _atomic_syms(a.size()) + target_syms = _atomic_syms(shape) + if not a_syms or not target_syms: + return False + + # 1) Bucket symbols by hint, deduplicated by sympy expr (one SymInt per + # unique expr per hint). Each non-trivial bucket is a duck-equality + # class: every member of the class will be set equal to the bucket's + # canonical symbol. This keeps `subs` and `candidates` perfectly in + # sync so the numel check exactly reflects what we'll commit. + from collections import defaultdict + + buckets: dict[int, dict[sympy.Expr, torch.SymInt]] = defaultdict(dict) + for s in list(a_syms) + list(target_syms): + # setdefault keeps the *first* SymInt seen for each (hint, expr). + # pyrefly: ignore [bad-index] + buckets[s.node.hint].setdefault(s.node.expr, s) + + candidates: list[tuple[torch.SymInt, torch.SymInt]] = [] + for members in buckets.values(): + canonical, *rest = members.values() + for m in rest: + candidates.append((canonical, m)) + + if not candidates: + return False + + # `subs` is derived from `candidates`, so they cannot drift. + subs: dict[sympy.Expr, sympy.Expr] = { + m.node.expr: c.node.expr for c, m in candidates + } + + # 2) Symbolic test: does the substitution make the view's numel match? + def _expr_of(s): + return s.node.expr if isinstance(s, torch.SymInt) else s + + try: + a_numel = reduce(operator.mul, (_expr_of(s) for s in a.size()), 1) + shape_numel = reduce(operator.mul, (_expr_of(s) for s in shape), 1) + diff = sympy.simplify((a_numel - shape_numel).subs(subs)) + if diff != 0: + return False + except (TypeError, ValueError, AttributeError, sympy.SympifyError): + return False + + # 3) Commit the equalities for real (adds Eq guards, triggers set_replacement). + for c, m in candidates: + torch._check(c == m) + return True + + +def _view_unbacked_meta( + a: torch.Tensor, + shape: ShapeType | tuple[ShapeType], + size_oblivious_enabled: bool = True, + allow_copy: bool = False, + tried_duck_specialize: bool = False, +) -> torch.Tensor: + from torch._prims import view_of + from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq + + # Creates a valid shape + shape = utils.extract_shape_from_varargs(shape, validate=False) + + # Reshape may be given a shape with a -1 length + # This indicates that the dimension's length should be inferred + shape = utils.infer_size(shape, a.numel()) + + # Special-cases reshaping zero dim tensors + if a.ndim == 0: + _a = a + for length in shape: + torch._check(length == 1) + _a = torch._refs.unsqueeze(_a, -1) + if _a is a: + return view_of(a) + else: + return _a # type: ignore[return-value] + + # Special-cases reshaping to zero dim tensors + if len(shape) == 0: + _a = a + for length in a.shape: + torch._check(length == 1) + _a = torch._refs.squeeze(_a, -1) + if _a is a: + return view_of(a) + else: + return _a # type: ignore[return-value] + + shape_numel = reduce(operator.mul, shape, 1) + + torch._check( + a.numel() == shape_numel, + lambda: f"Could not reshape a tensor with shape {a.shape} as a tensor with shape {shape}!", + ) + + if len(shape) == len(a.shape) and guard_or_false(sym_eq(shape, a.shape)): + return view_of(a) + + if is_contiguous_or_false(a) if size_oblivious_enabled else is_contiguous(a): + strides = make_contiguous_strides_for(shape) + return a.as_strided(shape, strides) # type: ignore[return-value] + + new_strides = _compute_stride( + a.size(), a.stride(), shape, size_oblivious=size_oblivious_enabled + ) + + if new_strides is not None: + return a.as_strided(shape, new_strides) # type: ignore[return-value] + + # If we fail to do size oblivious view, and backed_size_oblivious was on, + # then we redo everything by looking at hints and guarding instead of failing. + # Also if the expression has unbacked symbols, then we run again with size_oblivious_enabled=False + # to throw a data dependent error. + + if size_oblivious_enabled and ( + torch.fx.experimental._config.backed_size_oblivious + or _view_has_unbacked_input(a, shape) + ): + # Heuristic: before falling through to the specializing recursion + # (which often emits Eq(s, 1) via eval_eager), try to discover + # cross-symbol equalities between input and target shape symbols. + # If a pair (x, y) is True at the runtime hint, the shape env will + # record Eq(x, y) and set_replacement unifies them — letting the + # size-oblivious view path succeed without specialization on x==1. + # But with potential duck specializations which are more general. + if ( + torch.fx.experimental._config.unify_view_symbols_bso_meta + and not tried_duck_specialize + and try_duck_specialization_first(a, shape) + ): + return _view_unbacked_meta( + a, + shape, + size_oblivious_enabled=True, + allow_copy=allow_copy, + tried_duck_specialize=True, + ) + + if _is_contiguous_with_hinted_checks(a): + strides = make_contiguous_strides_for(shape) + return a.as_strided(shape, strides) # type: ignore[return-value] + + return _view_unbacked_meta( + a, shape, size_oblivious_enabled=False, allow_copy=allow_copy + ) + + # When allow_copy=True (i.e., view_copy), define unbacked semantics + # as "materialize": clone the input to break aliasing, then reshape. + if allow_copy: + strides = make_contiguous_strides_for(shape) + # pyrefly: ignore[bad-return] + return a.clone(memory_format=torch.contiguous_format).as_strided(shape, strides) + + msg = f"Cannot view a tensor with shape {a.shape} and strides {a.stride()} as a tensor with shape {shape}!" + raise ValueError(msg) + + +@register_op_impl(aten._reshape_copy.default) +def _reshape_copy( + fake_mode: FakeTensorMode, func: OpOverload, a: FakeTensor, *shape: Any +) -> FakeTensor | Exception: + if a.is_sparse or a.is_mkldnn: + return NotImplemented + + # pyrefly: ignore[bad-argument-count] + shape = utils.infer_size(*shape, a.numel()) + if is_contiguous_or_false(a): + view = _view_meta(fake_mode, func, a, *shape) + return typing_cast( + FakeTensor, view.clone(memory_format=torch.contiguous_format) + ) + else: + return _view_meta( + fake_mode, + func, + typing_cast(FakeTensor, a.clone(memory_format=torch.contiguous_format)), + *shape, + ) + + +@register_op_impl(aten.view.default) +@register_op_impl(aten._unsafe_view.default) +def _view_meta( + fake_mode: FakeTensorMode, + func: OpOverload, + a: FakeTensor, + *shape: Any, + allow_copy: bool = False, +) -> FakeTensor: + if torch.fx.experimental._config.backed_size_oblivious or _view_has_unbacked_input( + a, shape + ): + return typing_cast( + FakeTensor, _view_unbacked_meta(a, shape, allow_copy=allow_copy) + ) + else: + return typing_cast( + FakeTensor, + torch._refs._reshape_view_helper(a, *shape, allow_copy=allow_copy), + ) + + +@register_op_impl(aten.view_copy.default) +def _view_meta_copy( + fake_mode: FakeTensorMode, + func: OpOverload, + a: FakeTensor, + *shape: IntLikeType, + out: FakeTensor | None = None, +) -> FakeTensor: + # view_copy is the non-aliasing counterpart of view. Eager may succeed on + # cases where a pure view is impossible (e.g. expand -> flatten) by + # materializing the result. Match eager by allowing copy-if-needed in meta. + result = _view_meta(fake_mode, func, a, *shape, allow_copy=True) + + if out is not None: + return result + + return pytree.tree_map( + lambda x: x.clone(memory_format=torch.contiguous_format), + result, + ) + + +@register_op_impl(aten.repeat_interleave.Tensor) +def repeat_interleave_tensor( + fake_mode: FakeTensorMode, + func: OpOverload, + repeats: FakeTensor, + output_size: IntLikeType | None = None, +) -> FakeTensor: + if output_size is None: + if ( + fake_mode.shape_env is None + or not fake_mode.shape_env.allow_dynamic_output_shape_ops + ): + raise DynamicOutputShapeException(func) + + output_size = fake_mode.shape_env.create_unbacked_symint() + + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size + + _constrain_range_for_size(output_size) + # TODO: consider a memo + return repeats.new_empty(output_size) # type: ignore[return-value] + + +@register_op_impl(torch.ops.aten.item.default) +@register_op_impl(torch.ops.aten._local_scalar_dense.default) +def local_scalar_dense( + fake_mode: FakeTensorMode, func: OpOverload, arg: FakeTensor +) -> int | float | bool | torch.SymInt | torch.SymFloat | torch.SymBool: + if (r := arg.item_memo) is not None: + return r + if fake_mode.shape_env is None or ( + not fake_mode.shape_env.allow_scalar_outputs + and not fake_mode.allow_scalar_outputs + ): + # Without symints/symfloats, cannot handle this + raise DataDependentOutputException(func) + if is_float_dtype(arg.dtype): + r = fake_mode.shape_env.create_unbacked_symfloat() + elif is_integer_dtype(arg.dtype): + r = fake_mode.shape_env.create_unbacked_symint() + elif is_boolean_dtype(arg.dtype): + r = fake_mode.shape_env.create_unbacked_symbool() + else: + raise NotImplementedError(f"local_scalar_dense/item NYI for {arg.dtype}") + arg.item_memo = r + return r + + +@register_op_impl(torch.ops.aten.nonzero_numpy.default) +def nonzero_numpy( + fake_mode: FakeTensorMode, func: OpOverload, arg: FakeTensor +) -> list[FakeTensor]: + return torch.ops.aten.nonzero.default(arg).unbind(1) + + +@register_op_impl(torch.ops.aten.nonzero.default) +def nonzero(fake_mode: FakeTensorMode, func: OpOverload, arg: FakeTensor) -> FakeTensor: + if ( + fake_mode.shape_env is None + or not fake_mode.shape_env.allow_dynamic_output_shape_ops + ): + # Without symints/symfloats, cannot handle this + raise DynamicOutputShapeException(func) + + if (nnz := arg.nonzero_memo) is None: + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import ( + _constrain_range_for_size, + has_free_symbols, + ) + from torch.utils._sympy.numbers import IntInfinity + from torch.utils._sympy.value_ranges import bound_sympy + + if not has_free_symbols(arg.numel()) and arg.numel() == 0: + # If numel is zero, then the output size must be zero. + # In this case, we must not allocate an unbacked SymInt, + # because if we do, it will immediately get refined to + # zero, but this will be inconsistent with size oblivious + # tests (which will continue to claim that the unbacked + # symint cannot equal zero). We could also unconditionally + # allocate an unbacked SymInt and not refine its range, + # but this seems more precise. + nnz = 0 + else: + nnz = fake_mode.shape_env.create_unbacked_symint() + + maxval = sys.maxsize - 1 + + if not has_free_symbols(arg.numel()): + maxval = int(arg.numel()) + else: + prod_node = math.prod(arg.shape).node # type: ignore[union-attr] + prod_range = bound_sympy( + prod_node.expr, prod_node.shape_env.var_to_range + ) + if isinstance(prod_range.upper, IntInfinity): + maxval = sys.maxsize - 1 + else: + maxval = prod_range.upper + + _constrain_range_for_size(nnz, max=maxval) + + arg.nonzero_memo = nnz # pyrefly: ignore[bad-assignment] + return arg.new_empty_strided((nnz, arg.dim()), (1, nnz), dtype=torch.int64) # type: ignore[return] + + +@register_op_impl(torch.ops.aten._padded_dense_to_jagged_forward.default) +def _padded_dense_to_jagged_forward( + fake_mode: FakeTensorMode, + func: OpOverload, + padded: FakeTensor, + offsets: list[FakeTensor], + total_L: IntLikeType | None = None, +) -> FakeTensor: + # only one jagged dim is supported for now + if len(offsets) != 1: + raise AssertionError( + f"Only one jagged dim is supported, got {len(offsets)} offsets" + ) + + if total_L is None: + if ( + fake_mode.shape_env is None + or not fake_mode.shape_env.allow_dynamic_output_shape_ops + ): + # Without symints/symfloats, cannot handle this + raise DynamicOutputShapeException(func) + + total_L = fake_mode.shape_env.create_unbacked_symint() + + maxval = sys.maxsize - 1 + + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import ( + _constrain_range_for_size, + has_free_symbols, + ) + + if not has_free_symbols(padded.numel()): + maxval = int(padded.numel()) + + _constrain_range_for_size(total_L, min=0, max=maxval) + + output_shape = (total_L, *padded.shape[2:]) + return padded.new_empty(output_shape) # type: ignore[return] + + +def _compute_slice_index(size: IntLikeType, index: IntLikeType) -> IntLikeType | None: + from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_and + + if guard_or_false(sym_and(index >= 0, index <= size)): + return index + elif guard_or_false(sym_and(index < 0, index >= -size)): + return index + size + elif guard_or_false(index < -size): + return 0 + elif guard_or_false(index > size): + return size + elif guard_or_false(index >= 0): + return torch.sym_min(index, size) + elif guard_or_false(index < 0): + return torch.sym_max(index + size, 0) + + return None + + +@register_op_impl(torch.ops.aten.slice.Tensor) +def slice_forward( + fake_mode: FakeTensorMode, + func: OpOverload, + self: FakeTensor, + dim: int = 0, + start: int | None = None, + end: int | None = None, + step: int = 1, +) -> FakeTensor: + from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + statically_known_true, + ) + + shape_env = fake_mode.shape_env + ndim = self.dim() + if ndim == 0: + raise RuntimeError("slice() cannot be applied to a 0-dim tensor.") + dim = canonicalize_dim(self.dim(), dim) + sizes = list(self.size()) + strides = list(self.stride()) + + if step <= 0: + raise RuntimeError("slice step must be positive") + + # start, end + start_index = 0 if start is None else _compute_slice_index(sizes[dim], start) + end_index = ( + sizes[dim] + if statically_known_true(end == sys.maxsize) or end is None + else _compute_slice_index(sizes[dim], end) + ) + + # size + new_size: IntLikeType | None = None + if start_index is not None and end_index is not None: + if guard_or_false(end_index >= start_index): + new_size = (end_index - start_index + step - 1) // step # type: ignore[bad-assignment] + elif guard_or_false(start_index >= end_index): + new_size = 0 + else: + # Both indices are resolved but we can't statically determine their + # ordering (e.g., when they involve Min/Max). Compute the size via + # max(end - start, 0) to avoid creating an unbacked symint. + diff = torch.sym_max(end_index - start_index, 0) + new_size = (diff + step - 1) // step # type: ignore[assignment] + + # create unbacked if case unknown + if new_size is None: + if shape_env is None: + raise AssertionError("Must have shape_env to create symint") + new_size = shape_env.create_unbacked_symint() + torch._check(new_size >= 0) + torch._check(new_size <= sizes[dim]) + + # stride + new_stride = strides[dim] * step + + # storage offset + if start_index is not None: + storage_offset = self.storage_offset() + start_index * strides[dim] + else: + if shape_env is None: + raise AssertionError("Must have shape_env to create symint") + storage_offset = shape_env.create_unbacked_symint() + torch._check(storage_offset >= 0) + + sizes[dim] = new_size # type: ignore[unsupported-operation] + strides[dim] = new_stride + if self.is_quantized: + raise NotImplementedError( + "Slice decomposition for quantized tensors aren't implemented" + ) + else: + return self.as_strided(sizes, strides, storage_offset) # type: ignore[return-value] + + +@register_op_impl(torch.ops.aten.masked_select.default) +def masked_select( + fake_mode: FakeTensorMode, func: OpOverload, self: FakeTensor, mask: FakeTensor +) -> FakeTensor: + if ( + fake_mode.shape_env is None + or not fake_mode.shape_env.allow_dynamic_output_shape_ops + ): + # Without symints/symfloats, cannot handle this + raise DynamicOutputShapeException(func) + + nnz = fake_mode.shape_env.create_unbacked_symint() + + # see nonzero for commentary + maxval = sys.maxsize - 1 + + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import ( + _constrain_range_for_size, + has_free_symbols, + ) + from torch.utils._sympy.numbers import IntInfinity + from torch.utils._sympy.value_ranges import bound_sympy + + # If num elements is expressed symbolically, calculate + # the concrete value based on upper bounds. Otherwise, + # we can set max val directly. + if not has_free_symbols(self.numel()): + num_elements = int(self.numel()) + else: + prod_node = math.prod(self.shape).node # type: ignore[union-attr] + prod_range = bound_sympy(prod_node.expr, prod_node.shape_env.var_to_range) + if isinstance(prod_range.upper, IntInfinity): + num_elements = sys.maxsize - 1 + else: + num_elements = prod_range.upper + if num_elements > 2: + maxval = num_elements + + _constrain_range_for_size(nnz, max=maxval) + + return self.new_empty((nnz,)) # type: ignore[return] + + +@register_op_impl(torch.ops.aten._assert_tensor_metadata.default) +def assert_tensor_metadata( + fake_mode: FakeTensorMode, + func: OpOverload, + t: FakeTensor, + size: list[int] | None = None, + stride: list[int] | None = None, + dtype: torch.dtype | None = None, + *, + device: torch.device | None = None, + layout: torch.layout | None = None, +) -> None: + if size is not None: + if t.size() != tuple(size): + raise AssertionError( + f"Tensor size mismatch! Expected: {size}, Got: {t.size()}" + ) + if stride is not None: + if t.stride() != tuple(stride): + raise AssertionError( + f"Tensor stride mismatch! Expected: {stride}, Got: {t.stride()}" + ) + if dtype is not None: + if t.dtype != dtype: + raise AssertionError( + f"Tensor dtype mismatch! Expected: {dtype}, Got: {t.dtype}" + ) + if layout is not None: + if t.layout != layout: + raise AssertionError( + f"Tensor layout mismatch! Expected: {layout}, Got: {t.layout}" + ) + if device is not None: + if t.device != device: + raise AssertionError( + f"Tensor device mismatch! Expected: {device}, Got: {t.device}" + ) + + +# NB: this must be ordered after local_scalar_dense +@register_op_impl(lambda func: torch.Tag.data_dependent_output in func.tags) +def data_dep( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> None: + raise DataDependentOutputException(func) + + +# Bool Indices get Expanded as Masks +# See: IndexingUtils.h:expandTensors +def check_no_bool_index_tensors( + func: OpOverload, self: FakeTensor, indices: list[FakeTensor | None] +) -> None: + for index in indices: + if index is not None and index.dtype in (torch.bool, torch.uint8): + raise DynamicOutputShapeException(func) + + +def run_and_return_new_tensor_of_input_device( + fake_mode: FakeTensorMode, + func: OpOverload, + args: tuple[Any, ...], + kwargs: dict[str, Any], +) -> FakeTensor: + # TODO: ref + _, new_kwargs = _normalize_function_or_error( + func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True + ) + out_device = new_kwargs["input"].device + with in_kernel_invocation_manager(fake_mode): + out = func(*args, **kwargs) + if not is_noncontiguous_supported(out_device): + out = out.new_empty(out.shape) + + if out is new_kwargs["input"]: + return out # copy_ + return FakeTensor(fake_mode, out, out_device) + + +_is_builtin_namespaces = ordered_set("aten", "prims", "prim") + + +def is_builtin(op: OpOverload) -> bool: + return op.namespace in _is_builtin_namespaces + + +def has_meta(func: OpOverload) -> bool: + return torch._C._dispatch_has_computed_kernel_for_dispatch_key(func.name(), "Meta") + + +def maybe_to_dense_mkldnn( + fake_mode: FakeTensorMode, + a: FakeTensor, + dtype: torch.dtype | None = None, + masked_grad: bool | None = None, +) -> object: + # this function invokes in_kernel_invocation_manager and creates python + # FakeTensor, revisit later for C++ behaviour + if ( + not isinstance(a, FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR + or not a.is_mkldnn + ): + return NotImplemented + + out_dtype = dtype if dtype is not None else a.dtype + if a.dtype not in _MKLDNN_TO_DENSE_DTYPES: + raise RuntimeError( + "mkldnn_to_dense expects float, bfloat16, half, uint8, int8, " + "float8_e4m3fn tensor input" + ) + if out_dtype not in _MKLDNN_TO_DENSE_DTYPES: + raise RuntimeError( + "mkldnn tensor only can be converted to be a float, bfloat16, Half, " + "uint8, int8, float8_e4m3fn cpu tensor" + ) + if a.dtype in _MKLDNN_DTYPE_CHANGE_RESTRICTED_DTYPES and out_dtype != a.dtype: + raise RuntimeError( + "For int8, uint8, float8 mkldnn_tensor input, we should not change " + "the data type." + ) + shape = tuple(a.shape) + with in_kernel_invocation_manager(fake_mode): + out = torch.empty_strided( + shape, + make_contiguous_strides_for(shape), + dtype=out_dtype, + device="meta", + ) + return FakeTensor(fake_mode, out, a.fake_device) + + +class _ToDenseMkldnn(torch.autograd.Function): + @staticmethod + def forward( + self: torch.Tensor, + dtype: torch.dtype | None, + masked_grad: bool | None, + ) -> torch.Tensor: + return aten._to_dense.default(self, dtype, masked_grad) + + @staticmethod + def setup_context( + ctx: Any, + inputs: tuple[torch.Tensor, torch.dtype | None, bool | None], + output: torch.Tensor, + ) -> None: + ctx.set_materialize_grads(False) + ctx.input_is_mkldnn = inputs[0].is_mkldnn + ctx.input_dtype = inputs[0].dtype + + @staticmethod + # pyrefly: ignore [bad-override] + def backward( + ctx: Any, grad: torch.Tensor | None + ) -> tuple[torch.Tensor | None, None, None]: + if grad is None: + return None, None, None + if ctx.input_is_mkldnn: + return aten.to_mkldnn.default(grad, ctx.input_dtype), None, None + # torch.func transforms may replay setup_context on a strided wrapper; + # match that expected gradient layout instead of forcing MKLDNN. + return grad.to(dtype=ctx.input_dtype), None, None + + +# Fake MKLDNN tensors keep MKLDNN-ness in a side channel because the backing +# meta tensor is strided. The native composite reads TensorImpl::layout() +# directly, so this Python composite consults the layout override instead. +def to_dense_composite_impl( + self: torch.Tensor, + dtype: torch.dtype | None = None, + *, + masked_grad: bool | None = None, +) -> torch.Tensor: + layout = self.layout + # This composite is installed globally so direct aten.to_dense can see fake + # MKLDNN tensors. Keep the common strided path minimal. + if layout == torch.strided: + return self.to(dtype=dtype) if dtype is not None else self + if layout == torch._mkldnn: # type: ignore[attr-defined] + return _ToDenseMkldnn.apply(self, dtype, masked_grad) + if layout in _TO_DENSE_SPARSE_LAYOUTS: + return aten._to_dense.default(self, dtype, masked_grad) + torch._check(False, lambda: f"to_dense does not support layout {layout}") + raise AssertionError("unreachable") + + +def to_dense_functorch_frontmode_impl( + self: torch.Tensor, + dtype: torch.dtype | None = None, + *, + masked_grad: bool | None = None, +) -> torch.Tensor: + interpreter = retrieve_current_functorch_interpreter() + if interpreter.key() != TransformType.Grad or not is_functorch_wrapped_tensor(self): + with torch.enable_grad(), interpreter.lower(): + return aten.to_dense.default(self, dtype=dtype, masked_grad=masked_grad) + + level = interpreter.level() + + class _ToDenseGrad(torch.autograd.function._SingleLevelFunction): + @staticmethod + def forward( + ctx: Any, + self: torch.Tensor, + dtype: torch.dtype | None, + masked_grad: bool | None, + ) -> torch.Tensor: + ctx.set_materialize_grads(False) + unwrapped_self = _unwrap_for_grad(self, level) + ctx.save_for_backward(unwrapped_self) + ctx.input_dtype = unwrapped_self.dtype + ctx.input_is_mkldnn = unwrapped_self.is_mkldnn + ctx.masked_grad = masked_grad + with torch.enable_grad(), interpreter.lower(): + if unwrapped_self.is_mkldnn: + out = _ToDenseMkldnn.apply(unwrapped_self, dtype, masked_grad) + else: + out = aten.to_dense.default( + unwrapped_self, dtype=dtype, masked_grad=masked_grad + ) + return _wrap_for_grad(out, level) + + @staticmethod + def backward(ctx: Any, *grads: Any) -> Any: + (grad,) = grads + if grad is None: + return None, None, None + if ctx.input_is_mkldnn: + # Functorch grad transforms replay setup_context on a strided + # wrapper, so return the wrapper's expected dense gradient. + return grad.to(dtype=ctx.input_dtype), None, None + (input,) = ctx.saved_tensors + return ( + aten.to_dense_backward.default(grad, input, ctx.masked_grad), + None, + None, + ) + + with enable_single_level_autograd_function(): + # pyrefly: ignore [missing-attribute] + return _ToDenseGrad.apply(self, dtype, masked_grad) + + +_to_dense_functorch_lib = torch.library.Library( + "aten", "IMPL", "FuncTorchDynamicLayerFrontMode" +) +_to_dense_functorch_lib.impl("to_dense", to_dense_functorch_frontmode_impl) + + +def to_dense_python_tls_impl( + self: torch.Tensor, + dtype: torch.dtype | None = None, + *, + masked_grad: bool | None = None, +) -> torch.Tensor: + from torch._subclasses.functional_tensor import FunctionalTensor + + if isinstance(self, (FakeTensor, FunctionalTensor)): # noqa: ISINSTANCE_FAKE_TENSOR + return to_dense_composite_impl(self, dtype=dtype, masked_grad=masked_grad) + + with torch._C._ExcludeDispatchKeyGuard(_PYTHON_TLS_SNAPSHOT_KEYSET): + return aten.to_dense.default(self, dtype=dtype, masked_grad=masked_grad) + + +# Intercept fake/functional tensor calls before the native composite sees their +# strided wrapper metadata, but keep ordinary eager CPU/CUDA to_dense on the C++ +# dispatcher path. +_to_dense_python_tls_lib = torch.library.Library("aten", "IMPL", "PythonTLSSnapshot") +_to_dense_python_tls_lib.impl("to_dense", to_dense_python_tls_impl) + + +# Keep this as a Python decomposition for FakeTensorMode fallback paths without +# replacing the eager dispatcher entry for every ordinary to_dense() call. +aten.to_dense.default.py_impl(torch._C.DispatchKey.CompositeImplicitAutograd)( + to_dense_composite_impl +) + + +@register_op_impl(aten.to_mkldnn.default) +def to_mkldnn( + fake_mode: FakeTensorMode, + func: OpOverload, + a: FakeTensor, + dtype: torch.dtype | None = None, +) -> object: + if not isinstance(a, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + return NotImplemented + + out_dtype = dtype if dtype is not None else a.dtype + if a.fake_device.type != "cpu": + raise RuntimeError("dense_to_mkldnn expects CPU tensor input") + if a.layout != torch.strided: + raise RuntimeError("dense_to_mkldnn expects strided tensor input") + if a.dtype not in _MKLDNN_DTYPES: + raise RuntimeError( + "dense_to_mkldnn expects float, bfloat16, half, uint8, int8 tensor input" + ) + if a.dim() > 5: + raise RuntimeError("Can't convert cpu tensor with the number of dimensions > 5") + if a.dtype in (torch.uint8, torch.int8) and out_dtype != a.dtype: + raise RuntimeError( + "For int8, uint8 cpu_tensor input, we should not change the data type." + ) + if out_dtype not in _MKLDNN_DTYPES: + raise RuntimeError( + "cpu tensor only can be converted to be a float, bfloat16, half, " + "uint8, int8 mkldnn tensor" + ) + shape = tuple(a.shape) + with in_kernel_invocation_manager(fake_mode): + # Real MKLDNN tensors report opaque strides as (1, 0, ...); mirror that + # while carrying the layout bit through dispatch_keys. + out = torch.empty_strided( + shape, + (1,) + (0,) * (len(shape) - 1), + dtype=out_dtype, + device="meta", + ) + return FakeTensor( + fake_mode, out, a.fake_device, dispatch_keys=_MKLDNN_DISPATCH_KEYS + ) + + +# These are for the `torch._foreach_...` ops like `torch._foreach_add`. +@register_op_impl( + lambda func: is_builtin(func) + and func.name().startswith("aten::_foreach_") + and has_meta(func) +) +def foreach_run_and_map_input_device( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> list[FakeTensor] | None: + tensor_lists = [ + arg + for arg in itertools.chain(args, kwargs.values()) + if isinstance(arg, (list, tuple)) + and len(arg) + and isinstance(arg[0], torch.Tensor) + ] + + try: + with in_kernel_invocation_manager(fake_mode): + out_meta = func(*args, **kwargs) + except NotImplementedError: + return NotImplemented + + if not out_meta: + return out_meta + + if not tensor_lists: + raise AssertionError("tensor_lists must not be empty") + out_fake = [] + + for i, meta_t in enumerate(out_meta): + device, _ = FakeTensor._find_common_device(func, [tl[i] for tl in tensor_lists]) + out_fake.append( + fake_mode.fake_tensor_converter.from_meta_and_device( + fake_mode, meta_t, device + ) + ) + + return out_fake + + +# Don't default to default device handling, +# Since op can take in non-zero sized cpu +# index tensors with cuda self +@register_op_impl(aten.index.Tensor) +def index_tensor( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> FakeTensor: + from torch._meta_registrations import meta_index_Tensor + + _, new_kwargs = _normalize_function_or_error( + func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True + ) + + out_device = new_kwargs["input"].device + # ensure nonzero call goes to fake tensor + with fake_mode: + out = meta_index_Tensor(*args, **kwargs) + return out.to(out_device) + + +# Can take mixed meta/non-meta arguments; the meta registration +# will roughly do the right thing even when given real devices +@register_op_impl(aten._embedding_bag.default) +def embedding_bag( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> tuple[FakeTensor, FakeTensor, FakeTensor, FakeTensor]: + from torch._meta_registrations import meta_embedding_bag + + with fake_mode: + return meta_embedding_bag(*args, **kwargs) + + +@register_op_impl(aten.embedding.default) +def embedding( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> Any: + from torch._meta_registrations import embedding as meta_embedding + + _, new_kwargs = _normalize_function_or_error( + func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True + ) + weight = new_kwargs["weight"] + indices = new_kwargs["indices"] + if ( + weight.device != indices.device + and weight.device.type != "meta" + and indices.device.type != "meta" + ): + return NotImplemented + + with fake_mode: + return typing_cast(FakeTensor, meta_embedding(*args, **kwargs)) + + +# takes in multiple-devices, don't default to default device handling +@register_op_impl(aten._unsafe_index_put.default) +@register_op_impl(aten.copy.default) +@register_op_impl(aten.copy_.default) +@register_op_impl(aten.slice_scatter.default) +@register_op_impl(aten.diagonal_scatter.default) +def multi_device_op_default( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> FakeTensor: + return run_and_return_new_tensor_of_input_device(fake_mode, func, args, kwargs) + + +@register_op_impl(aten.shallow_copy_data_.default) +def _( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> FakeTensor: + _, new_kwargs = _normalize_function_or_error( + func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True + ) + source_device = new_kwargs["source"].device + with in_kernel_invocation_manager(fake_mode): + func(*args, **kwargs) + new_kwargs["input"].fake_device = source_device + return new_kwargs["input"] + + +# same with multi_device_op_default, but return the input +@register_op_impl(aten.copy.out) +@register_op_impl(aten.slice_scatter.out) +def multi_device_op_out( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> FakeTensor: + with in_kernel_invocation_manager(fake_mode): + func(*args, **kwargs) + + _, new_kwargs = _normalize_function_or_error( + func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True + ) + + return new_kwargs["input"] + + +@register_op_impl(aten.index_put.default) +@register_op_impl(aten.index_put_.default) +def index_put_impl( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> FakeTensor: + _, new_kwargs = _normalize_function_or_error( + func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True + ) + values = new_kwargs["values"] + self_device = new_kwargs["input"].fake_device + torch._check( + self_device == values.fake_device or (values.ndim == 0 and values.numel() == 1), + lambda: f"Mismatching {func} device between self ({self_device}) and values ({values.device})", + ) + + out = run_and_return_new_tensor_of_input_device(fake_mode, func, args, kwargs) + if func is aten.index_put_.default: + return new_kwargs["input"] + else: + return out + + +@register_op_impl(aten._nested_tensor_from_tensor_list.default) +@register_op_impl(aten._nested_tensor_from_tensor_list.out) +@register_op_impl(aten._nested_view_from_buffer.default) +@register_op_impl(aten._nested_view_from_buffer_copy.default) +def nested_tensors_unsupported( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> None: + raise UnsupportedOperatorException(func) + + +@register_op_impl( + [ + x + for x in _device_not_kwarg_ops + if x + not in ( + # these are already registered elsewhere + aten.is_pinned.default, + aten.to.device, + aten.to.prim_Device, + aten._nested_tensor_from_tensor_list.default, + aten._nested_tensor_from_tensor_list.out, + ) + ] +) +def nyi(fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any) -> None: + if func in _device_not_kwarg_ops: + raise AssertionError(f"NYI: {func}") + + +@register_op_impl( + [ + aten.convolution.default, + aten._convolution.default, + aten._convolution.deprecated, + aten.convolution_backward.default, + ] +) +def conv( + fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any +) -> FakeTensor | tuple[FakeTensor | None, FakeTensor | None, FakeTensor | None]: + _, new_kwargs = _normalize_function_or_error( + func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True + ) + + def expect_fake_tensor(name: str, value: object) -> FakeTensor: + if not isinstance(value, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + raise AssertionError( + "Expected fake convolution tensor arguments to be FakeTensors, " + f"but {name} was {type(value).__name__}" + ) + return value + + input_ = expect_fake_tensor("input", new_kwargs["input"]) + weight = expect_fake_tensor("weight", new_kwargs["weight"]) + device = input_.fake_device + # Internal passes such as Inductor freezing may run fake propagation over + # folded convs that do not need to match eager's public input checks. + if ( + func + in ( + aten.convolution.default, + aten._convolution.default, + aten._convolution.deprecated, + ) + and input_.dtype != weight.dtype + and not input_.is_mkldnn + and not fake_mode.allow_non_fake_inputs + ): + raise RuntimeError( + f"Input type ({input_.dtype}) and weight type " + f"({weight.dtype}) should be the same" + ) + for name, value in new_kwargs.items(): + if isinstance(value, torch.Tensor): + fake_value = expect_fake_tensor(name, value) + if not _same_device_or_unspecified_index(fake_value.fake_device, device): + raise RuntimeError( + "Expected all tensors to be on the same device, but got " + f"{name} is on {fake_value.fake_device}, different from " + f"other tensors on {device}" + ) + # need to re-enable mode so the tensors report fake device + with fake_mode: + # if the input is unsqueezed in Convolution.cpp we get segfault + k = weight.ndim + + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import has_guarding_hint + + all_hinted = all(has_guarding_hint(s) for s in input_.shape) and all( + has_guarding_hint(s) for s in weight.shape + ) + + if not all_hinted: + # TODO: We can make this a little more faithful with best effort + # channels last detection (but only if it's statically obvious!) + mem_fmt = None + elif input_.dim() == k - 1: + # Unbatched input: eager routes directly to the slow dilated + # backward kernels, which produce contiguous gradients and bypass + # the channels-last backend-memory-format selection. Mirror that + # here; _select_conv_backend would also reject the missing batch + # dim. + mem_fmt = None + else: + # convolution has "bias" but not "bias_sizes"; convolution_backward + # has "bias_sizes" but not "bias". .get() handles both with one call. + bias = new_kwargs.get("bias") + select_kwargs: dict[str, object] = dict( + stride=new_kwargs["stride"], + padding=new_kwargs["padding"], + dilation=new_kwargs["dilation"], + transposed=new_kwargs["transposed"], + output_padding=new_kwargs["output_padding"], + groups=new_kwargs["groups"], + bias=bias, + ) + if bias is None: + select_kwargs["bias_sizes"] = new_kwargs.get("bias_sizes") + conv_backend = torch._C._select_conv_backend( + input_, weight, **select_kwargs + ) + # Expand 1d -> 2d. + # Note: Avoid expanding before calling _select_conv_backend, + # as the function handles 2D expansion internally. + if k == 3 and not input_.is_mkldnn and not input_.is_xpu: + # Note: Using input.to(memory_format=contiguous) does not work. + input_ = input_.contiguous().unsqueeze(2) + weight = weight.unsqueeze(2) + mem_fmt = torch._C._conv_determine_backend_memory_format( + input_, weight, conv_backend + ) + + def convert( + t: torch.Tensor | None, mem_fmt: torch.memory_format | None + ) -> FakeTensor | None: + if t is None: + return t + if mem_fmt is not None: + # channels last only support 4d, try to expand dim then convert it back later. + if t.dim() == 3 and mem_fmt == torch.channels_last: + t = t.unsqueeze(2).to(memory_format=mem_fmt).squeeze(2) + else: + t = t.to(memory_format=mem_fmt) + return FakeTensor(fake_mode, t, device) + + with in_kernel_invocation_manager(fake_mode): + out = func(**new_kwargs) + + if func in ( + aten.convolution.default, + aten._convolution.default, + aten._convolution.deprecated, + ): + return convert(out, mem_fmt) # type: ignore[return] + else: + return ( + convert(out[0], mem_fmt), + convert(out[1], mem_fmt), + convert(out[2], None), + ) + + +@register_op_impl(torch.ops.aten.bincount.default) +def bincount( + fake_mode: FakeTensorMode, + func: OpOverload, + inputs: FakeTensor, + weights: FakeTensor | None = None, + minlength: IntLikeType = 0, +) -> FakeTensor: + if ( + fake_mode.shape_env is None + or not fake_mode.shape_env.allow_dynamic_output_shape_ops + ): + # Without symints/symfloats, cannot handle this + raise DynamicOutputShapeException(func) + + from torch.fx.experimental.symbolic_shapes import ( + _constrain_range_for_size, + has_free_symbols, + ) + + if not has_free_symbols(inputs.numel()) and inputs.numel() == 0: + return inputs.new_empty(minlength, dtype=torch.int64) # type: ignore[return] + + new_size = fake_mode.shape_env.create_unbacked_symint() + + _constrain_range_for_size(new_size) + torch._check(new_size >= minlength) + if weights is None: + return inputs.new_empty(new_size, dtype=torch.int64) # type: ignore[return] + + if weights.device.type == "mps": + dtype = ( + weights.dtype + if weights.dtype in (torch.float32, torch.int32, torch.float16) + else torch.int32 + ) + else: + dtype = weights.dtype if weights.dtype == torch.float32 else torch.float64 + return weights.new_empty(new_size, dtype=dtype) # type: ignore[return] + + +@register_op_impl(torch.ops.aten._pack_padded_sequence.default) +def _pack_padded_sequence( + fake_mode: FakeTensorMode, + func: OpOverload, + inputs: FakeTensor, + lengths: FakeTensor, + batch_first: bool, +) -> tuple[FakeTensor, FakeTensor]: + if ( + fake_mode.shape_env is None + or not fake_mode.shape_env.allow_dynamic_output_shape_ops + ): + # Without symints/symfloats, cannot handle this + raise DynamicOutputShapeException(func) + + new_batch_size = fake_mode.shape_env.create_unbacked_symint() + + from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size + + _constrain_range_for_size(new_batch_size) + + if not batch_first: + # Inputs should have shape (batch_size, seq_len, *) + inputs = inputs.transpose(0, 1) # type: ignore[assignment] + + res_size = inputs.shape[1:] + packed_data = inputs.new_empty(res_size) + batch_size = inputs.new_empty((new_batch_size,)) + return (packed_data, batch_size) # type: ignore[return] + + +def _fake_alias(fake_mode: FakeTensorMode, x: FakeTensor) -> FakeTensor: + with no_python_dispatcher(), in_kernel_invocation_manager(fake_mode): + out = aten.alias.default(x) + # Real MKLDNN alias is not public API, but compiler-generated alias nodes + # must preserve fake MKLDNN layout state through tracing. + return FakeTensor(fake_mode, out, x.device, dispatch_keys=x.dispatch_keys) + + +@register_op_impl(aten.alias.default) +def fake_alias( + fake_mode: FakeTensorMode, func: OpOverload, x: FakeTensor +) -> FakeTensor | object: + if not isinstance(x, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + return NotImplemented + return _fake_alias(fake_mode, x) + + +# pyrefly: ignore [implicit-any] +FAST_OP_IMPLEMENTATIONS = {} + + +# Unlike register_op_impl, these don't do the slow iteration for +# run_impl_check, and these run BEFORE decompositions +def register_fast_op_impl( + func: OpOverload, +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + def impl_decorator(op_impl: Callable[_P, _R]) -> Callable[_P, _R]: + FAST_OP_IMPLEMENTATIONS[func] = op_impl + return op_impl + + return impl_decorator + + +# infer_size_impl in ExpandUtils +def infer_size( + a: Sequence[IntLikeType], b: Sequence[IntLikeType] +) -> tuple[IntLikeType, ...]: + from torch.fx.experimental.symbolic_shapes import guard_or_false + + dimsA = len(a) + dimsB = len(b) + ndim = max(dimsA, dimsB) + expandedSizes: list[IntLikeType] = [0] * ndim + for i in range(ndim - 1, -1, -1): + offset = ndim - 1 - i + dimA = dimsA - 1 - offset + dimB = dimsB - 1 - offset + sizeA = a[dimA] if dimA >= 0 else 1 + sizeB = b[dimB] if dimB >= 0 else 1 + + # NB: It is very important to test for broadcasting, before testing + # sizeA == sizeB. This is because the broadcasting tests are likely + # to be statically known (in particular, if sizeA/sizeB is unbacked + # but size-like, we will unsoundly assume they never equal 1), but + # the sizeA == sizeB test may not be statically known. However, once + # we have established that no broadcasting is happening, the + # sizeA == sizeB is now expect_true and we can defer it as a runtime + # assert (this works because Python will return the terminal + # expression of an or statement as-is, without bool()'ing it; if this + # were not the case, we'd need to write this using torch.sym_or() or + # something like that). + torch._check( + guard_or_false(sizeA == 1) or guard_or_false(sizeB == 1) or sizeA == sizeB, + lambda: f"The size of tensor a ({sizeA}) " + f"must match the size of tensor b ({sizeB}) " + f"at non-singleton dimension {i})", + ) + expandedSizes[i] = sizeB if guard_or_false(sizeA == 1) else sizeA + return tuple(expandedSizes) + + +def make_fast_binary_impl( + slow_ref: Callable[..., Any], + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND = ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) -> Callable[..., FakeTensor]: + def fast_binary_impl(mode: FakeTensorMode, *args: Any, **kwargs: Any) -> FakeTensor: + def slow(msg: str) -> FakeTensor: + count_label(f"slow {msg}") + with mode: + return slow_ref(*args, **kwargs) + + count_label("attempt fast") + + # Fast path (based off of TensorIterator fast path). + # Unfortunately, there is no way to easily deduplicate + # this with either the TensorIterator C++ implementation + # (which we don't want to SymIntify, and also the algorithm + # here is slightly different from TensorIterator to allow + # for broadcasting), nor the PrimTorch implementation + # (which does not actually implement a fast path.) + + operands = args + + # compute_shape + final_shape: ShapeType | None = None + for op in operands: + shape: ShapeType = op.shape if isinstance(op, torch.Tensor) else () + if final_shape is None: + final_shape = shape + # TODO: Minor optimization: track if the shapes + # were equal so you can skip the equality check + # below if unnecessary + # pyrefly: ignore[bad-assignment] + final_shape = infer_size(final_shape, shape) + if final_shape is None: + raise AssertionError("final_shape must not be None") + + from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq + + # Do some extra safety checks to see if the output + # stride is obvious + for op in operands: + if ( + isinstance(op, torch.Tensor) + and len(op.shape) == len(final_shape) + # take the slow path if result is not determined. + and guard_or_false(sym_eq(op.shape, final_shape)) # type: ignore[arg-type] + ): + break + else: + # if we never break in the for loop above we take the slow path. + return slow("both tensors nontrivially broadcast") + + # compute_types + cpu = torch.device("cpu") + common_device: torch.device = cpu + common_dtype: torch.dtype | None = None + has_different_input_dtypes = False + for op in operands: + if not isinstance(op, torch.Tensor): + # Use elementwise_dtypes for the tricky case + has_different_input_dtypes = True + continue + if common_device == cpu and op.device.type != "cpu": + common_device = op.device + if common_dtype is None: + if type_promotion_kind != ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT: + has_different_input_dtypes = True + else: + common_dtype = op.dtype + elif common_dtype != op.dtype: + has_different_input_dtypes = True + + if has_different_input_dtypes: + # compute promotion + # TODO: we don't need the compute type + _, common_dtype = elementwise_dtypes( + *operands, type_promotion_kind=type_promotion_kind + ) + + # check all tensors on same device + # cpu scalars are assumed allow + current_cpu_scalars_on_non_cpu = 0 + max_cpu_scalars_on_non_cpu = 1 # hard coded atm + for op in operands: + if not isinstance(op, torch.Tensor): + continue + if common_device != cpu and op.dim() == 0 and op.device == cpu: + if current_cpu_scalars_on_non_cpu >= max_cpu_scalars_on_non_cpu: + return slow("error") + current_cpu_scalars_on_non_cpu += 1 + elif op.device != common_device: + return slow("error") + + # compute_fast_setup_type + definitely_contiguous = True + definitely_channels_last = True + + # TODO: is_non-overlapping_and_dense not bound from Python + # no inplace, no out, everything defined + + if is_noncontiguous_supported(common_device): + for op in operands: + if not isinstance(op, torch.Tensor): + continue + definitely_contiguous = ( + definitely_contiguous + and is_contiguous_for_memory_format_or_false( + op, memory_format=torch.contiguous_format + ) + ) + definitely_channels_last = ( + definitely_channels_last + and is_contiguous_for_memory_format_or_false( + op, memory_format=torch.channels_last + ) + ) + if definitely_contiguous: + # do contiguous + count_label("fast is_contiguous") + return FakeTensor( + mode, + torch.empty( + final_shape, + dtype=common_dtype, + device="meta", + memory_format=torch.contiguous_format, + ), + device=common_device, + ) + if definitely_channels_last: + count_label("fast channels_last") + # do channels last + return FakeTensor( + mode, + torch.empty( + final_shape, + dtype=common_dtype, + device="meta", + memory_format=torch.channels_last, + ), + device=common_device, + ) + + return slow("no contiguity match") + + return fast_binary_impl + + +# disable the python dispatcher to avoid decomposing detach() further +# (proxy_mode should still decompose detach() though) +def fast_detach( + fake_mode: FakeTensorMode | None, + x: FakeTensor | torch.Tensor, + include_real: bool = False, +) -> torch.Tensor: + if ( + not isinstance(x, FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR + or fake_mode is None + ): + raise AssertionError( + "type widening added for cpp faketensor but this is not used yet" + ) + with no_python_dispatcher(), in_kernel_invocation_manager(fake_mode): + out = torch.ops.aten.detach.default(x) + dispatch_keys = x.dispatch_keys + if include_real: + return FakeTensor( + fake_mode, + out, + x.device, + real_tensor=x.real_tensor, + dispatch_keys=dispatch_keys, + ) + return FakeTensor(fake_mode, out, x.device, dispatch_keys=dispatch_keys) + + +def fast_alias(fake_mode: FakeTensorMode, x: FakeTensor) -> FakeTensor: + return _fake_alias(fake_mode, x) + + +@functools.cache +def get_fast_op_impls() -> dict[OpOverload, Callable[..., Any]]: + import torch._refs + + register_fast_op_impl(torch.ops.aten.add.Tensor)( + make_fast_binary_impl(torch._refs.add) + ) + register_fast_op_impl(torch.ops.aten.sub.Tensor)( + make_fast_binary_impl(torch._refs.sub) + ) + register_fast_op_impl(torch.ops.aten.mul.Tensor)( + make_fast_binary_impl(torch._refs.mul) + ) # type: ignore[has-type] + register_fast_op_impl(torch.ops.aten.div.Tensor)( + make_fast_binary_impl( + torch._refs.div, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + ) + register_fast_op_impl(torch.ops.aten.detach.default)(fast_detach) + register_fast_op_impl(torch.ops.aten.alias.default)(fast_alias) + return FAST_OP_IMPLEMENTATIONS diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..b385bac5e66299d531bdb575aa3bff95dfe6ab6e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/fake_tensor.py @@ -0,0 +1,3866 @@ +from __future__ import annotations + +import atexit +import contextlib +import dataclasses +import functools +import logging +import math +import os +import threading +import traceback +import types +import typing +import weakref +from collections import defaultdict +from dataclasses import dataclass +from typing import Any, cast, Literal, TYPE_CHECKING, TypeGuard, TypeVar, Union +from typing_extensions import Self, TypedDict, Unpack +from weakref import ReferenceType + +import torch +import torch._library.utils as library_utils +from torch import SymBool, SymFloat, SymInt, Tensor +from torch._C._functorch import is_functorch_wrapped_tensor, is_legacy_batchedtensor +from torch._custom_class_base import CustomClassBase +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.fake_profile import MissingOpProfile +from torch._logging import dtrace_structured +from torch._prims_common import suggest_memory_format +from torch._subclasses.meta_utils import ( + assert_eq, + assert_metadata_eq, + is_sparse_any, + is_sparse_compressed, + MetaConverter, +) +from torch._utils import _is_privateuse1_backend_available, render_call +from torch.fx.immutable_collections import immutable_dict +from torch.fx.operator_schemas import normalize_function +from torch.multiprocessing.reductions import StorageWeakRef +from torch.overrides import TorchFunctionMode +from torch.types import IntLikeType, py_sym_types +from torch.utils._mode_utils import no_dispatch +from torch.utils._python_dispatch import ( + is_traceable_wrapper_subclass, + TorchDispatchMode, + TraceableWrapperSubclass, +) +from torch.utils._pytree import KeyPath, keystr, PyTree, tree_map, tree_map_, TreeSpec +from torch.utils._stats import count +from torch.utils._traceback import CapturedTraceback + +from ._fake_tensor_utils import _CacheKeyState, _PySymInputStub, _SymIntOutputStub + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, Iterable, Mapping, Sequence + from types import TracebackType + + from torch._guards import Source + from torch._ops import OpOverload + from torch.fx.experimental.symbolic_shapes import ShapeEnv, SymbolicContext + +log = logging.getLogger(__name__) +hc_log = torch._logging.getArtifactLogger(__name__, "hierarchical_compile") + +# TODO: Hack to unblock https://github.com/pytorch/pytorch/pull/108186 +# Proper fix tracked by https://github.com/pytorch/pytorch/issues/120105 +try: + not_implemented_log = torch._logging.getArtifactLogger(__name__, "not_implemented") +except ValueError as e: + if "'not_implemented' not registered" in str(e): + not_implemented_log = logging.getLogger(__name__ + ".not_implemented") + else: + raise e + + +DimList = list + +pytree = torch.utils._pytree +T = TypeVar("T") + +aten = torch._ops.ops.aten + +CONSTANT_NUMEL_LIMIT = 1 + +RECURSION_COUNT = 0 + +_MKLDNN_DISPATCH_KEY = torch._C._dispatch_key_parse("MkldnnCPU") + + +def _dispatch_keys_has_mkldnn(dispatch_keys: torch.DispatchKeySet | None) -> bool: + return dispatch_keys is not None and dispatch_keys.has(_MKLDNN_DISPATCH_KEY) + + +class _FakeTensorConstructorIgnoredState(TypedDict, total=False): + # Recompute memo descriptor state when reconstructing from + # FakeTensor.__dict__. + _nonzero_memo: object + _nonzero_memo_vc: object + _nonzero_memo_epoch: object + _item_memo: object + _item_memo_vc: object + _item_memo_epoch: object + _unique_memo: object + _unique_memo_vc: object + _unique_memo_epoch: object + _unique_consecutive_memo: object + _unique_consecutive_memo_vc: object + _unique_consecutive_memo_epoch: object + _nested_int_memo: object + _nested_int_memo_vc: object + _nested_int_memo_epoch: object + _debug_trace: object + + +_FAKE_TENSOR_CONSTRUCTOR_IGNORED_STATE_ATTRS = frozenset( + _FakeTensorConstructorIgnoredState.__annotations__ +) + + +# Check if device type supports device index +@functools.cache +def _is_indexed_device_type(device_type: str) -> bool: + return device_type in [ + "cuda", + "hpu", + "xpu", + "mps", + "mtia", + torch._C._get_privateuse1_backend_name(), + ] + + +# Small helper that increments recursion count, and +# resets it when the object goes out of scope. Useful +# if you don't want to increase indentation which is +# what a context manager would do. +class IncrementRecursionCount: + def __init__(self) -> None: + global RECURSION_COUNT + RECURSION_COUNT += 1 + + def __del__(self) -> None: + global RECURSION_COUNT + RECURSION_COUNT -= 1 + + +@dataclass +class UnsupportedFakeTensorException(RuntimeError): + reason: str + + +class FakeTensorDeviceMismatchError(RuntimeError): + def __init__( + self, + func: OpOverload, + common_device: torch.device, + device: torch.device, + ) -> None: + self.func = func + self.common_device = common_device + self.device = device + super().__init__( + "Expected all tensors to be on the same device, but found " + f"at least two devices, {common_device} and {device}!" + ) + + +@dataclass +class DynamicOutputShapeException(RuntimeError): + func: OpOverload + + +@dataclass +class DataDependentOutputException(RuntimeError): + func: OpOverload + + +@dataclass +class UnsupportedOperatorException(RuntimeError): + func: OpOverload + + +@dataclass +class UnsupportedMutationAliasingException(RuntimeError): + reason: str + + +@dataclass +class MetadataMismatchError(RuntimeError): + reason: str + + +class FakeTensorTLS(threading.local): + # Default to None, otherwise it'll be used to override _all_ + # `FakeTensorMode.allow_non_fake_inputs` in this thread. + allow_non_fake_inputs_override: bool | None + non_strict_export_fake_tensor_tracker: weakref.WeakSet[FakeTensor] + + def __init__(self) -> None: + self.allow_non_fake_inputs_override = None + self.non_strict_export_fake_tensor_tracker = weakref.WeakSet() + + +fake_tensor_tls = FakeTensorTLS() + + +def ordered_set(*items: T) -> dict[T, Literal[True]]: + return dict.fromkeys(items, True) + + +@contextlib.contextmanager +def unset_fake_temporarily() -> Generator[TorchDispatchMode | None, None, None]: + old = torch._C._unset_dispatch_mode(torch._C._TorchDispatchModeKey.FAKE) + try: + yield old + finally: + if old is not None: + torch._C._set_dispatch_mode(old) + + +@contextlib.contextmanager +def disable_fake_tensor_cache(fake_mode: FakeTensorMode) -> Generator[None, None, None]: + old_value: bool = fake_mode.cache_enabled + try: + fake_mode.cache_enabled = False + yield + finally: + fake_mode.cache_enabled = old_value + + +def get_plain_tensors( + subclass: Tensor | TraceableWrapperSubclass, + *, + out: list[Tensor | int | SymInt | CustomClassBase], +) -> list[Tensor | int | SymInt | CustomClassBase]: + # This function is used in Runtime, do not add redundant asserts + todo = [subclass] + while todo: + curr = todo.pop() + if not is_traceable_wrapper_subclass(curr): + out.append(curr) + continue + + inner_keys, _ = curr.__tensor_flatten__() + todo.extend(getattr(curr, key) for key in reversed(inner_keys)) + + return out + + +def is_fake_tensor(x: object) -> TypeGuard[Tensor]: + # True if x is itself a fake tensor: a Python FakeTensor, or a C++ fake. + if isinstance(x, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + return True + return isinstance(x, Tensor) and torch._C._is_fake_tensor(x) + + +def is_fake(x: object) -> TypeGuard[Tensor]: + from torch._subclasses.functional_tensor import FunctionalTensor + + if is_fake_tensor(x): + return True + if is_traceable_wrapper_subclass(x): + attrs, _ = type(x).__tensor_flatten__(x) + got_fake: bool | None = None + for attr in attrs: + match getattr(x, attr): + case Tensor() as v: + fake = is_fake(v) + if got_fake is None: + got_fake = fake + elif got_fake != fake: + raise AssertionError("got mixed fake and real tensors!") + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return got_fake or False + elif isinstance(x, FunctionalTensor): + return is_fake(x.elem) + elif isinstance(x, Tensor) and torch._is_functional_tensor(x): + reapply_views = torch._C._functionalization_reapply_views_tls() + unwrapped = torch._C._functorch._unwrap_functional_tensor(x, reapply_views) + return is_fake(unwrapped) + elif isinstance(x, Tensor) and is_functorch_wrapped_tensor(x): + unwrapped = torch._C._functorch.get_unwrapped(x) + return is_fake(unwrapped) + return False + + +def maybe_get_fake_mode(t: object) -> FakeTensorMode | None: + from torch._subclasses.functional_tensor import FunctionalTensor + + if isinstance(t, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + return t.fake_mode + if is_traceable_wrapper_subclass(t): + inner_tensor_names, _ = t.__tensor_flatten__() + mode: FakeTensorMode | None = None + for t_name in inner_tensor_names: + match getattr(t, t_name): + case Tensor() as v: + m = maybe_get_fake_mode(v) + if mode is None: + mode = m + elif mode is not m: + raise AssertionError("All fake tensor modes must be the same") + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return mode + elif isinstance(t, FunctionalTensor): + return maybe_get_fake_mode(t.elem) + elif isinstance(t, Tensor) and torch._is_functional_tensor(t): + reapply_views = torch._C._functionalization_reapply_views_tls() + unwrapped = torch._C._functorch._unwrap_functional_tensor(t, reapply_views) + return maybe_get_fake_mode(unwrapped) + elif isinstance(t, Tensor) and is_functorch_wrapped_tensor(t): + unwrapped = torch._C._functorch.get_unwrapped(t) + return maybe_get_fake_mode(unwrapped) + return None + + +def maybe_get_real_tensor(x: object) -> Tensor | None: + if isinstance(x, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + return x.real_tensor + return None + + +def maybe_get_fake_device(x: object) -> torch.device | None: + if isinstance(x, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + return x.fake_device + return None + + +def maybe_get_fake_constant(x: object) -> Tensor | None: + if isinstance(x, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + return x.constant + return None + + +@functools.cache +def get_schema_info(func: OpOverload) -> torch._C._SchemaInfo: + return torch._C._SchemaInfo(func._schema) + + +# many of the decompositions registered to torch/_prims do not at the moment model +# aliasing or strides, so as an incremental step, just enable the decompositions in +# torch/_decomp/decompositions.py. +# decomps are used for aot autograd tracing so we would like to unify on their +# implementation and add additional testing to them +@functools.cache +def torch_decomp_decompositions(func: OpOverload) -> bool: + from torch._decomp import decomposition_table + + decompositions = torch._decomp.decompositions + # Note that the function in the decomposition table might be + # different from the one in the module because of the difference + # in out handling in aten API and torch public API + return decomposition_table[func].__module__.startswith( + "torch._decomp" + ) and decomposition_table[func].__name__ in dir(decompositions) + + +def tree_flatten_only(ty: type[T], tree: PyTree) -> list[T]: + flat_vals = pytree.tree_leaves(tree) + return [elem for elem in flat_vals if isinstance(elem, ty)] + + +def _is_plain_tensor(t: object) -> bool: + return ( + type(t) is Tensor + and t.layout == torch.strided + and not ( + t.is_sparse + or t.is_nested + or is_functorch_wrapped_tensor(t) + or is_legacy_batchedtensor(t) + or torch._is_functional_tensor(t) + ) + ) + + +# Similar to `MetaConverter`, this is a class for converting +# multiple tensors into fake tensors which share the same view/storage +# structure. Like `MetaConverter`, it uses `WeakIdRef` to +# hold a weak reference for all memoized tensors. +class FakeTensorConverter: + @property + def tensor_memo( + self, + ) -> weakref.WeakValueDictionary[ + torch._subclasses.meta_utils.MetaTensorId, FakeTensor + ]: + return self.meta_converter.tensor_memo + + meta_converter: MetaConverter[FakeTensor] + constant_storage_mapping: dict[StorageWeakRef, list[ReferenceType[FakeTensor]]] + export: bool + + def __init__(self, *, copy_data: bool = False, export: bool = False) -> None: + self.meta_converter = MetaConverter(copy_data=copy_data) + self.export = export + + # map from to storage to corresponding constant tensors + self.constant_storage_mapping = {} + + def add_constant_storage_mapping(self, fake_tensor: FakeTensor) -> None: + # when you have a constant, aliased tensor: + # const_tensor.add_(torch.rand([1])) + # all aliases of it must become no longer const + if ( + not isinstance( # noqa: ISINSTANCE_FAKE_TENSOR + fake_tensor, FakeTensor + ) + or fake_tensor.constant is None + ): + raise AssertionError("fake_tensor must be a FakeTensor with a constant") + weak_st = StorageWeakRef(fake_tensor.constant._typed_storage()) + + # we need a map from a weak storage to all of its corresponding + # constant tensors. python doesn't have the weak value equivalent + # of defaultdict(list), so we are using a WeakValueDictionary as one + if weak_st not in self.constant_storage_mapping: + self.constant_storage_mapping[weak_st] = [] + self.constant_storage_mapping[weak_st].append(weakref.ref(fake_tensor)) + + def invalidate_constant_aliases(self, tensor: Tensor) -> None: + if isinstance(tensor, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + raise AssertionError("Expected a real tensor, not a FakeTensor") + + weak_st = StorageWeakRef(tensor._typed_storage()) + if weak_st not in self.constant_storage_mapping: + return + + for weak_tensor_ref in self.constant_storage_mapping[weak_st]: + ten = weak_tensor_ref() + if ten is not None: + # pyrefly: ignore [missing-attribute] + ten._fix_weakref() + ten.constant = None + + del self.constant_storage_mapping[weak_st] + + def clear_non_cpu_constants(self) -> None: + """Clear non-CPU constants while keeping cheap CPU constants for folding.""" + for weak_st, weak_tensor_refs in list(self.constant_storage_mapping.items()): + live_tensor_refs: list[ReferenceType[FakeTensor]] = [] + constant: Tensor | None = None + for weak_tensor_ref in weak_tensor_refs: + ten = weak_tensor_ref() + if ten is None or ten.constant is None: + continue + + live_tensor_refs.append(weak_tensor_ref) + if constant is None: + constant = ten.constant + + if constant is None: + del self.constant_storage_mapping[weak_st] + elif constant.device.type == "cpu": + self.constant_storage_mapping[weak_st] = live_tensor_refs + else: + self.invalidate_constant_aliases(constant) + + def _get_memo(self, t: Tensor) -> FakeTensor | None: + tid = self.meta_converter.describer.lookup_tensor.get(t) + if tid is None: + return None + return self.tensor_memo.get(tid) + + def set_tensor_memo(self, t: Tensor, v: FakeTensor) -> None: + tid = self.meta_converter.describer.get_tensor_id(t) + self.meta_converter.tensor_memo[tid] = v + + # You can have a real tensor that you need to convert into a fake tensor. + # If you have a meta tensor already, call from_meta_and_device. + # + # You're allowed to pass a meta tensor to be turned into a fake + # tensor; although an odd thing to do, this can occur if you're doing + # cross ref testing and the inner test is already operating on meta tensors. + def from_real_tensor( + self, + fake_mode: FakeTensorMode, + t: Tensor, + make_constant: bool = False, + shape_env: ShapeEnv | None = None, + *, + source: Source | None = None, + symbolic_context: SymbolicContext | None = None, + trace: bool = True, + ) -> FakeTensor: + # see note [Tensor Fakification and Symbol Caching] + if not symbolic_context and not source and shape_env: + if tracing_context := torch._guards.TracingContext.try_get(): + if t in tracing_context.tensor_to_context: + symbolic_context = tracing_context.tensor_to_context[t] + from torch.fx.experimental.symbolic_shapes import ( + StatefulSymbolicContext, + ) + + if not isinstance(symbolic_context, StatefulSymbolicContext): + raise AssertionError( + f"Expected StatefulSymbolicContext, got {type(symbolic_context)}" + ) + source = symbolic_context.tensor_source + + maybe_memo = self._get_memo(t) + if maybe_memo is not None: + if t.is_mkldnn and not maybe_memo.is_mkldnn: + maybe_memo.dispatch_keys = torch._C._dispatch_keys(t) + return maybe_memo + # not yet supported in metatensors + if t.is_quantized: + raise UnsupportedFakeTensorException("quantized nyi in meta tensors") + if type(t) is torch.nn.Parameter: + if make_constant: + raise AssertionError("make_constant must be False for nn.Parameter") + + constant = t if make_constant else None + + # This callback is used by both subclass and inner tensors. Require the + # caller to explicitly specify the device in case outer and inner tensors + # have different devices. + def mk_fake_tensor( + make_meta_t: Callable[[], object], device: torch.device | str + ) -> FakeTensor: + # NB: don't use in_kernel_invocation_manager. to + # ensure FakeTensor can internally do constant computation + # as necessary. Invocation manager is "more correct" as + # it works for more operators in make_meta_t, but + # invariant is that make_meta_t only calls factories + # for which it is not strictly necessary to use the + # invocation manager (I think!) + with no_dispatch(): + return FakeTensor( + fake_mode, + # pyrefly: ignore [bad-argument-type] + make_meta_t(), + # pyrefly: ignore [bad-argument-type] + device, + # TODO: callback might be used in recursive contexts, in + # which case using t is wrong! BUG! + constant=constant, + ) + + out = self.meta_converter( + t, + shape_env=shape_env, + callback=mk_fake_tensor, + source=source, + symbolic_context=symbolic_context, + trace=trace, + ) + if out is NotImplemented: + raise UnsupportedFakeTensorException("meta converter nyi") + if t.is_mkldnn: + out.dispatch_keys = torch._C._dispatch_keys(t) + + # Propagate grad_dtype here rather than in meta_converter because + # meta tensors don't carry autograd metadata. + # Unwrap FunctionalTensor because accessing is_leaf/grad_fn on a + # FunctionalTensor view whose base was mutated (e.g. via set_()) + # triggers lazy view replay through __torch_dispatch__, which + # errors without an active FunctionalTensorMode. + inner_t = ( + torch._from_functional_tensor(t.elem) + if isinstance(t, torch._subclasses.functional_tensor.FunctionalTensor) + else t + ) + if ( + inner_t.requires_grad + and inner_t.is_leaf + and inner_t.grad_dtype != inner_t.dtype + and out.is_leaf + ): + out.grad_dtype = inner_t.grad_dtype + + from torch._dynamo.source import RandomValueSource + + value = None + if ( + not self.export + and _is_plain_tensor(t) # mostly, we want to know if item() works + and t.dim() == 0 + and t.device.type == "cpu" + # All integer types are fair game, because signed overflow is UB + # (and even int64 can overflow, since integers in Python are + # arbitrary precision). But only float64 is OK for float, because + # switching between float32 and float64 changes semantics in an + # observable way without hitting UB. + and t.dtype + in [torch.int64, torch.int32, torch.int16, torch.int8, torch.float64] + # Dynamo may pass shape_env=None for static fakification while + # the mode still owns a ShapeEnv. In that case, do not install a + # concrete Python scalar where Dynamo expects a SymNode-like memo. + # + # Similarly, compiler tracing can use a FakeTensorMode without a + # ShapeEnv; keep concrete memos limited to truly manual/plain + # FakeTensorMode usage so _local_scalar_dense tracing semantics do + # not change under AOT/Inductor. + and ( + source is not None + or ( + fake_mode.shape_env is None + and torch._guards.TracingContext.try_get() is None + ) + ) + # Impede setting up item() on things coming from random. These + # are not "real" item() calls, instead UnspecializedPythonVariable + # is unsafely pretending an int is a tensor, which can sometimes + # implicitly cause an item call. The problem is this is pretty + # unsound: there's no reason substituting an int with a Tensor is + # going to give the same results. Today, you mostly get around + # this by typically not having capture_scalar_outputs on and graph + # breaking when someone tries to use the unspec variable in an + # int-y context. But allowing it through here would break that. + # So don't. + # + # Once random values are setup to be represented as + # SymNodeVariable, this condition can be removed. To check if + # you've done it right, this is a good test: + # + # PYTORCH_TEST_WITH_DYNAMO=1 python test/test_reductions.py -k + # TestReductionsCPU.test_dim_reduction_fns_fn_name_amax_cpu_bfloat16 + and (source is None or not isinstance(source, RandomValueSource)) + # In Dynamo, shape_env is never none (even with static shapes). + # However, FakeTensorMode can be used by hand and in some cases + # ShapeEnv is not allocated. + and (source is None or shape_env is not None) + ): + from torch._dynamo.source import CallMethodItemSource, FloatTensorSource + from torch.fx.experimental.symbolic_shapes import DimDynamic + + with no_dispatch(): + value = t.item() + if not math.isnan(value) and not math.isinf(value): + if source is None: + # Plain FakeTensorMode may not have a ShapeEnv. Preserve + # the concrete scalar memo for real 0-D tensor inputs. + out.item_memo = value + else: + if shape_env is None: + raise AssertionError("shape_env unexpectedly missing") + # Peephole strip out unnecessary torch.as_tensor(x).item() + if isinstance(source, FloatTensorSource): + item_source = source.base + else: + item_source = CallMethodItemSource(source) + symbol = shape_env.create_unspecified_symbol( + value, + source=item_source, + dynamic_dim=DimDynamic.DYNAMIC, + symbolic_context=symbolic_context, + ) + # NB: reusing item_memo here ensures that we invalidate on + # mutation + if t.dtype == torch.int64: + out.item_memo = shape_env.create_symintnode( + symbol, + hint=value, + source=item_source, + ) + elif t.dtype == torch.float64: + out.item_memo = shape_env.create_symfloatnode( + symbol, + hint=value, + source=item_source, + ) + if make_constant: + self.add_constant_storage_mapping(out) + # NB: meta_converter set the memo + return out + + # If you specify the device, it MUST be a meta tensor. + def from_meta_and_device( + self, + fake_mode: FakeTensorMode, + t: Tensor, + device: torch.device, + pytype: type[torch.Tensor] | None = None, + dispatch_keys: torch.DispatchKeySet | None = None, + ) -> FakeTensor: + if t.device.type != "meta": + raise AssertionError( + f"tensor's device must be `meta`, got {t.device.type} instead" + ) + # This is a bit abusive (this is not the "real" tensor) but whatever, + # the meta tensor should be fresh so there's no way to get it wrong + maybe_memo = self._get_memo(t) + if maybe_memo is not None: + return maybe_memo + out = FakeTensor( + fake_mode, t, device, pytype=pytype, dispatch_keys=dispatch_keys + ) + self.set_tensor_memo(t, out) + return out + + +@functools.cache +def init_gpu_context(device: torch.device) -> None: + # Backward will error with cuda Fake Tensors if no cuda tensors have been initialized first + if torch.accelerator.current_accelerator(True) == device.type: + ( + torch.empty(1, device=device) + if torch.version.hip is None + else torch.zeros(1, device=device) + ) + + +@contextlib.contextmanager +def in_kernel_invocation_manager( + fake_mode: FakeTensorMode, +) -> Generator[None, None, None]: + # See: note [Fake Tensor Dispatch Keys] + prev_in_kernel = fake_mode.in_kernel_invocation + meta_in_tls = torch._C._meta_in_tls_dispatch_include() + if meta_in_tls != prev_in_kernel: + raise AssertionError(f"{meta_in_tls}, {prev_in_kernel}") + + with torch._C._DisableTorchDispatch(): + fake_mode.in_kernel_invocation = True + # Unfortunately _set_meta_in_tls_dispatch_include(False) can leave + # `Dense` turned on (because it's implied by `Meta`) + with torch._C._PreserveDispatchKeyGuard(): + torch._C._set_meta_in_tls_dispatch_include(True) + try: + yield + finally: + fake_mode.in_kernel_invocation = prev_in_kernel + # torch._C._set_meta_in_tls_dispatch_include(prev_in_kernel) + + +# Return if the function allows Python numbers to bind to Tensors +def should_allow_numbers_as_tensors(func: OpOverload) -> bool: + return torch._C._should_allow_numbers_as_tensors( + func.name().split("::")[-1].split(".")[0] + ) + + +class FakeTensorConfig: + debug = os.environ.get("TORCH_FAKE_TENSOR_DEBUG", "0") == "1" + + +# This memorizes unbacked SymInt or SymFloats representing quantities like the +# number of nonzero elements in this tensor or learning rate. There is one +# instance of the descriptor per particular quantity to memoize. +# +# Memoization is helpful if you do something like x[mask] and y[mask]; +# mask.nonzero() gets repeatedly called and should give a consistent unbacked +# SymInt. It needs to be invalidated in the same way constant is. +# +# Making this a descriptor may seem overly fancy, but actually it's the most +# convenient way to ensure access to FakeTensor during access, which is +# required for testing version counter and epoch validity. +class SymNumberMemoDescriptor: + _name: str + + # By default, SymInts in this memo are invalidated across versions/epochs. + # nested_ints however are preserved across epochs and across versions. + # Preserving across versions is okay for nested int since the association + # of a nested int is agnostic to the underlying data and nested ints are not + # shared across multiple distinct tensors. + _is_nested_int: bool + + def __init__(self, *, is_nested_int: bool = False) -> None: + self._is_nested_int = is_nested_int + + def __set_name__(self, owner: str, name: str) -> None: + self._name = name + + def _memo(self, obj: FakeTensor) -> str: + return f"_{self._name}" + + def _memo_vc(self, obj: FakeTensor) -> str: + return f"_{self._name}_vc" + + # When we retrace, we need to invalidate all the memos so that we can + # accurately identify the first time unbacked SymInts are allocated. + # This is only relevant for inputs; for intermediates, they will get fresh + # fake tensors so you won't have a memo anyway + def _memo_epoch(self, obj: FakeTensor) -> str: + return f"_{self._name}_epoch" + + def __get__( + self, obj: FakeTensor, objtype: type[FakeTensor] | None = None + ) -> torch.SymInt | torch.SymFloat | None: + if (r := getattr(obj, self._memo(obj))) is None: + return None + + # Version counter based tracking isn't 100% sound but it's close + # enough. Inference tensors don't track version counters, so + # skip that check for them. + if not self._is_nested_int and not obj.is_inference(): + if getattr(obj, self._memo_vc(obj), None) != obj._version: + setattr(obj, self._memo(obj), None) + return None + + # Backed SymFloats are stable across retracing epochs, but tensor + # mutation (version counter check above) still invalidates the memo. + if isinstance(r, torch.SymFloat) and r.node.hint is not None: + return r + + if ( + not self._is_nested_int + and getattr(obj, self._memo_epoch(obj), None) != obj.fake_mode.epoch + ): + setattr(obj, self._memo(obj), None) + return None + + return r + + def __set__( + self, + obj: FakeTensor, + value: torch.SymInt | torch.SymFloat | torch.SymBool | int | float | None, + ) -> None: + if value is None: + setattr(obj, self._memo(obj), None) + setattr(obj, self._memo_vc(obj), None) + setattr(obj, self._memo_epoch(obj), None) + else: + setattr(obj, self._memo(obj), value) + if not self._is_nested_int and not obj.is_inference(): + setattr(obj, self._memo_vc(obj), obj._version) + setattr(obj, self._memo_epoch(obj), obj.fake_mode.epoch) + + +class FakeTensor(Tensor): + """ + Meta tensors give you the ability to run PyTorch code without having to + actually do computation through tensors allocated on a `meta` device. + Because the device is `meta`, meta tensors do not model device propagation. + FakeTensor extends MetaTensors to also carry an additional `fake_device` + which tracks devices that would have been used. + """ + + _fake_device: torch.device + fake_mode: FakeTensorMode + constant: Tensor | None + real_tensor: Tensor | None + + # TODO: Generalize this as needed, e.g., into a trie of memos, if + # you do something like x[0].item() (x[0] is fresh each time, so + # memo mechanism here won't work) + nonzero_memo: SymNumberMemoDescriptor | int | None = SymNumberMemoDescriptor() + item_memo = SymNumberMemoDescriptor() + unique_memo: SymNumberMemoDescriptor | int | None = SymNumberMemoDescriptor() + unique_consecutive_memo: SymNumberMemoDescriptor | int | None = ( + SymNumberMemoDescriptor() + ) + + # We expect nested_int_memo to be None when an offsets is a graph + # intermediate, or an input that has never been associated with a + # nested int. + nested_int_memo = SymNumberMemoDescriptor(is_nested_int=True) + + # FakeTensor doesn't fully emulate the original tensor's Python type + # and dispatch key set, therefore sometimes we want to track them + # separately. + pytype: type[Tensor] | None + dispatch_keys: torch.DispatchKeySet | None + + # Indicates to our torch_dispatch dispatching infra that + # this is an "infra" mode with lower dispatching precedence. + _mode_key = torch._C._TorchDispatchModeKey.FAKE + + @property + # pyrefly: ignore [bad-override] + def is_mkldnn(self) -> bool: + return _dispatch_keys_has_mkldnn(self.dispatch_keys) + + @property + # pyrefly: ignore [bad-override] + def layout(self) -> torch.layout: + if self.is_mkldnn: + return torch._mkldnn # type: ignore[attr-defined] + return Tensor.layout.__get__(self, type(self)) # type: ignore[attr-defined] + + def to_dense( + self, + dtype: torch.dtype | None = None, + *, + masked_grad: bool | None = None, + ) -> Tensor: + if self.is_mkldnn: + return torch.ops.aten._to_dense.default( + self, dtype=dtype, masked_grad=masked_grad + ) + return Tensor.to_dense(self, dtype=dtype, masked_grad=masked_grad) + + @property + # pyrefly: ignore [bad-override] + def device(self) -> torch.device: + if self.fake_mode.in_kernel_invocation: + return torch.device("meta") + else: + return self.fake_device + + @device.setter + def device(self, _: torch.device) -> None: + raise NotImplementedError + + @property + def fake_device(self) -> torch.device: + return self._fake_device + + @fake_device.setter + def fake_device(self, device: torch.device) -> None: + self._fake_device = self._normalize_fake_device(device) + + # Note: [Fake Tensor Dispatch Keys] + # In order to model the behavior of device-specific autocast + # and autograd logic, we update the dispatch keys of FakeTensors + # to reflect their fake device. This includes the BackendComponent + # (DispatchKey::Meta -> DispatchKey::CUDA), and also the BackendComponent + # related Autocast and Autograd keys. __torch_dispatch__ sits below + # Autocast and Autograd, and is only invoked when we are at the + # kernel for the BackendComponent. Then, we add Meta to the + # thread-local dispatch include set to hit the meta kernel + # instead of the kernel of the BackendComponent for the fake device. + # The `device_for_backend_keys` does that below + # NOTE: this probably will not do the right thing for backends + # that have dispatch keys which are higher than the "meta" key: + # https://github.com/pytorch/pytorch/blob/main/c10/core/DispatchKey.h#L189 + + @staticmethod + def _normalize_fake_device(device: torch.device) -> torch.device: + """Normalize device by initializing GPU context and setting device index.""" + if device.type in ("cuda", "xpu"): + init_gpu_context(device) + + if _is_indexed_device_type(device.type) and device.index is None: + if device.type != "mps" and getattr(torch, device.type).is_initialized(): + device = torch.device( + f"{device.type}:{getattr(torch, device.type).current_device()}" + ) + else: + device = torch.device(f"{device.type}:0") + return device + + @staticmethod + def __new__( + cls, + fake_mode_or_elem: FakeTensorMode | Tensor | None = None, + elem: Tensor | None = None, + device: torch.device | str | None = None, + constant: Tensor | None = None, + real_tensor: Tensor | None = None, + pytype: type[Tensor] | None = None, + dispatch_keys: torch.DispatchKeySet | None = None, + *, + fake_mode: FakeTensorMode | None = None, + fake_device: torch.device | str | None = None, + _fake_device: torch.device | str | None = None, + requires_grad: bool | None = None, + _is_param: bool = False, + **state: Unpack[_FakeTensorConstructorIgnoredState], + ) -> Self: + state_dict = cast(dict[str, object], state) + for attr_name in _FAKE_TENSOR_CONSTRUCTOR_IGNORED_STATE_ATTRS: + state_dict.pop(attr_name, None) + if state_dict: + unexpected = next(iter(state_dict)) + raise TypeError( + "FakeTensor.__new__() got an unexpected keyword argument " + f"{unexpected!r}" + ) + + if isinstance(fake_mode_or_elem, FakeTensorMode): + if fake_mode is not None and fake_mode is not fake_mode_or_elem: + raise TypeError("FakeTensor.__new__() got conflicting fake_mode values") + fake_mode = fake_mode_or_elem + else: + # Support bounded state-based reconstruction from known FakeTensor + # attrs, e.g. type(fake_tensor)(new_elem, **fake_tensor.__dict__). + if fake_mode_or_elem is not None: + if not isinstance(fake_mode_or_elem, Tensor): + raise TypeError( + "FakeTensor.__new__() expected a FakeTensorMode or Tensor " + f"as the first argument, got {type(fake_mode_or_elem)}" + ) + if elem is not None: + raise TypeError( + "FakeTensor.__new__() expected either " + "(fake_mode, elem, ...) or (elem, fake_mode=..., ...)" + ) + elem = fake_mode_or_elem + if fake_mode is None: + raise TypeError( + "FakeTensor.__new__() missing required argument: 'fake_mode'" + ) + + if elem is None: + raise TypeError("FakeTensor.__new__() missing required argument: 'elem'") + + specified_devices = [ + (name, FakeTensor._normalize_fake_device(torch.device(value))) + for name, value in ( + ("device", device), + ("fake_device", fake_device), + ("_fake_device", _fake_device), + ) + if value is not None + ] + if specified_devices: + first_name, resolved_device = specified_devices[0] + for name, candidate_device in specified_devices[1:]: + if resolved_device != candidate_device: + raise ValueError( + "FakeTensor.__new__() got conflicting device values: " + f"{first_name}={resolved_device}, {name}={candidate_device}" + ) + device = resolved_device + else: + raise TypeError( + "FakeTensor.__new__() missing required argument: " + "'device' (or 'fake_device')" + ) + + self = Tensor._make_subclass( + cls, + elem, + elem.requires_grad if requires_grad is None else requires_grad, + dispatch_device=True, + device_for_backend_keys=device, + ) + if not fake_mode._allow_unsafe_data_ptr_access: + torch._C._set_throw_on_mutable_data_ptr(self) + else: + torch._C._set_warn_deprecated_on_mutable_data_ptr(self) + + if elem.device.type != "meta": + raise AssertionError( + f"elem.device.type must be 'meta', got {elem.device.type}" + ) + # NB: it is fine, if a little confusing, for device to be meta + # (we are faking a meta tensor in that case). However, it often + # indicates some sort of confusion (e.g., you accidentally passed + # in a meta tensor when you should have passed in the real tensor). + # So by default we disallow meta, and if you are working in a situation + # where it is helpful (e.g., crossref testing) you can turn it back + # on + if not fake_mode.allow_meta: + if device.type == "meta": + raise AssertionError( + "device.type must not be 'meta' when allow_meta is False" + ) + self.fake_device = device + self.fake_mode = fake_mode + self.constant = constant + self.pytype = pytype + self.dispatch_keys = dispatch_keys + if isinstance(real_tensor, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + raise AssertionError("real_tensor must not be a FakeTensor") + self.real_tensor = real_tensor + self.nonzero_memo = None + self.item_memo = None + self.unique_memo = None + self.unique_consecutive_memo = None + self.nested_int_memo = None + + if _is_param: + self._is_param = _is_param + + if FakeTensorConfig.debug: + self._debug_trace = CapturedTraceback.extract() # type: ignore[attr-defined] + return self + + # In some circumstances, a conventional Tensor constructor + # will get rewritten to call into FakeTensor. We must provide an + # __init__ method that can accept the Python interpreters initialization + # in such a situation; we must also be able to handle direct fake + # tensor construction via FakeTensor(). + # + # In particular, the __init__ call will look funny in the following case: + # + # with FakeTensorMode(): + # x = Tensor([1, 2, 3]) + # + # this desugars into: + # + # with FakeTensorMode(): + # x = Tensor.__new__([1, 2, 3]) + # # NB: x is a fake tensor, because of the mode! + # x.__init__([1, 2, 3]) # not the normal fake tensor args! + # + def __init__(self, *args: object, **kwargs: object) -> None: + super().__init__() + if ( + torch.compiler.is_exporting() + and torch._export.config.detect_non_strict_fake_tensor_leaks + ): + fake_tensor_tls.non_strict_export_fake_tensor_tracker.add(self) + + @staticmethod + def from_tensor(t: Tensor, fake_mode: FakeTensorMode) -> FakeTensor: + return fake_mode.from_tensor(t) + + @classmethod + @count + def __torch_dispatch__( # type: ignore[override] # TODO + cls, + func: OpOverload, + types: Sequence[type], + args: Sequence[object] = (), + kwargs: Mapping[str, object] = immutable_dict(), + ) -> object: + # need to handle here to avoid infinite recursion + # see [in_kernel_invocation] + if func is torch.ops.prim.device.default: + if len(args) != 1 or not isinstance(args[0], FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + raise AssertionError( + "Expected exactly one FakeTensor argument for prim.device.default" + ) + if args[0].fake_mode.in_kernel_invocation: + return torch.device("meta") + else: + return args[0].fake_device + + # this handler must be done inside FakeTensor subclass, not mode, because + # we can end up dispatching here when we have a fake tensor with + # symbolic sizes running under in_kernel_invocation_manager. + # The subclass is asked to handle this query because size (not + # sym_size) was called, but we are unable to serve it directly because + # there are symbolic sizes in the class. The use of + # in_kernel_invocation_manager means it's incorrect to activate a + # mode to actually handle this (this caused + # https://github.com/pytorch/pytorch/issues/122772). + if handler := _DISPATCH_META_HANDLERS.get(func): + return handler(args) + + # Because fake mode can return NotImplemented (if it sees a subclass + # it doesn't know how to deal with), this test here is important + # because the next dispatch after a fake mode will attempt to use + # subclasses of tensors to dispatch, and any FakeTensor arguments + # will be considered eligible. + unrecognized_types = [ + t for t in types if not issubclass(t, FakeTensor) and t is not Tensor + ] + if unrecognized_types: + not_implemented_log.debug( + "FakeTensor unrecognized subclass(es): %s", unrecognized_types + ) + return NotImplemented + + fake_mode = None + for arg in pytree.arg_tree_leaves(*args, **kwargs): + if isinstance(arg, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + fake_mode = arg.fake_mode + break + + if fake_mode is None: + raise AssertionError("Could not find a FakeTensor in the arguments") + + # If the fake mode is already active, don't try to reapply it! + # NotImplemented is the right thing to return here, because the + # typical situation this can occur is if ProxyTensorMode returned a + # NotImplemented because of a not implemented subclass; we may have + # unluckily attempted to hit FakeTensor's dispatch first, + # NotImplemented lets us keep chaining until we find the actual + # subclass + maybe_cur_fake_mode = torch._C._get_dispatch_mode( + torch._C._TorchDispatchModeKey.FAKE + ) + if maybe_cur_fake_mode: + not_implemented_log.debug( + "FakeTensor mode already active: %s in %s", + fake_mode, + maybe_cur_fake_mode, + ) + return NotImplemented + + if fake_mode.in_kernel_invocation: + raise AssertionError("fake_mode.in_kernel_invocation must be False") + + with fake_mode: + return func(*args, **kwargs) + + @staticmethod + def _find_common_device( + func: OpOverload, flat_args: Sequence[object] + ) -> tuple[torch.device, bool]: + # Returns: (common_device, has_scalar_only_inputs) + + # cpu - zero-dim tensors can be called in cuda kernels, + # so overwrite the common_device if it the only existing + # device comes from a cpu zero-dim tensor + common_device = None + has_scalar_only_inputs = False + is_cpu_zero_dim = None + + # list of ops which can have args(tensor/tensorList) in mixed device + mixed_device_fns = ordered_set( + aten._foreach_copy.default, + ) + + # These in-place ops keep the destination tensor's device even if the + # rhs was explicitly constructed on meta. + meta_rhs_mixed_device_fns = ordered_set( + aten.add_.Tensor, + ) + + # list of ops not using zero dim cpu tensor logic to align with the eager mode. + bypass_zero_dim_cpu_tensor_check_ops = ordered_set( + aten.nextafter.default, + ) + + def is_device_cpu(device: torch.device) -> bool: + return device.type == "cpu" + + def is_device_meta(device: torch.device) -> bool: + return device.type == "meta" + + def cpu_zero_dim(t: Tensor) -> bool: + return is_device_cpu(t.device) and t.dim() == 0 + + def merge_devices(t: object) -> None: + nonlocal common_device + nonlocal is_cpu_zero_dim + if not isinstance(t, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + return + + if common_device is None: + common_device = t.device + is_cpu_zero_dim = cpu_zero_dim(t) + return + + t_is_cpu_zero_dim = cpu_zero_dim(t) + if t.device == common_device: + if is_cpu_zero_dim: + is_cpu_zero_dim = t_is_cpu_zero_dim + return + + is_bypass_zero_dim_cpu_tensor_check_op = ( + func in bypass_zero_dim_cpu_tensor_check_ops + ) + + # mismatching devices ! + # if current tensor is cpu 0 dim, defer to existing device + if t_is_cpu_zero_dim and not is_bypass_zero_dim_cpu_tensor_check_op: + return + + # current device is from cpu 0 dim tensor, overwrite + if is_cpu_zero_dim and not is_bypass_zero_dim_cpu_tensor_check_op: + common_device = t.device + is_cpu_zero_dim = t_is_cpu_zero_dim + return + + # if still device mismatches we will check ops which can work + # on different devices for ex. _foreach_copy, and one of the + # device must be cpu in this case we will return from here without + # throwing an error + if func in mixed_device_fns: + if any(map(is_device_cpu, (common_device, t.device))): + return + + if func in meta_rhs_mixed_device_fns: + if any(map(is_device_meta, (common_device, t.device))): + return + + # if prefer_device_type is set, prefer that device type over others + prefer_device_type = torch._functorch.config.fake_tensor_prefer_device_type + if prefer_device_type is not None: + common_has_preferred = prefer_device_type in common_device.type + t_has_preferred = prefer_device_type in t.device.type + + if not common_has_preferred and t_has_preferred: + # Switch to the preferred device type + common_device = t.device + is_cpu_zero_dim = t_is_cpu_zero_dim + return + elif common_has_preferred and not t_has_preferred: + # Keep the existing preferred device type + return + + # mismatching devices of non-zero dim tensors, throw + # This might be valid behavior and need to be explicitly modeled, e.g. reshape_as + raise FakeTensorDeviceMismatchError(func, common_device, t.device) + + for arg in flat_args: + merge_devices(arg) + + # some functions that allow Python numbers to bind to Tensors + # if we have failed to find a device, and we're running one of these operators, + # we must have scalar only inputs + if should_allow_numbers_as_tensors(func) and common_device is None: + # ops with scalar only inputs always have result on cpu + has_scalar_only_inputs = True + common_device = torch.device("cpu") + + if common_device is None: + raise AssertionError(f"Could not find common device for {func}") + + return common_device, has_scalar_only_inputs + + def get_nested_int( + self, + *, + coeff: int | torch.SymInt = 1, + ) -> torch.SymInt: + if self.nested_int_memo is None: + self.nested_int_memo = self.fake_mode.create_symbolic_nested_int( + nt_tensor_id=None + ) + if not isinstance(self.nested_int_memo, torch.SymInt): + raise AssertionError( + f"Expected nested_int_memo to be torch.SymInt, got {type(self.nested_int_memo)}" + ) + return self.nested_int_memo * coeff + + # Similar to FunctionalTensor.tolist + def tolist(self) -> Any: + if self.dim() == 0: + return self.item() + elif self.dim() == 1: + return [elem.item() for elem in self] + else: + return [elem.tolist() for elem in self] + + +_MetadataIntLike = Union[IntLikeType, "_PySymInputStub", "_SymIntOutputStub"] + + +@dataclass(slots=True) +class TensorMetadata: + """ + The Tensor metadata relevant to hashing FakeTensors when caching. + """ + + dtype: torch.dtype + shape: tuple[_MetadataIntLike, ...] + stride: tuple[_MetadataIntLike, ...] + device: torch.device + layout: torch.layout + memory_format: torch.memory_format | None + storage_offset: _MetadataIntLike + storage_bytes: _MetadataIntLike | None + requires_grad: bool + is_quantized: bool + is_conj: bool + is_neg: bool + is_inference: bool + is_sparse: bool # read: is sparse COO + is_coalesced: bool | None + dense_dim: int | None + sparse_dim: int | None + + def _flatten_into( + self, + result: list[object], + mode: FakeTensorMode, + state: _CacheKeyState, + ) -> None: + # Flatten the TensorMetadata out into `result`. Make sure to call + # state.convert_sym_int() on any SymInts. + for field in dataclasses.fields(self): + value = getattr(self, field.name) + if isinstance(value, (tuple, list, torch.Size)): + # This will recursively flatten the iterable, calling + # convert_sym_int() as necessary. + id_hashed_objects: list[object] = [] + mode._prep_args_for_hash(result, value, state, id_hashed_objects) + id_hashed_objects.clear() + elif isinstance(value, SymInt): + state.convert_sym_int(result, value) + else: + result.append(value) + + +def extract_tensor_metadata(t: Tensor) -> TensorMetadata: + """ + Extract the TensorMetadata of a tensor. + """ + # Read layout/sparseness once (hot-path Python properties on FakeTensor). + layout = t.layout + _is_sparse_any: bool = is_sparse_any(t) + # Don't call is_contiguous() on a Tensor which has symbolic sizes or things + # will go badly (guards will be messed up?). suggest_memory_format walks + # sizes and strides, which is symbolic arithmetic for such a tensor, so + # skip it too rather than computing a value we are about to discard. + memory_format: torch.memory_format | None + if t._has_symbolic_sizes_strides or _is_sparse_any: + memory_format = None + else: + memory_format = suggest_memory_format(t) + if not t.is_contiguous(memory_format=memory_format): + memory_format = None + + storage_offset = t.storage_offset() + + return TensorMetadata( + t.dtype, + t.shape, + t.stride() if layout == torch.strided else (), + t.device, + layout, + memory_format, + storage_offset, + # Only set storage_bytes for tensors that have storage (not sparse) + t.untyped_storage().nbytes() if not _is_sparse_any else None, + t.requires_grad, + t.is_quantized, + t.is_conj(), + t.is_neg(), + t.is_inference(), + t.is_sparse, + t.is_coalesced() if t.is_sparse else None, + t.dense_dim() if _is_sparse_any else None, + t.sparse_dim() if _is_sparse_any else None, + ) + + +@dataclass(slots=True) +class _DispatchCacheKey: + """ + Key for the FakeTensor dispatch cache. + """ + + key: tuple[object, ...] + hashvalue: int + + def __init__(self, tup: tuple[object, ...]) -> None: + self.key = tup + self.hashvalue = hash(tup) + + def __eq__(self, other: object) -> bool: + return isinstance(other, _DispatchCacheKey) and self.key == other.key + + def __hash__(self) -> int: + return self.hashvalue + + def strip_shape_env(self) -> None: + # We need to strip the ShapeEnv from any values before we store in the + # cache so the cache doesn't keep our ShapeEnvs alive. + for v in self.key: + if isinstance(v, _PySymInputStub): + v.strip_shape_env() + + +# Default value for constant_value in _DispatchCacheEntryOutputInfo. This is +# only for checking and differentiates from None. +class SingletonConstant: + pass + + +@dataclass(frozen=True, slots=True) +class _DispatchCacheEntryOutputInfo: + """ + Entry type for the FakeTensor dispatch cache for an output. Accounts for three + possibilities: + 1) The op is inplace, and a hit means we need to alias the argument at a + given index. + 2) We need to synthesize a new FakeTensor given tensor metadata. For view + ops, we further capture the index of the arg to alias. + 3) if the tensor related fields are None, then it is a constant value (e.g. + None or integer) + """ + + inplace_idx: int | None + metadata: TensorMetadata | None + view_idx: int | None + constant_value: Any | None = SingletonConstant + + +@dataclass(frozen=True, slots=True) +class _DispatchCacheValidEntry: + """ + Entry type for the FakeTensor dispatch cache. It supports two types of outputs + 1) tensor + 2) tuple of tensors + + is_output_tuple flag helps in differentiating the return type + """ + + output_infos: tuple[_DispatchCacheEntryOutputInfo] + is_output_tuple: bool = False + + +@dataclass(frozen=True, slots=True) +class _DispatchCacheBypassEntry: + """ + Entry type for a negative cache entry. + """ + + reason: str + + +if TYPE_CHECKING: + _DispatchCacheEntry = _DispatchCacheValidEntry | _DispatchCacheBypassEntry + + +@dataclass(frozen=True, slots=True) +class _BypassDispatchCache(Exception): + """ + Signals cases that should skip FakeTensor caching. + """ + + reason: str + + +@dataclass(frozen=True, slots=True) +class DispatchCacheInfo: + """ + Information about the state of the FakeTensor dispatch cache. + """ + + hits: int + misses: int + bypasses: dict[str, int] + size: int + + +# We keep one instantiation of `fake_tensor_converter` active +# for the duration of `with FakeTensorMode()`. +# This allows accurate storage aliasing across invocation of +# different operators. While this will keep all freshly allocated +# tensors alive during `FakeTensorMode`, there will be no +# new allocations of Tensors which have non-meta storage so +# memory should not significantly increase. + + +class FakeTensorMode(TorchDispatchMode): + cache: dict[_DispatchCacheKey, _DispatchCacheEntry] = {} + cache_hits: int = 0 + cache_misses: int = 0 + cache_bypasses: dict[str, int] = defaultdict(int) + # Every time you retrace using the same fake tensor mode, you should + # advance the epoch so we don't reuse unbacked memos + epoch: int = 0 + in_kernel_invocation: bool = False + static_shapes: bool + shape_env: ShapeEnv | None + _stack: str | None + allow_meta: bool + + # NestedTensor uses a tensor_id_counter to uniquely identify offsets. + # This counter is incremented when an offsets is used to create an NJT + # for the first time. To avoid mutating eager state if we construct NJT + # during tracing, we maintain a separate counter on the FakeTensorMode. + # The initial count is set to the current eager tensor_id_counter value + # upon initialization, and every time you retrace using the same fake tensor + # mode, you should reset the counter to the initial count. + nt_tensor_id_counter: int = -1 + nt_tensor_id_initial_count: int = -1 + + def __init__( + self, + *, + allow_fallback_kernels: bool = True, + allow_non_fake_inputs: bool = False, + shape_env: ShapeEnv | None = None, + static_shapes: bool | None = None, + # TODO: This is a temporary measure, see + # https://github.com/pytorch/pytorch/pull/126245#discussion_r1604185748 + # We're currently solely using this to impede population of + # item_memo for 0d scalar tensor inputs when export, because this + # causes things that used to be deferred runtime asserts to turn into + # guards, and then the guards are just lost. We can potentially fix + # this by ensuring guards also get put in the graph, but this is + # pending a rework of how deferred runtime asserts in export. Once + # that's done, we can remove this. + export: bool = False, + ) -> None: + log.debug("create_mode 0x%x", id(self)) + super().__init__() + self.allow_fallback_kernels = allow_fallback_kernels + + import torch._dynamo.config + import torch._functorch.config + + self.propagate_real_tensors = ( + torch._functorch.config.fake_tensor_propagate_real_tensors + ) + self.fake_tensor_converter = FakeTensorConverter( + copy_data=self.propagate_real_tensors, + export=export, + ) + + if static_shapes is not None: + self.static_shapes = static_shapes + else: + self.static_shapes = shape_env is None + + # This is temporarily patched to True in Dynamo to grandfather in some + # places where we unconditionally allow scalar outputs, TO BE REMOVED + self.allow_scalar_outputs = False + + self._allow_unsafe_data_ptr_access = ( + torch._functorch.config.fake_tensor_allow_unsafe_data_ptr_access + ) + self.allow_meta = torch._functorch.config.fake_tensor_allow_meta + self.cache_enabled: bool = ( + torch._dynamo.config.fake_tensor_cache_enabled + and not self.propagate_real_tensors + ) + self.cache_crosscheck_enabled = ( + torch._dynamo.config.fake_tensor_cache_crosscheck_enabled + ) + + # A flag that controls, whether we want to invoke ops on mix of + # real weights/global variables and fake inputs + self.allow_non_fake_inputs = allow_non_fake_inputs + + # [in_kernel_invocation] + # when FakeTensor is invoked in user code, .device should return + # the fake_device of the tensor so that code such as `if x.is_cuda` + # or torch.zeros([10, 10], device=x.device) continues to execute as if + # the FakeTensor were real. However, within kernel execution, we return + # the `Meta` device because all computation within the kernels should + # behave as if the Tensors are on meta devices. Kernels should allocate + # new tensors on meta devices, and checks like `is_meta` should return true. + # within python refs, we always return the real device by defining + # the device property + self.in_kernel_invocation = False + + # True if we enter'ed and actually enabled fake tensor mode, + # false if it was a no-op. Not thread safe but neither is + # in_kernel_invocation + # If another fake mode was already active when we enter, we also stash it here. + # That way when we exit, we know to re-enable the previous fake mode. + self.enter_stack: list[tuple[bool, TorchDispatchMode | None, bool | None]] = [] + + self.shape_env = shape_env + + self._stack_trace = traceback.extract_stack() + self._stack = None + + # Indicates to our torch_dispatch dispatching infra that + # this is an "infra" mode with lower dispatching precedence. + self._mode_key = torch._C._TorchDispatchModeKey.FAKE + + import torch.nested._internal.nested_tensor + + self.nt_tensor_id_initial_count = ( + torch.nested._internal.nested_tensor._tensor_id_counter + ) + self.nt_tensor_id_counter = self.nt_tensor_id_initial_count + + def reset_nt_tensor_id_counter(self) -> None: + self.nt_tensor_id_counter = self.nt_tensor_id_initial_count + + # Typically, there is only one fake tensor mode and you test for it by + # doing an isinstance test. However, in some situations, there might be + # TWO fake tensor modes. The canonical example of this is exporting + # a fake model: there is an outer fake mode created by the user, and + # an inner fake mode created by Dynamo. The two phase process is required + # because the outer fake mode typically won't have a ShapeEnv, even if + # the user is interested in exporting with dynamic shapes (so the inner + # fake mode will actually have a ShapeEnv and swap in symbolic sizes.) + # + # In this case, it's insufficient to test only one FakeTensor: you need + # to distinguish between our fake tensor and other fake tensors. That's + # what this function does. + def is_our_fake(self, t: object) -> TypeGuard[FakeTensor]: + return ( + isinstance( # noqa: ISINSTANCE_FAKE_TENSOR + t, FakeTensor + ) + and t.fake_mode is self + ) + + # If we should avoid device init. This changes the behavior of various APIs: + # - We avoid constant-prop on Tensors with ops that move them to another device + # - We change the torch.tensor ctor contract to never materialize + # tensors on device + # (see NOTE: [torch.tensor, lift_fresh, and device movement]) + @property + def avoid_device_init(self) -> bool: + if torch.xpu._is_compiled(): + if torch.cuda._is_compiled(): + raise AssertionError("Cannot have both xpu and cuda compiled") + return not torch.xpu.is_available() + + return not ( + torch.cuda.is_available() + or (hasattr(torch, "hpu") and torch.hpu.is_available()) + or _is_privateuse1_backend_available() + ) + + @property + def stack(self) -> str: + if self._stack is None: + self._stack = "".join(traceback.format_list(self._stack_trace)) + return self._stack + + @count + # pyrefly: ignore [bad-override] + def __torch_dispatch__( + self, + func: OpOverload, + types: Sequence[type], + args: Sequence[object] = (), + kwargs: Mapping[str, object] = immutable_dict(), + ) -> object: + # FakeTensorMode should not be set when we're inside of it. + if torch._C._get_dispatch_mode(torch._C._TorchDispatchModeKey.FAKE) is not None: + raise AssertionError( + f"FakeTensorMode should not be set when dispatching {func}" + ) + try: + return self.dispatch(func, types, args, kwargs) + except TypeError: + log.exception("fake tensor raised TypeError") + raise + + # No-op if FakeTensorMode is already in use + def __enter__(self) -> Self: + import torch.nested._internal.nested_tensor + + prev_only_lift_cpu_tensors = None + if self.avoid_device_init: + # See NOTE: [torch.tensor, lift_fresh, and device movement] + prev_only_lift_cpu_tensors = torch._C._only_lift_cpu_tensors() + torch._C._set_only_lift_cpu_tensors(True) + + # In the case of CPU-only build or cuda device unavailable, + # we patch the cuda device guard to use NoOpDeviceGuardImpl. + # This enables us to trace over cuda kernels under FakeTensorMode. + torch._C._ensureCUDADeviceGuardSet() + + maybe_prev_fake_mode = torch._C._unset_dispatch_mode(self._mode_key) + if self is not maybe_prev_fake_mode: + self.enter_stack.append( + (True, maybe_prev_fake_mode, prev_only_lift_cpu_tensors) + ) + return super().__enter__() + else: + # no-op (still need to re-set the fake mode though since we unset it) + torch._C._set_dispatch_mode(self) + self.enter_stack.append((False, None, prev_only_lift_cpu_tensors)) + + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + (live, maybe_prev_fake_mode, maybe_prev_only_lift_cpu_tensors) = ( + self.enter_stack.pop() + ) + if live: + super().__exit__(exc_type, exc_val, exc_tb) + + # Re-enable the previous fake mode, if there was one. + if maybe_prev_fake_mode is not None: + torch._C._set_dispatch_mode(maybe_prev_fake_mode) + if maybe_prev_only_lift_cpu_tensors is not None: + torch._C._set_only_lift_cpu_tensors(maybe_prev_only_lift_cpu_tensors) + + @classmethod + def is_infra_mode(cls) -> bool: + return True + + @classmethod + def cache_info(cls) -> DispatchCacheInfo: + """ + Query the state of the dispatch cache. + """ + return DispatchCacheInfo( + FakeTensorMode.cache_hits, + FakeTensorMode.cache_misses, + dict(FakeTensorMode.cache_bypasses), + len(FakeTensorMode.cache), + ) + + @classmethod + def cache_clear(cls) -> None: + """ + Clear the dispatch cache. + """ + cls.cache_hits = 0 + cls.cache_misses = 0 + cls.cache_bypasses.clear() + cls.cache.clear() + + def _cached_dispatch_impl( + self, + func: OpOverload, + types: Sequence[type], + args: Sequence[object], + kwargs: Mapping[str, object], + ) -> object: + """ + Lookup a cache entry for the given arguments. If none exists, dispatch + and cache the result (if the result is eligible for caching). + """ + state = None + key = None + try: + state = _CacheKeyState(self.shape_env) + key = self._cache_key(state, func, args, kwargs) + except _BypassDispatchCache as e: + # We couldn't create the cache key at all + if ( + isinstance(func, torch._ops.HigherOrderOperator) + and func.name() == "invoke_subgraph" + ): + hc_log.debug( + "Fake tensor cache failed: identifier = %s, reason = %s", + args[1], + e.reason, + ) + FakeTensorMode.cache_bypasses[e.reason] += 1 + + if key is None: + # Do this dispatch outside the above except handler so if it + # generates its own exception there won't be a __context__ caused by + # the caching mechanism. + + return self._dispatch_impl(func, types, args, kwargs) + + if state is None: + raise AssertionError("state must not be None after cache key generation") + if state.cache_on_shape_env(): + if state.shape_env is None: + raise AssertionError( + "state.shape_env must not be None when caching on shape_env" + ) + cache = state.shape_env.fake_tensor_cache + set_cache_key = _set_cache_key_for_shape_env + else: + cache = FakeTensorMode.cache + set_cache_key = _set_cache_key + entry = cache.get(key, None) + + if entry is not None: + if isinstance(entry, _DispatchCacheBypassEntry): + # This represents a negative cache entry - we already saw that the + # output is uncachable. Compute it from first principals. + FakeTensorMode.cache_bypasses[entry.reason] += 1 + + return self._dispatch_impl(func, types, args, kwargs) + + # We have a cache entry. + + output = self._output_from_cache_entry(state, entry, key, func, args) + FakeTensorMode.cache_hits += 1 + if self.cache_crosscheck_enabled: + # For debugging / testing: Validate that the output synthesized + # from the cache matches the output created by normal dispatch. + with disable_fake_tensor_cache(self): + self._crosscheck_cache_output(output, func, types, args, kwargs) + return output + + # We don't have a cache entry. + + output = self._dispatch_impl(func, types, args, kwargs) + + try: + entry = self._make_cache_entry(state, key, func, args, kwargs, output) + except _BypassDispatchCache as e: + # We ran "extra" checks on the cache key and determined that it's no + # good. Record the reason and mark it so we don't bother validating + # again. + if ( + isinstance(func, torch._ops.HigherOrderOperator) + and func.name() == "invoke_subgraph" + ): + hc_log.debug( + "Fake tensor cache failed: identifier = %s, reason = %s", + args[1], + e.reason, + ) + FakeTensorMode.cache_bypasses[e.reason] += 1 + set_cache_key(cache, key, _DispatchCacheBypassEntry(e.reason)) + return output + + set_cache_key(cache, key, entry) + FakeTensorMode.cache_misses += 1 + return output + + def _cache_key( + self, + state: _CacheKeyState, + func: OpOverload, + args: Sequence[object], + kwargs: Mapping[str, object], + ) -> _DispatchCacheKey: + """ + Create a cache key given the dispatch args. Raises _BypassDispatchCache + for any situation that precludes caching. + """ + is_tracing = torch.fx.experimental.proxy_tensor.get_proxy_mode() is not None + key_values = [ + func, + # Capture the default_dtype mode since that can affect the output tensor, + # e.g., when operating on constant float values. + torch.get_default_dtype(), + # Capture the current device to support, e.g., cache tensor creation, + # where there isn't necessarily a tensor to take the device from. + torch._C._get_default_device(), + # We want to create tensors from cached metadata only when the inference + # mode is the same. + torch.is_inference_mode_enabled(), + # Shape env settings could affect behavior. One example seen in the wild: + # Disallowing dynamic shapes can introduce a DynamicOutputShapeException + # where it wasn't seen on a previous instance of the same op. + self.shape_env.settings if self.shape_env else None, + # ProxyTorchDispatchMode needs to track how SymNodes are constructed + # so we need to handle things a little different depending on + # whether we're tracing or not. + is_tracing, + ] + if state.known_symbols: + # If there are symbols then include the epoch - this is really more + # of a Shape env var which lives on the FakeTensorMode. + # pyrefly: ignore [bad-argument-type] + key_values.append(self.epoch) + # Collect the id_hashed objects to attach a weakref finalize later + id_hashed_objects: list[object] = [] + # Translate any FakeTensor args to metadata. + if args: + # pyrefly: ignore [bad-argument-type] + self._prep_args_for_hash(key_values, args, state, id_hashed_objects) + if kwargs: + # pyrefly: ignore [bad-argument-type] + self._prep_args_for_hash(key_values, kwargs, state, id_hashed_objects) + key = _DispatchCacheKey(tuple(key_values)) + + for id_hashed_obj in id_hashed_objects: + weakref.finalize( + id_hashed_obj, functools.partial(evict_fake_tensor_cache_key, key=key) + ) + id_hashed_objects.clear() + return key + + def _validate_cache_key( + self, + func: OpOverload, + args: Sequence[object], + kwargs: Mapping[str, object], + ) -> None: + """ + Validate that the cache key generated by _cache_key will be + reasonable. + """ + from torch._higher_order_ops.utils import registered_hop_fake_fns + + # For hops, we perform the validity check in _make_cache_entry because we + # need to have the output tensor. + if ( + isinstance(func, torch._ops.HigherOrderOperator) + and func in registered_hop_fake_fns + ): + return + + # Avoid caching for any ops that would require a more sophisticated + # caching implementation, e.g., data dependent ops or ops that modify + # the inputs. + if torch.Tag.data_dependent_output in func.tags: + raise _BypassDispatchCache("data dependent output") + + if torch.Tag.dynamic_output_shape in func.tags: + if func is aten.index.Tensor: + _, new_kwargs = normalize_function( # type: ignore[misc] + func, + args=args, # type: ignore[arg-type] + kwargs=kwargs, # type: ignore[arg-type] + normalize_to_only_use_kwargs=True, + ) + for index in new_kwargs["indices"]: + # index calls nonzero for bool or int8 tensors, and + # therefore has a dynamic shape output. For other dtypes, + # the output shape depends on the input shape (and not data) + if isinstance(index, torch.Tensor) and index.dtype in ( + torch.bool, + torch.int8, + ): + raise _BypassDispatchCache("dynamic output shape") + return + + raise _BypassDispatchCache("dynamic output shape") + + if torch.Tag.inplace_view in func.tags: + raise _BypassDispatchCache("inplace view") + + if func is aten._unsafe_view.default: + raise _BypassDispatchCache("unsafe view") + + if func is torch.ops.prims.as_strided.default: + raise _BypassDispatchCache("prims.as_strided") + + if func in self.lift_fns: + raise _BypassDispatchCache("lift") + + if func is aten.to_mkldnn.default: + raise _BypassDispatchCache("mkldnn tensor") + + if func.name() == "inductor::resize_storage_bytes_": + raise _BypassDispatchCache("inductor::resize_storage_bytes_") + + if not torch._library.utils.is_builtin(func): + raise _BypassDispatchCache("non-builtin") + + # In order to handle storage aliasing, we need to establish the alias + # for any view op on a cache hit. But CompositeImplicitAutograd ops may + # or may not alias the input, so just punt on caching these. + if func.is_view and torch._C._dispatch_has_kernel_for_dispatch_key( + func.name(), torch._C.DispatchKey.CompositeImplicitAutograd + ): + raise _BypassDispatchCache("CompositeImplicitAutograd") + + def _prep_args_for_hash( + self, + result: list[object], + args: Mapping[str, object] | Sequence[object] | Iterable[object], + state: _CacheKeyState, + id_hashed_objects: list[object], + ) -> None: + """ + Translate the provided args into a form suitable for caching at FakeTensor + dispatch, i.e., convert unhashable types like lists & dicts into tuples and + convert FakeTensors into metadata. Raises _BypassDispatchCache to signal + unsupported cases that should bypass caching. + """ + from torch._higher_order_ops.auto_functionalize import ( + FunctionalCallableWithEpilogue, + ) + from torch._higher_order_ops.utils import SubgraphCallableWrapper + + if isinstance(args, (list, tuple, dict)): + result.append(type(args)) + result.append(f"length_{len(args)}") + + if isinstance(args, dict): + self._prep_args_for_hash(result, args.keys(), state, id_hashed_objects) + self._prep_args_for_hash(result, args.values(), state, id_hashed_objects) + return + + for arg in args: + if isinstance(arg, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + if not self.is_our_fake(arg): + raise _BypassDispatchCache("not our fake") + if arg.constant is not None: + raise _BypassDispatchCache("constant attribute") + if is_sparse_any(arg): + raise _BypassDispatchCache(f"{arg.layout} tensor") + if arg.is_mkldnn: + raise _BypassDispatchCache("mkldnn tensor") + metadata = extract_tensor_metadata(arg) + metadata._flatten_into(result, self, state) + elif isinstance(arg, Tensor): + raise _BypassDispatchCache("non-fake tensor") + elif isinstance(arg, SymInt): + state.convert_sym_int(result, arg) + elif isinstance(arg, (SymBool, SymFloat)): + raise _BypassDispatchCache("symbolic shape") + elif isinstance(arg, (list, tuple, dict)): + self._prep_args_for_hash(result, arg, state, id_hashed_objects) + elif isinstance(arg, types.FunctionType): + raise _BypassDispatchCache("function argument") + elif isinstance(arg, torch.fx.GraphModule): + # This is used for invoke_subgraph where id(graph_module) allows + # us to cache fake outputs + result.append(type(arg)) + result.append(id(arg)) + id_hashed_objects.append(arg) + elif isinstance(arg, SubgraphCallableWrapper): + result.append(hash(arg)) + id_hashed_objects.append(arg.subgraph) + elif isinstance(arg, FunctionalCallableWithEpilogue): + result.append(type(arg)) + result.append(hash(arg)) + id_hashed_objects.append(arg.orig_callable) + else: + # It's important to capture the type of the arg since, e.g., 1 and 1.0 + # hash to the same value, but can produce different dtypes for the + # output tensor. + result.append(type(arg)) + result.append(arg) + + def _validate_output_for_cache_entry( + self, + state: _CacheKeyState, + key: _DispatchCacheKey, + func: OpOverload, + args: Sequence[object], + kwargs: Mapping[str, object], + output: FakeTensor | None, + ) -> None: + # Is this even possible? According to the signature this can be None but + # not `int`. So either the signature is a lie or (part of) this line is + # unnecessary... + if isinstance(output, (int, type(None))): + return + + # Check for symbolic content that should bypass caching - raises + # _BypassDispatchCache if necessary. + _validate_symbolic_output_for_caching(state, output) + + # Some ops return tuples of Tensors, but it's rare, so avoid + # the complexity of caching other types. + if not isinstance(output, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + raise _BypassDispatchCache("non-FakeTensor output") + + # Avoid caching FakeTensors with constants attached since those + # can be invalidated. + if output.constant is not None: + raise _BypassDispatchCache("constant attribute") + + # TODO: support caching sparse outputs? + if output.is_sparse: + raise _BypassDispatchCache("sparse output") + + if is_sparse_compressed(output): + raise _BypassDispatchCache("sparse compressed output") + + # Can an in-place op really reference a kwarg? If so, then we need + # to extend the implementation to handle it. + for kval in kwargs.values(): + if id(kval) == id(output): + raise _BypassDispatchCache("kwarg aliases output") + + def _get_output_info_for_cache_entry( + self, + state: _CacheKeyState, + key: _DispatchCacheKey, + func: OpOverload, + args: Sequence[object], + kwargs: Mapping[str, object], + output: FakeTensor, + ) -> _DispatchCacheEntryOutputInfo: + if isinstance(output, (int, torch.SymInt, type(None))): + return _DispatchCacheEntryOutputInfo( + inplace_idx=None, metadata=None, view_idx=None, constant_value=output + ) + + # If this is an in-place op, the entry records which input arg is aliased. + for idx in range(len(args)): + if id(args[idx]) == id(output): + return _DispatchCacheEntryOutputInfo( + inplace_idx=idx, metadata=None, view_idx=None + ) + + # Otherwise, create an entry that records the output tensor's metadata. + view_idx = None + if isinstance(func, torch._ops.OpOverload) and func.is_view: + idxs = [i for i, t in enumerate(args) if isinstance(t, Tensor)] + if len(idxs) != 1: + raise AssertionError( + f"Expected exactly one tensor arg for view op, got {len(idxs)}" + ) + view_idx = idxs[0] + + metadata = extract_tensor_metadata(output) + metadata.shape = tuple(state.convert_output(v) for v in metadata.shape) + metadata.stride = tuple(state.convert_output(v) for v in metadata.stride) + metadata.storage_offset = state.convert_output(metadata.storage_offset) + metadata.storage_bytes = ( + None + if metadata.storage_bytes is None + else state.convert_output(metadata.storage_bytes) + ) + + entry = _DispatchCacheEntryOutputInfo( + inplace_idx=None, + metadata=metadata, + view_idx=view_idx, + ) + + # N.B.: Some checks for bypassing the cache would be performed on the + # output tensor synthesized from the cached metadata. As an optimization, + # we can synthesize a tensor here and do the checks on that instance. + # This approach keeps the (more frequent) cache-hit path as lightweight + # as possible. + entry_for_synth_output = _DispatchCacheValidEntry( + output_infos=(entry,), is_output_tuple=False + ) + from torch.fx.experimental.symbolic_shapes import GuardOnDataDependentSymNode + + try: + synth_output = self._output_from_cache_entry( + state, entry_for_synth_output, key, func, args + ) + except GuardOnDataDependentSymNode: + # This should probably never really happen. If it does it means that + # although the original call didn't get a data-dependent error when + # we tried to reconstruct the output we did - that's almost + # certainly a bug. + raise _BypassDispatchCache("data dependent symnode") from None + + # Make sure the dispatch_key_set from the synthesized output tensor will + # be the same. + synth_key_set = torch._C._dispatch_key_set(synth_output) + key_set = torch._C._dispatch_key_set(output) + if synth_key_set != key_set: + raise _BypassDispatchCache("dispatch_key_set mismatch") + + return entry + + def _make_cache_entry( + self, + state: _CacheKeyState, + key: _DispatchCacheKey, + func: OpOverload, + args: Sequence[object], + kwargs: Mapping[str, object], + output: FakeTensor | None, + ) -> _DispatchCacheValidEntry: + """ + Make a cache entry object for the given 'output' Tensor. Raises + _BypassDispatchCache if the output tensor has characteristics that + prevent caching it. + """ + from torch._higher_order_ops.utils import ( + hops_that_skip_faketensor_cache, + registered_hop_fake_fns, + ) + from torch.fx.experimental.symbolic_shapes import has_free_unbacked_symbols + + self._validate_cache_key(func, args, kwargs) + + # For hops, lets look at the output tensor to find any unbacked symints. + # If there are none, then we rely on the existing checks to validate + # caching. + # NB: Note that the HOPs that sta alive till FakeTensor are functional, + # once they support mutations, we will have to revisit this logic. + # Skipping caching for HOPs that used to be registered with @py.impl(FakeTensorMode) + # to preserve original behaviour + if ( + isinstance(func, torch._ops.HigherOrderOperator) + and func in registered_hop_fake_fns + ): + outs = output if isinstance(output, tuple) else (output,) + non_cacheable = ( + any( + isinstance(o, (torch.Tensor, torch.SymInt)) + and has_free_unbacked_symbols(o) + for o in outs + ) + or func in hops_that_skip_faketensor_cache + ) + if non_cacheable: + raise _BypassDispatchCache( + f"unbacked symbol in HOP {func} output \ + or {func} in hops_that_skip_faketensor_cache" + ) + + if isinstance(output, (int, torch.SymInt, type(None))): + output_info = _DispatchCacheEntryOutputInfo( + inplace_idx=None, metadata=None, view_idx=None, constant_value=output + ) + return _DispatchCacheValidEntry( + output_infos=(output_info,), is_output_tuple=False + ) + + if isinstance(output, tuple): + for out_element in output: + self._validate_output_for_cache_entry( + state, + key, + func, + args, + kwargs, + out_element, + ) + else: + self._validate_output_for_cache_entry( + state, + key, + func, + args, + kwargs, + output, + ) + + if isinstance(output, tuple): + output_infos = [ + self._get_output_info_for_cache_entry( + state, + key, + func, + args, + kwargs, + out_elem, + ) + for out_elem in output + ] + return _DispatchCacheValidEntry( + # pyrefly: ignore [bad-argument-type] + output_infos=tuple(output_infos), + is_output_tuple=True, + ) + + else: + output_info = self._get_output_info_for_cache_entry( + state, + key, + func, + args, + kwargs, + output, + ) + return _DispatchCacheValidEntry( + output_infos=(output_info,), is_output_tuple=False + ) + + def _get_output_tensor_from_cache_entry( + self, + state: _CacheKeyState, + entry: _DispatchCacheEntryOutputInfo, + key: _DispatchCacheKey, + func: OpOverload, + args: Sequence[object], + ) -> FakeTensor | None: + if ( + entry.inplace_idx is None + and entry.metadata is None + and entry.view_idx is None + ): + if entry.constant_value is SingletonConstant: + raise AssertionError( + "entry.constant_value must not be SingletonConstant" + ) + return entry.constant_value + if entry.inplace_idx is not None: + # This is an in-place op; return the aliased arg. + inplace_arg = args[entry.inplace_idx] + if not isinstance(inplace_arg, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + raise AssertionError("inplace_arg must be a FakeTensor") + return inplace_arg + + # Synthesize a new FakeTensor with the cached metadata. + metadata = entry.metadata + if metadata is None: + return None + + if is_sparse_any(metadata): + raise AssertionError("Sparse tensors are not supported in cache") + + def check_value(value: _MetadataIntLike, state: _CacheKeyState) -> IntLikeType: + if isinstance(value, _SymIntOutputStub): + if state.shape_env is None: + raise AssertionError( + "state.shape_env must not be None for _SymIntOutputStub" + ) + return value.extract(key, state.shape_env) + else: + if isinstance(value, _PySymInputStub): + raise AssertionError("Unexpected _PySymInputStub value") + return value + + shape = tuple(check_value(v, state) for v in metadata.shape) + stride = tuple(check_value(v, state) for v in metadata.stride) + storage_offset = check_value(metadata.storage_offset, state) + if metadata.storage_bytes is not None: + check_value(metadata.storage_bytes, state) + + maybe_suppress: Callable[[], typing.ContextManager[None]] = ( + contextlib.nullcontext + ) + if self.shape_env is not None: + maybe_suppress = self.shape_env.suppress_guards + + with in_kernel_invocation_manager(self), maybe_suppress(): + empty = torch.empty_strided( + shape, + stride, + dtype=metadata.dtype, + layout=metadata.layout, + device="meta", + requires_grad=metadata.requires_grad, + ) + + if metadata.is_conj: + torch._C._set_conj(empty, True) + if metadata.is_neg: + torch._C._set_neg(empty, True) + + if isinstance(func, torch._ops.OpOverload) and func.is_view: + # For view ops, the storage should be the same as the tensor input. + view_arg = args[cast(int, entry.view_idx)] + if not isinstance(view_arg, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + raise AssertionError("view_arg must be a FakeTensor") + storage = view_arg.untyped_storage() + with in_kernel_invocation_manager(self), maybe_suppress(): + empty.set_(storage, storage_offset, shape, stride) + + return FakeTensor(self, empty, metadata.device) + + def _output_from_cache_entry( + self, + state: _CacheKeyState, + entry: _DispatchCacheValidEntry, + key: _DispatchCacheKey, + func: OpOverload, + args: Sequence[object], + ) -> FakeTensor | None | tuple[FakeTensor | None, ...]: + """ + Create a new FakeTensor from the cache entry. + """ + + if entry.is_output_tuple: + outputs = [ + self._get_output_tensor_from_cache_entry( + state, output_info, key, func, args + ) + for output_info in entry.output_infos + ] + return tuple(outputs) + else: + return self._get_output_tensor_from_cache_entry( + state, entry.output_infos[0], key, func, args + ) + + def _crosscheck_cache_output( + self, + output: FakeTensor | None | tuple[FakeTensor | None, ...], + func: OpOverload, + types: Sequence[type], + args: Sequence[object], + kwargs: Mapping[str, object], + ) -> None: + """ + Helper to validate that the output synthesized from the cache matches + the output created by normal dispatch. + """ + + def assert_helper(a: Any, b: Any) -> None: + if isinstance(a, tuple): + if not isinstance(b, tuple): + raise AssertionError(f"Expected tuple, got {type(b)}") + if len(a) != len(b): + raise AssertionError(f"Tuple length mismatch: {len(a)} != {len(b)}") + for l, r in zip(a, b): + assert_helper(l, r) + elif isinstance(a, int): + if not isinstance(b, int) or a != b: + raise AssertionError(f"Int mismatch: {a} != {b}") + elif a is None: + if b is not None: + raise AssertionError(f"Expected None, got {b}") + elif isinstance(a, py_sym_types): + if type(a) is not type(b) or a.node is not b.node: + raise AssertionError(f"SymType mismatch: {a} != {b}") + elif isinstance(a, torch.Tensor): + if not isinstance(b, torch.Tensor): + raise AssertionError(f"Expected Tensor, got {type(b)}") + assert_metadata_eq(assert_eq, a, b) + else: + raise RuntimeError(f"Unsupported type {type(a)}") + + try: + true_output = self._dispatch_impl(func, types, args, kwargs) + except Exception as e: + raise RuntimeError( + f"FakeTensor cache crosscheck failure: func={func}, " + f"args={args}, kwargs={kwargs}: Dispatch raised={e}" + ) from e + try: + assert_helper(true_output, output) + except Exception as e: + raise RuntimeError( + f"FakeTensor cache crosscheck failure: func={func}, " + f"args={args}, kwargs={kwargs}" + ) from e + + def dispatch( + self, + func: OpOverload, + types: Sequence[type], + args: Sequence[object] = (), + kwargs: Mapping[str, object] = immutable_dict(), + ) -> object: + kwargs = kwargs or {} + with no_dispatch(): + log.debug("%s %s %s", func, args, kwargs) + + if func in _DISPATCH_META_HANDLERS: + return _DISPATCH_META_HANDLERS[func](args) + + if log.getEffectiveLevel() <= logging.DEBUG: + log.debug( + "%sFakeTensorMode.__torch_dispatch__: %s", " " * RECURSION_COUNT, func + ) + # NOTE: incr is intentionally unused for a RAII pattern + incr = IncrementRecursionCount() # noqa: F841 + + # Some attribute queries that can be serviced directly + # See Note [is_coalesced is dispatched] + if func in _DISPATCH_HANDLE_DIRECTLY: + # NB: no_dispatch is ok here too, this func is very simple + with in_kernel_invocation_manager(self): + return func(*args, **kwargs) + + if self.cache_enabled: + return self._cached_dispatch_impl(func, types, args, kwargs) + else: + return self._dispatch_impl(func, types, args, kwargs) + + def _maybe_infer_fake( + self, func: OpOverload, path: KeyPath, fake: object, real: object + ) -> tuple[object | None, bool]: + """ + Helper to cross-check fake/real output properties & values, + and create new fake vals if mismatched. + Returns tuple of object & boolean, for whether or not it was overwrriten + """ + import sympy + + from torch._subclasses.fake_utils import _check_fake_real_tensors + + def _check_fake_real_vals(fake: Any, real: Any) -> None: + # use real values + ShapeEnv to check mismatches between potentially symbolic values + if isinstance(fake, (SymInt, SymFloat)): + # symbolic expression, ask ShapeEnv to substitute known backed/unbacked values + if self.shape_env is None: + raise AssertionError( + "self.shape_env must not be None for symbolic values" + ) + if ( + not fake.node.expr.free_symbols + - self.shape_env.backed_var_to_val.keys() + - self.shape_env.real_tensor_prop_unbacked_vals.keys() + ): + if ( + self.shape_env._maybe_evaluate_static( + sympy.Eq(fake.node.expr, real), compute_hint=True + ) + is not sympy.S.true + ): + raise MetadataMismatchError( + f"mismatch between fake value {fake} and real value {real} " + ) + elif isinstance( + fake, (int, float, bool) + ): # concrete value, check direct equality + if fake != real: + raise MetadataMismatchError( + f"mismatch between fake value {fake} and real value {real} " + ) + + if isinstance(fake, torch.Tensor): + try: + _check_fake_real_tensors( + real, # type: ignore[arg-type] + fake, # type: ignore[arg-type] + context="Real tensor propagation found", + sizes=False, # manual check below + strides=False, # skip strides + storage_offset=True, + requires_grad=False, # issues with FakeTensorConverter preserving requires_grad + ) + except MetadataMismatchError as exc: + if torch._functorch.config.generate_fake_kernels_from_real_mismatches: + dtrace_structured( + "mismatched_fake_kernel", + metadata_fn=lambda: { + "op": str(func), + "reason": exc.reason, # noqa: F821 + }, + ) + return _infer_fake_from_real_tensor(self, func, real), True # type: ignore[arg-type] + raise MetadataMismatchError( + f"Real tensor propagation found a metadata mismatch between " + f"fake tensor {fake} and real tensor {real}, " + f" at output{keystr(path)}, for func: {func}" + ) from exc + + for j, (s_fake, s_real) in enumerate(zip(fake.size(), real.size())): # type: ignore[attr-defined] + try: + _check_fake_real_vals(s_fake, s_real) + except MetadataMismatchError as exc: + if torch._functorch.config.generate_fake_kernels_from_real_mismatches: + dtrace_structured( + "mismatched_fake_kernel", + metadata_fn=lambda: { + "op": str(func), + "reason": exc.reason, # noqa: F821 + }, + ) + return _infer_fake_from_real_tensor(self, func, real), True # type: ignore[arg-type] + raise MetadataMismatchError( + f"Real tensor propagation found an output size mismatch between " + f"fake shape {s_fake} and real shape {s_real}, " + f"at output{keystr(path)}.size({j}), for func: {func}" + ) from exc + elif fake is None and real is not None: + if torch._functorch.config.generate_fake_kernels_from_real_mismatches: + dtrace_structured( + "mismatched_fake_kernel", + metadata_fn=lambda: { + "op": str(func), + "reason": f"mismatch between fake value {fake} and real value {real}", + }, + ) + return _infer_fake_from_real_tensor(self, func, real), True # type: ignore[arg-type] + raise MetadataMismatchError( + f"Real tensor propagation found a metadata mismatch between " + f"fake tensor {fake} and real tensor {real}, " + f" at output{keystr(path)}, for func: {func}" + ) + else: + try: + _check_fake_real_vals(fake, real) + except MetadataMismatchError as exc: + raise MetadataMismatchError( + f"Real tensor propagation found an output value mismatch between " + f"fake output value {fake} and real output value {real}, " + f"at output{keystr(path)}, for func: {func}" + ) from exc + return fake, False + + def _maybe_infer_fake_kernel_from_pytree_out( + self, + func: OpOverload, + fake_in: object, + real_in: object, + fake_out: object, + real_out: object, + ) -> object | None: + """ + Helper to cross-check fake/real output properties & values, + and create new fake vals if mismatched, but at the kernel level. + Means this handles pytree outputs & checks aliasing. + """ + from torch._subclasses.fake_utils import _check_alias_info + + # we might have to clear pending unbacked symbols, if we override the kernel + pending_unbacked = None + if self.shape_env: + pending_unbacked = list(self.shape_env.pending_fresh_unbacked_symbols) + + def _clear_pending_unbacked() -> None: + self.shape_env.pending_fresh_unbacked_symbols = list( # type: ignore[union-attr] + set(self.shape_env.pending_fresh_unbacked_symbols).difference( # type: ignore[union-attr] + pending_unbacked # type: ignore[arg-type] + ) + ) + + fake_paths_leaves, fake_spec = pytree.tree_flatten_with_path(fake_out) + real_leaves, _ = pytree.tree_flatten(real_out) + try: + # catch aliasing mismatches between fake/real tensors + _check_alias_info( + "Real tensor propagation found", real_out, real_in, fake_out, fake_in + ) + except MetadataMismatchError as exc: + # if mismatch found, optionally infer fake kernel + if torch._functorch.config.generate_fake_kernels_from_real_mismatches: + dtrace_structured( + "mismatched_fake_kernel", + metadata_fn=lambda: { + "op": str(func), + "reason": ( + f"Mismatched aliasing spec between fake kernel and real kernel: {exc.reason}" # noqa: F821 + ), + }, + ) + # if aliasing mismatches are found, it's likely that the fake tensor impl + # is incorrectly aliasing, since we don't support aliasing custom ops. + # in this case we can default to inferring non-aliasing fake kernels from the real outputs. + _clear_pending_unbacked() + return tree_map( + lambda x: _infer_fake_from_real_tensor(self, func, x), real_out + ) + else: + raise MetadataMismatchError( + f"Real tensor propagation found an aliasing mismatch between " + f"fake output {fake_out} and real output {real_out}, " + f" for func: {func}" + ) from exc + + # if no errors raised, run cross checks on fake/real tensors, + # optionally overriding individual fake tensors, if individual meta kernel output is incorrect. + fake_leaves, overrides = zip( + *[ + self._maybe_infer_fake(func, _fake_path, _fake_out, _real_out) + for (_fake_path, _fake_out), _real_out in zip( + fake_paths_leaves, real_leaves + ) + ] + ) + if ( + any(overrides) and pending_unbacked + ): # only keep new pending unbacked symbols + _clear_pending_unbacked() + return pytree.tree_unflatten(fake_leaves, fake_spec) + + def _dispatch_impl( + self, + func: OpOverload, + types: Sequence[type], + args: Sequence[object], + kwargs: Mapping[str, object], + ) -> FakeTensor | None: + from torch._higher_order_ops.utils import registered_hop_fake_fns + + flat_args, args_spec = pytree.tree_flatten((args, kwargs)) + + # DO NOT PUT LOGIC BEFORE UNRECOGNIZED TYPE CHECKING + # We must throw NotImplemented in case of unrecognized types to handle subclasses. + # Throwing the exception will pass the control to the next __torch_dispatch__. + # See [subclass inputs] below + # NB: If you're seeing a mysterious infinite loop involving fake + # tensor, it might be related to this line. Though I'm not sure + # how you'll know to read this comment, as this line won't show up + # in the stack trace. + has_unrecognized_types = _check_for_subclass(flat_args) + if has_unrecognized_types: + unrecognized_types = [ + type(x) for x in flat_args if _check_for_subclass_arg(x) + ] + not_implemented_log.debug( + "FakeTensorMode unrecognized subclass(es): %s", unrecognized_types + ) + return NotImplemented + + flat_arg_fake_tensors = [t for t in flat_args if self.is_our_fake(t)] + has_symbolic_sizes = any( + i._has_symbolic_sizes_strides for i in flat_arg_fake_tensors + ) or any(isinstance(a, SymInt) for a in flat_args) + + converter = self.fake_tensor_converter + + is_lift_func = func in self.lift_fns + + # If we are trying to avoid device init, then we need to avoid constant + # prop on constant tensors for ops that change devices. + avoiding_device_init = False + if self.avoid_device_init: + if ( + func is torch.ops.aten._to_copy.default + and "device" in kwargs + and kwargs["device"].type != "cpu" # type: ignore[attr-defined] + ): + avoiding_device_init = True + if func is torch.ops.prims.device_put.default: + avoiding_device_init = True + + # skip const prop for aten._to_copy if + # 1. input tensor is on "meta" device + # 2. destination device is unavailable, captured by `avoiding_device_init` + device_conversion_skip_const_prop = ( + func is torch.ops.aten._to_copy.default + and isinstance(args[0], torch.Tensor) + and args[0].device.type == "meta" + ) or avoiding_device_init + + # To constant propagate through these functions: + # 1, If this is a lift due to a torch.tensor call, + # the input tensor is guaranteed to be a + # constant, so we keep a copy of the original argument along so + # we can query it if we're asked to item() it at some later point. + # (Note that you can always call a lift fn manually, so we do + # have to check if there are any fake tensors!) + # 2, Some functions that allow Python numbers to bind to Tensors, e.g, torch.div + if (is_lift_func and not flat_arg_fake_tensors) or ( + should_allow_numbers_as_tensors(func) + and not has_symbolic_sizes + and not flat_arg_fake_tensors + and not device_conversion_skip_const_prop + ): + if not all(t.constant is not None for t in flat_arg_fake_tensors): + raise AssertionError( + f"{func} should not have fake inputs without constants" + ) + const_flat_args = [ + a.constant if self.is_our_fake(a) else a for a in flat_args + ] + const_args, const_kwargs = pytree.tree_unflatten(const_flat_args, args_spec) + out = func(*const_args, **const_kwargs) + if type(out) is Tensor and self.may_turn_const(out): + # NB: not in_kernel_invocation_manager because we're doing real + # compute here + # NB: no_dispatch() here is VERY DANGEROUS (like, segfault + # dangerous) if this is actually a wrapper subclass tensor, + # therefore the exact type test above + with no_dispatch(): + out = out.clone() + return converter.from_real_tensor(self, out, make_constant=True) + + # if we are in the dispatch mode, we will enter this function even if the inputs + # are not FakeTensors. For now, throw if any non-Fake Tensor inputs + # and just support constructors. + + # this is generated from torch.tensor(), which does not use the + # dispatcher, to allow wrapper subclasses to wrap the new tensor + if is_lift_func: + if len(kwargs) != 0 or len(args) != 1: + raise AssertionError( + f"Expected exactly one arg for lift func, got args={args} kwargs={kwargs}" + ) + + if type(args[0]) is Tensor: + return converter.from_real_tensor(self, args[0]) + + # Recompute flat_arg_fake_tensors here again in case some of the inputs + # were real tensors and fakified in validate_and_convert_non_fake_tensors + (flat_args, flat_arg_fake_tensors) = self.validate_and_convert_non_fake_tensors( + func, converter, flat_args, args_spec + ) + del args, kwargs # Invalidated + + # The current constant handling only support tracing systems + # (aot autograd, torchdynamo) where each operation is run consecutively. + # Because each operation is run in order, we can trace out and support + # sequences like: x = torch.tensor(0.); y = x.add_(1) + # Whenever a constant is written to but with inputs that cannot be evaluated + # statically, such as random_(), we invalidate all constants that alias the input + # We will rely on functionalization for use of fake tensors constants as persistent + # objects on an FX Graph. + + all_constant = all(e.constant is not None for e in flat_arg_fake_tensors) + if ( + isinstance(func, torch._ops.OpOverload) + and torch.Tag.nondeterministic_seeded not in func.tags + # We dispatch size/stride/numel on the FakeTensor not its constant, so bail on inplace_view. + # Example: fake_a.transpose_(0,1) would mutate fake_a.constant in-place, changing its + # shape from (2,3) to (3,2), while fake_a.shape still reports (2,3) → divergence. + # However, detach_ is safe: it only mutates requires_grad (not shape/stride/data), + # and constants are used purely for their values, not autograd. + and ( + torch.Tag.inplace_view not in func.tags or func is aten.detach_.default + ) + and all_constant + and len(flat_arg_fake_tensors) != 0 + and not has_symbolic_sizes + and not avoiding_device_init + and func is not aten._nested_tensor_from_tensor_list.default + ): + const_flat_args = [ + a.constant if self.is_our_fake(a) else a for a in flat_args + ] + const_args, const_kwargs = pytree.tree_unflatten(const_flat_args, args_spec) + + # NB: not in_kernel_invocation_manager(self) as we want to do REAL + # compute + with no_dispatch(): + out = func(*const_args, **const_kwargs) + + flat_out = pytree.tree_leaves(out) + flat_out_tensors = [t for t in flat_out if isinstance(t, Tensor)] + all_constant = all(self.may_turn_const(t) for t in flat_out_tensors) + + if all_constant: + return pytree.tree_map_only( + Tensor, + lambda t: converter.from_real_tensor(self, t, make_constant=True), + out, + ) + + # we weren't able to turn outputs to constants, + # so invalidate all constants that might be aliases of the outputs + for ten in flat_out_tensors: + converter.invalidate_constant_aliases(ten) + + # we are falling through to running non constant tensors, any input constant that + # is written to must be invalidated + args, kwargs = pytree.tree_unflatten(flat_args, args_spec) + + if ( + isinstance(func, torch._ops.HigherOrderOperator) + and func in registered_hop_fake_fns + ): + # Reenable the fake tensor mode for the registered fake function + maybe_ignore_fresh_unbacked_symbols = ( + contextlib.nullcontext + if self.shape_env is None + else self.shape_env.ignore_fresh_unbacked_symbols + ) + + with self, maybe_ignore_fresh_unbacked_symbols(): + return registered_hop_fake_fns[func](*args, **kwargs) + + self.invalidate_written_to_constants(func, flat_arg_fake_tensors, args, kwargs) + + def maybe_to_real_tensor( + t: T, + ) -> T | Tensor | torch._C.ScriptObject | None: + if isinstance(t, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + return t.real_tensor + elif isinstance(t, py_sym_types): + if self.shape_env is None: + raise AssertionError( + "self.shape_env must not be None for symbolic types" + ) + return t.node.pytype( + t.node.expr.xreplace(self.shape_env.backed_var_to_val).xreplace( + self.shape_env.real_tensor_prop_unbacked_vals + ) + ) + elif isinstance(t, FakeScriptObject): + return t.real_obj + else: + return t + + from torch.fx.experimental.symbolic_shapes import ( + compute_unbacked_bindings, + free_unbacked_symbols, + ) + + nil = object() + + real_out = nil + if ( + self.propagate_real_tensors + and all(e.real_tensor is not None for e in flat_arg_fake_tensors) + and not any( + ( + isinstance(a, py_sym_types) + and (syms := free_unbacked_symbols(a)) + and self.shape_env is not None + and any( + s not in self.shape_env.real_tensor_prop_unbacked_vals + for s in syms + ) + ) + for a in flat_args + ) + ): + log.debug("propagate_real_tensors %s", func) + real_flat_args = [maybe_to_real_tensor(a) for a in flat_args] + real_args, real_kwargs = pytree.tree_unflatten(real_flat_args, args_spec) + + is_builtin = library_utils.is_builtin(func) + if not is_builtin: + mutation_checker = library_utils.MutationChecker( + func, real_flat_args, args_spec + ) + + try: + real_out = func(*real_args, **real_kwargs) + except ZeroDivisionError as exc: + # we shouldn't broadly catch all errors here; + # some come from real-kernel mutation/aliasing checks we want to run. + # add more exception types as needed. + log.debug( + "real-tensor fallback failed for %s: %s; silently ignoring", + func, + exc, + ) + + if not is_builtin: + mutation_checker.check() # type: ignore[possibly-undefined] + library_utils.check_aliasing_constraint(func._name, flat_args, real_out) + + elif self.propagate_real_tensors: + # This can happen occasionally legitimately, specifically when you + # are inside the meta of a data dependent operation and you create + # a tensor on an unbacked SymInt; at this point in time we don't + # know what the unbacked SymInt is, but we will know later. + # However, if there's a bug in the condition above, this condition + # will also trigger. + log.debug( + "SKIPPED propagate_real_tensors %s(%s, %s) %s", + func, + flat_arg_fake_tensors, + flat_args, + self.shape_env.real_tensor_prop_unbacked_vals + if self.shape_env + else None, + ) + + def maybe_propagate_real_tensors(fake_out: T) -> T: + import sympy + + log.debug("maybe_propagate_real_tensors %s", func) + + def go(t: object, real_t: Tensor) -> None: + if isinstance(t, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + # NB: unconditionally overwrite + log.debug( + "maybe_propagate_real_tensors %s -> %s", id(t), id(real_t) + ) + t.real_tensor = real_t + for s, real_s in zip(t.size(), real_t.size()): + go(s, real_s) # type: ignore[arg-type] + for s, real_s in zip(t.stride(), real_t.stride()): + go(s, real_s) # type: ignore[arg-type] + go(t.storage_offset(), real_t.storage_offset()) # type: ignore[arg-type] + elif isinstance(t, py_sym_types) and free_unbacked_symbols(t): + if isinstance(t.node.expr, sympy.Symbol): + if self.shape_env is None: + raise AssertionError( + "self.shape_env must not be None for symbolic Symbol" + ) + self.shape_env.set_real_tensor_prop_unbacked_vals( + t.node.expr, real_t + ) + elif ( + isinstance(s := t.node.expr, sympy.Eq) + and isinstance(s.lhs, sympy.Symbol) + and s.rhs == 1 + ): + if self.shape_env is None: + raise AssertionError( + "self.shape_env must not be None for symbolic Eq" + ) + + self.shape_env.set_real_tensor_prop_unbacked_vals(s, real_t) + + if real_out is not nil: + # cross check fake/real outputs, and optionally override fake kernel mismatches + if not torch._functorch.config.generate_fake_kernels_from_real_mismatches: + self._maybe_infer_fake_kernel_from_pytree_out( + func, + (args, kwargs), + (real_args, real_kwargs), + fake_out, + real_out, + ) + else: + # this can override the output only when the flag is True + fake_out = self._maybe_infer_fake_kernel_from_pytree_out( # type: ignore[assignment] + func, + (args, kwargs), + (real_args, real_kwargs), + fake_out, + real_out, + ) + + # populate real_tensor_prop_unbacked_vals + if ( + not isinstance(fake_out, Tensor) + and not isinstance(real_out, Tensor) + and type(fake_out) is not type(real_out) + ): + # This can happen when decompositions have different return types, + # e.g. namedtuple vs. tuple vs. list. + tree_map_( + go, + tuple(pytree.tree_flatten(fake_out)), + tuple(pytree.tree_flatten(real_out)), + ) + else: + tree_map_(go, fake_out, real_out) + + # If a data-dependent op is used in a decomposition, we + # may need to get the unbacked settings "early" + # TODO: Is this really needed? + compute_unbacked_bindings(self.shape_env, fake_out, peek=True) + + return fake_out + + # Try for fastpath + if has_symbolic_sizes: + fast_impl = get_fast_op_impls().get(func) + if fast_impl is not None: + return maybe_propagate_real_tensors(fast_impl(self, *args, **kwargs)) + + if func is torch.ops.aten.to_dense.default: + # The registered fake op impl handles the usual path, but symbolic + # shapes can still reach generic decomposition below. The native + # composite sees a fake MKLDNN tensor's strided meta backing, so + # handle this before generic decomposition. + dtype = args[1] if len(args) > 1 else kwargs.get("dtype") + masked_grad = kwargs.get("masked_grad") + op_impl_out = maybe_to_dense_mkldnn( + self, args[0], dtype=dtype, masked_grad=masked_grad + ) + if op_impl_out is not NotImplemented: + return maybe_propagate_real_tensors(cast(FakeTensor, op_impl_out)) + + # If there's a Python meta, prefer that over the decomposition + from torch._decomp import meta_table + + if ( + func not in meta_table + and not self.cpp_meta_supports_symint(func) + and not ( + has_symbolic_sizes and func in self._unbacked_special_fake_handling_ops + ) + ): + from torch._decomp import decomposition_table + + # Prefer Python decompositions over C++ ones + if func in decomposition_table and ( + has_symbolic_sizes + or ( + # TODO: Remove these exclusions, so that we can remove + # this leg entirely + torch_decomp_decompositions(func) + and all(not is_sparse_any(e) for e in flat_arg_fake_tensors) + ) + ): + with self: + return maybe_propagate_real_tensors( + decomposition_table[func](*args, **kwargs) + ) + + with self: + # Decomposes CompositeImplicitAutograd ops + r = func.decompose(*args, **kwargs) + if r is not NotImplemented: + return maybe_propagate_real_tensors(r) + + # prims already wrap FakeTensor inputs to FakeTensor outputs + # and do device logic, we don't need do anything but run them + # and ensure that Meta kernels are dispatched to (see) + # Fake Tensor Dispatch Keys + # TODO - we should be use the prim aten impl + # TODO - fix prims complex ops + if ( + "prims::" in func._schema.name + and hasattr(func, "prim_meta_impl") + and not stride_incorrect_op(func) + ): + with self: + return maybe_propagate_real_tensors( + func.prim_meta_impl(*args, **kwargs) + ) + + profiles = torch._dynamo.config._custom_ops_profile + if profiles is not None: + if func in profiles.data: + return profiles.generic_fake_kernel(func, self, *args, **kwargs) + + if ( + self.propagate_real_tensors + and real_out is not nil + and not library_utils.is_builtin(func) + and self.shape_env is not None + ): + # Automatically infer a Fake kernel if there isn't one. + if not library_utils.has_fake_kernel(func): + result = inferred_fake_kernel_from_real_out(self, func, real_out) + + dtrace_structured( + "missing_fake_kernel", + metadata_fn=lambda: { + "op": str(func), + }, + ) + return maybe_propagate_real_tensors(result) + + # Users can register FakeTensor rules for custom operators + # Call them if they exist. + maybe_fake_impl = torch._library.simple_registry.singleton.find( + func.name() + ).fake_impl.kernel + if maybe_fake_impl: + try: + ctx = torch._library.fake_impl.FakeImplCtx(self, func) + with torch._library.fake_impl.set_ctx_getter(lambda: ctx), self: + result = maybe_fake_impl(*args, **kwargs) + return maybe_propagate_real_tensors(result) + + except MissingOpProfile as e: + # If we have a fake kernel registered generated from OpProfiles + # but there doesn't exist a profile for the existing inputs, and we are in + if ( + self.propagate_real_tensors + and real_out is not nil + and not library_utils.is_builtin(func) + and self.shape_env is not None + ): + result = inferred_fake_kernel_from_real_out(self, func, real_out) + + dtrace_structured( + "missing_fake_kernel", + metadata_fn=lambda: { + "op": str(func), + }, + ) + return maybe_propagate_real_tensors(result) + else: + raise e + + # special handling for funcs registered through `register_op_impl`, + # e.g., manipulating args on constructor calls to construct meta tensors + # and then afterwards wrapping them to a FakeTensor + for run_impl_check, op_impl in op_implementations_checks: + if run_impl_check(func): + # pyrefly: ignore [bad-argument-count] + op_impl_out = op_impl(self, func, *args, **kwargs) + if op_impl_out is not NotImplemented: + # pyrefly: ignore [bad-return] + return maybe_propagate_real_tensors(op_impl_out) + + def maybe_run_unsafe_fallback( + error: RuntimeError | None = None, + ) -> FakeTensor | None: + # We infer the meta of custom ops that return None to just + # return None, and Tag.out ops to return their out= args. + # Custom ops are not allowed to mutate metadata of their + # inputs, so this is safe. + if torch._library.utils.can_generate_trivial_fake_impl(func): + return torch._library.utils.generate_trivial_fake_impl( + func, *args, **kwargs + ) + # no meta kernel registered, fallback to kernel for the device + if has_symbolic_sizes or not self.can_run_unsafe_fallback(func): + raise UnsupportedOperatorException(func) + if error is None: + error = UnsupportedOperatorException(func) + return run_fallback_kernel(self, func, flat_args, args_spec, error) + + # Optimization: If there is no Meta kernel, it takes a surprisingly long + # amount of time to catch the NotImplementedError, so we check it here. + if not has_meta(func): + fallback = maybe_run_unsafe_fallback() + return maybe_propagate_real_tensors(fallback) + + # run kernel registered to meta for func, which include + # python meta registrations, prims, decomps, and c++ meta fns (structured kernels) + # It's possible that the kernel will return NotImplementedError + try: + with in_kernel_invocation_manager(self): + r = func(*args, **kwargs) + except NotImplementedError as not_implemented_error: + return maybe_run_unsafe_fallback(not_implemented_error) + except Exception: + log.exception("failed while attempting to run meta for %s", func) + raise + + return maybe_propagate_real_tensors( + self.wrap_meta_outputs_with_default_device_logic( + r, func, flat_args, device=kwargs.get("device") + ) + ) + + # WARNING: DO NOT add any additional namespaces/operators here if they refer to operators + # outside of the pytorch/pytorch library! Any pre-existing things here + # are either in the pytorch/pytorch library or have been grandfathered in. + # The fallback does not always work and MAY CRASH and emit unreadable error messages + # so it should not be allowed by default. + _can_run_unsafe_fallback_allowed_namespaces = ordered_set( + "debugprims", + "prims", + "aten", + "xla", + "vision", + "torchtext", + "torchaudio", + "quantized", + ) + + def can_run_unsafe_fallback(self, func: OpOverload) -> bool: + if not self.allow_fallback_kernels: + return False + # It's OK to try the fallback for built-in ops (e.g. aten, prims) + # because we control and test these but the fallback leads to unexpected behavior + # in user-defined custom ops + return ( + func.namespace in self._can_run_unsafe_fallback_allowed_namespaces + or func.name() == "fbgemm::gmm" + ) + + def validate_and_convert_non_fake_tensors( + self, + func: OpOverload, + converter: FakeTensorConverter, + flat_args: Sequence[object], + args_spec: TreeSpec, + ) -> tuple[list[object], list[FakeTensor]]: + """ + Checks if the list of tensors are fake tensors. + If not, try to convert them to fake tensors. + Returns the original args, kwargs, and a flattened list of (args, kwargs) that are fake tensors. + """ + flat_arg_fake_tensors: list[FakeTensor] = [] + + def validate(x: T) -> T | FakeTensor: + if not isinstance(x, Tensor): + return x + + nonlocal flat_arg_fake_tensors + if not self.is_our_fake(x): + if hasattr(func, "tags") and torch.Tag.inplace_view in func.tags: + args, kwargs = pytree.tree_unflatten(flat_args, args_spec) + raise AssertionError( + f"Can't call metadata mutating ops on non-Fake Tensor inputs. Found in {render_call(func, args, kwargs)}" + ) + allow_non_fake_inputs = ( + self.allow_non_fake_inputs + if fake_tensor_tls.allow_non_fake_inputs_override is None + else fake_tensor_tls.allow_non_fake_inputs_override + ) + if not allow_non_fake_inputs: + if isinstance(x, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + # pyrefly: ignore [missing-attribute] + x_fake_mode = x.fake_mode + if x_fake_mode is not self: + raise AssertionError( + f"Mixing fake modes NYI x.fake_mode={x_fake_mode} vs self={self}" + ) + args, kwargs = pytree.tree_unflatten(flat_args, args_spec) + raise AssertionError( + f"Please convert all Tensors to FakeTensors first or instantiate FakeTensorMode " + f"with 'allow_non_fake_inputs'. Found in {render_call(func, args, kwargs)}" + ) + + out = converter.from_real_tensor(self, x) + else: + out = x + + flat_arg_fake_tensors.append(out) + return out + + validated_args = [validate(a) for a in flat_args] + return validated_args, flat_arg_fake_tensors + + def wrap_meta_outputs_with_default_device_logic( + self, + r: object, + func: OpOverload, + flat_args: Sequence[object], + device: torch.device, + ) -> PyTree: + converter = self.fake_tensor_converter + + # Lazily initialized, in case there are no tensor returns + common_device = None + has_scalar_only_inputs = False + preserve_dispatch_keys = False + input_dispatch_keys = None + if ( + (func is aten.alias.default or func is aten.detach.default) + and len(flat_args) == 1 + and isinstance(flat_args[0], FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR + ): + input_dispatch_keys = flat_args[0].dispatch_keys + preserve_dispatch_keys = input_dispatch_keys is not None + + def wrap(e: T) -> T | FakeTensor: + nonlocal common_device + nonlocal has_scalar_only_inputs + + if not isinstance(e, Tensor): + return e + + if common_device is None: + ( + common_device, + has_scalar_only_inputs, + ) = FakeTensor._find_common_device(func, flat_args) + + is_our_fake = self.is_our_fake(e) + if is_our_fake: + torch._check( + e.device == common_device, + lambda: f"FakeTensor is wrapped to wrong device, found {e.device}, expected {common_device}", + ) + if preserve_dispatch_keys: + e.dispatch_keys = input_dispatch_keys + return cast(T, e) + elif converter is not None: + if has_scalar_only_inputs: + # Under FakeTensorMode, op accepts scalar only inputs, such as aten.add/sub/mul/div, + # returns a real scalar tensor on CPU. See TensorMeta() in _prims/__init__.py for details. + # We thus directly convert real tensor to fake tensor. + out = converter.from_real_tensor(self, e) + else: + out = converter.from_meta_and_device( + self, e, device or common_device + ) + if preserve_dispatch_keys: + out.dispatch_keys = input_dispatch_keys + return out + else: + # pyrefly: ignore [bad-return] + return e + + return tree_map(wrap, r) + + def create_symbolic_nested_int( + self, *, nt_tensor_id: int | None = None + ) -> IntLikeType: + # See Note: [Creating symbolic nested int] + # Returned nested int always has coeff=1; multiply the result by coeff if needed + import torch.nested._internal.nested_tensor + from torch.nested._internal.nested_int import NestedIntNode + + if nt_tensor_id is None: + nt_tensor_id = self.nt_tensor_id_counter + if not self.enter_stack: + raise AssertionError( + "should only be called while FakeTensorMode is active" + ) + self.nt_tensor_id_counter += 1 + hint = torch.SymInt(NestedIntNode(nt_tensor_id, 1)) + + src = torch._dynamo.source.EphemeralSource("intermediate_offsets_or_lengths") + if self.shape_env is None: + raise AssertionError("self.shape_env must not be None") + ret = self.shape_env.create_symintnode( + sym=self.shape_env.create_symbol( + val=hint, + source=src, + ), + hint=hint, + source=src, + ) + return ret + + _cpp_meta_supports_symint = ordered_set( + aten.empty.memory_format, + aten.empty_strided.default, + aten.as_strided_scatter.default, + aten.as_strided.default, + aten.as_strided_.default, + aten.zeros.default, + aten.detach.default, + aten.view_as_real.default, + aten.view_as_complex.default, + aten.set_.source_Storage_storage_offset, + aten._sparse_coo_tensor_with_dims_and_tensors.default, + aten.stack.default, + ) + + _unbacked_special_fake_handling_ops = ordered_set( + aten.view.default, + aten._unsafe_view.default, + aten.slice.Tensor, + ) + + def cpp_meta_supports_symint(self, func: OpOverload) -> bool: + if torch.Tag.view_copy in func.tags: + return True + return func in self._cpp_meta_supports_symint + + lift_fns = ordered_set(aten.lift_fresh.default, aten.lift_fresh_copy.default) + + def may_turn_const(self, t: Tensor) -> bool: + return ( + t.numel() <= CONSTANT_NUMEL_LIMIT + and not is_sparse_any(t) + and not self.is_our_fake(t) + and t.device.type != "meta" + ) + + def invalidate_written_to_constants( + self, + func: OpOverload, + flat_arg_fake_tensors: Sequence[FakeTensor], + args: Sequence[object], + kwargs: Mapping[str, object], + ) -> None: + any_constant = any(e.constant is not None for e in flat_arg_fake_tensors) + schema_info = get_schema_info(func) + if any_constant and schema_info.is_mutable(): + _, new_kwargs = normalize_function( # type: ignore[misc] + func, + args=args, # type: ignore[arg-type] + kwargs=kwargs, # type: ignore[arg-type] + normalize_to_only_use_kwargs=True, + ) + for k, v in new_kwargs.items(): + k = k if (k != "input" or schema_info.has_argument(k)) else "self" + if ( + self.is_our_fake(v) + and schema_info.is_mutable(k) + and v.constant is not None + ): + self.fake_tensor_converter.invalidate_constant_aliases(v.constant) + + def from_tensor( + self, + tensor: Tensor, + *, + static_shapes: bool | None = None, + source: Source | None = None, + symbolic_context: SymbolicContext | None = None, + trace: bool = True, + ) -> FakeTensor: + if ( + isinstance(tensor, FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR + and tensor.fake_mode is self + and static_shapes is None + and source is None + and symbolic_context is None + ): + return tensor + + shape_env: ShapeEnv | None = self.shape_env + if static_shapes is None: + static_shapes = self.static_shapes + if static_shapes: + if symbolic_context is not None: + raise AssertionError( + "cannot set both static_shapes and symbolic_context" + ) + shape_env = None + return self.fake_tensor_converter.from_real_tensor( + self, + tensor, + shape_env=shape_env, + source=source, + symbolic_context=symbolic_context, + trace=trace, + ) + + +_StoragePointer = object + + +def _validate_symbolic_output_for_caching( + state: _CacheKeyState, output: FakeTensor +) -> None: + """ + Validate symbolic content in output and raise _BypassDispatchCache if + caching should be bypassed. + + Args: + state: Cache key state containing known symbols + output: Output to validate + proxy_mode_active: Whether PROXY dispatch mode is currently active + + Raises: _BypassDispatchCache: If output contains symbolic content that + prevents caching + + Details: + + If our output contains any symbols that didn't appear in the input then we + need to bypass. Usually this will be unbacked symbols which can't be + properly reconstructed but there could be "weird" cases where backed symbols + spontaneously appear (from non-input state)? + + If we're proxy (symbol) tracing and the output contains ANY symbols then we + need to bypass. The problem is that ProxyTorchDispatchMode relies on SymNode + object identity and being able to see the construction of SymNodes. + + We could improve the proxy tracing case in a few ways: + + 1. If the output SymNodes are directly copied from inputs then this is + actually fine - they're already tracked. This would probably be the + biggest bang/buck. + + 2. If the output (tensors) are all direct copies of the inputs then this is + also fine - since they're inputs they must be tracked. We already compute + this we just don't plumb it around enough. + + 3. If the output SymNodes are already tracked by the proxy then this is also + actually fine - they're properly tracked. This probably wouldn't be + common since for most outputs we use torch.empty_strided() and recompute + strides. + + 4. We could use the proxy to track "how" the SymNodes were computed and when + using the cache we could "replay" them properly to teach the proxy how to + build them. + """ + from torch.fx.experimental.symbolic_shapes import _iterate_exprs, _iterate_nodes + + is_tracing = torch.fx.experimental.proxy_tensor.get_proxy_mode() is not None + if is_tracing: + # Check for SymNode types in PROXY mode - this should bypass caching + # regardless of whether symbols are known or not + for _ in _iterate_nodes(output): + raise _BypassDispatchCache("Proxy mode with SymNode output") + else: + # Check for unrepresented symbols in tensor expressions + for s in _iterate_exprs(output): + for symbol in s.free_symbols: + if symbol not in state.known_symbols: + raise _BypassDispatchCache("unrepresented symbol in output") + + +# NB: returns fake tensors +def run_fallback_kernel( + fake_mode: FakeTensorMode, + func: OpOverload, + flat_args: Sequence[object], + args_spec: PyTree, + orig_not_implemented_exception: RuntimeError, +) -> FakeTensor: + # these should all be supported, just to be safe + # avoid fallback for operators which inplace modify metadata + # because the input fake tensors would be umodified + if torch.Tag.inplace_view in func.tags: + raise orig_not_implemented_exception + + # pyrefly: ignore [implicit-any] + inp_impls = {} + + # Don't use in_kernel_invocation_manager(fake_mode) as we want to do + # REAL compute (not with meta device) + with no_dispatch(): + + def to_real_tensor(e: T) -> T | Tensor: + if fake_mode.is_our_fake(e): + out = torch.zeros_like(e, device=e.fake_device) + if e.is_sparse: + out._coalesced_(e.is_coalesced()) + inp_impls[id(out)] = e + return out + return e + + flat_args = [to_real_tensor(a) for a in flat_args] + args, kwargs = pytree.tree_unflatten(flat_args, args_spec) + + r = func(*args, **kwargs) + + storages: set[_StoragePointer] = set() + + for e in flat_args: + if isinstance(e, Tensor): + if not is_sparse_any(e): + storages.add(e._typed_storage()._cdata) + + # TODO: also check metadata change on inputs + # proper aliasing/metadata relationship between outputs and inputs will + # not be set up, bc of conversion to device, unless we can reuse an + # input impl + + def map_out(e: T) -> T | FakeTensor: + if id(e) not in inp_impls and ( + isinstance(e, Tensor) + and not is_sparse_any(e) + and e._typed_storage()._cdata in storages + ): + raise orig_not_implemented_exception + + if isinstance(e, Tensor): + if id(e) in inp_impls: + return inp_impls[id(e)] + else: + return fake_mode.fake_tensor_converter.from_real_tensor(fake_mode, e) + else: + return e + + return pytree.tree_map(map_out, r) + + +def _set_cache_key_for_shape_env( + cache: dict[_DispatchCacheKey, _DispatchCacheEntry], + key: _DispatchCacheKey, + entry: _DispatchCacheEntry, +) -> None: + key.strip_shape_env() + cache[key] = entry + + +def _set_cache_key( + cache: dict[_DispatchCacheKey, _DispatchCacheEntry], + key: _DispatchCacheKey, + entry: _DispatchCacheEntry, +) -> None: + cache[key] = entry + + +# Just for use to allow copying a module to fake tensors, +# does not apply elsewhere +class FakeCopyMode(TorchFunctionMode): + def __init__(self, fake_mode: FakeTensorMode) -> None: + self.fake_mode = fake_mode + + def __torch_function__( + self, + func: OpOverload, + types: Sequence[type], + args: Sequence[object] = (), + kwargs: Mapping[str, object] | None = None, + ) -> FakeTensor: + kwargs = kwargs if kwargs else {} + + # clone will get called in Parameter deepcopy + if func is torch._C.TensorBase.clone: + if not isinstance(args[0], Tensor): + raise AssertionError(f"Expected Tensor, got {type(args[0])}") + return func( + self.fake_mode.from_tensor(args[0], static_shapes=True), **kwargs + ) + elif func is Tensor.__deepcopy__: + if len(args) != 2 or len(kwargs) != 0: + raise AssertionError( + f"Expected 2 args and 0 kwargs for __deepcopy__, got {len(args)} args and {len(kwargs)} kwargs" + ) + tensor = cast(Tensor, args[0]) + memo = cast(dict[int, FakeTensor], args[1]) + + if id(tensor) in memo: + return memo[id(tensor)] + + out = self.fake_mode.from_tensor(tensor, static_shapes=True) + memo[id(tensor)] = out + return out + else: + with torch._C.DisableTorchFunctionSubclass(): + return func(*args, **kwargs) + + +def _device_handler(args: Sequence[object]) -> torch.device: + # NB: Don't use is_our_fake, just serve the fake information + # as is. Notice we don't use 'self'; we use args[0].fake_mode + # because they may not be the same. It would also be possible + # to return NotImplemented here, in which case the FakeTensor + # handler on args[0] would handle it, but we're being nice and + # short-circuiting quickly. + if len(args) != 1 or not isinstance(args[0], FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + raise AssertionError( + "Expected exactly one FakeTensor argument for _device_handler" + ) + if args[0].fake_mode.in_kernel_invocation: + return torch.device("meta") + else: + return args[0].fake_device + + +# [subclass inputs] +# Suppose we enable fake tensor mode. This means that fake tensor +# mode will run first. But what if we do an operation that +# involves a tensor subclass that will desugar into normal tensor +# operations? Without returning NotImplemented, fake tensor mode will run first, +# decide that a conversion was made (since there was a non fake +# tensor argument), and report an error that converting non +# fake tensor is not supported. What we actually wanted to happen +# was to give the subclass a chance to figure out what it wants to +# before erroring out. Returning NotImplemented here allows this. +def _check_for_subclass(flat_args: Sequence[object]) -> bool: + return any(_check_for_subclass_arg(x) for x in flat_args) + + +def _check_for_subclass_arg(x: object) -> bool: + if isinstance(x, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + return False + if not isinstance(x, Tensor): + return False + + x_type = type(x) + if x_type is Tensor: + return False + + # Use the concrete type instead of isinstance because wrapper subclasses + # marked as Parameters (e.g. Parameter(TwoTensor(...))) still need subclass + # dispatch. Only metadata-only Parameter subclasses that inherit Tensor's + # disabled __torch_dispatch__ can follow the regular Parameter path. + is_metadata_only_parameter_subclass = ( + issubclass(x_type, torch.nn.Parameter) + and x_type.__torch_dispatch__ is Tensor.__torch_dispatch__ + ) + if is_metadata_only_parameter_subclass: + return False + + return True + + +_DISPATCH_META_HANDLERS = { + torch.ops.prim.device.default: _device_handler, + torch.ops.aten.size.default: lambda args: tuple( + int(s) for s in cast(Tensor, args[0]).size() + ), + torch.ops.aten.stride.default: lambda args: tuple( + int(s) for s in cast(Tensor, args[0]).stride() + ), + torch.ops.aten.storage_offset.default: lambda args: int( + cast(Tensor, args[0]).storage_offset() + ), +} + +_DISPATCH_HANDLE_DIRECTLY = ordered_set( + torch.ops.aten.is_coalesced.default, + torch.ops.aten.dense_dim.default, + torch.ops.aten.sparse_dim.default, + # _RecordFunction doesn't support __eq__ so make sure not to attempt to + # cache it. + torch.ops.profiler._record_function_exit._RecordFunction, +) + +from torch._subclasses.fake_impls import ( # noqa: F401 + _device_not_kwarg_ops, + _is_tensor_constructor, + _like_tensor_constructors, + contains_tensor_types, + get_fast_op_impls, + has_meta, + maybe_to_dense_mkldnn, + op_implementations_checks, + stride_incorrect_op, +) + + +def evict_fake_tensor_cache_key(key: _DispatchCacheKey) -> None: + if key in FakeTensorMode.cache: + FakeTensorMode.cache.pop(key) + + +@atexit.register +def dump_cache_stats() -> None: + log.info("FakeTensor cache stats:") + log.info(" cache_hits: %s", FakeTensorMode.cache_hits) + log.info(" cache_misses: %s", FakeTensorMode.cache_misses) + bypasses = FakeTensorMode.cache_bypasses + if bypasses: + log.info(" cache_bypasses:") + width = max(len(k) for k in bypasses) + for k, v in sorted(bypasses.items(), key=lambda i: -i[1]): + log.info(" %-*s %s", width + 1, f"{k}:", v) + + +def _infer_fake_from_real_tensor( + mode: FakeTensorMode, op: torch._ops.OpOverload, real_out: torch.Tensor +) -> torch.Tensor: + def unsupported(reason: str) -> None: + raise RuntimeError( + f"propagate_real_tensors: we cannot infer a Fake kernel " + f"(meta kernel) for operator {op._name} because {reason}. " + f"Please use torch.library.register_fake to add a Fake kernel." + ) + + if real_out.storage_offset() != 0: + unsupported( + f"a return has a non-zero storage offset {real_out.storage_offset()}" + ) + + # Since PT2 is rank specialized, there's no such thing as a symbolic + # output rank. So we can assume the fake tensor has the same number of + # dimensions as the real tensor output. + # + # We shouldn't assume the Fake sizes/strides are exactly what we see on + # the real tensor output (perhaps we should give users a lever to toggle + # this). This is because there's a good amount of operators that return + # outputs with data-dependent output shape. + # So we infer the output sizes to all be unbacked symints + fake_shape = [ + torch._library.fake_impl.allocate_size(mode.shape_env) + for _ in range(real_out.dim()) + ] + + # We infer what the strides are. We had a couple of options for this: + # - assume the strides are computable from the sizes + # - use new fresh unbacked symints in the strides + # This doesn't work that well (PT2 doesn't support unbacked symint strides well) + # - use the real strides + # This can only be used if we assume the strides are static. + # We went with the first option. + fake_strides = [-1] * real_out.dim() + strides = [(s, idx) for idx, s in enumerate(real_out.stride())] + strides.sort(key=lambda x: (x[0], -x[1])) + expected = 1 + fake_stride = expected + for s, idx in strides: + if s != expected: + unsupported( + f"a return was not dense in memory (sizes {real_out.shape} strides {real_out.stride()})" + ) + fake_strides[idx] = fake_stride + expected = expected * real_out.shape[idx] + fake_stride = fake_stride * fake_shape[idx] + + with mode: + return torch.empty_strided( + fake_shape, + fake_strides, + device=real_out.device, + dtype=real_out.dtype, + layout=real_out.layout, + ) + + +def inferred_fake_kernel_from_real_out( + mode: FakeTensorMode, op: torch._ops.OpOverload, real_out: Any +) -> Any: + if mode.shape_env is None: + raise AssertionError("mode.shape_env must not be None") + + # Only support operators that have all Tensor outputs + # This is a general limitation on custom ops that we impose for PT2 + # to avoid baking non-symbolic float/int outputs into the graph. + real_flat_out, spec = pytree.tree_flatten(real_out) + if not all(isinstance(t, torch.Tensor) for t in real_flat_out): + raise RuntimeError( + f"propagate_real_tensors: we don't support operators that return " + f"non-Tensors. Got {op._schema}" + ) + + fake_flat_out = [_infer_fake_from_real_tensor(mode, op, t) for t in real_flat_out] + return pytree.tree_unflatten(fake_flat_out, spec) diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/fake_utils.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/fake_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6d8fe35b991208a455c2e49b53796154bfd33d1f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/fake_utils.py @@ -0,0 +1,331 @@ +from __future__ import annotations + +import functools +import warnings +from typing import Any, TYPE_CHECKING + +import torch +import torch.utils._pytree as pytree +from torch._subclasses.fake_tensor import ( + FakeTensor, + FakeTensorMode, + is_fake_tensor, + maybe_get_fake_mode, + MetadataMismatchError, + tree_flatten_only, + UnsupportedFakeTensorException, +) +from torch.utils._python_dispatch import TorchDispatchMode + + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping, Sequence + + from torch._ops import OpOverload + from torch.utils._pytree import PyTree + + +aten = torch._ops.ops.aten + + +def outputs_alias_inputs(outputs: PyTree, inputs: PyTree) -> bool: + input_storages = { + inp._typed_storage()._cdata + for inp in tree_flatten_only(torch.Tensor, inputs) + if torch._C._has_storage(inp) + } + return any( + torch._C._has_storage(out) and out._typed_storage()._cdata in input_storages + for out in tree_flatten_only(torch.Tensor, outputs) + ) + + +def outputs_are_inputs(outputs: PyTree, inputs: PyTree) -> bool: + input_ids = {id(inp) for inp in tree_flatten_only(torch.Tensor, inputs)} + return any(id(out) in input_ids for out in tree_flatten_only(torch.Tensor, outputs)) + + +def output_alias_each_other(outputs: PyTree) -> bool: + storages = set() + for out in tree_flatten_only(torch.Tensor, outputs): + if not torch._C._has_storage(out): + continue + stor = out._typed_storage()._cdata + if stor in storages: + return True + storages.add(stor) + return False + + +def _check_alias_info( + context: str, + real_out: PyTree, + real_in: PyTree, + fake_out: PyTree, + fake_in: PyTree, +) -> None: + r_aliasing = outputs_alias_inputs(real_out, real_in) + f_aliasing = outputs_alias_inputs(fake_out, fake_in) + if r_aliasing != f_aliasing: + raise MetadataMismatchError( + f"{context} mismatch in outputs_alias_inputs check {f_aliasing} != {r_aliasing}" + ) + + r_identity_eq = outputs_are_inputs(real_out, real_in) + f_identity_eq = outputs_are_inputs(fake_out, fake_in) + if r_identity_eq != f_identity_eq: + raise MetadataMismatchError( + f"{context} mismatch in outputs_are_inputs check {f_identity_eq} != {r_identity_eq}" + ) + + r_output_alias_each_other = output_alias_each_other(real_out) + f_output_alias_each_other = output_alias_each_other(fake_out) + if r_output_alias_each_other != f_output_alias_each_other: + raise MetadataMismatchError( + f"{context} mismatch in outputs_alias_each_other check " + f"{f_output_alias_each_other} != {r_output_alias_each_other}" + ) + + +def is_sdpa_error(func: OpOverload, idx: int, e: Exception) -> bool: + if ( + ( + func is aten._scaled_dot_product_flash_attention.default + or func is aten._flash_attention_forward.default + ) + and idx in (6, 7) + and "Devices" in repr(e) + ): + return True + if ( + ( + func is aten._scaled_dot_product_efficient_attention.default + or func is aten._efficient_attention_forward.default + ) + and idx in (2, 3) + and "Devices" in repr(e) + ): + return True + if ( + func is aten._scaled_dot_product_cudnn_attention.default + and idx in (6, 7) + and "Devices" in repr(e) + ): + return True + return False + + +def try_convert_fake_to_real( + ten_list: list[FakeTensor | Any], +) -> list[FakeTensor | torch.Tensor | Any]: + """ + Attempt to convert fake tensors to a corresponding real tensor with the correct underlying storage by looking up + the FakeTensorMode meta to real storage mapping. On failure to find the storage mapping, the FakeTensor will + remain in the list. + + Note: this is not currently optimized (makes copies of the meta converter internal dictionaries) + """ + + fake_tensor = next((item for item in ten_list if is_fake_tensor(item)), None) + if fake_tensor is None: + return ten_list + + fake_mode = maybe_get_fake_mode(fake_tensor) + if fake_mode is None: + return ten_list + meta_converter = fake_mode.fake_tensor_converter.meta_converter + desc = meta_converter.describer + + storage_to_key = {v: k for k, v in meta_converter.storage_memo.items()} + key_to_real_storage = {v: k for k, v in desc.lookup_storage.items()} + out = [] + for t in ten_list: + if not is_fake_tensor(t) or t.layout != torch.strided: + out.append(t) + continue + + key = storage_to_key.get(t.untyped_storage()) + real_storage = None if key is None else key_to_real_storage.get(key) + if real_storage is None: + out.append(t) + continue + + contains_unhinted = False + + def map_symint(s: torch.SymInt | int) -> int: + nonlocal contains_unhinted + if not isinstance(s, torch.SymInt): + return s + hint = s.hint + if hint is None: + contains_unhinted = True + return 0 # unused: caller bails (contains_unhinted) and discards this + return hint + + stor_offset = map_symint(t.storage_offset()) + size = [map_symint(s) for s in t.shape] + stride = [map_symint(s) for s in t.stride()] + + if contains_unhinted: + out.append(t) + continue + + new_tensor = torch.empty( + [], + dtype=t.dtype, + device=t.device, + ) + new_tensor.set_( + real_storage, + storage_offset=stor_offset, + size=size, + stride=stride, + ) + out.append(new_tensor.clone()) + + return out + + +def _check_fake_real_tensors( + real_out: torch.Tensor, + fake_out: FakeTensor, + context: str = "", + sizes: bool = True, + strides: bool = False, + storage_offset: bool = True, + requires_grad: bool = True, +) -> None: + if requires_grad: + if real_out.requires_grad != fake_out.requires_grad: + raise MetadataMismatchError( + f"{context} mismatched requires_grad-ness of outputs. " + f"This usually means that you have added autograd support " + f"for your operator at a dispatch key other than Autograd, " + f"which will lead to problems" + ) + + if torch._C._has_storage(real_out): + r_offset = real_out.storage_offset() + f_offset = fake_out.storage_offset() + if r_offset != f_offset: + raise MetadataMismatchError(f"{context} mismatched storage offset") + + torch._prims.utils.compare_tensor_meta( + real_out, + fake_out, + check_sizes=sizes, + check_strides=strides, + allow_rhs_unbacked=True, + ) + + +class CrossRefFakeMode(TorchDispatchMode): + def __init__( + self, + ignore_op_fn: Callable[[OpOverload], bool] | None = None, + *, + check_strides: bool = True, + check_aliasing: bool = True, + only_check_ops_with_meta: bool = True, + ) -> None: + super().__init__() + self.ignore_op_fn = ( + ignore_op_fn if ignore_op_fn is not None else lambda fn: False + ) + self.check_strides = check_strides + self.check_aliasing = check_aliasing + self.only_check_ops_with_meta = only_check_ops_with_meta + + def __torch_dispatch__( + self, + func: OpOverload, + types: Sequence[type], + args: Sequence[object] = (), + kwargs: Mapping[str, object] | None = None, + ) -> object: + kwargs = kwargs or {} + + fake_r = None + fake_args: Sequence[object] = () + fake_kwargs: Mapping[str, object] = {} + + # empty_like excluded for now due to sparse complex + # aten._to_dense.default this one is getting called with csc + if ( + func + not in ( + aten.lift_fresh.default, + aten.lift_fresh_copy.default, + aten.set_.source_Storage_storage_offset, + ) + and not self.ignore_op_fn(func) + and ( + not self.only_check_ops_with_meta + or torch._subclasses.fake_impls.has_meta(func) + ) + and torch.Tag.dynamic_output_shape not in func.tags + and torch.Tag.inplace_view not in func.tags + and torch.Tag.data_dependent_output not in func.tags + ): + # Do not import symbolic_shapes at the top of the module as it imports sympy and that's slow + from torch.fx.experimental.symbolic_shapes import ShapeEnv + + try: + # TODO: enable_python_dispatcher() here + with FakeTensorMode(shape_env=ShapeEnv()) as fake_mode: + fake_args, fake_kwargs = pytree.tree_map_only( + torch.Tensor, + functools.partial(fake_mode.from_tensor, static_shapes=True), + (args, kwargs), + ) + with warnings.catch_warnings(): + fake_r = func(*fake_args, **fake_kwargs) + except UnsupportedFakeTensorException: + pass + + context = ( + f"When comparing the output of {func} on FakeTensor and concrete Tensors, " + f"found" + ) + r = func(*args, **kwargs) + if fake_r is not None: + r_flat = pytree.tree_leaves(r) + f_flat = pytree.tree_leaves(fake_r) + if len(f_flat) != len(r_flat): + raise AssertionError( + f"{context} mismatch in number of returns {len(f_flat)} != {len(r_flat)}" + ) + + if self.check_aliasing: + _check_alias_info( + context, r, (args, kwargs), fake_r, (fake_args, fake_kwargs) + ) + + for idx, (r_out, f_out) in enumerate( + zip(pytree.tree_leaves(r), pytree.tree_leaves(fake_r)) + ): + r_is_ten = isinstance(r_out, torch.Tensor) + if r_is_ten != isinstance(f_out, torch.Tensor): + raise AssertionError( + f"{context} mismatched number of tensor outputs" + ) + if r_is_ten: + try: + _check_fake_real_tensors( + r_out, + f_out, + sizes=True, + strides=self.check_strides, + storage_offset=True, + requires_grad=True, + ) + except Exception as e: + if is_sdpa_error(func, idx, e): + continue + error_message = ( + f"{context} mismatched tensor metadata: {e}" + if len(r_flat) == 1 + else f"{context} mismatched tensor metadata for output[{idx}]: {e}" + ) + raise MetadataMismatchError(error_message) from e + return r diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/functional_tensor.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/functional_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..fc90a261d072feff9852acbf5168ee7c0da4f708 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/functional_tensor.py @@ -0,0 +1,999 @@ +from __future__ import annotations + +import contextlib +import functools +import warnings +import weakref +from abc import ABC, abstractmethod +from contextlib import AbstractContextManager +from typing import Any, cast, TYPE_CHECKING +from typing_extensions import Self + + +if TYPE_CHECKING: + import builtins + from collections.abc import Callable, Generator, Sequence + from types import TracebackType + + from torch._functorch.pyfunctorch import FunctionalizeInterpreter + from torch._ops import OpOverload + +import torch +import torch.fx.traceback as fx_traceback +import torch.utils._pytree as pytree +from torch._C import _functionalization_reapply_views_tls as _reapply_views +from torch._ops import _get_dispatch_mode_pre_dispatch, TorchBindOpOverload +from torch._subclasses.meta_utils import is_sparse_any +from torch.utils._python_dispatch import ( + _detect_infra_mode, + _disable_infra_mode, + autograd_would_have_decomposed, + return_and_correct_aliasing, + TorchDispatchMode, +) + + +not_implemented_log = torch._logging.getArtifactLogger(__name__, "not_implemented") + + +def _has_unrecognized_tensor_types(types: Sequence[type]) -> bool: + unrecognized_types = [ + t + for t in types + if t not in (torch.Tensor, torch._subclasses.FakeTensor, FunctionalTensor) + ] + if unrecognized_types: + not_implemented_log.debug( + "FunctionalTensor unrecognized subclass(es): %s", unrecognized_types + ) + return bool(unrecognized_types) + + +@functools.lru_cache(maxsize=512) +def _can_decompose_fast( + func: OpOverload, export: bool, pre_dispatch: bool +) -> bool | None: + """Fast path for _can_decompose that depends only on (func, export, pre_dispatch). + + Returns True/False for a definitive answer, or None to fall through + to the slow path (autograd_would_have_decomposed). + """ + if export and func is torch.ops.aten.dropout.default: + return False + + from torch._decomp import _should_decompose_because_unsafe_op + + if _should_decompose_because_unsafe_op(func): + return True + + alias_info_present = any(arg.alias_info for arg in func._schema.arguments) + if alias_info_present or func._schema.is_mutable: + return True + + if export: + if pre_dispatch: + if func.namespace not in ("aten", "prim") and func._can_decompose(): + warnings.warn( + f"At pre-dispatch tracing, we assume that any custom op marked with " + f"CompositeImplicitAutograd and have functional schema are safe to not decompose. " + f"Found {func} to be one such op.", + stacklevel=3, + ) + return False + return True + + return None + + +def _assert_functionalize_not_active(msg: str) -> None: + is_included = torch._C._dispatch_tls_is_dispatch_key_included( + torch._C.DispatchKey.Functionalize + ) + is_excluded = torch._C._dispatch_tls_is_dispatch_key_excluded( + torch._C.DispatchKey.Functionalize + ) + if not is_excluded and is_included: + raise AssertionError(msg) + + +# NOTE Some special handling for tensor conversion during export is needed. +# Normally, when tracing through the model with tensor.to(), the maybe-aliasing +# relationship between input and output tensors will be baked into the graph. +# For example, if we got a tensor with device cpu and call tensor.to("cpu"), +# it will become a no-op in the graph. For a whole graph capture, this is not +# sound so we need to do something different. Instead, in export we will try to +# preserve the tensor conversion by forcing a non-semantic-breaking aten::_to_copy +# operator to be traced in the graph, and subsequently banning mutations on all +# such converted tensors. +# In addition to patching .to() method call in functionalization, we will have to +# patch other similar methods like float() and cpu(), because they intentionally +# don't fall back to .to() methods, but have the same behavior as .to() according to +# pytorch document. https://pytorch.org/docs/stable/generated/torch.Tensor.float.html +# thus we simply force them to go through .to() call. +def _conversion_method_template(**extra_kwargs: Any) -> Callable[..., Any]: + def _(self: FunctionalTensor, *args: Any, **kwargs: Any) -> Any: + return self.to(*args, **{**kwargs, **extra_kwargs}) + + return _ + + +class FunctionalTensor(torch.Tensor): + """ + Functional tensors represent tensors that will remove mutations + from a program. If you perform a mutable operation on a functional tensor, + it will re-dispatch to the functional variant of that operation. + + Historically, functionalization is implemented in C++ in the dispatcher. + This class is a lightweight python shim around the C++ functionalization logic. + + FunctionalTensor is required to be used with a corresponding + FunctionalTensorMode active, because it relies + on using the mode for dispatch (which can properly handle factory functions). + """ + + elem: torch.Tensor + # Indicates to our torch_dispatch dispatching infra that + # this is an "infra" mode with lower dispatching precedence. + _mode_key = torch._C._TorchDispatchModeKey.FUNCTIONAL + + # Note: The reason we add these extra keys to our FunctionalTensor subclass + # is to mirror the behavior of C++ functionalization (we can choose to change this + # later, as long as it doesn't break anything). + # FunctionalTensorWrapper copies **all** dispatch keys from the inner tensor + # to the wrapper, excluding functorch and python dispatch keys. + # Here I'm trying to reuse the keyset the functorch wrapper subclasses copy, + # except that they don't include ZeroTensor so I'm manually adding it in. + _extra_dispatch_keys = torch._C._additional_keys_to_prop_for_wrapper_tensors.add( + torch._C.DispatchKey.ZeroTensor + ) + + # These are all aten ops that correspond to metadata queries. + # We want FunctionalTensor to be able to handle them directly. + metadata_fns = frozenset( + { + torch.ops.aten.is_contiguous.default, + torch.ops.aten.is_contiguous.memory_format, + torch.ops.aten.is_strides_like_format.default, + torch.ops.aten.is_non_overlapping_and_dense.default, + torch.ops.aten.size.default, + torch.ops.aten.sym_size.default, + torch.ops.aten.stride.default, + torch.ops.aten.sym_stride.default, + torch.ops.aten.storage_offset.default, + torch.ops.aten.sym_storage_offset.default, + torch.ops.aten.numel.default, + torch.ops.aten.sym_numel.default, + torch.ops.aten.dim.default, + torch.ops.prim.device.default, + } + ) + + # Used by auto_functionalize to determine base of tensors during inference mode. + _inference_mode_base: FunctionalTensor | None = None + + def __new__(cls, elem: torch.Tensor, mode: FunctionalTensorMode) -> Self: + if not torch._is_functional_tensor(elem): + raise AssertionError("elem must be a functional tensor") + + # In general, we'd like our functional tensor subclass to only be in charge of functionalization, + # and defer to the inner subclass for all other functionality. + # Example: If our inner tensor is a ZeroTensor, we would want to defer running the ZeroTensor fallback + # until after we redispatch to our inner ZeroTensor. + # However, there are a few keys that we need to mirror between the inner and outer tensors. + # Conjugate + # Negative + # Why? These keys are used to test metadata queries, like `.is_conj()` and `.is_neg()`. + # We **need** calls to is_conj() to return the same thing on the outer and inner tensors, + # Because user code / framework code that branches like so needs to do the same thing + # when it sees the outer FunctionalTensor: + # if (x.is_conj()) { + # return at::view_as_real(x.resolve_conj()); + # } else { + # return at::view_as_real(x); + # } + extra_dispatch_keys = ( + FunctionalTensor._extra_dispatch_keys & torch._C._dispatch_keys(elem) + ) + + out = torch.Tensor._make_wrapper_subclass( + # TODO: right now, _make_wrapper_subclass's dynamic shape interaction is not great. + # Calling the overload that has kwargs causes us to go down the first overload path, + # which will **always** specialize sizes. + # We should probably eventually fix this so that the first overload can just handle dynamic shapes. + cls, + elem.shape, # sizes + elem.stride() if not is_sparse_any(elem) else None, # strides + ( + elem.storage_offset() if not is_sparse_any(elem) else None + ), # storage_offset + None, # memory_format + elem.dtype, # dtype + elem.layout, # layout + elem.device, # device + False, # pin_memory + elem.requires_grad, # requires_grad + None, # dispatch_sizes_strides_policy + False, # dispatch_device + False, # dispatch_layout + extra_dispatch_keys, # _extra_dispatch_keys + ) + torch._C._set_throw_on_mutable_data_ptr(out) + out.elem = elem + + if ( + torch._export.config.enable_auto_functionalized_v2_for_export + and torch.is_inference_mode_enabled() + and torch._inductor.config.enable_auto_functionalized_v2 + ): + storage = out.elem.untyped_storage() + if out.is_base_tensor(): + out._inference_mode_base = None + # This assumes that the FunctionalTensor.elem does not change its storage after this point. + # Otherwise this would be invalid. + mode._storage_to_base[storage] = out + else: + out._inference_mode_base = mode._storage_to_base.get(storage) + if out._inference_mode_base is None: + mode._storage_to_base[storage] = out + return out + + def __torch_dispatch__( # type: ignore[override] + self, + func: OpOverload, + types: Sequence[type], + args: tuple[Any, ...] = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + if _has_unrecognized_tensor_types(types): + return NotImplemented + + if kwargs is None: + kwargs = {} + # FunctionalTensor needs to plumb all metadata requests to the inner tensor. + # In theory we don't have to do this - but if we want to service metadata requests here, + # we need to carefully make sure all metadata is accurate (including metadata mutations) + if func in FunctionalTensor.metadata_fns: + # All metadata accesses should be plumbed to the inner tensor, that way we don't have to worry + # about the problem of keeping metadata in sync between the wrapper and inner tensor. + # This also alleviates us from having to manually handle metadata mutations on the wrapper. + if len(kwargs) != 0: + raise AssertionError("kwargs must be empty for metadata functions") + if func in [ + torch.ops.aten.is_strides_like_format.default, + torch.ops.aten.is_contiguous.memory_format, + ]: + if len(args) != 2 or not isinstance(args[0], FunctionalTensor): + raise AssertionError("Expected 2 args with FunctionalTensor first") + return func(torch._from_functional_tensor(args[0].elem), args[1]) + if len(args) != 1 or not isinstance(args[0], FunctionalTensor): + raise AssertionError("Expected 1 arg with FunctionalTensor") + + return func(torch._from_functional_tensor(args[0].elem)) + if func is torch.ops.aten.detach.default: + # detach can reach this dispatch when no FunctionalTensorMode is active + # (e.g. snapshot_fake under ProxyTorchDispatchMode). Returning self is safe: + # autograd has already run above this layer, so detach has no effect here, + # and we must avoid falling through to the "on its own" RuntimeError below. + if len(args) == 1 and isinstance(args[0], FunctionalTensor): + return args[0] + # Originally I tried to implement my subclass without giving it a torch_dispatch, but I gave up: + # - _make_wrapper_subclass requires a __torch_dispatch__ + # - If we want to use _make_subclass(), we have a problem: the subclass will share a TensorImpl with the inner tensor, + # which is of type FunctionalTensorWrapper! We explicitly do not want our wrapper to be a FunctionalTensorWrapper. + # - If we use the default tensor.__new__(), we have another problem: it returns inner_tensor.alias(), + # which causes every subclass created above autograd to have autograd view metadata + # (in addition to also being a FunctionalTensorWrapper). + raise RuntimeError( + "Attempting to use FunctionalTensor on its own. Instead, please use it with a corresponding FunctionalTensorMode()" + ) + + def __repr__(self, *, tensor_contents: object | None = None) -> str: + return f"FunctionalTensor({repr(self.elem)})" + + @staticmethod + def to_functional(x: torch.Tensor) -> FunctionalTensor: + # We will do the wrapping for the user. + + if torch._is_functional_tensor(x): + raise AssertionError("x must not already be a functional tensor") + # The only autograd metadata we care about on the FunctionalTensor is: + # - requires_grad (so autograd runs) + # - is_leaf (so that mutations on graph inputs that are not leaves are allowed by the autograd engine) + # this is handled by FunctionalTensor.to_functional + x_functional = torch._to_functional_tensor(x) + # Technically the FunctionalTensormode here is unnecessary, + # but it avoids spurious NotImplemented logs during `ProxyTorchDispatchMode` tracing. + # _mirror_autograd_meta_to queries tensor sizes, + # and otherwise the sym_size() call will go to the proxy mode before hitting + # FunctionalTensor.__torch_dispatch__ + + functional_mode = _detect_infra_mode(torch._C._TorchDispatchModeKey.FUNCTIONAL) + if functional_mode is None: + raise AssertionError("functional_mode must not be None") + + with functional_mode: + torch._mirror_autograd_meta_to(x, x_functional) # type: ignore[attr-defined] + out = FunctionalTensor(x_functional, functional_mode) + torch._mirror_autograd_meta_to(x_functional, out) # type: ignore[attr-defined] + return out + + def from_functional(self) -> torch.Tensor: + torch._sync(self) + return torch._from_functional_tensor(self.elem) + + def is_base_tensor(self) -> bool: + return torch._is_functional_tensor_base(self.elem) + + def replace_(self, output: torch.Tensor) -> None: + torch._functionalize_replace(self.elem, output) + + def commit_update(self) -> None: + torch._functionalize_commit_update(self.elem) + + def sync(self) -> None: + torch._functionalize_sync(self.elem) + + def mark_mutation_hidden_from_autograd(self) -> None: + torch._functionalize_mark_mutation_hidden_from_autograd(self.elem) + + def tolist(self) -> Any: + if self.elem.dim() == 0: + return self.elem.item() + elif self.elem.dim() == 1: + return [elem.item() for elem in self.elem] + else: + return [elem.tolist() for elem in self.elem] + + def to(self, *args: Any, **kwargs: Any) -> torch.Tensor: + if _detect_infra_mode(torch._C._TorchDispatchModeKey.FUNCTIONAL).export: + torch.ops.aten._assert_tensor_metadata( + self, + dtype=self.dtype, + device=self.device, + layout=self.layout, + ) + return super().to(*args, **kwargs) + + # pyrefly: ignore[bad-override] + def cuda( + self, device: torch.device | int | str | None = None, *args: Any, **kwargs: Any + ) -> torch.Tensor: + device = device or torch.cuda.current_device() + if len(args) > 0: + return self.to(device, *args, **kwargs) + else: + return self.to(device=device, **kwargs) + + char = _conversion_method_template(dtype=torch.int8) + cpu = _conversion_method_template(device=torch.device("cpu")) + bfloat16 = _conversion_method_template(dtype=torch.bfloat16) + byte = _conversion_method_template(dtype=torch.uint8) + double = _conversion_method_template(dtype=torch.float64) + float = _conversion_method_template(dtype=torch.float32) + bool = _conversion_method_template(dtype=torch.bool) + half = _conversion_method_template(dtype=torch.float16) + int = _conversion_method_template(dtype=torch.int32) + long = _conversion_method_template(dtype=torch.int64) + + # TODO(sparse-team): fixes #133174 but can we do without the relay? + def to_dense( + self, + dtype: torch.dtype | None = None, + *, + masked_grad: builtins.bool | None = None, + ) -> torch.Tensor: + if self.layout == torch.strided: + return self.to(dtype=dtype) if dtype is not None else self + + inner = torch._from_functional_tensor(self.elem) + if not torch._subclasses.fake_tensor.is_fake_tensor(inner): + out = self.elem.to_dense(dtype=dtype, masked_grad=masked_grad) + if isinstance(out, torch.Tensor) and torch._is_functional_tensor(out): + functional_mode = _detect_infra_mode( + torch._C._TorchDispatchModeKey.FUNCTIONAL + ) + if functional_mode is None: + raise AssertionError("functional_mode must not be None") + with functional_mode: + return FunctionalTensor(out, functional_mode) + return out + + return torch.ops.aten.to_dense.default( + self, dtype=dtype, masked_grad=masked_grad + ) + + @property + # pyrefly: ignore[bad-override] + def is_mkldnn(self) -> builtins.bool: + return torch._from_functional_tensor(self.elem).is_mkldnn + + @property + # pyrefly: ignore[bad-override] + def layout(self) -> torch.layout: + return torch._from_functional_tensor(self.elem).layout + + def __bool__(self) -> builtins.bool: + return bool(self.item()) + + +class FunctionalTensorMode(TorchDispatchMode): + def __init__( + self, + pre_dispatch: bool = False, + export: bool = False, + _allow_token_discovery: bool = False, + _keep_input_mutations: bool = True, + ) -> None: + super().__init__() + self.export = export + self.is_on_stack = False + self.enter_stack = [] + # Indicates to our torch_dispatch dispatching infra that + # this is an "infra" mode with lower dispatching precedence. + self._mode_key = torch._C._TorchDispatchModeKey.FUNCTIONAL + self.pre_dispatch = pre_dispatch + # This will be turned off later for pre-dispatch functionalization + self._dispatch_key = torch._C.DispatchKey.PreDispatch if pre_dispatch else None # type: ignore[attr-defined] + # Map of effect type (ex. _EffectType.ORDERED) to a token. The tokens help keep + # track of the ordering between side effectful operations. + self._tokens: dict[Any, torch.Tensor] = {} + + # Filled after forward tracing. + self._tokens_forward_output: dict[Any, torch.Tensor] = {} + + # Functionalization runs twice in AOTAutograd, once in + # `run_functionalized_fw_and_collect_metadata` to collect metadata to + # see which tensors need to be functionalized and discover how many + # tokens we need, and another time in `make_fx` which does the actual + # tracing to replace ops with their functional variants and handling + # side-effectful ops. In the second stage there should be no token + # discovery. This flag distinguishes between the two stages. + self._allow_token_discovery = _allow_token_discovery + # Controls whether invoke_subgraph keeps input mutations in its graph. + self._keep_input_mutations = _keep_input_mutations + + self._storage_to_base: weakref.WeakKeyDictionary[ + torch.storage.UntypedStorage, FunctionalTensor | None + ] = weakref.WeakKeyDictionary() + + # No-op if FunctionalTensorMode is already in use + def __enter__(self) -> Self: + def _get_prev_mode() -> FunctionalTensorMode | None: + if self._dispatch_key == torch._C.DispatchKey.PreDispatch: + return _get_dispatch_mode_pre_dispatch( + torch._C._TorchDispatchModeKey.FUNCTIONAL + ) + return cast( + "FunctionalTensorMode | None", + torch._C._get_dispatch_mode(torch._C._TorchDispatchModeKey.FUNCTIONAL), + ) + + if _get_prev_mode() is None: + self.enter_stack.append(True) + return super().__enter__() + else: + self.enter_stack.append(False) + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + is_on_stack = self.enter_stack.pop() + if is_on_stack: + super().__exit__(exc_type, exc_val, exc_tb) + + def __torch_dispatch__( + self, + func: OpOverload, + types: Sequence[type], + args: tuple[Any, ...] = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + if kwargs is None: + kwargs = {} + + if _has_unrecognized_tensor_types(types): + return NotImplemented + + if ( + func not in FunctionalTensor.metadata_fns + and self._can_decompose(func, args, kwargs) + # Not all funcs from __torch_dispatch__ are actual dispatcher ops, + # e.g. prim.device + and torch._C._dispatch_has_kernel(func.name()) + ): + with self: + r = func.decompose(*args, **kwargs) + if r is not NotImplemented: + return r + + def wrap(x: object) -> object: + # Only wrap our outputs in subclasses if the inner functionalization call + # also wrapped outputs into FunctionalTensorWrappers. + # When can this happen? e.g. `torch.div(2, 2)` + if isinstance(x, FunctionalTensor): + raise AssertionError("x must not be a FunctionalTensor in wrap()") + if isinstance(x, torch.Tensor) and torch._is_functional_tensor(x): + return FunctionalTensor(x, self) + return x + + def unwrap(x: FunctionalTensor) -> torch.Tensor: + return x.elem + + from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize, + do_auto_functionalize_v2, + ) + + if can_auto_functionalize( + func + ) and not torch._C._dispatch_has_kernel_for_dispatch_key( + func.name(), torch._C.DispatchKey.Functionalize + ): + import torch._export.config as export_config + import torch._inductor.config as inductor_config + + if torch.compiler.is_exporting(): + # NB: out= ops are not yet handled here; they only go through v2 below. + if export_config.enable_auto_functionalized_v2_for_export: + return do_auto_functionalize_v2(self, func, args, kwargs) + + return do_auto_functionalize(self, func, args, kwargs) + + if inductor_config.enable_auto_functionalized_v2 or ( + isinstance(func, torch._ops.OpOverload) + and ( + torch._library.utils.is_out(func) + or torch._library.utils.is_inplace(func) + ) + ): + return do_auto_functionalize_v2(self, func, args, kwargs) + return do_auto_functionalize(self, func, args, kwargs) + + from torch._higher_order_ops.effects import handle_effects, has_effects + + if has_effects(func): + if torch._C._dispatch_has_kernel_for_dispatch_key( + func.name(), torch._C.DispatchKey.Functionalize + ): + raise AssertionError( + f"func {func.name()} with effects should not have a kernel for Functionalize dispatch key" + ) + return handle_effects( + self._allow_token_discovery, self._tokens, func, args, kwargs + ) + + args_unwrapped, kwargs_unwrapped = pytree.tree_map_only( + FunctionalTensor, unwrap, (args, kwargs) + ) + + # Expectation: functionalization should not **already** be enabled above our mode. + # Why would that be bad? when we return a FunctionalTensor here, we don't want functionalization + # to run above this mode and further wrap that output in **another** C++ FunctionalTensorWrapper. + _assert_functionalize_not_active( + "Functionalization should not already be enabled above this mode" + ) + include_to_set = ( + torch._C._dispatch_tls_local_include_set() + | torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize) + ) + exclude_to_set = ( + torch._C._dispatch_tls_local_exclude_set().remove( + torch._C.DispatchKey.Functionalize + ) + - FunctionalTensor._extra_dispatch_keys + ) + + if isinstance(func, TorchBindOpOverload): + # When the function is a TorchBindOpOverload, meaning some of the + # inputs are FakeScriptObjects, we need to skip c++ dispatcher and + # dispatch in python because C++ dispatcher will check the schema + # and cannot recognize FakeScriptObject. + ctx = PythonFunctionalizeAPI() + fully_unwrapped_args = ctx.unwrap_tensors(args) + fully_unwrapped_kwargs = ctx.unwrap_tensors( + kwargs # pyrefly: ignore[bad-argument-type] + ) + outs_unwrapped = func( + *fully_unwrapped_args, + **fully_unwrapped_kwargs, + ) + outs_wrapped = ctx.wrap_tensors(outs_unwrapped) + else: + # All we want to do here is reuse the existing C++ functionalization logic. + # This requires swizzling our TLS dispatch keys so that the Functionalize key is active. + with torch._C._ForceDispatchKeyGuard(include_to_set, exclude_to_set): + try: + # By default for python functionalization (for AOTAutograd), we reapply views. + old_apply_views = torch._functionalize_enable_reapply_views(True) # type: ignore[attr-defined] + + # Sometimes these functions cannot be directly dispatched to functionalize key + # because args are sometimes not functional tensors for some reason? + if func in FunctionalTensor.metadata_fns: + # With dynamic shapes, metadata ops (e.g. aten.sym_size) + # on the unwrapped inner tensor re-enter Python dispatch + # because symbolic sizes require Python-side evaluation. + # The inner tensors don't have proxy slots (only the outer + # FunctionalTensor does), so ProxyTorchDispatchMode would + # store them as spurious graph constants. The metadata op + # was already recorded on the FunctionalTensor by the proxy + # mode above us, so we disable proxy tracing here. + with torch.fx.experimental.proxy_tensor.disable_proxy_modes_tracing(): + outs_unwrapped = func(*args_unwrapped, **kwargs_unwrapped) + outs_wrapped = pytree.tree_map_only( + torch.Tensor, wrap, outs_unwrapped + ) + else: + self._sync_view_replay_annotations(args, kwargs) + + # When we dispatch to the C++ functionalization kernel, we might need to jump back to the + # PreDispatch mode stack afterwards, to handle any other PreDispatch modes underneath + # FunctionalTensorMode. If we call func() directly, we would need to exclude PreDispatch + # from the TLS in order to avoid infinite looping, but this would prevent us from coming + # back to PreDispatch later + outs_unwrapped = func._op_dk( + torch._C.DispatchKey.Functionalize, + *args_unwrapped, + **kwargs_unwrapped, + ) + + if self.export: + if func is torch.ops.aten.dropout.default: + torch._freeze_functional_tensor(outs_unwrapped) # type: ignore[attr-defined] + outs_wrapped = pytree.tree_map_only( + torch.Tensor, wrap, outs_unwrapped + ) + finally: + torch._disable_functionalization() + torch._functionalize_enable_reapply_views(old_apply_views) # type: ignore[attr-defined] + + _assert_functionalize_not_active( + "Functionalization should not already be enabled above this mode after dispatch" + ) + + if ( + ( + func is torch.ops.aten.alias.default + or func is torch.ops.aten.detach.default + ) + and len(args) == 1 + and isinstance(args[0], FunctionalTensor) + ): + input_unwrapped = torch._from_functional_tensor(args[0].elem) + if ( + isinstance( # noqa: ISINSTANCE_FAKE_TENSOR + input_unwrapped, torch._subclasses.FakeTensor + ) + and input_unwrapped.dispatch_keys is not None + ): + input_dispatch_keys = input_unwrapped.dispatch_keys + + def preserve_dispatch_keys(out: object) -> None: + if isinstance(out, FunctionalTensor): + unwrapped = torch._from_functional_tensor(out.elem) + if isinstance( # noqa: ISINSTANCE_FAKE_TENSOR + unwrapped, torch._subclasses.FakeTensor + ): + unwrapped.dispatch_keys = input_dispatch_keys + + pytree.tree_map_(preserve_dispatch_keys, outs_wrapped) + + if ( + # If no outputs are our functional subclass, then don't try to fix up aliasing + not any( + isinstance(x, FunctionalTensor) + for x in pytree.tree_leaves(outs_wrapped) + ) + # Since lift_fresh lifts its argument into a functional tensor, we can skip the + # aliasing correction step. Otherwise, we would be setting the storage of a + # lifted tensor to that of an unlifted tensor. + # Ref: https://github.com/pytorch/pytorch/issues/111506 + or func is torch.ops.aten.lift_fresh.default + ): + return outs_wrapped + # for metadata mutations, need to manually mutate the metadata of the FunctionalTensor wrapper + if ( + torch.Tag.inplace_view in func.tags + and func is not torch.ops.aten.set_.source_Tensor + ): + with torch.utils._mode_utils.no_dispatch(): + func(*args, **kwargs) + # Wrapper tensor subclasses do not have correct aliasing info! Use this util to manually correct the output aliasing. + # inplace ops like `aten.add_()` are expected to return inputs **directly**, instead of creating fresh tensor objects. + # Use this util to figure out the right thing to return. + # If none of our inputs were wrapped, then we have no FunctionalTensor outputs that we need to fix up storages for. + return return_and_correct_aliasing(func, args, kwargs, outs_wrapped) + + def _sync_view_replay_annotations( + self, + args: tuple[Any, ...], + kwargs: dict[str, Any], + ) -> None: + """Sync FunctionalTensor args so view replay uses correct fx node metadata. + + When functionalization encounters a mutation, it handles aliases by lazily + regenerating them at the first time they are next used. This is a problem when + plumbing user annotations during tracing: we want view ops from view replay to + have the same annotation the user specified on the original views. But view + replay happens the next time the alias is used (e.g. + second_op(alias_with_pending_mutation)), so the regenerated views would get the + metadata for second_op instead. + + To fix this, we remember the node metadata from the original views and globally + set it when we lazily perform view replay. The globally set metadata will be + used to populate the fx node created for the replayed operation. + """ + m = torch._C._get_dispatch_mode(torch._C._TorchDispatchModeKey.PROXY) + if m is not None: + for a in pytree.tree_leaves([args, kwargs]): + if not isinstance(a, FunctionalTensor): + continue + unwrapped = torch._from_functional_tensor(a.elem) + try: + # pyrefly: ignore[missing-attribute] + tracker_entry = m.tracer.tensor_tracker[unwrapped] + except KeyError: + # A tensor constant lifted from a nested HOP subgraph + # (e.g. invoke_subgraph / nested_compile_region) is wrapped + # as a FunctionalTensor during dispatch but is owned by the + # inner subgraph's tracer, not the outer one. Constants do + # not require grad; for any grad-requiring tensor that is + # missing from the tracker, re-raise to preserve visibility + # of genuine bugs. + if unwrapped.requires_grad: + raise RuntimeError( + f"cannot find {unwrapped} in tensor_tracker" + ) from None + continue + curr_node = tracker_entry.proxy.node + with fx_traceback.set_current_replay_node(curr_node): + torch._sync(a) + + def _can_decompose( + self, + func: OpOverload, + args: tuple[Any, ...], + kwargs: dict[str, Any], + ) -> bool: + result = _can_decompose_fast(func, self.export, self.pre_dispatch) + if result is not None: + return result + + # in normal torch.compile IR, we only decompose an op if autograd + # would have decomposed it (NB: autograd may have been skipped if + # we are in inference mode) + # TODO: the flatten here can potentially be deduped with the + # unwrapping pytree_map later + flat_args_kwargs, _ = pytree.tree_flatten((args, kwargs)) + return autograd_would_have_decomposed(func, flat_args_kwargs) + + @classmethod + def is_infra_mode(cls) -> bool: + return True + + +@contextlib.contextmanager +def disable_functional_mode() -> Generator[None, None, None]: + return _disable_infra_mode(torch._C._TorchDispatchModeKey.FUNCTIONAL) + + +# This is similar to torch.func.functionalize, but: +# - It uses FunctionalTensorMode, and FunctionalTensor (a python subclass). +# One important advantage to using this mode is that it will let us +# run functionalization underneath __torch_dispatch__, +# which we need in AOTAutograd. +# - Doing so means that it does not automatically compose with other +# functorch transforms, since these transforms always run above __torch_dispatch__. +# That's why this util lives here, and not in functorch. +# - Input mutations are only propagated back when propagate_input_mutations is set. +def dispatch_functionalize( + func: Callable[..., Any], + mode: FunctionalTensorMode = FunctionalTensorMode(), + *, + propagate_input_mutations: bool = False, +) -> Callable[..., Any]: + # TODO: pull these from aot autograd + def to_fun(t: object) -> object: + if isinstance(t, torch.Tensor): + return FunctionalTensor.to_functional(t) + return t + + def from_fun(t: object) -> object: + if not isinstance(t, FunctionalTensor): + # quick sanity check + if isinstance(t, torch.Tensor): + if torch._is_functional_tensor(t): + raise AssertionError( + "Non-FunctionalTensor torch.Tensor should not be a functional tensor" + ) + return t + torch._sync(t) + return torch._from_functional_tensor(t.elem) + + def inner(*args: Any, **kwargs: Any) -> Any: + disable_above = torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize) + ) + flat_inputs: list[Any] = [] + flat_func_inputs: list[Any] = [] + with disable_above: + with mode: + func_args = pytree.tree_map_only(torch.Tensor, to_fun, args) + func_kwargs = pytree.tree_map_only(torch.Tensor, to_fun, kwargs) + if propagate_input_mutations: + # A boxed func clears its input list, so flatten before the call. + flat_inputs = pytree.arg_tree_leaves(*args, **kwargs) + flat_func_inputs = pytree.arg_tree_leaves(*func_args, **func_kwargs) + func_outputs = func(*func_args, **func_kwargs) + outputs = pytree.tree_map_only(FunctionalTensor, from_fun, func_outputs) + + if propagate_input_mutations: + from torch._C._functorch import _propagate_functional_input_mutation + + # Runs outside of mode so the copy_ mutates the caller's tensors. + for arg, func_arg in zip(flat_inputs, flat_func_inputs): + if isinstance(func_arg, FunctionalTensor): + _propagate_functional_input_mutation(arg, func_arg.elem) + + return outputs + + return inner + + +class BaseFunctionalizeAPI(ABC): + @abstractmethod + def wrap_tensors(self, args: tuple[Any, ...]) -> tuple[Any, ...]: + pass + + @abstractmethod + def unwrap_tensors(self, args: torch.Tensor | tuple[torch.Tensor, ...]) -> Any: + pass + + @abstractmethod + def functionalize(self, inner_f: Callable[..., Any]) -> Callable[..., Any]: + pass + + @abstractmethod + def redispatch_to_next(self) -> AbstractContextManager[None]: + pass + + def replace(self, input_tensor: torch.Tensor, output_tensor: torch.Tensor) -> None: + torch._functionalize_replace(input_tensor, output_tensor) + + def commit_update(self, tensor: torch.Tensor) -> None: + torch._functionalize_commit_update(tensor) + + def sync(self, tensor: torch.Tensor) -> None: + torch._functionalize_sync(tensor) + + def mark_mutation_hidden_from_autograd(self, tensor: torch.Tensor) -> None: + torch._functionalize_mark_mutation_hidden_from_autograd(tensor) + + +class PythonFunctionalizeAPI(BaseFunctionalizeAPI): + def __init__( + self, mode: FunctionalTensorMode | None = None, pre_dispatch: bool = False + ) -> None: + super().__init__() + self.mode = mode if mode else FunctionalTensorMode() + self.pre_dispatch = pre_dispatch + + def wrap_tensors(self, args: tuple[Any]) -> tuple[Any]: + with self.mode: + return torch.utils._pytree.tree_map_only( + torch.Tensor, FunctionalTensor.to_functional, args + ) + + def unwrap_tensors( + self, args: torch.Tensor | tuple[torch.Tensor, ...] | list[torch.Tensor] + ) -> Any: + return torch.utils._pytree.tree_map_only( + FunctionalTensor, FunctionalTensor.from_functional, args + ) + + # pyrefly: ignore [implicit-any] + def functionalize(self, inner_f: Callable) -> Callable: + return dispatch_functionalize(inner_f, self.mode) + + def redispatch_to_next(self) -> AbstractContextManager[None]: + # [NOTE] We don't do anything here because at the time + # we exercise this path, we would have already popped the + # FunctionalTensorMode from mode stack. Since FunctionalTensorMode + # is now stateful, it is better to explicitly pass in correct mode + # directly instead of globally setting it. + return contextlib.nullcontext() + + @staticmethod + def _check_cast_functional(tensor: torch.Tensor, name: str) -> FunctionalTensor: + if not isinstance(tensor, FunctionalTensor): + raise AssertionError( + f"{name} must be a FunctionalTensor, got {type(tensor)}" + ) + return tensor + + def replace(self, input_tensor: torch.Tensor, output_tensor: torch.Tensor) -> None: + ft = self._check_cast_functional(input_tensor, "input_tensor") + if isinstance(output_tensor, FunctionalTensor): + raise AssertionError("output_tensor must not be a FunctionalTensor") + ft.replace_(output_tensor) + + def commit_update(self, tensor: torch.Tensor) -> None: + self._check_cast_functional(tensor, "tensor").commit_update() + + def sync(self, tensor: torch.Tensor) -> None: + self._check_cast_functional(tensor, "tensor").sync() + + def mark_mutation_hidden_from_autograd(self, tensor: torch.Tensor) -> None: + self._check_cast_functional( + tensor, "tensor" + ).mark_mutation_hidden_from_autograd() + + +class CppFunctionalizeAPI(BaseFunctionalizeAPI): + def wrap_tensors(self, args: tuple[Any, ...]) -> tuple[Any, ...]: + from torch._functorch.eager_transforms import _wrap_all_tensors_to_functional + + return _wrap_all_tensors_to_functional(args, level=0) + + def unwrap_tensors( + self, args: torch.Tensor | tuple[torch.Tensor, ...] + ) -> torch.Tensor | tuple[torch.Tensor, ...]: + from torch._functorch.eager_transforms import ( + _unwrap_all_tensors_from_functional, + ) + + return _unwrap_all_tensors_from_functional(args, reapply_views=_reapply_views()) + + # pyrefly: ignore [implicit-any] + def functionalize(self, inner_f: Callable) -> Callable: + return torch.func.functionalize(inner_f) + + def redispatch_to_next(self) -> AbstractContextManager[None]: + return torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize) + ) + + +class FunctorchFunctionalizeAPI(BaseFunctionalizeAPI): + def __init__(self, interpreter: FunctionalizeInterpreter) -> None: + self.interpreter = interpreter + + def wrap_tensors(self, args: tuple[Any]) -> tuple[Any]: + from torch._functorch.eager_transforms import _wrap_all_tensors_to_functional + + return _wrap_all_tensors_to_functional(args, level=self.interpreter.level()) + + def unwrap_tensors( + self, args: torch.Tensor | tuple[torch.Tensor, ...] + ) -> torch.Tensor | tuple[torch.Tensor, ...]: + from torch._functorch.eager_transforms import ( + _unwrap_all_tensors_from_functional, + ) + + return _unwrap_all_tensors_from_functional( + args, reapply_views=self.interpreter.functionalize_add_back_views() + ) + + # pyrefly: ignore [implicit-any] + def functionalize(self, inner_f: Callable) -> Callable: + return torch.func.functionalize( + inner_f, + remove=( + "mutations_and_views" + if self.interpreter.functionalize_add_back_views() + else "mutations" + ), + ) + + def redispatch_to_next(self) -> AbstractContextManager[None]: + return self.interpreter.lower() + + +def mb_unwrap_functional_tensor(tensor: torch.Tensor) -> torch.Tensor: + if isinstance(tensor, FunctionalTensor): + return torch._from_functional_tensor(tensor.elem) + return tensor diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..36c83d3f13b4c279f7be8893a98274b54046286b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/meta_utils.py @@ -0,0 +1,2430 @@ +from __future__ import annotations + +import contextlib +import dataclasses +import functools +import threading +import typing +import weakref +from abc import abstractmethod +from contextlib import AbstractContextManager, contextmanager +from dataclasses import dataclass +from typing import ( + Any, + ClassVar, + Generic, + NewType, + Protocol, + TYPE_CHECKING, + TypeGuard, + TypeVar, +) +from typing_extensions import override, TypedDict, Unpack + +import torch +from torch._C._autograd import CreationMeta +from torch._C._functorch import ( + _add_batch_dim, + _unwrap_functional_tensor, + _wrap_functional_tensor, + get_unwrapped, + is_batchedtensor, + is_functorch_wrapped_tensor, + is_gradtrackingtensor, + is_legacy_batchedtensor, + maybe_get_bdim, + maybe_get_level, + peek_interpreter_stack, +) +from torch._custom_class_base import CustomClassBase +from torch._dispatch.python import enable_python_dispatcher +from torch._logging import trace_structured +from torch.utils._mode_utils import no_dispatch +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torch.utils._typing_utils import not_none +from torch.utils.weak import WeakIdKeyDictionary + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator + + from torch._C._functorch import CInterpreter + from torch._guards import Source + from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode + + # Import here to avoid cycle + # Import the following modules during type checking to enable code intelligence features, + # Do not import unconditionally, as they import sympy and importing sympy is very slow + from torch.fx.experimental.symbolic_shapes import ShapeEnv, SymbolicContext + from torch.types import IntLikeType + + +def _unwrap_python_functional_tensor(t: torch.Tensor) -> torch.Tensor: + # Avoid a top-level import cycle: functional_tensor imports this module. + from torch._subclasses.functional_tensor import FunctionalTensor + + if isinstance(t, FunctionalTensor): + return t.from_functional() + return t + + +def _clone_real_storage_from_tensor(t: torch.Tensor) -> torch.UntypedStorage: + from torch._subclasses.fake_tensor import is_fake_tensor, maybe_get_real_tensor + + t = _unwrap_python_functional_tensor(t) + if is_fake_tensor(t): + real_tensor = maybe_get_real_tensor(t) + if real_tensor is None: + raise AssertionError( + "t.real_tensor must not be None when copy_data is True" + ) + t = real_tensor + return t.untyped_storage().clone() + + +DimList = list +_TensorLikeT = TypeVar("_TensorLikeT", "MetaTensorDesc[Any]", torch.Tensor) +_T = TypeVar("_T") +_TensorT = TypeVar("_TensorT", bound=torch.Tensor) +_TensorT_cov = TypeVar("_TensorT_cov", bound=torch.Tensor, covariant=True) + + +def safe_is_leaf(t: MetaTensorDesc[Any] | torch.Tensor) -> bool: + try: + return t.is_leaf + except RuntimeError: + # inference mode can trigger this + return False + + +def safe_grad(t: _TensorLikeT) -> _TensorLikeT | None: + with torch._logging.hide_warnings(torch._logging._internal.safe_grad_filter): + # pyrefly: ignore [bad-return] + return t.grad + + +def _expect_safe_grad(t: _TensorLikeT) -> _TensorLikeT: + grad = safe_grad(t) + if grad is None: + raise AssertionError("Expected tensor to have a gradient but grad is None") + return grad + + +def assert_eq(a: _T, b: _T) -> None: + if a != b: + raise AssertionError(f"{a} != {b}") + + +tls = threading.local() +# Turns off inference mode for fake tensor propagation. This is turned to True +# only for `torch.compile`. Also look at +# _dynamo.config.fake_tensor_disable_inference_mode +tls.disable_inference_mode = False + + +@contextmanager +def disable_inference_mode_for_fake_prop() -> Generator[None, None, None]: + prior = getattr(tls, "disable_inference_mode", False) + tls.disable_inference_mode = True + try: + yield + finally: + tls.disable_inference_mode = prior + + +def assert_metadata_eq( + assert_eq: Callable[[object, object], None], + m1: MetaTensorDesc[Any] | torch.Tensor, + m2: torch.Tensor, + *, + skip_symbolic: bool = False, + skip_leaf: bool = False, +) -> None: + m1 = ( + MetaTensorDescriber().describe_tensor(m1) + if isinstance(m1, torch.Tensor) + else m1 + ) + + def go(m1: MetaTensorDesc[Any], m2: torch.Tensor) -> None: + assert_eq(m1.dtype, m2.dtype) + if not skip_symbolic: + assert_eq(m1.shape, m2.shape) + assert_eq(m1.requires_grad, m2.requires_grad) + if not skip_leaf: + assert_eq(m1.is_leaf, m2.is_leaf) + # MetaTensorDesc doesn't store grad_fn; inferred from leaf + # assert_eq(m1.grad_fn is None, m2.grad_fn is None) + assert_eq(m1.is_sparse, m2.is_sparse) + if not getattr(tls, "disable_inference_mode", False): + assert_eq(m1.is_inference, m2.is_inference()) + else: + assert_eq(m1.is_inference, False) + assert_eq(m1.is_conj, m2.is_conj()) + assert_eq(m1.is_neg, m2.is_neg()) + assert_eq(m1.grad is not None, safe_grad(m2) is not None) + if m1.grad is not None: + go(m1.grad, _expect_safe_grad(m2)) + # TODO: move "assert_eq(m1.layout, m2.layout)" out of sparse + # branches (but not ready for prime time yet)... + if m1.is_sparse: + assert_eq(m1.layout, m2.layout) + assert_eq(m1.dense_dim, m2.dense_dim()) + assert_eq(m1.sparse_dim, m2.sparse_dim()) + assert_eq(m1.is_coalesced, m2.is_coalesced()) + elif is_sparse_compressed(m1): + assert_eq(m1.layout, m2.layout) + assert_eq(m1.dense_dim, m2.dense_dim()) + assert_eq(m1.sparse_dim, m2.sparse_dim()) + else: + if not skip_symbolic: + assert_eq(m1.stride, m2.stride()) + assert_eq(m1.storage_offset, m2.storage_offset()) + assert_eq(m1.is_view, m2._is_view()) + if m1.is_view: + if m1.base is None: + raise AssertionError("m1.base must not be None for a view tensor") + if m2._base is None: + raise AssertionError("m2._base must not be None for a view tensor") + go(m1.base, m2._base) + # TODO: test if is resizable (no direct query for this atm) + # TODO: audit AutogradMeta to see if it matches + # TODO: test forward AD + + return go(m1, m2) + + +# TypeGuard (not TypeIs): False does not imply !torch.Tensor +def is_sparse_coo(t: object) -> TypeGuard[torch.Tensor]: + return isinstance(t, torch.Tensor) and t.layout is torch.sparse_coo + + +def is_sparse_compressed_layout(layout: torch.layout) -> bool: + return layout in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + } + + +# TypeGuard (not TypeIs): False does not imply !torch.Tensor +def is_sparse_compressed(t: object) -> TypeGuard[torch.Tensor]: + return isinstance(t, torch.Tensor) and is_sparse_compressed_layout(t.layout) + + +# TypeGuard (not TypeIs): False does not imply !torch.Tensor +def is_sparse_any(t: object) -> TypeGuard[torch.Tensor]: + return is_sparse_coo(t) or is_sparse_compressed(t) + + +def _checked_cast(ty: type[_T], obj: object) -> _T: + if not isinstance(obj, ty): + raise AssertionError(f"expected {ty} but got {type(obj)}") + return obj + + +def _get_real_storage(base: torch.UntypedStorage) -> torch.UntypedStorage: + return base.real_storage # type: ignore[attr-defined] + + +def _set_real_storage( + base: torch.UntypedStorage, real_storage: torch.UntypedStorage +) -> None: + base.real_storage = real_storage # type: ignore[attr-defined] + + +# Don't use id() directly, because those can get reallocated over time. +MetaStorageId = NewType("MetaStorageId", int) +MetaTensorId = NewType("MetaTensorId", int) + + +_DescriberId = NewType("_DescriberId", int) +DESCRIBER_NEXT_ID = _DescriberId(0) + + +class MetaTensorDescriber: + """ + Given a Tensor/Storage, generate a MetaTensorDesc/MetaStorageDesc + for it, which is enough information to reconstruct a meta tensor/fake tensor + corresponding to a Tensor as faithfully as possible. + + This is a stateful conversion object because we keep track of the IDs + of the tensors/storages passed to us, so we can consistently give + the same ID when we see the same tensor/storage. + """ + + def __init__(self, *, copy_data: bool = False) -> None: + global DESCRIBER_NEXT_ID + self.id = DESCRIBER_NEXT_ID + DESCRIBER_NEXT_ID = _DescriberId(DESCRIBER_NEXT_ID + 1) + self.next_tensor_id: MetaTensorId = MetaTensorId(0) + self.next_storage_id: MetaStorageId = MetaStorageId(0) + # Tensor -> int + self.lookup_tensor = WeakIdKeyDictionary() + # Storage -> int + self.lookup_storage = WeakIdKeyDictionary() + self.copy_data = copy_data + self.traced_tensors: set[int] = set() + self.traced_storages: set[int] = set() + + def get_tensor_id(self, t: torch.Tensor) -> MetaTensorId: + if t not in self.lookup_tensor: + self.lookup_tensor[t] = self.next_tensor_id + self.next_tensor_id = MetaTensorId(self.next_tensor_id + 1) + return self.lookup_tensor[t] + + def get_storage_id(self, s: torch.UntypedStorage) -> MetaStorageId: + if s not in self.lookup_storage: + self.lookup_storage[s] = self.next_storage_id + self.next_storage_id = MetaStorageId(self.next_storage_id + 1) + return self.lookup_storage[s] + + def describe_storage( + self, + s: torch.UntypedStorage, + *, + data: torch.Tensor | None = None, + trace: bool = False, + ) -> MetaStorageDesc: + r = MetaStorageDesc( + id=self.get_storage_id(s), + size=s.size(), + # NB: We don't do the copy yet; copy happens when we start + # creating the new storages + data=data if data is not None else s if self.copy_data else None, + ) + if trace and r.id not in self.traced_storages: + trace_structured( + "describe_storage", + metadata_fn=lambda: r.as_json(self.id), + ) + self.traced_storages.add(r.id) + return r + + def describe_tensor( + self, t: torch.Tensor, *, recurse: bool = True, trace: bool = False + ) -> MetaTensorDesc[Any]: + data = _unwrap_python_functional_tensor(t) if self.copy_data else None + is_leaf = safe_is_leaf(t) + is_view = t._is_view() + is_sparse = t.is_sparse + layout = t.layout + is_nested = t.is_nested + is_traceable_wrapper_subclass_v = is_traceable_wrapper_subclass(t) + is_functorch_wrapped = is_functorch_wrapped_tensor(t) + is_mkldnn = t.is_mkldnn + is_batchedtensor_v = is_batchedtensor(t) + is_legacy_batchedtensor_v = is_legacy_batchedtensor(t) + is_gradtrackingtensor_v = is_gradtrackingtensor(t) + is_functional = torch._is_functional_tensor(t) + + storage = None + # NB: For compatibility, I default this to zero, as sometimes people + # still have stuffed zero into storage offset even though the tensor + # doesn't meaningfully have an offset + storage_offset = 0 + if not ( + is_sparse + or is_sparse_compressed_layout(layout) + or (is_nested and not is_traceable_wrapper_subclass_v) + or is_mkldnn + # TODO: TBH, functorch wrapped tensors probably should have + # storage associated with them + or is_functorch_wrapped + or is_legacy_batchedtensor_v + ): + # NB: We actually don't use storage to do views, but might as well + # put it in for accuracy + storage = self.describe_storage(t.untyped_storage(), data=data, trace=trace) + storage_offset = t.storage_offset() # type: ignore[assignment] + + stride = None + if not ( + is_sparse + or is_sparse_compressed_layout(layout) + or (is_nested and not is_traceable_wrapper_subclass_v) + ): + # stride/storage_offset are called from is_functorch_wrapped, + # view_from_base, empty_create_subclass, + # sym_sizes_strides_storage_offset (empty_create) + stride = t.stride() + + # NB: this technically should refer to functorch unwrapped tensor, but + # I am (perhaps abusively) using it to store both the functorch and + # non-functorch functional tensor + unwrapped = None + autograd_meta_from = None + current_level = None + if is_batchedtensor_v or is_gradtrackingtensor_v: + unwrapped = self.describe_tensor(get_unwrapped(t), trace=trace) + # xla and lazy tensors present as functional tensors, but we want them + # to be handled specially + elif is_functional and t.device.type not in ("xla", "lazy"): + if t._is_view(): + raise RuntimeError( + "Cannot safely fakify a view because this process drops the view information right now." + ) + if not is_functorch_wrapped: + torch._sync(t) + unwrapped = self.describe_tensor( + torch._from_functional_tensor(t), trace=trace + ) + autograd_meta_from = t + else: + reapply_views = torch._C._functionalization_reapply_views_tls() + # NB: has side effects! + unwrapped = self.describe_tensor( + _unwrap_functional_tensor(t, reapply_views), trace=trace + ) + # TODO: It's pretty suspicious that functional tensors don't have + # valid level and thus we just grab whatever the current level + # is + current_level = torch._C._functorch.current_level() + + maybe_functorch_stack = None + if is_functorch_wrapped: + with ( + torch._functorch.pyfunctorch.temporarily_clear_interpreter_stack() + ) as maybe_functorch_stack: + pass + + attrs = None + opaque_attrs = None + ctx = None + type_v = None + if is_traceable_wrapper_subclass_v: + if not hasattr(t, "__tensor_flatten__"): + raise AssertionError( + "Traceable wrapper subclass must have __tensor_flatten__ method" + ) + raw_attrs, ctx = t.__tensor_flatten__() + attrs = {} + opaque_attrs = {} + for attr in raw_attrs: + inner = getattr(t, attr) + match inner: + case torch.Tensor(): + attrs[attr] = self.describe_tensor(inner, trace=trace) + case CustomClassBase(): + from torch._library.fake_class_registry import ( + maybe_unwrap_fake_script_object, + ) + + opaque_attrs[attr] = maybe_unwrap_fake_script_object(inner) + case _: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(inner)}" + ) + type_v = type(t) + + from torch.nested._internal.nested_tensor import _tensor_symint_registry + + view_func = ViewFunc.from_tensor(t) + + # TODO: Is it important to enable torch.inference_mode before querying + # these values? + is_inference_mode_disabled = getattr(tls, "disable_inference_mode", False) + r: MetaTensorDesc[Any] = MetaTensorDesc( + id=self.get_tensor_id(t), + storage=storage, + is_inference=False if is_inference_mode_disabled else t.is_inference(), + is_leaf=is_leaf, + requires_grad=t.requires_grad, + # NB: ndim should be OK too but there is a disaster at + # python test/dynamo/test_subclasses.py -k test_user_overridden_property_unsupported + # Actually, this means that we have a little bit of a problem + # here, which is that there is some sensitivity to how exactly an + # access is done if you have a __torch_function__ subclass. Maybe + # should disable torch function before doing accesses? + ndim=t.dim(), + dtype=t.dtype, + is_sparse=is_sparse, + is_mkldnn=is_mkldnn, + is_functorch_wrapped=is_functorch_wrapped, + is_batchedtensor=is_batchedtensor_v, + is_legacy_batchedtensor=is_legacy_batchedtensor_v, + is_gradtrackingtensor=is_gradtrackingtensor_v, + is_view=is_view, + is_conj=t.is_conj(), + is_neg=t.is_neg(), + is_parameter=isinstance(t, torch.nn.Parameter), + is_traceable_wrapper_subclass=is_traceable_wrapper_subclass_v, + is_nested=is_nested, + nested_int=( + _tensor_symint_registry[t].node.nested_int() + if t in _tensor_symint_registry + else None + ), + is_functional=is_functional, + layout=layout, + device=t.device, + size=t.size(), + stride=stride, + # pyrefly: ignore [bad-argument-type] + storage_offset=storage_offset, + dynamo_dynamic_indices=list(getattr(t, "_dynamo_dynamic_indices", ())), + dynamo_hint_overrides=getattr(t, "_dynamo_hint_overrides", {}), + sparse_dim=( + t.sparse_dim() if t.is_sparse or is_sparse_compressed(t) else None + ), + dense_dim=t.dense_dim() if t.is_sparse or is_sparse_compressed(t) else None, + is_coalesced=t.is_coalesced() if t.is_sparse else None, + # TODO: I actually think recursing here is correct, but we have at + # least an infinite cycle from base -> values -> base + # https://github.com/pytorch/pytorch/issues/122089 + crow_indices=( + self.describe_tensor(t.crow_indices(), recurse=False, trace=trace) + if recurse and t.layout in {torch.sparse_csr, torch.sparse_bsr} + else None + ), + col_indices=( + self.describe_tensor(t.col_indices(), recurse=False, trace=trace) + if recurse and t.layout in {torch.sparse_csr, torch.sparse_bsr} + else None + ), + ccol_indices=( + self.describe_tensor(t.ccol_indices(), recurse=False, trace=trace) + if recurse and t.layout in {torch.sparse_csc, torch.sparse_bsc} + else None + ), + row_indices=( + self.describe_tensor(t.row_indices(), recurse=False, trace=trace) + if recurse and t.layout in {torch.sparse_csc, torch.sparse_bsc} + else None + ), + values=( + self.describe_tensor(t.values(), recurse=False, trace=trace) + if recurse and is_sparse_compressed(t) + else None + ), + grad=( + self.describe_tensor(grad, trace=trace) + if (grad := safe_grad(t)) is not None + else None + ), + creation_meta=( + torch._C._autograd._get_creation_meta(t) if t._is_view() else None + ), + unwrapped=unwrapped, + level=( + maybe_get_level(t) + if is_batchedtensor_v or is_gradtrackingtensor_v + else None + ), + bdim=maybe_get_bdim(t) if is_batchedtensor_v else None, + base=( + self.describe_tensor(t._base, trace=trace) + if recurse and t._is_view() and t._base is not None + else None + ), + fake_mode=torch._subclasses.fake_tensor.maybe_get_fake_mode(t), + view_func=view_func, + # pyrefly: ignore [bad-argument-type] + attrs=attrs, + opaque_attrs=opaque_attrs if opaque_attrs else None, + ctx=ctx, + type=type_v, + # NB: even if functorch is enabled, don't actually save the + # interpreter stack here unless we are actually functorch wrapped; + # it's irrelevant for non-functorch stuff + functorch_stack=maybe_functorch_stack, + autograd_meta_from=autograd_meta_from, + current_level=current_level, + data=data, + ) + if trace and r.id not in self.traced_tensors: + trace_structured( + "describe_tensor", + metadata_fn=lambda: r.as_json(self.id), + ) + self.traced_tensors.add(r.id) + return r + + +@dataclass(frozen=True) +class MetaStorageDesc: + id: MetaStorageId + size: int + # NB: this is only populated with copy_data True, it is not directly + # serializable in JSON, you want to do something special here anyway + data: torch.UntypedStorage | torch.Tensor | None + + def as_json(self, describer_id: _DescriberId) -> dict[str, object]: + metadata: dict[str, object] = { + "id": self.id, + "describer_id": describer_id, + "size": self.size if isinstance(self.size, int) else repr(self.size), + } + if isinstance(self.size, torch.SymInt): + node = self.size.node + free_symbols = node.expr.free_symbols + if free_symbols: + shape_env = not_none(node.shape_env) + if all( + symbol in shape_env.var_to_hint_override for symbol in free_symbols + ): + metadata["size_hint"] = shape_env.optimization_hint(node.expr) + return metadata + + +@dataclass(frozen=True) +class ViewFunc(Generic[_TensorT]): + @abstractmethod + def apply( + self, + t: _TensorT, + new_base: _TensorT, + symint_visitor_fn: Callable[[int], int] | None = None, + tensor_visitor_fn: Callable[[torch.Tensor], _TensorT] | None = None, + ) -> _TensorT: ... + + @staticmethod + def from_tensor(t: torch.Tensor) -> ViewFunc[Any]: + from torch._subclasses.fake_tensor import is_fake_tensor + + if is_fake_tensor(t): + return _FakeTensorViewFunc() + else: + return _CustomViewFunc(t._view_func_unsafe) + + +@dataclass(frozen=True) +class _FakeTensorViewFunc(ViewFunc["FakeTensor"]): + @override + def apply( + self, + t: torch.Tensor, + new_base: torch.Tensor, + symint_visitor_fn: Callable[[int], int] | None = None, + tensor_visitor_fn: Callable[[torch.Tensor], FakeTensor] | None = None, + ) -> FakeTensor: + return torch._subclasses.fake_tensor.FakeTensor._view_func_unsafe( + # pyrefly: ignore [bad-argument-type] + t, + new_base, + symint_visitor_fn, + tensor_visitor_fn, + ) + + +@dataclass(frozen=True) +class _CustomViewFunc(ViewFunc[_TensorT], Generic[_TensorT]): + func: Callable[ + [ + torch.Tensor, + Callable[[int], int] | None, + Callable[[torch.Tensor], _TensorT] | None, + ], + _TensorT, + ] + + @override + def apply( + self, + t: torch.Tensor, + new_base: torch.Tensor, + symint_visitor_fn: Callable[[int], int] | None = None, + tensor_visitor_fn: Callable[[torch.Tensor], _TensorT] | None = None, + ) -> _TensorT: + # ignore `t` + return self.func(new_base, symint_visitor_fn, tensor_visitor_fn) + + +# A callback where the device is either optional or required. +# All of these satisfy this protocol: +# def mk(arg: Callable[[], torch.Tensor], device: Union[torch.device, str]) +# def mk(arg: Callable[[], torch.Tensor], device: Union[torch.device, str] = "meta") +# def mk(arg: Callable[[], torch.Tensor], device: Optional[Union[torch.device, str]] = None) +class _MetaTensorCallback(Protocol, Generic[_TensorT_cov]): + def __call__( + self, arg: Callable[[], torch.Tensor], /, *, device: torch.device | str + ) -> _TensorT_cov: ... + + +class _MetaTensorCallbackKwargs(TypedDict, total=False): + device: torch.device | str + + +# A callback where the device may not be provided (is optional). +# All of these satisfy this protocol: +# def mk(arg: Callable[[], torch.Tensor], device: Union[torch.device, str] = "meta") +# def mk(arg: Callable[[], torch.Tensor], device: Optional[Union[torch.device, str]] = None) +class _MetaTensorCallbackOptDevice(Protocol, Generic[_TensorT_cov]): + def __call__( + self, + arg: Callable[[], torch.Tensor], + /, + **kwargs: Unpack[_MetaTensorCallbackKwargs], + ) -> _TensorT_cov: ... + + +@dataclass(frozen=True) +class MetaTensorDesc(Generic[_TensorT]): + id: MetaTensorId + ndim: int + dtype: torch.dtype + device: torch.device + + # NB: Sometimes, size, stride and storage_offset contain SymInt, in which + # case this is NOT serializable. That only happens when you're + # re-fakeifying a fake tensor with an existing ShapeEnv... maybe we + # can get rid of this use case entirely. Notably, even if we are + # fakeifying a real tensor into a fake tensor with symbolic shapes, the + # size here is NOT dynamic + # NB: These also contain SymInt because wrap_meta_outputs_with_default_device_logic + # goes through this codepath. But it really should not LOL. + # NB: size could potentially be None as you can override it and make it + # throw an error, but we don't currently have any subclasses that do this + # except C++ nested tensor but we're going to have nested int to make this + # defined on NJT + size: tuple[int, ...] + dynamo_dynamic_indices: list[int] + dynamo_hint_overrides: dict[int, int] + + layout: torch.layout = torch.strided + is_inference: bool = False + is_leaf: bool = False + requires_grad: bool = False + is_sparse: bool = False + is_mkldnn: bool = False + is_functorch_wrapped: bool = False + is_batchedtensor: bool = False + is_legacy_batchedtensor: bool = False + is_gradtrackingtensor: bool = False + is_view: bool = False + is_nested: bool = False + # We eagerly symbolicize the associated nested int for e.g. offsets / lengths + # metadata if that offsets is already associated with a nested int. + # See test_construct_from_jagged_with_input_offsets_mixed_case. + nested_int: int | None = None + is_traceable_wrapper_subclass: bool = False + is_functional: bool = False + is_conj: bool = False + is_neg: bool = False + is_parameter: bool = False + stride: tuple[int, ...] | None = None + storage_offset: int = 0 + # NB: We have a choice whether or not to store the id or a direct pointer + # to the data structure. For ease of use, we store the data structure, + # but this means that when we serialize, we have to swizzle these pointers + # back into ids (so we have accurate aliasing relationships) + storage: MetaStorageDesc | None = None + sparse_dim: int | None = None # is_sparse, is_sparse_compressed + dense_dim: int | None = None # is_sparse, is_sparse_compressed + is_coalesced: bool | None = None # is_sparse + crow_indices: MetaTensorDesc[Any] | None = None # is_sparse_compressed + col_indices: MetaTensorDesc[Any] | None = None # is_sparse_compressed + ccol_indices: MetaTensorDesc[Any] | None = None # is_sparse_compressed + row_indices: MetaTensorDesc[Any] | None = None # is_sparse_compressed + values: MetaTensorDesc[Any] | None = None # is_sparse_compressed + unwrapped: MetaTensorDesc[Any] | None = None # is_functorch_wrapped + bdim: int | None = None # is_functorch_wrapped + base: MetaTensorDesc[Any] | None = None # is_view + attrs: dict[str, MetaTensorDesc[Any]] | None = None # is_traceable_wrapper_subclass + # A Tensor subclass containing opaque references is almost certainly NOT + # serializable. + opaque_attrs: dict[str, CustomClassBase] | None = ( + None # non-tensor attrs from __tensor_flatten__ + ) + creation_meta: CreationMeta | None = None + grad: MetaTensorDesc[Any] | None = None + + # Everything below is NOT serializable, need some more work + + _UNSERIALIZABLE: ClassVar[set[str]] = { + "ctx", + "type", + "fake_mode", + # view_func isn't serializable when it's a _CustomViewFunc + "view_func", + "level", + "current_level", + "functorch_stack", + "autograd_meta_from", + "data", + "nested_int", + } + + ctx: object | None = None # is_traceable_wrapper_subclass + type: type | None = None # is_traceable_wrapper_subclass + fake_mode: FakeTensorMode | None = None + view_func: ViewFunc[Any] | None = None + # level looks serializable, but actually it is meaningless without + # the functorch_stack below + level: int | None = None # is_functorch_wrapped + current_level: int | None = None + functorch_stack: list[CInterpreter] | None = None + autograd_meta_from: torch.Tensor | None = None + + # This is only populated on copy_data, and typically is not used at all, + # except for some of our meta-ification paths that don't properly use + # storage (pro-tip: you should use storage) + data: torch.Tensor | None = None + + # Faithfully serializing functorch tensors will not be too difficult. + # We only need to consider grad/vmap interpreters, and their internal + # state is only bools (mostly what the grad enabled/disabled state + # should be in the lower layer). Beyond that, tensors just need to + # precisely indicate which particular interpreter they correspond + # to (we then replace level with a pointer to the interpreter stack.) + # However, this use of functorch is very "non-lexical" so it's not + # entirely clear how to make it all lexical again, so we haven't done + # it for now. + + # NB: This will reference numeric IDs, and it is assumed that you've + # already serialized everything this recursively references + def as_json(self, describer_id: _DescriberId) -> dict[str, object]: + def json(k: str, v: object) -> object: + # Some best-effort debugging serialization for unserializable + # fields (feel free to add other special cases as appropriate) + if k in ["data", "autograd_meta_from"]: + return None # never repr these + if k in MetaTensorDesc._UNSERIALIZABLE: + return repr(v) + if isinstance(v, (torch.device, torch.dtype, torch.layout)): + return repr(v) + if isinstance(v, torch.SymInt): + return repr(v) + if isinstance(v, (tuple, list)): + return [json(k, v1) for v1 in v] + if isinstance(v, (MetaStorageDesc, MetaTensorDesc)): + return v.id + if isinstance(v, CreationMeta): + return str(v) + if k == "attrs" and isinstance(v, dict): + return {k1: v1.id for k1, v1 in v.items()} + return v + + r = { + field.name: json(field.name, getattr(self, field.name)) + for field in dataclasses.fields(self) + if not ( + getattr(self, field.name) is field.default + or ( + field.name == "dynamo_dynamic_indices" + and not getattr(self, field.name) + ) + ) + } + r.update({"describer_id": describer_id}) + return r + + @property + def shape(self) -> tuple[int, ...]: + return self.size + + +# A more faithful reproduction would do a copy on the entire +# storage, but this needs to be done carefully because the +# underlying storage could have larger extent than is implied +# by size/stride. The real fix is to properly call +# meta_storage recursively here. +# +# These "safe" functions are intended to be used under no_dispatch() mode. +# The no_dispatch() here is intended to prevent ambient fake tensor mode from +# fakeifying the operation. But if we are given an honest to goodness +# FakeTensor as src, we MUST NOT run the copy/clone operation. A better way +# to do this would be to not use no_dispatch and instead just disable fake +# tensor mode only (allowing for subclass dispatch to occur) +def _safe_copy(dst: torch.Tensor, src: torch.Tensor | None) -> None: + if type(src) is not torch.Tensor: + return + dst.copy_(src) + + +def _safe_clone(src: torch.Tensor) -> torch.Tensor | None: + if type(src) is not torch.Tensor: + return None + return src.clone() + + +def _grad_context_compatible( + symbolic_context: torch.fx.experimental.symbolic_shapes.SymbolicContext, + grad_desc: MetaTensorDesc[torch.Tensor], +) -> bool: + """Check if a symbolic_context is compatible with a grad tensor. + + Returns False when the view base structure in symbolic_context doesn't + match the grad, which means we need a fresh symbolic context. This + happens in FSDP2 where param._local_tensor is a view of an N-D padded + base while grad._local_tensor is a view of a 1-D flat gradient buffer. + + We check at both the outer level and the inner (subclass attr) level. + """ + from torch.fx.experimental.symbolic_shapes import ( + StatelessSymbolicContext, + SubclassSymbolicContext, + ) + + def _view_base_compatible( + ctx: StatelessSymbolicContext[Any, Any], + grad_t: MetaTensorDesc[torch.Tensor], + ) -> bool: + vbc = ctx.view_base_context + if grad_t.is_view and vbc is None: + return False + if not grad_t.is_view and vbc is not None: + return False + if ( + grad_t.is_view + and vbc is not None + and isinstance(vbc, StatelessSymbolicContext) + and grad_t.base is not None + and len(vbc.dynamic_sizes) != grad_t.base.ndim + ): + return False + return True + + if not isinstance(symbolic_context, StatelessSymbolicContext): + return True + + # Check outer level + if not _view_base_compatible(symbolic_context, grad_desc): + return False + + if grad_desc.is_traceable_wrapper_subclass and not isinstance( + symbolic_context, SubclassSymbolicContext + ): + return False + + # Check inner (subclass) level + if isinstance(symbolic_context, SubclassSymbolicContext): + if grad_desc.attrs is None: + return False + for attr, inner_ctx in symbolic_context.inner_contexts.items(): + if attr not in grad_desc.attrs: + return False + if isinstance( + inner_ctx, StatelessSymbolicContext + ) and not _view_base_compatible(inner_ctx, grad_desc.attrs[attr]): + return False + + return True + + +# This is a class for converting multiple tensors into meta tensors which +# share the same view/storage structure. The operation model is you allocate +# one of these, and then call it repeatedly on all the tensors you want to +# convert. It's important to use the same object for tensors you want to +# share storage because this is how we correlate shared storages to the same +# meta storages. This class will hold weak references to cached tensors +# and tensor storages. +class MetaConverter(Generic[_TensorT]): + def __init__(self, *, copy_data: bool = False) -> None: + # Maps MetaStorageId to UntypedStorage + self.storage_memo: weakref.WeakValueDictionary[ + MetaStorageId, torch.UntypedStorage + ] = weakref.WeakValueDictionary() + # Maps MetaTensorId to torch.Tensor (typically a meta tensor or + # FakeTensor) + self.tensor_memo: weakref.WeakValueDictionary[MetaTensorId, _TensorT] = ( + weakref.WeakValueDictionary() + ) + self.hit = 0 + self.miss = 0 + self.del_hook = None + self.arg_cnt = 0 + # Ensures real_storage/real_tensor are populated on the resulting + # metaified storage/tensor. The naming of this attribute is load + # bearing: FakeTensor relies on real tensor being set to exactly this + # value + self.copy_data = copy_data + self.describer = MetaTensorDescriber(copy_data=copy_data) + + def successful(self) -> bool: + return self.hit > 0 and self.miss == 0 + + def get_tensor_memo(self, t: MetaTensorDesc[Any]) -> torch.Tensor | None: + return self.tensor_memo.get(t.id, None) + + def _checked_get_tensor_memo(self, t: MetaTensorDesc[Any]) -> _TensorT: + r = self.tensor_memo.get(t.id, None) + if r is None: + raise AssertionError(f"Tensor memo for id {t.id} is None") + return r + + def set_tensor_memo(self, t: MetaTensorDesc[Any], v: _TensorT) -> None: + self.tensor_memo[t.id] = v + + def get_storage_memo(self, s: MetaStorageDesc) -> torch.UntypedStorage | None: + return self.storage_memo.get(s.id, None) + + def set_storage_memo(self, s: MetaStorageDesc, v: torch.UntypedStorage) -> None: + self.storage_memo[s.id] = v + + def meta_storage( + self, + s: MetaStorageDesc, + callback: Callable[[Callable[[], torch.Tensor]], _TensorT], + ) -> torch.UntypedStorage: + # If we are fakeifying a tensor that has a secretly-zero-sized storage, + # Need to make sure to resize the meta storage too. + if (memo := self.get_storage_memo(s)) is None: + r_s = callback( + lambda: torch.empty(s.size, dtype=torch.uint8, device="meta"), + ).untyped_storage() + if self.copy_data: + # NB: no_dispatch is needed because internally storage copy is + # implemented as Tensor operations + with torch.no_grad(), no_dispatch(): + if s.data is None: + raise AssertionError( + "s.data must not be None when copy_data is True" + ) + if isinstance(s.data, torch.Tensor): + real_storage = _clone_real_storage_from_tensor(s.data) + else: + real_storage = s.data.clone() + _set_real_storage(r_s, real_storage) + self.set_storage_memo(s, r_s) + return r_s + else: + return memo + + @classmethod + def _checked_cast_tensor_t(cls, t: torch.Tensor) -> _TensorT: + # TODO: how to check _TensorT? + return typing.cast(_TensorT, t) + + @classmethod + def _identity_callable( + cls, + t: Callable[[], torch.Tensor], + device: torch.device | str | None = None, + ) -> _TensorT: + return cls._checked_cast_tensor_t(t()) + + @classmethod + def _backward_error(cls, t: _TensorT) -> _TensorT: + errfn = torch._C._functions.DelayedError( + "Internal error: Tried to backward() through example input", + 1, + ) + err = errfn(t) + return typing.cast(_TensorT, err) + + def _empty_create_subclass( + self, + t: MetaTensorDesc[Any], + outer_size: tuple[int, ...] | None, + outer_stride: tuple[int, ...] | None, + shape_env: ShapeEnv | None, + symbolic_context: torch.fx.experimental.symbolic_shapes.SymbolicContext | None, + callback: _MetaTensorCallbackOptDevice[_TensorT], + source: torch._guards.Source, + ) -> _TensorT: + from torch._dynamo.source import AttrSource + from torch.fx.experimental.symbolic_shapes import SubclassSymbolicContext + + # We are hitting plain meta_desc tensor so actually + # create a tensor here. + if t.attrs is None: + return self.meta_tensor( + t, + shape_env, + callback, + source, + symbolic_context, + ) + + inner_tensors: dict[str, torch.Tensor | CustomClassBase] = {} + for attr, meta_tensor_desc in t.attrs.items(): + current_context = None + if symbolic_context is not None: + if not isinstance(symbolic_context, SubclassSymbolicContext): + raise AssertionError( + f"Expected SubclassSymbolicContext, got {type(symbolic_context)}" + ) + if attr not in symbolic_context.inner_contexts: + raise AssertionError( + f"tensor attr {attr!r} missing from inner_contexts" + ) + if ( + current_context_ := symbolic_context.inner_contexts[attr] + ) is not None: + current_context = _checked_cast( + torch.fx.experimental.symbolic_shapes.SymbolicContext, + current_context_, + ) + + current_source = AttrSource(source, attr) + inner_callback = functools.partial(callback, device=meta_tensor_desc.device) + new_empty_tensor = self._empty_create_subclass( + meta_tensor_desc, + meta_tensor_desc.size, + meta_tensor_desc.stride, + shape_env, + current_context, + inner_callback, + current_source, + ) + inner_tensors[attr] = new_empty_tensor + + # Pass through opaque (non-tensor) attrs + if t.opaque_attrs: + inner_tensors.update(t.opaque_attrs) + + if t.type is None: + raise AssertionError("t.type must not be None for subclass") + return t.type.__tensor_unflatten__( # type: ignore[attr-defined] + inner_tensors, t.ctx, outer_size, outer_stride + ) + + # This function assumes that it's possible to do the conversion + # NB: name here is used in a conventional way by Dynamo; it corresponds + # precisely to the Source.name of the tensor we're fakeifying and + # corresponds to a valid Python expression. When we construct sub-names + # as part of this process, we will maintain this invariant! (Even though + # other users of this may not need it this property to be upheld.) + def meta_tensor( + self, + t: MetaTensorDesc[Any], + shape_env: ShapeEnv | None, + callback_: _MetaTensorCallback[_TensorT], + source: Source | None, + symbolic_context: SymbolicContext | None, + ) -> _TensorT: + from torch._subclasses.fake_tensor import is_fake_tensor, maybe_get_real_tensor + + callback: _MetaTensorCallbackOptDevice[_TensorT] = functools.partial( + callback_, device=t.device + ) + if source is None: + from torch._dynamo.source import ConstantSource + + # TODO: make a dedicated UnknownSource for this? + source = ConstantSource( + f"__meta_utils_unknown_tensor{len(self.tensor_memo)}" + ) + + msg = ( + " This indicates you set no_dispatch() before calling into this" + " function. This is an error: we may be creating fake tensors and" + " will perform operations on them which need fake tensor mode to" + " be active. You will segfault if you are in a no_dispatch() block." + ) + if torch._C._dispatch_tls_local_exclude_set().has(torch._C.DispatchKey.Python): + raise AssertionError(msg) + self.arg_cnt += 1 + + # When we make as_strided calls, we end up generating a guard + # that the new as_strided tensor is in bounds for the old storage + # for the base (since as_strided calls can "bust" out of their + # bounding box.) This guard is unnecessary: if a user is able + # to provide us a tensor with the view base setup this way, we + # don't need to produce a guard, because the fact that they + # were able to produce the view base means its in bounds. + # + # Now, ordinarily, this guard would be harmless. However, the + # generated guard refers to variables bound on the base variable. + # At the moment, Dynamo doesn't actually guard on x._base, because + # according to Voz this results in a lot of spurious invalidations, + # and also if the user doesn't directly make use of _base, its + # pointless anyway (because programs should be parametric over + # whether or not the input tensor is a view or not--unless you're + # mutating the input, but that's a whole 'nother ballgame). So + # for expediency, we suppress these guards so we don't have to + # deal with this (yet, anyway.) + # + # NB: An old version of this code suppressed guards for ALL operations + # happening during meta conversion, not just as_strided calls. + # This is too aggressive: we do duck sizing and 0/1 simplification + # as we allocate variables, and we do need to register guards for + # these cases. + maybe_suppress: Callable[[], Any] = contextlib.nullcontext + if shape_env is not None: + maybe_suppress = shape_env.suppress_guards + + def sym_sizes_strides_storage_offset( + t: MetaTensorDesc[Any], + src: torch._guards.Source, + symbolic_context: torch.fx.experimental.symbolic_shapes.SymbolicContext + | None = symbolic_context, + ) -> tuple[tuple[IntLikeType, ...], tuple[IntLikeType, ...], IntLikeType]: + # local import to prevent circular import + from torch.fx.experimental.symbolic_shapes import is_symbolic + + if t.stride is None: + raise AssertionError("t.stride must not be None") + + if shape_env is not None: + fake_mode = t.fake_mode + has_symbolic = ( + any(is_symbolic(sz) for sz in t.size) + or any(is_symbolic(sd) for sd in t.stride) + or is_symbolic(t.storage_offset) + ) + if fake_mode is not None and fake_mode.shape_env is shape_env: + # Don't reallocate the sizes; the shape envs are the same, + # so reuse the old sizes/strides/etc + return (t.size, t.stride, t.storage_offset) + elif ( + fake_mode is not None + and not has_symbolic + and symbolic_context is None + ): + return (t.size, t.stride, t.storage_offset) + elif fake_mode is None: + # Real tensor (not a FakeTensor). Use + # _create_symbolic_sizes_strides_storage_offset directly + # since there are no foreign symbols to transfer. + return shape_env._create_symbolic_sizes_strides_storage_offset( + t.size, + t.stride, + t.storage_offset, + [False] * t.ndim, + src, + symbolic_context=symbolic_context, + hint_overrides=t.dynamo_hint_overrides, + ) + else: + # FakeTensor from a different ShapeEnv. Transfer symbols. + # _transfer_foreign_expr picks the hint up via the foreign env. + return shape_env.transfer_symbols_from_foreign_shape_env( + t.size, + t.stride, + t.storage_offset, + src, + symbolic_context=symbolic_context, + ) + else: + return (t.size, t.stride, t.storage_offset) + + def sym_sparse_sizes( + t: MetaTensorDesc[Any], + src: torch._guards.Source, + symbolic_context: torch.fx.experimental.symbolic_shapes.SymbolicContext + | None = symbolic_context, + ) -> tuple[IntLikeType, ...]: + if shape_env is None: + return t.size + + from torch._prims_common import make_contiguous_strides_for + from torch.fx.experimental.symbolic_shapes import is_symbolic + + fake_mode = t.fake_mode + has_symbolic = any(is_symbolic(sz) for sz in t.size) + if fake_mode is not None and fake_mode.shape_env is shape_env: + return t.size + if symbolic_context is None and not ( + fake_mode is not None and has_symbolic + ): + return t.size + + sparse_tensor_with_synthetic_strides = dataclasses.replace( + t, + stride=make_contiguous_strides_for(t.size), + storage_offset=0, + ) + sizes, _, _ = sym_sizes_strides_storage_offset( + sparse_tensor_with_synthetic_strides, + src, + symbolic_context, + ) + return sizes + + def empty_create( + inner_t: MetaTensorDesc[Any], + inner_src: torch._guards.Source, + symbolic_context: torch.fx.experimental.symbolic_shapes.SymbolicContext + | None = symbolic_context, + ) -> torch.Tensor: + ( + inner_sizes, + inner_strides, + _inner_storage_offset, + ) = sym_sizes_strides_storage_offset(inner_t, inner_src, symbolic_context) + return torch.empty_strided( + inner_sizes, + inner_strides, + dtype=inner_t.dtype, + device="meta", + ) + + # Creates a subclass instance with empty inner tensors according to the specified + # symbolic context. + def empty_create_subclass( + t: MetaTensorDesc[Any], + outer_size: tuple[IntLikeType, ...], + outer_stride: tuple[IntLikeType, ...], + symbolic_context: torch.fx.experimental.symbolic_shapes.SymbolicContext + | None = symbolic_context, + source: torch._guards.Source | None = source, + ) -> _TensorT: + from torch.fx.experimental.symbolic_shapes import SubclassSymbolicContext + + if t.attrs is None: + raise AssertionError("t.attrs must not be None for subclass") + if t.type is None: + raise AssertionError("t.type must not be None for subclass") + # NB: t.ctx could be None if the subclass in question has no + # meaningful context + + # Note: transform_subclass will use __tensor_unflatten__ to generate + # a fresh subclass wrapper with outer sizes / strides according to the + # outer symbolic context (passed in to this function). Inner size / stride + # / storage offset symbols are allocated according to the appropriate inner + # symbolic contexts, after which the checks in transform_subclass() will + # relate them to the outer metadata as possible. + # + # Morally, the code here is same as transform_subclass, but we've + # written it from scratch to read EmptyCreateSubclass + outer_size = outer_size if outer_size is not None else t.size + # pyrefly: ignore [bad-assignment] + outer_stride = outer_stride if outer_stride is not None else t.stride + + if symbolic_context is not None and not isinstance( + symbolic_context, SubclassSymbolicContext + ): + raise AssertionError( + f"Expected SubclassSymbolicContext or None, got {type(symbolic_context)}" + ) + + if source is None: + raise AssertionError("source must not be None") + sub = self._empty_create_subclass( + t, + # pyrefly: ignore[bad-argument-type] + outer_size, + # pyrefly: ignore[bad-argument-type] + outer_stride, + shape_env, + symbolic_context, + callback, + source, + ) + + # NB: Purposefully guard here to simplify the inner / outer symbols. + # Using sym_eq() for symbolic comparison can result in an expression that's too + # difficult to guard on, so we use == here. + if sub.shape != outer_size: + raise AssertionError( + f"Expected return value from {t.type}__tensor_unflatten__() to have " + f"shape equal to {outer_size}, but got: {sub.shape}" + ) + if sub.stride() != outer_stride: + raise AssertionError( + f"Expected return value from {t.type}__tensor_unflatten__() to have " + f"stride equal to {outer_stride}, but got: {sub.stride()}" + ) + + return sub + + # Returns an all-dynamic symbolic context used for metafying the given tensor with + # fully dynamic dims. This is useful when fake-ifying intermediate tensors in + # closed-over ViewFunc state, as we don't have symbolic contexts for them, but we + # don't want to over-specialize during view replay. + def all_dynamic_symbolic_context( + t: MetaTensorDesc[Any], + source: torch._guards.Source, + shape_env: torch.fx.experimental.symbolic_shapes.ShapeEnv | None, + callback: _MetaTensorCallback[_TensorT], + ) -> torch.fx.experimental.symbolic_shapes.SymbolicContext: + from torch._dynamo.source import AttrSource + from torch.fx.experimental.symbolic_shapes import ( + DimDynamic, + StatelessSymbolicContext, + SubclassSymbolicContext, + ) + + view_base_context: ( + torch.fx.experimental.symbolic_shapes.SymbolicContext | None + ) = None + if t.is_view: + if t.base is None: + raise AssertionError("t.base must not be None for view tensor") + view_base_context = all_dynamic_symbolic_context( + t.base, AttrSource(source, "_base"), shape_env, callback + ) + + t_symbolic_context: torch.fx.experimental.symbolic_shapes.SymbolicContext + t_dynamic_sizes = [DimDynamic.DYNAMIC] * t.ndim + if t.is_traceable_wrapper_subclass: + if t.attrs is None: + raise AssertionError("t.attrs must not be None for subclass") + inner_contexts: dict[ + str, torch.fx.experimental.symbolic_shapes.SymbolicContext + ] = {} + for attr, inner in t.attrs.items(): + if not isinstance(attr, str): + raise AssertionError( + f"Expected attr to be str, got {type(attr)}" + ) + inner_contexts[attr] = all_dynamic_symbolic_context( + inner, AttrSource(source, attr), shape_env, callback + ) + t_symbolic_context = SubclassSymbolicContext( + dynamic_sizes=t_dynamic_sizes, + constraint_sizes=[None] * t.ndim, + inner_contexts=inner_contexts, # type: ignore[arg-type] + tensor_source=source, + view_base_context=view_base_context, + ) + else: + t_symbolic_context = StatelessSymbolicContext( + dynamic_sizes=t_dynamic_sizes, + constraint_sizes=[None] * t.ndim, + view_base_context=view_base_context, + ) + + return t_symbolic_context + + # Returns a fake-ified version of an input view tensor t, given an already fake-ified + # base. At a high level, we want two things: + # 1. fake_t should have the same view relationship to the given fake base as the + # input t has to its _base. + # 2. fake_t should have symbolic sizes / strides / storage offset according to the + # appropriate symbolic context (i.e. from the automatic dynamic algorithm). + # + # We currently take different strategies across view types: + # * For dense -> dense views, accomplish both (1) and (2) simultaneously via an + # as_strided() call on the fake-ified base, passing symbolic metadata. + # * For views involving subclasses, perform view replay using view funcs to + # achieve (1). It's necessary for (2) to swap out any closed-over state in + # the view funcs with symbolicized SymInts and fake-ified tensors. Doing this + # avoids specialization (and thus over-eager simplification of symbols) that + # could occur during view replay on the fake-ified base. + # + # Examples: + # * t.unsqueeze(-1) with dense t is a dense -> dense view. It can be modeled + # with an as_strided() call on the fake base passing symbolic metadata. + # * sub.select(dim=0, index=3) is a subclass -> subclass view. The index arg + # is made symbolic to avoid invalid specialization and view replay is then + # done to reconstruct the view. + # * _nested_from_jagged(values, offsets) is a dense -> subclass view + # that returns a subclass instance from a dense values tensor. The offsets + # tensor is closed over in the view func, as it can be considered view metadata. + # First, the offsets tensor is fake-ified according to the inner symbolic + # context and with the correct relationship to the outer size / stride metadata. + # Then view replay is done, swapping in the fake offsets so the view replay output + # is fully fake with no invalid specialization. + def view_from_base( + base: _TensorT, + t: MetaTensorDesc[Any], + shape_env: torch.fx.experimental.symbolic_shapes.ShapeEnv + | None = shape_env, + ) -> _TensorT: + with enable_python_dispatcher(): + # fake-ify t's metadata according to the outer symbolic context + (sizes, strides, storage_offset) = sym_sizes_strides_storage_offset( + t, source + ) + if ( + not t.is_traceable_wrapper_subclass + and not is_traceable_wrapper_subclass(base) + ): + # Dense -> Dense view case uses as_strided() to construct view relationship. + # TODO: Change this logic to use view replay for consistency? + # It's likely there is no view func available. + with maybe_suppress(): + return self._checked_cast_tensor_t( + base.as_strided(sizes, strides, storage_offset) + ) + + from torch._dynamo.source import EphemeralSource + from torch.fx.experimental.symbolic_shapes import ( + StatelessSymbolicContext, + sym_eq, + ) + + def symint_visitor_fn(s: int) -> IntLikeType: + nonlocal symbolic_context + from torch.fx.experimental.symbolic_shapes import DimDynamic + + all_static_sizes = ( + symbolic_context is not None + and isinstance(symbolic_context, StatelessSymbolicContext) + and all( + x is DimDynamic.STATIC + for x in symbolic_context.dynamic_sizes + ) + ) + # Can't just rely on shape env being None - dynamo always initializes it + if all_static_sizes or shape_env is None: + return s + + # NB: The symbol here is expected to be simplified out because we a priori + # allocate inner and outer symbols according to the appropriate symbolic + # contexts and prefer those over this symbol during symbol simplification + # (via usage of EphemeralSource below). This -shouldn't- happen, but if + # this symbol somehow leaks out beyond the view tensor's shape metadata, our + # assumption of it being simplified out will fail and it may be guarded on, + # which will hard error. + sym_source = EphemeralSource("symint_visitor_fn") + + symbol = shape_env.create_symbol(s, sym_source, positive=None) + return shape_env.create_symintnode( + symbol, hint=s, source=sym_source + ) + + real_to_fake_mapping = {} + if t.is_traceable_wrapper_subclass: + if t.attrs is None: + raise AssertionError("t.attrs must not be None for subclass") + # NB: t.ctx could be None if the subclass in question has no + # meaningful context + if t.type is None: + raise AssertionError("t.type must not be None for subclass") + + # Fake-ify t naively here; this is only done so we can get fake-ified inner + # tensors with the correct relationships to the outer sizes / strides for use + # in view replay. It's done beforehand here because it's not easy to do when + # visiting tensors one-by-one during view replay. + # + # Example: + # Consider a Dense -> NJT view. NJT has (values, offsets) components and we + # want a view of values with the offsets closed over. As the offsets component + # is needed to describe the output view, it's important that it's fakeified + # correctly. + fake_t: _TensorT = empty_create_subclass( + t, outer_size=sizes, outer_stride=strides + ) + attrs, _ = fake_t.__tensor_flatten__() # type: ignore[attr-defined] + for attr in attrs: + if attr in t.attrs: + real_to_fake_mapping[t.attrs[attr].id] = getattr( + fake_t, attr + ) + + def tensor_visitor_fn( + visited_t: torch.Tensor, + # These arguments are never passed, we just use them to close + # over these relevant values + shape_env: torch.fx.experimental.symbolic_shapes.ShapeEnv + | None = shape_env, + callback: _MetaTensorCallbackOptDevice[_TensorT] = callback, + ) -> torch.Tensor: + # It's possible to close over an undefined tensor (e.g. NJT's lengths). + if visited_t is None: + # pyrefly: ignore [bad-return] + return None + + # NB: visited_t being a Tensor here is very naughty! Should + # have already been described + + # Fake inner tensors of view subclasses will come from the mapping built above. + visited_id = self.describer.get_tensor_id(visited_t) + fake_visited_t = real_to_fake_mapping.get(visited_id) + if fake_visited_t is not None: + return fake_visited_t + + visited_desc = self.describer.describe_tensor(visited_t) + + # For other closed-over tensor state, fake-ify it as all dynamic with an + # ephemeral source. This avoids invalid specialization during view replay. + # If we find that in practice the usage of ephemeral sources isn't enough + # to guarantee that we don't have guards on these symbols, we may need to + # explicitly suppress guards (as is done for _base in the dense -> dense + # view case). + temp_source = EphemeralSource("tensor_visitor_fn") + return self.meta_tensor( + visited_desc, + shape_env, + callback, + temp_source, + all_dynamic_symbolic_context( + visited_desc, temp_source, shape_env, callback + ), + ) + + # Replay the view, swapping out any non-symbolic SymInts or real tensors + # for symbolic SymInts or fake tensors. + if t.view_func is None: + raise AssertionError("t.view_func must not be None for view replay") + # NB: we do NOT suppress guards here, we need to remove ephemeral + # sources + fake_t = t.view_func.apply( + t, + base, + # pyrefly: ignore[bad-argument-type] + symint_visitor_fn, + tensor_visitor_fn, + ) + + # Ensure the output has symbolic shapes according to the outer symbolic context. + # These checks should simplify out any symbols created for closed-over view func + # SymInts. + torch._check(sym_eq(fake_t.size(), sizes)) + torch._check(sym_eq(fake_t.stride(), strides)) + torch._check(sym_eq(fake_t.storage_offset(), storage_offset)) + return fake_t + + if self.get_tensor_memo(t) is None: + GRAD_TENSOR_SENTINEL_VALUE = -2 + + with torch.inference_mode(t.is_inference): + if t.is_sparse: + is_leaf = t.is_leaf + + sparse_size = sym_sparse_sizes(t, source, symbolic_context) + if t.sparse_dim is None: + raise AssertionError("t.sparse_dim must not be None") + if t.dense_dim is None: + raise AssertionError("t.dense_dim must not be None") + + # The lambda function below is similar to + # `t.to(device='meta')` except the latter + # preserves nnz value + r = callback( + lambda: torch.ops.aten._sparse_coo_tensor_with_dims_and_tensors( + t.sparse_dim, + t.dense_dim, + sparse_size, + torch.empty( + (t.sparse_dim, 0), + dtype=torch.int64, + device="meta", + ), + torch.empty( + (0, *sparse_size[t.sparse_dim :]), + dtype=t.dtype, + device="meta", + ), + dtype=t.dtype, + layout=torch.sparse_coo, + device="meta", + is_coalesced=t.is_coalesced, + ) + ) + if self.copy_data: + # Pray that sparse clone doesn't lose information + if t.data is None: + raise AssertionError( + "t.data must not be None when copy_data is True" + ) + with torch.no_grad(), no_dispatch(): + if not is_fake_tensor(r): + raise AssertionError("Expected r to be a FakeTensor") + # pyrefly: ignore[missing-attribute] + r.real_tensor = _safe_clone(t.data) + if not safe_is_leaf(r): + raise AssertionError( + "the callback you passed in doesn't detach" + ) + # Note [is_coalesced is dispatched] + # Strangely enough, is_coalesced() is a dispatched operator, + # which means that it will get caught by fake tensor mode. + # Ordinarily this would error, but there's some logic in + # fake tensor ensure this doesn't happen. + r._coalesced_(bool(t.is_coalesced)) + if t.requires_grad: + r.requires_grad = True + if t.requires_grad and not is_leaf: + # This should probably use DelayedError, + # but clone is fine for now for sparse tensors. + # (DelayedError does not work for sparse because it causes + # the Fake sparse tensor to "lose" its fakeness) + r = self._checked_cast_tensor_t(r.clone()) + with torch.enable_grad(): + r._coalesced_(bool(t.is_coalesced)) + elif is_sparse_compressed_layout(t.layout): + is_leaf = t.is_leaf + + if t.layout in {torch.sparse_bsr, torch.sparse_bsc}: + if t.sparse_dim is None: + raise AssertionError( + "t.sparse_dim must not be None for sparse block layout" + ) + if t.dense_dim is None: + raise AssertionError( + "t.dense_dim must not be None for sparse block layout" + ) + if t.values is None: + raise AssertionError( + "t.values must not be None for sparse block layout" + ) + batch_dim = t.ndim - t.sparse_dim - t.dense_dim + blocksize = t.values.shape[batch_dim + 1 : batch_dim + 3] + else: + blocksize = () + if t.layout in {torch.sparse_csr, torch.sparse_bsr}: + if t.crow_indices is None: + raise AssertionError( + "t.crow_indices must not be None for sparse csr/bsr layout" + ) + index_dtype = t.crow_indices.dtype + else: + if t.ccol_indices is None: + raise AssertionError( + "t.ccol_indices must not be None for sparse csc/bsc layout" + ) + index_dtype = t.ccol_indices.dtype + + r = callback( + lambda: torch.ops.aten._sparse_compressed_tensor_with_dims( + 0, + t.dense_dim, + t.shape, + blocksize, + index_dtype, + layout=t.layout, + dtype=t.dtype, + device="meta", + ) + ) + if self.copy_data: + # Pray sparse clone doesn't lose information + if t.data is None: + raise AssertionError( + "t.data must not be None when copy_data is True" + ) + with torch.no_grad(), no_dispatch(): + if not is_fake_tensor(r): + raise AssertionError("Expected r to be a FakeTensor") + # pyrefly: ignore[missing-attribute] + r.real_tensor = _safe_clone(t.data) + if not safe_is_leaf(r): + raise AssertionError( + "the callback you passed in doesn't detach" + ) + if t.requires_grad: + r.requires_grad = True + if t.requires_grad and not is_leaf: + r = self._backward_error(r) + elif t.is_nested and not t.is_traceable_wrapper_subclass: + # TODO: Handle this better in Dynamo? + # There are checks there now, but this can still be triggered by a dense + # tensor graph input that is a view of a strided NT. + from torch._dynamo.exc import unimplemented + + # NOTE this graph break will NOT be present in Dynamo's graph break registry + unimplemented( + gb_type="attempted to apply meta conversion to strided nested tensor", + context=str(t), + explanation="This is not supported.", + hints=[], + ) + elif t.is_mkldnn: + is_leaf = t.is_leaf + ( + sizes, + strides, + _storage_offset, + ) = sym_sizes_strides_storage_offset(t, source) + # TODO: This doesn't seem right, where's the MKLDNN'ness + # lol + r = callback( + lambda: torch.empty_strided( + sizes, strides, dtype=t.dtype, device="meta" + ) + ) + if self.copy_data: + with torch.no_grad(), no_dispatch(): + if t.size is None: + raise AssertionError( + "t.size must not be None when copy_data is True" + ) + if t.stride is None: + raise AssertionError( + "t.stride must not be None when copy_data is True" + ) + if not is_fake_tensor(r): + raise AssertionError("Expected r to be a FakeTensor") + real_tensor = torch.empty_strided( + t.size, t.stride, dtype=t.dtype, device=t.device + ) + # pyrefly: ignore[missing-attribute] + r.real_tensor = real_tensor + if t.data is None: + raise AssertionError( + "t.data must not be None when copy_data is True" + ) + _safe_copy(real_tensor, t.data) + if not safe_is_leaf(r): + raise AssertionError( + "the callback you passed in doesn't detach" + ) + if t.requires_grad: + r.requires_grad = True + if t.requires_grad and not is_leaf: + r = self._backward_error(r) + elif t.is_functorch_wrapped: + if t.is_view: + from torch._dynamo.exc import unimplemented + + unimplemented( + gb_type="attempted to apply meta conversion to view functorch tensor", + context=str(t), + explanation="This is not supported.", + hints=[], + ) + + # Wraps a functorch tensor class (BatchedTensor, GradTrackingTensor) + # in a FakeTensor + def _to_fake_tensor(t: MetaTensorDesc[Any]) -> _TensorT: + # TODO: why aren't the recursive calls going to + # meta_tensor + r: _TensorT + if t.is_batchedtensor: + if t.unwrapped is None: + raise AssertionError( + "t.unwrapped must not be None for batchedtensor" + ) + if t.level is None: + raise AssertionError( + "t.level must not be None for batchedtensor" + ) + if t.bdim is None: + raise AssertionError( + "t.bdim must not be None for batchedtensor" + ) + ft = _to_fake_tensor(t.unwrapped) + lvl = t.level + bdim = t.bdim + # You cannot create functorch tensors without + # having the ambient funtorch interpreter stack + # available, as the level refers to things in the + # stack + with torch._functorch.pyfunctorch.temporarily_restore_interpreter_stack( + t.functorch_stack + ): + r = self._checked_cast_tensor_t( + _add_batch_dim(ft, bdim, lvl) + ) + elif t.is_gradtrackingtensor: + if t.unwrapped is None: + raise AssertionError( + "t.unwrapped must not be None for gradtrackingtensor" + ) + if t.level is None: + raise AssertionError( + "t.level must not be None for gradtrackingtensor" + ) + disable_functorch = torch._C._DisableFuncTorch + with disable_functorch(): + ft = _to_fake_tensor(t.unwrapped) + lvl = t.level + if lvl == GRAD_TENSOR_SENTINEL_VALUE: + r = ft + else: + with torch._functorch.pyfunctorch.temporarily_restore_interpreter_stack( + t.functorch_stack + ): + r = self._checked_cast_tensor_t( + torch._C._functorch._wrap_for_grad(ft, lvl), + ) + + is_leaf = t.is_leaf + if t.requires_grad and safe_is_leaf(r): + r.requires_grad = True + elif t.requires_grad and not is_leaf: + r = self._backward_error(r) + elif t.is_functional: + if t.unwrapped is None: + raise AssertionError( + "t.unwrapped must not be None for functional tensor" + ) + if t.current_level is None: + raise AssertionError( + "t.current_level must not be None for functional tensor" + ) + ft = self.meta_tensor( + t.unwrapped, + shape_env, + callback, + # NB: reuse these exactly, we treat the + # functional tensor as "invisible". + # TODO: Actually this all probably doesn't + # work, take a closer look. + source, + symbolic_context, + ) + r = self._checked_cast_tensor_t( + _wrap_functional_tensor(ft, t.current_level), + ) + # TODO: is_leaf/requires_grad? + else: + if t.stride is None: + raise AssertionError("t.stride must not be None") + + sizes = t.size + strides = t.stride + r = callback( + lambda: torch.empty_strided( + sizes, + strides, + dtype=t.dtype, + device="meta", + ), + # device="meta", + ) + if self.copy_data: + with torch.no_grad(), no_dispatch(): + r.real_tensor = torch.empty_strided( # type: ignore[attr-defined] + t.size, + t.stride, + dtype=t.dtype, + device=t.device, + ) + if t.data is None: + raise AssertionError( + "t.data must not be None when copy_data is True" + ) + _safe_copy(r.real_tensor, t.data) # type: ignore[attr-defined] + # pyrefly: ignore [bad-return] + return r + + r = _to_fake_tensor(t) + + elif t.is_functional and t.device.type not in ["xla", "lazy"]: + if t.unwrapped is None: + raise AssertionError( + "t.unwrapped must not be None for functional tensor" + ) + if t.is_functorch_wrapped: # handled above + raise AssertionError( + "Expected non-functorch wrapped functional tensor" + ) + unwrapped = self.meta_tensor( + t.unwrapped, + shape_env, + callback, + source, + symbolic_context, + ) + r = self._checked_cast_tensor_t( + torch._to_functional_tensor(unwrapped) + ) + torch._mirror_autograd_meta_to(t.autograd_meta_from, r) # type: ignore[attr-defined] + + elif t.is_view: + # Construct views in two steps: recursively meta-fy their + # base, and then create view(s) off that. NB: doing it + # directly from storage is WRONG because this won't cause + # version counters to get shared. + + if t.base is None: + raise AssertionError("t.base must not be None for view tensor") + + base_symbolic_context = None + if shape_env and symbolic_context is not None: + from torch.fx.experimental.symbolic_shapes import ( + StatelessSymbolicContext, + ) + + if not isinstance(symbolic_context, StatelessSymbolicContext): + raise AssertionError( + f"Expected StatelessSymbolicContext, got {type(symbolic_context)}" + ) + # NB: This should generally be set when the input is a view, + # but the exception right now is for fake-ifying grads, which is + # a work in progress. + if symbolic_context.view_base_context is not None: + base_symbolic_context = symbolic_context.view_base_context + + # We don't track the example values of base tensors. + # Allocation of unbacked symbols can happen when mark_unbacked + # is called on a base tensor that have unbacked_indices. + with ( + shape_env.ignore_fresh_unbacked_symbols() + if shape_env + else contextlib.nullcontext() + ): + base = self.meta_tensor( + t.base, + shape_env, + callback, + torch._dynamo.source.AttrSource(source, "_base"), + base_symbolic_context, + ) + + def is_c_of_r( + complex_dtype: torch.dtype, real_dtype: torch.dtype + ) -> bool: + return ( + utils.is_complex_dtype(complex_dtype) + and utils.corresponding_real_dtype(complex_dtype) + == real_dtype + ) + + # In some situations, MetaConverter may be called in a + # context where autograd is disabled. For the _is_view + # assert to pass, we have to setup the autograd view + # metadata anyway. Do this by reenabling the + # ADInplaceOrView key. This is kind of a hack. + old_exclude = torch._C._dispatch_tls_is_dispatch_key_excluded( + torch._C.DispatchKey.ADInplaceOrView + ) + torch._C._dispatch_tls_set_dispatch_key_excluded( + torch._C.DispatchKey.ADInplaceOrView, False + ) + try: + if base.dtype == t.dtype: + pass + elif is_c_of_r(base.dtype, t.dtype): + base = self._checked_cast_tensor_t(torch.view_as_real(base)) + elif is_c_of_r(t.dtype, base.dtype): + base = self._checked_cast_tensor_t( + torch.view_as_complex(base) + ) + else: + # This is not guaranteed to succeed. If it fails, it + # means there is another dtype-converting view function + # that hasn't been handled here + base = self._checked_cast_tensor_t(base.view(t.dtype)) + + # This is very tricky. Naively, you might expect this + # to hold: + # + # if t.requires_grad and not safe_is_leaf(t) + # assert t._base.requires_grad + # + # But it's not true! As you can see in the following + # program: + # + # x = torch.zeros(4) + # y = x.view(1, 4) + # y.requires_grad = True + # z = y.view(1, 1, 4) + # assert z._base is x + # + # So we may have to do *two* views out of the base to + # recreate this situation. + if t.is_leaf: + # Leaf views that track view metadata are created by + # creating a view inside a no_grad block + with torch.no_grad(): + r = view_from_base(base, t) + # As it's a leaf, we can directly assign requires_grad + r.requires_grad = t.requires_grad + else: + if t.base.requires_grad == t.requires_grad: + # Easy case, just run the view op + with torch.enable_grad(): + r = view_from_base(base, t) + + # NB: We don't actually faithfully replicate + # autograd connectivity, but that doesn't matter + # today. See following for more info: + # https://gist.github.com/soulitzer/e03f015b314c3f5fcf80888c69390913 + else: + # Obscure case. Create a leaf view and give it the + # correct requires_grad, then do the final view. + # NB: Can't have a non-leaf without requiring grad! + if not t.requires_grad: + raise AssertionError( + "t.requires_grad must be True for non-leaf view" + ) + with torch.no_grad(), enable_python_dispatcher(): + mid = self._checked_cast_tensor_t( + base.view(base.shape) + ) + mid.requires_grad = t.requires_grad + with torch.enable_grad(): + r = view_from_base(mid, t) + # The CreationMeta influences whether or not inplace + # mutation is an error or not. So we need to make + # sure we properly propagate this as well. + if t.creation_meta is None: + raise AssertionError( + "t.creation_meta must not be None for view tensor" + ) + torch._C._autograd._set_creation_meta(r, t.creation_meta) + finally: + torch._C._dispatch_tls_set_dispatch_key_excluded( + torch._C.DispatchKey.ADInplaceOrView, old_exclude + ) + + r.fake_device = t.device # type: ignore[attr-defined] + + else: + is_leaf = t.is_leaf + + # Graph-Break for wrapped tensors + if ( + not (t.is_batchedtensor or t.is_gradtrackingtensor) + and t.is_functorch_wrapped + ) or t.is_legacy_batchedtensor: + # pyrefly: ignore [bad-return] + return NotImplemented + + ( + sizes, + strides, + storage_offset, + ) = sym_sizes_strides_storage_offset(t, source, symbolic_context) + + # If we have a subclass that desugars into dense tensors, + # perform our callback on each inner tensor. + if t.is_traceable_wrapper_subclass: + r = empty_create_subclass( + t, outer_size=sizes, outer_stride=strides + ) + else: + r = callback( + lambda: torch.empty_strided( + sizes, + strides, + dtype=t.dtype, + device="meta", + ) + ) + if self.copy_data: + with torch.no_grad(), no_dispatch(): + if t.size is None: + raise AssertionError( + "t.size must not be None when copy_data is True" + ) + if t.stride is None: + raise AssertionError( + "t.stride must not be None when copy_data is True" + ) + if not is_fake_tensor(r): + raise AssertionError( + "Expected r to be a FakeTensor" + ) + real_tensor = torch.empty_strided( + t.size, t.stride, dtype=t.dtype, device=t.device + ) + # pyrefly: ignore[missing-attribute] + r.real_tensor = real_tensor + _safe_copy(real_tensor, t.data) + + if not safe_is_leaf(r): + raise AssertionError( + "the callback you passed in doesn't detach" + ) + if t.requires_grad: + r.requires_grad = t.requires_grad + if not is_leaf: + # Fake up some autograd history. + # Note: we *used* to call .clone() here to mock up some autograd history. + # This is bad for subclasses. + # Consider the case where you have a wrapper subclass that is contiguous, + # but its inner tensor is noncontiguous(). + # .clone() (or other ops) will have the side effect of changing + # the metadata of the inner tensor. + # So instead, we now have a dedicated fn to set autograd history, + # without inadvertently changing other metadata. + # pyrefly: ignore [bad-argument-type] + r = self._backward_error(r) + + # Storage aliasing for traceable wrapper subclasses is tracked + # through their inner tensors. Memoizing the wrapper placeholder + # storage can later force a cross-device set_ on the wrapper. + if not t.is_traceable_wrapper_subclass: + s = t.storage + if s is None: + raise AssertionError("t.storage must not be None") + from torch.fx.experimental.symbolic_shapes import ( + guard_or_false, + sym_eq, + ) + + storage_needs_resize = False + source_storage_size = s.size + source_storage_is_zero = ( + isinstance(source_storage_size, int) + and source_storage_size == 0 + ) + if not r.is_nested: + r_storage = r.untyped_storage() + r_storage_size = r_storage.size() + if isinstance(r_storage_size, int) and isinstance( + source_storage_size, int + ): + storage_needs_resize = ( + source_storage_size != 0 + and r_storage_size < source_storage_size + ) + if s.id not in self.storage_memo and ( + r.is_nested + or ( + guard_or_false(sym_eq(r.stride(), strides)) + and guard_or_false(r.storage_offset() == storage_offset) + ) + ): + if not r.is_nested: + # The freshly allocated tensor storage can stand in + # for the source storage only if it covers the whole + # storage. Parameters made from views are not + # autograd views, but can still share a larger + # storage with later parameters. Leave symbolic + # sizes alone; this preserves the fast path for + # dynamic inputs without adding storage-size guards. + # Zero-sized source storages are handled by the + # resize_(0) below. + if storage_needs_resize: + r.untyped_storage().resize_(s.size) + # You're normal and happy, install the fresh storage into the memo + self.set_storage_memo(s, r.untyped_storage()) + if self.copy_data: + if not is_fake_tensor(r): + raise AssertionError( + "Expected r to be a FakeTensor" + ) + r_real_tensor = maybe_get_real_tensor(r) + if r_real_tensor is None: + raise AssertionError( + "r.real_tensor must not be None when copy_data is True" + ) + if source_storage_is_zero: + _set_real_storage( + r.untyped_storage(), + r_real_tensor.untyped_storage(), + ) + else: + if t.size is None: + raise AssertionError( + "t.size must not be None when copy_data is True" + ) + if t.stride is None: + raise AssertionError( + "t.stride must not be None when copy_data is True" + ) + if t.data is None: + raise AssertionError( + "t.data must not be None when copy_data is True" + ) + with torch.no_grad(), no_dispatch(): + real_storage = _clone_real_storage_from_tensor( + t.data + ) + _set_real_storage( + r.untyped_storage(), real_storage + ) + r_real_tensor.set_( + real_storage, + t.storage_offset, + t.size, + t.stride, + ) + else: + # You're in crazy town; somehow you gave us a tensor + # that wasn't a view, but had nonzero storage offset, + # nontrivial strides (such that clone() couldn't + # preserve them), or already aliases with another + # tensor's storage. The most typical way to end + # up here is with set_. So use set_ to bludgeon this + # in. + r_s = self.meta_storage(s, callback=callback) + # NB: In principle, this should always work, but there + # is some subtle difference in the autograd metadata + # that means we will backprop the set_ call, even if + # r is declared as an input to grad. + # See https://github.com/pytorch/pytorch/issues/87956 + # for the reproducer. + # NB: The in_kernel_invocation_manager here is necessary + # for fake tensor. If we run the set_ call with fake + # tensor on, r will improperly report that it is NOT a + # meta tensor but a cpu tensor, and then the set_ call + # will fail due to device mismatch. no_dispatch() is + # not enough, because the fake tensor will still claim + # to be a CPU tensor and you'll end up in the CPU + # kernel. Arguably this is a hack; a cleaner way to + # solve this is to have a FakeStorage concept which + # would report it's CPU device--no problem now! But + # this is difficult to do because we don't have storage + # subclasses. Relevant test is + # DynamicShapesFunctionTests::test_add_dynamic_shapes in + # test/dynamo/test_dynamic_shapes.py + maybe_fake_mgr: AbstractContextManager[None] = ( + contextlib.nullcontext() + ) + from torch._subclasses.fake_tensor import ( + in_kernel_invocation_manager, + maybe_get_fake_mode, + ) + + mb_fake_mode = maybe_get_fake_mode(r) + if mb_fake_mode is not None: + maybe_fake_mgr = in_kernel_invocation_manager( + mb_fake_mode + ) + with torch.no_grad(), maybe_suppress(): + with maybe_fake_mgr: + r.set_(r_s, storage_offset, sizes, strides) + if self.copy_data: + with torch.no_grad(), no_dispatch(): + if not is_fake_tensor(r): + raise AssertionError( + "Expected r to be a FakeTensor" + ) + r_real_tensor = maybe_get_real_tensor(r) + if r_real_tensor is None: + raise AssertionError( + "r.real_tensor must not be None when copy_data is True" + ) + if t.stride is None: + raise AssertionError( + "t.stride must not be None when copy_data is True" + ) + r_real_tensor.set_( + _get_real_storage(r_s), + t.storage_offset, + t.size, + t.stride, + ) + + if t.grad is not None: + from torch._dynamo.source import AttrSource + + grad_source = AttrSource(source, "grad") + grad_symbolic_context = symbolic_context + + # The param's symbolic_context may be incompatible with the + # grad when they have different view base dimensionalities. + # This happens in FSDP2 where param._local_tensor is a view + # of an N-D padded base but grad._local_tensor is a view of + # a 1-D flat gradient buffer. Build a fresh context only in + # that case to preserve FX graph cache consistency. + if shape_env is not None and symbolic_context is not None: + if not _grad_context_compatible(symbolic_context, t.grad): + grad_symbolic_context = all_dynamic_symbolic_context( + t.grad, grad_source, shape_env, callback + ) + + # pyrefly: ignore [unbound-name] + r.grad = self.meta_tensor( + t.grad, + shape_env, + callback, + grad_source, + grad_symbolic_context, + ) + # pyrefly: ignore [unbound-name] + torch._C._set_conj(r, t.is_conj) + # pyrefly: ignore [unbound-name] + torch._C._set_neg(r, t.is_neg) + # This can be skipped if necessary for performance reasons + skip_leaf = ( + t.is_gradtrackingtensor and t.level == GRAD_TENSOR_SENTINEL_VALUE + ) + # pyrefly: ignore [unbound-name] + assert_metadata_eq(assert_eq, t, r, skip_symbolic=True, skip_leaf=skip_leaf) + # Thanks to storage resizing, it's possible to end up with a tensor + # that advertises a real size, but has a storage that actually has zero bytes. + # Need to reflect this in the generated FakeTensor. + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if t.storage is not None and guard_or_false(t.storage.size == 0): + # pyrefly: ignore [unbound-name] + r.untyped_storage().resize_(0) + + if t.is_parameter: + # pyrefly: ignore [unbound-name] + r._is_param = True + + # See Note: [Creating symbolic nested int] + if t.nested_int is not None: + # pyrefly: ignore [unbound-name] + if not is_fake_tensor(r): + raise AssertionError("Expected r to be a FakeTensor for nested int") + # pyrefly: ignore [unbound-name, missing-attribute] + r.nested_int_memo = r.fake_mode.create_symbolic_nested_int( + nt_tensor_id=t.nested_int + ) + + # pyrefly: ignore [bad-argument-type, unbound-name] + self.set_tensor_memo(t, r) + + return self._checked_get_tensor_memo(t) + + def __call__( + self, + t: torch.Tensor, + shape_env: ShapeEnv | None = None, + *, + callback: _MetaTensorCallback[_TensorT] | None = None, + source: Source | None = None, + symbolic_context: SymbolicContext | None = None, + # Controls whether or not we should dump the tensor metadata to structured logs + # when source is not None. Because we refakify after Dynamo is done, + # we don't want to dump info again from AOTAutograd, it is redundant. + trace: bool = True, + ) -> _TensorT: + callback_: _MetaTensorCallback[_TensorT] + if callback is None: + callback_ = self._identity_callable + else: + callback_ = callback + # TODO: zero tensors? We appear to have eliminated them by + # excluding complex for now + + # Filter out cases we don't support + # TODO: This can probably be simplified quite a bit + if isinstance(t, torch.Tensor): + if ( + # Lazy tensors are not supported. Note that XLA is + # implemented on top of lazy tensor, not excluded here; we + # have some special handling for it; this is for XLA Dynamo + # integration + t.device.type == "lazy" + or + # Quantization is not supported + t.is_quantized + or + # Views out of sparse tensors not currently supported (plain + # sparse is supported though) + (t._is_view() and t._base is not None and t._base.is_sparse) + ): + self.miss += 1 + # pyrefly: ignore [bad-return] + return NotImplemented + else: + self.hit += 1 + elif torch.overrides.is_tensor_like(t): + self.miss += 1 + # pyrefly: ignore [bad-return] + return NotImplemented + else: + # non-Tensor types don't count as hit or miss + return t + + if source is None: + trace = False + + # Describe the tensor. NB: do NOT disable ambient modes, we may need + # to query them when figuring out what to put in here + t_desc = self.describer.describe_tensor(t, trace=trace) + + if trace: + if source is None: + raise AssertionError("source must not be None when trace is True") + trace_structured( + "describe_source", + metadata_fn=lambda: { + "describer_id": self.describer.id, + "id": t_desc.id, + "source": source.name, + }, + ) + + # Do the meta-fication. Here, we disable all the ambient modes, to + # better simulate what would be like to re-fakeify from a fresh + # process + with contextlib.ExitStack() as exit_stack: + exit_stack.enter_context(torch._dispatch.python.suspend_functionalization()) + st = peek_interpreter_stack() + if st is not None: + exit_stack.enter_context( + torch._functorch.pyfunctorch.temporarily_clear_interpreter_stack() + ) + + r = self.meta_tensor( + t_desc, + shape_env, + callback_, + source, + symbolic_context, + ) + + if type(t) is torch.nn.Parameter: + # NB: Cannot directly use Parameter constructor + # because that would force a detach, not desirable + r._is_param = True + + # forward the 'is_buffer' metadata if present (for nn.Buffer checks) + if getattr(t, "_is_buffer", False): + # pyrefly: ignore [missing-attribute] + r._is_buffer = True + if hasattr(t, "persistent"): + # pyrefly: ignore [missing-attribute] + r.persistent = t.persistent + + # TODO: return the description for later + return r + + +import torch._prims_common as utils diff --git a/.venv/lib/python3.12/site-packages/torch/_subclasses/schema_check_mode.py b/.venv/lib/python3.12/site-packages/torch/_subclasses/schema_check_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..0c46f73600c399ab5649b76e2bc6e892beb99ee0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_subclasses/schema_check_mode.py @@ -0,0 +1,260 @@ +from __future__ import annotations + +from copy import deepcopy +from itertools import combinations +from typing import Any, NamedTuple, TYPE_CHECKING + +import torch +from torch.fx.operator_schemas import _normalize_function_or_error +from torch.utils import _pytree as pytree +from torch.utils._python_dispatch import TorchDispatchMode +from torch.utils._pytree import tree_map + + +if TYPE_CHECKING: + from collections.abc import Iterable + + from torch._ops import OpOverload + + +class Mutation(NamedTuple): + op_name: str + arg_name: str + + +class Aliasing(NamedTuple): + op_name: str + arg_name: str + output_number: str + + +# Simplified naming for C++ classes +# pyrefly: ignore [missing-attribute] +SchemaArgument = torch._C._SchemaArgument +# pyrefly: ignore [missing-attribute] +SchemaArgType = torch._C._SchemaArgType +SchemaInfo = torch._C._SchemaInfo + +# This TorchDispatchMode Subclass is used to verify op schemas +# This TorchDispatchMode Subclass currently: +# - Records the called ops +# - Checks for mutations on all inputs +# - Checks for aliasing on all inputs + + +# move these 2 functions here to avoid numpy dependency in testing/_internal/common_utils.py + + +def is_iterable_of_tensors(iterable: Iterable[Any]) -> bool: + # Tensor itself is iterable so we check this first + if isinstance(iterable, torch.Tensor): + return False + try: + # pyrefly: ignore[bad-argument-type] + if len(iterable) == 0: + return False + for t in iter(iterable): + if not isinstance(t, torch.Tensor): + return False + except TypeError: + return False + return True + + +def clone_inputs(args: Iterable[Any]) -> list[Any]: + inputs: list[Any] = [] + + for arg in args: + if isinstance(arg, torch.Tensor): + inputs.append(arg.detach().clone()) + elif is_iterable_of_tensors(arg): + inputs.append([t.detach().clone() for t in arg]) + else: + inputs.append(arg) + + return inputs + + +class SchemaCheckMode(TorchDispatchMode): + def __init__(self) -> None: + # Information recorded for testing purposes. For example: + # - incorrect schemas + # - overly conservative schemas + self.ops: list[str] = [] + self.mutated: list[Mutation] = [] + self.aliasing: list[Aliasing] = [] + + def reset_cache(self) -> None: + self.ops.clear() + self.mutated.clear() + self.aliasing.clear() + + def display_ops(self) -> None: + print(*self.ops, sep=",") + + def __torch_dispatch__( + self, + func: OpOverload, + types: tuple[type[Any], ...], + args: tuple[Any, ...] = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + def bitwise_equal(lhs: torch.Tensor, rhs: torch.Tensor) -> bool: + if lhs.is_quantized: + # TODO: This is only OK if can't have NaN quantized; idk if + # this is actually true + return torch.equal(lhs, rhs) + else: + return torch.allclose(lhs, rhs, equal_nan=True) + + def has_mutated( + before: Any, after: Any, md: tuple[tuple[int, ...], int] | None + ) -> bool: + are_tensors = type(before) is torch.Tensor and type(after) is torch.Tensor + if ( + are_tensors + and before.layout != torch.sparse_csr + and after.layout != torch.sparse_csr + ): + return md is not None and not ( + before.size() == after.size() + and bitwise_equal(before, after) + and md[0] == after.stride() + and md[1] == after._typed_storage()._cdata + ) + return False + + def has_aliased(lhs: Any, rhs: Any) -> bool: + try: + # pyrefly: ignore [missing-attribute] + return torch._C._overlaps(lhs, rhs) + except Exception as exception: + if str(exception).startswith("Cannot inspect value of type "): + return False + else: + raise exception + + def standardize_name(name: str) -> str: + return name if name != "self" else "input" + + def unwrap(e: Any) -> Any: + if isinstance(e, torch.Tensor) and type(e) is not torch.Tensor: + try: + # pyrefly: ignore[missing-attribute] + return e.elem + except AttributeError: + return e + return e + + def parse_metadata(e: Any) -> tuple[tuple[int, ...], int] | None: + if isinstance(e, torch.Tensor): + if type(e) is not torch.Tensor: + try: + # pyrefly: ignore[missing-attribute] + current = e.elem + return ( + deepcopy(current.stride()), + current._typed_storage()._cdata, + ) + except AttributeError: + return None + # Sparse CSR tensors do not have strides or storage + elif e.layout != torch.sparse_csr: + return (deepcopy(e.stride()), e._typed_storage()._cdata) + return None + + self.ops.append(func._schema.name) + + # Clone and process arguments and outputs + pre_arguments = _normalize_function_or_error( + func, args, kwargs, normalize_to_only_use_kwargs=True + ).kwargs + + c_p_args = dict(zip(pre_arguments.keys(), clone_inputs(pre_arguments.values()))) + cloned_arguments = { + name: tree_map(unwrap, c_p_args.get(name)) for name in c_p_args + } + cloned_metadata = { + name: [ + parse_metadata(a) for a in pytree.tree_leaves(pre_arguments.get(name)) + ] + for name in pre_arguments + } + + out = func(*args, **kwargs) + arguments = { + name: tree_map(unwrap, pre_arguments.get(name)) for name in pre_arguments + } + tuple_out = out if isinstance(out, tuple) else (out,) + tuple_out = tree_map(unwrap, tuple_out) + + schema_info = SchemaInfo(func._schema) + # pyrefly: ignore [missing-attribute] + schema_info.add_argument_values(pre_arguments) + + # Process arguments with outputs + for i in range(len(func._schema.arguments)): + arg = func._schema.arguments[i] + name = standardize_name(arg.name) + if arguments.get(name) is not None: + before = cloned_arguments.get(name) + md = cloned_metadata.get(name) + after = arguments.get(name) + for j in range(len(tuple_out)): + # aten::_unsafe_view is intended to have incorrect aliasing notation (hence unsafe) + unsafe_ops = ("aten::_unsafe_view", "aten::unsafe_split") + if ( + has_aliased(tuple_out[j], after) + and func._schema.name not in unsafe_ops + ): + # pyrefly: ignore [missing-attribute] + if not schema_info.may_contain_alias( + SchemaArgument(SchemaArgType.output, j), + SchemaArgument(SchemaArgType.input, i), + ): + raise RuntimeError( + f"Argument {name} is not defined to alias output but was aliasing" + ) + else: + self.aliasing.append( + Aliasing(func._schema.name, name, f"output_{j}") + ) + if after is tuple_out[j] and isinstance(after, torch.Tensor): + # Only mutable ops e.g. (add_, add.out) are allowed to directly return inputs. + if not schema_info.is_mutable( + SchemaArgument(SchemaArgType.input, i) + ) and func not in [ + torch.ops.aten.lift.default, + torch.ops.aten.lift_fresh.default, + ]: + raise RuntimeError( + f"""\ +Dispatcher operators below autograd are not allowed to directly return inputs. +However, we found that `outputs[{str(j)}] is {name}""" + ) + if md is not None and any( + has_mutated(a, b, c) + for a, b, c in zip( + pytree.tree_leaves(before), pytree.tree_leaves(after), md + ) + ): + if not schema_info.is_mutable( + SchemaArgument(SchemaArgType.input, i) + ): + raise RuntimeError( + f"Argument {name} is not defined as mutable but was mutated" + ) + else: + self.mutated.append(Mutation(func._schema.name, name)) + + # Aliasing between outputs + for i, j in combinations(range(len(func._schema.returns)), 2): + if has_aliased(tuple_out[i], tuple_out[j]): + # pyrefly: ignore [missing-attribute] + if not schema_info.may_contain_alias( + SchemaArgument(SchemaArgType.output, i), + SchemaArgument(SchemaArgType.output, j), + ): + raise RuntimeError(f"Outputs {i} and {j} alias unexpectedly") + + return out diff --git a/.venv/lib/python3.12/site-packages/torch/_tensor.py b/.venv/lib/python3.12/site-packages/torch/_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..e346bccf14b677e27f2244ff0244e2c3d81c3dc9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_tensor.py @@ -0,0 +1,1746 @@ +# mypy: allow-untyped-defs +import copyreg +import enum +import functools +import itertools +import warnings +from collections import OrderedDict +from collections.abc import Callable +from copy import deepcopy +from numbers import Number +from typing import Any, cast, Concatenate, TypeVar, Union +from typing_extensions import ParamSpec + +import torch +import torch._C as _C +from torch.overrides import ( + get_default_nowrap_functions, + handle_torch_function, + has_torch_function, + has_torch_function_unary, + has_torch_function_variadic, +) + + +_P = ParamSpec("_P") +_TensorLike = TypeVar("_TensorLike", bound=_C.TensorBase) + + +def _handle_torch_function_and_wrap_type_error_to_not_implemented( + f: Callable[Concatenate[_TensorLike, _P], "Tensor"], +) -> Callable[Concatenate[_TensorLike, _P], "Tensor"]: + @functools.wraps(f) + def wrapped(self: _TensorLike, *args: _P.args, **kwargs: _P.kwargs) -> "Tensor": + try: + # See https://github.com/pytorch/pytorch/issues/75462 + sargs = self, *args + if has_torch_function(sargs): + return handle_torch_function(wrapped, sargs, self, *args, **kwargs) + return f(self, *args, **kwargs) + except TypeError: + return NotImplemented + + return wrapped + + +# Should not be used, this is kept only for BC of loading old serialized Tensor subclasses +def _rebuild_from_type(func, type, args, dict): + if type is Tensor: + return func(*args) + + ret = func(*args).as_subclass(type) + ret.__dict__ = dict + return ret + + +def _rebuild_from_type_v2(func, new_type, args, state): + ret = func(*args) + if type(ret) is not new_type: + ret = ret.as_subclass(new_type) + # Tensor does define __setstate__ even though it doesn't define + # __getstate__. So only use __setstate__ if it is NOT the one defined + # on Tensor + if ( + getattr(ret.__class__, "__setstate__", Tensor.__setstate__) + is not Tensor.__setstate__ + ): + ret.__setstate__(state) + else: + ret = torch._utils._set_obj_state(ret, state) + return ret + + +def _dtype_to_typestr(dtype): + # CUDA devices are little-endian and tensors are stored in native byte + # order. 1-byte entries are endian-agnostic. + return { + torch.complex64: " torch.TypedStorage + + Returns the underlying :class:`TypedStorage`. + + .. warning:: + + :class:`TypedStorage` is deprecated. It will be removed in the future, and + :class:`UntypedStorage` will be the only storage class. To access the + :class:`UntypedStorage` directly, use :attr:`Tensor.untyped_storage()`. + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.storage, (self,), self) + + torch.storage._warn_typed_storage_removal(stacklevel=2) + return self._typed_storage() + + # For internal use only, to avoid raising deprecation warning + def _typed_storage(self): + untyped_storage = self.untyped_storage() + return torch.TypedStorage( + wrap_storage=untyped_storage, dtype=self.dtype, _internal=True + ) + + def _reduce_ex_internal(self, proto): + from torch.utils.hooks import warn_if_has_hooks + + # See Note [Don't serialize hooks] + warn_if_has_hooks(self) + backward_hooks: dict[Any, Any] = OrderedDict() + + skip_data = torch.serialization._serialization_tls.skip_data + materialize_fake_tensors = ( + torch.serialization._serialization_tls.materialize_fake_tensors + ) + + if self.device.type in ["xla", "maia", "mtia"] or ( + not torch._C._has_storage(self) + and self.device.type == torch._C._get_privateuse1_backend_name() + ): + if skip_data: + raise RuntimeError( + "Cannot serialize tensors on backends with no storage under skip_data context manager" + ) + cpu_tensor = self.cpu() + return ( + torch._utils._rebuild_device_tensor_from_cpu_tensor, + (cpu_tensor, self.dtype, str(self.device), self.requires_grad), + ) + if self.device.type == "meta": + # NB: This implementation BREAKS storage sharing. Current + # hypothesis is that no one cares for meta tensors. + if skip_data: + warnings.warn( + "Serializing tensors on the meta device under skip_data context manager is a no-op", + stacklevel=2, + ) + arg_meta = ( + self.dtype, + tuple(self.size()), + self.stride(), + self.requires_grad, + ) + return (torch._utils._rebuild_meta_tensor_no_storage, arg_meta) + if self.is_quantized: + if skip_data: + raise RuntimeError( + "Cannot serialize qtensor under skip_data context manager, file an issue if you need this feature" + ) + # quantizer_params can be different type based on torch attribute + quantizer_params: ( + tuple[torch.qscheme, float, int] | tuple[Any, Tensor, Tensor, int] + ) + if self.qscheme() == torch.per_tensor_affine: + quantizer_params = ( + torch.per_tensor_affine, + self.q_scale(), + self.q_zero_point(), + ) + elif self.qscheme() in ( + torch.per_channel_affine, + torch.per_channel_affine_float_qparams, + ): + # convert scales and zero points to tuple to avoid recursive calls + # when/if we get multi-axis quantized tensors in the future, the shape + # is recoverable from the main tensor shape + quantizer_params = ( + torch.per_channel_affine, + self.q_per_channel_scales(), + self.q_per_channel_zero_points(), + self.q_per_channel_axis(), + ) + else: + raise RuntimeError( + f"Serialization is not supported for tensors of type {self.qscheme()}" + ) + # TODO: Once we decide to break serialization FC, no longer + # need to wrap with TypedStorage + args_qtensor = ( + torch.storage.TypedStorage( + wrap_storage=self._typed_storage()._untyped_storage, + dtype=self.dtype, + _internal=True, + ), + self.storage_offset(), + tuple(self.size()), + self.stride(), + quantizer_params, + self.requires_grad, + backward_hooks, + ) + return (torch._utils._rebuild_qtensor, args_qtensor) + elif self.is_sparse: + if self.layout == torch.sparse_coo: + args_sparse = ( + self.layout, + (self._indices(), self._values(), self.size(), self.is_coalesced()), + ) + else: + raise NotImplementedError( + f"sparse tensor __reduce_ex__ for layout `{self.layout}`" + ) + return (torch._utils._rebuild_sparse_tensor, args_sparse) + elif self.layout in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + }: + if self.layout in {torch.sparse_csr, torch.sparse_bsr}: + compressed_indices, plain_indices = ( + self.crow_indices(), + self.col_indices(), + ) + else: + compressed_indices, plain_indices = ( + self.ccol_indices(), + self.row_indices(), + ) + args_sparse_compressed = ( + self.layout, + ( + compressed_indices, + plain_indices, + self.values(), + self.size(), + ), + ) + return (torch._utils._rebuild_sparse_tensor, args_sparse_compressed) + elif self.is_nested: + if skip_data: + raise RuntimeError( + "Cannot serialize nested tensor under skip_data context manager, file an issue if you need this feature" + ) + args_nested = ( + # NB: values() currently returns the storage as a buffer in an unsafe way. + # Ideally, we'd use a private API for this instead. TODO: Switch to this if + # we ever get around to adding it. + self.values(), + self._nested_tensor_size(), + self._nested_tensor_strides(), + self._nested_tensor_storage_offsets(), + ) + return (torch._utils._rebuild_nested_tensor, args_nested) + elif ( + type(self) is not torch.Tensor + and type(self).__torch_dispatch__ is not torch.Tensor.__torch_dispatch__ + and ( + isinstance(self, torch._subclasses.functional_tensor.FunctionalTensor) + or ( + not torch._subclasses.fake_tensor.is_fake_tensor(self) + and self.data_ptr() == 0 + ) + ) + ): + arg_wrapper_subclass = ( + type(self), + self.dtype, + tuple(self.size()), + self.stride(), + self.storage_offset(), + self.layout, + self.device, + self.requires_grad, + ) + return (torch._utils._rebuild_wrapper_subclass, arg_wrapper_subclass) + elif ( + type(self) is not torch.Tensor + and type(self).__torch_dispatch__ is not torch.Tensor.__torch_dispatch__ + and ( + torch._subclasses.fake_tensor.is_fake_tensor(self) + and not (skip_data and materialize_fake_tensors) + ) + ): + arg_wrapper_subclass = ( + type(self), + self.dtype, + tuple(self.size()), + self.stride(), + self.storage_offset(), + self.layout, + self.device, + self.requires_grad, + ) + return (torch._utils._rebuild_wrapper_subclass, arg_wrapper_subclass) + else: + v3_dtypes = torch.storage._new_dtypes() + if self.dtype in v3_dtypes: + rebuild_func = torch._utils._rebuild_tensor_v3 + storage = self.untyped_storage() + else: + # TODO: Once we decide to break serialization FC, no longer + # need to wrap with TypedStorage + rebuild_func = torch._utils._rebuild_tensor_v2 # type: ignore[assignment] + storage = torch.storage.TypedStorage( + wrap_storage=self._typed_storage()._untyped_storage, + dtype=self.dtype, + _internal=True, + ) # type: ignore[assignment] + + # TODO: remove hasattr, it's a hack to support versions of torch that + # don't have _subclasses + if ( + hasattr(torch, "_subclasses") + and torch._subclasses.fake_tensor.is_fake_tensor(self) + and skip_data + ): + storage._fake_device = self.device + + args = ( + storage, + self.storage_offset(), + tuple(self.size()), + self.stride(), + self.requires_grad, + backward_hooks, + ) # previously was self._backward_hooks + + if isinstance(storage, torch.storage.UntypedStorage): + args = args + (self.dtype,) # type: ignore[assignment] + + metadata = torch._utils.get_tensor_metadata(self) + if metadata: + args = args + (metadata,) # type: ignore[assignment] + + return (rebuild_func, args) + + def __setstate__(self, state): + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__setstate__, (self,), self, state) + # Warning: this method is NOT called when you torch.load() a tensor; + # that is managed by _rebuild_tensor_v2 + if not self.is_leaf: + raise RuntimeError("__setstate__ can be only called on leaf Tensors") + if len(state) == 4: + # legacy serialization of Tensor + + self.set_(*state) + return + elif len(state) == 5: + # legacy serialization of Variable + self.data = state[0] + state = (state[3], state[4], state[2]) + # The setting of _backward_hooks is expected to be a no-op. + # See Note [Don't serialize hooks] + self.requires_grad, _, self._backward_hooks = state + + def __repr__(self, *, tensor_contents=None): + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.__repr__, (self,), self, tensor_contents=tensor_contents + ) + # All strings are unicode in Python 3. + return torch._tensor_str._str(self, tensor_contents=tensor_contents) + + def backward( + self, gradient=None, retain_graph=None, create_graph=False, inputs=None + ): + r"""Computes the gradient of current tensor wrt graph leaves. + + The graph is differentiated using the chain rule. If the tensor is + non-scalar (i.e. its data has more than one element) and requires + gradient, the function additionally requires specifying a ``gradient``. + It should be a tensor of matching type and shape, that represents + the gradient of the differentiated function w.r.t. ``self``. + + This function accumulates gradients in the leaves - you might need to zero + ``.grad`` attributes or set them to ``None`` before calling it. + See :ref:`Default gradient layouts` + for details on the memory layout of accumulated gradients. + + .. note:: + + If you run any forward ops, create ``gradient``, and/or call ``backward`` + in a user-specified CUDA stream context, see + :ref:`Stream semantics of backward passes`. + + .. note:: + + When ``inputs`` are provided and a given input is not a leaf, + the current implementation will call its grad_fn (though it is not strictly needed to get this gradients). + It is an implementation detail on which the user should not rely. + See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details. + + Args: + gradient (Tensor, optional): The gradient of the function + being differentiated w.r.t. ``self``. + This argument can be omitted if ``self`` is a scalar. Defaults to ``None``. + retain_graph (bool, optional): If ``False``, the graph used to compute the grads will be freed; + If ``True``, it will be retained. The default is ``None``, in which case the value is inferred from ``create_graph`` + (i.e., the graph is retained only when higher-order derivative tracking is requested). Note that in nearly all cases + setting this option to True is not needed and often can be worked around in a much more efficient way. + create_graph (bool, optional): If ``True``, graph of the derivative will + be constructed, allowing to compute higher order derivative + products. Defaults to ``False``. + inputs (Sequence[Tensor] or dict[str, Tensor], optional): Inputs w.r.t. which + the gradient will be accumulated into ``.grad``. All other tensors will be + ignored. If not provided, the gradient is accumulated into all the leaf + Tensors that were used to compute the :attr:`tensors`. A dict of tensors + (e.g. ``dict(model.named_parameters())``) is also accepted. + Defaults to ``None``. + """ + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.backward, + (self,), + self, + gradient=gradient, + retain_graph=retain_graph, + create_graph=create_graph, + inputs=inputs, + ) + torch.autograd.backward( + self, gradient, retain_graph, create_graph, inputs=inputs + ) + + def index(self, positions, dims): + """ + Index a regular tensor by binding specified positions to dims. + + This converts a regular tensor to a first-class tensor by binding + the specified positional dimensions to Dim objects. + + Args: + positions: Tuple of dimension positions to bind + dims: Dim objects or tuple of Dim objects to bind to + + Returns: + First-class tensor with specified dimensions bound + """ + # TODO: make it possible to dispatch on positions/dims + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.index, + (self,), + self, + positions, + dims, + ) + + from functorch.dim import index + + return index(self, positions, dims) + + def register_hook(self, hook): + r"""Registers a backward hook. + + The hook will be called every time a gradient with respect to the + Tensor is computed. The hook should have the following signature:: + + hook(grad) -> Tensor or None + + + The hook should not modify its argument, but it can optionally return + a new gradient which will be used in place of :attr:`grad`. + + This function returns a handle with a method ``handle.remove()`` + that removes the hook from the module. + + .. note:: + See :ref:`backward-hooks-execution` for more information on how when this hook + is executed, and how its execution is ordered relative to other hooks. + + Example:: + + >>> v = torch.tensor([0., 0., 0.], requires_grad=True) + >>> h = v.register_hook(lambda grad: grad * 2) # double the gradient + >>> v.backward(torch.tensor([1., 2., 3.])) + >>> v.grad + + 2 + 4 + 6 + [torch.FloatTensor of size (3,)] + + >>> h.remove() # removes the hook + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.register_hook, (self,), self, hook) + if not self.requires_grad: + raise RuntimeError( + "cannot register a hook on a tensor that doesn't require gradient" + ) + if self._backward_hooks is None: + self._backward_hooks = OrderedDict() + if self.grad_fn is not None: + self.grad_fn._register_hook_dict(self) + + from torch.utils.hooks import RemovableHandle + + handle = RemovableHandle(self._backward_hooks) + self._backward_hooks[handle.id] = hook + return handle + + def register_post_accumulate_grad_hook(self, hook): + r"""Registers a backward hook that runs after grad accumulation. + + The hook will be called after all gradients for a tensor have been accumulated, + meaning that the .grad field has been updated on that tensor. The post + accumulate grad hook is ONLY applicable for leaf tensors (tensors without a + .grad_fn field). Registering this hook on a non-leaf tensor will error! + + The hook should have the following signature:: + + hook(param: Tensor) -> None + + Note that, unlike other autograd hooks, this hook operates on the tensor + that requires grad and not the grad itself. The hook can in-place modify + and access its Tensor argument, including its .grad field. + + This function returns a handle with a method ``handle.remove()`` + that removes the hook from the module. + + .. note:: + See :ref:`backward-hooks-execution` for more information on how when this hook + is executed, and how its execution is ordered relative to other hooks. Since + this hook runs during the backward pass, it will run in no_grad mode (unless + create_graph is True). You can use torch.enable_grad() to re-enable autograd + within the hook if you need it. + + Example:: + + >>> v = torch.tensor([0., 0., 0.], requires_grad=True) + >>> lr = 0.01 + >>> # simulate a simple SGD update + >>> h = v.register_post_accumulate_grad_hook(lambda p: p.add_(p.grad, alpha=-lr)) + >>> v.backward(torch.tensor([1., 2., 3.])) + >>> v + tensor([-0.0100, -0.0200, -0.0300], requires_grad=True) + + >>> h.remove() # removes the hook + """ + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.register_post_accumulate_grad_hook, (self,), self, hook + ) + if not self.requires_grad: + raise RuntimeError( + "cannot register a hook on a tensor that doesn't require gradient" + ) + if self.grad_fn is not None: + raise RuntimeError( + "post accumulate grad hooks cannot be registered on non-leaf tensors" + ) + if self._post_accumulate_grad_hooks is None: + self._post_accumulate_grad_hooks: dict[Any, Any] = ( + # pyrefly: ignore [bad-assignment] + OrderedDict() + ) + + from torch.utils.hooks import RemovableHandle + + handle = RemovableHandle(self._post_accumulate_grad_hooks) + self._post_accumulate_grad_hooks[handle.id] = hook + return handle + + def reinforce(self, reward): + def trim(str): + return "\n".join([line.strip() for line in str.split("\n")]) + + raise RuntimeError( + trim( + r"""reinforce() was removed. + Use torch.distributions instead. + See https://pytorch.org/docs/main/distributions.html + + Instead of: + + probs = policy_network(state) + action = probs.multinomial() + next_state, reward = env.step(action) + action.reinforce(reward) + action.backward() + + Use: + + probs = policy_network(state) + # NOTE: categorical is equivalent to what used to be called multinomial + m = torch.distributions.Categorical(probs) + action = m.sample() + next_state, reward = env.step(action) + loss = -m.log_prob(action) * reward + loss.backward() + """ + ) + ) + + detach = _C._add_docstr( + _C.TensorBase.detach, + r""" + Returns a new Tensor, detached from the current graph. + + The result will never require gradient. + + This method also affects forward mode AD gradients and the result will never + have forward mode AD gradients. + + .. note:: + + Returned Tensor shares the same storage with the original one. + In-place modifications on either of them will be seen, and may trigger + errors in correctness checks. + """, + ) + + detach_ = _C._add_docstr( + _C.TensorBase.detach_, + r""" + Detaches the Tensor from the graph that created it, making it a leaf. + Views cannot be detached in-place. + + This method also affects forward mode AD gradients and the result will never + have forward mode AD gradients. + """, + ) + + def is_shared(self): + r"""Checks if tensor is in shared memory. + + This is always ``True`` for CUDA tensors. + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.is_shared, (self,), self) + return self._typed_storage()._is_shared() + + def share_memory_(self): + r"""Moves the underlying storage to shared memory. + + This is a no-op if the underlying storage is already in shared memory + and for CUDA tensors. Tensors in shared memory cannot be resized. + + See :meth:`torch.UntypedStorage.share_memory_` for more details. + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.share_memory_, (self,), self) + self._typed_storage()._share_memory_() + return self + + def module_load(self, other, assign=False): + r"""Defines how to transform ``other`` when loading it into ``self`` in :meth:`~nn.Module.load_state_dict`. + + Used when :func:`~torch.__future__.get_swap_module_params_on_conversion` is ``True``. + + It is expected that ``self`` is a parameter or buffer in an ``nn.Module`` and ``other`` is the + value in the state dictionary with the corresponding key, this method defines + how ``other`` is remapped before being swapped with ``self`` via + :func:`~torch.utils.swap_tensors` in :meth:`~nn.Module.load_state_dict`. + + .. note:: + This method should always return a new object that is not ``self`` or ``other``. + For example, the default implementation returns ``self.copy_(other).detach()`` + if ``assign`` is ``False`` or ``other.detach()`` if ``assign`` is ``True``. + + Args: + other (Tensor): value in state dict with key corresponding to ``self`` + assign (bool): the assign argument passed to :meth:`nn.Module.load_state_dict` + + """ + if has_torch_function_variadic(self, other): + return handle_torch_function( + Tensor.module_load, (self, other), self, other, assign=assign + ) + + if assign: + return other.detach() + else: + return self.copy_(other).detach() + + def __reversed__(self): + r"""Reverses the tensor along dimension 0.""" + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__reversed__, (self,), self) + if self.dim() == 0: + return self + else: + return self.flip(0) + + def norm( + self, + p: float | str | None = "fro", + dim=None, + keepdim=False, + dtype=None, + ): + r"""See :func:`torch.linalg.norm`""" + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.norm, (self,), self, p=p, dim=dim, keepdim=keepdim, dtype=dtype + ) + return torch.norm(self, p, dim, keepdim, dtype=dtype) + + def cholesky(self, upper=False): + from ._linalg_utils import cholesky + + return cholesky(self, upper=upper) + + def solve(self, other): + from torch._linalg_utils import solve + + return solve(self, other) + + def lstsq(self, other): + from torch._linalg_utils import lstsq + + return lstsq(self, other) + + def eig(self, eigenvectors=False): + from torch._linalg_utils import eig + + return eig(self, eigenvectors=eigenvectors) + + def qr(self, some=True): + from torch._linalg_utils import qr + + return qr(self, some=some) + + def symeig(self, eigenvectors=False): + from torch._linalg_utils import _symeig + + return _symeig(self, eigenvectors=eigenvectors) + + def lu(self, pivot=True, get_infos=False): + r"""See :func:`torch.lu`""" + # If get_infos is True, then we don't need to check for errors and vice versa + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.lu, (self,), self, pivot=pivot, get_infos=get_infos + ) + + LU, pivots, infos = torch._lu_with_info( + self, pivot=pivot, check_errors=(not get_infos) + ) + if get_infos: + return LU, pivots, infos + else: + return LU, pivots + + def stft( + self, + n_fft: int, + hop_length: int | None = None, + win_length: int | None = None, + window: "Tensor | None" = None, + center: bool = True, + pad_mode: str = "reflect", + normalized: bool = False, + onesided: bool | None = None, + return_complex: bool | None = None, + align_to_window: bool | None = None, + ): + r"""See :func:`torch.stft` + + .. warning:: + This function changed signature at version 0.4.1. Calling with + the previous signature may cause error or return incorrect result. + """ + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.stft, + (self,), + self, + n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + normalized=normalized, + onesided=onesided, + return_complex=return_complex, + align_to_window=align_to_window, + ) + return torch.stft( + self, + n_fft, + hop_length, + win_length, + window, + center, + pad_mode, + normalized, + onesided, + return_complex=return_complex, + align_to_window=align_to_window, + ) + + def istft( + self, + n_fft: int, + hop_length: int | None = None, + win_length: int | None = None, + window: "Tensor | None" = None, + center: bool = True, + normalized: bool = False, + onesided: bool | None = None, + length: int | None = None, + return_complex: bool = False, + ): + r"""See :func:`torch.istft`""" + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.istft, + (self,), + self, + n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + normalized=normalized, + onesided=onesided, + length=length, + return_complex=return_complex, + ) + return torch.istft( + self, + n_fft, + hop_length, + win_length, + window, + center, + normalized, + onesided, + length, + return_complex=return_complex, + ) + + def resize(self, *sizes): + if has_torch_function_unary(self): + return handle_torch_function(Tensor.resize, (self,), self, *sizes) + warnings.warn("non-inplace resize is deprecated", stacklevel=2) + from torch.autograd._functions import Resize + + return Resize.apply(self, sizes) + + def resize_as(self, tensor): + if has_torch_function_variadic(self, tensor): + return handle_torch_function(Tensor.resize_as, (self, tensor), self, tensor) + warnings.warn("non-inplace resize_as is deprecated", stacklevel=2) + from torch.autograd._functions import Resize + + return Resize.apply(self, tensor.size()) + + def split(self, split_size, dim=0): + r"""See :func:`torch.split`""" + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.split, (self,), self, split_size, dim=dim + ) + if isinstance(split_size, Tensor): + try: + split_size = int(split_size) + except ValueError: + pass + + if isinstance(split_size, (int, torch.SymInt)): + return torch._VF.split(self, split_size, dim) # type: ignore[attr-defined] + else: + return torch._VF.split_with_sizes( + self, + split_size, + dim, + ) + + def unique(self, sorted=True, return_inverse=False, return_counts=False, dim=None): + r"""Returns the unique elements of the input tensor. + + See :func:`torch.unique` + """ + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.unique, + (self,), + self, + sorted=sorted, + return_inverse=return_inverse, + return_counts=return_counts, + dim=dim, + ) + return torch.unique( + self, + sorted=sorted, + return_inverse=return_inverse, + return_counts=return_counts, + dim=dim, + ) + + def unique_consecutive(self, return_inverse=False, return_counts=False, dim=None): + r"""Eliminates all but the first element from every consecutive group of equivalent elements. + + See :func:`torch.unique_consecutive` + """ + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.unique_consecutive, + (self,), + self, + return_inverse=return_inverse, + return_counts=return_counts, + dim=dim, + ) + return torch.unique_consecutive( + self, return_inverse=return_inverse, return_counts=return_counts, dim=dim + ) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rsub__(self, other: Union["Tensor", int, float, bool, complex]) -> "Tensor": + return _C._VariableFunctions.rsub(self, other) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rdiv__(self, other: Union["Tensor", int, float, bool, complex]) -> "Tensor": + return self.reciprocal() * other + + __rtruediv__ = __rdiv__ + __itruediv__ = _C.TensorBase.__idiv__ + + # pyrefly: ignore [bad-override] + __pow__ = cast( + Callable[ + ["torch._C.TensorBase", Union["Tensor", int, float, bool, complex]], + "Tensor", + ], + _handle_torch_function_and_wrap_type_error_to_not_implemented( + _C.TensorBase.pow + ), + ) + + __ipow__ = _handle_torch_function_and_wrap_type_error_to_not_implemented( + _C.TensorBase.pow_ + ) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rmod__(self, other: Union["Tensor", int, float, bool, complex]) -> "Tensor": + return torch.remainder(other, self) + + def __format__(self, format_spec): + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__format__, (self,), self, format_spec) + if self.dim() == 0 and not self.is_meta and type(self) is Tensor: + # Use detach() here to avoid the warning when converting a scalar Tensor that + # requires gradients to a python number. It is ok for formatting. + return self.detach().item().__format__(format_spec) + return object.__format__(self, format_spec) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rpow__(self, other: Union["Tensor", int, float, bool, complex]) -> "Tensor": + return torch.pow(other, self) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __floordiv__(self, other: Union["Tensor", int, float, bool]) -> "Tensor": # type: ignore[override] + # TODO(rec): the superclass says it accepts complex here, + # but torch.floor_divide says it doesn't. + return torch.floor_divide(self, other) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rfloordiv__(self, other: Union["Tensor", int, float, bool]) -> "Tensor": # type: ignore[override] + return torch.floor_divide(other, self) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rlshift__( + self, other: Union["Tensor", int, float, bool, complex] + ) -> "Tensor": + return torch.bitwise_left_shift(other, self) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rrshift__( + self, other: Union["Tensor", int, float, bool, complex] + ) -> "Tensor": + return torch.bitwise_right_shift(other, self) + + @_handle_torch_function_and_wrap_type_error_to_not_implemented + def __rmatmul__(self, other: "Tensor") -> "Tensor": + return torch.matmul(other, self) + + __pos__ = _C.TensorBase.positive + __neg__ = _C.TensorBase.neg + __abs__ = _C.TensorBase.abs + + def __len__(self): + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__len__, (self,), self) + if self.dim() == 0: + raise TypeError("len() of a 0-d tensor") + if torch._C._get_tracing_state(): + warnings.warn( + "Using len to get tensor shape might cause the trace to be incorrect. " + "Recommended usage would be tensor.shape[0]. " + "Passing a tensor of different shape might lead to errors or silently give " + "incorrect results.", + category=torch.jit.TracerWarning, + stacklevel=2, + ) + return self.shape[0] + + def __iter__(self): + # NB: we use 'imap' and not 'map' here, so that we get a generator + # and don't eagerly perform all the indexes. This could save us + # work, and also helps keep trace ordering deterministic + # (e.g., if you zip(*hiddens), the eager map will force all the + # indexes of hiddens[0] before hiddens[1], while the generator + # map will interleave them.) + # NB: We have intentionally skipped __torch_function__ dispatch here. + # See gh-54457 + if self.dim() == 0: + raise TypeError("iteration over a 0-d tensor") + if torch._C._get_tracing_state(): + warnings.warn( + "Iterating over a tensor might cause the trace to be incorrect. " + "Passing a tensor of different shape won't change the number of " + "iterations executed (and might lead to errors or silently give " + "incorrect results).", + category=torch.jit.TracerWarning, + stacklevel=2, + ) + return iter(self.unbind(0)) + + def __hash__(self): + # Do NOT handle __torch_function__ here as user's default + # implementation that handle most functions will most likely do it wrong. + # It can be easily overridden by defining this method on the user + # subclass if needed. + return id(self) + + def __dir__(self): + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__dir__, (self,), self) + tensor_methods = dir(self.__class__) + tensor_methods.remove("volatile") # deprecated + attrs = list(self.__dict__.keys()) + keys = tensor_methods + attrs + + # property only available dense, cuda tensors + if (not self.is_cuda) or self.is_sparse: + keys.remove("__cuda_array_interface__") + + return sorted(keys) + + # Numpy array interface, to support `numpy.asarray(tensor) -> ndarray` + __array_priority__ = 1000 # prefer Tensor ops over numpy ones + + def __array__(self, dtype=None): + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__array__, (self,), self, dtype=dtype) + if dtype is None: + return self.numpy() + else: + return self.numpy().astype(dtype, copy=False) + + # Wrap Numpy array again in a suitable tensor when done, to support e.g. + # `numpy.sin(tensor) -> tensor` or `numpy.greater(tensor, 0) -> ByteTensor` + def __array_wrap__(self, array): + if has_torch_function_unary(self): + return handle_torch_function( + Tensor.__array_wrap__, (self,), self, array=array + ) + if array.dtype == bool: + # Workaround, torch has no built-in bool tensor + array = array.astype("uint8") + return torch.from_numpy(array) + + def __contains__(self, element: Any, /) -> bool: + r"""Check if `element` is present in tensor + + Args: + element (Tensor or scalar): element to be checked + for presence in current tensor" + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__contains__, (self,), self, element) + if isinstance( + element, (torch.Tensor, Number, torch.SymInt, torch.SymFloat, torch.SymBool) + ): + # type hint doesn't understand the __contains__ result array + return bool((element == self).any().item()) # type: ignore[union-attr] + + raise RuntimeError( + f"Tensor.__contains__ only supports Tensor or scalar, but you passed in a {type(element)}." + ) + + @property + def __cuda_array_interface__(self): + """Array view description for cuda tensors. + + See: + https://numba.pydata.org/numba-doc/dev/cuda/cuda_array_interface.html + """ + if has_torch_function_unary(self): + # TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185 + return handle_torch_function( # pyrefly: ignore [bad-argument-count] + Tensor.__cuda_array_interface__.__get__, # type: ignore[attr-defined] + (self,), + self, # pyrefly: ignore [bad-argument-type] + ) + + # raise AttributeError for unsupported tensors, so that + # hasattr(cpu_tensor, "__cuda_array_interface__") is False. + if not self.is_cuda: + raise AttributeError( + f"Can't get __cuda_array_interface__ on non-CUDA tensor type: {self.type()} " + "If CUDA data is required use tensor.cuda() to copy tensor to device memory." + ) + + if self.is_sparse: + raise AttributeError( + f"Can't get __cuda_array_interface__ on sparse type: {self.type()} " + "Use Tensor.to_dense() to convert to a dense tensor first." + ) + + # RuntimeError, matching tensor.__array__() behavior. + if self.requires_grad: + raise RuntimeError( + "Can't get __cuda_array_interface__ on Variable that requires grad. " + "If gradients aren't required, use var.detach() to get Variable that doesn't require grad." + ) + + typestr = _dtype_to_typestr(self.dtype) + itemsize = self.element_size() + shape = tuple(self.shape) + if self.is_contiguous(): + # __cuda_array_interface__ v2 requires the strides to be omitted + # (either not set or set to None) for C-contiguous arrays. + strides = None + else: + strides = tuple(s * itemsize for s in self.stride()) + data_ptr = self.data_ptr() if self.numel() > 0 else 0 + data = (data_ptr, False) # read-only is false + + return dict(typestr=typestr, shape=shape, strides=strides, data=data, version=2) + + def storage_type(self): + r"""storage_type() -> type + + Returns the type of the underlying storage. + + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.storage_type, (self,), self) + + torch.storage._warn_typed_storage_removal() + + return self._typed_storage()._get_legacy_storage_class() + + def unflatten(self, dim, sizes): # type: ignore[override] + r""" + unflatten(dim, sizes) -> Tensor + + See :func:`torch.unflatten`. + + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.unflatten, (self,), self, dim, sizes) + + if not sizes: + raise RuntimeError("unflatten: sizes must be non-empty") + + return super().unflatten(dim, sizes) + + def to_sparse_coo(self): + """Convert a tensor to :ref:`coordinate format `. + + Examples:: + + >>> dense = torch.randn(5, 5) + >>> sparse = dense.to_sparse_coo() + >>> sparse._nnz() + 25 + + """ + return self.to_sparse() + + def dim_order(self, *, ambiguity_check: bool | list[torch.memory_format] = False): + """ + dim_order(ambiguity_check=False) -> tuple + + Returns the uniquely determined tuple of int describing the dim order or + physical layout of :attr:`self`. + + The dim order represents how dimensions are laid out in memory of dense tensors, + starting from the outermost to the innermost dimension. + + Note that the dim order may not always be uniquely determined. + If `ambiguity_check` is True, this function raises a RuntimeError when the dim order cannot be uniquely determined; + If `ambiguity_check` is a list of memory formats, this function raises a RuntimeError when tensor can not be interpreted + into exactly one of the given memory formats, or it cannot be uniquely determined. + If `ambiguity_check` is False, it will return one of legal dim order(s) without checking its uniqueness. + Otherwise, it will raise TypeError. + + Args: + ambiguity_check (bool or List[torch.memory_format]): The check method for ambiguity of dim order. + + Examples:: + + >>> torch.empty((2, 3, 5, 7)).dim_order() + (0, 1, 2, 3) + >>> torch.empty((2, 3, 5, 7)).transpose(1, 2).dim_order() + (0, 2, 1, 3) + >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).dim_order() + (0, 2, 3, 1) + >>> torch.empty((1, 2, 3, 4)).dim_order() + (0, 1, 2, 3) + >>> try: + ... torch.empty((1, 2, 3, 4)).dim_order(ambiguity_check=True) + ... except RuntimeError as e: + ... print(e) + The tensor does not have unique dim order, or cannot map to exact one of the given memory formats. + >>> torch.empty((1, 2, 3, 4)).dim_order( + ... ambiguity_check=[torch.contiguous_format, torch.channels_last] + ... ) # It can be mapped to contiguous format + (0, 1, 2, 3) + >>> try: + ... torch.empty((1, 2, 3, 4)).dim_order(ambiguity_check="ILLEGAL") # type: ignore[arg-type] + ... except TypeError as e: + ... print(e) + The ambiguity_check argument must be a bool or a list of memory formats. + + .. warning:: + The dim_order tensor API is experimental and subject to change. + """ + if has_torch_function_unary(self): + return handle_torch_function(Tensor.dim_order, (self,), self) + + if self.is_sparse: + raise AttributeError( + f"Can't get dim order on sparse type: {self.type()} " + "Use Tensor.to_dense() to convert to a dense tensor first." + ) + + # Sanity check ambiguity_check data types + if not isinstance(ambiguity_check, bool): + if not isinstance(ambiguity_check, list): + raise TypeError( + "The ambiguity_check argument must be a bool or a list of memory formats." + ) + for memory_format in ambiguity_check: + if not isinstance(memory_format, torch.memory_format): + raise TypeError( + "The ambiguity_check argument must be a bool or a list of memory formats." + ) + + def invalid_unique_memory_format(tensor, valid_memory_formats): + """ + Returns True if the tensor cannot be uniquely mapped to any of the given memory formats, False otherwise. + """ + + n_legality = 0 + + for memory_format in valid_memory_formats: + if tensor.is_contiguous(memory_format=memory_format): + n_legality += 1 + + return n_legality != 1 + + def has_multiple_dim_order(tensor): + """ + Returns True if there're multiple legal dim orders for given tensor, False otherwise. + + The tensor is considered to have multiple legal dim orders if either of the following conditions is met: + + * Singleton Dimensions: There's at least one singleton dimension in the tensor. + Since their size is 1, they don't affect the memory offset (stride * index + is zero because index is always zero). Therefore, they can be placed anywhere + in the dimension order without changing how data is accessed. + * Same strides: Strides reflect how the tensor is stored in memory. + If any two dimensions have the same stride, swapping these dimensions won't + change how data is accessed, leading to multiple correct dimension orders. + """ + from torch.fx.experimental.symbolic_shapes import guard_or_false + + sizes = tensor.size() + strides = tensor.stride() + + # Check if there are any duplicate strides + has_duplicate_strides = any( + guard_or_false(earlier == later) + for earlier, later in itertools.pairwise(strides) + ) + + # Check if there are any singleton dimensions + has_singleton_dims = any(guard_or_false(size == 1) for size in sizes) + + return has_duplicate_strides or has_singleton_dims + + valid_memory_formats = ( + ambiguity_check if isinstance(ambiguity_check, list) else [] + ) + check_multiple_dim_order = ( + ambiguity_check if isinstance(ambiguity_check, bool) else True + ) + + if ( + check_multiple_dim_order and has_multiple_dim_order(self) + ) and invalid_unique_memory_format(self, valid_memory_formats): + raise RuntimeError( + "The tensor does not have unique dim order, or cannot map to exact one of the given memory formats." + ) + + import torch._prims_common as utils + + out_perm, raise_ambiguity = ( + utils.compute_elementwise_output_logical_to_physical_perm( + self, ambiguity_check=ambiguity_check + ) + ) + if raise_ambiguity: + raise RuntimeError("The tensor does not have unique dim order.") + return tuple(out_perm) + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + """ + This __torch_function__ implementation wraps subclasses such that + methods called on subclasses return a subclass instance instead of + a ``torch.Tensor`` instance. + + One corollary to this is that you need coverage for torch.Tensor + methods if implementing __torch_function__ for subclasses. + + We recommend always calling ``super().__torch_function__`` as the base + case when doing the above. + + While not mandatory, we recommend making `__torch_function__` a classmethod. + """ + if kwargs is None: + kwargs = {} + + if not all(issubclass(cls, t) for t in types): + return NotImplemented + + with _C.DisableTorchFunctionSubclass(): + ret = func(*args, **kwargs) + if func in get_default_nowrap_functions(): + return ret + else: + return _convert(ret, cls) + + __torch_dispatch__ = _C._disabled_torch_dispatch_impl + + def __dlpack__( + self, + *, + stream: Any | None = -1, + max_version: tuple[int, int] | None = None, + dl_device: tuple[enum.IntEnum, int] | None = None, + copy: bool | None = None, + read_only: bool = False, + ): + """ + Creates a DLpack `capsule https://data-apis.org/array-api/latest/design_topics/data_interchange.html#data-interchange`_ + of the current tensor to be exported to other libraries. + + This function will be called from the `from_dlpack` method + of the library that will consume the capsule. `from_dlpack` passes the current + stream to this method as part of the specification. + + Args: + stream (integer or None): An optional Python integer representing a + pointer to a CUDA stream. The current stream is synchronized with + this stream before the capsule is created, and since the capsule + shares its storage with the tensor this make it safe to access from + both streams. If -1 is passed then no synchronization is performed. + If 1 (on CUDA) or 0 (on ROCM) then the default stream is used for + synchronization. This API intentionally slightly deviates from the DLPack + guidance: the default stream is -1 (stream-preserving; no cross-stream sync), + because many from_dlpack implementations intend stream preservation. + For non-CUDA devices, -1 is treated the same as None. + + max_version (tuple[int, int] or None): An optional Python tuple with + 2 integers, representing the maximum version the caller supports. If + None (default), PyTorch will fallback to DLPack 0.8. + + dl_device (tuple[DLDeviceType, int] or None): An optional tuple specifying + in which device the exported DLPack capsule should be on. If None (default), + the exported DLPack capsule will be on the same device as ``self``. + + copy (bool or None): An optional boolean indicating whether or not to copy + ``self``. If None, PyTorch will copy only if necessary. + + read_only (bool): If True, the exported capsule is marked read-only + (``DLPACK_FLAG_BITMASK_READ_ONLY``) and the data is exported + through ``const_data_ptr()`` so a copy-on-write tensor is not + materialized. The consumer must not mutate the data. Requires + the versioned DLPack protocol (``max_version >= (1, 0)``). + """ + if has_torch_function_unary(self): + args = (self,) + kwargs = { + "stream": stream, + "max_version": max_version, + "dl_device": dl_device, + "copy": copy, + "read_only": read_only, + } + return handle_torch_function(Tensor.__dlpack__, (self,), *args, **kwargs) + + # DLPack capsules can't capture all of PyTorch's semantics, + # so we prohibit exporting tensors that would lose their properties like + # requires_grad and having the conjugate bit set. + if self.requires_grad: + raise BufferError( + "Can't export tensors that require gradient, use tensor.detach()" + ) + if self.is_conj(): + raise BufferError("Can't export tensors with the conjugate bit set") + if self.layout != torch.strided: + raise BufferError( + "Can't export tensors with layout other than torch.strided" + ) + + if ( + self.device.type == "cuda" + and self.device.index != torch.cuda.current_device() + ): + raise BufferError( + "Can't export tensors on a different CUDA device index. " + f"Expected: {self.device.index}. " + f"Current device: {torch.cuda.current_device()}." + ) + + if stream is not None and type(stream) is not int: + # Stream pointers in CUDA/ROCm are uniquely numbered and can + # be retrieved from their integer value. + raise TypeError("stream must be ``int`` or ``none``") + elif self.device.type == "cuda" and stream != -1: + # NB: This logic handles the special case values for default + # streams and must be kept in sync with from_dlpack in + # torch/utils/dlpack.py + is_rocm = torch.version.hip is not None + is_cuda = not is_rocm + + if stream is None or (is_rocm and stream == 0) or (is_cuda and stream == 1): + stream = torch.cuda.default_stream() + else: + if is_cuda and stream == 2: + raise BufferError("per-thread default stream is not supported.") + + device_str = "CUDA" if is_cuda else "ROCm" + if not ( + (is_cuda and stream != 0) or (is_rocm and stream not in (1, 2)) + ): + raise AssertionError( + f"unsupported stream on {device_str}: {stream}." + ) + + stream = torch.cuda.ExternalStream(stream) + + # Only synchronize on different streams + current_stream = torch.cuda.current_stream() + if stream != current_stream: + event = torch.cuda.Event() + event.record(current_stream) + stream.wait_event(event) + elif self.device.type == "cpu": + if stream is not None and stream != -1: + raise AssertionError("stream should be None on cpu.") + + if self.device.type == "xla": + import torch_xla + import torch_xla.utils.dlpack as xla_dlpack + + if ( + len(torch_xla.real_devices()) <= 0 + or "cuda" not in torch_xla.real_devices()[0].lower() + ): + raise RuntimeError( + "Can't export to dlpack an XLA tensor that is not on CUDA." + ) + + # Does not support DLPack 1.0, yet. + return xla_dlpack.to_dlpack(self) + + if max_version is None or max_version[0] < 1: + # Fallback to the old, unversioned variant, which has no flags field + # and therefore cannot represent read-only. + if read_only: + raise BufferError( + "read_only export requires the versioned DLPack protocol; " + "pass max_version=(1, 0) or higher" + ) + return _C._to_dlpack(self, dl_device=dl_device, copy=copy) + + return _C._to_dlpack_versioned( + self, dl_device=dl_device, copy=copy, read_only=read_only + ) + + def __dlpack_device__(self) -> tuple[enum.IntEnum, int]: + if has_torch_function_unary(self): + return handle_torch_function(Tensor.__dlpack_device__, (self,), self) + + from torch.utils.dlpack import DLDeviceType + + device = self.device + idx = device.index if device.index is not None else 0 + torch_device_type = device.type + if torch_device_type == "cuda" and torch.version.hip is not None: + device_type = DLDeviceType.kDLROCM + elif torch_device_type == "cpu" and self.is_pinned(): + device_type = DLDeviceType.kDLCUDAHost + elif torch_device_type == "cuda": + device_type = DLDeviceType.kDLCUDA + elif torch_device_type == "cpu": + device_type = DLDeviceType.kDLCPU + elif torch_device_type == "xpu": + device_type = DLDeviceType.kDLOneAPI + elif self.device.type == "privateuse1": + device_type = DLDeviceType.kDLExtDev + elif torch_device_type == "xla": + import torch_xla + + if ( + len(torch_xla.real_devices()) <= 0 + or "cuda" not in torch_xla.real_devices()[0].lower() + ): + raise ValueError(f"Unknown device type {torch_device_type} for Dlpack") + + device_type = DLDeviceType.kDLCUDA + elif torch_device_type == "mps": + device_type = DLDeviceType.kDLMetal + else: + raise ValueError(f"Unknown device type {torch_device_type} for Dlpack") + return (device_type, idx) + + __module__ = "torch" + + +def _convert(ret, cls): + if cls is Tensor: + return ret + + if isinstance(ret, Tensor) and not isinstance(ret, cls): + ret = ret.as_subclass(cls) + + if isinstance(ret, (tuple, list)): + # Also handles things like namedtuples + ret = type(ret)(_convert(r, cls) for r in ret) + + return ret diff --git a/.venv/lib/python3.12/site-packages/torch/_tensor_docs.py b/.venv/lib/python3.12/site-packages/torch/_tensor_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..d024f2a467070c5ee17f828823f8154c63179bcf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_tensor_docs.py @@ -0,0 +1,6922 @@ +# mypy: allow-untyped-defs +"""Adds docstrings to Tensor functions""" + +import torch._C +from torch._C import _add_docstr as add_docstr +from torch._torch_docs import parse_kwargs, reproducibility_notes + + +def add_docstr_all(method: str, docstr: str) -> None: + add_docstr(getattr(torch._C.TensorBase, method), docstr) + + +common_args = parse_kwargs( + """ + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. +""" +) + +new_common_args = parse_kwargs( + """ + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. +""" +) + +add_docstr_all( + "new_tensor", + """ +new_tensor(data, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a new Tensor with :attr:`data` as the tensor data. +By default, the returned Tensor has the same :class:`torch.dtype` and +:class:`torch.device` as this tensor. + +.. warning:: + + :func:`new_tensor` always copies :attr:`data`. If you have a Tensor + ``data`` and want to avoid a copy, use :func:`torch.Tensor.requires_grad_` + or :func:`torch.Tensor.detach`. + If you have a numpy array and want to avoid a copy, use + :func:`torch.from_numpy`. + +.. warning:: + + When data is a tensor `x`, :func:`new_tensor()` reads out 'the data' from whatever it is passed, + and constructs a leaf variable. Therefore ``tensor.new_tensor(x)`` is equivalent to ``x.detach().clone()`` + and ``tensor.new_tensor(x, requires_grad=True)`` is equivalent to ``x.detach().clone().requires_grad_(True)``. + The equivalents using ``detach()`` and ``clone()`` are recommended. + +Args: + data (array_like): The returned Tensor copies :attr:`data`. + +Keyword args: + {dtype} + {device} + {requires_grad} + {layout} + {pin_memory} + +Example:: + + >>> tensor = torch.ones((2,), dtype=torch.int8) + >>> data = [[0, 1], [2, 3]] + >>> tensor.new_tensor(data) + tensor([[ 0, 1], + [ 2, 3]], dtype=torch.int8) + +""".format(**new_common_args), +) + +add_docstr_all( + "new_full", + """ +new_full(size, fill_value, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a Tensor of size :attr:`size` filled with :attr:`fill_value`. +By default, the returned Tensor has the same :class:`torch.dtype` and +:class:`torch.device` as this tensor. + +Args: + fill_value (scalar): the number to fill the output tensor with. + +Keyword args: + {dtype} + {device} + {requires_grad} + {layout} + {pin_memory} + +Example:: + + >>> tensor = torch.ones((2,), dtype=torch.float64) + >>> tensor.new_full((3, 4), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416, 3.1416]], dtype=torch.float64) + +""".format(**new_common_args), +) + +add_docstr_all( + "new_empty", + """ +new_empty(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a Tensor of size :attr:`size` filled with uninitialized data. +By default, the returned Tensor has the same :class:`torch.dtype` and +:class:`torch.device` as this tensor. + +Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + +Keyword args: + {dtype} + {device} + {requires_grad} + {layout} + {pin_memory} + +Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty((2, 3)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + +""".format(**new_common_args), +) + +add_docstr_all( + "new_empty_strided", + """ +new_empty_strided(size, stride, dtype=None, device=None, requires_grad=False, layout=torch.strided, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a Tensor of size :attr:`size` and strides :attr:`stride` filled with +uninitialized data. By default, the returned Tensor has the same +:class:`torch.dtype` and :class:`torch.device` as this tensor. + +Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + +Keyword args: + {dtype} + {device} + {requires_grad} + {layout} + {pin_memory} + +Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty_strided((2, 3), (3, 1)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + +""".format(**new_common_args), +) + +add_docstr_all( + "new_ones", + """ +new_ones(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a Tensor of size :attr:`size` filled with ``1``. +By default, the returned Tensor has the same :class:`torch.dtype` and +:class:`torch.device` as this tensor. + +Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + +Keyword args: + {dtype} + {device} + {requires_grad} + {layout} + {pin_memory} + +Example:: + + >>> tensor = torch.tensor((), dtype=torch.int32) + >>> tensor.new_ones((2, 3)) + tensor([[ 1, 1, 1], + [ 1, 1, 1]], dtype=torch.int32) + +""".format(**new_common_args), +) + +add_docstr_all( + "new_zeros", + """ +new_zeros(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a Tensor of size :attr:`size` filled with ``0``. +By default, the returned Tensor has the same :class:`torch.dtype` and +:class:`torch.device` as this tensor. + +Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + +Keyword args: + {dtype} + {device} + {requires_grad} + {layout} + {pin_memory} + +Example:: + + >>> tensor = torch.tensor((), dtype=torch.float64) + >>> tensor.new_zeros((2, 3)) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]], dtype=torch.float64) + +""".format(**new_common_args), +) + +add_docstr_all( + "abs", + r""" +abs() -> Tensor + +See :func:`torch.abs` +""", +) + +add_docstr_all( + "abs_", + r""" +abs_() -> Tensor + +In-place version of :meth:`~Tensor.abs` +""", +) + +add_docstr_all( + "absolute", + r""" +absolute() -> Tensor + +Alias for :func:`abs` +""", +) + +add_docstr_all( + "absolute_", + r""" +absolute_() -> Tensor + +In-place version of :meth:`~Tensor.absolute` +Alias for :func:`abs_` +""", +) + +add_docstr_all( + "acos", + r""" +acos() -> Tensor + +See :func:`torch.acos` +""", +) + +add_docstr_all( + "acos_", + r""" +acos_() -> Tensor + +In-place version of :meth:`~Tensor.acos` +""", +) + +add_docstr_all( + "arccos", + r""" +arccos() -> Tensor + +See :func:`torch.arccos` +""", +) + +add_docstr_all( + "arccos_", + r""" +arccos_() -> Tensor + +In-place version of :meth:`~Tensor.arccos` +""", +) + +add_docstr_all( + "acosh", + r""" +acosh() -> Tensor + +See :func:`torch.acosh` +""", +) + +add_docstr_all( + "acosh_", + r""" +acosh_() -> Tensor + +In-place version of :meth:`~Tensor.acosh` +""", +) + +add_docstr_all( + "arccosh", + r""" +acosh() -> Tensor + +See :func:`torch.arccosh` +""", +) + +add_docstr_all( + "arccosh_", + r""" +acosh_() -> Tensor + +In-place version of :meth:`~Tensor.arccosh` +""", +) + +add_docstr_all( + "add", + r""" +add(other, *, alpha=1) -> Tensor + +Add a scalar or tensor to :attr:`self` tensor. If both :attr:`alpha` +and :attr:`other` are specified, each element of :attr:`other` is scaled by +:attr:`alpha` before being used. + +When :attr:`other` is a tensor, the shape of :attr:`other` must be +:ref:`broadcastable ` with the shape of the underlying +tensor + +See :func:`torch.add` +""", +) + +add_docstr_all( + "add_", + r""" +add_(other, *, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.add` +""", +) + +add_docstr_all( + "addbmm", + r""" +addbmm(batch1, batch2, *, beta=1, alpha=1) -> Tensor + +See :func:`torch.addbmm` +""", +) + +add_docstr_all( + "addbmm_", + r""" +addbmm_(batch1, batch2, *, beta=1, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.addbmm` +""", +) + +add_docstr_all( + "addcdiv", + r""" +addcdiv(tensor1, tensor2, *, value=1) -> Tensor + +See :func:`torch.addcdiv` +""", +) + +add_docstr_all( + "addcdiv_", + r""" +addcdiv_(tensor1, tensor2, *, value=1) -> Tensor + +In-place version of :meth:`~Tensor.addcdiv` +""", +) + +add_docstr_all( + "addcmul", + r""" +addcmul(tensor1, tensor2, *, value=1) -> Tensor + +See :func:`torch.addcmul` +""", +) + +add_docstr_all( + "addcmul_", + r""" +addcmul_(tensor1, tensor2, *, value=1) -> Tensor + +In-place version of :meth:`~Tensor.addcmul` +""", +) + +add_docstr_all( + "addmm", + r""" +addmm(mat1, mat2, *, beta=1, alpha=1) -> Tensor + +See :func:`torch.addmm` +""", +) + +add_docstr_all( + "addmm_", + r""" +addmm_(mat1, mat2, *, beta=1, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.addmm` +""", +) + +add_docstr_all( + "addmv", + r""" +addmv(mat, vec, *, beta=1, alpha=1) -> Tensor + +See :func:`torch.addmv` +""", +) + +add_docstr_all( + "addmv_", + r""" +addmv_(mat, vec, *, beta=1, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.addmv` +""", +) + +add_docstr_all( + "sspaddmm", + r""" +sspaddmm(mat1, mat2, *, beta=1, alpha=1) -> Tensor + +See :func:`torch.sspaddmm` +""", +) + +add_docstr_all( + "smm", + r""" +smm(mat) -> Tensor + +See :func:`torch.smm` +""", +) + +add_docstr_all( + "addr", + r""" +addr(vec1, vec2, *, beta=1, alpha=1) -> Tensor + +See :func:`torch.addr` +""", +) + +add_docstr_all( + "addr_", + r""" +addr_(vec1, vec2, *, beta=1, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.addr` +""", +) + +add_docstr_all( + "all", + r""" +all(dim=None, keepdim=False) -> Tensor + +See :func:`torch.all` +""", +) + +add_docstr_all( + "allclose", + r""" +allclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + +See :func:`torch.allclose` +""", +) + +add_docstr_all( + "angle", + r""" +angle() -> Tensor + +See :func:`torch.angle` +""", +) + +add_docstr_all( + "any", + r""" +any(dim=None, keepdim=False) -> Tensor + +See :func:`torch.any` +""", +) + +add_docstr_all( + "apply_", + r""" +apply_(callable) -> Tensor + +Applies the function :attr:`callable` to each element in the tensor, replacing +each element with the value returned by :attr:`callable`. + +.. note:: + + This function only works with CPU tensors and should not be used in code + sections that require high performance. +""", +) + +add_docstr_all( + "asin", + r""" +asin() -> Tensor + +See :func:`torch.asin` +""", +) + +add_docstr_all( + "asin_", + r""" +asin_() -> Tensor + +In-place version of :meth:`~Tensor.asin` +""", +) + +add_docstr_all( + "arcsin", + r""" +arcsin() -> Tensor + +See :func:`torch.arcsin` +""", +) + +add_docstr_all( + "arcsin_", + r""" +arcsin_() -> Tensor + +In-place version of :meth:`~Tensor.arcsin` +""", +) + +add_docstr_all( + "asinh", + r""" +asinh() -> Tensor + +See :func:`torch.asinh` +""", +) + +add_docstr_all( + "asinh_", + r""" +asinh_() -> Tensor + +In-place version of :meth:`~Tensor.asinh` +""", +) + +add_docstr_all( + "arcsinh", + r""" +arcsinh() -> Tensor + +See :func:`torch.arcsinh` +""", +) + +add_docstr_all( + "arcsinh_", + r""" +arcsinh_() -> Tensor + +In-place version of :meth:`~Tensor.arcsinh` +""", +) + +add_docstr_all( + "as_strided", + r""" +as_strided(size, stride, storage_offset=None) -> Tensor + +See :func:`torch.as_strided` +""", +) + +add_docstr_all( + "as_strided_", + r""" +as_strided_(size, stride, storage_offset=None) -> Tensor + +In-place version of :meth:`~Tensor.as_strided` +""", +) + +add_docstr_all( + "atan", + r""" +atan() -> Tensor + +See :func:`torch.atan` +""", +) + +add_docstr_all( + "atan_", + r""" +atan_() -> Tensor + +In-place version of :meth:`~Tensor.atan` +""", +) + +add_docstr_all( + "arctan", + r""" +arctan() -> Tensor + +See :func:`torch.arctan` +""", +) + +add_docstr_all( + "arctan_", + r""" +arctan_() -> Tensor + +In-place version of :meth:`~Tensor.arctan` +""", +) + +add_docstr_all( + "atan2", + r""" +atan2(other) -> Tensor + +See :func:`torch.atan2` +""", +) + +add_docstr_all( + "atan2_", + r""" +atan2_(other) -> Tensor + +In-place version of :meth:`~Tensor.atan2` +""", +) + +add_docstr_all( + "arctan2", + r""" +arctan2(other) -> Tensor + +See :func:`torch.arctan2` +""", +) + +add_docstr_all( + "arctan2_", + r""" +atan2_(other) -> Tensor + +In-place version of :meth:`~Tensor.arctan2` +""", +) + +add_docstr_all( + "atanh", + r""" +atanh() -> Tensor + +See :func:`torch.atanh` +""", +) + +add_docstr_all( + "atanh_", + r""" +atanh_(other) -> Tensor + +In-place version of :meth:`~Tensor.atanh` +""", +) + +add_docstr_all( + "arctanh", + r""" +arctanh() -> Tensor + +See :func:`torch.arctanh` +""", +) + +add_docstr_all( + "arctanh_", + r""" +arctanh_(other) -> Tensor + +In-place version of :meth:`~Tensor.arctanh` +""", +) + +add_docstr_all( + "baddbmm", + r""" +baddbmm(batch1, batch2, *, beta=1, alpha=1) -> Tensor + +See :func:`torch.baddbmm` +""", +) + +add_docstr_all( + "baddbmm_", + r""" +baddbmm_(batch1, batch2, *, beta=1, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.baddbmm` +""", +) + +add_docstr_all( + "bernoulli", + r""" +bernoulli(*, generator=None) -> Tensor + +Returns a result tensor where each :math:`\texttt{result[i]}` is independently +sampled from :math:`\text{Bernoulli}(\texttt{self[i]})`. :attr:`self` must have +floating point ``dtype``, and the result will have the same ``dtype``. + +See :func:`torch.bernoulli` +""", +) + +add_docstr_all( + "bernoulli_", + r""" +bernoulli_(p=0.5, *, generator=None) -> Tensor + +Fills each location of :attr:`self` with an independent sample from +:math:`\text{Bernoulli}(\texttt{p})`. :attr:`self` can have integral +``dtype``. + +:attr:`p` should either be a scalar or tensor containing probabilities to be +used for drawing the binary random number. + +If it is a tensor, the :math:`\text{i}^{th}` element of :attr:`self` tensor +will be set to a value sampled from +:math:`\text{Bernoulli}(\texttt{p\_tensor[i]})`. In this case `p` must have +floating point ``dtype``. + +See also :meth:`~Tensor.bernoulli` and :func:`torch.bernoulli` +""", +) + +add_docstr_all( + "bincount", + r""" +bincount(weights=None, minlength=0) -> Tensor + +See :func:`torch.bincount` +""", +) + +add_docstr_all( + "bitwise_not", + r""" +bitwise_not() -> Tensor + +See :func:`torch.bitwise_not` +""", +) + +add_docstr_all( + "bitwise_not_", + r""" +bitwise_not_() -> Tensor + +In-place version of :meth:`~Tensor.bitwise_not` +""", +) + +add_docstr_all( + "bitwise_and", + r""" +bitwise_and() -> Tensor + +See :func:`torch.bitwise_and` +""", +) + +add_docstr_all( + "bitwise_and_", + r""" +bitwise_and_() -> Tensor + +In-place version of :meth:`~Tensor.bitwise_and` +""", +) + +add_docstr_all( + "bitwise_or", + r""" +bitwise_or() -> Tensor + +See :func:`torch.bitwise_or` +""", +) + +add_docstr_all( + "bitwise_or_", + r""" +bitwise_or_() -> Tensor + +In-place version of :meth:`~Tensor.bitwise_or` +""", +) + +add_docstr_all( + "bitwise_xor", + r""" +bitwise_xor() -> Tensor + +See :func:`torch.bitwise_xor` +""", +) + +add_docstr_all( + "bitwise_xor_", + r""" +bitwise_xor_() -> Tensor + +In-place version of :meth:`~Tensor.bitwise_xor` +""", +) + +add_docstr_all( + "bitwise_left_shift", + r""" +bitwise_left_shift(other) -> Tensor + +See :func:`torch.bitwise_left_shift` +""", +) + +add_docstr_all( + "bitwise_left_shift_", + r""" +bitwise_left_shift_(other) -> Tensor + +In-place version of :meth:`~Tensor.bitwise_left_shift` +""", +) + +add_docstr_all( + "bitwise_right_shift", + r""" +bitwise_right_shift(other) -> Tensor + +See :func:`torch.bitwise_right_shift` +""", +) + +add_docstr_all( + "bitwise_right_shift_", + r""" +bitwise_right_shift_(other) -> Tensor + +In-place version of :meth:`~Tensor.bitwise_right_shift` +""", +) + +add_docstr_all( + "broadcast_to", + r""" +broadcast_to(shape) -> Tensor + +See :func:`torch.broadcast_to`. +""", +) + +add_docstr_all( + "logical_and", + r""" +logical_and() -> Tensor + +See :func:`torch.logical_and` +""", +) + +add_docstr_all( + "logical_and_", + r""" +logical_and_() -> Tensor + +In-place version of :meth:`~Tensor.logical_and` +""", +) + +add_docstr_all( + "logical_not", + r""" +logical_not() -> Tensor + +See :func:`torch.logical_not` +""", +) + +add_docstr_all( + "logical_not_", + r""" +logical_not_() -> Tensor + +In-place version of :meth:`~Tensor.logical_not` +""", +) + +add_docstr_all( + "logical_or", + r""" +logical_or() -> Tensor + +See :func:`torch.logical_or` +""", +) + +add_docstr_all( + "logical_or_", + r""" +logical_or_() -> Tensor + +In-place version of :meth:`~Tensor.logical_or` +""", +) + +add_docstr_all( + "logical_xor", + r""" +logical_xor() -> Tensor + +See :func:`torch.logical_xor` +""", +) + +add_docstr_all( + "logical_xor_", + r""" +logical_xor_() -> Tensor + +In-place version of :meth:`~Tensor.logical_xor` +""", +) + +add_docstr_all( + "bmm", + r""" +bmm(batch2) -> Tensor + +See :func:`torch.bmm` +""", +) + +add_docstr_all( + "cauchy_", + r""" +cauchy_(median=0, sigma=1, *, generator=None) -> Tensor + +Fills the tensor with numbers drawn from the Cauchy distribution: + +.. math:: + + f(x) = \dfrac{1}{\pi} \dfrac{\sigma}{(x - \text{median})^2 + \sigma^2} + +.. note:: + Sigma (:math:`\sigma`) is used to denote the scale parameter in Cauchy distribution. +""", +) + +add_docstr_all( + "ceil", + r""" +ceil() -> Tensor + +See :func:`torch.ceil` +""", +) + +add_docstr_all( + "ceil_", + r""" +ceil_() -> Tensor + +In-place version of :meth:`~Tensor.ceil` +""", +) + +add_docstr_all( + "cholesky_solve", + r""" +cholesky_solve(input2, upper=False) -> Tensor + +See :func:`torch.cholesky_solve` +""", +) + +add_docstr_all( + "cholesky_inverse", + r""" +cholesky_inverse(upper=False) -> Tensor + +See :func:`torch.cholesky_inverse` +""", +) + +add_docstr_all( + "clamp", + r""" +clamp(min=None, max=None) -> Tensor + +See :func:`torch.clamp` +""", +) + +add_docstr_all( + "clamp_", + r""" +clamp_(min=None, max=None) -> Tensor + +In-place version of :meth:`~Tensor.clamp` +""", +) + +add_docstr_all( + "clip", + r""" +clip(min=None, max=None) -> Tensor + +Alias for :meth:`~Tensor.clamp`. +""", +) + +add_docstr_all( + "clip_", + r""" +clip_(min=None, max=None) -> Tensor + +Alias for :meth:`~Tensor.clamp_`. +""", +) + +add_docstr_all( + "clone", + r""" +clone(*, memory_format=torch.preserve_format) -> Tensor + +See :func:`torch.clone` +""".format(**common_args), +) + +add_docstr_all( + "coalesce", + r""" +coalesce() -> Tensor + +Returns a coalesced copy of :attr:`self` if :attr:`self` is an +:ref:`uncoalesced tensor `. + +Returns :attr:`self` if :attr:`self` is a coalesced tensor. + +.. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. +""", +) + +add_docstr_all( + "contiguous", + r""" +contiguous(memory_format=torch.contiguous_format) -> Tensor + +Returns a contiguous in memory tensor containing the same data as :attr:`self` tensor. If +:attr:`self` tensor is already in the specified memory format, this function returns the +:attr:`self` tensor. + +Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. +""", +) + +add_docstr_all( + "copy_", + r""" +copy_(src, non_blocking=False) -> Tensor + +Copies the elements from :attr:`src` into :attr:`self` tensor and returns +:attr:`self`. + +The :attr:`src` tensor must be :ref:`broadcastable ` +with the :attr:`self` tensor. It may be of a different data type or reside on a +different device. + +Args: + src (Tensor): the source tensor to copy from + non_blocking (bool, optional): if ``True`` and this copy is between CPU and GPU, + the copy may occur asynchronously with respect to the host. For other + cases, this argument has no effect. Default: ``False`` + +.. note:: + + When :attr:`non_blocking` is ``True`` and the copy is issued on a + non-default CUDA stream, the caller is responsible for proper + cross-stream synchronization. See :ref:`cuda-stream-semantics` for + the required pattern. +""", +) + +add_docstr_all( + "conj", + r""" +conj() -> Tensor + +See :func:`torch.conj` +""", +) + +add_docstr_all( + "conj_physical", + r""" +conj_physical() -> Tensor + +See :func:`torch.conj_physical` +""", +) + +add_docstr_all( + "conj_physical_", + r""" +conj_physical_() -> Tensor + +In-place version of :meth:`~Tensor.conj_physical` +""", +) + +add_docstr_all( + "resolve_conj", + r""" +resolve_conj() -> Tensor + +See :func:`torch.resolve_conj` +""", +) + +add_docstr_all( + "resolve_neg", + r""" +resolve_neg() -> Tensor + +See :func:`torch.resolve_neg` +""", +) + +add_docstr_all( + "copysign", + r""" +copysign(other) -> Tensor + +See :func:`torch.copysign` +""", +) + +add_docstr_all( + "copysign_", + r""" +copysign_(other) -> Tensor + +In-place version of :meth:`~Tensor.copysign` +""", +) + +add_docstr_all( + "cos", + r""" +cos() -> Tensor + +See :func:`torch.cos` +""", +) + +add_docstr_all( + "cos_", + r""" +cos_() -> Tensor + +In-place version of :meth:`~Tensor.cos` +""", +) + +add_docstr_all( + "cosh", + r""" +cosh() -> Tensor + +See :func:`torch.cosh` +""", +) + +add_docstr_all( + "cosh_", + r""" +cosh_() -> Tensor + +In-place version of :meth:`~Tensor.cosh` +""", +) + +add_docstr_all( + "cpu", + r""" +cpu(memory_format=torch.preserve_format) -> Tensor + +Returns a copy of this object in CPU memory. + +If this object is already in CPU memory, +then no copy is performed and the original object is returned. + +Args: + {memory_format} + +""".format(**common_args), +) + +add_docstr_all( + "count_nonzero", + r""" +count_nonzero(dim=None) -> Tensor + +See :func:`torch.count_nonzero` +""", +) + +add_docstr_all( + "cov", + r""" +cov(*, correction=1, fweights=None, aweights=None) -> Tensor + +See :func:`torch.cov` +""", +) + +add_docstr_all( + "corrcoef", + r""" +corrcoef() -> Tensor + +See :func:`torch.corrcoef` +""", +) + +add_docstr_all( + "cross", + r""" +cross(other, dim=None) -> Tensor + +See :func:`torch.cross` +""", +) + +add_docstr_all( + "cuda", + r""" +cuda(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + +Returns a copy of this object in CUDA memory. + +If this object is already in CUDA memory and on the correct device, +then no copy is performed and the original object is returned. + +Args: + device (:class:`torch.device`, optional): The destination GPU device. + Defaults to the current CUDA device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "mtia", + r""" +mtia(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + +Returns a copy of this object in MTIA memory. + +If this object is already in MTIA memory and on the correct device, +then no copy is performed and the original object is returned. + +Args: + device (:class:`torch.device`, optional): The destination MTIA device. + Defaults to the current MTIA device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "ipu", + r""" +ipu(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + +Returns a copy of this object in IPU memory. + +If this object is already in IPU memory and on the correct device, +then no copy is performed and the original object is returned. + +Args: + device (:class:`torch.device`, optional): The destination IPU device. + Defaults to the current IPU device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "xpu", + r""" +xpu(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + +Returns a copy of this object in XPU memory. + +If this object is already in XPU memory and on the correct device, +then no copy is performed and the original object is returned. + +Args: + device (:class:`torch.device`, optional): The destination XPU device. + Defaults to the current XPU device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "logcumsumexp", + r""" +logcumsumexp(dim) -> Tensor + +See :func:`torch.logcumsumexp` +""", +) + +add_docstr_all( + "cummax", + r""" +cummax(dim) -> (Tensor, Tensor) + +See :func:`torch.cummax` +""", +) + +add_docstr_all( + "cummin", + r""" +cummin(dim) -> (Tensor, Tensor) + +See :func:`torch.cummin` +""", +) + +add_docstr_all( + "cumprod", + r""" +cumprod(dim, dtype=None) -> Tensor + +See :func:`torch.cumprod` +""", +) + +add_docstr_all( + "cumprod_", + r""" +cumprod_(dim, dtype=None) -> Tensor + +In-place version of :meth:`~Tensor.cumprod` +""", +) + +add_docstr_all( + "cumsum", + r""" +cumsum(dim, dtype=None) -> Tensor + +See :func:`torch.cumsum` +""", +) + +add_docstr_all( + "cumsum_", + r""" +cumsum_(dim, dtype=None) -> Tensor + +In-place version of :meth:`~Tensor.cumsum` +""", +) + +add_docstr_all( + "const_data_ptr", + r""" +const_data_ptr() -> int + +Returns the address of the first element of :attr:`self` tensor. + +Unlike :meth:`data_ptr`, this is guaranteed to be a read-only access +that will not trigger copy-on-write materialization. For regular +(non-COW) tensors, the return value is identical to :meth:`data_ptr`. + +.. warning:: + + The returned pointer must not be used to mutate the tensor data. + Use :meth:`data_ptr` when write access is needed. +""", +) + +add_docstr_all( + "data_ptr", + r""" +data_ptr() -> int + +Returns the address of the first element of :attr:`self` tensor. + +.. note:: + + If the tensor is a copy-on-write tensor (e.g. created via + :meth:`_lazy_clone`), calling this method will materialize the + copy. Use :meth:`const_data_ptr` if you only need read-only access + to the data pointer. +""", +) + +add_docstr_all( + "dequantize", + r""" +dequantize() -> Tensor + +Given a quantized Tensor, dequantize it and return the dequantized float Tensor. +""", +) + +add_docstr_all( + "dense_dim", + r""" +dense_dim() -> int + +Return the number of dense dimensions in a :ref:`sparse tensor ` :attr:`self`. + +.. note:: + Returns ``len(self.shape)`` if :attr:`self` is not a sparse tensor. + +See also :meth:`Tensor.sparse_dim` and :ref:`hybrid tensors `. +""", +) + +add_docstr_all( + "diag", + r""" +diag(diagonal=0) -> Tensor + +See :func:`torch.diag` +""", +) + +add_docstr_all( + "diag_embed", + r""" +diag_embed(offset=0, dim1=-2, dim2=-1) -> Tensor + +See :func:`torch.diag_embed` +""", +) + +add_docstr_all( + "diagflat", + r""" +diagflat(offset=0) -> Tensor + +See :func:`torch.diagflat` +""", +) + +add_docstr_all( + "diagonal", + r""" +diagonal(offset=0, dim1=0, dim2=1) -> Tensor + +See :func:`torch.diagonal` +""", +) + +add_docstr_all( + "diagonal_scatter", + r""" +diagonal_scatter(src, offset=0, dim1=0, dim2=1) -> Tensor + +See :func:`torch.diagonal_scatter` +""", +) + +add_docstr_all( + "as_strided_scatter", + r""" +as_strided_scatter(src, size, stride, storage_offset=None) -> Tensor + +See :func:`torch.as_strided_scatter` +""", +) + +add_docstr_all( + "fill_diagonal_", + r""" +fill_diagonal_(fill_value, wrap=False) -> Tensor + +Fill the main diagonal of a tensor that has at least 2-dimensions. +When dims>2, all dimensions of input must be of equal length. +This function modifies the input tensor in-place, and returns the input tensor. + +Arguments: + fill_value (Scalar): the fill value + wrap (bool, optional): the diagonal 'wrapped' after N columns for tall matrices. Default: ``False`` + +Example:: + + >>> a = torch.zeros(3, 3) + >>> a.fill_diagonal_(5) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.]]) + >>> b = torch.zeros(7, 3) + >>> b.fill_diagonal_(5) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.], + [0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> c = torch.zeros(7, 3) + >>> c.fill_diagonal_(5, wrap=True) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.], + [0., 0., 0.], + [5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.]]) + +""", +) + +add_docstr_all( + "floor_divide", + r""" +floor_divide(value) -> Tensor + +See :func:`torch.floor_divide` +""", +) + +add_docstr_all( + "floor_divide_", + r""" +floor_divide_(value) -> Tensor + +In-place version of :meth:`~Tensor.floor_divide` +""", +) + +add_docstr_all( + "diff", + r""" +diff(n=1, dim=-1, prepend=None, append=None) -> Tensor + +See :func:`torch.diff` +""", +) + +add_docstr_all( + "digamma", + r""" +digamma() -> Tensor + +See :func:`torch.digamma` +""", +) + +add_docstr_all( + "digamma_", + r""" +digamma_() -> Tensor + +In-place version of :meth:`~Tensor.digamma` +""", +) + +add_docstr_all( + "dim", + r""" +dim() -> int + +Returns the number of dimensions of :attr:`self` tensor. +""", +) + +add_docstr_all( + "dist", + r""" +dist(other, p=2) -> Tensor + +See :func:`torch.dist` +""", +) + +add_docstr_all( + "div", + r""" +div(value, *, rounding_mode=None) -> Tensor + +See :func:`torch.div` +""", +) + +add_docstr_all( + "div_", + r""" +div_(value, *, rounding_mode=None) -> Tensor + +In-place version of :meth:`~Tensor.div` +""", +) + +add_docstr_all( + "divide", + r""" +divide(value, *, rounding_mode=None) -> Tensor + +See :func:`torch.divide` +""", +) + +add_docstr_all( + "divide_", + r""" +divide_(value, *, rounding_mode=None) -> Tensor + +In-place version of :meth:`~Tensor.divide` +""", +) + +add_docstr_all( + "dot", + r""" +dot(other) -> Tensor + +See :func:`torch.dot` +""", +) + +add_docstr_all( + "element_size", + r""" +element_size() -> int + +Returns the size in bytes of an individual element. + +Example:: + + >>> torch.tensor([]).element_size() + 4 + >>> torch.tensor([], dtype=torch.uint8).element_size() + 1 + +""", +) + +add_docstr_all( + "eq", + r""" +eq(other) -> Tensor + +See :func:`torch.eq` +""", +) + +add_docstr_all( + "eq_", + r""" +eq_(other) -> Tensor + +In-place version of :meth:`~Tensor.eq` +""", +) + +add_docstr_all( + "equal", + r""" +equal(other) -> bool + +See :func:`torch.equal` +""", +) + +add_docstr_all( + "erf", + r""" +erf() -> Tensor + +See :func:`torch.erf` +""", +) + +add_docstr_all( + "erf_", + r""" +erf_() -> Tensor + +In-place version of :meth:`~Tensor.erf` +""", +) + +add_docstr_all( + "erfc", + r""" +erfc() -> Tensor + +See :func:`torch.erfc` +""", +) + +add_docstr_all( + "erfc_", + r""" +erfc_() -> Tensor + +In-place version of :meth:`~Tensor.erfc` +""", +) + +add_docstr_all( + "erfinv", + r""" +erfinv() -> Tensor + +See :func:`torch.erfinv` +""", +) + +add_docstr_all( + "erfinv_", + r""" +erfinv_() -> Tensor + +In-place version of :meth:`~Tensor.erfinv` +""", +) + +add_docstr_all( + "exp", + r""" +exp() -> Tensor + +See :func:`torch.exp` +""", +) + +add_docstr_all( + "exp_", + r""" +exp_() -> Tensor + +In-place version of :meth:`~Tensor.exp` +""", +) + +add_docstr_all( + "exp2", + r""" +exp2() -> Tensor + +See :func:`torch.exp2` +""", +) + +add_docstr_all( + "exp2_", + r""" +exp2_() -> Tensor + +In-place version of :meth:`~Tensor.exp2` +""", +) + +add_docstr_all( + "expm1", + r""" +expm1() -> Tensor + +See :func:`torch.expm1` +""", +) + +add_docstr_all( + "expm1_", + r""" +expm1_() -> Tensor + +In-place version of :meth:`~Tensor.expm1` +""", +) + +add_docstr_all( + "exponential_", + r""" +exponential_(lambd=1, *, generator=None) -> Tensor + +Fills :attr:`self` tensor with elements drawn from the PDF (probability density function): + +.. math:: + + f(x) = \lambda e^{-\lambda x}, x > 0 + +.. note:: + In probability theory, exponential distribution is supported on interval [0, :math:`\inf`) (i.e., :math:`x >= 0`) + implying that zero can be sampled from the exponential distribution. + However, :func:`torch.Tensor.exponential_` does not sample zero, + which means that its actual support is the interval (0, :math:`\inf`). + + Note that :func:`torch.distributions.exponential.Exponential` is supported on the interval [0, :math:`\inf`) and can sample zero. +""", +) + +add_docstr_all( + "fill_", + r""" +fill_(value) -> Tensor + +Fills :attr:`self` tensor with the specified value. +""", +) + +add_docstr_all( + "floor", + r""" +floor() -> Tensor + +See :func:`torch.floor` +""", +) + +add_docstr_all( + "flip", + r""" +flip(dims) -> Tensor + +See :func:`torch.flip` +""", +) + +add_docstr_all( + "fliplr", + r""" +fliplr() -> Tensor + +See :func:`torch.fliplr` +""", +) + +add_docstr_all( + "flipud", + r""" +flipud() -> Tensor + +See :func:`torch.flipud` +""", +) + +add_docstr_all( + "roll", + r""" +roll(shifts, dims) -> Tensor + +See :func:`torch.roll` +""", +) + +add_docstr_all( + "floor_", + r""" +floor_() -> Tensor + +In-place version of :meth:`~Tensor.floor` +""", +) + +add_docstr_all( + "fmod", + r""" +fmod(divisor) -> Tensor + +See :func:`torch.fmod` +""", +) + +add_docstr_all( + "fmod_", + r""" +fmod_(divisor) -> Tensor + +In-place version of :meth:`~Tensor.fmod` +""", +) + +add_docstr_all( + "frac", + r""" +frac() -> Tensor + +See :func:`torch.frac` +""", +) + +add_docstr_all( + "frac_", + r""" +frac_() -> Tensor + +In-place version of :meth:`~Tensor.frac` +""", +) + +add_docstr_all( + "frexp", + r""" +frexp(input) -> (Tensor mantissa, Tensor exponent) + +See :func:`torch.frexp` +""", +) + +add_docstr_all( + "flatten", + r""" +flatten(start_dim=0, end_dim=-1) -> Tensor + +See :func:`torch.flatten` +""", +) + +add_docstr_all( + "gather", + r""" +gather(dim, index) -> Tensor + +See :func:`torch.gather` +""", +) + +add_docstr_all( + "gcd", + r""" +gcd(other) -> Tensor + +See :func:`torch.gcd` +""", +) + +add_docstr_all( + "gcd_", + r""" +gcd_(other) -> Tensor + +In-place version of :meth:`~Tensor.gcd` +""", +) + +add_docstr_all( + "ge", + r""" +ge(other) -> Tensor + +See :func:`torch.ge`. +""", +) + +add_docstr_all( + "ge_", + r""" +ge_(other) -> Tensor + +In-place version of :meth:`~Tensor.ge`. +""", +) + +add_docstr_all( + "greater_equal", + r""" +greater_equal(other) -> Tensor + +See :func:`torch.greater_equal`. +""", +) + +add_docstr_all( + "greater_equal_", + r""" +greater_equal_(other) -> Tensor + +In-place version of :meth:`~Tensor.greater_equal`. +""", +) + +add_docstr_all( + "geometric_", + r""" +geometric_(p, *, generator=None) -> Tensor + +Fills :attr:`self` tensor with elements drawn from the geometric distribution: + +.. math:: + + P(X=k) = (1 - p)^{k - 1} p, k = 1, 2, ... + +.. note:: + :func:`torch.Tensor.geometric_` `k`-th trial is the first success hence draws samples in :math:`\{1, 2, \ldots\}`, whereas + :func:`torch.distributions.geometric.Geometric` :math:`(k+1)`-th trial is the first success + hence draws samples in :math:`\{0, 1, \ldots\}`. +""", +) + +add_docstr_all( + "geqrf", + r""" +geqrf() -> (Tensor, Tensor) + +See :func:`torch.geqrf` +""", +) + +add_docstr_all( + "ger", + r""" +ger(vec2) -> Tensor + +See :func:`torch.ger` +""", +) + +add_docstr_all( + "inner", + r""" +inner(other) -> Tensor + +See :func:`torch.inner`. +""", +) + +add_docstr_all( + "outer", + r""" +outer(vec2) -> Tensor + +See :func:`torch.outer`. +""", +) + +add_docstr_all( + "hypot", + r""" +hypot(other) -> Tensor + +See :func:`torch.hypot` +""", +) + +add_docstr_all( + "hypot_", + r""" +hypot_(other) -> Tensor + +In-place version of :meth:`~Tensor.hypot` +""", +) + +add_docstr_all( + "i0", + r""" +i0() -> Tensor + +See :func:`torch.i0` +""", +) + +add_docstr_all( + "i0_", + r""" +i0_() -> Tensor + +In-place version of :meth:`~Tensor.i0` +""", +) + +add_docstr_all( + "igamma", + r""" +igamma(other) -> Tensor + +See :func:`torch.igamma` +""", +) + +add_docstr_all( + "igamma_", + r""" +igamma_(other) -> Tensor + +In-place version of :meth:`~Tensor.igamma` +""", +) + +add_docstr_all( + "igammac", + r""" +igammac(other) -> Tensor +See :func:`torch.igammac` +""", +) + +add_docstr_all( + "igammac_", + r""" +igammac_(other) -> Tensor +In-place version of :meth:`~Tensor.igammac` +""", +) + +add_docstr_all( + "indices", + r""" +indices() -> Tensor + +Return the indices tensor of a :ref:`sparse COO tensor `. + +.. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + +See also :meth:`Tensor.values`. + +.. note:: + This method can only be called on a coalesced sparse tensor. See + :meth:`Tensor.coalesce` for details. +""", +) + +add_docstr_all( + "get_device", + r""" +get_device() -> Device ordinal (Integer) + +For CUDA tensors, this function returns the device ordinal of the GPU on which the tensor resides. +For CPU tensors, this function returns `-1`. + +Example:: + + >>> x = torch.randn(3, 4, 5, device='cuda:0') + >>> x.get_device() + 0 + >>> x.cpu().get_device() + -1 +""", +) + +add_docstr_all( + "values", + r""" +values() -> Tensor + +Return the values tensor of a :ref:`sparse COO tensor `. + +.. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + +See also :meth:`Tensor.indices`. + +.. note:: + This method can only be called on a coalesced sparse tensor. See + :meth:`Tensor.coalesce` for details. +""", +) + +add_docstr_all( + "gt", + r""" +gt(other) -> Tensor + +See :func:`torch.gt`. +""", +) + +add_docstr_all( + "gt_", + r""" +gt_(other) -> Tensor + +In-place version of :meth:`~Tensor.gt`. +""", +) + +add_docstr_all( + "greater", + r""" +greater(other) -> Tensor + +See :func:`torch.greater`. +""", +) + +add_docstr_all( + "greater_", + r""" +greater_(other) -> Tensor + +In-place version of :meth:`~Tensor.greater`. +""", +) + +add_docstr_all( + "hardshrink", + r""" +hardshrink(lambd=0.5) -> Tensor + +See :func:`torch.nn.functional.hardshrink` +""", +) + +add_docstr_all( + "heaviside", + r""" +heaviside(values) -> Tensor + +See :func:`torch.heaviside` +""", +) + +add_docstr_all( + "heaviside_", + r""" +heaviside_(values) -> Tensor + +In-place version of :meth:`~Tensor.heaviside` +""", +) + +add_docstr_all( + "histc", + r""" +histc(bins=100, min=0, max=0) -> Tensor + +See :func:`torch.histc` +""", +) + +add_docstr_all( + "histogram", + r""" +histogram(input, bins, *, range=None, weight=None, density=False) -> (Tensor, Tensor) + +See :func:`torch.histogram` +""", +) + +add_docstr_all( + "index_add_", + r""" +index_add_(dim, index, source, *, alpha=1) -> Tensor + +Accumulate the elements of :attr:`alpha` times ``source`` into the :attr:`self` +tensor by adding to the indices in the order given in :attr:`index`. For example, +if ``dim == 0``, ``index[i] == j``, and ``alpha=-1``, then the ``i``\ th row of +``source`` is subtracted from the ``j``\ th row of :attr:`self`. + +The :attr:`dim`\ th dimension of ``source`` must have the same size as the +length of :attr:`index` (which must be a vector), and all other dimensions must +match :attr:`self`, or an error will be raised. + +For a 3-D tensor the output is given as:: + + self[index[i], :, :] += alpha * src[i, :, :] # if dim == 0 + self[:, index[i], :] += alpha * src[:, i, :] # if dim == 1 + self[:, :, index[i]] += alpha * src[:, :, i] # if dim == 2 + +Note: + {forward_reproducibility_note} + +Args: + dim (int): dimension along which to index + index (Tensor): indices of ``source`` to select from, + should have dtype either `torch.int64` or `torch.int32` + source (Tensor): the tensor containing values to add + +Keyword args: + alpha (Number): the scalar multiplier for ``source`` + +Example:: + + >>> x = torch.ones(5, 3) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2]) + >>> x.index_add_(0, index, t) + tensor([[ 2., 3., 4.], + [ 1., 1., 1.], + [ 8., 9., 10.], + [ 1., 1., 1.], + [ 5., 6., 7.]]) + >>> x.index_add_(0, index, t, alpha=-1) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) +""".format(**reproducibility_notes), +) + +add_docstr_all( + "index_copy_", + r""" +index_copy_(dim, index, tensor) -> Tensor + +Copies the elements of :attr:`tensor` into the :attr:`self` tensor by selecting +the indices in the order given in :attr:`index`. For example, if ``dim == 0`` +and ``index[i] == j``, then the ``i``\ th row of :attr:`tensor` is copied to the +``j``\ th row of :attr:`self`. + +The :attr:`dim`\ th dimension of :attr:`tensor` must have the same size as the +length of :attr:`index` (which must be a vector), and all other dimensions must +match :attr:`self`, or an error will be raised. + +.. note:: + If :attr:`index` contains duplicate entries, multiple elements from + :attr:`tensor` will be copied to the same index of :attr:`self`. The result + is nondeterministic since it depends on which copy occurs last. + +Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`tensor` to select from + tensor (Tensor): the tensor containing values to copy + +Example:: + + >>> x = torch.zeros(5, 3) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2]) + >>> x.index_copy_(0, index, t) + tensor([[ 1., 2., 3.], + [ 0., 0., 0.], + [ 7., 8., 9.], + [ 0., 0., 0.], + [ 4., 5., 6.]]) +""", +) + +add_docstr_all( + "index_fill_", + r""" +index_fill_(dim, index, value) -> Tensor + +Fills the elements of the :attr:`self` tensor with value :attr:`value` by +selecting the indices in the order given in :attr:`index`. + +Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`self` tensor to fill in + value (float): the value to fill with + +Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 2]) + >>> x.index_fill_(1, index, -1) + tensor([[-1., 2., -1.], + [-1., 5., -1.], + [-1., 8., -1.]]) +""", +) + +add_docstr_all( + "index_put_", + r""" +index_put_(indices, values, accumulate=False) -> Tensor + +Puts values from the tensor :attr:`values` into the tensor :attr:`self` using +the indices specified in :attr:`indices` (which is a tuple of Tensors). The +expression ``tensor.index_put_(indices, values)`` is equivalent to +``tensor[indices] = values``. Returns :attr:`self`. + +If :attr:`accumulate` is ``True``, the elements in :attr:`values` are added to +:attr:`self`. If accumulate is ``False``, the behavior is undefined if indices +contain duplicate elements. + +Args: + indices (tuple of LongTensor): tensors used to index into `self`. + values (Tensor): tensor of same dtype as `self`. + accumulate (bool): whether to accumulate into self +""", +) + +add_docstr_all( + "index_put", + r""" +index_put(indices, values, accumulate=False) -> Tensor + +Out-place version of :meth:`~Tensor.index_put_`. +""", +) + +add_docstr_all( + "index_reduce_", + r""" +index_reduce_(dim, index, source, reduce, *, include_self=True) -> Tensor + +Accumulate the elements of ``source`` into the :attr:`self` +tensor by accumulating to the indices in the order given in :attr:`index` +using the reduction given by the ``reduce`` argument. For example, if ``dim == 0``, +``index[i] == j``, ``reduce == prod`` and ``include_self == True`` then the ``i``\ th +row of ``source`` is multiplied by the ``j``\ th row of :attr:`self`. If +:obj:`include_self="True"`, the values in the :attr:`self` tensor are included +in the reduction, otherwise, rows in the :attr:`self` tensor that are accumulated +to are treated as if they were filled with the reduction identities. + +The :attr:`dim`\ th dimension of ``source`` must have the same size as the +length of :attr:`index` (which must be a vector), and all other dimensions must +match :attr:`self`, or an error will be raised. + +For a 3-D tensor with :obj:`reduce="prod"` and :obj:`include_self=True` the +output is given as:: + + self[index[i], :, :] *= src[i, :, :] # if dim == 0 + self[:, index[i], :] *= src[:, i, :] # if dim == 1 + self[:, :, index[i]] *= src[:, :, i] # if dim == 2 + +Note: + {forward_reproducibility_note} + +.. note:: + + This function only supports floating point tensors. + +.. warning:: + + This function is in beta and may change in the near future. + +Args: + dim (int): dimension along which to index + index (Tensor): indices of :attr:`self` to accumulate into, + should have dtype either `torch.int64` or `torch.int32` + source (FloatTensor): the tensor containing values to accumulate + reduce (str): the reduction operation to apply + (:obj:`"prod"`, :obj:`"mean"`, :obj:`"amax"`, :obj:`"amin"`) + +Keyword args: + include_self (bool): whether the elements from the ``self`` tensor are + included in the reduction + +Example:: + + >>> x = torch.empty(5, 3).fill_(2) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2, 0]) + >>> x.index_reduce_(0, index, t, 'prod') + tensor([[20., 44., 72.], + [ 2., 2., 2.], + [14., 16., 18.], + [ 2., 2., 2.], + [ 8., 10., 12.]]) + >>> x = torch.empty(5, 3).fill_(2) + >>> x.index_reduce_(0, index, t, 'prod', include_self=False) + tensor([[10., 22., 36.], + [ 2., 2., 2.], + [ 7., 8., 9.], + [ 2., 2., 2.], + [ 4., 5., 6.]]) +""".format(**reproducibility_notes), +) + +add_docstr_all( + "index_select", + r""" +index_select(dim, index) -> Tensor + +See :func:`torch.index_select` +""", +) + +add_docstr_all( + "sparse_mask", + r""" +sparse_mask(mask) -> Tensor + +Returns a new :ref:`sparse tensor ` with values from a +strided tensor :attr:`self` filtered by the indices of the sparse +tensor :attr:`mask`. The values of :attr:`mask` sparse tensor are +ignored. :attr:`self` and :attr:`mask` tensors must have the same +shape. + +.. note:: + + The returned sparse tensor might contain duplicate values if :attr:`mask` + is not coalesced. It is therefore advisable to pass ``mask.coalesce()`` + if such behavior is not desired. + +.. note:: + + The returned sparse tensor has the same indices as the sparse tensor + :attr:`mask`, even when the corresponding values in :attr:`self` are + zeros. + +Args: + mask (Tensor): a sparse tensor whose indices are used as a filter + +Example:: + + >>> nse = 5 + >>> dims = (5, 5, 2, 2) + >>> I = torch.cat([torch.randint(0, dims[0], size=(nse,)), + ... torch.randint(0, dims[1], size=(nse,))], 0).reshape(2, nse) + >>> V = torch.randn(nse, dims[2], dims[3]) + >>> S = torch.sparse_coo_tensor(I, V, dims).coalesce() + >>> D = torch.randn(dims) + >>> D.sparse_mask(S) + tensor(indices=tensor([[0, 0, 0, 2], + [0, 1, 4, 3]]), + values=tensor([[[ 1.6550, 0.2397], + [-0.1611, -0.0779]], + + [[ 0.2326, -1.0558], + [ 1.4711, 1.9678]], + + [[-0.5138, -0.0411], + [ 1.9417, 0.5158]], + + [[ 0.0793, 0.0036], + [-0.2569, -0.1055]]]), + size=(5, 5, 2, 2), nnz=4, layout=torch.sparse_coo) +""", +) + +add_docstr_all( + "inverse", + r""" +inverse() -> Tensor + +See :func:`torch.inverse` +""", +) + +add_docstr_all( + "isnan", + r""" +isnan() -> Tensor + +See :func:`torch.isnan` +""", +) + +add_docstr_all( + "isinf", + r""" +isinf() -> Tensor + +See :func:`torch.isinf` +""", +) + +add_docstr_all( + "isposinf", + r""" +isposinf() -> Tensor + +See :func:`torch.isposinf` +""", +) + +add_docstr_all( + "isneginf", + r""" +isneginf() -> Tensor + +See :func:`torch.isneginf` +""", +) + +add_docstr_all( + "isfinite", + r""" +isfinite() -> Tensor + +See :func:`torch.isfinite` +""", +) + +add_docstr_all( + "isclose", + r""" +isclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + +See :func:`torch.isclose` +""", +) + +add_docstr_all( + "isreal", + r""" +isreal() -> Tensor + +See :func:`torch.isreal` +""", +) + +add_docstr_all( + "is_coalesced", + r""" +is_coalesced() -> bool + +Returns ``True`` if :attr:`self` is a :ref:`sparse COO tensor +` that is coalesced, ``False`` otherwise. + +.. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + +See :meth:`coalesce` and :ref:`uncoalesced tensors `. +""", +) + +add_docstr_all( + "is_contiguous", + r""" +is_contiguous(memory_format=torch.contiguous_format) -> bool + +Returns True if :attr:`self` tensor is contiguous in memory in the order specified +by memory format. + +Args: + memory_format (:class:`torch.memory_format`, optional): Specifies memory allocation + order. Default: ``torch.contiguous_format``. +""", +) + +add_docstr_all( + "is_pinned", + r""" +Returns true if this tensor resides in pinned memory. +By default, the device pinned memory on will be the current :ref:`accelerator`. +""", +) + +add_docstr_all( + "is_floating_point", + r""" +is_floating_point() -> bool + +Returns True if the data type of :attr:`self` is a floating point data type. +""", +) + +add_docstr_all( + "is_complex", + r""" +is_complex() -> bool + +Returns True if the data type of :attr:`self` is a complex data type. +""", +) + +add_docstr_all( + "is_inference", + r""" +is_inference() -> bool + +See :func:`torch.is_inference` +""", +) + +add_docstr_all( + "is_conj", + r""" +is_conj() -> bool + +Returns True if the conjugate bit of :attr:`self` is set to true. +""", +) + +add_docstr_all( + "is_neg", + r""" +is_neg() -> bool + +Returns True if the negative bit of :attr:`self` is set to true. +""", +) + +add_docstr_all( + "is_signed", + r""" +is_signed() -> bool + +Returns True if the data type of :attr:`self` is a signed data type. +""", +) + +add_docstr_all( + "is_set_to", + r""" +is_set_to(tensor) -> bool + +Returns True if both tensors are pointing to the exact same memory (same +storage, offset, size and stride). +""", +) + +add_docstr_all( + "item", + r""" +item() -> number + +Returns the value of this tensor as a standard Python number. This only works +for tensors with one element. For other cases, see :meth:`~Tensor.tolist`. + +This operation is not differentiable. + +Example:: + + >>> x = torch.tensor([1.0]) + >>> x.item() + 1.0 + +""", +) + +add_docstr_all( + "kron", + r""" +kron(other) -> Tensor + +See :func:`torch.kron` +""", +) + +add_docstr_all( + "kthvalue", + r""" +kthvalue(k, dim=None, keepdim=False) -> (Tensor, LongTensor) + +See :func:`torch.kthvalue` +""", +) + +add_docstr_all( + "ldexp", + r""" +ldexp(other) -> Tensor + +See :func:`torch.ldexp` +""", +) + +add_docstr_all( + "ldexp_", + r""" +ldexp_(other) -> Tensor + +In-place version of :meth:`~Tensor.ldexp` +""", +) + +add_docstr_all( + "lcm", + r""" +lcm(other) -> Tensor + +See :func:`torch.lcm` +""", +) + +add_docstr_all( + "lcm_", + r""" +lcm_(other) -> Tensor + +In-place version of :meth:`~Tensor.lcm` +""", +) + +add_docstr_all( + "le", + r""" +le(other) -> Tensor + +See :func:`torch.le`. +""", +) + +add_docstr_all( + "le_", + r""" +le_(other) -> Tensor + +In-place version of :meth:`~Tensor.le`. +""", +) + +add_docstr_all( + "less_equal", + r""" +less_equal(other) -> Tensor + +See :func:`torch.less_equal`. +""", +) + +add_docstr_all( + "less_equal_", + r""" +less_equal_(other) -> Tensor + +In-place version of :meth:`~Tensor.less_equal`. +""", +) + +add_docstr_all( + "lerp", + r""" +lerp(end, weight) -> Tensor + +See :func:`torch.lerp` +""", +) + +add_docstr_all( + "lerp_", + r""" +lerp_(end, weight) -> Tensor + +In-place version of :meth:`~Tensor.lerp` +""", +) + +add_docstr_all( + "lgamma", + r""" +lgamma() -> Tensor + +See :func:`torch.lgamma` +""", +) + +add_docstr_all( + "lgamma_", + r""" +lgamma_() -> Tensor + +In-place version of :meth:`~Tensor.lgamma` +""", +) + +add_docstr_all( + "log", + r""" +log() -> Tensor + +See :func:`torch.log` +""", +) + +add_docstr_all( + "log_", + r""" +log_() -> Tensor + +In-place version of :meth:`~Tensor.log` +""", +) + +add_docstr_all( + "log10", + r""" +log10() -> Tensor + +See :func:`torch.log10` +""", +) + +add_docstr_all( + "log10_", + r""" +log10_() -> Tensor + +In-place version of :meth:`~Tensor.log10` +""", +) + +add_docstr_all( + "log1p", + r""" +log1p() -> Tensor + +See :func:`torch.log1p` +""", +) + +add_docstr_all( + "log1p_", + r""" +log1p_() -> Tensor + +In-place version of :meth:`~Tensor.log1p` +""", +) + +add_docstr_all( + "log2", + r""" +log2() -> Tensor + +See :func:`torch.log2` +""", +) + +add_docstr_all( + "log2_", + r""" +log2_() -> Tensor + +In-place version of :meth:`~Tensor.log2` +""", +) + +add_docstr_all( + "logaddexp", + r""" +logaddexp(other) -> Tensor + +See :func:`torch.logaddexp` +""", +) + +add_docstr_all( + "logaddexp2", + r""" +logaddexp2(other) -> Tensor + +See :func:`torch.logaddexp2` +""", +) + +add_docstr_all( + "log_normal_", + r""" +log_normal_(mean=1, std=2, *, generator=None) + +Fills :attr:`self` tensor with numbers samples from the log-normal distribution +parameterized by the given mean :math:`\mu` and standard deviation +:math:`\sigma`. Note that :attr:`mean` and :attr:`std` are the mean and +standard deviation of the underlying normal distribution, and not of the +returned distribution: + +.. math:: + + f(x) = \dfrac{1}{x \sigma \sqrt{2\pi}}\ e^{-\frac{(\ln x - \mu)^2}{2\sigma^2}} +""", +) + +add_docstr_all( + "logsumexp", + r""" +logsumexp(dim, keepdim=False) -> Tensor + +See :func:`torch.logsumexp` +""", +) + +add_docstr_all( + "lt", + r""" +lt(other) -> Tensor + +See :func:`torch.lt`. +""", +) + +add_docstr_all( + "lt_", + r""" +lt_(other) -> Tensor + +In-place version of :meth:`~Tensor.lt`. +""", +) + +add_docstr_all( + "less", + r""" +lt(other) -> Tensor + +See :func:`torch.less`. +""", +) + +add_docstr_all( + "less_", + r""" +less_(other) -> Tensor + +In-place version of :meth:`~Tensor.less`. +""", +) + +add_docstr_all( + "lu_solve", + r""" +lu_solve(LU_data, LU_pivots) -> Tensor + +See :func:`torch.lu_solve` +""", +) + +add_docstr_all( + "map_", + r""" +map_(tensor, callable) + +Applies :attr:`callable` for each element in :attr:`self` tensor and the given +:attr:`tensor` and stores the results in :attr:`self` tensor. :attr:`self` tensor and +the given :attr:`tensor` must be :ref:`broadcastable `. + +The :attr:`callable` should have the signature:: + + def callable(a, b) -> number +""", +) + +add_docstr_all( + "masked_scatter_", + r""" +masked_scatter_(mask, source) + +Copies elements from :attr:`source` into :attr:`self` tensor at positions where +the :attr:`mask` is True. Elements from :attr:`source` are copied into :attr:`self` +starting at position 0 of :attr:`source` and continuing in order one-by-one for each +occurrence of :attr:`mask` being True. +The shape of :attr:`mask` must be :ref:`broadcastable ` +with the shape of the underlying tensor. The :attr:`source` should have at least +as many elements as the number of ones in :attr:`mask`. + +Args: + mask (BoolTensor): the boolean mask + source (Tensor): the tensor to copy from + +.. note:: + + The :attr:`mask` operates on the :attr:`self` tensor, not on the given + :attr:`source` tensor. + +Example: + + >>> self = torch.tensor([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) + >>> mask = torch.tensor( + ... [[0, 0, 0, 1, 1], [1, 1, 0, 1, 1]], + ... dtype=torch.bool, + ... ) + >>> source = torch.tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) + >>> self.masked_scatter_(mask, source) + tensor([[0, 0, 0, 0, 1], + [2, 3, 0, 4, 5]]) + +""", +) + +add_docstr_all( + "masked_fill_", + r""" +masked_fill_(mask, value) + +Fills elements of :attr:`self` tensor with :attr:`value` where :attr:`mask` is +True. The shape of :attr:`mask` must be +:ref:`broadcastable ` with the shape of the underlying +tensor. + +Args: + mask (BoolTensor): the boolean mask + value (float): the value to fill in with +""", +) + +add_docstr_all( + "masked_select", + r""" +masked_select(mask) -> Tensor + +See :func:`torch.masked_select` +""", +) + +add_docstr_all( + "matrix_power", + r""" +matrix_power(n) -> Tensor + +.. note:: :meth:`~Tensor.matrix_power` is deprecated, use :func:`torch.linalg.matrix_power` instead. + +Alias for :func:`torch.linalg.matrix_power` +""", +) + +add_docstr_all( + "matrix_exp", + r""" +matrix_exp() -> Tensor + +See :func:`torch.matrix_exp` +""", +) + +add_docstr_all( + "max", + r""" +max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + +See :func:`torch.max` +""", +) + +add_docstr_all( + "amax", + r""" +amax(dim=None, keepdim=False) -> Tensor + +See :func:`torch.amax` +""", +) + +add_docstr_all( + "maximum", + r""" +maximum(other) -> Tensor + +See :func:`torch.maximum` +""", +) + +add_docstr_all( + "fmax", + r""" +fmax(other) -> Tensor + +See :func:`torch.fmax` +""", +) + +add_docstr_all( + "argmax", + r""" +argmax(dim=None, keepdim=False) -> LongTensor + +See :func:`torch.argmax` +""", +) + +add_docstr_all( + "argwhere", + r""" +argwhere() -> Tensor + +See :func:`torch.argwhere` +""", +) + +add_docstr_all( + "mean", + r""" +mean(dim=None, keepdim=False, *, dtype=None) -> Tensor + +See :func:`torch.mean` +""", +) + +add_docstr_all( + "nanmean", + r""" +nanmean(dim=None, keepdim=False, *, dtype=None) -> Tensor + +See :func:`torch.nanmean` +""", +) + +add_docstr_all( + "median", + r""" +median(dim=None, keepdim=False) -> (Tensor, LongTensor) + +See :func:`torch.median` +""", +) + +add_docstr_all( + "nanmedian", + r""" +nanmedian(dim=None, keepdim=False) -> (Tensor, LongTensor) + +See :func:`torch.nanmedian` +""", +) + +add_docstr_all( + "min", + r""" +min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + +See :func:`torch.min` +""", +) + +add_docstr_all( + "amin", + r""" +amin(dim=None, keepdim=False) -> Tensor + +See :func:`torch.amin` +""", +) + +add_docstr_all( + "minimum", + r""" +minimum(other) -> Tensor + +See :func:`torch.minimum` +""", +) + +add_docstr_all( + "aminmax", + r""" +aminmax(*, dim=None, keepdim=False) -> (Tensor min, Tensor max) + +See :func:`torch.aminmax` +""", +) + +add_docstr_all( + "fmin", + r""" +fmin(other) -> Tensor + +See :func:`torch.fmin` +""", +) + +add_docstr_all( + "argmin", + r""" +argmin(dim=None, keepdim=False) -> LongTensor + +See :func:`torch.argmin` +""", +) + +add_docstr_all( + "mm", + r""" +mm(mat2) -> Tensor + +See :func:`torch.mm` +""", +) + +add_docstr_all( + "mode", + r""" +mode(dim=None, keepdim=False) -> (Tensor, LongTensor) + +See :func:`torch.mode` +""", +) + +add_docstr_all( + "movedim", + r""" +movedim(source, destination) -> Tensor + +See :func:`torch.movedim` +""", +) + +add_docstr_all( + "moveaxis", + r""" +moveaxis(source, destination) -> Tensor + +See :func:`torch.moveaxis` +""", +) + +add_docstr_all( + "mul", + r""" +mul(value) -> Tensor + +See :func:`torch.mul`. +""", +) + +add_docstr_all( + "mul_", + r""" +mul_(value) -> Tensor + +In-place version of :meth:`~Tensor.mul`. +""", +) + +add_docstr_all( + "multiply", + r""" +multiply(value) -> Tensor + +See :func:`torch.multiply`. +""", +) + +add_docstr_all( + "multiply_", + r""" +multiply_(value) -> Tensor + +In-place version of :meth:`~Tensor.multiply`. +""", +) + +add_docstr_all( + "multinomial", + r""" +multinomial(num_samples, replacement=False, *, generator=None) -> Tensor + +See :func:`torch.multinomial` +""", +) + +add_docstr_all( + "mv", + r""" +mv(vec) -> Tensor + +See :func:`torch.mv` +""", +) + +add_docstr_all( + "mvlgamma", + r""" +mvlgamma(p) -> Tensor + +See :func:`torch.mvlgamma` +""", +) + +add_docstr_all( + "mvlgamma_", + r""" +mvlgamma_(p) -> Tensor + +In-place version of :meth:`~Tensor.mvlgamma` +""", +) + +add_docstr_all( + "narrow", + r""" +narrow(dimension, start, length) -> Tensor + +See :func:`torch.narrow`. +""", +) + +add_docstr_all( + "narrow_copy", + r""" +narrow_copy(dimension, start, length) -> Tensor + +See :func:`torch.narrow_copy`. +""", +) + +add_docstr_all( + "ndimension", + r""" +ndimension() -> int + +Alias for :meth:`~Tensor.dim()` +""", +) + +add_docstr_all( + "nan_to_num", + r""" +nan_to_num(nan=0.0, posinf=None, neginf=None) -> Tensor + +See :func:`torch.nan_to_num`. +""", +) + +add_docstr_all( + "nan_to_num_", + r""" +nan_to_num_(nan=0.0, posinf=None, neginf=None) -> Tensor + +In-place version of :meth:`~Tensor.nan_to_num`. +""", +) + +add_docstr_all( + "ne", + r""" +ne(other) -> Tensor + +See :func:`torch.ne`. +""", +) + +add_docstr_all( + "ne_", + r""" +ne_(other) -> Tensor + +In-place version of :meth:`~Tensor.ne`. +""", +) + +add_docstr_all( + "not_equal", + r""" +not_equal(other) -> Tensor + +See :func:`torch.not_equal`. +""", +) + +add_docstr_all( + "not_equal_", + r""" +not_equal_(other) -> Tensor + +In-place version of :meth:`~Tensor.not_equal`. +""", +) + +add_docstr_all( + "neg", + r""" +neg() -> Tensor + +See :func:`torch.neg` +""", +) + +add_docstr_all( + "negative", + r""" +negative() -> Tensor + +See :func:`torch.negative` +""", +) + +add_docstr_all( + "neg_", + r""" +neg_() -> Tensor + +In-place version of :meth:`~Tensor.neg` +""", +) + +add_docstr_all( + "negative_", + r""" +negative_() -> Tensor + +In-place version of :meth:`~Tensor.negative` +""", +) + +add_docstr_all( + "nelement", + r""" +nelement() -> int + +Alias for :meth:`~Tensor.numel` +""", +) + +add_docstr_all( + "nextafter", + r""" +nextafter(other) -> Tensor +See :func:`torch.nextafter` +""", +) + +add_docstr_all( + "nextafter_", + r""" +nextafter_(other) -> Tensor +In-place version of :meth:`~Tensor.nextafter` +""", +) + +add_docstr_all( + "nonzero", + r""" +nonzero() -> LongTensor + +See :func:`torch.nonzero` +""", +) + +add_docstr_all( + "nonzero_static", + r""" +nonzero_static(*, size, fill_value=-1) -> LongTensor + +See :func:`torch.nonzero_static` +""", +) + +add_docstr_all( + "norm", + r""" +norm(p=2, dim=None, keepdim=False) -> Tensor + +See :func:`torch.norm` +""", +) + +add_docstr_all( + "normal_", + r""" +normal_(mean=0, std=1, *, generator=None) -> Tensor + +Fills :attr:`self` tensor with elements samples from the normal distribution +parameterized by :attr:`mean` and :attr:`std`. +""", +) + +add_docstr_all( + "numel", + r""" +numel() -> int + +See :func:`torch.numel` +""", +) + +add_docstr_all( + "numpy", + r""" +numpy(*, force=False) -> numpy.ndarray + +Returns the tensor as a NumPy :class:`ndarray`. + +If :attr:`force` is ``False`` (the default), the conversion +is performed only if the tensor is on the CPU, does not require grad, +does not have its conjugate bit set, and is a dtype and layout that +NumPy supports. The returned ndarray and the tensor will share their +storage, so changes to the tensor will be reflected in the ndarray +and vice versa. + +If :attr:`force` is ``True`` this is equivalent to +calling ``t.detach().cpu().resolve_conj().resolve_neg().numpy()``. +If the tensor isn't on the CPU or the conjugate or negative bit is set, +the tensor won't share its storage with the returned ndarray. +Setting :attr:`force` to ``True`` can be a useful shorthand. + +Args: + force (bool): if ``True``, the ndarray may be a copy of the tensor + instead of always sharing memory, defaults to ``False``. +""", +) + +add_docstr_all( + "orgqr", + r""" +orgqr(input2) -> Tensor + +See :func:`torch.orgqr` +""", +) + +add_docstr_all( + "ormqr", + r""" +ormqr(input2, input3, left=True, transpose=False) -> Tensor + +See :func:`torch.ormqr` +""", +) + +add_docstr_all( + "permute", + r""" +permute(*dims) -> Tensor + +Returns a view of the tensor with its dimensions permuted. + +Args: + dims (torch.Size, int..., tuple of int or list of int): the desired ordering of dimensions. + +Example: + >>> x = torch.randn(2, 3, 5) + >>> x.size() + torch.Size([2, 3, 5]) + >>> x.permute(2, 0, 1).size() + torch.Size([5, 2, 3]) +""", +) + +add_docstr_all( + "polygamma", + r""" +polygamma(n) -> Tensor + +See :func:`torch.polygamma` +""", +) + +add_docstr_all( + "polygamma_", + r""" +polygamma_(n) -> Tensor + +In-place version of :meth:`~Tensor.polygamma` +""", +) + +add_docstr_all( + "positive", + r""" +positive() -> Tensor + +See :func:`torch.positive` +""", +) + +add_docstr_all( + "pow", + r""" +pow(exponent) -> Tensor + +See :func:`torch.pow` +""", +) + +add_docstr_all( + "pow_", + r""" +pow_(exponent) -> Tensor + +In-place version of :meth:`~Tensor.pow` +""", +) + +add_docstr_all( + "float_power", + r""" +float_power(exponent) -> Tensor + +See :func:`torch.float_power` +""", +) + +add_docstr_all( + "float_power_", + r""" +float_power_(exponent) -> Tensor + +In-place version of :meth:`~Tensor.float_power` +""", +) + +add_docstr_all( + "prod", + r""" +prod(dim=None, keepdim=False, dtype=None) -> Tensor + +See :func:`torch.prod` +""", +) + +add_docstr_all( + "put_", + r""" +put_(index, source, accumulate=False) -> Tensor + +Copies the elements from :attr:`source` into the positions specified by +:attr:`index`. For the purpose of indexing, the :attr:`self` tensor is treated as if +it were a 1-D tensor. + +:attr:`index` and :attr:`source` need to have the same number of elements, but not necessarily +the same shape. + +If :attr:`accumulate` is ``True``, the elements in :attr:`source` are added to +:attr:`self`. If accumulate is ``False``, the behavior is undefined if :attr:`index` +contain duplicate elements. + +Args: + index (LongTensor): the indices into self + source (Tensor): the tensor containing values to copy from + accumulate (bool, optional): whether to accumulate into self. Default: ``False`` + +Example:: + + >>> src = torch.tensor([[4, 3, 5], + ... [6, 7, 8]]) + >>> src.put_(torch.tensor([1, 3]), torch.tensor([9, 10])) + tensor([[ 4, 9, 5], + [ 10, 7, 8]]) +""", +) + +add_docstr_all( + "put", + r""" +put(input, index, source, accumulate=False) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.put_`. +`input` corresponds to `self` in :meth:`torch.Tensor.put_`. +""", +) + +add_docstr_all( + "qscheme", + r""" +qscheme() -> torch.qscheme + +Returns the quantization scheme of a given QTensor. +""", +) + +add_docstr_all( + "quantile", + r""" +quantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + +See :func:`torch.quantile` +""", +) + +add_docstr_all( + "nanquantile", + r""" +nanquantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + +See :func:`torch.nanquantile` +""", +) + +add_docstr_all( + "q_scale", + r""" +q_scale() -> float + +Given a Tensor quantized by linear(affine) quantization, +returns the scale of the underlying quantizer(). +""", +) + +add_docstr_all( + "q_zero_point", + r""" +q_zero_point() -> int + +Given a Tensor quantized by linear(affine) quantization, +returns the zero_point of the underlying quantizer(). +""", +) + +add_docstr_all( + "q_per_channel_scales", + r""" +q_per_channel_scales() -> Tensor + +Given a Tensor quantized by linear (affine) per-channel quantization, +returns a Tensor of scales of the underlying quantizer. It has the number of +elements that matches the corresponding dimensions (from q_per_channel_axis) of +the tensor. +""", +) + +add_docstr_all( + "q_per_channel_zero_points", + r""" +q_per_channel_zero_points() -> Tensor + +Given a Tensor quantized by linear (affine) per-channel quantization, +returns a tensor of zero_points of the underlying quantizer. It has the number of +elements that matches the corresponding dimensions (from q_per_channel_axis) of +the tensor. +""", +) + +add_docstr_all( + "q_per_channel_axis", + r""" +q_per_channel_axis() -> int + +Given a Tensor quantized by linear (affine) per-channel quantization, +returns the index of dimension on which per-channel quantization is applied. +""", +) + +add_docstr_all( + "random_", + r""" +random_(from=0, to=None, *, generator=None) -> Tensor + +Fills :attr:`self` tensor with numbers sampled from the discrete uniform +distribution over ``[from, to - 1]``. If not specified, the values are usually +only bounded by :attr:`self` tensor's data type. However, for floating point +types, if unspecified, range will be ``[0, 2^mantissa]`` to ensure that every +value is representable. For example, `torch.tensor(1, dtype=torch.double).random_()` +will be uniform in ``[0, 2^53]``. +""", +) + +add_docstr_all( + "rad2deg", + r""" +rad2deg() -> Tensor + +See :func:`torch.rad2deg` +""", +) + +add_docstr_all( + "rad2deg_", + r""" +rad2deg_() -> Tensor + +In-place version of :meth:`~Tensor.rad2deg` +""", +) + +add_docstr_all( + "deg2rad", + r""" +deg2rad() -> Tensor + +See :func:`torch.deg2rad` +""", +) + +add_docstr_all( + "deg2rad_", + r""" +deg2rad_() -> Tensor + +In-place version of :meth:`~Tensor.deg2rad` +""", +) + +add_docstr_all( + "ravel", + r""" +ravel() -> Tensor + +see :func:`torch.ravel` +""", +) + +add_docstr_all( + "reciprocal", + r""" +reciprocal() -> Tensor + +See :func:`torch.reciprocal` +""", +) + +add_docstr_all( + "reciprocal_", + r""" +reciprocal_() -> Tensor + +In-place version of :meth:`~Tensor.reciprocal` +""", +) + +add_docstr_all( + "record_stream", + r""" +record_stream(stream) + +Marks the tensor as having been used by this stream. When the tensor +is deallocated, ensure the tensor memory is not reused for another tensor +until all work queued on :attr:`stream` at the time of deallocation is +complete. + +.. note:: + + The caching allocator is aware of only the stream where a tensor was + allocated. Due to the awareness, it already correctly manages the life + cycle of tensors on only one stream. But if a tensor is used on a stream + different from the stream of origin, the allocator might reuse the memory + unexpectedly. Calling this method lets the allocator know which streams + have used the tensor. + +.. warning:: + + This method is most suitable for use cases where you are providing a + function that created a tensor on a side stream, and want users to be able + to make use of the tensor without having to think carefully about stream + safety when making use of them. These safety guarantees come at some + performance and predictability cost (analogous to the tradeoff between GC + and manual memory management), so if you are in a situation where + you manage the full lifetime of your tensors, you may consider instead + manually managing CUDA events so that calling this method is not necessary. + In particular, when you call this method, on later allocations the + allocator will poll the recorded stream to see if all operations have + completed yet; you can potentially race with side stream computation and + non-deterministically reuse or fail to reuse memory for an allocation. + + You can safely use tensors allocated on side streams without + :meth:`~Tensor.record_stream`; you must manually ensure that + any non-creation stream uses of a tensor are synced back to the creation + stream before you deallocate the tensor. As the CUDA caching allocator + guarantees that the memory will only be reused with the same creation stream, + this is sufficient to ensure that writes to future reallocations of the + memory will be delayed until non-creation stream uses are done. + (Counterintuitively, you may observe that on the CPU side we have already + reallocated the tensor, even though CUDA kernels on the old tensor are + still in progress. This is fine, because CUDA operations on the new + tensor will appropriately wait for the old operations to complete, as they + are all on the same stream.) + + Concretely, this looks like this:: + + with torch.cuda.stream(s0): + x = torch.zeros(N) + + s1.wait_stream(s0) + with torch.cuda.stream(s1): + y = some_comm_op(x) + + ... some compute on s0 ... + + # synchronize creation stream s0 to side stream s1 + # before deallocating x + s0.wait_stream(s1) + del x + + Note that some discretion is required when deciding when to perform + ``s0.wait_stream(s1)``. In particular, if we were to wait immediately + after ``some_comm_op``, there wouldn't be any point in having the side + stream; it would be equivalent to have run ``some_comm_op`` on ``s0``. + Instead, the synchronization must be placed at some appropriate, later + point in time where you expect the side stream ``s1`` to have finished + work. This location is typically identified via profiling, e.g., using + Chrome traces produced + :meth:`torch.autograd.profiler.profile.export_chrome_trace`. If you + place the wait too early, work on s0 will block until ``s1`` has finished, + preventing further overlapping of communication and computation. If you + place the wait too late, you will use more memory than is strictly + necessary (as you are keeping ``x`` live for longer.) For a concrete + example of how this guidance can be applied in practice, see this post: + `FSDP and CUDACachingAllocator + `_. +""", +) + +add_docstr_all( + "remainder", + r""" +remainder(divisor) -> Tensor + +See :func:`torch.remainder` +""", +) + +add_docstr_all( + "remainder_", + r""" +remainder_(divisor) -> Tensor + +In-place version of :meth:`~Tensor.remainder` +""", +) + +add_docstr_all( + "renorm", + r""" +renorm(p, dim, maxnorm) -> Tensor + +See :func:`torch.renorm` +""", +) + +add_docstr_all( + "renorm_", + r""" +renorm_(p, dim, maxnorm) -> Tensor + +In-place version of :meth:`~Tensor.renorm` +""", +) + +add_docstr_all( + "repeat", + r""" +repeat(*repeats) -> Tensor + +Repeats this tensor along the specified dimensions. + +Unlike :meth:`~Tensor.expand`, this function copies the tensor's data. + +.. warning:: + + :meth:`~Tensor.repeat` behaves differently from + `numpy.repeat `_, + but is more similar to + `numpy.tile `_. + For the operator similar to `numpy.repeat`, see :func:`torch.repeat_interleave`. + +Args: + repeat (torch.Size, int..., tuple of int or list of int): The number of times to repeat this tensor along each dimension + +Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat(4, 2) + tensor([[ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3]]) + >>> x.repeat(4, 2, 1).size() + torch.Size([4, 2, 3]) +""", +) + +add_docstr_all( + "repeat_interleave", + r""" +repeat_interleave(repeats, dim=None, *, output_size=None) -> Tensor + +See :func:`torch.repeat_interleave`. +""", +) + +add_docstr_all( + "requires_grad_", + r""" +requires_grad_(requires_grad=True) -> Tensor + +Change if autograd should record operations on this tensor: sets this tensor's +:attr:`requires_grad` attribute in-place. Returns this tensor. + +:func:`requires_grad_`'s main use case is to tell autograd to begin recording +operations on a Tensor ``tensor``. If ``tensor`` has ``requires_grad=False`` +(because it was obtained through a DataLoader, or required preprocessing or +initialization), ``tensor.requires_grad_()`` makes it so that autograd will +begin to record operations on ``tensor``. + +Args: + requires_grad (bool): If autograd should record operations on this tensor. + Default: ``True``. + +Example:: + + >>> # Let's say we want to preprocess some saved weights and use + >>> # the result as new weights. + >>> saved_weights = [0.1, 0.2, 0.3, 0.25] + >>> loaded_weights = torch.tensor(saved_weights) + >>> weights = preprocess(loaded_weights) # some function + >>> weights + tensor([-0.5503, 0.4926, -2.1158, -0.8303]) + + >>> # Now, start to record operations done to weights + >>> weights.requires_grad_() + >>> out = weights.pow(2).sum() + >>> out.backward() + >>> weights.grad + tensor([-1.1007, 0.9853, -4.2316, -1.6606]) + +""", +) + +add_docstr_all( + "reshape", + r""" +reshape(*shape) -> Tensor + +Returns a tensor with the same data and number of elements as :attr:`self` +but with the specified shape. This method returns a view if :attr:`shape` is +compatible with the current shape. See :meth:`torch.Tensor.view` on when it is +possible to return a view. + +See :func:`torch.reshape` + +Args: + shape (tuple of ints or int...): the desired shape + +""", +) + +add_docstr_all( + "reshape_as", + r""" +reshape_as(other) -> Tensor + +Returns this tensor as the same shape as :attr:`other`. +``self.reshape_as(other)`` is equivalent to ``self.reshape(other.sizes())``. +This method returns a view if ``other.sizes()`` is compatible with the current +shape. See :meth:`torch.Tensor.view` on when it is possible to return a view. + +Please see :meth:`reshape` for more information about ``reshape``. + +Args: + other (:class:`torch.Tensor`): The result tensor has the same shape + as :attr:`other`. +""", +) + +add_docstr_all( + "resize_", + r""" +resize_(*sizes, memory_format=torch.contiguous_format) -> Tensor + +Resizes :attr:`self` tensor to the specified size. If the number of elements is +larger than the current storage size, then the underlying storage is resized +to fit the new number of elements. If the number of elements is smaller, the +underlying storage is not changed. Existing elements are preserved but any new +memory is uninitialized. + +.. warning:: + + This is a low-level method. The storage is reinterpreted as C-contiguous, + ignoring the current strides (unless the target size equals the current + size, in which case the tensor is left unchanged). For most purposes, you + will instead want to use :meth:`~Tensor.view()`, which checks for + contiguity, or :meth:`~Tensor.reshape()`, which copies data if needed. To + change the size in-place with custom strides, see :meth:`~Tensor.set_()`. + +.. note:: + + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, new elements are initialized to prevent nondeterministic behavior + from using the result as an input to an operation. Floating point and + complex values are set to NaN, and integer values are set to the maximum + value. + +Args: + sizes (torch.Size or int...): the desired size + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``sizes``. + +Example:: + + >>> x = torch.tensor([[1, 2], [3, 4], [5, 6]]) + >>> x.resize_(2, 2) + tensor([[ 1, 2], + [ 3, 4]]) +""", +) + +add_docstr_all( + "resize_as_", + r""" +resize_as_(tensor, memory_format=torch.contiguous_format) -> Tensor + +Resizes the :attr:`self` tensor to be the same size as the specified +:attr:`tensor`. This is equivalent to ``self.resize_(tensor.size())``. + +Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``tensor.size()``. + +""", +) + +add_docstr_all( + "rot90", + r""" +rot90(k, dims) -> Tensor + +See :func:`torch.rot90` +""", +) + +add_docstr_all( + "round", + r""" +round(decimals=0) -> Tensor + +See :func:`torch.round` +""", +) + +add_docstr_all( + "round_", + r""" +round_(decimals=0) -> Tensor + +In-place version of :meth:`~Tensor.round` +""", +) + +add_docstr_all( + "rsqrt", + r""" +rsqrt() -> Tensor + +See :func:`torch.rsqrt` +""", +) + +add_docstr_all( + "rsqrt_", + r""" +rsqrt_() -> Tensor + +In-place version of :meth:`~Tensor.rsqrt` +""", +) + +add_docstr_all( + "scatter_", + r""" +scatter_(dim, index, src, *, reduce=None) -> Tensor + +Writes all values from the tensor :attr:`src` into :attr:`self` at the indices +specified in the :attr:`index` tensor. For each value in :attr:`src`, its output +index is specified by its index in :attr:`src` for ``dimension != dim`` and by +the corresponding value in :attr:`index` for ``dimension = dim``. + +For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + +This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + +It is also required that +``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that +``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. +Note that ``input`` and ``index`` do not broadcast against each other for NPUs, +so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. +Standard broadcasting occurs in all other cases. + +Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be +between ``0`` and ``self.size(dim) - 1`` inclusive. + +.. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + +.. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + +Additionally accepts an optional :attr:`reduce` argument that allows +specification of an optional reduction operation, which is applied to all +values in the tensor :attr:`src` into :attr:`self` at the indices +specified in the :attr:`index`. For each value in :attr:`src`, the reduction +operation is applied to an index in :attr:`self` which is specified by +its index in :attr:`src` for ``dimension != dim`` and by the corresponding +value in :attr:`index` for ``dimension = dim``. + +Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` +is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + +Reducing with the addition operation is the same as using +:meth:`~torch.Tensor.scatter_add_`. + +.. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + +Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + +Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + +Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + +.. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + +Writes the value from :attr:`value` into :attr:`self` at the indices +specified in the :attr:`index` tensor. This operation is equivalent to the previous version, +with the :attr:`src` tensor filled entirely with :attr:`value`. + +Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + +Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + +Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) +""", +) + +add_docstr_all( + "scatter_add_", + r""" +scatter_add_(dim, index, src) -> Tensor + +Adds all values from the tensor :attr:`src` into :attr:`self` at the indices +specified in the :attr:`index` tensor in a similar fashion as +:meth:`~torch.Tensor.scatter_`. For each value in :attr:`src`, it is added to +an index in :attr:`self` which is specified by its index in :attr:`src` +for ``dimension != dim`` and by the corresponding value in :attr:`index` for +``dimension = dim``. + +For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2 + +:attr:`self`, :attr:`index` and :attr:`src` should have same number of +dimensions. It is also required that ``index.size(d) <= src.size(d)`` for all +dimensions ``d``, and that ``index.size(d) <= self.size(d)`` for all dimensions +``d != dim``. Note that ``index`` and ``src`` do not broadcast. +When :attr:`index` is empty, we always return the original tensor +without further error checking. + +Note: + {forward_reproducibility_note} + +.. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + +Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter and add, can be + either empty or of the same dimensionality as ``src``. When empty, the + operation returns ``self`` unchanged. + src (Tensor): the source elements to scatter and add + +Example:: + + >>> src = torch.ones((2, 5)) + >>> index = torch.tensor([[0, 1, 2, 0, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src) + tensor([[1., 0., 0., 1., 1.], + [0., 1., 0., 0., 0.], + [0., 0., 1., 0., 0.]]) + >>> index = torch.tensor([[0, 1, 2, 0, 0], [0, 1, 2, 2, 2]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src) + tensor([[2., 0., 0., 1., 1.], + [0., 2., 0., 0., 0.], + [0., 0., 2., 1., 1.]]) + +""".format(**reproducibility_notes), +) + +add_docstr_all( + "scatter_reduce_", + r""" +scatter_reduce_(dim, index, src, reduce, *, include_self=True) -> Tensor + +Reduces all values from the :attr:`src` tensor to the indices specified in +the :attr:`index` tensor in the :attr:`self` tensor using the applied reduction +defined via the :attr:`reduce` argument (:obj:`"sum"`, :obj:`"prod"`, :obj:`"mean"`, +:obj:`"amax"`, :obj:`"amin"`). For each value in :attr:`src`, it is reduced to an +index in :attr:`self` which is specified by its index in :attr:`src` for +``dimension != dim`` and by the corresponding value in :attr:`index` for +``dimension = dim``. If :obj:`include_self="True"`, the values in the :attr:`self` +tensor are included in the reduction. + +:attr:`self`, :attr:`index` and :attr:`src` should all have +the same number of dimensions. It is also required that +``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that +``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. +Note that ``index`` and ``src`` do not broadcast. + +For a 3-D tensor with :obj:`reduce="sum"` and :obj:`include_self=True` the +output is given as:: + + self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2 + +Note: + {forward_reproducibility_note} + +.. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + +.. warning:: + + This function is in beta and may change in the near future. + +Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter and reduce. + src (Tensor): the source elements to scatter and reduce + reduce (str): the reduction operation to apply for non-unique indices + (:obj:`"sum"`, :obj:`"prod"`, :obj:`"mean"`, :obj:`"amax"`, :obj:`"amin"`) + include_self (bool): whether elements from the :attr:`self` tensor are + included in the reduction + +Example:: + + >>> src = torch.tensor([1., 2., 3., 4., 5., 6.]) + >>> index = torch.tensor([0, 1, 0, 1, 2, 1]) + >>> input = torch.tensor([1., 2., 3., 4.]) + >>> input.scatter_reduce(0, index, src, reduce="sum") + tensor([5., 14., 8., 4.]) + >>> input.scatter_reduce(0, index, src, reduce="sum", include_self=False) + tensor([4., 12., 5., 4.]) + >>> input2 = torch.tensor([5., 4., 3., 2.]) + >>> input2.scatter_reduce(0, index, src, reduce="amax") + tensor([5., 6., 5., 2.]) + >>> input2.scatter_reduce(0, index, src, reduce="amax", include_self=False) + tensor([3., 6., 5., 2.]) + + +""".format(**reproducibility_notes), +) + +add_docstr_all( + "select", + r""" +select(dim, index) -> Tensor + +See :func:`torch.select` +""", +) + +add_docstr_all( + "select_scatter", + r""" +select_scatter(src, dim, index) -> Tensor + +See :func:`torch.select_scatter` +""", +) + +add_docstr_all( + "slice_scatter", + r""" +slice_scatter(src, dim=0, start=None, end=None, step=1) -> Tensor + +See :func:`torch.slice_scatter` +""", +) + +add_docstr_all( + "set_", + r""" +set_(source=None, storage_offset=0, size=None, stride=None) -> Tensor + +Sets the underlying storage, size, and strides. If :attr:`source` is a tensor, +:attr:`self` tensor will share the same storage and have the same size and +strides as :attr:`source`. Changes to elements in one tensor will be reflected +in the other. + +If :attr:`source` is a :class:`~torch.Storage`, the method sets the underlying +storage, offset, size, and stride. + +Args: + source (Tensor or Storage): the tensor or storage to use + storage_offset (int, optional): the offset in the storage + size (torch.Size, optional): the desired size. Defaults to the size of the source. + stride (tuple, optional): the desired stride. Defaults to C-contiguous strides. +""", +) + +add_docstr_all( + "sigmoid", + r""" +sigmoid() -> Tensor + +See :func:`torch.sigmoid` +""", +) + +add_docstr_all( + "sigmoid_", + r""" +sigmoid_() -> Tensor + +In-place version of :meth:`~Tensor.sigmoid` +""", +) + +add_docstr_all( + "logit", + r""" +logit() -> Tensor + +See :func:`torch.logit` +""", +) + +add_docstr_all( + "logit_", + r""" +logit_() -> Tensor + +In-place version of :meth:`~Tensor.logit` +""", +) + +add_docstr_all( + "sign", + r""" +sign() -> Tensor + +See :func:`torch.sign` +""", +) + +add_docstr_all( + "sign_", + r""" +sign_() -> Tensor + +In-place version of :meth:`~Tensor.sign` +""", +) + +add_docstr_all( + "signbit", + r""" +signbit() -> Tensor + +See :func:`torch.signbit` +""", +) + +add_docstr_all( + "sgn", + r""" +sgn() -> Tensor + +See :func:`torch.sgn` +""", +) + +add_docstr_all( + "sgn_", + r""" +sgn_() -> Tensor + +In-place version of :meth:`~Tensor.sgn` +""", +) + +add_docstr_all( + "sin", + r""" +sin() -> Tensor + +See :func:`torch.sin` +""", +) + +add_docstr_all( + "sin_", + r""" +sin_() -> Tensor + +In-place version of :meth:`~Tensor.sin` +""", +) + +add_docstr_all( + "sinc", + r""" +sinc() -> Tensor + +See :func:`torch.sinc` +""", +) + +add_docstr_all( + "sinc_", + r""" +sinc_() -> Tensor + +In-place version of :meth:`~Tensor.sinc` +""", +) + +add_docstr_all( + "sinh", + r""" +sinh() -> Tensor + +See :func:`torch.sinh` +""", +) + +add_docstr_all( + "sinh_", + r""" +sinh_() -> Tensor + +In-place version of :meth:`~Tensor.sinh` +""", +) + +add_docstr_all( + "size", + r""" +size(dim=None) -> torch.Size or int + +Returns the size of the :attr:`self` tensor. If ``dim`` is not specified, +the returned value is a :class:`torch.Size`, a subclass of :class:`tuple`. +If ``dim`` is specified, returns an int holding the size of that dimension. + +Args: + dim (int, optional): The dimension for which to retrieve the size. + +Example:: + + >>> t = torch.empty(3, 4, 5) + >>> t.size() + torch.Size([3, 4, 5]) + >>> t.size(dim=1) + 4 + +""", +) + +add_docstr_all( + "shape", + r""" +shape() -> torch.Size + +Returns the size of the :attr:`self` tensor. Alias for :attr:`size`. + +See also :meth:`Tensor.size`. + +Example:: + + >>> t = torch.empty(3, 4, 5) + >>> t.size() + torch.Size([3, 4, 5]) + >>> t.shape + torch.Size([3, 4, 5]) + +""", +) + +add_docstr_all( + "sort", + r""" +sort(dim=-1, descending=False) -> (Tensor, LongTensor) + +See :func:`torch.sort` +""", +) + +add_docstr_all( + "msort", + r""" +msort() -> Tensor + +See :func:`torch.msort` +""", +) + +add_docstr_all( + "argsort", + r""" +argsort(dim=-1, descending=False) -> LongTensor + +See :func:`torch.argsort` +""", +) + +add_docstr_all( + "sparse_dim", + r""" +sparse_dim() -> int + +Return the number of sparse dimensions in a :ref:`sparse tensor ` :attr:`self`. + +.. note:: + Returns ``0`` if :attr:`self` is not a sparse tensor. + +See also :meth:`Tensor.dense_dim` and :ref:`hybrid tensors `. +""", +) + +add_docstr_all( + "sparse_resize_", + r""" +sparse_resize_(size, sparse_dim, dense_dim) -> Tensor + +Resizes :attr:`self` :ref:`sparse tensor ` to the desired +size and the number of sparse and dense dimensions. + +.. note:: + If the number of specified elements in :attr:`self` is zero, then + :attr:`size`, :attr:`sparse_dim`, and :attr:`dense_dim` can be any + size and positive integers such that ``len(size) == sparse_dim + + dense_dim``. + + If :attr:`self` specifies one or more elements, however, then each + dimension in :attr:`size` must not be smaller than the corresponding + dimension of :attr:`self`, :attr:`sparse_dim` must equal the number + of sparse dimensions in :attr:`self`, and :attr:`dense_dim` must + equal the number of dense dimensions in :attr:`self`. + +.. warning:: + Throws an error if :attr:`self` is not a sparse tensor. + +Args: + size (torch.Size): the desired size. If :attr:`self` is non-empty + sparse tensor, the desired size cannot be smaller than the + original size. + sparse_dim (int): the number of sparse dimensions + dense_dim (int): the number of dense dimensions +""", +) + +add_docstr_all( + "sparse_resize_and_clear_", + r""" +sparse_resize_and_clear_(size, sparse_dim, dense_dim) -> Tensor + +Removes all specified elements from a :ref:`sparse tensor +` :attr:`self` and resizes :attr:`self` to the desired +size and the number of sparse and dense dimensions. + +.. warning: + Throws an error if :attr:`self` is not a sparse tensor. + +Args: + size (torch.Size): the desired size. + sparse_dim (int): the number of sparse dimensions + dense_dim (int): the number of dense dimensions +""", +) + +add_docstr_all( + "sqrt", + r""" +sqrt() -> Tensor + +See :func:`torch.sqrt` +""", +) + +add_docstr_all( + "sqrt_", + r""" +sqrt_() -> Tensor + +In-place version of :meth:`~Tensor.sqrt` +""", +) + +add_docstr_all( + "square", + r""" +square() -> Tensor + +See :func:`torch.square` +""", +) + +add_docstr_all( + "square_", + r""" +square_() -> Tensor + +In-place version of :meth:`~Tensor.square` +""", +) + +add_docstr_all( + "squeeze", + r""" +squeeze(dim=None) -> Tensor + +See :func:`torch.squeeze` +""", +) + +add_docstr_all( + "squeeze_", + r""" +squeeze_(dim=None) -> Tensor + +In-place version of :meth:`~Tensor.squeeze` +""", +) + +add_docstr_all( + "std", + r""" +std(dim=None, *, correction=1, keepdim=False) -> Tensor + +See :func:`torch.std` +""", +) + +add_docstr_all( + "storage_offset", + r""" +storage_offset() -> int + +Returns :attr:`self` tensor's offset in the underlying storage in terms of +number of storage elements (not bytes). + +Example:: + + >>> x = torch.tensor([1, 2, 3, 4, 5]) + >>> x.storage_offset() + 0 + >>> x[3:].storage_offset() + 3 + +""", +) + +add_docstr_all( + "untyped_storage", + r""" +untyped_storage() -> torch.UntypedStorage + +Returns the underlying :class:`UntypedStorage`. +""", +) + +add_docstr_all( + "stride", + r""" +stride(dim) -> tuple or int + +Returns the stride of :attr:`self` tensor. + +Stride is the jump necessary to go from one element to the next one in the +specified dimension :attr:`dim`. A tuple of all strides is returned when no +argument is passed in. Otherwise, an integer value is returned as the stride in +the particular dimension :attr:`dim`. + +Args: + dim (int, optional): the desired dimension in which stride is required + +Example:: + + >>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) + >>> x.stride() + (5, 1) + >>> x.stride(0) + 5 + >>> x.stride(-1) + 1 + +""", +) + +add_docstr_all( + "sub", + r""" +sub(other, *, alpha=1) -> Tensor + +See :func:`torch.sub`. +""", +) + +add_docstr_all( + "sub_", + r""" +sub_(other, *, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.sub` +""", +) + +add_docstr_all( + "subtract", + r""" +subtract(other, *, alpha=1) -> Tensor + +See :func:`torch.subtract`. +""", +) + +add_docstr_all( + "subtract_", + r""" +subtract_(other, *, alpha=1) -> Tensor + +In-place version of :meth:`~Tensor.subtract`. +""", +) + +add_docstr_all( + "sum", + r""" +sum(dim=None, keepdim=False, dtype=None) -> Tensor + +See :func:`torch.sum` +""", +) + +add_docstr_all( + "nansum", + r""" +nansum(dim=None, keepdim=False, dtype=None) -> Tensor + +See :func:`torch.nansum` +""", +) + +add_docstr_all( + "svd", + r""" +svd(some=True, compute_uv=True) -> (Tensor, Tensor, Tensor) + +See :func:`torch.svd` +""", +) + +add_docstr_all( + "swapdims", + r""" +swapdims(dim0, dim1) -> Tensor + +See :func:`torch.swapdims` +""", +) + +add_docstr_all( + "swapdims_", + r""" +swapdims_(dim0, dim1) -> Tensor + +In-place version of :meth:`~Tensor.swapdims` +""", +) + +add_docstr_all( + "swapaxes", + r""" +swapaxes(axis0, axis1) -> Tensor + +See :func:`torch.swapaxes` +""", +) + +add_docstr_all( + "swapaxes_", + r""" +swapaxes_(axis0, axis1) -> Tensor + +In-place version of :meth:`~Tensor.swapaxes` +""", +) + +add_docstr_all( + "t", + r""" +t() -> Tensor + +See :func:`torch.t` +""", +) + +add_docstr_all( + "t_", + r""" +t_() -> Tensor + +In-place version of :meth:`~Tensor.t` +""", +) + +add_docstr_all( + "tile", + r""" +tile(dims) -> Tensor + +See :func:`torch.tile` +""", +) + +add_docstr_all( + "to", + r""" +to(*args, **kwargs) -> Tensor + +Performs Tensor dtype and/or device conversion. A :class:`torch.dtype` and :class:`torch.device` are +inferred from the arguments of ``self.to(*args, **kwargs)``. + +.. note:: + + If the ``self`` Tensor already + has the correct :class:`torch.dtype` and :class:`torch.device`, then ``self`` is returned. + Otherwise, the returned tensor is a copy of ``self`` with the desired + :class:`torch.dtype` and :class:`torch.device`. + +.. note:: + + If ``self`` requires gradients (``requires_grad=True``) but the target + ``dtype`` specified is an integer type, the returned tensor will implicitly + set ``requires_grad=False``. This is because only tensors with + floating-point or complex dtypes can require gradients. + +Here are the ways to call ``to``: + +.. method:: to(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`dtype` + + Args: + {memory_format} + +.. note:: + + According to `C++ type conversion rules `_, + converting floating point value to integer type will truncate the fractional part. + If the truncated value cannot fit into the target type (e.g., casting ``torch.inf`` to ``torch.long``), + the behavior is undefined and the result may vary across platforms. + +.. method:: to(device=None, dtype=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`device` and (optional) + :attr:`dtype`. If :attr:`dtype` is ``None`` it is inferred to be ``self.dtype``. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Args: + {memory_format} + +.. method:: to(other, non_blocking=False, copy=False) -> Tensor + :noindex: + + Returns a Tensor with same :class:`torch.dtype` and :class:`torch.device` as + the Tensor :attr:`other`. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + +.. note:: + + When :attr:`non_blocking` is ``True`` and the conversion is issued on + a non-default CUDA stream, the caller is responsible for proper + cross-stream synchronization. See :ref:`cuda-stream-semantics` for + the required pattern. + +Example:: + + >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu + >>> tensor.to(torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64) + + >>> cuda0 = torch.device('cuda:0') + >>> tensor.to(cuda0) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], device='cuda:0') + + >>> tensor.to(cuda0, dtype=torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + + >>> other = torch.randn((), dtype=torch.float64, device=cuda0) + >>> tensor.to(other, non_blocking=True) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') +""".format(**common_args), +) + +add_docstr_all( + "byte", + r""" +byte(memory_format=torch.preserve_format) -> Tensor + +``self.byte()`` is equivalent to ``self.to(torch.uint8)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "bool", + r""" +bool(memory_format=torch.preserve_format) -> Tensor + +``self.bool()`` is equivalent to ``self.to(torch.bool)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "char", + r""" +char(memory_format=torch.preserve_format) -> Tensor + +``self.char()`` is equivalent to ``self.to(torch.int8)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "bfloat16", + r""" +bfloat16(memory_format=torch.preserve_format) -> Tensor +``self.bfloat16()`` is equivalent to ``self.to(torch.bfloat16)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "double", + r""" +double(memory_format=torch.preserve_format) -> Tensor + +``self.double()`` is equivalent to ``self.to(torch.float64)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "float", + r""" +float(memory_format=torch.preserve_format) -> Tensor + +``self.float()`` is equivalent to ``self.to(torch.float32)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "cdouble", + r""" +cdouble(memory_format=torch.preserve_format) -> Tensor + +``self.cdouble()`` is equivalent to ``self.to(torch.complex128)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "cfloat", + r""" +cfloat(memory_format=torch.preserve_format) -> Tensor + +``self.cfloat()`` is equivalent to ``self.to(torch.complex64)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "chalf", + r""" +chalf(memory_format=torch.preserve_format) -> Tensor + +``self.chalf()`` is equivalent to ``self.to(torch.complex32)``. See :func:`to`. + +Args: + {memory_format} + """.format(**common_args), +) + +add_docstr_all( + "half", + r""" +half(memory_format=torch.preserve_format) -> Tensor + +``self.half()`` is equivalent to ``self.to(torch.float16)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "int", + r""" +int(memory_format=torch.preserve_format) -> Tensor + +``self.int()`` is equivalent to ``self.to(torch.int32)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "int_repr", + r""" +int_repr() -> Tensor + +Given a quantized Tensor, +``self.int_repr()`` returns a CPU Tensor with uint8_t as data type that stores the +underlying uint8_t values of the given Tensor. +""", +) + + +add_docstr_all( + "long", + r""" +long(memory_format=torch.preserve_format) -> Tensor + +``self.long()`` is equivalent to ``self.to(torch.int64)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "short", + r""" +short(memory_format=torch.preserve_format) -> Tensor + +``self.short()`` is equivalent to ``self.to(torch.int16)``. See :func:`to`. + +Args: + {memory_format} +""".format(**common_args), +) + +add_docstr_all( + "take", + r""" +take(indices) -> Tensor + +See :func:`torch.take` +""", +) + +add_docstr_all( + "take_along_dim", + r""" +take_along_dim(indices, dim) -> Tensor + +See :func:`torch.take_along_dim` +""", +) + +add_docstr_all( + "tan", + r""" +tan() -> Tensor + +See :func:`torch.tan` +""", +) + +add_docstr_all( + "tan_", + r""" +tan_() -> Tensor + +In-place version of :meth:`~Tensor.tan` +""", +) + +add_docstr_all( + "tanh", + r""" +tanh() -> Tensor + +See :func:`torch.tanh` +""", +) + +add_docstr_all( + "softmax", + r""" +softmax(dim) -> Tensor + +Alias for :func:`torch.nn.functional.softmax`. +""", +) + +add_docstr_all( + "tanh_", + r""" +tanh_() -> Tensor + +In-place version of :meth:`~Tensor.tanh` +""", +) + +add_docstr_all( + "tolist", + r""" +tolist() -> list or number + +Returns the tensor as a (nested) list. For scalars, a standard +Python number is returned, just like with :meth:`~Tensor.item`. +Tensors are automatically moved to the CPU first if necessary. + +This operation is not differentiable. + +Examples:: + + >>> a = torch.randn(2, 2) + >>> a.tolist() + [[0.012766935862600803, 0.5415473580360413], + [-0.08909505605697632, 0.7729271650314331]] + >>> a[0,0].tolist() + 0.012766935862600803 +""", +) + +add_docstr_all( + "topk", + r""" +topk(k, dim=None, largest=True, sorted=True) -> (Tensor, LongTensor) + +See :func:`torch.topk` +""", +) + +add_docstr_all( + "to_dense", + r""" +to_dense(dtype=None, *, masked_grad=True) -> Tensor + +Creates a strided copy of :attr:`self` if :attr:`self` is not a strided tensor, otherwise returns :attr:`self`. + +Keyword args: + {dtype} + masked_grad (bool, optional): If set to ``True`` (default) and + :attr:`self` has a sparse layout then the backward of + :meth:`to_dense` returns ``grad.sparse_mask(self)``. + +Example:: + + >>> s = torch.sparse_coo_tensor( + ... torch.tensor([[1, 1], + ... [0, 2]]), + ... torch.tensor([9, 10]), + ... size=(3, 3)) + >>> s.to_dense() + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) +""", +) + +add_docstr_all( + "to_sparse", + r""" +to_sparse(sparseDims) -> Tensor + +Returns a sparse copy of the tensor. PyTorch supports sparse tensors in +:ref:`coordinate format `. + +Args: + sparseDims (int, optional): the number of sparse dimensions to include in the new sparse tensor + +Example:: + + >>> d = torch.tensor([[0, 0, 0], [9, 0, 10], [0, 0, 0]]) + >>> d + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) + >>> d.to_sparse() + tensor(indices=tensor([[1, 1], + [0, 2]]), + values=tensor([ 9, 10]), + size=(3, 3), nnz=2, layout=torch.sparse_coo) + >>> d.to_sparse(1) + tensor(indices=tensor([[1]]), + values=tensor([[ 9, 0, 10]]), + size=(3, 3), nnz=1, layout=torch.sparse_coo) + +.. method:: to_sparse(*, layout=None, blocksize=None, dense_dim=None) -> Tensor + :noindex: + +Returns a sparse tensor with the specified layout and blocksize. If +the :attr:`self` is strided, the number of dense dimensions could be +specified, and a hybrid sparse tensor will be created, with +`dense_dim` dense dimensions and `self.dim() - 2 - dense_dim` batch +dimension. + +.. note:: If the :attr:`self` layout and blocksize parameters match + with the specified layout and blocksize, return + :attr:`self`. Otherwise, return a sparse tensor copy of + :attr:`self`. + +Args: + + layout (:class:`torch.layout`, optional): The desired sparse + layout. One of ``torch.sparse_coo``, ``torch.sparse_csr``, + ``torch.sparse_csc``, ``torch.sparse_bsr``, or + ``torch.sparse_bsc``. Default: if ``None``, + ``torch.sparse_coo``. + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR or BSC tensor. For other layouts, + specifying the block size that is not ``None`` will result in a + RuntimeError exception. A block size must be a tuple of length + two such that its items evenly divide the two sparse dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR, CSC, BSR or BSC tensor. This argument should be + used only if :attr:`self` is a strided tensor, and must be a + value between 0 and dimension of :attr:`self` tensor minus two. + +Example:: + + >>> x = torch.tensor([[1, 0], [0, 0], [2, 3]]) + >>> x.to_sparse(layout=torch.sparse_coo) + tensor(indices=tensor([[0, 2, 2], + [0, 0, 1]]), + values=tensor([1, 2, 3]), + size=(3, 2), nnz=3, layout=torch.sparse_coo) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(1, 2)) + tensor(crow_indices=tensor([0, 1, 1, 2]), + col_indices=tensor([0, 0]), + values=tensor([[[1, 0]], + [[2, 3]]]), size=(3, 2), nnz=2, layout=torch.sparse_bsr) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(2, 1)) + RuntimeError: Tensor size(-2) 3 needs to be divisible by blocksize[0] 2 + >>> x.to_sparse(layout=torch.sparse_csr, blocksize=(3, 1)) + RuntimeError: to_sparse for Strided to SparseCsr conversion does not use specified blocksize + + >>> x = torch.tensor([[[1], [0]], [[0], [0]], [[2], [3]]]) + >>> x.to_sparse(layout=torch.sparse_csr, dense_dim=1) + tensor(crow_indices=tensor([0, 1, 1, 3]), + col_indices=tensor([0, 0, 1]), + values=tensor([[1], + [2], + [3]]), size=(3, 2, 1), nnz=3, layout=torch.sparse_csr) + +""", +) + +add_docstr_all( + "to_sparse_csr", + r""" +to_sparse_csr(dense_dim=None) -> Tensor + +Convert a tensor to compressed row storage format (CSR). Except for +strided tensors, only works with 2D tensors. If the :attr:`self` is +strided, then the number of dense dimensions could be specified, and a +hybrid CSR tensor will be created, with `dense_dim` dense dimensions +and `self.dim() - 2 - dense_dim` batch dimension. + +Args: + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + +Example:: + + >>> dense = torch.randn(5, 5) + >>> sparse = dense.to_sparse_csr() + >>> sparse._nnz() + 25 + + >>> dense = torch.zeros(3, 3, 1, 1) + >>> dense[0, 0] = dense[1, 2] = dense[2, 1] = 1 + >>> dense.to_sparse_csr(dense_dim=2) + tensor(crow_indices=tensor([0, 1, 2, 3]), + col_indices=tensor([0, 2, 1]), + values=tensor([[[1.]], + + [[1.]], + + [[1.]]]), size=(3, 3, 1, 1), nnz=3, + layout=torch.sparse_csr) + +""", +) + +add_docstr_all( + "to_sparse_csc", + r""" +to_sparse_csc() -> Tensor + +Convert a tensor to compressed column storage (CSC) format. Except +for strided tensors, only works with 2D tensors. If the :attr:`self` +is strided, then the number of dense dimensions could be specified, +and a hybrid CSC tensor will be created, with `dense_dim` dense +dimensions and `self.dim() - 2 - dense_dim` batch dimension. + +Args: + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSC tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + +Example:: + + >>> dense = torch.randn(5, 5) + >>> sparse = dense.to_sparse_csc() + >>> sparse._nnz() + 25 + + >>> dense = torch.zeros(3, 3, 1, 1) + >>> dense[0, 0] = dense[1, 2] = dense[2, 1] = 1 + >>> dense.to_sparse_csc(dense_dim=2) + tensor(ccol_indices=tensor([0, 1, 2, 3]), + row_indices=tensor([0, 2, 1]), + values=tensor([[[1.]], + + [[1.]], + + [[1.]]]), size=(3, 3, 1, 1), nnz=3, + layout=torch.sparse_csc) + +""", +) + +add_docstr_all( + "to_sparse_bsr", + r""" +to_sparse_bsr(blocksize, dense_dim) -> Tensor + +Convert a tensor to a block sparse row (BSR) storage format of given +blocksize. If the :attr:`self` is strided, then the number of dense +dimensions could be specified, and a hybrid BSR tensor will be +created, with `dense_dim` dense dimensions and `self.dim() - 2 - +dense_dim` batch dimension. + +Args: + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR tensor. A block size must be a tuple of + length two such that its items evenly divide the two sparse + dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting BSR tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + +Example:: + + >>> dense = torch.randn(10, 10) + >>> sparse = dense.to_sparse_csr() + >>> sparse_bsr = sparse.to_sparse_bsr((5, 5)) + >>> sparse_bsr.col_indices() + tensor([0, 1, 0, 1]) + + >>> dense = torch.zeros(4, 3, 1) + >>> dense[0:2, 0] = dense[0:2, 2] = dense[2:4, 1] = 1 + >>> dense.to_sparse_bsr((2, 1), 1) + tensor(crow_indices=tensor([0, 2, 3]), + col_indices=tensor([0, 2, 1]), + values=tensor([[[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]]]), size=(4, 3, 1), nnz=3, + layout=torch.sparse_bsr) + +""", +) + +add_docstr_all( + "to_sparse_bsc", + r""" +to_sparse_bsc(blocksize, dense_dim) -> Tensor + +Convert a tensor to a block sparse column (BSC) storage format of +given blocksize. If the :attr:`self` is strided, then the number of +dense dimensions could be specified, and a hybrid BSC tensor will be +created, with `dense_dim` dense dimensions and `self.dim() - 2 - +dense_dim` batch dimension. + +Args: + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSC tensor. A block size must be a tuple of + length two such that its items evenly divide the two sparse + dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting BSC tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + +Example:: + + >>> dense = torch.randn(10, 10) + >>> sparse = dense.to_sparse_csr() + >>> sparse_bsc = sparse.to_sparse_bsc((5, 5)) + >>> sparse_bsc.row_indices() + tensor([0, 1, 0, 1]) + + >>> dense = torch.zeros(4, 3, 1) + >>> dense[0:2, 0] = dense[0:2, 2] = dense[2:4, 1] = 1 + >>> dense.to_sparse_bsc((2, 1), 1) + tensor(ccol_indices=tensor([0, 1, 2, 3]), + row_indices=tensor([0, 1, 0]), + values=tensor([[[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]]]), size=(4, 3, 1), nnz=3, + layout=torch.sparse_bsc) + +""", +) + +add_docstr_all( + "to_mkldnn", + r""" +to_mkldnn() -> Tensor +Returns a copy of the tensor in ``torch.mkldnn`` layout. + +""", +) + +add_docstr_all( + "trace", + r""" +trace() -> Tensor + +See :func:`torch.trace` +""", +) + +add_docstr_all( + "transpose", + r""" +transpose(dim0, dim1) -> Tensor + +See :func:`torch.transpose` +""", +) + +add_docstr_all( + "transpose_", + r""" +transpose_(dim0, dim1) -> Tensor + +In-place version of :meth:`~Tensor.transpose` +""", +) + +add_docstr_all( + "triangular_solve", + r""" +triangular_solve(A, upper=True, transpose=False, unitriangular=False) -> (Tensor, Tensor) + +See :func:`torch.triangular_solve` +""", +) + +add_docstr_all( + "tril", + r""" +tril(diagonal=0) -> Tensor + +See :func:`torch.tril` +""", +) + +add_docstr_all( + "tril_", + r""" +tril_(diagonal=0) -> Tensor + +In-place version of :meth:`~Tensor.tril` +""", +) + +add_docstr_all( + "triu", + r""" +triu(diagonal=0) -> Tensor + +See :func:`torch.triu` +""", +) + +add_docstr_all( + "triu_", + r""" +triu_(diagonal=0) -> Tensor + +In-place version of :meth:`~Tensor.triu` +""", +) + +add_docstr_all( + "true_divide", + r""" +true_divide(value) -> Tensor + +See :func:`torch.true_divide` +""", +) + +add_docstr_all( + "true_divide_", + r""" +true_divide_(value) -> Tensor + +In-place version of :meth:`~Tensor.true_divide_` +""", +) + +add_docstr_all( + "trunc", + r""" +trunc() -> Tensor + +See :func:`torch.trunc` +""", +) + +add_docstr_all( + "fix", + r""" +fix() -> Tensor + +See :func:`torch.fix`. +""", +) + +add_docstr_all( + "trunc_", + r""" +trunc_() -> Tensor + +In-place version of :meth:`~Tensor.trunc` +""", +) + +add_docstr_all( + "fix_", + r""" +fix_() -> Tensor + +In-place version of :meth:`~Tensor.fix` +""", +) + +add_docstr_all( + "type", + r""" +type(dtype=None, non_blocking=False, **kwargs) -> str or Tensor +Returns the type if `dtype` is not provided, else casts this object to +the specified type. + +If this is already of the correct type, no copy is performed and the +original object is returned. + +Args: + dtype (dtype or string): The desired type + non_blocking (bool): If ``True``, and the source is in pinned memory + and destination is on the GPU or vice versa, the copy is performed + asynchronously with respect to the host. Otherwise, the argument + has no effect. + **kwargs: For compatibility, may contain the key ``async`` in place of + the ``non_blocking`` argument. The ``async`` arg is deprecated. +""", +) + +add_docstr_all( + "type_as", + r""" +type_as(tensor) -> Tensor + +Returns this tensor cast to the type of the given tensor. + +This is a no-op if the tensor is already of the correct type. This is +equivalent to ``self.type(tensor.type())`` + +Args: + tensor (Tensor): the tensor which has the desired type +""", +) + +add_docstr_all( + "unfold", + r""" +unfold(dimension, size, step) -> Tensor + +Returns a view of the original tensor which contains all slices of size :attr:`size` from +:attr:`self` tensor in the dimension :attr:`dimension`. + +Step between two slices is given by :attr:`step`. + +If `sizedim` is the size of dimension :attr:`dimension` for :attr:`self`, the size of +dimension :attr:`dimension` in the returned tensor will be +`(sizedim - size) / step + 1`. + +An additional dimension of size :attr:`size` is appended in the returned tensor. + +Args: + dimension (int): dimension in which unfolding happens + size (int): the size of each slice that is unfolded + step (int): the step between each slice + +Example:: + + >>> x = torch.arange(1., 8) + >>> x + tensor([ 1., 2., 3., 4., 5., 6., 7.]) + >>> x.unfold(0, 2, 1) + tensor([[ 1., 2.], + [ 2., 3.], + [ 3., 4.], + [ 4., 5.], + [ 5., 6.], + [ 6., 7.]]) + >>> x.unfold(0, 2, 2) + tensor([[ 1., 2.], + [ 3., 4.], + [ 5., 6.]]) +""", +) + +add_docstr_all( + "uniform_", + r""" +uniform_(from=0, to=1, *, generator=None) -> Tensor + +Fills :attr:`self` tensor with numbers sampled from the continuous uniform +distribution: + +.. math:: + f(x) = \dfrac{1}{\text{to} - \text{from}} +""", +) + +add_docstr_all( + "unsqueeze", + r""" +unsqueeze(dim) -> Tensor + +See :func:`torch.unsqueeze` +""", +) + +add_docstr_all( + "unsqueeze_", + r""" +unsqueeze_(dim) -> Tensor + +In-place version of :meth:`~Tensor.unsqueeze` +""", +) + +add_docstr_all( + "var", + r""" +var(dim=None, *, correction=1, keepdim=False) -> Tensor + +See :func:`torch.var` +""", +) + +add_docstr_all( + "vdot", + r""" +vdot(other) -> Tensor + +See :func:`torch.vdot` +""", +) + +add_docstr_all( + "view", + r""" +view(*shape) -> Tensor + +Returns a new tensor with the same data as the :attr:`self` tensor but of a +different :attr:`shape`. + +The returned tensor shares the same data and must have the same number +of elements, but may have a different size. For a tensor to be viewed, the new +view size must be compatible with its original size and stride, i.e., each new +view dimension must either be a subspace of an original dimension, or only span +across original dimensions :math:`d, d+1, \dots, d+k` that satisfy the following +contiguity-like condition that :math:`\forall i = d, \dots, d+k-1`, + +.. math:: + + \text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1] + +Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape` +without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a +:meth:`view` can be performed, it is advisable to use :meth:`reshape`, which +returns a view if the shapes are compatible, and copies (equivalent to calling +:meth:`contiguous`) otherwise. + +Args: + shape (torch.Size or int...): the desired size + +Example:: + + >>> x = torch.randn(4, 4) + >>> x.size() + torch.Size([4, 4]) + >>> y = x.view(16) + >>> y.size() + torch.Size([16]) + >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions + >>> z.size() + torch.Size([2, 8]) + + >>> a = torch.randn(1, 2, 3, 4) + >>> a.size() + torch.Size([1, 2, 3, 4]) + >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension + >>> b.size() + torch.Size([1, 3, 2, 4]) + >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory + >>> c.size() + torch.Size([1, 3, 2, 4]) + >>> torch.equal(b, c) + False + + +.. method:: view(dtype) -> Tensor + :noindex: + +Returns a new tensor with the same data as the :attr:`self` tensor but of a +different :attr:`dtype`. + +If the element size of :attr:`dtype` is different than that of ``self.dtype``, +then the size of the last dimension of the output will be scaled +proportionally. For instance, if :attr:`dtype` element size is twice that of +``self.dtype``, then each pair of elements in the last dimension of +:attr:`self` will be combined, and the size of the last dimension of the output +will be half that of :attr:`self`. If :attr:`dtype` element size is half that +of ``self.dtype``, then each element in the last dimension of :attr:`self` will +be split in two, and the size of the last dimension of the output will be +double that of :attr:`self`. For this to be possible, the following conditions +must be true: + + * ``self.dim()`` must be greater than 0. + * ``self.stride(-1)`` must be 1. + +Additionally, if the element size of :attr:`dtype` is greater than that of +``self.dtype``, the following conditions must be true as well: + + * ``self.size(-1)`` must be divisible by the ratio between the element + sizes of the dtypes. + * ``self.storage_offset()`` must be divisible by the ratio between the + element sizes of the dtypes. + * The strides of all dimensions, except the last dimension, must be + divisible by the ratio between the element sizes of the dtypes. + +If any of the above conditions are not met, an error is thrown. + +.. warning:: + + This overload is not supported by TorchScript, and using it in a Torchscript + program will cause undefined behavior. + + +Args: + dtype (:class:`torch.dtype`): the desired dtype + +Example:: + + >>> x = torch.randn(4, 4) + >>> x + tensor([[ 0.9482, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + >>> x.dtype + torch.float32 + + >>> y = x.view(torch.int32) + >>> y + tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], + [-1105482831, 1061112040, 1057999968, -1084397505], + [-1071760287, -1123489973, -1097310419, -1084649136], + [-1101533110, 1073668768, -1082790149, -1088634448]], + dtype=torch.int32) + >>> y[0, 0] = 1000000000 + >>> x + tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + + >>> x.view(torch.cfloat) + tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], + [-0.1520+0.7472j, 0.5617-0.8649j], + [-2.4724-0.0334j, -0.2976-0.8499j], + [-0.2109+1.9913j, -0.9607-0.6123j]]) + >>> x.view(torch.cfloat).size() + torch.Size([4, 2]) + + >>> x.view(torch.uint8) + tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, + 8, 191], + [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, + 93, 191], + [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, + 89, 191], + [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, + 28, 191]], dtype=torch.uint8) + >>> x.view(torch.uint8).size() + torch.Size([4, 16]) +""", +) + +add_docstr_all( + "view_as", + r""" +view_as(other) -> Tensor + +View this tensor as the same size as :attr:`other`. +``self.view_as(other)`` is equivalent to ``self.view(other.size())``. + +Please see :meth:`~Tensor.view` for more information about ``view``. + +Args: + other (:class:`torch.Tensor`): The result tensor has the same size + as :attr:`other`. +""", +) + +add_docstr_all( + "expand", + r""" +expand(*size) -> Tensor + +Returns a new view of the :attr:`self` tensor with singleton dimensions expanded +to a larger size. + +Passing -1 as the size for a dimension means not changing the size of +that dimension. + +Tensor can be also expanded to a larger number of dimensions, and the +new ones will be appended at the front. For the new dimensions, the +size cannot be set to -1. + +Expanding a tensor does not allocate new memory, but only creates a +new view on the existing tensor where a dimension of size one is +expanded to a larger size by setting the ``stride`` to 0. Any dimension +of size 1 can be expanded to an arbitrary value without allocating new +memory. + +.. note:: + + Operations on an expanded view may still allocate memory if they need to + materialize the expanded values. For example, changing dtype after + :meth:`expand` can allocate memory for the full expanded shape. + +Args: + *size (torch.Size or int...): the desired expanded size + +.. warning:: + + More than one element of an expanded tensor may refer to a single + memory location. As a result, in-place operations (especially ones that + are vectorized) may result in incorrect behavior. If you need to write + to the tensors, please clone them first. + +Example:: + + >>> x = torch.tensor([[1], [2], [3]]) + >>> x.size() + torch.Size([3, 1]) + >>> x.expand(3, 4) + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + >>> x.expand(-1, 4) # -1 means not changing the size of that dimension + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) +""", +) + +add_docstr_all( + "expand_as", + r""" +expand_as(other) -> Tensor + +Expand this tensor to the same size as :attr:`other`. +``self.expand_as(other)`` is equivalent to ``self.expand(other.size())``. + +Please see :meth:`~Tensor.expand` for more information about ``expand``. + +Args: + other (:class:`torch.Tensor`): The result tensor has the same size + as :attr:`other`. +""", +) + +add_docstr_all( + "sum_to_size", + r""" +sum_to_size(*size) -> Tensor + +Sum ``this`` tensor to :attr:`size`. +:attr:`size` must be broadcastable to ``this`` tensor size. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. +""", +) + + +add_docstr_all( + "zero_", + r""" +zero_() -> Tensor + +Fills :attr:`self` tensor with zeros. +""", +) + +add_docstr_all( + "matmul", + r""" +matmul(tensor2) -> Tensor + +See :func:`torch.matmul` +""", +) + +add_docstr_all( + "chunk", + r""" +chunk(chunks, dim=0) -> List of Tensors + +See :func:`torch.chunk` +""", +) + +add_docstr_all( + "unsafe_chunk", + r""" +unsafe_chunk(chunks, dim=0) -> List of Tensors + +See :func:`torch.unsafe_chunk` +""", +) + +add_docstr_all( + "unsafe_split", + r""" +unsafe_split(split_size, dim=0) -> List of Tensors + +See :func:`torch.unsafe_split` +""", +) + +add_docstr_all( + "tensor_split", + r""" +tensor_split(indices_or_sections, dim=0) -> List of Tensors + +See :func:`torch.tensor_split` +""", +) + +add_docstr_all( + "hsplit", + r""" +hsplit(split_size_or_sections) -> List of Tensors + +See :func:`torch.hsplit` +""", +) + +add_docstr_all( + "vsplit", + r""" +vsplit(split_size_or_sections) -> List of Tensors + +See :func:`torch.vsplit` +""", +) + +add_docstr_all( + "dsplit", + r""" +dsplit(split_size_or_sections) -> List of Tensors + +See :func:`torch.dsplit` +""", +) + +add_docstr_all( + "stft", + r""" +stft(frame_length, hop, fft_size=None, return_onesided=True, window=None, + pad_end=0, align_to_window=None) -> Tensor + +See :func:`torch.stft` +""", +) + +add_docstr_all( + "istft", + r""" +istft(n_fft, hop_length=None, win_length=None, window=None, + center=True, normalized=False, onesided=True, length=None) -> Tensor + +See :func:`torch.istft` +""", +) + +add_docstr_all( + "det", + r""" +det() -> Tensor + +See :func:`torch.det` +""", +) + +add_docstr_all( + "where", + r""" +where(condition, y) -> Tensor + +``self.where(condition, y)`` is equivalent to ``torch.where(condition, self, y)``. +See :func:`torch.where` +""", +) + +add_docstr_all( + "logdet", + r""" +logdet() -> Tensor + +See :func:`torch.logdet` +""", +) + +add_docstr_all( + "slogdet", + r""" +slogdet() -> (Tensor, Tensor) + +See :func:`torch.slogdet` +""", +) + +add_docstr_all( + "unbind", + r""" +unbind(dim=0) -> seq + +See :func:`torch.unbind` +""", +) + +add_docstr_all( + "pin_memory", + r""" +pin_memory() -> Tensor + +Copies the tensor to pinned memory, if it's not already pinned. +By default, the device pinned memory on will be the current :ref:`accelerator`. +""", +) + +add_docstr_all( + "pinverse", + r""" +pinverse() -> Tensor + +See :func:`torch.pinverse` +""", +) + +add_docstr_all( + "index_add", + r""" +index_add(dim, index, source, *, alpha=1) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.index_add_`. +""", +) + +add_docstr_all( + "index_copy", + r""" +index_copy(dim, index, tensor2) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.index_copy_`. +""", +) + +add_docstr_all( + "index_fill", + r""" +index_fill(dim, index, value) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.index_fill_`. +""", +) + +add_docstr_all( + "scatter", + r""" +scatter(dim, index, src) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_` +""", +) + +add_docstr_all( + "scatter_add", + r""" +scatter_add(dim, index, src) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_add_` +""", +) + +add_docstr_all( + "scatter_reduce", + r""" +scatter_reduce(dim, index, src, reduce, *, include_self=True) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_reduce_` +""", +) + +add_docstr_all( + "masked_scatter", + r""" +masked_scatter(mask, tensor) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.masked_scatter_` + +.. note:: + + The inputs :attr:`self` and :attr:`mask` + :ref:`broadcast `. + +Example: + + >>> self = torch.tensor([0, 0, 0, 0, 0]) + >>> mask = torch.tensor( + ... [[0, 0, 0, 1, 1], [1, 1, 0, 1, 1]], + ... dtype=torch.bool, + ... ) + >>> source = torch.tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) + >>> self.masked_scatter(mask, source) + tensor([[0, 0, 0, 0, 1], + [2, 3, 0, 4, 5]]) + +""", +) + +add_docstr_all( + "xlogy", + r""" +xlogy(other) -> Tensor + +See :func:`torch.xlogy` +""", +) + +add_docstr_all( + "xlogy_", + r""" +xlogy_(other) -> Tensor + +In-place version of :meth:`~Tensor.xlogy` +""", +) + +add_docstr_all( + "masked_fill", + r""" +masked_fill(mask, value) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.masked_fill_` +""", +) + +add_docstr_all( + "grad", + r""" +This attribute is ``None`` by default and becomes a Tensor the first time a call to +:func:`backward` computes gradients for ``self``. +The attribute will then contain the gradients computed and future calls to +:func:`backward` will accumulate (add) gradients into it. +""", +) + +add_docstr_all( + "grad_dtype", + r""" +The allowed dtype of :attr:``grad`` for this tensor. + +:attr:``grad_dtype`` can be set to a specific dtype or ``None``. By default, +``t.grad_dtype == t.dtype``. When not None, the autograd engine casts +incoming gradients to this dtype. This attribute is only accessible and +settable for leaf tensors. + +.. warning:: + Use with caution. Diverging the dtypes of a tensor and its gradient may + break downstream systems that assume they match. + +Example:: + + >>> x = torch.tensor([1.0, 2.0], requires_grad=True) + >>> x.grad_dtype + torch.float32 + + >>> x.grad_dtype = torch.float16 + >>> x.grad_dtype + torch.float16 + + >>> # Allow any gradient dtype + >>> x.grad_dtype = None + >>> x.grad_dtype +""", +) + +add_docstr_all( + "retain_grad", + r""" +retain_grad() -> None + +Enables this Tensor to have their :attr:`grad` populated during +:func:`backward`. This is a no-op for leaf tensors. +""", +) + +add_docstr_all( + "retains_grad", + r""" +Is ``True`` if this Tensor is non-leaf and its :attr:`grad` is enabled to be +populated during :func:`backward`, ``False`` otherwise. +""", +) + +add_docstr_all( + "requires_grad", + r""" +Is ``True`` if gradients need to be computed for this Tensor, ``False`` otherwise. + +.. note:: + + The fact that gradients need to be computed for a Tensor do not mean that the :attr:`grad` + attribute will be populated, see :attr:`is_leaf` for more details. + +""", +) + +add_docstr_all( + "is_leaf", + r""" +All Tensors that have :attr:`requires_grad` which is ``False`` will be leaf Tensors by convention. + +For Tensors that have :attr:`requires_grad` which is ``True``, they will be leaf Tensors if they were +created by the user. This means that they are not the result of an operation and so +:attr:`grad_fn` is None. + +Only leaf Tensors will have their :attr:`grad` populated during a call to :func:`backward`. +To get :attr:`grad` populated for non-leaf Tensors, you can use :func:`retain_grad`. + +Example:: + + >>> a = torch.rand(10, requires_grad=True) + >>> a.is_leaf + True + >>> b = torch.rand(10, requires_grad=True).cuda() + >>> b.is_leaf + False + # b was created by the operation that cast a cpu Tensor into a cuda Tensor + >>> c = torch.rand(10, requires_grad=True) + 2 + >>> c.is_leaf + False + # c was created by the addition operation + >>> d = torch.rand(10).cuda() + >>> d.is_leaf + True + # d does not require gradients and so has no operation creating it (that is tracked by the autograd engine) + >>> e = torch.rand(10).cuda().requires_grad_() + >>> e.is_leaf + True + # e requires gradients and has no operations creating it + >>> f = torch.rand(10, requires_grad=True, device="cuda") + >>> f.is_leaf + True + # f requires grad, has no operation creating it + + +""", +) + +add_docstr_all( + "is_cuda", + r""" +Is ``True`` if the Tensor is stored on the GPU, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_cpu", + r""" +Is ``True`` if the Tensor is stored on the CPU, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_xla", + r""" +Is ``True`` if the Tensor is stored on an XLA device, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_ipu", + r""" +Is ``True`` if the Tensor is stored on the IPU, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_xpu", + r""" +Is ``True`` if the Tensor is stored on the XPU, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_quantized", + r""" +Is ``True`` if the Tensor is quantized, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_meta", + r""" +Is ``True`` if the Tensor is a meta tensor, ``False`` otherwise. Meta tensors +are like normal tensors, but they carry no data. +""", +) + +add_docstr_all( + "is_mps", + r""" +Is ``True`` if the Tensor is stored on the MPS device, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_sparse", + r""" +Is ``True`` if the Tensor uses sparse COO storage layout, ``False`` otherwise. +""", +) + +add_docstr_all( + "is_sparse_csr", + r""" +Is ``True`` if the Tensor uses sparse CSR storage layout, ``False`` otherwise. +""", +) + +add_docstr_all( + "device", + r""" +Is the :class:`torch.device` where this Tensor is. +""", +) + +add_docstr_all( + "ndim", + r""" +Alias for :meth:`~Tensor.dim()` +""", +) + +add_docstr_all( + "itemsize", + r""" +Alias for :meth:`~Tensor.element_size()` +""", +) + +add_docstr_all( + "nbytes", + r""" +Returns the number of bytes consumed by the "view" of elements of the Tensor +if the Tensor does not use sparse storage layout. +Defined to be :meth:`~Tensor.numel()` * :meth:`~Tensor.element_size()` +""", +) + +add_docstr_all( + "T", + r""" +Returns a view of this tensor with its dimensions reversed. + +If ``n`` is the number of dimensions in ``x``, +``x.T`` is equivalent to ``x.permute(n-1, n-2, ..., 0)``. + +.. warning:: + The use of :attr:`Tensor.T` on tensors of dimension other than 2 to reverse their shape + is deprecated and it will throw an error in a future release. Consider :attr:`~.Tensor.mT` + to transpose batches of matrices or `x.permute(*torch.arange(x.ndim - 1, -1, -1))` to reverse + the dimensions of a tensor. +""", +) + +add_docstr_all( + "H", + r""" +Returns a view of a matrix (2-D tensor) conjugated and transposed. + +``x.H`` is equivalent to ``x.transpose(0, 1).conj()`` for complex matrices and +``x.transpose(0, 1)`` for real matrices. + +.. seealso:: + + :attr:`~.Tensor.mH`: An attribute that also works on batches of matrices. +""", +) + +add_docstr_all( + "mT", + r""" +Returns a view of this tensor with the last two dimensions transposed. + +``x.mT`` is equivalent to ``x.transpose(-2, -1)``. +""", +) + +add_docstr_all( + "mH", + r""" +Accessing this property is equivalent to calling :func:`adjoint`. +""", +) + +add_docstr_all( + "adjoint", + r""" +adjoint() -> Tensor + +Alias for :func:`adjoint` +""", +) + +add_docstr_all( + "real", + r""" +Returns a new tensor containing real values of the :attr:`self` tensor for a complex-valued input tensor. +The returned tensor and :attr:`self` share the same underlying storage. + +Returns :attr:`self` if :attr:`self` is a real-valued tensor. + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.real + tensor([ 0.3100, -0.5445, -1.6492, -0.0638]) + +""", +) + +add_docstr_all( + "imag", + r""" +Returns a new tensor containing imaginary values of the :attr:`self` tensor. +The returned tensor and :attr:`self` share the same underlying storage. + +.. warning:: + :func:`imag` is only supported for tensors with complex dtypes. + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.imag + tensor([ 0.3553, -0.7896, -0.0633, -0.8119]) + +""", +) + +add_docstr_all( + "as_subclass", + r""" +as_subclass(cls) -> Tensor + +Makes a ``cls`` instance with the same data pointer as ``self``. Changes +in the output mirror changes in ``self``, and the output stays attached +to the autograd graph. ``cls`` must be a subclass of ``Tensor``. +""", +) + +add_docstr_all( + "crow_indices", + r""" +crow_indices() -> IntTensor + +Returns the tensor containing the compressed row indices of the :attr:`self` +tensor when :attr:`self` is a sparse CSR tensor of layout ``sparse_csr``. +The ``crow_indices`` tensor is strictly of shape (:attr:`self`.size(0) + 1) +and of type ``int32`` or ``int64``. When using MKL routines such as sparse +matrix multiplication, it is necessary to use ``int32`` indexing in order +to avoid downcasting and potentially losing information. + +Example:: + + >>> csr = torch.eye(5,5).to_sparse_csr() + >>> csr.crow_indices() + tensor([0, 1, 2, 3, 4, 5], dtype=torch.int32) + +""", +) + +add_docstr_all( + "col_indices", + r""" +col_indices() -> IntTensor + +Returns the tensor containing the column indices of the :attr:`self` +tensor when :attr:`self` is a sparse CSR tensor of layout ``sparse_csr``. +The ``col_indices`` tensor is strictly of shape (:attr:`self`.nnz()) +and of type ``int32`` or ``int64``. When using MKL routines such as sparse +matrix multiplication, it is necessary to use ``int32`` indexing in order +to avoid downcasting and potentially losing information. + +Example:: + + >>> csr = torch.eye(5,5).to_sparse_csr() + >>> csr.col_indices() + tensor([0, 1, 2, 3, 4], dtype=torch.int32) + +""", +) + +add_docstr_all( + "to_padded_tensor", + r""" +to_padded_tensor(padding, output_size=None) -> Tensor +See :func:`to_padded_tensor` +""", +) diff --git a/.venv/lib/python3.12/site-packages/torch/_tensor_iterator.py b/.venv/lib/python3.12/site-packages/torch/_tensor_iterator.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc5295926f6b85df5d069e86c9a07ace9ec6531 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_tensor_iterator.py @@ -0,0 +1,401 @@ +"""Python access to ATen's TensorIterator build pipeline. + +:class:`TensorIterator` builds an iterator from a set of operands and flags +that mirror ``at::TensorIteratorConfig``, then exposes the post-build +shape / dtype / device / stride information for inspection. + +This is a build-pipeline-only surface: there is no ``for_each`` here. Use it +to debug shape and dtype inference, validate custom-op contracts, or inspect +how ATen would lay out a kernel's iteration. + +Construction is canonical, *not* a faithful replay of arbitrary +``TensorIteratorConfig`` call sequences. Operands are always registered in +the order ``outputs -> inputs -> const_inputs`` and setters are applied in +one fixed order. Notably: + +* The C++ builder distinguishes ``add_input(a); add_const_input(b)`` from + ``add_const_input(b); add_input(a)`` -- ``input(0)`` refers to different + operands. This Python surface cannot express that distinction: every + ``inputs[i]`` precedes every ``const_inputs[j]``. +* Some C++ setters have order-dependent side effects (e.g. + ``promote_inputs_to_common_dtype(true)`` also flips + ``check_all_same_dtype`` to ``false``). The Python surface materializes + the *final* boolean state of each knob, not the call order, so it can't + reproduce a sequence where an intermediate setter observed a + since-overwritten value. + +Every in-tree caller of ``at::TensorIteratorConfig`` fits the canonical- +recipe shape; the lossiness is theoretical, not practical. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from torch._C import ( + _TensorIterator as _CTensorIterator, + _TensorIteratorSpec as _CTensorIteratorSpec, +) + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +__all__ = [ + "TensorIterator", + "binary_op", + "binary_float_op", + "comparison_op", + "unary_op", + "unary_float_op", + "nullary_op", + "reduce_op", +] + + +class TensorIterator: + """A built TensorIterator. Read-only view of the build-pipeline result. + + Constructor kwargs mirror ``at::TensorIteratorConfig``; defaults match + the C++ defaults. See module docstring for canonical-recipe caveats. + + Examples + -------- + Build a TI for a binary op with type promotion and inspect the result:: + + >>> import torch + >>> from torch._tensor_iterator import TensorIterator + >>> a = torch.zeros(3, 4, dtype=torch.float32) + >>> b = torch.zeros(3, 4, dtype=torch.float64) + >>> it = TensorIterator( + ... outputs=[None], + ... const_inputs=[a, b], + ... promote_inputs_to_common_dtype=True, + ... cast_common_dtype_to_outputs=True, + ... ) + >>> it.common_dtype + torch.float64 + >>> it.numel + 12 + >>> it.ndim # contiguous (3, 4) collapses to a single dim + 1 + + Declare a static shape (the iterator skips broadcast/coalesce):: + + >>> a = torch.zeros(2, 6) + >>> out = torch.empty(2, 6) + >>> it = TensorIterator( + ... outputs=[out], + ... const_inputs=[a], + ... resize_outputs=False, + ... static_shape=(2, 6), + ... ) + + Build a reduction TI (output must be pre-allocated to the reduced shape):: + + >>> a = torch.zeros(3, 4) + >>> out = torch.empty(3, 1) + >>> it = TensorIterator( + ... outputs=[out], + ... const_inputs=[a], + ... resize_outputs=False, + ... is_reduction=True, + ... ) + + Inspect post-coalesce strides (in bytes; use ``element_strides`` for + element units):: + + >>> a = torch.zeros(3, 4) + >>> b = torch.zeros(3, 4) + >>> it = TensorIterator(outputs=[None], const_inputs=[a, b]) + >>> tuple(it.strides(0)) # output byte strides + (4,) + >>> it.element_strides(0) # ... in elements + (1,) + """ + + def __init__( + self, + *, + outputs: list[torch.Tensor | None] | None = None, + inputs: list[torch.Tensor] | None = None, + const_inputs: list[torch.Tensor] | None = None, + check_all_same_dtype: bool = True, + check_all_same_device: bool = True, + promote_inputs_to_common_dtype: bool = False, + promote_integer_inputs_to_float: bool = False, + cast_common_dtype_to_outputs: bool = False, + enforce_safe_casting_to_output: bool = False, + enforce_linear_iteration: bool = False, + resize_outputs: bool = True, + check_mem_overlap: bool = True, + allow_cpu_scalars: bool = False, + is_reduction: bool = False, + static_dtype: torch.dtype | None = None, + static_device: torch.device | None = None, + static_shape: Sequence[int] | None = None, + squash_dims: Sequence[int] = (), + ) -> None: + spec = _CTensorIteratorSpec() + spec.outputs = list(outputs) if outputs is not None else [] + spec.inputs = list(inputs) if inputs is not None else [] + spec.const_inputs = list(const_inputs) if const_inputs is not None else [] + + spec.check_all_same_dtype = check_all_same_dtype + spec.check_all_same_device = check_all_same_device + spec.promote_inputs_to_common_dtype = promote_inputs_to_common_dtype + spec.promote_integer_inputs_to_float = promote_integer_inputs_to_float + spec.cast_common_dtype_to_outputs = cast_common_dtype_to_outputs + spec.enforce_safe_casting_to_output = enforce_safe_casting_to_output + spec.enforce_linear_iteration = enforce_linear_iteration + spec.resize_outputs = resize_outputs + spec.check_mem_overlap = check_mem_overlap + spec.allow_cpu_scalars = allow_cpu_scalars + spec.is_reduction = is_reduction + + if static_dtype is not None: + spec.static_dtype = static_dtype + if static_device is not None: + spec.static_device = static_device + if static_shape is not None: + spec.static_shape = list(static_shape) + spec.squash_dims = list(squash_dims) + + self._impl: _CTensorIterator = spec.build() + + @property + def ndim(self) -> int: + return self._impl.ndim + + @property + def shape(self) -> memoryview: + """Iterator shape (post coalesce/reorder), as a zero-copy + ``memoryview`` of ``int64`` elements. The view holds a reference + to this iterator and keeps it alive for as long as the view is + reachable; copy via ``tuple(it.shape)`` if you need a snapshot + you can outlive the iterator with. Hot-path readers (dispatch + conditionals) get index access without an allocation.""" + return self._impl.shape + + @property + def numel(self) -> int: + return self._impl.numel + + @property + def ntensors(self) -> int: + return self._impl.ntensors + + @property + def ninputs(self) -> int: + return self._impl.ninputs + + @property + def noutputs(self) -> int: + return self._impl.noutputs + + @property + def is_contiguous(self) -> bool: + return self._impl.is_contiguous + + @property + def is_trivial_1d(self) -> bool: + return self._impl.is_trivial_1d + + @property + def common_dtype(self) -> torch.dtype | None: + """The inferred computation dtype, or ``None`` if no single dtype + was inferred. Populated whenever TensorIterator can resolve a + common dtype -- under promotion flags, or when every input + already shares a dtype. ``None`` does not mean "promotion was + not requested"; it means inference produced no answer.""" + return self._impl.common_dtype + + def tensor(self, index: int) -> torch.Tensor: + """Return the iterator's current operand at ``index``. + + Note: under ``promote_inputs_to_common_dtype`` / + ``cast_common_dtype_to_outputs`` (CPU paths), this may be a + promoted/cast kernel temporary rather than the tensor that was + registered with the config -- it's the iterator's view of the + operand a kernel would actually iterate over.""" + return self._impl.tensor(index) + + def input(self, index: int = 0) -> torch.Tensor: + """Return the iterator's current input. See :meth:`tensor` for the + promoted-temporary caveat.""" + return self._impl.input(index) + + def output(self, index: int = 0) -> torch.Tensor: + """Return the iterator's current output. See :meth:`tensor` for the + cast-temporary caveat.""" + return self._impl.output(index) + + def dtype(self, index: int = 0) -> torch.dtype: + return self._impl.dtype(index) + + def device(self, index: int = 0) -> torch.device: + return self._impl.device(index) + + def strides(self, index: int) -> memoryview: + """Per-operand strides in bytes (post reorder/coalesce), as a + zero-copy ``memoryview`` of ``int64`` elements. The view holds a + reference to this iterator and keeps it alive for as long as the + view is reachable; copy via ``tuple(it.strides(i))`` if you need + a snapshot you can outlive the iterator with.""" + return self._impl.strides(index) + + def element_strides(self, index: int) -> tuple[int, ...]: + """Per-operand strides in elements (byte stride / element size). + + Allocates a fresh tuple on every call. Don't use on a hot path: + cache the result, or read :meth:`strides` once and divide by + :meth:`element_size` of the operand inline.""" + return self._impl.element_strides(index) + + def __repr__(self) -> str: + return repr(self._impl) + + +# --- Factory shortcuts. These mirror the C++ named constructors at +# aten/src/ATen/TensorIterator.cpp:1069+. Pass ``out=None`` to ask the iterator +# to allocate a fresh output tensor of the inferred shape/dtype/device. + + +def binary_op( + out: torch.Tensor | None, a: torch.Tensor, b: torch.Tensor +) -> TensorIterator: + """Equivalent of ``at::TensorIterator::binary_op``.""" + return TensorIterator( + outputs=[out], + const_inputs=[a, b], + allow_cpu_scalars=True, + promote_inputs_to_common_dtype=True, + cast_common_dtype_to_outputs=True, + enforce_safe_casting_to_output=True, + ) + + +def binary_float_op( + out: torch.Tensor | None, a: torch.Tensor, b: torch.Tensor +) -> TensorIterator: + """Equivalent of ``at::TensorIterator::binary_float_op``.""" + return TensorIterator( + outputs=[out], + const_inputs=[a, b], + allow_cpu_scalars=True, + promote_inputs_to_common_dtype=True, + cast_common_dtype_to_outputs=True, + enforce_safe_casting_to_output=True, + promote_integer_inputs_to_float=True, + ) + + +def comparison_op( + out: torch.Tensor | None, a: torch.Tensor, b: torch.Tensor +) -> TensorIterator: + """Equivalent of ``at::TensorIterator::comparison_op``. + + When ``out`` is ``None``, the output dtype is forced to bool. When ``out`` + is a defined non-bool tensor, the common dtype is cast back to its dtype + via ``cast_common_dtype_to_outputs``. The bool-output case skips that cast + as a performance optimization. + """ + static_dtype = torch.bool if out is None else None + cast_to_outputs = out is not None and out.dtype != torch.bool + return TensorIterator( + outputs=[out], + const_inputs=[a, b], + allow_cpu_scalars=True, + promote_inputs_to_common_dtype=True, + cast_common_dtype_to_outputs=cast_to_outputs, + static_dtype=static_dtype, + ) + + +def unary_op(out: torch.Tensor | None, a: torch.Tensor) -> TensorIterator: + """Equivalent of ``at::TensorIterator::unary_op``.""" + return TensorIterator(outputs=[out], const_inputs=[a]) + + +def unary_float_op(out: torch.Tensor | None, a: torch.Tensor) -> TensorIterator: + """Equivalent of ``at::TensorIterator::unary_float_op``.""" + return TensorIterator( + outputs=[out], + const_inputs=[a], + promote_inputs_to_common_dtype=True, + cast_common_dtype_to_outputs=True, + enforce_safe_casting_to_output=True, + promote_integer_inputs_to_float=True, + ) + + +def nullary_op(out: torch.Tensor) -> TensorIterator: + """Equivalent of ``at::TensorIterator::nullary_op``. + + Unlike the binary/unary factories, ``out`` must be a defined tensor; + the C++ named constructor takes a non-undefined output. + """ + if out is None: + raise TypeError( + "nullary_op requires a defined output tensor; None is not allowed." + ) + return TensorIterator( + outputs=[out], + check_all_same_dtype=False, + resize_outputs=False, + ) + + +def reduce_op( + out: torch.Tensor, + a: torch.Tensor, + *, + out2: torch.Tensor | None = None, +) -> TensorIterator: + """Equivalent of ``at::TensorIterator::reduce_op``. + + Pass ``out2`` for the two-output reduction overload (e.g. ``min`` returning + values + indices). The output tensor(s) must be pre-allocated and shaped + correctly: this factory does not allocate or resize. With ``out2``, both + outputs must live on ``a``'s device and share its sizes/strides -- the + C++ named constructor asserts this and the same checks are mirrored + here. + """ + # Mirror the TORCH_INTERNAL_ASSERTs in TensorIterator::reduce_op. We + # surface them as RuntimeError up front since the binding doesn't + # rebind the named constructor itself; without this, mismatched + # out1/out2 would build a kernel-shape that doesn't match the + # tensors and corrupt memory once a kernel is invoked. + if out2 is not None: + if not out.device == a.device == out2.device: + raise RuntimeError( + "reduce_op: out, out2, and the input must share a device, " + f"got out={out.device}, out2={out2.device}, a={a.device}" + ) + if out.dim() != out2.dim(): + raise RuntimeError( + f"reduce_op: out and out2 must have the same dim, got " + f"{out.dim()} and {out2.dim()}" + ) + if out.shape != out2.shape or out.stride() != out2.stride(): + raise RuntimeError( + "reduce_op: out and out2 must have identical sizes and strides" + ) + return TensorIterator( + outputs=[out, out2], + const_inputs=[a], + check_all_same_dtype=False, + resize_outputs=False, + check_mem_overlap=False, + is_reduction=True, + ) + return TensorIterator( + outputs=[out], + const_inputs=[a], + promote_inputs_to_common_dtype=True, + resize_outputs=False, + check_mem_overlap=False, + is_reduction=True, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_tensor_str.py b/.venv/lib/python3.12/site-packages/torch/_tensor_str.py new file mode 100644 index 0000000000000000000000000000000000000000..4ad8b5526f74990714d49566cb84378f7b7b44aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_tensor_str.py @@ -0,0 +1,715 @@ +# mypy: allow-untyped-defs +import contextlib +import dataclasses +import math +import textwrap +from typing import Any + +import torch +from torch import inf + + +@dataclasses.dataclass +class __PrinterOptions: + precision: int = 4 + threshold: float = 1000 + edgeitems: int = 3 + linewidth: int = 80 + sci_mode: bool | None = None + + +PRINT_OPTS = __PrinterOptions() + + +# We could use **kwargs, but this will give better docs +def set_printoptions( + precision=None, + threshold=None, + edgeitems=None, + linewidth=None, + profile=None, + sci_mode=None, +): + r"""Set options for printing. Items shamelessly taken from NumPy + + Args: + precision: Number of digits of precision for floating point output + (default = 4). + threshold: Total number of array elements which trigger summarization + rather than full `repr` (default = 1000). + edgeitems: Number of array items in summary at beginning and end of + each dimension (default = 3). + linewidth: The number of characters per line for the purpose of + inserting line breaks (default = 80). Thresholded matrices will + ignore this parameter. + profile: Sane defaults for pretty printing. Can override with any of + the above options. (any one of `default`, `short`, `full`) + sci_mode: Enable (True) or disable (False) scientific notation. If + None (default) is specified, the value is defined by + `torch._tensor_str._Formatter`. This value is automatically chosen + by the framework. + + Example:: + + >>> # Limit the precision of elements + >>> torch.set_printoptions(precision=2) + >>> torch.tensor([1.12345]) + tensor([1.12]) + >>> # Limit the number of elements shown + >>> torch.set_printoptions(threshold=5) + >>> torch.arange(10) + tensor([0, 1, 2, ..., 7, 8, 9]) + >>> # Restore defaults + >>> torch.set_printoptions(profile='default') + >>> torch.tensor([1.12345]) + tensor([1.1235]) + >>> torch.arange(10) + tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + """ + if profile is not None: + if profile == "default": + PRINT_OPTS.precision = 4 + PRINT_OPTS.threshold = 1000 + PRINT_OPTS.edgeitems = 3 + PRINT_OPTS.linewidth = 80 + elif profile == "short": + PRINT_OPTS.precision = 2 + PRINT_OPTS.threshold = 1000 + PRINT_OPTS.edgeitems = 2 + PRINT_OPTS.linewidth = 80 + elif profile == "full": + PRINT_OPTS.precision = 4 + PRINT_OPTS.threshold = inf + PRINT_OPTS.edgeitems = 3 + PRINT_OPTS.linewidth = 80 + + if precision is not None: + PRINT_OPTS.precision = precision + if threshold is not None: + PRINT_OPTS.threshold = threshold + if edgeitems is not None: + PRINT_OPTS.edgeitems = edgeitems + if linewidth is not None: + PRINT_OPTS.linewidth = linewidth + PRINT_OPTS.sci_mode = sci_mode + + +def get_printoptions() -> dict[str, Any]: + r"""Gets the current options for printing, as a dictionary that + can be passed as ``**kwargs`` to set_printoptions(). + """ + return dataclasses.asdict(PRINT_OPTS) + + +@contextlib.contextmanager +def printoptions(**kwargs): + r"""Context manager that temporarily changes the print options. Accepted + arguments are same as :func:`set_printoptions`.""" + old_kwargs = get_printoptions() + set_printoptions(**kwargs) + try: + yield + finally: + set_printoptions(**old_kwargs) + + +def tensor_totype(t): + dtype = ( + torch.float + if ( + t.is_mps + or (t.is_xpu and not torch.xpu.get_device_properties(t.device).has_fp64) + or t.is_maia + ) + else torch.double + ) + return t.to(dtype=dtype) + + +class _Formatter: + def __init__(self, tensor): + self.floating_dtype = tensor.dtype.is_floating_point + self.int_mode = True + self.sci_mode = False + self.max_width = 1 + + with torch.no_grad(): + tensor_view = tensor.reshape(-1) + + if not self.floating_dtype: + for value in tensor_view: + value_str = f"{value}" + self.max_width = max(self.max_width, len(value_str)) + + else: + if tensor.dtype == torch.float4_e2m1fn_x2: # type: ignore[attr-defined] + # torch.float4_e2m1fn_x2 is special and does not support the casts necessary + # to print it, we choose to display the uint8 representation here for + # convenience of being able to print a tensor. + # TODO(#146647): extend this to other dtypes without casts defined, such + # as the bits, uint1..7 and int1..7 dtypes. + tensor_view = tensor_view.view(torch.uint8) + + nonzero_finite_vals = torch.masked_select( + tensor_view, torch.isfinite(tensor_view) & tensor_view.ne(0) + ) + + if nonzero_finite_vals.numel() == 0: + # no valid number, do nothing + return + + if tensor.dtype == torch.float8_e8m0fnu: # type: ignore[attr-defined] + # float8_e8m0fnu is special and does not define arithmetic ops, + # and printing code further in this file assumes the existence + # of various arithmetic ops to figure out what to print. We hack + # and convert to float here to make printing work correctly. + # TODO(#113663): also add the other float8 dtypes here after arithmetic + # support for them is removed + nonzero_finite_vals = nonzero_finite_vals.float() + + # Convert to double (or float) for easy calculation. HalfTensor overflows with 1e8, and there's no div() on CPU. + nonzero_finite_abs = tensor_totype(nonzero_finite_vals.abs()) + nonzero_finite_min = tensor_totype(nonzero_finite_abs.min()) + nonzero_finite_max = tensor_totype(nonzero_finite_abs.max()) + + for value in nonzero_finite_vals: + if value != torch.ceil(value): + self.int_mode = False + break + + self.sci_mode = ( + nonzero_finite_max / nonzero_finite_min > 1000.0 + or nonzero_finite_max > 1.0e8 + or nonzero_finite_min < 1.0e-4 + if PRINT_OPTS.sci_mode is None + else PRINT_OPTS.sci_mode + ) + + if self.int_mode: + # in int_mode for floats, all numbers are integers, and we append a decimal to nonfinites + # to indicate that the tensor is of floating type. add 1 to the len to account for this. + if self.sci_mode: + for value in nonzero_finite_vals: + value_str = f"{{:.{PRINT_OPTS.precision}e}}".format(value) + self.max_width = max(self.max_width, len(value_str)) + else: + for value in nonzero_finite_vals: + value_str = f"{value:.0f}" + self.max_width = max(self.max_width, len(value_str) + 1) + else: + # Check if scientific representation should be used. + if self.sci_mode: + for value in nonzero_finite_vals: + value_str = f"{{:.{PRINT_OPTS.precision}e}}".format(value) + self.max_width = max(self.max_width, len(value_str)) + else: + for value in nonzero_finite_vals: + value_str = f"{{:.{PRINT_OPTS.precision}f}}".format(value) + self.max_width = max(self.max_width, len(value_str)) + + def width(self): + return self.max_width + + def format(self, value): + if self.floating_dtype: + if self.sci_mode: + ret = f"{{:{self.max_width}.{PRINT_OPTS.precision}e}}".format(value) + elif self.int_mode: + ret = f"{value:.0f}" + if not (math.isinf(value) or math.isnan(value)): + ret += "." + else: + ret = f"{{:.{PRINT_OPTS.precision}f}}".format(value) + else: + ret = f"{value}" + return (self.max_width - len(ret)) * " " + ret + + +def _scalar_str(self, formatter1, formatter2=None): + if formatter2 is not None: + real_str = _scalar_str(self.real, formatter1) + imag_str = (_scalar_str(self.imag, formatter2) + "j").lstrip() + # handles negative numbers, +0.0, -0.0 + if imag_str[0] == "+" or imag_str[0] == "-": + return real_str + imag_str + else: + return real_str + "+" + imag_str + else: + return formatter1.format(self.item()) + + +def _vector_str(self, indent, summarize, formatter1, formatter2=None): + # length includes spaces and comma between elements + element_length = formatter1.width() + 2 + if formatter2 is not None: + # width for imag_formatter + an extra j for complex + element_length += formatter2.width() + 1 + + elements_per_line = max( + 1, math.floor((PRINT_OPTS.linewidth - indent) / (element_length)) + ) + + def _val_formatter(val, formatter1=formatter1, formatter2=formatter2): + if formatter2 is not None: + real_str = formatter1.format(val.real) + imag_str = (formatter2.format(val.imag) + "j").lstrip() + # handles negative numbers, +0.0, -0.0 + if imag_str[0] == "+" or imag_str[0] == "-": + return real_str + imag_str + else: + return real_str + "+" + imag_str + else: + return formatter1.format(val) + + if self.dtype == torch.float4_e2m1fn_x2: # type: ignore[attr-defined] + # torch.float4_e2m1fn_x2 is special and does not support the casts necessary + # to print it, we choose to display the uint8 representation here for + # convenience of being able to print a tensor. + # TODO(#146647): extend this to other dtypes without casts defined, such + # as the bits, uint1..7 and int1..7 dtypes. + self = self.view(torch.uint8) + + if summarize and not PRINT_OPTS.edgeitems: + # Deal with edge case that negative zero is zero + data = ["..."] + elif summarize and self.size(0) > 2 * PRINT_OPTS.edgeitems: + data = ( + [_val_formatter(val) for val in self[: PRINT_OPTS.edgeitems].tolist()] + + [" ..."] + + [_val_formatter(val) for val in self[-PRINT_OPTS.edgeitems :].tolist()] + ) + else: + data = [_val_formatter(val) for val in self.tolist()] + + data_lines = [ + data[i : i + elements_per_line] for i in range(0, len(data), elements_per_line) + ] + lines = [", ".join(line) for line in data_lines] + return "[" + ("," + "\n" + " " * (indent + 1)).join(lines) + "]" + + +# formatter2 is only used for printing complex tensors. +# For complex tensors, formatter1 and formatter2 are the formatters for tensor.real +# and tensor.imag respectively +def _tensor_str_with_formatter(self, indent, summarize, formatter1, formatter2=None): + dim = self.dim() + + if dim == 0: + return _scalar_str(self, formatter1, formatter2) + + if dim == 1: + return _vector_str(self, indent, summarize, formatter1, formatter2) + + if summarize and self.size(0) > 2 * PRINT_OPTS.edgeitems: + slices = ( + [ + _tensor_str_with_formatter( + self[i], indent + 1, summarize, formatter1, formatter2 + ) + for i in range(PRINT_OPTS.edgeitems) + ] + + ["..."] + + [ + _tensor_str_with_formatter( + self[i], indent + 1, summarize, formatter1, formatter2 + ) + for i in range(len(self) - PRINT_OPTS.edgeitems, len(self)) + ] + ) + else: + slices = [ + _tensor_str_with_formatter( + self[i], indent + 1, summarize, formatter1, formatter2 + ) + for i in range(self.size(0)) + ] + + tensor_str = ("," + "\n" * (dim - 1) + " " * (indent + 1)).join(slices) + return "[" + tensor_str + "]" + + +def _tensor_str(self, indent): + if self.numel() == 0: + return "[]" + + summarize = self.numel() > PRINT_OPTS.threshold + + if self._is_zerotensor(): + self = self.clone() + + # handle the negative bit + if self.is_neg(): + self = self.resolve_neg() + + # TODO: Remove me when `masked_select` is implemented for FP8 + if self.dtype in [ + torch.float8_e5m2, + torch.float8_e5m2fnuz, + torch.float8_e4m3fn, + torch.float8_e4m3fnuz, + ]: + self = self.half() + + if self.dtype.is_complex: + # handle the conjugate bit + self = self.resolve_conj() + real_formatter = _Formatter( + get_summarized_data(self.real) if summarize else self.real + ) + imag_formatter = _Formatter( + get_summarized_data(self.imag) if summarize else self.imag + ) + return _tensor_str_with_formatter( + self, indent, summarize, real_formatter, imag_formatter + ) + else: + formatter = _Formatter(get_summarized_data(self) if summarize else self) + return _tensor_str_with_formatter(self, indent, summarize, formatter) + + +def _add_suffixes(tensor_str, suffixes, indent, force_newline): + tensor_strs = [tensor_str] + last_line_len = len(tensor_str) - tensor_str.rfind("\n") + 1 + for suffix in suffixes: + suffix_len = len(suffix) + if force_newline or last_line_len + suffix_len + 2 > PRINT_OPTS.linewidth: + tensor_strs.append(",\n" + " " * indent + suffix) + last_line_len = indent + suffix_len + force_newline = False + else: + tensor_strs.append(", " + suffix) + last_line_len += suffix_len + 2 + tensor_strs.append(")") + return "".join(tensor_strs) + + +def get_summarized_data(self): + dim = self.dim() + if dim == 0: + return self + if dim == 1: + if self.size(0) > 2 * PRINT_OPTS.edgeitems: + return torch.cat( + (self[: PRINT_OPTS.edgeitems], self[-PRINT_OPTS.edgeitems :]) + ) + else: + return self + if not PRINT_OPTS.edgeitems: + return self.new_empty([0] * self.dim()) + elif self.size(0) > 2 * PRINT_OPTS.edgeitems: + start = [self[i] for i in range(PRINT_OPTS.edgeitems)] + end = [self[i] for i in range(len(self) - PRINT_OPTS.edgeitems, len(self))] + return torch.stack([get_summarized_data(x) for x in (start + end)]) + else: + return torch.stack([get_summarized_data(x) for x in self]) + + +def _str_intern(inp, *, tensor_contents=None): + if torch._C._functorch.is_functorch_wrapped_tensor(inp): + return _functorch_wrapper_str_intern(inp, tensor_contents=tensor_contents) + is_plain_tensor = type(inp) is torch.Tensor or type(inp) is torch.nn.Parameter + if inp.is_nested: + prefix = "nested_tensor(" + elif is_plain_tensor: + prefix = "tensor(" + else: + prefix = f"{type(inp).__name__}(" + indent = len(prefix) + suffixes = [] + custom_contents_provided = tensor_contents is not None + if custom_contents_provided: + tensor_str = tensor_contents + + # This is used to extract the primal value and thus disable the forward AD + # within this function. + # TODO(albanD) This needs to be updated when more than one level is supported + self, tangent = torch.autograd.forward_ad.unpack_dual(inp) + + # Note [Print tensor device]: + # A general logic here is we only print device when it doesn't match + # the device specified in default tensor type. + # Currently torch.set_default_tensor_type() only supports CPU/CUDA, thus + # torch._C._get_default_device() only returns either cpu or cuda. + # In other cases, we don't have a way to set them as default yet, + # and we should always print out device for them. + if ( + self.device.type != torch._C._get_default_device() + or ( + self.device.type == "cuda" + and torch.cuda.current_device() != self.device.index + ) + or (self.device.type == "mps") + ): + suffixes.append("device='" + str(self.device) + "'") + + # Tensor printing performs tensor operations like slice, indexing, etc to make it in a + # representable format. These operations on ipu/xla/lazy/mtia tensor results in compilations. Hence, + # to avoid compilations, copying the tensor to cpu before printing. + if self.device.type in ["xla", "lazy", "ipu", "mtia"]: + self = self.to("cpu") + + # TODO: add an API to map real -> complex dtypes + _default_complex_dtype = ( + torch.cdouble if torch.get_default_dtype() == torch.double else torch.cfloat + ) + has_default_dtype = self.dtype in ( + torch.get_default_dtype(), + _default_complex_dtype, + torch.int64, + torch.bool, + ) + if self.is_sparse: + suffixes.append("size=" + str(tuple(self.shape))) + from torch._subclasses.fake_tensor import is_fake_tensor + + is_meta = self.is_meta or is_fake_tensor(self) + if not is_meta: + suffixes.append("nnz=" + str(self._nnz())) + if not has_default_dtype: + suffixes.append("dtype=" + str(self.dtype)) + if not custom_contents_provided: + indices_prefix = "indices=tensor(" + indices = self._indices().detach() + if is_meta: + indices_str = "..." + else: + indices_str = _tensor_str(indices, indent + len(indices_prefix)) + if is_meta or indices.numel() == 0: + indices_str += ", size=" + str(tuple(indices.shape)) + values_prefix = "values=tensor(" + values = self._values().detach() + if is_meta: + values_str = "..." + else: + values_str = _tensor_str(values, indent + len(values_prefix)) + if is_meta or values.numel() == 0: + values_str += ", size=" + str(tuple(values.shape)) + tensor_str = ( + indices_prefix + + indices_str + + "),\n" + + " " * indent + + values_prefix + + values_str + + ")" + ) + elif self.layout in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + }: + from torch._subclasses.fake_tensor import is_fake_tensor + + suffixes.append("size=" + str(tuple(self.shape))) + is_meta = self.is_meta or is_fake_tensor(self) + if not is_meta: + suffixes.append("nnz=" + str(self._nnz())) + if not has_default_dtype: + suffixes.append("dtype=" + str(self.dtype)) + if not custom_contents_provided: + compressed_indices_method, plain_indices_method = { + torch.sparse_csr: (torch.Tensor.crow_indices, torch.Tensor.col_indices), + torch.sparse_csc: (torch.Tensor.ccol_indices, torch.Tensor.row_indices), + torch.sparse_bsr: (torch.Tensor.crow_indices, torch.Tensor.col_indices), + torch.sparse_bsc: (torch.Tensor.ccol_indices, torch.Tensor.row_indices), + }[self.layout] + if self.layout in {torch.sparse_csr, torch.sparse_bsr}: + cdimname, pdimname = "row", "column" + else: + cdimname, pdimname = "column", "row" + compressed_indices_prefix = f"c{cdimname[:3]}_indices=tensor(" + compressed_indices = compressed_indices_method(self).detach() + if is_meta: + compressed_indices_str = "..." + else: + compressed_indices_str = _tensor_str( + compressed_indices, indent + len(compressed_indices_prefix) + ) + if compressed_indices.numel() == 0 or is_meta: + compressed_indices_str += ", size=" + str( + tuple(compressed_indices.shape) + ) + plain_indices_prefix = f"{pdimname[:3]}_indices=tensor(" + plain_indices = plain_indices_method(self).detach() + if is_meta: + plain_indices_str = "..." + else: + plain_indices_str = _tensor_str( + plain_indices, indent + len(plain_indices_prefix) + ) + if plain_indices.numel() == 0 or is_meta: + plain_indices_str += ", size=" + str(tuple(plain_indices.shape)) + values_prefix = "values=tensor(" + values = self.values().detach() + if is_meta: + values_str = "..." + else: + values_str = _tensor_str(values, indent + len(values_prefix)) + if values.numel() == 0 or is_meta: + values_str += ", size=" + str(tuple(values.shape)) + tensor_str = ( + compressed_indices_prefix + + compressed_indices_str + + "),\n" + + " " * indent + + plain_indices_prefix + + plain_indices_str + + "),\n" + + " " * indent + + values_prefix + + values_str + + ")" + ) + elif self.is_quantized: + suffixes.append("size=" + str(tuple(self.shape))) + if not has_default_dtype: + suffixes.append("dtype=" + str(self.dtype)) + suffixes.append("quantization_scheme=" + str(self.qscheme())) + if ( + self.qscheme() == torch.per_tensor_affine + or self.qscheme() == torch.per_tensor_symmetric + ): + suffixes.append("scale=" + str(self.q_scale())) + suffixes.append("zero_point=" + str(self.q_zero_point())) + elif ( + self.qscheme() == torch.per_channel_affine + or self.qscheme() == torch.per_channel_symmetric + or self.qscheme() == torch.per_channel_affine_float_qparams + ): + suffixes.append("scale=" + str(self.q_per_channel_scales())) + suffixes.append("zero_point=" + str(self.q_per_channel_zero_points())) + suffixes.append("axis=" + str(self.q_per_channel_axis())) + if not custom_contents_provided: + tensor_str = _tensor_str(self.dequantize(), indent) + elif self.is_nested: + if not custom_contents_provided: + + def indented_str(s, indent): + return "\n".join(f" {line}" for line in s.split("\n")) + + strs = ",\n".join( + indented_str(str(t), indent + 1) + for t in torch.ops.aten.unbind.int(self, 0) + ) + tensor_str = f"[\n{strs}\n]" + elif torch._is_functional_tensor(self): + prefix = "_to_functional_tensor(" + tensor_str = repr(torch._from_functional_tensor(self)) + else: + # Circular import problem, so we import it here + from torch._subclasses.fake_tensor import is_fake_tensor + + if self.is_meta or is_fake_tensor(self): + suffixes.append("size=" + str(tuple(self.shape))) + if self.dtype != torch.get_default_dtype(): + suffixes.append("dtype=" + str(self.dtype)) + # TODO: This implies that ellipses is valid syntax for allocating + # a meta tensor or FakeTensor, which it could be, but it isn't right now + if not custom_contents_provided: + tensor_str = "..." + else: + if self.numel() == 0 and not self.is_sparse: + # Explicitly print the shape if it is not (0,), to match NumPy behavior + if self.dim() != 1: + suffixes.append("size=" + str(tuple(self.shape))) + + # In an empty tensor, there are no elements to infer if the dtype + # should be int64, so it must be shown explicitly. + if self.dtype != torch.get_default_dtype(): + suffixes.append("dtype=" + str(self.dtype)) + if not custom_contents_provided: + tensor_str = "[]" + else: + if not PRINT_OPTS.edgeitems: + suffixes.append("size=" + str(tuple(self.shape))) + + if not has_default_dtype: + suffixes.append("dtype=" + str(self.dtype)) + + if not custom_contents_provided: + if self.layout != torch.strided: + tensor_str = _tensor_str(self.to_dense(), indent) + else: + tensor_str = _tensor_str(self, indent) + + if self.layout != torch.strided: + suffixes.append("layout=" + str(self.layout)) + + # Use inp here to get the original grad_fn and not the one generated by the forward grad + # unpacking. + grad_fn_name = None + try: + grad_fn = inp.grad_fn + except RuntimeError: + # Accessing the grad_fn calls rebasing logic which would cause an error + # if that tensor is a view created in no-grad mode modified in-place in + # no-grad mode. See: https://github.com/pytorch/pytorch/issues/99968 + grad_fn_name = "Invalid" + + if grad_fn_name is None and grad_fn is not None: # type: ignore[possibly-undefined] + # pyrefly: ignore [unbound-name] + grad_fn_name = type(grad_fn).__name__ + if grad_fn_name == "CppFunction": + # pyrefly: ignore [unbound-name] + grad_fn_name = grad_fn.name().rsplit("::", 1)[-1] + + if grad_fn_name is not None: + suffixes.append(f"grad_fn=<{grad_fn_name}>") + elif inp.requires_grad: + suffixes.append("requires_grad=True") + + if tangent is not None: + suffixes.append(f"tangent={tangent}") + + string_repr = _add_suffixes( + prefix + tensor_str, # type: ignore[possibly-undefined] + suffixes, + indent, + force_newline=self.is_sparse, + ) + + # Check if this instance is flagged as a parameter and change the repr accordingly. + # Unfortunately, this function has to be aware of this detail. + # NB: This is currently skipped for plain tensor parameters to maintain BC. In the future, + # this should be done for those as well to produce a valid repr. + if isinstance(self, torch.nn.Parameter) and not is_plain_tensor: + string_repr = f"Parameter({string_repr})" + + return string_repr + + +def _functorch_wrapper_str_intern(tensor, *, tensor_contents=None): + level = torch._C._functorch.maybe_get_level(tensor) + if level == -1: + raise AssertionError("expected functorch level to be >= 0, got -1") + + if torch._C._functorch.is_functionaltensor(tensor): + # Since we're unwrapping the FunctionalTensorWrapper, we need to make sure + # that it's up to date first + torch._sync(tensor) + + value = torch._C._functorch.get_unwrapped(tensor) + value_repr = repr(value) + + indented_value_repr = textwrap.indent(value_repr, " " * 4) + if torch._C._functorch.is_batchedtensor(tensor): + bdim = torch._C._functorch.maybe_get_bdim(tensor) + if bdim == -1: + raise AssertionError("expected batch dimension to be >= 0, got -1") + return ( + f"BatchedTensor(lvl={level}, bdim={bdim}, value=\n{indented_value_repr}\n)" + ) + if torch._C._functorch.is_gradtrackingtensor(tensor): + return f"GradTrackingTensor(lvl={level}, value=\n{indented_value_repr}\n)" + if torch._C._functorch.is_functionaltensor(tensor): + return f"FunctionalTensor(lvl={level}, value=\\\n{value_repr})" + + raise ValueError("We don't know how to print this, please file us an issue") + + +def _str(self, *, tensor_contents=None): + with torch.no_grad(), torch.utils._python_dispatch._disable_current_modes(): + guard = torch._C._DisableFuncTorch() # noqa: F841 + return _str_intern(self, tensor_contents=tensor_contents) diff --git a/.venv/lib/python3.12/site-packages/torch/_thread_safe_fork.py b/.venv/lib/python3.12/site-packages/torch/_thread_safe_fork.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_torch_docs.py b/.venv/lib/python3.12/site-packages/torch/_torch_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..d2c1e46c9b02a481a5b0eccf1da30cbd58aaca69 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_torch_docs.py @@ -0,0 +1,14985 @@ +# mypy: allow-untyped-defs +"""Adds docstrings to functions defined in the torch._C module.""" + +import re + +import torch._C +from torch._C import _add_docstr as add_docstr + + +def parse_kwargs(desc): + r"""Map a description of args to a dictionary of {argname: description}. + + Input: + (' weight (Tensor): a weight tensor\n' + + ' Some optional description') + Output: { + 'weight': \ + 'weight (Tensor): a weight tensor\n Some optional description' + } + """ + # Split on exactly 4 spaces after a newline + regx = re.compile(r"\n\s{4}(?!\s)") + kwargs = [section.strip() for section in regx.split(desc)] + kwargs = [section for section in kwargs if len(section) > 0] + return {desc.split(" ")[0]: desc for desc in kwargs} + + +def merge_dicts(*dicts): + """Merge dictionaries into a single dictionary.""" + return {x: d[x] for d in dicts for x in d} + + +common_args = parse_kwargs( + """ + input (Tensor): the input tensor. + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned tensor. Default: ``torch.preserve_format``. +""" +) + +reduceops_common_args = merge_dicts( + common_args, + parse_kwargs( + """ + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + keepdim (bool): whether the output tensor has :attr:`dim` retained or not. +""" + ), + { + "opt_keepdim": """ + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. +""" + }, +) + +multi_dim_common = merge_dicts( + reduceops_common_args, + parse_kwargs( + """ + dim (int or tuple of ints): the dimension or dimensions to reduce. +""" + ), + { + "keepdim_details": """ +If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the +output tensor having 1 (or ``len(dim)``) fewer dimension(s). +""" + }, + { + "opt_dim": """ + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. +""" + }, + { + "opt_dim_all_reduce": """ + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. +""" + }, +) + +single_dim_common = merge_dicts( + reduceops_common_args, + parse_kwargs( + """ + dim (int): the dimension to reduce. +""" + ), + { + "opt_dim": """ + dim (int, optional): the dimension to reduce. +""" + }, + { + "opt_dim_all_reduce": """ + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. +""" + }, + { + "opt_dim_without_none": """ + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. +""" + }, + { + "keepdim_details": """If :attr:`keepdim` is ``True``, the output tensor is of the same size +as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in +the output tensor having 1 fewer dimension than :attr:`input`.""" + }, +) + +factory_common_args = merge_dicts( + common_args, + parse_kwargs( + """ + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. +""" + ), + { + "sparse_factory_device_note": """\ +.. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor.""" + }, +) + +factory_like_common_args = parse_kwargs( + """ + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. +""" +) + +factory_data_common_args = parse_kwargs( + """ + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. +""" +) + +tf32_notes = { + "tf32_note": """This operator supports :ref:`TensorFloat32`.""" +} + +rocm_fp16_notes = { + "rocm_fp16_note": """On certain ROCm devices, when using float16 inputs this module will use \ +:ref:`different precision` for backward.""" +} + +reproducibility_notes: dict[str, str] = { + "forward_reproducibility_note": """This operation may behave nondeterministically when given tensors on \ +a CUDA device. See :doc:`/notes/randomness` for more information.""", + "backward_reproducibility_note": """This operation may produce nondeterministic gradients when given tensors on \ +a CUDA device. See :doc:`/notes/randomness` for more information.""", + "cudnn_reproducibility_note": """In some circumstances when given tensors on a CUDA device \ +and using CuDNN, this operator may select a nondeterministic algorithm to increase performance. If this is \ +undesirable, you can try to make the operation deterministic (potentially at \ +a performance cost) by setting ``torch.backends.cudnn.deterministic = True``. \ +See :doc:`/notes/randomness` for more information.""", +} + +sparse_support_notes = { + "sparse_beta_warning": """ +.. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request.""", +} + +add_docstr( + torch.abs, + r""" +abs(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Computes the absolute value of each element in :attr:`input`. + +.. math:: + \text{out}_{i} = |\text{input}_{i}| +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.abs(torch.tensor([-1, -2, 3])) + tensor([ 1, 2, 3]) +""".format(**common_args), +) + +add_docstr( + torch.abs_, + r""" +abs_(input) -> Tensor + +In-place version of :func:`torch.abs` +""", +) + +add_docstr( + torch.absolute, + r""" +absolute(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.abs` +""", +) + +add_docstr( + torch.acos, + r""" +acos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the arccosine (in radians) of each element in :attr:`input`. + +.. math:: + \text{out}_{i} = \cos^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.3348, -0.5889, 0.2005, -0.1584]) + >>> torch.acos(a) + tensor([ 1.2294, 2.2004, 1.3690, 1.7298]) +""".format(**common_args), +) + +add_docstr( + torch.acos_, + r""" +acos_(input) -> Tensor + +In-place version of :func:`torch.acos` +""", +) + +add_docstr( + torch.arccos, + r""" +arccos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.acos`. +""", +) + +add_docstr( + torch.arccos_, + r""" +arccos_(input) -> Tensor + +In-place version of :func:`torch.arccos` +""", +) + +add_docstr( + torch.acosh, + r""" +acosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the inverse hyperbolic cosine of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \cosh^{-1}(\text{input}_{i}) + +Note: + The domain of the inverse hyperbolic cosine is `[1, inf)` and values outside this range + will be mapped to ``NaN``, except for `+ INF` for which the output is mapped to `+ INF`. +""" + + r""" +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.randn(4).uniform_(1, 2) + >>> a + tensor([ 1.3192, 1.9915, 1.9674, 1.7151 ]) + >>> torch.acosh(a) + tensor([ 0.7791, 1.3120, 1.2979, 1.1341 ]) +""".format(**common_args), +) + +add_docstr( + torch.acosh_, + r""" +acosh_(input) -> Tensor + +In-place version of :func:`torch.acosh` +""", +) + +add_docstr( + torch.arccosh, + r""" +arccosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.acosh`. +""", +) + +add_docstr( + torch.arccosh_, + r""" +arccosh_(input) -> Tensor + +In-place version of :func:`torch.arccosh` +""", +) + +add_docstr( + torch.index_add, + r""" +index_add(input: Tensor, dim: int, index: Tensor, source: Tensor, *, alpha: Union[Number, _complex] = 1, out: Optional[Tensor]) -> Tensor # noqa: B950 + +See :meth:`~Tensor.index_add_` for function description. +""", +) + +add_docstr( + torch.index_copy, + r""" +index_copy(input: Tensor, dim: int, index: Tensor, source: Tensor, *, out: Optional[Tensor]) -> Tensor + +See :meth:`~Tensor.index_copy_` for function description. +""", +) + +add_docstr( + torch.index_reduce, + r""" +index_reduce(input: Tensor, dim: int, index: Tensor, source: Tensor, reduce: str, *, include_self: bool = True, out: Optional[Tensor]) -> Tensor # noqa: B950 + +See :meth:`~Tensor.index_reduce_` for function description. +""", +) + +add_docstr( + torch.add, + r""" +add(input, other, *, alpha=1, out=None) -> Tensor + +Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + +.. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i +""" + + r""" + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer, float, and complex inputs. + +Args: + {input} + other (Tensor or Number): the tensor or number to add to :attr:`input`. + +Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + {out} + +Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) +""".format(**common_args), +) + +add_docstr( + torch.addbmm, + r""" +addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + +Performs a batch matrix-matrix product of matrices stored +in :attr:`batch1` and :attr:`batch2`, +with a reduced add step (all matrix multiplications get accumulated +along the first dimension). +:attr:`input` is added to the final result. + +:attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the +same number of matrices. + +If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a +:math:`(b \times m \times p)` tensor, :attr:`input` must be +:ref:`broadcastable ` with a :math:`(n \times p)` tensor +and :attr:`out` will be a :math:`(n \times p)` tensor. + +.. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + +If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` +must be real numbers, otherwise they should be integers. + +{tf32_note} + +{rocm_fp16_note} + +Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + {out} + +Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) +""".format(**common_args, **tf32_notes, **rocm_fp16_notes), +) + +add_docstr( + torch.addcdiv, + r""" +addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + +Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, +multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + +.. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + +.. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} +""" + + r""" + +The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be +:ref:`broadcastable `. + +For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be +a real number, otherwise an integer. + +Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + +Keyword args: + value (Number, optional): multiplier for :math:`\text{{tensor1}} / \text{{tensor2}}` + {out} + +Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) +""".format(**common_args), +) + +add_docstr( + torch.addcmul, + r""" +addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + +Performs the element-wise multiplication of :attr:`tensor1` +by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` +and adds it to :attr:`input`. + +.. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i +""" + + r""" +The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be +:ref:`broadcastable `. + +For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be +a real number, otherwise an integer. + +Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + +Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + {out} + +Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) +""".format(**common_args), +) + +add_docstr( + torch.addmm, + r""" +addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + +Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. +The matrix :attr:`input` is added to the final result. + +If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a +:math:`(m \times p)` tensor, then :attr:`input` must be +:ref:`broadcastable ` with a :math:`(n \times p)` tensor +and :attr:`out` will be a :math:`(n \times p)` tensor. + +:attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between +:attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + +.. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + +If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and +:attr:`alpha` must be real numbers, otherwise they should be integers. + +This operation has support for arguments with :ref:`sparse layouts`. If +:attr:`input` is sparse the result will have the same layout and if :attr:`out` +is provided it must have the same layout as :attr:`input`. + +{sparse_beta_warning} + +{tf32_note} + +{rocm_fp16_note} + +Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + {out} + +Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + +.. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + +Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + {out} +""".format(**common_args, **tf32_notes, **rocm_fp16_notes, **sparse_support_notes), +) + +add_docstr( + torch.adjoint, + r""" +adjoint(input: Tensor) -> Tensor +Returns a view of the tensor conjugated and with the last two dimensions transposed. + +``x.adjoint()`` is equivalent to ``x.transpose(-2, -1).conj()`` for complex tensors and +to ``x.transpose(-2, -1)`` for real tensors. + +Args: + {input} + +Example:: + + >>> x = torch.arange(4, dtype=torch.float) + >>> A = torch.complex(x, x).reshape(2, 2) + >>> A + tensor([[0.+0.j, 1.+1.j], + [2.+2.j, 3.+3.j]]) + >>> A.adjoint() + tensor([[0.-0.j, 2.-2.j], + [1.-1.j, 3.-3.j]]) + >>> (A.adjoint() == A.mH).all() + tensor(True) +""", +) + +add_docstr( + torch.sspaddmm, + r""" +sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + +Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor +:attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + +Note: This function is equivalent to :func:`torch.addmm`, except +:attr:`input` and :attr:`mat1` are sparse. + +Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + {out} +""".format(**common_args), +) + +add_docstr( + torch.smm, + r""" +smm(input, mat) -> Tensor + +Performs a matrix multiplication of the sparse matrix :attr:`input` +with the dense matrix :attr:`mat`. + +Args: + input (Tensor): a sparse matrix to be matrix multiplied + mat (Tensor): a dense matrix to be matrix multiplied +""", +) + +add_docstr( + torch.addmv, + r""" +addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + +Performs a matrix-vector product of the matrix :attr:`mat` and +the vector :attr:`vec`. +The vector :attr:`input` is added to the final result. + +If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of +size `m`, then :attr:`input` must be +:ref:`broadcastable ` with a 1-D tensor of size `n` and +:attr:`out` will be 1-D tensor of size `n`. + +:attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between +:attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + +.. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + +If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and +:attr:`alpha` must be real numbers, otherwise they should be integers. + +Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + {out} + +Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) +""".format(**common_args), +) + +add_docstr( + torch.addmv_, + r""" +addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + +In-place version of :func:`torch.addmv` +""", +) + +add_docstr( + torch.addr, + r""" +addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + +Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` +and adds it to the matrix :attr:`input`. + +Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the +outer product between :attr:`vec1` and :attr:`vec2` and the added matrix +:attr:`input` respectively. + +.. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + +If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector +of size `m`, then :attr:`input` must be +:ref:`broadcastable ` with a matrix of size +:math:`(n \times m)` and :attr:`out` will be a matrix of size +:math:`(n \times m)`. + +Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{{vec1}} \otimes \text{{vec2}}` (:math:`\alpha`) + {out} + +Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) +""".format(**common_args), +) + +add_docstr( + torch.allclose, + r""" +allclose(input: Tensor, other: Tensor, rtol: float = 1e-05, atol: float = 1e-08, equal_nan: bool = False) -> bool + +This function checks if :attr:`input` and :attr:`other` satisfy the condition: + +.. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other}_i \rvert +""" + + r""" +elementwise, for all elements of :attr:`input` and :attr:`other`. The behaviour of this function is analogous to +`numpy.allclose `_ + +Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + atol (float, optional): absolute tolerance. Default: 1e-08 + rtol (float, optional): relative tolerance. Default: 1e-05 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + +Example:: + + >>> torch.allclose(torch.tensor([10000., 1e-07]), torch.tensor([10000.1, 1e-08])) + False + >>> torch.allclose(torch.tensor([10000., 1e-08]), torch.tensor([10000.1, 1e-09])) + True + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')])) + False + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')]), equal_nan=True) + True +""", +) + +add_docstr( + torch.all, + r""" +all(input: Tensor, *, out=None) -> Tensor + +Tests if all elements in :attr:`input` evaluate to `True`. + +.. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + +.. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + +For each row of :attr:`input` in the given dimension :attr:`dim`, +returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) +""".format(**multi_dim_common), +) + +add_docstr( + torch.any, + r""" +any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Tests if any element in :attr:`input` evaluates to `True`. + +.. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + +.. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + +For each row of :attr:`input` in the given dimension :attr:`dim`, +returns `True` if any element in the row evaluate to `True` and `False` otherwise. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) +""".format(**multi_dim_common), +) + +add_docstr( + torch.angle, + r""" +angle(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Computes the element-wise angle (in radians) of the given :attr:`input` tensor. + +.. math:: + \text{out}_{i} = angle(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +.. note:: Starting in PyTorch 1.8, angle returns pi for negative real numbers, + zero for non-negative real numbers, and propagates NaNs. Previously + the function would return zero for all real numbers and not propagate + floating-point NaNs. + +Example:: + + >>> torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159 + tensor([ 135., 135, -45]) +""".format(**common_args), +) + +add_docstr( + torch.as_strided, + r""" +as_strided(input, size, stride, storage_offset=None) -> Tensor + +Create a view of an existing `torch.Tensor` :attr:`input` with specified +:attr:`size`, :attr:`stride` and :attr:`storage_offset`. + +.. warning:: + Prefer using other view functions, like :meth:`torch.Tensor.view` or + :meth:`torch.Tensor.expand`, to setting a view's strides manually with + `as_strided`, as this function will throw an error on non-standard Pytorch + backends (that do not have a concept of stride) and the result will depend + on the current layout in memory. The constructed view must only refer to + elements within the Tensor's storage or a runtime error will be thrown. + If the generated view is "overlapped" (with multiple indices referring to + the same element in memory), the behavior of inplace operations on this view + is undefined (and might not throw runtime errors). + +Args: + {input} + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor. + If ``None``, the storage_offset of the output tensor will match the input tensor. + +Example:: + + >>> x = torch.randn(3, 3) + >>> x + tensor([[ 0.9039, 0.6291, 1.0795], + [ 0.1586, 2.1939, -0.4900], + [-0.1909, -0.7503, 1.9355]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2)) + >>> t + tensor([[0.9039, 1.0795], + [0.6291, 0.1586]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2), 1) + tensor([[0.6291, 0.1586], + [1.0795, 2.1939]]) +""".format(**common_args), +) + +add_docstr( + torch.alpha_dropout_, + r""" +alpha_dropout_(input, p, train) -> Tensor + +In-place version of :func:`torch.alpha_dropout` +""", +) + +add_docstr( + torch.as_strided_, + r""" +as_strided_(input, size, stride, storage_offset=None) -> Tensor + +In-place version of :func:`torch.as_strided` +""", +) + +add_docstr( + torch.as_tensor, + r""" +as_tensor(data: Any, *, dtype: Optional[dtype] = None, device: Optional[DeviceLikeType]) -> Tensor + +Converts :attr:`data` into a tensor, sharing data and preserving autograd +history if possible. + +If :attr:`data` is already a tensor with the requested dtype and device +then :attr:`data` itself is returned, but if :attr:`data` is a +tensor with a different dtype or device then it's copied as if using +`data.to(dtype=dtype, device=device)`. + +If :attr:`data` is a NumPy array (an ndarray) with the same dtype and device then a +tensor is constructed using :func:`torch.from_numpy`. + +If :attr:`data` is a CuPy array, the returned tensor will be located on the same device as the CuPy array unless +specifically overwritten by :attr:`device` or a default device. The device of the CuPy array is inferred from the +pointer of the array using `cudaPointerGetAttributes` unless :attr:`device` is provided with an explicit device index. + +.. seealso:: + + :func:`torch.tensor` never shares its data and creates a new "leaf tensor" (see :doc:`/notes/autograd`). + + +Args: + {data} + {dtype} + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + + +Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a, device=torch.device('cuda')) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([1, 2, 3]) +""".format(**factory_data_common_args), +) + +add_docstr( + torch.asin, + r""" +asin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the arcsine of the elements (in radians) in the :attr:`input` tensor. + +.. math:: + \text{out}_{i} = \sin^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5962, 1.4985, -0.4396, 1.4525]) + >>> torch.asin(a) + tensor([-0.6387, nan, -0.4552, nan]) +""".format(**common_args), +) + +add_docstr( + torch.asin_, + r""" +asin_(input) -> Tensor + +In-place version of :func:`torch.asin` +""", +) + +add_docstr( + torch.arcsin, + r""" +arcsin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.asin`. +""", +) + +add_docstr( + torch.arcsin_, + r""" +arcsin_(input) -> Tensor + +In-place version of :func:`torch.arcsin` +""", +) + +add_docstr( + torch.asinh, + r""" +asinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the inverse hyperbolic sine of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \sinh^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1606, -1.4267, -1.0899, -1.0250 ]) + >>> torch.asinh(a) + tensor([ 0.1599, -1.1534, -0.9435, -0.8990 ]) +""".format(**common_args), +) + +add_docstr( + torch.asinh_, + r""" +asinh_(input) -> Tensor + +In-place version of :func:`torch.asinh` +""", +) + +add_docstr( + torch.arcsinh, + r""" +arcsinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.asinh`. +""", +) + +add_docstr( + torch.arcsinh_, + r""" +arcsinh_(input) -> Tensor + +In-place version of :func:`torch.arcsinh` +""", +) + +add_docstr( + torch.atan, + r""" +atan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the arctangent of the elements (in radians) in the :attr:`input` tensor. + +.. math:: + \text{out}_{i} = \tan^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.2341, 0.2539, -0.6256, -0.6448]) + >>> torch.atan(a) + tensor([ 0.2299, 0.2487, -0.5591, -0.5727]) +""".format(**common_args), +) + +add_docstr( + torch.atan_, + r""" +atan_(input) -> Tensor + +In-place version of :func:`torch.atan` +""", +) + +add_docstr( + torch.arctan, + r""" +arctan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.atan`. +""", +) + +add_docstr( + torch.arctan_, + r""" +arctan_(input) -> Tensor + +In-place version of :func:`torch.arctan` +""", +) + +add_docstr( + torch.atan2, + r""" +atan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + +Element-wise arctangent of :math:`\text{{input}}_{{i}} / \text{{other}}_{{i}}` +with consideration of the quadrant. Returns a new tensor with the signed angles +in radians between vector :math:`(\text{{other}}_{{i}}, \text{{input}}_{{i}})` +and vector :math:`(1, 0)`. (Note that :math:`\text{{other}}_{{i}}`, the second +parameter, is the x-coordinate, while :math:`\text{{input}}_{{i}}`, the first +parameter, is the y-coordinate.) + +The shapes of ``input`` and ``other`` must be +:ref:`broadcastable `. + +Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.9041, 0.0196, -0.3108, -2.4423]) + >>> torch.atan2(a, torch.randn(4)) + tensor([ 0.9833, 0.0811, -1.9743, -1.4151]) +""".format(**common_args), +) + +add_docstr( + torch.arctan2, + r""" +arctan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor +Alias for :func:`torch.atan2`. +""", +) + +add_docstr( + torch.atanh, + r""" +atanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the inverse hyperbolic tangent of the elements of :attr:`input`. + +Note: + The domain of the inverse hyperbolic tangent is `(-1, 1)` and values outside this range + will be mapped to ``NaN``, except for the values `1` and `-1` for which the output is + mapped to `+/-INF` respectively. + +.. math:: + \text{out}_{i} = \tanh^{-1}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.randn(4).uniform_(-1, 1) + >>> a + tensor([ -0.9385, 0.2968, -0.8591, -0.1871 ]) + >>> torch.atanh(a) + tensor([ -1.7253, 0.3060, -1.2899, -0.1893 ]) +""".format(**common_args), +) + +add_docstr( + torch.atanh_, + r""" +atanh_(input) -> Tensor + +In-place version of :func:`torch.atanh` +""", +) + +add_docstr( + torch.arctanh, + r""" +arctanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Alias for :func:`torch.atanh`. +""", +) + +add_docstr( + torch.arctanh_, + r""" +arctanh_(input) -> Tensor + +In-place version of :func:`torch.arctanh` +""", +) + +add_docstr( + torch.asarray, + r""" +asarray(obj: Any, *, dtype: Optional[dtype], device: Optional[DeviceLikeType], copy: Optional[bool] = None, requires_grad: Optional[bool] = None) -> Tensor # noqa: B950 + +Converts :attr:`obj` to a tensor. + +:attr:`obj` can be one of: + +1. a tensor +2. a NumPy array or a NumPy scalar +3. a DLPack capsule +4. an object that implements Python's buffer protocol +5. a scalar +6. a sequence of scalars + +When :attr:`obj` is a tensor, NumPy array, or DLPack capsule the returned tensor will, +by default, have the same requires_grad as :attr:`obj` (defaulting to False), have the +same datatype, be on the same device, and share memory with it. These properties can be +controlled with the :attr:`dtype`, :attr:`device`, :attr:`copy`, and +:attr:`requires_grad` keyword arguments. If the returned tensor is of a different +datatype, on a different device, or a copy is requested then it will not share its +memory with :attr:`obj`. If :attr:`requires_grad` is ``True`` (or ``None``, and +:attr:`obj` was a tensor with requires_grad set), then the returned tensor will require +a gradient, and if :attr:`obj` is also a tensor with an autograd history then the +returned tensor will have the same history. + +When :attr:`obj` is not a tensor, NumPy array, or DLPack capsule but implements Python's +buffer protocol then the buffer is interpreted as an array of bytes grouped according to +the size of the datatype passed to the :attr:`dtype` keyword argument. (If no datatype is +passed then the default floating point datatype is used, instead.) The returned tensor +will have the specified datatype (or default floating point datatype if none is specified) +and, by default, be on the CPU device and share memory with the buffer. + +When :attr:`obj` is a NumPy scalar, the returned tensor will be a 0-dimensional tensor on +the CPU and that doesn't share its memory (i.e. ``copy=True``). By default datatype will +be the PyTorch datatype corresponding to the NumPy's scalar's datatype. + +When :attr:`obj` is none of the above but a scalar, or a sequence of scalars then the +returned tensor will, by default, infer its datatype from the scalar values, be on the +current default device, and not share its memory. + +.. seealso:: + + :func:`torch.tensor` creates a tensor that always copies the data from the input object. + :func:`torch.from_numpy` creates a tensor that always shares memory from NumPy arrays. + :func:`torch.frombuffer` creates a tensor that always shares memory from objects that + implement the buffer protocol. + :func:`torch.from_dlpack` creates a tensor that always shares memory from + DLPack capsules. + +Args: + obj (object): a tensor, NumPy array, DLPack Capsule, object that implements Python's + buffer protocol, scalar, or sequence of scalars. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the datatype of the returned tensor. + Default: ``None``, which causes the datatype of the returned tensor to be + inferred from :attr:`obj`. + copy (bool, optional): controls whether the returned tensor shares memory with :attr:`obj`. + Default: ``None``, which causes the returned tensor to share memory with :attr:`obj` + whenever possible. If ``True`` then the returned tensor does not share its memory. + If ``False`` then the returned tensor shares its memory with :attr:`obj` and an + error is thrown if it cannot. + device (:class:`torch.device`, optional): the device of the returned tensor. + Default: ``None``, which causes the device of :attr:`obj` to be used. Or, if + :attr:`obj` is a Python sequence, the current default device will be used. + requires_grad (bool, optional): whether the returned tensor requires grad. + Default: ``None``, which causes requires_grad for the returned tensor to be + inferred from :attr:`obj`. If ``True``, then the returned tensor will require + a gradient, and if :attr:`obj` is also a tensor with an autograd history then + the returned tensor will have the same history. + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> # Shares memory with tensor 'a' + >>> b = torch.asarray(a) + >>> a.data_ptr() == b.data_ptr() + True + >>> # Forces memory copy + >>> c = torch.asarray(a, copy=True) + >>> a.data_ptr() == c.data_ptr() + False + + >>> a = torch.tensor([1., 2., 3.], requires_grad=True) + >>> b = a + 2 + >>> b + tensor([3., 4., 5.], grad_fn=) + >>> # Shares memory with tensor 'b', with no grad + >>> c = torch.asarray(b, requires_grad=False) + >>> c + tensor([3., 4., 5.]) + >>> # Shares memory with tensor 'b', retaining autograd history + >>> d = torch.asarray(b, requires_grad=True) + >>> d + tensor([3., 4., 5.], grad_fn=) + >>> # Shares memory with tensor 'b', retaining autograd history + >>> e = torch.asarray(b) + >>> e + tensor([3., 4., 5.], grad_fn=) + + >>> array = numpy.array([1, 2, 3]) + >>> # Shares memory with array 'array' + >>> t1 = torch.asarray(array) + >>> array.__array_interface__['data'][0] == t1.data_ptr() + True + >>> # Copies memory due to dtype mismatch + >>> t2 = torch.asarray(array, dtype=torch.float32) + >>> array.__array_interface__['data'][0] == t2.data_ptr() + False + + >>> scalar = numpy.float64(0.5) + >>> torch.asarray(scalar) + tensor(0.5000, dtype=torch.float64) +""", +) + +add_docstr( + torch.baddbmm, + r""" +baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + +Performs a batch matrix-matrix product of matrices in :attr:`batch1` +and :attr:`batch2`. +:attr:`input` is added to the final result. + +:attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same +number of matrices. + +If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a +:math:`(b \times m \times p)` tensor, then :attr:`input` must be +:ref:`broadcastable ` with a +:math:`(b \times n \times p)` tensor and :attr:`out` will be a +:math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the +same as the scaling factors used in :meth:`torch.addbmm`. + +.. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + +If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in +it will not be propagated. +""" + + r""" +For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and +:attr:`alpha` must be real numbers, otherwise they should be integers. + +{tf32_note} + +{rocm_fp16_note} + +Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{{batch1}} \mathbin{{@}} \text{{batch2}}` (:math:`\alpha`) + {out} + +Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + +.. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + +Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + +Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{{batch1}} \mathbin{{@}} \text{{batch2}}` (:math:`\alpha`) + {out} +""".format(**common_args, **tf32_notes, **rocm_fp16_notes), +) + +add_docstr( + torch.bernoulli, + r""" +bernoulli(input: Tensor, *, generator: Optional[Generator], out: Optional[Tensor]) -> Tensor + +Draws binary random numbers (0 or 1) from a Bernoulli distribution. + +The :attr:`input` tensor should be a tensor containing probabilities +to be used for drawing the binary random number. +Hence, all values in :attr:`input` have to be in the range: +:math:`0 \leq \text{input}_i \leq 1`. + +The :math:`\text{i}^{th}` element of the output tensor will draw a +value :math:`1` according to the :math:`\text{i}^{th}` probability value given +in :attr:`input`. + +.. math:: + \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i}) +""" + + r""" +The returned :attr:`out` tensor only has values 0 or 1 and is of the same +shape as :attr:`input`. + +:attr:`out` can have integral ``dtype``, but :attr:`input` must have floating +point ``dtype``. + +Args: + input (Tensor): the input tensor of probability values for the Bernoulli distribution + +Keyword args: + {generator} + {out} + +Example:: + + >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] + >>> a + tensor([[ 0.1737, 0.0950, 0.3609], + [ 0.7148, 0.0289, 0.2676], + [ 0.9456, 0.8937, 0.7202]]) + >>> torch.bernoulli(a) + tensor([[ 1., 0., 0.], + [ 0., 0., 0.], + [ 1., 1., 1.]]) + + >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 + >>> torch.bernoulli(a) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 + >>> torch.bernoulli(a) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) +""".format(**common_args), +) + +add_docstr( + torch.bincount, + r""" +bincount(input, weights=None, minlength=0) -> Tensor + +Count the frequency of each value in an array of non-negative ints. + +The number of bins (size 1) is one larger than the largest value in +:attr:`input` unless :attr:`input` is empty, in which case the result is a +tensor of size 0. If :attr:`minlength` is specified, the number of bins is at least +:attr:`minlength` and if :attr:`input` is empty, then the result is tensor of size +:attr:`minlength` filled with zeros. If ``n`` is the value at position ``i``, +``out[n] += weights[i]`` if :attr:`weights` is specified else +``out[n] += 1``. + +Note: + {backward_reproducibility_note} + +Arguments: + input (Tensor): 1-d int tensor + weights (Tensor): optional, weight for each value in the input tensor. + Should be of same size as input tensor. + minlength (int): optional, minimum number of bins. Should be non-negative. + +Returns: + output (Tensor): a tensor of shape ``Size([max(input) + 1])`` if + :attr:`input` is non-empty, else ``Size(0)`` + +Example:: + + >>> input = torch.randint(0, 8, (5,), dtype=torch.int64) + >>> weights = torch.linspace(0, 1, steps=5) + >>> input, weights + (tensor([4, 3, 6, 3, 4]), + tensor([ 0.0000, 0.2500, 0.5000, 0.7500, 1.0000]) + + >>> torch.bincount(input) + tensor([0, 0, 0, 2, 2, 0, 1]) + + >>> input.bincount(weights) + tensor([0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 0.0000, 0.5000]) +""".format(**reproducibility_notes), +) + +add_docstr( + torch.bitwise_not, + r""" +bitwise_not(input, *, out=None) -> Tensor + +Computes the bitwise NOT of the given input tensor. The input tensor must be of +integral or Boolean types. For bool tensors, it computes the logical NOT. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_not(torch.tensor([-1, -2, 3], dtype=torch.int8)) + tensor([ 0, 1, -4], dtype=torch.int8) +""".format(**common_args), +) + +add_docstr( + torch.bmm, + r""" +bmm(input, mat2, *, out=None) -> Tensor + +Performs a batch matrix-matrix product of matrices stored in :attr:`input` +and :attr:`mat2`. + +:attr:`input` and :attr:`mat2` must be 3-D tensors each containing +the same number of matrices. + +If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` is a +:math:`(b \times m \times p)` tensor, :attr:`out` will be a +:math:`(b \times n \times p)` tensor. + +.. math:: + \text{out}_i = \text{input}_i \mathbin{@} \text{mat2}_i +""" + + r""" +{tf32_note} + +{rocm_fp16_note} + +.. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + +Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + +Keyword Args: + {out} + +Example:: + + >>> input = torch.randn(10, 3, 4) + >>> mat2 = torch.randn(10, 4, 5) + >>> res = torch.bmm(input, mat2) + >>> res.size() + torch.Size([10, 3, 5]) + +.. function:: bmm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + +Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + +Keyword Args: + {out} +""".format(**common_args, **tf32_notes, **rocm_fp16_notes), +) + +add_docstr( + torch.bitwise_and, + r""" +bitwise_and(input, other, *, out=None) -> Tensor + +Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of +integral or Boolean types. For bool tensors, it computes the logical AND. + +Args: + input: the first input tensor + other: the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.bitwise_or, + r""" +bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + +Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of +integral or Boolean types. For bool tensors, it computes the logical OR. + +Args: + input: the first input tensor + other: the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.bitwise_xor, + r""" +bitwise_xor(input, other, *, out=None) -> Tensor + +Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of +integral or Boolean types. For bool tensors, it computes the logical XOR. + +Args: + input: the first input tensor + other: the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) +""".format(**common_args), +) + +add_docstr( + torch.bitwise_left_shift, + r""" +bitwise_left_shift(input, other, *, out=None) -> Tensor + +Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. +The input tensor must be of integral type. This operator supports +:ref:`broadcasting to a common shape ` and +:ref:`type promotion `. + +The operation applied is: + +.. math:: + \text{{out}}_i = \text{{input}}_i << \text{{other}}_i + +Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) +""".format(**common_args), +) + +add_docstr( + torch.bitwise_right_shift, + r""" +bitwise_right_shift(input, other, *, out=None) -> Tensor + +Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. +The input tensor must be of integral type. This operator supports +:ref:`broadcasting to a common shape ` and +:ref:`type promotion `. +In any case, if the value of the right operand is negative or is greater +or equal to the number of bits in the promoted left operand, the behavior is undefined. + +The operation applied is: + +.. math:: + \text{{out}}_i = \text{{input}}_i >> \text{{other}}_i + +Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) +""".format(**common_args), +) + +add_docstr( + torch.broadcast_to, + r""" +broadcast_to(input, shape) -> Tensor + +Broadcasts :attr:`input` to the shape :attr:`\shape`. +Equivalent to calling ``input.expand(shape)``. See :meth:`~Tensor.expand` for details. + +Args: + {input} + shape (list, tuple, or :class:`torch.Size`): the new shape. + +Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> torch.broadcast_to(x, (3, 3)) + tensor([[1, 2, 3], + [1, 2, 3], + [1, 2, 3]]) +""".format(**common_args), +) + +add_docstr( + torch.stack, + r""" +stack(tensors, dim=0, *, out=None) -> Tensor + +Concatenates a sequence of tensors along a new dimension. + +All tensors need to be of the same size. + +.. seealso:: + + :func:`torch.cat` concatenates the given sequence along an existing dimension. + +Arguments: + tensors (sequence of Tensors): sequence of tensors to concatenate + dim (int, optional): dimension to insert. Has to be between 0 and the number + of dimensions of concatenated tensors (inclusive). Default: 0 + +Keyword args: + {out} + +Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]) + >>> torch.stack((x, x)) # same as torch.stack((x, x), dim=0) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]], + + [[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]]) + >>> torch.stack((x, x)).size() + torch.Size([2, 2, 3]) + >>> torch.stack((x, x), dim=1) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.3367, 0.1288, 0.2345]], + + [[ 0.2303, -1.1229, -0.1863], + [ 0.2303, -1.1229, -0.1863]]]) + >>> torch.stack((x, x), dim=2) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) + >>> torch.stack((x, x), dim=-1) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) +""".format(**common_args), +) + +add_docstr( + torch.hstack, + r""" +hstack(tensors, *, out=None) -> Tensor + +Stack tensors in sequence horizontally (column wise). + +This is equivalent to concatenation along the first axis for 1-D tensors, and along the second axis for all other tensors. + +Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.hstack((a,b)) + tensor([1, 2, 3, 4, 5, 6]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.hstack((a,b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + +""".format(**common_args), +) + +add_docstr( + torch.vstack, + r""" +vstack(tensors, *, out=None) -> Tensor + +Stack tensors in sequence vertically (row wise). + +This is equivalent to concatenation along the first axis after all 1-D tensors have been reshaped by :func:`torch.atleast_2d`. + +Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.vstack((a,b)) + tensor([[1, 2, 3], + [4, 5, 6]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.vstack((a,b)) + tensor([[1], + [2], + [3], + [4], + [5], + [6]]) + + +""".format(**common_args), +) + +add_docstr( + torch.dstack, + r""" +dstack(tensors, *, out=None) -> Tensor + +Stack tensors in sequence depthwise (along third axis). + +This is equivalent to concatenation along the third axis after 1-D and 2-D tensors have been reshaped by :func:`torch.atleast_3d`. + +Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.dstack((a,b)) + tensor([[[1, 4], + [2, 5], + [3, 6]]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.dstack((a,b)) + tensor([[[1, 4]], + [[2, 5]], + [[3, 6]]]) + + +""".format(**common_args), +) + +add_docstr( + torch.tensor_split, + r""" +tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + +Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, +along dimension :attr:`dim` according to the indices or number of sections specified +by :attr:`indices_or_sections`. This function is based on NumPy's +:func:`numpy.array_split`. + +.. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + +.. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + +Args: + input (Tensor): the tensor to split + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + +Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) +""", +) + +add_docstr( + torch.chunk, + r""" +chunk(input: Tensor, chunks: int, dim: int = 0) -> Tuple[Tensor, ...] + +Attempts to split a tensor into the specified number of chunks. Each chunk is a view of +the input tensor. + + +.. note:: + + This function may return fewer than the specified number of chunks! + +.. seealso:: + + :func:`torch.tensor_split` a function that always returns exactly the specified number of chunks + +If the tensor size along the given dimension :attr:`dim` is divisible by :attr:`chunks`, +all returned chunks will be the same size. +If the tensor size along the given dimension :attr:`dim` is not divisible by :attr:`chunks`, +all returned chunks will be the same size, except the last one. +If such division is not possible, this function may return fewer +than the specified number of chunks. + +Arguments: + input (Tensor): the tensor to split + chunks (int): number of chunks to return + dim (int): dimension along which to split the tensor + +Example: + >>> torch.arange(11).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10])) + >>> torch.arange(12).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10, 11])) + >>> torch.arange(13).chunk(6) + (tensor([0, 1, 2]), + tensor([3, 4, 5]), + tensor([6, 7, 8]), + tensor([ 9, 10, 11]), + tensor([12])) +""", +) + +add_docstr( + torch.unsafe_chunk, + r""" +unsafe_chunk(input, chunks, dim=0) -> List of Tensors + +Works like :func:`torch.chunk` but without enforcing the autograd restrictions +on inplace modification of the outputs. + +.. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. +""", +) + +add_docstr( + torch.unsafe_split, + r""" +unsafe_split(tensor, split_size_or_sections, dim=0) -> List of Tensors + +Works like :func:`torch.split` but without enforcing the autograd restrictions +on inplace modification of the outputs. + +.. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. +""", +) + +add_docstr( + torch.hsplit, + r""" +hsplit(input, indices_or_sections) -> List of Tensors + +Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors +horizontally according to :attr:`indices_or_sections`. Each split is a view of +:attr:`input`. + +If :attr:`input` is one dimensional this is equivalent to calling +torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is +zero), and if :attr:`input` has two or more dimensions it's equivalent to calling +torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), +except that if :attr:`indices_or_sections` is an integer it must evenly divide +the split dimension or a runtime error will be thrown. + +This function is based on NumPy's :func:`numpy.hsplit`. + +Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + +Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + +""", +) + +add_docstr( + torch.vsplit, + r""" +vsplit(input, indices_or_sections) -> List of Tensors + +Splits :attr:`input`, a tensor with two or more dimensions, into multiple tensors +vertically according to :attr:`indices_or_sections`. Each split is a view of +:attr:`input`. + +This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=0) +(the split dimension is 0), except that if :attr:`indices_or_sections` is an integer +it must evenly divide the split dimension or a runtime error will be thrown. + +This function is based on NumPy's :func:`numpy.vsplit`. + +Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + +Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.vsplit(t, 2) + (tensor([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), + tensor([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])) + >>> torch.vsplit(t, [3, 6]) + (tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), + tensor([[12., 13., 14., 15.]]), + tensor([], size=(0, 4))) + +""", +) + +add_docstr( + torch.dsplit, + r""" +dsplit(input, indices_or_sections) -> List of Tensors + +Splits :attr:`input`, a tensor with three or more dimensions, into multiple tensors +depthwise according to :attr:`indices_or_sections`. Each split is a view of +:attr:`input`. + +This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=2) +(the split dimension is 2), except that if :attr:`indices_or_sections` is an integer +it must evenly divide the split dimension or a runtime error will be thrown. + +This function is based on NumPy's :func:`numpy.dsplit`. + +Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + +Example:: + + >>> t = torch.arange(16.0).reshape(2, 2, 4) + >>> t + tensor([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> torch.dsplit(t, 2) + (tensor([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), + tensor([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])) + + >>> torch.dsplit(t, [3, 6]) + (tensor([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + tensor([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + tensor([], size=(2, 2, 0))) + +""", +) + +add_docstr( + torch.can_cast, + r""" +can_cast(from_, to) -> bool + +Determines if a type conversion is allowed under PyTorch casting rules +described in the type promotion :ref:`documentation `. + +Args: + from\_ (dtype): The original :class:`torch.dtype`. + to (dtype): The target :class:`torch.dtype`. + +Example:: + + >>> torch.can_cast(torch.double, torch.float) + True + >>> torch.can_cast(torch.float, torch.int) + False +""", +) + +add_docstr( + torch.corrcoef, + r""" +corrcoef(input) -> Tensor + +Estimates the Pearson product-moment correlation coefficient matrix of the variables given by the :attr:`input` matrix, +where rows are the variables and columns are the observations. + +.. note:: + + The correlation coefficient matrix R is computed using the covariance matrix C as given by + :math:`R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }` + +.. note:: + + Due to floating point rounding, the resulting array may not be Hermitian and its diagonal elements may not be 1. + The real and imaginary values are clipped to the interval [-1, 1] in an attempt to improve this situation. + +Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + +Returns: + (Tensor) The correlation coefficient matrix of the variables. + +.. seealso:: + + :func:`torch.cov` covariance matrix. + +Example:: + + >>> x = torch.tensor([[0, 1, 2], [2, 1, 0]]) + >>> torch.corrcoef(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> x = torch.randn(2, 4) + >>> x + tensor([[-0.2678, -0.0908, -0.3766, 0.2780], + [-0.5812, 0.1535, 0.2387, 0.2350]]) + >>> torch.corrcoef(x) + tensor([[1.0000, 0.3582], + [0.3582, 1.0000]]) + >>> torch.corrcoef(x[0]) + tensor(1.) +""", +) + +add_docstr( + torch.cov, + r""" +cov(input, *, correction=1, fweights=None, aweights=None) -> Tensor + +Estimates the covariance matrix of the variables given by the :attr:`input` matrix, where rows are +the variables and columns are the observations. + +A covariance matrix is a square matrix giving the covariance of each pair of variables. The diagonal contains +the variance of each variable (covariance of a variable with itself). By definition, if :attr:`input` represents +a single variable (Scalar or 1D) then its variance is returned. + +The sample covariance of the variables :math:`x` and :math:`y` is given by: + +.. math:: + \text{cov}(x,y) = \frac{\sum^{N}_{i = 1}(x_{i} - \bar{x})(y_{i} - \bar{y})}{\max(0,~N~-~\delta N)} + +where :math:`\bar{x}` and :math:`\bar{y}` are the simple means of the :math:`x` and :math:`y` respectively, and +:math:`\delta N` is the :attr:`correction`. + +If :attr:`fweights` and/or :attr:`aweights` are provided, the weighted covariance +is calculated, which is given by: + +.. math:: + \text{cov}_w(x,y) = \frac{\sum^{N}_{i = 1}w_i(x_{i} - \mu_x^*)(y_{i} - \mu_y^*)} + {\max(0,~\sum^{N}_{i = 1}w_i~-~\frac{\sum^{N}_{i = 1}w_ia_i}{\sum^{N}_{i = 1}w_i}~\delta N)} + +where :math:`w` denotes :attr:`fweights` or :attr:`aweights` (``f`` and ``a`` for brevity) based on whichever is +provided, or :math:`w = f \times a` if both are provided, and +:math:`\mu_x^* = \frac{\sum^{N}_{i = 1}w_ix_{i} }{\sum^{N}_{i = 1}w_i}` is the weighted mean of the variable. If not +provided, ``f`` and/or ``a`` can be seen as a :math:`\mathbb{1}` vector of appropriate size. + +Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + +Keyword Args: + correction (int, optional): difference between the sample size and sample degrees of freedom. + Defaults to Bessel's correction, ``correction = 1`` which returns the unbiased estimate, + even if both :attr:`fweights` and :attr:`aweights` are specified. ``correction = 0`` + will return the simple average. Defaults to ``1``. + fweights (tensor, optional): A Scalar or 1D tensor of observation vector frequencies representing the number of + times each observation should be repeated. Its numel must equal the number of columns of :attr:`input`. + Must have integral dtype. Ignored if ``None``. Defaults to ``None``. + aweights (tensor, optional): A Scalar or 1D array of observation vector weights. + These relative weights are typically large for observations considered "important" and smaller for + observations considered less "important". Its numel must equal the number of columns of :attr:`input`. + Must have floating point dtype. Ignored if ``None``. Defaults to ``None``. + +Returns: + (Tensor) The covariance matrix of the variables. + +.. seealso:: + + :func:`torch.corrcoef` normalized covariance matrix. + +Example:: + + >>> x = torch.tensor([[0, 2], [1, 1], [2, 0]]).T + >>> x + tensor([[0, 1, 2], + [2, 1, 0]]) + >>> torch.cov(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> torch.cov(x, correction=0) + tensor([[ 0.6667, -0.6667], + [-0.6667, 0.6667]]) + >>> fw = torch.randint(1, 10, (3,)) + >>> fw + tensor([1, 6, 9]) + >>> aw = torch.rand(3) + >>> aw + tensor([0.4282, 0.0255, 0.4144]) + >>> torch.cov(x, fweights=fw, aweights=aw) + tensor([[ 0.4169, -0.4169], + [-0.4169, 0.4169]]) +""", +) + +add_docstr( + torch.cat, + r""" +cat(tensors, dim=0, *, out=None) -> Tensor + +Concatenates the given sequence of tensors in :attr:`tensors` in the given dimension. +All tensors must either have the same shape (except in the concatenating +dimension) or be a 1-D empty tensor with size ``(0,)``. + +:func:`torch.cat` can be seen as an inverse operation for :func:`torch.split` +and :func:`torch.chunk`. + +:func:`torch.cat` can be best understood via examples. + +.. seealso:: + + :func:`torch.stack` concatenates the given sequence along a new dimension. + +Args: + tensors (sequence of Tensors): Non-empty tensors provided must have the same shape, + except in the cat dimension. + + dim (int, optional): the dimension over which the tensors are concatenated + +Keyword args: + {out} + +Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 0) + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 1) + tensor([[ 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614, 0.6580, + -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497, -0.1034, + -0.5790, 0.1497]]) +""".format(**common_args), +) + +add_docstr( + torch.concat, + r""" +concat(tensors, dim=0, *, out=None) -> Tensor + +Alias of :func:`torch.cat`. +""", +) + +add_docstr( + torch.concatenate, + r""" +concatenate(tensors, axis=0, out=None) -> Tensor + +Alias of :func:`torch.cat`. +""", +) + +add_docstr( + torch.ceil, + r""" +ceil(input, *, out=None) -> Tensor + +Returns a new tensor with the ceil of the elements of :attr:`input`, +the smallest integer greater than or equal to each element. + +For integer inputs, follows the array-api convention of returning a +copy of the input tensor. + +.. math:: + \text{out}_{i} = \left\lceil \text{input}_{i} \right\rceil +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.6341, -1.4208, -1.0900, 0.5826]) + >>> torch.ceil(a) + tensor([-0., -1., -1., 1.]) +""".format(**common_args), +) + +add_docstr( + torch.ceil_, + r""" +ceil_(input) -> Tensor + +In-place version of :func:`torch.ceil` +""", +) + +add_docstr( + torch.real, + r""" +real(input) -> Tensor + +Returns a new tensor containing real values of the :attr:`self` tensor. +The returned tensor and :attr:`self` share the same underlying storage. + +Args: + {input} + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.real + tensor([ 0.3100, -0.5445, -1.6492, -0.0638]) + +""".format(**common_args), +) + +add_docstr( + torch.imag, + r""" +imag(input) -> Tensor + +Returns a new tensor containing imaginary values of the :attr:`self` tensor. +The returned tensor and :attr:`self` share the same underlying storage. + +.. warning:: + :func:`imag` is only supported for tensors with complex dtypes. + +Args: + {input} + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.imag + tensor([ 0.3553, -0.7896, -0.0633, -0.8119]) + +""".format(**common_args), +) + +add_docstr( + torch.view_as_real, + r""" +view_as_real(input) -> Tensor + +Returns a view of :attr:`input` as a real tensor. For an input complex tensor of +:attr:`size` :math:`m1, m2, \dots, mi`, this function returns a new +real tensor of size :math:`m1, m2, \dots, mi, 2`, where the last dimension of size 2 +represents the real and imaginary components of complex numbers. + +.. warning:: + :func:`view_as_real` is only supported for tensors with ``complex dtypes``. + +Args: + {input} + +Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.4737-0.3839j), (-0.2098-0.6699j), (0.3470-0.9451j), (-0.5174-1.3136j)]) + >>> torch.view_as_real(x) + tensor([[ 0.4737, -0.3839], + [-0.2098, -0.6699], + [ 0.3470, -0.9451], + [-0.5174, -1.3136]]) +""".format(**common_args), +) + +add_docstr( + torch.view_as_complex, + r""" +view_as_complex(input) -> Tensor + +Returns a view of :attr:`input` as a complex tensor. For an input complex +tensor of :attr:`size` :math:`m1, m2, \dots, mi, 2`, this function returns a +new complex tensor of :attr:`size` :math:`m1, m2, \dots, mi` where the last +dimension of the input tensor is expected to represent the real and imaginary +components of complex numbers. + +.. warning:: + :func:`view_as_complex` is only supported for tensors with + :class:`torch.dtype` ``torch.float64`` and ``torch.float32``. The input is + expected to have the last dimension of :attr:`size` 2. In addition, the + tensor must have a `stride` of 1 for its last dimension. The strides of all + other dimensions must be even numbers. + +Args: + {input} + +Example:: + + >>> x=torch.randn(4, 2) + >>> x + tensor([[ 1.6116, -0.5772], + [-1.4606, -0.9120], + [ 0.0786, -1.7497], + [-0.6561, -1.6623]]) + >>> torch.view_as_complex(x) + tensor([(1.6116-0.5772j), (-1.4606-0.9120j), (0.0786-1.7497j), (-0.6561-1.6623j)]) +""".format(**common_args), +) + +add_docstr( + torch.reciprocal, + r""" +reciprocal(input, *, out=None) -> Tensor + +Returns a new tensor with the reciprocal of the elements of :attr:`input` + +.. math:: + \text{out}_{i} = \frac{1}{\text{input}_{i}} + +.. note:: + Unlike NumPy's reciprocal, torch.reciprocal supports integral inputs. Integral + inputs to reciprocal are automatically :ref:`promoted ` to + the default scalar type. +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.4595, -2.1219, -1.4314, 0.7298]) + >>> torch.reciprocal(a) + tensor([-2.1763, -0.4713, -0.6986, 1.3702]) +""".format(**common_args), +) + +add_docstr( + torch.reciprocal_, + r""" +reciprocal_(input) -> Tensor + +In-place version of :func:`torch.reciprocal` +""", +) + +add_docstr( + torch.cholesky_solve, + r""" +cholesky_solve(B, L, upper=False, *, out=None) -> Tensor + +Computes the solution of a system of linear equations with complex Hermitian +or real symmetric positive-definite lhs given its Cholesky decomposition. + +Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, +and :math:`L` its Cholesky decomposition such that: + +.. math:: + + A = LL^{\text{H}} + +where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, +and the transpose when :math:`L` is real-valued. + +Returns the solution :math:`X` of the following linear system: + +.. math:: + + AX = B + +Supports inputs of float, double, cfloat and cdouble dtypes. +Also supports batches of matrices, and if :math:`A` or :math:`B` is a batch of matrices +then the output has the same batch dimensions. + +Args: + B (Tensor): right-hand side tensor of shape `(*, n, k)` + where :math:`*` is zero or more batch dimensions + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False``. + +Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + +Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> B = torch.randn(3, 2) + >>> torch.cholesky_solve(B, L) + tensor([[ -8.1625, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + >>> A.inverse() @ B + tensor([[ -8.1626, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> B = torch.randn(2, 1, dtype=torch.complex64) + >>> X = torch.cholesky_solve(B, L) + >>> torch.dist(X, A.inverse() @ B) + tensor(1.6881e-5) +""", +) + +add_docstr( + torch.cholesky_inverse, + r""" +cholesky_inverse(L, upper=False, *, out=None) -> Tensor + +Computes the inverse of a complex Hermitian or real symmetric +positive-definite matrix given its Cholesky decomposition. + +Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, +and :math:`L` its Cholesky decomposition such that: + +.. math:: + + A = LL^{\text{H}} + +where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, +and the transpose when :math:`L` is real-valued. + +Computes the inverse matrix :math:`A^{-1}`. + +Supports input of float, double, cfloat and cdouble dtypes. +Also supports batches of matrices, and if :math:`A` is a batch of matrices +then the output has the same batch dimensions. + +Args: + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False`` + +Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + +Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> torch.cholesky_inverse(L) + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + >>> A.inverse() + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> torch.dist(torch.inverse(A), torch.cholesky_inverse(L)) + tensor(5.6358e-7) +""", +) + +add_docstr( + torch.clone, + r""" +clone(input, *, memory_format=torch.preserve_format) -> Tensor + +Returns a copy of :attr:`input`. + +.. note:: + + This function is differentiable, so gradients will flow back from the + result of this operation to :attr:`input`. To create a tensor without an + autograd relationship to :attr:`input` see :meth:`~Tensor.detach`. + + In addition, when ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense (contiguous) format. + +Args: + {input} + +Keyword args: + {memory_format} +""".format(**common_args), +) + +add_docstr( + torch.clamp, + r""" +clamp(input, min=None, max=None, *, out=None) -> Tensor + +Clamps all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]`. +Letting min_value and max_value be :attr:`min` and :attr:`max`, respectively, this returns: + +.. math:: + y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value}_i) + +If :attr:`min` is ``None``, there is no lower bound. +Or, if :attr:`max` is ``None`` there is no upper bound. +""" + + r""" + +.. note:: + If :attr:`min` is greater than :attr:`max` :func:`torch.clamp(..., min, max) ` + sets all elements in :attr:`input` to the value of :attr:`max`. + +Args: + {input} + min (Number or Tensor, optional): lower-bound of the range to be clamped to + max (Number or Tensor, optional): upper-bound of the range to be clamped to + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.7120, 0.1734, -0.0478, -0.0922]) + >>> torch.clamp(a, min=-0.5, max=0.5) + tensor([-0.5000, 0.1734, -0.0478, -0.0922]) + + >>> min = torch.linspace(-1, 1, steps=4) + >>> torch.clamp(a, min=min) + tensor([-1.0000, 0.1734, 0.3333, 1.0000]) + +""".format(**common_args), +) + +add_docstr( + torch.clamp_, + r""" +clamp_(input, min=None, max=None) -> Tensor + +In-place version of :func:`torch.clamp` +""", +) + +add_docstr( + torch.clip, + r""" +clip(input, min=None, max=None, *, out=None) -> Tensor + +Alias for :func:`torch.clamp`. +""", +) + +add_docstr( + torch.clip_, + r""" +clip_(input, min=None, max=None) -> Tensor + +In-place version of :func:`torch.clip` +""", +) + +add_docstr( + torch.column_stack, + r""" +column_stack(tensors, *, out=None) -> Tensor + +Creates a new tensor by horizontally stacking the tensors in :attr:`tensors`. + +Equivalent to ``torch.hstack(tensors)``, except each zero or one dimensional tensor ``t`` +in :attr:`tensors` is first reshaped into a ``(t.numel(), 1)`` column before being stacked horizontally. + +Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.column_stack((a, b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + >>> a = torch.arange(5) + >>> b = torch.arange(10).reshape(5, 2) + >>> torch.column_stack((a, b, b)) + tensor([[0, 0, 1, 0, 1], + [1, 2, 3, 2, 3], + [2, 4, 5, 4, 5], + [3, 6, 7, 6, 7], + [4, 8, 9, 8, 9]]) + +""".format(**common_args), +) + +add_docstr( + torch.complex, + r""" +complex(real, imag, *, out=None) -> Tensor + +Constructs a complex tensor with its real part equal to :attr:`real` and its +imaginary part equal to :attr:`imag`. + +Args: + real (Tensor): The real part of the complex tensor. Must be half, float or double. + imag (Tensor): The imaginary part of the complex tensor. Must be same dtype + as :attr:`real`. + +Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + +Example:: + + >>> real = torch.tensor([1, 2], dtype=torch.float32) + >>> imag = torch.tensor([3, 4], dtype=torch.float32) + >>> z = torch.complex(real, imag) + >>> z + tensor([(1.+3.j), (2.+4.j)]) + >>> z.dtype + torch.complex64 + +""", +) + +add_docstr( + torch.polar, + r""" +polar(abs, angle, *, out=None) -> Tensor + +Constructs a complex tensor whose elements are Cartesian coordinates +corresponding to the polar coordinates with absolute value :attr:`abs` and angle +:attr:`angle`. + +.. math:: + \text{out} = \text{abs} \cdot \cos(\text{angle}) + \text{abs} \cdot \sin(\text{angle}) \cdot j + +.. note:: + `torch.polar` is similar to + `std::polar `_ + and does not compute the polar decomposition + of a complex tensor like Python's `cmath.polar` and SciPy's `linalg.polar` do. + The behavior of this function is undefined if `abs` is negative or NaN, or if `angle` is + infinite. + +""" + + r""" +Args: + abs (Tensor): The absolute value the complex tensor. Must be float or double. + angle (Tensor): The angle of the complex tensor. Must be same dtype as + :attr:`abs`. + +Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + +Example:: + + >>> import numpy as np + >>> abs = torch.tensor([1, 2], dtype=torch.float64) + >>> angle = torch.tensor([np.pi / 2, 5 * np.pi / 4], dtype=torch.float64) + >>> z = torch.polar(abs, angle) + >>> z + tensor([(0.0000+1.0000j), (-1.4142-1.4142j)], dtype=torch.complex128) +""", +) + +add_docstr( + torch.conj_physical, + r""" +conj_physical(input, *, out=None) -> Tensor + +Computes the element-wise conjugate of the given :attr:`input` tensor. +If :attr:`input` has a non-complex dtype, this function just returns :attr:`input`. + +.. note:: + This performs the conjugate operation regardless of the fact conjugate bit is set or not. + +.. warning:: In the future, :func:`torch.conj_physical` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + +.. math:: + \text{out}_{i} = conj(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.conj_physical(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j])) + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) +""".format(**common_args), +) + +add_docstr( + torch.conj_physical_, + r""" +conj_physical_(input) -> Tensor + +In-place version of :func:`torch.conj_physical` +""", +) + +add_docstr( + torch.conj, + r""" +conj(input) -> Tensor + +Returns a view of :attr:`input` with a flipped conjugate bit. If :attr:`input` has a non-complex dtype, +this function just returns :attr:`input`. + +.. note:: + :func:`torch.conj` performs a lazy conjugation, but the actual conjugated tensor can be materialized + at any time using :func:`torch.resolve_conj`. + +.. warning:: In the future, :func:`torch.conj` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + +Args: + {input} + +Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> x.is_conj() + False + >>> y = torch.conj(x) + >>> y.is_conj() + True +""".format(**common_args), +) + +add_docstr( + torch.resolve_conj, + r""" +resolve_conj(input) -> Tensor + +Returns a new tensor with materialized conjugation if :attr:`input`'s conjugate bit is set to `True`, +else returns :attr:`input`. The output tensor will always have its conjugate bit set to `False`. + +Args: + {input} + +Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> y.is_conj() + True + >>> z = y.resolve_conj() + >>> z + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) + >>> z.is_conj() + False +""".format(**common_args), +) + +add_docstr( + torch.resolve_neg, + r""" +resolve_neg(input) -> Tensor + +Returns a new tensor with materialized negation if :attr:`input`'s negative bit is set to `True`, +else returns :attr:`input`. The output tensor will always have its negative bit set to `False`. + +Args: + {input} + +Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> z = y.imag + >>> z.is_neg() + True + >>> out = z.resolve_neg() + >>> out + tensor([-1., -2., 3.]) + >>> out.is_neg() + False +""".format(**common_args), +) + +add_docstr( + torch.copysign, + r""" +copysign(input, other, *, out=None) -> Tensor + +Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + +.. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} +""" + + r""" + +Supports :ref:`broadcasting to a common shape `, +and integer and float inputs. + +Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + +.. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + +""".format(**common_args), +) + +add_docstr( + torch.cos, + r""" +cos(input, *, out=None) -> Tensor + +Returns a new tensor with the cosine of the elements of :attr:`input` given in radians. + +.. math:: + \text{out}_{i} = \cos(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 1.4309, 1.2706, -0.8562, 0.9796]) + >>> torch.cos(a) + tensor([ 0.1395, 0.2957, 0.6553, 0.5574]) +""".format(**common_args), +) + +add_docstr( + torch.cos_, + r""" +cos_(input) -> Tensor + +In-place version of :func:`torch.cos` +""", +) + +add_docstr( + torch.cosh, + r""" +cosh(input, *, out=None) -> Tensor + +Returns a new tensor with the hyperbolic cosine of the elements of +:attr:`input`. + +.. math:: + \text{out}_{i} = \cosh(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1632, 1.1835, -0.6979, -0.7325]) + >>> torch.cosh(a) + tensor([ 1.0133, 1.7860, 1.2536, 1.2805]) + +""".format(**common_args), +) + +add_docstr( + torch.cosh_, + r""" +cosh_(input) -> Tensor + +In-place version of :func:`torch.cosh` +""", +) + +add_docstr( + torch.cross, + r""" +cross(input, other, dim=None, *, out=None) -> Tensor + + +Returns the cross product of vectors in dimension :attr:`dim` of :attr:`input` +and :attr:`other`. + +Supports input of float, double, cfloat and cdouble dtypes. Also supports batches +of vectors, for which it computes the product along the dimension :attr:`dim`. +In this case, the output has the same batch dimensions as the inputs. + +.. warning:: + If :attr:`dim` is not given, it defaults to the first dimension found + with the size 3. Note that this might be unexpected. + + This behavior is deprecated and will be changed to match that of :func:`torch.linalg.cross` + in a future release. + +.. seealso:: + :func:`torch.linalg.cross` which has dim=-1 as default. + + +Args: + {input} + other (Tensor): the second input tensor + dim (int, optional): the dimension to take the cross-product in. + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4, 3) + >>> a + tensor([[-0.3956, 1.1455, 1.6895], + [-0.5849, 1.3672, 0.3599], + [-1.1626, 0.7180, -0.0521], + [-0.1339, 0.9902, -2.0225]]) + >>> b = torch.randn(4, 3) + >>> b + tensor([[-0.0257, -1.4725, -1.2251], + [-1.1479, -0.7005, -1.9757], + [-1.3904, 0.3726, -1.1836], + [-0.9688, -0.7153, 0.2159]]) + >>> torch.cross(a, b, dim=1) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + >>> torch.cross(a, b) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) +""".format(**common_args), +) + +add_docstr( + torch.logcumsumexp, + r""" +logcumsumexp(input, dim, *, out=None) -> Tensor +Returns the logarithm of the cumulative summation of the exponentiation of +elements of :attr:`input` in the dimension :attr:`dim`. + +For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{{logcumsumexp}}(x)_{{ij}} = \log \sum\limits_{{k=0}}^{{j}} \exp(x_{{ik}}) + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(10) + >>> torch.logcumsumexp(a, dim=0) + tensor([-0.42296738, -0.04462666, 0.86278635, 0.94622083, 1.05277811, + 1.39202815, 1.83525007, 1.84492621, 2.06084887, 2.06844475])) +""".format(**reduceops_common_args), +) + +add_docstr( + torch.cummax, + r""" +cummax(input, dim, *, out=None) -> (Tensor, LongTensor) +Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative maximum of +elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index +location of each maximum value found in the dimension :attr:`dim`. + +.. math:: + y_i = max(x_1, x_2, x_3, \dots, x_i) + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + +Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.3449, -1.5447, 0.0685, -1.5104, -1.1706, 0.2259, 1.4696, -1.3284, + 1.9946, -0.8209]) + >>> torch.cummax(a, dim=0) + torch.return_types.cummax( + values=tensor([-0.3449, -0.3449, 0.0685, 0.0685, 0.0685, 0.2259, 1.4696, 1.4696, + 1.9946, 1.9946]), + indices=tensor([0, 0, 2, 2, 2, 5, 6, 6, 8, 8])) +""".format(**reduceops_common_args), +) + +add_docstr( + torch.cummin, + r""" +cummin(input, dim, *, out=None) -> (Tensor, LongTensor) +Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative minimum of +elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index +location of each maximum value found in the dimension :attr:`dim`. + +.. math:: + y_i = min(x_1, x_2, x_3, \dots, x_i) + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + +Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220, -0.3885, 1.1762, + 0.9165, 1.6684]) + >>> torch.cummin(a, dim=0) + torch.return_types.cummin( + values=tensor([-0.2284, -0.6628, -0.6628, -0.6628, -1.3298, -1.3298, -1.3298, -1.3298, + -1.3298, -1.3298]), + indices=tensor([0, 1, 1, 1, 4, 4, 4, 4, 4, 4])) +""".format(**reduceops_common_args), +) + +add_docstr( + torch.cumprod, + r""" +cumprod(input, dim, *, dtype=None, out=None) -> Tensor + +Returns the cumulative product of elements of :attr:`input` in the dimension +:attr:`dim`. + +For example, if :attr:`input` is a vector of size N, the result will also be +a vector of size N, with elements. + +.. math:: + y_i = x_1 \times x_2\times x_3\times \dots \times x_i + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + {dtype} + {out} + +Example:: + + >>> a = torch.randn(10) + >>> a + tensor([ 0.6001, 0.2069, -0.1919, 0.9792, 0.6727, 1.0062, 0.4126, + -0.2129, -0.4206, 0.1968]) + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0158, -0.0065, + 0.0014, -0.0006, -0.0001]) + + >>> a[5] = 0.0 + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0000, -0.0000, + 0.0000, -0.0000, -0.0000]) +""".format(**reduceops_common_args), +) + +add_docstr( + torch.cumsum, + r""" +cumsum(input, dim, *, dtype=None, out=None) -> Tensor + +Returns the cumulative sum of elements of :attr:`input` in the dimension +:attr:`dim`. + +For example, if :attr:`input` is a vector of size N, the result will also be +a vector of size N, with elements. + +.. math:: + y_i = x_1 + x_2 + x_3 + \dots + x_i + +Args: + {input} + dim (int): the dimension to do the operation over + +Keyword args: + {dtype} + {out} + +Example:: + + >>> a = torch.randint(1, 20, (10,)) + >>> a + tensor([13, 7, 3, 10, 13, 3, 15, 10, 9, 10]) + >>> torch.cumsum(a, dim=0) + tensor([13, 20, 23, 33, 46, 49, 64, 74, 83, 93]) +""".format(**reduceops_common_args), +) + +add_docstr( + torch.count_nonzero, + r""" +count_nonzero(input, dim=None) -> Tensor + +Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. +If no dim is specified then all non-zeros in the tensor are counted. + +Args: + {input} + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + +Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) +""".format(**reduceops_common_args), +) + +add_docstr( + torch.dequantize, + r""" +dequantize(tensor) -> Tensor + +Returns an fp32 Tensor by dequantizing a quantized Tensor + +Args: + tensor (Tensor): A quantized Tensor + +.. function:: dequantize(tensors) -> sequence of Tensors + :noindex: + +Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors + +Args: + tensors (sequence of Tensors): A list of quantized Tensors +""", +) + +add_docstr( + torch.diag, + r""" +diag(input, diagonal=0, *, out=None) -> Tensor + +- If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. +- If :attr:`input` is a matrix (2-D tensor), then returns a 1-D tensor with + the diagonal elements of :attr:`input`. + +The argument :attr:`diagonal` controls which diagonal to consider: + +- If :attr:`diagonal` = 0, it is the main diagonal. +- If :attr:`diagonal` > 0, it is above the main diagonal. +- If :attr:`diagonal` < 0, it is below the main diagonal. + +Args: + {input} + diagonal (int, optional): the diagonal to consider + +Keyword args: + {out} + +.. seealso:: + + :func:`torch.diagonal` always returns the diagonal of its input. + + :func:`torch.diagflat` always constructs a tensor with diagonal elements + specified by the input. + +Examples: + +Get the square matrix where the input vector is the diagonal:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.5950,-0.0872, 2.3298]) + >>> torch.diag(a) + tensor([[ 0.5950, 0.0000, 0.0000], + [ 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 2.3298]]) + >>> torch.diag(a, 1) + tensor([[ 0.0000, 0.5950, 0.0000, 0.0000], + [ 0.0000, 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 0.0000, 2.3298], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + +Get the k-th diagonal of a given matrix:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-0.4264, 0.0255,-0.1064], + [ 0.8795,-0.2429, 0.1374], + [ 0.1029,-0.6482,-1.6300]]) + >>> torch.diag(a, 0) + tensor([-0.4264,-0.2429,-1.6300]) + >>> torch.diag(a, 1) + tensor([ 0.0255, 0.1374]) +""".format(**common_args), +) + +add_docstr( + torch.diag_embed, + r""" +diag_embed(input, offset=0, dim1=-2, dim2=-1) -> Tensor + +Creates a tensor whose diagonals of certain 2D planes (specified by +:attr:`dim1` and :attr:`dim2`) are filled by :attr:`input`. +To facilitate creating batched diagonal matrices, the 2D planes formed by +the last two dimensions of the returned tensor are chosen by default. + +The argument :attr:`offset` controls which diagonal to consider: + +- If :attr:`offset` = 0, it is the main diagonal. +- If :attr:`offset` > 0, it is above the main diagonal. +- If :attr:`offset` < 0, it is below the main diagonal. + +The size of the new matrix will be calculated to make the specified diagonal +of the size of the last input dimension. +Note that for :attr:`offset` other than :math:`0`, the order of :attr:`dim1` +and :attr:`dim2` matters. Exchanging them is equivalent to changing the +sign of :attr:`offset`. + +Applying :meth:`torch.diagonal` to the output of this function with +the same arguments yields a matrix identical to input. However, +:meth:`torch.diagonal` has different default dimensions, so those +need to be explicitly specified. + +Args: + {input} Must be at least 1-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: -2. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: -1. + +Example:: + + >>> a = torch.randn(2, 3) + >>> torch.diag_embed(a) + tensor([[[ 1.5410, 0.0000, 0.0000], + [ 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -2.1788]], + + [[ 0.5684, 0.0000, 0.0000], + [ 0.0000, -1.0845, 0.0000], + [ 0.0000, 0.0000, -1.3986]]]) + + >>> torch.diag_embed(a, offset=1, dim1=0, dim2=2) + tensor([[[ 0.0000, 1.5410, 0.0000, 0.0000], + [ 0.0000, 0.5684, 0.0000, 0.0000]], + + [[ 0.0000, 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -1.0845, 0.0000]], + + [[ 0.0000, 0.0000, 0.0000, -2.1788], + [ 0.0000, 0.0000, 0.0000, -1.3986]], + + [[ 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.0000]]]) +""".format(**common_args), +) + + +add_docstr( + torch.diagflat, + r""" +diagflat(input, offset=0) -> Tensor + +- If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. +- If :attr:`input` is a tensor with more than one dimension, then returns a + 2-D tensor with diagonal elements equal to a flattened :attr:`input`. + +The argument :attr:`offset` controls which diagonal to consider: + +- If :attr:`offset` = 0, it is the main diagonal. +- If :attr:`offset` > 0, it is above the main diagonal. +- If :attr:`offset` < 0, it is below the main diagonal. + +Args: + {input} + offset (int, optional): the diagonal to consider. Default: 0 (main + diagonal). + +Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([-0.2956, -0.9068, 0.1695]) + >>> torch.diagflat(a) + tensor([[-0.2956, 0.0000, 0.0000], + [ 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.1695]]) + >>> torch.diagflat(a, 1) + tensor([[ 0.0000, -0.2956, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.1695], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + + >>> a = torch.randn(2, 2) + >>> a + tensor([[ 0.2094, -0.3018], + [-0.1516, 1.9342]]) + >>> torch.diagflat(a) + tensor([[ 0.2094, 0.0000, 0.0000, 0.0000], + [ 0.0000, -0.3018, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.1516, 0.0000], + [ 0.0000, 0.0000, 0.0000, 1.9342]]) +""".format(**common_args), +) + +add_docstr( + torch.diagonal, + r""" +diagonal(input, offset=0, dim1=0, dim2=1) -> Tensor + +Returns a partial view of :attr:`input` with the its diagonal elements +with respect to :attr:`dim1` and :attr:`dim2` appended as a dimension +at the end of the shape. + +The argument :attr:`offset` controls which diagonal to consider: + +- If :attr:`offset` = 0, it is the main diagonal. +- If :attr:`offset` > 0, it is above the main diagonal. +- If :attr:`offset` < 0, it is below the main diagonal. + +Applying :meth:`torch.diag_embed` to the output of this function with +the same arguments yields a diagonal matrix with the diagonal entries +of the input. However, :meth:`torch.diag_embed` has different default +dimensions, so those need to be explicitly specified. + +Args: + {input} Must be at least 2-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + +.. note:: To take a batch diagonal, pass in dim1=-2, dim2=-1. + +Examples:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0854, 1.1431, -0.1752], + [ 0.8536, -0.0905, 0.0360], + [ 0.6927, -0.3735, -0.4945]]) + + + >>> torch.diagonal(a) + tensor([-1.0854, -0.0905, -0.4945]) + + + >>> torch.diagonal(a, 1) + tensor([ 1.1431, 0.0360]) + + >>> b = torch.randn(2, 5) + >>> b + tensor([[-1.7948, -1.2731, -0.3181, 2.0200, -1.6745], + [ 1.8262, -1.5049, 0.4114, 1.0704, -1.2607]]) + + >>> torch.diagonal(b, 1, 1, 0) + tensor([1.8262]) + + >>> x = torch.randn(2, 5, 4, 2) + >>> torch.diagonal(x, offset=-1, dim1=1, dim2=2) + tensor([[[-1.2631, 0.3755, -1.5977, -1.8172], + [-1.1065, 1.0401, -0.2235, -0.7938]], + + [[-1.7325, -0.3081, 0.6166, 0.2335], + [ 1.0500, 0.7336, -0.3836, -1.1015]]]) +""".format(**common_args), +) + +add_docstr( + torch.diagonal_scatter, + r""" +diagonal_scatter(input, src, offset=0, dim1=0, dim2=1) -> Tensor + +Embeds the values of the :attr:`src` tensor into :attr:`input` along +the diagonal elements of :attr:`input`, with respect to :attr:`dim1` +and :attr:`dim2`. + +This function returns a tensor with fresh storage; it does not +return a view. + +The argument :attr:`offset` controls which diagonal to consider: + +- If :attr:`offset` = 0, it is the main diagonal. +- If :attr:`offset` > 0, it is above the main diagonal. +- If :attr:`offset` < 0, it is below the main diagonal. + +Args: + {input} Must be at least 2-dimensional. + src (Tensor): the tensor to embed into :attr:`input`. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + +.. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.diagonal(input, offset, dim1, dim2)`` + +Examples:: + + >>> a = torch.zeros(3, 3) + >>> a + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + + >>> torch.diagonal_scatter(a, torch.ones(3), 0) + tensor([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + + >>> torch.diagonal_scatter(a, torch.ones(2), 1) + tensor([[0., 1., 0.], + [0., 0., 1.], + [0., 0., 0.]]) +""".format(**common_args), +) + +add_docstr( + torch.as_strided_scatter, + r""" +as_strided_scatter(input, src, size, stride, storage_offset=None) -> Tensor + +Embeds the values of the :attr:`src` tensor into :attr:`input` along +the elements corresponding to the result of calling +input.as_strided(size, stride, storage_offset). + +This function returns a tensor with fresh storage; it does not +return a view. + +Args: + {input} + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor + +.. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + `torch.as_strided(input, size, stride, storage_offset)` + +Example:: + + >>> a = torch.arange(4).reshape(2, 2) + 1 + >>> a + tensor([[1, 2], + [3, 4]]) + >>> b = torch.zeros(3, 3) + >>> b + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> torch.as_strided_scatter(b, a, (2, 2), (1, 2)) + tensor([[1., 3., 2.], + [4., 0., 0.], + [0., 0., 0.]]) + +""".format(**common_args), +) + +add_docstr( + torch.diff, + r""" +diff(input, n=1, dim=-1, prepend=None, append=None) -> Tensor + +Computes the n-th forward difference along the given dimension. + +The first-order differences are given by `out[i] = input[i + 1] - input[i]`. Higher-order +differences are calculated by using :func:`torch.diff` recursively. + +Args: + input (Tensor): the tensor to compute the differences on + n (int, optional): the number of times to recursively compute the difference + dim (int, optional): the dimension to compute the difference along. + Default is the last dimension. + prepend, append (Tensor, optional): values to prepend or append to + :attr:`input` along :attr:`dim` before computing the difference. + Their dimensions must be equivalent to that of input, and their shapes + must match input's shape except on :attr:`dim`. + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([1, 3, 2]) + >>> torch.diff(a) + tensor([ 2, -1]) + >>> b = torch.tensor([4, 5]) + >>> torch.diff(a, append=b) + tensor([ 2, -1, 2, 1]) + >>> c = torch.tensor([[1, 2, 3], [3, 4, 5]]) + >>> torch.diff(c, dim=0) + tensor([[2, 2, 2]]) + >>> torch.diff(c, dim=1) + tensor([[1, 1], + [1, 1]]) +""".format(**common_args), +) + +add_docstr( + torch.digamma, + r""" +digamma(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.digamma`. +""", +) + +add_docstr( + torch.dist, + r""" +dist(input, other, p=2) -> Tensor + +Returns the p-norm of (:attr:`input` - :attr:`other`) + +The shapes of :attr:`input` and :attr:`other` must be +:ref:`broadcastable `. + +Args: + {input} + other (Tensor): the Right-hand-side input tensor + p (float, optional): the norm to be computed + +Example:: + + >>> x = torch.randn(4) + >>> x + tensor([-1.5393, -0.8675, 0.5916, 1.6321]) + >>> y = torch.randn(4) + >>> y + tensor([ 0.0967, -1.0511, 0.6295, 0.8360]) + >>> torch.dist(x, y, 3.5) + tensor(1.6727) + >>> torch.dist(x, y, 3) + tensor(1.6973) + >>> torch.dist(x, y, 0) + tensor(4.) + >>> torch.dist(x, y, 1) + tensor(2.6537) +""".format(**common_args), +) + +add_docstr( + torch.div, + r""" +div(input, other, *, rounding_mode=None, out=None) -> Tensor + +Divides each element of the input ``input`` by the corresponding element of +:attr:`other`. + +.. math:: + \text{{out}}_i = \frac{{\text{{input}}_i}}{{\text{{other}}_i}} + +.. note:: + By default, this performs a "true" division like Python 3. + See the :attr:`rounding_mode` argument for floor division. + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer, float, and complex inputs. +Always promotes integer types to the default scalar type. + +Args: + input (Tensor): the dividend + other (Tensor or Number): the divisor + +Keyword args: + rounding_mode (str, optional): Type of rounding applied to the result: + + * None - default behavior. Performs no rounding and, if both :attr:`input` and + :attr:`other` are integer types, promotes the inputs to the default scalar type. + Equivalent to true division in Python (the ``/`` operator) and NumPy's ``np.true_divide``. + * ``"trunc"`` - rounds the results of the division towards zero. + Equivalent to C-style integer division. + * ``"floor"`` - rounds the results of the division down. + Equivalent to floor division in Python (the ``//`` operator) and NumPy's ``np.floor_divide``. + + {out} + +Examples:: + + >>> x = torch.tensor([ 0.3810, 1.2774, -0.2972, -0.3719, 0.4637]) + >>> torch.div(x, 0.5) + tensor([ 0.7620, 2.5548, -0.5944, -0.7438, 0.9274]) + + >>> a = torch.tensor([[-0.3711, -1.9353, -0.4605, -0.2917], + ... [ 0.1815, -1.0111, 0.9805, -1.5923], + ... [ 0.1062, 1.4581, 0.7759, -1.2344], + ... [-0.1830, -0.0313, 1.1908, -1.4757]]) + >>> b = torch.tensor([ 0.8032, 0.2930, -0.8113, -0.2308]) + >>> torch.div(a, b) + tensor([[-0.4620, -6.6051, 0.5676, 1.2639], + [ 0.2260, -3.4509, -1.2086, 6.8990], + [ 0.1322, 4.9764, -0.9564, 5.3484], + [-0.2278, -0.1068, -1.4678, 6.3938]]) + + >>> torch.div(a, b, rounding_mode='trunc') + tensor([[-0., -6., 0., 1.], + [ 0., -3., -1., 6.], + [ 0., 4., -0., 5.], + [-0., -0., -1., 6.]]) + + >>> torch.div(a, b, rounding_mode='floor') + tensor([[-1., -7., 0., 1.], + [ 0., -4., -2., 6.], + [ 0., 4., -1., 5.], + [-1., -1., -2., 6.]]) + +""".format(**common_args), +) + +add_docstr( + torch.divide, + r""" +divide(input, other, *, rounding_mode=None, out=None) -> Tensor + +Alias for :func:`torch.div`. +""", +) + +add_docstr( + torch.dot, + r""" +dot(input, tensor, *, out=None) -> Tensor + +Computes the dot product of two 1D tensors. + +.. note:: + + Unlike NumPy's dot, torch.dot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + +Args: + input (Tensor): first tensor in the dot product, must be 1D. + tensor (Tensor): second tensor in the dot product, must be 1D. + +Keyword args: + {out} + +Example:: + + >>> torch.dot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + + >>> t1, t2 = torch.tensor([0, 1]), torch.tensor([2, 3]) + >>> torch.dot(t1, t2) + tensor(3) +""".format(**common_args), +) + +add_docstr( + torch.vdot, + r""" +vdot(input, other, *, out=None) -> Tensor + +Computes the dot product of two 1D vectors along a dimension. + +In symbols, this function computes + +.. math:: + + \sum_{i=1}^n \overline{x_i}y_i. + +where :math:`\overline{x_i}` denotes the conjugate for complex +vectors, and it is the identity for real vectors. + +.. note:: + + Unlike NumPy's vdot, torch.vdot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + +.. seealso:: + + :func:`torch.linalg.vecdot` computes the dot product of two batches of vectors along a dimension. + +Args: + input (Tensor): first tensor in the dot product, must be 1D. Its conjugate is used if it's complex. + other (Tensor): second tensor in the dot product, must be 1D. + +Keyword args: +""" + + rf""" +.. note:: {common_args["out"]} +""" + + r""" + +Example:: + + >>> torch.vdot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + >>> a = torch.tensor((1 +2j, 3 - 1j)) + >>> b = torch.tensor((2 +1j, 4 - 0j)) + >>> torch.vdot(a, b) + tensor([16.+1.j]) + >>> torch.vdot(b, a) + tensor([16.-1.j]) +""", +) + +add_docstr( + torch.eq, + r""" +eq(input, other, *, out=None) -> Tensor + +Computes element-wise equality + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + +Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) +""".format(**common_args), +) + +add_docstr( + torch.equal, + r""" +equal(input, other) -> bool + +``True`` if two tensors have the same size and elements, ``False`` otherwise. + +.. note:: + + Tensors containing NaNs are never equal to each other. Additionally, this function does not + differentiate between the data types of the tensors during comparison. For more thorough tensor checks, + use :meth:`torch.testing.assert_close`. + +Example:: + + >>> torch.equal(torch.tensor([1, 2]), torch.tensor([1, 2])) + True + >>> torch.equal(torch.tensor([3, torch.nan]), torch.tensor([3, torch.nan])) + False + >>> torch.equal(torch.tensor([1, 2, 3], dtype=torch.int32), torch.tensor([1, 2, 3], dtype=torch.float32)) + True +""", +) + +add_docstr( + torch.erf, + r""" +erf(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.erf`. +""", +) + +add_docstr( + torch.erf_, + r""" +erf_(input) -> Tensor + +In-place version of :func:`torch.erf` +""", +) + +add_docstr( + torch.erfc, + r""" +erfc(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.erfc`. +""", +) + +add_docstr( + torch.erfc_, + r""" +erfc_(input) -> Tensor + +In-place version of :func:`torch.erfc` +""", +) + +add_docstr( + torch.erfinv, + r""" +erfinv(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.erfinv`. +""", +) + +add_docstr( + torch.exp, + r""" +exp(input, *, out=None) -> Tensor + +Returns a new tensor with the exponential of the elements +of the input tensor :attr:`input`. + +.. math:: + y_{i} = e^{x_{i}} +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.exp(torch.tensor([0, math.log(2.)])) + tensor([ 1., 2.]) +""".format(**common_args), +) + +add_docstr( + torch.exp_, + r""" +exp_(input) -> Tensor + +In-place version of :func:`torch.exp` +""", +) + +add_docstr( + torch.exp2, + r""" +exp2(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.exp2`. +""", +) + +add_docstr( + torch.exp2_, + r""" +exp2_(input) -> Tensor + +In-place version of :func:`torch.exp2` +""", +) + +add_docstr( + torch.expm1, + r""" +expm1(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.expm1`. +""", +) + +add_docstr( + torch.expm1_, + r""" +expm1_(input) -> Tensor + +In-place version of :func:`torch.expm1` +""", +) + +add_docstr( + torch.eye, + r""" +eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + +Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + +Keyword arguments: + {out} + {dtype} + {layout} + {device} + {requires_grad} + +Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + +Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.floor, + r""" +floor(input, *, out=None) -> Tensor + +Returns a new tensor with the floor of the elements of :attr:`input`, +the largest integer less than or equal to each element. + +For integer inputs, follows the array-api convention of returning a +copy of the input tensor. + +.. math:: + \text{out}_{i} = \left\lfloor \text{input}_{i} \right\rfloor +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.8166, 1.5308, -0.2530, -0.2091]) + >>> torch.floor(a) + tensor([-1., 1., -1., -1.]) +""".format(**common_args), +) + +add_docstr( + torch.floor_, + r""" +floor_(input) -> Tensor + +In-place version of :func:`torch.floor` +""", +) + +add_docstr( + torch.floor_divide, + r""" +floor_divide(input, other, *, out=None) -> Tensor + +.. note:: + + Before PyTorch 1.13 :func:`torch.floor_divide` incorrectly performed + truncation division. To restore the previous behavior use + :func:`torch.div` with ``rounding_mode='trunc'``. + +Computes :attr:`input` divided by :attr:`other`, elementwise, and floors +the result. + +.. math:: + \text{{out}}_i = \text{floor} \left( \frac{{\text{{input}}_i}}{{\text{{other}}_i}} \right) + +""" + + r""" + +Supports broadcasting to a common shape, type promotion, and integer and float inputs. + +Args: + input (Tensor or Number): the dividend + other (Tensor or Number): the divisor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([4.0, 3.0]) + >>> b = torch.tensor([2.0, 2.0]) + >>> torch.floor_divide(a, b) + tensor([2.0, 1.0]) + >>> torch.floor_divide(a, 1.4) + tensor([2.0, 2.0]) +""".format(**common_args), +) + +add_docstr( + torch.fmod, + r""" +fmod(input, other, *, out=None) -> Tensor + +Applies C++'s `std::fmod `_ entrywise. +The result has the same sign as the dividend :attr:`input` and its absolute value +is less than that of :attr:`other`. + +This function may be defined in terms of :func:`torch.div` as + +.. code:: python + + torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer and float inputs. + +.. note:: + + When the divisor is zero, returns ``NaN`` for floating point dtypes + on both CPU and GPU; raises ``RuntimeError`` for integer division by + zero on CPU; Integer division by zero on GPU may return any value. + +.. note:: + + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + +.. seealso:: + + :func:`torch.remainder` which implements Python's modulus operator. + This one is defined using division rounding down the result. + +Args: + input (Tensor): the dividend + other (Tensor or Scalar): the divisor + +Keyword args: + {out} + +Example:: + + >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([-1., -0., -1., 1., 0., 1.]) + >>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) + +""".format(**common_args), +) + +add_docstr( + torch.frac, + r""" +frac(input, *, out=None) -> Tensor + +Computes the fractional portion of each element in :attr:`input`. + +.. math:: + \text{out}_{i} = \text{input}_{i} - \left\lfloor |\text{input}_{i}| \right\rfloor * \operatorname{sgn}(\text{input}_{i}) + +Example:: + + >>> torch.frac(torch.tensor([1, 2.5, -3.2])) + tensor([ 0.0000, 0.5000, -0.2000]) +""", +) + +add_docstr( + torch.frac_, + r""" +frac_(input) -> Tensor + +In-place version of :func:`torch.frac` +""", +) + +add_docstr( + torch.frexp, + r""" +frexp(input, *, out=None) -> (Tensor mantissa, Tensor exponent) + +Decomposes :attr:`input` into mantissa and exponent tensors +such that :math:`\text{input} = \text{mantissa} \times 2^{\text{exponent}}`. + +The range of mantissa is the open interval (-1, 1). + +Supports float inputs. + +Args: + input (Tensor): the input tensor + + +Keyword args: + out (tuple, optional): the output tensors + +Example:: + + >>> x = torch.arange(9.) + >>> mantissa, exponent = torch.frexp(x) + >>> mantissa + tensor([0.0000, 0.5000, 0.5000, 0.7500, 0.5000, 0.6250, 0.7500, 0.8750, 0.5000]) + >>> exponent + tensor([0, 1, 2, 2, 3, 3, 3, 3, 4], dtype=torch.int32) + >>> torch.ldexp(mantissa, exponent) + tensor([0., 1., 2., 3., 4., 5., 6., 7., 8.]) +""", +) + +add_docstr( + torch.from_numpy, + r""" +from_numpy(ndarray) -> Tensor + +Creates a :class:`Tensor` from a :class:`numpy.ndarray`. + +The returned tensor and :attr:`ndarray` share the same memory. Modifications to +the tensor will be reflected in the :attr:`ndarray` and vice versa. The returned +tensor is not resizable. + +It currently accepts :attr:`ndarray` with dtypes of ``numpy.float64``, +``numpy.float32``, ``numpy.float16``, ``numpy.complex64``, ``numpy.complex128``, +``numpy.int64``, ``numpy.int32``, ``numpy.int16``, ``numpy.int8``, ``numpy.uint8``, +and ``bool``. + +.. warning:: + Writing to a tensor created from a read-only NumPy array is not supported and will result in undefined behavior. + +Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.from_numpy(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) +""", +) + +add_docstr( + torch.frombuffer, + r""" +frombuffer(buffer, *, dtype, count=-1, offset=0, requires_grad=False) -> Tensor + +Creates a 1-dimensional :class:`Tensor` from an object that implements +the Python buffer protocol. + +Skips the first :attr:`offset` bytes in the buffer, and interprets the rest of +the raw bytes as a 1-dimensional tensor of type :attr:`dtype` with :attr:`count` +elements. + +Note that either of the following must be true: + +1. :attr:`count` is a positive non-zero number, and the total number of bytes +in the buffer is more than :attr:`offset` plus :attr:`count` times the size +(in bytes) of :attr:`dtype`. + +2. :attr:`count` is negative, and the length (number of bytes) of the buffer +subtracted by the :attr:`offset` is a multiple of the size (in bytes) of +:attr:`dtype`. + +The returned tensor and buffer share the same memory. Modifications to +the tensor will be reflected in the buffer and vice versa. The returned +tensor is not resizable. + +.. note:: + This function increments the reference count for the object that + owns the shared memory. Therefore, such memory will not be deallocated + before the returned tensor goes out of scope. + +.. warning:: + This function's behavior is undefined when passed an object implementing + the buffer protocol whose data is not on the CPU. Doing so is likely to + cause a segmentation fault. + +.. warning:: + This function does not try to infer the :attr:`dtype` (hence, it is not + optional). Passing a different :attr:`dtype` than its source may result + in unexpected behavior. + +Args: + buffer (object): a Python object that exposes the buffer interface. + +Keyword args: + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + count (int, optional): the number of desired elements to be read. + If negative, all the elements (until the end of the buffer) will be + read. Default: -1. + offset (int, optional): the number of bytes to skip at the start of + the buffer. Default: 0. + {requires_grad} + +Example:: + + >>> import array + >>> a = array.array('i', [1, 2, 3]) + >>> t = torch.frombuffer(a, dtype=torch.int32) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> # Interprets the signed char bytes as 32-bit integers. + >>> # Each 4 signed char elements will be interpreted as + >>> # 1 signed 32-bit integer. + >>> import array + >>> a = array.array('b', [-1, 0, 0, 0]) + >>> torch.frombuffer(a, dtype=torch.int32) + tensor([255], dtype=torch.int32) +""".format(**factory_common_args), +) + +add_docstr( + torch.from_file, + r""" +from_file(filename, shared=None, size=0, *, dtype=None, layout=None, device=None, pin_memory=False) + +Creates a CPU tensor with a storage backed by a memory-mapped file. + +If ``shared`` is True, then memory is shared between processes. All changes are written to the file. +If ``shared`` is False, then changes to the tensor do not affect the file. + +``size`` is the number of elements in the Tensor. If ``shared`` is ``False``, then the file must contain +at least ``size * sizeof(dtype)`` bytes. If ``shared`` is ``True`` the file will be created if needed. + +.. note:: + Only CPU tensors can be mapped to files. + +.. note:: + For now, tensors with storages backed by a memory-mapped file cannot be created in pinned memory. + + +Args: + filename (str): file name to map + shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the + underlying `mmap(2) call `_) + size (int): number of elements in the tensor + +Keyword args: + {dtype} + {layout} + {device} + {pin_memory} + +Example:: + + >>> t = torch.randn(2, 5, dtype=torch.float64) + >>> t.numpy().tofile('storage.pt') + >>> t_mapped = torch.from_file('storage.pt', shared=False, size=10, dtype=torch.float64) + """.format(**factory_common_args), +) + +add_docstr( + torch.flatten, + r""" +flatten(input, start_dim=0, end_dim=-1) -> Tensor + +Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` +are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. +The order of elements in :attr:`input` is unchanged. + +Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, +or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can +be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the +flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + +.. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + +Args: + {input} + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + +Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) +""".format(**common_args), +) + +add_docstr( + torch.unflatten, + r""" +unflatten(input, dim, sizes) -> Tensor + +Expands a dimension of the input tensor over multiple dimensions. + +.. seealso:: + + :func:`torch.flatten` the inverse of this function. It coalesces several dimensions into one. + +Args: + {input} + dim (int): Dimension to be unflattened, specified as an index into + ``input.shape``. + sizes (Tuple[int]): New shape of the unflattened dimension. + One of its elements can be `-1` in which case the corresponding output + dimension is inferred. Otherwise, the product of ``sizes`` *must* + equal ``input.shape[dim]``. + +Returns: + A View of input with the specified dimension unflattened. + +Examples:: + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (2, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (-1, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(5, 12, 3), -2, (2, 2, 3, 1, 1)).shape + torch.Size([5, 2, 2, 3, 1, 1, 3]) +""".format(**common_args), +) + +add_docstr( + torch.gather, + r""" +gather(input, dim, index, *, sparse_grad=False, out=None) -> Tensor + +Gathers values along an axis specified by `dim`. + +For a 3-D tensor the output is specified by:: + + out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 + out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 + out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 + +:attr:`input` and :attr:`index` must have the same number of dimensions. +It is also required that ``index.size(d) <= input.size(d)`` for all +dimensions ``d != dim``. :attr:`out` will have the same shape as :attr:`index`. +Note that ``input`` and ``index`` do not broadcast against each other. +When :attr:`index` is empty, we always return an empty output with the same shape +without further error checking. + +Args: + input (Tensor): the source tensor + dim (int): the axis along which to index + index (LongTensor): the indices of elements to gather + +Keyword arguments: + sparse_grad (bool, optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse tensor. + out (Tensor, optional): the destination tensor + +Example:: + + >>> t = torch.tensor([[1, 2], [3, 4]]) + >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])) + tensor([[ 1, 1], + [ 4, 3]]) +""", +) + + +add_docstr( + torch.gcd, + r""" +gcd(input, other, *, out=None) -> Tensor + +Computes the element-wise greatest common divisor (GCD) of :attr:`input` and :attr:`other`. + +Both :attr:`input` and :attr:`other` must have integer types. + +.. note:: + This defines :math:`gcd(0, 0) = 0`. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.gcd(a, b) + tensor([1, 2, 5]) + >>> c = torch.tensor([3]) + >>> torch.gcd(a, c) + tensor([1, 1, 3]) +""".format(**common_args), +) + +add_docstr( + torch.gcd_, + r""" +gcd_(input, other) -> Tensor + +In-place version of :func:`torch.gcd` +""", +) + +add_docstr( + torch.ge, + r""" +ge(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} \geq \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is greater than or equal to :attr:`other` and False elsewhere + +Example:: + + >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, True], [False, True]]) +""".format(**common_args), +) + +add_docstr( + torch.greater_equal, + r""" +greater_equal(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.ge`. +""", +) + +add_docstr( + torch.gradient, + r""" +gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + +Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in +one or more dimensions using the `second-order accurate central differences method +`_ and +either first or second order estimates at the boundaries. + +The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not +specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates +to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional +:attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and +:math:`g(1, 2, 3)\ == input[1, 2, 3]`. + +When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. +This is detailed in the "Keyword Arguments" section below. + +The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is +accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be +improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative +is estimated using `Taylor's theorem with remainder `_. +Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring +it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + +.. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + +Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + +.. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + +.. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + +The value of each partial derivative at the boundary points is computed differently. See edge_order below. + +Args: + input (``Tensor``): the tensor that represents the values of the function + +Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + +Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + +""", +) + +add_docstr( + torch.geqrf, + r""" +geqrf(input, *, out=None) -> (Tensor, Tensor) + +This is a low-level function for calling LAPACK's geqrf directly. This function +returns a namedtuple (a, tau) as defined in `LAPACK documentation for geqrf`_ . + +Computes a QR decomposition of :attr:`input`. +Both `Q` and `R` matrices are stored in the same output tensor `a`. +The elements of `R` are stored on and above the diagonal. +Elementary reflectors (or Householder vectors) implicitly defining matrix `Q` +are stored below the diagonal. +The results of this function can be used together with :func:`torch.linalg.householder_product` +to obtain the `Q` matrix or +with :func:`torch.ormqr`, which uses an implicit representation of the `Q` matrix, +for an efficient matrix-matrix multiplication. + +See `LAPACK documentation for geqrf`_ for further details. + +.. note:: + See also :func:`torch.linalg.qr`, which computes Q and R matrices, and :func:`torch.linalg.lstsq` + with the ``driver="gels"`` option for a function that can solve matrix equations using a QR decomposition. + +Args: + input (Tensor): the input matrix + +Keyword args: + out (tuple, optional): the output tuple of (Tensor, Tensor). Ignored if `None`. Default: `None`. + +.. _LAPACK documentation for geqrf: + http://www.netlib.org/lapack/explore-html/df/dc5/group__variants_g_ecomputational_ga3766ea903391b5cf9008132f7440ec7b.html + +""", +) + +add_docstr( + torch.inner, + r""" +inner(input, other, *, out=None) -> Tensor + +Computes the dot product for 1D tensors. For higher dimensions, sums the product +of elements from :attr:`input` and :attr:`other` along their last dimension. + +.. note:: + + If either :attr:`input` or :attr:`other` is a scalar, the result is equivalent + to `torch.mul(input, other)`. + + If both :attr:`input` and :attr:`other` are non-scalars, the size of their last + dimension must match and the result is equivalent to `torch.tensordot(input, + other, dims=([-1], [-1]))` + +Args: + input (Tensor): First input tensor + other (Tensor): Second input tensor + +Keyword args: + out (Tensor, optional): Optional output tensor to write result into. The output + shape is `input.shape[:-1] + other.shape[:-1]`. + +Example:: + + # Dot product + >>> torch.inner(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 1])) + tensor(7) + + # Multidimensional input tensors + >>> a = torch.randn(2, 3) + >>> a + tensor([[0.8173, 1.0874, 1.1784], + [0.3279, 0.1234, 2.7894]]) + >>> b = torch.randn(2, 4, 3) + >>> b + tensor([[[-0.4682, -0.7159, 0.1506], + [ 0.4034, -0.3657, 1.0387], + [ 0.9892, -0.6684, 0.1774], + [ 0.9482, 1.3261, 0.3917]], + + [[ 0.4537, 0.7493, 1.1724], + [ 0.2291, 0.5749, -0.2267], + [-0.7920, 0.3607, -0.3701], + [ 1.3666, -0.5850, -1.7242]]]) + >>> torch.inner(a, b) + tensor([[[-0.9837, 1.1560, 0.2907, 2.6785], + [ 2.5671, 0.5452, -0.6912, -1.5509]], + + [[ 0.1782, 2.9843, 0.7366, 1.5672], + [ 3.5115, -0.4864, -1.2476, -4.4337]]]) + + # Scalar input + >>> torch.inner(a, torch.tensor(2)) + tensor([[1.6347, 2.1748, 2.3567], + [0.6558, 0.2469, 5.5787]]) +""", +) + +add_docstr( + torch.outer, + r""" +outer(input, vec2, *, out=None) -> Tensor + +Outer product of :attr:`input` and :attr:`vec2`. +If :attr:`input` is a vector of size :math:`n` and :attr:`vec2` is a vector of +size :math:`m`, then :attr:`out` must be a matrix of size :math:`(n \times m)`. + +.. note:: This function does not :ref:`broadcast `. + +Args: + input (Tensor): 1-D input vector + vec2 (Tensor): 1-D input vector + +Keyword args: + out (Tensor, optional): optional output matrix + +Example:: + + >>> v1 = torch.arange(1., 5.) + >>> v2 = torch.arange(1., 4.) + >>> torch.outer(v1, v2) + tensor([[ 1., 2., 3.], + [ 2., 4., 6.], + [ 3., 6., 9.], + [ 4., 8., 12.]]) +""", +) + +add_docstr( + torch.ger, + r""" +ger(input, vec2, *, out=None) -> Tensor + +Alias of :func:`torch.outer`. + +.. warning:: + This function is deprecated and will be removed in a future PyTorch release. + Use :func:`torch.outer` instead. +""", +) + +add_docstr( + torch.get_default_dtype, + r""" +get_default_dtype() -> torch.dtype + +Get the current default floating point :class:`torch.dtype`. + +Example:: + + >>> torch.get_default_dtype() # initial default for floating point is torch.float32 + torch.float32 + >>> torch.set_default_dtype(torch.float64) + >>> torch.get_default_dtype() # default is now changed to torch.float64 + torch.float64 + +""", +) + +add_docstr( + torch.get_num_threads, + r""" +get_num_threads() -> int + +Returns the number of threads used for parallelizing CPU operations +""", +) + +add_docstr( + torch.get_num_interop_threads, + r""" +get_num_interop_threads() -> int + +Returns the number of threads used for inter-op parallelism on CPU +(e.g. in JIT interpreter) +""", +) + +add_docstr( + torch.gt, + r""" +gt(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} > \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + +Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) +""".format(**common_args), +) + +add_docstr( + torch.greater, + r""" +greater(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.gt`. +""", +) + +add_docstr( + torch.hash_tensor, + r""" +hash_tensor(input, *, mode=0) -> Tensor + +Returns a hash of all elements in the :attr:`input` tensor. + +Currently only mode=0 (reduction via xor) is supported. The output will always +be of type ``torch.uint64``. The elements of ``input`` are upcasted to their +64 bit float / integer equivalent and bitcasted to ``torch.uint64`` before +reduction via xor. + +Args: + {input} + +Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.1918, -1.1813, 0.3373]]) + >>> torch.hash_tensor(a) + tensor(13822780554648485888, dtype=torch.uint64) + +.. function:: hash_tensor(input, dim, *, keepdim=False, mode=0) -> Tensor + :noindex: + +Returns the hash of each row of the :attr:`input` tensor in the given +dimension :attr:`dim` given by mode. If :attr:`dim` is a list of dimensions, +reduce over all of them. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + +Example:: + + >>> a = torch.randn(2, 4) + >>> a + tensor([[ 0.1317, -0.5554, -1.4724, -1.1391], + [ 0.0778, -0.6070, 0.6375, 0.1798]]) + >>> torch.hash_tensor(a, 1) + tensor([9233691267014066176, 9255993250844508160], dtype=torch.uint64) +""".format(**multi_dim_common), +) + +add_docstr( + torch.histc, + r""" +histc(input, bins=100, min=0, max=0, *, out=None) -> Tensor + +Computes the histogram of a tensor. + +The elements are sorted into equal width bins between :attr:`min` and +:attr:`max`. If :attr:`min` and :attr:`max` are both zero, the minimum and +maximum values of the data are used. + +Elements lower than min and higher than max and ``NaN`` elements are ignored. + +Args: + {input} + bins (int): number of histogram bins + min (Scalar): lower end of the range (inclusive) + max (Scalar): upper end of the range (inclusive) + +Keyword args: + {out} + +Returns: + Tensor: Histogram represented as a tensor + +Example:: + + >>> torch.histc(torch.tensor([1., 2, 1]), bins=4, min=0, max=3) + tensor([ 0., 2., 1., 0.]) +""".format(**common_args), +) + +add_docstr( + torch.histogram, + r""" +histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + +Computes a histogram of the values in a tensor. + +:attr:`bins` can be an integer or a 1D tensor. + +If :attr:`bins` is an int, it specifies the number of equal-width bins. +By default, the lower and upper range of the bins is determined by the +minimum and maximum elements of the input tensor. The :attr:`range` +argument can be provided to specify a range for the bins. + +If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges +including the rightmost edge. It should contain at least 2 elements +and its elements should be increasing. + +Args: + {input} + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + +Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + {out} (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + +Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + +Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) +""".format(**common_args), +) + +add_docstr( + torch.histogramdd, + r""" +histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + +Computes a multi-dimensional histogram of the values in a tensor. + +Interprets the elements of an input tensor whose innermost dimension has size N +as a collection of N-dimensional points. Maps each of the points into a set of +N-dimensional bins and returns the number of points (or total weight) in each bin. + +:attr:`input` must be a tensor with at least 2 dimensions. +If input has shape (M, N), each of its M rows defines a point in N-dimensional space. +If input has three or more dimensions, all but the last dimension are flattened. + +Each dimension is independently associated with its own strictly increasing sequence +of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D +tensors. Alternatively, bin edges may be constructed automatically by passing a +sequence of integers specifying the number of equal-width bins in each dimension. + +For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + +:attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + +If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences +of bin edges. Each 1D tensor should contain a strictly increasing sequence with at +least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying +the left and right edges of all bins. Every bin is inclusive of its left edge. Only +the rightmost bin is inclusive of its right edge. + +If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins +in each dimension. By default, the leftmost and rightmost bin edges in each dimension +are determined by the minimum and maximum elements of the input tensor in the +corresponding dimension. The :attr:`range` argument can be provided to manually +specify the leftmost and rightmost bin edges in each dimension. + +If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + +.. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + +Args: + {input} + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. +Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. +Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + +Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + +""".format(**common_args), +) +# TODO: Fix via https://github.com/pytorch/pytorch/issues/75798 +torch.histogramdd.__module__ = "torch" + +add_docstr( + torch.hypot, + r""" +hypot(input, other, *, out=None) -> Tensor + +Given the legs of a right triangle, return its hypotenuse. + +.. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}^{2} + \text{other}_{i}^{2}} + +The shapes of ``input`` and ``other`` must be +:ref:`broadcastable `. +""" + + r""" +Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.hypot(torch.tensor([4.0]), torch.tensor([3.0, 4.0, 5.0])) + tensor([5.0000, 5.6569, 6.4031]) + +""".format(**common_args), +) + +add_docstr( + torch.i0, + r""" +i0(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.i0`. +""", +) + +add_docstr( + torch.i0_, + r""" +i0_(input) -> Tensor + +In-place version of :func:`torch.i0` +""", +) + +add_docstr( + torch.igamma, + r""" +igamma(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.special.gammainc`. +""", +) + +add_docstr( + torch.igammac, + r""" +igammac(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.special.gammaincc`. +""", +) + +add_docstr( + torch.index_select, + r""" +index_select(input, dim, index, *, out=None) -> Tensor + +Returns a new tensor which indexes the :attr:`input` tensor along dimension +:attr:`dim` using the entries in :attr:`index`. + +The returned tensor has the same number of dimensions as the original tensor +(:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length +of :attr:`index`; other dimensions have the same size as in the original tensor. + +.. note:: The returned tensor does **not** use the same storage as the original + tensor. If :attr:`out` has a different shape than expected, we + silently change it to the correct shape, reallocating the underlying + storage if necessary. + +Args: + {input} + dim (int): the dimension in which we index + index (IntTensor or LongTensor): the 1-D tensor containing the indices to index + +Keyword args: + {out} + +Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-0.4664, 0.2647, -0.1228, -1.1068], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> indices = torch.tensor([0, 2]) + >>> torch.index_select(x, 0, indices) + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> torch.index_select(x, 1, indices) + tensor([[ 0.1427, -0.5414], + [-0.4664, -0.1228], + [-1.1734, 0.7230]]) +""".format(**common_args), +) + +add_docstr( + torch.inverse, + r""" +inverse(input, *, out=None) -> Tensor + +Alias for :func:`torch.linalg.inv` +""", +) + +add_docstr( + torch.isin, + r""" +isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + +Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns +a boolean tensor of the same shape as :attr:`elements` that is True for elements +in :attr:`test_elements` and False otherwise. + +.. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + +Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + +Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + +Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) +""", +) + +add_docstr( + torch.isinf, + r""" +isinf(input) -> Tensor + +Tests if each element of :attr:`input` is infinite +(positive or negative infinity) or not. + +.. note:: + Complex values are infinite when their real or imaginary part is + infinite. + +Args: + {input} + +Returns: + A boolean tensor that is True where :attr:`input` is infinite and False elsewhere + +Example:: + + >>> torch.isinf(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([False, True, False, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.isposinf, + r""" +isposinf(input, *, out=None) -> Tensor +Tests if each element of :attr:`input` is positive infinity or not. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isposinf(a) + tensor([False, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.isneginf, + r""" +isneginf(input, *, out=None) -> Tensor +Tests if each element of :attr:`input` is negative infinity or not. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isneginf(a) + tensor([ True, False, False]) +""".format(**common_args), +) + +add_docstr( + torch.isclose, + r""" +isclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + +Returns a new tensor with boolean elements representing if each element of +:attr:`input` is "close" to the corresponding element of :attr:`other`. +Closeness is defined as: + +.. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{rtol} \times \lvert \text{other}_i \rvert + \texttt{atol} +""" + + r""" + +where :attr:`input` and :attr:`other` are finite. Where :attr:`input` +and/or :attr:`other` are nonfinite they are close if and only if +they are equal, with NaNs being considered equal to each other when +:attr:`equal_nan` is True. + +Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + rtol (float, optional): relative tolerance. Default: 1e-05 + atol (float, optional): absolute tolerance. Default: 1e-08 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + +Examples:: + + >>> torch.isclose(torch.tensor((1., 2, 3)), torch.tensor((1 + 1e-10, 3, 4))) + tensor([ True, False, False]) + >>> torch.isclose(torch.tensor((float('inf'), 4)), torch.tensor((float('inf'), 6)), rtol=.5) + tensor([True, True]) +""", +) + +add_docstr( + torch.isfinite, + r""" +isfinite(input) -> Tensor + +Returns a new tensor with boolean elements representing if each element is `finite` or not. + +Real values are finite when they are not NaN, negative infinity, or infinity. +Complex values are finite when both their real and imaginary parts are finite. + +Args: + {input} + +Returns: + A boolean tensor that is True where :attr:`input` is finite and False elsewhere + +Example:: + + >>> torch.isfinite(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([True, False, True, False, False]) +""".format(**common_args), +) + +add_docstr( + torch.isnan, + r""" +isnan(input) -> Tensor + +Returns a new tensor with boolean elements representing if each element of :attr:`input` +is NaN or not. Complex values are considered NaN when either their real +and/or imaginary part is NaN. + +Arguments: + {input} + +Returns: + A boolean tensor that is True where :attr:`input` is NaN and False elsewhere + +Example:: + + >>> torch.isnan(torch.tensor([1, float('nan'), 2])) + tensor([False, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.isreal, + r""" +isreal(input) -> Tensor + +Returns a new tensor with boolean elements representing if each element of :attr:`input` is real-valued or not. +All real-valued types are considered real. Complex values are considered real when their imaginary part is 0. + +Arguments: + {input} + +Returns: + A boolean tensor that is True where :attr:`input` is real and False elsewhere + +Example:: + + >>> torch.isreal(torch.tensor([1, 1+1j, 2+0j])) + tensor([True, False, True]) +""".format(**common_args), +) + +add_docstr( + torch.is_floating_point, + r""" +is_floating_point(input: Tensor) -> bool + +Returns True if the data type of :attr:`input` is a floating point data type i.e., +one of ``torch.float64``, ``torch.float32``, ``torch.float16``, and ``torch.bfloat16``. + +Args: + {input} + +Example:: + + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0])) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.complex64)) + False +""".format(**common_args), +) + +add_docstr( + torch.is_complex, + r""" +is_complex(input: Tensor) -> bool + +Returns True if the data type of :attr:`input` is a complex data type i.e., +one of ``torch.complex64``, and ``torch.complex128``. + +Args: + {input} + +Example:: + + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex64)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex128)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_complex(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + False +""".format(**common_args), +) + +add_docstr( + torch.is_grad_enabled, + r""" +is_grad_enabled() -> (bool) + +Returns True if grad mode is currently enabled. +""".format(**common_args), +) + +add_docstr( + torch.is_inference_mode_enabled, + r""" +is_inference_mode_enabled() -> (bool) + +Returns True if inference mode is currently enabled. +""".format(**common_args), +) + +add_docstr( + torch.is_inference, + r""" +is_inference(input) -> (bool) + +Returns True if :attr:`input` is an inference tensor. + +A non-view tensor is an inference tensor if and only if it was +allocated during inference mode. A view tensor is an inference +tensor if and only if the tensor it is a view of is an inference tensor. + +For details on inference mode please see +`Inference Mode `_. + +Args: + {input} +""".format(**common_args), +) + +add_docstr( + torch.is_conj, + r""" +is_conj(input) -> (bool) + +Returns True if the :attr:`input` is a conjugated tensor, i.e. its conjugate bit is set to `True`. + +Args: + {input} +""".format(**common_args), +) + +add_docstr( + torch.is_nonzero, + r""" +is_nonzero(input) -> (bool) + +Returns True if the :attr:`input` is a single element tensor which is not equal to zero +after type conversions. +i.e. not equal to ``torch.tensor([0.])`` or ``torch.tensor([0])`` or +``torch.tensor([False])``. +Throws a ``RuntimeError`` if ``torch.numel() != 1`` (even in case +of sparse tensors). + +Args: + {input} + +Examples:: + + >>> torch.is_nonzero(torch.tensor([0.])) + False + >>> torch.is_nonzero(torch.tensor([1.5])) + True + >>> torch.is_nonzero(torch.tensor([False])) + False + >>> torch.is_nonzero(torch.tensor([3])) + True + >>> torch.is_nonzero(torch.tensor([1, 3, 5])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with more than one value is ambiguous + >>> torch.is_nonzero(torch.tensor([])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with no values is ambiguous +""".format(**common_args), +) + +add_docstr( + torch.kron, + r""" +kron(input, other, *, out=None) -> Tensor + +Computes the Kronecker product, denoted by :math:`\otimes`, of :attr:`input` and :attr:`other`. + +If :attr:`input` is a :math:`(a_0 \times a_1 \times \dots \times a_n)` tensor and :attr:`other` is a +:math:`(b_0 \times b_1 \times \dots \times b_n)` tensor, the result will be a +:math:`(a_0*b_0 \times a_1*b_1 \times \dots \times a_n*b_n)` tensor with the following entries: + +.. math:: + (\text{input} \otimes \text{other})_{k_0, k_1, \dots, k_n} = + \text{input}_{i_0, i_1, \dots, i_n} * \text{other}_{j_0, j_1, \dots, j_n}, + +where :math:`k_t = i_t * b_t + j_t` for :math:`0 \leq t \leq n`. +If one tensor has fewer dimensions than the other it is unsqueezed until it has the same number of dimensions. + +Supports real-valued and complex-valued inputs. + +.. note:: + This function generalizes the typical definition of the Kronecker product for two matrices to two tensors, + as described above. When :attr:`input` is a :math:`(m \times n)` matrix and :attr:`other` is a + :math:`(p \times q)` matrix, the result will be a :math:`(p*m \times q*n)` block matrix: + + .. math:: + \mathbf{A} \otimes \mathbf{B}=\begin{bmatrix} + a_{11} \mathbf{B} & \cdots & a_{1 n} \mathbf{B} \\ + \vdots & \ddots & \vdots \\ + a_{m 1} \mathbf{B} & \cdots & a_{m n} \mathbf{B} \end{bmatrix} + + where :attr:`input` is :math:`\mathbf{A}` and :attr:`other` is :math:`\mathbf{B}`. + +Arguments: + input (Tensor) + other (Tensor) + +Keyword args: + out (Tensor, optional): The output tensor. Ignored if ``None``. Default: ``None`` + +Examples:: + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.ones(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 1., 0., 0.], + [1., 1., 0., 0.], + [0., 0., 1., 1.], + [0., 0., 1., 1.]]) + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.arange(1, 5).reshape(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 2., 0., 0.], + [3., 4., 0., 0.], + [0., 0., 1., 2.], + [0., 0., 3., 4.]]) +""", +) + +add_docstr( + torch.kthvalue, + r""" +kthvalue(input, k, dim=None, keepdim=False, *, out=None) -> (Tensor, LongTensor) + +Returns a namedtuple ``(values, indices)`` where ``values`` is the :attr:`k` th +smallest element of each row of the :attr:`input` tensor in the given dimension +:attr:`dim`. And ``indices`` is the index location of each element found. + +If :attr:`dim` is not given, the last dimension of the `input` is chosen. + +If :attr:`keepdim` is ``True``, both the :attr:`values` and :attr:`indices` tensors +are the same size as :attr:`input`, except in the dimension :attr:`dim` where +they are of size 1. Otherwise, :attr:`dim` is squeezed +(see :func:`torch.squeeze`), resulting in both the :attr:`values` and +:attr:`indices` tensors having 1 fewer dimension than the :attr:`input` tensor. + +.. note:: + When :attr:`input` is a CUDA tensor and there are multiple valid + :attr:`k` th values, this function may nondeterministically return + :attr:`indices` for any of them. + +Args: + {input} + k (int): k for the k-th smallest element + dim (int, optional): the dimension to find the kth value along + {opt_keepdim} + +Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) + can be optionally given to be used as output buffers + +Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.kthvalue(x, 4) + torch.return_types.kthvalue(values=tensor(4.), indices=tensor(3)) + + >>> x=torch.arange(1.,7.).resize_(2,3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.]]) + >>> torch.kthvalue(x, 2, 0, True) + torch.return_types.kthvalue(values=tensor([[4., 5., 6.]]), indices=tensor([[1, 1, 1]])) +""".format(**single_dim_common), +) + +add_docstr( + torch.lcm, + r""" +lcm(input, other, *, out=None) -> Tensor + +Computes the element-wise least common multiple (LCM) of :attr:`input` and :attr:`other`. + +Both :attr:`input` and :attr:`other` must have integer types. + +.. note:: + This defines :math:`lcm(0, 0) = 0` and :math:`lcm(0, a) = 0`. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.lcm(a, b) + tensor([15, 20, 15]) + >>> c = torch.tensor([3]) + >>> torch.lcm(a, c) + tensor([15, 30, 15]) +""".format(**common_args), +) + +add_docstr( + torch.lcm_, + r""" +lcm_(input, other) -> Tensor + +In-place version of :func:`torch.lcm` +""", +) + +add_docstr( + torch.ldexp, + r""" +ldexp(input, other, *, out=None) -> Tensor + +Multiplies :attr:`input` by 2 ** :attr:`other`. + +.. math:: + \text{{out}}_i = \text{{input}}_i * 2^\text{{other}}_i +""" + + r""" + +Typically this function is used to construct floating point numbers by multiplying +mantissas in :attr:`input` with integral powers of two created from the exponents +in :attr:`other`. + +Args: + {input} + other (Tensor): a tensor of exponents, typically integers. + +Keyword args: + {out} + +Example:: + + >>> torch.ldexp(torch.tensor([1.]), torch.tensor([1])) + tensor([2.]) + >>> torch.ldexp(torch.tensor([1.0]), torch.tensor([1, 2, 3, 4])) + tensor([ 2., 4., 8., 16.]) + + +""".format(**common_args), +) + +add_docstr( + torch.ldexp_, + r""" +ldexp_(input, other) -> Tensor + +In-place version of :func:`torch.ldexp` +""", +) + +add_docstr( + torch.le, + r""" +le(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} \leq \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or Scalar): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is less than or equal to + :attr:`other` and False elsewhere + +Example:: + + >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, False], [True, True]]) +""".format(**common_args), +) + +add_docstr( + torch.less_equal, + r""" +less_equal(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.le`. +""", +) + +add_docstr( + torch.lerp, + r""" +lerp(input, end, weight, *, out=None) + +Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based +on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor. + +.. math:: + \text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i) +""" + + r""" +The shapes of :attr:`start` and :attr:`end` must be +:ref:`broadcastable `. If :attr:`weight` is a tensor, then +the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable `. + +Args: + input (Tensor): the tensor with the starting points + end (Tensor): the tensor with the ending points + weight (float or tensor): the weight for the interpolation formula + +Keyword args: + {out} + +Example:: + + >>> start = torch.arange(1., 5.) + >>> end = torch.empty(4).fill_(10) + >>> start + tensor([ 1., 2., 3., 4.]) + >>> end + tensor([ 10., 10., 10., 10.]) + >>> torch.lerp(start, end, 0.5) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + >>> torch.lerp(start, end, torch.full_like(start, 0.5)) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) +""".format(**common_args), +) + +add_docstr( + torch.lgamma, + r""" +lgamma(input, *, out=None) -> Tensor + +Computes the natural logarithm of the absolute value of the gamma function on :attr:`input`. + +.. math:: + \text{out}_{i} = \ln |\Gamma(\text{input}_{i})| +""" + + """ +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.arange(0.5, 2, 0.5) + >>> torch.lgamma(a) + tensor([ 0.5724, 0.0000, -0.1208]) +""".format(**common_args), +) + +add_docstr( + torch.linspace, + r""" +linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly +spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + +.. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) +""" + + """ + +From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + +Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + +Keyword arguments: + {out} + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + {layout} + {device} + {requires_grad} + + +Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) +""".format(**factory_common_args), +) + +add_docstr( + torch.log, + r""" +log(input, *, out=None) -> Tensor + +Returns a new tensor with the natural logarithm of the elements +of :attr:`input`. + +.. math:: + y_{i} = \log_{e} (x_{i}) +""" + + r""" + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(5) * 5 + >>> a + tensor([4.7767, 4.3234, 1.2156, 0.2411, 4.5739]) + >>> torch.log(a) + tensor([ 1.5637, 1.4640, 0.1952, -1.4226, 1.5204]) +""".format(**common_args), +) + +add_docstr( + torch.log_, + r""" +log_(input) -> Tensor + +In-place version of :func:`torch.log` +""", +) + +add_docstr( + torch.log10, + r""" +log10(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the logarithm to the base 10 of the elements +of :attr:`input`. + +.. math:: + y_{i} = \log_{10} (x_{i}) +""" + + r""" + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.5224, 0.9354, 0.7257, 0.1301, 0.2251]) + + + >>> torch.log10(a) + tensor([-0.2820, -0.0290, -0.1392, -0.8857, -0.6476]) + +""".format(**common_args), +) + +add_docstr( + torch.log10_, + r""" +log10_(input) -> Tensor + +In-place version of :func:`torch.log10` +""", +) + +add_docstr( + torch.log1p, + r""" +log1p(input, *, out=None) -> Tensor + +Returns a new tensor with the natural logarithm of (1 + :attr:`input`). + +.. math:: + y_i = \log_{e} (x_i + 1) +""" + + r""" +.. note:: This function is more accurate than :func:`torch.log` for small + values of :attr:`input` + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.0090, -0.9923, 1.0249, -0.5372, 0.2492]) + >>> torch.log1p(a) + tensor([ nan, -4.8653, 0.7055, -0.7705, 0.2225]) +""".format(**common_args), +) + +add_docstr( + torch.log1p_, + r""" +log1p_(input) -> Tensor + +In-place version of :func:`torch.log1p` +""", +) + +add_docstr( + torch.log2, + r""" +log2(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the logarithm to the base 2 of the elements +of :attr:`input`. + +.. math:: + y_{i} = \log_{2} (x_{i}) +""" + + r""" + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.8419, 0.8003, 0.9971, 0.5287, 0.0490]) + + + >>> torch.log2(a) + tensor([-0.2483, -0.3213, -0.0042, -0.9196, -4.3504]) + +""".format(**common_args), +) + +add_docstr( + torch.log2_, + r""" +log2_(input) -> Tensor + +In-place version of :func:`torch.log2` +""", +) + +add_docstr( + torch.logaddexp, + r""" +logaddexp(input, other, *, out=None) -> Tensor + +Logarithm of the sum of exponentiations of the inputs. + +Calculates pointwise :math:`\log\left(e^x + e^y\right)`. This function is useful +in statistics where the calculated probabilities of events may be so small as to +exceed the range of normal floating point numbers. In such cases the logarithm +of the calculated probability is stored. This function allows adding +probabilities stored in such a fashion. + +This op should be disambiguated with :func:`torch.logsumexp` which performs a +reduction on a single tensor. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword arguments: + {out} + +Example:: + + >>> torch.logaddexp(torch.tensor([-1.0]), torch.tensor([-1.0, -2, -3])) + tensor([-0.3069, -0.6867, -0.8731]) + >>> torch.logaddexp(torch.tensor([-100.0, -200, -300]), torch.tensor([-1.0, -2, -3])) + tensor([-1., -2., -3.]) + >>> torch.logaddexp(torch.tensor([1.0, 2000, 30000]), torch.tensor([-1.0, -2, -3])) + tensor([1.1269e+00, 2.0000e+03, 3.0000e+04]) +""".format(**common_args), +) + +add_docstr( + torch.logaddexp2, + r""" +logaddexp2(input, other, *, out=None) -> Tensor + +Logarithm of the sum of exponentiations of the inputs in base-2. + +Calculates pointwise :math:`\log_2\left(2^x + 2^y\right)`. See +:func:`torch.logaddexp` for more details. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword arguments: + {out} +""".format(**common_args), +) + +add_docstr( + torch.xlogy, + r""" +xlogy(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.special.xlogy`. +""", +) + +add_docstr( + torch.xlogy_, + r""" +xlogy_(input, other) -> Tensor + +In-place version of :func:`torch.xlogy` +""", +) + +add_docstr( + torch.logical_and, + r""" +logical_and(input, other, *, out=None) -> Tensor + +Computes the element-wise logical AND of the given input tensors. Zeros are treated as ``False`` and nonzeros are +treated as ``True``. + +Args: + {input} + other (Tensor): the tensor to compute AND with + +Keyword args: + {out} + +Example:: + + >>> torch.logical_and(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, False]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_and(a, b) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b.double()) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b) + tensor([False, False, True, False]) + >>> torch.logical_and(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([False, False, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.logical_not, + r""" +logical_not(input, *, out=None) -> Tensor + +Computes the element-wise logical NOT of the given input tensor. If not specified, the output tensor will have the bool +dtype. If the input tensor is not a bool tensor, zeros are treated as ``False`` and non-zeros are treated as ``True``. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> torch.logical_not(torch.tensor([True, False])) + tensor([False, True]) + >>> torch.logical_not(torch.tensor([0, 1, -10], dtype=torch.int8)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1.5, -10.], dtype=torch.double)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1., -10.], dtype=torch.double), out=torch.empty(3, dtype=torch.int16)) + tensor([1, 0, 0], dtype=torch.int16) +""".format(**common_args), +) + +add_docstr( + torch.logical_or, + r""" +logical_or(input, other, *, out=None) -> Tensor + +Computes the element-wise logical OR of the given input tensors. Zeros are treated as ``False`` and nonzeros are +treated as ``True``. + +Args: + {input} + other (Tensor): the tensor to compute OR with + +Keyword args: + {out} + +Example:: + + >>> torch.logical_or(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_or(a, b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b.double()) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, True, False]) +""".format(**common_args), +) + +add_docstr( + torch.logical_xor, + r""" +logical_xor(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + +Computes the element-wise logical XOR of the given input tensors. Zeros are treated as ``False`` and nonzeros are +treated as ``True``. + +Args: + {input} + other (Tensor): the tensor to compute XOR with + +Keyword args: + {out} + +Example:: + + >>> torch.logical_xor(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([False, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_xor(a, b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b.double()) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, False, False]) +""".format(**common_args), +) + +add_docstr( + torch.logspace, + """ +logspace(start, end, steps, base=10.0, *, \ + out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" + +Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly +spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to +:math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale +with base :attr:`base`. That is, the values are: + +.. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) +""" + + """ + + +From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + +Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + +Keyword arguments: + {out} + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) +""".format(**factory_common_args), +) + +add_docstr( + torch.logsumexp, + r""" +logsumexp(input, dim, keepdim=False, *, out=None) + +Returns the log of summed exponentials of each row of the :attr:`input` +tensor in the given dimension :attr:`dim`. The computation is numerically +stabilized. + +For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{{logsumexp}}(x)_{{i}} = \log \sum_j \exp(x_{{ij}}) + +{keepdim_details} + +Args: + {input} + {dim} + {opt_keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(3, 3) + >>> torch.logsumexp(a, 1) + tensor([1.4907, 1.0593, 1.5696]) + >>> torch.dist(torch.logsumexp(a, 1), torch.log(torch.sum(torch.exp(a), 1))) + tensor(1.6859e-07) +""".format(**multi_dim_common), +) + +add_docstr( + torch.lt, + r""" +lt(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} < \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is less than :attr:`other` and False elsewhere + +Example:: + + >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, False], [True, False]]) +""".format(**common_args), +) + +add_docstr( + torch.lu_unpack, + r""" +lu_unpack(LU_data, LU_pivots, unpack_data=True, unpack_pivots=True, *, out=None) -> (Tensor, Tensor, Tensor) + +Unpacks the LU decomposition returned by :func:`~linalg.lu_factor` into the `P, L, U` matrices. + +.. seealso:: + + :func:`~linalg.lu` returns the matrices from the LU decomposition. Its gradient formula is more efficient + than that of doing :func:`~linalg.lu_factor` followed by :func:`~linalg.lu_unpack`. + +Args: + LU_data (Tensor): the packed LU factorization data + LU_pivots (Tensor): the packed LU factorization pivots + unpack_data (bool): flag indicating if the data should be unpacked. + If ``False``, then the returned ``L`` and ``U`` are empty tensors. + Default: ``True`` + unpack_pivots (bool): flag indicating if the pivots should be unpacked into a permutation matrix ``P``. + If ``False``, then the returned ``P`` is an empty tensor. + Default: ``True`` + +Keyword args: + out (tuple, optional): output tuple of three tensors. Ignored if `None`. + +Returns: + A namedtuple ``(P, L, U)`` + +Examples:: + + >>> A = torch.randn(2, 3, 3) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # We can recover A from the factorization + >>> A_ = P @ L @ U + >>> torch.allclose(A, A_) + True + + >>> # LU factorization of a rectangular matrix: + >>> A = torch.randn(2, 3, 2) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # P, L, U are the same as returned by linalg.lu + >>> P_, L_, U_ = torch.linalg.lu(A) + >>> torch.allclose(P, P_) and torch.allclose(L, L_) and torch.allclose(U, U_) + True + +""".format(**common_args), +) + +add_docstr( + torch.less, + r""" +less(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.lt`. +""", +) + +add_docstr( + torch.lu_solve, + r""" +lu_solve(b, LU_data, LU_pivots, *, out=None) -> Tensor + +Returns the LU solve of the linear system :math:`Ax = b` using the partially pivoted +LU factorization of A from :func:`~linalg.lu_factor`. + +This function supports ``float``, ``double``, ``cfloat`` and ``cdouble`` dtypes for :attr:`input`. + +.. warning:: + + :func:`torch.lu_solve` is deprecated in favor of :func:`torch.linalg.lu_solve`. + :func:`torch.lu_solve` will be removed in a future PyTorch release. + ``X = torch.lu_solve(B, LU, pivots)`` should be replaced with + + .. code:: python + + X = linalg.lu_solve(LU, pivots, B) + +Arguments: + b (Tensor): the RHS tensor of size :math:`(*, m, k)`, where :math:`*` + is zero or more batch dimensions. + LU_data (Tensor): the pivoted LU factorization of A from :meth:`~linalg.lu_factor` of size :math:`(*, m, m)`, + where :math:`*` is zero or more batch dimensions. + LU_pivots (IntTensor): the pivots of the LU factorization from :meth:`~linalg.lu_factor` of size :math:`(*, m)`, + where :math:`*` is zero or more batch dimensions. + The batch dimensions of :attr:`LU_pivots` must be equal to the batch dimensions of + :attr:`LU_data`. + +Keyword args: + {out} + +Example:: + + >>> A = torch.randn(2, 3, 3) + >>> b = torch.randn(2, 3, 1) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> x = torch.lu_solve(b, LU, pivots) + >>> torch.dist(A @ x, b) + tensor(1.00000e-07 * + 2.8312) +""".format(**common_args), +) + +add_docstr( + torch.masked_select, + r""" +masked_select(input, mask, *, out=None) -> Tensor + +Returns a new 1-D tensor which indexes the :attr:`input` tensor according to +the boolean mask :attr:`mask` which is a `BoolTensor`. + +The shapes of the :attr:`mask` tensor and the :attr:`input` tensor don't need +to match, but they must be :ref:`broadcastable `. + +.. note:: The returned tensor does **not** use the same storage + as the original tensor + +Args: + {input} + mask (BoolTensor): the tensor containing the binary mask to index with + +Keyword args: + {out} + +Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.3552, -2.3825, -0.8297, 0.3477], + [-1.2035, 1.2252, 0.5002, 0.6248], + [ 0.1307, -2.0608, 0.1244, 2.0139]]) + >>> mask = x.ge(0.5) + >>> mask + tensor([[False, False, False, False], + [False, True, True, True], + [False, False, False, True]]) + >>> torch.masked_select(x, mask) + tensor([ 1.2252, 0.5002, 0.6248, 2.0139]) +""".format(**common_args), +) + +add_docstr( + torch.matrix_power, + r""" +matrix_power(input, n, *, out=None) -> Tensor + +Alias for :func:`torch.linalg.matrix_power` +""", +) + +add_docstr( + torch.matrix_exp, + r""" +matrix_exp(A) -> Tensor + +Alias for :func:`torch.linalg.matrix_exp`. +""", +) + +add_docstr( + torch.max, + r""" +max(input, *, out=None) -> Tensor + +Returns the maximum value of all elements in the ``input`` tensor. + +.. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + +.. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + +Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum +value of each row of the :attr:`input` tensor in the given dimension +:attr:`dim`. And ``indices`` is the index location of each maximum value found +(argmax). + +If ``keepdim`` is ``True``, the output tensors are of the same size +as ``input`` except in the dimension ``dim`` where they are of size 1. +Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting +in the output tensors having 1 fewer dimension than ``input``. + +.. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + +Args: + {input} + {opt_dim_without_none} + {opt_keepdim} + +Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + +.. function:: max(input, other, *, out=None) -> Tensor + :noindex: + +See :func:`torch.maximum`. + +""".format(**single_dim_common), +) + +add_docstr( + torch.maximum, + r""" +maximum(input, other, *, out=None) -> Tensor + +Computes the element-wise maximum of :attr:`input` and :attr:`other`. + +.. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`maximum` is not supported for tensors with complex dtypes. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.maximum(a, b) + tensor([3, 2, 4]) +""".format(**common_args), +) + +add_docstr( + torch.fmax, + r""" +fmax(input, other, *, out=None) -> Tensor + +Computes the element-wise maximum of :attr:`input` and :attr:`other`. + +This is like :func:`torch.maximum` except it handles NaNs differently: +if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the maximum. +Only if both elements are NaN is NaN propagated. + +This function is a wrapper around C++'s ``std::fmax`` and is similar to NumPy's ``fmax`` function. + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer and floating-point inputs. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([9.7, float('nan'), 3.1, float('nan')]) + >>> b = torch.tensor([-2.2, 0.5, float('nan'), float('nan')]) + >>> torch.fmax(a, b) + tensor([9.7000, 0.5000, 3.1000, nan]) +""".format(**common_args), +) + +add_docstr( + torch.amax, + r""" +amax(input, dim=None, keepdim=False, *, out=None) -> Tensor + +Returns the maximum value of each slice of the :attr:`input` tensor in the given +dimension(s) :attr:`dim`. + +.. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.8177, 1.4878, -0.2491, 0.9130], + [-0.7158, 1.1775, 2.0992, 0.4817], + [-0.0053, 0.0164, -1.3738, -0.0507], + [ 1.9700, 1.1106, -1.0318, -1.0816]]) + >>> torch.amax(a, 1) + tensor([1.4878, 2.0992, 0.0164, 1.9700]) +""".format(**multi_dim_common), +) + +add_docstr( + torch.argmax, + r""" +argmax(input) -> LongTensor + +Returns the indices of the maximum value of all elements in the :attr:`input` tensor. + +This is the second value returned by :meth:`torch.max`. See its +documentation for the exact semantics of this method. + +.. note:: If there are multiple maximal values then the indices of the first maximal value are returned. + +Args: + {input} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a) + tensor(0) + +.. function:: argmax(input, dim, keepdim=False) -> LongTensor + :noindex: + +Returns the indices of the maximum values of a tensor across a dimension. + +This is the second value returned by :meth:`torch.max`. See its +documentation for the exact semantics of this method. + +Args: + {input} + {opt_dim} If ``None``, the argmax of the flattened input is returned. + {opt_keepdim} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a, dim=1) + tensor([ 0, 2, 0, 1]) +""".format(**single_dim_common), +) + +add_docstr( + torch.argwhere, + r""" +argwhere(input) -> Tensor + +Returns a tensor containing the indices of all non-zero elements of +:attr:`input`. Each row in the result contains the indices of a non-zero +element in :attr:`input`. The result is sorted lexicographically, with +the last index changing the fastest (C-style). + +If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor +:attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of +non-zero elements in the :attr:`input` tensor. + +.. note:: + This function is similar to NumPy's `argwhere`. + + When :attr:`input` is on CUDA, this function causes host-device synchronization. + +Args: + {input} + +Example:: + + >>> t = torch.tensor([1, 0, 1]) + >>> torch.argwhere(t) + tensor([[0], + [2]]) + >>> t = torch.tensor([[1, 0, 1], [0, 1, 1]]) + >>> torch.argwhere(t) + tensor([[0, 0], + [0, 2], + [1, 1], + [1, 2]]) +""", +) + +add_docstr( + torch.mean, + r""" +mean(input, *, dtype=None) -> Tensor + +.. note:: + If the `input` tensor is empty, ``torch.mean()`` returns ``nan``. + This behavior is consistent with NumPy and follows the definition + that the mean over an empty set is undefined. + + +Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + +Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + +.. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + +Returns the mean value of each row of the :attr:`input` tensor in the given +dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, +reduce over all of them. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {dtype} + {out} + +.. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) +""".format(**multi_dim_common), +) + +add_docstr( + torch.nanmean, + r""" +nanmean(input, dim=None, keepdim=False, *, dtype=None, out=None) -> Tensor + +Computes the mean of all `non-NaN` elements along the specified dimensions. +Input must be floating point or complex. + +This function is identical to :func:`torch.mean` when there are no `NaN` values +in the :attr:`input` tensor. In the presence of `NaN`, :func:`torch.mean` will +propagate the `NaN` to the output whereas :func:`torch.nanmean` will ignore the +`NaN` values (`torch.nanmean(a)` is equivalent to `torch.mean(a[~a.isnan()])`). + +{keepdim_details} + +Args: + input (Tensor): the input tensor, either of floating point or complex dtype + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {dtype} + {out} + +.. seealso:: + + :func:`torch.mean` computes the mean value, propagating `NaN`. + +Example:: + + >>> x = torch.tensor([[torch.nan, 1, 2], [1, 2, 3]]) + >>> x.mean() + tensor(nan) + >>> x.nanmean() + tensor(1.8000) + >>> x.mean(dim=0) + tensor([ nan, 1.5000, 2.5000]) + >>> x.nanmean(dim=0) + tensor([1.0000, 1.5000, 2.5000]) + + # If all elements in the reduced dimensions are NaN then the result is NaN + >>> torch.tensor([torch.nan]).nanmean() + tensor(nan) +""".format(**multi_dim_common), +) + +add_docstr( + torch.median, + r""" +median(input) -> Tensor + +Returns the median of the values in :attr:`input`. + +.. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + +.. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + +Args: + {input} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + +.. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + +Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` +in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + +By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + +If :attr:`keepdim` is ``True``, the output tensors are of the same size +as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in +the outputs tensor having 1 fewer dimension than :attr:`input`. + +.. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + +.. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + +Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) +""".format(**single_dim_common), +) + +add_docstr( + torch.nanmedian, + r""" +nanmedian(input) -> Tensor + +Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + +This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. +When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, +while this function will return the median of the non-``NaN`` elements in :attr:`input`. +If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + +Args: + {input} + +Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + +.. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + +Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` +in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values +found in the dimension :attr:`dim`. + +This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has +one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the +median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + +Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) +""".format(**single_dim_common), +) + +add_docstr( + torch.quantile, + r""" +quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + +Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + +To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location +of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with +indices ``i`` and ``j`` in the sorted order, result is computed according to the given +:attr:`interpolation` method as follows: + +- ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. +- ``lower``: ``a``. +- ``higher``: ``b``. +- ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). +- ``midpoint``: ``(a + b) / 2``. + +If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size +equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + +.. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + +Args: + {input} + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + {opt_dim} + {opt_keepdim} + +Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + {out} + +Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) +""".format(**single_dim_common), +) + +add_docstr( + torch.nanquantile, + r""" +nanquantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + +This is a variant of :func:`torch.quantile` that "ignores" ``NaN`` values, +computing the quantiles :attr:`q` as if ``NaN`` values in :attr:`input` did +not exist. If all values in a reduced row are ``NaN`` then the quantiles for +that reduction will be ``NaN``. See the documentation for :func:`torch.quantile`. + +Args: + {input} + q (float or Tensor): a scalar or 1D tensor of quantile values in the range [0, 1] + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword arguments: + interpolation (str): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + {out} + +Example:: + + >>> t = torch.tensor([float('nan'), 1, 2]) + >>> t.quantile(0.5) + tensor(nan) + >>> t.nanquantile(0.5) + tensor(1.5000) + >>> t = torch.tensor([[float('nan'), float('nan')], [1, 2]]) + >>> t + tensor([[nan, nan], + [1., 2.]]) + >>> t.nanquantile(0.5, dim=0) + tensor([1., 2.]) + >>> t.nanquantile(0.5, dim=1) + tensor([ nan, 1.5000]) +""".format(**single_dim_common), +) + +add_docstr( + torch.min, + r""" +min(input, *, out=None) -> Tensor + +Returns the minimum value of all elements in the :attr:`input` tensor. + +.. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + +.. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + +Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum +value of each row of the :attr:`input` tensor in the given dimension +:attr:`dim`. And ``indices`` is the index location of each minimum value found +(argmin). + +If :attr:`keepdim` is ``True``, the output tensors are of the same size as +:attr:`input` except in the dimension :attr:`dim` where they are of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in +the output tensors having 1 fewer dimension than :attr:`input`. + +.. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + +Args: + {input} + {opt_dim_without_none} + {opt_keepdim} + +Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + +.. function:: min(input, other, *, out=None) -> Tensor + :noindex: + +See :func:`torch.minimum`. +""".format(**single_dim_common), +) + +add_docstr( + torch.minimum, + r""" +minimum(input, other, *, out=None) -> Tensor + +Computes the element-wise minimum of :attr:`input` and :attr:`other`. + +.. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`minimum` is not supported for tensors with complex dtypes. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.minimum(a, b) + tensor([1, 0, -1]) +""".format(**common_args), +) + +add_docstr( + torch.fmin, + r""" +fmin(input, other, *, out=None) -> Tensor + +Computes the element-wise minimum of :attr:`input` and :attr:`other`. + +This is like :func:`torch.minimum` except it handles NaNs differently: +if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the minimum. +Only if both elements are NaN is NaN propagated. + +This function is a wrapper around C++'s ``std::fmin`` and is similar to NumPy's ``fmin`` function. + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer and floating-point inputs. + +Args: + {input} + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([2.2, float('nan'), 2.1, float('nan')]) + >>> b = torch.tensor([-9.3, 0.1, float('nan'), float('nan')]) + >>> torch.fmin(a, b) + tensor([-9.3000, 0.1000, 2.1000, nan]) +""".format(**common_args), +) + +add_docstr( + torch.amin, + r""" +amin(input, dim=None, keepdim=False, *, out=None) -> Tensor + +Returns the minimum value of each slice of the :attr:`input` tensor in the given +dimension(s) :attr:`dim`. + +.. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.6451, -0.4866, 0.2987, -1.3312], + [-0.5744, 1.2980, 1.8397, -0.2713], + [ 0.9128, 0.9214, -1.7268, -0.2995], + [ 0.9023, 0.4853, 0.9075, -1.6165]]) + >>> torch.amin(a, 1) + tensor([-1.3312, -0.5744, -1.7268, -1.6165]) +""".format(**multi_dim_common), +) + +add_docstr( + torch.aminmax, + r""" +aminmax(input, *, dim=None, keepdim=False, out=None) -> (Tensor min, Tensor max) + +Computes the minimum and maximum values of the :attr:`input` tensor. + +Args: + input (Tensor): + The input tensor + +Keyword Args: + dim (Optional[int]): + The dimension along which to compute the values. If `None`, + computes the values over the entire :attr:`input` tensor. + Default is `None`. + keepdim (bool): + If `True`, the reduced dimensions will be kept in the output + tensor as dimensions with size 1 for broadcasting, otherwise + they will be removed, as if calling (:func:`torch.squeeze`). + Default is `False`. + out (Optional[Tuple[Tensor, Tensor]]): + Optional tensors on which to write the result. Must have the same + shape and dtype as the expected output. + Default is `None`. + +Returns: + A named tuple `(min, max)` containing the minimum and maximum values. + +Raises: + RuntimeError + If any of the dimensions to compute the values over has size 0. + +.. note:: + NaN values are propagated to the output if at least one value is NaN. + +.. seealso:: + :func:`torch.amin` computes just the minimum value + :func:`torch.amax` computes just the maximum value + +Example:: + + >>> torch.aminmax(torch.tensor([1, -3, 5])) + torch.return_types.aminmax( + min=tensor(-3), + max=tensor(5)) + + >>> # aminmax propagates NaNs + >>> torch.aminmax(torch.tensor([1, -3, 5, torch.nan])) + torch.return_types.aminmax( + min=tensor(nan), + max=tensor(nan)) + + >>> t = torch.arange(10).view(2, 5) + >>> t + tensor([[0, 1, 2, 3, 4], + [5, 6, 7, 8, 9]]) + >>> t.aminmax(dim=0, keepdim=True) + torch.return_types.aminmax( + min=tensor([[0, 1, 2, 3, 4]]), + max=tensor([[5, 6, 7, 8, 9]])) +""", +) + +add_docstr( + torch.argmin, + r""" +argmin(input, dim=None, keepdim=False) -> LongTensor + +Returns the indices of the minimum value(s) of the flattened tensor or along a dimension + +This is the second value returned by :meth:`torch.min`. See its +documentation for the exact semantics of this method. + +.. note:: If there are multiple minimal values then the indices of the first minimal value are returned. + +Args: + {input} + {opt_dim} If ``None``, the argmin of the flattened input is returned. + {opt_keepdim} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.1139, 0.2254, -0.1381, 0.3687], + [ 1.0100, -1.1975, -0.0102, -0.4732], + [-0.9240, 0.1207, -0.7506, -1.0213], + [ 1.7809, -1.2960, 0.9384, 0.1438]]) + >>> torch.argmin(a) + tensor(13) + >>> torch.argmin(a, dim=1) + tensor([ 2, 1, 3, 1]) + >>> torch.argmin(a, dim=1, keepdim=True) + tensor([[2], + [1], + [3], + [1]]) +""".format(**single_dim_common), +) + +add_docstr( + torch.mm, + r""" +mm(input, mat2, *, out=None) -> Tensor + +Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`. + +If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`mat2` is a +:math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor. + +.. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + +Supports strided and sparse 2-D tensors as inputs, autograd with +respect to strided inputs. + +This operation has support for arguments with :ref:`sparse layouts`. +If :attr:`out` is provided its layout will be used. Otherwise, the result +layout will be deduced from that of :attr:`input`. + +{sparse_beta_warning} + +{tf32_note} + +{rocm_fp16_note} + +Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + +Keyword args: + {out} + +Example:: + + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.mm(mat1, mat2) + tensor([[ 0.4851, 0.5037, -0.3633], + [-0.0760, -3.6705, 2.4784]]) + +.. function:: mm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + +Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + +Keyword args: + {out} +""".format(**common_args, **tf32_notes, **rocm_fp16_notes, **sparse_support_notes), +) + +add_docstr( + torch.hspmm, + r""" +hspmm(mat1, mat2, *, out=None) -> Tensor + +Performs a matrix multiplication of a :ref:`sparse COO matrix +` :attr:`mat1` and a strided matrix :attr:`mat2`. The +result is a (1 + 1)-dimensional :ref:`hybrid COO matrix +`. + +Args: + mat1 (Tensor): the first sparse matrix to be matrix multiplied + mat2 (Tensor): the second strided matrix to be matrix multiplied + +Keyword args: + {out} +""".format(**common_args), +) + +add_docstr( + torch.matmul, + r""" +matmul(input, other, *, out=None) -> Tensor + +Matrix product of two tensors. + +The behavior depends on the dimensionality of the tensors as follows: + +- If both tensors are 1-dimensional, the dot product (scalar) is returned. +- If both arguments are 2-dimensional, the matrix-matrix product is returned. +- If the first argument is 1-dimensional and the second argument is 2-dimensional, + a 1 is prepended to its dimension for the purpose of the matrix multiply. + After the matrix multiply, the prepended dimension is removed. +- If the first argument is 2-dimensional and the second argument is 1-dimensional, + the matrix-vector product is returned. +- If both arguments are at least 1-dimensional and at least one argument is + N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first + argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the + batched matrix multiply and removed after. If the second argument is 1-dimensional, a + 1 is appended to its dimension for the purpose of the batched matrix multiply and removed after. + + The first N-2 dimensions of each argument, the batch dimensions, are + :ref:`broadcast ` (and thus must be broadcastable). + The last 2, the matrix dimensions, are handled as in the matrix-matrix product. + + For example, if :attr:`input` is a + :math:`(j \times 1 \times n \times m)` tensor and :attr:`other` is a :math:`(k \times m \times p)` + tensor, the batch dimensions are :math:`(j \times 1)` and :math:`(k)`, + and the matrix dimensions are :math:`(n \times m)` and :math:`(m \times p)`. + :attr:`out` will be a :math:`(j \times k \times n \times p)` tensor. + +This operation has support for arguments with :ref:`sparse layouts`. In particular the +matrix-matrix (both arguments 2-dimensional) supports sparse arguments with the same restrictions +as :func:`torch.mm` + +{sparse_beta_warning} + +{tf32_note} + +{rocm_fp16_note} + +.. note:: + + The 1-dimensional dot product version of this function does not support an :attr:`out` parameter. + +Arguments: + input (Tensor): the first tensor to be multiplied + other (Tensor): the second tensor to be multiplied + +Keyword args: + {out} + +Example:: + + >>> # vector x vector + >>> tensor1 = torch.randn(3) + >>> tensor2 = torch.randn(3) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([]) + >>> # matrix x vector + >>> tensor1 = torch.randn(3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([3]) + >>> # batched matrix x broadcasted vector + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3]) + >>> # batched matrix x batched matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(10, 4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + >>> # batched matrix x broadcasted matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + +""".format(**common_args, **tf32_notes, **rocm_fp16_notes, **sparse_support_notes), +) + +add_docstr( + torch.mode, + r""" +mode(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + +Returns a namedtuple ``(values, indices)`` where ``values`` is the mode +value of each row of the :attr:`input` tensor in the given dimension +:attr:`dim`, i.e. a value which appears most often +in that row, and ``indices`` is the index location of each mode value found. + +By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + +If :attr:`keepdim` is ``True``, the output tensors are of the same size as +:attr:`input` except in the dimension :attr:`dim` where they are of size 1. +Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting +in the output tensors having 1 fewer dimension than :attr:`input`. + +Args: + {input} + {opt_dim} + {opt_keepdim} + +Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + +Example:: + + >>> b = torch.tensor([[0, 0, 0, 2, 0, 0, 2], + ... [0, 3, 0, 0, 2, 0, 1], + ... [2, 2, 2, 0, 0, 0, 3], + ... [2, 2, 3, 0, 1, 1, 0], + ... [1, 1, 0, 0, 2, 0, 2]]) + >>> torch.mode(b, 0) + torch.return_types.mode( + values=tensor([0, 2, 0, 0, 0, 0, 2]), + indices=tensor([1, 3, 4, 4, 2, 4, 4])) +""".format(**single_dim_common), +) + +add_docstr( + torch.mul, + r""" +mul(input, other, *, out=None) -> Tensor + +Multiplies :attr:`input` by :attr:`other`. + + +.. math:: + \text{out}_i = \text{input}_i \times \text{other}_i +""" + + r""" + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer, float, and complex inputs. + +Args: + {input} + other (Tensor or Number): the tensor or number to multiply input by. + +Keyword args: + {out} + +Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.2015, -0.4255, 2.6087]) + >>> torch.mul(a, 100) + tensor([ 20.1494, -42.5491, 260.8663]) + + >>> b = torch.randn(4, 1) + >>> b + tensor([[ 1.1207], + [-0.3137], + [ 0.0700], + [ 0.8378]]) + >>> c = torch.randn(1, 4) + >>> c + tensor([[ 0.5146, 0.1216, -0.5244, 2.2382]]) + >>> torch.mul(b, c) + tensor([[ 0.5767, 0.1363, -0.5877, 2.5083], + [-0.1614, -0.0382, 0.1645, -0.7021], + [ 0.0360, 0.0085, -0.0367, 0.1567], + [ 0.4312, 0.1019, -0.4394, 1.8753]]) +""".format(**common_args), +) + +add_docstr( + torch.multiply, + r""" +multiply(input, other, *, out=None) + +Alias for :func:`torch.mul`. +""", +) + +add_docstr( + torch.multinomial, + r""" +multinomial(input, num_samples, replacement=False, *, generator=None, out=None) -> LongTensor + +Returns a tensor where each row contains :attr:`num_samples` indices sampled +from the multinomial (a stricter definition would be multivariate, +refer to :class:`torch.distributions.multinomial.Multinomial` for more details) +probability distribution located in the corresponding row +of tensor :attr:`input`. + +.. note:: + The rows of :attr:`input` do not need to sum to one (in which case we use + the values as weights), but must be non-negative, finite and have + a non-zero sum. + +Indices are ordered from left to right according to when each was sampled +(first samples are placed in first column). + +If :attr:`input` is a vector, :attr:`out` is a vector of size :attr:`num_samples`. + +If :attr:`input` is a matrix with `m` rows, :attr:`out` is an matrix of shape +:math:`(m \times \text{{num\_samples}})`. + +If replacement is ``True``, samples are drawn with replacement. + +If not, they are drawn without replacement, which means that when a +sample index is drawn for a row, it cannot be drawn again for that row. + +.. note:: + When drawn without replacement, :attr:`num_samples` must be lower than + number of non-zero elements in :attr:`input` (or the min number of non-zero + elements in each row of :attr:`input` if it is a matrix). + +Args: + input (Tensor): the input tensor containing probabilities + num_samples (int): number of samples to draw + replacement (bool, optional): whether to draw with replacement or not + +Keyword args: + {generator} + {out} + +Example:: + + >>> weights = torch.tensor([0, 10, 3, 0], dtype=torch.float) # create a tensor of weights + >>> torch.multinomial(weights, 2) + tensor([1, 2]) + >>> torch.multinomial(weights, 5) # ERROR! + RuntimeError: cannot sample n_sample > prob_dist.size(-1) samples without replacement + >>> torch.multinomial(weights, 4, replacement=True) + tensor([ 2, 1, 1, 1]) +""".format(**common_args), +) + +add_docstr( + torch.mv, + r""" +mv(input, vec, *, out=None) -> Tensor + +Performs a matrix-vector product of the matrix :attr:`input` and the vector +:attr:`vec`. + +If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of +size :math:`m`, :attr:`out` will be 1-D of size :math:`n`. + +.. note:: This function does not :ref:`broadcast `. + +Args: + input (Tensor): matrix to be multiplied + vec (Tensor): vector to be multiplied + +Keyword args: + {out} + +Example:: + + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.mv(mat, vec) + tensor([ 1.0404, -0.6361]) +""".format(**common_args), +) + +add_docstr( + torch.mvlgamma, + r""" +mvlgamma(input, p, *, out=None) -> Tensor + +Alias for :func:`torch.special.multigammaln`. +""", +) + +add_docstr( + torch.movedim, + r""" +movedim(input, source, destination) -> Tensor + +Moves the dimension(s) of :attr:`input` at the position(s) in :attr:`source` +to the position(s) in :attr:`destination`. + +Other dimensions of :attr:`input` that are not explicitly moved remain in +their original order and appear at the positions not specified in :attr:`destination`. + +Args: + {input} + source (int or tuple of ints): Original positions of the dims to move. These must be unique. + destination (int or tuple of ints): Destination positions for each of the original dims. These must also be unique. + +Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.movedim(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.movedim(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.movedim(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.movedim(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) +""".format(**common_args), +) + +add_docstr( + torch.moveaxis, + r""" +moveaxis(input, source, destination) -> Tensor + +Alias for :func:`torch.movedim`. + +This function is equivalent to NumPy's moveaxis function. + +Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.moveaxis(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.moveaxis(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.moveaxis(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.moveaxis(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) +""".format(**common_args), +) + +add_docstr( + torch.swapdims, + r""" +swapdims(input, dim0, dim1) -> Tensor + +Alias for :func:`torch.transpose`. + +This function is equivalent to NumPy's swapaxes function. + +Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapdims(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapdims(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) +""".format(**common_args), +) + +add_docstr( + torch.swapaxes, + r""" +swapaxes(input, axis0, axis1) -> Tensor + +Alias for :func:`torch.transpose`. + +This function is equivalent to NumPy's swapaxes function. + +Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) +""".format(**common_args), +) + +add_docstr( + torch.narrow, + r""" +narrow(input, dim, start, length) -> Tensor + +Returns a new tensor that is a narrowed version of :attr:`input` tensor. The +dimension :attr:`dim` is input from :attr:`start` to ``start + length``. The +returned tensor and :attr:`input` tensor share the same underlying storage. + +Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int or Tensor): index of the element to start the narrowed dimension + from. Can be negative, which means indexing from the end of `dim`. If + `Tensor`, it must be an 0-dim integral `Tensor` (bools not allowed) + length (int): length of the narrowed dimension, must be weakly positive + +Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> torch.narrow(x, -1, torch.tensor(-1), 1) + tensor([[3], + [6], + [9]]) +""", +) + +add_docstr( + torch.narrow_copy, + r""" +narrow_copy(input, dim, start, length, *, out=None) -> Tensor + +Same as :meth:`Tensor.narrow` except this returns a copy rather +than shared storage. This is primarily for sparse tensors, which +do not have a shared-storage narrow method. + +Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int): index of the element to start the narrowed dimension from. Can + be negative, which means indexing from the end of `dim` + length (int): length of the narrowed dimension, must be weakly positive + +Keyword args: + {out} + +Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow_copy(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow_copy(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> s = torch.arange(16).reshape(2, 2, 2, 2).to_sparse(2) + >>> torch.narrow_copy(s, 0, 0, 1) + tensor(indices=tensor([[0, 0], + [0, 1]]), + values=tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]), + size=(1, 2, 2, 2), nnz=2, layout=torch.sparse_coo) + +.. seealso:: + + :func:`torch.narrow` for a non copy variant + +""".format(**common_args), +) + +add_docstr( + torch.nan_to_num, + r""" +nan_to_num(input, nan=0.0, posinf=None, neginf=None, *, out=None) -> Tensor + +Replaces :literal:`NaN`, positive infinity, and negative infinity values in :attr:`input` +with the values specified by :attr:`nan`, :attr:`posinf`, and :attr:`neginf`, respectively. +By default, :literal:`NaN`\ s are replaced with zero, positive infinity is replaced with the +greatest finite value representable by :attr:`input`'s dtype, and negative infinity +is replaced with the least finite value representable by :attr:`input`'s dtype. + +Args: + {input} + nan (Number, optional): the value to replace :literal:`NaN`\s with. Default is zero. + posinf (Number, optional): if a Number, the value to replace positive infinity values with. + If None, positive infinity values are replaced with the greatest finite value representable by :attr:`input`'s dtype. + Default is None. + neginf (Number, optional): if a Number, the value to replace negative infinity values with. + If None, negative infinity values are replaced with the lowest finite value representable by :attr:`input`'s dtype. + Default is None. + +Keyword args: + {out} + +Example:: + + >>> x = torch.tensor([float('nan'), float('inf'), -float('inf'), 3.14]) + >>> torch.nan_to_num(x) + tensor([ 0.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0) + tensor([ 2.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0, posinf=1.0) + tensor([ 2.0000e+00, 1.0000e+00, -3.4028e+38, 3.1400e+00]) + +""".format(**common_args), +) + +add_docstr( + torch.nan_to_num_, + r""" +nan_to_num_(input, nan=0.0, posinf=None, neginf=None) -> Tensor + +In-place version of :func:`torch.nan_to_num` +""", +) + +add_docstr( + torch.ne, + r""" +ne(input, other, *, out=None) -> Tensor + +Computes :math:`\text{input} \neq \text{other}` element-wise. +""" + + r""" + +The second argument can be a number or a tensor whose shape is +:ref:`broadcastable ` with the first argument. + +Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + +Keyword args: + {out} + +Returns: + A boolean tensor that is True where :attr:`input` is not equal to :attr:`other` and False elsewhere + +Example:: + + >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [True, False]]) +""".format(**common_args), +) + +add_docstr( + torch.not_equal, + r""" +not_equal(input, other, *, out=None) -> Tensor + +Alias for :func:`torch.ne`. +""", +) + +add_docstr( + torch.neg, + r""" +neg(input, *, out=None) -> Tensor + +Returns a new tensor with the negative of the elements of :attr:`input`. + +.. math:: + \text{out} = -1 \times \text{input} +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(5) + >>> a + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.neg(a) + tensor([-0.0090, 0.2262, 0.0682, 0.2866, -0.3940]) +""".format(**common_args), +) + +add_docstr( + torch.neg_, + r""" +neg_(input) -> Tensor + +In-place version of :func:`torch.neg` +""", +) + +add_docstr( + torch.negative, + r""" +negative(input, *, out=None) -> Tensor + +Alias for :func:`torch.neg` +""", +) + +add_docstr( + torch.negative_, + r""" +negative_(input) -> Tensor + +In-place version of :func:`torch.negative` +""", +) + +add_docstr( + torch.nextafter, + r""" +nextafter(input, other, *, out=None) -> Tensor + +Return the next floating-point value after :attr:`input` towards :attr:`other`, elementwise. + +The shapes of ``input`` and ``other`` must be +:ref:`broadcastable `. + +Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + +Keyword args: + {out} + +Example:: + + >>> eps = torch.finfo(torch.float32).eps + >>> torch.nextafter(torch.tensor([1.0, 2.0]), torch.tensor([2.0, 1.0])) == torch.tensor([eps + 1, 2 - eps]) + tensor([True, True]) + +""".format(**common_args), +) + +add_docstr( + torch.nonzero, + r""" +nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors + +.. note:: + :func:`torch.nonzero(..., as_tuple=False) ` (default) returns a + 2-D tensor where each row is the index for a nonzero value. + + :func:`torch.nonzero(..., as_tuple=True) ` returns a tuple of 1-D + index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]`` + gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor + contains nonzero indices for a certain dimension. + + See below for more details on the two behaviors. + + When :attr:`input` is on CUDA, :func:`torch.nonzero() ` causes + host-device synchronization. + +**When** :attr:`as_tuple` **is** ``False`` **(default)**: + +Returns a tensor containing the indices of all non-zero elements of +:attr:`input`. Each row in the result contains the indices of a non-zero +element in :attr:`input`. The result is sorted lexicographically, with +the last index changing the fastest (C-style). + +If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor +:attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of +non-zero elements in the :attr:`input` tensor. + +**When** :attr:`as_tuple` **is** ``True``: + +Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`, +each containing the indices (in that dimension) of all non-zero elements of +:attr:`input` . + +If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n` +tensors of size :math:`z`, where :math:`z` is the total number of +non-zero elements in the :attr:`input` tensor. + +As a special case, when :attr:`input` has zero dimensions and a nonzero scalar +value, it is treated as a one-dimensional tensor with one element. + +Args: + {input} + +Keyword args: + out (LongTensor, optional): the output tensor containing indices + +Returns: + LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output + tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for + each dimension, containing the indices of each nonzero element along that + dimension. + +Example:: + + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1])) + tensor([[ 0], + [ 1], + [ 2], + [ 4]]) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]])) + tensor([[ 0, 0], + [ 1, 1], + [ 2, 2], + [ 3, 3]]) + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True) + (tensor([0, 1, 2, 4]),) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]]), as_tuple=True) + (tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])) + >>> torch.nonzero(torch.tensor(5), as_tuple=True) + (tensor([0]),) +""".format(**common_args), +) + +add_docstr( + torch.nonzero_static, + r""" +nonzero_static(input, *, size, fill_value=-1) -> Tensor + +Returns a 2-D tensor where each row is the index for a non-zero value. +The returned Tensor has the same `torch.dtype` as `torch.nonzero()`. + +Args: + {input} + +Keyword args: + size (int): the size of non-zero elements expected to be included in the out + tensor. Pad the out tensor with `fill_value` if the `size` is larger + than total number of non-zero elements, truncate out tensor if `size` + is smaller. The size must be a non-negative integer. + fill_value (int, optional): the value to fill the output tensor with when `size` is larger + than the total number of non-zero elements. Default is `-1` to represent + invalid index. + +Example:: + + # Example 1: Padding + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 4 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0], + [ 1, 1], + [ -1, -1]], dtype=torch.int64) + + # Example 2: Truncating + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0]], dtype=torch.int64) + + # Example 3: 0 size + >>> input_tensor = torch.tensor([10]) + >>> static_size = 0 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(0, 1), dtype=torch.int64) + + # Example 4: 0 rank input + >>> input_tensor = torch.tensor(10) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(2, 0), dtype=torch.int64) +""".format(**common_args), +) + +add_docstr( + torch.normal, + r""" +normal(mean, std, *, generator=None, out=None) -> Tensor + +Returns a tensor of random numbers drawn from separate normal distributions +whose mean and standard deviation are given. + +The :attr:`mean` is a tensor with the mean of +each output element's normal distribution + +The :attr:`std` is a tensor with the standard deviation of +each output element's normal distribution + +The shapes of :attr:`mean` and :attr:`std` don't need to match, but the +total number of elements in each tensor need to be the same. + +.. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + +.. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + +Args: + mean (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + +Keyword args: + {generator} + {out} + +Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + +.. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + +Similar to the function above, but the means are shared among all drawn +elements. + +Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + +Keyword args: + {out} + +Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + +.. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + +Similar to the function above, but the standard deviations are shared among +all drawn elements. + +Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + +Keyword args: + out (Tensor, optional): the output tensor + +Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + +.. function:: normal(mean, std, size, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + :noindex: + +Similar to the function above, but the means and standard deviations are shared +among all drawn elements. The resulting tensor has size given by :attr:`size`. + +Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + +Keyword args: + {generator} + {out} + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.numel, + r""" +numel(input: Tensor) -> int + +Returns the total number of elements in the :attr:`input` tensor. + +Args: + {input} + +Example:: + + >>> a = torch.randn(1, 2, 3, 4, 5) + >>> torch.numel(a) + 120 + >>> a = torch.zeros(4,4) + >>> torch.numel(a) + 16 + +""".format(**common_args), +) + +add_docstr( + torch.ones, + r""" +ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a tensor filled with the scalar value `1`, with the shape defined +by the variable argument :attr:`size`. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword arguments: + {out} + {dtype} + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + +""".format(**factory_common_args), +) + +add_docstr( + torch.ones_like, + r""" +ones_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + +Returns a tensor filled with the scalar value `1`, with the same size as +:attr:`input`. ``torch.ones_like(input)`` is equivalent to +``torch.ones(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +.. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.ones_like(input, out=output)`` is equivalent to + ``torch.ones(input.size(), out=output)``. + +Args: + {input} + +Keyword arguments: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +Example:: + + >>> input = torch.empty(2, 3) + >>> torch.ones_like(input) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) +""".format(**factory_like_common_args), +) + +add_docstr( + torch.orgqr, + r""" +orgqr(input, tau) -> Tensor + +Alias for :func:`torch.linalg.householder_product`. +""", +) + +add_docstr( + torch.ormqr, + r""" +ormqr(input, tau, other, left=True, transpose=False, *, out=None) -> Tensor + +Computes the matrix-matrix multiplication of a product of Householder matrices with a general matrix. + +Multiplies a :math:`m \times n` matrix `C` (given by :attr:`other`) with a matrix `Q`, +where `Q` is represented using Householder reflectors `(input, tau)`. +See `Representation of Orthogonal or Unitary Matrices`_ for further details. + +If :attr:`left` is `True` then `op(Q)` times `C` is computed, otherwise the result is `C` times `op(Q)`. +When :attr:`left` is `True`, the implicit matrix `Q` has size :math:`m \times m`. +It has size :math:`n \times n` otherwise. +If :attr:`transpose` is `True` then `op` is the conjugate transpose operation, otherwise it's a no-op. + +Supports inputs of float, double, cfloat and cdouble dtypes. +Also supports batched inputs, and, if the input is batched, the output is batched with the same dimensions. + +.. seealso:: + :func:`torch.geqrf` can be used to form the Householder representation `(input, tau)` of matrix `Q` + from the QR decomposition. + +.. note:: + This function supports backward but it is only fast when ``(input, tau)`` do not require gradients + and/or ``tau.size(-1)`` is very small. + `` + +Args: + input (Tensor): tensor of shape `(*, mn, k)` where `*` is zero or more batch dimensions + and `mn` equals to `m` or `n` depending on the :attr:`left`. + tau (Tensor): tensor of shape `(*, min(mn, k))` where `*` is zero or more batch dimensions. + other (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions. + left (bool): controls the order of multiplication. + transpose (bool): controls whether the matrix `Q` is conjugate transposed or not. + +Keyword args: + out (Tensor, optional): the output Tensor. Ignored if `None`. Default: `None`. + +.. _Representation of Orthogonal or Unitary Matrices: + https://www.netlib.org/lapack/lug/node128.html +""", +) + +add_docstr( + torch.permute, + r""" +permute(input, dims) -> Tensor + +Returns a view of the original tensor :attr:`input` with its dimensions permuted. + +Args: + {input} + dims (torch.Size, tuple of int or list of int): the desired ordering of dimensions. + +Example: + >>> x = torch.randn(2, 3, 5) + >>> x.size() + torch.Size([2, 3, 5]) + >>> torch.permute(x, (2, 0, 1)).size() + torch.Size([5, 2, 3]) +""".format(**common_args), +) + +add_docstr( + torch.poisson, + r""" +poisson(input, generator=None) -> Tensor + +Returns a tensor of the same size as :attr:`input` with each element +sampled from a Poisson distribution with rate parameter given by the corresponding +element in :attr:`input` i.e., + +.. math:: + \text{{out}}_i \sim \text{{Poisson}}(\text{{input}}_i) + +:attr:`input` must be non-negative. + +Args: + input (Tensor): the input tensor containing the rates of the Poisson distribution + +Keyword args: + {generator} + +Example:: + + >>> rates = torch.rand(4, 4) * 5 # rate parameter between 0 and 5 + >>> torch.poisson(rates) + tensor([[9., 1., 3., 5.], + [8., 6., 6., 0.], + [0., 4., 5., 3.], + [2., 1., 4., 2.]]) +""".format(**common_args), +) + +add_docstr( + torch.polygamma, + r""" +polygamma(n, input, *, out=None) -> Tensor + +Alias for :func:`torch.special.polygamma`. +""", +) + +add_docstr( + torch.positive, + r""" +positive(input) -> Tensor + +Returns :attr:`input`. +Throws a runtime error if :attr:`input` is a bool tensor. +""" + + r""" +Args: + {input} + +Example:: + + >>> t = torch.randn(5) + >>> t + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.positive(t) + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) +""".format(**common_args), +) + +add_docstr( + torch.pow, + r""" +pow(input, exponent, *, out=None) -> Tensor + +Takes the power of each element in :attr:`input` with :attr:`exponent` and +returns a tensor with the result. + +:attr:`exponent` can be either a single ``float`` number or a `Tensor` +with the same number of elements as :attr:`input`. + +When :attr:`exponent` is a scalar value, the operation applied is: + +.. math:: + \text{out}_i = x_i ^ \text{exponent} + +When :attr:`exponent` is a tensor, the operation applied is: + +.. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} +""" + + r""" +When :attr:`exponent` is a tensor, the shapes of :attr:`input` +and :attr:`exponent` must be :ref:`broadcastable `. + +Args: + {input} + exponent (float or tensor): the exponent value + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + +.. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + +:attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. +The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + +The operation applied is: + +.. math:: + \text{{out}}_i = \text{{self}} ^ {{\text{{exponent}}_i}} + +Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + +Keyword args: + {out} + +Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) +""".format(**common_args), +) + +add_docstr( + torch.float_power, + r""" +float_power(input, exponent, *, out=None) -> Tensor + +Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. +If neither input is complex returns a ``torch.float64`` tensor, +and if one or more inputs is complex returns a ``torch.complex128`` tensor. + +.. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + +Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + +Keyword args: + {out} + +Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) +""".format(**common_args), +) + +add_docstr( + torch.prod, + r""" +prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor + +Returns the product of all elements in the :attr:`input` tensor. + +Args: + {input} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + +.. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + +Returns the product of each row of the :attr:`input` tensor in the given +dimension :attr:`dim`. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) +""".format(**single_dim_common), +) + +add_docstr( + torch.promote_types, + r""" +promote_types(type1, type2) -> dtype + +Returns the :class:`torch.dtype` with the smallest size and scalar kind that is +not smaller nor of lower kind than either `type1` or `type2`. See type promotion +:ref:`documentation ` for more information on the type +promotion logic. + +Args: + type1 (:class:`torch.dtype`) + type2 (:class:`torch.dtype`) + +Example:: + + >>> torch.promote_types(torch.int32, torch.float32) + torch.float32 + >>> torch.promote_types(torch.uint8, torch.long) + torch.long +""", +) + +add_docstr( + torch.rad2deg, + r""" +rad2deg(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with each of the elements of :attr:`input` +converted from angles in radians to degrees. + +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.tensor([[3.142, -3.142], [6.283, -6.283], [1.570, -1.570]]) + >>> torch.rad2deg(a) + tensor([[ 180.0233, -180.0233], + [ 359.9894, -359.9894], + [ 89.9544, -89.9544]]) + +""".format(**common_args), +) + +add_docstr( + torch.rad2deg_, + r""" +rad2deg_(input) -> Tensor + +In-place version of :func:`torch.rad2deg` +""", +) + +add_docstr( + torch.deg2rad, + r""" +deg2rad(input, *, out=None) -> Tensor + +Returns a new tensor with each of the elements of :attr:`input` +converted from angles in degrees to radians. + +Args: + {input} + +Keyword arguments: + {out} + +Example:: + + >>> a = torch.tensor([[180.0, -180.0], [360.0, -360.0], [90.0, -90.0]]) + >>> torch.deg2rad(a) + tensor([[ 3.1416, -3.1416], + [ 6.2832, -6.2832], + [ 1.5708, -1.5708]]) + +""".format(**common_args), +) + +add_docstr( + torch.deg2rad_, + r""" +deg2rad_(input) -> Tensor + +In-place version of :func:`torch.deg2rad` +""", +) + +add_docstr( + torch.heaviside, + r""" +heaviside(input, values, *, out=None) -> Tensor + +Computes the Heaviside step function for each element in :attr:`input`. +The Heaviside step function is defined as: + +.. math:: + \text{{heaviside}}(input, values) = \begin{cases} + 0, & \text{if input < 0}\\ + values, & \text{if input == 0}\\ + 1, & \text{if input > 0} + \end{cases} +""" + + r""" + +Args: + {input} + values (Tensor): The values to use where :attr:`input` is zero. + +Keyword arguments: + {out} + +Example:: + + >>> input = torch.tensor([-1.5, 0, 2.0]) + >>> values = torch.tensor([0.5]) + >>> torch.heaviside(input, values) + tensor([0.0000, 0.5000, 1.0000]) + >>> values = torch.tensor([1.2, -2.0, 3.5]) + >>> torch.heaviside(input, values) + tensor([0., -2., 1.]) + +""".format(**common_args), +) + +add_docstr( + torch.rand, + """ +rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, \ +requires_grad=False, pin_memory=False) -> Tensor +""" + + r""" +Returns a tensor filled with random numbers from a uniform distribution +on the interval :math:`[0, 1)` + +The shape of the tensor is defined by the variable argument :attr:`size`. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword args: + {generator} + {out} + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.rand_like, + """ +rand_like(input, *, generator=None, dtype=None, layout=None, device=None, \ +requires_grad=False, memory_format=torch.preserve_format) -> Tensor +""" + + r""" +Returns a tensor with the same size as :attr:`input` that is filled with +random numbers from a uniform distribution on the interval :math:`[0, 1)`. +``torch.rand_like(input)`` is equivalent to +``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +Args: + {input} + +Keyword args: + {generator} + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +""".format(**factory_like_common_args), +) + +add_docstr( + torch.randint, + """ +randint(low=0, high, size, \\*, generator=None, out=None, \ +dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a tensor filled with random integers generated uniformly +between :attr:`low` (inclusive) and :attr:`high` (exclusive). + +The shape of the tensor is defined by the variable argument :attr:`size`. + +.. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + +Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + +Keyword args: + {generator} + {out} + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + + +""".format(**factory_common_args), +) + +add_docstr( + torch.randint_like, + """ +randint_like(input, low=0, high, \\*, generator=None, dtype=None, layout=torch.strided, \ +device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor +""" + + r""" +Returns a tensor with the same shape as Tensor :attr:`input` filled with +random integers generated uniformly between :attr:`low` (inclusive) and +:attr:`high` (exclusive). + +.. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + +Args: + {input} + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + +Keyword args: + {generator} + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +""".format(**factory_like_common_args), +) + +add_docstr( + torch.randn, + """ +randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, \ +pin_memory=False) -> Tensor +""" + + r""" + +Returns a tensor filled with random numbers from a normal distribution +with mean `0` and variance `1` (also called the standard normal +distribution). + +.. math:: + \text{{out}}_{{i}} \sim \mathcal{{N}}(0, 1) + +For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and +unit variance as + +.. math:: + \text{{out}}_{{i}} \sim \mathcal{{CN}}(0, 1) + +This is equivalent to separately sampling the real :math:`(\operatorname{{Re}})` and imaginary +:math:`(\operatorname{{Im}})` part of :math:`\text{{out}}_i` as + +.. math:: + \operatorname{{Re}}(\text{{out}}_{{i}}) \sim \mathcal{{N}}(0, \frac{{1}}{{2}}),\quad + \operatorname{{Im}}(\text{{out}}_{{i}}) \sim \mathcal{{N}}(0, \frac{{1}}{{2}}) + +The shape of the tensor is defined by the variable argument :attr:`size`. + + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword args: + {generator} + {out} + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + +.. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution +""".format(**factory_common_args), +) + +add_docstr( + torch.randn_like, + """ +randn_like(input, *, generator=None, dtype=None, layout=None, device=None, \ +requires_grad=False, memory_format=torch.preserve_format) -> Tensor +""" + + r""" +Returns a tensor with the same size as :attr:`input` that is filled with +random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the +sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to +``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +Args: + {input} + +Keyword args: + {generator} + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +""".format(**factory_like_common_args), +) + +add_docstr( + torch.randperm, + """ +randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, \ +device=None, requires_grad=False, pin_memory=False) -> Tensor +""" + + r""" +Returns a random permutation of integers from ``0`` to ``n - 1``. + +Args: + n (int): the upper bound (exclusive) + +Keyword args: + {generator} + {out} + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) +""".format(**factory_common_args), +) + +add_docstr( + torch.tensor, + r""" +tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + +Constructs a tensor with no autograd history (also known as a "leaf tensor", see :doc:`/notes/autograd`) by copying :attr:`data`. + +.. warning:: + + When working with tensors prefer using :func:`torch.Tensor.clone`, + :func:`torch.Tensor.detach`, and :func:`torch.Tensor.requires_grad_` for + readability. Letting `t` be a tensor, ``torch.tensor(t)`` is equivalent to + ``t.detach().clone()``, and ``torch.tensor(t, requires_grad=True)`` + is equivalent to ``t.detach().clone().requires_grad_(True)``. + +.. seealso:: + + :func:`torch.as_tensor` preserves autograd history and avoids copies where possible. + :func:`torch.from_numpy` creates a tensor that shares storage with a NumPy array. + +Args: + {data} + +Keyword args: + {dtype} + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + {requires_grad} + {pin_memory} + + +Example:: + + >>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) + tensor([[ 0.1000, 1.2000], + [ 2.2000, 3.1000], + [ 4.9000, 5.2000]]) + + >>> torch.tensor([0, 1]) # Type inference on data + tensor([ 0, 1]) + + >>> torch.tensor([[0.11111, 0.222222, 0.3333333]], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) # creates a double tensor on a CUDA device + tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0') + + >>> torch.tensor(3.14159) # Create a zero-dimensional (scalar) tensor + tensor(3.1416) + + >>> torch.tensor([]) # Create an empty tensor (of size (0,)) + tensor([]) +""".format(**factory_data_common_args), +) + +add_docstr( + torch.range, + r""" +range(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a 1-D tensor of size :math:`\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1` +with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is +the gap between two values in the tensor. + +.. math:: + \text{out}_{i+1} = \text{out}_i + \text{step}. +""" + + r""" +.. warning:: + This function is deprecated and will be removed in a future release because its behavior is inconsistent with + Python's range builtin. Instead, use :func:`torch.arange`, which produces values in [start, end). + +Args: + start (float, optional): the starting value for the set of points. Default: ``0``. + end (float): the ending value for the set of points + step (float, optional): the gap between each pair of adjacent points. Default: ``1``. + +Keyword args: + {out} + {dtype} If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.range(1, 4) + tensor([ 1., 2., 3., 4.]) + >>> torch.range(1, 4, 0.5) + tensor([ 1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000]) +""".format(**factory_common_args), +) + +add_docstr( + torch.arange, + r""" +arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` +with values from the interval ``[start, end)`` taken with common difference +:attr:`step` beginning from `start`. + +Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), +the results may be affected by floating-point rounding behavior. Some values in the sequence +might not be exactly representable in certain floating-point formats, which can lead to +repeated values or unexpected rounding. For precise sequences, it is recommended to use +integer dtypes instead of floating-point dtypes. + +Note that non-integer :attr:`step` is subject to floating point rounding errors when +comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` +in such cases. + +.. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} +""" + + r""" +Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + +Keyword args: + {out} + {dtype} If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) +""".format(**factory_common_args), +) + +add_docstr( + torch.ravel, + r""" +ravel(input) -> Tensor + +Return a contiguous flattened tensor. A copy is made only if needed. + +Args: + {input} + +Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.ravel(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) +""".format(**common_args), +) + +add_docstr( + torch.remainder, + r""" +remainder(input, other, *, out=None) -> Tensor + +Computes +`Python's modulus operation `_ +entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value +is less than that of :attr:`other`. + +It may also be defined in terms of :func:`torch.div` as + +.. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer and float inputs. + +.. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + +.. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + +Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + +Keyword args: + {out} + +Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) +""".format(**common_args), +) + +add_docstr( + torch.renorm, + r""" +renorm(input, p, dim, maxnorm, *, out=None) -> Tensor + +Returns a tensor where each sub-tensor of :attr:`input` along dimension +:attr:`dim` is normalized such that the `p`-norm of the sub-tensor is lower +than the value :attr:`maxnorm` + +.. note:: If the norm of a row is lower than `maxnorm`, the row is unchanged + +Args: + {input} + p (float): the power for the norm computation + dim (int): the dimension to slice over to get the sub-tensors + maxnorm (float): the maximum norm to keep each sub-tensor under + +Keyword args: + {out} + +Example:: + + >>> x = torch.ones(3, 3) + >>> x[1].fill_(2) + tensor([ 2., 2., 2.]) + >>> x[2].fill_(3) + tensor([ 3., 3., 3.]) + >>> x + tensor([[ 1., 1., 1.], + [ 2., 2., 2.], + [ 3., 3., 3.]]) + >>> torch.renorm(x, 1, 0, 5) + tensor([[ 1.0000, 1.0000, 1.0000], + [ 1.6667, 1.6667, 1.6667], + [ 1.6667, 1.6667, 1.6667]]) +""".format(**common_args), +) + +add_docstr( + torch.reshape, + r""" +reshape(input, shape) -> Tensor + +Returns a tensor with the same data and number of elements as :attr:`input`, +but with the specified shape. When possible, the returned tensor will be a view +of :attr:`input`. Otherwise, it will be a copy. Contiguous inputs and inputs +with compatible strides can be reshaped without copying, but you should not +depend on the copying vs. viewing behavior. + +See :meth:`torch.Tensor.view` on when it is possible to return a view. + +A single dimension may be -1, in which case it's inferred from the remaining +dimensions and the number of elements in :attr:`input`. + +Args: + input (Tensor): the tensor to be reshaped + shape (tuple of int): the new shape + +Example:: + + >>> a = torch.arange(4.) + >>> torch.reshape(a, (2, 2)) + tensor([[ 0., 1.], + [ 2., 3.]]) + >>> b = torch.tensor([[0, 1], [2, 3]]) + >>> torch.reshape(b, (-1,)) + tensor([ 0, 1, 2, 3]) +""", +) + + +add_docstr( + torch.result_type, + r""" +result_type(tensor1, tensor2) -> dtype + +Returns the :class:`torch.dtype` that would result from performing an arithmetic +operation on the provided input tensors. See type promotion :ref:`documentation ` +for more information on the type promotion logic. + +Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + +Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 +""", +) + +add_docstr( + torch.row_stack, + r""" +row_stack(tensors, *, out=None) -> Tensor + +Alias of :func:`torch.vstack`. +""", +) + +add_docstr( + torch.round, + r""" +round(input, *, decimals=0, out=None) -> Tensor + +Rounds elements of :attr:`input` to the nearest integer. + +For integer inputs, follows the array-api convention of returning a +copy of the input tensor. +The return type of output is same as that of input's dtype. + +.. note:: + This function implements the "round half to even" to + break ties when a number is equidistant from two + integers (e.g. `round(2.5)` is 2). + + When the :attr:\`decimals\` argument is specified the + algorithm used is similar to NumPy's `around`. This + algorithm is fast but inexact and it can easily + overflow for low precision dtypes. + Eg. `round(tensor([10000], dtype=torch.float16), decimals=3)` is `inf`. + +.. seealso:: + :func:`torch.ceil`, which rounds up. + :func:`torch.floor`, which rounds down. + :func:`torch.trunc`, which rounds towards zero. + +Args: + {input} + decimals (int): Number of decimal places to round to (default: 0). + If decimals is negative, it specifies the number of positions + to the left of the decimal point. + +Keyword args: + {out} + +Example:: + + >>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) + tensor([ 5., -2., 9., -8.]) + + >>> # Values equidistant from two integers are rounded towards the + >>> # nearest even value (zero is treated as even) + >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) + tensor([-0., 0., 2., 2.]) + + >>> # A positive decimals argument rounds to that decimal place + >>> torch.round(torch.tensor([0.1234567]), decimals=3) + tensor([0.1230]) + + >>> # A negative decimals argument rounds to the left of the decimal + >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) + tensor([1000.]) +""".format(**common_args), +) + +add_docstr( + torch.round_, + r""" +round_(input, *, decimals=0) -> Tensor + +In-place version of :func:`torch.round` +""", +) + +add_docstr( + torch.rsqrt, + r""" +rsqrt(input, *, out=None) -> Tensor + +Returns a new tensor with the reciprocal of the square-root of each of +the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \frac{1}{\sqrt{\text{input}_{i}}} +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.0370, 0.2970, 1.5420, -0.9105]) + >>> torch.rsqrt(a) + tensor([ nan, 1.8351, 0.8053, nan]) +""".format(**common_args), +) + +add_docstr( + torch.rsqrt_, + r""" +rsqrt_(input) -> Tensor + +In-place version of :func:`torch.rsqrt` +""", +) + +add_docstr( + torch.scatter, + r""" +scatter(input, dim, index, src) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_` +""", +) + +add_docstr( + torch.scatter_add, + r""" +scatter_add(input, dim, index, src) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_add_` +""", +) + +add_docstr( + torch.scatter_reduce, + r""" +scatter_reduce(input, dim, index, src, reduce, *, include_self=True) -> Tensor + +Out-of-place version of :meth:`torch.Tensor.scatter_reduce_` +""", +) + +add_docstr( + torch.segment_reduce, + r""" +segment_reduce(data: Tensor, reduce: str, *, lengths: Tensor | None = None, indices: Tensor | None = None, offsets: Tensor | None = None, axis: _int = 0, unsafe: _bool = False, initial: Number | _complex | None = None) -> Tensor # noqa: B950 + +Perform a segment reduction operation on the input tensor along the specified axis. + +Args: + data (Tensor): The input tensor on which the segment reduction operation will be performed. + reduce (str): The type of reduction operation. Supported values are ``sum``, ``mean``, ``max``, ``min``, ``prod``. + +Keyword args: + lengths (Tensor, optional): Length of each segment. Default: ``None``. + offsets (Tensor, optional): Offset of each segment. Default: ``None``. + axis (int, optional): The axis perform reduction. Default: ``0``. + unsafe (bool, optional): Skip validation If `True`. Default: ``False``. + initial (Number, optional): The initial value for the reduction operation. Default: ``None``. + +Example:: + + >>> data = torch.tensor([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]], dtype=torch.float32, device='cuda') + >>> lengths = torch.tensor([2, 1], device='cuda') + >>> torch.segment_reduce(data, 'max', lengths=lengths) + tensor([[ 5., 6., 7., 8.], + [ 9., 10., 11., 12.]], device='cuda:0') +""", +) + +add_docstr( + torch.select, + r""" +select(input, dim, index) -> Tensor + +Slices the :attr:`input` tensor along the selected dimension at the given index. +This function returns a view of the original tensor with the given dimension removed. + +.. note:: If :attr:`input` is a sparse tensor and returning a view of + the tensor is not possible, a RuntimeError exception is + raised. In this is the case, consider using + :func:`torch.select_copy` function. + +Args: + {input} + dim (int): the dimension to slice + index (int): the index to select with + +.. note:: + + :meth:`select` is equivalent to slicing. For example, + ``tensor.select(0, index)`` is equivalent to ``tensor[index]`` and + ``tensor.select(2, index)`` is equivalent to ``tensor[:,:,index]``. +""".format(**common_args), +) + +add_docstr( + torch.select_scatter, + r""" +select_scatter(input, src, dim, index) -> Tensor + +Embeds the values of the :attr:`src` tensor into :attr:`input` at the given index. +This function returns a tensor with fresh storage; it does not create a view. + + +Args: + {input} + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into. + index (int): the index to select with + +.. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.select(input, dim, index)`` + +Example:: + + >>> a = torch.zeros(2, 2) + >>> b = torch.ones(2) + >>> a.select_scatter(b, 0, 0) + tensor([[1., 1.], + [0., 0.]]) +""".format(**common_args), +) + +add_docstr( + torch.slice_scatter, + r""" +slice_scatter(input, src, dim=0, start=None, end=None, step=1) -> Tensor + +Embeds the values of the :attr:`src` tensor into :attr:`input` at the given +dimension. +This function returns a tensor with fresh storage; it does not create a view. + + +Args: + {input} + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into + start (Optional[int]): the start index of where to insert the slice + end (Optional[int]): the end index of where to insert the slice + step (int): the how many elements to skip in + +Example:: + + >>> a = torch.zeros(8, 8) + >>> b = torch.ones(2, 8) + >>> a.slice_scatter(b, start=6) + tensor([[0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [1., 1., 1., 1., 1., 1., 1., 1.], + [1., 1., 1., 1., 1., 1., 1., 1.]]) + + >>> b = torch.ones(8, 2) + >>> a.slice_scatter(b, dim=1, start=2, end=6, step=2) + tensor([[0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.]]) +""".format(**common_args), +) + +add_docstr( + torch.set_flush_denormal, + r""" +set_flush_denormal(mode) -> bool + +Disables denormal floating numbers on CPU. + +Returns ``True`` if your system supports flushing denormal numbers and it +successfully configures flush denormal mode. :meth:`~torch.set_flush_denormal` +is supported on x86 architectures supporting SSE3 and AArch64 architecture. + +Args: + mode (bool): Controls whether to enable flush denormal mode or not + +Example:: + + >>> torch.set_flush_denormal(True) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor([ 0.], dtype=torch.float64) + >>> torch.set_flush_denormal(False) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor(9.88131e-324 * + [ 1.0000], dtype=torch.float64) +""", +) + +add_docstr( + torch.set_num_threads, + r""" +set_num_threads(int) + +Sets the number of threads used for intraop parallelism on CPU. + +.. warning:: + To ensure that the correct number of threads is used, set_num_threads + must be called before running eager, JIT or autograd code. +""", +) + +add_docstr( + torch.set_num_interop_threads, + r""" +set_num_interop_threads(int) + +Sets the number of threads used for interop parallelism +(e.g. in JIT interpreter) on CPU. + +.. warning:: + Can only be called once and before any inter-op parallel work + is started (e.g. JIT execution). +""", +) + +add_docstr( + torch.sigmoid, + r""" +sigmoid(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.expit`. +""", +) + +add_docstr( + torch.sigmoid_, + r""" +sigmoid_(input) -> Tensor + +In-place version of :func:`torch.sigmoid` +""", +) + +add_docstr( + torch.logit, + r""" +logit(input, eps=None, *, out=None) -> Tensor + +Alias for :func:`torch.special.logit`. +""", +) + +add_docstr( + torch.logit_, + r""" +logit_(input, eps=None) -> Tensor + +In-place version of :func:`torch.logit` +""", +) + +add_docstr( + torch.sign, + r""" +sign(input, *, out=None) -> Tensor + +Returns a new tensor with the signs of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \operatorname{sgn}(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> a + tensor([ 0.7000, -1.2000, 0.0000, 2.3000]) + >>> torch.sign(a) + tensor([ 1., -1., 0., 1.]) +""".format(**common_args), +) + +add_docstr( + torch.signbit, + r""" +signbit(input, *, out=None) -> Tensor + +Tests if each element of :attr:`input` has its sign bit set or not. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> torch.signbit(a) + tensor([ False, True, False, False]) + >>> a = torch.tensor([-0.0, 0.0]) + >>> torch.signbit(a) + tensor([ True, False]) + +.. note:: + signbit handles signed zeros, so negative zero (-0) returns True. + +""".format(**common_args), +) + +add_docstr( + torch.sgn, + r""" +sgn(input, *, out=None) -> Tensor + +This function is an extension of torch.sign() to complex tensors. +It computes a new tensor whose elements have +the same angles as the corresponding elements of :attr:`input` and +absolute values (i.e. magnitudes) of one for complex tensors and +is equivalent to torch.sign() for non-complex tensors. + +.. math:: + \text{out}_{i} = \begin{cases} + 0 & |\text{{input}}_i| == 0 \\ + \frac{{\text{{input}}_i}}{|{\text{{input}}_i}|} & \text{otherwise} + \end{cases} + +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> t = torch.tensor([3+4j, 7-24j, 0, 1+2j]) + >>> t.sgn() + tensor([0.6000+0.8000j, 0.2800-0.9600j, 0.0000+0.0000j, 0.4472+0.8944j]) +""".format(**common_args), +) + +add_docstr( + torch.sin, + r""" +sin(input, *, out=None) -> Tensor + +Returns a new tensor with the sine of the elements in the :attr:`input` tensor, +where each value in this input tensor is in radians. + +.. math:: + \text{out}_{i} = \sin(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5461, 0.1347, -2.7266, -0.2746]) + >>> torch.sin(a) + tensor([-0.5194, 0.1343, -0.4032, -0.2711]) +""".format(**common_args), +) + +add_docstr( + torch.sin_, + r""" +sin_(input) -> Tensor + +In-place version of :func:`torch.sin` +""", +) + +add_docstr( + torch.sinc, + r""" +sinc(input, *, out=None) -> Tensor + +Alias for :func:`torch.special.sinc`. +""", +) + +add_docstr( + torch.sinc_, + r""" +sinc_(input) -> Tensor + +In-place version of :func:`torch.sinc` +""", +) + +add_docstr( + torch.sinh, + r""" +sinh(input, *, out=None) -> Tensor + +Returns a new tensor with the hyperbolic sine of the elements of +:attr:`input`. + +.. math:: + \text{out}_{i} = \sinh(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.5380, -0.8632, -0.1265, 0.9399]) + >>> torch.sinh(a) + tensor([ 0.5644, -0.9744, -0.1268, 1.0845]) + +""".format(**common_args), +) + +add_docstr( + torch.sinh_, + r""" +sinh_(input) -> Tensor + +In-place version of :func:`torch.sinh` +""", +) + +add_docstr( + torch.sort, + r""" +sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + +Sorts the elements of the :attr:`input` tensor along a given dimension +in ascending order by value. + +If :attr:`dim` is not given, the last dimension of the `input` is chosen. + +If :attr:`descending` is ``True`` then the elements are sorted in descending +order by value. + +If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving +the order of equivalent elements. + +A namedtuple of (values, indices) is returned, where the `values` are the +sorted values and `indices` are the indices of the elements in the original +`input` tensor. + +Args: + {input} + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + +Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + +Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) +""".format(**common_args), +) + +add_docstr( + torch.argsort, + r""" +argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + +Returns the indices that sort a tensor along a given dimension in ascending +order by value. + +This is the second value returned by :meth:`torch.sort`. See its documentation +for the exact semantics of this method. + +If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving +the order of equivalent elements. If ``False``, the relative order of values +which compare equal is not guaranteed. ``True`` is slower. + +Args: + {input} + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + +Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) +""".format(**common_args), +) + +add_docstr( + torch.msort, + r""" +msort(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Sorts the elements of the :attr:`input` tensor along its first dimension +in ascending order by value. + +.. note:: `torch.msort(t)` is equivalent to `torch.sort(t, dim=0)[0]`. + See also :func:`torch.sort`. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> t = torch.randn(3, 4) + >>> t + tensor([[-0.1321, 0.4370, -1.2631, -1.1289], + [-2.0527, -1.1250, 0.2275, 0.3077], + [-0.0881, -0.1259, -0.5495, 1.0284]]) + >>> torch.msort(t) + tensor([[-2.0527, -1.1250, -1.2631, -1.1289], + [-0.1321, -0.1259, -0.5495, 0.3077], + [-0.0881, 0.4370, 0.2275, 1.0284]]) +""".format(**common_args), +) + +add_docstr( + torch.sparse_compressed_tensor, + r"""sparse_compressed_tensor(compressed_indices, plain_indices, values, size=None, """ + r"""*, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in Compressed Sparse format - CSR, +CSC, BSR, or BSC - ` with specified values at +the given :attr:`compressed_indices` and :attr:`plain_indices`. Sparse +matrix multiplication operations in Compressed Sparse format are +typically faster than that for sparse tensors in COO format. Make you +have a look at :ref:`the note on the data type of the indices +`. + +{sparse_factory_device_note} + +Args: + compressed_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, compressed_dim_size + 1)``. The last element of + each batch is the number of non-zero elements or blocks. This + tensor encodes the index in ``values`` and ``plain_indices`` + depending on where the given compressed dimension (row or + column) starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + elements or blocks in a given compressed dimension. + plain_indices (array_like): Plain dimension (column or row) + coordinates of each element or block in values. (B+1)-dimensional + tensor with the same length as values. + + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types. that + represents a (1+K)-dimensional (for CSR and CSC layouts) or + (1+2+K)-dimensional tensor (for BSR and BSC layouts) where + ``K`` is the number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize[0] == + blocksize[1] == 1`` for CSR and CSC formats. If not provided, + the size will be inferred as the minimum size big enough to + hold all non-zero elements or blocks. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + layout (:class:`torch.layout`, required): the desired layout of + returned tensor: :attr:`torch.sparse_csr`, + :attr:`torch.sparse_csc`, :attr:`torch.sparse_bsr`, or + :attr:`torch.sparse_bsc`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {pin_memory} + {requires_grad} + {check_invariants} + +Example:: + + >>> compressed_indices = [0, 2, 4] + >>> plain_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_compressed_tensor(torch.tensor(compressed_indices, dtype=torch.int64), + ... torch.tensor(plain_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double, layout=torch.sparse_csr) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) +""".format(**factory_common_args), +) + +add_docstr( + torch.sparse_csr_tensor, + r"""sparse_csr_tensor(crow_indices, col_indices, values, size=None, """ + r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in CSR (Compressed Sparse Row) ` with specified +values at the given :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix multiplication operations +in CSR format are typically faster than that for sparse tensors in COO format. Make you have a look +at :ref:`the note on the data type of the indices `. + +{sparse_factory_device_note} + +Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrows + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and col_indices depending on where the given row + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + row. + col_indices (array_like): Column coordinates of each element in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {pin_memory} + {requires_grad} + {check_invariants} + +Example:: + + >>> crow_indices = [0, 2, 4] + >>> col_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) +""".format(**factory_common_args), +) + +add_docstr( + torch.sparse_csc_tensor, + r"""sparse_csc_tensor(ccol_indices, row_indices, values, size=None, """ + r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in CSC (Compressed Sparse Column) +` with specified values at the given +:attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix +multiplication operations in CSC format are typically faster than that +for sparse tensors in COO format. Make you have a look at :ref:`the +note on the data type of the indices `. + +{sparse_factory_device_note} + +Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncols + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and row_indices depending on where the given column + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + column. + row_indices (array_like): Row coordinates of each element in + values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {pin_memory} + {requires_grad} + {check_invariants} + +Example:: + + >>> ccol_indices = [0, 2, 4] + >>> row_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 2, 4]), + row_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csc) +""".format(**factory_common_args), +) + +add_docstr( + torch.sparse_bsr_tensor, + r"""sparse_bsr_tensor(crow_indices, col_indices, values, size=None, """ + r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in BSR (Block Compressed Sparse Row)) +` with specified 2-dimensional blocks at the given +:attr:`crow_indices` and :attr:`col_indices`. Sparse matrix +multiplication operations in BSR format are typically faster than that +for sparse tensors in COO format. Make you have a look at :ref:`the +note on the data type of the indices `. + +{sparse_factory_device_note} + +Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrowblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + block index in values and col_indices depending on where the + given row block starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + blocks in a given row. + col_indices (array_like): Column block coordinates of each block + in values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize == + values.shape[1:3]``. If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {pin_memory} + {requires_grad} + {check_invariants} + +Example:: + + >>> crow_indices = [0, 1, 2] + >>> col_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 1, 2]), + col_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsr) +""".format(**factory_common_args), +) + +add_docstr( + torch.sparse_bsc_tensor, + r"""sparse_bsc_tensor(ccol_indices, row_indices, values, size=None, """ + r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + +Constructs a :ref:`sparse tensor in BSC (Block Compressed Sparse +Column)) ` with specified 2-dimensional blocks at the +given :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix +multiplication operations in BSC format are typically faster than that +for sparse tensors in COO format. Make you have a look at :ref:`the +note on the data type of the indices `. + +{sparse_factory_device_note} + +Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncolblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + index in values and row_indices depending on where the given + column starts. Each successive number in the tensor subtracted + by the number before it denotes the number of elements in a + given column. + row_indices (array_like): Row block coordinates of each block in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial blocks for the tensor. Can be a list, + tuple, NumPy ``ndarray``, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + {pin_memory} + {requires_grad} + {check_invariants} + +Example:: + + >>> ccol_indices = [0, 1, 2] + >>> row_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 1, 2]), + row_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsc) +""".format(**factory_common_args), +) + +add_docstr( + torch.sparse_coo_tensor, + r"""sparse_coo_tensor(indices, values, size=None, """ + r"""*, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None, is_coalesced=None) -> Tensor + +Constructs a :ref:`sparse tensor in COO(rdinate) format +` with specified values at the given +:attr:`indices`. + +.. note:: + + This function returns an :ref:`uncoalesced tensor + ` when :attr:`is_coalesced` is + unspecified or ``None``. + +{sparse_factory_device_note} + +Args: + indices (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. Will be cast to a :class:`torch.LongTensor` + internally. The indices are the coordinates of the non-zero values in the matrix, and thus + should be two-dimensional where the first dimension is the number of tensor dimensions and + the second dimension is the number of non-zero values. + values (array_like): Initial values for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + size (list, tuple, or :class:`torch.Size`, optional): Size of the sparse tensor. If not + provided the size will be inferred as the minimum size big enough to hold all non-zero + elements. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if None, infers data type from :attr:`values`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + {pin_memory} + {requires_grad} + {check_invariants} + is_coalesced (bool, optional): When``True``, the caller is + responsible for providing tensor indices that correspond to a + coalesced tensor. If the :attr:`check_invariants` flag is + False, no error will be raised if the prerequisites are not + met and this will lead to silently incorrect results. To force + coalescing please use :meth:`coalesce` on the resulting + Tensor. + Default: None: except for trivial cases (e.g. nnz < 2) the + resulting Tensor has is_coalesced set to ``False```. + +Example:: + + >>> i = torch.tensor([[0, 1, 1], + ... [2, 0, 2]]) + >>> v = torch.tensor([3, 4, 5], dtype=torch.float32) + >>> torch.sparse_coo_tensor(i, v, [2, 4]) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 4), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v) # Shape inference + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 3), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v, [2, 4], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64, + layout=torch.sparse_coo) + + # Create an empty sparse tensor with the following invariants: + # 1. sparse_dim + dense_dim = len(SparseTensor.shape) + # 2. SparseTensor._indices().shape = (sparse_dim, nnz) + # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:]) + # + # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and + # sparse_dim = 1 (hence indices is a 2D tensor of shape = (1, 0)) + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0,)), + size=(1,), nnz=0, layout=torch.sparse_coo) + + # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and + # sparse_dim = 1 + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0, 2)), + size=(1, 2), nnz=0, layout=torch.sparse_coo) + +.. _torch.sparse: https://pytorch.org/docs/stable/sparse.html +""".format(**factory_common_args), +) + +add_docstr( + torch.sqrt, + r""" +sqrt(input, *, out=None) -> Tensor + +Returns a new tensor with the square-root of the elements of :attr:`input`. + +.. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}} +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.sqrt(a) + tensor([ nan, 1.0112, 0.2883, 0.6933]) +""".format(**common_args), +) + +add_docstr( + torch.sqrt_, + r""" +sqrt_(input) -> Tensor + +In-place version of :func:`torch.sqrt` +""", +) + +add_docstr( + torch.square, + r""" +square(input: Tensor, *, out: Optional[Tensor]) -> Tensor + +Returns a new tensor with the square of the elements of :attr:`input`. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.square(a) + tensor([ 4.3077, 1.0457, 0.0069, 0.2310]) +""".format(**common_args), +) + +add_docstr( + torch.square_, + r""" +square_(input) -> Tensor + +In-place version of :func:`torch.square` +""", +) + +add_docstr( + torch.squeeze, + r""" +squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + +Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + +For example, if `input` is of shape: +:math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` +will be of shape: :math:`(A \times B \times C \times D)`. + +When :attr:`dim` is given, a squeeze operation is done only in the given +dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, +``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` +will squeeze the tensor to the shape :math:`(A \times B)`. + +.. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + +.. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + +Args: + {input} + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + +Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) +""".format(**common_args), +) + +add_docstr( + torch.std, + r""" +std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + +Calculates the standard deviation over the dimensions specified by :attr:`dim`. +:attr:`dim` can be a single dimension, list of dimensions, or ``None`` to +reduce over all dimensions. + +The standard deviation (:math:`\sigma`) is calculated as + +.. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + +where :math:`x` is the sample set of elements, :math:`\bar{x}` is the +sample mean, :math:`N` is the number of samples and :math:`\delta N` is +the :attr:`correction`. +""" + + r""" + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + +Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + {opt_keepdim} + {out} + +Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + +.. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + +""".format(**multi_dim_common), +) + +add_docstr( + torch.std_mean, + r""" +std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + +Calculates the standard deviation and mean over the dimensions specified by +:attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or +``None`` to reduce over all dimensions. + +The standard deviation (:math:`\sigma`) is calculated as + +.. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + +where :math:`x` is the sample set of elements, :math:`\bar{x}` is the +sample mean, :math:`N` is the number of samples and :math:`\delta N` is +the :attr:`correction`. + +""" + + r""" + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + +Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + {opt_keepdim} + {out} + +Returns: + A tuple (std, mean) containing the standard deviation and mean. + +Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + +.. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + +""".format(**multi_dim_common), +) + +add_docstr( + torch.sub, + r""" +sub(input, other, *, alpha=1, out=None) -> Tensor + +Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + +.. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i +""" + + r""" + +Supports :ref:`broadcasting to a common shape `, +:ref:`type promotion `, and integer, float, and complex inputs. + +Args: + {input} + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + +Keyword args: + alpha (Number): the multiplier for :attr:`other`. + {out} + +Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) +""".format(**common_args), +) + +add_docstr( + torch.subtract, + r""" +subtract(input, other, *, alpha=1, out=None) -> Tensor + +Alias for :func:`torch.sub`. +""", +) + +add_docstr( + torch.sum, + r""" +sum(input, *, dtype=None) -> Tensor + +Returns the sum of all elements in the :attr:`input` tensor. + +Args: + {input} + +Keyword args: + {dtype} + +.. note:: Use the `dtype` argument if you need the result in a specific tensor type. + Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`). + +Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + +.. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + +Returns the sum of each row of the :attr:`input` tensor in the given +dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, +reduce over all of them. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) +""".format(**multi_dim_common), +) + +add_docstr( + torch.nansum, + r""" +nansum(input, *, dtype=None) -> Tensor + +Returns the sum of all elements, treating Not a Numbers (NaNs) as zero. + +Args: + {input} + +Keyword args: + {dtype} + +Example:: + + >>> a = torch.tensor([1., 2., float('nan'), 4.]) + >>> torch.nansum(a) + tensor(7.) + +.. function:: nansum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + +Returns the sum of each row of the :attr:`input` tensor in the given +dimension :attr:`dim`, treating Not a Numbers (NaNs) as zero. +If :attr:`dim` is a list of dimensions, reduce over all of them. + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + {opt_keepdim} + +Keyword args: + {dtype} + +Example:: + + >>> torch.nansum(torch.tensor([1., float("nan")])) + tensor(1.) + >>> a = torch.tensor([[1, 2], [3., float("nan")]]) + >>> torch.nansum(a) + tensor(6.) + >>> torch.nansum(a, dim=0) + tensor([4., 2.]) + >>> torch.nansum(a, dim=1) + tensor([3., 3.]) +""".format(**multi_dim_common), +) + +add_docstr( + torch.svd, + r""" +svd(input, some=True, compute_uv=True, *, out=None) -> (Tensor, Tensor, Tensor) + +Computes the singular value decomposition of either a matrix or batch of +matrices :attr:`input`. The singular value decomposition is represented as a +namedtuple `(U, S, V)`, such that :attr:`input` :math:`= U \text{diag}(S) V^{\text{H}}`. +where :math:`V^{\text{H}}` is the transpose of `V` for real inputs, +and the conjugate transpose of `V` for complex inputs. +If :attr:`input` is a batch of matrices, then `U`, `S`, and `V` are also +batched with the same batch dimensions as :attr:`input`. + +If :attr:`some` is `True` (default), the method returns the reduced singular +value decomposition. In this case, if the last two dimensions of :attr:`input` are +`m` and `n`, then the returned `U` and `V` matrices will contain only +`min(n, m)` orthonormal columns. + +If :attr:`compute_uv` is `False`, the returned `U` and `V` will be +zero-filled matrices of shape `(m, m)` and `(n, n)` +respectively, and the same device as :attr:`input`. The argument :attr:`some` +has no effect when :attr:`compute_uv` is `False`. + +Supports :attr:`input` of float, double, cfloat and cdouble data types. +The dtypes of `U` and `V` are the same as :attr:`input`'s. `S` will +always be real-valued, even if :attr:`input` is complex. + +.. warning:: + + :func:`torch.svd` is deprecated in favor of :func:`torch.linalg.svd` + and will be removed in a future PyTorch release. + + ``U, S, V = torch.svd(A, some=some, compute_uv=True)`` (default) should be replaced with + + .. code:: python + + U, S, Vh = torch.linalg.svd(A, full_matrices=not some) + V = Vh.mH + + ``_, S, _ = torch.svd(A, some=some, compute_uv=False)`` should be replaced with + + .. code:: python + + S = torch.linalg.svdvals(A) + +.. note:: Differences with :func:`torch.linalg.svd`: + + * :attr:`some` is the opposite of + :func:`torch.linalg.svd`'s :attr:`full_matrices`. Note that + default value for both is `True`, so the default behavior is + effectively the opposite. + * :func:`torch.svd` returns `V`, whereas :func:`torch.linalg.svd` returns + `Vh`, that is, :math:`V^{\text{H}}`. + * If :attr:`compute_uv` is `False`, :func:`torch.svd` returns zero-filled + tensors for `U` and `Vh`, whereas :func:`torch.linalg.svd` returns + empty tensors. + +.. note:: The singular values are returned in descending order. If :attr:`input` is a batch of matrices, + then the singular values of each matrix in the batch are returned in descending order. + +.. note:: The `S` tensor can only be used to compute gradients if :attr:`compute_uv` is `True`. + +.. note:: When :attr:`some` is `False`, the gradients on `U[..., :, min(m, n):]` + and `V[..., :, min(m, n):]` will be ignored in the backward pass, as those vectors + can be arbitrary bases of the corresponding subspaces. + +.. note:: The implementation of :func:`torch.linalg.svd` on CPU uses LAPACK's routine `?gesdd` + (a divide-and-conquer algorithm) instead of `?gesvd` for speed. Analogously, + on GPU, it uses cuSOLVER's routines `gesvdj` and `gesvdjBatched`. + +.. note:: The returned `U` will not be contiguous. The matrix (or batch of matrices) will + be represented as a column-major matrix (i.e. Fortran-contiguous). + +.. warning:: The gradients with respect to `U` and `V` will only be finite when the input does not + have zero nor repeated singular values. + +.. warning:: If the distance between any two singular values is close to zero, the gradients with respect to + `U` and `V` will be numerically unstable, as they depends on + :math:`\frac{1}{\min_{i \neq j} \sigma_i^2 - \sigma_j^2}`. The same happens when the matrix + has small singular values, as these gradients also depend on `S^{-1}`. + +.. warning:: For complex-valued :attr:`input` the singular value decomposition is not unique, + as `U` and `V` may be multiplied by an arbitrary phase factor :math:`e^{i \phi}` on every column. + The same happens when :attr:`input` has repeated singular values, where one may multiply + the columns of the spanning subspace in `U` and `V` by a rotation matrix + and `the resulting vectors will span the same subspace`_. + Different platforms, like NumPy, or inputs on different device types, + may produce different `U` and `V` tensors. + +Args: + input (Tensor): the input tensor of size `(*, m, n)` where `*` is zero or more + batch dimensions consisting of `(m, n)` matrices. + some (bool, optional): controls whether to compute the reduced or full decomposition, and + consequently, the shape of returned `U` and `V`. Default: `True`. + compute_uv (bool, optional): controls whether to compute `U` and `V`. Default: `True`. + +Keyword args: + out (tuple, optional): the output tuple of tensors + +Example:: + + >>> a = torch.randn(5, 3) + >>> a + tensor([[ 0.2364, -0.7752, 0.6372], + [ 1.7201, 0.7394, -0.0504], + [-0.3371, -1.0584, 0.5296], + [ 0.3550, -0.4022, 1.5569], + [ 0.2445, -0.0158, 1.1414]]) + >>> u, s, v = torch.svd(a) + >>> u + tensor([[ 0.4027, 0.0287, 0.5434], + [-0.1946, 0.8833, 0.3679], + [ 0.4296, -0.2890, 0.5261], + [ 0.6604, 0.2717, -0.2618], + [ 0.4234, 0.2481, -0.4733]]) + >>> s + tensor([2.3289, 2.0315, 0.7806]) + >>> v + tensor([[-0.0199, 0.8766, 0.4809], + [-0.5080, 0.4054, -0.7600], + [ 0.8611, 0.2594, -0.4373]]) + >>> torch.dist(a, torch.mm(torch.mm(u, torch.diag(s)), v.t())) + tensor(8.6531e-07) + >>> a_big = torch.randn(7, 5, 3) + >>> u, s, v = torch.svd(a_big) + >>> torch.dist(a_big, torch.matmul(torch.matmul(u, torch.diag_embed(s)), v.mT)) + tensor(2.6503e-06) + +.. _the resulting vectors will span the same subspace: + (https://en.wikipedia.org/wiki/Singular_value_decomposition#Singular_values,_singular_vectors,_and_their_relation_to_the_SVD) +""", +) + + +add_docstr( + torch.t, + r""" +t(input) -> Tensor + +Expects :attr:`input` to be <= 2-D tensor and transposes dimensions 0 +and 1. + +0-D and 1-D tensors are returned as is. When input is a 2-D tensor this +is equivalent to ``transpose(input, 0, 1)``. + +Args: + {input} + +Example:: + + >>> x = torch.randn(()) + >>> x + tensor(0.1995) + >>> torch.t(x) + tensor(0.1995) + >>> x = torch.randn(3) + >>> x + tensor([ 2.4320, -0.4608, 0.7702]) + >>> torch.t(x) + tensor([ 2.4320, -0.4608, 0.7702]) + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.4875, 0.9158, -0.5872], + [ 0.3938, -0.6929, 0.6932]]) + >>> torch.t(x) + tensor([[ 0.4875, 0.3938], + [ 0.9158, -0.6929], + [-0.5872, 0.6932]]) + +See also :func:`torch.transpose`. +""".format(**common_args), +) + +add_docstr( + torch.flip, + r""" +flip(input, dims) -> Tensor + +Reverse the order of an n-D tensor along given axis in dims. + +.. note:: + `torch.flip` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flip`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flip` is expected to be slower than `np.flip`. + +Args: + {input} + dims (a list or tuple): axis to flip on + +Example:: + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[ 0, 1], + [ 2, 3]], + + [[ 4, 5], + [ 6, 7]]]) + >>> torch.flip(x, [0, 1]) + tensor([[[ 6, 7], + [ 4, 5]], + + [[ 2, 3], + [ 0, 1]]]) +""".format(**common_args), +) + +add_docstr( + torch.fliplr, + r""" +fliplr(input) -> Tensor + +Flip tensor in the left/right direction, returning a new tensor. + +Flip the entries in each row in the left/right direction. +Columns are preserved, but appear in a different order than before. + +Note: + Requires the tensor to be at least 2-D. + +.. note:: + `torch.fliplr` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.fliplr`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.fliplr` is expected to be slower than `np.fliplr`. + +Args: + input (Tensor): Must be at least 2-dimensional. + +Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.fliplr(x) + tensor([[1, 0], + [3, 2]]) +""".format(**common_args), +) + +add_docstr( + torch.flipud, + r""" +flipud(input) -> Tensor + +Flip tensor in the up/down direction, returning a new tensor. + +Flip the entries in each column in the up/down direction. +Rows are preserved, but appear in a different order than before. + +Note: + Requires the tensor to be at least 1-D. + +.. note:: + `torch.flipud` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flipud`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flipud` is expected to be slower than `np.flipud`. + +Args: + input (Tensor): Must be at least 1-dimensional. + +Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.flipud(x) + tensor([[2, 3], + [0, 1]]) +""".format(**common_args), +) + +add_docstr( + torch.roll, + r""" +roll(input, shifts, dims=None) -> Tensor + +Roll the tensor :attr:`input` along the given dimension(s). Elements that are +shifted beyond the last position are re-introduced at the first position. If +:attr:`dims` is `None`, the tensor will be flattened before rolling and then +restored to the original shape. + +Args: + {input} + shifts (int or tuple of ints): The number of places by which the elements + of the tensor are shifted. If shifts is a tuple, dims must be a tuple of + the same size, and each dimension will be rolled by the corresponding + value + dims (int or tuple of ints): Axis along which to roll + +Example:: + + >>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2) + >>> x + tensor([[1, 2], + [3, 4], + [5, 6], + [7, 8]]) + >>> torch.roll(x, 1) + tensor([[8, 1], + [2, 3], + [4, 5], + [6, 7]]) + >>> torch.roll(x, 1, 0) + tensor([[7, 8], + [1, 2], + [3, 4], + [5, 6]]) + >>> torch.roll(x, -1, 0) + tensor([[3, 4], + [5, 6], + [7, 8], + [1, 2]]) + >>> torch.roll(x, shifts=(2, 1), dims=(0, 1)) + tensor([[6, 5], + [8, 7], + [2, 1], + [4, 3]]) +""".format(**common_args), +) + +add_docstr( + torch.rot90, + r""" +rot90(input, k=1, dims=(0, 1)) -> Tensor + +Rotate an n-D tensor by 90 degrees in the plane specified by dims axis. +Rotation direction is from the first towards the second axis if k > 0, and from the second towards the first for k < 0. + +Args: + {input} + k (int): number of times to rotate. Default value is 1 + dims (a list or tuple): axis to rotate. Default value is [0, 1] + +Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.rot90(x, 1, [0, 1]) + tensor([[1, 3], + [0, 2]]) + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.rot90(x, 1, [1, 2]) + tensor([[[1, 3], + [0, 2]], + + [[5, 7], + [4, 6]]]) +""".format(**common_args), +) + +add_docstr( + torch.take, + r""" +take(input, index) -> Tensor + +Returns a new tensor with the elements of :attr:`input` at the given indices. +The input tensor is treated as if it were viewed as a 1-D tensor. The result +takes the same shape as the indices. + +Args: + {input} + index (LongTensor): the indices into tensor + +Example:: + + >>> src = torch.tensor([[4, 3, 5], + ... [6, 7, 8]]) + >>> torch.take(src, torch.tensor([0, 2, 5])) + tensor([ 4, 5, 8]) +""".format(**common_args), +) + +add_docstr( + torch.take_along_dim, + r""" +take_along_dim(input, indices, dim=None, *, out=None) -> Tensor + +Selects values from :attr:`input` at the 1-dimensional indices from :attr:`indices` along the given :attr:`dim`. + +If :attr:`dim` is None, the input array is treated as if it has been flattened to 1d. + +Functions that return indices along a dimension, like :func:`torch.argmax` and :func:`torch.argsort`, +are designed to work with this function. See the examples below. + +.. note:: + This function is similar to NumPy's `take_along_axis`. + See also :func:`torch.gather`. + +Args: + {input} + indices (LongTensor): the indices into :attr:`input`. Must have long dtype. + dim (int, optional): dimension to select along. Default: `None`. + +Keyword args: + {out} + +Example:: + + >>> t = torch.tensor([[10, 30, 20], [60, 40, 50]]) + >>> max_idx = torch.argmax(t) + >>> torch.take_along_dim(t, max_idx) + tensor([60]) + >>> sorted_idx = torch.argsort(t, dim=1) + >>> torch.take_along_dim(t, sorted_idx, dim=1) + tensor([[10, 20, 30], + [40, 50, 60]]) +""".format(**common_args), +) + +add_docstr( + torch.tan, + r""" +tan(input, *, out=None) -> Tensor + +Returns a new tensor with the tangent of the elements in the :attr:`input` tensor, +where each value in this input tensor is in radians. + +.. math:: + \text{out}_{i} = \tan(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.2027, -1.7687, 0.4412, -1.3856]) + >>> torch.tan(a) + tensor([-2.5930, 4.9859, 0.4722, -5.3366]) +""".format(**common_args), +) + +add_docstr( + torch.tan_, + r""" +tan_(input) -> Tensor + +In-place version of :func:`torch.tan` +""", +) + +add_docstr( + torch.tanh, + r""" +tanh(input, *, out=None) -> Tensor + +Returns a new tensor with the hyperbolic tangent of the elements +of :attr:`input`. + +.. math:: + \text{out}_{i} = \tanh(\text{input}_{i}) +""" + + r""" +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.8986, -0.7279, 1.1745, 0.2611]) + >>> torch.tanh(a) + tensor([ 0.7156, -0.6218, 0.8257, 0.2553]) +""".format(**common_args), +) + +add_docstr( + torch.tanh_, + r""" +tanh_(input) -> Tensor + +In-place version of :func:`torch.tanh` +""", +) + +add_docstr( + # torch.softmax doc str. Point this to torch.nn.functional.softmax + torch.softmax, + r""" +softmax(input, dim, *, dtype=None) -> Tensor + +Alias for :func:`torch.nn.functional.softmax`. +""", +) + +add_docstr( + torch.topk, + r""" +topk(input, k, dim=None, largest=True, sorted=True, *, out=None) -> (Tensor, LongTensor) + +Returns the :attr:`k` largest elements of the given :attr:`input` tensor along +a given dimension. + +If :attr:`dim` is not given, the last dimension of the `input` is chosen. + +If :attr:`largest` is ``False`` then the `k` smallest elements are returned. + +A namedtuple of `(values, indices)` is returned with the `values` and +`indices` of the largest `k` elements of each row of the `input` tensor in the +given dimension `dim`. + +The boolean option :attr:`sorted` if ``True``, will make sure that the returned +`k` elements are themselves sorted + +.. note:: + When using `torch.topk`, the indices of tied elements are not guaranteed to be stable + and may vary across different invocations. + +Args: + {input} + k (int): the k in "top-k" + dim (int, optional): the dimension to sort along + largest (bool, optional): controls whether to return largest or + smallest elements + sorted (bool, optional): controls whether to return the elements + in sorted order + +Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) that can be + optionally given to be used as output buffers + +Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.topk(x, 3) + torch.return_types.topk(values=tensor([5., 4., 3.]), indices=tensor([4, 3, 2])) +""".format(**common_args), +) + +add_docstr( + torch.trace, + r""" +trace(input) -> Tensor + +Returns the sum of the elements of the diagonal of the input 2-D matrix. + +Example:: + + >>> x = torch.arange(1., 10.).view(3, 3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.], + [ 7., 8., 9.]]) + >>> torch.trace(x) + tensor(15.) +""", +) + +add_docstr( + torch.transpose, + r""" +transpose(input, dim0, dim1) -> Tensor + +Returns a tensor that is a transposed version of :attr:`input`. +The given dimensions :attr:`dim0` and :attr:`dim1` are swapped. + +If :attr:`input` is a strided tensor then the resulting :attr:`out` +tensor shares its underlying storage with the :attr:`input` tensor, so +changing the content of one would change the content of the other. + +If :attr:`input` is a :ref:`sparse tensor ` then the +resulting :attr:`out` tensor *does not* share the underlying storage +with the :attr:`input` tensor. + +If :attr:`input` is a :ref:`sparse tensor ` with compressed +layout (SparseCSR, SparseBSR, SparseCSC or SparseBSC) the arguments +:attr:`dim0` and :attr:`dim1` must be both batch dimensions, or must +both be sparse dimensions. The batch dimensions of a sparse tensor are the +dimensions preceding the sparse dimensions. + +.. note:: + Transpositions which interchange the sparse dimensions of a `SparseCSR` + or `SparseCSC` layout tensor will result in the layout changing between + the two options. Transposition of the sparse dimensions of a ` SparseBSR` + or `SparseBSC` layout tensor will likewise generate a result with the + opposite layout. + + +Args: + {input} + dim0 (int): the first dimension to be transposed + dim1 (int): the second dimension to be transposed + +Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 1.0028, -0.9893, 0.5809], + [-0.1669, 0.7299, 0.4942]]) + >>> torch.transpose(x, 0, 1) + tensor([[ 1.0028, -0.1669], + [-0.9893, 0.7299], + [ 0.5809, 0.4942]]) + +See also :func:`torch.t`. +""".format(**common_args), +) + +add_docstr( + torch.triangular_solve, + r""" +triangular_solve(b, A, upper=True, transpose=False, unitriangular=False, *, out=None) -> (Tensor, Tensor) + +Solves a system of equations with a square upper or lower triangular invertible matrix :math:`A` +and multiple right-hand sides :math:`b`. + +In symbols, it solves :math:`AX = b` and assumes :math:`A` is square upper-triangular +(or lower-triangular if :attr:`upper`\ `= False`) and does not have zeros on the diagonal. + +`torch.triangular_solve(b, A)` can take in 2D inputs `b, A` or inputs that are +batches of 2D matrices. If the inputs are batches, then returns +batched outputs `X` + +If the diagonal of :attr:`A` contains zeros or elements that are very close to zero and +:attr:`unitriangular`\ `= False` (default) or if the input matrix is badly conditioned, +the result may contain `NaN` s. + +Supports input of float, double, cfloat and cdouble data types. + +.. warning:: + + :func:`torch.triangular_solve` is deprecated in favor of :func:`torch.linalg.solve_triangular` + and will be removed in a future PyTorch release. + :func:`torch.linalg.solve_triangular` has its arguments reversed and does not return a + copy of one of the inputs. + + ``X = torch.triangular_solve(B, A).solution`` should be replaced with + + .. code:: python + + X = torch.linalg.solve_triangular(A, B) + +Args: + b (Tensor): multiple right-hand sides of size :math:`(*, m, k)` where + :math:`*` is zero of more batch dimensions + A (Tensor): the input triangular coefficient matrix of size :math:`(*, m, m)` + where :math:`*` is zero or more batch dimensions + upper (bool, optional): whether :math:`A` is upper or lower triangular. Default: ``True``. + transpose (bool, optional): solves `op(A)X = b` where `op(A) = A^T` if this flag is ``True``, + and `op(A) = A` if it is ``False``. Default: ``False``. + unitriangular (bool, optional): whether :math:`A` is unit triangular. + If True, the diagonal elements of :math:`A` are assumed to be + 1 and not referenced from :math:`A`. Default: ``False``. + +Keyword args: + out ((Tensor, Tensor), optional): tuple of two tensors to write + the output to. Ignored if `None`. Default: `None`. + +Returns: + A namedtuple `(solution, cloned_coefficient)` where `cloned_coefficient` + is a clone of :math:`A` and `solution` is the solution :math:`X` to :math:`AX = b` + (or whatever variant of the system of equations, depending on the keyword arguments.) + +Examples:: + + >>> A = torch.randn(2, 2).triu() + >>> A + tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]]) + >>> b = torch.randn(2, 3) + >>> b + tensor([[-0.0210, 2.3513, -1.5492], + [ 1.5429, 0.7403, -1.0243]]) + >>> torch.triangular_solve(b, A) + torch.return_types.triangular_solve( + solution=tensor([[ 1.7841, 2.9046, -2.5405], + [ 1.9320, 0.9270, -1.2826]]), + cloned_coefficient=tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]])) +""", +) + +add_docstr( + torch.tril, + r""" +tril(input, diagonal=0, *, out=None) -> Tensor + +Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices +:attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + +The lower triangular part of the matrix is defined as the elements on and +below the diagonal. + +The argument :attr:`diagonal` controls which diagonal to consider. If +:attr:`diagonal` = 0, all elements on and below the main diagonal are +retained. A positive value includes just as many diagonals above the main +diagonal, and similarly a negative value excludes just as many diagonals below +the main diagonal. The main diagonal are the set of indices +:math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where +:math:`d_{1}, d_{2}` are the dimensions of the matrix. +""" + + r""" +Args: + {input} + diagonal (int, optional): the diagonal to consider + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0813, -0.8619, 0.7105], + [ 0.0935, 0.1380, 2.2112], + [-0.3409, -0.9828, 0.0289]]) + >>> torch.tril(a) + tensor([[-1.0813, 0.0000, 0.0000], + [ 0.0935, 0.1380, 0.0000], + [-0.3409, -0.9828, 0.0289]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 1.2219, 0.5653, -0.2521, -0.2345, 1.2544, 0.3461], + [ 0.4785, -0.4477, 0.6049, 0.6368, 0.8775, 0.7145], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.3615, 0.6864], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0978]]) + >>> torch.tril(b, diagonal=1) + tensor([[ 1.2219, 0.5653, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, -0.4477, 0.6049, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0000]]) + >>> torch.tril(b, diagonal=-1) + tensor([[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, 0.0000, 0.0000, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, 0.0000, 0.0000, 0.0000]]) +""".format(**common_args), +) + +# docstr is split in two parts to avoid format mis-captureing :math: braces '{}' +# as common args. +add_docstr( + torch.tril_indices, + r""" +tril_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + +Returns the indices of the lower triangular part of a :attr:`row`-by- +:attr:`col` matrix in a 2-by-N Tensor, where the first row contains row +coordinates of all indices and the second row contains column coordinates. +Indices are ordered based on rows and then columns. + +The lower triangular part of the matrix is defined as the elements on and +below the diagonal. + +The argument :attr:`offset` controls which diagonal to consider. If +:attr:`offset` = 0, all elements on and below the main diagonal are +retained. A positive value includes just as many diagonals above the main +diagonal, and similarly a negative value excludes just as many diagonals below +the main diagonal. The main diagonal are the set of indices +:math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` +where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + +.. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. +""" + + r""" +Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + {device} + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + +Example:: + + >>> a = torch.tril_indices(3, 3) + >>> a + tensor([[0, 1, 1, 2, 2, 2], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, -1) + >>> a + tensor([[1, 2, 2, 3, 3, 3], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], + [0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.triu, + r""" +triu(input, diagonal=0, *, out=None) -> Tensor + +Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices +:attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + +The upper triangular part of the matrix is defined as the elements on and +above the diagonal. + +The argument :attr:`diagonal` controls which diagonal to consider. If +:attr:`diagonal` = 0, all elements on and above the main diagonal are +retained. A positive value excludes just as many diagonals above the main +diagonal, and similarly a negative value includes just as many diagonals below +the main diagonal. The main diagonal are the set of indices +:math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where +:math:`d_{1}, d_{2}` are the dimensions of the matrix. +""" + + r""" +Args: + {input} + diagonal (int, optional): the diagonal to consider + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.3480, -0.5211, -0.4573]]) + >>> torch.triu(a) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.0000, -1.0680, 0.6602], + [ 0.0000, 0.0000, -0.4573]]) + >>> torch.triu(a, diagonal=1) + tensor([[ 0.0000, 0.5207, 2.0049], + [ 0.0000, 0.0000, 0.6602], + [ 0.0000, 0.0000, 0.0000]]) + >>> torch.triu(a, diagonal=-1) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.0000, -0.5211, -0.4573]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.4333, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [-0.9888, 1.0679, -1.3337, -1.6556, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=1) + tensor([[ 0.0000, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [ 0.0000, 0.0000, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.0000, 0.0000, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=-1) + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, -1.3337, -1.6556, 0.4798, 0.2830]]) +""".format(**common_args), +) + +# docstr is split in two parts to avoid format mis-capturing :math: braces '{}' +# as common args. +add_docstr( + torch.triu_indices, + r""" +triu_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + +Returns the indices of the upper triangular part of a :attr:`row` by +:attr:`col` matrix in a 2-by-N Tensor, where the first row contains row +coordinates of all indices and the second row contains column coordinates. +Indices are ordered based on rows and then columns. + +The upper triangular part of the matrix is defined as the elements on and +above the diagonal. + +The argument :attr:`offset` controls which diagonal to consider. If +:attr:`offset` = 0, all elements on and above the main diagonal are +retained. A positive value excludes just as many diagonals above the main +diagonal, and similarly a negative value includes just as many diagonals below +the main diagonal. The main diagonal are the set of indices +:math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` +where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + +.. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. +""" + + r""" +Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + +Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + {device} + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + +Example:: + + >>> a = torch.triu_indices(3, 3) + >>> a + tensor([[0, 0, 0, 1, 1, 2], + [0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, -1) + >>> a + tensor([[0, 0, 0, 1, 1, 1, 2, 2, 3], + [0, 1, 2, 0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1], + [1, 2, 2]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.true_divide, + r""" +true_divide(dividend, divisor, *, out) -> Tensor + +Alias for :func:`torch.div` with ``rounding_mode=None``. +""", +) + +add_docstr( + torch.trunc, + r""" +trunc(input, *, out=None) -> Tensor + +Returns a new tensor with the truncated integer values of +the elements of :attr:`input`. + +For integer inputs, follows the array-api convention of returning a +copy of the input tensor. + +Args: + {input} + +Keyword args: + {out} + +Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 3.4742, 0.5466, -0.8008, -0.9079]) + >>> torch.trunc(a) + tensor([ 3., 0., -0., -0.]) +""".format(**common_args), +) + +add_docstr( + torch.trunc_, + r""" +trunc_(input) -> Tensor + +In-place version of :func:`torch.trunc` +""", +) + +add_docstr( + torch.fake_quantize_per_tensor_affine, + r""" +fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + +Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, +:attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + +.. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + +Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + +Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + +Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) +""", +) + +add_docstr( + torch.fake_quantize_per_channel_affine, + r""" +fake_quantize_per_channel_affine(input, scale, zero_point, axis, quant_min, quant_max) -> Tensor + +Returns a new tensor with the data in :attr:`input` fake quantized per channel using :attr:`scale`, +:attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`, across the channel specified by :attr:`axis`. + +.. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + +Args: + input (Tensor): the input value(s), in ``torch.float32`` + scale (Tensor): quantization scale, per channel in ``torch.float32`` + zero_point (Tensor): quantization zero_point, per channel in ``torch.int32`` or ``torch.half`` or ``torch.float32`` + axis (int32): channel axis + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + +Returns: + Tensor: A newly fake_quantized per channel ``torch.float32`` tensor + +Example:: + + >>> x = torch.randn(2, 2, 2) + >>> x + tensor([[[-0.2525, -0.0466], + [ 0.3491, -0.2168]], + + [[-0.5906, 1.6258], + [ 0.6444, -0.0542]]]) + >>> scales = (torch.randn(2) + 1) * 0.05 + >>> scales + tensor([0.0475, 0.0486]) + >>> zero_points = torch.zeros(2).to(torch.int32) + >>> zero_points + tensor([0, 0]) + >>> torch.fake_quantize_per_channel_affine(x, scales, zero_points, 1, 0, 255) + tensor([[[0.0000, 0.0000], + [0.3405, 0.0000]], + + [[0.0000, 1.6134], + [0.6323, 0.0000]]]) +""", +) + +add_docstr( + torch.fill_, + r""" +fill_(input, value) -> Tensor + +In-place version of :func:`torch.fill` +""", +) + +add_docstr( + torch.fix, + r""" +fix(input, *, out=None) -> Tensor + +Alias for :func:`torch.trunc` +""", +) + +add_docstr( + torch.fix_, + r""" +fix_(input) -> Tensor + +In-place version of :func:`torch.fix` +""", +) + +add_docstr( + torch.unsqueeze, + r""" +unsqueeze(input, dim) -> Tensor + +Returns a new tensor with a dimension of size one inserted at the +specified position. + +The returned tensor shares the same underlying data with this tensor. + +A :attr:`dim` value within the range ``[-input.dim() - 1, input.dim() + 1)`` +can be used. Negative :attr:`dim` will correspond to :meth:`unsqueeze` +applied at :attr:`dim` = ``dim + input.dim() + 1``. + +Args: + {input} + dim (int): the index at which to insert the singleton dimension + +Example:: + + >>> x = torch.tensor([1, 2, 3, 4]) + >>> torch.unsqueeze(x, 0) + tensor([[ 1, 2, 3, 4]]) + >>> torch.unsqueeze(x, 1) + tensor([[ 1], + [ 2], + [ 3], + [ 4]]) +""".format(**common_args), +) + +add_docstr( + torch.var, + r""" +var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + +Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` +can be a single dimension, list of dimensions, or ``None`` to reduce over all +dimensions. + +The variance (:math:`\sigma^2`) is calculated as + +.. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + +where :math:`x` is the sample set of elements, :math:`\bar{x}` is the +sample mean, :math:`N` is the number of samples and :math:`\delta N` is +the :attr:`correction`. +""" + + r""" + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + +Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + {opt_keepdim} + {out} + +Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + +.. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + +""".format(**multi_dim_common), +) + +add_docstr( + torch.var_mean, + r""" +var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + +Calculates the variance and mean over the dimensions specified by :attr:`dim`. +:attr:`dim` can be a single dimension, list of dimensions, or ``None`` to +reduce over all dimensions. + +The variance (:math:`\sigma^2`) is calculated as + +.. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + +where :math:`x` is the sample set of elements, :math:`\bar{x}` is the +sample mean, :math:`N` is the number of samples and :math:`\delta N` is +the :attr:`correction`. +""" + + r""" + +{keepdim_details} + +Args: + {input} + {opt_dim_all_reduce} + +Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + {opt_keepdim} + {out} + +Returns: + A tuple (var, mean) containing the variance and mean. + +Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + +.. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + +""".format(**multi_dim_common), +) + +add_docstr( + torch.zeros, + r""" +zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Returns a tensor filled with the scalar value `0`, with the shape defined +by the variable argument :attr:`size`. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword args: + {out} + {dtype} + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) +""".format(**factory_common_args), +) + +add_docstr( + torch.zeros_like, + r""" +zeros_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + +Returns a tensor filled with the scalar value `0`, with the same size as +:attr:`input`. ``torch.zeros_like(input)`` is equivalent to +``torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +.. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.zeros_like(input, out=output)`` is equivalent to + ``torch.zeros(input.size(), out=output)``. + +Args: + {input} + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +Example:: + + >>> input = torch.empty(2, 3) + >>> torch.zeros_like(input) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) +""".format(**factory_like_common_args), +) + +add_docstr( + torch.empty, + """ +empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, \ +memory_format=torch.contiguous_format) -> Tensor + +Returns a tensor filled with uninitialized data. The shape of the tensor is +defined by the variable argument :attr:`size`. + +.. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + +Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + +Keyword args: + {out} + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + {memory_format} + +Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.empty_like, + r""" +empty_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + +Returns an uninitialized tensor with the same size as :attr:`input`. +``torch.empty_like(input)`` is equivalent to +``torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + +.. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + When ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense format. + +Args: + {input} + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +Example:: + + >>> a=torch.empty((2,3), dtype=torch.int32, device = 'cuda') + >>> torch.empty_like(a) + tensor([[0, 0, 0], + [0, 0, 0]], device='cuda:0', dtype=torch.int32) +""".format(**factory_like_common_args), +) + +add_docstr( + torch.empty_strided, + r""" +empty_strided(size, stride, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + +Creates a tensor with the specified :attr:`size` and :attr:`stride` and filled with undefined data. + +.. warning:: + If the constructed tensor is "overlapped" (with multiple indices referring to the same element + in memory) its behavior is undefined. + +.. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + +Args: + size (tuple of int): the shape of the output tensor + stride (tuple of int): the strides of the output tensor + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Example:: + + >>> a = torch.empty_strided((2, 3), (1, 2)) + >>> a + tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07], + [0.0000e+00, 0.0000e+00, 3.0705e-41]]) + >>> a.stride() + (1, 2) + >>> a.size() + torch.Size([2, 3]) +""".format(**factory_common_args), +) + +add_docstr( + torch.empty_permuted, + r""" +empty_permuted(size, physical_layout, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + +Creates an uninitialized, non-overlapping and dense tensor with the +specified :attr:`size`, with :attr:`physical_layout` specifying how the +dimensions are physically laid out in memory (each logical dimension is listed +from outermost to innermost). :attr:`physical_layout` is a generalization +of NCHW/NHWC notation: if each dimension is assigned a number according to +what order they occur in size (N=0, C=1, H=2, W=3), then NCHW is ``(0, 1, 2, 3)`` +while NHWC is ``(0, 2, 3, 1)``. Equivalently, the strides of the output +tensor ``t`` are such that ``t.stride(physical_layout[i]) == contiguous_strides[i]`` +(notably, this function is *not* equivalent to ``torch.empty(size).permute(physical_layout)``). + +Unlike :func:`torch.empty_strided`, this is guaranteed to produce a dense +tensor with no overlaps. If possible, prefer using this function over +:func:`torch.empty_strided` or manual use of :func:`torch.as_strided`. + +.. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + +Args: + size (tuple of int): the shape of the output tensor + physical_layout (tuple of int): the ordering of dimensions physically in memory + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {pin_memory} + +Examples: + + >>> torch.empty((2, 3, 5, 7)).stride() + (105, 35, 7, 1) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 1, 2, 3)).stride() + (105, 35, 7, 1) + >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).dim_order() + (0, 2, 3, 1) +""".format(**factory_common_args), +) + +add_docstr( + torch.full, + r""" +full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + +Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The +tensor's dtype is inferred from :attr:`fill_value`. + +Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + +Keyword args: + {out} + {dtype} + {layout} + {device} + {requires_grad} + +Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) +""".format(**factory_common_args), +) + +add_docstr( + torch.full_like, + """ +full_like(input, fill_value, \\*, dtype=None, layout=torch.strided, device=None, requires_grad=False, \ +memory_format=torch.preserve_format) -> Tensor + +Returns a tensor with the same size as :attr:`input` filled with :attr:`fill_value`. +``torch.full_like(input, fill_value)`` is equivalent to +``torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device)``. + +Args: + {input} + fill_value: the number to fill the output tensor with. + +Keyword args: + {dtype} + {layout} + {device} + {requires_grad} + {memory_format} + +Example:: + + >>> x = torch.ones(2, 3) + >>> torch.full_like(x, 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + >>> torch.full_like(x, 7) + tensor([[7., 7., 7.], + [7., 7., 7.]]) + >>> torch.full_like(x, 0.5, dtype=torch.int32) + tensor([[0, 0, 0], + [0, 0, 0]], dtype=torch.int32) + >>> y = torch.randn(3, 4, dtype=torch.float64) + >>> torch.full_like(y, -1.0) + tensor([[-1., -1., -1., -1.], + [-1., -1., -1., -1.], + [-1., -1., -1., -1.]], dtype=torch.float64) +""".format(**factory_like_common_args), +) + +add_docstr( + torch.det, + r""" +det(input) -> Tensor + +Alias for :func:`torch.linalg.det` +""", +) + +add_docstr( + torch.where, + r""" +where(condition, input, other, *, out=None) -> Tensor + +Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + +The operation is defined as: + +.. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} +""" + + r""" +.. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + +Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + +Keyword args: + {out} + +Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + +Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + +.. function:: where(condition) -> tuple of LongTensor + :noindex: + +``torch.where(condition)`` is identical to +``torch.nonzero(condition, as_tuple=True)``. + +.. note:: + See also :func:`torch.nonzero`. +""".format(**common_args), +) + +add_docstr( + torch.logdet, + r""" +logdet(input) -> Tensor + +Calculates log determinant of a square matrix or batches of square matrices. + +It returns ``-inf`` if the input has a determinant of zero, and ``NaN`` if it has +a negative determinant. + +.. note:: + Backward through :meth:`logdet` internally uses SVD results when :attr:`input` + is not invertible. In this case, double backward through :meth:`logdet` will + be unstable in when :attr:`input` doesn't have distinct singular values. See + :func:`torch.linalg.svd` for details. + +.. seealso:: + + :func:`torch.linalg.slogdet` computes the sign (resp. angle) and natural logarithm of the + absolute value of the determinant of real-valued (resp. complex) square matrices. + +Arguments: + input (Tensor): the input tensor of size ``(*, n, n)`` where ``*`` is zero or more + batch dimensions. + +Example:: + + >>> A = torch.randn(3, 3) + >>> torch.det(A) + tensor(0.2611) + >>> torch.logdet(A) + tensor(-1.3430) + >>> A + tensor([[[ 0.9254, -0.6213], + [-0.5787, 1.6843]], + + [[ 0.3242, -0.9665], + [ 0.4539, -0.0887]], + + [[ 1.1336, -0.4025], + [-0.7089, 0.9032]]]) + >>> A.det() + tensor([1.1990, 0.4099, 0.7386]) + >>> A.det().log() + tensor([ 0.1815, -0.8917, -0.3031]) +""", +) + +add_docstr( + torch.slogdet, + r""" +slogdet(input) -> (Tensor, Tensor) + +Alias for :func:`torch.linalg.slogdet` +""", +) + +add_docstr( + torch.pinverse, + r""" +pinverse(input, rcond=1e-15) -> Tensor + +Alias for :func:`torch.linalg.pinv` +""", +) + +add_docstr( + torch.hann_window, + """ +hann_window(window_length, periodic=True, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Hann window function. + +.. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + +where :math:`N` is the full window size. + +The input :attr:`window_length` is a positive integer controlling the +returned window size. :attr:`periodic` flag determines whether the returned +window trims off the last duplicate value from the symmetric window and is +ready to be used as a periodic window with functions like +:meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in +above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have +``torch.hann_window(L, periodic=True)`` equal to +``torch.hann_window(L + 1, periodic=False)[:-1])``. + +.. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. +""" + + r""" +Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window + +""".format(**factory_common_args), +) + + +add_docstr( + torch.hamming_window, + """ +hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, \ +requires_grad=False) -> Tensor +""" + + r""" +Hamming window function. + +.. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + +where :math:`N` is the full window size. + +The input :attr:`window_length` is a positive integer controlling the +returned window size. :attr:`periodic` flag determines whether the returned +window trims off the last duplicate value from the symmetric window and is +ready to be used as a periodic window with functions like +:meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in +above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have +``torch.hamming_window(L, periodic=True)`` equal to +``torch.hamming_window(L + 1, periodic=False)[:-1])``. + +.. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + +.. note:: + This is a generalized version of :meth:`torch.hann_window`. +""" + + r""" +Arguments: + window_length (int): the size of returned window + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {pin_memory} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window. + +.. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + +Hamming window function with periodic specified. + +Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {pin_memory} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window. + +.. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + +Hamming window function with periodic and alpha specified. + +Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {pin_memory} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window. + +.. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + +Hamming window function with periodic, alpha and beta specified. + +Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {pin_memory} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window. + +""".format(**factory_common_args), +) + + +add_docstr( + torch.bartlett_window, + """ +bartlett_window(window_length, periodic=True, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Bartlett window function. + +.. math:: + w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases} + \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\ + 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\ + \end{cases}, + +where :math:`N` is the full window size. + +The input :attr:`window_length` is a positive integer controlling the +returned window size. :attr:`periodic` flag determines whether the returned +window trims off the last duplicate value from the symmetric window and is +ready to be used as a periodic window with functions like +:meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in +above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have +``torch.bartlett_window(L, periodic=True)`` equal to +``torch.bartlett_window(L + 1, periodic=False)[:-1])``. + +.. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. +""" + + r""" +Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window + +""".format(**factory_common_args), +) + + +add_docstr( + torch.blackman_window, + """ +blackman_window(window_length, periodic=True, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Blackman window function. + +.. math:: + w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right) + +where :math:`N` is the full window size. + +The input :attr:`window_length` is a positive integer controlling the +returned window size. :attr:`periodic` flag determines whether the returned +window trims off the last duplicate value from the symmetric window and is +ready to be used as a periodic window with functions like +:meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in +above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have +``torch.blackman_window(L, periodic=True)`` equal to +``torch.blackman_window(L + 1, periodic=False)[:-1]``. + +.. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. +""" + + r""" +Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + +Keyword args: + {dtype} Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +Returns: + Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window + +""".format(**factory_common_args), +) + + +add_docstr( + torch.kaiser_window, + """ +kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, \ +layout=torch.strided, device=None, requires_grad=False) -> Tensor +""" + + r""" +Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + +Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and +``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, +where ``L`` is the :attr:`window_length`. This function computes: + +.. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + +Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling +``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. +The :attr:`periodic` argument is intended as a helpful shorthand +to produce a periodic window as input to functions like :func:`torch.stft`. + +.. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + +""" + + r""" +Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + +Keyword args: + {dtype} + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + {device} + {requires_grad} + +""".format(**factory_common_args), +) + + +add_docstr( + torch.vander, + """ +vander(x, N=None, increasing=False) -> Tensor +""" + + r""" +Generates a Vandermonde matrix. + +The columns of the output matrix are elementwise powers of the input vector :math:`x^{{(N-1)}}, x^{{(N-2)}}, ..., x^0`. +If increasing is True, the order of the columns is reversed :math:`x^0, x^1, ..., x^{{(N-1)}}`. Such a +matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde. + +Arguments: + x (Tensor): 1-D input tensor. + N (int, optional): Number of columns in the output. If N is not specified, + a square array is returned :math:`(N = len(x))`. + increasing (bool, optional): Order of the powers of the columns. If True, + the powers increase from left to right, if False (the default) they are reversed. + +Returns: + Tensor: Vandermonde matrix. If increasing is False, the first column is :math:`x^{{(N-1)}}`, + the second :math:`x^{{(N-2)}}` and so forth. If increasing is True, the columns + are :math:`x^0, x^1, ..., x^{{(N-1)}}`. + +Example:: + + >>> x = torch.tensor([1, 2, 3, 5]) + >>> torch.vander(x) + tensor([[ 1, 1, 1, 1], + [ 8, 4, 2, 1], + [ 27, 9, 3, 1], + [125, 25, 5, 1]]) + >>> torch.vander(x, N=3) + tensor([[ 1, 1, 1], + [ 4, 2, 1], + [ 9, 3, 1], + [25, 5, 1]]) + >>> torch.vander(x, N=3, increasing=True) + tensor([[ 1, 1, 1], + [ 1, 2, 4], + [ 1, 3, 9], + [ 1, 5, 25]]) + +""".format(**factory_common_args), +) + + +add_docstr( + torch.unbind, + r""" +unbind(input, dim=0) -> seq + +Removes a tensor dimension. + +Returns a tuple of all slices along a given dimension, already without it. + +Arguments: + input (Tensor): the tensor to unbind + dim (int): dimension to remove + +Example:: + + >>> torch.unbind(torch.tensor([[1, 2, 3], + >>> [4, 5, 6], + >>> [7, 8, 9]])) + (tensor([1, 2, 3]), tensor([4, 5, 6]), tensor([7, 8, 9])) +""", +) + + +add_docstr( + torch.combinations, + r""" +combinations(input: Tensor, r: int = 2, with_replacement: bool = False) -> seq + +Compute combinations of length :math:`r` of the given tensor. The behavior is similar to +python's `itertools.combinations` when `with_replacement` is set to `False`, and +`itertools.combinations_with_replacement` when `with_replacement` is set to `True`. + +Arguments: + input (Tensor): 1D vector. + r (int, optional): number of elements to combine + with_replacement (bool, optional): whether to allow duplication in combination + +Returns: + Tensor: A tensor equivalent to converting all the input tensors into lists, do + `itertools.combinations` or `itertools.combinations_with_replacement` on these + lists, and finally convert the resulting list into tensor. + +Example:: + + >>> a = [1, 2, 3] + >>> list(itertools.combinations(a, r=2)) + [(1, 2), (1, 3), (2, 3)] + >>> list(itertools.combinations(a, r=3)) + [(1, 2, 3)] + >>> list(itertools.combinations_with_replacement(a, r=2)) + [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] + >>> tensor_a = torch.tensor(a) + >>> torch.combinations(tensor_a) + tensor([[1, 2], + [1, 3], + [2, 3]]) + >>> torch.combinations(tensor_a, r=3) + tensor([[1, 2, 3]]) + >>> torch.combinations(tensor_a, with_replacement=True) + tensor([[1, 1], + [1, 2], + [1, 3], + [2, 2], + [2, 3], + [3, 3]]) + +""", +) + +add_docstr( + torch.trapezoid, + r""" +trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + +Computes the `trapezoidal rule `_ along +:attr:`dim`. By default the spacing between elements is assumed to be 1, but +:attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be +used to specify arbitrary spacing along :attr:`dim`. Only one of :attr:`x` or :attr:`dx` should be specified. + + +Assuming :attr:`y` is a one-dimensional tensor with elements :math:`{y_0, y_1, ..., y_n}`, +the default computation is + +.. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{1}{2} (y_i + y_{i-1}) + \end{aligned} + +When :attr:`dx` is specified the computation becomes + +.. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{\Delta x}{2} (y_i + y_{i-1}) + \end{aligned} + +effectively multiplying the result by :attr:`dx`. When :attr:`x` is specified, +assuming :attr:`x` is also a one-dimensional tensor with +elements :math:`{x_0, x_1, ..., x_n}`, the computation becomes + +.. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1}) + \end{aligned} + +When :attr:`x` and :attr:`y` have the same size, the computation is as described above and no broadcasting is needed. +The broadcasting behavior of this function is as follows when their sizes are different. For both :attr:`x` +and :attr:`y`, the function computes the difference between consecutive elements along +dimension :attr:`dim`. This effectively creates two tensors, `x_diff` and `y_diff`, that have +the same shape as the original tensors except their lengths along the dimension :attr:`dim` is reduced by 1. +After that, those two tensors are broadcast together to compute final output as part of the trapezoidal rule. +See the examples below for details. + +.. note:: + The trapezoidal rule is a technique for approximating the definite integral of a function + by averaging its left and right Riemann sums. The approximation becomes more accurate as + the resolution of the partition increases. + +Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + +Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + +Examples:: + + >>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1 + >>> y = torch.tensor([1, 5, 10]) + >>> torch.trapezoid(y) + tensor(10.5) + + >>> # Computes the same trapezoidal rule directly to verify + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.trapezoid(y, dx=2) + 21.0 + + >>> # Computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + 28.5 + + >>> # Computes the same trapezoidal rule directly to verify + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.trapezoid(y) + tensor([ 2., 8., 14.]) + + >>> # Computes the trapezoidal rule for each column of the matrix + >>> torch.trapezoid(y, dim=0) + tensor([ 6., 8., 10.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + array([5., 5., 5.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.trapezoid(y, x) + array([2., 4., 6.]) +""", +) + +add_docstr( + torch.trapz, + r""" +trapz(y, x=None, *, dim=-1) -> Tensor + +Alias for :func:`torch.trapezoid`. +""", +) + +add_docstr( + torch.cumulative_trapezoid, + r""" +cumulative_trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + +Cumulatively computes the `trapezoidal rule `_ +along :attr:`dim`. By default the spacing between elements is assumed to be 1, but +:attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be +used to specify arbitrary spacing along :attr:`dim`. + +For more details, please read :func:`torch.trapezoid`. The difference between :func:`torch.trapezoid` +and this function is that, :func:`torch.trapezoid` returns a value for each integration, +where as this function returns a cumulative value for every spacing within the integration. This +is analogous to how `.sum` returns a value and `.cumsum` returns a cumulative sum. + +Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + +Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + +Examples:: + + >>> # Cumulatively computes the trapezoidal rule in 1D, spacing is implicitly 1. + >>> y = torch.tensor([1, 5, 10]) + >>> torch.cumulative_trapezoid(y) + tensor([3., 10.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> (1 + 5) / 2 + 3.0 + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.cumulative_trapezoid(y, dx=2) + tensor([6., 21.]) + + >>> # Cumulatively computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([6., 28.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> ((3 - 1) * (1 + 5)) / 2 + 6.0 + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.cumulative_trapezoid(y) + tensor([[ 0.5, 2.], + [ 3.5, 8.], + [ 6.5, 14.]]) + + >>> # Cumulatively computes the trapezoidal rule for each column of the matrix + >>> torch.cumulative_trapezoid(y, dim=0) + tensor([[ 1.5, 2.5, 3.5], + [ 6.0, 8.0, 10.0]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[2., 5.], + [2., 5.], + [2., 5.]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[1., 2.], + [2., 4.], + [3., 6.]]) +""", +) + +add_docstr( + torch.repeat_interleave, + r""" +repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + +Repeat elements of a tensor. + +.. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + +Args: + {input} + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + +Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + +Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + +Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + +If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be +`tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, +`1` appears `n2` times, `2` appears `n3` times, etc. + +.. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + +Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + +Args: + repeats (Tensor): The number of repetitions for each element. + +Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + +Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + +""".format(**common_args), +) + +add_docstr( + torch.tile, + r""" +tile(input, dims) -> Tensor + +Constructs a tensor by repeating the elements of :attr:`input`. +The :attr:`dims` argument specifies the number of repetitions +in each dimension. + +If :attr:`dims` specifies fewer dimensions than :attr:`input` has, then +ones are prepended to :attr:`dims` until all dimensions are specified. +For example, if :attr:`input` has shape (8, 6, 4, 2) and :attr:`dims` +is (2, 2), then :attr:`dims` is treated as (1, 1, 2, 2). + +Analogously, if :attr:`input` has fewer dimensions than :attr:`dims` +specifies, then :attr:`input` is treated as if it were unsqueezed at +dimension zero until it has as many dimensions as :attr:`dims` specifies. +For example, if :attr:`input` has shape (4, 2) and :attr:`dims` +is (3, 3, 2, 2), then :attr:`input` is treated as if it had the +shape (1, 1, 4, 2). + +.. note:: + + This function is similar to NumPy's tile function. + +Args: + input (Tensor): the tensor whose elements to repeat. + dims (tuple): the number of repetitions per dimension. + +Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.tile((2,)) + tensor([1, 2, 3, 1, 2, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.tile(y, (2, 2)) + tensor([[1, 2, 1, 2], + [3, 4, 3, 4], + [1, 2, 1, 2], + [3, 4, 3, 4]]) +""", +) + +add_docstr( + torch.quantize_per_tensor, + r""" +quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + +Converts a float tensor to a quantized tensor with given scale and zero point. + +Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + +Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + +Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) +""", +) + +add_docstr( + torch.quantize_per_tensor_dynamic, + r""" +quantize_per_tensor_dynamic(input, dtype, reduce_range) -> Tensor + +Converts a float tensor to a quantized tensor with scale and zero_point calculated +dynamically based on the input. + +Arguments: + input (Tensor): float tensor or list of tensors to quantize + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8`` + reduce_range (bool): a flag to indicate whether to reduce the range of quantized + data by 1 bit, it's required to avoid instruction overflow for some hardwares + +Returns: + Tensor: A newly (dynamically) quantized tensor + +Example:: + + >>> t = torch.quantize_per_tensor_dynamic(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.quint8, False) + >>> print(t) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.011764705882352941, + zero_point=85) + >>> t.int_repr() + tensor([ 0, 85, 170, 255], dtype=torch.uint8) +""", +) + +add_docstr( + torch.quantize_per_channel, + r""" +quantize_per_channel(input, scales, zero_points, axis, dtype) -> Tensor + +Converts a float tensor to a per-channel quantized tensor with given scales and zero points. + +Arguments: + input (Tensor): float tensor to quantize + scales (Tensor): float 1D tensor of scales to use, size should match ``input.size(axis)`` + zero_points (int): integer 1D tensor of offset to use, size should match ``input.size(axis)`` + axis (int): dimension on which apply per-channel quantization + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + +Returns: + Tensor: A newly quantized tensor + +Example:: + + >>> x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]]) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8) + tensor([[-1., 0.], + [ 1., 2.]], size=(2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_channel_affine, + scale=tensor([0.1000, 0.0100], dtype=torch.float64), + zero_point=tensor([10, 0]), axis=0) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8).int_repr() + tensor([[ 0, 10], + [100, 200]], dtype=torch.uint8) +""", +) + + +add_docstr( + torch.quantized_batch_norm, + r""" +quantized_batch_norm(input, weight=None, bias=None, mean, var, eps, output_scale, output_zero_point) -> Tensor + +Applies batch normalization on a 4D (NCHW) quantized tensor. + +.. math:: + + y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta + +Arguments: + input (Tensor): quantized tensor + weight (Tensor): float tensor that corresponds to the gamma, size C + bias (Tensor): float tensor that corresponds to the beta, size C + mean (Tensor): float mean value in batch normalization, size C + var (Tensor): float tensor for variance, size C + eps (float): a value added to the denominator for numerical stability. + output_scale (float): output quantized tensor scale + output_zero_point (int): output quantized tensor zero_point + +Returns: + Tensor: A quantized tensor with batch normalization applied. + +Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_batch_norm(qx, torch.ones(2), torch.zeros(2), torch.rand(2), torch.rand(2), 0.00001, 0.2, 2) + tensor([[[[-0.2000, -0.2000], + [ 1.6000, -0.2000]], + + [[-0.4000, -0.4000], + [-0.4000, 0.6000]]], + + + [[[-0.2000, -0.2000], + [-0.2000, -0.2000]], + + [[ 0.6000, -0.4000], + [ 0.6000, -0.4000]]]], size=(2, 2, 2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=2) +""", +) + + +add_docstr( + torch.quantized_max_pool1d, + r""" +quantized_max_pool1d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + +Applies a 1D max pooling over an input quantized tensor composed of several input planes. + +Arguments: + input (Tensor): quantized tensor + kernel_size (list of int): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + +Returns: + Tensor: A quantized tensor with max_pool1d applied. + +Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool1d(qx, [2]) + tensor([[0.0000], + [1.5000]], size=(2, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) +""", +) + + +add_docstr( + torch.quantized_max_pool2d, + r""" +quantized_max_pool2d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + +Applies a 2D max pooling over an input quantized tensor composed of several input planes. + +Arguments: + input (Tensor): quantized tensor + kernel_size (``list of int``): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + +Returns: + Tensor: A quantized tensor with max_pool2d applied. + +Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool2d(qx, [2,2]) + tensor([[[[1.5000]], + + [[1.5000]]], + + + [[[0.0000]], + + [[0.0000]]]], size=(2, 2, 1, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) +""", +) + + +add_docstr( + torch.Stream, + r""" +Stream(device, *, priority) -> Stream + +An in-order queue of executing the respective tasks asynchronously in first in first out (FIFO) order. +It can control or synchronize the execution of other Stream or block the current host thread to ensure +the correct task sequencing. It supports with statement as a context manager to ensure the operators +within the with block are running on the corresponding stream. + +See in-depth description of the CUDA behavior at :ref:`cuda-semantics` for details +on the exact semantic that applies to all devices. + +Arguments: + device (:class:`torch.device`, optional): the desired device for the Stream. + If not given, the current :ref:`accelerator` type will be used. + priority (int, optional): priority of the stream, should be 0 or negative, where negative + numbers indicate higher priority. By default, streams have priority 0. + +Returns: + Stream: An torch.Stream object. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> with torch.Stream(device='cuda') as s_cuda: + >>> a = torch.randn(10, 5, device='cuda') + >>> b = torch.randn(5, 10, device='cuda') + >>> c = torch.mm(a, b) +""", +) + + +add_docstr( + torch.Stream.query, + r""" +Stream.query() -> bool + +Check if all the work submitted has been completed. + +Returns: + bool: A boolean indicating if all kernels in this stream are completed. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> s_cuda.query() + True +""", +) + + +add_docstr( + torch.Stream.record_event, + r""" +Stream.record_event(event) -> Event + +Record an event. En-queuing it into the Stream to allow further synchronization from the current point in the FIFO queue. + +Arguments: + event (:class:`torch.Event`, optional): event to record. If not given, a new one will be allocated. + +Returns: + Event: Recorded event. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> e_cuda = s_cuda.record_event() +""", +) + + +add_docstr( + torch.Stream.synchronize, + r""" +Stream.synchronize() -> None + +Wait for all the kernels in this stream to complete. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> s_cuda.synchronize() +""", +) + +add_docstr( + torch.Stream.is_capturing, + r""" +Stream.is_capturing() -> bool + +Return true if this stream is currently recording work for graph capture. + +Returns: + bool: A boolean indicating if the stream is capturing. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> s_cuda.is_capturing() +""", +) + + +add_docstr( + torch.Stream.wait_event, + r""" +Stream.wait_event(event) -> None + +Make all future work submitted to the stream wait for an event. + +Arguments: + event (:class:`torch.Event`): an event to wait for. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s1_cuda = torch.Stream(device='cuda') + >>> s2_cuda = torch.Stream(device='cuda') + >>> e_cuda = s1_cuda.record_event() + >>> s2_cuda.wait_event(e_cuda) +""", +) + + +add_docstr( + torch.Stream.wait_stream, + r""" +Stream.wait_stream(stream) -> None + +Synchronize with another stream. All future work submitted to this stream will wait until all kernels +already submitted to the given stream are completed. + +Arguments: + stream (:class:`torch.Stream`): a stream to synchronize. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s1_cuda = torch.Stream(device='cuda') + >>> s2_cuda = torch.Stream(device='cuda') + >>> s2_cuda.wait_stream(s1_cuda) +""", +) + + +add_docstr( + torch.Event, + r""" +Event(device=None, *, enable_timing=False, blocking=False, interprocess=False) + +Query and record Stream status to identify or control dependencies across Stream and measure timing. + +Arguments: + device (:class:`torch.device`, optional): the desired device for the Event. + If not given, the current :ref:`accelerator` type will be used. + enable_timing (bool, optional): indicates if the event should measure time (default: ``False``) + blocking (bool, optional): if ``True``, :meth:`wait` will be blocking (default: ``False``) + interprocess (bool): if ``True``, the event can be shared between processes (default: ``False``) + +.. warning:: + + Both blocking and interprocess are not supported right now and are noops. + +Returns: + Event: An torch.Event object. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> event = torch.Event() + >>> e_cuda = torch.Event(device='cuda') +""", +) + + +add_docstr( + torch.Event.elapsed_time, + r""" +Event.elapsed_time(end_event) -> float + +Returns the elapsed time in milliseconds between when this event and the :attr:`end_event` are +each recorded via :func:`torch.Stream.record_event`. + +Arguments: + end_event (:class:`torch.Event`): The ending event has been recorded. + +Returns: + float: Time between starting and ending event in milliseconds. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> e1_cuda = s_cuda.record_event() + >>> e2_cuda = s_cuda.record_event() + >>> ms = e1_cuda.elapsed_time(e2_cuda) +""", +) + + +add_docstr( + torch.Event.query, + r""" +Event.query() -> bool + +Check if the stream where this event was recorded already moved past the point where the event was recorded. +Always returns ``True`` if the Event was not recorded. + +Returns: + bool: A boolean indicating if all work currently captured by event has completed. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> e_cuda = s_cuda.record_event() + >>> e_cuda.query() + True +""", +) + + +add_docstr( + torch.Event.record, + r""" +Event.record(stream=None) -> None + +Record the event in a given stream. The stream's device must match the event's device. +This function is equivalent to ``stream.record_event(self)``. + +Arguments: + stream (:class:`torch.Stream`, optional): A stream to be recorded. + If not given, the current stream will be used. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> e_cuda = torch.Event(device='cuda') + >>> e_cuda.record() +""", +) + + +add_docstr( + torch.Event.synchronize, + r""" +Event.synchronize() -> None + +Wait for the event to complete. This prevents the CPU thread from proceeding until the event completes. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s_cuda = torch.Stream(device='cuda') + >>> e_cuda = s_cuda.record_event() + >>> e_cuda.synchronize() +""", +) + + +add_docstr( + torch.Event.wait, + r""" +Event.wait(stream=None) -> None + +Make all future work submitted to the given stream wait for this event. + +Arguments: + stream (:class:`torch.Stream`, optional): A stream to synchronize. + If not given, the current stream will be used. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> s1_cuda = torch.Stream(device='cuda') + >>> s2_cuda = torch.Stream(device='cuda') + >>> e_cuda = s1_cuda.record() + >>> e_cuda.wait(s2) +""", +) + + +add_docstr( + torch.Generator, + r""" +Generator(device='cpu') -> Generator + +Creates and returns a generator object that manages the state of the algorithm which +produces pseudo random numbers. Used as a keyword argument in many :ref:`inplace-random-sampling` +functions. + +Arguments: + device (:class:`torch.device`, optional): the desired device for the generator. + +Returns: + Generator: An torch.Generator object. + +Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> g_cpu = torch.Generator() + >>> g_cuda = torch.Generator(device='cuda') +""", +) + + +add_docstr( + torch.Generator.set_state, + r""" +Generator.set_state(new_state) -> void + +Sets the Generator state. + +Arguments: + new_state (torch.ByteTensor): The desired state. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu_other = torch.Generator() + >>> g_cpu.set_state(g_cpu_other.get_state()) +""", +) + + +add_docstr( + torch.Generator.get_state, + r""" +Generator.get_state() -> Tensor + +Returns the Generator state as a ``torch.ByteTensor``. + +Returns: + Tensor: A ``torch.ByteTensor`` which contains all the necessary bits + to restore a Generator to a specific point in time. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.get_state() +""", +) + +add_docstr( + torch.Generator.graphsafe_set_state, + r""" +Generator.graphsafe_set_state(state) -> None + +Sets the state of the generator to the specified state in a manner that is safe for use in graph capture. +This method is crucial for ensuring that the generator's state can be captured in the CUDA graph. + +Arguments: + state (torch.Generator): A Generator point to the new state for the generator, typically obtained from `graphsafe_get_state`. + +Example: + >>> g_cuda = torch.Generator(device='cuda') + >>> g_cuda_other = torch.Generator(device='cuda') + >>> current_state = g_cuda_other.graphsafe_get_state() + >>> g_cuda.graphsafe_set_state(current_state) +""", +) + +add_docstr( + torch.Generator.graphsafe_get_state, + r""" +Generator.graphsafe_get_state() -> torch.Generator + +Retrieves the current state of the generator in a manner that is safe for graph capture. +This method is crucial for ensuring that the generator's state can be captured in the CUDA graph. + +Returns: + torch.Generator: A Generator point to the current state of the generator + +Example: + >>> g_cuda = torch.Generator(device='cuda') + >>> current_state = g_cuda.graphsafe_get_state() +""", +) + +add_docstr( + torch.Generator.philox_state, + r""" +Generator.philox_state(increment) -> tuple[Tensor, Tensor, Tensor] + +Reserves ``increment`` values from this generator's Philox4x32-10 stream and +returns the reserved position as ``(seed, offset, intragraph_offset)``, three +1-element ``int64`` tensors. This is the same reservation protocol the +built-in CUDA random kernels use (``PhiloxCudaState`` in C++), so kernels +built on it draw from the same stream as, and compose with, the built-in +random operations. Only Philox-based generators (currently CUDA) support this +method. + +**What the reservation grants.** With ``effective_offset = +(uint64(offset) + uint64(intragraph_offset)) % 2**64`` (both operands +reinterpreted back from int64 to uint64 first; see below), the caller owns +the Philox counter values ``effective_offset / 4`` through +``effective_offset / 4 + ceil(increment / 4) - 1`` (the counter advances once +per 4 generated values), at the fixed ``seed``, for **every** subsequence. +Following the built-in kernels' convention of one subsequence per thread +(``curand_init(seed, subsequence, effective_offset, ...)``, where the counter +occupies ``counter.x/y`` and the subsequence ``counter.z/w``), a thread may +generate up to ``increment`` values rounded up to a multiple of 4. The +generator's offset advances by that rounded amount, so ``increment`` must be +at least the number of 32-bit values any single thread of the consuming +kernel generates. + +**int64 reinterpretation.** Seed and offset are unsigned 64-bit quantities +returned bit-exactly in ``int64`` tensors (PyTorch tensors have no uint64 +arithmetic support); values at or above ``2**63`` appear negative. Kernels +should reinterpret the bits back to uint64 (e.g. load as int64 and bitcast); +for host-side inspection use ``.item() & (2**64 - 1)``. The offset wraps +modulo ``2**64`` on advancement. + +**Graph capture.** The two return modes mirror the C++ ``PhiloxCudaState`` +protocol. Outside capture (``HostState``), ``seed`` and ``offset`` are CPU +tensors holding the current values; ``.item()`` is cheap and does not +synchronize, so callers pass the values as scalar kernel arguments. During +capture (``DevState``, under :class:`torch.accelerator.Graph` or +:class:`torch.cuda.CUDAGraph`), ``seed`` and ``offset`` are CUDA tensors +aliasing generator state that each replay refills with the values current at +replay time, so kernels must load them from device memory at run time. +``intragraph_offset`` is always a CPU tensor: 0 outside capture, and this +reservation's position within the graph during capture. Callers branch on +capture state (e.g. :func:`torch.cuda.is_current_stream_capturing`, or the +device of the returned tensors), exactly like the built-in kernels branch on +``PhiloxCudaState`` via ``at::cuda::philox::unpack``. + +.. warning:: + Tensors returned during capture alias the capture's state: their contents + are undefined until the first replay and they must not be used after the + graph is destroyed. + +Arguments: + increment (int): Number of Philox outputs to reserve. Must be + non-negative and at most ``2**64 - 1``; the offset it advances + wraps modulo ``2**64`` (under graph capture, where the intragraph + offset starts at 0, the total reserved within one graph must stay + below ``2**64``). + +Returns: + tuple[Tensor, Tensor, Tensor]: ``(seed, offset, intragraph_offset)``, + each a 1-element ``int64`` tensor. ``seed`` and ``offset`` hold the + generator's seed and the reserved stream position as uint64 bits (CPU + tensors outside capture, CUDA tensors aliasing generator state during + capture); ``intragraph_offset`` is always a CPU tensor holding this + reservation's position within the capturing graph (0 outside capture). + +Example: + >>> g_cuda = torch.Generator(device='cuda') + >>> seed, offset, intragraph = g_cuda.philox_state(4) +""", +) + +add_docstr( + torch.Generator.clone_state, + r""" +Generator.clone_state() -> torch.Generator + +Clones the current state of the generator and returns a new generator pointing to this cloned state. +This method is beneficial for preserving a particular state of a generator to restore at a later point. + +Returns: + torch.Generator: A Generator pointing to the newly cloned state. + +Example: + >>> g_cuda = torch.Generator(device='cuda') + >>> cloned_state = g_cuda.clone_state() +""", +) + +add_docstr( + torch.Generator.manual_seed, + r""" +Generator.manual_seed(seed) -> Generator + +Sets the seed for generating random numbers. Returns a `torch.Generator` object. Any 32-bit integer is a valid seed. + +Arguments: + seed (int): The desired seed. Value must be within the inclusive range + `[-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]`. Otherwise, a RuntimeError + is raised. Negative inputs are remapped to positive values with the formula + `0xffff_ffff_ffff_ffff + seed`. + +Returns: + Generator: An torch.Generator object. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.manual_seed(2147483647) +""", +) + + +add_docstr( + torch.Generator.initial_seed, + r""" +Generator.initial_seed() -> int + +Returns the initial seed for generating random numbers. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.initial_seed() + 2147483647 +""", +) + + +add_docstr( + torch.Generator.seed, + r""" +Generator.seed() -> int + +Gets a non-deterministic random number from std::random_device or the current +time and uses it to seed a Generator. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.seed() + 1516516984916 +""", +) + + +add_docstr( + torch.Generator.device, + r""" +Generator.device -> device + +Gets the current device of the generator. + +Example:: + + >>> g_cpu = torch.Generator() + >>> g_cpu.device + device(type='cpu') +""", +) + +add_docstr( + torch._assert_async, + r""" +_assert_async(tensor) -> void + +Asynchronously assert that the contents of tensor are nonzero. For CPU tensors, +this is equivalent to ``assert tensor`` or ``assert tensor.is_nonzero()``; for +CUDA tensors, we DO NOT synchronize and you may only find out the assertion +failed at a later CUDA kernel launch. Asynchronous assertion can be helpful for +testing invariants in CUDA tensors without giving up performance. This function +is NOT intended to be used for regular error checking, as it will trash your CUDA +context if the assert fails (forcing you to restart your PyTorch process.) + +Args: + tensor (Tensor): a one element tensor to test to see if it is nonzero. Zero + elements (including False for boolean tensors) cause an assertion failure + to be raised. +""", +) + +add_docstr( + torch.searchsorted, + r""" +searchsorted(sorted_sequence, values, *, out_int32=False, right=False, side=None, out=None, sorter=None) -> Tensor + +Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the +corresponding values in :attr:`values` were inserted before the indices, when sorted, the order +of the corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved. +Return a new tensor with the same size as :attr:`values`. More formally, +the returned index satisfies the following rules: + +.. list-table:: + :widths: 12 10 78 + :header-rows: 1 + + * - :attr:`sorted_sequence` + - :attr:`right` + - *returned index satisfies* + * - 1-D + - False + - ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]`` + * - 1-D + - True + - ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]`` + * - N-D + - False + - ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]`` + * - N-D + - True + - ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]`` + +Args: + sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost* + dimension unless :attr:`sorter` is provided, in which case the sequence does not + need to be sorted. PyTorch does not validate this condition when :attr:`sorter` is + not provided, and the behavior is undefined if the sequence is not sorted. + values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + +Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): if False, return the first suitable location that is found. If True, return the + last such index. If no suitable index found, return 0 for non-numerical value + (eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence` + (one pass the last index of the *innermost* dimension). In other words, if False, + gets the lower bound index for each value in :attr:`values` on the corresponding + *innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper + bound index instead. Default value is False. :attr:`side` does the same and is + preferred. It will error if :attr:`side` is set to "left" while this is True. + side (str, optional): the same as :attr:`right` but preferred. "left" corresponds to False for :attr:`right` + and "right" corresponds to True for :attr:`right`. It will error if this is set to + "left" while :attr:`right` is True. Default value is None. + out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided. + sorter (LongTensor, optional): if provided, a tensor matching the shape of the unsorted + :attr:`sorted_sequence` containing a sequence of indices that sort it in the + ascending order on the innermost dimension + + +Example:: + + >>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]) + >>> sorted_sequence + tensor([[ 1, 3, 5, 7, 9], + [ 2, 4, 6, 8, 10]]) + >>> values = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> values + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.searchsorted(sorted_sequence, values) + tensor([[1, 3, 4], + [1, 2, 4]]) + >>> torch.searchsorted(sorted_sequence, values, side='right') + tensor([[2, 3, 5], + [1, 3, 4]]) + + >>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9]) + >>> sorted_sequence_1d + tensor([1, 3, 5, 7, 9]) + >>> torch.searchsorted(sorted_sequence_1d, values) + tensor([[1, 3, 4], + [1, 3, 4]]) +""", +) + +add_docstr( + torch.bucketize, + r""" +bucketize(input, boundaries, *, out_int32=False, right=False, out=None) -> Tensor + +Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the +boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size +as :attr:`input`. If :attr:`right` is False (default), then the left boundary is open. Note that +this behavior is opposite the behavior of +`numpy.digitize `_. +More formally, the returned index satisfies the following rules: + +.. list-table:: + :widths: 15 85 + :header-rows: 1 + + * - :attr:`right` + - *returned index satisfies* + * - False + - ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]`` + * - True + - ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]`` + +Args: + input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + boundaries (Tensor): 1-D tensor, must contain a strictly increasing sequence, or the return value is undefined. + +Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): determines the behavior for values in :attr:`boundaries`. See the table above. + out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided. + + +Example:: + + >>> boundaries = torch.tensor([1, 3, 5, 7, 9]) + >>> boundaries + tensor([1, 3, 5, 7, 9]) + >>> v = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> v + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.bucketize(v, boundaries) + tensor([[1, 3, 4], + [1, 3, 4]]) + >>> torch.bucketize(v, boundaries, right=True) + tensor([[2, 3, 5], + [2, 3, 5]]) +""", +) + +add_docstr( + torch.view_as_real_copy, + r""" +Performs the same operation as :func:`torch.view_as_real`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.view_as_complex_copy, + r""" +Performs the same operation as :func:`torch.view_as_complex`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.as_strided_copy, + r""" +Performs the same operation as :func:`torch.as_strided`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.diagonal_copy, + r""" +Performs the same operation as :func:`torch.diagonal`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.expand_copy, + r""" +Performs the same operation as :func:`torch.Tensor.expand`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.permute_copy, + r""" +Performs the same operation as :func:`torch.permute`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.select_copy, + r""" +Performs the same operation as :func:`torch.select`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.detach_copy, + r""" +Performs the same operation as :func:`torch.detach`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.slice_copy, + r""" +Performs the same operation as :func:`torch.slice`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.split_copy, + r""" +Performs the same operation as :func:`torch.split`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.split_with_sizes_copy, + r""" +Performs the same operation as :func:`torch.split_with_sizes`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.squeeze_copy, + r""" +Performs the same operation as :func:`torch.squeeze`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.t_copy, + r""" +Performs the same operation as :func:`torch.t`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.transpose_copy, + r""" +Performs the same operation as :func:`torch.transpose`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.unsqueeze_copy, + r""" +Performs the same operation as :func:`torch.unsqueeze`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.indices_copy, + r""" +Performs the same operation as :func:`torch.indices`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.values_copy, + r""" +Performs the same operation as :func:`torch.values`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.crow_indices_copy, + r""" +Performs the same operation as :func:`torch.crow_indices`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.col_indices_copy, + r""" +Performs the same operation as :func:`torch.col_indices`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.unbind_copy, + r""" +Performs the same operation as :func:`torch.unbind`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.view_copy, + r""" +Performs the same operation as :func:`torch.view`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.unfold_copy, + r""" +Performs the same operation as :func:`torch.unfold`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +add_docstr( + torch.alias_copy, + r""" +Performs the same operation as :func:`torch.alias`, but all output tensors +are freshly created instead of aliasing the input. +""", +) + +for unary_base_func_name in ( + "exp", + "sqrt", + "abs", + "acos", + "asin", + "atan", + "ceil", + "cos", + "cosh", + "erf", + "erfc", + "expm1", + "floor", + "log", + "log10", + "log1p", + "log2", + "neg", + "tan", + "tanh", + "sin", + "sinh", + "round", + "lgamma", + "frac", + "reciprocal", + "sigmoid", + "trunc", + "zero", +): + unary_foreach_func_name = f"_foreach_{unary_base_func_name}" + if hasattr(torch, unary_foreach_func_name): + add_docstr( + getattr(torch, unary_foreach_func_name), + rf""" +{unary_foreach_func_name}(self: List[Tensor]) -> List[Tensor] + +Apply :func:`torch.{unary_base_func_name}` to each Tensor of the input list. + """, + ) + unary_inplace_foreach_func_name = f"{unary_foreach_func_name}_" + if hasattr(torch, unary_inplace_foreach_func_name): + add_docstr( + getattr(torch, unary_inplace_foreach_func_name), + rf""" +{unary_inplace_foreach_func_name}(self: List[Tensor]) -> None + +Apply :func:`torch.{unary_base_func_name}` to each Tensor of the input list. + """, + ) + +add_docstr( + torch.detach_, + r""" +detach_(input) -> Tensor + +In-place version of :func:`torch.detach` +""", +) + +add_docstr( + torch.feature_alpha_dropout_, + r""" +feature_alpha_dropout_(input, p, train) -> Tensor + +In-place version of :func:`torch.feature_alpha_dropout` +""", +) + +add_docstr( + torch.feature_dropout_, + r""" +feature_dropout_(input, p, train) -> Tensor + +In-place version of :func:`torch.feature_dropout` +""", +) diff --git a/.venv/lib/python3.12/site-packages/torch/_utils.py b/.venv/lib/python3.12/site-packages/torch/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fcfe80627901641196f4ddf55b4054dec4deb492 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_utils.py @@ -0,0 +1,1527 @@ +# mypy: allow-untyped-defs +import _compat_pickle +import copyreg +import functools +import importlib +import logging +import math +import os +import pickle +import re +import sys +import traceback +import warnings +from collections import defaultdict +from collections.abc import Callable +from types import ModuleType +from typing import Any, cast, Generic, TYPE_CHECKING, TypedDict +from typing_extensions import deprecated, NotRequired, ParamSpec + +import torch + + +def _type(self, dtype=None, non_blocking=False, **kwargs): + """Returns the type if `dtype` is not provided, else casts this object to + the specified type. + + If this is already of the correct type, no copy is performed and the + original object is returned. + + Args: + dtype (type or string): The desired type + non_blocking (bool): If ``True``, and the source is in pinned memory + and destination is on the GPU or vice versa, the copy is performed + asynchronously with respect to the host. Otherwise, the argument + has no effect. + **kwargs: For compatibility, may contain the key ``async`` in place of + the ``non_blocking`` argument. The ``async`` arg is deprecated. + """ + non_blocking = _get_async_or_non_blocking("type", non_blocking, kwargs) + if dtype is None: + return self.__module__ + "." + self.__class__.__name__ + + if isinstance(dtype, str): + dtype = _import_dotted_name(dtype) + if dtype is type(self): + return self + if self.is_sparse: + if not dtype.is_sparse: + raise RuntimeError("Cannot cast sparse tensor to dense tensor") + new_module_name = dtype.__module__.replace(".sparse", "") + new_values_type_name = new_module_name + "." + dtype.__name__ + new_values = torch.Tensor._values(self).type(new_values_type_name, non_blocking) + new_indices_type_name = new_module_name + ".LongTensor" + new_indices = torch.Tensor._indices(self).type( + new_indices_type_name, non_blocking + ) + return dtype(new_indices, new_values, self.size()) + if dtype.is_sparse: + raise RuntimeError("Cannot cast dense tensor to sparse tensor") + return dtype(self.size()).copy_(self, non_blocking) + + +def _to(self, device, non_blocking=False): + """Returns a copy of this object in device memory. + + If this object is already on the correct device, then no copy is performed + and the original object is returned. + + Args: + device (int): The destination device. + non_blocking (bool): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. Otherwise, + the argument has no effect. + """ + if self.device == device: + return self + + if device.type == "cpu": + pin_memory = non_blocking and self.device.type in ( + "cuda", + "xpu", + "mtia", + torch._C._get_privateuse1_backend_name(), + ) + untyped_storage = torch.empty( + self.nbytes(), dtype=torch.uint8, device=device, pin_memory=pin_memory + ).untyped_storage() + untyped_storage.copy_(self, non_blocking) + return untyped_storage + + device_module = getattr(torch, device.type, None) + if device_module is None: + raise AssertionError(f"{device.type.upper()} device module is not loaded") + with device_module.device(device): + if self.is_sparse and hasattr(device_module, "sparse"): + new_type = getattr(device_module.sparse, self.__class__.__name__) + indices = getattr(torch.Tensor._indices(self), device.type)( + device, non_blocking + ) + values = getattr(torch.Tensor._values(self), device.type)( + device, non_blocking + ) + return new_type(indices, values, self.size()) + else: + if self.is_sparse: + raise AssertionError( + f"sparse storage is not supported for {device.type.upper()} tensors" + ) + untyped_storage = torch.UntypedStorage(self.size(), device=device) + untyped_storage.copy_(self, non_blocking) + return untyped_storage + + +def _get_async_or_non_blocking(function_name, non_blocking, kwargs): + """Return the non-blocking flag given the function name and kwargs. + + Args: + function_name (str): the name of the function being used. + non_blocking (bool): the default value. + **kwargs (dict): the kwargs passed to the function. + """ + if not kwargs: + return non_blocking + if len(kwargs) != 1 or "async" not in kwargs: + message = "{}() got an unexpected keyword argument '{}'" + argument = list(kwargs.keys()).pop() + raise TypeError(message.format(function_name, argument)) + warnings.warn("'async' is deprecated; use 'non_blocking'", stacklevel=2) + return kwargs["async"] + + +def _get_restore_location(device): + """Return the map_location location. + + Used for rebuild functions where the tensor device is distinct from the storage + """ + + map_location = torch.serialization._serialization_tls.map_location + if map_location is None: + return device + else: + if isinstance(map_location, dict): + return map_location.get(device, device) + elif isinstance(map_location, (str, torch.device)): + return map_location + else: + if not callable(map_location): + raise AssertionError( + f"expected callable map_location, got {type(map_location).__name__}" + ) + raise RuntimeError( + "Callable map_location not supported with _rebuild_wrapper_subclass " + "or _rebuild_device_tensor_from_numpy" + ) + + +# Note [Don't serialize hooks] +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# Since time immemorial, we have serialized the backward hooks associated with +# variables. This kind of half-worked--Python can pickle global functions +# (but not closures!)--but there were problems. +# +# - It's fragile. If you serialize a backward hook into a saved +# model, and then you rename the function associated with the hook, +# now your saved model is broken and you can't load it anymore. +# +# - It's not actually used. The standard recommendation is to +# serialize the *state_dict* of a model, not the model itself +# (since this is more stable to code changes affecting the model +# serialization), and the state dict saves "data" only, thus +# stripping the backward hooks. In some cases, hooks are +# essential to the well-functioning of a model (e.g., DDP), +# but DDP already manages re-adding the hooks! +# +# - We didn't serialize them in many cases. Prior to #10220, we +# were dropping backward hooks in ForkingPickler. We "fixed" this +# to be convenient with other serialization sites, but lack of +# serializing backward hooks wasn't actually the root cause of +# the bug. +# +# With these cases in mind, we have decided that a better strategy +# is to just NOT serialize hooks at all. +# +# Since this is a BC-breaking change, we should warn when we previously +# serialized a hook, but no longer do so. This will be done by adding a special +# sentinel property to hooks will be used to suppress this warning. If a hook +# has the property _torch_serialize_ignore, we will not emit a warning if we +# attempt to serialize a Tensor with this hook attached to it. +# +# By the way, when _backward_hooks is skipped, we must give an EMPTY +# OrderedDict(), if you pass a None you'll run afoul #12219. + + +# TODO: Once we decide to break serialization FC, `storage` no longer needs to +# be a TypedStorage +def _rebuild_tensor(storage, storage_offset, size, stride): + # first construct a tensor with the correct dtype/device + t = torch.empty((0,), dtype=storage.dtype, device=storage._untyped_storage.device) + return t.set_(storage._untyped_storage, storage_offset, size, stride) + + +def get_tensor_metadata(tensor): + # Tensor's Metadata for serializing. + # Currently, this only returns a dict[string, bool] specifying whether + # `conj` or `neg` bit is set. + if not isinstance(tensor, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(tensor).__name__}") + return torch._C._get_tensor_metadata(tensor) # type: ignore[attr-defined] + + +def set_tensor_metadata(tensor, metadata): + # See `get_tensor_metadata` above + if not isinstance(metadata, dict): + raise AssertionError(f"expected dict, got {type(metadata).__name__}") + if not isinstance(tensor, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(tensor).__name__}") + torch._C._set_tensor_metadata(tensor, metadata) # type: ignore[attr-defined] + + +def _restore_device_fake_mode(tensor): + if torch._guards.detect_fake_mode(None) is not None: + if tensor.untyped_storage()._fake_device is not None: + device = _get_restore_location(tensor.untyped_storage()._fake_device) + if not isinstance(device, torch.device): + device = torch.device(device) + tensor.fake_device = torch.device(device) + return tensor + + +def _rebuild_tensor_v2( + storage, + storage_offset, + size, + stride, + requires_grad, + backward_hooks, + metadata=None, +): + tensor = _rebuild_tensor(storage, storage_offset, size, stride) + tensor.requires_grad = requires_grad + if metadata: + set_tensor_metadata(tensor, metadata) + + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + tensor._backward_hooks = backward_hooks + + tensor = _restore_device_fake_mode(tensor) + return tensor + + +def _rebuild_tensor_v3( + storage, + storage_offset, + size, + stride, + requires_grad, + backward_hooks, + dtype, + metadata=None, +): + t = torch.empty( + (0,), + dtype=dtype, + device=storage._untyped_storage.device, + requires_grad=requires_grad, + ) + t.set_(storage._untyped_storage, storage_offset, size, stride) + if metadata: + set_tensor_metadata(t, metadata) + t._backward_hooks = backward_hooks + t = _restore_device_fake_mode(t) + return t + + +_sparse_tensors_to_validate: list["torch.Tensor"] = [] + + +# In _legacy_load() in serialization.py we unpickle storages after the sparse +# tensors have been already unpickled. Those storages contain data necessary for +# validating sparse tensors: indices and values. That's why sparse tensors are +# first unpickled without any validation, and then this function is called just +# before _legacy_load() returns, so that all the sparse tensors can be validated +# in bulk. +# +# The same procedure must be followed by _load() in serialization.py because due +# to Pickler semantics, we have to use the same (non-validating) function for +# unpickling sparse tensors, regardless of the caller. +def _validate_loaded_sparse_tensors(weights_only=False): + # In weights_only mode we always validate: malformed sparse indices can + # cause out-of-bounds reads later (e.g. in to_dense()), and an untrusted + # checkpoint must not be able to slip those through. Otherwise we fall back + # to the global check_sparse_tensor_invariants setting. + try: + if not _sparse_tensors_to_validate: + return + if weights_only: + warnings.warn( + "Validating sparse tensor invariants because weights_only=True; " + "this is an O(nnz) scan per sparse tensor and may be slow for " + "large checkpoints.", + stacklevel=2, + ) + elif not torch.sparse.check_sparse_tensor_invariants().is_enabled(): + return + # We disable pinning check (see check_pinning=False below) to + # avoid gh-153143. In fact, pinning check is unnecessary + # anyway when loading sparse data from external sources. + for t in _sparse_tensors_to_validate: + if t.layout is torch.sparse_coo: + torch._validate_sparse_coo_tensor_args( + t._indices(), + t._values(), + t.size(), + t.is_coalesced(), + check_pinning=False, + ) + elif t.layout in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + }: + # TODO: Validation currently involves an expensive traversal + # on CPU, which may include a device transfer. + if t.layout in {torch.sparse_csr, torch.sparse_bsr}: + compressed_indices, plain_indices = ( + t.crow_indices(), + t.col_indices(), + ) + else: + compressed_indices, plain_indices = ( + t.ccol_indices(), + t.row_indices(), + ) + torch._validate_sparse_compressed_tensor_args( + compressed_indices, + plain_indices, + t.values(), + t.size(), + t.layout, + check_pinning=False, + ) + else: + raise NotImplementedError( + f"_validate_loaded_sparse_tensors for layout `{t.layout}`" + ) + + finally: + _sparse_tensors_to_validate.clear() + + +def _rebuild_sparse_tensor(layout, data): + """ + Rebuilds a sparse tensor from its sparse storage representation. + + Args: + layout (str): The sparse storage layout of the tensor. + data (tuple): The tensor's sparse storage representation. + """ + if layout == torch.sparse_coo: + if len(data) == 3: + # For BC: + indices, values, size = data + is_coalesced = None + else: + indices, values, size, is_coalesced = data + result = torch.sparse_coo_tensor( + indices, values, size, check_invariants=False, is_coalesced=is_coalesced + ) + _sparse_tensors_to_validate.append(result) + return result + + elif layout in { + torch.sparse_csr, + torch.sparse_csc, + torch.sparse_bsr, + torch.sparse_bsc, + }: + compressed_indices, plain_indices, values, size = data + result = torch.sparse_compressed_tensor( + compressed_indices, + plain_indices, + values, + size, + layout=layout, + check_invariants=False, + ) + _sparse_tensors_to_validate.append(result) + return result + + raise NotImplementedError(f"rebuilding sparse tensor for layout {layout}") + + +def _rebuild_nested_tensor(buffer, sizes, strides, storage_offsets): + return torch._nested_view_from_buffer(buffer, sizes, strides, storage_offsets) + + +def _rebuild_device_tensor_from_cpu_tensor(data, dtype, device, requires_grad): + device = _get_restore_location(device) + tensor = data.to(dtype=dtype, device=device) + tensor.requires_grad = requires_grad + return tensor + + +def _rebuild_device_tensor_from_numpy(data, dtype, device, requires_grad): + device = _get_restore_location(device) + tensor = torch.from_numpy(data).to(dtype=dtype, device=device) + tensor.requires_grad = requires_grad + return tensor + + +# Should not be used, only here to be able to load Tensors serialized with older versions of pytorch +_rebuild_xla_tensor = _rebuild_device_tensor_from_numpy + + +def _rebuild_meta_tensor_no_storage(dtype, size, stride, requires_grad): + return torch.empty_strided( + size, stride, dtype=dtype, device="meta", requires_grad=requires_grad + ) + + +def _rebuild_wrapper_subclass( + cls, + dtype, + size, + stride, + storage_offset, + layout, + device, + requires_grad, +): + device = _get_restore_location(device) + return torch.Tensor._make_wrapper_subclass( + cls, + size, + strides=stride, + dtype=dtype, + storage_offset=storage_offset, + layout=layout, + device=device, + requires_grad=requires_grad, + ) + + +# TODO: Once we decide to break serialization FC, `storage` no longer needs to +# be a TypedStorage +def _rebuild_qtensor( + storage, + storage_offset, + size, + stride, + quantizer_params, + requires_grad, + backward_hooks, +): + qscheme = quantizer_params[0] + if qscheme == torch.per_tensor_affine: + _, scale, zero_point = quantizer_params + tensor = torch._empty_affine_quantized( + size, + scale=scale, + zero_point=zero_point, + dtype=storage.dtype, + device=storage.device, + ) + elif qscheme in (torch.per_channel_affine, torch.per_channel_affine_float_qparams): + _, scales, zero_points, axis = quantizer_params + # The C++ constructor does not bound-check axis or the + # scales/zero_points length against size; values arriving from an + # untrusted weights_only checkpoint can otherwise be arbitrary. + if not 0 <= axis < len(size): + raise ValueError( + f"_rebuild_qtensor: per_channel axis {axis} out of range for size {tuple(size)}" + ) + expected_len = int(size[axis]) + scales_len = len(scales) if isinstance(scales, list) else scales.numel() + zero_points_len = ( + len(zero_points) if isinstance(zero_points, list) else zero_points.numel() + ) + if scales_len != expected_len or zero_points_len != expected_len: + raise ValueError( + "_rebuild_qtensor: per_channel scales/zero_points length must equal " + f"size[axis]={expected_len}, got scales={scales_len}, " + f"zero_points={zero_points_len}" + ) + if type(scales) is list and type(zero_points) is list: + if qscheme == torch.per_channel_affine: + scales = torch.tensor(scales, dtype=torch.double, device=storage.device) + zero_points = torch.tensor( + zero_points, dtype=torch.long, device=storage.device + ) + else: + scales = torch.tensor(scales, dtype=torch.float, device=storage.device) + zero_points = torch.tensor( + zero_points, dtype=torch.float, device=storage.device + ) + tensor = torch._empty_per_channel_affine_quantized( + size, + scales=scales, + zero_points=zero_points, + axis=axis, + dtype=storage.dtype, + device=storage.device, + ) + else: + raise RuntimeError(f"Can't deserialize quantized tensor with qscheme {qscheme}") + tensor.set_(storage, storage_offset, size, stride) + tensor.requires_grad = requires_grad + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + tensor._backward_hooks = backward_hooks + return tensor + + +def _rebuild_parameter(data, requires_grad, backward_hooks): + param = torch.nn.Parameter(data, requires_grad) + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + param._backward_hooks = backward_hooks + + return param + + +def _rebuild_parameter_with_state(data, requires_grad, backward_hooks, state): + param = torch.nn.Parameter(data, requires_grad) + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + param._backward_hooks = backward_hooks + + # Restore state on Parameter like python attr. + param = _set_obj_state(param, state) + return param + + +def _get_obj_state(obj): + # Get the state of the python subclass + # This loosely mimics the function on the object class but since Tensor do not inherit + # from it, we cannot call that function directly + # https://github.com/python/cpython/blob/c83919bd635f4433f1c6ae8504996a9fe3c215e5/Objects/typeobject.c#L4891 + # Note that starting with Python 3.11, this `__getstate__` is always defined and thus + # the else branch will never be taken. + getstate_fn = getattr(obj, "__getstate__", None) + if getstate_fn: + state = getstate_fn() + else: + slots_to_save = copyreg._slotnames(obj.__class__) # type: ignore[attr-defined] + if slots_to_save: + state = ( + obj.__dict__, + { + name: getattr(obj, name) + for name in slots_to_save + if hasattr(obj, name) + }, + ) + else: + state = obj.__dict__ + + return state + + +def _set_obj_state(obj, state): + if isinstance(state, tuple): + if not len(state) == 2: + raise RuntimeError(f"Invalid serialized state: {state}") + dict_state = state[0] + slots_state = state[1] + else: + dict_state = state + slots_state = None + + # Starting with Python 3.11, the __dict__ attribute is lazily created + # and is serialized as None when not needed. + if dict_state: + for k, v in dict_state.items(): + setattr(obj, k, v) + + if slots_state: + for k, v in slots_state.items(): + setattr(obj, k, v) + return obj + + +def _import_dotted_name(name): + components = name.split(".") + obj = __import__(components[0]) + for component in components[1:]: + obj = getattr(obj, component) + return obj + + +def _flatten_dense_tensors(tensors): + """Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of + same dense type. + + Since inputs are dense, the resulting tensor will be a concatenated 1D + buffer. Element-wise operation on this buffer will be equivalent to + operating individually. + + Args: + tensors (Iterable[Tensor]): dense tensors to flatten. + + Returns: + A contiguous 1D buffer containing input tensors. + """ + return torch._C._nn.flatten_dense_tensors(tensors) + + +def _flatten_sparse_tensors(tensors): + """Flatten sparse tensors into two contiguous 1D buffers, one of indices and + one of values. Assume tensors are of same sparse type. + + Args: + tensors (Iterable[Tensor]): sparse tensors to flatten. + + Returns: + A tuple of two contiguous 1D buffers, one containing input tensors' + indices and the other containing the values. + """ + flat_indices = torch._C._nn.flatten_dense_tensors( + [torch.Tensor._indices(t) for t in tensors] + ) + flat_values = torch._C._nn.flatten_dense_tensors( + [torch.Tensor._values(t) for t in tensors] + ) + return flat_indices, flat_values + + +def _unflatten_dense_tensors(flat, tensors): + """View a flat buffer using the sizes of tensors. Assume that tensors are of + same dense type, and that flat is given by _flatten_dense_tensors. + + Args: + flat (Tensor): flattened dense tensors to unflatten. + tensors (Iterable[Tensor]): dense tensors whose sizes will be used to + unflatten flat. + + Returns: + Unflattened dense tensors with sizes same as tensors and values from + flat. + """ + return torch._C._nn.unflatten_dense_tensors(flat, tensors) + + +def _unflatten_sparse_tensors(flat, tensors): + """View flat buffer (containing indices and values) using the sizes of + tensors. Assume that tensors are of same sparse type, and that flat is given + by _flatten_sparse_tensors. + + Args: + flat (tuple(Tensor, Tensor)): flattened indices and values of sparse + tensors to unflatten. + tensors (Iterable[Tensor]): sparse tensors whose sizes will be used to + unflatten flat. + + Returns: + Unflattened sparse tensors with sizes same as tensors and values from + flat. + """ + flat_indices, flat_values = flat + indices = torch._C._nn.unflatten_dense_tensors( + flat_indices, [torch.Tensor._indices(t) for t in tensors] + ) + values = torch._C._nn.unflatten_dense_tensors( + flat_values, [torch.Tensor._values(t) for t in tensors] + ) + outputs = [] + for t, i, v in zip(tensors, indices, values): + outputs.append(t.new(i, v, t.size())) + return tuple(outputs) + + +def _reorder_tensors_as(tensors, ordered_tensors): + """Assume that tensors are of same order as ordered_tensors within their + types, e.g., from _take_tensors. Reorder them to be of same order as + ordered_tensors. + + Args: + tensors (Iterable[Tensor]): tensors to be reordered. They should be of + the same order as ordered_tensors within their own types. + ordered_tensors (Iterable[Tensor]): tensors whose order will be the + reference. + + Returns: + Ordered tuple of tensors with contents from tensors and order of + ordered_tensors. + """ + type_dict = defaultdict(list) + for tensor in tensors: + type_dict[tensor.type()].append(tensor) + type_dict_ = {t: iter(coll) for t, coll in type_dict.items()} + return tuple(next(type_dict_[tensor.type()]) for tensor in ordered_tensors) + + +def _take_tensors(tensors, size_limit): + """Group tensors into chunks. This generator yields a chunk at each time, + each containing tensors of same type up to certain byte limit in total size. + + Args: + tensors (Sequence): A sequence of tensors to be separated into chunks. + size_limit (int): The limit of each chunk in bytes. + + Yields: + Blocks of tensors of same type and within size_limit. The yielded + tensors are only ordered as the original sequence within its types. + """ + buf_dict: defaultdict[str, list] = defaultdict(lambda: [[], 0]) + for tensor in tensors: + t = tensor.type() + if tensor.is_sparse: + indices = torch.Tensor._indices(tensor) + values = torch.Tensor._values(tensor) + size = ( + indices.numel() * indices.element_size() + + values.numel() * values.element_size() + ) + else: + size = tensor.numel() * tensor.element_size() + buf_and_size = buf_dict[t] + if buf_and_size[1] + size > size_limit and buf_and_size[1] > 0: + yield buf_and_size[0] + buf_and_size = buf_dict[t] = [[], 0] + buf_and_size[0].append(tensor) # pyrefly: ignore [missing-attribute] + buf_and_size[1] += size # pyrefly: ignore [unsupported-operation] + for buf, _ in buf_dict.values(): + if len(buf) > 0: + yield buf + + +def render_call(fn, args, kwargs): + str_fn = torch.overrides.resolve_name(fn) + if str_fn is None: + str_fn = str(fn) + + str_args: list[str] = [] + with torch._tensor_str.printoptions(threshold=0, edgeitems=0): + str_args.extend(repr(a) for a in args) + str_args.extend(f"{k}={repr(v)}" for k, v in kwargs.items()) + r = f"{str_fn}({', '.join(str_args)})" + return r + + +# NOTE [ Python Traceback Reference Cycle Problem ] +# +# When using sys.exc_info(), it is important to **not** store the exc_info[2], +# which is the traceback, because otherwise you will run into the traceback +# reference cycle problem, i.e., the traceback holding reference to the frame, +# and the frame (which holds reference to all the object in its temporary scope) +# holding reference the traceback. + + +class KeyErrorMessage(str): + r"""str subclass that returns itself in repr""" + + __slots__ = () + + def __repr__(self): + return self + + +class ExceptionWrapper: + r"""Wraps an exception plus traceback to communicate across threads""" + + def __init__(self, exc_info=None, where="in background"): + # It is important that we don't store exc_info, see + # NOTE [ Python Traceback Reference Cycle Problem ] + if exc_info is None: + exc_info = sys.exc_info() + self.exc_type = exc_info[0] + + self.exc_msg = "".join(traceback.format_exception(*exc_info)) + self.where = where + + def reraise(self): + r"""Reraises the wrapped exception in the current thread""" + # Format a message such as: "Caught ValueError in DataLoader worker + # process 2. Original Traceback:", followed by the traceback. + msg = f"Caught {self.exc_type.__name__} {self.where}.\nOriginal {self.exc_msg}" # pyrefly: ignore [missing-attribute] + if self.exc_type is KeyError: + # KeyError calls repr() on its argument (usually a dict key). This + # makes stack traces unreadable. It will not be changed in Python + # (https://bugs.python.org/issue2651), so we work around it. + msg = KeyErrorMessage(msg) + elif getattr(self.exc_type, "message", None): + # Some exceptions have first argument as non-str but explicitly + # have message field + # pyrefly: ignore [not-callable] + raise self.exc_type( + # pyrefly: ignore [unexpected-keyword] + message=msg + ) + try: + exception = self.exc_type(msg) # pyrefly: ignore [not-callable] + except Exception: + # If the exception takes multiple arguments or otherwise can't + # be constructed, don't try to instantiate since we don't know how to + raise RuntimeError(msg) from None + raise exception + + +def cpu_count() -> int | None: + """Return the number of CPUs available to the current process. + + Prefers ``os.sched_getaffinity`` (respects cgroups / taskset) and + falls back to ``os.cpu_count``. + """ + # os.process_cpu_count was added in CPython 3.13, see + # https://docs.python.org/3/library/os.html#os.process_cpu_count + if hasattr(os, "sched_getaffinity"): + return len(os.sched_getaffinity(0)) + return os.cpu_count() + + +def _get_available_device_type(): + if torch.cuda.is_available(): + return "cuda" + if torch.backends.mps.is_available(): + return "mps" + if hasattr(torch, "xpu") and torch.xpu.is_available(): # type: ignore[attr-defined] + return "xpu" + if hasattr(torch, "mtia") and torch.mtia.is_available(): + return "mtia" + custom_backend_name = torch._C._get_privateuse1_backend_name() + custom_device_mod = getattr(torch, custom_backend_name, None) + if custom_device_mod and custom_device_mod.is_available(): + return custom_backend_name + # add more available device types here + return None + + +def _get_device_attr(get_member): + device_type = _get_available_device_type() + if device_type and device_type.lower() == "cuda": + return get_member(torch.cuda) + if device_type and device_type.lower() == "mps": + return get_member(torch.mps) + if device_type and device_type.lower() == "xpu": + return get_member(torch.xpu) # type: ignore[attr-defined] + if device_type and device_type.lower() == "mtia": + return get_member(torch.mtia) + if device_type == torch._C._get_privateuse1_backend_name(): + return get_member(getattr(torch, device_type)) + # add more available device types here + return None + + +def _get_current_device_index(): + # current device index + return _get_device_attr(lambda m: m.current_device()) + + +def _get_all_device_indices(): + # all device index + return _get_device_attr(lambda m: list(range(m.device_count()))) + + +def _get_devices_properties(device_ids): + # all device properties + return [_get_device_attr(lambda m: m.get_device_properties(i)) for i in device_ids] + + +def get_current_device_index() -> int: + r"""Checks if there are CUDA devices available and + returns the device index of the current default CUDA device. + Returns -1 in case there are no CUDA devices available. + Arguments: ``None`` + """ + if torch.cuda.device_count() > 0: + return torch.cuda.current_device() + return -1 + + +def _get_device_index( + device: Any, + optional: bool = False, + allow_cpu: bool = False, +) -> int: + r"""Gets the device index from :attr:`device`, which can be a torch.device + object, a Python integer, or ``None``. + + If :attr:`device` is a torch.device object, returns the device index if it + has index. Note that for a device without a specified index, + i.e., ``torch.device('xxx')``, this will return the current default + device of that type if :attr:`optional` is ``True``. If :attr:`allow_cpu` is ``True``, + CPU devices will be accepted and ``-1`` will be returned in this case. + + If :attr:`device` is a Python integer, it is returned as is. + + If :attr:`device` is ``None``, this will return the current default + device of the supported runtime platform if :attr:`optional` is ``True``. + i.e., the current default CUDA device will be returned if CUDA runtime is supported. + """ + if isinstance(device, str): + device = torch.device(device) + device_idx: int | None = None + if isinstance(device, torch.device): + if not allow_cpu and device.type == "cpu": + raise ValueError(f"Expected a non cpu device, but got: {device}") + device_idx = -1 if device.type == "cpu" else device.index + if isinstance(device, int): + device_idx = device + if device_idx is None: + if optional: + # The eager API _get_current_device_index uses `lambda` functions which are + # not supported in JIT and hence not scriptable. The JIT equivalent API to get + # the current device index is `get_current_device_index()` which can + # be scripted. We use is_scripting to check the mode we are in and call the + # appropriate API. + if torch.jit.is_scripting(): + device_idx = get_current_device_index() + else: + device_idx = _get_current_device_index() + else: + raise ValueError( + f"Expected a torch.device with a specified index or an integer, but got:{device}" + ) + return device_idx + + +def _handle_complex(tensor): + """ + Returns a real view of a tensor if complex dtype else just the tensor + need to check if a UninitializedParameter because otherwise checking is_complex is an error for a LazyModule + """ + return ( + torch.view_as_real(tensor) + if not isinstance(tensor, torch.nn.UninitializedParameter) + and tensor.is_complex() + else tensor + ) + + +def _element_size(dtype): + """ + Returns the element size for a dtype, in bytes + """ + if not isinstance(dtype, torch.dtype): + raise RuntimeError(f"expected torch.dtype, but got {type(dtype)}") + + if dtype.is_complex: + return torch.finfo(dtype).bits >> 2 + elif dtype.is_floating_point: + return torch.finfo(dtype).bits >> 3 + elif dtype == torch.bool: + # NOTE: torch.bool is not supported in torch.iinfo() + return 1 + else: + return torch.iinfo(dtype).bits >> 3 + + +class _ClassPropertyDescriptor: + def __init__(self, fget, fset=None): + self.fget = fget + + def __get__(self, instance, owner=None): + if owner is None: + owner = type(instance) + return self.fget.__get__(instance, owner)() + + +def classproperty(func): + if not isinstance(func, (classmethod, staticmethod)): + func = classmethod(func) + return _ClassPropertyDescriptor(func) + + +if TYPE_CHECKING: + # TorchScript does not support `@deprecated` + # This is a workaround to avoid breaking TorchScript + @deprecated( + "`torch._utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.", + category=FutureWarning, + ) + def is_compiling() -> bool: + return torch.compiler.is_compiling() + +else: + + def is_compiling() -> bool: + """ + Indicates whether we are tracing/compiling with torch.compile() or torch.export(). + """ + warnings.warn( # use `warnings.warn` instead of `@deprecated` + "`torch._utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.", + # FutureWarning, # TorchScript does not support Warning type + stacklevel=2, + ) + return torch.compiler.is_compiling() + + +def _functionalize_sync(t): + # This code lives in python instead of C++ since conditioning on a certain python subclass + # is much more of a pain in C++. + from torch._subclasses.functional_tensor import FunctionalTensor + + if isinstance(t, FunctionalTensor): + # If a FunctionalTensorMode is active while syncing, we don't want it to intercept any ops that get called + # when we sync our inner tensor. + # Why? + # (1) If there are input mutations in the graph, then they will be re-applied during + # AOTAutograd when we call _sync() from inside of our functionalization kernels. + # (2) _sync() causes us to regenerate our updated the tensor from the updated base, + # which dispatches to a bunch of view ops + # (3) The input to these view ops is our inner FunctionalTensorWrapper + # (since the sync was called from C++), not the python FunctionalTensor + # (4) if a python FunctionalTensorMode is active, it will complain when it intercepts + # the view op, since it will see an input that is a C++ FunctionalTensorWrapper + # (aka a normal torch.Tensor) instead of a python `FunctionalTensor). + maybe_functional_mode = torch._C._unset_dispatch_mode( + torch._C._TorchDispatchModeKey.FUNCTIONAL + ) + try: + torch._functionalize_sync(t.elem) # type: ignore[attr-defined] + finally: + if maybe_functional_mode is not None: + torch._C._set_dispatch_mode(maybe_functional_mode) + else: + torch._functionalize_sync(t) # type: ignore[attr-defined] + + +@functools.lru_cache(2) +def _get_device_module(device_type: str): + device_module = getattr(torch, device_type, None) + if device_module is None: + raise RuntimeError( + f"Device '{device_type}' does not have a corresponding module registered as 'torch.{device_type}'." + ) + return device_module + + +def _dummy_type(name: str) -> type: + def get_err_fn(is_init: bool): + def err_fn(obj, *args, **kwargs): + if is_init: + class_name = obj.__class__.__name__ + else: + class_name = obj.__name__ + raise RuntimeError(f"Tried to instantiate dummy base class {class_name}") + + return err_fn + + return type( + name, (object,), {"__init__": get_err_fn(True), "__new__": get_err_fn(False)} + ) + + +class _LazySeedTracker: + # Since seeding is memory-less, only track the latest seed. + # Note: `manual_seed_all` followed by `manual_seed` overwrites + # the seed on current device. We track the order of **latest** + # calls between these two API. + def __init__(self): + self.manual_seed_all_cb = None + self.manual_seed_cb = None + self.call_order = [] + + def queue_seed_all(self, cb, traceback): + self.manual_seed_all_cb = (cb, traceback) # pyrefly: ignore [bad-assignment] + # update seed_all to be latest + self.call_order = [self.manual_seed_cb, self.manual_seed_all_cb] + + def queue_seed(self, cb, traceback): + self.manual_seed_cb = (cb, traceback) # pyrefly: ignore [bad-assignment] + # update seed to be latest + self.call_order = [self.manual_seed_all_cb, self.manual_seed_cb] + + def get_calls(self) -> list: + return self.call_order + + +logger = logging.getLogger(__name__) +P = ParamSpec("P") + + +class CallbackRegistry(Generic[P]): + def __init__(self, name: str): + self.name = name + self.callback_list: list[Callable[P, None]] = [] + + def add_callback(self, cb: Callable[P, None]) -> None: + self.callback_list.append(cb) + + def fire_callbacks(self, *args: P.args, **kwargs: P.kwargs) -> None: + for cb in self.callback_list: + try: + cb(*args, **kwargs) + except Exception: + logger.exception( + "Exception in callback for %s registered with gpu trace", self.name + ) + + +def try_import(module_name: str) -> ModuleType | None: + # Implementation based on + # https://docs.python.org/3/library/importlib.html#checking-if-a-module-can-be-imported + if (module := sys.modules.get(module_name, None)) is not None: + return module + + if (spec := importlib.util.find_spec(module_name)) is not None: + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + + # https://docs.python.org/3/library/importlib.html#importlib.machinery.ModuleSpec.loader + # "The finder should always set this attribute" + if spec.loader is None: + raise AssertionError("The loader attribute should always be set") + spec.loader.exec_module(module) + return module + + return None + + +# IMPORT_MAPPING and NAME_MAPPING are adapted from https://github.com/python/cpython/blob/main/Lib/_compat_pickle.py +# for use in the weights_only Unpickler. + +IMPORT_MAPPING = { + "__builtin__": "builtins", + "copy_reg": "copyreg", + "Queue": "queue", + "repr": "reprlib", + "_abcoll": "collections.abc", + # Non-mutual mappings. + "UserDict": "collections", + "UserList": "collections", + "UserString": "collections", + "whichdb": "dbm", + "StringIO": "io", + "cStringIO": "io", +} + + +# This contains rename rules that are easy to handle. We ignore the more +# complex stuff (e.g. mapping the names in the urllib and types modules). +# These rules should be run before import names are fixed. +NAME_MAPPING = { + ("__builtin__", "xrange"): ("builtins", "range"), + ("__builtin__", "reduce"): ("functools", "reduce"), + ("__builtin__", "intern"): ("sys", "intern"), + ("__builtin__", "unichr"): ("builtins", "chr"), + ("__builtin__", "unicode"): ("builtins", "str"), + ("__builtin__", "long"): ("builtins", "int"), + ("itertools", "izip"): ("builtins", "zip"), + ("itertools", "imap"): ("builtins", "map"), + ("itertools", "ifilter"): ("builtins", "filter"), + ("itertools", "ifilterfalse"): ("itertools", "filterfalse"), + ("itertools", "izip_longest"): ("itertools", "zip_longest"), + ("UserDict", "IterableUserDict"): ("collections", "UserDict"), + ("UserList", "UserList"): ("collections", "UserList"), + ("UserString", "UserString"): ("collections", "UserString"), + # Non-mutual mappings. + ("__builtin__", "basestring"): ("builtins", "str"), + ("exceptions", "StandardError"): ("builtins", "Exception"), + ("UserDict", "UserDict"): ("collections", "UserDict"), +} + +# Protocol 2 pickle (torch.save's default) maps builtin exceptions to the +# Python 2 "exceptions" module via REVERSE_NAME_MAPPING; map them back so +# allowlisted exception types resolve under their builtins.* names. +NAME_MAPPING.update( + { + ("exceptions", name): ("builtins", name) + for name in _compat_pickle.PYTHON2_EXCEPTIONS + } +) + + +def _chunk_or_narrow_cat( + tensor: "torch.Tensor", + num_chunks: int, + narrow_dim: int, + cat_dim: int = 0, +) -> "torch.Tensor": + """ + Splits tensor along narrow_dim into num_chunks and concatenates along cat_dim. + Uses torch.chunk in eager mode, but torch.narrow under tracing to be unbacked-symint safe. + """ + if torch.distributed.is_available(): + from torch.distributed._functional_collectives import _are_we_tracing + from torch.fx.experimental.symbolic_shapes import has_free_unbacked_symbols + + # TODO(pianpwk): remove the unbacked symbols check and fix AsyncTP pattern matching + # for test_micro_pipeline_tp.py. + if _are_we_tracing() and has_free_unbacked_symbols(tensor): + chunk_size = tensor.size(narrow_dim) // num_chunks + chunks = [ + torch.narrow(tensor, narrow_dim, i * chunk_size, chunk_size) + for i in range(num_chunks) + ] + return torch.cat(chunks, dim=cat_dim) + return torch.cat(torch.chunk(tensor, num_chunks, dim=narrow_dim), dim=cat_dim) + + +def _maybe_view_chunk_cat( + res: "torch.Tensor", group_size: int, gather_dim: int +) -> "torch.Tensor": + """ + This is intuitively the same as torch.cat(torch.chunk(res, group_size, + dim=0), dim=gather_dim), but returns a view if data movement is not + necessary. This operation arises in NCCL all_gather, where you always get + a result which is concatenated on dim=0, even though actually you may need + to undo this concatenation and then re-cat on the gather dim. + + When is data-movement not necessary? Intuitively, we need to understand if + the unflatten in this reference implementation of this code triggers a + copy or not: + + chunks = torch.unflatten(res, 0, [group_size, -1]) + return torch.flatten(torch.movedim(chunks, 0, gather_dim), gather_dim, gather_dim + 1) + + Assume res is contiguous (it will be coming out of the collective). We + essentially need to know if the movedim maintains the contiguity of the + tensor. Moving a dimension typically does NOT preserve contiguity, unless + EVERY dimension it is moved across is size 1. + + Example: shape [4, d1, d2] with group_size=4, gather_dim=1 -> [1, 4*d1, d2] + + [4, d1, d2] -> [4, 1, d1, d2] -> [1, 4, d1, d2] (contiguous!) + + Example: shape [4, 2, d2] with group_size=4, gather_dim=2 -> [1, 2, 4*d2] + + [4, 2, d2] -> [4, 1, 2, d2] -> [1, 2, 4, d2] (not contiguous!) + + Args: + res: Tensor with gathered data in dim 0, shape [group_size, ...] + group_size: Number of ranks in the group + gather_dim: Dimension to gather along in the output + + Returns: + Tensor with data rearranged to gather along gather_dim + """ + + if gather_dim == 0: + # When gather_dim is 0, chunk+cat is a no-op + return res + + shape = list(res.shape) + + # Optimization: Can use view instead of split+cat when: + # 1. res.shape[0] == group_size (invariant after all_gather) + # 2. All dims between 0 and gather_dim (exclusive) have size 1 + from torch.fx.experimental.symbolic_shapes import guard_or_false + + numel_between = math.prod(shape[1:gather_dim]) if gather_dim > 1 else 1 + + if guard_or_false(shape[0] == group_size) and guard_or_false(numel_between == 1): + # View optimization: reshape to collapse dim 0 into gather_dim + final_shape = ( + [1] # Dim 0 becomes 1 + + shape[1:gather_dim] # Dims 1 to gather_dim-1 unchanged + + [shape[0] * shape[gather_dim]] # gather_dim gets multiplied by group_size + + shape[gather_dim + 1 :] # Rest unchanged + ) + return res.view(final_shape) + else: + # General case: fall back to split + cat + # This is better than torch.flatten as cat can be vectorized, whereas + # the contiguous kernel is always bad. + return _chunk_or_narrow_cat(res, group_size, narrow_dim=0, cat_dim=gather_dim) + + +class _Frame(TypedDict): + """Frame information from memory profiler snapshots.""" + + filename: str + line: int + name: str + # Fields added by FX augmentation (optional) + fx_node_op: NotRequired[str] + fx_node_name: NotRequired[str] + fx_node_target: NotRequired[str] + fx_original_trace: NotRequired[str] + + +class _Block(TypedDict): + """Memory block information.""" + + size: int + requested_size: int + address: int + state: str + frames: list[_Frame] + + +class _Segment(TypedDict): + """Memory segment information.""" + + address: int + total_size: int + stream: int + segment_type: str + allocated_size: int + active_size: int + blocks: list[_Block] + + +class _TraceEntry(TypedDict): + """Memory trace entry information.""" + + action: str + addr: NotRequired[int] + frames: list[_Frame] + size: int + stream: int + device_free: NotRequired[int] + + +class _Snapshot(TypedDict): + """Memory snapshot structure.""" + + segments: list[_Segment] + device_traces: NotRequired[list[list[_TraceEntry]]] + + +def _augment_frames(frames: list[_Frame]) -> int: + """ + Augment a list of frames with FX debug information. For each frame corresponding + to an FX-generated Python file, this function attaches additional FX node + metadata (op, name, target, and original trace). + + Args: + frames (list[_Frame]): List of frame dictionaries to augment + + Returns: + int: The count of frames that were augmented. + """ + from torch.fx.graph_module import FX_GRAPH_MODULE_FILE_PREFIX + from torch.fx.traceback import _FX_METADATA_REGISTRY + + # Regex pattern to match FX generated files + _FX_GENERATED_PATTERN = re.compile( + rf"{re.escape(FX_GRAPH_MODULE_FILE_PREFIX)}.*\.py$" + ) + + count = 0 + + for frame in frames: + filename = frame.get("filename") + lineno = frame.get("line") + if not filename or not lineno: + continue + + # Check if this looks like an FX generated file + if not _FX_GENERATED_PATTERN.search(os.path.basename(filename)): + continue + + metadata = _FX_METADATA_REGISTRY.get(filename) + if metadata is None: + continue + + lineno_map = metadata.get("lineno_map", {}) + node_metadata = metadata.get("node_metadata", {}) + prologue_start = metadata.get("prologue_start", 0) + + # Get the node index for this line + node_idx = lineno_map.get(lineno - prologue_start) + if node_idx is None: + continue + + node_info = node_metadata.get(node_idx) + if node_info is None: + continue + + # Populate FX metadata fields + frame["fx_node_op"] = node_info.get("op") + frame["fx_node_name"] = node_info.get("name") + frame["fx_node_target"] = str(node_info.get("target")) + + # Attach original stack trace if available + original_trace = node_info.get("stack_trace") + if original_trace: + frame["fx_original_trace"] = original_trace + + count += 1 + + return count + + +def _augment_memory_snapshot_stack_traces( + snapshot: str | _Snapshot, +) -> _Snapshot: + """ + Augment a memory snapshot with original source stack traces from FX metadata. + + IMPORTANT: This function reads from a global in-memory registry (_FX_METADATA_REGISTRY) + that is populated during graph module compilation. It must be called in the same + Python process where the FX graphs were compiled. It cannot be used to augment + snapshots loaded from disk in a different process. + + Args: + snapshot (str or _Snapshot): Either a memory snapshot dict or path to a snapshot pickle file + + Returns: + _Snapshot: The augmented snapshot dictionary with fx_node_op, fx_node_name, + fx_original_trace, and fx_node_info fields added to frames + """ + + snapshot_dict: _Snapshot + if isinstance(snapshot, str): + # Load the memory snapshot + with open(snapshot, "rb") as f: + snapshot_dict = cast(_Snapshot, pickle.load(f)) + else: + snapshot_dict = snapshot + + # Process blocks in segments (for regular allocations) + for segment in snapshot_dict.get("segments", []): + for block in segment.get("blocks", []): + if "frames" in block: + _augment_frames(block["frames"]) + + # Process device traces (for memory history) + for trace_list in snapshot_dict.get("device_traces", []): + for trace_entry in trace_list: + if isinstance(trace_entry, dict) and "frames" in trace_entry: + _augment_frames(trace_entry["frames"]) + + return snapshot_dict + + +def _is_privateuse1_backend_available(): + """ + Determines whether the privateuse1 backend is registered and available. + + Returns: + Return True if the privateuse1 backend is registered and available. + """ + privateuse1_backend_name = torch._C._get_privateuse1_backend_name() + privateuse1_backend_module = getattr(torch, privateuse1_backend_name, None) + return ( + is_available := getattr(privateuse1_backend_module, "is_available", None) + ) and is_available() + + +def getenv(name: str) -> "str | None": + """Read an environment variable through torch's serialized env access. + + Prefer this over :func:`os.getenv` when torch is loaded: it shares c10's + environment mutex, so the read is consistent with concurrent C++ code and + other :func:`torch._utils.setenv` calls that also go through c10. + + Args: + name: Name of the environment variable. + + Returns: + The variable's value, or ``None`` if it is not set. + """ + return torch._C._getenv(name) + + +def setenv(name: str, value: str, overwrite: bool = True) -> None: + """Set an environment variable through torch's serialized env access. + + Prefer this over assigning to :data:`os.environ` when torch is loaded: it + shares c10's environment mutex, so the write is consistent with concurrent + C++ code and other :func:`torch._utils.getenv` calls that also go through + c10. + + Args: + name: Name of the environment variable. + value: Value to set. + overwrite: If ``False`` and the variable is already set, leave it + unchanged. Defaults to ``True``. + """ + torch._C._setenv(name, value, overwrite) + + +def unsetenv(name: str) -> None: + """Remove an environment variable through torch's serialized env access. + + The counterpart to :func:`setenv`; shares c10's environment mutex. + + Args: + name: Name of the environment variable to remove. + """ + torch._C._unsetenv(name) + + +# Saved originals so os.environ interception can be reverted; ``None`` means the +# hook is not currently installed. +_original_os_putenv: "Callable[..., None] | None" = None +_original_os_unsetenv: "Callable[..., None] | None" = None + + +def _torch_putenv(key: "str | bytes", value: "str | bytes") -> None: + setenv(os.fsdecode(key), os.fsdecode(value)) + + +def _torch_unsetenv(key: "str | bytes") -> None: + unsetenv(os.fsdecode(key)) + + +def install_os_environ_hook() -> None: + """Route ``os.environ`` mutations through torch's serialized env access. + + CPython's ``os.environ.__setitem__`` / ``__delitem__`` call the module-level + ``os.putenv`` / ``os.unsetenv`` and then update ``os.environ``'s cached dict. + This replaces those two functions so that mutating ``os.environ`` (and any + direct ``os.putenv`` / ``os.unsetenv`` call) goes through c10's environment + mutex, keeping Python and C++ env access consistent. The cached dict is still + updated by CPython afterwards, so ``os.environ`` reads stay correct. + + Idempotent: calling it again while installed is a no-op. Use + :func:`remove_os_environ_hook` to revert. + """ + global _original_os_putenv, _original_os_unsetenv + if _original_os_putenv is not None: + return + _original_os_putenv = os.putenv + _original_os_unsetenv = os.unsetenv + os.putenv = _torch_putenv # type: ignore[assignment] + os.unsetenv = _torch_unsetenv # type: ignore[assignment] + + +def remove_os_environ_hook() -> None: + """Undo :func:`install_os_environ_hook`; a no-op if it was not installed.""" + global _original_os_putenv, _original_os_unsetenv + if _original_os_putenv is None or _original_os_unsetenv is None: + return + os.putenv = _original_os_putenv + os.unsetenv = _original_os_unsetenv + _original_os_putenv = None + _original_os_unsetenv = None diff --git a/.venv/lib/python3.12/site-packages/torch/_utils_internal.py b/.venv/lib/python3.12/site-packages/torch/_utils_internal.py new file mode 100644 index 0000000000000000000000000000000000000000..e98d53a47c1155e2828d3bea661d30e0730d5d83 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_utils_internal.py @@ -0,0 +1,411 @@ +# mypy: allow-untyped-defs +import functools +import logging +import os +import sys +import tempfile +import typing_extensions +from collections.abc import Callable +from typing import Any, TypeVar +from typing_extensions import ParamSpec + +import torch +from torch._strobelight.compile_time_profiler import StrobelightCompileTimeProfiler + + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +log = logging.getLogger(__name__) + +if os.environ.get("TORCH_COMPILE_STROBELIGHT", False): + import shutil + + if not shutil.which("strobeclient"): + log.info( + "TORCH_COMPILE_STROBELIGHT is true, but seems like you are not on a FB machine." + ) + else: + log.info("Strobelight profiler is enabled via environment variable") + StrobelightCompileTimeProfiler.enable() + +# this arbitrary-looking assortment of functionality is provided here +# to have a central place for overridable behavior. The motivating +# use is the FB build environment, where this source file is replaced +# by an equivalent. + + +def _compute_torch_parent() -> str: + torch_dir = os.path.dirname(os.path.abspath(__file__)) + if os.path.basename(torch_dir) == "shared": + return os.path.dirname(os.path.dirname(torch_dir)) + # In scikit-build-core editable installs with redirect mode, binary + # artifacts (bin/, lib/) are installed to the dist package directory + # rather than the source tree. Fall back to the installed package + # location for get_file_path. + if not os.path.isdir(os.path.join(torch_dir, "bin")): + try: + from importlib.metadata import distribution + + installed = str(distribution("torch").locate_file("torch")) + if os.path.isdir(os.path.join(installed, "bin")): + return os.path.dirname(installed) + except Exception: + pass + return os.path.dirname(torch_dir) + + +torch_parent = _compute_torch_parent() + + +def get_file_path(*path_components: str) -> str: + return os.path.join(torch_parent, *path_components) + + +def get_file_path_2(*path_components: str) -> str: + return os.path.join(*path_components) + + +def get_writable_path(path: str) -> str: + if os.access(path, os.W_OK): + return path + return tempfile.mkdtemp(suffix=os.path.basename(path)) + + +def prepare_multiprocessing_environment(path: str) -> None: + pass + + +def resolve_library_path(path: str) -> str: + return os.path.realpath(path) + + +def throw_abstract_impl_not_imported_error(opname, module, context): + if module in sys.modules: + raise NotImplementedError( + f"{opname}: We could not find the fake impl for this operator. " + ) + else: + raise NotImplementedError( + f"{opname}: We could not find the fake impl for this operator. " + f"The operator specified that you may need to import the '{module}' " + f"Python module to load the fake impl. {context}" + ) + + +# NB! This treats "skip" kwarg specially!! +def compile_time_strobelight_meta( + phase_name: str, +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + def compile_time_strobelight_meta_inner( + function: Callable[_P, _T], + ) -> Callable[_P, _T]: + @functools.wraps(function) + def wrapper_function(*args: _P.args, **kwargs: _P.kwargs) -> _T: + if "skip" in kwargs and isinstance( + skip := kwargs["skip"], + int, + ): + kwargs["skip"] = skip + 1 + + # This is not needed but we have it here to avoid having profile_compile_time + # in stack traces when profiling is not enabled. + if not StrobelightCompileTimeProfiler.enabled: + return function(*args, **kwargs) + + return StrobelightCompileTimeProfiler.profile_compile_time( + function, phase_name, *args, **kwargs + ) + + return wrapper_function + + return compile_time_strobelight_meta_inner + + +# Meta only, see +# https://www.internalfb.com/intern/wiki/ML_Workflow_Observability/User_Guides/Adding_instrumentation_to_your_code/ +# +# This will cause an event to get logged to Scuba via the signposts API. You +# can view samples on the API at https://fburl.com/scuba/workflow_signpost/zh9wmpqs +# we log to subsystem "torch", and the category and name you provide here. +# Each of the arguments translate into a Scuba column. We're still figuring +# out local conventions in PyTorch, but category should be something like +# "dynamo" or "inductor", and name should be a specific string describing what +# kind of event happened. +# +# Killswitch is at +# https://www.internalfb.com/intern/justknobs/?name=pytorch%2Fsignpost#event +def signpost_event(category: str, name: str, parameters: dict[str, Any]): + log.info("%s %s: %r", category, name, parameters) + + +def add_mlhub_insight(category: str, insight: str, insight_description: str): + pass + + +def log_compilation_event(metrics): + log.info("%s", metrics) + + +def upload_graph(graph): + pass + + +def set_pytorch_distributed_envs_from_justknobs(): + pass + + +def log_export_usage(**kwargs): + pass + + +def log_draft_export_usage(**kwargs): + pass + + +def log_trace_structured_event(*args, **kwargs) -> None: + pass + + +def log_cache_bypass(*args, **kwargs) -> None: + pass + + +def log_torchscript_usage(api: str, **kwargs): + _ = api + return + + +def check_if_torch_exportable(): + return False + + +def export_training_ir_rollout_check() -> bool: + return True + + +def full_aoti_runtime_assert() -> bool: + return True + + +def log_torch_jit_trace_exportability( + api: str, + type_of_export: str, + export_outcome: str, + result: str, +): + _, _, _, _ = api, type_of_export, export_outcome, result + return + + +DISABLE_JUSTKNOBS = True + + +def justknobs_check(name: str, default: bool = True) -> bool: + """ + This function can be used to killswitch functionality in FB prod, + where you can toggle this value to False in JK without having to + do a code push. In OSS, we always have everything turned on all + the time, because downstream users can simply choose to not update + PyTorch. (If more fine-grained enable/disable is needed, we could + potentially have a map we lookup name in to toggle behavior. But + the point is that it's all tied to source code in OSS, since there's + no live server to query.) + + This is the bare minimum functionality I needed to do some killswitches. + We have a more detailed plan at + https://docs.google.com/document/d/1Ukerh9_42SeGh89J-tGtecpHBPwGlkQ043pddkKb3PU/edit + In particular, in some circumstances it may be necessary to read in + a knob once at process start, and then use it consistently for the + rest of the process. Future functionality will codify these patterns + into a better high level API. + + WARNING: Do NOT call this function at module import time, JK is not + fork safe and you will break anyone who forks the process and then + hits JK again. + """ + return default + + +def justknobs_getval_int(name: str) -> int: + """ + Read warning on justknobs_check + """ + return 0 + + +def is_fb_unit_test() -> bool: + return False + + +@functools.cache +def max_clock_rate(): + """ + unit: MHz + """ + if not torch.version.hip: + from triton.testing import nvsmi + + try: + return nvsmi(["clocks.max.sm"])[0] + except FileNotFoundError: + import pynvml # type: ignore[import] + + handle = torch.cuda._get_pynvml_handler() + try: + return pynvml.nvmlDeviceGetMaxClockInfo(handle, pynvml.NVML_CLOCK_SM) + finally: + pynvml.nvmlShutdown() + else: + # Manually set max-clock speeds on ROCm until equivalent nvmsi + # functionality in triton.testing or via pyamdsmi enablement. Required + # for test_snode_runtime unit tests. + gcn_arch = str(torch.cuda.get_device_properties(0).gcnArchName.split(":", 1)[0]) + if "gfx94" in gcn_arch: + return 1700 + elif "gfx90a" in gcn_arch: + return 1700 + elif "gfx908" in gcn_arch: + return 1502 + elif "gfx12" in gcn_arch: + return 1700 + elif "gfx11" in gcn_arch: + return 1700 + elif "gfx103" in gcn_arch: + return 1967 + elif "gfx101" in gcn_arch: + return 1144 + elif "gfx95" in gcn_arch: + return 1700 # TODO: placeholder, get actual value + else: + return 1100 + + +def get_mast_job_name_version() -> tuple[str, int] | None: + return None + + +TEST_MASTER_ADDR = "127.0.0.1" +TEST_MASTER_PORT = 29500 +# USE_GLOBAL_DEPS controls whether __init__.py tries to load +# libtorch_global_deps, see Note [Global dependencies] +USE_GLOBAL_DEPS = True +# USE_RTLD_GLOBAL_WITH_LIBTORCH controls whether __init__.py tries to load +# _C.so with RTLD_GLOBAL during the call to dlopen. +USE_RTLD_GLOBAL_WITH_LIBTORCH = False +# If an op was defined in C++ and extended from Python using the +# torch.library.register_fake, returns if we require that there be a +# m.set_python_module("mylib.ops") call from C++ that associates +# the C++ op with a python module. +REQUIRES_SET_PYTHON_MODULE = False + + +def maybe_upload_prof_stats_to_manifold(profile_path: str) -> str | None: + print("Uploading profile stats (fb-only otherwise no-op)") + return None + + +def log_chromium_event_internal( + event: dict[str, Any], + stack: list[str], + logger_uuid: str, + start_time_ns: int, +): + return None + + +def record_chromium_event_internal( + event: dict[str, Any], +): + return None + + +def profiler_allow_cudagraph_cupti_lazy_reinit_cuda12(): + return True + + +def deprecated(): + """ + When we deprecate a function that might still be in use, we make it internal + by adding a leading underscore. This decorator is used with a private function, + and creates a public alias without the leading underscore, but has a deprecation + warning. This tells users "THIS FUNCTION IS DEPRECATED, please use something else" + without breaking them, however, if they still really really want to use the + deprecated function without the warning, they can do so by using the internal + function name. + """ + + def decorator(func: Callable[_P, _T]) -> Callable[_P, _T]: + # Validate naming convention - single leading underscore, not dunder + if not (func.__name__.startswith("_")): + raise ValueError( + "@deprecate must decorate a function whose name " + "starts with a single leading underscore (e.g. '_foo') as the api should be considered internal for deprecation." + ) + + public_name = func.__name__[1:] # drop exactly one leading underscore + module = sys.modules[func.__module__] + + # Don't clobber an existing symbol accidentally. + if hasattr(module, public_name): + raise RuntimeError( + f"Cannot create alias '{public_name}' -> symbol already exists in {module.__name__}. \ + Please rename it or consult a pytorch developer on what to do" + ) + + warning_msg = f"{func.__name__[1:]} is DEPRECATED, please consider using an alternative API(s). " + + # public deprecated alias + alias = typing_extensions.deprecated( + # pyrefly: ignore [bad-argument-type] + warning_msg, + category=UserWarning, + stacklevel=1, + )(func) + + alias.__name__ = public_name + + # Adjust qualname if nested inside a class or another function + if "." in func.__qualname__: + alias.__qualname__ = func.__qualname__.rsplit(".", 1)[0] + "." + public_name + else: + alias.__qualname__ = public_name + + setattr(module, public_name, alias) + + return func + + return decorator + + +def get_default_numa_options(): + """ + When using elastic agent, if no numa options are provided, we will use these + as the default. + + For external use cases, we return None, i.e. no numa binding. If you would like + to use torch's automatic numa binding capabilities, you should provide + NumaOptions to your launch config directly or use the numa binding option + available in torchrun. + + Must return None or NumaOptions, but not specifying to avoid circular import. + """ + return None + + +def log_triton_builds(fail: str | None): + pass + + +def find_compile_subproc_binary() -> str | None: + """ + Allows overriding the binary used for subprocesses + """ + return None + + +def get_torch_source_version() -> str: + """Return the source commit hash for the current PyTorch build.""" + import torch.version as torch_version + + return getattr(torch_version, "git_version", "") diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/__init__.py b/.venv/lib/python3.12/site-packages/torch/_vendor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28e03bb3fa03aae66ec0a0c2ad9994d00c3a4853 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/LICENSE b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6f62d44e4ef733c0e713afcd2371fed7f2b3de67 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/LICENSE @@ -0,0 +1,3 @@ +This software is made available under the terms of *either* of the licenses +found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made +under the terms of *both* these licenses. diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/LICENSE.APACHE b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/LICENSE.APACHE new file mode 100644 index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/LICENSE.APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/LICENSE.BSD b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/LICENSE.BSD new file mode 100644 index 0000000000000000000000000000000000000000..42ce7b75c92fb01a3f6ed17eea363f756b7da582 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/LICENSE.BSD @@ -0,0 +1,23 @@ +Copyright (c) Donald Stufft and individual contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/__init__.py b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..22809cfd5dc25792d77070c269fc8d111a12eed0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/__init__.py @@ -0,0 +1,15 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +__title__ = "packaging" +__summary__ = "Core utilities for Python packages" +__uri__ = "https://github.com/pypa/packaging" + +__version__ = "23.2" + +__author__ = "Donald Stufft and individual contributors" +__email__ = "donald@stufft.io" + +__license__ = "BSD-2-Clause or Apache-2.0" +__copyright__ = "2014 %s" % __author__ diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fe0290e3df82f71812afcb0d63e5e09d41637d7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/__pycache__/_structures.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/__pycache__/_structures.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cddedb01039befe205df4ca45b4e607af87551ae Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/__pycache__/_structures.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/__pycache__/version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20e74692c75f6b53665bbd3e5ab40c85fd780a5f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/__pycache__/version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/_structures.py b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..90a6465f9682c886363eea5327dac64bf623a6ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/_structures.py @@ -0,0 +1,61 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + + +class InfinityType: + def __repr__(self) -> str: + return "Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return False + + def __le__(self, other: object) -> bool: + return False + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return True + + def __ge__(self, other: object) -> bool: + return True + + def __neg__(self: object) -> "NegativeInfinityType": + return NegativeInfinity + + +Infinity = InfinityType() + + +class NegativeInfinityType: + def __repr__(self) -> str: + return "-Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return True + + def __le__(self, other: object) -> bool: + return True + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return False + + def __ge__(self, other: object) -> bool: + return False + + def __neg__(self: object) -> InfinityType: + return Infinity + + +NegativeInfinity = NegativeInfinityType() diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/version.py b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/version.py new file mode 100644 index 0000000000000000000000000000000000000000..5faab9bd0dcf28847960162b2b4f13a8a556ef20 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_vendor/packaging/version.py @@ -0,0 +1,563 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.version import parse, Version +""" + +import itertools +import re +from typing import Any, Callable, NamedTuple, Optional, SupportsInt, Tuple, Union + +from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType + +__all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"] + +LocalType = Tuple[Union[int, str], ...] + +CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]] +CmpLocalType = Union[ + NegativeInfinityType, + Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...], +] +CmpKey = Tuple[ + int, + Tuple[int, ...], + CmpPrePostDevType, + CmpPrePostDevType, + CmpPrePostDevType, + CmpLocalType, +] +VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] + + +class _Version(NamedTuple): + epoch: int + release: Tuple[int, ...] + dev: Optional[Tuple[str, int]] + pre: Optional[Tuple[str, int]] + post: Optional[Tuple[str, int]] + local: Optional[LocalType] + + +def parse(version: str) -> "Version": + """Parse the given version string. + + >>> parse('1.0.dev1') + + + :param version: The version string to parse. + :raises InvalidVersion: When the version string is not a valid version. + """ + return Version(version) + + +class InvalidVersion(ValueError): + """Raised when a version string is not a valid version. + + >>> Version("invalid") + Traceback (most recent call last): + ... + packaging.version.InvalidVersion: Invalid version: 'invalid' + """ + + +class _BaseVersion: + _key: Tuple[Any, ...] + + def __hash__(self) -> int: + return hash(self._key) + + # Please keep the duplicated `isinstance` check + # in the six comparisons hereunder + # unless you find a way to avoid adding overhead function calls. + def __lt__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key < other._key + + def __le__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key <= other._key + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key == other._key + + def __ge__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key >= other._key + + def __gt__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key > other._key + + def __ne__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key != other._key + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse +_VERSION_PATTERN = r""" + v? + (?: + (?:(?P[0-9]+)!)? # epoch + (?P[0-9]+(?:\.[0-9]+)*) # release segment + (?P
                                          # pre-release
+            [-_\.]?
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+VERSION_PATTERN = _VERSION_PATTERN
+"""
+A string containing the regular expression used to match a valid version.
+
+The pattern is not anchored at either end, and is intended for embedding in larger
+expressions (for example, matching a version number as part of a file name). The
+regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
+flags set.
+
+:meta hide-value:
+"""
+
+
+class Version(_BaseVersion):
+    """This class abstracts handling of a project's versions.
+
+    A :class:`Version` instance is comparison aware and can be compared and
+    sorted using the standard Python interfaces.
+
+    >>> v1 = Version("1.0a5")
+    >>> v2 = Version("1.0")
+    >>> v1
+    
+    >>> v2
+    
+    >>> v1 < v2
+    True
+    >>> v1 == v2
+    False
+    >>> v1 > v2
+    False
+    >>> v1 >= v2
+    False
+    >>> v1 <= v2
+    True
+    """
+
+    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
+    _key: CmpKey
+
+    def __init__(self, version: str) -> None:
+        """Initialize a Version object.
+
+        :param version:
+            The string representation of a version which will be parsed and normalized
+            before use.
+        :raises InvalidVersion:
+            If the ``version`` does not conform to PEP 440 in any way then this
+            exception will be raised.
+        """
+
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: '{version}'")
+
+        # Store the parsed out pieces of the version
+        self._version = _Version(
+            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+            release=tuple(int(i) for i in match.group("release").split(".")),
+            pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
+            post=_parse_letter_version(
+                match.group("post_l"), match.group("post_n1") or match.group("post_n2")
+            ),
+            dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
+            local=_parse_local_version(match.group("local")),
+        )
+
+        # Generate a key which will be used for sorting
+        self._key = _cmpkey(
+            self._version.epoch,
+            self._version.release,
+            self._version.pre,
+            self._version.post,
+            self._version.dev,
+            self._version.local,
+        )
+
+    def __repr__(self) -> str:
+        """A representation of the Version that shows all internal state.
+
+        >>> Version('1.0.0')
+        
+        """
+        return f""
+
+    def __str__(self) -> str:
+        """A string representation of the version that can be rounded-tripped.
+
+        >>> str(Version("1.0a5"))
+        '1.0a5'
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        # Pre-release
+        if self.pre is not None:
+            parts.append("".join(str(x) for x in self.pre))
+
+        # Post-release
+        if self.post is not None:
+            parts.append(f".post{self.post}")
+
+        # Development release
+        if self.dev is not None:
+            parts.append(f".dev{self.dev}")
+
+        # Local version segment
+        if self.local is not None:
+            parts.append(f"+{self.local}")
+
+        return "".join(parts)
+
+    @property
+    def epoch(self) -> int:
+        """The epoch of the version.
+
+        >>> Version("2.0.0").epoch
+        0
+        >>> Version("1!2.0.0").epoch
+        1
+        """
+        return self._version.epoch
+
+    @property
+    def release(self) -> Tuple[int, ...]:
+        """The components of the "release" segment of the version.
+
+        >>> Version("1.2.3").release
+        (1, 2, 3)
+        >>> Version("2.0.0").release
+        (2, 0, 0)
+        >>> Version("1!2.0.0.post0").release
+        (2, 0, 0)
+
+        Includes trailing zeroes but not the epoch or any pre-release / development /
+        post-release suffixes.
+        """
+        return self._version.release
+
+    @property
+    def pre(self) -> Optional[Tuple[str, int]]:
+        """The pre-release segment of the version.
+
+        >>> print(Version("1.2.3").pre)
+        None
+        >>> Version("1.2.3a1").pre
+        ('a', 1)
+        >>> Version("1.2.3b1").pre
+        ('b', 1)
+        >>> Version("1.2.3rc1").pre
+        ('rc', 1)
+        """
+        return self._version.pre
+
+    @property
+    def post(self) -> Optional[int]:
+        """The post-release number of the version.
+
+        >>> print(Version("1.2.3").post)
+        None
+        >>> Version("1.2.3.post1").post
+        1
+        """
+        return self._version.post[1] if self._version.post else None
+
+    @property
+    def dev(self) -> Optional[int]:
+        """The development number of the version.
+
+        >>> print(Version("1.2.3").dev)
+        None
+        >>> Version("1.2.3.dev1").dev
+        1
+        """
+        return self._version.dev[1] if self._version.dev else None
+
+    @property
+    def local(self) -> Optional[str]:
+        """The local version segment of the version.
+
+        >>> print(Version("1.2.3").local)
+        None
+        >>> Version("1.2.3+abc").local
+        'abc'
+        """
+        if self._version.local:
+            return ".".join(str(x) for x in self._version.local)
+        else:
+            return None
+
+    @property
+    def public(self) -> str:
+        """The public portion of the version.
+
+        >>> Version("1.2.3").public
+        '1.2.3'
+        >>> Version("1.2.3+abc").public
+        '1.2.3'
+        >>> Version("1.2.3+abc.dev1").public
+        '1.2.3'
+        """
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self) -> str:
+        """The "base version" of the version.
+
+        >>> Version("1.2.3").base_version
+        '1.2.3'
+        >>> Version("1.2.3+abc").base_version
+        '1.2.3'
+        >>> Version("1!1.2.3+abc.dev1").base_version
+        '1!1.2.3'
+
+        The "base version" is the public version of the project without any pre or post
+        release markers.
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        return "".join(parts)
+
+    @property
+    def is_prerelease(self) -> bool:
+        """Whether this version is a pre-release.
+
+        >>> Version("1.2.3").is_prerelease
+        False
+        >>> Version("1.2.3a1").is_prerelease
+        True
+        >>> Version("1.2.3b1").is_prerelease
+        True
+        >>> Version("1.2.3rc1").is_prerelease
+        True
+        >>> Version("1.2.3dev1").is_prerelease
+        True
+        """
+        return self.dev is not None or self.pre is not None
+
+    @property
+    def is_postrelease(self) -> bool:
+        """Whether this version is a post-release.
+
+        >>> Version("1.2.3").is_postrelease
+        False
+        >>> Version("1.2.3.post1").is_postrelease
+        True
+        """
+        return self.post is not None
+
+    @property
+    def is_devrelease(self) -> bool:
+        """Whether this version is a development release.
+
+        >>> Version("1.2.3").is_devrelease
+        False
+        >>> Version("1.2.3.dev1").is_devrelease
+        True
+        """
+        return self.dev is not None
+
+    @property
+    def major(self) -> int:
+        """The first item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").major
+        1
+        """
+        return self.release[0] if len(self.release) >= 1 else 0
+
+    @property
+    def minor(self) -> int:
+        """The second item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").minor
+        2
+        >>> Version("1").minor
+        0
+        """
+        return self.release[1] if len(self.release) >= 2 else 0
+
+    @property
+    def micro(self) -> int:
+        """The third item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").micro
+        3
+        >>> Version("1").micro
+        0
+        """
+        return self.release[2] if len(self.release) >= 3 else 0
+
+
+def _parse_letter_version(
+    letter: Optional[str], number: Union[str, bytes, SupportsInt, None]
+) -> Optional[Tuple[str, int]]:
+
+    if letter:
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a numeral associated with it.
+        if number is None:
+            number = 0
+
+        # We normalize any letters to their lower case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        if letter == "alpha":
+            letter = "a"
+        elif letter == "beta":
+            letter = "b"
+        elif letter in ["c", "pre", "preview"]:
+            letter = "rc"
+        elif letter in ["rev", "r"]:
+            letter = "post"
+
+        return letter, int(number)
+    if not letter and number:
+        # We assume if we are given a number, but we are not given a letter
+        # then this is using the implicit post release syntax (e.g. 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+    return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: Optional[str]) -> Optional[LocalType]:
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_separators.split(local)
+        )
+    return None
+
+
+def _cmpkey(
+    epoch: int,
+    release: Tuple[int, ...],
+    pre: Optional[Tuple[str, int]],
+    post: Optional[Tuple[str, int]],
+    dev: Optional[Tuple[str, int]],
+    local: Optional[LocalType],
+) -> CmpKey:
+
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. So we'll use a reverse the list, drop all the now
+    # leading zeros until we come to something non zero, then take the rest
+    # re-reverse it back into the correct order and make it a tuple and use
+    # that for our sorting key.
+    _release = tuple(
+        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
+    )
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre segment, but we _only_ want to do this
+    # if there is not a pre or a post segment. If we have one of those then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        _pre: CmpPrePostDevType = NegativeInfinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        _pre = Infinity
+    else:
+        _pre = pre
+
+    # Versions without a post segment should sort before those with one.
+    if post is None:
+        _post: CmpPrePostDevType = NegativeInfinity
+
+    else:
+        _post = post
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        _dev: CmpPrePostDevType = Infinity
+
+    else:
+        _dev = dev
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        _local: CmpLocalType = NegativeInfinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alpha numeric segments sort before numeric segments
+        # - Alpha numeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        _local = tuple(
+            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
+        )
+
+    return epoch, _release, _pre, _post, _dev, _local
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/LICENSE b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/LICENSE
@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__init__.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..838c5c2882cd8097035c9d529e7d548f2d6342c0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__init__.py
@@ -0,0 +1,37 @@
+"""Vendored subset of the quack library (https://github.com/Dao-AILab/quack).
+
+The pinned upstream commit is recorded in ``__upstream_sha__`` below and is
+sourced from ``PINNED_SHA`` in tools/vendoring/quack/vendor.sh. The
+vendoring script verifies that commit is reachable from Dao-AILab/quack main
+before applying the local FlexGEMM patchset. Only the modules required by
+torch._native.ops.norm.rmsnorm_impl and selected GEMM epilogue implementation
+paths are vendored. Imports are rewritten to be package-relative
+so this copy is independent of any ``quack`` top-level package that may be
+installed via pip. Custom op namespaces are renamed from ``quack::`` to
+``torch_vendor_quack::`` for the same reason.
+"""
+__version__ = "0.5.0"
+__upstream_sha__ = "99bd7973bf3dc6db40961e413d4bdfea6c6fee3e"
+
+# Two CuTeDSL workarounds, both must run before the first cute.compile call:
+#   - cutlass#3161: duplicate .text section flags break MCJIT in multi-process
+#     loads (see cute_dsl_elf_fix).
+#   - cutlass#3062: ir.Context spawns LLVM thread pools that leak across
+#     compiles, eventually exhausting pthreads (see cute_dsl_mlir_threading).
+from . import cute_dsl_elf_fix
+from . import cute_dsl_mlir_threading
+
+cute_dsl_elf_fix.patch()
+cute_dsl_mlir_threading.patch()
+
+def __getattr__(name):
+    if name == "rmsnorm":
+        from .rmsnorm import rmsnorm
+
+        return rmsnorm
+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
+__all__ = [
+    "rmsnorm",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e234af57a7e554f68f955eab6ad4ad87e0343a5c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/_compile_worker.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/_compile_worker.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bbb281d7a185568caf3400213d960a7d8f43ddab
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/_compile_worker.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/activation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/activation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..07d5f66b620e139f632305715126acb3eb477ead
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/activation.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/autotuner.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/autotuner.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..339997c5c09b8be6bd1db05207dd56ec51463577
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/autotuner.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/blockscaled_gemm_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/blockscaled_gemm_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac36fb178fa1f3ec5efa0d57c59ebcc6d36906c4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/blockscaled_gemm_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/compile_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/compile_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b25bdcadf2d6c1c6ec7a3a4a8d57847d77f445e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/compile_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/copy_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/copy_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8a946b628e23060608baf46a7c1eed1cf86d645
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/copy_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/cute_dsl_elf_fix.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/cute_dsl_elf_fix.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..28d742145d405ee2edd55c269975a2d7c952e04e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/cute_dsl_elf_fix.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/cute_dsl_mlir_threading.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/cute_dsl_mlir_threading.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b168b37afde4b6723fca6ece99af0ec4dea7fc5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/cute_dsl_mlir_threading.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/cute_dsl_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/cute_dsl_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9848db400a2daa876a3065c735de9d901f4746c5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/cute_dsl_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/epi_composable.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/epi_composable.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..858674f6dd8cbbf228a79e7663d4829dbea6ad92
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/epi_composable.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/epi_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/epi_ops.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a1c40393e56195efad6f3130fe7c88da9e08dded
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/epi_ops.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/epi_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/epi_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..377c8e1749fb4a9ed042ef2ee87eae380c8b4346
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/epi_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/fast_math.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/fast_math.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b721d17a08fd132fc5dfa12a2c70cec07563215
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/fast_math.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_act.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_act.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e98329a4569d4c053980c6218c6a4b43f5a0596d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_act.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_base.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7993a9e1e14beed26113a6c87301cfff045565f2
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_base.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_blockscaled_interface.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_blockscaled_interface.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..245e8963f1070e1a36fa222d6a4d98e33110b8ab
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_blockscaled_interface.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_config.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7fe99328c0ab83b8e310def0dbff7453b628b9f8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_config.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_default_epi.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_default_epi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f3b761608d5f4666411c1510b86e6afe2afd23c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_default_epi.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm100.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm100.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..58e355991d8fc2a8dafb03f22e15d1d5eff9dc55
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm100.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:be47af0ce878fcb8ac7439ff22465b5348160cdb39f823be16c0913a4fc1ce54
+size 112384
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm120.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm120.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e7d441c97d6b359a55830dc3592a1bec4f9339b7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm120.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm80.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm80.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc2ba7964c3c31e7bcf7c458b64033029bb9023c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm80.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm90.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm90.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..86ee7cb58750245871045b8cf58dd5c78610367e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm90.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_tvm_ffi_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_tvm_ffi_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..83a1b8a8694945c02a69f5c09efbbb2a4b61d5ff
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_tvm_ffi_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/layout_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/layout_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..391de683da256a0c0a68fc4d853859dbff9373e1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/layout_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/mx_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/mx_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6b10ede9e068e3f88f999d6e1e67219dd771e87d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/mx_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/pipeline.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/pipeline.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..77367e8d5a79293ad3784cfc6390c31a124df5f4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/pipeline.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/reduce.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/reduce.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d7f8780aaff7907da476ce20f6500df1b8d45806
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/reduce.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/reduction_base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/reduction_base.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91b123ba5f2728b4df7863a5a475eb78978e73de
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/reduction_base.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/rmsnorm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/rmsnorm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b374b04e8bdc4e6cab58c1edb13989624bc89900
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/rmsnorm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/rmsnorm_config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/rmsnorm_config.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d4709b9d987521c62e85bbca8faab065b5fdfa7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/rmsnorm_config.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/rounding.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/rounding.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d75188481f1ec79f7db4baa062489a945522262
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/rounding.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/sm100_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/sm100_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40f1dcd908b4eae40060e8fa71f593fb0de896b7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/sm100_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/sm80_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/sm80_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0d68f86ab69a8c7c4fa769c389223bfc90a16d1c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/sm80_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/sm90_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/sm90_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17d2286e35e214b78c7703e65c8ca351eb741bec
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/sm90_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/tile_scheduler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/tile_scheduler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53bddd52db38d3ba931cd4fddea3acb67dd25464
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/tile_scheduler.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/trace.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/trace.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..09cfcdffd2fc082ef6f1511252dec35d2935ee42
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/trace.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7fbc16ae96da73e594e36b0617b47d86430b905a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/varlen_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/varlen_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c803bd5aaf6cc97da98568c2adb85712588e7e9
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/varlen_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/_compile_worker.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/_compile_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..59932d3c238812064b52fa00a952a475c51b764e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/_compile_worker.py
@@ -0,0 +1,189 @@
+# Copyright (c) 2025, Tri Dao.
+# Persistent subprocess worker for parallel autotuning pre-compilation.
+# Receives length-prefixed pickled tasks on stdin, creates FakeTensors
+# matching the parent's tensor metadata, and compiles with COMPILE_ONLY=True.
+# Stays alive to process multiple configs (amortizes import overhead).
+
+import importlib
+import os
+import pickle
+import signal
+import struct
+import sys
+import threading
+import time
+
+import torch
+
+from . import cache
+from .cache import CompileOnlyFakeTensorMode
+
+
+# Watchdog poll interval. 60 s matches PyTorch Inductor's
+# ``_async_compile_initializer``; short enough that orphan workers don't
+# linger long, but long enough that the syscall cost is negligible.
+_WATCHDOG_POLL_SECS = 60.0
+
+
+def _install_parent_watchdog() -> None:
+    """Self-terminate if the spawning parent process dies.
+
+    Without this, a worker whose parent died (segfault, OOM-kill, the
+    cute.compile MLIR retention leak that ``conftest.pytest_handlecrashitem``
+    works around) gets reparented to init (PID 1) and lingers — consuming
+    CPU/memory until something else reaps it. Long-lived self-hosted CI
+    runners accumulate orphans across runs.
+
+    The parent's PID is passed via the ``QUACK_COMPILE_WORKER_PARENT_PID``
+    env var set by ``quack.autotuner._precompile`` before ``subprocess.Popen``.
+    A daemon thread polls ``os.getppid()`` every ``_WATCHDOG_POLL_SECS`` and
+    ``os.kill(self, SIGKILL)`` if the observed ppid no longer matches.
+
+    Also installs ``SIGINT → SIG_IGN`` so Ctrl-C in the parent doesn't spam
+    worker logs (the parent's pipe-close handles the orderly shutdown path).
+    """
+    raw = os.environ.get("QUACK_COMPILE_WORKER_PARENT_PID")
+    if raw is None:
+        # No env var — worker was launched outside of _precompile (e.g. by
+        # an external driver script). Skip silently; orphan risk is on the
+        # external caller.
+        return
+    try:
+        orig_ppid = int(raw)
+    except ValueError:
+        return
+
+    # Ignore SIGINT regardless of whether the watchdog poll is meaningful;
+    # this keeps worker logs clean on Ctrl-C in the parent shell.
+    signal.signal(signal.SIGINT, signal.SIG_IGN)
+
+    def _poll():
+        while True:
+            time.sleep(_WATCHDOG_POLL_SECS)
+            # ``os.getppid()`` returns 1 (init) once the original parent
+            # exits. Comparing against the recorded ``orig_ppid`` catches
+            # both the reparented-to-init case and the unusual case where
+            # ppid changes to some other PID.
+            if os.getppid() != orig_ppid:
+                os.kill(os.getpid(), signal.SIGKILL)
+
+    t = threading.Thread(target=_poll, name="quack-compile-worker-watchdog", daemon=True)
+    t.start()
+
+
+# This subprocess lives in compile-only mode for its entire lifetime; push
+# the depth counter once at module load and let process exit pop it. We
+# deliberately reach into the underscore-prefixed ``_COMPILE_ONLY_DEPTH``
+# ContextVar instead of using ``compile_only_mode()`` because:
+#
+#   1. ``compile_only_mode()`` is a context manager that also enters a
+#      ``CompileOnlyFakeTensorMode``. The worker enters its own per-task
+#      ``CompileOnlyFakeTensorMode`` (see ``main()`` below) and doesn't want
+#      a long-lived outer one shadowing it.
+#   2. The depth is permanent for this process; there is nothing to ``.reset()``
+#      — the process terminates instead.
+#
+# This is an intentional internal exception to the rule documented in
+# ``quack/cache/__init__.py`` ("only :func:`compile_only_mode` mutates the
+# depth"). External callers should still use ``compile_only_mode()``.
+cache._COMPILE_ONLY_DEPTH.set(cache._COMPILE_ONLY_DEPTH.get() + 1)
+
+_TENSOR_META_TAG = "__quack_tensor_meta__"
+
+
+_dtype_map = {
+    "torch.float16": torch.float16,
+    "torch.bfloat16": torch.bfloat16,
+    "torch.float32": torch.float32,
+    "torch.float64": torch.float64,
+    "torch.int32": torch.int32,
+    "torch.int64": torch.int64,
+    "torch.int8": torch.int8,
+    "torch.uint8": torch.uint8,
+    "torch.bool": torch.bool,
+}
+
+
+def _make_fake_tensor(meta):
+    shape = meta["shape"]
+    stride = meta["stride"]
+    dtype = _dtype_map[meta["dtype"]]
+    return torch.empty_strided(shape, stride, dtype=dtype, device="cuda")
+
+
+def _deserialize_precompile_value(value):
+    if isinstance(value, dict):
+        if value.get(_TENSOR_META_TAG):
+            return _make_fake_tensor(value)
+        return {k: _deserialize_precompile_value(v) for k, v in value.items()}
+    if isinstance(value, tuple):
+        return tuple(_deserialize_precompile_value(v) for v in value)
+    if isinstance(value, list):
+        return [_deserialize_precompile_value(v) for v in value]
+    return value
+
+
+def _recv(stream):
+    """Read a length-prefixed pickled message. Returns None on EOF."""
+    header = stream.read(4)
+    if len(header) < 4:
+        return None
+    length = struct.unpack(" Float32:
+    return Float32(
+        llvm.inline_asm(
+            T.f32(),
+            [Float32(a).ir_value(loc=loc, ip=ip)],
+            "tanh.approx.f32 $0, $1;",
+            "=f,f",
+            has_side_effects=False,
+            is_align_stack=False,
+        )
+    )
+
+
+@dsl_user_op
+def sigmoid_tanh(x: F32_or_F32x2, *, loc=None, ip=None) -> F32_or_F32x2:
+    if const_expr(not isinstance(x, tuple)):
+        # return 0.5 + 0.5 * cute.math.tanh(0.5 * x, fastmath=True)
+        return 0.5 + 0.5 * tanh(0.5 * x)
+    else:
+        x_half = cute.arch.mul_packed_f32x2((0.5, 0.5), x)
+        tanh_x_half = (tanh(x_half[0]), tanh(x_half[1]))
+        return cute.arch.fma_packed_f32x2(tanh_x_half, (0.5, 0.5), (0.5, 0.5))
+
+
+@dsl_user_op
+def sigmoid(x: F32_or_F32x2, *, loc=None, ip=None) -> F32_or_F32x2:
+    if const_expr(not isinstance(x, tuple)):
+        return cute.arch.rcp_approx(1.0 + cute.math.exp(-x, fastmath=True), loc=loc, ip=ip)
+    else:
+        log2_e = math.log2(math.e)
+        neg_x = cute.arch.mul_packed_f32x2(x, (-log2_e, -log2_e))
+        exp_neg_x = (
+            cute.math.exp2(neg_x[0], fastmath=True),
+            cute.math.exp2(neg_x[1], fastmath=True),
+        )
+        denom = cute.arch.add_packed_f32x2(exp_neg_x, (1.0, 1.0))
+        return cute.arch.rcp_approx(denom[0]), cute.arch.rcp_approx(denom[1])
+
+
+@dsl_user_op
+def dsigmoid_from_output(out: Float32, dout: Float32, *, loc=None, ip=None) -> Float32:
+    # return dout * out * (1.0 - out)
+    return dout * (out - out * out)
+
+
+@dsl_user_op
+def relu(x: F32_or_F32x2, *, loc=None, ip=None) -> F32_or_F32x2:
+    if const_expr(not isinstance(x, tuple)):
+        return cute.arch.fmax(x, Float32(0.0))
+    else:
+        return cute.arch.fmax(x[0], Float32(0.0)), cute.arch.fmax(x[1], Float32(0.0))
+
+
+@dsl_user_op
+@cute.jit
+def drelu(
+    x: F32_or_F32x2, dout: F32_or_F32x2, *, loc=None, ip=None
+) -> Tuple[F32_or_F32x2, F32_or_F32x2]:
+    if const_expr(not isinstance(x, tuple)):
+        x_pos = Boolean(x > 0)
+        return dout if x_pos else Float32(0.0), cute.arch.fmax(x, Float32(0.0))
+    else:
+        x0_pos = Boolean(x[0] > 0)
+        x1_pos = Boolean(x[1] > 0)
+        dx = (dout[0] if x0_pos else Float32(0.0), dout[1] if x1_pos else Float32(0.0))
+        return dx, relu(x)
+
+
+@dsl_user_op
+def relu_sq(x: F32_or_F32x2, *, loc=None, ip=None) -> F32_or_F32x2:
+    if const_expr(not isinstance(x, tuple)):
+        return cute.arch.fmax(x, Float32(0.0)) * x
+    else:
+        relu_x = (cute.arch.fmax(x[0], Float32(0.0)), cute.arch.fmax(x[1], Float32(0.0)))
+        return cute.arch.mul_packed_f32x2(relu_x, x)
+
+
+@dsl_user_op
+@cute.jit
+def drelu_sq(
+    x: F32_or_F32x2, dout: F32_or_F32x2, *, loc=None, ip=None
+) -> Tuple[F32_or_F32x2, F32_or_F32x2]:
+    """
+    ReLU squared backward pass: computes gradient w.r.t. x and recomputes forward
+    Given: relu_sq_out = max(x, 0) * x, and dout = grad w.r.t. relu_sq_out
+    Returns: (dx, relu_sq_out) where:
+    - dx = dout * 2 * x if x > 0, else 0
+    - relu_sq_out = max(x, 0) * x
+    """
+    if const_expr(not isinstance(x, tuple)):
+        relu_x = relu(x)
+        relu_sq_out = relu_x * x
+        # Derivative: d/dx[max(x,0) * x] = 2*x if x > 0, else 0
+        dx = 2.0 * (dout * relu_x)
+        return dx, relu_sq_out
+    else:
+        relu_x = relu(x)
+        relu_sq_out = cute.arch.mul_packed_f32x2(relu_x, x)
+        dx = cute.arch.mul_packed_f32x2((2.0, 2.0), cute.arch.mul_packed_f32x2(dout, relu_x))
+        return dx, relu_sq_out
+
+
+@dsl_user_op
+def gelu_tanh_approx(x: F32_or_F32x2, *, loc=None, ip=None) -> F32_or_F32x2:
+    """
+    gelu(x) = 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))
+            = 0.5 * x * (1 + tanh(x * (0.797885 + 0.0356774 * x * x)))
+    """
+    sqrt_2_over_pi = math.sqrt(2 / math.pi)  # ~0.797885
+    sqrt_2_over_pi_coeff = 0.044715 * sqrt_2_over_pi  # ~0.0356774
+    if const_expr(not isinstance(x, tuple)):
+        return 0.5 * (
+            x
+            # Currently cute.math.tanh(x, fastmath=True) generates very slow code
+            # * (1 + cute.math.tanh(x * (sqrt_2_over_pi + sqrt_2_over_pi_coeff * (x * x)), fastmath=True))
+            * (1.0 + tanh(x * (sqrt_2_over_pi + sqrt_2_over_pi_coeff * (x * x))))
+        )
+    else:
+        x_sq = cute.arch.mul_packed_f32x2(x, x)
+        x_sq_scaled = cute.arch.fma_packed_f32x2(
+            x_sq, (sqrt_2_over_pi_coeff, sqrt_2_over_pi_coeff), (sqrt_2_over_pi, sqrt_2_over_pi)
+        )
+        z = cute.arch.mul_packed_f32x2(x, x_sq_scaled)
+        tanh_z = (tanh(z[0]), tanh(z[1]))
+        x_tanh_z = cute.arch.fma_packed_f32x2(tanh_z, x, x)
+        return cute.arch.mul_packed_f32x2((0.5, 0.5), x_tanh_z)
+
+
+@dsl_user_op
+def dgelu_tanh_approx(
+    x: F32_or_F32x2, dout: F32_or_F32x2, *, loc=None, ip=None
+) -> Tuple[F32_or_F32x2, F32_or_F32x2]:
+    """
+    GELU tanh approximation backward pass: computes gradient w.r.t. x and recomputes forward
+    Given: gelu_out = 0.5 * x * (1 + tanh(x * (c1 + c2 * x^2))), and dout = grad w.r.t. gelu_out
+    Returns: (dx, gelu_out)
+
+    Derivative uses the chain rule:
+    d/dx[gelu(x)] = 0.5 * (1 + tanh(z)) + 0.5 * x * sech^2(z) * dz/dx
+    where z = x * (c1 + c2 * x^2), dz/dx = c1 + 3 * c2 * x^2
+    and sech^2(z) = 1 - tanh^2(z)
+    """
+    sqrt_2_over_pi = math.sqrt(2 / math.pi)  # c1 ~0.797885
+    sqrt_2_over_pi_coeff = 0.044715 * sqrt_2_over_pi  # c2 ~0.0356774
+    sqrt_2_over_pi_coeff_3 = 3.0 * sqrt_2_over_pi_coeff  # c3 ~0.01070322
+
+    if const_expr(not isinstance(x, tuple)):
+        # Compute z = x * (c1 + c2 * x^2)
+        x_sq = x * x
+        # tanh_z = cute.math.tanh(x * (sqrt_2_over_pi + sqrt_2_over_pi_coeff * x_sq), fastmath=True)
+        tanh_z = tanh(x * (sqrt_2_over_pi + sqrt_2_over_pi_coeff * x_sq))
+        half_tanh_z_plus_one = 0.5 + 0.5 * tanh_z
+        gelu_out = x * half_tanh_z_plus_one
+
+        # Compute gradient
+        # sech^2(z) = 1 - tanh^2(z)
+        sech2_z = 1 - tanh_z * tanh_z
+        # dz/dx = c1 + 3 * c2 * x^2
+        dz_dx = sqrt_2_over_pi + sqrt_2_over_pi_coeff_3 * x_sq
+        # d/dx[gelu(x)] = 0.5 * (1 + tanh(z)) + 0.5 * x * sech^2(z) * dz/dx
+        dgelu = half_tanh_z_plus_one + x * (0.5 * (sech2_z * dz_dx))
+
+        dx = dout * dgelu
+        return dx, gelu_out
+    else:
+        # Compute z = x * (c1 + c2 * x^2)
+        x_sq = cute.arch.mul_packed_f32x2(x, x)
+        x_sq_scaled = cute.arch.fma_packed_f32x2(
+            x_sq, (sqrt_2_over_pi_coeff, sqrt_2_over_pi_coeff), (sqrt_2_over_pi, sqrt_2_over_pi)
+        )
+        z = cute.arch.mul_packed_f32x2(x, x_sq_scaled)
+        tanh_z = (tanh(z[0]), tanh(z[1]))
+        half_tanh_z_plus_one = cute.arch.fma_packed_f32x2(tanh_z, (0.5, 0.5), (0.5, 0.5))
+        gelu_out = cute.arch.mul_packed_f32x2(x, half_tanh_z_plus_one)
+
+        # Compute gradient
+        # sech^2(z) = 1 - tanh^2(z)
+        sech2_z = cute.arch.fma_packed_f32x2(tanh_z, (-tanh_z[0], -tanh_z[1]), (1.0, 1.0))
+        # dz/dx = c1 + 3 * c2 * x^2
+        dz_dx = cute.arch.fma_packed_f32x2(
+            x_sq, (sqrt_2_over_pi_coeff_3, sqrt_2_over_pi_coeff_3), (sqrt_2_over_pi, sqrt_2_over_pi)
+        )
+        # d/dx[gelu(x)] = 0.5 * (1 + tanh(z)) + 0.5 * x * sech^2(z) * dz/dx
+        sech2_dz_dx = cute.arch.mul_packed_f32x2(sech2_z, dz_dx)
+        x_sech2_dz_dx = cute.arch.mul_packed_f32x2(x, sech2_dz_dx)
+        dgelu = cute.arch.fma_packed_f32x2(x_sech2_dz_dx, (0.5, 0.5), half_tanh_z_plus_one)
+
+        dx = cute.arch.mul_packed_f32x2(dout, dgelu)
+        return dx, gelu_out
+
+
+@dsl_user_op
+@cute.jit
+def softplus(x: F32_or_F32x2, *, loc=None, ip=None) -> F32_or_F32x2:
+    if const_expr(not isinstance(x, tuple)):
+        use_linear = Boolean(x > 20.0)
+        return (
+            cute.math.log(Float32(cute.math.exp(x, fastmath=True)) + 1.0, fastmath=True)
+            if not use_linear
+            else x
+        )
+    else:
+        log2_e = math.log2(math.e)
+        x_log2e = cute.arch.mul_packed_f32x2(x, (log2_e, log2_e))
+        x_exp = (cute.math.exp(x_log2e[0], fastmath=True), cute.math.exp(x_log2e[1], fastmath=True))
+        x_exp_p1 = cute.arch.add_packed_f32x2(x_exp, (1.0, 1.0))
+        log_x_exp_p1 = (
+            cute.math.log2(x_exp_p1[0], fastmath=True),
+            cute.math.log2(x_exp_p1[1], fastmath=True),
+        )
+        ln2 = math.log(2.0)
+        softplus_x = cute.arch.mul_packed_f32x2(log_x_exp_p1, (ln2, ln2))
+        use_linear_0 = Boolean(x[0] > 20.0)
+        use_linear_1 = Boolean(x[1] > 20.0)
+        return (
+            softplus_x[0] if not use_linear_0 else x[0],
+            softplus_x[1] if not use_linear_1 else x[1],
+        )
+
+
+@dsl_user_op
+@cute.jit
+def dsoftplus_from_output(out: Float32, dout: Float32, *, loc=None, ip=None) -> Float32:
+    use_linear = Boolean(out > 20.0)
+    # dx = dout * (1.0 - cute.math.exp(-out, fastmath=True)) if not use_linear else dout
+    dx = dout - dout * cute.math.exp(-out, fastmath=True)
+    return dx if not use_linear else dout
+
+
+@dsl_user_op
+def silu(x: F32_or_F32x2, *, loc=None, ip=None) -> F32_or_F32x2:
+    """
+    silu(x) = x * sigmoid(x) = x * rcp(1 + exp(-x)).
+    """
+    if const_expr(not isinstance(x, tuple)):
+        return x * sigmoid(x)
+    else:
+        return cute.arch.mul_packed_f32x2(x, sigmoid(x))
+
+
+@dsl_user_op
+def silu_tanh(x: F32_or_F32x2, *, already_halved: bool = False, loc=None, ip=None) -> F32_or_F32x2:
+    """
+    silu(x) = x * sigmoid(x) = x * (1 + tanh(x / 2)) / 2 = (0.5 * x) * tanh(0.5 * x) + (0.5 * x)
+    This compiles down to 3 SASS instructions: FMUL to get 0.5 * x, MUFU.TANH, and FFMA.
+    """
+    if const_expr(not isinstance(x, tuple)):
+        x_half = 0.5 * x if const_expr(not already_halved) else x
+        # return x_half * cute.math.tanh(x_half, fastmath=True) + x_half
+        return x_half * tanh(x_half) + x_half
+    else:
+        x_half = cute.arch.mul_packed_f32x2((0.5, 0.5), x) if const_expr(not already_halved) else x
+        tanh_x_half = (tanh(x_half[0]), tanh(x_half[1]))
+        return cute.arch.fma_packed_f32x2(x_half, tanh_x_half, x_half)
+
+
+@dsl_user_op
+def dsilu(
+    x: F32_or_F32x2,
+    dout: F32_or_F32x2,
+    *,
+    loc=None,
+    ip=None,
+) -> Tuple[F32_or_F32x2, F32_or_F32x2]:
+    """
+    SiLU backward pass: computes d_silu(x) * dout and recomputes silu(x).
+
+    d_silu(x) = sigmoid(x) * (1 + x * (1 - sigmoid(x))).
+    """
+    if const_expr(not isinstance(x, tuple)):
+        sigmoid_x = sigmoid(x)
+        silu_x = x * sigmoid_x
+        d_silu_x_dout = (sigmoid_x - silu_x * sigmoid_x + silu_x) * dout
+        return d_silu_x_dout, silu_x
+    else:
+        sigmoid_x = sigmoid(x)
+        silu_x = cute.arch.mul_packed_f32x2(x, sigmoid_x)
+        sigmoid_x_minus_silu_x_sigmoid_x = cute.arch.fma_packed_f32x2(
+            sigmoid_x, (-silu_x[0], -silu_x[1]), sigmoid_x
+        )
+        sigmoid_x_minus_silu_x_sigmoid_x_plus_silu_x = cute.arch.add_packed_f32x2(
+            sigmoid_x_minus_silu_x_sigmoid_x, silu_x
+        )
+        d_silu_x_dout = cute.arch.mul_packed_f32x2(
+            sigmoid_x_minus_silu_x_sigmoid_x_plus_silu_x, dout
+        )
+        return d_silu_x_dout, silu_x
+
+
+@dsl_user_op
+def dsilu_tanh(
+    x: F32_or_F32x2,
+    dout: F32_or_F32x2,
+    *,
+    already_halved: bool = False,
+    loc=None,
+    ip=None,
+) -> Tuple[F32_or_F32x2, F32_or_F32x2]:
+    """
+    SiLU backward using sigmoid(x) = 0.5 * (1 + tanh(0.5 * x)).
+    """
+    if const_expr(not isinstance(x, tuple)):
+        if const_expr(not already_halved):
+            x_half = 0.5 * x
+            tanh_x_half = tanh(x_half)
+            sigmoid_x = 0.5 * tanh_x_half + 0.5
+            silu_x = x_half * tanh_x_half + x_half
+        else:
+            tanh_x = tanh(x)
+            sigmoid_x = 0.5 * tanh_x + 0.5
+            silu_x = x * tanh_x + x
+        d_silu_x_dout = (sigmoid_x - silu_x * sigmoid_x + silu_x) * dout
+        return d_silu_x_dout, silu_x
+    else:
+        if const_expr(not already_halved):
+            x_half = cute.arch.mul_packed_f32x2((0.5, 0.5), x)
+            tanh_x_half = (tanh(x_half[0]), tanh(x_half[1]))
+            sigmoid_x = cute.arch.fma_packed_f32x2(tanh_x_half, (0.5, 0.5), (0.5, 0.5))
+            silu_x = cute.arch.fma_packed_f32x2(x_half, tanh_x_half, x_half)
+        else:
+            tanh_x = (tanh(x[0]), tanh(x[1]))
+            sigmoid_x = cute.arch.fma_packed_f32x2(tanh_x, (0.5, 0.5), (0.5, 0.5))
+            silu_x = cute.arch.fma_packed_f32x2(x, tanh_x, x)
+        sigmoid_x_minus_silu_x_sigmoid_x = cute.arch.fma_packed_f32x2(
+            sigmoid_x, (-silu_x[0], -silu_x[1]), sigmoid_x
+        )
+        sigmoid_x_minus_silu_x_sigmoid_x_plus_silu_x = cute.arch.add_packed_f32x2(
+            sigmoid_x_minus_silu_x_sigmoid_x, silu_x
+        )
+        d_silu_x_dout = cute.arch.mul_packed_f32x2(
+            sigmoid_x_minus_silu_x_sigmoid_x_plus_silu_x, dout
+        )
+        return d_silu_x_dout, silu_x
+
+
+@dsl_user_op
+def swiglu(x: F32_or_F32x2, y: F32_or_F32x2, *, loc=None, ip=None) -> F32_or_F32x2:
+    if const_expr(not isinstance(x, tuple)):
+        return silu(x) * y
+    else:
+        return cute.arch.mul_packed_f32x2(silu(x), y)
+
+
+@dsl_user_op
+def swiglu_tanh(x: F32_or_F32x2, y: F32_or_F32x2, *, loc=None, ip=None) -> F32_or_F32x2:
+    if const_expr(not isinstance(x, tuple)):
+        return silu_tanh(x) * y
+    else:
+        return cute.arch.mul_packed_f32x2(silu_tanh(x), y)
+
+
+@dsl_user_op
+def dswiglu(
+    x: F32_or_F32x2,
+    y: F32_or_F32x2,
+    dout: F32_or_F32x2,
+    *,
+    loc=None,
+    ip=None,
+) -> Tuple[F32_or_F32x2, F32_or_F32x2, F32_or_F32x2]:
+    """
+    SwiGLU backward pass: computes gradients w.r.t. x (gate) and y (up projection)
+    Given: swiglu_out = silu(x) * y, and dout = grad w.r.t. swiglu_out
+    Returns: (dx, dy, swiglu_out) where dx = dout * y * d_silu(x), dy = dout * silu(x)
+
+    d_silu(x) = sigmoid(x) * (1 + x * (1 - sigmoid(x)))
+
+    This has been optimized to use fewer instructions (i.e. we expand things out
+    to use FFMA instead of FADD and FMUL).
+    """
+    if const_expr(not isinstance(x, tuple)):
+        sigmoid_x = sigmoid(x)
+        silu_x = x * sigmoid_x  # FMUL
+        silu_x_dout = silu_x * dout  # FMUL
+        #   d_silu(x) * dout
+        # = sigmoid_x * (1 + x * (1 - sigmoid_x)) * dout
+        # = (sigmoid_x + sigmoid_x * x * (1 - sigmoid_x)) * dout
+        # = (sigmoid_x + silu_x * (1 - sigmoid_x)) * dout
+        # = (sigmoid_x + silu_x - silu_x * sigmoid_x) * dout
+        # = (sigmoid_x - silu_x * sigmoid_x) * dout + silu_x * dout
+        d_silu_x_dout = (sigmoid_x - silu_x * sigmoid_x) * dout + silu_x_dout  # FFMA, FFMA
+        dx = d_silu_x_dout * y  # FMUL
+        dy = silu_x_dout
+        swiglu_out = silu_x * y  # FMUL
+        return dx, dy, swiglu_out
+    else:
+        # Compute sigmoid(x) and silu(x)
+        sigmoid_x = sigmoid(x)
+        silu_x = cute.arch.mul_packed_f32x2(x, sigmoid_x)
+        silu_x_dout = cute.arch.mul_packed_f32x2(silu_x, dout)
+        # d_silu(x) * dout = (sigmoid_x - silu_x * sigmoid_x) * dout + silu_x * dout
+        sigmoid_x_minus_silu_x_sigmoid_x = cute.arch.fma_packed_f32x2(
+            sigmoid_x, (-silu_x[0], -silu_x[1]), sigmoid_x
+        )
+        d_silu_x_dout = cute.arch.fma_packed_f32x2(
+            sigmoid_x_minus_silu_x_sigmoid_x, dout, silu_x_dout
+        )
+        dx = cute.arch.mul_packed_f32x2(d_silu_x_dout, y)
+        dy = silu_x_dout
+        swiglu_out = cute.arch.mul_packed_f32x2(silu_x, y)
+        return dx, dy, swiglu_out
+
+
+@dsl_user_op
+def dswiglu_tanh(
+    x: F32_or_F32x2,
+    y: F32_or_F32x2,
+    dout: F32_or_F32x2,
+    *,
+    already_halved: bool = False,
+    loc=None,
+    ip=None,
+) -> Tuple[F32_or_F32x2, F32_or_F32x2, F32_or_F32x2]:
+    """
+    SwiGLU backward using sigmoid(x) = 0.5 * (1 + tanh(0.5 * x)).
+    """
+    if const_expr(not isinstance(x, tuple)):
+        if const_expr(not already_halved):
+            sigmoid_x = sigmoid_tanh(x)
+            silu_x = x * sigmoid_x  # FMUL
+        else:
+            tanh_x = tanh(x)
+            sigmoid_x = 0.5 * tanh_x + 0.5
+            silu_x = x * tanh_x + x
+        silu_x_dout = silu_x * dout
+        d_silu_x_dout = (sigmoid_x - silu_x * sigmoid_x) * dout + silu_x_dout
+        dx = d_silu_x_dout * y
+        dy = silu_x_dout
+        swiglu_out = silu_x * y
+        # Overall it's 1 MUFU.TANH, 5 FMUL, 3 FFMA
+        return dx, dy, swiglu_out
+    else:
+        if const_expr(not already_halved):
+            sigmoid_x = sigmoid_tanh(x)
+            silu_x = cute.arch.mul_packed_f32x2(x, sigmoid_x)
+        else:
+            tanh_x = (tanh(x[0]), tanh(x[1]))
+            sigmoid_x = cute.arch.fma_packed_f32x2(tanh_x, (0.5, 0.5), (0.5, 0.5))
+            silu_x = cute.arch.fma_packed_f32x2(x, tanh_x, x)
+        silu_x_dout = cute.arch.mul_packed_f32x2(silu_x, dout)
+        # d_silu(x) * dout = (sigmoid_x - silu_x * sigmoid_x) * dout + silu_x * dout
+        sigmoid_x_minus_silu_x_sigmoid_x = cute.arch.fma_packed_f32x2(
+            sigmoid_x, (-silu_x[0], -silu_x[1]), sigmoid_x
+        )
+        d_silu_x_dout = cute.arch.fma_packed_f32x2(
+            sigmoid_x_minus_silu_x_sigmoid_x, dout, silu_x_dout
+        )
+        dx = cute.arch.mul_packed_f32x2(d_silu_x_dout, y)
+        dy = silu_x_dout
+        swiglu_out = cute.arch.mul_packed_f32x2(silu_x, y)
+        return dx, dy, swiglu_out
+
+
+@dsl_user_op
+def swiglu_oai(
+    x: F32_or_F32x2, y: F32_or_F32x2, alpha: float = 1.702, *, loc=None, ip=None
+) -> F32_or_F32x2:
+    """The swiglu variant used in gpt-oss, which has a scaling factor on x and bias of 1 to y.
+    https://github.com/openai/gpt-oss/blob/7be9334950053a888e24887a57dac797a17d6e00/gpt_oss/torch/model.py#L249
+    x * sigmoid(alpha * x) * (y + 1)
+    """
+    if const_expr(not isinstance(x, tuple)):
+        sigmoid_alpha_x = sigmoid(alpha * x)
+        silu_x = x * sigmoid_alpha_x
+        return silu_x * y + silu_x
+    else:
+        alpha_x = cute.arch.mul_packed_f32x2((alpha, alpha), x)
+        sigmoid_alpha_x = sigmoid(alpha_x)
+        silu_x = cute.arch.mul_packed_f32x2(x, sigmoid_alpha_x)
+        return cute.arch.fma_packed_f32x2(silu_x, y, silu_x)
+
+
+@dsl_user_op
+def swiglu_oai_tanh(
+    x: F32_or_F32x2, y: F32_or_F32x2, alpha: float = 1.702, *, loc=None, ip=None
+) -> F32_or_F32x2:
+    """Tanh-based swiglu_oai kept for SASS/accuracy comparison."""
+    if const_expr(not isinstance(x, tuple)):
+        x_half = 0.5 * x
+        silu_x = x_half * tanh(alpha * x_half) + x_half
+        return silu_x * y + silu_x
+    else:
+        x_half = cute.arch.mul_packed_f32x2((0.5, 0.5), x)
+        alpha_x_half = cute.arch.mul_packed_f32x2((alpha, alpha), x_half)
+        tanh_alpha_x_half = (tanh(alpha_x_half[0]), tanh(alpha_x_half[1]))
+        silu_x = cute.arch.fma_packed_f32x2(x_half, tanh_alpha_x_half, x_half)
+        return cute.arch.fma_packed_f32x2(silu_x, y, silu_x)
+
+
+@dsl_user_op
+def dswiglu_oai(
+    x: F32_or_F32x2, y: F32_or_F32x2, dout: F32_or_F32x2, alpha: float = 1.702, *, loc=None, ip=None
+) -> Tuple[F32_or_F32x2, F32_or_F32x2, F32_or_F32x2]:
+    """
+    Swiglu OAI backward pass: computes gradients w.r.t. x and y
+    Given: swiglu_oai_out = x * sigmoid(alpha * x) * (y + 1), and dout = grad w.r.t. swiglu_oai_out
+    Returns: (dx, dy, swiglu_oai_out)
+
+    Derivative of x * sigmoid(alpha * x) w.r.t. x:
+    d/dx[x * sigmoid(alpha * x)] = sigmoid(alpha * x) + alpha * x * sigmoid(alpha * x) * (1 - sigmoid(alpha * x))
+    """
+    if const_expr(not isinstance(x, tuple)):
+        sigmoid_alpha_x = sigmoid(alpha * x)
+        silu_x = x * sigmoid_alpha_x
+        silu_x_dout = silu_x * dout
+        d_silu_x_dout = (sigmoid_alpha_x + alpha * (silu_x - silu_x * sigmoid_alpha_x)) * dout
+        dx = d_silu_x_dout * y + d_silu_x_dout
+        dy = silu_x_dout
+        swiglu_out = silu_x * y + silu_x
+        return dx, dy, swiglu_out
+    else:
+        alpha_x = cute.arch.mul_packed_f32x2((alpha, alpha), x)
+        sigmoid_alpha_x = sigmoid(alpha_x)
+        silu_x = cute.arch.mul_packed_f32x2(x, sigmoid_alpha_x)
+        silu_x_dout = cute.arch.mul_packed_f32x2(silu_x, dout)
+        silu_x_minus_product = cute.arch.fma_packed_f32x2(
+            silu_x, (-sigmoid_alpha_x[0], -sigmoid_alpha_x[1]), silu_x
+        )
+        sigmoid_plus_alpha_diff = cute.arch.fma_packed_f32x2(
+            (alpha, alpha), silu_x_minus_product, sigmoid_alpha_x
+        )
+        d_silu_x_dout = cute.arch.mul_packed_f32x2(sigmoid_plus_alpha_diff, dout)
+        dx = cute.arch.fma_packed_f32x2(d_silu_x_dout, y, d_silu_x_dout)
+        dy = silu_x_dout
+        swiglu_out = cute.arch.fma_packed_f32x2(silu_x, y, silu_x)
+        return dx, dy, swiglu_out
+
+
+@dsl_user_op
+def dswiglu_oai_tanh(
+    x: F32_or_F32x2, y: F32_or_F32x2, dout: F32_or_F32x2, alpha: float = 1.702, *, loc=None, ip=None
+) -> Tuple[F32_or_F32x2, F32_or_F32x2, F32_or_F32x2]:
+    """Tanh-based dswiglu_oai kept for SASS/accuracy comparison."""
+    if const_expr(not isinstance(x, tuple)):
+        alpha_x_half = (0.5 * alpha) * x
+        sigmoid_alpha_x = 0.5 + 0.5 * tanh(alpha_x_half)
+        silu_x = x * sigmoid_alpha_x
+        silu_x_dout = silu_x * dout
+        d_silu_x_dout = (sigmoid_alpha_x + alpha * (silu_x - silu_x * sigmoid_alpha_x)) * dout
+        dx = d_silu_x_dout * y + d_silu_x_dout
+        dy = silu_x_dout
+        swiglu_out = silu_x * y + silu_x
+        return dx, dy, swiglu_out
+    else:
+        alpha_x_half = cute.arch.mul_packed_f32x2(((0.5 * alpha), (0.5 * alpha)), x)
+        tanh_alpha_x_half = (tanh(alpha_x_half[0]), tanh(alpha_x_half[1]))
+        sigmoid_alpha_x = cute.arch.fma_packed_f32x2(tanh_alpha_x_half, (0.5, 0.5), (0.5, 0.5))
+        silu_x = cute.arch.mul_packed_f32x2(x, sigmoid_alpha_x)
+        silu_x_dout = cute.arch.mul_packed_f32x2(silu_x, dout)
+        silu_x_minus_product = cute.arch.fma_packed_f32x2(
+            silu_x, (-sigmoid_alpha_x[0], -sigmoid_alpha_x[1]), silu_x
+        )
+        sigmoid_plus_alpha_diff = cute.arch.fma_packed_f32x2(
+            (alpha, alpha), silu_x_minus_product, sigmoid_alpha_x
+        )
+        d_silu_x_dout = cute.arch.mul_packed_f32x2(sigmoid_plus_alpha_diff, dout)
+        dx = cute.arch.fma_packed_f32x2(d_silu_x_dout, y, d_silu_x_dout)
+        dy = silu_x_dout
+        swiglu_out = cute.arch.fma_packed_f32x2(silu_x, y, silu_x)
+        return dx, dy, swiglu_out
+
+
+@dsl_user_op
+def glu(x: F32_or_F32x2, y: F32_or_F32x2, *, loc=None, ip=None) -> F32_or_F32x2:
+    """GLU: Gated Linear Unit
+    glu(x, y) = sigmoid(x) * y
+    """
+    if const_expr(not isinstance(x, tuple)):
+        sigmoid_x = sigmoid(x)
+        return sigmoid_x * y  # FMUL
+    else:
+        sigmoid_x = sigmoid(x)
+        return cute.arch.mul_packed_f32x2(sigmoid_x, y)
+
+
+@dsl_user_op
+def dglu(
+    x: F32_or_F32x2, y: F32_or_F32x2, dout: F32_or_F32x2, *, loc=None, ip=None
+) -> Tuple[F32_or_F32x2, F32_or_F32x2, F32_or_F32x2]:
+    """
+    GLU backward pass: computes gradients w.r.t. x (gate) and y (up projection)
+    Given: glu_out = sigmoid(x) * y, and dout = grad w.r.t. glu_out
+    Returns: (dx, dy, glu_out) where:
+    - dx = dout * y * sigmoid(x) * (1 - sigmoid(x))
+    - dy = dout * sigmoid(x)
+    - glu_out = sigmoid(x) * y
+    """
+    if const_expr(not isinstance(x, tuple)):
+        sigmoid_x = sigmoid(x)
+        sigmoid_x_dout = sigmoid_x * dout  # FMUL
+        glu_out = sigmoid_x * y  # FMUL
+        # dx = y * sigmoid(x) * (1 - sigmoid(x)) * dout
+        #    = y * (1 - sigmoid(x)) * sigmoid_x_dout
+        #    = (y - y * sigmoid(x)) * sigmoid_x_dout
+        #    = (y - glu_out) * sigmoid_x_dout
+        dx = (y - glu_out) * sigmoid_x_dout  # FADD, FMUL
+        dy = sigmoid_x_dout
+        # Total: 1 MUFU.TANH, 4 FMUL, 1 FADD, 1 FFMA
+        return dx, dy, glu_out
+    else:
+        sigmoid_x = sigmoid(x)
+        sigmoid_x_dout = cute.arch.mul_packed_f32x2(sigmoid_x, dout)
+        glu_out = cute.arch.mul_packed_f32x2(sigmoid_x, y)
+        # dx = (y - glu_out) * sigmoid_x_dout
+        y_minus_glu_out = sub_packed_f32x2(y, glu_out)
+        dx = cute.arch.mul_packed_f32x2(y_minus_glu_out, sigmoid_x_dout)
+        dy = sigmoid_x_dout
+        return dx, dy, glu_out
+
+
+@dsl_user_op
+def reglu(x: F32_or_F32x2, y: F32_or_F32x2, *, loc=None, ip=None) -> F32_or_F32x2:
+    """ReGLU: ReLU Gated Linear Unit
+    reglu(x, y) = relu(x) * y = max(x, 0) * y
+    """
+    if const_expr(not isinstance(x, tuple)):
+        return cute.arch.fmax(x, Float32(0.0)) * y
+    else:
+        relu_x = relu(x)
+        return cute.arch.mul_packed_f32x2(relu_x, y)
+
+
+@dsl_user_op
+@cute.jit
+def dreglu(
+    x: F32_or_F32x2, y: F32_or_F32x2, dout: F32_or_F32x2, *, loc=None, ip=None
+) -> Tuple[F32_or_F32x2, F32_or_F32x2, F32_or_F32x2]:
+    """
+    ReGLU backward pass: computes gradients w.r.t. x (gate) and y (up projection)
+    Given: reglu_out = relu(x) * y, and dout = grad w.r.t. reglu_out
+    Returns: (dx, dy, reglu_out) where:
+    - dx = dout * y if x > 0, else 0
+    - dy = dout * relu(x)
+    - reglu_out = relu(x) * y
+    """
+    if const_expr(not isinstance(x, tuple)):
+        x_pos = Boolean(x > 0)
+        relu_x = cute.arch.fmax(x, Float32(0.0))
+        dx = (dout * y) if x_pos else Float32(0.0)
+        dy = dout * relu_x
+        reglu_out = relu_x * y
+        return dx, dy, reglu_out
+    else:
+        x0_pos = Boolean(x[0] > 0)
+        x1_pos = Boolean(x[1] > 0)
+        relu_x = relu(x)
+        dout_y = cute.arch.mul_packed_f32x2(dout, y)
+        dx = ((dout_y[0] if x0_pos else Float32(0.0)), (dout_y[1] if x1_pos else Float32(0.0)))
+        dy = cute.arch.mul_packed_f32x2(dout, relu_x)
+        reglu_out = cute.arch.mul_packed_f32x2(relu_x, y)
+        return dx, dy, reglu_out
+
+
+@dsl_user_op
+def geglu(x: F32_or_F32x2, y: F32_or_F32x2, *, loc=None, ip=None) -> F32_or_F32x2:
+    """GeGLU: GELU Gated Linear Unit
+    geglu(x, y) = gelu(x) * y
+    Uses the tanh approximation of GELU
+    """
+    if const_expr(not isinstance(x, tuple)):
+        return gelu_tanh_approx(x) * y
+    else:
+        return cute.arch.mul_packed_f32x2(gelu_tanh_approx(x), y)
+
+
+@dsl_user_op
+def dgeglu(
+    x: F32_or_F32x2, y: F32_or_F32x2, dout: F32_or_F32x2, *, loc=None, ip=None
+) -> Tuple[F32_or_F32x2, F32_or_F32x2, F32_or_F32x2]:
+    """
+    GeGLU backward pass: computes gradients w.r.t. x (gate) and y (up projection)
+    Given: geglu_out = gelu(x) * y, and dout = grad w.r.t. geglu_out
+    Returns: (dx, dy, geglu_out) where:
+    - dx = dout * y * d_gelu(x)
+    - dy = dout * gelu(x)
+    - geglu_out = gelu(x) * y
+    """
+    if const_expr(not isinstance(x, tuple)):
+        # Reuse dgelu_tanh_approx to compute d_gelu(x) * dout and gelu(x)
+        dgelu_x_dout, gelu_x = dgelu_tanh_approx(x, dout)
+        # Compute gradients for geglu
+        dx = dgelu_x_dout * y
+        dy = gelu_x * dout
+        geglu_out = gelu_x * y
+        return dx, dy, geglu_out
+    else:
+        # Reuse dgelu_tanh_approx to compute d_gelu(x) * dout and gelu(x)
+        dgelu_x_dout, gelu_x = dgelu_tanh_approx(x, dout)
+        # Compute gradients for geglu
+        dx = cute.arch.mul_packed_f32x2(dgelu_x_dout, y)
+        dy = cute.arch.mul_packed_f32x2(gelu_x, dout)
+        geglu_out = cute.arch.mul_packed_f32x2(gelu_x, y)
+        return dx, dy, geglu_out
+
+
+# ============================================================================
+# Activation name -> function maps
+# ============================================================================
+
+act_fn_map = {
+    None: None,
+    "silu": silu,
+    "silu-tanh": silu_tanh,
+    "relu": relu,
+    "relu_sq": relu_sq,
+    "gelu_tanh_approx": gelu_tanh_approx,
+}
+
+dact_fn_map = {
+    None: None,
+    "silu": dsilu,
+    "silu-tanh": dsilu_tanh,
+    "relu": drelu,
+    "relu_sq": drelu_sq,
+    "gelu_tanh_approx": dgelu_tanh_approx,
+}
+
+gate_fn_map = {
+    "swiglu": swiglu,
+    "swiglu-tanh": swiglu_tanh,
+    "swiglu_oai": swiglu_oai,
+    "swiglu_oai-tanh": swiglu_oai_tanh,
+    "reglu": reglu,
+    "geglu": geglu,
+    "glu": glu,
+}
+
+dgate_fn_map = {
+    "swiglu": dswiglu,
+    "swiglu-tanh": dswiglu_tanh,
+    "swiglu_oai": dswiglu_oai,
+    "swiglu_oai-tanh": dswiglu_oai_tanh,
+    "reglu": dreglu,
+    "geglu": dgeglu,
+    "glu": dglu,
+}
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/autotuner.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/autotuner.py
new file mode 100644
index 0000000000000000000000000000000000000000..2196e1499f77470c9fd402be3081c36f15a7ff2d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/autotuner.py
@@ -0,0 +1,868 @@
+# Adapted from https://github.com/triton-lang/triton/blob/main/python/triton/runtime/autotuner.py
+# Copyright (C) 2025, Tri Dao.
+from __future__ import annotations
+
+import builtins
+import os
+import subprocess
+import sys
+import threading
+import time
+import inspect
+import base64
+import hashlib
+import json
+from dataclasses import dataclass, field
+from pathlib import Path
+from functools import cached_property, partial
+from typing import Dict, Tuple, List, Optional, Any
+from .bench.bench_utils import (
+    _bench_cuda_graph_l2_rotate,
+    _clone_l2_rotate_inputs,
+    _pick_l2_rotate_count,
+)
+
+import torch
+from torch import Tensor
+
+import triton
+
+from . import __version__
+
+
+PACKAGE_NAME = "torch_vendor_quack"
+VERSION = __version__
+
+
+_TENSOR_META_TAG = "__quack_tensor_meta__"
+
+
+def _serialize_precompile_value(value: Any) -> Any:
+    if isinstance(value, Tensor):
+        return {
+            _TENSOR_META_TAG: True,
+            "shape": list(value.shape),
+            "stride": list(value.stride()),
+            "dtype": str(value.dtype),
+        }
+    if isinstance(value, tuple):
+        return tuple(_serialize_precompile_value(v) for v in value)
+    if isinstance(value, list):
+        return [_serialize_precompile_value(v) for v in value]
+    if isinstance(value, dict):
+        return {k: _serialize_precompile_value(v) for k, v in value.items()}
+    return value
+
+
+def _get_current_cuda_device() -> str | None:
+    """Return the physical CUDA device identifier for the current process.
+
+    Maps the logical ``torch.cuda.current_device()`` index through
+    ``CUDA_VISIBLE_DEVICES`` (if set) so the result is valid as a
+    standalone ``CUDA_VISIBLE_DEVICES`` value (handles integer IDs,
+    GPU UUIDs, and MIG IDs).
+
+    Returns ``None`` if CUDA is not initialized or the device cannot
+    be determined.
+    """
+    if not (torch.cuda.is_available() and torch.cuda.is_initialized()):
+        return None
+    logical_device = torch.cuda.current_device()
+    parent_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
+    if parent_visible is not None:
+        visible_devices = [d.strip() for d in parent_visible.split(",")]
+        if logical_device < len(visible_devices):
+            return visible_devices[logical_device]
+        return None
+    return str(logical_device)
+
+
+def get_home_dir():
+    return os.getenv(f"{PACKAGE_NAME.upper()}_HOME", Path.home())
+
+
+def default_cache_dir():
+    return os.path.join(get_home_dir(), f".{PACKAGE_NAME}", "cache")
+
+
+class FileCacheManager(triton.runtime.cache.FileCacheManager):
+    def __init__(self, key):
+        super().__init__(key)
+        self.cache_dir = (
+            os.getenv(f"{PACKAGE_NAME.upper()}_CACHE_DIR", "").strip() or default_cache_dir()
+        )
+        if self.cache_dir:
+            self.cache_dir = os.path.join(self.cache_dir, self.key)
+            self.lock_path = os.path.join(self.cache_dir, "lock")
+            os.makedirs(self.cache_dir, exist_ok=True)
+        else:
+            raise RuntimeError("Could not create or locate cache dir")
+
+
+def _base32(key):
+    # Assume key is a hex string.
+    return base64.b32encode(bytes.fromhex(key)).decode("utf-8").rstrip("=")
+
+
+def _gpu_warmup(duration_ms=200):
+    """Saturate the GPU to reach thermal steady-state before benchmarking.
+
+    Without this, the first autotuning config gets artificially good numbers
+    because the GPU hasn't been power-throttled yet.
+    """
+    a = torch.randn(4096, 4096, device="cuda", dtype=torch.bfloat16)
+    torch.cuda.synchronize()
+    target = duration_ms / 1000
+    t0 = time.time()
+    while time.time() - t0 < target:
+        for _ in range(100):
+            a = a @ a
+        torch.cuda.synchronize()
+
+
+# ---------------------------------------------------------------------------
+# Async precompile handle (gaps 2 + 3 from the autotune-pool hardening pass)
+#
+# The legacy ``_precompile`` was a blocking barrier: spawn N workers, dispatch
+# all configs round-robin, collect-all-results, then return. Two consequences:
+#
+#   * If a worker died mid-compile (e.g. a config that trips an internal
+#     cute.compile assert), the configs it had not yet acknowledged were
+#     silently dropped. The autotuner then ran the eager body for those
+#     configs without a warm .o, paying ~500 ms of compile inside the bench
+#     measurement; the artificially-slow timing made that config never get
+#     picked even when it was the actual best one.
+#   * Total wall = parallel_compile + serial_bench. With ~10 configs at
+#     ~500 ms compile and ~100 ms bench each, that's (5s/pool) + 1s. With
+#     async overlap it drops to max(5s/pool, 1s) — a ~40 % win on cold
+#     autotune.
+#
+# :class:`_PrecompileHandle` returns immediately after spawning workers and
+# dispatching their initial round of tasks. Per-config :class:`threading.Event`
+# completion signals let the bench loop wait on the specific config it's
+# about to benchmark. A background reader thread per worker drains stdout
+# replies and sets the corresponding events; on worker crash (None from
+# ``_recv`` = EOF) every still-pending task assigned to that worker is
+# marked failed (and the event set) so callers don't deadlock.
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class _PrecompileHandle:
+    """Per-config completion handle returned by :meth:`Autotuner._precompile`.
+
+    Empty / no-op when the subprocess pool was skipped (cache hit, disabled,
+    only 1 config). Calling ``wait_for(i)`` on a missing index returns
+    immediately as a no-op, so the bench loop can iterate uniformly.
+    """
+
+    events: Dict[int, threading.Event] = field(default_factory=dict)
+    failures: Dict[int, str] = field(default_factory=dict)
+    _workers: List[Any] = field(default_factory=list)  # subprocess.Popen
+    _reader_threads: List[threading.Thread] = field(default_factory=list)
+    _lock: threading.Lock = field(default_factory=threading.Lock)
+
+    def wait_for(self, config_idx: int, timeout: Optional[float] = None) -> None:
+        """Block until ``config_idx``'s compile completes (or failed).
+
+        No-op for indices that were never registered (e.g. the entire handle
+        is empty because precompile was skipped). The bench loop relies on
+        this to call ``wait_for`` unconditionally.
+        """
+        evt = self.events.get(config_idx)
+        if evt is not None:
+            evt.wait(timeout=timeout)
+
+    def is_failed(self, config_idx: int) -> bool:
+        """True if the subprocess pool failed to compile this config.
+
+        Use after :meth:`wait_for` returns. Failed configs need an in-process
+        jit_cache warm before benchmarking to avoid contaminating the timing
+        measurement with compile cost (see :meth:`Autotuner._bench_with_warm`).
+        """
+        with self._lock:
+            return config_idx in self.failures
+
+    def shutdown(self) -> None:
+        """Close stdins, wait for workers and reader threads to exit.
+
+        Idempotent. Safe to call even if ``__init__`` failed midway through
+        spawning workers.
+        """
+        for w in self._workers:
+            try:
+                if w.poll() is None and w.stdin is not None:
+                    w.stdin.close()
+            except (BrokenPipeError, OSError):
+                pass
+        for w in self._workers:
+            try:
+                w.wait(timeout=5.0)
+            except subprocess.TimeoutExpired:
+                w.kill()
+                try:
+                    w.wait(timeout=1.0)
+                except subprocess.TimeoutExpired:
+                    pass  # process really stuck; give up rather than hang the bench
+        for t in self._reader_threads:
+            t.join(timeout=1.0)
+
+
+def _reader_thread_main(handle, worker, config_indices):
+    """Drain replies from one worker's stdout and signal per-config events.
+
+    Replies arrive in dispatch order (length-prefixed pickled strings:
+    ``"OK"`` or ``"ERR:..."``). On EOF (= worker crashed), every config
+    this worker still had pending is marked failed and its event set so
+    waiters don't deadlock.
+
+    Runs in its own daemon thread so the bench loop can interleave waiting
+    with kernel launches.
+    """
+    for pos, config_idx in enumerate(config_indices):
+        try:
+            r = _recv_from_worker(worker.stdout)
+        except (BrokenPipeError, EOFError, ConnectionResetError):
+            r = None
+        with handle._lock:
+            if r is None:
+                # Worker died; mark this config + all remaining ones failed.
+                # ``setdefault`` so we don't clobber a real ERR: reply that
+                # somehow raced (unlikely, but cheap to be safe).
+                for remaining_idx in config_indices[pos:]:
+                    handle.failures.setdefault(remaining_idx, "worker crashed during compile")
+                    handle.events[remaining_idx].set()
+                return
+            if isinstance(r, str) and r.startswith("ERR:"):
+                handle.failures[config_idx] = r
+            handle.events[config_idx].set()
+
+
+def _recv_from_worker(stream):
+    """Read a length-prefixed pickled message. Returns None on EOF or partial body.
+
+    Mirrors ``_compile_worker._recv`` so the parent and worker speak the
+    same protocol. Kept private to this module rather than re-imported from
+    the worker because the worker module isn't safe to import in the parent
+    (it pushes ``_COMPILE_ONLY_DEPTH`` at module load).
+
+    Returns ``None`` on both:
+
+    * clean EOF (header shorter than 4 bytes — pipe write side closed before
+      writing the header);
+    * truncated body (header read OK, but the body read returns fewer bytes
+      than the declared length — the worker was SIGKILL'd by its parent-death
+      watchdog, or by OOM-killer, *between* writing the header and writing
+      the body).
+
+    Without the truncated-body check, ``pickle.loads`` raises ``UnpicklingError``
+    on a short body. That exception would propagate out of the reader thread,
+    leaving the per-config events unset and deadlocking every ``wait_for(i)``
+    waiter in :meth:`Autotuner.__call__`'s ``benchmark()`` closure.
+    """
+    import pickle
+    import struct
+
+    header = stream.read(4)
+    if len(header) < 4:
+        return None
+    length = struct.unpack(" 0:
+
+            def _pre_hook(kwargs):
+                self.restore_copies = {name: kwargs[name].clone() for name in self.restore_value}
+
+            self.pre_hook = _pre_hook
+        else:
+            self.pre_hook = None
+
+        if len(self.restore_value) > 0:
+
+            def _post_hook(kwargs, exception):
+                for name in self.restore_value:
+                    kwargs[name].copy_(self.restore_copies[name])
+                self.restore_copies = {}
+
+            self.post_hook = _post_hook
+        else:
+            self.post_hook = None
+
+        self.perf_model = None
+        self.configs_top_k = 1.0
+        self.early_config_prune = None
+        if prune_configs_by:
+            self.perf_model = prune_configs_by.get("perf_model", self.perf_model)
+            self.configs_top_k = prune_configs_by.get("top_k", self.configs_top_k)
+            self.early_config_prune = prune_configs_by.get(
+                "early_config_prune", self.early_config_prune
+            )
+
+        self.fn = fn
+        self._do_bench = do_bench
+
+    @cached_property
+    def do_bench(self):
+        if self._do_bench is None:
+            return partial(triton.testing.do_bench, warmup=5, rep=25)
+        return self._do_bench
+
+    def _precompile(self, *args, configs, **kwargs) -> _PrecompileHandle:
+        """Pre-compile all configs in parallel subprocesses to populate .o cache.
+
+        cute.compile() is not thread-safe (MLIR thread-local state) and fork after
+        CUDA init causes segfaults. So we spawn persistent subprocess workers: each
+        has its own CUDA context, creates FakeTensors matching the parent's tensor
+        metadata, and compiles with COMPILE_ONLY=True. Workers stay alive to amortize
+        import overhead across multiple configs. The parent then loads instantly from
+        the .o cache during benchmarking.
+
+        Returns a :class:`_PrecompileHandle` whose ``wait_for(i)`` blocks until
+        config ``i``'s compile completes; the bench loop interleaves
+        ``wait_for`` + benchmark to overlap the remaining compiles with GPU
+        work. Workers are equipped with a parent-death watchdog
+        (:func:`quack._compile_worker._install_parent_watchdog`) so an
+        orphaned worker self-terminates within ~60 s instead of lingering on
+        long-lived self-hosted CI runners.
+
+        The returned handle is also valid (empty but functional) when
+        precompilation is skipped — cache disabled, only 1 config, the
+        first-config warm-cache shortcut hit. Callers always call
+        ``wait_for`` + ``shutdown``; the no-op handle makes both fast.
+        """
+        from .cache import CACHE_ENABLED
+
+        if not self.precompile_configs or not CACHE_ENABLED:
+            return _PrecompileHandle()
+
+        max_workers = min(len(configs), int(os.getenv("QUACK_COMPILE_WORKERS", "8")))
+        if max_workers <= 1:
+            return _PrecompileHandle()
+
+        # Quick check: compile first config in-process. If it loads from .o cache
+        # (<0.5s), the rest are likely cached too — skip spawning workers.
+        t_check = time.time()
+        try:
+            current = dict(kwargs, **configs[0].all_kwargs())
+            self.fn(*args, **current)
+        except Exception:
+            pass
+        if time.time() - t_check < 0.5:
+            return _PrecompileHandle()
+
+        verbose = os.getenv(f"{PACKAGE_NAME.upper()}_PRINT_AUTOTUNING", None) == "1"
+        if verbose:
+            print(f"Pre-compiling {len(configs)} configs with {max_workers} workers")
+
+        import pickle
+        import struct
+
+        def _send(stream, msg):
+            data = pickle.dumps(msg)
+            stream.write(struct.pack(" 1:
+            all_args = {**self.nargs, **kwargs}
+            _args = {k: v for (k, v) in all_args.items() if k in self.arg_names}
+            # Need "str" to make it json-serializable
+            key = [str(_args[key]) for key in self.keys if key in _args]
+            for _, arg in _args.items():
+                if isinstance(arg, Tensor):
+                    key.append(str(arg.shape))
+                    # If stride != 0, 1, we just cache it as 2
+                    key.append(str([s if s in {0, 1} else 2 for s in arg.stride()]))
+                    key.append(str(arg.dtype))
+            key = tuple(key)
+            if key not in self.cache:
+                used_cached_result = False
+                pruned_configs = self.prune_configs(kwargs)
+
+                @torch.compiler.disable  # Don't want any tracing here
+                def benchmark():
+                    # Two new mechanisms cooperate here:
+                    #   (a) ``_precompile`` returns a ``_PrecompileHandle``
+                    #       whose ``wait_for(i)`` blocks until config i is
+                    #       done compiling in the subprocess pool; remaining
+                    #       configs continue compiling in background reader
+                    #       threads, overlapping with this loop's GPU work.
+                    #       Total wall = max(parallel_compile, serial_bench).
+                    #   (b) The L2-cold ``_bench`` path needs pre-cloned
+                    #       (args, kwargs) sets attached to ``self`` once per
+                    #       shape so all configs share the same buffer set.
+                    # Both share one try/finally so handle.shutdown() and the
+                    # L2-cold set cleanup run even on exception (incl. OOM
+                    # inside ``_gpu_warmup``).
+                    handle = self._precompile(*args, configs=pruned_configs, **kwargs)
+                    bench_start = time.time()
+                    verbose = os.getenv(f"{PACKAGE_NAME.upper()}_PRINT_AUTOTUNING", None) == "1"
+                    has_hooks = self.pre_hook is not None or self.post_hook is not None
+                    timings = {}
+                    try:
+                        _gpu_warmup()
+                        # Pre-allocate cloned (args, kwargs) sets once per
+                        # shape; the same sets are reused across all configs
+                        # to avoid ~400x re-cloning. Skipped when hooks are
+                        # present or a custom do_bench was supplied (legacy
+                        # fallback in _bench).
+                        if self._do_bench is None and not has_hooks:
+                            try:
+                                n_buffers = _pick_l2_rotate_count(args, kwargs)
+                                arg_sets, kwarg_sets = _clone_l2_rotate_inputs(
+                                    args, kwargs, n_buffers
+                                )
+                                self._l2_cold_arg_sets = arg_sets
+                                self._l2_cold_kwarg_sets = kwarg_sets
+                            except (RuntimeError, MemoryError):
+                                # Cloning failed (likely OOM at extreme N);
+                                # legacy do_bench path will be used by _bench.
+                                self._l2_cold_arg_sets = None
+                                self._l2_cold_kwarg_sets = None
+                        else:
+                            self._l2_cold_arg_sets = None
+                            self._l2_cold_kwarg_sets = None
+
+                        for i, config in enumerate(pruned_configs):
+                            # Block until this config's compile has finished
+                            # in the subprocess pool. The other configs keep
+                            # compiling in their reader threads while we
+                            # benchmark, giving us the parallel/serial overlap.
+                            handle.wait_for(i)
+                            # If the subprocess pool failed to compile this
+                            # config (worker crashed, ERR: reply, etc.), warm
+                            # jit_cache in-process FIRST so the bench time
+                            # below excludes the compile cost — otherwise the
+                            # artificially-slow timing would mask a config
+                            # that's actually the best.
+                            if handle.is_failed(i):
+                                if verbose:
+                                    print(
+                                        f"[autotune] config {i} subprocess "
+                                        f"compile failed ({handle.failures[i]}); "
+                                        f"falling back to in-process compile "
+                                        f"before benchmarking"
+                                    )
+                                try:
+                                    current = dict(kwargs, **config.all_kwargs())
+                                    self.fn(*args, **current)
+                                except Exception:
+                                    # _bench below will record float('inf')
+                                    # if the kernel raises during the run.
+                                    pass
+                            timings[config] = self._bench(*args, config=config, **kwargs)
+                    finally:
+                        # Free L2-cold sets before persisting the cache so the
+                        # user's subsequent .fn(...) call has full HBM.
+                        self._l2_cold_arg_sets = None
+                        self._l2_cold_kwarg_sets = None
+                        # Always shutdown to avoid orphan workers / dangling
+                        # reader threads, even if a bench raised.
+                        handle.shutdown()
+                    bench_end = time.time()
+                    if verbose:
+                        for config, time_ in timings.items():
+                            print(f"[{config}] -> {time_[0]:.3f}ms")
+                    # Surface bench failures (configs returning inf timings)
+                    # so smem-overflow / launch errors aren't silently masked.
+                    n_failed = sum(1 for t in timings.values() if t[0] == float("inf"))
+                    if n_failed:
+                        print(
+                            f"quack autotune: {n_failed}/{len(timings)} configs "
+                            f"failed for {self.fn.__name__}{key}; "
+                            f"set {PACKAGE_NAME.upper()}_PRINT_AUTOTUNING=1 for details",
+                            file=sys.stderr,
+                        )
+                    self.bench_time = bench_end - bench_start
+                    self.cache[key] = builtins.min(timings, key=timings.get)
+                    self.configs_timings = timings
+
+                if self.cache_results:
+                    self.check_disk_cache(key, pruned_configs, benchmark)
+                else:
+                    benchmark()
+
+            config = self.cache[key]
+        else:
+            config = self.configs[0]
+        self.best_config = config
+        if (
+            os.getenv(f"{PACKAGE_NAME.upper()}_PRINT_AUTOTUNING", None) == "1"
+            and not used_cached_result
+        ):
+            print(
+                f"{PACKAGE_NAME} autotuning for function {self.fn.__name__} finished after "
+                f"{self.bench_time:.2f}s; best config selected: {self.best_config};"
+            )
+        ret = self.fn.__call__(
+            *args,
+            **kwargs,
+            **config.all_kwargs(),
+        )
+        self.nargs = None
+        return ret
+
+    def prune_configs(self, kwargs: Dict) -> List[Any]:
+        pruned_configs = self.configs
+        if self.early_config_prune:
+            pruned_configs = self.early_config_prune(self.configs, self.nargs, **kwargs)
+        if self.perf_model:
+            top_k = self.configs_top_k
+            if isinstance(top_k, float) and top_k <= 1.0:
+                top_k = int(len(self.configs) * top_k)
+            elif not isinstance(top_k, int):
+                # Slice index must be an integer
+                raise TypeError(
+                    "Error while pruning configs, top_k must be either 1) a float <= 1.0 or 2) an int"
+                )
+
+            if len(pruned_configs) > top_k:
+                est_timing = {
+                    config: self.perf_model(
+                        **self.nargs,
+                        **kwargs,
+                        **config.all_kwargs(),
+                    )
+                    for config in pruned_configs
+                }
+                pruned_configs = sorted(est_timing.keys(), key=lambda x: est_timing[x])[:top_k]
+        return pruned_configs
+
+
+class AutotuneConfig:
+    """
+    An object that represents a possible kernel configuration for the auto-tuner to try.
+
+    :ivar kwargs: a dictionary of meta-parameters to pass to the kernel as keyword arguments.
+    :type kwargs: dict[Str, Any]
+    """
+
+    def __init__(self, **kwargs):
+        self.kwargs = kwargs
+
+    def __setstate__(self, state):
+        self.kwargs = state.get("kwargs", {})
+
+    def all_kwargs(self):
+        return self.kwargs
+
+    def __str__(self):
+        res = []
+        for k, v in self.kwargs.items():
+            res.append(f"{k}: {v}")
+        return ", ".join(res)
+
+    def __hash__(self):
+        return hash(tuple(self.all_kwargs().items()))
+
+    def __eq__(self, other):
+        self_tuple = tuple(self.all_kwargs().items())
+        other_tuple = tuple(other.all_kwargs().items())
+        return self_tuple == other_tuple
+
+
+def autotune(
+    configs,
+    key=None,
+    prune_configs_by=None,
+    restore_value=None,
+    do_bench=None,
+    cache_results=True,
+    precompile_configs=True,
+):
+    f"""
+    Decorator for auto-tuning a function function.
+
+    .. highlight:: python
+
+    If the environment variable :code:`{PACKAGE_NAME.upper()}_PRINT_AUTOTUNING` is set to
+    :code:`"1"`, we will print a message to stdout after autotuning each
+    kernel, including the time spent autotuning and the best configuration.
+
+    :param configs: a list of :code:`AutotuneConfig` objects
+    :type configs: list[AutotuneConfig]
+    :param key: a list of argument names whose change in value will trigger the evaluation of all provided configs.
+    :type key: list[str]
+    :param prune_configs_by: a dict of functions that are used to prune configs, fields:
+        'perf_model': performance model used to predicate running time with different configs, returns running time
+        'top_k': number of configs to bench
+        'early_config_prune'(optional): a function used to do early prune (eg, num_stages). It takes configs:List[Config] as its input, and returns pruned configs.
+    :param restore_value: a list of argument names whose value will be restored after evaluating any configs.
+    :type restore_value: list[str]
+    :param do_bench: a benchmark function to measure the time of each run.
+    :type do_bench: lambda fn, quantiles
+    :param cache_results: whether to cache autotune timings to disk.  Defaults to False.
+    :param precompile_configs: whether to warm config compile caches in worker subprocesses.
+    "type cache_results: bool
+    """
+
+    if key is None:
+        key = []
+
+    def decorator(fn):
+        return Autotuner(
+            fn,
+            key,
+            configs,
+            restore_value=restore_value,
+            prune_configs_by=prune_configs_by,
+            do_bench=do_bench,
+            cache_results=cache_results,
+            precompile_configs=precompile_configs,
+        )
+
+    return decorator
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/bench/__init__.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/bench/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/bench/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/bench/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b4f1017ba447fc9da8535b89e8ee363936b45fa
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/bench/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/bench/__pycache__/bench_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/bench/__pycache__/bench_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad997abdcc0cb5819b319c6ad4032c7f78d9a2d3
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/bench/__pycache__/bench_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/bench/bench_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/bench/bench_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..129d37121522461f3abf02c2c296535091f4a3c1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/bench/bench_utils.py
@@ -0,0 +1,202 @@
+"""Shared helpers for triton perf_report-based benchmarks."""
+
+from __future__ import annotations
+
+import os
+from typing import TYPE_CHECKING
+
+import torch
+from torch import Tensor
+
+if TYPE_CHECKING:
+    import pandas as pd
+    from triton.testing import Benchmark
+
+
+def run_and_print(mark, save_path=None):
+    """Run a triton ``Mark`` (from ``perf_report``) and print/save results.
+
+    Each runner is expected to return a ``dict[str, Any]`` mapping stat name to
+    value, e.g. ``{"ms": 0.123, "GB/s": 1234}``. All providers in a benchmark
+    must return the same set of keys. Values are written through unchanged --
+    rounding/formatting is the caller's responsibility.
+
+    Output columns are ``x_names + [f"{line_name} ({stat})" for ...]``.
+    """
+    benchmarks = mark.benchmarks if isinstance(mark.benchmarks, list) else [mark.benchmarks]
+    for bench in benchmarks:
+        df = _run_one(mark.fn, bench)
+        print(bench.plot_name + ":")
+        print(df.to_string())
+        if save_path:
+            os.makedirs(save_path, exist_ok=True)
+            df.to_csv(os.path.join(save_path, f"{bench.plot_name}.csv"), index=False)
+
+
+def _run_one(fn, bench: Benchmark) -> pd.DataFrame:
+    try:
+        import pandas as pd
+    except ImportError as e:
+        raise ImportError(
+            "pandas is required to format benchmark results. "
+            "Install it with `pip install pandas` or `pip install -e '.[bench]'`."
+        ) from e
+
+    x_names = list(bench.x_names)
+    rows = []
+    stat_keys = None  # locked in from the first runner result
+    for x in bench.x_vals:
+        if not isinstance(x, (list, tuple)):
+            x = [x] * len(x_names)
+        x_args = dict(zip(x_names, x))
+        row = list(x)
+        for line_val in bench.line_vals:
+            stats = fn(**x_args, **{bench.line_arg: line_val}, **bench.args)
+            if not isinstance(stats, dict):
+                raise TypeError(f"runner must return dict[str, Any], got {type(stats).__name__}")
+            if stat_keys is None:
+                stat_keys = list(stats.keys())
+            elif list(stats.keys()) != stat_keys:
+                raise ValueError(f"runner returned keys {list(stats.keys())}, expected {stat_keys}")
+            row.extend(stats[k] for k in stat_keys)
+        rows.append(row)
+    cols = list(x_names) + [
+        f"{name} ({stat})" for name in bench.line_names for stat in (stat_keys or [])
+    ]
+    return pd.DataFrame(rows, columns=cols)
+
+
+def _bench_cuda_graph_l2_rotate(
+    fn,
+    arg_sets,
+    kwarg_sets,
+    extra_kwargs,
+    warmup_target_ms: float = 200.0,
+    n_timed_calls: int = 200,
+    quantiles=None,
+):
+    """L2-cold single-replay CUDA-graph benchmark.
+
+    Warmup is time-based: probe a single kernel launch to estimate the
+    per-call cost, then iterate round-robin over the pre-cloned
+    ``(arg_sets[i], kwarg_sets[i])`` pairs as a plain Python loop for
+    ``warmup_target_ms`` of wall-clock GPU work. Heavy pipelined configs
+    (TMA + smem_stages=3) need enough warmup to drain the pipeline-fill
+    phase or the timed window catches them artificially fast - a fixed
+    count of warmup launches underwarms heavy configs while overpaying
+    for cheap ones.
+
+    The timed window is a single ``graph.replay()`` of a captured CUDA
+    graph whose body records ``n_timed_calls`` round-robin invocations -
+    no Python loop, no per-launch CPU overhead - so the measurement is
+    just GPU work / total recorded calls.
+
+    Round-robin over fresh tensor sets defeats the L2-resident caching
+    that inflates short-kernel timing under ``triton.testing.do_bench``
+    (which calls the kernel on the same single tensor each iteration).
+    For cache-cold production workloads the round-robin number predicts
+    real-world latency; the L2-hot number favours wider layouts / deeper
+    smem stages that don't actually win once data has to come from HBM.
+
+    ``fn`` is called as ``fn(*arg_sets[i], **kwarg_sets[i], **extra_kwargs)``
+    once per recorded launch. ``extra_kwargs`` holds the per-config kwargs
+    (e.g. ``{"config": }``) which don't need cloning;
+    keys in ``extra_kwargs`` must not overlap with ``kwarg_sets[i]``.
+    Returns ms/call, or a ``len(quantiles)``-list replicating that value
+    when ``quantiles`` is provided (for API parity with
+    ``triton.testing.do_bench``).
+    """
+    n_sets = len(arg_sets)
+    # Round timed-call count to a multiple of n_sets for even L2 turnover.
+    rounds_timed = max(1, n_timed_calls // n_sets)
+    total_timed_calls = rounds_timed * n_sets
+
+    # A few priming launches so the probe doesn't catch first-launch
+    # driver / kernel-load overhead.
+    for _ in range(3):
+        fn(*arg_sets[0], **kwarg_sets[0], **extra_kwargs)
+    torch.cuda.synchronize()
+
+    # Probe a single launch to estimate per-call ms; size the warmup loop
+    # to hit ``warmup_target_ms`` of GPU work regardless of kernel cost.
+    probe_start = torch.cuda.Event(enable_timing=True)
+    probe_end = torch.cuda.Event(enable_timing=True)
+    probe_start.record()
+    fn(*arg_sets[0], **kwarg_sets[0], **extra_kwargs)
+    probe_end.record()
+    torch.cuda.synchronize()
+    est_ms = max(probe_start.elapsed_time(probe_end), 1e-3)
+    n_warmup_calls = max(50, int(warmup_target_ms / est_ms))
+
+    # Warmup: plain Python loop over rotating sets, no graph capture.
+    for i in range(n_warmup_calls):
+        idx = i % n_sets
+        fn(*arg_sets[idx], **kwarg_sets[idx], **extra_kwargs)
+    torch.cuda.synchronize()
+
+    # Capture timed graph: a single replay covers all timed kernel launches.
+    timed_graph = torch.cuda.CUDAGraph()
+    with torch.cuda.graph(timed_graph):
+        for _ in range(rounds_timed):
+            for i in range(n_sets):
+                fn(*arg_sets[i], **kwarg_sets[i], **extra_kwargs)
+    torch.cuda.synchronize()
+
+    start_evt = torch.cuda.Event(enable_timing=True)
+    end_evt = torch.cuda.Event(enable_timing=True)
+    start_evt.record()
+    timed_graph.replay()
+    end_evt.record()
+    torch.cuda.synchronize()
+    ms = start_evt.elapsed_time(end_evt) / total_timed_calls
+
+    if quantiles:
+        return [ms for _ in quantiles]
+    return ms
+
+
+def _clone_l2_rotate_inputs(args, kwargs, n_buffers: int):
+    """Clone tensor args AND tensor kwargs ``n_buffers`` times.
+
+    Returns ``(arg_sets, kwarg_sets)``: ``arg_sets[i]`` is a tuple matching
+    ``args``' positional shape with tensors cloned to fresh memory;
+    ``kwarg_sets[i]`` is a dict matching ``kwargs``' keys with tensor values
+    cloned. Non-tensor values (ints, strings, None, dataclasses, etc.) are
+    shared across all sets (no clone).
+
+    Both args and kwargs are cloned so that every recorded launch in the
+    L2-cold round-robin CUDA graph touches distinct GMEM addresses,
+    including for write-target kwargs like ``dw_partial`` / ``dx``.
+    """
+    arg_sets = []
+    kwarg_sets = []
+    for _ in range(n_buffers):
+        arg_sets.append(tuple(a.clone() if isinstance(a, Tensor) else a for a in args))
+        kwarg_sets.append({k: v.clone() if isinstance(v, Tensor) else v for k, v in kwargs.items()})
+    return arg_sets, kwarg_sets
+
+
+def _pick_l2_rotate_count(
+    args, kwargs, target_ratio: int = 3, min_buffers: int = 4, max_buffers: int = 16
+):
+    """Pick ``n_bufs`` so cloned input bytes per round exceed
+    ``target_ratio * L2_size`` (defeats L2 reuse), capped by HBM headroom and
+    [min_buffers, max_buffers]. Counts tensor bytes across both ``args`` and
+    ``kwargs`` so write-target kwargs (``dw_partial``, ``dx``, etc.) are
+    included in the L2-turnover calculation.
+    """
+    if not torch.cuda.is_available():
+        return min_buffers
+    tensor_bytes = sum(a.numel() * a.element_size() for a in args if isinstance(a, Tensor)) + sum(
+        v.numel() * v.element_size() for v in kwargs.values() if isinstance(v, Tensor)
+    )
+    if tensor_bytes == 0:
+        return min_buffers
+    props = torch.cuda.get_device_properties(torch.cuda.current_device())
+    l2_size = props.L2_cache_size
+    n_by_l2 = (target_ratio * l2_size + tensor_bytes - 1) // tensor_bytes
+    free_bytes, _ = torch.cuda.mem_get_info()
+    # Leave half of free memory headroom for the kernel's own scratch + the
+    # user's other allocations.
+    n_by_mem = max(1, int(free_bytes * 0.5) // tensor_bytes)
+    return max(min_buffers, min(max_buffers, min(n_by_l2, n_by_mem)))
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/blockscaled_gemm_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/blockscaled_gemm_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdd682fd7d409bdcb32b9c3e0a07890ad4af6561
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/blockscaled_gemm_utils.py
@@ -0,0 +1,752 @@
+# Copyright (c) 2026, Tri Dao.
+
+import itertools
+from functools import partial
+from typing import Callable, Optional, Type, Tuple
+
+import torch
+
+import cutlass
+import cutlass.cute as cute
+
+from .compile_utils import make_fake_tensor as fake_tensor
+from .cute_dsl_utils import get_device_capacity, get_max_active_clusters
+from .gemm_default_epi import GemmDefaultSm100
+from .gemm_tvm_ffi_utils import div_for_dtype, make_scheduler_args
+from .mx_utils import (
+    to_mx_compiled,
+    to_mxfp4_compiled,
+    to_nvfp4_compiled,
+)
+from .varlen_utils import VarlenArguments
+
+
+TORCH_DTYPE_MAP = {
+    cutlass.Float4E2M1FN: torch.float4_e2m1fn_x2,
+    cutlass.Float16: torch.float16,
+    cutlass.BFloat16: torch.bfloat16,
+    cutlass.Float32: torch.float32,
+    cutlass.Float8E4M3FN: torch.float8_e4m3fn,
+    cutlass.Float8E5M2: torch.float8_e5m2,
+    cutlass.Float8E8M0FNU: torch.float8_e8m0fnu,
+}
+
+FLOAT8_DTYPES = {
+    torch.float8_e4m3fn,
+    torch.float8_e5m2,
+    torch.float8_e8m0fnu,
+}
+
+
+FP4_E2M1FN_VALUES = (
+    0.0,
+    0.5,
+    1.0,
+    1.5,
+    2.0,
+    3.0,
+    4.0,
+    6.0,
+    -0.0,
+    -0.5,
+    -1.0,
+    -1.5,
+    -2.0,
+    -3.0,
+    -4.0,
+    -6.0,
+)
+
+
+def ceil_div(a: int, b: int) -> int:
+    return (a + b - 1) // b
+
+
+def torch_dtype_for_cutlass(dtype: Type[cutlass.Numeric]) -> torch.dtype:
+    if dtype not in TORCH_DTYPE_MAP:
+        raise TypeError(f"Unsupported dtype: {dtype}")
+    return TORCH_DTYPE_MAP[dtype]
+
+
+def _make_fake_tensor_like(tensor: torch.Tensor, dtype: Type[cutlass.Numeric]) -> cute.Tensor:
+    return cute.runtime.make_fake_tensor(
+        dtype,
+        tensor.shape,
+        stride=tensor.stride(),
+        assumed_align=16,
+    )
+
+
+def _leading_dim_from_stride(tensor: torch.Tensor) -> int:
+    for i, stride in enumerate(tensor.stride()):
+        if stride == 1:
+            return i
+    raise ValueError(
+        f"Tensor has no unit stride dimension: shape={tensor.shape}, stride={tensor.stride()}"
+    )
+
+
+def _make_compile_tensor_like(
+    tensor: torch.Tensor, dtype: Type[cutlass.Numeric], dynamic_layout: bool = False
+) -> cute.Tensor:
+    compile_tensor = cute.runtime.from_dlpack(tensor)
+    compile_tensor.element_type = dtype
+    if dynamic_layout:
+        marked = compile_tensor.mark_layout_dynamic(leading_dim=_leading_dim_from_stride(tensor))
+        if marked is not None:
+            compile_tensor = marked
+    return compile_tensor
+
+
+def _make_fake_compact_tensor(
+    shape: Tuple[int, ...], dtype: Type[cutlass.Numeric], leading_dim: int
+) -> cute.Tensor:
+    logical_shape = list(shape)
+    if dtype == cutlass.Float4E2M1FN:
+        logical_shape[leading_dim] *= 2
+    return fake_tensor(
+        dtype,
+        tuple(logical_shape),
+        leading_dim=leading_dim,
+        divisibility=div_for_dtype(dtype),
+    )
+
+
+def _fp4_e2m1fn_value_table(device: torch.device) -> torch.Tensor:
+    return torch.tensor(FP4_E2M1FN_VALUES, dtype=torch.float32, device=device)
+
+
+def _pack_fp4_e2m1fn_codes(codes: torch.Tensor) -> torch.Tensor:
+    """Pack logical FP4 codes into torch.float4_e2m1fn_x2 storage."""
+    if codes.dtype != torch.uint8:
+        raise TypeError(f"Expected uint8 FP4 codes, got {codes.dtype}")
+    packed_shape = (codes.shape[0], ceil_div(codes.shape[1], 2), codes.shape[2])
+    packed = torch.empty(packed_shape, dtype=torch.float4_e2m1fn_x2, device=codes.device)
+    packed_u8 = packed.view(torch.uint8)
+    low = codes[:, 0::2, :]
+    high = torch.zeros_like(low)
+    high[:, : codes[:, 1::2, :].shape[1], :] = codes[:, 1::2, :]
+    packed_u8.copy_(low | (high << 4))
+    return packed
+
+
+def _create_fp4_operand_tensor(
+    l: int,
+    mode0: int,
+    mode1: int,
+    is_mode0_major: bool,
+    *,
+    init: str,
+) -> Tuple[Optional[torch.Tensor], torch.Tensor]:
+    if is_mode0_major:
+        raise ValueError("Float4E2M1FN blockscaled operands must be K-major")
+    tensor = torch.empty(
+        (mode0, ceil_div(mode1, 2), l), dtype=torch.float4_e2m1fn_x2, device="cuda"
+    )
+    tensor.view(torch.uint8).zero_()
+    if init == "empty":
+        return None, tensor
+    if init != "normal":
+        raise ValueError(f"Unsupported init: {init}")
+
+    magnitudes = torch.randint(0, 8, (mode0, mode1, l), device="cuda", dtype=torch.uint8)
+    signs = torch.randint(0, 2, (mode0, mode1, l), device="cuda", dtype=torch.uint8)
+    signs = torch.where(magnitudes == 0, torch.zeros_like(signs), signs << 3)
+    codes = magnitudes | signs
+    tensor.copy_(_pack_fp4_e2m1fn_codes(codes))
+    ref = _fp4_e2m1fn_value_table(tensor.device)[codes.long()]
+    return ref, tensor
+
+
+def create_blockscaled_operand_tensor(
+    l: int,
+    mode0: int,
+    mode1: int,
+    is_mode0_major: bool,
+    dtype: Type[cutlass.Numeric],
+    *,
+    init: str = "normal",
+) -> Tuple[Optional[torch.Tensor], torch.Tensor]:
+    if dtype == cutlass.Float4E2M1FN:
+        return _create_fp4_operand_tensor(l, mode0, mode1, is_mode0_major, init=init)
+    shape = (l, mode1, mode0) if is_mode0_major else (l, mode0, mode1)
+    permute_order = (2, 1, 0) if is_mode0_major else (1, 2, 0)
+    torch_dtype = torch_dtype_for_cutlass(dtype)
+    gen_dtype = torch.bfloat16 if torch_dtype in FLOAT8_DTYPES else torch_dtype
+    tensor = torch.empty(shape, dtype=gen_dtype, device="cuda")
+    if init == "normal":
+        tensor.normal_(std=mode1 ** (-0.5))
+    elif init != "empty":
+        raise ValueError(f"Unsupported init: {init}")
+    # Do NOT .contiguous() after .permute() — that would re-materialize with wrong
+    # strides (L innermost) and break K-majorness / N-majorness for l > 1.
+    # The original (l, mode0/1, mode1/0) is contiguous, and the permuted view has
+    # the correct per-mode strides: stride=1 on the intended contiguous dim.
+    tensor = tensor.to(torch_dtype).permute(permute_order)
+    ref = tensor.float() if init != "empty" else None
+    return ref, tensor
+
+
+def _pack_blockscaled_scales(ref_blocks: torch.Tensor) -> torch.Tensor:
+    """Rearrange (mn, sf_k, l) scales into the (l, rm, rk, 512) blocked layout."""
+    mn, sf_k, l = ref_blocks.shape
+    rm = ceil_div(mn, 128)
+    rk = ceil_div(sf_k, 4)
+    packed_6d = torch.zeros((l, rm, rk, 32, 4, 4), dtype=torch.float32, device=ref_blocks.device)
+    packed_view = packed_6d.permute(3, 4, 1, 5, 2, 0)  # (32, 4, rm, 4, rk, l)
+    m_idx = torch.arange(mn, device=ref_blocks.device)
+    k_idx = torch.arange(sf_k, device=ref_blocks.device)
+    l_idx = torch.arange(l, device=ref_blocks.device)
+    packed_view[
+        m_idx[:, None, None] % 32,
+        (m_idx[:, None, None] // 32) % 4,
+        m_idx[:, None, None] // 128,
+        k_idx[None, :, None] % 4,
+        k_idx[None, :, None] // 4,
+        l_idx[None, None, :],
+    ] = ref_blocks
+    return packed_6d.view(l, rm, rk, 512)
+
+
+def create_blockscaled_scale_tensor(
+    l: int,
+    mn: int,
+    k: int,
+    sf_vec_size: int,
+    dtype: Type[cutlass.Numeric],
+) -> Tuple[torch.Tensor, torch.Tensor]:
+    sf_k = ceil_div(k, sf_vec_size)
+    if dtype == cutlass.Float8E8M0FNU:
+        exponents = torch.randint(0, 2, (mn, sf_k, l), device="cuda", dtype=torch.int32)
+        ref_blocks = torch.pow(2.0, exponents.float())
+    else:
+        ref_blocks = torch.randint(1, 4, (mn, sf_k, l), device="cuda", dtype=torch.int32).float()
+
+    packed_f32 = _pack_blockscaled_scales(ref_blocks)
+    packed = torch.empty_like(packed_f32, dtype=torch_dtype_for_cutlass(dtype))
+    packed.copy_(packed_f32)
+    ref = (
+        ref_blocks.permute(2, 0, 1)
+        .unsqueeze(-1)
+        .expand(l, mn, sf_k, sf_vec_size)
+        .reshape(l, mn, sf_k * sf_vec_size)
+        .permute(1, 2, 0)
+    )[:, :k, :]
+    return ref, packed
+
+
+def pack_scale_2d_to_blocked_contig(scale_2d: torch.Tensor) -> torch.Tensor:
+    """Rearrange a (l, mn, sf_k) or (mn, sf_k) e8m0 scale tensor into the
+    contiguous (l, rm, rk, 512) blocked layout shared by the quack kernel and
+    cuBLAS's block-scaling. Each 512 B inner block holds one 128 MN × 4 K
+    swizzled tile. Pads `mn` to a multiple of 128 and `sf_k` to a multiple of
+    4 with zeros."""
+    if scale_2d.dim() == 2:
+        scale_2d = scale_2d.unsqueeze(0)
+    assert scale_2d.dim() == 3, f"expected (l, mn, sf_k), got shape {tuple(scale_2d.shape)}"
+    orig_dtype = scale_2d.dtype
+    l, mn, sf_k = scale_2d.shape
+    rm = ceil_div(mn, 128)
+    rk = ceil_div(sf_k, 4)
+    mn_pad = rm * 128
+    sf_k_pad = rk * 4
+    u8 = scale_2d.contiguous().view(torch.uint8)
+    if mn_pad != mn or sf_k_pad != sf_k:
+        padded = torch.zeros(l, mn_pad, sf_k_pad, device=scale_2d.device, dtype=torch.uint8)
+        padded[:, :mn, :sf_k] = u8
+    else:
+        padded = u8
+    # (l, mn_pad, sf_k_pad) -> (l, rm, 128, rk, 4) -> (l, rm, rk, 128, 4)
+    blocks = padded.view(l, rm, 128, rk, 4).permute(0, 1, 3, 2, 4)
+    # split 128 into (4 outer, 32 inner), then swap to (32, 4)
+    blocks = blocks.reshape(l, rm, rk, 4, 32, 4).transpose(3, 4).contiguous()
+    return blocks.view(l, rm, rk, 512).view(orig_dtype)
+
+
+def scale_view_for_kernel(scale_contig: torch.Tensor, mn: int, sf_k: int, l: int) -> torch.Tensor:
+    """Validate a (l, rm, rk, 512) scale tensor and return it unchanged.
+    Only the innermost 512-B tile must be contiguous (stride 1, size 512);
+    outer (L, rm, rk) strides are free — the kernel reads them from the
+    passed tensor. This lets callers pass a slice/view of a larger buffer
+    with no extra copy. Works for both E8M0 (MX) and E4M3 (NVFP4)."""
+    rm = ceil_div(mn, 128)
+    rk = ceil_div(sf_k, 4)
+    assert scale_contig.shape == (l, rm, rk, 512), (
+        f"expected (l, rm, rk, 512) = ({l}, {rm}, {rk}, 512), got {tuple(scale_contig.shape)}"
+    )
+    assert scale_contig.stride(-1) == 1, (
+        f"innermost 512-B dim must be unit-stride, got stride {scale_contig.stride(-1)}"
+    )
+    return scale_contig
+
+
+def scale_blocked_for_cublas(
+    scale_contig: torch.Tensor, mn: int, sf_k: int, l_idx: int = 0
+) -> torch.Tensor:
+    """Flatten a (l, rm, rk, 512) scale tensor to the 1D swizzled layout
+    torch._scaled_mm expects. Uses a single l slice."""
+    assert scale_contig.is_contiguous() and scale_contig.dim() == 4
+    return scale_contig[l_idx].reshape(-1)
+
+
+_FP4_E2M1_CODE_TO_VALUE = torch.tensor(FP4_E2M1FN_VALUES, dtype=torch.float32)
+
+
+def _fp4_unpacked_to_value(codes_u8: torch.Tensor) -> torch.Tensor:
+    """Convert FP4 E2M1 codes in [0,16) to signed float values via table lookup.
+    Code layout: bit 3 = sign, bits 0-2 = magnitude index into {0,.5,1,1.5,2,3,4,6}."""
+    table = _FP4_E2M1_CODE_TO_VALUE.to(codes_u8.device)
+    return table[codes_u8.long()]
+
+
+def _blockscaled_format_of(ab_dtype, sf_dtype, sf_vec_size) -> str:
+    """Identify which blockscaled format the (ab, sf, vec) tuple corresponds to."""
+    if ab_dtype == cutlass.Float8E4M3FN and sf_dtype == cutlass.Float8E8M0FNU and sf_vec_size == 32:
+        return "mxfp8"
+    if ab_dtype == cutlass.Float4E2M1FN and sf_dtype == cutlass.Float8E8M0FNU and sf_vec_size == 32:
+        return "mxfp4"
+    if ab_dtype == cutlass.Float4E2M1FN and sf_dtype == cutlass.Float8E4M3FN and sf_vec_size == 16:
+        return "nvfp4"
+    raise ValueError(
+        f"init=quant does not support (ab={ab_dtype}, sf={sf_dtype}, vec={sf_vec_size}). "
+        f"Supported: MXFP8 (e4m3+e8m0+32), MXFP4 (e2m1+e8m0+32), NVFP4 (e2m1+e4m3+16)."
+    )
+
+
+def create_blockscaled_operand_quantized(
+    l: int,
+    mn: int,
+    k: int,
+    is_mn_major: bool,
+    sf_vec_size: int = 32,
+    ab_dtype: Type[cutlass.Numeric] = cutlass.Float8E4M3FN,
+    sf_dtype: Type[cutlass.Numeric] = cutlass.Float8E8M0FNU,
+    *,
+    randn_std: Optional[float] = None,
+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+    """Generate bf16 randn, quantize to MXFP8/MXFP4/NVFP4 and produce:
+    ref:   (mn, k, l) float32 dequantized reference
+    q_mkl: (mn, k, l) operand tensor in the layout the quack kernel consumes
+           (float8_e4m3fn for fp8 formats; int8 with packed nibbles for fp4)
+    scale_contig: (l, rm, rk, 512) contiguous scale storage. Each 512 B
+           inner block is one 128 MN × 4 K swizzled tile. Byte layout matches
+           cuBLAS `to_blocked`. Pass directly to the quack kernel, or use
+           `scale_blocked_for_cublas` for cuBLAS.
+    """
+    fmt = _blockscaled_format_of(ab_dtype, sf_dtype, sf_vec_size)
+    if is_mn_major and fmt != "mxfp8":
+        raise NotImplementedError(
+            f"is_mn_major=True is only supported for MXFP8 (tcgen05 MMA requires "
+            f"K-major for MXFP4/NVFP4 operands); got fmt={fmt}"
+        )
+    assert k % sf_vec_size == 0, f"k ({k}) must be divisible by sf_vec_size ({sf_vec_size})"
+    sf_k = k // sf_vec_size
+    std = randn_std if randn_std is not None else k**-0.5
+
+    x_hp = (torch.randn(l, mn, k, dtype=torch.bfloat16, device="cuda") * std).contiguous()
+    x_flat = x_hp.view(l * mn, k)
+
+    if fmt == "mxfp8":
+        q_flat, scale_2d = to_mx_compiled(x_flat, sf_vec_size)  # (l*mn, k), (l*mn, sf_k)
+        if is_mn_major:
+            # Operand: (mn, k, l) MN-major. Start from (l, mn, k) contig, transpose
+            # to (l, k, mn) contig, then permute to (mn, k, l) with strides (1, mn, mn*k).
+            q_mkl = (
+                q_flat.view(l, mn, k).transpose(1, 2).contiguous().permute(2, 1, 0)
+            )  # strides (1, mn, mn*k)
+        else:
+            # Operand: (mn, k, l) K-major VIEW of contiguous (l, mn, k).
+            # Do NOT call .contiguous() here — that would materialize as (mn, k, l) row-major,
+            # making L the innermost stride=1 dim and BREAKING K-majorness for l > 1.
+            q_mkl = q_flat.view(l, mn, k).contiguous().permute(1, 2, 0)  # strides (k, 1, mn*k)
+        q_vals = q_flat.float().view(l, mn, k)
+        scale_vals = scale_2d.float().view(l, mn, sf_k).repeat_interleave(sf_vec_size, dim=-1)
+        ref_mkl = (q_vals * scale_vals).permute(1, 2, 0).contiguous()
+        scale_2d = scale_2d.view(l, mn, sf_k)
+    elif fmt in ("mxfp4", "nvfp4"):
+        if fmt == "mxfp4":
+            q_packed, scale_2d = to_mxfp4_compiled(x_flat, sf_vec_size)  # (l*mn, k/2), (l*mn, sf_k)
+        else:
+            q_packed, scale_2d, _pts = to_nvfp4_compiled(x_flat, sf_vec_size, None)
+        # q_packed is uint8, two 4-bit codes per byte (low nibble=even K, high=odd K).
+        # Decode for ref: code -> {0,.5,1,1.5,2,3,4,6,-0,-.5,...} via lookup.
+        codes_lo = (q_packed & 0x0F).view(l, mn, k // 2)
+        codes_hi = ((q_packed >> 4) & 0x0F).view(l, mn, k // 2)
+        vals_lo = _fp4_unpacked_to_value(codes_lo)  # (l, mn, k/2)
+        vals_hi = _fp4_unpacked_to_value(codes_hi)
+        q_values = torch.stack([vals_lo, vals_hi], dim=-1).reshape(l, mn, k)  # interleave back
+        scale_vals = scale_2d.float().view(l, mn, sf_k).repeat_interleave(sf_vec_size, dim=-1)
+        ref_mkl = (q_values * scale_vals).permute(1, 2, 0).contiguous()
+        # Kernel operand: (mn, k/2, l) K-major view (no post-contiguous!)
+        q_mkl = (
+            q_packed.view(l, mn, k // 2).contiguous().permute(1, 2, 0).view(torch.float4_e2m1fn_x2)
+        )
+        scale_2d = scale_2d.view(l, mn, sf_k)
+
+    scale_contig = pack_scale_2d_to_blocked_contig(scale_2d)
+    return ref_mkl, q_mkl, scale_contig
+
+
+def create_blockscaled_varlen_m_operands(
+    num_experts: int,
+    m_per: int,
+    n: int,
+    k: int,
+    sf_vec_size: int,
+    ab_dtype: Type[cutlass.Numeric] = cutlass.Float8E4M3FN,
+    sf_dtype: Type[cutlass.Numeric] = cutlass.Float8E8M0FNU,
+    *,
+    randn_std: Optional[float] = None,
+    seqlens_m: Optional[list] = None,
+    b_major: str = "k",
+):
+    """Generate bf16 randn + quantize for a varlen_m blockscaled GEMM.
+
+    Per-expert seqlens may be arbitrary (not required to be multiples of 128).
+    SF is stored in dQaccum-style padded format: each expert `i`'s scales
+    occupy `ceildiv(m_i, 128) * 128` rows at offset
+    `(cu_seqlens_m[i] + i * 128) // 128 * 128` in the padded scale buffer.
+    The kernel decodes via `VarlenManager.offset_batch_SFA` which applies the
+    same formula.
+
+    Returns (a_ref, b_ref, qa, qb, a_sc_contig, b_sc_contig, cu_seqlens_m):
+      a_ref: (total_m, k) fp32 dequantized
+      b_ref: (num_experts, n, k) fp32 dequantized
+      qa:   (total_m, k) 2D K-major quantized operand (fp8) or (total_m, k/2) (fp4)
+      qb:   (n, k, num_experts) 3D K-major quantized operand (fp8) or (n, k/2, num_experts) (fp4)
+      a_sc_contig: (1, total_padded_rm, rk, 512) — dQaccum-padded SFA.
+        total_padded_rm = ((total_m + num_experts * 128) // 128).
+      b_sc_contig: (num_experts, rn, rk, 512) — regular per-expert SFB.
+      cu_seqlens_m: (num_experts+1,) int32
+    """
+    assert k % sf_vec_size == 0
+    if seqlens_m is None:
+        seqlens_m = [m_per] * num_experts
+    assert len(seqlens_m) == num_experts, (
+        f"seqlens_m length {len(seqlens_m)} != num_experts {num_experts}"
+    )
+    total_m = int(sum(seqlens_m))
+    std = randn_std if randn_std is not None else k**-0.5
+    sf_k = k // sf_vec_size
+
+    if ab_dtype == cutlass.Float8E4M3FN and sf_dtype == cutlass.Float8E8M0FNU and sf_vec_size == 32:
+        from .mx_utils import to_mx_compiled
+
+        to_fn = to_mx_compiled
+    else:
+        raise NotImplementedError(
+            f"varlen_m currently only supports MXFP8 (got ab={ab_dtype}, sf={sf_dtype}, vec={sf_vec_size}). "
+            "FP4 support pending."
+        )
+
+    # Quantize A: (total_m, k) bf16 -> (total_m, k) fp8 K-major.
+    # A data itself is stored packed (no per-expert padding); only SFA is padded.
+    a_hp = (torch.randn(total_m, k, dtype=torch.bfloat16, device="cuda") * std).contiguous()
+    qa, sa_2d = to_fn(a_hp, sf_vec_size)  # (total_m, k), (total_m, sf_k)
+    a_ref = qa.float() * sa_2d.float().repeat_interleave(sf_vec_size, dim=-1)
+
+    # Build padded SFA storage (dQaccum format). Each expert's m_i rows of
+    # scales are written at padded tile offset `cu_seqlens[i] // 128 + i`.
+    # Allocation: `ceildiv(total_m, 128) + (L - 1)` tiles — proven sufficient
+    # in AI/varlen_blockscaled_sf_layout.md (proof 2's "tighter alternative").
+    # Matches `total_m // 128 + L` when total_m % 128 > 0; 1 tile smaller
+    # when total_m is an exact multiple of 128.
+    tile = 128
+    total_padded_rm = (total_m + tile - 1) // tile + (num_experts - 1)
+    total_padded_m = total_padded_rm * tile
+    sa_2d_padded = torch.zeros(total_padded_m, sf_k, dtype=sa_2d.dtype, device=sa_2d.device)
+    offset = 0
+    for i, m_i in enumerate(seqlens_m):
+        offset_padded = (offset // tile + i) * tile
+        sa_2d_padded[offset_padded : offset_padded + m_i] = sa_2d[offset : offset + m_i]
+        offset += m_i
+    a_sc_contig = pack_scale_2d_to_blocked_contig(sa_2d_padded.view(1, total_padded_m, sf_k))
+
+    # Quantize B: (num_experts, n, k) bf16 -> (n, k, num_experts). b_major selects
+    # k-major (stride (k, 1, n*k)) or n-major (stride (1, n, n*k)).
+    assert b_major in ("k", "n"), f"b_major must be 'k' or 'n', got {b_major!r}"
+    b_hp = (torch.randn(num_experts, n, k, dtype=torch.bfloat16, device="cuda") * std).contiguous()
+    qb_flat, sb_2d = to_fn(b_hp.view(num_experts * n, k), sf_vec_size)
+    if b_major == "k":
+        qb = (
+            qb_flat.view(num_experts, n, k).contiguous().permute(1, 2, 0)
+        )  # (n, k, l) stride (k, 1, n*k)
+    else:
+        qb = (
+            qb_flat.view(num_experts, n, k).transpose(1, 2).contiguous().permute(2, 1, 0)
+        )  # (n, k, l) stride (1, n, n*k)
+    sb_2d = sb_2d.view(num_experts, n, sf_k)
+    b_sc_contig = pack_scale_2d_to_blocked_contig(sb_2d)
+    b_ref = qb_flat.float().view(num_experts, n, k) * sb_2d.float().repeat_interleave(
+        sf_vec_size, dim=-1
+    )
+
+    cu_seqlens_m = torch.tensor(
+        [0] + list(itertools.accumulate(seqlens_m)), dtype=torch.int32, device="cuda"
+    )
+    return a_ref, b_ref, qa, qb, a_sc_contig, b_sc_contig, cu_seqlens_m
+
+
+def create_blockscaled_varlen_k_operands(
+    num_experts: int,
+    k_per: int,
+    m: int,
+    n: int,
+    sf_vec_size: int,
+    ab_dtype: Type[cutlass.Numeric] = cutlass.Float8E4M3FN,
+    sf_dtype: Type[cutlass.Numeric] = cutlass.Float8E8M0FNU,
+    *,
+    randn_std: Optional[float] = None,
+    seqlens_k: Optional[list] = None,
+):
+    """Generate bf16 randn + quantize for a varlen_k blockscaled GEMM.
+
+    Per-expert `k_i` must be a multiple of `sf_vec_size` (quantization chunk)
+    but NOT necessarily a multiple of `sf_vec_size * 4` (= 128 for MXFP8).
+    The SF buffer uses dQaccum-style K padding: each expert `i`'s scales occupy
+    `ceildiv(k_i, 128) * 128` bytes worth of K at offset
+    `(cu_seqlens_k[i] + i * 128) // 128 * 128` (in source-K units). A and B
+    operand data stay packed and unpadded along K — only their SF buffers pad.
+
+    Returns (a_ref_list, b_ref_list, qa, qb, a_sc_contig, b_sc_contig, cu_seqlens_k):
+      a_ref_list: list of per-expert (m, k_i) fp32 dequantized A.
+      b_ref_list: list of per-expert (n, k_i) fp32 dequantized B.
+      qa:  (m, total_k) K-major fp8 (stride (total_k, 1)).
+      qb:  (n, total_k) K-major fp8 (stride (total_k, 1)).
+      a_sc_contig: (1, rm, total_padded_rk, 512) dQaccum-padded SFA.
+      b_sc_contig: (1, rn, total_padded_rk, 512) dQaccum-padded SFB.
+      cu_seqlens_k: (num_experts+1,) int32.
+    """
+    if not (
+        ab_dtype == cutlass.Float8E4M3FN and sf_dtype == cutlass.Float8E8M0FNU and sf_vec_size == 32
+    ):
+        raise NotImplementedError(
+            f"varlen_k currently only supports MXFP8 (got ab={ab_dtype}, sf={sf_dtype}, "
+            f"vec={sf_vec_size}). FP4 is k-major-only and not wired up."
+        )
+    if seqlens_k is None:
+        seqlens_k = [k_per] * num_experts
+    assert len(seqlens_k) == num_experts, (
+        f"seqlens_k length {len(seqlens_k)} != num_experts {num_experts}"
+    )
+    for i, k_i in enumerate(seqlens_k):
+        assert k_i % sf_vec_size == 0, (
+            f"seqlens_k[{i}]={k_i} must be divisible by sf_vec_size={sf_vec_size}"
+        )
+    total_k = int(sum(seqlens_k))
+    std = randn_std if randn_std is not None else (max(seqlens_k)) ** -0.5
+    sf_k_total = total_k // sf_vec_size
+
+    from .mx_utils import to_mx_compiled
+
+    a_q_list, a_sc_list, a_ref_list = [], [], []
+    b_q_list, b_sc_list, b_ref_list = [], [], []
+    for k_i in seqlens_k:
+        # A slice: (m, k_i) bf16 -> fp8, scales (m, k_i // sf_vec_size).
+        a_hp = (torch.randn(m, k_i, dtype=torch.bfloat16, device="cuda") * std).contiguous()
+        a_q, a_sc = to_mx_compiled(a_hp, sf_vec_size)
+        a_q_list.append(a_q)
+        a_sc_list.append(a_sc)
+        a_ref_list.append(a_q.float() * a_sc.float().repeat_interleave(sf_vec_size, dim=-1))
+
+        b_hp = (torch.randn(n, k_i, dtype=torch.bfloat16, device="cuda") * std).contiguous()
+        b_q, b_sc = to_mx_compiled(b_hp, sf_vec_size)
+        b_q_list.append(b_q)
+        b_sc_list.append(b_sc)
+        b_ref_list.append(b_q.float() * b_sc.float().repeat_interleave(sf_vec_size, dim=-1))
+
+    # Pack operand data along K: (m, total_k), (n, total_k). varlen_k's
+    # ragged TMA descriptors are built for MN-major operands (stride 1 on
+    # M/N), so store M-major A and N-major B.
+    # cat gives K-major; transpose → contiguous → transpose to get M-major.
+    qa = torch.cat(a_q_list, dim=1).t().contiguous().t()  # (m, total_k) stride (1, m)
+    qb = torch.cat(b_q_list, dim=1).t().contiguous().t()  # (n, total_k) stride (1, n)
+    assert qa.stride() == (1, qa.shape[0])
+    assert qb.stride() == (1, qb.shape[0])
+
+    # Pad SFA/SFB per-expert to multiples of 128 source-K (= 4 scales).
+    # offset_tile = cu_seqlens[i] // 128 + i (same formula the kernel uses).
+    # Allocation = ceildiv(total_k, 128) + (L - 1) tiles (tighter than
+    # total_k//128 + L when total_k is a multiple of 128; same otherwise).
+    tile = 128  # sf_vec_size * 4
+    total_padded_rk = (total_k + tile - 1) // tile + (num_experts - 1)
+    total_padded_k = total_padded_rk * tile
+    total_padded_sf_k = total_padded_k // sf_vec_size
+    sa_2d_padded = torch.zeros(m, total_padded_sf_k, dtype=a_sc_list[0].dtype, device="cuda")
+    sb_2d_padded = torch.zeros(n, total_padded_sf_k, dtype=b_sc_list[0].dtype, device="cuda")
+    k_offset = 0
+    for i, k_i in enumerate(seqlens_k):
+        sf_k_i = k_i // sf_vec_size
+        k_offset_padded = (k_offset // tile + i) * tile
+        sf_k_offset_padded = k_offset_padded // sf_vec_size
+        sa_2d_padded[:, sf_k_offset_padded : sf_k_offset_padded + sf_k_i] = a_sc_list[i]
+        sb_2d_padded[:, sf_k_offset_padded : sf_k_offset_padded + sf_k_i] = b_sc_list[i]
+        k_offset += k_i
+
+    a_sc_contig = pack_scale_2d_to_blocked_contig(sa_2d_padded.view(1, m, total_padded_sf_k))
+    b_sc_contig = pack_scale_2d_to_blocked_contig(sb_2d_padded.view(1, n, total_padded_sf_k))
+
+    cu_seqlens_k = torch.tensor(
+        [0] + list(itertools.accumulate(seqlens_k)), dtype=torch.int32, device="cuda"
+    )
+    return a_ref_list, b_ref_list, qa, qb, a_sc_contig, b_sc_contig, cu_seqlens_k
+
+
+def compile_blockscaled_gemm_tvm_ffi(
+    ab_dtype: Type[cutlass.Numeric],
+    sf_dtype: Type[cutlass.Numeric],
+    sf_vec_size: int,
+    d_dtype: Type[cutlass.Numeric],
+    mma_tiler_mn: Tuple[int, int],
+    cluster_shape_mn: Tuple[int, int],
+    mA: torch.Tensor,
+    mB: torch.Tensor,
+    mD: torch.Tensor,
+    mSFA: torch.Tensor,
+    mSFB: torch.Tensor,
+    *,
+    use_clc_persistence: bool = True,
+    varlen_m: bool = False,
+    varlen_k: bool = False,
+) -> Callable:
+    """Compile the SM100 blockscaled GEMM.
+
+    When varlen_m: mA is (total_m, k) K-major, mD is (total_m, n) N-major,
+    mB is (n, k, l); run(...) takes an extra cu_seqlens_m tensor.
+    When varlen_k: mA is (m, total_k), mB is (n, total_k), mD is (m, n, l);
+    run(...) takes an extra cu_seqlens_k tensor.
+    """
+    device_capacity = get_device_capacity(mA.device)
+    if device_capacity[0] not in (10, 11):
+        raise RuntimeError("Blockscaled SM100 GEMM requires SM100/SM110")
+    assert not (varlen_m and varlen_k), "Only one of varlen_m / varlen_k"
+
+    gemm = partial(
+        GemmDefaultSm100,
+        sf_vec_size=sf_vec_size,
+        use_clc_persistence=use_clc_persistence,
+    )(cutlass.Float32, ab_dtype, mma_tiler_mn, (*cluster_shape_mn, 1))
+    compile_epi_args = gemm.EpilogueArguments()
+    scheduler_args = make_scheduler_args(
+        get_max_active_clusters(cluster_shape_mn[0] * cluster_shape_mn[1]),
+        max_swizzle_size=8,
+        tile_count_semaphore=None,
+        batch_idx_permute=None,
+    )
+    stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True)
+
+    from .gemm_tvm_ffi_utils import make_fake_varlen_args
+
+    varlen_args_fake = make_fake_varlen_args(varlen_m, varlen_k, False, None) or VarlenArguments()
+
+    # Fake operand tensors with sym_ints (varlen-aware shapes).
+    if varlen_m:
+        total_m_sym = cute.sym_int()
+        n_sym, k_sym, l_sym = cute.sym_int(), cute.sym_int(), cute.sym_int()
+        # Detect each operand's leading (stride-1) dim so m-major A / n-major B
+        # are accepted for varlen_m (MXFP8 only — fp4 is rejected upstream).
+        fake_mA = fake_tensor(
+            ab_dtype,
+            (total_m_sym, k_sym),
+            leading_dim=_leading_dim_from_stride(mA),
+            divisibility=div_for_dtype(ab_dtype),
+        )
+        fake_mB = fake_tensor(
+            ab_dtype,
+            (n_sym, k_sym, l_sym),
+            leading_dim=_leading_dim_from_stride(mB),
+            divisibility=div_for_dtype(ab_dtype),
+        )
+        fake_mD = fake_tensor(
+            d_dtype,
+            (total_m_sym, n_sym),
+            leading_dim=_leading_dim_from_stride(mD),
+            divisibility=div_for_dtype(d_dtype),
+        )
+    elif varlen_k:
+        total_k_sym = cute.sym_int()
+        m_sym, n_sym, l_sym = cute.sym_int(), cute.sym_int(), cute.sym_int()
+        # varlen_k uses MN-major A/B convention (stride 1 on M/N axis), but
+        # detect from the actual tensor so either layout works.
+        fake_mA = fake_tensor(
+            ab_dtype,
+            (m_sym, total_k_sym),
+            leading_dim=_leading_dim_from_stride(mA),
+            divisibility=div_for_dtype(ab_dtype),
+        )
+        fake_mB = fake_tensor(
+            ab_dtype,
+            (n_sym, total_k_sym),
+            leading_dim=_leading_dim_from_stride(mB),
+            divisibility=div_for_dtype(ab_dtype),
+        )
+        fake_mD = fake_tensor(
+            d_dtype,
+            (m_sym, n_sym, l_sym),
+            leading_dim=_leading_dim_from_stride(mD),
+            divisibility=div_for_dtype(d_dtype),
+        )
+    else:
+        # Detect each operand's leading (stride-1) dim so m-major A / n-major B
+        # are accepted along with the default k-major.
+        fake_mA = _make_fake_compact_tensor(
+            mA.shape, ab_dtype, leading_dim=_leading_dim_from_stride(mA)
+        )
+        fake_mB = _make_fake_compact_tensor(
+            mB.shape, ab_dtype, leading_dim=_leading_dim_from_stride(mB)
+        )
+        fake_mD = _make_fake_compact_tensor(
+            mD.shape, d_dtype, leading_dim=_leading_dim_from_stride(mD)
+        )
+
+    @cute.jit
+    def runner(
+        a: cute.Tensor,
+        b: cute.Tensor,
+        d: cute.Tensor,
+        sfa: cute.Tensor,
+        sfb: cute.Tensor,
+        varlen_args,
+        stream,
+    ):
+        gemm(a, b, d, None, compile_epi_args, scheduler_args, varlen_args, stream, sfa, sfb, None)
+
+    compiled = cute.compile(
+        runner,
+        fake_mA,
+        fake_mB,
+        fake_mD,
+        _make_compile_tensor_like(mSFA, sf_dtype, dynamic_layout=True),
+        _make_compile_tensor_like(mSFB, sf_dtype, dynamic_layout=True),
+        varlen_args_fake,
+        stream,
+        options="--enable-tvm-ffi",
+    )
+
+    if varlen_m or varlen_k:
+
+        def run(a, b, d, sfa, sfb, cu_seqlens):
+            varlen_args = VarlenArguments(
+                mCuSeqlensM=cu_seqlens if varlen_m else None,
+                mCuSeqlensK=cu_seqlens if varlen_k else None,
+            )
+            compiled(a, b, d, sfa, sfb, varlen_args)
+    else:
+
+        def run(a, b, d, sfa, sfb):
+            compiled(a, b, d, sfa, sfb, VarlenArguments())
+
+    return run
+
+
+def blockscaled_gemm_reference(
+    a_ref: torch.Tensor,
+    b_ref: torch.Tensor,
+    sfa_ref: torch.Tensor,
+    sfb_ref: torch.Tensor,
+) -> torch.Tensor:
+    return torch.einsum(
+        "mkl,nkl->mnl",
+        torch.einsum("mkl,mkl->mkl", a_ref, sfa_ref),
+        torch.einsum("nkl,nkl->nkl", b_ref, sfb_ref),
+    )
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/__init__.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f109ea0017461707bffefd148f8d920d99d641bd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/__init__.py
@@ -0,0 +1,236 @@
+# Copyright (c) 2025-2026, Tri Dao.
+"""Persistent kernel-cache + compile-only utilities for QuACK.
+
+Public API
+----------
+
+Persistent ``.o`` cache:
+* :func:`jit_cache` \u2014 decorator that wraps a kernel-compile function with
+  in-memory + persistent ``.o`` caching (see :mod:`quack.cache.jit`).
+* :data:`CACHE_ENABLED`, :data:`CACHE_DIR`, :data:`EXTRA_SOURCE_DIRS` \u2014
+  static-config flags (see "Flag semantics" below).
+* :class:`FileLock`, :func:`get_cache_path`, :class:`CacheInfo` \u2014
+  supporting types.
+
+Compile-only cache warming:
+* :class:`CompileOnlyFakeTensorMode`, :func:`compile_only_mode`,
+  :func:`is_compile_only` \u2014 helpers for populating the cache via
+  :class:`~torch._subclasses.fake_tensor.FakeTensorMode` (no GPU memory)
+  before the real run. See :mod:`quack.cache.compile_only`.
+
+Flag semantics
+--------------
+
+The **compile-only flag is a stack**, backed by a :class:`contextvars.ContextVar`
+counter. There is no module-level boolean to assign to. The only sanctioned
+mutation path is :func:`compile_only_mode` (push on enter, pop on exit, leak-free
+by construction). Reads go through :func:`is_compile_only`, which always
+reflects the live stack depth.
+
+For backward compatibility, *attribute reads* of ``quack.cache.COMPILE_ONLY``
+still work via the module ``__getattr__`` hook and return a live bool on
+each access. This covers patterns like::
+
+    import quack.cache
+    if quack.cache.COMPILE_ONLY: ...        # live read on every access
+
+``from quack.cache import COMPILE_ONLY`` does **NOT** give a live read \u2014
+PEP 562's module ``__getattr__`` fires on attribute *access*, not on import
+binding. ``from ... import COMPILE_ONLY`` snapshots the value once at import
+time; subsequent reads of the local name don't re-enter ``__getattr__``.
+New code should call :func:`is_compile_only` instead.
+
+Direct *writes* (``quack.cache.COMPILE_ONLY = True``) are forbidden \u2014 a
+custom module ``__setattr__`` raises :class:`AttributeError` with a pointer
+to :func:`compile_only_mode`.
+
+Why the change: the old design used a plain module attribute. Two failure
+modes followed:
+
+* Capture-at-import: ``pytestmark = pytest.mark.skipif(quack.cache.COMPILE_ONLY, ...)``
+  reads at decorator-application time. Under xdist worksteal the worker can
+  import the module before the plugin's ``pytest_configure`` flips the flag,
+  so the skip captures ``False`` and never fires. (The :func:`is_compile_only`
+  function call avoids this for code under our control; test-file ``pytestmark``
+  patterns still need the marker introduced in R2.)
+* Leak-on-reset: any caller that did ``COMPILE_ONLY = True; ... finally:
+  COMPILE_ONLY = False`` clobbered the *outer* session value to ``False`` on
+  exit, breaking the plugin's invariant for the rest of the xdist worker.
+  Token-based push/pop on a ``ContextVar`` removes that footgun by design.
+
+Recommended access patterns:
+
+  >>> from quack.cache import is_compile_only, compile_only_mode
+  >>> if is_compile_only(): ...               # live read
+  >>> with compile_only_mode():                # push, auto-pop on exit
+  ...     run_kernels()
+"""
+
+from __future__ import annotations
+
+import contextvars
+import os
+import sys
+import types
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Iterator, List, Optional
+
+# ---------------------------------------------------------------------------
+# Runtime flags. Source of truth.
+#
+# CRITICAL ORDERING: ``CACHE_ENABLED``/``CACHE_DIR``/``EXTRA_SOURCE_DIRS`` and
+# the compile-only ContextVar MUST be defined before the ``from
+# quack.cache.jit import ...`` block below. ``quack/cache/jit.py`` does
+# ``import quack.cache as _state`` at its module top; Python returns the
+# partially-initialized package object, and lookups inside ``jit_cache``'s
+# wrapper rely on these names already existing at that checkpoint.
+# Reordering the imports here, even via an auto-formatter, will break the
+# first kernel compile with ``AttributeError``.
+#
+# The defensive unit tests in ``tests/test_cache.py`` exercise this path
+# end-to-end so a reordering bug surfaces immediately.
+# ---------------------------------------------------------------------------
+
+CACHE_ENABLED: bool = os.getenv("QUACK_CACHE_ENABLED", "1") == "1"
+CACHE_DIR: Optional[str] = os.getenv("QUACK_CACHE_DIR", None)
+_CACHE_DIR_OVERRIDE: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar(
+    "quack_cache_dir_override", default=None
+)
+
+
+@contextmanager
+def cache_dir_override(cache_dir: Optional[str]) -> Iterator[None]:
+    token = _CACHE_DIR_OVERRIDE.set(cache_dir)
+    try:
+        yield
+    finally:
+        _CACHE_DIR_OVERRIDE.reset(token)
+
+
+def get_cache_dir() -> Optional[str]:
+    override = _CACHE_DIR_OVERRIDE.get()
+    return CACHE_DIR if override is None else override
+
+
+# Stack depth for compile-only mode. ``compile_only_mode()`` pushes
+# (depth += 1) on enter and pops (reset to prior token) on exit, so:
+#   * Nested ``with compile_only_mode():`` blocks stay True throughout.
+#   * An exception inside the block still pops correctly (context-manager
+#     finally + ContextVar token semantics).
+#   * No caller can leak ``False`` back to the outer session by accident,
+#     because there is no boolean to assign to \u2014 only a token to reset.
+# Read via :func:`quack.cache.compile_only.is_compile_only`.
+_COMPILE_ONLY_DEPTH: contextvars.ContextVar[int] = contextvars.ContextVar(
+    "quack_compile_only_depth", default=0
+)
+
+#: Downstream projects can append directories here to include their sources
+#: in the cache fingerprint. Must be set before the first jit_cache call.
+EXTRA_SOURCE_DIRS: List[Path] = []
+
+
+# ---------------------------------------------------------------------------
+# Module attribute hooks: live read for legacy ``quack.cache.COMPILE_ONLY``,
+# hard-stop on write to surface migration callers.
+# ---------------------------------------------------------------------------
+
+
+def __getattr__(name: str):
+    """Resolve legacy ``COMPILE_ONLY`` attribute reads to a live boolean.
+
+    Triggers on attribute access \u2014 ``quack.cache.COMPILE_ONLY``, the
+    ``hasattr(quack.cache, "COMPILE_ONLY")`` probe, etc. Returns the current
+    stack depth as a bool. There is no module-level attribute to shadow it
+    (so the hook always wins), and *writes* are intercepted by the custom
+    module ``__setattr__`` installed below.
+
+    Important caveat: ``from quack.cache import COMPILE_ONLY`` performs the
+    attribute lookup *once* at import time and binds the *value* in the
+    importer's namespace; subsequent reads of the local name do NOT re-enter
+    this hook. New code should call :func:`is_compile_only` instead of
+    relying on the legacy ``from`` import for live semantics.
+    """
+    if name == "COMPILE_ONLY":
+        return _COMPILE_ONLY_DEPTH.get() > 0
+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
+class _CacheModule(types.ModuleType):
+    """Custom module class that forbids assignment to ``COMPILE_ONLY``.
+
+    Without this guard, ``quack.cache.COMPILE_ONLY = True`` would place a
+    real attribute in ``__dict__`` and shadow the ``__getattr__`` proxy
+    forever (Python looks in ``__dict__`` before falling through). That's
+    the exact leak mode the ContextVar redesign exists to prevent, so we
+    raise instead of silently breaking the invariant.
+    """
+
+    def __setattr__(self, name: str, value) -> None:
+        if name == "COMPILE_ONLY":
+            raise AttributeError(
+                "quack.cache.COMPILE_ONLY is now a read-only stack-backed flag. "
+                "Use `with quack.cache.compile_only_mode(): ...` to enable it "
+                "for a scope (auto-restores on exit, exception-safe, leak-free). "
+                "See quack/cache/__init__.py docstring for migration notes."
+            )
+        super().__setattr__(name, value)
+
+
+sys.modules[__name__].__class__ = _CacheModule
+
+
+class CompileOnlyStrictError(RuntimeError):
+    """Raised by precompile helpers under ``QUACK_COMPILE_ONLY_STRICT=1``.
+
+    Wraps the underlying exception so the reusable pytest plugin's blanket
+    swallow hooks (which exist to ignore expected FakeTensor-incompatibility
+    errors *after* the kernel has dispatched) can let strict-mode failures
+    surface as real test failures.
+
+    Without this distinction, ``QUACK_COMPILE_ONLY_STRICT=1`` looks like it
+    works (the inner ``try/except`` does re-raise) but the surrounding
+    pytest plugin would force-pass the test anyway, defeating the strict
+    mode entirely.
+    """
+
+
+# ---------------------------------------------------------------------------
+# Public API surface. Imported AFTER the flags are defined.
+# ---------------------------------------------------------------------------
+
+from .jit import (  # noqa: E402
+    EXPORT_FUNC_NAME,
+    LOCK_TIMEOUT,
+    CacheInfo,
+    FileLock,
+    get_cache_path,
+    jit_cache,
+)
+from .compile_only import (  # noqa: E402
+    CompileOnlyFakeTensorMode,
+    compile_only_mode,
+    is_compile_only,
+)
+
+# ``__all__`` advertises the *recommended* public API only. Static-config
+# flags (``CACHE_ENABLED``, ``CACHE_DIR``, ``EXTRA_SOURCE_DIRS``) and the
+# legacy ``COMPILE_ONLY`` live-read proxy are intentionally *not* listed: the
+# recommended patterns for compile-only mode are :func:`is_compile_only`
+# (read) and :func:`compile_only_mode` (push/pop, context-managed).
+__all__ = [
+    # Persistent .o cache.
+    "jit_cache",
+    "CacheInfo",
+    "EXPORT_FUNC_NAME",
+    "LOCK_TIMEOUT",
+    "FileLock",
+    "get_cache_path",
+    "cache_dir_override",
+    "get_cache_dir",
+    # Compile-only cache warming.
+    "CompileOnlyFakeTensorMode",
+    "CompileOnlyStrictError",
+    "compile_only_mode",
+    "is_compile_only",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..50036a90060f0f3c4d20c1bda212382631b345f2
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/__pycache__/compile_only.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/__pycache__/compile_only.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f6315ebd01d483ed47afa91b8ddae9423dbf17d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/__pycache__/compile_only.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/__pycache__/jit.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/__pycache__/jit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..706a7641dd748aa0e0c15004b9ab82bc1861cacd
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/__pycache__/jit.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/compile_only.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/compile_only.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee58f0b717e638aad8eb540b2635e93cb54906e7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/compile_only.py
@@ -0,0 +1,216 @@
+# Copyright (c) 2026, Tri Dao.
+"""Tooling for ``--compile-only`` cache warming.
+
+Background
+----------
+
+Each ``@cute_op``-wrapped QuACK kernel registers a ``register_fake`` that, under
+:data:`quack.cache.COMPILE_ONLY` ``= True`` + ``FakeTensorMode``, invokes the
+underlying body of the op *without* actually launching a kernel. The body's
+call to ``_compile_*`` exports a ``.o`` file to the persistent cache via
+:func:`quack.cache.jit_cache`. Subsequent real runs load the ``.o`` in ~1 ms
+instead of paying a ~500 ms CuTe-DSL compile.
+
+This module exposes a thin context manager and a ``FakeTensorMode`` subclass
+that fix the one rough edge of that workflow: ``aten._local_scalar_dense``
+(which backs ``.item()``, ``.tolist()``, ``int(t)``, ``float(t)``) raises
+``DataDependentOutputException`` under stock ``FakeTensorMode``. Many tests
+shape their inputs with patterns like::
+
+    seq_lens = torch.randint(8192 - 1024, 8192 + 1024, (num_groups,), device=...)
+    total_m = seq_lens.sum().item()
+    A = torch.randn(total_m, k, ...)
+    gemm(A, B, cu_seqlens_m=cu_seqlens_m, ...)
+
+…which bails at ``.item()`` and never reaches the kernel dispatch. The compile
+signature for ``_compile_gemm`` is shape-key-independent for the batch dim
+(it always uses ``cute.sym_int()``), so returning *any* small concrete int
+from ``.item()`` lets the test setup proceed far enough to fire the compile.
+
+Usage
+-----
+
+Driver-script style (warm the cache from a CLI tool)::
+
+    from .cache import compile_only_mode
+    from my_lib import my_kernel
+
+    with compile_only_mode():
+        for shape in shapes_to_warm:
+            A, B = make_inputs(shape)        # FakeTensors
+            my_kernel(A, B)                  # compiles, doesn't launch
+
+Pytest style — use the reusable plugin in your project's ``conftest.py``::
+
+    pytest_plugins = ["quack.testing.pytest_plugin"]
+
+…then run ``pytest --compile-only`` to populate the cache.
+
+Low-level style (only when neither of the above fits) — push the depth
+counter manually::
+
+    import quack.cache
+    from .cache import CompileOnlyFakeTensorMode
+
+    token = quack.cache._COMPILE_ONLY_DEPTH.set(
+        quack.cache._COMPILE_ONLY_DEPTH.get() + 1
+    )
+    fake_mode = CompileOnlyFakeTensorMode()
+    fake_mode.__enter__()
+    try:
+        # ... your code here ...
+    finally:
+        fake_mode.__exit__(None, None, None)
+        quack.cache._COMPILE_ONLY_DEPTH.reset(token)
+
+Direct assignment to ``quack.cache.COMPILE_ONLY`` is **forbidden** — the
+module's custom ``__setattr__`` raises :class:`AttributeError` to prevent
+the old leak-on-reset failure mode. See :mod:`quack.cache` for background.
+"""
+
+from __future__ import annotations
+
+import contextlib
+from typing import Iterator
+
+import torch
+from torch._subclasses.fake_tensor import FakeTensorMode
+from torch.utils._python_dispatch import TorchDispatchMode
+
+
+# Sentinel values returned from intercepted ``.item()`` / ``.tolist()`` /
+# ``int(t)`` / ``float(t)`` calls. They only need to be valid Python scalars
+# of the right kind so test setup that uses them as shape arguments,
+# divisors, or stddev factors keeps working. The compile-key signatures of
+# ``@cute_op``-decorated kernels do not depend on these values — the batch
+# dim is always a ``cute.sym_int()`` in the compile key.
+#
+# Chose ``1`` (not e.g. ``256``) deliberately: any test code that turns out
+# to depend on the concrete returned value should surface as a test-time
+# failure under ``--compile-only``, not silently pass with a quietly-aligned
+# magic number. The remaining usage patterns we surveyed (``total_k /
+# num_groups`` as a stddev scale, ``total_m * 2`` as a buffer size) all
+# behave fine with ``1``.
+_INT_SENTINEL = 1
+_FLOAT_SENTINEL = 1.0
+
+
+class _LocalScalarDenseSentinel(TorchDispatchMode):
+    """Internal: intercept ``aten._local_scalar_dense`` and return a sentinel.
+
+    Implemented as a separate :class:`TorchDispatchMode` rather than as a
+    ``FakeTensorMode`` subclass. Two benefits:
+
+    * Uses the documented ``__torch_dispatch__`` protocol — stable across
+      PyTorch versions — instead of overriding ``FakeTensorMode.dispatch``
+      (an internal method whose signature has shifted in past releases).
+    * Cleanly composes with whatever ``FakeTensorMode`` configuration the
+      user provides (dynamic shapes, ``allow_non_fake_inputs``, etc.); we
+      no longer have to mirror ``FakeTensorMode``'s public surface in a
+      subclass.
+
+    Any op other than ``_local_scalar_dense`` is delegated to the next mode
+    in the dispatch stack via ``func(*args, **kwargs)``, which from inside a
+    ``FakeTensorMode`` context routes naturally to fake dispatch.
+    """
+
+    def __torch_dispatch__(self, func, types, args=(), kwargs=None):
+        kwargs = kwargs or {}
+        if func is torch.ops.aten._local_scalar_dense.default:
+            t = args[0]
+            return _FLOAT_SENTINEL if t.dtype.is_floating_point else _INT_SENTINEL
+        return func(*args, **kwargs)
+
+
+class CompileOnlyFakeTensorMode:
+    """Context manager: stock :class:`FakeTensorMode` + sentinel override.
+
+    The override (:class:`_LocalScalarDenseSentinel`) returns a sentinel value
+    from ``aten._local_scalar_dense`` (the op behind ``.item()``,
+    ``.tolist()``, ``int(t)``, ``float(t)``) so data-dependent test setup
+    proceeds far enough to dispatch the kernel and populate the ``.o`` cache.
+
+    Compile-key signatures don't depend on the sentinel value.
+
+    Forwards ``**fake_kwargs`` to the inner :class:`FakeTensorMode`
+    constructor, so callers that need e.g. ``shape_env=ShapeEnv()`` or
+    ``allow_non_fake_inputs=True`` can pass them through.
+    """
+
+    def __init__(self, **fake_kwargs):
+        self._fake_mode = FakeTensorMode(**fake_kwargs)
+        self._override = _LocalScalarDenseSentinel()
+
+    def __enter__(self):
+        self._fake_mode.__enter__()
+        self._override.__enter__()
+        return self
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        # Exit inner override first, then outer FakeTensorMode (LIFO).
+        self._override.__exit__(exc_type, exc_val, exc_tb)
+        self._fake_mode.__exit__(exc_type, exc_val, exc_tb)
+
+
+@contextlib.contextmanager
+def compile_only_mode() -> Iterator[CompileOnlyFakeTensorMode]:
+    """Enter the QuACK compile-only cache-warming context.
+
+    Inside the ``with`` block:
+
+    * :func:`is_compile_only` returns ``True`` (the depth counter is pushed),
+      so the ``@cute_op`` ``register_fake`` hooks fire the underlying kernel
+      body (which compiles and exports ``.o``) and the launch path no-ops via
+      :func:`quack.cache._noop_kernel`.
+    * A :class:`CompileOnlyFakeTensorMode` is active, so all tensor
+      allocations are fake (no GPU memory) and ``.item()`` &c. return
+      sentinel values instead of raising.
+
+    Yields the active :class:`CompileOnlyFakeTensorMode` so callers can
+    inspect or augment it if needed.
+
+    Nested calls compose correctly: each ``with`` pushes the depth counter
+    one level deeper and pops back to the prior depth on exit, so callers
+    can compose the context inside outer compile-only regions without ever
+    leaking ``False`` back to the outer scope. The token-based push/pop is
+    structurally leak-free: even an exception inside the block pops to the
+    exact prior depth, never to ``0``.
+
+    Example::
+
+        from .cache import compile_only_mode
+
+        with compile_only_mode():
+            for cfg in parametrize_grid():
+                run_kernel(*build_inputs(cfg))   # compiles, doesn't launch
+    """
+    import torch._vendor.quack.cache as _state
+
+    token = _state._COMPILE_ONLY_DEPTH.set(_state._COMPILE_ONLY_DEPTH.get() + 1)
+    fake_mode = CompileOnlyFakeTensorMode()
+    fake_mode.__enter__()
+    try:
+        yield fake_mode
+    finally:
+        fake_mode.__exit__(None, None, None)
+        _state._COMPILE_ONLY_DEPTH.reset(token)
+
+
+def is_compile_only() -> bool:
+    """Return ``True`` if the QuACK compile-only mode is currently active.
+
+    Always returns the live stack depth as a bool; no capture-at-import
+    hazard at any callsite. Prefer this over ``quack.cache.COMPILE_ONLY``
+    in new code:
+
+    * ``quack.cache.COMPILE_ONLY`` attribute reads work via the legacy
+      ``__getattr__`` proxy and *are* live, but rely on PEP 562 module
+      hooks that don't survive ``from quack.cache import COMPILE_ONLY``
+      (that captures the value once at import time).
+    * :func:`is_compile_only` is a regular function call, so it's safe to
+      use anywhere — in decorator arguments, at module top level, inside
+      lazy imports, etc.
+    """
+    import torch._vendor.quack.cache as _state
+
+    return _state._COMPILE_ONLY_DEPTH.get() > 0
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/jit.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/jit.py
new file mode 100644
index 0000000000000000000000000000000000000000..584958c137a2443e877b6e0cb2a4258ec619cf14
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cache/jit.py
@@ -0,0 +1,267 @@
+# Copyright (c) 2025, Wentao Guo, Ted Zadouri, Tri Dao.
+"""Persistent ``.o`` cache for CuTe DSL compiled kernels.
+
+Compiled kernels are exported as object files (``.o``) via ``export_to_c``. On
+subsequent runs the ``.o`` is loaded via tvm_ffi (~1 ms) instead of
+re-generating IR + re-JIT'ing (~500 ms per kernel).
+
+Runtime config (``CACHE_ENABLED``, ``CACHE_DIR``, ``EXTRA_SOURCE_DIRS``) and
+the compile-only depth counter live in :mod:`quack.cache` (the package init).
+The compile-only state is read here via :func:`quack.cache.is_compile_only`
+(a ContextVar-backed live read); see :mod:`quack.cache` for the redesign
+rationale.
+"""
+
+from __future__ import annotations
+
+import fcntl
+import functools
+import hashlib
+import os
+import pickle
+import sys
+import tempfile
+import time
+from collections import namedtuple
+from getpass import getuser
+from pathlib import Path
+
+import cutlass
+import cutlass.cute as cute
+import tvm_ffi
+
+# `quack.cache` (the package itself) holds the mutable runtime flags as a
+# single source of truth; reads happen via attribute access on `_state` so we
+# always see the live value, not a snapshot taken at module import.
+import torch._vendor.quack.cache as _state  # noqa: E402  (intentional partial-import; see __init__.py)
+
+
+EXPORT_FUNC_NAME = "func"
+LOCK_TIMEOUT = 60
+CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"])
+
+
+def _noop_kernel(*args, **kwargs):
+    pass
+
+
+def get_cache_path() -> Path:
+    if (cache_dir_override := _state.get_cache_dir()) is not None:
+        cache_dir = Path(cache_dir_override)
+    else:
+        cache_dir = Path(tempfile.gettempdir()) / getuser() / "torch_vendor_quack_cache"
+    cache_dir.mkdir(parents=True, exist_ok=True)
+    return cache_dir
+
+
+def _hash_source_dir(h, root: Path) -> None:
+    """Hash all Python sources under *root* into *h*."""
+    for src in sorted(root.rglob("*.py")):
+        if not src.is_file():
+            continue
+        h.update(src.relative_to(root).as_posix().encode())
+        content = src.read_bytes()
+        h.update(len(content).to_bytes(8, "little"))
+        h.update(content)
+
+
+@functools.lru_cache(maxsize=1)
+def _compute_source_fingerprint() -> str:
+    """Hash quack + extra source dirs plus runtime ABI stamps into a fingerprint."""
+    h = hashlib.sha256()
+    h.update(f"py{sys.version_info.major}.{sys.version_info.minor}".encode())
+    h.update(f"cutlass={cutlass.__version__}".encode())
+    h.update(f"tvm_ffi={tvm_ffi.__version__}".encode())
+    # Hash the entire `quack` package, not just `quack/cache/`. Resolving via
+    # the top-level package import keeps the fingerprint stable regardless of
+    # where inside the package this file lives.
+    import torch._vendor.quack as _quack
+
+    _hash_source_dir(h, Path(_quack.__file__).resolve().parent)
+    for extra_dir in _state.EXTRA_SOURCE_DIRS:
+        _hash_source_dir(h, Path(extra_dir).resolve())
+    return h.hexdigest()
+
+
+def _key_to_hash(key: tuple) -> str:
+    return hashlib.sha256(pickle.dumps(key)).hexdigest()
+
+
+# ---------------------------------------------------------------------------
+# File locking
+# ---------------------------------------------------------------------------
+
+
+class FileLock:
+    """Advisory file lock using fcntl.flock with timeout."""
+
+    def __init__(self, lock_path: Path, exclusive: bool, timeout: float = 15):
+        self.lock_path = lock_path
+        self.exclusive = exclusive
+        self.timeout = timeout
+        self._fd: int = -1
+
+    def __enter__(self) -> "FileLock":
+        flags = os.O_WRONLY | os.O_CREAT if self.exclusive else os.O_RDONLY | os.O_CREAT
+        lock_type = fcntl.LOCK_EX if self.exclusive else fcntl.LOCK_SH
+        self._fd = os.open(str(self.lock_path), flags)
+        deadline = time.monotonic() + self.timeout
+        while time.monotonic() < deadline:
+            try:
+                fcntl.flock(self._fd, lock_type | fcntl.LOCK_NB)
+                return self
+            except OSError:
+                time.sleep(0.1)
+        os.close(self._fd)
+        self._fd = -1
+        raise RuntimeError(f"Timed out waiting for lock: {self.lock_path}")
+
+    def __exit__(self, *exc) -> None:
+        if self._fd >= 0:
+            fcntl.flock(self._fd, fcntl.LOCK_UN)
+            os.close(self._fd)
+            self._fd = -1
+
+
+# ---------------------------------------------------------------------------
+# JIT cache decorator
+# ---------------------------------------------------------------------------
+
+
+def jit_cache(fn):
+    """Decorator that caches compiled CuTe DSL kernels in-memory and on disk.
+
+    The decorated function should return a compiled kernel (i.e. call cute.compile).
+    The disk cache key is (fn.__qualname__, *args, **sorted_kwargs).
+
+    Concurrency model
+    -----------------
+    The disk side uses a per-key ``{sha}.lock`` file (advisory ``flock``):
+
+    * **Fast path (warm cache).** If the ``.o`` file already exists, we take a
+      shared lock just long enough to ``load_module`` it. Many readers can
+      proceed concurrently.
+    * **Slow path (cold cache).** The actual ``fn(*args, **kwargs)`` compile
+      runs *under* the exclusive lock. This serializes redundant compilations
+      of the same key across xdist workers / processes: if N processes race
+      on a cold key, only one calls ``cute.compile``; the rest wait for the
+      lock, see the ``.o`` appear, and load it. (Previously the compile ran
+      *between* the shared-lock check and the exclusive-lock export, so all
+      N processes wasted CPU compiling the same key in parallel — wall time
+      was unchanged but compile-CPU pressure scaled with concurrency, which
+      starved other compiles when many keys were cold at once.)
+
+    The lock is per-key, so distinct keys never contend with each other.
+    """
+    cache = {}
+    hits = 0
+    misses = 0
+
+    @functools.wraps(fn)
+    def wrapper(*args, **kwargs):
+        nonlocal hits, misses
+        cache_key = args + tuple(sorted(kwargs.items())) if kwargs else args
+
+        # Snapshot mutable state once per call so a concurrent flip of
+        # ``_state.CACHE_ENABLED`` mid-call can't desync the disk-path branch.
+        # Sampling ``is_compile_only()`` once per call keeps the wrapper's
+        # in-memory-hit / disk-hit / compile / store branches consistent under
+        # async task switching (each ``asyncio.Task`` runs in its own copy of
+        # the parent's ``contextvars.Context``, but a single coroutine could
+        # otherwise observe both states if ``await`` landed between the in-mem
+        # check and the disk-hit branch). Note: ``ContextVar`` is per-thread,
+        # so a helper *thread* spawned inside ``compile_only_mode()`` will not
+        # observe ``True`` — a behavioral change vs. the old module-attribute
+        # design that the project's single-threaded ``_compile_worker`` and
+        # pytest workflows are unaffected by, but worth recording for future
+        # callers that might spawn worker threads inside compile-only.
+        enabled = _state.CACHE_ENABLED
+        compile_only = _state.is_compile_only()
+
+        # 1. In-memory hit. Same process already compiled or loaded this key.
+        if cache_key in cache:
+            hits += 1
+            return _noop_kernel if compile_only else cache[cache_key]
+
+        # 2. Cache disabled: pure in-process compile, no disk side effects.
+        if not enabled:
+            misses += 1
+            compiled_fn = fn(*args, **kwargs)
+            cache[cache_key] = compiled_fn
+            return _noop_kernel if compile_only else compiled_fn
+
+        sha = _key_to_hash((fn.__qualname__,) + cache_key)
+        cache_path = get_cache_path() / _compute_source_fingerprint()
+        cache_path.mkdir(parents=True, exist_ok=True)
+        o_path = cache_path / f"{sha}.o"
+        lock_path = cache_path / f"{sha}.lock"
+
+        def _load_cached() -> object:
+            """Load the .o into a callable; caller guarantees existence."""
+            m = cute.runtime.load_module(str(o_path), enable_tvm_ffi=True)
+            return m[EXPORT_FUNC_NAME]
+
+        # 3. Fast path: optimistic existence check, then shared-lock load.
+        #    The unlocked ``.exists()`` is a no-cost short-circuit for warm
+        #    caches; the shared lock guards against reading a partial file
+        #    while a concurrent writer holds the exclusive lock.
+        if o_path.exists():
+            try:
+                with FileLock(lock_path, exclusive=False, timeout=LOCK_TIMEOUT):
+                    if o_path.exists():
+                        loaded = _load_cached()
+                        cache[cache_key] = loaded
+                        hits += 1
+                        return _noop_kernel if compile_only else loaded
+            except RuntimeError:
+                pass  # lock timeout; fall through to slow path
+
+        # 4. Slow path: take EXCLUSIVE lock and compile under it. The recheck
+        #    inside the lock catches the race where another process compiled
+        #    while we were waiting; in that case we just load and return
+        #    without duplicating the compile.
+        try:
+            with FileLock(lock_path, exclusive=True, timeout=LOCK_TIMEOUT):
+                if o_path.exists():
+                    loaded = _load_cached()
+                    cache[cache_key] = loaded
+                    hits += 1
+                    return _noop_kernel if compile_only else loaded
+
+                misses += 1
+                compiled_fn = fn(*args, **kwargs)
+                try:
+                    compiled_fn.export_to_c(
+                        object_file_path=str(o_path),
+                        function_name=EXPORT_FUNC_NAME,
+                    )
+                except Exception as e:
+                    print(f"torch._vendor.quack cache: export failed for key {sha}: {e}")
+                cache[cache_key] = compiled_fn
+                return _noop_kernel if compile_only else compiled_fn
+        except RuntimeError as e:
+            # Lock acquisition timed out (heavy contention or stuck holder).
+            # Fall back to in-process compile, no disk write. Better to do
+            # the work twice than to fail the test.
+            print(
+                f"torch._vendor.quack cache: lock timeout for key {sha}: {e}; "
+                f"falling back to in-process compile without disk cache"
+            )
+            misses += 1
+            compiled_fn = fn(*args, **kwargs)
+            cache[cache_key] = compiled_fn
+            return _noop_kernel if compile_only else compiled_fn
+
+    def cache_clear():
+        nonlocal hits, misses
+        cache.clear()
+        hits = 0
+        misses = 0
+
+    def cache_info():
+        return CacheInfo(hits=hits, misses=misses, maxsize=None, currsize=len(cache))
+
+    wrapper.cache = cache
+    wrapper.cache_clear = cache_clear
+    wrapper.cache_info = cache_info
+    return wrapper
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/compile_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/compile_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4375594669c8f12d6a79d8878316271cb819568a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/compile_utils.py
@@ -0,0 +1,19 @@
+# Copyright (c) 2025, Wentao Guo, Ted Zadouri, Tri Dao.
+
+from typing import Optional
+
+import cutlass.cute as cute
+
+
+def make_fake_tensor(dtype, shape, divisibility=1, leading_dim=-1) -> Optional[cute.Tensor]:
+    if leading_dim < 0:
+        leading_dim = len(shape) + leading_dim
+    if dtype is None:
+        return None
+    stride = tuple(
+        cute.sym_int64(divisibility=divisibility) if i != leading_dim else 1
+        for i in range(len(shape))
+    )
+    return cute.runtime.make_fake_tensor(
+        dtype, shape, stride=stride, assumed_align=divisibility * dtype.width // 8
+    )
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/copy_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/copy_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e16511944c530d11664a0a9f246cd206dc855252
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/copy_utils.py
@@ -0,0 +1,1239 @@
+# Copyright (c) 2025-2026, QuACK team.
+
+from typing import Optional, Type, Tuple, Callable, Sequence
+from functools import partial
+
+import cutlass
+import cutlass.cute as cute
+
+from cutlass import Int32, Int16, Boolean, const_expr
+from cutlass.base_dsl.arch import Arch
+from cutlass.cute.nvgpu import cpasync, tcgen05, warp
+from cutlass.cute.nvgpu.tcgen05.mma import CtaGroup  # noqa
+from cutlass.cutlass_dsl import dsl_user_op
+import cutlass.pipeline
+from cutlass._mlir.dialects import llvm
+from cutlass._mlir import ir
+from cutlass._mlir.dialects import cute_nvgpu as _cute_nvgpu_ir
+
+from . import layout_utils
+from .utils import make_vector
+
+
+Sm100MmaPeerBitMask = 0xFEFFFFFF
+
+
+@dsl_user_op
+def cvt_copy(
+    tiled_copy: cute.TiledCopy,
+    src: cute.Tensor,
+    dst: cute.Tensor,
+    *,
+    pred: Optional[cute.Tensor] = None,
+    retile: bool = False,
+    loc=None,
+    ip=None,
+    **kwargs,
+) -> None:
+    assert isinstance(src.iterator, cute.Pointer) and src.memspace == cute.AddressSpace.rmem
+    if const_expr(src.element_type != dst.element_type):
+        src_cvt = cute.make_rmem_tensor_like(src, dst.element_type)
+        src_cvt.store(src.load().to(dst.element_type))
+        src = src_cvt
+    if const_expr(retile):
+        src = tiled_copy.retile(src)
+    cute.copy(tiled_copy, src, dst, pred=pred, loc=loc, ip=ip, **kwargs)
+
+
+@dsl_user_op
+def sr_cvt_copy(
+    tiled_copy: cute.TiledCopy,
+    src: cute.Tensor,
+    dst: cute.Tensor,
+    seed: Int32,
+    tidx: Int32,
+    *,
+    loc=None,
+    ip=None,
+) -> None:
+    """Like cvt_copy but uses stochastic rounding for FP32 -> BF16 conversion."""
+    assert isinstance(src.iterator, cute.Pointer) and src.memspace == cute.AddressSpace.rmem
+    from .rounding import convert_f32_to_bf16_sr
+    from cutlass.cute.tensor import TensorSSA
+
+    src_cvt = cute.make_rmem_tensor_like(src, dst.element_type)
+    src_vec = src.load()
+    raw_vec = convert_f32_to_bf16_sr(src_vec, seed, tidx, loc=loc, ip=ip)
+    src_cvt.store(TensorSSA(raw_vec, src_vec.shape, dst.element_type))
+    src = src_cvt
+    cute.copy(tiled_copy, src, dst, loc=loc, ip=ip)
+
+
+@dsl_user_op
+def load_s2r(src: cute.Tensor, *, loc=None, ip=None) -> cute.Tensor:
+    dst = cute.make_rmem_tensor_like(src, src.element_type, loc=loc, ip=ip)
+    cute.autovec_copy(src, dst, loc=loc, ip=ip)
+    return dst
+
+
+@dsl_user_op
+def contiguous(src: cute.Tensor, *, loc=None, ip=None) -> cute.Tensor:
+    dst = cute.make_rmem_tensor(src.shape, src.element_type, loc=loc, ip=ip)
+    cute.autovec_copy(src, dst, loc=loc, ip=ip)
+    return dst
+
+
+@dsl_user_op
+def load_s2r_retile(
+    tiled_copy: cute.TiledCopy,
+    src: cute.Tensor,
+    dst_shape: cute.Tensor | cute.Shape,
+    *,
+    loc=None,
+    ip=None,
+) -> cute.Tensor:
+    # Will also accept dst_shape being a tensor, in which case we write into that tensor
+    if const_expr(not isinstance(dst_shape, cute.Tensor)):
+        dst = cute.make_rmem_tensor(dst_shape, src.element_type, loc=loc, ip=ip)
+    else:
+        dst = dst_shape
+    cute.copy(tiled_copy, src, tiled_copy.retile(dst), loc=loc, ip=ip)
+    return dst
+
+
+@dsl_user_op
+def load_t2r(
+    thr_copy: cute.ThrCopy, shape: cute.Shape, src: cute.Tensor, *, loc=None, ip=None
+) -> cute.Tensor:
+    cDst = cute.make_identity_tensor(shape)
+    dst = cute.make_rmem_tensor(thr_copy.partition_D(cDst).shape, src.element_type, loc=loc, ip=ip)
+    cute.copy(thr_copy, src, dst, loc=loc, ip=ip)
+    return dst
+
+
+@dsl_user_op
+def get_copy_atom(
+    dtype: Type[cutlass.Numeric], num_copy_elems: int, is_async: bool = False, *, loc=None, ip=None
+) -> cute.CopyAtom:
+    num_copy_bits = const_expr(min(128, num_copy_elems * dtype.width))
+    copy_op = cpasync.CopyG2SOp() if is_async else cute.nvgpu.CopyUniversalOp()
+    return cute.make_copy_atom(copy_op, dtype, num_bits_per_copy=num_copy_bits)
+
+
+@dsl_user_op
+def copy(
+    src: cute.Tensor,
+    dst: cute.Tensor,
+    *,
+    pred: Optional[cute.Tensor] = None,
+    is_async: bool = False,
+    loc=None,
+    ip=None,
+    **kwargs,
+) -> None:
+    num_copy_elems = src.shape[0][0]
+    copy_atom = get_copy_atom(src.element_type, num_copy_elems, is_async)
+    cute.copy(copy_atom, src, dst, pred=pred, loc=loc, ip=ip, **kwargs)
+
+
+def tiled_copy_1d(
+    dtype: Type[cutlass.Numeric], num_threads: int, num_copy_elems: int = 1, is_async: bool = False
+) -> cute.TiledCopy:
+    num_copy_bits = num_copy_elems * dtype.width
+    copy_op = cpasync.CopyG2SOp() if is_async else cute.nvgpu.CopyUniversalOp()
+    copy_atom = cute.make_copy_atom(copy_op, dtype, num_bits_per_copy=num_copy_bits)
+    thr_layout = cute.make_layout(num_threads)
+    val_layout = cute.make_layout(num_copy_elems)
+    return cute.make_tiled_copy_tv(copy_atom, thr_layout, val_layout)
+
+
+def tiled_copy_2d(
+    dtype: Type[cutlass.Numeric],
+    threads_per_row: int,
+    num_threads: int,
+    num_copy_elems: int = 1,
+    is_async: bool = False,
+) -> cute.TiledCopy:
+    num_copy_bits = num_copy_elems * dtype.width
+    copy_op = cpasync.CopyG2SOp() if is_async else cute.nvgpu.CopyUniversalOp()
+    copy_atom = cute.make_copy_atom(copy_op, dtype, num_bits_per_copy=num_copy_bits)
+    assert num_threads % threads_per_row == 0
+    thr_layout = cute.make_ordered_layout(
+        (num_threads // threads_per_row, threads_per_row),
+        order=(1, 0),
+    )
+    val_layout = cute.make_layout((1, num_copy_elems))
+    return cute.make_tiled_copy_tv(copy_atom, thr_layout, val_layout)
+
+
+@cute.jit
+def predicate_k(tAcA: cute.Tensor, limit: Int32) -> cute.Tensor:
+    # Only compute predicates for the "k" dimension. For the mn dimension, we will use "if"
+    tApA = cute.make_rmem_tensor(
+        cute.make_layout(
+            (cute.size(tAcA, mode=[0, 1]), cute.size(tAcA, mode=[1]), cute.size(tAcA, mode=[2])),
+            stride=(cute.size(tAcA, mode=[2]), 0, 1),
+        ),
+        Boolean,
+    )
+    for rest_v in cutlass.range_constexpr(tApA.shape[0]):
+        for rest_k in cutlass.range_constexpr(tApA.shape[2]):
+            tApA[rest_v, 0, rest_k] = cute.elem_less(tAcA[(0, rest_v), 0, rest_k][1], limit)
+    return tApA
+
+
+# def tiled_copy_2d(
+#     dtype: Type[cutlass.Numeric], major_mode_size: int, num_threads: int, is_async: bool = False
+# ) -> cute.TiledCopy:
+#     num_copy_bits = math.gcd(major_mode_size, 128 // dtype.width) * dtype.width
+#     copy_elems = num_copy_bits // dtype.width
+#     copy_op = cpasync.CopyG2SOp() if is_async else cute.nvgpu.CopyUniversalOp()
+#     copy_atom = cute.make_copy_atom(copy_op, dtype, num_bits_per_copy=num_copy_bits)
+#     gmem_threads_per_row = major_mode_size // copy_elems
+#     assert num_threads % gmem_threads_per_row == 0
+#     thr_layout = cute.make_ordered_layout(
+#         (num_threads // gmem_threads_per_row, gmem_threads_per_row),
+#         order=(1, 0),
+#     )
+#     val_layout = cute.make_layout((1, copy_elems))
+#     return cute.make_tiled_copy_tv(copy_atom, thr_layout, val_layout)
+
+
+# Ragged tensor trick for TMA: encodes variable-length sequences into a higher-rank
+# tensor so that TMA's out-of-bounds checking handles sequence boundaries.
+#
+# Given a tensor T with a ragged dimension (variable-length across batches), we create
+# a higher-rank tensor where the ragged dim is replaced with a fixed size `big_int`, and
+# extra dim(s) are appended. When indexing into a specific sequence at (offset, length),
+# `offset_ragged_tensor` computes coordinates such that:
+#   ragged_coord = big_int - length   (OOB check clamps reads past the sequence end)
+#   extra_coord(s) = f(offset, length) (selects the correct memory region)
+#
+# ptr_shift=True: 1-extra-dim approach (adds 1 dim, supports up to 4D input):
+#   Shape:  (*before, big_int, *after, max_int)
+#   Stride: (*original_strides, stride_r)     where stride_r = T.stride[ragged_dim]
+#   Pointer shifted backward by big_int * stride_r elements.
+#   Address for coords (big_int - length) in ragged dim, (offset + length) in extra dim:
+#     addr = (base - big_int * s_r) + (big_int - length) * s_r + (offset + length) * s_r
+#          = base + offset * s_r                                                      [correct]
+#   Works for epilogue TMA store. Does NOT work for TMA load with large big_int
+#   — the shifted pointer must land in physically mapped GPU memory.
+#
+# ptr_shift=False: 2-extra-dim approach (adds 2 dims, supports up to 3D input):
+#   Shape:  (*before, big_int, *after, max_int, max_int)
+#   Stride: (*before_strides, stride_r, *after_strides, 2^34 - stride_r, stride_r)
+#   No pointer shift. Uses 64-bit address wraparound to cancel the ragged offset.
+#   Let W = 2^34 - stride_r. Address for coords (big_int - length) in ragged dim,
+#   big_int in extra dim 0, (offset + length) in extra dim 1:
+#     addr = base + (big_int - length) * s_r + big_int * W + (offset + length) * s_r
+#          = base + big_int * (s_r + W) - length * s_r + (offset + length) * s_r
+#          = base + big_int * 2^34 + offset * s_r
+#   Since big_int = 2^30: big_int * 2^34 = 2^64 ≡ 0 (mod 2^64), so:
+#     addr = base + offset * s_r                                                      [correct]
+#   Works for all TMA paths since the base pointer is never shifted.
+#
+# Ragged tensor was adapted from the implementation from Triton, but here we have an option that
+# only needs 1 extra dimension instead of 2.
+# https://github.com/triton-lang/triton/blob/main/python/triton/tools/ragged_tma.py
+BIG_INT = 2**30
+MAX_INT = 2**31 - 1
+BIG_INT_INV = 2**64 // BIG_INT
+
+
+@dsl_user_op
+def create_ragged_tensor_for_tma(
+    T: cute.Tensor,
+    ragged_dim: int = 0,
+    ptr_shift: bool = False,
+    *,
+    loc=None,
+    ip=None,
+) -> cute.Tensor:
+    rank = cute.rank(T)
+    if ragged_dim < 0:
+        ragged_dim += rank
+    if ptr_shift:
+        assert rank <= 4, "ptr_shift ragged tensor only supports up to 4 dimensions"
+        new_shape = T.shape[:ragged_dim] + (BIG_INT,) + T.shape[ragged_dim + 1 :] + (MAX_INT,)
+        new_stride = T.stride + (T.stride[ragged_dim],)
+        ptr_offset = (None,) * ragged_dim + (-BIG_INT,) + (None,) * (rank - ragged_dim - 1)
+        new_ptr = cute.domain_offset(ptr_offset, T).iterator
+        return cute.make_tensor(new_ptr, cute.make_layout(new_shape, stride=new_stride))
+    else:
+        assert rank <= 3, "non-ptr_shift ragged tensor only supports up to 3 dimensions"
+        stride_r = T.stride[ragged_dim]
+        new_shape = (
+            T.shape[:ragged_dim] + (BIG_INT,) + T.shape[ragged_dim + 1 :] + (MAX_INT, MAX_INT)
+        )
+        new_stride = (
+            T.stride[:ragged_dim]
+            + (stride_r,)
+            + T.stride[ragged_dim + 1 :]
+            + (BIG_INT_INV - stride_r, stride_r)
+        )
+        return cute.make_tensor(T.iterator, cute.make_layout(new_shape, stride=new_stride))
+
+
+@dsl_user_op
+def offset_ragged_tensor(
+    T: cute.Tensor,
+    offset: Int32,
+    length: Int32,
+    ragged_dim: int = 0,
+    ptr_shift: bool = False,
+    *,
+    loc=None,
+    ip=None,
+) -> cute.Tensor:
+    rank = cute.rank(T)
+    if ragged_dim < 0:
+        ragged_dim += rank
+    big_int = cute.size(T, mode=[ragged_dim])
+    offset_val = big_int - length
+    if ptr_shift:
+        # 1-extra-dim: rank = original_rank + 1
+        assert rank >= ragged_dim + 2
+        offset_tuple = (None,) * ragged_dim + (offset_val,) + (None,) * (rank - ragged_dim - 2)
+        index_tuple = (None,) * (rank - 1) + (offset + length,)
+    else:
+        # 2-extra-dim: rank = original_rank + 2, last 2 modes are the wraparound dims
+        assert rank >= ragged_dim + 3
+        offset_tuple = (None,) * ragged_dim + (offset_val,) + (None,) * (rank - ragged_dim - 3)
+        index_tuple = (None,) * (rank - 2) + (big_int, offset + length)
+    return cute.domain_offset(offset_tuple, T[index_tuple])
+
+
+def swizzle_int(ptr_int: Int32, b: int, m: int, s: int) -> Int32:
+    bit_msk = (1 << b) - 1
+    yyy_msk = bit_msk << (m + s)
+    return ptr_int ^ ((ptr_int & yyy_msk) >> s)
+
+
+def swizzle_ptr(ptr: cute.Pointer):
+    swz = ptr.type.swizzle_type
+    ptr_int = swizzle_int(ptr.toint(), swz.num_bits, swz.num_base, swz.num_shift)
+    return cute.make_ptr(ptr.dtype, ptr_int, ptr.memspace, assumed_align=ptr.alignment)
+
+
+def as_position_independent_swizzle_tensor(tensor: cute.Tensor) -> cute.Tensor:
+    outer = tensor.layout
+    width = tensor.element_type.width
+    swizzle_type = tensor.iterator.type.swizzle_type
+    inner = cute.make_swizzle(swizzle_type.num_bits, swizzle_type.num_base, swizzle_type.num_shift)
+    # Need to recast the swizzle from byte (e.g. <3, 4, 3> to element units (e.g. <3, 3, 3> for
+    # for 16 bits and <3, 2, 3> for 32 bits)
+    new_layout = cute.recast_layout(
+        width, 8, cute.make_composed_layout(inner, 0, cute.recast_layout(8, width, outer))
+    )
+    # recast_ptr to remove the pointer swizzle
+    return cute.make_tensor(cute.recast_ptr(tensor.iterator, dtype=tensor.element_type), new_layout)
+
+
+def partition_D_position_independent(thr_copy: cute.ThrCopy, tensor: cute.Tensor) -> cute.Tensor:
+    return cute.make_tensor(
+        swizzle_ptr(thr_copy.partition_D(tensor).iterator),
+        thr_copy.partition_D(as_position_independent_swizzle_tensor(tensor)).layout,
+    )
+
+
+def partition_S_position_independent(thr_copy: cute.ThrCopy, tensor: cute.Tensor) -> cute.Tensor:
+    return cute.make_tensor(
+        swizzle_ptr(thr_copy.partition_S(tensor).iterator),
+        thr_copy.partition_S(as_position_independent_swizzle_tensor(tensor)).layout,
+    )
+
+
+@dsl_user_op
+def sm90_get_smem_load_op(
+    layout_c: cutlass.utils.LayoutEnum,
+    elem_ty_c: Type[cutlass.Numeric],
+    *,
+    loc=None,
+    ip=None,
+) -> cute.CopyAtom:
+    """
+    Selects the largest vectorized smem load atom available subject to constraint of gmem layout.
+
+    Parameters:
+    -----------
+    layout_c : LayoutEnum
+        The layout enum of the output tensor D.
+
+    elem_ty_c : Type[Numeric]
+        The element type for output tensor D.
+
+    Returns:
+    --------
+    Either SmemLoadMatrix or SimtSyncCopy, based on the input parameters.
+    """
+
+    if not isinstance(elem_ty_c, cutlass.cutlass_dsl.NumericMeta):
+        raise TypeError(f"elem_ty_c must be a Numeric, but got {elem_ty_c}")
+    is_m_major = layout_c.is_m_major_c()
+    if elem_ty_c.width == 16:
+        return cute.make_copy_atom(warp.LdMatrix8x8x16bOp(is_m_major, 4), elem_ty_c, loc=loc, ip=ip)
+    else:
+        return cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), elem_ty_c, loc=loc, ip=ip)
+
+
+def get_smem_store_atom(
+    element_type: Type[cute.Numeric],
+    transpose: bool = False,
+    major_mode_size: Optional[int] = None,
+) -> cute.CopyAtom:
+    arch = cutlass.base_dsl.BaseDSL._get_dsl().get_arch_enum()
+    if const_expr(arch < Arch.sm_90 or element_type.width != 16):
+        return cute.make_copy_atom(
+            cute.nvgpu.CopyUniversalOp(),
+            element_type,
+            num_bits_per_copy=(2 if not transpose else 1) * element_type.width,
+        )
+    else:
+        num_matrices = (
+            4
+            if major_mode_size is None or major_mode_size % 16 == 0
+            else (2 if major_mode_size % 8 == 0 else 1)
+        )
+        return cute.make_copy_atom(
+            warp.StMatrix8x8x16bOp(transpose=transpose, num_matrices=num_matrices),
+            element_type,
+        )
+
+
+def get_smem_load_atom(
+    element_type: Type[cute.Numeric],
+    transpose: bool = False,
+    major_mode_size: Optional[int] = None,
+) -> cute.CopyAtom:
+    arch = cutlass.base_dsl.BaseDSL._get_dsl().get_arch_enum()
+    if const_expr(arch < Arch.sm_90 or element_type.width != 16):
+        return cute.make_copy_atom(
+            cute.nvgpu.CopyUniversalOp(),
+            element_type,
+            num_bits_per_copy=(2 if not transpose else 1) * element_type.width,
+        )
+    else:
+        num_matrices = (
+            4
+            if major_mode_size is None or major_mode_size % 16 == 0
+            else (2 if major_mode_size % 8 == 0 else 1)
+        )
+        return cute.make_copy_atom(
+            warp.LdMatrix8x8x16bOp(transpose=transpose, num_matrices=num_matrices),
+            element_type,
+        )
+
+
+def get_smem_store_C(
+    tiled_mma: cute.TiledMma,
+    sC: cute.Tensor,
+    tidx: Int32,
+    transpose: bool = False,
+    position_independent=False,
+    major_mode_size: Optional[int] = None,
+) -> Tuple[Callable, cute.TiledCopy, cute.Tensor]:
+    dtype = sC.element_type
+    copy_atom = get_smem_store_atom(dtype, transpose, major_mode_size=major_mode_size)
+    tiled_copy = cute.make_tiled_copy_C(copy_atom, tiled_mma)
+    thr_copy = tiled_copy.get_slice(tidx)
+    if const_expr(not position_independent):
+        tRS_sC = thr_copy.partition_D(sC)
+    else:
+        tRS_sC = partition_D_position_independent(thr_copy, sC)
+
+    def copy_fn(src: cute.Tensor, dst_idx: Optional[Int32] = None, **new_kwargs):
+        dst_tensor = tRS_sC if const_expr(dst_idx is None) else tRS_sC[None, None, None, dst_idx]
+        cvt_copy(tiled_copy, src, dst_tensor, retile=True, **new_kwargs)
+
+    return copy_fn, thr_copy, tRS_sC
+
+
+def get_smem_load_C(
+    tiled_mma: cute.TiledMma,
+    sC: cute.Tensor,
+    tidx: Int32,
+    transpose: bool = False,
+    position_independent=False,
+) -> Tuple[Callable, cute.TiledCopy, cute.Tensor]:
+    dtype = sC.element_type
+    copy_atom = get_smem_load_atom(dtype, transpose)
+    tiled_copy = cute.make_tiled_copy_C(copy_atom, tiled_mma)
+    thr_copy = tiled_copy.get_slice(tidx)
+    if const_expr(not position_independent):
+        tSR_sC = thr_copy.partition_S(sC)
+    else:
+        tSR_sC = partition_S_position_independent(thr_copy, sC)
+    copy_atom_RS = get_smem_store_atom(dtype, transpose)
+    thr_copy_RS = cute.make_tiled_copy_C(copy_atom_RS, tiled_mma).get_slice(tidx)
+    tRS_shape = thr_copy_RS.partition_S(cute.make_identity_tensor(sC.shape[:2])).shape
+
+    def copy_fn(src_idx: Optional[Int32] = None, **new_kwargs):
+        src_tensor = tSR_sC if const_expr(src_idx is None) else tSR_sC[None, None, None, src_idx]
+        return load_s2r_retile(tiled_copy, src_tensor, dst_shape=tRS_shape, **new_kwargs)
+
+    return copy_fn, thr_copy, tSR_sC
+
+
+def epilog_smem_copy_atom(
+    tiled_mma: cute.TiledMma, epi_tile: cute.Shape, transpose: bool = False
+) -> cute.TiledCopy:
+    arch = cutlass.base_dsl.BaseDSL._get_dsl().get_arch_enum()
+    if const_expr(arch < Arch.sm_90):
+        copy_atom_C = cute.make_copy_atom(
+            cute.nvgpu.CopyUniversalOp(),
+            cutlass.Float16,  # this is just to get the right source layout
+            num_bits_per_copy=(2 if not transpose else 1) * cutlass.Float16.width,
+        )
+    else:
+        copy_atom_C = cute.make_copy_atom(
+            warp.StMatrix8x8x16bOp(transpose, num_matrices=4 if epi_tile[1] % 16 == 0 else 2),
+            cutlass.Float16,  # this is just to get the right source layout
+        )
+    tiled_copy_C_atom = cute.make_tiled_copy_C_atom(copy_atom_C, tiled_mma)
+    return tiled_copy_C_atom
+
+
+def get_smem_store_epi(
+    tiled_mma: cute.TiledMma,
+    epi_tile: cute.Shape,
+    sC: Optional[cute.Tensor],
+    tidx: Int32,
+    transpose: bool = False,
+    position_independent=False,
+) -> Tuple[Callable, cute.TiledCopy, cute.Tensor, cute.Tensor]:
+    dtype = sC.element_type if const_expr(sC is not None) else cutlass.Float16
+    copy_atom = get_smem_store_atom(dtype, transpose)
+    tiled_copy_C_atom = epilog_smem_copy_atom(tiled_mma, epi_tile)
+    tiled_copy = cute.make_tiled_copy_S(copy_atom, tiled_copy_C_atom)
+    thr_copy = tiled_copy.get_slice(tidx)
+    tRS_sC = None
+    if const_expr(sC is not None):
+        if const_expr(not position_independent):
+            tRS_sC = thr_copy.partition_D(sC)
+        else:
+            tRS_sC = partition_D_position_independent(thr_copy, sC)
+    sC_shape = sC.shape[:2] if sC is not None else epi_tile
+    # (R2S, R2S_M, R2S_N, PIPE_C)
+    tRS_rC_shape = thr_copy.partition_S(cute.make_identity_tensor(sC_shape)).shape
+    tRS_rC = cute.make_rmem_tensor(tRS_rC_shape, tiled_mma.op.acc_dtype)
+
+    def copy_fn(src: cute.Tensor, dst_idx: Int32, **new_kwargs):
+        cvt_copy(tiled_copy, src, tRS_sC[None, None, None, dst_idx], **new_kwargs)
+
+    return copy_fn if const_expr(sC is not None) else None, thr_copy, tRS_sC, tRS_rC
+
+
+def get_smem_store_A(
+    tiled_mma: cute.TiledMma, sA: cute.Tensor, tidx: Int32, position_independent=False
+) -> Tuple[Callable, cute.TiledCopy, cute.Tensor]:
+    dtype = sA.element_type
+    transpose = tiled_mma.op.a_major_mode == cute.nvgpu.OperandMajorMode.MN
+    copy_atom = get_smem_store_atom(dtype, transpose)
+    tiled_copy = cute.make_tiled_copy_A(copy_atom, tiled_mma)
+    thr_copy = tiled_copy.get_slice(tidx)
+    if const_expr(not position_independent):
+        tRS_sA = thr_copy.partition_D(sA)
+    else:
+        tRS_sA = partition_D_position_independent(thr_copy, sA)
+
+    def copy_fn(src: cute.Tensor, dst_idx: Int32, **new_kwargs):
+        cvt_copy(tiled_copy, src, tRS_sA[None, None, None, dst_idx], retile=True, **new_kwargs)
+
+    return copy_fn, thr_copy, tRS_sA
+
+
+def get_smem_load_A(
+    tiled_mma: cute.TiledMma,
+    sA: cute.Tensor,
+    tidx: Int32,
+    with_dst_tensor: bool = False,
+    position_independent=False,
+) -> Tuple[Callable, cute.TiledCopy, cute.Tensor]:
+    dtype = sA.element_type
+    transpose = tiled_mma.op.a_major_mode == cute.nvgpu.OperandMajorMode.MN
+    copy_atom = get_smem_load_atom(dtype, transpose)
+    tiled_copy = cute.make_tiled_copy_A(copy_atom, tiled_mma)
+    thr_copy = tiled_copy.get_slice(tidx)
+    if const_expr(not position_independent):
+        tSR_sA = thr_copy.partition_S(sA)
+    else:
+        tSR_sA = partition_S_position_independent(thr_copy, sA)
+    tRS_shape = tiled_mma.partition_shape_A(sA.shape[:2])
+
+    def copy_fn(src_idx: Int32, **new_kwargs):
+        return load_s2r_retile(
+            tiled_copy, tSR_sA[None, None, None, src_idx], dst_shape=tRS_shape, **new_kwargs
+        )
+
+    def copy_fn_w_dst_tensor(src_idx: Int32, dst: cute.Tensor, **new_kwargs):
+        return load_s2r_retile(tiled_copy, tSR_sA[None, None, None, src_idx], dst, **new_kwargs)
+
+    return copy_fn if not with_dst_tensor else copy_fn_w_dst_tensor, thr_copy, tSR_sA
+
+
+@dsl_user_op
+def cpasync_reduce_bulk_add_f32(
+    smem_ptr: cute.Pointer,
+    gmem_ptr: cute.Pointer,
+    store_bytes: int | Int32,
+    *,
+    loc=None,
+    ip=None,
+):
+    smem_ptr_i32 = smem_ptr.toint(loc=loc, ip=ip).ir_value()
+    # cache_hint = cutlass.Int64(0x14F0000000000000)  # EVICT_LAST
+    llvm.inline_asm(
+        None,
+        [gmem_ptr.llvm_ptr, smem_ptr_i32, Int32(store_bytes).ir_value()],
+        "cp.reduce.async.bulk.global.shared::cta.bulk_group.add.f32 [$0], [$1], $2;",
+        "l,r,r",
+        # [gmem_ptr.llvm_ptr, smem_ptr_i32, Int32(store_bytes).ir_value(), cache_hint.ir_value()],
+        # "cp.reduce.async.bulk.global.shared::cta.bulk_group.L2::cache_hint.add.f32 [$0], [$1], $2, $3;",
+        # "l,r,r,l",
+        has_side_effects=True,
+        is_align_stack=False,
+    )
+
+
+@dsl_user_op
+def get_tma_desc_addr(tma_atom: cute.CopyAtom, *, loc=None, ip=None) -> cute.Pointer:
+    """
+    Get the address of the TMA descriptor embedded in a TMA Copy Atom.
+
+    Extracts the constant memory address of the TMA descriptor for use with
+    custom PTX instructions.
+
+    :param tma_atom: TMA Copy Atom from make_tiled_tma_atom
+    :return: Pointer to TMA descriptor in constant memory
+
+    Example:
+        >>> desc_ptr = get_tma_descriptor_address(tma_atom)
+    """
+    exec_atom = _cute_nvgpu_ir.atom_make_exec_tma(tma_atom._trait.value, loc=loc, ip=ip)
+    tma_desc_ptr_type = ir.Type.parse(
+        "!cute.ptr>"
+    )
+    return _cute_nvgpu_ir.get_tma_desc_addr(tma_desc_ptr_type, exec_atom, loc=loc, ip=ip)
+
+
+@dsl_user_op
+def tma_gather4_load(
+    tma_desc_ptr: cute.Pointer,
+    dst_smem_ptr: cute.Pointer,
+    mbarrier_ptr: cute.Pointer,
+    col_idx: Int32,
+    row_indices: Sequence[Int32],
+    *,
+    num_cta: int = 1,
+    multicast_mask=None,
+    loc=None,
+    ip=None,
+) -> None:
+    """
+    Perform TMA gather4 load from global memory to shared memory.
+
+    Issues PTX instruction:
+    cp.async.bulk.tensor.2d.shared::cta.global.tile::gather4.mbarrier::complete_tx::bytes
+        [dstMem], [tensorMap, {col_idx, row0, row1, row2, row3}], [smem_bar];
+
+    This loads 4 rows (specified by row_indices) from a 2D tensor at the given
+    column index into shared memory, using the TMA descriptor.
+
+    :param tma_desc_ptr: Pointer to TMA descriptor in constant memory (128-byte aligned)
+    :type tma_desc_ptr:  Pointer
+    :param dst_smem_ptr: Destination address in shared memory
+    :type dst_smem_ptr:  Pointer
+    :param mbarrier_ptr: Pointer to mbarrier in shared memory for completion tracking
+    :type mbarrier_ptr:  Pointer
+    :param col_idx:      Column index
+    :type col_idx:       Int32
+    :param row_indices:  Sequence of exactly 4 row indices
+    :type row_indices:   Sequence[Int32]
+    :param num_cta:      Number of CTAs participating (default: 1)
+    :type num_cta:       int
+    :param multicast_mask: Optional multicast mask
+    :type multicast_mask: Int16
+
+    Requirements:
+        - row_indices must contain exactly 4 elements
+        - Compute capability >= SM_100 (Blackwell)
+        - TMA descriptor must be properly initialized for 2D tensor
+
+    Example:
+        >>> from cutlass.cute.nvgpu import cpasync
+        >>> from cutlass.cute import core
+        >>>
+        >>> # Create TMA descriptor
+        >>> tma_atom, tma_tensor = cpasync.make_tiled_tma_atom(...)
+        >>> tma_desc_ptr = get_tma_descriptor_address(tma_atom)
+        >>>
+        >>> # Compute indices (typically from kernel logic)
+        >>> col_idx = core.get(...) or 5  # Int32 value
+        >>> row_indices = [core.get(...) for _ in range(4)]  # 4 Int32 values
+        >>>
+        >>> # Gather 4 rows at computed column
+        >>> tma_gather4_load(
+        ...     tma_desc_ptr=tma_desc_ptr,
+        ...     dst_smem_ptr=smem_ptr,
+        ...     mbarrier_ptr=barrier_ptr,
+        ...     col_idx=col_idx,
+        ...     row_indices=row_indices
+        ... )
+    """
+    if len(row_indices) != 4:
+        raise ValueError(f"gather4 requires exactly 4 row indices, got {len(row_indices)}")
+    col_val = Int32(col_idx).ir_value()
+    row_vals = [Int32(row_idx).ir_value() for row_idx in row_indices]
+    # Convert pointers to integer addresses
+    desc_addr = tma_desc_ptr.toint(loc=loc, ip=ip).ir_value()
+    dst_addr = dst_smem_ptr.toint(loc=loc, ip=ip).ir_value()
+    mbar_addr = mbarrier_ptr.toint(loc=loc, ip=ip)
+    if num_cta > 1:
+        # Executed by both CTAs. Set peer bit to 0 so that the
+        # transaction bytes will update CTA0's barrier.
+        mbar_addr = mbar_addr & Sm100MmaPeerBitMask
+    mbar_addr = mbar_addr.ir_value()
+    # Handle multicast_mask - may already be ir.Value or Python int
+    multicast_mask_val = None
+    if multicast_mask is not None:
+        multicast_mask_val = Int16(multicast_mask).ir_value()
+    assert multicast_mask_val is None, "multicast is not supported yet"
+    # Emit inline PTX for TMA gather4
+    # PTX: cp.async.bulk.tensor.2d.shared::cta.global.tile::gather4.mbarrier::complete_tx::bytes
+    #      [dstMem], [tensorMap, {col, row0, row1, row2, row3}], [smem_bar];
+    ptx = (
+        f"cp.async.bulk.tensor.2d.shared::cta.global.tile::gather4.mbarrier::complete_tx::bytes.cta_group::{num_cta} "
+        "[$0], [$1, {$2, $3, $4, $5, $6}], [$7];"
+    )
+
+    llvm.inline_asm(
+        None,
+        [
+            dst_addr,
+            desc_addr,
+            col_val,
+            row_vals[0],
+            row_vals[1],
+            row_vals[2],
+            row_vals[3],
+            mbar_addr,
+        ],
+        ptx,
+        "r,l,r,r,r,r,r,r",  # constraints: register, long, 6x register
+        has_side_effects=True,
+        is_align_stack=False,
+        loc=loc,
+        ip=ip,
+    )
+
+
+def cpasync_bulk_get_copy_fn(
+    src_tensor: cute.Tensor,
+    dst_tensor: cute.Tensor,
+    single_stage: bool = False,
+    **kwargs,
+) -> Callable:
+    group_rank_src = const_expr(cute.rank(src_tensor) - (1 if not single_stage else 0))
+    group_rank_dst = const_expr(cute.rank(dst_tensor) - (1 if not single_stage else 0))
+    # ((atom_v, rest_v), STAGE), ((atom_v, rest_v), RestK)
+    src = cute.group_modes(src_tensor, 0, group_rank_src)
+    dst = cute.group_modes(dst_tensor, 0, group_rank_dst)
+
+    def copy_bulk(src_idx, dst_idx, tma_bar_ptr: cute.Pointer, **new_kwargs):
+        atom = cute.make_copy_atom(cpasync.CopyBulkG2SOp(), src.element_type)
+        with cute.arch.elect_one():
+            cute.copy(
+                atom,
+                src[None, src_idx],
+                dst[None, dst_idx],
+                mbar_ptr=tma_bar_ptr,
+                **new_kwargs,
+                **kwargs,
+            )
+
+    def copy_bulk_single_stage(tma_bar_ptr: cute.Pointer, **new_kwargs):
+        atom = cute.make_copy_atom(cpasync.CopyBulkG2SOp(), src.element_type)
+        with cute.arch.elect_one():
+            cute.copy(atom, src, dst, mbar_ptr=tma_bar_ptr, **new_kwargs, **kwargs)
+
+    return copy_bulk if const_expr(not single_stage) else copy_bulk_single_stage
+
+
+@dsl_user_op
+def tma_get_copy_fn(
+    atom: cute.CopyAtom,
+    cta_coord: cute.Coord,
+    cta_layout: cute.Layout,
+    src_tensor: cute.Tensor,
+    dst_tensor: cute.Tensor,
+    filter_zeros: bool = False,
+    single_stage: bool = False,
+    *,
+    loc=None,
+    ip=None,
+    **kwargs,
+) -> Callable:
+    src_is_smem = const_expr(
+        isinstance(src_tensor.iterator, cute.Pointer)
+        and src_tensor.memspace == cute.AddressSpace.smem
+    )
+    smem_tensor, gmem_tensor = (src_tensor, dst_tensor) if src_is_smem else (dst_tensor, src_tensor)
+    group_rank_smem = const_expr(cute.rank(smem_tensor) - (1 if not single_stage else 0))
+    group_rank_gmem = const_expr(cute.rank(gmem_tensor) - (1 if not single_stage else 0))
+    # ((atom_v, rest_v), STAGE), ((atom_v, rest_v), RestK)
+    s, g = cpasync.tma_partition(
+        atom,
+        cta_coord,
+        cta_layout,
+        cute.group_modes(smem_tensor, 0, group_rank_smem),
+        cute.group_modes(gmem_tensor, 0, group_rank_gmem),
+        loc=loc,
+        ip=ip,
+    )
+    if const_expr(filter_zeros):
+        s = cute.filter_zeros(s)
+        g = cute.filter_zeros(g)
+    src, dst = (s, g) if src_is_smem else (g, s)
+
+    @dsl_user_op
+    def copy_tma(src_idx, dst_idx, *, loc=None, ip=None, **new_kwargs):
+        cute.copy(
+            atom, src[None, src_idx], dst[None, dst_idx], **new_kwargs, **kwargs, loc=loc, ip=ip
+        )
+
+    @dsl_user_op
+    def copy_tma_single_stage(*, loc=None, ip=None, **new_kwargs):
+        cute.copy(atom, src, dst, **new_kwargs, **kwargs, loc=loc, ip=ip)
+
+    return (copy_tma if const_expr(not single_stage) else copy_tma_single_stage), s, g
+
+
+def s2t_get_copy_fn(
+    src_tensor: cute.Tensor,
+    dst_tensor: cute.Tensor,
+    cta_group: tcgen05.CtaGroup,
+) -> Callable:
+    """
+    Make tiledCopy for smem to tmem load, then return a copy function over stages.
+
+    :param src_tensor: The source tensor in smem
+    :param dst_tensor: The destination tensor in tmem
+    """
+    assert src_tensor.element_type == dst_tensor.element_type
+    # (MMA, MMA_MN, MMA_K, STAGE)
+    src_compact = cute.filter_zeros(src_tensor)
+    # (MMA, MMA_MN, MMA_K)
+    dst_compact = cute.filter_zeros(dst_tensor)
+    # Make S2T CopyAtom and tiledCopy.
+    copy_atom = cute.make_copy_atom(tcgen05.Cp4x32x128bOp(cta_group), dst_tensor.element_type)
+    tiled_copy = tcgen05.make_s2t_copy(copy_atom, dst_compact)
+    thr_copy = tiled_copy.get_slice(0)
+    # ((ATOM_V, REST_V), Rest_Tiler, MMA_MN, MMA_K, STAGE)
+    src_partition = tcgen05.get_s2t_smem_desc_tensor(tiled_copy, thr_copy.partition_S(src_compact))
+    # ((ATOM_V, REST_V), Rest_Tiler, MMA_MN, MMA_K)
+    dst_partition = thr_copy.partition_D(dst_compact)
+
+    @dsl_user_op
+    def copy_s2t(stage_idx, *, loc=None, ip=None, **new_kwargs):
+        # Stage slice of partitioned source tensor: ((ATOM_V, REST_V), Rest_Tiler, MMA_MN, MMA_K)
+        stage_coord = (None, None, None, None, stage_idx)
+        cute.copy(
+            tiled_copy, src_partition[stage_coord], dst_partition, loc=loc, ip=ip, **new_kwargs
+        )
+
+    return copy_s2t
+
+
+def tma_producer_copy_fn(copy: Callable, pipeline: cutlass.pipeline.PipelineAsync):
+    def copy_fn(src_idx, producer_state: cutlass.pipeline.PipelineState, **new_kwargs):
+        copy(
+            src_idx=src_idx,
+            dst_idx=producer_state.index,
+            tma_bar_ptr=pipeline.producer_get_barrier(producer_state),
+            **new_kwargs,
+        )
+
+    return copy_fn
+
+
+def chain_tma_producer_copy_fns(copy_fns: Sequence[Optional[Callable]]):
+    if not any(fn is not None for fn in copy_fns):
+        return None
+
+    def copy_fn(src_idx, producer_state: cutlass.pipeline.PipelineState, **new_kwargs):
+        for fn in copy_fns:
+            if const_expr(fn is not None):
+                fn(src_idx=src_idx, producer_state=producer_state, **new_kwargs)
+
+    return copy_fn
+
+
+@cute.jit
+def gather_m_get_copy_fn(
+    thr_copy_A: cute.ThrCopy,
+    mA: cute.Tensor,  # (whatever, K)
+    sA: cute.Tensor,  # (tile_M, tile_K, STAGE)
+    gsAIdx: cute.Tensor,  # (tile_M), either gmem or smem
+    limit_m: Int32,
+    limit_k: Int32,
+) -> Callable:
+    tile_M, tile_K = cute.size(sA, mode=[0]), cute.size(sA, mode=[1])
+    tAsA = partition_D_position_independent(thr_copy_A, sA)
+    # k-major
+    assert tAsA.shape[2] == 1
+    tAsA = cute.group_modes(cute.slice_(tAsA, (None, None, 0, None)), 0, 2)
+
+    is_even_m_smem = tile_M % thr_copy_A.tiler_mn[0].shape == 0
+    if const_expr(not is_even_m_smem):
+        limit_m = min(limit_m, tile_M)
+    elems_per_load = cute.size(tAsA.shape[0][0])
+    cA = cute.make_identity_tensor((tile_M, tile_K))
+    tAcA = thr_copy_A.partition_S(cA)
+    t0AcA = thr_copy_A.get_slice(0).partition_S(cA)
+    # Instead of comparing tAcA to limit_m, we instead compare t0AcA to limit_m - tAcA[0][0]
+    # since we know that tAcA[m][0] = t0AcA[m][0] + tAcA[0][0].
+    # This is so that when we do the comparison, t0AcA is known at compile time.
+    limit_m = limit_m - tAcA[0][0]
+    limit_k = limit_k - tAcA[0][1]
+    # Read and cache indices for A
+    rows_per_thread = const_expr(cute.size(tAcA.shape, mode=[1]))
+    cols_per_thread = const_expr(cute.size(tAcA.shape, mode=[2]))
+    tApA_m = cute.make_rmem_tensor(rows_per_thread, Boolean)
+    for m in cutlass.range(rows_per_thread, unroll_full=True):
+        tApA_m[m] = t0AcA[0, m, 0][0] < limit_m
+    m_idx = cute.make_rmem_tensor(rows_per_thread, Int32)
+    for m in cutlass.range(rows_per_thread, unroll_full=True):
+        row_idx = tAcA[0, m, 0][0]
+        if tApA_m[m]:
+            m_idx[m] = gsAIdx[row_idx]
+        else:
+            m_idx[m] = 0  # It's ok to load row 0 in the case of OOB
+
+    mA_k = cute.logical_divide(mA, (None, tile_K))
+
+    def copy_fn(src_idx, dst_idx, pred: cutlass.Constexpr[bool] = False):
+        tApA_k = None
+        if const_expr(pred):
+            tApA_k = cute.make_rmem_tensor(cols_per_thread, Boolean)
+            limit_k_cur = limit_k - src_idx * tile_K
+            for k in cutlass.range(cols_per_thread, unroll_full=True):
+                tApA_k[k] = t0AcA[0, 0, k][1] < limit_k_cur
+        mA_cur = mA_k[None, (None, src_idx)]
+        for m in cutlass.range_constexpr(tAcA.shape[1]):
+            # cute.tiled_divide(mA_cur[m_idx[m], None], (elems_per_load,)) would give shape
+            # ((elems_per_load), thread_per_row)
+            # But we actually want shape ((elems_per_load, 1), thread_per_row) to match tAsA
+            # So we append 1s to the last dimension and then do tiled_divide, then slice.
+            mA_row = cute.tiled_divide(
+                cute.append_ones(mA_cur[m_idx[m], None], up_to_rank=2), (elems_per_load, 1)
+            )[None, None, 0]
+            if const_expr(is_even_m_smem) or tApA_m[m]:
+                # There's only 1 load per row
+                assert cute.size(tAcA.shape, mode=[2]) == 1
+                ki = tAcA[0, 0, 0][1] // elems_per_load
+                cute.copy(thr_copy_A, mA_row[None, ki], tAsA[(None, m), dst_idx], pred=tApA_k)
+
+    return copy_fn
+
+
+@cute.jit
+def gather_k_get_copy_fn(
+    thr_copy_A: cute.ThrCopy,
+    mA: cute.Tensor,  # (tile_M, whatever)
+    sA: cute.Tensor,  # (tile_M, tile_K, STAGE)
+    gsAIdx: cute.Tensor,  # (tile_K, RestK), either gmem or smem
+    limit_m: Int32,
+    limit_k: Int32,
+) -> Callable:
+    gAIdx, sAIdx = None, None
+    if const_expr(gsAIdx.memspace == cute.AddressSpace.gmem):
+        gAIdx = gsAIdx
+    else:
+        assert gsAIdx.memspace == cute.AddressSpace.smem
+        sAIdx = gsAIdx
+    tile_shape_mk = (cute.size(sA, mode=[0]), cute.size(sA, mode=[1]))
+    # (atom_v, CPY_M, 1, STAGE)
+    tAsA = thr_copy_A.partition_D(sA)
+    # m-major
+    tAsA = cute.group_modes(tAsA, 0, 3)
+
+    is_even_m_smem = tile_shape_mk[0] % thr_copy_A.tiler_mn[0].shape == 0
+    if const_expr(not is_even_m_smem):
+        limit_m = min(limit_m, tile_shape_mk[0])
+    elems_per_load = cute.size(tAsA.shape[0][0])
+    cA = cute.make_identity_tensor(tile_shape_mk)
+    tAcA = thr_copy_A.partition_S(cA)
+    t0AcA = thr_copy_A.get_slice(0).partition_S(cA)
+    # Instead of comparing tAcA to limit_m, we instead compare t0AcA to limit_m - tAcA[0][0]
+    # since we know that tAcA[m][0] = t0AcA[m][0] + tAcA[0][0].
+    # This is so that when we do the comparison, t0AcA is known at compile time.
+    limit_m = limit_m - tAcA[0][0]
+    limit_k = limit_k - tAcA[0][1]
+    # Read and cache indices for A
+    rows_per_thread = const_expr(cute.size(tAcA.shape, mode=[1]))
+    cols_per_thread = const_expr(cute.size(tAcA.shape, mode=[2]))
+    tApA_m = cute.make_rmem_tensor(rows_per_thread, Boolean)
+    for m in cutlass.range(rows_per_thread, unroll_full=True):
+        tApA_m[m] = t0AcA[0, m, 0][0] < limit_m
+    threads_per_col = const_expr(thr_copy_A.tiler_mn[0].shape // elems_per_load)
+    # This is very convoluted but idk a better way
+    # for tile_M=128, flat_divide gives (8, 16, K),
+    # then logical_divide gives ((8, 1), (8, 2), K).
+    tidx = thr_copy_A.thr_idx
+    tAmA = cute.logical_divide(
+        cute.flat_divide(mA, (elems_per_load,)), (elems_per_load, threads_per_col)
+    )[None, (tidx % threads_per_col, None), None]  # ((8, 1), 2, K)
+
+    def prefetch_from_gmem_fn(src_idx, pred: bool = False) -> Tuple[cute.Tensor, cute.Tensor]:
+        # Prefetch mAIdx early, even before smem is free
+        tApA_k = None
+        if const_expr(pred):
+            tApA_k = cute.make_rmem_tensor(cols_per_thread, Boolean)
+            limit_k_cur = limit_k - src_idx * tile_shape_mk[1]
+            for k in cutlass.range(cols_per_thread, unroll_full=True):
+                tApA_k[k] = t0AcA[0, 0, k][1] < limit_k_cur
+        gAIdx_cur = gAIdx[None, src_idx]
+        k_idx = cute.make_rmem_tensor(cols_per_thread, Int32)
+        for k in cutlass.range(cols_per_thread):
+            col_idx = tAcA[0, 0, k][1]
+            if const_expr(not pred):
+                k_idx[k] = gAIdx_cur[col_idx]
+            else:
+                if tApA_k[k]:
+                    k_idx[k] = gAIdx_cur[col_idx]
+                else:
+                    k_idx[k] = -1
+        return k_idx, tApA_k
+
+    def prefetch_from_smem_fn(
+        a_prefetch_pipeline, src_idx, dst_idx, a_prefetch_consumer_state, pred: bool = False
+    ) -> Tuple[cute.Tensor, cute.Tensor]:
+        tApA_k = None
+        if const_expr(pred):
+            tApA_k = cute.make_rmem_tensor(cols_per_thread, Boolean)
+            limit_k_cur = limit_k - src_idx * tile_shape_mk[1]
+            for k in cutlass.range(cols_per_thread, unroll_full=True):
+                tApA_k[k] = t0AcA[0, 0, k][1] < limit_k_cur
+        a_prefetch_pipeline.consumer_wait(a_prefetch_consumer_state)
+        sAIdx_cur = sAIdx[None, dst_idx]
+        k_idx = cute.make_rmem_tensor(cols_per_thread, Int32)
+        for k in cutlass.range(cols_per_thread):
+            col_idx = tAcA[0, 0, k][1]
+            k_idx[k] = sAIdx_cur[col_idx]
+        cute.arch.sync_warp()
+        with cute.arch.elect_one():
+            a_prefetch_pipeline.consumer_release(a_prefetch_consumer_state)
+        return k_idx, tApA_k
+
+    def copy_fn(
+        src_idx, dst_idx, k_idx_tApA_k: Tuple[cute.Tensor, cute.Tensor], pred: bool = False
+    ):
+        k_idx, tApA_k = k_idx_tApA_k
+        tApA_k_pred = None
+        if const_expr(pred):
+            tApA_k_pred = cute.prepend_ones(tApA_k, up_to_rank=2)  # (1, cols_per_thread)
+        for k in cutlass.range_constexpr(tAcA.shape[2]):
+            # copy_A(tAmA[None, None, k_idx[k]], tAsA[(None, None, k), smem_idx], pred=cute.prepend_ones(tApA_m, up_to_rank=2))
+            for m in cutlass.range_constexpr(tAcA.shape[1]):
+                if tApA_m[m]:
+                    cute.copy(
+                        thr_copy_A,
+                        tAmA[None, m, k_idx[k]],
+                        tAsA[(None, m, k), dst_idx],
+                        pred=None if const_expr(tApA_k_pred is None) else tApA_k_pred[None, k],
+                    )
+
+    return copy_fn, prefetch_from_gmem_fn if const_expr(
+        gAIdx is not None
+    ) else prefetch_from_smem_fn
+
+
+@cute.jit
+def gather_m_get_tma_copy_fn(
+    tma_atom: cute.CopyAtom,
+    mA: cute.Tensor,  # (whatever, K)
+    sA: cute.Tensor,  # ((4, 32), (64, 1), STAGE)
+    sAIdx: cute.Tensor,  # (tile_M),
+    warp_idx: Int32,
+    num_warps: int,
+    num_cta: int = 1,
+) -> Callable:
+    tile_M = cute.size(sAIdx, mode=[0])
+    tile_K = cute.size(sA[None, None, 0]) // tile_M
+    assert tile_M % 4 == 0
+    # cta_group = 1 if tma_atom.op.cta_group == CtaGroup.ONE else 2
+    cta_group = num_cta  # Somehow all tma_atom has CtaGroup.ONE inside the kernel
+
+    copy_AIdx_s2r = cute.make_tiled_copy_tv(
+        cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), Int32, num_bits_per_copy=128),
+        cute.make_layout(num_warps),  # thr_layout
+        cute.make_layout(4),  # val_layout
+    )
+    warp_copy_AIdx_s2r = copy_AIdx_s2r.get_slice(warp_idx)
+    tSR_sAIdx = warp_copy_AIdx_s2r.partition_S(sAIdx)
+    # ((4, 1), 8, (64, 1), STAGE)
+    tSR_sA = warp_copy_AIdx_s2r.partition_S(sA)
+    tSR_rAIdx = load_s2r(tSR_sAIdx)
+    tma_desc_ptr = get_tma_desc_addr(tma_atom)
+    tma_gather4_load_fn = partial(tma_gather4_load, tma_desc_ptr, num_cta=cta_group)
+
+    def copy_fn(src_idx, dst_idx, tma_bar_ptr: cute.Pointer):
+        tSR_sA_cur = tSR_sA[None, None, None, dst_idx]
+        col_idx = tile_K * src_idx
+        for m in cutlass.range(cute.size(tSR_rAIdx, mode=[1]), unroll_full=True):
+            row_indices = [tSR_rAIdx[v, m] for v in range(4)]
+            smem_ptr = tSR_sA_cur[None, m, None].iterator
+            with cute.arch.elect_one():
+                tma_gather4_load_fn(smem_ptr, tma_bar_ptr, col_idx, row_indices)
+
+    return copy_fn
+
+
+@cute.jit
+def gather_k_get_tma_copy_fn(
+    tma_atom: cute.CopyAtom,
+    sA: cute.Tensor,  # ((4, tile_K/4), (tile_M,), STAGE) — K-grouped load layout
+    sAIdx: cute.Tensor,  # (tile_K, a_prefetch_stage) — K indices in smem
+    col_idx: Int32,  # M offset in global tensor (contiguous dim for M-major)
+    warp_idx: Int32,
+    num_warps: int,
+    num_cta: int = 1,
+) -> Tuple[Callable, Callable]:
+    """Build a copy function for TMA gather4 in K dimension (M-major A).
+
+    Each gather4 instruction loads 4 K-columns × tile_M contiguous M-elements.
+    col_idx is the absolute M position in the global tensor.
+    K indices come from sAIdx (prefetched to smem by the scheduler warp).
+
+    Returns copy_fn(src_idx, dst_idx, tma_bar_ptr) which:
+      Issues gather4 calls with those K indices as row_indices
+    """
+    tile_K = cute.size(sAIdx, mode=[0])
+    assert tile_K % 4 == 0
+    cta_group = num_cta
+
+    # Tiled copy for loading K indices from smem to registers (4 per vector, across warps)
+    copy_AIdx_s2r = cute.make_tiled_copy_tv(
+        cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), Int32, num_bits_per_copy=128),
+        cute.make_layout(num_warps),  # thr_layout
+        cute.make_layout(4),  # val_layout — 4 K indices per gather4
+    )
+    warp_idx = cute.arch.make_warp_uniform(warp_idx)
+    warp_copy_AIdx_s2r = copy_AIdx_s2r.get_slice(warp_idx)
+    tSR_sAIdx = warp_copy_AIdx_s2r.partition_S(sAIdx)  # (((4,1),4,4))
+    # ((4,1),4,(64,2),(1,4)):((64,0),1024,(1,4096),(0,8192))
+    tSR_sA = warp_copy_AIdx_s2r.partition_S(layout_utils.transpose_view(sA))
+    tma_desc_ptr = get_tma_desc_addr(tma_atom)
+    tma_gather4_load_fn = partial(tma_gather4_load, tma_desc_ptr, num_cta=cta_group)
+
+    def prefetch_from_smem_fn(
+        a_prefetch_pipeline,
+        src_idx,
+        dst_idx,
+        a_prefetch_consumer_state,
+    ) -> cute.Tensor:
+        a_prefetch_pipeline.consumer_wait(a_prefetch_consumer_state)
+        tSR_rAIdx = load_s2r(tSR_sAIdx[None, None, dst_idx])
+        cute.arch.sync_warp()
+        with cute.arch.elect_one():
+            a_prefetch_pipeline.consumer_release(a_prefetch_consumer_state)
+        return tSR_rAIdx
+
+    def copy_fn(src_idx, dst_idx, tSR_rAIdx, tma_bar_ptr: cute.Pointer):
+        # Issue gather4: col_idx = M position, row_indices = 4 K positions
+        tSR_sA_cur = tSR_sA[None, None, None, dst_idx]
+        gather_dim = cute.size(tSR_sA_cur, mode=[2, 0])  # Typically 64
+        for k in cutlass.range(cute.size(tSR_rAIdx, mode=[1]), unroll_full=True):
+            row_indices = [tSR_rAIdx[v, k] for v in range(4)]
+            for m in cutlass.range(cute.size(tSR_sA_cur, mode=[2, 1]), unroll_full=True):
+                smem_ptr = tSR_sA_cur[None, k, (None, m)].iterator
+                with cute.arch.elect_one():
+                    tma_gather4_load_fn(
+                        smem_ptr, tma_bar_ptr, col_idx + m * gather_dim, row_indices
+                    )
+
+    return copy_fn, prefetch_from_smem_fn
+
+
+# ---------------------------------------------------------------------------
+# Store helpers
+# ---------------------------------------------------------------------------
+
+
+@dsl_user_op
+@cute.jit
+def store(
+    ptr: cute.Pointer,
+    val,
+    pred: Optional[Boolean] = None,
+    cop: cutlass.Constexpr = None,
+    *,
+    loc=None,
+    ip=None,
+):
+    """Store a scalar value via cute.arch.store.
+
+    ptr:  cute.Pointer (any address space).
+    val:  DSL Numeric value.
+    pred: None → unconditional.  DSL Boolean → skipped when pred == 0.
+    cop:  Cache operator — "wb" (default), "cg", "cs" (streaming), "wt".
+    """
+    if const_expr(pred is None):
+        cute.arch.store(ptr.llvm_ptr, type(val)(val), cop=cop, loc=loc, ip=ip)
+    else:
+        if pred:
+            cute.arch.store(ptr.llvm_ptr, type(val)(val), cop=cop, loc=loc, ip=ip)
+
+
+@dsl_user_op
+@cute.jit
+def store_v2(
+    ptr: cute.Pointer,
+    v0,
+    v1,
+    pred: Optional[Boolean] = None,
+    cop: cutlass.Constexpr = None,
+    *,
+    loc=None,
+    ip=None,
+):
+    """Vectorized store of 2 elements via cute.arch.store.
+
+    Packs v0, v1 into an MLIR <2 x T> vector.
+    ptr:  cute.Pointer (any address space, must be aligned for vector width).
+    cop:  Cache operator — "wb" (default), "cg", "cs" (streaming), "wt".
+    """
+    vec = make_vector(type(v0), v0, v1, loc=loc, ip=ip)
+    if const_expr(pred is None):
+        cute.arch.store(ptr.llvm_ptr, vec, cop=cop, loc=loc, ip=ip)
+    else:
+        if pred:
+            cute.arch.store(ptr.llvm_ptr, vec, cop=cop, loc=loc, ip=ip)
+
+
+@dsl_user_op
+@cute.jit
+def store_v4(
+    ptr: cute.Pointer,
+    v0,
+    v1,
+    v2,
+    v3,
+    pred: Optional[Boolean] = None,
+    cop: cutlass.Constexpr = None,
+    *,
+    loc=None,
+    ip=None,
+):
+    """Vectorized store of 4 elements via cute.arch.store.
+
+    Packs v0–v3 into an MLIR <4 x T> vector.
+    ptr:  cute.Pointer (any address space, must be aligned for vector width).
+    cop:  Cache operator — "wb" (default), "cg", "cs" (streaming), "wt".
+    """
+    vec = make_vector(type(v0), v0, v1, v2, v3, loc=loc, ip=ip)
+    if const_expr(pred is None):
+        cute.arch.store(ptr.llvm_ptr, vec, cop=cop, loc=loc, ip=ip)
+    else:
+        if pred:
+            cute.arch.store(ptr.llvm_ptr, vec, cop=cop, loc=loc, ip=ip)
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cute_dsl_elf_fix.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cute_dsl_elf_fix.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a55a68681bc096dc50f43e2568eb5c497b3a695
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cute_dsl_elf_fix.py
@@ -0,0 +1,90 @@
+# Monkey patch for NVIDIA/cutlass#3161 [CuTeDSL] workaround of MLIR codegen
+# emitting duplicate .text sections with conflicting flags.
+#
+# The CUTLASS MLIR code-gen produces .o files with two .text sections:
+# one executable (ALLOC|EXECINSTR) and a small writable-data trampoline
+# (WRITE|ALLOC). LLVM's MCJIT backend merges same-named sections and
+# misapplies page protections, causing non-deterministic segfaults in
+# multi-process torchrun workloads. LLVM JitLink rejects the file outright.
+#
+# Fix: before constructing the execution engine, rewrite all duplicate
+# .text sections to ALLOC|EXECINSTR so JitLink accepts the file, then
+# force useJitLink=True for that path. Relocations are applied before
+# page protection, so the trampoline does not need WRITE at load time.
+#
+# Drop this file once the upstream PR lands in the CuTeDSL release quack pins.
+
+import struct
+
+_PATCHED = False
+
+
+def _fix_elf_dup_text_flags(data: bytes) -> bytes:
+    if len(data) < 64 or data[4] != 2 or data[5] != 1:  # ELF64 LE only
+        return data
+    e_shoff = struct.unpack_from("= e_shnum:
+        return data
+    shstr_hdr = e_shoff + e_shstrndx * e_shentsize
+    shstr_off = struct.unpack_from(" None:
+    """Install the ELF duplicate-.text flags workaround. Idempotent."""
+    global _PATCHED
+    if _PATCHED:
+        return
+    try:
+        from cutlass.base_dsl.export import external_binary_module as _ebm
+        from cutlass.base_dsl.common import DSLRuntimeError
+    except Exception:
+        return  # CuTeDSL not importable; nothing to patch
+
+    cls = _ebm.ExternalBinaryModule
+    orig_init = cls.__init__
+
+    def patched_init(self, file_path: str, enable_tvm_ffi: bool = False) -> None:
+        # Mirror of upstream __init__ (cutlass.base_dsl.export.external_binary_module)
+        # with the PR #3161 fix inserted between useJitLink selection and
+        # engine construction.
+        self.enable_tvm_ffi = enable_tvm_ffi
+        assert self.load_provider is not None, "Load provider is not set for ExternalBinaryModule."
+        shared_libs = self.load_provider.dsl._get_dsl().get_shared_libs()
+        object_file_content = bytes()
+        if file_path.endswith(".so"):
+            shared_libs.append(file_path)
+        else:
+            try:
+                with open(file_path, "rb") as f:
+                    object_file_content = f.read()
+            except Exception as e:
+                raise DSLRuntimeError(f"Failed to read object file {file_path}: {e}")
+
+        useJitLink = not enable_tvm_ffi
+        if not useJitLink and object_file_content:
+            object_file_content = _fix_elf_dup_text_flags(object_file_content)
+            useJitLink = True
+        self.engine = self.load_provider.execution_engine_constructor(
+            object_file_content, shared_libs, useJitLink
+        )
+
+    # Fall back to the original __init__ if any check here changes upstream.
+    patched_init.__wrapped__ = orig_init  # type: ignore[attr-defined]
+    cls.__init__ = patched_init
+    _PATCHED = True
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cute_dsl_mlir_threading.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cute_dsl_mlir_threading.py
new file mode 100644
index 0000000000000000000000000000000000000000..309fbe26de31ae541a19a100aacffff0e0881efd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cute_dsl_mlir_threading.py
@@ -0,0 +1,43 @@
+# Copyright (c) 2025-2026, QuACK team.
+"""Work around CuTeDSL MLIR context thread-pool leaks.
+
+NVIDIA/cutlass#3062 documents that MLIR contexts keep LLVM worker thread pools
+alive when context threading is enabled. Large pytest sweeps compile many CuTe
+kernels in one Python process, so these idle workers accumulate until LLVM
+eventually fails to create another pthread.
+
+Remove this workaround once QuACK updates to cutlass-dsl 4.5.
+"""
+
+import os
+
+_PATCHED = False
+
+
+def patch() -> None:
+    """Disable MLIR context threading for new CuTeDSL contexts. Idempotent."""
+    global _PATCHED
+    if _PATCHED or os.getenv("QUACK_DISABLE_MLIR_THREADING_PATCH", "0") == "1":
+        return
+    try:
+        from cutlass._mlir import ir
+    except Exception:
+        return  # CuTeDSL not importable; nothing to patch
+
+    orig_context = ir.Context
+    if getattr(orig_context, "_quack_mlir_threading_patch", False):
+        _PATCHED = True
+        return
+
+    class SingleThreadedContext(orig_context):
+        _quack_mlir_threading_patch = True
+
+        def __init__(self, *args, **kwargs):
+            super().__init__(*args, **kwargs)
+            self.enable_multithreading(False)
+
+    SingleThreadedContext.__name__ = orig_context.__name__
+    SingleThreadedContext.__qualname__ = orig_context.__qualname__
+    SingleThreadedContext.__module__ = orig_context.__module__
+    ir.Context = SingleThreadedContext
+    _PATCHED = True
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cute_dsl_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cute_dsl_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1e46c942caf50f656f573b044a63af618af7177
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/cute_dsl_utils.py
@@ -0,0 +1,204 @@
+# Copyright (c) 2025, Tri Dao.
+
+from typing import Tuple, get_origin
+from functools import lru_cache
+from dataclasses import dataclass, fields
+
+import os
+import re
+
+import torch
+
+try:
+    from triton.tools.disasm import extract
+except ImportError:
+    extract = None
+
+import cutlass
+import cutlass.cute as cute
+from cutlass import (
+    BFloat16,
+    Float16,
+    Float32,
+    Float8E4M3FN,
+    Float8E8M0FNU,
+    Int32,
+    Int64,
+    Uint8,
+)
+from cutlass.base_dsl.tvm_ffi_builder import spec
+from cutlass.cutlass_dsl import NumericMeta
+
+
+StaticTypes = (cutlass.Constexpr, NumericMeta, int, bool, str, float, type(None))
+
+
+load_cubin_module_data_og = cutlass.base_dsl.runtime.cuda.load_cubin_module_data
+cute_compile_og = cute.compile
+
+
+# Patch TVM-FFI converter to handle Constexpr type annotations as compile-time constants.
+# Fields annotated with cutlass.Constexpr[T] are emitted as ConstNone (not runtime args).
+# At call time, pass None for these fields; the compile-time value is baked in.
+import cutlass.cute._tvm_ffi_args_spec_converter as _converter_module  # noqa
+
+_original_convert_single_arg = _converter_module._convert_single_arg
+
+
+def _patched_convert_single_arg(arg, arg_name, arg_type, ctx):
+    if arg_type is not None and get_origin(arg_type) is cutlass.Constexpr:
+        return spec.ConstNone(arg_name)
+    # If arg is a NamedTuple but arg_type doesn't have _fields (e.g. annotated as tuple),
+    # redirect so the converter uses the NamedTuple's own type hints.
+    if (
+        isinstance(arg, tuple)
+        and hasattr(type(arg), "_fields")
+        and (arg_type is None or not hasattr(arg_type, "_fields"))
+    ):
+        return _original_convert_single_arg(arg, arg_name, type(arg), ctx)
+    return _original_convert_single_arg(arg, arg_name, arg_type, ctx)
+
+
+_converter_module._convert_single_arg = _patched_convert_single_arg
+
+
+torch2cute_dtype_map = {
+    torch.bool: Uint8,
+    torch.uint8: Uint8,
+    torch.float16: Float16,
+    torch.bfloat16: BFloat16,
+    torch.float32: Float32,
+    torch.float8_e4m3fn: Float8E4M3FN,
+    torch.float8_e8m0fnu: Float8E8M0FNU,
+    torch.int32: Int32,
+    torch.int64: Int64,
+}
+
+
+@lru_cache
+def get_device_multiprocessor_count(device_id: int = 0) -> int:
+    return cutlass.utils.HardwareInfo(device_id).get_device_multiprocessor_count()
+
+
+@lru_cache
+def get_max_active_clusters(
+    cluster_size: int,
+    device_capacity: Tuple[int, int] | None = None,
+    device_id: int = 0,
+) -> int:
+    if device_capacity is None:
+        device_capacity = get_device_capacity()
+    if device_capacity[0] < 9:
+        if cluster_size != 1:
+            raise ValueError("SM8x kernels do not support CTA clusters; cluster_size must be 1")
+        return get_device_multiprocessor_count(device_id)
+    return cutlass.utils.HardwareInfo(device_id).get_max_active_clusters(cluster_size=cluster_size)
+
+
+def _parse_arch_str(arch_str: str) -> Tuple[int, int]:
+    """Parse arch string (e.g. 'sm_90', 'sm90', '90', 'sm_100a') to (major, minor) tuple."""
+    match = re.match(r"^(?:sm_?)?(\d+)(\d)([af]?)$", arch_str.strip(), re.IGNORECASE)
+    if not match:
+        raise ValueError(f"Invalid QUACK_ARCH format: {arch_str!r} (expected e.g. '90', 'sm_90')")
+    major, minor, _ = match.groups()
+    return int(major), int(minor)
+
+
+@lru_cache
+def _get_device_capacity_cached(device: torch.device = None) -> Tuple[int, int]:
+    """Return (major, minor) device capability.
+
+    Override with QUACK_ARCH (e.g. 'sm_90' or '90') for CPU-only compilation
+    without a GPU present.
+    """
+    arch_override = os.environ.get("QUACK_ARCH")
+    if arch_override is not None:
+        return _parse_arch_str(arch_override)
+    return torch.cuda.get_device_capability(device)
+
+
+def get_device_capacity(
+    device: torch.device | torch.Tensor | None = None,
+) -> Tuple[int, int]:
+    """Return (major, minor) device capability.
+
+    Override with QUACK_ARCH (e.g. 'sm_90' or '90') for CPU-only compilation
+    without a GPU present.
+
+    Accepts either a ``torch.device`` or a tensor and canonicalizes to the
+    underlying device before consulting the cached helper. This avoids leaking
+    tensors through the LRU cache key.
+    """
+    if isinstance(device, torch.Tensor):
+        device = device.device
+    return _get_device_capacity_cached(device)
+
+
+def _partition_fields(obj):
+    """Split dataclass fields into (constexpr_dict, non_constexpr_dict) by type."""
+    all_fields = {field.name: getattr(obj, field.name) for field in fields(obj)}
+    constexpr = {n: f for n, f in all_fields.items() if isinstance(f, StaticTypes)}
+    non_constexpr = {n: f for n, f in all_fields.items() if not isinstance(f, StaticTypes)}
+    return constexpr, non_constexpr
+
+
+def _new_from_mlir_values(self, values):
+    constexpr_fields, non_constexpr_fields = _partition_fields(self)
+    for (name, field), n_items in zip(non_constexpr_fields.items(), self._values_pos):
+        non_constexpr_fields[name] = cutlass.new_from_mlir_values(field, values[:n_items])
+        values = values[n_items:]
+    return self.__class__(**non_constexpr_fields, **constexpr_fields)
+
+
+def _namedtuple_new_from_mlir_values(self, values):
+    """Generic __new_from_mlir_values__ for NamedTuples.
+
+    Applied to NamedTuple classes via the ``@mlir_namedtuple`` decorator.
+
+    Fields that are None or Constexpr (StaticTypes) are preserved from ``self`` (the compile-time
+    template). Only non-static fields consume MLIR values. Multi-value fields (e.g. cute.Tensor)
+    consume the correct number of values via ``cutlass.new_from_mlir_values``.
+
+    Constexpr fields (annotated ``cutlass.Constexpr[T]``) are baked into the compiled kernel via
+    a converter patch (see above). At call time, pass None for these fields.
+    """
+    from cutlass.base_dsl.typing import get_mlir_types
+
+    values = list(values)
+    new_fields = []
+    for field_val in self:
+        if field_val is None or isinstance(field_val, StaticTypes):
+            new_fields.append(field_val)
+        else:
+            n_items = len(get_mlir_types(field_val))
+            new_fields.append(cutlass.new_from_mlir_values(field_val, values[:n_items]))
+            values = values[n_items:]
+    return self.__class__(*new_fields)
+
+
+def mlir_namedtuple(cls):
+    """Decorator that adds MLIR value reconstruction to a NamedTuple class.
+
+    Usage::
+
+        @mlir_namedtuple
+        class MyArgs(NamedTuple):
+            tensor_arg: cute.Tensor
+            const_arg: cutlass.Constexpr[int] = 0
+    """
+    cls.__new_from_mlir_values__ = _namedtuple_new_from_mlir_values
+    return cls
+
+
+@dataclass
+class ParamsBase:
+    def __extract_mlir_values__(self):
+        _, non_constexpr_fields = _partition_fields(self)
+        values, self._values_pos = [], []
+        for obj in non_constexpr_fields.values():
+            obj_values = cutlass.extract_mlir_values(obj)
+            values += obj_values
+            self._values_pos.append(len(obj_values))
+        return values
+
+    __new_from_mlir_values__ = _new_from_mlir_values
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/epi_composable.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/epi_composable.py
new file mode 100644
index 0000000000000000000000000000000000000000..7821cf6395816e723acddace41923c3652b5302d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/epi_composable.py
@@ -0,0 +1,294 @@
+# Copyright (c) 2025, Tri Dao.
+"""ComposableEpiMixin: composes EpiOps into epilogue hook methods.
+
+Subclasses declare _epi_ops as a class-level tuple of EpiOp instances — the
+static *schema* for the epilogue. The mixin auto-generates epi_smem_bytes,
+epi_get_smem_struct, epi_get_smem_tensors, epi_begin, epi_begin_loop,
+epi_end_loop, epi_end, and EpilogueParams by querying each op.
+
+Host-side, `_epi_ops_to_params_dict` (called from each subclass's
+`epi_to_underlying_arguments`) filters `_epi_ops` automatically: it shadows
+the class-level tuple with an instance-level tuple containing only the ops
+whose argument tensor is non-None. All later iteration (host- and
+device-side) walks the filtered tuple, so each EpiOp's hook methods can
+assume their `param`/`arg_tensor` is non-None.
+
+The two host-side hooks that run *before* `epi_to_underlying_arguments`
+(`resolve_epi_m_major` and the classmethod `epi_smem_bytes`) filter inline
+from `args`, preserving the same non-None invariant for `op.epi_m_major_score`
+and `op.smem_bytes`. They have to run first because `epi_to_underlying_arguments`
+itself depends on static attributes set up before it (e.g. `gemm.epi_tile`,
+`gemm.epi_c_stage`), and those attributes are themselves derived from
+`epi_m_major` and the epi smem budget — a chicken-and-egg ordering we resolve by
+letting these two hooks see the raw `args` and filter inline.
+
+epi_get_smem_tensors, epi_begin, and epi_begin_loop all return dicts keyed by
+op name, so consumers access values by name (e.g. epi_smem_tensors["mAuxOut"],
+epi_loop_tensors["alpha"]). Because inactive ops are filtered out, consumers
+must use `.get(name)` (returns None for inactive ops) rather than `[name]`.
+
+EpilogueParams is auto-generated from the full class-level _epi_ops (via
+param_fields()) plus any _extra_param_fields declared on the subclass.
+Subclasses still define EpilogueArguments and epi_to_underlying_arguments
+manually.
+"""
+
+from dataclasses import make_dataclass, MISSING
+
+import cutlass.cute as cute
+from cutlass import Int32, const_expr
+
+from .cute_dsl_utils import ParamsBase
+from .epi_ops import EpiContext, EpiSmemBytes, Scalar
+
+
+def _make_epi_params(epi_ops, extra_fields, bases):
+    """Build EpilogueParams dataclass from epi_ops + extra fields.
+
+    Required fields (default=MISSING) are placed first, then optional fields.
+    """
+    required, optional = [], []
+    for op in epi_ops:
+        for name, typ, default in op.param_fields():
+            (required if default is MISSING else optional).append((name, typ, default))
+    for name, typ, default in extra_fields:
+        (required if default is MISSING else optional).append((name, typ, default))
+    fields = [(n, t) for n, t, _ in required] + [(n, t, d) for n, t, d in optional]
+    return make_dataclass("EpilogueParams", fields, bases=bases)
+
+
+class ComposableEpiMixin:
+    """Base mixin that composes EpiOps into the standard epilogue hooks."""
+
+    _epi_ops = ()
+    _extra_param_fields = ()  # [(name, type, default), ...] for non-op params (e.g. act_fn)
+    _epi_param_bases = (ParamsBase,)  # Base classes for the auto-generated EpilogueParams
+
+    def __init_subclass__(cls, **kwargs):
+        super().__init_subclass__(**kwargs)
+        if cls._epi_ops:
+            # Auto-generate EpilogueParams if not explicitly defined on this class
+            if "EpilogueParams" not in cls.__dict__:
+                cls.EpilogueParams = _make_epi_params(
+                    cls._epi_ops, cls._extra_param_fields, cls._epi_param_bases
+                )
+
+    # --- Host-side: args → params ---
+
+    def _filter_epi_ops(self, args):
+        """Shadow `_epi_ops` with an instance-level tuple of only the ops whose
+        arg is non-None. Called automatically by `_epi_ops_to_params_dict`, so
+        subclass `epi_to_underlying_arguments` methods don't need to invoke it
+        directly. After this runs, op hook methods can assume their
+        `param`/`arg_tensor` is non-None."""
+        self._epi_ops = tuple(
+            op for op in type(self)._epi_ops if getattr(args, op.name, None) is not None
+        )
+
+    def _epi_ops_to_params_dict(self, args):
+        """Filter `_epi_ops` to active ops, then merge each op's to_params into
+        a single dict. Subclasses call this from epi_to_underlying_arguments,
+        add custom fields, then construct self.EpilogueParams(**d). Filtering
+        here means every later iteration of self._epi_ops (host- and
+        device-side) walks only active ops, and each op hook can assume its
+        arg is non-None."""
+        self._filter_epi_ops(args)
+        d = {}
+        for op in self._epi_ops:
+            d.update(op.to_params(self, args))
+        return d
+
+    def resolve_epi_m_major(self, args):
+        # Runs inside _setup_attributes, before epi_to_underlying_arguments,
+        # because epi_m_major drives epi_tile / smem layout choices that
+        # epi_to_underlying_arguments later consumes. self._epi_ops is still
+        # the class-level schema at this point, so we filter inline from args
+        # to keep op.epi_m_major_score's non-None invariant.
+        score = 0
+        for op in type(self)._epi_ops:
+            arg = getattr(args, op.name, None)
+            if arg is not None:
+                score += op.epi_m_major_score(arg, self)
+        return score >= 0
+
+    # --- Host-side: smem allocation (queried from ops) ---
+
+    @classmethod
+    def epi_smem_bytes(cls, args, cta_tile_shape_mnk, epi_tile, warp_shape_mnk=None):
+        # Runs inside _compute_stages, before epi_to_underlying_arguments,
+        # because the AB/epi stage counts (and therefore epi_c_stage) depend
+        # on the epi smem budget that this returns; epi_to_underlying_arguments
+        # then consumes epi_c_stage to build TileLoad's staged smem layout.
+        # Stays a classmethod because _compute_stages is a classmethod and may
+        # be invoked without an instance, so we filter inline from args.
+        result = EpiSmemBytes()
+        for op in cls._epi_ops:
+            arg = getattr(args, op.name, None)
+            if arg is not None:
+                result += op.smem_bytes(arg, cta_tile_shape_mnk, epi_tile, warp_shape_mnk)
+        return result
+
+    def epi_get_smem_struct(self, params):
+        fields = []
+        for op in self._epi_ops:
+            result = op.smem_struct_field(self, params)
+            if result is not None:
+                fields.append(result)
+
+        # cute.struct rejects empty annotations. When every active op contributes
+        # no smem (e.g. only Scalar ops, or no active ops at all), return a
+        # zero-byte placeholder matching gemm_base's default epi struct.
+        if not fields:
+            return cute.struct.MemRange[Int32, 0]
+
+        # Sort smallest-to-largest so smaller fields pack ahead of larger
+        # higher-aligned fields, reducing smem wasted to alignment padding.
+        def _field_bytes(name_ftype):
+            wrapper = type("_F", (), {"__annotations__": {name_ftype[0]: name_ftype[1]}})
+            return cute.struct(wrapper).size_in_bytes()
+
+        fields.sort(key=_field_bytes)
+        annotations = {name: ftype for name, ftype in fields}
+        EpiSharedStorage = type("EpiSharedStorage", (), {"__annotations__": annotations})
+        return cute.struct(EpiSharedStorage)
+
+    def epi_get_smem_tensors(self, params, storage):
+        return {
+            op.name: op.get_smem_tensor(self, params, storage.epi)
+            for op in self._epi_ops
+            if not isinstance(op, Scalar)
+        }
+
+    def epi_get_tma_atoms(self, params, *, loc=None, ip=None):
+        atoms = []
+        for op in self._epi_ops:
+            atoms.extend(op.tma_atoms(self, params))
+        return atoms
+
+    # --- Device-side: kernel execution (delegates to ops) ---
+
+    @cute.jit
+    def epi_begin(
+        self,
+        params,
+        epi_smem_tensors,
+        epi_tile,
+        tiled_copy_t2r,
+        tiled_copy_r2s,
+        tile_coord_mnkl,
+        varlen_manager,
+        epilogue_barrier,
+        tidx,
+        tRS_rD_layout=None,
+    ):
+        ctx = EpiContext(
+            self,
+            epi_tile,
+            tiled_copy_t2r,
+            tiled_copy_r2s,
+            tile_coord_mnkl,
+            varlen_manager,
+            epilogue_barrier,
+            tidx,
+            tRS_rD_layout,
+        )
+        results = {
+            op.name: op.begin(
+                self,
+                getattr(params, op.name),
+                epi_smem_tensors.get(op.name),
+                ctx,
+            )
+            for op in self._epi_ops
+        }
+        # self._epi_ops is filtered to active ops, so any op needing a fence
+        # has a non-None tensor; no inner None check required.
+        has_async_data = any(op.needs_async_fence() for op in self._epi_ops)
+        if const_expr(has_async_data):
+            cute.arch.cp_async_commit_group()
+            cute.arch.cp_async_wait_group(0)
+            epilogue_barrier.arrive_and_wait()
+        return results
+
+    def epi_begin_loop(self, params, epi_tensors, epi_coord):
+        return {
+            op.name: op.begin_loop(self, epi_tensors[op.name], epi_coord) for op in self._epi_ops
+        }
+
+    def epi_tile_load_g2s_copy_fns(
+        self,
+        params,
+        epi_smem_tensors,
+        tile_coord_mnkl,
+        varlen_manager,
+        epi_pipeline,
+    ):
+        return tuple(
+            op.load_g2s_copy_fn(
+                self,
+                params,
+                epi_smem_tensors.get(op.name),
+                tile_coord_mnkl,
+                varlen_manager,
+                epi_pipeline,
+            )
+            for op in self._epi_ops
+            if op.is_tile_load()
+        )
+
+    @cute.jit
+    def epi_tile_load_s2r(self, params, epi_tensors, stage_idx):
+        for op in self._epi_ops:
+            op.load_s2r(self, getattr(params, op.name), epi_tensors[op.name], stage_idx)
+
+    @cute.jit
+    def epi_end_loop(
+        self,
+        params,
+        epi_tensors,
+        epi_coord,
+        epi_tile,
+        tiled_copy_t2r,
+        tiled_copy_r2s,
+        tile_coord_mnkl,
+        varlen_manager,
+        tidx,
+    ):
+        for op in self._epi_ops:
+            op.end_loop(
+                self,
+                getattr(params, op.name),
+                epi_tensors[op.name],
+                epi_coord,
+                epi_tile,
+                tiled_copy_t2r,
+                tiled_copy_r2s,
+                tile_coord_mnkl,
+                varlen_manager,
+                tidx,
+            )
+
+    @cute.jit
+    def epi_end(
+        self,
+        params,
+        epi_tensors,
+        epi_tile,
+        tiled_copy_t2r,
+        tiled_copy_r2s,
+        tile_coord_mnkl,
+        varlen_manager,
+        tidx,
+    ):
+        for op in self._epi_ops:
+            op.end(
+                self,
+                getattr(params, op.name),
+                epi_tensors[op.name],
+                epi_tile,
+                tiled_copy_t2r,
+                tiled_copy_r2s,
+                tile_coord_mnkl,
+                varlen_manager,
+                tidx,
+            )
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/epi_ops.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/epi_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bfa2b0da29a1356be7dd2a66673366135929a9d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/epi_ops.py
@@ -0,0 +1,1858 @@
+# Copyright (c) 2025, Tri Dao.
+"""Composable epilogue operations (EpiOps) for GEMM kernels.
+
+Each EpiOp encapsulates a single tensor kind's behavior across the epilogue lifecycle:
+smem allocation, begin (one-time per-tile setup), begin_loop (per-subtile extraction),
+end (cleanup).
+
+The ops are composed via ComposableEpiMixin. Class-level `_epi_ops` is the
+static schema; `_epi_ops_to_params_dict` (called from each subclass's
+`epi_to_underlying_arguments`) shadows it with an instance-level tuple of only
+the active ops (those whose arg tensor is non-None). All EpiOp hook methods
+below therefore assume their `param` / `arg_tensor` is non-None — the
+framework guarantees inactive ops are never iterated.
+"""
+
+import math
+import operator
+from functools import partial
+from typing import NamedTuple
+
+import cutlass
+import cutlass.cute as cute
+from cutlass import Boolean, Float32, const_expr
+
+from .epi_utils import assume_stride_divisibility, setup_epi_tensor
+from .sm90_utils import partition_for_epilogue
+from . import utils
+from . import copy_utils
+from . import layout_utils
+
+
+class EpiContext:
+    """Shared context passed to EpiOp.begin methods. Bundles common arguments.
+
+    `tRS_rD_layout` is only populated by callers that need TileLoad — it's the
+    register layout of the matmul output tile, which TileLoad uses to shape its
+    own register tile so it lines up element-wise with tRS_rD in epi_visit_subtile.
+    """
+
+    __slots__ = (
+        "epi_tile",
+        "tiled_copy_t2r",
+        "tiled_copy_r2s",
+        "tile_coord_mnkl",
+        "varlen_manager",
+        "epilogue_barrier",
+        "tidx",
+        "tRS_rD_layout",
+        "partition_for_epilogue_fn",
+        "num_epi_threads",
+        "batch_idx",
+        "tile_M",
+        "tile_N",
+    )
+
+    def __init__(
+        self,
+        gemm,
+        epi_tile,
+        tiled_copy_t2r,
+        tiled_copy_r2s,
+        tile_coord_mnkl,
+        varlen_manager,
+        epilogue_barrier,
+        tidx,
+        tRS_rD_layout=None,
+    ):
+        self.epi_tile = epi_tile
+        self.tiled_copy_t2r = tiled_copy_t2r
+        self.tiled_copy_r2s = tiled_copy_r2s
+        self.tile_coord_mnkl = tile_coord_mnkl
+        self.varlen_manager = varlen_manager
+        self.epilogue_barrier = epilogue_barrier
+        self.tidx = tidx
+        self.tRS_rD_layout = tRS_rD_layout
+        self.tile_M = gemm.cta_tile_shape_mnk[0]
+        self.tile_N = gemm.cta_tile_shape_mnk[1]
+        self.batch_idx = tile_coord_mnkl[3]
+        self.num_epi_threads = gemm.num_epi_warps * cute.arch.WARP_SIZE
+        self.partition_for_epilogue_fn = partial(
+            partition_for_epilogue,
+            epi_tile=epi_tile,
+            tiled_copy=tiled_copy_t2r if tiled_copy_t2r is not None else tiled_copy_r2s,
+            tidx=tidx,
+            reference_src=tiled_copy_t2r is None,
+        )
+
+
+def _get_lane_warp_layouts(tiled_copy, reference_src=True):
+    """Derive lane and warp layouts along M and N from the epilogue tiled_copy.
+
+    Follows the CUTLASS Sm90RowReduction / Sm90ColReduction pattern.
+    Uses layout_src_tv_tiled (SM90, reference_src=True) or
+    layout_dst_tv_tiled (SM100, reference_src=False), matching the C++ impl's
+    get_layoutS_TV / get_layoutD_TV selection.
+
+    Returns (lane_layout_MN, warp_layout_MN) where each is a 2D layout (M, N):
+      lane_layout_MN[0] = lane_M: (lanes_in_M):(lane_stride_M) — e.g. 8:4
+      lane_layout_MN[1] = lane_N: (lanes_in_N):(lane_stride_N) — e.g. 4:1
+      warp_layout_MN[0] = warp_M: (warps_in_M):(warp_stride_M) — e.g. 4:1
+      warp_layout_MN[1] = warp_N: (warps_in_N):(warp_stride_N) — e.g. 1:0
+
+    For RowVecReduce (reduce along M): shuffle across lane_M, smem reduce across warp_M.
+    For ColVecReduce (reduce along N): shuffle across lane_N, direct write (warps_in_N == 1).
+    """
+    # right_inverse of the TV layout gives tile_element_idx -> tv_idx.
+    # SM90: use src (register) layout; SM100: use dst (smem) layout.
+    layout_tv = tiled_copy.layout_src_tv_tiled if reference_src else tiled_copy.layout_dst_tv_tiled
+    ref_layout = cute.right_inverse(layout_tv)
+    tile_M_size, tile_N_size = cute.size(tiled_copy.tiler_mn[0]), cute.size(tiled_copy.tiler_mn[1])
+    ref_layout_MN = cute.composition(
+        ref_layout, cute.make_layout((tile_M_size, tile_N_size))
+    )  # (tile_M, tile_N) -> tv_idx
+
+    num_warps = cute.size(tiled_copy) // cute.arch.WARP_SIZE
+
+    # tv2lane: tv_idx -> lane_idx  (lane = tv_idx % 32)
+    tv2lane = cute.make_layout((cute.arch.WARP_SIZE, num_warps, 1), stride=(1, 0, 0))
+    ref2lane = cute.composition(tv2lane, ref_layout_MN)  # (tile_M, tile_N) -> lane_idx
+    # select mode [0] = M part, [1] = N part; filter removes stride-0
+    lane_M = cute.filter(cute.select(ref2lane, [0]))  # lane_m -> lane_idx
+    lane_N = cute.filter(cute.select(ref2lane, [1]))  # lane_n -> lane_idx
+    lane_layout_MN = layout_utils.concat_layout(lane_M, lane_N)  # (lane_M, lane_N) -> lane_idx
+
+    # tv2warp: tv_idx -> warp_idx  (warp = tv_idx / 32)
+    tv2warp = cute.make_layout((cute.arch.WARP_SIZE, num_warps, 1), stride=(0, 1, 0))
+    ref2warp = cute.composition(tv2warp, ref_layout_MN)  # (tile_M, tile_N) -> warp_idx
+    warp_M = cute.filter(cute.select(ref2warp, [0]))  # warp_m -> warp_idx
+    warp_N = cute.filter(cute.select(ref2warp, [1]))  # warp_n -> warp_idx
+    warp_layout_MN = layout_utils.concat_layout(warp_M, warp_N)  # (warp_M, warp_N) -> warp_idx
+
+    return lane_layout_MN, warp_layout_MN
+
+
+class EpiSmemBytes(NamedTuple):
+    """Shared-memory accounting for one epilogue op.
+
+    unstaged: allocated once per CTA tile.
+    d_stage: allocated per D/store epilogue stage.
+    c_stage: allocated per C/load epilogue stage.
+    """
+
+    unstaged: int = 0
+    d_stage: int = 0
+    c_stage: int = 0
+
+    def __add__(self, other):
+        return EpiSmemBytes(
+            self.unstaged + other.unstaged,
+            self.d_stage + other.d_stage,
+            self.c_stage + other.c_stage,
+        )
+
+    def __radd__(self, other):
+        if other == 0:
+            return self
+        return self.__add__(other)
+
+
+LOCAL_REDUCE_FRAGMENT_WIDTH = 32
+
+
+def grouped_local_reduce_uses_smem(axis: int, group: int) -> bool:
+    """Return whether a grouped-M reduction crosses lane fragments."""
+    return axis == 0 and group > LOCAL_REDUCE_FRAGMENT_WIDTH
+
+
+class EpiOp:
+    """Base class for composable epilogue operations."""
+
+    def __init__(self, name):
+        self.name = name
+
+    # --- Host-side: args → params ---
+    def param_fields(self):
+        """Return [(field_name, type, default), ...] for auto-generating EpilogueParams.
+        Must match the keys returned by to_params()."""
+        return []
+
+    def to_params(self, gemm, args):
+        """Convert this op's arg field(s) to param dict entries.
+        Returns dict of {param_name: value}. Like EVT's to_underlying_arguments."""
+        return {}
+
+    def epi_m_major_score(self, arg_tensor, gemm):
+        """Preference for epilogue subtile order. Positive prefers M-major, negative N-major."""
+        return 0
+
+    # --- Host-side: smem allocation ---
+    def smem_bytes(self, arg_tensor, cta_tile_shape_mnk, epi_tile, warp_shape_mnk=None):
+        """Bytes of smem needed by unstaged / D-stage / C-stage storage."""
+        return EpiSmemBytes()
+
+    def smem_struct_field(self, gemm, params):
+        """Return (field_name, field_type) for @cute.struct, or None if no smem needed.
+        params is the full EpilogueParams object."""
+        return None
+
+    def get_smem_tensor(self, gemm, params, storage_epi):
+        """Extract smem tensor from storage.epi. Returns tensor or None.
+        params is the full EpilogueParams object."""
+        return None
+
+    def tma_atoms(self, gemm, params):
+        """Return list of TMA atoms for this op."""
+        return []
+
+    def is_tile_load(self):
+        """Whether this op is a tile-sized epilogue input loaded through the C pipeline."""
+        return False
+
+    def load_g2s_copy_fn(
+        self,
+        gemm,
+        params,
+        smem_tensor,
+        tile_coord_mnkl,
+        varlen_manager,
+        epi_pipeline,
+    ):
+        """Return a per-subtile gmem->smem copy function, or None."""
+        return None
+
+    # --- Device-side: kernel execution ---
+    @cute.jit
+    def begin(self, gemm, param, smem_tensor, ctx):
+        """One-time per-tile setup. Returns state for begin_loop."""
+        return None
+
+    def begin_loop(self, gemm, state, epi_coord):
+        """Per-subtile extraction. Returns value for epi_visit_subtile."""
+        return state
+
+    @cute.jit
+    def load_s2r(self, gemm, param, state, stage_idx):
+        """Issue this op's tile-load smem->register copy for one epilogue stage."""
+        pass
+
+    def end_loop(
+        self,
+        gemm,
+        param,
+        state,
+        epi_coord,
+        epi_tile,
+        tiled_copy_t2r,
+        tiled_copy_r2s,
+        tile_coord_mnkl,
+        varlen_manager,
+        tidx,
+    ):
+        """Per-subtile cleanup after epi_visit_subtile."""
+        pass
+
+    def needs_async_fence(self):
+        """Whether this op issues async copies that need a fence."""
+        return False
+
+    def end(
+        self,
+        gemm,
+        param,
+        state,
+        epi_tile,
+        tiled_copy_t2r,
+        tiled_copy_r2s,
+        tile_coord_mnkl,
+        varlen_manager,
+        tidx,
+    ):
+        """Cleanup after all subtiles (reductions, direct writes)."""
+        pass
+
+
+class Scalar(EpiOp):
+    """Loads a scalar value or device pointer once per tile. No smem."""
+
+    def __init__(self, name, dtype=None):
+        super().__init__(name)
+        self.dtype = dtype
+
+    def param_fields(self):
+        return [(self.name, object, None)]
+
+    def to_params(self, gemm, args):
+        return {self.name: getattr(args, self.name)}
+
+    @cute.jit
+    def begin(self, gemm, param, smem_tensor, ctx):
+        if const_expr(self.dtype is not None):
+            return utils.load_scalar_or_pointer(param, dtype=self.dtype)
+        return utils.load_scalar_or_pointer(param)
+
+
+class VecLoad(EpiOp):
+    """Base class for broadcast vector loads (row or col) via cp_async.
+
+    Subclasses set `dim` to 0 (M/col) or 1 (N/row) and override `_get_gmem_vec`
+    for varlen handling.
+    """
+
+    dim = None  # 0 for col (M), 1 for row (N)
+    convert_to_acc_dtype = True
+
+    def param_fields(self):
+        return [(self.name, object, None)]
+
+    def to_params(self, gemm, args):
+        return {self.name: assume_stride_divisibility(getattr(args, self.name))}
+
+    def _tile_size(self, cta_tile_shape_mnk):
+        return cta_tile_shape_mnk[self.dim]
+
+    def _broadcast_stride(self):
+        # Row: stride (0,1) — broadcast along M. Col: stride (1,0) — broadcast along N.
+        return (0, 1) if self.dim == 1 else (1, 0)
+
+    def _tile_dim(self, ctx):
+        return ctx.tile_N if self.dim == 1 else ctx.tile_M
+
+    def _coord_idx(self):
+        return 1 if self.dim == 1 else 0
+
+    def smem_bytes(self, arg_tensor, cta_tile_shape_mnk, epi_tile, warp_shape_mnk=None):
+        return EpiSmemBytes(
+            unstaged=self._tile_size(cta_tile_shape_mnk) * (arg_tensor.element_type.width // 8)
+        )
+
+    def smem_struct_field(self, gemm, params):
+        tensor = getattr(params, self.name)
+        size = self._tile_size(gemm.cta_tile_shape_mnk)
+        return (
+            f"s_{self.name}",
+            cute.struct.Align[cute.struct.MemRange[tensor.element_type, size], 16],
+        )
+
+    def get_smem_tensor(self, gemm, params, storage_epi):
+        return getattr(storage_epi, f"s_{self.name}").get_tensor(
+            cute.make_layout(self._tile_size(gemm.cta_tile_shape_mnk))
+        )
+
+    def needs_async_fence(self):
+        return True
+
+    def epi_m_major_score(self, arg_tensor, gemm):
+        # It costs more registers (say 4x) to keep rowvec in register vs keeping colvec in register
+        return 4 if self.dim == 1 else -1
+
+    def _get_gmem_vec(self, param, ctx):
+        """Get the global memory vector for this tile. Override for varlen."""
+        return param[ctx.batch_idx, None]
+
+    @cute.jit
+    def begin(self, gemm, param, smem_tensor, ctx):
+        dtype = param.element_type
+        num_copy_elems = const_expr(max(32, dtype.width)) // dtype.width
+        thr_copy = copy_utils.tiled_copy_1d(
+            dtype, ctx.num_epi_threads, num_copy_elems, is_async=True
+        ).get_slice(ctx.tidx)
+        mVec = self._get_gmem_vec(param, ctx)
+        tile_dim = self._tile_dim(ctx)
+        coord_idx = ctx.tile_coord_mnkl[self._coord_idx()]
+        gVec = cute.local_tile(mVec, (tile_dim,), (coord_idx,))
+        tVgV = thr_copy.partition_S(gVec)
+        tVsV = thr_copy.partition_D(smem_tensor)
+        tVcV = thr_copy.partition_S(cute.make_identity_tensor(tile_dim))
+        limit = min(cute.size(mVec, mode=[0]) - coord_idx * tile_dim, tile_dim)
+        for m in cutlass.range(cute.size(tVsV.shape[1]), unroll_full=True):
+            if tVcV[0, m] < tile_dim:  # Guard to avoid writing beyond the smem we've allocated
+                pred = cute.make_rmem_tensor(1, Boolean)
+                pred[0] = tVcV[0, m] < limit
+                cute.copy(thr_copy, tVgV[None, m], tVsV[None, m], pred=pred)
+        tDsV = ctx.partition_for_epilogue_fn(
+            cute.make_tensor(
+                smem_tensor.iterator,
+                cute.make_layout((ctx.tile_M, ctx.tile_N), stride=self._broadcast_stride()),
+            )
+        )
+        if const_expr(ctx.tiled_copy_t2r is not None):
+            tDsV = ctx.tiled_copy_r2s.retile(tDsV)
+        # Pre-allocate register tensor reused across begin_loop calls
+        tDsV_sub = cute.group_modes(tDsV, 3, cute.rank(tDsV))[None, None, None, 0]
+        register_dtype = (
+            gemm.acc_dtype
+            if const_expr(self.convert_to_acc_dtype)
+            else tDsV_sub.element_type
+        )
+        tDrV_cvt = cute.make_rmem_tensor(tDsV_sub.layout, register_dtype)
+        return [tDsV, tDrV_cvt]
+
+    @cute.jit
+    def begin_loop(self, gemm, state, epi_coord):
+        tDsV, tDrV_cvt = state[0], state[1]
+        should_load = Boolean(True)
+        if const_expr(self.dim == 1):
+            if const_expr(gemm.epi_m_major):
+                should_load = epi_coord[0] == 0
+        else:
+            if const_expr(not gemm.epi_m_major):
+                should_load = epi_coord[1] == 0
+        if should_load:
+            tDsV_cur = cute.group_modes(tDsV, 3, cute.rank(tDsV))[None, None, None, epi_coord]
+            tDrV = cute.make_rmem_tensor(tDsV_cur.layout, tDsV_cur.element_type)
+            cute.autovec_copy(cute.filter_zeros(tDsV_cur), cute.filter_zeros(tDrV))
+            if const_expr(self.convert_to_acc_dtype):
+                tDrV_cvt.store(tDrV.load().to(gemm.acc_dtype))
+            else:
+                tDrV_cvt.store(tDrV.load())
+        return tDrV_cvt
+
+
+class RowVecLoad(VecLoad):
+    """Loads a row vector (N,) via cp_async, broadcasts along M with stride (0,1)."""
+
+    dim = 1
+
+
+class ColVecLoad(VecLoad):
+    """Loads a col vector (M,) via cp_async, broadcasts along N with stride (1,0).
+
+    Optimization: with N-major subtile loop, consecutive epi_n iterations for the same
+    epi_m share the same column data. The smem→register copy only runs when epi_n == 0.
+    Supports varlen_m via domain_offset.
+    """
+
+    dim = 0
+
+    @cute.jit
+    def _get_gmem_vec(self, param, ctx):
+        if const_expr(not ctx.varlen_manager.varlen_m):
+            mVec = param[ctx.batch_idx, None]
+        else:
+            mVec = cute.domain_offset(
+                (ctx.varlen_manager.params.cu_seqlens_m[ctx.batch_idx],), param
+            )
+        return mVec
+
+    @cute.jit
+    def begin(self, gemm, param, smem_tensor, ctx):
+        dtype = param.element_type
+        num_copy_elems = const_expr(max(32, dtype.width)) // dtype.width
+        thr_copy = copy_utils.tiled_copy_1d(
+            dtype, ctx.num_epi_threads, num_copy_elems, is_async=True
+        ).get_slice(ctx.tidx)
+        mVec = self._get_gmem_vec(param, ctx)
+        tile_dim = self._tile_dim(ctx)
+        coord_idx = ctx.tile_coord_mnkl[self._coord_idx()]
+        gVec = cute.local_tile(mVec, (tile_dim,), (coord_idx,))
+        tVgV = thr_copy.partition_S(gVec)
+        tVsV = thr_copy.partition_D(smem_tensor)
+        tVcV = thr_copy.partition_S(cute.make_identity_tensor(tile_dim))
+        # ColVec uses varlen-aware limit
+        limit = min(
+            ctx.varlen_manager.len_m(ctx.batch_idx) - coord_idx * tile_dim,
+            tile_dim,
+        )
+        for m in cutlass.range(cute.size(tVsV.shape[1]), unroll_full=True):
+            if tVcV[0, m] < tile_dim:  # Guard to avoid writing beyond the smem we've allocated
+                pred = cute.make_rmem_tensor(1, Boolean)
+                pred[0] = tVcV[0, m] < limit
+                cute.copy(thr_copy, tVgV[None, m], tVsV[None, m], pred=pred)
+        tDsV = ctx.partition_for_epilogue_fn(
+            cute.make_tensor(
+                smem_tensor.iterator,
+                cute.make_layout((ctx.tile_M, ctx.tile_N), stride=self._broadcast_stride()),
+            )
+        )
+        if const_expr(ctx.tiled_copy_t2r is not None):
+            tDsV = ctx.tiled_copy_r2s.retile(tDsV)
+        # Pre-allocate register tensor reused across begin_loop calls
+        tDsV_sub = cute.group_modes(tDsV, 3, cute.rank(tDsV))[None, None, None, 0]
+        register_dtype = (
+            gemm.acc_dtype
+            if const_expr(self.convert_to_acc_dtype)
+            else tDsV_sub.element_type
+        )
+        tDrV_cvt = cute.make_rmem_tensor(tDsV_sub.layout, register_dtype)
+        return [tDsV, tDrV_cvt]
+
+
+class VecTupleLoad(EpiOp):
+    vec_op_cls = VecLoad
+
+    def param_fields(self):
+        return [(self.name, object, None)]
+
+    def to_params(self, gemm, args):
+        tensors = getattr(args, self.name)
+        if tensors is None:
+            return {self.name: None}
+        return {self.name: tuple(assume_stride_divisibility(tensor) for tensor in tensors)}
+
+    def smem_bytes(self, arg_tensor, cta_tile_shape_mnk, epi_tile, warp_shape_mnk=None):
+        return sum(
+            (
+                self.vec_op_cls(f"{self.name}{i}").smem_bytes(
+                    tensor, cta_tile_shape_mnk, epi_tile, warp_shape_mnk
+                )
+                for i, tensor in enumerate(arg_tensor)
+            ),
+            EpiSmemBytes(),
+        )
+
+    def smem_struct_field(self, gemm, params):
+        annotations = {}
+        for i, tensor in enumerate(getattr(params, self.name)):
+            size = self.vec_op_cls(f"{self.name}{i}")._tile_size(gemm.cta_tile_shape_mnk)
+            annotations[f"v{i}"] = cute.struct.Align[
+                cute.struct.MemRange[tensor.element_type, size], 16
+            ]
+        storage = type(f"{self.name}Storage", (), {"__annotations__": annotations})
+        return (f"s_{self.name}", cute.struct(storage))
+
+    def get_smem_tensor(self, gemm, params, storage_epi):
+        storage = getattr(storage_epi, f"s_{self.name}")
+        return tuple(
+            getattr(storage, f"v{i}").get_tensor(
+                cute.make_layout(
+                    self.vec_op_cls(f"{self.name}{i}")._tile_size(gemm.cta_tile_shape_mnk)
+                )
+            )
+            for i, _ in enumerate(getattr(params, self.name))
+        )
+
+    def needs_async_fence(self):
+        return True
+
+    def epi_m_major_score(self, arg_tensor, gemm):
+        return sum(
+            self.vec_op_cls(f"{self.name}{i}").epi_m_major_score(tensor, gemm)
+            for i, tensor in enumerate(arg_tensor)
+        )
+
+    @cute.jit
+    def begin(self, gemm, param, smem_tensor, ctx):
+        states = []
+        for i, tensor in enumerate(param):
+            states.append(
+                self.vec_op_cls(f"{self.name}{i}").begin(gemm, tensor, smem_tensor[i], ctx)
+            )
+        return tuple(states)
+
+    def begin_loop(self, gemm, state, epi_coord):
+        values = []
+        for i, tensor_state in enumerate(state):
+            values.append(
+                self.vec_op_cls(f"{self.name}{i}").begin_loop(gemm, tensor_state, epi_coord)
+            )
+        return tuple(values)
+
+
+class CapturedRowVecLoad(RowVecLoad):
+    convert_to_acc_dtype = False
+
+
+class CapturedColVecLoad(ColVecLoad):
+    convert_to_acc_dtype = False
+
+
+class RowVecTupleLoad(VecTupleLoad):
+    vec_op_cls = CapturedRowVecLoad
+
+
+class ColVecTupleLoad(VecTupleLoad):
+    vec_op_cls = CapturedColVecLoad
+
+
+class CapturedScalarLoad(EpiOp):
+    """Loads a captured (1,)-shaped tensor's element once per tile. No smem."""
+
+    def param_fields(self):
+        return [(self.name, object, None)]
+
+    def to_params(self, gemm, args):
+        return {self.name: getattr(args, self.name)}
+
+    @cute.jit
+    def begin(self, gemm, param, smem_tensor, ctx):
+        return param.load()
+
+
+class ScalarTupleLoad(EpiOp):
+    """Loads a tuple of captured scalar tensors once per tile. No smem."""
+
+    def param_fields(self):
+        return [(self.name, object, None)]
+
+    def to_params(self, gemm, args):
+        return {self.name: getattr(args, self.name)}
+
+    @cute.jit
+    def begin(self, gemm, param, smem_tensor, ctx):
+        values = []
+        for i, tensor in enumerate(param):
+            values.append(
+                CapturedScalarLoad(f"{self.name}{i}").begin(gemm, tensor, None, ctx)
+            )
+        return tuple(values)
+
+
+class TileStore(EpiOp):
+    """Tile-sized output tensor stored via TMA (e.g. postact).
+
+    Args:
+        name: field name in EpilogueArguments/Params (e.g. "mAuxOut")
+        epi_tile_fn: optional (gemm, epi_tile) -> epi_tile for half-tile (GemmGated)
+    """
+
+    def __init__(self, name, epi_tile_fn=None):
+        super().__init__(name)
+        self.epi_tile_fn = epi_tile_fn
+
+    def _tma_atom_key(self):
+        return f"tma_atom_{self.name}"
+
+    def _smem_layout_key(self):
+        return f"epi_{self.name}_smem_layout_staged"
+
+    def _epi_tile_key(self):
+        return f"epi_tile_{self.name}"
+
+    def param_fields(self):
+        # Defaults are None so EpilogueParams can be constructed when this op is
+        # filtered out (inactive). Active calls always set all four via to_params.
+        return [
+            (self._tma_atom_key(), object, None),
+            (self.name, object, None),
+            (self._smem_layout_key(), object, None),
+            (self._epi_tile_key(), object, None),
+        ]
+
+    def to_params(self, gemm, args):
+        tensors = getattr(args, self.name)
+        epi_tile = self.epi_tile_fn(gemm, gemm.epi_tile) if self.epi_tile_fn else None
+        if isinstance(tensors, tuple):
+            prepared = tuple(
+                setup_epi_tensor(gemm, tensor, epi_tile=epi_tile) for tensor in tensors
+            )
+            return {
+                self._tma_atom_key(): tuple(item[0] for item in prepared),
+                self.name: tuple(item[1] for item in prepared),
+                self._smem_layout_key(): tuple(item[2] for item in prepared),
+                self._epi_tile_key(): tuple(item[3] for item in prepared),
+            }
+        tma_atom, tma_tensor, smem_layout, epi_tile_out = setup_epi_tensor(
+            gemm, tensors, epi_tile=epi_tile
+        )
+        return {
+            self._tma_atom_key(): tma_atom,
+            self.name: tma_tensor,
+            self._smem_layout_key(): smem_layout,
+            self._epi_tile_key(): epi_tile_out,
+        }
+
+    def smem_bytes(self, arg_tensor, cta_tile_shape_mnk, epi_tile, warp_shape_mnk=None):
+        if self.epi_tile_fn is not None:
+            epi_tile = self.epi_tile_fn(None, epi_tile)
+        # epi_tile may contain Layout entries (from SM100's compute_epilogue_tile_shape
+        # fixup path), so extract the int shape first.
+        if isinstance(arg_tensor, tuple):
+            return sum(
+                (
+                    EpiSmemBytes(
+                        d_stage=cute.size(cute.shape(epi_tile))
+                        * (tensor.element_type.width // 8)
+                    )
+                    for tensor in arg_tensor
+                ),
+                EpiSmemBytes(),
+            )
+        return EpiSmemBytes(
+            d_stage=cute.size(cute.shape(epi_tile)) * (arg_tensor.element_type.width // 8)
+        )
+
+    def smem_struct_field(self, gemm, params):
+        smem_layout = getattr(params, self._smem_layout_key())
+        if isinstance(smem_layout, tuple):
+            annotations = {}
+            for i, layout in enumerate(smem_layout):
+                annotations[f"v{i}"] = cute.struct.Align[
+                    cute.struct.MemRange[
+                        gemm.aux_out_dtypes[i],
+                        cute.cosize(layout),
+                    ],
+                    gemm.buffer_align_bytes,
+                ]
+            storage = type(f"{self.name}Storage", (), {"__annotations__": annotations})
+            return (f"s_{self.name}", cute.struct(storage))
+        return (
+            f"s_{self.name}",
+            cute.struct.Align[
+                cute.struct.MemRange[
+                    gemm.aux_out_dtype,
+                    cute.cosize(smem_layout),
+                ],
+                gemm.buffer_align_bytes,
+            ],
+        )
+
+    def get_smem_tensor(self, gemm, params, storage_epi):
+        smem_layout = getattr(params, self._smem_layout_key())
+        storage = getattr(storage_epi, f"s_{self.name}")
+        if isinstance(smem_layout, tuple):
+            return tuple(
+                getattr(storage, f"v{i}").get_tensor(
+                    layout.outer,
+                    swizzle=layout.inner,
+                )
+                for i, layout in enumerate(smem_layout)
+            )
+        return storage.get_tensor(
+            smem_layout.outer,
+            swizzle=smem_layout.inner,
+        )
+
+    def tma_atoms(self, gemm, params):
+        tma_atom = getattr(params, self._tma_atom_key())
+        return list(tma_atom) if isinstance(tma_atom, tuple) else [tma_atom]
+
+
+class _TileLoadState(NamedTuple):
+    """Per-tile register state produced by TileLoad.begin and consumed by load_s2r /
+    begin_loop. tRS_rTile is the register tile partitioned to match tRS_rD's layout;
+    tSR_sTile / tSR_rTile drive the per-stage smem→register copy."""
+
+    tiled_copy_s2r: object
+    tRS_rTile: object
+    tSR_rTile: object
+    tSR_sTile: object
+
+
+class TileLoad(EpiOp):
+    """Tile-sized auxiliary input loaded through the epilogue load pipeline.
+
+    TileLoad uses the same staged gmem->smem->register pipeline as GEMM's C operand,
+    but it is exposed to the epilogue as ``epi_loop_tensors[name]`` instead of as
+    ``tRS_rC``. That lets custom epilogues consume extra MxN tensors without using
+    the GEMM C argument.
+
+    Its shared memory is accounted as ``EpiSmemBytes.c_stage``, so it is allocated
+    per epilogue load stage. Multiple TileLoads are supported: each has its own TMA
+    descriptor and smem buffer, and the pipeline transaction count includes C plus
+    all enabled TileLoad buffers. Supported on SM90, SM100, and SM120.
+    """
+
+    def __init__(self, name, epi_tile_fn=None):
+        super().__init__(name)
+        self.epi_tile_fn = epi_tile_fn
+
+    def _tma_atom_key(self):
+        return f"tma_atom_{self.name}"
+
+    def _smem_layout_key(self):
+        return f"epi_{self.name}_smem_layout_staged"
+
+    def _epi_tile_key(self):
+        return f"epi_tile_{self.name}"
+
+    # The original LayoutEnum and element_type can't be recovered from the
+    # TMA-prepared tensor that ends up in params (`from_tensor` returns a typing
+    # annotation post-TMA, not a Numeric class). We stash both on the gemm at
+    # to_params time and read them back in begin(). The dtype is also exposed on
+    # the params dataclass for smem_struct_field.
+    def _layout_gemm_attr(self):
+        return f"_tile_load_layout_{self.name}"
+
+    def _dtype_gemm_attr(self):
+        return f"_tile_load_dtype_{self.name}"
+
+    def _dtype_field(self):
+        return f"{self.name}_dtype"
+
+    def param_fields(self):
+        # Defaults are None so EpilogueParams can be constructed when this op is
+        # filtered out (inactive). Active calls always set all five via to_params.
+        return [
+            (self._tma_atom_key(), object, None),
+            (self.name, object, None),
+            (self._smem_layout_key(), object, None),
+            (self._epi_tile_key(), object, None),
+            (self._dtype_field(), object, None),
+        ]
+
+    def to_params(self, gemm, args):
+        tensor = getattr(args, self.name)
+        setattr(gemm, self._layout_gemm_attr(), cutlass.utils.LayoutEnum.from_tensor(tensor))
+        setattr(gemm, self._dtype_gemm_attr(), tensor.element_type)
+        epi_tile = self.epi_tile_fn(gemm, gemm.epi_tile) if self.epi_tile_fn else None
+        tma_atom, tma_tensor, smem_layout, epi_tile_out = setup_epi_tensor(
+            gemm, tensor, epi_tile=epi_tile, op_type="load", stage=gemm.epi_c_stage
+        )
+        return {
+            self._tma_atom_key(): tma_atom,
+            self.name: tma_tensor,
+            self._smem_layout_key(): smem_layout,
+            self._epi_tile_key(): epi_tile_out,
+            self._dtype_field(): tensor.element_type,
+        }
+
+    def is_tile_load(self):
+        return True
+
+    def smem_bytes(self, arg_tensor, cta_tile_shape_mnk, epi_tile, warp_shape_mnk=None):
+        if self.epi_tile_fn is not None:
+            epi_tile = self.epi_tile_fn(None, epi_tile)
+        # epi_tile may contain Layout entries from SM100's compute_epilogue_tile_shape
+        # fixup; extract the int shape first.
+        return EpiSmemBytes(
+            c_stage=cute.size(cute.shape(epi_tile)) * (arg_tensor.element_type.width // 8)
+        )
+
+    def smem_struct_field(self, gemm, params):
+        smem_layout = getattr(params, self._smem_layout_key())
+        dtype = getattr(params, self._dtype_field())
+        return (
+            f"s_{self.name}",
+            cute.struct.Align[
+                cute.struct.MemRange[dtype, cute.cosize(smem_layout)],
+                gemm.buffer_align_bytes,
+            ],
+        )
+
+    def get_smem_tensor(self, gemm, params, storage_epi):
+        smem_layout = getattr(params, self._smem_layout_key())
+        return getattr(storage_epi, f"s_{self.name}").get_tensor(
+            smem_layout.outer,
+            swizzle=smem_layout.inner,
+        )
+
+    def tma_atoms(self, gemm, params):
+        return [getattr(params, self._tma_atom_key())]
+
+    def load_g2s_copy_fn(
+        self,
+        gemm,
+        params,
+        smem_tensor,
+        tile_coord_mnkl,
+        varlen_manager,
+        epi_pipeline,
+    ):
+        tensor = getattr(params, self.name)
+        batch_idx = tile_coord_mnkl[3]
+        copy_tile_fn, _, _ = gemm.epilog_gmem_copy_and_partition(
+            getattr(params, self._tma_atom_key()),
+            varlen_manager.offset_batch_epi(tensor, batch_idx),
+            gemm.cta_tile_shape_mnk[:2],
+            getattr(params, self._epi_tile_key()),
+            smem_tensor,
+            tile_coord_mnkl,
+        )
+        return copy_utils.tma_producer_copy_fn(copy_tile_fn, epi_pipeline)
+
+    @cute.jit
+    def begin(self, gemm, param, smem_tensor, ctx):
+        assert gemm.arch in (90, 100, 120), "TileLoad requires the SM90/SM100/SM120 epilogue path"
+        assert ctx.tRS_rD_layout is not None
+        smem_load_ref = ctx.tiled_copy_t2r if const_expr(gemm.arch == 100) else gemm.tiled_mma
+        tiled_copy_s2r, tRS_rTile, tSR_rTile, tSR_sTile = gemm.epilog_smem_load_and_partition(
+            smem_load_ref,
+            getattr(gemm, self._layout_gemm_attr()),
+            getattr(gemm, self._dtype_gemm_attr()),
+            smem_tensor,
+            ctx.tRS_rD_layout,
+            ctx.tidx,
+        )
+        # Shape: (s2r-copy-handle, register-tile-as-rD-layout, smem→r retile target,
+        # smem→r staged source). begin_loop returns tRS_rTile; load_s2r uses the rest.
+        return _TileLoadState(tiled_copy_s2r, tRS_rTile, tSR_rTile, tSR_sTile)
+
+    @cute.jit
+    def load_s2r(self, gemm, param, state, stage_idx):
+        cute.copy(
+            state.tiled_copy_s2r,
+            state.tSR_sTile[None, None, None, stage_idx],
+            state.tSR_rTile,
+        )
+
+    @cute.jit
+    def begin_loop(self, gemm, state, epi_coord):
+        return state.tRS_rTile
+
+
+class TileTupleLoad(EpiOp):
+    def _tma_atoms_key(self):
+        return f"tma_atoms_{self.name}"
+
+    def _smem_layouts_key(self):
+        return f"epi_{self.name}_smem_layouts_staged"
+
+    def _epi_tiles_key(self):
+        return f"epi_tiles_{self.name}"
+
+    def _layout_gemm_attr(self, index):
+        return f"_tile_tuple_load_layout_{self.name}_{index}"
+
+    def _dtype_gemm_attr(self, index):
+        return f"_tile_tuple_load_dtype_{self.name}_{index}"
+
+    def param_fields(self):
+        return [
+            (self._tma_atoms_key(), object, None),
+            (self.name, object, None),
+            (self._smem_layouts_key(), object, None),
+            (self._epi_tiles_key(), object, None),
+        ]
+
+    def to_params(self, gemm, args):
+        tensors = getattr(args, self.name)
+        tma_atoms, tma_tensors, smem_layouts, epi_tiles = [], [], [], []
+        for i, tensor in enumerate(tensors):
+            setattr(gemm, self._layout_gemm_attr(i), cutlass.utils.LayoutEnum.from_tensor(tensor))
+            setattr(gemm, self._dtype_gemm_attr(i), tensor.element_type)
+            tma_atom, tma_tensor, smem_layout, epi_tile = setup_epi_tensor(
+                gemm, tensor, epi_tile=None, op_type="load", stage=gemm.epi_c_stage
+            )
+            tma_atoms.append(tma_atom)
+            tma_tensors.append(tma_tensor)
+            smem_layouts.append(smem_layout)
+            epi_tiles.append(epi_tile)
+        return {
+            self._tma_atoms_key(): tuple(tma_atoms),
+            self.name: tuple(tma_tensors),
+            self._smem_layouts_key(): tuple(smem_layouts),
+            self._epi_tiles_key(): tuple(epi_tiles),
+        }
+
+    def is_tile_load(self):
+        return True
+
+    def smem_bytes(self, arg_tensor, cta_tile_shape_mnk, epi_tile, warp_shape_mnk=None):
+        return sum(
+            (
+                EpiSmemBytes(
+                    c_stage=cute.size(cute.shape(epi_tile)) * tensor.element_type.width // 8
+                )
+                for tensor in arg_tensor
+            ),
+            EpiSmemBytes(),
+        )
+
+    def smem_struct_field(self, gemm, params):
+        annotations = {}
+        for i, smem_layout in enumerate(getattr(params, self._smem_layouts_key())):
+            annotations[f"v{i}"] = cute.struct.Align[
+                cute.struct.MemRange[
+                    getattr(gemm, self._dtype_gemm_attr(i)), cute.cosize(smem_layout)
+                ],
+                gemm.buffer_align_bytes,
+            ]
+        storage = type(f"{self.name}Storage", (), {"__annotations__": annotations})
+        return (f"s_{self.name}", cute.struct(storage))
+
+    def get_smem_tensor(self, gemm, params, storage_epi):
+        storage = getattr(storage_epi, f"s_{self.name}")
+        return tuple(
+            getattr(storage, f"v{i}").get_tensor(smem_layout.outer, swizzle=smem_layout.inner)
+            for i, smem_layout in enumerate(getattr(params, self._smem_layouts_key()))
+        )
+
+    def tma_atoms(self, gemm, params):
+        return list(getattr(params, self._tma_atoms_key()))
+
+    def load_g2s_copy_fn(self, gemm, params, smem_tensor, tile_coord_mnkl, varlen_manager, epi_pipeline):
+        copy_fns = []
+        for tma_atom, tensor, epi_tile, smem in zip(
+            getattr(params, self._tma_atoms_key()),
+            getattr(params, self.name),
+            getattr(params, self._epi_tiles_key()),
+            smem_tensor,
+        ):
+            copy_tile_fn, _, _ = gemm.epilog_gmem_copy_and_partition(
+                tma_atom,
+                varlen_manager.offset_batch_epi(tensor, tile_coord_mnkl[3]),
+                gemm.cta_tile_shape_mnk[:2],
+                epi_tile,
+                smem,
+                tile_coord_mnkl,
+            )
+            copy_fns.append(copy_utils.tma_producer_copy_fn(copy_tile_fn, epi_pipeline))
+        return copy_utils.chain_tma_producer_copy_fns(tuple(copy_fns))
+
+    @cute.jit
+    def begin(self, gemm, param, smem_tensor, ctx):
+        assert gemm.arch in (90, 100, 120), "TileTupleLoad requires the SM90/SM100/SM120 epilogue path"
+        states = []
+        smem_load_ref = ctx.tiled_copy_t2r if const_expr(gemm.arch == 100) else gemm.tiled_mma
+        for i, smem in enumerate(smem_tensor):
+            tiled_copy_s2r, tRS_rTile, tSR_rTile, tSR_sTile = gemm.epilog_smem_load_and_partition(
+                smem_load_ref,
+                getattr(gemm, self._layout_gemm_attr(i)),
+                getattr(gemm, self._dtype_gemm_attr(i)),
+                smem,
+                ctx.tRS_rD_layout,
+                ctx.tidx,
+            )
+            states.append(_TileLoadState(tiled_copy_s2r, tRS_rTile, tSR_rTile, tSR_sTile))
+        return tuple(states)
+
+    @cute.jit
+    def load_s2r(self, gemm, param, state, stage_idx):
+        for tile_state in state:
+            cute.copy(
+                tile_state.tiled_copy_s2r,
+                tile_state.tSR_sTile[None, None, None, stage_idx],
+                tile_state.tSR_rTile,
+            )
+
+    @cute.jit
+    def begin_loop(self, gemm, state, epi_coord):
+        return tuple(tile_state.tRS_rTile for tile_state in state)
+
+
+@cute.jit
+def vec_multiply(gemm, tRS_rD, tDrColVec, tDrRowVec):
+    """Multiply tRS_rD by colvec and/or rowvec in-place. Uses packed f32x2 on SM100."""
+    if const_expr(tDrColVec is not None):
+        if const_expr(gemm.arch != 100):
+            for i in cutlass.range(cute.size(tDrColVec), unroll_full=True):
+                tRS_rD[i] *= tDrColVec[i]
+        else:
+            for i in cutlass.range(cute.size(tRS_rD) // 2, unroll_full=True):
+                tRS_rD[2 * i], tRS_rD[2 * i + 1] = cute.arch.mul_packed_f32x2(
+                    (tRS_rD[2 * i], tRS_rD[2 * i + 1]),
+                    (tDrColVec[2 * i], tDrColVec[2 * i + 1]),
+                )
+    if const_expr(tDrRowVec is not None):
+        if const_expr(gemm.arch != 100):
+            for i in cutlass.range(cute.size(tDrRowVec), unroll_full=True):
+                tRS_rD[i] *= tDrRowVec[i]
+        else:
+            for i in cutlass.range(cute.size(tRS_rD) // 2, unroll_full=True):
+                tRS_rD[2 * i], tRS_rD[2 * i + 1] = cute.arch.mul_packed_f32x2(
+                    (tRS_rD[2 * i], tRS_rD[2 * i + 1]),
+                    (tDrRowVec[2 * i], tDrRowVec[2 * i + 1]),
+                )
+
+
+@cute.jit
+def colvec_reduce_accumulate(gemm, tDrReduce, tRS_rInput, transform_fn=None, rScale=None):
+    """Accumulate transform_fn(input) or input * rScale into a ColVecReduce buffer.
+
+    If transform_fn is provided, accumulates transform_fn(input[i]).
+    If rScale is provided, accumulates input[i] * rScale[i] (uses packed mul/fma for SM100).
+    If neither, accumulates input directly (identity).
+    """
+    if const_expr(tDrReduce is not None):
+        if const_expr(transform_fn is None):
+            transform_fn = lambda x: x
+        if const_expr(gemm.arch != 100):
+            for i in cutlass.range(cute.size(tDrReduce), unroll_full=True):
+                val = transform_fn(tRS_rInput[i])
+                tDrReduce[i] += val * rScale[i] if const_expr(rScale is not None) else val
+        else:
+            tDrReduce_mn = layout_utils.convert_layout_zero_stride(tDrReduce, tDrReduce.layout)
+            tRS_rInput_mn = layout_utils.convert_layout_zero_stride(tRS_rInput, tDrReduce.layout)
+            if const_expr(rScale is not None):
+                rScale_mn = layout_utils.convert_layout_zero_stride(rScale, tDrReduce.layout)
+            for m in cutlass.range(cute.size(tDrReduce_mn, mode=[0]), unroll_full=True):
+                inp = lambda n: (tRS_rInput_mn[m, 2 * n], tRS_rInput_mn[m, 2 * n + 1])
+                val0 = transform_fn(inp(0))
+                assert cute.size(tDrReduce_mn, mode=[1]) % 2 == 0
+                if const_expr(rScale is not None):
+                    row_sum = cute.arch.mul_packed_f32x2(val0, (rScale_mn[m, 0], rScale_mn[m, 1]))
+                else:
+                    row_sum = val0
+                for n in cutlass.range(1, cute.size(tDrReduce_mn, mode=[1]) // 2, unroll_full=True):
+                    val = transform_fn(inp(n))
+                    if const_expr(rScale is not None):
+                        row_sum = cute.arch.fma_packed_f32x2(
+                            val, (rScale_mn[m, 2 * n], rScale_mn[m, 2 * n + 1]), row_sum
+                        )
+                    else:
+                        row_sum = cute.arch.add_packed_f32x2(val, row_sum)
+                tDrReduce_mn[m, 0] += row_sum[0] + row_sum[1]
+
+
+@cute.jit
+def rowvec_reduce_accumulate(gemm, tDrReduce, tRS_rInput, transform_fn=None, rScale=None):
+    """Accumulate transform_fn(input) or input * rScale into a RowVecReduce buffer.
+
+    Reduces along M dimension, keeping N. The zero-stride layout on M ensures
+    elements at different M positions but same N column accumulate correctly.
+    """
+    if const_expr(tDrReduce is not None):
+        if const_expr(transform_fn is None):
+            transform_fn = lambda x: x
+        if const_expr(gemm.arch != 100):
+            for i in cutlass.range(cute.size(tDrReduce), unroll_full=True):
+                val = transform_fn(tRS_rInput[i])
+                tDrReduce[i] += val * rScale[i] if const_expr(rScale is not None) else val
+        else:
+            # Keep CUTLASS's linear fragment indexing, but use packed f32x2 arithmetic
+            # for any transform that accepts and returns an f32x2 tuple.
+            # We have to be careful to avoid tDrReduce[2 * i] and tDrReduce[2 * i + 1] aliasing
+            # each other. For SM100, tDrReduce has layout ((32,1),1,1):((1,0),0,0) or
+            # (((2,2,4),1),2,1):(((1,0,8),0),0,0), so this works. But it's error-prone.
+            for i in cutlass.range(cute.size(tRS_rInput) // 2, unroll_full=True):
+                acc = (tDrReduce[2 * i], tDrReduce[2 * i + 1])
+                val = (tRS_rInput[2 * i], tRS_rInput[2 * i + 1])
+                val = transform_fn(val)
+                if const_expr(rScale is not None):
+                    scale = (rScale[2 * i], rScale[2 * i + 1])
+                    tDrReduce[2 * i], tDrReduce[2 * i + 1] = cute.arch.fma_packed_f32x2(
+                        val, scale, acc
+                    )
+                else:
+                    tDrReduce[2 * i], tDrReduce[2 * i + 1] = cute.arch.add_packed_f32x2(val, acc)
+            if const_expr(cute.size(tRS_rInput) % 2 != 0):
+                i = cute.size(tRS_rInput) - 1
+                val = transform_fn(tRS_rInput[i])
+                tDrReduce[i] += val * rScale[i] if const_expr(rScale is not None) else val
+
+
+class VecReduce(EpiOp):
+    """Base class for row/column vector reductions."""
+
+    dim = 0  # 0 for colvec output along M, 1 for rowvec output along N
+    epi_m_major_preference = 0
+
+    def param_fields(self):
+        return [(self.name, object, None)]
+
+    def to_params(self, gemm, args):
+        return {self.name: assume_stride_divisibility(getattr(args, self.name))}
+
+    def epi_m_major_score(self, arg_tensor, gemm):
+        return self.epi_m_major_preference
+
+    def _tile_size(self, cta_tile_shape_mnk):
+        return cta_tile_shape_mnk[self.dim]
+
+    def _broadcast_stride(self):
+        # Col: stride (1,0) broadcasts along N. Row: stride (0,1) broadcasts along M.
+        return (1, 0) if self.dim == 0 else (0, 1)
+
+    def _reduce_dim(self):
+        return 1 - self.dim
+
+    def _smem_warps(self, warp_shape_mnk):
+        warps = warp_shape_mnk[self._reduce_dim()] if warp_shape_mnk is not None else 1
+        return max(warps - 1, 0)
+
+    def _uses_smem(self, gemm):
+        return True
+
+    def smem_bytes(self, arg_tensor, cta_tile_shape_mnk, epi_tile, warp_shape_mnk=None):
+        smem_warps = self._smem_warps(warp_shape_mnk)
+        if smem_warps == 0:
+            return EpiSmemBytes()
+        return EpiSmemBytes(
+            unstaged=self._tile_size(cta_tile_shape_mnk) * smem_warps * (Float32.width // 8)
+        )
+
+    def smem_struct_field(self, gemm, params):
+        smem_warps = self._smem_warps(gemm.epi_smem_warp_shape_mnk())
+        if smem_warps == 0 or not self._uses_smem(gemm):
+            return None
+        size = self._tile_size(gemm.cta_tile_shape_mnk) * smem_warps
+        return (f"s_{self.name}", cute.struct.Align[cute.struct.MemRange[Float32, size], 16])
+
+    def get_smem_tensor(self, gemm, params, storage_epi):
+        smem_warps = self._smem_warps(gemm.epi_smem_warp_shape_mnk())
+        if smem_warps == 0 or not self._uses_smem(gemm):
+            return None
+        return getattr(storage_epi, f"s_{self.name}").get_tensor(
+            cute.make_layout((self._tile_size(gemm.cta_tile_shape_mnk), smem_warps))
+        )
+
+    @cute.jit
+    def begin(self, gemm, param, smem_tensor, ctx):
+        vec_mma_layout = cute.make_layout((ctx.tile_M, ctx.tile_N), stride=self._broadcast_stride())
+        tDrReduce_layout = ctx.partition_for_epilogue_fn(
+            cute.make_rmem_tensor(vec_mma_layout, Float32)
+        ).layout
+        tDrReduce = cute.make_rmem_tensor(tDrReduce_layout, Float32)
+        return (tDrReduce, smem_tensor)
+
+    @cute.jit
+    def begin_loop(self, gemm, state, epi_coord):
+        tDrReduce = state[0]
+        result = tDrReduce[None, None, None, epi_coord[0], epi_coord[1]]
+        if const_expr(epi_coord[self._reduce_dim()] == 0):
+            cute.filter_zeros(result).fill(0.0)
+        return result
+
+
+class _GroupedLocalReduceParams(NamedTuple):
+    tensor: object
+    combine_fn: object
+    finalize_fn: object
+    feeds_main: bool
+
+
+class _GroupedLocalReduceFeedState(NamedTuple):
+    lane_layout_MN: object
+    local_reduce: object | None
+
+
+@cute.jit
+def grouped_rowvec_reduce_value(gemm, tRS_rInput, row_state, combine_fn, finalize_fn):
+    """Return same-warp grouped-M reductions broadcast to every row lane.
+
+    Feed-main has no cross-warp replay phase, so ``group`` must fit within the
+    current lane-layout M extent; cross-warp M stitching is only implemented for
+    compressed aux stores.
+    """
+    result = None
+    if const_expr(row_state is not None):
+        group = const_expr(gemm.local_reduce_group)
+        lane_layout_MN = row_state.lane_layout_MN
+        lanes_in_M = cute.size(lane_layout_MN, mode=[0])
+        lanes_in_N = cute.size(lane_layout_MN, mode=[1])
+        assert group <= lanes_in_M
+        assert lanes_in_M % group == 0
+        if const_expr(lanes_in_N > 1):
+            assert lane_layout_MN.stride[1] == 1
+        result = cute.make_rmem_tensor_like(tRS_rInput, tRS_rInput.element_type)
+        cute.autovec_copy(tRS_rInput, result)
+        result_flt = cute.filter_zeros(result)
+        if const_expr(group > 1):
+            for i in cutlass.range(cute.size(result_flt), unroll_full=True):
+                reduction_rows = group // 2
+                while reduction_rows > 0:
+                    result_flt[i] = combine_fn(
+                        result_flt[i],
+                        cute.arch.shuffle_sync_bfly(
+                            result_flt[i],
+                            offset=cute.crd2idx((reduction_rows, 0), lane_layout_MN),
+                        ),
+                    )
+                    reduction_rows = reduction_rows // 2
+        for i in cutlass.range(cute.size(result_flt), unroll_full=True):
+            result_flt[i] = finalize_fn(result_flt[i])
+    return result
+
+
+class GroupedLocalReduce(VecReduce):
+    """Store or broadcast generated grouped local-reduce values."""
+
+    dim = 1
+    epi_m_major_preference = -1
+
+    def _uses_smem(self, gemm):
+        return grouped_local_reduce_uses_smem(
+            gemm.local_reduce_axis, gemm.local_reduce_group
+        )
+
+    def smem_bytes(self, arg_tensor, cta_tile_shape_mnk, epi_tile, warp_shape_mnk=None):
+        return EpiSmemBytes()
+
+    def to_params(self, gemm, args):
+        return {
+            self.name: _GroupedLocalReduceParams(
+                getattr(args, self.name),
+                args.local_reduce_combine_fn,
+                args.local_reduce_finalize_fn,
+                args.local_reduce_feeds_main,
+            )
+        }
+
+    @cute.jit
+    def begin(self, gemm, param, smem_tensor, ctx):
+        result = None
+        if const_expr(param is not None):
+            group = const_expr(gemm.local_reduce_group)
+            axis = const_expr(gemm.local_reduce_axis)
+            tile_M, tile_N = ctx.tile_M, ctx.tile_N
+            tile = tile_N if const_expr(axis == 1) else tile_M
+            assert group != 0 and group <= tile
+            assert tile % group == 0
+            tiled_copy = (
+                ctx.tiled_copy_t2r
+                if ctx.tiled_copy_t2r is not None
+                else ctx.tiled_copy_r2s
+            )
+            if const_expr(gemm.arch == 100 and axis == 1 and group == tile_N):
+                _, warp_layout_MN = _get_lane_warp_layouts(
+                    tiled_copy, ctx.tiled_copy_t2r is None
+                )
+                warps_in_N = const_expr(cute.size(warp_layout_MN, mode=[1]))
+                assert warps_in_N == 1, (
+                    "full-N GroupedLocalReduce requires one epilogue N-warp partition"
+                )
+            if const_expr(param.feeds_main):
+                assert axis == 0
+                lane_layout_MN, _ = _get_lane_warp_layouts(
+                    tiled_copy, ctx.tiled_copy_t2r is None
+                )
+                local_reduce = None
+                if const_expr(param.tensor is not None):
+                    vec_mma_layout = cute.make_layout((ctx.tile_M, ctx.tile_N))
+                    tDrReduce_layout = ctx.partition_for_epilogue_fn(
+                        cute.make_rmem_tensor(vec_mma_layout, Float32)
+                    ).layout
+                    local_reduce = cute.make_rmem_tensor(tDrReduce_layout, Float32)
+                result = _GroupedLocalReduceFeedState(lane_layout_MN, local_reduce)
+            else:
+                vec_mma_layout = cute.make_layout((ctx.tile_M, ctx.tile_N))
+                tDrReduce_layout = ctx.partition_for_epilogue_fn(
+                    cute.make_rmem_tensor(vec_mma_layout, Float32)
+                ).layout
+                result = (cute.make_rmem_tensor(tDrReduce_layout, Float32), smem_tensor)
+        return result
+
+    @cute.jit
+    def begin_loop(self, gemm, state, epi_coord):
+        result = None
+        if const_expr(state is not None):
+            if const_expr(gemm.local_reduce_feeds_main):
+                if const_expr(state.local_reduce is None):
+                    return state
+                tDrReduce_cur = state.local_reduce[
+                    None, None, None, epi_coord[0], epi_coord[1]
+                ]
+                cute.filter_zeros(tDrReduce_cur).fill(0.0)
+                return _GroupedLocalReduceFeedState(
+                    state.lane_layout_MN, tDrReduce_cur
+                )
+            tDrReduce = state[0]
+            result = tDrReduce[None, None, None, epi_coord[0], epi_coord[1]]
+            cute.filter_zeros(result).fill(0.0)
+        return result
+
+    @cute.jit
+    def end_loop(
+        self,
+        gemm,
+        param,
+        state,
+        epi_coord,
+        epi_tile,
+        tiled_copy_t2r,
+        tiled_copy_r2s,
+        tile_coord_mnkl,
+        varlen_manager,
+        tidx,
+    ):
+        if const_expr(param is not None):
+            if const_expr(param.feeds_main and param.tensor is None):
+                return
+            param_tensor = param.tensor
+            combine_fn = const_expr(param.combine_fn)
+            finalize_fn = const_expr(param.finalize_fn)
+            group = const_expr(gemm.local_reduce_group)
+            axis = const_expr(gemm.local_reduce_axis)
+            tDrReduce = state.local_reduce if const_expr(param.feeds_main) else state[0]
+            tDrReduce_cur = tDrReduce[None, None, None, epi_coord[0], epi_coord[1]]
+            tiled_copy = tiled_copy_t2r if tiled_copy_t2r is not None else tiled_copy_r2s
+            partition_for_epilogue_fn = partial(
+                partition_for_epilogue,
+                epi_tile=epi_tile,
+                tiled_copy=tiled_copy,
+                tidx=tidx,
+                reference_src=tiled_copy_t2r is None,
+            )
+            tile_M, tile_N = gemm.cta_tile_shape_mnk[:2]
+            tile = tile_N if const_expr(axis == 1) else tile_M
+            groups_per_cta = const_expr(tile // group)
+            tDcD = partition_for_epilogue_fn(cute.make_identity_tensor((tile_M, tile_N)))
+            tDcD_cur = tDcD[None, None, None, epi_coord[0], epi_coord[1]]
+            tDrReduce_flt = cute.filter_zeros(tDrReduce_cur)
+            tDcD_flt = cute.filter_zeros(tDcD_cur)
+            batch_idx = tile_coord_mnkl[3]
+            limit_m = min(
+                varlen_manager.len_m(batch_idx) - tile_coord_mnkl[0] * tile_M,
+                tile_M,
+            )
+            limit_n = min(cute.size(param_tensor, mode=[2]) - tile_coord_mnkl[1] * tile_N, tile_N)
+            if const_expr(axis == 1):
+                local_fragment_n = const_expr(cute.size(tDrReduce_cur.shape, mode=[0]))
+            if const_expr(axis == 1 and group > local_fragment_n):
+                assert combine_fn is not None
+                assert finalize_fn is not None
+                assert group % local_fragment_n == 0
+                fragments_per_group = const_expr(group // local_fragment_n)
+                if const_expr((epi_coord[1] + 1) % fragments_per_group == 0):
+                    group_start_epi_n = const_expr(epi_coord[1] + 1 - fragments_per_group)
+                    limit_groups = (
+                        param_tensor.shape[2]
+                        if not varlen_manager.varlen_m
+                        else param_tensor.shape[1]
+                    )
+                    if const_expr(not varlen_manager.varlen_m):
+                        mReduce = param_tensor[batch_idx, None, None]
+                    else:
+                        mReduce = cute.domain_offset(
+                            (varlen_manager.params.cu_seqlens_m[batch_idx], None),
+                            param_tensor[None, None],
+                        )
+                    gReduce = cute.local_tile(
+                        mReduce,
+                        (tile_M, groups_per_cta),
+                        (tile_coord_mnkl[0], tile_coord_mnkl[1]),
+                    )
+                    tDrReduce_first = tDrReduce[
+                        None, None, None, epi_coord[0], group_start_epi_n
+                    ]
+                    tDrReduce_first_flt = cute.filter_zeros(tDrReduce_first)
+                    for i in cutlass.range(cute.size(tDrReduce_flt), unroll_full=True):
+                        row_idx = tDcD_flt[i][0]
+                        n_idx = tDcD_flt[i][1]
+                        group_idx = n_idx // group
+                        global_group_idx = tile_coord_mnkl[1] * groups_per_cta + group_idx
+                        group_value = tDrReduce_first_flt[i]
+                        for fragment_idx in cutlass.range_constexpr(1, fragments_per_group):
+                            tDrReduce_fragment = tDrReduce[
+                                None,
+                                None,
+                                None,
+                                epi_coord[0],
+                                group_start_epi_n + fragment_idx,
+                            ]
+                            tDrReduce_fragment_flt = cute.filter_zeros(tDrReduce_fragment)
+                            group_value = combine_fn(group_value, tDrReduce_fragment_flt[i])
+                        group_value = finalize_fn(group_value)
+                        if const_expr(param_tensor.element_type != Float32):
+                            group_value = group_value.to(param_tensor.element_type)
+                        if (
+                            n_idx % group == group - local_fragment_n
+                            and row_idx < limit_m
+                            and global_group_idx < limit_groups
+                        ):
+                            gReduce[row_idx, group_idx] = group_value
+                return
+            if const_expr(axis == 0):
+                assert combine_fn is not None
+                assert finalize_fn is not None
+                lane_layout_MN, warp_layout_MN = _get_lane_warp_layouts(
+                    tiled_copy, tiled_copy_t2r is None
+                )
+                lanes_in_M = cute.size(lane_layout_MN, mode=[0])
+                lanes_in_N = cute.size(lane_layout_MN, mode=[1])
+                assert lanes_in_M == LOCAL_REDUCE_FRAGMENT_WIDTH
+                assert group <= tile_M
+                if const_expr(group <= lanes_in_M):
+                    assert lanes_in_M % group == 0
+                    reduction_group = const_expr(group)
+                else:
+                    assert group % lanes_in_M == 0
+                    reduction_group = const_expr(lanes_in_M)
+                if const_expr(lanes_in_N > 1):
+                    assert lane_layout_MN.stride[1] == 1
+                if const_expr(reduction_group > 1):
+                    for i in cutlass.range(cute.size(tDrReduce_flt), unroll_full=True):
+                        reduction_rows = reduction_group // 2
+                        while reduction_rows > 0:
+                            tDrReduce_flt[i] = combine_fn(
+                                tDrReduce_flt[i],
+                                cute.arch.shuffle_sync_bfly(
+                                    tDrReduce_flt[i],
+                                    offset=cute.crd2idx((reduction_rows, 0), lane_layout_MN),
+                                ),
+                            )
+                            reduction_rows = reduction_rows // 2
+                if const_expr(grouped_local_reduce_uses_smem(axis, group)):
+                    sReduce = state[1]
+                    assert sReduce is not None
+                    warp_M = warp_layout_MN[0]
+                    warps_in_M = const_expr(cute.size(warp_M))
+                    group_warps = const_expr(group // lanes_in_M)
+                    assert group_warps <= warps_in_M
+                    assert groups_per_cta * group_warps <= warps_in_M
+                    warp_idx = cute.arch.make_warp_uniform(tidx // cute.arch.WARP_SIZE)
+                    warp_m_idx = warp_layout_MN.get_hier_coord(warp_idx)[0]
+                    limit_groups = (
+                        param_tensor.shape[1]
+                        if not varlen_manager.varlen_m
+                        else param_tensor.shape[0]
+                    )
+                    if const_expr(not varlen_manager.varlen_m):
+                        mReduce = param_tensor[batch_idx, None, None]
+                    else:
+                        mReduce = cute.domain_offset(
+                            (varlen_manager.params.cu_seqlens_m[batch_idx], None),
+                            param_tensor[None, None],
+                        )
+                    gReduce = cute.local_tile(
+                        mReduce,
+                        (groups_per_cta, tile_N),
+                        (tile_coord_mnkl[0], tile_coord_mnkl[1]),
+                    )
+                    for i in cutlass.range(cute.size(tDrReduce_flt), unroll_full=True):
+                        row_idx = tDcD_flt[i][0]
+                        n_idx = tDcD_flt[i][1]
+                        group_idx = row_idx // group
+                        group_warp_start = group_idx * group_warps
+                        group_warp_idx = warp_m_idx - group_warp_start
+                        smem_warp_idx = warp_m_idx - group_idx - 1
+                        if (
+                            row_idx % lanes_in_M == 0
+                            and group_warp_idx > 0
+                            and group_warp_idx < group_warps
+                        ):
+                            sReduce[n_idx, smem_warp_idx] = tDrReduce_flt[i]
+                    gemm.epilogue_barrier.arrive_and_wait()
+                    for i in cutlass.range(cute.size(tDrReduce_flt), unroll_full=True):
+                        row_idx = tDcD_flt[i][0]
+                        n_idx = tDcD_flt[i][1]
+                        group_idx = row_idx // group
+                        group_warp_start = group_idx * group_warps
+                        global_group_idx = tile_coord_mnkl[0] * groups_per_cta + group_idx
+                        group_value = tDrReduce_flt[i]
+                        if row_idx % group == 0 and warp_m_idx == group_warp_start:
+                            for warp_offset in cutlass.range_constexpr(1, group_warps):
+                                smem_warp_idx = group_warp_start + warp_offset - group_idx - 1
+                                group_value = combine_fn(
+                                    group_value, sReduce[n_idx, smem_warp_idx]
+                                )
+                            group_value = finalize_fn(group_value)
+                            if const_expr(param_tensor.element_type != Float32):
+                                group_value = group_value.to(param_tensor.element_type)
+                            if n_idx < limit_n and global_group_idx < limit_groups:
+                                gReduce[group_idx, n_idx] = group_value
+                    gemm.epilogue_barrier.arrive_and_wait()
+                    return
+            if const_expr(axis == 1):
+                limit_groups = param_tensor.shape[2] if not varlen_manager.varlen_m else param_tensor.shape[1]
+                tile_shape = (tile_M, groups_per_cta)
+                tile_coord = (tile_coord_mnkl[0], tile_coord_mnkl[1])
+            else:
+                limit_groups = param_tensor.shape[1] if not varlen_manager.varlen_m else param_tensor.shape[0]
+                tile_shape = (groups_per_cta, tile_N)
+                tile_coord = (tile_coord_mnkl[0], tile_coord_mnkl[1])
+            if const_expr(not varlen_manager.varlen_m):
+                mReduce = param_tensor[batch_idx, None, None]
+            else:
+                mReduce = cute.domain_offset(
+                    (varlen_manager.params.cu_seqlens_m[batch_idx], None),
+                    param_tensor[None, None],
+                )
+            gReduce = cute.local_tile(mReduce, tile_shape, tile_coord)
+            if const_expr(
+                axis == 0
+                and param_tensor.element_type == Float32
+                and param_tensor.iterator.alignment >= 16
+                and cute.size(tDrReduce_flt) % 4 == 0
+                and tile_N % 4 == 0
+            ):
+                store_vec = const_expr(4)
+                for chunk in cutlass.range(
+                    cute.size(tDrReduce_flt) // store_vec, unroll_full=True
+                ):
+                    i = chunk * store_vec
+                    row_idx = tDcD_flt[i][0]
+                    n_idx = tDcD_flt[i][1]
+                    group_idx = row_idx // group
+                    global_group_idx = tile_coord_mnkl[0] * groups_per_cta + group_idx
+                    can_store_vec = (
+                        row_idx % group == 0
+                        and n_idx % store_vec == 0
+                        and cute.size(param_tensor, mode=[2]) % store_vec == 0
+                        and n_idx + store_vec <= limit_n
+                        and global_group_idx < limit_groups
+                    )
+                    for vec_idx in cutlass.range_constexpr(1, store_vec):
+                        can_store_vec = (
+                            can_store_vec
+                            and tDcD_flt[i + vec_idx][0] == row_idx
+                            and tDcD_flt[i + vec_idx][1] == n_idx + vec_idx
+                        )
+                    if can_store_vec:
+                        tDrStore = cute.make_rmem_tensor(store_vec, Float32)
+                        for vec_idx in cutlass.range_constexpr(store_vec):
+                            tDrStore[vec_idx] = finalize_fn(tDrReduce_flt[i + vec_idx])
+                        gReduce_vec_ptr = cute.domain_offset(
+                            (group_idx, n_idx), gReduce
+                        ).iterator
+                        gReduce_vec = cute.make_tensor(
+                            cute.make_ptr(
+                                gReduce_vec_ptr.dtype,
+                                gReduce_vec_ptr.toint(),
+                                gReduce_vec_ptr.memspace,
+                                assumed_align=16,
+                            ),
+                            cute.make_layout(store_vec),
+                        )
+                        cute.autovec_copy(tDrStore, gReduce_vec)
+                    else:
+                        for vec_idx in cutlass.range_constexpr(store_vec):
+                            row_idx_cur = tDcD_flt[i + vec_idx][0]
+                            n_idx_cur = tDcD_flt[i + vec_idx][1]
+                            group_idx_cur = row_idx_cur // group
+                            global_group_idx_cur = (
+                                tile_coord_mnkl[0] * groups_per_cta + group_idx_cur
+                            )
+                            if (
+                                row_idx_cur % group == 0
+                                and n_idx_cur < limit_n
+                                and global_group_idx_cur < limit_groups
+                            ):
+                                gReduce[group_idx_cur, n_idx_cur] = finalize_fn(
+                                    tDrReduce_flt[i + vec_idx]
+                                )
+                return
+            for i in cutlass.range(cute.size(tDrReduce_flt), unroll_full=True):
+                row_idx = tDcD_flt[i][0]
+                n_idx = tDcD_flt[i][1]
+                group_idx = n_idx // group if const_expr(axis == 1) else row_idx // group
+                group_leader = n_idx % group == 0 if const_expr(axis == 1) else row_idx % group == 0
+                global_group_idx = (
+                    tile_coord_mnkl[1] * groups_per_cta + group_idx
+                    if const_expr(axis == 1)
+                    else tile_coord_mnkl[0] * groups_per_cta + group_idx
+                )
+                group_value = tDrReduce_flt[i]
+                if const_expr(axis == 0 or finalize_fn is not None):
+                    group_value = finalize_fn(group_value)
+                if const_expr(param_tensor.element_type != Float32):
+                    group_value = group_value.to(param_tensor.element_type)
+                if const_expr(axis == 1):
+                    if (
+                        group_leader
+                        and row_idx < limit_m
+                        and global_group_idx < limit_groups
+                    ):
+                        gReduce[row_idx, group_idx] = group_value
+                else:
+                    if (
+                        group_leader
+                        and n_idx < limit_n
+                        and global_group_idx < limit_groups
+                    ):
+                        gReduce[group_idx, n_idx] = group_value
+
+
+class ColVecReduce(VecReduce):
+    """Column vector reduction: accumulates across N subtiles in registers,
+    then reduces across N lanes/warps and writes to gmem per completed M stripe.
+
+    The accumulation itself happens in epi_visit_subtile (user code).
+    This op handles the register allocation (begin), per-subtile slicing (begin_loop),
+    and reduction + gmem write (end_loop).
+    """
+
+    dim = 0
+    epi_m_major_preference = -1
+
+    @cute.jit
+    def end_loop(
+        self,
+        gemm,
+        param,
+        state,
+        epi_coord,
+        epi_tile,
+        tiled_copy_t2r,
+        tiled_copy_r2s,
+        tile_coord_mnkl,
+        varlen_manager,
+        tidx,
+    ):
+        """Flush the current M stripe when the last N subtile has accumulated."""
+        epi_tile_shape = cute.zipped_divide(
+            cute.make_layout(gemm.cta_tile_shape_mnk[:2]), epi_tile
+        ).shape[1]
+        if const_expr(epi_coord[1] == epi_tile_shape[1] - 1):
+            tDrReduce, sDrReduce = state[0], state[1]
+            tDrReduce_cur = tDrReduce[None, None, None, epi_coord[0], epi_coord[1]]
+            tiled_copy = tiled_copy_t2r if tiled_copy_t2r is not None else tiled_copy_r2s
+            reference_src = tiled_copy_t2r is None
+
+            # ── Derive lane layout from tiled_copy ──
+            lane_layout_MN, warp_layout_MN = _get_lane_warp_layouts(tiled_copy, reference_src)
+            # For ColVecReduce: reduce across N lanes (lanes_in_N threads share same M row)
+            lanes_in_N = cute.size(lane_layout_MN, mode=[1])
+            is_lane_n_leader = cute.arch.lane_idx() % lanes_in_N == 0
+            # Typically lanes_in_N is 4 for Sm90
+            assert lanes_in_N == 1 << int(math.log2(lanes_in_N)), (
+                "lanes_in_N must be a power of 2 for butterfly reduction"
+            )
+
+            # Intra-warp shuffle reduction across N lanes
+            if const_expr(lanes_in_N > 1):
+                # Assumes threads for each M row are contiguous along N, so
+                # warp_reduction over groups of lanes_in_N matches lane_layout_MN.
+                assert lane_layout_MN.stride[1] == 1
+                tDrReduce_flt = cute.filter_zeros(tDrReduce_cur)
+                for i in cutlass.range(cute.size(tDrReduce_flt), unroll_full=True):
+                    tDrReduce_flt[i] = cute.arch.warp_reduction(
+                        tDrReduce_flt[i], operator.add, threads_in_group=lanes_in_N
+                    )
+
+            warp_N = warp_layout_MN[1]
+            warps_in_N = const_expr(cute.size(warp_N))
+            partition_for_epilogue_fn = partial(
+                partition_for_epilogue,
+                epi_tile=epi_tile,
+                tiled_copy=tiled_copy,
+                tidx=tidx,
+                reference_src=tiled_copy_t2r is None,
+            )
+            tile_M, tile_N = gemm.cta_tile_shape_mnk[:2]
+            tDcD = partition_for_epilogue_fn(cute.make_identity_tensor((tile_M, tile_N)))
+            tDcD_cur = tDcD[None, None, None, epi_coord[0], epi_coord[1]]
+            tDrReduce_m = layout_utils.convert_layout_zero_stride(
+                tDrReduce_cur, tDrReduce_cur.layout
+            )[None, 0]
+            tDcD_m = layout_utils.convert_layout_zero_stride(tDcD_cur, tDrReduce_cur.layout)[
+                None, 0
+            ]
+
+            # Inter-warp reduction through smem
+            warp_idx = cute.arch.make_warp_uniform(tidx // cute.arch.WARP_SIZE)
+            warp_n_idx = warp_layout_MN.get_hier_coord(warp_idx)[1]
+            if const_expr(warps_in_N > 1):
+                if warp_n_idx > 0 and is_lane_n_leader:
+                    for m in cutlass.range(cute.size(tDcD_m, mode=[0])):
+                        row_idx = tDcD_m[m][0]
+                        sDrReduce[row_idx, warp_n_idx - 1] = tDrReduce_m[m]
+                gemm.epilogue_barrier.arrive_and_wait()
+                if warp_n_idx == 0 and is_lane_n_leader:
+                    for m in cutlass.range(cute.size(tDcD_m, mode=[0])):
+                        row_idx = tDcD_m[m][0]
+                        for warp_n in cutlass.range_constexpr(1, warps_in_N):
+                            tDrReduce_m[m] += sDrReduce[row_idx, warp_n - 1]
+
+            # Write to gmem
+            batch_idx = tile_coord_mnkl[3]
+            limit_m = min(varlen_manager.len_m(batch_idx) - tile_coord_mnkl[0] * tile_M, tile_M)
+            limit_n_tiles = param.shape[2] if not varlen_manager.varlen_m else param.shape[1]
+            if const_expr(not varlen_manager.varlen_m):
+                mColVec = param[batch_idx, None, tile_coord_mnkl[1]]
+            else:
+                mColVec = cute.domain_offset(
+                    (varlen_manager.params.cu_seqlens_m[batch_idx],),
+                    param[None, tile_coord_mnkl[1]],
+                )
+            gColVec = cute.local_tile(mColVec, (tile_M,), (tile_coord_mnkl[0],))
+            should_write_gmem = (
+                is_lane_n_leader
+                if const_expr(warps_in_N == 1)
+                else warp_n_idx == 0 and is_lane_n_leader
+            )
+            if tile_coord_mnkl[1] < limit_n_tiles and should_write_gmem:
+                for m in cutlass.range(cute.size(tDcD_m, mode=[0])):
+                    row_idx = tDcD_m[m][0]
+                    if row_idx < limit_m:
+                        gColVec[row_idx] = tDrReduce_m[m]
+
+
+class RowVecReduce(VecReduce):
+    """Row vector reduction: accumulates across M subtiles in registers,
+    then reduces across M lanes/warps and writes to gmem per completed N stripe.
+
+    Output shape is (L, ceildiv(M, tile_M), N): one partial sum per CTA-M tile per
+    N column. This mirrors ColVecReduce with M/N swapped.
+    """
+
+    dim = 1
+    epi_m_major_preference = 4
+
+    @cute.jit
+    def end_loop(
+        self,
+        gemm,
+        param,
+        state,
+        epi_coord,
+        epi_tile,
+        tiled_copy_t2r,
+        tiled_copy_r2s,
+        tile_coord_mnkl,
+        varlen_manager,
+        tidx,
+    ):
+        """Flush the current N stripe when the last M subtile has accumulated."""
+        epi_tile_shape = cute.zipped_divide(
+            cute.make_layout(gemm.cta_tile_shape_mnk[:2]), epi_tile
+        ).shape[1]
+        if const_expr(epi_coord[0] == epi_tile_shape[0] - 1):
+            tDrReduce, sDrReduce = state[0], state[1]
+            tDrReduce_cur = tDrReduce[None, None, None, epi_coord[0], epi_coord[1]]
+            tiled_copy = tiled_copy_t2r if tiled_copy_t2r is not None else tiled_copy_r2s
+            reference_src = tiled_copy_t2r is None
+
+            # ── Derive lane layout from tiled_copy ──
+            lane_layout_MN, warp_layout_MN = _get_lane_warp_layouts(tiled_copy, reference_src)
+            # For RowVecReduce: reduce across M lanes (lanes_in_M threads share same N col)
+            lanes_in_M = cute.size(lane_layout_MN, mode=[0])
+            lanes_in_N = cute.size(lane_layout_MN, mode=[1])
+            is_lane_m_leader = cute.arch.lane_idx() < lanes_in_N
+            assert lanes_in_M == 1 << int(math.log2(lanes_in_M)), (
+                "lanes_in_M must be a power of 2 for butterfly reduction"
+            )
+            if const_expr(lanes_in_N > 1):
+                assert lane_layout_MN.stride[1] == 1, (
+                    "RowVecReduce assumes contiguous N lanes when lanes_in_N > 1"
+                )
+
+            # Intra-warp shuffle reduction across M lanes. M lanes may be either contiguous
+            # (SM100 N-major output) or strided by N lanes (SM100 M-major output).
+            tDrReduce_n = layout_utils.convert_layout_zero_stride(
+                tDrReduce_cur, tDrReduce_cur.layout
+            )[None, 0]
+            if const_expr(lanes_in_M > 1):
+                for n in cutlass.range(cute.size(tDrReduce_n), unroll_full=True):
+                    reduction_rows = lanes_in_M // 2
+                    while reduction_rows > 0:
+                        tDrReduce_n[n] += cute.arch.shuffle_sync_bfly(
+                            tDrReduce_n[n],
+                            offset=cute.crd2idx((reduction_rows, 0), lane_layout_MN),
+                        )
+                        reduction_rows = reduction_rows // 2
+
+            warp_M = warp_layout_MN[0]
+            warps_in_M = const_expr(cute.size(warp_M))
+            partition_for_epilogue_fn = partial(
+                partition_for_epilogue,
+                epi_tile=epi_tile,
+                tiled_copy=tiled_copy,
+                tidx=tidx,
+                reference_src=tiled_copy_t2r is None,
+            )
+            tile_M, tile_N = gemm.cta_tile_shape_mnk[:2]
+            tDcD = partition_for_epilogue_fn(cute.make_identity_tensor((tile_M, tile_N)))
+            tDcD_cur = tDcD[None, None, None, epi_coord[0], epi_coord[1]]
+            tDcD_n = layout_utils.convert_layout_zero_stride(tDcD_cur, tDrReduce_cur.layout)[
+                None, 0
+            ]
+
+            # Inter-warp reduction through smem
+            warp_idx = cute.arch.make_warp_uniform(tidx // cute.arch.WARP_SIZE)
+            warp_m_idx = warp_layout_MN.get_hier_coord(warp_idx)[0]
+            if const_expr(warps_in_M > 1):
+                if warp_m_idx > 0 and is_lane_m_leader:
+                    for n in cutlass.range(cute.size(tDcD_n, mode=[0])):
+                        col_idx = tDcD_n[n][1]
+                        sDrReduce[col_idx, warp_m_idx - 1] = tDrReduce_n[n]
+                gemm.epilogue_barrier.arrive_and_wait()
+                if warp_m_idx == 0 and is_lane_m_leader:
+                    for n in cutlass.range(cute.size(tDcD_n, mode=[0])):
+                        col_idx = tDcD_n[n][1]
+                        for warp_m in cutlass.range_constexpr(1, warps_in_M):
+                            tDrReduce_n[n] += sDrReduce[col_idx, warp_m - 1]
+
+            # Write to gmem
+            batch_idx = tile_coord_mnkl[3]
+            limit_m_tiles = param.shape[1] if not varlen_manager.varlen_m else param.shape[0]
+            if const_expr(not varlen_manager.varlen_m):
+                mRowVec = param[batch_idx, tile_coord_mnkl[0], None]
+            else:
+                mRowVec = param[tile_coord_mnkl[0], None]
+            gRowVec = cute.local_tile(mRowVec, (tile_N,), (tile_coord_mnkl[1],))
+            limit_n = min(
+                cute.size(mRowVec, mode=[0]) - tile_coord_mnkl[1] * tile_N,
+                tile_N,
+            )
+            should_write_gmem = (
+                is_lane_m_leader
+                if const_expr(warps_in_M == 1)
+                else warp_m_idx == 0 and is_lane_m_leader
+            )
+            if tile_coord_mnkl[0] < limit_m_tiles and should_write_gmem:
+                for n in cutlass.range(cute.size(tDcD_n, mode=[0])):
+                    col_idx = tDcD_n[n][1]
+                    if col_idx < limit_n:
+                        gRowVec[col_idx] = tDrReduce_n[n]
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/epi_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/epi_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b5f0ffba092bd99c4ddc9ac842e6ecddb65d7dd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/epi_utils.py
@@ -0,0 +1,69 @@
+# Copyright (c) 2025, Tri Dao.
+"""Epilogue utilities: shared helpers for epilogue mixin classes."""
+
+import cutlass
+import cutlass.cute as cute
+import cutlass.utils.blackwell_helpers as sm100_utils
+
+from . import sm90_utils
+from . import copy_utils
+
+
+def assume_stride_divisibility(tensor):
+    """Assume all strides are divisible by 32 bits (except static strides).
+
+    Used for broadcast vectors and similar tensors where stride alignment is guaranteed.
+    Returns a new tensor with the assumed strides.
+    """
+    if tensor is None:
+        return None
+    new_stride = tuple(
+        cute.assume(s, divby=32 // tensor.element_type.width) if not cute.is_static(s) else s
+        for s in tensor.stride
+    )
+    return cute.make_tensor(tensor.iterator, cute.make_layout(tensor.shape, stride=new_stride))
+
+
+def assume_broadcast_strides(*tensors):
+    """Apply stride divisibility assumptions to multiple broadcast vectors.
+
+    Returns a list with None preserved for None inputs.
+    """
+    return [assume_stride_divisibility(t) for t in tensors]
+
+
+def setup_epi_tensor(gemm, tensor, epi_tile=None, op_type="store", stage=None):
+    """Create copy metadata + smem layout for a supplemental epilogue tensor.
+
+    Args:
+        gemm: The GEMM object (provides arch, epi_stage, and epilogue layout helpers).
+        tensor: The global memory tensor to set up for the epilogue.
+        epi_tile: Epilogue tile shape. Defaults to gemm.epi_tile.
+        op_type: "store" or "load".
+
+    Returns:
+        (copy_atom, tensor, smem_layout_staged, epi_tile). copy_atom is None for pre-TMA archs.
+    """
+    if epi_tile is None:
+        epi_tile = gemm.epi_tile
+    if stage is None:
+        stage = gemm.epi_stage
+    dtype = tensor.element_type
+    layout = cutlass.utils.LayoutEnum.from_tensor(tensor)
+    utils_cls = sm100_utils if gemm.arch >= 100 else sm90_utils
+    smem_layout_staged = utils_cls.make_smem_layout_epi(dtype, layout, epi_tile, stage)
+    # Ragging-for-TMA is for varlen_m stores that need a per-batch row offset baked
+    # into the TMA descriptor. Loads don't currently support varlen_m, so skip the
+    # ragging conversion.
+    tma_input = (
+        copy_utils.create_ragged_tensor_for_tma(tensor, ragged_dim=0, ptr_shift=True)
+        if op_type != "load" and cute.rank(tensor) == 2
+        else tensor
+    )
+    tma_atom, tma_tensor = gemm._make_tma_epi_atoms_and_tensors(
+        tma_input,
+        smem_layout_staged,
+        epi_tile,
+        op_type=op_type,
+    )
+    return tma_atom, tma_tensor, smem_layout_staged, epi_tile
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/fast_math.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/fast_math.py
new file mode 100644
index 0000000000000000000000000000000000000000..73bbd2ecb04686d17a621fdd46bc67a78b1e2331
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/fast_math.py
@@ -0,0 +1,33 @@
+# Copyright (c) 2025, Tri Dao.
+
+import cutlass
+import cutlass.cute as cute
+from cutlass.base_dsl.typing import Integer
+from cutlass.cutlass_dsl import dsl_user_op
+
+
+class FastDivmod(cute.FastDivmodDivisor):
+    """We store the divisor along with the FastDivmodDivisor."""
+
+    @dsl_user_op
+    def __init__(
+        self,
+        divisor: Integer,
+        is_power_of_2: bool = None,
+        *,
+        loc=None,
+        ip=None,
+    ):
+        super().__init__(divisor, is_power_of_2=is_power_of_2, loc=loc, ip=ip)
+        self.divisor = divisor
+
+    def __extract_mlir_values__(self):
+        """Extract MLIR values for Host->Device transfer."""
+        return [self._divisor] + cutlass.extract_mlir_values(self.divisor)
+
+    def __new_from_mlir_values__(self, values):
+        """Reconstruct FastDivmodDivisor from MLIR values."""
+        new_obj = object.__new__(FastDivmod)
+        new_obj._divisor = values[0]
+        new_obj.divisor = cutlass.new_from_mlir_values(self.divisor, values[1:])
+        return new_obj
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_act.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_act.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ed6e39b7be96684b0ede62f6bf8d8b47744258d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_act.py
@@ -0,0 +1,1366 @@
+# Copyright (c) 2025, Wentao Guo, Tri Dao.
+from __future__ import annotations
+import math
+from typing import NamedTuple, Tuple, Optional, Callable, Type
+
+from torch import Tensor
+from torch._subclasses.fake_tensor import is_fake_tensor
+
+import cutlass
+import cutlass.cute as cute
+import cutlass.utils.blackwell_helpers as sm100_utils
+from cutlass import Int32, Float32, const_expr
+from cutlass.cute.runtime import make_ptr
+from cutlass.cute.nvgpu import warp
+
+from .compile_utils import make_fake_tensor as fake_tensor
+from .cute_dsl_utils import (
+    mlir_namedtuple,
+    get_device_capacity,
+    get_max_active_clusters,
+    torch2cute_dtype_map,
+)
+from .epi_composable import ComposableEpiMixin
+from .epi_ops import (
+    ColVecLoad,
+    RowVecLoad,
+    RowVecTupleLoad,
+    ColVecTupleLoad,
+    ScalarTupleLoad,
+    EpiSmemBytes,
+    GroupedLocalReduce,
+    LOCAL_REDUCE_FRAGMENT_WIDTH,
+    Scalar,
+    grouped_local_reduce_uses_smem,
+    grouped_rowvec_reduce_value,
+    TileTupleLoad,
+    TileStore,
+)
+from .gemm_sm80 import GemmSm80
+from .gemm_sm90 import GemmSm90
+from .gemm_sm100 import GemmSm100
+from .gemm_sm120 import GemmSm120
+from .gemm_default_epi import GemmDefaultEpiMixin
+from .gemm_tvm_ffi_utils import (
+    get_major,
+    perm3d_single,
+    make_scheduler_args,
+    make_varlen_args,
+    make_fake_scheduler_args,
+    make_fake_varlen_args,
+    div_for_dtype,
+    make_fake_gemm_tensors,
+    compile_gemm_kernel,
+)
+from .cache import jit_cache
+from . import layout_utils
+from . import copy_utils
+from .layout_utils import permute_gated_Cregs_b16
+from .activation import act_fn_map, gate_fn_map
+from .rounding import RoundingMode, convert_f32_to_bf16_sr, epilogue_aux_out_sr_seed
+
+
+_tensor_epilogue_fns: dict[str, Callable] = {}
+_local_reduce_combine_fns: dict[str, Callable] = {}
+_local_reduce_finalize_fns: dict[str, Callable] = {}
+
+
+def power_of_2_divisibility(value: int, max_divisibility: int) -> int:
+    value = abs(int(value))
+    if value == 0:
+        return max_divisibility
+    divisibility = 1
+    while divisibility * 2 <= max_divisibility and value % (divisibility * 2) == 0:
+        divisibility *= 2
+    return divisibility
+
+
+def tensor_stride_divisibility(
+    tensor: Tensor | None,
+    dtype: Type[cutlass.Numeric],
+    leading_dim: int,
+) -> int:
+    """Return the strongest 16-byte-capped layout contract true for a tensor."""
+    if tensor is None:
+        return 1
+    max_divisibility = div_for_dtype(dtype)
+    divisibility = max_divisibility
+    for dim, stride in enumerate(tensor.stride()):
+        if dim != leading_dim:
+            divisibility = min(
+                divisibility, power_of_2_divisibility(stride, max_divisibility)
+            )
+    if is_fake_tensor(tensor) or tensor.is_meta:
+        # AOT inputs have no real pointer; reuse this contract only when the
+        # runtime tensor has the allocator-backed base alignment assumed here.
+        return divisibility
+    element_bytes = max(dtype.width // 8, 1)
+    return min(
+        divisibility,
+        power_of_2_divisibility(tensor.data_ptr() // element_bytes, max_divisibility),
+    )
+
+
+def register_tensor_epilogue_fn(
+    tensor_epilogue_key: str, tensor_epilogue_fn: Callable
+) -> None:
+    _tensor_epilogue_fns[tensor_epilogue_key] = tensor_epilogue_fn
+
+
+def register_local_reduce_fns(
+    combine_key: str,
+    combine_fn: Callable,
+    finalize_key: str,
+    finalize_fn: Callable,
+) -> None:
+    _local_reduce_combine_fns[combine_key] = combine_fn
+    _local_reduce_finalize_fns[finalize_key] = finalize_fn
+
+
+def validate_grouped_n_contract_device(
+    group: int | None, device_capacity: tuple[int, int]
+) -> None:
+    """Validate grouped-main support at the public dispatch boundary."""
+    if group is None:
+        return
+    major = device_capacity[0]
+    if major == 12:
+        raise NotImplementedError("grouped_n_contract is not yet supported on SM120")
+    if major not in (10, 11):
+        raise NotImplementedError(
+            "grouped_n_contract is currently validated only on "
+            "SM100 and SM110"
+        )
+    if group == 2 or (group == 4 and major == 10):
+        return
+    raise NotImplementedError(
+        "grouped_n_contract supports group 2 on SM100 and SM110, "
+        "plus group 4 on SM100"
+    )
+
+
+class GemmActMixin(ComposableEpiMixin):
+    grouped_n_contract_group = 1
+    _epi_ops = (
+        Scalar("alpha"),
+        Scalar("beta"),
+        Scalar("sr_seed", dtype=Int32),
+        RowVecLoad("mRowVecBroadcast"),
+        ColVecLoad("mColVecBroadcast"),
+        RowVecTupleLoad("mTensorEpilogueRowVecBroadcasts"),
+        ColVecTupleLoad("mTensorEpilogueColVecBroadcasts"),
+        TileTupleLoad("mTensorEpilogueTiles"),
+        ScalarTupleLoad("mTensorEpilogueScalars"),
+        GroupedLocalReduce("mLocalReduce"),
+        TileStore("mAuxOut"),
+    )
+    _extra_param_fields = (
+        ("act_fn", cutlass.Constexpr, None),
+        ("tensor_epilogue_fn", cutlass.Constexpr, None),
+        ("tensor_epilogue_arg_kinds", cutlass.Constexpr, ()),
+        ("tensor_epilogue_returns_aux", cutlass.Constexpr, False),
+        ("tensor_epilogue_returns_local_reduce", cutlass.Constexpr, False),
+        ("local_reduce_feeds_main", cutlass.Constexpr, False),
+        ("local_reduce_group", cutlass.Constexpr, 0),
+        ("local_reduce_axis", cutlass.Constexpr, 1),
+    )
+
+    @mlir_namedtuple
+    class EpilogueArguments(NamedTuple):
+        mAuxOut: cute.Tensor
+        act_fn: cutlass.Constexpr[Optional[Callable]] = None
+        tensor_epilogue_fn: cutlass.Constexpr[Optional[Callable]] = None
+        tensor_epilogue_arg_kinds: cutlass.Constexpr[tuple] = ()
+        tensor_epilogue_returns_aux: cutlass.Constexpr[bool] = False
+        tensor_epilogue_returns_local_reduce: cutlass.Constexpr[bool] = False
+        local_reduce_feeds_main: cutlass.Constexpr[bool] = False
+        local_reduce_group: cutlass.Constexpr[int] = 0
+        local_reduce_axis: cutlass.Constexpr[int] = 1
+        local_reduce_combine_fn: cutlass.Constexpr[Optional[Callable]] = None
+        local_reduce_finalize_fn: cutlass.Constexpr[Optional[Callable]] = None
+        alpha: Optional[Float32 | cute.Tensor] = None
+        beta: Optional[Float32 | cute.Tensor] = None
+        mRowVecBroadcast: Optional[cute.Tensor] = None
+        mColVecBroadcast: Optional[cute.Tensor] = None
+        mTensorEpilogueRowVecBroadcasts: Optional[tuple[cute.Tensor, ...]] = None
+        mTensorEpilogueColVecBroadcasts: Optional[tuple[cute.Tensor, ...]] = None
+        mTensorEpilogueTiles: Optional[tuple[cute.Tensor, ...]] = None
+        mTensorEpilogueScalars: Optional[tuple[cute.Tensor, ...]] = None
+        mLocalReduce: Optional[cute.Tensor] = None
+        rounding_mode: cutlass.Constexpr[int] = RoundingMode.RN
+        sr_seed: Optional[Int32 | cute.Tensor] = None
+
+    # EpilogueParams auto-generated from _epi_ops + _extra_param_fields
+
+    def _filter_epi_ops(self, args):
+        super()._filter_epi_ops(args)
+        if args.local_reduce_feeds_main and not any(
+            op.name == "mLocalReduce" for op in self._epi_ops
+        ):
+            reduce_ops = tuple(
+                op for op in type(self)._epi_ops if op.name == "mLocalReduce"
+            )
+            self._epi_ops = (*self._epi_ops, *reduce_ops)
+
+    def epi_to_underlying_arguments(self, args: EpilogueArguments, *, loc=None, ip=None):
+        self.rounding_mode = args.rounding_mode
+        if isinstance(args.mAuxOut, tuple):
+            self.aux_out_dtypes = tuple(tensor.element_type for tensor in args.mAuxOut)
+            self.aux_out_layouts = tuple(
+                cutlass.utils.LayoutEnum.from_tensor(tensor) for tensor in args.mAuxOut
+            )
+        else:
+            self.aux_out_dtype = args.mAuxOut.element_type
+            self.aux_out_layout = cutlass.utils.LayoutEnum.from_tensor(args.mAuxOut)
+        self.cta_tile_shape_aux_out_mn = self.cta_tile_shape_mnk[:2]
+        d = self._epi_ops_to_params_dict(args)
+        d["act_fn"] = args.act_fn
+        d["tensor_epilogue_fn"] = args.tensor_epilogue_fn
+        d["tensor_epilogue_arg_kinds"] = args.tensor_epilogue_arg_kinds
+        d["tensor_epilogue_returns_aux"] = args.tensor_epilogue_returns_aux
+        d["tensor_epilogue_returns_local_reduce"] = args.tensor_epilogue_returns_local_reduce
+        d["local_reduce_feeds_main"] = args.local_reduce_feeds_main
+        d["local_reduce_group"] = args.local_reduce_group
+        d["local_reduce_axis"] = args.local_reduce_axis
+        self.local_reduce_feeds_main = args.local_reduce_feeds_main
+        self.local_reduce_group = args.local_reduce_group
+        self.local_reduce_axis = args.local_reduce_axis
+        for key in ("mRowVecBroadcast", "mColVecBroadcast"):
+            if key in self.concat_layout and key in d:
+                d[key] = layout_utils.concat_to_interleave(d[key], 1)
+        return self.EpilogueParams(**d)
+
+    @classmethod
+    def epi_smem_bytes(cls, args, cta_tile_shape_mnk, epi_tile, warp_shape_mnk=None):
+        result = super().epi_smem_bytes(args, cta_tile_shape_mnk, epi_tile, warp_shape_mnk)
+        if args.mLocalReduce is not None and grouped_local_reduce_uses_smem(
+            args.local_reduce_axis, args.local_reduce_group
+        ):
+            smem_warps = max(
+                (warp_shape_mnk[0] if warp_shape_mnk is not None else 1) - 1, 0
+            )
+            result += EpiSmemBytes(
+                unstaged=cta_tile_shape_mnk[1] * smem_warps * (Float32.width // 8)
+            )
+        return result
+
+    # epi_get_tma_atoms, epi_get_smem_struct, and epi_get_smem_tensors are all
+    # inherited from ComposableEpiMixin via _epi_ops.
+
+    def epi_make_aux_out_copy_atom_r2s(self, params, tiled_copy_t2r, index=None):
+        """Build the register-to-shared copy atom used by aux outputs."""
+        aux_out_layout = (
+            self.aux_out_layouts[index] if index is not None else self.aux_out_layout
+        )
+        aux_out_dtype = self.aux_out_dtypes[index] if index is not None else self.aux_out_dtype
+        epi_tile_mAuxOut = (
+            params.epi_tile_mAuxOut[index]
+            if index is not None
+            else params.epi_tile_mAuxOut
+        )
+        if self.arch == 100:
+            return sm100_utils.get_smem_store_op(
+                aux_out_layout, aux_out_dtype, self.acc_dtype, tiled_copy_t2r
+            )
+        else:
+            return copy_utils.get_smem_store_atom(
+                aux_out_dtype,
+                transpose=aux_out_layout != cutlass.utils.LayoutEnum.ROW_MAJOR,
+                major_mode_size=cute.size(epi_tile_mAuxOut, mode=[1])
+                // self.atom_layout_mnk[1],
+            )
+
+    def epi_make_aux_out_tiled_copy_r2s(
+        self, params, tiled_copy_r2s, tiled_copy_t2r, index=None
+    ):
+        """Build the register-to-shared tiled copy used by aux outputs."""
+        copy_atom_aux_out_r2s = self.epi_make_aux_out_copy_atom_r2s(
+            params, tiled_copy_t2r, index
+        )
+        return cute.make_tiled_copy_S(copy_atom_aux_out_r2s, tiled_copy_r2s)
+
+    def epi_setup_aux_out(
+        self,
+        params,
+        epi_smem_tensors,
+        tiled_copy_r2s,
+        tiled_copy_t2r,
+        tile_coord_mnkl,
+        varlen_manager,
+        tidx,
+    ):
+        """Setup aux output TMA copies and partitions before the epilogue loop.
+
+        Returns None when mAuxOut wasn't supplied so the framework skips the aux-out path.
+        """
+        if getattr(params, "mAuxOut", None) is None:
+            return None
+        sAuxOut = epi_smem_tensors["mAuxOut"]
+        if isinstance(params.mAuxOut, tuple):
+            contexts = []
+            batch_idx = tile_coord_mnkl[3]
+            for i, aux_out in enumerate(params.mAuxOut):
+                tiled_copy_aux_out_r2s = self.epi_make_aux_out_tiled_copy_r2s(
+                    params, tiled_copy_r2s, tiled_copy_t2r, i
+                )
+                tRS_sAuxOut = tiled_copy_aux_out_r2s.get_slice(tidx).partition_D(
+                    sAuxOut[i]
+                )
+                copy_aux_out, _, _ = self.epilog_gmem_copy_and_partition(
+                    params.tma_atom_mAuxOut[i],
+                    varlen_manager.offset_batch_epi(aux_out, batch_idx),
+                    self.cta_tile_shape_aux_out_mn,
+                    params.epi_tile_mAuxOut[i],
+                    sAuxOut[i],
+                    tile_coord_mnkl,
+                )
+                contexts.append((tiled_copy_aux_out_r2s, tRS_sAuxOut, copy_aux_out))
+            return tuple(contexts)
+        tiled_copy_aux_out_r2s = self.epi_make_aux_out_tiled_copy_r2s(
+            params, tiled_copy_r2s, tiled_copy_t2r
+        )
+        tRS_sAuxOut = tiled_copy_aux_out_r2s.get_slice(tidx).partition_D(sAuxOut)
+        batch_idx = tile_coord_mnkl[3]
+        copy_aux_out, _, _ = self.epilog_gmem_copy_and_partition(
+            params.tma_atom_mAuxOut,
+            varlen_manager.offset_batch_epi(params.mAuxOut, batch_idx),
+            self.cta_tile_shape_aux_out_mn,
+            params.epi_tile_mAuxOut,
+            sAuxOut,
+            tile_coord_mnkl,
+        )
+        return ((tiled_copy_aux_out_r2s, tRS_sAuxOut, copy_aux_out),)
+
+    @cute.jit
+    def epi_convert_one_aux_out(
+        self,
+        tRS_rAuxOut,
+        aux_out_dtype: cutlass.Constexpr,
+        sr_seed,
+        tidx,
+        tile_coord_mnkl,
+        num_prev_subtiles,
+        epi_idx,
+    ):
+        if const_expr(
+            self.rounding_mode == RoundingMode.RS
+            and tRS_rAuxOut.element_type == cutlass.Float32
+            and aux_out_dtype == cutlass.BFloat16
+        ):
+            from cutlass.cute.tensor import TensorSSA
+
+            seed = epilogue_aux_out_sr_seed(
+                sr_seed, tile_coord_mnkl, num_prev_subtiles + epi_idx
+            )
+            tRS_rAuxOut_out = cute.make_rmem_tensor_like(tRS_rAuxOut, aux_out_dtype)
+            src_vec = tRS_rAuxOut.load()
+            raw_vec = convert_f32_to_bf16_sr(src_vec, seed, tidx)
+            tRS_rAuxOut_out.store(TensorSSA(raw_vec, src_vec.shape, aux_out_dtype))
+        else:
+            tRS_rAuxOut_out = cute.make_rmem_tensor_like(tRS_rAuxOut, aux_out_dtype)
+            tRS_rAuxOut_out.store(tRS_rAuxOut.load().to(aux_out_dtype))
+        return tRS_rAuxOut_out
+
+    @cute.jit
+    def epi_convert_aux_out(
+        self, tRS_rAuxOut, sr_seed, tidx, tile_coord_mnkl, num_prev_subtiles, epi_idx
+    ):
+        """Convert aux outputs from acc_dtype to their output dtypes."""
+        if const_expr(isinstance(tRS_rAuxOut, tuple)):
+            result = []
+            for i, aux_out in enumerate(tRS_rAuxOut):
+                result.append(
+                    self.epi_convert_one_aux_out(
+                        aux_out,
+                        self.aux_out_dtypes[i],
+                        sr_seed,
+                        tidx,
+                        tile_coord_mnkl,
+                        num_prev_subtiles,
+                        epi_idx,
+                    )
+                )
+            return tuple(result)
+        return self.epi_convert_one_aux_out(
+            tRS_rAuxOut,
+            self.aux_out_dtype,
+            sr_seed,
+            tidx,
+            tile_coord_mnkl,
+            num_prev_subtiles,
+            epi_idx,
+        )
+
+    @cute.jit
+    def epi_visit_subtile(
+        self,
+        params,
+        epi_loop_tensors: Tuple[cute.Tensor, ...],
+        tRS_rD: cute.Tensor,
+        tRS_rC: Optional[cute.Tensor] = None,
+    ) -> Optional[cute.Tensor]:
+        tDrLocalReduceValue = None
+        if const_expr(params.local_reduce_feeds_main):
+            tDrLocalReduce = epi_loop_tensors.get("mLocalReduce")
+            combine_fn = const_expr(params.mLocalReduce.combine_fn)
+            finalize_fn = const_expr(params.mLocalReduce.finalize_fn)
+            tDrLocalReduceValue = grouped_rowvec_reduce_value(
+                self, tRS_rD, tDrLocalReduce, combine_fn, finalize_fn
+            )
+        if const_expr(params.tensor_epilogue_fn is None or not params.tensor_epilogue_arg_kinds):
+            GemmDefaultEpiMixin.epi_visit_subtile(self, params, epi_loop_tensors, tRS_rD, tRS_rC)
+        if const_expr(params.tensor_epilogue_fn is not None):
+            tRS_rEpilogueIn = cute.make_rmem_tensor_like(tRS_rD, self.acc_dtype)
+            tRS_rEpilogueIn.store(tRS_rD.load())
+            epilogue_aux_values = []
+            if const_expr(params.tensor_epilogue_arg_kinds):
+                tDrRowVecs = epi_loop_tensors.get("mTensorEpilogueRowVecBroadcasts")
+                tDrColVecs = epi_loop_tensors.get("mTensorEpilogueColVecBroadcasts")
+                tRsTileAuxes = epi_loop_tensors.get("mTensorEpilogueTiles")
+                scalars = epi_loop_tensors.get("mTensorEpilogueScalars")
+                row_arg_index = 0
+                col_arg_index = 0
+                tile_arg_index = 0
+                scalar_arg_index = 0
+                for arg_kind in params.tensor_epilogue_arg_kinds:
+                    if const_expr(arg_kind == 4):
+                        scalar = scalars[scalar_arg_index]
+                        scalar_arg_index += 1
+                        if const_expr(self.grouped_n_contract_group == 1):
+                            tRS_rScalar = cute.make_rmem_tensor_like(tRS_rD, scalar.dtype)
+                            tRS_rScalar.fill(scalar[0])
+                            epilogue_aux_values.append(tRS_rScalar.load())
+                        else:
+                            epilogue_aux_values.append(scalar[0])
+                    else:
+                        if const_expr(arg_kind == 1):
+                            epilogue_aux = tRsTileAuxes[tile_arg_index]
+                            tile_arg_index += 1
+                        elif const_expr(arg_kind == 2):
+                            epilogue_aux = tDrRowVecs[row_arg_index]
+                            row_arg_index += 1
+                        else:
+                            epilogue_aux = tDrColVecs[col_arg_index]
+                            col_arg_index += 1
+                        if const_expr(
+                            self.grouped_n_contract_group != 1 and arg_kind == 3
+                        ):
+                            epilogue_aux_values.append(
+                                cute.filter_zeros(epilogue_aux).load()[0]
+                            )
+                        else:
+                            tRS_rEpilogueAux = cute.make_rmem_tensor_like(
+                                tRS_rD, epilogue_aux.element_type
+                            )
+                            tRS_rEpilogueAux.store(epilogue_aux.load())
+                            epilogue_aux_values.append(tRS_rEpilogueAux.load())
+            if const_expr(tDrLocalReduceValue is not None):
+                epilogue_aux_values.append(tDrLocalReduceValue.load())
+            epilogue_result = params.tensor_epilogue_fn(
+                tRS_rEpilogueIn.load(), *tuple(epilogue_aux_values)
+            )
+            if const_expr(params.tensor_epilogue_returns_aux):
+                tRS_rD.store(epilogue_result[0])
+                aux_results = []
+                for i, _ in enumerate(params.mAuxOut):
+                    aux_result = epilogue_result[i + 1]
+                    tRS_rAuxOut = cute.make_rmem_tensor(
+                        aux_result.shape,
+                        aux_result.element_type,
+                    )
+                    tRS_rAuxOut.store(aux_result)
+                    aux_results.append(tRS_rAuxOut)
+                if const_expr(params.tensor_epilogue_returns_local_reduce):
+                    tDrLocalReduce = epi_loop_tensors.get("mLocalReduce")
+                    if const_expr(params.local_reduce_feeds_main):
+                        tDrLocalReduce = tDrLocalReduce.local_reduce
+                    tDrLocalReduce.store(epilogue_result[len(params.mAuxOut) + 1])
+                tRS_rAuxOut = tuple(aux_results)
+            else:
+                main_result = epilogue_result
+                if const_expr(params.tensor_epilogue_returns_local_reduce):
+                    tDrLocalReduce = epi_loop_tensors.get("mLocalReduce")
+                    if const_expr(params.local_reduce_feeds_main):
+                        tDrLocalReduce = tDrLocalReduce.local_reduce
+                    tDrLocalReduce.store(epilogue_result[1])
+                    main_result = epilogue_result[0]
+                    if const_expr(self.grouped_n_contract_group == 1):
+                        tRS_rD.store(main_result)
+                result_dtype = self.acc_dtype
+                if const_expr(self.grouped_n_contract_group != 1):
+                    result_dtype = main_result.element_type
+                tRS_rAuxOut = cute.make_rmem_tensor(main_result.shape, result_dtype)
+                tRS_rAuxOut.store(main_result)
+        elif const_expr(params.act_fn is not None):
+            tRS_rAuxOut = cute.make_rmem_tensor(tRS_rD.layout.shape, self.acc_dtype)
+            if const_expr(self.arch != 100):
+                for i in cutlass.range(cute.size(tRS_rAuxOut), unroll_full=True):
+                    tRS_rAuxOut[i] = params.act_fn(tRS_rD[i])
+            else:
+                for i in cutlass.range(cute.size(tRS_rAuxOut) // 2, unroll_full=True):
+                    tRS_rAuxOut[2 * i], tRS_rAuxOut[2 * i + 1] = params.act_fn(
+                        (tRS_rD[2 * i], tRS_rD[2 * i + 1])
+                    )
+        else:
+            tRS_rAuxOut = tRS_rD
+        return tRS_rAuxOut
+
+
+class GemmActSm90(GemmActMixin, GemmSm90):
+    pass
+
+
+class GemmActSm80(GemmActMixin, GemmSm80):
+    pass
+
+
+class GemmActSm100(GemmActMixin, GemmSm100):
+    pass
+
+
+class GemmActSm120(GemmActMixin, GemmSm120):
+    pass
+
+
+def _grouped_n_contract_epi_tile(epi_tile, group):
+    if isinstance(epi_tile[1], cute.Layout):
+        return (epi_tile[0], cute.recast_layout(group, 1, epi_tile[1]))
+    return (epi_tile[0], epi_tile[1] // group)
+
+
+def _grouped_n_contract_epi_tile_fn(gemm, epi_tile):
+    return _grouped_n_contract_epi_tile(epi_tile, 2)
+
+
+def _grouped_n_contract4_epi_tile_fn(gemm, epi_tile):
+    return _grouped_n_contract_epi_tile(epi_tile, 4)
+
+
+class GemmGroupedNContractMixin(GemmActMixin):
+    """Store the contracted logical main through PostAct while leaving D unused.
+
+    TODO: Move this specialization behind a stable provider-extension boundary
+    so Inductor can own it beside the generated epilogue.
+    """
+
+    grouped_n_contract_group = 2
+    _epi_ops = (
+        Scalar("alpha"),
+        Scalar("beta"),
+        Scalar("sr_seed", dtype=Int32),
+        RowVecLoad("mRowVecBroadcast"),
+        ColVecLoad("mColVecBroadcast"),
+        ColVecTupleLoad("mTensorEpilogueColVecBroadcasts"),
+        ScalarTupleLoad("mTensorEpilogueScalars"),
+        # TODO: Add row/tile captures after chunked N-sensitive loads are remapped.
+        TileStore("mAuxOut", epi_tile_fn=_grouped_n_contract_epi_tile_fn),
+    )
+
+    def epi_to_underlying_arguments(
+        self, args: GemmActMixin.EpilogueArguments, *, loc=None, ip=None
+    ):
+        params = super().epi_to_underlying_arguments(args, loc=loc, ip=ip)
+        self.cta_tile_shape_aux_out_mn = (
+            self.cta_tile_shape_mnk[0],
+            self.cta_tile_shape_mnk[1] // self.grouped_n_contract_group,
+        )
+        return params
+
+class GemmGroupedNContractSm100(GemmGroupedNContractMixin, GemmSm100):
+    pass
+
+
+class GemmGroupedNContract4Sm100(GemmGroupedNContractMixin, GemmSm100):
+    grouped_n_contract_group = 4
+    _epi_ops = (
+        Scalar("alpha"),
+        Scalar("beta"),
+        Scalar("sr_seed", dtype=Int32),
+        RowVecLoad("mRowVecBroadcast"),
+        ColVecLoad("mColVecBroadcast"),
+        ColVecTupleLoad("mTensorEpilogueColVecBroadcasts"),
+        ScalarTupleLoad("mTensorEpilogueScalars"),
+        TileStore("mAuxOut", epi_tile_fn=_grouped_n_contract4_epi_tile_fn),
+    )
+
+
+def _gated_epi_tile_fn(gemm, epi_tile):
+    """Halve the N dimension of the epi_tile for gated postact."""
+    if isinstance(epi_tile[1], cute.Layout):
+        return (epi_tile[0], cute.recast_layout(2, 1, epi_tile[1]))
+    return (epi_tile[0], epi_tile[1] // 2)
+
+
+
+class GemmGatedMixin(GemmActMixin):
+    _epi_ops = (
+        Scalar("alpha"),
+        Scalar("beta"),
+        Scalar("sr_seed", dtype=Int32),
+        RowVecLoad("mRowVecBroadcast"),
+        ColVecLoad("mColVecBroadcast"),
+        TileStore("mAuxOut", epi_tile_fn=_gated_epi_tile_fn),
+    )
+
+    def epi_to_underlying_arguments(
+        self, args: GemmActMixin.EpilogueArguments, *, loc=None, ip=None
+    ) -> GemmActMixin.EpilogueParams:
+        assert args.mAuxOut.element_type.width == 16, (
+            "GemmGated only supports 16bit postact for now"
+        )
+        assert self.d_layout is None or self.d_layout.is_n_major_c()
+        assert cutlass.utils.LayoutEnum.from_tensor(args.mAuxOut).is_n_major_c()
+        if self.arch == 90:
+            assert self.cta_tile_shape_mnk[1] % 32 == 0, (
+                "GemmGatedSm90 requires tileN to be divisible by 32"
+            )
+        self.rounding_mode = args.rounding_mode
+        self.aux_out_dtype = args.mAuxOut.element_type
+        self.aux_out_layout = cutlass.utils.LayoutEnum.from_tensor(args.mAuxOut)
+        self.cta_tile_shape_aux_out_mn = (
+            self.cta_tile_shape_mnk[0],
+            self.cta_tile_shape_mnk[1] // 2,
+        )
+        d = self._epi_ops_to_params_dict(args)
+        d["act_fn"] = args.act_fn
+        for key in ("mRowVecBroadcast", "mColVecBroadcast"):
+            if key in self.concat_layout and key in d:
+                d[key] = layout_utils.concat_to_interleave(d[key], 1)
+        return self.EpilogueParams(**d)
+
+    @cute.jit
+    def epi_visit_subtile(
+        self,
+        params: GemmActMixin.EpilogueParams,
+        epi_loop_tensors: Tuple[cute.Tensor, ...],
+        tRS_rD: cute.Tensor,
+        tRS_rC: Optional[cute.Tensor] = None,
+    ) -> Optional[cute.Tensor]:
+        GemmDefaultEpiMixin.epi_visit_subtile(self, params, epi_loop_tensors, tRS_rD, tRS_rC)
+        tRS_rAuxOut_layout = cute.recast_layout(2, 1, tRS_rD.layout)
+        # If we don't have .shape here, the compiler generates local stores and loads
+        tRS_rAuxOut = cute.make_rmem_tensor(tRS_rAuxOut_layout.shape, self.acc_dtype)
+        if const_expr(self.arch != 100):
+            for i in cutlass.range(cute.size(tRS_rAuxOut), unroll_full=True):
+                tRS_rAuxOut[i] = params.act_fn(tRS_rD[2 * i], tRS_rD[2 * i + 1])
+        else:
+            for i in cutlass.range(cute.size(tRS_rAuxOut) // 2, unroll_full=True):
+                tRS_rAuxOut[2 * i], tRS_rAuxOut[2 * i + 1] = params.act_fn(
+                    (tRS_rD[4 * i], tRS_rD[4 * i + 2]), (tRS_rD[4 * i + 1], tRS_rD[4 * i + 3])
+                )
+        return tRS_rAuxOut
+
+    @cute.jit
+    def epi_convert_aux_out(
+        self, tRS_rAuxOut, sr_seed, tidx, tile_coord_mnkl, num_prev_subtiles, epi_idx
+    ):
+        tRS_rAuxOut_out = GemmActMixin.epi_convert_aux_out(
+            self, tRS_rAuxOut, sr_seed, tidx, tile_coord_mnkl, num_prev_subtiles, epi_idx
+        )
+        if const_expr(self.arch in (90, 120)):
+            # Only need this if we're using STSM
+            permute_gated_Cregs_b16(tRS_rAuxOut_out)
+        return tRS_rAuxOut_out
+
+
+class GemmGatedSm90(GemmGatedMixin, GemmSm90):
+    pass
+
+
+class GemmGatedSm80(GemmGatedMixin, GemmSm80):
+    pass
+
+
+class GemmGatedSm100(GemmGatedMixin, GemmSm100):
+    pass
+
+
+class GemmGatedSm120Mixin:
+    @staticmethod
+    def _compute_tile_shape_or_override(
+        cta_tile_shape_mnk: Tuple[int, int, int],
+        atom_layout_mnk: Tuple[int, int, int],
+        element_type: Optional[Type[cutlass.Numeric]] = None,
+        epi_tile_override: Tuple[int, int] | None = None,
+    ) -> Tuple[int, int]:
+        if epi_tile_override is not None:
+            return epi_tile_override
+        # Typically epi_tile is (64, 32) but since we want tile_n = 64 (see below), we might set
+        # tile_m = 32 if there's only 2 warps along the M direction.
+        tile_m = math.gcd(atom_layout_mnk[0] * 16, cute.size(cta_tile_shape_mnk, mode=[0]))
+        atom_n = atom_layout_mnk[1]
+        # E.g. if we have 2 warps along N direction, we want each warp to have 32 elems so that
+        # postact has 16 elements, which means tile_n should be 64.
+        tile_n = math.gcd(atom_n * 8 * 4, cute.size(cta_tile_shape_mnk, mode=[1]))
+        return (tile_m, tile_n)
+
+    def epi_make_aux_out_tiled_copy_r2s(self, params, tiled_copy_r2s, tiled_copy_t2r):
+        copy_atom_aux_out_r2s = self.epi_make_aux_out_copy_atom_r2s(params, tiled_copy_t2r)
+        copy_atom_postact_c = self.epi_make_aux_out_copy_atom_r2s(params, cutlass.Float16)
+        op = warp.MmaF16BF16Op(self.a_dtype, self.acc_dtype, self.mma_inst_mnk)
+        tC = cute.make_layout(self.atom_layout_mnk)
+        atom_m, atom_n, atom_k = self.atom_layout_mnk
+        permutation_mnk = (
+            self.mma_inst_mnk[0] * atom_m,
+            self.mma_inst_mnk[1] * atom_n * 2,
+            self.mma_inst_mnk[2] * atom_k,
+        )
+        tiled_mma_gated_postact = cute.make_tiled_mma(op, tC, permutation_mnk=permutation_mnk)
+        tiled_copy_aux_out_c_atom = cute.make_tiled_copy_C_atom(
+            copy_atom_postact_c, tiled_mma_gated_postact
+        )
+        return cute.make_tiled_copy_S(copy_atom_aux_out_r2s, tiled_copy_aux_out_c_atom)
+
+
+class GemmGatedSm120(GemmGatedSm120Mixin, GemmGatedMixin, GemmSm120):
+    pass
+
+
+@jit_cache
+def _compile_gemm_act(
+    a_dtype,
+    b_dtype,
+    d_dtype,
+    c_dtype,
+    postact_dtypes,
+    a_major,
+    b_major,
+    d_major,
+    c_major,
+    postact_majors,
+    tile_shape_mn,
+    cluster_shape_mnk,
+    pingpong,
+    persistent,
+    is_dynamic_persistent,
+    activation,
+    tensor_epilogue_key,
+    tensor_epilogue_arg_kinds,
+    tensor_epilogue_returns_aux,
+    tensor_epilogue_returns_local_reduce,
+    local_reduce_feeds_main,
+    tensor_epilogue_rowvec_dtypes,
+    tensor_epilogue_colvec_dtypes,
+    tensor_epilogue_colvec_ndims,
+    tensor_epilogue_tile_dtypes,
+    tensor_epilogue_tile_majors,
+    tensor_epilogue_scalar_dtypes,
+    local_reduce_dtype,
+    local_reduce_ndim,
+    local_reduce_group,
+    local_reduce_axis,
+    local_reduce_stride_divisibility,
+    local_reduce_combine_key,
+    local_reduce_finalize_key,
+    alpha_mode,
+    beta_mode,
+    rowvec_dtype,
+    colvec_dtype,
+    colvec_ndim,
+    main_output_transform_group,
+    varlen_m,
+    gather_A,
+    concat_layout,
+    device_capacity,
+    gemm_cls_name,
+    rounding_mode=RoundingMode.RN,
+    sr_seed_mode=0,
+    use_tma_gather=False,
+):
+    sm_to_cls = {
+        "act": {
+            8: GemmActSm80,
+            9: GemmActSm90,
+            10: GemmActSm100,
+            11: GemmActSm100,
+            12: GemmActSm120,
+        },
+        "gated": {
+            8: GemmGatedSm80,
+            9: GemmGatedSm90,
+            10: GemmGatedSm100,
+            11: GemmGatedSm100,
+            12: GemmGatedSm120,
+        },
+        "grouped_n_contract": {
+            10: GemmGroupedNContractSm100,
+            11: GemmGroupedNContractSm100,
+        },
+    }
+    GemmCls = sm_to_cls[gemm_cls_name][device_capacity[0]]
+    if gemm_cls_name == "grouped_n_contract" and main_output_transform_group == 4:
+        GemmCls = GemmGroupedNContract4Sm100
+    postact_dtype = postact_dtypes[0]
+    postact_major = postact_majors[0]
+    pa_leading = 1 if postact_major == "n" else 0
+    mA, mB, mD, mC, m, n, k, l = make_fake_gemm_tensors(
+        a_dtype,
+        b_dtype,
+        d_dtype,
+        c_dtype,
+        a_major,
+        b_major,
+        d_major,
+        c_major,
+        varlen_m=varlen_m,
+        gather_A=gather_A,
+    )
+    pa_n = (
+        cute.sym_int()
+        if gemm_cls_name in ("gated", "grouped_n_contract")
+        else n
+    )
+    pa_shape = (m, pa_n) if varlen_m else (m, pa_n, l)
+    if tensor_epilogue_returns_aux:
+        mAuxOut = tuple(
+            fake_tensor(
+                dtype,
+                pa_shape,
+                leading_dim=1 if major == "n" else 0,
+                divisibility=div_for_dtype(dtype),
+            )
+            for dtype, major in zip(postact_dtypes, postact_majors)
+        )
+    else:
+        div_pa = div_for_dtype(postact_dtype)
+        pa_leading_dim = (
+            1 if gemm_cls_name in ("gated", "grouped_n_contract") else pa_leading
+        )
+        mAuxOut = fake_tensor(
+            postact_dtype, pa_shape, leading_dim=pa_leading_dim, divisibility=div_pa
+        )
+
+    mRowVec = fake_tensor(rowvec_dtype, (l, n), leading_dim=1, divisibility=4)
+    mTensorEpilogueRowVecs = tuple(
+        fake_tensor(dtype, (l, n), leading_dim=1, divisibility=4)
+        for dtype in tensor_epilogue_rowvec_dtypes
+    ) or None
+    mTensorEpilogueTiles = tuple(
+        fake_tensor(
+            dtype,
+            (m, n, l),
+            leading_dim=1 if major == "n" else 0,
+            divisibility=div_for_dtype(dtype),
+        )
+        for dtype, major in zip(tensor_epilogue_tile_dtypes, tensor_epilogue_tile_majors)
+    ) or None
+    if colvec_ndim == 2:
+        mColVec = fake_tensor(colvec_dtype, (l, m), leading_dim=1, divisibility=4)
+    elif colvec_ndim == 1:
+        mColVec = fake_tensor(colvec_dtype, (m,), leading_dim=0, divisibility=4)
+    else:
+        mColVec = None
+    mTensorEpilogueColVecs = tuple(
+        fake_tensor(
+            dtype,
+            (l, m) if ndim == 2 else (m,),
+            leading_dim=1 if ndim == 2 else 0,
+            divisibility=4,
+        )
+        for dtype, ndim in zip(tensor_epilogue_colvec_dtypes, tensor_epilogue_colvec_ndims)
+    ) or None
+    mTensorEpilogueScalars = tuple(
+        fake_tensor(dtype, (1,), leading_dim=0, divisibility=1)
+        for dtype in tensor_epilogue_scalar_dtypes
+    ) or None
+    if local_reduce_dtype is not None and local_reduce_axis == 0:
+        local_reduce_shape = (
+            (l, cute.sym_int(), n) if local_reduce_ndim == 3 else (cute.sym_int(), n)
+        )
+    elif local_reduce_dtype is not None:
+        local_reduce_shape = (
+            (l, m, cute.sym_int()) if local_reduce_ndim == 3 else (m, cute.sym_int())
+        )
+    else:
+        local_reduce_shape = None
+    if (
+        local_reduce_dtype is None
+        or (local_reduce_feeds_main and local_reduce_ndim == 0)
+    ):
+        mLocalReduce = None
+    else:
+        local_reduce_leading_dim = 2 if local_reduce_ndim == 3 else 1
+        mLocalReduce = fake_tensor(
+            local_reduce_dtype,
+            local_reduce_shape,
+            leading_dim=local_reduce_leading_dim,
+            divisibility=local_reduce_stride_divisibility,
+        )
+
+    tensor_epilogue_fn = (
+        _tensor_epilogue_fns[tensor_epilogue_key]
+        if tensor_epilogue_key is not None and activation is None
+        else None
+    )
+    local_reduce_combine_fn = (
+        _local_reduce_combine_fns[local_reduce_combine_key]
+        if local_reduce_combine_key is not None
+        else None
+    )
+    local_reduce_finalize_fn = (
+        _local_reduce_finalize_fns[local_reduce_finalize_key]
+        if local_reduce_finalize_key is not None
+        else None
+    )
+    act_fn = None if tensor_epilogue_fn is not None else (
+        act_fn_map[activation] if gemm_cls_name == "act" else gate_fn_map[activation]
+    )
+
+    def fake_scalar(mode, dtype=Int32):
+        if mode == 0:
+            return None
+        elif mode == 1:
+            return dtype(0)
+        else:
+            return make_ptr(dtype, 0, cute.AddressSpace.gmem, assumed_align=4)
+
+    epi_args = GemmCls.EpilogueArguments(
+        mAuxOut=mAuxOut,
+        act_fn=act_fn,
+        tensor_epilogue_fn=tensor_epilogue_fn,
+        tensor_epilogue_arg_kinds=tensor_epilogue_arg_kinds,
+        tensor_epilogue_returns_aux=tensor_epilogue_returns_aux,
+        tensor_epilogue_returns_local_reduce=tensor_epilogue_returns_local_reduce,
+        local_reduce_feeds_main=local_reduce_feeds_main,
+        local_reduce_group=local_reduce_group,
+        local_reduce_axis=local_reduce_axis,
+        local_reduce_combine_fn=local_reduce_combine_fn,
+        local_reduce_finalize_fn=local_reduce_finalize_fn,
+        alpha=fake_scalar(alpha_mode, Float32),
+        beta=fake_scalar(beta_mode, Float32),
+        mRowVecBroadcast=mRowVec,
+        mColVecBroadcast=mColVec,
+        mTensorEpilogueRowVecBroadcasts=mTensorEpilogueRowVecs,
+        mTensorEpilogueColVecBroadcasts=mTensorEpilogueColVecs,
+        mTensorEpilogueTiles=mTensorEpilogueTiles,
+        mTensorEpilogueScalars=mTensorEpilogueScalars,
+        mLocalReduce=mLocalReduce,
+        rounding_mode=rounding_mode,
+        sr_seed=fake_scalar(sr_seed_mode),
+    )
+    scheduler_args = make_fake_scheduler_args(
+        (is_dynamic_persistent and device_capacity[0] == 9), False, l
+    )
+    varlen_args = make_fake_varlen_args(
+        varlen_m, False, gather_A, m if varlen_m else None
+    )
+    return compile_gemm_kernel(
+        GemmCls,
+        a_dtype,
+        tile_shape_mn,
+        cluster_shape_mnk,
+        pingpong,
+        persistent,
+        gather_A,
+        is_dynamic_persistent,
+        device_capacity,
+        mA,
+        mB,
+        mD,
+        mC,
+        epi_args,
+        scheduler_args,
+        varlen_args,
+        use_tma_gather=use_tma_gather,
+        concat_layout=concat_layout or None,
+    )
+
+
+def gemm_act(
+    A: Tensor,  # (l, m, k) or (total_m, k) if varlen_m or (whatever, k) if gather_A with varlen_m
+    B: Tensor,  # (l, n, k)
+    D: Optional[Tensor],  # (l, m, n) or (total_m, n) if varlen_m
+    C: Optional[Tensor],  # (l, m, n) or (total_m, n) if varlen_m
+    PostAct: Tensor | tuple[Tensor, ...],  # tensor epilogues pass same-shape aux outputs as a tuple
+    tile_count_semaphore: Optional[Tensor],  # (1,)
+    activation: Optional[str],
+    tile_M: int,
+    tile_N: int,
+    cluster_M: int,
+    cluster_N: int,
+    tile_K: int | None = None,
+    pingpong: bool = False,
+    persistent: bool = True,
+    is_dynamic_persistent: bool = False,
+    max_swizzle_size: int = 8,
+    rowvec_bias: Optional[Tensor] = None,  # (l, n)
+    colvec_bias: Optional[Tensor] = None,  # (l, m), or (total_m,) if varlen_m
+    cu_seqlens_m: Optional[Tensor] = None,  # (l+1,) cumulative sum of m values for variable length
+    A_idx: Optional[Tensor] = None,  # (total_m,) if gather_A with varlen_m
+    rounding_mode: int = RoundingMode.RN,
+    sr_seed: int | Tensor = 0,
+    use_tma_gather: bool = False,
+    concat_layout: tuple | None = None,
+    tensor_epilogue_fn: Optional[Callable] = None,
+    tensor_epilogue_key: Optional[str] = None,
+    tensor_epilogue_returns_aux: bool = False,
+    tensor_epilogue_returns_local_reduce: bool = False,
+    local_reduce_feeds_main: bool = False,
+    tensor_epilogue_arg_kinds: tuple[str, ...] = (),
+    tensor_epilogue_rowvec_biases: tuple[Tensor, ...] = (),
+    tensor_epilogue_colvec_biases: tuple[Tensor, ...] = (),
+    tensor_epilogue_tile_biases: tuple[Tensor, ...] = (),
+    tensor_epilogue_scalar_biases: tuple[Tensor, ...] = (),
+    local_reduce_out: Optional[Tensor] = None,
+    local_reduce_group: int = 0,
+    local_reduce_axis: int = 1,
+    local_reduce_combine_key: Optional[str] = None,
+    local_reduce_finalize_key: Optional[str] = None,
+    main_output_transform_group: int | None = None,
+    alpha: float | Tensor = 1.0,
+    beta: float | Tensor = 1.0,
+    device_capacity_override: tuple[int, int] | None = None,
+) -> None:
+    """Run GEMM with an optional generated tensor epilogue and local reduction.
+
+    Local reductions group the logical GEMM output ``[L, M, N]``. Axis 0 groups
+    M and writes ``local_reduce_out`` with shape ``[L, M / group, N]``; axis 1
+    groups N and writes ``[L, M, N / group]``. ``local_reduce_group`` must be
+    positive, divide the selected dimension, and fit the selected GEMM tile.
+    ``local_reduce_out`` is always 3-D at this QuACK boundary.
+
+    When ``tensor_epilogue_returns_local_reduce`` is true, the generated tensor
+    epilogue's final return value, after the main result and any same-shape aux
+    results, supplies the grouped reduction. The flag and ``local_reduce_out``
+    must be provided together, and a tensor epilogue function or registry key is
+    required.
+
+    ``local_reduce_feeds_main`` instead reduces the accumulator, broadcasts the
+    finalized group value to its member rows, and appends it as the final input
+    to the tensor epilogue. It does not request an output store by itself. This
+    mode requires a tensor epilogue and both callback keys, and currently accepts
+    only axis-0 groups that fit within one warp. The callback omission described
+    below applies only to store-only reductions.
+
+    ``local_reduce_combine_key`` and ``local_reduce_finalize_key`` identify
+    CuTeDSL callbacks registered with ``register_local_reduce_fns``. The binary
+    combine callback merges two physical partial values using the reduction
+    operation. The unary finalize callback transforms the fully combined value
+    before conversion and storage. Both keys are required whenever the grouped
+    reduction needs physical lane, warp, or fragment combining; they may be
+    omitted when the tensor epilogue returns an already-complete TensorSSA group.
+
+    Returns:
+        None. Results are written to the supplied output tensors.
+    """
+    if tensor_epilogue_fn is not None:
+        assert activation is None, "tensor_epilogue_fn and activation are mutually exclusive"
+        tensor_epilogue_key = (
+            tensor_epilogue_key
+            if tensor_epilogue_key is not None
+            else repr(tensor_epilogue_fn)
+        )
+        register_tensor_epilogue_fn(tensor_epilogue_key, tensor_epilogue_fn)
+        gemm_cls_name = "act"
+    elif activation in gate_fn_map:
+        gemm_cls_name = "gated"
+    else:
+        assert activation in act_fn_map, f"Unsupported activation {activation}"
+        gemm_cls_name = "act"
+    if main_output_transform_group is not None:
+        if main_output_transform_group not in (2, 4):
+            raise NotImplementedError(
+                f"unsupported grouped_n_contract group={main_output_transform_group}"
+            )
+        if main_output_transform_group == 4 and concat_layout and "B" in concat_layout:
+            raise NotImplementedError(
+                "grouped_n_contract group 4 does not yet support chunked B layout"
+            )
+        if tensor_epilogue_fn is None and tensor_epilogue_key is None:
+            raise RuntimeError("grouped_n_contract requires a generated tensor epilogue")
+        if tensor_epilogue_returns_aux or tensor_epilogue_returns_local_reduce:
+            raise NotImplementedError(
+                "grouped_n_contract does not compose with auxiliary outputs"
+            )
+        gemm_cls_name = "grouped_n_contract"
+
+    if tensor_epilogue_returns_aux:
+        if not isinstance(PostAct, tuple):
+            raise RuntimeError("tensor epilogue aux outputs must be passed as a tuple")
+        postact_tensors = PostAct
+    else:
+        postact_tensors = (PostAct,)
+    if main_output_transform_group is not None and any(
+        tensor.stride(-1) != 1 for tensor in postact_tensors
+    ):
+        raise NotImplementedError("grouped_n_contract requires PostAct to be n-major")
+    if main_output_transform_group is not None:
+        physical_n = B.shape[-2]
+        if physical_n % main_output_transform_group != 0:
+            raise RuntimeError(
+                f"grouped_n_contract physical N={physical_n} must be divisible by "
+                f"group={main_output_transform_group}"
+            )
+        expected_shape = (*A.shape[:-1], physical_n // main_output_transform_group)
+        for tensor in postact_tensors:
+            if tuple(tensor.shape) != expected_shape:
+                raise RuntimeError(
+                    "grouped_n_contract requires PostAct shape "
+                    f"{expected_shape}, got {tuple(tensor.shape)}"
+                )
+    varlen_m = cu_seqlens_m is not None
+    gather_A = A_idx is not None
+    if varlen_m:
+        assert persistent, "varlen_m requires persistent=True"
+        assert A.stride(-1) == 1, "varlen_m requires A to be k-major"
+        if D is not None:
+            assert D.stride(-1) == 1, "varlen_m requires D to be n-major"
+        assert all(
+            tensor.stride(-1) == 1 for tensor in postact_tensors
+        ), "varlen_m requires PostAct to be n-major"
+    if gather_A:
+        assert varlen_m, "gather_A requires varlen_m"
+        assert cluster_N == 1, "gather_A requires cluster_N=1"
+
+    A_p = perm3d_single(A, varlen_m)
+    B_p = perm3d_single(B)
+    D_p = perm3d_single(D, varlen_m)
+    C_p = perm3d_single(C, varlen_m)
+    if tensor_epilogue_returns_aux:
+        PostAct_p = tuple(perm3d_single(tensor, varlen_m) for tensor in postact_tensors)
+    else:
+        PostAct_p = perm3d_single(PostAct, varlen_m)
+    tensor_epilogue_tile_biases_p = tuple(
+        perm3d_single(tensor, varlen_m) for tensor in tensor_epilogue_tile_biases
+    )
+
+    a_major = get_major(A_p, "m", "k")
+    b_major = get_major(B_p, "n", "k")
+    d_major = get_major(D_p, "m", "n") if D_p is not None else None
+    c_major = get_major(C_p, "m", "n") if C_p is not None else None
+    postact_majors = (
+        tuple(get_major(tensor, "m", "n") for tensor in PostAct_p)
+        if isinstance(PostAct_p, tuple)
+        else (get_major(PostAct_p, "m", "n"),)
+    )
+
+    a_dtype = torch2cute_dtype_map[A.dtype]
+    b_dtype = torch2cute_dtype_map[B.dtype]
+    d_dtype = torch2cute_dtype_map[D.dtype] if D is not None else None
+    c_dtype = torch2cute_dtype_map[C.dtype] if C is not None else None
+    postact_dtypes = (
+        tuple(torch2cute_dtype_map[tensor.dtype] for tensor in PostAct)
+        if isinstance(PostAct, tuple)
+        else (torch2cute_dtype_map[PostAct.dtype],)
+    )
+    if not set(tensor_epilogue_arg_kinds) <= {"tile", "row", "col", "scalar"}:
+        raise NotImplementedError(
+            f"QUACK tensor epilogues support only tile/row/col/scalar aux tensors, got {tensor_epilogue_arg_kinds}"
+        )
+    expected_tensor_epilogue_arg_counts = {
+        "row": len(tensor_epilogue_rowvec_biases),
+        "col": len(tensor_epilogue_colvec_biases),
+        "tile": len(tensor_epilogue_tile_biases),
+        "scalar": len(tensor_epilogue_scalar_biases),
+    }
+    actual_tensor_epilogue_arg_counts = {
+        kind: tensor_epilogue_arg_kinds.count(kind)
+        for kind in expected_tensor_epilogue_arg_counts
+    }
+    if actual_tensor_epilogue_arg_counts != expected_tensor_epilogue_arg_counts:
+        raise RuntimeError(
+            "tensor_epilogue_arg_kinds must match row/col/tile/scalar tensor epilogue args"
+        )
+    tensor_epilogue_arg_kind_codes = tuple(
+        {"tile": 1, "row": 2, "col": 3, "scalar": 4}[kind]
+        for kind in tensor_epilogue_arg_kinds
+    )
+    colvec_ndim = colvec_bias.ndim if colvec_bias is not None else 0
+
+    device_capacity = (
+        device_capacity_override
+        if device_capacity_override is not None
+        else get_device_capacity(A.device)
+    )
+    assert device_capacity[0] in [8, 9, 10, 11, 12], (
+        "Only SM8x, SM90, SM100, SM110, and SM120 are supported"
+    )
+    validate_grouped_n_contract_device(main_output_transform_group, device_capacity)
+    if rounding_mode == RoundingMode.RS:
+        assert device_capacity[0] == 10, "Stochastic rounding (RoundingMode.RS) requires SM100"
+
+    if is_dynamic_persistent and device_capacity[0] == 9:
+        assert tile_count_semaphore is not None, (
+            "Dynamic persistent tile scheduler in SM90 requires a semaphore in GMEM"
+        )
+
+    sr_seed_mode = (
+        2 if isinstance(sr_seed, Tensor) else (1 if rounding_mode == RoundingMode.RS else 0)
+    )
+    alpha_mode = 2 if isinstance(alpha, Tensor) else (1 if alpha != 1.0 else 0)
+    beta_mode = 2 if isinstance(beta, Tensor) else (1 if beta != 1.0 else 0)
+    if (tensor_epilogue_arg_kinds or local_reduce_feeds_main) and (
+        C is not None or alpha_mode != 0 or beta_mode != 0
+    ):
+        raise NotImplementedError(
+            "QUACK tensor epilogues with aux args or feed-main local reductions "
+            "cannot be combined with C/alpha/beta yet"
+        )
+    if tensor_epilogue_returns_local_reduce != (local_reduce_out is not None):
+        raise RuntimeError(
+            "tensor_epilogue_returns_local_reduce requires local_reduce_out and vice versa"
+        )
+    if local_reduce_feeds_main:
+        if local_reduce_axis != 0:
+            raise NotImplementedError("local_reduce_feeds_main currently supports only axis 0")
+        if local_reduce_group <= 0:
+            raise RuntimeError("local_reduce_group must be positive")
+        if local_reduce_group > LOCAL_REDUCE_FRAGMENT_WIDTH:
+            raise NotImplementedError(
+                "local_reduce_feeds_main currently supports only same-warp axis-0 "
+                f"groups <= {LOCAL_REDUCE_FRAGMENT_WIDTH}"
+            )
+        if tensor_epilogue_fn is None and tensor_epilogue_key is None:
+            raise RuntimeError(
+                "local_reduce_feeds_main requires tensor_epilogue_fn or tensor_epilogue_key"
+            )
+        if local_reduce_combine_key is None or local_reduce_finalize_key is None:
+            raise RuntimeError(
+                "local_reduce_feeds_main requires generated local-reduce callback keys"
+            )
+        if LOCAL_REDUCE_FRAGMENT_WIDTH % local_reduce_group != 0:
+            raise RuntimeError(
+                "local_reduce_group must divide TensorSSA fragment width 32"
+            )
+        if A.shape[-2] % local_reduce_group != 0:
+            raise RuntimeError(
+                "local_reduce_group must divide the selected GEMM output dimension"
+            )
+    if local_reduce_out is not None and tensor_epilogue_fn is None and tensor_epilogue_key is None:
+        raise RuntimeError("local_reduce_out requires tensor_epilogue_fn")
+    if local_reduce_out is not None:
+        if local_reduce_group <= 0:
+            raise RuntimeError("local_reduce_group must be positive")
+        if local_reduce_axis not in (0, 1):
+            raise RuntimeError("local_reduce_axis must be 0 or 1")
+        if (
+            local_reduce_axis == 0
+            or local_reduce_group > LOCAL_REDUCE_FRAGMENT_WIDTH
+        ) and (
+            local_reduce_combine_key is None or local_reduce_finalize_key is None
+        ):
+            raise RuntimeError(
+                "physical local reductions require generated local-reduce callback keys"
+            )
+        if local_reduce_out.ndim != 3:
+            raise NotImplementedError("QUACK local_reduce_out must be 3-D")
+    concat_layout = tuple(sorted(concat_layout)) if concat_layout else ()
+    local_reduce_dtype = (
+        torch2cute_dtype_map[local_reduce_out.dtype]
+        if local_reduce_out is not None
+        else (Float32 if local_reduce_feeds_main else None)
+    )
+    local_reduce_leading_dim = (
+        2 if local_reduce_out is not None and local_reduce_out.ndim == 3 else 1
+    )
+    local_reduce_stride_divisibility = (
+        tensor_stride_divisibility(
+            local_reduce_out, local_reduce_dtype, local_reduce_leading_dim
+        )
+        if local_reduce_out is not None
+        else 1
+    )
+    compiled_fn = _compile_gemm_act(
+        a_dtype,
+        b_dtype,
+        d_dtype,
+        c_dtype,
+        postact_dtypes,
+        a_major,
+        b_major,
+        d_major,
+        c_major,
+        postact_majors,
+        (tile_M, tile_N, tile_K) if tile_K is not None else (tile_M, tile_N),
+        (cluster_M, cluster_N, 1),
+        pingpong,
+        persistent,
+        is_dynamic_persistent,
+        activation,
+        tensor_epilogue_key,
+        tensor_epilogue_arg_kind_codes,
+        tensor_epilogue_returns_aux,
+        tensor_epilogue_returns_local_reduce,
+        local_reduce_feeds_main,
+        tuple(torch2cute_dtype_map[tensor.dtype] for tensor in tensor_epilogue_rowvec_biases),
+        tuple(torch2cute_dtype_map[tensor.dtype] for tensor in tensor_epilogue_colvec_biases),
+        tuple(tensor.ndim for tensor in tensor_epilogue_colvec_biases),
+        tuple(torch2cute_dtype_map[tensor.dtype] for tensor in tensor_epilogue_tile_biases_p),
+        tuple(get_major(tensor, "m", "n") for tensor in tensor_epilogue_tile_biases_p),
+        tuple(torch2cute_dtype_map[tensor.dtype] for tensor in tensor_epilogue_scalar_biases),
+        local_reduce_dtype,
+        local_reduce_out.ndim if local_reduce_out is not None else 0,
+        local_reduce_group,
+        local_reduce_axis,
+        local_reduce_stride_divisibility,
+        local_reduce_combine_key,
+        local_reduce_finalize_key,
+        alpha_mode,
+        beta_mode,
+        torch2cute_dtype_map[rowvec_bias.dtype] if rowvec_bias is not None else None,
+        torch2cute_dtype_map[colvec_bias.dtype] if colvec_bias is not None else None,
+        colvec_ndim,
+        0 if main_output_transform_group is None else main_output_transform_group,
+        varlen_m,
+        gather_A,
+        concat_layout,
+        device_capacity,
+        gemm_cls_name,
+        rounding_mode=rounding_mode,
+        sr_seed_mode=sr_seed_mode,
+        use_tma_gather=use_tma_gather,
+    )
+
+    from .cache import is_compile_only
+
+    if is_compile_only():
+        return
+
+    max_active_clusters = get_max_active_clusters(cluster_M * cluster_N) if persistent else 0
+
+    def scalar_arg(scalar, mode, dtype=Int32):
+        if mode == 0:
+            return None
+        elif mode == 1:
+            return dtype(scalar)
+        else:
+            return scalar.data_ptr()
+
+    epi_args = GemmActMixin.EpilogueArguments(
+        mAuxOut=PostAct_p,
+        act_fn=None,
+        tensor_epilogue_fn=None,
+        tensor_epilogue_arg_kinds=None,
+        tensor_epilogue_returns_aux=None,
+        tensor_epilogue_returns_local_reduce=None,
+        local_reduce_feeds_main=None,
+        local_reduce_group=None,
+        local_reduce_axis=None,
+        local_reduce_combine_fn=None,
+        local_reduce_finalize_fn=None,
+        alpha=scalar_arg(alpha, alpha_mode, Float32),
+        beta=scalar_arg(beta, beta_mode, Float32),
+        mRowVecBroadcast=rowvec_bias,
+        mColVecBroadcast=colvec_bias,
+        mTensorEpilogueRowVecBroadcasts=tensor_epilogue_rowvec_biases or None,
+        mTensorEpilogueColVecBroadcasts=tensor_epilogue_colvec_biases or None,
+        mTensorEpilogueTiles=tensor_epilogue_tile_biases_p or None,
+        mTensorEpilogueScalars=tensor_epilogue_scalar_biases or None,
+        mLocalReduce=local_reduce_out,
+        rounding_mode=None,  # Constexpr, pass None at call time
+        sr_seed=scalar_arg(sr_seed, sr_seed_mode),
+    )
+    scheduler_args = make_scheduler_args(
+        max_active_clusters,
+        max_swizzle_size,
+        tile_count_semaphore,
+    )
+    varlen_args = make_varlen_args(cu_seqlens_m, None, A_idx)
+
+    if device_capacity[0] in [10, 11]:
+        compiled_fn(A_p, B_p, D_p, C_p, epi_args, scheduler_args, varlen_args, None, None, None)
+    else:
+        compiled_fn(A_p, B_p, D_p, C_p, epi_args, scheduler_args, varlen_args, None)
+
+
+gemm_gated = gemm_act
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_base.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..911e03b30f634dc211d673c9534bbcffda10590a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_base.py
@@ -0,0 +1,723 @@
+# Copyright (c) 2026, Tri Dao.
+
+import enum
+import math
+from dataclasses import dataclass
+from typing import Callable, Dict, Literal, Optional, Sequence, Tuple
+
+import cutlass
+import cutlass.cute as cute
+import cutlass.pipeline as pipeline
+from cutlass import Boolean, Int32, const_expr
+from cutlass.cute.nvgpu import cpasync
+from cutlass.utils import LayoutEnum
+
+from . import copy_utils
+from .cute_dsl_utils import ParamsBase
+from .epi_ops import EpiSmemBytes
+from .pipeline import PipelineTmaCpAsync
+from .rounding import RoundingMode, epilogue_sr_seed
+from .tile_scheduler import (
+    PersistenceMode,
+    TileScheduler,
+    TileSchedulerArguments,
+    VarlenMTileScheduler,
+    VarlenMTileSchedulerArguments,
+)
+from .varlen_utils import VarlenManager
+
+
+class NamedBarrierGemm(enum.IntEnum):
+    Epilogue = enum.auto()  # starts from 1 as barrier 0 is reserved for sync_threads()
+    # For mainloop load warps to signal that the epilogue load warp can start.
+    # This is to avoid loading C too early, interfering with loading A and B.
+    EpilogueLoad = enum.auto()
+    MmaWG0 = enum.auto()
+    MmaWG1 = enum.auto()
+    EpiWG0 = enum.auto()
+    EpiWG1 = enum.auto()
+    TmemPtr = enum.auto()
+
+
+class GemmBase:
+    """Common non-mainloop pieces shared by GEMM architectures."""
+
+    arch = 0
+
+    @dataclass
+    class EpilogueArguments:
+        pass
+
+    EpilogueParams = ParamsBase
+
+    def epi_smem_warp_shape_mnk(self):
+        return (self.num_epi_warps, 1, 1)
+
+    @cute.jit
+    def epilogue(
+        self,
+        params: EpilogueParams,
+        epi_smem_tensors: Dict[str, cute.Tensor],
+        epi_pipeline: Optional[cutlass.pipeline.PipelineAsync],
+        epi_store_pipeline: Optional[cutlass.pipeline.PipelineAsync],
+        epi_read_state: Optional[cutlass.pipeline.PipelineState],
+        epi_producer_state: Optional[cutlass.pipeline.PipelineState],
+        epi_tile: cute.Tile,
+        load_acc_subtile: Callable,
+        tRS_rD: cute.Tensor,
+        tRS_rC: Optional[cute.Tensor],
+        tiled_copy_t2r: Optional[cute.TiledCopy],  # Only for Sm100
+        tiled_copy_r2s: cute.TiledCopy,
+        tRS_sD: cute.Tensor,
+        tiled_copy_s2r: Optional[cute.ThrCopy],
+        tSR_rC: Optional[cute.Tensor],
+        tSR_sC: Optional[cute.Tensor],
+        copy_D: Optional[Callable],
+        copy_C: Optional[Callable],
+        tile_coord_mnkl: cute.Coord,
+        varlen_manager: VarlenManager,
+        epilogue_barrier: cutlass.pipeline.NamedBarrier,
+        tile_scheduler,
+        tidx: Int32,
+        is_tma_warp: cutlass.Boolean,
+    ) -> Tuple[cutlass.pipeline.PipelineState, cutlass.pipeline.PipelineState]:
+        has_C = const_expr(tRS_rC is not None)
+        has_epi_load = const_expr(self.epi_c_stage > 0)
+        has_D = const_expr(copy_D is not None)
+        use_tma_epi = const_expr(epi_store_pipeline is not None)
+        use_tma_c = const_expr(epi_pipeline is not None)
+        inline_epi_load = const_expr(copy_C is not None)
+        use_stochastic_rounding = const_expr(
+            self.rounding_mode == RoundingMode.RS
+            and self.acc_dtype == cutlass.Float32
+            and self.d_dtype == cutlass.BFloat16
+        )
+
+        # Setup aux output (returns None for default epilogue, context tuple for Act)
+        aux_out_ctx = self.epi_setup_aux_out(
+            params,
+            epi_smem_tensors,
+            tiled_copy_r2s,
+            tiled_copy_t2r,
+            tile_coord_mnkl,
+            varlen_manager,
+            tidx,
+        )
+
+        epi_tile_shape = cute.zipped_divide(
+            cute.make_layout(self.cta_tile_shape_mnk[:2]), epi_tile
+        ).shape[1]
+        epi_tile_layout = cute.make_ordered_layout(
+            epi_tile_shape, order=(0, 1) if const_expr(self.epi_m_major) else (1, 0)
+        )
+        epi_tile_num = cute.size(epi_tile_shape)
+        num_prev_subtiles = tile_scheduler.num_tiles_executed * epi_tile_num
+
+        epi_tensors = self.epi_begin(
+            params,
+            epi_smem_tensors,
+            epi_tile,
+            tiled_copy_t2r,
+            tiled_copy_r2s,
+            tile_coord_mnkl,
+            varlen_manager,
+            epilogue_barrier,
+            tidx,
+            tRS_rD.layout,
+        )
+
+        if const_expr(inline_epi_load):
+            for epi_idx in cutlass.range(min(epi_tile_num, self.epi_c_stage), unroll=1):
+                epi_coord_C = epi_tile_layout.get_hier_coord(epi_idx)
+                if const_expr(use_tma_c):
+                    if is_tma_warp:
+                        epi_pipeline.producer_acquire(epi_producer_state)
+                        copy_C(src_idx=epi_coord_C, producer_state=epi_producer_state)
+                        epi_pipeline.producer_commit(epi_producer_state)
+                    epi_producer_state.advance()
+                else:
+                    # TODO: turn this to cp.async instead of direct G2R copy
+                    copy_C(src_idx=epi_coord_C, dst_idx=epi_idx % self.epi_c_stage)
+            if const_expr(use_tma_c):
+                epilogue_barrier.arrive_and_wait()
+
+        for epi_idx in cutlass.range_constexpr(epi_tile_num):
+            epi_coord = epi_tile_layout.get_hier_coord(epi_idx)  # (epi_m, epi_n)
+            # Copy from acc to D registers
+            load_acc_subtile(tRS_rD, epi_coord)
+            if const_expr(has_epi_load):
+                if const_expr(use_tma_c):
+                    epi_pipeline.consumer_wait(epi_read_state)
+                    if const_expr(has_C):
+                        cute.copy(
+                            tiled_copy_s2r, tSR_sC[None, None, None, epi_read_state.index], tSR_rC
+                        )
+                    self.epi_tile_load_s2r(params, epi_tensors, epi_read_state.index)
+                    cute.arch.fence_view_async_shared()
+                    cute.arch.sync_warp()
+                    with cute.arch.elect_one():
+                        epi_pipeline.consumer_release(epi_read_state)
+                    epi_read_state.advance()
+                else:
+                    c_buffer = epi_idx % self.epi_c_stage
+                    cute.copy(tiled_copy_s2r, tSR_sC[None, None, None, c_buffer], tSR_rC)
+                    # TODO: cp.async wait once we switch to cp.async
+                    epilogue_barrier.arrive_and_wait()
+            epi_loop_tensors = self.epi_begin_loop(params, epi_tensors, epi_coord)
+            if const_expr(inline_epi_load and epi_idx + self.epi_c_stage < epi_tile_num):
+                epi_coord_C = epi_tile_layout.get_hier_coord(epi_idx + self.epi_c_stage)
+                if const_expr(use_tma_c):
+                    if is_tma_warp:
+                        epi_pipeline.producer_acquire(epi_producer_state)
+                        copy_C(src_idx=epi_coord_C, producer_state=epi_producer_state)
+                        epi_pipeline.producer_commit(epi_producer_state)
+                    epi_producer_state.advance()
+                else:
+                    epilogue_barrier.arrive_and_wait()
+                    copy_C(
+                        src_idx=epi_coord_C,
+                        dst_idx=(epi_idx + self.epi_c_stage) % self.epi_c_stage,
+                    )
+            tRS_rAuxOut = self.epi_visit_subtile(params, epi_loop_tensors, tRS_rD, tRS_rC)
+            self.epi_end_loop(
+                params,
+                epi_tensors,
+                epi_coord,
+                epi_tile,
+                tiled_copy_t2r,
+                tiled_copy_r2s,
+                tile_coord_mnkl,
+                varlen_manager,
+                tidx,
+            )
+            if const_expr(aux_out_ctx is not None):
+                tRS_rAuxOut_out = self.epi_convert_aux_out(
+                    tRS_rAuxOut,
+                    epi_loop_tensors.get("sr_seed"),
+                    tidx,
+                    tile_coord_mnkl,
+                    num_prev_subtiles,
+                    epi_idx,
+                )
+            if const_expr(use_tma_epi):
+                if is_tma_warp:
+                    epi_store_pipeline.producer_acquire()
+            else:
+                epilogue_barrier.arrive_and_wait()
+            if const_expr(use_tma_epi):
+                epilogue_barrier.arrive_and_wait()
+            epi_buffer = (num_prev_subtiles + epi_idx) % self.epi_stage
+            if const_expr(has_D):
+                tRS_sD_cur = tRS_sD[None, None, None, epi_buffer]
+                if const_expr(use_stochastic_rounding):
+                    seed = epilogue_sr_seed(
+                        epi_loop_tensors.get("sr_seed"),
+                        tile_coord_mnkl,
+                        num_prev_subtiles + epi_idx,
+                    )
+                    copy_utils.sr_cvt_copy(tiled_copy_r2s, tRS_rD, tRS_sD_cur, seed, tidx)
+                else:
+                    copy_utils.cvt_copy(tiled_copy_r2s, tRS_rD, tRS_sD_cur)
+            if const_expr(aux_out_ctx is not None):
+                if const_expr(isinstance(tRS_rAuxOut_out, tuple)):
+                    for i, aux_ctx in enumerate(aux_out_ctx):
+                        tiled_copy_aux_out_r2s, tRS_sAuxOut, _ = aux_ctx
+                        cute.copy(
+                            tiled_copy_aux_out_r2s,
+                            copy_utils.contiguous(
+                                tiled_copy_aux_out_r2s.retile(tRS_rAuxOut_out[i])
+                            ),
+                            tRS_sAuxOut[None, None, None, epi_buffer],
+                        )
+                else:
+                    tiled_copy_aux_out_r2s, tRS_sAuxOut, _ = aux_out_ctx[0]
+                    cute.copy(
+                        tiled_copy_aux_out_r2s,
+                        # Need contiguous for Sm80 and Sm120 where acc layout is ((2, 2), MMA_M, MMA_N)
+                        copy_utils.contiguous(tiled_copy_aux_out_r2s.retile(tRS_rAuxOut_out)),
+                        tRS_sAuxOut[None, None, None, epi_buffer],
+                    )
+            if const_expr(use_tma_epi):
+                cute.arch.fence_view_async_shared()
+                epilogue_barrier.arrive_and_wait()
+                if is_tma_warp:
+                    if const_expr(has_D):
+                        copy_D(src_idx=epi_buffer, dst_idx=epi_coord)
+                    if const_expr(aux_out_ctx is not None):
+                        for _, _, copy_aux_out in aux_out_ctx:
+                            copy_aux_out(src_idx=epi_buffer, dst_idx=epi_coord)
+                    epi_store_pipeline.producer_commit()
+            else:
+                epilogue_barrier.arrive_and_wait()
+                if const_expr(has_D):
+                    copy_D(src_idx=epi_buffer, dst_idx=epi_coord)
+                if const_expr(aux_out_ctx is not None):
+                    for _, _, copy_aux_out in aux_out_ctx:
+                        copy_aux_out(src_idx=epi_buffer, dst_idx=epi_coord)
+                epilogue_barrier.arrive_and_wait()
+
+        self.epi_end(
+            params,
+            epi_tensors,
+            epi_tile,
+            tiled_copy_t2r,
+            tiled_copy_r2s,
+            tile_coord_mnkl,
+            varlen_manager,
+            tidx,
+        )
+
+        return epi_read_state, epi_producer_state
+
+    def get_scheduler_class(self, varlen_m: bool = False):
+        """Return the scheduler class to use. Override in subclasses for custom schedulers."""
+        return TileScheduler if not varlen_m else VarlenMTileScheduler
+
+    def resolve_epi_m_major(self, epilogue_args: EpilogueArguments):
+        return True
+
+    def get_scheduler_arguments(
+        self,
+        mA: cute.Tensor,
+        mB: cute.Tensor,
+        mD: Optional[cute.Tensor],
+        scheduler_args,
+        varlen_args,
+        epilogue_args,
+    ):
+        """Create scheduler arguments. Override in subclasses for custom schedulers."""
+        if const_expr(not self.is_persistent):
+            persistence_mode = PersistenceMode.NONE
+        else:
+            if const_expr(self.arch >= 100 and self.use_clc_persistence):
+                persistence_mode = PersistenceMode.CLC
+            elif const_expr(scheduler_args.tile_count_semaphore is not None):
+                persistence_mode = PersistenceMode.DYNAMIC
+            else:
+                persistence_mode = PersistenceMode.STATIC
+        if const_expr(varlen_args.mCuSeqlensM is None):
+            num_problems = (
+                mD.shape[2]
+                if mD is not None
+                else (
+                    mB.shape[2]
+                    if varlen_args.mCuSeqlensK is None
+                    else varlen_args.mCuSeqlensK.shape[0] - 1
+                )
+            )
+            problem_shape_ntile_mnl = (
+                cute.ceil_div(cute.size(mA, mode=[0]), self.cta_tile_shape_mnk[0]),
+                cute.ceil_div(cute.size(mB, mode=[0]), self.cta_tile_shape_mnk[1]),
+                num_problems,
+            )
+            tile_sched_args = TileSchedulerArguments(
+                problem_shape_ntile_mnl=problem_shape_ntile_mnl,
+                raster_order=scheduler_args.raster_order,
+                group_size=scheduler_args.max_swizzle_size,
+                cluster_shape_mnk=self.cluster_shape_mnk,
+                tile_count_semaphore=scheduler_args.tile_count_semaphore,
+                batch_idx_permute=scheduler_args.batch_idx_permute,
+                persistence_mode=persistence_mode,
+            )
+        else:
+            assert (mD is not None) or (epilogue_args.mAuxOut is not None) or (not self.gather_A)
+            problem_shape_ntile_mnl = (
+                None,
+                cute.ceil_div(cute.size(mB, mode=[0]), self.cta_tile_shape_mnk[1]),
+                varlen_args.mCuSeqlensM.shape[0] - 1,
+            )
+            tile_sched_args = VarlenMTileSchedulerArguments(
+                problem_shape_ntile_mnl=problem_shape_ntile_mnl,
+                total_m=(
+                    mD.shape[0]
+                    if mD is not None
+                    else (
+                        varlen_args.mAIdx.shape[0]
+                        if varlen_args.mAIdx is not None
+                        else cute.size(mA, mode=[0])
+                    )
+                ),
+                cu_seqlens_m=varlen_args.mCuSeqlensM,
+                raster_order=scheduler_args.raster_order,
+                group_size=scheduler_args.max_swizzle_size,
+                tile_shape_mn=self.cta_tile_shape_mnk[:2],
+                cluster_shape_mnk=self.cluster_shape_mnk,
+                tile_count_semaphore=scheduler_args.tile_count_semaphore,
+                persistence_mode=persistence_mode,
+            )
+        return tile_sched_args
+
+    @cute.jit
+    def epi_load_acc_subtile(
+        self,
+        tRS_rAcc: cute.Tensor,
+        tRS_rD: cute.Tensor,
+        epi_coord,  # (int, int)
+    ):
+        cute.autovec_copy(tRS_rAcc[None, None, None, epi_coord], tRS_rD)
+
+    @cute.jit
+    def epi_begin(
+        self,
+        params: EpilogueParams,
+        epi_smem_tensors: Dict[str, cute.Tensor],
+        epi_tile: cute.Tile,
+        tiled_copy_t2r: Optional[cute.TiledCopy],
+        tiled_copy_r2s: cute.TiledCopy,
+        tile_coord_mnkl: cute.Coord,
+        varlen_manager: VarlenManager,
+        epilogue_barrier: cutlass.pipeline.NamedBarrier,
+        tidx: Int32,
+        tRS_rD_layout=None,
+    ) -> Tuple[cute.Tensor, ...]:
+        return ()
+
+    def epi_begin_loop(
+        self, params: EpilogueParams, epi_tensors: Tuple[cute.Tensor, ...], epi_coord: cute.Coord
+    ) -> Tuple[cute.Tensor, ...]:
+        return ()
+
+    def epi_visit_subtile(
+        self,
+        params: EpilogueParams,
+        epi_loop_tensors: Tuple[cute.Tensor, ...],
+        tRS_rD: cute.Tensor,
+        tRS_rC: Optional[cute.Tensor] = None,
+    ) -> Optional[cute.Tensor]:
+        return None
+
+    def epi_visit_acc(
+        self,
+        params: EpilogueParams,
+        acc: cute.Tensor,
+        tiled_mma: cute.TiledMma,
+        tile_coord_mnkl: cute.Coord,
+        tidx: Int32,
+    ) -> None:
+        pass
+
+    @cute.jit
+    def epi_end_loop(
+        self,
+        params: EpilogueParams,
+        epi_tensors: Tuple[cute.Tensor, ...],
+        epi_coord: cute.Coord,
+        epi_tile: cute.Tile,
+        tiled_copy_t2r: Optional[cute.TiledCopy],
+        tiled_copy_r2s: cute.TiledCopy,
+        tile_coord_mnkl: cute.Coord,
+        varlen_manager,
+        tidx,
+    ) -> None:
+        pass
+
+    @cute.jit
+    def epi_end(
+        self,
+        params: EpilogueParams,
+        epi_tensors: Tuple[cute.Tensor, ...],
+        epi_tile: cute.Tile,
+        tiled_copy_t2r: Optional[cute.TiledCopy],
+        tiled_copy_r2s: cute.TiledCopy,
+        tile_coord_mnkl: cute.Coord,
+        varlen_manager,
+        tidx,
+    ) -> None:
+        pass
+
+    def epi_to_underlying_arguments(
+        self, args: EpilogueArguments, *, loc=None, ip=None
+    ) -> EpilogueParams:
+        return self.EpilogueParams()
+
+    def epi_get_tma_atoms(
+        self, params: EpilogueParams, *, loc=None, ip=None
+    ) -> list[cute.CopyAtom]:
+        """Subclasses can override this."""
+        return []
+
+    def epi_tile_load_g2s_copy_fns(
+        self,
+        params,
+        epi_smem_tensors,
+        tile_coord_mnkl,
+        varlen_manager,
+        epi_pipeline,
+    ):
+        return ()
+
+    @cute.jit
+    def epi_tile_load_s2r(self, params, epi_tensors, stage_idx):
+        pass
+
+    @staticmethod
+    def epi_smem_bytes(
+        args: Optional[EpilogueArguments],
+        cta_tile_shape_mnk: Tuple[int, int, int],
+        epi_tile: cute.Tile,
+        warp_shape_mnk: Tuple[int, int, int] | None = None,
+    ) -> EpiSmemBytes:
+        return EpiSmemBytes()
+
+    def epi_get_smem_struct(self, params: EpilogueParams):
+        return cute.struct.MemRange[Int32, 0]  # Dummy struct
+
+    def epi_get_smem_tensors(self, params: EpilogueParams, storage) -> Dict[str, cute.Tensor]:
+        return {}
+
+    def epi_setup_aux_out(
+        self,
+        params,
+        epi_smem_tensors,
+        tiled_copy_r2s,
+        tiled_copy_t2r,
+        tile_coord_mnkl,
+        varlen_manager,
+        tidx,
+    ):
+        """Default epilogue has no aux output."""
+        return None
+
+    @cute.jit
+    def epi_convert_aux_out(
+        self, tRS_rAuxOut, sr_seed, tidx, tile_coord_mnkl, num_prev_subtiles, epi_idx
+    ):
+        """Convert aux output from acc_dtype to output dtype. Override for custom postprocessing."""
+        return tRS_rAuxOut
+
+
+class GemmTmaBase(GemmBase):
+    """Common TMA descriptor and pipeline helpers for SM90+ GEMM paths."""
+
+    @cute.jit
+    def load_tma(
+        self,
+        pipeline: cutlass.pipeline.PipelineAsync,
+        producer_state: cutlass.pipeline.PipelineState,
+        copy_fns: Sequence[Optional[Callable]],
+        k_tile_cnt: Int32,
+    ) -> cutlass.pipeline.PipelineState:
+        # Peek (try_wait) AB buffer empty for k_block = prefetch_k_tile_cnt.
+        peek_empty_status = Boolean(True)
+        if 0 < k_tile_cnt:
+            peek_empty_status = pipeline.producer_try_acquire(producer_state)
+        # TMA load
+        for k_tile in cutlass.range(k_tile_cnt, unroll=1):
+            # Wait for A/B buffers to be empty before loading into them.
+            # Also sets the transaction barrier for the A/B buffers.
+            pipeline.producer_acquire(producer_state, peek_empty_status)
+            tma_bar_ptr = pipeline.producer_get_barrier(producer_state)
+            smem_idx = producer_state.index
+            for copy_fn in copy_fns:
+                if const_expr(copy_fn is not None):
+                    copy_fn(k_tile, smem_idx, tma_bar_ptr=tma_bar_ptr)
+            # Mainloop pipeline's producer commit is a NOP for TMA pipelines.
+            pipeline.producer_commit(producer_state)
+            producer_state.advance()
+            peek_empty_status = Boolean(True)
+            if k_tile + 1 < k_tile_cnt:
+                peek_empty_status = pipeline.producer_try_acquire(producer_state)
+        return producer_state
+
+    def _make_gmem_tiled_copy_A(self, dtype, major_mode, num_threads, copy_bits=128):
+        atom_async_copy = cute.make_copy_atom(
+            cpasync.CopyG2SOp(cache_mode=cpasync.LoadCacheMode.GLOBAL),
+            dtype,
+            num_bits_per_copy=copy_bits,
+        )
+        copy_elems = copy_bits // dtype.width
+        loads_per_cache_line = 128 * 8 // copy_bits  # 128 bytes per cache line
+        shape_dim_1 = cute.size(self.cta_tile_shape_mnk[2]) // copy_elems
+        if shape_dim_1 > loads_per_cache_line:
+            shape_dim_1 = math.gcd(shape_dim_1, loads_per_cache_line)
+        # thread layout for copy
+        thread_layout = cute.make_layout(
+            (num_threads // shape_dim_1, shape_dim_1), stride=(shape_dim_1, 1)
+        )
+        if major_mode != LayoutEnum.ROW_MAJOR:
+            shape_dim_0 = cute.size(self.cta_tile_shape_mnk[0]) // copy_elems
+            if shape_dim_0 > loads_per_cache_line:
+                shape_dim_0 = math.gcd(shape_dim_0, loads_per_cache_line)
+            thread_layout = cute.make_layout(
+                (shape_dim_0, num_threads // shape_dim_0), stride=(1, shape_dim_0)
+            )
+        # Value layout for copy
+        value_layout = (
+            cute.make_layout((1, copy_elems))
+            if major_mode == LayoutEnum.ROW_MAJOR
+            else cute.make_layout((copy_elems, 1))
+        )
+        return cute.make_tiled_copy_tv(atom_async_copy, thread_layout, value_layout)
+
+    def make_tma_load_atoms_and_tensors(
+        self,
+        mA: cute.Tensor,
+        mB: cute.Tensor,
+        a_smem_layout: cute.ComposedLayout,
+        b_smem_layout: cute.ComposedLayout,
+        varlen_k: bool,
+    ):
+        tma_atom_a, tma_tensor_a = None, None
+        if const_expr(not self.gather_A):
+            tma_atom_a, tma_tensor_a = self._make_tma_atoms_and_tensors(
+                copy_utils.create_ragged_tensor_for_tma(mA, ragged_dim=1)
+                if varlen_k and not self.gather_A
+                else mA,
+                a_smem_layout,
+                (self.cta_tile_shape_mnk[0], self.cta_tile_shape_mnk[2]),
+                self.cluster_shape_mnk[1],
+            )
+        tma_atom_b, tma_tensor_b = self._make_tma_atoms_and_tensors(
+            copy_utils.create_ragged_tensor_for_tma(mB, ragged_dim=1) if varlen_k else mB,
+            b_smem_layout,
+            (self.cta_tile_shape_mnk[1], self.cta_tile_shape_mnk[2]),
+            self.cluster_shape_mnk[0],
+        )
+        return tma_atom_a, tma_tensor_a, tma_atom_b, tma_tensor_b
+
+    def make_tma_epilogue_atoms_and_tensors(
+        self,
+        mD: Optional[cute.Tensor],
+        mC: Optional[cute.Tensor],
+        epilogue_args,
+        varlen_m: bool,
+    ):
+        tma_atom_d, tma_tensor_d = None, None
+        if const_expr(mD is not None):
+            tma_atom_d, tma_tensor_d = self._make_tma_epi_atoms_and_tensors(
+                copy_utils.create_ragged_tensor_for_tma(mD, ragged_dim=0, ptr_shift=True)
+                if varlen_m
+                else mD,
+                self.epi_smem_layout_staged,
+                self.epi_tile,
+                op_type="store"
+                if not (hasattr(epilogue_args, "add_to_output") and epilogue_args.add_to_output)
+                else "add",
+            )
+        tma_atom_c, tma_tensor_c = None, None
+        if const_expr(mC is not None):
+            tma_atom_c, tma_tensor_c = self._make_tma_epi_atoms_and_tensors(
+                mC, self.epi_c_smem_layout_staged, self.epi_tile, op_type="load"
+            )
+        return tma_atom_d, tma_tensor_d, tma_atom_c, tma_tensor_c
+
+    def epilog_gmem_copy_and_partition(
+        self,
+        atom: cute.CopyAtom | cute.TiledCopy,
+        mD_mn: cute.Tensor,
+        tile_shape_mn: cute.Tile,
+        epi_tile: cute.Tile,
+        sD: cute.Tensor,
+        tile_coord_mnkl: cute.Coord,
+    ) -> Tuple[cute.Tensor, cute.Tensor]:
+        gD = cute.local_tile(mD_mn, tile_shape_mn, tile_coord_mnkl[:2])  # (bM, bN)
+        tDgD_for_tma_partition = cute.zipped_divide(gD, epi_tile)
+        is_s2g = isinstance(
+            atom.op, (cpasync.CopyBulkTensorTileS2GOp, cpasync.CopyReduceBulkTensorTileS2GOp)
+        )
+        src_tensor, dst_tensor = (
+            (sD, tDgD_for_tma_partition) if is_s2g else (tDgD_for_tma_partition, sD)
+        )
+        return copy_utils.tma_get_copy_fn(
+            atom,
+            cta_coord=0,
+            cta_layout=cute.make_layout(1),
+            src_tensor=src_tensor,
+            dst_tensor=dst_tensor,
+        )
+
+    def make_ab_pipeline(
+        self,
+        tiled_mma: cute.TiledMma,
+        cluster_layout_vmnk: cute.Layout,
+        ab_pipeline_mbar_ptr: cute.Pointer,
+    ):
+        # Threads/warps participating in this pipeline
+        producer_cnt = 1 if const_expr(not self.gather_A) else 1 + self.num_ab_load_warps * 32
+        ab_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, producer_cnt)
+        # Each warp will contribute to the arrive count with the number of mcast size
+        mcast_size = self.num_mcast_ctas_a + self.num_mcast_ctas_b - 1
+        consumer_arrive_cnt = mcast_size * tiled_mma.size // cute.arch.WARP_SIZE
+        ab_pipeline_consumer_group = pipeline.CooperativeGroup(
+            pipeline.Agent.Thread, consumer_arrive_cnt
+        )
+        pipeline_cls = pipeline.PipelineTmaAsync if not self.gather_A else PipelineTmaCpAsync
+        return pipeline_cls.create(
+            barrier_storage=ab_pipeline_mbar_ptr,
+            num_stages=self.ab_stage,
+            producer_group=ab_pipeline_producer_group,
+            consumer_group=ab_pipeline_consumer_group,
+            tx_count=self.num_tma_load_bytes,
+            cta_layout_vmnk=cluster_layout_vmnk,
+            defer_sync=True,
+        )
+
+    def make_epi_pipeline(
+        self,
+        epi_pipeline_mbar_ptr: cute.Pointer,
+        tx_count: int,
+    ):
+        epi_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread)
+        # Each warp will contribute 1 to the arrive count
+        consumer_arrive_cnt = self.num_epi_warps
+        epi_pipeline_consumer_group = pipeline.CooperativeGroup(
+            pipeline.Agent.Thread, consumer_arrive_cnt
+        )
+        return pipeline.PipelineTmaAsync.create(
+            barrier_storage=epi_pipeline_mbar_ptr,
+            num_stages=self.epi_c_stage,
+            producer_group=epi_pipeline_producer_group,
+            consumer_group=epi_pipeline_consumer_group,
+            tx_count=tx_count,
+            defer_sync=True,
+        )
+
+    def make_epi_store_pipeline(self):
+        num_epi_threads = self.num_epi_warps * cute.arch.WARP_SIZE
+        epi_store_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, num_epi_threads)
+        return pipeline.PipelineTmaStore.create(
+            num_stages=self.epi_stage, producer_group=epi_store_producer_group
+        )
+
+    @staticmethod
+    def _make_tma_epi_atoms_and_tensors(
+        tensor_d: cute.Tensor,
+        epi_smem_layout_staged: cute.ComposedLayout,
+        epi_tile: Tuple[int, int],
+        op_type: Literal["store", "load", "add"],
+    ) -> Tuple[cute.CopyAtom, cute.Tensor]:
+        """Create TMA atoms and tensors for storing D or loading C."""
+        assert op_type in ["load", "store", "add"]
+        epi_smem_layout = cute.slice_(epi_smem_layout_staged, (None, None, 0))
+        d_cta_v_layout = cute.composition(cute.make_identity_layout(tensor_d.shape), epi_tile)
+        op = {
+            "load": cpasync.CopyBulkTensorTileG2SOp(),
+            "store": cpasync.CopyBulkTensorTileS2GOp(),
+            "add": cpasync.CopyReduceBulkTensorTileS2GOp(cpasync.ReductionOp.ADD),
+        }[op_type]
+        tma_atom_d, tma_tensor_d = cpasync.make_tiled_tma_atom(
+            op, tensor_d, epi_smem_layout, d_cta_v_layout
+        )
+        return tma_atom_d, tma_tensor_d
+
+    @staticmethod
+    def _make_tma_atoms_and_tensors(
+        tensor: cute.Tensor,
+        smem_layout: cute.ComposedLayout,
+        smem_tile: Tuple[int, int],
+        mcast_dim: int,
+    ) -> Tuple[cute.CopyAtom, cute.Tensor]:
+        """Create TMA atoms and tensors for input tensors."""
+        op = (
+            cpasync.CopyBulkTensorTileG2SOp()
+            if mcast_dim == 1
+            else cpasync.CopyBulkTensorTileG2SMulticastOp()
+        )
+        tma_atom, tma_tensor = cpasync.make_tiled_tma_atom(
+            op,
+            tensor,
+            smem_layout,
+            smem_tile,
+            num_multicast=mcast_dim,
+        )
+        return tma_atom, tma_tensor
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_blockscaled_interface.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_blockscaled_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bc39749e5dee049cc137e6329a93223ac8b3c81
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_blockscaled_interface.py
@@ -0,0 +1,326 @@
+# Copyright (c) 2026, Tri Dao.
+"""PyTorch-friendly interface for the SM100 MXFP8 blockscaled GEMM.
+
+Shape / layout conventions (matches torch.matmul, torch._scaled_mm, cuBLAS):
+  A:       (M, K)     or (L, M, K)       dtype float8_e4m3fn, K-contiguous (row-major)
+  B:       (K, N)     or (L, K, N)       dtype float8_e4m3fn, K-contiguous (col-major)
+  A_scale: (M, K/32)  or (L, M, K/32)    dtype float8_e8m0fnu, K-contiguous
+  B_scale: (K/32, N)  or (L, K/32, N)    dtype float8_e8m0fnu, K-contiguous
+  out:     (M, N)     or (L, M, N)       dtype bfloat16/float16, contiguous
+
+"K-contiguous" means stride 1 on the K axis. This matches how torchao/cuBLAS
+use `torch._scaled_mm(a, b.t(), ...)`:
+  - you store a weight as nn.Linear-style `W` of shape `(N, K)` row-major
+  - you pass `W.mT` (a zero-copy view of shape (K, N) with K-contig) as B
+The interface applies `.mT` internally to reach the `(N, K) K-major` layout
+the quack kernel consumes. No data is copied.
+"""
+
+from functools import lru_cache
+from typing import Optional, Tuple
+
+import torch
+from torch import Tensor
+
+import cutlass
+
+from .blockscaled_gemm_utils import (
+    ceil_div,
+    compile_blockscaled_gemm_tvm_ffi,
+    pack_scale_2d_to_blocked_contig,
+    scale_blocked_for_cublas,
+    scale_view_for_kernel,
+)
+from .gemm_default_epi import GemmDefaultSm100
+from .mx_utils import to_mx
+
+_SF_VEC_SIZE = 32
+_TORCH_TO_CUTLASS_D = {
+    torch.bfloat16: cutlass.BFloat16,
+    torch.float16: cutlass.Float16,
+    torch.float32: cutlass.Float32,
+}
+
+
+def _default_tiler_cluster(m: int, n: int) -> Tuple[Tuple[int, int], Tuple[int, int]]:
+    """Pick a reasonable default (mma_tiler_mn, cluster_shape_mn)."""
+    if m >= 512 and n >= 128:
+        return (256, 128), (2, 1)
+    return (128, 128), (1, 1)
+
+
+@lru_cache(maxsize=64)
+def _compile_cached(
+    m: int,
+    n: int,
+    k: int,
+    l: int,
+    mma_tiler_mn: Tuple[int, int],
+    cluster_shape_mn: Tuple[int, int],
+    out_torch_dtype,
+    ab_dtype_cutlass,
+    sf_dtype_cutlass,
+):
+    """Compile kernel for a given (shape, dtype, tiler, cluster) and cache it."""
+    dev = torch.device("cuda")
+    rm = ceil_div(m, 128)
+    rn = ceil_div(n, 128)
+    rk = ceil_div(k // _SF_VEC_SIZE, 4)
+    # K-major: (l, m, k) contiguous, viewed as (m, k, l) strides (k, 1, m*k)
+    fake_mA = torch.empty(l, m, k, dtype=torch.float8_e4m3fn, device=dev).permute(1, 2, 0)
+    fake_mB = torch.empty(l, n, k, dtype=torch.float8_e4m3fn, device=dev).permute(1, 2, 0)
+    # N-major: (l, m, n) contiguous, viewed as (m, n, l) strides (n, 1, m*n)
+    fake_mD = torch.empty(l, m, n, dtype=out_torch_dtype, device=dev).permute(1, 2, 0)
+    fake_sc_A = torch.empty(l, rm, rk, 512, dtype=torch.float8_e8m0fnu, device=dev)
+    fake_sc_B = torch.empty(l, rn, rk, 512, dtype=torch.float8_e8m0fnu, device=dev)
+    fake_mSFA = scale_view_for_kernel(fake_sc_A, m, k // _SF_VEC_SIZE, l)
+    fake_mSFB = scale_view_for_kernel(fake_sc_B, n, k // _SF_VEC_SIZE, l)
+    return compile_blockscaled_gemm_tvm_ffi(
+        ab_dtype_cutlass,
+        sf_dtype_cutlass,
+        _SF_VEC_SIZE,
+        _TORCH_TO_CUTLASS_D[out_torch_dtype],
+        mma_tiler_mn,
+        cluster_shape_mn,
+        fake_mA,
+        fake_mB,
+        fake_mD,
+        fake_mSFA,
+        fake_mSFB,
+    )
+
+
+def _as_3d(x: Tensor, ndim_in: int) -> Tensor:
+    """Add a leading batch dim if input is 2D. Returns a view."""
+    if ndim_in == 2:
+        return x.unsqueeze(0)
+    return x
+
+
+def _to_kernel_layout(
+    A: Tensor,
+    B: Tensor,
+    A_scale: Tensor,
+    B_scale: Tensor,
+) -> Tuple[int, int, int, int, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, bool]:
+    """Normalize shapes/strides, validate, and repack scales. Returns
+    (m, n, k, l, mA_mkl, mB_nkl, sc_contig_A, sc_contig_B, sfa_view, sfb_view, was_2d).
+
+    A: (M,K) or (L,M,K) K-contig.  B: (K,N) or (L,K,N) K-contig.
+    A_scale: (M,K/32) or (L,M,K/32) K-contig.  B_scale: (K/32,N) or (L,K/32,N) K-contig.
+    """
+    assert A.dtype == torch.float8_e4m3fn, f"A dtype must be float8_e4m3fn, got {A.dtype}"
+    assert B.dtype == torch.float8_e4m3fn, f"B dtype must be float8_e4m3fn, got {B.dtype}"
+    assert A_scale.dtype == torch.float8_e8m0fnu
+    assert B_scale.dtype == torch.float8_e8m0fnu
+    was_2d = A.dim() == 2
+    # Flip B from (K,N) to (N,K) via .mT (zero-copy). User's B K-contig → .mT K-contig.
+    A3 = _as_3d(A, A.dim())  # (l, m, k) K-contig row-major expected
+    B3 = _as_3d(B, B.dim()).mT  # (l, n, k) K-contig (view) from (l, k, n)
+    l, m, k = A3.shape
+    l2, n, k2 = B3.shape
+    assert l == l2, f"batch mismatch: A={l}, B={l2}"
+    assert k == k2, f"K mismatch: A K={k}, B K={k2}"
+    assert k % _SF_VEC_SIZE == 0, f"K ({k}) must be divisible by {_SF_VEC_SIZE}"
+    assert A3.stride(-1) == 1, "A must be K-contiguous (stride 1 on K)"
+    assert B3.stride(-1) == 1, (
+        "B must be K-contiguous on its K axis (pass .mT of an (N,K) row-major tensor)"
+    )
+    sf_k = k // _SF_VEC_SIZE
+    as3 = _as_3d(A_scale, A_scale.dim())  # expected (l, m, sf_k) K-contig row-major
+    bs3 = _as_3d(B_scale, B_scale.dim()).mT  # (l, n, sf_k) K-contig (view) from (l, sf_k, n)
+    assert as3.stride(-1) == 1, "A_scale must be K-contiguous"
+    assert bs3.stride(-1) == 1, (
+        "B_scale must be K-contiguous on its K axis (pass .mT of an (N, K/32) row-major tensor)"
+    )
+    assert as3.shape == (l, m, sf_k), (
+        f"A_scale shape: expected (l={l},m={m},sf_k={sf_k}) K-contig, got {tuple(as3.shape)}"
+    )
+    assert bs3.shape == (l, n, sf_k), (
+        f"B_scale shape: expected .mT of (l={l},sf_k={sf_k},n={n}) -> ({l},{n},{sf_k}), got {tuple(bs3.shape)}"
+    )
+    # Force row-major contiguous for packer/kernel consumption.
+    # A3 / B3 are views — .contiguous() materializes (l,m,k) / (l,n,k) row-major.
+    A3_c = A3.contiguous()
+    B3_c = B3.contiguous()
+    # (l, m, k) -> (m, k, l) K-major view (no copy; strides (k, 1, m*k))
+    mA_mkl = A3_c.permute(1, 2, 0)
+    mB_nkl = B3_c.permute(1, 2, 0)
+    sc_contig_A = pack_scale_2d_to_blocked_contig(as3.contiguous())
+    sc_contig_B = pack_scale_2d_to_blocked_contig(bs3.contiguous())
+    sfa_view = scale_view_for_kernel(sc_contig_A, m, sf_k, l)
+    sfb_view = scale_view_for_kernel(sc_contig_B, n, sf_k, l)
+    return m, n, k, l, mA_mkl, mB_nkl, sc_contig_A, sc_contig_B, sfa_view, sfb_view, was_2d
+
+
+def mxfp8_gemm_out(
+    A: Tensor,
+    B: Tensor,
+    A_scale: Tensor,
+    B_scale: Tensor,
+    out: Tensor,
+    *,
+    mma_tiler_mn: Optional[Tuple[int, int]] = None,
+    cluster_shape_mn: Optional[Tuple[int, int]] = None,
+) -> None:
+    """MXFP8 blockscaled GEMM with pre-allocated output. See module doc for shape conventions."""
+    m, n, k, l, mA, mB, _scA, _scB, sfa, sfb, was_2d = _to_kernel_layout(A, B, A_scale, B_scale)
+    out_dtype = out.dtype
+    assert out_dtype in _TORCH_TO_CUTLASS_D, f"unsupported out dtype: {out_dtype}"
+    expected_out_shape = (m, n) if was_2d else (l, m, n)
+    assert tuple(out.shape) == expected_out_shape, (
+        f"out shape {tuple(out.shape)} != expected {expected_out_shape}"
+    )
+    assert out.is_contiguous(), "out must be contiguous"
+    # View caller's contiguous (M,N) or (L,M,N) as (M,N,L) N-major strided view, no copy.
+    out_3d = out.unsqueeze(0) if was_2d else out  # (l, m, n)
+    mD = out_3d.permute(1, 2, 0)  # (m, n, l), strides (n, 1, m*n)
+    if mma_tiler_mn is None or cluster_shape_mn is None:
+        tlr, clu = _default_tiler_cluster(m, n)
+        mma_tiler_mn = mma_tiler_mn or tlr
+        cluster_shape_mn = cluster_shape_mn or clu
+    if not GemmDefaultSm100.can_implement_blockscaled(
+        cutlass.Float8E4M3FN,
+        cutlass.Float8E8M0FNU,
+        _SF_VEC_SIZE,
+        _TORCH_TO_CUTLASS_D[out_dtype],
+        mma_tiler_mn,
+        cluster_shape_mn,
+        m,
+        n,
+        k,
+        l,
+        "k",
+        "k",
+        "n",
+    ):
+        raise ValueError(
+            f"unsupported config: m={m}, n={n}, k={k}, l={l}, "
+            f"tiler={mma_tiler_mn}, cluster={cluster_shape_mn}"
+        )
+    runner = _compile_cached(
+        m,
+        n,
+        k,
+        l,
+        mma_tiler_mn,
+        cluster_shape_mn,
+        out_dtype,
+        cutlass.Float8E4M3FN,
+        cutlass.Float8E8M0FNU,
+    )
+    runner(mA, mB, mD, sfa, sfb)
+
+
+def mxfp8_gemm(
+    A: Tensor,
+    B: Tensor,
+    A_scale: Tensor,
+    B_scale: Tensor,
+    out: Optional[Tensor] = None,
+    out_dtype: torch.dtype = torch.bfloat16,
+    *,
+    mma_tiler_mn: Optional[Tuple[int, int]] = None,
+    cluster_shape_mn: Optional[Tuple[int, int]] = None,
+) -> Tensor:
+    """MXFP8 blockscaled GEMM. Allocates output if not provided."""
+    if out is None:
+        # A: (M,K) or (L,M,K); B: (K,N) or (L,K,N); out: (M,N) or (L,M,N)
+        if A.dim() == 2:
+            out_shape = (A.shape[0], B.shape[1])
+        else:
+            out_shape = (A.shape[0], A.shape[1], B.shape[2])
+        out = torch.empty(out_shape, dtype=out_dtype, device=A.device)
+    mxfp8_gemm_out(
+        A,
+        B,
+        A_scale,
+        B_scale,
+        out,
+        mma_tiler_mn=mma_tiler_mn,
+        cluster_shape_mn=cluster_shape_mn,
+    )
+    return out
+
+
+def mxfp8_quantize(x: Tensor) -> Tuple[Tensor, Tensor]:
+    """Quantize a (..., K) bf16/fp32 tensor to MXFP8. Returns (qdata, scale_2d)
+    in torchao-convention layout. Last dim (K) must be divisible by 32."""
+    assert x.shape[-1] % _SF_VEC_SIZE == 0, (
+        f"last dim ({x.shape[-1]}) must be divisible by {_SF_VEC_SIZE}"
+    )
+    return to_mx(x.contiguous(), _SF_VEC_SIZE)
+
+
+def mxfp8_gemm_quantize(
+    A: Tensor,
+    B: Tensor,
+    out: Optional[Tensor] = None,
+    out_dtype: torch.dtype = torch.bfloat16,
+    *,
+    mma_tiler_mn: Optional[Tuple[int, int]] = None,
+    cluster_shape_mn: Optional[Tuple[int, int]] = None,
+) -> Tensor:
+    """High-level: quantize bf16 A, B_as_NK to MXFP8, then run C = A @ B_as_NK.mT.
+    Inputs: A=(M,K)/(L,M,K), B_as_NK=(N,K)/(L,N,K) bf16/fp32. Quantization
+    scales along the last (K) dim. Returned output has shape (M,N)/(L,M,N)."""
+    A_q, A_sc = mxfp8_quantize(A)
+    B_q, B_sc = mxfp8_quantize(B)
+    # B_q, B_sc are (..., N, K) / (..., N, K/32). Flip to (..., K, N) / (..., K/32, N)
+    # K-contig zero-copy views to match the interface convention.
+    return mxfp8_gemm(
+        A_q,
+        B_q.mT,
+        A_sc,
+        B_sc.mT,
+        out=out,
+        out_dtype=out_dtype,
+        mma_tiler_mn=mma_tiler_mn,
+        cluster_shape_mn=cluster_shape_mn,
+    )
+
+
+def mxfp8_gemm_cublas(
+    A: Tensor,
+    B: Tensor,
+    A_scale: Tensor,
+    B_scale: Tensor,
+    out_dtype: torch.dtype = torch.bfloat16,
+) -> Tensor:
+    """Reference path via torch._scaled_mm. Requires l=1 (or 2D inputs)."""
+    m, n, k, l, _mA, _mB, sc_A, sc_B, _sfa, _sfb, was_2d = _to_kernel_layout(A, B, A_scale, B_scale)
+    assert l == 1, "torch._scaled_mm MXFP8 path is 2D only; pass 2D inputs or l=1"
+    # torch._scaled_mm: A=(M,K) row-major, B=(K,N) col-major (both K-contig) -- same layout user gave us.
+    a2d = A if A.dim() == 2 else A.squeeze(0)
+    b2d = B if B.dim() == 2 else B.squeeze(0)
+    sca = scale_blocked_for_cublas(sc_A, m, k // _SF_VEC_SIZE, 0)
+    scb = scale_blocked_for_cublas(sc_B, n, k // _SF_VEC_SIZE, 0)
+    out = torch._scaled_mm(
+        a2d,
+        b2d,
+        scale_a=sca,
+        scale_b=scb,
+        out_dtype=out_dtype,
+    )
+    return out if was_2d else out.unsqueeze(0)
+
+
+def mxfp8_gemm_ref(
+    A: Tensor,
+    B: Tensor,
+    A_scale: Tensor,
+    B_scale: Tensor,
+    out_dtype: torch.dtype = torch.bfloat16,
+) -> Tensor:
+    """Dequantize + plain matmul reference. A=(M,K), B=(K,N)."""
+    was_2d = A.dim() == 2
+    # (l, m, k)
+    A3 = _as_3d(A, A.dim()).float()
+    # B is (K, N)/(L, K, N); flip to (l, n, k) for dequant by last-dim
+    B3 = _as_3d(B, B.dim()).mT.contiguous().float()
+    as3 = _as_3d(A_scale, A_scale.dim()).float()
+    bs3 = _as_3d(B_scale, B_scale.dim()).mT.contiguous().float()
+    a_dq = A3 * as3.repeat_interleave(_SF_VEC_SIZE, dim=-1)
+    b_dq = B3 * bs3.repeat_interleave(_SF_VEC_SIZE, dim=-1)
+    out3 = torch.einsum("lmk,lnk->lmn", a_dq, b_dq).to(out_dtype)
+    return out3.squeeze(0) if was_2d else out3
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_config.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..6718d1eabbe76f07408e67b8ebaa201ced4f92dd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_config.py
@@ -0,0 +1,191 @@
+# Copyright (C) 2025, Tri Dao.
+import itertools
+from typing import Optional, List
+from functools import partial
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class GemmConfig:
+    tile_m: int = 128
+    tile_n: int = 192
+    tile_k: int | None = None
+    num_warps: int | None = None
+    pingpong: bool = True
+    # by default, we use dynamic persistent tile scheduler on SM100 but not on SM90
+    is_dynamic_persistent: bool = True
+    cluster_m: int = 2
+    cluster_n: int = 1
+    cluster_k: int = 1
+    swap_ab: bool = False
+    # raster_order: int = 1
+    max_swizzle_size: int = 8
+    device_capacity: int = 9
+    # whether to use TMA gather (vs normal cp.async) for gather_A on SM100
+    use_tma_gather: bool = False
+
+
+def _get_sm90_configs(
+    epilogue: Optional[str] = None,
+    tune_coop: bool = True,
+) -> List[GemmConfig]:
+    tile_n_vals = [128, 160, 192, 208]
+    tile_mn_vals_coop = [(256, tile_n) for tile_n in tile_n_vals] + [
+        (128, 224),
+        (128, 256),
+        # (192, 256),  # Getting IOT instruction (core dumped) in the bwd
+    ]
+    tile_mn_vals_pingpong = [(128, tile_n) for tile_n in tile_n_vals] + [(192, 128)]
+    if epilogue in ["gated"]:
+        tile_mn_vals_coop = [(m, n) for m, n in tile_mn_vals_coop if n % 32 == 0 and m != 192]
+        tile_mn_vals_pingpong = [(m, n) for m, n in tile_mn_vals_pingpong if n % 32 == 0]
+    elif epilogue in ["lse"]:
+        tile_mn_vals_coop = [(m, n) for m, n in tile_mn_vals_coop if m != 192]
+    tile_mn_vals = []
+    if tune_coop:
+        tile_mn_vals += [(m, n, False) for m, n in tile_mn_vals_coop]
+    tile_mn_vals += [(m, n, True) for m, n in tile_mn_vals_pingpong]
+    cluster = [(1, 2), (2, 1)]
+    # cluster = [(1, 1), (1, 2), (2, 1)]
+    if epilogue in ["lse"]:
+        cluster = [(1, 2), (2, 1)]
+    swap_ab_vals = [False, True]
+    if epilogue in ["lse", "gated"]:
+        swap_ab_vals = [False]
+
+    return [
+        GemmConfig(
+            tile_m=tile_m,
+            tile_n=tile_n,
+            pingpong=pingpong,
+            cluster_m=cluster_m,
+            cluster_n=cluster_n,
+            swap_ab=swap_ab,
+            device_capacity=9,
+            is_dynamic_persistent=False,  # default to not use dynamic persistent on SM90
+            use_tma_gather=False,  # TMA gather not supported on SM90
+        )
+        for (tile_m, tile_n, pingpong), (cluster_m, cluster_n), swap_ab in itertools.product(
+            tile_mn_vals,
+            cluster,
+            swap_ab_vals,
+        )
+    ]
+
+
+def _get_sm80_configs() -> List[GemmConfig]:
+    tile_mn_warps_vals = [
+        (128, 128, 4),
+        (128, 128, 8),
+        (128, 160, 4),
+        # TODO: Make 128x160 work with 8 warps. It currently makes the accumulator
+        # N layout odd and fails epilogue retile.
+        (128, 192, 4),
+        (128, 192, 8),
+        (128, 256, 8),
+        (128, 64, 4),
+        (64, 128, 4),
+    ]
+    return [
+        GemmConfig(
+            tile_m=tile_m,
+            tile_n=tile_n,
+            tile_k=tile_k,
+            num_warps=num_warps,
+            pingpong=False,
+            cluster_m=1,
+            cluster_n=1,
+            swap_ab=swap_ab,
+            device_capacity=8,
+            is_dynamic_persistent=False,
+            use_tma_gather=False,
+        )
+        for (tile_m, tile_n, num_warps), tile_k, swap_ab in itertools.product(
+            tile_mn_warps_vals, [32, 64], [False, True]
+        )
+    ]
+
+
+def _get_sm100_configs(
+    epilogue: Optional[str] = None,
+) -> List[GemmConfig]:
+    tile_n_vals = [64, 128, 160, 192, 224, 256]
+    tile_mn_cluster_vals = (
+        [(128, tile_n, (1, 1)) for tile_n in tile_n_vals]
+        + [(128, tile_n, (1, 2)) for tile_n in tile_n_vals]
+        + [(128, tile_n, (2, 1)) for tile_n in tile_n_vals]
+        + [(128, tile_n, (2, 2)) for tile_n in tile_n_vals]
+        + [(256, tile_n, (2, 1)) for tile_n in tile_n_vals]
+        + [(256, tile_n, (2, 2)) for tile_n in tile_n_vals]
+        + [(256, 512, (2, 1))]
+    )
+    swap_ab_vals = [False, True]
+    if epilogue in ["lse", "gated"]:
+        swap_ab_vals = [False]
+    GemmConfigCls = partial(
+        GemmConfig, pingpong=False, device_capacity=10
+    )  # There's no pingpong on Sm100
+    use_clc_vals = [True, False]
+    use_tma_gather_vals = [True, False]
+    return [
+        GemmConfigCls(
+            tile_m=m,
+            tile_n=n,
+            cluster_m=cm,
+            cluster_n=cn,
+            swap_ab=sab,
+            max_swizzle_size=8,
+            is_dynamic_persistent=use_clc,
+            use_tma_gather=use_tma_gather,
+        )
+        for (m, n, (cm, cn)), sab, use_clc, use_tma_gather in itertools.product(
+            tile_mn_cluster_vals, swap_ab_vals, use_clc_vals, use_tma_gather_vals
+        )
+    ]
+
+
+def _get_sm120_configs(
+    epilogue: Optional[str] = None,
+    tune_coop: bool = True,
+) -> List[GemmConfig]:
+    tile_mn_vals_coop = [(128, 128), (128, 64), (64, 128), (128, 160), (128, 192)]
+    tile_mn_vals_pingpong = [(128, 128), (128, 64), (64, 128), (128, 160)]
+    tile_mn_vals = []
+    if tune_coop:
+        tile_mn_vals += [(m, n, False) for m, n in tile_mn_vals_coop]
+    tile_mn_vals += [(m, n, True) for m, n in tile_mn_vals_pingpong]
+    swap_ab_vals = [False, True]
+    if epilogue in ["lse", "gated"]:
+        swap_ab_vals = [False]
+    return [
+        GemmConfig(
+            tile_m=tile_m,
+            tile_n=tile_n,
+            pingpong=pingpong,
+            cluster_m=1,
+            cluster_n=1,
+            swap_ab=swap_ab,
+            device_capacity=12,
+            is_dynamic_persistent=True,
+            use_tma_gather=False,  # TMA gather not supported on SM120
+        )
+        for (tile_m, tile_n, pingpong), swap_ab in itertools.product(tile_mn_vals, swap_ab_vals)
+    ]
+
+
+def get_all_configs(
+    epilogue: Optional[str] = None,
+    tune_coop: bool = True,
+) -> List[GemmConfig]:
+    """Return autotuning configs for all supported device capabilities.
+
+    Each GemmConfig is tagged with its target device_capacity, so the caller can
+    filter at runtime based on the actual device. This avoids querying the device
+    (and initializing a CUDA context) at import time.
+    """
+    return (
+        _get_sm80_configs()
+        + _get_sm90_configs(epilogue, tune_coop)
+        + _get_sm100_configs(epilogue)
+        + _get_sm120_configs(epilogue, tune_coop)
+    )
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_default_epi.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_default_epi.py
new file mode 100644
index 0000000000000000000000000000000000000000..f705dc725ed89f6a73f9e66d8498674cf5422665
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_default_epi.py
@@ -0,0 +1,98 @@
+# Copyright (c) 2025, Wentao Guo, Tri Dao.
+from typing import NamedTuple, Optional
+
+import cutlass
+import cutlass.cute as cute
+from cutlass import Int32, Float32, const_expr
+
+from .cute_dsl_utils import mlir_namedtuple
+from .epi_composable import ComposableEpiMixin
+from .epi_ops import Scalar, RowVecLoad, ColVecLoad
+from .gemm_sm80 import GemmSm80
+from .gemm_sm90 import GemmSm90
+from .gemm_sm100 import GemmSm100
+from .gemm_sm120 import GemmSm120
+from .rounding import RoundingMode
+from . import layout_utils
+from . import utils
+
+
+class GemmDefaultEpiMixin(ComposableEpiMixin):
+    _epi_ops = (
+        Scalar("alpha"),
+        Scalar("beta"),
+        Scalar("sr_seed", dtype=Int32),
+        RowVecLoad("mRowVecBroadcast"),
+        ColVecLoad("mColVecBroadcast"),
+    )
+
+    @mlir_namedtuple
+    class EpilogueArguments(NamedTuple):
+        alpha: Optional[Float32 | cute.Tensor] = None
+        beta: Optional[Float32 | cute.Tensor] = None
+        mRowVecBroadcast: Optional[cute.Tensor] = None
+        mColVecBroadcast: Optional[cute.Tensor] = None
+        add_to_output: cutlass.Constexpr[bool] = False
+        rounding_mode: cutlass.Constexpr[int] = RoundingMode.RN
+        sr_seed: Optional[Int32 | cute.Tensor] = None
+
+    # EpilogueParams auto-generated from _epi_ops
+
+    def epi_to_underlying_arguments(self, args, *, loc=None, ip=None):
+        self.rounding_mode = args.rounding_mode
+        d = self._epi_ops_to_params_dict(args)
+        for key in ("mRowVecBroadcast", "mColVecBroadcast"):
+            if key in self.concat_layout and key in d:
+                d[key] = layout_utils.concat_to_interleave(d[key], 1)
+        return self.EpilogueParams(**d)
+
+    @cute.jit
+    def epi_visit_subtile(
+        self,
+        params,
+        epi_loop_tensors,
+        tRS_rD: cute.Tensor,
+        tRS_rC: Optional[cute.Tensor] = None,
+    ) -> Optional[cute.Tensor]:
+        # Use .get(): inactive ops are filtered out of epi_loop_tensors.
+        alpha = epi_loop_tensors.get("alpha")
+        beta = epi_loop_tensors.get("beta")
+        tDrRowVec = epi_loop_tensors.get("mRowVecBroadcast")
+        tDrColVec = epi_loop_tensors.get("mColVecBroadcast")
+        rD = tRS_rD.load()
+        # Apply alpha scaling to accumulator if alpha is provided (not None)
+        if const_expr(hasattr(params, "alpha") and params.alpha is not None):
+            alpha = utils.load_scalar_or_pointer(params.alpha)
+            rD *= alpha
+        # Apply C with beta scaling
+        if const_expr(tRS_rC is not None):
+            if const_expr(not hasattr(params, "beta") or params.beta is None):
+                # beta is None, default behavior: add C (beta=1.0)
+                rD += tRS_rC.load().to(tRS_rD.element_type)
+            else:
+                beta = utils.load_scalar_or_pointer(params.beta)
+                rD += beta * tRS_rC.load().to(tRS_rD.element_type)
+        tRS_rD.store(rD)
+        if const_expr(tDrRowVec is not None):
+            for i in cutlass.range(cute.size(tDrRowVec), unroll_full=True):
+                tRS_rD[i] += tDrRowVec[i]
+        if const_expr(tDrColVec is not None):
+            for i in cutlass.range(cute.size(tDrColVec), unroll_full=True):
+                tRS_rD[i] += tDrColVec[i]
+        return None
+
+
+class GemmDefaultSm80(GemmDefaultEpiMixin, GemmSm80):
+    pass
+
+
+class GemmDefaultSm90(GemmDefaultEpiMixin, GemmSm90):
+    pass
+
+
+class GemmDefaultSm100(GemmDefaultEpiMixin, GemmSm100):
+    pass
+
+
+class GemmDefaultSm120(GemmDefaultEpiMixin, GemmSm120):
+    pass
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_sm100.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_sm100.py
new file mode 100644
index 0000000000000000000000000000000000000000..43919bc4e114531f10dbc2461703c089fc2b3a73
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_sm100.py
@@ -0,0 +1,2733 @@
+# Copyright (c) 2025-2026, QuACK team.
+# Based on the cute-dsl example:
+# https://github.com/NVIDIA/cutlass/blob/main/examples/python/CuTeDSL/blackwell/dense_gemm_persistent.py
+
+from typing import Optional, Type, Tuple, Union, Callable, Literal
+from functools import partial
+import math
+
+import cuda.bindings.driver as cuda
+
+import cutlass
+import cutlass.cute as cute
+from cutlass.cute.nvgpu import cpasync, tcgen05
+import cutlass.pipeline as pipeline
+from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait
+import cutlass.utils.blackwell_helpers as sm100_utils
+import cutlass.utils.blockscaled_layout as blockscaled_utils
+from cutlass.cute.nvgpu.warp import (
+    LdMatrix8x8x16bOp,
+    LdMatrix16x16x8bOp,
+    StMatrix8x8x16bOp,
+    StMatrix16x8x8bOp,
+)
+from cutlass import Int32, Float32, Boolean, const_expr
+from cutlass.utils import LayoutEnum
+
+from .pipeline import PipelineTmaUmma, PipelineTmaCpAsyncUmma
+from .tile_scheduler import TileSchedulerOptions
+from .varlen_utils import VarlenArguments, VarlenManager
+from .gemm_base import GemmTmaBase, NamedBarrierGemm
+from . import layout_utils
+from . import copy_utils
+from . import sm100_utils as quack_sm100_utils
+from .layout_utils import tile_atom_to_shape_SF_strided
+
+# return PipelineStateWAdvance instead of PipelineState
+
+"""
+A high-performance persistent batched dense GEMM example for the NVIDIA Blackwell SM100 architecture
+using CUTE DSL.
+- Matrix A is MxKxL, L is batch dimension, A can be row-major("K") or column-major("M")
+- Matrix B is NxKxL, L is batch dimension, B can be row-major("N") or column-major("K")
+- Matrix C is MxNxL, L is batch dimension, C can be row-major("N") or column-major("M")
+
+This GEMM kernel supports the following features:
+    - Utilizes Tensor Memory Access (TMA) for efficient memory operations
+    - Utilizes Blackwell's tcgen05.mma for matrix multiply-accumulate (MMA) operations (including 2cta mma instructions)
+    - Implements TMA multicast with cluster to reduce L2 memory traffic
+    - Support persistent tile scheduling to better overlap memory load/store with mma between tiles
+    - Support warp specialization to avoid explicit pipelining between mainloop load and mma
+
+This GEMM works as follows:
+1. DMA warp: Load A and B matrices from global memory (GMEM) to shared memory (SMEM) using TMA operations.
+2. MMA warp: Perform matrix multiply-accumulate (MMA) operations using tcgen05.mma instruction.
+3. EPILOGUE warp:
+    - Load completed accumulator from tensor memory (TMEM) to registers (RMEM) using tcgen05.ld.
+    - Type convert C matrix to output type.
+    - Optionally store C matrix from registers (RMEM) to shared memory (SMEM) to global memory (GMEM) with TMA operations,
+      or directly store C matrix from registers (RMEM) to global memory (GMEM) without TMA operations.
+
+SM100 tcgen05.mma instructions operate as follows:
+- Read matrix A from SMEM
+- Read matrix B from SMEM
+- Write accumulator to TMEM
+The accumulator in TMEM must then be loaded to registers before writing back to GMEM.
+
+Constraints:
+* Supported input data types: fp16, bf16, tf32, int8, uint8, fp8 (e4m3fn, e5m2),
+  see detailed valid dtype combinations in below GemmSm100 class documentation
+* A/B tensor must have the same data type
+* Mma tiler M must be 64/128 (use_2cta_instrs=False) or 128/256 (use_2cta_instrs=True)
+* Mma tiler N must be 32-256, step 32
+* Cluster shape M/N must be positive and power of 2, total cluster size <= 16
+* The contiguous dimension of A/B/C tensors must be at least 16 bytes aligned,
+  i.e, number of elements is a multiple of 4, 8, and 16 for TFloat32,
+  Float16/BFloat16, and Int8/Uint8/Float8, respectively.
+"""
+
+
+class GemmSm100(GemmTmaBase):
+    """This class implements batched matrix multiplication (C = A x B) with support for various data types
+    and architectural features specific to Blackwell GPUs with persistent tile scheduling and warp specialization.
+
+    :param acc_dtype: Data type for accumulation during computation
+    :type acc_dtype: type[cutlass.Numeric]
+    :param mma_tiler_mnk: Shape of the MMA tile. Pass (M, N) to default K to
+        4 MMA instructions, or (M, N, K) to set the K tile size explicitly.
+    :type mma_tiler_mnk: Union[Tuple[int, int], Tuple[int, int, int]]
+    :param cluster_shape_mn: Cluster dimensions (M,N) for parallel processing
+    :type cluster_shape_mn: Tuple[int, int]
+
+    :note: In current version, A and B tensor must have the same data type
+        - i.e., Float8E4M3FN for A and Float8E5M2 for B is not supported
+
+    :note: Supported A/B data types:
+        - TFloat32
+        - Float16/BFloat16
+        - Int8/Uint8
+        - Float8E4M3FN/Float8E5M2
+
+    :note: Supported accumulator data types:
+        - Float32 (for all floating point A/B data types)
+        - Float16 (only for fp16 and fp8 A/B data types)
+        - Int32 (only for uint8/int8 A/B data types)
+
+    :note: Supported C data types:
+        - Float32 (for float32 and int32 accumulator data types)
+        - Int32 (for float32 and int32 accumulator data types)
+        - Float16/BFloat16 (for fp16 and fp8 accumulator data types)
+        - Int8/Uint8 (for uint8/int8 accumulator data types)
+        - Float8E4M3FN/Float8E5M2 (for float32 accumulator data types)
+
+    :note: Constraints:
+        - MMA tiler M must be 64/128 (use_2cta_instrs=False) or 128/256 (use_2cta_instrs=True)
+        - MMA tiler N must be 32-256, step 32
+        - Cluster shape M must be multiple of 2 if use_2cta_instrs=True
+        - Cluster shape M/N must be positive and power of 2, total cluster size <= 16
+
+    Example:
+        >>> gemm = GemmSm100(
+        ...     acc_dtype=Float32,
+        ...     mma_tiler_mnk=(128, 128),
+        ...     cluster_shape_mn=(2, 2)
+        ... )
+        >>> gemm(mA, mB, mD, max_active_clusters, stream)
+    """
+
+    arch = 100
+
+    EpilogueArguments = GemmTmaBase.EpilogueArguments
+    EpilogueParams = GemmTmaBase.EpilogueParams
+
+    def __init__(
+        self,
+        acc_dtype: Type[cutlass.Numeric],
+        a_dtype: Type[cutlass.Numeric],  # ignored for now
+        mma_tiler_mnk: Union[Tuple[int, int], Tuple[int, int, int]],
+        cluster_shape_mnk: Tuple[int, int, int],
+        sf_vec_size: Optional[int] = None,
+        gather_A: bool = False,
+        use_tma_gather: bool = False,
+        use_clc_persistence: bool = True,
+        concat_layout: tuple | None = None,
+        use_pdl: bool = True,
+    ):
+        """Initializes the configuration for a Blackwell dense GEMM kernel.
+
+        This configuration includes several key aspects:
+
+        1.  MMA Instruction Settings (tcgen05):
+            - acc_dtype: Data types for MMA accumulator.
+            - mma_tiler_mnk: The (M, N) or (M, N, K) shape of the MMA instruction tiler.
+            - use_2cta_instrs: Boolean indicating if the tcgen05 MMA variant
+              with cta_group=2 should be used.
+
+        2.  Cluster Shape:
+            - cluster_shape_mnk: The (ClusterM, ClusterN) shape of the CTA cluster.
+
+        :param acc_dtype: Data type of the accumulator.
+        :type acc_dtype: type[cutlass.Numeric]
+        :param mma_tiler_mnk: (M, N) or (M, N, K) shape of the MMA tile.
+            If only (M, N) is given, K defaults to 4 * instruction K.
+        :type mma_tiler_mnk: Union[Tuple[int, int], Tuple[int, int, int]]
+        :param cluster_shape_mnk: Tuple (ClusterM, ClusterN) shape of the cluster.
+        :type cluster_shape_mnk: Tuple[int, int]
+        """
+
+        self.acc_dtype: Type[cutlass.Numeric] = acc_dtype
+        self.sf_vec_size = sf_vec_size
+        self.blockscaled = sf_vec_size is not None
+        assert len(mma_tiler_mnk) in [2, 3], "MMA tiler must be (M, N) or (M, N, K)"
+        valid_2cta_m = (128, 256) if not self.blockscaled else (256,)
+        self.use_2cta_instrs = cluster_shape_mnk[0] % 2 == 0 and mma_tiler_mnk[0] in valid_2cta_m
+        self.cluster_shape_mnk = cluster_shape_mnk
+        assert cluster_shape_mnk[2] == 1, "Cluster shape K must be 1"
+        # K dimension: if user provides 3 values, use their K; otherwise default in _setup_attributes
+        if len(mma_tiler_mnk) == 3:
+            self.mma_tiler = tuple(mma_tiler_mnk)
+        else:
+            self.mma_tiler = (*mma_tiler_mnk, 0)
+        self.is_persistent = True
+        self.use_clc_persistence = use_clc_persistence
+        self.epi_m_major = True
+        self.gather_A = gather_A
+        self.concat_layout = concat_layout or ()
+        self.use_tma_gather = use_tma_gather
+        self.use_pdl = use_pdl
+        if gather_A:
+            assert cluster_shape_mnk[1] == 1, "Cluster shape N must be 1 for gather A "
+        if use_tma_gather:
+            assert gather_A, "TMA gather requires gather_A=True"
+
+        self.cta_group = tcgen05.CtaGroup.TWO if self.use_2cta_instrs else tcgen05.CtaGroup.ONE
+
+        self.num_ab_load_warps = 1 if not self.gather_A else 4
+        self.occupancy = 1
+        # Set specialized warp ids
+        self.epi_warps_per_accumulator = 4
+        num_epi_warps = self.epi_warps_per_accumulator
+        self.epilog_warp_id = tuple(range(num_epi_warps))
+        self.mma_warp_id = len(self.epilog_warp_id)
+        self.ab_load_warp_id = self.mma_warp_id + 1
+        self.epi_load_warp_id = self.ab_load_warp_id + self.num_ab_load_warps
+        self.scheduler_warp_id = self.epi_load_warp_id + 1
+        # For gather_A: separate A-index prefetch warp (was the empty warp)
+        self.a_prefetch_warp_id = self.scheduler_warp_id + 1 if self.gather_A else None
+        self.num_epi_warps = len(self.epilog_warp_id)
+        self.epilogue_barrier = pipeline.NamedBarrier(
+            barrier_id=int(NamedBarrierGemm.Epilogue),
+            num_threads=self.num_epi_warps * cute.arch.WARP_SIZE,
+        )
+        # Register reallocation for gather_A (3 warp groups, 504 regs total, 168 per WG default).
+        # Heavy epilogues (e.g. colvec_reduce in DGated) override these to avoid register spilling.
+        # Without gather_A there are only 2 WGs (512 total, 256 per WG = max), no reallocation needed.
+        self.num_regs_other = 120
+        self.num_regs_epi = 256
+        extra_warp_ids = (self.a_prefetch_warp_id,) if self.gather_A else ()
+        self.threads_per_cta = cute.arch.WARP_SIZE * (
+            self.num_ab_load_warps
+            + len(
+                (
+                    self.mma_warp_id,
+                    self.epi_load_warp_id,
+                    self.scheduler_warp_id,
+                    *self.epilog_warp_id,
+                    *extra_warp_ids,
+                )
+            )
+        )
+        # Multiple of 4 warps to increase/decrease number of registers
+        assert self.threads_per_cta % 128 == 0
+
+    def epi_smem_warp_shape_mnk(self):
+        # Mirrors cutlass.utils.blackwell_helpers.compute_epilogue_tile_shape:
+        # the epilogue tmem layout uses two M warps and two N warps when the
+        # per-CTA M tile is 64 and the kernel uses 2-CTA instructions.
+        warp_m, warp_n = (
+            (2, 2) if self.cta_tile_shape_mnk[0] == 64 and self.use_2cta_instrs else (4, 1)
+        )
+        return (warp_m, warp_n, 1)
+
+    def _setup_attributes(self, epilogue_args: EpilogueArguments, varlen_args: VarlenArguments):
+        """Set up configurations that are dependent on GEMM inputs
+
+        This method configures various attributes based on the input tensor properties
+        (data types, leading dimensions) and kernel settings:
+        - Configuring tiled MMA
+        - Computing MMA/cluster/tile shapes
+        - Computing cluster layout
+        - Computing multicast CTAs for A/B
+        - Computing epilogue subtile
+        - Setting up A/B/C stage counts in shared memory
+        - Computing A/B/C shared memory layout
+        - Computing tensor memory allocation columns
+        """
+        self.epi_m_major = self.resolve_epi_m_major(epilogue_args)
+
+        # Compute mma instruction shapes
+        mma_inst_bits_k = 256
+        # (MMA_Tile_Shape_M, MMA_Tile_Shape_N, MMA_Inst_Shape_K)
+        mma_inst_shape_n = self.mma_tiler[1] if self.mma_tiler[1] <= 256 else self.mma_tiler[1] // 2
+        self.mma_inst_shape_mnk = (
+            self.mma_tiler[0],
+            mma_inst_shape_n,
+            mma_inst_bits_k // self.a_dtype.width,
+        )
+        # (CTA_Tile_Shape_M, Round_Up(MMA_Tile_Shape_N, 128), MMA_Inst_Shape_K)
+        self.mma_inst_shape_mnk_sfb = (
+            self.mma_inst_shape_mnk[0] // (2 if self.use_2cta_instrs else 1),
+            cute.round_up(self.mma_inst_shape_mnk[1], 128),
+            self.mma_inst_shape_mnk[2],
+        )
+
+        # Configure tiled mma
+        if const_expr(not self.blockscaled):
+            self.tiled_mma = sm100_utils.make_trivial_tiled_mma(
+                self.a_dtype,
+                self.b_dtype,
+                self.a_major_mode,
+                self.b_major_mode,
+                self.acc_dtype,
+                self.cta_group,
+                self.mma_inst_shape_mnk[:2],
+            )
+            self.tiled_mma_sfb = None
+        else:
+            self.tiled_mma = sm100_utils.make_blockscaled_trivial_tiled_mma(
+                self.a_dtype,
+                self.b_dtype,
+                self.a_major_mode,
+                self.b_major_mode,
+                self.sf_dtype,
+                self.sf_vec_size,
+                self.cta_group,
+                self.mma_inst_shape_mnk[:2],
+            )
+            self.tiled_mma_sfb = sm100_utils.make_blockscaled_trivial_tiled_mma(
+                self.a_dtype,
+                self.b_dtype,
+                self.a_major_mode,
+                self.b_major_mode,
+                self.sf_dtype,
+                self.sf_vec_size,
+                tcgen05.CtaGroup.ONE,
+                self.mma_inst_shape_mnk_sfb[:2],
+            )
+
+        # Compute mma/cluster/tile shapes
+        if self.mma_tiler[2] > 0:
+            assert self.mma_tiler[2] % self.mma_inst_shape_mnk[2] == 0, (
+                f"MMA tiler K ({self.mma_tiler[2]}) must be divisible by "
+                f"MMA instruction K ({self.mma_inst_shape_mnk[2]})"
+            )
+            mma_inst_tile_k = self.mma_tiler[2] // self.mma_inst_shape_mnk[2]
+        else:
+            mma_inst_tile_k = 4
+        self.mma_tiler = (
+            self.mma_tiler[0],
+            self.mma_tiler[1],
+            self.mma_inst_shape_mnk[2] * mma_inst_tile_k,
+        )
+        if const_expr(self.blockscaled):
+            self.mma_tiler_sfb = (
+                self.mma_inst_shape_mnk_sfb[0],
+                self.mma_inst_shape_mnk_sfb[1],
+                self.mma_inst_shape_mnk_sfb[2] * mma_inst_tile_k,
+            )
+        else:
+            self.mma_tiler_sfb = None
+        self.cta_tile_shape_mnk = (
+            self.mma_tiler[0] // cute.size(self.tiled_mma.thr_id.shape),
+            self.mma_tiler[1],
+            self.mma_tiler[2],
+        )
+        if const_expr(self.blockscaled):
+            self.cta_tile_shape_mnk_sfb = (
+                self.mma_tiler_sfb[0] // cute.size(self.tiled_mma.thr_id.shape),
+                self.mma_tiler_sfb[1],
+                self.mma_tiler_sfb[2],
+            )
+        else:
+            self.cta_tile_shape_mnk_sfb = None
+
+        # Compute cluster layout
+        self.cluster_layout_vmnk = cute.tiled_divide(
+            cute.make_layout(self.cluster_shape_mnk),
+            (self.tiled_mma.thr_id.shape,),
+        )
+        if const_expr(self.blockscaled):
+            self.cluster_layout_sfb_vmnk = cute.tiled_divide(
+                cute.make_layout(self.cluster_shape_mnk),
+                (self.tiled_mma_sfb.thr_id.shape,),
+            )
+        else:
+            self.cluster_layout_sfb_vmnk = None
+
+        # Compute number of multicast CTAs for A/B
+        self.num_mcast_ctas_a = cute.size(self.cluster_layout_vmnk.shape[2])
+        if self.gather_A:
+            assert self.num_mcast_ctas_a == 1
+        self.num_mcast_ctas_b = cute.size(self.cluster_layout_vmnk.shape[1])
+        self.is_a_mcast = self.num_mcast_ctas_a > 1
+        self.is_b_mcast = self.num_mcast_ctas_b > 1
+        if const_expr(self.blockscaled):
+            self.num_mcast_ctas_sfb = cute.size(self.cluster_layout_sfb_vmnk.shape[1])
+            self.is_sfb_mcast = self.num_mcast_ctas_sfb > 1
+
+        # Compute epilogue subtile
+        tile_load_layout = None
+        tile_load_dtype = None
+        # If TileLoad exists without C, use the first non-None tile-load tensor as
+        # the C-like input for SM100's epilogue tile shape. Multiple TileLoads
+        # share the same epi_tile shape.
+        for op in getattr(self, "_epi_ops", ()):
+            if op.is_tile_load():
+                tile_load_tensor = getattr(epilogue_args, op.name, None)
+                if tile_load_tensor is not None:
+                    if isinstance(tile_load_tensor, tuple):
+                        tile_load_tensor = tile_load_tensor[0]
+                    tile_load_layout = LayoutEnum.from_tensor(tile_load_tensor)
+                    tile_load_dtype = tile_load_tensor.element_type
+                    break
+        self.epi_tile = sm100_utils.compute_epilogue_tile_shape(
+            self.cta_tile_shape_mnk,
+            self.use_2cta_instrs,
+            self.d_layout if self.d_layout is not None else LayoutEnum.ROW_MAJOR,
+            self.d_dtype if self.d_dtype is not None else cutlass.BFloat16,
+            layout_c=self.c_layout if self.c_layout is not None else tile_load_layout,
+            elem_ty_c=self.c_dtype if self.c_dtype is not None else tile_load_dtype,
+        )
+        # TMA store tile starts must stay aligned when advancing across CTA-N tiles.
+        # There's a bug w compute_epilogue_tile_shape (as of cutlass-dsl 4.4.2) where if
+        # tile_n = 224 and there's C, it will set epi_tile to (128, 64).
+        if const_expr(self.cta_tile_shape_mnk[1] % cute.size(self.epi_tile[1]) != 0):
+            warp_n = 2 if (self.cta_tile_shape_mnk[0] == 64 and self.use_2cta_instrs) else 1
+            epi_tile_n = math.gcd(self.cta_tile_shape_mnk[1], cute.size(self.epi_tile[1]))
+            epi_tile_n_layout = cute.make_layout(
+                (epi_tile_n // warp_n, warp_n), stride=(1, self.cta_tile_shape_mnk[1] // warp_n)
+            )
+            self.epi_tile = (self.epi_tile[0], cute.coalesce(epi_tile_n_layout))
+
+        # Setup A/B/C stage count in shared memory and ACC stage count in tensor memory
+        prefetch_A_idx = (
+            None
+            if not self.gather_A
+            else ("varlen_m" if varlen_args.mCuSeqlensM is not None else "varlen_k")
+        )
+        (
+            self.num_acc_stage,
+            self.ab_stage,
+            self.epi_stage,
+            self.epi_c_stage,
+        ) = self._compute_stages(
+            self.tiled_mma,
+            self.mma_tiler,
+            self.cta_tile_shape_mnk,
+            self.epi_tile,
+            self.a_dtype,
+            self.b_dtype,
+            self.sf_dtype,
+            self.sf_vec_size,
+            self.d_dtype,
+            self.c_dtype,
+            self.d_layout,
+            self.c_layout,
+            epilogue_args,
+            prefetch_A_idx,
+            cutlass.utils.get_smem_capacity_in_bytes(f"sm_{self.arch}"),  # smem_capacity
+            self.occupancy,
+            self.epi_smem_warp_shape_mnk(),
+        )
+        self.sched_stage = 1
+        self.a_prefetch_stage = (
+            0
+            if not self.gather_A
+            else (2 if varlen_args.mCuSeqlensM is not None else self.ab_stage)
+        )
+
+        # Compute A/B/SFA/SFB/C shared memory layout
+        self.a_smem_layout_staged = sm100_utils.make_smem_layout_a(
+            self.tiled_mma, self.mma_tiler, self.a_dtype, self.ab_stage
+        )
+        self.a_smem_load_layout_staged = self.a_smem_layout_staged
+        if const_expr(self.gather_A):
+            if const_expr(self.use_tma_gather):
+                self.a_smem_load_layout_staged = quack_sm100_utils.make_smem_layout_tma_gather_a(
+                    self.tiled_mma, self.mma_tiler, self.a_dtype, self.ab_stage
+                )
+            else:
+                self.a_smem_load_layout_staged = quack_sm100_utils.make_smem_layout_cpasync_a(
+                    self.tiled_mma, self.mma_tiler, self.a_dtype, self.ab_stage
+                )
+        self.b_smem_layout_staged = sm100_utils.make_smem_layout_b(
+            self.tiled_mma, self.mma_tiler, self.b_dtype, self.ab_stage
+        )
+        self.epi_smem_layout_staged = None
+        if const_expr(self.d_dtype is not None):
+            self.epi_smem_layout_staged = sm100_utils.make_smem_layout_epi(
+                self.d_dtype, self.d_layout, self.epi_tile, self.epi_stage
+            )
+        self.epi_c_smem_layout_staged = None
+        if const_expr(self.c_dtype is not None):
+            self.epi_c_smem_layout_staged = sm100_utils.make_smem_layout_epi(
+                self.c_dtype, self.c_layout, self.epi_tile, self.epi_c_stage
+            )
+        if const_expr(self.blockscaled):
+            self.sfa_smem_layout_staged = blockscaled_utils.make_smem_layout_sfa(
+                self.tiled_mma,
+                self.mma_tiler,
+                self.sf_vec_size,
+                self.ab_stage,
+            )
+            self.sfb_smem_layout_staged = blockscaled_utils.make_smem_layout_sfb(
+                self.tiled_mma,
+                self.mma_tiler,
+                self.sf_vec_size,
+                self.ab_stage,
+            )
+        else:
+            self.sfa_smem_layout_staged, self.sfb_smem_layout_staged = None, None
+
+        # Compute the number of tensor memory allocation columns
+        if const_expr(not self.blockscaled):
+            self.num_tmem_alloc_cols = self._compute_num_tmem_alloc_cols(
+                self.tiled_mma, self.mma_tiler, self.num_acc_stage
+            )
+        else:
+            self.num_tmem_alloc_cols = cute.arch.get_max_tmem_alloc_cols("sm_100")
+
+        # Overlapping accumulator and scaling factor in tmem, targetting the case tile_n == 256
+        # For iter 0, 2, ..., accum is in col 0...255 and SF are in col 256...256+SF_size.
+        # For iter 1, 3, ..., accum is in col 256...511 and SF are in col 0...0+SF_size.
+        # During the epilogue, we release acc_pipeline after being done with @SF_size columns.
+        # In the cute-dsl example,
+        # https://github.com/NVIDIA/cutlass/blob/08185b9c3e90510ee2b656662ed0d53b06d28157/examples/python/CuTeDSL/blackwell/dense_blockscaled_gemm_persistent.py#L369
+        # instead the 2 stages of accum are in col 0...255 and 256-SF_size...512-SF_size, and
+        # the SF are in 512-SF_size...511. The 2 accum stages overlap, so in the epilogue,
+        # they alternate the direction of epi tiles (from right to left, then from left to right)
+        # to release acc_pipeline early.
+        # The two approaches perform about the same.
+        self.overlap_accum_sf = self.blockscaled and self.num_acc_stage == 1
+        if const_expr(self.overlap_accum_sf):
+            num_sf_tmem_cols = (
+                (
+                    cute.ceil_div(self.cta_tile_shape_mnk[0], 128)
+                    + cute.ceil_div(self.cta_tile_shape_mnk[1], 128)
+                )
+                * 4  # 4 cols per stage
+                * (self.mma_inst_shape_mnk[2] // self.sf_vec_size)
+            )
+            self.iter_acc_early_release = num_sf_tmem_cols // cute.size(self.epi_tile[1])
+        else:
+            self.iter_acc_early_release = -1
+
+    @cute.jit
+    def __call__(
+        self,
+        mA: cute.Tensor,
+        mB: cute.Tensor,
+        mD: Optional[cute.Tensor],
+        mC: Optional[cute.Tensor],
+        epilogue_args: tuple,
+        scheduler_args: TileSchedulerOptions,
+        varlen_args: Optional[VarlenArguments],
+        stream: cuda.CUstream,
+        mSFA: Optional[cute.Tensor] = None,
+        mSFB: Optional[cute.Tensor] = None,
+        trace_ptr: Optional[cutlass.Int64] = None,
+    ):
+        """Execute the GEMM operation in steps:
+        - Setup static attributes before smem/grid/tma computation
+        - Setup TMA load/store atoms and tensors
+        - Compute grid size with regard to hardware constraints
+        - Define shared storage for kernel
+        - Launch the kernel synchronously
+
+        :param mA: Input tensor A
+        :type mA: cute.Tensor
+        :param mB: Input tensor B
+        :type mB: cute.Tensor
+        :param mD: Output tensor D
+        :type mD: cute.Tensor
+        :param max_active_clusters: Maximum number of active clusters
+        :type max_active_clusters: cutlass.Constexpr
+        :param stream: CUDA stream for asynchronous execution
+        :type stream: cuda.CUstream
+        :raises TypeError: If input data types are incompatible with the MMA instruction.
+        :raises AssertionError: If OOB (Out-Of-Bounds) tiles are present when TMA store is disabled.
+        """
+        if const_expr(self.blockscaled):
+            assert mSFA is not None and mSFB is not None
+        # Concat layout: interleave the non-contiguous dim (detected via leading_dim).
+        mA, mB, mD, mC = [
+            layout_utils.concat_to_interleave(mT, 1 - mT.leading_dim)
+            if const_expr(name in self.concat_layout and mT is not None)
+            else mT
+            for name, mT in [("A", mA), ("B", mB), ("out", mD), ("C", mC)]
+        ]
+        # Setup static attributes before smem/grid/tma computation
+        self.a_dtype = mA.element_type
+        self.b_dtype = mB.element_type
+        self.d_dtype = mD.element_type if mD is not None else None
+        self.c_dtype = mC.element_type if mC is not None else None
+        self.sf_dtype: Optional[Type[cutlass.Numeric]] = (
+            mSFA.element_type if mSFA is not None else None
+        )
+        self.a_layout = LayoutEnum.from_tensor(mA)
+        self.b_layout = LayoutEnum.from_tensor(mB)
+        self.d_layout = LayoutEnum.from_tensor(mD) if mD is not None else None
+        self.c_layout = LayoutEnum.from_tensor(mC) if mC is not None else None
+        self.a_major_mode = LayoutEnum.from_tensor(mA).mma_major_mode()
+        self.b_major_mode = LayoutEnum.from_tensor(mB).mma_major_mode()
+
+        # Check if input data types are compatible with MMA instruction
+        if const_expr(self.a_dtype != self.b_dtype):
+            raise TypeError(f"Type must match: {self.a_dtype} != {self.b_dtype}")
+
+        if const_expr(varlen_args is None):
+            varlen_args = VarlenArguments()
+        assert (varlen_args.mAIdx is not None) == self.gather_A
+        varlen_m = varlen_args.mCuSeqlensM is not None
+        varlen_k = varlen_args.mCuSeqlensK is not None
+
+        # Setup attributes that dependent on gemm inputs
+        self._setup_attributes(epilogue_args, varlen_args)
+
+        if const_expr(self.blockscaled):
+            # Rebuild the SFA/SFB layouts from mSFA/mSFB's actual strides
+            # so non-packed buffers work (e.g. a slice of a larger scale tensor).
+            # Only the innermost 512-B tile must be contiguous.
+            # For varlen_m, mSFA is sized for per-expert 128-row-padded storage
+            # (dQaccum format), so use its own M dim (= total_padded_rm * 128)
+            # instead of mA.shape[0] (= total_m, unpadded).
+            if const_expr(cute.rank(mA) == 3):
+                sfa_shape = mA.shape
+            elif const_expr(varlen_m):
+                sfa_shape = (mSFA.shape[1] * 128, mA.shape[1])
+            else:  # varlen_k
+                sfa_shape = (mA.shape[0], mSFA.shape[2] * 128)
+            sfa_layout = tile_atom_to_shape_SF_strided(sfa_shape, self.sf_vec_size, mSFA.stride)
+            mSFA = cute.make_tensor(mSFA.iterator, sfa_layout)
+            if const_expr(cute.rank(mB) == 3):
+                sfb_shape = mB.shape
+            else:  # varlen_k: mB is (n, total_k)
+                sfb_shape = (mB.shape[0], mSFB.shape[2] * 128)
+            sfb_layout = tile_atom_to_shape_SF_strided(sfb_shape, self.sf_vec_size, mSFB.stride)
+            mSFB = cute.make_tensor(mSFB.iterator, sfb_layout)
+
+        atom_thr_size = cute.size(self.tiled_mma.thr_id.shape)
+
+        # Setup TMA load for A & B
+        a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0))
+        b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0))
+        tma_atom_a, tma_tensor_a = None, None
+        a_op = sm100_utils.cluster_shape_to_tma_atom_A(
+            self.cluster_shape_mnk, self.tiled_mma.thr_id
+        )
+        if const_expr(not self.gather_A):
+            tma_atom_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A(
+                a_op,
+                copy_utils.create_ragged_tensor_for_tma(mA, ragged_dim=1, ptr_shift=False)
+                if varlen_k and not self.gather_A
+                else mA,
+                a_smem_layout,
+                self.mma_tiler,
+                self.tiled_mma,
+                self.cluster_layout_vmnk.shape,
+                internal_type=(cutlass.TFloat32 if mA.element_type is Float32 else None),
+            )
+        elif const_expr(self.use_tma_gather):
+            # gather4 descriptor: box has 1 in the gathered dim, tile size in the contiguous dim.
+            # varlen_m (K-major): box (1, tile_K), gather M rows at K offset
+            # varlen_k (M-major): box (64, 1), gather K cols at M offset
+            tma_smem_layout = quack_sm100_utils.make_smem_layout_atom_tma_gather_a(
+                self.tiled_mma, self.mma_tiler, self.a_dtype, gather_size=1
+            )
+            tma_atom_a, tma_tensor_a = cpasync.make_tiled_tma_atom(
+                a_op,
+                mA,
+                tma_smem_layout,
+                tma_smem_layout.shape,
+                internal_type=(cutlass.TFloat32 if mA.element_type is Float32 else None),
+            )
+        b_op = sm100_utils.cluster_shape_to_tma_atom_B(
+            self.cluster_shape_mnk, self.tiled_mma.thr_id
+        )
+        tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B(
+            b_op,
+            copy_utils.create_ragged_tensor_for_tma(mB, ragged_dim=1) if varlen_k else mB,
+            b_smem_layout,
+            self.mma_tiler,
+            self.tiled_mma,
+            self.cluster_layout_vmnk.shape,
+            internal_type=(cutlass.TFloat32 if mB.element_type is Float32 else None),
+        )
+
+        tma_atom_sfa, tma_tensor_sfa = None, None
+        tma_atom_sfb, tma_tensor_sfb = None, None
+        if const_expr(self.blockscaled):
+            # Setup TMA load for SFA
+            sfa_op = sm100_utils.cluster_shape_to_tma_atom_A(
+                self.cluster_shape_mnk, self.tiled_mma.thr_id
+            )
+            sfa_smem_layout = cute.slice_(self.sfa_smem_layout_staged, (None, None, None, 0))
+            tma_atom_sfa, tma_tensor_sfa = cute.nvgpu.make_tiled_tma_atom_A(
+                sfa_op,
+                mSFA,
+                sfa_smem_layout,
+                self.mma_tiler,
+                self.tiled_mma,
+                self.cluster_layout_vmnk.shape,
+                internal_type=cutlass.Int16,
+            )
+            # Setup TMA load for SFB
+            sfb_op = sm100_utils.cluster_shape_to_tma_atom_SFB(
+                self.cluster_shape_mnk, self.tiled_mma.thr_id
+            )
+            sfb_smem_layout = cute.slice_(self.sfb_smem_layout_staged, (None, None, None, 0))
+            tma_atom_sfb, tma_tensor_sfb = cute.nvgpu.make_tiled_tma_atom_B(
+                sfb_op,
+                mSFB,
+                sfb_smem_layout,
+                self.mma_tiler_sfb,
+                self.tiled_mma_sfb,
+                self.cluster_layout_sfb_vmnk.shape,
+                internal_type=cutlass.Int16,
+            )
+            if const_expr(
+                self.cta_tile_shape_mnk[1] == 192 and self.sf_dtype is cutlass.Float8E8M0FNU
+            ):
+                x = tma_tensor_sfb.stride[0][1]
+                y = cute.ceil_div(tma_tensor_sfb.shape[0][1], 4)
+                tma_tensor_sfb = cute.make_tensor(
+                    tma_tensor_sfb.iterator,
+                    cute.make_layout(
+                        (
+                            (tma_tensor_sfb.shape[0][0], ((2, 2), y)),
+                            tma_tensor_sfb.shape[1],
+                            tma_tensor_sfb.shape[2],
+                        ),
+                        stride=(
+                            (tma_tensor_sfb.stride[0][0], ((x, x), 3 * x)),
+                            tma_tensor_sfb.stride[1],
+                            tma_tensor_sfb.stride[2],
+                        ),
+                    ),
+                )
+
+        self.num_tma_load_bytes = cute.size_in_bytes(self.b_dtype, b_smem_layout)
+        if const_expr(not self.gather_A or self.use_tma_gather):
+            self.num_tma_load_bytes += cute.size_in_bytes(self.a_dtype, a_smem_layout)
+        if const_expr(self.blockscaled):
+            sfa_copy_size = cute.size_in_bytes(self.sf_dtype, sfa_smem_layout)
+            sfb_copy_size = cute.size_in_bytes(self.sf_dtype, sfb_smem_layout)
+            self.num_tma_load_bytes += sfa_copy_size + sfb_copy_size
+        self.num_tma_load_bytes *= atom_thr_size
+
+        # Setup TMA store for D and TMA load for C.
+        tma_atom_d, tma_tensor_d, tma_atom_c, tma_tensor_c = (
+            self.make_tma_epilogue_atoms_and_tensors(mD, mC, epilogue_args, varlen_m)
+        )
+
+        epilogue_params = self.epi_to_underlying_arguments(epilogue_args)
+        varlen_params = VarlenManager.to_underlying_arguments(varlen_args)
+
+        self.epi_load_bytes_per_stage = self.epi_smem_bytes(
+            epilogue_args,
+            self.cta_tile_shape_mnk,
+            self.epi_tile,
+            self.epi_smem_warp_shape_mnk(),
+        ).c_stage
+        if const_expr(mC is not None):
+            c_smem_layout = cute.slice_(self.epi_c_smem_layout_staged, (None, None, 0))
+            self.epi_load_bytes_per_stage += cute.size_in_bytes(self.c_dtype, c_smem_layout)
+
+        TileSchedulerCls = self.get_scheduler_class(varlen_m=varlen_m)
+        tile_sched_args = self.get_scheduler_arguments(
+            mA, mB, mD, scheduler_args, varlen_args, epilogue_args
+        )
+        tile_sched_params = TileSchedulerCls.to_underlying_arguments(tile_sched_args)
+        grid = TileSchedulerCls.get_grid_shape(
+            tile_sched_params, scheduler_args.max_active_clusters
+        )
+
+        self.buffer_align_bytes = 1024
+
+        epi_smem_size = cute.cosize(self.epi_smem_layout_staged) if mD is not None else 0
+        epi_c_smem_size = cute.cosize(self.epi_c_smem_layout_staged) if mC is not None else 0
+        sf_dtype = self.sf_dtype if const_expr(self.blockscaled) else cutlass.Float8E8M0FNU
+        sfa_smem_size = (
+            cute.cosize(self.sfa_smem_layout_staged) if const_expr(self.blockscaled) else 0
+        )
+        sfb_smem_size = (
+            cute.cosize(self.sfb_smem_layout_staged) if const_expr(self.blockscaled) else 0
+        )
+        a_idx_smem_size = 0
+        if const_expr(self.gather_A):
+            a_idx_smem_size = self.a_prefetch_stage * (
+                self.cta_tile_shape_mnk[0] if varlen_m else self.cta_tile_shape_mnk[2]
+            )
+
+        # Define shared storage for kernel
+        @cute.struct
+        class SharedStorage:
+            ab_pipeline_array_ptr: cute.struct.MemRange[cutlass.Int64, self.ab_stage * 2]
+            epi_pipeline_array_ptr: cute.struct.MemRange[cutlass.Int64, self.epi_c_stage * 2]
+            acc_pipeline_array_ptr: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage * 2]
+            sched_pipeline_array_ptr: cute.struct.MemRange[cutlass.Int64, self.sched_stage * 2]
+            a_prefetch_pipeline_array_ptr: cute.struct.MemRange[
+                cutlass.Int64, self.a_prefetch_stage * 2
+            ]
+            sched_data: cute.struct.MemRange[Int32, self.sched_stage * 12]
+            tmem_dealloc_mbar_ptr: cutlass.Int64
+            tmem_holding_buf: Int32
+            sAIdx: cute.struct.Align[cute.struct.MemRange[Int32, a_idx_smem_size], 16]
+            # (EPI_TILE_M, EPI_TILE_N, STAGE)
+            sD: cute.struct.Align[
+                cute.struct.MemRange[
+                    self.d_dtype if self.d_dtype is not None else Int32, epi_smem_size
+                ],
+                self.buffer_align_bytes,
+            ]
+            sC: cute.struct.Align[
+                cute.struct.MemRange[
+                    self.c_dtype if self.c_dtype is not None else Int32, epi_c_smem_size
+                ],
+                self.buffer_align_bytes,
+            ]
+            epi: self.epi_get_smem_struct(epilogue_params)
+            # (MMA, MMA_M, MMA_K, STAGE)
+            sA: cute.struct.Align[
+                cute.struct.MemRange[self.a_dtype, cute.cosize(self.a_smem_layout_staged.outer)],
+                self.buffer_align_bytes,
+            ]
+            # (MMA, MMA_N, MMA_K, STAGE)
+            sB: cute.struct.Align[
+                cute.struct.MemRange[self.b_dtype, cute.cosize(self.b_smem_layout_staged.outer)],
+                self.buffer_align_bytes,
+            ]
+            # (MMA, MMA_M, MMA_K, STAGE)
+            sSFA: cute.struct.Align[
+                cute.struct.MemRange[sf_dtype, sfa_smem_size],
+                self.buffer_align_bytes,
+            ]
+            # (MMA, MMA_N, MMA_K, STAGE)
+            sSFB: cute.struct.Align[
+                cute.struct.MemRange[sf_dtype, sfb_smem_size],
+                self.buffer_align_bytes,
+            ]
+
+        self.shared_storage = SharedStorage
+
+        # Launch the kernel synchronously
+        self.kernel(
+            self.tiled_mma,
+            self.tiled_mma_sfb,
+            tma_atom_a,
+            tma_tensor_a if const_expr(not self.gather_A or self.use_tma_gather) else mA,
+            tma_atom_b,
+            tma_tensor_b,
+            tma_atom_sfa,
+            tma_tensor_sfa,
+            tma_atom_sfb,
+            tma_tensor_sfb,
+            tma_atom_d,
+            tma_tensor_d,
+            tma_atom_c,
+            tma_tensor_c,
+            epilogue_params,
+            varlen_params,
+            self.cluster_layout_vmnk,
+            self.cluster_layout_sfb_vmnk,
+            self.a_smem_layout_staged,
+            self.a_smem_load_layout_staged,
+            self.b_smem_layout_staged,
+            self.sfa_smem_layout_staged,
+            self.sfb_smem_layout_staged,
+            self.epi_smem_layout_staged,
+            self.epi_c_smem_layout_staged,
+            self.epi_tile,
+            tile_sched_params,
+            TileSchedulerCls,
+            trace_ptr,
+        ).launch(
+            grid=grid,
+            block=[self.threads_per_cta, 1, 1],
+            cluster=self.cluster_shape_mnk,
+            stream=stream,
+            min_blocks_per_mp=1,
+            use_pdl=self.use_pdl,
+        )
+        return
+
+    # GPU device kernel
+    @cute.kernel
+    def kernel(
+        self,
+        tiled_mma: cute.TiledMma,
+        tiled_mma_sfb: Optional[cute.TiledMma],
+        tma_atom_a: Optional[cute.CopyAtom],
+        mA_mkl: cute.Tensor,
+        tma_atom_b: cute.CopyAtom,
+        mB_nkl: cute.Tensor,
+        tma_atom_sfa: Optional[cute.CopyAtom],
+        mSFA_mkl: Optional[cute.Tensor],
+        tma_atom_sfb: Optional[cute.CopyAtom],
+        mSFB_nkl: Optional[cute.Tensor],
+        tma_atom_d: Optional[cute.CopyAtom],
+        mD_mnl: Optional[cute.Tensor],
+        tma_atom_c: Optional[cute.CopyAtom],
+        mC_mnl: Optional[cute.Tensor],
+        epilogue_params,
+        varlen_params: VarlenManager.Params,
+        cluster_layout_vmnk: cute.Layout,
+        cluster_layout_sfb_vmnk: Optional[cute.Layout],
+        a_smem_layout: cute.ComposedLayout,
+        a_smem_load_layout: cute.ComposedLayout,
+        b_smem_layout: cute.ComposedLayout,
+        sfa_smem_layout: Optional[cute.Layout],
+        sfb_smem_layout: Optional[cute.Layout],
+        epi_smem_layout: Union[cute.Layout, cute.ComposedLayout, None],
+        epi_c_smem_layout: Union[cute.Layout, cute.ComposedLayout, None],
+        epi_tile: cute.Tile,
+        tile_sched_params,
+        TileSchedulerCls: cutlass.Constexpr[Callable],
+        trace_ptr: Optional[cutlass.Int64] = None,
+    ):
+        """
+        GPU device kernel performing the Persistent batched GEMM computation.
+        """
+
+        from .trace import TraceContext
+
+        tctx = TraceContext.create(trace_ptr)
+
+        varlen_m = const_expr(varlen_params.cu_seqlens_m is not None)
+        varlen_k = const_expr(varlen_params.cu_seqlens_k is not None)
+        assert not (varlen_m and varlen_k)
+        if const_expr(self.gather_A):
+            assert varlen_m or varlen_k
+        has_D = const_expr(mD_mnl is not None)
+        has_C = const_expr(mC_mnl is not None)
+        has_epi_load = const_expr(self.epi_c_stage > 0)
+
+        warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
+
+        # Prefetch Tma desc
+        if warp_idx == self.ab_load_warp_id:
+            for tma_atom in (
+                tma_atom_a,
+                tma_atom_b,
+                tma_atom_sfa,
+                tma_atom_sfb,
+                tma_atom_d,
+                tma_atom_c,
+            ):
+                if const_expr(tma_atom is not None):
+                    cpasync.prefetch_descriptor(tma_atom)
+
+        use_2cta_instrs = cute.size(tiled_mma.thr_id.shape) == 2
+
+        # Setup cta/thread coordinates
+        # Coords inside cluster
+        bidx, _, _ = cute.arch.block_idx()
+        mma_tile_coord_v = bidx % cute.size(tiled_mma.thr_id.shape)
+        is_leader_cta = mma_tile_coord_v == 0
+        cta_rank_in_cluster = cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster())
+        # Coord inside cta
+        tidx, _, _ = cute.arch.thread_idx()
+
+        # Alloc and init: a+b full/empty, accumulator full/empty, tensor memory dealloc barrier
+        smem = cutlass.utils.SmemAllocator()
+        storage = smem.allocate(self.shared_storage)
+
+        # Initialize pipelines and states
+        ab_pipeline = self.make_ab_pipeline(
+            tiled_mma=tiled_mma,
+            cluster_layout_vmnk=cluster_layout_vmnk,
+            ab_pipeline_mbar_ptr=storage.ab_pipeline_array_ptr.data_ptr(),
+            is_leader_cta=is_leader_cta,
+        )
+        epi_pipeline = None
+        if const_expr(has_epi_load):
+            epi_pipeline = self.make_epi_pipeline(
+                epi_pipeline_mbar_ptr=storage.epi_pipeline_array_ptr.data_ptr(),
+                tx_count=self.epi_load_bytes_per_stage,
+            )
+        acc_pipeline = self.make_acc_pipeline(
+            cluster_layout_vmnk=cluster_layout_vmnk,
+            acc_pipeline_mbar_ptr=storage.acc_pipeline_array_ptr.data_ptr(),
+        )
+        sched_pipeline = None
+        sched_data = None
+        if const_expr(self.is_persistent):
+            sched_pipeline = self.make_sched_pipeline(
+                self.cluster_shape_mnk,
+                sched_pipeline_mbar_ptr=storage.sched_pipeline_array_ptr.data_ptr(),
+                has_C=has_epi_load,
+            )
+            sched_data = storage.sched_data.get_tensor((12, self.sched_stage))
+        a_prefetch_pipeline = None
+        if const_expr(self.gather_A):
+            a_prefetch_pipeline = self.make_a_prefetch_pipeline(
+                storage.a_prefetch_pipeline_array_ptr.data_ptr(),
+            )
+
+        tmem_alloc_barrier = pipeline.NamedBarrier(
+            barrier_id=int(NamedBarrierGemm.TmemPtr),
+            num_threads=cute.arch.WARP_SIZE * len((self.mma_warp_id, *self.epilog_warp_id)),
+        )
+        # Tensor memory dealloc barrier init
+        tmem = cutlass.utils.TmemAllocator(
+            storage.tmem_holding_buf.ptr,
+            barrier_for_retrieve=tmem_alloc_barrier,
+            allocator_warp_id=self.epilog_warp_id[0],
+            is_two_cta=use_2cta_instrs,
+            two_cta_tmem_dealloc_mbar_ptr=storage.tmem_dealloc_mbar_ptr.ptr,
+        )
+
+        # Cluster arrive after barrier init
+        pipeline_init_arrive(cluster_shape_mn=cluster_layout_vmnk, is_relaxed=True)
+
+        # Setup smem tensor A/B/D
+        # (MMA, MMA_M, MMA_K, STAGE)
+        sA_mma = storage.sA.get_tensor(a_smem_layout.outer, swizzle=a_smem_layout.inner)
+        sA = storage.sA.get_tensor(a_smem_load_layout.outer, swizzle=a_smem_load_layout.inner)
+        # (MMA, MMA_N, MMA_K, STAGE)
+        sB = storage.sB.get_tensor(b_smem_layout.outer, swizzle=b_smem_layout.inner)
+        sAIdx = None
+        if const_expr(self.gather_A):
+            a_idx_smem_dim = self.cta_tile_shape_mnk[0] if varlen_m else self.cta_tile_shape_mnk[2]
+            a_idx_smem_layout = cute.make_layout((a_idx_smem_dim, self.a_prefetch_stage))
+            sAIdx = storage.sAIdx.get_tensor(a_idx_smem_layout)
+        sSFA, sSFB = None, None
+        if const_expr(self.blockscaled):
+            # (MMA, MMA_M, MMA_K, STAGE)
+            sSFA = storage.sSFA.get_tensor(sfa_smem_layout)
+            # (MMA, MMA_N, MMA_K, STAGE)
+            sSFB = storage.sSFB.get_tensor(sfb_smem_layout)
+        sD = None
+        if const_expr(has_D):
+            # (EPI_TILE_M, EPI_TILE_N, STAGE)
+            sD = storage.sD.get_tensor(epi_smem_layout.outer, swizzle=epi_smem_layout.inner)
+        sC = None
+        if const_expr(has_C):
+            sC = storage.sC.get_tensor(epi_c_smem_layout.outer, swizzle=epi_c_smem_layout.inner)
+        epi_smem_tensors = self.epi_get_smem_tensors(epilogue_params, storage)
+
+        thr_mma = tiled_mma.get_slice(mma_tile_coord_v)
+        thr_mma_sfb = (
+            tiled_mma_sfb.get_slice(mma_tile_coord_v) if const_expr(self.blockscaled) else None
+        )
+
+        # (MMA, MMA_M, MMA_N)
+        acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2])
+        # (MMA, MMA_M, MMA_N, STAGE)
+        tCtAcc_fake = tiled_mma.make_fragment_C(
+            cute.append(acc_shape, self.num_acc_stage if not self.overlap_accum_sf else 2)
+        )
+
+        varlen_manager = VarlenManager.create(
+            varlen_params,
+            # Only used if not varlen_m
+            len_m_static=Int32(
+                cute.size(mA_mkl, mode=[0])
+                if varlen_k or varlen_params.mAIdx is None
+                else varlen_params.mAIdx.shape[0]
+            ),
+            len_k_static=Int32(cute.size(mA_mkl, mode=[1])),
+        )
+
+        TileSchedulerCls = partial(
+            TileSchedulerCls.create, tile_sched_params, sched_data, sched_pipeline
+        )
+
+        epi_load_barrier = None
+        if const_expr(has_epi_load):
+            epi_load_barrier = pipeline.NamedBarrier(
+                barrier_id=int(NamedBarrierGemm.EpilogueLoad),
+                num_threads=(self.num_ab_load_warps + 1) * cute.arch.WARP_SIZE,
+            )
+
+        # Cluster wait before tensor memory alloc
+        pipeline_init_wait(cluster_shape_mn=cluster_layout_vmnk)
+
+        # Specialized AB load warps
+        if (
+            warp_idx >= self.ab_load_warp_id
+            and warp_idx < self.ab_load_warp_id + self.num_ab_load_warps
+        ):
+            # PDL: wait for prior kernel before any TMA loads (matches cutlass C++ main_load)
+            if const_expr(self.use_pdl):
+                cute.arch.griddepcontrol_wait()
+            if const_expr(self.gather_A):
+                cute.arch.setmaxregister_decrease(self.num_regs_other)
+            # Compute multicast mask for A/B buffer full
+            block_in_cluster_coord_vmnk = cluster_layout_vmnk.get_flat_coord(cta_rank_in_cluster)
+            block_in_cluster_coord_sfb_vmnk = None
+            if const_expr(self.blockscaled):
+                block_in_cluster_coord_sfb_vmnk = cluster_layout_sfb_vmnk.get_flat_coord(
+                    cta_rank_in_cluster
+                )
+            a_mcast_mask, b_mcast_mask = None, None
+            sfa_mcast_mask, sfb_mcast_mask = None, None
+            if const_expr(self.is_a_mcast or self.is_b_mcast or use_2cta_instrs):
+                a_mcast_mask = cpasync.create_tma_multicast_mask(
+                    cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=2
+                )
+                b_mcast_mask = cpasync.create_tma_multicast_mask(
+                    cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=1
+                )
+                if const_expr(self.blockscaled):
+                    sfa_mcast_mask = cpasync.create_tma_multicast_mask(
+                        cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=2
+                    )
+                    sfb_mcast_mask = cpasync.create_tma_multicast_mask(
+                        cluster_layout_sfb_vmnk, block_in_cluster_coord_sfb_vmnk, mcast_mode=1
+                    )
+
+            # Persistent tile scheduling loop
+            tile_scheduler = TileSchedulerCls()
+            work_tile = tile_scheduler.initial_work_tile_info()
+            ab_producer_state = pipeline.make_pipeline_state(
+                pipeline.PipelineUserType.Producer, self.ab_stage
+            )
+            a_prefetch_consumer_state = pipeline.make_pipeline_state(
+                pipeline.PipelineUserType.Consumer, self.a_prefetch_stage
+            )
+            do_epi_load_barrier_arrive = Boolean(True)
+            while work_tile.is_valid_tile:
+                tile_coord_mnkl = work_tile.tile_idx
+                batch_idx = tile_coord_mnkl[3]
+                # Local_tile partition global tensors
+                mma_tile_coord_mnl = (
+                    tile_coord_mnkl[0] // cute.size(tiled_mma.thr_id.shape),
+                    tile_coord_mnkl[1],
+                    tile_coord_mnkl[3],
+                )
+                gA_mk = None
+                if const_expr(not self.gather_A):
+                    mA_mk = varlen_manager.offset_batch_A(mA_mkl, batch_idx)
+                    # (bM, bK, RestK)
+                    gA_mk = cute.local_tile(
+                        mA_mk,
+                        cute.select(self.mma_tiler, [0, 2]),
+                        (mma_tile_coord_mnl[0], None),
+                    )
+                # (bN, bK, RestK)
+                gB_nk = cute.local_tile(
+                    varlen_manager.offset_batch_B(mB_nkl, batch_idx),
+                    cute.select(self.mma_tiler, [1, 2]),
+                    (mma_tile_coord_mnl[1], None),
+                )
+                if const_expr(self.blockscaled):
+                    # (bM, bK)
+                    # SFA uses padded per-expert offset (dQaccum format), not
+                    # the A-data offset — allows varlen_m seqlens that aren't
+                    # multiples of 128.
+                    gSFA_mkl = cute.local_tile(
+                        varlen_manager.offset_batch_SFA(mSFA_mkl, batch_idx),
+                        cute.select(self.mma_tiler, [0, 2]),
+                        (mma_tile_coord_mnl[0], None),
+                    )
+                    # (bN, bK)
+                    # SFB uses padded per-expert K offset in varlen_k (dQaccum format).
+                    gSFB_nkl = cute.local_tile(
+                        varlen_manager.offset_batch_SFB(mSFB_nkl, batch_idx),
+                        cute.select(self.mma_tiler_sfb, [1, 2]),
+                        (
+                            (
+                                mma_tile_coord_mnl[1] // 2
+                                if self.cta_tile_shape_mnk[1] == 64
+                                else mma_tile_coord_mnl[1]
+                            ),
+                            None,
+                        ),
+                    )
+
+                # Partition global tensor for TiledMMA_A/B/D
+                # Then partition global/shared tensor for TMA load A/B
+                len_k = varlen_manager.len_k(batch_idx)
+                # TMA load A partition_S/D
+                a_cta_layout = cute.make_layout(
+                    cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape
+                )
+                copy_A, prefetch_A = None, None
+                if const_expr(not self.gather_A):
+                    # (MMA, MMA_M, MMA_K, RestK)
+                    tCgA = thr_mma.partition_A(gA_mk)
+                    copy_A, _, _ = copy_utils.tma_get_copy_fn(
+                        tma_atom_a,
+                        cta_coord=block_in_cluster_coord_vmnk[2],
+                        cta_layout=a_cta_layout,
+                        src_tensor=tCgA,
+                        dst_tensor=sA,
+                        mcast_mask=a_mcast_mask,
+                    )
+                else:
+                    # For varlen_m paths (TMA or cp.async): consume indices from
+                    # a_prefetch_pipeline once per work tile.
+                    sAIdx_stage = sAIdx
+                    if const_expr(varlen_m):
+                        a_prefetch_pipeline.consumer_wait(a_prefetch_consumer_state)
+                        sAIdx_stage = sAIdx[None, a_prefetch_consumer_state.index]
+                    copy_A, prefetch_A = self._make_gather_A_copy(
+                        mA_mkl,
+                        sA,
+                        sAIdx_stage,
+                        tma_atom_a,
+                        varlen_manager,
+                        tile_coord_mnkl,
+                        batch_idx,
+                        warp_idx,
+                    )
+                    if const_expr(varlen_m):
+                        cute.arch.sync_warp()
+                        with cute.arch.elect_one():
+                            a_prefetch_pipeline.consumer_release(a_prefetch_consumer_state)
+                        a_prefetch_consumer_state.advance()
+                    if const_expr(prefetch_A is not None):
+                        prefetch_A = partial(prefetch_A, a_prefetch_pipeline)
+                # (MMA, MMA_N, MMA_K, RestK)
+                tCgB = thr_mma.partition_B(gB_nk)
+                if const_expr(self.blockscaled):
+                    # (MMA, MMA_M, MMA_K)
+                    tCgSFA = thr_mma.partition_A(gSFA_mkl)
+                    # (MMA, MMA_N, MMA_K)
+                    tCgSFB = thr_mma_sfb.partition_B(gSFB_nkl)
+                # TMA load B partition_S/D
+                copy_B, _, _ = copy_utils.tma_get_copy_fn(
+                    tma_atom_b,
+                    cta_coord=block_in_cluster_coord_vmnk[1],
+                    cta_layout=cute.make_layout(
+                        cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape
+                    ),
+                    src_tensor=tCgB,
+                    dst_tensor=sB,
+                    mcast_mask=b_mcast_mask,
+                )
+                copy_SFA, copy_SFB = None, None
+                if const_expr(self.blockscaled):
+                    #  TMA load SFA partition_S/D
+                    copy_SFA, _, _ = copy_utils.tma_get_copy_fn(
+                        tma_atom_sfa,
+                        cta_coord=block_in_cluster_coord_vmnk[2],
+                        cta_layout=a_cta_layout,
+                        src_tensor=tCgSFA,
+                        dst_tensor=sSFA,
+                        filter_zeros=True,
+                        mcast_mask=sfa_mcast_mask,
+                    )
+                    # TMA load SFB partition_S/D
+                    sfb_cta_layout = cute.make_layout(
+                        cute.slice_(cluster_layout_sfb_vmnk, (0, None, 0, 0)).shape
+                    )
+                    copy_SFB, _, _ = copy_utils.tma_get_copy_fn(
+                        tma_atom_sfb,
+                        cta_coord=block_in_cluster_coord_sfb_vmnk[1],
+                        cta_layout=sfb_cta_layout,
+                        src_tensor=tCgSFB,
+                        dst_tensor=sSFB,
+                        filter_zeros=True,
+                        mcast_mask=sfb_mcast_mask,
+                    )
+                k_tile_cnt = cute.ceil_div(len_k, self.cta_tile_shape_mnk[2])
+                tctx.b("tma_load")
+                if const_expr(not self.gather_A):
+                    ab_producer_state = self.load_tma(
+                        ab_pipeline,
+                        ab_producer_state,
+                        [copy_A, copy_B, copy_SFA, copy_SFB],
+                        k_tile_cnt,
+                    )
+                elif const_expr(self.use_tma_gather):
+                    ab_producer_state, a_prefetch_consumer_state = self.load_AB_tma_gather(
+                        ab_pipeline,
+                        ab_producer_state,
+                        a_prefetch_consumer_state,
+                        copy_A,
+                        prefetch_A,
+                        copy_B,
+                        k_tile_cnt,
+                    )
+                else:
+                    ab_producer_state, a_prefetch_consumer_state = self.load_AB_gather_A(
+                        ab_pipeline,
+                        ab_producer_state,
+                        a_prefetch_consumer_state,
+                        copy_A,
+                        prefetch_A,
+                        copy_B,
+                        k_tile_cnt,
+                    )
+                tctx.e("tma_load")
+                if const_expr(epi_load_barrier is not None):
+                    # In the first work tile, the epi load warp will wait for the signal
+                    # from the mainloop load warp to start loading C, to avoid interfering
+                    # with loading A and B.
+                    if do_epi_load_barrier_arrive:
+                        epi_load_barrier.arrive()
+                        do_epi_load_barrier_arrive = Boolean(False)
+                # Advance to next tile
+                tile_scheduler.advance_to_next_work()
+                work_tile = tile_scheduler.get_current_work()
+            # Wait A/B buffer empty
+            if warp_idx == self.ab_load_warp_id:
+                ab_pipeline.producer_tail(ab_producer_state)
+
+        # Specialized scheduler warp
+        if const_expr(self.is_persistent or self.gather_A):
+            if warp_idx == self.scheduler_warp_id:
+                # PDL: wait for prior kernel before reading CLC state (matches cutlass C++ sched)
+                if const_expr(self.use_pdl):
+                    cute.arch.griddepcontrol_wait()
+                if const_expr(self.gather_A):
+                    cute.arch.setmaxregister_decrease(self.num_regs_other)
+                is_scheduler_warp = True
+                if const_expr(cute.size(cluster_layout_vmnk) > 1):
+                    is_scheduler_warp = cute.arch.block_idx_in_cluster() == 0
+                # Persistent tile scheduling loop
+                tile_scheduler = TileSchedulerCls(is_scheduler_warp=is_scheduler_warp)
+                work_tile = tile_scheduler.initial_work_tile_info()
+                while work_tile.is_valid_tile:
+                    # Advance to next tile
+                    tile_scheduler.advance_to_next_work(is_scheduler_warp=is_scheduler_warp)
+                    work_tile = tile_scheduler.get_current_work()
+                    # End of persistent scheduler loop
+                if is_scheduler_warp:
+                    tile_scheduler.producer_tail()
+
+        # Specialized A-index prefetch warp (gather_A only)
+        if const_expr(self.gather_A):
+            if warp_idx == self.a_prefetch_warp_id:
+                cute.arch.setmaxregister_decrease(self.num_regs_other)
+                tile_M = self.cta_tile_shape_mnk[0]
+                tile_K = self.cta_tile_shape_mnk[2]
+                tiled_copy_AIdx = copy_utils.tiled_copy_1d(Int32, num_threads=32, is_async=True)
+                thr_copy_AIdx = tiled_copy_AIdx.get_slice(cute.arch.lane_idx())
+                tAsAIdx = thr_copy_AIdx.partition_D(sAIdx)
+                tAcAIdx = thr_copy_AIdx.partition_S(
+                    cute.make_identity_tensor(tile_M if varlen_m else tile_K)
+                )
+                # Persistent tile scheduling loop
+                tile_scheduler = TileSchedulerCls()
+                work_tile = tile_scheduler.initial_work_tile_info()
+                a_prefetch_producer_state = pipeline.make_pipeline_state(
+                    pipeline.PipelineUserType.Producer, self.a_prefetch_stage
+                )
+                while work_tile.is_valid_tile:
+                    tile_coord_mnkl = work_tile.tile_idx
+                    batch_idx = tile_coord_mnkl[3]
+                    mAIdx_mk = varlen_manager.offset_batch_AIdx(batch_idx)
+                    if const_expr(varlen_m):
+                        # (tile_M,)
+                        gAIdx = cute.local_tile(mAIdx_mk, (tile_M,), (tile_coord_mnkl[0],))
+                        tAgAIdx = thr_copy_AIdx.partition_S(gAIdx)
+                        len_m = varlen_manager.len_m(batch_idx)
+                        m_limit = len_m - tile_coord_mnkl[0] * tile_M
+                        tApAIdx_m = cute.make_rmem_tensor((1, tAsAIdx.shape[1]), Boolean)
+                        for m in cutlass.range(tAsAIdx.shape[1], unroll_full=True):
+                            tApAIdx_m[0, m] = tAcAIdx[0, m] < m_limit
+                        a_prefetch_pipeline.producer_acquire(a_prefetch_producer_state)
+                        cute.copy(
+                            thr_copy_AIdx,
+                            tAgAIdx,
+                            tAsAIdx[None, None, a_prefetch_producer_state.index],
+                            pred=tApAIdx_m,
+                        )
+                        a_prefetch_pipeline.producer_commit(a_prefetch_producer_state)
+                        a_prefetch_producer_state.advance()
+                    else:
+                        # (tile_K, RestK)
+                        gAIdx = cute.flat_divide(mAIdx_mk, (tile_K,))
+                        tAgAIdx = thr_copy_AIdx.partition_S(gAIdx)
+                        len_k = varlen_manager.len_k(batch_idx)
+                        k_tile_cnt = cute.ceil_div(len_k, tile_K)
+                        for k_tile in cutlass.range(k_tile_cnt - 1, unroll=1):
+                            a_prefetch_pipeline.producer_acquire(a_prefetch_producer_state)
+                            cute.copy(
+                                thr_copy_AIdx,
+                                tAgAIdx[None, None, k_tile],
+                                tAsAIdx[None, None, a_prefetch_producer_state.index],
+                            )
+                            a_prefetch_pipeline.producer_commit(a_prefetch_producer_state)
+                            a_prefetch_producer_state.advance()
+                        if 0 < k_tile_cnt:
+                            k_tile = k_tile_cnt - 1
+                            k_limit = len_k - k_tile * tile_K
+                            tApAIdx_k = cute.make_rmem_tensor((1, tAsAIdx.shape[1]), Boolean)
+                            for m in cutlass.range(tAsAIdx.shape[1], unroll_full=True):
+                                tApAIdx_k[0, m] = tAcAIdx[0, m] < k_limit
+                            a_prefetch_pipeline.producer_acquire(a_prefetch_producer_state)
+                            cute.copy(
+                                tiled_copy_AIdx,
+                                tAgAIdx[None, None, k_tile],
+                                tAsAIdx[None, None, a_prefetch_producer_state.index],
+                                pred=tApAIdx_k,
+                            )
+                            a_prefetch_pipeline.producer_commit(a_prefetch_producer_state)
+                            a_prefetch_producer_state.advance()
+                    # Advance to next tile
+                    tile_scheduler.advance_to_next_work()
+                    work_tile = tile_scheduler.get_current_work()
+
+        # Specialized TMA epi load warp
+        if warp_idx == self.epi_load_warp_id:
+            if const_expr(self.gather_A):
+                cute.arch.setmaxregister_decrease(self.num_regs_other)
+            # PDL: wait for prior kernel before any C TMA loads (matches cutlass C++ epi_load)
+            if const_expr(self.use_pdl and has_epi_load):
+                cute.arch.griddepcontrol_wait()
+            if const_expr(has_epi_load):
+                epi_producer_state = pipeline.make_pipeline_state(
+                    pipeline.PipelineUserType.Producer, self.epi_c_stage
+                )
+                do_epi_load_barrier_wait = Boolean(True)
+                # Persistent tile scheduling loop
+                tile_scheduler = TileSchedulerCls()
+                work_tile = tile_scheduler.initial_work_tile_info()
+                while work_tile.is_valid_tile:
+                    # Get tile coord from tile scheduler
+                    tile_coord_mnkl = work_tile.tile_idx
+                    batch_idx = tile_coord_mnkl[3]
+                    copy_C = None
+                    if const_expr(has_C):
+                        copy_C_fn, _, _ = self.epilog_gmem_copy_and_partition(
+                            tma_atom_c,
+                            varlen_manager.offset_batch_epi(mC_mnl, batch_idx),
+                            self.cta_tile_shape_mnk[:2],
+                            epi_tile,
+                            sC,
+                            tile_coord_mnkl,
+                        )
+                        copy_C = copy_utils.tma_producer_copy_fn(copy_C_fn, epi_pipeline)
+                    tile_load_copy_fns = self.epi_tile_load_g2s_copy_fns(
+                        epilogue_params,
+                        epi_smem_tensors,
+                        tile_coord_mnkl,
+                        varlen_manager,
+                        epi_pipeline,
+                    )
+                    copy_epi_load = copy_utils.chain_tma_producer_copy_fns(
+                        (copy_C, *tile_load_copy_fns)
+                    )
+                    if do_epi_load_barrier_wait:
+                        epi_load_barrier.arrive_and_wait()
+                        do_epi_load_barrier_wait = Boolean(False)
+                    epi_tile_num = const_expr(
+                        cute.size(
+                            cute.zipped_divide(
+                                cute.make_layout(self.cta_tile_shape_mnk[:2]), epi_tile
+                            ),
+                            mode=[1],
+                        )
+                    )
+                    for epi_idx in cutlass.range(epi_tile_num, unroll=1):
+                        epi_pipeline.producer_acquire(epi_producer_state)
+                        copy_epi_load(src_idx=epi_idx, producer_state=epi_producer_state)
+                        # Epi pipeline's producer commit is a NOP
+                        epi_pipeline.producer_commit(epi_producer_state)
+                        epi_producer_state.advance()
+                    # Advance to next tile
+                    tile_scheduler.advance_to_next_work()
+                    work_tile = tile_scheduler.get_current_work()
+                    # End of persistent scheduler loop
+                epi_pipeline.producer_tail(epi_producer_state)
+
+        # Specialized MMA warp
+        if warp_idx == self.mma_warp_id:
+            if const_expr(self.gather_A):
+                cute.arch.setmaxregister_decrease(self.num_regs_other)
+            # Retrieving tensor memory ptr and make accumulator tensor
+            tmem.wait_for_alloc()
+            acc_tmem_ptr = tmem.retrieve_ptr(self.acc_dtype)
+            # Partition shared/tensor memory tensor for TiledMMA_A/B/D
+            # (MMA, MMA_M, MMA_K, STAGE)
+            tCrA = tiled_mma.make_fragment_A(sA_mma)
+            # (MMA, MMA_N, MMA_K, STAGE)
+            tCrB = tiled_mma.make_fragment_B(sB)
+            # (MMA, MMA_M, MMA_N, STAGE)
+            tCtAcc_base = cute.make_tensor(acc_tmem_ptr, tCtAcc_fake.layout)
+
+            if const_expr(self.blockscaled):
+                # Make SFA tmem tensor
+                acc_tmem_col_offset = const_expr(
+                    tcgen05.find_tmem_tensor_col_offset(
+                        tCtAcc_base
+                        if const_expr(not self.overlap_accum_sf)
+                        else tCtAcc_base[None, None, None, 0]
+                    )
+                )
+                sfa_tmem_ptr = cute.recast_ptr(
+                    acc_tmem_ptr + acc_tmem_col_offset, dtype=self.sf_dtype
+                )
+                # (MMA, MMA_M, MMA_K)
+                tCtSFA_layout = blockscaled_utils.make_tmem_layout_sfa(
+                    tiled_mma,
+                    self.mma_tiler,
+                    self.sf_vec_size,
+                    cute.slice_(sfa_smem_layout, (None, None, None, 0)),
+                )
+                tCtSFA = cute.make_tensor(sfa_tmem_ptr, tCtSFA_layout)
+                # Make SFB tmem tensor
+                sfa_tmem_col_offset = tcgen05.find_tmem_tensor_col_offset(tCtSFA)
+                sfb_tmem_col_offset = acc_tmem_col_offset + sfa_tmem_col_offset
+                sfb_tmem_base_ptr = acc_tmem_ptr + sfb_tmem_col_offset
+                sfb_tmem_ptr = cute.recast_ptr(sfb_tmem_base_ptr, dtype=self.sf_dtype)
+                # (MMA, MMA_N, MMA_K)
+                tCtSFB_layout = blockscaled_utils.make_tmem_layout_sfb(
+                    tiled_mma,
+                    self.mma_tiler,
+                    self.sf_vec_size,
+                    cute.slice_(sfb_smem_layout, (None, None, None, 0)),
+                )
+                tCtSFB = cute.make_tensor(sfb_tmem_ptr, tCtSFB_layout)
+            else:
+                tCtSFA, tCtSFB = None, None
+
+            # Persistent tile scheduling loop
+            tile_scheduler = TileSchedulerCls()
+            work_tile = tile_scheduler.initial_work_tile_info()
+            ab_consumer_state = pipeline.make_pipeline_state(
+                pipeline.PipelineUserType.Consumer, self.ab_stage
+            )
+            acc_producer_state = pipeline.make_pipeline_state(
+                pipeline.PipelineUserType.Producer, self.num_acc_stage
+            )
+            while work_tile.is_valid_tile:
+                # Get tile coord from tile scheduler
+                tile_coord_mnkl = work_tile.tile_idx
+                batch_idx = tile_coord_mnkl[3]
+                k_len = varlen_manager.len_k(batch_idx)
+                k_tile_cnt = cute.ceil_div(k_len, self.mma_tiler[2])
+                # Set tensor memory buffer for current tile
+                # (MMA, MMA_M, MMA_N)
+                acc_stage_idx = (
+                    acc_producer_state.phase ^ 1
+                    if const_expr(self.overlap_accum_sf)
+                    else acc_producer_state.index
+                )
+                tCtAcc = tCtAcc_base[None, None, None, acc_stage_idx]
+                tCtSFB_mma = tCtSFB
+                if const_expr(self.blockscaled and self.mma_inst_shape_mnk[1] in (64, 192)):
+                    tCtSFB_mma = cute.make_tensor(
+                        cute.recast_ptr(
+                            sfb_tmem_base_ptr + Int32((tile_coord_mnkl[1] % 2) * 2),
+                            dtype=self.sf_dtype,
+                        ),
+                        tCtSFB.layout,
+                    )
+                copy_s2t_sfa, copy_s2t_sfb = None, None
+                if const_expr(self.blockscaled):
+                    copy_s2t_sfa = copy_utils.s2t_get_copy_fn(sSFA, tCtSFA, self.cta_group)
+                    copy_s2t_sfb = copy_utils.s2t_get_copy_fn(sSFB, tCtSFB, self.cta_group)
+                tctx.b("mma")
+                ab_consumer_state, acc_producer_state, tiled_mma = self.mma(
+                    ab_pipeline,
+                    acc_pipeline,
+                    ab_consumer_state,
+                    acc_producer_state,
+                    tiled_mma,
+                    tCrA,
+                    tCrB,
+                    tCtAcc,
+                    k_tile_cnt,
+                    is_leader_cta,
+                    cta_rank_in_cluster,
+                    tCtSFA,
+                    tCtSFB_mma,
+                    copy_s2t_sfa,
+                    copy_s2t_sfb,
+                )
+                if const_expr(self.overlap_accum_sf):
+                    # After iter 0, 2, ..., shift tmem ptr by -256.
+                    # After iter 1, 3, ..., shift tmem ptr by 256.
+                    tCtSFA, tCtSFB = [
+                        cute.make_tensor(
+                            cute.recast_ptr(
+                                # Doing tmem ptr arithmetic requires 32-bit type, wrong otherwise
+                                cute.recast_ptr(mT.iterator, dtype=Float32)
+                                + cute.assume(
+                                    acc_tmem_col_offset * (acc_producer_state.phase * 2 - 1),
+                                    divby=acc_tmem_col_offset,
+                                ),
+                                dtype=self.sf_dtype,
+                            ),
+                            mT.layout,
+                        )
+                        for mT in [tCtSFA, tCtSFB]
+                    ]
+                tctx.e("mma")
+                # Advance to next tile
+                tile_scheduler.advance_to_next_work()
+                work_tile = tile_scheduler.get_current_work()
+
+            # PDL: hint the next kernel to launch early now that all MMAs are issued
+            if const_expr(self.use_pdl):
+                cute.arch.griddepcontrol_launch_dependents()
+
+            tmem_alloc_barrier.arrive()
+            # Wait for accumulator buffer empty
+            acc_pipeline.producer_tail(acc_producer_state)
+
+        #
+        # Specialized epilogue warps
+        #
+        if warp_idx < self.mma_warp_id:
+            if const_expr(self.gather_A):
+                cute.arch.setmaxregister_increase(self.num_regs_epi)
+            # Alloc tensor memory buffer
+            tmem.allocate(self.num_tmem_alloc_cols)
+            tmem.wait_for_alloc()
+
+            is_tma_warp = Boolean(warp_idx == self.epilog_warp_id[0])
+
+            # Retrieving tensor memory ptr and make accumulator tensor
+            acc_tmem_ptr = tmem.retrieve_ptr(self.acc_dtype)
+            # (MMA, MMA_M, MMA_N, STAGE)
+            tCtAcc_base = cute.make_tensor(acc_tmem_ptr, tCtAcc_fake.layout)
+
+            # Partition for epilogue
+            epi_tidx = tidx
+            tiled_copy_t2r, tTR_tAcc_base, tTR_rAcc = self.epilog_tmem_copy_and_partition(
+                epi_tidx, tCtAcc_base, epi_tile, use_2cta_instrs
+            )
+
+            tTR_rD = cute.make_rmem_tensor(tTR_rAcc.shape, self.acc_dtype)
+            tiled_copy_r2s, tRS_rD, tRS_sD = self.epilog_smem_store_and_partition(
+                tiled_copy_t2r, self.d_layout, self.d_dtype, tTR_rD, sD, epi_tidx
+            )
+            tRS_rC, tSR_rC, tSR_sC = None, None, None
+            tiled_copy_s2r = None
+            if const_expr(mC_mnl is not None):
+                tiled_copy_s2r, tRS_rC, tSR_rC, tSR_sC = self.epilog_smem_load_and_partition(
+                    tiled_copy_t2r, self.c_layout, self.c_dtype, sC, tRS_rD.layout, epi_tidx
+                )
+
+            # Persistent tile scheduling loop
+            tile_scheduler = TileSchedulerCls()
+            work_tile = tile_scheduler.initial_work_tile_info()
+            acc_consumer_state = pipeline.make_pipeline_state(
+                pipeline.PipelineUserType.Consumer, self.num_acc_stage
+            )
+            epi_store_pipeline = self.make_epi_store_pipeline()
+            epi_read_state = pipeline.make_pipeline_state(
+                pipeline.PipelineUserType.Consumer, self.epi_c_stage
+            )
+            while work_tile.is_valid_tile:
+                # Get tile coord from tile scheduler
+                tile_coord_mnkl = work_tile.tile_idx
+                batch_idx = tile_coord_mnkl[3]
+                # Set tensor memory buffer for current tile
+                # (T2R, T2R_M, T2R_N, EPI_M, EPI_M)
+                epi_acc_stage = (
+                    acc_consumer_state.index
+                    if const_expr(not self.overlap_accum_sf)
+                    else acc_consumer_state.phase
+                )
+                tTR_tAcc = tTR_tAcc_base[None, None, None, None, None, epi_acc_stage]
+                # Wait for accumulator buffer full
+                acc_pipeline.consumer_wait(acc_consumer_state)
+
+                copy_D = None
+                if const_expr(has_D):
+                    copy_D, _, _ = self.epilog_gmem_copy_and_partition(
+                        tma_atom_d,
+                        varlen_manager.offset_batch_epi(mD_mnl, batch_idx),
+                        self.cta_tile_shape_mnk[:2],
+                        epi_tile,
+                        sD,
+                        tile_coord_mnkl,
+                    )
+                copy_C = None  # We're using a separate warp to load C
+
+                tTR_tAcc = cute.group_modes(tTR_tAcc, 3, cute.rank(tTR_tAcc))
+                k_len = varlen_manager.len_k(batch_idx)
+                epi_tile_num = cute.size(
+                    cute.zipped_divide(cute.make_layout(self.cta_tile_shape_mnk[:2]), epi_tile),
+                    mode=[1],
+                )
+                load_acc_subtile = partial(
+                    self.epi_load_acc_subtile,
+                    tiled_copy_t2r,
+                    tiled_copy_r2s,
+                    tTR_tAcc,
+                    tTR_rAcc,
+                    acc_pipeline=acc_pipeline,
+                    acc_consumer_state=acc_consumer_state,
+                    acc_release_idx=self.iter_acc_early_release
+                    if const_expr(self.overlap_accum_sf)
+                    else epi_tile_num - 1,
+                    clear_acc=(varlen_k and k_len == 0),
+                )
+
+                tctx.b("epilogue")
+                epi_read_state, _ = self.epilogue(
+                    epilogue_params,
+                    epi_smem_tensors,
+                    epi_pipeline,
+                    epi_store_pipeline,
+                    epi_read_state,
+                    None,  # epi_producer_state
+                    epi_tile,
+                    load_acc_subtile,
+                    tRS_rD,
+                    tRS_rC,
+                    tiled_copy_t2r,
+                    tiled_copy_r2s,
+                    tRS_sD,
+                    tiled_copy_s2r,
+                    tSR_rC,
+                    tSR_sC,
+                    copy_D,
+                    copy_C,
+                    tile_coord_mnkl,
+                    varlen_manager,
+                    self.epilogue_barrier,
+                    tile_scheduler,
+                    epi_tidx,
+                    is_tma_warp,
+                )
+                # acc_pipeline.consumer_release was already called in self.epi_load_acc_subtile
+                acc_consumer_state.advance()
+                tctx.e("epilogue")
+
+                # Advance to next tile
+                tile_scheduler.advance_to_next_work()
+                work_tile = tile_scheduler.get_current_work()
+
+            # Wait for D store complete
+            if is_tma_warp:
+                epi_store_pipeline.producer_tail()
+
+            # Dealloc the tensor memory buffer
+            tmem.relinquish_alloc_permit()
+            tmem_alloc_barrier.arrive_and_wait()
+            tmem.free(acc_tmem_ptr)
+
+        tctx.flush()
+
+    @cute.jit
+    def _make_gather_A_copy(
+        self,
+        mA_mkl: cute.Tensor,
+        sA: cute.Tensor,
+        sAIdx: cute.Tensor,  # if varlen, this is already sliced into the current prefetch stage
+        tma_atom_a: Optional[cute.CopyAtom],
+        varlen_manager: VarlenManager,
+        tile_coord_mnkl,
+        batch_idx: Int32,
+        warp_idx: Int32,
+    ):
+        """Create copy_A and prefetch_A for gather_A (cp.async and TMA gather paths).
+        sAIdx: sAIdx sliced to the current prefetch stage (for varlen_m paths).
+        For varlen_k TMA gather, sAIdx (full) is used instead.
+        """
+        varlen_m = varlen_manager.varlen_m
+        varlen_k = varlen_manager.varlen_k
+        if const_expr(varlen_m):
+            mA_mk = mA_mkl
+        else:
+            mA_mk = cute.local_tile(
+                mA_mkl, (self.cta_tile_shape_mnk[0],), (tile_coord_mnkl[0], None)
+            )
+        len_m = varlen_manager.len_m(batch_idx)
+        len_k = varlen_manager.len_k(batch_idx)
+        num_cta = 2 if self.use_2cta_instrs else 1
+        dma_warp_idx = warp_idx - self.ab_load_warp_id
+        dma_tidx = cute.arch.thread_idx()[0] - self.ab_load_warp_id * 32
+        copy_A, prefetch_A = None, None
+        if const_expr(self.use_tma_gather):
+            if const_expr(varlen_m):
+                copy_A = copy_utils.gather_m_get_tma_copy_fn(
+                    tma_atom_a,
+                    mA_mk,
+                    sA,
+                    sAIdx,
+                    dma_warp_idx,
+                    num_warps=self.num_ab_load_warps,
+                    num_cta=num_cta,
+                )
+            elif const_expr(varlen_k):
+                col_idx = Int32(tile_coord_mnkl[0] * self.cta_tile_shape_mnk[0])
+                copy_A, prefetch_A = copy_utils.gather_k_get_tma_copy_fn(
+                    tma_atom_a,
+                    sA,
+                    sAIdx,
+                    col_idx,
+                    dma_warp_idx,
+                    num_warps=self.num_ab_load_warps,
+                    num_cta=num_cta,
+                )
+        else:
+            # cp.async path
+            tiled_copy_A = self._make_gmem_tiled_copy_A(
+                self.a_dtype, self.a_layout, self.num_ab_load_warps * 32
+            )
+            thr_copy_A = tiled_copy_A.get_slice(dma_tidx)
+            if const_expr(varlen_m):
+                copy_A = copy_utils.gather_m_get_copy_fn(
+                    thr_copy_A,
+                    mA_mk,
+                    sA,
+                    sAIdx,
+                    limit_m=len_m - tile_coord_mnkl[0] * self.cta_tile_shape_mnk[0],
+                    limit_k=len_k,
+                )
+            else:
+                copy_A, prefetch_A = copy_utils.gather_k_get_copy_fn(
+                    thr_copy_A,
+                    mA_mk,
+                    sA,
+                    sAIdx,
+                    limit_m=len_m - tile_coord_mnkl[0] * self.cta_tile_shape_mnk[0],
+                    limit_k=len_k,
+                )
+        return copy_A, prefetch_A
+
+    @cute.jit
+    def load_AB_gather_A(
+        self,
+        ab_pipeline: cutlass.pipeline.PipelineAsync,
+        ab_producer_state: cutlass.pipeline.PipelineState,
+        a_prefetch_consumer_state: Optional[cutlass.pipeline.PipelineState],
+        copy_A: Callable,
+        prefetch_A: Optional[Callable],
+        copy_B: Callable,
+        k_tile_cnt: Int32,
+        varlen_m: bool = True,
+    ) -> Tuple[cutlass.pipeline.PipelineState, Optional[cutlass.pipeline.PipelineState]]:
+        warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
+        # Peek (try_wait) AB buffer empty for k_block = prefetch_k_tile_cnt
+        peek_ab_empty_status = Boolean(True)
+        if 0 < k_tile_cnt:
+            peek_ab_empty_status = ab_pipeline.producer_try_acquire(ab_producer_state)
+        # TMA load on B and cp.async on A
+        for k_tile in cutlass.range(k_tile_cnt - 1, unroll=2 if const_expr(varlen_m) else 1):
+            smem_idx = ab_producer_state.index
+            prefetch_out = ()
+            if const_expr(prefetch_A is not None):  # Prefetch early, even before smem is free
+                prefetch_out = (prefetch_A(k_tile, smem_idx, a_prefetch_consumer_state),)
+                a_prefetch_consumer_state.advance()
+            # Wait for A/B buffers to be empty before loading into them
+            # Also sets the transaction barrier for the A/B buffers
+            # A tiny bit faster to rotate the warp that does TMA
+            is_tma_warp = warp_idx == self.ab_load_warp_id + (k_tile % self.num_ab_load_warps)
+            ab_pipeline.producer_acquire(ab_producer_state, peek_ab_empty_status, is_tma_warp)
+            # A bit faster to load B first while we calculate the indices for A
+            tma_bar_ptr = ab_pipeline.producer_get_barrier(ab_producer_state)
+            if is_tma_warp:
+                copy_B(k_tile, smem_idx, tma_bar_ptr=tma_bar_ptr)
+            copy_A(k_tile, smem_idx, *prefetch_out)
+            # This tells mbarrier to track the completion of cp.async
+            ab_pipeline.producer_cpasync_commit(ab_producer_state)
+            ab_producer_state.advance()
+            peek_ab_empty_status = Boolean(True)
+            if k_tile + 1 < k_tile_cnt:
+                peek_ab_empty_status = ab_pipeline.producer_try_acquire(ab_producer_state)
+        # bound checking in the K dimension on the last k_tile
+        if 0 < k_tile_cnt:
+            k_tile = k_tile_cnt - 1
+            smem_idx = ab_producer_state.index
+            prefetch_out = ()
+            if const_expr(prefetch_A is not None):  # Prefetch early, even before smem is free
+                prefetch_out = (prefetch_A(k_tile, smem_idx, a_prefetch_consumer_state, pred=True),)
+                a_prefetch_consumer_state.advance()
+            is_tma_warp = warp_idx == self.ab_load_warp_id + k_tile % self.num_ab_load_warps
+            ab_pipeline.producer_acquire(ab_producer_state, peek_ab_empty_status, is_tma_warp)
+            tma_bar_ptr = ab_pipeline.producer_get_barrier(ab_producer_state)
+            if is_tma_warp:
+                copy_B(k_tile, smem_idx, tma_bar_ptr=tma_bar_ptr)
+            copy_A(k_tile, smem_idx, *prefetch_out, pred=True)
+            ab_pipeline.producer_cpasync_commit(ab_producer_state)
+            ab_producer_state.advance()
+        return ab_producer_state, a_prefetch_consumer_state
+
+    @cute.jit
+    def load_AB_tma_gather(
+        self,
+        ab_pipeline: cutlass.pipeline.PipelineAsync,
+        ab_producer_state: cutlass.pipeline.PipelineState,
+        a_prefetch_consumer_state: Optional[cutlass.pipeline.PipelineState],
+        copy_A: Callable,
+        prefetch_A: Optional[Callable],
+        copy_B: Callable,
+        k_tile_cnt: Int32,
+    ) -> Tuple[cutlass.pipeline.PipelineState, Optional[cutlass.pipeline.PipelineState]]:
+        """Unified TMA gather loading loop for both varlen_m and varlen_k.
+
+        For varlen_m: a_prefetch_pipeline is None, copy_A receives k_tile as src_idx.
+        For varlen_k: a_prefetch_pipeline is set, copy_A receives the prefetch stage index,
+          and indices are consumed/released per K-tile.
+        """
+        warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
+        peek_ab_empty_status = Boolean(True)
+        if 0 < k_tile_cnt:
+            peek_ab_empty_status = ab_pipeline.producer_try_acquire(ab_producer_state)
+        for k_tile in cutlass.range(k_tile_cnt, unroll=1):
+            smem_idx = ab_producer_state.index
+            prefetch_out = ()
+            if const_expr(prefetch_A is not None):  # Prefetch early, even before smem is free
+                prefetch_out = (prefetch_A(k_tile, smem_idx, a_prefetch_consumer_state),)
+                a_prefetch_consumer_state.advance()
+            is_tma_warp = warp_idx == self.ab_load_warp_id + (k_tile % self.num_ab_load_warps)
+            ab_pipeline.producer_acquire(ab_producer_state, peek_ab_empty_status, is_tma_warp)
+            tma_bar_ptr = ab_pipeline.producer_get_barrier(ab_producer_state)
+            if is_tma_warp:
+                copy_B(k_tile, smem_idx, tma_bar_ptr=tma_bar_ptr)
+            copy_A(k_tile, smem_idx, *prefetch_out, tma_bar_ptr=tma_bar_ptr)
+            ab_pipeline.producer_commit(ab_producer_state)
+            ab_producer_state.advance()
+            peek_ab_empty_status = Boolean(True)
+            if k_tile + 1 < k_tile_cnt:
+                peek_ab_empty_status = ab_pipeline.producer_try_acquire(ab_producer_state)
+        return ab_producer_state, a_prefetch_consumer_state
+
+    @cute.jit
+    def mma(
+        self,
+        ab_pipeline: cutlass.pipeline.PipelineAsync,
+        acc_pipeline: cutlass.pipeline.PipelineAsync,
+        ab_consumer_state: cutlass.pipeline.PipelineState,
+        acc_producer_state: cutlass.pipeline.PipelineState,
+        tiled_mma: cute.TiledMma,
+        tCrA: cute.Tensor,
+        tCrB: cute.Tensor,
+        acc: cute.Tensor,
+        k_tile_cnt: Int32,
+        is_leader_cta: Boolean,
+        cta_rank_in_cluster: Int32,
+        tCtSFA: Optional[cute.Tensor] = None,
+        tCtSFB: Optional[cute.Tensor] = None,
+        copy_s2t_sfa: Optional[Callable] = None,
+        copy_s2t_sfb: Optional[Callable] = None,
+    ) -> Tuple[cutlass.pipeline.PipelineState, cutlass.pipeline.PipelineState, cute.TiledMma]:
+        blockscaled = const_expr(copy_s2t_sfa is not None)
+        if const_expr(blockscaled):
+            assert all(x is not None for x in (tCtSFA, tCtSFB))
+            assert copy_s2t_sfb is not None
+        # If gather_A and use_2cta_instrs, the cp.async for the non-leader CTA will
+        # arrive at an mbarrier on the non-leader CTA side, then the mma warp of the non-leader
+        # CTA will wait for that then arrive at the mbarrier on the leader CTA.
+        need_nonleader_cta = const_expr(
+            self.gather_A and self.use_2cta_instrs and not self.use_tma_gather
+        )
+        # Peek (try_wait) AB buffer full for k_tile = 0
+        peek_ab_full_status = Boolean(True)
+        if 0 < k_tile_cnt and (is_leader_cta or need_nonleader_cta):
+            peek_ab_full_status = ab_pipeline.consumer_try_wait(ab_consumer_state)
+        # Wait for accumulator buffer empty
+        if is_leader_cta:
+            acc_pipeline.producer_acquire(acc_producer_state)
+        # Reset the ACCUMULATE field for each tile
+        tiled_mma.set(tcgen05.Field.ACCUMULATE, False)
+        # Mma mainloop
+        num_k_blocks = cute.size(tCrA, mode=[2])
+        for k_tile in cutlass.range(k_tile_cnt, unroll=1):
+            if const_expr(need_nonleader_cta):
+                if not is_leader_cta:
+                    ab_pipeline.consumer_wait(ab_consumer_state, peek_ab_full_status)
+                    with cute.arch.elect_one():
+                        # The odd CTA signals the even CTA
+                        ab_pipeline.sync_object_full.arrive_mbarrier(
+                            ab_consumer_state.index, dst_rank=cta_rank_in_cluster & 0xFE
+                        )
+            if is_leader_cta:
+                # Conditionally wait for AB buffer full
+                ab_pipeline.consumer_wait(ab_consumer_state, peek_ab_full_status)
+                #  Copy SFA/SFB from smem to tmem
+                if const_expr(blockscaled):
+                    copy_s2t_sfa(ab_consumer_state.index)
+                    copy_s2t_sfb(ab_consumer_state.index)
+                for k_blk_idx in cutlass.range(num_k_blocks, unroll_full=True):
+                    k_blk_coord = (None, None, k_blk_idx, ab_consumer_state.index)
+                    if const_expr(blockscaled):
+                        # Set SFA/SFB tensor to tiled_mma
+                        sf_kblock_coord = (None, None, k_blk_idx)
+                        tiled_mma.set(tcgen05.Field.SFA, tCtSFA[sf_kblock_coord].iterator)
+                        tiled_mma.set(tcgen05.Field.SFB, tCtSFB[sf_kblock_coord].iterator)
+                    cute.gemm(tiled_mma, acc, tCrA[k_blk_coord], tCrB[k_blk_coord], acc)
+                    tiled_mma.set(tcgen05.Field.ACCUMULATE, True)
+                # Async arrive AB buffer empty
+                ab_pipeline.consumer_release(ab_consumer_state)
+            ab_consumer_state.advance()
+            # Peek (try_wait) AB buffer full for k_tile = k_tile + 1
+            peek_ab_full_status = Boolean(True)
+            if k_tile + 1 < k_tile_cnt and (is_leader_cta or need_nonleader_cta):
+                peek_ab_full_status = ab_pipeline.consumer_try_wait(ab_consumer_state)
+        # Async arrive accumulator buffer full
+        if is_leader_cta:
+            acc_pipeline.producer_commit(acc_producer_state)
+        acc_producer_state.advance()
+        # If we don't return the tiled_mma, we get compiler error
+        # "operand #0 does not dominate this use"
+        return ab_consumer_state, acc_producer_state, tiled_mma
+
+    @cute.jit
+    def epi_load_acc_subtile(
+        self,
+        tiled_copy_t2r: cute.TiledCopy,
+        tiled_copy_r2s: cute.TiledCopy,
+        tTR_tAcc: cute.Tensor,
+        tTR_rAcc: cute.Tensor,
+        tRS_rD: cute.Tensor,
+        epi_coord: [int, int],
+        acc_pipeline: pipeline.PipelineAsync,
+        acc_consumer_state: pipeline.PipelineState,
+        acc_release_idx: int,
+        clear_acc: Boolean = False,
+    ):
+        if not clear_acc:
+            # Load accumulator from tensor memory buffer to register
+            cute.copy(tiled_copy_t2r, tTR_tAcc[None, None, None, epi_coord], tTR_rAcc)
+            tRS_rAcc = tiled_copy_r2s.retile(tTR_rAcc)
+            tRS_rD.store(tRS_rAcc.load())
+        else:
+            tRS_rD.fill(0.0)
+        assert epi_coord[0] == 0  # For Sm100, we assume epi_M = 1
+        if epi_coord[1] == acc_release_idx:
+            cute.arch.fence_view_async_tmem_load()
+            with cute.arch.elect_one():
+                acc_pipeline.consumer_release(acc_consumer_state)
+
+    def epilog_tmem_copy_and_partition(
+        self,
+        tidx: Int32,
+        tAcc: cute.Tensor,
+        epi_tile: cute.Tile,
+        use_2cta_instrs: Union[Boolean, bool],
+    ) -> Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]:
+        """
+        Make tiledCopy for tensor memory load, then use it to partition tensor memory (source) and register array (destination).
+
+        :param tidx: The thread index in epilogue warp groups
+        :type tidx: Int32
+        :param tAcc: The accumulator tensor to be copied and partitioned
+        :type tAcc: cute.Tensor
+        :param epi_tile: The epilogue tiler
+        :type epi_tile: cute.Tile
+        :param use_2cta_instrs: Whether use_2cta_instrs is enabled
+        :type use_2cta_instrs: bool
+
+        :return: A tuple containing (tiled_copy_t2r, tTR_tAcc, tTR_rAcc) where:
+            - tiled_copy_t2r: The tiled copy operation for tmem to register copy(t2r)
+            - tTR_tAcc: The partitioned accumulator tensor
+            - tTR_rAcc: The accumulated tensor in register used to hold t2r results
+        :rtype: Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]
+        """
+        # Make tiledCopy for tensor memory load
+        copy_atom_t2r = sm100_utils.get_tmem_load_op(
+            self.cta_tile_shape_mnk,
+            self.d_layout if self.d_layout is not None else LayoutEnum.ROW_MAJOR,
+            self.d_dtype if self.d_dtype is not None else cutlass.BFloat16,
+            self.acc_dtype,
+            epi_tile,
+            use_2cta_instrs,
+        )
+        # (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, STAGE)
+        tAcc_epi = cute.flat_divide(tAcc[((None, None), 0, 0, None)], epi_tile)
+        # (EPI_TILE_M, EPI_TILE_N)
+        tiled_copy_t2r = tcgen05.make_tmem_copy(copy_atom_t2r, tAcc_epi[(None, None, 0, 0, 0)])
+
+        thr_copy_t2r = tiled_copy_t2r.get_slice(tidx)
+        # (T2R, T2R_M, T2R_N, EPI_M, EPI_M, STAGE)
+        tTR_tAcc = thr_copy_t2r.partition_S(tAcc_epi)
+
+        cAcc = cute.make_identity_tensor((self.cta_tile_shape_mnk[0], self.cta_tile_shape_mnk[1]))
+        # (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N)
+        cAcc_epi = cute.flat_divide(cAcc, epi_tile)
+        # (T2R, T2R_M, T2R_N, EPI_M, EPI_N)
+        tTR_cAcc = thr_copy_t2r.partition_D(cAcc_epi)
+        # (T2R, T2R_M, T2R_N)
+        tTR_rAcc = cute.make_rmem_tensor(tTR_cAcc[None, None, None, 0, 0].shape, self.acc_dtype)
+        return tiled_copy_t2r, tTR_tAcc, tTR_rAcc
+
+    def epilog_smem_store_and_partition(
+        self,
+        tiled_copy_t2r: cute.TiledCopy,
+        d_layout: Optional[LayoutEnum],
+        dtype: Optional[Type[cutlass.Numeric]],
+        tTR_rD: cute.Tensor,
+        sD: cute.Tensor,
+        tidx: Int32,
+    ) -> Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]:
+        """
+        Make tiledCopy for shared memory store, then use it to partition register array (source) and shared memory (destination).
+
+        :param tiled_copy_t2r: The tiled copy operation for tmem to register copy(t2r)
+        :type tiled_copy_t2r: cute.TiledCopy
+        :param tTR_rD: The partitioned accumulator tensor
+        :type tTR_rD: cute.Tensor
+        :param tidx: The thread index in epilogue warp groups
+        :type tidx: Int32
+        :param sD: The shared memory tensor to be copied and partitioned
+        :type sD: cute.Tensor
+        :type sepi: cute.Tensor
+
+        :return: A tuple containing (tiled_copy_r2s, tRS_rD, tRS_sD) where:
+            - tiled_copy_r2s: The tiled copy operation for register to smem copy(r2s)
+            - tRS_rD: The partitioned tensor C (register source)
+            - tRS_sD: The partitioned tensor C (smem destination)
+        :rtype: Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]
+        """
+        copy_atom_r2s = sm100_utils.get_smem_store_op(
+            d_layout if d_layout is not None else LayoutEnum.ROW_MAJOR,
+            dtype if dtype is not None else cutlass.BFloat16,
+            self.acc_dtype,
+            tiled_copy_t2r,
+        )
+        tiled_copy_r2s = cute.make_tiled_copy_D(copy_atom_r2s, tiled_copy_t2r)
+        # (R2S, R2S_M, R2S_N, PIPE_D)
+        thr_copy_r2s = tiled_copy_r2s.get_slice(tidx)
+        tRS_sD = thr_copy_r2s.partition_D(sD) if sD is not None else None
+        # (R2S, R2S_M, R2S_N)
+        tRS_rD = tiled_copy_r2s.retile(tTR_rD)
+        return tiled_copy_r2s, tRS_rD, tRS_sD
+
+    def epilog_smem_load_and_partition(
+        self,
+        tiled_copy_t2r: cute.TiledCopy,
+        c_layout: LayoutEnum,
+        dtype: Type[cutlass.Numeric],
+        # tTR_rC: cute.Tensor,
+        sC: cute.Tensor,
+        tRS_rD_layout: cutlass.Layout,
+        tidx: Int32,
+    ) -> Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]:
+        copy_atom_r2s = sm100_utils.get_smem_store_op(
+            c_layout, dtype, self.acc_dtype, tiled_copy_t2r
+        )
+        store_op = copy_atom_r2s.op
+        # m8n8 16-bit path
+        if isinstance(store_op, StMatrix8x8x16bOp):
+            op = LdMatrix8x8x16bOp(num_matrices=store_op.num_matrices, transpose=store_op.transpose)
+        # m16n8 8-bit store -> m16n16 8-bit load
+        elif isinstance(store_op, StMatrix16x8x8bOp) and store_op.num_matrices in [2, 4]:
+            # transpose=True is enforced by the class
+            op = LdMatrix16x16x8bOp(num_matrices=store_op.num_matrices // 2)
+        else:
+            op = cute.nvgpu.CopyUniversalOp()
+        copy_atom_s2r = cute.make_copy_atom(op, dtype)
+        tiled_copy_s2r = cute.make_tiled_copy_D(copy_atom_s2r, tiled_copy_t2r)
+        thr_copy_s2r = tiled_copy_s2r.get_slice(tidx)
+        # (R2S, R2S_M, R2S_N, PIPE_D)
+        tSR_sC = thr_copy_s2r.partition_S(sC)
+        tRS_rC = cute.make_rmem_tensor(tRS_rD_layout, dtype)
+        # (R2S, R2S_M, R2S_N)
+        tSR_rC = tiled_copy_s2r.retile(tRS_rC)
+        return tiled_copy_s2r, tRS_rC, tSR_rC, tSR_sC
+
+    @cute.jit
+    def make_ab_pipeline(
+        self,
+        tiled_mma: cute.TiledMma,
+        cluster_layout_vmnk: cute.Layout,
+        ab_pipeline_mbar_ptr: cute.Pointer,
+        is_leader_cta: Boolean,
+    ) -> pipeline.PipelineAsync:
+        # If gather_A and use_2cta_instrs, the cp.async for the non-leader CTA will
+        # arrive at an mbarrier on the non-leader CTA side, then the mma warp of the non-leader
+        # CTA will wait for that then arrive at the mbarrier on the leader CTA.
+        # The producer count for the leader CTA is 1 (TMA) + num_cpasync_threads
+        # + 1 (from non-leader CTA).
+        # The producer count for the non-leader CTA is num_cpasync_threads
+        # (TMA doesn't arrive there).
+        if const_expr(not self.gather_A or self.use_tma_gather):
+            producer_cnt = 1
+        else:
+            producer_cnt = self.num_ab_load_warps * 32 + (
+                1 if const_expr(not self.use_2cta_instrs) else 2
+            )
+        ab_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, producer_cnt)
+        # Each warp will contribute to the arrive count with the number of mcast size
+        mcast_size = self.num_mcast_ctas_a + self.num_mcast_ctas_b - 1
+        consumer_arrive_cnt = mcast_size
+        ab_pipeline_consumer_group = pipeline.CooperativeGroup(
+            pipeline.Agent.Thread, consumer_arrive_cnt
+        )
+        if const_expr(not self.gather_A):
+            pipeline_ab = pipeline.PipelineTmaUmma.create(
+                barrier_storage=ab_pipeline_mbar_ptr,
+                num_stages=self.ab_stage,
+                producer_group=ab_pipeline_producer_group,
+                consumer_group=ab_pipeline_consumer_group,
+                tx_count=self.num_tma_load_bytes,
+                cta_layout_vmnk=cluster_layout_vmnk,
+                defer_sync=True,
+            )
+        elif const_expr(self.use_tma_gather):
+            pipeline_ab = PipelineTmaUmma.create(
+                barrier_storage=ab_pipeline_mbar_ptr,
+                num_stages=self.ab_stage,
+                producer_group=ab_pipeline_producer_group,
+                consumer_group=ab_pipeline_consumer_group,
+                tx_count=self.num_tma_load_bytes,
+                cta_layout_vmnk=cluster_layout_vmnk,
+                defer_sync=True,
+            )
+        else:
+            pipeline_ab = PipelineTmaCpAsyncUmma.create(
+                barrier_storage=ab_pipeline_mbar_ptr,
+                num_stages=self.ab_stage,
+                producer_group=ab_pipeline_producer_group,
+                consumer_group=ab_pipeline_consumer_group,
+                tx_count=self.num_tma_load_bytes,
+                cta_layout_vmnk=cluster_layout_vmnk,
+                producer_drop_count=None
+                if not self.use_2cta_instrs
+                else (2 if not is_leader_cta else 0),
+                defer_sync=True,
+            )
+        return pipeline_ab
+
+    def make_acc_pipeline(
+        self, cluster_layout_vmnk: cute.Layout, acc_pipeline_mbar_ptr: cute.Pointer
+    ) -> pipeline.PipelineAsync:
+        acc_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread)
+        num_acc_consumer_threads = self.num_epi_warps * (2 if self.use_2cta_instrs else 1)
+        acc_pipeline_consumer_group = pipeline.CooperativeGroup(
+            pipeline.Agent.Thread, num_acc_consumer_threads
+        )
+        return pipeline.PipelineUmmaAsync.create(
+            barrier_storage=acc_pipeline_mbar_ptr,
+            num_stages=self.num_acc_stage,
+            producer_group=acc_pipeline_producer_group,
+            consumer_group=acc_pipeline_consumer_group,
+            cta_layout_vmnk=cluster_layout_vmnk,
+            defer_sync=True,
+        )
+
+    def make_sched_pipeline(
+        self,
+        cluster_layout_mnk: cute.Layout,
+        sched_pipeline_mbar_ptr: cute.Pointer,
+        has_C: bool = False,
+    ) -> pipeline.PipelineAsync:
+        # Threads/warps participating in this pipeline
+        sched_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread)
+        cluster_size = cute.size(cluster_layout_mnk)
+        # Each warp will contribute 1 to the arrive count
+        extra_warp_ids = (self.a_prefetch_warp_id,) if self.gather_A else ()
+        warps_per_cta = self.num_ab_load_warps + len(
+            (self.mma_warp_id, *self.epilog_warp_id, self.scheduler_warp_id, *extra_warp_ids)
+        )
+        if has_C:
+            warps_per_cta += 1
+        consumer_arrive_cnt = warps_per_cta * cluster_size
+        sched_pipeline_consumer_group = pipeline.CooperativeGroup(
+            pipeline.Agent.Thread, consumer_arrive_cnt
+        )
+        return pipeline.PipelineAsync.create(
+            barrier_storage=sched_pipeline_mbar_ptr,
+            num_stages=self.sched_stage,
+            producer_group=sched_pipeline_producer_group,
+            consumer_group=sched_pipeline_consumer_group,
+            # If there's cluster, the consumers must arrive at the mbar of CTA 0 in the cluster.
+            consumer_mask=None if const_expr(cluster_size == 1) else 0,
+            defer_sync=True,
+        )
+
+    @cute.jit
+    def make_a_prefetch_pipeline(
+        self, a_prefetch_pipeline_mbar_ptr: cute.Pointer
+    ) -> pipeline.PipelineAsync:
+        producer_cnt = 32
+        a_prefetch_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, producer_cnt)
+        consumer_arrive_cnt = self.num_ab_load_warps
+        a_prefetch_consumer_group = pipeline.CooperativeGroup(
+            pipeline.Agent.Thread, consumer_arrive_cnt
+        )
+        return pipeline.PipelineCpAsync.create(
+            barrier_storage=a_prefetch_pipeline_mbar_ptr,
+            num_stages=self.a_prefetch_stage,
+            producer_group=a_prefetch_producer_group,
+            consumer_group=a_prefetch_consumer_group,
+            defer_sync=True,
+        )
+
+    @classmethod
+    def _compute_stages(
+        cls,
+        tiled_mma: cute.TiledMma,
+        mma_tiler_mnk: Tuple[int, int, int],
+        cta_tile_shape_mnk: Tuple[int, int, int],
+        epi_tile: cute.Tile,
+        a_dtype: Type[cutlass.Numeric],
+        b_dtype: Type[cutlass.Numeric],
+        sf_dtype: Optional[Type[cutlass.Numeric]],
+        sf_vec_size: Optional[int],
+        d_dtype: Optional[Type[cutlass.Numeric]],
+        c_dtype: Optional[Type[cutlass.Numeric]],
+        d_layout: Optional[LayoutEnum],
+        c_layout: Optional[LayoutEnum],
+        epilogue_args: EpilogueArguments,
+        prefetch_A_idx: Literal[None, "varlen_m", "varlen_k"],
+        smem_capacity: int,
+        occupancy: int,
+        warp_shape_mnk: Tuple[int, int, int] | None = None,
+    ) -> Tuple[int, int, int]:
+        """Computes the number of stages for A/B/C operands based on heuristics.
+
+        :param tiled_mma: The tiled MMA object defining the core computation.
+        :type tiled_mma: cute.TiledMma
+        :param mma_tiler_mnk: The shape (M, N, K) of the MMA tiler.
+        :type mma_tiler_mnk: tuple[int, int, int]
+        :param a_dtype: Data type of operand A.
+        :type a_dtype: type[cutlass.Numeric]
+        :param b_dtype: Data type of operand B.
+        :type b_dtype: type[cutlass.Numeric]
+        :param epi_tile: The epilogue tile shape.
+        :type epi_tile: cute.Tile
+        :param d_dtype: Data type of operand C (output).
+        :type d_dtype: type[cutlass.Numeric]
+        :param d_layout: Layout enum of operand D.
+        :type d_layout: LayoutEnum
+        :param smem_capacity: Total available shared memory capacity in bytes.
+        :type smem_capacity: int
+        :param occupancy: Target number of CTAs per SM (occupancy).
+        :type occupancy: int
+
+        :return: A tuple containing the computed number of stages for:
+                 (ACC stages, A/B operand stages, C stages)
+        :rtype: tuple[int, int, int]
+        """
+        blockscaled = sf_dtype is not None
+        # Default ACC stages
+        if const_expr(not blockscaled):
+            num_acc_stage = 1 if mma_tiler_mnk[1] > 256 else 2
+        else:
+            num_acc_stage = 1 if mma_tiler_mnk[1] >= 256 else 2
+
+        # Default D stages
+        epi_stage = 4 if cute.size(epi_tile[1]) <= 16 else 2
+        epi_smem_bytes = cls.epi_smem_bytes(
+            epilogue_args, cta_tile_shape_mnk, epi_tile, warp_shape_mnk
+        )
+        has_tile_load = epi_smem_bytes.c_stage > 0
+        epi_c_stage = (
+            0
+            if c_dtype is None and not has_tile_load
+            else (4 if cute.size(epi_tile[1]) <= 16 else 2)
+        )
+
+        # Calculate smem layout and size for one stage of A, B, and C
+        a_smem_layout_staged_one = sm100_utils.make_smem_layout_a(
+            tiled_mma,
+            mma_tiler_mnk,
+            a_dtype,
+            1,  # a tmp 1 stage is provided
+        )
+        b_smem_layout_staged_one = sm100_utils.make_smem_layout_b(
+            tiled_mma,
+            mma_tiler_mnk,
+            b_dtype,
+            1,  # a tmp 1 stage is provided
+        )
+        d_smem_layout_staged_one = (
+            sm100_utils.make_smem_layout_epi(d_dtype, d_layout, epi_tile, 1)
+            if d_dtype is not None
+            else None
+        )
+        c_smem_layout_staged_one = (
+            sm100_utils.make_smem_layout_epi(c_dtype, c_layout, epi_tile, 1)
+            if c_dtype is not None
+            else None
+        )
+        if const_expr(blockscaled):
+            sfa_smem_layout_staged_one = blockscaled_utils.make_smem_layout_sfa(
+                tiled_mma,
+                mma_tiler_mnk,
+                sf_vec_size,
+                1,  # a tmp 1 stage is provided
+            )
+            sfb_smem_layout_staged_one = blockscaled_utils.make_smem_layout_sfb(
+                tiled_mma,
+                mma_tiler_mnk,
+                sf_vec_size,
+                1,  # a tmp 1 stage is provided
+            )
+
+        ab_bytes_per_stage = cute.size_in_bytes(
+            a_dtype, a_smem_layout_staged_one
+        ) + cute.size_in_bytes(b_dtype, b_smem_layout_staged_one)
+        if const_expr(prefetch_A_idx == "varlen_k"):  # Need smem to prefetch A indices
+            ab_bytes_per_stage += Int32.width // 8 * cta_tile_shape_mnk[2]
+        if const_expr(blockscaled):
+            ab_bytes_per_stage += cute.size_in_bytes(
+                sf_dtype, sfa_smem_layout_staged_one
+            ) + cute.size_in_bytes(sf_dtype, sfb_smem_layout_staged_one)
+        mbar_helpers_bytes = 1024
+        if const_expr(prefetch_A_idx == "varlen_m"):
+            mbar_helpers_bytes += Int32.width // 8 * cta_tile_shape_mnk[0] * 2
+        d_bytes_per_stage = (
+            cute.size_in_bytes(d_dtype, d_smem_layout_staged_one) if d_dtype is not None else 0
+        )
+        epi_bytes_per_stage = d_bytes_per_stage + epi_smem_bytes.d_stage
+        epi_bytes = epi_smem_bytes.unstaged + epi_bytes_per_stage * epi_stage
+        if const_expr(c_dtype is not None):
+            c_bytes_per_stage = cute.size_in_bytes(c_dtype, c_smem_layout_staged_one)
+            epi_bytes += c_bytes_per_stage * epi_c_stage
+        if const_expr(has_tile_load):
+            epi_bytes += epi_smem_bytes.c_stage * epi_c_stage
+
+        # Calculate A/B/SFA/SFB stages:
+        # Start with total smem per CTA (capacity / occupancy)
+        # Subtract reserved bytes and initial C stages bytes
+        # Divide remaining by bytes needed per A/B/SFA/SFB stage
+        remaining_bytes = smem_capacity // occupancy - mbar_helpers_bytes - epi_bytes
+        ab_stage = remaining_bytes // ab_bytes_per_stage
+
+        # Refine epilogue stages:
+        # Calculate remaining smem after allocating for A/B stages and reserved bytes
+        # Add remaining unused smem to epilogue
+        if epi_bytes_per_stage > 0:
+            epi_stage += (remaining_bytes - ab_bytes_per_stage * ab_stage) // epi_bytes_per_stage
+        return num_acc_stage, ab_stage, epi_stage, epi_c_stage
+
+    @staticmethod
+    def _compute_num_tmem_alloc_cols(
+        tiled_mma: cute.TiledMma,
+        mma_tiler: Tuple[int, int, int],
+        num_acc_stage: int,
+    ) -> int:
+        """
+        Compute the number of tensor memory allocation columns.
+
+        :param tiled_mma: The tiled MMA object defining the core computation.
+        :type tiled_mma: cute.TiledMma
+        :param mma_tiler: The shape (M, N, K) of the MMA tile.
+        :type mma_tiler: tuple[int, int, int]
+        :param num_acc_stage: The stage of the accumulator tensor.
+        :type num_acc_stage: int
+
+        :return: The number of tensor memory allocation columns.
+        :rtype: int
+        """
+        acc_shape = tiled_mma.partition_shape_C(mma_tiler[:2])
+        tCtAcc_fake = tiled_mma.make_fragment_C(cute.append(acc_shape, num_acc_stage))
+        num_tmem_alloc_cols = cutlass.utils.get_num_tmem_alloc_cols(tCtAcc_fake)
+        return num_tmem_alloc_cols
+
+    @staticmethod
+    def is_valid_dtypes(
+        a_dtype: Type[cutlass.Numeric],
+        b_dtype: Type[cutlass.Numeric],
+        acc_dtype: Type[cutlass.Numeric],
+        d_dtype: Optional[Type[cutlass.Numeric]],
+        a_major: str,
+        b_major: str,
+    ) -> bool:
+        """
+        Check if the dtypes are valid
+
+        :param ab_dtype: The data type of the A and B operands
+        :type ab_dtype: Type[cutlass.Numeric]
+        :param acc_dtype: The data type of the accumulator
+        :type acc_dtype: Type[cutlass.Numeric]
+        :param d_dtype: The data type of the output tensor
+        :type d_dtype: Type[cutlass.Numeric]
+
+        :return: True if the dtypes are valid, False otherwise
+        :rtype: bool
+        """
+        is_valid = True
+        if b_dtype != a_dtype:
+            is_valid = False
+        ab_dtype = a_dtype
+        if ab_dtype not in {
+            cutlass.Float16,
+            cutlass.BFloat16,
+            cutlass.TFloat32,
+            cutlass.Uint8,
+            cutlass.Int8,
+            cutlass.Float8E4M3FN,
+            cutlass.Float8E5M2,
+        }:
+            is_valid = False
+        if (
+            acc_dtype not in {Float32, cutlass.Float16, Int32}
+            or acc_dtype == cutlass.Float16
+            and ab_dtype not in {cutlass.Float16, cutlass.Float8E4M3FN, cutlass.Float8E5M2}
+            or acc_dtype == Int32
+            and ab_dtype not in {cutlass.Uint8, cutlass.Int8}
+        ):
+            is_valid = False
+        if d_dtype is not None and (
+            acc_dtype == Float32
+            and d_dtype
+            not in {
+                Float32,
+                cutlass.Float16,
+                cutlass.BFloat16,
+                cutlass.Float8E4M3FN,
+                cutlass.Float8E5M2,
+                Int32,
+                cutlass.Int8,
+                cutlass.Uint8,
+            }
+            or acc_dtype == cutlass.Float16
+            and d_dtype
+            not in {
+                cutlass.BFloat16,
+                cutlass.Float16,
+            }
+            or acc_dtype == Int32
+            and d_dtype
+            not in {
+                cutlass.BFloat16,
+                cutlass.Float16,
+                Float32,
+                Int32,
+                cutlass.Int8,
+                cutlass.Uint8,
+            }
+        ):
+            is_valid = False
+        if ab_dtype is cutlass.Float4E2M1FN and not (a_major == "k" and b_major == "k"):
+            is_valid = False
+        return is_valid
+
+    @staticmethod
+    def is_valid_dtypes_and_scale_factor_vec_size(
+        ab_dtype: Type[cutlass.Numeric],
+        sf_dtype: Type[cutlass.Numeric],
+        sf_vec_size: int,
+        d_dtype: Type[cutlass.Numeric],
+    ) -> bool:
+        """
+        Check if the dtypes and sf_vec_size are valid combinations
+
+        :param ab_dtype: The data type of the A and B operands
+        :type ab_dtype: Type[cutlass.Numeric]
+        :param sf_dtype: The data type of the scale factor
+        :type sf_dtype: Type[cutlass.Numeric]
+        :param sf_vec_size: The vector size of the scale factor
+        :type sf_vec_size: int
+        :param d_dtype: The data type of the output tensor
+        :type d_dtype: Type[cutlass.Numeric]
+
+        :return: True if the dtypes and sf_vec_size are valid, False otherwise
+        :rtype: bool
+        """
+        is_valid = True
+
+        # Check valid ab_dtype
+        if ab_dtype not in {cutlass.Float4E2M1FN, cutlass.Float8E5M2, cutlass.Float8E4M3FN}:
+            is_valid = False
+
+        # Check valid sf_vec_size
+        if sf_vec_size not in {16, 32}:
+            is_valid = False
+
+        # Check valid sf_dtype
+        if sf_dtype not in {cutlass.Float8E8M0FNU, cutlass.Float8E4M3FN}:
+            is_valid = False
+
+        # Check valid sf_dtype and sf_vec_size combinations
+        if sf_dtype == cutlass.Float8E4M3FN and sf_vec_size == 32:
+            is_valid = False
+        if ab_dtype in {cutlass.Float8E5M2, cutlass.Float8E4M3FN} and sf_vec_size == 16:
+            is_valid = False
+
+        # Check valid d_dtype
+        if d_dtype not in {
+            Float32,
+            cutlass.Float16,
+            cutlass.BFloat16,
+            cutlass.Float8E5M2,
+            cutlass.Float8E4M3FN,
+        }:
+            is_valid = False
+
+        return is_valid
+
+    @staticmethod
+    def is_valid_mma_tiler_and_cluster_shape(
+        mma_tiler_mnk: Union[Tuple[int, int], Tuple[int, int, int]],
+        cluster_shape_mn: Tuple[int, int],
+        blockscaled: bool,
+    ) -> bool:
+        """
+        Check if the mma tiler and cluster shape are valid
+
+        :param mma_tiler_mnk: The (M, N) or (M, N, K) shape of the MMA instruction tiler
+        :type mma_tiler_mnk: Union[Tuple[int, int], Tuple[int, int, int]]
+        :param cluster_shape_mn: The (ClusterM, ClusterN) shape of the CTA cluster
+        :type cluster_shape_mn: Tuple[int, int]
+
+        :return: True if the mma tiler and cluster shape are valid, False otherwise
+        :rtype: bool
+        """
+        is_valid = True
+        # Skip invalid mma tile shape
+        if not blockscaled:
+            if mma_tiler_mnk[0] not in [64, 128, 256]:
+                is_valid = False
+        else:
+            if mma_tiler_mnk[0] not in [128, 256]:
+                is_valid = False
+        mma_inst_n = mma_tiler_mnk[1] if mma_tiler_mnk[1] <= 256 else mma_tiler_mnk[1] // 2
+        if not blockscaled:
+            if mma_inst_n not in range(32, 257, 32):
+                is_valid = False
+        else:
+            # Blockscaled currently supports tile_n in {64, 128, 192, 256}.
+            if mma_tiler_mnk[1] not in [64, 128, 192, 256]:
+                is_valid = False
+        if cluster_shape_mn[0] % (2 if mma_tiler_mnk[0] == 256 else 1) != 0:
+            is_valid = False
+        # Skip invalid cluster shape
+        is_power_of_2 = lambda x: x > 0 and (x & (x - 1)) == 0
+        if (
+            cluster_shape_mn[0] * cluster_shape_mn[1] > 16
+            or cluster_shape_mn[0] <= 0
+            or cluster_shape_mn[1] <= 0
+            or not is_power_of_2(cluster_shape_mn[0])
+            or not is_power_of_2(cluster_shape_mn[1])
+        ):
+            is_valid = False
+        if blockscaled:
+            # Special cluster shape check for scale factor multicasts.
+            # Due to limited size of scale factors, we can't multicast among more than 4 CTAs.
+            if cluster_shape_mn[0] > 4 or cluster_shape_mn[1] > 4:
+                is_valid = False
+        return is_valid
+
+    @staticmethod
+    def is_valid_tensor_alignment(
+        m: int,
+        n: int,
+        k: int,
+        l: int,
+        ab_dtype: Type[cutlass.Numeric],
+        d_dtype: Type[cutlass.Numeric],
+        a_major: str,
+        b_major: str,
+        d_major: str,
+    ) -> bool:
+        """
+        Check if the tensor alignment is valid
+
+        :param m: The number of rows in the A tensor
+        :type m: int
+        :param n: The number of columns in the B tensor
+        :type n: int
+        :param k: The number of columns in the A tensor
+        :type k: int
+        :param l: The number of columns in the C tensor
+        :type l: int
+        :param ab_dtype: The data type of the A and B operands
+        :type ab_dtype: Type[cutlass.Numeric]
+        :param d_dtype: The data type of the output tensor
+        :type d_dtype: Type[cutlass.Numeric]
+        :param a_major: The major axis of the A tensor
+        :type a_major: str
+        :param b_major: The major axis of the B tensor
+        :type b_major: str
+        :param d_major: The major axis of the C tensor
+        :type d_major: str
+
+        :return: True if the problem shape is valid, False otherwise
+        :rtype: bool
+        """
+        is_valid = True
+
+        def check_contigous_16B_alignment(dtype, is_mode0_major, tensor_shape):
+            major_mode_idx = 0 if is_mode0_major else 1
+            num_major_elements = tensor_shape[major_mode_idx]
+            num_contiguous_elements = 16 * 8 // dtype.width
+            return num_major_elements % num_contiguous_elements == 0
+
+        if (
+            not check_contigous_16B_alignment(ab_dtype, a_major == "m", (m, k, l))
+            or not check_contigous_16B_alignment(ab_dtype, b_major == "n", (n, k, l))
+            or not check_contigous_16B_alignment(d_dtype, d_major == "m", (m, n, l))
+        ):
+            is_valid = False
+        return is_valid
+
+    @staticmethod
+    def can_implement_blockscaled(
+        ab_dtype: Type[cutlass.Numeric],
+        sf_dtype: Type[cutlass.Numeric],
+        sf_vec_size: int,
+        d_dtype: Type[cutlass.Numeric],
+        mma_tiler_mnk: Union[Tuple[int, int], Tuple[int, int, int]],
+        cluster_shape_mn: Tuple[int, int],
+        m: int,
+        n: int,
+        k: int,
+        l: int,
+        a_major: str,
+        b_major: str,
+        d_major: str,
+    ) -> bool:
+        can_implement = True
+        if not GemmSm100.is_valid_dtypes_and_scale_factor_vec_size(
+            ab_dtype, sf_dtype, sf_vec_size, d_dtype
+        ):
+            can_implement = False
+        if ab_dtype is cutlass.Float4E2M1FN and not (a_major == "k" and b_major == "k"):
+            can_implement = False
+        if not GemmSm100.is_valid_mma_tiler_and_cluster_shape(
+            mma_tiler_mnk, cluster_shape_mn, blockscaled=True
+        ):
+            can_implement = False
+        if not GemmSm100.is_valid_tensor_alignment(
+            m, n, k, l, ab_dtype, d_dtype, a_major, b_major, d_major
+        ):
+            can_implement = False
+        return can_implement
+
+    @staticmethod
+    def can_implement(
+        ab_dtype: Type[cutlass.Numeric],
+        acc_dtype: Type[cutlass.Numeric],
+        d_dtype: Type[cutlass.Numeric],
+        mma_tiler_mnk: Union[Tuple[int, int], Tuple[int, int, int]],
+        cluster_shape_mn: Tuple[int, int],
+        m: int,
+        n: int,
+        k: int,
+        l: int,
+        a_major: str,
+        b_major: str,
+        d_major: str,
+    ) -> bool:
+        """
+        Check if the gemm can be implemented
+
+        :param ab_dtype: The data type of the A and B operands
+        :type ab_dtype: Type[cutlass.Numeric]
+        :param acc_dtype: The data type of the accumulator
+        :type acc_dtype: Type[cutlass.Numeric]
+        :param d_dtype: The data type of the output tensor
+        :type d_dtype: Type[cutlass.Numeric]
+        :param mma_tiler_mnk: The (M, N) or (M, N, K) shape of the MMA instruction tiler
+        :type mma_tiler_mnk: Union[Tuple[int, int], Tuple[int, int, int]]
+        :param cluster_shape_mn: The (ClusterM, ClusterN) shape of the CTA cluster
+        :type cluster_shape_mn: Tuple[int, int]
+        :param m: The number of rows in the A tensor
+        :type m: int
+        :param n: The number of columns in the B tensor
+        :type n: int
+        :param k: The number of columns in the A tensor
+        :type k: int
+        :param l: The number of columns in the C tensor
+        :type l: int
+        :param a_major: The major axis of the A tensor
+        :type a_major: str
+        :param b_major: The major axis of the B tensor
+        :type b_major: str
+        :param d_major: The major axis of the C tensor
+        :type d_major: str
+
+        :return: True if the gemm can be implemented, False otherwise
+        :rtype: bool
+        """
+        can_implement = True
+        # Skip unsupported types
+        if not GemmSm100.is_valid_dtypes(ab_dtype, ab_dtype, acc_dtype, d_dtype, a_major, b_major):
+            can_implement = False
+        # Skip invalid mma tile shape and cluster shape
+        if not GemmSm100.is_valid_mma_tiler_and_cluster_shape(
+            mma_tiler_mnk, cluster_shape_mn, blockscaled=False
+        ):
+            can_implement = False
+        # Skip illegal problem shape for load/store alignment
+        if not GemmSm100.is_valid_tensor_alignment(
+            m, n, k, l, ab_dtype, d_dtype, a_major, b_major, d_major
+        ):
+            can_implement = False
+        return can_implement
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_sm120.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_sm120.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f7ebd10f7b704b8a4d4367fec11fce7434ebbcf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_sm120.py
@@ -0,0 +1,674 @@
+# Copyright (c) 2025-2026, QuACK team.
+# Based on the cute-dsl example:
+# https://github.com/NVIDIA/cutlass/blob/main/examples/python/CuTeDSL/blackwell_geforce/dense_gemm.py
+# SM120-style GEMM using warp-level MMA (MmaF16BF16Op) + ldmatrix.
+# Unlike SM90 WGMMA (which reads A/B from SMEM directly), warp-level MMA
+# requires explicit SMEM→RMEM copies via ldmatrix before each MMA instruction.
+
+# This is a work in progress and not very optimized.
+
+import math
+from typing import Tuple, Type, Callable, Optional
+from functools import partial
+
+import cutlass
+import cutlass.cute as cute
+import cutlass.pipeline as pipeline
+from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait
+from cutlass.cute.nvgpu import cpasync, warp
+from cutlass import Int32, Boolean, const_expr
+
+from .varlen_utils import VarlenManager
+from .pipeline import make_pipeline_state
+from . import copy_utils
+from .gemm_sm90 import GemmSm90, NamedBarrierGemm
+from . import sm80_utils
+
+
+class GemmSm120(GemmSm90):
+    """SM120-style GEMM using warp-level MMA instead of WGMMA.
+
+    Key differences from SM90:
+    - Uses MmaF16BF16Op (warp-level, 32 threads) instead of WGMMA (warp-group, 128 threads)
+    - Requires explicit SMEM→RMEM copy via ldmatrix before MMA
+    - Thread config: num_mma_warps regular warps + 1 DMA warp
+    - Pingpong: 2 warp groups of (2,2,1), each processing alternating tiles
+    - No fp8 support (warp-level MMA only supports fp16/bf16)
+    """
+
+    arch = 120
+
+    def __init__(
+        self,
+        acc_dtype: Type[cutlass.Numeric],
+        a_dtype: Type[cutlass.Numeric],
+        tile_shape_mnk: Tuple[int, int] | Tuple[int, int, int],
+        cluster_shape_mnk: Tuple[int, int, int],
+        pingpong: bool = False,
+        is_persistent: bool = True,
+        gather_A: bool = False,
+        concat_layout: tuple | None = None,
+        use_pdl: bool = True,
+    ):
+        # Don't call super().__init__ — we set up our own config
+        self.acc_dtype = acc_dtype
+        self.pingpong = pingpong
+        self.is_persistent = is_persistent
+        self.use_clc_persistence = False
+        self.use_pdl = use_pdl
+        self.fp8_slow_accum = False
+        self.gather_A = gather_A
+        self.concat_layout = concat_layout or ()
+        if self.pingpong:
+            assert self.is_persistent, "Pingpong gemm requires persistent scheduler"
+        if gather_A:
+            assert cluster_shape_mnk[1] == 1
+
+        self.cluster_shape_mnk = cluster_shape_mnk
+        assert len(tile_shape_mnk) in [2, 3], "CTA tile shape must be (M, N) or (M, N, K)"
+        # K dimension: if user provides 3 values, use their K; otherwise default in _setup_tiled_mma.
+        self.cta_tile_shape_mnk = (
+            tuple(tile_shape_mnk) if len(tile_shape_mnk) == 3 else (*tile_shape_mnk, 0)
+        )
+        tile_M, tile_N = self.cta_tile_shape_mnk[:2]
+
+        # Pingpong: 2 warp groups each with (2,2,1) atom layout
+        # Non-pingpong: 1 group of 8 warps with (4,2,1) atom layout
+        self.mma_inst_mnk = (16, 8, 16)
+        self.atom_layout_mnk = (4, 2, 1) if not self.pingpong else (2, 2, 1)
+        # num_mma_warps = total warps doing MMA (both warp groups in pingpong)
+        self.num_mma_warps = math.prod(self.atom_layout_mnk) * (1 if not self.pingpong else 2)
+        # For compatibility with SM90 code that uses warp groups
+        self.num_threads_per_warp_group = 128
+        assert self.num_mma_warps % 4 == 0
+        self.mma_warp_groups = self.num_mma_warps // 4
+        if self.pingpong:
+            assert self.mma_warp_groups == 2
+        # threads_per_cta must be a multiple of 128 (warp group size) so that
+        # the DMA warp's setmaxnreg.dec.sync has a complete warp group to sync with.
+        self.threads_per_cta = (self.mma_warp_groups + 1) * self.num_threads_per_warp_group
+
+        self.num_mcast_ctas_a = cluster_shape_mnk[1]
+        if gather_A:
+            assert self.num_mcast_ctas_a == 1
+        self.num_mcast_ctas_b = cluster_shape_mnk[0]
+        self.is_a_mcast = self.num_mcast_ctas_a > 1
+        self.is_b_mcast = self.num_mcast_ctas_b > 1
+
+        self.occupancy = 1
+        self.smem_capacity = cutlass.utils.get_smem_capacity_in_bytes(f"sm_{self.arch}")
+
+        # In pingpong, only 1 warp group (4 warps) participates in epilogue at a time
+        self.num_epi_warps = (self.mma_warp_groups if not self.pingpong else 1) * 4
+        self.epilogue_barrier = pipeline.NamedBarrier(
+            barrier_id=int(NamedBarrierGemm.Epilogue),
+            num_threads=self.num_epi_warps * cute.arch.WARP_SIZE,
+        )
+        self.num_ab_load_warps = 1 if not self.gather_A else 4
+        self.ab_load_warp_id = self.num_mma_warps
+
+        if not self.gather_A:
+            self.num_regs_load = 40
+            self.num_regs_mma = 232
+        else:
+            self.num_regs_load = 56
+            self.num_regs_mma = 224
+
+        self.ab_stage = None
+        self.epi_stage = None
+        self.epi_m_major = True
+        self.a_smem_layout_staged = None
+        self.b_smem_layout_staged = None
+        self.epi_smem_layout_staged = None
+        self.epi_tile = None
+        self.shared_storage = None
+        self.buffer_align_bytes = 1024
+
+    def epi_smem_warp_shape_mnk(self):
+        return self.atom_layout_mnk
+
+    def _setup_tiled_mma(self):
+        """Set up warp-level MMA (MmaF16BF16Op) and tile K dimension."""
+        op = warp.MmaF16BF16Op(self.a_dtype, self.acc_dtype, self.mma_inst_mnk)
+        tC = cute.make_layout(self.atom_layout_mnk)
+        atom_m, atom_n, atom_k = self.atom_layout_mnk
+        # We want each warp to have 16 consecutive elements in the N direction, for STSM
+        # and for gated epilogue.
+        permutation_n = cute.make_ordered_layout((self.mma_inst_mnk[1], atom_n, 2), order=(0, 2, 1))
+        permutation_mnk = (
+            atom_m * self.mma_inst_mnk[0],
+            permutation_n,
+            atom_k * self.mma_inst_mnk[2],
+        )
+        self.tiled_mma = cute.make_tiled_mma(op, tC, permutation_mnk=permutation_mnk)
+        tile_k = (
+            self.cta_tile_shape_mnk[2]
+            if self.cta_tile_shape_mnk[2] > 0
+            else self.mma_inst_mnk[2] * 4
+        )
+        assert tile_k > 0, "CTA tile K must be positive"
+        assert tile_k % self.mma_inst_mnk[2] == 0, (
+            f"CTA tile K ({tile_k}) must be divisible by MMA instruction K ({self.mma_inst_mnk[2]})"
+        )
+        self.cta_tile_shape_mnk = (self.cta_tile_shape_mnk[0], self.cta_tile_shape_mnk[1], tile_k)
+
+    # __call__, _setup_attributes, make_ab_pipeline, make_epi_store_pipeline,
+    # make_sched_pipeline, epilogue are all inherited from GemmSm90.
+
+    @cute.kernel
+    def kernel(
+        self,
+        tiled_mma: cute.TiledMma,
+        tma_atom_a: Optional[cute.CopyAtom],
+        mA_mkl: cute.Tensor,
+        tma_atom_b: cute.CopyAtom,
+        mB_nkl: cute.Tensor,
+        tma_atom_d: Optional[cute.CopyAtom],
+        mD_mnl: Optional[cute.Tensor],
+        tma_atom_c: Optional[cute.CopyAtom],
+        mC_mnl: Optional[cute.Tensor],
+        epilogue_params,
+        varlen_params: VarlenManager.Params,
+        cluster_layout_mnk: cute.Layout,
+        a_smem_layout: cute.ComposedLayout,
+        b_smem_layout: cute.ComposedLayout,
+        epi_smem_layout: cute.ComposedLayout,
+        epi_c_smem_layout: cute.ComposedLayout,
+        tile_sched_params,
+        TileSchedulerCls: cutlass.Constexpr[Callable],
+        trace_ptr: Optional[cutlass.Int64] = None,
+    ):
+        from .trace import TraceContext
+
+        tctx = TraceContext.create(trace_ptr)
+
+        varlen_m = const_expr(varlen_params.cu_seqlens_m is not None)
+        varlen_k = const_expr(varlen_params.cu_seqlens_k is not None)
+        if const_expr(self.gather_A):
+            assert varlen_m or varlen_k
+        has_D = const_expr(mD_mnl is not None)
+        has_C = const_expr(mC_mnl is not None)
+
+        warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
+
+        # Prefetch TMA descriptors
+        if warp_idx == self.ab_load_warp_id:
+            for tma_atom in (tma_atom_a, tma_atom_b, tma_atom_d, tma_atom_c):
+                if const_expr(tma_atom is not None):
+                    cpasync.prefetch_descriptor(tma_atom)
+
+        # Allocate shared memory
+        smem = cutlass.utils.SmemAllocator()
+        storage = smem.allocate(self.shared_storage)
+
+        ab_pipeline = self.make_ab_pipeline(
+            tiled_mma=tiled_mma,
+            cluster_layout_vmnk=cute.make_layout((1, *cluster_layout_mnk.shape)),
+            ab_pipeline_mbar_ptr=storage.ab_pipeline_array_ptr.data_ptr(),
+        )
+        epi_pipeline = None
+        has_epi_load = const_expr(self.epi_c_stage > 0)
+        if const_expr(has_epi_load):
+            epi_pipeline = self.make_epi_pipeline(
+                epi_pipeline_mbar_ptr=storage.epi_pipeline_array_ptr.data_ptr(),
+                tx_count=self.epi_load_bytes_per_stage,
+            )
+        sched_pipeline = None
+        sched_data = None
+        if const_expr(self.is_persistent):
+            sched_pipeline = self.make_sched_pipeline(
+                cluster_layout_mnk,
+                sched_pipeline_mbar_ptr=storage.sched_pipeline_array_ptr.data_ptr(),
+                varlen_k=varlen_k,
+            )
+            sched_data = storage.sched_data.get_tensor((4, self.sched_stage))
+
+        # Cluster sync
+        pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mnk[:-1], is_relaxed=True)
+
+        # SMEM tensors
+        sA = storage.sA.get_tensor(a_smem_layout.outer, swizzle=a_smem_layout.inner)
+        sB = storage.sB.get_tensor(b_smem_layout.outer, swizzle=b_smem_layout.inner)
+        sD = None
+        if const_expr(has_D):
+            sD = storage.sD.get_tensor(epi_smem_layout.outer, swizzle=epi_smem_layout.inner)
+        sC = None
+        if const_expr(has_C):
+            sC = storage.sC.get_tensor(epi_c_smem_layout.outer, swizzle=epi_c_smem_layout.inner)
+        epi_smem_tensors = self.epi_get_smem_tensors(epilogue_params, storage)
+
+        varlen_manager = VarlenManager.create(
+            varlen_params,
+            len_m_static=Int32(
+                cute.size(mA_mkl, mode=[0])
+                if varlen_k or varlen_params.mAIdx is None
+                else varlen_params.mAIdx.shape[0]
+            ),
+            len_k_static=Int32(cute.size(mA_mkl, mode=[1])),
+        )
+
+        TileSchedulerCls = partial(
+            TileSchedulerCls.create, tile_sched_params, sched_data, sched_pipeline
+        )
+
+        # Cluster wait
+        pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mnk[:-1])
+
+        if warp_idx >= self.ab_load_warp_id:
+            cute.arch.setmaxregister_decrease(self.num_regs_load)
+            if (
+                warp_idx >= self.ab_load_warp_id
+                and warp_idx < self.ab_load_warp_id + self.num_ab_load_warps
+            ):
+                # Get mcast mask
+                cta_rank_in_cluster = cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster())
+                block_in_cluster_coord_mnk = cluster_layout_mnk.get_flat_coord(cta_rank_in_cluster)
+                a_mcast_mask = cute.make_layout_image_mask(
+                    cluster_layout_mnk, block_in_cluster_coord_mnk, mode=1
+                )
+                b_mcast_mask = cute.make_layout_image_mask(
+                    cluster_layout_mnk, block_in_cluster_coord_mnk, mode=0
+                )
+                a_mcast_mask = a_mcast_mask if self.is_a_mcast else 0
+                b_mcast_mask = b_mcast_mask if self.is_b_mcast else 0
+
+                # Persistent tile scheduling loop
+                is_scheduler_warp = self.num_ab_load_warps == 1 or warp_idx == self.ab_load_warp_id
+                if const_expr(cute.size(cluster_layout_mnk) > 1):
+                    is_scheduler_warp = is_scheduler_warp and cute.arch.block_idx_in_cluster() == 0
+                tile_scheduler = TileSchedulerCls()
+                work_tile = tile_scheduler.initial_work_tile_info()
+                ab_producer_state = make_pipeline_state(
+                    pipeline.PipelineUserType.Producer, self.ab_stage
+                )
+                while work_tile.is_valid_tile:
+                    tctx.b("tma_load")
+                    tile_coord_mnkl = work_tile.tile_idx
+                    batch_idx = tile_coord_mnkl[3]
+                    # Local_tile partition global tensors
+                    copy_A, prefetch_A = None, None
+                    if const_expr(not self.gather_A):
+                        mA_mk = varlen_manager.offset_batch_A(mA_mkl, batch_idx)
+                        # (bM, bK, RestK)
+                        gA_mk = cute.local_tile(
+                            mA_mk,
+                            cute.select(self.cta_tile_shape_mnk, [0, 2]),
+                            (tile_coord_mnkl[0], None),
+                        )
+                        #  TMA load A partition_S/D
+                        copy_A, _, _ = copy_utils.tma_get_copy_fn(
+                            tma_atom_a,
+                            cta_coord=block_in_cluster_coord_mnk[1],
+                            cta_layout=cute.make_layout(
+                                cute.slice_(cluster_layout_mnk, (0, None, 0)).shape
+                            ),
+                            src_tensor=gA_mk,
+                            dst_tensor=sA,
+                            mcast_mask=a_mcast_mask,
+                        )
+                    else:
+                        copy_A, prefetch_A = self._make_gather_A_copy(
+                            mA_mkl, sA, varlen_manager, tile_coord_mnkl, batch_idx
+                        )
+                    # (bN, bK, RestK)
+                    gB_nk = cute.local_tile(
+                        varlen_manager.offset_batch_B(mB_nkl, batch_idx),
+                        cute.select(self.cta_tile_shape_mnk, [1, 2]),
+                        (tile_coord_mnkl[1], None),
+                    )
+                    # TMA load B partition_S/D
+                    copy_B, _, _ = copy_utils.tma_get_copy_fn(
+                        tma_atom_b,
+                        cta_coord=block_in_cluster_coord_mnk[0],
+                        cta_layout=cute.make_layout(
+                            cute.slice_(cluster_layout_mnk, (None, 0, 0)).shape
+                        ),
+                        src_tensor=gB_nk,
+                        dst_tensor=sB,
+                        mcast_mask=b_mcast_mask,
+                    )
+                    len_k = varlen_manager.len_k(batch_idx)
+                    k_tile_cnt = cute.ceil_div(len_k, self.cta_tile_shape_mnk[2])
+                    if const_expr(not self.gather_A):
+                        ab_producer_state = self.load_tma(
+                            ab_pipeline, ab_producer_state, [copy_A, copy_B], k_tile_cnt
+                        )
+                    else:
+                        ab_producer_state = self.load_AB_gather_A(
+                            ab_pipeline,
+                            ab_producer_state,
+                            copy_A,
+                            prefetch_A,
+                            copy_B,
+                            k_tile_cnt,
+                            varlen_m=varlen_m,
+                        )
+                    tctx.e("tma_load")
+                    tile_scheduler.advance_to_next_work(is_scheduler_warp=is_scheduler_warp)
+                    work_tile = tile_scheduler.get_current_work()
+                    # End of persistent scheduler loop
+                if const_expr(self.pingpong and not varlen_k):
+                    # Need to write the tile_idx to smem for the next WG in the pingpong mode
+                    if is_scheduler_warp:
+                        tile_scheduler.write_work_tile_to_smem(work_tile)
+                    work_tile = tile_scheduler.get_current_work()
+                ab_pipeline.producer_tail(ab_producer_state)
+                if is_scheduler_warp:
+                    tile_scheduler.producer_tail()
+
+        # =====================================================================
+        # MMA warps
+        # =====================================================================
+        if warp_idx < self.num_mma_warps:
+            cute.arch.setmaxregister_increase(self.num_regs_mma)
+            is_tma_warp = Boolean(
+                (not self.pingpong and warp_idx == 0)
+                or (self.pingpong and (warp_idx == 0 or warp_idx == 4))
+            )
+            tidx, _, _ = cute.arch.thread_idx()
+            # For pingpong, adjust tidx to within-warp-group index
+            warp_group_idx = cute.arch.make_warp_uniform(tidx // self.num_threads_per_warp_group)
+            if const_expr(self.pingpong):
+                tidx = tidx % self.num_threads_per_warp_group
+
+            # ldmatrix copy atoms for SMEM → RMEM
+            atom_copy_ldmatrix_A = cute.make_copy_atom(
+                warp.LdMatrix8x8x16bOp(self.a_layout.is_m_major_a(), 4),
+                self.a_dtype,
+            )
+            atom_copy_ldmatrix_B = cute.make_copy_atom(
+                warp.LdMatrix8x8x16bOp(self.b_layout.is_n_major_b(), 4),
+                self.b_dtype,
+            )
+            smem_tiled_copy_A = cute.make_tiled_copy_A(atom_copy_ldmatrix_A, tiled_mma)
+            smem_tiled_copy_B = cute.make_tiled_copy_B(atom_copy_ldmatrix_B, tiled_mma)
+            thr_copy_ldmatrix_A = smem_tiled_copy_A.get_slice(tidx)
+            thr_copy_ldmatrix_B = smem_tiled_copy_B.get_slice(tidx)
+            tCsA_copy_view = thr_copy_ldmatrix_A.partition_S(sA)
+            tCsB_copy_view = thr_copy_ldmatrix_B.partition_S(sB)
+
+            # Make fragments
+            thr_mma = tiled_mma.get_slice(tidx)
+            acc, tCsA, tCsB, tCrA, tCrB = sm80_utils.partition_fragment_ABC(
+                thr_mma, self.cta_tile_shape_mnk, sA, sB
+            )
+
+            if const_expr(self.pingpong):
+                if warp_group_idx == 0:
+                    # WG0 needs a start signal at the very beginning
+                    self.pingpong_barrier_arrive(warp_group_idx=0, stage="mma")
+                    self.pingpong_barrier_arrive(warp_group_idx=0, stage="epi")
+
+            k_tile_cnt_static = cute.ceil_div(
+                cute.size(mA_mkl, mode=[1]), self.cta_tile_shape_mnk[2]
+            )
+            c_tile_cnt = cute.size(cute.ceil_div(self.cta_tile_shape_mnk[:2], self.epi_tile))
+
+            ab_read_state = make_pipeline_state(pipeline.PipelineUserType.Consumer, self.ab_stage)
+            epi_store_pipeline = self.make_epi_store_pipeline()
+            epi_read_state = make_pipeline_state(
+                pipeline.PipelineUserType.Consumer, self.epi_c_stage
+            )
+            epi_producer_state = make_pipeline_state(
+                pipeline.PipelineUserType.Producer, self.epi_c_stage
+            )
+            tile_scheduler = TileSchedulerCls()
+            work_tile = tile_scheduler.initial_work_tile_info()
+
+            if const_expr(self.pingpong):
+                if warp_idx >= 4:
+                    # Advance 2nd Math WG pipeline states to the end of 1st Math WG
+                    epi_read_state.advance_iters(c_tile_cnt)
+                    epi_producer_state.advance_iters(c_tile_cnt)
+                    if const_expr(not varlen_k):
+                        ab_read_state.advance_iters(k_tile_cnt_static)
+                    else:
+                        len_k = varlen_manager.len_k(batch_idx=work_tile.tile_idx[3])
+                        k_tile_cnt = cute.ceil_div(len_k, self.cta_tile_shape_mnk[2])
+                        ab_read_state.advance_iters(k_tile_cnt)
+                    tile_scheduler.advance_to_next_work()
+                    work_tile = tile_scheduler.get_current_work()
+            while work_tile.is_valid_tile:
+                tile_coord_mnkl = work_tile.tile_idx
+                batch_idx = tile_coord_mnkl[3]
+                len_k = varlen_manager.len_k(batch_idx)
+                k_tile_cnt = cute.ceil_div(len_k, self.cta_tile_shape_mnk[2])
+                acc.fill(0.0)
+                if const_expr(self.pingpong):
+                    self.pingpong_barrier_sync(warp_group_idx, stage="mma")
+                tctx.b("mma")
+                ab_read_state = self.mma(
+                    ab_pipeline,
+                    ab_read_state,
+                    tiled_mma,
+                    acc,
+                    k_tile_cnt,
+                    smem_tiled_copy_A,
+                    smem_tiled_copy_B,
+                    tCsA_copy_view,
+                    tCsB_copy_view,
+                    tCrA,
+                    tCrB,
+                )
+                if const_expr(self.pingpong):
+                    # Cue for next WG's MMA to start
+                    self.pingpong_barrier_arrive(1 - warp_group_idx, stage="mma")
+                tctx.e("mma")
+
+                # ============================================================
+                # EPILOGUE — reuse SM90's epilogue flow
+                # ============================================================
+                if const_expr(self.pingpong):
+                    self.pingpong_barrier_sync(warp_group_idx, "epi")
+                tctx.b("epilogue")
+
+                copy_D = None
+                if const_expr(has_D):
+                    copy_D, _, _ = self.epilog_gmem_copy_and_partition(
+                        tma_atom_d,
+                        varlen_manager.offset_batch_epi(mD_mnl, tile_coord_mnkl[3]),
+                        self.cta_tile_shape_mnk[:2],
+                        self.epi_tile,
+                        sD,
+                        tile_coord_mnkl,
+                    )
+                copy_C = None
+                if const_expr(has_C):
+                    copy_C_fn, _, _ = self.epilog_gmem_copy_and_partition(
+                        tma_atom_c,
+                        varlen_manager.offset_batch_epi(mC_mnl, tile_coord_mnkl[3]),
+                        self.cta_tile_shape_mnk[:2],
+                        self.epi_tile,
+                        sC,
+                        tile_coord_mnkl,
+                    )
+                    copy_C = copy_utils.tma_producer_copy_fn(copy_C_fn, epi_pipeline)
+                if const_expr(has_epi_load):
+                    tile_load_copy_fns = self.epi_tile_load_g2s_copy_fns(
+                        epilogue_params,
+                        epi_smem_tensors,
+                        tile_coord_mnkl,
+                        varlen_manager,
+                        epi_pipeline,
+                    )
+                    copy_C = copy_utils.chain_tma_producer_copy_fns((copy_C, *tile_load_copy_fns))
+
+                d_dtype_for_layout = self.d_dtype if self.d_dtype is not None else cutlass.BFloat16
+                tiled_copy_r2s, tRS_rD, tRS_sD = self.epilog_smem_store_and_partition(
+                    tiled_mma, self.d_layout, d_dtype_for_layout, sD, tidx
+                )
+                # (R2S, R2S_M, R2S_N, (epi_M, epi_N))
+                tRS_rAcc = self.epi_retile_acc(acc, tRS_rD, tiled_copy_r2s)
+                load_acc_subtile = partial(self.epi_load_acc_subtile, tRS_rAcc)
+                if const_expr(has_C):
+                    tiled_copy_s2r, tRS_rC, tSR_rC, tSR_sC = self.epilog_smem_load_and_partition(
+                        tiled_mma, self.c_layout, self.c_dtype, sC, tRS_rD.layout, tidx
+                    )
+                else:
+                    tiled_copy_s2r, tSR_sC, tRS_rC, tSR_rC = None, None, None, None
+
+                self.epi_visit_acc(epilogue_params, acc, tiled_mma, tile_coord_mnkl, tidx)
+
+                epi_read_state, epi_producer_state = self.epilogue(
+                    epilogue_params,
+                    epi_smem_tensors,
+                    epi_pipeline,
+                    epi_store_pipeline,
+                    epi_read_state,
+                    epi_producer_state,
+                    self.epi_tile,
+                    load_acc_subtile,
+                    tRS_rD,
+                    tRS_rC,
+                    None,  # tiled_copy_t2r, for Sm100 only
+                    tiled_copy_r2s,
+                    tRS_sD,
+                    tiled_copy_s2r,
+                    tSR_rC,
+                    tSR_sC,
+                    copy_D,
+                    copy_C,
+                    tile_coord_mnkl,
+                    varlen_manager,
+                    self.epilogue_barrier,
+                    tile_scheduler,
+                    tidx,
+                    is_tma_warp,
+                )
+
+                if const_expr(self.pingpong):
+                    # With pingpong, 2 WGs write two different output tiles to the same smem,
+                    # so we have to make sure the smem content is done reading before signaling
+                    # the next WG's epilogue.
+                    if is_tma_warp:
+                        epi_store_pipeline.producer_tail()
+                    self.pingpong_barrier_arrive(1 - warp_group_idx, stage="epi")
+                tctx.e("epilogue")
+
+                if const_expr(not self.pingpong):
+                    tile_scheduler.advance_to_next_work()
+                    work_tile = tile_scheduler.get_current_work()
+                else:  # Skip a tile for pingpong
+                    # Update starting load/store pipeline states for the next tile
+                    epi_read_state.advance_iters(c_tile_cnt)
+                    epi_producer_state.advance_iters(c_tile_cnt)
+                    # Update starting mainloop pipeline state for the next tile
+                    if const_expr(not varlen_k):
+                        ab_read_state.advance_iters(k_tile_cnt_static)
+                        tile_scheduler.advance_to_next_work(advance_count=self.mma_warp_groups)
+                        work_tile = tile_scheduler.get_current_work()
+                    else:
+                        tile_scheduler.advance_to_next_work()
+                        work_tile = tile_scheduler.get_current_work()
+                        if work_tile.is_valid_tile:
+                            len_k = varlen_manager.len_k(batch_idx=work_tile.tile_idx[3])
+                            k_tile_cnt = cute.ceil_div(len_k, self.cta_tile_shape_mnk[2])
+                            ab_read_state.advance_iters(k_tile_cnt)
+                            tile_scheduler.advance_to_next_work()
+                            work_tile = tile_scheduler.get_current_work()
+
+            # Wait for D store complete
+            if const_expr(not self.pingpong):
+                if is_tma_warp:
+                    epi_store_pipeline.producer_tail()
+
+        tctx.flush()
+
+    @cute.jit
+    def mma(
+        self,
+        ab_pipeline: cutlass.pipeline.PipelineAsync,
+        ab_read_state: cutlass.pipeline.PipelineState,
+        tiled_mma: cute.TiledMma,
+        acc: cute.Tensor,
+        k_tile_cnt: Int32,
+        smem_tiled_copy_A: cute.TiledCopy,
+        smem_tiled_copy_B: cute.TiledCopy,
+        tCsA_copy_view: cute.Tensor,
+        tCsB_copy_view: cute.Tensor,
+        tCrA: cute.Tensor,
+        tCrB: cute.Tensor,
+    ) -> cutlass.pipeline.PipelineState:
+        """Warp-level MMA mainloop: ldmatrix SMEM→RMEM + warp MMA."""
+        tCrA_copy_view = smem_tiled_copy_A.retile(tCrA)
+        tCrB_copy_view = smem_tiled_copy_B.retile(tCrB)
+        load_sA = partial(cute.copy, smem_tiled_copy_A)
+        load_sB = partial(cute.copy, smem_tiled_copy_B)
+
+        num_k_blocks = cute.size(tCrA, mode=[2])
+        peek_ab_full_status = Boolean(True)
+        if 0 < k_tile_cnt:
+            peek_ab_full_status = ab_pipeline.consumer_try_wait(ab_read_state)
+        ab_pipeline.consumer_wait(ab_read_state, peek_ab_full_status)
+
+        # Load first k-block
+        tCsA_p = tCsA_copy_view[None, None, None, ab_read_state.index]
+        tCsB_p = tCsB_copy_view[None, None, None, ab_read_state.index]
+        load_sA(tCsA_p[None, None, 0], tCrA_copy_view[None, None, 0])
+        load_sB(tCsB_p[None, None, 0], tCrB_copy_view[None, None, 0])
+
+        for k_tile in cutlass.range(k_tile_cnt - 1, unroll=1):
+            for k in cutlass.range_constexpr(num_k_blocks):
+                k_next = 0 if k + 1 == num_k_blocks else k + 1
+                if const_expr(k == num_k_blocks - 1):
+                    # TMA writes this smem stage through the async proxy, while ldmatrix
+                    # reads it through the generic proxy. Fence before release so the
+                    # producer's next async-proxy write cannot race those reads; sync the
+                    # warp because only one lane signals the empty mbarrier.
+                    cute.arch.fence_view_async_shared()
+                    cute.arch.sync_warp()
+                    ab_pipeline.consumer_release(ab_read_state)
+                    ab_read_state.advance()
+                    peek_ab_full_status = ab_pipeline.consumer_try_wait(ab_read_state)
+                    tCsA_p = tCsA_copy_view[None, None, None, ab_read_state.index]
+                    tCsB_p = tCsB_copy_view[None, None, None, ab_read_state.index]
+                    ab_pipeline.consumer_wait(ab_read_state, peek_ab_full_status)
+                load_sA(tCsA_p[None, None, k_next], tCrA_copy_view[None, None, k_next])
+                load_sB(tCsB_p[None, None, k_next], tCrB_copy_view[None, None, k_next])
+                cute.gemm(tiled_mma, acc, tCrA[None, None, k], tCrB[None, None, k], acc)
+
+        # Last k-tile (hoisted)
+        if 0 < k_tile_cnt:
+            for k in cutlass.range_constexpr(num_k_blocks):
+                k_next = 0 if k + 1 == num_k_blocks else k + 1
+                if const_expr(k == num_k_blocks - 1):
+                    # TMA writes this smem stage through the async proxy, while ldmatrix
+                    # reads it through the generic proxy. Fence before release so the
+                    # producer's next async-proxy write cannot race those reads; sync the
+                    # warp because only one lane signals the empty mbarrier.
+                    cute.arch.fence_view_async_shared()
+                    cute.arch.sync_warp()
+                    ab_pipeline.consumer_release(ab_read_state)
+                    ab_read_state.advance()
+                if const_expr(k_next > 0):
+                    load_sA(tCsA_p[None, None, k_next], tCrA_copy_view[None, None, k_next])
+                    load_sB(tCsB_p[None, None, k_next], tCrB_copy_view[None, None, k_next])
+                cute.gemm(tiled_mma, acc, tCrA[None, None, k], tCrB[None, None, k], acc)
+
+        return ab_read_state
+
+    @staticmethod
+    def _compute_tile_shape_or_override(
+        cta_tile_shape_mnk: Tuple[int, int, int],
+        atom_layout_mnk: Tuple[int, int, int],
+        element_type: Optional[Type[cutlass.Numeric]] = None,
+        epi_tile_override: Tuple[int, int] | None = None,
+    ) -> Tuple[int, int]:
+        """Compute the epilogue tile shape or use override if provided.
+
+        :param cta_tile_shape_mnk: CTA tile shape (M,N,K)
+        :type cta_tile_shape_mnk: Tuple[int, int, int]
+        :param element_type: Data type of elements
+        :type element_type: type[cutlass.Numeric]
+        :param epi_tile_override: Optional override for epilogue tile shape
+        :type epi_tile_override: Tuple[int, int] or None
+
+        :return: Computed epilogue tile shape
+        :rtype: Tuple[int, int]
+        """
+        if epi_tile_override is not None:
+            return epi_tile_override
+        n_perf = 64 if element_type is not None and element_type.width == 8 else 32
+        tile_m = math.gcd(64, cute.size(cta_tile_shape_mnk, mode=[0]))
+        tile_n = math.gcd(n_perf, cute.size(cta_tile_shape_mnk, mode=[1]))
+        return (tile_m, tile_n)
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_sm80.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_sm80.py
new file mode 100644
index 0000000000000000000000000000000000000000..259ebddebf61c043c49072b6581783e70d88e0a3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_sm80.py
@@ -0,0 +1,150 @@
+# Copyright (c) 2026, Tri Dao.
+#
+# Ampere GEMM using warp-level MMA and cp.async global-to-shared loads.
+# All CTA threads participate in cp.async, MMA, and epilogue.
+
+from typing import Optional, Tuple, Type, Union
+
+import cuda.bindings.driver as cuda
+
+import cutlass
+import cutlass.cute as cute
+import cutlass.pipeline as pipeline
+from cutlass.cute.nvgpu import warp
+
+from .gemm_base import GemmBase, NamedBarrierGemm
+from .tile_scheduler import TileSchedulerOptions
+from .varlen_utils import VarlenArguments
+
+
+class GemmSm80(GemmBase):
+    """SM80 GEMM with cp.async loads and warp-level tensor-core MMA.
+
+    SM80 has no TMA, so both the A/B mainloop and the epilogue global memory
+    movement use per-thread copies. The epilogue still reuses the standard
+    composable epilogue hooks used by the SM90/SM120 classes.
+    """
+
+    arch = 80
+    _supported_archs = (80, 86, 87, 89)
+
+    def __init__(
+        self,
+        acc_dtype: Type[cutlass.Numeric],
+        a_dtype: Type[cutlass.Numeric],
+        tile_shape_mnk: Union[Tuple[int, int], Tuple[int, int, int]],
+        cluster_shape_mnk: Tuple[int, int, int],
+        pingpong: bool = False,
+        is_persistent: bool = False,
+        gather_A: bool = False,
+        concat_layout: tuple | None = None,
+        use_pdl: bool = False,
+        num_warps: Optional[int] = None,
+        occupancy: Optional[int] = None,
+        arch: int = 80,
+    ):
+        if arch not in self._supported_archs:
+            raise ValueError(
+                f"SM80-family GEMM supports arch in {self._supported_archs}, got {arch}"
+            )
+        self.arch = arch
+        self.acc_dtype = acc_dtype
+        self.pingpong = False
+        self.is_persistent = is_persistent
+        self.use_clc_persistence = False
+        self.use_pdl = use_pdl
+        self.fp8_slow_accum = False
+        self.gather_A = gather_A
+        self.concat_layout = concat_layout or ()
+
+        assert not pingpong, "SM8x GEMM does not use pingpong scheduling"
+        assert cluster_shape_mnk == (1, 1, 1), "SM8x GEMM does not support CTA clusters"
+        # The shared tile scheduler API still takes a cluster shape. SM8x only launches
+        # independent CTAs, so keep this fixed at a single-CTA cluster.
+        self.cluster_shape_mnk = (1, 1, 1)
+        self.mma_inst_mnk = (16, 8, 16)
+        if len(tile_shape_mnk) == 3:
+            tile_m, tile_n, tile_k = tile_shape_mnk
+        elif len(tile_shape_mnk) == 2:
+            tile_m, tile_n = tile_shape_mnk
+            tile_k = 4 * self.mma_inst_mnk[2]
+        else:
+            raise ValueError("SM80 tile shape must be (M, N) or (M, N, K)")
+        if tile_m % 16 != 0 or tile_n % 16 != 0:
+            raise ValueError("SM80 tile shape M/N must be divisible by 16")
+        if tile_k <= 0 or tile_k % self.mma_inst_mnk[2] != 0:
+            raise ValueError("SM80 tile shape K must be a positive multiple of MMA instruction K")
+        self.cta_tile_shape_mnk = (tile_m, tile_n, tile_k)
+
+        self.num_warps = (
+            num_warps
+            if num_warps is not None
+            else (8 if (tile_m, tile_n) in ((128, 256), (128, 192)) else 4)
+        )
+        if self.num_warps not in (4, 8):
+            raise ValueError("SM80 GEMM supports num_warps=4 or 8")
+        self.atom_layout_mnk = (2, self.num_warps // 2, 1)
+        self.mma_inst_tile_k = tile_k // self.mma_inst_mnk[2]
+        self.threads_per_cta = self.num_warps * cute.arch.WARP_SIZE
+
+        self.smem_capacity = self._smem_capacity_for_arch(self.arch)
+        self.buffer_align_bytes = 1024
+        default_occupancy = 1 if self.num_warps == 8 else 2
+        ab_bytes_per_stage = (tile_m + tile_n) * tile_k * a_dtype.width // 8
+        if (
+            3 * ab_bytes_per_stage
+            > self.smem_capacity // default_occupancy - self.buffer_align_bytes
+        ):
+            default_occupancy = 1
+        self.occupancy = occupancy if occupancy is not None else default_occupancy
+        self.num_epi_warps = self.num_warps
+        self.epilogue_barrier = pipeline.NamedBarrier(
+            barrier_id=int(NamedBarrierGemm.Epilogue),
+            num_threads=self.num_epi_warps * cute.arch.WARP_SIZE,
+        )
+
+        self.ab_stage = None
+        self.epi_stage = None
+        self.epi_c_stage = None
+        self.epi_m_major = True
+        self.a_smem_layout_staged = None
+        self.b_smem_layout_staged = None
+        self.epi_smem_layout_staged = None
+        self.epi_c_smem_layout_staged = None
+        self.epi_tile = None
+        self.shared_storage = None
+
+    @staticmethod
+    def _smem_capacity_for_arch(arch: int) -> int:
+        # CUDA documents CC 8.7 with the same shared-memory capacity as CC 8.0,
+        # but this CUTLASS helper build does not accept "sm_87".
+        if arch == 87:
+            arch = 80
+        return cutlass.utils.get_smem_capacity_in_bytes(f"sm_{arch}")
+
+    def _setup_tiled_mma(self):
+        op = warp.MmaF16BF16Op(self.a_dtype, self.acc_dtype, self.mma_inst_mnk)
+        atom_m, atom_n, atom_k = self.atom_layout_mnk
+        tC = cute.make_layout(self.atom_layout_mnk)
+        permutation_mnk = (
+            atom_m * self.mma_inst_mnk[0],
+            atom_n * self.mma_inst_mnk[1] * 2,
+            atom_k * self.mma_inst_mnk[2],
+        )
+        self.tiled_mma = cute.make_tiled_mma(op, tC, permutation_mnk=permutation_mnk)
+        self.tiled_mma_gated_postact = self.tiled_mma
+
+    @cute.jit
+    def __call__(
+        self,
+        mA: cute.Tensor,
+        mB: cute.Tensor,
+        mD: Optional[cute.Tensor],
+        mC: Optional[cute.Tensor],
+        epilogue_args: tuple,
+        scheduler_args: TileSchedulerOptions,
+        varlen_args: Optional[VarlenArguments],
+        stream: cuda.CUstream,
+        trace_ptr: Optional[cutlass.Int64] = None,
+    ):
+        raise NotImplementedError("Gemm Sm80 is not implemented yet")
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_sm90.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_sm90.py
new file mode 100644
index 0000000000000000000000000000000000000000..13fca681c346dd607bafee493dad740a8e9880aa
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_sm90.py
@@ -0,0 +1,1499 @@
+# Copyright (c) 2025-2026, QuACK team.
+
+# Based on the cute-dsl example:
+# https://github.com/NVIDIA/cutlass/blob/main/examples/python/CuTeDSL/hopper/dense_gemm.py
+
+from typing import Tuple, Type, Callable, Optional
+from functools import partial
+import math
+
+
+import cuda.bindings.driver as cuda
+
+import cutlass
+import cutlass.cute as cute
+import cutlass.pipeline as pipeline
+from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait
+from cutlass.cute.nvgpu import cpasync, warp, warpgroup
+import cutlass.utils.hopper_helpers as sm90_utils
+from cutlass import Int32, Float32, Float16, Boolean, const_expr
+from cutlass.utils import LayoutEnum
+
+
+from . import layout_utils
+from .gemm_base import GemmTmaBase, NamedBarrierGemm
+from .tile_scheduler import TileSchedulerOptions
+from .varlen_utils import VarlenArguments, VarlenManager
+
+# return PipelineStateWAdvance instead of PipelineState
+from .pipeline import make_pipeline_state
+from . import copy_utils
+from . import sm90_utils as quack_sm90_utils
+
+"""
+A high-performance batched dense GEMM (C = A * B) example for the NVIDIA Hopper architecture
+using CUTE DSL.
+- Matrix A is MxKxL, L is batch dimension, A can be row-major("K") or column-major("M")
+- Matrix B is NxKxL, L is batch dimension, B can be row-major("N") or column-major("K")
+- Matrix C is MxNxL, L is batch dimension, C can be row-major("N") or column-major("M")
+
+This GEMM kernel supports the following features:
+    - Utilizes Tensor Memory Access (TMA) for efficient memory operations
+    - Utilizes Hopper's WGMMA for matrix multiply-accumulate (MMA) operations
+    - Implements TMA multicast with cluster to reduce L2 memory traffic
+    - Supports multi-stage pipeline to overlap computation and memory access
+
+This GEMM works as follows:
+1. Load A and B matrices from global memory (GMEM) to shared memory (SMEM) using TMA operations.
+2. Perform matrix multiply-accumulate (MMA) operations using WGMMA instruction.
+3. Store results from registers (RMEM) to shared memory (SMEM), then to global memory (GMEM) with TMA operations.
+
+Hopper WGMMA instructions operate as follows:
+- Read matrix A from SMEM
+- Read matrix B from SMEM
+- Perform MMA operation and store the result in Accumulator(register)
+
+Constraints:
+* Supported input data types: fp16, fp8 (e4m3fn, e5m2)
+* For fp16 types, A and B must have the same data type
+* For fp8 types, A and B can have different types (e4m3fn or e5m2) but both must be 8-bit
+* Fp8 types only support k-major layout
+* Only fp32 accumulation is supported in this example
+* CTA tile shape M must be 64/128
+* CTA tile shape N must be 64/128/256
+* CTA tile shape K must be 64
+* Cluster shape M/N must be positive and power of 2, total cluster size <= 4
+* The contiguous dimension of A/B/C tensors must be at least 16 bytes aligned,
+  i.e, number of elements is a multiple of 8, 16 for Float16, and Float8, respectively.
+"""
+
+
+class GemmSm90(GemmTmaBase):
+    """
+    This class implements batched matrix multiplication (C = A x B) with support for various data types
+    and architectural features specific to Hopper GPUs with persistent tile scheduling and warp specialization.
+
+    :param acc_dtype: Data type for accumulation during computation
+    :type acc_dtype: type[cutlass.Numeric]
+    :param tile_shape_mnk: Shape of the CTA tile. Pass (M, N) to default K to
+        4 MMA instructions, or (M, N, K) to set K explicitly.
+    :type tile_shape_mnk: Tuple[int, int] | Tuple[int, int, int]
+    :param cluster_shape_mnk: Cluster dimensions (M,N,K) for parallel processing
+    :type cluster_shape_mnk: Tuple[int, int, int]
+
+    :note: Data type requirements:
+        - For 16-bit types: A and B must have the same data type
+        - For 8-bit types: A and B can have different types (Float8E4M3FN/Float8E5M2) as long as both are 8-bit
+        - Float8 types only support k-major layout
+
+    :note: Supported data types:
+        - Float16
+        - BFloat16
+        - Float8E4M3FN/Float8E5M2
+
+    :note: Supported accumulation types:
+        - Float32 (for all floating point inputs)
+
+    :note: Constraints:
+        - Cluster shape M/N must be positive and power of 2, total cluster size <= 4
+
+    Example:
+        >>> gemm = GemmSm90(
+        ...     acc_dtype=Float32,
+        ...     tile_shape_mnk=(128, 256),
+        ...     cluster_shape_mnk=(1, 1, 1)
+        ... )
+        >>> gemm(a_tensor, b_tensor, c_tensor, stream)
+    """
+
+    arch = 90
+    EpilogueArguments = GemmTmaBase.EpilogueArguments
+    EpilogueParams = GemmTmaBase.EpilogueParams
+
+    def __init__(
+        self,
+        acc_dtype: Type[cutlass.Numeric],
+        a_dtype: Type[cutlass.Numeric],
+        tile_shape_mnk: Tuple[int, int] | Tuple[int, int, int],
+        cluster_shape_mnk: Tuple[int, int, int],
+        pingpong: bool = False,
+        is_persistent: bool = True,
+        fp8_fast_accum: bool = False,
+        gather_A: bool = False,
+        use_clc_persistence: bool = False,
+        concat_layout: tuple | None = None,
+        use_pdl: bool = True,
+    ):
+        """
+        Initializes the configuration for a Hopper dense GEMM kernel.
+
+        This configuration includes data types for operands, tile shape, cluster configuration,
+        and thread layout.
+
+        :param acc_dtype: Data type for accumulation during computation
+        :type acc_dtype: type[cutlass.Numeric]
+        :param tile_shape_mnk: Shape of the CTA tile (M,N) or (M,N,K)
+        :type tile_shape_mnk: Tuple[int, int] | Tuple[int, int, int]
+        :param cluster_shape_mnk: Cluster dimensions (M,N,K) for parallel processing
+        :type cluster_shape_mnk: Tuple[int, int, int]
+        """
+
+        self.acc_dtype = acc_dtype
+        self.pingpong = pingpong
+        self.is_persistent = is_persistent
+        self.use_clc_persistence = use_clc_persistence
+        if self.use_clc_persistence:
+            assert self.arch == 100
+        self.use_pdl = use_pdl
+        if self.pingpong:
+            assert self.is_persistent, "Pingpong gemm requires persistent scheduler"
+        self.fp8_slow_accum = not fp8_fast_accum and a_dtype.width == 8
+        self.gather_A = gather_A
+        self.concat_layout = concat_layout or ()
+        if gather_A:
+            assert cluster_shape_mnk[1] == 1, "Cluster shape N must be 1 for gather A "
+
+        self.cluster_shape_mnk = cluster_shape_mnk
+        assert len(tile_shape_mnk) in [2, 3], "CTA tile shape must be (M, N) or (M, N, K)"
+        # K dimension: if user provides 3 values, use their K; otherwise default in _setup_tiled_mma.
+        self.cta_tile_shape_mnk = (
+            tuple(tile_shape_mnk) if len(tile_shape_mnk) == 3 else (*tile_shape_mnk, 0)
+        )
+        tile_M, tile_N = self.cta_tile_shape_mnk[0], self.cta_tile_shape_mnk[1]
+        # check the cta tile shape
+        if not self.pingpong:
+            if tile_M not in [64, 128, 192, 256, 320]:
+                raise ValueError("CTA tile shape M must be 64/128/192/256/320")
+            if tile_M in [192, 320]:  # special case
+                tile_N_max = 256 if tile_M == 192 else 160
+                if not (tile_N % 32 == 0 and tile_N <= tile_N_max):
+                    raise ValueError(
+                        f"If tile_m == {tile_M}, CTA tile shape N must be divisible by 32 and <= {tile_N_max}"
+                    )
+            else:
+                if not (
+                    (tile_N % 16 == 0 and tile_N <= 256) or (tile_N % 32 == 0 and tile_N <= 512)
+                ):
+                    raise ValueError(
+                        "CTA tile shape N must be divisible by 16 and <= 256, or divisible by 32 and <= 512"
+                    )
+        else:
+            if tile_M not in [64, 128, 192]:
+                raise ValueError("CTA tile shape M must be 64/128/192 if pingpong")
+            tile_N_max = 256 if tile_M == 64 else (208 if tile_M == 128 else 128)
+            if not (tile_N % 16 == 0 and tile_N <= tile_N_max):
+                raise ValueError(f"CTA tile shape N must be divisible by 16 and <= {tile_N_max}")
+
+        if not self.pingpong:
+            if tile_M == 320:  # tile_M / 64 is not even so we have to split along N
+                atom_layout_m, atom_layout_n = 1, 2
+            elif tile_M == 192:
+                if tile_N <= 128:
+                    atom_layout_m, atom_layout_n = 3, 1
+                else:
+                    atom_layout_m, atom_layout_n = 1, 2
+            else:
+                atom_layout_m = (
+                    self.cta_tile_shape_mnk[0] // 64 if self.cta_tile_shape_mnk[0] < 256 else 2
+                )
+                atom_layout_n = 1
+            assert atom_layout_m in [1, 2, 3] and atom_layout_n in [1, 2]
+        else:
+            atom_layout_m, atom_layout_n = 1, 1
+        self.atom_layout_mnk = (atom_layout_m, atom_layout_n, 1)
+
+        self.num_mcast_ctas_a = self.cluster_shape_mnk[1]
+        if self.gather_A:
+            assert self.num_mcast_ctas_a == 1
+        self.num_mcast_ctas_b = self.cluster_shape_mnk[0]
+        self.is_a_mcast = self.num_mcast_ctas_a > 1
+        self.is_b_mcast = self.num_mcast_ctas_b > 1
+
+        self.occupancy = 1
+        self.mma_warp_groups = math.prod(self.atom_layout_mnk) * (1 if not self.pingpong else 2)
+        if self.pingpong:
+            assert self.mma_warp_groups == 2
+        assert self.mma_warp_groups in [1, 2, 3]
+        self.num_threads_per_warp_group = 128
+        self.threads_per_cta = (self.mma_warp_groups + 1) * self.num_threads_per_warp_group
+        self.smem_capacity = cutlass.utils.get_smem_capacity_in_bytes("sm_90")
+        self.num_epi_warps = (self.mma_warp_groups if not self.pingpong else 1) * 4
+        self.epilogue_barrier = pipeline.NamedBarrier(
+            barrier_id=int(NamedBarrierGemm.Epilogue),
+            num_threads=self.num_epi_warps * cute.arch.WARP_SIZE,
+        )
+        self.num_ab_load_warps = 1 if not self.gather_A else 4
+        self.ab_load_warp_id = self.mma_warp_groups * 4
+
+        regs_per_thread = math.prod(self.cta_tile_shape_mnk[:2]) // (
+            math.prod(self.atom_layout_mnk) * self.num_threads_per_warp_group
+        )
+        if self.fp8_slow_accum:
+            regs_per_thread *= 2
+        if not self.gather_A:
+            if self.mma_warp_groups == 3:
+                self.num_regs_load, self.num_regs_mma = 32, 160
+            else:
+                heavy_register_pressure = regs_per_thread >= 208
+                self.num_regs_load, self.num_regs_mma = (
+                    (40, 232) if not heavy_register_pressure else (24, 240)
+                )
+        else:
+            if self.mma_warp_groups == 3:
+                self.num_regs_load, self.num_regs_mma = 56, 152
+            else:
+                self.num_regs_load, self.num_regs_mma = (56, 224)
+
+        self.ab_stage = None
+        self.epi_stage = None
+        self.epi_m_major = True
+
+        self.a_smem_layout_staged = None
+        self.b_smem_layout_staged = None
+        self.epi_smem_layout_staged = None
+        self.epi_tile = None
+
+        self.shared_storage = None
+        self.buffer_align_bytes = 1024
+
+    def epi_smem_warp_shape_mnk(self):
+        atom_m, atom_n, atom_k = self.atom_layout_mnk
+        return (atom_m * 4, atom_n, atom_k)
+
+    def _setup_tiled_mma(self):
+        """Set up tiled MMA and tile K dimension. Override for different MMA types."""
+        self.tiled_mma = sm90_utils.make_trivial_tiled_mma(
+            self.a_dtype,
+            self.b_dtype,
+            self.a_layout.sm90_mma_major_mode(),
+            self.b_layout.sm90_mma_major_mode(),
+            self.acc_dtype,
+            self.atom_layout_mnk,
+            tiler_mn=(64, self.cta_tile_shape_mnk[1] // self.atom_layout_mnk[1]),
+        )
+        if const_expr(self.atom_layout_mnk[1] > 1):
+            # If N dimension is split among 2 WGs, we need to permute the N dimension so
+            # that in the epilogue, WG0 and WG1 can write to epi smem of size e.g. (64, 32)
+            # containing accumulators that are next to each other in the N dimension.
+            # Without permutation WG0 would write to epi smem of size (64, 16) and
+            # WG1 would write to a separate epi smem of size (64, 16) that's far away.
+            atom_n = self.atom_layout_mnk[1]
+            permutation_n = cute.make_ordered_layout(
+                (8, self.cta_tile_shape_mnk[1] // atom_n // 8, atom_n), order=(0, 2, 1)
+            )
+            self.tiled_mma = cute.make_tiled_mma(
+                cute.make_mma_atom(self.tiled_mma.op),
+                self.atom_layout_mnk,
+                permutation_mnk=(None, permutation_n, None),
+            )
+        mma_inst_shape_k = cute.size(self.tiled_mma.shape_mnk, mode=[2])
+        tile_k = (
+            self.cta_tile_shape_mnk[2] if self.cta_tile_shape_mnk[2] > 0 else mma_inst_shape_k * 4
+        )
+        assert tile_k > 0, "CTA tile K must be positive"
+        assert tile_k % mma_inst_shape_k == 0, (
+            f"CTA tile K ({tile_k}) must be divisible by MMA instruction K ({mma_inst_shape_k})"
+        )
+        self.cta_tile_shape_mnk = (
+            self.cta_tile_shape_mnk[0],
+            self.cta_tile_shape_mnk[1],
+            tile_k,
+        )
+
+    def _setup_attributes(self, epilogue_args: EpilogueArguments):
+        """Set up configurations that are dependent on GEMM inputs
+
+        This method configures various attributes based on the input tensor properties
+        (data types, leading dimensions) and kernel settings:
+        - Configuring tiled MMA
+        - Computing MMA/cluster/tile shapes
+        - Computing cluster layout
+        - Computing multicast CTAs for A/B
+        - Computing epilogue subtile
+        - Setting up A/B/C stage counts in shared memory
+        - Computing A/B/C shared memory layout
+        """
+        self._setup_tiled_mma()
+        self.epi_m_major = self.resolve_epi_m_major(epilogue_args)
+
+        self.cluster_layout_mnk = cute.make_layout(self.cluster_shape_mnk)
+
+        self.epi_tile = self._compute_tile_shape_or_override(
+            self.cta_tile_shape_mnk,
+            self.atom_layout_mnk,
+            self.d_dtype,
+        )
+        self.epi_tile_shape = cute.ceil_div(self.cta_tile_shape_mnk[:2], self.epi_tile)
+
+        # Compute stage before compute smem layout
+        self.ab_stage, self.epi_stage, self.epi_c_stage = self._compute_stages(
+            self.cta_tile_shape_mnk,
+            self.epi_tile,
+            self.a_dtype,
+            self.b_dtype,
+            self.d_dtype,
+            self.c_dtype,
+            epilogue_args,
+            cutlass.utils.get_smem_capacity_in_bytes(f"sm_{self.arch}"),  # smem_capacity
+            self.occupancy,
+            self.epi_smem_warp_shape_mnk(),
+        )
+        self.sched_stage = 2 if self.pingpong else 1
+
+        (
+            self.a_smem_layout_staged,
+            self.b_smem_layout_staged,
+            self.epi_smem_layout_staged,
+            self.epi_c_smem_layout_staged,
+        ) = self._make_smem_layouts(
+            self.cta_tile_shape_mnk,
+            self.epi_tile,
+            self.a_dtype,
+            self.a_layout,
+            self.b_dtype,
+            self.b_layout,
+            self.ab_stage,
+            self.d_dtype,
+            self.d_layout,
+            self.epi_stage,
+            self.c_dtype,
+            self.c_layout,
+            self.epi_c_stage,
+        )
+
+    @cute.jit
+    def __call__(
+        self,
+        mA: cute.Tensor,
+        mB: cute.Tensor,
+        mD: Optional[cute.Tensor],
+        mC: Optional[cute.Tensor],
+        epilogue_args: tuple,
+        scheduler_args: TileSchedulerOptions,
+        varlen_args: Optional[VarlenArguments],
+        stream: cuda.CUstream,
+        trace_ptr: Optional[cutlass.Int64] = None,
+    ):
+        """Execute the GEMM operation in steps:
+        - Setup static attributes
+        - Setup TMA load/store atoms and tensors
+        - Compute grid size
+        - Define shared storage for kernel
+        - Launch the kernel synchronously
+
+        :param mA: Input tensor A
+        :type mA: cute.Tensor
+        :param mB: Input tensor B
+        :type mB: cute.Tensor
+        :param mD: Output tensor D
+        :type mD: cute.Tensor
+        :param stream: CUDA stream for asynchronous execution
+        :type stream: cuda.CUstream
+        """
+
+        # Concat layout: interleave the non-contiguous dim (detected via leading_dim).
+        mA, mB, mD, mC = [
+            layout_utils.concat_to_interleave(mT, 1 - mT.leading_dim)
+            if const_expr(name in self.concat_layout and mT is not None)
+            else mT
+            for name, mT in [("A", mA), ("B", mB), ("out", mD), ("C", mC)]
+        ]
+
+        # setup static attributes before smem/grid/tma computation
+        self.a_dtype = mA.element_type
+        self.b_dtype = mB.element_type
+        self.d_dtype = mD.element_type if mD is not None else None
+        self.c_dtype = mC.element_type if mC is not None else None
+        self.a_layout = LayoutEnum.from_tensor(mA)
+        self.b_layout = LayoutEnum.from_tensor(mB)
+        self.d_layout = LayoutEnum.from_tensor(mD) if mD is not None else None
+        self.c_layout = LayoutEnum.from_tensor(mC) if mC is not None else None
+
+        if const_expr(self.a_dtype.width == 16 and self.a_dtype != self.b_dtype):
+            raise TypeError(f"Type mismatch: {self.a_dtype} != {self.b_dtype}")
+        if const_expr(self.a_dtype.width != self.b_dtype.width):
+            raise TypeError(f"Type width mismatch: {self.a_dtype.width} != {self.b_dtype.width}")
+        if const_expr(self.a_dtype.width != 16 and self.a_dtype.width != 8):
+            raise TypeError("a_dtype should be float16 or float8")
+
+        if const_expr(varlen_args is None):
+            varlen_args = VarlenArguments()
+        assert (varlen_args.mAIdx is not None) == self.gather_A
+        varlen_m = varlen_args.mCuSeqlensM is not None
+        varlen_k = varlen_args.mCuSeqlensK is not None
+
+        self._setup_attributes(epilogue_args)
+
+        a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, 0))
+        b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, 0))
+        tma_atom_a, tma_tensor_a, tma_atom_b, tma_tensor_b = self.make_tma_load_atoms_and_tensors(
+            mA, mB, a_smem_layout, b_smem_layout, varlen_k
+        )
+
+        self.num_tma_load_bytes = cute.size_in_bytes(self.b_dtype, b_smem_layout)
+        if const_expr(not self.gather_A):
+            self.num_tma_load_bytes += cute.size_in_bytes(self.a_dtype, a_smem_layout)
+
+        tma_atom_d, tma_tensor_d, tma_atom_c, tma_tensor_c = (
+            self.make_tma_epilogue_atoms_and_tensors(mD, mC, epilogue_args, varlen_m)
+        )
+
+        epilogue_params = self.epi_to_underlying_arguments(epilogue_args)
+        varlen_params = VarlenManager.to_underlying_arguments(varlen_args)
+
+        self.epi_load_bytes_per_stage = self.epi_smem_bytes(
+            epilogue_args,
+            self.cta_tile_shape_mnk,
+            self.epi_tile,
+            self.epi_smem_warp_shape_mnk(),
+        ).c_stage
+        if const_expr(mC is not None):
+            c_smem_layout = cute.slice_(self.epi_c_smem_layout_staged, (None, None, 0))
+            self.epi_load_bytes_per_stage += cute.size_in_bytes(self.c_dtype, c_smem_layout)
+
+        TileSchedulerCls = self.get_scheduler_class(varlen_m=varlen_m)
+        tile_sched_args = self.get_scheduler_arguments(
+            mA, mB, mD, scheduler_args, varlen_args, epilogue_args
+        )
+        tile_sched_params = TileSchedulerCls.to_underlying_arguments(tile_sched_args)
+        grid = TileSchedulerCls.get_grid_shape(
+            tile_sched_params, scheduler_args.max_active_clusters
+        )
+
+        epi_smem_size = cute.cosize(self.epi_smem_layout_staged) if mD is not None else 0
+        epi_c_smem_size = cute.cosize(self.epi_c_smem_layout_staged) if mC is not None else 0
+
+        @cute.struct
+        class SharedStorage:
+            ab_pipeline_array_ptr: cute.struct.MemRange[cutlass.Int64, self.ab_stage * 2]
+            epi_pipeline_array_ptr: cute.struct.MemRange[cutlass.Int64, self.epi_c_stage * 2]
+            sched_pipeline_array_ptr: cute.struct.MemRange[cutlass.Int64, self.sched_stage * 2]
+            sched_data: cute.struct.MemRange[Int32, self.sched_stage * 4]
+            sD: cute.struct.Align[
+                cute.struct.MemRange[
+                    self.d_dtype if self.d_dtype is not None else Int32, epi_smem_size
+                ],
+                self.buffer_align_bytes,
+            ]
+            sC: cute.struct.Align[
+                cute.struct.MemRange[
+                    self.c_dtype if self.c_dtype is not None else Int32, epi_c_smem_size
+                ],
+                self.buffer_align_bytes,
+            ]
+            epi: self.epi_get_smem_struct(epilogue_params)
+            sA: cute.struct.Align[
+                cute.struct.MemRange[self.a_dtype, cute.cosize(self.a_smem_layout_staged)],
+                self.buffer_align_bytes,
+            ]
+            sB: cute.struct.Align[
+                cute.struct.MemRange[self.b_dtype, cute.cosize(self.b_smem_layout_staged)],
+                self.buffer_align_bytes,
+            ]
+
+        self.shared_storage = SharedStorage
+
+        # Launch the kernel synchronously
+        self.kernel(
+            self.tiled_mma,
+            tma_atom_a,
+            tma_tensor_a if const_expr(not self.gather_A) else mA,
+            tma_atom_b,
+            tma_tensor_b,
+            tma_atom_d,
+            tma_tensor_d,
+            tma_atom_c,
+            tma_tensor_c,
+            epilogue_params,
+            varlen_params,
+            self.cluster_layout_mnk,
+            self.a_smem_layout_staged,
+            self.b_smem_layout_staged,
+            self.epi_smem_layout_staged,
+            self.epi_c_smem_layout_staged,
+            tile_sched_params,
+            TileSchedulerCls,
+            trace_ptr,
+        ).launch(
+            grid=grid,
+            block=[self.threads_per_cta, 1, 1],
+            cluster=self.cluster_shape_mnk,
+            stream=stream,
+            min_blocks_per_mp=1,
+            use_pdl=self.use_pdl,
+        )
+        return
+
+    #  GPU device kernel
+    @cute.kernel
+    def kernel(
+        self,
+        tiled_mma: cute.TiledMma,
+        tma_atom_a: Optional[cute.CopyAtom],
+        mA_mkl: cute.Tensor,
+        tma_atom_b: cute.CopyAtom,
+        mB_nkl: cute.Tensor,
+        tma_atom_d: Optional[cute.CopyAtom],
+        mD_mnl: Optional[cute.Tensor],
+        tma_atom_c: Optional[cute.CopyAtom],
+        mC_mnl: Optional[cute.Tensor],
+        epilogue_params,
+        varlen_params: VarlenManager.Params,
+        cluster_layout_mnk: cute.Layout,
+        a_smem_layout: cute.ComposedLayout,
+        b_smem_layout: cute.ComposedLayout,
+        epi_smem_layout: cute.ComposedLayout,
+        epi_c_smem_layout: cute.ComposedLayout,
+        tile_sched_params,
+        TileSchedulerCls: cutlass.Constexpr[Callable],
+        trace_ptr: Optional[cutlass.Int64] = None,
+    ):
+        """
+        GPU device kernel performing the batched GEMM computation.
+
+        :param tma_atom_a: TMA copy atom for A tensor
+        :type tma_atom_a: cute.CopyAtom
+        :param mA_mkl: Input tensor A
+        :type mA_mkl: cute.Tensor
+        :param tma_atom_b: TMA copy atom for B tensor
+        :type tma_atom_b: cute.CopyAtom
+        :param mB_nkl: Input tensor B
+        :type mB_nkl: cute.Tensor
+        :param tma_atom_d: TMA copy atom for D tensor
+        :type tma_atom_d: cute.CopyAtom
+        :param mD_mnl: Output tensor D
+        :type mD_mnl: cute.Tensor
+        :param tiled_mma: Tiled MMA object
+        :type tiled_mma: cute.TiledMma
+        :param cluster_layout_mnk: CTA layout
+        :type cluster_layout_mnk: cute.Layout
+        :param a_smem_layout: Shared memory layout for A
+        :type a_smem_layout: cute.ComposedLayout
+        :param b_smem_layout: Shared memory layout for B
+        :type b_smem_layout: cute.ComposedLayout
+        :param epi_smem_layout: Shared memory layout for epilogue
+        :type epi_smem_layout: cute.ComposedLayout
+        """
+
+        from .trace import TraceContext
+
+        tctx = TraceContext.create(trace_ptr)
+
+        varlen_m = const_expr(varlen_params.cu_seqlens_m is not None)
+        varlen_k = const_expr(varlen_params.cu_seqlens_k is not None)
+        assert not (varlen_m and varlen_k)
+        if const_expr(self.gather_A):
+            assert varlen_m or varlen_k
+        has_D = const_expr(mD_mnl is not None)
+        has_C = const_expr(mC_mnl is not None)
+        has_epi_load = const_expr(self.epi_c_stage > 0)
+
+        warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
+
+        # Prefetch Tma desc
+        if warp_idx == self.ab_load_warp_id:
+            for tma_atom in (tma_atom_a, tma_atom_b, tma_atom_d, tma_atom_c):
+                if const_expr(tma_atom is not None):
+                    cpasync.prefetch_descriptor(tma_atom)
+
+        # Alloc and init AB full/empty + ACC full mbar (pipeline)
+        smem = cutlass.utils.SmemAllocator()
+        storage = smem.allocate(self.shared_storage)
+
+        ab_pipeline = self.make_ab_pipeline(
+            tiled_mma=tiled_mma,
+            cluster_layout_vmnk=cute.make_layout((1, *cluster_layout_mnk.shape)),
+            ab_pipeline_mbar_ptr=storage.ab_pipeline_array_ptr.data_ptr(),
+        )
+        epi_pipeline = None
+        if const_expr(has_epi_load):
+            epi_pipeline = self.make_epi_pipeline(
+                epi_pipeline_mbar_ptr=storage.epi_pipeline_array_ptr.data_ptr(),
+                tx_count=self.epi_load_bytes_per_stage,
+            )
+        sched_pipeline = None
+        sched_data = None
+        if const_expr(self.is_persistent):
+            sched_pipeline = self.make_sched_pipeline(
+                cluster_layout_mnk,
+                sched_pipeline_mbar_ptr=storage.sched_pipeline_array_ptr.data_ptr(),
+                varlen_k=varlen_k,
+            )
+            sched_data = storage.sched_data.get_tensor((4, self.sched_stage))
+
+        # Cluster arrive after barrier init
+        pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mnk[:-1], is_relaxed=True)
+
+        # Generate smem tensor A/B
+        sA = storage.sA.get_tensor(a_smem_layout.outer, swizzle=a_smem_layout.inner)
+        sB = storage.sB.get_tensor(b_smem_layout.outer, swizzle=b_smem_layout.inner)
+        sD = None
+        if const_expr(has_D):
+            sD = storage.sD.get_tensor(epi_smem_layout.outer, swizzle=epi_smem_layout.inner)
+        sC = None
+        if const_expr(has_C):
+            sC = storage.sC.get_tensor(epi_c_smem_layout.outer, swizzle=epi_c_smem_layout.inner)
+        epi_smem_tensors = self.epi_get_smem_tensors(epilogue_params, storage)
+
+        varlen_manager = VarlenManager.create(
+            varlen_params,
+            # Only used if not varlen_m
+            len_m_static=Int32(
+                cute.size(mA_mkl, mode=[0])
+                if varlen_k or varlen_params.mAIdx is None
+                else varlen_params.mAIdx.shape[0]
+            ),
+            len_k_static=Int32(cute.size(mA_mkl, mode=[1])),
+        )
+
+        TileSchedulerCls = partial(
+            TileSchedulerCls.create, tile_sched_params, sched_data, sched_pipeline
+        )
+
+        # Cluster wait for barrier init
+        pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mnk[:-1])
+
+        if warp_idx >= self.ab_load_warp_id:
+            cute.arch.setmaxregister_decrease(self.num_regs_load)
+            if (
+                warp_idx >= self.ab_load_warp_id
+                and warp_idx < self.ab_load_warp_id + self.num_ab_load_warps
+            ):
+                # PDL: wait for prior kernel before any TMA loads (matches cutlass C++ sm90 mainloop producer)
+                if const_expr(self.use_pdl):
+                    cute.arch.griddepcontrol_wait()
+                # Get mcast mask
+                cta_rank_in_cluster = cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster())
+                block_in_cluster_coord_mnk = cluster_layout_mnk.get_flat_coord(cta_rank_in_cluster)
+                a_mcast_mask = cute.make_layout_image_mask(
+                    cluster_layout_mnk, block_in_cluster_coord_mnk, mode=1
+                )
+                b_mcast_mask = cute.make_layout_image_mask(
+                    cluster_layout_mnk, block_in_cluster_coord_mnk, mode=0
+                )
+                a_mcast_mask = a_mcast_mask if self.is_a_mcast else 0
+                b_mcast_mask = b_mcast_mask if self.is_b_mcast else 0
+
+                # Persistent tile scheduling loop
+                is_scheduler_warp = self.num_ab_load_warps == 1 or warp_idx == self.ab_load_warp_id
+                if const_expr(cute.size(cluster_layout_mnk) > 1):
+                    is_scheduler_warp = is_scheduler_warp and cute.arch.block_idx_in_cluster() == 0
+                tile_scheduler = TileSchedulerCls()
+                work_tile = tile_scheduler.initial_work_tile_info()
+                ab_producer_state = make_pipeline_state(
+                    pipeline.PipelineUserType.Producer, self.ab_stage
+                )
+                while work_tile.is_valid_tile:
+                    tctx.b("tma_load")
+                    tile_coord_mnkl = work_tile.tile_idx
+                    batch_idx = tile_coord_mnkl[3]
+                    # Local_tile partition global tensors
+                    copy_A, prefetch_A = None, None
+                    if const_expr(not self.gather_A):
+                        mA_mk = varlen_manager.offset_batch_A(mA_mkl, batch_idx)
+                        # (bM, bK, RestK)
+                        gA_mk = cute.local_tile(
+                            mA_mk,
+                            cute.select(self.cta_tile_shape_mnk, [0, 2]),
+                            (tile_coord_mnkl[0], None),
+                        )
+                        #  TMA load A partition_S/D
+                        copy_A, _, _ = copy_utils.tma_get_copy_fn(
+                            tma_atom_a,
+                            cta_coord=block_in_cluster_coord_mnk[1],
+                            cta_layout=cute.make_layout(
+                                cute.slice_(cluster_layout_mnk, (0, None, 0)).shape
+                            ),
+                            src_tensor=gA_mk,
+                            dst_tensor=sA,
+                            mcast_mask=a_mcast_mask,
+                        )
+                    else:
+                        copy_A, prefetch_A = self._make_gather_A_copy(
+                            mA_mkl, sA, varlen_manager, tile_coord_mnkl, batch_idx
+                        )
+                    # (bN, bK, RestK)
+                    gB_nk = cute.local_tile(
+                        varlen_manager.offset_batch_B(mB_nkl, batch_idx),
+                        cute.select(self.cta_tile_shape_mnk, [1, 2]),
+                        (tile_coord_mnkl[1], None),
+                    )
+                    # TMA load B partition_S/D
+                    copy_B, _, _ = copy_utils.tma_get_copy_fn(
+                        tma_atom_b,
+                        cta_coord=block_in_cluster_coord_mnk[0],
+                        cta_layout=cute.make_layout(
+                            cute.slice_(cluster_layout_mnk, (None, 0, 0)).shape
+                        ),
+                        src_tensor=gB_nk,
+                        dst_tensor=sB,
+                        mcast_mask=b_mcast_mask,
+                    )
+                    len_k = varlen_manager.len_k(batch_idx)
+                    k_tile_cnt = cute.ceil_div(len_k, self.cta_tile_shape_mnk[2])
+                    if const_expr(not self.gather_A):
+                        ab_producer_state = self.load_tma(
+                            ab_pipeline, ab_producer_state, [copy_A, copy_B], k_tile_cnt
+                        )
+                    else:
+                        ab_producer_state = self.load_AB_gather_A(
+                            ab_pipeline,
+                            ab_producer_state,
+                            copy_A,
+                            prefetch_A,
+                            copy_B,
+                            k_tile_cnt,
+                            varlen_m=varlen_m,
+                        )
+                    tctx.e("tma_load")
+                    tile_scheduler.advance_to_next_work(is_scheduler_warp=is_scheduler_warp)
+                    work_tile = tile_scheduler.get_current_work()
+                    # End of persistent scheduler loop
+                if const_expr(self.pingpong and not varlen_k):
+                    # Need to write the tile_idx to smem for the next WG in the pingpong mode
+                    if is_scheduler_warp:
+                        tile_scheduler.write_work_tile_to_smem(work_tile)
+                    work_tile = tile_scheduler.get_current_work()
+                if warp_idx == self.ab_load_warp_id:
+                    ab_pipeline.producer_tail(ab_producer_state)
+                if is_scheduler_warp:
+                    tile_scheduler.producer_tail()
+
+        if warp_idx < self.ab_load_warp_id:
+            cute.arch.setmaxregister_increase(self.num_regs_mma)
+            is_tma_warp = Boolean(
+                (not self.pingpong and warp_idx == 0)
+                or (self.pingpong and (warp_idx == 0 or warp_idx == 4))
+            )
+            # Partition global tensor for TiledMMA_A/B/C
+            tidx, _, _ = cute.arch.thread_idx()
+            warp_group_idx = cute.arch.make_warp_uniform(tidx // self.num_threads_per_warp_group)
+            if const_expr(self.pingpong):
+                tidx = tidx % self.num_threads_per_warp_group
+            warp_group_thread_layout = cute.make_layout(
+                self.mma_warp_groups if const_expr(not self.pingpong) else 1,
+                stride=self.num_threads_per_warp_group,
+            )
+            thr_mma = tiled_mma.get_slice(
+                warp_group_thread_layout(warp_group_idx if not self.pingpong else 0)
+            )
+
+            # Make fragments
+            acc, tCrA, tCrB = quack_sm90_utils.partition_fragment_ABC(
+                thr_mma, self.cta_tile_shape_mnk, sA, sB
+            )
+            acc_slow = None
+            if const_expr(self.fp8_slow_accum):
+                acc_slow = cute.make_rmem_tensor(acc.shape, self.acc_dtype)
+            mma_fn = partial(quack_sm90_utils.gemm_w_idx, tiled_mma, acc, tCrA, tCrB)
+
+            if const_expr(self.pingpong):
+                if warp_group_idx == 0:
+                    # WG0 needs a start signal at the very beginning
+                    self.pingpong_barrier_arrive(warp_group_idx=0, stage="mma")
+                    self.pingpong_barrier_arrive(warp_group_idx=0, stage="epi")
+
+            k_tile_cnt_static = cute.ceil_div(
+                cute.size(mA_mkl, mode=[1]), self.cta_tile_shape_mnk[2]
+            )
+            c_tile_cnt = cute.size(self.epi_tile_shape)
+
+            ab_read_state = make_pipeline_state(pipeline.PipelineUserType.Consumer, self.ab_stage)
+            epi_store_pipeline = self.make_epi_store_pipeline()
+            epi_read_state = make_pipeline_state(
+                pipeline.PipelineUserType.Consumer, self.epi_c_stage
+            )
+            epi_producer_state = make_pipeline_state(
+                pipeline.PipelineUserType.Producer, self.epi_c_stage
+            )
+            tile_scheduler = TileSchedulerCls()
+            work_tile = tile_scheduler.initial_work_tile_info()
+            if const_expr(self.pingpong):
+                if warp_idx >= 4:
+                    # Advance 2nd Math WG pipeline states to the end of 1st Math WG
+                    epi_read_state.advance_iters(c_tile_cnt)
+                    epi_producer_state.advance_iters(c_tile_cnt)
+                    if const_expr(not varlen_k):
+                        ab_read_state.advance_iters(k_tile_cnt_static)
+                    else:
+                        len_k = varlen_manager.len_k(batch_idx=work_tile.tile_idx[3])
+                        k_tile_cnt = cute.ceil_div(len_k, self.cta_tile_shape_mnk[2])
+                        ab_read_state.advance_iters(k_tile_cnt)
+                    # TODO: do we need to check if work_tile is valid?
+                    tile_scheduler.advance_to_next_work()
+                    work_tile = tile_scheduler.get_current_work()
+            while work_tile.is_valid_tile:
+                tile_coord_mnkl = work_tile.tile_idx
+                batch_idx = tile_coord_mnkl[3]
+                len_k = varlen_manager.len_k(batch_idx)
+                k_tile_cnt = cute.ceil_div(len_k, self.cta_tile_shape_mnk[2])
+                if const_expr(self.pingpong):
+                    self.pingpong_barrier_sync(warp_group_idx, stage="mma")
+                tctx.b("mma")
+                ab_read_state = self.mma(
+                    ab_pipeline, ab_read_state, mma_fn, acc, acc_slow, k_tile_cnt, warp_group_idx
+                )
+                if const_expr(varlen_k):
+                    if k_tile_cnt == 0:
+                        acc.fill(0.0)
+                tctx.e("mma")
+
+                # EPILOGUE
+                if const_expr(self.pingpong):
+                    self.pingpong_barrier_sync(warp_group_idx, "epi")
+                tctx.b("epilogue")
+
+                copy_D = None
+                if const_expr(has_D):
+                    copy_D, _, _ = self.epilog_gmem_copy_and_partition(
+                        tma_atom_d,
+                        varlen_manager.offset_batch_epi(mD_mnl, batch_idx),
+                        self.cta_tile_shape_mnk[:2],
+                        self.epi_tile,
+                        sD,
+                        tile_coord_mnkl,
+                    )
+                copy_C = None
+                if const_expr(has_C):
+                    copy_C_fn, _, _ = self.epilog_gmem_copy_and_partition(
+                        tma_atom_c,
+                        varlen_manager.offset_batch_epi(mC_mnl, batch_idx),
+                        self.cta_tile_shape_mnk[:2],
+                        self.epi_tile,
+                        sC,
+                        tile_coord_mnkl,
+                    )
+                    copy_C = copy_utils.tma_producer_copy_fn(copy_C_fn, epi_pipeline)
+                if const_expr(has_epi_load):
+                    tile_load_copy_fns = self.epi_tile_load_g2s_copy_fns(
+                        epilogue_params,
+                        epi_smem_tensors,
+                        tile_coord_mnkl,
+                        varlen_manager,
+                        epi_pipeline,
+                    )
+                    copy_C = copy_utils.chain_tma_producer_copy_fns((copy_C, *tile_load_copy_fns))
+
+                d_dtype_for_layout = self.d_dtype if self.d_dtype is not None else cutlass.BFloat16
+                tiled_copy_r2s, tRS_rD, tRS_sD = self.epilog_smem_store_and_partition(
+                    tiled_mma, self.d_layout, d_dtype_for_layout, sD, tidx
+                )
+                # (R2S, R2S_M, R2S_N, (epi_M, epi_N))
+                tRS_rAcc = self.epi_retile_acc(acc, tRS_rD, tiled_copy_r2s)
+                load_acc_subtile = partial(self.epi_load_acc_subtile, tRS_rAcc)
+                if const_expr(has_C):
+                    tiled_copy_s2r, tRS_rC, tSR_rC, tSR_sC = self.epilog_smem_load_and_partition(
+                        tiled_mma, self.c_layout, self.c_dtype, sC, tRS_rD.layout, tidx
+                    )
+                else:
+                    tiled_copy_s2r, tSR_sC, tRS_rC, tSR_rC = None, None, None, None
+
+                self.epi_visit_acc(epilogue_params, acc, tiled_mma, tile_coord_mnkl, tidx)
+
+                epi_read_state, epi_producer_state = self.epilogue(
+                    epilogue_params,
+                    epi_smem_tensors,
+                    epi_pipeline,
+                    epi_store_pipeline,
+                    epi_read_state,
+                    epi_producer_state,
+                    self.epi_tile,
+                    load_acc_subtile,
+                    tRS_rD,
+                    tRS_rC,
+                    None,  # tiled_copy_t2r, for Sm100 only
+                    tiled_copy_r2s,
+                    tRS_sD,
+                    tiled_copy_s2r,
+                    tSR_rC,
+                    tSR_sC,
+                    copy_D,
+                    copy_C,
+                    tile_coord_mnkl,
+                    varlen_manager,
+                    self.epilogue_barrier,
+                    tile_scheduler,
+                    tidx,
+                    is_tma_warp,
+                )
+
+                if const_expr(self.pingpong):
+                    # With pingpong, 2 WGs write two different output tiles to the same smem,
+                    # so we have to make sure the smem content is done reading before signaling
+                    # the next WG's epilogue.
+                    if is_tma_warp:
+                        epi_store_pipeline.producer_tail()
+                    self.pingpong_barrier_arrive(1 - warp_group_idx, stage="epi")
+                tctx.e("epilogue")
+
+                if const_expr(not self.pingpong):
+                    tile_scheduler.advance_to_next_work()
+                    work_tile = tile_scheduler.get_current_work()
+                else:  # Skip a tile for pingpong
+                    # Update starting load/store pipeline states for the next tile
+                    epi_read_state.advance_iters(c_tile_cnt)
+                    epi_producer_state.advance_iters(c_tile_cnt)
+                    # Update starting mainloop pipeline state for the next tile
+                    if const_expr(not varlen_k):
+                        ab_read_state.advance_iters(k_tile_cnt_static)
+                        tile_scheduler.advance_to_next_work(advance_count=self.mma_warp_groups)
+                        work_tile = tile_scheduler.get_current_work()
+                    else:
+                        tile_scheduler.advance_to_next_work()
+                        work_tile = tile_scheduler.get_current_work()
+                        if work_tile.is_valid_tile:
+                            len_k = varlen_manager.len_k(batch_idx=work_tile.tile_idx[3])
+                            k_tile_cnt = cute.ceil_div(len_k, self.cta_tile_shape_mnk[2])
+                            ab_read_state.advance_iters(k_tile_cnt)
+                            tile_scheduler.advance_to_next_work()
+                            work_tile = tile_scheduler.get_current_work()
+                # End of persistent scheduler loop
+
+            # PDL: hint next kernel to launch (matches cutlass C++ sm90 consumer)
+            if const_expr(self.use_pdl):
+                cute.arch.griddepcontrol_launch_dependents()
+
+            # Wait for D store complete
+            if const_expr(not self.pingpong):
+                if is_tma_warp:
+                    epi_store_pipeline.producer_tail()
+
+        tctx.flush()
+
+    @cute.jit
+    def load_AB_gather_A(
+        self,
+        ab_pipeline: cutlass.pipeline.PipelineAsync,
+        ab_producer_state: cutlass.pipeline.PipelineState,
+        copy_A: Callable,
+        prefetch_A: Optional[Callable],
+        copy_B: Callable,
+        k_tile_cnt: Int32,
+        varlen_m: bool = True,
+    ) -> cutlass.pipeline.PipelineState:
+        warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
+        # Peek (try_wait) AB buffer empty for k_block = prefetch_k_tile_cnt
+        peek_ab_empty_status = Boolean(True)
+        if 0 < k_tile_cnt:
+            peek_ab_empty_status = ab_pipeline.producer_try_acquire(ab_producer_state)
+        # TMA load on B and cp.async on A
+        for k_tile in cutlass.range(k_tile_cnt - 1, unroll=1):
+            prefetch_out = ()
+            if const_expr(prefetch_A is not None):  # Prefetch early, even before smem is free
+                prefetch_out = (prefetch_A(k_tile),)
+            # Wait for A/B buffers to be empty before loading into them
+            # Also sets the transaction barrier for the A/B buffers
+            # A tiny bit faster to rotate the warp that does TMA
+            is_tma_warp = warp_idx == self.ab_load_warp_id + (k_tile % self.num_ab_load_warps)
+            ab_pipeline.producer_acquire(ab_producer_state, peek_ab_empty_status, is_tma_warp)
+            smem_idx = ab_producer_state.index
+            # A bit faster to load B first while we calculate the indices for A
+            if is_tma_warp:
+                tma_bar_ptr = ab_pipeline.producer_get_barrier(ab_producer_state)
+                copy_B(k_tile, smem_idx, tma_bar_ptr=tma_bar_ptr)
+            copy_A(k_tile, smem_idx, *prefetch_out)
+            # This tells mbarrier to track the completion of cp.async
+            ab_pipeline.producer_cpasync_commit(ab_producer_state)
+            ab_producer_state.advance()
+            peek_ab_empty_status = Boolean(True)
+            if k_tile + 1 < k_tile_cnt:
+                peek_ab_empty_status = ab_pipeline.producer_try_acquire(ab_producer_state)
+        # bound checking in the K dimension on the last k_tile
+        if 0 < k_tile_cnt:
+            k_tile = k_tile_cnt - 1
+            prefetch_out = ()
+            if const_expr(prefetch_A is not None):  # Prefetch early, even before smem is free
+                prefetch_out = (prefetch_A(k_tile, pred=True),)
+            is_tma_warp = warp_idx == self.ab_load_warp_id + k_tile % self.num_ab_load_warps
+            ab_pipeline.producer_acquire(ab_producer_state, peek_ab_empty_status, is_tma_warp)
+            smem_idx = ab_producer_state.index
+            if is_tma_warp:
+                tma_bar_ptr = ab_pipeline.producer_get_barrier(ab_producer_state)
+                copy_B(k_tile, smem_idx, tma_bar_ptr=tma_bar_ptr)
+            copy_A(k_tile, smem_idx, *prefetch_out, pred=True)
+            ab_pipeline.producer_cpasync_commit(ab_producer_state)
+            ab_producer_state.advance()
+        return ab_producer_state
+
+    @cute.jit
+    def _make_gather_A_copy(
+        self,
+        mA_mkl: cute.Tensor,
+        sA: cute.Tensor,
+        varlen_manager: VarlenManager,
+        tile_coord_mnkl,
+        batch_idx: Int32,
+    ):
+        """Create copy_A and prefetch_A for gather_A (shared by SM90/SM120 DMA)."""
+        varlen_m = varlen_manager.varlen_m
+        mAIdx_mk = varlen_manager.offset_batch_AIdx(batch_idx)
+        if const_expr(varlen_m):
+            gAIdx = cute.local_tile(mAIdx_mk, (self.cta_tile_shape_mnk[0],), (tile_coord_mnkl[0],))
+            mA_mk = mA_mkl
+        else:
+            gAIdx = cute.flat_divide(mAIdx_mk, (self.cta_tile_shape_mnk[2],))
+            mA_mk = cute.local_tile(
+                mA_mkl, (self.cta_tile_shape_mnk[0],), (tile_coord_mnkl[0], None)
+            )
+        len_m = varlen_manager.len_m(batch_idx)
+        len_k = varlen_manager.len_k(batch_idx)
+        tiled_copy_A = self._make_gmem_tiled_copy_A(
+            mA_mkl.element_type, self.a_layout, self.num_ab_load_warps * 32
+        )
+        dma_tidx = cute.arch.thread_idx()[0] - cute.arch.WARP_SIZE * self.ab_load_warp_id
+        thr_copy_A = tiled_copy_A.get_slice(dma_tidx)
+        copy_A, prefetch_A = None, None
+        if const_expr(varlen_m):
+            copy_A = copy_utils.gather_m_get_copy_fn(
+                thr_copy_A,
+                mA_mk,
+                sA,
+                gAIdx,
+                limit_m=len_m - tile_coord_mnkl[0] * self.cta_tile_shape_mnk[0],
+                limit_k=len_k,
+            )
+        else:
+            copy_A, prefetch_A = copy_utils.gather_k_get_copy_fn(
+                thr_copy_A,
+                mA_mk,
+                sA,
+                gAIdx,
+                limit_m=len_m - tile_coord_mnkl[0] * self.cta_tile_shape_mnk[0],
+                limit_k=len_k,
+            )
+        return copy_A, prefetch_A
+
+    @cute.jit
+    def mma(
+        self,
+        ab_pipeline: cutlass.pipeline.PipelineAsync,
+        ab_read_state: cutlass.pipeline.PipelineState,
+        mma_fn: Callable,
+        acc: cute.Tensor,
+        acc_slow: Optional[cute.Tensor],
+        k_tile_cnt: Int32,
+        warp_group_idx: Int32,
+    ) -> cutlass.pipeline.PipelineState:
+        # Prologue MMAs
+        k_pipe_mmas = 1
+        ab_release_state = ab_read_state.clone()
+        num_prologue_mma = min(k_pipe_mmas, k_tile_cnt)
+        peek_ab_full_status = Boolean(True)
+        if 0 < k_tile_cnt:
+            peek_ab_full_status = ab_pipeline.consumer_try_wait(ab_read_state)
+        zero_init = Boolean(True)
+        for k_tile in cutlass.range(num_prologue_mma):
+            # Wait for A/B buffer to be ready
+            ab_pipeline.consumer_wait(ab_read_state, peek_ab_full_status)
+            mma_fn(A_idx=ab_read_state.index, B_idx=ab_read_state.index, zero_init=zero_init)
+            zero_init = Boolean(False)
+            ab_read_state.advance()
+            peek_ab_full_status = Boolean(True)
+            if k_tile + 1 < k_tile_cnt:
+                peek_ab_full_status = ab_pipeline.consumer_try_wait(ab_read_state)
+        # If k_tile_cnt == 0, this is not correct. But we will set acc to 0 in the mainloop
+        # in that case.
+        if const_expr(self.fp8_slow_accum):
+            warpgroup.wait_group(0)
+            acc_slow.store(acc.load())
+
+        # MAINLOOP
+        for k_tile in cutlass.range(num_prologue_mma, k_tile_cnt, unroll=1):
+            # Wait for TMA copies to complete
+            ab_pipeline.consumer_wait(ab_read_state, peek_ab_full_status)
+            if const_expr(self.fp8_slow_accum):
+                zero_init = Boolean(True)
+            mma_fn(A_idx=ab_read_state.index, B_idx=ab_read_state.index, zero_init=zero_init)
+            zero_init = Boolean(False)
+            # Wait on the wgmma barrier for previous k_pipe_mmas wgmmas to complete
+            if const_expr(not self.fp8_slow_accum):
+                warpgroup.wait_group(k_pipe_mmas)
+            else:
+                warpgroup.wait_group(0)
+                acc_slow.store(acc_slow.load() + acc.load())
+            ab_pipeline.consumer_release(ab_release_state)
+            ab_read_state.advance()
+            ab_release_state.advance()
+            peek_ab_full_status = Boolean(True)
+            if k_tile + 1 < k_tile_cnt:
+                peek_ab_full_status = ab_pipeline.consumer_try_wait(ab_read_state)
+        if const_expr(self.pingpong):
+            # Cue for next WG's MMA to start
+            self.pingpong_barrier_arrive(1 - warp_group_idx, stage="mma")
+        if const_expr(not self.fp8_slow_accum):
+            # fp8_slow_accum would already called wait_group(0) inside the loop
+            warpgroup.wait_group(0)
+        for k_tile in cutlass.range(num_prologue_mma, unroll=1):
+            ab_pipeline.consumer_release(ab_release_state)
+            ab_release_state.advance()
+        if const_expr(self.fp8_slow_accum):
+            acc.store(acc_slow.load())
+        return ab_read_state
+
+    def epi_retile_acc(self, acc, tRS_rD, tiled_copy_r2s):
+        """Retile accumulator for epilogue subtile access."""
+        acc_reshaped = layout_utils.reshape_acc_to_frgA(acc)  # ((2, 2, 2), MMA_M, MMA_N)
+        # ((2, 2, 2), MMA_M / epi_M, MMA_N / epi_N)
+        epi_acc_shape = (
+            acc_reshaped.shape[0],
+            *cute.ceil_div(acc_reshaped.shape[1:], self.epi_tile_shape),
+        )
+        # ((2, 2, 2), MMA_M / epi_M, MMA_N / epi_N, (1, 1, 1), epi_M, epi_N)
+        acc_divide = cute.flat_divide(acc_reshaped, epi_acc_shape)
+        assert cute.size(acc_divide, mode=[3]) == 1
+        # ((2, 2, 2), MMA_M / epi_M, MMA_N / epi_N, (epi_M, epi_N))
+        tRS_rAcc = cute.group_modes(acc_divide[None, None, None, 0, None, None], 3, 5)
+        # (((2,2,2),1), MMA_M / epi_M, MMA_N / epi_N, (epi_M, epi_N))
+        return tiled_copy_r2s.retile(tRS_rAcc)
+
+    def epilog_smem_copy_atom(self, tiled_mma: cute.TiledMma) -> cute.TiledCopy:
+        copy_atom_C = cute.make_copy_atom(
+            warp.StMatrix8x8x16bOp(
+                self.d_layout.is_m_major_c() if self.d_layout is not None else False,
+                num_matrices=4 if self.epi_tile[1] % 16 == 0 else 2,
+            ),
+            Float16,  # this is just to get the right source layout
+        )
+        tiled_copy_C_atom = cute.make_tiled_copy_C_atom(copy_atom_C, tiled_mma)
+        return tiled_copy_C_atom
+
+    def epilog_smem_store_and_partition(
+        self,
+        tiled_mma: cute.TiledMma,
+        d_layout: Optional[LayoutEnum],
+        dtype: Type[cutlass.Numeric],
+        sD: Optional[cute.Tensor],
+        tidx: Int32,
+    ) -> Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]:
+        if d_layout is None:
+            d_layout = LayoutEnum.ROW_MAJOR
+        tiled_copy_C_atom = self.epilog_smem_copy_atom(tiled_mma)
+        # Doesn't work with tile_N % 8 == 0 but tile_n % 16 != since this always
+        # get st.matrix with num_matrices=4
+        copy_atom_r2s = sm90_utils.sm90_get_smem_store_op(
+            d_layout, elem_ty_d=dtype, elem_ty_acc=self.acc_dtype
+        )
+        tiled_copy_r2s = cute.make_tiled_copy_S(copy_atom_r2s, tiled_copy_C_atom)
+        # (R2S, R2S_M, R2S_N, PIPE_D)
+        thr_copy_r2s = tiled_copy_r2s.get_slice(tidx)
+        tRS_sD = thr_copy_r2s.partition_D(sD) if sD is not None else None
+        sD_shape = sD.shape[:2] if sD is not None else self.epi_tile
+        tRS_rD_shape = thr_copy_r2s.partition_S(cute.make_identity_tensor(sD_shape)).shape
+        tRS_rD = cute.make_rmem_tensor(tRS_rD_shape, self.acc_dtype)
+        return tiled_copy_r2s, tRS_rD, tRS_sD
+
+    def epilog_smem_load_and_partition(
+        self,
+        tiled_mma: cute.TiledMma,
+        c_layout: LayoutEnum,
+        dtype: Type[cutlass.Numeric],
+        sC: cute.Tensor,
+        tRS_rD_layout: cutlass.Layout,
+        tidx: Int32,
+    ) -> Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]:
+        tiled_copy_C_atom = self.epilog_smem_copy_atom(tiled_mma)
+        copy_atom_s2r = copy_utils.sm90_get_smem_load_op(c_layout, dtype)
+        tiled_copy_s2r = cute.make_tiled_copy_S(copy_atom_s2r, tiled_copy_C_atom)
+        thr_copy_s2r = tiled_copy_s2r.get_slice(tidx)
+        tSR_sC = thr_copy_s2r.partition_S(sC)
+        tRS_rC = cute.make_rmem_tensor(tRS_rD_layout, dtype)
+        tSR_rC = thr_copy_s2r.retile(tRS_rC)
+        return tiled_copy_s2r, tRS_rC, tSR_rC, tSR_sC
+
+    def pingpong_barrier_sync(self, warp_group_idx: Int32, stage: str):
+        assert stage in ["mma", "epi"]
+        barrier = NamedBarrierGemm.MmaWG0 if stage == "mma" else NamedBarrierGemm.EpiWG0
+        cute.arch.barrier(
+            barrier_id=int(barrier) + warp_group_idx,
+            number_of_threads=2 * self.num_threads_per_warp_group,
+        )
+
+    def pingpong_barrier_arrive(self, warp_group_idx: Int32, stage: str):
+        assert stage in ["mma", "epi"]
+        barrier = NamedBarrierGemm.MmaWG0 if stage == "mma" else NamedBarrierGemm.EpiWG0
+        cute.arch.barrier_arrive(
+            barrier_id=int(barrier) + warp_group_idx,
+            number_of_threads=2 * self.num_threads_per_warp_group,
+        )
+
+    def make_sched_pipeline(
+        self, cluster_layout_mnk: cute.Layout, sched_pipeline_mbar_ptr: cute.Pointer, varlen_k: bool
+    ):
+        sched_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread)
+        cluster_size = cute.size(cluster_layout_mnk)
+        # Each warp will contribute 1 to the arrive count
+        # If pingpong and varlen_k, then all 8 mma warps will participate in the scheduler barrier
+        # at each round. If pingpong and not varlen_k, then only 4 mma warp will participate.
+        consumer_arrive_cnt = (
+            (self.mma_warp_groups if not (self.pingpong and not varlen_k) else 1) * 4
+            + self.num_ab_load_warps
+        ) * cluster_size
+        sched_pipeline_consumer_group = pipeline.CooperativeGroup(
+            pipeline.Agent.Thread, consumer_arrive_cnt
+        )
+        return pipeline.PipelineAsync.create(
+            barrier_storage=sched_pipeline_mbar_ptr,
+            num_stages=self.sched_stage,
+            producer_group=sched_pipeline_producer_group,
+            consumer_group=sched_pipeline_consumer_group,
+            # If there's cluster, the consumers must arrive at the mbar of CTA 0 in the cluster.
+            consumer_mask=None if const_expr(cluster_size == 1) else 0,
+            defer_sync=True,
+        )
+
+    @classmethod
+    def _compute_stages(
+        cls,
+        cta_tile_shape_mnk: Tuple[int, int, int],
+        epi_tile: Tuple[int, int],
+        a_dtype: Type[cutlass.Numeric],
+        b_dtype: Type[cutlass.Numeric],
+        d_dtype: Optional[Type[cutlass.Numeric]],
+        c_dtype: Optional[Type[cutlass.Numeric]],
+        epilogue_args: EpilogueArguments,
+        smem_capacity: int,
+        occupancy: int,
+        warp_shape_mnk: Tuple[int, int, int] | None = None,
+    ) -> Tuple[int, int]:
+        """Computes the number of stages for A/B/C operands based on heuristics.
+
+        :param cta_tile_shape_mnk: The shape (M, N, K) of the CTA tile.
+        :type cta_tile_shape_mnk: Tuple[int, int, int]
+        :param a_dtype: Data type of operand A.
+        :type a_dtype: type[cutlass.Numeric]
+        :param b_dtype: Data type of operand B.
+        :type b_dtype: type[cutlass.Numeric]
+        :param smem_capacity: Total available shared memory capacity in bytes.
+        :type smem_capacity: int
+        :param occupancy: Target number of CTAs per SM (occupancy).
+        :type occupancy: int
+
+        :return: A tuple containing the computed number of stages for:
+                 (A/B operand stages, epilogue stages)
+        :rtype: Tuple[int, int]
+        """
+
+        epi_stage = 4 if epi_tile[1] <= 16 else 2
+        epi_smem_bytes = cls.epi_smem_bytes(
+            epilogue_args, cta_tile_shape_mnk, epi_tile, warp_shape_mnk
+        )
+        has_tile_load = epi_smem_bytes.c_stage > 0
+        epi_tile_elems = cute.size(cute.shape(epi_tile))
+        d_bytes_per_stage = epi_tile_elems * d_dtype.width // 8 if d_dtype is not None else 0
+        epi_bytes_per_stage = d_bytes_per_stage + epi_smem_bytes.d_stage
+        epi_bytes = epi_smem_bytes.unstaged + epi_bytes_per_stage * epi_stage
+        epi_c_stage = (
+            0 if c_dtype is None and not has_tile_load else (4 if epi_tile[1] <= 16 else 2)
+        )
+        if c_dtype is not None:
+            epi_bytes += epi_tile_elems * c_dtype.width // 8 * epi_c_stage
+        if has_tile_load:
+            epi_bytes += epi_smem_bytes.c_stage * epi_c_stage
+
+        a_shape = cute.slice_(cta_tile_shape_mnk, (None, 0, None))
+        b_shape = cute.slice_(cta_tile_shape_mnk, (0, None, None))
+        ab_bytes_per_stage = (
+            cute.size(a_shape) * a_dtype.width // 8 + cute.size(b_shape) * b_dtype.width // 8
+        )
+        mbar_helpers_bytes = 1024
+
+        remaining_bytes = smem_capacity // occupancy - mbar_helpers_bytes - epi_bytes
+        ab_stage = remaining_bytes // ab_bytes_per_stage
+
+        # Refine epilogue stages:
+        # Calculate remaining smem after allocating for A/B stages and reserved bytes
+        # Add remaining unused smem to epilogue
+        if epi_bytes_per_stage > 0:
+            epi_stage += (remaining_bytes - ab_bytes_per_stage * ab_stage) // epi_bytes_per_stage
+        return ab_stage, epi_stage, epi_c_stage
+
+    @staticmethod
+    def _compute_tile_shape_or_override(
+        cta_tile_shape_mnk: Tuple[int, int, int],
+        atom_layout_mnk: Tuple[int, int, int],
+        element_type: Optional[Type[cutlass.Numeric]] = None,
+        epi_tile_override: Tuple[int, int] | None = None,
+    ) -> Tuple[int, int]:
+        """Compute the epilogue tile shape or use override if provided.
+
+        :param cta_tile_shape_mnk: CTA tile shape (M,N,K)
+        :type cta_tile_shape_mnk: Tuple[int, int, int]
+        :param element_type: Data type of elements
+        :type element_type: type[cutlass.Numeric]
+        :param is_cooperative: Whether to use cooperative approach
+        :type is_cooperative: bool
+        :param epi_tile_override: Optional override for epilogue tile shape
+        :type epi_tile_override: Tuple[int, int] or None
+
+        :return: Computed epilogue tile shape
+        :rtype: Tuple[int, int]
+        """
+        if epi_tile_override is not None:
+            return epi_tile_override
+        if cta_tile_shape_mnk[0] % 128 == 0 and atom_layout_mnk[0] > 1:
+            tile_m = math.gcd(128, cute.size(cta_tile_shape_mnk, mode=[0]))
+            tile_n = math.gcd(32, cute.size(cta_tile_shape_mnk, mode=[1]))
+        elif cta_tile_shape_mnk[0] % 192 == 0 and atom_layout_mnk[0] > 1:
+            tile_m = math.gcd(192, cute.size(cta_tile_shape_mnk, mode=[0]))
+            tile_n = math.gcd(32, cute.size(cta_tile_shape_mnk, mode=[1]))
+        else:
+            # In the case of tile shape 128 x N but atom_layout 1 x 2, we need to set
+            # epi_tile_m = 64. If epi_tile_m = 128, the epilogue would iterate along the
+            # M dimension first, then move to the N dimension. But the accumulator in registers
+            # iterate along the N dimension first, then move to the M dimension.
+            # We could change the epilogue to accommodate this,
+            # but it's easier to just set epi_tile_m = 64.
+            n_perf = 64 if element_type is not None and element_type.width == 8 else 32
+            tile_m = math.gcd(64, cute.size(cta_tile_shape_mnk, mode=[0]))
+            tile_n = math.gcd(n_perf, cute.size(cta_tile_shape_mnk, mode=[1]))
+        return (tile_m, tile_n)
+
+    @staticmethod
+    def _make_smem_layouts(
+        cta_tile_shape_mnk: Tuple[int, int, int],
+        epi_tile: Tuple[int, int],
+        a_dtype: Type[cutlass.Numeric],
+        a_layout: LayoutEnum,
+        b_dtype: Type[cutlass.Numeric],
+        b_layout: LayoutEnum,
+        ab_stage: int,
+        d_dtype: Optional[Type[cutlass.Numeric]],
+        d_layout: LayoutEnum,
+        epi_stage: int,
+        c_dtype: Optional[Type[cutlass.Numeric]],
+        c_layout: Optional[LayoutEnum],
+        epi_c_stage: int,
+    ) -> Tuple[
+        cute.ComposedLayout, cute.ComposedLayout, cute.ComposedLayout, Optional[cute.ComposedLayout]
+    ]:
+        """Create shared memory layouts for A, B, and C tensors.
+
+        :param cta_tile_shape_mnk: CTA tile shape (M,N,K)
+        :type cta_tile_shape_mnk: Tuple[int, int, int]
+        :param epi_tile: Epilogue tile shape
+        :type epi_tile: Tuple[int, int]
+        :param a_dtype: Data type for matrix A
+        :type a_dtype: type[cutlass.Numeric]
+        :param a_layout: Layout enum for matrix A
+        :type a_layout: LayoutEnum
+        :param b_dtype: Data type for matrix B
+        :type b_dtype: type[cutlass.Numeric]
+        :param b_layout: Layout enum for matrix B
+        :type b_layout: LayoutEnum
+        :param ab_stage: Number of stages for A/B tensors
+        :type ab_stage: int
+        :param d_dtype: Data type for output matrix D
+        :type d_dtype: type[cutlass.Numeric]
+        :param d_layout: Layout enum for the output matrix C
+        :type d_layout: LayoutEnum
+        :param epi_stage: Number of epilogue stages
+        :type epi_stage: int
+
+        :return: Tuple of shared memory layouts for A, B, and C
+        :rtype: Tuple[cute.ComposedLayout, cute.ComposedLayout, cute.ComposedLayout]
+        """
+        a_smem_shape = cute.slice_(cta_tile_shape_mnk, (None, 0, None))
+
+        a_is_k_major = a_layout.sm90_mma_major_mode() == cute.nvgpu.OperandMajorMode.K
+        b_is_k_major = b_layout.sm90_mma_major_mode() == cute.nvgpu.OperandMajorMode.K
+        a_major_mode_size = cta_tile_shape_mnk[2 if a_is_k_major else 0]
+        a_smem_layout_atom = warpgroup.make_smem_layout_atom(
+            sm90_utils.get_smem_layout_atom(a_layout, a_dtype, a_major_mode_size),
+            a_dtype,
+        )
+        a_smem_layout_staged = cute.tile_to_shape(
+            a_smem_layout_atom,
+            cute.append(a_smem_shape, ab_stage),
+            order=(0, 1, 2) if a_is_k_major else (1, 0, 2),
+        )
+
+        b_smem_shape = cute.slice_(cta_tile_shape_mnk, (0, None, None))
+
+        b_major_mode_size = cta_tile_shape_mnk[2 if b_is_k_major else 1]
+        b_smem_layout_atom = warpgroup.make_smem_layout_atom(
+            sm90_utils.get_smem_layout_atom(b_layout, b_dtype, b_major_mode_size),
+            b_dtype,
+        )
+        b_smem_layout_staged = cute.tile_to_shape(
+            b_smem_layout_atom,
+            cute.append(b_smem_shape, ab_stage),
+            order=(0, 1, 2) if b_is_k_major else (1, 0, 2),
+        )
+
+        epi_smem_layout_staged = None
+        if d_dtype is not None:
+            epi_smem_layout_staged = quack_sm90_utils.make_smem_layout_epi(
+                d_dtype, d_layout, epi_tile, epi_stage
+            )
+
+        epi_c_smem_layout_staged = None
+        if c_dtype is not None:
+            assert c_layout is not None
+            epi_c_smem_layout_staged = quack_sm90_utils.make_smem_layout_epi(
+                c_dtype, c_layout, epi_tile, epi_c_stage
+            )
+
+        return (
+            a_smem_layout_staged,
+            b_smem_layout_staged,
+            epi_smem_layout_staged,
+            epi_c_smem_layout_staged,
+        )
+
+    @staticmethod
+    def is_valid_dtypes(
+        a_dtype: Type[cutlass.Numeric],
+        b_dtype: Type[cutlass.Numeric],
+        acc_dtype: Type[cutlass.Numeric],
+        d_dtype: Optional[Type[cutlass.Numeric]],
+        a_major: str,
+        b_major: str,
+    ) -> bool:
+        """
+        Check if the dtypes are valid
+
+        :param a_dtype: The data type of tensor A
+        :type a_dtype: Type[cutlass.Numeric]
+        :param b_dtype: The data type of tensor B
+        :type b_dtype: Type[cutlass.Numeric]
+        :param acc_dtype: The data type of the accumulator
+        :type acc_dtype: Type[cutlass.Numeric]
+        :param d_dtype: The data type of the output tensor
+        :type d_dtype: Type[cutlass.Numeric]
+        :param a_major: major mode of tensor A
+        :type a_major: str
+        :param b_major: major mode of tensor B
+        :type b_major: str
+
+        :return: True if the dtypes are valid, False otherwise
+        :rtype: bool
+        """
+        is_valid = True
+        if a_dtype not in {Float16, cutlass.BFloat16, cutlass.Float8E4M3FN, cutlass.Float8E5M2}:
+            is_valid = False
+        # tested b_dtype
+        if b_dtype not in {Float16, cutlass.BFloat16, cutlass.Float8E4M3FN, cutlass.Float8E5M2}:
+            is_valid = False
+        if acc_dtype not in {Float32, Float16}:
+            is_valid = False
+        # tested d_dtype
+        if d_dtype not in {
+            None,
+            Float32,
+            Float16,
+            cutlass.BFloat16,
+            cutlass.Float8E4M3FN,
+            cutlass.Float8E5M2,
+        }:
+            is_valid = False
+        # make sure a_dtype == b_dtype for Float16
+        if a_dtype.width == 16 and a_dtype != b_dtype:
+            is_valid = False
+        # make sure a_dtype.width == b_dtype.width (i.e, Float8E4M3FN or Float8E5M2)
+        if a_dtype.width != b_dtype.width:
+            is_valid = False
+
+        # for Float8 types, this implementation only supports k-major layout
+        if (a_dtype.width == 8 and a_major != "k") or (b_dtype.width == 8 and b_major != "k"):
+            is_valid = False
+        return is_valid
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_tvm_ffi_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_tvm_ffi_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d080ea36f7d8339643bb0416198ccd5d0141b9fa
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/gemm_tvm_ffi_utils.py
@@ -0,0 +1,234 @@
+# Copyright (c) 2025, Tri Dao.
+# Shared utilities for TVM-FFI GEMM compilation.
+
+from functools import partial
+
+
+import cutlass.cute as cute
+from cutlass import Int32, Int64, Float32
+from cutlass.cute.runtime import make_ptr
+
+from .compile_utils import make_fake_tensor as fake_tensor
+from .cute_dsl_utils import torch2cute_dtype_map
+from .tile_scheduler import TileSchedulerOptions
+from .varlen_utils import VarlenArguments
+
+
+def div_for_dtype(dtype):
+    """16-byte alignment: divisibility in elements = 128 // dtype_width_bits."""
+    return 128 // dtype.width
+
+
+def perm3d_single(t, varlen_m=False):
+    """Permute a single 3D tensor from (L, *, *) to (*, *, L), skipping for varlen_m or 2D."""
+    return t.permute(1, 2, 0) if t is not None and t.ndim == 3 and not varlen_m else t
+
+
+def perm3d(A, B, D, C, varlen_m=False, varlen_k=False):
+    """Permute 3D tensors from (L, *, *) to (*, *, L)."""
+
+    def _perm(t):
+        return t.permute(1, 2, 0) if t is not None and t.ndim == 3 else t
+
+    if varlen_m:
+        return A, _perm(B), D, C
+    elif varlen_k:
+        return A, B, _perm(D), _perm(C)
+    else:
+        return _perm(A), _perm(B), _perm(D), _perm(C)
+
+
+def get_major(t, dim0, dim1):
+    return dim1 if t.stride(1) == 1 else dim0
+
+
+def get_majors(A_p, B_p, D_p, C_p):
+    a_major = get_major(A_p, "m", "k")
+    b_major = get_major(B_p, "n", "k")
+    d_major = get_major(D_p, "m", "n")
+    c_major = get_major(C_p, "m", "n") if C_p is not None else None
+    return a_major, b_major, d_major, c_major
+
+
+def get_dtypes(A, B, D, C):
+    a_dtype = torch2cute_dtype_map[A.dtype]
+    b_dtype = torch2cute_dtype_map[B.dtype]
+    d_dtype = torch2cute_dtype_map[D.dtype]
+    c_dtype = torch2cute_dtype_map[C.dtype] if C is not None else None
+    return a_dtype, b_dtype, d_dtype, c_dtype
+
+
+def make_scheduler_args(
+    max_active_clusters, max_swizzle_size, tile_count_semaphore, batch_idx_permute=None
+):
+    return TileSchedulerOptions(
+        max_active_clusters=Int32(max_active_clusters),
+        raster_order=None,
+        max_swizzle_size=max_swizzle_size,
+        tile_count_semaphore=(
+            tile_count_semaphore.data_ptr() if tile_count_semaphore is not None else None
+        ),
+        batch_idx_permute=batch_idx_permute,
+    )
+
+
+def make_fake_scheduler_args(has_semaphore, has_batch_idx_permute, l_sym):
+    return TileSchedulerOptions(
+        max_active_clusters=Int32(1),
+        max_swizzle_size=Int32(8),
+        tile_count_semaphore=(
+            make_ptr(Int32, 0, cute.AddressSpace.gmem, assumed_align=4) if has_semaphore else None
+        ),
+        batch_idx_permute=(
+            fake_tensor(Int32, (l_sym,), leading_dim=0, divisibility=4)
+            if has_batch_idx_permute
+            else None
+        ),
+    )
+
+
+def make_varlen_args(cu_seqlens_m, cu_seqlens_k, A_idx):
+    if cu_seqlens_m is None and cu_seqlens_k is None:
+        return None
+    return VarlenArguments(
+        mCuSeqlensM=cu_seqlens_m,
+        mCuSeqlensK=cu_seqlens_k,
+        mAIdx=A_idx,
+    )
+
+
+def make_fake_varlen_args(varlen_m, varlen_k, gather_A, aidx_len):
+    if not varlen_m and not varlen_k:
+        return None
+    num_seqlens = cute.sym_int()
+    return VarlenArguments(
+        mCuSeqlensM=(
+            fake_tensor(Int32, (num_seqlens,), leading_dim=0, divisibility=4) if varlen_m else None
+        ),
+        mCuSeqlensK=(
+            fake_tensor(Int32, (num_seqlens,), leading_dim=0, divisibility=4) if varlen_k else None
+        ),
+        mAIdx=(
+            fake_tensor(Int32, (aidx_len,), leading_dim=0, divisibility=4) if gather_A else None
+        ),
+    )
+
+
+def make_fake_gemm_tensors(
+    a_dtype,
+    b_dtype,
+    d_dtype,
+    c_dtype,
+    a_major,
+    b_major,
+    d_major,
+    c_major,
+    varlen_m=False,
+    varlen_k=False,
+    gather_A=False,
+):
+    """Create fake tensors for mA, mB, mD, mC with shared sym_ints.
+    Pass dtype=None to get None for that tensor (e.g. optional C).
+    Returns (mA, mB, mD, mC, m, n, k, l).
+    When varlen_m, m is total_m (flattened M of D/C). When varlen_k, k is total_k.
+    """
+    a_leading = 1 if a_major == "k" else 0
+    b_leading = 1 if b_major == "k" else 0
+    d_leading = 1 if d_major == "n" else 0
+    c_leading = 1 if c_major == "n" else 0
+    m, n, k, l = cute.sym_int(), cute.sym_int(), cute.sym_int(), cute.sym_int()
+    div_a = div_for_dtype(a_dtype)
+    div_b = div_for_dtype(b_dtype)
+    div_d = div_for_dtype(d_dtype) if d_dtype is not None else 1
+    div_c = div_for_dtype(c_dtype) if c_dtype is not None else 1
+    if varlen_m:
+        # m is total_m in this case: the flattened M dimension of D/C
+        m = cute.sym_int()
+        a_m = cute.sym_int() if gather_A else m
+        mA = fake_tensor(a_dtype, (a_m, k), leading_dim=a_leading, divisibility=div_a)
+        mB = fake_tensor(b_dtype, (n, k, l), leading_dim=b_leading, divisibility=div_b)
+        mD = fake_tensor(d_dtype, (m, n), leading_dim=d_leading, divisibility=div_d)
+        mC = fake_tensor(c_dtype, (m, n), leading_dim=c_leading, divisibility=div_c)
+    elif varlen_k:
+        # k is total_k in this case: the flattened K dimension of A/B
+        k = cute.sym_int()
+        a_k = cute.sym_int() if gather_A else k
+        mA = fake_tensor(a_dtype, (m, a_k), leading_dim=a_leading, divisibility=div_a)
+        mB = fake_tensor(b_dtype, (n, k), leading_dim=b_leading, divisibility=div_b)
+        mD = fake_tensor(d_dtype, (m, n, l), leading_dim=d_leading, divisibility=div_d)
+        mC = fake_tensor(c_dtype, (m, n, l), leading_dim=c_leading, divisibility=div_c)
+    else:
+        mA = fake_tensor(a_dtype, (m, k, l), leading_dim=a_leading, divisibility=div_a)
+        mB = fake_tensor(b_dtype, (n, k, l), leading_dim=b_leading, divisibility=div_b)
+        mD = fake_tensor(d_dtype, (m, n, l), leading_dim=d_leading, divisibility=div_d)
+        mC = fake_tensor(c_dtype, (m, n, l), leading_dim=c_leading, divisibility=div_c)
+    return mA, mB, mD, mC, m, n, k, l
+
+
+def compile_gemm_kernel(
+    GemmCls,
+    a_dtype,
+    tile_shape_mn,
+    cluster_shape_mnk,
+    pingpong,
+    persistent,
+    gather_A,
+    is_dynamic_persistent,
+    device_capacity,
+    mA,
+    mB,
+    mD,
+    mC,
+    epi_args,
+    scheduler_args,
+    varlen_args,
+    post_init=None,
+    mSFA=None,
+    mSFB=None,
+    has_trace_ptr=False,
+    use_tma_gather=False,
+    concat_layout=None,
+    num_warps=None,
+):
+    """Build GemmCls instance, apply SM90 partial, and cute.compile with TVM-FFI."""
+    if device_capacity[0] == 8:
+        sm8x_kwargs = {"is_persistent": persistent, "num_warps": num_warps}
+        sm8x_kwargs["arch"] = device_capacity[0] * 10 + device_capacity[1]
+        GemmCls = partial(GemmCls, **sm8x_kwargs)
+    elif device_capacity[0] in [9, 12]:
+        GemmCls = partial(GemmCls, pingpong=pingpong, is_persistent=persistent)
+    elif device_capacity[0] in [10, 11]:
+        GemmCls = partial(
+            GemmCls,
+            use_clc_persistence=is_dynamic_persistent,
+            use_tma_gather=use_tma_gather,
+        )
+    gemm_obj = GemmCls(
+        Float32,
+        a_dtype,
+        tile_shape_mn,
+        cluster_shape_mnk,
+        gather_A=gather_A,
+        concat_layout=concat_layout,
+    )
+    if post_init:
+        post_init(gemm_obj)
+    stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True)
+    sf_args = () if device_capacity[0] in (8, 9, 12) else (mSFA, mSFB)
+    # Trace pointer: Optional[Int64]. Compile with Int64(0) when tracing is
+    # requested, None otherwise. TVM-FFI caches each variant separately.
+    trace_ptr = Int64(0) if has_trace_ptr else None
+    return cute.compile(
+        gemm_obj,
+        mA,
+        mB,
+        mD,
+        mC,
+        epi_args,
+        scheduler_args,
+        varlen_args,
+        stream,
+        *sf_args,
+        trace_ptr,
+        options="--enable-tvm-ffi",
+    )
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/layout_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/layout_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..77def95de62ff3adfac1810330cb840def01cf83
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/layout_utils.py
@@ -0,0 +1,385 @@
+# Copyright (c) 2025, Wentao Guo, Ted Zadouri, Tri Dao.
+
+
+import cutlass
+import cutlass.cute as cute
+
+from cutlass import Int32, const_expr
+
+
+def transpose_view(a: cute.Tensor) -> cute.Tensor:
+    """Transpose the first two dimensions of a tensor on smem."""
+    shape = (a.shape[1], a.shape[0], *a.shape[2:])
+    order = (1, 0, *range(2, cute.rank(a)))
+    return cute.composition(a, cute.make_ordered_layout(shape, order=order))
+
+
+def select(a: cute.Tensor, mode: list[int]) -> cute.Tensor:
+    return cute.make_tensor(a.iterator, cute.select(a.layout, mode))
+
+
+def concat_to_interleave(a: cute.Tensor, dim: int) -> cute.Tensor:
+    """Reshape a concat [first_half; second_half] layout to interleaved along `dim`.
+
+    Splits dimension `dim` (size 2N) into hierarchical (2, N) so that elements
+    from the first half and second half alternate: [first_0, second_0, first_1, ...].
+    Used to convert gated MLP weight layout from concat [gate; up] to interleaved.
+    """
+    half = cute.size(a, mode=[dim]) // 2
+    shape = (*a.shape[:dim], (2, half), *a.shape[dim + 1 :])
+    stride = (*a.stride[:dim], (half * a.stride[dim], a.stride[dim]), *a.stride[dim + 1 :])
+    return cute.make_tensor(a.iterator, cute.make_layout(shape, stride=stride))
+
+
+def expand(a: cute.Tensor, dim: int, size: Int32 | int) -> cute.Tensor:
+    shape = (*a.shape[:dim], size, *a.shape[dim:])
+    stride = (*a.layout.stride[:dim], 0, *a.layout.stride[dim:])
+    return cute.make_tensor(a.iterator, cute.make_layout(shape, stride=stride))
+
+
+@cute.jit
+def permute_gated_Cregs_b16(t: cute.Tensor) -> None:
+    assert t.element_type.width == 16
+    assert cute.size(t.shape) % 4 == 0, "Tensor size must be a multiple of 4 for b16 permutation"
+    t_u32 = cute.recast_tensor(t, Int32)
+
+    quad_idx = cute.arch.lane_idx() % 4
+    lane_03 = quad_idx == 0 or quad_idx == 3
+    selector_upper = Int32(0x5410) if lane_03 else Int32(0x1054)
+    selector_lower = Int32(0x7632) if lane_03 else Int32(0x3276)
+    # upper_map = [0, 3, 1, 2]
+    # lower_map = [1, 2, 0, 3]
+    # upper_idx = upper_map[quad_idx]
+    # indexing isn't supported so we have to do arithmetic
+    upper_idx = quad_idx // 2 if quad_idx % 2 == 0 else 3 - quad_idx // 2
+    lower_idx = upper_idx ^ 1
+
+    # 1 -> 0b11111, 2 -> 0b11110, 4 -> 0b11100, 8 -> 0b11000, 16 -> 0b10000, 32 -> 0b00000
+    width = 4
+    mask = cute.arch.WARP_SIZE - width
+    clamp = cute.arch.WARP_SIZE - 1
+    mask_and_clamp = mask << 8 | clamp
+
+    for i in cutlass.range(cute.size(t_u32.shape) // 2, unroll_full=True):
+        upper, lower = t_u32[i * 2 + 0], t_u32[i * 2 + 1]
+        upper0 = upper if lane_03 else lower
+        lower0 = lower if lane_03 else upper
+        upper0 = cute.arch.shuffle_sync(upper0, offset=upper_idx, mask_and_clamp=mask_and_clamp)
+        lower0 = cute.arch.shuffle_sync(lower0, offset=lower_idx, mask_and_clamp=mask_and_clamp)
+        t_u32[i * 2 + 0] = cute.arch.prmt(upper0, lower0, selector_upper)
+        t_u32[i * 2 + 1] = cute.arch.prmt(upper0, lower0, selector_lower)
+
+
+@cute.jit
+def permute_Cregs_b32_for_stsm(t: cute.Tensor) -> None:
+    """Permute and shuffle within 4 threads to change the layout from
+     T0 | T1  | T2  | T3
+    a b | c d | e f | g h
+    to
+    T0 | T1 | T2 | T3 | T0 | T1 | T2 | T3
+    a  | b  | c  | d  | e  | f  | g  | h
+    This is so that we can use STSM (instead of STS.64) to store C registers without bank conflict.
+    """
+
+    assert t.element_type.width == 32
+    assert cute.size(t.shape) % 4 == 0, "Tensor size must be a multiple of 4 for b32 permutation"
+
+    quad_idx = cute.arch.lane_idx() % 4
+    # left_map = [0, 2, 1, 3]
+    # right_map = [2, 0, 3, 1]
+    # indexing isn't supported so we have to do arithmetic
+    left_idx = quad_idx // 2 if quad_idx % 2 == 0 else 2 + quad_idx // 2
+    right_idx = left_idx ^ 0b10
+
+    # 1 -> 0b11111, 2 -> 0b11110, 4 -> 0b11100, 8 -> 0b11000, 16 -> 0b10000, 32 -> 0b00000
+    width = 4
+    mask = cute.arch.WARP_SIZE - width
+    clamp = cute.arch.WARP_SIZE - 1
+    mask_and_clamp = mask << 8 | clamp
+
+    for i in cutlass.range(cute.size(t.shape) // 4, unroll_full=True):
+        for r in cutlass.range(2, unroll_full=True):
+            left, right = t[i * 4 + r * 2 + 0], t[i * 4 + r * 2 + 1]
+            # a b | c d | e f | g h -> a b | c d | f e | h g
+            left0 = left if quad_idx < 2 else right
+            right0 = right if quad_idx < 2 else left
+            # a b | c d | f e | h g -> a b | f d | c e | h g
+            left0 = cute.arch.shuffle_sync(left0, offset=left_idx, mask_and_clamp=mask_and_clamp)
+            # a b | f d | c e | h g -> a e | f b | c g | h d
+            right0 = cute.arch.shuffle_sync(right0, offset=right_idx, mask_and_clamp=mask_and_clamp)
+            # a e | f b | c g | h d -> a e | b f | c g | d h
+            t[i * 4 + r * 2 + 0] = left0 if quad_idx % 2 == 0 else right0
+            t[i * 4 + r * 2 + 1] = right0 if quad_idx % 2 == 0 else left0
+        t[i * 4 + 1], t[i * 4 + 2] = t[i * 4 + 2], t[i * 4 + 1]
+
+
+@cute.jit
+def permute_Cregs_b32_for_ldsm(t: cute.Tensor) -> None:
+    """Permute and shuffle within 4 threads to change the layout from
+    T0 | T1 | T2 | T3 | T0 | T1 | T2 | T3
+    a  | b  | c  | d  | e  | f  | g  | h
+    to
+     T0 | T1  | T2  | T3
+    a b | c d | e f | g h
+    This is so that we can use LDSM (instead of LDS.64) to store C registers without bank conflict.
+    """
+
+    assert t.element_type.width == 32
+    assert cute.size(t.shape) % 4 == 0, "Tensor size must be a multiple of 4 for b32 permutation"
+
+    quad_idx = cute.arch.lane_idx() % 4
+    # left_map = [0, 2, 1, 3]
+    # right_map = [1, 3, 0, 2]
+    # indexing isn't supported so we have to do arithmetic
+    left_idx = quad_idx // 2 if quad_idx % 2 == 0 else 2 + quad_idx // 2
+    right_idx = left_idx ^ 0b01
+
+    # 1 -> 0b11111, 2 -> 0b11110, 4 -> 0b11100, 8 -> 0b11000, 16 -> 0b10000, 32 -> 0b00000
+    width = 4
+    mask = cute.arch.WARP_SIZE - width
+    clamp = cute.arch.WARP_SIZE - 1
+    mask_and_clamp = mask << 8 | clamp
+
+    # This is just the inverse of permute_Cregs_b32_for_stsm
+    for i in cutlass.range(cute.size(t.shape) // 4, unroll_full=True):
+        t[i * 4 + 1], t[i * 4 + 2] = t[i * 4 + 2], t[i * 4 + 1]
+        for r in cutlass.range(2, unroll_full=True):
+            left, right = t[i * 4 + r * 2 + 0], t[i * 4 + r * 2 + 1]
+            # a e | b f | c g | d h -> a e | f b | c g | h d
+            left0 = left if quad_idx % 2 == 0 else right
+            right0 = right if quad_idx % 2 == 0 else left
+            # a e | f b | c g | h d -> a b | f d | c e | h g
+            right0 = cute.arch.shuffle_sync(right0, offset=right_idx, mask_and_clamp=mask_and_clamp)
+            # a b | f d | c e | h g -> a b | c d | f e | h g
+            left0 = cute.arch.shuffle_sync(left0, offset=left_idx, mask_and_clamp=mask_and_clamp)
+            # a b | c d | f e | h g -> a b | c d | e f | g h
+            t[i * 4 + r * 2 + 0] = left0 if quad_idx < 2 else right0
+            t[i * 4 + r * 2 + 1] = right0 if quad_idx < 2 else left0
+
+
+@cute.jit
+def concat_layout(*layouts: cute.Layout) -> cute.Layout:
+    return cute.make_layout(
+        tuple(l.shape for l in layouts),
+        stride=tuple(l.stride for l in layouts),
+    )
+
+
+def convert_layout_acc_mn(acc_layout: cute.Layout, transpose: bool = False) -> cute.Layout:
+    """
+    For Sm80, convert ((2, 2), MMA_M, MMA_N, ...) to ((2, MMA_M), (2, MMA_N), ...).
+    For Sm90, convert ((2, 2, V), MMA_M, MMA_N, ...) to ((2, MMA_M), (2, V, MMA_N), ...).
+    """
+    acc_layout_col_major = cute.make_layout(acc_layout.shape)
+    shape = (
+        (acc_layout_col_major.shape[0][1], acc_layout_col_major.shape[1]),  # MMA_M
+        (
+            acc_layout_col_major.shape[0][0],
+            *acc_layout_col_major.shape[0][2:],
+            acc_layout_col_major.shape[2],
+        ),  # MMA_N
+        *acc_layout_col_major.shape[3:],
+    )
+    stride = (
+        (acc_layout_col_major.stride[0][1], acc_layout_col_major.stride[1]),  # MMA_M
+        (
+            acc_layout_col_major.stride[0][0],
+            *acc_layout_col_major.stride[0][2:],
+            acc_layout_col_major.stride[2],
+        ),  # MMA_N
+        *acc_layout_col_major.stride[3:],
+    )
+    if const_expr(transpose):
+        shape = (shape[1], shape[0], *shape[2:])
+        stride = (stride[1], stride[0], *stride[2:])
+    acc_layout_mn = cute.make_layout(shape, stride=stride)
+    return cute.composition(acc_layout, acc_layout_mn)
+
+
+def make_acc_tensor_mn_view(acc: cute.Tensor, transpose: bool = False) -> cute.Tensor:
+    return cute.make_tensor(acc.iterator, convert_layout_acc_mn(acc.layout, transpose=transpose))
+
+
+def reshape_acc_to_mn(acc: cute.Tensor, transpose: bool = False) -> cute.Tensor:
+    return cute.make_tensor(acc.iterator, convert_layout_acc_mn(acc.layout, transpose=transpose))
+
+
+@cute.jit
+def convert_layout_acc_frgA(acc_layout: cute.Layout) -> cute.Layout:
+    # For back to back gemm, convert layout of acc0 to gemm 1 accept layout.
+    # For Sm80, as the mma instruction shape is 16x8x16, we need to convert from (4, MMA_M, MMA_N) to ((4, 2), MMA_M, MMA_N / 2)
+    # For Sm90, FP16/BF16, convert acc_layout from ((2, 2, N / 8), MMA_M, MMA_N) to ((2, 2, 2), MMA_M, (N / 16, MMA_N))
+    # If N / 8 is odd, we'll convert to ((2, 2, 1), MMA_M, N / 8, MMA_N).
+    # TODO: Sm90 FP8
+    if const_expr(cute.rank(acc_layout.shape[0]) == 3):  # Sm90
+        div = 2 if const_expr(acc_layout.shape[0][2] % 2 == 0) else 1
+        l = cute.logical_divide(
+            acc_layout, ((None, None, div), None, None)
+        )  # ((2, 2, (2, N / 16)), MMA_M, MMA_N)
+        rA_mma_view = cute.make_layout(
+            (
+                (l.shape[0][0], l.shape[0][1], l.shape[0][2][0]),
+                l.shape[1],
+                (l.shape[0][2][1], l.shape[2]),
+            ),
+            stride=(
+                (l.stride[0][0], l.stride[0][1], l.stride[0][2][0]),
+                l.stride[1],
+                (l.stride[0][2][1], l.stride[2]),
+            ),
+        )
+    else:  # Sm80
+        # (4, MMA_M, MMA_N) -> (4, MMA_M, (2, MMA_N / 2))
+        assert acc_layout.shape[2] % 2 == 0
+        l = cute.logical_divide(acc_layout, (None, None, 2))
+        rA_mma_view = cute.make_layout(
+            (
+                (l.shape[0][0], l.shape[0][1], l.shape[2][0]),
+                l.shape[1],
+                l.shape[2][1],
+            ),
+            stride=(
+                (l.stride[0][0], l.stride[0][1], l.stride[2][0]),
+                l.stride[1],
+                l.stride[2][1],
+            ),
+        )
+    return rA_mma_view
+
+
+def reshape_acc_to_frgA(acc: cute.Tensor) -> cute.Tensor:
+    return cute.make_tensor(acc.iterator, convert_layout_acc_frgA(acc.layout))
+
+
+def convert_layout_zero_stride(
+    input: cute.Tensor | cute.Layout, ref_layout: cute.Layout
+) -> cute.Layout:
+    layout = input.layout if const_expr(isinstance(input, cute.Tensor)) else input
+    # Group the modes with non-zero stride in the ref_layout together,
+    # and the modes with zero stride together
+    layout_flat = cute.flatten(layout)
+    ref_layout_flat = cute.flatten(ref_layout)
+    nonzero_modes = [i for i in range(cute.rank(layout_flat)) if ref_layout_flat[i].stride != 0]
+    zero_modes = [i for i in range(cute.rank(layout_flat)) if ref_layout_flat[i].stride == 0]
+    # There's an edge case when all modes are zero stride
+    new_shape = (
+        tuple(layout_flat[i].shape for i in nonzero_modes) if len(nonzero_modes) > 0 else (1,),
+        tuple(layout_flat[i].shape for i in zero_modes),
+    )
+    new_stride = (
+        tuple(layout_flat[i].stride for i in nonzero_modes) if len(nonzero_modes) > 0 else (0,),
+        tuple(layout_flat[i].stride for i in zero_modes),
+    )
+    out_layout = cute.make_layout(new_shape, stride=new_stride)
+    if const_expr(isinstance(input, cute.Tensor)):
+        return cute.make_tensor(input.iterator, out_layout)
+    else:
+        return out_layout
+
+
+def mma_partition_C_vec(
+    sVec: cute.Tensor, thr_mma: cute.ThrMma, expand_shape: int, is_colvec: bool
+) -> cute.Tensor:
+    assert cute.rank(sVec) == 2
+    assert sVec.stride[0] == 1
+    stage = sVec.shape[1]
+    shape = (
+        (sVec.shape[0], expand_shape, stage)
+        if const_expr(is_colvec)
+        else (expand_shape, sVec.shape[0], stage)
+    )
+    stride = (1, 0, sVec.stride[1]) if const_expr(is_colvec) else (0, 1, sVec.stride[1])
+    sVec_mma = cute.make_tensor(sVec.iterator, cute.make_layout(shape, stride=stride))
+    tC_sVec = make_acc_tensor_mn_view(thr_mma.partition_C(sVec_mma))
+    return tC_sVec[None, 0, None] if const_expr(is_colvec) else tC_sVec[0, None, None]
+
+
+def mma_partition_A_vec(
+    sVec: cute.Tensor, thr_mma: cute.ThrMma, expand_shape: int, is_colvec: bool
+) -> cute.Tensor:
+    assert cute.rank(sVec) == 2
+    assert sVec.stride[0] == 1
+    stage = sVec.shape[1]
+    shape = (
+        (sVec.shape[0], expand_shape, stage)
+        if const_expr(is_colvec)
+        else (expand_shape, sVec.shape[0], stage)
+    )
+    stride = (1, 0, sVec.stride[1]) if const_expr(is_colvec) else (0, 1, sVec.stride[1])
+    sVec_mma = cute.make_tensor(sVec.iterator, cute.make_layout(shape, stride=stride))
+    tC_sVec = make_acc_tensor_mn_view(thr_mma.partition_A(sVec_mma))
+    return tC_sVec[None, 0, None] if const_expr(is_colvec) else tC_sVec[0, None, None]
+
+
+def copy_partition_S_vec(
+    sVec: cute.Tensor, thr_copy: cute.ThrCopy, expand_shape: int, is_colvec: bool
+) -> cute.Tensor:
+    assert cute.rank(sVec) == 2
+    assert sVec.stride[0] == 1
+    stage = sVec.shape[1]
+    shape = (
+        (sVec.shape[0], expand_shape, stage)
+        if const_expr(is_colvec)
+        else (expand_shape, sVec.shape[0], stage)
+    )
+    stride = (1, 0, sVec.stride[1]) if const_expr(is_colvec) else (0, 1, sVec.stride[1])
+    sVec_thr = cute.make_tensor(sVec.iterator, cute.make_layout(shape, stride=stride))
+    tC_sVec = reshape_acc_to_mn(thr_copy.partition_S(sVec_thr))
+    return tC_sVec[None, 0, None] if const_expr(is_colvec) else tC_sVec[0, None, None]
+
+
+def copy_partition_D_vec(
+    sVec: cute.Tensor, thr_copy: cute.ThrCopy, expand_shape: int, is_colvec: bool
+) -> cute.Tensor:
+    assert cute.rank(sVec) == 2
+    assert sVec.stride[0] == 1
+    stage = sVec.shape[1]
+    shape = (
+        (sVec.shape[0], expand_shape, stage)
+        if const_expr(is_colvec)
+        else (expand_shape, sVec.shape[0], stage)
+    )
+    stride = (1, 0, sVec.stride[1]) if const_expr(is_colvec) else (0, 1, sVec.stride[1])
+    sVec_thr = cute.make_tensor(sVec.iterator, cute.make_layout(shape, stride=stride))
+    tC_sVec = reshape_acc_to_mn(thr_copy.partition_D(sVec_thr))
+    return tC_sVec[None, 0, None] if const_expr(is_colvec) else tC_sVec[0, None, None]
+
+
+def tile_atom_to_shape_SF_strided(
+    shape: cute.Shape,
+    sf_vec_size: int,
+    sf_strides,
+) -> cute.Layout:
+    """Build an SFA/SFB layout matching `shape` (A or B operand shape) but
+    honoring the scale tensor's actual strides instead of hardcoded packed
+    ones.
+
+    Mirrors `cutlass.utils.blockscaled_layout.tile_atom_to_shape_SF(shape,
+    sf_vec_size)`, except outer-mode strides come from `sf_strides` (pass
+    `mSFA.stride` / `mSFB.stride` directly). The inner 512-B atom
+    `((32, 4), (sf_vec_size, 4)) : ((16, 4), (0, 1))` is hardware-fixed.
+
+    Implementation uses `cute.blocked_product(atom, outer)`; `blocked_product`
+    scales the outer layout's strides by `cosize(atom) == 512`, so we divide
+    the byte strides by 512 (one tile) before handing them in.
+
+    Args:
+        shape: A/B operand shape. Rank-3 `(m/n, k, l)` or rank-2
+            `(total_mn, k)` (varlen_m).
+        sf_vec_size: Scale factor vector size (16 or 32).
+        sf_strides: Strides of the scale tensor, which has logical shape
+            `(L, rmn, rk, 512)` (rank 4). Only `sf_strides[0..2]` are used:
+            `sf_strides[1]` as the rmn stride, `sf_strides[2]` as the rk
+            stride, and `sf_strides[0]` as the L stride (only for rank-3
+            `shape`).
+    """
+    from cutlass.utils.blockscaled_layout import BlockScaledBasicChunk
+
+    atom = BlockScaledBasicChunk(sf_vec_size).layout
+    rmn = cute.ceil_div(shape[0], 128)
+    rk = cute.ceil_div(shape[1], sf_vec_size * 4)
+    outer = cute.make_layout((rmn, rk), stride=(sf_strides[1] // 512, sf_strides[2] // 512))
+    sf_layout = cute.blocked_product(atom, outer)
+    if const_expr(len(shape) == 3):
+        sf_layout = cute.append(sf_layout, cute.make_layout(shape[2], stride=sf_strides[0]))
+    return sf_layout
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/mx_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/mx_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5184bc9238dc9444f3d0bf91a65b4941512abe6e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/mx_utils.py
@@ -0,0 +1,269 @@
+"""Minimal MX / NVFP4 quantization + scale swizzling utilities.
+
+Ported from torchao (BSD-3) to avoid the runtime dependency:
+  torchao/prototype/mx_formats/{mx_tensor, nvfp4_tensor, utils, constants}.py
+  torchao/prototype/custom_fp_utils.py
+  torchao/prototype/mx_formats/kernels.py
+
+All quantizers are pure-PyTorch. Use the `to_mx_compiled` / `to_mxfp4_compiled` /
+`to_nvfp4_compiled` module-level handles if you want torch.compile-generated
+Triton kernels (much faster on big tensors; one-time compile overhead).
+
+Only the FLOOR scaling mode is ported (torchao's default for MX formats).
+"""
+
+import torch
+
+F8E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max  # 448.0
+F8E4M3_MAX_POW2 = 8
+E8M0_EXPONENT_BIAS = 127
+E8M0_EXPONENT_NAN_VAL = 255
+F32_EXP_BIAS = 127
+F32_MIN_NORMAL = 2 ** (-F32_EXP_BIAS + 1)  # 2**-126
+MBITS_F32 = 23
+EBITS_F32 = 8
+
+# FP4 E2M1 constants
+F4_E2M1_MAX = 6.0
+F4_E2M1_MAX_POW2 = 2
+F4_E2M1_MAX_INT = 7  # 3-bit magnitude mask
+EBITS_F4_E2M1, MBITS_F4_E2M1 = 2, 1
+
+E4M3_EPS = torch.finfo(torch.float8_e4m3fn).tiny
+
+
+def _n_ones(n: int) -> int:
+    return (1 << n) - 1
+
+
+def to_mx(data_hp: torch.Tensor, block_size: int = 32):
+    """MXFP8-e4m3 quantization with FLOOR scaling.
+
+    Args:
+        data_hp: (..., K) bf16 or fp32 tensor, contiguous, K % block_size == 0.
+    Returns:
+        qdata: (..., K) float8_e4m3fn
+        scale: (..., K // block_size) float8_e8m0fnu
+    """
+    assert data_hp.dtype in (torch.bfloat16, torch.float32)
+    assert data_hp.shape[-1] % block_size == 0
+    assert data_hp.is_contiguous()
+
+    orig_shape = data_hp.shape
+    data_hp = data_hp.reshape(*orig_shape[:-1], orig_shape[-1] // block_size, block_size)
+    max_abs = torch.amax(torch.abs(data_hp), -1).unsqueeze(-1)
+
+    data_hp = data_hp.to(torch.float32)
+    max_abs = max_abs.to(torch.float32)
+
+    # FLOOR scaling: extract biased exponent of max_abs via bit-shift
+    max_abs_int32 = max_abs.view(torch.int32)
+    extracted_pow2 = ((torch.bitwise_right_shift(max_abs_int32, MBITS_F32)) & 0xFF) - F32_EXP_BIAS
+    scale_e8m0_unbiased = extracted_pow2 - F8E4M3_MAX_POW2
+    scale_e8m0_unbiased = torch.clamp(
+        scale_e8m0_unbiased, min=-E8M0_EXPONENT_BIAS, max=E8M0_EXPONENT_BIAS + 1
+    )
+    scale_e8m0_biased = (scale_e8m0_unbiased + E8M0_EXPONENT_BIAS).to(torch.uint8)
+    # restore NaN sentinel (uint8 cast drops NaN)
+    scale_e8m0_biased = torch.where(torch.isnan(max_abs), E8M0_EXPONENT_NAN_VAL, scale_e8m0_biased)
+
+    # reconstruct fp32 scale from biased exponent
+    scale_fp32 = (torch.bitwise_left_shift(scale_e8m0_biased.to(torch.int32), MBITS_F32)).view(
+        torch.float32
+    )
+    # avoid 2**-127 being flushed to 0 (pytorch #125557)
+    scale_fp32 = torch.clamp(scale_fp32, min=F32_MIN_NORMAL)
+
+    data_lp = data_hp / scale_fp32
+    # eager fp8 cast is unsaturated; clamp explicitly
+    if not torch._dynamo.is_compiling():
+        data_lp = torch.clamp(data_lp, min=-F8E4M3_MAX, max=F8E4M3_MAX)
+
+    qdata = data_lp.to(torch.float8_e4m3fn).reshape(orig_shape)
+    scale = scale_e8m0_biased.view(torch.float8_e8m0fnu).squeeze(-1)
+    return qdata, scale
+
+
+def _f32_to_floatx_unpacked(x: torch.Tensor, ebits: int, mbits: int) -> torch.Tensor:
+    """FP32 -> sub-byte float (uint8, code in low bits). Verbatim from torchao.
+
+    Round-to-nearest-even via magic-adder; saturation on overflow; no NaN.
+    """
+    assert x.dtype == torch.float
+    assert 1 + ebits + mbits <= 8
+    exp_bias = _n_ones(ebits - 1)
+    max_int = _n_ones(ebits + mbits)
+    sign_mask = 1 << (ebits + mbits)
+    magic_adder = _n_ones(MBITS_F32 - mbits - 1)
+    max_normal = 2 ** (_n_ones(ebits) - exp_bias) * (_n_ones(mbits + 1) / (2**mbits))
+    min_normal = 2 ** (1 - exp_bias)
+    denorm_exp = (F32_EXP_BIAS - exp_bias) + (MBITS_F32 - mbits) + 1
+    denorm_mask_int = denorm_exp << MBITS_F32
+    denorm_mask_float = torch.tensor(denorm_mask_int, dtype=torch.int32).view(torch.float32)
+
+    x = x.view(torch.int32)
+    sign = x & 0x80000000
+    x = x ^ sign
+    x = x.view(torch.float)
+    saturate_mask = x >= max_normal
+    denormal_mask = torch.logical_and(torch.logical_not(saturate_mask), x < min_normal)
+    normal_mask = torch.logical_not(torch.logical_or(saturate_mask, denormal_mask))
+    denormal_x = x + denorm_mask_float
+    denormal_x = denormal_x.view(torch.int32)
+    denormal_x -= denorm_mask_int
+    denormal_x = denormal_x.to(torch.uint8)
+    normal_x = x.view(torch.int32)
+    mant_odd = (normal_x >> (MBITS_F32 - mbits)) & 1
+    val_to_add = ((exp_bias - F32_EXP_BIAS) << MBITS_F32) + magic_adder
+    normal_x += val_to_add
+    normal_x += mant_odd
+    normal_x = normal_x >> (MBITS_F32 - mbits)
+    normal_x = normal_x.to(torch.uint8)
+    x = torch.full_like(x, max_int, dtype=torch.uint8)
+    x = torch.where(denormal_mask, denormal_x, x)
+    x = torch.where(normal_mask, normal_x, x)
+    sign_lp = sign >> (MBITS_F32 + EBITS_F32 - mbits - ebits)
+    sign_lp = sign_lp.to(torch.uint8)
+    sign_lp = sign_lp & sign_mask
+    x = x | sign_lp
+    return x.to(torch.uint8)
+
+
+def _pack_uint4(uint8_data: torch.Tensor) -> torch.Tensor:
+    """Pack 4-bit uint8 values in pairs: pair (a,b) -> byte (b<<4 | a)."""
+    shape = uint8_data.shape
+    assert shape[-1] % 2 == 0
+    uint8_data = uint8_data.contiguous().view(-1)
+    return (uint8_data[::2] | uint8_data[1::2] << 4).view(*shape[:-1], shape[-1] // 2)
+
+
+def _compute_e8m0_scale_floor(max_abs: torch.Tensor, target_max_pow2: int) -> torch.Tensor:
+    """Return biased E8M0 scale (uint8) for FLOOR-mode MX quantization."""
+    max_abs_int32 = max_abs.view(torch.int32)
+    extracted_pow2 = ((torch.bitwise_right_shift(max_abs_int32, MBITS_F32)) & 0xFF) - F32_EXP_BIAS
+    scale_unbiased = extracted_pow2 - target_max_pow2
+    scale_unbiased = torch.clamp(
+        scale_unbiased, min=-E8M0_EXPONENT_BIAS, max=E8M0_EXPONENT_BIAS + 1
+    )
+    scale_biased = (scale_unbiased + E8M0_EXPONENT_BIAS).to(torch.uint8)
+    scale_biased = torch.where(torch.isnan(max_abs), E8M0_EXPONENT_NAN_VAL, scale_biased)
+    return scale_biased
+
+
+def to_mxfp4(x: torch.Tensor, block_size: int = 32):
+    """MXFP4 quantization: E2M1 data + E8M0 per-block scales, FLOOR scaling.
+
+    Args:
+        x: (..., K) bf16/fp16/fp32, contiguous, K % block_size == 0.
+    Returns:
+        qdata_packed: uint8, shape (..., K // 2). Two FP4 values per byte
+                      (first -> low nibble, second -> high nibble).
+        scale: float8_e8m0fnu, shape (..., K // block_size).
+    """
+    assert x.dtype in (torch.bfloat16, torch.float16, torch.float32)
+    assert x.shape[-1] % block_size == 0
+    assert x.is_contiguous()
+
+    orig_shape = x.shape
+    data_hp = x.reshape(*orig_shape[:-1], orig_shape[-1] // block_size, block_size)
+    max_abs = torch.amax(torch.abs(data_hp), -1).unsqueeze(-1)
+    data_hp = data_hp.to(torch.float32)
+    max_abs = max_abs.to(torch.float32)
+
+    scale_biased = _compute_e8m0_scale_floor(max_abs, F4_E2M1_MAX_POW2)
+    scale_fp32 = (torch.bitwise_left_shift(scale_biased.to(torch.int32), MBITS_F32)).view(
+        torch.float32
+    )
+    scale_fp32 = torch.clamp(scale_fp32, min=F32_MIN_NORMAL)
+
+    data_lp = data_hp / scale_fp32
+    data_lp = data_lp.reshape(orig_shape)
+    data_lp = _f32_to_floatx_unpacked(data_lp.float(), EBITS_F4_E2M1, MBITS_F4_E2M1)
+    data_lp = _pack_uint4(data_lp)
+
+    scale = scale_biased.view(torch.float8_e8m0fnu).squeeze(-1)
+    return data_lp, scale
+
+
+def nvfp4_per_tensor_scale(amax: torch.Tensor) -> torch.Tensor:
+    """NVFP4 per-tensor scale: amax / (F8E4M3_MAX * F4_E2M1_MAX) = amax / 2688."""
+    return amax.to(torch.float32) / (F8E4M3_MAX * F4_E2M1_MAX)
+
+
+def to_nvfp4(x: torch.Tensor, block_size: int = 16, per_tensor_scale=None):
+    """NVFP4 quantization: E2M1 data + E4M3 per-block scales + optional fp32 per-tensor scale.
+
+    Args:
+        x: (..., K) bf16/fp32, contiguous, K % 16 == 0.
+        block_size: must be 16.
+        per_tensor_scale: scalar fp32 tensor, or None (uses 1.0 / returns unit).
+    Returns:
+        qdata_packed: uint8, shape (..., K // 2)
+        scale: float8_e4m3fn, shape (..., K // 16)
+        per_tensor_scale: scalar fp32 tensor (1.0 if None was passed)
+    """
+    assert x.dtype in (torch.bfloat16, torch.float32)
+    assert x.shape[-1] % block_size == 0
+    assert x.is_contiguous()
+    assert block_size == 16, "NVFP4 requires block_size=16"
+
+    orig_shape = x.shape
+    data_hp = x.float().reshape(*orig_shape[:-1], orig_shape[-1] // block_size, block_size)
+    max_abs = torch.amax(torch.abs(data_hp), dim=-1)
+    block_scale = max_abs / F4_E2M1_MAX
+
+    if per_tensor_scale is None:
+        block_scale_fp8 = torch.clamp(block_scale, min=E4M3_EPS, max=F8E4M3_MAX).to(
+            torch.float8_e4m3fn
+        )
+        recip = 1.0 / block_scale_fp8.to(torch.float32)
+        returned_pts = torch.tensor(1.0, dtype=torch.float32, device=x.device)
+    else:
+        scaled = block_scale.to(torch.float32) / per_tensor_scale
+        block_scale_fp8 = torch.clamp(scaled, min=E4M3_EPS, max=F8E4M3_MAX).to(torch.float8_e4m3fn)
+        recip = (1.0 / per_tensor_scale) / block_scale_fp8.to(torch.float32)
+        returned_pts = per_tensor_scale.to(torch.float32)
+
+    data_scaled = data_hp * recip.unsqueeze(-1)
+    data_scaled = torch.clamp(data_scaled, -F4_E2M1_MAX, F4_E2M1_MAX)
+    data_scaled = data_scaled.view(orig_shape)
+    data_lp = _f32_to_floatx_unpacked(data_scaled.float(), EBITS_F4_E2M1, MBITS_F4_E2M1)
+    data_lp = _pack_uint4(data_lp)
+    return data_lp, block_scale_fp8, returned_pts
+
+
+# ---------------------------------------------------------------------------
+# torch.compile-wrapped fast paths. Generates fused Triton quant kernels via
+# Inductor. dynamic=True avoids recompilation on shape changes.
+# ---------------------------------------------------------------------------
+to_mx_compiled = torch.compile(to_mx, dynamic=True)
+to_mxfp4_compiled = torch.compile(to_mxfp4, dynamic=True)
+to_nvfp4_compiled = torch.compile(to_nvfp4, dynamic=True)
+
+
+def _ceil_div(a, b):
+    return (a + b - 1) // b
+
+
+def to_blocked(input_matrix: torch.Tensor) -> torch.Tensor:
+    """Swizzle a (H, W) e8m0 scale tensor into the 128x4 blocked layout
+    cuBLAS expects for MXFP8 _scaled_mm. Returns a 1-D flat tensor of size
+    32*ceil(H/128) * 16*ceil(W/4)."""
+    rows, cols = input_matrix.shape
+    n_row_blocks = _ceil_div(rows, 128)
+    n_col_blocks = _ceil_div(cols, 4)
+    padded_rows = n_row_blocks * 128
+    padded_cols = n_col_blocks * 4
+
+    padded = input_matrix
+    if torch.compiler.is_compiling() or (rows, cols) != (padded_rows, padded_cols):
+        padded = torch.zeros(
+            (padded_rows, padded_cols),
+            device=input_matrix.device,
+            dtype=input_matrix.dtype,
+        )
+        padded[:rows, :cols] = input_matrix
+
+    blocks = padded.view(n_row_blocks, 128, n_col_blocks, 4).permute(0, 2, 1, 3)
+    rearranged = blocks.reshape(-1, 4, 32, 4).transpose(1, 2).reshape(-1, 32, 16)
+    return rearranged.flatten()
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/pipeline.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/pipeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..7589ff555c24357626e0473d0fb9d34c83546d0f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/pipeline.py
@@ -0,0 +1,619 @@
+# Copyright (c) 2025-2026, Tri Dao.
+
+from typing import Optional
+from dataclasses import dataclass
+
+import cutlass.cute as cute
+from cutlass import Boolean, Int32, const_expr
+from cutlass.cutlass_dsl import if_generate, and_, dsl_user_op
+from cutlass.pipeline import MbarrierArray, CooperativeGroup, PipelineOp
+from cutlass.pipeline import PipelineState, PipelineUserType
+from cutlass.pipeline import Agent, agent_sync
+from cutlass.pipeline import NamedBarrier as NamedBarrierOg
+from cutlass.pipeline import PipelineAsync as PipelineAsyncOg
+from cutlass.pipeline import PipelineCpAsync as PipelineCpAsyncOg
+from cutlass.pipeline import PipelineTmaAsync as PipelineTmaAsyncOg
+from cutlass.pipeline import PipelineTmaUmma as PipelineTmaUmmaOg
+from cutlass.pipeline import PipelineUmmaAsync as PipelineUmmaAsyncOg
+from cutlass.pipeline import PipelineAsyncUmma as PipelineAsyncUmmaOg
+
+
+# ── Shared helpers ───────────────────────────────────────────────────────────
+
+
+def _override_create(parent_cls, child_cls):
+    """Create a static factory that constructs parent_cls then re-classes to child_cls."""
+
+    @staticmethod
+    def create(*args, **kwargs):
+        obj = parent_cls.create(*args, **kwargs)
+        # Can't assign to __class__ directly since the dataclass is frozen
+        object.__setattr__(obj, "__class__", child_cls)
+        return obj
+
+    return create
+
+
+def _make_state(index: Int32, phase: Int32) -> PipelineState:
+    """Construct a PipelineState from index and phase (count/stages unused by callers)."""
+    return PipelineState(stages=0, count=Int32(0), index=index, phase=phase)
+
+
+def _call_with_elect_one(parent_method, self, state, elect_one, syncwarp, loc, ip):
+    """Optionally wrap a parent pipeline method call in sync_warp + elect_one."""
+    if const_expr(elect_one):
+        if const_expr(syncwarp):
+            cute.arch.sync_warp()
+        with cute.arch.elect_one():
+            parent_method(self, state, loc=loc, ip=ip)
+    else:
+        parent_method(self, state, loc=loc, ip=ip)
+
+
+# ── Pipeline state ──────────────────────────────────────────────────────────
+
+
+class PipelineStateWAdvance(PipelineState):
+    @dsl_user_op
+    def advance_iters(self, num_iterations: Int32, *, loc=None, ip=None):
+        self._count += Int32(num_iterations)
+        new_index = self._index + Int32(num_iterations)
+        # How many times did we cross the stages boundary
+        num_crossings = new_index // self.stages
+        self._phase ^= num_crossings
+        self._index = new_index % self.stages
+
+    # This can be overridden by derived classes
+    def __new_from_mlir_values__(self, values):
+        return PipelineStateWAdvance(
+            self.stages, Int32(values[0]), Int32(values[1]), Int32(values[2])
+        )
+
+
+def make_pipeline_state(type: PipelineUserType, stages: int):
+    """
+    Creates a pipeline state. Producers are assumed to start with an empty buffer and have a flipped phase bit of 1.
+    """
+    if type is PipelineUserType.Producer:
+        return PipelineStateWAdvance(stages, Int32(0), Int32(0), Int32(1))
+    elif type is PipelineUserType.Consumer:
+        return PipelineStateWAdvance(stages, Int32(0), Int32(0), Int32(0))
+    else:
+        assert False, "Error: invalid PipelineUserType specified for make_pipeline_state."
+
+
+# ── Mixin: _w_index / _w_index_phase variants ───────────────────────────────
+
+
+class _PipelineIndexPhaseMixin:
+    """Mixin providing _w_index_phase / _w_index methods that delegate to PipelineState-based parents."""
+
+    @dsl_user_op
+    def producer_acquire_w_index_phase(
+        self,
+        index: Int32,
+        phase: Int32,
+        try_acquire_token: Optional[Boolean] = None,
+        *,
+        loc=None,
+        ip=None,
+    ):
+        state = _make_state(index, phase)
+        self.producer_acquire(state, try_acquire_token, loc=loc, ip=ip)
+
+    @dsl_user_op
+    def producer_commit_w_index(self, index: Int32, *, loc=None, ip=None):
+        state = _make_state(index, Int32(0))
+        self.producer_commit(state, loc=loc, ip=ip)
+
+    @dsl_user_op
+    def consumer_wait_w_index_phase(
+        self,
+        index: Int32,
+        phase: Int32,
+        try_wait_token: Optional[Boolean] = None,
+        *,
+        loc=None,
+        ip=None,
+    ):
+        state = _make_state(index, phase)
+        self.consumer_wait(state, try_wait_token, loc=loc, ip=ip)
+
+    @dsl_user_op
+    def consumer_release_w_index(self, index: Int32, *, loc=None, ip=None):
+        state = _make_state(index, Int32(0))
+        self.consumer_release(state, loc=loc, ip=ip)
+
+
+# ── NamedBarrier ─────────────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class NamedBarrier(NamedBarrierOg):
+    create = _override_create(NamedBarrierOg, None)  # patched below
+
+    @dsl_user_op
+    def arrive_w_index(self, index: Int32, *, loc=None, ip=None) -> None:
+        """
+        The aligned flavor of arrive is used when all threads in the CTA will execute the
+        same instruction. See PTX documentation.
+        """
+        cute.arch.barrier_arrive(
+            barrier_id=self.barrier_id + index,
+            number_of_threads=self.num_threads,
+            loc=loc,
+            ip=ip,
+        )
+
+    @dsl_user_op
+    def arrive_and_wait_w_index(self, index: Int32, *, loc=None, ip=None) -> None:
+        cute.arch.barrier(
+            barrier_id=self.barrier_id + index,
+            number_of_threads=self.num_threads,
+            loc=loc,
+            ip=ip,
+        )
+
+
+NamedBarrier.create = _override_create(NamedBarrierOg, NamedBarrier)
+
+
+# ── PipelineAsync ────────────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class PipelineAsync(_PipelineIndexPhaseMixin, PipelineAsyncOg):
+    """
+    PipelineAsync with optional elect_one for producer_commit and consumer_release.
+
+    When elect_one_*=True (set at create time), only one elected thread per warp
+    signals the barrier arrive. This is useful when the mask count is set to 1 per warp.
+
+    Args (to create):
+        elect_one_commit: If True, only elected thread signals producer_commit.
+        syncwarp_before_commit: If True (default), issue syncwarp before elect_one.
+        elect_one_release: If True, only elected thread signals consumer_release.
+        syncwarp_before_release: If True (default), issue syncwarp before elect_one.
+            Set syncwarp to False when threads are already converged (e.g. after wgmma wait_group).
+    """
+
+    _elect_one_commit: bool = False
+    _syncwarp_before_commit: bool = True
+    _elect_one_release: bool = False
+    _syncwarp_before_release: bool = True
+
+    @staticmethod
+    def create(
+        *args,
+        elect_one_commit: bool = False,
+        syncwarp_before_commit: bool = True,
+        elect_one_release: bool = False,
+        syncwarp_before_release: bool = True,
+        **kwargs,
+    ):
+        obj = PipelineAsyncOg.create(*args, **kwargs)
+        object.__setattr__(obj, "__class__", PipelineAsync)
+        object.__setattr__(obj, "_elect_one_commit", elect_one_commit)
+        object.__setattr__(obj, "_syncwarp_before_commit", syncwarp_before_commit)
+        object.__setattr__(obj, "_elect_one_release", elect_one_release)
+        object.__setattr__(obj, "_syncwarp_before_release", syncwarp_before_release)
+        return obj
+
+    @dsl_user_op
+    def producer_commit(self, state: PipelineState, *, loc=None, ip=None):
+        _call_with_elect_one(
+            PipelineAsyncOg.producer_commit,
+            self,
+            state,
+            self._elect_one_commit,
+            self._syncwarp_before_commit,
+            loc,
+            ip,
+        )
+
+    @dsl_user_op
+    def consumer_release(self, state: PipelineState, *, loc=None, ip=None):
+        _call_with_elect_one(
+            PipelineAsyncOg.consumer_release,
+            self,
+            state,
+            self._elect_one_release,
+            self._syncwarp_before_release,
+            loc,
+            ip,
+        )
+
+    # _w_index variants inherited from _PipelineIndexPhaseMixin, which delegate
+    # to producer_commit / consumer_release above.
+
+
+# ── PipelineCpAsync ──────────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class PipelineCpAsync(_PipelineIndexPhaseMixin, PipelineCpAsyncOg):
+    _elect_one_release: bool = False
+    _syncwarp_before_release: bool = True
+
+    @staticmethod
+    def create(
+        *args,
+        elect_one_release: bool = False,
+        syncwarp_before_release: bool = True,
+        **kwargs,
+    ):
+        obj = PipelineCpAsyncOg.create(*args, **kwargs)
+        object.__setattr__(obj, "__class__", PipelineCpAsync)
+        object.__setattr__(obj, "_elect_one_release", elect_one_release)
+        object.__setattr__(obj, "_syncwarp_before_release", syncwarp_before_release)
+        return obj
+
+    @dsl_user_op
+    def consumer_release(self, state: PipelineState, *, loc=None, ip=None):
+        _call_with_elect_one(
+            PipelineCpAsyncOg.consumer_release,
+            self,
+            state,
+            self._elect_one_release,
+            self._syncwarp_before_release,
+            loc,
+            ip,
+        )
+
+    # _w_index variants inherited from _PipelineIndexPhaseMixin.
+
+
+# ── PipelineTmaAsync ────────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class PipelineTmaAsync(_PipelineIndexPhaseMixin, PipelineTmaAsyncOg):
+    """Override producer_acquire to take in extra_tx_count parameter."""
+
+    @dsl_user_op
+    def producer_acquire(
+        self,
+        state: PipelineState,
+        try_acquire_token: Optional[Boolean] = None,
+        extra_tx_count: int = 0,
+        *,
+        loc=None,
+        ip=None,
+    ):
+        """
+        TMA producer commit conditionally waits on buffer empty and sets the transaction barrier for leader threadblocks.
+        """
+        if_generate(
+            try_acquire_token is None or try_acquire_token == 0,
+            lambda: self.sync_object_empty.wait(state.index, state.phase, loc=loc, ip=ip),
+            loc=loc,
+            ip=ip,
+        )
+        if const_expr(extra_tx_count == 0):
+            self.sync_object_full.arrive(state.index, self.producer_mask, loc=loc, ip=ip)
+        else:
+            tx_count = self.sync_object_full.tx_count + extra_tx_count
+            self.sync_object_full.arrive_and_expect_tx(state.index, tx_count, loc=loc, ip=ip)
+
+
+PipelineTmaAsync.create = _override_create(PipelineTmaAsyncOg, PipelineTmaAsync)
+
+
+# ── PipelineTmaUmma ─────────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class PipelineTmaUmma(_PipelineIndexPhaseMixin, PipelineTmaUmmaOg):
+    """Override producer_acquire to take in extra_tx_count parameter."""
+
+    @dsl_user_op
+    def producer_acquire(
+        self,
+        state: PipelineState,
+        try_acquire_token: Optional[Boolean] = None,
+        is_tma_warp: Optional[Boolean] = True,
+        extra_tx_count: int = 0,
+        *,
+        loc=None,
+        ip=None,
+    ):
+        """
+        TMA producer commit conditionally waits on buffer empty and sets the transaction barrier for leader threadblocks.
+        """
+        if_generate(
+            try_acquire_token is None or try_acquire_token == 0,
+            lambda: self.sync_object_empty.wait(state.index, state.phase, loc=loc, ip=ip),
+            loc=loc,
+            ip=ip,
+        )
+        # This is the difference between this and PipelineTmaAsync: we could have multiple
+        # warps calling this, but only 1 warp should do the arrive on the full barrier
+        if const_expr(extra_tx_count == 0):
+            if_generate(
+                and_(self.is_leader_cta, is_tma_warp),
+                lambda: self.sync_object_full.arrive(
+                    state.index, self.producer_mask, loc=loc, ip=ip
+                ),
+                loc=loc,
+                ip=ip,
+            )
+        else:
+            tx_count = self.sync_object_full.tx_count + extra_tx_count
+            if_generate(
+                and_(self.is_leader_cta, is_tma_warp),
+                lambda: self.sync_object_full.arrive_and_expect_tx(
+                    state.index, tx_count, loc=loc, ip=ip
+                ),
+                loc=loc,
+                ip=ip,
+            )
+
+
+PipelineTmaUmma.create = _override_create(PipelineTmaUmmaOg, PipelineTmaUmma)
+
+
+# ── PipelineUmmaAsync ───────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class PipelineUmmaAsync(_PipelineIndexPhaseMixin, PipelineUmmaAsyncOg):
+    pass
+
+
+PipelineUmmaAsync.create = _override_create(PipelineUmmaAsyncOg, PipelineUmmaAsync)
+
+
+# ── PipelineAsyncUmma ───────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class PipelineAsyncUmma(_PipelineIndexPhaseMixin, PipelineAsyncUmmaOg):
+    pass
+
+
+PipelineAsyncUmma.create = _override_create(PipelineAsyncUmmaOg, PipelineAsyncUmma)
+
+
+# ── PipelineTmaCpAsync ──────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class PipelineTmaCpAsync(_PipelineIndexPhaseMixin, PipelineTmaAsyncOg):
+    """
+    PipelineTmaCpAsync is used for CpAsync + TMA producers and AsyncThread consumers.
+    Compared to PipelineTmaAsync, producer_acquire gates the full-barrier arrive on is_tma_warp.
+    """
+
+    @dsl_user_op
+    def producer_acquire(
+        self,
+        state: PipelineState,
+        try_acquire_token: Optional[Boolean] = None,
+        is_tma_warp: Optional[Boolean] = True,
+        *,
+        loc=None,
+        ip=None,
+    ):
+        if_generate(
+            try_acquire_token is None or try_acquire_token == 0,
+            lambda: self.sync_object_empty.wait(state.index, state.phase, loc=loc, ip=ip),
+            loc=loc,
+            ip=ip,
+        )
+        # This is the difference between this and PipelineTmaAsync: we could have multiple
+        # warps calling this, but only 1 warp should do the arrive on the full barrier
+        if_generate(
+            is_tma_warp,
+            lambda: self.sync_object_full.arrive(state.index, self.producer_mask, loc=loc, ip=ip),
+            loc=loc,
+            ip=ip,
+        )
+
+    @dsl_user_op
+    def producer_cpasync_commit(self, state: PipelineState, *, loc=None, ip=None):
+        """We need the mbarrier to track the completion of cp.async."""
+        cute.arch.cp_async_mbarrier_arrive_noinc(
+            self.producer_get_barrier(state, loc=loc, ip=ip), loc=loc, ip=ip
+        )
+
+
+PipelineTmaCpAsync.create = _override_create(PipelineTmaAsyncOg, PipelineTmaCpAsync)
+
+
+# ── MbarrierArrayWDropCount ─────────────────────────────────────────────────
+
+
+class MbarrierArrayWDropCount(MbarrierArray):
+    @dsl_user_op
+    def __init__(
+        self,
+        barrier_storage: cute.Pointer,
+        num_stages: int,
+        agent: tuple[PipelineOp, CooperativeGroup],
+        tx_count: int = 0,
+        drop_count: Optional[Int32] = None,
+        *,
+        loc=None,
+        ip=None,
+    ) -> None:
+        self.barrier_storage = barrier_storage
+        self.tx_count = tx_count
+        self.num_stages = num_stages
+        self.op_type, self.cg = agent
+        self.arrive_count = self.cg.size
+        self.drop_count = drop_count
+
+        if self.num_stages <= 0:
+            raise ValueError("Error: Mbarrier stage count must be greater than 0.")
+        if self.arrive_count <= 0:
+            raise ValueError("Error: Mbarrier arrive count must be greater than 0.")
+        if self.op_type is PipelineOp.TmaLoad and self.tx_count < 0:
+            raise ValueError("Error: Mbarrier tx count must not be less than 0 for TMA ops.")
+
+        if const_expr(drop_count is not None):
+            self.arrive_count = self.arrive_count - drop_count
+
+        # Store mbarrier base pointer
+        self.mbarrier_base = self.barrier_storage
+
+        # Mbarrier initialization in constructor
+        self.mbarrier_init(loc=loc, ip=ip)
+
+    def __extract_mlir_values__(self):
+        return [self.barrier_storage, self.drop_count]
+
+    def __new_from_mlir_values__(self, values):
+        return MbarrierArrayWDropCount(
+            values[0], self.num_stages, (self.op_type, self.cg), self.tx_count, values[1]
+        )
+
+
+# ── PipelineTmaCpAsyncUmma ──────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class PipelineTmaCpAsyncUmma(PipelineTmaUmmaOg):
+    """
+    PipelineTmaCpAsync is used for CpAsync + TMA producers and UMMA consumers
+    (e.g. Blackwell mainloops)
+    """
+
+    @dsl_user_op
+    @staticmethod
+    def create(
+        *,
+        num_stages: int,
+        producer_group: CooperativeGroup,
+        consumer_group: CooperativeGroup,
+        tx_count: int,
+        barrier_storage: cute.Pointer = None,
+        cta_layout_vmnk: Optional[cute.Layout] = None,
+        mcast_mode_mn: tuple[int, int] = (1, 1),
+        defer_sync: bool = False,
+        producer_drop_count: Optional[Int32] = None,
+        loc=None,
+        ip=None,
+    ):
+        """Creates and initializes a new PipelineTmaUmma instance.
+
+        :param num_stages: Number of buffer stages for this pipeline
+        :type num_stages: int
+        :param producer_group: CooperativeGroup for the producer agent
+        :type producer_group: CooperativeGroup
+        :param consumer_group: CooperativeGroup for the consumer agent
+        :type consumer_group: CooperativeGroup
+        :param tx_count: Number of bytes expected to be written to the transaction barrier for one stage
+        :type tx_count: int
+        :param barrier_storage: Pointer to the shared memory address for this pipeline's mbarriers
+        :type barrier_storage: cute.Pointer, optional
+        :param cta_layout_vmnk: Layout of the cluster shape
+        :type cta_layout_vmnk: cute.Layout, optional
+        :param mcast_mode_mn: Tuple specifying multicast modes for m and n dimensions (each 0 or 1)
+        :type mcast_mode_mn: tuple[int, int], optional
+        :raises ValueError: If barrier_storage is not a cute.Pointer instance
+        :return: A new PipelineTmaUmma instance configured with the provided parameters
+        :rtype: PipelineTmaUmma
+        """
+        if not isinstance(barrier_storage, cute.Pointer):
+            raise TypeError(
+                f"Expected barrier_storage to be a cute.Pointer, but got {type(barrier_storage)}"
+            )
+
+        producer_type = PipelineOp.TmaLoad
+        consumer_type = PipelineOp.TCGen05Mma
+
+        producer = (producer_type, producer_group)
+        consumer = (consumer_type, consumer_group)
+
+        sync_object_full = MbarrierArrayWDropCount(
+            barrier_storage.align(min_align=8),
+            num_stages,
+            producer,
+            tx_count,
+            drop_count=producer_drop_count,
+            loc=loc,
+            ip=ip,
+        )
+        sync_object_empty = PipelineTmaUmmaOg._make_sync_object(
+            barrier_storage.align(min_align=8) + num_stages,
+            num_stages,
+            consumer,
+            loc=loc,
+            ip=ip,
+        )
+
+        if cta_layout_vmnk is None or cute.size(cta_layout_vmnk, loc=loc, ip=ip) == 1:
+            # No mcast mask if not using clusters
+            producer_mask = None
+            # All threadblocks are leaders if not using clusters
+            is_leader_cta = True
+        else:
+            producer_mask = PipelineTmaUmmaOg._compute_mcast_arrival_mask(
+                cta_layout_vmnk, mcast_mode_mn, loc=loc, ip=ip
+            )
+            is_leader_cta = PipelineTmaUmmaOg._compute_is_leader_cta(
+                cta_layout_vmnk, loc=loc, ip=ip
+            )
+
+        cta_group = (
+            cute.nvgpu.tcgen05.CtaGroup.ONE
+            if cta_layout_vmnk is None or cute.size(cta_layout_vmnk, mode=[0], loc=loc, ip=ip) == 1
+            else cute.nvgpu.tcgen05.CtaGroup.TWO
+        )
+
+        consumer_mask = producer_mask
+
+        if not defer_sync:
+            cute.arch.mbarrier_init_fence()
+            if cta_layout_vmnk is None or cute.size(cta_layout_vmnk, loc=loc, ip=ip) == 1:
+                agent_sync(Agent.ThreadBlock)
+            else:
+                agent_sync(Agent.ThreadBlockCluster, is_relaxed=True)
+
+        return PipelineTmaCpAsyncUmma(
+            sync_object_full,
+            sync_object_empty,
+            num_stages,
+            producer_mask,
+            consumer_mask,
+            is_leader_cta,
+            cta_group,
+        )
+
+    @dsl_user_op
+    def producer_acquire(
+        self,
+        state: PipelineState,
+        try_acquire_token: Optional[Boolean] = None,
+        is_tma_warp: Optional[Boolean] = True,
+        *,
+        loc=None,
+        ip=None,
+    ):
+        """
+        TMA producer commit conditionally waits on buffer empty and sets the
+        transaction barrier for leader threadblocks.
+        """
+        if_generate(
+            try_acquire_token is None or try_acquire_token == 0,
+            lambda: self.sync_object_empty.wait(state.index, state.phase, loc=loc, ip=ip),
+            loc=loc,
+            ip=ip,
+        )
+        # This is the difference between this and PipelineTmaAsync: we could have multiple
+        # warps calling this, but only 1 warp should do the arrive on the full barrier
+        if_generate(
+            and_(self.is_leader_cta, is_tma_warp),
+            lambda: self.sync_object_full.arrive(state.index, self.producer_mask, loc=loc, ip=ip),
+            loc=loc,
+            ip=ip,
+        )
+
+    @dsl_user_op
+    def producer_cpasync_commit(self, state: PipelineState, *, loc=None, ip=None):
+        """
+        We need the mbarrier to track the completion of cp.async
+        """
+        cute.arch.cp_async_mbarrier_arrive_noinc(
+            self.producer_get_barrier(state, loc=loc, ip=ip), loc=loc, ip=ip
+        )
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/reduce.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/reduce.py
new file mode 100644
index 0000000000000000000000000000000000000000..11f7f57499d9d2a1a54b9f15f96b8628fbd823c6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/reduce.py
@@ -0,0 +1,279 @@
+# Copyright (c) 2025, Tri Dao.
+
+import math
+import operator
+from typing import Callable, Optional
+
+import cutlass
+import cutlass.cute as cute
+from cutlass import Int32, Int64, Float32, Boolean, const_expr
+
+from . import utils
+
+
+@cute.jit
+def block_reduce(
+    val: cute.Numeric, op: Callable, reduction_buffer: cute.Tensor, init_val: cute.Numeric = 0.0
+) -> cute.Numeric:
+    """reduction_buffer has shape (num_warps / warp_per_row, warps_per_row)"""
+    lane_idx, warp_idx = cute.arch.lane_idx(), cute.arch.warp_idx()
+    warps_per_row = cute.size(reduction_buffer.shape[1])
+    row_idx, col_idx = warp_idx // warps_per_row, warp_idx % warps_per_row
+    if lane_idx == 0:
+        reduction_buffer[row_idx, col_idx] = val
+    cute.arch.barrier()
+    block_reduce_val = init_val
+    if lane_idx < warps_per_row:
+        block_reduce_val = reduction_buffer[row_idx, lane_idx]
+    return cute.arch.warp_reduction(block_reduce_val, op)
+
+
+@cute.jit
+def cluster_reduce(
+    val: cute.Numeric,
+    op: Callable,
+    reduction_buffer: cute.Tensor,
+    mbar_ptr: cute.Pointer,
+    init_val: cute.Numeric = 0.0,
+    phase: Optional[Int32] = None,
+) -> cute.Numeric:
+    """reduction_buffer has shape (num_warps / warps_per_row, (warps_per_row, cluster_n))"""
+    cta_rank_in_cluster = cute.arch.block_idx_in_cluster()
+    lane_idx, warp_idx = cute.arch.lane_idx(), cute.arch.warp_idx()
+    rows_per_block, (warps_per_row, cluster_n) = reduction_buffer.shape
+    row_idx, col_idx = warp_idx // warps_per_row, warp_idx % warps_per_row
+    if warp_idx == 0:
+        with cute.arch.elect_one():
+            num_warps = rows_per_block * warps_per_row
+            cute.arch.mbarrier_arrive_and_expect_tx(
+                mbar_ptr,
+                num_warps * cluster_n * reduction_buffer.element_type.width // 8,
+            )
+    if lane_idx < cluster_n:
+        utils.store_shared_remote(
+            val,
+            utils.elem_pointer(reduction_buffer, (row_idx, (col_idx, cta_rank_in_cluster))),
+            mbar_ptr,
+            peer_cta_rank_in_cluster=lane_idx,
+        )
+    cute.arch.mbarrier_wait(mbar_ptr, phase=phase if phase is not None else 0)
+    block_reduce_val = init_val
+    num_iter = cute.ceil_div(warps_per_row * cluster_n, cute.arch.WARP_SIZE)
+    for i in cutlass.range_constexpr(num_iter):
+        idx = lane_idx + i * cute.arch.WARP_SIZE
+        if idx < cute.size(reduction_buffer, mode=[1]):
+            block_reduce_val = op(block_reduce_val, reduction_buffer[row_idx, idx])
+    return cute.arch.warp_reduction(block_reduce_val, op)
+
+
+@cute.jit
+def block_or_cluster_reduce(
+    val: cute.Numeric,
+    op: Callable,
+    reduction_buffer: cute.Tensor,
+    mbar_ptr: Optional[cute.Pointer],
+    phase: Optional[Int32] = None,
+    init_val: cute.Numeric = 0.0,
+) -> cute.Numeric:
+    """Perform either block or cluster reduction based on whether mbar_ptr is provided."""
+    if const_expr(mbar_ptr is None):
+        return block_reduce(val, op, reduction_buffer, init_val=init_val)
+    else:
+        return cluster_reduce(val, op, reduction_buffer, mbar_ptr, phase=phase, init_val=init_val)
+
+
+@cute.jit
+def row_reduce(
+    x: cute.TensorSSA | cute.Numeric,
+    op: cute.ReductionOp,
+    threads_per_row: cutlass.Constexpr[int],
+    reduction_buffer: Optional[cute.Tensor] = None,
+    mbar_ptr: Optional[cute.Pointer] = None,
+    phase: Optional[Int32] = None,
+    init_val: cute.Numeric = 0.0,
+    hook_fn: Optional[Callable] = None,
+) -> cute.Numeric:
+    """reduction_buffer must have shape (num_warps / warps_per_row, (warps_per_row, cluster_n))"""
+    if const_expr(isinstance(x, cute.TensorSSA)):
+        val = x.reduce(op, init_val=init_val, reduction_profile=0)
+    else:
+        val = x
+    warp_op = {
+        cute.ReductionOp.ADD: operator.add,
+        cute.ReductionOp.MAX: cute.arch.fmax if const_expr(x.dtype == Float32) else max,
+        cute.ReductionOp.MIN: min,
+        cute.ReductionOp.MUL: operator.mul,
+    }[op]
+    val = cute.arch.warp_reduction(
+        val,
+        warp_op,
+        threads_in_group=min(threads_per_row, cute.arch.WARP_SIZE),
+    )
+    if const_expr(hook_fn is not None):
+        hook_fn()
+    if const_expr(reduction_buffer is not None):
+        warps_per_row, cluster_n = reduction_buffer.shape[1]
+        assert cluster_n == 1 or mbar_ptr is not None, (
+            "mbar_ptr must be provided for cluster reduction"
+        )
+        if const_expr(warps_per_row > 1 or cluster_n > 1):
+            val = block_or_cluster_reduce(
+                val, warp_op, reduction_buffer, mbar_ptr, phase=phase, init_val=init_val
+            )
+    return val
+
+
+@cute.jit
+def online_softmax_reduce(
+    x: cute.TensorSSA,
+    threads_per_row: cutlass.Constexpr[int],
+    reduction_buffer: Optional[cute.Tensor] = None,
+    mbar_ptr: Optional[cute.Pointer] = None,
+    hook_fn: Optional[Callable] = None,
+    phase: Optional[Int32] = None,
+    return_exp_x: bool = False,
+) -> [Float32, Float32, Optional[cute.TensorSSA]]:
+    assert x.dtype == Float32, "x must be of type Float32"
+    """reduction_buffer must have shape (num_warps / warps_per_row, (warps_per_row, cluster_n), 2)"""
+    max_x = cute.arch.warp_reduction(
+        x.reduce(cute.ReductionOp.MAX, init_val=-Float32.inf, reduction_profile=0),
+        cute.arch.fmax,
+        threads_in_group=min(threads_per_row, cute.arch.WARP_SIZE),
+    )
+    log2_e = math.log2(math.e)
+    exp_x = cute.math.exp2(x * log2_e - (max_x * log2_e), fastmath=True)
+    sum_exp_x = cute.arch.warp_reduction(
+        exp_x.reduce(cute.ReductionOp.ADD, init_val=0.0, reduction_profile=0),
+        operator.add,
+        threads_in_group=min(threads_per_row, cute.arch.WARP_SIZE),
+    )
+    if const_expr(hook_fn is not None):
+        hook_fn()
+    if const_expr(reduction_buffer is not None):
+        rows_per_block, (warps_per_row, cluster_n) = reduction_buffer.shape
+        assert cluster_n == 1 or mbar_ptr is not None, (
+            "mbar_ptr must be provided for cluster reduction"
+        )
+        if const_expr(warps_per_row > 1 or cluster_n > 1):
+            assert reduction_buffer.element_type == Int64, (
+                "reduction_buffer must be of type cute.Int64"
+            )
+            lane_idx, warp_idx = cute.arch.lane_idx(), cute.arch.warp_idx()
+            row_idx, col_idx = warp_idx // warps_per_row, warp_idx % warps_per_row
+            if const_expr(mbar_ptr is None):
+                if lane_idx == 0:
+                    reduction_buffer[row_idx, col_idx] = utils.f32x2_to_i64(max_x, sum_exp_x)
+                cute.arch.barrier()
+                max_x_single_warp = -Float32.inf
+                sum_exp_x = 0.0
+                if lane_idx < warps_per_row:
+                    max_x_single_warp, sum_exp_x = utils.i64_to_f32x2(
+                        reduction_buffer[row_idx, lane_idx]
+                    )
+                max_x_final = cute.arch.warp_reduction(max_x_single_warp, cute.arch.fmax)
+                sum_exp_x *= cute.math.exp(max_x_single_warp - max_x_final, fastmath=True)
+                sum_exp_x = cute.arch.warp_reduction(sum_exp_x, operator.add)
+                if const_expr(return_exp_x):
+                    exp_x *= cute.math.exp(max_x - max_x_final, fastmath=True)
+                max_x = max_x_final
+            else:
+                cta_rank_in_cluster = cute.arch.block_idx_in_cluster()
+                if warp_idx == 0:
+                    with cute.arch.elect_one():
+                        num_warps = rows_per_block * warps_per_row
+                        cute.arch.mbarrier_arrive_and_expect_tx(
+                            mbar_ptr,
+                            num_warps * cluster_n * reduction_buffer.element_type.width // 8,
+                        )
+                if lane_idx < cluster_n:
+                    utils.store_shared_remote(
+                        utils.f32x2_to_i64(max_x, sum_exp_x),
+                        utils.elem_pointer(
+                            reduction_buffer, (row_idx, (col_idx, cta_rank_in_cluster))
+                        ),
+                        mbar_ptr,
+                        peer_cta_rank_in_cluster=lane_idx,
+                    )
+                cute.arch.mbarrier_wait(mbar_ptr, phase=phase if phase is not None else 0)
+                num_iter = cute.ceil_div(warps_per_row * cluster_n, cute.arch.WARP_SIZE)
+                max_x_single_warp = cute.make_rmem_tensor(num_iter, Float32)
+                max_x_single_warp.fill(-Float32.inf)
+                sum_exp_x_single_warp = cute.make_rmem_tensor(num_iter, Float32)
+                sum_exp_x_single_warp.fill(0.0)
+                for i in cutlass.range_constexpr(num_iter):
+                    idx = lane_idx + i * cute.arch.WARP_SIZE
+                    if idx < cute.size(reduction_buffer, mode=[1]):
+                        max_x_single_warp[i], sum_exp_x_single_warp[i] = utils.i64_to_f32x2(
+                            reduction_buffer[row_idx, idx]
+                        )
+                max_x_final = max_x_single_warp.load().reduce(
+                    cute.ReductionOp.MAX, init_val=-Float32.inf, reduction_profile=0
+                )
+                max_x_final = cute.arch.warp_reduction(max_x_final, cute.arch.fmax)
+                sum_exp_x = 0.0
+                for i in cutlass.range_constexpr(num_iter):
+                    sum_exp_x += sum_exp_x_single_warp[i] * cute.math.exp(
+                        max_x_single_warp[i] - max_x_final, fastmath=True
+                    )
+                sum_exp_x = cute.arch.warp_reduction(sum_exp_x, operator.add)
+                if const_expr(return_exp_x):
+                    exp_x *= cute.math.exp(max_x - max_x_final, fastmath=True)
+                max_x = max_x_final
+    return max_x, sum_exp_x, (exp_x if const_expr(return_exp_x) else None)
+
+
+@cute.jit
+def sum_swap_shuffle(
+    X: cute.Tensor, elem_per_lane: int = 1, subwarp_size: int = 1, warp_size: int = 32
+) -> cute.Tensor:
+    """
+    For warp reduction, we use Swap Shuffle
+    The normal way to reduction among threads:
+    use shuffle to let *** the first half of threads *** have *** whole data *** from the second half of threads.
+    After each step of reduction, a half of threads won't work in the following steps.
+    That is, as the reduction progresses, the efficiency of shuffle & reduction instructions gradually change from 1/2, 1/4 to 1/32 (the worst case).
+    To overcome this shortcoming, for a NxN matrix to be reduced among N threads as a 1XN vectors,
+    we use swap & shuffle aiming to let *** each half of threads *** have *** a half of data *** from the other half of threads.
+    After reduction, each half of threads should deal with a (N/2)x(N/2) sub-matrix independently in the following step.
+    We can recursively do this until the problem size is 1.
+    """
+    assert (
+        subwarp_size >= 1
+        and subwarp_size <= 32
+        and subwarp_size == 1 << int(math.log2(subwarp_size))
+    )
+    assert (
+        warp_size <= 32
+        and warp_size % subwarp_size == 0
+        and warp_size == 1 << int(math.log2(warp_size))
+    )
+    lane_idx = cute.arch.lane_idx() // subwarp_size
+    X = cute.logical_divide(X, cute.make_layout(elem_per_lane))  # (elem_per_lane, M)
+    numvec = cute.size(X, mode=[1])
+    assert numvec <= 32 // subwarp_size
+    # If X has more values than warp_size // subwarp_size, we first do a normal warp reduction
+    # to sum up values held by lanes further than size(X) away
+    for i in cutlass.range(
+        int(math.log2(numvec)), int(math.log2(warp_size // subwarp_size)), unroll_full=True
+    ):
+        for v in cutlass.range(cute.size(X), unroll_full=True):
+            shfl_val = cute.arch.shuffle_sync_bfly(X[v], offset=(1 << i) * subwarp_size)
+            X[v] = X[v] + shfl_val
+    for logm in cutlass.range_constexpr(int(math.log2(cute.size(X, mode=[1]))) - 1, -1, -1):
+        m = 1 << logm
+        for r in cutlass.range(m, unroll_full=True):
+            frg_A = X[None, r]
+            frg_B = X[None, r + m]
+            #  First half of threads swap fragments from the first half of data to the second
+            should_swap = not Boolean(lane_idx & m)
+            for v in cutlass.range(cute.size(frg_A), unroll_full=True):
+                # Step 1: swap
+                lower, upper = frg_A[v], frg_B[v]
+                frg_A[v] = upper if should_swap else lower
+                frg_B[v] = lower if should_swap else upper
+                # Step 2: shuffle
+                # each half of threads get a half of data from the other half of threads
+                shfl_val = cute.arch.shuffle_sync_bfly(frg_A[v], offset=m * subwarp_size)
+                # Step 3: reduction
+                frg_A[v] = frg_B[v] + shfl_val
+    return X[None, 0]
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/reduction_base.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/reduction_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..e17c31cd873cf72ae05cf007b2e16b23b059d146
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/reduction_base.py
@@ -0,0 +1,97 @@
+# Copyright (c) 2025, Wentao Guo, Ted Zadouri, Tri Dao.
+
+from typing import Type, Tuple, Optional
+
+import cutlass
+import cutlass.cute as cute
+from cutlass import Int32, Int64, Float32, const_expr
+
+from . import copy_utils
+
+
+class ReductionBase:
+    def __init__(self, dtype: Type[cutlass.Numeric], N: int, stage: int, reduction_dtype=Float32):
+        self.dtype = dtype
+        self.N = N
+        self.stage = stage
+        self.reduction_dtype = reduction_dtype
+
+    def _threads_per_row(self):
+        raise NotImplementedError()
+
+    def _num_threads(self):
+        return 128 if self.N <= 16384 else 256
+
+    def _set_cluster_n(self):
+        self.cluster_n = 1
+
+    def _cap_cluster_n(self, vecsize: int) -> None:
+        """Cap ``cluster_n`` so every peer CTA owns a distinct, non-empty N-tile.
+
+        A clustered launch splits the row across ``cluster_n`` CTAs. If
+        ``threads_per_row * cluster_n`` exceeds the number of vector blocks in the
+        row (``N // vecsize``), one CTA tile already spans the whole row
+        (``tiler_mn[1] >= N``); local_tile then collapses every peer onto tile 0,
+        so the peers re-reduce the same columns and double-count in the cluster
+        reduction. Capping to ``(N // vecsize) // threads_per_row`` guarantees
+        ``tiler_mn[1] < N`` whenever the resulting ``cluster_n > 1``.
+        """
+        max_cluster_n = max(1, (self.N // vecsize) // self._threads_per_row())
+        self.cluster_n = min(self.cluster_n, max_cluster_n)
+
+    def _get_tiled_copy(self, vecsize: int = 1):
+        assert self.N % vecsize == 0, f"Input N {self.N} is not divisible by vector size {vecsize}"
+        threads_per_row = self._threads_per_row()
+        num_threads = self._num_threads()
+        assert num_threads % cute.arch.WARP_SIZE == 0
+        num_blocks_N = cute.ceil_div(self.N // vecsize, threads_per_row * self.cluster_n)
+        tiler_mn = (num_threads // threads_per_row, vecsize * num_blocks_N * threads_per_row)
+        tiled_copy = copy_utils.tiled_copy_2d(self.dtype, threads_per_row, num_threads, vecsize)
+        return tiled_copy, tiler_mn, threads_per_row
+
+    def _get_reduction_buffer_layout(self, tv_layout: cute.Layout, cluster_n: int):
+        num_warps = cute.size(tv_layout, mode=[0]) // cute.arch.WARP_SIZE
+        warps_per_row = (
+            num_warps
+            if cute.rank(tv_layout.shape[0]) == 1
+            else max(tv_layout.shape[0][0] // cute.arch.WARP_SIZE, 1)
+        )
+        return cute.make_ordered_layout(
+            (num_warps // warps_per_row, (warps_per_row, cluster_n), self.stage),
+            order=(1, 0, 2),
+        )
+
+    def _allocate_reduction_buffer_and_mbar(
+        self, smem: cutlass.utils.SmemAllocator, tv_layout: cute.Layout, is_persistent: bool = False
+    ) -> Tuple[cute.Tensor, Optional[cute.Pointer]]:
+        reduction_buffer = smem.allocate_tensor(
+            self.reduction_dtype,
+            self._get_reduction_buffer_layout(tv_layout, self.cluster_n),
+            byte_alignment=8,
+        )
+        if const_expr(self.cluster_n > 1):
+            mbar_ptr = smem.allocate_array(
+                Int64, num_elems=self.stage if not is_persistent else self.stage * 2
+            )
+        else:
+            mbar_ptr = None
+        return reduction_buffer, mbar_ptr
+
+    @cute.jit
+    def _initialize_cluster(
+        self,
+        tidx: Int32,
+        mbar_ptr: cute.Pointer,
+        num_warps: int,
+        is_persistent: bool = False,
+    ):
+        if const_expr(self.cluster_n > 1):
+            if tidx < self.stage:  # Initialize full barrier
+                cute.arch.mbarrier_init(mbar_ptr + tidx, 1)
+                if const_expr(is_persistent):  # Initialize empty barrier
+                    cute.arch.mbarrier_init(
+                        mbar_ptr + self.stage + tidx, num_warps * self.cluster_n
+                    )
+            cute.arch.mbarrier_init_fence()
+            # Cluster arrive after barrier init
+            cute.arch.cluster_arrive_relaxed()
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/rmsnorm.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/rmsnorm.py
new file mode 100644
index 0000000000000000000000000000000000000000..ddfd81d682e6e22135b4de8ddb681c8ecae4bf79
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/rmsnorm.py
@@ -0,0 +1,1549 @@
+# Copyright (c) 2025, Wentao Guo, Ted Zadouri, Tri Dao.
+
+import math
+from typing import Optional, Tuple, Type
+from functools import partial
+
+import cuda.bindings.driver as cuda
+
+import cutlass
+import cutlass.cute as cute
+import cutlass.pipeline as pipeline
+from cutlass import Float32, Int32, Int64, const_expr
+from cutlass.cute.nvgpu import cpasync
+
+import torch
+from torch import Tensor
+
+from . import utils
+from . import copy_utils
+from . import layout_utils
+from .compile_utils import make_fake_tensor as fake_tensor
+from .reduce import row_reduce
+from .reduction_base import ReductionBase
+from .cache import jit_cache
+from .cute_dsl_utils import torch2cute_dtype_map
+from .autotuner import autotune, AutotuneConfig
+from .rmsnorm_config import (
+    RmsNormBwdConfig,
+    RmsNormFwdConfig,
+    get_all_bwd_configs,
+    get_all_fwd_configs,
+    get_sm_count,
+    prune_invalid_rmsnorm_bwd_configs,
+    prune_invalid_rmsnorm_fwd_configs,
+)
+from cutlass.base_dsl.arch import Arch
+
+
+def _bucket_T_hint(T_hint: int) -> int:
+    """Round ``T_hint`` up to the next power of 2 to bucket the JIT cache key.
+
+    Each base-2 order of magnitude becomes a single bucket so adjacent T
+    values share a compiled binary instead of triggering a recompile per row
+    count. Buckets align with powers of 2 (..., 512, 1024, 2048, ...), which
+    keeps the analytical heuristic thresholds (e.g. ``T_hint <= 1024``) exact
+    at their power-of-2 boundaries. ``T_hint <= 0`` (the "unknown shape"
+    SymInt sentinel) is preserved.
+    """
+    if T_hint <= 0:
+        return 0
+    return 1 << (T_hint - 1).bit_length()
+
+
+def _ensure_contiguous(t):
+    """Ensure last-dim stride is 1. Under torch.compile use unconditional .contiguous()
+    (dynamo can't inspect strides on fake tensors); otherwise check first to avoid copies.
+    """
+    if torch.compiler.is_compiling():
+        return t.contiguous()
+    return t if t.stride(-1) == 1 else t.contiguous()
+
+
+class RMSNorm(ReductionBase):
+    def __init__(
+        self,
+        dtype: Type[cutlass.Numeric],
+        N: int,
+        is_layernorm: bool = False,
+        config: Optional["RmsNormFwdConfig"] = None,
+    ):
+        super().__init__(dtype, N, stage=2 if is_layernorm else 1)
+        self.is_layernorm = is_layernorm
+        if config is None:
+            config = RmsNormFwdConfig.from_analytical_heuristic(
+                N, dtype.width, is_layernorm=is_layernorm
+            )
+        self.config = config
+        self.reload_from = config.reload_from
+        self.delay_w_load = config.delay_w_load
+        self._num_threads_val = config.num_threads
+        self._threads_per_row_val = config.threads_per_row
+        self._cluster_n_val = config.cluster_n
+
+    def _num_threads(self):
+        return self._num_threads_val
+
+    def _threads_per_row(self):
+        return self._threads_per_row_val
+
+    def _set_cluster_n(self):
+        arch = cutlass.base_dsl.BaseDSL._get_dsl().get_arch_enum()
+        # SM8x (Ampere/Ada) lacks cluster support
+        if arch < Arch.sm_90:
+            self.cluster_n = 1
+            return
+        # SM12x supports cluster up to 8
+        max_cluster = 8 if arch.major == 12 else 16
+        self.cluster_n = min(self._cluster_n_val, max_cluster)
+
+    @cute.jit
+    def __call__(
+        self,
+        mX: cute.Tensor,  # (b, N) or (b, H, N)
+        mW: Optional[cute.Tensor],  # (N,) or (H, N)
+        mB: Optional[cute.Tensor],  # (N,) or (H, N)
+        mRes: Optional[cute.Tensor],  # (b, N) or (b, H, N)
+        mO: cute.Tensor,  # (b, N) or (b, H, N)
+        mResO: Optional[cute.Tensor],
+        mRstd: Optional[cute.Tensor],
+        mMean: Optional[cute.Tensor],
+        eps: Float32,
+        stream: cuda.CUstream,
+    ):
+        assert mX.element_type == self.dtype
+        self._set_cluster_n()
+        largest_dtype_width = const_expr(
+            max(*(t.element_type.width for t in [mX, mRes, mW, mB, mO, mResO] if t is not None))
+        )
+        vecsize = math.gcd(self.N, 128 // largest_dtype_width)
+        self._cap_cluster_n(vecsize)
+        tiled_copy, tiler_mn, threads_per_row = self._get_tiled_copy(vecsize=vecsize)
+        num_threads = tiled_copy.size
+        mW, mB = [
+            layout_utils.expand(mT, dim=0, size=tiler_mn[0]) if const_expr(mT is not None) else None
+            for mT in (mW, mB)
+        ]
+        mRstd, mMean = [
+            layout_utils.expand(mT, dim=cute.rank(mT), size=self.N)
+            if const_expr(mT is not None)
+            else None
+            for mT in (mRstd, mMean)
+        ]
+        num_heads = mX.shape[1] if const_expr(cute.rank(mX) == 3) else 1
+        self.kernel(
+            mX, mW, mB, mRes, mO, mResO, mRstd, mMean, eps, tiler_mn, tiled_copy, threads_per_row
+        ).launch(
+            grid=[cute.ceil_div(mX.shape[0], tiler_mn[0]), self.cluster_n, num_heads],
+            block=[num_threads, 1, 1],
+            cluster=[1, self.cluster_n, 1] if const_expr(self.cluster_n > 1) else None,
+            stream=stream,
+        )
+
+    @cute.kernel
+    def kernel(
+        self,
+        mX: cute.Tensor,
+        mW: Optional[cute.Tensor],
+        mB: Optional[cute.Tensor],
+        mRes: Optional[cute.Tensor],
+        mO: cute.Tensor,
+        mResO: Optional[cute.Tensor],
+        mRstd: Optional[cute.Tensor],
+        mMean: Optional[cute.Tensor],
+        eps: Float32,
+        tiler_mn: cute.Shape,
+        tiled_copy: cute.TiledCopy,
+        threads_per_row: cutlass.Constexpr[int],
+    ):
+        tidx, _, _ = cute.arch.thread_idx()
+        bidx, _, bidz = cute.arch.block_idx()
+        cluster_y = const_expr(0) if const_expr(self.cluster_n == 1) else cute.arch.block_idx()[1]
+        tv_layout = tiled_copy.layout_tv_tiled
+
+        smem = cutlass.utils.SmemAllocator()
+        sX = smem.allocate_tensor(
+            mX.element_type, cute.make_ordered_layout(tiler_mn, order=(1, 0)), byte_alignment=16
+        )
+        if const_expr(mRes is not None):
+            sRes = smem.allocate_tensor(
+                mRes.element_type,
+                cute.make_ordered_layout(tiler_mn, order=(1, 0)),
+                byte_alignment=16,
+            )
+        reduction_buffer, mbar_ptr = self._allocate_reduction_buffer_and_mbar(smem, tv_layout)
+
+        # Slice per head
+        if const_expr(cute.rank(mX) == 3):
+            mX, mW, mB, mRes, mO, mResO, mRstd, mMean = [
+                mT[None, bidz, None] if const_expr(mT is not None) else None
+                for mT in (mX, mW, mB, mRes, mO, mResO, mRstd, mMean)
+            ]
+
+        shape = (cute.size(mX, mode=[0]), cute.size(mX, mode=[1]))
+        idX = cute.make_identity_tensor(shape)
+        # Slice for CTAs
+        gX, gRes, gO, gResO, gRstd, gMean, cX = [
+            cute.local_tile(mT, tiler_mn, (bidx, cluster_y)) if mT is not None else None
+            for mT in (mX, mRes, mO, mResO, mRstd, mMean, idX)
+        ]
+        gW, gB = [
+            cute.local_tile(mT, tiler_mn, (0, cluster_y)) if const_expr(mT is not None) else None
+            for mT in (mW, mB)
+        ]
+
+        thr_copy_X = tiled_copy.get_slice(tidx)
+
+        tXgW = thr_copy_X.partition_S(gW) if const_expr(mW is not None) else None
+        tXgB = thr_copy_X.partition_S(gB) if const_expr(mB is not None) else None
+        tXgX = thr_copy_X.partition_S(gX)
+        tXsX = thr_copy_X.partition_D(sX)
+        if const_expr(mRes is not None):
+            tXgRes = thr_copy_X.partition_S(gRes)
+            tXsRes = thr_copy_X.partition_D(sRes)
+        tXgO = thr_copy_X.partition_D(gO)
+        if const_expr(mResO is not None):
+            tXgResO = thr_copy_X.partition_D(gResO)
+        tXrRstd = thr_copy_X.partition_D(gRstd) if const_expr(mRstd is not None) else None
+        tXrMean = thr_copy_X.partition_D(gMean) if const_expr(mMean is not None) else None
+        tXcX = thr_copy_X.partition_S(cX)[(0, None), None, None]
+
+        # allocate fragments for gmem->rmem
+        tXrW = cute.make_rmem_tensor_like(tXgW) if const_expr(mW is not None) else None
+        tXrB = cute.make_rmem_tensor_like(tXgB) if const_expr(mB is not None) else None
+        tXrX, tXrO = [cute.make_rmem_tensor_like(t) for t in (tXgX, tXgO)]
+        if const_expr(mRes is not None):
+            tXrRes = cute.make_rmem_tensor_like(tXgRes)
+
+        num_warps = cute.size(tiled_copy) // cute.arch.WARP_SIZE
+        self._initialize_cluster(tidx, mbar_ptr, num_warps)
+
+        is_even_N = const_expr(shape[1] == tiler_mn[1] * self.cluster_n)
+        tXpX = (
+            copy_utils.predicate_k(thr_copy_X.partition_S(cX), limit=shape[1])
+            if not is_even_N
+            else None
+        )
+        # Each copy will use the same predicate
+        copy = partial(copy_utils.copy, pred=tXpX)
+
+        row = tXcX[0][0]
+        if row < shape[0]:
+            copy(tXgX, tXsX, is_async=True)
+            if const_expr(mRes is not None):
+                copy(tXgRes, tXsRes, is_async=True)
+        cute.arch.cp_async_commit_group()
+
+        if const_expr(not self.delay_w_load):
+            if const_expr(mW is not None):
+                copy(tXgW, tXrW)
+            if const_expr(mB is not None):
+                copy(tXgB, tXrB)
+
+        cute.arch.cp_async_wait_group(0)
+        cute.autovec_copy(tXsX, tXrX)
+        x = tXrX.load().to(cute.Float32)
+        if const_expr(mRes is not None):
+            cute.autovec_copy(tXsRes, tXrRes)
+            x += tXrRes.load().to(cute.Float32)
+        if const_expr(mResO is not None):
+            tXrResO = cute.make_rmem_tensor_like(tXgResO)
+            tXrResO.store(x.to(tXrResO.element_type))
+            if row < shape[0]:
+                copy(tXrResO, tXgResO)
+
+        mean, rstd = None, None
+        if const_expr(self.is_layernorm):
+            # LayerNorm: compute mean first, then variance
+            sum_x = row_reduce(
+                x,
+                cute.ReductionOp.ADD,
+                threads_per_row,
+                reduction_buffer[None, None, 0],
+                mbar_ptr + 0 if const_expr(self.cluster_n > 1) else None,
+                init_val=0.0,
+                hook_fn=cute.arch.cluster_wait if const_expr(self.cluster_n > 1) else None,
+            )
+            mean = sum_x / shape[1]
+            if const_expr(mMean is not None):
+                # Only the thread corresponding to column 0 writes out the mean to gmem
+                if (
+                    tXcX[0][1] == 0
+                    and row < shape[0]
+                    and (self.cluster_n == 1 or cute.arch.block_idx_in_cluster() == 0)
+                ):
+                    tXrMean[0] = mean
+            if const_expr(self.reload_from == "smem"):
+                cute.autovec_copy(tXsX, tXrX)
+                x = tXrX.load().to(cute.Float32)
+                if const_expr(mRes is not None):
+                    cute.autovec_copy(tXsRes, tXrRes)
+                    x += tXrRes.load().to(cute.Float32)
+            elif const_expr(self.reload_from == "gmem"):
+                copy(tXgX, tXrX)
+                x = tXrX.load().to(cute.Float32)
+                if const_expr(mRes is not None):
+                    copy(tXgRes, tXrRes)
+                    x += tXrRes.load().to(cute.Float32)
+            x_centered = x - mean
+            if const_expr(not is_even_N):
+                # OOB lanes are zero-filled for the mean pass, but they must contribute zero
+                # to the variance pass (not mean^2 from (0 - mean)^2).
+                tXrX_centered = cute.make_rmem_tensor_like(tXrX, Float32)
+                tXrX_centered.store(x_centered)
+                utils.fill_oob(tXrX_centered, tXpX, fill_value=Float32.zero)
+                x_centered = tXrX_centered.load()
+            sum_sq_x_sub_mean = row_reduce(
+                x_centered * x_centered,
+                cute.ReductionOp.ADD,
+                threads_per_row,
+                reduction_buffer[None, None, 1],
+                mbar_ptr + 1 if const_expr(self.cluster_n > 1) else None,
+                init_val=0.0,
+            )
+            rstd = cute.math.rsqrt(sum_sq_x_sub_mean / shape[1] + eps, fastmath=True)
+        else:
+            # RMSNorm: compute sum of squares directly
+            mean = const_expr(0.0)
+            sum_sq_x = row_reduce(
+                x * x,
+                cute.ReductionOp.ADD,
+                threads_per_row,
+                reduction_buffer[None, None, 0],
+                mbar_ptr,
+                init_val=0.0,
+                hook_fn=cute.arch.cluster_wait if const_expr(self.cluster_n > 1) else None,
+            )
+            rstd = cute.math.rsqrt(sum_sq_x / shape[1] + eps, fastmath=True)
+        if const_expr(mRstd is not None):
+            # Only the thread corresponding to column 0 writes out the rstd to gmem
+            if (
+                tXcX[0][1] == 0
+                and row < shape[0]
+                and (self.cluster_n == 1 or cute.arch.block_idx_in_cluster() == 0)
+            ):
+                tXrRstd[0] = rstd
+        if const_expr(self.delay_w_load):
+            if const_expr(mW is not None):
+                copy(tXgW, tXrW)
+            if const_expr(mB is not None):
+                copy(tXgB, tXrB)
+        if const_expr(self.reload_from == "smem" or self.reload_from == "gmem"):
+            if const_expr(self.reload_from == "smem"):
+                cute.autovec_copy(tXsX, tXrX)
+                if const_expr(mRes is not None):
+                    cute.autovec_copy(tXsRes, tXrRes)
+            else:
+                copy(tXgX, tXrX)
+                if const_expr(mRes is not None):
+                    copy(tXgRes, tXrRes)
+            x = tXrX.load().to(cute.Float32)
+            if const_expr(mRes is not None):
+                x += tXrRes.load().to(cute.Float32)
+        x_hat = (x - mean) * rstd if const_expr(self.is_layernorm) else x * rstd
+        y = x_hat
+        if const_expr(mW is not None):
+            y *= tXrW.load().to(cute.Float32)
+        if const_expr(mB is not None):
+            y += tXrB.load().to(cute.Float32)
+        tXrO.store(y.to(tXrO.element_type))
+        if row < shape[0]:
+            copy(tXrO, tXgO)
+
+
+def _rmsnorm_fwd(
+    x: Tensor,
+    weight: Optional[Tensor],
+    out: Tensor,
+    bias: Optional[Tensor] = None,
+    rstd: Optional[Tensor] = None,
+    mean: Optional[Tensor] = None,
+    residual: Optional[Tensor] = None,
+    residual_out: Optional[Tensor] = None,
+    eps: float = 1e-6,
+    is_layernorm: bool = False,
+) -> None:
+    """RMSNorm/LayerNorm forward pass.
+    Args:
+        x: Input tensor of shape (M, N)
+        weight: Optional weight tensor of shape (N,) or (H, N) for per-head weight
+        eps: Small value for numerical stability
+        is_layernorm: If True, compute LayerNorm instead of RMSNorm
+    Returns:
+        Normalized output tensor of same shape as x
+    """
+    # TVM FFI validates tensor devices at runtime.
+    supported_types = {torch.float16, torch.bfloat16, torch.float32}
+    assert x.dtype in supported_types, "Unsupported dtype"
+    if weight is not None:
+        assert weight.dtype in supported_types, "Weight must be float32, float16 or bfloat16"
+    if residual is not None:
+        assert residual.dtype in supported_types, "Residual must be float16, bfloat16, or float32"
+    if x.numel() == 0:
+        return
+
+    N = x.size(-1)
+    per_head = (weight is not None and weight.dim() == 2) or (bias is not None and bias.dim() == 2)
+    dtype, out_dtype, weight_dtype, bias_dtype, res_dtype, res_out_dtype = [
+        torch2cute_dtype_map[t.dtype] if t is not None else None
+        for t in [x, out, weight, bias, residual, residual_out]
+    ]
+    _compile_rmsnorm_fwd(
+        dtype,
+        out_dtype,
+        res_dtype,
+        weight_dtype,
+        bias_dtype,
+        res_out_dtype,
+        N,
+        rstd is not None,
+        mean is not None,
+        is_layernorm,
+        per_head,
+    )(x, weight, bias, residual, out, residual_out, rstd, mean, eps)
+
+
+@jit_cache
+def _compile_rmsnorm_fwd(
+    dtype,
+    out_dtype,
+    res_dtype,
+    weight_dtype,
+    bias_dtype,
+    res_out_dtype,
+    N,
+    has_rstd,
+    has_mean,
+    is_layernorm,
+    per_head,
+    config: Optional[RmsNormFwdConfig] = None,
+):
+    batch_sym = cute.sym_int()
+    head_sym = cute.sym_int() if per_head else None
+    batch_shape = (batch_sym, head_sym) if per_head else (batch_sym,)
+    all_dtypes = [dtype, out_dtype, res_dtype, weight_dtype, bias_dtype, res_out_dtype]
+    div = math.gcd(N, *(128 // dt.width for dt in all_dtypes if dt is not None))
+    x_cute, out_cute, res_cute, res_out_cute = [
+        fake_tensor(dt, (*batch_shape, N), div)
+        for dt in [dtype, out_dtype, res_dtype, res_out_dtype]
+    ]
+    weight_shape = (head_sym, N) if per_head else (N,)
+    weight_cute, bias_cute = [
+        fake_tensor(dt, weight_shape, div) for dt in [weight_dtype, bias_dtype]
+    ]
+    rstd_cute = fake_tensor(Float32, batch_shape) if has_rstd else None
+    mean_cute = fake_tensor(Float32, batch_shape) if has_mean else None
+    return cute.compile(
+        RMSNorm(dtype, N, is_layernorm=is_layernorm, config=config),
+        x_cute,
+        weight_cute,
+        bias_cute,
+        res_cute,
+        out_cute,
+        res_out_cute,
+        rstd_cute,
+        mean_cute,
+        Float32(0),  # eps, just for compilation
+        cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True),
+        options="--enable-tvm-ffi",
+    )
+
+
+def rmsnorm_fwd(
+    x: Tensor,
+    weight: Optional[Tensor] = None,
+    bias: Optional[Tensor] = None,
+    residual: Optional[Tensor] = None,
+    out_dtype: Optional[torch.dtype] = None,
+    residual_dtype: Optional[torch.dtype] = None,
+    eps: float = 1e-6,
+    store_rstd: bool = False,
+) -> Tuple[Tensor, Tensor, Optional[Tensor]]:
+    # Need to wrap to handle the case where residual_out is a alias of x, which makes torch.library
+    # and torch.compile unhappy. Also allocate memory for out and residual_out if they are None
+    # so that _layer_norm_fwd_impl doesn't have to return them.
+    out_dtype = x.dtype if out_dtype is None else out_dtype
+    out = torch.empty_like(x, dtype=out_dtype)
+    rstd = torch.empty(*x.shape[:-1], device=x.device, dtype=torch.float32) if store_rstd else None
+    if residual is not None and residual_dtype is None:
+        residual_dtype = residual.dtype
+    if residual is not None or (residual_dtype is not None and residual_dtype != x.dtype):
+        residual_out = torch.empty_like(
+            x, dtype=residual_dtype if residual_dtype is not None else x.dtype
+        )
+    else:
+        residual_out = None
+    _rmsnorm_fwd(x, weight, out, bias, rstd, None, residual, residual_out, eps, False)
+    # residual_out is None if residual is None and residual_dtype == input_dtype and dropout_p == 0.0
+    if residual_out is None:
+        residual_out = x
+    return out, residual_out, rstd
+
+
+@autotune(
+    configs=[AutotuneConfig(config=c) for c in get_all_fwd_configs()],
+    key=["is_layernorm", "per_head"],
+    prune_configs_by={"early_config_prune": prune_invalid_rmsnorm_fwd_configs},
+)
+def rmsnorm_fwd_tuned(
+    x: Tensor,
+    weight: Optional[Tensor],
+    out: Tensor,
+    bias: Optional[Tensor] = None,
+    rstd: Optional[Tensor] = None,
+    mean: Optional[Tensor] = None,
+    residual: Optional[Tensor] = None,
+    residual_out: Optional[Tensor] = None,
+    eps: float = 1e-6,
+    is_layernorm: bool = False,
+    per_head: bool = False,
+    config: Optional[RmsNormFwdConfig] = None,
+) -> None:
+    """Autotuned RMSNorm/LayerNorm forward dispatch.
+
+    The ``@autotune`` decorator injects ``config`` from the exhaustive search
+    space at first call for a given (shape, dtype, ``is_layernorm``, ``per_head``)
+    and caches the winner for subsequent calls. The un-tuned counterpart is
+    :func:`rmsnorm_fwd`, which uses the analytical heuristic.
+    """
+    if config is None:
+        raise RuntimeError(
+            "rmsnorm_fwd_tuned requires a config (provided automatically by "
+            "the @autotune decorator). Use rmsnorm_fwd for the un-tuned path."
+        )
+    N = x.size(-1)
+    dtype, out_dtype, weight_dtype, bias_dtype, res_dtype, res_out_dtype = [
+        torch2cute_dtype_map[t.dtype] if t is not None else None
+        for t in [x, out, weight, bias, residual, residual_out]
+    ]
+    _compile_rmsnorm_fwd(
+        dtype,
+        out_dtype,
+        res_dtype,
+        weight_dtype,
+        bias_dtype,
+        res_out_dtype,
+        N,
+        rstd is not None,
+        mean is not None,
+        is_layernorm,
+        per_head,
+        config=config,
+    )(x, weight, bias, residual, out, residual_out, rstd, mean, eps)
+
+
+def rmsnorm_ref(x, w=None, bias=None, residual=None, eps=1e-6):
+    x_f32 = x.float()
+    if residual is not None:
+        residual_f32 = residual.float()
+        x_f32 = x_f32 + residual_f32
+    x_norm = x_f32 / (torch.sqrt(torch.mean(x_f32.square(), dim=-1, keepdim=True) + eps))
+    out = x_norm * w if w is not None else x_norm
+    if bias is not None:
+        out = out + bias.float()
+    if residual is None:
+        return out.to(x.dtype)
+    else:
+        return out.to(x.dtype), x_f32.to(residual.dtype)
+
+
+def rmsnorm_bwd_ref(x, w, dout, rstd, eps=1e-6):
+    """Reference implementation for RMSNorm backward pass."""
+    x_f32 = x.float()
+    x_hat = x_f32 * rstd.unsqueeze(1)
+    if w is not None:
+        wdy = dout * w
+    else:
+        wdy = dout
+    c1 = (x_hat * wdy).mean(dim=-1, keepdim=True)
+    dx = (wdy - x_hat * c1) * rstd.unsqueeze(1)
+
+    # dL/dW
+    if w is not None:
+        dw = (dout * x_hat).sum(dim=0)
+        return dx.to(x.dtype), dw.to(w.dtype)
+    else:
+        return dx.to(x.dtype), None
+
+
+class RMSNormBackward(ReductionBase):
+    def __init__(
+        self,
+        dtype: cutlass.Numeric,
+        N: int,
+        dout_dtype: Optional[Type[cutlass.Numeric]] = None,
+        T_hint: int = 0,
+        per_head: bool = False,
+        config: Optional["RmsNormBwdConfig"] = None,
+    ):
+        # 2 stages for double buffering when computing mean of x_hat * wdy
+        super().__init__(dtype, N, stage=2, reduction_dtype=Float32)
+        dout_width = dout_dtype.width if dout_dtype is not None else dtype.width
+        if config is None:
+            config = RmsNormBwdConfig.from_analytical_heuristic(
+                N, dtype.width, dout_width, T_hint=T_hint
+            )
+        self.config = config
+        self.reload_wdy = config.reload_wdy
+        self.reload_x = config.reload_x
+        self.per_head = per_head
+        self._num_threads_val = config.num_threads
+        self._threads_per_row_val = config.threads_per_row
+        self._cluster_n_val = config.cluster_n
+        tile_n = N // max(1, config.cluster_n)
+        row_bytes_x = tile_n * dtype.width // 8
+        row_bytes_do = tile_n * dout_width // 8
+        self.USE_TMA = (
+            config.use_tma and not per_head and row_bytes_x % 16 == 0 and row_bytes_do % 16 == 0
+        )
+        self._can_use_tma = self.USE_TMA
+        if self.N > 128 * 1024 and self.dtype.width >= 32:
+            # Not enough smem
+            raise ValueError("RMSNormBackward does not support N > 128k with dtype >= 32 bits")
+
+    def _num_threads(self):
+        return self._num_threads_val
+
+    def _threads_per_row(self):
+        return self._threads_per_row_val
+
+    def _set_cluster_n(self):
+        arch = cutlass.base_dsl.BaseDSL._get_dsl().get_arch_enum()
+        # SM8x (Ampere/Ada) lacks cluster support
+        if arch < Arch.sm_90:
+            self.cluster_n = 1
+            return
+        max_cluster = 8 if arch.major == 12 else 16
+        self.cluster_n = min(self._cluster_n_val, max_cluster)
+
+    @cute.jit
+    def __call__(
+        self,
+        mX: cute.Tensor,
+        mW: Optional[cute.Tensor],
+        mdO: cute.Tensor,
+        mdResO: Optional[cute.Tensor],
+        mRstd: cute.Tensor,
+        mdX: cute.Tensor,
+        mdW: Optional[cute.Tensor],
+        mdRes: Optional[cute.Tensor],
+        mdB: Optional[cute.Tensor],
+        sm_count: Int32,
+        stream: cuda.CUstream,
+    ):
+        assert mX.element_type == self.dtype
+        self._set_cluster_n()
+        largest_dtype_width = const_expr(
+            max(*(t.element_type.width for t in [mX, mW, mdO, mdResO, mdX, mdRes] if t is not None))
+        )
+        vecsize = math.gcd(self.N, 128 // largest_dtype_width)
+        self._cap_cluster_n(vecsize)
+        tiled_copy, tiler_mn, threads_per_row = self._get_tiled_copy(vecsize=vecsize)
+        num_threads = tiled_copy.size
+        mW = (
+            layout_utils.expand(mW, dim=0, size=tiler_mn[0]) if const_expr(mW is not None) else None
+        )
+        use_tma = const_expr(self.USE_TMA)
+        if const_expr(use_tma):
+            tma_smem_layout = cute.make_ordered_layout(tiler_mn, order=(1, 0))
+            tma_op = cpasync.CopyBulkTensorTileG2SOp()
+            tma_atom_X, mX_tma = cpasync.make_tiled_tma_atom(tma_op, mX, tma_smem_layout, tiler_mn)
+            tma_atom_dO, mdO_tma = cpasync.make_tiled_tma_atom(
+                tma_op, mdO, tma_smem_layout, tiler_mn
+            )
+        else:
+            tma_atom_X, mX_tma, tma_atom_dO, mdO_tma = None, None, None, None
+        num_blocks = sm_count
+        num_heads = mX.shape[1] if const_expr(self.per_head) else 1
+        self.kernel(
+            mX,
+            mW,
+            mdO,
+            mdResO,
+            mRstd,
+            mdX,
+            mdW,
+            mdB,
+            mdRes,
+            tma_atom_X,
+            mX_tma,
+            tma_atom_dO,
+            mdO_tma,
+            tiler_mn,
+            tiled_copy,
+            threads_per_row,
+        ).launch(
+            grid=[num_blocks, self.cluster_n, num_heads],
+            block=[num_threads, 1, 1],
+            cluster=[1, self.cluster_n, 1] if self.cluster_n > 1 else None,
+            stream=stream,
+        )
+
+    @cute.kernel
+    def kernel(
+        self,
+        mX: cute.Tensor,
+        mW: Optional[cute.Tensor],
+        mdO: cute.Tensor,
+        mdResO: Optional[cute.Tensor],
+        mRstd: cute.Tensor,
+        mdX: cute.Tensor,
+        mdW: Optional[cute.Tensor],
+        mdB: Optional[cute.Tensor],
+        mdRes: Optional[cute.Tensor],
+        tma_atom_X: Optional[cute.CopyAtom],
+        mX_tma: Optional[cute.Tensor],
+        tma_atom_dO: Optional[cute.CopyAtom],
+        mdO_tma: Optional[cute.Tensor],
+        tiler_mn: cute.Shape,
+        tiled_copy: cute.TiledCopy,
+        threads_per_row: cutlass.Constexpr[int],
+    ):
+        tidx, _, _ = cute.arch.thread_idx()
+        warp_id = cute.arch.make_warp_uniform(cute.arch.warp_idx())
+        if const_expr(self.per_head):
+            bidx_start, _, bidz = cute.arch.block_idx()
+        else:
+            bidx_start, _, _ = cute.arch.block_idx()
+        gdim, _, _ = cute.arch.grid_dim()
+        cluster_y = const_expr(0) if const_expr(self.cluster_n == 1) else cute.arch.block_idx()[1]
+        tv_layout = tiled_copy.layout_tv_tiled
+
+        # Slice per head
+        if const_expr(self.per_head):
+            mX, mW, mdO, mdResO, mdX, mdW, mdB, mdRes = [
+                mT[None, bidz, None] if const_expr(mT is not None) else None
+                for mT in (mX, mW, mdO, mdResO, mdX, mdW, mdB, mdRes)
+            ]
+            mRstd = mRstd[None, bidz]
+
+        shape = mX.shape
+        M = shape[0]
+        is_even_N = const_expr(shape[1] == tiler_mn[1] * self.cluster_n)
+
+        idX = cute.make_identity_tensor(shape)
+
+        smem = cutlass.utils.SmemAllocator()
+        USE_TMA = const_expr(self.USE_TMA)
+        n_smem_stages = const_expr(self.config.smem_stages)
+        smem_layout = cute.make_ordered_layout(
+            (tiler_mn[0], tiler_mn[1], n_smem_stages), order=(1, 0, 2)
+        )
+        smem_align = const_expr(128 if USE_TMA else 16)
+        sX = smem.allocate_tensor(mX.element_type, smem_layout, byte_alignment=smem_align)
+        sdO = smem.allocate_tensor(mdO.element_type, smem_layout, byte_alignment=smem_align)
+        reduction_buffer, mbar_ptr = self._allocate_reduction_buffer_and_mbar(
+            smem, tv_layout, is_persistent=True
+        )
+        if const_expr(mbar_ptr is not None):
+            mbar_full_ptr, mbar_empty_ptr = mbar_ptr, mbar_ptr + 2
+        else:
+            mbar_full_ptr, mbar_empty_ptr = None, None
+
+        thr_copy_X = tiled_copy.get_slice(tidx)
+
+        gX, gdO, gdResO, gdX, gdRes, cX = [
+            cute.local_tile(mT, tiler_mn, (None, cluster_y)) if mT is not None else None
+            for mT in (mX, mdO, mdResO, mdX, mdRes, idX)
+        ]
+        gW = cute.local_tile(mW, tiler_mn, (0, cluster_y)) if mW is not None else None
+        gdW, gdB = [
+            cute.local_tile(mT, (1, tiler_mn[1]), (bidx_start, cluster_y))
+            if const_expr(mT is not None)
+            else None
+            for mT in (mdW, mdB)
+        ]
+
+        tXgX = thr_copy_X.partition_S(gX)
+        tXsX = thr_copy_X.partition_D(sX)
+        tXgdO = thr_copy_X.partition_S(gdO)
+        tXsdO = thr_copy_X.partition_D(sdO)
+        tXgdX = thr_copy_X.partition_D(gdX)
+        if const_expr(mdResO is not None):
+            tXgdResO = thr_copy_X.partition_S(gdResO)
+        if const_expr(mdRes is not None):
+            tXgdRes = thr_copy_X.partition_D(gdRes)
+        tXcX = thr_copy_X.partition_S(cX)[(0, None), None, None, None]
+
+        tXrX, tXrdO, tXrdX = [
+            cute.make_rmem_tensor_like(thr[None, None, None, 0]) for thr in (tXgX, tXgdO, tXgdX)
+        ]
+        tXrdResO = None
+        if const_expr(mdResO is not None):
+            tXrdResO = cute.make_rmem_tensor_like(tXgdResO[None, None, None, 0])
+        tXrdRes = None
+        if const_expr(mdRes is not None):
+            tXrdRes = cute.make_rmem_tensor_like(tXgdRes[None, None, None, 0])
+
+        # This doesn't change across iterations
+        tXpX = (
+            None
+            if is_even_N
+            else copy_utils.predicate_k(thr_copy_X.partition_S(cX[None, None, 0]), limit=shape[1])
+        )
+        # Each copy will use the same number of elements as X
+        copy = partial(copy_utils.copy, pred=tXpX)
+
+        tXgdW, tXrdW = None, None
+        tXgdB, tXrdB = None, None
+        if const_expr(mdW is not None):
+            tXgdW = thr_copy_X.partition_S(gdW)
+            # Always compute partial weight gradients in fp32
+            tXrdW = cute.make_rmem_tensor_like(tXgdW, Float32)
+        if const_expr(mdB is not None):
+            tXgdB = thr_copy_X.partition_S(gdB)
+            # Always compute partial bias gradients in fp32
+            tXrdB = cute.make_rmem_tensor_like(tXgdB, Float32)
+
+        num_warps = cute.size(tiled_copy) // cute.arch.WARP_SIZE
+        NUM_PIPE_STAGES = const_expr(self.config.smem_stages)
+
+        if const_expr(USE_TMA):
+            tma_mbar_ptr = smem.allocate_array(Int64, num_elems=NUM_PIPE_STAGES * 2)
+
+        self._initialize_cluster(tidx, mbar_ptr, num_warps, is_persistent=True)
+
+        tXrW = None
+        if const_expr(mW is not None):
+            tXgW = thr_copy_X.partition_S(gW)
+            tXrW = cute.make_rmem_tensor_like(tXgW)
+            # Need this, otherwise rW can have arbitrary values that changes the reduction
+            if const_expr(not is_even_N):
+                tXrW.fill(0.0)
+            copy(tXgW, tXrW)
+            # No-op fp32 round-trip; pins tXrW into stable registers across the loop.
+            tXrW.store((tXrW.load().to(Float32) + Float32(0.0)).to(tXrW.element_type))
+
+        if const_expr(self.cluster_n > 1):
+            cute.arch.cluster_wait()
+
+        producer_state = pipeline.make_pipeline_state(
+            pipeline.PipelineUserType.Producer, NUM_PIPE_STAGES
+        )
+        consumer_state = pipeline.make_pipeline_state(
+            pipeline.PipelineUserType.Consumer, NUM_PIPE_STAGES
+        )
+        if const_expr(USE_TMA):
+            num_threads_total = cute.size(tiled_copy)
+            producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, 1)
+            consumer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, num_threads_total)
+            tma_bytes_x = const_expr(cute.size(tiler_mn) * mX.element_type.width // 8)
+            tma_bytes_do = const_expr(cute.size(tiler_mn) * mdO.element_type.width // 8)
+            tma_pipeline = pipeline.PipelineTmaAsync.create(
+                barrier_storage=tma_mbar_ptr,
+                num_stages=NUM_PIPE_STAGES,
+                producer_group=producer_group,
+                consumer_group=consumer_group,
+                tx_count=tma_bytes_x + tma_bytes_do,
+                cta_layout_vmnk=cute.make_layout((1, 1, 1, 1)),
+            )
+            gX_tma = cute.local_tile(mX_tma, tiler_mn, (None, cluster_y))
+            gdO_tma = cute.local_tile(mdO_tma, tiler_mn, (None, cluster_y))
+            tXsX_tma, tXgX_tma = cpasync.tma_partition(
+                tma_atom_X,
+                0,
+                cute.make_layout(1),
+                cute.group_modes(sX, 0, 2),
+                cute.group_modes(gX_tma, 0, 2),
+            )
+            tXsdO_tma, tXgdO_tma = cpasync.tma_partition(
+                tma_atom_dO,
+                0,
+                cute.make_layout(1),
+                cute.group_modes(sdO, 0, 2),
+                cute.group_modes(gdO_tma, 0, 2),
+            )
+
+        if const_expr(mdW is not None):
+            tXrdW.fill(0.0)
+        if const_expr(mdB is not None):
+            tXrdB.fill(0.0)
+        stage = Int32(0)
+        producer_phase = Int32(1)
+        consumer_phase = Int32(0)
+        next_wave_work_id = (NUM_PIPE_STAGES - 1) * gdim
+        next_wave_row_id = next_wave_work_id * tiler_mn[0]
+
+        M_ceil = cute.ceil_div(M, tiler_mn[0])
+        if const_expr(USE_TMA):
+            for prefetch_iter in cutlass.range_constexpr(const_expr(NUM_PIPE_STAGES - 1)):
+                init_bidx = bidx_start + prefetch_iter * gdim
+                if warp_id == 0:
+                    if init_bidx < M_ceil:
+                        tma_pipeline.producer_acquire(producer_state)
+                        pipe_bar = tma_pipeline.producer_get_barrier(producer_state)
+                        cute.copy(
+                            tma_atom_X,
+                            tXgX_tma[None, init_bidx],
+                            tXsX_tma[None, producer_state.index],
+                            tma_bar_ptr=pipe_bar,
+                        )
+                        cute.copy(
+                            tma_atom_dO,
+                            tXgdO_tma[None, init_bidx],
+                            tXsdO_tma[None, producer_state.index],
+                            tma_bar_ptr=pipe_bar,
+                        )
+                        tma_pipeline.producer_commit(producer_state)
+                        producer_state.advance()
+        else:
+            # Pre-issue NUM_PIPE_STAGES-1 prefetches into smem stages 0..N-2.
+            # The bidx loop then maintains exactly NUM_PIPE_STAGES groups in flight
+            # via cp_async_wait_group(NUM_PIPE_STAGES - 1).
+            for prefetch_iter in cutlass.range_constexpr(const_expr(NUM_PIPE_STAGES - 1)):
+                init_bidx = bidx_start + prefetch_iter * gdim
+                init_row = tXcX[None, None, None, init_bidx][0][0]
+                if init_row < M:
+                    copy(
+                        tXgX[None, None, None, init_bidx],
+                        tXsX[None, None, None, producer_state.index],
+                        is_async=True,
+                    )
+                    copy(
+                        tXgdO[None, None, None, init_bidx],
+                        tXsdO[None, None, None, producer_state.index],
+                        is_async=True,
+                    )
+                else:
+                    if const_expr(tiler_mn[0] > 1):
+                        utils.fill_oob(
+                            tXsX[None, None, None, producer_state.index],
+                            None,
+                            fill_value=mX.element_type.zero,
+                        )
+                        utils.fill_oob(
+                            tXsdO[None, None, None, producer_state.index],
+                            None,
+                            fill_value=mdO.element_type.zero,
+                        )
+                cute.arch.cp_async_commit_group()
+                producer_state.advance()
+
+        for bidx in cutlass.range(bidx_start, cute.ceil_div(M, tiler_mn[0]), gdim):
+            row = tXcX[None, None, None, bidx][0][0]
+            if const_expr(USE_TMA):
+                ahead_bidx = bidx + next_wave_work_id
+                if warp_id == 0:
+                    if ahead_bidx < M_ceil:
+                        tma_pipeline.producer_acquire(producer_state)
+                        pipe_bar = tma_pipeline.producer_get_barrier(producer_state)
+                        cute.copy(
+                            tma_atom_X,
+                            tXgX_tma[None, ahead_bidx],
+                            tXsX_tma[None, producer_state.index],
+                            tma_bar_ptr=pipe_bar,
+                        )
+                        cute.copy(
+                            tma_atom_dO,
+                            tXgdO_tma[None, ahead_bidx],
+                            tXsdO_tma[None, producer_state.index],
+                            tma_bar_ptr=pipe_bar,
+                        )
+                        tma_pipeline.producer_commit(producer_state)
+                        producer_state.advance()
+            else:
+                # cp.async: prefetch the (NUM_PIPE_STAGES-1)-ahead batch into the
+                # smem slot we're about to free up.
+                ahead_bidx = bidx + next_wave_work_id
+                if row + next_wave_row_id < M:
+                    copy(
+                        tXgX[None, None, None, ahead_bidx],
+                        tXsX[None, None, None, producer_state.index],
+                        is_async=True,
+                    )
+                    copy(
+                        tXgdO[None, None, None, ahead_bidx],
+                        tXsdO[None, None, None, producer_state.index],
+                        is_async=True,
+                    )
+                else:
+                    if const_expr(tiler_mn[0] > 1):
+                        utils.fill_oob(
+                            tXsX[None, None, None, producer_state.index],
+                            None,
+                            fill_value=mX.element_type.zero,
+                        )
+                        utils.fill_oob(
+                            tXsdO[None, None, None, producer_state.index],
+                            None,
+                            fill_value=mdO.element_type.zero,
+                        )
+                cute.arch.cp_async_commit_group()
+                producer_state.advance()
+            rstd = cutlass.Float.zero
+            if row < M or tiler_mn[0] == 1:
+                rstd = mRstd[row]
+            if const_expr(mdResO is not None):
+                if row < M or tiler_mn[0] == 1:
+                    copy(tXgdResO[None, None, None, bidx], tXrdResO)
+                elif tiler_mn[0] > 1:
+                    tXrdResO.fill(0.0)
+            if const_expr(USE_TMA):
+                tma_pipeline.consumer_wait(consumer_state)
+            else:
+                cute.arch.cp_async_wait_group(const_expr(NUM_PIPE_STAGES - 1))
+            smem_stage = consumer_state.index
+            cute.autovec_copy(tXsX[None, None, None, smem_stage], tXrX)
+            x = tXrX.load().to(cute.Float32)
+            cute.autovec_copy(tXsdO[None, None, None, smem_stage], tXrdO)
+            dout = tXrdO.load().to(cute.Float32)
+            x_hat = x * rstd
+            wdy = dout
+            if const_expr(mW is not None):
+                wdy *= tXrW.load().to(Float32)
+            if const_expr(self.cluster_n > 1):
+                cute.arch.mbarrier_wait(mbar_empty_ptr + stage, producer_phase)
+            mean_xhat_wdy = (
+                row_reduce(
+                    x_hat * wdy,
+                    cute.ReductionOp.ADD,
+                    threads_per_row,
+                    reduction_buffer[None, None, stage],
+                    (mbar_full_ptr + stage if const_expr(self.cluster_n > 1) else None),
+                    phase=consumer_phase,
+                    init_val=0.0,
+                )
+                / shape[1]
+            )
+
+            if const_expr(self.cluster_n > 1):
+                # Need this fence since the STAS from the producer is using the async proxy.
+                cute.arch.fence_view_async_shared()
+                # It's faster to have 1 lane per warp to signal the mbar, rather than all lanes
+                # Requires adjusting the thread_count when initializing the mbar
+                cute.arch.sync_warp()
+                lane_idx = cute.arch.lane_idx()
+                if lane_idx < self.cluster_n:
+                    cute.arch.mbarrier_arrive(
+                        mbar_empty_ptr + stage, peer_cta_rank_in_cluster=lane_idx
+                    )
+
+            if const_expr(self.reload_wdy == "smem"):
+                cute.autovec_copy(tXsdO[None, None, None, smem_stage], tXrdO)
+                dout = tXrdO.load().to(cute.Float32)
+                wdy = dout
+                if const_expr(mW is not None):
+                    wdy *= tXrW.load().to(Float32)
+
+            if const_expr(self.reload_x == "smem"):
+                cute.autovec_copy(tXsX[None, None, None, smem_stage], tXrX)
+                x = tXrX.load().to(cute.Float32)
+                x_hat = x * rstd
+
+            dx = (wdy - x_hat * mean_xhat_wdy) * rstd
+            if const_expr(mdResO is not None):
+                dx += tXrdResO.load().to(cute.Float32)
+            tXrdX.store(dx.to(tXrdX.element_type))
+            if row < M or tiler_mn[0] == 1:
+                copy(tXrdX, tXgdX[None, None, None, bidx])
+            if const_expr(mdRes is not None):
+                tXrdRes.store(dx.to(tXrdRes.element_type))
+                if row < M or tiler_mn[0] == 1:
+                    copy(tXrdRes, tXgdRes[None, None, None, bidx])
+            if const_expr(mdW is not None):
+                tXrdW.store(tXrdW.load() + dout * x_hat)
+            if const_expr(mdB is not None):
+                tXrdB.store(tXrdB.load() + dout)
+
+            if const_expr(USE_TMA):
+                tma_pipeline.sync_object_empty.arrive(
+                    consumer_state.index, tma_pipeline.consumer_mask
+                )
+            consumer_state.advance()
+
+            stage ^= 1
+            if stage == 0:
+                consumer_phase ^= 1
+                producer_phase ^= 1
+
+        if const_expr(tiler_mn[0] > 1):
+            if const_expr(mdW is not None):
+                # reduction of dw_partial within the same threadblock
+                sdW = cute.make_tensor(
+                    cute.recast_ptr(sX.iterator, dtype=cute.Float32),
+                    cute.make_ordered_layout(tiler_mn, order=(1, 0)),
+                )
+                tXsdW = thr_copy_X.partition_D(sdW)
+                cute.arch.barrier()
+                row = tXcX[None, None, None, 0][0][0]
+                if row > 0:
+                    cute.autovec_copy(tXrdW, tXsdW)
+                cute.arch.barrier()
+                if row == 0:
+                    for i in cutlass.range_constexpr(1, const_expr(tiler_mn[0])):
+                        tXrdW_other = cute.make_rmem_tensor_like(tXrdW)
+                        tXsdW_other = cute.make_tensor(
+                            tXsdW.iterator + i * sdW.stride[0], tXsdW.layout
+                        )
+                        cute.autovec_copy(tXsdW_other, tXrdW_other)
+                        tXrdW.store(tXrdW.load() + tXrdW_other.load())
+                    copy(tXrdW, tXgdW)
+                cute.arch.barrier()
+            if const_expr(mdB is not None):
+                sdB = cute.make_tensor(
+                    cute.recast_ptr(sX.iterator, dtype=cute.Float32),
+                    cute.make_ordered_layout(tiler_mn, order=(1, 0)),
+                )
+                tXsdB = thr_copy_X.partition_D(sdB)
+                cute.arch.barrier()
+                row = tXcX[None, None, None, 0][0][0]
+                if row > 0:
+                    cute.autovec_copy(tXrdB, tXsdB)
+                cute.arch.barrier()
+                if row == 0:
+                    for i in cutlass.range_constexpr(1, const_expr(tiler_mn[0])):
+                        tXrdB_other = cute.make_rmem_tensor_like(tXrdB)
+                        tXsdB_other = cute.make_tensor(
+                            tXsdB.iterator + i * sdB.stride[0], tXsdB.layout
+                        )
+                        cute.autovec_copy(tXsdB_other, tXrdB_other)
+                        tXrdB.store(tXrdB.load() + tXrdB_other.load())
+                    copy(tXrdB, tXgdB)
+        else:
+            # dw is already in fp32, so we can directly copy to global memory
+            if const_expr(mdW is not None):
+                copy(tXrdW, tXgdW)
+            if const_expr(mdB is not None):
+                copy(tXrdB, tXgdB)
+
+        if const_expr(self.cluster_n > 1):  # Prevent cluster from exiting early
+            # Assume state contains that next useful buffer
+            # So we only need to advance to num_stages - 1 times to last used buffer
+            stage ^= 1
+            if stage == 0:
+                producer_phase ^= 1
+            cute.arch.mbarrier_wait(mbar_empty_ptr + stage, producer_phase)
+
+
+def _rmsnorm_bwd(
+    x: Tensor,
+    weight: Optional[Tensor],
+    dout: Tensor,
+    rstd: Tensor,
+    dx: Tensor,
+    dw_partial: Optional[Tensor],
+    db_partial: Optional[Tensor] = None,
+    dresidual_out: Optional[Tensor] = None,
+    dresidual: Optional[Tensor] = None,
+    sm_count: Optional[int] = None,
+) -> None:
+    """RMSNorm backward pass.
+    Args:
+        x: Input tensor of shape (M, N) or (M, H, N) for per-head
+        weight: Optional weight tensor of shape (N,) or (H, N) for per-head
+        dout: Upstream gradients tensor of shape (M, N) or (M, H, N)
+        rstd: Reciprocal standard deviation tensor of shape (M,) or (M, H)
+    Returns:
+        Tuple of (dx, dw) where:
+        - dx: Input gradients tensor of same shape as x
+        - dw: Weight gradients tensor of same shape as weight (or None if weight is None)
+    """
+    assert x.dim() in (2, 3), "Input must be 2D or 3D"
+    supported_types = {torch.float16, torch.bfloat16, torch.float32}
+    assert x.dtype in supported_types, "Unsupported dtype"
+    per_head = x.dim() == 3
+    if weight is not None:
+        assert weight.dtype in supported_types, "Weight must be float32, float16 or bfloat16"
+    if dresidual_out is not None:
+        assert dresidual_out.shape == x.shape
+        assert dresidual_out.dtype in supported_types, (
+            "Residual must be float16, bfloat16, or float32"
+        )
+    if dresidual is not None:
+        assert dresidual.shape == x.shape
+        assert dresidual.dtype in supported_types, "Residual must be float16, bfloat16, or float32"
+    if x.numel() == 0:
+        return
+
+    N = x.size(-1)
+    if dw_partial is None and db_partial is None:
+        assert sm_count is not None
+    else:
+        sm_count = dw_partial.shape[0] if dw_partial is not None else db_partial.shape[0]
+    dtype, dout_dtype, dx_dtype, weight_dtype, dres_dtype, dres_out_dtype = [
+        torch2cute_dtype_map[t.dtype] if t is not None else None
+        for t in [x, dout, dx, weight, dresidual, dresidual_out]
+    ]
+    T_hint = _bucket_T_hint(int(x.size(0)) if not isinstance(x.size(0), torch.SymInt) else 0)
+    _compile_rmsnorm_bwd(
+        N,
+        dtype,
+        dout_dtype,
+        dx_dtype,
+        weight_dtype,
+        db_partial is not None,
+        dres_dtype,
+        dres_out_dtype,
+        dw_partial is not None,
+        per_head,
+        T_hint=T_hint,
+    )(x, weight, dout, dresidual_out, rstd, dx, dw_partial, dresidual, db_partial, sm_count)
+
+
+@jit_cache
+def _compile_rmsnorm_bwd(
+    N,
+    dtype,
+    dout_dtype,
+    dx_dtype,
+    weight_dtype,
+    has_db_partial,
+    dres_dtype,
+    dres_out_dtype,
+    has_dw_partial,
+    per_head=False,
+    T_hint=0,
+    config: Optional[RmsNormBwdConfig] = None,
+):
+    batch_sym, batch_partial_sym = cute.sym_int(), cute.sym_int()
+    head_sym = cute.sym_int() if per_head else None
+    batch_shape = (batch_sym, head_sym) if per_head else (batch_sym,)
+    all_dtypes = [dtype, dout_dtype, dx_dtype, dres_dtype, dres_out_dtype]
+    div = math.gcd(N, *(128 // dt.width for dt in all_dtypes if dt is not None))
+    x_cute, dout_cute, dx_cute, dres_out_cute, dres_cute = [
+        fake_tensor(dt, (*batch_shape, N), div)
+        for dt in [dtype, dout_dtype, dx_dtype, dres_out_dtype, dres_dtype]
+    ]
+    weight_shape = (head_sym, N) if per_head else (N,)
+    weight_cute = fake_tensor(weight_dtype, weight_shape, div)
+    rstd_cute = fake_tensor(Float32, batch_shape)
+    dw_shape = (batch_partial_sym, head_sym, N) if per_head else (batch_partial_sym, N)
+    dw_partial_cute = fake_tensor(Float32, dw_shape, div) if has_dw_partial else None
+    db_partial_cute = fake_tensor(Float32, dw_shape, div) if has_db_partial else None
+    return cute.compile(
+        RMSNormBackward(
+            dtype,
+            N,
+            dout_dtype=dout_dtype,
+            T_hint=T_hint,
+            per_head=per_head,
+            config=config,
+        ),
+        x_cute,
+        weight_cute,
+        dout_cute,
+        dres_out_cute,
+        rstd_cute,
+        dx_cute,
+        dw_partial_cute,
+        dres_cute,
+        db_partial_cute,
+        0,  # sm_count, just for compilation
+        cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True),
+        options="--enable-tvm-ffi",
+    )
+
+
+def rmsnorm_bwd(
+    x: Tensor,
+    weight: Optional[Tensor],
+    dout: Tensor,
+    rstd: Tensor,
+    dresidual_out: Optional[Tensor] = None,  # grad wrt residual_out
+    has_bias: bool = False,
+    has_residual: bool = False,
+) -> Tuple[Tensor, Optional[Tensor], Optional[Tensor], Optional[Tensor]]:
+    device = x.device
+    N = x.size(-1)
+    per_head = x.dim() == 3
+    dx = torch.empty_like(x)
+    if dresidual_out is not None and dresidual_out.dtype != dx.dtype:
+        dresidual = torch.empty_like(x, dtype=dresidual_out.dtype)
+    else:
+        dresidual = None
+    sm_count = get_sm_count(N, device)
+    if per_head:
+        H = x.size(1)
+        sm_count = max(round(sm_count / H), 1)
+    else:
+        H = None
+    if weight is not None:
+        # Always store partial gradients in fp32 for numerical accuracy
+        dw_shape = (sm_count, H, N) if per_head else (sm_count, N)
+        dw_partial = torch.empty(dw_shape, device=device, dtype=torch.float32)
+    else:
+        dw_partial = None
+    db_shape = (sm_count, H, N) if per_head else (sm_count, N)
+    db_partial = torch.empty(db_shape, device=device, dtype=torch.float32) if has_bias else None
+
+    if x.numel() > 0:
+        _rmsnorm_bwd(
+            x, weight, dout, rstd, dx, dw_partial, db_partial, dresidual_out, dresidual, sm_count
+        )
+        # we have summed the partial gradients in fp32, now we convert back to the weight dtype
+        dw = dw_partial.sum(dim=0).to(weight.dtype) if weight is not None else None
+        db = db_partial.sum(dim=0).to(weight.dtype) if has_bias else None
+    else:
+        dw = torch.zeros_like(weight) if weight is not None else None
+        db = torch.zeros_like(weight) if has_bias else None
+    # dresidual is the same as dx in this case
+    if has_residual and dresidual is None:
+        dresidual = dx
+    return dx, dw, db, dresidual
+
+
+@autotune(
+    configs=[AutotuneConfig(config=c) for c in get_all_bwd_configs()],
+    key=["per_head", "has_dw_partial", "has_db_partial"],
+    prune_configs_by={"early_config_prune": prune_invalid_rmsnorm_bwd_configs},
+)
+def rmsnorm_bwd_tuned(
+    x: Tensor,
+    weight: Optional[Tensor],
+    dout: Tensor,
+    rstd: Tensor,
+    dx: Tensor,
+    dw_partial: Optional[Tensor] = None,
+    db_partial: Optional[Tensor] = None,
+    dresidual_out: Optional[Tensor] = None,
+    dresidual: Optional[Tensor] = None,
+    sm_count: Optional[int] = None,
+    per_head: bool = False,
+    has_dw_partial: bool = False,
+    has_db_partial: bool = False,
+    config: Optional[RmsNormBwdConfig] = None,
+) -> None:
+    """Autotuned RMSNorm backward dispatch.
+
+    The ``@autotune`` decorator injects ``config`` from the exhaustive search
+    space at first call for a given (shape, dtype, ``per_head``, has_*) and
+    caches the winner for subsequent calls. The un-tuned counterpart is
+    :func:`rmsnorm_bwd`, which uses the analytical heuristic.
+    """
+    if config is None:
+        raise RuntimeError(
+            "rmsnorm_bwd_tuned requires a config (provided automatically by "
+            "the @autotune decorator). Use rmsnorm_bwd for the un-tuned path."
+        )
+    # The persistent grid size is encoded in the partial-accumulator shape
+    # (dw_partial / db_partial have shape (sm_count, ..., N)). Derive
+    # sm_count from there when available; require it explicitly only when
+    # neither buffer is provided. Mirrors the _rmsnorm_bwd torch-op
+    # contract.
+    if dw_partial is not None:
+        sm_count = dw_partial.shape[0]
+    elif db_partial is not None:
+        sm_count = db_partial.shape[0]
+    elif sm_count is None:
+        raise ValueError(
+            "rmsnorm_bwd_tuned: sm_count is required when neither dw_partial "
+            "nor db_partial is provided."
+        )
+    N = x.size(-1)
+    dtype, dout_dtype, dx_dtype, weight_dtype, dres_dtype, dres_out_dtype = [
+        torch2cute_dtype_map[t.dtype] if t is not None else None
+        for t in [x, dout, dx, weight, dresidual, dresidual_out]
+    ]
+    _compile_rmsnorm_bwd(
+        N,
+        dtype,
+        dout_dtype,
+        dx_dtype,
+        weight_dtype,
+        has_db_partial,
+        dres_dtype,
+        dres_out_dtype,
+        has_dw_partial,
+        per_head,
+        T_hint=0,
+        config=config,
+    )(x, weight, dout, dresidual_out, rstd, dx, dw_partial, dresidual, db_partial, sm_count)
+
+
+class RMSNormFunction(torch.autograd.Function):
+    """Autograd wrapper for rmsnorm.
+
+    All input reshaping (flattening batch dims, per-head layout) is done in the
+    rmsnorm() wrapper BEFORE calling .apply(). This function receives already-
+    flattened tensors so that tensor ranks never change between recompilations,
+    which is required for torch.compile compatibility.
+    """
+
+    @staticmethod
+    def forward(
+        ctx,
+        x,
+        weight,
+        bias=None,
+        residual=None,
+        out_dtype=None,
+        residual_dtype=None,
+        eps=1e-6,
+        prenorm=False,
+    ):
+        x = _ensure_contiguous(x)
+        if residual is not None:
+            residual = _ensure_contiguous(residual)
+        need_grad = any(ctx.needs_input_grad[:3])
+        out, residual_out, rstd = rmsnorm_fwd(
+            x,
+            weight,
+            bias=bias,
+            residual=residual,
+            out_dtype=out_dtype,
+            residual_dtype=residual_dtype,
+            eps=eps,
+            store_rstd=need_grad,
+        )
+        ctx.save_for_backward(x if residual is None else residual_out, weight, rstd)
+        ctx.has_bias = bias is not None
+        ctx.has_residual = residual is not None
+        ctx.prenorm = prenorm
+        if residual_out is None or not prenorm:
+            return out
+        else:
+            return out, residual_out
+
+    @staticmethod
+    def backward(ctx, dout, *args):
+        x, weight, rstd = ctx.saved_tensors
+        dout = _ensure_contiguous(dout)
+        if ctx.prenorm and ctx.has_residual:
+            dresidual_out = _ensure_contiguous(args[0])
+        else:
+            dresidual_out = None
+        dx, dw, db, dresidual = rmsnorm_bwd(
+            x,
+            weight,
+            dout,
+            rstd,
+            dresidual_out,
+            ctx.has_bias,
+            has_residual=ctx.has_residual,
+        )
+        return dx, dw, db, dresidual, *([None] * 4)
+
+
+def rmsnorm(
+    x: Tensor,
+    weight: Optional[Tensor] = None,
+    bias: Optional[Tensor] = None,
+    residual: Optional[Tensor] = None,
+    out_dtype: Optional[torch.dtype] = None,
+    residual_dtype: Optional[torch.dtype] = None,
+    eps: float = 1e-6,
+    prenorm: bool = False,
+) -> Tensor:
+    """RMSNorm with automatic differentiation support.
+
+    Args:
+        x: Input tensor of shape (M, N) or (B, S, H, D) for per-head mode
+        weight: Optional weight tensor of shape (N,) or (H, D) for per-head mode
+        eps: Small value for numerical stability
+
+    Returns:
+        Normalized output tensor of same shape as x
+    """
+    x_shape_og = x.shape
+    per_head = (weight is not None and weight.dim() == 2) or (bias is not None and bias.dim() == 2)
+    last_shape = x_shape_og[-1:] if not per_head else x_shape_og[-2:]
+    # Flatten batch dims before entering autograd.Function so tensor ranks
+    # are determined by per_head (which dynamo guards on via the if-branch),
+    # not by the original input shape. This ensures torch.compile can
+    # recompile the backward subgraph correctly when switching between
+    # per_head=False and per_head=True.
+    x_flat = x.reshape(-1, *last_shape)
+    res_flat = residual.reshape(-1, *last_shape) if residual is not None else None
+    result = RMSNormFunction.apply(
+        x_flat, weight, bias, res_flat, out_dtype, residual_dtype, eps, prenorm
+    )
+    if isinstance(result, tuple):
+        return tuple(r.reshape(x_shape_og) for r in result)
+    return result.reshape(x_shape_og)
+
+
+class QuackRMSNorm(torch.nn.RMSNorm):
+    """RMSNorm module that behaves like torch.nn.RMSNorm.
+
+    This class provides a drop-in replacement for torch.nn.RMSNorm that uses
+    the torch._vendor.quack.rmsnorm implementation under the hood.
+
+    Args:
+        dim (int): The dimension to normalize over
+        eps (float, optional): A small constant for numerical stability. Default: 1e-6
+
+    Attributes:
+        weight (torch.nn.Parameter): The learnable weight parameter
+        eps (float): A small constant for numerical stability
+    """
+
+    def __init__(
+        self, dim: int, eps: float = 1e-6, elementwise_affine: bool = True, device=None, dtype=None
+    ):
+        super().__init__(dim, eps, elementwise_affine, device=device, dtype=dtype)
+
+    def forward(self, x: Tensor) -> Tensor:
+        """Apply RMSNorm to the input tensor.
+
+        Args:
+            x (Tensor): Input tensor
+
+        Returns:
+            Tensor: Normalized tensor
+        """
+        return rmsnorm(x, self.weight, eps=self.eps)
+
+
+def layernorm_fwd(
+    x: Tensor,
+    weight: Tensor,
+    bias: Optional[Tensor] = None,
+    eps: float = 1e-6,
+    return_rstd: bool = False,
+    return_mean: bool = False,
+):
+    """LayerNorm forward pass using the unified RMSNorm/LayerNorm kernel.
+
+    Args:
+        x: Input tensor of shape (M, N)
+        weight: Weight tensor of shape (N,). Must be float32.
+        bias: Optional bias tensor of shape (N,). Must be float32.
+        eps: Small value for numerical stability
+        return_rstd: Whether to return the reciprocal standard deviation
+        return_mean: Whether to return the mean
+
+    Returns:
+        Normalized output tensor of same shape as x
+        If return_rstd is True, also returns rstd tensor of shape (M,)
+        If return_mean is True, also returns mean tensor of shape (M,)
+    """
+    assert x.dim() == 2, "Input must be 2D"
+    assert weight.dim() == 1, "Weight must be 1D"
+    assert x.dtype in [torch.float16, torch.bfloat16, torch.float32], "Unsupported dtype"
+    assert weight.dtype == torch.float32, "Weight must be float32"
+    if bias is not None:
+        assert bias.dim() == 1, "Bias must be 1D"
+        assert bias.dtype == torch.float32, "Bias must be float32"
+
+    M, N = x.shape
+    device = x.device
+    out = torch.empty_like(x)
+    rstd = torch.empty(M, device=device, dtype=torch.float32) if return_rstd else None
+    mean = torch.empty(M, device=device, dtype=torch.float32) if return_mean else None
+
+    _rmsnorm_fwd(x, weight, out, bias, rstd, mean, None, None, eps, True)
+
+    if return_rstd and return_mean:
+        return out, rstd, mean
+    elif return_rstd:
+        return out, rstd
+    elif return_mean:
+        return out, mean
+    return out
+
+
+def layernorm_ref(x: Tensor, w: Tensor, eps: float = 1e-6) -> Tensor:
+    """Reference implementation for LayerNorm."""
+    x_f32 = x.float()
+    return torch.nn.functional.layer_norm(x_f32, w.shape, w, None, eps).to(x.dtype)
+
+
+def layernorm_rstd_ref(x: torch.Tensor, eps: float = 1e-6):
+    x_f32 = x.float()
+    mean = x_f32.mean(dim=-1, keepdim=True)
+    var = ((x_f32 - mean) ** 2).mean(dim=-1)
+    return 1.0 / torch.sqrt(var + eps)
+
+
+def layernorm_mean_ref(x: torch.Tensor) -> torch.Tensor:
+    return x.float().mean(dim=-1)
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/rmsnorm_config.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/rmsnorm_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..d44de037e491f213d9e3bff76e5557b49855722d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/rmsnorm_config.py
@@ -0,0 +1,496 @@
+# Copyright (c) 2025, Wentao Guo, Ted Zadouri, Tri Dao.
+
+"""Launch configuration for the RMSNorm forward and backward kernels.
+
+Mirrors :mod:`quack.gemm_config`: frozen dataclasses that capture the launch
+knobs, plus arch-specific factories that own the heuristics.
+"""
+
+import itertools
+from dataclasses import dataclass
+from typing import List, Optional
+
+import torch
+
+
+@dataclass(frozen=True)
+class RmsNormFwdConfig:
+    num_threads: int
+    threads_per_row: int
+    cluster_n: int
+    # None = compute once into registers; "smem" / "gmem" = reload x (and
+    # residual) before the post-reduction epilogue.
+    reload_from: Optional[str]
+    # Defer the weight/bias load until after the row reduction.
+    delay_w_load: bool = False
+
+    @classmethod
+    def from_analytical_heuristic(
+        cls,
+        N: int,
+        dtype_width: int,
+        arch_major: Optional[int] = None,
+        is_layernorm: bool = False,
+    ) -> "RmsNormFwdConfig":
+        """Pick a launch config from the hand-tuned analytical heuristic.
+
+        ``arch_major`` defaults to the current device's capability. The same
+        ladder is used for Hopper, Blackwell, and SM12x today; a future
+        ``_for_blackwell_fwd`` factory can be added and dispatched on
+        ``arch_major >= 10``. For autotuning, use :func:`get_all_fwd_configs`.
+        """
+        if arch_major is None:
+            arch_major = _detect_arch_major()
+        return _for_hopper_fwd(N, dtype_width, arch_major, is_layernorm)
+
+
+def _for_hopper_fwd(
+    N: int, dtype_width: int, arch_major: int, is_layernorm: bool
+) -> RmsNormFwdConfig:
+    num_threads = 128 if N <= 16 * 1024 else 256
+
+    threads_per_row = 256
+    for limit, threads in [(64, 8), (128, 16), (3072, 32), (6144, 64), (16384, 128)]:
+        if N <= limit:
+            threads_per_row = threads
+            break
+
+    if arch_major < 9:
+        cluster_n = 1
+    else:
+        max_cluster = 8 if arch_major == 12 else 16
+        # cluster_n=4 is faster than cluster_n=2 for N=64k; cluster_n=8 is
+        # faster for N=128k.
+        if arch_major == 12 and dtype_width >= 32:
+            # SM12x 99 KB SMEM: fp32 needs tighter clustering (conservative for residual case)
+            thresholds = [(8 * 1024, 1), (16 * 1024, 2), (32 * 1024, 4), (64 * 1024, 8)]
+        elif dtype_width == 16:
+            thresholds = [(16 * 1024, 1), (32 * 1024, 2), (64 * 1024, 4), (128 * 1024, 8)]
+        elif is_layernorm:
+            # fp32 layernorm: bump cluster earlier than fp16/bf16. The 2-pass path's
+            # single-CTA tile is bandwidth-limited at N=16k/32k; cluster_n=2 splits
+            # the row across two CTAs and recovers ~3-14% at those sizes.
+            thresholds = [(8 * 1024, 1), (64 * 1024, 2), (128 * 1024, 4), (256 * 1024, 8)]
+        else:
+            # fp32 rmsnorm (1-pass) is already saturated at cluster_n=1 for N<=32k;
+            # bumping to cluster_n=2 there regresses ~3%.
+            thresholds = [(32 * 1024, 1), (64 * 1024, 2), (128 * 1024, 4), (256 * 1024, 8)]
+        cluster_n = max_cluster
+        for limit, cluster in thresholds:
+            if N <= limit:
+                cluster_n = cluster
+                break
+
+    reload_threshold = 16 * 1024 if is_layernorm else 8 * 1024
+    return RmsNormFwdConfig(
+        num_threads=num_threads,
+        threads_per_row=threads_per_row,
+        cluster_n=cluster_n,
+        reload_from=None if N <= reload_threshold else "smem",
+        delay_w_load=False,
+    )
+
+
+@dataclass(frozen=True)
+class RmsNormBwdConfig:
+    num_threads: int
+    threads_per_row: int
+    cluster_n: int
+    # None = recompute from registers; "smem" = reload from shared memory.
+    reload_wdy: Optional[str]
+    reload_x: Optional[str]
+    use_tma: bool
+    # Number of smem stages used by the prefetch pipeline. Drives both the
+    # cp.async (use_tma=False) and TMA (use_tma=True) paths, which lead by
+    # ``smem_stages - 1`` batches. Larger depths hide more latency at the cost
+    # of smem footprint.
+    smem_stages: int = 2
+
+    @classmethod
+    def from_analytical_heuristic(
+        cls,
+        N: int,
+        dtype_width: int,
+        dout_width: int,
+        arch_major: Optional[int] = None,
+        T_hint: int = 0,
+    ) -> "RmsNormBwdConfig":
+        """Pick a launch config from the hand-tuned analytical heuristic.
+
+        ``arch_major`` defaults to the current device's capability.
+        ``arch_major >= 10`` selects the Blackwell heuristic; anything else
+        uses the legacy/default path tuned on Hopper. For autotuning, use
+        :func:`get_all_bwd_configs`.
+        """
+        if arch_major is None:
+            arch_major = _detect_arch_major()
+        if arch_major >= 10:
+            return _for_blackwell_bwd(N, dtype_width, dout_width, T_hint)
+        return _for_hopper_bwd(N, dtype_width, arch_major)
+
+
+def _for_hopper_bwd(N: int, dtype_width: int, arch_major: int) -> RmsNormBwdConfig:
+    num_threads = 128 if N <= 4096 else 256
+    for limit, threads in [(64, 8), (128, 16), (256, 32), (512, 64), (4096, 128)]:
+        if N <= limit:
+            threads_per_row = threads
+            break
+    else:
+        threads_per_row = 256
+
+    if arch_major < 9:
+        cluster_n = 1
+    else:
+        max_cluster = 8 if arch_major == 12 else 16
+        if arch_major == 12 and dtype_width >= 32:
+            thresholds = [(1024, 1), (8 * 1024, 2), (16 * 1024, 4), (32 * 1024, 8)]
+        else:
+            thresholds = [(8 * 1024, 1), (16 * 1024, 2), (32 * 1024, 4), (64 * 1024, 8)]
+        cluster_n = max_cluster
+        for limit, cluster in thresholds:
+            if N <= limit:
+                cluster_n = cluster
+                break
+
+    return RmsNormBwdConfig(
+        num_threads=num_threads,
+        threads_per_row=threads_per_row,
+        cluster_n=cluster_n,
+        reload_wdy=None if N <= 16 * 1024 else "smem",
+        reload_x=None,
+        use_tma=False,
+    )
+
+
+def _for_blackwell_bwd(
+    N: int, dtype_width: int, dout_width: int, T_hint: int = 0
+) -> RmsNormBwdConfig:
+    """Pick a launch config for RMSNorm bwd on Blackwell.
+
+    All thresholds are expressed in ``row_bytes = N * max(x, dout)`` so a
+    single ladder handles bf16, fp32, and mixed-dtype combinations. ``x_bytes``
+    governs the X tile (loads, smem footprint); ``max_bytes`` is the wider
+    side which sets register pressure for the per-thread fragments.
+    """
+    # Safety floor for very narrow rows: keep tpr below 128 so we don't over-
+    # parallelise tiny problems.
+    if N <= 64:
+        threads_per_row = 8
+    elif N <= 128:
+        threads_per_row = 16
+    elif N <= 256:
+        threads_per_row = 32
+    elif N <= 512:
+        threads_per_row = 64
+    else:
+        threads_per_row = None
+
+    if threads_per_row is not None:
+        return RmsNormBwdConfig(
+            num_threads=128,
+            threads_per_row=threads_per_row,
+            cluster_n=1,
+            reload_wdy=None,
+            reload_x=None,
+            use_tma=False,
+        )
+
+    max_bytes = max(dtype_width, dout_width) // 8
+    row_bytes = N * max_bytes
+
+    if row_bytes >= 48 * 1024:
+        # Spread the row across a CTA cluster. Step back to cluster_n=4 only
+        # when T is tiny AND the row isn't extreme — otherwise cn=8 keeps each
+        # CTA's tile small enough to fit comfortably in registers.
+        cluster_n = 4 if 0 < T_hint <= 1024 and row_bytes <= 64 * 1024 else 8
+        num_threads, threads_per_row = 128, 128
+        # Override if this cluster_n would overflow the device's smem budget.
+        cluster_n = _bump_cluster_n_for_smem(
+            cluster_n,
+            N,
+            smem_stages=2,
+            sum_bytes=(dtype_width + dout_width) // 8,
+            max_cluster=_max_cluster_for(10),  # Blackwell
+        )
+    elif row_bytes > 16 * 1024:
+        # Wider than 128 threads can comfortably handle at cluster_n=1; bump
+        # threads/row to keep per-thread fragments small.
+        cluster_n = 1
+        num_threads, threads_per_row = 256, 256
+    else:
+        cluster_n = 1
+        num_threads, threads_per_row = 128, 128
+
+    bytes_per_thread_frag = (N // cluster_n) // threads_per_row * max_bytes
+
+    # TMA pays off when the cluster needs prefetch (cn>=4), and also for
+    # fp32-class single-CTA wide rows where TMA's wider descriptors amortise
+    # setup. Pure bf16 single-CTA cases mostly don't benefit and can lose ~5%.
+    use_tma = cluster_n >= 4 or (max_bytes >= 4 and row_bytes >= 16 * 1024)
+    # reload_x: wide end of the cluster ladder, plus fp32-class single-CTA
+    # cases where the wider X fragments crowd registers across the row
+    # reduction barrier.
+    reload_x = (
+        "smem"
+        if (cluster_n >= 8 and N >= 32 * 1024)
+        or (cluster_n == 1 and max_bytes >= 4 and bytes_per_thread_frag >= 64)
+        else None
+    )
+    # reload_wdy: cluster cases get it for free, plus single-CTA cases where
+    # each thread holds ≥64 bytes of fragment (the wdy register count is then
+    # large enough to spill).
+    reload_wdy = "smem" if cluster_n >= 4 or bytes_per_thread_frag >= 64 else None
+
+    return RmsNormBwdConfig(
+        num_threads=num_threads,
+        threads_per_row=threads_per_row,
+        cluster_n=cluster_n,
+        reload_wdy=reload_wdy,
+        reload_x=reload_x,
+        use_tma=use_tma,
+    )
+
+
+def _get_sm_count_hopper(N: int, sm_count: int) -> int:
+    # This should be tuned on how many CTAs can be launched on each SM.
+    sm_count_multiple = (
+        16 if N <= 256 else (8 if N <= 1024 else (4 if N <= 2048 else (2 if N <= 4096 else 1)))
+    )
+    # By right, if we're using cluster, this should be cluster_count not sm_count.
+    # But for cluster >= 4, due to quantization we would need to query active max cluster.
+    # Instead we just do sm_count * 2, which is reasonably larger than active_cluster_count to
+    # avoid wave quantization.
+    return (
+        sm_count * sm_count_multiple if N <= 8192 else sm_count // 2 if N <= 16384 else sm_count * 2
+    )
+
+
+def _get_sm_count_blackwell(N: int, sm_count: int) -> int:
+    if N <= 256:
+        return sm_count * 16
+    if N <= 1024:
+        return sm_count * 8
+    if N <= 2048:
+        return sm_count * 4
+    return sm_count * 2
+
+
+def get_sm_count(N: int, device: torch.device) -> int:
+    props = torch.cuda.get_device_properties(device)
+    if props.major >= 10:
+        return _get_sm_count_blackwell(N, props.multi_processor_count)
+    return _get_sm_count_hopper(N, props.multi_processor_count)
+
+
+_CTA_THREAD_SIZE = (128, 256)
+# Full launch-knob menu lives here; the per-call pruner in
+# ``prune_invalid_rmsnorm_{fwd,bwd}_configs`` drops layouts that don't fit the
+# current row. The tiny widths (8, 16, 32) are kept for the analytical
+# heuristic's narrow-row safety floor (N <= 512) but are dropped from the
+# autotune search space below since they're only optimal for that floor.
+_THREADS_PER_REDUCTION_DIM = (8, 16, 32, 64, 128, 256)
+_AUTOTUNE_THREADS_PER_REDUCTION_DIM = (64, 128, 256)
+# smem_stages=4 doubles the data-buffer footprint vs stages=2 and crashes at
+# launch for fp32 N>=64K on Blackwell (227 KB opt-in smem). Stages=3 still
+# offers a meaningful prefetch depth without that risk.
+_AUTOTUNE_SMEM_STAGES = (2, 3)
+
+
+def _max_dynamic_smem_bytes() -> int:
+    """Per-CTA opt-in dynamic smem capacity for the current device.
+
+    Returns 0 when CUDA is unavailable (callers should treat this as "no
+    smem-budget guard"). Falls back to ``shared_memory_per_block`` on older
+    PyTorch builds that lack the ``_optin`` field.
+    """
+    if not torch.cuda.is_available():
+        return 0
+    props = torch.cuda.get_device_properties(torch.cuda.current_device())
+    return getattr(props, "shared_memory_per_block_optin", props.shared_memory_per_block)
+
+
+def _bump_cluster_n_for_smem(
+    cluster_n: int,
+    N: int,
+    smem_stages: int,
+    sum_bytes: int,
+    max_cluster: int,
+) -> int:
+    """Raise ``cluster_n`` to the smallest power of 2 such that the bwd's
+    sX+sdO data buffers fit under the device's opt-in dynamic smem.
+
+    Footprint per CTA is ``(N / cluster_n) * smem_stages * sum_bytes`` where
+    ``sum_bytes = x_bytes + dout_bytes``. Snaps up to the next power of 2,
+    floors at the input ``cluster_n`` (never lowers the tuning's choice), and
+    caps at ``max_cluster``. If the required cluster_n exceeds ``max_cluster``
+    the runtime guard in ``RMSNormBackward.__init__`` raises a precise overflow
+    error. Returns the input unchanged if CUDA is unavailable.
+    """
+    # Reserved for row-reduction buffer, mbars, and smem alignment overhead.
+    _BWD_SMEM_RESERVED_BYTES = 4 * 1024
+    smem_max = _max_dynamic_smem_bytes()
+    if smem_max <= 0:
+        return cluster_n
+    budget = max(smem_max - _BWD_SMEM_RESERVED_BYTES, 1)
+    needed = (N * smem_stages * sum_bytes + budget - 1) // budget  # ceil-div
+    pow2 = 1
+    while pow2 < needed:
+        pow2 *= 2
+    return min(max(pow2, cluster_n), max_cluster)
+
+
+def _detect_arch_major() -> int:
+    """Return the major device capability of the current CUDA device.
+
+    Falls back to 0 (no-cluster, no-TMA) when CUDA is unavailable so the
+    autotune search space stays well-defined for CPU-only imports.
+    """
+    if not torch.cuda.is_available():
+        return 0
+    return torch.cuda.get_device_capability(torch.cuda.current_device())[0]
+
+
+def _max_cluster_for(arch_major: int) -> int:
+    """Maximum cluster_n supported on this arch."""
+    if arch_major < 9:
+        return 1
+    # SM12x (RTX 50) supports up to 8; Hopper/Blackwell up to 16.
+    return 8 if arch_major == 12 else 16
+
+
+def get_all_fwd_configs() -> List[RmsNormFwdConfig]:
+    """Exhaustive search space of RMSNorm fwd configs for the current device.
+
+    The search space is over launch knobs only — ``device_capacity`` is not a
+    tunable parameter, so the current device's capability is queried once and
+    used to bound ``cluster_n``.
+    """
+    arch_major = _detect_arch_major()
+    max_cluster = _max_cluster_for(arch_major)
+    cluster_vals = tuple(c for c in (1, 2, 4, 8, 16) if c <= max_cluster)
+    reload_from_vals = (None, "smem", "gmem")
+    delay_w_load_vals = (False,)
+
+    configs: List[RmsNormFwdConfig] = []
+    for num_threads, threads_per_row, cluster_n, reload_from, delay_w_load in itertools.product(
+        _CTA_THREAD_SIZE,
+        _AUTOTUNE_THREADS_PER_REDUCTION_DIM,
+        cluster_vals,
+        reload_from_vals,
+        delay_w_load_vals,
+    ):
+        if threads_per_row > num_threads:
+            continue
+        if num_threads % threads_per_row != 0:
+            continue
+        configs.append(
+            RmsNormFwdConfig(
+                num_threads=num_threads,
+                threads_per_row=threads_per_row,
+                cluster_n=cluster_n,
+                reload_from=reload_from,
+                delay_w_load=delay_w_load,
+            )
+        )
+    return configs
+
+
+def get_all_bwd_configs() -> List[RmsNormBwdConfig]:
+    """Exhaustive search space of RMSNorm bwd configs for the current device.
+
+    Like :func:`get_all_fwd_configs`, the current device's capability bounds
+    ``cluster_n`` and gates ``use_tma`` (TMA requires SM90+). ``smem_stages``
+    sweeps the safe depths in :data:`_AUTOTUNE_SMEM_STAGES`.
+    """
+    arch_major = _detect_arch_major()
+    max_cluster = _max_cluster_for(arch_major)
+    cluster_vals = tuple(c for c in (1, 2, 4, 8, 16) if c <= max_cluster)
+    use_tma_vals = (False, True) if arch_major >= 9 else (False,)
+    reload_vals = (None, "smem")
+
+    configs: List[RmsNormBwdConfig] = []
+    for (
+        num_threads,
+        threads_per_row,
+        cluster_n,
+        reload_wdy,
+        reload_x,
+        use_tma,
+        smem_stages,
+    ) in itertools.product(
+        _CTA_THREAD_SIZE,
+        _AUTOTUNE_THREADS_PER_REDUCTION_DIM,
+        cluster_vals,
+        reload_vals,
+        reload_vals,
+        use_tma_vals,
+        _AUTOTUNE_SMEM_STAGES,
+    ):
+        if threads_per_row > num_threads:
+            continue
+        if num_threads % threads_per_row != 0:
+            continue
+        configs.append(
+            RmsNormBwdConfig(
+                num_threads=num_threads,
+                threads_per_row=threads_per_row,
+                cluster_n=cluster_n,
+                reload_wdy=reload_wdy,
+                reload_x=reload_x,
+                use_tma=use_tma,
+                smem_stages=smem_stages,
+            )
+        )
+    return configs
+
+
+def prune_invalid_rmsnorm_fwd_configs(configs, named_args: dict, **kwargs):
+    """Drop configs whose CTA layout doesn't fit the row width.
+
+    The search space (see :func:`get_all_fwd_configs`) is already restricted to
+    the current device's capability, so all that's left is a per-call shape
+    check: ``threads_per_row * cluster_n > N`` would leave cluster CTAs with no
+    work to do, so skip those.
+    """
+    kwargs = named_args | kwargs
+    x = kwargs["x"]
+    N = int(x.size(-1))
+    pruned = []
+    for ac in configs:
+        c = ac.kwargs["config"]
+        if c.threads_per_row * c.cluster_n > N:
+            continue
+        pruned.append(ac)
+    return pruned
+
+
+def prune_invalid_rmsnorm_bwd_configs(configs, named_args: dict, **kwargs):
+    """Same per-call shape filter as the fwd, plus three ``use_tma`` drops
+    that mirror the runtime ``USE_TMA`` guard in :class:`RMSNormBackward`
+    (``USE_TMA = use_tma and not per_head and row_bytes_x % 16 == 0 and
+    row_bytes_do % 16 == 0``). Configs that would silently fall back to the
+    cp.async path are dropped here so the autotune bench doesn't time the
+    same kernel twice and pick whichever happens to bench faster by noise.
+    """
+    kwargs = named_args | kwargs
+    x = kwargs["x"]
+    dout = kwargs.get("dout")
+    N = int(x.size(-1))
+    per_head = bool(kwargs.get("per_head", x.dim() == 3))
+    x_bytes = x.element_size()
+    dout_bytes = dout.element_size() if dout is not None else x_bytes
+    pruned = []
+    for ac in configs:
+        c = ac.kwargs["config"]
+        if c.threads_per_row * c.cluster_n > N:
+            continue
+        if c.use_tma:
+            if per_head:
+                continue
+            tile_n = N // max(1, c.cluster_n)
+            row_bytes_x = tile_n * x_bytes
+            row_bytes_do = tile_n * dout_bytes
+            if row_bytes_x % 16 != 0 or row_bytes_do % 16 != 0:
+                continue
+        pruned.append(ac)
+    return pruned
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/rounding.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/rounding.py
new file mode 100644
index 0000000000000000000000000000000000000000..cba881062bc14ebb29426a3792c519e9aff86f21
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/rounding.py
@@ -0,0 +1,238 @@
+# Copyright (c) 2025-2026, Vijay Thakkar, Tri Dao.
+"""Rounding mode control and stochastic rounding primitives for GEMM epilogues.
+
+Provides a RoundingMode enum for configuring how epilogues downconvert the
+accumulator dtype (typically FP32) to the output dtype before storing to gmem.
+Stochastic rounding (RS) uses the hardware cvt.rs.satfinite.bf16x2.f32 PTX
+instruction and is only supported on Blackwell (SM100+) GPUs.
+"""
+
+from enum import IntEnum
+
+import cutlass
+import cutlass.cute as cute
+from cutlass import Float32, Uint32
+from cutlass._mlir import ir
+from cutlass._mlir.dialects import arith, llvm, vector
+from cutlass.cutlass_dsl import dsl_user_op, Int32, T
+
+
+class RoundingMode(IntEnum):
+    """Rounding modes for epilogue dtype downconversion.
+
+    RN — Round to nearest even (default hardware behavior)
+    RS — Stochastic rounding (SM100+ only, BF16 output only)
+    """
+
+    RN = 0
+    RS = 1
+
+
+# Odd strides used to derive distinct Philox counters across output tiles and subtiles.
+EPILOGUE_SR_SEED_M_STRIDE = 65537
+EPILOGUE_SR_SEED_N_STRIDE = 257
+EPILOGUE_SR_SEED_BATCH_STRIDE = 17
+EPILOGUE_SR_SEED_SUBTILE_STRIDE = 7
+EPILOGUE_SR_SEED_AUX_OUT_SALT = 0x9E3779B1
+
+PHILOX_N_ROUNDS_DEFAULT = 7
+
+PHILOX_ROUND_A = 0xD2511F53
+PHILOX_ROUND_B = 0xCD9E8D57
+PHILOX_KEY_A = 0x9E3779B9
+PHILOX_KEY_B = 0xBB67AE85
+
+
+@dsl_user_op
+def epilogue_sr_seed(
+    base_seed: Int32,
+    tile_coord_mnkl: cute.Coord,
+    subtile_idx,
+    *,
+    loc=None,
+    ip=None,
+) -> Int32:
+    return base_seed + (
+        tile_coord_mnkl[0] * EPILOGUE_SR_SEED_M_STRIDE
+        + tile_coord_mnkl[1] * EPILOGUE_SR_SEED_N_STRIDE
+        + tile_coord_mnkl[3] * EPILOGUE_SR_SEED_BATCH_STRIDE
+        + subtile_idx * EPILOGUE_SR_SEED_SUBTILE_STRIDE
+    )
+
+
+@dsl_user_op
+def epilogue_aux_out_sr_seed(
+    base_seed: Int32,
+    tile_coord_mnkl: cute.Coord,
+    subtile_idx,
+    *,
+    loc=None,
+    ip=None,
+) -> Int32:
+    return epilogue_sr_seed(
+        base_seed + EPILOGUE_SR_SEED_AUX_OUT_SALT,
+        tile_coord_mnkl,
+        subtile_idx,
+        loc=loc,
+        ip=ip,
+    )
+
+
+@dsl_user_op
+def mul_wide_u32(a: Uint32, b: Uint32, *, loc=None, ip=None) -> tuple:
+    """Unsigned 32b x 32b -> 64 wide multiply via PTX `mul.wide.u32`.
+
+    Returns (hi, lo) as a pair of Uint32 values.
+    """
+    struct_ty = ir.Type.parse("!llvm.struct<(i32, i32)>")
+    result = llvm.inline_asm(
+        struct_ty,
+        [
+            Uint32(a).ir_value(loc=loc, ip=ip),
+            Uint32(b).ir_value(loc=loc, ip=ip),
+        ],
+        "{\n  .reg .u64 prod;\n  mul.wide.u32 prod, $2, $3;\n  mov.b64 {$1, $0}, prod;\n}",
+        "=r,=r,r,r",
+        has_side_effects=False,
+        is_align_stack=False,
+    )
+    i32_ty = T.i32()
+    hi = cutlass.Uint32(llvm.extractvalue(i32_ty, result, [0], loc=loc, ip=ip))
+    lo = cutlass.Uint32(llvm.extractvalue(i32_ty, result, [1], loc=loc, ip=ip))
+    return hi, lo
+
+
+@dsl_user_op
+def cvt_f32x2_bf16x2_rs(
+    a: Float32,
+    b: Float32,
+    rand_bits: Uint32,
+    *,
+    loc=None,
+    ip=None,
+) -> cutlass.Int32:
+    """Convert 2 FP32 values to packed BF16x2 using stochastic rounding.
+
+    Uses Blackwell PTX instruction: cvt.rs.satfinite.bf16x2.f32 dst, src_hi, src_lo, rand
+    """
+    return cutlass.Int32(
+        llvm.inline_asm(
+            T.i32(),
+            [
+                Float32(a).ir_value(loc=loc, ip=ip),
+                Float32(b).ir_value(loc=loc, ip=ip),
+                Uint32(rand_bits).ir_value(loc=loc, ip=ip),
+            ],
+            "cvt.rs.satfinite.bf16x2.f32 $0, $2, $1, $3;",
+            "=r,f,f,r",
+            has_side_effects=False,
+            is_align_stack=False,
+        )
+    )
+
+
+@dsl_user_op
+def philox(
+    counter: Uint32,
+    key: Uint32,
+    n_rounds: int = PHILOX_N_ROUNDS_DEFAULT,
+    *,
+    loc=None,
+    ip=None,
+) -> tuple:
+    """Philox 4x32b counter-based random number generator.
+
+    Given a 32b counter and a 32b key, returns four pseudo-random uint32 words
+    produced by running n_rounds of the Philox 4x32 bijection. Each round
+    performs two wide 32x32->64 multiplies with the Philox constants.
+    """
+    c0 = Uint32(counter)
+    c1 = Uint32(0)
+    c2 = Uint32(0)
+    c3 = Uint32(0)
+    k0 = Uint32(key)
+    k1 = Uint32(0)
+
+    round_a = Uint32(PHILOX_ROUND_A)
+    round_b = Uint32(PHILOX_ROUND_B)
+    key_a = Uint32(PHILOX_KEY_A)
+    key_b = Uint32(PHILOX_KEY_B)
+
+    for _ in range(n_rounds):
+        hi_b, lo_b = mul_wide_u32(c2, round_b, loc=loc, ip=ip)
+        hi_a, lo_a = mul_wide_u32(c0, round_a, loc=loc, ip=ip)
+        c0 = hi_b ^ c1 ^ k0
+        c2 = hi_a ^ c3 ^ k1
+        c1 = lo_b
+        c3 = lo_a
+        k0 = k0 + key_a
+        k1 = k1 + key_b
+
+    return c0, c1, c2, c3
+
+
+@dsl_user_op
+def convert_f32_to_bf16_sr(
+    src_vec,
+    seed: Int32,
+    tid: Int32,
+    *,
+    loc=None,
+    ip=None,
+):
+    """Convert an MLIR FP32 vector to BF16 with stochastic rounding.
+
+    Processes elements in pairs using Philox PRNG for entropy and the hardware
+    cvt.rs.satfinite.bf16x2.f32 instruction.
+    """
+    src_vec_type = ir.VectorType(src_vec.type)
+    num_elems = src_vec_type.shape[0]
+    assert num_elems % 2 == 0, f"requires even number of elements, got {num_elems}"
+    num_pairs = num_elems // 2
+    assert num_pairs % 4 == 0, (
+        f"num_pairs must be divisible by 4 for stochastic rounding, got {num_pairs}"
+    )
+
+    dst_mlir_type = cutlass.BFloat16.mlir_type
+    dst_vec_type = ir.VectorType.get([num_elems], dst_mlir_type, loc=loc)
+
+    i32_vec_type = ir.VectorType.get([num_pairs], Int32.mlir_type, loc=loc)
+    i32_vec = llvm.mlir_undef(i32_vec_type, loc=loc, ip=ip)
+
+    for pair_idx in range(num_pairs):
+        lo_idx = pair_idx * 2
+        hi_idx = pair_idx * 2 + 1
+
+        src_lo = vector.extractelement(
+            src_vec,
+            position=arith.constant(Int32.mlir_type, lo_idx, loc=loc, ip=ip),
+            loc=loc,
+            ip=ip,
+        )
+        src_hi = vector.extractelement(
+            src_vec,
+            position=arith.constant(Int32.mlir_type, hi_idx, loc=loc, ip=ip),
+            loc=loc,
+            ip=ip,
+        )
+
+        group_idx = pair_idx // 4
+        intra_idx = pair_idx % 4
+        if intra_idx == 0:
+            counter = cutlass.Uint32(group_idx << 16) | cutlass.Uint32(tid)
+            rand_batch = philox(counter, cutlass.Uint32(seed))
+
+        entropy = rand_batch[intra_idx]
+        packed_i32 = cvt_f32x2_bf16x2_rs(Float32(src_lo), Float32(src_hi), entropy, loc=loc, ip=ip)
+
+        packed_i32_val = cutlass.Int32(packed_i32).ir_value(loc=loc, ip=ip)
+        i32_vec = vector.insertelement(
+            packed_i32_val,
+            i32_vec,
+            position=arith.constant(Int32.mlir_type, pair_idx, loc=loc, ip=ip),
+            loc=loc,
+            ip=ip,
+        )
+
+    dst_vec = llvm.bitcast(dst_vec_type, i32_vec, loc=loc, ip=ip)
+    return dst_vec
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/sm100_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/sm100_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f01fee6cc739af9ddbcc2eeddc810c9467579eb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/sm100_utils.py
@@ -0,0 +1,150 @@
+# Copyright (c) 2025, Tri Dao.
+
+from typing import Type, Union
+
+import cutlass.cute as cute
+import cutlass.utils.blackwell_helpers as sm100_utils_og
+from cutlass.cutlass_dsl import Numeric, dsl_user_op
+from cutlass.cute.nvgpu import OperandMajorMode
+
+
+@dsl_user_op
+def make_smem_layout_cpasync_a(
+    tiled_mma: cute.TiledMma,
+    mma_tiler_mnk: cute.Tile,
+    a_dtype: Type[Numeric],
+    num_stages: int,
+    *,
+    loc=None,
+    ip=None,
+) -> Union[cute.Layout, cute.ComposedLayout]:
+    """
+    :param tiled_mma: The tiled MMA used to partition tensor A
+    :type tiled_mma: cute.TiledMma
+    :param mma_tiler_mnk: The MMA tile shape
+    :type mma_tiler_mnk: cute.cute.Tile
+    :param a_dtype: The element type for tensor A
+    :type a_dtype: Type[Numeric]
+    :param num_stages: The number of pipeline stages for tensor A
+    :type num_stages: int
+
+    :return: SMEM layout for tensor A
+    :rtype: Union[cute.Layout, cute.ComposedLayout]
+    """
+
+    is_k_major = tiled_mma.op.a_major_mode == OperandMajorMode.K
+    a_smem_shape = tiled_mma.partition_shape_A(
+        cute.dice(mma_tiler_mnk, (1, None, 1), loc=loc, ip=ip)
+    )
+    a_smem_shape_mn_k = (
+        cute.size(a_smem_shape[0][0], loc=loc, ip=ip) * a_smem_shape[1],
+        cute.size(a_smem_shape[0][1], loc=loc, ip=ip) * a_smem_shape[2],
+    )
+    a_smem_layout_atom = sm100_utils_og.make_smem_layout_atom(
+        sm100_utils_og.get_smem_layout_atom_ab(
+            tiled_mma.op.a_major_mode,
+            a_dtype,
+            a_smem_shape_mn_k,
+            loc=loc,
+            ip=ip,
+        ),
+        a_dtype,
+        loc=loc,
+        ip=ip,
+    )
+    a_smem_layout_staged = cute.tile_to_shape(
+        a_smem_layout_atom,
+        cute.append(a_smem_shape_mn_k, num_stages, loc=loc, ip=ip),
+        order=((1, 0, 2) if not is_k_major else (0, 1, 2)),
+        loc=loc,
+        ip=ip,
+    )
+    return a_smem_layout_staged
+
+
+@dsl_user_op
+def make_smem_layout_atom_tma_gather_a(
+    tiled_mma: cute.TiledMma,
+    mma_tiler_mnk: cute.Tile,
+    a_dtype: Type[Numeric],
+    gather_size: int = 4,
+    *,
+    loc=None,
+    ip=None,
+) -> Union[cute.Layout, cute.ComposedLayout]:
+    """SMEM load layout atom for A with TMA gather4."""
+    is_k_major = tiled_mma.op.a_major_mode == OperandMajorMode.K
+    a_smem_shape = tiled_mma.partition_shape_A(
+        cute.dice(mma_tiler_mnk, (1, None, 1), loc=loc, ip=ip)
+    )
+    a_smem_shape_mn_k = (
+        cute.size(a_smem_shape[0][0], loc=loc, ip=ip) * a_smem_shape[1],
+        cute.size(a_smem_shape[0][1], loc=loc, ip=ip) * a_smem_shape[2],
+    )
+    # e,g., S<3, 4, 3> o  0 o (8, 64):(64, 1) for k_major
+    # e,g., S<3, 4, 3> o  0 o (64, 8):(1, 64) for m_major
+    a_smem_layout_atom = sm100_utils_og.make_smem_layout_atom(
+        sm100_utils_og.get_smem_layout_atom_ab(
+            tiled_mma.op.a_major_mode, a_dtype, a_smem_shape_mn_k, loc=loc, ip=ip
+        ),
+        a_dtype,
+        loc=loc,
+        ip=ip,
+    )
+    swizzle = a_smem_layout_atom.inner
+    smem_layout = a_smem_layout_atom.outer
+    if is_k_major:
+        # Replace M-dim with 4 for gather4, keep original strides
+        a_smem_layout_atom = cute.make_composed_layout(
+            swizzle,
+            0,
+            cute.make_layout(
+                (gather_size, smem_layout.shape[1]), stride=smem_layout.stride, loc=loc, ip=ip
+            ),
+            loc=loc,
+            ip=ip,
+        )
+    else:
+        # Replace K-dim with 4 for gather4, keep original strides
+        a_smem_layout_atom = cute.make_composed_layout(
+            swizzle,
+            0,
+            cute.make_layout(
+                (smem_layout.shape[0], gather_size), stride=smem_layout.stride, loc=loc, ip=ip
+            ),
+            loc=loc,
+            ip=ip,
+        )
+    return a_smem_layout_atom
+
+
+@dsl_user_op
+def make_smem_layout_tma_gather_a(
+    tiled_mma: cute.TiledMma,
+    mma_tiler_mnk: cute.Tile,
+    a_dtype: Type[Numeric],
+    num_stages: int,
+    *,
+    loc=None,
+    ip=None,
+) -> Union[cute.Layout, cute.ComposedLayout]:
+    """SMEM load layout for A with TMA gather4."""
+    is_k_major = tiled_mma.op.a_major_mode == OperandMajorMode.K
+    a_smem_shape = tiled_mma.partition_shape_A(
+        cute.dice(mma_tiler_mnk, (1, None, 1), loc=loc, ip=ip)
+    )
+    a_smem_shape_mn_k = (
+        cute.size(a_smem_shape[0][0], loc=loc, ip=ip) * a_smem_shape[1],
+        cute.size(a_smem_shape[0][1], loc=loc, ip=ip) * a_smem_shape[2],
+    )
+    a_smem_layout_atom = make_smem_layout_atom_tma_gather_a(
+        tiled_mma, mma_tiler_mnk, a_dtype, loc=loc, ip=ip
+    )
+    a_smem_layout_staged = cute.tile_to_shape(
+        a_smem_layout_atom,
+        cute.append(a_smem_shape_mn_k, num_stages, loc=loc, ip=ip),
+        order=(1, 0, 2) if not is_k_major else (0, 1, 2),
+        loc=loc,
+        ip=ip,
+    )
+    return a_smem_layout_staged
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/sm80_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/sm80_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0d3a226156cf45c1ecdb35f20413609551bac5a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/sm80_utils.py
@@ -0,0 +1,27 @@
+# Copyright (c) 2025-2026, Tri Dao.
+import cutlass.cute as cute
+from cutlass import Float32, const_expr
+
+
+def partition_fragment_ABC(
+    thr_mma: cute.ThrMma,
+    shape_mnk: cute.Shape,
+    sA: cute.Tensor,
+    sB: cute.Tensor,
+    swap_AB: bool = False,
+):
+    if const_expr(not swap_AB):
+        acc = cute.make_rmem_tensor(thr_mma.partition_shape_C(shape_mnk[:2]), Float32)
+        tCsA = thr_mma.partition_A(sA)
+        tCsB = thr_mma.partition_B(sB)
+        tCrA = thr_mma.make_fragment_A(tCsA[None, None, None, 0])
+        tCrB = thr_mma.make_fragment_B(tCsB[None, None, None, 0])
+    else:
+        acc = cute.make_rmem_tensor(
+            thr_mma.partition_shape_C((shape_mnk[1], shape_mnk[0])), Float32
+        )
+        tCsB = thr_mma.partition_A(sB)
+        tCsA = thr_mma.partition_B(sA)
+        tCrB = thr_mma.make_fragment_A(tCsB[None, None, None, 0])
+        tCrA = thr_mma.make_fragment_B(tCsA[None, None, None, 0])
+    return acc, tCsA, tCsB, tCrA, tCrB
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/sm90_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/sm90_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..25a6966a51f1733745132fb1cd0bccba5121a1b1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/sm90_utils.py
@@ -0,0 +1,193 @@
+# Copyright (c) 2025, Tri Dao.
+
+from typing import Literal, Type, Union, Optional
+
+import cutlass
+import cutlass.cute as cute
+import cutlass.utils.hopper_helpers as sm90_utils_og
+from cutlass.cute.nvgpu import warpgroup
+from cutlass.cutlass_dsl import Numeric, dsl_user_op
+from cutlass import Float32, Int32, Boolean, const_expr
+from cutlass.utils import LayoutEnum
+
+
+@dsl_user_op
+def make_smem_layout(
+    dtype: Type[Numeric],
+    layout: LayoutEnum,
+    tile: cute.Tile,
+    stage: Optional[int] = None,
+    major_mode_size: Optional[int] = None,
+    *,
+    loc=None,
+    ip=None,
+) -> Union[cute.Layout, cute.ComposedLayout]:
+    shape = cute.product_each(cute.shape(tile, loc=loc, ip=ip), loc=loc, ip=ip)
+    if const_expr(major_mode_size is None):
+        major_mode_size = shape[1] if layout.is_n_major_c() else shape[0]
+    smem_layout_atom = warpgroup.make_smem_layout_atom(
+        sm90_utils_og.get_smem_layout_atom(layout, dtype, major_mode_size),
+        dtype,
+    )
+    order = (1, 0, 2) if const_expr(layout.is_m_major_c()) else (0, 1, 2)
+    smem_layout_staged = cute.tile_to_shape(
+        smem_layout_atom,
+        cute.append(shape, stage) if const_expr(stage is not None) else shape,
+        order=order if const_expr(stage is not None) else order[:2],
+    )
+    return smem_layout_staged
+
+
+# For compatibility with blackwell_helpers.py
+make_smem_layout_epi = make_smem_layout
+
+
+def make_tiled_mma(
+    a_dtype: Type[Numeric],
+    a_major: Literal["K", "MN"],
+    b_major: Literal["K", "MN"],
+    tiler_n: int,
+    source: Literal["SS", "RS"] = "SS",
+    atom_layout_mnk: tuple = (1, 1, 1),
+    swap_AB: bool = False,
+    b_dtype: Optional[Type[Numeric]] = None,
+    acc_dtype: Type[Numeric] = Float32,
+) -> cute.TiledMma:
+    """`b_dtype` defaults to `a_dtype`; pass it for mixed-precision MMAs (e.g. fp8).
+    `acc_dtype` defaults to Float32."""
+    if b_dtype is None:
+        b_dtype = a_dtype
+    mode = {"K": cute.nvgpu.OperandMajorMode.K, "MN": cute.nvgpu.OperandMajorMode.MN}
+    a_mode, b_mode = mode[a_major], mode[b_major]
+    if swap_AB:
+        a_mode, b_mode = b_mode, a_mode
+    a_source = warpgroup.OperandSource.RMEM if source == "RS" else warpgroup.OperandSource.SMEM
+    return sm90_utils_og.make_trivial_tiled_mma(
+        a_dtype,
+        b_dtype,
+        a_mode,
+        b_mode,
+        acc_dtype,
+        atom_layout_mnk=atom_layout_mnk,
+        tiler_mn=(64, tiler_n),
+        a_source=a_source,
+    )
+
+
+@dsl_user_op
+def partition_for_epilogue(
+    cT: cute.Tensor,
+    epi_tile: cute.Tile,
+    tiled_copy: cute.TiledCopy,
+    tidx: Int32,
+    reference_src: bool,  # do register tensors reference the src or dst layout of the tiled copy
+    *,
+    loc=None,
+    ip=None,
+) -> cute.Tensor:
+    thr_copy = tiled_copy.get_slice(tidx)
+    cT_epi = cute.flat_divide(cT, epi_tile)
+    # (CPY, CPY_M, CPY_N, EPI_M, EPI_N)
+    if const_expr(reference_src):
+        return thr_copy.partition_S(cT_epi, loc=loc, ip=ip)
+    else:
+        return thr_copy.partition_D(cT_epi, loc=loc, ip=ip)
+
+
+@cute.jit
+def gemm(
+    tiled_mma: cute.TiledMma,
+    acc: cute.Tensor,
+    tCrA: cute.Tensor,
+    tCrB: cute.Tensor,
+    zero_init: cutlass.Constexpr[bool] = False,
+    wg_wait: cutlass.Constexpr[int] = 0,
+    # A_in_regs: cutlass.Constexpr[bool] = False,
+    swap_AB: cutlass.Constexpr[bool] = False,
+) -> None:
+    if const_expr(swap_AB):
+        gemm(tiled_mma, acc, tCrB, tCrA, zero_init=zero_init, wg_wait=wg_wait, swap_AB=False)
+    else:
+        warpgroup.fence()
+        # We make a new mma_atom since we'll be modifying its attribute (accumulate).
+        # Otherwise the compiler complains "operand #0 does not dominate this use"
+        mma_atom = cute.make_mma_atom(tiled_mma.op)
+        mma_atom.set(warpgroup.Field.ACCUMULATE, not zero_init)
+        for k in cutlass.range_constexpr(cute.size(tCrA.shape[2])):
+            cute.gemm(mma_atom, acc, tCrA[None, None, k], tCrB[None, None, k], acc)
+            mma_atom.set(warpgroup.Field.ACCUMULATE, True)
+        warpgroup.commit_group()
+        if const_expr(wg_wait >= 0):
+            warpgroup.wait_group(wg_wait)
+
+
+def gemm_zero_init(
+    tiled_mma: cute.TiledMma,
+    shape: cute.Shape,
+    tCrA: cute.Tensor,
+    tCrB: cute.Tensor,
+    A_idx: Optional[Int32] = None,
+    B_idx: Optional[Int32] = None,
+    wg_wait: int = -1,
+    swap_AB: bool = False,
+) -> cute.Tensor:
+    if const_expr(swap_AB):
+        return gemm_zero_init(
+            tiled_mma, shape[::-1], tCrB, tCrA, B_idx, A_idx, wg_wait, swap_AB=False
+        )
+    else:
+        acc = cute.make_rmem_tensor(tiled_mma.partition_shape_C(shape), Float32)
+        rA = tCrA if const_expr(A_idx is None) else tCrA[None, None, None, A_idx]
+        rB = tCrB if const_expr(B_idx is None) else tCrB[None, None, None, B_idx]
+        gemm(tiled_mma, acc, rA, rB, zero_init=True, wg_wait=wg_wait)
+        return acc
+
+
+def gemm_w_idx(
+    tiled_mma: cute.TiledMma,
+    acc: cute.Tensor,
+    tCrA: cute.Tensor,
+    tCrB: cute.Tensor,
+    zero_init: Boolean,
+    A_idx: Optional[Int32] = None,
+    B_idx: Optional[Int32] = None,
+    wg_wait: int = -1,
+    swap_AB: bool = False,
+) -> None:
+    if const_expr(swap_AB):
+        gemm_w_idx(tiled_mma, acc, tCrB, tCrA, zero_init, B_idx, A_idx, wg_wait, swap_AB=False)
+    else:
+        rA = tCrA if const_expr(A_idx is None) else tCrA[None, None, None, A_idx]
+        rB = tCrB if const_expr(B_idx is None) else tCrB[None, None, None, B_idx]
+        gemm(tiled_mma, acc, rA, rB, zero_init=zero_init, wg_wait=wg_wait)
+
+
+def partition_fragment_ABC(
+    thr_mma: cute.ThrMma,
+    shape_mnk: cute.Shape,
+    sA: Optional[cute.Tensor],
+    sB: Optional[cute.Tensor],
+    swap_AB: bool = False,
+):
+    is_rs = thr_mma.op.a_src == warpgroup.OperandSource.RMEM
+    if const_expr(not swap_AB):
+        acc = cute.make_rmem_tensor(thr_mma.partition_shape_C(shape_mnk[:2]), Float32)
+        if const_expr(not is_rs):
+            assert sA is not None
+            tCrA = thr_mma.make_fragment_A(thr_mma.partition_A(sA))
+        else:
+            tCrA = thr_mma.make_fragment_A(thr_mma.partition_shape_A((shape_mnk[0], shape_mnk[2])))
+        assert sB is not None
+        tCrB = thr_mma.make_fragment_B(thr_mma.partition_B(sB))
+    else:
+        acc = cute.make_rmem_tensor(
+            thr_mma.partition_shape_C((shape_mnk[1], shape_mnk[0])), Float32
+        )
+        if const_expr(not is_rs):
+            assert sB is not None
+            tCrB = thr_mma.make_fragment_A(thr_mma.partition_A(sB))
+        else:  # B in rmem
+            tCrB = thr_mma.make_fragment_A(thr_mma.partition_shape_A((shape_mnk[1], shape_mnk[2])))
+        assert sA is not None
+        tCrA = thr_mma.make_fragment_B(thr_mma.partition_B(sA))
+    return acc, tCrA, tCrB
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/tile_scheduler.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/tile_scheduler.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7124ddd1928ccf858b4078b8301d6b9f937b8e6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/tile_scheduler.py
@@ -0,0 +1,1140 @@
+# Copyright (c) 2025, Tri Dao.
+
+from typing import NamedTuple, Tuple, Optional
+from dataclasses import dataclass
+from enum import IntEnum
+
+import cutlass
+import cutlass.cute as cute
+from cutlass import Int32, Float32, Boolean, const_expr
+
+from . import utils
+from .fast_math import FastDivmod
+from .pipeline import PipelineStateWAdvance
+from .cute_dsl_utils import mlir_namedtuple
+
+
+class RasterOrderOption(IntEnum):
+    AlongM = 0
+    AlongN = 1
+    Heuristic = 2  # Pick AlongM if tiles_n > tiles_m, else AlongN
+
+
+class RasterOrder(IntEnum):
+    AlongM = 0
+    AlongN = 1
+
+
+class PersistenceMode(IntEnum):
+    NONE = 0
+    STATIC = 1
+    DYNAMIC = 2
+    CLC = 3
+
+
+@cute.jit
+def get_raster_order_from_option(
+    raster_order_option: RasterOrderOption, problem_shape_ncluster_mn: cute.Shape, group_size: Int32
+) -> RasterOrder:
+    raster_order = (
+        RasterOrder.AlongM
+        if raster_order_option == RasterOrderOption.AlongM
+        else RasterOrder.AlongN
+    )
+    if raster_order_option == RasterOrderOption.Heuristic:
+        problem_blocks_m = cute.round_up(problem_shape_ncluster_mn[0], group_size)
+        problem_blocks_n = cute.round_up(problem_shape_ncluster_mn[1], group_size)
+        raster_order = (
+            RasterOrder.AlongM if problem_blocks_n > problem_blocks_m else RasterOrder.AlongN
+        )
+    return raster_order
+
+
+# Grouping arguments together that should be passed to __call__
+@mlir_namedtuple
+class TileSchedulerOptions(NamedTuple):
+    max_active_clusters: Int32
+    raster_order: cutlass.Constexpr[RasterOrderOption] = RasterOrderOption.Heuristic
+    max_swizzle_size: Int32 = Int32(8)
+    tile_count_semaphore: Optional[cute.Pointer] = None
+    batch_idx_permute: Optional[cute.Tensor] = None
+
+
+@dataclass
+class TileSchedulerArguments:
+    problem_shape_ntile_mnl: cute.Shape
+    raster_order: cutlass.Constexpr[RasterOrderOption]
+    group_size: Int32
+    cluster_shape_mnk: cutlass.Constexpr[cute.Shape]
+    tile_count_semaphore: Optional[cute.Pointer] = None
+    batch_idx_permute: Optional[cute.Tensor] = None
+    persistence_mode: cutlass.Constexpr[PersistenceMode] = PersistenceMode.NONE
+
+
+class TileScheduler:
+    @dataclass
+    class Params:
+        problem_shape_ncluster_mnl: cute.Shape
+        raster_order: RasterOrder
+        num_clusters_per_problem_fdd: FastDivmod
+        num_groups_regular: Int32
+        group_size_fdd: FastDivmod
+        group_size_tail_fdd: FastDivmod
+        num_clusters_in_group_fdd: FastDivmod
+        tile_count_semaphore: Optional[cute.Pointer]
+        batch_idx_permute: Optional[cute.Tensor]
+        cluster_shape_mnk: cutlass.Constexpr[cute.Shape]
+        persistence_mode: cutlass.Constexpr[PersistenceMode]
+
+        @staticmethod
+        @cute.jit
+        def create(args: TileSchedulerArguments, *, loc=None, ip=None) -> "TileScheduler.Params":
+            problem_shape_ntile_mn = cute.select(args.problem_shape_ntile_mnl, mode=[0, 1])
+            problem_shape_ncluster_mn = (
+                cute.ceil_div(problem_shape_ntile_mn[0], args.cluster_shape_mnk[0]),
+                cute.ceil_div(problem_shape_ntile_mn[1], args.cluster_shape_mnk[1]),
+            )
+            problem_shape_ncluster_mnl = problem_shape_ncluster_mn + (
+                args.problem_shape_ntile_mnl[2],
+            )
+            num_clusters_per_problem = cute.size(problem_shape_ncluster_mn)
+            raster_order = get_raster_order_from_option(
+                args.raster_order, problem_shape_ncluster_mn, args.group_size
+            )
+            ncluster_fast = (
+                problem_shape_ncluster_mn[0]
+                if raster_order == RasterOrder.AlongM
+                else problem_shape_ncluster_mn[1]
+            )
+            ncluster_slow = (
+                problem_shape_ncluster_mn[1]
+                if raster_order == RasterOrder.AlongM
+                else problem_shape_ncluster_mn[0]
+            )
+            group_size = min(args.group_size, ncluster_fast)
+            group_size_tail = ncluster_fast % group_size
+            num_groups_regular = ncluster_fast // group_size
+            num_clusters_in_group = group_size * ncluster_slow
+            if const_expr(args.persistence_mode == PersistenceMode.DYNAMIC):
+                assert args.tile_count_semaphore is not None
+            return TileScheduler.Params(
+                problem_shape_ncluster_mnl,
+                raster_order,
+                FastDivmod(num_clusters_per_problem),
+                num_groups_regular,
+                FastDivmod(group_size),
+                # Don't divide by 0
+                FastDivmod(group_size_tail if group_size_tail > 0 else 1),
+                FastDivmod(num_clusters_in_group),
+                args.tile_count_semaphore
+                if const_expr(args.persistence_mode == PersistenceMode.DYNAMIC)
+                else None,
+                args.batch_idx_permute,
+                args.cluster_shape_mnk,
+                args.persistence_mode,
+            )
+
+    def __init__(
+        self,
+        current_work_idx: Int32,
+        num_tiles_executed: Int32,
+        current_batch_idx: Int32,
+        num_work_idx_before_cur_batch: Int32,
+        sched_smem: Optional[cute.Tensor],
+        scheduler_pipeline: Optional[cutlass.pipeline.PipelineAsync],
+        pipeline_state: PipelineStateWAdvance,
+        params: Params,
+        *,
+        loc=None,
+        ip=None,
+    ):
+        self._current_work_idx = current_work_idx
+        self.num_tiles_executed = num_tiles_executed
+        self._current_batch_idx = current_batch_idx
+        self._num_work_idx_before_cur_batch = num_work_idx_before_cur_batch
+        self._sched_smem = sched_smem
+        self._scheduler_pipeline = scheduler_pipeline
+        self._pipeline_state = pipeline_state
+        self.params = params
+        self._loc = loc
+        self._ip = ip
+
+    @staticmethod
+    def to_underlying_arguments(args: TileSchedulerArguments, *, loc=None, ip=None) -> Params:
+        return TileScheduler.Params.create(args, loc=loc, ip=ip)
+
+    @staticmethod
+    @cute.jit
+    def _init_clc_mbarrier(sched_smem: Optional[cute.Tensor] = None, *, loc=None, ip=None) -> None:
+        # We use 4 ints to store (pid_m, pid_n, batch_idx, is_valid),
+        # another 4 ints to store clc response, and 2 ints to store the mbarrier for CLC
+        # Since only the scheduler warp will touch the mbarrier (we don't use multicast when trying
+        # to cancel workID), we only need the scheduler warp to initialize and sync.
+        # If we use multicast when canceling workID, we would need all threads to sync.
+        assert cute.size(sched_smem, mode=[0]) >= 12
+        clc_mbar_ptr = sched_smem[None, 0].iterator + 8
+        with cute.arch.elect_one():
+            cute.arch.mbarrier_init(clc_mbar_ptr, 1)
+        cute.arch.mbarrier_init_fence()
+        cute.arch.sync_warp()
+
+    @staticmethod
+    @cute.jit
+    def _cluster_idx_to_work_idx_batch(
+        params: Params, cluster_idx: Tuple[Int32, Int32, Int32], *, loc=None, ip=None
+    ) -> Tuple[Int32, Optional[Int32]]:
+        if const_expr(params.persistence_mode in [PersistenceMode.NONE, PersistenceMode.CLC]):
+            current_work_idx = Int32(cluster_idx[0])
+            batch_idx = Int32(cluster_idx[2])
+            return current_work_idx, batch_idx
+        else:
+            current_work_idx = Int32(cluster_idx[2])
+            batch_idx = None
+            return current_work_idx, batch_idx
+
+    @staticmethod
+    @cute.jit
+    def create(
+        params: Params,
+        sched_smem: Optional[cute.Tensor] = None,
+        scheduler_pipeline: Optional[cutlass.pipeline.PipelineAsync] = None,
+        is_scheduler_warp: bool | Boolean = False,
+        *,
+        loc=None,
+        ip=None,
+    ) -> "TileScheduler":
+        """is_scheduler_warp should only be true for one warp in the whole cluster"""
+        if const_expr(cute.size(params.cluster_shape_mnk, loc=loc, ip=ip) == 1):
+            cluster_idx = cute.arch.block_idx()
+        else:
+            cluster_idx = cute.arch.cluster_idx()
+        current_work_idx, _ = TileScheduler._cluster_idx_to_work_idx_batch(
+            params, cluster_idx, loc=loc, ip=ip
+        )
+        stages = 0
+        if const_expr(
+            params.persistence_mode
+            in [PersistenceMode.STATIC, PersistenceMode.DYNAMIC, PersistenceMode.CLC]
+        ):
+            assert sched_smem is not None
+            assert scheduler_pipeline is not None
+            stages = const_expr(cute.size(sched_smem, mode=[1]))
+        if const_expr(params.persistence_mode == PersistenceMode.CLC):
+            if is_scheduler_warp:
+                TileScheduler._init_clc_mbarrier(sched_smem, loc=loc, ip=ip)
+        return TileScheduler(
+            current_work_idx,
+            Int32(0),  # num_tiles_executed
+            Int32(0),  # current_batch_idx
+            Int32(0),  # num_work_idx_before_cur_batch
+            sched_smem,
+            scheduler_pipeline,
+            PipelineStateWAdvance(stages, Int32(0), Int32(0), Int32(0)),
+            params,
+            loc=loc,
+            ip=ip,
+        )
+
+    # called by host
+    @staticmethod
+    def get_grid_shape(
+        params: Params,
+        max_active_clusters: Int32,
+        *,
+        loc=None,
+        ip=None,
+    ) -> Tuple[Int32, Int32, Int32]:
+        if const_expr(params.persistence_mode in [PersistenceMode.NONE, PersistenceMode.CLC]):
+            return (
+                params.cluster_shape_mnk[0] * cute.size(params.problem_shape_ncluster_mnl[:2]),
+                params.cluster_shape_mnk[1],
+                params.cluster_shape_mnk[2] * params.problem_shape_ncluster_mnl[2],
+            )
+        else:
+            num_ctas_in_problem = cute.size(
+                params.problem_shape_ncluster_mnl, loc=loc, ip=ip
+            ) * cute.size(params.cluster_shape_mnk)
+            num_ctas_per_cluster = cute.size(params.cluster_shape_mnk, loc=loc, ip=ip)
+            # Total ctas that can run in one wave
+            num_ctas_per_wave = max_active_clusters * num_ctas_per_cluster
+            num_persistent_ctas = cutlass.min(num_ctas_in_problem, num_ctas_per_wave)
+            num_persistent_clusters = num_persistent_ctas // num_ctas_per_cluster
+            return (
+                params.cluster_shape_mnk[0],
+                params.cluster_shape_mnk[1],
+                params.cluster_shape_mnk[2] * num_persistent_clusters,
+            )
+
+    @cute.jit
+    def _swizzle_cta(
+        self, cluster_id_in_problem: Int32, *, loc=None, ip=None
+    ) -> Tuple[Int32, Int32]:
+        # CTA Swizzle to promote L2 data reuse
+        params = self.params
+        group_id, id_in_group = divmod(cluster_id_in_problem, params.num_clusters_in_group_fdd)
+        cid_fast_in_group, cid_slow = Int32(0), Int32(0)
+        if group_id < params.num_groups_regular:
+            cid_slow, cid_fast_in_group = divmod(id_in_group, params.group_size_fdd)
+            # if cid_slow % 2 == 1:  # inner serpentine
+            #     cid_fast_in_group = params.group_size_fdd.divisor - 1 - cid_fast_in_group
+        else:  # tail part
+            cid_slow, cid_fast_in_group = divmod(id_in_group, params.group_size_tail_fdd)
+            # if cid_slow % 2 == 1:  # inner serpentine
+            #     cid_fast_in_group = params.group_size_tail_fdd.divisor - 1 - cid_fast_in_group
+        if group_id % 2 == 1:  # serpentine order
+            ncluster_slow = (
+                params.problem_shape_ncluster_mnl[1]
+                if params.raster_order == RasterOrder.AlongM
+                else params.problem_shape_ncluster_mnl[0]
+            )
+            cid_slow = ncluster_slow - 1 - cid_slow
+        cid_fast = group_id * params.group_size_fdd.divisor + cid_fast_in_group
+        cid_m, cid_n = cid_fast, cid_slow
+        if params.raster_order == RasterOrder.AlongN:
+            cid_m, cid_n = cid_slow, cid_fast
+        return cid_m, cid_n
+
+    @cute.jit
+    def _cluster_id_to_cta_id(
+        self, cid_m: Int32, cid_n: Int32, *, block_zero_only: bool = False, loc=None, ip=None
+    ) -> Tuple[Int32, Int32]:
+        if const_expr(
+            block_zero_only or cute.size(self.params.cluster_shape_mnk, loc=loc, ip=ip) == 1
+        ):
+            bidx_in_cluster = (Int32(0), Int32(0))
+        else:
+            # Get the pid from cluster id
+            bidx_in_cluster = cute.arch.block_in_cluster_idx()
+        pid_m = cid_m * self.params.cluster_shape_mnk[0] + bidx_in_cluster[0]
+        pid_n = cid_n * self.params.cluster_shape_mnk[1] + bidx_in_cluster[1]
+        return pid_m, pid_n
+
+    @cute.jit
+    def _delinearize_work_idx(
+        self,
+        work_idx: Int32,
+        bidz: Optional[Int32] = None,
+        is_valid: Optional[Boolean] = None,
+        *,
+        block_zero_only: bool = False,
+        loc=None,
+        ip=None,
+    ) -> cutlass.utils.WorkTileInfo:
+        params = self.params
+        if const_expr(is_valid is None):
+            if const_expr(params.persistence_mode == PersistenceMode.NONE):
+                is_valid = self.num_tiles_executed == 0
+            elif const_expr(params.persistence_mode == PersistenceMode.CLC):
+                is_valid = work_idx < cute.size(params.problem_shape_ncluster_mnl[:2])
+            else:
+                is_valid = work_idx < cute.size(params.problem_shape_ncluster_mnl)
+        pid_m, pid_n, batch_idx = Int32(0), Int32(0), Int32(0)
+        if is_valid:
+            if const_expr(params.persistence_mode in [PersistenceMode.NONE, PersistenceMode.CLC]):
+                cluster_id_in_problem = work_idx
+                bidz_ = (
+                    cute.arch.block_idx()[2]
+                    if const_expr(cute.size(params.cluster_shape_mnk, loc=loc, ip=ip) == 1)
+                    else cute.arch.cluster_idx()[2]
+                )
+            else:
+                bidz_, cluster_id_in_problem = divmod(work_idx, params.num_clusters_per_problem_fdd)
+            if const_expr(bidz is not None):
+                bidz_ = bidz
+            cid_m, cid_n = self._swizzle_cta(cluster_id_in_problem, loc=loc, ip=ip)
+            pid_m, pid_n = self._cluster_id_to_cta_id(
+                cid_m, cid_n, block_zero_only=block_zero_only, loc=loc, ip=ip
+            )
+            batch_idx = (
+                bidz_
+                if const_expr(params.batch_idx_permute is None)
+                else params.batch_idx_permute[bidz_]
+            )
+        tile_coord_mnkl = (pid_m, pid_n, None, batch_idx)
+        return cutlass.utils.WorkTileInfo(tile_coord_mnkl, is_valid)
+
+    @cute.jit
+    def get_current_work(self, *, loc=None, ip=None) -> cutlass.utils.WorkTileInfo:
+        params = self.params
+        pid_m, pid_n, batch_idx, is_valid = Int32(0), Int32(0), Int32(0), Boolean(False)
+        if const_expr(params.persistence_mode == PersistenceMode.NONE):
+            pass
+        # elif const_expr(params.persistence_mode == PersistenceMode.STATIC):
+        #     return self._delinearize_work_idx(loc=loc, ip=ip)
+        else:
+            self._scheduler_pipeline.consumer_wait(self._pipeline_state)
+            pid_m, pid_n, batch_idx, is_valid_i32 = [
+                self._sched_smem[i, self._pipeline_state.index] for i in range(4)
+            ]
+            # Need this fence since the STAS from the producer is using the async proxy.
+            # Without this, we get race condition / deadlock.
+            if const_expr(cute.size(params.cluster_shape_mnk) > 1):
+                cute.arch.fence_view_async_shared()
+            cute.arch.sync_warp()
+            with cute.arch.elect_one():
+                self._scheduler_pipeline.consumer_release(self._pipeline_state)
+            self._pipeline_state.advance()
+            is_valid = Boolean(is_valid_i32)
+        tile_coord_mnkl = (pid_m, pid_n, None, batch_idx)
+        return cutlass.utils.WorkTileInfo(tile_coord_mnkl, Boolean(is_valid))
+
+    # @cute.jit
+    def initial_work_tile_info(self, *, loc=None, ip=None) -> cutlass.utils.WorkTileInfo:
+        return self._delinearize_work_idx(self._current_work_idx, loc=loc, ip=ip)
+        # if is_scheduler_warp:
+        # work_tile_info = self._delinearize_work_idx(block_zero_only=True, loc=loc, ip=ip)
+        # self.write_work_tile_to_smem(work_tile_info, loc=loc, ip=ip)
+        # self.write_work_tile_to_smem(self._delinearize_work_idx(block_zero_only=True, loc=loc, ip=ip), loc=loc, ip=ip)
+
+    @cute.jit
+    def _fetch_next_work_idx(self, *, loc=None, ip=None) -> Int32 | Tuple[Int32, Int32, Boolean]:
+        """should only be called by the scheduler warp"""
+        params = self.params
+        num_persistent_clusters = (
+            cute.arch.grid_dim()[2]
+            if const_expr(cute.size(params.cluster_shape_mnk, loc=loc, ip=ip) == 1)
+            else cute.arch.cluster_dim()[2]
+        )
+        if const_expr(params.persistence_mode == PersistenceMode.STATIC):
+            return self._current_work_idx + num_persistent_clusters
+            # Serpentine: alternate wave direction for a bit better load balancing
+            # But currently seems a tiny bit slower, disabling for now.
+            # c = Int32(cute.arch.cluster_idx()[2])
+            # next_work_idx = self._current_work_idx + 2 * c + 1
+            # if self.num_tiles_executed % 2 == 1:
+            #     next_work_idx = self._current_work_idx + 2 * (num_persistent_clusters - 1 - c) + 1
+            # return next_work_idx
+        elif const_expr(params.persistence_mode == PersistenceMode.DYNAMIC):
+            next_work_linear_idx = Int32(0)
+            if cute.arch.lane_idx() == 0:
+                # If varlen_m, problem_shape_ncluster_mnl[0] is None, so we use atomic_add
+                # instead of atomic_inc, and at the end of the kernel must reset the semaphore to 0.
+                #                 # cute.printf("before atomicadd, tidx = {}, bidz = {}, idx = {}", cute.arch.thread_idx()[0], cute.arch.block_idx()[2], current_work_idx)
+                if const_expr(params.problem_shape_ncluster_mnl[0] is not None):
+                    next_work_linear_idx = num_persistent_clusters + utils.atomic_inc_i32(
+                        cute.size(params.problem_shape_ncluster_mnl) - 1,
+                        params.tile_count_semaphore,
+                    )
+                else:  # varlen_m
+                    next_work_linear_idx = num_persistent_clusters + utils.atomic_add_i32(
+                        1, params.tile_count_semaphore
+                    )
+                # cute.printf("after atomicadd, tidx = {}, bidz = {}, idx = {}", cute.arch.thread_idx()[0], cute.arch.block_idx()[2], current_work_idx)
+            return cute.arch.shuffle_sync(next_work_linear_idx, 0)
+        elif const_expr(params.persistence_mode == PersistenceMode.CLC):
+            clc_response_ptr = self._sched_smem[None, self._pipeline_state.index].iterator + 4
+            mbarrier_addr = self._sched_smem[None, 0].iterator + 8
+            cute.arch.sync_warp()
+            with cute.arch.elect_one():
+                cute.arch.mbarrier_arrive_and_expect_tx(mbarrier_addr, 16, loc=loc, ip=ip)
+                utils.issue_clc_query_nomulticast(mbarrier_addr, clc_response_ptr, loc=loc, ip=ip)
+            cute.arch.sync_warp()
+            cute.arch.mbarrier_wait(mbarrier_addr, self._pipeline_state.phase, loc=loc, ip=ip)
+            bidx, bidy, bidz, valid = cute.arch.clc_response(clc_response_ptr, loc=loc, ip=ip)
+            cute.arch.fence_view_async_shared()
+            cluster_idx = (
+                bidx // params.cluster_shape_mnk[0],
+                bidy // params.cluster_shape_mnk[1],
+                bidz // params.cluster_shape_mnk[2],
+            )
+            cluster_idx, batch_idx = type(self)._cluster_idx_to_work_idx_batch(
+                params, cluster_idx, loc=loc, ip=ip
+            )
+            return cluster_idx, batch_idx, Boolean(valid)
+        else:
+            return Int32(0)
+
+    @cute.jit
+    def write_work_tile_to_smem(
+        self, work_tile_info: cutlass.utils.WorkTileInfo, *, loc=None, ip=None
+    ):
+        params = self.params
+        if const_expr(self._sched_smem is not None):
+            # producer phase is always consumer_phase ^ 1
+            pipeline_state_producer = PipelineStateWAdvance(
+                self._pipeline_state.stages,
+                self._pipeline_state.count,
+                self._pipeline_state.index,
+                self._pipeline_state.phase ^ 1,
+            )
+            self._scheduler_pipeline.producer_acquire(pipeline_state_producer)
+            sched_data = [
+                work_tile_info.tile_idx[0],
+                work_tile_info.tile_idx[1],
+                work_tile_info.tile_idx[3],
+                Int32(work_tile_info.is_valid_tile),
+            ]
+            lane_idx = cute.arch.lane_idx()
+            if lane_idx < cute.size(params.cluster_shape_mnk):
+                # cute.printf("Producer pid_m = {}, pid_n = {}, batch_idx = {}, is_valid = {}, after empty wait, idx = {}", sched_data[0], sched_data[1], sched_data[2], sched_data[3], self._current_work_idx)
+                pipeline_idx = self._pipeline_state.index
+                if const_expr(cute.size(params.cluster_shape_mnk) == 1):
+                    for i in cutlass.range_constexpr(4):
+                        self._sched_smem[i, pipeline_idx] = sched_data[i]
+                    self._scheduler_pipeline.producer_commit(self._pipeline_state)
+                else:
+                    peer_cta_rank_in_cluster = lane_idx
+                    # Here we assume that the block idx in cluster is linearized such that
+                    # x is the fastest moving direction, followed by y, then z.
+                    bidx_in_cluster = peer_cta_rank_in_cluster % params.cluster_shape_mnk[0]
+                    bidy_in_cluster = (
+                        peer_cta_rank_in_cluster // params.cluster_shape_mnk[0]
+                    ) % params.cluster_shape_mnk[1]
+                    mbar_ptr = self._scheduler_pipeline.producer_get_barrier(self._pipeline_state)
+                    cute.arch.mbarrier_arrive_and_expect_tx(mbar_ptr, 16, peer_cta_rank_in_cluster)
+                    utils.store_shared_remote_x4(
+                        sched_data[0] + bidx_in_cluster,
+                        sched_data[1] + bidy_in_cluster,
+                        sched_data[2],
+                        sched_data[3],
+                        smem_ptr=self._sched_smem[None, pipeline_idx].iterator,
+                        mbar_ptr=mbar_ptr,
+                        peer_cta_rank_in_cluster=peer_cta_rank_in_cluster,
+                    )
+
+    @cute.jit
+    def advance_to_next_work(
+        self,
+        is_scheduler_warp: bool | Boolean = False,
+        *,
+        advance_count: int = 1,
+        loc=None,
+        ip=None,
+    ):
+        """is_scheduler_warp should only be true for one warp in the whole cluster.
+        Moreover, we assume that only block zero in the cluster is calling this function.
+        If calling with is_scheduler_warp = True, advance_count must be 1.
+        """
+        params = self.params
+        self.num_tiles_executed += Int32(advance_count)
+        if const_expr(self._pipeline_state is not None and advance_count > 1):
+            self._pipeline_state.advance_iters(advance_count - 1)
+        if const_expr(params.persistence_mode in [PersistenceMode.STATIC, PersistenceMode.DYNAMIC]):
+            # We assume here that advance_count is 1 for scheduler_warp
+            if is_scheduler_warp:
+                self._current_work_idx = self._fetch_next_work_idx(loc=loc, ip=ip)
+                work_tile_info = self._delinearize_work_idx(
+                    self._current_work_idx, block_zero_only=True, loc=loc, ip=ip
+                )
+                self.write_work_tile_to_smem(work_tile_info, loc=loc, ip=ip)
+        elif const_expr(params.persistence_mode == PersistenceMode.CLC):
+            # We assume here that advance_count is 1 for scheduler_warp
+            if is_scheduler_warp:
+                self._current_work_idx, batch, is_valid = self._fetch_next_work_idx(loc=loc, ip=ip)
+                work_tile_info = self._delinearize_work_idx(
+                    self._current_work_idx, batch, is_valid, block_zero_only=True, loc=loc, ip=ip
+                )
+                self.write_work_tile_to_smem(work_tile_info, loc=loc, ip=ip)
+
+    def producer_tail(self):
+        if const_expr(self._scheduler_pipeline is not None):
+            pipeline_state_producer = PipelineStateWAdvance(
+                self._pipeline_state.stages,
+                self._pipeline_state.count,
+                self._pipeline_state.index,
+                self._pipeline_state.phase ^ 1,
+            )
+            self._scheduler_pipeline.producer_tail(pipeline_state_producer)
+
+    def __extract_mlir_values__(self):
+        values, self._values_pos = [], []
+        for obj in [
+            self._current_work_idx,
+            self.num_tiles_executed,
+            self._current_batch_idx,
+            self._num_work_idx_before_cur_batch,
+            self._sched_smem,
+            self._scheduler_pipeline,
+            self._pipeline_state,
+            self.params,
+        ]:
+            obj_values = cutlass.extract_mlir_values(obj)
+            values += obj_values
+            self._values_pos.append(len(obj_values))
+        return values
+
+    def __new_from_mlir_values__(self, values):
+        obj_list = []
+        for obj, n_items in zip(
+            [
+                self._current_work_idx,
+                self.num_tiles_executed,
+                self._current_batch_idx,
+                self._num_work_idx_before_cur_batch,
+                self._sched_smem,
+                self._scheduler_pipeline,
+                self._pipeline_state,
+                self.params,
+            ],
+            self._values_pos,
+        ):
+            obj_list.append(cutlass.new_from_mlir_values(obj, values[:n_items]))
+            values = values[n_items:]
+        return self.__class__(*(tuple(obj_list)), loc=self._loc)
+
+
+@cute.jit
+def triangular_idx_to_coord(idx: Int32) -> Tuple[Int32, Int32]:
+    """
+    Convert a triangular index to 2D coordinates.
+    This is used to convert the linear index to 2D coordinates for triangular matrices.
+    """
+    row = utils.ceil((utils.sqrt(2 * idx + 2.25) - 0.5)) - 1
+    col = idx - (row * (row + 1)) // 2
+    return row, col
+
+
+class TriangularTileScheduler(TileScheduler):
+    """We assume the tile size per cluster is square (e.g., 128 x 256 per CTA, with cluster 2 x 1)"""
+
+    @dataclass
+    class Params:
+        problem_shape_ncluster_mnl: cute.Shape
+        num_clusters_per_problem_fdd: FastDivmod
+        group_size_inv_f32: Float32
+        num_groups_regular: Int32
+        group_size_fdd: FastDivmod
+        group_size_tail_fdd: FastDivmod
+        group_size_mul_group_size_fdd: FastDivmod
+        group_size_tail_mul_group_size_fdd: FastDivmod
+        tile_count_semaphore: Optional[cute.Pointer]
+        cluster_shape_mnk: cutlass.Constexpr[cute.Shape]
+        persistence_mode: cutlass.Constexpr[PersistenceMode]
+
+        @staticmethod
+        @cute.jit
+        def create(
+            args: TileSchedulerArguments, *, loc=None, ip=None
+        ) -> "TriangularTileScheduler.Params":
+            assert args.cluster_shape_mnk[2] == 1
+            problem_shape_ntile_mn = cute.select(args.problem_shape_ntile_mnl, mode=[0, 1])
+            problem_shape_ncluster_mn = (
+                cute.ceil_div(problem_shape_ntile_mn[0], args.cluster_shape_mnk[0]),
+                cute.ceil_div(problem_shape_ntile_mn[1], args.cluster_shape_mnk[1]),
+            )
+            problem_shape_ncluster_mnl = problem_shape_ncluster_mn + (
+                args.problem_shape_ntile_mnl[2],
+            )
+            cluster_m = problem_shape_ncluster_mn[0]
+            # Assume that each cluster is responsible for a square tile
+            num_clusters_per_problem = cluster_m * (cluster_m + 1) // 2
+            group_size = min(args.group_size, cluster_m)
+            group_size_tail = cluster_m % group_size
+            num_groups_regular = cluster_m // group_size
+            if const_expr(args.persistence_mode == PersistenceMode.DYNAMIC):
+                assert args.tile_count_semaphore is not None
+            return TriangularTileScheduler.Params(
+                problem_shape_ncluster_mnl,
+                FastDivmod(num_clusters_per_problem),
+                Float32(1.0 / group_size),
+                num_groups_regular,
+                FastDivmod(group_size),
+                # Don't divide by 0
+                FastDivmod(group_size_tail if group_size_tail > 0 else 1),
+                FastDivmod(group_size * group_size),
+                FastDivmod((group_size_tail if group_size_tail > 0 else 1) * group_size),
+                args.tile_count_semaphore
+                if const_expr(args.persistence_mode == PersistenceMode.DYNAMIC)
+                else None,
+                args.cluster_shape_mnk,
+                args.persistence_mode,
+            )
+
+    @staticmethod
+    def to_underlying_arguments(args: TileSchedulerArguments, *, loc=None, ip=None) -> Params:
+        return TriangularTileScheduler.Params.create(args, loc=loc, ip=ip)
+
+    @staticmethod
+    @cute.jit
+    def create(
+        params: Params,
+        sched_smem: Optional[cute.Tensor] = None,
+        scheduler_pipeline: Optional[cutlass.pipeline.PipelineAsync] = None,
+        is_scheduler_warp: bool | Boolean = False,
+        *,
+        loc=None,
+        ip=None,
+    ) -> "TriangularTileScheduler":
+        if const_expr(cute.size(params.cluster_shape_mnk, loc=loc, ip=ip) == 1):
+            cluster_idx = cute.arch.block_idx()
+        else:
+            cluster_idx = cute.arch.cluster_idx()
+        current_work_idx, _ = TileScheduler._cluster_idx_to_work_idx_batch(
+            params, cluster_idx, loc=loc, ip=ip
+        )
+        stages = 0
+        if const_expr(
+            params.persistence_mode
+            in [PersistenceMode.STATIC, PersistenceMode.DYNAMIC, PersistenceMode.CLC]
+        ):
+            assert sched_smem is not None
+            assert scheduler_pipeline is not None
+            stages = const_expr(cute.size(sched_smem, mode=[1]))
+        if const_expr(params.persistence_mode == PersistenceMode.CLC):
+            if is_scheduler_warp:
+                TileScheduler._init_clc_mbarrier(sched_smem, loc=loc, ip=ip)
+        return TriangularTileScheduler(
+            current_work_idx,
+            Int32(0),  # num_tiles_executed
+            Int32(0),  # current_batch_idx
+            Int32(0),  # num_work_idx_before_cur_batch
+            sched_smem,
+            scheduler_pipeline,
+            PipelineStateWAdvance(stages, Int32(0), Int32(0), Int32(0)),
+            params,
+            loc=loc,
+            ip=ip,
+        )
+
+    # called by host
+    @staticmethod
+    def get_grid_shape(
+        params: Params,
+        max_active_clusters: Int32,
+        *,
+        loc=None,
+        ip=None,
+    ) -> Tuple[Int32, Int32, Int32]:
+        clusters = (params.num_clusters_per_problem_fdd.divisor, 1)
+        num_ctas_mnl = (
+            clusters[0] * params.cluster_shape_mnk[0],
+            clusters[1] * params.cluster_shape_mnk[1],
+            params.cluster_shape_mnk[2] * params.problem_shape_ncluster_mnl[2],
+        )
+        if const_expr(params.persistence_mode in [PersistenceMode.NONE, PersistenceMode.CLC]):
+            return num_ctas_mnl
+        else:
+            num_ctas_in_problem = cute.size(num_ctas_mnl, loc=loc, ip=ip)
+            num_ctas_per_cluster = cute.size(params.cluster_shape_mnk, loc=loc, ip=ip)
+            # Total ctas that can run in one wave
+            num_ctas_per_wave = max_active_clusters * num_ctas_per_cluster
+            num_persistent_ctas = cutlass.min(num_ctas_in_problem, num_ctas_per_wave)
+            num_persistent_clusters = num_persistent_ctas // num_ctas_per_cluster
+            return (
+                params.cluster_shape_mnk[0],
+                params.cluster_shape_mnk[1],
+                params.cluster_shape_mnk[2] * num_persistent_clusters,
+            )
+
+    @cute.jit
+    def _swizzle_cta(
+        self, cluster_id_in_problem: Int32, *, loc=None, ip=None
+    ) -> Tuple[Int32, Int32]:
+        # CTA Swizzle to promote L2 data reuse
+        params = self.params
+        group_size = params.group_size_fdd.divisor
+        group_id = (
+            utils.ceil(
+                (utils.sqrt(2 * cluster_id_in_problem + 2.25) - 0.5) * params.group_size_inv_f32
+            )
+            - 1
+        )
+        cid_m_start = group_id * group_size
+        id_in_group = cluster_id_in_problem - (cid_m_start * (cid_m_start + 1)) // 2
+        group_size_actual = (
+            group_size
+            if group_id < params.num_groups_regular
+            else params.group_size_tail_fdd.divisor
+        )
+        group_col, group_remainder = Int32(0), Int32(0)
+        if group_id < params.num_groups_regular:
+            group_col, group_remainder = divmod(id_in_group, params.group_size_mul_group_size_fdd)
+        else:  # tail part
+            group_col, group_remainder = divmod(
+                id_in_group, params.group_size_tail_mul_group_size_fdd
+            )
+        cid_m_in_group, cid_n_in_group = Int32(0), Int32(0)
+        if id_in_group >= group_size_actual * group_size * group_id:  # triangular tail
+            cid_m_in_group, cid_n_in_group = triangular_idx_to_coord(group_remainder)
+        else:
+            if group_id < params.num_groups_regular:
+                cid_n_in_group, cid_m_in_group = divmod(group_remainder, params.group_size_fdd)
+            else:
+                cid_n_in_group, cid_m_in_group = divmod(group_remainder, params.group_size_tail_fdd)
+        cid_m = cid_m_start + cid_m_in_group
+        cid_n = group_col * group_size + cid_n_in_group
+        return cid_m, cid_n
+
+    @cute.jit
+    def _delinearize_work_idx(
+        self,
+        work_idx: Int32,
+        bidz: Optional[Int32] = None,
+        is_valid: Optional[Boolean] = None,
+        *,
+        block_zero_only: bool = False,
+        loc=None,
+        ip=None,
+    ) -> cutlass.utils.WorkTileInfo:
+        params = self.params
+        if const_expr(is_valid is None):
+            if const_expr(params.persistence_mode == PersistenceMode.NONE):
+                is_valid = self.num_tiles_executed == 0
+            else:
+                is_valid = (
+                    work_idx
+                    < params.num_clusters_per_problem_fdd.divisor
+                    * params.problem_shape_ncluster_mnl[2]
+                )
+        pid_m, pid_n, batch_idx = Int32(0), Int32(0), Int32(0)
+        if is_valid:
+            if const_expr(params.persistence_mode in [PersistenceMode.NONE, PersistenceMode.CLC]):
+                cluster_id_in_problem = work_idx
+                bidz_ = (
+                    cute.arch.block_idx()[2]
+                    if const_expr(cute.size(params.cluster_shape_mnk, loc=loc, ip=ip) == 1)
+                    else cute.arch.cluster_idx()[2]
+                )
+            else:
+                bidz_, cluster_id_in_problem = divmod(work_idx, params.num_clusters_per_problem_fdd)
+                cluster_id_in_problem = Int32(cluster_id_in_problem)  # divmod returns IntValue
+            if const_expr(bidz is not None):
+                bidz_ = bidz
+            cid_m, cid_n = self._swizzle_cta(cluster_id_in_problem, loc=loc, ip=ip)
+            pid_m, pid_n = self._cluster_id_to_cta_id(
+                cid_m, cid_n, block_zero_only=block_zero_only, loc=loc, ip=ip
+            )
+            batch_idx = bidz_
+        tile_coord_mnkl = (pid_m, pid_n, None, batch_idx)
+        # tidx, _, _ = cute.arch.thread_idx()
+        # if tidx == 0:
+        #     cute.printf("bidx = {}, bidy = {}, group_id = {}, id_in_group = {}, group_size_actual = {}, group_col = {}, group_remainder = {}, cid_n_in_group = {}, cid_m_in_group = {}, cid_m = {}, cid_n = {}, is_valid = {}",
+        #                 bidx, bidy, group_id, id_in_group, group_size_actual, group_col, group_remainder, cid_n_in_group, cid_m_in_group, cid_m, cid_n, is_valid)
+        return cutlass.utils.WorkTileInfo(tile_coord_mnkl, is_valid)
+
+
+@dataclass
+class VarlenMTileSchedulerArguments:
+    problem_shape_ntile_mnl: cute.Shape
+    total_m: Int32
+    cu_seqlens_m: cute.Tensor
+    raster_order: cutlass.Constexpr[RasterOrderOption]
+    group_size: Int32
+    tile_shape_mn: cutlass.Constexpr[cute.Shape]
+    cluster_shape_mnk: cutlass.Constexpr[cute.Shape]
+    tile_count_semaphore: Optional[cute.Pointer] = None
+    persistence_mode: cutlass.Constexpr[PersistenceMode] = PersistenceMode.NONE
+
+
+class VarlenMTileScheduler(TileScheduler):
+    @dataclass
+    class Params:
+        problem_shape_ncluster_mnl: cute.Shape
+        total_m: Int32
+        cu_seqlens_m: cute.Tensor
+        raster_order: cutlass.Constexpr[RasterOrder]
+        group_size: Int32
+        group_size_fdd: Optional[FastDivmod]
+        group_size_tail_fdd: Optional[FastDivmod]
+        num_clusters_in_group_fdd: FastDivmod
+        tile_shape_mn: cutlass.Constexpr[cute.Shape]
+        tile_count_semaphore: Optional[cute.Pointer]
+        cluster_shape_mnk: cutlass.Constexpr[cute.Shape]
+        persistence_mode: cutlass.Constexpr[PersistenceMode]
+
+        @staticmethod
+        @cute.jit
+        def create(
+            args: TileSchedulerArguments, *, loc=None, ip=None
+        ) -> "VarlenMTileScheduler.Params":
+            # problem_shape_ntile_mnl[0] will be None for VarlenM
+            problem_shape_ntile_mn = cute.select(args.problem_shape_ntile_mnl, mode=[0, 1])
+            problem_shape_ncluster_mn = (
+                None,
+                cute.ceil_div(problem_shape_ntile_mn[1], args.cluster_shape_mnk[1]),
+            )
+            problem_shape_ncluster_mnl = problem_shape_ncluster_mn + (
+                args.problem_shape_ntile_mnl[2],
+            )
+            raster_order = const_expr(
+                RasterOrder.AlongM
+                if args.raster_order == RasterOrderOption.AlongM
+                else RasterOrder.AlongN  # For Heuristic we also use AlongN
+            )
+            ncluster_fast = problem_shape_ncluster_mn[
+                0 if raster_order == RasterOrder.AlongM else 1
+            ]
+            ncluster_slow = problem_shape_ncluster_mn[
+                1 if raster_order == RasterOrder.AlongM else 0
+            ]
+            if const_expr(ncluster_fast is not None):
+                group_size = min(args.group_size, ncluster_fast)
+                group_size_tail = ncluster_fast % group_size
+            else:
+                group_size, group_size_tail = args.group_size, None
+            num_clusters_in_group = None
+            if const_expr(ncluster_slow is not None):
+                num_clusters_in_group = group_size * ncluster_slow
+            if const_expr(args.persistence_mode == PersistenceMode.DYNAMIC):
+                assert args.tile_count_semaphore is not None
+            return VarlenMTileScheduler.Params(
+                problem_shape_ncluster_mnl,
+                args.total_m,
+                args.cu_seqlens_m,
+                raster_order,
+                group_size,
+                FastDivmod(group_size) if ncluster_fast is not None else None,
+                # Don't divide by 0
+                FastDivmod(group_size_tail if group_size_tail > 0 else 1)
+                if group_size_tail is not None
+                else None,
+                FastDivmod(num_clusters_in_group) if num_clusters_in_group is not None else None,
+                args.tile_shape_mn,
+                args.tile_count_semaphore
+                if const_expr(args.persistence_mode == PersistenceMode.DYNAMIC)
+                else None,
+                args.cluster_shape_mnk,
+                args.persistence_mode,
+            )
+
+    def __init__(
+        self,
+        current_work_idx: Int32,
+        num_tiles_executed: Int32,
+        current_batch_idx: Int32,
+        num_work_idx_before_cur_batch: Int32,
+        sched_smem: Optional[cute.Tensor],
+        scheduler_pipeline: Optional[cutlass.pipeline.PipelineAsync],
+        pipeline_state: PipelineStateWAdvance,
+        params: Params,
+        *,
+        loc=None,
+        ip=None,
+    ):
+        self._current_work_idx = current_work_idx
+        self.num_tiles_executed = num_tiles_executed
+        self._current_batch_idx = current_batch_idx
+        self._num_work_idx_before_cur_batch = num_work_idx_before_cur_batch
+        self._sched_smem = sched_smem
+        self._scheduler_pipeline = scheduler_pipeline
+        self._pipeline_state = pipeline_state
+        self.params = params
+        self._loc = loc
+        self._ip = ip
+
+    @staticmethod
+    def to_underlying_arguments(args: TileSchedulerArguments, *, loc=None, ip=None) -> Params:
+        return VarlenMTileScheduler.Params.create(args, loc=loc, ip=ip)
+
+    @staticmethod
+    @cute.jit
+    def _cluster_idx_to_work_idx_batch(
+        params: Params, cluster_idx: Tuple[Int32, Int32, Int32], *, loc=None, ip=None
+    ) -> Tuple[Int32, Optional[Int32]]:
+        if const_expr(params.persistence_mode in [PersistenceMode.NONE, PersistenceMode.CLC]):
+            current_work_idx = Int32(cluster_idx[0])
+        else:
+            current_work_idx = Int32(cluster_idx[2])
+        batch_idx = None
+        return current_work_idx, batch_idx
+
+    @staticmethod
+    @cute.jit
+    def create(
+        params: Params,
+        sched_smem: Optional[cute.Tensor] = None,
+        scheduler_pipeline: Optional[cutlass.pipeline.PipelineAsync] = None,
+        is_scheduler_warp: bool | Boolean = False,
+        *,
+        loc=None,
+        ip=None,
+    ) -> "VarlenMTileScheduler":
+        if const_expr(cute.size(params.cluster_shape_mnk, loc=loc, ip=ip) == 1):
+            cluster_idx = cute.arch.block_idx()
+        else:
+            cluster_idx = cute.arch.cluster_idx()
+        current_work_idx, _ = VarlenMTileScheduler._cluster_idx_to_work_idx_batch(
+            params, cluster_idx, loc=loc, ip=ip
+        )
+        stages = 0
+        if const_expr(
+            params.persistence_mode
+            in [PersistenceMode.STATIC, PersistenceMode.DYNAMIC, PersistenceMode.CLC]
+        ):
+            assert sched_smem is not None
+            assert scheduler_pipeline is not None
+            stages = const_expr(cute.size(sched_smem, mode=[1]))
+        if const_expr(params.persistence_mode == PersistenceMode.CLC):
+            if is_scheduler_warp:
+                TileScheduler._init_clc_mbarrier(sched_smem, loc=loc, ip=ip)
+        return VarlenMTileScheduler(
+            current_work_idx,
+            Int32(0),  # num_tiles_executed
+            Int32(0),  # current_batch_idx
+            Int32(0),  # num_work_idx_before_cur_batch
+            sched_smem,
+            scheduler_pipeline,
+            PipelineStateWAdvance(stages, Int32(0), Int32(0), Int32(0)),
+            params,
+            loc=loc,
+            ip=ip,
+        )
+
+    # called by host
+    @staticmethod
+    def get_grid_shape(
+        params: Params,
+        max_active_clusters: Int32,
+        *,
+        loc=None,
+        ip=None,
+    ) -> Tuple[Int32, Int32, Int32]:
+        block_size = params.tile_shape_mn[0] * params.cluster_shape_mnk[0]
+        num_batch = params.problem_shape_ncluster_mnl[2]
+        total_clusters_m_max = (params.total_m + num_batch * (block_size - 1)) // block_size
+        total_clusters_max = total_clusters_m_max * params.problem_shape_ncluster_mnl[1]
+        if const_expr(params.persistence_mode in [PersistenceMode.NONE, PersistenceMode.CLC]):
+            return (
+                params.cluster_shape_mnk[0] * total_clusters_max,
+                params.cluster_shape_mnk[1],
+                params.cluster_shape_mnk[2],
+            )
+        else:
+            num_persistent_clusters = cutlass.min(max_active_clusters, total_clusters_max)
+            return (
+                params.cluster_shape_mnk[0],
+                params.cluster_shape_mnk[1],
+                params.cluster_shape_mnk[2] * num_persistent_clusters,
+            )
+
+    @cute.jit
+    def _swizzle_cta(
+        self, cluster_id_in_problem: Int32, num_clusters_m: Int32, *, loc=None, ip=None
+    ) -> Tuple[Int32, Int32]:
+        params = self.params
+        # CTA Swizzle to promote L2 data reuse
+        if const_expr(params.num_clusters_in_group_fdd is not None):
+            group_id, id_in_group = divmod(cluster_id_in_problem, params.num_clusters_in_group_fdd)
+            num_clusters_in_group = params.num_clusters_in_group_fdd.divisor
+        else:
+            assert params.raster_order == RasterOrder.AlongN
+            num_clusters_in_group = params.group_size * num_clusters_m
+            group_id = cluster_id_in_problem // num_clusters_in_group
+            id_in_group = cluster_id_in_problem - group_id * num_clusters_in_group
+        cid_fast_in_group, cid_slow = Int32(0), Int32(0)
+        if const_expr(params.group_size_fdd is not None and params.group_size_tail_fdd is not None):
+            num_clusters = num_clusters_m * params.problem_shape_ncluster_mnl[1]
+            if (group_id + 1) * num_clusters_in_group <= num_clusters:
+                cid_slow, cid_fast_in_group = divmod(id_in_group, params.group_size_fdd)
+                # if cid_slow % 2 == 1:  # inner serpentine
+                #     cid_fast_in_group = params.group_size_fdd.divisor - 1 - cid_fast_in_group
+            else:  # tail part
+                cid_slow, cid_fast_in_group = divmod(id_in_group, params.group_size_tail_fdd)
+                # if cid_slow % 2 == 1:  # inner serpentine
+                #     cid_fast_in_group = params.group_size_tail_fdd.divisor - 1 - cid_fast_in_group
+        else:
+            assert params.raster_order == RasterOrder.AlongM
+            group_size_actual = cutlass.min(
+                params.group_size, num_clusters_m - group_id * params.group_size
+            )
+            cid_slow = id_in_group // group_size_actual
+            cid_fast_in_group = id_in_group - cid_slow * group_size_actual
+            # if cid_slow % 2 == 1:  # inner serpentine
+            #     cid_fast_in_group = group_size_actual - 1 - cid_fast_in_group
+        if group_id % 2 == 1:  # serpentine order
+            ncluster_slow = (
+                params.problem_shape_ncluster_mnl[1]
+                if params.raster_order == RasterOrder.AlongM
+                else num_clusters_m
+            )
+            cid_slow = ncluster_slow - 1 - cid_slow
+        cid_fast = group_id * params.group_size + cid_fast_in_group
+        cid_m, cid_n = cid_fast, cid_slow
+        if params.raster_order == RasterOrder.AlongN:
+            cid_m, cid_n = cid_slow, cid_fast
+        return cid_m, cid_n
+
+    @cute.jit
+    def _get_num_m_blocks(
+        self, lane: Int32, bidb_start: Int32, block_size: cutlass.Constexpr[int]
+    ) -> Int32:
+        num_batch = self.params.problem_shape_ncluster_mnl[2]
+        batch_idx = lane + bidb_start
+        cur_cu_seqlen = Int32(0)
+        if batch_idx <= num_batch:
+            cur_cu_seqlen = self.params.cu_seqlens_m[batch_idx]
+        next_cu_seqlen = cute.arch.shuffle_sync_down(cur_cu_seqlen, offset=1)
+        seqlen = next_cu_seqlen - cur_cu_seqlen
+        return (
+            cute.ceil_div(seqlen, block_size)
+            if batch_idx < num_batch and lane < cute.arch.WARP_SIZE - 1
+            else Int32(0)
+        )
+
+    @cute.jit
+    def _delinearize_work_idx(
+        self,
+        work_idx: Int32,
+        bidz: Optional[Int32] = None,  # not used
+        is_valid_: Optional[Boolean] = None,
+        *,
+        block_zero_only: bool = False,
+        loc=None,
+        ip=None,
+    ) -> cutlass.utils.WorkTileInfo:
+        assert bidz is None
+        params = self.params
+        lane_idx = cute.arch.lane_idx()
+        num_batch = self.params.problem_shape_ncluster_mnl[2]
+        block_size = params.tile_shape_mn[0] * params.cluster_shape_mnk[0]
+        batch_idx = self._current_batch_idx
+        next_tile_idx = work_idx
+
+        problems_end_tile = self._num_work_idx_before_cur_batch
+        num_clusters_m, num_clusters_cumulative, clusters_in_problems = Int32(0), Int32(0), Int32(0)
+        is_valid = True
+        if const_expr(is_valid_ is not None):
+            is_valid = is_valid_
+        if is_valid:
+            while problems_end_tile <= next_tile_idx:
+                num_clusters_m = self._get_num_m_blocks(
+                    lane_idx, bidb_start=batch_idx, block_size=block_size
+                )
+                num_clusters = num_clusters_m * params.problem_shape_ncluster_mnl[1]
+                num_clusters_cumulative = utils.warp_prefix_sum(num_clusters, lane_idx)
+                # Total number of blocks for the next 31 problems, same for all lanes
+                clusters_in_problems = cute.arch.shuffle_sync(
+                    num_clusters_cumulative, cute.arch.WARP_SIZE - 1
+                )
+                problems_end_tile += clusters_in_problems
+                if problems_end_tile <= next_tile_idx:
+                    batch_idx += cute.arch.WARP_SIZE - 1
+                if batch_idx >= num_batch:
+                    batch_idx = Int32(num_batch)
+                    problems_end_tile = next_tile_idx + 1
+        else:
+            batch_idx = Int32(num_batch)
+
+        is_valid = batch_idx < num_batch
+        if const_expr(params.persistence_mode == PersistenceMode.NONE):
+            is_valid &= self.num_tiles_executed == 0
+        cid_m, cid_n = Int32(0), Int32(0)
+        num_work_idx_before_cur_batch = self._num_work_idx_before_cur_batch
+        if is_valid:
+            problems_start_tile = problems_end_tile - clusters_in_problems
+            # if cute.arch.thread_idx()[0] == 128 + 31: cute.printf("SingleTileVarlenScheduler: tile_idx=%d, problems_end_tile = %d, num_clusters_m=%d, batch_idx = %d", self._tile_idx, problems_end_tile, num_clusters_m, batch_idx)
+            # The next problem to process is the first one that does not have ending tile position
+            # that is greater than or equal to tile index.
+            batch_idx_in_problems = cute.arch.popc(
+                cute.arch.vote_ballot_sync(
+                    problems_start_tile + num_clusters_cumulative <= next_tile_idx
+                )
+            )
+            batch_idx += batch_idx_in_problems
+            num_clusters_prev_lane = (
+                0
+                if batch_idx_in_problems == 0
+                else cute.arch.shuffle_sync(num_clusters_cumulative, batch_idx_in_problems - 1)
+            )
+            num_clusters_m = cute.arch.shuffle_sync(num_clusters_m, batch_idx_in_problems)
+            num_work_idx_before_cur_batch = problems_start_tile + num_clusters_prev_lane
+            cluster_id_in_problem = next_tile_idx - num_work_idx_before_cur_batch
+            # if cute.arch.thread_idx()[0] == 128: cute.printf("SingleTileVarlenScheduler: tile_idx=%d, batch_idx=%d, cid_n=%d, cid_m=%d, is_valid = %d", self._tile_idx, batch_idx, cid_n, cid_m, is_valid)
+            cid_m, cid_n = self._swizzle_cta(cluster_id_in_problem, num_clusters_m, loc=loc, ip=ip)
+        pid_m, pid_n = self._cluster_id_to_cta_id(
+            cid_m, cid_n, block_zero_only=block_zero_only, loc=loc, ip=ip
+        )
+        tile_coord_mnkl = (pid_m, pid_n, None, batch_idx)
+        self._current_batch_idx = batch_idx
+        self._num_work_idx_before_cur_batch = num_work_idx_before_cur_batch
+        return cutlass.utils.WorkTileInfo(tile_coord_mnkl, is_valid)
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/trace.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/trace.py
new file mode 100644
index 0000000000000000000000000000000000000000..13494212fde2a8d6efb0b04bcf7a09e47e836e51
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/trace.py
@@ -0,0 +1,847 @@
+# Copyright (c) 2025-2026, Tri Dao.
+"""Intra-kernel trace profiler for CuTe-DSL kernels.
+
+Emits Chrome Trace JSON (compatible with Perfetto / chrome://tracing) from
+per-warp instrumentation inserted directly into CuTe-DSL kernels.
+
+Toggle with QUACK_TRACE=1 env var.  When disabled (the default) every trace
+call is a compile-time no-op — the JIT never emits any profiling PTX.
+
+Design decisions
+----------------
+**Two-timer approach (inspired by Triton Proton).**
+NVIDIA GPUs expose two timers accessible from PTX:
+  - %globaltimer — device-wide, ~1 GHz, synchronized across all SMs.
+  - %clock64    — per-SM cycle counter, ~2.1 GHz on H100, *not* synchronized
+                  across SMs (confirmed empirically: cross-SM spread > 400M ticks
+                  vs ~200 ticks for globaltimer on the same launch).
+We read %globaltimer once at init and once at flush (per warp) to anchor each
+warp's timeline to a device-wide epoch, then read %clock64 for every event.
+This gives us low-overhead per-event timestamps (local SM register read) while
+retaining cross-SM comparability.  During post-processing the per-slot pair
+    (init_globaltimer, init_clock64) and (final_globaltimer, final_clock64)
+auto-calibrates the clock64-to-nanosecond conversion:
+    ratio = (final_gt - init_gt) / (final_clk - init_clk)
+    event_ns = init_gt + (event_clk - init_clk) * ratio
+
+**Compact events (inspired by ThunderKittens).**
+Each event is 8 bytes: a raw 32-bit %clock value and a packed (region_id,
+event_type) tag, stored with a single v2.u32 streaming store.  The device
+writes the raw clock — no subtraction needed.  The host computes deltas
+during post-processing using init_clock from metadata with proper u32
+wraparound.  Block and warp identity (constant per slot) are stored once
+in per-slot metadata instead of per event.
+
+**Minimal live registers.**
+The TraceContext dataclass carries only 3 DSL values across loop iterations:
+  - slot_ptr (64-bit)  — base of this warp's interleaved [metadata|events]
+  - cnt     (32-bit)  — circular buffer write index
+  - is_active (1-bit) — predicate for stores (warp leader AND warp sampling)
+init_clk is NOT stored — the device writes raw clock values and the host
+subtracts init_clk during post-processing.  This saves one register vs
+computing deltas on device.
+
+**Interleaved per-slot layout.**
+Each warp's metadata and events are contiguous in memory:
+    [meta₀ events₀ | meta₁ events₁ | ...]
+This means the device needs only ONE pointer (slot_ptr) instead of separate
+metadata and event pointers, saving another register.
+
+**Warp sampling.**
+An optional warp_ids parameter restricts profiling to specific warps.
+Non-selected warps execute predicated stores that the GPU evaluates to
+hardware no-ops — zero store bandwidth and no branch divergence.
+
+**Auto-interned region names.**
+ctx.b("mma") / ctx.e("mma") auto-assign integer IDs via a module-level
+registry at JIT time.  The host reads the same registry at write_trace time.
+No region_names parameter needed on either side.
+
+Usage
+-----
+Host:
+    with TraceSession("trace.json", grid_size=G, block_size=B) as sess:
+        my_kernel[grid, block](..., sess.ptr)
+
+Device (safe to call from all lanes):
+    ctx = TraceContext.create(trace_ptr)
+    ctx.b("load"); ctx.e("load")
+    ctx.flush()
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import os
+import struct
+from typing import Optional
+from collections import defaultdict
+from dataclasses import dataclass
+
+import torch
+
+import cutlass
+import cutlass.cute as cute
+from cutlass import Int32, Int64, const_expr
+from cutlass.base_dsl.arch import Arch
+from cutlass._mlir.dialects import llvm, nvvm
+from cutlass.cutlass_dsl import T
+
+from .copy_utils import store, store_v2
+from .cute_dsl_utils import ParamsBase
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+QUACK_TRACE_ENV = "QUACK_TRACE"
+
+EVENT_BEGIN = 0
+EVENT_END = 1
+EVENT_MARK = 2
+
+# Per-event record: (u32 raw_clock, u16 region_id, u16 event_type)
+# raw_clock is the 32-bit %clock value at event time; the host converts to
+# nanoseconds by subtracting init_clock and applying the calibration ratio.
+EVENT_SIZE = 8
+EVENT_STRUCT = struct.Struct(" bool:
+    """Check QUACK_TRACE=1.  Evaluated at JIT time so disabled = no codegen."""
+    return os.environ.get(QUACK_TRACE_ENV, "") == "1"
+
+
+# Module-level registry: auto-populated by TraceContext at JIT time,
+# read by TraceSession at write_trace time.  No need for the user to
+# pass region_names to both sides.
+_REGION_REGISTRY: dict[int, str] = {}
+
+
+def _intern_region(name: str) -> int:
+    """Assign a stable integer ID to a region name.  JIT-time only."""
+    for rid, n in _REGION_REGISTRY.items():
+        if n == name:
+            return rid
+    rid = len(_REGION_REGISTRY)
+    _REGION_REGISTRY[rid] = name
+    return rid
+
+
+def _reset_region_registry():
+    """Clear the registry.  Called by TraceContext.create so each kernel starts fresh."""
+    _REGION_REGISTRY.clear()
+
+
+# ---------------------------------------------------------------------------
+# Contiguous buffer layout (shared between host and device)
+# ---------------------------------------------------------------------------
+# Per-slot data is interleaved: metadata followed by events for each slot.
+# This means the device only needs ONE pointer per warp (the slot base).
+#
+#   ┌──────────────────────────────────────┐  slot 0
+#   │ metadata (40B) │ events (8B × cap)   │
+#   ├──────────────────────────────────────┤  slot 1
+#   │ metadata (40B) │ events (8B × cap)   │
+#   ├──────────────────────────────────────┤  ...
+#   │ ...                                  │
+#   └──────────────────────────────────────┘
+#
+# In u32 elements: slot_size = META_ELEMS + per_warp_cap * EVENT_ELEMS
+
+META_ELEMS = METADATA_SIZE // 4  # 10 u32 elements per slot's metadata
+EVENT_ELEMS = EVENT_SIZE // 4  # 2 u32 elements per event
+
+
+def _slot_size(per_warp_cap: int) -> int:
+    """Per-slot size in bytes (metadata + events)."""
+    return METADATA_SIZE + per_warp_cap * EVENT_SIZE
+
+
+def _buf_total_bytes(total_slots: int, per_warp_cap: int) -> int:
+    return total_slots * _slot_size(per_warp_cap)
+
+
+# ---------------------------------------------------------------------------
+# Device-side helpers
+# ---------------------------------------------------------------------------
+# Timer reads use side-effecting inline asm instead of nvvm.read_ptx_sreg_* so
+# MLIR CSE cannot merge adjacent reads and erase elapsed time.
+# Unpredicated stores use cute.arch.store (which wraps nvvm.store_ext with nice
+# pointer/Numeric handling).  Predicated stores still need inline asm since the
+# NVVM store op doesn't support PTX predication.
+
+
+def _read_globaltimer():
+    return Int64(
+        llvm.inline_asm(
+            T.i64(),
+            [],
+            "mov.u64 $0, %globaltimer;",
+            "=l",
+            has_side_effects=True,
+            is_align_stack=False,
+        )
+    )
+
+
+def _read_clock64():
+    return Int64(
+        llvm.inline_asm(
+            T.i64(),
+            [],
+            "mov.u64 $0, %clock64;",
+            "=l",
+            has_side_effects=True,
+            is_align_stack=False,
+        )
+    )
+
+
+def _read_clock():
+    return cutlass.Int32(
+        llvm.inline_asm(
+            T.i32(),
+            [],
+            "mov.u32 $0, %clock;",
+            "=r",
+            has_side_effects=True,
+            is_align_stack=False,
+        )
+    )
+
+
+def _read_smid():
+    return cutlass.Int32(nvvm.read_ptx_sreg_smid(T.i32()))
+
+
+def _gmem_ptr(dtype, addr):
+    """Create a cute global-memory pointer from an Int64 address."""
+    return cute.make_ptr(dtype, Int64(addr), cute.AddressSpace.gmem)
+
+
+def _is_warp_leader():
+    """Return a DSL predicate for the warp leader thread.
+
+    Uses nvvm.elect_sync() on SM90+ (hardware single-thread election),
+    falls back to lane_idx() == 0 on older architectures.
+    """
+    if cutlass.base_dsl.BaseDSL._get_dsl().get_arch_enum() >= Arch.sm_90:
+        if cutlass.const_expr(cutlass.CUDA_VERSION.major) == 12:
+            return cutlass.Boolean(nvvm.elect_sync(T.bool()))
+        elif cutlass.const_expr(cutlass.CUDA_VERSION.major) == 13:
+            return cutlass.Boolean(nvvm.elect_sync())
+        else:
+            raise ValueError(f"CUDA_VERSION.major must be >= 12, got {cutlass.CUDA_VERSION.major}")
+    return cute.arch.lane_idx() == 0
+
+
+# ---------------------------------------------------------------------------
+# Device-side: TraceContext
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class TraceContext(ParamsBase):
+    """Per-warp trace recorder for use inside CuTe-DSL kernels.
+
+    Use the ``create`` classmethod (not ``__init__``) to construct.  Named
+    regions (ctx.b("mma") / ctx.e("mma")) are resolved to integer IDs at JIT
+    time.  Optional warp_ids restricts profiling to specific warps.
+
+    Usage::
+
+        ctx = TraceContext.create(trace_ptr)
+        ctx.b("load"); ctx.e("load")
+        ctx.flush()
+    """
+
+    # Compile-time constants (auto-detected as static by ParamsBase)
+    per_warp_cap: int = 0
+    warp_ids: tuple | None = None
+
+    # DSL values (auto-serialized by ParamsBase across cutlass.range loops).
+    # slot_ptr points to this warp's interleaved [metadata | events] region.
+    # Metadata at slot_ptr+0, events at slot_ptr+META_ELEMS.
+    slot_ptr: cute.Pointer = None
+    cnt: cutlass.Int32 = None
+    is_active: cutlass.Boolean = None
+
+    # ── Public factory ──────────────────────────────────────────────────────
+
+    @classmethod
+    def create(
+        cls,
+        buf_ptr: Optional[Int64],
+        per_warp_cap: int = 4096,
+        warp_ids: tuple[int, ...] | list[int] | None = None,
+    ):
+        """Create and initialize a TraceContext.  Safe to call from all lanes.
+
+        Only lane 0 (warp leader) performs stores; all other lanes execute
+        the arithmetic but skip the writes via predication.  The caller does
+        NOT need an ``if is_warp_leader():`` guard.
+
+        Region names are auto-interned by ctx.b("name") / ctx.e("name") via a
+        module-level registry — no explicit region_names list needed.
+        """
+        assert (per_warp_cap & (per_warp_cap - 1)) == 0, "per_warp_cap must be power of 2"
+        _reset_region_registry()
+        warp_ids = tuple(warp_ids) if warp_ids is not None else None
+
+        if not enabled() or const_expr(buf_ptr is None):
+            return cls(
+                per_warp_cap=per_warp_cap,
+                warp_ids=warp_ids,
+                slot_ptr=None,
+                cnt=None,
+                is_active=None,
+            )
+
+        SLOT_ELEMS = META_ELEMS + per_warp_cap * EVENT_ELEMS  # u32 elements per slot
+
+        bdx, bdy, bdz = cute.arch.block_dim()
+        warps_per_block = (bdx * bdy * bdz + cute.arch.WARP_SIZE - 1) // cute.arch.WARP_SIZE
+        warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
+        smid = _read_smid()
+
+        # Linearize blockIdx across all grid dimensions.
+        bidx, bidy, bidz = cute.arch.block_idx()
+        gdx, gdy, gdz = cute.arch.grid_dim()
+        linear_block = bidx + bidy * gdx + bidz * gdx * gdy
+        slot = linear_block * warps_per_block + warp_idx
+
+        # Single pointer to this warp's interleaved [metadata | events] region.
+        buf = _gmem_ptr(Int32, Int64(buf_ptr))
+        slot_ptr = buf + slot * SLOT_ELEMS
+
+        # is_active gates all stores: warp leader only, AND warp sampling if set.
+        is_leader = _is_warp_leader()
+        if warp_ids is not None:
+            is_active = cutlass.Boolean(False)
+            for wid in warp_ids:
+                is_active = is_active | (warp_idx == wid)
+            is_active = is_active & is_leader
+        else:
+            is_active = is_leader
+
+        # Pack warp + smid into 16 bits: warp[5:0] | smid[15:6]
+        packed = (warp_idx & 0x3F) | ((smid & 0x3FF) << 6)
+        info = linear_block | (packed << 16)
+
+        # Read timers for metadata (host-side calibration).
+        gt = _read_globaltimer()
+        clk64 = _read_clock64()
+
+        # Write init metadata at slot_ptr. cnt is written by flush().
+        store(slot_ptr, gt, is_active, cop="cs")  # offset 0: init_gt
+        store(slot_ptr + 2, clk64, is_active, cop="cs")  # offset 8: init_clk64
+        store(slot_ptr + 8, info, is_active, cop="cs")  # offset 32: info
+
+        return cls(
+            per_warp_cap=per_warp_cap,
+            warp_ids=warp_ids,
+            slot_ptr=slot_ptr,
+            cnt=Int32(0),
+            is_active=is_active,
+        )
+
+    def flush(self):
+        """Write final timer pair and event count.  Safe to call from all lanes."""
+        if self.slot_ptr is None:
+            return
+        gt = _read_globaltimer()
+        clk = _read_clock64()
+        store(self.slot_ptr + 4, gt, self.is_active, cop="cs")  # final_gt
+        store(self.slot_ptr + 6, clk, self.is_active, cop="cs")  # final_clk
+        store(self.slot_ptr + 9, self.cnt, self.is_active, cop="cs")  # cnt
+
+    # ── Recording ───────────────────────────────────────────────────────────
+
+    def _record(self, region_id: int, event_type: int):
+        if self.slot_ptr is None:
+            return
+        clk = _read_clock()  # raw 32-bit clock; host subtracts init_clk
+        evt_off = META_ELEMS + (self.cnt & (self.per_warp_cap - 1)) * EVENT_ELEMS
+        tag = Int32(region_id) | (Int32(event_type) << 16)
+        store_v2(self.slot_ptr + evt_off, clk, tag, self.is_active, cop="cs")
+        self.cnt += 1
+
+    # Integer-ID API
+    def record_b(self, region_id: int):
+        self._record(region_id, EVENT_BEGIN)
+
+    def record_e(self, region_id: int):
+        self._record(region_id, EVENT_END)
+
+    def record_m(self, region_id: int):
+        self._record(region_id, EVENT_MARK)
+
+    # Named-region API (string → int resolved at JIT time via module registry)
+    def b(self, name: str):
+        self._record(_intern_region(name), EVENT_BEGIN)
+
+    def e(self, name: str):
+        self._record(_intern_region(name), EVENT_END)
+
+    def m(self, name: str):
+        self._record(_intern_region(name), EVENT_MARK)
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# Host-side
+# ═══════════════════════════════════════════════════════════════════════════
+
+
+def _unpack_warp(packed: int) -> int:
+    return packed & 0x3F
+
+
+def _unpack_smid(packed: int) -> int:
+    return packed >> 6
+
+
+@dataclass
+class _Event:
+    """Reconstructed event with absolute timestamp (nanoseconds)."""
+
+    ts: int
+    id: int
+    type: int
+    block: int
+    warp_smid: int
+
+    @property
+    def warp(self) -> int:
+        return _unpack_warp(self.warp_smid)
+
+    @property
+    def smid(self) -> int:
+        return _unpack_smid(self.warp_smid)
+
+
+@dataclass
+class _SlotMeta:
+    """Per-slot metadata read back from device."""
+
+    init_gt: int
+    init_clk: int
+    final_gt: int
+    final_clk: int
+    info: int
+    cnt: int
+
+    @property
+    def block(self) -> int:
+        return self.info & 0xFFFF
+
+    @property
+    def warp_smid(self) -> int:
+        return (self.info >> 16) & 0xFFFF
+
+    @property
+    def init_clk32(self) -> int:
+        """Low 32 bits of init_clock64 (%clock at init time)."""
+        return self.init_clk & 0xFFFFFFFF
+
+    @property
+    def ratio(self) -> float:
+        """clock64 ticks → nanoseconds conversion factor for this slot."""
+        dclk = self.final_clk - self.init_clk
+        return (self.final_gt - self.init_gt) / dclk if dclk > 0 else 1.0
+
+    def clock_to_ns(self, raw_clock32: int) -> float:
+        """Convert a raw 32-bit clock value to absolute nanoseconds."""
+        delta = (raw_clock32 - self.init_clk32) & 0xFFFFFFFF  # u32 wraparound
+        return self.init_gt + delta * self.ratio
+
+
+@dataclass
+class TraceWriteOptions:
+    scale: float = 1e-3  # globaltimer is ns; Chrome trace displayTimeUnit is also "ns"
+    emit_complete_events: bool = True  # pair B/E into ph:"X" (more robust in viewers)
+    group_by_smid: bool = False  # pid = block id (ordered); True = pid = SM id
+    emit_summary_json: bool = True
+    summary_hist_bins: int = 128
+
+
+class TraceSession:
+    """Host-side profiling session.
+
+    Allocates a single contiguous device buffer, provides one pointer (sess.ptr)
+    to pass to the kernel, and writes Chrome Trace JSON on exit.
+
+    Can be used as a context manager for automatic sync + write:
+
+        with TraceSession("trace.json", grid_size=G, block_size=B) as sess:
+            my_kernel[grid, block](..., sess.ptr)
+        # trace.json written here
+    """
+
+    def __init__(
+        self,
+        path: str | None = None,
+        *,
+        per_warp_cap: int = 4096,
+        grid_size: int = 1,
+        block_size: int = 128,
+        warp_ids: list[int] | tuple[int, ...] | None = None,
+        device: str | torch.device = "cuda",
+    ):
+        assert (per_warp_cap & (per_warp_cap - 1)) == 0, "per_warp_cap must be power of 2"
+        self.path = path
+        self.per_warp_cap = per_warp_cap
+        self.total_blocks = grid_size
+        self.warps_per_block = (block_size + 31) // 32
+        self.warp_ids = tuple(warp_ids) if warp_ids is not None else None
+        self.device = device
+
+        if not enabled():
+            self.d_buf = None
+            return
+
+        total_slots = self.total_blocks * self.warps_per_block
+        self.d_buf = torch.zeros(
+            _buf_total_bytes(total_slots, per_warp_cap),
+            dtype=torch.uint8,
+            device=device,
+        )
+
+    @property
+    def ptr(self):
+        """Device pointer as Int64, or None when tracing is disabled.
+        Pass directly as an Optional[Int64] kernel argument."""
+        from cutlass.cutlass_dsl import Int64
+
+        return Int64(self.d_buf.data_ptr()) if self.d_buf is not None else None
+
+    def reset(self):
+        if self.d_buf is not None:
+            self.d_buf.zero_()
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        if self.path and enabled():
+            torch.cuda.synchronize()
+            self.write_trace(self.path)
+        return False
+
+    # ── Read helpers ────────────────────────────────────────────────────────
+
+    def _raw_bytes(self):
+        return self.d_buf.cpu().numpy()
+
+    def _read_metadata(self, raw) -> list[_SlotMeta]:
+        total_slots = self.total_blocks * self.warps_per_block
+        slot_bytes = _slot_size(self.per_warp_cap)
+        return [
+            _SlotMeta(*METADATA_STRUCT.unpack_from(raw, s * slot_bytes)) for s in range(total_slots)
+        ]
+
+    def _read_events(self, raw, metas) -> list[_Event]:
+        total_slots = self.total_blocks * self.warps_per_block
+        slot_bytes = _slot_size(self.per_warp_cap)
+        events = []
+        for s in range(total_slots):
+            cnt = metas[s].cnt
+            n = min(cnt, self.per_warp_cap)
+            start = (cnt & (self.per_warp_cap - 1)) if cnt > self.per_warp_cap else 0
+            # Events start after metadata within this slot.
+            slot_events_off = s * slot_bytes + METADATA_SIZE
+            meta = metas[s]
+            for i in range(n):
+                idx = (start + i) & (self.per_warp_cap - 1)
+                raw_clk, eid, etype = EVENT_STRUCT.unpack_from(
+                    raw,
+                    slot_events_off + idx * EVENT_SIZE,
+                )
+                events.append(
+                    _Event(
+                        ts=int(meta.clock_to_ns(raw_clk)),
+                        id=eid,
+                        type=etype,
+                        block=meta.block,
+                        warp_smid=meta.warp_smid,
+                    )
+                )
+        events.sort(
+            key=lambda ev: (
+                ev.ts,
+                _unpack_smid(ev.warp_smid),
+                ev.block,
+                _unpack_warp(ev.warp_smid),
+                0 if ev.type == 0 else (1 if ev.type == 2 else 2),
+                ev.id,
+            )
+        )
+        return events
+
+    def _region_name(self, rid: int) -> str:
+        return _REGION_REGISTRY.get(rid, str(rid))
+
+    # ── Chrome Trace JSON output ────────────────────────────────────────────
+
+    def write_trace(self, path: str, opt: TraceWriteOptions | None = None):
+        if not enabled():
+            return
+        opt = opt or TraceWriteOptions()
+
+        raw = self._raw_bytes()
+        metas = self._read_metadata(raw)
+        events = self._read_events(raw, metas)
+        if not events:
+            print("intra_kernel_profiler::trace: 0 events")
+            return
+
+        os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+        min_ts = events[0].ts
+        trace_events: list[dict] = []
+
+        # Collect unique pids/tids and build name metadata entries.
+        used_pids: set[int] = set()
+        used_threads: set[tuple[int, int]] = set()
+        block_to_smid: dict[int, int] = {}
+        for e in events:
+            sm, b, w = e.smid, e.block, e.warp
+            block_to_smid.setdefault(b, sm)
+            pid = sm if opt.group_by_smid else b
+            tid = ((b << 6) | w) if opt.group_by_smid else (w * 32)
+            used_pids.add(pid)
+            used_threads.add((pid, tid))
+
+        for pid in sorted(used_pids):
+            pname = (
+                f"SM {pid:03d}"
+                if opt.group_by_smid
+                else f"SM {block_to_smid.get(pid, 0):03d} Block {pid:04d}"
+            )
+            trace_events.append(
+                {"ph": "M", "name": "process_name", "pid": pid, "tid": 0, "args": {"name": pname}}
+            )
+            trace_events.append(
+                {
+                    "ph": "M",
+                    "name": "process_sort_index",
+                    "pid": pid,
+                    "tid": 0,
+                    "args": {"sort_index": pid},
+                }
+            )
+        for pid, tid in sorted(used_threads):
+            if opt.group_by_smid:
+                tname = f"Block {tid >> 6:04d} Warp {tid & 0x3F:02d}"
+            else:
+                tname = f"Warp {tid // 32:02d}"
+            trace_events.append(
+                {"ph": "M", "name": "thread_name", "pid": pid, "tid": tid, "args": {"name": tname}}
+            )
+            trace_events.append(
+                {
+                    "ph": "M",
+                    "name": "thread_sort_index",
+                    "pid": pid,
+                    "tid": tid,
+                    "args": {"sort_index": tid},
+                }
+            )
+
+        # Convert events to Chrome Trace format.
+        if opt.emit_complete_events:
+            out_events = self._pair_begin_end(events, opt)
+            for ts, dur, pid, tid, rid, kind, b, w, sm in out_events:
+                ev = {
+                    "name": self._region_name(rid),
+                    "pid": pid,
+                    "tid": tid,
+                    "cname": _CNAME_LIST[rid % len(_CNAME_LIST)],
+                    "args": {"sm": sm, "block": b, "warp": w},
+                }
+                if kind == 0:
+                    ev.update(ph="X", ts=(ts - min_ts) * opt.scale, dur=dur * opt.scale)
+                else:
+                    ev.update(ph="i", s="t", ts=(ts - min_ts) * opt.scale)
+                trace_events.append(ev)
+        else:
+            out_events = []
+            for e in events:
+                sm, b, w = e.smid, e.block, e.warp
+                pid = sm if opt.group_by_smid else b
+                tid = ((b << 6) | w) if opt.group_by_smid else (w * 32)
+                ph = "B" if e.type == 0 else ("E" if e.type == 1 else "i")
+                ev = {
+                    "name": self._region_name(e.id),
+                    "ph": ph,
+                    "ts": (e.ts - min_ts) * opt.scale,
+                    "pid": pid,
+                    "tid": tid,
+                    "cname": _CNAME_LIST[e.id % len(_CNAME_LIST)],
+                    "args": {"sm": sm, "block": b, "warp": w},
+                }
+                if e.type == EVENT_MARK:
+                    ev["s"] = "t"
+                trace_events.append(ev)
+
+        with open(path, "w") as f:
+            json.dump({"displayTimeUnit": "ns", "traceEvents": trace_events}, f)
+        print(f"intra_kernel_profiler::trace: {len(events)} events -> {path}")
+
+        if opt.emit_complete_events and opt.emit_summary_json:
+            self._write_summary(path, out_events, opt)
+
+    @staticmethod
+    def _pair_begin_end(events, opt):
+        """Match B/E events into (ts, dur, pid, tid, rid, kind, block, warp, sm) tuples."""
+        thread_states: dict[tuple, dict[int, list[int]]] = defaultdict(lambda: defaultdict(list))
+        out = []
+        for e in events:
+            sm, b, w = e.smid, e.block, e.warp
+            pid = sm if opt.group_by_smid else b
+            tid = ((b << 6) | w) if opt.group_by_smid else (w * 32)
+            key = (pid, tid)
+            if e.type == EVENT_BEGIN:
+                thread_states[key][e.id].append(e.ts)
+            elif e.type == EVENT_END:
+                stack = thread_states[key][e.id]
+                if stack:
+                    t0 = stack.pop()
+                    if e.ts >= t0:
+                        out.append((t0, e.ts - t0, pid, tid, e.id, 0, b, w, sm))
+            else:
+                out.append((e.ts, 0, pid, tid, e.id, 1, b, w, sm))
+        return out
+
+    # ── Summary JSON ────────────────────────────────────────────────────────
+
+    def _write_summary(self, trace_path, out_events, opt):
+        base = trace_path.rsplit(".json", 1)[0] if trace_path.endswith(".json") else trace_path
+        summary_path = base + "_summary.json"
+
+        region_stats: dict[int, list[float]] = defaultdict(list)
+        for ts, dur, pid, tid, rid, kind, b, w, sm in out_events:
+            if kind == 0:
+                region_stats[rid].append(dur * opt.scale)
+
+        regions = []
+        for rid in sorted(region_stats):
+            durs = region_stats[rid]
+            n = len(durs)
+            if n == 0:
+                continue
+            mean = sum(durs) / n
+            min_d, max_d = min(durs), max(durs)
+            var_pop = sum((d - mean) ** 2 for d in durs) / n
+            var_sample = sum((d - mean) ** 2 for d in durs) / (n - 1) if n > 1 else 0
+            cv = math.sqrt(var_sample) / abs(mean) if abs(mean) > 0 and n > 1 else None
+
+            bins = opt.summary_hist_bins or 128
+            hist = [0] * bins
+            if max_d > min_d:
+                for d in durs:
+                    hist[
+                        min(int(max(0.0, min(1.0, (d - min_d) / (max_d - min_d))) * bins), bins - 1)
+                    ] += 1
+            else:
+                hist[0] = n
+
+            w_bin = (max_d - min_d) / bins if max_d > min_d else 0
+            pcts = {}
+            for p in (5, 10, 25, 50, 75, 90, 95, 99):
+                q, cum, val = p / 100.0, 0.0, min_d
+                for i, c in enumerate(hist):
+                    prev = cum
+                    cum += c / n
+                    if cum >= q:
+                        prob = c / n
+                        frac = max(0.0, min(1.0, (q - prev) / prob)) if prob > 0 else 0
+                        val = min_d + w_bin * i + frac * w_bin
+                        break
+                pcts[f"p{p}"] = val
+
+            regions.append(
+                {
+                    "region": rid,
+                    "name": self._region_name(rid),
+                    "count": n,
+                    "mean_dur": mean,
+                    "cv_dur": cv,
+                    "min_dur": min_d,
+                    "max_dur": max_d,
+                    "var_dur_pop": var_pop,
+                    "var_dur_sample": var_sample,
+                    "percentiles": pcts,
+                    "hist": {
+                        "bins": bins,
+                        "min": min_d,
+                        "max": max_d,
+                        "prob": [c / n for c in hist],
+                    },
+                }
+            )
+
+        with open(summary_path, "w") as f:
+            json.dump(
+                {
+                    "trace": trace_path,
+                    "displayTimeUnit": "ns",
+                    "scale": opt.scale,
+                    "blocks": self.total_blocks,
+                    "warps_per_block": self.warps_per_block,
+                    "per_warp_cap": self.per_warp_cap,
+                    "regions": regions,
+                },
+                f,
+                indent=2,
+            )
+        print(f"intra_kernel_profiler::trace: summary -> {summary_path}")
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5be0f5a4c354ca34091ca1dbc9d2afe34410fc2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/utils.py
@@ -0,0 +1,334 @@
+# Copyright (c) 2025, Wentao Guo, Ted Zadouri, Tri Dao.
+
+import math
+from typing import Optional, Tuple, Union
+
+import cutlass
+import cutlass.cute as cute
+
+from cutlass import Float32, Int32, const_expr
+from cutlass._mlir.dialects import arith as _arith
+from cutlass._mlir.dialects import llvm, nvvm, vector
+from cutlass.cutlass_dsl import T, dsl_user_op
+
+
+@dsl_user_op
+def elem_pointer(x: cute.Tensor, coord: cute.Coord, *, loc=None, ip=None) -> cute.Pointer:
+    return x.iterator + cute.crd2idx(coord, x.layout, loc=loc, ip=ip)
+
+
+@cute.jit
+def load_scalar_or_pointer(x, dtype=Float32):
+    if const_expr(isinstance(x, cute.Pointer)):
+        return dtype(cute.make_tensor(x, cute.make_layout(1))[0])
+    else:
+        return x
+
+
+@dsl_user_op
+def set_block_rank(
+    smem_ptr: cute.Pointer, peer_cta_rank_in_cluster: Int32, *, loc=None, ip=None
+) -> Int32:
+    """Map the given smem pointer to the address at another CTA rank in the cluster."""
+    smem_ptr_i32 = smem_ptr.toint(loc=loc, ip=ip).ir_value()
+    return Int32(
+        llvm.inline_asm(
+            T.i32(),
+            [smem_ptr_i32, peer_cta_rank_in_cluster.ir_value()],
+            "mapa.shared::cluster.u32 $0, $1, $2;",
+            "=r,r,r",
+            has_side_effects=False,
+            is_align_stack=False,
+        )
+    )
+
+
+@dsl_user_op
+def store_shared_remote(
+    val: float | Float32 | Int32 | cutlass.Int64,
+    smem_ptr: cute.Pointer,
+    mbar_ptr: cute.Pointer,
+    peer_cta_rank_in_cluster: cute.typing.Int,
+    *,
+    loc=None,
+    ip=None,
+) -> None:
+    remote_smem_ptr_i32 = set_block_rank(
+        smem_ptr, peer_cta_rank_in_cluster, loc=loc, ip=ip
+    ).ir_value()
+    remote_mbar_ptr_i32 = set_block_rank(
+        mbar_ptr, peer_cta_rank_in_cluster, loc=loc, ip=ip
+    ).ir_value()
+    if const_expr(isinstance(val, float)):
+        val = Float32(val)
+    assert isinstance(val, (Float32, Int32, cutlass.Int64)), "val must be Float32, Int32, or Int64"
+    suffix = {Float32: "f32", Int32: "s32", cutlass.Int64: "s64"}[type(val)]
+    constraint = {Float32: "f", Int32: "r", cutlass.Int64: "l"}[type(val)]
+    llvm.inline_asm(
+        None,
+        [remote_smem_ptr_i32, val.ir_value(loc=loc, ip=ip), remote_mbar_ptr_i32],
+        f"st.async.shared::cluster.mbarrier::complete_tx::bytes.{suffix} [$0], $1, [$2];",
+        f"r,{constraint},r",
+        has_side_effects=True,
+        is_align_stack=False,
+    )
+
+
+@dsl_user_op
+def store_shared_remote_x4(
+    val0: Float32 | Int32,
+    val1: Float32 | Int32,
+    val2: Float32 | Int32,
+    val3: Float32 | Int32,
+    smem_ptr: cute.Pointer,
+    mbar_ptr: cute.Pointer,
+    peer_cta_rank_in_cluster: cute.typing.Int,
+    *,
+    loc=None,
+    ip=None,
+) -> None:
+    remote_smem_ptr_i32 = set_block_rank(
+        smem_ptr, peer_cta_rank_in_cluster, loc=loc, ip=ip
+    ).ir_value()
+    remote_mbar_ptr_i32 = set_block_rank(
+        mbar_ptr, peer_cta_rank_in_cluster, loc=loc, ip=ip
+    ).ir_value()
+    assert isinstance(val0, (Float32, Int32)), "val must be Float32, or Int32"
+    dtype = Float32 if isinstance(val0, Float32) else Int32
+    suffix = {Float32: "f32", Int32: "s32"}[dtype]
+    constraint = {Float32: "f", Int32: "r"}[dtype]
+    llvm.inline_asm(
+        None,
+        [
+            remote_smem_ptr_i32,
+            remote_mbar_ptr_i32,
+            dtype(val0).ir_value(loc=loc, ip=ip),
+            dtype(val1).ir_value(loc=loc, ip=ip),
+            dtype(val2).ir_value(loc=loc, ip=ip),
+            dtype(val3).ir_value(loc=loc, ip=ip),
+        ],
+        "{\n\t"
+        f".reg .v4 .{suffix} abcd;\n\t"
+        f"mov.{suffix} abcd.x, $2;\n\t"
+        f"mov.{suffix} abcd.y, $3;\n\t"
+        f"mov.{suffix} abcd.z, $4;\n\t"
+        f"mov.{suffix} abcd.w, $5;\n\t"
+        f"st.async.shared::cluster.mbarrier::complete_tx::bytes.v4.{suffix} [$0], abcd, [$1];\n\t"
+        "}\n",
+        f"r,r,{constraint},{constraint},{constraint},{constraint}",
+        has_side_effects=True,
+        is_align_stack=False,
+    )
+
+
+@dsl_user_op
+def fmin(a: Union[float, Float32], b: Union[float, Float32], *, loc=None, ip=None) -> Float32:
+    if cutlass.const_expr(cutlass.CUDA_VERSION.major) == 12:
+        return Float32(
+            nvvm.fmin(
+                T.f32(),
+                Float32(a).ir_value(loc=loc, ip=ip),
+                Float32(b).ir_value(loc=loc, ip=ip),
+                loc=loc,
+                ip=ip,
+            )
+        )
+    return Float32(
+        nvvm.fmin(
+            Float32(a).ir_value(loc=loc, ip=ip),
+            Float32(b).ir_value(loc=loc, ip=ip),
+            loc=loc,
+            ip=ip,
+        )
+    )
+
+
+@dsl_user_op
+def sqrt(a: float | Float32, *, loc=None, ip=None) -> Float32:
+    return Float32(
+        llvm.inline_asm(
+            T.f32(),
+            [Float32(a).ir_value(loc=loc, ip=ip)],
+            "sqrt.approx.f32 $0, $1;",
+            "=f,f",
+            has_side_effects=False,
+            is_align_stack=False,
+        )
+    )
+
+
+@dsl_user_op
+def ceil(a: float | Float32, *, loc=None, ip=None) -> Int32:
+    return Int32(
+        llvm.inline_asm(
+            T.i32(),
+            [Float32(a).ir_value(loc=loc, ip=ip)],
+            "cvt.rpi.ftz.s32.f32 $0, $1;",
+            "=r,f",
+            has_side_effects=False,
+            is_align_stack=False,
+        )
+    )
+
+
+@cute.jit
+def fill_oob(tXsX: cute.Tensor, tXpX: Optional[cute.Tensor], fill_value: cute.Numeric) -> None:
+    """Fill out-of-bounds values in shared memory tensor.
+
+    Args:
+        tXsX: Shared memory tensor to fill
+        tXpX: Predicate tensor indicating valid elements
+        fill_value: Value to fill OOB locations with
+    """
+    tXrX_fill = cute.make_rmem_tensor_like(tXsX[(None, 0), None, 0])
+    tXrX_fill.fill(fill_value)
+    for rest_v in cutlass.range_constexpr(tXsX.shape[0][1]):
+        for rest_k in cutlass.range_constexpr(tXsX.shape[2]):
+            if const_expr(tXpX is not None):
+                if not tXpX[rest_v, 0, rest_k]:
+                    cute.autovec_copy(tXrX_fill, tXsX[(None, rest_v), None, rest_k])
+            else:
+                cute.autovec_copy(tXrX_fill, tXsX[(None, rest_v), None, rest_k])
+
+
+# ---------------------------------------------------------------------------
+# General-purpose DSL store / vector helpers
+# ---------------------------------------------------------------------------
+
+
+@dsl_user_op
+def make_vector(elem_type, *values, loc=None, ip=None):
+    """Build an MLIR vector  from N scalar DSL values.
+
+    Example: make_vector(cutlass.Uint32, v0, v1) -> <2 x i32> MLIR vector
+    """
+    from cutlass._mlir import ir
+
+    n = len(values)
+    mlir_ty = elem_type.mlir_type
+    vec_ty = ir.VectorType.get([n], mlir_ty)
+    vec = llvm.mlir_undef(vec_ty, loc=loc, ip=ip)
+    for i, v in enumerate(values):
+        vec = vector.insertelement(
+            elem_type(v).ir_value(loc=loc, ip=ip),
+            vec,
+            position=_arith.constant(T.i32(), i, loc=loc, ip=ip),
+            loc=loc,
+            ip=ip,
+        )
+    return vec
+
+
+@dsl_user_op
+def f32x2_to_i64(a: Float32, b: Float32, *, loc=None, ip=None) -> cutlass.Int64:
+    vec_f32x2 = vector.from_elements(
+        T.vector(2, T.f32()), (a.ir_value(), b.ir_value()), loc=loc, ip=ip
+    )
+    vec_i64x1 = vector.bitcast(T.vector(1, T.i64()), vec_f32x2)
+    res = cutlass.Int64(
+        vector.extract(vec_i64x1, dynamic_position=[], static_position=[0], loc=loc, ip=ip)
+    )
+    return res
+
+
+@dsl_user_op
+def i64_to_f32x2(c: cutlass.Int64, *, loc=None, ip=None) -> Tuple[Float32, Float32]:
+    vec_i64x1 = vector.from_elements(T.vector(1, T.i64()), (c.ir_value(),), loc=loc, ip=ip)
+    vec_f32x2 = vector.bitcast(T.vector(2, T.f32()), vec_i64x1)
+    res0 = Float32(
+        vector.extract(vec_f32x2, dynamic_position=[], static_position=[0], loc=loc, ip=ip)
+    )
+    res1 = Float32(
+        vector.extract(vec_f32x2, dynamic_position=[], static_position=[1], loc=loc, ip=ip)
+    )
+    return res0, res1
+
+
+@cute.jit
+def warp_prefix_sum(val: Int32, lane: Optional[Int32] = None) -> Int32:
+    if const_expr(lane is None):
+        lane = cute.arch.lane_idx()
+    for i in cutlass.range_constexpr(int(math.log2(cute.arch.WARP_SIZE))):
+        offset = 1 << i
+        # Very important that we set mask_and_clamp to 0
+        partial_sum = cute.arch.shuffle_sync_up(val, offset=offset, mask_and_clamp=0)
+        if lane >= offset:
+            val += partial_sum
+    return val
+
+
+@dsl_user_op
+def atomic_inc_i32(a: int | Int32, gmem_ptr: cute.Pointer, *, loc=None, ip=None) -> Int32:
+    from cutlass import CUDA_VERSION
+
+    # * NVVM call based on nvvm version
+    if CUDA_VERSION.major == 12 and CUDA_VERSION.minor == 9:
+        # Old API: requires explicit result type as first positional argument
+        return nvvm.atomicrmw(
+            res=T.i32(), op=nvvm.AtomicOpKind.INC, ptr=gmem_ptr.llvm_ptr, a=Int32(a).ir_value()
+        )
+    else:
+        # New API: infers result type automatically
+        return nvvm.atomicrmw(
+            op=nvvm.AtomicOpKind.INC, ptr=gmem_ptr.llvm_ptr, a=Int32(a).ir_value()
+        )
+
+
+@dsl_user_op
+def atomic_add_i32(a: int | Int32, gmem_ptr: cute.Pointer, *, loc=None, ip=None) -> Int32:
+    from cutlass import CUDA_VERSION
+
+    # * NVVM call based on nvvm version
+    if CUDA_VERSION.major == 12 and CUDA_VERSION.minor == 9:
+        # Old API: requires explicit result type as first positional argument
+        return nvvm.atomicrmw(
+            res=T.i32(), op=nvvm.AtomicOpKind.ADD, ptr=gmem_ptr.llvm_ptr, a=Int32(a).ir_value()
+        )
+    else:
+        # New API: infers result type automatically
+        return nvvm.atomicrmw(
+            op=nvvm.AtomicOpKind.ADD, ptr=gmem_ptr.llvm_ptr, a=Int32(a).ir_value()
+        )
+
+
+@dsl_user_op
+def issue_clc_query_nomulticast(
+    mbar_ptr: cute.Pointer,
+    clc_response_ptr: cute.Pointer,
+    loc=None,
+    ip=None,
+) -> None:
+    """
+    The clusterlaunchcontrol.try_cancel instruction requests atomically cancelling the launch
+    of a cluster that has not started running yet. It asynchronously writes an opaque response
+    to shared memory indicating whether the operation succeeded or failed. On success, the
+    opaque response contains the ctaid of the first CTA of the canceled cluster.
+
+    :param mbar_ptr: A pointer to the mbarrier address in SMEM
+    :type mbar_ptr:  Pointer
+    :param clc_response_ptr: A pointer to the cluster launch control response address in SMEM
+    :type clc_response_ptr:  Pointer
+    """
+    mbar_llvm_ptr = mbar_ptr.llvm_ptr
+    clc_response_llvm_ptr = clc_response_ptr.llvm_ptr
+    nvvm.clusterlaunchcontrol_try_cancel(
+        clc_response_llvm_ptr,
+        mbar_llvm_ptr,
+        loc=loc,
+        ip=ip,
+    )
+
+
+@dsl_user_op
+def domain_offset_aligned(
+    coord: cute.Coord, tensor: cute.Tensor, *, loc=None, ip=None
+) -> cute.Tensor:
+    assert isinstance(tensor.iterator, cute.Pointer)
+    # We assume that applying the offset does not change the pointer alignment
+    new_ptr = cute.make_ptr(
+        tensor.element_type,
+        elem_pointer(tensor, coord).toint(),
+        tensor.memspace,
+        assumed_align=tensor.iterator.alignment,
+    )
+    return cute.make_tensor(new_ptr, tensor.layout)
diff --git a/.venv/lib/python3.12/site-packages/torch/_vendor/quack/varlen_utils.py b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/varlen_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8a45aa47434992668b42639ede52f3ba4681f69
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vendor/quack/varlen_utils.py
@@ -0,0 +1,226 @@
+# Copyright (c) 2025, Tri Dao.
+
+from typing import Optional, NamedTuple
+from dataclasses import dataclass
+
+import cutlass
+import cutlass.cute as cute
+from cutlass import Int32, Boolean, const_expr
+
+from . import copy_utils
+from .cute_dsl_utils import mlir_namedtuple
+
+
+# Grouping arguments together that should be passed to __call__
+@mlir_namedtuple
+class VarlenArguments(NamedTuple):
+    mCuSeqlensM: Optional[cute.Tensor] = None
+    mCuSeqlensK: Optional[cute.Tensor] = None
+    mAIdx: Optional[cute.Tensor] = None
+
+
+class VarlenManager:
+    @dataclass
+    class Params:
+        cu_seqlens_m: Optional[cute.Tensor] = None
+        cu_seqlens_k: Optional[cute.Tensor] = None
+        mAIdx: Optional[cute.Tensor] = None
+
+        @staticmethod
+        @cute.jit
+        def create(args: VarlenArguments, *, loc=None, ip=None) -> "VarlenManager.Params":
+            return VarlenManager.Params(
+                cu_seqlens_m=args.mCuSeqlensM,
+                cu_seqlens_k=args.mCuSeqlensK,
+                mAIdx=args.mAIdx,
+            )
+
+    def __init__(
+        self,
+        params: Params,
+        len_m_static: Int32,
+        len_k_static: Int32,
+        last_batch_idx: Int32 = Int32(-1),
+        is_group_changed: Boolean = Boolean(True),
+        *,
+        loc=None,
+        ip=None,
+    ):
+        self.params = params
+        self._len_m_static = len_m_static
+        self._len_k_static = len_k_static
+        self._last_batch_idx = last_batch_idx
+        self._is_group_changed = is_group_changed
+        self.varlen_m = const_expr(params.cu_seqlens_m is not None)
+        self.varlen_k = const_expr(params.cu_seqlens_k is not None)
+        self.gather_A = const_expr(params.mAIdx is not None)
+        self._loc = loc
+        self._ip = ip
+
+    @staticmethod
+    def to_underlying_arguments(args: VarlenArguments, *, loc=None, ip=None) -> Params:
+        assert not (args.mCuSeqlensM is not None and args.mCuSeqlensK is not None), (
+            "Only support either varlen_m or varlen_k"
+        )
+        return VarlenManager.Params.create(args, loc=loc, ip=ip)
+
+    @staticmethod
+    @cute.jit
+    def create(
+        params: Params,
+        len_m_static: Int32,
+        len_k_static: Int32,
+        *,
+        loc=None,
+        ip=None,
+    ) -> "VarlenManager":
+        return VarlenManager(params, len_m_static=len_m_static, len_k_static=len_k_static)
+
+    def len_m(self, batch_idx: Int32) -> Int32:
+        if const_expr(self.varlen_m):
+            return self.params.cu_seqlens_m[batch_idx + 1] - self.params.cu_seqlens_m[batch_idx]
+        else:
+            return self._len_m_static
+
+    def len_k(self, batch_idx: Int32) -> Int32:
+        if const_expr(self.varlen_k):
+            return self.params.cu_seqlens_k[batch_idx + 1] - self.params.cu_seqlens_k[batch_idx]
+        else:
+            return self._len_k_static
+
+    def offset_batch_A(self, mA_mkl: cute.Tensor, batch_idx: Int32) -> cute.Tensor:
+        params = self.params
+        if const_expr(self.varlen_m):
+            mA_mk = cute.domain_offset((params.cu_seqlens_m[batch_idx], None), mA_mkl)
+        elif const_expr(self.varlen_k):
+            offset = params.cu_seqlens_k[batch_idx]
+            ragged_rank = const_expr(cute.rank(mA_mkl))
+            if const_expr(ragged_rank == 2):  # Didn't create ragged tensor
+                mA_mk = cute.domain_offset((None, offset), mA_mkl)
+            else:
+                length = params.cu_seqlens_k[batch_idx + 1] - offset
+                # rank 3 = 1-extra-dim (ptr_shift), rank 4 = 2-extra-dim
+                ptr_shift = const_expr(ragged_rank == 3)
+                mA_mk = copy_utils.offset_ragged_tensor(
+                    mA_mkl,
+                    offset,
+                    length,
+                    ragged_dim=1,
+                    ptr_shift=ptr_shift,
+                )
+        else:
+            mA_mk = mA_mkl[None, None, batch_idx]
+        return mA_mk
+
+    def offset_batch_AIdx(self, batch_idx: Int32) -> cute.Tensor:
+        params = self.params
+        if const_expr(self.varlen_m):
+            mAIdx_mk = cute.domain_offset((params.cu_seqlens_m[batch_idx],), params.mAIdx)
+        elif const_expr(self.varlen_k):
+            mAIdx_mk = cute.domain_offset((params.cu_seqlens_k[batch_idx],), params.mAIdx)
+        else:
+            mAIdx_mk = params.mAIdx[None, batch_idx]
+        return mAIdx_mk
+
+    def offset_batch_SFA(self, mSFA_mkl: cute.Tensor, batch_idx: Int32) -> cute.Tensor:
+        """Offset SFA by padded per-expert offset (dQaccum-style).
+
+        The padded offset, in tile units (128 source-M or source-K per tile),
+        is simply `cu_seqlens[b] // 128 + b`. (Algebraically identical to
+        `(cu_seqlens[b] + b*128) // 128 * 128` / 128.) We pass it as a
+        compound coord `(0, offset_tile)` to `domain_offset` so the outer
+        rm/rk mode is shifted in tile units — no `* 128` needed, and the
+        compiler sees the tile alignment natively.
+        """
+        params = self.params
+        tile = 128
+        if const_expr(self.varlen_m):
+            offset_tile = params.cu_seqlens_m[batch_idx] // tile + batch_idx
+            return cute.domain_offset(((0, offset_tile), None), mSFA_mkl)
+        elif const_expr(self.varlen_k):
+            offset_tile = params.cu_seqlens_k[batch_idx] // tile + batch_idx
+            return cute.domain_offset((None, (0, offset_tile)), mSFA_mkl)
+        else:
+            return mSFA_mkl[None, None, batch_idx]
+
+    def offset_batch_SFB(self, mSFB_nkl: cute.Tensor, batch_idx: Int32) -> cute.Tensor:
+        """Offset SFB by padded per-expert K offset (varlen_k only)."""
+        params = self.params
+        tile = 128
+        if const_expr(self.varlen_k):
+            offset_tile = params.cu_seqlens_k[batch_idx] // tile + batch_idx
+            return cute.domain_offset((None, (0, offset_tile)), mSFB_nkl)
+        else:
+            return mSFB_nkl[None, None, batch_idx]
+
+    def offset_batch_B(self, mB_nkl: cute.Tensor, batch_idx: Int32) -> cute.Tensor:
+        params = self.params
+        if const_expr(self.varlen_k):
+            offset = params.cu_seqlens_k[batch_idx]
+            ragged_rank = const_expr(cute.rank(mB_nkl))
+            if const_expr(ragged_rank == 2):  # Didn't create ragged tensor
+                mB_nk = cute.domain_offset((None, offset), mB_nkl)
+            else:
+                length = params.cu_seqlens_k[batch_idx + 1] - offset
+                ptr_shift = const_expr(ragged_rank == 3)
+                mB_nk = copy_utils.offset_ragged_tensor(
+                    mB_nkl,
+                    offset,
+                    length,
+                    ragged_dim=1,
+                    ptr_shift=ptr_shift,
+                )
+        else:
+            mB_nk = mB_nkl[None, None, batch_idx]
+        return mB_nk
+
+    def offset_batch_epi(self, mD_mnl: cute.Tensor, batch_idx: Int32) -> cute.Tensor:
+        params = self.params
+        if const_expr(self.varlen_m):
+            offset = params.cu_seqlens_m[batch_idx]
+            ragged_rank = const_expr(cute.rank(mD_mnl))
+            if const_expr(ragged_rank == 2):  # Didn't create ragged tensor
+                mD_mn = cute.domain_offset((offset, None), mD_mnl)
+            else:
+                length = params.cu_seqlens_m[batch_idx + 1] - offset
+                ptr_shift = const_expr(ragged_rank == 3)
+                mD_mn = copy_utils.offset_ragged_tensor(
+                    mD_mnl,
+                    offset,
+                    length,
+                    ragged_dim=0,
+                    ptr_shift=ptr_shift,
+                )
+        else:
+            mD_mn = mD_mnl[None, None, batch_idx]
+        return mD_mn
+
+    def __extract_mlir_values__(self):
+        values, self._values_pos = [], []
+        for obj in [
+            self.params,
+            self._len_m_static,
+            self._len_k_static,
+            self._last_batch_idx,
+            self._is_group_changed,
+        ]:
+            obj_values = cutlass.extract_mlir_values(obj)
+            values += obj_values
+            self._values_pos.append(len(obj_values))
+        return values
+
+    def __new_from_mlir_values__(self, values):
+        obj_list = []
+        for obj, n_items in zip(
+            [
+                self.params,
+                self._len_m_static,
+                self._len_k_static,
+                self._last_batch_idx,
+                self._is_group_changed,
+            ],
+            self._values_pos,
+        ):
+            obj_list.append(cutlass.new_from_mlir_values(obj, values[:n_items]))
+            values = values[n_items:]
+        return self.__class__(*(tuple(obj_list)), loc=self._loc)
diff --git a/.venv/lib/python3.12/site-packages/torch/_vmap_internals.py b/.venv/lib/python3.12/site-packages/torch/_vmap_internals.py
new file mode 100644
index 0000000000000000000000000000000000000000..a45dd91ea20418aa444b61ca8f32ec0b663f12f7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_vmap_internals.py
@@ -0,0 +1,246 @@
+# mypy: allow-untyped-defs
+import functools
+from collections.abc import Callable
+from typing import Any
+from typing_extensions import deprecated
+
+import torch
+from torch import Tensor
+from torch.utils._pytree import _broadcast_to_and_flatten, tree_flatten, tree_unflatten
+
+
+in_dims_t = int | tuple
+out_dims_t = int | tuple[int, ...]
+
+
+# Checks that all args-to-be-batched have the same batch dim size
+def _validate_and_get_batch_size(
+    flat_in_dims: list[int | None],
+    flat_args: list,
+) -> int:
+    batch_sizes = [
+        arg.size(in_dim)
+        for in_dim, arg in zip(flat_in_dims, flat_args)
+        if in_dim is not None
+    ]
+    if batch_sizes and any(size != batch_sizes[0] for size in batch_sizes):
+        raise ValueError(
+            f"vmap: Expected all tensors to have the same size in the mapped "
+            f"dimension, got sizes {batch_sizes} for the mapped dimension"
+        )
+    return batch_sizes[0]
+
+
+def _num_outputs(batched_outputs: Tensor | tuple[Tensor, ...]) -> int:
+    if isinstance(batched_outputs, tuple):
+        return len(batched_outputs)
+    return 1
+
+
+# If value is a tuple, check it has length `num_elements`.
+# If value is not a tuple, make a tuple with `value` repeated `num_elements` times
+def _as_tuple(
+    value: Any,
+    num_elements: int,
+    error_message_lambda: Callable[[], str],
+) -> tuple:
+    if not isinstance(value, tuple):
+        return (value,) * num_elements
+    if len(value) != num_elements:
+        raise ValueError(error_message_lambda())
+    return value
+
+
+# Creates BatchedTensors for every Tensor in arg that should be batched.
+# Returns the (potentially) batched arguments and the batch_size.
+def _create_batched_inputs(
+    in_dims: in_dims_t,
+    args: tuple,
+    vmap_level: int,
+    func: Callable,
+) -> tuple[tuple, int]:
+    if not isinstance(in_dims, int) and not isinstance(in_dims, tuple):
+        raise ValueError(
+            f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): "
+            f"expected `in_dims` to be int or a (potentially nested) tuple "
+            f"matching the structure of inputs, got: {type(in_dims)}."
+        )
+    if len(args) == 0:
+        raise ValueError(
+            f"vmap({_get_name(func)})(): got no inputs. Maybe you forgot to add "
+            f"inputs, or you are trying to vmap over a function with no inputs. "
+            f"The latter is unsupported."
+        )
+
+    flat_args, args_spec = tree_flatten(args)
+    flat_in_dims = _broadcast_to_and_flatten(in_dims, args_spec)
+    if flat_in_dims is None:
+        raise ValueError(
+            f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): "
+            f"in_dims is not compatible with the structure of `inputs`. "
+            f"in_dims has structure {tree_flatten(in_dims)[1]} but inputs "
+            f"has structure {args_spec}."
+        )
+
+    for arg, in_dim in zip(flat_args, flat_in_dims):
+        if not isinstance(in_dim, int) and in_dim is not None:
+            raise ValueError(
+                f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): "
+                f"Got in_dim={in_dim} for an input but in_dim must be either "
+                f"an integer dimension or None."
+            )
+        if isinstance(in_dim, int) and not isinstance(arg, Tensor):
+            raise ValueError(
+                f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): "
+                f"Got in_dim={in_dim} for an input but the input is of type "
+                f"{type(arg)}. We cannot vmap over non-Tensor arguments, "
+                f"please use None as the respective in_dim"
+            )
+        if in_dim is not None and (in_dim < 0 or in_dim >= arg.dim()):
+            raise ValueError(
+                f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): "
+                f"Got in_dim={in_dim} for some input, but that input is a Tensor "
+                f"of dimensionality {arg.dim()} so expected in_dim to satisfy "
+                f"0 <= in_dim < {arg.dim()}."
+            )
+
+    batch_size = _validate_and_get_batch_size(flat_in_dims, flat_args)
+    # See NOTE [Ignored _remove_batch_dim, _add_batch_dim]
+    batched_inputs = [
+        arg if in_dim is None else torch._add_batch_dim(arg, in_dim, vmap_level)
+        for in_dim, arg in zip(flat_in_dims, flat_args)
+    ]
+    return tree_unflatten(batched_inputs, args_spec), batch_size
+
+
+# Undoes the batching (and any batch dimensions) associated with the `vmap_level`.
+def _unwrap_batched(
+    batched_outputs: Tensor | tuple[Tensor, ...],
+    out_dims: out_dims_t,
+    vmap_level: int,
+    batch_size: int,
+    func: Callable,
+    allow_none_pass_through: bool = False,
+) -> tuple:
+    num_outputs = _num_outputs(batched_outputs)
+    out_dims_as_tuple = _as_tuple(
+        out_dims,
+        num_outputs,
+        lambda: f"vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must "
+        f"have one dim per output (got {num_outputs} outputs) of {_get_name(func)}.",
+    )
+
+    # NOTE [Ignored _remove_batch_dim, _add_batch_dim]
+    # There is something wrong with our type bindings for functions that begin
+    # with '_', see #40397.
+    if isinstance(batched_outputs, Tensor):
+        out_dim = out_dims_as_tuple[0]
+        return torch._remove_batch_dim(batched_outputs, vmap_level, batch_size, out_dim)  # type: ignore[return-value]
+    if allow_none_pass_through:
+        return tuple(
+            (
+                torch._remove_batch_dim(out, vmap_level, batch_size, out_dim)
+                if out is not None
+                else None
+            )
+            for out, out_dim in zip(batched_outputs, out_dims_as_tuple)
+        )
+    else:
+        return tuple(
+            torch._remove_batch_dim(out, vmap_level, batch_size, out_dim)
+            for out, out_dim in zip(batched_outputs, out_dims_as_tuple)
+        )
+
+
+# Checks that `fn` returned one or more Tensors and nothing else.
+# NB: A python function that return multiple arguments returns a single tuple,
+# so we are effectively checking that `outputs` is a single Tensor or a tuple of
+# Tensors.
+def _validate_outputs(outputs: Any, func: Callable) -> None:
+    if isinstance(outputs, Tensor):
+        return
+    if not isinstance(outputs, tuple):
+        raise ValueError(
+            f"vmap({_get_name(func)}, ...): `{_get_name(func)}` must only return "
+            f"Tensors, got type {type(outputs)} as the return."
+        )
+    for idx, output in enumerate(outputs):
+        if isinstance(output, Tensor):
+            continue
+        raise ValueError(
+            f"vmap({_get_name(func)}, ...): `{_get_name(func)}` must only return "
+            f"Tensors, got type {type(output)} for return {idx}."
+        )
+
+
+def _check_out_dims_is_int_or_int_tuple(out_dims: out_dims_t, func: Callable) -> None:
+    if isinstance(out_dims, int):
+        return
+    if not isinstance(out_dims, tuple) or not all(
+        isinstance(out_dim, int) for out_dim in out_dims
+    ):
+        raise ValueError(
+            f"vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must be "
+            f"an int or a tuple of int representing where in the outputs the "
+            f"vmapped dimension should appear."
+        )
+
+
+def _get_name(func: Callable):
+    if hasattr(func, "__name__"):
+        return func.__name__
+
+    # Not all callables have __name__, in fact, only static functions/methods do.
+    # A callable created via functools.partial or an nn.Module, to name some
+    # examples, don't have a __name__.
+    return repr(func)
+
+
+# vmap(func)(inputs) wraps all Tensor inputs to be batched in BatchedTensors,
+# sends those into func, and then unwraps the output BatchedTensors. Operations
+# on BatchedTensors perform the batched operations that the user is asking for.
+@deprecated(
+    "Please use `torch.vmap` instead of `torch._vmap_internals.vmap`.",
+    category=FutureWarning,
+)
+def vmap(func: Callable, in_dims: in_dims_t = 0, out_dims: out_dims_t = 0) -> Callable:
+    """
+    Please use torch.vmap instead of this API.
+    """
+    return _vmap(func, in_dims, out_dims)
+
+
+# A version of vmap but without the initial "experimental prototype" warning
+def _vmap(
+    func: Callable,
+    in_dims: in_dims_t = 0,
+    out_dims: out_dims_t = 0,
+    allow_none_pass_through: bool = False,
+) -> Callable:
+    # The `allow_none_pass_through` argument is a temporary workaround may be removed.
+    # Currently it enables us to wrap the call in `autograd.grad` to the autograd engine,
+    # which may return None if any of the inputs are unused. See the issue discussing this:
+    # https://github.com/pytorch/functorch/issues/159.
+    @functools.wraps(func)
+    def wrapped(*args):
+        _check_out_dims_is_int_or_int_tuple(out_dims, func)
+        vmap_level = torch._C._vmapmode_increment_nesting()
+        try:
+            batched_inputs, batch_size = _create_batched_inputs(
+                in_dims, args, vmap_level, func
+            )
+            batched_outputs = func(*batched_inputs)
+            if not allow_none_pass_through:
+                _validate_outputs(batched_outputs, func)
+            return _unwrap_batched(
+                batched_outputs,
+                out_dims,
+                vmap_level,
+                batch_size,
+                func,
+                allow_none_pass_through=allow_none_pass_through,
+            )
+        finally:
+            torch._C._vmapmode_decrement_nesting()
+
+    return wrapped
diff --git a/.venv/lib/python3.12/site-packages/torch/_weights_only_unpickler.py b/.venv/lib/python3.12/site-packages/torch/_weights_only_unpickler.py
new file mode 100644
index 0000000000000000000000000000000000000000..c51ee86836b62332d0fd429144107981d1c1ea6c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/_weights_only_unpickler.py
@@ -0,0 +1,593 @@
+# mypy: allow-untyped-defs
+# Unpickler restricted to loading only state dicts
+# Restrict constructing types to a list defined in _get_allowed_globals()
+# Restrict BUILD operation to `Tensor`, `Parameter` and `OrderedDict` types only
+# Restrict APPEND/APPENDS to `list` (and allowlisted list subclasses)
+# In `GLOBALS` operation do not do class lookup by name, but rather rely on dictionary
+# defined by `_get_allowed_globals()` method, that contains:
+# - torch types (Storage, dtypes, Tensor, `torch.Size`),
+# - `torch._utils._rebuild` functions.
+# - `torch.nn.Parameter`
+# - `collections.Counter`
+# - `collections.OrderedDict`
+# Additionally, users can use an allowlist for adding classes they have deemed as safe using
+# `_add_safe_globals()` (`torch.serialization.add_safe_globals`)
+# `_clear_safe_globals()` (`torch.serialization.clear_safe_globals`)
+# `_get_safe_globals()` (`torch.serialization.get_safe_globals`)
+
+# Based of https://github.com/python/cpython/blob/main/Lib/pickle.py
+# Expected to be useful for loading PyTorch model weights
+# For example:
+# data = urllib.request.urlopen('https://download.pytorch.org/models/resnet50-0676ba61.pth').read()
+# buf = io.BytesIO(data)
+# weights = torch.load(buf, weights_only = True)
+
+import functools as _functools
+import warnings
+
+from _codecs import encode
+from collections import Counter, OrderedDict
+from collections.abc import Callable
+from pickle import (
+    APPEND,
+    APPENDS,
+    BINFLOAT,
+    BINGET,
+    BININT,
+    BININT1,
+    BININT2,
+    BINPERSID,
+    BINPUT,
+    BINUNICODE,
+    BUILD,
+    bytes_types,
+    decode_long,
+    EMPTY_DICT,
+    EMPTY_LIST,
+    EMPTY_SET,
+    EMPTY_TUPLE,
+    GLOBAL,
+    LONG1,
+    LONG_BINGET,
+    LONG_BINPUT,
+    MARK,
+    NEWFALSE,
+    NEWOBJ,
+    NEWTRUE,
+    NONE,
+    PROTO,
+    REDUCE,
+    SETITEM,
+    SETITEMS,
+    SHORT_BINSTRING,
+    STOP,
+    TUPLE,
+    TUPLE1,
+    TUPLE2,
+    TUPLE3,
+    UnpicklingError,
+)
+from struct import unpack
+from sys import maxsize
+from typing import Any
+
+import torch
+from torch._utils import _sparse_tensors_to_validate, IMPORT_MAPPING, NAME_MAPPING
+
+
+# modules in this list are never allowed, even if the user attempts to allowlist
+# functions/classes from them
+_blocklisted_modules = [
+    "sys",
+    "os",
+    "posix",
+    "nt",
+]
+
+_marked_safe_globals_set: set[Callable | tuple[Callable, str]] = set()
+
+
+def _add_safe_globals(safe_globals: list[Callable | tuple[Callable, str]]):
+    global _marked_safe_globals_set
+    _marked_safe_globals_set = _marked_safe_globals_set.union(set(safe_globals))
+
+
+def _get_safe_globals() -> list[Callable | tuple[Callable, str]]:
+    global _marked_safe_globals_set
+    return list(_marked_safe_globals_set)
+
+
+def _clear_safe_globals():
+    global _marked_safe_globals_set
+    _marked_safe_globals_set = set()
+
+
+def _remove_safe_globals(
+    globals_to_remove: list[Callable | tuple[Callable, str]],
+):
+    global _marked_safe_globals_set
+    _marked_safe_globals_set = _marked_safe_globals_set - set(globals_to_remove)
+
+
+class _safe_globals:
+    def __init__(self, safe_globals: list[Callable | tuple[Callable, str]]):
+        self.safe_globals = safe_globals
+
+    def __enter__(self):
+        _add_safe_globals(self.safe_globals)
+
+    def __exit__(self, type, value, tb):
+        _remove_safe_globals(self.safe_globals)
+
+
+# Separate from _get_allowed_globals because of the lru_cache on _get_allowed_globals
+# For example if user had a script like
+#   torch.load(file_a)
+#   torch.serialization._add_safe_globals([torch.foo])
+#   torch.load(file_b)
+# the dynamic additions to safe_globals would not be picked up by
+# _get_allowed_globals due to the lru_cache
+def _get_user_allowed_globals():
+    rc: dict[str, Any] = {}
+    for f in _marked_safe_globals_set:
+        if isinstance(f, tuple):
+            if len(f) != 2:
+                raise ValueError(
+                    f"Expected tuple of length 2 (global, str of callable full path), but got tuple of length: {len(f)}"
+                )
+            if type(f[1]) is not str:
+                raise TypeError(
+                    f"Expected second item in tuple to be str of callable full path, but got: {type(f[1])}"
+                )
+            f, name = f
+            rc[name] = f
+        else:
+            module, name = f.__module__, f.__qualname__
+            rc[f"{module}.{name}"] = f
+    return rc
+
+
+def _tensor_rebuild_functions():
+    return {
+        torch._utils._rebuild_parameter,
+        torch._utils._rebuild_parameter_with_state,
+        torch._utils._rebuild_qtensor,
+        torch._utils._rebuild_tensor,
+        torch._utils._rebuild_tensor_v2,
+        torch._utils._rebuild_tensor_v3,
+        torch._utils._rebuild_sparse_tensor,
+        torch._utils._rebuild_meta_tensor_no_storage,
+        torch._utils._rebuild_nested_tensor,
+        torch._utils._rebuild_wrapper_subclass,
+        # Allowlisting this, but not allowlisting the numpy functions by default
+        # Reasoning is that we don't have control over the numpy functions, but
+        # this utility is provided by pytorch
+        torch._utils._rebuild_device_tensor_from_numpy,
+        # In 2.6, we should no longer have a dependency on numpy and the above
+        # _rebuild_device_tensor_from_numpy function.
+        torch._utils._rebuild_device_tensor_from_cpu_tensor,
+    }
+
+
+# Unpickling machinery
+@_functools.lru_cache(maxsize=1)
+def _get_allowed_globals():
+    rc: dict[str, Any] = {
+        "collections.OrderedDict": OrderedDict,
+        "collections.Counter": Counter,
+        "torch.nn.parameter.Parameter": torch.nn.Parameter,
+        "torch.serialization._get_layout": torch.serialization._get_layout,
+        "torch.Size": torch.Size,
+        "torch.Tensor": torch.Tensor,
+        "torch.device": torch.device,
+        "_codecs.encode": encode,  # for bytes
+        "builtins.bytearray": bytearray,  # for bytearray
+        "builtins.set": set,  # for set
+        "builtins.complex": complex,  # for complex
+    }
+
+    # dtype
+    for t in torch.storage._dtype_to_storage_type_map():
+        rc[str(t)] = t
+    for t in torch.storage._new_dtypes():
+        rc[str(t)] = t
+    for t in [getattr(torch, f"uint{x}") for x in range(1, 8)]:
+        rc[str(t)] = t
+    for t in [getattr(torch, f"int{x}") for x in range(1, 8)]:
+        rc[str(t)] = t
+
+    # Tensor classes
+    for tt in torch._tensor_classes:
+        rc[f"{tt.__module__}.{tt.__name__}"] = tt
+    # Storage classes
+    for ts in torch._storage_classes:
+        if ts not in (torch.storage.TypedStorage, torch.storage.UntypedStorage):
+            # Wrap legacy storage types in a dummy class
+            rc[f"{ts.__module__}.{ts.__name__}"] = torch.serialization.StorageType(
+                ts.__name__
+            )
+        else:
+            rc[f"{ts.__module__}.{ts.__name__}"] = ts
+    # Quantization specific
+    for qt in [
+        torch.per_tensor_affine,
+        torch.per_tensor_symmetric,
+        torch.per_channel_affine,
+        torch.per_channel_symmetric,
+        torch.per_channel_affine_float_qparams,
+    ]:
+        rc[str(qt)] = qt
+    # Rebuild functions
+    for f in _tensor_rebuild_functions():
+        rc[f"torch._utils.{f.__name__}"] = f
+
+    # Handles Tensor Subclasses, Tensor's with attributes.
+    # NOTE: It calls into above rebuild functions for regular Tensor types.
+    rc["torch._tensor._rebuild_from_type_v2"] = torch._tensor._rebuild_from_type_v2
+    return rc
+
+
+def _read_global_instruction(readline: Callable) -> tuple[str, str]:
+    module = readline()[:-1].decode("utf-8")
+    name = readline()[:-1].decode("utf-8")
+    # Patch since torch.save default protocol is 2
+    # users will be running this code in python > 3
+    if (module, name) in NAME_MAPPING:
+        module, name = NAME_MAPPING[(module, name)]
+    elif module in IMPORT_MAPPING:
+        module = IMPORT_MAPPING[module]
+    return module, name
+
+
+def get_globals_in_pkl(file) -> set[str]:
+    globals_in_checkpoint = set()
+    read = file.read
+    readline = file.readline
+    op_to_bytes_to_read = {
+        NEWOBJ[0]: 0,
+        REDUCE[0]: 0,
+        BUILD[0]: 0,
+        APPEND[0]: 0,
+        APPENDS[0]: 0,
+        SETITEM[0]: 0,
+        SETITEMS[0]: 0,
+        MARK[0]: 0,
+        TUPLE[0]: 0,
+        TUPLE1[0]: 0,
+        TUPLE2[0]: 0,
+        TUPLE3[0]: 0,
+        NONE[0]: 0,
+        NEWFALSE[0]: 0,
+        NEWTRUE[0]: 0,
+        EMPTY_TUPLE[0]: 0,
+        EMPTY_LIST[0]: 0,
+        EMPTY_DICT[0]: 0,
+        EMPTY_SET[0]: 0,
+        BINPERSID[0]: 0,
+        BININT[0]: 4,
+        BININT1[0]: 1,
+        BININT2[0]: 2,
+        BINFLOAT[0]: 8,
+        BINGET[0]: 1,
+        LONG_BINGET[0]: 4,
+        BINPUT[0]: 1,
+        LONG_BINPUT[0]: 4,
+    }
+    while True:
+        key = read(1)
+        if not key:
+            raise EOFError
+        if not isinstance(key, bytes_types):
+            raise AssertionError(f"Expected bytes, got {type(key).__name__}")
+        if key[0] == GLOBAL[0]:
+            module, name = _read_global_instruction(readline)
+            globals_in_checkpoint.add(f"{module}.{name}")
+        elif key[0] in op_to_bytes_to_read:
+            bytes_to_read = op_to_bytes_to_read[key[0]]
+            if bytes_to_read:
+                read(bytes_to_read)
+        # ops where bytes to read depends on the data
+        elif key[0] == BINUNICODE[0]:
+            strlen = unpack(" maxsize:
+                raise UnpicklingError("String is too long")
+            read(strlen)
+        elif key[0] in {SHORT_BINSTRING[0], LONG1[0]}:
+            strlen = read(1)[0]
+            read(strlen)
+        # first and last op
+        elif key[0] == PROTO[0]:
+            read(1)[0]
+        elif key[0] == STOP[0]:
+            return globals_in_checkpoint
+        else:
+            raise UnpicklingError(f"Unsupported operand {key[0]}")
+
+
+class Unpickler:
+    def __init__(self, file, *, encoding: str = "bytes"):
+        self.encoding = encoding
+        self.readline = file.readline
+        self.read = file.read
+        self.memo: dict[int, Any] = {}
+        self.proto: int = -1
+
+    def load(self):
+        """Read a pickled object representation from the open file.
+
+        Return the reconstituted object hierarchy specified in the file.
+        """
+        self.metastack = []
+        self.stack: list[Any] = []
+        self.append = self.stack.append
+        read = self.read
+        while True:
+            key = read(1)
+            if not key:
+                raise EOFError
+            if not isinstance(key, bytes_types):
+                raise AssertionError(f"Expected bytes, got {type(key).__name__}")
+            # Risky operators
+            if key[0] == GLOBAL[0]:
+                module, name = _read_global_instruction(self.readline)
+                full_path = f"{module}.{name}"
+                if module in _blocklisted_modules:
+                    raise UnpicklingError(
+                        f"Trying to load unsupported GLOBAL {full_path} whose module {module} is blocked."
+                    )
+                if full_path in _get_allowed_globals():
+                    self.append(_get_allowed_globals()[full_path])
+                elif full_path in _get_user_allowed_globals():
+                    self.append(_get_user_allowed_globals()[full_path])
+                elif full_path in (
+                    [
+                        "torch.nested._internal.nested_tensor.NestedTensor",
+                        "torch.nested._internal.nested_tensor._rebuild_njt",
+                        "torch._dynamo.decorators._DimRange",
+                    ]
+                ):
+                    raise UnpicklingError(
+                        "``torch.nested`` and ``torch._dynamo`` must be imported to load nested jagged tensors (NJTs)"
+                    )
+                elif full_path in (
+                    [
+                        "torch.distributed.device_mesh.DeviceMesh",
+                        "torch.distributed.tensor._dtensor_spec.DTensorSpec",
+                        "torch.distributed.tensor._dtensor_spec.TensorMeta",
+                        "torch.distributed.tensor.DTensor",
+                        "torch.distributed.tensor.placement_types.Partial",
+                        "torch.distributed.tensor.placement_types.Replicate",
+                        "torch.distributed.tensor.placement_types.Shard",
+                    ]
+                ):
+                    raise UnpicklingError(
+                        "``torch.distributed.tensor`` must be imported to load DTensors"
+                    )
+                else:
+                    builtins_name = "builtins"
+                    if (
+                        builtins_name in full_path
+                        and builtins_name == full_path[: len(builtins_name)]
+                    ):
+                        full_path = full_path[len(builtins_name) :]
+                        full_path = (
+                            full_path[1:]
+                            if len(full_path) > 0 and full_path[0] == "."
+                            else builtins_name + full_path
+                        )
+                    raise UnpicklingError(
+                        f"Unsupported global: GLOBAL {full_path} was not an allowed global by default. "
+                        f"Please use `torch.serialization.add_safe_globals([{full_path}])` or the "
+                        f"`torch.serialization.safe_globals([{full_path}])` context manager to allowlist this global "
+                        "if you trust this class/function."
+                    )
+            elif key[0] == NEWOBJ[0]:
+                args = self.stack.pop()
+                cls = self.stack.pop()
+                if cls is torch.nn.Parameter:
+                    self.append(torch.nn.Parameter(*args))
+                elif (
+                    cls in _get_user_allowed_globals().values()
+                    or cls in _get_allowed_globals().values()
+                ):
+                    result = cls.__new__(cls, *args)
+                    if cls in torch._tensor_classes and "sparse" in cls.__module__:
+                        _sparse_tensors_to_validate.append(result)
+                    self.append(result)
+                else:
+                    raise UnpicklingError(
+                        "Can only create new object for nn.Parameter or classes allowlisted "
+                        f"via `add_safe_globals` but got {cls}"
+                    )
+            elif key[0] == REDUCE[0]:
+                args = self.stack.pop()
+                func = self.stack[-1]
+                if (
+                    func not in _get_allowed_globals().values()
+                    and func not in _get_user_allowed_globals().values()
+                ):
+                    error_msg = (
+                        f"Trying to call reduce for unrecognized function {func}"
+                    )
+                    if hasattr(func, "__self__"):
+                        error_msg += f" which belongs to {func.__self__}"
+                    raise UnpicklingError(error_msg)
+                result = func(*args)
+                if func in torch._tensor_classes and "sparse" in func.__module__:
+                    _sparse_tensors_to_validate.append(result)
+                self.stack[-1] = result
+            elif key[0] == BUILD[0]:
+                state = self.stack.pop()
+                inst = self.stack[-1]
+                if type(inst) is torch.Tensor:
+                    # Legacy unpickling
+
+                    inst.set_(*state)
+                elif type(inst) is torch.nn.Parameter:
+                    inst.__setstate__(state)
+                elif type(inst) is OrderedDict:
+                    inst.__dict__.update(state)
+                elif (
+                    type(inst) in _get_user_allowed_globals().values()
+                    or type(inst) in _get_allowed_globals().values()
+                ):
+                    if hasattr(inst, "__setstate__"):
+                        inst.__setstate__(state)
+                    else:
+                        # mimics load_build in pickle
+                        # https://github.com/python/cpython/blob/f0c6fccd08904787a39269367f09f263d496114c/Lib/pickle.py#L1854-L1867
+                        slotstate = None
+                        if isinstance(state, tuple) and len(state) == 2:
+                            state, slotstate = state
+                        if state:
+                            inst.__dict__.update(state)
+                        if slotstate:
+                            for k, v in slotstate.items():
+                                setattr(inst, k, v)
+                else:
+                    raise UnpicklingError(
+                        "Can only build Tensor, Parameter, OrderedDict or types allowlisted "
+                        f"via `add_safe_globals`, but got {type(inst)}"
+                    )
+            # Stack manipulation
+            elif key[0] == APPEND[0]:
+                item = self.stack.pop()
+                list_obj = self.stack[-1]
+                self._check_append_target(list_obj)
+                list_obj.append(item)
+            elif key[0] == APPENDS[0]:
+                items = self.pop_mark()
+                list_obj = self.stack[-1]
+                self._check_append_target(list_obj)
+                list_obj.extend(items)
+            elif key[0] == SETITEM[0]:
+                (v, k) = (self.stack.pop(), self.stack.pop())
+                self._check_set_item_target("SETITEM")
+                self.stack[-1][k] = v
+            elif key[0] == SETITEMS[0]:
+                items = self.pop_mark()
+                self._check_set_item_target("SETITEMS")
+                for i in range(0, len(items), 2):
+                    self.stack[-1][items[i]] = items[i + 1]
+            elif key[0] == MARK[0]:
+                self.metastack.append(self.stack)
+                self.stack = []
+                self.append = self.stack.append
+            elif key[0] == TUPLE[0]:
+                items = self.pop_mark()
+                self.append(tuple(items))
+            elif key[0] == TUPLE1[0]:
+                self.stack[-1] = (self.stack[-1],)
+            elif key[0] == TUPLE2[0]:
+                self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
+            elif key[0] == TUPLE3[0]:
+                self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
+            # Basic types construction
+            elif key[0] == NONE[0]:
+                self.append(None)
+            elif key[0] == NEWFALSE[0]:
+                self.append(False)
+            elif key[0] == NEWTRUE[0]:
+                self.append(True)
+            elif key[0] == EMPTY_TUPLE[0]:
+                self.append(())
+            elif key[0] == EMPTY_LIST[0]:
+                self.append([])
+            elif key[0] == EMPTY_DICT[0]:
+                self.append({})
+            elif key[0] == EMPTY_SET[0]:
+                self.append(set())
+            elif key[0] == BININT[0]:
+                self.append(unpack("d", self.read(8))[0])
+            elif key[0] == BINUNICODE[0]:
+                strlen = unpack(" maxsize:
+                    raise UnpicklingError("String is too long")
+                strval = str(read(strlen), "utf-8", "surrogatepass")
+                self.append(strval)
+            elif key[0] == SHORT_BINSTRING[0]:
+                strlen = read(1)[0]
+                strdata = read(strlen)
+                if self.encoding != "bytes":
+                    strdata = strdata.decode(self.encoding, "strict")
+                self.append(strdata)
+            elif key[0] == BINPERSID[0]:
+                pid = self.stack.pop()
+                # Only allow persistent load of storage
+                if type(pid) is not tuple and type(pid) is not int:
+                    raise UnpicklingError(
+                        f"persistent_load id must be tuple or int, but got {type(pid)}"
+                    )
+                if (
+                    type(pid) is tuple
+                    and len(pid) > 0
+                    and torch.serialization._maybe_decode_ascii(pid[0]) != "storage"
+                ):
+                    raise UnpicklingError(
+                        f"Only persistent_load of storage is allowed, but got {type(pid[0])}"
+                    )
+                self.append(self.persistent_load(pid))
+            elif key[0] in [BINGET[0], LONG_BINGET[0]]:
+                idx = (read(1) if key[0] == BINGET[0] else unpack("` in python.
+"""
+
+from functools import cache
+from typing import Any
+from typing_extensions import deprecated
+
+import torch
+
+from . import random
+from ._utils import _device_t, _get_device_index
+from .graphs import Graph
+from .memory import (
+    empty_cache,
+    empty_host_cache,
+    get_memory_info,
+    max_memory_allocated,
+    max_memory_reserved,
+    memory_allocated,
+    memory_reserved,
+    memory_stats,
+    reset_accumulated_memory_stats,
+    reset_peak_memory_stats,
+)
+
+
+__all__ = [
+    "Graph",
+    "current_accelerator",
+    "current_device_idx",  # deprecated
+    "current_device_index",
+    "get_device_capability",
+    "current_stream",
+    "device_count",
+    "device_index",
+    "empty_cache",
+    "empty_host_cache",
+    "get_memory_info",
+    "is_available",
+    "max_memory_allocated",
+    "max_memory_reserved",
+    "memory_allocated",
+    "memory_reserved",
+    "memory_stats",
+    "reset_accumulated_memory_stats",
+    "reset_peak_memory_stats",
+    "set_device_idx",  # deprecated
+    "set_device_index",
+    "set_stream",
+    "synchronize",
+]
+
+
+def device_count() -> int:
+    r"""Return the number of current :ref:`accelerator` available.
+
+    Returns:
+        int: the number of the current :ref:`accelerator` available.
+            If there is no available accelerators, return 0.
+
+    .. note:: This API delegates to the device-specific version of `device_count`.
+        On CUDA, this API will NOT poison fork if NVML discovery succeeds.
+        Otherwise, it will. For more details, see :ref:`multiprocessing-poison-fork-note`.
+    """
+    acc = current_accelerator()
+    if acc is None:
+        return 0
+
+    mod = torch.get_device_module(acc)
+    return mod.device_count()
+
+
+def is_available() -> bool:
+    r"""Check if the current accelerator is available at runtime: it was built, all the
+    required drivers are available and at least one device is visible.
+    See :ref:`accelerator` for details.
+
+    Returns:
+        bool: A boolean indicating if there is an available :ref:`accelerator`.
+
+    .. note:: This API delegates to the device-specific version of `is_available`.
+        On CUDA, when the environment variable ``PYTORCH_NVML_BASED_CUDA_CHECK=1`` is set,
+        this function will NOT poison fork. Otherwise, it will. For more details, see
+        :ref:`multiprocessing-poison-fork-note`.
+
+    Example::
+
+        >>> assert torch.accelerator.is_available() "No available accelerators detected."
+    """
+    # Why not just check "device_count() > 0" like other is_available call?
+    # Because device like CUDA have a python implementation of is_available that is
+    # non-poisoning and some features like Dataloader rely on it.
+    # So we are careful to delegate to the Python version of the accelerator here
+    acc = current_accelerator()
+    if acc is None:
+        return False
+
+    mod = torch.get_device_module(acc)
+    return mod.is_available()
+
+
+def current_accelerator(check_available: bool = False) -> torch.device | None:
+    r"""Return the device of the accelerator available at compilation time.
+    If no accelerator were available at compilation time, returns None.
+    See :ref:`accelerator` for details.
+
+    Args:
+        check_available (bool, optional): if True, will also do a runtime check to see
+            if the device :func:`torch.accelerator.is_available` on top of the compile-time
+            check.
+            Default: ``False``
+
+    Returns:
+        torch.device: return the current accelerator as :class:`torch.device`.
+
+    .. note:: The index of the returned :class:`torch.device` will be ``None``, please use
+        :func:`torch.accelerator.current_device_index` to know the current index being used.
+        This API does NOT poison fork. For more details, see :ref:`multiprocessing-poison-fork-note`.
+
+    Example::
+
+        >>> # xdoctest:
+        >>> # If an accelerator is available, sent the model to it
+        >>> model = torch.nn.Linear(2, 2)
+        >>> if (current_device := current_accelerator(check_available=True)) is not None:
+        >>>     model.to(current_device)
+    """
+    if (acc := torch._C._accelerator_getAccelerator()) is not None:
+        if (not check_available) or (check_available and is_available()):
+            return acc
+    return None
+
+
+def current_device_index() -> int:
+    r"""Return the index of a currently selected device for the current :ref:`accelerator`.
+
+    Returns:
+        int: the index of a currently selected device.
+    """
+    return torch._C._accelerator_getDeviceIndex()
+
+
+current_device_idx = deprecated(
+    "Use `current_device_index` instead.",
+    category=FutureWarning,
+)(current_device_index)
+
+current_device_idx.__doc__ = r"""
+    (Deprecated) Return the index of a currently selected device for the current :ref:`accelerator`.
+
+    Returns:
+        int: the index of a currently selected device.
+
+    .. warning::
+
+        :func:`torch.accelerator.current_device_idx` is deprecated in favor of :func:`torch.accelerator.current_device_index`
+        and will be removed in a future PyTorch release.
+    """
+
+
+@cache
+def get_device_capability(device: _device_t = None, /) -> dict[str, Any]:
+    r"""Return the capability of the currently selected device.
+
+    Args:
+        device (:class:`torch.device`, str, int, optional): The device to query capabilities for
+            :ref:`accelerator` device type. If not given,
+            use :func:`torch.accelerator.current_device_index` by default.
+
+    Returns:
+        dict[str, Any]: A dictionary containing device capability information. The dictionary includes:
+            - ``supported_dtypes`` (set(torch.dtype)): Set of PyTorch data types for which
+              tensors can be allocated on the accelerator and type conversion across
+              supported dtypes are supported. Any operator support outside of that
+              is not guaranteed
+
+    Examples:
+        >>> # xdoctest: +SKIP("requires cuda")
+        >>> # Query capabilities for current device
+        >>> capabilities = torch.accelerator.get_device_capability("cuda:0")
+        >>> print("Supported dtypes:", capabilities["supported_dtypes"])
+    """
+    device_index = _get_device_index(device, optional=True)
+    # pyrefly: ignore [missing-attribute]
+    return torch._C._accelerator_getDeviceCapability(device_index)
+
+
+def set_device_index(device: _device_t, /) -> None:
+    r"""Set the current device index to a given device.
+
+    Args:
+        device (:class:`torch.device`, str, int): a given device that must match the current
+            :ref:`accelerator` device type.
+
+    .. note:: This function is a no-op if this device index is negative.
+    """
+    device_index = _get_device_index(device, optional=False)
+    torch._C._accelerator_setDeviceIndex(device_index)
+
+
+set_device_idx = deprecated(
+    "Use `set_device_index` instead.",
+    category=FutureWarning,
+)(set_device_index)
+
+set_device_idx.__doc__ = r"""
+    (Deprecated) Set the current device index to a given device.
+
+    Args:
+        device (:class:`torch.device`, str, int): a given device that must match the current
+            :ref:`accelerator` device type.
+
+    .. warning::
+
+        :func:`torch.accelerator.set_device_idx` is deprecated in favor of :func:`torch.accelerator.set_device_index`
+        and will be removed in a future PyTorch release.
+    """
+
+
+def current_stream(device: _device_t = None, /) -> torch.Stream:
+    r"""Return the currently selected stream for a given device.
+
+    Args:
+        device (:class:`torch.device`, str, int, optional): a given device that must match the current
+            :ref:`accelerator` device type. If not given,
+            use :func:`torch.accelerator.current_device_index` by default.
+
+    Returns:
+        torch.Stream: the currently selected stream for a given device.
+    """
+    device_index = _get_device_index(device, optional=True)
+    return torch._C._accelerator_getStream(device_index)
+
+
+def set_stream(stream: torch.Stream) -> None:
+    r"""Set the current stream to a given stream.
+
+    Args:
+        stream (torch.Stream): a given stream that must match the current :ref:`accelerator` device type.
+
+    .. note:: This function will set the current device index to the device index of the given stream.
+    """
+    torch._C._accelerator_setStream(stream)
+
+
+def synchronize(device: _device_t = None, /) -> None:
+    r"""Wait for all kernels in all streams on the given device to complete.
+
+    Args:
+        device (:class:`torch.device`, str, int, optional): device for which to synchronize. It must match
+            the current :ref:`accelerator` device type. If not given,
+            use :func:`torch.accelerator.current_device_index` by default.
+
+    .. note:: This function is a no-op if the current :ref:`accelerator` is not initialized.
+
+    Example::
+
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
+        >>> assert torch.accelerator.is_available() "No available accelerators detected."
+        >>> start_event = torch.Event(enable_timing=True)
+        >>> end_event = torch.Event(enable_timing=True)
+        >>> start_event.record()
+        >>> tensor = torch.randn(100, device=torch.accelerator.current_accelerator())
+        >>> sum = torch.sum(tensor)
+        >>> end_event.record()
+        >>> torch.accelerator.synchronize()
+        >>> elapsed_time_ms = start_event.elapsed_time(end_event)
+    """
+    device_index = _get_device_index(device, optional=True)
+    torch._C._accelerator_synchronizeDevice(device_index)
+
+
+class device_index:
+    r"""Context manager to set the current device index for the current :ref:`accelerator`.
+    Temporarily changes the current device index to the specified value for the duration
+    of the context, and automatically restores the previous device index when exiting
+    the context.
+
+    Args:
+        device (Optional[int]): a given device index to temporarily set. If None,
+            no device index switching occurs.
+
+    Examples:
+
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
+        >>> # Set device 0 as the current device temporarily
+        >>> with torch.accelerator.device_index(0):
+        ...     # Code here runs with device 0 as the current device
+        ...     pass
+        >>> # Original device is now restored
+        >>> # No-op when None is passed
+        >>> with torch.accelerator.device_index(None):
+        ...     # No device switching occurs
+        ...     pass
+    """
+
+    def __init__(self, device: int | None, /) -> None:
+        self.idx = device
+        self.prev_idx = -1
+
+    def __enter__(self) -> None:
+        if self.idx is not None:
+            self.prev_idx = torch._C._accelerator_exchangeDevice(self.idx)
+
+    def __exit__(self, *exc_info: object) -> None:
+        if self.idx is not None:
+            torch._C._accelerator_maybeExchangeDevice(self.prev_idx)
diff --git a/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6e16215e6646f64f0d844a19b627fa59a70752d1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05d25ff2f891b6a857b9cdcccb30eee940187001
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/graphs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/graphs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0431ce372949880830ae6eeb4a5d83983341c6db
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/graphs.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/memory.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/memory.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..afc62d0933d80ab0fc4489b812fe299e92caf2f7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/memory.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/random.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/random.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f1a9a341286bb7fd276e8e89715e29c8f9773fc
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/accelerator/__pycache__/random.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/accelerator/_utils.py b/.venv/lib/python3.12/site-packages/torch/accelerator/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a040e56fb4e4f27be15d8becde005b6bbf2ee607
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/accelerator/_utils.py
@@ -0,0 +1,51 @@
+from collections.abc import Callable
+
+import torch
+from torch.types import Device as _device_t
+
+
+def _get_device_index(device: _device_t, optional: bool = False) -> int:
+    if isinstance(device, int):
+        return device
+    if isinstance(device, str):
+        device = torch.device(device)
+    device_index: int | None = None
+    if isinstance(device, torch.device):
+        acc = torch.accelerator.current_accelerator()
+        if acc is None:
+            raise RuntimeError("Accelerator expected")
+        if acc.type != device.type:
+            raise ValueError(
+                f"{device.type} doesn't match the current accelerator {acc}."
+            )
+        device_index = device.index
+    if device_index is None:
+        if not optional:
+            raise ValueError(
+                f"Expected a torch.device with a specified index or an integer, but got:{device}"
+            )
+        return torch.accelerator.current_device_index()
+    return device_index
+
+
+def _lazy_call(callable: Callable[[], None], **kwargs) -> None:
+    r"""Defer a callable until the :ref:`accelerator` runtime is initialized.
+
+    If the runtime is already initialized or the backend does not support lazy
+    initialization, the callable runs immediately. If no accelerator is
+    available, the callable is silently dropped.
+
+    Args:
+        callable (Callable[[], None]): The function to be called.
+        **kwargs: Additional keyword arguments forwarded to the backend's ``_lazy_call``
+            (e.g., ``seed=True``, ``seed_all=True``).
+    """
+    acc = torch.accelerator.current_accelerator()
+    if acc is None:
+        return
+    device_module = torch.get_device_module(acc)
+    if hasattr(device_module, "_lazy_call"):
+        device_module._lazy_call(callable, **kwargs)
+    else:
+        # Backend does not support lazy initialization; run immediately.
+        callable()
diff --git a/.venv/lib/python3.12/site-packages/torch/accelerator/graphs.py b/.venv/lib/python3.12/site-packages/torch/accelerator/graphs.py
new file mode 100644
index 0000000000000000000000000000000000000000..f02e91f253a45843ec81b8eda0ea5cd4d032da57
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/accelerator/graphs.py
@@ -0,0 +1,177 @@
+import gc
+from typing import Literal
+from typing_extensions import Self
+
+import torch
+from torch._C import _acceleratorGraph
+
+
+class Graph(_acceleratorGraph):
+    r"""
+    Wrapper around an :ref:`accelerator` graph that supports capture and replay.
+
+    A graph captures a sequence of operations and their dependencies, allowing them to be
+    replayed efficiently with reduced overhead. This class can be used as a context manager
+    to automatically capture operations on the current stream.
+
+    Arguments:
+        keep_graph (bool, optional): If ``False``, the underlying graph is destroyed and the
+            executable graph is instantiated on the GPU at the end of ``capture_end``.
+            If ``True``, the underlying graph is preserved after ``capture_end``. In this case,
+            the executable graph is not instantiated automatically; it must be explicitly created
+            by calling ``instantiate``, or it will be instantiated on the first call to ``replay``.
+            Defaults to ``False``.
+        pool (tuple[int, int], optional): Memory pool identifier for this graph. Multiple graphs
+            can share the same pool by passing the same identifier, which can reduce memory overhead.
+            Defaults to ``None``.
+        capture_error_mode (Literal["default", "global", "thread_local", "relaxed"], optional):
+            Specifies the behavior of graph capture. The exact semantics are backend-specific.
+            ``"default"``: backend-defined default capture behavior.
+            ``"global"``: potentially unsafe API calls are prohibited. Errors may occur if capture
+            in the current thread affects other threads.
+            ``"thread_local"``: potentially unsafe API calls are prohibited. Errors occur only if
+            capture in the current thread affects itself.
+            ``"relaxed"``: the current thread is allowed to make potentially unsafe API calls, except
+            for calls that inherently conflict with stream capture.
+            Default: ``"default"``.
+
+    Example::
+
+        >>> # xdoctest: +SKIP
+        >>> x = torch.zeros([2000], device=0)
+
+        >>> stream = torch.Stream()
+        >>> graph = torch.accelerator.Graph()
+        >>> with stream, graph:
+        ...     x += 1
+
+        >>> graph.replay()
+    """
+
+    def __new__(
+        cls,
+        keep_graph: bool = False,
+        *,
+        pool: tuple[int, int] | None = None,
+        capture_error_mode: Literal[
+            "default", "global", "thread_local", "relaxed"
+        ] = "default",
+    ) -> Self:
+        return super().__new__(cls, keep_graph)
+
+    def __init__(
+        self,
+        keep_graph: bool = False,
+        *,
+        pool: tuple[int, int] | None = None,
+        capture_error_mode: Literal[
+            "default", "global", "thread_local", "relaxed"
+        ] = "default",
+    ) -> None:
+        super().__init__(keep_graph)
+        self.graph_pool = pool
+        self.capture_error_mode = capture_error_mode
+
+    # pyrefly: ignore [bad-override]
+    def capture_begin(self) -> None:
+        r"""
+        Begin graph capture on the current stream.
+
+        All operations on the current stream after this call will be recorded into the graph until
+        ``capture_end`` is called, using the memory pool and capture error mode provided at construction time.
+        """
+        super().capture_begin(
+            pool=self.graph_pool, capture_error_mode=self.capture_error_mode
+        )
+
+    def capture_end(self) -> None:
+        r"""
+        End graph capture on the current stream of the current device.
+
+        After this call, the graph can be replayed via ``replay``.
+        """
+        super().capture_end()
+
+    def instantiate(self) -> None:
+        r"""
+        Instantiate the underlying graph. Will be called by ``capture_end``
+        if ``keep_graph=False``, or by ``replay`` if ``keep_graph=True`` and
+        ``instantiate`` has not already been explicitly called.
+        """
+        super().instantiate()
+
+    def replay(self) -> None:
+        r"""Replay the work captured by this graph."""
+        super().replay()
+
+    def reset(self) -> None:
+        r"""
+        Delete the graph currently held by this instance.
+
+        After this call, the graph can be recaptured. Set :attr:`graph_pool` or
+        :attr:`capture_error_mode` beforehand to use different settings on the next capture.
+        """
+        super().reset()
+
+    def pool(self) -> tuple[int, int]:
+        r"""
+        Return an opaque token representing the id of this graph's memory pool.
+
+        This id can optionally be passed to another graph's ``capture_begin``,
+        which hints the other graph may share the same memory pool.
+
+        Example::
+            >>> # xdoctest: +SKIP
+            >>> g1 = torch.accelerator.Graph()
+            >>> g1.capture_begin()
+            >>> # ... operations ...
+            >>> g1.capture_end()
+
+            >>> # Share g1's memory pool with a new graph
+            >>> pool_id = g1.pool()
+            >>> g2 = torch.accelerator.Graph(pool=pool_id)
+        """
+        return super().pool()
+
+    def enable_debug_mode(self) -> None:
+        r"""Enable debugging mode for ``debug_dump``."""
+        return super().enable_debug_mode()
+
+    def debug_dump(self, path: str) -> None:
+        r"""
+        Dump the captured graph to a file for debugging purposes if the debugging is
+        enabled via ``enable_debug_mode``.
+
+        Arguments:
+            path (str): Path to dump the graph to.
+
+        Example::
+            >>> # xdoctest: +SKIP
+            >>> s = torch.Stream()
+            >>> g = torch.accelerator.Graph()
+            >>> g.enable_debug_mode()
+
+            >>> with s, g:
+            >>> # ... operations ...
+
+            >>> # Dump captured graph to a file "graph_dump.dot"
+            >>> g.debug_dump("graph_dump.dot")
+        """
+        return super().debug_dump(path)
+
+    def __enter__(self) -> None:
+        torch.accelerator.synchronize()
+        if torch.compiler.config.force_cudagraph_gc:
+            # We previously always ran garbage collection here. While this can help
+            # reclaim accelerator device memory held by dead Python cycles, it is
+            # very expensive, especially when performing multiple graph captures in sequence.
+            gc.collect()
+        torch.accelerator.empty_cache()
+        torch.accelerator.empty_host_cache()
+        self.capture_begin()
+
+    def __exit__(self, *exc_info: object) -> None:
+        self.capture_end()
+
+
+__all__ = ["Graph"]
diff --git a/.venv/lib/python3.12/site-packages/torch/accelerator/memory.py b/.venv/lib/python3.12/site-packages/torch/accelerator/memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..5aab0e267f2e3b7be5f1e5242ab0732ffb14fa2f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/accelerator/memory.py
@@ -0,0 +1,277 @@
+from collections import OrderedDict
+from typing import Any
+
+import torch
+
+from ._utils import _device_t, _get_device_index
+
+
+__all__ = [
+    "empty_cache",
+    "empty_host_cache",
+    "get_memory_info",
+    "max_memory_allocated",
+    "max_memory_reserved",
+    "memory_allocated",
+    "memory_reserved",
+    "memory_stats",
+    "reset_accumulated_memory_stats",
+    "reset_peak_memory_stats",
+]
+
+
+def empty_cache() -> None:
+    r"""Release all unoccupied cached memory currently held by the caching
+    allocator so that those can be used in other application.
+
+    .. note:: This function is a no-op if the memory allocator for the current
+        :ref:`accelerator ` has not been initialized.
+    """
+    if not torch._C._accelerator_isAllocatorInitialized():
+        return
+    torch._C._accelerator_emptyCache()
+
+
+def empty_host_cache() -> None:
+    r"""Release all unoccupied cached host (pinned) memory currently held by the host caching
+    allocator so that it can be used by other applications.
+
+    .. note:: This function is a no-op if the memory allocator for the current
+        :ref:`accelerator ` has not been initialized.
+    """
+    torch._C._accelerator_emptyHostCache()
+
+
+def _flatten_stats(result: list[tuple[str, Any]], prefix: str, value: Any) -> None:
+    if isinstance(value, dict):
+        for key, nested_value in value.items():
+            nested_prefix = f"{prefix}.{key}" if prefix else key
+            _flatten_stats(result, nested_prefix, nested_value)
+    else:
+        result.append((prefix, value))
+
+
+def memory_stats(device_index: _device_t = None, /) -> OrderedDict[str, Any]:
+    r"""Return a dictionary of accelerator device memory allocator statistics for a given device index.
+
+    The return value of this function is a dictionary of statistics, each of
+    which is a non-negative integer.
+
+    Core statistics:
+
+    - ``"allocated.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
+      number of allocation requests received by the memory allocator.
+    - ``"allocated_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
+      amount of allocated memory.
+    - ``"segment.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
+      number of reserved segments from device memory allocation.
+    - ``"reserved_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
+      amount of reserved memory.
+    - ``"active.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
+      number of active memory blocks.
+    - ``"active_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
+      amount of active memory.
+    - ``"inactive_split.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
+      number of inactive, non-releasable memory blocks.
+    - ``"inactive_split_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``:
+      amount of inactive, non-releasable memory.
+
+    For these core statistics, values are broken down as follows.
+
+    Pool type:
+
+    - ``all``: combined statistics across all memory pools.
+    - ``large_pool``: statistics for the large allocation pool
+      (as of June 2025, for size >= 1MB allocations).
+    - ``small_pool``: statistics for the small allocation pool
+      (as of June 2025, for size < 1MB allocations).
+
+    Metric type:
+
+    - ``current``: current value of this metric.
+    - ``peak``: maximum value of this metric.
+    - ``allocated``: historical total increase in this metric.
+    - ``freed``: historical total decrease in this metric.
+
+    In addition to the core statistics, we also provide some simple event
+    counters:
+
+    - ``"num_alloc_retries"``: number of failed device memory allocation calls that
+      result in a cache flush and retry.
+    - ``"num_ooms"``: number of out-of-memory errors thrown.
+    - ``"num_sync_all_streams"``: number of ``synchronize_and_free_events`` calls.
+    - ``"num_device_alloc"``: number of device memory allocation calls.
+    - ``"num_device_free"``: number of device memory free calls.
+
+    Args:
+        device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
+            If not given, use :func:`torch.accelerator.current_device_index` by default.
+            If a :class:`torch.device` or str is provided, its type must match the current
+            :ref:`accelerator` device type.
+
+    Returns:
+        OrderedDict[str, Any]: an ordered dictionary mapping statistic names to their values.
+    """
+    if not torch._C._accelerator_isAllocatorInitialized():
+        return OrderedDict()
+    device_index = _get_device_index(device_index, optional=True)
+    stats = torch._C._accelerator_getDeviceStats(device_index)
+    flat_stats = []
+
+    _flatten_stats(flat_stats, "", stats)
+    flat_stats.sort()
+    # pyrefly: ignore [no-matching-overload]
+    return OrderedDict(flat_stats)
+
+
+def memory_allocated(device_index: _device_t = None, /) -> int:
+    r"""Return the current :ref:`accelerator` device memory occupied by tensors
+    in bytes for a given device index.
+
+    Args:
+        device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
+            If not given, use :func:`torch.accelerator.current_device_index` by default.
+            If a :class:`torch.device` or str is provided, its type must match the current
+            :ref:`accelerator` device type.
+
+    Returns:
+        int: the current memory occupied by live tensors (in bytes) within the current process.
+    """
+    return memory_stats(device_index).get("allocated_bytes.all.current", 0)
+
+
+def max_memory_allocated(device_index: _device_t = None, /) -> int:
+    r"""Return the current :ref:`accelerator` maximum device memory occupied by tensors
+    in bytes for a given device index.
+
+    By default, this returns the peak allocated memory since the beginning of
+    this program. :func:`~torch.accelerator.reset_peak_memory_stats` can be used to
+    reset the starting point in tracking this metric.
+
+    Args:
+        device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
+            If not given, use :func:`torch.accelerator.current_device_index` by default.
+            If a :class:`torch.device` or str is provided, its type must match the current
+            :ref:`accelerator` device type.
+
+    Returns:
+        int: the peak memory occupied by live tensors (in bytes) within the current process.
+    """
+    return memory_stats(device_index).get("allocated_bytes.all.peak", 0)
+
+
+def memory_reserved(device_index: _device_t = None, /) -> int:
+    r"""Return the current :ref:`accelerator` device memory managed by the caching allocator
+    in bytes for a given device index.
+
+    Args:
+        device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
+            If not given, use :func:`torch.accelerator.current_device_index` by default.
+            If a :class:`torch.device` or str is provided, its type must match the current
+            :ref:`accelerator` device type.
+
+    Returns:
+        int: the current memory reserved by PyTorch (in bytes) within the current process.
+    """
+    return memory_stats(device_index).get("reserved_bytes.all.current", 0)
+
+
+def max_memory_reserved(device_index: _device_t = None, /) -> int:
+    r"""Return the current :ref:`accelerator` maximum device memory managed by the caching allocator
+    in bytes for a given device index.
+
+    By default, this returns the peak cached memory since the beginning of this
+    program. :func:`~torch.accelerator.reset_peak_memory_stats` can be used to reset
+    the starting point in tracking this metric.
+
+    Args:
+        device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
+            If not given, use :func:`torch.accelerator.current_device_index` by default.
+            If a :class:`torch.device` or str is provided, its type must match the current
+            :ref:`accelerator` device type.
+
+    Returns:
+        int: the peak memory reserved by PyTorch (in bytes) within the current process.
+    """
+    return memory_stats(device_index).get("reserved_bytes.all.peak", 0)
+
+
+def reset_accumulated_memory_stats(device_index: _device_t = None, /) -> None:
+    r"""Reset the "accumulated" (historical) stats tracked by the current :ref:`accelerator`
+    memory allocator for a given device index.
+
+    Args:
+        device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
+            If not given, use :func:`torch.accelerator.current_device_index` by default.
+            If a :class:`torch.device` or str is provided, its type must match the current
+            :ref:`accelerator` device type.
+
+    .. note:: This function is a no-op if the memory allocator for the current
+        :ref:`accelerator ` has not been initialized.
+    """
+    if not torch._C._accelerator_isAllocatorInitialized():
+        return
+    device_index = _get_device_index(device_index, optional=True)
+    return torch._C._accelerator_resetAccumulatedStats(device_index)
+
+
+def reset_peak_memory_stats(device_index: _device_t = None, /) -> None:
+    r"""Reset the "peak" stats tracked by the current :ref:`accelerator`
+    memory allocator for a given device index.
+
+    Args:
+        device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
+            If not given, use :func:`torch.accelerator.current_device_index` by default.
+            If a :class:`torch.device` or str is provided, its type must match the current
+            :ref:`accelerator` device type.
+
+    .. note:: This function is a no-op if the memory allocator for the current
+        :ref:`accelerator ` has not been initialized.
+    """
+    if not torch._C._accelerator_isAllocatorInitialized():
+        return
+    device_index = _get_device_index(device_index, optional=True)
+    return torch._C._accelerator_resetPeakStats(device_index)
+
+
+def get_memory_info(device_index: _device_t = None, /) -> tuple[int, int]:
+    r"""Return the current device memory information for a given device index.
+
+    Args:
+        device_index (:class:`torch.device`, str, int, optional): the index of the device to target.
+            If not given, use :func:`torch.accelerator.current_device_index` by default.
+            If a :class:`torch.device` or str is provided, its type must match the current
+            :ref:`accelerator` device type.
+
+    Returns:
+        tuple[int, int]: a tuple of two integers (free_memory, total_memory) in bytes.
+            The first value is the free memory on the device (available across all processes and applications),
+            The second value is the device's total hardware memory capacity.
+    """
+    device_index = _get_device_index(device_index, optional=True)
+    # pyrefly: ignore [missing-attribute]
+    return torch._C._accelerator_getMemoryInfo(device_index)
+
+
+def _snapshot(device=None, augment_with_fx_traces: bool = False):
+    r"""Return a snapshot of the current :ref:`accelerator` memory allocator state.
+
+    Requires :func:`_record_memory_history` on the appropriate device module
+    (e.g., :func:`torch.cuda.memory._record_memory_history`) to have been called.
+
+    Args:
+        device: the device to snapshot. If not given, uses the current device.
+        augment_with_fx_traces (bool, optional): if True, augment stack traces
+            with FX graph information. Default: ``False``.
+
+    Returns:
+        dict: a dictionary containing memory allocator state information.
+    """
+    acc = torch.accelerator.current_accelerator()
+    if acc is not None and acc.type == "xpu":
+        return torch.xpu.memory._snapshot(
+            device, augment_with_fx_traces=augment_with_fx_traces
+        )
+    return torch.cuda.memory._snapshot(
+        device, augment_with_fx_traces=augment_with_fx_traces
+    )
diff --git a/.venv/lib/python3.12/site-packages/torch/accelerator/random.py b/.venv/lib/python3.12/site-packages/torch/accelerator/random.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd7333f756bbb7cb9140ce8b83be45ce20836d41
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/accelerator/random.py
@@ -0,0 +1,58 @@
+import torch
+from torch import Tensor
+
+from ._utils import _device_t, _get_device_index
+
+
+def initial_seed(device: _device_t = None, /) -> int:
+    r"""Return the initial seed of the default :class:`torch.Generator` for the current :ref:`accelerator`
+    on the specified device.
+
+    Args:
+        device (:class:`torch.device`, str, int, optional): The device to return the initial seed of.
+            If not given, uses :func:`torch.accelerator.current_device_index` by default.
+
+    Returns:
+        int: the initial seed of the default generator for the specified device.
+
+    .. warning::
+        This function eagerly initializes the accelerator runtime.
+    """
+    device_index = _get_device_index(device, optional=True)
+    default_generator = torch._C._accelerator_getDefaultGenerator(device_index)
+    return default_generator.initial_seed()
+
+
+def get_rng_state(device: _device_t = None, /) -> Tensor:
+    r"""Return the RNG state of the default :class:`torch.Generator` for the current :ref:`accelerator`
+    as a `torch.Tensor` of dtype `torch.uint8` for the specified accelerator device.
+
+    Args:
+        device (:class:`torch.device`, str, int, optional): The device to return the RNG state of.
+            If not given, uses :func:`torch.accelerator.current_device_index` by default.
+
+    Returns:
+        torch.Tensor: the RNG state of the default generator for the specified device.
+
+    .. warning::
+        This function eagerly initializes the accelerator runtime.
+    """
+    device_index = _get_device_index(device, optional=True)
+    default_generator = torch._C._accelerator_getDefaultGenerator(device_index)
+    return default_generator.get_state()
+
+
+def get_rng_state_all() -> list[Tensor]:
+    r"""Return a list of `torch.Tensor` of dtype `torch.uint8` representing the RNG states of all devices for
+    the current :ref:`accelerator`.
+
+    Returns:
+        list[torch.Tensor]: the RNG states of the default generators for all devices.
+
+    .. warning::
+        This function eagerly initializes the accelerator runtime.
+    """
+    return [get_rng_state(i) for i in range(torch.accelerator.device_count())]
+
+
+__all__ = ["initial_seed", "get_rng_state", "get_rng_state_all"]
diff --git a/.venv/lib/python3.12/site-packages/torch/amp/__init__.py b/.venv/lib/python3.12/site-packages/torch/amp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..99c53f90ce8018a82e3f99771edca20c278ae86e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/amp/__init__.py
@@ -0,0 +1,18 @@
+from .autocast_mode import (
+    _enter_autocast,
+    _exit_autocast,
+    autocast,
+    custom_bwd,
+    custom_fwd,
+    is_autocast_available,
+)
+from .grad_scaler import GradScaler
+
+
+__all__ = [
+    "autocast",
+    "custom_bwd",
+    "custom_fwd",
+    "is_autocast_available",
+    "GradScaler",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/amp/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/amp/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb72bc3d71560c20dfc39af15793427a2a07f3c4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/amp/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/amp/__pycache__/autocast_mode.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/amp/__pycache__/autocast_mode.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..722fc14d9e33cdd6c947966c076457fd57825fc1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/amp/__pycache__/autocast_mode.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/amp/__pycache__/grad_scaler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/amp/__pycache__/grad_scaler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a95a84d4b4dd33fe60b97dce9ae836c8042d9e03
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/amp/__pycache__/grad_scaler.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/amp/autocast_mode.py b/.venv/lib/python3.12/site-packages/torch/amp/autocast_mode.py
new file mode 100644
index 0000000000000000000000000000000000000000..51a90f04e0dfa5be6b14c46385fa53864d89a9ed
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/amp/autocast_mode.py
@@ -0,0 +1,529 @@
+# mypy: allow-untyped-defs
+import collections
+import functools
+import warnings
+from typing import Any
+
+import torch
+from torch.types import _dtype
+
+
+try:
+    import numpy as np
+
+    HAS_NUMPY = True
+except ModuleNotFoundError:
+    HAS_NUMPY = False
+    np = None  # type: ignore[assignment]
+
+__all__ = [
+    "autocast_decorator",
+    "autocast",
+    "is_autocast_available",
+    "custom_fwd",
+    "custom_bwd",
+]
+
+
+def is_autocast_available(device_type: str) -> bool:
+    r"""
+    Return a bool indicating if autocast is available on :attr:`device_type`.
+
+    Args:
+        device_type(str):  Device type to use. Possible values are: 'cuda', 'cpu', 'mtia', 'maia', 'xpu', and so on.
+            The type is the same as the `type` attribute of a :class:`torch.device`.
+            Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
+    """
+    return torch._C._is_autocast_available(device_type)
+
+
+def autocast_decorator(autocast_instance, func):
+    @functools.wraps(func)
+    def decorate_autocast(*args, **kwargs):
+        with autocast_instance:
+            return func(*args, **kwargs)
+
+    decorate_autocast.__script_unsupported = (  # type: ignore[attr-defined]
+        "@autocast() decorator is not supported in script mode"
+    )
+    return decorate_autocast
+
+
+class autocast:
+    r"""
+    Instances of :class:`autocast` serve as context managers or decorators that
+    allow regions of your script to run in mixed precision.
+
+    In these regions, ops run in an op-specific dtype chosen by autocast
+    to improve performance while maintaining accuracy.
+    See the :ref:`Autocast Op Reference` for details.
+
+    When entering an autocast-enabled region, Tensors may be any type.
+    You should not call ``half()`` or ``bfloat16()`` on your model(s) or inputs when using autocasting.
+
+    :class:`autocast` should wrap only the forward pass(es) of your network, including the loss
+    computation(s).  Backward passes under autocast are not recommended.
+    Backward ops run in the same type that autocast used for corresponding forward ops.
+
+    Example for CUDA Devices::
+
+        # Creates model and optimizer in default precision
+        model = Net().cuda()
+        optimizer = optim.SGD(model.parameters(), ...)
+
+        for input, target in data:
+            optimizer.zero_grad()
+
+            # Enables autocasting for the forward pass (model + loss)
+            with torch.autocast(device_type="cuda"):
+                output = model(input)
+                loss = loss_fn(output, target)
+
+            # Exits the context manager before backward()
+            loss.backward()
+            optimizer.step()
+
+    See the :ref:`Automatic Mixed Precision examples` for usage (along with gradient scaling)
+    in more complex scenarios (e.g., gradient penalty, multiple models/losses, custom autograd functions).
+
+    :class:`autocast` can also be used as a decorator, e.g., on the ``forward`` method of your model::
+
+        class AutocastModel(nn.Module):
+            ...
+
+            @torch.autocast(device_type="cuda")
+            def forward(self, input): ...
+
+    Floating-point Tensors produced in an autocast-enabled region may be ``float16``.
+    After returning to an autocast-disabled region, using them with floating-point
+    Tensors of different dtypes may cause type mismatch errors.  If so, cast the Tensor(s)
+    produced in the autocast region back to ``float32`` (or other dtype if desired).
+    If a Tensor from the autocast region is already ``float32``, the cast is a no-op,
+    and incurs no additional overhead.
+    CUDA Example::
+
+        # Creates some tensors in default dtype (here assumed to be float32)
+        a_float32 = torch.rand((8, 8), device="cuda")
+        b_float32 = torch.rand((8, 8), device="cuda")
+        c_float32 = torch.rand((8, 8), device="cuda")
+        d_float32 = torch.rand((8, 8), device="cuda")
+
+        with torch.autocast(device_type="cuda"):
+            # torch.mm is on autocast's list of ops that should run in float16.
+            # Inputs are float32, but the op runs in float16 and produces float16 output.
+            # No manual casts are required.
+            e_float16 = torch.mm(a_float32, b_float32)
+            # Also handles mixed input types
+            f_float16 = torch.mm(d_float32, e_float16)
+
+        # After exiting autocast, calls f_float16.float() to use with d_float32
+        g_float32 = torch.mm(d_float32, f_float16.float())
+
+    CPU Training Example::
+
+        # Creates model and optimizer in default precision
+        model = Net()
+        optimizer = optim.SGD(model.parameters(), ...)
+
+        for epoch in epochs:
+            for input, target in data:
+                optimizer.zero_grad()
+
+                # Runs the forward pass with autocasting.
+                with torch.autocast(device_type="cpu", dtype=torch.bfloat16):
+                    output = model(input)
+                    loss = loss_fn(output, target)
+
+                loss.backward()
+                optimizer.step()
+
+
+    CPU Inference Example::
+
+        # Creates model in default precision
+        model = Net().eval()
+
+        with torch.autocast(device_type="cpu", dtype=torch.bfloat16):
+            for input in data:
+                # Runs the forward pass with autocasting.
+                output = model(input)
+
+    CPU Inference Example with Jit Trace::
+
+        class TestModel(nn.Module):
+            def __init__(self, input_size, num_classes):
+                super().__init__()
+                self.fc1 = nn.Linear(input_size, num_classes)
+
+            def forward(self, x):
+                return self.fc1(x)
+
+
+        input_size = 2
+        num_classes = 2
+        model = TestModel(input_size, num_classes).eval()
+
+        # For now, we suggest to disable the Jit Autocast Pass,
+        # As the issue: https://github.com/pytorch/pytorch/issues/75956
+        torch._C._jit_set_autocast_mode(False)
+
+        with torch.cpu.amp.autocast(cache_enabled=False):
+            model = torch.jit.trace(model, torch.randn(1, input_size))
+        model = torch.jit.freeze(model)
+        # Models Run
+        for _ in range(3):
+            model(torch.randn(1, input_size))
+
+    Type mismatch errors *in* an autocast-enabled region are a bug; if this is what you observe,
+    please file an issue.
+
+    ``autocast(enabled=False)`` subregions can be nested in autocast-enabled regions.
+    Locally disabling autocast can be useful, for example, if you want to force a subregion
+    to run in a particular ``dtype``.  Disabling autocast gives you explicit control over
+    the execution type.  In the subregion, inputs from the surrounding region
+    should be cast to ``dtype`` before use::
+
+        # Creates some tensors in default dtype (here assumed to be float32)
+        a_float32 = torch.rand((8, 8), device="cuda")
+        b_float32 = torch.rand((8, 8), device="cuda")
+        c_float32 = torch.rand((8, 8), device="cuda")
+        d_float32 = torch.rand((8, 8), device="cuda")
+
+        with torch.autocast(device_type="cuda"):
+            e_float16 = torch.mm(a_float32, b_float32)
+            with torch.autocast(device_type="cuda", enabled=False):
+                # Calls e_float16.float() to ensure float32 execution
+                # (necessary because e_float16 was created in an autocasted region)
+                f_float32 = torch.mm(c_float32, e_float16.float())
+
+            # No manual casts are required when re-entering the autocast-enabled region.
+            # torch.mm again runs in float16 and produces float16 output, regardless of input types.
+            g_float16 = torch.mm(d_float32, f_float32)
+
+    The autocast state is thread-local.  If you want it enabled in a new thread, the context manager or decorator
+    must be invoked in that thread.  This affects :class:`torch.nn.DataParallel` and
+    :class:`torch.nn.parallel.DistributedDataParallel` when used with more than one GPU per process
+    (see :ref:`Working with Multiple GPUs`).
+
+    Args:
+        device_type(str, required):  Device type to use. Possible values are: 'cuda', 'cpu', 'mtia', 'maia', 'xpu', and 'hpu'.
+                                     The type is the same as the `type` attribute of a :class:`torch.device`.
+                                     Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
+        enabled(bool, optional):  Whether autocasting should be enabled in the region.
+            Default: ``True``
+        dtype(torch_dtype, optional):  Data type for ops run in autocast. It uses the default value
+            (``torch.float16`` for CUDA and ``torch.bfloat16`` for CPU), given by
+            :func:`~torch.get_autocast_dtype`, if :attr:`dtype` is ``None``.
+            Default: ``None``
+        cache_enabled(bool, optional):  Whether the weight cache inside autocast should be enabled.
+            Default: ``True``
+    """
+
+    def __init__(
+        self,
+        device_type: str,
+        dtype: _dtype | None = None,
+        enabled: bool = True,
+        cache_enabled: bool | None = None,
+    ):
+        if not isinstance(device_type, str):
+            raise ValueError(
+                f"Expected `device_type` of type `str`, got: `{type(device_type)}`"
+            )
+        self.fast_dtype = (
+            torch.get_autocast_dtype(device_type) if dtype is None else dtype
+        )
+        if torch._jit_internal.is_scripting():
+            self._enabled = enabled
+            self.device = device_type
+            if self.fast_dtype is None:
+                raise AssertionError("fast_dtype must not be None in scripting mode")
+            return
+        self.device = device_type
+        if not is_autocast_available(self.device):
+            raise RuntimeError(
+                f"User specified an unsupported autocast device_type '{self.device}'"
+            )
+
+        device_supported_dtypes = [torch.bfloat16, torch.float16]
+
+        self.custom_backend_name = torch._C._get_privateuse1_backend_name()
+        if self.device == self.custom_backend_name:
+            necessary_funcs = [
+                "get_amp_supported_dtype",
+            ]
+            message = f"Tried to use AMP with the `{self.custom_backend_name}` backend, but the backend has not "
+            message += "registered a module or the module misses some necessary funcs. The backend should register "
+            message += "a module by `torch._register_device_module`, and the module must have these funcs: \n"
+            message += "`get_amp_supported_dtype() -> List[torch.dtype]`. \n"
+
+            if not hasattr(torch, self.custom_backend_name):
+                raise AssertionError(message)
+            self.custom_device_mod = getattr(torch, self.custom_backend_name)
+            for func in necessary_funcs:
+                if not hasattr(self.custom_device_mod, func):
+                    raise AssertionError(
+                        message + f"But the func `{func}` is missing. \n"
+                    )
+            device_supported_dtypes = self.custom_device_mod.get_amp_supported_dtype()
+
+        self._cache_enabled = (
+            torch.is_autocast_cache_enabled()
+            if cache_enabled is None
+            else cache_enabled
+        )
+
+        device_name = (
+            self.device
+            if self.device == self.custom_backend_name
+            else self.device.upper()
+        )
+        if enabled:
+            # Special case for CUDA AMP and bfloat16 support
+            if self.device == "cuda":
+                if torch.cuda.amp.common.amp_definitely_not_available():
+                    warnings.warn(
+                        "CUDA is not available or torch_xla is imported. Disabling autocast.",
+                        stacklevel=2,
+                    )
+                    enabled = False
+                elif (
+                    self.fast_dtype == torch.bfloat16
+                    and not torch.cuda.is_bf16_supported()
+                ):
+                    raise RuntimeError(
+                        "Current CUDA Device does not support bfloat16. Please switch dtype to float16."
+                    )
+            elif self.fast_dtype not in device_supported_dtypes:
+                error_message = (
+                    f"In {device_name} autocast, but the target dtype is not supported. Disabling autocast.\n"
+                    f"{device_name} Autocast only supports dtypes of "
+                    + ", ".join(map(str, device_supported_dtypes))
+                    + " currently."
+                )
+                warnings.warn(error_message, stacklevel=2)
+                enabled = False
+        self._enabled = enabled
+
+    def __enter__(self):
+        if torch._jit_internal.is_scripting():
+            if self.fast_dtype is None:
+                raise AssertionError("fast_dtype must not be None in scripting mode")
+            return self
+
+        self.prev_cache_enabled = torch.is_autocast_cache_enabled()
+        self.prev = torch.is_autocast_enabled(self.device)
+        self.prev_fastdtype = torch.get_autocast_dtype(self.device)
+        torch.set_autocast_enabled(self.device, self._enabled)
+        torch.set_autocast_dtype(self.device, self.fast_dtype)  # type: ignore[arg-type]
+        torch.autocast_increment_nesting()
+        torch.set_autocast_cache_enabled(self._cache_enabled)
+
+        # only dispatch to PreDispatchTorchFunctionMode to avoid exposing this
+        # API to other functional modes. We only expose to PreDispatchTorchFunctionMode
+        # for preserving autocast in torch.export.export.
+        if torch._C._is_torch_function_mode_enabled():
+            stacks = torch.overrides._get_current_function_mode_stack()
+            for mode in stacks:
+                if isinstance(
+                    mode,
+                    torch.fx.experimental.proxy_tensor.PreDispatchTorchFunctionMode,
+                ):
+                    args = (
+                        self.device,
+                        self.fast_dtype,
+                        self._enabled,
+                        self._cache_enabled,
+                    )
+                    mode.__torch_function__(torch.amp._enter_autocast, (), args)
+                    return self
+
+        return self
+
+    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any):  # type: ignore[override]
+        if torch._jit_internal.is_scripting():
+            return
+
+        # Drop the cache when we exit to a nesting level that's outside any instance of autocast.
+        if torch.autocast_decrement_nesting() == 0:
+            torch.clear_autocast_cache()
+        torch.set_autocast_enabled(self.device, self.prev)
+        torch.set_autocast_dtype(self.device, self.prev_fastdtype)
+        torch.set_autocast_cache_enabled(self.prev_cache_enabled)
+
+        # only dispatch to PreDispatchTorchFunctionMode to avoid exposing this
+        # API to other functional modes. We only expose to PreDispatchTorchFunctionMode
+        # for preserving autocast in torch.export.export.
+        if torch._C._is_torch_function_mode_enabled():
+            stacks = torch.overrides._get_current_function_mode_stack()
+            for mode in stacks:
+                if isinstance(
+                    mode,
+                    torch.fx.experimental.proxy_tensor.PreDispatchTorchFunctionMode,
+                ):
+                    mode.__torch_function__(torch.amp._exit_autocast, (), ())
+                    # This is very important because the above line actually doesn't
+                    # run exit code so it end up swallowing exceptions.
+                    return False
+        return False
+
+    def __call__(self, func):
+        if torch._jit_internal.is_scripting():
+            return func
+        if not callable(func):
+            raise TypeError(
+                f"autocast()(func) requires a callable, but got {type(func).__name__}. "
+                f"Did you mean to use autocast as a context manager? For example:\n"
+                f"    with torch.autocast(device_type=...):\n"
+                f"        output = model(input)"
+            )
+        return autocast_decorator(self, func)
+
+
+# Subclass to distinguish autocast variables created by _enter_autocast (and not managed by a with statement)
+class _UnmanagedAutocast(autocast):
+    pass
+
+
+# These functions aren't meant for public usage.
+# They are what we trace into a graph during pre_dispatch tracing
+# when we encounter an autocast context manager.
+def _enter_autocast(*vals):
+    # For pre-dispatch tracing, if a TorchFunction mode is active, we'll want to trace this into a graph.
+    if torch._C._is_torch_function_mode_enabled():
+        return torch.overrides.handle_torch_function(
+            torch.amp._enter_autocast, [], *vals
+        )
+    mode = _UnmanagedAutocast(*vals)
+    mode.__enter__()
+    return mode
+
+
+def _exit_autocast(mode):
+    if torch._C._is_torch_function_mode_enabled():
+        return torch.overrides.handle_torch_function(torch.amp._exit_autocast, [], mode)
+    mode.__exit__(None, None, None)
+
+
+# Casts Tensors and containers of Tensors.  Special-cases passthroughs for strings and np.ndarrays, which
+# may be falsely detected as "Iterables."
+def _cast(value, device_type: str, dtype: _dtype):
+    if isinstance(value, torch.Tensor):
+        is_eligible = (
+            value.is_floating_point()
+            and value.device.type == device_type
+            and (value.dtype is not torch.float64)
+        )
+        return value.to(dtype) if is_eligible else value
+    elif isinstance(value, (str, bytes)):
+        return value
+    elif HAS_NUMPY and isinstance(
+        value,
+        # pyrefly: ignore [missing-attribute]
+        np.ndarray,
+    ):
+        return value
+    elif isinstance(value, collections.abc.Mapping):
+        return {
+            _cast(k, device_type, dtype): _cast(v, device_type, dtype)
+            for k, v in value.items()
+        }
+    elif isinstance(value, collections.abc.Iterable):
+        iterable = (_cast(v, device_type, dtype) for v in value)
+        if isinstance(value, (list, tuple)):
+            return type(value)(iterable)
+        else:
+            return iterable
+    else:
+        return value
+
+
+def custom_fwd(
+    fwd=None,
+    *,
+    device_type: str,
+    cast_inputs: _dtype | None = None,
+):
+    """
+    Create a helper decorator for ``forward`` methods of custom autograd functions.
+
+    Autograd functions are subclasses of :class:`torch.autograd.Function`.
+    See the :ref:`example page` for more detail.
+
+    Args:
+        device_type(str):  Device type to use. 'cuda', 'cpu', 'mtia', 'maia', 'xpu' and so on.
+            The type is the same as the `type` attribute of a :class:`torch.device`.
+            Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
+        cast_inputs (:class:`torch.dtype` or None, optional, default=None):  If not ``None``,
+            when ``forward`` runs in an autocast-enabled region, casts incoming
+            floating-point Tensors to the target dtype (non-floating-point Tensors are not affected),
+            then executes ``forward`` with autocast disabled.
+            If ``None``, ``forward``'s internal ops execute with the current autocast state.
+
+    .. note::
+        If the decorated ``forward`` is called outside an autocast-enabled region,
+        :func:`custom_fwd` is a no-op and ``cast_inputs`` has no effect.
+    """
+    if not isinstance(device_type, str):
+        raise ValueError(
+            f"Expected `device_type` of type `str`, got: `{type(device_type)}`"
+        )
+    if fwd is None:
+        return functools.partial(
+            custom_fwd, device_type=device_type, cast_inputs=cast_inputs
+        )
+
+    @functools.wraps(fwd)
+    def decorate_fwd(*args, **kwargs):
+        args[0]._dtype = torch.get_autocast_dtype(device_type)
+        if cast_inputs is None:
+            args[0]._fwd_used_autocast = torch.is_autocast_enabled(device_type)
+            return fwd(*args, **kwargs)  # pyrefly: ignore [not-callable]
+        else:
+            autocast_context = torch.is_autocast_enabled(device_type)
+            args[0]._fwd_used_autocast = False
+            if autocast_context:
+                with autocast(device_type=device_type, enabled=False):
+                    return fwd(  # pyrefly: ignore  # not-callable
+                        *_cast(args, device_type, cast_inputs),
+                        **_cast(kwargs, device_type, cast_inputs),
+                    )
+            else:
+                return fwd(*args, **kwargs)  # pyrefly: ignore [not-callable]
+
+    return decorate_fwd
+
+
+# Autograd ensures incoming gradients are the same type as forward outputs.  Allowing a separate
+# cast_inputs argument on custom_bwd is unnecessary and could cause errors if it doesn't match
+# cast_inputs supplied to custom_fwd.
+def custom_bwd(bwd=None, *, device_type: str):
+    """Create a helper decorator for backward methods of custom autograd functions.
+
+    Autograd functions are subclasses of :class:`torch.autograd.Function`.
+    Ensures that ``backward`` executes with the same autocast state as ``forward``.
+    See the :ref:`example page` for more detail.
+
+    Args:
+        device_type(str):  Device type to use. 'cuda', 'cpu', 'mtia', 'maia', 'xpu' and so on.
+            The type is the same as the `type` attribute of a :class:`torch.device`.
+            Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
+    """
+
+    if not isinstance(device_type, str):
+        raise ValueError(
+            f"Expected `device_type` of type `str`, got: `{type(device_type)}`"
+        )
+    if bwd is None:
+        return functools.partial(custom_bwd, device_type=device_type)
+
+    @functools.wraps(bwd)
+    def decorate_bwd(*args, **kwargs):
+        with autocast(
+            device_type=device_type,
+            enabled=args[0]._fwd_used_autocast,
+            dtype=args[0]._dtype,
+        ):
+            return bwd(*args, **kwargs)  # pyrefly: ignore [not-callable]
+
+    return decorate_bwd
diff --git a/.venv/lib/python3.12/site-packages/torch/amp/grad_scaler.py b/.venv/lib/python3.12/site-packages/torch/amp/grad_scaler.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1592efe9f737030aa6d15ce03d45325e33ef40a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/amp/grad_scaler.py
@@ -0,0 +1,714 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import inspect
+import warnings
+from collections import abc, defaultdict
+from enum import Enum
+from typing import Any, cast, overload, TYPE_CHECKING
+
+import torch
+
+
+if TYPE_CHECKING:
+    from collections.abc import Iterable
+
+
+__all__ = ["OptState", "GradScaler"]
+
+
+class _MultiDeviceReplicator:
+    """Lazily serves copies of a tensor to requested devices.
+
+    Copies are cached per-device.
+    """
+
+    def __init__(self, master_tensor: torch.Tensor) -> None:
+        self.master = master_tensor
+        self._per_device_tensors: dict[torch.device, torch.Tensor] = {}
+
+    def get(self, device: torch.device) -> torch.Tensor:
+        retval = self._per_device_tensors.get(device, None)
+        if retval is None:
+            retval = self.master.to(device=device, non_blocking=True, copy=True)
+            self._per_device_tensors[device] = retval
+        return retval
+
+
+# Defines default_factory for GradScaler's _per_optimizer_states defaultdict,
+# as well as associated "enum" values.  Prefers defining these at top level because
+# - Lambdas can't be pickled, so we don't want to supply a lambda as the factory.
+# - Defining READY, UNSCALED, STEPPED and _refresh_per_optimizer_state within GradScaler
+#   causes a circular reference, which we'd rather avoid.
+class OptState(Enum):
+    READY = 0
+    UNSCALED = 1
+    STEPPED = 2
+
+
+def _refresh_per_optimizer_state() -> dict[str, Any]:
+    return {"stage": OptState.READY, "found_inf_per_device": {}}
+
+
+class GradScaler:
+    """An instance ``scaler`` of :class:`GradScaler`.
+
+    Helps perform the steps of gradient scaling
+    conveniently.
+
+    * ``scaler.scale(loss)`` multiplies a given loss by ``scaler``'s current scale factor.
+    * ``scaler.step(optimizer)`` safely unscales gradients and calls ``optimizer.step()``.
+    * ``scaler.update()`` updates ``scaler``'s scale factor.
+
+    Example::
+
+        # Creates a GradScaler once at the beginning of training.
+        scaler = GradScaler()
+
+        for epoch in epochs:
+            for input, target in data:
+                optimizer.zero_grad()
+                output = model(input)
+                loss = loss_fn(output, target)
+
+                # Scales loss.  Calls backward() on scaled loss to create scaled gradients.
+                scaler.scale(loss).backward()
+
+                # scaler.step() first unscales gradients of the optimizer's params.
+                # If gradients don't contain infs/NaNs, optimizer.step() is then called,
+                # otherwise, optimizer.step() is skipped.
+                scaler.step(optimizer)
+
+                # Updates the scale for next iteration.
+                scaler.update()
+
+    See the :ref:`Automatic Mixed Precision examples` for usage
+    (along with autocasting) in more complex cases like gradient clipping, gradient accumulation, gradient penalty,
+    and multiple losses/optimizers.
+
+    ``scaler`` dynamically estimates the scale factor each iteration.  To minimize gradient underflow,
+    a large scale factor should be used.  However, ``float16`` values can "overflow" (become inf or NaN) if
+    the scale factor is too large.  Therefore, the optimal scale factor is the largest factor that can be used
+    without incurring inf or NaN gradient values.
+    ``scaler`` approximates the optimal scale factor over time by checking the gradients for infs and NaNs during every
+    ``scaler.step(optimizer)`` (or optional separate ``scaler.unscale_(optimizer)``, see :meth:`unscale_`).
+
+    * If infs/NaNs are found, ``scaler.step(optimizer)`` skips the underlying ``optimizer.step()`` (so the params
+      themselves remain uncorrupted) and ``update()`` multiplies the scale by ``backoff_factor``.
+
+    * If no infs/NaNs are found, ``scaler.step(optimizer)`` runs the underlying ``optimizer.step()`` as usual.
+      If ``growth_interval`` unskipped iterations occur consecutively, ``update()`` multiplies the scale by
+      ``growth_factor``.
+
+    The scale factor often causes infs/NaNs to appear in gradients for the first few iterations as its
+    value calibrates.  ``scaler.step`` will skip the underlying ``optimizer.step()`` for these
+    iterations.  After that, step skipping should occur rarely (once every few hundred or thousand iterations).
+
+    Args:
+        device (str, optional, default="cuda"): Device type to use. Possible values are: 'cuda' and 'cpu'.
+            The type is the same as the `type` attribute of a :class:`torch.device`.
+            Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
+        init_scale (float, optional, default=2.**16):  Initial scale factor.
+        growth_factor (float, optional, default=2.0):  Factor by which the scale is multiplied during
+            :meth:`update` if no inf/NaN gradients occur for ``growth_interval`` consecutive iterations.
+        backoff_factor (float, optional, default=0.5):  Factor by which the scale is multiplied during
+            :meth:`update` if inf/NaN gradients occur in an iteration.
+        growth_interval (int, optional, default=2000):  Number of consecutive iterations without inf/NaN gradients
+            that must occur for the scale to be multiplied by ``growth_factor``.
+        enabled (bool, optional):  If ``False``, disables gradient scaling. :meth:`step` simply
+            invokes the underlying ``optimizer.step()``, and other methods become no-ops.
+            Default: ``True``
+    """
+
+    def __init__(
+        self,
+        device: str = "cuda",
+        init_scale: float = 2.0**16,
+        growth_factor: float = 2.0,
+        backoff_factor: float = 0.5,
+        growth_interval: int = 2000,
+        enabled: bool = True,
+    ) -> None:
+        self._device = device
+        self._enabled = enabled
+        if self._device == "cuda":
+            if enabled and torch.cuda.amp.common.amp_definitely_not_available():
+                warnings.warn(
+                    "torch.cuda.amp.GradScaler is enabled, but CUDA is not available.  Disabling.",
+                    stacklevel=2,
+                )
+                self._enabled = False
+
+        if self._enabled:
+            if growth_factor <= 1.0:
+                raise AssertionError("The growth factor must be > 1.0.")
+            if backoff_factor >= 1.0:
+                raise AssertionError("The backoff factor must be < 1.0.")
+
+            self._init_scale = init_scale
+            # self._scale will be lazily initialized during the first call to scale()
+            self._scale: torch.Tensor | None = None
+            self._growth_factor = growth_factor
+            self._backoff_factor = backoff_factor
+            self._growth_interval = growth_interval
+            self._init_growth_tracker = 0
+            # self._growth_tracker will be lazily initialized during the first call to scale()
+            self._growth_tracker: torch.Tensor | None = None
+            self._per_optimizer_states: dict[int, dict[str, Any]] = defaultdict(
+                _refresh_per_optimizer_state
+            )
+
+    def _check_scale_growth_tracker(
+        self, funcname: str
+    ) -> tuple[torch.Tensor, torch.Tensor]:
+        fix = "This may indicate your script did not use scaler.scale(loss or outputs) earlier in the iteration."
+        if self._scale is None:
+            raise AssertionError(f"Attempted {funcname} but _scale is None.  " + fix)
+        if self._growth_tracker is None:
+            raise AssertionError(
+                f"Attempted {funcname} but _growth_tracker is None.  " + fix
+            )
+        return (self._scale, self._growth_tracker)
+
+    def _lazy_init_scale_growth_tracker(self, dev: torch.device) -> None:
+        if self._growth_tracker is not None:
+            raise AssertionError("_growth_tracker initialized before _scale")
+        self._scale = torch.full((), self._init_scale, dtype=torch.float32, device=dev)
+        self._growth_tracker = torch.full(
+            (), self._init_growth_tracker, dtype=torch.int32, device=dev
+        )
+
+    @overload
+    def scale(self, outputs: torch.Tensor) -> torch.Tensor: ...
+
+    @overload
+    def scale(self, outputs: list[torch.Tensor]) -> list[torch.Tensor]: ...
+
+    @overload
+    def scale(self, outputs: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]: ...
+
+    @overload
+    def scale(self, outputs: Iterable[torch.Tensor]) -> Iterable[torch.Tensor]: ...
+
+    def scale(
+        self,
+        outputs: torch.Tensor | Iterable[torch.Tensor],
+    ) -> torch.Tensor | Iterable[torch.Tensor]:
+        """
+        Multiplies ('scales') a tensor or list of tensors by the scale factor.
+
+        Returns scaled outputs.  If this instance of :class:`GradScaler` is not enabled, outputs are returned
+        unmodified.
+
+        Args:
+            outputs (Tensor or iterable of Tensors):  Outputs to scale.
+        """
+        if not self._enabled:
+            return outputs
+
+        # Short-circuit for the common case.
+        if isinstance(outputs, torch.Tensor):
+            if self._scale is None:
+                self._lazy_init_scale_growth_tracker(outputs.device)
+            # _scale is now guaranteed to be set
+            scale = self._scale
+            if scale is None:
+                raise AssertionError("_scale should not be None after lazy init")
+            return outputs * scale.to(device=outputs.device, non_blocking=True)
+
+        # Invoke the more complex machinery only if we're treating multiple outputs.
+        stash: list[
+            _MultiDeviceReplicator
+        ] = []  # holds a reference that can be overwritten by apply_scale
+
+        def apply_scale(val: torch.Tensor | Iterable[torch.Tensor]):
+            if isinstance(val, torch.Tensor):
+                if len(stash) == 0:
+                    if self._scale is None:
+                        self._lazy_init_scale_growth_tracker(val.device)
+                    # _scale is now guaranteed to be set
+                    scale = self._scale
+                    if scale is None:
+                        raise AssertionError(
+                            "_scale should not be None after lazy init"
+                        )
+                    stash.append(_MultiDeviceReplicator(scale))
+                return val * stash[0].get(val.device)
+            if isinstance(val, abc.Iterable):
+                iterable = map(apply_scale, val)
+                if isinstance(val, (list, tuple)):
+                    return type(val)(iterable)
+                return iterable
+            raise ValueError("outputs must be a Tensor or an iterable of Tensors")
+
+        return apply_scale(outputs)
+
+    def _unscale_grads_(
+        self,
+        optimizer: torch.optim.Optimizer,
+        inv_scale: torch.Tensor,
+        found_inf: torch.Tensor,
+        allow_fp16: bool,
+    ) -> dict[torch.device, torch.Tensor]:
+        per_device_inv_scale = _MultiDeviceReplicator(inv_scale)
+        per_device_found_inf = _MultiDeviceReplicator(found_inf)
+
+        # To set up _amp_foreach_non_finite_check_and_unscale_, split grads by device and dtype.
+        # There could be hundreds of grads, so we'd like to iterate through them just once.
+        # However, we don't know their devices or dtypes in advance.
+
+        # https://stackoverflow.com/questions/5029934/defaultdict-of-defaultdict
+        # Google says mypy struggles with defaultdicts type annotations.
+        per_device_and_dtype_grads: dict[
+            torch.device, dict[torch.dtype, list[torch.Tensor]]
+        ] = defaultdict(lambda: defaultdict(list))
+        with torch.no_grad():
+            for group in optimizer.param_groups:
+                for param in group["params"]:
+                    if not isinstance(param, torch.Tensor):
+                        raise AssertionError(
+                            f"expected param to be torch.Tensor, got {type(param).__name__}"
+                        )
+                    if param.grad is None:
+                        continue
+                    if (not allow_fp16) and param.grad.dtype == torch.float16:
+                        raise ValueError("Attempting to unscale FP16 gradients.")
+                    if param.grad.is_sparse:
+                        # is_coalesced() == False means the sparse grad has values with duplicate indices.
+                        # coalesce() deduplicates indices and adds all values that have the same index.
+                        # For scaled fp16 values, there's a good chance coalescing will cause overflow,
+                        # so we should check the coalesced _values().
+                        if param.grad.dtype is torch.float16:
+                            param.grad = param.grad.coalesce()
+                        to_unscale = param.grad._values()
+                    else:
+                        to_unscale = param.grad
+
+                    # TODO: is there a way to split by device and dtype without appending in the inner loop?
+                    per_device_and_dtype_grads[to_unscale.device][
+                        to_unscale.dtype
+                    ].append(to_unscale)
+
+            for device, per_dtype_grads in per_device_and_dtype_grads.items():
+                for grads in per_dtype_grads.values():
+                    torch._amp_foreach_non_finite_check_and_unscale_(
+                        grads,
+                        per_device_found_inf.get(device),
+                        per_device_inv_scale.get(device),
+                    )
+
+        return per_device_found_inf._per_device_tensors
+
+    def unscale_(self, optimizer: torch.optim.Optimizer) -> None:
+        """
+        Divides ("unscales") the optimizer's gradient tensors by the scale factor.
+
+        :meth:`unscale_` is optional, serving cases where you need to
+        :ref:`modify or inspect gradients`
+        between the backward pass(es) and :meth:`step`.
+        If :meth:`unscale_` is not called explicitly,  gradients will be unscaled  automatically during :meth:`step`.
+
+        Simple example, using :meth:`unscale_` to enable clipping of unscaled gradients::
+
+            ...
+            scaler.scale(loss).backward()
+            scaler.unscale_(optimizer)
+            torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)
+            scaler.step(optimizer)
+            scaler.update()
+
+        Args:
+            optimizer (torch.optim.Optimizer):  Optimizer that owns the gradients to be unscaled.
+
+        .. note::
+            :meth:`unscale_` does not incur a CPU-GPU sync.
+
+        .. warning::
+            :meth:`unscale_` should only be called once per optimizer per :meth:`step` call,
+            and only after all gradients for that optimizer's assigned parameters have been accumulated.
+            Calling :meth:`unscale_` twice for a given optimizer between each :meth:`step` triggers a RuntimeError.
+
+        .. warning::
+            :meth:`unscale_` may unscale sparse gradients out of place, replacing the ``.grad`` attribute.
+        """
+        if not self._enabled:
+            return
+
+        self._check_scale_growth_tracker("unscale_")
+
+        optimizer_state = self._per_optimizer_states[id(optimizer)]
+
+        if optimizer_state["stage"] is OptState.UNSCALED:
+            raise RuntimeError(
+                "unscale_() has already been called on this optimizer since the last update()."
+            )
+        elif optimizer_state["stage"] is OptState.STEPPED:
+            raise RuntimeError("unscale_() is being called after step().")
+
+        # FP32 division can be imprecise for certain compile options, so we carry out the reciprocal in FP64.
+        if self._scale is None:
+            raise AssertionError("_scale is None in unscale_")
+        inv_scale = (
+            self._scale.double().reciprocal().float()
+            if self._scale.device != torch.device("mps:0")
+            else self._scale.reciprocal()
+        )
+        found_inf = torch.full((), 0.0, dtype=torch.float32, device=self._scale.device)
+
+        optimizer_state["found_inf_per_device"] = self._unscale_grads_(
+            optimizer, inv_scale, found_inf, False
+        )
+        optimizer_state["stage"] = OptState.UNSCALED
+
+    def _maybe_opt_step(
+        self,
+        optimizer: torch.optim.Optimizer,
+        optimizer_state: dict[str, Any],
+        *args: Any,
+        **kwargs: Any,
+    ) -> float | None:
+        retval: float | None = None
+        if not sum(v.item() for v in optimizer_state["found_inf_per_device"].values()):
+            retval = optimizer.step(*args, **kwargs)
+        return retval
+
+    def step(
+        self, optimizer: torch.optim.Optimizer, *args: Any, **kwargs: Any
+    ) -> float | None:
+        """Invoke ``unscale_(optimizer)`` followed by parameter update, if gradients are not infs/NaN.
+
+        :meth:`step` carries out the following two operations:
+
+        1.  Internally invokes ``unscale_(optimizer)`` (unless :meth:`unscale_` was explicitly called for ``optimizer``
+            earlier in the iteration).  As part of the :meth:`unscale_`, gradients are checked for infs/NaNs.
+        2.  If no inf/NaN gradients are found, invokes ``optimizer.step()`` using the unscaled
+            gradients.  Otherwise, ``optimizer.step()`` is skipped to avoid corrupting the params.
+
+        ``*args`` and ``**kwargs`` are forwarded to ``optimizer.step()``.
+
+        Returns the return value of ``optimizer.step(*args, **kwargs)``.
+
+        Args:
+            optimizer (torch.optim.Optimizer):  Optimizer that applies the gradients.
+            args:  Any arguments.
+            kwargs:  Any keyword arguments.
+
+        .. warning::
+            Closure use is not currently supported.
+        """
+        if not self._enabled:
+            return optimizer.step(*args, **kwargs)
+
+        if "closure" in kwargs:
+            raise RuntimeError(
+                "Closure use is not currently supported if GradScaler is enabled."
+            )
+
+        self._check_scale_growth_tracker("step")
+
+        optimizer_state = self._per_optimizer_states[id(optimizer)]
+
+        if optimizer_state["stage"] is OptState.STEPPED:
+            raise RuntimeError(
+                "step() has already been called since the last update()."
+            )
+
+        retval: float | None = None
+
+        if getattr(optimizer, "_step_supports_amp_scaling", False):
+            # This optimizer has customized scale-handling logic, so we can call optimizer.step() directly.
+            # The contract with custom optimizers is that their step() should accept an additional,
+            # optional grad_scaler kwarg.  We append self to the kwargs so the custom optimizer has full information:
+            # it can query its own state, invoke unscale_ on itself, etc
+            # The contract above is being deprecated to avoid introducing `grad_scaler: GradScaler` argument
+            # to `Optimizer.step`. The new behavior is going to add two Tensor attributes of `grad_scale`
+            # and `found_inf` to the passed optimizer so that the optimizer can utilize those
+            # to skip the parameter updates or unscale gradients before updating parameters in
+            # the fused kernel, e.g. `FusedAdamMathFunctor`.
+            # In this behavior, `GradScaler._check_inf_per_device` is called if `OptState.READY`,
+            # while the method is expected to be called by users side, i.e. their optimizers.
+            kwargs_ = kwargs
+            has_grad_scaler_kwarg = (
+                "grad_scaler" in inspect.signature(optimizer.step).parameters
+            )
+            if has_grad_scaler_kwarg:
+                warnings.warn(
+                    "GradScaler is going to stop passing itself as a keyword argument to the passed "
+                    "optimizer. In the near future GradScaler registers `grad_scale: Tensor` and "
+                    "`found_inf: Tensor` to the passed optimizer and let the optimizer use them directly.",
+                    FutureWarning,
+                    stacklevel=2,
+                )
+                kwargs_.update({"grad_scaler": self})
+            else:
+                if optimizer_state["stage"] is OptState.READY:
+                    self._check_inf_per_device(optimizer)
+                scaler = self._get_scale_async()
+                if scaler is None:
+                    raise AssertionError("_get_scale_async returned None")
+                found_inf = cast(
+                    torch.Tensor,
+                    sum(
+                        [
+                            t.to(scaler.device, non_blocking=True)
+                            for t in optimizer_state["found_inf_per_device"].values()
+                        ]
+                    ),
+                )
+                # Take the product of the scales, if the user has already set `optimizer.grad_scale`.
+                optimizer.grad_scale = (  # type: ignore[attr-defined]
+                    getattr(optimizer, "grad_scale", None)
+                    if optimizer_state["stage"] == OptState.UNSCALED
+                    else scaler * getattr(optimizer, "grad_scale", 1)
+                )
+                optimizer.found_inf = found_inf  # type: ignore[attr-defined]
+            retval = optimizer.step(*args, **kwargs_)
+            optimizer_state["stage"] = OptState.STEPPED
+            if not has_grad_scaler_kwarg:
+                del optimizer.grad_scale  # type: ignore[attr-defined]
+                del optimizer.found_inf  # type: ignore[attr-defined]
+            return retval
+
+        if optimizer_state["stage"] is OptState.READY:
+            self.unscale_(optimizer)
+
+        if len(optimizer_state["found_inf_per_device"]) == 0:
+            raise AssertionError("No inf checks were recorded for this optimizer.")
+
+        retval = self._maybe_opt_step(optimizer, optimizer_state, *args, **kwargs)
+
+        optimizer_state["stage"] = OptState.STEPPED
+
+        return retval
+
+    def update(self, new_scale: float | torch.Tensor | None = None) -> None:
+        """Update the scale factor.
+
+        If any optimizer steps were skipped the scale is multiplied by ``backoff_factor``
+        to reduce it. If ``growth_interval`` unskipped iterations occurred consecutively,
+        the scale is multiplied by ``growth_factor`` to increase it.
+
+        Passing ``new_scale`` sets the new scale value manually. (``new_scale`` is not
+        used directly, it's used to fill GradScaler's internal scale tensor. So if
+        ``new_scale`` was a tensor, later in-place changes to that tensor will not further
+        affect the scale GradScaler uses internally.)
+
+        Args:
+            new_scale (float or :class:`torch.Tensor`, optional, default=None):  New scale factor.
+
+        .. warning::
+            :meth:`update` should only be called at the end of the iteration, after ``scaler.step(optimizer)`` has
+            been invoked for all optimizers used this iteration.
+
+        .. warning::
+            For performance reasons, we do not check the scale factor value to avoid synchronizations,
+            so the scale factor is not guaranteed to be above 1. If the scale falls below 1 and/or
+            you are seeing NaNs in your gradients or loss, something is likely wrong. For example,
+            bf16-pretrained models are often incompatible with AMP/fp16 due to differing dynamic ranges.
+        """
+        if not self._enabled:
+            return
+
+        _scale, _growth_tracker = self._check_scale_growth_tracker("update")
+
+        if new_scale is not None:
+            if self._scale is None:
+                raise AssertionError("_scale is None in update")
+            # Accept a new user-defined scale.
+            if isinstance(new_scale, float):
+                self._scale.fill_(new_scale)
+            else:
+                reason = (
+                    "new_scale should be a float or a 1-element torch.cuda.FloatTensor or "
+                    "torch.FloatTensor with requires_grad=False."
+                )
+                if new_scale.device.type != self._device:
+                    raise AssertionError(reason)
+                if new_scale.numel() != 1:
+                    raise AssertionError(reason)
+                if new_scale.requires_grad is True:
+                    raise AssertionError(reason)
+                self._scale.copy_(new_scale)
+        else:
+            # Consume shared inf/nan data collected from optimizers to update the scale.
+            # If all found_inf tensors are on the same device as self._scale, this operation is asynchronous.
+            found_infs = [
+                found_inf.to(device=_scale.device, non_blocking=True)
+                for state in self._per_optimizer_states.values()
+                for found_inf in state["found_inf_per_device"].values()
+            ]
+
+            if len(found_infs) == 0:
+                raise AssertionError("No inf checks were recorded prior to update.")
+
+            found_inf_combined = found_infs[0]
+            if len(found_infs) > 1:
+                for i in range(1, len(found_infs)):
+                    found_inf_combined += found_infs[i]
+
+            torch._amp_update_scale_(
+                _scale,
+                _growth_tracker,
+                found_inf_combined,
+                self._growth_factor,
+                self._backoff_factor,
+                self._growth_interval,
+            )
+
+        # To prepare for next iteration, clear the data collected from optimizers this iteration.
+        self._per_optimizer_states = defaultdict(_refresh_per_optimizer_state)
+
+    def _get_scale_async(self) -> torch.Tensor | None:
+        return self._scale
+
+    def get_scale(self) -> float:
+        """Return a Python float containing the current scale, or 1.0 if scaling is disabled.
+
+        .. warning::
+            :meth:`get_scale` incurs a CPU-GPU sync.
+        """
+        if self._enabled:
+            return (
+                self._init_scale
+                if (scale := self._get_scale_async()) is None
+                else cast(float, scale.item())
+            )
+        return 1.0
+
+    def get_growth_factor(self) -> float:
+        r"""Return a Python float containing the scale growth factor."""
+        return self._growth_factor
+
+    def set_growth_factor(self, new_factor: float) -> None:
+        r"""Set a new scale growth factor.
+
+        Args:
+            new_scale (float):  Value to use as the new scale growth factor.
+        """
+        self._growth_factor = new_factor
+
+    def get_backoff_factor(self) -> float:
+        r"""Return a Python float containing the scale backoff factor."""
+        return self._backoff_factor
+
+    def set_backoff_factor(self, new_factor: float) -> None:
+        r"""Set a new scale backoff factor.
+
+        Args:
+            new_scale (float):  Value to use as the new scale backoff factor.
+        """
+        self._backoff_factor = new_factor
+
+    def get_growth_interval(self) -> int:
+        r"""Return a Python int containing the growth interval."""
+        return self._growth_interval
+
+    def set_growth_interval(self, new_interval: int) -> None:
+        r"""Set a new growth interval.
+
+        Args:
+            new_interval (int):  Value to use as the new growth interval.
+        """
+        self._growth_interval = new_interval
+
+    def _get_growth_tracker(self) -> int:
+        if self._enabled:
+            return (
+                self._init_growth_tracker
+                if self._growth_tracker is None
+                else cast(int, self._growth_tracker.item())
+            )
+        return 0
+
+    def is_enabled(self) -> bool:
+        r"""Return a bool indicating whether this instance is enabled."""
+        return self._enabled
+
+    def state_dict(self) -> dict[str, Any]:
+        r"""Return the state of the scaler as a :class:`dict`.
+
+        It contains five entries:
+
+        * ``"scale"`` - a Python float containing the current scale
+        * ``"growth_factor"`` - a Python float containing the current growth factor
+        * ``"backoff_factor"`` - a Python float containing the current backoff factor
+        * ``"growth_interval"`` - a Python int containing the current growth interval
+        * ``"_growth_tracker"`` - a Python int containing the number of recent consecutive unskipped steps.
+
+        If this instance is not enabled, returns an empty dict.
+
+        .. note::
+           If you wish to checkpoint the scaler's state after a particular iteration, :meth:`state_dict`
+           should be called after :meth:`update`.
+        """
+        if self._enabled:
+            return {
+                "scale": self.get_scale(),
+                "growth_factor": self._growth_factor,
+                "backoff_factor": self._backoff_factor,
+                "growth_interval": self._growth_interval,
+                "_growth_tracker": self._get_growth_tracker(),
+            }
+        return {}
+
+    def load_state_dict(self, state_dict: dict[str, Any]) -> None:
+        r"""Load the scaler state.
+
+        If this instance is disabled, :meth:`load_state_dict` is a no-op.
+
+        Args:
+           state_dict(dict): scaler state.  Should be an object returned from a call to :meth:`state_dict`.
+        """
+        if not self._enabled:
+            return
+
+        if len(state_dict) == 0:
+            raise RuntimeError(
+                "The source state dict is empty, possibly because it was saved "
+                "from a disabled instance of GradScaler."
+            )
+
+        self._init_scale = cast(float, state_dict["scale"])
+        if self._scale is not None:
+            self._scale.fill_(state_dict["scale"])
+        self._growth_factor = cast(float, state_dict["growth_factor"])
+        self._backoff_factor = cast(float, state_dict["backoff_factor"])
+        self._growth_interval = cast(int, state_dict["growth_interval"])
+        self._init_growth_tracker = cast(int, state_dict["_growth_tracker"])
+        if self._growth_tracker is not None:
+            self._growth_tracker.fill_(state_dict["_growth_tracker"])
+
+    def __getstate__(self) -> dict[str, Any]:
+        state = self.__dict__.copy()
+        if self._enabled:
+            if len(self._per_optimizer_states) != 0:
+                raise AssertionError(
+                    "A GradScaler instance may only be pickled at the beginning "
+                    "of an iteration, or at the end after scaler.update()."
+                )
+            # Pickling _scale and _growth_tracker Tensors directly triggers
+            # "warnings.warn("pickle support for Storage will be removed in 1.5..."
+            # so instead, we set the unpickled instance up to reinitialize them lazily.
+            state["_init_scale"] = self.get_scale()
+            state["_init_growth_tracker"] = self._get_growth_tracker()
+            state["_scale"] = None
+            state["_growth_tracker"] = None
+        return state
+
+    def __setstate__(self, state: dict[str, Any]) -> None:
+        self.__dict__.update(state)
+
+    def _check_inf_per_device(self, optimizer: torch.optim.Optimizer) -> dict[str, Any]:
+        _scale, _ = self._check_scale_growth_tracker("_check_inf_per_device")
+
+        dummy_inv_scale = torch.full((), 1.0, dtype=torch.float32, device=_scale.device)
+        found_inf = torch.full((), 0.0, dtype=torch.float32, device=_scale.device)
+
+        self._per_optimizer_states[id(optimizer)]["found_inf_per_device"] = (
+            self._unscale_grads_(optimizer, dummy_inv_scale, found_inf, True)
+        )
+
+        return self._per_optimizer_states[id(optimizer)]["found_inf_per_device"]
+
+    def _found_inf_per_device(self, optimizer: torch.optim.Optimizer) -> dict[str, Any]:
+        return self._per_optimizer_states[id(optimizer)]["found_inf_per_device"]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0919208c4201f69c91c69fbca9246e54854a6100
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/__init__.py
@@ -0,0 +1,31 @@
+# torch.ao is a package with a lot of interdependencies.
+# We will use lazy import to avoid cyclic dependencies here.
+
+from typing import TYPE_CHECKING as _TYPE_CHECKING
+
+
+if _TYPE_CHECKING:
+    from types import ModuleType
+
+    from torch.ao import (
+        nn as nn,
+        ns as ns,
+        pruning as pruning,
+        quantization as quantization,
+    )
+
+
+__all__ = [
+    "nn",
+    "ns",
+    "pruning",
+    "quantization",
+]
+
+
+def __getattr__(name: str) -> "ModuleType":
+    if name in __all__:
+        import importlib
+
+        return importlib.import_module("." + name, __name__)
+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa58f1e70b79c29eae10fa1971a680ba499eb1bf
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3f48fa2bb34214d05255b78e73013ece57d9f92
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/__init__.py
@@ -0,0 +1,35 @@
+# We are exposing all subpackages to the end-user.
+# Because of possible inter-dependency, we want to avoid
+# the cyclic imports, thus implementing lazy version
+# as per https://peps.python.org/pep-0562/
+
+from typing import TYPE_CHECKING as _TYPE_CHECKING
+
+
+if _TYPE_CHECKING:
+    from types import ModuleType
+
+    from torch.ao.nn import (
+        intrinsic as intrinsic,
+        qat as qat,
+        quantizable as quantizable,
+        quantized as quantized,
+        sparse as sparse,
+    )
+
+
+__all__ = [
+    "intrinsic",
+    "qat",
+    "quantizable",
+    "quantized",
+    "sparse",
+]
+
+
+def __getattr__(name: str) -> "ModuleType":
+    if name in __all__:
+        import importlib
+
+        return importlib.import_module("." + name, __name__)
+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eebf87953c7d7e9d73852f13dcecf11ce059878c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5236cb7ba7e1de7aa5c601c42b0746d4e3b46b02
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/__init__.py
@@ -0,0 +1,41 @@
+import types
+
+from .modules import *  # noqa: F403
+from .modules.fused import _FusedModule
+
+
+# # Subpackages
+# from . import qat
+# from . import quantized
+
+__all__ = [
+    "ConvBn1d",
+    "ConvBn2d",
+    "ConvBn3d",
+    "ConvBnReLU1d",
+    "ConvBnReLU2d",
+    "ConvBnReLU3d",
+    "ConvReLU1d",
+    "ConvReLU2d",
+    "ConvReLU3d",
+    "LinearReLU",
+    "BNReLU2d",
+    "BNReLU3d",
+    "LinearBn1d",
+    "LinearLeakyReLU",
+    "LinearTanh",
+    "ConvAdd2d",
+    "ConvAddReLU2d",
+]
+
+
+# We are exposing all subpackages to the end-user.
+# Because of possible inter-dependency, we want to avoid
+# the cyclic imports, thus implementing lazy version
+# as per https://peps.python.org/pep-0562/
+def __getattr__(name: str) -> types.ModuleType:
+    if name in __all__:
+        import importlib
+
+        return importlib.import_module("." + name, __name__)
+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d3deff6aac40d115badd2b3e0fe82c930fec4b4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/modules/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..038d4b567f902e7225a9367bf60836d2097a11e6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/modules/__init__.py
@@ -0,0 +1,41 @@
+from .fused import (
+    _FusedModule,
+    BNReLU2d,
+    BNReLU3d,
+    ConvAdd2d,
+    ConvAddReLU2d,
+    ConvBn1d,
+    ConvBn2d,
+    ConvBn3d,
+    ConvBnReLU1d,
+    ConvBnReLU2d,
+    ConvBnReLU3d,
+    ConvReLU1d,
+    ConvReLU2d,
+    ConvReLU3d,
+    LinearBn1d,
+    LinearLeakyReLU,
+    LinearReLU,
+    LinearTanh,
+)
+
+
+__all__ = [
+    "ConvBn1d",
+    "ConvBn2d",
+    "ConvBn3d",
+    "ConvBnReLU1d",
+    "ConvBnReLU2d",
+    "ConvBnReLU3d",
+    "ConvReLU1d",
+    "ConvReLU2d",
+    "ConvReLU3d",
+    "LinearReLU",
+    "BNReLU2d",
+    "BNReLU3d",
+    "LinearBn1d",
+    "LinearLeakyReLU",
+    "LinearTanh",
+    "ConvAdd2d",
+    "ConvAddReLU2d",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/modules/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/modules/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bbb96cecd01bd53f806a0fc9771d91c70d38d3d6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/modules/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/modules/__pycache__/fused.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/modules/__pycache__/fused.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45a0b6a8bcaf5114f07a5f1ee6bf143685fc6aab
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/modules/__pycache__/fused.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/modules/fused.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/modules/fused.py
new file mode 100644
index 0000000000000000000000000000000000000000..65f86b79676e513b9b40fa3cbdf519cb29d9dd6a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/modules/fused.py
@@ -0,0 +1,319 @@
+# mypy: allow-untyped-defs
+import torch
+from torch.nn import (
+    BatchNorm1d,
+    BatchNorm2d,
+    BatchNorm3d,
+    Conv1d,
+    Conv2d,
+    Conv3d,
+    Linear,
+    ReLU,
+)
+from torch.nn.utils.parametrize import type_before_parametrizations
+
+
+__all__ = [
+    "ConvReLU1d",
+    "ConvReLU2d",
+    "ConvReLU3d",
+    "LinearReLU",
+    "ConvBn1d",
+    "ConvBn2d",
+    "ConvBnReLU1d",
+    "ConvBnReLU2d",
+    "ConvBn3d",
+    "ConvBnReLU3d",
+    "BNReLU2d",
+    "BNReLU3d",
+    "LinearBn1d",
+    "LinearLeakyReLU",
+    "LinearTanh",
+    "ConvAdd2d",
+    "ConvAddReLU2d",
+]
+
+
+# Used for identifying intrinsic modules used in quantization
+class _FusedModule(torch.nn.Sequential):
+    pass
+
+
+class ConvReLU1d(_FusedModule):
+    r"""This is a sequential container which calls the Conv1d and ReLU modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, conv, relu):
+        if not (
+            type_before_parametrizations(conv) == Conv1d
+            and type_before_parametrizations(relu) == ReLU
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(conv).__name__} and "
+                f"{type_before_parametrizations(relu).__name__}"
+            )
+        super().__init__(conv, relu)
+
+
+class ConvReLU2d(_FusedModule):
+    r"""This is a sequential container which calls the Conv2d and ReLU modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, conv, relu):
+        if not (
+            type_before_parametrizations(conv) == Conv2d
+            and type_before_parametrizations(relu) == ReLU
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(conv).__name__} and "
+                f"{type_before_parametrizations(relu).__name__}"
+            )
+        super().__init__(conv, relu)
+
+
+class ConvReLU3d(_FusedModule):
+    r"""This is a sequential container which calls the Conv3d and ReLU modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, conv, relu):
+        if not (
+            type_before_parametrizations(conv) == Conv3d
+            and type_before_parametrizations(relu) == ReLU
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(conv).__name__} and "
+                f"{type_before_parametrizations(relu).__name__}"
+            )
+        super().__init__(conv, relu)
+
+
+class LinearReLU(_FusedModule):
+    r"""This is a sequential container which calls the Linear and ReLU modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, linear, relu):
+        if not (
+            type_before_parametrizations(linear) == Linear
+            and type_before_parametrizations(relu) == ReLU
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(linear).__name__} and "
+                f"{type_before_parametrizations(relu).__name__}"
+            )
+        super().__init__(linear, relu)
+
+
+class ConvBn1d(_FusedModule):
+    r"""This is a sequential container which calls the Conv 1d and Batch Norm 1d modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, conv, bn):
+        if not (
+            type_before_parametrizations(conv) == Conv1d
+            and type_before_parametrizations(bn) == BatchNorm1d
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(conv).__name__} and "
+                f"{type_before_parametrizations(bn).__name__}"
+            )
+        super().__init__(conv, bn)
+
+
+class ConvBn2d(_FusedModule):
+    r"""This is a sequential container which calls the Conv 2d and Batch Norm 2d modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, conv, bn):
+        if not (
+            type_before_parametrizations(conv) == Conv2d
+            and type_before_parametrizations(bn) == BatchNorm2d
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(conv).__name__} and "
+                f"{type_before_parametrizations(bn).__name__}"
+            )
+        super().__init__(conv, bn)
+
+
+class ConvBnReLU1d(_FusedModule):
+    r"""This is a sequential container which calls the Conv 1d, Batch Norm 1d, and ReLU modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, conv, bn, relu):
+        if not (
+            type_before_parametrizations(conv) == Conv1d
+            and type_before_parametrizations(bn) == BatchNorm1d
+            and type_before_parametrizations(relu) == ReLU
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(conv).__name__}, "
+                f"{type_before_parametrizations(bn).__name__}, and "
+                f"{type_before_parametrizations(relu).__name__}"
+            )
+        super().__init__(conv, bn, relu)
+
+
+class ConvBnReLU2d(_FusedModule):
+    r"""This is a sequential container which calls the Conv 2d, Batch Norm 2d, and ReLU modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, conv, bn, relu):
+        if not (
+            type_before_parametrizations(conv) == Conv2d
+            and type_before_parametrizations(bn) == BatchNorm2d
+            and type_before_parametrizations(relu) == ReLU
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(conv).__name__}, "
+                f"{type_before_parametrizations(bn).__name__}, and "
+                f"{type_before_parametrizations(relu).__name__}"
+            )
+        super().__init__(conv, bn, relu)
+
+
+class ConvBn3d(_FusedModule):
+    r"""This is a sequential container which calls the Conv 3d and Batch Norm 3d modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, conv, bn):
+        if not (
+            type_before_parametrizations(conv) == Conv3d
+            and type_before_parametrizations(bn) == BatchNorm3d
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(conv).__name__} and "
+                f"{type_before_parametrizations(bn).__name__}"
+            )
+        super().__init__(conv, bn)
+
+
+class ConvBnReLU3d(_FusedModule):
+    r"""This is a sequential container which calls the Conv 3d, Batch Norm 3d, and ReLU modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, conv, bn, relu):
+        if not (
+            type_before_parametrizations(conv) == Conv3d
+            and type_before_parametrizations(bn) == BatchNorm3d
+            and type_before_parametrizations(relu) == ReLU
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(conv).__name__}, "
+                f"{type_before_parametrizations(bn).__name__}, and "
+                f"{type_before_parametrizations(relu).__name__}"
+            )
+        super().__init__(conv, bn, relu)
+
+
+class BNReLU2d(_FusedModule):
+    r"""This is a sequential container which calls the BatchNorm 2d and ReLU modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, batch_norm, relu):
+        if not (
+            type_before_parametrizations(batch_norm) == BatchNorm2d
+            and type_before_parametrizations(relu) == ReLU
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(batch_norm).__name__} and "
+                f"{type_before_parametrizations(relu).__name__}"
+            )
+        super().__init__(batch_norm, relu)
+
+
+class BNReLU3d(_FusedModule):
+    r"""This is a sequential container which calls the BatchNorm 3d and ReLU modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, batch_norm, relu):
+        if not (
+            type_before_parametrizations(batch_norm) == BatchNorm3d
+            and type_before_parametrizations(relu) == ReLU
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(batch_norm).__name__} and "
+                f"{type_before_parametrizations(relu).__name__}"
+            )
+        super().__init__(batch_norm, relu)
+
+
+class LinearBn1d(_FusedModule):
+    r"""This is a sequential container which calls the Linear and BatchNorm1d modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, linear, bn):
+        if not (
+            type_before_parametrizations(linear) == Linear
+            and type_before_parametrizations(bn) == BatchNorm1d
+        ):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type_before_parametrizations(linear).__name__} and "
+                f"{type_before_parametrizations(bn).__name__}"
+            )
+        super().__init__(linear, bn)
+
+
+class LinearLeakyReLU(_FusedModule):
+    r"""This is a sequential container which calls the Linear and LeakyReLU modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, linear, leaky_relu):
+        if not (type(linear) is Linear and type(leaky_relu) is torch.nn.LeakyReLU):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type(linear).__name__} and {type(leaky_relu).__name__}"
+            )
+        super().__init__(linear, leaky_relu)
+
+
+class LinearTanh(_FusedModule):
+    r"""This is a sequential container which calls the Linear and Tanh modules.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, linear, tanh):
+        if not (type(linear) is Linear and type(tanh) is torch.nn.Tanh):
+            raise AssertionError(
+                f"Incorrect types for input modules: "
+                f"{type(linear).__name__} and {type(tanh).__name__}"
+            )
+        super().__init__(linear, tanh)
+
+
+class ConvAdd2d(_FusedModule):
+    r"""This is a sequential container which calls the Conv2d modules with extra Add.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, conv, add):
+        super().__init__(conv)
+        self.add = add
+
+    def forward(self, x1, x2):  # type: ignore[override]
+        r"""Applies convolution to x1 and adds the result to x2."""
+        return self.add(self[0](x1), x2)
+
+
+class ConvAddReLU2d(_FusedModule):
+    r"""This is a sequential container which calls the Conv2d, add, Relu.
+    During quantization this will be replaced with the corresponding fused module."""
+
+    def __init__(self, conv, add, relu):
+        super().__init__(conv)
+        self.add = add
+        self.relu = relu
+
+    def forward(self, x1, x2):  # type: ignore[override]
+        r"""Applies convolution to x1, adds the result to x2, and applies ReLU."""
+        return self.relu(self.add(self[0](x1), x2))
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d79bdbfe83209f18b17cc8c7b245f322871d6c0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/__init__.py
@@ -0,0 +1 @@
+from .modules import *  # noqa: F403
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7daf5b5bb24e3e2e0722d28540d9b43fe653b13c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..18534bbc588e7480ac6529c6648c5976eadaea3a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__init__.py
@@ -0,0 +1,32 @@
+from .conv_fused import (
+    ConvBn1d,
+    ConvBn2d,
+    ConvBn3d,
+    ConvBnReLU1d,
+    ConvBnReLU2d,
+    ConvBnReLU3d,
+    ConvReLU1d,
+    ConvReLU2d,
+    ConvReLU3d,
+    freeze_bn_stats,
+    update_bn_stats,
+)
+from .linear_fused import LinearBn1d
+from .linear_relu import LinearReLU
+
+
+__all__ = [
+    "LinearReLU",
+    "LinearBn1d",
+    "ConvReLU1d",
+    "ConvReLU2d",
+    "ConvReLU3d",
+    "ConvBn1d",
+    "ConvBn2d",
+    "ConvBn3d",
+    "ConvBnReLU1d",
+    "ConvBnReLU2d",
+    "ConvBnReLU3d",
+    "update_bn_stats",
+    "freeze_bn_stats",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e2947438871eb37117adf03b342a747c53e5f9a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__pycache__/conv_fused.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__pycache__/conv_fused.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..765331d94b26fbca48a580ebb069521c4bc0c423
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__pycache__/conv_fused.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__pycache__/linear_fused.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__pycache__/linear_fused.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c438e25ed1b655dd7aa376a2d0ecd2629977c881
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__pycache__/linear_fused.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__pycache__/linear_relu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__pycache__/linear_relu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..312f75902bb2bc905a962cc13b6d9e02ac2dee9a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/__pycache__/linear_relu.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/conv_fused.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/conv_fused.py
new file mode 100644
index 0000000000000000000000000000000000000000..b96b7c5acb2e5b6cdf0c1cec3d9624b0e60b66d5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/conv_fused.py
@@ -0,0 +1,971 @@
+# mypy: allow-untyped-defs
+import math
+from typing import ClassVar
+
+import torch
+import torch.ao.nn.intrinsic as nni
+import torch.ao.nn.qat as nnqat
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.nn import init
+from torch.nn.modules.utils import _pair, _single, _triple
+from torch.nn.parameter import Parameter
+from torch.nn.utils import fuse_conv_bn_weights
+
+
+__all__ = [
+    "ConvBn1d",
+    "ConvBnReLU1d",
+    "ConvReLU1d",
+    "ConvBn2d",
+    "ConvBnReLU2d",
+    "ConvReLU2d",
+    "ConvBn3d",
+    "ConvBnReLU3d",
+    "ConvReLU3d",
+    "update_bn_stats",
+    "freeze_bn_stats",
+]
+_BN_CLASS_MAP = {
+    1: nn.BatchNorm1d,
+    2: nn.BatchNorm2d,
+    3: nn.BatchNorm3d,
+}
+
+
+class _ConvBnNd(nn.modules.conv._ConvNd, nni._FusedModule):
+    _version = 2
+    _FLOAT_MODULE: ClassVar[type[nn.modules.conv._ConvNd]]
+
+    def __init__(
+        self,
+        # ConvNd args
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride,
+        padding,
+        dilation,
+        transposed,
+        output_padding,
+        groups,
+        bias,
+        padding_mode,
+        # BatchNormNd args
+        # num_features: out_channels
+        eps=1e-05,
+        momentum=0.1,
+        # affine: True
+        # track_running_stats: True
+        # Args for this module
+        freeze_bn=False,
+        qconfig=None,
+        dim=2,
+    ):
+        nn.modules.conv._ConvNd.__init__(
+            self,
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            transposed,
+            output_padding,
+            groups,
+            False,
+            padding_mode,
+        )
+        if not qconfig:
+            raise AssertionError("qconfig must be provided for QAT module")
+        self.qconfig = qconfig
+        self.freeze_bn = freeze_bn if self.training else True
+        self.bn = _BN_CLASS_MAP[dim](out_channels, eps, momentum, True, True)
+        self.weight_fake_quant = self.qconfig.weight()
+        if bias:
+            self.bias = Parameter(torch.empty(out_channels))
+        else:
+            self.register_parameter("bias", None)
+        self.reset_bn_parameters()
+
+        # this needs to be called after reset_bn_parameters,
+        # as they modify the same state
+        if self.training:
+            if freeze_bn:
+                self.freeze_bn_stats()
+            else:
+                self.update_bn_stats()
+        else:
+            self.freeze_bn_stats()
+
+        self._enable_slow_path_for_better_numerical_stability = False
+
+    def reset_running_stats(self):
+        self.bn.reset_running_stats()
+
+    def reset_bn_parameters(self):
+        self.bn.reset_running_stats()
+        init.uniform_(self.bn.weight)
+        init.zeros_(self.bn.bias)
+        # note: below is actually for conv, not BN
+        if self.bias is not None:
+            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
+            bound = 1 / math.sqrt(fan_in)
+            init.uniform_(self.bias, -bound, bound)
+
+    def update_bn_stats(self):
+        self.freeze_bn = False
+        self.bn.training = True
+        return self
+
+    def freeze_bn_stats(self):
+        self.freeze_bn = True
+        self.bn.training = False
+        return self
+
+    def _forward(self, input):
+        if self._enable_slow_path_for_better_numerical_stability:
+            return self._forward_slow(input)
+        return self._forward_approximate(input)
+
+    def _forward_approximate(self, input):
+        """Approximated method to fuse conv and bn. It requires only one forward pass.
+        conv_orig = conv / scale_factor where scale_factor = bn.weight / running_std
+        """
+        if self.bn.running_var is None:
+            raise AssertionError("self.bn.running_var must not be None")
+        running_std = torch.sqrt(self.bn.running_var + self.bn.eps)
+        scale_factor = self.bn.weight / running_std
+        weight_shape = [1] * len(self.weight.shape)
+        weight_shape[0] = -1
+        bias_shape = [1] * len(self.weight.shape)
+        bias_shape[1] = -1
+        scaled_weight = self.weight_fake_quant(
+            self.weight * scale_factor.reshape(weight_shape)
+        )
+        # using zero bias here since the bias for original conv
+        # will be added later
+        if self.bias is not None:
+            zero_bias = torch.zeros_like(self.bias, dtype=input.dtype)
+        else:
+            zero_bias = torch.zeros(
+                self.out_channels, device=scaled_weight.device, dtype=input.dtype
+            )
+        conv = self._conv_forward(input, scaled_weight, zero_bias)
+        conv_orig = conv / scale_factor.reshape(bias_shape)
+        if self.bias is not None:
+            conv_orig = conv_orig + self.bias.reshape(bias_shape)
+        conv = self.bn(conv_orig)
+        return conv
+
+    def _forward_slow(self, input):
+        """
+        A more accurate but slow method to compute conv bn fusion, following https://arxiv.org/pdf/1806.08342.pdf
+        It requires two forward passes but handles the case bn.weight == 0
+
+        Conv: Y = WX + B_c
+        Conv without bias: Y0 = WX = Y - B_c, Y = Y0 + B_c
+
+        Batch statistics:
+          mean_Y = Y.mean()
+                 = Y0.mean() + B_c
+          var_Y = (Y - mean_Y)^2.mean()
+                = (Y0 - Y0.mean())^2.mean()
+        BN (r: bn.weight, beta: bn.bias):
+          Z = r * (Y - mean_Y) / sqrt(var_Y + eps) + beta
+            = r * (Y0 - Y0.mean()) / sqrt(var_Y + eps) + beta
+
+        Fused Conv BN training (std_Y = sqrt(var_Y + eps)):
+          Z = (r * W / std_Y) * X + r * (B_c - mean_Y) / std_Y + beta
+            = (r * W / std_Y) * X - r * Y0.mean() / std_Y + beta
+
+        Fused Conv BN inference (running_std = sqrt(running_var + eps)):
+          Z = (r * W / running_std) * X - r * (running_mean - B_c) / running_std + beta
+
+        QAT with fused conv bn:
+          Z_train = fake_quant(r * W / running_std) * X * (running_std / std_Y) - r * Y0.mean() / std_Y + beta
+                  = conv(X, fake_quant(r * W / running_std)) * (running_std / std_Y) - r * Y0.mean() / std_Y + beta
+          Z_inference = conv(X, fake_quant(r * W / running_std)) - r * (running_mean - B_c) / running_std + beta
+        """
+
+        if self.bn.running_var is None:
+            raise AssertionError("self.bn.running_var must not be None")
+        if self.bn.running_mean is None:
+            raise AssertionError("self.bn.running_mean must not be None")
+
+        # using zero bias here since the bias for original conv
+        # will be added later
+        zero_bias = torch.zeros(
+            self.out_channels, device=self.weight.device, dtype=input.dtype
+        )
+
+        weight_shape = [1] * len(self.weight.shape)
+        weight_shape[0] = -1
+        bias_shape = [1] * len(self.weight.shape)
+        bias_shape[1] = -1
+
+        if self.bn.training:
+            # needed to compute batch mean/std
+            conv_out = self._conv_forward(input, self.weight, zero_bias)
+            # update bn statistics
+            with torch.no_grad():
+                conv_out_bias = (
+                    conv_out
+                    if self.bias is None
+                    else conv_out + self.bias.reshape(bias_shape)
+                )
+                self.bn(conv_out_bias)
+
+            # fused conv + bn without bias using bn running statistics
+            running_std = torch.sqrt(self.bn.running_var + self.bn.eps)
+            scale_factor = self.bn.weight / running_std
+            scaled_weight = self.weight_fake_quant(
+                self.weight * scale_factor.reshape(weight_shape)
+            )
+            # fused conv without bias for inference: (r * W / running_std) * X
+            conv_bn = self._conv_forward(input, scaled_weight, zero_bias)
+
+            avg_dims = [0] + list(range(2, len(self.weight.shape)))
+            batch_mean = conv_out.mean(avg_dims)
+            batch_var = torch.square(conv_out - batch_mean.reshape(bias_shape)).mean(
+                avg_dims
+            )
+            batch_std = torch.sqrt(batch_var + self.bn.eps)
+
+            # scale to use batch std in training mode
+            # conv(X, r * W / std_Y) = conv(X, r * W / running_std) * (running_std / std_Y)
+            unscale_factor = running_std / batch_std
+            conv_bn *= unscale_factor.reshape(bias_shape)
+
+            fused_mean = batch_mean
+            fused_std = batch_std
+        else:
+            # fused conv + bn without bias using bn running statistics
+            running_std = torch.sqrt(self.bn.running_var + self.bn.eps)
+            scale_factor = self.bn.weight / running_std
+            scaled_weight = self.weight_fake_quant(
+                self.weight * scale_factor.reshape(weight_shape)
+            )
+            # fused conv without bias for inference: (r * W / running_std) * X
+            conv_bn = self._conv_forward(input, scaled_weight, zero_bias)
+
+            fused_mean = self.bn.running_mean - (
+                self.bias if self.bias is not None else 0
+            )
+            fused_std = running_std
+
+        # fused bias = beta - r * mean / std
+        fused_bias = self.bn.bias - self.bn.weight * fused_mean / fused_std
+        conv_bn += fused_bias.reshape(bias_shape)
+
+        # HACK to let conv bias participate in loss to avoid DDP error (parameters
+        #   were not used in producing loss)
+        if self.bias is not None:
+            conv_bn += (self.bias - self.bias).reshape(bias_shape)
+
+        return conv_bn
+
+    def forward(self, input):
+        return self._forward(input)
+
+    def train(self, mode=True):
+        """
+        Batchnorm's training behavior is using the self.training flag. Prevent
+        changing it if BN is frozen. This makes sure that calling `model.train()`
+        on a model with a frozen BN will behave properly.
+        """
+        self.training = mode
+        if not self.freeze_bn:
+            for module in self.children():
+                module.train(mode)
+        return self
+
+    # ===== Serialization version history =====
+    #
+    # Version 1/None
+    #   self
+    #   |--- weight : Tensor
+    #   |--- bias : Tensor
+    #   |--- gamma : Tensor
+    #   |--- beta : Tensor
+    #   |--- running_mean : Tensor
+    #   |--- running_var : Tensor
+    #   |--- num_batches_tracked : Tensor
+    #
+    # Version 2
+    #   self
+    #   |--- weight : Tensor
+    #   |--- bias : Tensor
+    #   |--- bn : Module
+    #        |--- weight : Tensor (moved from v1.self.gamma)
+    #        |--- bias : Tensor (moved from v1.self.beta)
+    #        |--- running_mean : Tensor (moved from v1.self.running_mean)
+    #        |--- running_var : Tensor (moved from v1.self.running_var)
+    #        |--- num_batches_tracked : Tensor (moved from v1.self.num_batches_tracked)
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        version = local_metadata.get("version", None)
+        if version is None or version == 1:
+            # BN related parameters and buffers were moved into the BN module for v2
+            v2_to_v1_names = {
+                "bn.weight": "gamma",
+                "bn.bias": "beta",
+                "bn.running_mean": "running_mean",
+                "bn.running_var": "running_var",
+                "bn.num_batches_tracked": "num_batches_tracked",
+            }
+            for v2_name, v1_name in v2_to_v1_names.items():
+                if prefix + v1_name in state_dict:
+                    state_dict[prefix + v2_name] = state_dict[prefix + v1_name]
+                    state_dict.pop(prefix + v1_name)
+                elif prefix + v2_name in state_dict:
+                    # there was a brief period where forward compatibility
+                    # for this module was broken (between
+                    # https://github.com/pytorch/pytorch/pull/38478
+                    # and https://github.com/pytorch/pytorch/pull/38820)
+                    # and modules emitted the v2 state_dict format while
+                    # specifying that version == 1. This patches the forward
+                    # compatibility issue by allowing the v2 style entries to
+                    # be used.
+                    pass
+                elif strict:
+                    missing_keys.append(prefix + v2_name)
+
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            strict,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Create a qat module from a float module or qparams_dict
+
+        Args: `mod` a float module, either produced by torch.ao.quantization utilities
+        or directly from user
+        """
+        # The ignore is because _FLOAT_MODULE is a TypeVar here where the bound
+        # has no __name__ (code is fine though)
+        if type(mod) is not cls._FLOAT_MODULE:
+            raise AssertionError(
+                "qat."
+                + cls.__name__
+                + ".from_float only works for "
+                + cls._FLOAT_MODULE.__name__
+            )
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+        if not mod.qconfig:
+            raise AssertionError("Input float module must have a valid qconfig")
+        qconfig = mod.qconfig
+        conv, bn = mod[0], mod[1]  # type: ignore[index]
+        qat_convbn = cls(
+            conv.in_channels,
+            conv.out_channels,
+            conv.kernel_size,
+            conv.stride,
+            conv.padding,
+            conv.dilation,
+            conv.groups,
+            conv.bias is not None,
+            conv.padding_mode,
+            bn.eps,
+            bn.momentum,
+            False,
+            qconfig,
+        )
+        qat_convbn.weight = conv.weight
+        qat_convbn.bias = conv.bias
+        qat_convbn.bn.weight = bn.weight
+        qat_convbn.bn.bias = bn.bias
+        qat_convbn.bn.running_mean = bn.running_mean
+        qat_convbn.bn.running_var = bn.running_var
+        # mypy error: Cannot determine type of 'num_batches_tracked'
+        qat_convbn.bn.num_batches_tracked = bn.num_batches_tracked
+        return qat_convbn
+
+    def to_float(self):
+        cls = type(self)
+        conv = cls._FLOAT_CONV_MODULE(  # type: ignore[attr-defined]
+            self.in_channels,
+            self.out_channels,
+            self.kernel_size,
+            self.stride,
+            self.padding,
+            self.dilation,
+            self.groups,
+            self.bias is not None,
+            self.padding_mode,
+        )
+        conv.weight = torch.nn.Parameter(self.weight.detach())
+        if self.bias is not None:
+            conv.bias = torch.nn.Parameter(self.bias.detach())
+
+        if cls._FLOAT_BN_MODULE:  # type: ignore[attr-defined]
+            # fuse bn into conv
+            if self.bn.running_var is None or self.bn.running_mean is None:
+                raise AssertionError(
+                    "self.bn.running_var and self.bn.running_mean must not be None"
+                )
+            conv.weight, conv.bias = fuse_conv_bn_weights(
+                conv.weight,
+                conv.bias,
+                self.bn.running_mean,
+                self.bn.running_var,
+                self.bn.eps,
+                self.bn.weight,
+                self.bn.bias,
+            )
+
+        if cls._FLOAT_RELU_MODULE:  # type: ignore[attr-defined]
+            modules = []
+            modules.append(conv)
+            relu = cls._FLOAT_RELU_MODULE()  # type: ignore[attr-defined]
+            modules.append(relu)
+            conv_relu = cls._FUSED_FLOAT_MODULE(*modules)  # type: ignore[attr-defined]
+            conv_relu.train(self.training)
+            return conv_relu
+        else:
+            conv.train(self.training)
+            return conv
+
+
+class ConvBn1d(_ConvBnNd, nn.Conv1d):
+    r"""
+    A ConvBn1d module is a module fused from Conv1d and BatchNorm1d,
+    attached with FakeQuantize modules for weight,
+    used in quantization aware training.
+
+    We combined the interface of :class:`torch.nn.Conv1d` and
+    :class:`torch.nn.BatchNorm1d`.
+
+    Similar to :class:`torch.nn.Conv1d`, with FakeQuantize modules initialized
+    to default.
+
+    Attributes:
+        freeze_bn:
+        weight_fake_quant: fake quant module for weight
+
+    """
+
+    _FLOAT_BN_MODULE: ClassVar[type[nn.BatchNorm1d]] = nn.BatchNorm1d
+    _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
+    _FLOAT_MODULE: ClassVar[type[nn.Module]] = nni.ConvBn1d  # type: ignore[assignment]
+    _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
+
+    def __init__(
+        self,
+        # Conv1d args
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=None,
+        padding_mode="zeros",
+        # BatchNorm1d args
+        # num_features: out_channels
+        eps=1e-05,
+        momentum=0.1,
+        # affine: True
+        # track_running_stats: True
+        # Args for this module
+        freeze_bn=False,
+        qconfig=None,
+    ):
+        kernel_size = _single(kernel_size)
+        stride = _single(stride)
+        padding = _single(padding)
+        dilation = _single(dilation)
+        _ConvBnNd.__init__(
+            self,
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            False,
+            _single(0),
+            groups,
+            bias,
+            padding_mode,
+            eps,
+            momentum,
+            freeze_bn,
+            qconfig,
+            dim=1,
+        )
+
+
+class ConvBnReLU1d(ConvBn1d):
+    r"""
+    A ConvBnReLU1d module is a module fused from Conv1d, BatchNorm1d and ReLU,
+    attached with FakeQuantize modules for weight,
+    used in quantization aware training.
+
+    We combined the interface of :class:`torch.nn.Conv1d` and
+    :class:`torch.nn.BatchNorm1d` and :class:`torch.nn.ReLU`.
+
+    Similar to `torch.nn.Conv1d`, with FakeQuantize modules initialized to
+    default.
+
+    Attributes:
+        weight_fake_quant: fake quant module for weight
+
+    """
+
+    # base class defines _FLOAT_MODULE as "ConvBn1d"
+    _FLOAT_MODULE: ClassVar[type[nn.Module]] = nni.ConvBnReLU1d
+    _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
+    _FLOAT_BN_MODULE: ClassVar[type[nn.BatchNorm1d]] = nn.BatchNorm1d
+    _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
+    # module class after fusing bn into conv
+    _FUSED_FLOAT_MODULE: ClassVar[type[nn.Module] | None] = nni.ConvReLU1d
+
+    def forward(self, input):
+        r"""Performs forward pass through fused Conv1d, BatchNorm1d, and ReLU."""
+        return F.relu(self._forward(input))
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Creates a QAT module from a floating point module."""
+        return super().from_float(mod, use_precomputed_fake_quant)
+
+
+class ConvReLU1d(nnqat.Conv1d, nni._FusedModule):
+    r"""A ConvReLU1d module is a fused module of Conv1d and ReLU, attached with
+    FakeQuantize modules for weight for
+    quantization aware training.
+
+    We combined the interface of :class:`~torch.nn.Conv1d` and
+    :class:`~torch.nn.BatchNorm1d`.
+
+    Attributes:
+        weight_fake_quant: fake quant module for weight
+
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nni.ConvReLU1d]] = nni.ConvReLU1d  # type: ignore[assignment]
+    _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
+    _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = None
+    _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        qconfig=None,
+    ):
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride=stride,
+            padding=padding,
+            dilation=dilation,
+            groups=groups,
+            bias=bias,
+            # pyrefly: ignore [bad-argument-type]
+            padding_mode=padding_mode,
+            qconfig=qconfig,
+        )
+        if not qconfig:
+            raise AssertionError("qconfig must be provided for QAT module")
+        self.qconfig = qconfig
+        self.weight_fake_quant = self.qconfig.weight()
+
+    def forward(self, input):
+        r"""Performs forward pass through fused Conv1d and ReLU."""
+        return F.relu(
+            self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a QAT module from a floating point module."""
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+
+class ConvBn2d(_ConvBnNd, nn.Conv2d):
+    r"""
+    A ConvBn2d module is a module fused from Conv2d and BatchNorm2d,
+    attached with FakeQuantize modules for weight,
+    used in quantization aware training.
+
+    We combined the interface of :class:`torch.nn.Conv2d` and
+    :class:`torch.nn.BatchNorm2d`.
+
+    Similar to :class:`torch.nn.Conv2d`, with FakeQuantize modules initialized
+    to default.
+
+    Attributes:
+        freeze_bn:
+        weight_fake_quant: fake quant module for weight
+
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nni.ConvBn2d]] = nni.ConvBn2d  # type: ignore[assignment]
+    _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
+    _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = nn.BatchNorm2d
+    _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
+
+    def __init__(
+        self,
+        # ConvNd args
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=None,
+        padding_mode="zeros",
+        # BatchNorm2d args
+        # num_features: out_channels
+        eps=1e-05,
+        momentum=0.1,
+        # affine: True
+        # track_running_stats: True
+        # Args for this module
+        freeze_bn=False,
+        qconfig=None,
+    ):
+        kernel_size = _pair(kernel_size)
+        stride = _pair(stride)
+        padding = _pair(padding)
+        dilation = _pair(dilation)
+        _ConvBnNd.__init__(
+            self,
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            False,
+            _pair(0),
+            groups,
+            bias,
+            padding_mode,
+            eps,
+            momentum,
+            freeze_bn,
+            qconfig,
+            dim=2,
+        )
+
+
+class ConvBnReLU2d(ConvBn2d):
+    r"""
+    A ConvBnReLU2d module is a module fused from Conv2d, BatchNorm2d and ReLU,
+    attached with FakeQuantize modules for weight,
+    used in quantization aware training.
+
+    We combined the interface of :class:`torch.nn.Conv2d` and
+    :class:`torch.nn.BatchNorm2d` and :class:`torch.nn.ReLU`.
+
+    Similar to `torch.nn.Conv2d`, with FakeQuantize modules initialized to
+    default.
+
+    Attributes:
+        weight_fake_quant: fake quant module for weight
+
+    """
+
+    # base class defines _FLOAT_MODULE as "ConvBn2d"
+    _FLOAT_MODULE: ClassVar[type[nni.ConvBnReLU2d]] = nni.ConvBnReLU2d  # type: ignore[assignment]
+    _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
+    _FLOAT_BN_MODULE: ClassVar[type[nn.BatchNorm2d]] = nn.BatchNorm2d
+    _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
+    # module class after fusing bn into conv
+    _FUSED_FLOAT_MODULE: ClassVar[type[nni.ConvReLU2d] | None] = nni.ConvReLU2d
+
+    def forward(self, input):
+        r"""Performs forward pass through fused Conv2d, BatchNorm2d, and ReLU."""
+        return F.relu(self._forward(input))
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Creates a QAT module from a floating point module."""
+        return super().from_float(mod, use_precomputed_fake_quant)
+
+
+class ConvReLU2d(nnqat.Conv2d, nni._FusedModule):
+    r"""A ConvReLU2d module is a fused module of Conv2d and ReLU, attached with
+    FakeQuantize modules for weight for
+    quantization aware training.
+
+    We combined the interface of :class:`~torch.nn.Conv2d` and
+    :class:`~torch.nn.BatchNorm2d`.
+
+    Attributes:
+        weight_fake_quant: fake quant module for weight
+
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.Module]] = nni.ConvReLU2d  # type: ignore[assignment]
+    _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
+    _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = None
+    _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        qconfig=None,
+    ):
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride=stride,
+            padding=padding,
+            dilation=dilation,
+            groups=groups,
+            bias=bias,
+            # pyrefly: ignore [bad-argument-type]
+            padding_mode=padding_mode,
+            qconfig=qconfig,
+        )
+        if not qconfig:
+            raise AssertionError("qconfig must be provided for QAT module")
+        self.qconfig = qconfig
+        self.weight_fake_quant = self.qconfig.weight()
+
+    def forward(self, input):
+        r"""Performs forward pass through fused Conv2d and ReLU."""
+        return F.relu(
+            self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a QAT module from a floating point module."""
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+
+class ConvBn3d(_ConvBnNd, nn.Conv3d):
+    r"""
+    A ConvBn3d module is a module fused from Conv3d and BatchNorm3d,
+    attached with FakeQuantize modules for weight,
+    used in quantization aware training.
+
+    We combined the interface of :class:`torch.nn.Conv3d` and
+    :class:`torch.nn.BatchNorm3d`.
+
+    Similar to :class:`torch.nn.Conv3d`, with FakeQuantize modules initialized
+    to default.
+
+    Attributes:
+        freeze_bn:
+        weight_fake_quant: fake quant module for weight
+
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nni.ConvBn3d]] = nni.ConvBn3d  # type: ignore[assignment]
+    _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
+    _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = nn.BatchNorm3d
+    _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
+
+    def __init__(
+        self,
+        # ConvNd args
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=None,
+        padding_mode="zeros",
+        # BatchNorm3d args
+        # num_features: out_channels
+        eps=1e-05,
+        momentum=0.1,
+        # affine: True
+        # track_running_stats: True
+        # Args for this module
+        freeze_bn=False,
+        qconfig=None,
+    ):
+        kernel_size = _triple(kernel_size)
+        stride = _triple(stride)
+        padding = _triple(padding)
+        dilation = _triple(dilation)
+        _ConvBnNd.__init__(
+            self,
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            False,
+            _triple(0),
+            groups,
+            bias,
+            padding_mode,
+            eps,
+            momentum,
+            freeze_bn,
+            qconfig,
+            dim=3,
+        )
+
+
+class ConvBnReLU3d(ConvBn3d):
+    r"""
+    A ConvBnReLU3d module is a module fused from Conv3d, BatchNorm3d and ReLU,
+    attached with FakeQuantize modules for weight,
+    used in quantization aware training.
+
+    We combined the interface of :class:`torch.nn.Conv3d` and
+    :class:`torch.nn.BatchNorm3d` and :class:`torch.nn.ReLU`.
+
+    Similar to `torch.nn.Conv3d`, with FakeQuantize modules initialized to
+    default.
+
+    Attributes:
+        weight_fake_quant: fake quant module for weight
+
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nni.ConvBnReLU3d]] = nni.ConvBnReLU3d  # type: ignore[assignment]
+    _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
+    _FLOAT_BN_MODULE: ClassVar[type[nn.BatchNorm3d]] = nn.BatchNorm3d
+    _FLOAT_RELU_MODULE: ClassVar[type[nn.ReLU] | None] = nn.ReLU
+    # module class after fusing bn into conv
+    _FUSED_FLOAT_MODULE: ClassVar[type[nni.ConvReLU3d] | None] = nni.ConvReLU3d
+
+    def forward(self, input):
+        r"""Performs forward pass through fused Conv3d, BatchNorm3d, and ReLU."""
+        return F.relu(ConvBn3d._forward(self, input))
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Creates a QAT module from a floating point module."""
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+
+class ConvReLU3d(nnqat.Conv3d, nni._FusedModule):
+    r"""A ConvReLU3d module is a fused module of Conv3d and ReLU, attached with
+    FakeQuantize modules for weight for
+    quantization aware training.
+
+    We combined the interface of :class:`~torch.nn.Conv3d` and
+    :class:`~torch.nn.BatchNorm3d`.
+
+    Attributes:
+        weight_fake_quant: fake quant module for weight
+
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nni.ConvReLU3d]] = nni.ConvReLU3d  # type: ignore[assignment]
+    _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
+    _FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = None
+    _FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        qconfig=None,
+    ):
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride=stride,
+            padding=padding,
+            dilation=dilation,
+            groups=groups,
+            bias=bias,
+            # pyrefly: ignore [bad-argument-type]
+            padding_mode=padding_mode,
+            qconfig=qconfig,
+        )
+        if not qconfig:
+            raise AssertionError("qconfig must be provided for QAT module")
+        self.qconfig = qconfig
+        self.weight_fake_quant = self.qconfig.weight()
+
+    def forward(self, input):
+        r"""Performs forward pass through fused Conv3d and ReLU."""
+        return F.relu(
+            self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a QAT module from a floating point module."""
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+
+def update_bn_stats(mod):
+    if type(mod) in {
+        ConvBnReLU1d,
+        ConvBnReLU2d,
+        ConvBnReLU3d,
+        ConvBn1d,
+        ConvBn2d,
+        ConvBn3d,
+    }:
+        mod.update_bn_stats()
+
+
+def freeze_bn_stats(mod):
+    if type(mod) in {
+        ConvBnReLU1d,
+        ConvBnReLU2d,
+        ConvBnReLU3d,
+        ConvBn1d,
+        ConvBn2d,
+        ConvBn3d,
+    }:
+        mod.freeze_bn_stats()
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_fused.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_fused.py
new file mode 100644
index 0000000000000000000000000000000000000000..7364f5ee20908cf9b57756974113755b888be9c5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_fused.py
@@ -0,0 +1,199 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.ao.nn.intrinsic as nni
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.nn import init
+from torch.nn.parameter import Parameter
+from torch.nn.utils.fusion import fuse_linear_bn_weights
+
+
+__all__ = [
+    "LinearBn1d",
+]
+
+
+class LinearBn1d(nn.modules.linear.Linear, nni._FusedModule):
+    r"""
+    A LinearBn1d module is a module fused from Linear and BatchNorm1d, attached
+    with FakeQuantize modules for weight, used in quantization aware training.
+
+    We combined the interface of :class:`torch.nn.Linear` and
+    :class:torch.nn.BatchNorm1d`.
+
+    Similar to :class:`torch.nn.Linear`, with FakeQuantize modules initialized
+    to default.
+
+    Attributes:
+        freeze_bn:
+        weight_fake_quant: fake quant module for weight
+
+    """
+
+    def __init__(
+        self,
+        # Linear args
+        in_features,
+        out_features,
+        bias=True,
+        # BatchNorm1d args
+        # num_features: out_features
+        eps=1e-05,
+        momentum=0.1,
+        # affine: True
+        # track_running_stats: True
+        # Args for this module
+        freeze_bn=False,
+        qconfig=None,
+    ):
+        nn.modules.linear.Linear.__init__(self, in_features, out_features, bias)
+        if not qconfig:
+            raise AssertionError("qconfig must be provided for QAT module")
+        self.qconfig = qconfig
+        self.freeze_bn = freeze_bn if self.training else True
+        self.bn = nn.BatchNorm1d(out_features, eps, momentum, True, True)
+        self.weight_fake_quant = self.qconfig.weight()
+        if bias:
+            self.bias = Parameter(torch.empty(out_features))
+        else:
+            self.register_parameter("bias", None)
+        self.reset_bn_parameters()
+
+        # this needs to be called after reset_bn_parameters,
+        # as they modify the same state
+        if self.training:
+            if freeze_bn:
+                self.freeze_bn_stats()
+            else:
+                self.update_bn_stats()
+        else:
+            self.freeze_bn_stats()
+
+    def reset_running_stats(self):
+        self.bn.reset_running_stats()
+
+    def reset_bn_parameters(self):
+        self.bn.reset_running_stats()
+        init.uniform_(self.bn.weight)
+        init.zeros_(self.bn.bias)
+
+    def update_bn_stats(self):
+        self.freeze_bn = False
+        self.bn.training = True
+        return self
+
+    def freeze_bn_stats(self):
+        self.freeze_bn = True
+        self.bn.training = False
+        return self
+
+    def forward(self, input):
+        if self.bn.running_var is None:
+            raise AssertionError("self.bn.running_var must not be None")
+
+        # Scale the linear weights by BN's running statistics to reduce
+        # weight jitter, see https://arxiv.org/pdf/1806.08342.pdf, page 18
+        # for motivation.
+        #
+        # Instead of
+        #
+        #   x1 = F.linear(x0, fq(w), b)
+        #   x2 = self.bn(x1)
+        #
+        # We have
+        #
+        #   # scale the weight by previous batch's running statistics
+        #   scale_factor = bn.w / bn.running_std_from_prev_batch
+        #   # do the linear transformation without bias
+        #   x1_scaled = F.linear(x0, fq(w * scale_factor), 0)
+        #   # reverse the scaling and add original bias
+        #   x1_orig = x1_scaled / scale_factor + b
+        #   x2 = self.bn(x1_orig)
+
+        running_std = torch.sqrt(self.bn.running_var + self.bn.eps)
+        scale_factor = self.bn.weight / running_std
+        weight_shape = [1] * len(self.weight.shape)
+        weight_shape[0] = -1
+        bias_shape = [1] * len(self.weight.shape)
+        bias_shape[1] = -1
+        scaled_weight = self.weight_fake_quant(
+            self.weight * scale_factor.reshape(weight_shape)
+        )
+        if self.bias is not None:
+            zero_bias = torch.zeros_like(self.bias)
+        else:
+            zero_bias = torch.zeros(self.out_features, device=scaled_weight.device)
+        linear_out = F.linear(input, scaled_weight, zero_bias)
+        linear_out_orig = linear_out / scale_factor.reshape(bias_shape)
+        if self.bias is not None:
+            linear_out_orig = linear_out_orig + self.bias.reshape(bias_shape)
+        bn_out = self.bn(linear_out_orig)
+        return bn_out
+
+    def train(self, mode=True):
+        """
+        Batchnorm's training behavior is using the self.training flag. Prevent
+        changing it if BN is frozen. This makes sure that calling `model.train()`
+        on a model with a frozen BN will behave properly.
+        """
+        self.training = mode
+        if not self.freeze_bn:
+            for module in self.children():
+                module.train(mode)
+        return self
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Create a qat module from a float module or qparams_dict
+
+        Args:
+            mod: A float module, either produced by torch.ao.quantization
+                utilities or directly from the user.
+        """
+        if type(mod) is not nni.LinearBn1d:
+            raise AssertionError(
+                "qat."
+                + cls.__name__
+                + ".from_float only works for "
+                + nni.LinearBn1d.__name__
+            )
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+        if not mod.qconfig:
+            raise AssertionError("Input float module must have a valid config")
+        qconfig = mod.qconfig
+        linear, bn = mod[0], mod[1]
+        qat_linearbn = cls(
+            linear.in_features,
+            linear.out_features,
+            linear.bias is not None,
+            bn.eps,
+            bn.momentum,
+            False,
+            qconfig,
+        )
+        qat_linearbn.weight = linear.weight  # type: ignore[assignment]
+        qat_linearbn.bias = linear.bias  # type: ignore[assignment]
+        qat_linearbn.bn.weight = bn.weight  # type: ignore[assignment]
+        qat_linearbn.bn.bias = bn.bias  # type: ignore[assignment]
+        qat_linearbn.bn.running_mean = bn.running_mean  # type: ignore[assignment]
+        qat_linearbn.bn.running_var = bn.running_var  # type: ignore[assignment]
+        qat_linearbn.bn.num_batches_tracked = bn.num_batches_tracked  # type: ignore[assignment]
+        return qat_linearbn
+
+    def to_float(self):
+        linear = torch.nn.Linear(self.in_features, self.out_features)
+        if self.bn.running_var is None or self.bn.running_mean is None:
+            raise AssertionError(
+                "self.bn.running_var and self.bn.running_mean must not be None"
+            )
+        linear.weight, linear.bias = fuse_linear_bn_weights(
+            self.weight,
+            self.bias,
+            self.bn.running_mean,
+            self.bn.running_var,
+            self.bn.eps,
+            self.bn.weight,
+            self.bn.bias,
+        )
+        return linear
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_relu.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_relu.py
new file mode 100644
index 0000000000000000000000000000000000000000..183286ebb8dad25e49cd2fcd7c2dba2436003823
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/qat/modules/linear_relu.py
@@ -0,0 +1,74 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import torch
+import torch.ao.nn.intrinsic as nni
+import torch.ao.nn.qat as nnqat
+import torch.nn.functional as F
+from torch.ao.nn.intrinsic.modules.fused import _FusedModule
+
+
+if TYPE_CHECKING:
+    from torch.ao.quantization.qconfig import QConfigAny
+
+
+__all__ = ["LinearReLU"]
+
+
+class LinearReLU(nnqat.Linear, _FusedModule):
+    r"""
+    A LinearReLU module fused from Linear and ReLU modules, attached with
+    FakeQuantize modules for weight, used in
+    quantization aware training.
+
+    We adopt the same interface as :class:`torch.nn.Linear`.
+
+    Similar to `torch.ao.nn.intrinsic.LinearReLU`, with FakeQuantize modules initialized to
+    default.
+
+    Attributes:
+        weight: fake quant module for weight
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> m = nn.qat.LinearReLU(20, 30)
+        >>> input = torch.randn(128, 20)
+        >>> output = m(input)
+        >>> print(output.size())
+        torch.Size([128, 30])
+    """
+
+    # pyrefly: ignore [bad-override]
+    _FLOAT_MODULE = nni.LinearReLU
+
+    def __init__(
+        self,
+        in_features: int,
+        out_features: int,
+        bias: bool = True,
+        qconfig: QConfigAny = None,
+    ) -> None:
+        super().__init__(in_features, out_features, bias, qconfig)
+
+    def forward(self, input: torch.Tensor) -> torch.Tensor:
+        return F.relu(F.linear(input, self.weight_fake_quant(self.weight), self.bias))
+
+    @classmethod
+    def from_float(
+        cls,
+        mod: torch.nn.Module,
+        use_precomputed_fake_quant: bool = False,
+    ) -> LinearReLU:
+        return super().from_float(mod, use_precomputed_fake_quant)  # type: ignore[no-untyped-call,no-any-return]
+
+    def to_float(self) -> nni.LinearReLU:
+        linear = torch.nn.Linear(
+            self.in_features, self.out_features, self.bias is not None
+        )
+        linear.weight = torch.nn.Parameter(self.weight.detach())
+        if self.bias is not None:
+            linear.bias = torch.nn.Parameter(self.bias.detach())
+        relu = torch.nn.ReLU()
+        return torch.ao.nn.intrinsic.LinearReLU(linear, relu)  # type: ignore[no-untyped-call]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6af3b4aeee893966323cc4e73a27ff41814fc251
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/__init__.py
@@ -0,0 +1,15 @@
+from .modules import *  # noqa: F403
+
+
+__all__ = [
+    "BNReLU2d",
+    "BNReLU3d",
+    "ConvReLU1d",
+    "ConvReLU2d",
+    "ConvReLU3d",
+    "LinearReLU",
+    "LinearLeakyReLU",
+    "LinearTanh",
+    "ConvAdd2d",
+    "ConvAddReLU2d",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e4976a61612dc7d6cdd691b15fdc292ef196fbbd
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d79bdbfe83209f18b17cc8c7b245f322871d6c0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__init__.py
@@ -0,0 +1 @@
+from .modules import *  # noqa: F403
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f84ec230b504d73758dfbb5061c38ef035f6ec7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7a6c3c57c7828861b574e76b134aee2c23f0aad
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__init__.py
@@ -0,0 +1,6 @@
+from .linear_relu import LinearReLU
+
+
+__all__ = [
+    "LinearReLU",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..105c7dcc4a47d33a8872890ceff5d1cf9b007f8e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__pycache__/linear_relu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__pycache__/linear_relu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c23e8f20c8f81347a2b7ae43dd18cff4cd55e34
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__pycache__/linear_relu.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/linear_relu.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/linear_relu.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e7596af582e995c42ac5ab26e6b33c1b3ba08f3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/linear_relu.py
@@ -0,0 +1,72 @@
+from typing import Any
+from typing_extensions import Self
+
+import torch
+import torch.ao.nn.intrinsic as nni
+import torch.ao.nn.quantized.dynamic as nnqd
+
+
+__all__ = ["LinearReLU"]
+
+
+class LinearReLU(nnqd.Linear):
+    r"""
+    A LinearReLU module fused from Linear and ReLU modules that can be used
+    for dynamic quantization.
+    Supports both, FP16 and INT8 quantization.
+
+    We adopt the same interface as :class:`torch.ao.nn.quantized.dynamic.Linear`.
+
+    Attributes:
+        Same as torch.ao.nn.quantized.dynamic.Linear
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> m = nn.intrinsic.quantized.dynamic.LinearReLU(20, 30)
+        >>> input = torch.randn(128, 20)
+        >>> output = m(input)
+        >>> print(output.size())
+        torch.Size([128, 30])
+    """
+
+    # pyrefly: ignore [bad-override]
+    _FLOAT_MODULE = nni.LinearReLU
+
+    def __init__(
+        self,
+        in_features: int,
+        out_features: int,
+        bias: bool = True,
+        dtype: torch.dtype = torch.qint8,
+    ) -> None:
+        super().__init__(in_features, out_features, bias, dtype)
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        if self._packed_params.dtype == torch.qint8:
+            # TODO check if we should set reduce_range = True by default here
+            Y = torch.ops.quantized.linear_relu_dynamic(
+                x, self._packed_params._packed_params, reduce_range=True
+            )
+        elif self._packed_params.dtype == torch.float16:
+            Y = torch.ops.quantized.linear_relu_dynamic_fp16(
+                x, self._packed_params._packed_params
+            )
+        else:
+            raise RuntimeError("Unsupported dtype on dynamic quantized linear relu!")
+        return Y.to(x.dtype)
+
+    def _get_name(self) -> str:
+        return "DynamicQuantizedLinearReLU"
+
+    @classmethod
+    def from_float(
+        cls, mod: torch.nn.Module, use_precomputed_fake_quant: bool = False
+    ) -> Self:
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+    @classmethod
+    def from_reference(cls, ref_qlinear_relu: Any) -> Self:  # type: ignore[override]
+        return super().from_reference(ref_qlinear_relu[0])
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7fa4dcec2597e18c002489405894ea7251d5156
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__init__.py
@@ -0,0 +1,18 @@
+from .bn_relu import BNReLU2d, BNReLU3d
+from .conv_add import ConvAdd2d, ConvAddReLU2d
+from .conv_relu import ConvReLU1d, ConvReLU2d, ConvReLU3d
+from .linear_relu import LinearLeakyReLU, LinearReLU, LinearTanh
+
+
+__all__ = [
+    "LinearReLU",
+    "ConvReLU1d",
+    "ConvReLU2d",
+    "ConvReLU3d",
+    "BNReLU2d",
+    "BNReLU3d",
+    "LinearLeakyReLU",
+    "LinearTanh",
+    "ConvAdd2d",
+    "ConvAddReLU2d",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69b4d9f50572f93eef9798265e3a91bf3ad962a6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/bn_relu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/bn_relu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd1b15036f257fa199f3e9f762f872b2852ca63d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/bn_relu.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/conv_add.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/conv_add.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..55f95423b512838fd45848a3e8a4df2d9f41ad9a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/conv_add.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/conv_relu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/conv_relu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0107a6ce1e6bccbc3b34f4d87b860fd65be5a110
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/conv_relu.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/linear_relu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/linear_relu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7368357c3ceb7ea1415235dfc538d47efd94ea4f
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/linear_relu.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/bn_relu.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/bn_relu.py
new file mode 100644
index 0000000000000000000000000000000000000000..f05618c0949e1164f05cbd1edbfb8eb6440063e9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/bn_relu.py
@@ -0,0 +1,113 @@
+# mypy: allow-untyped-defs
+
+import torch
+import torch.ao.nn.intrinsic
+import torch.ao.nn.intrinsic.qat
+import torch.ao.nn.quantized as nnq
+
+
+__all__ = ["BNReLU2d", "BNReLU3d"]
+
+
+class BNReLU2d(nnq.BatchNorm2d):
+    r"""
+    A BNReLU2d module is a fused module of BatchNorm2d and ReLU
+
+    We adopt the same interface as :class:`torch.ao.nn.quantized.BatchNorm2d`.
+
+    Attributes:
+        Same as torch.ao.nn.quantized.BatchNorm2d
+
+    """
+
+    _FLOAT_MODULE = torch.ao.nn.intrinsic.BNReLU2d
+
+    def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
+        super().__init__(
+            num_features, eps=eps, momentum=momentum, device=device, dtype=dtype
+        )
+
+    def forward(self, input):
+        r"""Applies fused BatchNorm2d and ReLU."""
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 4:
+            raise ValueError("Input shape must be `(N, C, H, W)`!")
+        return torch.ops.quantized.batch_norm2d_relu(
+            input,
+            self.weight,
+            self.bias,
+            self.running_mean,
+            self.running_var,
+            self.eps,
+            self.scale,
+            self.zero_point,
+        )
+
+    def _get_name(self):
+        return "QuantizedBNReLU2d"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a quantized module from a float module."""
+        # TODO: Add qat support for BNReLU2d
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+    @classmethod
+    def from_reference(cls, bn_relu, output_scale, output_zero_point):
+        r"""Creates a quantized module from a reference module."""
+        return super().from_reference(bn_relu[0], output_scale, output_zero_point)
+
+
+class BNReLU3d(nnq.BatchNorm3d):
+    r"""
+    A BNReLU3d module is a fused module of BatchNorm3d and ReLU
+
+    We adopt the same interface as :class:`torch.ao.nn.quantized.BatchNorm3d`.
+
+    Attributes:
+        Same as torch.ao.nn.quantized.BatchNorm3d
+
+    """
+
+    _FLOAT_MODULE = torch.ao.nn.intrinsic.BNReLU3d
+
+    def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
+        super().__init__(
+            num_features, eps=eps, momentum=momentum, device=device, dtype=dtype
+        )
+
+    def forward(self, input):
+        r"""Applies fused BatchNorm3d and ReLU."""
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 5:
+            raise ValueError("Input shape must be `(N, C, D, H, W)`!")
+        return torch.ops.quantized.batch_norm3d_relu(
+            input,
+            self.weight,
+            self.bias,
+            self.running_mean,
+            self.running_var,
+            self.eps,
+            self.scale,
+            self.zero_point,
+        )
+
+    def _get_name(self):
+        return "QuantizedBNReLU3d"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a quantized module from a float module."""
+        # TODO: Add qat support for BNReLU3d
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+    @classmethod
+    def from_reference(cls, bn_relu, output_scale, output_zero_point):
+        r"""Creates a quantized module from a reference module."""
+        return super().from_reference(bn_relu[0], output_scale, output_zero_point)
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_add.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_add.py
new file mode 100644
index 0000000000000000000000000000000000000000..82d5673e7173c56b5b56d2bd48a0b154bbfdfe9e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_add.py
@@ -0,0 +1,153 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.ao.nn.intrinsic
+import torch.ao.nn.intrinsic.qat
+import torch.ao.nn.quantized as nnq
+import torch.nn.functional as F
+
+
+_reverse_repeat_padding = nnq.modules.conv._reverse_repeat_padding
+
+
+class ConvAdd2d(nnq.Conv2d):
+    r"""
+    A ConvAdd2d module is a fused module of Conv2d and Add
+
+    We adopt the same interface as :class:`torch.ao.nn.quantized.Conv2d`.
+
+    Attributes:
+        Same as torch.ao.nn.quantized.Conv2d
+
+    """
+
+    _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvAdd2d  # type: ignore[assignment]
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride=stride,
+            padding=padding,
+            dilation=dilation,
+            groups=groups,
+            bias=bias,
+            padding_mode=padding_mode,
+            device=device,
+            dtype=dtype,
+        )
+
+    def forward(self, input, extra_input):  # type: ignore[override]
+        r"""Applies fused quantized Conv2d and addition."""
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 4:
+            raise ValueError("Input shape must be `(N, C, H, W)`!")
+        if self.padding_mode != "zeros":
+            _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
+            input = F.pad(
+                input, _reversed_padding_repeated_twice, mode=self.padding_mode
+            )
+        return torch.ops.quantized.conv2d_add(
+            input, extra_input, self._packed_params, self.scale, self.zero_point
+        )
+
+    def _get_name(self):
+        return "QuantizedConvAdd2d"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a quantized module from a float module."""
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+    @classmethod
+    def from_reference(cls, ref_qconv, output_scale, output_zero_point):
+        r"""Creates a quantized module from a reference module."""
+        return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
+
+
+class ConvAddReLU2d(nnq.Conv2d):
+    r"""
+    A ConvAddReLU2d module is a fused module of Conv2d, Add and Relu
+
+    We adopt the same interface as :class:`torch.ao.nn.quantized.Conv2d`.
+
+    Attributes:
+        Same as torch.ao.nn.quantized.Conv2d
+
+    """
+
+    _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvAddReLU2d  # type: ignore[assignment]
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride=stride,
+            padding=padding,
+            dilation=dilation,
+            groups=groups,
+            bias=bias,
+            padding_mode=padding_mode,
+            device=device,
+            dtype=dtype,
+        )
+
+    def forward(self, input, extra_input):  # type: ignore[override]
+        r"""Applies fused quantized Conv2d, addition, and ReLU."""
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 4:
+            raise ValueError("Input shape must be `(N, C, H, W)`!")
+        if self.padding_mode != "zeros":
+            _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
+            input = F.pad(
+                input, _reversed_padding_repeated_twice, mode=self.padding_mode
+            )
+        return torch.ops.quantized.conv2d_add_relu(
+            input, extra_input, self._packed_params, self.scale, self.zero_point
+        )
+
+    def _get_name(self):
+        return "QuantizedConvAddReLU2d"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a quantized module from a float module."""
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+    @classmethod
+    def from_reference(cls, ref_qconv, output_scale, output_zero_point):
+        r"""Creates a quantized module from a reference module."""
+        return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_relu.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_relu.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4c6fe7961fda4f3bae513bd3ab274f4892150c2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_relu.py
@@ -0,0 +1,289 @@
+# mypy: allow-untyped-defs
+
+import torch
+import torch.ao.nn.intrinsic
+import torch.ao.nn.intrinsic.qat
+import torch.ao.nn.quantized as nnq
+import torch.nn.functional as F
+from torch.nn.utils import fuse_conv_bn_weights
+
+
+__all__ = [
+    "ConvReLU1d",
+    "ConvReLU2d",
+    "ConvReLU3d",
+]
+
+_reverse_repeat_padding = nnq.modules.conv._reverse_repeat_padding
+
+
+# TODO: factor out the common parts to ConvNd
+class ConvReLU1d(nnq.Conv1d):
+    r"""
+    A ConvReLU1d module is a fused module of Conv1d and ReLU
+
+    We adopt the same interface as :class:`torch.ao.nn.quantized.Conv1d`.
+
+    Attributes:
+        Same as torch.ao.nn.quantized.Conv1d
+
+    """
+
+    _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU1d  # type: ignore[assignment]
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride=stride,
+            padding=padding,
+            dilation=dilation,
+            groups=groups,
+            bias=bias,
+            # pyrefly: ignore [bad-argument-type]
+            padding_mode=padding_mode,
+            device=device,
+            dtype=dtype,
+        )
+
+    def forward(self, input):
+        r"""Applies fused quantized Conv1d and ReLU."""
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 3:
+            raise ValueError("Input shape must be `(N, C, L)`!")
+        if self.padding_mode != "zeros":
+            # Padding in Conv1d is stored as (p, p), need to get (p,)
+            _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding[:1])
+            input = F.pad(
+                input, _reversed_padding_repeated_twice, mode=self.padding_mode
+            )
+        return torch.ops.quantized.conv1d_relu(
+            input, self._packed_params, self.scale, self.zero_point
+        )
+
+    def _get_name(self):
+        return "QuantizedConvReLU1d"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a quantized module from a float module."""
+        if type(mod) is torch.ao.nn.intrinsic.qat.ConvBnReLU1d:
+            if mod.bn.running_var is None or mod.bn.running_mean is None:
+                raise AssertionError(
+                    "mod.bn.running_var and mod.bn.running_mean must not be None"
+                )
+            mod.weight, mod.bias = fuse_conv_bn_weights(
+                mod.weight,
+                mod.bias,
+                mod.bn.running_mean,
+                mod.bn.running_var,
+                mod.bn.eps,
+                mod.bn.weight,
+                mod.bn.bias,
+            )
+        return super().from_float(mod, use_precomputed_fake_quant)
+
+    @classmethod
+    def from_reference(cls, ref_qconv, output_scale, output_zero_point):
+        r"""Creates a quantized module from a reference module."""
+        if type(ref_qconv) is torch.ao.nn.intrinsic.ConvBnReLU1d:
+            raise AssertionError(
+                "BatchNorm1d should be fused into Conv1d before converting to reference module"
+            )
+        return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
+
+
+class ConvReLU2d(nnq.Conv2d):
+    r"""
+    A ConvReLU2d module is a fused module of Conv2d and ReLU
+
+    We adopt the same interface as :class:`torch.ao.nn.quantized.Conv2d`.
+
+    Attributes:
+        Same as torch.ao.nn.quantized.Conv2d
+
+    """
+
+    _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU2d  # type: ignore[assignment]
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride=stride,
+            padding=padding,
+            dilation=dilation,
+            groups=groups,
+            bias=bias,
+            padding_mode=padding_mode,
+            device=device,
+            dtype=dtype,
+        )
+
+    def forward(self, input):
+        r"""Applies fused quantized Conv2d and ReLU."""
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 4:
+            raise ValueError("Input shape must be `(N, C, H, W)`!")
+        if self.padding_mode != "zeros":
+            _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
+            input = F.pad(
+                input, _reversed_padding_repeated_twice, mode=self.padding_mode
+            )
+        return torch.ops.quantized.conv2d_relu(
+            input, self._packed_params, self.scale, self.zero_point
+        )
+
+    def _get_name(self):
+        return "QuantizedConvReLU2d"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a quantized module from a float module."""
+        if type(mod) is torch.ao.nn.intrinsic.qat.ConvBnReLU2d:
+            if mod.bn.running_var is None or mod.bn.running_mean is None:
+                raise AssertionError(
+                    "mod.bn.running_var and mod.bn.running_mean must not be None"
+                )
+            mod.weight, mod.bias = fuse_conv_bn_weights(
+                mod.weight,
+                mod.bias,
+                mod.bn.running_mean,
+                mod.bn.running_var,
+                mod.bn.eps,
+                mod.bn.weight,
+                mod.bn.bias,
+            )
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+    @classmethod
+    def from_reference(cls, ref_qconv, output_scale, output_zero_point):
+        r"""Creates a quantized module from a reference module."""
+        if type(ref_qconv) is torch.ao.nn.intrinsic.ConvBnReLU2d:
+            raise AssertionError(
+                "BatchNorm2d should be fused into Conv2d before converting to reference module"
+            )
+        return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
+
+
+class ConvReLU3d(nnq.Conv3d):
+    r"""
+    A ConvReLU3d module is a fused module of Conv3d and ReLU
+
+    We adopt the same interface as :class:`torch.ao.nn.quantized.Conv3d`.
+
+    Attributes: Same as torch.ao.nn.quantized.Conv3d
+
+    """
+
+    _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU3d  # type: ignore[assignment]
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        if padding_mode == "reflect":
+            raise AssertionError("Conv3d does not support reflection padding")
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride=stride,
+            padding=padding,
+            dilation=dilation,
+            groups=groups,
+            bias=bias,
+            padding_mode=padding_mode,
+            device=device,
+            dtype=dtype,
+        )
+
+    def forward(self, input):
+        r"""Applies fused quantized Conv3d and ReLU."""
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 5:
+            raise ValueError("Input shape must be `(N, C, D, H, W)`!")
+        if self.padding_mode != "zeros":
+            _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
+            input = F.pad(
+                input, _reversed_padding_repeated_twice, mode=self.padding_mode
+            )
+        return torch.ops.quantized.conv3d_relu(
+            input, self._packed_params, self.scale, self.zero_point
+        )
+
+    def _get_name(self):
+        return "QuantizedConvReLU3d"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a quantized module from a float module."""
+        if type(mod) is torch.ao.nn.intrinsic.qat.ConvBnReLU3d:
+            if mod.bn.running_var is None or mod.bn.running_mean is None:
+                raise AssertionError(
+                    "mod.bn.running_var and mod.bn.running_mean must not be None"
+                )
+            mod.weight, mod.bias = fuse_conv_bn_weights(
+                mod.weight,
+                mod.bias,
+                mod.bn.running_mean,
+                mod.bn.running_var,
+                mod.bn.eps,
+                mod.bn.weight,
+                mod.bn.bias,
+            )
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+    @classmethod
+    def from_reference(cls, ref_qconv, output_scale, output_zero_point):
+        r"""Creates a quantized module from a reference module."""
+        if type(ref_qconv) is torch.ao.nn.intrinsic.ConvBnReLU3d:
+            raise AssertionError(
+                "BatchNorm3d should be fused into Conv3d before converting to reference module"
+            )
+        return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/linear_relu.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/linear_relu.py
new file mode 100644
index 0000000000000000000000000000000000000000..d190fd2ce63cf2e634f024797cf8095442f8bb94
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/intrinsic/quantized/modules/linear_relu.py
@@ -0,0 +1,198 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.ao.nn.intrinsic as nni
+import torch.ao.nn.quantized as nnq
+from torch.ao.nn.quantized.modules.utils import _quantize_weight
+
+
+__all__ = [
+    "LinearReLU",
+    "LinearLeakyReLU",
+    "LinearTanh",
+]
+
+
+class LinearReLU(nnq.Linear):
+    r"""
+    A LinearReLU module fused from Linear and ReLU modules
+
+    We adopt the same interface as :class:`torch.ao.nn.quantized.Linear`.
+
+    Attributes:
+        Same as torch.ao.nn.quantized.Linear
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> m = nn.intrinsic.LinearReLU(20, 30)
+        >>> input = torch.randn(128, 20)
+        >>> output = m(input)
+        >>> print(output.size())
+        torch.Size([128, 30])
+    """
+
+    _FLOAT_MODULE = nni.LinearReLU  # type: ignore[assignment]
+
+    def __init__(self, in_features, out_features, bias=True, dtype=torch.qint8):
+        super().__init__(in_features, out_features, bias, dtype)
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        return torch.ops.quantized.linear_relu(
+            x, self._packed_params._packed_params, self.scale, self.zero_point
+        )
+
+    def _get_name(self):
+        return "QuantizedLinearReLU"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        return super().from_float(mod, use_precomputed_fake_quant)
+
+    @classmethod
+    def from_reference(cls, ref_linear_relu, output_scale, output_zero_point):
+        return super().from_reference(
+            ref_linear_relu[0], output_scale, output_zero_point
+        )
+
+
+class LinearLeakyReLU(nnq.Linear):
+    r"""
+    For onednn backend only
+    A LinearLeakyReLU module fused from Linear and LeakyReLU modules
+    We adopt the same interface as :class:`torch.ao.nn.quantized.Linear`.
+    Attributes:
+        Same as torch.ao.nn.quantized.Linear
+        + negative_slope
+    Examples::
+        >>> # xdoctest: +SKIP
+        >>> m = nn.intrinsic.LinearLeakyReLU(20, 30, 0.01)
+        >>> input = torch.randn(128, 20)
+        >>> output = m(input)
+        >>> print(output.size())
+        torch.Size([128, 30])
+    """
+
+    _FLOAT_MODULE = nni.LinearLeakyReLU  # type: ignore[assignment]
+
+    def __init__(
+        self, in_features, out_features, negative_slope, bias=True, dtype=torch.qint8
+    ):
+        super().__init__(in_features, out_features, bias, dtype)
+        self.negative_slope = negative_slope
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        return torch.ops.quantized.linear_leaky_relu(
+            x,
+            self._packed_params._packed_params,
+            self.scale,
+            self.zero_point,
+            self.negative_slope,
+        )
+
+    def _get_name(self):
+        return "QuantizedLinearLeakyReLU"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        if type(mod) is not nni.LinearLeakyReLU:
+            raise AssertionError("Input float module should be LinearLeakyReLU")
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+        activation_post_process = mod.activation_post_process
+        leaky_relu = mod[1]
+        mod = mod[0]
+        weight_post_process = mod.qconfig.weight()  # type: ignore[union-attr, operator]
+        weight_post_process(mod.weight)
+        dtype = weight_post_process.dtype
+        act_scale, act_zp = activation_post_process.calculate_qparams()  # type: ignore[union-attr,operator]
+        if dtype != torch.qint8:
+            raise AssertionError(
+                f"Weight observer must have dtype torch.qint8, got {dtype}"
+            )
+        qweight = _quantize_weight(mod.weight.float(), weight_post_process)
+        qlinear_leaky_relu = cls(
+            mod.in_features, mod.out_features, leaky_relu.negative_slope, dtype=dtype
+        )
+        qlinear_leaky_relu.set_weight_bias(qweight, mod.bias)  # type: ignore[arg-type]
+        qlinear_leaky_relu.scale = float(act_scale)
+        qlinear_leaky_relu.zero_point = int(act_zp)
+        return qlinear_leaky_relu
+
+    @classmethod
+    def from_reference(cls, ref_mod, output_scale, output_zero_point):
+        linear = ref_mod[0]
+        leaky_relu = ref_mod[1]
+        qlinear_leaky_relu = cls(
+            linear.in_features, linear.out_features, leaky_relu.negative_slope
+        )
+        qweight = linear.get_quantized_weight()
+        qlinear_leaky_relu.set_weight_bias(qweight, linear.bias)
+        qlinear_leaky_relu.scale = float(output_scale)
+        qlinear_leaky_relu.zero_point = int(output_zero_point)
+        return qlinear_leaky_relu
+
+
+class LinearTanh(nnq.Linear):
+    r"""
+    A LinearTanh module fused from Linear and Tanh modules
+
+    We adopt the same interface as :class:`torch.ao.nn.quantized.Linear`.
+
+    Attributes:
+        Same as torch.ao.nn.quantized.Linear
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> m = nn.intrinsic.LinearTanh(20, 30)
+        >>> input = torch.randn(128, 20)
+        >>> output = m(input)
+        >>> print(output.size())
+        torch.Size([128, 30])
+    """
+
+    _FLOAT_MODULE = nni.LinearTanh  # type: ignore[assignment]
+
+    def __init__(self, in_features, out_features, bias=True, dtype=torch.qint8):
+        super().__init__(in_features, out_features, bias, dtype)
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        return torch.ops.quantized.linear_tanh(
+            x, self._packed_params._packed_params, self.scale, self.zero_point
+        )
+
+    def _get_name(self):
+        return "QuantizedLinearTanh"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        if type(mod) is not nni.LinearTanh:
+            raise AssertionError("Input float module should be LinearTanh")
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+        activation_post_process = mod.activation_post_process
+        mod = mod[0]
+        weight_post_process = mod.qconfig.weight()  # type: ignore[union-attr,operator]
+        weight_post_process(mod.weight)
+        dtype = weight_post_process.dtype
+        act_scale, act_zp = activation_post_process.calculate_qparams()  # type: ignore[union-attr,operator]
+        if dtype != torch.qint8:
+            raise AssertionError(
+                f"Weight observer must have dtype torch.qint8, got {dtype}"
+            )
+        qweight = _quantize_weight(mod.weight.float(), weight_post_process)
+        qlinear_tanh = cls(mod.in_features, mod.out_features, dtype=dtype)
+        qlinear_tanh.set_weight_bias(qweight, mod.bias)  # type: ignore[arg-type]
+        qlinear_tanh.scale = float(act_scale)
+        qlinear_tanh.zero_point = int(act_zp)
+        return qlinear_tanh
+
+    @classmethod
+    def from_reference(cls, ref_mod, output_scale, output_zero_point):
+        linear = ref_mod[0]
+        qlinear_tanh = cls(linear.in_features, linear.out_features)
+        qweight = linear.get_quantized_weight()
+        qlinear_tanh.set_weight_bias(qweight, linear.bias)
+        qlinear_tanh.scale = float(output_scale)
+        qlinear_tanh.zero_point = int(output_zero_point)
+        return qlinear_tanh
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d79bdbfe83209f18b17cc8c7b245f322871d6c0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/__init__.py
@@ -0,0 +1 @@
+from .modules import *  # noqa: F403
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf1a1ea9f95967a963d2a9c58072eac24207064d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d79bdbfe83209f18b17cc8c7b245f322871d6c0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/__init__.py
@@ -0,0 +1 @@
+from .modules import *  # noqa: F403
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e60087d68580b2c33dd624dba9690b0129f4ca0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/modules/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dca71fcf09b019f3e197576eb415ba4fd54fa28a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/modules/__init__.py
@@ -0,0 +1,4 @@
+from .linear import Linear
+
+
+__all__ = ["Linear"]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/modules/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/modules/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8067b15c9acbe19150a20773d86bdc008df3173
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/modules/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/modules/__pycache__/linear.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/modules/__pycache__/linear.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb90215d4717c346830dc0db91335820c727643c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/modules/__pycache__/linear.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/modules/linear.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/modules/linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc2238eedf6f902174421a94702a4188fa463098
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/dynamic/modules/linear.py
@@ -0,0 +1,40 @@
+from typing import Optional, TYPE_CHECKING
+
+import torch
+
+
+if TYPE_CHECKING:
+    from torch.ao.quantization.qconfig import QConfig
+
+
+__all__ = ["Linear"]
+
+
+class Linear(torch.ao.nn.qat.Linear):
+    r"""
+    A linear module attached with FakeQuantize modules for weight,
+    used for dynamic quantization aware training.
+
+    We adopt the same interface as `torch.nn.Linear`, please see
+    https://pytorch.org/docs/stable/nn.html#torch.nn.Linear
+    for documentation.
+
+    Similar to `torch.nn.Linear`, with FakeQuantize modules initialized to
+    default.
+    """
+
+    def __init__(
+        self,
+        in_features: int,
+        out_features: int,
+        bias: bool = True,
+        qconfig: Optional["QConfig"] = None,
+        device: int | str | torch.device | None = None,
+        dtype: str | None = None,
+    ) -> None:
+        super().__init__(in_features, out_features, bias, qconfig, device, dtype)
+        if not torch.ao.quantization.qconfig._activation_is_memoryless(qconfig):  # type: ignore[arg-type]
+            raise ValueError(
+                "Dynamic QAT requires a memoryless observer."
+                + "This means a MovingAverage observer with averaging constant equal to 1"
+            )
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e28e0968a60d7612ebbd26d5f607b4407c2d380
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__init__.py
@@ -0,0 +1,13 @@
+from .conv import Conv1d, Conv2d, Conv3d
+from .embedding_ops import Embedding, EmbeddingBag
+from .linear import Linear
+
+
+__all__ = [
+    "Linear",
+    "Conv1d",
+    "Conv2d",
+    "Conv3d",
+    "Embedding",
+    "EmbeddingBag",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..843f2e9daf7c20d7e769519493e4e64a148d1f29
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__pycache__/conv.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__pycache__/conv.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..48ac71693994dad3eb615464e30b4e2508eb2d83
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__pycache__/conv.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__pycache__/embedding_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__pycache__/embedding_ops.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e1165723787a855ab71fa4258d0d37610a84eee
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__pycache__/embedding_ops.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__pycache__/linear.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__pycache__/linear.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d001b891def42a33434ac20347a58211bb5d7873
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/__pycache__/linear.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/conv.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/conv.py
new file mode 100644
index 0000000000000000000000000000000000000000..a24a4c8d7dae7c80726a76671b3956b4430bc93d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/conv.py
@@ -0,0 +1,318 @@
+# mypy: allow-untyped-defs
+from typing import ClassVar, Literal
+
+import torch
+import torch.nn as nn
+from torch.ao.nn.intrinsic import _FusedModule
+from torch.nn.common_types import _size_1_t, _size_2_t, _size_3_t
+from torch.nn.modules.utils import _pair, _single, _triple
+
+
+__all__ = ["Conv1d", "Conv2d", "Conv3d"]
+
+
+class _ConvNd(nn.modules.conv._ConvNd):
+    _FLOAT_MODULE: ClassVar[type[nn.modules.conv._ConvNd]]
+
+    def __init__(
+        self,
+        in_channels: int,
+        out_channels: int,
+        kernel_size: tuple[int, ...],
+        stride: tuple[int, ...],
+        padding: str | tuple[int, ...],
+        dilation: tuple[int, ...],
+        transposed: bool,
+        output_padding: tuple[int, ...],
+        groups: int,
+        bias: bool,
+        padding_mode: Literal["zeros", "reflect", "replicate", "circular"],
+        qconfig=None,
+        device=None,
+        dtype=None,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        nn.modules.conv._ConvNd.__init__(
+            self,
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            transposed,
+            output_padding,
+            groups,
+            bias,
+            padding_mode,
+            **factory_kwargs,
+        )
+        if not qconfig:
+            raise AssertionError("qconfig must be provided for QAT module")
+        self.qconfig = qconfig
+        self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs)
+
+    def forward(self, input):
+        return self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
+
+    @staticmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Create a qat module from a float module
+
+        Args:
+           `mod`: a float module, either produced by torch.ao.quantization utilities
+           or directly from user
+        """
+        if type(mod) is not cls._FLOAT_MODULE:
+            raise AssertionError(
+                f"qat.{cls.__name__}.from_float only works for "
+                f"{cls._FLOAT_MODULE.__name__}, got {type(mod).__name__}"
+            )
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+        if not mod.qconfig:
+            raise AssertionError("Input float module must have a valid qconfig")
+        if issubclass(type(mod), _FusedModule):
+            mod = mod[0]
+        qconfig = mod.qconfig
+        qat_conv = cls(
+            mod.in_channels,
+            mod.out_channels,
+            mod.kernel_size,
+            stride=mod.stride,
+            padding=mod.padding,
+            dilation=mod.dilation,
+            groups=mod.groups,
+            bias=mod.bias is not None,
+            padding_mode=mod.padding_mode,
+            qconfig=qconfig,
+        )
+        qat_conv.weight = mod.weight
+        qat_conv.bias = mod.bias
+        return qat_conv
+
+    def to_float(self):
+        """This works for both single qat conv, and the qat conv - relu modules
+        to convert the qat module to a floating point module
+        """
+        cls = type(self)
+        conv = cls._FLOAT_CONV_MODULE(  # type: ignore[attr-defined]
+            self.in_channels,
+            self.out_channels,
+            self.kernel_size,
+            self.stride,
+            self.padding,
+            self.dilation,
+            self.groups,
+            self.bias is not None,
+            self.padding_mode,
+        )
+        conv.weight = torch.nn.Parameter(self.weight.detach())
+        if self.bias is not None:
+            conv.bias = torch.nn.Parameter(self.bias.detach())
+        # conv relu
+        if issubclass(cls, _FusedModule):
+            modules = [conv]
+            if not hasattr(cls, "_FLOAT_RELU_MODULE"):
+                raise AssertionError(
+                    f"{cls.__name__} must have _FLOAT_RELU_MODULE attribute"
+                )
+            relu = cls._FLOAT_RELU_MODULE()
+            modules.append(relu)
+
+            # pyrefly: ignore [missing-attribute]
+            fused = cls._FLOAT_MODULE(*modules)
+            fused.train(self.training)
+            return fused
+        else:
+            return conv
+
+
+class Conv1d(_ConvNd, nn.Conv1d):
+    r"""
+    A Conv1d module attached with FakeQuantize modules for weight,
+    used for quantization aware training.
+
+    We adopt the same interface as :class:`~torch.nn.Conv1d`
+
+    Similar to :class:`~torch.nn.Conv2d`, with FakeQuantize modules initialized to
+    default.
+
+    Attributes:
+        weight_fake_quant: fake quant module for weight
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
+    _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
+
+    def __init__(
+        self,
+        in_channels: int,
+        out_channels: int,
+        kernel_size: _size_1_t,
+        stride: _size_1_t = 1,
+        padding: str | _size_1_t = 0,
+        dilation: _size_1_t = 1,
+        groups: int = 1,
+        bias: bool = True,
+        padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
+        qconfig=None,
+        device=None,
+        dtype=None,
+    ) -> None:
+        kernel_size_ = _single(kernel_size)
+        stride_ = _single(stride)
+        padding_ = padding if isinstance(padding, str) else _single(padding)
+        dilation_ = _single(dilation)
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size_,
+            stride=stride_,
+            padding=padding_,
+            dilation=dilation_,
+            transposed=False,
+            output_padding=_single(0),
+            groups=groups,
+            bias=bias,
+            padding_mode=padding_mode,
+            qconfig=qconfig,
+            device=device,
+            dtype=dtype,
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        return super().from_float(
+            cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+
+class Conv2d(_ConvNd, nn.Conv2d):
+    r"""
+    A Conv2d module attached with FakeQuantize modules for weight,
+    used for quantization aware training.
+
+    We adopt the same interface as `torch.nn.Conv2d`, please see
+    https://pytorch.org/docs/stable/nn.html?highlight=conv2d#torch.nn.Conv2d
+    for documentation.
+
+    Similar to `torch.nn.Conv2d`, with FakeQuantize modules initialized to
+    default.
+
+    Attributes:
+        weight_fake_quant: fake quant module for weight
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
+    _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
+
+    def __init__(
+        self,
+        in_channels: int,
+        out_channels: int,
+        kernel_size: _size_2_t,
+        stride: _size_2_t = 1,
+        padding: str | _size_2_t = 0,
+        dilation: _size_2_t = 1,
+        groups: int = 1,
+        bias: bool = True,
+        padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
+        qconfig=None,
+        device=None,
+        dtype=None,
+    ) -> None:
+        kernel_size_ = _pair(kernel_size)
+        stride_ = _pair(stride)
+        padding_ = padding if isinstance(padding, str) else _pair(padding)
+        dilation_ = _pair(dilation)
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size_,
+            stride=stride_,
+            padding=padding_,
+            dilation=dilation_,
+            transposed=False,
+            output_padding=_pair(0),
+            groups=groups,
+            bias=bias,
+            padding_mode=padding_mode,
+            qconfig=qconfig,
+            device=device,
+            dtype=dtype,
+        )
+
+    def forward(self, input):
+        return self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        return super().from_float(
+            cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+
+class Conv3d(_ConvNd, nn.Conv3d):
+    r"""
+    A Conv3d module attached with FakeQuantize modules for weight,
+    used for quantization aware training.
+
+    We adopt the same interface as `torch.nn.Conv3d`, please see
+    https://pytorch.org/docs/stable/nn.html?highlight=conv3d#torch.nn.Conv3d
+    for documentation.
+
+    Similar to `torch.nn.Conv3d`, with FakeQuantize modules initialized to
+    default.
+
+    Attributes:
+        weight_fake_quant: fake quant module for weight
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
+    _FLOAT_CONV_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
+
+    def __init__(
+        self,
+        in_channels: int,
+        out_channels: int,
+        kernel_size: _size_3_t,
+        stride: _size_3_t = 1,
+        padding: str | _size_3_t = 0,
+        dilation: _size_3_t = 1,
+        groups: int = 1,
+        bias: bool = True,
+        padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
+        qconfig=None,
+        device=None,
+        dtype=None,
+    ) -> None:
+        kernel_size_ = _triple(kernel_size)
+        stride_ = _triple(stride)
+        padding_ = padding if isinstance(padding, str) else _triple(padding)
+        dilation_ = _triple(dilation)
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size_,
+            stride=stride_,
+            padding=padding_,
+            dilation=dilation_,
+            transposed=False,
+            output_padding=_triple(0),
+            groups=groups,
+            bias=bias,
+            padding_mode=padding_mode,
+            qconfig=qconfig,
+            device=device,
+            dtype=dtype,
+        )
+
+    def forward(self, input):
+        return self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        return super().from_float(
+            cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/embedding_ops.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/embedding_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..532ef186bf30b10a0b2f6ece106c00335c7a2627
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/embedding_ops.py
@@ -0,0 +1,264 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch import Tensor
+
+
+__all__ = ["Embedding", "EmbeddingBag"]
+
+
+class Embedding(nn.Embedding):
+    r"""
+    An embedding bag module attached with FakeQuantize modules for weight,
+    used for quantization aware training.
+
+    We adopt the same interface as `torch.nn.Embedding`, please see
+    https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html#torch.nn.Embedding
+    for documentation.
+
+    Similar to `torch.nn.Embedding`, with FakeQuantize modules initialized to
+    default.
+
+    Attributes:
+        weight: fake quant module for weight
+    """
+
+    _FLOAT_MODULE = nn.Embedding
+
+    def __init__(
+        self,
+        num_embeddings,
+        embedding_dim,
+        padding_idx=None,
+        max_norm=None,
+        norm_type=2.0,
+        scale_grad_by_freq=False,
+        sparse=False,
+        _weight=None,
+        device=None,
+        dtype=None,
+        qconfig=None,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(
+            num_embeddings,
+            embedding_dim,
+            padding_idx,
+            max_norm,
+            norm_type,
+            scale_grad_by_freq,
+            sparse,
+            _weight,
+            **factory_kwargs,
+        )
+        if not qconfig:
+            raise AssertionError("qconfig must be provided for QAT module")
+        weight_qscheme = qconfig.weight().qscheme
+        if weight_qscheme != torch.per_channel_affine_float_qparams:
+            raise AssertionError(
+                "Embedding weights requires a qscheme of torch.per_channel_affine_float_qparams Got "
+                + str(weight_qscheme)
+            )
+        self.qconfig = qconfig
+        self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs)
+
+    def forward(self, input) -> Tensor:
+        return F.embedding(
+            input,
+            self.weight_fake_quant(self.weight),
+            self.padding_idx,
+            self.max_norm,
+            self.norm_type,
+            self.scale_grad_by_freq,
+            self.sparse,
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Create a qat module from a float module
+
+        Args: `mod` a float module, either produced by torch.ao.quantization utilities
+        or directly from user
+        """
+        if type(mod) is not cls._FLOAT_MODULE:
+            raise AssertionError(
+                " qat."
+                + cls.__name__
+                + ".from_float only works for "
+                + cls._FLOAT_MODULE.__name__
+            )
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+        if not mod.qconfig:
+            raise AssertionError("Input float module must have a valid qconfig")
+        weight_qscheme = mod.qconfig.weight().qscheme  # type: ignore[union-attr, operator]
+        if weight_qscheme != torch.per_channel_affine_float_qparams:
+            raise AssertionError(
+                "Embedding weights requires a qscheme of torch.per_channel_affine_float_qparams Got "
+                + str(weight_qscheme)
+            )
+
+        qconfig = mod.qconfig
+        qat_embedding_bag = cls(
+            mod.num_embeddings,
+            mod.embedding_dim,
+            mod.padding_idx,
+            mod.max_norm,
+            mod.norm_type,
+            mod.scale_grad_by_freq,
+            mod.sparse,
+            mod.weight,
+            qconfig=qconfig,
+        )
+
+        return qat_embedding_bag
+
+    def to_float(self):
+        embedding_bag = torch.nn.Embedding(
+            self.num_embeddings,
+            self.embedding_dim,
+            self.padding_idx,
+            self.max_norm,
+            self.norm_type,
+            self.scale_grad_by_freq,
+            self.sparse,
+            None,
+        )
+        embedding_bag.weight = torch.nn.Parameter(self.weight.detach())
+        embedding_bag.train(self.training)
+        return embedding_bag
+
+
+class EmbeddingBag(nn.EmbeddingBag):
+    r"""
+    An embedding bag module attached with FakeQuantize modules for weight,
+    used for quantization aware training.
+
+    We adopt the same interface as `torch.nn.EmbeddingBag`, please see
+    https://pytorch.org/docs/stable/generated/torch.nn.EmbeddingBag.html#torch.nn.EmbeddingBag
+    for documentation.
+
+    Similar to `torch.nn.EmbeddingBag`, with FakeQuantize modules initialized to
+    default.
+
+    Attributes:
+        weight: fake quant module for weight
+    """
+
+    _FLOAT_MODULE = nn.EmbeddingBag
+
+    def __init__(
+        self,
+        num_embeddings,
+        embedding_dim,
+        max_norm=None,
+        norm_type=2.0,
+        scale_grad_by_freq=False,
+        mode="mean",
+        sparse=False,
+        _weight=None,
+        include_last_offset=False,
+        padding_idx=None,
+        qconfig=None,
+        device=None,
+        dtype=None,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(
+            num_embeddings,
+            embedding_dim,
+            max_norm,
+            norm_type,
+            scale_grad_by_freq,
+            mode,
+            sparse,
+            _weight,
+            include_last_offset,
+            padding_idx,
+            **factory_kwargs,
+        )
+        if not qconfig:
+            raise AssertionError("qconfig must be provided for QAT module")
+        weight_qscheme = qconfig.weight().qscheme
+        if weight_qscheme != torch.per_channel_affine_float_qparams:
+            raise AssertionError(
+                "Embedding Bag weights requires a qscheme of torch.per_channel_affine_float_qparams Got "
+                + str(weight_qscheme)
+            )
+        self.qconfig = qconfig
+        self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs)
+
+    def forward(self, input, offsets=None, per_sample_weights=None) -> Tensor:
+        return F.embedding_bag(
+            input,
+            self.weight_fake_quant(self.weight),
+            offsets,
+            self.max_norm,
+            self.norm_type,
+            self.scale_grad_by_freq,
+            self.mode,
+            self.sparse,
+            per_sample_weights,
+            self.include_last_offset,
+            self.padding_idx,
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Create a qat module from a float module
+
+        Args: `mod` a float module, either produced by torch.ao.quantization utilities
+        or directly from user
+        """
+        if type(mod) is not cls._FLOAT_MODULE:
+            raise AssertionError(
+                " qat."
+                + cls.__name__
+                + ".from_float only works for "
+                + cls._FLOAT_MODULE.__name__
+            )
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+        if not mod.qconfig:
+            raise AssertionError("Input float module must have a valid qconfig")
+        weight_qscheme = mod.qconfig.weight().qscheme  # type: ignore[union-attr, operator]
+        if weight_qscheme != torch.per_channel_affine_float_qparams:
+            raise AssertionError(
+                "Embedding Bag weights requires a qscheme of torch.per_channel_affine_float_qparams Got "
+                + str(weight_qscheme)
+            )
+
+        qconfig = mod.qconfig
+        qat_embedding_bag = cls(
+            mod.num_embeddings,
+            mod.embedding_dim,
+            mod.max_norm,
+            mod.norm_type,
+            mod.scale_grad_by_freq,
+            mod.mode,
+            mod.sparse,
+            mod.weight,
+            mod.include_last_offset,
+            mod.padding_idx,
+            qconfig=qconfig,
+        )
+
+        return qat_embedding_bag
+
+    def to_float(self):
+        embedding_bag = torch.nn.EmbeddingBag(
+            self.num_embeddings,
+            self.embedding_dim,
+            self.max_norm,
+            self.norm_type,
+            self.scale_grad_by_freq,
+            self.mode,
+            self.sparse,
+            None,
+            self.include_last_offset,
+            self.padding_idx,
+        )
+        embedding_bag.weight = torch.nn.Parameter(self.weight.detach())
+        embedding_bag.train(self.training)
+        return embedding_bag
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/linear.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..28e533a76cb16b99944f7f11b4b79b8802c8b624
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/qat/modules/linear.py
@@ -0,0 +1,99 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.ao.nn.intrinsic import LinearReLU
+from torch.nn.utils.parametrize import (
+    is_parametrized,
+    transfer_parametrizations_and_params,
+    type_before_parametrizations,
+)
+
+
+__all__ = ["Linear"]
+
+
+class Linear(nn.Linear):
+    r"""
+    A linear module attached with FakeQuantize modules for weight,
+    used for quantization aware training.
+
+    We adopt the same interface as `torch.nn.Linear`, please see
+    https://pytorch.org/docs/stable/nn.html#torch.nn.Linear
+    for documentation.
+
+    Similar to `torch.nn.Linear`, with FakeQuantize modules initialized to
+    default.
+
+    Attributes:
+        weight: fake quant module for weight
+    """
+
+    _FLOAT_MODULE = nn.Linear
+
+    def __init__(
+        self,
+        in_features,
+        out_features,
+        bias=True,
+        qconfig=None,
+        device=None,
+        dtype=None,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(in_features, out_features, bias, **factory_kwargs)
+        if not qconfig:
+            raise AssertionError("qconfig must be provided for QAT module")
+        self.qconfig = qconfig
+        self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs)
+
+    def forward(self, input):
+        return F.linear(input, self.weight_fake_quant(self.weight), self.bias)
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Create a qat module from a float module or qparams_dict
+        Args: `mod` a float module, either produced by torch.ao.quantization utilities
+        or directly from user
+        """
+        if type_before_parametrizations(mod) != cls._FLOAT_MODULE:
+            raise AssertionError(
+                f"qat.{cls.__name__}.from_float only works for "
+                f"{cls._FLOAT_MODULE.__name__}, got {type_before_parametrizations(mod).__name__}"
+            )
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+        if not mod.qconfig:
+            raise AssertionError("Input float module must have a valid qconfig")
+        if type_before_parametrizations(mod) == LinearReLU:
+            mod = mod[0]
+
+        qconfig = mod.qconfig
+        qat_linear = cls(
+            mod.in_features,
+            mod.out_features,
+            bias=mod.bias is not None,
+            qconfig=qconfig,
+        )
+
+        if is_parametrized(mod, "weight"):
+            transfer_parametrizations_and_params(mod, qat_linear, "weight")
+        else:
+            qat_linear.weight = mod.weight
+
+        if is_parametrized(mod, "bias"):
+            transfer_parametrizations_and_params(mod, qat_linear, "bias")
+        else:
+            qat_linear.bias = mod.bias
+
+        return qat_linear
+
+    def to_float(self):
+        linear = torch.nn.Linear(
+            self.in_features, self.out_features, self.bias is not None
+        )
+        linear.weight = torch.nn.Parameter(self.weight.detach())
+        if self.bias is not None:
+            linear.bias = torch.nn.Parameter(self.bias.detach())
+        linear.train(self.training)
+        return linear
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d79bdbfe83209f18b17cc8c7b245f322871d6c0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/__init__.py
@@ -0,0 +1 @@
+from .modules import *  # noqa: F403
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e3ea5fb08ae715c22f1f1671fa3b508f5f58131b
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..221107660158171ada5d1823cc193666c9e152e7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/__init__.py
@@ -0,0 +1,9 @@
+from .activation import MultiheadAttention
+from .rnn import LSTM, LSTMCell
+
+
+__all__ = [
+    "LSTM",
+    "LSTMCell",
+    "MultiheadAttention",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b554d76e1dfda279abd487ffaaf06deb006237e5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/__pycache__/activation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/__pycache__/activation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20c40d4c21fd1a793da68579f81867fa6f931cd4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/__pycache__/activation.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/__pycache__/rnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/__pycache__/rnn.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..abf294d3eccb47ec4ef8b8491eb5be558621026d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/__pycache__/rnn.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/activation.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/activation.py
new file mode 100644
index 0000000000000000000000000000000000000000..9465da1940be2c538017bfc046512a8c10a4e9cb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/activation.py
@@ -0,0 +1,623 @@
+# mypy: allow-untyped-defs
+import warnings
+
+import torch
+import torch.jit  # this is needed to avoid a circular import
+import torch.nn.functional as F
+from torch import nn, Tensor
+
+
+__all__ = ["MultiheadAttention"]
+
+
+class MultiheadAttention(nn.MultiheadAttention):
+    _FLOAT_MODULE = nn.MultiheadAttention
+
+    r"""Quantizable implementation of the MultiheadAttention.
+
+    Note::
+        Please, refer to :class:`~torch.nn.MultiheadAttention` for more
+        information
+
+    Allows the model to jointly attend to information from different
+    representation subspaces.
+    See reference: Attention Is All You Need
+
+    The original MHA module is not quantizable.
+    This reimplements it by explicitly instantiating the linear layers.
+
+    .. math::
+        \text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O
+        \text{where} head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)
+
+    Args:
+        embed_dim: total dimension of the model.
+        num_heads: parallel attention heads.
+        dropout: a Dropout layer on attn_output_weights. Default: 0.0.
+        bias: add bias as module parameter. Default: True.
+        add_bias_kv: add bias to the key and value sequences at dim=0.
+        add_zero_attn: add a new batch of zeros to the key and
+                       value sequences at dim=1.
+        kdim: total number of features in key. Default: None.
+        vdim: total number of features in value. Default: None.
+        batch_first: If ``True``, then the input and output tensors are provided
+            as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
+
+    Note that if :attr:`kdim` and :attr:`vdim` are None, they will be set
+    to :attr:`embed_dim` such that query, key, and value have the same
+    number of features.
+
+    Examples::
+
+        >>> import torch.ao.nn.quantizable as nnqa
+        >>> multihead_attn = nnqa.MultiheadAttention(embed_dim, num_heads)
+        >>> attn_output, attn_output_weights = multihead_attn(query, key, value)
+
+    Note::
+        Please, follow the quantization flow to convert the quantizable MHA.
+    """
+    __constants__ = ["batch_first"]
+
+    def __init__(
+        self,
+        embed_dim: int,
+        num_heads: int,
+        dropout: float = 0.0,
+        bias: bool = True,
+        add_bias_kv: bool = False,
+        add_zero_attn: bool = False,
+        kdim: int | None = None,
+        vdim: int | None = None,
+        batch_first: bool = False,
+        device=None,
+        dtype=None,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(
+            embed_dim,
+            num_heads,
+            dropout,
+            bias,
+            add_bias_kv,
+            add_zero_attn,
+            kdim,
+            vdim,
+            batch_first,
+            **factory_kwargs,
+        )
+        self.linear_Q = nn.Linear(
+            self.embed_dim, self.embed_dim, bias=bias, **factory_kwargs
+        )
+        self.linear_K = nn.Linear(
+            self.kdim, self.embed_dim, bias=bias, **factory_kwargs
+        )
+        self.linear_V = nn.Linear(
+            self.vdim, self.embed_dim, bias=bias, **factory_kwargs
+        )
+        # for the type: ignore, see https://github.com/pytorch/pytorch/issues/58969
+        # pyrefly: ignore [bad-assignment]
+        self.out_proj = nn.Linear(
+            self.embed_dim, self.embed_dim, bias=bias, **factory_kwargs
+        )  # type: ignore[assignment]
+
+        # Functionals
+        self.q_scaling_product = torch.ao.nn.quantized.FloatFunctional()
+        # note: importing torch.ao.nn.quantized at top creates a circular import
+
+        # Quant/Dequant
+        self.quant_attn_output = torch.ao.quantization.QuantStub()
+        self.quant_attn_output_weights = torch.ao.quantization.QuantStub()
+        self.dequant_q = torch.ao.quantization.DeQuantStub()
+        self.dequant_k = torch.ao.quantization.DeQuantStub()
+        self.dequant_v = torch.ao.quantization.DeQuantStub()
+
+    def _get_name(self):
+        return "QuantizableMultiheadAttention"
+
+    @classmethod
+    def from_float(cls, other):
+        if type(other) is not cls._FLOAT_MODULE:
+            raise AssertionError(
+                f"Expected type {cls._FLOAT_MODULE}, got {type(other)}"
+            )
+        if not hasattr(other, "qconfig"):
+            raise AssertionError("The float module must have 'qconfig'")
+        # Setting the dropout to 0.0!
+        observed = cls(
+            other.embed_dim,
+            other.num_heads,
+            other.dropout,
+            (other.in_proj_bias is not None),
+            (other.bias_k is not None),
+            other.add_zero_attn,
+            other.kdim,
+            other.vdim,
+            other.batch_first,
+        )
+        observed.bias_k = other.bias_k
+        observed.bias_v = other.bias_v
+        observed.qconfig = other.qconfig
+
+        # Set the linear weights
+        # for the type: ignores, see https://github.com/pytorch/pytorch/issues/58969
+        observed.out_proj.weight = other.out_proj.weight
+        observed.out_proj.bias = other.out_proj.bias
+        if other._qkv_same_embed_dim:
+            # Use separate params
+            bias = other.in_proj_bias
+            _start = 0
+            _end = _start + other.embed_dim
+            weight = other.in_proj_weight[_start:_end, :]
+            if bias is not None:
+                bias = torch.nn.Parameter(bias[_start:_end], bias.requires_grad)
+            observed.linear_Q.weight = torch.nn.Parameter(weight, weight.requires_grad)
+            observed.linear_Q.bias = bias
+
+            bias = other.in_proj_bias
+            _start = _end
+            _end = _start + other.embed_dim
+            weight = other.in_proj_weight[_start:_end, :]
+            if bias is not None:
+                bias = torch.nn.Parameter(bias[_start:_end], bias.requires_grad)
+            observed.linear_K.weight = torch.nn.Parameter(weight, weight.requires_grad)
+            observed.linear_K.bias = bias
+
+            bias = other.in_proj_bias
+            _start = _end
+            weight = other.in_proj_weight[_start:, :]
+            if bias is not None:
+                bias = torch.nn.Parameter(bias[_start:], bias.requires_grad)
+            observed.linear_V.weight = torch.nn.Parameter(weight, weight.requires_grad)
+            observed.linear_V.bias = bias
+        else:
+            observed.linear_Q.weight = nn.Parameter(other.q_proj_weight)
+            observed.linear_K.weight = nn.Parameter(other.k_proj_weight)
+            observed.linear_V.weight = nn.Parameter(other.v_proj_weight)
+            if other.in_proj_bias is None:
+                # pyrefly: ignore [bad-assignment]
+                observed.linear_Q.bias = None
+                # pyrefly: ignore [bad-assignment]
+                observed.linear_K.bias = None
+                # pyrefly: ignore [bad-assignment]
+                observed.linear_V.bias = None
+            else:
+                observed.linear_Q.bias = nn.Parameter(
+                    other.in_proj_bias[0 : other.embed_dim]
+                )
+                observed.linear_K.bias = nn.Parameter(
+                    other.in_proj_bias[other.embed_dim : (other.embed_dim * 2)]
+                )
+                observed.linear_V.bias = nn.Parameter(
+                    other.in_proj_bias[(other.embed_dim * 2) :]
+                )
+        observed.eval()
+        # Explicit prepare
+        observed = torch.ao.quantization.prepare(observed, inplace=True)
+        return observed
+
+    @torch.jit.unused
+    def dequantize(self):
+        r"""Utility to convert the quantized MHA back to float.
+
+        The motivation for this is that it is not trivial to convert the weights
+        from the format that is used in the quantized version back to the
+        float.
+        """
+        fp = self._FLOAT_MODULE(
+            self.embed_dim,
+            self.num_heads,
+            self.dropout,
+            (self.linear_Q._weight_bias()[1] is not None),  # type: ignore[operator]
+            (self.bias_k is not None),
+            self.add_zero_attn,
+            self.kdim,
+            self.vdim,
+            self.batch_first,
+        )
+        if fp._qkv_same_embed_dim != self._qkv_same_embed_dim:
+            raise AssertionError(
+                f"_qkv_same_embed_dim mismatch: {fp._qkv_same_embed_dim} != {self._qkv_same_embed_dim}"
+            )
+        if self.bias_k is not None:
+            fp.bias_k = nn.Parameter(self.bias_k.dequantize())
+        if self.bias_v is not None:
+            fp.bias_v = nn.Parameter(self.bias_v.dequantize())
+
+        # Set the linear weights
+        # Note: Because the linear layers are quantized, mypy does not know how
+        # to deal with them -- might need to ignore the typing checks.
+        # for the type: ignore[has-type], see https://github.com/pytorch/pytorch/issues/58969
+        w, b = self.out_proj._weight_bias()  # type: ignore[operator, has-type]
+        fp.out_proj.weight = nn.Parameter(w.dequantize())
+        if b is not None:
+            fp.out_proj.bias = nn.Parameter(b)
+
+        wQ, bQ = self.linear_Q._weight_bias()  # type: ignore[operator]
+        wQ = wQ.dequantize()
+        wK, bK = self.linear_K._weight_bias()  # type: ignore[operator]
+        wK = wK.dequantize()
+        wV, bV = self.linear_V._weight_bias()  # type: ignore[operator]
+        wV = wV.dequantize()
+        if fp._qkv_same_embed_dim:
+            # Use separate params
+            _start = 0
+            _end = _start + fp.embed_dim
+            fp.in_proj_weight[_start:_end, :] = wQ
+            if fp.in_proj_bias is not None:
+                # pyrefly: ignore [bad-argument-type]
+                if not all(bQ == 0):
+                    raise AssertionError("Expected all bQ elements to be 0")
+                fp.in_proj_bias[_start:_end] = bQ
+
+            _start = _end
+            _end = _start + fp.embed_dim
+            fp.in_proj_weight[_start:_end, :] = wK
+            if fp.in_proj_bias is not None:
+                # pyrefly: ignore [bad-argument-type]
+                if not all(bK == 0):
+                    raise AssertionError("Expected all bK elements to be 0")
+                fp.in_proj_bias[_start:_end] = bK
+
+            _start = _end
+            fp.in_proj_weight[_start:, :] = wV
+            if fp.in_proj_bias is not None:
+                # pyrefly: ignore [bad-argument-type]
+                if not all(bV == 0):
+                    raise AssertionError("Expected all bV elements to be 0")
+                fp.in_proj_bias[_start:] = bV
+        else:
+            fp.q_proj_weight = nn.Parameter(wQ)
+            fp.k_proj_weight = nn.Parameter(wK)
+            fp.v_proj_weight = nn.Parameter(wV)
+            if fp.in_proj_bias is None:
+                # pyrefly: ignore [bad-assignment]
+                self.linear_Q.bias = None
+                # pyrefly: ignore [bad-assignment]
+                self.linear_K.bias = None
+                # pyrefly: ignore [bad-assignment]
+                self.linear_V.bias = None
+            else:
+                fp.in_proj_bias[0 : fp.embed_dim] = bQ
+                fp.in_proj_bias[fp.embed_dim : (fp.embed_dim * 2)] = bK
+                fp.in_proj_bias[(fp.embed_dim * 2) :] = bV
+
+        return fp
+
+    @classmethod
+    def from_observed(cls, other):
+        # The whole flow is float -> observed -> quantized
+        # This class does float -> observed only
+        # See nn.quantized.MultiheadAttention
+        raise NotImplementedError(
+            "It looks like you are trying to prepare an "
+            "MHA module. Please, see "
+            "the examples on quantizable MHAs."
+        )
+
+    def forward(
+        self,
+        query: Tensor,
+        key: Tensor,
+        value: Tensor,
+        key_padding_mask: Tensor | None = None,
+        need_weights: bool = True,
+        attn_mask: Tensor | None = None,
+        average_attn_weights: bool = True,
+        is_causal: bool = False,
+    ) -> tuple[Tensor, Tensor | None]:
+        r"""
+        Note::
+            Please, refer to :func:`~torch.nn.MultiheadAttention.forward` for more
+            information
+
+        Args:
+            query, key, value: map a query and a set of key-value pairs to an output.
+                See "Attention Is All You Need" for more details.
+            key_padding_mask: if provided, specified padding elements in the key will
+                be ignored by the attention. When given a binary mask and a value is True,
+                the corresponding value on the attention layer will be ignored.
+            need_weights: output attn_output_weights.
+            attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
+                the batches while a 3D mask allows to specify a different mask for the entries of each batch.
+
+        Shape:
+            - Inputs:
+            - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
+              the embedding dimension. :math:`(N, L, E)` if ``batch_first`` is ``True``.
+            - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
+              the embedding dimension. :math:`(N, S, E)` if ``batch_first`` is ``True``.
+            - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
+              the embedding dimension. :math:`(N, S, E)` if ``batch_first`` is ``True``.
+            - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.
+              If a BoolTensor is provided, the positions with the
+              value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
+            - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
+              3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
+              S is the source sequence length. attn_mask ensure that position i is allowed to attend the unmasked
+              positions. If a BoolTensor is provided, positions with ``True``
+              is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
+              is provided, it will be added to the attention weight.
+            - is_causal: If specified, applies a causal mask as attention mask. Mutually exclusive with providing attn_mask.
+              Default: ``False``.
+            - average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across
+              heads. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an
+              effect when ``need_weights=True.``. Default: True (i.e. average weights across heads)
+
+            - Outputs:
+            - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
+              E is the embedding dimension. :math:`(N, L, E)` if ``batch_first`` is ``True``.
+            - attn_output_weights: If ``average_attn_weights=True``, returns attention weights averaged
+              across heads of shape :math:`(N, L, S)`, where N is the batch size, L is the target sequence length,
+              S is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
+              head of shape :math:`(N, num_heads, L, S)`.
+        """
+        return self._forward_impl(
+            query,
+            key,
+            value,
+            key_padding_mask,
+            need_weights,
+            attn_mask,
+            average_attn_weights,
+            is_causal,
+        )
+
+    def _forward_impl(
+        self,
+        query: Tensor,
+        key: Tensor,
+        value: Tensor,
+        key_padding_mask: Tensor | None = None,
+        need_weights: bool = True,
+        attn_mask: Tensor | None = None,
+        average_attn_weights: bool = True,
+        is_causal: bool = False,
+    ) -> tuple[Tensor, Tensor | None]:
+        # This version will not deal with the static key/value pairs.
+        # Keeping it here for future changes.
+        #
+        # TODO: This method has some duplicate lines with the
+        # `torch.nn.functional.multi_head_attention`. Will need to refactor.
+        static_k = None
+        static_v = None
+
+        if attn_mask is not None and is_causal:
+            raise AssertionError("Only allow causal mask or attn_mask")
+
+        if is_causal:
+            raise AssertionError("causal mask not supported by AO MHA module")
+
+        if self.batch_first:
+            query, key, value = (x.transpose(0, 1) for x in (query, key, value))
+
+        tgt_len, bsz, embed_dim_to_check = query.size()
+        if self.embed_dim != embed_dim_to_check:
+            raise AssertionError(
+                f"embed_dim mismatch: {self.embed_dim} != {embed_dim_to_check}"
+            )
+        # allow MHA to have different sizes for the feature dimension
+        if key.size(0) != value.size(0) or key.size(1) != value.size(1):
+            raise AssertionError(
+                f"key and value size mismatch: key.size()={key.size()}, value.size()={value.size()}"
+            )
+
+        head_dim = self.embed_dim // self.num_heads
+        if head_dim * self.num_heads != self.embed_dim:
+            raise AssertionError("embed_dim must be divisible by num_heads")
+        scaling = float(head_dim) ** -0.5
+
+        q = self.linear_Q(query)
+        k = self.linear_K(key)
+        v = self.linear_V(value)
+
+        q = self.q_scaling_product.mul_scalar(q, scaling)
+
+        if attn_mask is not None:
+            if attn_mask.dtype == torch.uint8:
+                warnings.warn(
+                    "Byte tensor for `attn_mask` in `nn.MultiheadAttention` is deprecated. "
+                    "Use bool tensor instead.",
+                    stacklevel=3,
+                )
+                attn_mask = attn_mask.to(torch.bool)
+            if not attn_mask.is_floating_point() and attn_mask.dtype != torch.bool:
+                raise AssertionError(
+                    f"Only float and bool types are supported for attn_mask, not {attn_mask.dtype}"
+                )
+
+            if attn_mask.dim() == 2:
+                attn_mask = attn_mask.unsqueeze(0)
+                if list(attn_mask.size()) != [1, query.size(0), key.size(0)]:
+                    raise RuntimeError("The size of the 2D attn_mask is not correct.")
+            elif attn_mask.dim() == 3:
+                if list(attn_mask.size()) != [
+                    bsz * self.num_heads,
+                    query.size(0),
+                    key.size(0),
+                ]:
+                    raise RuntimeError("The size of the 3D attn_mask is not correct.")
+            else:
+                raise RuntimeError(
+                    f"attn_mask's dimension {attn_mask.dim()} is not supported"
+                )
+            # attn_mask's dim is 3 now.
+
+        # convert ByteTensor key_padding_mask to bool
+        if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8:
+            warnings.warn(
+                "Byte tensor for `key_padding_mask` in `nn.MultiheadAttention` is deprecated. "
+                "Use bool tensor instead.",
+                stacklevel=3,
+            )
+            key_padding_mask = key_padding_mask.to(torch.bool)
+        if self.bias_k is not None and self.bias_v is not None:
+            if static_k is None and static_v is None:
+                # Explicitly check that bias_k and bias_v are not None
+                # in a way that TorchScript can understand.
+                bias_k = self.bias_k
+                if bias_k is None:
+                    raise AssertionError("bias_k must not be None")
+                bias_v = self.bias_v
+                if bias_v is None:
+                    raise AssertionError("bias_v must not be None")
+
+                k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
+                v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
+                if attn_mask is not None:
+                    attn_mask = F.pad(attn_mask, (0, 1))
+                if key_padding_mask is not None:
+                    key_padding_mask = F.pad(key_padding_mask, (0, 1))
+            else:
+                if static_k is not None:
+                    raise AssertionError("bias cannot be added to static key.")
+                if static_v is not None:
+                    raise AssertionError("bias cannot be added to static value.")
+        else:
+            if self.bias_k is not None:
+                raise AssertionError(
+                    "self.bias_k must be None when self.bias_v is None"
+                )
+            if self.bias_v is not None:
+                raise AssertionError(
+                    "self.bias_v must be None when self.bias_k is None"
+                )
+
+        q = q.contiguous().view(tgt_len, bsz * self.num_heads, head_dim).transpose(0, 1)
+        if k is not None:
+            k = k.contiguous().view(-1, bsz * self.num_heads, head_dim).transpose(0, 1)
+        if v is not None:
+            v = v.contiguous().view(-1, bsz * self.num_heads, head_dim).transpose(0, 1)
+
+        if static_k is not None:
+            if static_k.size(0) != bsz * self.num_heads:
+                raise AssertionError(
+                    f"static_k.size(0) must be {bsz * self.num_heads}, got {static_k.size(0)}"
+                )
+            if static_k.size(2) != head_dim:
+                raise AssertionError(
+                    f"static_k.size(2) must be {head_dim}, got {static_k.size(2)}"
+                )
+            k = static_k
+
+        if static_v is not None:
+            if static_v.size(0) != bsz * self.num_heads:
+                raise AssertionError(
+                    f"static_v.size(0) must be {bsz * self.num_heads}, got {static_v.size(0)}"
+                )
+            if static_v.size(2) != head_dim:
+                raise AssertionError(
+                    f"static_v.size(2) must be {head_dim}, got {static_v.size(2)}"
+                )
+            v = static_v
+
+        src_len = k.size(1)
+
+        if key_padding_mask is not None:
+            if key_padding_mask.size(0) != bsz:
+                raise AssertionError(
+                    f"key_padding_mask.size(0) must be {bsz}, got {key_padding_mask.size(0)}"
+                )
+            if key_padding_mask.size(1) != src_len:
+                raise AssertionError(
+                    f"key_padding_mask.size(1) must be {src_len}, got {key_padding_mask.size(1)}"
+                )
+
+        if self.add_zero_attn:
+            src_len += 1
+
+            k_zeros = torch.zeros((k.size(0), 1) + k.size()[2:])
+
+            if k.is_quantized:
+                k_zeros = torch.quantize_per_tensor(
+                    k_zeros,
+                    k.q_scale(),
+                    k.q_zero_point(),
+                    k.dtype,
+                )
+
+            k = torch.cat([k, k_zeros], dim=1)
+
+            v_zeros = torch.zeros((v.size(0), 1) + k.size()[2:])
+
+            if v.is_quantized:
+                v_zeros = torch.quantize_per_tensor(
+                    v_zeros,
+                    v.q_scale(),
+                    v.q_zero_point(),
+                    v.dtype,
+                )
+
+            v = torch.cat([v, v_zeros], dim=1)
+
+            if attn_mask is not None:
+                attn_mask = F.pad(attn_mask, (0, 1))
+            if key_padding_mask is not None:
+                key_padding_mask = F.pad(key_padding_mask, (0, 1))
+
+        # Leaving the quantized zone here
+        q = self.dequant_q(q)
+        k = self.dequant_k(k)
+        v = self.dequant_v(v)
+        attn_output_weights = torch.bmm(q, k.transpose(1, 2))
+        expected_size = [bsz * self.num_heads, tgt_len, src_len]
+        if list(attn_output_weights.size()) != expected_size:
+            raise AssertionError(
+                f"attn_output_weights size mismatch: expected {expected_size}, "
+                f"got {list(attn_output_weights.size())}"
+            )
+
+        if attn_mask is not None:
+            if attn_mask.dtype == torch.bool:
+                attn_output_weights.masked_fill_(attn_mask, float("-inf"))
+            else:
+                attn_output_weights += attn_mask
+
+        if key_padding_mask is not None:
+            attn_output_weights = attn_output_weights.view(
+                bsz, self.num_heads, tgt_len, src_len
+            )
+            attn_output_weights = attn_output_weights.masked_fill(
+                key_padding_mask.unsqueeze(1).unsqueeze(2),
+                float("-inf"),
+            )
+            attn_output_weights = attn_output_weights.view(
+                bsz * self.num_heads, tgt_len, src_len
+            )
+
+        attn_output_weights = F.softmax(attn_output_weights, dim=-1)
+        attn_output_weights = F.dropout(
+            attn_output_weights, p=self.dropout, training=self.training
+        )
+
+        attn_output = torch.bmm(attn_output_weights, v)
+        expected_output_size = [bsz * self.num_heads, tgt_len, head_dim]
+        if list(attn_output.size()) != expected_output_size:
+            raise AssertionError(
+                f"attn_output size mismatch: expected {expected_output_size}, "
+                f"got {list(attn_output.size())}"
+            )
+        if self.batch_first:
+            attn_output = attn_output.view(bsz, tgt_len, self.embed_dim)
+        else:
+            attn_output = (
+                attn_output.transpose(0, 1)
+                .contiguous()
+                .view(tgt_len, bsz, self.embed_dim)
+            )
+
+        # Reentering the quantized zone
+        attn_output = self.quant_attn_output(attn_output)
+        # for the type: ignore[has-type], see https://github.com/pytorch/pytorch/issues/58969
+        attn_output = self.out_proj(attn_output)  # type: ignore[has-type]
+        attn_output_weights = self.quant_attn_output_weights(attn_output_weights)
+
+        if need_weights:
+            # average attention weights over heads
+            attn_output_weights = attn_output_weights.view(
+                bsz, self.num_heads, tgt_len, src_len
+            )
+            if average_attn_weights:
+                attn_output_weights = attn_output_weights.mean(dim=1)
+            return attn_output, attn_output_weights
+        else:
+            return attn_output, None
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/rnn.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/rnn.py
new file mode 100644
index 0000000000000000000000000000000000000000..f09077a70f14040bd96ff60362a9d9975718cbb8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantizable/modules/rnn.py
@@ -0,0 +1,618 @@
+"""
+We will recreate all the RNN modules as we require the modules to be decomposed
+into its building blocks to be able to observe.
+"""
+
+# mypy: allow-untyped-defs
+
+import numbers
+import warnings
+
+import torch
+from torch import Tensor
+
+
+__all__ = ["LSTMCell", "LSTM"]
+
+
+class LSTMCell(torch.nn.Module):
+    r"""A quantizable long short-term memory (LSTM) cell.
+
+    For the description and the argument types, please, refer to :class:`~torch.nn.LSTMCell`
+
+    `split_gates`: specify True to compute the input/forget/cell/output gates separately
+    to avoid an intermediate tensor which is subsequently chunk'd. This optimization can
+    be beneficial for on-device inference latency. This flag is cascaded down from the
+    parent classes.
+
+    Examples::
+
+        >>> import torch.ao.nn.quantizable as nnqa
+        >>> rnn = nnqa.LSTMCell(10, 20)
+        >>> input = torch.randn(6, 10)
+        >>> hx = torch.randn(3, 20)
+        >>> cx = torch.randn(3, 20)
+        >>> output = []
+        >>> for i in range(6):
+        ...     hx, cx = rnn(input[i], (hx, cx))
+        ...     output.append(hx)
+    """
+
+    _FLOAT_MODULE = torch.nn.LSTMCell
+    __constants__ = ["split_gates"]  # for jit.script
+
+    def __init__(
+        self,
+        input_dim: int,
+        hidden_dim: int,
+        bias: bool = True,
+        device=None,
+        dtype=None,
+        *,
+        split_gates=False,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__()
+        self.input_size = input_dim
+        self.hidden_size = hidden_dim
+        self.bias = bias
+        self.split_gates = split_gates
+
+        if not split_gates:
+            self.igates: torch.nn.Module = torch.nn.Linear(
+                input_dim, 4 * hidden_dim, bias=bias, **factory_kwargs
+            )
+            self.hgates: torch.nn.Module = torch.nn.Linear(
+                hidden_dim, 4 * hidden_dim, bias=bias, **factory_kwargs
+            )
+            self.gates: torch.nn.Module = torch.ao.nn.quantized.FloatFunctional()
+        else:
+            # keep separate Linear layers for each gate
+            self.igates = torch.nn.ModuleDict()
+            self.hgates = torch.nn.ModuleDict()
+            self.gates = torch.nn.ModuleDict()
+            for g in ["input", "forget", "cell", "output"]:
+                # pyre-fixme[29]: `Union[torch._tensor.Tensor, torch.nn.modules.module.Module]`
+                self.igates[g] = torch.nn.Linear(
+                    input_dim, hidden_dim, bias=bias, **factory_kwargs
+                )
+                # pyre-fixme[29]: `Union[torch._tensor.Tensor, torch.nn.modules.module.Module]`
+                self.hgates[g] = torch.nn.Linear(
+                    hidden_dim, hidden_dim, bias=bias, **factory_kwargs
+                )
+                # pyre-fixme[29]: `Union[torch._tensor.Tensor, torch.nn.modules.module.Module]`
+                self.gates[g] = torch.ao.nn.quantized.FloatFunctional()
+
+        self.input_gate = torch.nn.Sigmoid()
+        self.forget_gate = torch.nn.Sigmoid()
+        self.cell_gate = torch.nn.Tanh()
+        self.output_gate = torch.nn.Sigmoid()
+
+        self.fgate_cx = torch.ao.nn.quantized.FloatFunctional()
+        self.igate_cgate = torch.ao.nn.quantized.FloatFunctional()
+        self.fgate_cx_igate_cgate = torch.ao.nn.quantized.FloatFunctional()
+
+        self.ogate_cy = torch.ao.nn.quantized.FloatFunctional()
+
+        self.initial_hidden_state_qparams: tuple[float, int] = (1.0, 0)
+        self.initial_cell_state_qparams: tuple[float, int] = (1.0, 0)
+        self.hidden_state_dtype: torch.dtype = torch.quint8
+        self.cell_state_dtype: torch.dtype = torch.quint8
+
+    def forward(
+        self, x: Tensor, hidden: tuple[Tensor, Tensor] | None = None
+    ) -> tuple[Tensor, Tensor]:
+        if hidden is None or hidden[0] is None or hidden[1] is None:
+            hidden = self.initialize_hidden(x.shape[0], x.is_quantized)
+        hx, cx = hidden
+
+        if not self.split_gates:
+            igates = self.igates(x)
+            hgates = self.hgates(hx)
+            gates = self.gates.add(igates, hgates)  # type: ignore[operator]
+
+            input_gate, forget_gate, cell_gate, out_gate = gates.chunk(4, 1)
+
+            input_gate = self.input_gate(input_gate)
+            forget_gate = self.forget_gate(forget_gate)
+            cell_gate = self.cell_gate(cell_gate)
+            out_gate = self.output_gate(out_gate)
+        else:
+            # apply each input + hidden projection and add together
+            gate = {}
+            for (key, gates), igates, hgates in zip(
+                self.gates.items(),  # type: ignore[operator]
+                self.igates.values(),  # type: ignore[operator]
+                self.hgates.values(),  # type: ignore[operator]
+            ):
+                gate[key] = gates.add(igates(x), hgates(hx))
+
+            input_gate = self.input_gate(gate["input"])
+            forget_gate = self.forget_gate(gate["forget"])
+            cell_gate = self.cell_gate(gate["cell"])
+            out_gate = self.output_gate(gate["output"])
+
+        fgate_cx = self.fgate_cx.mul(forget_gate, cx)
+        igate_cgate = self.igate_cgate.mul(input_gate, cell_gate)
+        fgate_cx_igate_cgate = self.fgate_cx_igate_cgate.add(fgate_cx, igate_cgate)
+        cy = fgate_cx_igate_cgate
+
+        # TODO: make this tanh a member of the module so its qparams can be configured
+        tanh_cy = torch.tanh(cy)
+        hy = self.ogate_cy.mul(out_gate, tanh_cy)
+        return hy, cy
+
+    def initialize_hidden(
+        self, batch_size: int, is_quantized: bool = False
+    ) -> tuple[Tensor, Tensor]:
+        h, c = (
+            torch.zeros((batch_size, self.hidden_size)),
+            torch.zeros((batch_size, self.hidden_size)),
+        )
+        if is_quantized:
+            (h_scale, h_zp) = self.initial_hidden_state_qparams
+            (c_scale, c_zp) = self.initial_cell_state_qparams
+            h = torch.quantize_per_tensor(
+                h, scale=h_scale, zero_point=h_zp, dtype=self.hidden_state_dtype
+            )
+            c = torch.quantize_per_tensor(
+                c, scale=c_scale, zero_point=c_zp, dtype=self.cell_state_dtype
+            )
+        return h, c
+
+    def _get_name(self):
+        return "QuantizableLSTMCell"
+
+    @classmethod
+    def from_params(cls, wi, wh, bi=None, bh=None, split_gates=False):
+        """Uses the weights and biases to create a new LSTM cell.
+
+        Args:
+            wi, wh: Weights for the input and hidden layers
+            bi, bh: Biases for the input and hidden layers
+        """
+        if (bi is None) != (bh is None):
+            raise AssertionError("bi and bh must both be None or both have values")
+        input_size = wi.shape[1]
+        hidden_size = wh.shape[1]
+        cell = cls(
+            input_dim=input_size,
+            hidden_dim=hidden_size,
+            bias=(bi is not None),
+            split_gates=split_gates,
+        )
+
+        if not split_gates:
+            cell.igates.weight = torch.nn.Parameter(wi)
+            if bi is not None:
+                cell.igates.bias = torch.nn.Parameter(bi)
+            cell.hgates.weight = torch.nn.Parameter(wh)
+            if bh is not None:
+                cell.hgates.bias = torch.nn.Parameter(bh)
+        else:
+            # split weight/bias
+            for w, b, gates in zip([wi, wh], [bi, bh], [cell.igates, cell.hgates]):
+                for w_chunk, gate in zip(w.chunk(4, dim=0), gates.values()):  # type: ignore[operator]
+                    gate.weight = torch.nn.Parameter(w_chunk)
+
+                if b is not None:
+                    for b_chunk, gate in zip(b.chunk(4, dim=0), gates.values()):  # type: ignore[operator]
+                        gate.bias = torch.nn.Parameter(b_chunk)
+
+        return cell
+
+    @classmethod
+    def from_float(cls, other, use_precomputed_fake_quant=False, split_gates=False):
+        if type(other) is not cls._FLOAT_MODULE:
+            raise AssertionError(
+                f"Expected module type {cls._FLOAT_MODULE}, got {type(other)}"
+            )
+        if not hasattr(other, "qconfig"):
+            raise AssertionError("The float module must have 'qconfig'")
+        observed = cls.from_params(
+            other.weight_ih,
+            other.weight_hh,
+            other.bias_ih,
+            other.bias_hh,
+            split_gates=split_gates,
+        )
+        observed.qconfig = other.qconfig
+        observed.igates.qconfig = other.qconfig
+        observed.hgates.qconfig = other.qconfig
+        if split_gates:
+            # also apply qconfig directly to Linear modules
+            for g in observed.igates.values():
+                g.qconfig = other.qconfig
+            for g in observed.hgates.values():
+                g.qconfig = other.qconfig
+        return observed
+
+
+class _LSTMSingleLayer(torch.nn.Module):
+    r"""A single one-directional LSTM layer.
+
+    The difference between a layer and a cell is that the layer can process a
+    sequence, while the cell only expects an instantaneous value.
+    """
+
+    def __init__(
+        self,
+        input_dim: int,
+        hidden_dim: int,
+        bias: bool = True,
+        device=None,
+        dtype=None,
+        *,
+        split_gates=False,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__()
+        self.cell = LSTMCell(
+            input_dim, hidden_dim, bias=bias, split_gates=split_gates, **factory_kwargs
+        )
+
+    def forward(self, x: Tensor, hidden: tuple[Tensor, Tensor] | None = None):
+        result = []
+        seq_len = x.shape[0]
+        for i in range(seq_len):
+            hidden = self.cell(x[i], hidden)
+            result.append(hidden[0])  # type: ignore[index]
+        result_tensor = torch.stack(result, 0)
+        return result_tensor, hidden
+
+    @classmethod
+    def from_params(cls, *args, **kwargs):
+        cell = LSTMCell.from_params(*args, **kwargs)
+        layer = cls(
+            cell.input_size, cell.hidden_size, cell.bias, split_gates=cell.split_gates
+        )
+        layer.cell = cell
+        return layer
+
+
+class _LSTMLayer(torch.nn.Module):
+    r"""A single bi-directional LSTM layer."""
+
+    def __init__(
+        self,
+        input_dim: int,
+        hidden_dim: int,
+        bias: bool = True,
+        batch_first: bool = False,
+        bidirectional: bool = False,
+        device=None,
+        dtype=None,
+        *,
+        split_gates=False,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__()
+        self.batch_first = batch_first
+        self.bidirectional = bidirectional
+        self.layer_fw = _LSTMSingleLayer(
+            input_dim, hidden_dim, bias=bias, split_gates=split_gates, **factory_kwargs
+        )
+        if self.bidirectional:
+            self.layer_bw = _LSTMSingleLayer(
+                input_dim,
+                hidden_dim,
+                bias=bias,
+                split_gates=split_gates,
+                **factory_kwargs,
+            )
+
+    def forward(self, x: Tensor, hidden: tuple[Tensor, Tensor] | None = None):
+        if self.batch_first:
+            x = x.transpose(0, 1)
+        if hidden is None:
+            hx_fw, cx_fw = (None, None)
+        else:
+            hx_fw, cx_fw = hidden
+        hidden_bw: tuple[Tensor, Tensor] | None = None
+        if self.bidirectional:
+            if hx_fw is None:
+                hx_bw = None
+            else:
+                hx_bw = hx_fw[1]
+                hx_fw = hx_fw[0]
+            if cx_fw is None:
+                cx_bw = None
+            else:
+                cx_bw = cx_fw[1]
+                cx_fw = cx_fw[0]
+            if hx_bw is not None and cx_bw is not None:
+                hidden_bw = hx_bw, cx_bw
+        if hx_fw is None and cx_fw is None:
+            hidden_fw = None
+        else:
+            hidden_fw = (
+                torch.jit._unwrap_optional(hx_fw),
+                torch.jit._unwrap_optional(cx_fw),
+            )
+        result_fw, hidden_fw = self.layer_fw(x, hidden_fw)
+
+        if hasattr(self, "layer_bw") and self.bidirectional:
+            x_reversed = x.flip(0)
+            result_bw, hidden_bw = self.layer_bw(x_reversed, hidden_bw)
+            result_bw = result_bw.flip(0)
+
+            result = torch.cat([result_fw, result_bw], result_fw.dim() - 1)
+            if hidden_fw is None and hidden_bw is None:
+                h = None
+                c = None
+            elif hidden_fw is None:
+                (h, c) = torch.jit._unwrap_optional(hidden_bw)
+            elif hidden_bw is None:
+                (h, c) = torch.jit._unwrap_optional(hidden_fw)
+            else:
+                h = torch.stack([hidden_fw[0], hidden_bw[0]], 0)  # type: ignore[list-item]
+                c = torch.stack([hidden_fw[1], hidden_bw[1]], 0)  # type: ignore[list-item]
+        else:
+            result = result_fw
+            h, c = torch.jit._unwrap_optional(hidden_fw)  # type: ignore[assignment]
+
+        if self.batch_first:
+            result.transpose_(0, 1)
+
+        return result, (h, c)
+
+    @classmethod
+    def from_float(cls, other, layer_idx=0, qconfig=None, **kwargs):
+        r"""
+        There is no FP equivalent of this class. This function is here just to
+        mimic the behavior of the `prepare` within the `torch.ao.quantization`
+        flow.
+        """
+        if not hasattr(other, "qconfig") and qconfig is None:
+            raise AssertionError("other must have qconfig or qconfig must be provided")
+
+        input_size = kwargs.get("input_size", other.input_size)
+        hidden_size = kwargs.get("hidden_size", other.hidden_size)
+        bias = kwargs.get("bias", other.bias)
+        batch_first = kwargs.get("batch_first", other.batch_first)
+        bidirectional = kwargs.get("bidirectional", other.bidirectional)
+        split_gates = kwargs.get("split_gates", False)
+
+        layer = cls(
+            # pyrefly: ignore [bad-argument-type]
+            input_size,
+            # pyrefly: ignore [bad-argument-type]
+            hidden_size,
+            # pyrefly: ignore [bad-argument-type]
+            bias,
+            # pyrefly: ignore [bad-argument-type]
+            batch_first,
+            # pyrefly: ignore [bad-argument-type]
+            bidirectional,
+            split_gates=split_gates,
+        )
+        # pyrefly: ignore [bad-argument-type]
+        layer.qconfig = getattr(other, "qconfig", qconfig)
+        wi = getattr(other, f"weight_ih_l{layer_idx}")
+        wh = getattr(other, f"weight_hh_l{layer_idx}")
+        bi = getattr(other, f"bias_ih_l{layer_idx}", None)
+        bh = getattr(other, f"bias_hh_l{layer_idx}", None)
+
+        layer.layer_fw = _LSTMSingleLayer.from_params(
+            wi, wh, bi, bh, split_gates=split_gates
+        )
+
+        if other.bidirectional:
+            wi = getattr(other, f"weight_ih_l{layer_idx}_reverse")
+            wh = getattr(other, f"weight_hh_l{layer_idx}_reverse")
+            bi = getattr(other, f"bias_ih_l{layer_idx}_reverse", None)
+            bh = getattr(other, f"bias_hh_l{layer_idx}_reverse", None)
+            layer.layer_bw = _LSTMSingleLayer.from_params(
+                wi, wh, bi, bh, split_gates=split_gates
+            )
+        return layer
+
+
+class LSTM(torch.nn.Module):
+    r"""A quantizable long short-term memory (LSTM).
+
+    For the description and the argument types, please, refer to :class:`~torch.nn.LSTM`
+
+    Attributes:
+        layers : instances of the `_LSTMLayer`
+
+    .. note::
+        To access the weights and biases, you need to access them per layer.
+        See examples below.
+
+    Examples::
+
+        >>> import torch.ao.nn.quantizable as nnqa
+        >>> rnn = nnqa.LSTM(10, 20, 2)
+        >>> input = torch.randn(5, 3, 10)
+        >>> h0 = torch.randn(2, 3, 20)
+        >>> c0 = torch.randn(2, 3, 20)
+        >>> output, (hn, cn) = rnn(input, (h0, c0))
+        >>> # To get the weights:
+        >>> # xdoctest: +SKIP
+        >>> print(rnn.layers[0].weight_ih)
+        tensor([[...]])
+        >>> print(rnn.layers[0].weight_hh)
+        AssertionError: There is no reverse path in the non-bidirectional layer
+    """
+
+    _FLOAT_MODULE = torch.nn.LSTM
+
+    def __init__(
+        self,
+        input_size: int,
+        hidden_size: int,
+        num_layers: int = 1,
+        bias: bool = True,
+        batch_first: bool = False,
+        dropout: float = 0.0,
+        bidirectional: bool = False,
+        device=None,
+        dtype=None,
+        *,
+        split_gates: bool = False,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__()
+        self.input_size = input_size
+        self.hidden_size = hidden_size
+        self.num_layers = num_layers
+        self.bias = bias
+        self.batch_first = batch_first
+        self.dropout = float(dropout)
+        self.bidirectional = bidirectional
+        self.training = False  # Default to eval mode. If we want to train, we will explicitly set to training.
+
+        if (
+            not isinstance(dropout, numbers.Number)
+            or not 0 <= dropout <= 1
+            or isinstance(dropout, bool)
+        ):
+            raise ValueError(
+                "dropout should be a number in range [0, 1] "
+                "representing the probability of an element being "
+                "zeroed"
+            )
+
+        if dropout > 0:
+            warnings.warn(
+                "dropout option for quantizable LSTM is ignored. "
+                "If you are training, please, use nn.LSTM version "
+                "followed by `prepare` step.",
+                stacklevel=2,
+            )
+            if num_layers == 1:
+                warnings.warn(
+                    "dropout option adds dropout after all but last "
+                    "recurrent layer, so non-zero dropout expects "
+                    f"num_layers greater than 1, but got dropout={dropout} "
+                    f"and num_layers={num_layers}",
+                    stacklevel=2,
+                )
+
+        layers = [
+            _LSTMLayer(
+                self.input_size,
+                self.hidden_size,
+                self.bias,
+                batch_first=False,
+                bidirectional=self.bidirectional,
+                split_gates=split_gates,
+                **factory_kwargs,
+            )
+        ]
+        layers.extend(
+            _LSTMLayer(
+                self.hidden_size,
+                self.hidden_size,
+                self.bias,
+                batch_first=False,
+                bidirectional=self.bidirectional,
+                split_gates=split_gates,
+                **factory_kwargs,
+            )
+            for _ in range(1, num_layers)
+        )
+        self.layers = torch.nn.ModuleList(layers)
+
+    def forward(self, x: Tensor, hidden: tuple[Tensor, Tensor] | None = None):
+        if self.batch_first:
+            x = x.transpose(0, 1)
+
+        max_batch_size = x.size(1)
+        num_directions = 2 if self.bidirectional else 1
+        if hidden is None:
+            zeros = torch.zeros(
+                num_directions,
+                max_batch_size,
+                self.hidden_size,
+                dtype=torch.float,
+                device=x.device,
+            )
+            zeros.squeeze_(0)
+            if x.is_quantized:
+                zeros = torch.quantize_per_tensor(
+                    zeros, scale=1.0, zero_point=0, dtype=x.dtype
+                )
+            hxcx = [(zeros, zeros) for _ in range(self.num_layers)]
+        else:
+            hidden_non_opt = torch.jit._unwrap_optional(hidden)
+            if isinstance(hidden_non_opt[0], Tensor):
+                hx = hidden_non_opt[0].reshape(
+                    self.num_layers, num_directions, max_batch_size, self.hidden_size
+                )
+                cx = hidden_non_opt[1].reshape(
+                    self.num_layers, num_directions, max_batch_size, self.hidden_size
+                )
+                hxcx = [
+                    (hx[idx].squeeze(0), cx[idx].squeeze(0))
+                    for idx in range(self.num_layers)
+                ]
+            else:
+                hxcx = hidden_non_opt
+
+        hx_list = []
+        cx_list = []
+        for idx, layer in enumerate(self.layers):
+            x, (h, c) = layer(x, hxcx[idx])
+            hx_list.append(torch.jit._unwrap_optional(h))
+            cx_list.append(torch.jit._unwrap_optional(c))
+        hx_tensor = torch.stack(hx_list)
+        cx_tensor = torch.stack(cx_list)
+
+        # We are creating another dimension for bidirectional case
+        # need to collapse it
+        hx_tensor = hx_tensor.reshape(-1, hx_tensor.shape[-2], hx_tensor.shape[-1])
+        cx_tensor = cx_tensor.reshape(-1, cx_tensor.shape[-2], cx_tensor.shape[-1])
+
+        if self.batch_first:
+            x = x.transpose(0, 1)
+
+        return x, (hx_tensor, cx_tensor)
+
+    def _get_name(self):
+        return "QuantizableLSTM"
+
+    @classmethod
+    def from_float(cls, other, qconfig=None, split_gates=False):
+        if not isinstance(other, cls._FLOAT_MODULE):
+            raise AssertionError(
+                f"Expected module type {cls._FLOAT_MODULE}, got {type(other)}"
+            )
+        if not hasattr(other, "qconfig") and not qconfig:
+            raise AssertionError("other must have qconfig or qconfig must be provided")
+        observed = cls(
+            other.input_size,
+            other.hidden_size,
+            other.num_layers,
+            other.bias,
+            other.batch_first,
+            other.dropout,
+            other.bidirectional,
+            split_gates=split_gates,
+        )
+        # pyrefly: ignore [bad-argument-type]
+        observed.qconfig = getattr(other, "qconfig", qconfig)
+        for idx in range(other.num_layers):
+            observed.layers[idx] = _LSTMLayer.from_float(
+                other, idx, qconfig, batch_first=False, split_gates=split_gates
+            )
+
+        # Prepare the model
+        if other.training:
+            observed.train()
+            observed = torch.ao.quantization.prepare_qat(observed, inplace=True)
+        else:
+            observed.eval()
+            observed = torch.ao.quantization.prepare(observed, inplace=True)
+        return observed
+
+    @classmethod
+    def from_observed(cls, other):
+        # The whole flow is float -> observed -> quantized
+        # This class does float -> observed only
+        raise NotImplementedError(
+            "It looks like you are trying to convert a "
+            "non-quantizable LSTM module. Please, see "
+            "the examples on quantizable LSTMs."
+        )
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..77e97d8595282f3d69963ee129fa473249e3ae29
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/__init__.py
@@ -0,0 +1,39 @@
+from . import functional
+from .modules import *  # noqa: F403
+from .modules import MaxPool2d
+
+
+__all__ = [
+    "BatchNorm2d",
+    "BatchNorm3d",
+    "Conv1d",
+    "Conv2d",
+    "Conv3d",
+    "ConvTranspose1d",
+    "ConvTranspose2d",
+    "ConvTranspose3d",
+    "DeQuantize",
+    "ELU",
+    "Embedding",
+    "EmbeddingBag",
+    "GroupNorm",
+    "Hardswish",
+    "InstanceNorm1d",
+    "InstanceNorm2d",
+    "InstanceNorm3d",
+    "LayerNorm",
+    "LeakyReLU",
+    "Linear",
+    "LSTM",
+    "MultiheadAttention",
+    "Quantize",
+    "ReLU6",
+    "Sigmoid",
+    "Softmax",
+    "Dropout",
+    "PReLU",
+    # Wrapper modules
+    "FloatFunctional",
+    "FXFloatFunctional",
+    "QFunctional",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3c6693c59db49bd6c376023a95de5b10ffefd46
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/__pycache__/functional.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/__pycache__/functional.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..24b7d1e2de604d098f3f4a6e2015aa26168b160e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/__pycache__/functional.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d79bdbfe83209f18b17cc8c7b245f322871d6c0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/__init__.py
@@ -0,0 +1 @@
+from .modules import *  # noqa: F403
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78178e4b78b6f66a778945e867dc9b32d944261e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..969fd6f121f5ddb72ed2e8e158e3ee7e990cfd0c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__init__.py
@@ -0,0 +1,26 @@
+from .conv import (
+    Conv1d,
+    Conv2d,
+    Conv3d,
+    ConvTranspose1d,
+    ConvTranspose2d,
+    ConvTranspose3d,
+)
+from .linear import Linear
+from .rnn import GRU, GRUCell, LSTM, LSTMCell, RNNCell
+
+
+__all__ = [
+    "Linear",
+    "LSTM",
+    "GRU",
+    "LSTMCell",
+    "RNNCell",
+    "GRUCell",
+    "Conv1d",
+    "Conv2d",
+    "Conv3d",
+    "ConvTranspose1d",
+    "ConvTranspose2d",
+    "ConvTranspose3d",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..868ec99df4c13ac7074fb288af80865d2c0a7291
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/conv.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/conv.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c00d6545a613b9a41193593eb0a10d08a209b314
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/conv.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/linear.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/linear.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a86e9cfd8f381d640fad1781b290b7f332e60cb
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/linear.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/rnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/rnn.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57930da703c6824135d00ef0f0432a90bd3ce976
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/rnn.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/conv.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/conv.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f63756d37b3109b1603e19e06a9973e0c2339d3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/conv.py
@@ -0,0 +1,531 @@
+# mypy: allow-untyped-defs
+r"""Dynamically quantized convolution modules."""
+
+import warnings
+from typing import ClassVar, Literal
+
+import torch
+import torch.ao.nn.quantized as nnq
+import torch.nn as nn
+import torch.nn.functional as F
+from torch import Tensor
+from torch._ops import ops
+from torch.ao.nn.quantized.modules.conv import _reverse_repeat_padding
+from torch.nn.common_types import _size_1_t
+from torch.nn.modules.utils import _pair, _single, _triple
+
+
+__all__ = [
+    "Conv1d",
+    "Conv2d",
+    "Conv3d",
+    "ConvTranspose1d",
+    "ConvTranspose2d",
+    "ConvTranspose3d",
+]
+
+
+class Conv1d(nnq.Conv1d):
+    r"""A dynamically quantized conv module with floating point tensors as inputs and outputs.
+
+    For details on input arguments, parameters, and implementation see
+    :class:`~torch.nn.Conv1d` and :class:`~torch.ao.nn.quantized.dynamic.Conv1d` and
+
+    Attributes:
+        weight (Tensor):     packed tensor derived from the learnable weight
+                             parameter.
+        scale (Tensor):      scalar for the output scale
+        zero_point (Tensor): scalar for the output zero point
+
+    See :class:`~torch.nn.Conv1d` for other attributes.
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> m = nn.quantized.dynamic.Conv1d(16, 33, 3, stride=2)
+        >>> input = torch.randn(20, 16, 100)
+        >>> output = m(input)
+
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
+    _NNIQAT_CONV_BN_MODULE: ClassVar[type[nn.Module] | None] = None
+    _NNI_CONV_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
+
+    def __init__(
+        self,
+        in_channels: int,
+        out_channels: int,
+        kernel_size: _size_1_t,
+        stride: _size_1_t = 1,
+        padding: _size_1_t = 0,
+        dilation: _size_1_t = 1,
+        groups: int = 1,
+        bias: bool = True,
+        padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
+        device=None,
+        dtype=None,
+        reduce_range=True,
+    ):
+        warnings.warn(
+            f"The current implementation of the {self._get_name()} module has poor numerical accuracy and its use is not recommended",
+            stacklevel=2,
+        )
+        factory_kwargs = {"device": device, "dtype": dtype}
+        kernel_size = _single(kernel_size)
+        stride = _single(stride)
+
+        padding = padding if isinstance(padding, str) else _single(padding)
+        dilation = _single(dilation)
+
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            groups,
+            bias,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _get_name(self):
+        return "DynamicQuantizedConv1d"
+
+    def forward(self, input: Tensor, reduce_range: bool = True) -> Tensor:
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 3:
+            raise ValueError("Input shape must be `(N, C, L)`!")
+        if self.padding_mode != "zeros":
+            # Padding in Conv1d is stored as (p, p), need to get (p,)
+            _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding[:1])
+            input = F.pad(
+                input, _reversed_padding_repeated_twice, mode=self.padding_mode
+            )
+        return ops.quantized.conv1d_dynamic(input, self._packed_params, reduce_range)
+
+
+class Conv2d(nnq.Conv2d):
+    r"""A dynamically quantized conv module with floating point tensors as inputs and outputs.
+
+    For details on input arguments, parameters, and implementation see
+    :class:`~torch.nn.Conv2d` and :class:`~torch.ao.nn.quantized.dynamic.Conv2d` and
+
+    Attributes:
+        weight (Tensor):     packed tensor derived from the learnable weight
+                             parameter.
+        scale (Tensor):      scalar for the output scale
+        zero_point (Tensor): scalar for the output zero point
+
+    See :class:`~torch.nn.Conv2d` for other attributes.
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> # With square kernels and equal stride
+        >>> m = nn.quantized.dynamic.Conv2d(16, 33, 3, stride=2)
+        >>> # non-square kernels and unequal stride and with padding
+        >>> m = nn.quantized.dynamic.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
+        >>> # non-square kernels and unequal stride and with padding and dilation
+        >>> m = nn.quantized.dynamic.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
+        >>> input = torch.randn(20, 16, 50, 100)
+        >>> output = m(input)
+
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
+    _NNIQAT_CONV_BN_MODULE: ClassVar[type[nn.Module] | None] = None
+    _NNI_CONV_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        warnings.warn(
+            f"The current implementation of the {self._get_name()} module "
+            "has poor numerical accuracy and its use is not recommended",
+            stacklevel=2,
+        )
+        factory_kwargs = {"device": device, "dtype": dtype}
+        kernel_size = _pair(kernel_size)
+        stride = _pair(stride)
+        padding = _pair(padding)
+        dilation = _pair(dilation)
+
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            groups,
+            bias,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _get_name(self):
+        return "DynamicQuantizedConv2d"
+
+    def forward(self, input: Tensor, reduce_range: bool = True) -> Tensor:
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 4:
+            raise ValueError("Input shape must be `(N, C, H, W)`!")
+        if self.padding_mode != "zeros":
+            _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
+            input = F.pad(
+                input, _reversed_padding_repeated_twice, mode=self.padding_mode
+            )
+        return ops.quantized.conv2d_dynamic(input, self._packed_params, reduce_range)
+
+
+class Conv3d(nnq.Conv3d):
+    r"""A dynamically quantized conv module with floating point tensors as inputs and outputs.
+
+    For details on input arguments, parameters, and implementation see
+    :class:`~torch.nn.Conv3d` and :class:`~torch.ao.nn.quantized.dynamic.Conv3d` and
+
+    Attributes:
+        weight (Tensor):     packed tensor derived from the learnable weight
+                             parameter.
+        scale (Tensor):      scalar for the output scale
+        zero_point (Tensor): scalar for the output zero point
+
+    See :class:`~torch.nn.Conv3d` for other attributes.
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> # With square kernels and equal stride
+        >>> m = nn.quantized.dynamic.Conv3d(16, 33, 3, stride=2)
+        >>> # non-square kernels and unequal stride and with padding
+        >>> m = nn.quantized.dynamic.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2))
+        >>> # non-square kernels and unequal stride and with padding and dilation
+        >>> m = nn.quantized.dynamic.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2), dilation=(1, 2, 2))
+        >>> input = torch.randn(20, 16, 56, 56, 56)
+        >>> output = m(input)
+
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
+    _NNIQAT_CONV_BN_MODULE: ClassVar[type[nn.Module] | None] = None
+    _NNI_CONV_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        warnings.warn(
+            f"The current implementation of the {self._get_name()} module has poor numerical accuracy and its use is not recommended",
+            stacklevel=2,
+        )
+        if padding_mode == "reflect":
+            raise AssertionError("Conv3d does not support reflection padding")
+        factory_kwargs = {"device": device, "dtype": dtype}
+        kernel_size = _triple(kernel_size)
+        stride = _triple(stride)
+        padding = _triple(padding)
+        dilation = _triple(dilation)
+        super()._init(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            False,
+            _triple(0),
+            groups,
+            bias,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _get_name(self):
+        return "DynamicQuantizedConv3d"
+
+    def forward(self, input: Tensor, reduce_range: bool = True) -> Tensor:
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 5:
+            raise ValueError("Input shape must be `(N, C, D, H, W)`!")
+        if self.padding_mode != "zeros":
+            _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
+            input = F.pad(
+                input, _reversed_padding_repeated_twice, mode=self.padding_mode
+            )
+        return ops.quantized.conv3d_dynamic(input, self._packed_params, reduce_range)
+
+
+class ConvTranspose1d(nnq.ConvTranspose1d):
+    r"""A dynamically quantized transposed convolution module with floating point tensors as inputs and outputs.
+
+    For details on input arguments, parameters, and implementation see
+    :class:`~torch.nn.ConvTranspose1d`.
+
+    For special notes, please, see :class:`~torch.ao.nn.quantized.dynamic.Conv1d`
+
+    Attributes:
+        weight (Tensor):     packed tensor derived from the learnable weight
+                             parameter.
+        scale (Tensor):      scalar for the output scale
+        zero_point (Tensor): scalar for the output zero point
+    See :class:`~torch.nn.ConvTranspose1d` for other attributes.
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> # With square kernels and equal stride
+        >>> m = nndq.ConvTranspose1d(16, 33, 3, stride=2)
+        >>> # non-square kernels and unequal stride and with padding
+        >>> m = nndq.ConvTranspose1d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
+        >>> output = m(input)
+        >>> # exact output size can be also specified as an argument
+        >>> downsample = nndq.Conv1d(16, 16, 3, stride=2, padding=1)
+        >>> upsample = nndq.ConvTranspose1d(16, 16, 3, stride=2, padding=1)
+        >>> h = downsample(input)
+        >>> h.size()
+        torch.Size([1, 16, 6])
+        >>> output = upsample(h, output_size=input.size())
+        >>> output.size()
+        torch.Size([1, 16, 12])
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.ConvTranspose1d]] = nn.ConvTranspose1d
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        output_padding=0,
+        groups=1,
+        bias=True,
+        dilation=1,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        warnings.warn(
+            f"The current implementation of the {self._get_name()} module has poor numerical accuracy and its use is not recommended",
+            stacklevel=2,
+        )
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            output_padding,
+            groups,
+            bias,
+            dilation,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _get_name(self):
+        return "DynamicQuantizedConvTranspose1d"
+
+    def forward(self, input: Tensor, reduce_range: bool = True) -> Tensor:
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 3:
+            raise ValueError("Input shape must be `(N, C, L)`!")
+        return torch.ops.quantized.conv_transpose1d_dynamic(
+            input, self._packed_params, reduce_range
+        )
+
+
+class ConvTranspose2d(nnq.ConvTranspose2d):
+    r"""A dynamically quantized transposed convolution module with floating point tensors as inputs and outputs.
+
+    For details on input arguments, parameters, and implementation see
+    :class:`~torch.nn.ConvTranspose2d`.
+
+    For special notes, please, see :class:`~torch.ao.nn.quantized.dynamic.Conv2d`
+
+    Attributes:
+        weight (Tensor):     packed tensor derived from the learnable weight
+                             parameter.
+        scale (Tensor):      scalar for the output scale
+        zero_point (Tensor): scalar for the output zero point
+    See :class:`~torch.nn.ConvTranspose2d` for other attributes.
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> # With square kernels and equal stride
+        >>> m = nnq.ConvTranspose2d(16, 33, 3, stride=2)
+        >>> # non-square kernels and unequal stride and with padding
+        >>> m = nnq.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
+        >>> output = m(input)
+        >>> # exact output size can be also specified as an argument
+        >>> downsample = nnq.Conv2d(16, 16, 3, stride=2, padding=1)
+        >>> upsample = nnq.ConvTranspose2d(16, 16, 3, stride=2, padding=1)
+        >>> h = downsample(input)
+        >>> h.size()
+        torch.Size([1, 16, 6, 6])
+        >>> output = upsample(h, output_size=input.size())
+        >>> output.size()
+        torch.Size([1, 16, 12, 12])
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.ConvTranspose2d]] = nn.ConvTranspose2d
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        output_padding=0,
+        groups=1,
+        bias=True,
+        dilation=1,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        warnings.warn(
+            f"The current implementation of the {self._get_name()} module has poor numerical accuracy and its use is not recommended",
+            stacklevel=2,
+        )
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            output_padding,
+            groups,
+            bias,
+            dilation,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _get_name(self):
+        return "DynamicQuantizedConvTranspose2d"
+
+    def forward(self, input: Tensor, reduce_range: bool = True) -> Tensor:
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 4:
+            raise ValueError("Input shape must be `(N, C, H, W)`!")
+        return ops.quantized.conv_transpose2d_dynamic(
+            input, self._packed_params, reduce_range
+        )
+
+
+class ConvTranspose3d(nnq.ConvTranspose3d):
+    r"""A dynamically quantized transposed convolution module with floating point tensors as inputs and outputs.
+
+    For details on input arguments, parameters, and implementation see
+    :class:`~torch.nn.ConvTranspose3d`.
+
+    For special notes, please, see :class:`~torch.ao.nn.quantized.dynamic.Conv3d`
+
+    Attributes:
+        weight (Tensor):     packed tensor derived from the learnable weight
+                             parameter.
+        scale (Tensor):      scalar for the output scale
+        zero_point (Tensor): scalar for the output zero point
+    See :class:`~torch.nn.ConvTranspose3d` for other attributes.
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> # With cubic kernels and equal stride
+        >>> m = nnq.ConvTranspose3d(16, 33, 3, stride=2)
+        >>> # non-cubic kernels and unequal stride and with padding
+        >>> m = nnq.ConvTranspose3d(16, 33, (3, 3, 5), stride=(2, 1, 1), padding=(4, 2, 2))
+        >>> output = m(input)
+        >>> # exact output size can be also specified as an argument
+        >>> downsample = nnq.Conv3d(16, 16, 3, stride=2, padding=1)
+        >>> upsample = nnq.ConvTranspose3d(16, 16, 3, stride=2, padding=1)
+        >>> h = downsample(input)
+        >>> h.size()
+        torch.Size([1, 16, 6, 6, 6])
+        >>> output = upsample(h, output_size=input.size())
+        >>> output.size()
+        torch.Size([1, 16, 12, 12, 12])
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.ConvTranspose3d]] = nn.ConvTranspose3d
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        output_padding=0,
+        groups=1,
+        bias=True,
+        dilation=1,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        warnings.warn(
+            f"The current implementation of the {self._get_name()} module has poor numerical accuracy and its use is not recommended",
+            stacklevel=2,
+        )
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            output_padding,
+            groups,
+            bias,
+            dilation,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _get_name(self):
+        return "DynamicQuantizedConvTranspose3d"
+
+    def forward(self, input: Tensor, reduce_range: bool = True) -> Tensor:
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 5:
+            raise ValueError("Input shape must be `(N, C, T, H, W)`!")
+        return ops.quantized.conv_transpose3d_dynamic(
+            input, self._packed_params, reduce_range
+        )
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/linear.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..402fa093f40148b8bdcea34be43d4734e25a3364
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/linear.py
@@ -0,0 +1,170 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.ao.nn.intrinsic as nni
+import torch.ao.nn.quantized as nnq
+from torch.ao.nn.quantized.modules.utils import _quantize_weight
+
+
+__all__ = [
+    "Linear",
+]
+
+
+class Linear(nnq.Linear):
+    r"""
+    A dynamic quantized linear module with floating point tensor as inputs and outputs.
+    We adopt the same interface as `torch.nn.Linear`, please see
+    https://pytorch.org/docs/stable/nn.html#torch.nn.Linear for documentation.
+
+    Similar to :class:`torch.nn.Linear`, attributes will be randomly
+    initialized at module creation time and will be overwritten later
+
+    Attributes:
+        weight (Tensor): the non-learnable quantized weights of the module which are of
+                         shape :math:`(\text{out\_features}, \text{in\_features})`.
+        bias (Tensor): the non-learnable floating point bias of the module of shape
+                       :math:`(\text{out\_features})`. If :attr:`bias` is ``True``,
+                       the values are initialized to zero.
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> m = nn.quantized.dynamic.Linear(20, 30)
+        >>> input = torch.randn(128, 20)
+        >>> output = m(input)
+        >>> print(output.size())
+        torch.Size([128, 30])
+    """
+
+    # version used in this class is different from the parent class nnq.Linear
+    _version = 4
+
+    def __init__(self, in_features, out_features, bias_=True, dtype=torch.qint8):
+        super().__init__(in_features, out_features, bias_, dtype=dtype)
+        # We don't muck around with buffers or attributes or anything here
+        # to keep the module simple. *everything* is simply a Python attribute.
+        # Serialization logic is explicitly handled in the below serialization and
+        # deserialization modules
+        self.version = 4
+
+    def forward(self, x):
+        # Note that we can handle self.bias == None case.
+        if self._packed_params.dtype == torch.qint8:
+            if self.version is None or self.version < 4:
+                Y = torch.ops.quantized.linear_dynamic(
+                    x, self._packed_params._packed_params
+                )
+            else:
+                Y = torch.ops.quantized.linear_dynamic(
+                    x, self._packed_params._packed_params, reduce_range=True
+                )
+        elif self._packed_params.dtype == torch.float16:
+            Y = torch.ops.quantized.linear_dynamic_fp16(
+                x, self._packed_params._packed_params
+            )
+        else:
+            raise RuntimeError("Unsupported dtype on dynamic quantized linear!")
+        return Y.to(x.dtype)
+
+    def _get_name(self):
+        return "DynamicQuantizedLinear"
+
+    def extra_repr(self):
+        extra_repr_str = f"in_features={self.in_features}, out_features={self.out_features}, dtype={self._packed_params.dtype}"
+        if self._packed_params.dtype == torch.qint8:
+            extra_repr_str += f", qscheme={self.weight().qscheme()}"
+        return extra_repr_str
+
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        version = local_metadata.get("version", None)
+        self.version = version
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Create a dynamic quantized module from a float module or qparams_dict
+
+        Args:
+            mod (Module): a float module, either produced by torch.ao.quantization
+                          utilities or provided by the user
+        """
+        float_modules = [
+            torch.nn.Linear,
+            torch.nn.modules.linear.NonDynamicallyQuantizableLinear,
+            torch.ao.nn.intrinsic.modules.fused.LinearReLU,
+            torch.ao.nn.qat.dynamic.Linear,
+        ]
+
+        if type(mod) not in float_modules:
+            raise AssertionError(
+                "nn.quantized.dynamic.Linear.from_float only works for one of"
+                + str([float_mod.__name__ for float_mod in float_modules])
+                + f", got {type(mod)}"
+            )
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+        if type(mod) is nni.LinearReLU:
+            mod = mod[0]
+
+        if mod.qconfig is not None and mod.qconfig.weight is not None:
+            weight_observer = mod.qconfig.weight()
+        else:
+            # We have the circular import issues if we import the qconfig in the beginning of this file:
+            # https://github.com/pytorch/pytorch/pull/24231. The current workaround is to postpone the
+            # import until we need it.
+            from torch.ao.quantization.qconfig import default_dynamic_qconfig
+
+            weight_observer = default_dynamic_qconfig.weight()
+        dtype = weight_observer.dtype
+        if dtype not in [torch.qint8, torch.float16]:
+            raise AssertionError(
+                f"The only supported dtypes for dynamic quantized linear are qint8 and float16, got: {dtype}"
+            )
+        weight_observer(mod.weight)
+        if dtype == torch.qint8:
+            qweight = _quantize_weight(mod.weight.float(), weight_observer)
+        elif dtype == torch.float16:
+            qweight = mod.weight.float()
+        else:
+            raise RuntimeError(
+                "Unsupported dtype specified for dynamic quantized Linear!"
+            )
+        qlinear = cls(mod.in_features, mod.out_features, dtype=dtype)
+
+        qlinear.set_weight_bias(qweight, mod.bias)
+        return qlinear
+
+    @classmethod
+    def from_reference(cls, ref_qlinear):  # type: ignore[override]
+        """Create a (fbgemm/qnnpack) dynamic quantized module from a reference quantized
+        module
+        Args:
+            ref_qlinear (Module): a reference quantized  module, either produced by
+            torch.ao.quantization functions or provided by the user
+        """
+        qlinear = cls(
+            ref_qlinear.in_features,
+            ref_qlinear.out_features,
+            dtype=ref_qlinear.weight_dtype,
+        )
+        qweight = ref_qlinear.get_quantized_weight()
+        bias = ref_qlinear.bias
+        qlinear.set_weight_bias(qweight, bias)
+        return qlinear
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/rnn.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/rnn.py
new file mode 100644
index 0000000000000000000000000000000000000000..29cca89663a6b67d168dd3f7c629169a38ad219e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/rnn.py
@@ -0,0 +1,1375 @@
+# mypy: allow-untyped-defs
+import numbers
+import warnings
+from typing_extensions import deprecated
+
+import torch
+import torch.nn as nn
+from torch import Tensor
+from torch._jit_internal import Dict, List, Optional, Tuple, Union  # noqa: F401
+from torch.ao.nn.quantized.modules.utils import _quantize_weight
+from torch.nn.utils.rnn import PackedSequence
+
+
+__all__ = [
+    "pack_weight_bias",
+    "PackedParameter",
+    "RNNBase",
+    "LSTM",
+    "GRU",
+    "RNNCellBase",
+    "RNNCell",
+    "LSTMCell",
+    "GRUCell",
+    "apply_permutation",
+]
+
+
+def _apply_permutation(tensor: Tensor, permutation: Tensor, dim: int = 1) -> Tensor:
+    return tensor.index_select(dim, permutation)
+
+
+@deprecated(
+    "`apply_permutation` is deprecated, please use `tensor.index_select(dim, permutation)` instead",
+    category=FutureWarning,
+)
+def apply_permutation(tensor: Tensor, permutation: Tensor, dim: int = 1) -> Tensor:
+    return _apply_permutation(tensor, permutation, dim)
+
+
+def pack_weight_bias(qweight, bias, dtype):
+    if dtype == torch.qint8:
+        # for each layer, for each direction we need to quantize and pack
+        # weights and pack parameters in this order:
+        #
+        #   w_ih, w_hh
+        packed_weight = torch.ops.quantized.linear_prepack(qweight, bias)
+
+        return packed_weight
+    else:
+        # for each layer, for each direction we need to quantize and pack
+        # weights and pack parameters in this order:
+        #
+        #   packed_ih, packed_hh, b_ih, b_hh
+        packed_weight = torch.ops.quantized.linear_prepack_fp16(qweight, bias)
+
+        return packed_weight
+
+
+class PackedParameter(torch.nn.Module):
+    def __init__(self, param):
+        super().__init__()
+        self.param = param
+
+    def _save_to_state_dict(self, destination, prefix, keep_vars):
+        super()._save_to_state_dict(destination, prefix, keep_vars)
+        destination[prefix + "param"] = self.param
+
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        self.param = state_dict[prefix + "param"]
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+
+class RNNBase(torch.nn.Module):
+    _FLOAT_MODULE = nn.RNNBase
+
+    _version = 2
+
+    def __init__(
+        self,
+        mode,
+        input_size,
+        hidden_size,
+        num_layers=1,
+        bias=True,
+        batch_first=False,
+        dropout=0.0,
+        bidirectional=False,
+        dtype=torch.qint8,
+    ):
+        super().__init__()
+
+        self.mode = mode
+        self.input_size = input_size
+        self.hidden_size = hidden_size
+        self.num_layers = num_layers
+        self.bias = bias
+        self.batch_first = batch_first
+        self.dropout = float(dropout)
+        self.bidirectional = bidirectional
+        self.dtype = dtype
+        self.version = 2
+        self.training = False
+        num_directions = 2 if bidirectional else 1
+
+        # "type: ignore" is required since ints and Numbers are not fully comparable
+        # https://github.com/python/mypy/issues/8566
+        if (
+            not isinstance(dropout, numbers.Number)
+            or not 0 <= dropout <= 1  # type: ignore[operator]
+            or isinstance(dropout, bool)
+        ):
+            raise ValueError(
+                "dropout should be a number in range [0, 1] "
+                "representing the probability of an element being "
+                "zeroed"
+            )
+        if dropout > 0 and num_layers == 1:  # type: ignore[operator]
+            warnings.warn(
+                "dropout option adds dropout after all but last "
+                "recurrent layer, so non-zero dropout expects "
+                f"num_layers greater than 1, but got dropout={dropout} and "
+                f"num_layers={num_layers}",
+                stacklevel=2,
+            )
+
+        if mode == "LSTM":
+            gate_size = 4 * hidden_size
+        elif mode == "GRU":
+            gate_size = 3 * hidden_size
+        else:
+            raise ValueError("Unrecognized RNN mode: " + mode)
+
+        _all_weight_values = []
+        for layer in range(num_layers):
+            for _ in range(num_directions):
+                layer_input_size = (
+                    input_size if layer == 0 else hidden_size * num_directions
+                )
+
+                w_ih = torch.randn(gate_size, layer_input_size).to(torch.float)
+                w_hh = torch.randn(gate_size, hidden_size).to(torch.float)
+                b_ih = torch.randn(gate_size).to(torch.float)
+                b_hh = torch.randn(gate_size).to(torch.float)
+                if dtype == torch.qint8:
+                    w_ih = torch.quantize_per_tensor(
+                        w_ih, scale=0.1, zero_point=0, dtype=torch.qint8
+                    )
+                    w_hh = torch.quantize_per_tensor(
+                        w_hh, scale=0.1, zero_point=0, dtype=torch.qint8
+                    )
+                    packed_ih = torch.ops.quantized.linear_prepack(w_ih, b_ih)
+                    packed_hh = torch.ops.quantized.linear_prepack(w_hh, b_hh)
+                    # pyrefly: ignore [unnecessary-comparison]
+                    if self.version is None or self.version < 2:
+                        cell_params = (
+                            torch.ops.quantized.make_quantized_cell_params_dynamic(
+                                packed_ih, packed_hh, b_ih, b_hh
+                            )
+                        )
+                    else:
+                        cell_params = (
+                            torch.ops.quantized.make_quantized_cell_params_dynamic(
+                                packed_ih, packed_hh, b_ih, b_hh, True
+                            )
+                        )
+                else:
+                    packed_ih = torch.ops.quantized.linear_prepack_fp16(w_ih, b_ih)
+                    packed_hh = torch.ops.quantized.linear_prepack_fp16(w_hh, b_hh)
+                    cell_params = torch.ops.quantized.make_quantized_cell_params_fp16(
+                        packed_ih, packed_hh
+                    )
+
+                _all_weight_values.append(PackedParameter(cell_params))
+        self._all_weight_values = torch.nn.ModuleList(_all_weight_values)
+
+    def _get_name(self):
+        return "DynamicQuantizedRNN"
+
+    def extra_repr(self):
+        s = "{input_size}, {hidden_size}"
+        if self.num_layers != 1:
+            s += ", num_layers={num_layers}"
+        if self.bias is not True:
+            s += ", bias={bias}"
+        if self.batch_first is not False:
+            s += ", batch_first={batch_first}"
+        if self.dropout != 0:
+            s += ", dropout={dropout}"
+        if self.bidirectional is not False:
+            s += ", bidirectional={bidirectional}"
+        return s.format(**self.__dict__)
+
+    def __repr__(self):
+        # We don't want to show `ModuleList` children, hence custom
+        # `__repr__`. This is the same as nn.Module.__repr__, except the check
+        # for the `PackedParameter` and `nn.ModuleList`.
+        # You should still override `extra_repr` to add more info.
+        extra_lines = []
+        extra_repr = self.extra_repr()
+        # empty string will be split into list ['']
+        if extra_repr:
+            extra_lines = extra_repr.split("\n")
+        child_lines = []
+        for key, module in self._modules.items():
+            if isinstance(module, (PackedParameter, nn.ModuleList)):
+                continue
+            mod_str = repr(module)
+            mod_str = nn.modules.module._addindent(mod_str, 2)
+            child_lines.append("(" + key + "): " + mod_str)
+        lines = extra_lines + child_lines
+
+        main_str = self._get_name() + "("
+        if lines:
+            # simple one-liner info, which most builtin Modules will use
+            if len(extra_lines) == 1 and not child_lines:
+                main_str += extra_lines[0]
+            else:
+                main_str += "\n  " + "\n  ".join(lines) + "\n"
+
+        main_str += ")"
+        return main_str
+
+    def check_input(self, input: Tensor, batch_sizes: Optional[Tensor]) -> None:
+        expected_input_dim = 2 if batch_sizes is not None else 3
+        if input.dim() != expected_input_dim:
+            raise RuntimeError(
+                f"input must have {expected_input_dim} dimensions, got {input.dim()}"
+            )
+        if self.input_size != input.size(-1):
+            raise RuntimeError(
+                f"input.size(-1) must be equal to input_size. Expected {self.input_size}, got {input.size(-1)}"
+            )
+
+    def get_expected_hidden_size(
+        self, input: Tensor, batch_sizes: Optional[Tensor]
+    ) -> tuple[int, int, int]:
+        if batch_sizes is not None:
+            mini_batch = int(batch_sizes[0])
+        else:
+            mini_batch = input.size(0) if self.batch_first else input.size(1)
+        num_directions = 2 if self.bidirectional else 1
+        expected_hidden_size = (
+            self.num_layers * num_directions,
+            mini_batch,
+            self.hidden_size,
+        )
+        return expected_hidden_size
+
+    def check_hidden_size(
+        self,
+        hx: Tensor,
+        expected_hidden_size: tuple[int, int, int],
+        msg: str = "Expected hidden size {}, got {}",
+    ) -> None:
+        if hx.size() != expected_hidden_size:
+            raise RuntimeError(msg.format(expected_hidden_size, list(hx.size())))
+
+    def check_forward_args(
+        self, input: Tensor, hidden: Tensor, batch_sizes: Optional[Tensor]
+    ) -> None:
+        self.check_input(input, batch_sizes)
+        expected_hidden_size = self.get_expected_hidden_size(input, batch_sizes)
+        self.check_hidden_size(
+            hidden, expected_hidden_size, msg="Expected hidden size {}, got {}"
+        )
+
+    def permute_hidden(self, hx: Tensor, permutation: Optional[Tensor]) -> Tensor:
+        if permutation is None:
+            return hx
+        return _apply_permutation(hx, permutation)
+
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        version = local_metadata.get("version", None)
+        self.version = version
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+    def set_weight_bias(self, weight_bias_dict):
+        def weight_bias_name(ihhh, layer, suffix):
+            weight_name = f"weight_{ihhh}_l{layer}{suffix}"
+            bias_name = f"bias_{ihhh}_l{layer}{suffix}"
+            return weight_name, bias_name
+
+        num_directions = 2 if self.bidirectional else 1
+        # TODO: dedup with __init__ of RNNBase
+        _all_weight_values = []
+        for layer in range(self.num_layers):
+            for direction in range(num_directions):
+                suffix = "_reverse" if direction == 1 else ""
+                w_ih_name, b_ih_name = weight_bias_name("ih", layer, suffix)
+                w_hh_name, b_hh_name = weight_bias_name("hh", layer, suffix)
+                w_ih = weight_bias_dict[w_ih_name]
+                b_ih = weight_bias_dict[b_ih_name]
+                w_hh = weight_bias_dict[w_hh_name]
+                b_hh = weight_bias_dict[b_hh_name]
+                if w_ih.dtype == torch.qint8:
+                    packed_ih = torch.ops.quantized.linear_prepack(w_ih, b_ih)
+                    packed_hh = torch.ops.quantized.linear_prepack(w_hh, b_hh)
+                    if self.version is None or self.version < 2:
+                        cell_params = (
+                            torch.ops.quantized.make_quantized_cell_params_dynamic(
+                                packed_ih, packed_hh, b_ih, b_hh
+                            )
+                        )
+                    else:
+                        cell_params = (
+                            torch.ops.quantized.make_quantized_cell_params_dynamic(
+                                packed_ih, packed_hh, b_ih, b_hh, True
+                            )
+                        )
+                else:
+                    packed_ih = torch.ops.quantized.linear_prepack_fp16(w_ih, b_ih)
+                    packed_hh = torch.ops.quantized.linear_prepack_fp16(w_hh, b_hh)
+                    cell_params = torch.ops.quantized.make_quantized_cell_params_fp16(
+                        packed_ih, packed_hh
+                    )
+
+                _all_weight_values.append(PackedParameter(cell_params))
+        self._all_weight_values = torch.nn.ModuleList(_all_weight_values)
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        if type(mod) not in {torch.nn.LSTM, torch.nn.GRU}:
+            raise AssertionError(
+                "nn.quantized.dynamic.RNNBase.from_float only works for nn.LSTM and nn.GRU"
+            )
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+
+        if mod.qconfig is not None and mod.qconfig.weight is not None:
+            weight_observer_method = mod.qconfig.weight
+        else:
+            # We have the circular import issues if we import the qconfig in the beginning of this file:
+            # https://github.com/pytorch/pytorch/pull/24231. The current workaround is to postpone the
+            # import until we need it.
+            from torch.ao.quantization.qconfig import default_dynamic_qconfig
+
+            weight_observer_method = default_dynamic_qconfig.weight
+
+        dtype = weight_observer_method().dtype
+        supported_scalar_types = [torch.qint8, torch.float16]
+        if dtype not in supported_scalar_types:
+            raise RuntimeError(
+                f"Unsupported dtype for dynamic RNN quantization: {dtype}"
+            )
+        # RNNBase can be either LSTM or GRU
+        qRNNBase: Union[LSTM, GRU]
+        if mod.mode == "LSTM":
+            qRNNBase = LSTM(
+                mod.input_size,
+                mod.hidden_size,
+                mod.num_layers,
+                mod.bias,
+                mod.batch_first,
+                mod.dropout,
+                mod.bidirectional,
+                dtype,
+            )
+        elif mod.mode == "GRU":
+            qRNNBase = GRU(
+                mod.input_size,
+                mod.hidden_size,
+                mod.num_layers,
+                mod.bias,
+                mod.batch_first,
+                mod.dropout,
+                mod.bidirectional,
+                dtype,
+            )
+        else:
+            raise NotImplementedError(
+                "Only LSTM/GRU is supported for QuantizedRNN for now"
+            )
+
+        num_directions = 2 if mod.bidirectional else 1
+
+        if not mod.bias:
+            raise AssertionError("mod.bias must be True")
+
+        _all_weight_values = []
+        for layer in range(qRNNBase.num_layers):
+            for direction in range(num_directions):
+                suffix = "_reverse" if direction == 1 else ""
+
+                def retrieve_weight_bias(ihhh):
+                    weight_name = f"weight_{ihhh}_l{layer}{suffix}"
+                    bias_name = f"bias_{ihhh}_l{layer}{suffix}"
+                    weight = getattr(mod, weight_name)
+                    bias = getattr(mod, bias_name)
+                    return weight, bias
+
+                weight_ih, bias_ih = retrieve_weight_bias("ih")
+                weight_hh, bias_hh = retrieve_weight_bias("hh")
+
+                if dtype == torch.qint8:
+
+                    def quantize_and_pack(w, b):
+                        weight_observer = weight_observer_method()
+                        weight_observer(w)
+                        qweight = _quantize_weight(w.float(), weight_observer)
+                        packed_weight = torch.ops.quantized.linear_prepack(qweight, b)
+                        return packed_weight
+
+                    packed_ih = quantize_and_pack(weight_ih, bias_ih)
+                    packed_hh = quantize_and_pack(weight_hh, bias_hh)
+                    if qRNNBase.version is None or qRNNBase.version < 2:
+                        cell_params = (
+                            torch.ops.quantized.make_quantized_cell_params_dynamic(
+                                packed_ih, packed_hh, bias_ih, bias_hh
+                            )
+                        )
+                    else:
+                        cell_params = (
+                            torch.ops.quantized.make_quantized_cell_params_dynamic(
+                                packed_ih, packed_hh, bias_ih, bias_hh, True
+                            )
+                        )
+
+                elif dtype == torch.float16:
+                    packed_ih = torch.ops.quantized.linear_prepack_fp16(
+                        weight_ih.float(), bias_ih
+                    )
+                    packed_hh = torch.ops.quantized.linear_prepack_fp16(
+                        weight_hh.float(), bias_hh
+                    )
+
+                    cell_params = torch.ops.quantized.make_quantized_cell_params_fp16(
+                        packed_ih, packed_hh
+                    )
+                else:
+                    raise RuntimeError(
+                        "Unsupported dtype specified for dynamic quantized LSTM!"
+                    )
+
+                _all_weight_values.append(PackedParameter(cell_params))
+        qRNNBase._all_weight_values = torch.nn.ModuleList(_all_weight_values)
+
+        return qRNNBase
+
+    def _weight_bias(self):
+        # Returns a dict of weights and biases
+        weight_bias_dict: Dict[str, Dict] = {"weight": {}, "bias": {}}
+        count = 0
+        num_directions = 2 if self.bidirectional else 1
+        for layer in range(self.num_layers):
+            for direction in range(num_directions):
+                suffix = "_reverse" if direction == 1 else ""
+                key_name1 = f"weight_ih_l{layer}{suffix}"
+                key_name2 = f"weight_hh_l{layer}{suffix}"
+                # packed weights are part of torchbind class, CellParamsSerializationType
+                # Within the packed weight class, the weight and bias are accessible as Tensors
+                packed_weight_bias = self._all_weight_values[  # type: ignore[index]
+                    count
+                ].param.__getstate__()[0][4]
+                weight_bias_dict["weight"][key_name1] = packed_weight_bias[
+                    0
+                ].__getstate__()[0][0]
+                weight_bias_dict["weight"][key_name2] = packed_weight_bias[
+                    1
+                ].__getstate__()[0][0]
+                key_name1 = f"bias_ih_l{layer}{suffix}"
+                key_name2 = f"bias_hh_l{layer}{suffix}"
+                weight_bias_dict["bias"][key_name1] = packed_weight_bias[
+                    0
+                ].__getstate__()[0][1]
+                weight_bias_dict["bias"][key_name2] = packed_weight_bias[
+                    1
+                ].__getstate__()[0][1]
+                count = count + 1
+        return weight_bias_dict
+
+    def get_weight(self):
+        return self._weight_bias()["weight"]
+
+    def get_bias(self):
+        return self._weight_bias()["bias"]
+
+
+class LSTM(RNNBase):
+    r"""
+    A dynamic quantized LSTM module with floating point tensor as inputs and outputs.
+    We adopt the same interface as `torch.nn.LSTM`, please see
+    https://pytorch.org/docs/stable/nn.html#torch.nn.LSTM for documentation.
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> rnn = nn.LSTM(10, 20, 2)
+        >>> input = torch.randn(5, 3, 10)
+        >>> h0 = torch.randn(2, 3, 20)
+        >>> c0 = torch.randn(2, 3, 20)
+        >>> output, (hn, cn) = rnn(input, (h0, c0))
+    """
+
+    _FLOAT_MODULE = nn.LSTM
+
+    __overloads__ = {"forward": ["forward_packed", "forward_tensor"]}
+
+    def __init__(self, *args, **kwargs):
+        super().__init__("LSTM", *args, **kwargs)
+
+    def _get_name(self):
+        return "DynamicQuantizedLSTM"
+
+    def forward_impl(
+        self,
+        input: Tensor,
+        hx: Optional[tuple[Tensor, Tensor]],
+        batch_sizes: Optional[Tensor],
+        max_batch_size: int,
+        sorted_indices: Optional[Tensor],
+    ) -> tuple[Tensor, tuple[Tensor, Tensor]]:
+        if hx is None:
+            num_directions = 2 if self.bidirectional else 1
+            zeros = torch.zeros(
+                self.num_layers * num_directions,
+                max_batch_size,
+                self.hidden_size,
+                dtype=input.dtype,
+                device=input.device,
+            )
+            hx = (zeros, zeros)
+        else:
+            # Each batch of the hidden state should match the input sequence that
+            # the user believes he/she is passing in.
+            hx = self.permute_hidden(hx, sorted_indices)
+
+        self.check_forward_args(input, hx, batch_sizes)
+
+        _all_params = [m.param for m in self._all_weight_values]
+        if batch_sizes is None:
+            result = torch.quantized_lstm(
+                input,
+                hx,
+                _all_params,
+                self.bias,
+                self.num_layers,
+                float(self.dropout),
+                self.training,
+                self.bidirectional,
+                self.batch_first,
+                dtype=self.dtype,
+                use_dynamic=True,
+            )
+        else:
+            result = torch.quantized_lstm(
+                input,
+                batch_sizes,
+                hx,
+                _all_params,
+                self.bias,
+                self.num_layers,
+                float(self.dropout),
+                self.training,
+                self.bidirectional,
+                dtype=self.dtype,
+                use_dynamic=True,
+            )
+        output = result[0]
+        hidden = result[1:]
+
+        return output, hidden
+
+    @torch.jit.export
+    def forward_tensor(
+        self, input: Tensor, hx: Optional[tuple[Tensor, Tensor]] = None
+    ) -> tuple[Tensor, tuple[Tensor, Tensor]]:
+        batch_sizes = None
+        max_batch_size = input.size(0) if self.batch_first else input.size(1)
+        sorted_indices = None
+        unsorted_indices = None
+
+        output, hidden = self.forward_impl(
+            input, hx, batch_sizes, max_batch_size, sorted_indices
+        )
+
+        return output, self.permute_hidden(hidden, unsorted_indices)
+
+    @torch.jit.export
+    def forward_packed(
+        self, input: PackedSequence, hx: Optional[tuple[Tensor, Tensor]] = None
+    ) -> tuple[PackedSequence, tuple[Tensor, Tensor]]:
+        input_, batch_sizes, sorted_indices, unsorted_indices = input
+        max_batch_size = int(batch_sizes[0])
+
+        output_, hidden = self.forward_impl(
+            input_, hx, batch_sizes, max_batch_size, sorted_indices
+        )
+
+        output = PackedSequence(output_, batch_sizes, sorted_indices, unsorted_indices)
+        return output, self.permute_hidden(hidden, unsorted_indices)
+
+    # "type: ignore" is required due to issue #43072
+    def permute_hidden(  # type: ignore[override]
+        self,
+        hx: tuple[Tensor, Tensor],
+        permutation: Optional[Tensor],
+    ) -> tuple[Tensor, Tensor]:
+        if permutation is None:
+            return hx
+        return _apply_permutation(hx[0], permutation), _apply_permutation(
+            hx[1], permutation
+        )
+
+    # "type: ignore" is required due to issue #43072
+    def check_forward_args(  # type: ignore[override]
+        self,
+        input: Tensor,
+        hidden: tuple[Tensor, Tensor],
+        batch_sizes: Optional[Tensor],
+    ) -> None:
+        self.check_input(input, batch_sizes)
+        expected_hidden_size = self.get_expected_hidden_size(input, batch_sizes)
+
+        self.check_hidden_size(
+            hidden[0], expected_hidden_size, "Expected hidden[0] size {}, got {}"
+        )
+        self.check_hidden_size(
+            hidden[1], expected_hidden_size, "Expected hidden[1] size {}, got {}"
+        )
+
+    @torch.jit.ignore
+    def forward(self, input, hx=None):
+        if isinstance(input, PackedSequence):
+            return self.forward_packed(input, hx)
+        else:
+            return self.forward_tensor(input, hx)
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+    @classmethod
+    def from_reference(cls, ref_mod):
+        if not hasattr(ref_mod, "weight_ih_l0_dtype"):
+            raise AssertionError(
+                "We are assuming weight_ih_l0 exists in LSTM, "
+                "may need to relax the assumption to support the use case"
+            )
+        qmod = cls(
+            ref_mod.input_size,
+            ref_mod.hidden_size,
+            ref_mod.num_layers,
+            ref_mod.bias,
+            ref_mod.batch_first,
+            ref_mod.dropout,
+            ref_mod.bidirectional,
+            # assuming there is layer 0, which should be OK
+            ref_mod.weight_ih_l0_dtype,
+        )
+        qmod.set_weight_bias(ref_mod.get_quantized_weight_bias_dict())
+        return qmod
+
+
+class GRU(RNNBase):
+    r"""Applies a multi-layer gated recurrent unit (GRU) RNN to an input sequence.
+
+
+    For each element in the input sequence, each layer computes the following
+    function:
+
+    .. math::
+        \begin{array}{ll}
+            r_t = \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\
+            z_t = \sigma(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\
+            n_t = \tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{(t-1)}+ b_{hn})) \\
+            h_t = (1 - z_t) \odot n_t + z_t \odot h_{(t-1)}
+        \end{array}
+
+    where :math:`h_t` is the hidden state at time `t`, :math:`x_t` is the input
+    at time `t`, :math:`h_{(t-1)}` is the hidden state of the layer
+    at time `t-1` or the initial hidden state at time `0`, and :math:`r_t`,
+    :math:`z_t`, :math:`n_t` are the reset, update, and new gates, respectively.
+    :math:`\sigma` is the sigmoid function, and :math:`\odot` is the Hadamard product.
+
+    In a multilayer GRU, the input :math:`x^{(l)}_t` of the :math:`l` -th layer
+    (:math:`l >= 2`) is the hidden state :math:`h^{(l-1)}_t` of the previous layer multiplied by
+    dropout :math:`\delta^{(l-1)}_t` where each :math:`\delta^{(l-1)}_t` is a Bernoulli random
+    variable which is :math:`0` with probability :attr:`dropout`.
+
+    Args:
+        input_size: The number of expected features in the input `x`
+        hidden_size: The number of features in the hidden state `h`
+        num_layers: Number of recurrent layers. E.g., setting ``num_layers=2``
+            would mean stacking two GRUs together to form a `stacked GRU`,
+            with the second GRU taking in outputs of the first GRU and
+            computing the final results. Default: 1
+        bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`.
+            Default: ``True``
+        batch_first: If ``True``, then the input and output tensors are provided
+            as (batch, seq, feature). Default: ``False``
+        dropout: If non-zero, introduces a `Dropout` layer on the outputs of each
+            GRU layer except the last layer, with dropout probability equal to
+            :attr:`dropout`. Default: 0
+        bidirectional: If ``True``, becomes a bidirectional GRU. Default: ``False``
+
+    Inputs: input, h_0
+        - **input** of shape `(seq_len, batch, input_size)`: tensor containing the features
+          of the input sequence. The input can also be a packed variable length
+          sequence. See :func:`torch.nn.utils.rnn.pack_padded_sequence`
+          for details.
+        - **h_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor
+          containing the initial hidden state for each element in the batch.
+          Defaults to zero if not provided. If the RNN is bidirectional,
+          num_directions should be 2, else it should be 1.
+
+    Outputs: output, h_n
+        - **output** of shape `(seq_len, batch, num_directions * hidden_size)`: tensor
+          containing the output features h_t from the last layer of the GRU,
+          for each `t`. If a :class:`torch.nn.utils.rnn.PackedSequence` has been
+          given as the input, the output will also be a packed sequence.
+          For the unpacked case, the directions can be separated
+          using ``output.view(seq_len, batch, num_directions, hidden_size)``,
+          with forward and backward being direction `0` and `1` respectively.
+
+          Similarly, the directions can be separated in the packed case.
+        - **h_n** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor
+          containing the hidden state for `t = seq_len`
+
+          Like *output*, the layers can be separated using
+          ``h_n.view(num_layers, num_directions, batch, hidden_size)``.
+
+    Shape:
+        - Input1: :math:`(L, N, H_{in})` tensor containing input features where
+          :math:`H_{in}=\text{input\_size}` and `L` represents a sequence length.
+        - Input2: :math:`(S, N, H_{out})` tensor
+          containing the initial hidden state for each element in the batch.
+          :math:`H_{out}=\text{hidden\_size}`
+          Defaults to zero if not provided. where :math:`S=\text{num\_layers} * \text{num\_directions}`
+          If the RNN is bidirectional, num_directions should be 2, else it should be 1.
+        - Output1: :math:`(L, N, H_{all})` where :math:`H_{all}=\text{num\_directions} * \text{hidden\_size}`
+        - Output2: :math:`(S, N, H_{out})` tensor containing the next hidden state
+          for each element in the batch
+
+    Attributes:
+        weight_ih_l[k] : the learnable input-hidden weights of the :math:`\text{k}^{th}` layer
+            (W_ir|W_iz|W_in), of shape `(3*hidden_size, input_size)` for `k = 0`.
+            Otherwise, the shape is `(3*hidden_size, num_directions * hidden_size)`
+        weight_hh_l[k] : the learnable hidden-hidden weights of the :math:`\text{k}^{th}` layer
+            (W_hr|W_hz|W_hn), of shape `(3*hidden_size, hidden_size)`
+        bias_ih_l[k] : the learnable input-hidden bias of the :math:`\text{k}^{th}` layer
+            (b_ir|b_iz|b_in), of shape `(3*hidden_size)`
+        bias_hh_l[k] : the learnable hidden-hidden bias of the :math:`\text{k}^{th}` layer
+            (b_hr|b_hz|b_hn), of shape `(3*hidden_size)`
+
+    .. note::
+        All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`
+        where :math:`k = \frac{1}{\text{hidden\_size}}`
+
+    .. note::
+        The calculation of new gate :math:`n_t` subtly differs from the original paper and other frameworks.
+        In the original implementation, the Hadamard product :math:`(\odot)` between :math:`r_t` and the
+        previous hidden state :math:`h_{(t-1)}` is done before the multiplication with the weight matrix
+        `W` and addition of bias:
+
+        .. math::
+            \begin{aligned}
+                n_t = \tanh(W_{in} x_t + b_{in} + W_{hn} ( r_t \odot h_{(t-1)} ) + b_{hn})
+            \end{aligned}
+
+        This is in contrast to PyTorch implementation, which is done after :math:`W_{hn} h_{(t-1)}`
+
+        .. math::
+            \begin{aligned}
+                n_t = \tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{(t-1)}+ b_{hn}))
+            \end{aligned}
+
+        This implementation differs on purpose for efficiency.
+
+    .. include:: ../cudnn_persistent_rnn.rst
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> rnn = nn.GRU(10, 20, 2)
+        >>> input = torch.randn(5, 3, 10)
+        >>> h0 = torch.randn(2, 3, 20)
+        >>> output, hn = rnn(input, h0)
+    """
+
+    _FLOAT_MODULE = nn.GRU
+
+    __overloads__ = {"forward": ["forward_packed", "forward_tensor"]}
+
+    def __init__(self, *args, **kwargs):
+        super().__init__("GRU", *args, **kwargs)
+
+    def _get_name(self):
+        return "DynamicQuantizedGRU"
+
+    def check_forward_args(
+        self, input: Tensor, hidden: Tensor, batch_sizes: Optional[Tensor]
+    ) -> None:
+        self.check_input(input, batch_sizes)
+        expected_hidden_size = self.get_expected_hidden_size(input, batch_sizes)
+
+        self.check_hidden_size(
+            hidden, expected_hidden_size, "Expected hidden size {}, got {}"
+        )
+
+    def forward_impl(
+        self,
+        input: Tensor,
+        hx: Optional[Tensor],
+        batch_sizes: Optional[Tensor],
+        max_batch_size: int,
+        sorted_indices: Optional[Tensor],
+    ) -> tuple[Tensor, Tensor]:
+        if hx is None:
+            num_directions = 2 if self.bidirectional else 1
+            zeros = torch.zeros(
+                self.num_layers * num_directions,
+                max_batch_size,
+                self.hidden_size,
+                dtype=input.dtype,
+                device=input.device,
+            )
+            hx = zeros
+        else:
+            # Each batch of the hidden state should match the input sequence that
+            # the user believes he/she is passing in.
+            hx = self.permute_hidden(hx, sorted_indices)
+
+        self.check_forward_args(input, hx, batch_sizes)
+
+        _all_params = [m.param for m in self._all_weight_values]
+        if batch_sizes is None:
+            result = torch.quantized_gru(
+                input,
+                hx,
+                _all_params,
+                self.bias,
+                self.num_layers,
+                self.dropout,
+                self.training,
+                self.bidirectional,
+                self.batch_first,
+            )
+        else:
+            result = torch.quantized_gru(
+                input,
+                batch_sizes,
+                hx,
+                _all_params,
+                self.bias,
+                self.num_layers,
+                self.dropout,
+                self.training,
+                self.bidirectional,
+            )
+        output = result[0]
+        hidden = result[1]
+
+        return output, hidden
+
+    @torch.jit.export
+    def forward_tensor(
+        self, input: Tensor, hx: Optional[Tensor] = None
+    ) -> tuple[Tensor, Tensor]:
+        batch_sizes = None
+        max_batch_size = input.size(0) if self.batch_first else input.size(1)
+        sorted_indices = None
+        unsorted_indices = None
+
+        output, hidden = self.forward_impl(
+            input, hx, batch_sizes, max_batch_size, sorted_indices
+        )
+
+        return output, self.permute_hidden(hidden, unsorted_indices)
+
+    @torch.jit.export
+    def forward_packed(
+        self, input: PackedSequence, hx: Optional[Tensor] = None
+    ) -> tuple[PackedSequence, Tensor]:
+        input_, batch_sizes, sorted_indices, unsorted_indices = input
+        max_batch_size = int(batch_sizes[0])
+        output_, hidden = self.forward_impl(
+            input_, hx, batch_sizes, max_batch_size, sorted_indices
+        )
+
+        output = PackedSequence(output_, batch_sizes, sorted_indices, unsorted_indices)
+        return output, self.permute_hidden(hidden, unsorted_indices)
+
+    def permute_hidden(self, hx: Tensor, permutation: Optional[Tensor]) -> Tensor:
+        if permutation is None:
+            return hx
+        return _apply_permutation(hx, permutation)
+
+    @torch.jit.ignore
+    def forward(self, input, hx=None):
+        if isinstance(input, PackedSequence):
+            return self.forward_packed(input, hx)
+        else:
+            return self.forward_tensor(input, hx)
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+    @classmethod
+    def from_reference(cls, ref_mod):
+        if not hasattr(ref_mod, "weight_ih_l0_dtype"):
+            raise AssertionError(
+                "We are assuming weight_ih_l0 exists in GRU, "
+                "may need to relax the assumption to support the use case"
+            )
+        qmod = cls(
+            ref_mod.input_size,
+            ref_mod.hidden_size,
+            ref_mod.num_layers,
+            ref_mod.bias,
+            ref_mod.batch_first,
+            ref_mod.dropout,
+            ref_mod.bidirectional,
+            # assuming there is layer 0, which should be OK
+            ref_mod.weight_ih_l0_dtype,
+        )
+        qmod.set_weight_bias(ref_mod.get_quantized_weight_bias_dict())
+        return qmod
+
+
+class RNNCellBase(torch.nn.Module):
+    # _FLOAT_MODULE = nn.CellRNNBase
+    __constants__ = ["input_size", "hidden_size", "bias"]
+
+    def __init__(
+        self, input_size, hidden_size, bias=True, num_chunks=4, dtype=torch.qint8
+    ):
+        super().__init__()
+        self.input_size = input_size
+        self.hidden_size = hidden_size
+        self.bias = bias
+        self.weight_dtype = dtype
+        if bias:
+            self.bias_ih = torch.randn(num_chunks * hidden_size).to(dtype=torch.float)
+            self.bias_hh = torch.randn(num_chunks * hidden_size).to(dtype=torch.float)
+        else:
+            self.register_parameter("bias_ih", None)
+            self.register_parameter("bias_hh", None)
+
+        weight_ih = torch.randn(num_chunks * hidden_size, input_size).to(torch.float)
+        weight_hh = torch.randn(num_chunks * hidden_size, hidden_size).to(torch.float)
+        if dtype == torch.qint8:
+            weight_ih = torch.quantize_per_tensor(
+                weight_ih, scale=1, zero_point=0, dtype=torch.qint8
+            )
+            weight_hh = torch.quantize_per_tensor(
+                weight_hh, scale=1, zero_point=0, dtype=torch.qint8
+            )
+
+        if dtype == torch.qint8:
+            # for each layer, for each direction we need to quantize and pack
+            # weights and pack parameters in this order:
+            #
+            #   w_ih, w_hh
+            packed_weight_ih = torch.ops.quantized.linear_prepack(
+                weight_ih, self.bias_ih
+            )
+            packed_weight_hh = torch.ops.quantized.linear_prepack(
+                weight_hh, self.bias_hh
+            )
+        else:
+            # for each layer, for each direction we need to quantize and pack
+            # weights and pack parameters in this order:
+            #
+            #   packed_ih, packed_hh, b_ih, b_hh
+            packed_weight_ih = torch.ops.quantized.linear_prepack_fp16(
+                weight_ih, self.bias_ih
+            )
+            packed_weight_hh = torch.ops.quantized.linear_prepack_fp16(
+                weight_hh, self.bias_hh
+            )
+
+        self._packed_weight_ih = packed_weight_ih
+        self._packed_weight_hh = packed_weight_hh
+
+    def _get_name(self):
+        return "DynamicQuantizedRNNBase"
+
+    def extra_repr(self):
+        s = "{input_size}, {hidden_size}"
+        if "bias" in self.__dict__ and self.bias is not True:
+            s += ", bias={bias}"
+        if "nonlinearity" in self.__dict__ and self.nonlinearity != "tanh":
+            s += ", nonlinearity={nonlinearity}"
+        return s.format(**self.__dict__)
+
+    def check_forward_input(self, input):
+        if input.size(1) != self.input_size:
+            raise RuntimeError(
+                f"input has inconsistent input_size: got {input.size(1)}, expected {self.input_size}"
+            )
+
+    def check_forward_hidden(
+        self, input: Tensor, hx: Tensor, hidden_label: str = ""
+    ) -> None:
+        if input.size(0) != hx.size(0):
+            raise RuntimeError(
+                f"Input batch size {input.size(0)} doesn't match hidden{hidden_label} batch size {hx.size(0)}"
+            )
+
+        if hx.size(1) != self.hidden_size:
+            raise RuntimeError(
+                f"hidden{hidden_label} has inconsistent hidden_size: got {hx.size(1)}, expected {self.hidden_size}"
+            )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        if type(mod) not in {torch.nn.LSTMCell, torch.nn.GRUCell, torch.nn.RNNCell}:
+            raise AssertionError(
+                "nn.quantized.dynamic.RNNCellBase.from_float "
+                "only works for nn.LSTMCell, nn.GRUCell and nn.RNNCell"
+            )
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+
+        if mod.qconfig is not None and mod.qconfig.weight is not None:
+            weight_observer_method = mod.qconfig.weight
+        else:
+            # We have the circular import issues if we import the qconfig in the beginning of this file:
+            # https://github.com/pytorch/pytorch/pull/24231. The current workaround is to postpone the
+            # import until we need it.
+            from torch.ao.quantization.qconfig import default_dynamic_qconfig
+
+            weight_observer_method = default_dynamic_qconfig.weight
+
+        dtype = weight_observer_method().dtype
+        supported_scalar_types = [torch.qint8, torch.float16]
+        if dtype not in supported_scalar_types:
+            raise RuntimeError(
+                f"Unsupported dtype for dynamic RNN quantization: {dtype}"
+            )
+
+        qRNNCellBase: Union[LSTMCell, GRUCell, RNNCell]
+
+        if type(mod) is torch.nn.LSTMCell:
+            qRNNCellBase = LSTMCell(
+                mod.input_size, mod.hidden_size, bias=mod.bias, dtype=dtype
+            )
+        elif type(mod) is torch.nn.GRUCell:
+            qRNNCellBase = GRUCell(
+                mod.input_size, mod.hidden_size, bias=mod.bias, dtype=dtype
+            )
+        elif type(mod) is torch.nn.RNNCell:
+            qRNNCellBase = RNNCell(
+                mod.input_size,
+                mod.hidden_size,
+                bias=mod.bias,
+                nonlinearity=mod.nonlinearity,
+                dtype=dtype,
+            )
+        else:
+            raise NotImplementedError(
+                "Only LSTMCell, GRUCell and RNNCell \
+            are supported for QuantizedRNN for now"
+            )
+
+        if not mod.bias:
+            raise AssertionError("mod.bias must be True")
+
+        def _observe_and_quantize_weight(weight):
+            if dtype == torch.qint8:
+                weight_observer = weight_observer_method()
+                weight_observer(weight)
+                qweight = _quantize_weight(weight.float(), weight_observer)
+                return qweight
+            else:
+                return weight.float()
+
+        qRNNCellBase._packed_weight_ih = pack_weight_bias(
+            _observe_and_quantize_weight(mod.weight_ih), mod.bias_ih, dtype
+        )
+        qRNNCellBase._packed_weight_hh = pack_weight_bias(
+            _observe_and_quantize_weight(mod.weight_hh), mod.bias_hh, dtype
+        )
+        return qRNNCellBase
+
+    @classmethod
+    def from_reference(cls, ref_mod):
+        if not hasattr(ref_mod, "weight_ih_dtype"):
+            raise AssertionError(
+                "We are assuming weight_ih exists in reference module, "
+                "may need to relax the assumption to support the use case"
+            )
+        if hasattr(ref_mod, "nonlinearity"):
+            qmod = cls(
+                ref_mod.input_size,
+                ref_mod.hidden_size,
+                ref_mod.bias,
+                ref_mod.nonlinearity,
+                dtype=ref_mod.weight_ih_dtype,
+            )
+        else:
+            qmod = cls(
+                ref_mod.input_size,
+                ref_mod.hidden_size,
+                ref_mod.bias,
+                dtype=ref_mod.weight_ih_dtype,
+            )
+        weight_bias_dict = {
+            "weight": {
+                "weight_ih": ref_mod.get_quantized_weight_ih(),
+                "weight_hh": ref_mod.get_quantized_weight_hh(),
+            },
+            "bias": {
+                "bias_ih": ref_mod.bias_ih,
+                "bias_hh": ref_mod.bias_hh,
+            },
+        }
+        qmod.set_weight_bias(weight_bias_dict)
+        return qmod
+
+    def _weight_bias(self):
+        # Returns a dict of weights and biases
+        weight_bias_dict: Dict[str, Dict] = {"weight": {}, "bias": {}}
+        w1, b1 = self._packed_weight_ih.__getstate__()[0]
+        w2, b2 = self._packed_weight_hh.__getstate__()[0]
+        # TODO: these can be simplified to one level? e.g. using weight_ih as key
+        # directly
+        weight_bias_dict["weight"]["weight_ih"] = w1
+        weight_bias_dict["weight"]["weight_hh"] = w2
+        weight_bias_dict["bias"]["bias_ih"] = b1
+        weight_bias_dict["bias"]["bias_hh"] = b2
+        return weight_bias_dict
+
+    def get_weight(self):
+        return self._weight_bias()["weight"]
+
+    def get_bias(self):
+        return self._weight_bias()["bias"]
+
+    def set_weight_bias(self, weight_bias_dict):
+        # TODO: these can be simplified to one level? e.g. using weight_ih as key
+        # directly
+        self._packed_weight_ih = pack_weight_bias(
+            weight_bias_dict["weight"]["weight_ih"],
+            weight_bias_dict["bias"]["bias_ih"],
+            self.weight_dtype,
+        )
+        self._packed_weight_hh = pack_weight_bias(
+            weight_bias_dict["weight"]["weight_hh"],
+            weight_bias_dict["bias"]["bias_hh"],
+            self.weight_dtype,
+        )
+
+    def _save_to_state_dict(self, destination, prefix, keep_vars):
+        super()._save_to_state_dict(destination, prefix, keep_vars)
+        destination[prefix + "_packed_weight_ih"] = self._packed_weight_ih
+        destination[prefix + "_packed_weight_hh"] = self._packed_weight_hh
+
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        self._packed_weight_ih = state_dict.pop(prefix + "_packed_weight_ih")
+        self._packed_weight_hh = state_dict.pop(prefix + "_packed_weight_hh")
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+
+class RNNCell(RNNCellBase):
+    r"""An Elman RNN cell with tanh or ReLU non-linearity.
+    A dynamic quantized RNNCell module with floating point tensor as inputs and outputs.
+    Weights are quantized to 8 bits. We adopt the same interface as `torch.nn.RNNCell`,
+    please see https://pytorch.org/docs/stable/nn.html#torch.nn.RNNCell for documentation.
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> rnn = nn.RNNCell(10, 20)
+        >>> input = torch.randn(6, 3, 10)
+        >>> hx = torch.randn(3, 20)
+        >>> output = []
+        >>> for i in range(6):
+        ...     hx = rnn(input[i], hx)
+        ...     output.append(hx)
+    """
+
+    __constants__ = ["input_size", "hidden_size", "bias", "nonlinearity"]
+
+    def __init__(
+        self, input_size, hidden_size, bias=True, nonlinearity="tanh", dtype=torch.qint8
+    ):
+        super().__init__(input_size, hidden_size, bias, num_chunks=1, dtype=dtype)
+        self.nonlinearity = nonlinearity
+
+    def _get_name(self):
+        return "DynamicQuantizedRNNCell"
+
+    def forward(self, input: Tensor, hx: Optional[Tensor] = None) -> Tensor:
+        self.check_forward_input(input)
+        if hx is None:
+            hx = torch.zeros(
+                input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
+            )
+        self.check_forward_hidden(input, hx, "")
+        if self.nonlinearity == "tanh":
+            ret = torch.ops.quantized.quantized_rnn_tanh_cell_dynamic(
+                input,
+                hx,
+                self._packed_weight_ih,
+                self._packed_weight_hh,
+                self.bias_ih,
+                self.bias_hh,
+            )
+        elif self.nonlinearity == "relu":
+            ret = torch.ops.quantized.quantized_rnn_relu_cell_dynamic(
+                input,
+                hx,
+                self._packed_weight_ih,
+                self._packed_weight_hh,
+                self.bias_ih,
+                self.bias_hh,
+            )
+        else:
+            ret = input  # TODO: remove when jit supports exception flow
+            raise RuntimeError(f"Unknown nonlinearity: {self.nonlinearity}")
+        return ret
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+
+class LSTMCell(RNNCellBase):
+    r"""A long short-term memory (LSTM) cell.
+
+    A dynamic quantized LSTMCell module with floating point tensor as inputs and outputs.
+    Weights are quantized to 8 bits. We adopt the same interface as `torch.nn.LSTMCell`,
+    please see https://pytorch.org/docs/stable/nn.html#torch.nn.LSTMCell for documentation.
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> rnn = nn.LSTMCell(10, 20)
+        >>> input = torch.randn(6, 3, 10)
+        >>> hx = torch.randn(3, 20)
+        >>> cx = torch.randn(3, 20)
+        >>> output = []
+        >>> for i in range(6):
+        ...     hx, cx = rnn(input[i], (hx, cx))
+        ...     output.append(hx)
+    """
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, num_chunks=4, **kwargs)  # type: ignore[misc]
+
+    def _get_name(self):
+        return "DynamicQuantizedLSTMCell"
+
+    def forward(
+        self, input: Tensor, hx: Optional[tuple[Tensor, Tensor]] = None
+    ) -> tuple[Tensor, Tensor]:
+        self.check_forward_input(input)
+        if hx is None:
+            zeros = torch.zeros(
+                input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
+            )
+            hx = (zeros, zeros)
+        self.check_forward_hidden(input, hx[0], "[0]")
+        self.check_forward_hidden(input, hx[1], "[1]")
+        return torch.ops.quantized.quantized_lstm_cell_dynamic(
+            input,
+            hx,
+            self._packed_weight_ih,
+            self._packed_weight_hh,
+            self.bias_ih,
+            self.bias_hh,
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+
+class GRUCell(RNNCellBase):
+    r"""A gated recurrent unit (GRU) cell
+
+    A dynamic quantized GRUCell module with floating point tensor as inputs and outputs.
+    Weights are quantized to 8 bits. We adopt the same interface as `torch.nn.GRUCell`,
+    please see https://pytorch.org/docs/stable/nn.html#torch.nn.GRUCell for documentation.
+
+    Examples::
+
+        >>> # xdoctest: +SKIP
+        >>> rnn = nn.GRUCell(10, 20)
+        >>> input = torch.randn(6, 3, 10)
+        >>> hx = torch.randn(3, 20)
+        >>> output = []
+        >>> for i in range(6):
+        ...     hx = rnn(input[i], hx)
+        ...     output.append(hx)
+    """
+
+    def __init__(self, input_size, hidden_size, bias=True, dtype=torch.qint8):
+        super().__init__(input_size, hidden_size, bias, num_chunks=3, dtype=dtype)
+
+    def _get_name(self):
+        return "DynamicQuantizedGRUCell"
+
+    def forward(self, input: Tensor, hx: Optional[Tensor] = None) -> Tensor:
+        self.check_forward_input(input)
+        if hx is None:
+            hx = torch.zeros(
+                input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
+            )
+        self.check_forward_hidden(input, hx, "")
+        return torch.ops.quantized.quantized_gru_cell_dynamic(
+            input,
+            hx,
+            self._packed_weight_ih,
+            self._packed_weight_hh,
+            self.bias_ih,
+            self.bias_hh,
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        return super().from_float(
+            mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/functional.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/functional.py
new file mode 100644
index 0000000000000000000000000000000000000000..507ae77f68ef026908d5db1524693fee5ce73eae
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/functional.py
@@ -0,0 +1,785 @@
+# mypy: allow-untyped-defs
+r"""Functional interface (quantized)."""
+
+import warnings
+
+import torch
+from torch import Tensor
+from torch.jit.annotations import BroadcastingList2
+from torch.nn.modules.utils import _pair, _triple
+
+from .modules.utils import _pair_from_first
+
+
+# Although some of the functions and docstrings are mirrored from the torch.nn,
+# we want to have them here for future changes.
+
+__all__ = [
+    "avg_pool2d",
+    "avg_pool3d",
+    "adaptive_avg_pool2d",
+    "adaptive_avg_pool3d",
+    "conv1d",
+    "conv2d",
+    "conv3d",
+    "interpolate",
+    "linear",
+    "max_pool1d",
+    "max_pool2d",
+    "celu",
+    "leaky_relu",
+    "hardtanh",
+    "hardswish",
+    "threshold",
+    "elu",
+    "hardsigmoid",
+    "clamp",
+    "upsample",
+    "upsample_bilinear",
+    "upsample_nearest",
+]
+
+
+def avg_pool2d(
+    input,
+    kernel_size,
+    stride=None,
+    padding=0,
+    ceil_mode=False,
+    count_include_pad=True,
+    divisor_override=None,
+):
+    r"""
+    Applies 2D average-pooling operation in :math:`kH \times kW` regions by step size
+    :math:`sH \times sW` steps. The number of output features is equal to the number of
+    input planes.
+
+    .. note:: The input quantization parameters propagate to the output.
+
+    See :class:`~torch.ao.nn.quantized.AvgPool2d` for details and output shape.
+
+    Args:
+        input: quantized input tensor :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
+        kernel_size: size of the pooling region. Can be a single number or a
+          tuple `(kH, kW)`
+        stride: stride of the pooling operation. Can be a single number or a
+          tuple `(sH, sW)`. Default: :attr:`kernel_size`
+        padding: implicit zero paddings on both sides of the input. Can be a
+          single number or a tuple `(padH, padW)`. Default: 0
+        ceil_mode: when True, will use `ceil` instead of `floor` in the formula
+            to compute the output shape. Default: ``False``
+        count_include_pad: when True, will include the zero-padding in the
+            averaging calculation. Default: ``True``
+        divisor_override: if specified, it will be used as divisor, otherwise
+             size of the pooling region will be used. Default: None
+    """
+    if not input.is_quantized:
+        raise ValueError("Input to 'quantized.avg_pool2d' must be quantized!")
+    return torch.nn.functional.avg_pool2d(
+        input,
+        kernel_size,
+        stride,
+        padding,
+        ceil_mode,
+        count_include_pad,
+        divisor_override,
+    )
+
+
+def avg_pool3d(
+    input,
+    kernel_size,
+    stride=None,
+    padding=0,
+    ceil_mode=False,
+    count_include_pad=True,
+    divisor_override=None,
+):
+    r"""
+    Applies 3D average-pooling operation in :math:`kD \ times kH \times kW` regions by step size
+    :math:`sD \times sH \times sW` steps. The number of output features is equal to the number of
+    input planes.
+
+    .. note:: The input quantization parameters propagate to the output.
+
+    Args:
+        input: quantized input tensor :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
+        kernel_size: size of the pooling region. Can be a single number or a
+          tuple `(kD, kH, kW)`
+        stride: stride of the pooling operation. Can be a single number or a
+          tuple `(sD, sH, sW)`. Default: :attr:`kernel_size`
+        padding: implicit zero paddings on both sides of the input. Can be a
+          single number or a tuple `(padD, padH, padW)`. Default: 0
+        ceil_mode: when True, will use `ceil` instead of `floor` in the formula
+            to compute the output shape. Default: ``False``
+        count_include_pad: when True, will include the zero-padding in the
+            averaging calculation. Default: ``True``
+        divisor_override: if specified, it will be used as divisor, otherwise
+             size of the pooling region will be used. Default: None
+    """
+    if not input.is_quantized:
+        raise ValueError("Input to 'quantized.avg_pool3d' must be quantized!")
+    return torch.nn.functional.avg_pool3d(
+        input,
+        kernel_size,
+        stride,
+        padding,
+        ceil_mode,
+        count_include_pad,
+        divisor_override,
+    )
+
+
+def adaptive_avg_pool2d(input: Tensor, output_size: BroadcastingList2[int]) -> Tensor:
+    r"""
+    Applies a 2D adaptive average pooling over a quantized input signal composed
+    of several quantized input planes.
+
+    .. note:: The input quantization parameters propagate to the output.
+
+    See :class:`~torch.ao.nn.quantized.AdaptiveAvgPool2d` for details and output shape.
+
+    Args:
+        output_size: the target output size (single integer or
+                     double-integer tuple)
+    """
+    if not input.is_quantized:
+        raise ValueError(
+            "Input to 'quantized.functional.adaptive_avg_pool2d' must be quantized!"
+        )
+    return torch.nn.functional.adaptive_avg_pool2d(input, output_size)
+
+
+def adaptive_avg_pool3d(input: Tensor, output_size: BroadcastingList2[int]) -> Tensor:
+    r"""
+    Applies a 3D adaptive average pooling over a quantized input signal composed
+    of several quantized input planes.
+
+    .. note:: The input quantization parameters propagate to the output.
+
+    See :class:`~torch.ao.nn.quantized.AdaptiveAvgPool3d` for details and output shape.
+
+    Args:
+        output_size: the target output size (single integer or
+                     double-integer tuple)
+    """
+    if not input.is_quantized:
+        raise ValueError(
+            "Input to 'quantized.functional.adaptive_avg_pool3d' must be quantized!"
+        )
+    return torch.nn.functional.adaptive_avg_pool3d(input, output_size)
+
+
+def conv1d(
+    input,
+    weight,
+    bias,
+    stride=1,
+    padding=0,
+    dilation=1,
+    groups=1,
+    padding_mode="zeros",
+    scale=1.0,
+    zero_point=0,
+    dtype=torch.quint8,
+):
+    r"""
+    Applies a 1D convolution over a quantized 1D input composed of several input
+    planes.
+
+    See :class:`~torch.ao.nn.quantized.Conv1d` for details and output shape.
+
+    Args:
+        input: quantized input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)`
+        weight: quantized filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , iW)`
+        bias: **non-quantized** bias tensor of shape :math:`(\text{out\_channels})`. The tensor type must be `torch.float`.
+        stride: the stride of the convolving kernel. Can be a single number or a
+          tuple `(sW,)`. Default: 1
+        padding: implicit paddings on both sides of the input. Can be a
+          single number or a tuple `(padW,)`. Default: 0
+        dilation: the spacing between kernel elements. Can be a single number or
+          a tuple `(dW,)`. Default: 1
+        groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
+          number of groups. Default: 1
+        padding_mode: the padding mode to use. Only "zeros" is supported for quantized convolution at the moment. Default: "zeros"
+        scale: quantization scale for the output. Default: 1.0
+        zero_point: quantization zero_point for the output. Default: 0
+        dtype: quantization data type to use. Default: ``torch.quint8``
+
+    Examples::
+
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
+        >>> warnings.filterwarnings("ignore", message=".*quantized tensor creation functions")  # docs: hide
+        >>> from torch.ao.nn.quantized import functional as qF
+        >>> filters = torch.randn(33, 16, 3, dtype=torch.float)
+        >>> inputs = torch.randn(20, 16, 50, dtype=torch.float)
+        >>> bias = torch.randn(33, dtype=torch.float)
+        >>>
+        >>> scale, zero_point = 1.0, 0
+        >>> dtype_inputs = torch.quint8
+        >>> dtype_filters = torch.qint8
+        >>>
+        >>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters)
+        >>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs)
+        >>> qF.conv1d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point)
+    """
+    if padding_mode != "zeros":
+        raise NotImplementedError("Only zero-padding is supported!")
+    if input.dtype != torch.quint8:
+        raise NotImplementedError(
+            "Only torch.quint8 is supported for activation tensor!"
+        )
+    if weight.dtype != torch.qint8:
+        raise NotImplementedError("Only torch.qint8 is supported for weight tensor!")
+    if input.ndim != 3:
+        raise ValueError("Input shape must be `(N, C, L)`!")
+    stride = _pair_from_first(stride)
+    padding = _pair_from_first(padding)
+    dilation = _pair_from_first(dilation)
+
+    packed_params = torch.ops.quantized.conv1d_prepack(
+        weight, bias, stride, padding, dilation, groups
+    )
+    return torch.ops.quantized.conv1d(input, packed_params, scale, zero_point)
+
+
+def conv2d(
+    input,
+    weight,
+    bias,
+    stride=1,
+    padding=0,
+    dilation=1,
+    groups=1,
+    padding_mode="zeros",
+    scale=1.0,
+    zero_point=0,
+    dtype=torch.quint8,
+):
+    r"""
+    Applies a 2D convolution over a quantized 2D input composed of several input
+    planes.
+
+    See :class:`~torch.ao.nn.quantized.Conv2d` for details and output shape.
+
+    Args:
+        input: quantized input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
+        weight: quantized filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kH , kW)`
+        bias: **non-quantized** bias tensor of shape :math:`(\text{out\_channels})`. The tensor type must be `torch.float`.
+        stride: the stride of the convolving kernel. Can be a single number or a
+          tuple `(sH, sW)`. Default: 1
+        padding: implicit paddings on both sides of the input. Can be a
+          single number or a tuple `(padH, padW)`. Default: 0
+        dilation: the spacing between kernel elements. Can be a single number or
+          a tuple `(dH, dW)`. Default: 1
+        groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
+          number of groups. Default: 1
+        padding_mode: the padding mode to use. Only "zeros" is supported for quantized convolution at the moment. Default: "zeros"
+        scale: quantization scale for the output. Default: 1.0
+        zero_point: quantization zero_point for the output. Default: 0
+        dtype: quantization data type to use. Default: ``torch.quint8``
+
+    Examples::
+
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
+        >>> warnings.filterwarnings("ignore", message=".*quantized tensor creation functions")  # docs: hide
+        >>> from torch.ao.nn.quantized import functional as qF
+        >>> filters = torch.randn(8, 4, 3, 3, dtype=torch.float)
+        >>> inputs = torch.randn(1, 4, 5, 5, dtype=torch.float)
+        >>> bias = torch.randn(8, dtype=torch.float)
+        >>>
+        >>> scale, zero_point = 1.0, 0
+        >>> dtype_inputs = torch.quint8
+        >>> dtype_filters = torch.qint8
+        >>>
+        >>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters)
+        >>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs)
+        >>> qF.conv2d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point)
+    """
+    if padding_mode != "zeros":
+        raise NotImplementedError("Only zero-padding is supported!")
+    if input.dtype != torch.quint8:
+        raise NotImplementedError(
+            "Only torch.quint8 is supported for activation tensor!"
+        )
+    if weight.dtype != torch.qint8:
+        raise NotImplementedError("Only torch.qint8 is supported for weight tensor!")
+    if input.ndim != 4:
+        raise ValueError("Input shape must be `(N, C, H, W)`!")
+    stride = _pair(stride)
+    padding = _pair(padding)
+    dilation = _pair(dilation)
+
+    packed_params = torch.ops.quantized.conv2d_prepack(
+        weight, bias, stride, padding, dilation, groups
+    )
+    return torch.ops.quantized.conv2d(input, packed_params, scale, zero_point)
+
+
+def conv3d(
+    input,
+    weight,
+    bias,
+    stride=1,
+    padding=0,
+    dilation=1,
+    groups=1,
+    padding_mode="zeros",
+    scale=1.0,
+    zero_point=0,
+    dtype=torch.quint8,
+):
+    r"""
+    Applies a 3D convolution over a quantized 3D input composed of several input
+    planes.
+
+    See :class:`~torch.ao.nn.quantized.Conv3d` for details and output shape.
+
+    Args:
+        input: quantized input tensor of shape
+          :math:`(\text{minibatch} , \text{in\_channels} , iD , iH , iW)`
+        weight: quantized filters of shape
+          :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kD , kH , kW)`
+        bias: **non-quantized** bias tensor of shape
+          :math:`(\text{out\_channels})`. The tensor type must be `torch.float`.
+        stride: the stride of the convolving kernel. Can be a single number or a
+          tuple `(sD, sH, sW)`. Default: 1
+        padding: implicit paddings on both sides of the input. Can be a
+          single number or a tuple `(padD, padH, padW)`. Default: 0
+        dilation: the spacing between kernel elements. Can be a single number or
+          a tuple `(dD, dH, dW)`. Default: 1
+        groups: split input into groups, :math:`\text{in\_channels}` should be
+          divisible by the number of groups. Default: 1
+        padding_mode: the padding mode to use. Only "zeros" is supported for
+          quantized convolution at the moment. Default: "zeros"
+        scale: quantization scale for the output. Default: 1.0
+        zero_point: quantization zero_point for the output. Default: 0
+        dtype: quantization data type to use. Default: ``torch.quint8``
+
+    Examples::
+
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
+        >>> warnings.filterwarnings("ignore", message=".*quantized tensor creation functions")  # docs: hide
+        >>> from torch.ao.nn.quantized import functional as qF
+        >>> filters = torch.randn(8, 4, 3, 3, 3, dtype=torch.float)
+        >>> inputs = torch.randn(1, 4, 5, 5, 5, dtype=torch.float)
+        >>> bias = torch.randn(8, dtype=torch.float)
+        >>>
+        >>> scale, zero_point = 1.0, 0
+        >>> dtype_inputs = torch.quint8
+        >>> dtype_filters = torch.qint8
+        >>>
+        >>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters)
+        >>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs)
+        >>> qF.conv3d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point)
+    """
+    if padding_mode != "zeros":
+        raise NotImplementedError("Only zero-padding is supported!")
+    if input.dtype != torch.quint8:
+        raise NotImplementedError(
+            "Only torch.quint8 is supported for activation tensor!"
+        )
+    if weight.dtype != torch.qint8:
+        raise NotImplementedError("Only torch.qint8 is supported for weight tensor!")
+    if input.ndim != 5:
+        raise ValueError("Input shape must be `(N, C, D, H, W)`!")
+    stride = _triple(stride)
+    padding = _triple(padding)
+    dilation = _triple(dilation)
+
+    packed_params = torch.ops.quantized.conv3d_prepack(
+        weight, bias, stride, padding, dilation, groups
+    )
+    return torch.ops.quantized.conv3d(input, packed_params, scale, zero_point)
+
+
+def interpolate(
+    input, size=None, scale_factor=None, mode="nearest", align_corners=None
+):
+    r"""Down/up samples the input to either the given :attr:`size` or the given
+    :attr:`scale_factor`
+
+    See :func:`torch.nn.functional.interpolate` for implementation details.
+
+    The input dimensions are interpreted in the form:
+    `mini-batch x channels x [optional depth] x [optional height] x width`.
+
+    .. note:: The input quantization parameters propagate to the output.
+
+    .. note:: Only 2D/3D input is supported for quantized inputs
+
+    .. note:: Only the following modes are supported for the quantized inputs:
+
+        - `bilinear`
+        - `nearest`
+
+    Args:
+        input (Tensor): the input tensor
+        size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]):
+            output spatial size.
+        scale_factor (float or Tuple[float]): multiplier for spatial size. Has to match input size if it is a tuple.
+        mode (str): algorithm used for upsampling:
+            ``'nearest'`` | ``'bilinear'``
+        align_corners (bool, optional): Geometrically, we consider the pixels of the
+            input and output as squares rather than points.
+            If set to ``True``, the input and output tensors are aligned by the
+            center points of their corner pixels, preserving the values at the corner pixels.
+            If set to ``False``, the input and output tensors are aligned by the corner
+            points of their corner pixels, and the interpolation uses edge value padding
+            for out-of-boundary values, making this operation *independent* of input size
+            when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode`
+            is ``'bilinear'``.
+            Default: ``False``
+    """
+    if not input.is_quantized:
+        raise ValueError("Input to 'quantized.interpolate' must be quantized!")
+    return torch.nn.functional.interpolate(
+        input, size, scale_factor, mode, align_corners
+    )
+
+
+def linear(
+    input: Tensor,
+    weight: Tensor,
+    bias: Tensor | None = None,
+    scale: float | None = None,
+    zero_point: int | None = None,
+) -> Tensor:
+    r"""
+    Applies a linear transformation to the incoming quantized data:
+    :math:`y = xA^T + b`.
+    See :class:`~torch.ao.nn.quantized.Linear`
+
+    .. note::
+
+      Current implementation packs weights on every call, which has penalty on performance.
+      If you want to avoid the overhead, use :class:`~torch.ao.nn.quantized.Linear`.
+
+    Args:
+      input (Tensor): Quantized input of type `torch.quint8`
+      weight (Tensor): Quantized weight of type `torch.qint8`
+      bias (Tensor): None or fp32 bias of type `torch.float`
+      scale (double): output scale. If None, derived from the input scale
+      zero_point (long): output zero point. If None, derived from the input zero_point
+
+    Shape:
+        - Input: :math:`(N, *, in\_features)` where `*` means any number of
+          additional dimensions
+        - Weight: :math:`(out\_features, in\_features)`
+        - Bias: :math:`(out\_features)`
+        - Output: :math:`(N, *, out\_features)`
+    """
+    if scale is None:
+        scale = input.q_scale()
+    if zero_point is None:
+        zero_point = input.q_zero_point()
+    _packed_params = torch.ops.quantized.linear_prepack(weight, bias)
+    return torch.ops.quantized.linear(input, _packed_params, scale, zero_point)
+
+
+def max_pool1d(
+    input,
+    kernel_size,
+    stride=None,
+    padding=0,
+    dilation=1,
+    ceil_mode=False,
+    return_indices=False,
+):
+    r"""Applies a 1D max pooling over a quantized input signal composed of
+    several quantized input planes.
+
+    .. note:: The input quantization parameters are propagated to the output.
+
+    See :class:`~torch.ao.nn.quantized.MaxPool1d` for details.
+    """
+    if return_indices:
+        raise NotImplementedError("return_indices is not yet implemented!")
+    if stride is None:
+        stride = torch.jit.annotate(list[int], [])
+    return torch.nn.functional.max_pool1d(
+        input,
+        kernel_size,
+        stride,
+        padding,
+        dilation,
+        ceil_mode=ceil_mode,
+        return_indices=return_indices,
+    )
+
+
+def max_pool2d(
+    input,
+    kernel_size,
+    stride=None,
+    padding=0,
+    dilation=1,
+    ceil_mode=False,
+    return_indices=False,
+):
+    r"""Applies a 2D max pooling over a quantized input signal composed of
+    several quantized input planes.
+
+    .. note:: The input quantization parameters are propagated to the output.
+
+    See :class:`~torch.ao.nn.quantized.MaxPool2d` for details.
+    """
+    if return_indices:
+        raise NotImplementedError("return_indices is not yet implemented!")
+    if stride is None:
+        stride = torch.jit.annotate(list[int], [])
+    return torch.nn.functional.max_pool2d(
+        input,
+        kernel_size,
+        stride,
+        padding,
+        dilation,
+        ceil_mode=ceil_mode,
+        return_indices=return_indices,
+    )
+
+
+def celu(input: Tensor, scale: float, zero_point: int, alpha: float = 1.0) -> Tensor:
+    r"""celu(input, scale, zero_point, alpha=1.) -> Tensor
+
+    Applies the quantized CELU function element-wise.
+
+    .. math::
+        \text{CELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x / \alpha) - 1))
+
+    Args:
+        input: quantized input
+        alpha: the :math:`\alpha` value for the CELU formulation. Default: 1.0
+    """
+    if not input.is_quantized:
+        raise ValueError("Input to 'quantized.celu' must be quantized!")
+    return torch.ops.quantized.celu(input, scale, zero_point, alpha)
+
+
+def leaky_relu(
+    input: Tensor,
+    negative_slope: float = 0.01,
+    inplace: bool = False,
+    scale: float | None = None,
+    zero_point: int | None = None,
+):
+    r"""
+    Quantized version of the.
+    leaky_relu(input, negative_slope=0.01, inplace=False, scale, zero_point) -> Tensor
+
+    Applies element-wise,
+    :math:`\text{LeakyReLU}(x) = \max(0, x) + \text{negative\_slope} * \min(0, x)`
+
+    Args:
+        input: Quantized input
+        negative_slope: The slope of the negative input
+        inplace: Inplace modification of the input tensor
+        scale, zero_point: Scale and zero point of the output tensor.
+
+    See :class:`~torch.nn.LeakyReLU` for more details.
+    """
+    if scale is not None and zero_point is not None:
+        if inplace:
+            raise AssertionError("Cannot rescale with `inplace`")
+        output = torch._empty_affine_quantized(
+            input.shape, scale=scale, zero_point=int(zero_point), dtype=input.dtype
+        )
+        torch._C._nn.leaky_relu(input, negative_slope, out=output)
+        return output
+    if inplace:
+        result = torch._C._nn.leaky_relu_(input, negative_slope)
+    else:
+        result = torch._C._nn.leaky_relu(input, negative_slope)
+    return result
+
+
+def hardtanh(
+    input: Tensor, min_val: float = -1.0, max_val: float = 1.0, inplace: bool = False
+) -> Tensor:
+    r"""This is the quantized version of :func:`~torch.nn.functional.hardtanh`."""
+    if not input.is_quantized:
+        raise ValueError("Input to 'quantized.hardtanh' must be quantized!")
+    if inplace:
+        return torch._C._nn.hardtanh_(input, min_val, max_val)
+    return torch._C._nn.hardtanh(input, min_val, max_val)
+
+
+def hardswish(input: Tensor, scale: float, zero_point: int) -> Tensor:
+    r"""This is the quantized version of :func:`~torch.nn.functional.hardswish`.
+
+    Args:
+        input: quantized input
+        scale: quantization scale of the output tensor
+        zero_point: quantization zero point of the output tensor
+    """
+    if not input.is_quantized:
+        raise ValueError("Input to 'quantized.hardswish' must be quantized!")
+    return torch._ops.ops.quantized.hardswish(input, scale, zero_point)
+
+
+def threshold(input: Tensor, threshold: float, value: float) -> Tensor:
+    r"""Applies the quantized version of the threshold function element-wise:
+
+    .. math::
+        x = \begin{cases}
+                x & \text{if~} x > \text{threshold} \\
+                \text{value} & \text{otherwise}
+            \end{cases}
+
+    See :class:`~torch.nn.Threshold` for more details.
+    """
+    if not input.is_quantized:
+        raise ValueError("Input to 'quantized.threshold' must be quantized!")
+    if threshold is None:
+        raise ValueError("Input to 'threshold' must be specified!")
+    if value is None:
+        raise ValueError("Input to 'value' must be specified!")
+    return torch._ops.ops.quantized.threshold(input, threshold, value)
+
+
+def elu(input: Tensor, scale: float, zero_point: int, alpha: float = 1.0) -> Tensor:
+    r"""This is the quantized version of :func:`~torch.nn.functional.elu`.
+
+    Args:
+        input: quantized input
+        scale: quantization scale of the output tensor
+        zero_point: quantization zero point of the output tensor
+        alpha: the alpha constant
+    """
+    if not input.is_quantized:
+        raise ValueError("Input to 'quantized.elu' must be quantized!")
+    return torch.ops.quantized.elu(input, scale, zero_point, alpha)
+
+
+def hardsigmoid(input: Tensor, inplace: bool = False) -> Tensor:
+    r"""This is the quantized version of :func:`~torch.nn.functional.hardsigmoid`."""
+    if not input.is_quantized:
+        raise ValueError("Input to 'quantized.hardsigmoid' must be quantized!")
+    if inplace:
+        return torch._C._nn.hardsigmoid_(input)  # type: ignore[attr-defined]
+    return torch._C._nn.hardsigmoid(input)
+
+
+def clamp(input: Tensor, min_: float, max_: float) -> Tensor:
+    r"""float(input, min\_, max\_) -> Tensor
+
+    Applies the clamp function element-wise.
+    See :class:`~torch.ao.nn.quantized.clamp` for more details.
+
+    Args:
+        input: quantized input
+        min_: minimum value for clamping
+        max_: maximum value for clamping
+    """
+    if not input.is_quantized:
+        raise ValueError("Input to 'quantized.clamp' must be quantized!")
+    return torch.clamp(input, min_, max_)
+
+
+def upsample(input, size=None, scale_factor=None, mode="nearest", align_corners=None):
+    r"""Upsamples the input to either the given :attr:`size` or the given
+    :attr:`scale_factor`
+
+    .. warning::
+        This function is deprecated in favor of
+        :func:`torch.ao.nn.quantized.functional.interpolate`.
+        This is equivalent with ``nn.quantized.functional.interpolate(...)``.
+
+    See :func:`torch.nn.functional.interpolate` for implementation details.
+
+    The input dimensions are interpreted in the form:
+    `mini-batch x channels x [optional depth] x [optional height] x width`.
+
+    .. note:: The input quantization parameters propagate to the output.
+
+    .. note:: Only 2D input is supported for quantized inputs
+
+    .. note:: Only the following modes are supported for the quantized inputs:
+
+        - `bilinear`
+        - `nearest`
+
+    Args:
+        input (Tensor): quantized input tensor
+        size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]):
+            output spatial size.
+        scale_factor (float or Tuple[float]): multiplier for spatial size. Has to be an integer.
+        mode (str): algorithm used for upsampling:
+            ``'nearest'`` | ``'bilinear'``
+        align_corners (bool, optional): Geometrically, we consider the pixels of the
+            input and output as squares rather than points.
+            If set to ``True``, the input and output tensors are aligned by the
+            center points of their corner pixels, preserving the values at the corner pixels.
+            If set to ``False``, the input and output tensors are aligned by the corner
+            points of their corner pixels, and the interpolation uses edge value padding
+            for out-of-boundary values, making this operation *independent* of input size
+            when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode`
+            is ``'bilinear'``.
+            Default: ``False``
+
+    .. warning::
+        With ``align_corners = True``, the linearly interpolating modes
+        (`bilinear`) don't proportionally align the
+        output and input pixels, and thus the output values can depend on the
+        input size. This was the default behavior for these modes up to version
+        0.3.1. Since then, the default behavior is ``align_corners = False``.
+        See :class:`~torch.nn.Upsample` for concrete examples on how this
+        affects the outputs.
+    """
+    warnings.warn(
+        "nn.quantized.functional.upsample is deprecated. Use nn.quantized.functional.interpolate instead.",
+        stacklevel=2,
+    )
+    return interpolate(input, size, scale_factor, mode, align_corners)
+
+
+def upsample_bilinear(input, size=None, scale_factor=None):
+    r"""Upsamples the input, using bilinear upsampling.
+
+    .. warning::
+        This function is deprecated in favor of
+        :func:`torch.ao.nn.quantized.functional.interpolate`.
+        This is equivalent with
+        ``nn.quantized.functional.interpolate(..., mode='bilinear', align_corners=True)``.
+
+    .. note:: The input quantization parameters propagate to the output.
+
+    .. note:: Only 2D inputs are supported
+
+    Args:
+        input (Tensor): quantized input
+        size (int or Tuple[int, int]): output spatial size.
+        scale_factor (int or Tuple[int, int]): multiplier for spatial size
+    """
+    # DeprecationWarning is ignored by default
+    warnings.warn(
+        "nn.quantized.functional.upsample_bilinear is deprecated. Use nn.quantized.functional.interpolate instead.",
+        stacklevel=2,
+    )
+    return interpolate(input, size, scale_factor, mode="bilinear", align_corners=True)
+
+
+def upsample_nearest(input, size=None, scale_factor=None):
+    r"""Upsamples the input, using nearest neighbours' pixel values.
+
+    .. warning::
+        This function is deprecated in favor of
+        :func:`torch.ao.nn.quantized.functional.interpolate`.
+        This is equivalent with ``nn.quantized.functional.interpolate(..., mode='nearest')``.
+
+    .. note:: The input quantization parameters propagate to the output.
+
+    .. note:: Only 2D inputs are supported
+
+    Args:
+        input (Tensor): quantized input
+        size (int or Tuple[int, int] or Tuple[int, int, int]): output spatial
+            size.
+        scale_factor (int): multiplier for spatial size. Has to be an integer.
+    """
+    # DeprecationWarning is ignored by default
+    warnings.warn(
+        "nn.quantized.functional.upsample_nearest is deprecated. Use nn.quantized.functional.interpolate instead.",
+        stacklevel=2,
+    )
+    return interpolate(input, size, scale_factor, mode="nearest")
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..def9ed3b65584d0ca970ca94a061b8ade76588e6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__init__.py
@@ -0,0 +1,165 @@
+# mypy: allow-untyped-defs
+import torch
+
+# The quantized modules use `torch.nn` and `torch.ao.nn.quantizable`
+# packages. However, the `quantizable` package uses "lazy imports"
+# to avoid circular dependency.
+# Hence we need to include it here to make sure it is resolved before
+# they are used in the modules.
+import torch.ao.nn.quantizable
+from torch.nn.modules.pooling import MaxPool2d
+
+from .activation import (
+    ELU,
+    Hardswish,
+    LeakyReLU,
+    MultiheadAttention,
+    PReLU,
+    ReLU6,
+    Sigmoid,
+    Softmax,
+)
+from .batchnorm import BatchNorm2d, BatchNorm3d
+from .conv import (
+    Conv1d,
+    Conv2d,
+    Conv3d,
+    ConvTranspose1d,
+    ConvTranspose2d,
+    ConvTranspose3d,
+)
+from .dropout import Dropout
+from .embedding_ops import Embedding, EmbeddingBag
+from .functional_modules import FloatFunctional, FXFloatFunctional, QFunctional
+from .linear import Linear
+from .normalization import (
+    GroupNorm,
+    InstanceNorm1d,
+    InstanceNorm2d,
+    InstanceNorm3d,
+    LayerNorm,
+)
+from .rnn import LSTM
+
+
+__all__ = [
+    "BatchNorm2d",
+    "BatchNorm3d",
+    "Conv1d",
+    "Conv2d",
+    "Conv3d",
+    "ConvTranspose1d",
+    "ConvTranspose2d",
+    "ConvTranspose3d",
+    "DeQuantize",
+    "ELU",
+    "Embedding",
+    "EmbeddingBag",
+    "GroupNorm",
+    "Hardswish",
+    "InstanceNorm1d",
+    "InstanceNorm2d",
+    "InstanceNorm3d",
+    "LayerNorm",
+    "LeakyReLU",
+    "Linear",
+    "LSTM",
+    "MultiheadAttention",
+    "Quantize",
+    "ReLU6",
+    "Sigmoid",
+    "Softmax",
+    "Dropout",
+    "PReLU",
+    # Wrapper modules
+    "FloatFunctional",
+    "FXFloatFunctional",
+    "QFunctional",
+]
+
+
+class Quantize(torch.nn.Module):
+    r"""Quantizes an incoming tensor
+
+    Args:
+     `scale`: scale of the output Quantized Tensor
+     `zero_point`: zero_point of output Quantized Tensor
+     `dtype`: data type of output Quantized Tensor
+     `factory_kwargs`: Dictionary of kwargs used for configuring initialization
+         of internal buffers. Currently, `device` and `dtype` are supported.
+         Example: `factory_kwargs={'device': 'cuda', 'dtype': torch.float64}`
+         will initialize internal buffers as type `torch.float64` on the current CUDA device.
+         Note that `dtype` only applies to floating-point buffers.
+
+    Examples::
+        >>> t = torch.tensor([[1., -1.], [1., -1.]])
+        >>> scale, zero_point, dtype = 1.0, 2, torch.qint8
+        >>> qm = Quantize(scale, zero_point, dtype)
+        >>> # xdoctest: +SKIP
+        >>> qt = qm(t)
+        >>> print(qt)
+        tensor([[ 1., -1.],
+                [ 1., -1.]], size=(2, 2), dtype=torch.qint8, scale=1.0, zero_point=2)
+    """
+
+    scale: torch.Tensor
+    zero_point: torch.Tensor
+
+    def __init__(self, scale, zero_point, dtype, factory_kwargs=None):
+        factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
+        super().__init__()
+        self.register_buffer("scale", torch.tensor([scale], **factory_kwargs))
+        self.register_buffer(
+            "zero_point",
+            torch.tensor(
+                [zero_point],
+                dtype=torch.long,
+                **{k: v for k, v in factory_kwargs.items() if k != "dtype"},
+            ),
+        )
+        self.dtype = dtype
+
+    def forward(self, X):
+        return torch.quantize_per_tensor(
+            X, float(self.scale), int(self.zero_point), self.dtype
+        )
+
+    @staticmethod
+    def from_float(mod, use_precomputed_fake_quant=False):
+        if not hasattr(mod, "activation_post_process"):
+            raise AssertionError(
+                f"Module {type(mod).__name__} must have activation_post_process attribute"
+            )
+        scale, zero_point = mod.activation_post_process.calculate_qparams()
+        return Quantize(
+            scale.float().item(),
+            zero_point.long().item(),
+            mod.activation_post_process.dtype,
+        )
+
+    def extra_repr(self):
+        return f"scale={self.scale}, zero_point={self.zero_point}, dtype={self.dtype}"
+
+
+class DeQuantize(torch.nn.Module):
+    r"""Dequantizes an incoming tensor
+
+    Examples::
+        >>> input = torch.tensor([[1., -1.], [1., -1.]])
+        >>> scale, zero_point, dtype = 1.0, 2, torch.qint8
+        >>> qm = Quantize(scale, zero_point, dtype)
+        >>> # xdoctest: +SKIP
+        >>> quantized_input = qm(input)
+        >>> dqm = DeQuantize()
+        >>> dequantized = dqm(quantized_input)
+        >>> print(dequantized)
+        tensor([[ 1., -1.],
+                [ 1., -1.]], dtype=torch.float32)
+    """
+
+    def forward(self, Xq):
+        return Xq.dequantize()
+
+    @staticmethod
+    def from_float(mod, use_precomputed_fake_quant=False):
+        return DeQuantize()
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c9db9b61d7cccfd10f5aa06b43e53710517cadda
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/activation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/activation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d68482f0523ee0a259d0c0d39e8bd68f3d7cf5e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/activation.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/batchnorm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/batchnorm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a8b2982a3d3deaabcafcf5b5bbf0c8e08a1fea23
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/batchnorm.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/conv.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/conv.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e6280487e832e23d99d320dd896591b5a81c663
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/conv.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/dropout.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/dropout.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f27d8d4af57fff5a972a52155dfe81829e1b6826
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/dropout.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..741848bbf4c275b5537c9ec30e8379ba2debfd90
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/functional_modules.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/functional_modules.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f650e3031b52232f50ad60e17ee313fc11e9b97
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/functional_modules.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/linear.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/linear.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4fbe6e8bc884b6d57bdd203c68c1c038166a6ff7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/linear.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/normalization.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/normalization.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93d2f0d4e264742681421e0ae6db1034a599e7af
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/normalization.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/rnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/rnn.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c504190c552b3baafe9b6dadd6acb0543f569ea
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/rnn.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e9b824bc4b7ab9390f4f264920db5761f7cad61
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/activation.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/activation.py
new file mode 100644
index 0000000000000000000000000000000000000000..669a9978c27ba5e8545d329a0194cd62e981447f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/activation.py
@@ -0,0 +1,346 @@
+# mypy: allow-untyped-defs
+from warnings import warn
+
+import torch
+
+
+__all__ = [
+    "ReLU6",
+    "Hardswish",
+    "ELU",
+    "LeakyReLU",
+    "Sigmoid",
+    "Softmax",
+    "MultiheadAttention",
+    "PReLU",
+]
+
+
+class ReLU6(torch.nn.ReLU):
+    r"""Applies the element-wise function:
+
+    :math:`\text{ReLU6}(x) = \min(\max(x_0, x), q(6))`, where :math:`x_0` is the
+    zero_point, and :math:`q(6)` is the quantized representation of number 6.
+
+    Args:
+        inplace: can optionally do the operation in-place. Default: ``False``
+
+    Shape:
+        - Input: :math:`(N, *)` where `*` means, any number of additional
+          dimensions
+        - Output: :math:`(N, *)`, same shape as the input
+
+    .. image:: ../scripts/activation_images/ReLU6.png
+
+    Examples::
+
+        >>> m = nn.quantized.ReLU6()
+        >>> input = torch.randn(2)
+        >>> # xdoctest: +SKIP
+        >>> input = torch.quantize_per_tensor(input, 1.0, 0, dtype=torch.qint32)
+        >>> output = m(input)
+    """
+
+    def __init__(self, inplace=False):
+        super().__init__(inplace)
+        self.inplace = inplace
+
+    def forward(self, input):
+        return torch.ops.quantized.relu6(input, self.inplace)
+
+    def _get_name(self):
+        return "QuantizedReLU6"
+
+    @staticmethod
+    def from_float(mod, use_precomputed_fake_quant=False):
+        return ReLU6(mod.inplace)
+
+
+class Hardswish(torch.nn.Hardswish):
+    r"""This is the quantized version of :class:`~torch.nn.Hardswish`.
+
+    Args:
+        scale: quantization scale of the output tensor
+        zero_point: quantization zero point of the output tensor
+    """
+
+    def __init__(self, scale, zero_point, device=None, dtype=None):
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__()
+        self.register_buffer("scale", torch.tensor(scale, **factory_kwargs))
+        self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs))
+
+    def forward(self, input):
+        return torch.ops.quantized.hardswish(input, self.scale, self.zero_point)
+
+    def _get_name(self):
+        return "QuantizedHardswish"
+
+    @staticmethod
+    def from_float(mod, use_precomputed_fake_quant=False):
+        scale, zero_point = mod.activation_post_process.calculate_qparams()
+        return Hardswish(float(scale), int(zero_point))
+
+    @classmethod
+    def from_reference(cls, mod, scale, zero_point):
+        return cls(float(scale), int(zero_point))
+
+
+class ELU(torch.nn.ELU):
+    r"""This is the quantized equivalent of :class:`~torch.nn.ELU`.
+
+    Args:
+        scale: quantization scale of the output tensor
+        zero_point: quantization zero point of the output tensor
+        alpha: the alpha constant
+    """
+
+    def __init__(self, scale, zero_point, alpha=1.0):
+        super().__init__(alpha)
+        self.scale = scale
+        self.zero_point = zero_point
+
+    def forward(self, input):
+        return torch.ao.nn.quantized.functional.elu(
+            input, self.scale, self.zero_point, self.alpha
+        )
+
+    def _get_name(self):
+        return "QuantizedELU"
+
+    @staticmethod
+    def from_float(mod, use_precomputed_fake_quant=False):
+        scale, zero_point = mod.activation_post_process.calculate_qparams()
+        return ELU(float(scale), int(zero_point), mod.alpha)
+
+    @classmethod
+    def from_reference(cls, mod, scale, zero_point):
+        return cls(float(scale), int(zero_point), mod.alpha)
+
+
+class LeakyReLU(torch.nn.LeakyReLU):
+    r"""This is the quantized equivalent of :class:`~torch.nn.LeakyReLU`.
+
+    Args:
+        scale: quantization scale of the output tensor
+        zero_point: quantization zero point of the output tensor
+        negative_slope: Controls the angle of the negative slope. Default: 1e-2
+    """
+
+    def __init__(
+        self,
+        scale: float,
+        zero_point: int,
+        negative_slope: float = 1e-2,
+        inplace: bool = False,
+        device=None,
+        dtype=None,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(negative_slope, inplace)
+        self.register_buffer("scale", torch.tensor(scale, **factory_kwargs))
+        self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs))
+
+    def forward(self, input):
+        return torch.ops.quantized.leaky_relu(
+            input, self.negative_slope, self.inplace, self.scale, self.zero_point
+        )
+
+    def _get_name(self):
+        return "QuantizedLeakyReLU"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        scale, zero_point = mod.activation_post_process.calculate_qparams()
+        return cls(float(scale), int(zero_point), mod.negative_slope, mod.inplace)
+
+    @classmethod
+    def from_reference(cls, mod, scale, zero_point):
+        return cls(float(scale), int(zero_point), mod.negative_slope, mod.inplace)
+
+
+class Sigmoid(torch.nn.Sigmoid):
+    r"""This is the quantized equivalent of :class:`~torch.nn.Sigmoid`.
+
+    Args:
+        scale: quantization scale of the output tensor
+        zero_point: quantization zero point of the output tensor
+    """
+
+    def __init__(self, output_scale: float, output_zero_point: int):
+        super().__init__()
+        self.output_scale = output_scale
+        self.output_zero_point = output_zero_point
+
+    def forward(self, input):
+        return torch.ops.quantized.sigmoid(
+            input, self.output_scale, self.output_zero_point
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        (
+            output_scale,
+            output_zero_point,
+        ) = mod.activation_post_process.calculate_qparams()
+        return cls(float(output_scale), int(output_zero_point))
+
+
+class Softmax(torch.nn.Softmax):
+    r"""This is the quantized version of :class:`~torch.nn.Softmax`.
+
+    Args:
+        dim: A dimension along which Softmax will be computed (so every slice along dim will sum to 1).
+        scale: quantization scale of the output tensor
+        zero_point: quantization zero point of the output tensor
+    """
+
+    def __init__(self, dim=None, scale=1.0, zero_point=0):
+        super().__init__()
+        self.dim = dim
+        self.scale = scale
+        self.zero_point = zero_point
+
+    def forward(self, input):
+        dim = self.dim
+        if dim is None:
+            stacklevel = 3
+            # Note: adding the mypy ignore on _get_softmax_dim seems less bad
+            # than making `_get_softmax_dim` an official API.
+            dim = torch.nn.functional._get_softmax_dim(  # type: ignore[attr-defined]
+                "softmax", input.dim(), stacklevel
+            )
+        return torch.ops.quantized.softmax(input, dim, self.scale, self.zero_point)
+
+    def _get_name(self):
+        return "QuantizedSoftmax"
+
+    @staticmethod
+    def from_float(mod, use_precomputed_fake_quant=False):
+        scale, zero_point = mod.activation_post_process.calculate_qparams()
+        return Softmax(mod.dim, float(scale), int(zero_point))
+
+    @classmethod
+    def from_reference(cls, mod, scale, zero_point):
+        return cls(mod.dim, float(scale), int(zero_point))
+
+
+class MultiheadAttention(torch.ao.nn.quantizable.MultiheadAttention):
+    _FLOAT_MODULE = torch.ao.nn.quantizable.MultiheadAttention
+
+    def _get_name(self):
+        return "QuantizedMultiheadAttention"
+
+    @classmethod
+    def from_float(cls, other):
+        # The whole flow is float -> observed -> quantized
+        # This class does observed -> quantized only
+        raise NotImplementedError(
+            "It looks like you are trying to convert a "
+            "non-observed MHA module. Please, see "
+            "the examples on quantizable MHAs."
+        )
+
+    @classmethod
+    def from_observed(cls, other):
+        converted = torch.ao.quantization.convert(
+            other,
+            mapping=None,
+            inplace=False,
+            remove_qconfig=True,
+            convert_custom_config_dict=None,
+        )
+        converted.__class__ = cls
+        # Remove the parameters for the bias_k and bias_v to quantize them
+        # TODO: This is a potential source of accuracy drop.
+        #       quantized cat takes the scale and zp of the first
+        #       element, which might lose the precision in the bias_k
+        #       and the bias_v (which are cat'ed with k/v being first).
+        if converted.bias_k is not None:
+            bias_k = converted._parameters.pop("bias_k")
+            sc, zp = torch._choose_qparams_per_tensor(bias_k, reduce_range=False)
+            bias_k = torch.quantize_per_tensor(bias_k, sc, zp, torch.quint8)
+            setattr(converted, "bias_k", bias_k)  # noqa: B010
+
+        if converted.bias_v is not None:
+            bias_v = converted._parameters.pop("bias_v")
+            sc, zp = torch._choose_qparams_per_tensor(
+                bias_k,  # type: ignore[possibly-undefined]
+                reduce_range=False,
+            )
+            bias_v = torch.quantize_per_tensor(bias_v, sc, zp, torch.quint8)
+            setattr(converted, "bias_v", bias_v)  # noqa: B010
+
+        del converted.in_proj_weight
+        del converted.in_proj_bias
+
+        return converted
+
+
+class PReLU(torch.nn.Module):
+    r"""This is the quantized equivalent of :class:`~torch.nn.PReLU`.
+
+    Args:
+        scale: quantization scale of the output tensor
+        zero_point: quantization zero point of the output tensor
+        num_parameters: number of parameters: 1, or the number of channels at input. Default: 1
+    """
+
+    def __init__(
+        self, output_scale: float, output_zero_point: int, num_parameters: int = 1
+    ) -> None:
+        super().__init__()
+        self.num_parameters = num_parameters
+        self.scale = output_scale
+        self.zero_point = output_zero_point
+        w = torch.randn(num_parameters, dtype=torch.float)
+        qw = torch.quantize_per_tensor(w, scale=1.0, zero_point=0, dtype=torch.quint8)
+        self.set_weight(qw)
+
+    def set_weight(self, w: torch.Tensor) -> None:
+        self.weight = w
+
+    def forward(self, input: torch.Tensor) -> torch.Tensor:
+        return torch.ops.quantized.prelu(
+            input, self.weight, self.scale, self.zero_point
+        )
+
+    def _get_name(self):
+        return "QuantizedPReLU"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        scale, zero_point = mod.activation_post_process.calculate_qparams()
+        qprelu = cls(float(scale), int(zero_point), mod.num_parameters)
+        float_wt = mod.weight.float()
+        observer = mod.qconfig.weight()
+        observer(float_wt)
+        if observer.dtype != torch.quint8:
+            warn(
+                f"PReLU's weight observer should have dtype quint8 but got {observer.dtype}",
+                stacklevel=2,
+            )
+        wt_scale, wt_zp = observer.calculate_qparams()
+        qweight = torch.quantize_per_tensor(
+            float_wt, float(wt_scale), int(wt_zp), torch.quint8
+        )
+        qprelu.set_weight(qweight)
+        return qprelu
+
+    @classmethod
+    def from_reference(cls, mod, scale, zero_point):
+        qprelu = cls(float(scale), int(zero_point), mod.num_parameters)
+        float_wt = mod.weight.float()
+        observer = mod.qconfig.weight()
+        observer(float_wt)
+        if observer.dtype != torch.quint8:
+            warn(
+                f"PReLU's weight observer should have dtype quint8 but got {observer.dtype}",
+                stacklevel=2,
+            )
+        wt_scale, wt_zp = observer.calculate_qparams()
+        qweight = torch.quantize_per_tensor(
+            float_wt, float(wt_scale), int(wt_zp), torch.quint8
+        )
+        qprelu.set_weight(qweight)
+        return qprelu
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/batchnorm.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/batchnorm.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad648743084e087326d872d16a73536523b69676
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/batchnorm.py
@@ -0,0 +1,128 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.ao.nn.intrinsic as nni
+
+
+__all__ = ["BatchNorm2d", "BatchNorm3d"]
+
+
+class _BatchNorm(torch.nn.modules.batchnorm._BatchNorm):
+    def __init__(
+        self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(num_features, eps, momentum, True, True, **factory_kwargs)
+        self.register_buffer("scale", torch.tensor(1.0, **factory_kwargs))
+        self.register_buffer("zero_point", torch.tensor(0, **factory_kwargs))
+
+    @staticmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        activation_post_process = mod.activation_post_process
+        if type(mod) is cls._NNI_BN_RELU_MODULE:
+            mod = mod[0]
+        scale, zero_point = activation_post_process.calculate_qparams()
+        new_mod = cls(mod.num_features, mod.eps)
+        new_mod.weight = mod.weight
+        new_mod.bias = mod.bias
+        new_mod.running_mean = mod.running_mean
+        new_mod.running_var = mod.running_var
+        new_mod.scale = scale
+        new_mod.zero_point = zero_point
+        return new_mod
+
+    @classmethod
+    def from_reference(cls, bn, output_scale, output_zero_point):
+        qbn = cls(
+            bn.num_features,
+            bn.eps,
+            bn.momentum,
+            device=bn.weight.device,
+            dtype=bn.weight.dtype,
+        )
+        qbn.weight = bn.weight
+        qbn.bias = bn.bias
+        qbn.running_mean = bn.running_mean
+        qbn.running_var = bn.running_var
+        qbn.scale = output_scale
+        qbn.zero_point = output_zero_point
+        return qbn
+
+
+class BatchNorm2d(_BatchNorm):
+    r"""This is the quantized version of :class:`~torch.nn.BatchNorm2d`."""
+
+    _NNI_BN_RELU_MODULE = nni.BNReLU2d
+
+    def __init__(
+        self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(num_features, eps, momentum, **factory_kwargs)
+
+    def _get_name(self):
+        return "QuantizedBatchNorm2d"
+
+    def _check_input_dim(self, input):
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 4:
+            raise ValueError("Input shape must be `(N, C, H, W)`!")
+
+    def forward(self, input: torch.Tensor) -> torch.Tensor:
+        # disabling this since this is not symbolically traceable
+        # self._check_input_dim(input)
+        return torch.ops.quantized.batch_norm2d(
+            input,
+            self.weight,
+            self.bias,
+            self.running_mean,
+            self.running_var,
+            self.eps,
+            self.scale,
+            self.zero_point,
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        return _BatchNorm.from_float(
+            cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+
+class BatchNorm3d(_BatchNorm):
+    r"""This is the quantized version of :class:`~torch.nn.BatchNorm3d`."""
+
+    _NNI_BN_RELU_MODULE = nni.BNReLU3d
+
+    def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(num_features, eps, momentum, **factory_kwargs)
+
+    def _get_name(self):
+        return "QuantizedBatchNorm3d"
+
+    def _check_input_dim(self, input):
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 5:
+            raise ValueError("Input shape must be `(N, C, H, W)`!")
+
+    def forward(self, input: torch.Tensor) -> torch.Tensor:
+        # disabling this since this is not symbolically traceable
+        # self._check_input_dim(input)
+        return torch.ops.quantized.batch_norm3d(
+            input,
+            self.weight,
+            self.bias,
+            self.running_mean,
+            self.running_var,
+            self.eps,
+            self.scale,
+            self.zero_point,
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        return _BatchNorm.from_float(
+            cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/conv.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/conv.py
new file mode 100644
index 0000000000000000000000000000000000000000..83e0b95e421fa1928a9568c71519d49f2e784da1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/conv.py
@@ -0,0 +1,1247 @@
+# mypy: allow-untyped-defs
+r"""Quantized convolution modules."""
+
+from typing import ClassVar, Literal
+
+import torch
+import torch.ao.nn.intrinsic as nni
+import torch.ao.nn.intrinsic.qat as nniqat
+import torch.nn as nn
+import torch.nn.functional as F
+from torch._ops import ops
+from torch.nn.common_types import _size_1_t
+from torch.nn.modules.utils import _pair, _single, _triple
+from torch.nn.utils import fuse_conv_bn_weights
+
+from .utils import _quantize_weight, WeightedQuantizedModule
+
+
+__all__ = [
+    "Conv1d",
+    "Conv2d",
+    "Conv3d",
+    "ConvTranspose1d",
+    "ConvTranspose2d",
+    "ConvTranspose3d",
+]
+
+_SUPPORTED_PADDING = {"zeros", "reflect"}
+
+
+def _reverse_repeat_padding(padding: list[int]) -> list[int]:
+    _reversed_padding_repeated_twice: list[int] = []
+    N = len(padding)
+    for idx in range(N):
+        _reversed_padding_repeated_twice.extend(padding[N - idx - 1] for _ in range(2))
+    return _reversed_padding_repeated_twice
+
+
+class _ConvNd(WeightedQuantizedModule):
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        # All subclasses have this signature - See PR #49702s
+        raise NotImplementedError
+
+    def _init(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride,
+        padding,
+        dilation,
+        transposed,
+        output_padding,
+        groups,
+        bias,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__()
+
+        if out_channels <= 0:
+            raise ValueError(f"out_channels must be greater than 0, got {out_channels}")
+        if in_channels % groups != 0:
+            raise ValueError("in_channels must be divisible by groups")
+        if out_channels % groups != 0:
+            raise ValueError("out_channels must be divisible by groups")
+        self.in_channels = in_channels
+        self.out_channels = out_channels
+        self.kernel_size = kernel_size
+        self.stride = stride
+        self.padding = padding
+        self.dilation = dilation
+        self.transposed = transposed
+        self.output_padding = output_padding
+        self.groups = groups
+        if padding_mode not in _SUPPORTED_PADDING:
+            raise ValueError(
+                f"'padding_mode' {padding_mode} is not supported by quantized convolution"
+            )
+        self.padding_mode = padding_mode
+        # Initialize as NCHW. set_weight will internally transpose to NHWC.
+        if self.transposed:
+            weight_shape = [in_channels, out_channels // self.groups]
+        else:
+            weight_shape = [out_channels, in_channels // self.groups]
+        qweight = torch._empty_affine_quantized(
+            weight_shape + list(kernel_size),
+            scale=1,
+            zero_point=0,
+            dtype=torch.qint8,
+            **{k: v for k, v in factory_kwargs.items() if k != "dtype"},
+        )
+        bias_float = (
+            torch.zeros(
+                out_channels,
+                dtype=torch.float,
+                **{k: v for k, v in factory_kwargs.items() if k != "dtype"},
+            )
+            if bias
+            else None
+        )
+
+        self.set_weight_bias(qweight, bias_float)
+        self.scale = 1.0
+        self.zero_point = 0
+
+    def set_weight_bias(self, qweight, bias_float):
+        raise NotImplementedError
+
+    def bias(self):
+        raise NotImplementedError
+
+    def _weight_bias(self):
+        raise NotImplementedError
+
+    def extra_repr(self):
+        s = (
+            "{in_channels}, {out_channels}, kernel_size={kernel_size}"
+            ", stride={stride}, scale={scale}, zero_point={zero_point}"
+        )
+        if self.padding != (0,) * len(self.padding):
+            s += ", padding={padding}"
+        if self.dilation != (1,) * len(self.dilation):
+            s += ", dilation={dilation}"
+        if self.output_padding != (0,) * len(self.output_padding):
+            s += ", output_padding={output_padding}"
+        if self.groups != 1:
+            s += ", groups={groups}"
+        if self.bias() is None:
+            s += ", bias=False"
+        return s.format(**self.__dict__)
+
+    # ===== Serialization methods =====
+    # The special consideration here is that we have to unpack the weights into
+    # their regular QTensor form for serialization. Packed weights should not
+    # live outside the process in which they were created, rather they should be
+    # derived from the QTensor weight.
+    #   self
+    #   |--- weight : Tensor
+    #   |--- bias : Tensor
+    #
+    # TODO: maybe change to this when https://github.com/pytorch/pytorch/pull/32958 is landed
+    #   self
+    #   |--- _packed_params : Conv2dPackedParamsBase or Conv3dPackedParamsBase
+    def _save_to_state_dict(self, destination, prefix, keep_vars):
+        super()._save_to_state_dict(destination, prefix, keep_vars)
+        (w, b) = self._weight_bias()
+        destination[prefix + "weight"] = w
+        destination[prefix + "bias"] = b
+        destination[prefix + "scale"] = torch.tensor(self.scale)
+        destination[prefix + "zero_point"] = torch.tensor(self.zero_point)
+
+    @torch.jit.export
+    def __getstate__(self):
+        (w, b) = self._weight_bias()
+        return (
+            self.in_channels,
+            self.out_channels,
+            self.kernel_size,
+            self.stride,
+            self.padding,
+            self.dilation,
+            self.transposed,
+            self.output_padding,
+            self.groups,
+            self.padding_mode,
+            w,
+            b,
+            self.scale,
+            self.zero_point,
+            self.training,
+        )
+
+    # ===== Deserialization methods =====
+    # Counterpart to the serialization methods, we must pack the serialized
+    # QTensor weight into its packed format for use by the FBGEMM ops.
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        self.set_weight_bias(state_dict[prefix + "weight"], state_dict[prefix + "bias"])
+        state_dict.pop(prefix + "weight")
+        state_dict.pop(prefix + "bias")
+        self.scale = float(state_dict[prefix + "scale"])
+        state_dict.pop(prefix + "scale")
+        self.zero_point = int(state_dict[prefix + "zero_point"])
+        state_dict.pop(prefix + "zero_point")
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+    @torch.jit.export
+    def __setstate__(self, state):
+        self.in_channels = state[0]
+        self.out_channels = state[1]
+        self.kernel_size = state[2]
+        self.stride = state[3]
+        self.padding = state[4]
+        self.dilation = state[5]
+        self.transposed = state[6]
+        self.output_padding = state[7]
+        self.groups = state[8]
+        self.padding_mode = state[9]
+        self.set_weight_bias(state[10], state[11])
+        self.scale = state[12]
+        self.zero_point = state[13]
+        self.training = state[14]
+
+    def __deepcopy__(self, memo):
+        new_instance = type(self).__new__(type(self))
+        torch.nn.Module.__init__(new_instance)
+        state = self.__getstate__()
+        new_instance.__setstate__(state)
+        return new_instance
+
+    def __copy__(self):
+        return self.__deepcopy__({})
+
+    @classmethod
+    def get_qconv(cls, mod, activation_post_process, weight_post_process=None):
+        r"""Creates a qconv object and returns it."""
+        if weight_post_process is None:
+            weight_post_process = mod.qconfig.weight()
+        weight_post_process(mod.weight)
+        if weight_post_process.dtype != torch.qint8:
+            raise AssertionError(
+                f"Weight observer must have a dtype of qint8, got {weight_post_process.dtype}"
+            )
+        qweight = _quantize_weight(mod.weight.float(), weight_post_process)
+        # the __init__ call used is the one from derived classes and not the one from _ConvNd
+        qconv = cls(
+            mod.in_channels,
+            mod.out_channels,
+            mod.kernel_size,
+            mod.stride,
+            mod.padding,
+            mod.dilation,
+            mod.groups,
+            mod.bias is not None,
+            mod.padding_mode,
+        )
+        qconv.set_weight_bias(qweight, mod.bias)
+        if (
+            activation_post_process is None
+            or activation_post_process.dtype == torch.float
+        ):
+            return qconv  # dynamic quantization doesn't need scale/zero_point
+        else:
+            act_scale, act_zp = activation_post_process.calculate_qparams()
+            qconv.scale = float(act_scale)
+            qconv.zero_point = int(act_zp)
+            return qconv
+
+    @staticmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        if hasattr(mod, "weight_fake_quant"):
+            # assert type(mod) is cls.__QAT_MODULE, " nnq." + cls.__name__ + \
+            # ".from_float only works for " + cls.__QAT_MODULE.__name__
+            if type(mod) is cls._NNIQAT_CONV_BN_MODULE:
+                mod.weight, mod.bias = fuse_conv_bn_weights(
+                    mod.weight,
+                    mod.bias,
+                    mod.bn.running_mean,
+                    mod.bn.running_var,
+                    mod.bn.eps,
+                    mod.bn.weight,
+                    mod.bn.bias,
+                )
+            if not hasattr(mod, "activation_post_process"):
+                raise AssertionError("Input QAT module must have observer attached")
+            weight_post_process = mod.weight_fake_quant
+            activation_post_process = mod.activation_post_process
+        else:
+            if type(mod) is not cls._FLOAT_MODULE:
+                raise AssertionError(
+                    f"nnq.{cls.__name__}.from_float only works for "
+                    f"{cls._FLOAT_MODULE.__name__} but got: {type(mod).__name__}"
+                )
+            if not hasattr(mod, "qconfig"):
+                raise AssertionError("Input float module must have qconfig defined.")
+            activation_post_process = (
+                None
+                if not hasattr(mod, "activation_post_process")
+                else mod.activation_post_process
+            )
+            if type(mod) in [
+                cls._NNI_CONV_RELU_MODULE,
+                cls._NNI_CONV_ADD_MODULE,
+                cls._NNI_CONV_ADD_RELU_MODULE,
+            ]:
+                mod = mod[0]
+            weight_post_process = mod.qconfig.weight()
+        return cls.get_qconv(mod, activation_post_process, weight_post_process)
+
+    @classmethod
+    def from_reference(cls, ref_qconv, output_scale, output_zero_point):
+        r"""Create a (fbgemm/qnnpack) quantized module from a reference quantized module
+        Args:
+            ref_qconv (Module): a reference quantized  module, either produced by torch.ao.quantization
+                                utilities or provided by the user
+            output_scale (float): scale for output Tensor
+            output_zero_point (int): zero point for output Tensor
+        """
+        qconv = cls(
+            ref_qconv.in_channels,
+            ref_qconv.out_channels,
+            ref_qconv.kernel_size,  # type: ignore[arg-type]
+            ref_qconv.stride,  # type: ignore[arg-type]
+            ref_qconv.padding,  # type: ignore[arg-type]
+            ref_qconv.dilation,  # type: ignore[arg-type]
+            ref_qconv.groups,
+            ref_qconv.bias is not None,  # type: ignore[arg-type]
+            ref_qconv.padding_mode,
+            device=ref_qconv.weight.device,
+            dtype=ref_qconv.weight.dtype,
+        )
+        qweight = ref_qconv.get_quantized_weight()
+        qconv.set_weight_bias(qweight, ref_qconv.bias)
+        qconv.scale = float(output_scale)
+        qconv.zero_point = int(output_zero_point)
+        return qconv
+
+
+class Conv1d(_ConvNd):
+    r"""Applies a 1D convolution over a quantized input signal composed of
+    several quantized input planes.
+
+    For details on input arguments, parameters, and implementation see
+    :class:`~torch.nn.Conv1d`.
+
+    .. note::
+        Only `zeros` is supported for the :attr:`padding_mode` argument.
+
+    .. note::
+        Only `torch.quint8` is supported for the input data type.
+
+
+    Attributes:
+        weight (Tensor):     packed tensor derived from the learnable weight
+                             parameter.
+        scale (Tensor):      scalar for the output scale
+        zero_point (Tensor): scalar for the output zero point
+
+    See :class:`~torch.nn.Conv1d` for other attributes.
+
+    Examples::
+
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
+        >>> m = nn.quantized.Conv1d(16, 33, 3, stride=2)
+        >>> input = torch.randn(20, 16, 100)
+        >>> # quantize input to quint8
+        >>> # xdoctest: +SKIP
+        >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0,
+        ...                                     dtype=torch.quint8)
+        >>> output = m(q_input)
+
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.Conv1d]] = nn.Conv1d
+    _NNIQAT_CONV_BN_MODULE: ClassVar[type[nn.Module] | None] = nniqat.ConvBn1d
+    _NNI_CONV_RELU_MODULE: ClassVar[type[nn.Module] | None] = nni.ConvReLU1d
+    _NNI_CONV_ADD_MODULE: ClassVar[type[nn.Module] | None] = None
+    _NNI_CONV_ADD_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
+
+    def __init__(
+        self,
+        in_channels: int,
+        out_channels: int,
+        kernel_size: _size_1_t,
+        stride: _size_1_t = 1,
+        padding: _size_1_t = 0,
+        dilation: _size_1_t = 1,
+        groups: int = 1,
+        bias: bool = True,
+        padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
+        device=None,
+        dtype=None,
+    ):
+        factory_kwargs = {"device": device, "dtype": dtype}
+        kernel_size = _single(kernel_size)
+        stride = _single(stride)
+
+        padding = padding if isinstance(padding, str) else _single(padding)
+        dilation = _single(dilation)
+
+        # Subclasses of _ConvNd needs to call _init rather than __init__. See
+        # discussion on PR #49702
+        super()._init(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            False,
+            _single(0),
+            groups,
+            bias,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _get_name(self):
+        return "QuantizedConv1d"
+
+    def set_weight_bias(self, w: torch.Tensor, b: torch.Tensor | None) -> None:
+        if self.padding_mode == "zeros":
+            self._packed_params = torch.ops.quantized.conv1d_prepack(
+                w, b, self.stride, self.padding, self.dilation, self.groups
+            )
+        else:
+            self._packed_params = torch.ops.quantized.conv1d_prepack(
+                w, b, self.stride, _pair(0), self.dilation, self.groups
+            )
+
+    def _weight_bias(self):
+        w, b = torch.ops.quantized.conv1d_unpack(self._packed_params)
+        return w, b
+
+    def weight(self):
+        return self._weight_bias()[0]
+
+    def bias(self):
+        return self._weight_bias()[1]
+
+    def forward(self, input):
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 3:
+            raise ValueError("Input shape must be `(N, C, L)`!")
+        if self.padding_mode != "zeros":
+            # Padding in Conv1d is stored as (p, p), need to get (p,)
+            _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding[:1])
+            input = F.pad(
+                input, _reversed_padding_repeated_twice, mode=self.padding_mode
+            )
+        return ops.quantized.conv1d(
+            input, self._packed_params, self.scale, self.zero_point
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a quantized module from a float module or qparams_dict.
+
+        Args:
+            mod (Module): a float module, either produced by torch.ao.quantization
+              utilities or provided by the user
+        """
+        return _ConvNd.from_float(
+            cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+
+class Conv2d(_ConvNd):
+    r"""Applies a 2D convolution over a quantized input signal composed of
+    several quantized input planes.
+
+    For details on input arguments, parameters, and implementation see
+    :class:`~torch.nn.Conv2d`.
+
+    .. note::
+        Only `zeros` is supported for the :attr:`padding_mode` argument.
+
+    .. note::
+        Only `torch.quint8` is supported for the input data type.
+
+
+    Attributes:
+        weight (Tensor):     packed tensor derived from the learnable weight
+                             parameter.
+        scale (Tensor):      scalar for the output scale
+        zero_point (Tensor): scalar for the output zero point
+
+    See :class:`~torch.nn.Conv2d` for other attributes.
+
+    Examples::
+
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
+        >>> # With square kernels and equal stride
+        >>> m = nn.quantized.Conv2d(16, 33, 3, stride=2)
+        >>> # non-square kernels and unequal stride and with padding
+        >>> m = nn.quantized.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
+        >>> # non-square kernels and unequal stride and with padding and dilation
+        >>> m = nn.quantized.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
+        >>> input = torch.randn(20, 16, 50, 100)
+        >>> # quantize input to quint8
+        >>> # xdoctest: +SKIP
+        >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
+        >>> output = m(q_input)
+
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
+    _NNIQAT_CONV_BN_MODULE: ClassVar[type[nn.Module] | None] = nniqat.ConvBn2d
+    _NNI_CONV_RELU_MODULE: ClassVar[type[nn.Module] | None] = nni.ConvReLU2d
+    _NNI_CONV_ADD_MODULE: ClassVar[type[nni.ConvAdd2d]] = nni.ConvAdd2d
+    _NNI_CONV_ADD_RELU_MODULE: ClassVar[type[nni.ConvAddReLU2d]] = nni.ConvAddReLU2d
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        factory_kwargs = {"device": device, "dtype": dtype}
+        kernel_size = _pair(kernel_size)
+        stride = _pair(stride)
+        padding = _pair(padding)
+        dilation = _pair(dilation)
+        # Subclasses of _ConvNd need to call _init rather than __init__. See
+        # discussion on PR #49702
+        super()._init(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            False,
+            _pair(0),
+            groups,
+            bias,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _get_name(self):
+        return "QuantizedConv2d"
+
+    def set_weight_bias(self, w: torch.Tensor, b: torch.Tensor | None) -> None:
+        if self.padding_mode == "zeros":
+            self._packed_params = torch.ops.quantized.conv2d_prepack(
+                w, b, self.stride, self.padding, self.dilation, self.groups
+            )
+        else:
+            self._packed_params = torch.ops.quantized.conv2d_prepack(
+                w, b, self.stride, _pair(0), self.dilation, self.groups
+            )
+
+    def _weight_bias(self):
+        return self._packed_params.unpack()
+
+    def weight(self):
+        return self._weight_bias()[0]
+
+    def bias(self):
+        return self._weight_bias()[1]
+
+    def forward(self, input):
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 4:
+            raise ValueError("Input shape must be `(N, C, H, W)`!")
+        if self.padding_mode != "zeros":
+            _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
+            input = F.pad(
+                input, _reversed_padding_repeated_twice, mode=self.padding_mode
+            )
+        return ops.quantized.conv2d(
+            input, self._packed_params, self.scale, self.zero_point
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a quantized module from a float module or qparams_dict.
+
+        Args:
+            mod (Module): a float module, either produced by torch.ao.quantization
+              utilities or provided by the user
+        """
+        return _ConvNd.from_float(
+            cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+
+class Conv3d(_ConvNd):
+    r"""Applies a 3D convolution over a quantized input signal composed of
+    several quantized input planes.
+
+    For details on input arguments, parameters, and implementation see
+    :class:`~torch.nn.Conv3d`.
+
+    .. note::
+        Only `zeros` is supported for the :attr:`padding_mode` argument.
+
+    .. note::
+        Only `torch.quint8` is supported for the input data type.
+
+
+    Attributes:
+        weight (Tensor):     packed tensor derived from the learnable weight
+                             parameter.
+        scale (Tensor):      scalar for the output scale
+        zero_point (Tensor): scalar for the output zero point
+
+    See :class:`~torch.nn.Conv3d` for other attributes.
+
+    Examples::
+
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
+        >>> # With square kernels and equal stride
+        >>> m = nn.quantized.Conv3d(16, 33, 3, stride=2)
+        >>> # non-square kernels and unequal stride and with padding
+        >>> m = nn.quantized.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2))
+        >>> # non-square kernels and unequal stride and with padding and dilation
+        >>> m = nn.quantized.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2), dilation=(1, 2, 2))
+        >>> input = torch.randn(20, 16, 56, 56, 56)
+        >>> # quantize input to quint8
+        >>> # xdoctest: +SKIP
+        >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
+        >>> output = m(q_input)
+
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
+    _NNIQAT_CONV_BN_MODULE: ClassVar[type[nn.Module] | None] = nniqat.ConvBn3d
+    _NNI_CONV_RELU_MODULE: ClassVar[type[nn.Module] | None] = nni.ConvReLU3d
+    _NNI_CONV_ADD_MODULE: ClassVar[type[nn.Module] | None] = None
+    _NNI_CONV_ADD_RELU_MODULE: ClassVar[type[nn.Module] | None] = None
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        if padding_mode == "reflect":
+            raise AssertionError("Conv3d does not support reflection padding")
+        factory_kwargs = {"device": device, "dtype": dtype}
+        kernel_size = _triple(kernel_size)
+        stride = _triple(stride)
+        padding = _triple(padding)
+        dilation = _triple(dilation)
+        # Subclasses of _ConvNd need to call _init rather than __init__. See
+        # discussion on PR #49702
+        super()._init(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            False,
+            _triple(0),
+            groups,
+            bias,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _get_name(self):
+        return "QuantizedConv3d"
+
+    def set_weight_bias(self, w: torch.Tensor, b: torch.Tensor | None) -> None:
+        if self.padding_mode == "zeros":
+            self._packed_params = torch.ops.quantized.conv3d_prepack(
+                w, b, self.stride, self.padding, self.dilation, self.groups
+            )
+        else:
+            self._packed_params = torch.ops.quantized.conv3d_prepack(
+                w, b, self.stride, _triple(0), self.dilation, self.groups
+            )
+
+    def _weight_bias(self):
+        return self._packed_params.unpack()
+
+    def weight(self):
+        return self._weight_bias()[0]
+
+    def bias(self):
+        return self._weight_bias()[1]
+
+    def forward(self, input):
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 5:
+            raise ValueError("Input shape must be `(N, C, D, H, W)`!")
+        if self.padding_mode != "zeros":
+            _reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
+            input = F.pad(
+                input, _reversed_padding_repeated_twice, mode=self.padding_mode
+            )
+        return ops.quantized.conv3d(
+            input, self._packed_params, self.scale, self.zero_point
+        )
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a quantized module from a float module or qparams_dict.
+
+        Args:
+            mod (Module): a float module, either produced by torch.ao.quantization
+              utilities or provided by the user
+        """
+        return _ConvNd.from_float(
+            cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
+        )
+
+
+# === Transposed Convolutions ===
+
+
+class _ConvTransposeNd(_ConvNd):
+    _FLOAT_MODULE: ClassVar[type[nn.modules.conv._ConvNd]]
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride,
+        padding,
+        dilation,
+        transposed,
+        output_padding,
+        groups,
+        bias,
+        padding_mode,
+        device=None,
+        dtype=None,
+    ):
+        if padding_mode != "zeros":
+            raise ValueError(
+                f'Only "zeros" padding mode is supported for {self.__class__.__name__}'
+            )
+        factory_kwargs = {"device": device, "dtype": dtype}
+        # Subclasses of _ConvNd need to call _init rather than __init__. See
+        # discussion on PR #49702
+        super()._init(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            transposed,
+            output_padding,
+            groups,
+            bias,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _input_padding(
+        self, kernel_size: list[int], dilation: list[int], padding: list[int]
+    ) -> list[int]:
+        res = torch.jit.annotate(list[int], [])
+        for kdx in range(len(kernel_size)):
+            pad = dilation[kdx] * (kernel_size[kdx] - 1) - padding[kdx]
+            res.append(pad)
+        return res
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):  # type: ignore[override]
+        r"""Creates a quantized module from a float module or qparams_dict.
+        Args:
+            mod (Module): a float module, either produced by torch.ao.quantization
+              utilities or provided by the user
+        """
+        # derived classes override cls._FLOAT_MODULE attribute
+        msg = (
+            " nnq."
+            + cls.__name__
+            + ".from_float only works for "
+            + cls._FLOAT_MODULE.__name__  # type: ignore[attr-defined]
+        )
+        if type(mod) is not cls._FLOAT_MODULE:
+            raise AssertionError(msg)
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined.")
+        weight_post_process = mod.qconfig.weight()  # type: ignore[operator, union-attr]
+        weight_post_process(mod.weight)
+        if weight_post_process.dtype != torch.qint8:
+            raise AssertionError(
+                f"Weight observer must have a dtype of qint8, got {weight_post_process.dtype}"
+            )
+        qweight = _quantize_weight(mod.weight.float(), weight_post_process)
+        # the __init__ call used is the one from derived classes and not the one from _ConvTransposeNd
+        # pyrefly: ignore [missing-argument]
+        qconv = cls(
+            mod.in_channels,
+            mod.out_channels,
+            mod.kernel_size,  # type: ignore[call-arg]
+            mod.stride,
+            mod.padding,
+            mod.output_padding,
+            mod.groups,
+            mod.bias is not None,
+            mod.dilation,
+            mod.padding_mode,
+        )
+        qconv.set_weight_bias(qweight, mod.bias)
+        if (
+            not hasattr(mod, "activation_post_process")
+            or mod.activation_post_process.dtype == torch.float
+        ):
+            return qconv  # dynamic quantization doesn't need scale/zero_point
+        else:
+            act_scale, act_zp = mod.activation_post_process.calculate_qparams()  # type: ignore[operator, union-attr]
+            qconv.scale = float(act_scale)
+            qconv.zero_point = int(act_zp)
+            return qconv
+
+    @staticmethod
+    def from_reference(cls, ref_qconvt, output_scale, output_zero_point):  # type: ignore[override]
+        r"""Create a (fbgemm/qnnpack) quantized module from a reference quantized module
+        Args:
+            ref_qconvt (Module): a reference quantized  module, either produced by torch.ao.quantization
+                                 utilities or provided by the user
+            output_scale (float): scale for output Tensor
+            output_zero_point (int): zero point for output Tensor
+        """
+        qconv = cls(
+            ref_qconvt.in_channels,
+            ref_qconvt.out_channels,
+            ref_qconvt.kernel_size,  # type: ignore[arg-type]
+            ref_qconvt.stride,  # type: ignore[arg-type]
+            ref_qconvt.padding,  # type: ignore[arg-type]
+            ref_qconvt.output_padding,  # type: ignore[arg-type]
+            ref_qconvt.groups,
+            ref_qconvt.bias is not None,  # type: ignore[arg-type]
+            ref_qconvt.dilation,  # type: ignore[arg-type]
+            ref_qconvt.padding_mode,
+            device=ref_qconvt.weight.device,
+            dtype=ref_qconvt.weight.dtype,
+        )
+        qweight = ref_qconvt.get_quantized_weight()
+        qconv.set_weight_bias(qweight, ref_qconvt.bias)
+        qconv.scale = float(output_scale)
+        qconv.zero_point = int(output_zero_point)
+        return qconv
+
+
+class ConvTranspose1d(_ConvTransposeNd):
+    r"""Applies a 1D transposed convolution operator over an input image
+    composed of several input planes.
+    For details on input arguments, parameters, and implementation see
+    :class:`~torch.nn.ConvTranspose1d`.
+
+    .. note:: Currently only the QNNPACK engine is implemented.
+        Please, set the `torch.backends.quantized.engine = 'qnnpack'`
+
+    For special notes, please, see :class:`~torch.ao.nn.quantized.Conv1d`
+
+    Attributes:
+        weight (Tensor):     packed tensor derived from the learnable weight
+                             parameter.
+        scale (Tensor):      scalar for the output scale
+        zero_point (Tensor): scalar for the output zero point
+    See :class:`~torch.nn.ConvTranspose2d` for other attributes.
+
+    Examples::
+
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
+        >>> torch.backends.quantized.engine = 'qnnpack'
+        >>> from torch.ao.nn import quantized as nnq
+        >>> # With square kernels and equal stride
+        >>> m = nnq.ConvTranspose1d(16, 33, 3, stride=2)
+        >>> # non-square kernels and unequal stride and with padding
+        >>> m = nnq.ConvTranspose1d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
+        >>> input = torch.randn(20, 16, 50)
+        >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
+        >>> output = m(q_input)
+        >>> # exact output size can be also specified as an argument
+        >>> input = torch.randn(1, 16, 12)
+        >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
+        >>> downsample = nnq.Conv1d(16, 16, 3, stride=2, padding=1)
+        >>> upsample = nnq.ConvTranspose1d(16, 16, 3, stride=2, padding=1)
+        >>> h = downsample(q_input)
+        >>> h.size()
+        torch.Size([1, 16, 6])
+        >>> # xdoctest: +SKIP("FIXME: output_size is not a parameter)
+        >>> output = upsample(h, output_size=input.size())
+        >>> output.size()
+        torch.Size([1, 16, 12])
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.ConvTranspose1d]] = nn.ConvTranspose1d
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        output_padding=0,
+        groups=1,
+        bias=True,
+        dilation=1,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        factory_kwargs = {"device": device, "dtype": dtype}
+        kernel_size = _single(kernel_size)
+        stride = _single(stride)
+        padding = _single(padding)
+        dilation = _single(dilation)
+        output_padding = _single(output_padding)
+
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            True,
+            output_padding,
+            groups,
+            bias,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _get_name(self):
+        return "QuantizedConvTranspose1d"
+
+    def set_weight_bias(self, w: torch.Tensor, b: torch.Tensor | None) -> None:
+        self._packed_params = torch.ops.quantized.conv_transpose1d_prepack(
+            w,
+            b,
+            self.stride,
+            self.padding,
+            self.output_padding,
+            self.dilation,
+            self.groups,
+        )
+
+    def _weight_bias(self):
+        w, b = torch.ops.quantized.conv_transpose1d_unpack(self._packed_params)
+        return w, b
+
+    def weight(self):
+        (w, _) = self._weight_bias()
+        return w
+
+    def bias(self):
+        (_, b) = self._weight_bias()
+        return b
+
+    def forward(self, input):
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 3:
+            raise ValueError("Input shape must be `(N, C, L)`!")
+        return torch.ops.quantized.conv_transpose1d(
+            input, self._packed_params, self.scale, self.zero_point
+        )
+
+    @classmethod
+    def from_reference(cls, ref_qconvt, output_scale, output_zero_point):  # type: ignore[override]
+        return _ConvTransposeNd.from_reference(
+            cls, ref_qconvt, output_scale, output_zero_point
+        )
+
+
+class ConvTranspose2d(_ConvTransposeNd):
+    r"""Applies a 2D transposed convolution operator over an input image
+    composed of several input planes.
+    For details on input arguments, parameters, and implementation see
+    :class:`~torch.nn.ConvTranspose2d`.
+
+    For special notes, please, see :class:`~torch.ao.nn.quantized.Conv2d`
+
+    Attributes:
+        weight (Tensor):     packed tensor derived from the learnable weight
+                             parameter.
+        scale (Tensor):      scalar for the output scale
+        zero_point (Tensor): scalar for the output zero point
+    See :class:`~torch.nn.ConvTranspose2d` for other attributes.
+
+    Examples::
+
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
+        >>> # QNNPACK or FBGEMM as backend
+        >>> torch.backends.quantized.engine = 'qnnpack'
+        >>> # With square kernels and equal stride
+        >>> import torch.ao.nn.quantized as nnq
+        >>> m = nnq.ConvTranspose2d(16, 33, 3, stride=2)
+        >>> # non-square kernels and unequal stride and with padding
+        >>> m = nnq.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
+        >>> input = torch.randn(20, 16, 50, 100)
+        >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
+        >>> output = m(q_input)
+        >>> # exact output size can be also specified as an argument
+        >>> input = torch.randn(1, 16, 12, 12)
+        >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
+        >>> downsample = nnq.Conv2d(16, 16, 3, stride=2, padding=1)
+        >>> upsample = nnq.ConvTranspose2d(16, 16, 3, stride=2, padding=1)
+        >>> h = downsample(q_input)
+        >>> h.size()
+        torch.Size([1, 16, 6, 6])
+        >>> # xdoctest: +SKIP("FIXME: output_size is not a parameter)
+        >>> output = upsample(h, output_size=input.size())
+        >>> output.size()
+        torch.Size([1, 16, 12, 12])
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.ConvTranspose2d]] = nn.ConvTranspose2d
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        output_padding=0,
+        groups=1,
+        bias=True,
+        dilation=1,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        factory_kwargs = {"device": device, "dtype": dtype}
+        kernel_size = _pair(kernel_size)
+        stride = _pair(stride)
+        padding = _pair(padding)
+        dilation = _pair(dilation)
+        output_padding = _pair(output_padding)
+
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            True,
+            output_padding,
+            groups,
+            bias,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _get_name(self):
+        return "QuantizedConvTranspose2d"
+
+    def set_weight_bias(self, w: torch.Tensor, b: torch.Tensor | None) -> None:
+        self._packed_params = torch.ops.quantized.conv_transpose2d_prepack(
+            w,
+            b,
+            self.stride,
+            self.padding,
+            self.output_padding,
+            self.dilation,
+            self.groups,
+        )
+
+    def _weight_bias(self):
+        w, b = torch.ops.quantized.conv2d_unpack(self._packed_params)
+        return w, b
+
+    def weight(self):
+        (w, _) = self._weight_bias()
+        return w
+
+    def bias(self):
+        (_, b) = self._weight_bias()
+        return b
+
+    def forward(self, input):
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 4:
+            raise ValueError("Input shape must be `(N, C, H, W)`!")
+        return ops.quantized.conv_transpose2d(
+            input, self._packed_params, self.scale, self.zero_point
+        )
+
+    @classmethod
+    def from_reference(cls, ref_qconvt, output_scale, output_zero_point):  # type: ignore[override]
+        return _ConvTransposeNd.from_reference(
+            cls, ref_qconvt, output_scale, output_zero_point
+        )
+
+
+class ConvTranspose3d(_ConvTransposeNd):
+    r"""Applies a 3D transposed convolution operator over an input image
+    composed of several input planes.
+    For details on input arguments, parameters, and implementation see
+    :class:`~torch.nn.ConvTranspose3d`.
+
+    .. note:: Currently only the FBGEMM engine is implemented.
+        Please, set the `torch.backends.quantized.engine = 'fbgemm'`
+
+    For special notes, please, see :class:`~torch.ao.nn.quantized.Conv3d`
+
+    Attributes:
+        weight (Tensor):     packed tensor derived from the learnable weight
+                             parameter.
+        scale (Tensor):      scalar for the output scale
+        zero_point (Tensor): scalar for the output zero point
+    See :class:`~torch.nn.ConvTranspose3d` for other attributes.
+
+    Examples::
+
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
+        >>> torch.backends.quantized.engine = 'fbgemm'
+        >>> from torch.ao.nn import quantized as nnq
+        >>> # With cubic kernels and equal stride
+        >>> m = nnq.ConvTranspose3d(16, 33, 3, stride=2)
+        >>> # non-cubic kernels and unequal stride and with padding
+        >>> m = nnq.ConvTranspose3d(16, 33, (3, 3, 5), stride=(2, 1, 1), padding=(4, 2, 2))
+        >>> input = torch.randn(20, 16, 50, 100, 100)
+        >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
+        >>> output = m(q_input)
+        >>> # exact output size can be also specified as an argument
+        >>> input = torch.randn(1, 16, 12, 12, 12)
+        >>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
+        >>> downsample = nnq.Conv3d(16, 16, 3, stride=2, padding=1)
+        >>> upsample = nnq.ConvTranspose3d(16, 16, 3, stride=2, padding=1)
+        >>> h = downsample(q_input)
+        >>> h.size()
+        torch.Size([1, 16, 6, 6, 6])
+        >>> # xdoctest: +SKIP("FIXME: output_size is not a parameter)
+        >>> output = upsample(h, output_size=input.size())
+        >>> output.size()
+        torch.Size([1, 16, 12, 12, 12])
+    """
+
+    _FLOAT_MODULE: ClassVar[type[nn.ConvTranspose3d]] = nn.ConvTranspose3d
+
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        output_padding=0,
+        groups=1,
+        bias=True,
+        dilation=1,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+    ):
+        factory_kwargs = {"device": device, "dtype": dtype}
+        kernel_size = _triple(kernel_size)
+        stride = _triple(stride)
+        padding = _triple(padding)
+        dilation = _triple(dilation)
+        output_padding = _triple(output_padding)
+
+        super().__init__(
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            True,
+            output_padding,
+            groups,
+            bias,
+            padding_mode,
+            **factory_kwargs,
+        )
+
+    def _get_name(self):
+        return "QuantizedConvTranspose3d"
+
+    def set_weight_bias(self, w: torch.Tensor, b: torch.Tensor | None) -> None:
+        self._packed_params = torch.ops.quantized.conv_transpose3d_prepack(
+            w,
+            b,
+            self.stride,
+            self.padding,
+            self.output_padding,
+            self.dilation,
+            self.groups,
+        )
+
+    def _weight_bias(self):
+        w, b = torch.ops.quantized.conv3d_unpack(self._packed_params)
+        return w, b
+
+    def weight(self):
+        (w, _) = self._weight_bias()
+        return w
+
+    def bias(self):
+        (_, b) = self._weight_bias()
+        return b
+
+    def forward(self, input):
+        # Temporarily using len(shape) instead of ndim due to JIT issue
+        # https://github.com/pytorch/pytorch/issues/23890
+        if len(input.shape) != 5:
+            raise ValueError("Input shape must be `(N, C, T, H, W)`!")
+        return ops.quantized.conv_transpose3d(
+            input, self._packed_params, self.scale, self.zero_point
+        )
+
+    @classmethod
+    def from_reference(cls, ref_qconvt, output_scale, output_zero_point):  # type: ignore[override]
+        return _ConvTransposeNd.from_reference(
+            cls, ref_qconvt, output_scale, output_zero_point
+        )
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/dropout.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/dropout.py
new file mode 100644
index 0000000000000000000000000000000000000000..3744ca30d5a49ba92cbb86690f2683af02d594fe
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/dropout.py
@@ -0,0 +1,30 @@
+# mypy: allow-untyped-defs
+import torch
+
+
+__all__ = ["Dropout"]
+
+
+class Dropout(torch.nn.Dropout):
+    r"""This is the quantized equivalent of :class:`~torch.nn.Dropout`.
+        And this is a placeholder to enable models where fp32 tensors
+        had dropout to work with quantized tensors in train and eval mode.
+
+    Args:
+        p: probability of an element to be zeroed
+        inplace: can optionally do the operation in-place. Default: ``False``
+    """
+
+    def forward(self, input):
+        return input
+
+    def _get_name(self):
+        return "QuantizedDropout"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        return cls(mod.p, mod.inplace)
+
+    @classmethod
+    def from_reference(cls, mod, scale, zero_point):
+        return cls(mod.p, mod.inplace)
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/embedding_ops.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/embedding_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa79daa0e2873adeebcccba7107e397ddceea0d7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/embedding_ops.py
@@ -0,0 +1,425 @@
+# mypy: allow-untyped-defs
+import torch
+import torch.nn as nn
+from torch import Tensor
+from torch._jit_internal import List, Optional  # noqa: F401
+
+from .utils import _hide_packed_params_repr, _quantize_weight
+
+
+__all__ = ["EmbeddingPackedParams", "Embedding", "EmbeddingBag"]
+
+
+class EmbeddingPackedParams(torch.nn.Module):
+    _version = 1
+
+    def __init__(self, num_embeddings, embedding_dim, dtype=torch.quint8):
+        super().__init__()
+        self.dtype = dtype
+        if self.dtype in [torch.quint8, torch.quint4x2]:
+            scales = torch.ones(num_embeddings, dtype=torch.float)
+            zero_points = torch.zeros(num_embeddings, dtype=torch.float)
+            wq = torch._empty_per_channel_affine_quantized(
+                [num_embeddings, embedding_dim],
+                scales=scales,
+                zero_points=zero_points,
+                axis=0,
+                dtype=self.dtype,
+            )
+            self.set_weight(wq)
+        else:
+            raise NotImplementedError(
+                f"Unsupported dtype on quantized embedding! Supports quint8 and quint4x2. Got dtype: {dtype}"
+            )
+
+    @torch.jit.export
+    def set_weight(self, weight: torch.Tensor) -> None:
+        if self.dtype in [torch.quint8, torch.quint4x2]:
+            self._packed_weight = torch.ops.quantized.embedding_bag_prepack(weight)
+        else:
+            raise NotImplementedError(
+                "Unsupported dtype for quantized embedding prepack! Supports quint8 and quint4x2."
+            )
+
+    @torch.jit.export
+    def _weight(self):
+        if self.dtype in [torch.quint8, torch.quint4x2]:
+            return torch.ops.quantized.embedding_bag_unpack(self._packed_weight)
+        else:
+            raise NotImplementedError(
+                "Unsupported dtype for quantized embedding unpack! Supports quint8 and quint4x2."
+            )
+
+    def forward(self, x):
+        return x
+
+    # Version 1
+    #   self
+    #   |--- _packed_weight : Tensor representing weight of EmbeddingPackedParamsBase
+    #   |--- dtype : torch.dtype
+
+    def _save_to_state_dict(self, destination, prefix, keep_vars):
+        super()._save_to_state_dict(destination, prefix, keep_vars)
+        destination[prefix + "dtype"] = self.dtype
+        destination[prefix + "_packed_weight"] = self._weight()
+
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        self.dtype = state_dict[prefix + "dtype"]
+        state_dict.pop(prefix + "dtype")
+
+        weight = state_dict[prefix + "_packed_weight"]
+        state_dict.pop(prefix + "_packed_weight")
+        self.set_weight(weight)
+
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+    def __repr__(self):
+        return self._weight().__repr__()
+
+
+class Embedding(torch.nn.Module):
+    r"""
+    A quantized Embedding module with quantized packed weights as inputs.
+    We adopt the same interface as `torch.nn.Embedding`, please see
+    https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html for documentation.
+
+    Similar to :class:`~torch.nn.Embedding`, attributes will be randomly
+    initialized at module creation time and will be overwritten later
+
+    Attributes:
+        weight (Tensor): the non-learnable quantized weights of the module of
+                         shape :math:`(\text{num\_embeddings}, \text{embedding\_dim})`.
+
+    Examples::
+        >>> warnings.filterwarnings("ignore", message=".*quantized tensor creation functions")  # docs: hide
+        >>> m = nn.quantized.Embedding(num_embeddings=10, embedding_dim=12)
+        >>> indices = torch.tensor([9, 6, 5, 7, 8, 8, 9, 2, 8])
+        >>> output = m(indices)
+        >>> print(output.size())
+        torch.Size([9, 12])
+
+    """
+
+    _version = 1
+
+    def __init__(
+        self,
+        num_embeddings: int,
+        embedding_dim: int,
+        padding_idx: Optional[int] = None,
+        max_norm: Optional[float] = None,
+        norm_type: float = 2.0,
+        scale_grad_by_freq: bool = False,
+        sparse: bool = False,
+        _weight: Optional[Tensor] = None,
+        dtype=torch.quint8,
+    ) -> None:
+        super().__init__()
+        self.num_embeddings = num_embeddings
+        self.embedding_dim = embedding_dim
+        self.dtype = dtype
+
+        if _weight is None:
+            scales = torch.ones(num_embeddings, dtype=torch.float)
+            zero_points = torch.zeros(num_embeddings, dtype=torch.float)
+            qweight = torch._empty_per_channel_affine_quantized(
+                [num_embeddings, embedding_dim],
+                scales=scales,
+                zero_points=zero_points,
+                axis=0,
+                dtype=torch.quint8,
+            )
+        else:
+            expected_shape = [num_embeddings, embedding_dim]
+            if list(_weight.shape) != expected_shape:
+                raise AssertionError(
+                    f"Shape of weight does not match num_embeddings and embedding_dim: "
+                    f"expected {expected_shape}, got {list(_weight.shape)}"
+                )
+            qweight = _weight
+
+        self._packed_params = EmbeddingPackedParams(
+            num_embeddings, embedding_dim, dtype
+        )
+        self._packed_params.set_weight(qweight)
+
+    def forward(self, indices: Tensor) -> Tensor:
+        if self.dtype == torch.quint4x2:
+            return torch.ops.quantized.embedding_4bit(
+                self._packed_params._packed_weight, indices
+            )
+        else:
+            return torch.ops.quantized.embedding_byte(
+                self._packed_params._packed_weight, indices
+            )
+
+    def _get_name(self):
+        return "QuantizedEmbedding"
+
+    def __repr__(self):
+        return _hide_packed_params_repr(self, EmbeddingPackedParams)
+
+    def extra_repr(self):
+        extra_repr_str = (
+            f"num_embeddings={self.num_embeddings}, embedding_dim={self.embedding_dim}, "
+            f"dtype={self._packed_params.dtype}, qscheme={self.weight().qscheme()}"
+        )
+
+        return extra_repr_str
+
+    def set_weight(self, w: torch.Tensor) -> None:
+        self._packed_params.set_weight(w)
+
+    def weight(self):
+        return self._packed_params._weight()
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Create a quantized embedding module from a float module
+
+        Args:
+            mod (Module): a float module, either produced by torch.ao.quantization
+                          utilities or provided by user
+        """
+        if hasattr(mod, "weight_fake_quant"):
+            if type(mod) is not torch.ao.nn.qat.Embedding:
+                raise AssertionError(
+                    "nnq."
+                    + cls.__name__
+                    + ".from_float "
+                    + "with fake quant only works for "
+                    + torch.ao.nn.qat.Embedding.__name__
+                )
+            weight_observer = mod.weight_fake_quant
+        else:
+            if type(mod) is not nn.Embedding:
+                raise AssertionError(
+                    "nnq."
+                    + cls.__name__
+                    + ".from_float only works for "
+                    + nn.Embedding.__name__
+                )
+            if not hasattr(mod, "qconfig"):
+                raise AssertionError(
+                    "Embedding input float module must have qconfig defined"
+                )
+            from torch.ao.quantization import float_qparams_weight_only_qconfig
+
+            if mod.qconfig is not None and mod.qconfig.weight is not None:  # type: ignore[union-attr]
+                weight_observer = mod.qconfig.weight()  # type: ignore[union-attr, operator]
+            else:
+                weight_observer = float_qparams_weight_only_qconfig.weight()
+
+        dtype = weight_observer.dtype
+        is_float_qparams_qconfig = (
+            weight_observer.qscheme == torch.per_channel_affine_float_qparams
+        )
+        if not is_float_qparams_qconfig:
+            raise AssertionError(
+                "Embedding quantization is only supported with float_qparams_weight_only_qconfig."
+            )
+
+        if dtype != torch.quint8 and dtype != torch.quint4x2:
+            raise AssertionError(
+                f"The only supported dtype for nnq.Embedding is torch.quint8 and torch.quint4x2, got {dtype}"
+            )
+
+        # Run the observer to calculate qparams.
+        weight_observer(mod.weight)
+        qweight = _quantize_weight(mod.weight.float(), weight_observer)
+
+        # Create quantized Embedding module and pass in the quantized weight
+        qembedding = Embedding(mod.num_embeddings, mod.embedding_dim)
+        qembedding.set_weight(qweight)
+        return qembedding
+
+    @classmethod
+    def from_reference(cls, ref_embedding):
+        qembedding = cls(
+            ref_embedding.num_embeddings,
+            ref_embedding.embedding_dim,
+            ref_embedding.padding_idx,
+            ref_embedding.max_norm,
+            ref_embedding.norm_type,
+            ref_embedding.scale_grad_by_freq,
+            ref_embedding.sparse,
+            ref_embedding.get_quantized_weight(),
+            ref_embedding.weight_dtype,
+        )
+        return qembedding
+
+
+class EmbeddingBag(Embedding):
+    r"""
+    A quantized EmbeddingBag module with quantized packed weights as inputs.
+    We adopt the same interface as `torch.nn.EmbeddingBag`, please see
+    https://pytorch.org/docs/stable/generated/torch.nn.EmbeddingBag.html for documentation.
+
+    Similar to :class:`~torch.nn.EmbeddingBag`, attributes will be randomly
+    initialized at module creation time and will be overwritten later
+
+    Attributes:
+        weight (Tensor): the non-learnable quantized weights of the module of
+                         shape :math:`(\text{num\_embeddings}, \text{embedding\_dim})`.
+
+    Examples::
+        >>> m = nn.quantized.EmbeddingBag(num_embeddings=10, embedding_dim=12, include_last_offset=True, mode='sum')
+        >>> indices = torch.tensor([9, 6, 5, 7, 8, 8, 9, 2, 8, 6, 6, 9, 1, 6, 8, 8, 3, 2, 3, 6, 3, 6, 5, 7, 0, 8, 4, 6, 5, 8, 2, 3])
+        >>> offsets = torch.tensor([0, 19, 20, 28, 28, 32])
+        >>> output = m(indices, offsets)
+        >>> print(output.size())
+        torch.Size([5, 12])
+
+    """
+
+    _version = 1
+
+    def __init__(
+        self,
+        num_embeddings: int,
+        embedding_dim: int,
+        max_norm: Optional[float] = None,
+        norm_type: float = 2.0,
+        scale_grad_by_freq: bool = False,
+        mode: str = "sum",
+        sparse: bool = False,
+        _weight: Optional[Tensor] = None,
+        include_last_offset: bool = False,
+        dtype=torch.quint8,
+    ) -> None:
+        super().__init__(num_embeddings, embedding_dim, _weight=_weight, dtype=dtype)
+
+        self.mode = mode
+        self.pruned_weights = False
+        self.include_last_offset = include_last_offset
+        self.dtype = dtype
+
+    def forward(
+        self,
+        indices: Tensor,
+        offsets: Optional[Tensor] = None,
+        per_sample_weights: Optional[Tensor] = None,
+        compressed_indices_mapping: Optional[Tensor] = None,
+    ) -> Tensor:
+        if self.dtype == torch.quint4x2:
+            return torch.ops.quantized.embedding_bag_4bit(
+                self._packed_params._packed_weight,
+                indices,
+                offsets,
+                False,
+                0,
+                self.pruned_weights,
+                per_sample_weights,
+                compressed_indices_mapping,
+                self.include_last_offset,
+            )
+        else:
+            return torch.ops.quantized.embedding_bag_byte(
+                self._packed_params._packed_weight,
+                indices,
+                offsets,
+                False,
+                0,
+                self.pruned_weights,
+                per_sample_weights,
+                compressed_indices_mapping,
+                self.include_last_offset,
+            )
+
+    def _get_name(self):
+        return "QuantizedEmbeddingBag"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Create a quantized embedding_bag module from a float module
+
+        Args:
+            mod (Module): a float module, either produced by torch.ao.quantization
+                          utilities or provided by user
+        """
+        if hasattr(mod, "weight_fake_quant"):
+            weight_observer = mod.weight_fake_quant
+        else:
+            if type(mod) is not nn.EmbeddingBag:
+                raise AssertionError(
+                    "nnq."
+                    + cls.__name__
+                    + ".from_float only works for "
+                    + nn.EmbeddingBag.__name__
+                )
+            if not hasattr(mod, "qconfig"):
+                raise AssertionError(
+                    "EmbeddingBag input float module must have qconfig defined"
+                )
+            from torch.ao.quantization.qconfig import float_qparams_weight_only_qconfig
+
+            if mod.qconfig is not None and mod.qconfig.weight is not None:  # type: ignore[union-attr]
+                weight_observer = mod.qconfig.weight()  # type: ignore[union-attr, operator]
+            else:
+                weight_observer = float_qparams_weight_only_qconfig.weight()
+
+        dtype = weight_observer.dtype
+        is_float_qparams_qconfig = (
+            weight_observer.qscheme == torch.per_channel_affine_float_qparams
+        )
+        if not is_float_qparams_qconfig:
+            raise AssertionError(
+                "EmbeddingBag quantization is only supported with float_qparams_weight_only_qconfig."
+            )
+
+        if dtype != torch.quint8 and dtype != torch.quint4x2:
+            raise AssertionError(
+                f"The only supported dtype for nnq.EmbeddingBag is torch.quint8 and torch.quint4x2, got {dtype}"
+            )
+
+        # Run the observer to calculate qparams.
+        weight_observer(mod.weight)
+        qweight = _quantize_weight(mod.weight.float(), weight_observer)
+
+        # Create quantized EmbeddingBag module and pass in the quantized weight
+        qembedding_bag = EmbeddingBag(
+            mod.num_embeddings,
+            mod.embedding_dim,
+            max_norm=mod.max_norm,
+            norm_type=mod.norm_type,
+            scale_grad_by_freq=mod.scale_grad_by_freq,
+            mode=mod.mode,
+            sparse=mod.sparse,
+            include_last_offset=mod.include_last_offset,
+            dtype=dtype,
+        )
+        qembedding_bag.set_weight(qweight)
+        return qembedding_bag
+
+    @classmethod
+    def from_reference(cls, ref_embedding_bag):
+        qembedding_bag = cls(
+            ref_embedding_bag.num_embeddings,
+            ref_embedding_bag.embedding_dim,
+            ref_embedding_bag.max_norm,
+            ref_embedding_bag.norm_type,
+            ref_embedding_bag.scale_grad_by_freq,
+            ref_embedding_bag.mode,
+            ref_embedding_bag.sparse,
+            ref_embedding_bag.get_quantized_weight(),
+            ref_embedding_bag.include_last_offset,
+            ref_embedding_bag.weight_dtype,
+        )
+        return qembedding_bag
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/functional_modules.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/functional_modules.py
new file mode 100644
index 0000000000000000000000000000000000000000..24315323f5467c334b3d3697528c88b20173c60d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/functional_modules.py
@@ -0,0 +1,300 @@
+# mypy: allow-untyped-defs
+
+import torch
+from torch import Tensor
+from torch._ops import ops
+
+
+__all__ = ["FloatFunctional", "FXFloatFunctional", "QFunctional"]
+
+
+class FloatFunctional(torch.nn.Module):
+    r"""State collector class for float operations.
+
+    The instance of this class can be used instead of the ``torch.`` prefix for
+    some operations. See example usage below.
+
+    .. note::
+
+        This class does not provide a ``forward`` hook. Instead, you must use
+        one of the underlying functions (e.g. ``add``).
+
+    Examples::
+
+        >>> f_add = FloatFunctional()
+        >>> a = torch.tensor(3.0)
+        >>> b = torch.tensor(4.0)
+        >>> f_add.add(a, b)  # Equivalent to ``torch.add(a, b)``
+
+    Valid operation names:
+        - add
+        - cat
+        - mul
+        - add_relu
+        - add_scalar
+        - mul_scalar
+    """
+
+    def __init__(self) -> None:
+        super().__init__()
+        self.activation_post_process = torch.nn.Identity()
+
+    def forward(self, x):
+        raise RuntimeError(
+            "FloatFunctional is not intended to use the "
+            + "'forward'. Please use the underlying operation"
+        )
+
+    r"""Operation equivalent to ``torch.add(Tensor, Tensor)``"""
+
+    def add(self, x: Tensor, y: Tensor) -> Tensor:
+        r = torch.add(x, y)
+        r = self.activation_post_process(r)
+        return r
+
+    r"""Operation equivalent to ``torch.add(Tensor, float)``"""
+
+    def add_scalar(self, x: Tensor, y: float) -> Tensor:
+        r = torch.add(x, y)
+        # Note: this operation is not observed because the observation is not
+        # needed for the quantized op.
+        return r
+
+    r"""Operation equivalent to ``torch.mul(Tensor, Tensor)``"""
+
+    def mul(self, x: Tensor, y: Tensor) -> Tensor:
+        r = torch.mul(x, y)
+        r = self.activation_post_process(r)
+        return r
+
+    r"""Operation equivalent to ``torch.mul(Tensor, float)``"""
+
+    def mul_scalar(self, x: Tensor, y: float) -> Tensor:
+        r = torch.mul(x, y)
+        # Note: this operation is not observed because the observation is not
+        # needed for the quantized op.
+        return r
+
+    r"""Operation equivalent to ``torch.cat``"""
+
+    def cat(self, x: list[Tensor], dim: int = 0) -> Tensor:
+        r = torch.cat(x, dim=dim)
+        r = self.activation_post_process(r)
+        return r
+
+    r"""Operation equivalent to ``relu(torch.add(x,y))``"""
+
+    def add_relu(self, x: Tensor, y: Tensor) -> Tensor:
+        r = torch.add(x, y)
+        r = torch.nn.functional.relu(r)
+        r = self.activation_post_process(r)
+        return r
+
+    r"""Operation equivalent to ``torch.matmul(Tensor, Tensor)``"""
+
+    def matmul(self, x: Tensor, y: Tensor) -> Tensor:
+        r = torch.matmul(x, y)
+        r = self.activation_post_process(r)
+        return r
+
+
+class FXFloatFunctional(torch.nn.Module):
+    r"""module to replace FloatFunctional module before FX graph mode quantization,
+    since activation_post_process will be inserted in top level module directly
+
+    Valid operation names:
+        - add
+        - cat
+        - mul
+        - add_relu
+        - add_scalar
+        - mul_scalar
+    """
+
+    def forward(self, x):
+        raise RuntimeError(
+            "FloatFunctional is not intended to use the "
+            + "'forward'. Please use the underlying operation"
+        )
+
+    r"""Operation equivalent to ``torch.add(Tensor, Tensor)``"""
+
+    def add(self, x: Tensor, y: Tensor) -> Tensor:
+        r = torch.add(x, y)
+        return r
+
+    r"""Operation equivalent to ``torch.add(Tensor, float)``"""
+
+    def add_scalar(self, x: Tensor, y: float) -> Tensor:
+        r = torch.add(x, y)
+        return r
+
+    r"""Operation equivalent to ``torch.mul(Tensor, Tensor)``"""
+
+    def mul(self, x: Tensor, y: Tensor) -> Tensor:
+        r = torch.mul(x, y)
+        return r
+
+    r"""Operation equivalent to ``torch.mul(Tensor, float)``"""
+
+    def mul_scalar(self, x: Tensor, y: float) -> Tensor:
+        r = torch.mul(x, y)
+        return r
+
+    r"""Operation equivalent to ``torch.cat``"""
+
+    def cat(self, x: list[Tensor], dim: int = 0) -> Tensor:
+        r = torch.cat(x, dim=dim)
+        return r
+
+    r"""Operation equivalent to ``relu(torch.add(x,y))``"""
+
+    def add_relu(self, x: Tensor, y: Tensor) -> Tensor:
+        r = torch.add(x, y)
+        r = torch.nn.functional.relu(r)
+        return r
+
+    r"""Operation equivalent to ``torch.matmul(Tensor, Tensor)``"""
+
+    def matmul(self, x: Tensor, y: Tensor) -> Tensor:
+        r = torch.matmul(x, y)
+        return r
+
+
+class QFunctional(torch.nn.Module):
+    r"""Wrapper class for quantized operations.
+
+    The instance of this class can be used instead of the
+    ``torch.ops.quantized`` prefix. See example usage below.
+
+    .. note::
+
+        This class does not provide a ``forward`` hook. Instead, you must use
+        one of the underlying functions (e.g. ``add``).
+
+    Examples::
+
+        >>> q_add = QFunctional()
+        >>> # xdoctest: +SKIP
+        >>> a = torch.quantize_per_tensor(torch.tensor(3.0), 1.0, 0, torch.qint32)
+        >>> b = torch.quantize_per_tensor(torch.tensor(4.0), 1.0, 0, torch.qint32)
+        >>> q_add.add(a, b)  # Equivalent to ``torch.ops.quantized.add(a, b, 1.0, 0)``
+
+    Valid operation names:
+        - add
+        - cat
+        - mul
+        - add_relu
+        - add_scalar
+        - mul_scalar
+    """
+
+    def __init__(self) -> None:
+        super().__init__()
+        self.scale = 1.0
+        self.zero_point = 0
+        self.activation_post_process = torch.nn.Identity()
+
+    def _save_to_state_dict(self, destination, prefix, keep_vars):
+        super()._save_to_state_dict(destination, prefix, keep_vars)
+        destination[prefix + "scale"] = torch.tensor(self.scale)
+        destination[prefix + "zero_point"] = torch.tensor(self.zero_point)
+
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        self.scale = float(state_dict.pop(prefix + "scale"))
+        self.zero_point = int(state_dict.pop(prefix + "zero_point"))
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+    def _get_name(self):
+        return "QFunctional"
+
+    def extra_repr(self):
+        return f"scale={self.scale}, zero_point={self.zero_point}"
+
+    def forward(self, x):
+        raise RuntimeError(
+            "Functional is not intended to use the "
+            + "'forward'. Please use the underlying operation"
+        )
+
+    r"""Operation equivalent to ``torch.ops.quantized.add``"""
+
+    def add(self, x: Tensor, y: Tensor) -> Tensor:
+        r = ops.quantized.add(x, y, scale=self.scale, zero_point=self.zero_point)
+        r = self.activation_post_process(r)
+        return r
+
+    r"""Operation equivalent to ``torch.ops.quantized.add(Tensor, float)``"""
+
+    def add_scalar(self, x: Tensor, y: float) -> Tensor:
+        r = ops.quantized.add_scalar(x, y)
+        # Note: this operation is not observed because the observation is not
+        # needed for the quantized op.
+        return r
+
+    r"""Operation equivalent to ``torch.ops.quantized.mul(Tensor, Tensor)``"""
+
+    def mul(self, x: Tensor, y: Tensor) -> Tensor:
+        r = ops.quantized.mul(x, y, scale=self.scale, zero_point=self.zero_point)
+        r = self.activation_post_process(r)
+        return r
+
+    r"""Operation equivalent to ``torch.ops.quantized.mul(Tensor, float)``"""
+
+    def mul_scalar(self, x: Tensor, y: float) -> Tensor:
+        r = ops.quantized.mul_scalar(x, y)
+        # Note: this operation is not observed because the observation is not
+        # needed for the quantized op.
+        return r
+
+    r"""Operation equivalent to ``torch.ops.quantized.cat``"""
+
+    def cat(self, x: list[Tensor], dim: int = 0) -> Tensor:
+        r = ops.quantized.cat(x, scale=self.scale, zero_point=self.zero_point, dim=dim)
+        r = self.activation_post_process(r)
+        return r
+
+    r"""Operation equivalent to ``torch.ops.quantized.add_relu``"""
+
+    def add_relu(self, x: Tensor, y: Tensor) -> Tensor:
+        r = ops.quantized.add_relu(x, y, scale=self.scale, zero_point=self.zero_point)
+        r = self.activation_post_process(r)
+        return r
+
+    r"""Operation equivalent to ``torch.ops.quantized.matmul(Tensor, Tensor)``"""
+
+    def matmul(self, x: Tensor, y: Tensor) -> Tensor:
+        r = ops.quantized.matmul(x, y, scale=self.scale, zero_point=self.zero_point)
+        # Note: this operation is not observed because the observation is not
+        # needed for the quantized op.
+        return r
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        if type(mod) is not FloatFunctional:
+            raise AssertionError(
+                f"QFunctional.from_float expects an instance of FloatFunctional, "
+                f"got {type(mod).__name__}"
+            )
+        scale, zero_point = mod.activation_post_process.calculate_qparams()  # type: ignore[operator]
+        new_mod = QFunctional()
+        new_mod.scale = float(scale)
+        new_mod.zero_point = int(zero_point)
+        return new_mod
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/linear.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..23d12c585535eecbec24ff879aa587f9f7e46f3a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/linear.py
@@ -0,0 +1,362 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+from collections.abc import Iterable
+
+import torch
+import torch.ao.nn.intrinsic as nni
+import torch.ao.nn.intrinsic.qat as nniqat
+import torch.nn as nn
+from torch.nn.utils.fusion import fuse_linear_bn_weights
+from torch.nn.utils.parametrize import type_before_parametrizations
+
+from .utils import _hide_packed_params_repr, _quantize_weight, WeightedQuantizedModule
+
+
+__all__ = ["LinearPackedParams", "Linear"]
+
+
+class LinearPackedParams(torch.nn.Module):
+    _version = 3
+
+    def __init__(self, dtype=torch.qint8):
+        super().__init__()
+        self.dtype = dtype
+        if self.dtype == torch.qint8:
+            wq = torch._empty_affine_quantized(
+                [1, 1], scale=1.0, zero_point=0, dtype=torch.qint8
+            )
+        elif self.dtype == torch.float16:
+            wq = torch.zeros([1, 1], dtype=torch.float)
+        self.set_weight_bias(wq, None)  # type: ignore[possibly-undefined]
+
+    @torch.jit.export
+    def set_weight_bias(self, weight: torch.Tensor, bias: torch.Tensor | None) -> None:
+        if self.dtype == torch.qint8:
+            self._packed_params = torch.ops.quantized.linear_prepack(weight, bias)
+        elif self.dtype == torch.float16:
+            self._packed_params = torch.ops.quantized.linear_prepack_fp16(weight, bias)
+        else:
+            raise RuntimeError("Unsupported dtype on dynamic quantized linear!")
+
+    @torch.jit.export
+    def _weight_bias(self):
+        if self.dtype == torch.qint8:
+            return torch.ops.quantized.linear_unpack(self._packed_params)
+        elif self.dtype == torch.float16:
+            return torch.ops.quantized.linear_unpack_fp16(self._packed_params)
+        else:
+            raise RuntimeError("Unsupported dtype on dynamic quantized linear!")
+
+    def forward(self, x):
+        return x
+
+    # Version 1
+    #   self
+    #   |--- weight : Tensor
+    #   |--- bias : Tensor
+    #
+    # Version 2
+    #   self
+    #   |--- weight : Tensor
+    #   |--- bias : Tensor
+    #   |--- dtype : torch.dtype
+    #
+    # Version 3
+    #   self
+    #   |--- _packed_params : (Tensor, Tensor) representing (weight, bias)
+    #                         of LinearPackedParams
+    #   |--- dtype : torch.dtype
+    def _save_to_state_dict(self, destination, prefix, keep_vars):
+        super()._save_to_state_dict(destination, prefix, keep_vars)
+        destination[prefix + "dtype"] = self.dtype
+        destination[prefix + "_packed_params"] = self._weight_bias()
+
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        version = local_metadata.get("version", None)
+        if version is None or version < 2:
+            self.dtype = torch.qint8
+        else:
+            self.dtype = state_dict[prefix + "dtype"]
+            state_dict.pop(prefix + "dtype")
+
+        if version is None or version < 3:
+            self.set_weight_bias(
+                state_dict[prefix + "weight"], state_dict[prefix + "bias"]
+            )
+            state_dict.pop(prefix + "weight")
+            state_dict.pop(prefix + "bias")
+
+        if version == 3:
+            weight, bias = state_dict[prefix + "_packed_params"]
+            state_dict.pop(prefix + "_packed_params")
+            self.set_weight_bias(weight, bias)
+
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+    def __repr__(self):
+        return self._weight_bias().__repr__()
+
+
+class Linear(WeightedQuantizedModule):
+    r"""
+    A quantized linear module with quantized tensor as inputs and outputs.
+    We adopt the same interface as `torch.nn.Linear`, please see
+    https://pytorch.org/docs/stable/nn.html#torch.nn.Linear for documentation.
+
+    Similar to :class:`~torch.nn.Linear`, attributes will be randomly
+    initialized at module creation time and will be overwritten later
+
+    Attributes:
+        weight (Tensor): the non-learnable quantized weights of the module of
+                         shape :math:`(\text{out\_features}, \text{in\_features})`.
+        bias (Tensor): the non-learnable bias of the module of shape :math:`(\text{out\_features})`.
+                If :attr:`bias` is ``True``, the values are initialized to zero.
+        scale: `scale` parameter of output Quantized Tensor, type: double
+        zero_point: `zero_point` parameter for output Quantized Tensor, type: long
+
+    Examples::
+
+        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
+        >>> m = nn.quantized.Linear(20, 30)
+        >>> input = torch.randn(128, 20)
+        >>> # xdoctest: +SKIP
+        >>> input = torch.quantize_per_tensor(input, 1.0, 0, torch.quint8)
+        >>> output = m(input)
+        >>> print(output.size())
+        torch.Size([128, 30])
+    """
+
+    _version = 3
+    _FLOAT_MODULE = (nn.Linear, nn.modules.linear.NonDynamicallyQuantizableLinear)
+
+    def __init__(self, in_features, out_features, bias_=True, dtype=torch.qint8):
+        super().__init__()
+        # We don't muck around with buffers or attributes or anything here
+        # to keep the module simple. *everything* is simply a Python attribute.
+        # Serialization logic is explicitly handled in the below serialization and
+        # deserialization modules
+        self.in_features = in_features
+        self.out_features = out_features
+        bias = None
+        if bias_:
+            bias = torch.zeros(out_features, dtype=torch.float)
+
+        if dtype == torch.qint8:
+            qweight = torch._empty_affine_quantized(
+                [out_features, in_features], scale=1, zero_point=0, dtype=torch.qint8
+            )
+        elif dtype == torch.float16:
+            qweight = torch.zeros([out_features, in_features], dtype=torch.float)
+        else:
+            raise RuntimeError("Unsupported dtype specified for quantized Linear!")
+
+        self._packed_params = LinearPackedParams(dtype)
+        self._packed_params.set_weight_bias(qweight, bias)
+        self.scale = 1.0
+        self.zero_point = 0
+
+    def _get_name(self):
+        return "QuantizedLinear"
+
+    def extra_repr(self):
+        return (
+            f"in_features={self.in_features}, out_features={self.out_features}, scale={self.scale}, "
+            f"zero_point={self.zero_point}, qscheme={self.weight().qscheme()}"
+        )
+
+    def __repr__(self):
+        return _hide_packed_params_repr(self, LinearPackedParams)
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        return torch.ops.quantized.linear(
+            x, self._packed_params._packed_params, self.scale, self.zero_point
+        )
+
+    # ===== Serialization methods =====
+    # The special consideration here is that we have to unpack the weights into their
+    # regular QTensor form for serialization. Packed weights should not live
+    # outside the process in which they were created, rather they should be derived
+    # from the QTensor weight.
+    #
+    # Version 1
+    #   self
+    #   |--- scale : float
+    #   |--- zero_point : int
+    #   |--- weight : Tensor
+    #   |--- bias : Tensor
+    #
+    # Version 2
+    #   self
+    #   |--- scale : float
+    #   |--- zero_point : int
+    #   |--- _packed_params : Module
+    #        |--- weight : Tensor
+    #        |--- bias : Tensor
+    #
+    # Version 3
+    #   self
+    #   |--- scale : float
+    #   |--- zero_point : int
+    #   |--- _packed_params : Module
+    #        |--- _packed_params : (Tensor, Tensor) representing weight, bias
+    #                              of LinearPackedParams C++ struct
+    #
+    def _save_to_state_dict(self, destination, prefix, keep_vars):
+        super()._save_to_state_dict(destination, prefix, keep_vars)
+        destination[prefix + "scale"] = torch.tensor(self.scale)
+        destination[prefix + "zero_point"] = torch.tensor(self.zero_point)
+
+    # ===== Deserialization methods =====
+    # Counterpart to the serialization methods, we must pack the serialized QTensor
+    # weight into its packed format for use by the FBGEMM ops.
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        self.scale = float(state_dict[prefix + "scale"])
+        state_dict.pop(prefix + "scale")
+
+        self.zero_point = int(state_dict[prefix + "zero_point"])
+        state_dict.pop(prefix + "zero_point")
+
+        version = local_metadata.get("version", None)
+
+        if version is None or version == 1:
+            # We moved the parameters into a LinearPackedParameters submodule
+            weight = state_dict.pop(prefix + "weight")
+            bias = state_dict.pop(prefix + "bias")
+            state_dict.update(
+                {
+                    prefix + "_packed_params.weight": weight,
+                    prefix + "_packed_params.bias": bias,
+                }
+            )
+
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+    # Function rather than property to make sure that JIT serialization doesn't
+    # register this as an attribute
+    def _weight_bias(self):
+        return self._packed_params._weight_bias()
+
+    def weight(self):
+        return self._weight_bias()[0]
+
+    def bias(self):
+        return self._weight_bias()[1]
+
+    def set_weight_bias(self, w: torch.Tensor, b: torch.Tensor | None) -> None:
+        self._packed_params.set_weight_bias(w, b)
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Create a quantized module from an observed float module
+
+        Args:
+            mod (Module): a float module, either produced by torch.ao.quantization
+                          utilities or provided by the user
+            use_precomputed_fake_quant (bool): if True, the module will reuse min/max
+                          values from the precomputed fake quant module.
+        """
+        if hasattr(mod, "weight_fake_quant"):
+            if type_before_parametrizations(mod) == nniqat.LinearBn1d:
+                mod.weight, mod.bias = fuse_linear_bn_weights(
+                    mod.weight,
+                    mod.bias,
+                    mod.bn.running_mean,
+                    mod.bn.running_var,
+                    mod.bn.eps,
+                    mod.bn.weight,
+                    mod.bn.bias,
+                )
+            weight_post_process = mod.weight_fake_quant
+            activation_post_process = mod.activation_post_process
+        else:
+            # This function does not participate in JIT, so it is OK to ignore
+            # the type mismatch in assignment. Also, mypy has an issue with
+            # iterables not being implemented, so we are ignoring those too.
+            if not isinstance(cls._FLOAT_MODULE, Iterable):
+                # pyrefly: ignore [bad-assignment]
+                cls._FLOAT_MODULE = [cls._FLOAT_MODULE]
+            supported_modules = ", ".join(
+                [float_mod.__name__ for float_mod in cls._FLOAT_MODULE]
+            )
+            error_msg = f"nnq.{cls.__name__}.from_float only works for {supported_modules}, but got: {type(mod)}"
+            if type_before_parametrizations(mod) not in cls._FLOAT_MODULE:
+                raise AssertionError(error_msg)
+            if not hasattr(mod, "qconfig"):
+                raise AssertionError("Input float module must have qconfig defined")
+            activation_post_process = mod.activation_post_process
+            if type_before_parametrizations(mod) == nni.LinearReLU:
+                mod = mod[0]
+            weight_post_process = (
+                mod.qconfig.weight()
+                if not hasattr(mod, "weight_fake_quant")
+                else mod.weight_fake_quant
+            )
+
+        if not use_precomputed_fake_quant:
+            # Observer may not have been called yet
+            # Observer might have been called in the previous stage via PTQ algorithm e.g. AdaRound
+            weight_post_process(mod.weight)
+        dtype = weight_post_process.dtype
+        act_scale, act_zp = activation_post_process.calculate_qparams()
+        if dtype != torch.qint8:
+            raise AssertionError(
+                f"Weight observer must have dtype torch.qint8, got {dtype}"
+            )
+        qweight = _quantize_weight(mod.weight.float(), weight_post_process)
+        qlinear = cls(mod.in_features, mod.out_features, dtype=dtype)
+        qlinear.set_weight_bias(qweight, mod.bias)
+        qlinear.scale = float(act_scale)
+        qlinear.zero_point = int(act_zp)
+        return qlinear
+
+    @classmethod
+    def from_reference(cls, ref_qlinear, output_scale, output_zero_point):
+        r"""Create a (fbgemm/qnnpack) quantized module from a reference quantized module
+
+        Args:
+            ref_qlinear (Module): a reference quantized linear module, either produced by torch.ao.quantization
+                          utilities or provided by the user
+            output_scale (float): scale for output Tensor
+            output_zero_point (int): zero point for output Tensor
+        """
+        qlinear = cls(ref_qlinear.in_features, ref_qlinear.out_features)
+        qweight = ref_qlinear.get_quantized_weight()
+        qlinear.set_weight_bias(qweight, ref_qlinear.bias)
+
+        qlinear.scale = float(output_scale)
+        qlinear.zero_point = int(output_zero_point)
+        return qlinear
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/normalization.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/normalization.py
new file mode 100644
index 0000000000000000000000000000000000000000..4db2ac6e928f47236eeab43e63d399452112a263
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/normalization.py
@@ -0,0 +1,347 @@
+# mypy: allow-untyped-defs
+import torch
+
+
+__all__ = [
+    "LayerNorm",
+    "GroupNorm",
+    "InstanceNorm1d",
+    "InstanceNorm2d",
+    "InstanceNorm3d",
+]
+
+
+class LayerNorm(torch.nn.LayerNorm):
+    r"""This is the quantized version of :class:`~torch.nn.LayerNorm`.
+
+    Additional args:
+        * **scale** - quantization scale of the output, type: double.
+        * **zero_point** - quantization zero point of the output, type: long.
+
+    """
+
+    def __init__(
+        self,
+        normalized_shape,
+        weight,
+        bias,
+        scale,
+        zero_point,
+        eps=1e-5,
+        elementwise_affine=True,
+        device=None,
+        dtype=None,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(
+            normalized_shape,
+            eps=eps,
+            elementwise_affine=elementwise_affine,
+            **factory_kwargs,
+        )
+        self.weight = weight
+        self.bias = bias
+        self.register_buffer("scale", torch.tensor(scale, **factory_kwargs))
+        self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs))
+
+    def forward(self, input):
+        return torch.ops.quantized.layer_norm(
+            input,
+            self.normalized_shape,
+            weight=self.weight,
+            bias=self.bias,
+            eps=self.eps,
+            output_scale=self.scale,
+            output_zero_point=self.zero_point,
+        )
+
+    def _get_name(self):
+        return "QuantizedLayerNorm"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        scale, zero_point = mod.activation_post_process.calculate_qparams()
+        new_mod = cls(
+            mod.normalized_shape,
+            mod.weight,
+            mod.bias,
+            float(scale),
+            int(zero_point),
+            mod.eps,
+            mod.elementwise_affine,
+        )
+        return new_mod
+
+    @classmethod
+    def from_reference(cls, mod, scale, zero_point):
+        return cls(
+            mod.normalized_shape,
+            mod.weight,
+            mod.bias,
+            float(scale),
+            int(zero_point),
+            mod.eps,
+            mod.elementwise_affine,
+        )
+
+
+class GroupNorm(torch.nn.GroupNorm):
+    r"""This is the quantized version of :class:`~torch.nn.GroupNorm`.
+
+    Additional args:
+        * **scale** - quantization scale of the output, type: double.
+        * **zero_point** - quantization zero point of the output, type: long.
+
+    """
+
+    __constants__ = ["num_groups", "num_channels", "eps", "affine"]
+
+    def __init__(
+        self,
+        num_groups,
+        num_channels,
+        weight,
+        bias,
+        scale,
+        zero_point,
+        eps=1e-5,
+        affine=True,
+        device=None,
+        dtype=None,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(num_groups, num_channels, eps, affine, **factory_kwargs)
+        self.weight = weight
+        self.bias = bias
+        self.register_buffer("scale", torch.tensor(scale, **factory_kwargs))
+        self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs))
+
+    def forward(self, input):
+        return torch.ops.quantized.group_norm(
+            input,
+            self.num_groups,
+            self.weight,
+            self.bias,
+            self.eps,
+            self.scale,
+            self.zero_point,
+        )
+
+    def _get_name(self):
+        return "QuantizedGroupNorm"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        scale, zero_point = mod.activation_post_process.calculate_qparams()
+        new_mod = cls(
+            mod.num_groups,
+            mod.num_channels,
+            mod.weight,
+            mod.bias,
+            float(scale),
+            int(zero_point),
+            mod.eps,
+            mod.affine,
+        )
+        return new_mod
+
+
+class InstanceNorm1d(torch.nn.InstanceNorm1d):
+    r"""This is the quantized version of :class:`~torch.nn.InstanceNorm1d`.
+
+    Additional args:
+        * **scale** - quantization scale of the output, type: double.
+        * **zero_point** - quantization zero point of the output, type: long.
+
+    """
+
+    def __init__(
+        self,
+        num_features,
+        weight,
+        bias,
+        scale,
+        zero_point,
+        eps=1e-5,
+        momentum=0.1,
+        affine=False,
+        track_running_stats=False,
+        device=None,
+        dtype=None,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(
+            num_features, eps, momentum, affine, track_running_stats, **factory_kwargs
+        )
+        self.weight = weight
+        self.bias = bias
+        self.register_buffer("scale", torch.tensor(scale, **factory_kwargs))
+        self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs))
+
+    def forward(self, input):
+        return torch.ops.quantized.instance_norm(
+            input, self.weight, self.bias, self.eps, self.scale, self.zero_point
+        )
+
+    def _get_name(self):
+        return "QuantizedInstanceNorm1d"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        scale, zero_point = mod.activation_post_process.calculate_qparams()
+        new_mod = cls(
+            mod.num_features,
+            mod.weight,
+            mod.bias,
+            float(scale),
+            int(zero_point),
+            mod.eps,
+            mod.affine,
+        )
+        return new_mod
+
+    @classmethod
+    def from_reference(cls, mod, scale, zero_point):
+        return cls(
+            mod.num_features,
+            mod.weight,
+            mod.bias,
+            float(scale),
+            int(zero_point),
+            mod.eps,
+            mod.affine,
+        )
+
+
+class InstanceNorm2d(torch.nn.InstanceNorm2d):
+    r"""This is the quantized version of :class:`~torch.nn.InstanceNorm2d`.
+
+    Additional args:
+        * **scale** - quantization scale of the output, type: double.
+        * **zero_point** - quantization zero point of the output, type: long.
+
+    """
+
+    def __init__(
+        self,
+        num_features,
+        weight,
+        bias,
+        scale,
+        zero_point,
+        eps=1e-5,
+        momentum=0.1,
+        affine=False,
+        track_running_stats=False,
+        device=None,
+        dtype=None,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(
+            num_features, eps, momentum, affine, track_running_stats, **factory_kwargs
+        )
+        self.weight = weight
+        self.bias = bias
+        self.register_buffer("scale", torch.tensor(scale, **factory_kwargs))
+        self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs))
+
+    def forward(self, input):
+        return torch.ops.quantized.instance_norm(
+            input, self.weight, self.bias, self.eps, self.scale, self.zero_point
+        )
+
+    def _get_name(self):
+        return "QuantizedInstanceNorm2d"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        scale, zero_point = mod.activation_post_process.calculate_qparams()
+        new_mod = cls(
+            mod.num_features,
+            mod.weight,
+            mod.bias,
+            float(scale),
+            int(zero_point),
+            mod.eps,
+            mod.affine,
+        )
+        return new_mod
+
+    @classmethod
+    def from_reference(cls, mod, scale, zero_point):
+        return cls(
+            mod.num_features,
+            mod.weight,
+            mod.bias,
+            float(scale),
+            int(zero_point),
+            mod.eps,
+            mod.affine,
+        )
+
+
+class InstanceNorm3d(torch.nn.InstanceNorm3d):
+    r"""This is the quantized version of :class:`~torch.nn.InstanceNorm3d`.
+
+    Additional args:
+        * **scale** - quantization scale of the output, type: double.
+        * **zero_point** - quantization zero point of the output, type: long.
+
+    """
+
+    def __init__(
+        self,
+        num_features,
+        weight,
+        bias,
+        scale,
+        zero_point,
+        eps=1e-5,
+        momentum=0.1,
+        affine=False,
+        track_running_stats=False,
+        device=None,
+        dtype=None,
+    ) -> None:
+        factory_kwargs = {"device": device, "dtype": dtype}
+        super().__init__(
+            num_features, eps, momentum, affine, track_running_stats, **factory_kwargs
+        )
+        self.weight = weight
+        self.bias = bias
+        self.register_buffer("scale", torch.tensor(scale, **factory_kwargs))
+        self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs))
+
+    def forward(self, input):
+        return torch.ops.quantized.instance_norm(
+            input, self.weight, self.bias, self.eps, self.scale, self.zero_point
+        )
+
+    def _get_name(self):
+        return "QuantizedInstanceNorm3d"
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        scale, zero_point = mod.activation_post_process.calculate_qparams()
+        new_mod = cls(
+            mod.num_features,
+            mod.weight,
+            mod.bias,
+            float(scale),
+            int(zero_point),
+            mod.eps,
+            mod.affine,
+        )
+        return new_mod
+
+    @classmethod
+    def from_reference(cls, mod, scale, zero_point):
+        return cls(
+            mod.num_features,
+            mod.weight,
+            mod.bias,
+            float(scale),
+            int(zero_point),
+            mod.eps,
+            mod.affine,
+        )
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/rnn.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/rnn.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0fc44d454ae1b13a2a0dbdbfe253be78b2332de
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/rnn.py
@@ -0,0 +1,62 @@
+from typing import Any
+
+import torch
+
+
+__all__ = [
+    "LSTM",
+]
+
+
+class LSTM(torch.ao.nn.quantizable.LSTM):
+    r"""A quantized long short-term memory (LSTM).
+
+    For the description and the argument types, please, refer to :class:`~torch.nn.LSTM`
+
+    Attributes:
+        layers : instances of the `_LSTMLayer`
+
+    .. note::
+        To access the weights and biases, you need to access them per layer.
+        See examples in :class:`~torch.ao.nn.quantizable.LSTM`
+
+    Examples::
+        >>> # xdoctest: +SKIP
+        >>> custom_module_config = {
+        ...     'float_to_observed_custom_module_class': {
+        ...         nn.LSTM: nn.quantizable.LSTM,
+        ...     },
+        ...     'observed_to_quantized_custom_module_class': {
+        ...         nn.quantizable.LSTM: nn.quantized.LSTM,
+        ...     }
+        ... }
+        >>> tq.prepare(model, prepare_custom_module_class=custom_module_config)
+        >>> tq.convert(model, convert_custom_module_class=custom_module_config)
+    """
+
+    _FLOAT_MODULE = torch.ao.nn.quantizable.LSTM  # type: ignore[assignment]
+
+    def _get_name(self) -> str:
+        return "QuantizedLSTM"
+
+    @classmethod
+    def from_float(cls, *args: Any, **kwargs: Any) -> None:
+        # The whole flow is float -> observed -> quantized
+        # This class does observed -> quantized only
+        raise NotImplementedError(
+            "It looks like you are trying to convert a "
+            "non-observed LSTM module. Please, see "
+            "the examples on quantizable LSTMs."
+        )
+
+    @classmethod
+    def from_observed(cls: type["LSTM"], other: torch.ao.nn.quantizable.LSTM) -> "LSTM":
+        if not isinstance(other, cls._FLOAT_MODULE):  # type: ignore[has-type]
+            raise AssertionError(
+                f"Expected module type {cls._FLOAT_MODULE}, got {type(other)}"
+            )
+        converted = torch.ao.quantization.convert(
+            other, inplace=False, remove_qconfig=True
+        )
+        converted.__class__ = cls
+        return converted
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/utils.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..51853335e5639eb355d00c9b60d278ab0ce3e054
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/utils.py
@@ -0,0 +1,144 @@
+# mypy: allow-untyped-defs
+import abc
+import collections
+import itertools
+
+import torch
+from torch.nn.modules.module import _addindent
+
+
+__all__ = [
+    "WeightedQuantizedModule",
+]
+
+
+class WeightedQuantizedModule(torch.nn.Module, metaclass=abc.ABCMeta):
+    """Wrapper for quantized modules that can be lowered from reference modules."""
+
+    @classmethod
+    @abc.abstractmethod
+    def from_reference(cls, ref_module, output_scale, output_zero_point):
+        raise NotImplementedError
+
+
+def _get_weight_observer(observer):
+    # FakeQuantize observer
+    if hasattr(observer, "activation_post_process"):
+        observer = observer.activation_post_process
+    # UniformQuantizationObserverBase observer
+    return observer
+
+
+def _needs_weight_clamping(observer, dtype):
+    observer = _get_weight_observer(observer)
+    if dtype in [torch.qint8, torch.quint8, torch.qint32]:
+        info = torch.iinfo(dtype)
+        return observer.quant_min > info.min or observer.quant_max < info.max
+    return False
+
+
+def _clamp_weights(qweight, observer, scale, zp):
+    if not _needs_weight_clamping(observer, qweight.dtype):
+        return qweight
+
+    observer = _get_weight_observer(observer)
+    min_, max_ = observer.quant_min, observer.quant_max
+
+    # Doing this because can't use torch.ops.quantized.clamp() with per_channel qscheme yet.
+    qw_int_max = torch.clone(qweight.int_repr()).fill_(max_)
+    qw_int_min = torch.clone(qweight.int_repr()).fill_(min_)
+    qw_int = torch.minimum(torch.maximum(qweight.int_repr(), qw_int_min), qw_int_max)
+
+    if observer.qscheme in [torch.per_tensor_symmetric, torch.per_tensor_affine]:
+        qweight = torch._make_per_tensor_quantized_tensor(
+            qw_int, scale.item(), zp.item()
+        )
+    elif observer.qscheme in [
+        torch.per_channel_symmetric,
+        torch.per_channel_affine,
+        torch.per_channel_affine_float_qparams,
+    ]:
+        qweight = torch._make_per_channel_quantized_tensor(
+            qw_int, scale, zp, axis=observer.ch_axis
+        )
+    else:
+        raise ValueError("Unexpected qscheme " + observer.qscheme)
+    return qweight
+
+
+def _quantize_weight(float_wt, observer):
+    wt_scale, wt_zp = observer.calculate_qparams()
+    if observer.qscheme in [torch.per_tensor_symmetric, torch.per_tensor_affine]:
+        qweight = torch.quantize_per_tensor(
+            float_wt, float(wt_scale), int(wt_zp), torch.qint8
+        )
+        qweight = _clamp_weights(qweight, observer, wt_scale, wt_zp)
+    elif observer.qscheme in [torch.per_channel_symmetric, torch.per_channel_affine]:
+        wt_axis = observer.ch_axis
+        qweight = torch.quantize_per_channel(
+            float_wt,
+            wt_scale.to(torch.double),
+            wt_zp.to(torch.int64),
+            wt_axis,
+            torch.qint8,
+        )
+        qweight = _clamp_weights(qweight, observer, wt_scale, wt_zp)
+    elif observer.qscheme == torch.per_channel_affine_float_qparams:
+        qweight = torch.quantize_per_channel(
+            float_wt,
+            wt_scale.to(torch.float),
+            wt_zp.to(torch.float),
+            observer.ch_axis,
+            observer.dtype,
+        )
+        qweight = _clamp_weights(qweight, observer, wt_scale, wt_zp)
+    else:
+        raise ValueError("Unexpected qscheme " + observer.qscheme)
+    return qweight
+
+
+def _ntuple_from_first(n):
+    """Converts the argument to a tuple of size n
+    with the first element repeated."""
+
+    def parse(x):
+        while isinstance(x, collections.abc.Sequence):
+            if len(x) == n:
+                break
+            x = x[0]
+        return tuple(itertools.repeat(x, n))
+
+    return parse
+
+
+def _hide_packed_params_repr(self, params):
+    # We don't want to show `PackedParams` children, hence custom
+    # `__repr__`. This is the same as nn.Module.__repr__, except the check
+    # for the `params module`.
+    extra_lines = []
+    extra_repr = self.extra_repr()
+    # empty string will be split into list ['']
+    if extra_repr:
+        extra_lines = extra_repr.split("\n")
+    child_lines = []
+    for key, module in self._modules.items():
+        if isinstance(module, params):
+            continue
+        mod_str = repr(module)
+        mod_str = _addindent(mod_str, 2)
+        child_lines.append("(" + key + "): " + mod_str)
+    lines = extra_lines + child_lines
+
+    main_str = self._get_name() + "("
+    if lines:
+        # simple one-liner info, which most builtin Modules will use
+        if len(extra_lines) == 1 and not child_lines:
+            main_str += extra_lines[0]
+        else:
+            main_str += "\n  " + "\n  ".join(lines) + "\n"
+
+    main_str += ")"
+    return main_str
+
+
+_pair_from_first = _ntuple_from_first(2)
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1e15e9c1516d30f7ca9ee47b21b267533de75b6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/__init__.py
@@ -0,0 +1,19 @@
+from .modules import *  # noqa: F403
+
+
+__all__ = [
+    "Linear",
+    "Conv1d",
+    "Conv2d",
+    "Conv3d",
+    "ConvTranspose1d",
+    "ConvTranspose2d",
+    "ConvTranspose3d",
+    "RNNCell",
+    "LSTMCell",
+    "GRUCell",
+    "LSTM",
+    "GRU",
+    "Embedding",
+    "EmbeddingBag",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e072c1f4c034f1ac4032ee505770926f1a4b5a5a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbe97c22f5a46a5eafc1432075fc57dd44c3aa8d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__init__.py
@@ -0,0 +1,29 @@
+from .conv import (
+    Conv1d,
+    Conv2d,
+    Conv3d,
+    ConvTranspose1d,
+    ConvTranspose2d,
+    ConvTranspose3d,
+)
+from .linear import Linear
+from .rnn import GRU, GRUCell, LSTM, LSTMCell, RNNCell
+from .sparse import Embedding, EmbeddingBag
+
+
+__all__ = [
+    "Linear",
+    "Conv1d",
+    "Conv2d",
+    "Conv3d",
+    "ConvTranspose1d",
+    "ConvTranspose2d",
+    "ConvTranspose3d",
+    "RNNCell",
+    "LSTMCell",
+    "GRUCell",
+    "LSTM",
+    "GRU",
+    "Embedding",
+    "EmbeddingBag",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8d8b63298b251745e0073ef0dae47a59a5890a2
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/conv.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/conv.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d17a1cba01379927b53dd62bcd87b7c61b86efeb
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/conv.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/linear.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/linear.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c979cfdc7425f4adc9e40356f69839cd1ed6882c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/linear.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/rnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/rnn.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f8fba710b43b579340a49cb34f734809752bded1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/rnn.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/sparse.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/sparse.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ecc654cba8f366ea2abdfc6ada012a6cd803fbfa
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/sparse.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6bc51ca4349a464c98031f664f3941e486ef8073
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/conv.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/conv.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e69270211eedc43fb608a42757e2e9d65763d96
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/conv.py
@@ -0,0 +1,527 @@
+# mypy: allow-untyped-defs
+from typing import Any, Literal
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.nn.common_types import _size_1_t
+
+from .utils import ReferenceQuantizedModule
+
+
+__all__ = [
+    "Conv1d",
+    "Conv2d",
+    "Conv3d",
+    "ConvTranspose1d",
+    "ConvTranspose2d",
+    "ConvTranspose3d",
+]
+
+
+class _ConvNd(torch.nn.modules.conv._ConvNd, ReferenceQuantizedModule):
+    """A reference version of nn.quantized.Conv2d
+    we will not pack the parameters in this module, since weight packing is an
+    optimization for quantized backends supported in PyTorch (fbgemm/qnnpack),
+    this is useful when user want to use this module in other backends like Glow.
+    """
+
+    __annotations__ = {"bias": torch.Tensor | None}
+    _IS_REFERENCE = True
+
+    @staticmethod
+    def from_float(cls, float_conv, weight_qparams):
+        qref_conv = cls(
+            float_conv.in_channels,
+            float_conv.out_channels,
+            float_conv.kernel_size,  # type: ignore[arg-type]
+            float_conv.stride,  # type: ignore[arg-type]
+            float_conv.padding,  # type: ignore[arg-type]
+            float_conv.dilation,  # type: ignore[arg-type]
+            float_conv.groups,
+            float_conv.bias is not None,  # type: ignore[arg-type]
+            float_conv.padding_mode,
+            device=float_conv.weight.device,
+            dtype=float_conv.weight.dtype,
+            weight_qparams=weight_qparams,
+        )
+        qref_conv.weight = torch.nn.Parameter(float_conv.weight.detach())
+        if float_conv.bias is not None:
+            qref_conv.bias = torch.nn.Parameter(float_conv.bias.detach())
+        return qref_conv
+
+
+class Conv1d(_ConvNd, nn.Conv1d):
+    def __init__(
+        self,
+        in_channels: int,
+        out_channels: int,
+        kernel_size: _size_1_t,
+        stride: _size_1_t = 1,
+        padding: _size_1_t = 0,
+        dilation: _size_1_t = 1,
+        groups: int = 1,
+        bias: bool = True,
+        padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
+        device=None,
+        dtype=None,
+        weight_qparams: dict[str, Any] | None = None,
+    ):
+        nn.Conv1d.__init__(
+            self,
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            groups,
+            bias,
+            padding_mode,
+            device,
+            dtype,
+        )
+        self._init_weight_qparams(weight_qparams, device)
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        """
+        we have:
+        w(float) -- quant - dequant \
+        x(float) ------------- F.conv1d ---
+
+        In the full model, we will see
+        w(float) -- quant - *dequant \
+        x -- quant --- *dequant --  *F.conv1d --- *quant - dequant
+        and the backend should be able to fuse the ops with `*` into a quantized conv1d
+        """
+        weight_quant_dequant = self.get_weight()
+
+        result = F.conv1d(
+            x,
+            weight_quant_dequant,
+            self.bias,
+            self.stride,
+            self.padding,
+            self.dilation,
+            self.groups,
+        )
+        return result
+
+    def _get_name(self):
+        return "QuantizedConv1d(Reference)"
+
+    @classmethod
+    def from_float(cls, float_conv, weight_qparams):  # type: ignore[override]
+        return _ConvNd.from_float(cls, float_conv, weight_qparams)
+
+
+class Conv2d(_ConvNd, nn.Conv2d):
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+        weight_qparams: dict[str, Any] | None = None,
+    ):
+        nn.Conv2d.__init__(
+            self,
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            groups,
+            bias,
+            # pyrefly: ignore [bad-argument-type]
+            padding_mode,
+            device,
+            dtype,
+        )
+        self._init_weight_qparams(weight_qparams, device)
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        """
+        we have:
+        w(float) -- quant - dequant \
+        x(float) ------------- F.conv2d ---
+
+        In the full model, we will see
+        w(float) -- quant - *dequant \
+        x -- quant --- *dequant --  *F.conv2d --- *quant - dequant
+        and the backend should be able to fuse the ops with `*` into a quantized conv2d
+        """
+        weight_quant_dequant = self.get_weight()
+
+        result = F.conv2d(
+            x,
+            weight_quant_dequant,
+            self.bias,
+            self.stride,
+            self.padding,
+            self.dilation,
+            self.groups,
+        )
+        return result
+
+    def _get_name(self):
+        return "QuantizedConv2d(Reference)"
+
+    @classmethod
+    def from_float(cls, float_conv, weight_qparams):  # type: ignore[override]
+        return _ConvNd.from_float(cls, float_conv, weight_qparams)
+
+
+class Conv3d(_ConvNd, nn.Conv3d):
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        dilation=1,
+        groups=1,
+        bias=True,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+        weight_qparams: dict[str, Any] | None = None,
+    ):
+        nn.Conv3d.__init__(
+            self,
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            dilation,
+            groups,
+            bias,
+            # pyrefly: ignore [bad-argument-type]
+            padding_mode,
+            device,
+            dtype,
+        )
+        self._init_weight_qparams(weight_qparams, device)
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        """
+        we have:
+        w(float) -- quant - dequant \
+        x(float) ------------- F.conv3d ---
+
+        In the full model, we will see
+        w(float) -- quant - *dequant \
+        x -- quant --- *dequant --  *F.conv3d --- *quant - dequant
+        and the backend should be able to fuse the ops with `*` into a quantized conv3d
+        """
+        weight_quant_dequant = self.get_weight()
+
+        result = F.conv3d(
+            x,
+            weight_quant_dequant,
+            self.bias,
+            self.stride,
+            self.padding,
+            self.dilation,
+            self.groups,
+        )
+        return result
+
+    def _get_name(self):
+        return "QuantizedConv3d(Reference)"
+
+    @classmethod
+    def from_float(cls, float_conv, weight_qparams):  # type: ignore[override]
+        return _ConvNd.from_float(cls, float_conv, weight_qparams)
+
+
+class _ConvTransposeNd(_ConvNd, torch.nn.modules.conv._ConvTransposeNd):
+    """A reference version of nn.quantized.ConvTranspose2d
+    we will not pack the parameters in this module, since weight packing is an
+    optimization for quantized backends supported in PyTorch (fbgemm/qnnpack),
+    this is useful when user want to use this module in other backends like Glow.
+    """
+
+    @staticmethod
+    def from_float(cls, float_conv, weight_qparams):
+        qref_conv = cls(
+            float_conv.in_channels,
+            float_conv.out_channels,
+            float_conv.kernel_size,  # type: ignore[arg-type]
+            float_conv.stride,  # type: ignore[arg-type]
+            float_conv.padding,  # type: ignore[arg-type]
+            float_conv.output_padding,  # type: ignore[arg-type]
+            float_conv.groups,
+            float_conv.bias is not None,  # type: ignore[arg-type]
+            float_conv.dilation,  # type: ignore[arg-type]
+            float_conv.padding_mode,
+            device=float_conv.weight.device,
+            dtype=float_conv.weight.dtype,
+            weight_qparams=weight_qparams,
+        )
+        qref_conv.weight = torch.nn.Parameter(float_conv.weight.detach())
+        if float_conv.bias is not None:
+            qref_conv.bias = torch.nn.Parameter(float_conv.bias.detach())
+        return qref_conv
+
+
+class ConvTranspose1d(_ConvTransposeNd, nn.ConvTranspose1d):
+    def __init__(
+        self,
+        in_channels: int,
+        out_channels: int,
+        kernel_size: _size_1_t,
+        stride: _size_1_t = 1,
+        padding: _size_1_t = 0,
+        output_padding: _size_1_t = 0,
+        groups: int = 1,
+        bias: bool = True,
+        dilation: _size_1_t = 1,
+        padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
+        device=None,
+        dtype=None,
+        weight_qparams: dict[str, Any] | None = None,
+    ):
+        nn.ConvTranspose1d.__init__(
+            self,
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            output_padding,
+            groups,
+            bias,
+            dilation,
+            padding_mode,
+            device,
+            dtype,
+        )
+        self._init_weight_qparams(weight_qparams, device)
+
+    def forward(
+        self, x: torch.Tensor, output_size: list[int] | None = None
+    ) -> torch.Tensor:
+        """
+        we have:
+        w(float) -- quant - dequant \
+        x(float) ------------- F.convTranspose1d ---
+        In the full model, we will see
+        w(float) -- quant - *dequant \
+        x -- quant --- *dequant --  *F.convTranspose1d --- *quant - dequant
+        and the backend should be able to fuse the ops with `*` into a quantized conv1d
+        """
+
+        if not isinstance(self.padding, tuple):
+            raise AssertionError(
+                f"Expected self.padding to be a tuple, got {type(self.padding)}"
+            )
+        # One cannot replace List by Tuple or Sequence in "_output_padding" because
+        # TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
+        output_padding = self._output_padding(
+            input,  # type: ignore[arg-type]
+            output_size,
+            self.stride,  # type: ignore[arg-type]
+            self.padding,  # type: ignore[arg-type]
+            self.kernel_size,  # type: ignore[arg-type]
+            self.dilation,  # type: ignore[arg-type]
+        )
+
+        weight_quant_dequant = self.get_weight()
+        result = F.conv_transpose1d(
+            x,
+            weight_quant_dequant,
+            self.bias,
+            self.stride,
+            self.padding,
+            output_padding,
+            self.groups,
+            self.dilation,
+        )
+        return result
+
+    def _get_name(self):
+        return "QuantizedConvTranspose1d(Reference)"
+
+    @classmethod
+    def from_float(cls, float_conv, weight_qparams):  # type: ignore[override]
+        return _ConvTransposeNd.from_float(cls, float_conv, weight_qparams)
+
+
+class ConvTranspose2d(_ConvTransposeNd, nn.ConvTranspose2d):
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        output_padding=0,
+        groups=1,
+        bias=True,
+        dilation=1,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+        weight_qparams: dict[str, Any] | None = None,
+    ):
+        nn.ConvTranspose2d.__init__(
+            self,
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            output_padding,
+            groups,
+            bias,
+            dilation,
+            # pyrefly: ignore [bad-argument-type]
+            padding_mode,
+            device,
+            dtype,
+        )
+        self._init_weight_qparams(weight_qparams, device)
+
+    def forward(
+        self, x: torch.Tensor, output_size: list[int] | None = None
+    ) -> torch.Tensor:
+        """
+        we have:
+        w(float) -- quant - dequant \
+        x(float) ------------- F.convTranspose2d ---
+        In the full model, we will see
+        w(float) -- quant - *dequant \
+        x -- quant --- *dequant --  *F.convTranspose2d --- *quant - dequant
+        and the backend should be able to fuse the ops with `*` into a quantized conv2d
+        """
+        if not isinstance(self.padding, tuple):
+            raise AssertionError(
+                f"Expected self.padding to be a tuple, got {type(self.padding)}"
+            )
+        # One cannot replace List by Tuple or Sequence in "_output_padding" because
+        # TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
+
+        output_padding = self._output_padding(
+            input,  # type: ignore[arg-type]
+            output_size,
+            self.stride,  # type: ignore[arg-type]
+            self.padding,  # type: ignore[arg-type]
+            self.kernel_size,  # type: ignore[arg-type]
+            self.dilation,  # type: ignore[arg-type]
+        )
+
+        weight_quant_dequant = self.get_weight()
+        result = F.conv_transpose2d(
+            x,
+            weight_quant_dequant,
+            self.bias,
+            self.stride,
+            self.padding,
+            output_padding,
+            self.groups,
+            self.dilation,
+        )
+
+        return result
+
+    def _get_name(self):
+        return "QuantizedConvTranspose2d(Reference)"
+
+    @classmethod
+    def from_float(cls, float_conv, weight_qparams):  # type: ignore[override]
+        return _ConvTransposeNd.from_float(cls, float_conv, weight_qparams)
+
+
+class ConvTranspose3d(_ConvTransposeNd, nn.ConvTranspose3d):
+    def __init__(
+        self,
+        in_channels,
+        out_channels,
+        kernel_size,
+        stride=1,
+        padding=0,
+        output_padding=0,
+        groups=1,
+        bias=True,
+        dilation=1,
+        padding_mode="zeros",
+        device=None,
+        dtype=None,
+        weight_qparams: dict[str, Any] | None = None,
+    ):
+        nn.ConvTranspose3d.__init__(
+            self,
+            in_channels,
+            out_channels,
+            kernel_size,
+            stride,
+            padding,
+            output_padding,
+            groups,
+            bias,
+            dilation,
+            # pyrefly: ignore [bad-argument-type]
+            padding_mode,
+            device,
+            dtype,
+        )
+        self._init_weight_qparams(weight_qparams, device)
+
+    def forward(
+        self, x: torch.Tensor, output_size: list[int] | None = None
+    ) -> torch.Tensor:
+        """
+        we have:
+        w(float) -- quant - dequant \
+        x(float) ------------- F.convTranspose3d ---
+        In the full model, we will see
+        w(float) -- quant - *dequant \
+        x -- quant --- *dequant --  *F.convTranspose3d --- *quant - dequant
+        and the backend should be able to fuse the ops with `*` into a quantized conv3d
+        """
+
+        if not isinstance(self.padding, tuple):
+            raise AssertionError(
+                f"Expected self.padding to be a tuple, got {type(self.padding)}"
+            )
+        # One cannot replace List by Tuple or Sequence in "_output_padding" because
+        # TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
+        output_padding = self._output_padding(
+            input,  # type: ignore[arg-type]
+            output_size,
+            self.stride,  # type: ignore[arg-type]
+            self.padding,  # type: ignore[arg-type]
+            self.kernel_size,  # type: ignore[arg-type]
+            self.dilation,  # type: ignore[arg-type]
+        )
+
+        weight_quant_dequant = self.get_weight()
+        result = F.conv_transpose3d(
+            x,
+            weight_quant_dequant,
+            self.bias,
+            self.stride,
+            self.padding,
+            output_padding,
+            self.groups,
+            self.dilation,
+        )
+        return result
+
+    def _get_name(self):
+        return "QuantizedConvTranspose3d(Reference)"
+
+    @classmethod
+    def from_float(cls, float_conv, weight_qparams):  # type: ignore[override]
+        return _ConvTransposeNd.from_float(cls, float_conv, weight_qparams)
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/linear.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..6014fab24036c30b183f5622d12aae4a345baedb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/linear.py
@@ -0,0 +1,69 @@
+from typing import Any
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from .utils import ReferenceQuantizedModule
+
+
+__all__ = ["Linear"]
+
+
+class Linear(nn.Linear, ReferenceQuantizedModule):
+    """A reference quantized linear module that fits into the FX
+    Graph Mode Quantization workflow
+    activation will be floating point Tensor, we will store floating
+    point weight as well in the module, but in forward we'll quantize
+    and dequantize the weight before running the floating point functional
+    linear operator.
+    """
+
+    _IS_REFERENCE = True
+
+    def __init__(
+        self,
+        in_features: int,
+        out_features: int,
+        bias_: bool = True,
+        device: torch.device | None = None,
+        dtype: torch.dtype | None = None,
+        weight_qparams: dict[str, Any] | None = None,
+    ) -> None:
+        super().__init__(in_features, out_features, bias_, device, dtype)
+        self._init_weight_qparams(weight_qparams, device)
+
+    def _get_name(self) -> str:
+        return "QuantizedLinear(Reference)"
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        """
+        we have:
+        w(float) -- quant - dequant \
+        x(float) ------------- F.linear ---
+
+        In the full model, we will see
+        w(float) -- quant - *dequant \
+        x -- quant --- *dequant --  *F.linear --- *quant - dequant
+        and the backend should be able to fuse the ops with `*` into a quantized linear
+        """
+        weight_quant_dequant = self.get_weight()
+        result = F.linear(x, weight_quant_dequant, self.bias)
+        return result
+
+    @classmethod
+    def from_float(
+        cls, float_linear: nn.Linear, weight_qparams: dict[str, Any]
+    ) -> "Linear":
+        qref_linear = Linear(
+            float_linear.in_features,
+            float_linear.out_features,
+            float_linear.bias is not None,
+            device=float_linear.weight.device,
+            dtype=float_linear.weight.dtype,
+            weight_qparams=weight_qparams,
+        )
+        qref_linear.weight = torch.nn.Parameter(float_linear.weight.detach())
+        if float_linear.bias is not None:
+            qref_linear.bias = torch.nn.Parameter(float_linear.bias.detach())
+        return qref_linear
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/rnn.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/rnn.py
new file mode 100644
index 0000000000000000000000000000000000000000..10b2b0e334cb9ff3e121dd8adbcc00bbf9d8bc82
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/rnn.py
@@ -0,0 +1,856 @@
+# mypy: allow-untyped-defs
+from typing import Any
+
+import torch
+import torch.nn as nn
+from torch import _VF, Tensor
+from torch.nn.utils.rnn import PackedSequence
+
+from .utils import _quantize_and_dequantize_weight, _quantize_weight
+
+
+__all__ = [
+    "RNNCellBase",
+    "RNNCell",
+    "LSTMCell",
+    "GRUCell",
+    "RNNBase",
+    "LSTM",
+    "GRU",
+    "get_quantized_weight",
+]
+
+
+def _apply_permutation(tensor: Tensor, permutation: Tensor, dim: int = 1) -> Tensor:
+    return tensor.index_select(dim, permutation)
+
+
+def _get_weight_and_quantization_params(module, wn):
+    weight = getattr(module, wn)
+    params = [weight]
+    for param_name in [
+        wn + n for n in ["_qscheme", "_dtype", "_scale", "_zero_point", "_axis_int"]
+    ]:
+        if hasattr(module, param_name):
+            param = getattr(module, param_name)
+        else:
+            param = None
+        params.append(param)
+    return params
+
+
+def get_quantized_weight(module, wn):
+    if not hasattr(module, wn):
+        return None
+    params = _get_weight_and_quantization_params(module, wn)
+    weight = _quantize_weight(*params)
+    return weight
+
+
+def _get_quantize_and_dequantized_weight(module, wn):
+    if not hasattr(module, wn):
+        return None
+    params = _get_weight_and_quantization_params(module, wn)
+    weight = _quantize_and_dequantize_weight(*params)
+    return weight
+
+
+class RNNCellBase(nn.RNNCellBase):
+    def __init__(
+        self,
+        input_size: int,
+        hidden_size: int,
+        bias: bool,
+        num_chunks: int,
+        device=None,
+        dtype=None,
+        weight_qparams_dict=None,
+    ) -> None:
+        super().__init__(
+            input_size, hidden_size, bias, num_chunks, device=device, dtype=dtype
+        )
+        # TODO(jerryzh168): maybe make this arg a required arg
+        if weight_qparams_dict is None:
+            weight_qparams = {
+                "qscheme": torch.per_tensor_affine,
+                "dtype": torch.quint8,
+                "scale": 1.0,
+                "zero_point": 0,
+            }
+            weight_qparams_dict = {
+                "weight_ih": weight_qparams,
+                "weight_hh": weight_qparams,
+                "is_decomposed": False,
+            }
+        if len(weight_qparams_dict) != 3:
+            raise AssertionError(
+                f"Expected length for weight_qparams_dict to be 3 for QuantizedRNNCellBase(Reference), "
+                f"got {len(weight_qparams_dict)}"
+            )
+        self._init_weight_qparams_dict(weight_qparams_dict, device)
+
+    def _init_weight_qparams_dict(self, weight_qparams_dict, device):
+        if weight_qparams_dict is None:
+            raise AssertionError("weight_qparams_dict must not be None")
+        self.is_decomposed = weight_qparams_dict["is_decomposed"]
+        for key, weight_qparams in weight_qparams_dict.items():
+            if key == "is_decomposed":
+                continue
+            # TODO: refactor the duplicated code to utils.py
+            weight_qscheme = weight_qparams["qscheme"]
+            weight_dtype = weight_qparams["dtype"]
+            setattr(self, key + "_qscheme", weight_qscheme)
+            setattr(self, key + "_dtype", weight_dtype)
+            if weight_qscheme not in [
+                None,
+                torch.per_tensor_affine,
+                torch.per_channel_affine,
+            ]:
+                raise AssertionError(
+                    f"qscheme: {weight_qscheme} is not supported in {self._get_name()}"
+                )
+            if weight_qscheme is not None:
+                scale = weight_qparams["scale"]
+                scale_tensor = (
+                    scale.detach().clone()
+                    if isinstance(scale, torch.Tensor)
+                    else torch.tensor(scale, dtype=torch.float, device=device)
+                )
+                self.register_buffer(key + "_scale", scale_tensor)
+                zp = weight_qparams["zero_point"]
+                zp_tensor = (
+                    zp.detach().clone()
+                    if isinstance(zp, torch.Tensor)
+                    else torch.tensor(zp, dtype=torch.int, device=device)
+                )
+                self.register_buffer(key + "_zero_point", zp_tensor)
+                if weight_qscheme == torch.per_channel_affine:
+                    axis = weight_qparams["axis"]
+                    axis_tensor = (
+                        axis.detach().clone()
+                        if isinstance(axis, torch.Tensor)
+                        else torch.tensor(axis, dtype=torch.int, device=device)
+                    )
+                    self.register_buffer(key + "_axis", axis_tensor)
+                else:
+                    # added for TorchScriptability, not used
+                    self.register_buffer(
+                        key + "_axis", torch.tensor(0, dtype=torch.int, device=device)
+                    )
+                setattr(self, key + "_axis_int", getattr(self, key + "_axis").item())
+
+    def _get_name(self):
+        return "QuantizedRNNCellBase(Reference)"
+
+    def get_quantized_weight_ih(self):
+        return get_quantized_weight(self, "weight_ih")
+
+    def get_quantized_weight_hh(self):
+        return get_quantized_weight(self, "weight_hh")
+
+    def get_weight_ih(self):
+        return _get_quantize_and_dequantized_weight(self, "weight_ih")
+
+    def get_weight_hh(self):
+        return _get_quantize_and_dequantized_weight(self, "weight_hh")
+
+
+class RNNCell(RNNCellBase):
+    """
+    We'll store weight_qparams for all the weights (weight_ih and weight_hh),
+    we need to pass in a `weight_qparams_dict` that maps from weight name,
+    e.g. weight_ih, to the weight_qparams for that weight
+    """
+
+    def __init__(
+        self,
+        input_size: int,
+        hidden_size: int,
+        bias: bool = True,
+        nonlinearity: str = "tanh",
+        device=None,
+        dtype=None,
+        weight_qparams_dict: dict[str, Any] | None = None,
+    ) -> None:
+        factory_kwargs = {
+            "device": device,
+            "dtype": dtype,
+            "weight_qparams_dict": weight_qparams_dict,
+        }
+        super().__init__(input_size, hidden_size, bias, num_chunks=1, **factory_kwargs)
+        self.nonlinearity = nonlinearity
+
+    def _get_name(self):
+        return "QuantizedRNNCell(Reference)"
+
+    # TODO: refactor nn.RNNCell to have a _forward that takes weight_ih and weight_hh as input
+    # and remove duplicated code, same for the other two Cell modules
+    def forward(self, input: Tensor, hx: Tensor | None = None) -> Tensor:
+        if input.dim() not in (1, 2):
+            raise AssertionError(
+                f"RNNCell: Expected input to be 1-D or 2-D but received {input.dim()}-D tensor"
+            )
+        is_batched = input.dim() == 2
+        if not is_batched:
+            input = input.unsqueeze(0)
+
+        if hx is None:
+            hx = torch.zeros(
+                input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
+            )
+        else:
+            hx = hx.unsqueeze(0) if not is_batched else hx
+
+        if self.nonlinearity == "tanh":
+            ret = _VF.rnn_tanh_cell(
+                input,
+                hx,
+                self.get_weight_ih(),
+                self.get_weight_hh(),
+                self.bias_ih,
+                self.bias_hh,
+            )
+        elif self.nonlinearity == "relu":
+            ret = _VF.rnn_relu_cell(
+                input,
+                hx,
+                self.get_weight_ih(),
+                self.get_weight_hh(),
+                self.bias_ih,
+                self.bias_hh,
+            )
+        else:
+            ret = input  # TODO: remove when jit supports exception flow
+            raise RuntimeError(f"Unknown nonlinearity: {self.nonlinearity}")
+
+        if not is_batched:
+            ret = ret.squeeze(0)
+
+        return ret
+
+    @classmethod
+    def from_float(cls, mod, weight_qparams_dict):
+        ref_mod = cls(
+            mod.input_size,
+            mod.hidden_size,
+            mod.bias,
+            mod.nonlinearity,
+            mod.weight_ih.device,
+            mod.weight_ih.dtype,
+            weight_qparams_dict,
+        )
+        ref_mod.weight_ih = mod.weight_ih
+        ref_mod.weight_hh = mod.weight_hh
+        ref_mod.bias_ih = mod.bias_ih
+        ref_mod.bias_hh = mod.bias_hh
+        return ref_mod
+
+
+class LSTMCell(RNNCellBase):
+    """
+    We'll store weight_qparams for all the weights (weight_ih and weight_hh),
+    we need to pass in a `weight_qparams_dict` that maps from weight name,
+    e.g. weight_ih, to the weight_qparams for that weight
+    """
+
+    def __init__(
+        self,
+        input_size: int,
+        hidden_size: int,
+        bias: bool = True,
+        device=None,
+        dtype=None,
+        weight_qparams_dict: dict[str, Any] | None = None,
+    ) -> None:
+        factory_kwargs = {
+            "device": device,
+            "dtype": dtype,
+            "weight_qparams_dict": weight_qparams_dict,
+        }
+        super().__init__(input_size, hidden_size, bias, num_chunks=4, **factory_kwargs)
+
+    def _get_name(self):
+        return "QuantizedLSTMCell(Reference)"
+
+    def forward(
+        self, input: Tensor, hx: tuple[Tensor, Tensor] | None = None
+    ) -> tuple[Tensor, Tensor]:
+        if input.dim() not in (1, 2):
+            raise AssertionError(
+                f"LSTMCell: Expected input to be 1-D or 2-D but received {input.dim()}-D tensor"
+            )
+        is_batched = input.dim() == 2
+        if not is_batched:
+            input = input.unsqueeze(0)
+
+        if hx is None:
+            zeros = torch.zeros(
+                input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
+            )
+            hx = (zeros, zeros)
+        else:
+            hx = (hx[0].unsqueeze(0), hx[1].unsqueeze(0)) if not is_batched else hx
+
+        ret = _VF.lstm_cell(
+            input,
+            hx,
+            self.get_weight_ih(),
+            self.get_weight_hh(),
+            self.bias_ih,
+            self.bias_hh,
+        )
+
+        if not is_batched:
+            ret = (ret[0].squeeze(0), ret[1].squeeze(0))
+        return ret
+
+    @classmethod
+    def from_float(cls, mod, weight_qparams_dict, use_precomputed_fake_quant=False):
+        ref_mod = cls(
+            mod.input_size,
+            mod.hidden_size,
+            mod.bias,
+            mod.weight_ih.device,
+            mod.weight_ih.dtype,
+            weight_qparams_dict,
+        )
+        ref_mod.weight_ih = mod.weight_ih
+        ref_mod.weight_hh = mod.weight_hh
+        ref_mod.bias_ih = mod.bias_ih
+        ref_mod.bias_hh = mod.bias_hh
+        return ref_mod
+
+
+class GRUCell(RNNCellBase):
+    """
+    We'll store weight_qparams for all the weights (weight_ih and weight_hh),
+    we need to pass in a `weight_qparams_dict` that maps from weight name,
+    e.g. weight_ih, to the weight_qparams for that weight
+    """
+
+    def __init__(
+        self,
+        input_size: int,
+        hidden_size: int,
+        bias: bool = True,
+        device=None,
+        dtype=None,
+        weight_qparams_dict: dict[str, Any] | None = None,
+    ) -> None:
+        factory_kwargs = {
+            "device": device,
+            "dtype": dtype,
+            "weight_qparams_dict": weight_qparams_dict,
+        }
+        super().__init__(input_size, hidden_size, bias, num_chunks=3, **factory_kwargs)
+
+    def _get_name(self):
+        return "QuantizedGRUCell(Reference)"
+
+    def forward(self, input: Tensor, hx: Tensor | None = None) -> Tensor:
+        if input.dim() not in (1, 2):
+            raise AssertionError(
+                f"GRUCell: Expected input to be 1-D or 2-D but received {input.dim()}-D tensor"
+            )
+        is_batched = input.dim() == 2
+        if not is_batched:
+            input = input.unsqueeze(0)
+
+        if hx is None:
+            hx = torch.zeros(
+                input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
+            )
+        else:
+            hx = hx.unsqueeze(0) if not is_batched else hx
+
+        ret = _VF.gru_cell(
+            input,
+            hx,
+            self.get_weight_ih(),
+            self.get_weight_hh(),
+            self.bias_ih,
+            self.bias_hh,
+        )
+
+        if not is_batched:
+            ret = ret.squeeze(0)
+
+        return ret
+
+    @classmethod
+    def from_float(cls, mod, weight_qparams_dict):
+        ref_mod = cls(
+            mod.input_size,
+            mod.hidden_size,
+            mod.bias,
+            mod.weight_ih.device,
+            mod.weight_ih.dtype,
+            weight_qparams_dict,
+        )
+        ref_mod.weight_ih = mod.weight_ih
+        ref_mod.weight_hh = mod.weight_hh
+        ref_mod.bias_ih = mod.bias_ih
+        ref_mod.bias_hh = mod.bias_hh
+        return ref_mod
+
+
+class RNNBase(nn.RNNBase):
+    def __init__(
+        self,
+        mode: str,
+        input_size: int,
+        hidden_size: int,
+        num_layers: int = 1,
+        bias: bool = True,
+        batch_first: bool = False,
+        dropout: float = 0.0,
+        bidirectional: bool = False,
+        proj_size: int = 0,
+        device=None,
+        dtype=None,
+        weight_qparams_dict: dict[str, Any] | None = None,
+    ) -> None:
+        super().__init__(
+            mode,
+            input_size,
+            hidden_size,
+            num_layers,
+            bias,
+            batch_first,
+            dropout,
+            bidirectional,
+            proj_size,
+            device,
+            dtype,
+        )
+        # TODO(jerryzh168): maybe make this arg a required arg
+        if weight_qparams_dict is None:
+            weight_qparams = {
+                "qscheme": torch.per_tensor_affine,
+                "dtype": torch.quint8,
+                "scale": 1.0,
+                "zero_point": 0,
+            }
+            weight_qparams_dict = {"is_decomposed": False}  # type: ignore[dict-item]
+            for wn in self._flat_weights_names:
+                if wn.startswith("weight"):
+                    weight_qparams_dict[wn] = weight_qparams
+        self._init_weight_qparams_dict(weight_qparams_dict, device)
+
+    def _init_weight_qparams_dict(self, weight_qparams_dict, device):
+        self.is_decomposed = weight_qparams_dict["is_decomposed"]
+        for key, weight_qparams in weight_qparams_dict.items():
+            if key == "is_decomposed":
+                continue
+            weight_qscheme = weight_qparams["qscheme"]
+            weight_dtype = weight_qparams["dtype"]
+            setattr(self, key + "_qscheme", weight_qscheme)
+            setattr(self, key + "_dtype", weight_dtype)
+            if weight_qscheme not in [
+                None,
+                torch.per_tensor_affine,
+                torch.per_channel_affine,
+            ]:
+                raise AssertionError(
+                    f"qscheme: {weight_qscheme} is not supported in {self._get_name()}"
+                )
+            if weight_qscheme is not None:
+                self.register_buffer(
+                    key + "_scale",
+                    torch.tensor(
+                        weight_qparams["scale"], dtype=torch.float, device=device
+                    ),
+                )
+                self.register_buffer(
+                    key + "_zero_point",
+                    torch.tensor(
+                        weight_qparams["zero_point"], dtype=torch.int, device=device
+                    ),
+                )
+                if weight_qscheme == torch.per_channel_affine:
+                    self.register_buffer(
+                        key + "_axis",
+                        torch.tensor(
+                            weight_qparams["axis"], dtype=torch.int, device=device
+                        ),
+                    )
+                else:
+                    # added for TorchScriptability, not used
+                    self.register_buffer(
+                        key + "_axis", torch.tensor(0, dtype=torch.int, device=device)
+                    )
+                setattr(self, key + "_axis_int", getattr(self, key + "_axis").item())
+
+
+class LSTM(RNNBase):
+    """Reference Quantized LSTM Module
+    We'll store weight_qparams for all the weights in _flat_weights, we need to pass in
+    a `weight_qparams_dict` that maps from weight name, e.g. weight_ih_l0,
+    to the weight_qparams for that weight
+    """
+
+    def __init__(self, *args, **kwargs):
+        super().__init__("LSTM", *args, **kwargs)
+
+    # Same as above, see torch/nn/modules/module.py::_forward_unimplemented
+    def permute_hidden(  # type: ignore[override]
+        self,
+        hx: tuple[Tensor, Tensor],
+        permutation: Tensor | None,
+    ) -> tuple[Tensor, Tensor]:
+        if permutation is None:
+            return hx
+        return _apply_permutation(hx[0], permutation), _apply_permutation(
+            hx[1], permutation
+        )
+
+    def get_expected_cell_size(
+        self, input: Tensor, batch_sizes: Tensor | None
+    ) -> tuple[int, int, int]:
+        if batch_sizes is not None:
+            mini_batch = int(batch_sizes[0])
+        else:
+            mini_batch = input.size(0) if self.batch_first else input.size(1)
+        num_directions = 2 if self.bidirectional else 1
+        expected_hidden_size = (
+            self.num_layers * num_directions,
+            mini_batch,
+            self.hidden_size,
+        )
+        return expected_hidden_size
+
+    # In the future, we should prevent mypy from applying contravariance rules here.
+    # See torch/nn/modules/module.py::_forward_unimplemented
+    def check_forward_args(  # type: ignore[override]
+        self,
+        input: Tensor,
+        hidden: tuple[Tensor, Tensor],
+        batch_sizes: Tensor | None,
+    ):
+        self.check_input(input, batch_sizes)
+        self.check_hidden_size(
+            hidden[0],
+            self.get_expected_hidden_size(input, batch_sizes),
+            "Expected hidden[0] size {}, got {}",
+        )
+        self.check_hidden_size(
+            hidden[1],
+            self.get_expected_cell_size(input, batch_sizes),
+            "Expected hidden[1] size {}, got {}",
+        )
+
+    def get_quantized_weight_bias_dict(self):
+        """dictionary from flat_weight_name to quantized weight or (unquantized) bias
+        e.g.
+        {
+          "weight_ih_l0": quantized_weight,
+          "bias_ih_l0": unquantized_bias,
+          ...
+        }
+        """
+        quantized_weight_bias_dict = {}
+        for wn in self._flat_weights_names:
+            if hasattr(self, wn):
+                if wn.startswith("weight"):
+                    weight_or_bias = get_quantized_weight(self, wn)
+                else:
+                    weight_or_bias = getattr(self, wn)
+            else:
+                weight_or_bias = None
+            quantized_weight_bias_dict[wn] = weight_or_bias
+        return quantized_weight_bias_dict
+
+    def get_flat_weights(self):
+        flat_weights = []
+        for wn in self._flat_weights_names:
+            if hasattr(self, wn):
+                weight = getattr(self, wn)
+                if wn.startswith("weight"):
+                    params = _get_weight_and_quantization_params(self, wn)
+                    weight = _quantize_and_dequantize_weight(*params)
+            else:
+                weight = None
+            flat_weights.append(weight)
+        return flat_weights
+
+    def forward(self, input, hx=None):
+        orig_input = input
+        # xxx: isinstance check needs to be in conditional for TorchScript to compile
+        batch_sizes = None
+        if isinstance(orig_input, PackedSequence):
+            input, batch_sizes, sorted_indices, unsorted_indices = input
+            max_batch_size = int(batch_sizes[0])
+        else:
+            batch_sizes = None
+            is_batched = input.dim() == 3
+            batch_dim = 0 if self.batch_first else 1
+            if not is_batched:
+                input = input.unsqueeze(batch_dim)
+            max_batch_size = input.size(0) if self.batch_first else input.size(1)
+            sorted_indices = None
+            unsorted_indices = None
+
+        if hx is None:
+            num_directions = 2 if self.bidirectional else 1
+            real_hidden_size = (
+                self.proj_size if self.proj_size > 0 else self.hidden_size
+            )
+            h_zeros = torch.zeros(
+                self.num_layers * num_directions,
+                max_batch_size,
+                real_hidden_size,
+                dtype=input.dtype,
+                device=input.device,
+            )
+            c_zeros = torch.zeros(
+                self.num_layers * num_directions,
+                max_batch_size,
+                self.hidden_size,
+                dtype=input.dtype,
+                device=input.device,
+            )
+            hx = (h_zeros, c_zeros)
+        else:
+            if batch_sizes is None:  # If not PackedSequence input.
+                if is_batched:  # type: ignore[possibly-undefined]
+                    if hx[0].dim() != 3 or hx[1].dim() != 3:
+                        msg = (
+                            "For batched 3-D input, hx and cx should "
+                            f"also be 3-D but got ({hx[0].dim()}-D, {hx[1].dim()}-D) tensors"
+                        )
+                        raise RuntimeError(msg)
+                else:
+                    if hx[0].dim() != 2 or hx[1].dim() != 2:
+                        msg = (
+                            "For unbatched 2-D input, hx and cx should "
+                            f"also be 2-D but got ({hx[0].dim()}-D, {hx[1].dim()}-D) tensors"
+                        )
+                        raise RuntimeError(msg)
+                    hx = (hx[0].unsqueeze(1), hx[1].unsqueeze(1))
+
+            # Each batch of the hidden state should match the input sequence that
+            # the user believes he/she is passing in.
+            hx = self.permute_hidden(hx, sorted_indices)
+
+        self.check_forward_args(input, hx, batch_sizes)
+        if batch_sizes is None:
+            result = _VF.lstm(
+                input,
+                hx,
+                self.get_flat_weights(),
+                self.bias,
+                self.num_layers,
+                self.dropout,
+                self.training,
+                self.bidirectional,
+                self.batch_first,
+            )
+        else:
+            result = _VF.lstm(
+                input,
+                batch_sizes,
+                hx,
+                self.get_flat_weights(),
+                self.bias,
+                self.num_layers,
+                self.dropout,
+                self.training,
+                self.bidirectional,
+            )
+        output = result[0]
+        hidden = result[1:]
+        # xxx: isinstance check needs to be in conditional for TorchScript to compile
+        if isinstance(orig_input, PackedSequence):
+            output_packed = PackedSequence(
+                output,
+                batch_sizes,
+                sorted_indices,
+                unsorted_indices,
+            )
+            return output_packed, self.permute_hidden(hidden, unsorted_indices)
+        else:
+            if not is_batched:  # type: ignore[possibly-undefined]
+                output = output.squeeze(batch_dim)  # type: ignore[possibly-undefined]
+                hidden = (hidden[0].squeeze(1), hidden[1].squeeze(1))
+            return output, self.permute_hidden(hidden, unsorted_indices)
+
+    def _get_name(self):
+        return "QuantizedLSTM(Reference)"
+
+    @classmethod
+    def from_float(cls, mod, weight_qparams_dict):
+        ref_mod = cls(
+            mod.input_size,
+            mod.hidden_size,
+            mod.num_layers,
+            mod.bias,
+            mod.batch_first,
+            mod.dropout,
+            mod.bidirectional,
+            weight_qparams_dict=weight_qparams_dict,
+        )
+        for wn in mod._flat_weights_names:
+            setattr(ref_mod, wn, getattr(mod, wn))
+        return ref_mod
+
+
+class GRU(RNNBase):
+    """Reference Quantized GRU Module
+    We'll store weight_qparams for all the weights in _flat_weights, we need to pass in
+    a `weight_qparams_dict` that maps from weight name, e.g. weight_ih_l0,
+    to the weight_qparams for that weight
+    """
+
+    def __init__(self, *args, **kwargs):
+        if "proj_size" in kwargs:
+            raise ValueError(
+                "proj_size argument is only supported for LSTM, not RNN or GRU"
+            )
+        super().__init__("GRU", *args, **kwargs)
+
+    def get_quantized_weight_bias_dict(self):
+        """dictionary from flat_weight_name to quantized weight or (unquantized) bias
+        e.g.
+        {
+          "weight_ih_l0": quantized_weight,
+          "bias_ih_l0": unquantized_bias,
+          ...
+        }
+        """
+        quantized_weight_bias_dict = {}
+        for wn in self._flat_weights_names:
+            if hasattr(self, wn):
+                if wn.startswith("weight"):
+                    weight_or_bias = get_quantized_weight(self, wn)
+                else:
+                    weight_or_bias = getattr(self, wn)
+            else:
+                weight_or_bias = None
+            quantized_weight_bias_dict[wn] = weight_or_bias
+        return quantized_weight_bias_dict
+
+    def get_flat_weights(self):
+        flat_weights = []
+        for wn in self._flat_weights_names:
+            if hasattr(self, wn):
+                weight = getattr(self, wn)
+                if wn.startswith("weight"):
+                    params = _get_weight_and_quantization_params(self, wn)
+                    weight = _quantize_and_dequantize_weight(*params)
+            else:
+                weight = None
+            flat_weights.append(weight)
+        return flat_weights
+
+    def forward(self, input, hx=None):
+        # Note: this is copied from the forward of GRU in https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/rnn.py
+        # only changed self._flat_weights to self.get_flat_weights()
+        # TODO: maybe we can try inheriting from that class and define get_flat_weights
+        # as a @property? this might interfere with TorchScript, if we remove that
+        # requirement in the future we should be able to do this
+        orig_input = input
+        # xxx: isinstance check needs to be in conditional for TorchScript to compile
+        if isinstance(orig_input, PackedSequence):
+            input, batch_sizes, sorted_indices, unsorted_indices = input
+            max_batch_size = int(batch_sizes[0])
+        else:
+            batch_sizes = None
+            if input.dim() not in (2, 3):
+                raise AssertionError(
+                    f"GRU: Expected input to be 2-D or 3-D but received {input.dim()}-D tensor"
+                )
+            is_batched = input.dim() == 3
+            batch_dim = 0 if self.batch_first else 1
+            if not is_batched:
+                input = input.unsqueeze(batch_dim)
+                if hx is not None:
+                    if hx.dim() != 2:
+                        raise RuntimeError(
+                            f"For unbatched 2-D input, hx should also be 2-D but got {hx.dim()}-D tensor"
+                        )
+                    hx = hx.unsqueeze(1)
+            else:
+                if hx is not None and hx.dim() != 3:
+                    raise RuntimeError(
+                        f"For batched 3-D input, hx should also be 3-D but got {hx.dim()}-D tensor"
+                    )
+            max_batch_size = input.size(0) if self.batch_first else input.size(1)
+            sorted_indices = None
+            unsorted_indices = None
+
+        if hx is None:
+            num_directions = 2 if self.bidirectional else 1
+            hx = torch.zeros(
+                self.num_layers * num_directions,
+                max_batch_size,
+                self.hidden_size,
+                dtype=input.dtype,
+                device=input.device,
+            )
+        else:
+            # Each batch of the hidden state should match the input sequence that
+            # the user believes he/she is passing in.
+            hx = self.permute_hidden(hx, sorted_indices)
+
+        self.check_forward_args(input, hx, batch_sizes)
+        if batch_sizes is None:
+            result = _VF.gru(
+                input,
+                hx,
+                self.get_flat_weights(),
+                self.bias,
+                self.num_layers,
+                self.dropout,
+                self.training,
+                self.bidirectional,
+                self.batch_first,
+            )
+        else:
+            result = _VF.gru(
+                input,
+                batch_sizes,
+                hx,
+                self.get_flat_weights(),
+                self.bias,
+                self.num_layers,
+                self.dropout,
+                self.training,
+                self.bidirectional,
+            )
+        output = result[0]
+        hidden = result[1]
+
+        # xxx: isinstance check needs to be in conditional for TorchScript to compile
+        if isinstance(orig_input, PackedSequence):
+            output_packed = PackedSequence(
+                output,
+                batch_sizes,
+                sorted_indices,
+                unsorted_indices,
+            )
+            return output_packed, self.permute_hidden(hidden, unsorted_indices)
+        else:
+            if not is_batched:  # type: ignore[possibly-undefined]
+                output = output.squeeze(batch_dim)  # type: ignore[possibly-undefined]
+                hidden = hidden.squeeze(1)
+
+            return output, self.permute_hidden(hidden, unsorted_indices)
+
+    def _get_name(self):
+        return "QuantizedGRU(Reference)"
+
+    @classmethod
+    def from_float(cls, mod, weight_qparams_dict):
+        ref_mod = cls(
+            mod.input_size,
+            mod.hidden_size,
+            mod.num_layers,
+            mod.bias,
+            mod.batch_first,
+            mod.dropout,
+            mod.bidirectional,
+            weight_qparams_dict=weight_qparams_dict,
+        )
+        for wn in mod._flat_weights_names:
+            setattr(ref_mod, wn, getattr(mod, wn))
+        return ref_mod
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/sparse.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/sparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ff80997c1439c50a456df328b4068ae0c419a01
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/sparse.py
@@ -0,0 +1,163 @@
+# mypy: allow-untyped-defs
+from typing import Any
+
+import torch.nn as nn
+import torch.nn.functional as F
+from torch import Tensor
+
+from .utils import ReferenceQuantizedModule
+
+
+__all__ = ["Embedding", "EmbeddingBag"]
+
+
+class Embedding(nn.Embedding, ReferenceQuantizedModule):
+    """A reference quantized Embedding module that fits into the
+    FX Graph Mode Quantization workflow, activation will be floating point Tensor,
+    we will store floating point weight as well in the module, but in forward we'll
+    quantize and dequantize the weight before running the floating point functional
+    embedding operator.
+    """
+
+    def __init__(
+        self,
+        num_embeddings: int,
+        embedding_dim: int,
+        padding_idx: int | None = None,
+        max_norm: float | None = None,
+        norm_type: float = 2.0,
+        scale_grad_by_freq: bool = False,
+        sparse: bool = False,
+        _weight: Tensor | None = None,
+        device=None,
+        dtype=None,
+        weight_qparams: dict[str, Any] | None = None,
+    ) -> None:
+        super().__init__(
+            num_embeddings,
+            embedding_dim,
+            padding_idx,
+            max_norm,
+            norm_type,
+            scale_grad_by_freq,
+            sparse,
+            _weight,
+            # pyrefly: ignore [bad-argument-type]
+            device,
+            dtype,
+        )
+        self._init_weight_qparams(weight_qparams, device)
+
+    def _get_name(self):
+        return "QuantizedEmbedding(Reference)"
+
+    def forward(self, input: Tensor) -> Tensor:
+        weight_quant_dequant = self.get_weight()
+        return F.embedding(
+            input,
+            weight_quant_dequant,
+            self.padding_idx,
+            self.max_norm,
+            self.norm_type,
+            self.scale_grad_by_freq,
+            self.sparse,
+        )
+
+    @classmethod
+    def from_float(cls, mod, weight_qparams):
+        return cls(
+            mod.num_embeddings,
+            mod.embedding_dim,
+            mod.padding_idx,
+            mod.max_norm,
+            mod.norm_type,
+            mod.scale_grad_by_freq,
+            mod.sparse,
+            mod.weight,
+            mod.weight.device,
+            mod.weight.dtype,
+            weight_qparams,
+        )
+
+
+class EmbeddingBag(nn.EmbeddingBag, ReferenceQuantizedModule):
+    """A reference quantized EmbeddingBag module that fits into the
+    FX Graph Mode Quantization workflow, activation will be floating point Tensor,
+    we will store floating point weight as well in the module, but in forward we'll
+    quantize and dequantize the weight before running the floating point functional
+    embedding operator.
+    """
+
+    def __init__(
+        self,
+        num_embeddings: int,
+        embedding_dim: int,
+        max_norm: float | None = None,
+        norm_type: float = 2.0,
+        scale_grad_by_freq: bool = False,
+        mode: str = "mean",
+        sparse: bool = False,
+        _weight: Tensor | None = None,
+        include_last_offset: bool = False,
+        padding_idx: int | None = None,
+        device=None,
+        dtype=None,
+        weight_qparams: dict[str, Any] | None = None,
+    ) -> None:
+        super().__init__(
+            num_embeddings,
+            embedding_dim,
+            max_norm,
+            norm_type,
+            scale_grad_by_freq,
+            mode,
+            sparse,
+            _weight,
+            include_last_offset,
+            padding_idx,
+            device,
+            dtype,
+        )
+        self._init_weight_qparams(weight_qparams, device)
+
+    def _get_name(self):
+        return "QuantizedEmbedding(Reference)"
+
+    def forward(
+        self,
+        input: Tensor,
+        offsets: Tensor | None = None,
+        per_sample_weights: Tensor | None = None,
+    ) -> Tensor:
+        weight_quant_dequant = self.get_weight()
+        return F.embedding_bag(
+            input,
+            weight_quant_dequant,
+            offsets,
+            self.max_norm,
+            self.norm_type,
+            self.scale_grad_by_freq,
+            self.mode,
+            self.sparse,
+            per_sample_weights,
+            self.include_last_offset,
+            self.padding_idx,
+        )
+
+    @classmethod
+    def from_float(cls, mod, weight_qparams, use_precomputed_fake_quant=False):
+        return cls(
+            mod.num_embeddings,
+            mod.embedding_dim,
+            mod.max_norm,
+            mod.norm_type,
+            mod.scale_grad_by_freq,
+            mod.mode,
+            mod.sparse,
+            mod.weight,
+            mod.include_last_offset,
+            mod.padding_idx,
+            mod.weight.device,
+            mod.weight.dtype,
+            weight_qparams,
+        )
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/utils.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff40b79a0a4d1a24d4416b492425f906f473a849
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/utils.py
@@ -0,0 +1,439 @@
+# mypy: allow-untyped-defs
+import typing
+
+import torch
+
+
+__all__ = [
+    "ReferenceQuantizedModule",
+]
+
+
+class ReferenceQuantizedModule(torch.nn.Module):
+    def _init_weight_qparams(self, weight_qparams, device):
+        if weight_qparams is None:
+            weight_qparams = {
+                "qscheme": torch.per_tensor_affine,
+                "dtype": torch.quint8,
+                "scale": 1.0,
+                "zero_point": 0,
+            }
+
+        self.weight_qscheme: torch.qscheme = weight_qparams["qscheme"]
+        self.weight_dtype = weight_qparams["dtype"]
+        if self.weight_qscheme not in [
+            None,
+            torch.per_tensor_affine,
+            torch.per_channel_affine,
+            torch.per_channel_affine_float_qparams,
+        ]:
+            raise AssertionError(
+                f"qscheme: {self.weight_qscheme} is not supported in reference quantized {self._get_name()}"
+            )
+        if self.weight_dtype in [
+            torch.quint8,
+            torch.qint8,
+            torch.quint4x2,
+            torch.qint32,
+        ]:
+            zero_point_dtype = (
+                weight_qparams["zero_point"].dtype
+                if isinstance(weight_qparams["zero_point"], torch.Tensor)
+                else torch.int
+            )
+            w_scale = weight_qparams["scale"]
+            w_scale_tensor = (
+                w_scale.detach().clone()
+                if isinstance(w_scale, torch.Tensor)
+                else torch.tensor(w_scale, dtype=torch.float, device=device)
+            )
+            self.register_buffer("weight_scale", w_scale_tensor)
+            w_zp = weight_qparams["zero_point"]
+            w_zp_tensor = (
+                w_zp.detach().clone()
+                if isinstance(w_zp, torch.Tensor)
+                else torch.tensor(w_zp, dtype=zero_point_dtype, device=device)
+            )
+            self.register_buffer("weight_zero_point", w_zp_tensor)
+            if self.weight_qscheme in [
+                torch.per_channel_affine,
+                torch.per_channel_affine_float_qparams,
+            ]:
+                w_axis = weight_qparams["axis"]
+                w_axis_tensor = (
+                    w_axis.detach().clone()
+                    if isinstance(w_axis, torch.Tensor)
+                    else torch.tensor(w_axis, dtype=torch.int, device=device)
+                )
+                self.register_buffer("weight_axis", w_axis_tensor)
+            else:
+                # added for TorchScriptability, not used
+                self.register_buffer(
+                    "weight_axis", torch.tensor(0, dtype=torch.int, device=device)
+                )
+        else:
+            # added for TorchScriptability, and for torch.float
+            self.register_buffer(
+                "weight_scale", torch.tensor(1.0, dtype=torch.float, device=device)
+            )
+            self.register_buffer(
+                "weight_zero_point", torch.tensor(0, dtype=torch.int, device=device)
+            )
+            self.register_buffer(
+                "weight_axis", torch.tensor(0, dtype=torch.int, device=device)
+            )
+
+        self.is_decomposed: bool = weight_qparams.get("is_decomposed", False)
+        # store weight_axis as weight_axis_int due to some constraints of torchdynamo.export
+        # for capturing `.item` operations
+        self.weight_axis_int: int = self.weight_axis.item()  # type: ignore[operator, assignment]
+
+        self.weight_quant_min: int | None = weight_qparams.get("quant_min")
+
+        self.weight_quant_max: int | None = weight_qparams.get("quant_max")
+
+    def get_weight(self):
+        """
+        Fake quantize (quantize and dequantize) the weight with
+        the quantization parameters for weight, this is used to
+        simulate the numerics for the quantized weight in a quantized
+        model
+        """
+        # suppress mypy warning
+        if not isinstance(self.weight_scale, torch.Tensor):
+            raise AssertionError("weight_scale must be a Tensor")
+        if not isinstance(self.weight_zero_point, torch.Tensor):
+            raise AssertionError("weight_zero_point must be a Tensor")
+        if self.is_decomposed:
+            return _quantize_and_dequantize_weight_decomposed(
+                self.weight,  # type: ignore[arg-type]
+                self.weight_qscheme,
+                self.weight_dtype,
+                self.weight_scale,
+                self.weight_zero_point,
+                self.weight_axis_int,
+                self.weight_quant_min,
+                self.weight_quant_max,
+            )
+        else:
+            return _quantize_and_dequantize_weight(
+                self.weight,  # type: ignore[arg-type]
+                self.weight_qscheme,
+                self.weight_dtype,
+                self.weight_scale,
+                self.weight_zero_point,
+                self.weight_axis_int,
+            )
+
+    def get_quantized_weight(self):
+        # suppress mypy warning
+        if not isinstance(self.weight_scale, torch.Tensor):
+            raise AssertionError("weight_scale must be a Tensor")
+        if not isinstance(self.weight_zero_point, torch.Tensor):
+            raise AssertionError("weight_zero_point must be a Tensor")
+        # assert isinstance(self.weight_axis, torch.Tensor)
+        if self.is_decomposed:
+            return _quantize_weight_decomposed(
+                self.weight,  # type: ignore[arg-type]
+                self.weight_qscheme,
+                self.weight_dtype,
+                self.weight_scale,
+                self.weight_zero_point,
+                self.weight_axis_int,
+                self.weight_quant_min,
+                self.weight_quant_max,
+            )
+        else:
+            return _quantize_weight(
+                self.weight,  # type: ignore[arg-type]
+                self.weight_qscheme,
+                self.weight_dtype,
+                self.weight_scale,
+                self.weight_zero_point,
+                self.weight_axis_int,
+            )
+
+    def _save_to_state_dict(self, destination, prefix, keep_vars):
+        super()._save_to_state_dict(destination, prefix, keep_vars)
+        _save_weight_qparams(
+            destination,
+            prefix,
+            self.weight_qscheme,
+            self.weight_dtype,
+            self.weight_scale,
+            self.weight_zero_point,
+            self.weight_axis,
+        )
+
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        for key in _get_weight_qparam_keys(state_dict, prefix):
+            setattr(self, key, state_dict[prefix + key])
+            state_dict.pop(prefix + key)
+
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+
+def _quantize_weight_decomposed(
+    weight: torch.Tensor,
+    weight_qscheme: torch.qscheme,
+    weight_dtype: torch.dtype,
+    weight_scale: torch.Tensor,
+    weight_zero_point: torch.Tensor,
+    weight_axis: int,
+    weight_quant_min: int | None,
+    weight_quant_max: int | None,
+) -> torch.Tensor:
+    _DTYPE_TO_QVALUE_BOUNDS: dict[torch.dtype, tuple[int, int]] = {
+        torch.uint8: (0, 255),
+        torch.int8: (-128, 127),
+        torch.int32: (-2147483648, 2147483647),  # torch.jit interprets 2**31 as a float
+    }
+
+    # TODO: add an util function for converting qdtype to dtype
+    _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE = {
+        torch.quint8: torch.uint8,
+        torch.qint8: torch.int8,
+        torch.qint32: torch.int32,
+    }
+    if weight_qscheme == torch.per_tensor_affine:
+        if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
+            weight_dtype_ = _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE[weight_dtype]
+            if weight_quant_min is None or weight_quant_max is None:
+                weight_quant_min, weight_quant_max = _DTYPE_TO_QVALUE_BOUNDS[
+                    weight_dtype_
+                ]
+            weight = torch.ops.quantized_decomposed.quantize_per_tensor(
+                weight,
+                weight_scale,
+                weight_zero_point,
+                weight_quant_min,
+                weight_quant_max,
+                weight_dtype_,
+            )
+            return weight
+    elif weight_qscheme in [
+        torch.per_channel_affine,
+        torch.per_channel_affine_float_qparams,
+    ]:
+        # TODO: torch.quint4x2 is not supported
+        if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
+            weight_dtype_ = _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE[weight_dtype]
+            if weight_quant_min is None or weight_quant_max is None:
+                weight_quant_min, weight_quant_max = _DTYPE_TO_QVALUE_BOUNDS[
+                    weight_dtype_
+                ]
+            weight = torch.ops.quantized_decomposed.quantize_per_channel(
+                weight,
+                weight_scale,
+                weight_zero_point,
+                weight_axis,
+                weight_quant_min,
+                weight_quant_max,
+                weight_dtype_,
+            )  # type: ignore[arg-type]
+            return weight
+    raise ValueError(f"Unsupported dtype and qscheme: {weight_dtype}, {weight_qscheme}")
+
+
+def _dequantize_weight_decomposed(
+    weight: torch.Tensor,
+    weight_qscheme: torch.qscheme,
+    weight_dtype: torch.dtype,
+    weight_scale: torch.Tensor,
+    weight_zero_point: torch.Tensor,
+    weight_axis: int,
+    weight_quant_min: int | None,
+    weight_quant_max: int | None,
+) -> torch.Tensor:
+    # TODO: get the quant_min and quant_max from activation_post_process
+    _DTYPE_TO_QVALUE_BOUNDS: dict[torch.dtype, tuple[int, int]] = {
+        torch.uint8: (0, 255),
+        torch.int8: (-128, 127),
+        torch.int32: (-2147483648, 2147483647),  # torch.jit interprets 2**31 as a float
+    }
+    # TODO: add an util function for converting qdtype to dtype
+    _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE = {
+        torch.quint8: torch.uint8,
+        torch.qint8: torch.int8,
+        torch.qint32: torch.int32,
+    }
+    weight_dtype_ = _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE[weight_dtype]
+    if weight_quant_min is None or weight_quant_max is None:
+        weight_quant_min, weight_quant_max = _DTYPE_TO_QVALUE_BOUNDS[weight_dtype_]
+    if weight_qscheme == torch.per_tensor_affine:
+        if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
+            weight = torch.ops.quantized_decomposed.dequantize_per_tensor(
+                weight,
+                weight_scale,
+                weight_zero_point,
+                weight_quant_min,
+                weight_quant_max,
+                weight_dtype_,
+            )
+            return weight
+    elif weight_qscheme in [
+        torch.per_channel_affine,
+        torch.per_channel_affine_float_qparams,
+    ]:
+        # TODO: torch.quint4x2 is not supported
+        if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
+            weight = torch.ops.quantized_decomposed.dequantize_per_channel(
+                weight,
+                weight_scale,
+                weight_zero_point,
+                weight_axis,
+                weight_quant_min,
+                weight_quant_max,
+                weight_dtype_,
+            )  # type: ignore[arg-type]
+            return weight
+    raise ValueError(f"Unsupported dtype and qscheme: {weight_dtype}, {weight_qscheme}")
+
+
+def _quantize_weight(
+    weight: torch.Tensor,
+    weight_qscheme: torch.qscheme,
+    weight_dtype: torch.dtype,
+    weight_scale: torch.Tensor,
+    weight_zero_point: torch.Tensor,
+    weight_axis_int: int,
+) -> torch.Tensor:
+    if weight_dtype == torch.float16:
+        weight = weight.to(weight_dtype)
+        return weight
+
+    if weight_qscheme == torch.per_tensor_affine:
+        if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
+            weight = torch.quantize_per_tensor(
+                weight, weight_scale, weight_zero_point, weight_dtype
+            )
+            return weight
+    elif weight_qscheme in [
+        torch.per_channel_affine,
+        torch.per_channel_affine_float_qparams,
+    ]:
+        if weight_dtype in [torch.quint8, torch.qint8, torch.quint4x2, torch.qint32]:
+            weight = torch.quantize_per_channel(
+                weight, weight_scale, weight_zero_point, weight_axis_int, weight_dtype
+            )  # type: ignore[arg-type]
+            return weight
+    raise ValueError(f"Unsupported dtype and qscheme: {weight_dtype}, {weight_qscheme}")
+
+
+def _quantize_and_dequantize_weight_decomposed(
+    weight: torch.Tensor,
+    weight_qscheme: torch.qscheme,
+    weight_dtype: torch.dtype,
+    weight_scale: torch.Tensor,
+    weight_zero_point: torch.Tensor,
+    weight_axis_int: int,
+    weight_quant_min: int | None,
+    weight_quant_max: int | None,
+) -> torch.Tensor:
+    """Quantize and then dequantize the weight based on
+    the quantization parameters
+    """
+    if weight_qscheme in [
+        torch.per_tensor_affine,
+        torch.per_channel_affine,
+        torch.per_channel_affine_float_qparams,
+    ]:
+        weight_quant = _quantize_weight_decomposed(
+            weight,
+            weight_qscheme,
+            weight_dtype,
+            weight_scale,
+            weight_zero_point,
+            weight_axis_int,
+            weight_quant_min,
+            weight_quant_max,
+        )
+        weight_dequant = _dequantize_weight_decomposed(
+            weight_quant,
+            weight_qscheme,
+            weight_dtype,
+            weight_scale,
+            weight_zero_point,
+            weight_axis_int,
+            weight_quant_min,
+            weight_quant_max,
+        )
+    else:
+        weight_dequant = weight
+    return weight_dequant
+
+
+def _quantize_and_dequantize_weight(
+    weight: torch.Tensor,
+    weight_qscheme: torch.qscheme,
+    weight_dtype: torch.dtype,
+    weight_scale: torch.Tensor,
+    weight_zero_point: torch.Tensor,
+    weight_axis_int: int,
+) -> torch.Tensor:
+    """Quantize and then dequantize the weight based on
+    the quantization parameters
+    """
+    if weight_qscheme in [
+        torch.per_tensor_affine,
+        torch.per_channel_affine,
+        torch.per_channel_affine_float_qparams,
+    ]:
+        weight_quant = _quantize_weight(
+            weight,
+            weight_qscheme,
+            weight_dtype,
+            weight_scale,
+            weight_zero_point,
+            weight_axis_int,
+        )
+        weight_dequant = weight_quant.dequantize()
+    else:
+        weight_dequant = weight
+    return weight_dequant
+
+
+def _save_weight_qparams(
+    destination,
+    prefix,
+    weight_qscheme,
+    weight_dtype,
+    weight_scale,
+    weight_zero_point,
+    weight_axis,
+):
+    destination[prefix + "weight_qscheme"] = weight_qscheme
+    destination[prefix + "weight_dtype"] = weight_dtype
+    if weight_qscheme is not None:
+        destination[prefix + "weight_scale"] = weight_scale
+        destination[prefix + "weight_zero_point"] = weight_zero_point
+        if weight_qscheme == torch.per_channel_affine:
+            destination[prefix + "weight_axis"] = weight_axis
+
+
+def _get_weight_qparam_keys(state_dict: dict[str, typing.Any], prefix: str):
+    keys = ["weight_qscheme", "weight_dtype"]
+    weight_qscheme = state_dict[prefix + "weight_qscheme"]
+    if weight_qscheme is not None:
+        keys.append("weight_scale")
+        keys.append("weight_zero_point")
+        if weight_qscheme == torch.quantize_per_channel:
+            keys.append("weight_axis")
+    return keys
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fda5a58f2984ee05b0d167297b458f62c37fc59
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/__init__.py
@@ -0,0 +1 @@
+from . import quantized
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01d31c4907e0cc272eac9cb570767f02276318af
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef66c90b0e8ecdbc7cd2cfb4c1cecf0bc38e8466
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__init__.py
@@ -0,0 +1,10 @@
+from torch.ao.nn.sparse.quantized import dynamic
+
+from .linear import Linear, LinearPackedParams
+
+
+__all__ = [
+    "dynamic",
+    "Linear",
+    "LinearPackedParams",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80a8782aa46856170b1fedc494dc87693993cca6
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/linear.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/linear.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c04638c8cdcb611cca0448eb16df9108bb0bc915
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/linear.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5afa1ada631f024df6ce938c60fc50faac03f324
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..91ecfd8793dc08b96ed64f47f531724aa8a866d0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__init__.py
@@ -0,0 +1,6 @@
+from .linear import Linear
+
+
+__all__ = [
+    "Linear",
+]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..19f53f873081e684bd2cab297040a272760df018
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__pycache__/linear.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__pycache__/linear.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f912e23ed0994c86c9e1b8fcf03f74a8b28e39c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__pycache__/linear.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/linear.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e60c47de74a34ba4057e641c98bd9cd4ff5a7b3
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/linear.py
@@ -0,0 +1,203 @@
+# mypy: allow-untyped-defs
+
+import torch
+import torch.ao.nn.intrinsic as nni
+from torch.ao.nn.quantized.modules.utils import (
+    _hide_packed_params_repr,
+    _quantize_weight,
+)
+from torch.ao.nn.sparse.quantized import linear
+from torch.ao.nn.sparse.quantized.utils import LinearBlockSparsePattern
+
+
+__all__ = ["Linear"]
+
+
+class Linear(torch.nn.Module):
+    r"""
+    A dynamically quantized sparse linear module with float tensor as inputs and outputs.
+    """
+
+    _version = 1
+    _op_type = "sparse_dynamic"
+    _FLOAT_MODULE = torch.nn.Linear
+
+    def __init__(
+        self,
+        in_features,
+        out_features,
+        row_block_size,
+        col_block_size,
+        bias=True,
+        dtype=torch.qint8,
+    ):
+        super().__init__()
+
+        if dtype != torch.qint8:
+            raise NotImplementedError(
+                "Only QINT8 is supported for Sparse Quantized Linear Dynamic"
+            )
+
+        self.in_features = in_features
+        self.out_features = out_features
+
+        if bias:
+            bias = torch.zeros(self.out_features, dtype=torch.float)
+        else:
+            bias = None
+
+        qweight = torch._empty_affine_quantized(
+            [out_features, in_features], scale=1, zero_point=0, dtype=torch.qint8
+        )
+        self._packed_params = linear.LinearPackedParams(
+            row_block_size=row_block_size, col_block_size=col_block_size, dtype=dtype
+        )
+        self._packed_params.set_weight_bias(
+            qweight, bias, row_block_size, col_block_size
+        )
+
+    def _get_name(self):
+        return "SparseQuantizedDynamicLinear"
+
+    def extra_repr(self):
+        return f"in_features={self.in_features}, out_features={self.out_features}, qscheme={self.weight().qscheme()}"
+
+    def __repr__(self):
+        return _hide_packed_params_repr(self, linear.LinearPackedParams)
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        return torch.ops.sparse.qlinear_dynamic(x, self._packed_params._packed_params)
+
+    def _save_to_state_dict(self, destination, prefix, keep_vars):
+        super()._save_to_state_dict(destination, prefix, keep_vars)
+        destination[prefix + "op_type"] = self._op_type
+
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        op_type = int(state_dict[prefix + "op_type"])
+        if op_type != "sparse":
+            raise AssertionError(
+                f"Cannot load from op_type [{op_type}], expecting [{self._op_type}]"
+            )
+        state_dict.pop(prefix + "op_type")
+
+        version = local_metadata.get("version", None)
+        if version is not None and version > self._version:
+            raise AssertionError(f"version {version} > self._version {self._version}")
+
+        # Is this code valid? In old quantization it seemed to be used to load
+        # older model
+        weight = state_dict.pop(prefix + "weight")
+        bias = state_dict.pop(prefix + "bias")
+        state_dict.update(
+            {
+                prefix + "_packed_params.weight": weight,
+                prefix + "_packed_params.bias": bias,
+            }
+        )
+
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+    def _weight_bias(self):
+        return self._packed_params._weight_bias()
+
+    def weight(self):
+        return self._weight_bias()[0]
+
+    def bias(self):
+        return self._weight_bias()[1]
+
+    def set_weight_bias(
+        self,
+        w: torch.Tensor,
+        b: torch.Tensor | None,
+        row_block_size: int | None,
+        col_block_size: int | None,
+    ) -> None:
+        if row_block_size is None or col_block_size is None:
+            raise AssertionError(
+                f"row_block_size and col_block_size must not be None, got {row_block_size=}, {col_block_size=}"
+            )
+        self.out_features = w.shape[0]
+        self.in_features = w.shape[1]
+        self._packed_params.set_weight_bias(w, b, row_block_size, col_block_size)
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Create a quantized sparse dynamic module from a float module.
+
+        We only care about the convert at this stage, no need for observers just yet.
+        """
+        if type(mod) is not cls._FLOAT_MODULE:
+            raise AssertionError(
+                " nnq."
+                + cls.__name__
+                + ".from_float only works for "
+                + cls._FLOAT_MODULE.__name__
+            )
+        # TODO: Need to add options to qconfig to avoid the calibration.
+        # TODO: Add calibration for the sparsity
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+        if type(mod) is nni.LinearReLU:
+            mod = mod[0]
+        # pyrefly: ignore [missing-attribute]
+        if mod.qconfig is not None and mod.qconfig.weight is not None:
+            # pyrefly: ignore [not-callable]
+            weight_observer = mod.qconfig.weight()
+        else:
+            # We have the circular import issues if we import the qconfig in the beginning of this file:
+            # https://github.com/pytorch/pytorch/pull/24231. The current workaround is to postpone the
+            # import until we need it.
+            from torch.ao.quantization.qconfig import default_dynamic_qconfig
+
+            weight_observer = default_dynamic_qconfig.weight()
+
+        # It is important to multiply by the mask BEFORE calling the `weight_observer`
+        # TODO (zaf): Mask might not be part of the qconfig (T83295194)
+        weight = mod.weight
+        if getattr(mod.qconfig, "mask", False):
+            weight = mod.qconfig.mask * mod.weight
+
+        weight_observer(weight)
+        dtype = weight_observer.dtype
+        if dtype != torch.qint8:
+            raise AssertionError(
+                f"Weight observer must have dtype torch.qint8, got {dtype}"
+            )
+        _w_sc, w_zp = weight_observer.calculate_qparams()
+        if isinstance(w_zp, torch.Tensor):
+            if torch.any(w_zp.bool()):
+                raise AssertionError("All weight zero points must map to 0")
+        else:
+            if w_zp != 0:
+                raise AssertionError(f"Weight zero point must map to 0, got {w_zp}")
+        qweight = _quantize_weight(weight.float(), weight_observer)
+
+        row_block_size, col_block_size = LinearBlockSparsePattern.block_size()
+        qlinear = cls(
+            mod.in_features,
+            mod.out_features,
+            row_block_size,
+            col_block_size,
+            dtype=dtype,
+        )
+        # pyrefly: ignore [bad-argument-type]
+        qlinear.set_weight_bias(qweight, mod.bias, row_block_size, col_block_size)
+        return qlinear
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/linear.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b12bf74973e75eab3f677aeed46d977f4ecb679
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/linear.py
@@ -0,0 +1,300 @@
+# mypy: allow-untyped-defs
+
+import torch
+from torch.ao.nn.quantized.modules.utils import (
+    _hide_packed_params_repr,
+    _quantize_weight,
+)
+
+
+__all__ = ["LinearPackedParams", "Linear"]
+
+
+# TODO (zaf): Inherit from `quantized.LinearPackedParams` (T83294430)
+class LinearPackedParams(torch.nn.Module):
+    _version = 1
+
+    def __init__(self, row_block_size=1, col_block_size=4, dtype=torch.qint8):
+        super().__init__()
+
+        if dtype != torch.qint8:
+            raise NotImplementedError("Linear prepacking only supports QINT8")
+        self.dtype = dtype
+        wq = torch._empty_affine_quantized(
+            [1, 1], scale=1.0, zero_point=0, dtype=torch.qint8
+        )
+        self.set_weight_bias(wq, None, row_block_size, col_block_size)
+
+    def _get_name(self):
+        return "SparseQuantizedLinearPackedParams"
+
+    @torch.jit.export
+    def set_weight_bias(
+        self,
+        weight: torch.Tensor,
+        bias: torch.Tensor | None,
+        row_block_size: int | None,
+        col_block_size: int | None,
+    ) -> None:
+        if row_block_size is None or col_block_size is None:
+            raise AssertionError(
+                "row_block_size and col_block_size must not be None, got "
+                f"row_block_size={row_block_size}, col_block_size={col_block_size}"
+            )
+        self._packed_params = torch.ops.sparse.qlinear_prepack(
+            weight, bias, row_block_size, col_block_size
+        )
+
+    @torch.jit.export
+    def _weight_bias(self):
+        (weight, bias, block_sizes) = torch.ops.sparse.qlinear_unpack(
+            self._packed_params
+        )
+        return (weight, bias, block_sizes[0], block_sizes[1])
+
+    def forward(self, x):
+        return x
+
+    def _save_to_state_dict(self, destination, prefix, keep_vars):
+        super()._save_to_state_dict(destination, prefix, keep_vars)
+        destination[prefix + "dtype"] = self.dtype
+        destination[prefix + "_packed_params"] = self._weight_bias()
+
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        version = local_metadata.get("version", None)
+        if version is not None and version > self._version:
+            raise AssertionError(f"version {version} > self._version {self._version}")
+
+        self.dtype = state_dict.pop(prefix + "dtype")
+        weight, bias, row_block_size, col_block_size = state_dict.pop(
+            prefix + "_packed_params"
+        )
+        self.set_weight_bias(weight, bias, row_block_size, col_block_size)
+
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+    @torch.jit.export
+    def __getstate__(self):
+        return self._packed_params, self.training, self.dtype
+
+    @torch.jit.export
+    def __setstate__(self, state):
+        (self._packed_params, self.training, self.dtype) = state
+
+    def __repr__(self):
+        return self._weight_bias().__repr__()
+
+
+# TODO (zaf): Inherit from `quantized.Linear` (T83294430)
+class Linear(torch.nn.Module):
+    r"""
+    A quantized sparse linear module with quantized tensor as inputs and outputs.
+    """
+
+    _version = 1
+    _FLOAT_MODULE = torch.nn.Linear
+
+    def __init__(
+        self,
+        in_features,
+        out_features,
+        row_block_size,
+        col_block_size,
+        bias=True,
+        dtype=torch.qint8,
+    ):
+        super().__init__()
+
+        if dtype != torch.qint8:
+            raise NotImplementedError(
+                "Only QINT8 is supported for Sparse Quantized Linear"
+            )
+
+        self.in_features = in_features
+        self.out_features = out_features
+
+        if bias:
+            bias = torch.zeros(self.out_features, dtype=torch.float)
+        else:
+            bias = None
+
+        qweight = torch._empty_affine_quantized(
+            [out_features, in_features], scale=1, zero_point=0, dtype=torch.qint8
+        )
+        self._packed_params = LinearPackedParams(
+            row_block_size=row_block_size, col_block_size=col_block_size, dtype=dtype
+        )
+        self._packed_params.set_weight_bias(
+            qweight, bias, row_block_size, col_block_size
+        )
+        self.scale = 1.0
+        self.zero_point = 0
+
+    @classmethod
+    def _get_name(cls):
+        return "SparseQuantizedLinear"
+
+    def extra_repr(self):
+        return (
+            f"in_features={self.in_features}, out_features={self.out_features}, scale={self.scale}, "
+            f"zero_point={self.zero_point}, qscheme={self.weight().qscheme()}"
+        )
+
+    def __repr__(self):
+        return _hide_packed_params_repr(self, LinearPackedParams)
+
+    def forward(self, x: torch.Tensor) -> torch.Tensor:
+        return torch.ops.sparse.qlinear(
+            x, self._packed_params._packed_params, self.scale, self.zero_point
+        )
+
+    def _save_to_state_dict(self, destination, prefix, keep_vars):
+        super()._save_to_state_dict(destination, prefix, keep_vars)
+        destination[prefix + "scale"] = torch.tensor(self.scale)
+        destination[prefix + "zero_point"] = torch.tensor(self.zero_point)
+
+    def _load_from_state_dict(
+        self,
+        state_dict,
+        prefix,
+        local_metadata,
+        strict,
+        missing_keys,
+        unexpected_keys,
+        error_msgs,
+    ):
+        self.scale = float(state_dict[prefix + "scale"])
+        state_dict.pop(prefix + "scale")
+
+        self.zero_point = int(state_dict[prefix + "zero_point"])
+        state_dict.pop(prefix + "zero_point")
+
+        state_dict.pop(prefix + "op_type")
+
+        version = local_metadata.get("version", None)
+        if version is not None and version > self._version:
+            raise AssertionError(f"version {version} > self._version {self._version}")
+
+        super()._load_from_state_dict(
+            state_dict,
+            prefix,
+            local_metadata,
+            False,
+            missing_keys,
+            unexpected_keys,
+            error_msgs,
+        )
+
+    def _weight_bias(self):
+        return self._packed_params._weight_bias()
+
+    def weight(self):
+        return self._weight_bias()[0]
+
+    def bias(self):
+        return self._weight_bias()[1]
+
+    def set_weight_bias(
+        self,
+        w: torch.Tensor,
+        b: torch.Tensor | None,
+        row_block_size: int | None,
+        col_block_size: int | None,
+    ) -> None:
+        if row_block_size is None or col_block_size is None:
+            raise AssertionError(
+                "row_block_size and col_block_size must not be None, "
+                f"got row_block_size={row_block_size}, col_block_size={col_block_size}"
+            )
+        self._packed_params.set_weight_bias(w, b, row_block_size, col_block_size)
+
+    @classmethod
+    def from_float(cls, mod, use_precomputed_fake_quant=False):
+        r"""Create a quantized sparse module from a float module.
+
+        We only care about the convert at this stage, no need for observers just yet.
+
+        TODO(zaf): Need to add the sparse params to the qconfig
+        """
+        if type(mod) is not cls._FLOAT_MODULE:
+            raise AssertionError(
+                cls._get_name()
+                + ".from_float only works for "
+                + cls._FLOAT_MODULE.__name__
+            )
+        if not hasattr(mod, "sparse_params"):
+            raise AssertionError(
+                "Expecting the Linear to have `sparse_params`. Make sure you have provided arguments "
+                'in the `sparsifier.squash_mask(params_to_save=("sparse_block_shape",))` method.'
+            )
+        sparse_block_shape = mod.sparse_params.get("sparse_block_shape", None)  # type: ignore[operator, union-attr]
+        if not isinstance(sparse_block_shape, (tuple, list)):
+            raise AssertionError(
+                f"sparse_block_shape must be tuple or list, got {type(sparse_block_shape)}"
+            )
+        if len(sparse_block_shape) != 2:
+            raise AssertionError(
+                f"sparse_block_shape must have length 2, got {len(sparse_block_shape)}"
+            )
+        # TODO: Need to add options to qconfig to avoid the calibration.
+        # TODO: Add calibration for the sparsity
+        if not hasattr(mod, "qconfig"):
+            raise AssertionError("Input float module must have qconfig defined")
+        activation_post_process = mod.activation_post_process
+        weight_post_process = mod.qconfig.weight()  # type: ignore[operator, union-attr]
+
+        # Assumption is that the weight is already sparsified by the
+        # `sparsifier.convert`
+        weight = mod.weight
+
+        weight_post_process(weight)
+        dtype = weight_post_process.dtype
+        act_scale, act_zp = activation_post_process.calculate_qparams()  # type: ignore[operator, union-attr]
+        if dtype != torch.qint8:
+            raise AssertionError(
+                f"Weight observer must have dtype torch.qint8, got {dtype}"
+            )
+        w_sc, w_zp = weight_post_process.calculate_qparams()
+        if isinstance(w_zp, torch.Tensor):
+            if torch.any(w_zp.bool()):
+                raise AssertionError("All weight zero points must map to 0")
+        else:
+            if w_zp != 0:
+                raise AssertionError(f"Weight zero point must map to 0, got {w_zp}")
+        qweight = _quantize_weight(weight.float(), weight_post_process)
+
+        row_block_size = mod.sparse_params["sparse_block_shape"][0]  # type: ignore[index]
+        col_block_size = mod.sparse_params["sparse_block_shape"][1]  # type: ignore[index]
+        qlinear = cls(
+            mod.in_features,
+            mod.out_features,
+            row_block_size,
+            col_block_size,
+            dtype=dtype,
+        )
+        qlinear.set_weight_bias(
+            qweight,
+            mod.bias,
+            row_block_size,  # type: ignore[arg-type]
+            col_block_size,  # type: ignore[arg-type]
+        )
+        qlinear.scale = float(act_scale)
+        qlinear.zero_point = int(act_zp)
+        return qlinear
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/utils.py b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..440c48d97d9198de794d41c30e5babf2f1504d33
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/utils.py
@@ -0,0 +1,66 @@
+import threading
+
+
+__all__ = ["LinearBlockSparsePattern"]
+
+
+def _is_valid_linear_block_sparse_pattern(
+    row_block_size: int, col_block_size: int
+) -> bool:
+    return (row_block_size == 1 and col_block_size == 4) or (
+        row_block_size == 8 and col_block_size == 1
+    )
+
+
+# This is a stop-gap measure as current flow does not allow module
+# specific block sparse pattern.
+# In fact there is no way to convey sparse pattern via module config
+# of quantization flow. Thus using the global context to convey
+# sparsity pattern.
+# Once the flow supports it, this should be removed.
+class LinearBlockSparsePattern:
+    rlock = threading.RLock()
+    row_block_size: int = 1
+    col_block_size: int = 4
+    prev_row_block_size: int = 1
+    prev_col_block_size: int = 4
+
+    def __init__(self, row_block_size: int = 1, col_block_size: int = 4):
+        if not _is_valid_linear_block_sparse_pattern(row_block_size, col_block_size):
+            raise AssertionError(
+                f"Invalid linear block sparse pattern: "
+                f"row_block_size={row_block_size}, col_block_size={col_block_size}"
+            )
+        LinearBlockSparsePattern.rlock.acquire()
+        LinearBlockSparsePattern.prev_row_block_size = (
+            LinearBlockSparsePattern.row_block_size
+        )
+        LinearBlockSparsePattern.prev_col_block_size = (
+            LinearBlockSparsePattern.col_block_size
+        )
+        LinearBlockSparsePattern.row_block_size = row_block_size
+        LinearBlockSparsePattern.col_block_size = col_block_size
+
+    def __enter__(self) -> None:
+        pass
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc_value: BaseException | None,
+        backtrace: object | None,
+    ) -> None:
+        LinearBlockSparsePattern.row_block_size = (
+            LinearBlockSparsePattern.prev_row_block_size
+        )
+        LinearBlockSparsePattern.col_block_size = (
+            LinearBlockSparsePattern.prev_col_block_size
+        )
+        LinearBlockSparsePattern.rlock.release()
+
+    @staticmethod
+    def block_size() -> tuple[int, int]:
+        return (
+            LinearBlockSparsePattern.row_block_size,
+            LinearBlockSparsePattern.col_block_size,
+        )
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ef5c5306155a3a44d99ae25eced0193f0aacc2e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/_numeric_suite.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/_numeric_suite.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8858b3c0693e54e3995ec7b8171f89674b407db1
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/_numeric_suite.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/_numeric_suite_fx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/_numeric_suite_fx.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..110b8d864f06841c7f48180dea6c1264b4fdafae
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/_numeric_suite_fx.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/_numeric_suite.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/_numeric_suite.py
new file mode 100644
index 0000000000000000000000000000000000000000..026ac73606e307bedd500a801a76ba1a97c4c655
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/ns/_numeric_suite.py
@@ -0,0 +1,568 @@
+# mypy: allow-untyped-defs
+from collections.abc import Callable
+from typing import Any
+
+import torch
+import torch.ao.nn.quantized as nnq
+import torch.ao.nn.quantized.dynamic as nnqd
+import torch.nn as nn
+from torch.ao.quantization import prepare
+from torch.ao.quantization.quantization_mappings import (
+    get_default_compare_output_module_list,
+)
+
+
+NON_LEAF_MODULE_TO_ADD_OBSERVER_ALLOW_LIST = {
+    nnqd.Linear,
+    nnq.Linear,
+    nnqd.LSTM,
+    nn.LSTM,
+}
+
+
+def _find_match(
+    str_list: dict[str, Any] | list[str],
+    key_str: str,
+    postfix: str,
+) -> str | None:
+    split_str = key_str.split(".")
+    if split_str[-1] == postfix:
+        match_string = "".join(key_str.split(".")[0:-1])
+        for s2 in str_list:
+            pattern1 = "".join(s2.split(".")[0:-1])
+            pattern2 = "".join(s2.split(".")[0:-2])
+            if match_string == pattern1:
+                return s2
+            if match_string == pattern2:
+                return s2
+
+        # For matching "fc.weight" and "fc._packed_params._packed_params"
+        if postfix == "_packed_params":
+            match_string = "".join(key_str.split(".")[0:-2])
+            if len(match_string) == 0:
+                return None
+            for s2 in str_list:
+                pattern1 = "".join(s2.split(".")[0:-1])
+                pattern2 = "".join(s2.split(".")[0:-2])
+                if match_string == pattern1:
+                    return s2
+                if match_string == pattern2:
+                    return s2
+        return None
+    else:
+        return None
+
+
+def compare_weights(
+    float_dict: dict[str, Any], quantized_dict: dict[str, Any]
+) -> dict[str, dict[str, torch.Tensor]]:
+    r"""Compare the weights of the float module with its corresponding quantized
+    module. Return a dict with key corresponding to module names and each entry being
+    a dictionary with two keys 'float' and 'quantized', containing the float and
+    quantized weights. This dict can be used to compare and compute the quantization
+    error of the weights of float and quantized models.
+
+    Example usage::
+
+        wt_compare_dict = compare_weights(float_model.state_dict(), qmodel.state_dict())
+        for key in wt_compare_dict:
+            print(
+                key,
+                compute_error(
+                    wt_compare_dict[key]["float"],
+                    wt_compare_dict[key]["quantized"].dequantize(),
+                ),
+            )
+
+    Args:
+        float_dict: state dict of the float model
+        quantized_dict: state dict of the quantized model
+
+    Return:
+        weight_dict: dict with key corresponding to module names and each entry being
+        a dictionary with two keys 'float' and 'quantized', containing the float and
+        quantized weights
+    """
+    torch._C._log_api_usage_once("quantization_api._numeric_suite.compare_weights")
+    weight_dict: dict[str, dict] = {}
+    for key in quantized_dict:
+        match_key = _find_match(float_dict, key, "weight")
+        if match_key is not None:
+            weight_dict[key] = {}
+            weight_dict[key]["float"] = float_dict[match_key]
+            weight_dict[key]["quantized"] = quantized_dict[key]
+            continue
+
+        # For matching "fc.weight" and "fc._packed_params._packed_params"
+        match_key = _find_match(float_dict, key, "_packed_params")
+        if match_key is not None:
+            weight_dict[key] = {}
+            weight_dict[key]["float"] = float_dict[match_key]
+            weight_dict[key]["quantized"] = quantized_dict[key][0]
+
+        # For LSTM
+        split_str = key.split(".")
+        if split_str[-1] == "param" and split_str[-3] == "_all_weight_values":
+            layer = split_str[-2]
+            module_name = ".".join(split_str[:-3])
+            float_weight_ih_key = module_name + ".weight_ih_l" + layer
+            float_weight_hh_key = module_name + ".weight_hh_l" + layer
+            if float_weight_ih_key in float_dict and float_weight_hh_key in float_dict:
+                weight_dict[key] = {}
+                weight_dict[key]["float"] = float_dict[float_weight_ih_key]
+                weight_dict[key]["quantized"] = (
+                    quantized_dict[key].__getstate__()[0][4][0].__getstate__()[0][0]
+                )
+                weight_dict[key]["float"] = float_dict[float_weight_hh_key]
+                weight_dict[key]["quantized"] = (
+                    quantized_dict[key].__getstate__()[0][4][1].__getstate__()[0][0]
+                )
+
+    return weight_dict
+
+
+def _get_logger_dict_helper(
+    mod: nn.Module,
+    target_dict: dict[str, Any],
+    prefix: str = "",
+) -> None:
+    r"""This is the helper function for get_logger_dict
+
+    Args:
+        mod: module we want to save all logger stats
+        prefix: prefix for the current module
+        target_dict: the dictionary used to save all logger stats
+    """
+
+    def get_prefix(prefix):
+        return prefix if prefix == "" else prefix + "."
+
+    for child in mod.children():
+        if isinstance(child, Logger):
+            target_dict[get_prefix(prefix) + "stats"] = child.stats
+            break
+
+    for name, child in mod.named_children():
+        module_prefix = get_prefix(prefix) + name if prefix else name
+        _get_logger_dict_helper(child, target_dict, module_prefix)
+
+
+def get_logger_dict(mod: nn.Module, prefix: str = "") -> dict[str, dict]:
+    r"""Traverse the modules and save all logger stats into target dict.
+    This is mainly used for quantization accuracy debug.
+
+    Type of loggers supported:
+        ShadowLogger: used to log the outputs of the quantized module and its matching float shadow module,
+        OutputLogger: used to log the outputs of the modules
+
+    Args:
+        mod: module we want to save all logger stats
+        prefix: prefix for the current module
+
+    Return:
+        target_dict: the dictionary used to save all logger stats
+
+    """
+    torch._C._log_api_usage_once("quantization_api._numeric_suite.get_logger_dict")
+
+    target_dict: dict[str, dict] = {}
+    _get_logger_dict_helper(mod, target_dict, prefix)
+    return target_dict
+
+
+class Logger(nn.Module):
+    r"""Base class for stats logging"""
+
+    def __init__(self):
+        super().__init__()
+        self.stats = {}
+        # We only insert observer if the op is quantized with static quantization,
+        # which is identified by activation_observer.dtype == quint8.  This is needed
+        # when attaching Logger as observer for FX mode
+        self.dtype = torch.quint8
+
+    def forward(self, x):
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+
+
+class ShadowLogger(Logger):
+    r"""Class used in Shadow module to record the outputs of the original and
+    shadow modules.
+    """
+
+    def __init__(self):
+        super().__init__()
+        self.stats["float"] = []
+        self.stats["quantized"] = []
+
+    def forward(self, x, y):  # type: ignore[override]
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+        if len(x) > 1:
+            x = x[0]
+        if len(y) > 1:
+            y = y[0]
+        self.stats["quantized"].append(x.detach())
+        self.stats["float"].append(y.detach())
+
+
+class OutputLogger(Logger):
+    r"""Class used to log the outputs of the module"""
+
+    def __init__(self):
+        super().__init__()
+        self.stats["tensor_val"] = []
+
+    def forward(self, x):
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+        self.stats["tensor_val"].append(x)
+        return x
+
+
+def _convert_tuple_to_list(t: Any) -> Any:
+    return [_convert_tuple_to_list(x) for x in t] if type(t) is tuple else t
+
+
+def _dequantize_tensor_list(t: Any) -> Any:
+    return (
+        [_dequantize_tensor_list(x) for x in t]
+        if type(t) is list
+        else t.dequantize()
+        if t.is_quantized
+        else t
+    )
+
+
+class Shadow(nn.Module):
+    r"""Shadow module attaches the float module to its matching quantized module
+    as the shadow. Then it uses Logger module to process the outputs of both
+    modules.
+
+    Args:
+        q_module: module quantized from float_module that we want to shadow
+        float_module: float module used to shadow q_module
+        logger_cls: type of logger used to process the outputs of q_module and
+            float_module. ShadowLogger or custom loggers can be used.
+    """
+
+    def __init__(self, q_module, float_module, logger_cls):
+        super().__init__()
+        self.orig_module = q_module
+        self.shadow_module = float_module
+        self.dequant = nnq.DeQuantize()
+        self.logger = logger_cls()
+
+    def forward(self, *x) -> torch.Tensor:
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+        xl = _convert_tuple_to_list(x)
+        output = self.orig_module(*xl)
+        xl_float = _dequantize_tensor_list(xl)
+        shadow_output = self.shadow_module(*xl_float)
+        self.logger(output, shadow_output)
+        return output
+
+    def add(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+        output = self.orig_module.add(x, y)
+        x = x.dequantize()
+        y = y.dequantize()
+        shadow_output = self.shadow_module.add(x, y)
+        self.logger(output, shadow_output)
+        return output
+
+    def add_scalar(self, x: torch.Tensor, y: float) -> torch.Tensor:
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+        output = self.orig_module.add_scalar(x, y)
+        x = x.dequantize()
+        shadow_output = self.shadow_module.add_scalar(x, y)
+        self.logger(output, shadow_output)
+        return output
+
+    def mul(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+        output = self.orig_module.mul(x, y)
+        x = x.dequantize()
+        y = y.dequantize()
+        shadow_output = self.shadow_module.mul(x, y)
+        self.logger(output, shadow_output)
+        return output
+
+    def mul_scalar(self, x: torch.Tensor, y: float) -> torch.Tensor:
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+        output = self.orig_module.mul_scalar(x, y)
+        x = x.dequantize()
+        shadow_output = self.shadow_module.mul_scalar(x, y)
+        self.logger(output, shadow_output)
+        return output
+
+    def cat(self, x: list[torch.Tensor], dim: int = 0) -> torch.Tensor:
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+        output = self.orig_module.cat(x, dim)
+        x = [y.dequantize() for y in x]
+        shadow_output = self.shadow_module.cat(x, dim)
+        self.logger(output, shadow_output)
+        return output
+
+    def add_relu(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+        output = self.orig_module.add_relu(x, y)
+        x = x.dequantize()
+        y = y.dequantize()
+        shadow_output = self.shadow_module.add_relu(x, y)
+        self.logger(output, shadow_output)
+        return output
+
+
+def prepare_model_with_stubs(
+    float_module: nn.Module,
+    q_module: nn.Module,
+    module_swap_list: set[type],
+    logger_cls: Callable,
+) -> None:
+    r"""Prepare the model by attaching the float module to its matching quantized
+    module as the shadow if the float module type is in module_swap_list.
+
+    Example usage::
+
+        prepare_model_with_stubs(float_model, q_model, module_swap_list, Logger)
+        q_model(data)
+        ob_dict = get_logger_dict(q_model)
+
+    Args:
+        float_module: float module used to generate the q_module
+        q_module: module quantized from float_module
+        module_swap_list: list of float module types to attach the shadow
+        logger_cls: type of logger to be used in shadow module to process the outputs of
+            quantized module and its float shadow module
+    """
+    torch._C._log_api_usage_once(
+        "quantization_api._numeric_suite.prepare_model_with_stubs"
+    )
+
+    float_module_children = dict(float_module.named_children())
+
+    reassign = {}
+    for name, mod in q_module.named_children():
+        if name not in float_module_children:
+            continue
+
+        float_mod = float_module_children[name]
+
+        if type(float_mod) not in module_swap_list:
+            prepare_model_with_stubs(float_mod, mod, module_swap_list, logger_cls)
+
+        # Insert shadow module only if the module is not of the same type as
+        # the floating point module
+        if type(float_mod) in module_swap_list and not _is_identical_module_type(
+            mod, float_mod
+        ):
+            reassign[name] = Shadow(mod, float_mod, logger_cls)
+
+    for key, value in reassign.items():
+        q_module._modules[key] = value
+
+
+def _is_identical_module_type(mod1, mod2):
+    # Compare if two modules have the same dtype
+    mod1_module_types = [type(mod) for mod in mod1.modules()]
+    mod2_module_types = [type(mod) for mod in mod2.modules()]
+    return mod1_module_types == mod2_module_types
+
+
+def compare_model_stub(
+    float_model: nn.Module,
+    q_model: nn.Module,
+    module_swap_list: set[type],
+    *data,
+    logger_cls=ShadowLogger,
+) -> dict[str, dict]:
+    r"""Compare quantized module in a model with its floating point counterpart,
+    feeding both of them the same input. Return a dict with key corresponding to
+    module names and each entry being a dictionary with two keys 'float' and
+    'quantized', containing the output tensors of quantized and its matching
+    float shadow module. This dict can be used to compare and compute the module
+    level quantization error.
+
+    This function first call prepare_model_with_stubs() to swap the quantized
+    module that we want to compare with the Shadow module, which takes quantized
+    module, corresponding float module and logger as input, and creates a forward
+    path inside to make the float module to shadow quantized module sharing the
+    same input. The logger can be customizable, default logger is ShadowLogger
+    and it will save the outputs of the quantized module and float module that
+    can be used to compute the module level quantization error.
+
+    Example usage::
+
+        module_swap_list = [
+            torchvision.models.quantization.resnet.QuantizableBasicBlock
+        ]
+        ob_dict = compare_model_stub(float_model, qmodel, module_swap_list, data)
+        for key in ob_dict:
+            print(
+                key,
+                compute_error(
+                    ob_dict[key]["float"], ob_dict[key]["quantized"].dequantize()
+                ),
+            )
+
+    Args:
+        float_model: float model used to generate the q_model
+        q_model: model quantized from float_model
+        module_swap_list: list of float module types at which shadow modules will
+            be attached.
+        data: input data used to run the prepared q_model
+        logger_cls: type of logger to be used in shadow module to process the outputs of
+            quantized module and its float shadow module
+    """
+    torch._C._log_api_usage_once("quantization_api._numeric_suite.compare_model_stub")
+    prepare_model_with_stubs(float_model, q_model, module_swap_list, logger_cls)
+    q_model(*data)
+    ob_dict = get_logger_dict(q_model)
+    return ob_dict
+
+
+def get_matching_activations(
+    float_module: nn.Module,
+    q_module: nn.Module,
+) -> dict[str, dict[str, torch.Tensor]]:
+    r"""Find the matching activation between float and quantized modules.
+
+    Args:
+        float_module: float module used to generate the q_module
+        q_module: module quantized from float_module
+
+    Return:
+        act_dict: dict with key corresponding to quantized module names and each
+        entry being a dictionary with two keys 'float' and 'quantized', containing
+        the matching float and quantized activations
+    """
+    torch._C._log_api_usage_once(
+        "quantization_api._numeric_suite.get_matching_activations"
+    )
+    float_dict = get_logger_dict(float_module)
+    quantized_dict = get_logger_dict(q_module)
+    act_dict: dict[str, dict] = {}
+    for key in quantized_dict:
+        if len(quantized_dict[key]["tensor_val"]) == 0:
+            continue
+        match_key = _find_match(sorted(float_dict, reverse=True), key, "stats")
+        if match_key is not None:
+            act_dict[key] = {}
+            act_dict[key]["float"] = float_dict[match_key]["tensor_val"]
+            act_dict[key]["quantized"] = quantized_dict[key]["tensor_val"]
+    return act_dict
+
+
+def prepare_model_outputs(
+    float_module: nn.Module,
+    q_module: nn.Module,
+    logger_cls=OutputLogger,
+    allow_list=None,
+) -> None:
+    r"""Prepare the model by attaching the logger to both float module
+    and quantized module if they are in the allow_list.
+
+    Args:
+        float_module: float module used to generate the q_module
+        q_module: module quantized from float_module
+        logger_cls: type of logger to be attached to float_module and q_module
+        allow_list: list of module types to attach logger
+    """
+    torch._C._log_api_usage_once(
+        "quantization_api._numeric_suite.prepare_model_outputs"
+    )
+    if allow_list is None:
+        allow_list = get_default_compare_output_module_list()
+
+    qconfig_debug = torch.ao.quantization.QConfig(activation=logger_cls, weight=None)
+    float_module.qconfig = qconfig_debug  # type: ignore[assignment]
+    prepare(
+        float_module, inplace=True, allow_list=allow_list, prepare_custom_config_dict={}
+    )
+    q_module.qconfig = qconfig_debug  # type: ignore[assignment]
+    prepare(
+        q_module,
+        inplace=True,
+        allow_list=allow_list,
+        observer_non_leaf_module_list=NON_LEAF_MODULE_TO_ADD_OBSERVER_ALLOW_LIST,
+        prepare_custom_config_dict={},
+    )
+
+
+def compare_model_outputs(
+    float_model: nn.Module,
+    q_model: nn.Module,
+    *data,
+    logger_cls=OutputLogger,
+    allow_list=None,
+) -> dict[str, dict[str, torch.Tensor]]:
+    r"""Compare output activations between float and quantized models at
+    corresponding locations for the same input. Return a dict with key corresponding
+    to quantized module names and each entry being a dictionary with two keys
+    'float' and 'quantized', containing the activations of quantized model and
+    float model at matching locations. This dict can be used to compare and
+    compute the propagation quantization error.
+
+    Example usage::
+
+        act_compare_dict = compare_model_outputs(float_model, qmodel, data)
+        for key in act_compare_dict:
+            print(
+                key,
+                compute_error(
+                    act_compare_dict[key]["float"],
+                    act_compare_dict[key]["quantized"].dequantize(),
+                ),
+            )
+
+    Args:
+        float_model: float model used to generate the q_model
+        q_model: model quantized from float_model
+        data: input data used to run the prepared float_model and q_model
+        logger_cls: type of logger to be attached to float_module and q_module
+        allow_list: list of module types to attach logger
+
+    Return:
+        act_compare_dict: dict with key corresponding to quantized module names
+        and each entry being a dictionary with two keys 'float' and 'quantized',
+        containing the matching float and quantized activations
+    """
+    torch._C._log_api_usage_once(
+        "quantization_api._numeric_suite.compare_model_outputs"
+    )
+    if allow_list is None:
+        allow_list = get_default_compare_output_module_list()
+    prepare_model_outputs(float_model, q_model, logger_cls, allow_list)
+    float_model(*data)
+    q_model(*data)
+    act_compare_dict = get_matching_activations(float_model, q_model)
+    return act_compare_dict
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/_numeric_suite_fx.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/_numeric_suite_fx.py
new file mode 100644
index 0000000000000000000000000000000000000000..1861d0160db152e73debda3bda7f714ca4bbf601
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/ns/_numeric_suite_fx.py
@@ -0,0 +1,1121 @@
+# mypy: allow-untyped-defs
+"""
+This module contains tooling to compare weights and activations
+across models. Example usage::
+
+    import copy
+    import torch
+    import torch.ao.quantization.quantize_fx as quantize_fx
+    import torch.ao.ns._numeric_suite_fx as ns
+
+    m = torch.nn.Sequential(torch.nn.Conv2d(1, 1, 1)).eval()
+    mp = quantize_fx.prepare_fx(m, {"": torch.ao.quantization.default_qconfig})
+    # We convert a copy because we need the original prepared model
+    # to be available for comparisons, and `quantize_fx.convert_fx` is inplace.
+    mq = quantize_fx.convert_fx(copy.deepcopy(mp))
+
+    #
+    # Comparing weights
+    #
+
+    # extract weight pairs
+    weight_comparison = ns.extract_weights("a", mp, "b", mq)
+
+    # add SQNR for each comparison, inplace
+    ns.extend_logger_results_with_comparison(
+        weight_comparison, "a", "b", torch.ao.ns.fx.utils.compute_sqnr, "sqnr"
+    )
+
+    # weight_comparison contains the weights from `mp` and `mq` stored
+    # in pairs, and can be used for further analysis.
+
+
+    #
+    # Comparing activations, with error propagation
+    #
+
+    # add loggers
+    mp_ns, mq_ns = ns.add_loggers(
+        "a", copy.deepcopy(mp), "b", copy.deepcopy(mq), ns.OutputLogger
+    )
+
+    # send an example datum to capture intermediate activations
+    datum = torch.randn(1, 1, 1, 1)
+    mp_ns(datum)
+    mq_ns(datum)
+
+    # extract intermediate activations
+    act_comparison = ns.extract_logger_info(mp_ns, mq_ns, ns.OutputLogger, "b")
+
+    # add SQNR for each comparison, inplace
+    ns.extend_logger_results_with_comparison(
+        act_comparison, "a", "b", torch.ao.ns.fx.utils.compute_sqnr, "sqnr"
+    )
+
+    # act_comparison contains the activations from `mp_ns` and `mq_ns` stored
+    # in pairs, and can be used for further analysis.
+
+    #
+    # Comparing activations, without error propagation
+    #
+
+    # create shadow model
+    mp_shadows_mq = ns.add_shadow_loggers(
+        "a", copy.deepcopy(mp), "b", copy.deepcopy(mq), ns.OutputLogger
+    )
+
+    # send an example datum to capture intermediate activations
+    datum = torch.randn(1, 1, 1, 1)
+    mp_shadows_mq(datum)
+
+    # extract intermediate activations
+    shadow_act_comparison = ns.extract_shadow_logger_info(
+        mp_shadows_mq, ns.OutputLogger, "b"
+    )
+
+    # add SQNR for each comparison, inplace
+    ns.extend_logger_results_with_comparison(
+        shadow_act_comparison, "a", "b", torch.ao.ns.fx.utils.compute_sqnr, "sqnr"
+    )
+
+    # shadow_act_comparison contains the activations from `mp_ns` and `mq_ns` stored
+    # in pairs, and can be used for further analysis.
+
+"""
+
+import collections
+from collections.abc import Callable
+from typing import Any, TYPE_CHECKING
+
+import torch
+import torch.ao.quantization.quantize_fx as quantize_fx
+import torch.nn as nn
+from torch.ao.ns.fx.graph_matcher import get_matching_subgraph_pairs
+from torch.ao.ns.fx.mappings import get_base_name_to_sets_of_related_ops
+from torch.ao.ns.fx.n_shadows_utils import (
+    _get_dedup_subgraphs,
+    create_add_loggers_graph,
+    create_n_transformed_and_logged_copies_of_subgraph,
+    create_results_comparison,
+    extract_weight_comparison,
+    group_results_by_subgraph,
+    OutputProp,
+    print_n_shadows_summary,
+    SHADOW_WRAPPER_NODE_NAME_PREFIX,
+)
+from torch.ao.ns.fx.qconfig_multi_mapping import QConfigMultiMapping
+from torch.ao.quantization import QConfigMapping
+from torch.ao.quantization.backend_config import BackendConfig
+from torch.ao.quantization.backend_config.utils import (
+    get_fusion_pattern_to_root_node_getter,
+)
+from torch.ao.quantization.fx.graph_module import _get_observed_graph_module_attr
+from torch.ao.quantization.fx.match_utils import _find_matches
+from torch.ao.quantization.fx.qconfig_mapping_utils import (
+    _generate_node_name_to_qconfig,
+)
+from torch.ao.quantization.fx.quantize_handler import _get_pattern_to_quantize_handlers
+from torch.fx import GraphModule
+from torch.fx.graph import Node
+
+from .fx.graph_passes import add_loggers_to_model, create_a_shadows_b
+from .fx.ns_types import NSNodeTargetType, NSResultsType, NSSingleResultValuesType
+from .fx.utils import (
+    get_target_type_str,
+    maybe_add_missing_fqns,
+    rekey_logger_info_on_node_name_of_model,
+)
+from .fx.weight_utils import extract_weight_from_node
+
+
+if TYPE_CHECKING:
+    from torch.ao.quantization.qconfig import QConfigAny
+
+RNNReturnType = tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]
+
+
+class OutputLogger(nn.Module):
+    """
+    Base class for capturing intermediate values.
+    """
+
+    stats: list[torch.Tensor]
+    stats_rnn: list[RNNReturnType]
+
+    # Mark as impure so that calls to it will not be removed during DCE.
+    _is_impure = True
+
+    def __init__(
+        self,
+        ref_node_name: str,
+        prev_node_name: str,
+        model_name: str,
+        ref_name: str,
+        prev_node_target_type: str,
+        ref_node_target_type: str,
+        results_type: str,
+        index_within_arg: int,
+        index_of_arg: int,
+        fqn: str | None,
+        qconfig_str: str | None = "",
+    ):
+        super().__init__()
+        self.stats: list[torch.Tensor] = []
+        self.stats_rnn: list[RNNReturnType] = []
+
+        # name of the node which was responsible for adding this logger
+        # Note:
+        # - if we are logging node outputs, this is the same as prev_node_name
+        # - if we are logging node inputs, this is the name of the node
+        #   whose input this logger is logging.
+        #
+        # example, where logger1 is logging input of op1 and logger2 is logging
+        #    the output of op1:
+        #
+        #  x1 -> logger1 -> op1 -> logger2 -> x2
+        #
+        # in this example,
+        #   - logger1's prev_node_name is x1 and ref_node_name is op1
+        #   - logger2's prev_node_name is op1 and ref_node_name is op1
+        self.ref_node_name = ref_node_name
+        # name of the node whose output this Logger is capturing
+        self.prev_node_name = prev_node_name
+
+        # name of the model from which the node originated from
+        self.model_name = model_name
+        # reference name, used to match loggers from separate models
+        # to each other
+        self.ref_name = ref_name
+        # type of the target of the node whose output this logger is logging
+        self.prev_node_target_type = prev_node_target_type
+        # type of the target of the node which was responsible for adding this
+        # logger
+        self.ref_node_target_type = ref_node_target_type
+        # what kind of values are inside of stats
+        self.results_type = results_type
+        # index of this node within the arg of the input/output node
+        # for example, in cat([x1, x2, x3], dim=0), x2 would have index_within_arg == 1
+        self.index_within_arg = index_within_arg
+        # index of this node within the args of the input/output node
+        # for example, in add(x1, x2), x2 would have index_of_arg == 1
+        self.index_of_arg = index_of_arg
+        # fully qualified name
+        self.fqn = fqn
+        # if loggers are added before prepare_fx, but we do not want
+        # collect results of calibration, only results after convert_fx
+        # so, we add a flag to control whether this logger collects data
+        self.enabled = True
+        # string representation of qconfig
+        self.qconfig_str = qconfig_str
+        # this can be turned off to reduce memory usage during calibration
+        self.save_activations = True
+
+    # Note: cannot annotate the type of x because TorchScript does not support
+    #   the Union type.
+    def forward(self, x):
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+        # TODO(future PR): consider designing this better, as the difference
+        # between these two flags is subtle and not obvious.
+        if not self.enabled:
+            return x
+        if not self.save_activations:
+            return x
+        # TODO(future PR): consider refactoring this to better reuse the parent
+        # class
+        if isinstance(x, torch.Tensor):
+            self.stats.append(x.detach())
+        elif isinstance(x, tuple) and len(x) == 2 and len(x[1]) == 2:
+            new_res = (x[0].detach(), (x[1][0].detach(), x[1][1].detach()))
+            self.stats_rnn.append(new_res)
+        return x
+
+    def __repr__(self):
+        clean_dict = {
+            k: v
+            for k, v in self.__dict__.items()
+            # skip nn.Module keys
+            if (k != "training") and not k.startswith("_")
+        }
+        return f"OutputLogger({clean_dict})"
+
+
+class OutputComparisonLogger(OutputLogger):
+    """
+    Same as OutputLogger, but also requires the original activation
+    in order to calculate the comparison at calibration time
+    """
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        # TODO(future PR): make the comparison function configurable
+        self.comparison_fn = torch.ao.ns.fx.utils.compute_sqnr
+        self.comparison_fn_name = "sqnr"
+        # precalculated comparisons of logger output versus reference
+        self.comparisons = []
+        # precalculated comparisons function
+
+    def forward(self, x, x_ref):  # type: ignore[override]
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+        if not self.enabled:
+            return x
+        if not isinstance(x, torch.Tensor):
+            raise AssertionError("non-tensor inputs not yet supported")
+        if self.save_activations:
+            # save the activation, for debugging
+            self.stats.append(x.detach())
+        # save the comparison
+        self.comparisons.append(self.comparison_fn(x, x_ref))
+        return x
+
+    def __repr__(self):
+        clean_dict = {
+            k: v
+            for k, v in self.__dict__.items()
+            # skip nn.Module keys
+            if (k != "training") and not k.startswith("_")
+        }
+        return f"OutputComparisonLogger({clean_dict})"
+
+
+class NSTracer(quantize_fx.QuantizationTracer):
+    """
+    Just like a regular FX quantization tracer, but treats observers and fake_quantize
+    modules as leaf modules.
+    """
+
+    def is_leaf_module(self, m: torch.nn.Module, module_qualified_name: str) -> bool:
+        # fmt: off
+        """
+        """  # blank docblock to make autodoc happy
+        # fmt: on
+        if isinstance(m, torch.ao.quantization.ObserverBase):
+            return True
+        elif isinstance(m, torch.ao.quantization.FakeQuantizeBase):
+            return True
+        return super().is_leaf_module(m, module_qualified_name)
+
+
+def _extract_weights_one_model(
+    model_name: str,
+    model: GraphModule,
+    nodes_and_names_to_instrument: list[tuple[Node, str]],
+    results: NSResultsType,
+    op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]]
+    | None = None,
+) -> None:
+    torch._C._log_api_usage_once(
+        "quantization_api._numeric_suite_fx._extract_weights_one_model"
+    )
+    for node, ref_name in nodes_and_names_to_instrument:
+        res_type = NSSingleResultValuesType.WEIGHT.value
+        extracted_weight = extract_weight_from_node(
+            node, model, op_to_type_to_weight_extraction_fn
+        )
+        if extracted_weight:
+            if ref_name not in results:
+                results[ref_name] = {res_type: {}}
+            results[ref_name][res_type][model_name] = [extracted_weight]
+
+
+def _extract_weights_impl(
+    model_name_a: str,
+    gm_a: GraphModule,
+    model_name_b: str,
+    gm_b: GraphModule,
+    base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
+    unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
+    op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]]
+    | None = None,
+) -> NSResultsType:
+    torch._C._log_api_usage_once(
+        "quantization_api._numeric_suite_fx._extract_weights_impl"
+    )
+    matched_subgraph_pairs = get_matching_subgraph_pairs(
+        gm_a, gm_b, base_name_to_sets_of_related_ops, unmatchable_types_map
+    )
+
+    # split the subgraph pairs into one data structure for each model
+    nodes_and_names_to_instrument_a: list[tuple[Node, str]] = []
+    nodes_and_names_to_instrument_b: list[tuple[Node, str]] = []
+    for match_name, match in matched_subgraph_pairs.items():
+        subgraph_a, subgraph_b = match
+        nodes_and_names_to_instrument_a.append((subgraph_a.base_op_node, match_name))
+        nodes_and_names_to_instrument_b.append((subgraph_b.base_op_node, match_name))
+
+    # populate the results, one model at a time
+    results: NSResultsType = {}
+    _extract_weights_one_model(
+        model_name_a,
+        gm_a,
+        nodes_and_names_to_instrument_a,
+        results,
+        op_to_type_to_weight_extraction_fn,
+    )
+    _extract_weights_one_model(
+        model_name_b,
+        gm_b,
+        nodes_and_names_to_instrument_b,
+        results,
+        op_to_type_to_weight_extraction_fn,
+    )
+
+    # fill in missing fqn entries
+    maybe_add_missing_fqns(results)
+
+    # rekey on names of nodes in gm_b
+    results = rekey_logger_info_on_node_name_of_model(results, model_name_b)
+
+    return results
+
+
+def extract_weights(
+    model_name_a: str,
+    model_a: nn.Module,
+    model_name_b: str,
+    model_b: nn.Module,
+    base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
+    unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
+    op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]]
+    | None = None,
+) -> NSResultsType:
+    """
+    Extract weights from model A and model B, and return a comparison.
+
+    Args:
+        model_name_a: string name of model A to use in results
+        model_a: model A
+        model_name_b: string name of model B to use in results
+        model_b: model B
+        base_name_to_sets_of_related_ops: optional override of subgraph base nodes, subject to change
+        unmatchable_types_map: optional override of unmatchable types, subject to change
+        op_to_type_to_weight_extraction_fn: optional override of function which extracts weight
+            from a type, subject to change
+
+    Return:
+        NSResultsType, containing the weight comparisons
+    """
+
+    torch._C._log_api_usage_once("quantization_api._numeric_suite_fx.extract_weights")
+    if base_name_to_sets_of_related_ops is None:
+        base_name_to_sets_of_related_ops = get_base_name_to_sets_of_related_ops()
+
+    # TODO(future PR): expose these
+    skipped_module_names: list[str] = []
+    skipped_module_classes: list[Callable] = []
+    tracer_a = NSTracer(skipped_module_names, skipped_module_classes)
+    tracer_b = NSTracer(skipped_module_names, skipped_module_classes)
+    gm_a = GraphModule(model_a, tracer_a.trace(model_a))
+    maybe_model_a_node_name_to_scope = _get_observed_graph_module_attr(
+        model_a, "node_name_to_scope"
+    )
+    if maybe_model_a_node_name_to_scope is not None:
+        gm_a._node_name_to_scope = maybe_model_a_node_name_to_scope
+    gm_b = GraphModule(model_b, tracer_b.trace(model_b))
+    maybe_model_b_node_name_to_scope = _get_observed_graph_module_attr(
+        model_b, "node_name_to_scope"
+    )
+    if maybe_model_b_node_name_to_scope is not None:
+        gm_b._node_name_to_scope = maybe_model_b_node_name_to_scope
+    return _extract_weights_impl(
+        model_name_a,
+        gm_a,
+        model_name_b,
+        gm_b,
+        base_name_to_sets_of_related_ops,
+        unmatchable_types_map,
+        op_to_type_to_weight_extraction_fn,
+    )
+
+
+def _add_loggers_one_model(
+    model_name: str,
+    model: GraphModule,
+    nodes_and_names_to_instrument_inputs: list[tuple[Node, str, str]],
+    nodes_and_names_to_instrument_outputs: list[tuple[Node, str, str]],
+    logger_cls: Callable,
+) -> nn.Module:
+    torch._C._log_api_usage_once(
+        "quantization_api._numeric_suite_fx._add_loggers_one_model"
+    )
+
+    # TODO(future PR): do not observe nodes we do not care
+    #   about (both fp32, denylist, etc)
+    node_to_instrument_inputs_to_ref_name: dict[Node, tuple[str, str]] = {}
+    node_to_instrument_outputs_to_ref_name: dict[Node, tuple[str, str]] = {}
+    for node, ref_name, ref_node_type in nodes_and_names_to_instrument_inputs:
+        node_to_instrument_inputs_to_ref_name[node] = (ref_name, ref_node_type)
+    for node, ref_name, ref_node_type in nodes_and_names_to_instrument_outputs:
+        node_to_instrument_outputs_to_ref_name[node] = (ref_name, ref_node_type)
+
+    model = add_loggers_to_model(
+        model,
+        node_to_instrument_inputs_to_ref_name,
+        node_to_instrument_outputs_to_ref_name,
+        logger_cls,
+        model_name,
+    )
+    return model
+
+
+def _add_loggers_impl(
+    name_a: str,
+    gm_a: GraphModule,
+    name_b: str,
+    gm_b: GraphModule,
+    logger_cls: Callable,
+    should_log_inputs: bool,
+    base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
+    unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
+) -> tuple[nn.Module, nn.Module]:
+    torch._C._log_api_usage_once("quantization_api._numeric_suite_fx._add_loggers_impl")
+    matched_subgraph_pairs = get_matching_subgraph_pairs(
+        gm_a, gm_b, base_name_to_sets_of_related_ops, unmatchable_types_map
+    )
+    nodes_and_names_to_instrument_inputs_a = []
+    nodes_and_names_to_instrument_inputs_b = []
+    nodes_and_names_to_instrument_outputs_a = []
+    nodes_and_names_to_instrument_outputs_b = []
+    for match_name, (subgraph_a, subgraph_b) in matched_subgraph_pairs.items():
+        ref_node_type_a = get_target_type_str(subgraph_a.base_op_node, gm_a)
+        ref_node_type_b = get_target_type_str(subgraph_b.base_op_node, gm_b)
+        # Note: for matching inputs we use start_node, such as observing
+        # the input of linear in linear-relu
+        if should_log_inputs:
+            nodes_and_names_to_instrument_inputs_a.append(
+                (subgraph_a.start_node, match_name, ref_node_type_a)
+            )
+            nodes_and_names_to_instrument_inputs_b.append(
+                (subgraph_b.start_node, match_name, ref_node_type_b)
+            )
+        # Note: for matching activations we always use end_node,
+        # such as observing the output of relu in linear-relu
+        nodes_and_names_to_instrument_outputs_a.append(
+            (subgraph_a.end_node, match_name, ref_node_type_a)
+        )
+        nodes_and_names_to_instrument_outputs_b.append(
+            (subgraph_b.end_node, match_name, ref_node_type_b)
+        )
+
+    new_model_a = _add_loggers_one_model(
+        name_a,
+        gm_a,
+        nodes_and_names_to_instrument_inputs_a,
+        nodes_and_names_to_instrument_outputs_a,
+        logger_cls,
+    )
+    new_model_b = _add_loggers_one_model(
+        name_b,
+        gm_b,
+        nodes_and_names_to_instrument_inputs_b,
+        nodes_and_names_to_instrument_outputs_b,
+        logger_cls,
+    )
+    return (new_model_a, new_model_b)
+
+
+def add_loggers(
+    name_a: str,
+    model_a: nn.Module,
+    name_b: str,
+    model_b: nn.Module,
+    logger_cls: Callable,
+    should_log_inputs: bool = False,
+    base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
+    unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
+) -> tuple[nn.Module, nn.Module]:
+    """
+    Instrument model A and model B with loggers.
+
+    Args:
+        name_a: string name of model A to use in results
+        model_a: model A
+        name_b: string name of model B to use in results
+        model_b: model B
+        logger_cls: class of Logger to use
+        base_name_to_sets_of_related_ops: optional override of subgraph base nodes, subject to change
+        unmatchable_types_map: optional override of unmatchable types, subject to change
+
+    Return:
+        Returns a tuple of (model_a_with_loggers, model_b_with_loggers).  Modifies both models inplace.
+    """
+
+    torch._C._log_api_usage_once("quantization_api._numeric_suite_fx.add_loggers")
+    # TODO(future PR): expose these
+    skipped_module_names: list[str] = []
+    skipped_module_classes: list[Callable] = []
+    tracer_a = NSTracer(skipped_module_names, skipped_module_classes)
+    tracer_b = NSTracer(skipped_module_names, skipped_module_classes)
+    gm_a = GraphModule(model_a, tracer_a.trace(model_a))
+    maybe_model_a_node_name_to_scope = _get_observed_graph_module_attr(
+        model_a, "node_name_to_scope"
+    )
+    if maybe_model_a_node_name_to_scope is not None:
+        gm_a._node_name_to_scope = maybe_model_a_node_name_to_scope
+    gm_b = GraphModule(model_b, tracer_b.trace(model_b))
+    maybe_model_b_node_name_to_scope = _get_observed_graph_module_attr(
+        model_b, "node_name_to_scope"
+    )
+    if maybe_model_b_node_name_to_scope is not None:
+        gm_b._node_name_to_scope = maybe_model_b_node_name_to_scope
+    return _add_loggers_impl(
+        name_a,
+        gm_a,
+        name_b,
+        gm_b,
+        logger_cls,
+        should_log_inputs=should_log_inputs,
+        base_name_to_sets_of_related_ops=base_name_to_sets_of_related_ops,
+        unmatchable_types_map=unmatchable_types_map,
+    )
+
+
+def _extract_logger_info_one_model(
+    model: nn.Module,
+    results: NSResultsType,
+    logger_cls: Callable,
+) -> None:
+    torch._C._log_api_usage_once(
+        "quantization_api._numeric_suite_fx._extract_logger_info_one_model"
+    )
+    for _gm_name, mod in model.named_modules():
+        # TODO(future PR): better check when scripted
+        is_logger = isinstance(mod, logger_cls) or (  # type: ignore[arg-type]
+            isinstance(mod, torch.jit.RecursiveScriptModule)
+            and mod.original_name == "OutputLogger"
+        )
+        if is_logger:
+            key = mod.ref_name
+            if key not in results:
+                results[key] = {}
+            if mod.model_name in results[key]:
+                raise AssertionError(f"{mod.model_name} is already present in results")
+            if mod.results_type not in results[key]:
+                results[key][mod.results_type] = {}
+            if mod.model_name not in results[key][mod.results_type]:
+                results[key][mod.results_type][mod.model_name] = []
+            stats_to_use = mod.stats
+            if len(mod.stats_rnn) > 0:
+                stats_to_use = mod.stats_rnn
+            data = {
+                "type": mod.results_type,
+                "values": stats_to_use,
+                "ref_node_name": mod.ref_node_name,
+                "ref_node_target_type": mod.ref_node_target_type,
+                "prev_node_name": mod.prev_node_name,
+                "prev_node_target_type": mod.prev_node_target_type,
+                "index_within_arg": mod.index_within_arg,
+                "index_of_arg": mod.index_of_arg,
+                "fqn": mod.fqn,
+                "qconfig_str": mod.qconfig_str,
+            }
+            if hasattr(mod, "comparisons"):
+                data["comparisons"] = mod.comparisons
+                data["comparison_fn_name"] = mod.comparison_fn_name
+            else:
+                data["comparisons"] = []
+                data["comparison_fn_name"] = ""
+            results[key][mod.results_type][mod.model_name].append(data)
+            # ensure the list stays sorted
+            results[key][mod.results_type][mod.model_name].sort(
+                key=lambda res: f"{res['index_of_arg']}:{res['index_within_arg']}"
+            )
+
+
+# TODO(future PR): align on naming
+# this is equivalent of just the comparison extraction part of `ns.compare_model_outputs`
+def extract_logger_info(
+    model_a: nn.Module,
+    model_b: nn.Module,
+    logger_cls: Callable,
+    model_name_to_use_for_layer_names: str,
+) -> NSResultsType:
+    """
+    Traverse all loggers in `model_a` and `model_b`, and extract the logged
+    information.
+
+    Args:
+        model_a: model A
+        model_b: model B
+        logger_cls: class of Logger to use
+        model_name_to_use_for_layer_names: string name of model to use for
+          layer names in the output
+
+    Return:
+        NSResultsType, containing the logged comparisons
+    """
+    torch._C._log_api_usage_once(
+        "quantization_api._numeric_suite_fx.extract_logger_info"
+    )
+    results: NSResultsType = {}
+    for model in (model_a, model_b):
+        _extract_logger_info_one_model(model, results, logger_cls)
+    # fill in missing fqn entries
+    maybe_add_missing_fqns(results)
+    # rekey on the name of model b
+    results = rekey_logger_info_on_node_name_of_model(
+        results, model_name_to_use_for_layer_names
+    )
+    return results
+
+
+def _add_shadow_loggers_impl(
+    name_a: str,
+    gm_a: GraphModule,
+    name_b: str,
+    gm_b: GraphModule,
+    logger_cls: Callable,
+    should_log_inputs: bool,
+    base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
+    node_type_to_io_type_map: dict[str, set[NSNodeTargetType]] | None = None,
+    unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
+) -> nn.Module:
+    torch._C._log_api_usage_once(
+        "quantization_api._numeric_suite_fx._add_shadow_loggers_impl"
+    )
+    matched_subgraph_pairs = get_matching_subgraph_pairs(
+        gm_a, gm_b, base_name_to_sets_of_related_ops, unmatchable_types_map
+    )
+    gm_a_shadows_b = create_a_shadows_b(
+        name_a,
+        gm_a,
+        name_b,
+        gm_b,
+        matched_subgraph_pairs,
+        logger_cls,
+        should_log_inputs=should_log_inputs,
+        node_type_to_io_type_map=node_type_to_io_type_map,
+    )
+    return gm_a_shadows_b
+
+
+def add_shadow_loggers(
+    name_a: str,
+    model_a: nn.Module,
+    name_b: str,
+    model_b: nn.Module,
+    logger_cls: Callable,
+    should_log_inputs: bool = False,
+    base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
+    node_type_to_io_type_map: dict[str, set[NSNodeTargetType]] | None = None,
+    unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
+) -> nn.Module:
+    """
+    Instrument model A and model B with shadow loggers.
+
+    Args:
+        name_a: string name of model A to use in results
+        model_a: model A
+        name_b: string name of model B to use in results
+        model_b: model B
+        logger_cls: class of Logger to use
+        should_log_inputs: whether to log inputs
+        base_name_to_sets_of_related_ops: optional override of subgraph base nodes, subject to change
+        unmatchable_types_map: optional override of unmatchable types, subject to change
+    """
+    torch._C._log_api_usage_once(
+        "quantization_api._numeric_suite_fx.add_shadow_loggers"
+    )
+    # TODO(future PR): expose these
+    skipped_module_names: list[str] = []
+    skipped_module_classes: list[Callable] = []
+    tracer_a = NSTracer(skipped_module_names, skipped_module_classes)
+    tracer_b = NSTracer(skipped_module_names, skipped_module_classes)
+    gm_a = GraphModule(model_a, tracer_a.trace(model_a))
+    maybe_model_a_node_name_to_scope = _get_observed_graph_module_attr(
+        model_a, "node_name_to_scope"
+    )
+    if maybe_model_a_node_name_to_scope is not None:
+        gm_a._node_name_to_scope = maybe_model_a_node_name_to_scope
+    gm_b = GraphModule(model_b, tracer_b.trace(model_b))
+    maybe_model_b_node_name_to_scope = _get_observed_graph_module_attr(
+        model_b, "node_name_to_scope"
+    )
+    if maybe_model_b_node_name_to_scope is not None:
+        gm_b._node_name_to_scope = maybe_model_b_node_name_to_scope
+    return _add_shadow_loggers_impl(
+        name_a,
+        gm_a,
+        name_b,
+        gm_b,
+        logger_cls,
+        should_log_inputs=should_log_inputs,
+        base_name_to_sets_of_related_ops=base_name_to_sets_of_related_ops,
+        node_type_to_io_type_map=node_type_to_io_type_map,
+        unmatchable_types_map=unmatchable_types_map,
+    )
+
+
+def extract_shadow_logger_info(
+    model_a_shadows_b: nn.Module,
+    logger_cls: Callable,
+    model_name_to_use_for_layer_names: str,
+) -> NSResultsType:
+    """
+    Traverse all loggers in a shadow model, and extract the logged
+    information.
+
+    Args:
+        model_a_shadows_b: shadow model
+        logger_cls: class of Logger to use
+        model_name_to_use_for_layer_names: string name of model to use for
+          layer names in the output
+
+    Return:
+        NSResultsType, containing the logged comparisons
+    """
+    torch._C._log_api_usage_once(
+        "quantization_api._numeric_suite_fx.extract_shadow_logger_info"
+    )
+    results: NSResultsType = collections.defaultdict(dict)
+    _extract_logger_info_one_model(model_a_shadows_b, results, logger_cls)
+    # fill in missing fqn entries
+    maybe_add_missing_fqns(results)
+    # rekey on the name of model b
+    results = rekey_logger_info_on_node_name_of_model(
+        results, model_name_to_use_for_layer_names
+    )
+    return dict(results)
+
+
+def extend_logger_results_with_comparison(
+    results: NSResultsType,
+    model_name_1: str,
+    model_name_2: str,
+    comparison_fn: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
+    comparison_name: str,
+) -> None:
+    """
+    Compares the logged values from `model_name_2` against the corresponding
+    values in `model_name_1`, using `comparison_fn`. Records the result
+    in `model_name_2`'s results under `comparison_name`. Modifies `results` inplace.
+
+    Args:
+        results: the result data structure from `extract_logger_info` or
+          `extract_shadow_logger_info`.
+        model_name_1: string name of model 1
+        model_name_2: string name of model 2
+        comparison_fn: function to compare two Tensors
+        comparison_name: string name of model to use for
+          layer names in the output
+    """
+    for results_type_to_results in results.values():
+        for model_name_to_results in results_type_to_results.values():
+            if model_name_1 not in model_name_to_results:
+                raise AssertionError(f"{model_name_1} not found in results")
+            if model_name_2 not in model_name_to_results:
+                raise AssertionError(f"{model_name_2} not found in results")
+
+            results_1 = model_name_to_results[model_name_1]
+            results_2 = model_name_to_results[model_name_2]
+
+            for result_2 in results_2:
+                index_within_arg_2 = result_2["index_within_arg"]
+                index_of_arg_2 = result_2["index_of_arg"]
+                # find corresponding result_1
+                result_1 = None
+                for cur_result_1 in results_1:
+                    index_within_arg_1 = cur_result_1["index_within_arg"]
+                    index_of_arg_1 = cur_result_1["index_of_arg"]
+                    if (index_within_arg_1 == index_within_arg_2) and (
+                        index_of_arg_1 == index_of_arg_2
+                    ):
+                        result_1 = cur_result_1
+                        break
+                if result_1 is None:
+                    raise AssertionError("Expected result_1 to be not None")
+
+                values_1 = result_1["values"]
+                values_2 = result_2["values"]
+                result_2[comparison_name] = []
+                for value_1, value_2 in zip(values_1, values_2):
+                    comparison_result = comparison_fn(value_1, value_2)
+                    result_2[comparison_name].append(comparison_result)
+
+
+def prepare_n_shadows_model(
+    model: torch.nn.Module,
+    example_inputs: Any,
+    qconfig_multi_mapping: QConfigMultiMapping,
+    backend_config: BackendConfig,
+    custom_prepare_fn: Callable | None = None,
+    custom_prepare_kwargs: dict[str, Any] | None = None,
+    custom_tracer: Any = None,
+) -> GraphModule:
+    """
+    Given a model with a graph with M ops such as
+
+
+      args_kwargs_m -> op_m -> output_m
+
+
+    And a set of N qconfigs for each op, creates a new model, with
+    each of the subgraph of `op_m` transformed into
+
+    .. code::
+
+           |---------> op_m_n -> log_m_n
+           |                     /
+      args_kwargs_m ---------> op_m -> log_m_0
+
+    Where op_m_n is op_m wrapped in a submodule and transformed with
+    qconfig_n, and its inner graph looks like
+
+    .. code::
+
+      args_m -------- op_m_prepared_with_qconfig_n -> out_m_n
+                  /
+      kwargs_m ---
+
+    This is useful for testing different quantization of multiple layers in
+    a single pass through the model.
+
+    High level TODOs for future PRs:
+    * figure out a better way to name the output structure
+    * return a results data structure instead of printing it out
+    * add examples to docblocks
+    """
+
+    if custom_tracer is None:
+        tracer = quantize_fx.QuantizationTracer([], [])
+    else:
+        tracer = custom_tracer
+    mt = torch.fx.GraphModule(model, tracer.trace(model))
+    # this is necessary to ensure logger FQNs get populated
+    mt._node_name_to_scope = tracer.node_name_to_scope  # type: ignore[assignment]
+
+    # run example input propagation, we need this to call prepare_fx on
+    # individual subgraphs
+    output_prop = OutputProp(mt)
+    output_prop.propagate(*example_inputs)
+
+    # Find the set of subgraphs in the original graph which we need to
+    # consider.
+    modules = dict(mt.named_modules(remove_duplicate=False))
+    patterns = _get_pattern_to_quantize_handlers(backend_config)
+    root_node_getter_mapping = get_fusion_pattern_to_root_node_getter(backend_config)
+    standalone_module_names: list[str] = []
+    standalone_module_classes: list[type] = []
+    custom_module_classes: list[type] = []
+    matches = _find_matches(
+        mt.graph,
+        modules,
+        patterns,
+        root_node_getter_mapping,
+        standalone_module_names,
+        standalone_module_classes,
+        custom_module_classes,
+    )
+    subgraphs_dedup: dict[str, list[Node]] = _get_dedup_subgraphs(matches)
+
+    # generate node to qconfig for each subgraph
+    # TODO(future PR): deduplicate repeating entries
+    list_of_node_name_to_qconfig: list[dict[str, QConfigAny]] = []
+    for qconfig_mapping in qconfig_multi_mapping.qconfig_mappings_list:
+        node_name_to_qconfig = _generate_node_name_to_qconfig(
+            mt, modules, mt.graph, qconfig_mapping, tracer.node_name_to_scope
+        )
+        list_of_node_name_to_qconfig.append(node_name_to_qconfig)
+
+    # For each region in the model, do the following:
+    #   For each qconfig for that region, do the following:
+    #     1. create a copy of the region wrapped in a module
+    #     2. pass original args, original kwargs, and expected output to module
+    #     3. add an output comparison logger and hook it up to compare
+    #        actual output to expected output
+    #     4. run `prepare_fx` on the module
+    for subgraph_idx, (match_name, nodes_in_this_subgraph) in enumerate(
+        subgraphs_dedup.items()
+    ):
+        create_n_transformed_and_logged_copies_of_subgraph(
+            mt,
+            subgraph_idx,
+            match_name,
+            nodes_in_this_subgraph,
+            qconfig_multi_mapping.qconfig_mappings_list,
+            list_of_node_name_to_qconfig,
+            custom_prepare_fn,
+            custom_prepare_kwargs,  # type: ignore[arg-type]
+        )
+
+    return mt
+
+
+# TODO(future PR): we should rethink the names of all the PNP APIs
+def _prepare_n_shadows_add_loggers_model(
+    model: torch.nn.Module,
+    example_inputs: Any,
+    qconfig_mapping: QConfigMapping,
+    backend_config: BackendConfig,
+) -> torch.nn.Module:
+    r"""
+    Note: this API is not recommended for wide usage, it is only
+    provided for customers who need to migrate from the `add_loggers`
+    API.
+
+    This creates a model which provides logging for the following
+    problem: if we quantize `model` with `qconfig_mapping` and feed
+    the same input through both models, log the comparisons of
+    corresponding intermediate layers.
+
+    The problem is solved with a single model.  Specifically, we
+    partition `model` into N subgraphs, create a copy of each relevant
+    subgraph, wrap it in a module, apply the quantization API to that
+    module, and hook up loggers to measure the comparisons.
+
+    Example starting graph:
+
+      x0 -> op0 -> x1 -> op1 -> x2
+
+    Example config: quantize op0 to int8, do nothing to op1.
+    The following graph will be created:
+
+    .. code::
+
+      x0_0 -> op0_0 -> x1_0 -> log -----> op1_0 -> x2_0 -> log
+       \                        \                           \       # noqa: W605
+         ---> op0_1 -> x1_1 ----> clog -> op1_0 -> x2_1 ----> clog
+
+    Where op0_0 is op0, op0_1 is op0 wrapped in a submodule and quantized
+    to int8, op1_0 is op1 (appearing in the graph twice), log is a logger,
+    and clog is a comparison logger.
+    """
+
+    tracer = quantize_fx.QuantizationTracer([], [])
+    mt = torch.fx.GraphModule(model, tracer.trace(model))
+    # this is necessary to ensure logger FQNs get populated
+    mt._node_name_to_scope = tracer.node_name_to_scope  # type: ignore[assignment]
+
+    # run example input propagation, we need this to call prepare_fx on
+    # individual subgraphs
+    output_prop = OutputProp(mt)
+    output_prop.propagate(*example_inputs)
+
+    # Find the set of subgraphs in the original graph which we need to
+    # consider.
+    modules = dict(mt.named_modules(remove_duplicate=False))
+    patterns = _get_pattern_to_quantize_handlers(backend_config)
+    root_node_getter_mapping = get_fusion_pattern_to_root_node_getter(backend_config)
+    standalone_module_names: list[str] = []
+    standalone_module_classes: list[type] = []
+    custom_module_classes: list[type] = []
+    matches = _find_matches(
+        mt.graph,
+        modules,
+        patterns,
+        root_node_getter_mapping,
+        standalone_module_names,
+        standalone_module_classes,
+        custom_module_classes,
+    )
+    subgraphs_dedup: dict[str, list[Node]] = _get_dedup_subgraphs(matches)
+
+    # generate node to qconfig for each subgraph
+    node_name_to_qconfig = _generate_node_name_to_qconfig(
+        mt, modules, mt.graph, qconfig_mapping, tracer.node_name_to_scope
+    )
+
+    # Now, mutate the graph to be the add_loggers graph with propagation
+    # error.
+    create_add_loggers_graph(mt, subgraphs_dedup, qconfig_mapping, node_name_to_qconfig)
+
+    return mt
+
+
+# TODO(future PR): we should rethink the names of all the PNP APIs
+def _n_shadows_compare_weights(
+    model: torch.nn.Module,
+    example_inputs: Any,
+    qconfig_mapping: QConfigMapping,
+    backend_config: BackendConfig,
+) -> NSResultsType:
+    """
+    Note: this API is not recommended for wide usage, it is only
+    provided for customers who need to migrate from the `add_loggers`
+    API.
+    """
+    qconfig_multi_mapping = QConfigMultiMapping.from_list_qconfig_mapping(
+        [qconfig_mapping]
+    )
+    mp = prepare_n_shadows_model(
+        model, example_inputs, qconfig_multi_mapping, backend_config
+    )
+    # passing inputs through the model is necessary to populate
+    # observers which observe weights with real values
+    mp(*example_inputs)
+    mq = convert_n_shadows_model(mp)
+    weight_comparison = extract_weight_comparison(mq)
+    return weight_comparison
+
+
+# TODO(future PR): consider aligning API signature with other similar quantization
+# functions (enable_fake_quant, etc)
+def loggers_set_enabled(model: torch.nn.Module, enabled: bool) -> None:
+    """
+    Sets the `enabled` setting on a `model`'s loggers
+    """
+    for _, child in model.named_modules():
+        if isinstance(child, OutputLogger):
+            child.enabled = enabled
+
+
+# TODO(future PR): consider aligning API signature with other similar quantization
+# functions (enable_fake_quant, etc)
+def loggers_set_save_activations(
+    model: torch.nn.Module,
+    save_activations: bool,
+) -> None:
+    """
+    Sets the `save_activations` setting on a `model`'s loggers
+    """
+    for _name, child in model.named_modules():
+        if isinstance(child, OutputLogger):
+            child.save_activations = save_activations
+
+
+def convert_n_shadows_model(
+    model: GraphModule,
+    custom_convert_fn: Callable | None = None,
+    custom_convert_kwargs: dict[str, Any] | None = None,
+) -> GraphModule:
+    """
+    Given a model from `prepare_n_shadows_model`, runs `convert_fx`
+    on each shadow submodule.
+    """
+    for node in model.graph.nodes:
+        # TODO(future PR): consider matching in a safer way than
+        # node name string match
+        if node.name.startswith(SHADOW_WRAPPER_NODE_NAME_PREFIX):
+            orig_mod = getattr(model, node.name)
+            if custom_convert_fn is None:
+                converted_mod = torch.ao.quantization.quantize_fx.convert_fx(orig_mod)
+            else:
+                if custom_convert_kwargs is None:
+                    custom_convert_kwargs = {}
+                converted_mod = custom_convert_fn(orig_mod, **custom_convert_kwargs)
+            setattr(model, node.name, converted_mod)
+
+    return model
+
+
+def extract_results_n_shadows_model(model: torch.nn.Module) -> NSResultsType:
+    """
+    Extracts logger results from `model`.
+    """
+    results: NSResultsType = {}
+    _extract_logger_info_one_model(model, results, OutputLogger)
+    return results
+
+
+def print_comparisons_n_shadows_model(results: NSResultsType) -> None:
+    """
+    Prints a summary of extracted `results`.
+    """
+    results_grouped = group_results_by_subgraph(results)
+    results_comparison = create_results_comparison(results_grouped)
+    print_n_shadows_summary(results_comparison)
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d2f95c8d1ae4ca0f724dae099fb648c530ac68d
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/graph_matcher.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/graph_matcher.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26f430e40c9041084d23068985a8407e3616f9f8
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/graph_matcher.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/graph_passes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/graph_passes.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fc035f4fe661a05c35d43907aaa316440bb7511
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/graph_passes.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/mappings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/mappings.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b9e771185ce7cf64fbda46e47412ddff87751518
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/mappings.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/n_shadows_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/n_shadows_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd37efc43e235d142e104f68bb63f9f4ddfa1ca4
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/n_shadows_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/ns_types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/ns_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d58bd347eb862aee2c9e628bbb565f8bbc81e14
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/ns_types.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/pattern_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/pattern_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b5adb97e9209e8ab4a867989baf4c305da33b2c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/pattern_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/qconfig_multi_mapping.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/qconfig_multi_mapping.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..51ff3936e8eb334a0f194dd600d04acf8791e204
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/qconfig_multi_mapping.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21bf3549bb9c400868add005b2aed4900ac5c4f7
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/weight_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/weight_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1014652b2f921485e44c73c47f85c8b362ca8b82
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/weight_utils.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/graph_matcher.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/graph_matcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8dbd98e31375253e13ddc4ef8ba742ceab72884
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/graph_matcher.py
@@ -0,0 +1,485 @@
+# mypy: allow-untyped-defs
+import collections
+import enum
+from typing import Any
+
+import torch
+from torch.ao.quantization import FakeQuantizeBase, ObserverBase
+from torch.ao.quantization.utils import getattr_from_fqn
+from torch.fx import GraphModule
+from torch.fx.graph import Graph, Node
+
+from .mappings import get_base_name_to_sets_of_related_ops, get_unmatchable_types_map
+from .ns_types import NSNodeTargetType, NSSubgraph
+from .pattern_utils import (
+    end_node_matches_reversed_fusion,
+    get_reversed_fusions,
+    get_type_a_related_to_b,
+)
+
+
+toq = torch.ops.quantized
+
+
+def _get_output_nodes(g: Graph) -> list[Node]:
+    return [n for n in g.nodes if n.op == "output"]
+
+
+class _NSGraphMatchableSubgraphsIterator:
+    """
+    Iterates through the graph of gm, starting with the output nodes
+    and continuing backwards.
+    1. Returns matchable subgraphs, in order. A subgraph is defined by
+       (start_node, end_node).
+    2. Skips over non-matchable subgraphs
+    """
+
+    def __init__(
+        self,
+        gm: GraphModule,
+        non_matchable_functions: set[NSNodeTargetType],
+        non_matchable_modules: set[NSNodeTargetType],
+        non_matchable_methods: set[NSNodeTargetType],
+    ):
+        self.gm: GraphModule = gm
+        self.non_matchable_functions: set[NSNodeTargetType] = non_matchable_functions
+        self.non_matchable_modules: set[NSNodeTargetType] = non_matchable_modules
+        self.non_matchable_methods: set[NSNodeTargetType] = non_matchable_methods
+        self.seen_nodes: set[Node] = set()
+        self.stack: list[Node] = []
+        for start_node in _get_output_nodes(self.gm.graph):
+            self.stack.append(start_node)
+
+    def __iter__(self):
+        return self
+
+    def __next__(self) -> NSSubgraph:
+        """
+        Returns the next matchable subgraph.
+        """
+        while len(self.stack) > 0:
+            cur_end_node = self.stack.pop()
+            if cur_end_node in self.seen_nodes:
+                continue
+
+            # for subgraphs which are single nodes, start_node == end_node
+            # for subgraphs with more than one node, start node != end_node
+            cur_start_node = cur_end_node
+            # Subgraphs like linear-relu have the base node as the start node.
+            # Subgraphs like dequantize-linear-relu-to(torch.float16) have the
+            #   base node as the second node.
+            # The cur_base_op_node var will move to the actual node during
+            #   the fusion matching later in this code block.
+            cur_base_op_node = cur_end_node
+
+            # Check for potential fusions. For now, we are greedy
+            # and always skip all non-base nodes of a fusion.  For example,
+            # if we match linear-relu backwards, we will always skip the
+            # relu node and attempt to match the linear node.  This can
+            # be made configurable later if needed.
+            for _reverse_fusion_ops, base_op_idx in get_reversed_fusions():
+                is_match = end_node_matches_reversed_fusion(
+                    cur_end_node, _reverse_fusion_ops, self.gm, self.seen_nodes
+                )
+                if is_match:
+                    # navigate to the base node
+                    # pyrefly: ignore [bad-assignment, non-convergent-recursion]
+                    for rev_fusion_idx in range(len(_reverse_fusion_ops) - 1):
+                        # pyrefly: ignore [bad-argument-type]
+                        self.seen_nodes.add(cur_start_node)
+                        # for now, assume that there are no other nodes
+                        # which need to be added to the stack
+                        cur_start_node = cur_start_node.args[0]  # type: ignore[assignment]
+                        # if the base op index matches the current node, set it
+                        rev_base_op_idx = len(_reverse_fusion_ops) - 2 - base_op_idx
+                        if rev_fusion_idx == rev_base_op_idx:
+                            cur_base_op_node = cur_start_node
+                    break
+
+            # pyrefly: ignore [bad-argument-type]
+            self.seen_nodes.add(cur_start_node)
+            # add args of previous nodes to stack
+            # pyrefly: ignore [missing-attribute]
+            for arg in cur_start_node.all_input_nodes:
+                self._recursively_add_node_arg_to_stack(arg)
+
+            # skip unmatchable nodes
+            # note: this check is done on the start_node, i.e.
+            # if we are matching linear-relu in reverse, this would do the matchable
+            # check on the linear
+            # pyrefly: ignore [bad-argument-type]
+            if not self._is_matchable(cur_base_op_node):
+                continue
+
+            # If an observer or a fake_quant was not matched as a part of
+            # a pattern of multiple nodes, ignore it. One case where this is
+            # relevant is an observer on a graph input, which was added because
+            # it is necessary for the next node.
+            if cur_end_node.op == "call_module" and cur_start_node is cur_end_node:
+                maybe_obs = getattr_from_fqn(self.gm, cur_end_node.target)  # type: ignore[arg-type]
+                if isinstance(maybe_obs, (ObserverBase, FakeQuantizeBase)):
+                    continue
+
+            return NSSubgraph(
+                # pyrefly: ignore [bad-argument-type]
+                start_node=cur_start_node,
+                end_node=cur_end_node,
+                # pyrefly: ignore [bad-argument-type]
+                base_op_node=cur_base_op_node,
+            )
+
+        raise StopIteration
+
+    def _recursively_add_node_arg_to_stack(self, arg: Any) -> None:
+        """
+        Adds all of the nodes in this arg to the stack, properly navigating
+        through list, dicts and tuples.
+        """
+        if isinstance(arg, Node):
+            self.stack.append(arg)
+        elif (
+            isinstance(arg, torch.fx.immutable_collections.immutable_list)
+            or type(arg) is tuple
+        ):
+            for inner_arg in arg:
+                self._recursively_add_node_arg_to_stack(inner_arg)
+        elif isinstance(arg, torch.fx.immutable_collections.immutable_dict):
+            for value in arg.values():
+                self._recursively_add_node_arg_to_stack(value)
+
+    def _is_matchable(self, node: Node) -> bool:
+        if node.op == "call_function":
+            return node.target not in self.non_matchable_functions
+        elif node.op == "call_module":
+            if not isinstance(node.target, str):
+                raise AssertionError(f"Expected str, got {type(node.target)}")
+            target_mod = getattr_from_fqn(self.gm, node.target)
+            return not any(
+                isinstance(target_mod, t)  # type: ignore[arg-type]
+                for t in self.non_matchable_modules
+            )
+        elif node.op == "call_method":
+            return node.target not in self.non_matchable_methods
+        else:
+            return False
+
+
+class GraphMatchingException(Exception):
+    """
+    Exception raised when two graphs cannot be matched.
+    """
+
+
+class SubgraphTypeRelationship(enum.Enum):
+    # same type, known
+    # example: F.linear and F.linear, or nn.Conv2d and nn.Conv2d
+    EQUAL = enum.auto()
+    # same type, but the type is not known to Numerical Suite
+    # (user defined type, etc).
+    EQUAL_BUT_UKNOWN = enum.auto()
+    # known, same subgraph_relationship set, but not the same type
+    # example: F.linear and toq.linear
+    RELATED_BUT_NOT_EQUAL = enum.auto()
+    # not related
+    NOT_RELATED = enum.auto()
+
+
+def _get_subgraph_relationship_type(
+    subgraph_a: NSSubgraph,
+    subgraph_b: NSSubgraph,
+    gm_a: GraphModule,
+    gm_b: GraphModule,
+    type_a_related_to_b: set[tuple[NSNodeTargetType, NSNodeTargetType]],
+) -> SubgraphTypeRelationship:
+    node_a = subgraph_a.base_op_node
+    node_b = subgraph_b.base_op_node
+
+    # TODO(next): make this code handle matching by what is before the base op
+    if node_a.op != node_b.op:
+        if not (
+            node_a.op in ("call_function", "call_method")
+            and node_b.op in ("call_function", "call_method")
+        ):
+            return SubgraphTypeRelationship.NOT_RELATED
+
+    if node_a.op in ("call_function", "call_method"):
+        key = (node_a.target, node_b.target)
+
+        if key not in type_a_related_to_b:
+            if node_a.target == node_b.target:
+                return SubgraphTypeRelationship.EQUAL_BUT_UKNOWN
+            else:
+                return SubgraphTypeRelationship.NOT_RELATED
+        # after this point, we are dealing with known types
+
+        if node_a.target == node_b.target:
+            node_a_has_prev = subgraph_a.base_op_node == subgraph_a.start_node
+            node_b_has_prev = subgraph_b.base_op_node == subgraph_b.start_node
+            if node_a_has_prev and (not node_b_has_prev):
+                return SubgraphTypeRelationship.RELATED_BUT_NOT_EQUAL
+            elif (not node_a_has_prev) and node_b_has_prev:
+                return SubgraphTypeRelationship.RELATED_BUT_NOT_EQUAL
+            elif (not node_a_has_prev) and (not node_b_has_prev):
+                return SubgraphTypeRelationship.EQUAL
+            else:
+                # TODO(future PR): check for matches start_op_node and base_op_node
+                return SubgraphTypeRelationship.EQUAL
+
+        if key in type_a_related_to_b:
+            return SubgraphTypeRelationship.RELATED_BUT_NOT_EQUAL
+        else:
+            return SubgraphTypeRelationship.NOT_RELATED
+    elif node_a.op == "call_module":
+        if (
+            subgraph_a.base_op_node != subgraph_a.start_node
+            or subgraph_b.base_op_node != subgraph_b.start_node
+        ):
+            raise AssertionError(
+                "Matching call_module patterns where base_op_node != start_node is not supported yet"
+            )
+        # for call_module, we need to look up the modules to do the type check
+        if not isinstance(node_a.target, str):
+            raise AssertionError(f"Expected str, got {type(node_a.target)}")
+        mod_a = getattr_from_fqn(gm_a, node_a.target)
+        if not isinstance(node_b.target, str):
+            raise AssertionError(f"Expected str, got {type(node_b.target)}")
+        mod_b = getattr_from_fqn(gm_b, node_b.target)
+
+        key = (type(mod_a), type(mod_b))
+
+        if key not in type_a_related_to_b:
+            if type(mod_a) is type(mod_b):
+                return SubgraphTypeRelationship.EQUAL_BUT_UKNOWN
+            else:
+                return SubgraphTypeRelationship.NOT_RELATED
+        elif type(mod_a) is type(mod_b):
+            return SubgraphTypeRelationship.EQUAL
+        else:
+            return SubgraphTypeRelationship.RELATED_BUT_NOT_EQUAL
+
+    return SubgraphTypeRelationship.NOT_RELATED
+
+
+def _get_name_for_subgraph(
+    subgraph_a: NSSubgraph,
+    gm_a: GraphModule,
+    base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]],
+    existing_names: set[str],
+) -> str:
+    """
+    Returns a unique name for a subgraph. This name is based on two things:
+    1. the name of the set containing the underlying type of the base op in the
+       subgraph (i.e. 'torch.nn.functional.linear' if this is related to a linear op)
+    2. the number of previous subgraphs with related underlying type of the base op
+
+    For example, in the graph
+
+    linear0 -> relu0 -> linear1 -> relu1
+
+    The subgraphs are (linear0, relu0) and (linear1, relu1).  If we iterate
+    from the output node backwards, the name given to (linear1, relu1) will be
+    `base_op_torch.nn.functional.linear_0`, and the name given to (linear0, relu0)
+    will be `base_op_torch.nn.functional.linear_1`.
+
+    Why are we not just using the node name? Answer: because of two requirements:
+    A. fusions must be supported
+    B. some Numeric Suite APIs can be called without having all of the models in memory
+
+    For example, let's say we need to match nodes of
+
+    (1) ... -> linear0 -> relu0 -> ...
+
+    And
+
+    (2) ... -> linear_relu0 -> ...
+
+    Without being able to inspect them together. With the current naming scheme, if
+    we iterate through both of these graphs in the same order, and assuming the rest
+    of the graphs match, both of these subgraphs will get the same name without
+    (1) and (2) knowing anything about each other.
+    """
+    target_type = _get_node_target_type(subgraph_a.base_op_node, gm_a)
+    target_base_type = None
+    for base_name, sets_of_related_ops in base_name_to_sets_of_related_ops.items():
+        if target_type in sets_of_related_ops:
+            target_base_type = base_name
+    target_base_name = "base_op_" + str(target_base_type)
+    counter = 0
+    proposed_name = target_base_name + "_" + str(counter)
+    while proposed_name in existing_names:
+        counter += 1
+        proposed_name = target_base_name + "_" + str(counter)
+    existing_names.add(proposed_name)
+    return proposed_name
+
+
+def _get_node_target_type(node: Node, gm: GraphModule) -> NSNodeTargetType | None:
+    if node.op in ("call_function", "call_method"):
+        return node.target
+    elif node.op == "call_module":
+        if not isinstance(node.target, str):
+            raise AssertionError(f"Expected str, got {type(node.target)}")
+        mod = getattr_from_fqn(gm, node.target)
+        return type(mod)
+    return None
+
+
+def get_matching_subgraph_pairs(
+    gm_a: GraphModule,
+    gm_b: GraphModule,
+    base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
+    unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
+) -> dict[str, tuple[NSSubgraph, NSSubgraph]]:
+    """
+    Matches matchable subgraphs of graph_a to graph_b.
+
+    For a node, "matchable" is defined as a node which is not an observer,
+    fake_quants, quant or dequant.
+
+    A subgraph can contain one or more nodes.  A subgraph is matchable if
+    at least one node inside of it is matchable.  Currently, all nodes in
+    a subgraph must be matchable (because we assume no observers will be
+    inserted in the middle of a fusion).
+
+    A subgraph is defined by (start_node, end_node).  We assume that only
+    start_node and end_node are linked with the surrounding graph, all other
+    nodes in a subgraph are self-contained.
+
+    A pair of nodes is "related" if both nodes represent the same mathematical
+    operation across different quantization flavors. For example,
+    `F.linear` and `torch.ops.quantized.linear` are related, and
+    `F.linear` and `torch.nn.Conv` are not related.
+
+    For each matchable pair of nodes node_a and node_b, they will match
+    if node_a and node_b are related.
+
+    For graphs A and B, they will match iff:
+    1. the number of matchable subgraphs in A and B is equivalent
+    2. when iterating through the matchable subgraphs of A and B in the same order, each
+       corresponding pair of base nodes is related.
+
+    This enables us to find the corresponding subgraphs between
+    graphs of related models.  For example, if we had two graphs such as:
+
+    graph_a: x0 -> conv_0 (type: nn.Conv2d) -> obs_0 -> x1
+             w  -/
+             b  -/
+
+    graph_b: x0 -> quant_0 -> qconv_0 (type: nnq.Conv2d) -> dequant_0 -> x1
+           packed_params_0 -/
+
+    This function will return the following result:
+    {
+        'conv_0': (  # the name of the node in graph_b
+          (conv_0, conv_0),  # (start_node_a, end_node_a)
+          (qconv_0, qconv_0),  # (start_node_b, end_node_b)
+        ),
+    }
+
+    Or, if we have a fusion pattern,
+
+    graph_a: x0 -> linear_0 -> relu_0 -> obs_0 -> x1
+             w  -/
+             b  -/
+
+    graph_b: x0 -> quant_0 -> linear_relu_0 -> dequant_0 -> x1
+           packed_params_0 -/
+
+    This function will return the following result:
+    {
+        'linear_relu_0': (  # the name of the node in graph_b
+          (linear_0, relu_0),  # (start_node_a, end_node_a)
+          (linear_relu_0, linear_relu_0),  # (start_node_b, end_node_b)
+        ),
+    }
+    """
+    if unmatchable_types_map is None:
+        unmatchable_types_map = get_unmatchable_types_map()
+    non_matchable_functions = unmatchable_types_map["funs_unmatchable"]
+    non_matchable_modules = unmatchable_types_map["mods_unmatchable"]
+    non_matchable_methods = unmatchable_types_map["meths_unmatchable"]
+
+    graph_a_iterator = _NSGraphMatchableSubgraphsIterator(
+        gm_a, non_matchable_functions, non_matchable_modules, non_matchable_methods
+    )
+    graph_b_iterator = _NSGraphMatchableSubgraphsIterator(
+        gm_b, non_matchable_functions, non_matchable_modules, non_matchable_methods
+    )
+    results = collections.OrderedDict()
+    if base_name_to_sets_of_related_ops is None:
+        base_name_to_sets_of_related_ops = get_base_name_to_sets_of_related_ops()
+    type_a_related_to_b = get_type_a_related_to_b(base_name_to_sets_of_related_ops)
+
+    existing_names_a: set[str] = set()
+    existing_names_b: set[str] = set()
+
+    while True:
+        # fetch the next subgraphs from a and b
+        cur_subgraph_a, cur_subgraph_b = None, None
+        try:
+            cur_subgraph_a = next(graph_a_iterator)
+        except StopIteration:
+            pass
+        try:
+            cur_subgraph_b = next(graph_b_iterator)
+        except StopIteration:
+            pass
+
+        # look up types of a and b for useful error messages
+        type_start_a, type_start_b = None, None
+        if cur_subgraph_a is not None:
+            type_start_a = _get_node_target_type(cur_subgraph_a.start_node, gm_a)
+        if cur_subgraph_b is not None:
+            type_start_b = _get_node_target_type(cur_subgraph_b.start_node, gm_b)
+
+        # check for results and determine what to do next
+        if cur_subgraph_a is not None and cur_subgraph_b is not None:
+            # both nodes were fetched, check for subgraph_relationship
+            # note: subgraph_relationship is checked on the start node, i.e.
+            # if a linear-relu pattern is checked, we would check for subgraph_relationship
+            # of the linear
+            subgraph_relationship = _get_subgraph_relationship_type(
+                cur_subgraph_a, cur_subgraph_b, gm_a, gm_b, type_a_related_to_b
+            )
+            if subgraph_relationship == SubgraphTypeRelationship.NOT_RELATED:
+                msg = f"""
+The subgraphs
+({cur_subgraph_a}, {type_start_a}) and
+({cur_subgraph_b}, {type_start_b})
+are not related. Please ensure that the two models you pass in have the same number
+of subgraphs, and each pair of subgraphs is related to each other."""
+                raise GraphMatchingException(msg)
+            elif subgraph_relationship == SubgraphTypeRelationship.EQUAL_BUT_UKNOWN:
+                # skip matching but unknown types
+                continue
+            key_name_a = _get_name_for_subgraph(
+                cur_subgraph_a, gm_a, base_name_to_sets_of_related_ops, existing_names_a
+            )
+            key_name_b = _get_name_for_subgraph(
+                cur_subgraph_b, gm_b, base_name_to_sets_of_related_ops, existing_names_b
+            )
+            if key_name_a != key_name_b:
+                raise AssertionError(
+                    f"Subgraph names {key_name_a} and {key_name_b} do not match"
+                )
+            results[key_name_a] = (cur_subgraph_a, cur_subgraph_b)
+            continue
+        elif cur_subgraph_a is None and cur_subgraph_b is None:
+            # we reached the end of both graphs
+            break
+        else:
+            # only one node was fetched, no match possible, throw error
+            msg = f"""
+Attempting to match
+({cur_subgraph_a}, {type_start_a}) and
+({cur_subgraph_b}, {type_start_b}),
+one of which is empty. Please ensure that the two models you pass in have the same number
+of subgraphs."""
+            raise GraphMatchingException(msg)
+
+    # The subgraph pairs are originally created by traversing the two graphs
+    # from the outputs to the inputs. Reverse the results to return the
+    # subgraphs in their order of execution.
+    results = collections.OrderedDict(reversed(results.items()))
+
+    return results
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/graph_passes.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/graph_passes.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f44fe2cdd00617c6cf5237a10e3da87a2b5a77b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/graph_passes.py
@@ -0,0 +1,1155 @@
+# mypy: allow-untyped-defs
+from collections.abc import Callable
+from typing import Any
+
+import torch
+from torch.ao.ns.fx.mappings import get_node_type_to_io_type_map
+from torch.ao.quantization.fx.utils import get_new_attr_name_with_prefix
+from torch.ao.quantization.observer import _is_activation_post_process
+from torch.fx import GraphModule, map_arg
+from torch.fx.graph import Graph, Node
+
+from .ns_types import NSNodeTargetType, NSSingleResultValuesType, NSSubgraph
+from .utils import (
+    get_arg_indices_of_inputs_to_log,
+    get_node_first_input_and_output_type,
+    get_node_input_qparams,
+    get_normalized_nth_input,
+    get_number_of_non_param_args,
+    get_target_type_str,
+    getattr_from_fqn,
+    NodeInputOrOutputType,
+    op_type_supports_shadowing,
+    return_first_non_observer_node,
+)
+
+
+def _maybe_get_fqn(node: Node, gm: GraphModule) -> str | None:
+    fqn = None
+    if hasattr(gm, "_node_name_to_scope"):
+        # fqn on observers is not present, because they do not
+        # exist when the fqns are created during tracing. If this is
+        # an observer, get the fqn of the node being observed.
+        node_to_use_for_fqn = node
+        if node.op == "call_module":
+            if not isinstance(node.target, str):
+                raise AssertionError(f"Expected str, got {type(node.target)}")
+            module = getattr_from_fqn(gm, node.target)
+            if _is_activation_post_process(module):
+                node_to_use_for_fqn = get_normalized_nth_input(node, gm, 0)
+        fqn = gm._node_name_to_scope[node_to_use_for_fqn.name][0]  # type: ignore[index]
+    return fqn  # type: ignore[return-value]
+
+
+def _insert_logger_after_node(
+    node: Node,
+    gm: GraphModule,
+    logger_cls: Callable,
+    logger_node_name_suffix: str,
+    ref_node_name: str,
+    model_name: str,
+    ref_name: str,
+    ref_node_target_type: str,
+    results_type: str,
+    index_within_arg: int,
+    index_of_arg: int,
+    fqn: str | None,
+) -> Node:
+    """
+    Given a starting graph of
+
+    prev_node -> node -> next_node
+
+    This function creates a new logger_cls obj and adds it
+    after node, resulting in
+
+    prev_node -> node -> logger_obj -> next_node
+    """
+    # create new name
+    logger_node_name = get_new_attr_name_with_prefix(
+        node.name + logger_node_name_suffix
+    )(gm)
+    target_type = get_target_type_str(node, gm)
+    # create the logger object
+    logger_obj = logger_cls(
+        ref_node_name,
+        node.name,
+        model_name,
+        ref_name,
+        target_type,
+        ref_node_target_type,
+        results_type,
+        index_within_arg,
+        index_of_arg,
+        fqn,
+    )
+    # attach the logger object to the parent module
+    setattr(gm, logger_node_name, logger_obj)
+    logger_node = node.graph.create_node("call_module", logger_node_name, (node,), {})
+    return logger_node
+
+
+def add_loggers_to_model(
+    gm: GraphModule,
+    node_to_instrument_inputs_to_ref_node_name: dict[Node, tuple[str, str]],
+    node_to_instrument_outputs_to_ref_node_name: dict[Node, tuple[str, str]],
+    logger_cls: Callable,
+    model_name: str,
+) -> GraphModule:
+    """
+    Takes the graph of gm, adds loggers to the output
+    of each node in nodes_to_instrument. Returns a GraphModule with the new
+    graph.
+    """
+
+    new_graph = Graph()
+    env: dict[str, Any] = {}
+
+    def load_arg(a):
+        return map_arg(a, lambda node: env[node.name])
+
+    for node in gm.graph.nodes:
+        if node.op == "output":
+            new_graph.output(map_arg(get_normalized_nth_input(node, gm, 0), load_arg))
+            continue
+
+        if (node in node_to_instrument_inputs_to_ref_node_name) or (
+            node in node_to_instrument_outputs_to_ref_node_name
+        ):
+            fqn = _maybe_get_fqn(node, gm)
+
+            if node in node_to_instrument_inputs_to_ref_node_name:
+                ref_name, ref_node_type = node_to_instrument_inputs_to_ref_node_name[
+                    node
+                ]
+                # Ops such as add and mul are special because either
+                # one or two of the first two arguments can be tensors,
+                # and if one argument is a tensor it can be first or
+                # second (x + 1 versus 1 + x).
+                arg_indices_to_log = get_arg_indices_of_inputs_to_log(node)
+                for node_arg_idx in arg_indices_to_log:
+                    node_arg = get_normalized_nth_input(node, gm, node_arg_idx)
+                    if type(node_arg) is Node:
+                        # create a single input logger
+                        prev_node = env[node_arg.name]
+                        env[node_arg.name] = _insert_logger_after_node(
+                            prev_node,
+                            gm,
+                            logger_cls,
+                            "_ns_logger_",
+                            node.name,
+                            model_name,
+                            ref_name,
+                            ref_node_type,
+                            NSSingleResultValuesType.NODE_INPUT.value,
+                            index_within_arg=0,
+                            index_of_arg=node_arg_idx,
+                            fqn=fqn,
+                        )
+                    elif (
+                        type(node_arg) is torch.fx.immutable_collections.immutable_list
+                    ):
+                        # create N input loggers, one for each node
+                        for arg_idx, arg in enumerate(node_arg):  # type: ignore[var-annotated, arg-type]
+                            prev_node = env[arg.name]
+                            env[prev_node.name] = _insert_logger_after_node(
+                                prev_node,
+                                gm,
+                                logger_cls,
+                                "_ns_logger_",
+                                node.name,
+                                model_name,
+                                ref_name,
+                                ref_node_type,
+                                NSSingleResultValuesType.NODE_INPUT.value,
+                                index_within_arg=arg_idx,
+                                index_of_arg=node_arg_idx,
+                                fqn=fqn,
+                            )
+
+            # ensure env is populated with base node
+            # Note: runs for both inputs and outputs
+            env[node.name] = new_graph.node_copy(node, load_arg)
+
+            if node in node_to_instrument_outputs_to_ref_node_name:
+                ref_name, ref_node_type = node_to_instrument_outputs_to_ref_node_name[
+                    node
+                ]
+                # add the logger after the base node
+                env[node.name] = _insert_logger_after_node(
+                    env[node.name],
+                    gm,
+                    logger_cls,
+                    "_ns_logger_",
+                    node.name,
+                    model_name,
+                    ref_name,
+                    ref_node_type,
+                    NSSingleResultValuesType.NODE_OUTPUT.value,
+                    index_within_arg=0,
+                    index_of_arg=0,
+                    fqn=fqn,
+                )
+
+        else:
+            env[node.name] = new_graph.node_copy(node, load_arg)
+
+    new_gm = GraphModule(gm, new_graph)
+    return new_gm
+
+
+def _insert_quantize_per_tensor_node(
+    prev_node_c: Node,
+    node_a: Node,
+    gm_b: GraphModule,
+    graph_c: Graph,
+    scale: torch.Tensor | float,
+    zero_point: torch.Tensor | int,
+    dtype_cast_name: str,
+) -> Node:
+    # copy scale
+    scale_node_name = get_new_attr_name_with_prefix(node_a.name + "_input_scale_")(gm_b)
+    setattr(gm_b, scale_node_name, scale)
+    scale_node = graph_c.create_node(
+        "get_attr", scale_node_name, (), {}, scale_node_name
+    )
+    # copy zero_point
+    zero_point_node_name = get_new_attr_name_with_prefix(
+        node_a.name + "_input_zero_point_"
+    )(gm_b)
+    setattr(gm_b, zero_point_node_name, zero_point)
+    zero_point_node = graph_c.create_node(
+        "get_attr", zero_point_node_name, (), {}, zero_point_node_name
+    )
+    # create the quantize_per_tensor call
+    return graph_c.create_node(
+        "call_function",
+        torch.quantize_per_tensor,
+        (prev_node_c, scale_node, zero_point_node, torch.quint8),
+        {},
+        dtype_cast_name,
+    )
+
+
+def _insert_dtype_cast_after_node(
+    node_a: Node,
+    node_c: Node,
+    prev_node_c: Node | list[Node],
+    gm_a: GraphModule,
+    gm_b: GraphModule,
+    graph_c: Graph,
+    node_name_prefix: str,
+    logger_cls: Callable,
+    node_type_to_io_type_map: dict[str, set[NSNodeTargetType]],
+) -> Node | list[Node]:
+    """
+    Given a starting graph C (derived from graph B) of
+
+    ... -> prev_node_c -> node_c -> ...
+
+    And a corresponding related node_a, inserts the correct dtype
+    cast node after prev_node_c to cast into the dtype expected
+    by node_a, resulting in:
+
+                          dtype_cast
+                        /
+    ... -> prev_node_c -> node_c -> ...
+
+    For example, if node_c is an int8 op and node_a is an fp32 op, this function
+    will insert a dequant.
+    """
+    dtype_cast_op = None
+    dtype_cast_mod_cls = None
+    dtype_cast_method = None
+    dtype_cast_method_dtype = None
+    dtype_cast_scale = None
+    dtype_cast_zero_point = None
+    node_input_type_a, _node_output_type_a = get_node_first_input_and_output_type(
+        node_a, gm_a, logger_cls, node_type_to_io_type_map
+    )
+    node_input_type_c, _node_output_type_c = get_node_first_input_and_output_type(
+        node_c, gm_b, logger_cls, node_type_to_io_type_map
+    )
+
+    if (
+        (
+            node_input_type_a == NodeInputOrOutputType.FP32
+            and node_input_type_c == NodeInputOrOutputType.INT8
+        )
+        or (
+            node_input_type_a == NodeInputOrOutputType.FP32
+            and node_input_type_c == NodeInputOrOutputType.FP16
+        )
+        or
+        # TODO(future PR): determine the actual dtype of node_c,
+        # the current code only works because dequantize works with
+        # multiple input dtypes.
+        (
+            node_input_type_a == NodeInputOrOutputType.FP32
+            and node_input_type_c == NodeInputOrOutputType.FP32_OR_INT8
+        )
+    ):
+        dtype_cast_op = torch.dequantize
+    elif (
+        node_input_type_a == node_input_type_c
+        and node_input_type_a != NodeInputOrOutputType.UNKNOWN
+    ):
+        dtype_cast_mod_cls = torch.nn.Identity
+    elif (
+        node_input_type_a == NodeInputOrOutputType.INT8
+        and node_input_type_c == NodeInputOrOutputType.FP32
+    ):
+        # int8 shadows fp32, the dtype cast needs to quantize to int8
+        # with the right qparams.
+        node_a_input_qparams = get_node_input_qparams(
+            node_a, gm_a, node_type_to_io_type_map
+        )
+        if node_a_input_qparams is not None:
+            dtype_cast_op = torch.quantize_per_tensor  # type: ignore[assignment]
+            dtype_cast_scale, dtype_cast_zero_point = node_a_input_qparams
+    elif (
+        node_input_type_a == NodeInputOrOutputType.FP16
+        and node_input_type_c == NodeInputOrOutputType.FP32
+    ):
+        dtype_cast_method = "to"
+        dtype_cast_method_dtype = torch.float16
+    else:
+        raise AssertionError(
+            f"dtype cast from {node_input_type_c} {node_c.format_node()} to "
+            + f"{node_input_type_a} {node_a.format_node()} needs to be implemented"
+        )
+
+    if isinstance(prev_node_c, Node):
+        new_dtype_cast_name = get_new_attr_name_with_prefix(node_name_prefix)(gm_b)
+        if dtype_cast_op:
+            if dtype_cast_scale is not None and dtype_cast_zero_point is not None:
+                return _insert_quantize_per_tensor_node(
+                    prev_node_c,
+                    node_a,
+                    gm_b,
+                    graph_c,
+                    dtype_cast_scale,
+                    dtype_cast_zero_point,
+                    new_dtype_cast_name,
+                )
+            else:
+                return graph_c.create_node(
+                    "call_function",
+                    dtype_cast_op,
+                    (prev_node_c,),
+                    {},
+                    new_dtype_cast_name,
+                )
+        elif dtype_cast_method:
+            return graph_c.create_node(
+                "call_method",
+                dtype_cast_method,
+                (prev_node_c, dtype_cast_method_dtype),
+                {},
+                new_dtype_cast_name,
+            )
+        else:
+            if not dtype_cast_mod_cls:
+                raise AssertionError("Expected dtype_cast_mod_cls to be not None")
+            dtype_cast_mod = dtype_cast_mod_cls()
+            setattr(gm_b, new_dtype_cast_name, dtype_cast_mod)
+            return graph_c.create_node(
+                "call_module",
+                new_dtype_cast_name,
+                (prev_node_c,),
+                {},
+                new_dtype_cast_name,
+            )
+    elif isinstance(prev_node_c, list):
+        results = []
+        for prev_node_c_inner in prev_node_c:
+            new_dtype_cast_name = get_new_attr_name_with_prefix(node_name_prefix)(gm_b)
+            if dtype_cast_op:
+                # TODO(future PR): add handling for quantize_per_tensor
+                new_dtype_cast_node = graph_c.create_node(
+                    "call_function",
+                    dtype_cast_op,
+                    (prev_node_c_inner,),
+                    {},
+                    new_dtype_cast_name,
+                )
+                results.append(new_dtype_cast_node)
+            else:
+                if not dtype_cast_mod_cls:
+                    raise AssertionError("Expected dtype_cast_mod_cls to be not None")
+                dtype_cast_mod = dtype_cast_mod_cls()
+                setattr(gm_b, new_dtype_cast_name, dtype_cast_mod)
+                new_dtype_cast_node = graph_c.create_node(
+                    "call_module",
+                    new_dtype_cast_name,
+                    (prev_node_c_inner,),
+                    {},
+                    new_dtype_cast_name,
+                )
+                results.append(new_dtype_cast_node)
+        return results
+    else:
+        raise AssertionError(f"type f{type(prev_node_c)} is not handled")
+
+
+# TODO(future PR): look into using copy_node API instead
+def _copy_node_from_a_to_c(
+    node_a: Node,
+    gm_a: GraphModule,
+    gm_b: GraphModule,
+    graph_c: Graph,
+) -> Node:
+    """
+    Simple copy of node_a to graph_c.
+    """
+    if node_a.op == "get_attr":
+        node_a_copy_name = get_new_attr_name_with_prefix(node_a.name + "_shadow_copy_")(
+            gm_b
+        )
+        node_a_obj = getattr_from_fqn(gm_a, node_a.target)  # type: ignore[arg-type]
+        if torch.is_tensor(node_a_obj):
+            node_a_obj = node_a_obj.detach()
+        setattr(gm_b, node_a_copy_name, node_a_obj)
+        node_a_copy = graph_c.create_node(
+            node_a.op, node_a_copy_name, (), {}, node_a_copy_name
+        )
+        return node_a_copy
+    elif node_a.op == "call_method":
+        if node_a.target not in ("dequantize", "to"):
+            raise AssertionError(f"target {node_a.target} is not implemented")
+        if node_a.target == "dequantize":
+            arg_copy = _copy_node_from_a_to_c(
+                get_normalized_nth_input(node_a, gm_a, 0), gm_a, gm_b, graph_c
+            )  # type: ignore[arg-type]
+            node_a_copy_name = get_new_attr_name_with_prefix(
+                node_a.name + "_shadow_copy_"
+            )(gm_b)
+            node_a_copy = graph_c.create_node(
+                node_a.op, node_a.target, (arg_copy,), {}, node_a_copy_name
+            )
+            return node_a_copy
+        else:  # to
+            arg_copy = _copy_node_from_a_to_c(
+                get_normalized_nth_input(node_a, gm_a, 0), gm_a, gm_b, graph_c
+            )  # type: ignore[arg-type]
+            node_a_copy_name = get_new_attr_name_with_prefix(
+                node_a.name + "_shadow_copy_"
+            )(gm_b)
+            node_a_copy = graph_c.create_node(
+                node_a.op,
+                node_a.target,
+                (arg_copy, get_normalized_nth_input(node_a, gm_a, 1)),
+                {},
+                node_a_copy_name,
+            )
+            return node_a_copy
+
+    else:
+        raise AssertionError(
+            f"handling of node {node_a.format_node()} with op {node_a.op} is not implemented"
+        )
+
+
+def _can_insert_copy_of_subgraph_a(
+    subgraph_a: NSSubgraph,
+    gm_a: GraphModule,
+    num_non_param_args_node_a: int,
+) -> bool:
+    """
+    This function returns `False` if the input subgraph cannot be copied by
+    `_insert_copy_of_subgraph_a_after_input_node_c`. This usually means
+    that there is a corner case logic for which copy is not yet implemented.
+    """
+    # populate the list of nodes we need to check
+    nodes = []
+    cur_node = subgraph_a.end_node
+    while cur_node != subgraph_a.start_node:
+        nodes.append(cur_node)
+        cur_node = get_normalized_nth_input(cur_node, gm_a, 0)  # type: ignore[assignment]
+    nodes.append(cur_node)
+    nodes.reverse()
+
+    def _can_insert(node_a_arg, gm_a):
+        if isinstance(node_a_arg, Node):
+            arg_a = return_first_non_observer_node(node_a_arg, gm_a)
+            if arg_a.op == "call_method":
+                return arg_a.target in ("dequantize", "to")
+            elif arg_a.op == "get_attr":
+                return True
+            else:
+                return False
+        elif isinstance(node_a_arg, (list, tuple)):
+            for el in node_a_arg:
+                if not isinstance(el, Node):
+                    return False
+        return True
+
+    # For each node, check if we handle the copy behavior. This follows the
+    # logic in `_insert_copy_of_subgraph_a_after_input_node_c`.
+    for node_a in nodes:
+        local_num_non_param_args_node_a = (
+            num_non_param_args_node_a if node_a is nodes[0] else 1
+        )
+
+        norm_args_kwargs = node_a.normalized_arguments(
+            gm_a, normalize_to_only_use_kwargs=True
+        )
+        if norm_args_kwargs is not None:
+            norm_args, norm_kwargs = norm_args_kwargs
+        else:
+            norm_args, norm_kwargs = node_a.args, node_a.kwargs
+
+        cur_idx = 0
+
+        while cur_idx < len(norm_args):
+            if cur_idx == 0:
+                pass
+            elif cur_idx == 1 and local_num_non_param_args_node_a == 2:
+                pass
+            else:
+                if not _can_insert(norm_args[cur_idx], gm_a):
+                    return False
+            cur_idx += 1
+
+        for kwarg_val in norm_kwargs.values():
+            # stitch the inputs from base graph
+            if cur_idx == 0:
+                pass
+            elif cur_idx == 1 and local_num_non_param_args_node_a == 2:
+                pass
+            else:
+                if not _can_insert(kwarg_val, gm_a):
+                    return False
+            cur_idx += 1
+
+    return True
+
+
+def _insert_copy_of_subgraph_a_after_input_node_c(
+    input_node_c: Node | list[Node],
+    input_node_c_2: Node | list[Node] | None,
+    subgraph_a: NSSubgraph,
+    gm_a: GraphModule,
+    gm_b: GraphModule,
+    node_name_prefix: str,
+) -> Node:
+    """
+    TODO(before land): real docblock
+    """
+    if not isinstance(input_node_c, (Node, list)):
+        raise AssertionError(f"Expected Node or list, got {type(input_node_c)}")
+
+    # create a sequential list of the subgraphs' nodes from start to end,
+    # because we need to add the nodes to graph C in non-reverse order
+    nodes_of_a = [subgraph_a.end_node]
+    cur_node = subgraph_a.end_node
+    while cur_node != subgraph_a.start_node:
+        cur_node = get_normalized_nth_input(cur_node, gm_a, 0)  # type: ignore[assignment]
+        nodes_of_a.insert(0, cur_node)
+
+    # go through nodes of a in order, and insert them into the graph of c
+    # sequentially
+    cur_node_a = nodes_of_a[0]
+    cur_node_c = _insert_copy_of_node_a_after_input_node_c(
+        input_node_c, input_node_c_2, cur_node_a, gm_a, gm_b, node_name_prefix
+    )
+    for cur_idx_a in range(1, len(nodes_of_a)):
+        cur_node_a = nodes_of_a[cur_idx_a]
+        prev_node_c = cur_node_c  # previous added node is the input to next node
+        cur_node_c = _insert_copy_of_node_a_after_input_node_c(
+            prev_node_c,
+            # TODO(future PR): enable multiple inputs for nodes which are not at start of subgraph
+            None,
+            cur_node_a,
+            gm_a,
+            gm_b,
+            node_name_prefix,
+        )
+    # return the last inserted node
+    return cur_node_c
+
+
+def _insert_copy_of_node_a_after_input_node_c(
+    input_node_c: Node | list[Node],
+    input_node_c_2: Node | list[Node] | None,
+    node_a: Node,
+    gm_a: GraphModule,
+    gm_b: GraphModule,
+    node_name_prefix: str,
+) -> Node:
+    """
+    Assume that node_a from graph_a has
+      args (input, (input2)?, arg1, ...), and
+      kwargs {kw0: kwarg0, ...}
+
+    Note: input2 is optional. If it equals to None, we assume that the op
+    has a single non-param input.  If it is specified, we assume that the op
+    has two non-param inputs.
+
+    Copies the underlying values of arg1..argn and kwarg0..kwargn into gm_b,
+    and creates the corresponding nodes in graph_c. Note: observers are ignored,
+    so if an arg is an observer we navigate up until we find a non-observer parent.
+
+    If node_a is a call_module, points the module pointed to by node_a to gm_b.
+
+    Creates the copy of node_a in graph_c, with input as the first arg,
+    and all other args and kwargs pointing to the copies of the objects
+    in gm_b created above.
+
+    An example in pictures:
+
+    graph A:
+    ========
+
+    input -------------> node_a
+                         / / /
+    (input_2)?----------/ / /
+                         / /
+    weight -> weight_obs  /
+                         /
+    bias ----------------
+
+    graph C (derived from B):
+    =========================
+
+    input_node_c --> node_a_copy
+                     / / /
+    (input_node_c_2)? / /
+                     / /
+    weight_copy ----/ /
+                     /
+    bias_copy ------/
+    """
+    if isinstance(input_node_c, Node):
+        graph_c = input_node_c.graph
+    else:
+        if not isinstance(input_node_c, list):
+            raise AssertionError(f"Expected list, got {type(input_node_c)}")
+        graph_c = input_node_c[0].graph
+
+    norm_args_kwargs = node_a.normalized_arguments(
+        gm_a, normalize_to_only_use_kwargs=True
+    )
+    if norm_args_kwargs is not None:
+        norm_args, norm_kwargs = norm_args_kwargs
+    else:
+        norm_args, norm_kwargs = node_a.args, node_a.kwargs
+
+    new_args = []
+    new_kwargs = {}
+
+    def _copy_arg(arg):
+        # copy the other inputs from the other graph
+        if isinstance(arg, Node):
+            arg = return_first_non_observer_node(arg, gm_a)
+            arg = _copy_node_from_a_to_c(arg, gm_a, gm_b, graph_c)
+            return arg
+        elif isinstance(arg, (int, float, torch.dtype)):
+            return arg
+        elif isinstance(kwarg_val, (list, tuple)):
+            for el in kwarg_val:
+                if isinstance(el, Node):
+                    raise AssertionError(
+                        "handling of Node inside list is not implemented"
+                    )
+            return arg
+        else:
+            raise AssertionError(
+                f"handling for kwarg of type {type(kwarg_val)} is not implemented"
+            )
+
+    cur_idx = 0
+
+    while cur_idx < len(norm_args):
+        if cur_idx == 0:
+            new_arg = input_node_c
+        elif cur_idx == 1 and input_node_c_2 is not None:
+            new_arg = input_node_c_2
+        else:
+            new_arg = _copy_arg(norm_args[cur_idx])
+        new_args.append(new_arg)
+        cur_idx += 1
+
+    for kwarg_name, kwarg_val in norm_kwargs.items():
+        # stitch the inputs from base graph
+        if cur_idx == 0:
+            new_kwargs[kwarg_name] = input_node_c
+        elif cur_idx == 1 and input_node_c_2 is not None:
+            new_kwargs[kwarg_name] = input_node_c_2
+        else:
+            new_kwargs[kwarg_name] = _copy_arg(kwarg_val)
+        cur_idx += 1
+
+    new_args = tuple(new_args)  # type: ignore[assignment]
+
+    node_a_shadows_c_name = get_new_attr_name_with_prefix(node_name_prefix)(gm_b)
+
+    if node_a.op == "call_module":
+        # if target is a module, we point to the module from gm_b
+        new_mod_copy_name = get_new_attr_name_with_prefix(node_name_prefix)(gm_b)
+        # fetch the corresponding module from gm_a
+        if not isinstance(node_a.target, str):
+            raise AssertionError(f"Expected str, got {type(node_a.target)}")
+        mod_a = getattr_from_fqn(gm_a, node_a.target)
+        setattr(gm_b, new_mod_copy_name, mod_a)
+        node_a_shadows_c = graph_c.create_node(
+            node_a.op,
+            new_mod_copy_name,
+            new_args,  # type: ignore[arg-type]
+            new_kwargs,  # type: ignore[arg-type]
+            node_a_shadows_c_name,
+        )
+        return node_a_shadows_c
+    else:
+        if node_a.op not in ("call_function", "call_method"):
+            raise AssertionError(f"Unexpected op: {node_a.op}")
+        node_a_shadows_c = graph_c.create_node(
+            node_a.op,
+            node_a.target,
+            new_args,  # type: ignore[arg-type]
+            new_kwargs,  # type: ignore[arg-type]
+            node_a_shadows_c_name,
+        )
+        return node_a_shadows_c
+
+
+def create_a_shadows_b(
+    name_a: str,
+    gm_a: GraphModule,
+    name_b: str,
+    gm_b: GraphModule,
+    matched_subgraph_pairs: dict[str, tuple[NSSubgraph, NSSubgraph]],
+    logger_cls: Callable,
+    should_log_inputs: bool,
+    node_type_to_io_type_map: dict[str, set[NSNodeTargetType]] | None = None,
+) -> GraphModule:
+    """
+    Creates a new GraphModule consisting of the graph of C, with the meaningful
+    nodes of A shadowing the corresponding nodes of B.  For example,
+
+    Graph A:
+    a0 -> op0_fp32 -> a1 -> op1_fp32 -> a2
+
+    Graph B:
+    b0 -> op0_int8 -> b1 -> op1_int8 -> b2
+
+    matched_node_pairs: {'op0': (op0_fp32, op0_int8), 'op1': (op1_fp32, op1_int8)}
+
+    Graph C (A shadows B):
+
+        / dequant0 -> op0_fp32 -> logger_a_0  / dequant_1 -> op1_fp32 -> logger_a_1
+       /                                     /
+    b0 -------------> op0_int8 -> logger_b_0 --------------> op1_int8 -> logger_b_1
+
+    In a nutshell, this function does the following for each node pair:
+    * copies the necessary attributes and modules from gm_a to gm_b,
+      keeping names unique
+    * adds a dtype cast op (dequant, quant, etc)
+    * adds a copy of node_a in gm_b's graph
+    * adds loggers to the outputs of node_a and node_b
+    """
+
+    if node_type_to_io_type_map is None:
+        node_type_to_io_type_map = get_node_type_to_io_type_map()
+
+    # graph_c is the graph created from copying the nodes of graph_b and inserting
+    # the shadows with the nodes copied from graph_a
+    graph_c = Graph()
+    env_c: dict[str, Any] = {}
+
+    def load_arg(a):
+        return map_arg(a, lambda node: env_c[node.name])
+
+    start_node_b_to_matched_subgraph_a_and_name = {}
+    end_node_b_to_matched_subgraph_a_and_name = {}
+    for match_name, match in matched_subgraph_pairs.items():
+        subgraph_a, subgraph_b = match
+        ref_node_type_a = get_target_type_str(subgraph_a.base_op_node, gm_a)
+        ref_node_type_b = get_target_type_str(subgraph_b.base_op_node, gm_b)
+        start_node_b_to_matched_subgraph_a_and_name[subgraph_b.start_node] = (
+            subgraph_a,
+            match_name,
+            ref_node_type_a,
+            ref_node_type_b,
+        )
+        end_node_b_to_matched_subgraph_a_and_name[subgraph_b.end_node] = (
+            subgraph_a,
+            match_name,
+            ref_node_type_a,
+            ref_node_type_b,
+        )
+
+    for node_b in gm_b.graph.nodes:
+        if node_b.op == "output":
+            graph_c.output(map_arg(node_b.args[0], load_arg))
+            continue
+
+        # calculate the flags to determine what to do with this node
+        node_b_is_start_node = node_b in start_node_b_to_matched_subgraph_a_and_name
+        node_b_is_end_node = node_b in end_node_b_to_matched_subgraph_a_and_name
+
+        if node_b_is_start_node or node_b_is_end_node:
+            if node_b_is_start_node:
+                (
+                    subgraph_a,
+                    ref_name,
+                    ref_node_type_a,
+                    ref_node_type_b,
+                ) = start_node_b_to_matched_subgraph_a_and_name[node_b]
+            else:
+                if not node_b_is_end_node:
+                    raise AssertionError("Expected node_b_is_end_node to be not false")
+                (
+                    subgraph_a,
+                    ref_name,
+                    ref_node_type_a,
+                    ref_node_type_b,
+                ) = end_node_b_to_matched_subgraph_a_and_name[node_b]
+
+            all_op_types_support_shadowing = op_type_supports_shadowing(
+                subgraph_a.start_node
+            ) and op_type_supports_shadowing(node_b)
+            if not all_op_types_support_shadowing:
+                print(
+                    f"skipping shadow loggers for node_b: {get_target_type_str(node_b, gm_b)}"
+                    + f", start_node_a: {get_target_type_str(subgraph_a.start_node, gm_a)}"
+                    + ", unsupported"
+                )
+                env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
+                continue
+
+            # For both start_node and end_node verify that we know how to do
+            # the dtype cast. If we do not, skip.
+            (
+                node_input_type_a,
+                node_output_type_a,
+            ) = get_node_first_input_and_output_type(
+                subgraph_a.start_node, gm_a, logger_cls, node_type_to_io_type_map
+            )
+            (
+                node_input_type_b,
+                node_output_type_b,
+            ) = get_node_first_input_and_output_type(
+                node_b, gm_b, logger_cls, node_type_to_io_type_map
+            )
+            node_io_types_known_a_and_b = (
+                node_input_type_a != NodeInputOrOutputType.UNKNOWN
+                and node_output_type_a != NodeInputOrOutputType.UNKNOWN
+                and node_input_type_b != NodeInputOrOutputType.UNKNOWN
+                and node_output_type_b != NodeInputOrOutputType.UNKNOWN
+            )
+            if not node_io_types_known_a_and_b:
+                print(
+                    f"skipping shadow loggers for node_b: {get_target_type_str(node_b, gm_b)}"
+                    + f", start_node_a: {get_target_type_str(subgraph_a.start_node, gm_a)}"
+                    + ", unknown dtype cast"
+                )
+                env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
+                continue
+
+            # If we are shadowing from fp32 to int8, we need to insert
+            # quantize_per_tensor call with qparams from the previous node.
+            # Only do this if we are able to infer these qparams from the graph.
+            if (
+                node_input_type_a == NodeInputOrOutputType.INT8
+                and node_input_type_b == NodeInputOrOutputType.FP32
+            ):
+                node_a_input_qparams = get_node_input_qparams(
+                    subgraph_a.start_node, gm_a, node_type_to_io_type_map
+                )
+                if not node_a_input_qparams:
+                    print(
+                        f"skipping shadow loggers for node_b: {get_target_type_str(node_b, gm_b)}"
+                        + f", start_node_a: {get_target_type_str(subgraph_a.start_node, gm_a)}"
+                        + ", unknown input qparams"
+                    )
+                    env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
+                    continue
+
+            num_non_param_args_node_a = get_number_of_non_param_args(
+                subgraph_a.start_node, gm_a
+            )
+            if not _can_insert_copy_of_subgraph_a(
+                subgraph_a, gm_a, num_non_param_args_node_a
+            ):
+                print(
+                    f"skipping shadow loggers for node_b: {get_target_type_str(node_b, gm_b)}"
+                    + f", start_node_a: {get_target_type_str(subgraph_a.start_node, gm_a)}"
+                    + ", unhandled logic in subgraph copy"
+                )
+                env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
+                continue
+
+            fqn_base_a = _maybe_get_fqn(subgraph_a.base_op_node, gm_a)
+            fqn_base_b = _maybe_get_fqn(subgraph_b.base_op_node, gm_b)  # type: ignore[possibly-undefined]
+
+            if node_b_is_start_node:
+                # if necessary, log the input of node_c
+                if should_log_inputs:
+                    prev_node_b = get_normalized_nth_input(node_b, gm_b, 0)
+                    if isinstance(prev_node_b, Node):
+                        prev_node_c = env_c[prev_node_b.name]
+                        env_c[prev_node_c.name] = _insert_logger_after_node(
+                            prev_node_c,
+                            gm_b,
+                            logger_cls,
+                            "_ns_logger_b_inp_",
+                            node_b.name,
+                            name_b,
+                            ref_name,
+                            ref_node_type_b,
+                            NSSingleResultValuesType.NODE_INPUT.value,
+                            index_within_arg=0,
+                            index_of_arg=0,
+                            fqn=fqn_base_b,
+                        )
+                    elif isinstance(prev_node_b, list):
+                        # first, save the prev_node instances, because they
+                        # will be overwritten in the env after the first logger
+                        # is added
+                        prev_node_c_list = [env_c[arg.name] for arg in prev_node_b]
+
+                        for arg_idx, prev_node_c in enumerate(prev_node_c_list):
+                            env_c[prev_node_c.name] = _insert_logger_after_node(
+                                prev_node_c,
+                                gm_b,
+                                logger_cls,
+                                "_ns_logger_b_inp_",
+                                node_b.name,
+                                name_b,
+                                ref_name,
+                                ref_node_type_b,
+                                NSSingleResultValuesType.NODE_INPUT.value,
+                                index_within_arg=arg_idx,
+                                index_of_arg=0,
+                                fqn=fqn_base_b,
+                            )
+                    else:
+                        # logging of inputs which are not lists is not supported yet
+                        raise AssertionError(
+                            f"type {type(prev_node_b)} is not handled yet"
+                        )
+                # subgraph so far:
+                #
+                # (prev_node_c)+ -> (logger_c_input)?
+
+            # Note: this if statement is always True, spelling it out to clarify code
+            # intent.
+            if node_b_is_start_node or node_b_is_end_node:
+                # ensure env_c is populated with base node
+                env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
+                node_c = env_c[node_b.name]
+
+                # after this point,
+                #
+                # node_a is the original node from graph_a, with parent module gm_a
+                # node_b is the original node from graph_b, with parent module gm_b
+                # node_c is the copy of node_b in graph_c
+                #
+                # subgraph so far:
+                #
+                # (prev_node_c)+ -> (logger_c_input)? -> node_start_c
+
+            if node_b_is_start_node:
+                # cast dtype from the dtype of node_c's input to the dtype of
+                # node_a's input (dequant, etc)
+                # prev_node_c = node_c.args[0]
+                prev_node_c = get_normalized_nth_input(node_c, gm_b, 0)  # type: ignore[possibly-undefined]
+                if should_log_inputs:
+                    # skip the input logger when inserting a dtype cast
+                    if isinstance(prev_node_c, Node):
+                        # pyrefly: ignore [unbound-name]
+                        prev_node_c = get_normalized_nth_input(node_c, gm_b, 0)
+                    elif isinstance(prev_node_c, list):
+                        prev_node_c = [
+                            get_normalized_nth_input(arg, gm_b, 0)
+                            for arg in prev_node_c
+                        ]
+                dtype_cast_node = _insert_dtype_cast_after_node(
+                    subgraph_a.start_node,
+                    # pyrefly: ignore [unbound-name]
+                    node_c,
+                    prev_node_c,
+                    gm_a,
+                    gm_b,
+                    graph_c,
+                    node_b.name + "_dtype_cast_",
+                    logger_cls,
+                    node_type_to_io_type_map,
+                )
+                # note: not inserting to env_c because all nodes which use the dtype
+                #   casts are copied from graph_a
+                #
+                # subgraph so far:
+                #
+                #           (dtype_cast_node)+
+                #                  /
+                # (prev_node_c)+ -> (logger_c_input)? -> node_start_c
+
+                # if input logging is enabled, log the input to the subgraph
+                if should_log_inputs:
+                    # TODO: explain this
+                    ref_node_name = ""
+                    if isinstance(dtype_cast_node, Node):
+                        dtype_cast_node = _insert_logger_after_node(
+                            dtype_cast_node,
+                            gm_b,
+                            logger_cls,
+                            "_ns_logger_a_inp_",
+                            ref_node_name,
+                            name_a,
+                            ref_name,
+                            ref_node_type_a,
+                            NSSingleResultValuesType.NODE_INPUT.value,
+                            index_within_arg=0,
+                            index_of_arg=0,
+                            fqn=fqn_base_a,
+                        )
+                        input_logger: Node | list[Node] = dtype_cast_node
+                    else:
+                        if not isinstance(dtype_cast_node, list):
+                            raise AssertionError(
+                                f"Expected list, got {type(dtype_cast_node)}"
+                            )
+                        new_loggers = []
+                        for dtype_cast_idx, dtype_cast_node_inner in enumerate(
+                            dtype_cast_node
+                        ):
+                            dtype_cast_logger = _insert_logger_after_node(
+                                dtype_cast_node_inner,
+                                gm_b,
+                                logger_cls,
+                                "_ns_logger_a_inp_",
+                                ref_node_name,
+                                name_a,
+                                ref_name,
+                                ref_node_type_a,
+                                NSSingleResultValuesType.NODE_INPUT.value,
+                                index_within_arg=dtype_cast_idx,
+                                index_of_arg=0,
+                                fqn=fqn_base_a,
+                            )
+                            new_loggers.append(dtype_cast_logger)
+                        dtype_cast_node = new_loggers
+                        input_logger = dtype_cast_node
+                    # subgraph so far:
+                    #
+                    #       (dtype_cast_node)+ -> (logger_a_input)?
+                    #                  /
+                    # prev_node_c -> (logger_c_input)? -> node_start_c
+
+                # hook up the new mod_a copy to be in the graph, receiving the
+                # same inputs as mod_b does, with dtype cast to match a
+                # Some ops, such as LSTMs, have two non-param inputs. If we have
+                # such an op, pass the second param as well. Note: dtype casting
+                # for the second param is not implemented yet, it can be added
+                # later if there is a use case.
+                node_c_second_non_param_arg = None
+                num_non_param_args_node_a = get_number_of_non_param_args(
+                    subgraph_a.start_node, gm_a
+                )
+                if num_non_param_args_node_a == 2:
+                    # node_c_second_non_param_arg = node_c.args[1]
+                    node_c_second_non_param_arg = get_normalized_nth_input(
+                        # pyrefly: ignore [unbound-name]
+                        node_c,
+                        gm_b,
+                        1,
+                    )
+                node_a_shadows_c = _insert_copy_of_subgraph_a_after_input_node_c(
+                    dtype_cast_node,
+                    node_c_second_non_param_arg,
+                    subgraph_a,
+                    gm_a,
+                    gm_b,
+                    # pyrefly: ignore [unbound-name]
+                    node_c.name + "_shadow_copy_",
+                )
+                env_c[node_a_shadows_c.name] = node_a_shadows_c
+                # subgraph so far:
+                #
+                #       dtype_cast_node -> (logger_a_input)? -> subgraph_a_copy(args/kwargs not shown)
+                #                  /
+                # (prev_node_c)+ -> (logger_c_input)? -> node_start_c
+
+                if should_log_inputs:
+                    # When we created the input logger, we left the ref_node_name
+                    # as an empty string, because the subgraph copy did not exist
+                    # yet. Now that the subgraph copy exists, we modify this name
+                    # to its true value.
+                    # Note: the alternative to this is to create the input logger
+                    # after creating the subgraph, which is slightly more
+                    # complicated. This is the lesser of two evils.
+                    # input_logger = env_c[dtype_cast_node.name]
+                    # Find the first node in the subgraph
+                    cur_node = node_a_shadows_c
+                    while get_normalized_nth_input(cur_node, gm_b, 0) != input_logger:  # type: ignore[possibly-undefined]
+                        cur_node = get_normalized_nth_input(cur_node, gm_b, 0)  # type: ignore[assignment]
+                    # pyrefly: ignore [unbound-name]
+                    if isinstance(input_logger, Node):
+                        # pyrefly: ignore [unbound-name]
+                        input_logger_mod = getattr(gm_b, input_logger.name)
+                        input_logger_mod.ref_node_name = cur_node.name
+                    else:
+                        # pyrefly: ignore [unbound-name]
+                        if not isinstance(input_logger, list):
+                            raise AssertionError(
+                                # pyrefly: ignore [unbound-name]
+                                f"Expected list, got {type(input_logger)}"
+                            )
+                        # pyrefly: ignore [unbound-name]
+                        for input_logger_inner in input_logger:
+                            input_logger_mod = getattr(gm_b, input_logger_inner.name)
+                            input_logger_mod.ref_node_name = cur_node.name
+
+                # hook up a logger to the mod_a copy
+                env_c[node_a_shadows_c.name] = _insert_logger_after_node(
+                    env_c[node_a_shadows_c.name],
+                    gm_b,
+                    logger_cls,
+                    "_ns_logger_a_",
+                    node_a_shadows_c.name,
+                    name_a,
+                    ref_name,
+                    ref_node_type_a,
+                    NSSingleResultValuesType.NODE_OUTPUT.value,
+                    index_within_arg=0,
+                    index_of_arg=0,
+                    fqn=fqn_base_a,
+                )
+                # subgraph so far:
+                #
+                #       dtype_cast_node -> (logger_a_input)? -> subgraph_a_copy -> logger_a
+                #                  /
+                # (prev_node_c)+ -> (logger_c_input)? -> node_start_c
+
+            if node_b_is_end_node:
+                # hook up a logger to the mod_b copy
+                env_c[node_b.name] = _insert_logger_after_node(
+                    env_c[node_b.name],
+                    gm_b,
+                    logger_cls,
+                    "_ns_logger_b_",
+                    node_b.name,
+                    name_b,
+                    ref_name,
+                    ref_node_type_b,
+                    NSSingleResultValuesType.NODE_OUTPUT.value,
+                    index_within_arg=0,
+                    index_of_arg=0,
+                    fqn=fqn_base_b,
+                )
+                # subgraph so far:
+                #
+                #       dtype_cast_node -> (logger_a_input)? -> subgraph_a_copy -> logger_a
+                #                  /
+                # (prev_node_c+) -> (logger_c_input)? -> node_start_c -> ... -> node_end_c -> logger_c
+                #
+                # Note: node_start_c may be the same node as node_end_c, or they
+                # may have nodes in between.
+
+        else:
+            env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
+
+    gm_c = GraphModule(gm_b, graph_c)
+    return gm_c
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/mappings.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/mappings.py
new file mode 100644
index 0000000000000000000000000000000000000000..275291789f1c5461af366038d7702801bf5fc303
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/mappings.py
@@ -0,0 +1,763 @@
+import operator
+from typing import TYPE_CHECKING
+
+import torch
+import torch.ao.nn.intrinsic as nni
+import torch.ao.nn.intrinsic.qat as nniqat
+import torch.ao.nn.intrinsic.quantized as nniq
+import torch.ao.nn.intrinsic.quantized.dynamic as nniqd
+import torch.ao.nn.qat as nnqat
+import torch.ao.nn.qat.dynamic as nnqatd
+import torch.ao.nn.quantized as nnq
+import torch.ao.nn.quantized.dynamic as nnqd
+import torch.ao.quantization.fx._lower_to_native_backend as _lower_to_native_backend
+import torch.ao.quantization.quantization_mappings as quantization_mappings
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.ao.quantization.backend_config import get_native_backend_config
+
+from .ns_types import NSNodeTargetType
+
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+
+
+toq = torch.ops.quantized
+
+
+def get_base_name_to_sets_of_related_ops() -> dict[str, set[NSNodeTargetType]]:
+    # note: this set is modified below by items from backend_config
+    sets_of_related_ops: list[set[NSNodeTargetType]] = [
+        # conv modules
+        {
+            nn.Conv1d,
+        },
+        {
+            nn.Conv2d,
+        },
+        {
+            nn.Conv3d,
+        },
+        # conv functionals
+        {
+            F.conv1d,
+        },
+        {
+            F.conv2d,
+        },
+        {
+            F.conv3d,
+        },
+        # linear modules
+        {
+            nn.Linear,
+        },
+        # linear functionals
+        {
+            F.linear,
+        },
+        # average pool
+        {
+            nn.AvgPool1d,
+            torch.avg_pool1d,
+        },
+        {
+            nn.AvgPool2d,
+            torch._C._nn.avg_pool2d,
+        },
+        {
+            nn.AvgPool3d,
+            torch._C._nn.avg_pool3d,
+        },
+        # adaptive average pool
+        {
+            nn.AdaptiveAvgPool1d,
+            F.adaptive_avg_pool1d,
+        },
+        {
+            nn.AdaptiveAvgPool2d,
+            F.adaptive_avg_pool2d,
+        },
+        {
+            nn.AdaptiveAvgPool3d,
+            F.adaptive_avg_pool3d,
+        },
+        # LSTM
+        {
+            nn.LSTM,
+        },
+        # add
+        {
+            torch.add,
+            operator.add,  # x + y
+        },
+        # cat
+        {
+            torch.cat,
+        },
+        # mul
+        {
+            torch.mul,
+            operator.mul,
+        },
+        # relu
+        {
+            F.relu,
+            nn.ReLU,
+            "relu",
+            "relu_",
+            torch.relu,
+        },
+        # maxpool
+        {
+            nn.MaxPool1d,
+            F.max_pool1d,
+        },
+        {
+            nn.MaxPool2d,
+            F.max_pool2d,
+        },
+        {
+            nn.MaxPool3d,
+            F.max_pool3d,
+        },
+        # sigmoid
+        {
+            torch.sigmoid,
+            "sigmoid",
+            "sigmoid_",
+            nn.Sigmoid,
+            F.sigmoid,
+        },
+        # BatchNorm
+        {
+            nn.BatchNorm2d,
+        },
+        {
+            nn.BatchNorm3d,
+        },
+        # ConvTranspose
+        {
+            nn.ConvTranspose1d,
+        },
+        {
+            nn.ConvTranspose2d,
+        },
+        {
+            nn.ConvTranspose3d,
+        },
+        # functional transposed conv
+        {
+            F.conv_transpose1d,
+        },
+        {
+            F.conv_transpose2d,
+        },
+        {
+            F.conv_transpose3d,
+        },
+        # ELU
+        {
+            nn.ELU,
+        },
+        # Embedding
+        {
+            nn.Embedding,
+        },
+        # EmbeddingBag
+        {
+            nn.EmbeddingBag,
+        },
+        # GroupNorm
+        {
+            nn.GroupNorm,
+        },
+        # Hardswish
+        {
+            nn.Hardswish,
+        },
+        # InstanceNorm
+        {
+            nn.InstanceNorm1d,
+        },
+        {
+            nn.InstanceNorm2d,
+        },
+        {
+            nn.InstanceNorm3d,
+        },
+        # LayerNorm
+        {
+            nn.LayerNorm,
+        },
+        # LeakyReLU
+        {
+            nn.LeakyReLU,
+        },
+        # ReLU6
+        {
+            nn.ReLU6,
+            F.relu6,
+        },
+        # F.elu
+        {
+            F.elu,
+        },
+        # F.hardswish
+        {
+            F.hardswish,
+        },
+        # F.group_norm
+        {
+            F.group_norm,
+        },
+        # F.instance_norm
+        {
+            F.instance_norm,
+        },
+        # F.layer_norm
+        {
+            F.layer_norm,
+        },
+        # F.leaky_relu
+        {
+            F.leaky_relu,
+        },
+        # F.silu
+        {
+            nn.SiLU,
+            F.silu,
+        },
+        # F.mish
+        {
+            nn.Mish,
+            F.mish,
+        },
+        # F.tanh
+        {
+            nn.Tanh,
+            F.tanh,
+            torch.tanh,
+            "tanh_",
+            "tanh",
+        },
+        # F.hardsigmoid
+        {
+            "hardsigmoid_",
+            "hardsigmoid",
+            F.hardsigmoid,
+            nn.Hardsigmoid,
+        },
+        # F.hardtanh
+        {
+            nn.Hardtanh,
+            F.hardtanh,
+            F.hardtanh_,
+        },
+        # floordiv
+        {
+            operator.floordiv,
+        },
+        # unsqueeze
+        {
+            torch.unsqueeze,
+        },
+        # stack
+        {
+            torch.stack,
+        },
+        # squeeze
+        {
+            torch.squeeze,
+        },
+        # sort
+        {
+            torch.sort,
+        },
+        # repeat_interleave
+        {
+            torch.repeat_interleave,
+        },
+        # min
+        {
+            torch.min,
+        },
+        # mean
+        {
+            torch.mean,
+        },
+        # max
+        {
+            torch.max,
+        },
+        # transpose
+        {
+            torch.transpose,
+        },
+        # flatten
+        {
+            torch.flatten,
+        },
+        # clamp
+        {
+            torch.clamp,
+        },
+        # chunk
+        {
+            torch.chunk,
+        },
+        # interpolate
+        {
+            torch.nn.functional.interpolate,
+        },
+        # dropout
+        {
+            nn.Dropout,
+        },
+        # F.dropout
+        {
+            F.dropout,
+        },
+        # matmul
+        {
+            torch.matmul,
+        },
+        # Softmax
+        {
+            nn.Softmax,
+        },
+        # PReLU
+        {
+            nn.PReLU,
+            nnq.PReLU,
+        },
+        # F.prelu
+        {
+            F.prelu,
+            toq.prelu,
+        },
+        # pixel shuffle
+        {
+            nn.PixelShuffle,
+        },
+        {
+            F.pixel_shuffle,
+        },
+        # pixel unshuffle
+        {
+            nn.PixelUnshuffle,
+        },
+        {
+            F.pixel_unshuffle,
+        },
+        # narrow
+        {
+            torch.narrow,
+        },
+    ]
+
+    # for each floating point op, add versions of the op added by
+    # backend_config
+    backend_config = get_native_backend_config()
+
+    new_connections: list[tuple[Callable, Callable]] = [
+        # technical debt edge case
+        (nn.Linear, nn.modules.linear.NonDynamicallyQuantizableLinear),
+    ]
+
+    for pattern, config in backend_config._pattern_complex_format_to_config.items():
+        # pattern format: (c, (b, a))
+        first_element = pattern
+        # look from the end, because pattern is in reverse order
+        while isinstance(first_element, (list, tuple)):
+            first_element = first_element[-1]
+
+        if config.fused_module is not None:
+            # case 1: pattern fuses a pattern of ops into an op
+            # example: nn.Conv1d, nn.ReLU fused into nni.ConvReLU1d
+            new_connections.append((first_element, config.fused_module))
+
+        if config.qat_module is not None:
+            # case 2: pattern swaps a module into a QAT module
+            # example: nni.ConvReLU1d swapped into nniqat.ConvReLU1d
+            new_connections.append((first_element, config.qat_module))
+
+        if config.reference_quantized_module is not None:
+            # case 3: reference version of floating point module, such as
+            # nn.Conv2d and nnqr.Conv2d
+            new_connections.append((first_element, config.reference_quantized_module))
+
+    #
+    # Add reference module swaps from default lowering path
+    #
+
+    for source_to_target in (
+        _lower_to_native_backend.STATIC_LOWER_MODULE_MAP,
+        _lower_to_native_backend.DYNAMIC_LOWER_MODULE_MAP,
+        _lower_to_native_backend.WEIGHT_ONLY_LOWER_MODULE_MAP,
+        _lower_to_native_backend.SPECIAL_PATTERN_LOWER_MODULE_MAP,
+    ):
+        for source, target in source_to_target.items():  # type: ignore[attr-defined]
+            new_connections.append((source, target))
+
+    for source_to_double_target in (
+        _lower_to_native_backend.STATIC_LOWER_FUSED_MODULE_MAP,
+        _lower_to_native_backend.STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP,
+        _lower_to_native_backend.DYNAMIC_LOWER_FUSED_MODULE_MAP,
+    ):
+        for source, (target1, target2) in source_to_double_target.items():  # type: ignore[attr-defined]
+            new_connections.append((source, target1))
+            new_connections.append((source, target2))
+
+    #
+    # Add function swaps from default lowering path
+    #
+
+    for source, (  # type:ignore[assignment]
+        target1,
+        target2,
+    ) in _lower_to_native_backend.STATIC_LOWER_FUNCTIONAL_MAP.items():
+        new_connections.append((source, target1))
+        # pyrefly: ignore [bad-argument-type]
+        new_connections.append((source, target2))
+
+    for source_to_target in (
+        _lower_to_native_backend.QBIN_OP_MAPPING,
+        _lower_to_native_backend.QBIN_RELU_OP_MAPPING,
+        quantization_mappings.DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS,
+    ):
+        for source, target in source_to_target.items():  # type:ignore[assignment]
+            # pyrefly: ignore [bad-argument-type]
+            new_connections.append((source, target))
+
+    #
+    # Add other swaps, ideally in the future this could be removed
+    # after the lowering code stops using these.
+    #
+    for source_to_target in (
+        quantization_mappings.DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS,
+    ):
+        for source, target in source_to_target.items():  # type:ignore[assignment]
+            new_connections.append((source, target))
+
+    # add the new connections from backend_config
+    for item1, item2 in new_connections:
+        for set_of_related_ops in sets_of_related_ops:
+            if item1 in set_of_related_ops or item2 in set_of_related_ops:
+                set_of_related_ops.add(item1)
+                set_of_related_ops.add(item2)
+                break
+
+    base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] = {}
+
+    for counter, set_of_related_ops in enumerate(sets_of_related_ops):
+        base_name = str(counter)
+        base_name_to_sets_of_related_ops[base_name] = set_of_related_ops
+
+    return base_name_to_sets_of_related_ops
+
+
+def get_base_name_for_op(
+    base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]],
+    op: NSNodeTargetType,
+) -> str | None:
+    for base_name, set_of_related_ops in base_name_to_sets_of_related_ops.items():
+        if op in set_of_related_ops:
+            return base_name
+    return None
+
+
+def add_op_to_sets_of_related_ops(
+    base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]],
+    op: NSNodeTargetType,
+    related_op: NSNodeTargetType | None,
+) -> None:
+    if related_op is not None:
+        for set_of_related_ops in base_name_to_sets_of_related_ops.values():
+            if related_op in set_of_related_ops:
+                set_of_related_ops.add(op)
+                return
+        # if we got here, related_op was not found
+        raise AssertionError(f"{related_op} was not found")
+    else:
+        counter = 0
+        while str(counter) in base_name_to_sets_of_related_ops:
+            counter += 1
+        base_name_to_sets_of_related_ops[str(counter)] = {op}
+
+
+# TODO(future PR): clean this up
+def get_node_type_to_io_type_map() -> dict[str, set[NSNodeTargetType]]:
+    FUNS_IO_TYPE_FP32: set[NSNodeTargetType] = {
+        F.linear,
+        F.conv1d,
+        F.conv2d,
+        F.conv3d,
+        torch.cat,
+        F.elu,
+        F.hardswish,
+        F.instance_norm,
+        F.layer_norm,
+        F.leaky_relu,
+        F.dropout,
+        F.silu,
+        F.mish,
+        operator.add,
+        torch.add,
+        operator.mul,
+        torch.mul,
+        torch.sum,
+        F.prelu,
+    }
+
+    FUNS_IO_TYPE_FP16: set[NSNodeTargetType] = set()
+
+    FUNS_IO_TYPE_INT8: set[NSNodeTargetType] = {
+        toq.linear,
+        toq.linear_relu,
+        toq.conv1d,
+        toq.conv1d_relu,
+        toq.conv2d,
+        toq.conv2d_relu,
+        toq.conv3d,
+        toq.conv3d_relu,
+        toq.cat,
+        toq.elu,
+        toq.hardswish,
+        toq.instance_norm,
+        toq.layer_norm,
+        toq.leaky_relu,
+        toq.dropout,
+        toq.prelu,
+        # TODO(future PR): implement shadowing for binary ops and
+        # uncomment below
+        # toq.add,
+        # toq.mul,
+    }
+
+    FUNS_IO_TYPE_FP32_OR_INT8: set[NSNodeTargetType] = {
+        F.relu,
+        F.tanh,
+        torch.tanh,
+        F.sigmoid,
+        torch.sigmoid,
+        F.hardsigmoid,
+        operator.floordiv,
+        torch.adaptive_avg_pool1d,
+        F.adaptive_avg_pool2d,
+        F.adaptive_avg_pool3d,
+        F.dropout,
+        F.hardtanh,
+        F.hardtanh_,
+        F.interpolate,
+        F.max_pool1d,
+        F.max_pool2d,
+        F.max_pool3d,
+        F.relu6,
+        F.pixel_shuffle,
+        F.pixel_unshuffle,
+        torch.avg_pool1d,
+        torch._C._nn.avg_pool2d,
+        torch._C._nn.avg_pool3d,
+        torch.cat,
+        torch.chunk,
+        torch.clamp,
+        torch.flatten,
+        torch.transpose,
+        torch.max,
+        torch.mean,
+        torch.min,
+        torch.narrow,
+        torch.repeat_interleave,
+        torch.sort,
+        torch.squeeze,
+        torch.stack,
+        torch.unsqueeze,
+        operator.add,
+    }
+
+    MODS_IO_TYPE_FP32: set[NSNodeTargetType] = {
+        nn.Linear,
+        nnqat.Linear,
+        nnqatd.Linear,
+        nnqd.Linear,
+        torch.nn.modules.linear.NonDynamicallyQuantizableLinear,
+        nn.Conv1d,
+        nn.Conv2d,
+        nn.Conv3d,
+        nnqat.Conv1d,
+        nnqat.Conv2d,
+        nnqat.Conv3d,
+        nnqat.Embedding,
+        nnqat.EmbeddingBag,
+        nn.LSTM,
+        # note: nnqd.Linear is an instance of nnq.Linear, so this
+        # check has to happen before the int8 module check
+        nnqd.LSTM,
+        nn.BatchNorm2d,
+        nn.BatchNorm3d,
+        nn.Dropout,
+        nn.ConvTranspose1d,
+        nn.ConvTranspose2d,
+        nn.ConvTranspose3d,
+        nn.ELU,
+        nn.GroupNorm,
+        nn.InstanceNorm1d,
+        nn.InstanceNorm2d,
+        nn.InstanceNorm3d,
+        nn.LayerNorm,
+        nn.Hardswish,
+        nn.LeakyReLU,
+        nn.ReLU6,
+        nn.SiLU,
+        nn.Mish,
+        nn.Softmax,
+        nn.PReLU,
+        nni.BNReLU2d,
+        nni.BNReLU3d,
+        nni.ConvReLU1d,
+        nni.ConvReLU2d,
+        nni.ConvReLU3d,
+        nni.LinearReLU,
+        nni.LinearBn1d,
+        nni.ConvBn1d,
+        nni.ConvBn2d,
+        nni.ConvBn3d,
+        nniqat.ConvBn1d,
+        nniqat.ConvBn2d,
+        nniqat.ConvBn3d,
+        nniqat.ConvBnReLU1d,
+        nniqat.ConvBnReLU2d,
+        nniqat.ConvBnReLU3d,
+        nniqat.ConvReLU1d,
+        nniqat.ConvReLU2d,
+        nniqat.ConvReLU3d,
+        nniqat.LinearReLU,
+        nniqat.LinearBn1d,
+        nniqd.LinearReLU,
+        nni.LinearLeakyReLU,
+        nni.LinearTanh,
+        nni.ConvAdd2d,
+        nni.ConvAddReLU2d,
+    }
+
+    MODS_IO_TYPE_INT8: set[NSNodeTargetType] = {
+        nnq.Linear,
+        nnq.Conv1d,
+        nnq.Conv2d,
+        nnq.Conv3d,
+        nnq.BatchNorm2d,
+        nnq.BatchNorm3d,
+        nnq.Dropout,
+        nnq.ConvTranspose1d,
+        nnq.ConvTranspose2d,
+        nnq.ELU,
+        nnq.InstanceNorm1d,
+        nnq.InstanceNorm2d,
+        nnq.InstanceNorm3d,
+        nnq.LayerNorm,
+        nnq.Hardswish,
+        nnq.LeakyReLU,
+        nnq.Embedding,
+        nnq.EmbeddingBag,
+        nnq.Dropout,
+        nnq.Softmax,
+        nnq.PReLU,
+        nniq.BNReLU2d,
+        nniq.BNReLU3d,
+        nniq.ConvReLU1d,
+        nniq.ConvReLU2d,
+        nniq.ConvReLU3d,
+        nniq.LinearReLU,
+        nniq.LinearLeakyReLU,
+        nniq.LinearTanh,
+        nniq.ConvAdd2d,
+        nniq.ConvAddReLU2d,
+    }
+
+    MODS_IO_TYPE_FP32_OR_INT8: set[NSNodeTargetType] = {
+        nn.ReLU,
+        nn.Tanh,
+        nn.Sigmoid,
+        nn.Hardsigmoid,
+        nn.AdaptiveAvgPool1d,
+        nn.AdaptiveAvgPool2d,
+        nn.AdaptiveAvgPool3d,
+        nn.AvgPool1d,
+        nn.AvgPool2d,
+        nn.AvgPool3d,
+        nn.Dropout,
+        nn.Hardtanh,
+        nn.Identity,
+        nn.MaxPool1d,
+        nn.MaxPool2d,
+        nn.MaxPool3d,
+        nn.PixelShuffle,
+        nn.PixelUnshuffle,
+        nn.ReLU6,
+    }
+
+    METHS_IO_TYPE_FP32_OR_INT8: set[NSNodeTargetType] = {
+        "sigmoid_",
+        "sigmoid",
+        "tanh_",
+        "tanh",
+        "hardsigmoid_",
+        "hardsigmoid",
+        "relu_",
+        "relu",
+    }
+
+    return {
+        "funs_io_type_fp32": FUNS_IO_TYPE_FP32,
+        "funs_io_type_fp16": FUNS_IO_TYPE_FP16,
+        "funs_io_type_int8": FUNS_IO_TYPE_INT8,
+        "funs_io_type_fp32_or_int8": FUNS_IO_TYPE_FP32_OR_INT8,
+        "mods_io_type_fp32": MODS_IO_TYPE_FP32,
+        "mods_io_type_int8": MODS_IO_TYPE_INT8,
+        "mods_io_type_fp32_or_int8": MODS_IO_TYPE_FP32_OR_INT8,
+        "meths_io_type_fp32_or_int8": METHS_IO_TYPE_FP32_OR_INT8,
+    }
+
+
+def get_unmatchable_types_map() -> dict[str, set[NSNodeTargetType]]:
+    FUNS_UNMATCHABLE: set[NSNodeTargetType] = {
+        torch.quantize_per_tensor,
+        operator.getitem,
+    }
+
+    MODS_UNMATCHABLE: set[NSNodeTargetType] = {
+        nn.Identity,
+    }
+
+    METHS_UNMATCHABLE: set[NSNodeTargetType] = {
+        "to",
+        "dequantize",
+        "reshape",
+        "view",
+        "unsqueeze_",
+        "unsqueeze",
+        "transpose",
+        "squeeze_",
+        "squeeze",
+        "size",
+        "shape",
+        "resize_",
+        "repeat_interleave",
+        "repeat",
+        "permute",
+        "numel",
+        "mean",
+        "detach_",
+        "detach",
+        "contiguous",
+        "clamp",
+        "chunk",
+    }
+
+    return {
+        "funs_unmatchable": FUNS_UNMATCHABLE,
+        "mods_unmatchable": MODS_UNMATCHABLE,
+        "meths_unmatchable": METHS_UNMATCHABLE,
+    }
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/n_shadows_utils.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/n_shadows_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a828b1e526a5914dd61acfe82e507802df6cff84
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/n_shadows_utils.py
@@ -0,0 +1,1412 @@
+# mypy: allow-untyped-defs
+import collections
+import copy
+import operator
+from collections.abc import Callable
+from typing import Any
+
+import torch
+import torch.fx
+from torch.ao.ns.fx.graph_passes import _maybe_get_fqn
+from torch.ao.ns.fx.ns_types import NSResultsType, NSSingleResultValuesType
+from torch.ao.ns.fx.utils import (  # TODO(future PR): make this work correctly for methods
+    get_normalized_nth_input,
+    get_target_type_str,
+)
+from torch.ao.quantization import QConfigMapping
+from torch.ao.quantization.fx.match_utils import _MatchResult
+from torch.ao.quantization.qconfig import QConfigAny
+from torch.ao.quantization.utils import getattr_from_fqn
+from torch.fx import Graph, GraphModule, Node
+from torch.utils._pytree import tree_map
+
+
+SHADOW_NODE_NAME_PREFIX = "shadow"
+SHADOW_WRAPPER_NODE_NAME_PREFIX = "shadow_wrapper"
+
+# TODO(future PR): reuse existing mapping instead of creating a new one
+BINARY_FUNCTIONS = {
+    torch.add,
+    torch.Tensor.add,
+    operator.add,
+    torch.mul,
+    torch.Tensor.mul,
+    operator.mul,
+}
+
+
+def _get_attr_name(subgraph_idx, subgraph_candidate_idx):
+    return f"{SHADOW_NODE_NAME_PREFIX}_{subgraph_idx}_{subgraph_candidate_idx}"
+
+
+def _get_attr_wrapper_name(subgraph_idx, subgraph_candidate_idx):
+    return f"{SHADOW_WRAPPER_NODE_NAME_PREFIX}_{subgraph_idx}_{subgraph_candidate_idx}"
+
+
+class OutputProp:
+    """
+    Output propagation (modeled from shape propagation).
+
+    Given a GraphModule and an example input, saves the output flowing
+    through each node on `node.traced_result`.
+
+    Code based on the example from
+    https://pytorch.org/docs/stable/fx.html#the-interpreter-pattern
+    """
+
+    def __init__(self, mod):
+        self.mod = mod
+        self.graph = mod.graph
+        self.modules = dict(self.mod.named_modules())
+
+    def propagate(self, *args):
+        args_iter = iter(args)
+        env: dict[str, Node] = {}
+
+        def load_arg(a):
+            return torch.fx.graph.map_arg(a, lambda n: env[n.name])
+
+        def fetch_attr(target: str):
+            target_atoms = target.split(".")
+            attr_itr = self.mod
+            for i, atom in enumerate(target_atoms):
+                if not hasattr(attr_itr, atom):
+                    raise RuntimeError(
+                        f"Node referenced nonexistent target {'.'.join(target_atoms[:i])}"
+                    )
+                attr_itr = getattr(attr_itr, atom)
+            return attr_itr
+
+        for node in self.graph.nodes:
+            if node.op == "placeholder":
+                result = next(args_iter)
+            elif node.op == "get_attr":
+                result = fetch_attr(node.target)
+            elif node.op == "call_function":
+                result = node.target(*load_arg(node.args), **load_arg(node.kwargs))
+            elif node.op == "call_method":
+                self_obj, *args = load_arg(node.args)
+                kwargs = load_arg(node.kwargs)
+                result = getattr(self_obj, node.target)(*args, **kwargs)
+            elif node.op == "call_module":
+                result = self.modules[node.target](
+                    *load_arg(node.args), **load_arg(node.kwargs)
+                )
+
+            if isinstance(result, torch.Tensor):  # type: ignore[possibly-undefined]
+                # pyrefly: ignore [unbound-name]
+                node.traced_result = result
+
+            # pyrefly: ignore [unbound-name]
+            env[node.name] = result
+
+        return None
+
+
+def _get_dedup_subgraphs(matches: dict[str, _MatchResult]) -> dict[str, list[Node]]:
+    # the original matches variable is unique by node, make it unique by subgraph
+    # instead
+    seen_nodes = set()
+    subgraphs_dedup = {}
+
+    # Dict items are not reversible until Python 3.8, so we hack it
+    # to be compatible with previous Python versions
+    # TODO(future PR): try reversed(list(matches.items()))
+    matches_items_reversed: list[tuple[str, _MatchResult]] = list(
+        reversed(matches.items())
+    )
+
+    # Note: the order is important.  `matches` currently provides the matches
+    # in reverse order.  We would like to process the matches in non-reverse
+    # order, so that we can create an intuitive naming scheme, such as
+    # naming the first op's submodules `shadow_0_0` through `shadow_0_(n-1)`
+    for name, cur_match in matches_items_reversed:  # type: ignore[call-overload]
+        was_seen = False
+        for node_or_tuple in cur_match[1]:
+            # Cur_match[1] has an unusual type. It says that it's a `List[Node]`,
+            # but it is really not. Furthermore, the contents of this field
+            # can change from match results of multiple nodes of the same pattern
+            #
+            # For example, for conv -> bn -> relu, we see
+            # match_results = {
+            #   'conv': (relu, [(bn, conv), relu], ...),
+            #   'bn': (relu, [(bn, conv), relu], ...),
+            #   'relu': (relu, [(bn, conv), relu], ...),
+            # }
+            #
+            # Ideally we should clean up the `find_matches` function to make
+            # this more intuitive. For the purposes of this prototype, we hack
+            # around it.
+
+            if isinstance(node_or_tuple, Node):
+                if node_or_tuple in seen_nodes:
+                    was_seen = True
+                seen_nodes.add(node_or_tuple)
+
+            else:
+                if not isinstance(node_or_tuple, tuple):
+                    raise AssertionError(f"Expected tuple, got {type(node_or_tuple)}")
+                for node in node_or_tuple:
+                    if not isinstance(node, Node):
+                        raise AssertionError(f"Expected Node, got {type(node)}")
+                    if node in seen_nodes:
+                        was_seen = True
+                    seen_nodes.add(node)
+
+        if was_seen:
+            continue
+
+        # Start with the unusual type, convert it to [op_0, ..., op_n]
+        list_of_nodes = []
+
+        if len(cur_match[1]) == 1:
+            list_of_nodes = cur_match[1]
+        else:
+            if len(cur_match[1]) != 2:
+                raise ValueError(
+                    f"Expected cur_match[1] to have length 2, got {len(cur_match[1])}"
+                )
+            # either (a, b), or ((a, b), c) or (c, (a, b))
+            # cannot make any assumptions on order, not clear what the
+            # _find_matches function is doing to populate this
+            # TODO(future PR): make this code less confusing,  see discussion
+            # in https://github.com/pytorch/pytorch/pull/80521/files#r975918836
+
+            def _order_nodes(node_a, node_b, node_c) -> list[Node]:
+                nodes = [node_a, node_b, node_c]
+                first_node = None
+                mid_node = None
+                last_node = None
+                for n in nodes:
+                    prev_n = n.args[0]
+                    next_n = next(iter(n.users))
+                    if prev_n not in nodes:
+                        first_node = n
+                    elif next_n not in nodes:
+                        last_node = n
+                    else:
+                        mid_node = n
+                if first_node is None or mid_node is None or last_node is None:
+                    raise AssertionError("Expected all nodes to be non-None")
+                if mid_node.args[0] is not first_node:
+                    raise AssertionError("Expected mid_node.args[0] to be first_node")
+                if last_node.args[0] is not mid_node:
+                    raise AssertionError("Expected last_node.args[0] to be mid_node")
+                return [last_node, mid_node, first_node]
+
+            if isinstance(cur_match[1][0], Node) and isinstance(cur_match[1][1], Node):
+                # (a, b)
+                list_of_nodes = cur_match[1]
+            elif isinstance(cur_match[1][0], tuple):
+                # ((a, b), c)
+                node_a, node_b = cur_match[1][0]
+                node_c = cur_match[1][1]
+                list_of_nodes = _order_nodes(node_a, node_b, node_c)
+            elif isinstance(cur_match[1][1], tuple):
+                # (a, (b, c))
+                node_a, node_b = cur_match[1][1]
+                node_c = cur_match[1][0]
+                list_of_nodes = _order_nodes(node_a, node_b, node_c)
+
+        # [node_n, ..., node_0], note that the order is reversed
+        # to make it chronological for simple subgraphs
+        list_of_nodes.reverse()
+        subgraphs_dedup[name] = list_of_nodes
+
+    return subgraphs_dedup
+
+
+def _get_logger_for_subgraph(
+    model: GraphModule,
+    first_node: Node,
+    last_node: Node,
+    subgraph_idx: int,
+    subgraph_candidate_idx: int,
+    qconfig_str: str,
+    logger_cls: Callable,
+    fqn: str | None,
+) -> torch.nn.Module:
+    """
+    Given a model and a linear subgraph starting from `first_node` and
+    ending with `last_node`, creates a logger for the end of this
+    subgraph.
+    """
+    if fqn is None:
+        fqn = ""
+    logger_mod_orig = logger_cls(
+        first_node.name,  # ref_node_name
+        last_node.name,  # prev_node_name
+        f"subgraph_{subgraph_idx}_{subgraph_candidate_idx}",  # model_name
+        "model",  # ref_name
+        get_target_type_str(last_node, model),  # prev_node_target_type
+        get_target_type_str(first_node, model),  # ref_node_target_type
+        NSSingleResultValuesType.NODE_OUTPUT.value,  # results_type
+        0,  # index_within_arg
+        0,  # index_of_arg
+        fqn,  # fqn
+        qconfig_str,
+    )
+    # Usually we expect the user to add loggers, then calibrate, then convert,
+    # and then populate loggers.  This is why the loggers start disabled.
+    # TODO(future PR): reconsider the design to make this more intuitive.
+    logger_mod_orig.enabled = False
+    return logger_mod_orig
+
+
+def create_submodule_from_subgraph(
+    model: torch.nn.Module,
+    first_node: Node,
+    last_node: Node,
+) -> GraphModule:
+    """
+    Input: a model, and a linear subgraph within the model from first_node to
+      last_node.
+
+    Output: a new submodule containing a copy of the subgraph, with the inputs
+      to the first node becoming the inputs to the submodule, and all other
+      nodes in the subgraph being copied.
+
+    Example inputs:
+
+    `model`: a module with graph
+
+      x0 -> op1 -> x1 -> op2 -> x2
+             |
+            arg1
+
+    `first_node`: op1
+    `last_node`: op2
+
+    Example output: a new module with graph
+
+      input1 -> op1_copy -> x1 -> op2_copy -> output1
+                   |
+                  arg1
+    """
+
+    #
+    # create a blank GraphModule with an empty graph
+    #
+
+    class M(torch.nn.Module):
+        def forward(self, x):
+            pass
+
+    m = M()
+    gm = torch.fx.symbolic_trace(m)
+    g = gm.graph
+    for node in reversed(gm.graph.nodes):
+        g.erase_node(node)
+
+    #
+    # modify the graph to have a copy of our subgraph
+    #
+
+    cur_node_orig = first_node
+
+    cur_name_idx = 0
+
+    iteration_limit = 100
+    cur_iteration = 0
+
+    while True:
+        if cur_node_orig is first_node:
+            # we are at the first node, we need to set up graph inputs
+            # TODO(future): some graphs could have placeholders which are unrelated
+            # to the first node, need to handle this
+            cur_args_copy = []
+            cur_kwargs_copy = {}
+            seen_names: set[str] = set()
+            old_name_to_new_node: dict[str, Node] = {}
+
+            def _add_placeholder(
+                g: Graph, node: Node, seen_names, old_name_to_new_node
+            ):
+                # note: for graphs starting with patterns such as `y = x + x`, we
+                # need to ensure we do not add multiple placeholders with the
+                # same name
+                counter = 0
+                while node.name + "_" + str(counter) in seen_names:
+                    counter += 1
+                cur_name = node.name + "_" + str(counter)
+                seen_names.add(cur_name)
+                placeholder = g.placeholder(cur_name)
+                old_name_to_new_node[node.name] = placeholder
+                return placeholder
+
+            for arg in cur_node_orig.args:
+                if isinstance(arg, Node):
+                    p = _add_placeholder(g, arg, seen_names, old_name_to_new_node)
+                    cur_args_copy.append(p)
+                elif isinstance(arg, (list, tuple)):
+                    new_arg = []
+                    for inner_arg in arg:
+                        if isinstance(inner_arg, Node):
+                            new_arg.append(
+                                _add_placeholder(
+                                    g, inner_arg, seen_names, old_name_to_new_node
+                                )
+                            )
+                        else:
+                            new_arg.append(inner_arg)
+                    cur_args_copy.append(new_arg)
+                else:
+                    cur_args_copy.append(arg)
+
+            # TODO(future PR): handle non-normalized kwargs
+            for kwarg_name, kwarg in cur_node_orig.kwargs.items():
+                if isinstance(kwarg, Node):
+                    cur_kwargs_copy[kwarg_name] = _add_placeholder(
+                        g, kwarg, seen_names, old_name_to_new_node
+                    )
+                elif isinstance(kwarg, (list, tuple)):
+                    new_kwarg = []
+                    for inner_kwarg in kwarg:
+                        p = _add_placeholder(
+                            g,
+                            inner_kwarg,  # type: ignore[arg-type]
+                            seen_names,
+                            old_name_to_new_node,
+                        )
+                        new_kwarg.append(p)
+                    cur_kwargs_copy[kwarg_name] = new_kwarg
+                else:
+                    cur_kwargs_copy[kwarg_name] = kwarg
+
+            cur_args_copy = tuple(cur_args_copy)  # type: ignore[assignment]
+        else:
+            # we are not at first node, first arg is from the previous node,
+            # and all other args are copied
+
+            # the current implementation is simplistic and cannot handle
+            # ops with two or more arguments which need to be passed from
+            # the previous op, so we assert them out
+            if cur_node_orig.target in BINARY_FUNCTIONS:
+                raise AssertionError(
+                    f"Unexpected binary function target: {cur_node_orig.target}"
+                )
+
+            # at this point in the code, cur_node_copy is pointing to the copy
+            # of the previous node
+            # TODO(future PR): this is not handling complicated graphs correctly, need to
+            # look at actual relationships instead of assuming sequential graph
+            # TODO(future PR): this is ignoring kwargs, will need to support kwargs
+            # for any fusion pattern which has them for a node that is not the
+            # first node.
+            cur_args_copy = [cur_node_copy]  # type: ignore[has-type, possibly-undefined]  # noqa: F821
+
+            if len(cur_node_orig.args) > 1:
+                for arg in cur_node_orig.args[1:]:
+                    if isinstance(arg, torch.nn.Parameter):
+                        new_arg = arg.detach().clone()  # type: ignore[assignment]
+                        mod_name = f"mod_{cur_name_idx}"
+                        cur_name_idx += 1
+                        setattr(gm, mod_name, new_arg)
+                        new_arg_placeholder = gm.placeholder(mod_name)  # type: ignore[operator]
+                        cur_args_copy.append(new_arg_placeholder)
+                    elif isinstance(arg, (float, int, torch.dtype)):
+                        # pyrefly: ignore [bad-argument-type]
+                        cur_args_copy.append(arg)
+                    else:
+                        raise AssertionError(f"arg of type {type(arg)} not handled yet")
+            cur_args_copy = tuple(cur_args_copy)  # type: ignore[assignment]
+
+        # copy the node
+        if cur_node_orig.op == "call_module":
+            orig_mod = getattr_from_fqn(model, cur_node_orig.target)  # type: ignore[arg-type]
+            orig_mod_copy = copy.deepcopy(orig_mod)
+            mod_name = f"mod_{cur_name_idx}"
+            setattr(gm, mod_name, orig_mod_copy)
+            cur_name_idx += 1
+            cur_node_copy = g.call_module(mod_name, cur_args_copy, cur_kwargs_copy)  # type: ignore[possibly-undefined,arg-type]
+
+        elif cur_node_orig.op == "call_function":
+            cur_node_copy = g.call_function(
+                cur_node_orig.target,  # type: ignore[arg-type]
+                cur_args_copy,  # type: ignore[arg-type]
+                cur_kwargs_copy,  # type: ignore[possibly-undefined]
+            )
+
+        elif cur_node_orig.op == "call_method":
+            cur_node_copy = g.call_method(
+                cur_node_orig.target,  # type: ignore[arg-type]
+                cur_args_copy,  # type: ignore[arg-type]
+                cur_kwargs_copy,  # type: ignore[possibly-undefined]
+            )
+
+        else:
+            raise AssertionError(f"{cur_node_orig.op} not supported yet")
+
+        if cur_node_orig is last_node:
+            break
+
+        # go to next node
+        if len(cur_node_orig.users.keys()) != 1:
+            raise AssertionError(
+                f"{cur_node_orig} has more than 1 users, not supported yet"
+            )
+        cur_node_orig = next(iter(cur_node_orig.users.keys()))
+        cur_iteration += 1
+        if cur_iteration > iteration_limit:
+            raise AssertionError("iteration limit exceeded")
+
+    # set up outputs
+    g.output(cur_node_copy)
+
+    gm.recompile()
+    return gm
+
+
+def create_one_transformed_and_logged_copy_of_subgraph(
+    mt: GraphModule,
+    subgraph_idx: int,
+    subgraph_candidate_idx: int,
+    first_node: Node,
+    last_node: Node,
+    fqn: str | None,
+    list_of_node_name_to_qconfig: list[dict[str, QConfigAny]],
+    example_inputs: Any,
+    last_added_shadow_node_list: list[Node | None],
+    custom_prepare_fn: Callable | None = None,
+    custom_prepare_kwargs: dict[str, Any] | None = None,
+) -> None:
+    """
+    Given a subgraph in `mt` and a subgraph candidate idx, inserts the
+    subgraph candidate copy and instruments it with loggers.
+
+    If subgraph_candidate_idx is 0, this is the baseline fp32 subgraph and we just
+    add a logger to the end.
+
+    If subgraph_candidate_idx is not 0, we create a copy of the subgraph and
+    prepare it with `prepare_fx`.
+    """
+
+    # TODO(future PR): move logger classes to utils to remove circular dependency
+    from torch.ao.ns._numeric_suite_fx import OutputComparisonLogger, OutputLogger
+
+    if subgraph_candidate_idx == 0:
+        # idx = 0 is the floating point (original) version of the subgraph
+        # We keep the subgraph as is, and add a logger at the end
+
+        qconfig_str = ""
+        logger_mod_orig = _get_logger_for_subgraph(
+            mt,
+            first_node,
+            last_node,
+            subgraph_idx,
+            subgraph_candidate_idx,
+            qconfig_str,
+            OutputLogger,
+            fqn,
+        )
+
+        attr_name = _get_attr_name(subgraph_idx, subgraph_candidate_idx)
+        if hasattr(mt, attr_name):
+            raise AssertionError(f"Unexpected attribute '{attr_name}' found in {mt}")
+        setattr(mt, attr_name, logger_mod_orig)
+        with mt.graph.inserting_after(last_node):
+            new_node = mt.graph.call_module(attr_name, args=(last_node,), kwargs={})
+            last_added_shadow_node_list[0] = new_node
+
+    else:
+        # idx > 0 means we have a candidate qconfig to try, so we need
+        # to make a copy of the subgraph, feed it with the right inputs,
+        # and add a logger at the end
+
+        # get the qconfig
+        # subtract one because the first candidate is the floating point
+        # version of the subgraph
+        node_name_to_qconfig = list_of_node_name_to_qconfig[subgraph_candidate_idx - 1]
+        qconfig = node_name_to_qconfig[first_node.name]
+
+        # if no quantization is requested, skip
+        # TODO(future PR): deduplicate equivalent qconfigs that come from
+        #   different qconfig mapping objects
+        if qconfig is None:
+            return
+
+        qconfig_mapping = QConfigMapping().set_global(qconfig)
+
+        # create a copy of the submodule, wrapped in a separate module
+        orig_mod_copy_wrapped = create_submodule_from_subgraph(
+            mt, first_node, last_node
+        )
+
+        # add a call to prepare_fx on the wrapper module
+        if custom_prepare_fn is None:
+            orig_mod_copy_wrapped = torch.ao.quantization.quantize_fx.prepare_fx(
+                orig_mod_copy_wrapped, qconfig_mapping, example_inputs=example_inputs
+            )
+        else:
+            if custom_prepare_kwargs is None:
+                custom_prepare_kwargs = {}
+            for kwarg_name in [
+                "example_inputs",
+                "prepare_custom_config",
+                "qconfig_mapping",
+            ]:
+                if kwarg_name in custom_prepare_kwargs:
+                    raise AssertionError(
+                        f"cannot specify {kwarg_name} in custom_prepare_kwargs"
+                    )
+            prepare_kwargs: dict[str, Any] = {
+                "example_inputs": example_inputs,
+                "qconfig_mapping": qconfig_mapping,
+            }
+            prepare_kwargs.update(custom_prepare_kwargs)
+            orig_mod_copy_wrapped = custom_prepare_fn(
+                orig_mod_copy_wrapped, **prepare_kwargs
+            )
+
+        # attach the wrapper to the model
+        attr_name = _get_attr_wrapper_name(subgraph_idx, subgraph_candidate_idx)
+        if hasattr(mt, attr_name):
+            raise AssertionError(f"Unexpected attribute '{attr_name}' found in {mt}")
+        setattr(mt, attr_name, orig_mod_copy_wrapped)
+
+        # add a call to the wrapper module from the parent graph
+        insert_after_node = last_added_shadow_node_list[0]
+        with mt.graph.inserting_after(insert_after_node):
+            # TODO(future PR): handle fusion patterns where non-first nodes
+            # need inputs
+
+            # pass in all node args and kwargs
+
+            new_args = []
+            for arg in first_node.args:
+                if isinstance(arg, Node):
+                    new_args.append(arg)
+                elif (
+                    isinstance(arg, (list, tuple))
+                    and len(arg)
+                    and isinstance(arg[0], Node)
+                ):
+                    new_args.extend(
+                        inner_arg for inner_arg in arg if isinstance(inner_arg, Node)
+                    )
+
+            new_kwargs = {}
+            for name, old_kwarg in first_node.kwargs.items():
+                if isinstance(old_kwarg, Node):
+                    new_kwargs[name] = old_kwarg
+                elif isinstance(old_kwarg, (list, tuple)) and len(old_kwarg):
+                    # TODO(future PR): clarify why we are adding kwargs to args
+                    new_args.extend(old_kwarg)  # type: ignore[arg-type]
+
+            new_args = tuple(new_args)  # type: ignore[assignment]
+
+            new_node = mt.graph.call_module(attr_name, args=new_args, kwargs=new_kwargs)  # type: ignore[arg-type]
+
+        # add a logger to parent graph to observe the shadow wrapper
+        logger_mod_orig = _get_logger_for_subgraph(
+            mt,
+            first_node,
+            last_node,
+            subgraph_idx,
+            subgraph_candidate_idx,
+            str(qconfig),
+            OutputComparisonLogger,
+            fqn,
+        )
+
+        attr_name = _get_attr_name(subgraph_idx, subgraph_candidate_idx)
+        if hasattr(mt, attr_name):
+            raise AssertionError(f"Unexpected attribute '{attr_name}' found in {mt}")
+        setattr(mt, attr_name, logger_mod_orig)
+        with mt.graph.inserting_after(new_node):
+            logger = mt.graph.call_module(
+                attr_name, args=(new_node, last_node), kwargs={}
+            )
+            last_added_shadow_node_list[0] = logger
+
+    mt.recompile()
+
+
+def create_n_transformed_and_logged_copies_of_subgraph(
+    mt: GraphModule,
+    subgraph_idx: int,
+    match_name: str,
+    nodes_in_this_subgraph: list[Any],
+    qconfig_mappings: list[QConfigMapping],
+    list_of_node_name_to_qconfig: list[dict[str, QConfigAny]],
+    custom_prepare_fn: Callable | None = None,
+    custom_prepare_kwargs: dict[str, Any] | None = None,
+) -> None:
+    """
+    Given a model `mt` and a subgraph_idx, creates the needed copies
+    of the subgraph for all qconfigs, and instruments them with loggers.
+    """
+    # for now, assume that
+    # 1. the first node has one input
+    # 2. the last node has one output
+
+    # for now, ignore all subgraphs that contain non-nodes (tuples, etc)
+    # TODO(future PR): implement this
+    if any(not isinstance(node, Node) for node in nodes_in_this_subgraph):
+        return
+
+    first_node = nodes_in_this_subgraph[0]
+    last_node = nodes_in_this_subgraph[-1]
+    # We used output propagation to populate example values on each
+    # node. Use the example values from the previous node as the input
+    # to the current node.
+    prev_node = get_normalized_nth_input(first_node, mt, 0)
+    if isinstance(prev_node, list):
+        example_inputs = [x.traced_result for x in prev_node]
+    elif isinstance(prev_node, tuple):
+        example_inputs = (x.traced_result for x in prev_node)  # type: ignore[assignment]
+    else:
+        # currently some customer models do not have a traced_result in
+        # every node, so we have to guard for this case since we cannot
+        # quantize without an example input
+        # TODO(future PR): add a test case for this once we have an easy
+        # repro, see https://github.com/pytorch/pytorch/pull/80521/files#r975940489
+        # for additional context
+        if hasattr(prev_node, "traced_result"):
+            example_inputs = (prev_node.traced_result,)  # type: ignore[attr-defined, assignment]
+        else:
+            print(
+                "unable to get example input for node "
+                + f"{first_node.format_node()}, skipping"
+            )
+            return
+
+    # If there are no quantization configs for this subgraph, skip adding
+    # loggers. This reduces memory usage for models where not all layers are
+    # quantized.
+    # TODO(future): consider making this configurable
+    found_at_least_one_qconfig = False
+    for subgraph_candidate_idx in range(len(qconfig_mappings) + 1):
+        if subgraph_candidate_idx == 0:
+            # fp32 baseline does not need a qconfig
+            continue
+
+        # a. we have N shadows, so len(qconfig_mappings) is N
+        # b. we will have the fp32 layer + N shadows, so overall number of
+        #    (original_op) + (*shadows) will be N+1
+        # c. since `subgraph_candidate_idx` represents (b), we need
+        #    to subtract 1 to query from (a)
+        node_name_to_qconfig = list_of_node_name_to_qconfig[subgraph_candidate_idx - 1]
+        qconfig = node_name_to_qconfig[first_node.name]
+        if qconfig is not None:
+            found_at_least_one_qconfig = True
+            break
+    if not found_at_least_one_qconfig:
+        print(
+            "unable to find at least one qconfig for node "
+            + f"{first_node.format_node()}, skipping"
+        )
+        return
+
+    fqn = _maybe_get_fqn(first_node, mt)
+
+    # We want the results to contain the subgraphs in natural order,
+    # and the graph to also contain shadow wrappers and shadow loggers
+    # in natural order.
+    # If we just iterate in reverse, the graph will be in natural
+    # order but the eventual results will be in reverse order.
+    # So, we keep track of the last shadow logger we added and
+    # always insert after it.
+    last_added_shadow_node_list: list[Node | None] = [None]
+    for subgraph_candidate_idx in range(len(qconfig_mappings) + 1):
+        create_one_transformed_and_logged_copy_of_subgraph(
+            mt,
+            subgraph_idx,
+            subgraph_candidate_idx,
+            first_node,
+            last_node,
+            fqn,
+            list_of_node_name_to_qconfig,
+            example_inputs,
+            last_added_shadow_node_list,
+            custom_prepare_fn,
+            custom_prepare_kwargs,
+        )
+
+
+def create_add_loggers_graph(
+    model: GraphModule,
+    subgraphs_dedup: dict[str, list[Node]],
+    qconfig_mapping: QConfigMapping,
+    node_name_to_qconfig: dict[str, QConfigAny],
+) -> None:
+    r"""
+    Given a model, a model graph partition (currently a set of matched
+    subgraphs) and instructions how to transform each subgraph
+    (currently quantizing it according to qconfig_mapping), modifies
+    the model graph to create an alternate path through the original graph,
+    with each of the subgraphs quantized.  This is useful to compare
+    propagation error of a transformation such as quantization.
+
+    For example, given layer op0 and op1, there are four cases when handling op1:
+    1. op0 and op1 quantized
+    2. op0 and op1 unquantized
+    3. op0 quantized, op1 unquantized
+    4. op0 unquantized, op1 quantized
+
+    Example input, case 1:
+
+    .. code::
+
+      x0_0 -> op0_0 -> x1_0 -> log -----> op1_0 -> x2_0 -> log
+       \                        \          \                 \       # noqa: W605
+         ---> op0_1 -> x1_1 ----> clog    op1_1 -> x2_1 ----> clog
+
+    Example output, case 1:
+
+    .. code::
+
+      x0_0 -> op0_0 -> x1_0 -> log -----> op1_0 -> x2_0 -> log
+       \                        \                           \        # noqa: W605
+         ---> op0_1 -> x1_1 ----> clog -> op1_1 -> x2_1 ----> clog
+
+    """
+    # TODO(future PR): move logger classes to utils to remove circular dependency
+    from torch.ao.ns._numeric_suite_fx import OutputComparisonLogger, OutputLogger
+
+    def _get_subgraph_containing_node(node, subgraphs_dedup):
+        for subgraph in subgraphs_dedup.values():
+            if node in subgraph:
+                return subgraph
+        return None
+
+    # First, we need to create shadow branches, going from
+    #
+    #   x0 -> op0 -> x1 -> ...
+    #
+    #
+    # to
+    #
+    #   x0 -> op0_0 -> x1_0 -> log -> ...
+    #    \                     \
+    #      -> op0_1 -> x1_1 -> clog
+    #
+    # Later, the outputs of each shadow will be rerouted to calculate
+    # propagation error.
+
+    # Note: we cannot iterate over matched subgraphs because some nodes
+    # may not be matched. So, we iterate over nodes in the graph, and
+    # associate them to matched subgraphs if possible.
+
+    nodes_to_skip = set()
+    # for each subgraph, save a mapping from first node of subgraph
+    # to first and last node of the shadow of this subgraph
+    orig_first_node_to_shadow_in_node = {}
+    orig_first_node_to_shadow_out_node = {}
+    # need to record original list because we will mutate the graph as we go
+    orig_nodes = list(model.graph.nodes)  # type: ignore[union-attr, arg-type]
+    cur_subgraph_idx = 0
+    for n in orig_nodes:
+        if n.op in ("placeholder", "get_attr", "output") or n in nodes_to_skip:
+            continue
+
+        maybe_subgraph = _get_subgraph_containing_node(n, subgraphs_dedup)
+        insert_submodule_copy = False
+        if maybe_subgraph is not None:
+            first_node, last_node = maybe_subgraph[0], maybe_subgraph[-1]
+            nodes_to_skip.update(maybe_subgraph)
+            qconfig = node_name_to_qconfig[first_node.name]
+            if qconfig is not None:
+                insert_submodule_copy = True
+        else:
+            first_node, last_node = n, n
+
+        if insert_submodule_copy:
+            match_name = first_node.name
+            create_n_transformed_and_logged_copies_of_subgraph(
+                model,
+                cur_subgraph_idx,
+                match_name,
+                maybe_subgraph,
+                [qconfig_mapping],
+                [node_name_to_qconfig],
+                None,
+                None,  # type: ignore[arg-type]
+            )
+            # find the created shadow module and record it so we
+            # can find it easily in step 2
+            expected_shadow_target = f"shadow_wrapper_{cur_subgraph_idx}_1"
+            new_shadow_mod = None
+            for maybe_shadow_mod in model.graph.nodes:
+                if (
+                    maybe_shadow_mod.op == "call_module"
+                    and maybe_shadow_mod.target == expected_shadow_target
+                ):
+                    new_shadow_mod = maybe_shadow_mod
+                    break
+            if new_shadow_mod is None:
+                raise AssertionError("Expected new_shadow_mod to be non-None")
+            orig_first_node_to_shadow_in_node[first_node] = new_shadow_mod
+            orig_first_node_to_shadow_out_node[first_node] = new_shadow_mod
+
+        else:
+            # create a copy of the subgraph by only copying FX nodes
+            # but not copying any parameters, to minimize memory usage
+            subgraph_to_use = (
+                maybe_subgraph if maybe_subgraph is not None else [first_node]
+            )
+
+            # add a regular logger after last_node
+            qconfig_str = ""
+            subgraph_candidate_idx = 0
+            fqn = _maybe_get_fqn(first_node, model)
+            logger_mod_orig = _get_logger_for_subgraph(
+                model,
+                first_node,
+                last_node,
+                cur_subgraph_idx,
+                subgraph_candidate_idx,
+                qconfig_str,
+                OutputLogger,
+                fqn,
+            )
+            attr_name = _get_attr_name(cur_subgraph_idx, subgraph_candidate_idx)
+            if hasattr(model, attr_name):
+                raise AssertionError(
+                    f"Unexpected attribute '{attr_name}' found in {model}"
+                )
+            setattr(model, attr_name, logger_mod_orig)
+            insertion_point = last_node
+            with model.graph.inserting_after(insertion_point):
+                logger = model.graph.call_module(
+                    attr_name, args=(last_node,), kwargs={}
+                )
+                insertion_point = logger
+
+            # create a copy of the subgraph
+            cur_node_orig = first_node
+            cur_node_copy = None
+            first_node_copy = None
+            # pyrefly: ignore [bad-assignment]
+            while cur_node_orig in subgraph_to_use:
+                # TODO(future PR): make this support all possible args/kwargs
+                if cur_node_orig is first_node:
+                    new_args = cur_node_orig.args
+                    new_kwargs = cur_node_orig.kwargs
+                else:
+                    first_arg_for_copy: Node | None = cur_node_copy
+                    new_args = (first_arg_for_copy, *cur_node_orig.args[1:])
+                    new_kwargs = cur_node_orig.kwargs
+                # make a copy of cur_node_orig
+                with model.graph.inserting_after(insertion_point):
+                    cur_node_copy = model.graph.create_node(
+                        cur_node_orig.op,
+                        cur_node_orig.target,
+                        new_args,
+                        new_kwargs,
+                        # cur_node_orig.name,  # TODO(future PR): set name explicitly
+                    )
+                    if first_node_copy is None:
+                        first_node_copy = cur_node_copy
+                # since now only linear subgraphs are supported, all nodes
+                # except the last one must have only one user
+                if cur_node_orig != last_node:
+                    if len(cur_node_orig.users.keys()) != 1:
+                        raise AssertionError(
+                            f"Expected exactly 1, but got {len(cur_node_orig.users)}"
+                        )
+                cur_node_orig = next(iter(cur_node_orig.users.keys()))
+                if cur_node_orig.name.startswith(SHADOW_NODE_NAME_PREFIX):
+                    raise AssertionError(
+                        "cur_node_orig should not start with SHADOW_NODE_NAME_PREFIX"
+                    )
+                insertion_point = cur_node_copy
+
+            # add a comparison logger after last_node's copy
+            subgraph_candidate_idx = 1
+            logger_mod_orig = _get_logger_for_subgraph(
+                model,
+                first_node,
+                last_node,
+                cur_subgraph_idx,
+                subgraph_candidate_idx,
+                qconfig_str,
+                OutputComparisonLogger,
+                fqn,
+            )
+            attr_name = _get_attr_name(cur_subgraph_idx, subgraph_candidate_idx)
+            if hasattr(model, attr_name):
+                raise AssertionError(
+                    f"Unexpected attribute '{attr_name}' found in {model}"
+                )
+            setattr(model, attr_name, logger_mod_orig)
+            with model.graph.inserting_after(insertion_point):
+                logger = model.graph.call_module(
+                    attr_name, args=(cur_node_copy, last_node), kwargs={}
+                )
+
+            # save the final node so we can use it in step 2
+            orig_first_node_to_shadow_in_node[first_node] = first_node_copy
+            orig_first_node_to_shadow_out_node[first_node] = cur_node_copy
+
+        cur_subgraph_idx += 1
+
+    model.recompile()
+
+    # Now, we go from
+    #
+    #   x0 -> op0_0 -> x1_0 -> log -> x1 -> op1_0 -> ...
+    #    \                     \       \
+    #      -> op0_1 -> x1_1 -> clog      -> op1_1 -> ...
+    #
+    # to
+    #
+    #   x0 -> op0_0 -> x1_0 -> log --> x1_0 -> op1_0 -> ...
+    #    \                     \
+    #      -> op0_1 -> x1_1 -> clog -> x1_1 -> op1_1 -> ...
+    #
+    # sample values of key internal variables for the example above:
+    #
+    #   orig_first_node_to_shadow_in_node = {op0_0: op0_1, op1_0: op1_1}
+    #   orig_first_node_to_shadow_out_node = {op0_0: op0_1, op1_0: op1_1}
+    #
+    # note: for subgraphs with more than one node, in_node will be different
+    # compared to out_node
+
+    nodes_to_skip = set()
+    for n in orig_nodes:
+        if n.op in ("placeholder", "get_attr", "output") or n in nodes_to_skip:
+            continue
+
+        maybe_subgraph = _get_subgraph_containing_node(n, subgraphs_dedup)
+        if maybe_subgraph is not None:
+            first_node, last_node = maybe_subgraph[0], maybe_subgraph[-1]
+            nodes_to_skip.update(maybe_subgraph)
+        else:
+            first_node, last_node = n, n
+
+        def maybe_remap_node_to_shadow(node):
+            """
+            If unshadowed `node` has a shadow version, return that. If not,
+            return `node`.
+            """
+            if not isinstance(node, Node):
+                # handle scalars
+                return node
+
+            if node.op in ("placeholder", "get_attr"):
+                return node
+
+            # Find the shadowed version of this arg from the previous
+            # subgraph. For this, we need to:
+            # 1. navigate to the first node of the previous subgraph
+            # 2. get the output of the shadow wrapper which has (1) as an input
+
+            # For now, assume the arg is in matched subgraphs. In the
+            # future we may have to handle the case where this is not true.
+            prev_subgraph = _get_subgraph_containing_node(node, subgraphs_dedup)
+            if prev_subgraph is None:
+                prev_subgraph = [node]
+            prev_first_node = prev_subgraph[0]
+            prev_shadow_output = orig_first_node_to_shadow_out_node[prev_first_node]
+            return prev_shadow_output
+
+        cur_shadow_input = orig_first_node_to_shadow_in_node[first_node]
+        if cur_shadow_input is None:
+            raise AssertionError("Expected cur_shadow_input to be non-None")
+        cur_shadow_input.args = tree_map(
+            maybe_remap_node_to_shadow, cur_shadow_input.args
+        )
+        cur_shadow_input.kwargs = tree_map(
+            maybe_remap_node_to_shadow, cur_shadow_input.kwargs
+        )
+
+        model.recompile()
+
+
+def _get_weight_info_from_shadow_wrapper(shadow_wrapper: torch.nn.Module):
+    # input: shadow wrapper module
+    # output if shadow wrapper module has a weighted op:
+    #   (quantize_fn, (quantize_fn_args))
+    # output if shadow wrapper module doesn't have a weighted op:
+    #   None
+
+    # For now, assume that the weight is the second input
+    # to the shadow module. If that changes, we can fix it later.
+    placeholders_seen = 0
+    for shadow_n in shadow_wrapper.graph.nodes:  # type: ignore[union-attr]
+        if shadow_n.op != "placeholder":
+            continue
+
+        placeholders_seen += 1
+        if placeholders_seen != 2:
+            continue
+
+        # the subgraph looks like
+        #
+        #   _input_scale_1 = self._input_scale_1
+        #   _input_zero_point_1 = self._input_zero_point_1
+        #   quantize_per_channel = torch.quantize_per_channel(
+        #       w2_0, _input_scale_1, _input_zero_point_1,
+        #       0, torch.qint8)
+        #
+        #  we have `w2_0`, and are navigating this subgraph
+        #  to get `_input_scale_1` and `_input_zero_point_1`
+
+        if len(shadow_n.users) != 1:
+            raise AssertionError(f"Expected exactly 1, got {len(shadow_n.users)}")
+        quant_node = next(iter(shadow_n.users.keys()))
+        new_args: Any = None
+        if quant_node.target is torch.quantize_per_channel:
+            _weight, scale_node, zp_node, axis, dtype = quant_node.args
+            scale_val = getattr_from_fqn(shadow_wrapper, scale_node.target)
+            zp_val = getattr_from_fqn(shadow_wrapper, zp_node.target)
+            new_args = (scale_val, zp_val, axis, dtype)
+        else:
+            if quant_node.target != torch.quantize_per_tensor:
+                raise AssertionError(
+                    f"Expected torch.quantize_per_tensor, but got {quant_node.target}"
+                )
+            _weight, scale_node, zp_node, dtype = quant_node.args
+            scale_val = getattr_from_fqn(shadow_wrapper, scale_node.target)
+            zp_val = getattr_from_fqn(shadow_wrapper, zp_node.target)
+            new_args = (scale_val, zp_val, dtype)
+        return (quant_node.target, new_args)
+
+    return None
+
+
+def extract_weight_comparison(m: GraphModule) -> NSResultsType:
+    # example graph:
+    #
+    #   w1 = self.w1
+    #   b1 = self.b1
+    #   linear = torch._C._nn.linear(x, w1, b1)
+    #   shadow_0_0 = self.shadow_0_0(linear)
+    #   shadow_wrapper_0_1 = self.shadow_wrapper_0_1(x, w1, b1)
+    #   shadow_0_1 = self.shadow_0_1(shadow_wrapper_0_1, linear)
+    #
+    # algorithm:
+    # 1. for each call_function node matching our allowlist:
+    # 2.   if corresponding shadow wrapper exists, extract the weight pair
+    #
+    # Note: this is not super robust, but that's ok because this is
+    # just for legacy customers who depend on the previous two-model version
+    # of this API. TBD if we need to make this robust.
+    # Note: modules are not supported, since existing customers only
+    # use functions.
+
+    # TODO(future PR): move this to config
+    weighted_ops = {
+        torch.nn.functional.linear,
+    }
+
+    results: NSResultsType = {"model": {NSSingleResultValuesType.WEIGHT.value: {}}}
+
+    for n in m.graph.nodes:  # type: ignore[union-attr]
+        if not (n.op == "call_function" and n.target in weighted_ops):
+            continue
+
+        # Check if we have a corresponding shadow wrapper
+        # TODO(future PR, if needed): support kwargs
+        # TODO(future PR, if needed): support multiple shadow users
+        first_arg = n.args[0]
+        shadow_wrapper_node = None
+        for user in first_arg.users:
+            # TODO(before land): fix string match
+            if user.op == "call_module" and user.target.startswith("shadow_wrapper"):
+                shadow_wrapper_node = user
+                break
+
+        if shadow_wrapper_node is None:
+            continue
+
+        shadow_wrapper = getattr_from_fqn(m, shadow_wrapper_node.target)  # type: ignore[arg-type]
+        weight_info = _get_weight_info_from_shadow_wrapper(shadow_wrapper)
+        if weight_info is None:
+            continue
+
+        # get weight
+        w_node = n.args[1]
+        w_obj = getattr_from_fqn(m, w_node.target).detach()
+
+        # get a quantized version of weight
+        quant_fn, quant_fn_args_except_first = weight_info
+        new_args = (w_obj, *quant_fn_args_except_first)
+        w_obj_q = quant_fn(*new_args)
+
+        # add a comparison
+        ref_node_name = n.name
+        prev_node_name = n.name
+        ref_node_type = get_target_type_str(n, m)
+        prev_node_type = ref_node_type
+        fqn = None
+        if hasattr(m, "_node_name_to_scope"):
+            fqn = m._node_name_to_scope[n.name][0]  # type: ignore[index]
+        comparison = torch.ao.ns.fx.utils.compute_sqnr(w_obj, w_obj_q)
+        result_fp32 = {
+            "res_type": NSSingleResultValuesType.WEIGHT.value,
+            "values": [w_obj],
+            "prev_node_name": prev_node_name,
+            "prev_node_target_type": prev_node_type,
+            "ref_node_name": ref_node_name,
+            "ref_node_target_type": ref_node_type,
+            "index_within_arg": 0,
+            "index_of_arg": 0,
+            "fqn": fqn,
+            "qconfig_str": "",
+            "comparisons": [comparison],
+            "comparison_fn_name": "sqnr",
+        }
+        result_q = {
+            "res_type": NSSingleResultValuesType.WEIGHT.value,
+            "values": [w_obj_q],
+            "prev_node_name": prev_node_name,
+            "prev_node_target_type": prev_node_type,
+            "ref_node_name": ref_node_name,
+            "ref_node_target_type": ref_node_type,
+            "index_within_arg": 0,
+            "index_of_arg": 0,
+            "fqn": fqn,
+            "qconfig_str": "",
+            "comparisons": [comparison],
+            "comparison_fn_name": "sqnr",
+        }
+
+        # go from subgraph_n_1 to subgraph_n_0
+        _1, _2, node_idx, _3 = shadow_wrapper_node.target.split("_")
+        name_fp32 = f"subgraph_{node_idx}_0"
+        name_q = f"subgraph_{node_idx}_1"
+
+        results["model"][NSSingleResultValuesType.WEIGHT.value][name_fp32] = [
+            result_fp32
+        ]
+        results["model"][NSSingleResultValuesType.WEIGHT.value][name_q] = [result_q]
+
+    return results
+
+
+# TODO(future PR): redesign this to make it easier to consume outputs
+def group_results_by_subgraph(results: NSResultsType) -> Any:
+    """
+    Creates a comparison of results
+
+    Input:
+
+    {
+      'model': {
+        'node_output': {
+          'subgraph_0_0': [
+            'values': [torch.tensor(...), ...], ...
+            'ref_node_name': ...,
+            'ref_node_target_type': ...,
+            'qconfig_str': ...,
+            'comparisons': [], ...
+            'comparison_fn_name': '',
+            'fqn': '...',
+          ],
+          'subgraph_0_1': [
+            'values': [torch.tensor(...), ...], ...
+            'ref_node_name': ...,
+            'ref_node_target_type': ...,
+            'qconfig_str': ...,
+            'comparisons': [torch.tensor(...), ...], ...
+            'comparison_fn_name': '...',
+            'fqn': '...',
+          ],
+          ...
+        },
+      },
+    }
+
+    Output:
+    {
+      'subgraph_0': {
+        '0': {
+          'ref_node_name': '...',
+          'ref_node_target_type': ...,
+          'values': [torch.tensor(...), ...],
+          'qconfig_str': None,
+          'comparisons': [torch.tensor(...), ...], ...
+          'comparison_fn_name': '...',
+          'fqn': '...',
+        },
+        '1': {
+          'ref_node_name': '...',
+          'ref_node_target_type': ...,
+          'values': [torch.tensor(...), ...],
+          'qconfig_str': '...',
+          'comparisons': [torch.tensor(...), ...], ...
+          'comparison_fn_name': '...',
+          'fqn': '...',
+        },
+      },
+    }
+
+    """
+    subgraph_name_to_subgraph_results: Any = collections.defaultdict(dict)
+
+    # node_output or weight
+    key_to_use = next(iter(results["model"].keys()))
+
+    for subgraph_name_with_idx, subgraph_candidate_results in results["model"][
+        key_to_use
+    ].items():
+        # convert from `subgraph_m_n` to `subgraph_m` and `n`
+        (
+            subgraph_str,
+            subgraph_idx,
+            subgraph_candidate_idx,
+        ) = subgraph_name_with_idx.split("_")
+        subgraph_name = f"{subgraph_str}_{subgraph_idx}"
+
+        subgraph_results = {
+            "ref_node_name": subgraph_candidate_results[0]["ref_node_name"],
+            "ref_node_target_type": subgraph_candidate_results[0][
+                "ref_node_target_type"
+            ],
+            "fqn": subgraph_candidate_results[0]["fqn"],
+            "values": subgraph_candidate_results[0]["values"],
+            "qconfig_str": subgraph_candidate_results[0]["qconfig_str"],
+            "comparisons": subgraph_candidate_results[0]["comparisons"],
+            "comparison_fn_name": subgraph_candidate_results[0]["comparison_fn_name"],
+        }
+
+        subgraph_name_to_subgraph_results[subgraph_name][subgraph_candidate_idx] = (
+            subgraph_results
+        )
+
+    return dict(subgraph_name_to_subgraph_results)
+
+
+# TODO(future PR): redesign this to make it easier to consume outputs
+def create_results_comparison(
+    results_grouped,
+) -> Any:
+    """
+    Input:
+
+    {
+      'subgraph_0': {
+        '0': {
+          'ref_node_name': '...',
+          'ref_node_target_type': ...,
+          'values': [torch.tensor(...), ...],
+          'qconfig_str': '',
+          'comparisons': [],
+          'comparison_fn_name': '',
+          'fqn': '...',
+        },
+        '1': {
+          'ref_node_name': '...',
+          'ref_node_target_type': ...,
+          'values': [torch.tensor(...), ...],
+          'qconfig_str': '...',
+          'comparisons': [torch.tensor(...), ...],
+          'comparison_fn_name': 'sqnr',
+          'fqn': '...',
+        },
+      },
+    }
+
+    Output:
+    {
+      'subgraph_0': {
+        'ref_node_name': '...',
+        'ref_node_target_type': '...',
+        'fqn': '...',
+        'candidates': {
+          '1': {
+            'qconfig_str': ...,
+            'comparison_fn_name': 'sqnr',
+            'cmp_raw': [..., ...],
+            'cmp_mean': ...,
+          },
+          ...,
+        },
+      },
+    }
+    """
+
+    results_comparison = {}
+
+    for subgraph_name, subgraph_results in results_grouped.items():
+        candidates = {}
+        for subgraph_inner_name, subgraph_inner_result in subgraph_results.items():
+            # skip comparing baseline to baseline
+            if subgraph_inner_name == "0":
+                continue
+
+            # we expect the comparisons to be precalculated from
+            # calibration, so we just fetch them here
+            cmp_raw = subgraph_inner_result["comparisons"]
+            cmp_raw_tensor = torch.stack(cmp_raw)
+
+            candidates[subgraph_inner_name] = {
+                "qconfig_str": subgraph_inner_result["qconfig_str"],
+                "comparison_fn_name": subgraph_inner_result["comparison_fn_name"],
+                "cmp_raw": cmp_raw_tensor,
+                "cmp_mean": torch.mean(cmp_raw_tensor),
+            }
+
+        results_comparison[subgraph_name] = {
+            "ref_node_name": subgraph_results["0"]["ref_node_name"],
+            "ref_node_target_type": subgraph_results["0"]["ref_node_target_type"],
+            "fqn": subgraph_results["0"]["fqn"],
+            "candidates": candidates,
+        }
+
+    return results_comparison
+
+
+# TODO(future PR): redesign this to make it easier to consume outputs
+def print_n_shadows_summary(
+    results_comparison,
+) -> None:
+    """
+    Input:
+
+    {
+      'subgraph_0': {
+        'ref_node_name': 'linear1',
+        'ref_node_target_type': '...',
+        'fqn': '...',
+        'candidates': {
+          '1': {
+            'qconfig_str': ...,
+            'comparison_fn_name': ...,
+            'cmp_raw': [45.0, 55.0],
+            'cmp_mean': 50.0,
+          },
+          ...,
+        },
+      },
+    }
+
+    Prints:
+
+    node_name | node_type | fqn | 0    | 1    | ...
+    linear1   | ...       | ... | 45.0 | 50.0 | ...
+    """
+
+    try:
+        from tabulate import tabulate
+    except ImportError:
+        print(
+            "`print_tabular` relies on the library `tabulate`, "
+            "which could not be found on this machine. Run `pip "
+            "install tabulate` to install the library."
+        )
+        return
+
+    results = []
+    for subgraph_data in results_comparison.values():
+        mean_all_candidates = [
+            candidate["cmp_mean"] for candidate in subgraph_data["candidates"].values()
+        ]
+
+        data_row = [
+            subgraph_data["ref_node_name"],
+            subgraph_data["ref_node_target_type"],
+            subgraph_data["fqn"],
+            *mean_all_candidates,
+        ]
+        results.append(data_row)
+
+    max_candidate_idx_len = -1
+    for data_row in results:
+        max_candidate_idx_len = max(max_candidate_idx_len, len(data_row[1]))
+    candidate_idx_headers = [str(x) for x in range(max_candidate_idx_len)]
+
+    headers = ["node_name", "node_type", "fqn", *candidate_idx_headers]
+    print(tabulate(results, headers=headers))
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/ns_types.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/ns_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a25c0a9eefca9c0b70e93f0b3e4ef40b28af27e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/ns_types.py
@@ -0,0 +1,66 @@
+import enum
+from collections.abc import Callable
+from typing import Any, NamedTuple
+
+from torch.fx.graph import Node
+
+
+class NSSingleResultValuesType(str, enum.Enum):
+    WEIGHT = "weight"
+    NODE_OUTPUT = "node_output"
+    NODE_INPUT = "node_input"
+
+
+class NSSubgraph(NamedTuple):
+    start_node: Node
+    end_node: Node
+    base_op_node: Node
+
+
+# TODO(future PR): see if we can use typing_extensions's TypedDict instead
+# to properly type the various keys
+# {
+#   # one of NSSingleResultValuesType
+#   'type': 'weight',
+#   # the values of type specified above
+#   'values': [torch.tensor(...), ...],
+#   # name of the node directly before the logger
+#   'prev_node_name': 'linear1',
+#   # type of the underlying function or module
+#   'prev_node_target_type': torch.nn.functional.linear  # or torch.nn.Linear, etc
+#   # name of the node responsible for adding this logger
+#   # Note: this may differ from prev_node_name if we are logging inputs
+#   'ref_node_name': 'linear1',
+#   # index of this node within the arg of the input/output node
+#   # for example, in cat([x1, x2, x3], dim=0), x2 would have index_within_arg == 1
+#   'index_within_arg': 0,
+#   # index of this node within the args of the input/output node
+#   # for example, in add(x1, x2), x2 would have index_of_arg == 1
+#   'index_of_arg': 0,
+#   # precomputed comparisons of logger values to reference values
+#   'comparisons': [torch.tensor(...), ...]
+#   # name of function used for precomputed comparisons
+#   'comparison_fn_name': 'sqnr',
+#   # string representation of qconfig responsible for creating this logger
+#   'qconfig_str': 'QConfig(...)',
+# }
+NSSingleResultType = dict[str, Any]
+
+# {
+#   'layer_name_1': {  # subgraph name
+#     'node_output': {  # results type (node_output, node_input, weight)
+#       'model_name_a':  # model name
+#          [NSSingleResultType, ...],  # results, ordered by index_within_arg
+#       'model_name_b':
+#          [NSSingleResultType, ...],
+#     },
+#   },
+# }
+#
+NSResultsType = dict[str, dict[str, dict[str, list[NSSingleResultType]]]]
+
+# Defines the underlying target type of a node, for example:
+# `F.conv1d` for a `call_function` conv node
+# `nn.Conv1d` for a `call_module` node calling the forward of a `nn.Conv1d` module
+# `'sigmoid'` for a `call_method` node calling `x.sigmoid()`
+NSNodeTargetType = Callable | str
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/pattern_utils.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/pattern_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4db832e0dad824b3cfc03716f8ec777133a508f0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/pattern_utils.py
@@ -0,0 +1,215 @@
+from collections.abc import Callable
+from typing import Any
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.ao.quantization import FakeQuantizeBase, ObserverBase
+from torch.ao.quantization.backend_config import get_native_backend_config
+from torch.ao.quantization.fx.quantize_handler import _get_pattern_to_quantize_handlers
+from torch.ao.quantization.utils import getattr_from_fqn
+from torch.fx import GraphModule
+from torch.fx.graph import Node
+
+from .ns_types import NSNodeTargetType
+
+
+toq = torch.ops.quantized
+
+
+def get_type_a_related_to_b(
+    base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]],
+) -> set[tuple[NSNodeTargetType, NSNodeTargetType]]:
+    # TODO(future PR): allow customizations
+    # TODO(future PR): reuse existing quantization mappings
+    # TODO(future PR): add the rest of modules and ops here
+    type_a_related_to_b: set[tuple[NSNodeTargetType, NSNodeTargetType]] = set()
+
+    for s in base_name_to_sets_of_related_ops.values():
+        s_list = list(s)
+        # add every bidirectional pair
+        for idx_0 in range(len(s_list)):
+            for idx_1 in range(idx_0, len(s_list)):
+                type_a_related_to_b.add((s_list[idx_0], s_list[idx_1]))
+                type_a_related_to_b.add((s_list[idx_1], s_list[idx_0]))
+
+    return type_a_related_to_b
+
+
+NSFusionElType = (
+    Callable  # call_function or call_module type, example: F.linear or nn.Conv2d
+    | str  # call_method name, example: "dequantize"
+    | tuple[
+        str, Any
+    ]  # call_method name and first argument, example: ("to", torch.float16)
+)
+NSFusionType = (
+    tuple[NSFusionElType, NSFusionElType]
+    | tuple[NSFusionElType, NSFusionElType, NSFusionElType, NSFusionElType]
+)
+
+
+def get_reversed_fusions() -> list[tuple[NSFusionType, int]]:
+    """
+    Set of potential fusions, in reverse order.  The order is reversed
+    to match how fusion patterns are defined in quantization code.
+
+    Fusion format:
+    ((fusion_op_0, fusion_op_1), base_op_idx)
+
+    Where base_op_idx is the idx of the op we should use to match other related
+    ops. Note: base_op_idx is specified in non-reverse order, i.e. a base_op_idx
+    of 0 represents the first op in regular (non-reverse) order, 1 represents the
+    second op, etc.
+    """
+    results: list[tuple[NSFusionType, int]] = []
+
+    # Possible syntaxes:
+    # * single op: torch.nn.Conv2d
+    # * multiple ops: (torch.nn.ReLU, torch.nn.Conv2d)
+    # For fusions, we only care about patterns composed of multiple ops.
+    # TODO(future PR): allow customizations from default patterns.
+    all_quant_patterns = _get_pattern_to_quantize_handlers(get_native_backend_config())
+
+    default_base_op_idx = 0
+    for quant_pattern in all_quant_patterns:
+        # TODO: this is a temporary hack to flatten the patterns from quantization so
+        # that it works with the ns matcher function, maybe we should use `_is_match`
+        # in torch.ao.quantization.fx.match_utils to match the patterns
+        if (
+            isinstance(quant_pattern, tuple)
+            and len(quant_pattern) == 2
+            and isinstance(quant_pattern[1], tuple)
+            and len(quant_pattern[1]) == 2
+        ):
+            # flatten the pattern with form (nn.ReLU, (nn.BatchNorm2d, nn.Conv2d))
+            quant_pattern = (quant_pattern[0], quant_pattern[1][0], quant_pattern[1][1])
+
+        # Only patterns of multiple ops are fusions, ignore
+        # patterns which contain a single op (they get matched
+        # without caring about fusions).
+        if isinstance(quant_pattern, tuple):
+            results.append((quant_pattern, default_base_op_idx))  # type: ignore[arg-type]
+
+        # For each pattern, add additional patterns with observers and
+        # fake quants at the end.
+        # TODO(future PR): if needed, implement matching for a node
+        #   having multiple output observers.
+        for cls in (ObserverBase, FakeQuantizeBase):
+            if isinstance(quant_pattern, tuple):
+                # pyrefly: ignore [not-iterable]
+                new_pattern = (cls, *quant_pattern)
+            else:
+                new_pattern = (cls, quant_pattern)
+            results.append((new_pattern, default_base_op_idx))  # type: ignore[arg-type]
+
+    # After this point, results contains values such as
+    # [..., ((torch.nn.Relu, torch.nn.Conv2d), 0), ...]
+
+    # Patterns for matching fp16 emulation are not specified in the quantization
+    # fusion mappings.  For now, define them here.
+    fp16_em_base_op_idx = 1
+    patterns_to_add = [
+        # linear-relu fp16 emulation:
+        # fp16_to_fp32 -> linear -> relu -> fp32_to_fp16
+        (
+            (("to", torch.float16), F.relu, F.linear, "dequantize"),
+            fp16_em_base_op_idx,
+        ),
+        # Conv-BN fusion (this happens outside of quantization patterns,
+        # which is why it is defined separately here).
+        ((nn.BatchNorm1d, nn.Conv1d), default_base_op_idx),
+        ((nn.BatchNorm2d, nn.Conv2d), default_base_op_idx),
+        ((nn.BatchNorm3d, nn.Conv3d), default_base_op_idx),
+        ((nn.ReLU, nn.BatchNorm1d, nn.Conv1d), default_base_op_idx),
+        ((nn.ReLU, nn.BatchNorm2d, nn.Conv2d), default_base_op_idx),
+        ((nn.ReLU, nn.BatchNorm3d, nn.Conv3d), default_base_op_idx),
+    ]
+    for p in patterns_to_add:
+        results.append(p)  # type: ignore[arg-type]
+        results.append(((ObserverBase, *p[0]), p[1]))  # type: ignore[arg-type]
+        results.append(((FakeQuantizeBase, *p[0]), p[1]))  # type: ignore[arg-type]
+
+    return results
+
+
+def end_node_matches_reversed_fusion(
+    end_node: Node,
+    reversed_fusion: NSFusionType,
+    gm: GraphModule,
+    seen_nodes: set[Node],
+) -> bool:
+    """
+    Returns true if a pattern ending with `end_node` matches
+    the fusion pattern.
+    """
+    cur_node = end_node
+    for fusion_idx in range(len(reversed_fusion)):
+        # each node can only belong to one matched pattern
+        if cur_node in seen_nodes:
+            return False
+
+        cur_fusion_el = reversed_fusion[fusion_idx]
+
+        if cur_node.op == "call_function":
+            fusion_el_is_fun = (not isinstance(cur_fusion_el, str)) and (
+                not isinstance(cur_fusion_el, type)
+            )
+            if fusion_el_is_fun:
+                if cur_node.target != cur_fusion_el:
+                    return False
+                if len(cur_node.args) > 0 and isinstance(cur_node.args[0], Node):
+                    cur_node = cur_node.args[0]
+                else:
+                    return False
+            else:
+                return False
+
+        elif cur_node.op == "call_module":
+            fusion_el_is_mod = isinstance(cur_fusion_el, type)
+            if fusion_el_is_mod:
+                if not isinstance(cur_node.target, str):
+                    raise AssertionError(f"Expected str, got {type(cur_node.target)}")
+                target_mod = getattr_from_fqn(gm, cur_node.target)
+                if not isinstance(cur_fusion_el, type):
+                    return False
+                if not isinstance(target_mod, cur_fusion_el):
+                    return False
+                if len(cur_node.args) > 0 and isinstance(cur_node.args[0], Node):
+                    cur_node = cur_node.args[0]
+                else:
+                    return False
+            else:
+                return False
+
+        elif cur_node.op == "call_method":
+            fusion_el_is_meth_with_second_arg = (
+                isinstance(cur_fusion_el, tuple) and len(cur_fusion_el) == 2
+            )
+            fusion_el_is_meth_without_args = isinstance(cur_fusion_el, str)
+            if fusion_el_is_meth_without_args or fusion_el_is_meth_with_second_arg:
+                if fusion_el_is_meth_without_args:
+                    if cur_node.target != cur_fusion_el:
+                        return False
+                else:
+                    if not isinstance(cur_fusion_el, tuple):
+                        raise AssertionError(
+                            f"Expected tuple, got {type(cur_fusion_el)}"
+                        )
+                    if cur_node.target != cur_fusion_el[0]:
+                        return False
+                    elif len(cur_node.args) < 2:
+                        return False
+                    elif cur_node.args[1] != cur_fusion_el[1]:
+                        return False
+
+                if len(cur_node.args) > 0 and isinstance(cur_node.args[0], Node):
+                    cur_node = cur_node.args[0]
+                else:
+                    return False
+            else:
+                return False
+        else:
+            return False
+
+    return True
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/qconfig_multi_mapping.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/qconfig_multi_mapping.py
new file mode 100644
index 0000000000000000000000000000000000000000..d36914b46929d7eb8311097cd6b5d0fdc0c82f12
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/qconfig_multi_mapping.py
@@ -0,0 +1,251 @@
+# mypy: allow-untyped-defs
+from __future__ import annotations
+
+import copy
+from typing import Any, TYPE_CHECKING
+
+import torch
+from torch.ao.quantization import QConfigMapping
+from torch.ao.quantization.qconfig_mapping import _QCONFIG_STYLE_ORDER
+
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+
+    from torch.ao.quantization.qconfig import QConfigAny
+
+__all__ = ["QConfigMultiMapping"]
+
+_QCONFIG_STYLE_TO_METHOD: dict[str, str] = {
+    "global_qconfig": "set_global",
+    "object_type_qconfigs": "set_object_type",
+    "module_name_regex_qconfigs": "set_module_name_regex",
+    "module_name_qconfigs": "set_module_name",
+    "module_name_object_type_order_qconfigs": "set_module_name_object_type_order",
+}
+
+
+def _remove_duplicates_and_none(qconfig_list: list[QConfigAny]) -> None:
+    to_remove = []
+    for index, cur_qconfig in enumerate(qconfig_list):
+        if cur_qconfig is None:
+            to_remove.append(index)
+            break
+        for checked_qconfig in qconfig_list[:index]:
+            if torch.ao.quantization.qconfig_equals(cur_qconfig, checked_qconfig):
+                to_remove.append(index)
+                break
+    for index in to_remove[::-1]:
+        qconfig_list.pop(index)
+
+
+class QConfigMultiMapping:
+    """
+    This class, used with the prepare_n_shadows_model API, stores a list of :class:`torch.ao.quantization.QConfigMapping`s
+    so that multiple QConfigs can be specified for each QConfig matching style.
+
+    The user can specify QConfigs using the following methods (in increasing match priority):
+
+        ``set_global`` : sets the global (default) QConfigs
+
+        ``set_object_type`` : sets the QConfigs for a given module type, function, or method name
+
+        ``set_module_name_regex`` : sets the QConfigs for modules matching the given regex string
+
+        ``set_module_name`` : sets the QConfigs for modules matching the given module name
+
+        ``set_module_name_object_type_order`` : sets the QConfigs for modules matching a combination
+        of the given module name, object type, and the index at which the module appears
+
+    Note: Usage of set methods is the same as in QConfigMapping except with a passed in list of QConfigs rather than a
+    single QConfig.
+
+    Example usage::
+
+        qconfig_mapping = QConfigMultiMapping()
+            .set_global([qconfig1, qconfig2])
+            .set_object_type(torch.nn.Linear, [qconfig2, qconfig3])
+            .set_object_type(torch.nn.ReLU, [qconfig1])
+            .set_module_name_regex("foo.*bar.*conv[0-9]+", [qconfig2])
+            .set_module_name_regex("foo.*", [qconfig1, qconfig2, qconfig3])
+            .set_module_name("module1", [None])
+            .set_module_name("module2", [qconfig2])
+            .set_module_name_object_type_order("foo.bar", torch.nn.functional.linear, 0, [qconfig3])
+
+    """
+
+    def __init__(self) -> None:
+        # initialize this with 1 QConfigMapping to avoid corner cases
+        self.qconfig_mappings_list: list[QConfigMapping] = [QConfigMapping()]
+
+    def _handle_list_size_mismatch(
+        self, qconfig_list: list[QConfigAny], style: str
+    ) -> None:
+        # this method handles cases where the size of qconfig_list does not match
+        # the size of qconfig_mappings_list.
+        # Issue: Consider a user inserting global_qconfig A and B first, then inserting
+        # qconfig C as an object_type_qconfig for conv ops. If we internally store
+        # 1 QConfigMapping with A and C and another with just B, then the
+        # second QConfigMapping will match B to conv ops (which is not wanted), since B is global.
+
+        # we avoid this by maintaining the invariant that if any QConfigMapping
+        # has a qconfig style+key with a qconfig in it, all QConfigMappings must
+        # have either a qconfig or None for that same style+key. In the above
+        # example, a None qconfig would prevent the unwanted match in the
+        # second QConfigMapping
+
+        if len(qconfig_list) > len(self.qconfig_mappings_list):
+            # Case: we have more qconfigs (in qconfig_list) than QConfigMappings
+
+            # Add new QConfigMappings (initialized so we maintain the `invariant`)
+
+            new_qconfig_mapping = QConfigMapping()
+            # searches other QConfigMappings for qconfig style+keys
+            # that need to be inserted as `None` into the new QConfigMapping
+            for qconfig_mapping in self.qconfig_mappings_list:
+                # global_qconfig has None by default
+                for check_style in _QCONFIG_STYLE_ORDER[1:]:
+                    qconfigs_dict = getattr(qconfig_mapping, check_style)
+                    target_qconfigs_dict = getattr(new_qconfig_mapping, check_style)
+                    for key in qconfigs_dict:
+                        target_qconfigs_dict[key] = None
+                break
+
+            # insert copies of this new QConfigMapping until all entries
+            # in qconfig_list can fit among the QConfigMappings
+            while len(qconfig_list) > len(self.qconfig_mappings_list):
+                self.qconfig_mappings_list.append(copy.deepcopy(new_qconfig_mapping))
+        else:
+            # Case: we have fewer qconfigs in qconfig_list than QConfigMappings
+
+            # pad qconfig_list with `None` until length is same
+            while len(qconfig_list) < len(self.qconfig_mappings_list):
+                qconfig_list.append(None)
+
+    # this function applies the insertion method across each QConfigMapping
+    def _insert_qconfig_list(
+        self,
+        style: str,
+        args: list[str | int | Callable],
+        qconfig_list: list[QConfigAny],
+    ) -> None:
+        # we remove duplicates and None to make the ordering of qconfigs
+        # deterministic upon insertion.
+        _remove_duplicates_and_none(qconfig_list)
+
+        self._handle_list_size_mismatch(qconfig_list, style)
+        method_name = _QCONFIG_STYLE_TO_METHOD[style]
+        for qconfig_mapping, qconfig in zip(self.qconfig_mappings_list, qconfig_list):
+            # uses QConfigMapping set method to insert qconfig
+            set_method = getattr(qconfig_mapping, method_name)
+            set_method(*args, qconfig)
+
+    def set_global(self, global_qconfig_list: list[QConfigAny]) -> QConfigMultiMapping:
+        """
+        Set global QConfigs
+        see :func:`~torch.ao.quantization.QConfigMapping.set_global()` for more info
+        """
+        self._insert_qconfig_list("global_qconfig", [], global_qconfig_list)
+        return self
+
+    def set_object_type(
+        self, object_type: Callable | str, qconfig_list: list[QConfigAny]
+    ) -> QConfigMultiMapping:
+        """
+        Set object type QConfigs
+        see :func:`~torch.ao.quantization.QConfigMapping.set_object_type()` for more info
+        """
+        self._insert_qconfig_list("object_type_qconfigs", [object_type], qconfig_list)
+        return self
+
+    def set_module_name_regex(
+        self, module_name_regex: str, qconfig_list: list[QConfigAny]
+    ) -> QConfigMultiMapping:
+        """
+        Set module_name_regex QConfigs
+        see :func:`~torch.ao.quantization.QConfigMapping.set_module_name_regex()` for more info
+        """
+        self._insert_qconfig_list(
+            "module_name_regex_qconfigs", [module_name_regex], qconfig_list
+        )
+        return self
+
+    def set_module_name(
+        self, module_name: str, qconfig_list: list[QConfigAny]
+    ) -> QConfigMultiMapping:
+        """
+        Set module_name QConfigs
+        see :func:`~torch.ao.quantization.QConfigMapping.set_module_name()` for more info
+        """
+        self._insert_qconfig_list("module_name_qconfigs", [module_name], qconfig_list)
+        return self
+
+    def set_module_name_object_type_order(
+        self,
+        module_name: str,
+        object_type: Callable,
+        index: int,
+        qconfig_list: list[QConfigAny],
+    ) -> QConfigMultiMapping:
+        """
+        Set module_name QConfigs
+        see :func:`~torch.ao.quantization.QConfigMapping.set_module_name_object_type_order()` for more info
+        """
+        self._insert_qconfig_list(
+            "module_name_object_type_order_qconfigs",
+            [module_name, object_type, index],
+            qconfig_list,
+        )
+        return self
+
+    def __repr__(self):
+        return (
+            self.__class__.__name__
+            + " ["
+            + "".join(
+                f"\n{qconfig_mapping.__repr__()},"
+                for qconfig_mapping in self.qconfig_mappings_list
+            )
+            + "\n]"
+        )
+
+    @classmethod
+    def from_list_qconfig_mapping(
+        cls, qconfig_mapping_list: list[QConfigMapping]
+    ) -> QConfigMultiMapping:
+        """
+        Creates a QConfigMultiMapping from a list of QConfigMappings
+        """
+        new_qconfig_multi_mapping = cls()
+
+        new_qconfig_multi_mapping.qconfig_mappings_list = copy.deepcopy(
+            qconfig_mapping_list
+        )
+
+        # we need to avoid the issue described in _handle_list_size_mismatch,
+        # so we reinsert all the qconfigs using the QConfigMultiMapping
+        # set methods
+
+        # go through all qconfig styles
+        # note: global can be ignored since it is None by default
+        for style in _QCONFIG_STYLE_ORDER[1:]:
+            # gather all key+qconfigs for current style
+            # into qconfig_dict_list
+            qconfig_dict_list: dict[Any, list[QConfigAny]] = {}
+            for qconfig_mapping in qconfig_mapping_list:
+                qconfig_dict = getattr(qconfig_mapping, style)
+                for key, qconfig in qconfig_dict.items():
+                    if key not in qconfig_dict_list:
+                        qconfig_dict_list[key] = []
+                    qconfig_dict_list[key].append(qconfig)
+
+            # reinsert all gathered key+qconfigs
+            set_method_name = _QCONFIG_STYLE_TO_METHOD[style]
+            set_method = getattr(new_qconfig_multi_mapping, set_method_name)
+            for key, qconfig_list in qconfig_dict_list.items():
+                if isinstance(key, tuple):
+                    set_method(*key, qconfig_list)
+                else:
+                    set_method(key, qconfig_list)
+
+        return new_qconfig_multi_mapping
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/utils.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..72cb5fc6eb7cb45d5e5460bbb8edf6002c8f5f2e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/utils.py
@@ -0,0 +1,579 @@
+# mypy: allow-untyped-decorators
+# mypy: allow-untyped-defs
+import enum
+import operator
+from collections.abc import Callable
+
+import torch
+import torch.ao.nn.intrinsic.quantized as nniq
+import torch.ao.nn.quantized as nnq
+import torch.nn as nn
+from torch.ao.quantization import FakeQuantizeBase, ObserverBase
+from torch.ao.quantization.observer import _is_activation_post_process
+from torch.ao.quantization.utils import getattr_from_fqn
+from torch.fx import GraphModule
+from torch.fx.graph import Node
+
+from .ns_types import NSNodeTargetType, NSResultsType
+
+
+toq = torch.ops.quantized
+
+
+# TODO(future PR): consider deleting this enum and using the torch types
+# directly.  This might be tricky because it is not a one to one mapping.
+class NodeInputOrOutputType(enum.Enum):
+    FP32 = enum.auto()  # torch.float
+    INT8 = enum.auto()  # torch.qint8 or torch.quint8
+    FP16 = enum.auto()  # torch.float16
+    UNKNOWN = enum.auto()  # we cannot determine input/output dtype
+    # TODO(future PR): while these functions can support multiple dtypes,
+    #   for the purposes of numerical debugging we want to get the actual
+    #   dtype used in the model. We will likely need some kind of dtype
+    #   propagation to estimate this.
+    FP32_OR_INT8 = enum.auto()  # either torch.float or torch.quint8 or torch.qint8
+    # TODO(future PRs): dynamic quant, fake quant, etc
+
+
+def get_node_first_input_and_output_type(
+    node: Node,
+    gm: GraphModule,
+    logger_cls: Callable,
+    node_type_to_io_type_map: dict[str, set[NSNodeTargetType]],
+) -> tuple[NodeInputOrOutputType, NodeInputOrOutputType]:
+    # TODO(future PR): clean this up
+    FUNS_IO_TYPE_FP32 = node_type_to_io_type_map["funs_io_type_fp32"]
+    FUNS_IO_TYPE_FP16 = node_type_to_io_type_map["funs_io_type_fp16"]
+    FUNS_IO_TYPE_INT8 = node_type_to_io_type_map["funs_io_type_int8"]
+    FUNS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["funs_io_type_fp32_or_int8"]
+    MODS_IO_TYPE_FP32 = node_type_to_io_type_map["mods_io_type_fp32"]
+    MODS_IO_TYPE_INT8 = node_type_to_io_type_map["mods_io_type_int8"]
+    MODS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["mods_io_type_fp32_or_int8"]
+    METHS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["meths_io_type_fp32_or_int8"]
+
+    if node.op == "call_function":
+        if node.target in FUNS_IO_TYPE_FP32:
+            return (NodeInputOrOutputType.FP32, NodeInputOrOutputType.FP32)
+        if node.target in FUNS_IO_TYPE_FP16:
+            return (NodeInputOrOutputType.FP16, NodeInputOrOutputType.FP16)
+        elif node.target in FUNS_IO_TYPE_INT8:
+            return (NodeInputOrOutputType.INT8, NodeInputOrOutputType.INT8)
+        elif node.target in FUNS_IO_TYPE_FP32_OR_INT8:
+            first_arg = get_normalized_nth_input(node, gm, 0)
+            if not isinstance(first_arg, Node):
+                raise AssertionError(f"Expected Node, got {type(first_arg)}")
+            (
+                _prev_node_input_type,
+                prev_node_output_type,
+            ) = get_node_first_input_and_output_type(
+                first_arg, gm, logger_cls, node_type_to_io_type_map
+            )
+            return (prev_node_output_type, prev_node_output_type)
+        else:
+            return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
+
+    elif node.op == "call_module":
+        if node.op != "call_module":
+            raise AssertionError(f"Expected call_module, got '{node.op}'")
+        if not isinstance(node.target, str):
+            raise AssertionError(f"Expected str, but got {type(node.target)}")
+
+        mod = getattr_from_fqn(gm, node.target)
+        is_known_fp32_or_int8_input_module = any(
+            isinstance(mod, target_type)  # type: ignore[arg-type]
+            for target_type in MODS_IO_TYPE_FP32_OR_INT8
+        )
+        if (
+            isinstance(mod, (logger_cls, ObserverBase, FakeQuantizeBase))  # type: ignore[arg-type]
+            or is_known_fp32_or_int8_input_module
+        ):
+            # A logger or observer's input and output type is the output
+            # type of the preceding node.
+            first_arg = get_normalized_nth_input(node, gm, 0)
+            if not isinstance(first_arg, Node):
+                raise AssertionError(f"Expected Node, got {type(first_arg)}")
+            (
+                _prev_node_input_type,
+                prev_node_output_type,
+            ) = get_node_first_input_and_output_type(
+                first_arg, gm, logger_cls, node_type_to_io_type_map
+            )
+            return (prev_node_output_type, prev_node_output_type)
+        is_known_fp32_input_module = any(
+            isinstance(mod, target_type)  # type: ignore[arg-type]
+            for target_type in MODS_IO_TYPE_FP32
+        )
+        is_known_int8_input_module = any(
+            isinstance(mod, target_type)  # type: ignore[arg-type]
+            for target_type in MODS_IO_TYPE_INT8
+        )
+        if is_known_fp32_input_module:
+            return (NodeInputOrOutputType.FP32, NodeInputOrOutputType.FP32)
+        elif is_known_int8_input_module:
+            return (NodeInputOrOutputType.INT8, NodeInputOrOutputType.INT8)
+        else:
+            return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
+
+    elif node.op == "call_method":
+        if node.target == "dequantize":
+            # Dequantize is a special node because it allows multiple input types.
+            # So, we look up the output type of the previous node and return that
+            # as the input type of this node instance.
+            prev_node = get_normalized_nth_input(node, gm, 0)
+            if not isinstance(prev_node, Node):
+                raise AssertionError(f"Expected Node, got {type(prev_node)}")
+            (
+                _prev_node_input_type,
+                prev_node_output_type,
+            ) = get_node_first_input_and_output_type(
+                prev_node, gm, logger_cls, node_type_to_io_type_map
+            )
+            return (prev_node_output_type, NodeInputOrOutputType.FP32)
+
+        elif node.target == "to":
+            # to is a special node because it allows multiple input types.
+            # So, we look up the output type of the previous node and return that
+            # as the input type of this node instance. We also look up the target
+            # of to and return the correct output type.
+            prev_node = get_normalized_nth_input(node, gm, 0)
+            if not isinstance(prev_node, Node):
+                raise AssertionError(f"Expected Node, got {type(prev_node)}")
+            (
+                _prev_node_input_type,
+                prev_node_output_type,
+            ) = get_node_first_input_and_output_type(
+                prev_node, gm, logger_cls, node_type_to_io_type_map
+            )
+
+            cur_node_dtype_target = get_normalized_nth_input(node, gm, 1)
+            if cur_node_dtype_target is not torch.float16:
+                raise AssertionError(
+                    f"{cur_node_dtype_target} handling needs to be added"
+                )
+
+            return (prev_node_output_type, NodeInputOrOutputType.FP16)
+
+        elif node.target in METHS_IO_TYPE_FP32_OR_INT8:
+            first_arg = get_normalized_nth_input(node, gm, 0)
+            if not isinstance(first_arg, Node):
+                raise AssertionError(f"Expected Node, got {type(first_arg)}")
+            (
+                _prev_node_input_type,
+                prev_node_output_type,
+            ) = get_node_first_input_and_output_type(
+                first_arg, gm, logger_cls, node_type_to_io_type_map
+            )
+            return (prev_node_output_type, prev_node_output_type)
+
+        return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
+    else:
+        return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
+
+
+def get_node_input_qparams(
+    node: Node,
+    gm: GraphModule,
+    node_type_to_io_type_map: dict[str, set[NSNodeTargetType]],
+) -> tuple[torch.Tensor | float, torch.Tensor | int] | None:
+    """
+    Returns the qparams (scale, zero_point) of the first input to `node`,
+    if they can be inferred from the graph.
+    """
+    prev_node = get_normalized_nth_input(node, gm, 0)
+
+    if not isinstance(prev_node, Node):
+        return None
+
+    MODS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["mods_io_type_fp32_or_int8"]
+
+    def _get_scale_zp_from_function_args(node, gm, scale_arg_idx, zp_arg_idx):
+        scale_node = get_normalized_nth_input(node, gm, scale_arg_idx)
+        zp_node = get_normalized_nth_input(node, gm, zp_arg_idx)
+        if not isinstance(scale_node, Node):
+            raise AssertionError(f"Expected Node, got {type(scale_node)}")
+        if not isinstance(scale_node.target, str):
+            raise AssertionError(f"Expected str, got {type(scale_node.target)}")
+        if not isinstance(zp_node, Node):
+            raise AssertionError(f"Expected Node, got {type(zp_node)}")
+        if not isinstance(zp_node.target, str):
+            raise AssertionError(f"Expected str, got {type(zp_node.target)}")
+        scale_obj = getattr_from_fqn(gm, scale_node.target)
+        zp_obj = getattr_from_fqn(gm, zp_node.target)
+        return (scale_obj, zp_obj)
+
+    if prev_node.op == "call_function":
+        # quantize - read the args directly
+        if prev_node.target is torch.quantize_per_tensor:
+            return _get_scale_zp_from_function_args(prev_node, gm, 1, 2)
+        elif prev_node.target in (toq.add, toq.add_relu, toq.mul, toq.mul_relu):
+            return _get_scale_zp_from_function_args(prev_node, gm, 2, 3)
+
+        return None
+        # TODO(future PR): handle more functionals
+        # TODO(future PR): handle functional ops which inherit qparams from input
+
+    elif prev_node.op == "call_module":
+        # get type of the module
+        if not isinstance(prev_node.target, str):
+            raise AssertionError(f"Expected str, got {type(prev_node.target)}")
+        module_obj = getattr_from_fqn(gm, prev_node.target)
+        if isinstance(
+            module_obj,
+            (
+                nnq.Linear,
+                nnq.Conv1d,
+                nnq.Conv2d,
+                nniq.ConvReLU2d,
+                nnq.Conv3d,
+                nnq.BatchNorm2d,
+                nnq.BatchNorm3d,
+                nnq.ConvTranspose1d,
+                nnq.ConvTranspose2d,
+                nnq.ELU,
+                nnq.GroupNorm,
+                nnq.InstanceNorm1d,
+                nnq.InstanceNorm2d,
+                nnq.InstanceNorm3d,
+                nnq.LayerNorm,
+                nnq.Hardswish,
+                nnq.LeakyReLU,
+                nnq.ReLU6,
+                nniq.BNReLU2d,
+                nniq.BNReLU3d,
+                nniq.ConvReLU1d,
+                nniq.ConvReLU2d,
+                nniq.ConvReLU3d,
+                nniq.LinearReLU,
+            ),
+        ):
+            return (module_obj.scale, module_obj.zero_point)  # type: ignore[return-value]
+
+        is_known_fp32_or_int8_input_module = any(
+            isinstance(module_obj, target_type)  # type: ignore[arg-type]
+            for target_type in MODS_IO_TYPE_FP32_OR_INT8
+        )
+        if is_known_fp32_or_int8_input_module:
+            return get_node_input_qparams(prev_node, gm, node_type_to_io_type_map)
+
+    return None
+
+
+def return_first_non_observer_node(
+    node: Node,
+    gm: GraphModule,
+) -> Node:
+    """
+    If node is not an observer, returns it.  If node is an observer,
+    navigates up the graph and returns the first parent which is not an
+    observer.  For example,
+
+    graph: (node_non_obs), node = node_non_obs : returns node_non_obs
+    graph: (node_non_obs -> obs0), node = obs0 : returns node_non_obs
+    graph: (node_non_obs -> obs0 -> fq0), node = fq0 : returns node_non_obs
+    """
+    if node.op == "call_module":
+        node_obj = getattr_from_fqn(gm, node.target)  # type: ignore[arg-type]
+        if _is_activation_post_process(node_obj):
+            if len(node.args) != 1:
+                raise AssertionError(
+                    f"Expected node.args to have length 1, got {len(node.args)}"
+                )
+            if not isinstance(node.args[0], Node):
+                raise AssertionError(f"Expected Node, got {type(node.args[0])}")
+            node = node.args[0]
+            # code duplication intended, not worth refactoring
+            if not isinstance(node.target, str):
+                raise AssertionError(f"Expected str, got {type(node.target)}")
+            node_obj = getattr_from_fqn(gm, node.target)
+            if _is_activation_post_process(node_obj):
+                if len(node.args) != 1:
+                    raise AssertionError(
+                        f"Expected node.args to have length 1, got {len(node.args)}"
+                    )
+                if not isinstance(node.args[0], Node):
+                    raise AssertionError(f"Expected Node, got {type(node.args[0])}")
+                node = node.args[0]
+    return node
+
+
+def get_number_of_non_param_args(
+    node: Node,
+    gm: GraphModule,
+) -> int:
+    """
+    Assumes that all non-param args occur first. Returns the number of
+    non-param args expected for a node.  For example, for
+
+      F.linear(x, weight, bias)
+
+    Returns 1, because x is a non-param arg and weight and bias are params.
+    For
+
+      lstm_mod(x, hid)
+
+    Returns 2, because both x and hid are non-param args.
+    """
+    if node.op == "call_module":
+        node_obj = getattr_from_fqn(gm, node.target)  # type: ignore[arg-type]
+        if isinstance(node_obj, nn.LSTM):
+            return 2
+
+    # default is 1
+    return 1
+
+
+def get_arg_indices_of_inputs_to_log(node: Node) -> list[int]:
+    """
+    Returns the indices of args of the node which we should attach
+    loggers to, if input logging is enabled.
+
+    For example,
+    * for (x + y), returns [0, 1]
+    * for (1 + y), returns [1]
+    * for (x + 1), returns [0]
+    * for (linear(x, w, b)) returns [0]
+    * by default, returns [0]
+    """
+    if len(node.args) == 0:
+        return []
+    if node.op == "call_function" and (
+        # TODO(future PR): use relationship map instead of hardcoding
+        node.target in (torch.add, torch.ops.quantized.add, operator.add)
+        or node.target in (torch.mul, torch.ops.quantized.mul, operator.mul)
+    ):
+        result = [i for i in range(2) if type(node.args[i]) is Node]
+        return result
+    return [0]
+
+
+def get_target_type_str(node: Node, gm: GraphModule) -> str:
+    """
+    Returns a string representation of the type of the function or module
+    pointed to by this node, or '' for other node types.
+    """
+    target_type = ""
+    if node.op in ("call_function", "call_method"):
+        target_type = torch.typename(node.target)
+    elif node.op == "call_module":
+        if not isinstance(node.target, str):
+            raise AssertionError(f"Expected str, got {type(node.target)}")
+        target_mod = getattr_from_fqn(gm, node.target)
+        target_type = torch.typename(target_mod)
+    return target_type
+
+
+def rekey_logger_info_on_node_name_of_model(
+    results: NSResultsType,
+    model_name: str,
+) -> NSResultsType:
+    """
+    Rekeys the layer name of a results dictionary to use node names
+    from `model_name`.
+
+    For example, transforms
+
+        {'base_op_1_0': {'node_output': {'model_a':
+          [{'ref_node_name': 'linear1', ...}]}}}
+
+    into
+
+        {'linear1': {'node_output': {'model_a':
+          [{'ref_node_name': 'linear1', ...}]}}}
+
+    Note: we cannot use these node names directly because they are not
+    guaranteed to be consistent across models. This is why we extract
+    the results first and rekey afterwards.
+    """
+    new_results = {}
+    for old_layer_name, result_type_to_results in results.items():
+        new_layer_name = None
+        for model_name_to_results in result_type_to_results.values():
+            for cur_model_name, list_of_results in model_name_to_results.items():
+                if cur_model_name == model_name:
+                    if len(list_of_results) == 0:
+                        raise AssertionError("Expected list_of_results to be not empty")
+                    new_layer_name = list_of_results[0]["ref_node_name"]
+                else:
+                    continue
+        if new_layer_name is not None:
+            new_results[new_layer_name] = result_type_to_results
+        else:
+            new_results[old_layer_name] = result_type_to_results
+    return new_results
+
+
+def maybe_add_missing_fqns(results: NSResultsType) -> None:
+    """
+    If `fqn` entries are filled in for one of the models in `results`, copies
+    them over to any models which do not have them filled out.
+
+    A common use case benefitting from this is comparing a model prepared by
+    quantization to a quantized model. In this case, the model prepared by
+    quantization would have `fqn` entries, and the quantized model would not.
+    """
+
+    # Check in the first result to find any model with fqn entries defined.
+    model_name_with_fqns = None
+    for result_type_to_results in results.values():
+        for model_name_to_results in result_type_to_results.values():
+            for model_name, model_results in model_name_to_results.items():
+                if len(model_results) > 0:
+                    if model_results[0]["fqn"] is not None:
+                        model_name_with_fqns = model_name
+                        break
+            break
+        break
+
+    if model_name_with_fqns:
+        for result_type_to_results in results.values():
+            for model_name_to_results in result_type_to_results.values():
+                ref_model_results = model_name_to_results[model_name_with_fqns]
+                for model_name, model_results in model_name_to_results.items():
+                    if model_name == model_name_with_fqns:
+                        continue
+
+                    for i in range(len(model_results)):
+                        fqn = ref_model_results[i]["fqn"]
+                        model_results[i]["fqn"] = fqn
+
+
+def maybe_dequantize_first_two_tensor_args_and_handle_tuples(f):
+    def inner(*args, **kwargs):
+        a0, a1, *a_other = args
+
+        if (isinstance(a0, tuple) and isinstance(a1, tuple)) or (
+            isinstance(a0, list) and isinstance(a1, list)
+        ):
+            results = []
+            for el0, el1 in zip(a0, a1):
+                new_args = (el0, el1, *a_other)
+                results.append(inner(*new_args, **kwargs))
+            return results
+
+        elif isinstance(a0, torch.Tensor) and isinstance(a1, torch.Tensor):
+            if a0.is_quantized:
+                a0 = a0.dequantize()
+            if a1.is_quantized:
+                a1 = a1.dequantize()
+
+        # for the purposes of this util, only handle floats
+        if a0.dtype != torch.float or a1.dtype != torch.float:
+            return None
+
+        new_args = (a0, a1, *a_other)
+        return f(*new_args, **kwargs)
+
+    return inner
+
+
+@maybe_dequantize_first_two_tensor_args_and_handle_tuples
+def compute_sqnr(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
+    """
+    Computes the SQNR between `x` and `y`.
+
+    Args:
+        x: Tensor or tuple of tensors
+        y: Tensor or tuple of tensors
+
+    Return:
+        float or tuple of floats
+    """
+    Ps = torch.linalg.vector_norm(x)
+    Pn = torch.linalg.vector_norm(x - y)
+    return 20 * torch.log10(Ps / Pn)
+
+
+@maybe_dequantize_first_two_tensor_args_and_handle_tuples
+def compute_normalized_l2_error(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
+    """
+    Computes the normalized L2 error between `x` and `y`.
+
+    Args:
+        x: Tensor or tuple of tensors
+        y: Tensor or tuple of tensors
+
+    Return:
+        float or tuple of floats
+    """
+
+    return torch.sqrt(((x - y) ** 2).sum() / (x**2).sum())
+
+
+@maybe_dequantize_first_two_tensor_args_and_handle_tuples
+def compute_cosine_similarity(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
+    """
+    Computes the cosine similarity between `x` and `y`.
+
+    Args:
+        x: Tensor or tuple of tensors
+        y: Tensor or tuple of tensors
+
+    Return:
+        float or tuple of floats
+    """
+    # For convolutions, the shape of the quantized weight has one additional
+    # dimension compared to the shape of the fp32 weight. Match the shapes
+    # to enable cosine similarity comparison.
+    x = x.reshape(1, -1)
+    y = y.reshape(1, -1)
+    return torch.nn.functional.cosine_similarity(x, y)
+
+
+def op_type_supports_shadowing(node: Node) -> bool:
+    if node.op == "call_function":
+        if node.target in (
+            torch.add,
+            torch.mul,
+            operator.add,
+            operator.mul,
+            torch.cat,
+            torch.stack,
+        ):
+            # shadowing for ops with multiple tensor inputs is not implemented yet
+            return False
+    return True
+
+
+def get_normalized_nth_input(node: Node, gm: GraphModule, idx: int) -> Node:
+    """
+    Given a node, gets the n'th input to that node, normalizing
+    args and kwargs to the best of its ability.
+    """
+    try:
+        norm_args_and_kwargs = node.normalized_arguments(
+            gm, normalize_to_only_use_kwargs=True
+        )
+        if norm_args_and_kwargs is not None:
+            norm_args, norm_kwargs = norm_args_and_kwargs
+            if len(norm_args) + len(norm_kwargs) <= idx:
+                raise AssertionError(
+                    f"Index {idx} out of range: total = {len(norm_args) + len(norm_kwargs)}"
+                )
+            if idx < len(norm_args):
+                return norm_args[idx]
+            else:
+                # note: in Python 3.7+ dicts are ordered
+                return list(norm_kwargs.values())[idx]
+        else:
+            if len(node.args) + len(node.kwargs) <= idx:
+                raise AssertionError(
+                    f"Index {idx} out of range: total = {len(node.args) + len(node.kwargs)}"
+                )
+            if idx < len(node.args):
+                return node.args[idx]  # type: ignore[return-value]
+            else:
+                kwargs_idx = idx + len(node.args)
+                return list(node.kwargs.values())[kwargs_idx]  # type: ignore[return-value]
+    except RuntimeError:
+        # this RuntimeError happens when node argument normalization
+        # requires typehints to proceed, such as for torch.add where
+        # either the first, second or both arguments could be tensors
+        if len(node.args) + len(node.kwargs) <= idx:
+            raise AssertionError(
+                f"Index {idx} out of range: total = {len(node.args) + len(node.kwargs)}"
+            ) from None
+        if idx < len(node.args):
+            return node.args[idx]  # type: ignore[return-value]
+        else:
+            kwargs_idx = idx + len(node.args)
+            return list(node.kwargs.values())[kwargs_idx]  # type: ignore[return-value]
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/weight_utils.py b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/weight_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..6bff44215e46174856918883f35aac92b4491c25
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/weight_utils.py
@@ -0,0 +1,302 @@
+from collections.abc import Callable
+
+import torch
+import torch.ao.nn.intrinsic as nni
+import torch.ao.nn.intrinsic.qat as nniqat
+import torch.ao.nn.intrinsic.quantized as nniq
+import torch.ao.nn.qat as nnqat
+import torch.ao.nn.quantized as nnq
+import torch.ao.nn.quantized.dynamic as nnqd
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.fx import GraphModule
+from torch.fx.graph import Node
+
+from .ns_types import NSSingleResultType, NSSingleResultValuesType
+from .utils import get_target_type_str, getattr_from_fqn, return_first_non_observer_node
+
+
+toq = torch.ops.quantized
+
+
+def mod_weight_detach(mod: nn.Module) -> torch.Tensor:
+    return mod.weight.detach()  # type: ignore[operator]
+
+
+def mod_0_weight_detach(mod: nn.Module) -> torch.Tensor:
+    return mod[0].weight.detach()  # type: ignore[index]
+
+
+def mod_weight_bias_0(mod: nn.Module) -> torch.Tensor:
+    return mod._weight_bias()[0]  # type: ignore[operator]
+
+
+def get_lstm_weight(mod: nn.Module) -> list[torch.Tensor]:
+    res = []
+    for idx, param_name in enumerate(mod._flat_weights_names):  # type: ignore[arg-type]
+        if "weight_ih_l" in param_name or "weight_hh_l" in param_name:
+            param_value = mod._flat_weights[idx].detach()  # type: ignore[index,union-attr]
+            res.append(param_value)
+    return res
+
+
+def get_qlstm_weight(mod: nn.Module) -> list[torch.Tensor]:
+    res = []
+    for weight_value in mod._all_weight_values:  # type: ignore[union-attr]
+        res.append(weight_value.param.__getstate__()[0][4][0].__getstate__()[0][0])
+        res.append(weight_value.param.__getstate__()[0][4][1].__getstate__()[0][0])
+    return res
+
+
+def get_conv_mod_weight(mod: nn.Module) -> torch.Tensor:
+    if isinstance(mod, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
+        return mod.weight.detach()
+    elif isinstance(mod, (nni.ConvReLU1d, nni.ConvReLU2d, nni.ConvReLU3d)):
+        return mod[0].weight.detach()  # type: ignore[operator]
+    else:
+        return mod._weight_bias()[0]  # type: ignore[operator]
+
+
+def get_linear_mod_weight(mod: nn.Module) -> torch.Tensor:
+    if isinstance(mod, nn.Linear):
+        return mod.weight.detach()
+    elif isinstance(mod, nni.LinearReLU):
+        return mod[0].weight.detach()  # type: ignore[operator]
+    else:
+        return mod._weight_bias()[0]  # type: ignore[operator]
+
+
+def get_lstm_mod_weights(mod: nn.Module) -> list[torch.Tensor]:
+    # TODO(future PR): make more generic, handle everything
+    if isinstance(mod, nn.LSTM):
+        res = []
+        for idx, param_name in enumerate(mod._flat_weights_names):
+            if "weight_ih_l" in param_name or "weight_hh_l" in param_name:
+                param_value = mod._flat_weights[idx].detach()  # type: ignore[index,union-attr]
+                res.append(param_value)
+        return res
+    else:
+        if not isinstance(mod, nnqd.LSTM):
+            raise AssertionError(f"type {type(mod)} not handled yet")
+        res = []
+        for weight_value in mod._all_weight_values:
+            res.append(
+                weight_value.param.__getstate__()[0][4][0].__getstate__()[0][0]  # type: ignore[index]
+            )
+            res.append(
+                weight_value.param.__getstate__()[0][4][1].__getstate__()[0][0]  # type: ignore[index]
+            )
+        return res
+
+
+def get_conv_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
+    # traverse backwards from the weight arg, accounting for any observers
+    weight_arg_node = node.args[1]
+    if not isinstance(weight_arg_node, Node):
+        raise AssertionError(f"Expected Node, got {type(weight_arg_node)}")
+    weight_node = return_first_non_observer_node(weight_arg_node, gm)
+    if not isinstance(weight_node, Node):
+        raise AssertionError(f"Expected Node, got {type(weight_node)}")
+    if weight_node.op != "get_attr":
+        raise AssertionError(f"Expected get_attr, got {weight_node.op}")
+    weight = getattr_from_fqn(gm, weight_node.target)  # type: ignore[arg-type]
+    return weight.detach()
+
+
+def get_qconv_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
+    # qconv state is arg 1
+    qconv_state_node = node.args[1]
+    if not isinstance(qconv_state_node, Node):
+        raise AssertionError(f"Expected Node, got {type(qconv_state_node)}")
+    if qconv_state_node.op != "get_attr":
+        raise AssertionError(f"Expected get_attr, got {qconv_state_node.op}")
+    qconv_state_obj = getattr_from_fqn(gm, qconv_state_node.target)  # type: ignore[arg-type]
+    return qconv_state_obj.weight()
+
+
+def get_linear_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
+    # traverse backwards from the weight arg, accounting for any observers
+    # supported patterns:
+    # weight -> obs -> linear
+    # weight -> to(torch.float16) -> dequantize -> linear
+    linear_second_arg = node.args[1]
+    if not isinstance(linear_second_arg, Node):
+        raise AssertionError(f"Expected Node, got {type(linear_second_arg)}")
+
+    if linear_second_arg.op == "call_module":
+        # weight -> obs -> linear
+        weight_arg_node = node.args[1]
+        if not isinstance(weight_arg_node, Node):
+            raise AssertionError(f"Expected Node, got {type(weight_arg_node)}")
+        weight_node = weight_arg_node.args[0]
+        if not isinstance(weight_node, Node):
+            raise AssertionError(f"Expected Node, got {type(weight_node)}")
+        if weight_node.op != "get_attr":
+            raise AssertionError(f"Expected get_attr, got {weight_node.op}")
+        weight = getattr_from_fqn(gm, weight_node.target)  # type: ignore[arg-type]
+        return weight.detach()
+    elif linear_second_arg.op == "call_method":
+        # weight -> to(torch.float16) -> dequantize -> linear
+        if linear_second_arg.op != "call_method":
+            raise AssertionError(f"Expected call_method, got {linear_second_arg.op}")
+        dequant_node = node.args[1]
+        if not isinstance(dequant_node, Node):
+            raise AssertionError(f"Expected Node, got {type(dequant_node)}")
+        to_fp16_node = dequant_node.args[0]
+        if not isinstance(to_fp16_node, Node):
+            raise AssertionError(f"Expected Node, got {type(to_fp16_node)}")
+        # extract the dtype, so we can cast to it before returning
+        target_dtype = to_fp16_node.args[1]
+        weight_node = to_fp16_node.args[0]
+        if not isinstance(weight_node, Node):
+            raise AssertionError(f"Expected Node, got {type(weight_node)}")
+        if weight_node.op != "get_attr":
+            raise AssertionError(f"Expected get_attr, got {weight_node.op}")
+        weight = getattr_from_fqn(gm, weight_node.target)  # type: ignore[arg-type]
+        # return the weight with fp16 cast
+        return weight.detach().to(target_dtype)
+    else:
+        if linear_second_arg.op != "get_attr":
+            raise AssertionError(f"Expected get_attr, got {linear_second_arg.op}")
+        weight = getattr_from_fqn(gm, linear_second_arg.target)  # type: ignore[arg-type]
+        return weight.detach()
+
+
+def get_qlinear_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
+    # packed weight is arg 1
+    packed_weight_node = node.args[1]
+    if not isinstance(packed_weight_node, Node):
+        raise AssertionError(f"Expected Node, got {type(packed_weight_node)}")
+    if packed_weight_node.op != "get_attr":
+        raise AssertionError(f"Expected get_attr, got {packed_weight_node.op}")
+    packed_weight = getattr_from_fqn(gm, packed_weight_node.target)  # type: ignore[arg-type]
+    # TODO(future PR): why does packed_weight.unpack() not work?
+    (weight, _bias), _name = packed_weight.__getstate__()
+    return weight
+
+
+def get_op_to_type_to_weight_extraction_fn() -> dict[str, dict[Callable, Callable]]:
+    op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]] = {
+        "call_module": {
+            # Conv1d
+            nn.Conv1d: mod_weight_detach,
+            nni.ConvReLU1d: mod_0_weight_detach,
+            nnq.Conv1d: mod_weight_bias_0,
+            nnqat.Conv1d: mod_weight_detach,
+            nniqat.ConvBn1d: mod_weight_detach,
+            nniqat.ConvBnReLU1d: mod_weight_detach,
+            nniqat.ConvReLU1d: mod_weight_detach,
+            nniq.ConvReLU1d: mod_weight_bias_0,
+            # Conv2d
+            nn.Conv2d: mod_weight_detach,
+            nni.ConvReLU2d: mod_0_weight_detach,
+            nnq.Conv2d: mod_weight_bias_0,
+            nnqat.Conv2d: mod_weight_detach,
+            nniqat.ConvBn2d: mod_weight_detach,
+            nniqat.ConvBnReLU2d: mod_weight_detach,
+            nniqat.ConvReLU2d: mod_weight_detach,
+            nniq.ConvReLU2d: mod_weight_bias_0,
+            # Conv3d
+            nn.Conv3d: mod_weight_detach,
+            nni.ConvReLU3d: mod_0_weight_detach,
+            nnq.Conv3d: mod_weight_bias_0,
+            nnqat.Conv3d: mod_weight_detach,
+            nniqat.ConvBn3d: mod_weight_detach,
+            nniqat.ConvBnReLU3d: mod_weight_detach,
+            nniqat.ConvReLU3d: mod_weight_detach,
+            nniq.ConvReLU3d: mod_weight_bias_0,
+            # Linear
+            nn.Linear: mod_weight_detach,
+            nnq.Linear: mod_weight_bias_0,
+            nni.LinearReLU: mod_0_weight_detach,
+            nniq.LinearReLU: mod_weight_bias_0,
+            nnqat.Linear: mod_weight_detach,
+            nnqd.Linear: mod_weight_bias_0,
+            nniqat.LinearReLU: mod_weight_detach,
+            nniqat.LinearBn1d: mod_weight_detach,
+            nn.modules.linear.NonDynamicallyQuantizableLinear: mod_weight_detach,
+            # LSTM
+            nn.LSTM: get_lstm_weight,
+            nnqd.LSTM: get_qlstm_weight,
+        },
+        "call_function": {
+            # Conv
+            F.conv1d: get_conv_fun_weight,
+            F.conv2d: get_conv_fun_weight,
+            F.conv3d: get_conv_fun_weight,
+            toq.conv1d: get_qconv_fun_weight,
+            toq.conv2d: get_qconv_fun_weight,
+            toq.conv3d: get_qconv_fun_weight,
+            toq.conv1d_relu: get_qconv_fun_weight,
+            toq.conv2d_relu: get_qconv_fun_weight,
+            toq.conv3d_relu: get_qconv_fun_weight,
+            # Linear
+            F.linear: get_linear_fun_weight,
+            toq.linear: get_qlinear_fun_weight,
+            toq.linear_relu: get_qlinear_fun_weight,
+        },
+    }
+
+    return op_to_type_to_weight_extraction_fn
+
+
+def extract_weight_from_node(
+    node: Node,
+    gm: GraphModule,
+    op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]]
+    | None = None,
+) -> NSSingleResultType | None:
+    res_type = NSSingleResultValuesType.WEIGHT.value
+
+    # Not all graphmodules have _node_name_to_scope, so only fill it
+    # out if it exists.
+    fqn = None
+    if hasattr(gm, "_node_name_to_scope"):
+        fqn = gm._node_name_to_scope[node.name][0]  # type: ignore[index]
+
+    if op_to_type_to_weight_extraction_fn is None:
+        op_to_type_to_weight_extraction_fn = get_op_to_type_to_weight_extraction_fn()
+
+    ref_node_type = get_target_type_str(node, gm)
+    # for extracting weights, these are always the same
+    prev_node_type = ref_node_type
+
+    if node.op == "call_function":
+        function_mapping = op_to_type_to_weight_extraction_fn["call_function"]
+        for target_fn_type, weight_extraction_fn in function_mapping.items():
+            if node.target == target_fn_type:
+                weight = weight_extraction_fn(node, gm)
+                return {
+                    "type": res_type,
+                    "values": [weight],
+                    "prev_node_name": node.name,
+                    "prev_node_target_type": prev_node_type,
+                    "ref_node_name": node.name,
+                    "ref_node_target_type": ref_node_type,
+                    "index_within_arg": 0,
+                    "index_of_arg": 0,
+                    "fqn": fqn,
+                }
+
+    elif node.op == "call_module":
+        # for call_module, we need to look up the modules to do the type check
+        if not isinstance(node.target, str):
+            raise AssertionError(f"Expected str, got {type(node.target)}")
+        mod = getattr_from_fqn(gm, node.target)
+        module_mapping = op_to_type_to_weight_extraction_fn["call_module"]
+        for target_mod_type, weight_extraction_fn in module_mapping.items():
+            if type(mod) is target_mod_type:
+                weight = weight_extraction_fn(mod)
+                return {
+                    "type": res_type,
+                    "values": [weight],
+                    "prev_node_name": node.name,
+                    "prev_node_target_type": prev_node_type,
+                    "ref_node_name": node.name,
+                    "ref_node_target_type": ref_node_type,
+                    "index_within_arg": 0,
+                    "index_of_arg": 0,
+                    "fqn": fqn,
+                }
+
+    return None
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/pruning/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/pruning/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..52fc301befd34642d51f1c27e07600a1f3ef26ff
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/torch/ao/pruning/__init__.py
@@ -0,0 +1,23 @@
+# Variables
+from ._mappings import (
+    get_dynamic_sparse_quantized_mapping,
+    get_static_sparse_quantized_mapping,
+)
+
+# Scheduler
+from .scheduler.base_scheduler import BaseScheduler
+from .scheduler.cubic_scheduler import CubicSL
+from .scheduler.lambda_scheduler import LambdaSL
+
+# Sparsifier
+from .sparsifier.base_sparsifier import BaseSparsifier
+from .sparsifier.nearly_diagonal_sparsifier import NearlyDiagonalSparsifier
+
+# Parametrizations
+from .sparsifier.utils import (
+    FakeSparsity,
+    fqn_to_module,
+    get_arg_info_from_tensor_fqn,
+    module_to_fqn,
+)
+from .sparsifier.weight_norm_sparsifier import WeightNormSparsifier
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/pruning/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/pruning/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c283a0b90a2942cad27b05aa08ec2fd27ee700c
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/pruning/__pycache__/__init__.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/pruning/__pycache__/_mappings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/pruning/__pycache__/_mappings.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c89ab6a058546eace372fca3faa1d8637f304e0e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/pruning/__pycache__/_mappings.cpython-312.pyc differ
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/__init__.py b/.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c341d2e4cf4323ad607915862f590324d8e0393
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/__pycache__/__init__.cpython-312.pyc differ